빈값 채우기 및 코드 정리
This commit is contained in:
commit
ff19db34a8
36 files changed
+3348
-377
No files matched your search
+138
-226
@@ -1,55 +1,29 @@
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
from datetime import datetime
|
||||
from urllib.parse import urlparse
|
||||
from common.db.run import select_run, update_run_report, update_run_plan
|
||||
from common.db.source import select_run_raw_data, select_run_mainpage_url
|
||||
from models.status import SourceType
|
||||
from common.utils import parse_iso_duration_seconds, format_seconds, format_clock, calc_avg_video_length, relative_date, calc_upload_frequency
|
||||
from common.db.run import update_run_report, update_run_plan, select_run_report_data, select_run
|
||||
from common.db.source import select_run_raw_data, select_mainpage_logo_url
|
||||
from common.db.market import select_market
|
||||
from integrations.llm.llm_service import LLMService
|
||||
from integrations.llm.prompt import report_prompt, plan_prompt, youtube_diagnosis_prompt, brand_consistency_prompt, critical_issues_prompt, transformation_prompt, roadmap_prompt
|
||||
from integrations.llm.schemas.report import ReportOutput, ClinicSnapshot, YouTubeAudit, BrandConsistencyOutput, CriticalIssuesOutput, DiagnosisItem, TransformationProposal, RoadmapOutput, RoadmapMonth
|
||||
from integrations.llm.prompt import report_prompt, plan_prompt, youtube_diagnosis_prompt, brand_consistency_prompt, critical_issues_prompt, transformation_prompt, roadmap_prompt, scores_prompt
|
||||
from integrations.llm.schemas.report import ReportOutput, ClinicSnapshot, YouTubeAudit, BrandConsistencyOutput, CriticalIssuesOutput, DiagnosisItem, TransformationProposal, RoadmapOutput, RoadmapMonth, ScoresOutput, ChannelScore
|
||||
from services.branding import analyze_branding
|
||||
from services.instagram_audit import build_instagram_audit
|
||||
from services.facebook_audit import build_facebook_audit
|
||||
from services.kpi_dashboard import build_kpi_dashboard
|
||||
from integrations.llm.schemas.plan import PlanOutput
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def generate_report(analysis_run_id: str) -> ReportOutput:
|
||||
raw = await select_run_raw_data(analysis_run_id)
|
||||
clinic = raw.get("mainpage") or {}
|
||||
market = await select_market(analysis_run_id)
|
||||
|
||||
def _json(v) -> str | None:
|
||||
return json.dumps(v, ensure_ascii=False) if v else None
|
||||
|
||||
input_data = {
|
||||
"clinic_name": clinic.get("clinicName"),
|
||||
"clinic_name_en": clinic.get("clinicNameEn"),
|
||||
"address": clinic.get("address"),
|
||||
"phone": clinic.get("phone"),
|
||||
"slogan": clinic.get("slogan"),
|
||||
"services": json.dumps(clinic.get("services", []), ensure_ascii=False),
|
||||
"doctors": json.dumps(clinic.get("doctors", []), ensure_ascii=False),
|
||||
"market_competitors": _json(market.get("competitors")),
|
||||
"market_keywords": _json(market.get("keywords")),
|
||||
"market_trend": _json(market.get("trend")),
|
||||
"market_target_audience": _json(market.get("target_audience")),
|
||||
**{
|
||||
source_type: _json(data)
|
||||
for source_type, data in raw.items()
|
||||
if source_type != "mainpage"
|
||||
},
|
||||
}
|
||||
|
||||
return await LLMService(provider="perplexity").generate(report_prompt, input_data)
|
||||
|
||||
async def generate_plan(analysis_run_id: str) -> PlanOutput:
|
||||
run = await select_run(analysis_run_id)
|
||||
raw = await select_run_raw_data(analysis_run_id)
|
||||
clinic = raw.get("mainpage") or {}
|
||||
report_data = run["report_data"]
|
||||
report = json.loads(report_data) if isinstance(report_data, str) else report_data
|
||||
clinic = raw.get(SourceType.MAINPAGE) or []
|
||||
clinic = clinic[0]["raw_data"] # if not exist, must error
|
||||
branding = raw.get(SourceType.BRANDING) or []
|
||||
branding = branding[0]["raw_data"] # if not exist, must error
|
||||
report = await select_run_report_data(analysis_run_id)
|
||||
market = await select_market(analysis_run_id)
|
||||
|
||||
def _json(v) -> str | None:
|
||||
@@ -68,23 +42,30 @@ async def generate_plan(analysis_run_id: str) -> PlanOutput:
|
||||
"market_keywords": _json(market.get("keywords")),
|
||||
"market_trend": _json(market.get("trend")),
|
||||
"market_target_audience": _json(market.get("target_audience")),
|
||||
"tiktok": _json(raw.get(SourceType.TIKTOK)),
|
||||
"instagram_en": _json(raw.get(SourceType.INSTAGRAM)),
|
||||
"facebook_en": _json(raw.get(SourceType.FACEBOOK)),
|
||||
"naver_blog": _json(_naver_blog_summary(raw.get(SourceType.NAVER_BLOG))),
|
||||
"naver_cafe": _json(raw.get(SourceType.NAVER_CAFE)),
|
||||
"kakao_talk": _json(raw.get(SourceType.KAKAOTALK)),
|
||||
"channel_logos": _json(branding.get("channelLogos")),
|
||||
"brand_assets": _json(branding.get("brandAssets")),
|
||||
}
|
||||
|
||||
return await LLMService(provider="perplexity").generate(plan_prompt, input_data)
|
||||
|
||||
|
||||
def _build_clinic_snapshot(gangnam_unni: dict, hospital: dict) -> dict:
|
||||
def _build_clinic_snapshot(mainpage: dict, gangnam_unni: dict, brand_assets: dict, logo_url: str | None) -> dict:
|
||||
snapshot: dict = {}
|
||||
doctors = gangnam_unni.get("doctors", [])
|
||||
lead = max(doctors, key=lambda d: d.get("reviews", 0)) if doctors else None
|
||||
if gangnam_unni.get("name"): snapshot["name"] = gangnam_unni["name"]
|
||||
if hospital.get("clinicNameEn"): snapshot["name_en"] = hospital["clinicNameEn"]
|
||||
if hospital.get("phone"): snapshot["phone"] = hospital["phone"]
|
||||
domain = hospital.get("domain") or urlparse(hospital.get("sourceUrl") or "").netloc
|
||||
if domain: snapshot["domain"] = domain
|
||||
snapshot["name"] = mainpage["clinicName"]
|
||||
snapshot["name_en"] = mainpage["clinicNameEn"]
|
||||
snapshot["phone"] = mainpage["phone"]
|
||||
snapshot["location"] = mainpage["address"]
|
||||
snapshot["domain"] = mainpage.get("domain") or urlparse(mainpage.get("sourceUrl") or "").netloc
|
||||
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:
|
||||
@@ -94,81 +75,31 @@ def _build_clinic_snapshot(gangnam_unni: dict, hospital: dict) -> dict:
|
||||
"rating": lead.get("rating"),
|
||||
"review_count": lead.get("reviews"),
|
||||
}
|
||||
# logo URL 은 raw_info.logo_url 컬럼에서, brand_colors 는 JSON 에서 강제 주입. LLM 의 null 처리 차단.
|
||||
if logo_url:
|
||||
snapshot["logo_images"] = {"circle": None, "horizontal": logo_url, "korean": None}
|
||||
if brand_assets.get("brand_colors"): snapshot["brand_colors"] = brand_assets["brand_colors"]
|
||||
return ClinicSnapshot.model_validate(snapshot).model_dump()
|
||||
|
||||
def _naver_blog_summary(blog: dict | None) -> dict | None:
|
||||
"""plan 카드 한 장에 들어가는 건 전체 포스트 수와 최근 활동 시점뿐. 그 외(본문·링크·제목)는
|
||||
던져봐야 토큰만 늘고 LLM 이 무관 정보로 hallucinate 함."""
|
||||
if not blog:
|
||||
return None
|
||||
posts = blog.get("posts") or []
|
||||
return {
|
||||
"totalPosts": blog.get("totalResults"),
|
||||
"latestPostDate": posts[0].get("postDate") if posts else None,
|
||||
}
|
||||
|
||||
def _parse_iso_duration_seconds(iso: str) -> int:
|
||||
m = re.match(r"PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?", iso or "")
|
||||
if not m:
|
||||
return 0
|
||||
h, mins, s = (int(x or 0) for x in m.groups())
|
||||
return h * 3600 + mins * 60 + s
|
||||
|
||||
|
||||
def _format_seconds(seconds: int) -> str:
|
||||
m, s = divmod(seconds, 60)
|
||||
h, m = divmod(m, 60)
|
||||
return f"{h}시간 {m}분" if h else f"{m}분 {s}초"
|
||||
|
||||
|
||||
def _format_clock(seconds: int) -> str:
|
||||
m, s = divmod(seconds, 60)
|
||||
h, m = divmod(m, 60)
|
||||
return f"{h}:{m:02d}:{s:02d}" if h else f"{m}:{s:02d}"
|
||||
|
||||
|
||||
def _calc_avg_video_length(videos: list[dict]) -> str:
|
||||
durations = [_parse_iso_duration_seconds(v.get("duration", "")) for v in videos]
|
||||
durations = [d for d in durations if d > 0]
|
||||
if not durations:
|
||||
return ""
|
||||
return _format_seconds(sum(durations) // len(durations))
|
||||
|
||||
|
||||
def _relative_date(date_str: str) -> str:
|
||||
if not date_str:
|
||||
return ""
|
||||
try:
|
||||
past = datetime.fromisoformat(date_str[:10])
|
||||
except ValueError:
|
||||
return ""
|
||||
days = (datetime.now() - past).days
|
||||
if days < 1:
|
||||
return "오늘"
|
||||
if days < 30:
|
||||
return f"{days}일 전"
|
||||
if days < 365:
|
||||
return f"{days // 30}개월 전"
|
||||
return f"{days // 365}년 전"
|
||||
|
||||
|
||||
def _calc_upload_frequency(videos: list[dict]) -> str:
|
||||
dates = sorted(
|
||||
[v["date"][:10] for v in videos if v.get("date")],
|
||||
reverse=True,
|
||||
)
|
||||
if len(dates) < 2:
|
||||
return ""
|
||||
gaps = [
|
||||
(datetime.fromisoformat(dates[i]) - datetime.fromisoformat(dates[i + 1])).days
|
||||
for i in range(len(dates) - 1)
|
||||
]
|
||||
avg_days = sum(gaps) // len(gaps)
|
||||
if avg_days <= 7:
|
||||
return f"주 {7 // max(avg_days, 1)}회"
|
||||
if avg_days <= 30:
|
||||
return f"월 {30 // avg_days}회"
|
||||
return f"{avg_days}일에 1회"
|
||||
|
||||
|
||||
async def _build_youtube_audit(youtube: dict) -> dict:
|
||||
async def _build_youtube_audit(youtube: dict) -> dict: # 기획상 1개의 input channel, 다중 채널은 기획에 없음.
|
||||
videos = youtube.get("videos", [])
|
||||
yt_patch: dict = {
|
||||
"weekly_view_growth": {"absolute": 0, "percentage": 0.0},
|
||||
"estimated_monthly_revenue": {"min": 0, "max": 0},
|
||||
"linked_urls": [],
|
||||
"avg_video_length": _calc_avg_video_length(videos),
|
||||
"upload_frequency": _calc_upload_frequency(videos),
|
||||
"avg_video_length": calc_avg_video_length(videos),
|
||||
"upload_frequency": calc_upload_frequency(videos),
|
||||
}
|
||||
if youtube.get("channelName"): yt_patch["channel_name"] = youtube["channelName"]
|
||||
if youtube.get("handle"): yt_patch["handle"] = youtube["handle"]
|
||||
@@ -176,16 +107,16 @@ async def _build_youtube_audit(youtube: dict) -> dict:
|
||||
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"]
|
||||
yt_patch["channel_description"] = youtube.get("description") or ""
|
||||
if youtube.get("playlists"): yt_patch["playlists"] = youtube["playlists"]
|
||||
if videos:
|
||||
yt_patch["top_videos"] = [
|
||||
{
|
||||
"title": v["title"],
|
||||
"views": v["views"],
|
||||
"duration": _format_clock(_parse_iso_duration_seconds(v.get("duration", ""))),
|
||||
"duration": format_clock(parse_iso_duration_seconds(v.get("duration", ""))),
|
||||
"type": "Short" if "M" not in v.get("duration", "") else "Long",
|
||||
"uploaded_ago": _relative_date(v.get("date", "")),
|
||||
"uploaded_ago": relative_date(v.get("date", "")),
|
||||
}
|
||||
for v in videos
|
||||
]
|
||||
@@ -212,7 +143,7 @@ async def _build_roadmap(analysis_run_id: str, raw: dict) -> list[dict]:
|
||||
result: RoadmapOutput = await LLMService(provider="perplexity").generate(
|
||||
roadmap_prompt,
|
||||
{
|
||||
"clinic_name": (raw.get("mainpage") or {}).get("clinicName"),
|
||||
"clinic_name": (raw.get(SourceType.MAINPAGE) or [{}])[0]["raw_data"].get("clinicName"),
|
||||
"data": json.dumps(raw, ensure_ascii=False),
|
||||
},
|
||||
)
|
||||
@@ -223,7 +154,7 @@ async def _build_transformation(analysis_run_id: str, raw: dict) -> dict:
|
||||
result: TransformationProposal = await LLMService(provider="perplexity").generate(
|
||||
transformation_prompt,
|
||||
{
|
||||
"clinic_name": (raw.get("mainpage") or {}).get("clinicName"),
|
||||
"clinic_name": (raw.get(SourceType.MAINPAGE) or [{}])[0]["raw_data"].get("clinicName"),
|
||||
"data": json.dumps(raw, ensure_ascii=False),
|
||||
},
|
||||
)
|
||||
@@ -234,155 +165,136 @@ async def _build_critical_issues(analysis_run_id: str, raw: dict) -> list[dict]:
|
||||
result: CriticalIssuesOutput = await LLMService(provider="perplexity").generate(
|
||||
critical_issues_prompt,
|
||||
{
|
||||
"clinic_name": (raw.get("mainpage") or {}).get("clinicName"),
|
||||
"clinic_name": (raw.get(SourceType.MAINPAGE) or [{}])[0]["raw_data"].get("clinicName"),
|
||||
"data": json.dumps(raw, ensure_ascii=False),
|
||||
},
|
||||
)
|
||||
return [DiagnosisItem.model_validate(item).model_dump() for item in result.diagnosis]
|
||||
|
||||
|
||||
async def _build_overrides(analysis_run_id: str) -> dict:
|
||||
async def _build_scores(analysis_run_id: str, raw: dict) -> ScoresOutput:
|
||||
return await LLMService(provider="perplexity").generate(
|
||||
scores_prompt,
|
||||
{
|
||||
"clinic_name": (raw.get(SourceType.MAINPAGE) or [{}])[0]["raw_data"].get("clinicName"),
|
||||
"data": json.dumps(raw, ensure_ascii=False),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
async def _build_report(analysis_run_id: str) -> dict:
|
||||
raw = await select_run_raw_data(analysis_run_id)
|
||||
run = await select_run(analysis_run_id)
|
||||
if not raw:
|
||||
return {}
|
||||
|
||||
mainpage = raw.get("mainpage", {}) or {}
|
||||
instagram = raw.get("instagram", {}) or {}
|
||||
facebook = raw.get("facebook", {}) or {}
|
||||
youtube = raw.get("youtube", {}) or {}
|
||||
gangnam_unni = raw.get("gangnam_unni", {}) or {}
|
||||
mainpage = raw.get(SourceType.MAINPAGE) or []
|
||||
mainpage = mainpage[0]["raw_data"] # 유일
|
||||
branding = raw.get(SourceType.BRANDING) or []
|
||||
branding = branding[0]["raw_data"] # 유일
|
||||
instagram = raw.get(SourceType.INSTAGRAM) or []
|
||||
facebook = raw.get(SourceType.FACEBOOK) or []
|
||||
youtube = raw.get(SourceType.YOUTUBE) or []
|
||||
youtube = youtube[0]["raw_data"] if youtube else None # 유일 (기획상)
|
||||
gangnam_unni = raw.get(SourceType.GANGNAM_UNNI) or []
|
||||
gangnam_unni = gangnam_unni[0]["raw_data"] if gangnam_unni else None# 유일 (기획상)
|
||||
naver_blog = raw.get(SourceType.NAVER_BLOG) or []
|
||||
naver_blog = naver_blog[0]["raw_data"] if naver_blog else None# 유일 (기획상)
|
||||
tiktok = raw.get(SourceType.TIKTOK) or []
|
||||
tiktok = tiktok[0]["raw_data"] if tiktok else None# 유일 (기획상)
|
||||
naver_cafe = raw.get(SourceType.NAVER_CAFE) or []
|
||||
naver_cafe = naver_cafe[0]["raw_data"] if naver_cafe else None# 유일 (기획상)
|
||||
|
||||
snapshot: dict = _build_clinic_snapshot(gangnam_unni, mainpage)
|
||||
yt_patch: dict = await _build_youtube_audit(youtube)
|
||||
brand_assets = branding.get("brandAssets") or {}
|
||||
channel_logos = branding.get("channelLogos") or {}
|
||||
|
||||
# ── instagram ─────────────────────────────────────────────────────────────
|
||||
ig_patch: dict = {}
|
||||
if instagram.get("username"): ig_patch["handle"] = instagram["username"]
|
||||
if instagram.get("posts"): ig_patch["posts"] = instagram["posts"]
|
||||
if instagram.get("followers"): ig_patch["followers"] = instagram["followers"]
|
||||
if instagram.get("following"): ig_patch["following"] = instagram["following"]
|
||||
if instagram.get("bio"): ig_patch["bio"] = instagram["bio"]
|
||||
if instagram.get("username"): ig_patch["profile_link"] = f"https://www.instagram.com/{instagram['username']}/"
|
||||
|
||||
# ── facebook ──────────────────────────────────────────────────────────────
|
||||
fb_pages: dict = {}
|
||||
if facebook.get("pageUrl"): fb_pages["url"] = facebook["pageUrl"]
|
||||
if facebook.get("pageUrl"): fb_pages["link"] = facebook["pageUrl"]
|
||||
if facebook.get("pageName"): fb_pages["page_name"] = facebook["pageName"]
|
||||
if facebook.get("followers"): fb_pages["followers"] = facebook["followers"]
|
||||
if facebook.get("intro"): fb_pages["bio"] = facebook["intro"]
|
||||
if facebook.get("categories"): fb_pages["category"] = ", ".join(facebook["categories"])
|
||||
if facebook.get("website"): fb_pages["linked_domain"] = facebook["website"]
|
||||
logo_url = await select_mainpage_logo_url(analysis_run_id)
|
||||
|
||||
brand = await generate_brand_consistency(analysis_run_id)
|
||||
brand_patch = brand.model_dump()["brand_inconsistencies"]
|
||||
critical_issues = await _build_critical_issues(analysis_run_id, raw)
|
||||
transformation = await _build_transformation(analysis_run_id, raw)
|
||||
roadmap = await _build_roadmap(analysis_run_id, raw)
|
||||
brand_patch : list[dict] = brand.model_dump()["brand_inconsistencies"]
|
||||
|
||||
kpi_extras = {
|
||||
"tiktok": tiktok,
|
||||
"naverCafe": naver_cafe,
|
||||
}
|
||||
|
||||
fb_patch: dict = {}
|
||||
if fb_pages:
|
||||
fb_patch["pages"] = [fb_pages]
|
||||
if brand_patch:
|
||||
fb_patch["brand_inconsistencies"] = brand_patch
|
||||
scores = (await _build_scores(analysis_run_id, raw)).model_dump()
|
||||
|
||||
overrides: dict = {}
|
||||
if snapshot:
|
||||
overrides["clinic_snapshot"] = snapshot
|
||||
if ig_patch:
|
||||
overrides["instagram_audit"] = {"accounts": [ig_patch]}
|
||||
if fb_patch:
|
||||
overrides["facebook_audit"] = fb_patch
|
||||
if yt_patch:
|
||||
overrides["youtube_audit"] = yt_patch
|
||||
if critical_issues:
|
||||
overrides["problem_diagnosis"] = critical_issues
|
||||
if transformation:
|
||||
overrides["transformation"] = transformation
|
||||
if roadmap:
|
||||
overrides["roadmap"] = roadmap
|
||||
return overrides
|
||||
report = {
|
||||
"id" : analysis_run_id,
|
||||
"created_at" : str(run["created_at"]) if run.get("created_at") else None,
|
||||
"target_url" : mainpage.get("domain") or urlparse(mainpage.get("sourceUrl") or "").netloc,
|
||||
"overall_score" : scores.get("overall_score"),
|
||||
"channel_scores" : scores.get("channel_scores"),
|
||||
|
||||
"clinic_snapshot": _build_clinic_snapshot(mainpage, gangnam_unni, brand_assets, logo_url),
|
||||
"instagram_audit": await build_instagram_audit(instagram, channel_logos),
|
||||
"facebook_audit": await build_facebook_audit(facebook, brand_patch, channel_logos),
|
||||
"youtube_audit": await _build_youtube_audit(youtube),
|
||||
|
||||
"other_channels": "",
|
||||
"website_audit": "",
|
||||
|
||||
"problem_diagnosis": await _build_critical_issues(analysis_run_id, raw),
|
||||
"transformation" : await _build_transformation(analysis_run_id, raw),
|
||||
"roadmap": await _build_roadmap(analysis_run_id, raw),
|
||||
"kpi_dashboard": build_kpi_dashboard(instagram, facebook, youtube, gangnam_unni, kpi_extras, naver_blog),
|
||||
}
|
||||
|
||||
return ReportOutput(**report)
|
||||
|
||||
|
||||
def _deep_merge(base: dict, overrides: dict) -> dict:
|
||||
"""dict 끼리 만나면 재귀로 안쪽까지 합치고, 그 외(list/scalar/None) 는 override 값으로 통째 치환."""
|
||||
for k, v in overrides.items():
|
||||
if isinstance(v, dict) and isinstance(base.get(k), dict):
|
||||
_deep_merge(base[k], v)
|
||||
elif isinstance(v, list) and isinstance(base.get(k), list):
|
||||
for i, item in enumerate(v):
|
||||
if i < len(base[k]) and isinstance(item, dict) and isinstance(base[k][i], dict):
|
||||
_deep_merge(base[k][i], item)
|
||||
else:
|
||||
base[k] = v
|
||||
return base
|
||||
|
||||
def _patch_report(result: ReportOutput, overrides: dict) -> ReportOutput:
|
||||
base = result.model_dump()
|
||||
for key in overrides:
|
||||
base.pop(key, None)
|
||||
return ReportOutput(**_deep_merge(base, overrides))
|
||||
|
||||
|
||||
_MOCK_DOMAINS = {"viewclinic.com"}
|
||||
_MOCK_REPORT_PATH = os.path.join(os.path.dirname(__file__), "../mock/report_viewclinic.json")
|
||||
|
||||
|
||||
async def _is_mock(analysis_run_id: str) -> bool:
|
||||
url = await select_run_mainpage_url(analysis_run_id)
|
||||
return any(domain in url for domain in _MOCK_DOMAINS)
|
||||
|
||||
|
||||
def _load_mock_report() -> ReportOutput:
|
||||
with open(_MOCK_REPORT_PATH, encoding="utf-8") as f:
|
||||
return ReportOutput(**json.load(f))
|
||||
|
||||
|
||||
_MOCK_PLAN_PATH = os.path.join(os.path.dirname(__file__), "../mock/plan_viewclinic.json")
|
||||
|
||||
|
||||
def _load_mock_plan() -> PlanOutput:
|
||||
with open(_MOCK_PLAN_PATH, encoding="utf-8") as f:
|
||||
return PlanOutput(**json.load(f))
|
||||
|
||||
|
||||
async def generate_brand_consistency(analysis_run_id: str) -> BrandConsistencyOutput:
|
||||
raw = await select_run_raw_data(analysis_run_id)
|
||||
|
||||
def _json(v) -> str | None:
|
||||
return json.dumps(v, ensure_ascii=False) if v else None
|
||||
|
||||
mainpage = raw.get("mainpage") or {}
|
||||
mainpage = raw.get(SourceType.MAINPAGE) or []
|
||||
input_data = {
|
||||
"clinic_name": mainpage.get("clinicName"),
|
||||
"clinic_name": (mainpage[0].get("clinicName") if mainpage else None),
|
||||
"mainpage": _json(mainpage),
|
||||
"instagram": _json(raw.get("instagram")),
|
||||
"facebook": _json(raw.get("facebook")),
|
||||
"youtube": _json(raw.get("youtube")),
|
||||
"gangnam_unni": _json(raw.get("gangnam_unni")),
|
||||
"instagram": _json(raw.get(SourceType.INSTAGRAM)),
|
||||
"facebook": _json(raw.get(SourceType.FACEBOOK)),
|
||||
"youtube": _json(raw.get(SourceType.YOUTUBE)),
|
||||
"gangnam_unni": _json(raw.get(SourceType.GANGNAM_UNNI)),
|
||||
}
|
||||
return await LLMService(provider="perplexity").generate(brand_consistency_prompt, input_data)
|
||||
|
||||
|
||||
|
||||
async def run_report_task(analysis_run_id: str) -> None:
|
||||
logger.info("[report] start run=%s", analysis_run_id)
|
||||
if await _is_mock(analysis_run_id):
|
||||
logger.info("[report] mock mode run=%s", analysis_run_id)
|
||||
result = _load_mock_report()
|
||||
result.youtube_audit.linked_urls = []
|
||||
else:
|
||||
result = await generate_report(analysis_run_id)
|
||||
|
||||
result = _patch_report(result, await _build_overrides(analysis_run_id))
|
||||
await analyze_branding(analysis_run_id)
|
||||
# result = await generate_report(analysis_run_id)
|
||||
result = await _build_report(analysis_run_id)
|
||||
await update_run_report(analysis_run_id, result.model_dump())
|
||||
logger.info("[report] done run=%s", analysis_run_id)
|
||||
|
||||
|
||||
def _patch_plan(result: PlanOutput, logo_desc: str) -> PlanOutput:
|
||||
"""brand_guide.channel_branding[].profile_photo 는 LLM 안 맡기고 코드가 박는다
|
||||
(모든 채널 동일값 = brand_assets.logo_description). LLM 이 fallback 문구 hallucinate 방지."""
|
||||
p = result.model_dump()
|
||||
for ch in (p.get("brand_guide") or {}).get("channel_branding") or []:
|
||||
ch["profile_photo"] = logo_desc
|
||||
return PlanOutput(**p)
|
||||
|
||||
|
||||
async def run_plan_task(analysis_run_id: str) -> None:
|
||||
logger.info("[plan] start run=%s", analysis_run_id)
|
||||
if await _is_mock(analysis_run_id):
|
||||
logger.info("[plan] mock mode run=%s", analysis_run_id)
|
||||
result = _load_mock_plan()
|
||||
else:
|
||||
result = await generate_plan(analysis_run_id)
|
||||
result = await generate_plan(analysis_run_id)
|
||||
# profile_photo 는 brand_assets.logo_description 으로 코드가 박음 (LLM "(가이드 미보유)" 같은 hallucination 차단).
|
||||
raw = await select_run_raw_data(analysis_run_id)
|
||||
branding = raw.get(SourceType.BRANDING) or []
|
||||
logo_desc = (((branding[0] if branding else {}).get("brandAssets") or {}).get("logo_description")) or ""
|
||||
result = _patch_plan(result, logo_desc)
|
||||
await update_run_plan(analysis_run_id, result.model_dump())
|
||||
logger.info("[plan] done run=%s", analysis_run_id)
|
||||
@@ -0,0 +1,172 @@
|
||||
"""collect 단계 - HTML/CSS 텍스트에서 brand 로고 URL + 색상 추출"""
|
||||
import logging
|
||||
import re
|
||||
from collections import Counter
|
||||
from urllib.parse import urljoin
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ── 로고 URL 추출 ─────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
LOGO_IMG_PATTERNS = [
|
||||
re.compile(r'<img[^>]*\bclass=["\'][^"\']*\blogo\b[^"\']*["\'][^>]*\bsrc=["\']([^"\']+)["\']', re.IGNORECASE),
|
||||
re.compile(r'<img[^>]*\bsrc=["\']([^"\']+)["\'][^>]*\bclass=["\'][^"\']*\blogo\b[^"\']*["\']', re.IGNORECASE),
|
||||
re.compile(r'<img[^>]*\bid=["\'][^"\']*\blogo\b[^"\']*["\'][^>]*\bsrc=["\']([^"\']+)["\']', re.IGNORECASE),
|
||||
re.compile(r'<img[^>]*\balt=["\'][^"\']*\blogo\b[^"\']*["\'][^>]*\bsrc=["\']([^"\']+)["\']', re.IGNORECASE),
|
||||
re.compile(r'<(?:a|h[1-6]|div|span)[^>]*\b(?:class|id)=["\'][^"\']*\blogo\b[^"\']*["\'][^>]*>(?:[^<]|<(?!img))*<img[^>]*\bsrc=["\']([^"\']+)["\']', re.IGNORECASE | re.DOTALL),
|
||||
re.compile(r'<(?:a|div|span|h[1-6])[^>]*\b(?:class|id)=["\'][^"\']*\blogo\b[^"\']*["\'][^>]*\bstyle=["\'][^"\']*background(?:-image)?\s*:\s*url\(\s*["\']?([^"\')\s]+)', re.IGNORECASE),
|
||||
re.compile(r'<(?:a|div|span|h[1-6])[^>]*\bstyle=["\'][^"\']*background(?:-image)?\s*:\s*url\(\s*["\']?([^"\')\s]+)[^"\']*["\'][^>]*\b(?:class|id)=["\'][^"\']*\blogo\b', re.IGNORECASE),
|
||||
re.compile(r'<img[^>]*\bsrc=["\']([^"\']*\blogo\b[^"\']*\.(?:png|svg|jpe?g|webp)[^"\']*)["\']', re.IGNORECASE),
|
||||
re.compile(r'<header\b[^>]*>(?:[^<]|<(?!img))*<img[^>]*\bsrc=["\']([^"\']+\.(?:png|svg|jpe?g|webp)[^"\']*)["\']', re.IGNORECASE | re.DOTALL),
|
||||
re.compile(r'<nav\b[^>]*>(?:[^<]|<(?!img))*<img[^>]*\bsrc=["\']([^"\']+\.(?:png|svg|jpe?g|webp)[^"\']*)["\']', re.IGNORECASE | re.DOTALL),
|
||||
re.compile(r'<meta[^>]*\bproperty=["\']og:image["\'][^>]*\bcontent=["\']([^"\']+)["\']', re.IGNORECASE),
|
||||
re.compile(r'<meta[^>]*\bcontent=["\']([^"\']+)["\'][^>]*\bproperty=["\']og:image["\']', re.IGNORECASE),
|
||||
]
|
||||
|
||||
LOGO_CSS_PATTERN = re.compile(
|
||||
r'\.[\w-]*\blogo\b[\w-]*\s*(?:,\s*\.[\w-]+\s*)*\{[^}]*background(?:-image)?\s*:\s*url\(\s*["\']?([^"\')\s]+)',
|
||||
re.IGNORECASE | re.DOTALL,
|
||||
)
|
||||
|
||||
|
||||
def find_logo_url_in_html(html: str, base_url: str, css_texts: list[str] | None = None) -> str | None:
|
||||
"""HTML 에서 logo URL 찾기. 우선순위: 1) class/id/alt 명시 img 2) 외부 CSS .logo bg 3) header/nav 첫 img."""
|
||||
|
||||
def _is_noise(src: str) -> bool:
|
||||
if not src or src.startswith("data:"):
|
||||
return True
|
||||
if re.search(r"(blank|spacer|pixel|transparent|1x1)\b", src, re.IGNORECASE):
|
||||
return True
|
||||
if re.search(r"(lang[-_]?(kor|eng|chn|jpn|rus|jp|en|ko|cn|ar|in)|flag|country|icon-|btn-|arrow|prev|next|search)\b", src, re.IGNORECASE):
|
||||
return True
|
||||
return False
|
||||
|
||||
for pat in LOGO_IMG_PATTERNS[:8]:
|
||||
for m in pat.finditer(html):
|
||||
src = m.group(1)
|
||||
if _is_noise(src):
|
||||
continue
|
||||
return urljoin(base_url, src)
|
||||
|
||||
for css in (css_texts or []):
|
||||
m = LOGO_CSS_PATTERN.search(css)
|
||||
if m:
|
||||
src = m.group(1)
|
||||
if not _is_noise(src):
|
||||
return urljoin(base_url, src)
|
||||
|
||||
for pat in LOGO_IMG_PATTERNS[8:]:
|
||||
for m in pat.finditer(html):
|
||||
src = m.group(1)
|
||||
if _is_noise(src):
|
||||
continue
|
||||
return urljoin(base_url, src)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
# ── 색상 추출 ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
HEX6 = re.compile(r"#([0-9a-fA-F]{6})\b")
|
||||
HEX3 = re.compile(r"#([0-9a-fA-F]{3})\b(?![0-9a-fA-F])")
|
||||
RGB = re.compile(r"rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*[\d.]+\s*)?\)")
|
||||
STYLE_BLOCK = re.compile(r"<style[^>]*>(.*?)</style>", re.IGNORECASE | re.DOTALL)
|
||||
|
||||
NOISE = {
|
||||
"#ffffff", "#000000", "#fff", "#000",
|
||||
"#333", "#222", "#111", "#444", "#555", "#666", "#777", "#888", "#999",
|
||||
"#aaa", "#bbb", "#ccc", "#ddd", "#eee", "#f0f0f0", "#f5f5f5", "#fafafa",
|
||||
}
|
||||
|
||||
|
||||
def _normalize(hex_str: str) -> str:
|
||||
h = hex_str.lstrip("#").lower()
|
||||
if len(h) == 3:
|
||||
h = "".join(c * 2 for c in h)
|
||||
if len(h) == 8:
|
||||
h = h[:6]
|
||||
return f"#{h}"
|
||||
|
||||
|
||||
def _rgb_to_hex(r: int, g: int, b: int) -> str:
|
||||
return f"#{r:02x}{g:02x}{b:02x}"
|
||||
|
||||
|
||||
def _hex_to_rgb(h: str) -> tuple[int, int, int]:
|
||||
h = h.lstrip("#")
|
||||
return int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)
|
||||
|
||||
|
||||
def _distance(a: str, b: str) -> float:
|
||||
ar, ag, ab = _hex_to_rgb(a)
|
||||
br, bg, bb = _hex_to_rgb(b)
|
||||
return ((ar - br) ** 2 + (ag - bg) ** 2 + (ab - bb) ** 2) ** 0.5
|
||||
|
||||
|
||||
def _is_grayscale(h: str, tol: int = 12) -> bool:
|
||||
r, g, b = _hex_to_rgb(h)
|
||||
return max(r, g, b) - min(r, g, b) < tol
|
||||
|
||||
|
||||
def _extract_hex(text: str) -> list[str]:
|
||||
out: list[str] = []
|
||||
out.extend(_normalize(m.group(0)) for m in HEX6.finditer(text))
|
||||
out.extend(_normalize(m.group(0)) for m in HEX3.finditer(text))
|
||||
for m in RGB.finditer(text):
|
||||
r, g, b = int(m.group(1)), int(m.group(2)), int(m.group(3))
|
||||
if 0 <= r <= 255 and 0 <= g <= 255 and 0 <= b <= 255:
|
||||
out.append(_rgb_to_hex(r, g, b))
|
||||
return out
|
||||
|
||||
|
||||
def _cluster(colors: Counter, threshold: float = 25.0) -> list[tuple[str, int]]:
|
||||
ranked = colors.most_common()
|
||||
clusters: list[tuple[str, int]] = []
|
||||
for color, count in ranked:
|
||||
merged = False
|
||||
for i, (rep, rep_count) in enumerate(clusters):
|
||||
if _distance(color, rep) < threshold:
|
||||
clusters[i] = (rep, rep_count + count)
|
||||
merged = True
|
||||
break
|
||||
if not merged:
|
||||
clusters.append((color, count))
|
||||
return clusters
|
||||
|
||||
|
||||
def extract_brand_colors_from_text(html: str, css_texts: list[str], source_url: str = "") -> dict:
|
||||
"""HTML + CSS 텍스트에서 hex 빈도 분석 → primary/accent/text + palette. (fetch 없음)"""
|
||||
all_text_chunks: list[str] = list(STYLE_BLOCK.findall(html))
|
||||
all_text_chunks.append(html)
|
||||
all_text_chunks.extend(css_texts)
|
||||
|
||||
counter: Counter = Counter()
|
||||
for text in all_text_chunks:
|
||||
for color in _extract_hex(text):
|
||||
if color in NOISE:
|
||||
continue
|
||||
counter[color] += 1
|
||||
|
||||
if not counter:
|
||||
logger.info("[brand_parser] no colors extracted from %s", source_url)
|
||||
return {}
|
||||
|
||||
clustered = _cluster(counter)
|
||||
chromatic = [c for c, _ in clustered if not _is_grayscale(c)]
|
||||
grayscale = [c for c, _ in clustered if _is_grayscale(c)]
|
||||
|
||||
palette_top = clustered[:8]
|
||||
palette = [{"name": f"색상 {i+1}", "hex": h, "usage": f"빈도 {n}"} for i, (h, n) in enumerate(palette_top)]
|
||||
|
||||
return {
|
||||
"brand_colors": {
|
||||
"primary": chromatic[0] if chromatic else None,
|
||||
"accent": chromatic[1] if len(chromatic) > 1 else None,
|
||||
"text": grayscale[0] if grayscale else None,
|
||||
},
|
||||
"color_palette": palette,
|
||||
"extracted_from": "html+css",
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
"""report 단계 - Gemini Vision 으로 로고 묘사 + 채널 로고 매칭."""
|
||||
import logging
|
||||
import os
|
||||
from urllib.parse import urlparse
|
||||
from common.db.source import (
|
||||
select_run_raw_data, update_raw_info_merge,
|
||||
select_branding_info_id, select_mainpage_logo_url,
|
||||
)
|
||||
from common.utils import _run_optional_step
|
||||
from integrations.llm.gemini_vision import VisionClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def _describe_logo(analysis_run_id: str, info_id: int, vc: VisionClient) -> None:
|
||||
"""공식 로고 정성 묘사. branding raw_info["brandAssets"] 머지.
|
||||
호출 우선순위: raw_info.logo_url 컬럼 (HTML parser canonical) → firecrawl 메타 fallback."""
|
||||
raw = await select_run_raw_data(analysis_run_id)
|
||||
mainpage = raw.get("mainpage") or {}
|
||||
homepage_url = mainpage.get("sourceUrl") or ""
|
||||
branding_meta = mainpage.get("branding") or {}
|
||||
column_logo = await select_mainpage_logo_url(analysis_run_id)
|
||||
candidates = [u for u in [
|
||||
column_logo,
|
||||
branding_meta.get("logoUrl"),
|
||||
branding_meta.get("faviconUrl"),
|
||||
] if u]
|
||||
if homepage_url:
|
||||
parsed = urlparse(homepage_url)
|
||||
if parsed.scheme and parsed.netloc:
|
||||
candidates.append(f"{parsed.scheme}://{parsed.netloc}/favicon.ico")
|
||||
if not candidates:
|
||||
logger.info("[brand_logo] skip — no candidates")
|
||||
return
|
||||
logger.info("[brand_logo] start run=%s candidates=%d", analysis_run_id, len(candidates))
|
||||
result: dict = {}
|
||||
for cand in candidates:
|
||||
result = await vc.analyze_brand_assets(logo_url=cand, homepage_url=homepage_url)
|
||||
if result:
|
||||
break
|
||||
if result:
|
||||
await update_raw_info_merge(info_id, {"brandAssets": result})
|
||||
logger.info("[brand_logo] done keys=%s", list(result.keys()) if result else None)
|
||||
|
||||
|
||||
async def _describe_channel_logos(analysis_run_id: str, info_id: int, vc: VisionClient) -> None:
|
||||
"""채널 프로필 로고를 공식 로고와 비교. branding raw_info["channelLogos"] 머지."""
|
||||
raw = await select_run_raw_data(analysis_run_id)
|
||||
official = await select_mainpage_logo_url(analysis_run_id)
|
||||
_label = {
|
||||
"instagram": "Instagram",
|
||||
"facebook": "Facebook",
|
||||
"youtube": "YouTube",
|
||||
"instagram_en": "Instagram EN",
|
||||
"facebook_en": "Facebook EN",
|
||||
"tiktok": "TikTok",
|
||||
}
|
||||
logos = [{"channel": label, "url": img}
|
||||
for key, label in _label.items()
|
||||
if (img := (raw.get(key) or {}).get("_logo_url"))]
|
||||
if not logos:
|
||||
logger.info("[channel_logos] skip — no channel profileImages")
|
||||
return
|
||||
logger.info("[channel_logos] start run=%s channels=%s official=%s",
|
||||
analysis_run_id, [l["channel"] for l in logos], bool(official))
|
||||
result = await vc.describe_channel_logos(official, logos)
|
||||
if result:
|
||||
await update_raw_info_merge(info_id, {"channelLogos": result})
|
||||
logger.info("[channel_logos] done keys=%s", list(result.keys()) if result else None)
|
||||
|
||||
|
||||
async def analyze_branding(analysis_run_id: str) -> None:
|
||||
"""report build 직전 호출 — 로고 묘사 + 채널 로고 매칭 (Gemini). 둘 다 격리."""
|
||||
api_key = os.getenv("GEMINI_API_KEY")
|
||||
if not api_key:
|
||||
logger.info("[branding] skip — GEMINI_API_KEY 없음")
|
||||
return
|
||||
branding_info_id = await select_branding_info_id(analysis_run_id)
|
||||
if branding_info_id is None:
|
||||
logger.info("[branding] skip — branding source 없음 run=%s", analysis_run_id)
|
||||
return
|
||||
vc = VisionClient(api_key)
|
||||
logger.info("[branding] start run=%s", analysis_run_id)
|
||||
await _run_optional_step(_describe_logo(analysis_run_id, branding_info_id, vc), "brand_logo")
|
||||
await _run_optional_step(_describe_channel_logos(analysis_run_id, branding_info_id, vc), "channel_logos")
|
||||
logger.info("[branding] done run=%s", analysis_run_id)
|
||||
+93
-4
@@ -2,16 +2,27 @@ import asyncio
|
||||
import logging
|
||||
from common.db.hospital import update_hospital_status, update_hospital
|
||||
from common.db.source import select_run_sources, update_raw_info_status, update_raw_info
|
||||
from common.utils import get_env
|
||||
from common.utils import get_env, _run_optional_step
|
||||
from integrations.apify import ApifyClient
|
||||
from integrations.naver import NaverClient
|
||||
from integrations.youtube import YouTubeClient
|
||||
from integrations.firecrawl import FirecrawlClient
|
||||
from models.status import SourceType
|
||||
from integrations.site_fetcher import fetch_html_and_css
|
||||
from services.brand_parser import find_logo_url_in_html, extract_brand_colors_from_text
|
||||
from common.db.source import update_raw_info_merge, update_raw_info_logo_url, select_run_raw_data
|
||||
from common.db.base import fetchone
|
||||
from services.facebook_audit import transform_for_storage as transform_facebook
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def _save_with_logo(info_id: int, data: dict) -> None:
|
||||
await update_raw_info(info_id, data)
|
||||
if data.get("profileImage"):
|
||||
await update_raw_info_logo_url(info_id, data["profileImage"])
|
||||
|
||||
|
||||
async def collect_instagram(analysis_run_id: str, info_id: int, url: str) -> None:
|
||||
logger.info("[instagram] start run=%s url=%s", analysis_run_id, url)
|
||||
await update_raw_info_status(info_id, "processing")
|
||||
@@ -20,7 +31,7 @@ async def collect_instagram(analysis_run_id: str, info_id: int, url: str) -> Non
|
||||
await update_raw_info_status(info_id, "failed")
|
||||
logger.warning("[instagram] failed run=%s", analysis_run_id)
|
||||
return
|
||||
await update_raw_info(info_id, data)
|
||||
await _save_with_logo(info_id, data)
|
||||
logger.info("[instagram] done run=%s", analysis_run_id)
|
||||
|
||||
|
||||
@@ -32,7 +43,8 @@ async def collect_facebook(analysis_run_id: str, info_id: int, url: str) -> None
|
||||
await update_raw_info_status(info_id, "failed")
|
||||
logger.warning("[facebook] failed run=%s", analysis_run_id)
|
||||
return
|
||||
await update_raw_info(info_id, data)
|
||||
data = transform_facebook(data)
|
||||
await _save_with_logo(info_id, data)
|
||||
logger.info("[facebook] done run=%s", analysis_run_id)
|
||||
|
||||
|
||||
@@ -56,7 +68,7 @@ async def collect_youtube(analysis_run_id: str, info_id: int, url: str) -> None:
|
||||
await update_raw_info_status(info_id, "failed")
|
||||
logger.warning("[youtube] failed run=%s", analysis_run_id)
|
||||
return
|
||||
await update_raw_info(info_id, data)
|
||||
await _save_with_logo(info_id, data)
|
||||
logger.info("[youtube] done run=%s", analysis_run_id)
|
||||
|
||||
|
||||
@@ -81,30 +93,107 @@ async def collect_mainpage(analysis_run_id: str, info_id: int, hospital_id: str,
|
||||
await update_raw_info_status(info_id, "failed")
|
||||
logger.warning("[mainpage] failed run=%s", analysis_run_id)
|
||||
return
|
||||
# 홈페이지 URL 자체도 raw_data 에 박아둬야 brand_assets / 분석 단계에서 mainpage URL 재조회 없이 사용 가능.
|
||||
data = {**data, "sourceUrl": url}
|
||||
await update_raw_info(info_id, data)
|
||||
await update_hospital(hospital_id, data, analysis_run_id=analysis_run_id)
|
||||
logger.info("[mainpage] done run=%s", analysis_run_id)
|
||||
|
||||
|
||||
async def collect_tiktok(analysis_run_id: str, info_id: int, url: str) -> None:
|
||||
logger.info("[tiktok] start run=%s url=%s", analysis_run_id, url)
|
||||
await update_raw_info_status(info_id, "processing")
|
||||
data = await ApifyClient(get_env("APIFY_API_TOKEN")).get_tiktok_profile(url)
|
||||
if data is None:
|
||||
await update_raw_info_status(info_id, "failed")
|
||||
logger.warning("[tiktok] failed run=%s", analysis_run_id)
|
||||
return
|
||||
await _save_with_logo(info_id, data)
|
||||
logger.info("[tiktok] done run=%s", analysis_run_id)
|
||||
|
||||
|
||||
async def collect_naver_cafe(analysis_run_id: str, info_id: int, url: str) -> None:
|
||||
"""카페는 로그인 필요라 본문 못 봄. URL 활성·cafeId·이름 언급수만 신호로 수집."""
|
||||
logger.info("[naver_cafe] start run=%s url=%s", analysis_run_id, url)
|
||||
await update_raw_info_status(info_id, "processing")
|
||||
data = await NaverClient(get_env("NAVER_CLIENT_ID"), get_env("NAVER_CLIENT_SECRET")).get_cafe_info(url)
|
||||
if data is None:
|
||||
await update_raw_info_status(info_id, "failed")
|
||||
logger.warning("[naver_cafe] failed run=%s", analysis_run_id)
|
||||
return
|
||||
await update_raw_info(info_id, data)
|
||||
logger.info("[naver_cafe] done run=%s", analysis_run_id)
|
||||
|
||||
|
||||
async def collect_kakaotalk(analysis_run_id: str, info_id: int, url: str) -> None:
|
||||
"""카카오톡은 수집 X — URL 보관만. LLM이 채널 존재 신호로만 사용."""
|
||||
logger.info("[kakaotalk] url-only run=%s url=%s", analysis_run_id, url)
|
||||
await update_raw_info(info_id, {"url": url})
|
||||
|
||||
|
||||
async def collect_brand_basics(analysis_run_id: str, info_id: int) -> None:
|
||||
logger.info("[brand_basics] start run=%s info=%s", analysis_run_id, info_id)
|
||||
raw = await select_run_raw_data(analysis_run_id)
|
||||
mainpage = raw.get("mainpage") or {}
|
||||
homepage_url = mainpage.get("sourceUrl") or ""
|
||||
branding_meta = mainpage.get("branding") or {}
|
||||
|
||||
html, css_texts = await fetch_html_and_css(homepage_url) if homepage_url else ("", [])
|
||||
html_logo_url = find_logo_url_in_html(html, homepage_url, css_texts) if html else None
|
||||
css_colors = extract_brand_colors_from_text(html, css_texts, homepage_url) if html else {}
|
||||
|
||||
logo_url = html_logo_url or branding_meta.get("logoUrl") or branding_meta.get("ogImage")
|
||||
if logo_url:
|
||||
mainpage_row = await fetchone(
|
||||
"SELECT ri.info_id FROM raw_info ri JOIN remote_source rs USING (source_id)"
|
||||
" WHERE ri.analysis_run_id = %s AND rs.source_type = 'mainpage' LIMIT 1",
|
||||
(analysis_run_id,),
|
||||
)
|
||||
if mainpage_row:
|
||||
await update_raw_info_logo_url(mainpage_row["info_id"], logo_url)
|
||||
|
||||
payload: dict = {}
|
||||
if css_colors:
|
||||
if css_colors.get("brand_colors"): payload["brand_colors"] = css_colors["brand_colors"]
|
||||
if css_colors.get("color_palette"): payload["color_palette"] = css_colors["color_palette"]
|
||||
payload["color_source"] = "html+css"
|
||||
if payload:
|
||||
await update_raw_info_merge(info_id, {"brandAssets": payload})
|
||||
logger.info("[brand_basics] done logo_url=%s colors=%s", bool(logo_url), bool(payload))
|
||||
|
||||
|
||||
async def collect_all(analysis_run_id: str, hospital_id: str) -> None:
|
||||
rows = await select_run_sources(analysis_run_id)
|
||||
|
||||
# source_type → collector. KR/EN 구분은 collector 입장에서 동일, language 컬럼만 다름.
|
||||
_collectors = {
|
||||
SourceType.INSTAGRAM: collect_instagram,
|
||||
SourceType.FACEBOOK: collect_facebook,
|
||||
SourceType.NAVER_BLOG: collect_naver_blog,
|
||||
SourceType.YOUTUBE: collect_youtube,
|
||||
SourceType.GANGNAM_UNNI: collect_gangnam_unni,
|
||||
SourceType.TIKTOK: collect_tiktok,
|
||||
SourceType.NAVER_CAFE: collect_naver_cafe,
|
||||
SourceType.KAKAOTALK: collect_kakaotalk,
|
||||
}
|
||||
|
||||
tasks = []
|
||||
branding_info_id: int | None = None
|
||||
for row in rows:
|
||||
info_id = row["info_id"]
|
||||
source_type = row["source_type"]
|
||||
url = row["url"]
|
||||
if source_type == SourceType.BRANDING:
|
||||
branding_info_id = info_id # mainpage·채널 수집 끝난 뒤 2단계에서 사용
|
||||
continue
|
||||
if source_type == SourceType.MAINPAGE:
|
||||
tasks.append(collect_mainpage(analysis_run_id, info_id, hospital_id, url))
|
||||
elif source_type in _collectors:
|
||||
tasks.append(_collectors[source_type](analysis_run_id, info_id, url))
|
||||
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
|
||||
# 2단계: branding (brandAssets → channelLogos 한 raw_info 안에 머지). mainpage·채널 raw_data 의존이라 순차.
|
||||
# 부가 기능이라 실패해도 리포트는 나와야 하므로 _run_optional_step 으로 격리.
|
||||
if branding_info_id is not None:
|
||||
await _run_optional_step(collect_brand_basics(analysis_run_id, branding_info_id), "brand_basics")
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Facebook audit 페이지(KR·EN)를 수집 데이터로 구성.
|
||||
수치 지표(최근 게시일·게시 빈도·참여율)는 **수집 시점에** 결정적으로 산출해 DB에 박는다 (transform_for_storage).
|
||||
콘텐츠 주제(top_content_type)는 캡션 본문 이해가 필요해 LLM이 채운다 (리포트 프롬프트 지시)."""
|
||||
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from common.utils import parse_ts
|
||||
from integrations.llm.llm_service import LLMService
|
||||
from integrations.llm.prompt import facebook_diagnosis_prompt
|
||||
from integrations.llm.schemas.report import FacebookAudit, DiagnosisItem
|
||||
|
||||
|
||||
def _humanize_age(days: int) -> str:
|
||||
days = max(days, 0)
|
||||
if days == 0: return "오늘"
|
||||
if days < 7: return f"{days}일 전"
|
||||
if days < 30: return f"{days // 7}주 전"
|
||||
if days < 365: return f"{days // 30}개월 전"
|
||||
return f"{days // 365}년 전"
|
||||
|
||||
|
||||
def _frequency_label(avg_gap_days: float) -> str:
|
||||
"""게시물 사이 평균 간격(일) → 빈도 라벨."""
|
||||
if avg_gap_days <= 1.5: return "거의 매일"
|
||||
if avg_gap_days <= 10: return f"주 {7 / avg_gap_days:.1f}회"
|
||||
if avg_gap_days <= 45: return f"월 {30 / avg_gap_days:.1f}회"
|
||||
return "비정기 (분기 이상 간격)"
|
||||
|
||||
|
||||
def _engagement_text(posts: list[dict]) -> str:
|
||||
"""게시물당 좋아요/반응/공유/조회를 min~max 범위로. 전부 0인 지표는 제외.
|
||||
댓글은 posts actor가 안 줘서 '댓글 거의 없음' 고정 부가 (FB 페이지는 댓글 희박이 일반적)."""
|
||||
def _rng(vals: list[int], label: str, unit: str) -> str | None:
|
||||
lo, hi = min(vals), max(vals)
|
||||
if hi == 0:
|
||||
return None
|
||||
return f"{label} {lo}{unit}" if lo == hi else f"{label} {lo}~{hi}{unit}"
|
||||
|
||||
parts = [
|
||||
_rng([p.get("likes", 0) for p in posts], "좋아요", "개"),
|
||||
_rng([p.get("reactions", 0) for p in posts], "반응", "개"),
|
||||
_rng([p.get("shares", 0) for p in posts], "공유", "개"),
|
||||
]
|
||||
vid_views = [p.get("views", 0) for p in posts if p.get("isVideo")]
|
||||
if vid_views:
|
||||
parts.append(_rng(vid_views, "영상 조회", "회"))
|
||||
parts = [x for x in parts if x]
|
||||
if not parts:
|
||||
return "게시물당 참여 거의 없음"
|
||||
return "게시물당 " + " · ".join(parts) + " · 댓글 거의 없음"
|
||||
|
||||
|
||||
def transform_for_storage(fb: dict | None) -> dict | None:
|
||||
"""apify 원본 → DB에 저장할 최종 형태.
|
||||
- 수치 지표(recent_post_age·post_frequency·engagement)를 그 자리에서 계산해 박음.
|
||||
- 게시물은 캡션·타입만 남김 (raw 숫자/timestamp는 어차피 재계산 안 하므로 버림).
|
||||
수집 시점에 한 번 계산 → 리포트 생성 때는 그대로 갖다 박기만 함."""
|
||||
if not isinstance(fb, dict):
|
||||
return fb
|
||||
posts = fb.get("latestPosts") or []
|
||||
out = {k: v for k, v in fb.items() if k != "latestPosts"}
|
||||
if posts:
|
||||
dts = sorted((d for d in (parse_ts(p.get("timestamp")) for p in posts) if d), reverse=True)
|
||||
if dts:
|
||||
out["recent_post_age"] = _humanize_age((datetime.now(timezone.utc) - dts[0]).days)
|
||||
if len(dts) > 1:
|
||||
avg_gap = ((dts[0] - dts[-1]).days or 1) / (len(dts) - 1)
|
||||
out["post_frequency"] = _frequency_label(avg_gap)
|
||||
out["engagement"] = _engagement_text(posts)
|
||||
out["latestPosts"] = [
|
||||
{"caption": (p.get("text") or "")[:160],
|
||||
"type": "video" if p.get("isVideo") else "image"}
|
||||
for p in posts
|
||||
]
|
||||
else:
|
||||
out["latestPosts"] = []
|
||||
return out
|
||||
|
||||
def _logo_data(channel_logos: dict, channel: str) -> dict:
|
||||
"""channelLogos(비전 결과)에서 해당 채널 가져온다."""
|
||||
for c in (channel_logos or {}).get("channel_logos", []):
|
||||
if c.get("channel") == channel:
|
||||
return c
|
||||
return {}
|
||||
|
||||
def _page_patch(item: dict, channel_logos) -> dict:
|
||||
p: dict = {}
|
||||
fb = item["raw_data"]
|
||||
language = item.get("language") if item.get("language") else "KR"
|
||||
label = "페이스북 " + language
|
||||
channel = "Facebook"
|
||||
if language != "KR":
|
||||
channel = channel + " " + language
|
||||
logo_data = _logo_data(channel_logos, channel)
|
||||
|
||||
if fb.get("pageUrl"): p["url"] = 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"]
|
||||
if fb.get("reviews") is not None: p["reviews"] = fb["reviews"]
|
||||
if fb.get("following") is not None: p["following"] = fb["following"]
|
||||
for key in ("recent_post_age", "post_frequency", "engagement"):
|
||||
if fb.get(key): p[key] = fb[key]
|
||||
if p:
|
||||
p["language"] = item["language"]
|
||||
p["label"] = label
|
||||
p["logo"] = "로고 일치 (공식 로고)" if logo_data["is_official"] else "로고 불일치 (비공식 변형)"
|
||||
p["logo_description"] = logo_data["logo_description"]
|
||||
return p
|
||||
|
||||
|
||||
async def build_facebook_audit(facebook: list[dict], brand_patch: list[dict], channel_logos) -> dict:
|
||||
pages = [_page_patch(item, channel_logos) for item in facebook]
|
||||
diagnosis_result = await LLMService(provider="perplexity").generate(
|
||||
facebook_diagnosis_prompt,
|
||||
{"pages": json.dumps(pages, ensure_ascii=False)},
|
||||
)
|
||||
return FacebookAudit.model_validate({
|
||||
"pages": pages,
|
||||
"diagnosis": [DiagnosisItem.model_validate(item).model_dump() for item in diagnosis_result.diagnosis],
|
||||
"brand_inconsistencies": brand_patch,
|
||||
}).model_dump()
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Instagram audit 계정(KR·EN)을 수집 데이터로 구성.
|
||||
fix 값(handle/followers/highlights/content_format 등)은 전부 코드에서 박는다 — LLM 출력 무시."""
|
||||
|
||||
import json
|
||||
from integrations.llm.llm_service import LLMService
|
||||
from integrations.llm.prompt import instagram_diagnosis_prompt
|
||||
from integrations.llm.schemas.report import InstagramAudit, DiagnosisItem
|
||||
|
||||
_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(item: dict, channel_logos: dict) -> dict:
|
||||
"""스크래퍼 수집값으로 InstagramAccount 전 필드를 구성."""
|
||||
language = item.get("language") if item.get("language") else "KR"
|
||||
label = "인스타그램 " + language
|
||||
channel = "Instagram"
|
||||
if language != "KR":
|
||||
channel = channel + " " + language
|
||||
|
||||
data = item.get("raw_data")
|
||||
|
||||
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", ""),
|
||||
}
|
||||
|
||||
|
||||
async def build_instagram_audit(instagram: list[dict], channel_logos: dict) -> dict:
|
||||
"""KR·EN 인스타 계정 리스트 구성 (username 있는 것만)."""
|
||||
accounts = [_account(item, channel_logos) for item in instagram if item.get("raw_data").get("username")]
|
||||
diagnosis_result = await LLMService(provider="perplexity").generate(
|
||||
instagram_diagnosis_prompt,
|
||||
{"accounts": json.dumps(accounts, ensure_ascii=False)},
|
||||
)
|
||||
return InstagramAudit.model_validate({
|
||||
"accounts": accounts,
|
||||
"diagnosis": [DiagnosisItem.model_validate(item).model_dump() for item in diagnosis_result.diagnosis],
|
||||
}).model_dump()
|
||||
@@ -0,0 +1,99 @@
|
||||
"""mockup 7개 역분석 — 채널 규모별 3개월/12개월 target 성장률 공식."""
|
||||
|
||||
from integrations.llm.schemas.report import KPIMetric
|
||||
|
||||
|
||||
def _round_clean(n: int) -> int:
|
||||
if n < 100: return n
|
||||
if n < 1000: return round(n / 100) * 100
|
||||
if n < 10_000: return round(n / 500) * 500
|
||||
if n < 100_000: return round(n / 1000) * 1000
|
||||
if n < 1_000_000: return round(n / 5000) * 5000
|
||||
return round(n / 50_000) * 50_000
|
||||
|
||||
|
||||
def _target_multiplier(current: int) -> tuple[float, float]:
|
||||
if current < 1_000: return (2.5, 9.0)
|
||||
if current < 5_000: return (1.7, 4.0)
|
||||
if current < 25_000: return (1.5, 2.5)
|
||||
if current < 50_000: return (1.3, 2.2)
|
||||
return (1.1, 1.9)
|
||||
|
||||
|
||||
def _follower_kpi(metric: str, val: int | None, unit: str = "명") -> dict | None:
|
||||
if not val: return None
|
||||
m3, m12 = _target_multiplier(val)
|
||||
return {
|
||||
"metric": metric,
|
||||
"current": f"{val:,}{unit}",
|
||||
"target_3_month": f"{_round_clean(int(val * m3)):,}{unit}",
|
||||
"target_12_month": f"{_round_clean(int(val * m12)):,}{unit}",
|
||||
}
|
||||
|
||||
|
||||
def _blog_frequency(posts: list) -> tuple[str, str, str] | None:
|
||||
"""RSS posts timestamp로 (current, target_3m, target_12m) 라벨 반환. target은 절대 downgrade 안 함."""
|
||||
from common.utils import parse_ts
|
||||
dts = sorted((d for d in (parse_ts(p.get("postDate")) for p in posts) if d), reverse=True)
|
||||
if len(dts) < 2: return None
|
||||
avg_gap = (dts[0] - dts[-1]).days / (len(dts) - 1)
|
||||
if avg_gap > 90: current = f"방치 ({dts[0].strftime('%Y-%m')})"
|
||||
elif avg_gap <= 1: current = f"주 {7 // max(int(avg_gap), 1)}회"
|
||||
elif avg_gap <= 3: current = "주 2~3회"
|
||||
elif avg_gap <= 14: current = "주 1~2회"
|
||||
elif avg_gap <= 30: current = f"월 {max(30 // int(avg_gap), 1)}회"
|
||||
else: current = "월 1회 미만"
|
||||
if avg_gap > 3: return current, "주 2회", "주 3회"
|
||||
if avg_gap > 2: return current, "주 3회", "주 5회"
|
||||
if avg_gap > 1: return current, "주 5회", "주 7회"
|
||||
return current, f"{current} 유지", f"{current} 유지"
|
||||
|
||||
|
||||
def build_kpi_dashboard(
|
||||
instagram: dict, facebook: dict, youtube: dict, gangnam_unni: dict, hospital: dict,
|
||||
naver_blog: dict | None = None,
|
||||
) -> list[dict]:
|
||||
tiktok = hospital.get("tiktok") or {}
|
||||
cafe = hospital.get("naverCafe") or {}
|
||||
# print("facebook", facebook)
|
||||
# print("instagram", instagram)
|
||||
|
||||
kpis: list[dict] = []
|
||||
facebook_kpis = [_follower_kpi("Facebook " + fb["language"] + " 팔로워", fb['raw_data'].get("followers") ) for fb in facebook]
|
||||
instagram_kpis = [_follower_kpi("Instagram " + ib["language"] + " 팔로워", ib['raw_data'].get("followers")) for ib in instagram]
|
||||
print("facebook_kpis", facebook_kpis)
|
||||
print("instagram_kpis", instagram_kpis)
|
||||
|
||||
kpis += facebook_kpis
|
||||
kpis += instagram_kpis
|
||||
for k in [
|
||||
_follower_kpi("YouTube 구독자", youtube.get("subscribers")),
|
||||
_follower_kpi("TikTok 팔로워", tiktok.get("followers")),
|
||||
_follower_kpi("Naver Cafe 회원 수", cafe.get("memberCount")),
|
||||
]:
|
||||
if k: kpis.append(k)
|
||||
|
||||
if naver_blog:
|
||||
freq = _blog_frequency(naver_blog.get("posts") or [])
|
||||
if freq:
|
||||
cur, t3, t12 = freq
|
||||
kpis.append({
|
||||
"metric": "네이버 블로그 포스팅 빈도",
|
||||
"current": cur,
|
||||
"target_3_month": t3,
|
||||
"target_12_month": t12,
|
||||
})
|
||||
|
||||
gu_reviews = gangnam_unni.get("totalReviews")
|
||||
if gu_reviews:
|
||||
if gu_reviews < 1000: rm3, rm12 = 2.0, 6.0
|
||||
elif gu_reviews < 5000: rm3, rm12 = 1.10, 1.50
|
||||
else: rm3, rm12 = 1.07, 1.27
|
||||
kpis.append({
|
||||
"metric": "강남언니 리뷰",
|
||||
"current": f"{gu_reviews:,}개",
|
||||
"target_3_month": f"{_round_clean(int(gu_reviews * rm3)):,}개",
|
||||
"target_12_month": f"{_round_clean(int(gu_reviews * rm12)):,}개",
|
||||
})
|
||||
print ("kpis", kpis)
|
||||
return [KPIMetric.model_validate(k).model_dump() for k in kpis]
|
||||
Reference in new issue
Block a user