Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4f756cf001 | ||
|
|
163e9d1c02 |
No files matched your search
+59
-69
@@ -1,9 +1,18 @@
|
|||||||
|
import asyncio
|
||||||
from http import HTTPMethod
|
from http import HTTPMethod
|
||||||
from urllib.parse import urlparse
|
from urllib.parse import urlparse
|
||||||
from common.utils import http_request
|
from common.utils import http_request
|
||||||
|
|
||||||
APIFY_BASE = "https://api.apify.com/v2"
|
APIFY_BASE = "https://api.apify.com/v2"
|
||||||
|
|
||||||
|
# Instagram: profile + highlights 두 actor 직접 호출.
|
||||||
|
IG_PROFILE_ACTOR = "coderx~instagram-profile-scraper-bio-posts"
|
||||||
|
IG_HIGHLIGHTS_ACTOR = "igview-owner~instagram-highlights-scraper"
|
||||||
|
|
||||||
|
|
||||||
|
def _ig_username(url: str) -> str:
|
||||||
|
return urlparse(url).path.strip("/").split("/")[0] if "://" in url else url.lstrip("@")
|
||||||
|
|
||||||
|
|
||||||
class ApifyClient:
|
class ApifyClient:
|
||||||
def __init__(self, token: str, wait_for_finish: int = 120):
|
def __init__(self, token: str, wait_for_finish: int = 120):
|
||||||
@@ -33,27 +42,39 @@ class ApifyClient:
|
|||||||
return []
|
return []
|
||||||
return items_resp.json()
|
return items_resp.json()
|
||||||
|
|
||||||
async def fetch_instagram_profile(self, url: str) -> dict | None:
|
async def fetch_instagram_profile(self, username: str) -> dict | None:
|
||||||
username = urlparse(url).path.strip("/").split("/")[0] if "://" in url else url.lstrip("@")
|
items = await self._run_actor(IG_PROFILE_ACTOR, {"usernames": [username]})
|
||||||
items = await self._run_actor("apify~instagram-profile-scraper", {"usernames": [username], "resultsLimit": 12})
|
|
||||||
return items[0] if items else None
|
return items[0] if items else None
|
||||||
|
|
||||||
|
async def fetch_instagram_highlights(self, username: str) -> list[dict]:
|
||||||
|
return await self._run_actor(IG_HIGHLIGHTS_ACTOR, {"usernames": [username]})
|
||||||
|
|
||||||
async def get_instagram_profile(self, url: str) -> dict | None:
|
async def get_instagram_profile(self, url: str) -> dict | None:
|
||||||
profile = await self.fetch_instagram_profile(url)
|
username = _ig_username(url)
|
||||||
if not profile or profile.get("error"):
|
# profile·highlights 두 actor를 병렬 호출 (highlights 실패해도 profile만 있으면 진행)
|
||||||
|
profile, highlights = await asyncio.gather(
|
||||||
|
self.fetch_instagram_profile(username),
|
||||||
|
self.fetch_instagram_highlights(username),
|
||||||
|
return_exceptions=True,
|
||||||
|
)
|
||||||
|
if isinstance(profile, Exception) or not profile or profile.get("error"):
|
||||||
return None
|
return None
|
||||||
|
if isinstance(highlights, Exception):
|
||||||
|
highlights = []
|
||||||
return {
|
return {
|
||||||
"username": profile["username"],
|
"username": profile["username"],
|
||||||
"profileImage": profile.get("profilePicUrlHD") or profile.get("profilePicUrl"),
|
"profileImage": profile.get("hdProfilePicUrl") or profile.get("profilePicUrl"),
|
||||||
"followers": profile.get("followersCount", 0),
|
"followers": profile.get("followersCount", 0),
|
||||||
"following": profile.get("followsCount", 0),
|
"following": profile.get("followsCount", 0),
|
||||||
"posts": profile.get("postsCount", 0),
|
"posts": profile.get("postsCount", 0),
|
||||||
"bio": profile.get("biography", ""),
|
"bio": profile.get("biography", ""),
|
||||||
|
"category": profile.get("businessCategoryName") or "",
|
||||||
"isBusinessAccount": profile.get("isBusinessAccount", False),
|
"isBusinessAccount": profile.get("isBusinessAccount", False),
|
||||||
#"externalUrl": profile.get("externalUrl"), LLM에 혼동을 주는 듯 하여 비활성화
|
#"externalUrl": profile.get("externalUrl"), LLM에 혼동을 주는 듯 하여 비활성화
|
||||||
|
"highlights": [h["highlightTitle"] for h in (highlights or []) if isinstance(h, dict) and h.get("highlightTitle")],
|
||||||
"latestPosts": [
|
"latestPosts": [
|
||||||
{
|
{
|
||||||
"type": p.get("type"),
|
"type": p.get("mediaType") or p.get("type"),
|
||||||
"likes": p.get("likesCount", 0),
|
"likes": p.get("likesCount", 0),
|
||||||
"comments": p.get("commentsCount", 0),
|
"comments": p.get("commentsCount", 0),
|
||||||
"caption": (p.get("caption") or "")[:500],
|
"caption": (p.get("caption") or "")[:500],
|
||||||
@@ -63,67 +84,36 @@ class ApifyClient:
|
|||||||
],
|
],
|
||||||
}
|
}
|
||||||
|
|
||||||
async def fetch_instagram_posts(self, url: str, limit: int = 20) -> list[dict]:
|
# 인스타 post 스크래퍼는 현재 파이프라인 미사용 — 비활성화 (필요 시 복구)
|
||||||
username = urlparse(url).path.strip("/").split("/")[0] if "://" in url else url.lstrip("@")
|
# async def fetch_instagram_posts(self, url: str, limit: int = 20) -> list[dict]:
|
||||||
return await self._run_actor("apify~instagram-post-scraper", {
|
# username = urlparse(url).path.strip("/").split("/")[0] if "://" in url else url.lstrip("@")
|
||||||
"directUrls": [f"https://www.instagram.com/{username}/"],
|
# return await self._run_actor("apify~instagram-post-scraper", {
|
||||||
"resultsLimit": limit,
|
# "directUrls": [f"https://www.instagram.com/{username}/"],
|
||||||
})
|
# "resultsLimit": limit,
|
||||||
|
# })
|
||||||
async def get_instagram_posts(self, url: str, limit: int = 20) -> dict:
|
#
|
||||||
items = await self.fetch_instagram_posts(url, limit)
|
# async def get_instagram_posts(self, url: str, limit: int = 20) -> dict:
|
||||||
posts = [
|
# items = await self.fetch_instagram_posts(url, limit)
|
||||||
{
|
# posts = [
|
||||||
"id": p["id"],
|
# {
|
||||||
"type": p.get("type"),
|
# "id": p["id"],
|
||||||
"url": p.get("url"),
|
# "type": p.get("type"),
|
||||||
"caption": (p.get("caption") or "")[:500],
|
# "url": p.get("url"),
|
||||||
"hashtags": p.get("hashtags", []),
|
# "caption": (p.get("caption") or "")[:500],
|
||||||
"likesCount": p.get("likesCount", 0),
|
# "hashtags": p.get("hashtags", []),
|
||||||
"commentsCount": p.get("commentsCount", 0),
|
# "likesCount": p.get("likesCount", 0),
|
||||||
"timestamp": p.get("timestamp"),
|
# "commentsCount": p.get("commentsCount", 0),
|
||||||
}
|
# "timestamp": p.get("timestamp"),
|
||||||
for p in items
|
# }
|
||||||
]
|
# for p in items
|
||||||
n = len(posts) or 1
|
# ]
|
||||||
return {
|
# n = len(posts) or 1
|
||||||
"posts": posts,
|
# return {
|
||||||
"totalPosts": len(posts),
|
# "posts": posts,
|
||||||
"avgLikes": round(sum(p["likesCount"] for p in posts) / n),
|
# "totalPosts": len(posts),
|
||||||
"avgComments": round(sum(p["commentsCount"] for p in posts) / n),
|
# "avgLikes": round(sum(p["likesCount"] for p in posts) / n),
|
||||||
}
|
# "avgComments": round(sum(p["commentsCount"] for p in posts) / n),
|
||||||
|
# }
|
||||||
async def fetch_instagram_reels(self, url: str, limit: int = 15) -> list[dict]:
|
|
||||||
username = urlparse(url).path.strip("/").split("/")[0] if "://" in url else url.lstrip("@")
|
|
||||||
return await self._run_actor("apify~instagram-reel-scraper", {
|
|
||||||
"directUrls": [f"https://www.instagram.com/{username}/reels/"],
|
|
||||||
"resultsLimit": limit,
|
|
||||||
})
|
|
||||||
|
|
||||||
async def get_instagram_reels(self, url: str, limit: int = 15) -> dict:
|
|
||||||
items = await self.fetch_instagram_reels(url, limit)
|
|
||||||
reels = [
|
|
||||||
{
|
|
||||||
"id": r["id"],
|
|
||||||
"url": r.get("url"),
|
|
||||||
"caption": (r.get("caption") or "")[:500],
|
|
||||||
"hashtags": r.get("hashtags", []),
|
|
||||||
"likesCount": r.get("likesCount", 0),
|
|
||||||
"commentsCount": r.get("commentsCount", 0),
|
|
||||||
"videoViewCount": r.get("videoViewCount", 0),
|
|
||||||
"videoPlayCount": r.get("videoPlayCount", 0),
|
|
||||||
"videoDuration": r.get("videoDuration", 0),
|
|
||||||
"timestamp": r.get("timestamp"),
|
|
||||||
}
|
|
||||||
for r in items
|
|
||||||
]
|
|
||||||
n = len(reels) or 1
|
|
||||||
return {
|
|
||||||
"reels": reels,
|
|
||||||
"totalReels": len(reels),
|
|
||||||
"avgViews": round(sum(r["videoViewCount"] for r in reels) / n),
|
|
||||||
"avgPlays": round(sum(r["videoPlayCount"] for r in reels) / n),
|
|
||||||
}
|
|
||||||
|
|
||||||
async def fetch_facebook_page(self, page_url: str) -> dict | None:
|
async def fetch_facebook_page(self, page_url: str) -> dict | None:
|
||||||
items = await self._run_actor("apify~facebook-pages-scraper", {"startUrls": [{"url": page_url}]})
|
items = await self._run_actor("apify~facebook-pages-scraper", {"startUrls": [{"url": page_url}]})
|
||||||
|
|||||||
@@ -67,10 +67,16 @@
|
|||||||
{channel_logos}
|
{channel_logos}
|
||||||
- channel_logos.channel_logos[]에 각 채널의 로고 설명(logo_description)과 공식 로고 일치 여부(is_official)가 있습니다.
|
- channel_logos.channel_logos[]에 각 채널의 로고 설명(logo_description)과 공식 로고 일치 여부(is_official)가 있습니다.
|
||||||
- **facebook_audit.pages[].logo** 는 짧은 판정 타이틀로: is_official=true면 `"일치 (공식 로고)"`, false면 `"불일치 (비공식 변형)"`. 그리고 **facebook_audit.pages[].logo_description** 에 해당 채널의 logo_description(설명문)을 넣으세요.
|
- **facebook_audit.pages[].logo** 는 짧은 판정 타이틀로: is_official=true면 `"일치 (공식 로고)"`, false면 `"불일치 (비공식 변형)"`. 그리고 **facebook_audit.pages[].logo_description** 에 해당 채널의 logo_description(설명문)을 넣으세요.
|
||||||
- **instagram_audit.accounts[].profile_photo** 는 해당 채널 로고를 짧게 서술 (예: `"모델 사진 (브랜드 로고 아님)"`, `"VIEW 골드 로고"`). 긴 문장 말고 짧게.
|
|
||||||
- 위 값들은 channel_logos 데이터 기반으로만 작성하고 추측하지 마세요.
|
- 위 값들은 channel_logos 데이터 기반으로만 작성하고 추측하지 마세요.
|
||||||
- 채널 간 로고 불일치(is_official=false)는 brand 일관성 진단(problem_diagnosis/weaknesses)에 반영하세요.
|
- 채널 간 로고 불일치(is_official=false)는 brand 일관성 진단(problem_diagnosis/weaknesses)에 반영하세요.
|
||||||
|
|
||||||
|
## clinic_snapshot / 채널 audit 작성 지침 (수집 데이터 그대로, 추측 금지)
|
||||||
|
- clinic_snapshot.name 은 {clinic_name} 을 **그대로** 사용 (강남언니 표기명 '-본원' 등으로 바꾸지 말 것).
|
||||||
|
- clinic_snapshot 의 overall_rating/total_reviews/staff_count/location/certifications/lead_doctor 는 강남언니({gangnam_unni}) 데이터의 값을 그대로 사용.
|
||||||
|
- **instagram_audit.accounts 는 반드시 빈 배열 []로 두세요.** 계정 정보는 시스템이 수집 데이터로 직접 채우니 LLM은 만들지 말고, instagram_audit.diagnosis(진단)만 작성하세요.
|
||||||
|
- facebook_audit.pages: KR 페북({facebook})·영문 페북({facebook_en}) 데이터가 있으면 **각각 별도 페이지**로 넣고, url/page_name/followers 등은 그 데이터 그대로. language/label 동일 규칙.
|
||||||
|
- 위 수치·URL·이름은 제공된 데이터에서 그대로 쓰고 절대 지어내지 마세요.
|
||||||
|
|
||||||
## 기타 채널 현황 (other_channels) 작성 지침
|
## 기타 채널 현황 (other_channels) 작성 지침
|
||||||
- other_channels에는 메인 audit(YouTube/Instagram/Facebook/Website)에 **포함되지 않은** 채널만 넣으세요.
|
- other_channels에는 메인 audit(YouTube/Instagram/Facebook/Website)에 **포함되지 않은** 채널만 넣으세요.
|
||||||
- 위 '채널 데이터'에 **실제 수집된 데이터가 있는 채널만** status=active와 실제 url로 일관되게 포함: 네이버 블로그, 강남언니, 틱톡, 영문 인스타그램({instagram_en}), 영문 페이스북({facebook_en}).
|
- 위 '채널 데이터'에 **실제 수집된 데이터가 있는 채널만** status=active와 실제 url로 일관되게 포함: 네이버 블로그, 강남언니, 틱톡, 영문 인스타그램({instagram_en}), 영문 페이스북({facebook_en}).
|
||||||
|
|||||||
@@ -119,7 +119,8 @@ class VisionClient:
|
|||||||
' "logo_text": "로고에 보이는 워드마크 텍스트 그대로 (한글/영문). 없으면 빈 문자열",\n'
|
' "logo_text": "로고에 보이는 워드마크 텍스트 그대로 (한글/영문). 없으면 빈 문자열",\n'
|
||||||
' "logo_colors_desc": "로고에 쓰인 색감을 사람이 부르는 이름으로 서술 (예: \'딥네이비 + 골드\'). 정확한 hex는 출력하지 말 것"\n'
|
' "logo_colors_desc": "로고에 쓰인 색감을 사람이 부르는 이름으로 서술 (예: \'딥네이비 + 골드\'). 정확한 hex는 출력하지 말 것"\n'
|
||||||
"}\n"
|
"}\n"
|
||||||
"주의: 색상 hex 값이나 logo URL 같은 필드는 출력하지 마세요 (별도 추출 로직이 처리)."
|
"주의: 색상 hex 값이나 logo URL 같은 필드는 출력하지 마세요 (별도 추출 로직이 처리).\n"
|
||||||
|
"모든 설명/텍스트 값은 반드시 한국어로 작성하세요 (영어 금지)."
|
||||||
)
|
)
|
||||||
result = await self._ask(urls, prompt)
|
result = await self._ask(urls, prompt)
|
||||||
if not result:
|
if not result:
|
||||||
@@ -166,6 +167,7 @@ class VisionClient:
|
|||||||
' "channel_logos": [{"channel": "...", "logo_description": "...", "is_official": true}],\n'
|
' "channel_logos": [{"channel": "...", "logo_description": "...", "is_official": true}],\n'
|
||||||
' "inconsistency_summary": "채널 간 로고 일관성 1~2문장 요약",\n'
|
' "inconsistency_summary": "채널 간 로고 일관성 1~2문장 요약",\n'
|
||||||
' "recommendation": "통합 권고 1문장"\n'
|
' "recommendation": "통합 권고 1문장"\n'
|
||||||
"}"
|
"}\n"
|
||||||
|
"모든 logo_description·inconsistency_summary·recommendation은 반드시 한국어로 작성하세요 (영어 금지)."
|
||||||
)
|
)
|
||||||
return await self._ask(urls, prompt)
|
return await self._ask(urls, prompt)
|
||||||
+59
-119
@@ -4,6 +4,7 @@ from common.db import fetchone, execute, fetch_raw, get_analysis_raw_data, save_
|
|||||||
from integrations.llm.llm_service import LLMService
|
from integrations.llm.llm_service import LLMService
|
||||||
from integrations.llm.prompt import report_prompt, plan_prompt
|
from integrations.llm.prompt import report_prompt, plan_prompt
|
||||||
from integrations.llm.schemas.report import ReportOutput
|
from integrations.llm.schemas.report import ReportOutput
|
||||||
|
from services.instagram_audit import build_instagram_accounts
|
||||||
from integrations.llm.schemas.plan import PlanOutput
|
from integrations.llm.schemas.plan import PlanOutput
|
||||||
from models.status import AnalysisStatus
|
from models.status import AnalysisStatus
|
||||||
|
|
||||||
@@ -94,100 +95,6 @@ async def generate_plan(analysis_run_id: str) -> PlanOutput:
|
|||||||
return await LLMService(provider="perplexity").generate(plan_prompt, input_data)
|
return await LLMService(provider="perplexity").generate(plan_prompt, input_data)
|
||||||
|
|
||||||
|
|
||||||
def _en_instagram_account(d: dict) -> dict:
|
|
||||||
"""영문 인스타 raw_data → InstagramAccount dict (factual 값 + 빈 정성필드). audit 보강용."""
|
|
||||||
return {
|
|
||||||
"handle": d["username"], "language": "EN", "label": "인스타그램 EN",
|
|
||||||
"posts": d.get("posts") or 0, "followers": d.get("followers") or 0,
|
|
||||||
"following": d.get("following") or 0, "category": "",
|
|
||||||
"profile_link": f"https://www.instagram.com/{d['username']}/",
|
|
||||||
"highlights": [], "reels_count": 0, "content_format": "", "profile_photo": "",
|
|
||||||
"bio": d.get("bio") or "",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _en_facebook_page(d: dict) -> dict:
|
|
||||||
"""영문 페북 raw_data → FacebookPage dict (factual 값 + 빈 정성필드). audit 보강용."""
|
|
||||||
url = d.get("pageUrl") or ""
|
|
||||||
return {
|
|
||||||
"url": url, "page_name": d.get("pageName") or "", "language": "EN", "label": "페이스북 EN",
|
|
||||||
"followers": d.get("followers") or 0, "following": 0,
|
|
||||||
"category": ", ".join(d.get("categories") or []), "bio": d.get("intro") or "",
|
|
||||||
"logo": "", "logo_description": "", "link": url, "linked_domain": d.get("website") or "",
|
|
||||||
"reviews": 0, "recent_post_age": "", "has_whatsapp": False,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _clinic_snapshot(brand_assets: dict, g: dict) -> dict:
|
|
||||||
"""brandAssets(색·로고) + 강남언니(평점/리뷰/대표의) → clinic_snapshot 정확값."""
|
|
||||||
snap: dict = {}
|
|
||||||
if brand_assets.get("brand_colors"): snap["brand_colors"] = brand_assets["brand_colors"]
|
|
||||||
if brand_assets.get("logo_images"): snap["logo_images"] = brand_assets["logo_images"]
|
|
||||||
if g.get("name"): snap["name"] = g["name"]
|
|
||||||
if g.get("rating"): snap["overall_rating"] = g["rating"]
|
|
||||||
if g.get("totalReviews"): snap["total_reviews"] = g["totalReviews"]
|
|
||||||
if g.get("address"): snap["location"] = g["address"]
|
|
||||||
if g.get("badges"): snap["certifications"] = g["badges"]
|
|
||||||
if g.get("totalMajorStaffs"): snap["staff_count"] = g["totalMajorStaffs"]
|
|
||||||
doctors = g.get("doctors", [])
|
|
||||||
if doctors:
|
|
||||||
lead = max(doctors, key=lambda d: d.get("reviews", 0))
|
|
||||||
snap["lead_doctor"] = {
|
|
||||||
"name": lead.get("name"), "credentials": lead.get("specialty"),
|
|
||||||
"rating": lead.get("rating"), "review_count": lead.get("reviews"),
|
|
||||||
}
|
|
||||||
return snap
|
|
||||||
|
|
||||||
|
|
||||||
def _instagram_patch(ig: dict) -> dict:
|
|
||||||
"""instagram_data(KR) → instagram_audit.accounts factual 덮어쓰기 값."""
|
|
||||||
p: dict = {}
|
|
||||||
if ig.get("username"):
|
|
||||||
p["handle"] = ig["username"]
|
|
||||||
p["profile_link"] = f"https://www.instagram.com/{ig['username']}/"
|
|
||||||
if ig.get("posts"): p["posts"] = ig["posts"]
|
|
||||||
if ig.get("followers"): p["followers"] = ig["followers"]
|
|
||||||
if ig.get("following"): p["following"] = ig["following"]
|
|
||||||
if ig.get("bio"): p["bio"] = ig["bio"]
|
|
||||||
return p
|
|
||||||
|
|
||||||
|
|
||||||
def _facebook_patch(fb: dict) -> dict:
|
|
||||||
"""facebook_data(KR) → facebook_audit.pages factual 덮어쓰기 값."""
|
|
||||||
p: dict = {}
|
|
||||||
if fb.get("pageUrl"):
|
|
||||||
p["url"] = fb["pageUrl"]
|
|
||||||
p["link"] = fb["pageUrl"]
|
|
||||||
if fb.get("pageName"): p["page_name"] = fb["pageName"]
|
|
||||||
if fb.get("followers"): p["followers"] = fb["followers"]
|
|
||||||
if fb.get("intro"): p["bio"] = fb["intro"]
|
|
||||||
if fb.get("categories"): p["category"] = ", ".join(fb["categories"])
|
|
||||||
if fb.get("website"): p["linked_domain"] = fb["website"]
|
|
||||||
return p
|
|
||||||
|
|
||||||
|
|
||||||
def _youtube_patch(yt: dict) -> dict:
|
|
||||||
"""youtube_data → youtube_audit factual 덮어쓰기 값."""
|
|
||||||
p: dict = {}
|
|
||||||
if yt.get("channelName"): p["channel_name"] = yt["channelName"]
|
|
||||||
if yt.get("handle"): p["handle"] = yt["handle"]
|
|
||||||
if yt.get("subscribers"): p["subscribers"] = yt["subscribers"]
|
|
||||||
if yt.get("totalVideos"): p["total_videos"] = yt["totalVideos"]
|
|
||||||
if yt.get("totalViews"): p["total_views"] = yt["totalViews"]
|
|
||||||
if yt.get("publishedAt"): p["channel_created_date"] = yt["publishedAt"][:10]
|
|
||||||
if yt.get("description"): p["channel_description"] = yt["description"]
|
|
||||||
if yt.get("videos"):
|
|
||||||
p["top_videos"] = [
|
|
||||||
{
|
|
||||||
"title": v["title"], "views": v["views"], "duration": v.get("duration"),
|
|
||||||
"type": "Short" if "M" not in v.get("duration", "") else "Long",
|
|
||||||
"uploaded_ago": v.get("date", "")[:10],
|
|
||||||
}
|
|
||||||
for v in yt["videos"]
|
|
||||||
]
|
|
||||||
return p
|
|
||||||
|
|
||||||
|
|
||||||
async def _build_overrides(analysis_run_id: str) -> dict:
|
async def _build_overrides(analysis_run_id: str) -> dict:
|
||||||
run = await fetchone(
|
run = await fetchone(
|
||||||
"SELECT hospital_id, instagram_data_id, facebook_data_id,"
|
"SELECT hospital_id, instagram_data_id, facebook_data_id,"
|
||||||
@@ -205,29 +112,74 @@ async def _build_overrides(analysis_run_id: str) -> dict:
|
|||||||
hospital = json.loads(hospital_row["raw_data"]) if hospital_row and isinstance(hospital_row.get("raw_data"), str) else (hospital_row or {}).get("raw_data") or {}
|
hospital = json.loads(hospital_row["raw_data"]) if hospital_row and isinstance(hospital_row.get("raw_data"), str) else (hospital_row or {}).get("raw_data") or {}
|
||||||
instagram = await fetch_raw("instagram_data", run["instagram_data_id"]) or {}
|
instagram = await fetch_raw("instagram_data", run["instagram_data_id"]) or {}
|
||||||
facebook = await fetch_raw("facebook_data", run["facebook_data_id"]) or {}
|
facebook = await fetch_raw("facebook_data", run["facebook_data_id"]) or {}
|
||||||
|
naver_blog = await fetch_raw("naver_blog_data", run["naver_blog_data_id"]) or {}
|
||||||
youtube = await fetch_raw("youtube_data", run["youtube_data_id"]) or {}
|
youtube = await fetch_raw("youtube_data", run["youtube_data_id"]) or {}
|
||||||
gangnam_unni = await fetch_raw("gangnam_unni_data", run["gangnam_unni_data_id"]) or {}
|
gangnam_unni = await fetch_raw("gangnam_unni_data", run["gangnam_unni_data_id"]) or {}
|
||||||
|
|
||||||
snapshot = _clinic_snapshot(hospital.get("brandAssets") or {}, gangnam_unni)
|
snapshot: dict = {}
|
||||||
ig_patch = _instagram_patch(instagram)
|
|
||||||
fb_patch = _facebook_patch(facebook)
|
# ── gangnam_unni ──────────────────────────────────────────────────────────
|
||||||
yt_patch = _youtube_patch(youtube)
|
doctors = gangnam_unni.get("doctors", [])
|
||||||
ig_en = hospital.get("instagramEn") or {}
|
lead = max(doctors, key=lambda d: d.get("reviews", 0)) if doctors else None
|
||||||
fb_en = hospital.get("facebookEn") or {}
|
if gangnam_unni.get("name"): snapshot["name"] = gangnam_unni["name"]
|
||||||
|
if gangnam_unni.get("rating"): snapshot["overall_rating"] = gangnam_unni["rating"]
|
||||||
|
if gangnam_unni.get("totalReviews"): snapshot["total_reviews"] = gangnam_unni["totalReviews"]
|
||||||
|
if gangnam_unni.get("address"): snapshot["location"] = gangnam_unni["address"]
|
||||||
|
if gangnam_unni.get("badges"): snapshot["certifications"] = gangnam_unni["badges"]
|
||||||
|
if gangnam_unni.get("totalMajorStaffs"): snapshot["staff_count"] = gangnam_unni["totalMajorStaffs"]
|
||||||
|
if lead:
|
||||||
|
snapshot["lead_doctor"] = {
|
||||||
|
"name": lead.get("name"),
|
||||||
|
"credentials": lead.get("specialty"),
|
||||||
|
"rating": lead.get("rating"),
|
||||||
|
"review_count": lead.get("reviews"),
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── instagram (KR·EN 계정을 코드에서 구성 → LLM 출력 무시하고 교체) ──────────────
|
||||||
|
ig_patch = build_instagram_accounts(
|
||||||
|
instagram, hospital.get("instagramEn") or {}, hospital.get("channelLogos") or {},
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── facebook ──────────────────────────────────────────────────────────────
|
||||||
|
fb_patch: dict = {}
|
||||||
|
if facebook.get("pageUrl"): fb_patch["url"] = facebook["pageUrl"]
|
||||||
|
if facebook.get("pageUrl"): fb_patch["link"] = facebook["pageUrl"]
|
||||||
|
if facebook.get("pageName"): fb_patch["page_name"] = facebook["pageName"]
|
||||||
|
if facebook.get("followers"): fb_patch["followers"] = facebook["followers"]
|
||||||
|
if facebook.get("intro"): fb_patch["bio"] = facebook["intro"]
|
||||||
|
if facebook.get("categories"): fb_patch["category"] = ", ".join(facebook["categories"])
|
||||||
|
if facebook.get("website"): fb_patch["linked_domain"] = facebook["website"]
|
||||||
|
|
||||||
|
# ── youtube ───────────────────────────────────────────────────────────────
|
||||||
|
yt_patch: dict = {}
|
||||||
|
if youtube.get("channelName"): yt_patch["channel_name"] = youtube["channelName"]
|
||||||
|
if youtube.get("handle"): yt_patch["handle"] = youtube["handle"]
|
||||||
|
if youtube.get("subscribers"): yt_patch["subscribers"] = youtube["subscribers"]
|
||||||
|
if youtube.get("totalVideos"): yt_patch["total_videos"] = youtube["totalVideos"]
|
||||||
|
if youtube.get("totalViews"): yt_patch["total_views"] = youtube["totalViews"]
|
||||||
|
if youtube.get("publishedAt"): yt_patch["channel_created_date"] = youtube["publishedAt"][:10]
|
||||||
|
if youtube.get("description"): yt_patch["channel_description"] = youtube["description"]
|
||||||
|
if youtube.get("videos"):
|
||||||
|
yt_patch["top_videos"] = [
|
||||||
|
{
|
||||||
|
"title": v["title"],
|
||||||
|
"views": v["views"],
|
||||||
|
"duration": v.get("duration"),
|
||||||
|
"type": "Short" if "M" not in v.get("duration", "") else "Long",
|
||||||
|
"uploaded_ago": v.get("date", "")[:10],
|
||||||
|
}
|
||||||
|
for v in youtube["videos"]
|
||||||
|
]
|
||||||
|
|
||||||
overrides: dict = {}
|
overrides: dict = {}
|
||||||
if snapshot:
|
if snapshot:
|
||||||
overrides["clinic_snapshot"] = snapshot
|
overrides["clinic_snapshot"] = snapshot
|
||||||
if ig_patch:
|
if ig_patch:
|
||||||
overrides["instagram_audit"] = {"accounts": [ig_patch]}
|
overrides["instagram_audit"] = {"accounts": ig_patch}
|
||||||
if fb_patch:
|
if fb_patch:
|
||||||
overrides["facebook_audit"] = {"pages": [fb_patch]}
|
overrides["facebook_audit"] = {"pages": [fb_patch]}
|
||||||
if yt_patch:
|
if yt_patch:
|
||||||
overrides["youtube_audit"] = yt_patch
|
overrides["youtube_audit"] = yt_patch
|
||||||
if ig_en.get("username"):
|
|
||||||
overrides["_en_ig_account"] = _en_instagram_account(ig_en)
|
|
||||||
if fb_en.get("pageUrl") or fb_en.get("pageName"):
|
|
||||||
overrides["_en_fb_page"] = _en_facebook_page(fb_en)
|
|
||||||
return overrides
|
return overrides
|
||||||
|
|
||||||
|
|
||||||
@@ -243,22 +195,10 @@ def _deep_merge(base: dict, overrides: dict) -> dict:
|
|||||||
base[k] = v
|
base[k] = v
|
||||||
return base
|
return base
|
||||||
|
|
||||||
def _ensure_en_entry(audit: dict, list_key: str, en_entry: dict | None) -> None:
|
|
||||||
"""audit 리스트(accounts/pages)에 EN 항목이 없으면 추가 — LLM 누락 대비, 중복 방지."""
|
|
||||||
if not en_entry:
|
|
||||||
return
|
|
||||||
items = audit.setdefault(list_key, [])
|
|
||||||
if not any(it.get("language") == "EN" for it in items):
|
|
||||||
items.append(en_entry)
|
|
||||||
|
|
||||||
|
|
||||||
def _patch_report(result: ReportOutput, overrides: dict) -> ReportOutput:
|
def _patch_report(result: ReportOutput, overrides: dict) -> ReportOutput:
|
||||||
en_ig = overrides.pop("_en_ig_account", None)
|
|
||||||
en_fb = overrides.pop("_en_fb_page", None)
|
|
||||||
merged = _deep_merge(result.model_dump(), overrides)
|
merged = _deep_merge(result.model_dump(), overrides)
|
||||||
# LLM이 audit에 영문 계정을 빠뜨려도 항상 KR+EN 둘 다 보장.
|
# 인스타 계정은 프롬프트에서 LLM이 []로 두게 했고, 코드가 수집 데이터로 채운다 (데이터 없으면 빈 리스트)
|
||||||
_ensure_en_entry(merged.setdefault("instagram_audit", {}), "accounts", en_ig)
|
merged.setdefault("instagram_audit", {})["accounts"] = (overrides.get("instagram_audit") or {}).get("accounts") or []
|
||||||
_ensure_en_entry(merged.setdefault("facebook_audit", {}), "pages", en_fb)
|
|
||||||
return ReportOutput(**merged)
|
return ReportOutput(**merged)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
"""Instagram audit 계정(KR·EN)을 수집 데이터로 구성.
|
||||||
|
fix 값(handle/followers/highlights/content_format 등)은 전부 코드에서 박는다 — LLM 출력 무시."""
|
||||||
|
|
||||||
|
_MEDIA = {"GraphImage": "이미지", "GraphSidecar": "카드뉴스", "GraphVideo": "영상/릴스"}
|
||||||
|
|
||||||
|
|
||||||
|
def _content_format(data: dict) -> str:
|
||||||
|
"""latestPosts 미디어 타입으로 콘텐츠 포맷 도출 (표기 순서는 _MEDIA 정의 순서로 고정)."""
|
||||||
|
present = {_MEDIA.get(p.get("type")) for p in (data.get("latestPosts") or [])}
|
||||||
|
return "/".join(m for m in _MEDIA.values() if m in present)
|
||||||
|
|
||||||
|
|
||||||
|
def _logo_desc(channel_logos: dict, channel: str) -> str:
|
||||||
|
"""channelLogos(비전 결과)에서 해당 채널 로고 설명만 가져온다."""
|
||||||
|
for c in (channel_logos or {}).get("channel_logos", []):
|
||||||
|
if c.get("channel") == channel:
|
||||||
|
return c.get("logo_description") or ""
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _account(data: dict, language: str, label: str, channel: str, channel_logos: dict) -> dict:
|
||||||
|
"""스크래퍼 수집값으로 InstagramAccount 전 필드를 구성."""
|
||||||
|
handle = data.get("username") or ""
|
||||||
|
return {
|
||||||
|
"handle": handle,
|
||||||
|
"language": language,
|
||||||
|
"label": label,
|
||||||
|
"posts": data.get("posts", 0),
|
||||||
|
"followers": data.get("followers", 0),
|
||||||
|
"following": data.get("following", 0),
|
||||||
|
"category": data.get("category", ""),
|
||||||
|
"profile_link": f"https://www.instagram.com/{handle}/" if handle else "",
|
||||||
|
"highlights": data.get("highlights") or [],
|
||||||
|
"reels_count": 0, # 릴스 스크래퍼 미사용
|
||||||
|
"content_format": _content_format(data),
|
||||||
|
"profile_photo": _logo_desc(channel_logos, channel),
|
||||||
|
"bio": data.get("bio", ""),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def build_instagram_accounts(instagram: dict, instagram_en: dict, channel_logos: dict) -> list[dict]:
|
||||||
|
"""KR·EN 인스타 계정 리스트 구성 (username 있는 것만)."""
|
||||||
|
accounts: list[dict] = []
|
||||||
|
if instagram.get("username"):
|
||||||
|
accounts.append(_account(instagram, "KR", "인스타그램 KR", "Instagram", channel_logos))
|
||||||
|
if instagram_en.get("username"):
|
||||||
|
accounts.append(_account(instagram_en, "EN", "인스타그램 EN", "Instagram EN", channel_logos))
|
||||||
|
return accounts
|
||||||
Reference in new issue
Block a user