Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
05e88fe70c | ||
|
|
a4fbf60d42 | ||
|
|
5ff1d68a27 | ||
|
|
c0fa48ff75 | ||
|
|
c4cbbaf7e7 | ||
|
|
4ad30d4d36 | ||
|
|
5baea01ae1 | ||
|
|
9919529a88 | ||
|
|
f949a23717 | ||
|
|
ff19db34a8 | ||
|
|
45a74ab970 | ||
|
|
2232273200 | ||
|
|
484ee41810 | ||
|
|
35e5e98524 |
No files matched your search
+13
-9
@@ -66,19 +66,23 @@ async def select_run_raw_data(analysis_run_id: str) -> dict:
|
|||||||
rows = await fetchall(
|
rows = await fetchall(
|
||||||
"SELECT rs.source_type, rs.language, ri.raw_data, ri.logo_url"
|
"SELECT rs.source_type, rs.language, ri.raw_data, ri.logo_url"
|
||||||
" FROM raw_info ri JOIN remote_source rs USING (source_id)"
|
" FROM raw_info ri JOIN remote_source rs USING (source_id)"
|
||||||
" WHERE ri.analysis_run_id = %s",
|
" WHERE ri.analysis_run_id = %s AND ri.status = 'done'",
|
||||||
(analysis_run_id,),
|
(analysis_run_id,),
|
||||||
)
|
)
|
||||||
result: dict = {}
|
result: dict = {}
|
||||||
for row in rows:
|
for row in rows:
|
||||||
raw = row["raw_data"]
|
source_type = row["source_type"]
|
||||||
key = row["source_type"]
|
if source_type not in result:
|
||||||
if (row.get("language") or "").upper() == "EN":
|
result[source_type] = list()
|
||||||
key = f"{key}_en"
|
|
||||||
data = json.loads(raw) if isinstance(raw, str) else (raw or {})
|
item : dict = {}
|
||||||
if isinstance(data, dict) and row.get("logo_url"):
|
item["raw_data"] = json.loads(row["raw_data"])
|
||||||
data["_logo_url"] = row["logo_url"]
|
item["logo_url"] = row["logo_url"]
|
||||||
result[key] = data
|
item["source_type"] = row["source_type"]
|
||||||
|
item["language"] = row["language"]
|
||||||
|
|
||||||
|
result[source_type].append(item)
|
||||||
|
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import os
|
import os
|
||||||
|
import re
|
||||||
import asyncio
|
import asyncio
|
||||||
import logging
|
import logging
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
@@ -10,6 +11,70 @@ logger = logging.getLogger(__name__)
|
|||||||
REQUEST_TIMEOUT = 60
|
REQUEST_TIMEOUT = 60
|
||||||
|
|
||||||
|
|
||||||
|
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회"
|
||||||
|
|
||||||
|
|
||||||
def parse_ts(v) -> datetime | None:
|
def parse_ts(v) -> datetime | None:
|
||||||
"""수집기마다 다른 timestamp 포맷을 통일된 datetime으로 변환.
|
"""수집기마다 다른 timestamp 포맷을 통일된 datetime으로 변환.
|
||||||
파싱 실패 시 None.
|
파싱 실패 시 None.
|
||||||
|
|||||||
@@ -74,7 +74,7 @@ class FirecrawlClient:
|
|||||||
headers=self._headers(),
|
headers=self._headers(),
|
||||||
json_body={
|
json_body={
|
||||||
"url": url,
|
"url": url,
|
||||||
"formats": ["json", "links"],
|
"formats": ["json", "links", "rawHtml"],
|
||||||
"jsonOptions": {
|
"jsonOptions": {
|
||||||
"prompt": "Extract: clinic name (Korean), clinic name (English), address, phone with dash format, business hours, slogan, services offered, doctors with name/title/specialty, brand identity (primary/accent/background/text colors in hex, heading/body fonts, logo URL from the actual header/main <img> src, og:image from <meta property='og:image'> content, favicon URL)",
|
"prompt": "Extract: clinic name (Korean), clinic name (English), address, phone with dash format, business hours, slogan, services offered, doctors with name/title/specialty, brand identity (primary/accent/background/text colors in hex, heading/body fonts, logo URL from the actual header/main <img> src, og:image from <meta property='og:image'> content, favicon URL)",
|
||||||
"schema": {
|
"schema": {
|
||||||
@@ -147,6 +147,7 @@ class FirecrawlClient:
|
|||||||
# "socialMedia": info.get("socialMedia", {}),
|
# "socialMedia": info.get("socialMedia", {}),
|
||||||
"branding": info.get("branding", {}),
|
"branding": info.get("branding", {}),
|
||||||
"siteLinks": data.get("links", []),
|
"siteLinks": data.get("links", []),
|
||||||
|
"html": data.get("rawHtml", "") or data.get("html", ""), # rawHtml = 가공 전 원본 — <script> 등 보존.
|
||||||
"sourceUrl": url,
|
"sourceUrl": url,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -219,7 +219,7 @@ class VisionClient:
|
|||||||
' "logo_symbol": "심볼이 묘사하는 대상 (예: \'잎사귀\', \'추상 곡선\'). 없으면 빈 문자열",\n'
|
' "logo_symbol": "심볼이 묘사하는 대상 (예: \'잎사귀\', \'추상 곡선\'). 없으면 빈 문자열",\n'
|
||||||
' "logo_text": "로고에 보이는 워드마크 텍스트 그대로 (한글/영문). 없으면 빈 문자열",\n'
|
' "logo_text": "로고에 보이는 워드마크 텍스트 그대로 (한글/영문). 없으면 빈 문자열",\n'
|
||||||
' "logo_colors_desc": "로고에 쓰인 색감을 사람이 부르는 이름으로 서술 (예: \'딥네이비 + 골드\')",\n'
|
' "logo_colors_desc": "로고에 쓰인 색감을 사람이 부르는 이름으로 서술 (예: \'딥네이비 + 골드\')",\n'
|
||||||
' "logo_colors_hex": ["로고에서 시각적으로 두드러진 색 정확히 5개의 hex 근사값 배열. 예: [\'#1A2B3C\', \'#D4A017\', \'#FFFFFF\', \'#9E5C2A\', \'#1F1F1F\']. 강한 색이 5개 안 되면 음영/명도 차이로 5개 채울 것. 빈 배열 금지."]\n'
|
' "logo_colors_hex": ["로고에서 시각적으로 가장 두드러진 색 최대 2개의 hex 근사값 배열. 예: [\'#1A2B3C\', \'#D4A017\']. 색이 1개면 1개만, 강한 색이 1개도 없으면 빈 배열."]\n'
|
||||||
"}\n"
|
"}\n"
|
||||||
"주의: logo_colors_hex 는 시각 추정이라 정확도 떨어질 수 있음. CSS 추출이 우선이고 이건 fallback/보완 용.\n"
|
"주의: logo_colors_hex 는 시각 추정이라 정확도 떨어질 수 있음. CSS 추출이 우선이고 이건 fallback/보완 용.\n"
|
||||||
"모든 설명/텍스트 값은 반드시 한국어로 작성하세요 (영어 금지)."
|
"모든 설명/텍스트 값은 반드시 한국어로 작성하세요 (영어 금지)."
|
||||||
@@ -229,14 +229,9 @@ class VisionClient:
|
|||||||
return {}
|
return {}
|
||||||
# logo_images는 우리가 직접 채움 (Vision은 묘사만)
|
# logo_images는 우리가 직접 채움 (Vision은 묘사만)
|
||||||
result["logo_images"] = {"circle": None, "horizontal": logo_url, "korean": None}
|
result["logo_images"] = {"circle": None, "horizontal": logo_url, "korean": None}
|
||||||
# logo_colors_hex 5개 강제 정규화 — LLM 이 4개나 6개 줄 수도 있어서 길이 fallback.
|
# logo_colors_hex 최대 2개로 제한.
|
||||||
hex_list = [h for h in (result.get("logo_colors_hex") or []) if isinstance(h, str) and h.startswith("#")]
|
hex_list = [h for h in (result.get("logo_colors_hex") or []) if isinstance(h, str) and h.startswith("#")]
|
||||||
if hex_list:
|
result["logo_colors_hex"] = hex_list[:2]
|
||||||
while len(hex_list) < 5:
|
|
||||||
hex_list.append(hex_list[-1]) # 마지막 색 복제로 패딩
|
|
||||||
result["logo_colors_hex"] = hex_list[:5]
|
|
||||||
else:
|
|
||||||
result["logo_colors_hex"] = []
|
|
||||||
return result
|
return result
|
||||||
|
|
||||||
async def describe_channel_logos(
|
async def describe_channel_logos(
|
||||||
|
|||||||
@@ -1,7 +1,18 @@
|
|||||||
import os
|
import os
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
from common.utils import get_env
|
from common.utils import get_env
|
||||||
from integrations.llm.schemas.report import ReportInput, ReportOutput, YouTubeDiagnosisInput, YouTubeDiagnosisOutput
|
from integrations.llm.schemas.report import (
|
||||||
|
ReportInput, ReportOutput,
|
||||||
|
CriticalIssuesInput, CriticalIssuesOutput,
|
||||||
|
YouTubeDiagnosisInput, YouTubeDiagnosisOutput,
|
||||||
|
InstagramDiagnosisInput, InstagramDiagnosisOutput,
|
||||||
|
FacebookDiagnosisInput, FacebookDiagnosisOutput,
|
||||||
|
BrandConsistencyInput, BrandConsistencyOutput,
|
||||||
|
TransformationInput, TransformationProposal,
|
||||||
|
RoadmapInput, RoadmapOutput,
|
||||||
|
ScoresInput, ScoresOutput,
|
||||||
|
OtherChannelsInput, OtherChannelsOutput
|
||||||
|
)
|
||||||
from integrations.llm.schemas.plan import PlanInput, PlanOutput
|
from integrations.llm.schemas.plan import PlanInput, PlanOutput
|
||||||
from integrations.llm.schemas.market import (
|
from integrations.llm.schemas.market import (
|
||||||
MarketCompetitorsInput, MarketCompetitorsOutput,
|
MarketCompetitorsInput, MarketCompetitorsOutput,
|
||||||
@@ -81,9 +92,65 @@ market_target_audience_prompt = Prompt(
|
|||||||
output_class=MarketTargetAudienceOutput,
|
output_class=MarketTargetAudienceOutput,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
facebook_diagnosis_prompt = Prompt(
|
||||||
|
file_name="facebook_diagnosis_prompt.txt",
|
||||||
|
prompt_model="REPORT_MODEL",
|
||||||
|
input_class=FacebookDiagnosisInput,
|
||||||
|
output_class=FacebookDiagnosisOutput,
|
||||||
|
)
|
||||||
|
|
||||||
|
instagram_diagnosis_prompt = Prompt(
|
||||||
|
file_name="instagram_diagnosis_prompt.txt",
|
||||||
|
prompt_model="REPORT_MODEL",
|
||||||
|
input_class=InstagramDiagnosisInput,
|
||||||
|
output_class=InstagramDiagnosisOutput,
|
||||||
|
)
|
||||||
|
|
||||||
youtube_diagnosis_prompt = Prompt(
|
youtube_diagnosis_prompt = Prompt(
|
||||||
file_name="youtube_diagnosis_prompt.txt",
|
file_name="youtube_diagnosis_prompt.txt",
|
||||||
prompt_model="REPORT_MODEL",
|
prompt_model="REPORT_MODEL",
|
||||||
input_class=YouTubeDiagnosisInput,
|
input_class=YouTubeDiagnosisInput,
|
||||||
output_class=YouTubeDiagnosisOutput,
|
output_class=YouTubeDiagnosisOutput,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
brand_consistency_prompt = Prompt(
|
||||||
|
file_name="brand_consistency_prompt.txt",
|
||||||
|
prompt_model="REPORT_MODEL",
|
||||||
|
input_class=BrandConsistencyInput,
|
||||||
|
output_class=BrandConsistencyOutput,
|
||||||
|
)
|
||||||
|
|
||||||
|
critical_issues_prompt = Prompt(
|
||||||
|
file_name="critical_issues_prompt.txt",
|
||||||
|
prompt_model="REPORT_MODEL",
|
||||||
|
input_class=CriticalIssuesInput,
|
||||||
|
output_class=CriticalIssuesOutput,
|
||||||
|
)
|
||||||
|
|
||||||
|
transformation_prompt = Prompt(
|
||||||
|
file_name="transformation_prompt.txt",
|
||||||
|
prompt_model="REPORT_MODEL",
|
||||||
|
input_class=TransformationInput,
|
||||||
|
output_class=TransformationProposal,
|
||||||
|
)
|
||||||
|
|
||||||
|
scores_prompt = Prompt(
|
||||||
|
file_name="scores_prompt.txt",
|
||||||
|
prompt_model="REPORT_MODEL",
|
||||||
|
input_class=ScoresInput,
|
||||||
|
output_class=ScoresOutput,
|
||||||
|
)
|
||||||
|
|
||||||
|
roadmap_prompt = Prompt(
|
||||||
|
file_name="roadmap_prompt.txt",
|
||||||
|
prompt_model="REPORT_MODEL",
|
||||||
|
input_class=RoadmapInput,
|
||||||
|
output_class=RoadmapOutput,
|
||||||
|
)
|
||||||
|
|
||||||
|
other_channels_prompt = Prompt(
|
||||||
|
file_name="other_channels_prompt.txt",
|
||||||
|
prompt_model="REPORT_MODEL",
|
||||||
|
input_class=OtherChannelsInput,
|
||||||
|
output_class=OtherChannelsOutput,
|
||||||
|
)
|
||||||
@@ -16,8 +16,8 @@ class PlanInput(BaseModel):
|
|||||||
market_trend: str | None = None
|
market_trend: str | None = None
|
||||||
market_target_audience: str | None = None
|
market_target_audience: str | None = None
|
||||||
tiktok: str | None = None
|
tiktok: str | None = None
|
||||||
instagram_en: str | None = None
|
instagram: str | None = None
|
||||||
facebook_en: str | None = None
|
facebook: str | None = None
|
||||||
naver_blog: str | None = None
|
naver_blog: str | None = None
|
||||||
naver_cafe: str | None = None
|
naver_cafe: str | None = None
|
||||||
kakao_talk: str | None = None
|
kakao_talk: str | None = None
|
||||||
|
|||||||
@@ -68,17 +68,15 @@ class RegistryData(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class ClinicSnapshot(BaseModel):
|
class ClinicSnapshot(BaseModel):
|
||||||
# _build_clinic_snapshot은 source 데이터 있을 때만 채움 (`if x:` 가드).
|
name: str
|
||||||
# required면 강남언니/홈페이지 누락 병원에서 ValidationError로 리포트 실패.
|
name_en: str
|
||||||
name: str | None = None
|
|
||||||
name_en: str | None = None
|
|
||||||
staff_count: int | None = None
|
staff_count: int | None = None
|
||||||
lead_doctor: LeadDoctor | None = None
|
lead_doctor: LeadDoctor | None = None
|
||||||
overall_rating: float | None = None
|
overall_rating: float | None = None
|
||||||
total_reviews: int | None = None
|
total_reviews: int | None = None
|
||||||
certifications: list[str] = []
|
certifications: list[str] = []
|
||||||
location: str | None = None
|
location: str
|
||||||
phone: str | None = None
|
phone: str
|
||||||
domain: str | None = None
|
domain: str | None = None
|
||||||
logo_images: LogoImages | None = None
|
logo_images: LogoImages | None = None
|
||||||
brand_colors: BrandColors | None = None
|
brand_colors: BrandColors | None = None
|
||||||
@@ -136,7 +134,7 @@ class YouTubeAudit(BaseModel):
|
|||||||
channel_description: str
|
channel_description: str
|
||||||
linked_urls: list[LinkedUrl]
|
linked_urls: list[LinkedUrl]
|
||||||
playlists: list[str]
|
playlists: list[str]
|
||||||
top_videos: list[TopVideo]
|
top_videos: list[TopVideo] = []
|
||||||
diagnosis: list[DiagnosisItem]
|
diagnosis: list[DiagnosisItem]
|
||||||
|
|
||||||
|
|
||||||
@@ -159,8 +157,8 @@ class InstagramAccount(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class InstagramAudit(BaseModel):
|
class InstagramAudit(BaseModel):
|
||||||
accounts: list[InstagramAccount] = []
|
accounts: list[InstagramAccount]
|
||||||
diagnosis: list[DiagnosisItem] = []
|
diagnosis: list[DiagnosisItem]
|
||||||
|
|
||||||
|
|
||||||
# --- Facebook ---
|
# --- Facebook ---
|
||||||
@@ -186,11 +184,11 @@ class FacebookPage(BaseModel):
|
|||||||
followers: int
|
followers: int
|
||||||
following: int
|
following: int
|
||||||
category: str
|
category: str
|
||||||
bio: str
|
bio: str = ""
|
||||||
logo: str
|
logo: str
|
||||||
logo_description: str
|
logo_description: str
|
||||||
link: str
|
link: str
|
||||||
linked_domain: str
|
linked_domain: str = ""
|
||||||
reviews: int
|
reviews: int
|
||||||
recent_post_age: str
|
recent_post_age: str
|
||||||
has_whatsapp: bool | None = None
|
has_whatsapp: bool | None = None
|
||||||
@@ -215,6 +213,19 @@ class OtherChannel(BaseModel):
|
|||||||
url: str | None = None
|
url: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class OtherChannelsInput(BaseModel):
|
||||||
|
clinic_name: str
|
||||||
|
tiktok: str | None = None
|
||||||
|
kakao_talk: str | None = None
|
||||||
|
naver_cafe: str | None = None
|
||||||
|
naver_blog: str | None = None
|
||||||
|
gangnam_unni: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class OtherChannelsOutput(BaseModel):
|
||||||
|
other_channels: list[OtherChannel]
|
||||||
|
|
||||||
|
|
||||||
class TrackingPixel(BaseModel):
|
class TrackingPixel(BaseModel):
|
||||||
name: str
|
name: str
|
||||||
installed: bool
|
installed: bool
|
||||||
@@ -234,7 +245,7 @@ class AdditionalDomain(BaseModel):
|
|||||||
|
|
||||||
class WebsiteAudit(BaseModel):
|
class WebsiteAudit(BaseModel):
|
||||||
primary_domain: str
|
primary_domain: str
|
||||||
additional_domains: list[AdditionalDomain]
|
additional_domains: list[AdditionalDomain] = []
|
||||||
sns_links_on_site: bool
|
sns_links_on_site: bool
|
||||||
sns_links_detail: list[SnsLink] | None = None
|
sns_links_detail: list[SnsLink] | None = None
|
||||||
tracking_pixels: list[TrackingPixel]
|
tracking_pixels: list[TrackingPixel]
|
||||||
@@ -340,7 +351,7 @@ class MarketingReport(BaseModel):
|
|||||||
facebook_audit: FacebookAudit
|
facebook_audit: FacebookAudit
|
||||||
other_channels: list[OtherChannel]
|
other_channels: list[OtherChannel]
|
||||||
website_audit: WebsiteAudit
|
website_audit: WebsiteAudit
|
||||||
problem_diagnosis: list[DiagnosisItem]
|
problem_diagnosis: list[CriticalIssueItem]
|
||||||
transformation: TransformationProposal
|
transformation: TransformationProposal
|
||||||
roadmap: list[RoadmapMonth]
|
roadmap: list[RoadmapMonth]
|
||||||
kpi_dashboard: list[KPIMetric]
|
kpi_dashboard: list[KPIMetric]
|
||||||
@@ -365,3 +376,79 @@ class YouTubeDiagnosisInput(BaseModel):
|
|||||||
|
|
||||||
class YouTubeDiagnosisOutput(BaseModel):
|
class YouTubeDiagnosisOutput(BaseModel):
|
||||||
diagnosis: list[DiagnosisItem]
|
diagnosis: list[DiagnosisItem]
|
||||||
|
|
||||||
|
|
||||||
|
class InstagramDiagnosisInput(BaseModel):
|
||||||
|
accounts: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class InstagramDiagnosisOutput(BaseModel):
|
||||||
|
diagnosis: list[DiagnosisItem]
|
||||||
|
|
||||||
|
|
||||||
|
class FacebookDiagnosisInput(BaseModel):
|
||||||
|
pages: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class FacebookDiagnosisOutput(BaseModel):
|
||||||
|
diagnosis: list[DiagnosisItem]
|
||||||
|
|
||||||
|
|
||||||
|
# --- Scores ---
|
||||||
|
|
||||||
|
class ScoresInput(BaseModel):
|
||||||
|
clinic_name: str | None = None
|
||||||
|
data: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class ScoresOutput(BaseModel):
|
||||||
|
overall_score: int
|
||||||
|
channel_scores: list[ChannelScore]
|
||||||
|
|
||||||
|
|
||||||
|
# --- Diagnosis ---
|
||||||
|
|
||||||
|
class CriticalIssueItem(DiagnosisItem):
|
||||||
|
title: str
|
||||||
|
|
||||||
|
|
||||||
|
class CriticalIssuesInput(BaseModel):
|
||||||
|
clinic_name: str | None = None
|
||||||
|
data: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class CriticalIssuesOutput(BaseModel):
|
||||||
|
diagnosis: list[CriticalIssueItem]
|
||||||
|
|
||||||
|
|
||||||
|
# --- Roadmap ---
|
||||||
|
|
||||||
|
class RoadmapInput(BaseModel):
|
||||||
|
clinic_name: str | None = None
|
||||||
|
data: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class RoadmapOutput(BaseModel):
|
||||||
|
roadmap: list[RoadmapMonth]
|
||||||
|
|
||||||
|
|
||||||
|
# --- Transformation ---
|
||||||
|
|
||||||
|
class TransformationInput(BaseModel):
|
||||||
|
clinic_name: str | None = None
|
||||||
|
data: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
# --- BrandConsistency ---
|
||||||
|
|
||||||
|
class BrandConsistencyInput(BaseModel):
|
||||||
|
clinic_name: str | None = None
|
||||||
|
mainpage: str | None = None
|
||||||
|
instagram: str | None = None
|
||||||
|
facebook: str | None = None
|
||||||
|
youtube: str | None = None
|
||||||
|
gangnam_unni: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class BrandConsistencyOutput(BaseModel):
|
||||||
|
brand_inconsistencies: list[BrandInconsistency]
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
다음은 성형외과/피부과 {clinic_name} 의 채널별 브랜드 데이터입니다.
|
||||||
|
|
||||||
|
공식 홈페이지: {mainpage}
|
||||||
|
인스타그램: {instagram}
|
||||||
|
페이스북: {facebook}
|
||||||
|
유튜브: {youtube}
|
||||||
|
강남언니: {gangnam_unni}
|
||||||
|
|
||||||
|
위 채널들 간의 브랜드 불일치 항목을 분석해줘.
|
||||||
|
비교 대상 필드 예시: 병원명(한글/영문), 전화번호, 주소, 로고, 슬로건, 소개 문구 등.
|
||||||
|
|
||||||
|
각 항목은 다음 JSON 형식의 배열로 출력해줘:
|
||||||
|
- field: 불일치 필드명
|
||||||
|
- values: 채널별 실제 값 목록 (channel, value, is_correct)
|
||||||
|
- impact: 불일치가 브랜드에 미치는 영향
|
||||||
|
- recommendation: 개선 권고사항
|
||||||
|
|
||||||
|
출처 번호([1], [2] 등)는 포함하지 마.
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
다음은 성형외과/피부과 {clinic_name} 의 전 채널 수집 데이터입니다.
|
||||||
|
|
||||||
|
{data}
|
||||||
|
|
||||||
|
위 데이터를 바탕으로 이 병원의 마케팅 전반에 걸친 핵심 문제점과 개선사항을 진단해줘.
|
||||||
|
각 항목은 title(해당 문제를 대표하는 2~4단어), category(진단 카테고리), detail(상세 설명), severity(critical/warning/info) 형식의 JSON 배열로 출력해줘.
|
||||||
|
|
||||||
|
현재 주요 진단 카테고리는 3개야.
|
||||||
|
브랜드 아이덴티티 파편화
|
||||||
|
콘텐츠 전략 부재
|
||||||
|
플랫폼 간 유입 단절
|
||||||
|
|
||||||
|
출처 번호([1], [2] 등)는 포함하지 마.
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
다음은 성형외과/피부과의 페이스북 페이지 데이터입니다.
|
||||||
|
|
||||||
|
{pages}
|
||||||
|
|
||||||
|
위 데이터를 바탕으로 이 병원의 페이스북 마케팅 현황을 진단해줘.
|
||||||
|
각 항목은 category(진단 카테고리), detail(상세 설명), severity(critical/warning/info) 형식의 JSON 배열로 출력해줘.
|
||||||
|
|
||||||
|
출처 번호([1], [2] 등)는 포함하지 마.
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
다음은 성형외과/피부과의 인스타그램 계정 데이터입니다.
|
||||||
|
|
||||||
|
{accounts}
|
||||||
|
|
||||||
|
위 데이터를 바탕으로 이 병원의 인스타그램 마케팅 현황을 진단해줘.
|
||||||
|
각 항목은 category(진단 카테고리), detail(상세 설명), severity(critical/warning/info) 형식의 JSON 배열로 출력해줘.
|
||||||
|
|
||||||
|
출처 번호([1], [2] 등)는 포함하지 마.
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
당신은 의료 마케팅 분석가입니다. 아래 부가 채널 데이터를 보고 `other_channels` 리스트만 JSON 으로 생성하세요.
|
||||||
|
결과물은 한국어로 작성하세요.
|
||||||
|
|
||||||
|
## 병원
|
||||||
|
- 병원명: {clinic_name}
|
||||||
|
|
||||||
|
## 부가 채널 raw 데이터
|
||||||
|
|
||||||
|
### TikTok
|
||||||
|
{tiktok}
|
||||||
|
|
||||||
|
### KakaoTalk
|
||||||
|
{kakao_talk}
|
||||||
|
|
||||||
|
### Naver Cafe
|
||||||
|
{naver_cafe}
|
||||||
|
|
||||||
|
### Naver Blog
|
||||||
|
{naver_blog}
|
||||||
|
|
||||||
|
### Gangnam Unni
|
||||||
|
{gangnam_unni}
|
||||||
|
|
||||||
|
## 작성 지침
|
||||||
|
|
||||||
|
- 메인 audit(YouTube/Instagram KR/Facebook KR/Website)에 **포함되지 않은** 채널만 넣으세요.
|
||||||
|
- 위 채널 데이터에 **실제 값이 있는 채널만** status=active 와 실제 URL 로 일관되게 포함:
|
||||||
|
- **카카오톡·네이버 카페**: {kakao_talk} 또는 {naver_cafe} 에 url 이 있으면 each "KakaoTalk" / "Naver Cafe" 로 status=active + 해당 url 로 포함. 수집된 콘텐츠 데이터는 없으므로 URL 존재 자체가 활성 채널 신호. **둘 다 null/빈 값이면 절대 만들지 마세요.**
|
||||||
|
- **그 외 데이터 없는 채널(네이버플레이스/Threads 등)은 절대 임의로 만들지 마세요.** 데이터 없으면 그 채널은 생략 (랜덤 생성·추측 금지).
|
||||||
|
- url 은 위 raw 데이터의 **실제 URL 만** 사용. 없으면 빈 문자열.
|
||||||
|
- **URL 에 'https://www.facebook.com/' 같은 prefix 를 절대 직접 만들지 마세요.** 받은 데이터 URL = 출력 URL. 이미 'https://...' 가 붙은 URL 에 또 prefix 붙이면 깨집니다.
|
||||||
|
- `details` 는 해당 채널의 짧은 1줄 묘사 (예: "팔로워 1.2만, 주 2회 게시", "오픈채팅 상담", "환자 후기 게시판"). 데이터 없으면 빈 문자열.
|
||||||
|
|
||||||
|
## 출력 형식
|
||||||
|
|
||||||
|
```json
|
||||||
|
{{
|
||||||
|
"other_channels": [
|
||||||
|
{{"name": "Naver Blog", "status": "active", "details": "...", "url": "https://..."}},
|
||||||
|
...
|
||||||
|
]
|
||||||
|
}}
|
||||||
|
```
|
||||||
|
|
||||||
|
`status` 는 active / inactive / unknown / not_found 중 하나. 데이터·URL 모두 없으면 그 채널 자체를 생략하세요 (null 항목 만들지 말 것).
|
||||||
@@ -33,7 +33,7 @@
|
|||||||
{report}
|
{report}
|
||||||
|
|
||||||
## 추가 채널 데이터 (네이버 블로그 / 틱톡 / 인스타그램 EN / 페이스북 EN / 네이버 카페 / 카카오톡)
|
## 추가 채널 데이터 (네이버 블로그 / 틱톡 / 인스타그램 EN / 페이스북 EN / 네이버 카페 / 카카오톡)
|
||||||
아래에 데이터가 있는 채널은 channelStrategies에 **반드시 포함**하세요 (네이버 블로그, 틱톡, 영문 인스타그램, 영문 페이스북, 네이버 카페, 카카오톡). channelBranding은 SNS·블로그·카페까지만 포함(카카오톡은 메신저라 제외). null이면 제외.
|
아래에 데이터가 있는 채널은 channelStrategies에 **반드시 포함**하세요 (네이버 블로그, 틱톡, 인스타그램, 페이스북, 네이버 카페, 카카오톡). channelBranding은 SNS·블로그·카페까지만 포함(카카오톡은 메신저라 제외). null이면 제외.
|
||||||
|
|
||||||
### 네이버 블로그 (Naver Blog)
|
### 네이버 블로그 (Naver Blog)
|
||||||
{naver_blog}
|
{naver_blog}
|
||||||
@@ -41,11 +41,11 @@
|
|||||||
### 틱톡 (TikTok)
|
### 틱톡 (TikTok)
|
||||||
{tiktok}
|
{tiktok}
|
||||||
|
|
||||||
### 인스타그램 (영문 계정)
|
### 인스타그램
|
||||||
{instagram_en}
|
{instagram}
|
||||||
|
|
||||||
### 페이스북 (영문 페이지)
|
### 페이스북
|
||||||
{facebook_en}
|
{facebook}
|
||||||
|
|
||||||
### 네이버 카페 (공식 카페 운영 신호)
|
### 네이버 카페 (공식 카페 운영 신호)
|
||||||
{naver_cafe}
|
{naver_cafe}
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
다음은 성형외과/피부과 {clinic_name} 의 전 채널 수집 데이터입니다.
|
||||||
|
|
||||||
|
{data}
|
||||||
|
|
||||||
|
위 데이터를 바탕으로 이 병원의 3개월 마케팅 실행 로드맵을 수립해줘.
|
||||||
|
month 1, 2, 3 각각 하나씩, 총 3개 항목을 포함한 roadmap JSON 배열로 출력해줘.
|
||||||
|
|
||||||
|
각 항목은 아래 형식을 따라줘:
|
||||||
|
- month: 월 번호 (1, 2, 3)
|
||||||
|
- title: 해당 월의 핵심 테마 (예: "브랜드 정비")
|
||||||
|
- subtitle: 한 줄 부제 (예: "기반 구축 — 로고·계정 통일")
|
||||||
|
- tasks: 실행 과제 목록, 각 과제는 task(string)와 completed(false)로 구성
|
||||||
|
|
||||||
|
출처 번호([1], [2] 등)는 포함하지 마.
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
다음은 성형외과/피부과 {clinic_name} 의 전 채널 수집 데이터입니다.
|
||||||
|
|
||||||
|
{data}
|
||||||
|
|
||||||
|
위 데이터를 바탕으로 이 병원의 마케팅 종합 점수를 평가해줘.
|
||||||
|
|
||||||
|
1. overall_score: 전체 마케팅 종합 점수 (0~100 정수)
|
||||||
|
2. channel_scores: 채널별 점수 목록. 각 항목은 아래 형식:
|
||||||
|
- channel: 채널명 (예: YouTube, Instagram, Facebook, 웹사이트 등)
|
||||||
|
- icon: 채널 아이콘 식별자 (예: youtube, instagram, facebook, website)
|
||||||
|
- score: 해당 채널 점수 (20 ~ 100)(정수)
|
||||||
|
- max_score: 해당 채널 최대 점수 (정수)
|
||||||
|
- status: 심각도 (critical / warning / info)
|
||||||
|
- headline: 한 줄 평가 요약
|
||||||
|
|
||||||
|
출처 번호([1], [2] 등)는 포함하지 마.
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
다음은 성형외과/피부과 {clinic_name} 의 전 채널 수집 데이터입니다.
|
||||||
|
|
||||||
|
{data}
|
||||||
|
|
||||||
|
위 데이터를 바탕으로 이 병원의 마케팅 전환 전략을 수립해줘.
|
||||||
|
아래 5개 항목을 포함한 JSON을 출력해줘.
|
||||||
|
|
||||||
|
1. brand_identity: 브랜드 아이덴티티 개선 항목 (area, as_is, to_be)
|
||||||
|
2. content_strategy: 콘텐츠 전략 개선 항목 (area, as_is, to_be)
|
||||||
|
3. platform_strategies: 플랫폼별 전략 (platform, icon, current_metric, target_metric, strategies: 각 항목은 strategy와 detail 포함)
|
||||||
|
4. website_improvements: 웹사이트 개선 항목 (area, as_is, to_be)
|
||||||
|
5. new_channel_proposals: 신규 채널 제안 (channel, priority, rationale)
|
||||||
|
|
||||||
|
출처 번호([1], [2] 등)는 포함하지 마.
|
||||||
+56
-27
@@ -48,7 +48,7 @@ class YouTubeClient:
|
|||||||
resp = await http_request(
|
resp = await http_request(
|
||||||
HTTPMethod.GET,
|
HTTPMethod.GET,
|
||||||
url=f"{YT}/channels",
|
url=f"{YT}/channels",
|
||||||
params={"part": "snippet,statistics", "id": channel_id, "key": self.api_key},
|
params={"part": "snippet,statistics,contentDetails", "id": channel_id, "key": self.api_key},
|
||||||
label="yt-channel",
|
label="yt-channel",
|
||||||
)
|
)
|
||||||
if not resp or not resp.is_success:
|
if not resp or not resp.is_success:
|
||||||
@@ -58,26 +58,52 @@ class YouTubeClient:
|
|||||||
return None
|
return None
|
||||||
channel = items[0]
|
channel = items[0]
|
||||||
|
|
||||||
video_ids: list[str] = []
|
async def _video_details(video_ids: list[str]) -> list[dict]:
|
||||||
resp = await http_request(
|
"""video_ids 순서를 보존한 채 snippet/statistics/contentDetails 채워서 반환."""
|
||||||
HTTPMethod.GET,
|
if not video_ids:
|
||||||
url=f"{YT}/search",
|
return []
|
||||||
params={"part": "snippet", "channelId": channel_id, "order": "viewCount", "type": "video", "maxResults": 10, "key": self.api_key},
|
|
||||||
label="yt-search",
|
|
||||||
)
|
|
||||||
if resp and resp.is_success:
|
|
||||||
video_ids = [i["id"]["videoId"] for i in resp.json().get("items", []) if i.get("id", {}).get("videoId")]
|
|
||||||
|
|
||||||
videos: list[dict] = []
|
|
||||||
if video_ids:
|
|
||||||
resp = await http_request(
|
resp = await http_request(
|
||||||
HTTPMethod.GET,
|
HTTPMethod.GET,
|
||||||
url=f"{YT}/videos",
|
url=f"{YT}/videos",
|
||||||
params={"part": "snippet,statistics,contentDetails", "id": ",".join(video_ids), "key": self.api_key},
|
params={"part": "snippet,statistics,contentDetails", "id": ",".join(video_ids), "key": self.api_key},
|
||||||
label="yt-videos",
|
label="yt-videos",
|
||||||
)
|
)
|
||||||
|
if not resp or not resp.is_success:
|
||||||
|
return []
|
||||||
|
video_map = {v["id"]: v for v in resp.json().get("items", [])}
|
||||||
|
return [video_map[vid] for vid in video_ids if vid in video_map]
|
||||||
|
|
||||||
|
# 인기 영상 top 10 (조회수순) — search index 기반, 정확한 정렬 보장.
|
||||||
|
resp = await http_request(
|
||||||
|
HTTPMethod.GET,
|
||||||
|
url=f"{YT}/search",
|
||||||
|
params={"part": "snippet", "channelId": channel_id, "order": "viewCount", "type": "video", "maxResults": 10, "key": self.api_key},
|
||||||
|
label="yt-search-top",
|
||||||
|
)
|
||||||
|
top_ids: list[str] = []
|
||||||
if resp and resp.is_success:
|
if resp and resp.is_success:
|
||||||
videos = resp.json().get("items", [])[:10]
|
top_ids = [i["id"]["videoId"] for i in resp.json().get("items", []) if i.get("id", {}).get("videoId")]
|
||||||
|
videos = await _video_details(top_ids)
|
||||||
|
|
||||||
|
# 최근 영상 10개 — search index는 누락이 흔해 채널의 실제 uploads 재생목록에서 직접 읽고
|
||||||
|
# publishedAt 기준으로 코드에서 직접 정렬 (재생목록 순서 자체는 보장되지 않으므로).
|
||||||
|
recents: list[dict] = []
|
||||||
|
uploads_id = (channel.get("contentDetails") or {}).get("relatedPlaylists", {}).get("uploads")
|
||||||
|
if uploads_id:
|
||||||
|
resp = await http_request(
|
||||||
|
HTTPMethod.GET,
|
||||||
|
url=f"{YT}/playlistItems",
|
||||||
|
params={"part": "snippet", "playlistId": uploads_id, "maxResults": 10, "key": self.api_key},
|
||||||
|
label="yt-uploads",
|
||||||
|
)
|
||||||
|
if resp and resp.is_success:
|
||||||
|
entries = resp.json().get("items", [])
|
||||||
|
entries.sort(key=lambda i: i.get("snippet", {}).get("publishedAt") or "", reverse=True)
|
||||||
|
recent_ids = [
|
||||||
|
vid for e in entries
|
||||||
|
if (vid := e.get("snippet", {}).get("resourceId", {}).get("videoId"))
|
||||||
|
]
|
||||||
|
recents = await _video_details(recent_ids)
|
||||||
|
|
||||||
playlists: list[dict] = []
|
playlists: list[dict] = []
|
||||||
resp = await http_request(
|
resp = await http_request(
|
||||||
@@ -89,7 +115,19 @@ class YouTubeClient:
|
|||||||
if resp and resp.is_success:
|
if resp and resp.is_success:
|
||||||
playlists = resp.json().get("items", [])
|
playlists = resp.json().get("items", [])
|
||||||
|
|
||||||
return {"channelId": channel_id, "channel": channel, "videos": videos, "playlists": playlists}
|
return {"channelId": channel_id, "channel": channel, "videos": videos, "recents": recents, "playlists": playlists}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _video_item(v: dict) -> dict:
|
||||||
|
return {
|
||||||
|
"title": v.get("snippet", {}).get("title"),
|
||||||
|
"views": int(v.get("statistics", {}).get("viewCount", 0)),
|
||||||
|
"likes": int(v.get("statistics", {}).get("likeCount", 0)),
|
||||||
|
"comments": int(v.get("statistics", {}).get("commentCount", 0)),
|
||||||
|
"date": v.get("snippet", {}).get("publishedAt"),
|
||||||
|
"duration": v.get("contentDetails", {}).get("duration"),
|
||||||
|
"url": f"https://www.youtube.com/watch?v={v['id']}",
|
||||||
|
}
|
||||||
|
|
||||||
async def get_channel(self, url: str) -> dict | None:
|
async def get_channel(self, url: str) -> dict | None:
|
||||||
raw = await self.fetch_channel(url)
|
raw = await self.fetch_channel(url)
|
||||||
@@ -99,6 +137,7 @@ class YouTubeClient:
|
|||||||
stats = ch.get("statistics", {})
|
stats = ch.get("statistics", {})
|
||||||
snippet = ch.get("snippet", {})
|
snippet = ch.get("snippet", {})
|
||||||
thumbs = snippet.get("thumbnails", {})
|
thumbs = snippet.get("thumbnails", {})
|
||||||
|
print(snippet)
|
||||||
return {
|
return {
|
||||||
"channelId": raw["channelId"],
|
"channelId": raw["channelId"],
|
||||||
"channelName": snippet.get("title"),
|
"channelName": snippet.get("title"),
|
||||||
@@ -109,18 +148,8 @@ class YouTubeClient:
|
|||||||
"subscribers": int(stats.get("subscriberCount", 0)),
|
"subscribers": int(stats.get("subscriberCount", 0)),
|
||||||
"totalViews": int(stats.get("viewCount", 0)),
|
"totalViews": int(stats.get("viewCount", 0)),
|
||||||
"totalVideos": int(stats.get("videoCount", 0)),
|
"totalVideos": int(stats.get("videoCount", 0)),
|
||||||
"videos": [
|
"videos": [self._video_item(v) for v in raw["videos"]],
|
||||||
{
|
"recents": [self._video_item(v) for v in raw["recents"]],
|
||||||
"title": v.get("snippet", {}).get("title"),
|
|
||||||
"views": int(v.get("statistics", {}).get("viewCount", 0)),
|
|
||||||
"likes": int(v.get("statistics", {}).get("likeCount", 0)),
|
|
||||||
"comments": int(v.get("statistics", {}).get("commentCount", 0)),
|
|
||||||
"date": v.get("snippet", {}).get("publishedAt"),
|
|
||||||
"duration": v.get("contentDetails", {}).get("duration"),
|
|
||||||
"url": f"https://www.youtube.com/watch?v={v['id']}",
|
|
||||||
}
|
|
||||||
for v in raw["videos"]
|
|
||||||
],
|
|
||||||
"playlists": [
|
"playlists": [
|
||||||
p.get("snippet", {}).get("title")
|
p.get("snippet", {}).get("title")
|
||||||
for p in raw["playlists"]
|
for p in raw["playlists"]
|
||||||
|
|||||||
+10
-6
@@ -30,6 +30,10 @@ class DiagnosisItem(CamelModel):
|
|||||||
evidence_ids: list[str] | None = None
|
evidence_ids: list[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class CriticalIssueItem(DiagnosisItem):
|
||||||
|
title: str
|
||||||
|
|
||||||
|
|
||||||
class LeadDoctor(CamelModel):
|
class LeadDoctor(CamelModel):
|
||||||
name: str
|
name: str
|
||||||
credentials: str
|
credentials: str
|
||||||
@@ -88,7 +92,7 @@ class ChannelScore(CamelModel):
|
|||||||
channel: str
|
channel: str
|
||||||
icon: str
|
icon: str
|
||||||
score: int
|
score: int
|
||||||
max_score: int
|
max_score: int = 100
|
||||||
status: Severity
|
status: Severity
|
||||||
headline: str
|
headline: str
|
||||||
|
|
||||||
@@ -130,7 +134,7 @@ class YouTubeAudit(CamelModel):
|
|||||||
channel_description: str
|
channel_description: str
|
||||||
linked_urls: list[LinkedUrl]
|
linked_urls: list[LinkedUrl]
|
||||||
playlists: list[str]
|
playlists: list[str]
|
||||||
top_videos: list[TopVideo]
|
top_videos: list[TopVideo] = []
|
||||||
diagnosis: list[DiagnosisItem]
|
diagnosis: list[DiagnosisItem]
|
||||||
|
|
||||||
|
|
||||||
@@ -176,11 +180,11 @@ class FacebookPage(CamelModel):
|
|||||||
followers: int
|
followers: int
|
||||||
following: int
|
following: int
|
||||||
category: str
|
category: str
|
||||||
bio: str
|
bio: str = ""
|
||||||
logo: str
|
logo: str
|
||||||
logo_description: str
|
logo_description: str
|
||||||
link: str
|
link: str
|
||||||
linked_domain: str
|
linked_domain: str = ""
|
||||||
reviews: int
|
reviews: int
|
||||||
recent_post_age: str
|
recent_post_age: str
|
||||||
has_whatsapp: bool | None = None
|
has_whatsapp: bool | None = None
|
||||||
@@ -222,7 +226,7 @@ class AdditionalDomain(CamelModel):
|
|||||||
|
|
||||||
class WebsiteAudit(CamelModel):
|
class WebsiteAudit(CamelModel):
|
||||||
primary_domain: str
|
primary_domain: str
|
||||||
additional_domains: list[AdditionalDomain]
|
additional_domains: list[AdditionalDomain] = []
|
||||||
sns_links_on_site: bool
|
sns_links_on_site: bool
|
||||||
sns_links_detail: list[SnsLink] | None = None
|
sns_links_detail: list[SnsLink] | None = None
|
||||||
tracking_pixels: list[TrackingPixel]
|
tracking_pixels: list[TrackingPixel]
|
||||||
@@ -295,7 +299,7 @@ class MarketingReportResponse(CamelModel):
|
|||||||
facebook_audit: FacebookAudit
|
facebook_audit: FacebookAudit
|
||||||
other_channels: list[OtherChannel]
|
other_channels: list[OtherChannel]
|
||||||
website_audit: WebsiteAudit
|
website_audit: WebsiteAudit
|
||||||
problem_diagnosis: list[DiagnosisItem]
|
problem_diagnosis: list[CriticalIssueItem]
|
||||||
transformation: TransformationProposal
|
transformation: TransformationProposal
|
||||||
roadmap: list[RoadmapMonth]
|
roadmap: list[RoadmapMonth]
|
||||||
kpi_dashboard: list[KPIMetric]
|
kpi_dashboard: list[KPIMetric]
|
||||||
|
|||||||
+198
-183
@@ -1,14 +1,14 @@
|
|||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import re
|
|
||||||
from datetime import datetime
|
|
||||||
from urllib.parse import urlparse
|
from urllib.parse import urlparse
|
||||||
from common.db.run import update_run_report, update_run_plan, select_run_report_data
|
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.source import select_run_raw_data, select_mainpage_logo_url
|
||||||
from common.db.market import select_market
|
from common.db.market import select_market
|
||||||
from integrations.llm.llm_service import LLMService
|
from integrations.llm.llm_service import LLMService
|
||||||
from integrations.llm.prompt import report_prompt, plan_prompt, youtube_diagnosis_prompt
|
from integrations.llm.prompt import report_prompt, plan_prompt, youtube_diagnosis_prompt, brand_consistency_prompt, critical_issues_prompt, transformation_prompt, roadmap_prompt, scores_prompt, other_channels_prompt
|
||||||
from integrations.llm.schemas.report import ReportOutput, ClinicSnapshot, YouTubeAudit
|
from integrations.llm.schemas.report import ReportOutput, ClinicSnapshot, YouTubeAudit, BrandConsistencyOutput, CriticalIssuesOutput, CriticalIssueItem, DiagnosisItem, TransformationProposal, RoadmapOutput, RoadmapMonth, ScoresOutput, ChannelScore, WebsiteAudit, OtherChannelsOutput, OtherChannel
|
||||||
from services.branding import analyze_branding
|
from services.branding import analyze_branding
|
||||||
from services.instagram_audit import build_instagram_audit
|
from services.instagram_audit import build_instagram_audit
|
||||||
from services.facebook_audit import build_facebook_audit
|
from services.facebook_audit import build_facebook_audit
|
||||||
@@ -17,59 +17,35 @@ from integrations.llm.schemas.plan import PlanOutput
|
|||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
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 {}
|
|
||||||
branding = raw.get("branding") 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")),
|
|
||||||
# firecrawl 이 mainpage 에서 뽑은 branding 메타(logoUrl/ogImage/faviconUrl) + Vision/CSS 산출물
|
|
||||||
"branding": _json(clinic.get("branding")),
|
|
||||||
"brand_assets": _json(branding.get("brandAssets")),
|
|
||||||
"channel_logos": _json(branding.get("channelLogos")),
|
|
||||||
# 부가 채널 (raw_info entry) — raw dict 의 한국식 key 그대로
|
|
||||||
"tiktok": _json(raw.get("tiktok")),
|
|
||||||
"instagram_en": _json(raw.get("instagram_en")),
|
|
||||||
"facebook_en": _json(raw.get("facebook_en")),
|
|
||||||
"kakao_talk": _json(raw.get("kakaotalk")),
|
|
||||||
"naver_cafe": _json(raw.get("naver_cafe")),
|
|
||||||
# 메인 5채널은 raw dict 그대로 펼쳐서 prompt placeholder 와 매칭
|
|
||||||
**{
|
|
||||||
source_type: _json(data)
|
|
||||||
for source_type, data in raw.items()
|
|
||||||
if source_type not in {
|
|
||||||
"mainpage", "branding",
|
|
||||||
"tiktok", "instagram_en", "facebook_en", "kakaotalk", "naver_cafe",
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
return await LLMService(provider="perplexity").generate(report_prompt, input_data)
|
|
||||||
|
|
||||||
|
|
||||||
async def generate_plan(analysis_run_id: str) -> PlanOutput:
|
async def generate_plan(analysis_run_id: str) -> PlanOutput:
|
||||||
raw = await select_run_raw_data(analysis_run_id)
|
raw = await select_run_raw_data(analysis_run_id)
|
||||||
clinic = raw.get("mainpage") or {}
|
clinic = raw.get(SourceType.MAINPAGE) or []
|
||||||
branding = raw.get("branding") 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)
|
report = await select_run_report_data(analysis_run_id)
|
||||||
market = await select_market(analysis_run_id)
|
market = await select_market(analysis_run_id)
|
||||||
|
|
||||||
|
|
||||||
|
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# 유일 (기획상)
|
||||||
|
kakaotalk = raw.get(SourceType.KAKAOTALK) or []
|
||||||
|
kakaotalk = kakaotalk[0]["raw_data"] if kakaotalk else None# 유일 (기획상)
|
||||||
|
|
||||||
def _json(v) -> str | None:
|
def _json(v) -> str | None:
|
||||||
return json.dumps(v, ensure_ascii=False) if v else None
|
return json.dumps(v, ensure_ascii=False) if v else None
|
||||||
|
|
||||||
@@ -86,12 +62,12 @@ async def generate_plan(analysis_run_id: str) -> PlanOutput:
|
|||||||
"market_keywords": _json(market.get("keywords")),
|
"market_keywords": _json(market.get("keywords")),
|
||||||
"market_trend": _json(market.get("trend")),
|
"market_trend": _json(market.get("trend")),
|
||||||
"market_target_audience": _json(market.get("target_audience")),
|
"market_target_audience": _json(market.get("target_audience")),
|
||||||
"tiktok": _json(raw.get("tiktok")),
|
"tiktok": _json(tiktok),
|
||||||
"instagram_en": _json(raw.get("instagram_en")),
|
"instagram": _json(instagram),
|
||||||
"facebook_en": _json(raw.get("facebook_en")),
|
"facebook": _json(facebook),
|
||||||
"naver_blog": _json(_naver_blog_summary(raw.get("naver_blog"))),
|
"naver_blog": _json(_naver_blog_summary(naver_blog)),
|
||||||
"naver_cafe": _json(raw.get("naver_cafe")),
|
"naver_cafe": _json(naver_cafe),
|
||||||
"kakao_talk": _json(raw.get("kakaotalk")),
|
"kakao_talk": _json(kakaotalk),
|
||||||
"channel_logos": _json(branding.get("channelLogos")),
|
"channel_logos": _json(branding.get("channelLogos")),
|
||||||
"brand_assets": _json(branding.get("brandAssets")),
|
"brand_assets": _json(branding.get("brandAssets")),
|
||||||
}
|
}
|
||||||
@@ -99,18 +75,17 @@ 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 _build_clinic_snapshot(gangnam_unni: dict, mainpage: dict, brand_assets: dict, logo_url: str | None) -> dict:
|
def _build_clinic_snapshot(mainpage: dict, gangnam_unni: dict, brand_assets: dict, logo_url: str | None) -> dict:
|
||||||
snapshot: dict = {}
|
snapshot: dict = {}
|
||||||
doctors = gangnam_unni.get("doctors", [])
|
doctors = gangnam_unni.get("doctors", [])
|
||||||
lead = max(doctors, key=lambda d: d.get("reviews", 0)) if doctors else None
|
lead = max(doctors, key=lambda d: d.get("reviews", 0)) if doctors else None
|
||||||
if gangnam_unni.get("name"): snapshot["name"] = gangnam_unni["name"]
|
snapshot["name"] = mainpage["clinicName"]
|
||||||
if mainpage.get("clinicNameEn"): snapshot["name_en"] = mainpage["clinicNameEn"]
|
snapshot["name_en"] = mainpage["clinicNameEn"]
|
||||||
if mainpage.get("phone"): snapshot["phone"] = mainpage["phone"]
|
snapshot["phone"] = mainpage["phone"]
|
||||||
domain = mainpage.get("domain") or urlparse(mainpage.get("sourceUrl") or "").netloc
|
snapshot["location"] = mainpage["address"]
|
||||||
if domain: snapshot["domain"] = domain
|
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("rating"): snapshot["overall_rating"] = gangnam_unni["rating"]
|
||||||
if gangnam_unni.get("totalReviews"): snapshot["total_reviews"] = gangnam_unni["totalReviews"]
|
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("badges"): snapshot["certifications"] = gangnam_unni["badges"]
|
||||||
if gangnam_unni.get("totalMajorStaffs"): snapshot["staff_count"] = gangnam_unni["totalMajorStaffs"]
|
if gangnam_unni.get("totalMajorStaffs"): snapshot["staff_count"] = gangnam_unni["totalMajorStaffs"]
|
||||||
if lead:
|
if lead:
|
||||||
@@ -126,7 +101,6 @@ def _build_clinic_snapshot(gangnam_unni: dict, mainpage: dict, brand_assets: dic
|
|||||||
if brand_assets.get("brand_colors"): snapshot["brand_colors"] = brand_assets["brand_colors"]
|
if brand_assets.get("brand_colors"): snapshot["brand_colors"] = brand_assets["brand_colors"]
|
||||||
return ClinicSnapshot.model_validate(snapshot).model_dump()
|
return ClinicSnapshot.model_validate(snapshot).model_dump()
|
||||||
|
|
||||||
|
|
||||||
def _naver_blog_summary(blog: dict | None) -> dict | None:
|
def _naver_blog_summary(blog: dict | None) -> dict | None:
|
||||||
"""plan 카드 한 장에 들어가는 건 전체 포스트 수와 최근 활동 시점뿐. 그 외(본문·링크·제목)는
|
"""plan 카드 한 장에 들어가는 건 전체 포스트 수와 최근 활동 시점뿐. 그 외(본문·링크·제목)는
|
||||||
던져봐야 토큰만 늘고 LLM 이 무관 정보로 hallucinate 함."""
|
던져봐야 토큰만 늘고 LLM 이 무관 정보로 hallucinate 함."""
|
||||||
@@ -138,79 +112,15 @@ def _naver_blog_summary(blog: dict | None) -> dict | None:
|
|||||||
"latestPostDate": posts[0].get("postDate") if posts else None,
|
"latestPostDate": posts[0].get("postDate") if posts else None,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async def _build_youtube_audit(youtube: dict) -> dict: # 기획상 1개의 input channel, 다중 채널은 기획에 없음.
|
||||||
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:
|
|
||||||
videos = youtube.get("videos", [])
|
videos = youtube.get("videos", [])
|
||||||
|
recents = youtube.get("recents", [])
|
||||||
yt_patch: dict = {
|
yt_patch: dict = {
|
||||||
"weekly_view_growth": {"absolute": 0, "percentage": 0.0},
|
"weekly_view_growth": {"absolute": 0, "percentage": 0.0},
|
||||||
"estimated_monthly_revenue": {"min": 0, "max": 0},
|
"estimated_monthly_revenue": {"min": 0, "max": 0},
|
||||||
"linked_urls": [],
|
"linked_urls": [],
|
||||||
"avg_video_length": _calc_avg_video_length(videos),
|
"avg_video_length": calc_avg_video_length(videos),
|
||||||
"upload_frequency": _calc_upload_frequency(videos),
|
"upload_frequency": calc_upload_frequency(recents),
|
||||||
}
|
}
|
||||||
if youtube.get("channelName"): yt_patch["channel_name"] = youtube["channelName"]
|
if youtube.get("channelName"): yt_patch["channel_name"] = youtube["channelName"]
|
||||||
if youtube.get("handle"): yt_patch["handle"] = youtube["handle"]
|
if youtube.get("handle"): yt_patch["handle"] = youtube["handle"]
|
||||||
@@ -218,16 +128,16 @@ async def _build_youtube_audit(youtube: dict) -> dict:
|
|||||||
if youtube.get("totalVideos"): yt_patch["total_videos"] = youtube["totalVideos"]
|
if youtube.get("totalVideos"): yt_patch["total_videos"] = youtube["totalVideos"]
|
||||||
if youtube.get("totalViews"): yt_patch["total_views"] = youtube["totalViews"]
|
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("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 youtube.get("playlists"): yt_patch["playlists"] = youtube["playlists"]
|
||||||
if videos:
|
if videos:
|
||||||
yt_patch["top_videos"] = [
|
yt_patch["top_videos"] = [
|
||||||
{
|
{
|
||||||
"title": v["title"],
|
"title": v["title"],
|
||||||
"views": v["views"],
|
"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",
|
"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
|
for v in videos
|
||||||
]
|
]
|
||||||
@@ -250,6 +160,139 @@ async def _build_youtube_audit(youtube: dict) -> dict:
|
|||||||
return YouTubeAudit.model_validate(yt_patch).model_dump()
|
return YouTubeAudit.model_validate(yt_patch).model_dump()
|
||||||
|
|
||||||
|
|
||||||
|
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(SourceType.MAINPAGE) or [{}])[0]["raw_data"].get("clinicName"),
|
||||||
|
"data": json.dumps(raw, ensure_ascii=False),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
return [RoadmapMonth.model_validate(item).model_dump() for item in result.roadmap]
|
||||||
|
|
||||||
|
|
||||||
|
async def _build_transformation(analysis_run_id: str, raw: dict) -> dict:
|
||||||
|
result: TransformationProposal = await LLMService(provider="perplexity").generate(
|
||||||
|
transformation_prompt,
|
||||||
|
{
|
||||||
|
"clinic_name": (raw.get(SourceType.MAINPAGE) or [{}])[0]["raw_data"].get("clinicName"),
|
||||||
|
"data": json.dumps(raw, ensure_ascii=False),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
return result.model_dump()
|
||||||
|
|
||||||
|
|
||||||
|
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(SourceType.MAINPAGE) or [{}])[0]["raw_data"].get("clinicName"),
|
||||||
|
"data": json.dumps(raw, ensure_ascii=False),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
return [CriticalIssueItem.model_validate(item).model_dump() for item in result.diagnosis]
|
||||||
|
|
||||||
|
|
||||||
|
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),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
def _build_website_audit(mainpage: dict) -> dict:
|
||||||
|
"""mainpage raw_data 에서 직접 매핑. LLM 미경유.
|
||||||
|
Firecrawl 의 raw HTML 을 collect_mainpage 가 정규식 파싱해서 tracking/SNS/domain 까지 mainpage 에 다 박아둠."""
|
||||||
|
domain = mainpage.get("domain") or urlparse(mainpage.get("sourceUrl") or "").netloc
|
||||||
|
sns_links = mainpage.get("snsLinks") or []
|
||||||
|
audit = {
|
||||||
|
"primary_domain": domain,
|
||||||
|
"additional_domains": mainpage.get("additionalDomains") or [],
|
||||||
|
"sns_links_on_site": bool(sns_links),
|
||||||
|
"sns_links_detail": sns_links or None,
|
||||||
|
"tracking_pixels": mainpage.get("trackingPixels") or [],
|
||||||
|
"main_cta": mainpage.get("mainCta") or "",
|
||||||
|
}
|
||||||
|
return WebsiteAudit.model_validate(audit).model_dump()
|
||||||
|
|
||||||
|
async def _build_other_channels(raw: dict) -> list[dict]:
|
||||||
|
result: OtherChannelsOutput = await LLMService(provider="perplexity").generate(
|
||||||
|
other_channels_prompt,
|
||||||
|
{
|
||||||
|
"clinic_name": (raw.get(SourceType.MAINPAGE) or [{}])[0]["raw_data"].get("clinicName"),
|
||||||
|
"tiktok": json.dumps(raw.get(SourceType.TIKTOK), ensure_ascii=False),
|
||||||
|
"kakao_talk": json.dumps(raw.get(SourceType.KAKAOTALK), ensure_ascii=False),
|
||||||
|
"naver_cafe": json.dumps(raw.get(SourceType.NAVER_CAFE), ensure_ascii=False),
|
||||||
|
"naver_blog": json.dumps(raw.get(SourceType.NAVER_BLOG), ensure_ascii=False),
|
||||||
|
"gangnam_unni": json.dumps(raw.get(SourceType.GANGNAM_UNNI), ensure_ascii=False),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
return [OtherChannel.model_validate(item).model_dump() for item in result.other_channels]
|
||||||
|
|
||||||
|
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(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# 유일 (기획상)
|
||||||
|
|
||||||
|
brand_assets = branding.get("brandAssets") or {}
|
||||||
|
channel_logos = branding.get("channelLogos") or {}
|
||||||
|
|
||||||
|
logo_url = await select_mainpage_logo_url(analysis_run_id)
|
||||||
|
|
||||||
|
brand = await generate_brand_consistency(analysis_run_id)
|
||||||
|
brand_patch : list[dict] = brand.model_dump()["brand_inconsistencies"]
|
||||||
|
|
||||||
|
kpi_extras = {
|
||||||
|
"tiktok": tiktok,
|
||||||
|
"naverCafe": naver_cafe,
|
||||||
|
}
|
||||||
|
|
||||||
|
scores = (await _build_scores(analysis_run_id, raw)).model_dump()
|
||||||
|
|
||||||
|
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": await _build_other_channels(raw),
|
||||||
|
"website_audit": _build_website_audit(mainpage),
|
||||||
|
|
||||||
|
"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:
|
def _deep_merge(base: dict, overrides: dict) -> dict:
|
||||||
"""dict 끼리 만나면 재귀로 안쪽까지 합치고, 그 외(list/scalar/None) 는 override 값으로 통째 치환."""
|
"""dict 끼리 만나면 재귀로 안쪽까지 합치고, 그 외(list/scalar/None) 는 override 값으로 통째 치환."""
|
||||||
for k, v in overrides.items():
|
for k, v in overrides.items():
|
||||||
@@ -259,57 +302,28 @@ def _deep_merge(base: dict, overrides: dict) -> dict:
|
|||||||
base[k] = v
|
base[k] = v
|
||||||
return base
|
return base
|
||||||
|
|
||||||
|
async def generate_brand_consistency(analysis_run_id: str) -> BrandConsistencyOutput:
|
||||||
async def _build_overrides(analysis_run_id: str, result: ReportOutput) -> ReportOutput:
|
|
||||||
raw = await select_run_raw_data(analysis_run_id)
|
raw = await select_run_raw_data(analysis_run_id)
|
||||||
if not raw:
|
|
||||||
return result
|
|
||||||
|
|
||||||
mainpage = raw.get("mainpage", {}) or {}
|
def _json(v) -> str | None:
|
||||||
branding = raw.get("branding", {}) or {}
|
return json.dumps(v, ensure_ascii=False) if v else None
|
||||||
instagram = raw.get("instagram", {}) or {}
|
|
||||||
facebook = raw.get("facebook", {}) or {}
|
|
||||||
youtube = raw.get("youtube", {}) or {}
|
|
||||||
gangnam_unni = raw.get("gangnam_unni", {}) or {}
|
|
||||||
naver_blog = raw.get("naver_blog", {}) or {}
|
|
||||||
instagram_en = raw.get("instagram_en", {}) or {}
|
|
||||||
facebook_en = raw.get("facebook_en", {}) or {}
|
|
||||||
tiktok = raw.get("tiktok", {}) or {}
|
|
||||||
naver_cafe = raw.get("naver_cafe", {}) or {}
|
|
||||||
brand_assets = branding.get("brandAssets") or {}
|
|
||||||
channel_logos = branding.get("channelLogos") or {}
|
|
||||||
logo_url = await select_mainpage_logo_url(analysis_run_id)
|
|
||||||
|
|
||||||
llm_fb_pages = result.model_dump().get("facebook_audit", {}).get("pages", [])
|
mainpage = raw.get(SourceType.MAINPAGE) or []
|
||||||
|
input_data = {
|
||||||
snapshot: dict = _build_clinic_snapshot(gangnam_unni, mainpage, brand_assets, logo_url)
|
"clinic_name": (mainpage[0].get("clinicName") if mainpage else None),
|
||||||
yt_patch: dict = await _build_youtube_audit(youtube)
|
"mainpage": _json(mainpage),
|
||||||
ig_patch = build_instagram_audit(instagram, instagram_en, channel_logos)
|
"instagram": _json(raw.get(SourceType.INSTAGRAM)),
|
||||||
fb_patch = build_facebook_audit(facebook, facebook_en, llm_fb_pages)
|
"facebook": _json(raw.get(SourceType.FACEBOOK)),
|
||||||
kpi_extras = {
|
"youtube": _json(raw.get(SourceType.YOUTUBE)),
|
||||||
"instagramEn": instagram_en,
|
"gangnam_unni": _json(raw.get(SourceType.GANGNAM_UNNI)),
|
||||||
"facebookEn": facebook_en,
|
|
||||||
"tiktok": tiktok,
|
|
||||||
"naverCafe": naver_cafe,
|
|
||||||
}
|
}
|
||||||
kpi = build_kpi_dashboard(instagram, facebook, youtube, gangnam_unni, kpi_extras, naver_blog)
|
return await LLMService(provider="perplexity").generate(brand_consistency_prompt, input_data)
|
||||||
|
|
||||||
overrides: dict = {}
|
|
||||||
if snapshot: overrides["clinic_snapshot"] = snapshot
|
|
||||||
if ig_patch: overrides["instagram_audit"] = ig_patch
|
|
||||||
if fb_patch: overrides["facebook_audit"] = fb_patch
|
|
||||||
if yt_patch: overrides["youtube_audit"] = yt_patch
|
|
||||||
if kpi: overrides["kpi_dashboard"] = kpi
|
|
||||||
|
|
||||||
merged = _deep_merge(result.model_dump(), overrides)
|
|
||||||
return ReportOutput(**merged)
|
|
||||||
|
|
||||||
|
|
||||||
async def run_report_task(analysis_run_id: str) -> None:
|
async def run_report_task(analysis_run_id: str) -> None:
|
||||||
logger.info("[report] start run=%s", analysis_run_id)
|
logger.info("[report] start run=%s", analysis_run_id)
|
||||||
await analyze_branding(analysis_run_id)
|
await analyze_branding(analysis_run_id)
|
||||||
result = await generate_report(analysis_run_id)
|
# result = await generate_report(analysis_run_id)
|
||||||
result = await _build_overrides(analysis_run_id, result)
|
result = await _build_report(analysis_run_id)
|
||||||
await update_run_report(analysis_run_id, result.model_dump())
|
await update_run_report(analysis_run_id, result.model_dump())
|
||||||
logger.info("[report] done run=%s", analysis_run_id)
|
logger.info("[report] done run=%s", analysis_run_id)
|
||||||
|
|
||||||
@@ -328,8 +342,9 @@ async def run_plan_task(analysis_run_id: str) -> None:
|
|||||||
result = await generate_plan(analysis_run_id)
|
result = await generate_plan(analysis_run_id)
|
||||||
# profile_photo 는 brand_assets.logo_description 으로 코드가 박음 (LLM "(가이드 미보유)" 같은 hallucination 차단).
|
# profile_photo 는 brand_assets.logo_description 으로 코드가 박음 (LLM "(가이드 미보유)" 같은 hallucination 차단).
|
||||||
raw = await select_run_raw_data(analysis_run_id)
|
raw = await select_run_raw_data(analysis_run_id)
|
||||||
branding = raw.get("branding") or {}
|
branding_list = raw.get(SourceType.BRANDING) or []
|
||||||
logo_desc = ((branding.get("brandAssets") or {}).get("logo_description")) or ""
|
branding_data = branding_list[0]["raw_data"] if branding_list else {}
|
||||||
|
logo_desc = (branding_data.get("brandAssets") or {}).get("logo_description") or ""
|
||||||
result = _patch_plan(result, logo_desc)
|
result = _patch_plan(result, logo_desc)
|
||||||
await update_run_plan(analysis_run_id, result.model_dump())
|
await update_run_plan(analysis_run_id, result.model_dump())
|
||||||
logger.info("[plan] done run=%s", analysis_run_id)
|
logger.info("[plan] done run=%s", analysis_run_id)
|
||||||
@@ -16,7 +16,7 @@ async def _describe_logo(analysis_run_id: str, info_id: int, vc: VisionClient) -
|
|||||||
"""공식 로고 정성 묘사. branding raw_info["brandAssets"] 머지.
|
"""공식 로고 정성 묘사. branding raw_info["brandAssets"] 머지.
|
||||||
호출 우선순위: raw_info.logo_url 컬럼 (HTML parser canonical) → firecrawl 메타 fallback."""
|
호출 우선순위: raw_info.logo_url 컬럼 (HTML parser canonical) → firecrawl 메타 fallback."""
|
||||||
raw = await select_run_raw_data(analysis_run_id)
|
raw = await select_run_raw_data(analysis_run_id)
|
||||||
mainpage = raw.get("mainpage") or {}
|
mainpage = ((raw.get("mainpage") or [{}])[0].get("raw_data")) or {}
|
||||||
homepage_url = mainpage.get("sourceUrl") or ""
|
homepage_url = mainpage.get("sourceUrl") or ""
|
||||||
branding_meta = mainpage.get("branding") or {}
|
branding_meta = mainpage.get("branding") or {}
|
||||||
column_logo = await select_mainpage_logo_url(analysis_run_id)
|
column_logo = await select_mainpage_logo_url(analysis_run_id)
|
||||||
@@ -39,7 +39,11 @@ async def _describe_logo(analysis_run_id: str, info_id: int, vc: VisionClient) -
|
|||||||
if result:
|
if result:
|
||||||
break
|
break
|
||||||
if result:
|
if result:
|
||||||
await update_raw_info_merge(info_id, {"brandAssets": result})
|
# collect_brand_basics 가 미리 채운 brand_colors/color_palette/color_source 보존하면서 logo_* 덧붙이기.
|
||||||
|
raw = await select_run_raw_data(analysis_run_id)
|
||||||
|
existing = ((raw.get("branding") or [{}])[0].get("raw_data") or {}).get("brandAssets") or {}
|
||||||
|
merged = {**existing, **result}
|
||||||
|
await update_raw_info_merge(info_id, {"brandAssets": merged})
|
||||||
logger.info("[brand_logo] done keys=%s", list(result.keys()) if result else None)
|
logger.info("[brand_logo] done keys=%s", list(result.keys()) if result else None)
|
||||||
|
|
||||||
|
|
||||||
@@ -47,17 +51,30 @@ async def _describe_channel_logos(analysis_run_id: str, info_id: int, vc: Vision
|
|||||||
"""채널 프로필 로고를 공식 로고와 비교. branding raw_info["channelLogos"] 머지."""
|
"""채널 프로필 로고를 공식 로고와 비교. branding raw_info["channelLogos"] 머지."""
|
||||||
raw = await select_run_raw_data(analysis_run_id)
|
raw = await select_run_raw_data(analysis_run_id)
|
||||||
official = await select_mainpage_logo_url(analysis_run_id)
|
official = await select_mainpage_logo_url(analysis_run_id)
|
||||||
|
|
||||||
|
|
||||||
_label = {
|
_label = {
|
||||||
"instagram": "Instagram",
|
"instagram": "Instagram",
|
||||||
"facebook": "Facebook",
|
"facebook": "Facebook",
|
||||||
"youtube": "YouTube",
|
"youtube": "YouTube",
|
||||||
"instagram_en": "Instagram EN",
|
|
||||||
"facebook_en": "Facebook EN",
|
|
||||||
"tiktok": "TikTok",
|
"tiktok": "TikTok",
|
||||||
}
|
}
|
||||||
logos = [{"channel": label, "url": img}
|
logos = []
|
||||||
for key, label in _label.items()
|
for key, label_prefix in _label.items():
|
||||||
if (img := (raw.get(key) or {}).get("_logo_url"))]
|
if key in raw:
|
||||||
|
channel_list = raw.get(key)
|
||||||
|
|
||||||
|
for item in channel_list:
|
||||||
|
language = item["language"]
|
||||||
|
if language != "KR":
|
||||||
|
label = label_prefix + " " + language
|
||||||
|
else :
|
||||||
|
label = label_prefix
|
||||||
|
img = item.get("logo_url")
|
||||||
|
|
||||||
|
if img:
|
||||||
|
logos.append({"channel": label, "url": img})
|
||||||
|
|
||||||
if not logos:
|
if not logos:
|
||||||
logger.info("[channel_logos] skip — no channel profileImages")
|
logger.info("[channel_logos] skip — no channel profileImages")
|
||||||
return
|
return
|
||||||
|
|||||||
+23
-1
@@ -1,5 +1,6 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
import logging
|
import logging
|
||||||
|
from urllib.parse import urlparse
|
||||||
from common.db.hospital import update_hospital_status, update_hospital
|
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.db.source import select_run_sources, update_raw_info_status, update_raw_info
|
||||||
from common.utils import get_env, _run_optional_step
|
from common.utils import get_env, _run_optional_step
|
||||||
@@ -10,6 +11,7 @@ from integrations.firecrawl import FirecrawlClient
|
|||||||
from models.status import SourceType
|
from models.status import SourceType
|
||||||
from integrations.site_fetcher import fetch_html_and_css
|
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 services.brand_parser import find_logo_url_in_html, extract_brand_colors_from_text
|
||||||
|
from services.website_parser import extract_tracking_pixels, extract_sns_links, extract_additional_domains, extract_main_cta
|
||||||
from common.db.source import update_raw_info_merge, update_raw_info_logo_url, select_run_raw_data
|
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 common.db.base import fetchone
|
||||||
from services.facebook_audit import transform_for_storage as transform_facebook
|
from services.facebook_audit import transform_for_storage as transform_facebook
|
||||||
@@ -84,6 +86,22 @@ async def collect_gangnam_unni(analysis_run_id: str, info_id: int, url: str) ->
|
|||||||
logger.info("[gangnam_unni] done run=%s", analysis_run_id)
|
logger.info("[gangnam_unni] done run=%s", analysis_run_id)
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_website_audit(html: str, url: str) -> dict:
|
||||||
|
"""raw HTML 에서 main CTA / tracking pixels / SNS / additional domains 정규식 추출."""
|
||||||
|
if not html:
|
||||||
|
return {}
|
||||||
|
primary_host = urlparse(url).netloc
|
||||||
|
result: dict = {
|
||||||
|
"trackingPixels": extract_tracking_pixels(html),
|
||||||
|
"snsLinks": extract_sns_links(html),
|
||||||
|
"additionalDomains": extract_additional_domains(html, primary_host),
|
||||||
|
}
|
||||||
|
html_cta = extract_main_cta(html)
|
||||||
|
if html_cta:
|
||||||
|
result["mainCta"] = html_cta
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
async def collect_mainpage(analysis_run_id: str, info_id: int, hospital_id: str, url: str) -> None:
|
async def collect_mainpage(analysis_run_id: str, info_id: int, hospital_id: str, url: str) -> None:
|
||||||
logger.info("[mainpage] start run=%s url=%s", analysis_run_id, url)
|
logger.info("[mainpage] start run=%s url=%s", analysis_run_id, url)
|
||||||
await update_raw_info_status(info_id, "processing")
|
await update_raw_info_status(info_id, "processing")
|
||||||
@@ -93,8 +111,12 @@ async def collect_mainpage(analysis_run_id: str, info_id: int, hospital_id: str,
|
|||||||
await update_raw_info_status(info_id, "failed")
|
await update_raw_info_status(info_id, "failed")
|
||||||
logger.warning("[mainpage] failed run=%s", analysis_run_id)
|
logger.warning("[mainpage] failed run=%s", analysis_run_id)
|
||||||
return
|
return
|
||||||
|
|
||||||
|
html = data.pop("html", "") or "" # raw_data 에는 저장 안 함 — 여기서만 사용하고 버림.
|
||||||
# 홈페이지 URL 자체도 raw_data 에 박아둬야 brand_assets / 분석 단계에서 mainpage URL 재조회 없이 사용 가능.
|
# 홈페이지 URL 자체도 raw_data 에 박아둬야 brand_assets / 분석 단계에서 mainpage URL 재조회 없이 사용 가능.
|
||||||
data = {**data, "sourceUrl": url}
|
data = {**data, "sourceUrl": url}
|
||||||
|
data.update(_extract_website_audit(html, url))
|
||||||
|
|
||||||
await update_raw_info(info_id, data)
|
await update_raw_info(info_id, data)
|
||||||
await update_hospital(hospital_id, data, analysis_run_id=analysis_run_id)
|
await update_hospital(hospital_id, data, analysis_run_id=analysis_run_id)
|
||||||
logger.info("[mainpage] done run=%s", analysis_run_id)
|
logger.info("[mainpage] done run=%s", analysis_run_id)
|
||||||
@@ -134,7 +156,7 @@ async def collect_kakaotalk(analysis_run_id: str, info_id: int, url: str) -> Non
|
|||||||
async def collect_brand_basics(analysis_run_id: str, info_id: int) -> None:
|
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)
|
logger.info("[brand_basics] start run=%s info=%s", analysis_run_id, info_id)
|
||||||
raw = await select_run_raw_data(analysis_run_id)
|
raw = await select_run_raw_data(analysis_run_id)
|
||||||
mainpage = raw.get("mainpage") or {}
|
mainpage = ((raw.get("mainpage") or [{}])[0].get("raw_data")) or {}
|
||||||
homepage_url = mainpage.get("sourceUrl") or ""
|
homepage_url = mainpage.get("sourceUrl") or ""
|
||||||
branding_meta = mainpage.get("branding") or {}
|
branding_meta = mainpage.get("branding") or {}
|
||||||
|
|
||||||
|
|||||||
@@ -2,10 +2,13 @@
|
|||||||
수치 지표(최근 게시일·게시 빈도·참여율)는 **수집 시점에** 결정적으로 산출해 DB에 박는다 (transform_for_storage).
|
수치 지표(최근 게시일·게시 빈도·참여율)는 **수집 시점에** 결정적으로 산출해 DB에 박는다 (transform_for_storage).
|
||||||
콘텐츠 주제(top_content_type)는 캡션 본문 이해가 필요해 LLM이 채운다 (리포트 프롬프트 지시)."""
|
콘텐츠 주제(top_content_type)는 캡션 본문 이해가 필요해 LLM이 채운다 (리포트 프롬프트 지시)."""
|
||||||
|
|
||||||
|
import json
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
from common.utils import parse_ts
|
from common.utils import parse_ts
|
||||||
from integrations.llm.schemas.report import FacebookAudit
|
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:
|
def _humanize_age(days: int) -> str:
|
||||||
@@ -74,11 +77,28 @@ def transform_for_storage(fb: dict | None) -> dict | None:
|
|||||||
out["latestPosts"] = []
|
out["latestPosts"] = []
|
||||||
return out
|
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
|
||||||
|
print("channel_logos NOT FOUND : ", channel_logos)
|
||||||
|
return {
|
||||||
|
"is_official" : False,
|
||||||
|
"logo_description" : "로고 찾지 못함"
|
||||||
|
}
|
||||||
|
|
||||||
|
def _page_patch(item: dict, channel_logos) -> dict:
|
||||||
|
p: dict = {"page_name": "", "followers": 0, "category": "", "reviews": 0,
|
||||||
|
"following": 0, "recent_post_age": "", "post_frequency": "", "engagement": ""}
|
||||||
|
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)
|
||||||
|
|
||||||
def _page_patch(fb: dict, language: str, label: str) -> dict:
|
|
||||||
"""저장된 페북 페이지 → FacebookPage 스키마 필드 패치. 수치 지표는 수집 시점에 박혀있어 그대로 복사.
|
|
||||||
language/label 은 데이터 있을 때만 명시적으로 박음 — template-copy 가 KR 값을 EN 슬롯에 잘못 상속시키는 것 방지."""
|
|
||||||
p: dict = {}
|
|
||||||
if fb.get("pageUrl"): p["url"] = p["link"] = fb["pageUrl"]
|
if fb.get("pageUrl"): p["url"] = p["link"] = fb["pageUrl"]
|
||||||
if fb.get("pageName"): p["page_name"] = fb["pageName"]
|
if fb.get("pageName"): p["page_name"] = fb["pageName"]
|
||||||
if fb.get("followers"): p["followers"] = fb["followers"]
|
if fb.get("followers"): p["followers"] = fb["followers"]
|
||||||
@@ -90,17 +110,21 @@ def _page_patch(fb: dict, language: str, label: str) -> dict:
|
|||||||
for key in ("recent_post_age", "post_frequency", "engagement"):
|
for key in ("recent_post_age", "post_frequency", "engagement"):
|
||||||
if fb.get(key): p[key] = fb[key]
|
if fb.get(key): p[key] = fb[key]
|
||||||
if p:
|
if p:
|
||||||
p["language"] = language
|
p["language"] = item["language"]
|
||||||
p["label"] = label
|
p["label"] = label
|
||||||
|
p["logo"] = "일치 (공식 로고)" if logo_data["is_official"] else "불일치 (비공식 변형)"
|
||||||
|
p["logo_description"] = logo_data["logo_description"]
|
||||||
return p
|
return p
|
||||||
|
|
||||||
|
|
||||||
def build_facebook_audit(facebook: dict, facebook_en: dict, llm_pages: list[dict] | None = None) -> dict:
|
async def build_facebook_audit(facebook: list[dict], brand_patch: list[dict], channel_logos) -> dict:
|
||||||
"""KR·EN 페북 페이지 구성. logo/logo_description 은 LLM Vision 결과(첫 페이지) 모든 페이지에 공통 적용,
|
pages = [_page_patch(item, channel_logos) for item in facebook]
|
||||||
나머지 필드는 코드가 수집 데이터로 계산."""
|
diagnosis_result = await LLMService(provider="perplexity").generate(
|
||||||
llm_logo = {k: v for k, v in ((llm_pages or [{}])[0]).items() if k in {"logo", "logo_description"} and v}
|
facebook_diagnosis_prompt,
|
||||||
pages = [{**llm_logo, **p} for p in (
|
{"pages": json.dumps(pages, ensure_ascii=False)},
|
||||||
_page_patch(facebook, "KR", "페이스북 KR"),
|
)
|
||||||
_page_patch(facebook_en, "EN", "페이스북 EN"),
|
return FacebookAudit.model_validate({
|
||||||
) if p]
|
"pages": pages,
|
||||||
return FacebookAudit.model_validate({"pages": pages}).model_dump(exclude_unset=True)
|
"diagnosis": [DiagnosisItem.model_validate(item).model_dump() for item in diagnosis_result.diagnosis],
|
||||||
|
"brand_inconsistencies": brand_patch,
|
||||||
|
}).model_dump()
|
||||||
@@ -1,7 +1,10 @@
|
|||||||
"""Instagram audit 계정(KR·EN)을 수집 데이터로 구성.
|
"""Instagram audit 계정(KR·EN)을 수집 데이터로 구성.
|
||||||
fix 값(handle/followers/highlights/content_format 등)은 전부 코드에서 박는다 — LLM 출력 무시."""
|
fix 값(handle/followers/highlights/content_format 등)은 전부 코드에서 박는다 — LLM 출력 무시."""
|
||||||
|
|
||||||
from integrations.llm.schemas.report import InstagramAudit
|
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": "영상/릴스"}
|
_MEDIA = {"GraphImage": "이미지", "GraphSidecar": "카드뉴스", "GraphVideo": "영상/릴스"}
|
||||||
|
|
||||||
@@ -20,8 +23,16 @@ def _logo_desc(channel_logos: dict, channel: str) -> str:
|
|||||||
return ""
|
return ""
|
||||||
|
|
||||||
|
|
||||||
def _account(data: dict, language: str, label: str, channel: str, channel_logos: dict) -> dict:
|
def _account(item: dict, channel_logos: dict) -> dict:
|
||||||
"""스크래퍼 수집값으로 InstagramAccount 전 필드를 구성."""
|
"""스크래퍼 수집값으로 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 ""
|
handle = data.get("username") or ""
|
||||||
return {
|
return {
|
||||||
"handle": handle,
|
"handle": handle,
|
||||||
@@ -40,11 +51,14 @@ def _account(data: dict, language: str, label: str, channel: str, channel_logos:
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def build_instagram_audit(instagram: dict, instagram_en: dict, channel_logos: dict) -> dict:
|
async def build_instagram_audit(instagram: list[dict], channel_logos: dict) -> dict:
|
||||||
"""KR·EN 인스타 계정 리스트 구성 (username 있는 것만)."""
|
"""KR·EN 인스타 계정 리스트 구성 (username 있는 것만)."""
|
||||||
accounts: list[dict] = []
|
accounts = [_account(item, channel_logos) for item in instagram if item.get("raw_data").get("username")]
|
||||||
if instagram.get("username"):
|
diagnosis_result = await LLMService(provider="perplexity").generate(
|
||||||
accounts.append(_account(instagram, "KR", "인스타그램 KR", "Instagram", channel_logos))
|
instagram_diagnosis_prompt,
|
||||||
if instagram_en.get("username"):
|
{"accounts": json.dumps(accounts, ensure_ascii=False)},
|
||||||
accounts.append(_account(instagram_en, "EN", "인스타그램 EN", "Instagram EN", channel_logos))
|
)
|
||||||
return InstagramAudit.model_validate({"accounts": accounts}).model_dump()
|
return InstagramAudit.model_validate({
|
||||||
|
"accounts": accounts,
|
||||||
|
"diagnosis": [DiagnosisItem.model_validate(item).model_dump() for item in diagnosis_result.diagnosis],
|
||||||
|
}).model_dump()
|
||||||
@@ -53,18 +53,21 @@ def build_kpi_dashboard(
|
|||||||
instagram: dict, facebook: dict, youtube: dict, gangnam_unni: dict, hospital: dict,
|
instagram: dict, facebook: dict, youtube: dict, gangnam_unni: dict, hospital: dict,
|
||||||
naver_blog: dict | None = None,
|
naver_blog: dict | None = None,
|
||||||
) -> list[dict]:
|
) -> list[dict]:
|
||||||
ig_en = hospital.get("instagramEn") or {}
|
|
||||||
fb_en = hospital.get("facebookEn") or {}
|
|
||||||
tiktok = hospital.get("tiktok") or {}
|
tiktok = hospital.get("tiktok") or {}
|
||||||
cafe = hospital.get("naverCafe") or {}
|
cafe = hospital.get("naverCafe") or {}
|
||||||
|
# print("facebook", facebook)
|
||||||
|
# print("instagram", instagram)
|
||||||
|
|
||||||
kpis: list[dict] = []
|
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 += [k for k in facebook_kpis if k]
|
||||||
|
kpis += [k for k in instagram_kpis if k]
|
||||||
for k in [
|
for k in [
|
||||||
_follower_kpi("YouTube 구독자", youtube.get("subscribers")),
|
_follower_kpi("YouTube 구독자", youtube.get("subscribers")),
|
||||||
_follower_kpi("Instagram KR 팔로워", instagram.get("followers")),
|
|
||||||
_follower_kpi("Instagram EN 팔로워", ig_en.get("followers")),
|
|
||||||
_follower_kpi("Facebook KR 팔로워", facebook.get("followers")),
|
|
||||||
_follower_kpi("Facebook EN 팔로워", fb_en.get("followers")),
|
|
||||||
_follower_kpi("TikTok 팔로워", tiktok.get("followers")),
|
_follower_kpi("TikTok 팔로워", tiktok.get("followers")),
|
||||||
_follower_kpi("Naver Cafe 회원 수", cafe.get("memberCount")),
|
_follower_kpi("Naver Cafe 회원 수", cafe.get("memberCount")),
|
||||||
]:
|
]:
|
||||||
@@ -92,5 +95,5 @@ def build_kpi_dashboard(
|
|||||||
"target_3_month": f"{_round_clean(int(gu_reviews * rm3)):,}개",
|
"target_3_month": f"{_round_clean(int(gu_reviews * rm3)):,}개",
|
||||||
"target_12_month": f"{_round_clean(int(gu_reviews * rm12)):,}개",
|
"target_12_month": f"{_round_clean(int(gu_reviews * rm12)):,}개",
|
||||||
})
|
})
|
||||||
|
print ("kpis", kpis)
|
||||||
return [KPIMetric.model_validate(k).model_dump() for k in kpis]
|
return [KPIMetric.model_validate(k).model_dump() for k in kpis]
|
||||||
@@ -31,7 +31,7 @@ async def run_market_analysis(analysis_run_id: str) -> None:
|
|||||||
run = await select_run(analysis_run_id)
|
run = await select_run(analysis_run_id)
|
||||||
clinic = await select_hospital(run["hospital_id"])
|
clinic = await select_hospital(run["hospital_id"])
|
||||||
raw = await select_run_raw_data(analysis_run_id)
|
raw = await select_run_raw_data(analysis_run_id)
|
||||||
mainpage = raw.get("mainpage") or {}
|
mainpage = ((raw.get("mainpage") or [{}])[0].get("raw_data")) or {}
|
||||||
|
|
||||||
clinic_name = (clinic or {}).get("hospital_name") or ""
|
clinic_name = (clinic or {}).get("hospital_name") or ""
|
||||||
address = (clinic or {}).get("road_address") or ""
|
address = (clinic or {}).get("road_address") or ""
|
||||||
|
|||||||
@@ -0,0 +1,248 @@
|
|||||||
|
"""HTML 정규식 기반 deterministic 추출 — tracking pixels / SNS / additional domains / main CTA."""
|
||||||
|
import re
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
|
||||||
|
# ── tracking pixels ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
# 픽셀별 시그니처: 하나라도 매치되면 installed, ID 는 첫 non-empty 그룹.
|
||||||
|
_TRACKING_PIXEL_PATTERNS: dict[str, list[re.Pattern]] = {
|
||||||
|
"Google Analytics": [
|
||||||
|
re.compile(r"googletagmanager\.com/gtag/js\?id=(G-[A-Z0-9]+)", re.IGNORECASE),
|
||||||
|
re.compile(r"google-analytics\.com/analytics\.js", re.IGNORECASE),
|
||||||
|
re.compile(r"\bgtag\(\s*['\"]config['\"]\s*,\s*['\"](G-[A-Z0-9]+|UA-\d+-\d+)['\"]", re.IGNORECASE),
|
||||||
|
re.compile(r"\b(UA-\d+-\d+)\b"),
|
||||||
|
],
|
||||||
|
"Google Tag Manager": [
|
||||||
|
re.compile(r"googletagmanager\.com/gtm\.js\?id=(GTM-[A-Z0-9]+)", re.IGNORECASE),
|
||||||
|
re.compile(r"\b(GTM-[A-Z0-9]+)\b"),
|
||||||
|
],
|
||||||
|
"Facebook Pixel": [
|
||||||
|
re.compile(r"connect\.facebook\.net/[^/]+/fbevents\.js", re.IGNORECASE),
|
||||||
|
re.compile(r"fbq\(\s*['\"]init['\"]\s*,\s*['\"](\d{10,20})['\"]", re.IGNORECASE),
|
||||||
|
re.compile(r"facebook\.com/tr/?\?id=(\d{10,20})", re.IGNORECASE), # noscript image pixel fallback
|
||||||
|
re.compile(r"_fbq\.push\(\s*\[\s*['\"]init['\"]\s*,\s*['\"](\d{10,20})['\"]", re.IGNORECASE), # legacy
|
||||||
|
],
|
||||||
|
"Naver Analytics": [
|
||||||
|
re.compile(r"wcs\.naver\.net/wcslog\.js", re.IGNORECASE),
|
||||||
|
re.compile(r"\bwcs_add\b", re.IGNORECASE),
|
||||||
|
re.compile(r"\bwcs\.inflow\(", re.IGNORECASE),
|
||||||
|
re.compile(r"wcs_add\s*\[\s*['\"]wa['\"]\s*\]\s*=\s*['\"]([a-zA-Z0-9_]+)['\"]", re.IGNORECASE), # wa ID
|
||||||
|
],
|
||||||
|
"Kakao Pixel": [
|
||||||
|
re.compile(r"t1\.daumcdn\.net/kas/static/kp\.js", re.IGNORECASE),
|
||||||
|
re.compile(r"kakaoPixel\s*\(\s*['\"]?(\d+)['\"]?", re.IGNORECASE),
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def extract_tracking_pixels(html: str) -> list[dict]:
|
||||||
|
"""HTML 에서 트래킹 픽셀 설치 여부 + ID 추출."""
|
||||||
|
if not html:
|
||||||
|
return []
|
||||||
|
pixels: list[dict] = []
|
||||||
|
for name, patterns in _TRACKING_PIXEL_PATTERNS.items():
|
||||||
|
any_match = False
|
||||||
|
captured_id: str | None = None
|
||||||
|
for pat in patterns:
|
||||||
|
m = pat.search(html)
|
||||||
|
if not m:
|
||||||
|
continue
|
||||||
|
any_match = True
|
||||||
|
if m.groups() and m.group(1) and not captured_id:
|
||||||
|
captured_id = m.group(1)
|
||||||
|
if any_match:
|
||||||
|
pixels.append({
|
||||||
|
"name": name,
|
||||||
|
"installed": True,
|
||||||
|
"details": captured_id,
|
||||||
|
})
|
||||||
|
return pixels
|
||||||
|
|
||||||
|
|
||||||
|
# ── main CTA ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
_CTA_KEYWORDS = re.compile(
|
||||||
|
r"(상담|예약|문의|신청|등록|Book\s*Now|Consult|Reservation|Contact|Apply)",
|
||||||
|
re.IGNORECASE,
|
||||||
|
)
|
||||||
|
# CTA 카테고리 우선순위 (전화>카톡>예약). 매치 없으면 결과에 포함 X.
|
||||||
|
_CTA_CATEGORIES: list[tuple[str, re.Pattern]] = [
|
||||||
|
("전화 상담", re.compile(r"전화|\bCall\b|\bPhone\b", re.IGNORECASE)),
|
||||||
|
("카카오톡 상담", re.compile(r"카(카오)?톡|Kakao", re.IGNORECASE)),
|
||||||
|
("온라인 예약", re.compile(r"예약|Reserv|Book", re.IGNORECASE)),
|
||||||
|
]
|
||||||
|
_BUTTON_TAG = re.compile(r"<button\b[^>]*>(.*?)</button>", re.IGNORECASE | re.DOTALL)
|
||||||
|
_ANCHOR_TAG = re.compile(r"<a\b[^>]*>(.*?)</a>", re.IGNORECASE | re.DOTALL)
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_text(inner: str) -> str:
|
||||||
|
text = re.sub(r"<[^>]+>", "", inner)
|
||||||
|
return re.sub(r"\s+", " ", text).strip()
|
||||||
|
|
||||||
|
|
||||||
|
_MAIN_CTA_LIMIT = 3
|
||||||
|
|
||||||
|
|
||||||
|
def _classify_cta(text: str) -> str | None:
|
||||||
|
"""CTA 텍스트 → 카테고리 (전화/카톡/예약). 매치 없으면 None."""
|
||||||
|
for label, pat in _CTA_CATEGORIES:
|
||||||
|
if pat.search(text):
|
||||||
|
return label
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def extract_main_cta(html: str) -> str:
|
||||||
|
"""<button>·<a> 라벨을 카테고리로 분류 후 우선순위 순서로 최대 _MAIN_CTA_LIMIT 개 join."""
|
||||||
|
if not html:
|
||||||
|
return ""
|
||||||
|
found: set[str] = set()
|
||||||
|
for pat in (_BUTTON_TAG, _ANCHOR_TAG):
|
||||||
|
for m in pat.finditer(html):
|
||||||
|
text = _clean_text(m.group(1))
|
||||||
|
if text and 1 <= len(text) <= 20 and _CTA_KEYWORDS.search(text):
|
||||||
|
cat = _classify_cta(text)
|
||||||
|
if cat:
|
||||||
|
found.add(cat)
|
||||||
|
ordered_labels = [label for label, _ in _CTA_CATEGORIES]
|
||||||
|
result = [label for label in ordered_labels if label in found]
|
||||||
|
return " + ".join(result[:_MAIN_CTA_LIMIT])
|
||||||
|
|
||||||
|
|
||||||
|
# ── SNS links ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
# SNS 도메인 → 표준 platform 이름.
|
||||||
|
_SNS_DOMAINS: dict[str, str] = {
|
||||||
|
"facebook.com": "Facebook",
|
||||||
|
"instagram.com": "Instagram",
|
||||||
|
"youtube.com": "YouTube",
|
||||||
|
"youtu.be": "YouTube",
|
||||||
|
"tiktok.com": "TikTok",
|
||||||
|
"pf.kakao.com": "KakaoTalk",
|
||||||
|
"open.kakao.com": "KakaoTalk",
|
||||||
|
"blog.naver.com": "Naver Blog",
|
||||||
|
"cafe.naver.com": "Naver Cafe",
|
||||||
|
"x.com": "X",
|
||||||
|
"twitter.com": "X",
|
||||||
|
}
|
||||||
|
|
||||||
|
_FOOTER_BLOCK = re.compile(r"<footer\b[^>]*>(.*?)</footer>", re.IGNORECASE | re.DOTALL)
|
||||||
|
_HEADER_BLOCK = re.compile(r"<header\b[^>]*>(.*?)</header>", re.IGNORECASE | re.DOTALL)
|
||||||
|
# <a> 태그 안의 href 만 매치 — <link>/<script> 등 리소스 호출 제외 (CDN 노이즈 차단).
|
||||||
|
_ANCHOR_HREF_PATTERN = re.compile(
|
||||||
|
r"""<a\b[^>]*\bhref\s*=\s*['"](https?://[^'"\s]+)['"]""",
|
||||||
|
re.IGNORECASE,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _platform_for(url: str) -> str | None:
|
||||||
|
try:
|
||||||
|
host = urlparse(url).netloc.lower().removeprefix("www.")
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
for domain, name in _SNS_DOMAINS.items():
|
||||||
|
if host == domain or host.endswith("." + domain):
|
||||||
|
return name
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _location_for(url: str, html: str) -> str:
|
||||||
|
"""url 이 <header>/<footer> 블록 안에 있는지 판정 — 둘 다 아니면 'body'."""
|
||||||
|
if not html:
|
||||||
|
return ""
|
||||||
|
needle = re.escape(url)
|
||||||
|
footer = _FOOTER_BLOCK.search(html)
|
||||||
|
if footer and re.search(needle, footer.group(1)):
|
||||||
|
return "footer"
|
||||||
|
header = _HEADER_BLOCK.search(html)
|
||||||
|
if header and re.search(needle, header.group(1)):
|
||||||
|
return "header"
|
||||||
|
return "body"
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_anchor_hrefs(html: str) -> list[str]:
|
||||||
|
"""<a href="http..."> 만 추출 — 순서 보존, 중복 제거."""
|
||||||
|
if not html:
|
||||||
|
return []
|
||||||
|
seen: dict[str, None] = {}
|
||||||
|
for url in _ANCHOR_HREF_PATTERN.findall(html):
|
||||||
|
if url not in seen:
|
||||||
|
seen[url] = None
|
||||||
|
return list(seen.keys())
|
||||||
|
|
||||||
|
|
||||||
|
def extract_sns_links(html: str) -> list[dict]:
|
||||||
|
"""anchor href 에서 SNS 도메인 매칭. 중복 platform 은 첫 URL 만 유지."""
|
||||||
|
seen: dict[str, dict] = {}
|
||||||
|
for url in _extract_anchor_hrefs(html):
|
||||||
|
platform = _platform_for(url)
|
||||||
|
if not platform or platform in seen:
|
||||||
|
continue
|
||||||
|
seen[platform] = {
|
||||||
|
"platform": platform,
|
||||||
|
"url": url,
|
||||||
|
"location": _location_for(url, html),
|
||||||
|
}
|
||||||
|
return list(seen.values())
|
||||||
|
|
||||||
|
|
||||||
|
# ── additional domains (글로벌/다국어 사이트만) ─────────────────────────────────
|
||||||
|
|
||||||
|
# 언어 코드 → 한국어 라벨.
|
||||||
|
_LANG_LABEL: dict[str, str] = {
|
||||||
|
"en": "영어", "eng": "영어",
|
||||||
|
"zh": "중국어", "cn": "중국어", "chn": "중국어",
|
||||||
|
"ja": "일본어", "jp": "일본어",
|
||||||
|
"ko": "한국어", "kor": "한국어", "kr": "한국어",
|
||||||
|
"vi": "베트남어", "vn": "베트남어",
|
||||||
|
"th": "태국어", "thai": "태국어",
|
||||||
|
"ru": "러시아어",
|
||||||
|
"es": "스페인어",
|
||||||
|
"mn": "몽골어",
|
||||||
|
"ar": "아랍어", "arab": "아랍어",
|
||||||
|
"id": "인도네시아어",
|
||||||
|
"de": "독일어",
|
||||||
|
"fr": "프랑스어",
|
||||||
|
"pt": "포르투갈어",
|
||||||
|
}
|
||||||
|
|
||||||
|
_LANG_LI_PATTERN = re.compile(
|
||||||
|
r'<li\b[^>]*\bdata-lang\s*=\s*[\'"]([^\'"]+)[\'"][^>]*>(.*?)</li>',
|
||||||
|
re.IGNORECASE | re.DOTALL,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_additional_domains(html: str, primary_host: str) -> list[dict]:
|
||||||
|
"""글로벌/다국어 사이트 anchor 수집 — data-lang 마커 + URL 서브도메인 prefix 로 식별."""
|
||||||
|
if not html:
|
||||||
|
return []
|
||||||
|
primary = (primary_host or "").lower().removeprefix("www.")
|
||||||
|
seen: dict[str, dict] = {}
|
||||||
|
|
||||||
|
def add(host: str, lang_kr: str):
|
||||||
|
host = host.lower().removeprefix("www.")
|
||||||
|
if not host or host == primary or host in seen:
|
||||||
|
return
|
||||||
|
seen[host] = {"domain": host, "purpose": lang_kr}
|
||||||
|
|
||||||
|
# 1) <li data-lang="xx"> 안의 anchor
|
||||||
|
for m in _LANG_LI_PATTERN.finditer(html):
|
||||||
|
lang_kr = _LANG_LABEL.get(m.group(1).lower())
|
||||||
|
if not lang_kr:
|
||||||
|
continue
|
||||||
|
a_m = re.search(r'<a[^>]*href\s*=\s*[\'"](https?://[^\'"\s]+)[\'"]', m.group(2), re.IGNORECASE)
|
||||||
|
if a_m:
|
||||||
|
add(urlparse(a_m.group(1)).netloc, lang_kr)
|
||||||
|
|
||||||
|
# 2) URL 서브도메인 prefix 가 언어 코드
|
||||||
|
for url in _extract_anchor_hrefs(html):
|
||||||
|
host = urlparse(url).netloc.lower().removeprefix("www.")
|
||||||
|
parts = host.split(".")
|
||||||
|
if len(parts) >= 3:
|
||||||
|
lang_kr = _LANG_LABEL.get(parts[0])
|
||||||
|
if lang_kr:
|
||||||
|
add(host, lang_kr)
|
||||||
|
|
||||||
|
return list(seen.values())
|
||||||
|
|
||||||
|
|
||||||
@@ -12,3 +12,8 @@ services:
|
|||||||
volumes:
|
volumes:
|
||||||
- ./app:/app
|
- ./app:/app
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
networks:
|
||||||
|
- o2o-net
|
||||||
|
networks:
|
||||||
|
o2o-net:
|
||||||
|
# external: true
|
||||||
Reference in new issue
Block a user