Merge branch 'wip/channel-brand-2026-05-29'
채널 확장 + 브랜드 자산 파이프라인을 main에 통합. 신규/주요 변경: - 5채널 외 부가 수집 (틱톡/IG·FB 영문/네이버 카페/카카오톡) — collect_extras.py - 브랜드 자산: 홈페이지 로고 URL + CSS 색상 추출 (color_extractor.py) + Gemini Vision 로고 묘사 (vision.py) - 채널 로고 비교: 공식 로고와 각 채널 프로필 이미지 일치 여부 평가 - 인스타/페북 audit 빌더 분리 (instagram_audit.py, facebook_audit.py) - mock_urls.py: 78개 병원 영문 채널 51건 + 필드 캐노니컬 순서 정규화 - ReportInput/PlanInput 신규 채널 필드 추가 - ChannelBrandingRule literal "missing" → "N/A" teammate eed5772와의 conflict 해결: - ClinicSnapshot/YouTubeAudit: teammate가 신뢰 못하는 필드 제거 (established/years_in_business/price_range/media_appearances/medical_tourism/nearest_station/subscriber_rank) - services/analysis.py: teammate의 _build_clinic_snapshot/_build_youtube_audit/duration helpers + 우리의 _naver_blog_summary 둘 다 보존 - imports: youtube_diagnosis_prompt + build_instagram_accounts/build_facebook_pages 모두 채택 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
commit
71b605eaa6
26 files changed
+2904
-125
No files matched your search
+148
-80
@@ -1,16 +1,32 @@
|
||||
import asyncio
|
||||
from http import HTTPMethod
|
||||
from urllib.parse import urlparse
|
||||
from common.utils import http_request
|
||||
|
||||
APIFY_BASE = "https://api.apify.com/v2"
|
||||
|
||||
# Instagram: profile + highlights 두 actor 직접 호출.
|
||||
IG_PROFILE_ACTOR = "coderx~instagram-profile-scraper-bio-posts"
|
||||
IG_HIGHLIGHTS_ACTOR = "igview-owner~instagram-highlights-scraper"
|
||||
|
||||
# Facebook: pages + posts 두 actor 직접 호출.
|
||||
FB_PAGES_ACTOR = "apify~facebook-pages-scraper"
|
||||
FB_POSTS_ACTOR = "apify~facebook-posts-scraper"
|
||||
|
||||
# TikTok
|
||||
TIKTOK_ACTOR = "clockworks~tiktok-scraper"
|
||||
|
||||
|
||||
def _ig_username(url: str) -> str:
|
||||
return urlparse(url).path.strip("/").split("/")[0] if "://" in url else url.lstrip("@")
|
||||
|
||||
|
||||
class ApifyClient:
|
||||
def __init__(self, token: str, wait_for_finish: int = 120):
|
||||
self.token = token
|
||||
self.wait_for_finish = wait_for_finish
|
||||
|
||||
async def _run_actor(self, actor_id: str, input_data: dict) -> list[dict]:
|
||||
async def _run_actor(self, actor_id: str, input_data: dict, limit: int = 20) -> list[dict]:
|
||||
resp = await http_request(
|
||||
HTTPMethod.POST,
|
||||
url=f"{APIFY_BASE}/acts/{actor_id}/runs",
|
||||
@@ -26,33 +42,53 @@ class ApifyClient:
|
||||
items_resp = await http_request(
|
||||
HTTPMethod.GET,
|
||||
url=f"{APIFY_BASE}/datasets/{dataset_id}/items",
|
||||
params={"token": self.token, "limit": 20},
|
||||
params={"token": self.token, "limit": limit},
|
||||
label=f"apify-dataset-{dataset_id}",
|
||||
)
|
||||
if not items_resp or not items_resp.is_success:
|
||||
return []
|
||||
return items_resp.json()
|
||||
|
||||
async def fetch_instagram_profile(self, url: str) -> dict | None:
|
||||
username = urlparse(url).path.strip("/").split("/")[0] if "://" in url else url.lstrip("@")
|
||||
items = await self._run_actor("apify~instagram-profile-scraper", {"usernames": [username], "resultsLimit": 12})
|
||||
async def fetch_instagram_profile(self, username: str) -> dict | None:
|
||||
items = await self._run_actor(IG_PROFILE_ACTOR, {"usernames": [username]})
|
||||
return items[0] if items else None
|
||||
|
||||
async def fetch_instagram_highlights(self, username: str) -> list[dict]:
|
||||
return await self._run_actor(IG_HIGHLIGHTS_ACTOR, {"usernames": [username]})
|
||||
|
||||
async def get_instagram_profile(self, url: str) -> dict | None:
|
||||
profile = await self.fetch_instagram_profile(url)
|
||||
if not profile or profile.get("error"):
|
||||
username = _ig_username(url)
|
||||
# profile·highlights 두 actor를 병렬 호출 (highlights 실패해도 profile만 있으면 진행)
|
||||
profile, highlights = await asyncio.gather(
|
||||
self.fetch_instagram_profile(username),
|
||||
self.fetch_instagram_highlights(username),
|
||||
return_exceptions=True,
|
||||
)
|
||||
if isinstance(profile, Exception) or not profile or profile.get("error"):
|
||||
return None
|
||||
if isinstance(highlights, Exception):
|
||||
highlights = []
|
||||
# 프로필상 하이라이트가 있다고 하면(highlight_reel_count>0) 빈 결과일 때 최대 2회 재시도.
|
||||
if not highlights and (profile.get("highlight_reel_count", 0) or profile.get("highlightReelCount", 0)) > 0:
|
||||
for _ in range(2):
|
||||
retry = await self.fetch_instagram_highlights(username)
|
||||
if retry:
|
||||
highlights = retry
|
||||
break
|
||||
return {
|
||||
"username": profile["username"],
|
||||
"profileImage": profile.get("hdProfilePicUrl") or profile.get("profilePicUrl"),
|
||||
"followers": profile.get("followersCount", 0),
|
||||
"following": profile.get("followsCount", 0),
|
||||
"posts": profile.get("postsCount", 0),
|
||||
"bio": profile.get("biography", ""),
|
||||
"category": profile.get("businessCategoryName") or "",
|
||||
"isBusinessAccount": profile.get("isBusinessAccount", False),
|
||||
#"externalUrl": profile.get("externalUrl"), LLM에 혼동을 주는 듯 하여 비활성화
|
||||
#"externalUrl": profile.get("externalUrl"), LLM에 혼동을 주는 듯 하여 비활성화
|
||||
"highlights": [h["highlightTitle"] for h in (highlights or []) if isinstance(h, dict) and h.get("highlightTitle")],
|
||||
"latestPosts": [
|
||||
{
|
||||
"type": p.get("type"),
|
||||
"type": p.get("mediaType") or p.get("type"),
|
||||
"likes": p.get("likesCount", 0),
|
||||
"comments": p.get("commentsCount", 0),
|
||||
"caption": (p.get("caption") or "")[:500],
|
||||
@@ -62,87 +98,119 @@ class ApifyClient:
|
||||
],
|
||||
}
|
||||
|
||||
async def fetch_instagram_posts(self, url: str, limit: int = 20) -> list[dict]:
|
||||
username = urlparse(url).path.strip("/").split("/")[0] if "://" in url else url.lstrip("@")
|
||||
return await self._run_actor("apify~instagram-post-scraper", {
|
||||
"username": [f"https://www.instagram.com/{username}/"],
|
||||
"resultsLimit": limit,
|
||||
})
|
||||
|
||||
async def get_instagram_posts(self, url: str, limit: int = 20) -> dict:
|
||||
items = await self.fetch_instagram_posts(url, limit)
|
||||
posts = [
|
||||
{
|
||||
"id": p["id"],
|
||||
"type": p.get("type"),
|
||||
"url": p.get("url"),
|
||||
"caption": (p.get("caption") or "")[:500],
|
||||
"hashtags": p.get("hashtags", []),
|
||||
"likesCount": p.get("likesCount", 0),
|
||||
"commentsCount": p.get("commentsCount", 0),
|
||||
"timestamp": p.get("timestamp"),
|
||||
}
|
||||
for p in items
|
||||
]
|
||||
n = len(posts) or 1
|
||||
return {
|
||||
"posts": posts,
|
||||
"totalPosts": len(posts),
|
||||
"avgLikes": round(sum(p["likesCount"] for p in posts) / n),
|
||||
"avgComments": round(sum(p["commentsCount"] for p in posts) / n),
|
||||
}
|
||||
|
||||
async def fetch_instagram_reels(self, url: str, limit: int = 15) -> list[dict]:
|
||||
username = urlparse(url).path.strip("/").split("/")[0] if "://" in url else url.lstrip("@")
|
||||
print(username)
|
||||
return await self._run_actor("apify~instagram-reel-scraper", {
|
||||
"username": [f"https://www.instagram.com/{username}/reels/"],
|
||||
"resultsLimit": limit,
|
||||
})
|
||||
|
||||
async def get_instagram_reels(self, url: str, limit: int = 15) -> dict:
|
||||
items = await self.fetch_instagram_reels(url, limit)
|
||||
reels = [
|
||||
{
|
||||
"id": r["id"],
|
||||
"url": r.get("url"),
|
||||
"caption": (r.get("caption") or "")[:500],
|
||||
"hashtags": r.get("hashtags", []),
|
||||
"likesCount": r.get("likesCount", 0),
|
||||
"commentsCount": r.get("commentsCount", 0),
|
||||
"videoViewCount": r.get("videoViewCount", 0),
|
||||
"videoPlayCount": r.get("videoPlayCount", 0),
|
||||
"videoDuration": r.get("videoDuration", 0),
|
||||
"timestamp": r.get("timestamp"),
|
||||
}
|
||||
for r in items
|
||||
]
|
||||
n = len(reels) or 1
|
||||
return {
|
||||
"reels": reels,
|
||||
"totalReels": len(reels),
|
||||
"avgViews": round(sum(r["videoViewCount"] for r in reels) / n),
|
||||
"avgPlays": round(sum(r["videoPlayCount"] for r in reels) / n),
|
||||
}
|
||||
# 인스타 post 스크래퍼는 현재 파이프라인 미사용 — 비활성화 (필요 시 복구)
|
||||
# async def fetch_instagram_posts(self, url: str, limit: int = 20) -> list[dict]:
|
||||
# username = urlparse(url).path.strip("/").split("/")[0] if "://" in url else url.lstrip("@")
|
||||
# return await self._run_actor("apify~instagram-post-scraper", {
|
||||
# "directUrls": [f"https://www.instagram.com/{username}/"],
|
||||
# "resultsLimit": limit,
|
||||
# })
|
||||
#
|
||||
# async def get_instagram_posts(self, url: str, limit: int = 20) -> dict:
|
||||
# items = await self.fetch_instagram_posts(url, limit)
|
||||
# posts = [
|
||||
# {
|
||||
# "id": p["id"],
|
||||
# "type": p.get("type"),
|
||||
# "url": p.get("url"),
|
||||
# "caption": (p.get("caption") or "")[:500],
|
||||
# "hashtags": p.get("hashtags", []),
|
||||
# "likesCount": p.get("likesCount", 0),
|
||||
# "commentsCount": p.get("commentsCount", 0),
|
||||
# "timestamp": p.get("timestamp"),
|
||||
# }
|
||||
# for p in items
|
||||
# ]
|
||||
# n = len(posts) or 1
|
||||
# return {
|
||||
# "posts": posts,
|
||||
# "totalPosts": len(posts),
|
||||
# "avgLikes": round(sum(p["likesCount"] for p in posts) / n),
|
||||
# "avgComments": round(sum(p["commentsCount"] for p in posts) / n),
|
||||
# }
|
||||
|
||||
async def fetch_facebook_page(self, page_url: str) -> dict | None:
|
||||
items = await self._run_actor("apify~facebook-pages-scraper", {"startUrls": [{"url": page_url}]})
|
||||
items = await self._run_actor(FB_PAGES_ACTOR, {"startUrls": [{"url": page_url}]})
|
||||
return items[0] if items else None
|
||||
|
||||
async def fetch_facebook_posts(self, page_url: str, limit: int = 20) -> list[dict]:
|
||||
return await self._run_actor(
|
||||
FB_POSTS_ACTOR, {"startUrls": [{"url": page_url}], "resultsLimit": limit}, limit=limit,
|
||||
)
|
||||
|
||||
async def get_facebook_page(self, page_url: str) -> dict | None:
|
||||
page = await self.fetch_facebook_page(page_url)
|
||||
if not page:
|
||||
# pages·posts 두 task 병렬 호출 (posts 실패해도 page만 있으면 진행)
|
||||
page, posts = await asyncio.gather(
|
||||
self.fetch_facebook_page(page_url),
|
||||
self.fetch_facebook_posts(page_url),
|
||||
return_exceptions=True,
|
||||
)
|
||||
if isinstance(page, Exception) or not page:
|
||||
return None
|
||||
if isinstance(posts, Exception):
|
||||
posts = []
|
||||
return {
|
||||
"pageName": page.get("title") or page.get("name"),
|
||||
"profileImage": page.get("profilePictureUrl") or page.get("profilePhoto") or page.get("profilePic"),
|
||||
"pageUrl": page.get("pageUrl", page_url),
|
||||
"followers": page.get("followers", 0),
|
||||
"likes": page.get("likes", 0),
|
||||
"following": page.get("followings", 0),
|
||||
"reviews": page.get("ratingCount", 0),
|
||||
"categories": page.get("categories", []),
|
||||
"email": page.get("email"),
|
||||
"phone": page.get("phone"),
|
||||
"website": page.get("website"),
|
||||
"address": page.get("address"),
|
||||
"website": page.get("website") or page.get("websites"),
|
||||
"intro": page.get("intro"),
|
||||
"rating": page.get("rating"),
|
||||
"latestPosts": [
|
||||
{
|
||||
"text": (p.get("text") or "")[:160],
|
||||
"likes": p.get("likes", 0),
|
||||
"reactions": p.get("topReactionsCount", 0),
|
||||
"shares": p.get("shares", 0),
|
||||
"views": p.get("viewsCount") or 0,
|
||||
"isVideo": p.get("isVideo", False),
|
||||
"timestamp": p.get("time") or p.get("timestamp"),
|
||||
}
|
||||
for p in (posts or []) if isinstance(p, dict)
|
||||
],
|
||||
}
|
||||
|
||||
async def fetch_tiktok_profile(self, url: str) -> list[dict]:
|
||||
user = urlparse(url).path.strip("/").lstrip("@").split("/")[0] if "://" in url else url.lstrip("@")
|
||||
return await self._run_actor(TIKTOK_ACTOR, {
|
||||
"profiles": [user],
|
||||
"resultsPerPage": 10,
|
||||
"profileScrapeSections": ["videos"],
|
||||
"profileSorting": "latest",
|
||||
"shouldDownloadVideos": False,
|
||||
"shouldDownloadCovers": False,
|
||||
"shouldDownloadSubtitles": False,
|
||||
})
|
||||
|
||||
async def get_tiktok_profile(self, url: str) -> dict | None:
|
||||
items = await self.fetch_tiktok_profile(url)
|
||||
if not items:
|
||||
return None
|
||||
author = (items[0] or {}).get("authorMeta") or {}
|
||||
videos = [
|
||||
{
|
||||
"title": (v.get("text") or "")[:300],
|
||||
"playCount": v.get("playCount", 0),
|
||||
"diggCount": v.get("diggCount", 0),
|
||||
"commentCount": v.get("commentCount", 0),
|
||||
"shareCount": v.get("shareCount", 0),
|
||||
"createTime": v.get("createTimeISO"),
|
||||
"url": v.get("webVideoUrl"),
|
||||
}
|
||||
for v in items if isinstance(v, dict)
|
||||
]
|
||||
return {
|
||||
"handle": author.get("name"),
|
||||
"profileImage": author.get("avatar"),
|
||||
"nickname": author.get("nickName"),
|
||||
"followers": author.get("fans", 0),
|
||||
"following": author.get("following", 0),
|
||||
"likes": author.get("heart", 0),
|
||||
"videoCount": author.get("video", 0),
|
||||
"verified": author.get("verified", False),
|
||||
"bio": author.get("signature", ""),
|
||||
"recentVideos": videos[:10],
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
"""홈페이지 HTML/CSS에서 hex 색상 직접 추출 + 빈도 기반 brand palette 산출.
|
||||
|
||||
Vision LLM에 의존하지 않고 페이지의 실제 CSS 값을 정규식으로 잡음.
|
||||
로고만 분석하는 Vision보다 사이트 전체 컬러 시스템 (primary/secondary/background/text)을 더 정확히 추출.
|
||||
"""
|
||||
import logging
|
||||
import re
|
||||
import ssl
|
||||
from collections import Counter
|
||||
from urllib.parse import urljoin, urlparse
|
||||
import httpx
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _make_ssl_context() -> ssl.SSLContext:
|
||||
"""오래된 한국 의료 사이트들이 SSL DH_KEY_TOO_SMALL / cipher 약함 등으로 차단되는 문제 우회.
|
||||
보안 등급 1로 낮춤 + cert 검증 유지."""
|
||||
ctx = ssl.create_default_context()
|
||||
try:
|
||||
ctx.set_ciphers("DEFAULT@SECLEVEL=1")
|
||||
except ssl.SSLError:
|
||||
pass
|
||||
return ctx
|
||||
|
||||
|
||||
async def _fetch_html(url: str, timeout: float = 20.0) -> tuple[int, str]:
|
||||
"""SSL/검증 단계별 fallback으로 HTML 받기. 그랜드/톡스앤필 같은 oldsite 대응."""
|
||||
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36"}
|
||||
# 1차: 표준 검증
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True, headers=headers) as c:
|
||||
r = await c.get(url)
|
||||
return r.status_code, r.text
|
||||
except (httpx.ConnectError, httpx.ReadError, ssl.SSLError) as e:
|
||||
logger.info("[fetch] %s standard SSL failed: %s — fallback to weak cipher", url, e)
|
||||
# 2차: 약한 cipher 허용
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True, headers=headers, verify=_make_ssl_context()) as c:
|
||||
r = await c.get(url)
|
||||
return r.status_code, r.text
|
||||
except (httpx.ConnectError, httpx.ReadError, ssl.SSLError) as e:
|
||||
logger.info("[fetch] %s weak cipher failed: %s — fallback to verify=False", url, e)
|
||||
# 3차: SSL 검증 끔 (host mismatch 등)
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True, headers=headers, verify=False) as c:
|
||||
r = await c.get(url)
|
||||
return r.status_code, r.text
|
||||
except Exception as e:
|
||||
logger.warning("[fetch] %s all fallbacks failed: %s", url, e)
|
||||
return 0, ""
|
||||
|
||||
LOGO_IMG_PATTERNS = [
|
||||
# 1) <img class="...logo..." src="...">
|
||||
re.compile(r'<img[^>]*\bclass=["\'][^"\']*\blogo\b[^"\']*["\'][^>]*\bsrc=["\']([^"\']+)["\']', re.IGNORECASE),
|
||||
# 2) <img src="..." class="...logo...">
|
||||
re.compile(r'<img[^>]*\bsrc=["\']([^"\']+)["\'][^>]*\bclass=["\'][^"\']*\blogo\b[^"\']*["\']', re.IGNORECASE),
|
||||
# 3) <img id="...logo..." src="...">
|
||||
re.compile(r'<img[^>]*\bid=["\'][^"\']*\blogo\b[^"\']*["\'][^>]*\bsrc=["\']([^"\']+)["\']', re.IGNORECASE),
|
||||
# 4) <img alt="...logo..." src="...">
|
||||
re.compile(r'<img[^>]*\balt=["\'][^"\']*\blogo\b[^"\']*["\'][^>]*\bsrc=["\']([^"\']+)["\']', re.IGNORECASE),
|
||||
# 5) <a/h1 class="logo"><...nested...><img src="...">
|
||||
re.compile(r'<(?:a|h[1-6]|div|span)[^>]*\b(?:class|id)=["\'][^"\']*\blogo\b[^"\']*["\'][^>]*>(?:[^<]|<(?!img))*<img[^>]*\bsrc=["\']([^"\']+)["\']', re.IGNORECASE | re.DOTALL),
|
||||
# 6) inline background-image: <a/div class="logo" style="background-image: url(...)">
|
||||
re.compile(r'<(?:a|div|span|h[1-6])[^>]*\b(?:class|id)=["\'][^"\']*\blogo\b[^"\']*["\'][^>]*\bstyle=["\'][^"\']*background(?:-image)?\s*:\s*url\(\s*["\']?([^"\')\s]+)', re.IGNORECASE),
|
||||
# 7) inline background-image: <a/div style="background-image: url(...)" class="logo"> (속성 순서 반대)
|
||||
re.compile(r'<(?:a|div|span|h[1-6])[^>]*\bstyle=["\'][^"\']*background(?:-image)?\s*:\s*url\(\s*["\']?([^"\')\s]+)[^"\']*["\'][^>]*\b(?:class|id)=["\'][^"\']*\blogo\b', re.IGNORECASE),
|
||||
# 8) src 자체에 "logo" 포함 (header_logo.png, brand-logo.svg 등)
|
||||
re.compile(r'<img[^>]*\bsrc=["\']([^"\']*\blogo\b[^"\']*\.(?:png|svg|jpe?g|webp)[^"\']*)["\']', re.IGNORECASE),
|
||||
# 9) <header>...<img src="..."> (헤더 영역 첫 img)
|
||||
re.compile(r'<header\b[^>]*>(?:[^<]|<(?!img))*<img[^>]*\bsrc=["\']([^"\']+\.(?:png|svg|jpe?g|webp)[^"\']*)["\']', re.IGNORECASE | re.DOTALL),
|
||||
# 10) <nav>...<img src="..."> (nav 영역 첫 img)
|
||||
re.compile(r'<nav\b[^>]*>(?:[^<]|<(?!img))*<img[^>]*\bsrc=["\']([^"\']+\.(?:png|svg|jpe?g|webp)[^"\']*)["\']', re.IGNORECASE | re.DOTALL),
|
||||
# 11) Open Graph image (대표 이미지) - 최후 fallback
|
||||
re.compile(r'<meta[^>]*\bproperty=["\']og:image["\'][^>]*\bcontent=["\']([^"\']+)["\']', re.IGNORECASE),
|
||||
re.compile(r'<meta[^>]*\bcontent=["\']([^"\']+)["\'][^>]*\bproperty=["\']og:image["\']', re.IGNORECASE),
|
||||
]
|
||||
|
||||
# CSS 파일에서 .logo { background-image: url(...) } 추출용
|
||||
LOGO_CSS_PATTERN = re.compile(
|
||||
r'\.[\w-]*\blogo\b[\w-]*\s*(?:,\s*\.[\w-]+\s*)*\{[^}]*background(?:-image)?\s*:\s*url\(\s*["\']?([^"\')\s]+)',
|
||||
re.IGNORECASE | re.DOTALL,
|
||||
)
|
||||
|
||||
|
||||
def find_logo_url_in_html(html: str, base_url: str, css_texts: list[str] | None = None) -> str | None:
|
||||
"""HTML에서 logo URL 찾기. 우선순위:
|
||||
1) 패턴 1~8 (class/id/alt/src에 'logo' 명시된 img — 가장 specific)
|
||||
2) 외부 CSS의 .logo background-image (class-based, 더 specific)
|
||||
3) 패턴 9~10 (<header>/<nav> 안 첫 img — 가장 generic, 잘못 잡힐 위험 큼)
|
||||
"""
|
||||
|
||||
def _is_noise(src: str) -> bool:
|
||||
"""logo로 잘못 잡힐 가능성 높은 URL 패턴 — lang/flag/icon/arrow/spacer 등."""
|
||||
if not src or src.startswith("data:"):
|
||||
return True
|
||||
if re.search(r"(blank|spacer|pixel|transparent|1x1)\b", src, re.IGNORECASE):
|
||||
return True
|
||||
# 헤더 첫 img가 lang flag / 검색 아이콘 / 네비 화살표인 경우 (JK plastic 한국어 깃발이 잡히던 케이스)
|
||||
if re.search(r"(lang[-_]?(kor|eng|chn|jpn|rus|jp|en|ko|cn|ar|in)|flag|country|icon-|btn-|arrow|prev|next|search)\b", src, re.IGNORECASE):
|
||||
return True
|
||||
return False
|
||||
|
||||
# 1) class/id/alt/src/inline-bg/src-with-logo 패턴 (1~8)
|
||||
for pat in LOGO_IMG_PATTERNS[:8]:
|
||||
for m in pat.finditer(html):
|
||||
src = m.group(1)
|
||||
if _is_noise(src):
|
||||
continue
|
||||
return urljoin(base_url, src)
|
||||
|
||||
# 2) 외부 CSS의 .logo { background-image } — class-based 이므로 generic 패턴보다 우선
|
||||
for css in (css_texts or []):
|
||||
m = LOGO_CSS_PATTERN.search(css)
|
||||
if m:
|
||||
src = m.group(1)
|
||||
if not _is_noise(src):
|
||||
return urljoin(base_url, src)
|
||||
|
||||
# 3) header/nav 첫 img — 가장 generic, lang flag 등 noise 필터 강화 적용
|
||||
for pat in LOGO_IMG_PATTERNS[8:]:
|
||||
for m in pat.finditer(html):
|
||||
src = m.group(1)
|
||||
if _is_noise(src):
|
||||
continue
|
||||
return urljoin(base_url, src)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
HEX6 = re.compile(r"#([0-9a-fA-F]{6})\b")
|
||||
HEX3 = re.compile(r"#([0-9a-fA-F]{3})\b(?![0-9a-fA-F])")
|
||||
RGB = re.compile(r"rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*[\d.]+\s*)?\)")
|
||||
CSS_VAR_HEX = re.compile(r"--[\w-]+\s*:\s*(#[0-9a-fA-F]{3,8})", re.IGNORECASE)
|
||||
CSS_LINK = re.compile(r'<link[^>]+rel=["\']stylesheet["\'][^>]+href=["\']([^"\']+)["\']', re.IGNORECASE)
|
||||
STYLE_BLOCK = re.compile(r"<style[^>]*>(.*?)</style>", re.IGNORECASE | re.DOTALL)
|
||||
|
||||
# 무채색·아주 흔한 노이즈 컬러 (이런 건 brand color로 잡지 않음)
|
||||
NOISE = {
|
||||
"#ffffff", "#000000", "#fff", "#000",
|
||||
"#333", "#222", "#111", "#444", "#555", "#666", "#777", "#888", "#999",
|
||||
"#aaa", "#bbb", "#ccc", "#ddd", "#eee", "#f0f0f0", "#f5f5f5", "#fafafa",
|
||||
}
|
||||
|
||||
|
||||
def _normalize(hex_str: str) -> str:
|
||||
h = hex_str.lstrip("#").lower()
|
||||
if len(h) == 3:
|
||||
h = "".join(c * 2 for c in h)
|
||||
if len(h) == 8:
|
||||
h = h[:6]
|
||||
return f"#{h}"
|
||||
|
||||
|
||||
def _rgb_to_hex(r: int, g: int, b: int) -> str:
|
||||
return f"#{r:02x}{g:02x}{b:02x}"
|
||||
|
||||
|
||||
def _hex_to_rgb(h: str) -> tuple[int, int, int]:
|
||||
h = h.lstrip("#")
|
||||
return int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)
|
||||
|
||||
|
||||
def _distance(a: str, b: str) -> float:
|
||||
ar, ag, ab = _hex_to_rgb(a)
|
||||
br, bg, bb = _hex_to_rgb(b)
|
||||
return ((ar - br) ** 2 + (ag - bg) ** 2 + (ab - bb) ** 2) ** 0.5
|
||||
|
||||
|
||||
def _is_grayscale(h: str, tol: int = 12) -> bool:
|
||||
r, g, b = _hex_to_rgb(h)
|
||||
return max(r, g, b) - min(r, g, b) < tol
|
||||
|
||||
|
||||
def _extract_hex(text: str) -> list[str]:
|
||||
"""텍스트에서 모든 hex 색상 추출 (정규화)."""
|
||||
out: list[str] = []
|
||||
out.extend(_normalize(m.group(0)) for m in HEX6.finditer(text))
|
||||
out.extend(_normalize(m.group(0)) for m in HEX3.finditer(text))
|
||||
for m in RGB.finditer(text):
|
||||
r, g, b = int(m.group(1)), int(m.group(2)), int(m.group(3))
|
||||
if 0 <= r <= 255 and 0 <= g <= 255 and 0 <= b <= 255:
|
||||
out.append(_rgb_to_hex(r, g, b))
|
||||
return out
|
||||
|
||||
|
||||
def _cluster(colors: Counter, threshold: float = 25.0) -> list[tuple[str, int]]:
|
||||
"""비슷한 색은 묶음. 가장 빈도 높은 색을 대표로."""
|
||||
ranked = colors.most_common()
|
||||
clusters: list[tuple[str, int]] = []
|
||||
for color, count in ranked:
|
||||
merged = False
|
||||
for i, (rep, rep_count) in enumerate(clusters):
|
||||
if _distance(color, rep) < threshold:
|
||||
clusters[i] = (rep, rep_count + count)
|
||||
merged = True
|
||||
break
|
||||
if not merged:
|
||||
clusters.append((color, count))
|
||||
return clusters
|
||||
|
||||
|
||||
async def _fetch_html_and_css(homepage_url: str, max_css_files: int = 8) -> tuple[str, list[str]]:
|
||||
"""홈페이지 HTML + 외부 CSS(Top N)를 한 번에 fetch. 로고/색상 추출이 사이트를 중복으로 긁지 않도록 공유.
|
||||
_fetch_html이 SSL 약함/host mismatch까지 fallback 처리. 실패 시 ("", [])."""
|
||||
status, html = await _fetch_html(homepage_url)
|
||||
if status != 200 or not html:
|
||||
logger.warning("[color_extractor] homepage fetch failed status=%s url=%s", status, homepage_url)
|
||||
return "", []
|
||||
css_texts: list[str] = []
|
||||
for css_href in CSS_LINK.findall(html)[:max_css_files]:
|
||||
cstatus, ctext = await _fetch_html(urljoin(homepage_url, css_href), timeout=15.0)
|
||||
if cstatus == 200 and ctext:
|
||||
css_texts.append(ctext)
|
||||
return html, css_texts
|
||||
|
||||
|
||||
def _colors_from_text(html: str, css_texts: list[str], source_url: str = "") -> dict:
|
||||
"""이미 받아온 HTML + CSS 텍스트에서 hex 빈도 분석 → primary/accent/text + palette. (fetch 없음, 순수 계산)"""
|
||||
# 1. HTML 내 <style> 블록 + 통째(inline style="color:#...") + 외부 CSS
|
||||
all_text_chunks: list[str] = list(STYLE_BLOCK.findall(html))
|
||||
all_text_chunks.append(html)
|
||||
all_text_chunks.extend(css_texts)
|
||||
|
||||
# 2. 모든 hex 추출 (NOISE 제외)
|
||||
counter: Counter = Counter()
|
||||
for text in all_text_chunks:
|
||||
for color in _extract_hex(text):
|
||||
if color in NOISE:
|
||||
continue
|
||||
counter[color] += 1
|
||||
|
||||
if not counter:
|
||||
logger.info("[color_extractor] no colors extracted from %s", source_url)
|
||||
return {}
|
||||
|
||||
# 3. 비슷한 색 클러스터링
|
||||
clustered = _cluster(counter)
|
||||
|
||||
# 4. primary = 빈도 높은 채도 있는 색 / accent = 두번째 채도 있는 색 / text = 빈도 높은 무채색
|
||||
chromatic = [c for c, _ in clustered if not _is_grayscale(c)]
|
||||
grayscale = [c for c, _ in clustered if _is_grayscale(c)]
|
||||
|
||||
palette_top = clustered[:8]
|
||||
palette = [{"name": f"색상 {i+1}", "hex": h, "usage": f"빈도 {n}"} for i, (h, n) in enumerate(palette_top)]
|
||||
|
||||
return {
|
||||
"brand_colors": {
|
||||
"primary": chromatic[0] if chromatic else None,
|
||||
"accent": chromatic[1] if len(chromatic) > 1 else None,
|
||||
"text": grayscale[0] if grayscale else None,
|
||||
},
|
||||
"color_palette": palette,
|
||||
"extracted_from": "html+css",
|
||||
}
|
||||
|
||||
|
||||
async def extract_brand_colors_from_site(homepage_url: str, max_css_files: int = 8) -> dict:
|
||||
"""홈페이지 HTML + 외부 CSS fetch → hex 색상 빈도 분석 → primary/accent/text + palette 5종."""
|
||||
html, css_texts = await _fetch_html_and_css(homepage_url, max_css_files)
|
||||
if not html:
|
||||
return {}
|
||||
return _colors_from_text(html, css_texts, homepage_url)
|
||||
|
||||
|
||||
async def extract_brand_assets_from_site(homepage_url: str, max_css_files: int = 8) -> dict:
|
||||
"""사이트를 한 번만 fetch해서 로고 URL과 brand 색상을 함께 추출.
|
||||
반환: {"logo_url": str | None, "colors": {brand_colors, color_palette, ...} | {}}"""
|
||||
html, css_texts = await _fetch_html_and_css(homepage_url, max_css_files)
|
||||
if not html:
|
||||
return {"logo_url": None, "colors": {}}
|
||||
return {
|
||||
"logo_url": find_logo_url_in_html(html, homepage_url, css_texts=css_texts),
|
||||
"colors": _colors_from_text(html, css_texts, homepage_url),
|
||||
}
|
||||
@@ -76,7 +76,7 @@ class FirecrawlClient:
|
||||
"url": url,
|
||||
"formats": ["json", "links"],
|
||||
"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, 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": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -119,6 +119,7 @@ class FirecrawlClient:
|
||||
"headingFont": {"type": "string"},
|
||||
"bodyFont": {"type": "string"},
|
||||
"logoUrl": {"type": "string"},
|
||||
"ogImage": {"type": "string"},
|
||||
"faviconUrl": {"type": "string"},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -15,6 +15,14 @@ class PlanInput(BaseModel):
|
||||
market_keywords: str | None = None
|
||||
market_trend: str | None = None
|
||||
market_target_audience: str | None = None
|
||||
tiktok: str | None = None
|
||||
instagram_en: str | None = None
|
||||
facebook_en: str | None = None
|
||||
naver_blog: str | None = None
|
||||
naver_cafe: str | None = None
|
||||
kakao_talk: str | None = None
|
||||
channel_logos: str | None = None
|
||||
brand_assets: str | None = None
|
||||
|
||||
|
||||
# --- BrandGuide ---
|
||||
@@ -51,7 +59,7 @@ class ChannelBrandingRule(BaseModel):
|
||||
profile_photo: str
|
||||
banner_spec: str
|
||||
bio_template: str
|
||||
current_status: Literal["correct", "incorrect", "missing"]
|
||||
current_status: Literal["correct", "incorrect", "N/A"]
|
||||
|
||||
|
||||
class BrandPlanInconsistencyValue(BaseModel):
|
||||
|
||||
@@ -314,6 +314,14 @@ class ReportInput(BaseModel):
|
||||
market_keywords: str | None = None
|
||||
market_trend: str | None = None
|
||||
market_target_audience: str | None = None
|
||||
branding: str | None = None
|
||||
brand_assets: str | None = None
|
||||
tiktok: str | None = None
|
||||
instagram_en: str | None = None
|
||||
facebook_en: str | None = None
|
||||
kakao_talk: str | None = None
|
||||
naver_cafe: str | None = None
|
||||
channel_logos: str | None = None
|
||||
|
||||
|
||||
# --- MarketingReport ---
|
||||
|
||||
@@ -32,19 +32,65 @@
|
||||
## 분석 리포트
|
||||
{report}
|
||||
|
||||
## 추가 채널 데이터 (네이버 블로그 / 틱톡 / 인스타그램 EN / 페이스북 EN / 네이버 카페 / 카카오톡)
|
||||
아래에 데이터가 있는 채널은 channelStrategies에 **반드시 포함**하세요 (네이버 블로그, 틱톡, 영문 인스타그램, 영문 페이스북, 네이버 카페, 카카오톡). channelBranding은 SNS·블로그·카페까지만 포함(카카오톡은 메신저라 제외). null이면 제외.
|
||||
|
||||
### 네이버 블로그 (Naver Blog)
|
||||
{naver_blog}
|
||||
|
||||
### 틱톡 (TikTok)
|
||||
{tiktok}
|
||||
|
||||
### 인스타그램 (영문 계정)
|
||||
{instagram_en}
|
||||
|
||||
### 페이스북 (영문 페이지)
|
||||
{facebook_en}
|
||||
|
||||
### 네이버 카페 (공식 카페 운영 신호)
|
||||
{naver_cafe}
|
||||
- naver_cafe.cafeName: 카페명, naver_cafe.memberCount: 회원수
|
||||
- currentStatus는 "회원 N명" 형태로 간단하게. 게시글 수·최근 활동은 수집 불가 (추측 금지).
|
||||
- targetGoal은 회원 확보 목표 수치 + 운영 권장 (예: "회원 5,000명, 주 1~2회 공지 발행").
|
||||
|
||||
### 카카오톡 채널 (URL only — 콘텐츠 수집 X, 존재 여부만)
|
||||
{kakao_talk}
|
||||
- channelStrategies 카드 하나로 포함. currentStatus는 "공식 카카오톡 채널 운영 중" 정도, targetGoal은 친구 추가 유도·상담 전환·자동응답 시나리오 구체화 등.
|
||||
|
||||
## 채널별 로고 분석 (Gemini Vision) — 채널룰/일관성의 근거
|
||||
{channel_logos}
|
||||
- 위 channel_logos[]의 각 항목: channel(채널명), logo_description(프로필이 어떻게 생겼는지), is_official(공식 로고와 일치 여부).
|
||||
- **channelBranding[]은 "어떻게 해야 하는지 권장 가이드라인" 섹션입니다.** 채널 통일 전략 기준으로 권장값 박을 것:
|
||||
- profilePhoto: **빈 문자열 ""로 두세요.** 시스템이 brand_assets.logo_description으로 직접 채우므로 LLM은 만들지 마세요.
|
||||
- bannerSpec: 권장 배너 규격 (크기·디자인 가이드)
|
||||
- bioTemplate: 권장 bio 템플릿 (구조·필수 요소·예약 링크 포함 여부)
|
||||
- currentStatus: is_official=true면 "correct" / false면 "incorrect" (데이터 없는 채널은 "N/A") — 현재 상태 마커는 이 필드 하나로만.
|
||||
- 현재 채널 프로필 이미지의 실제 묘사(channel_logos.channel_logos[].logo_description)는 brandInconsistencies에서만 사용. channelBranding에서 채널별로 다른 묘사를 박지 마세요.
|
||||
- **brandInconsistencies[]에 "로고" 항목을 반드시 만드세요**: values[]에 채널마다 channel(채널명) / value(logo_description 그대로) / is_correct(is_official 값) 세 필드를 넣고, impact는 inconsistency_summary, recommendation은 channel_logos.recommendation 기반으로 작성 (공식 로고로 통일 권고 포함).
|
||||
|
||||
## 브랜드 자산 (홈페이지 CSS에서 추출 — 결정적 데이터)
|
||||
{brand_assets}
|
||||
- brand_assets.color_palette[]의 hex와 brand_assets.brand_colors(primary/accent/text)는 **홈페이지 CSS에서 실제로 추출한 값**입니다.
|
||||
- **brandGuide.colors의 hex는 반드시 이 추출값을 그대로 사용하세요. hex를 새로 지어내거나 변형하지 마세요** (매 실행마다 동일해야 함). name/usage 설명은 의미있게 써도 되지만 hex 값 자체는 추출값으로 고정.
|
||||
|
||||
## 섹션별 작성 지침
|
||||
|
||||
### Section 1: brandGuide
|
||||
- colors: 병원 아이덴티티에 맞는 컬러 팔레트 3~5개 (hex + 사용 가이드)
|
||||
- colors: **brand_assets.color_palette / brand_colors의 hex를 그대로 사용** (홈페이지 CSS 추출값, 지어내기 금지). 3~5개, 각 hex에 name/usage 부여
|
||||
- fonts: 제목/본문/캡션용 폰트 시스템 (한글/영문 포함)
|
||||
- logoRules: DO/DON'T 형식의 로고 사용 규칙 4~6개
|
||||
- logoRules: 로고 사용 규칙 4~6개. 각 항목은 rule / description / correct 3개 필드로 구성:
|
||||
- rule: 규칙을 요약한 **구체적인 제목**. "DO"·"DON'T" 같은 단어를 그대로 넣지 말 것. 실제 규칙 내용을 쓸 것 (예: "보라색+골드 깃털 로고 통일 사용", "모델 사진 프로필 금지", "비공식 변형 로고 사용 금지", "로고 주변 여백 확보").
|
||||
- description: 해당 규칙의 상세 설명.
|
||||
- correct: 권장 규칙(DO)이면 true, 금지/지양 규칙(DON'T)이면 false. 권장(true)과 금지(false)를 섞어서 작성.
|
||||
- toneOfVoice: 브랜드 성격 키워드, 커뮤니케이션 스타일, 권장/지양 표현 예시
|
||||
- channelBranding: 리포트에 존재하는 채널별 브랜딩 적용 규칙
|
||||
- brandInconsistencies: 채널 간 브랜딩 불일치 항목 및 개선 권고
|
||||
|
||||
### Section 2: channelStrategies
|
||||
- 리포트에 데이터가 있는 채널만 포함
|
||||
- 각 채널의 우선순위(P0/P1/P2), 목표, 콘텐츠 유형, 게시 빈도, 포맷 가이드라인 작성
|
||||
- 메인 SNS 채널(Instagram, Facebook, YouTube, TikTok, 네이버 블로그) + 영문 계정(Instagram EN, Facebook EN) + **네이버 카페 / 카카오톡** (URL 있을 때) 카드를 **모두 포함**. 데이터 없는 채널도 빠뜨리지 말 것.
|
||||
- **currentStatus**: 데이터 있는 채널은 실제 수치로 서술 (예: "14,047 팔로워, Reels 0개", "104K 구독자, 주 2~3회 업로드"). **데이터 없는 채널은 "계정 없음"** 으로 표시. `excellent`/`warning`/`good` 같은 등급·평가어 금지.
|
||||
- **targetGoal은 모든 채널에 반드시 채울 것** — 구체적 목표 수치(예: "50K 팔로워, Reels 주 5개"). 데이터 없는 채널도 시작 시 권장 목표를 작성하고 비우지 말 것.
|
||||
- 각 채널의 우선순위(P0/P1/P2), 콘텐츠 유형, 게시 빈도, 포맷 가이드라인 모두 권장값으로 작성 — 데이터 없어도 시작 권장값으로 채울 것.
|
||||
- customerJourneyStage는 해당 채널의 주요 기여 단계로 설정
|
||||
|
||||
### Section 3: contentStrategy
|
||||
|
||||
@@ -12,6 +12,17 @@
|
||||
- 시술: {services}
|
||||
- 의료진: {doctors}
|
||||
|
||||
## 브랜드 자산 (홈페이지에서 자동 추출)
|
||||
|
||||
### Firecrawl branding (로고 URL / 색상 / 폰트)
|
||||
{branding}
|
||||
|
||||
### 추출된 브랜드 자산 (로고 묘사 + CSS 색상 팔레트)
|
||||
{brand_assets}
|
||||
|
||||
⚠️ clinic_snapshot.logo_images / brand_colors는 위 추출값(brand_assets.logo_images, brand_assets.brand_colors)을 **그대로** 사용하세요. hex나 로고 URL을 절대 추측하지 마세요. 추출값이 null이면 해당 필드도 null로 두세요.
|
||||
로고에 대한 정성 평가(심볼/워드마크/톤)는 brand_assets.logo_description을 근거로 하고, 채널 프로필 이미지가 공식 로고와 일치하는지 판단할 때도 이 묘사를 기준으로 삼으세요.
|
||||
|
||||
## 시장 분석 데이터
|
||||
|
||||
### 경쟁 병원
|
||||
@@ -43,9 +54,61 @@
|
||||
### 강남언니
|
||||
{gangnam_unni}
|
||||
|
||||
### 틱톡 (TikTok)
|
||||
{tiktok}
|
||||
|
||||
### 인스타그램 (영문 계정)
|
||||
{instagram_en}
|
||||
|
||||
### 페이스북 (영문 페이지)
|
||||
{facebook_en}
|
||||
|
||||
### 카카오톡 채널 (URL only — 수집 데이터 없음, 존재 여부만 확인)
|
||||
{kakao_talk}
|
||||
|
||||
### 네이버 카페 (공식 카페 운영 신호)
|
||||
{naver_cafe}
|
||||
- naver_cafe.cafeName: 카페명
|
||||
- naver_cafe.memberCount: 회원수
|
||||
- 게시글 총 수·최근 게시일은 로그인 필요라 수집 불가. 추측 금지. 위 두 값만 사용.
|
||||
|
||||
### 채널별 로고 분석 (Gemini Vision)
|
||||
{channel_logos}
|
||||
- channel_logos.channel_logos[]에 각 채널의 로고 설명(logo_description)과 공식 로고 일치 여부(is_official)가 있습니다.
|
||||
- **facebook_audit.pages[].logo** 는 짧은 판정 타이틀로: is_official=true면 `"일치 (공식 로고)"`, false면 `"불일치 (비공식 변형)"`. 그리고 **facebook_audit.pages[].logo_description** 에 해당 채널의 logo_description(설명문)을 넣으세요.
|
||||
- 위 값들은 channel_logos 데이터 기반으로만 작성하고 추측하지 마세요.
|
||||
- 채널 간 로고 불일치(is_official=false)는 brand 일관성 진단(problem_diagnosis/weaknesses)에 반영하세요.
|
||||
- **brand_inconsistencies[]에 "로고" 항목을 반드시 만드세요**: values[]에 channel_logos.channel_logos[] 각 채널마다 다음 3필드를 **그대로** 박을 것 — channel(채널명 그대로), value(해당 채널의 logo_description 문자열 그대로 복붙), is_correct(해당 채널의 is_official 값 그대로). ❗ **채널-묘사 매핑을 절대 swap·재해석·임의 변형 금지**. channel_logos에 적힌 그대로 사용. impact는 channel_logos.inconsistency_summary 사용, recommendation은 channel_logos.recommendation 사용.
|
||||
|
||||
## clinic_snapshot / 채널 audit 작성 지침 (수집 데이터 그대로, 추측 금지)
|
||||
- clinic_snapshot.name 은 {clinic_name} 을 **그대로** 사용 (강남언니 표기명 '-본원' 등으로 바꾸지 말 것).
|
||||
- clinic_snapshot 의 overall_rating/total_reviews/staff_count/location/certifications/lead_doctor 는 강남언니({gangnam_unni}) 데이터의 값을 그대로 사용.
|
||||
- **instagram_audit.accounts 는 반드시 빈 배열 []로 두세요.** 계정 정보는 시스템이 수집 데이터로 직접 채우니 LLM은 만들지 말고, instagram_audit.diagnosis(진단)만 작성하세요.
|
||||
- facebook_audit.pages: KR 페북({facebook})·영문 페북({facebook_en}) 데이터가 있으면 **각각 별도 페이지**로 넣고, url/page_name/followers 등은 그 데이터 그대로. language/label 동일 규칙.
|
||||
- facebook_audit.pages[].top_content_type 은 해당 페이지 latestPosts의 **캡션·미디어를 읽고** 주로 올리는 콘텐츠를 의미 기반으로 짧게 묘사하세요 (예: "Before/After 사진 + 환자 여정 Reels", "이벤트·프로모션 카드뉴스", "다국어 시술 소개"). 단순 "동영상/이미지 위주"가 아니라 **무슨 주제**인지 쓰세요. (recent_post_age·post_frequency·engagement 수치는 시스템이 덮어쓰니 대략 적어도 됩니다.)
|
||||
- 위 수치·URL·이름은 제공된 데이터에서 그대로 쓰고 절대 지어내지 마세요.
|
||||
|
||||
## 기타 채널 현황 (other_channels) 작성 지침
|
||||
- other_channels에는 메인 audit(YouTube/Instagram/Facebook/Website)에 **포함되지 않은** 채널만 넣으세요.
|
||||
- 위 '채널 데이터'에 **실제 수집된 데이터가 있는 채널만** status=active와 실제 url로 일관되게 포함: 네이버 블로그, 강남언니, 틱톡, 영문 인스타그램({instagram_en}), 영문 페이스북({facebook_en}).
|
||||
- **영문 인스타그램·영문 페이스북은 KR 메인 audit(Instagram/Facebook)과 별개 계정이므로, 데이터가 있으면 반드시 other_channels에 "Instagram EN" / "Facebook EN"으로 각각 포함하세요 (절대 누락 금지).**
|
||||
- **카카오톡·네이버 카페**: {kakao_talk} 또는 {naver_cafe}에 url이 있으면 other_channels에 각각 "KakaoTalk" / "Naver Cafe"로 status=active + 해당 url로 포함. 수집된 콘텐츠 데이터는 없으므로 URL 존재 자체가 활성 채널 신호. **둘 다 null/빈 값이면 절대 만들지 마세요.**
|
||||
- **그 외 데이터 없는 채널(네이버플레이스/Threads 등)은 절대 임의로 만들지 마세요.** 데이터 없으면 그 채널은 생략 (랜덤 생성·추측 금지).
|
||||
- url은 수집 데이터의 실제 URL만 사용. 없으면 빈 문자열.
|
||||
- **URL에 'https://www.facebook.com/' 같은 prefix를 절대 직접 만들지 마세요.** 수집 데이터의 URL을 그대로 사용. 이미 'https://...' 가 붙은 URL에 또 prefix 붙이면 'https://www.facebook.com/https://facebook.com/X' 같이 깨집니다. 받은 URL = 출력 URL.
|
||||
|
||||
## registry_data 작성 지침 (clinic_snapshot 안)
|
||||
- **registry_data.website_en / district / branches / brand_group / naver_place_url / gangnam_unni_url / google_maps_url 모두 제공된 데이터에 명시되지 않으면 반드시 null로 두세요.**
|
||||
- 영문 사이트 URL, 영문명, 지점 정보 같은 거 데이터에 없으면 **절대 추측하거나 그럴듯해 보이는 도메인을 지어내지 마세요** (예: 'thepsclinic.com', '*-eng.com' 같은 거).
|
||||
|
||||
## 분석 지침
|
||||
|
||||
- 점수는 0~100 기준입니다.
|
||||
- **channel_scores(채널 종합도)에는 데이터가 있는 모든 채널을 각각 별도 항목으로 만드세요. 같은 플랫폼이라도 한국 계정과 영문 계정을 절대 하나로 합치지 마세요:**
|
||||
- 인스타그램 KR → channel "Instagram", 영문 인스타그램({instagram_en}) 데이터가 있으면 → channel "Instagram EN" (별도 항목)
|
||||
- 페이스북 KR → channel "Facebook", 영문 페이스북({facebook_en}) 데이터가 있으면 → channel "Facebook EN" (별도 항목)
|
||||
- 틱톡({tiktok}) 데이터가 있으면 → channel "TikTok" (별도 항목)
|
||||
- 데이터가 null인 계정은 항목을 만들지 마세요. icon은 instagram/facebook/video 등 플랫폼에 맞게 설정.
|
||||
- strengths와 weaknesses는 각 3개 이상 작성하세요.
|
||||
- roadmap은 우선순위 순으로 실행 가능한 액션으로 작성하세요.
|
||||
- kpis는 실제 수집된 수치 기반으로 현실적인 측정 가능 지표로 작성하세요.
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import re
|
||||
import httpx
|
||||
from http import HTTPMethod
|
||||
from urllib.parse import urlparse
|
||||
from common.utils import http_request
|
||||
@@ -64,6 +65,20 @@ class NaverClient:
|
||||
return None
|
||||
return resp.text
|
||||
|
||||
async def fetch_blog_total_count(self, handle: str) -> int | None:
|
||||
"""블로그 전체 글 수는 RSS에 없어서 PostList HTML에서 '554개의 글' 패턴 추출.
|
||||
<h4 class="category_title pcol2">... 554개의 글</h4> 구조."""
|
||||
resp = await http_request(
|
||||
HTTPMethod.GET,
|
||||
url=f"https://blog.naver.com/PostList.naver?blogId={handle}&from=postList&directAccess=true",
|
||||
timeout=15,
|
||||
label="naver-blog-postlist",
|
||||
)
|
||||
if not resp or not resp.is_success:
|
||||
return None
|
||||
m = re.search(r"(\d+)개의 글", resp.text)
|
||||
return int(m.group(1)) if m else None
|
||||
|
||||
async def get_blog_rss(self, url: str) -> dict | None:
|
||||
blog_handle = urlparse(url).path.strip("/").split("/")[0] if "://" in url else url
|
||||
xml = await self.fetch_blog_rss(blog_handle)
|
||||
@@ -82,10 +97,71 @@ class NaverClient:
|
||||
"postDate": date.group(1) if date else "",
|
||||
"description": re.sub(r"<[^>]*>", "", desc.group(1) if desc else "").strip()[:150],
|
||||
})
|
||||
# RSS의 totalCount 우선, 없으면 블로그 PostList 페이지에서 "N개의 글" 파싱, 그것도 없으면 RSS 글수
|
||||
total_match = re.search(r"<totalCount>(\d+)</totalCount>", xml)
|
||||
if total_match:
|
||||
total = int(total_match.group(1))
|
||||
else:
|
||||
total = await self.fetch_blog_total_count(blog_handle) or len(posts)
|
||||
return {
|
||||
"officialBlogUrl": f"https://blog.naver.com/{blog_handle}",
|
||||
"officialBlogHandle": blog_handle,
|
||||
"totalResults": int(total_match.group(1)) if total_match else len(posts),
|
||||
"totalResults": total,
|
||||
"posts": posts[:10],
|
||||
}
|
||||
|
||||
async def get_cafe_info(self, cafe_url: str, *_args, **_kwargs) -> dict | None:
|
||||
"""네이버 카페 운영 신호 수집. 2단계 fetch:
|
||||
1) https://cafe.naver.com/{handle} → cafeId 추출
|
||||
2) ArticleList.nhn?search.clubid={cafeId} → memberCount + cafeName 추출
|
||||
본문/게시글은 로그인 필요라 못 가져옴. 회원수·카페명만 잡히면 충분.
|
||||
common.http_request는 redirect 안 따라가서 카페 페이지에 안 맞아 httpx 직접 사용."""
|
||||
handle = urlparse(cafe_url).path.strip("/").split("/")[0] if "://" in cafe_url else cafe_url.split("/")[-1]
|
||||
if not handle:
|
||||
return None
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
timeout=10, follow_redirects=True,
|
||||
headers={"User-Agent": "Mozilla/5.0"},
|
||||
) as c:
|
||||
# 1. cafeId 추출
|
||||
try:
|
||||
main = await c.get(f"https://cafe.naver.com/{handle}")
|
||||
except Exception:
|
||||
return {"url": f"https://cafe.naver.com/{handle}", "cafeHandle": handle, "accessible": False}
|
||||
if main.status_code != 200:
|
||||
return {"url": f"https://cafe.naver.com/{handle}", "cafeHandle": handle, "accessible": False}
|
||||
cid_match = re.search(r'cafeId["\']?\s*[:=]\s*["\']?(\d+)', main.text)
|
||||
cafe_id = cid_match.group(1) if cid_match else None
|
||||
|
||||
result: dict = {
|
||||
"url": f"https://cafe.naver.com/{handle}",
|
||||
"cafeHandle": handle,
|
||||
"cafeId": cafe_id,
|
||||
"accessible": True,
|
||||
"cafeName": None,
|
||||
"memberCount": None,
|
||||
}
|
||||
if not cafe_id:
|
||||
return result
|
||||
|
||||
# 2. ArticleList 페이지에서 회원수 + 카페명 추출 (로그인 없이 접근 가능한 유일한 endpoint)
|
||||
try:
|
||||
listing = await c.get(
|
||||
f"https://cafe.naver.com/ArticleList.nhn?search.clubid={cafe_id}&search.menuid=&search.boardtype=L",
|
||||
headers={"Referer": f"https://cafe.naver.com/{handle}"},
|
||||
)
|
||||
except Exception:
|
||||
return result
|
||||
if listing.status_code != 200:
|
||||
return result
|
||||
mc = re.search(r'memberCount[^0-9]+(\d[\d,]*)', listing.text)
|
||||
if mc:
|
||||
result["memberCount"] = int(mc.group(1).replace(",", ""))
|
||||
tm = re.search(r"<title>(.+?)\s*:\s*네이버 카페</title>", listing.text)
|
||||
if tm:
|
||||
name = re.sub(r"&", "&", tm.group(1)).strip()
|
||||
if "," in name:
|
||||
name = name.split(",", 1)[1].strip()
|
||||
result["cafeName"] = name
|
||||
return result
|
||||
@@ -0,0 +1,325 @@
|
||||
"""Gemini Vision — 로고/브랜드 비주얼 자동 분석 (OpenAI 호환 모드).
|
||||
|
||||
정확한 hex 색상은 color_extractor가 CSS에서 직접 뽑음 (Vision은 근사값밖에 못 냄).
|
||||
Vision은 사람이 봐야 알 수 있는 정성 정보 — 심볼 형태/워드마크/톤 — 를 담당.
|
||||
"""
|
||||
import asyncio
|
||||
import base64
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import ssl
|
||||
import httpx
|
||||
import resvg_py
|
||||
from openai import AsyncOpenAI
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
DEFAULT_MODEL = "gemini-2.5-flash"
|
||||
|
||||
|
||||
class VisionClient:
|
||||
"""Gemini Vision을 OpenAI 호환 endpoint로 호출. GEMINI_API_KEY만 필요."""
|
||||
|
||||
def __init__(self, api_key: str, model: str = DEFAULT_MODEL, timeout: float = 30.0, max_retries: int = 2):
|
||||
self.client = AsyncOpenAI(
|
||||
api_key=api_key,
|
||||
base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
|
||||
timeout=timeout,
|
||||
max_retries=max_retries,
|
||||
)
|
||||
self.model = model
|
||||
|
||||
@staticmethod
|
||||
def _extract_json(text: str) -> dict | None:
|
||||
if not text:
|
||||
return None
|
||||
m = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", text, re.DOTALL)
|
||||
if m:
|
||||
try:
|
||||
return json.loads(m.group(1))
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
m = re.search(r"\{.*\}", text, re.DOTALL)
|
||||
if m:
|
||||
try:
|
||||
return json.loads(m.group(0))
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
async def _fetch_as_data_url(url: str) -> str | None:
|
||||
"""Gemini는 URL 직접 fetch가 막힌 호스트가 많아 base64 인라인으로 변환.
|
||||
+ 'image does not exist' 같은 placeholder 이미지 거부 (작은 bytes / 잘못된 content-type).
|
||||
+ 한국 의료 사이트 중 SSL이 약해서 표준 검증에 실패하는 곳 대응 (3단 SSL fallback)."""
|
||||
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36"}
|
||||
|
||||
def _weak_ctx() -> ssl.SSLContext:
|
||||
ctx = ssl.create_default_context()
|
||||
try:
|
||||
ctx.set_ciphers("DEFAULT@SECLEVEL=1")
|
||||
except ssl.SSLError:
|
||||
pass
|
||||
return ctx
|
||||
|
||||
last_err: Exception | None = None
|
||||
for verify in (True, _weak_ctx(), False):
|
||||
try:
|
||||
async with httpx.AsyncClient(
|
||||
timeout=15.0, follow_redirects=True, headers=headers, verify=verify,
|
||||
) as c:
|
||||
resp = await c.get(url)
|
||||
if resp.status_code != 200:
|
||||
logger.warning("[vision] fetch %s status=%s", url, resp.status_code)
|
||||
return None
|
||||
mime = resp.headers.get("content-type", "").split(";")[0].strip()
|
||||
# 실제 이미지가 아니면 거부 (HTML 페이지가 404 대신 200으로 리다이렉트 되는 경우)
|
||||
if not mime.startswith("image/"):
|
||||
logger.warning("[vision] %s not an image (content-type=%s)", url, mime)
|
||||
return None
|
||||
# SVG는 Gemini가 못 보므로 즉시 PNG로 래스터화 (resvg, in-memory ~1ms)
|
||||
content = resp.content
|
||||
if mime == "image/svg+xml" or url.lower().split("?")[0].endswith(".svg"):
|
||||
try:
|
||||
content = bytes(resvg_py.svg_to_bytes(svg_string=resp.text))
|
||||
mime = "image/png"
|
||||
except Exception as e:
|
||||
logger.warning("[vision] svg rasterize failed %s: %s", url, e)
|
||||
return None
|
||||
size = len(content)
|
||||
if size < 500:
|
||||
logger.warning("[vision] %s too small (%d bytes) — likely placeholder", url, size)
|
||||
return None
|
||||
b64 = base64.b64encode(content).decode("ascii")
|
||||
return f"data:{mime};base64,{b64}"
|
||||
except (httpx.ConnectError, httpx.ReadError, ssl.SSLError) as e:
|
||||
last_err = e
|
||||
continue
|
||||
except Exception as e:
|
||||
logger.warning("[vision] fetch error %s: %s", url, e)
|
||||
return None
|
||||
logger.warning("[vision] fetch %s SSL fallback all failed: %s", url, last_err)
|
||||
return None
|
||||
|
||||
async def _ask(self, image_urls: list[str], prompt: str, max_tokens: int = 4000) -> dict | None:
|
||||
content: list[dict] = []
|
||||
for u in image_urls:
|
||||
if not u:
|
||||
continue
|
||||
data_url = await self._fetch_as_data_url(u)
|
||||
if not data_url:
|
||||
continue
|
||||
content.append({"type": "image_url", "image_url": {"url": data_url}})
|
||||
if not any(c.get("type") == "image_url" for c in content):
|
||||
logger.warning("[vision] no images could be fetched")
|
||||
return None
|
||||
content.append({"type": "text", "text": prompt})
|
||||
|
||||
try:
|
||||
resp = await self.client.chat.completions.create(
|
||||
model=self.model,
|
||||
messages=[{"role": "user", "content": content}],
|
||||
max_tokens=max_tokens,
|
||||
)
|
||||
choice = resp.choices[0]
|
||||
if choice.finish_reason != "stop":
|
||||
logger.warning("[vision] unexpected finish_reason=%s", choice.finish_reason)
|
||||
return self._extract_json(choice.message.content or "")
|
||||
except Exception as e:
|
||||
logger.warning("[vision] error: %s", e)
|
||||
return None
|
||||
|
||||
async def describe_svg_text(self, svg_url: str) -> dict | None:
|
||||
"""SVG는 Gemini Vision이 못 보지만 XML 텍스트 자체는 LLM이 읽을 수 있음.
|
||||
SVG 소스를 받아 그대로 text endpoint에 던지고 색·심볼·텍스트를 추론하게 함.
|
||||
analyze_brand_assets와 동일한 스키마(logo_description/style/has_symbol/...) 반환."""
|
||||
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36"}
|
||||
|
||||
def _weak_ctx() -> ssl.SSLContext:
|
||||
ctx = ssl.create_default_context()
|
||||
try:
|
||||
ctx.set_ciphers("DEFAULT@SECLEVEL=1")
|
||||
except ssl.SSLError:
|
||||
pass
|
||||
return ctx
|
||||
|
||||
svg_text: str | None = None
|
||||
for verify in (True, _weak_ctx(), False):
|
||||
try:
|
||||
async with httpx.AsyncClient(
|
||||
timeout=15.0, follow_redirects=True, headers=headers, verify=verify,
|
||||
) as c:
|
||||
resp = await c.get(svg_url)
|
||||
if resp.status_code == 200:
|
||||
svg_text = resp.text
|
||||
break
|
||||
except (httpx.ConnectError, httpx.ReadError, ssl.SSLError):
|
||||
continue
|
||||
except Exception as e:
|
||||
logger.warning("[vision] svg fetch error %s: %s", svg_url, e)
|
||||
return None
|
||||
if not svg_text:
|
||||
logger.warning("[vision] svg fetch failed %s", svg_url)
|
||||
return None
|
||||
# 페이로드 폭주 방지 — 평범한 로고 SVG는 수 KB 수준
|
||||
if len(svg_text) > 60000:
|
||||
svg_text = svg_text[:60000]
|
||||
|
||||
prompt = (
|
||||
"아래는 병원 로고 SVG 소스 코드입니다. SVG 마크업(path/circle/text/fill/stroke 등)을 "
|
||||
"읽고 로고의 시각적 특징을 추론해 아래 JSON 스키마로만 응답하세요. 코드펜스 없이 순수 JSON.\n"
|
||||
"{\n"
|
||||
' "logo_description": "심볼 형태 + 워드마크 + 톤을 1~2문장 한국어로",\n'
|
||||
' "logo_style": "minimal | illustrative | typographic | abstract 중 하나",\n'
|
||||
' "has_symbol": "심볼/아이콘이 있으면 true, 글자만 있으면 false (boolean)",\n'
|
||||
' "logo_symbol": "심볼 묘사 (예: \'잎사귀\'). 없으면 빈 문자열",\n'
|
||||
' "logo_text": "워드마크 텍스트 그대로. <text> 태그 내용 우선",\n'
|
||||
' "logo_colors_desc": "쓰인 색감을 사람이 부르는 이름으로 (예: \'딥네이비 + 골드\'). hex 출력 금지"\n'
|
||||
"}\n"
|
||||
"주의: hex 값이나 URL은 출력하지 마세요 (별도 추출 로직 처리). 모든 텍스트는 한국어로.\n\n"
|
||||
"SVG 소스:\n"
|
||||
f"{svg_text}"
|
||||
)
|
||||
try:
|
||||
resp = await self.client.chat.completions.create(
|
||||
model=self.model,
|
||||
messages=[{"role": "user", "content": prompt}],
|
||||
max_tokens=8000, # Gemini 2.5는 thinking 토큰을 max_tokens에서 차감하므로 여유 필요
|
||||
)
|
||||
choice = resp.choices[0]
|
||||
if choice.finish_reason != "stop":
|
||||
logger.warning("[vision] svg describe finish_reason=%s", choice.finish_reason)
|
||||
result = self._extract_json(choice.message.content or "")
|
||||
except Exception as e:
|
||||
logger.warning("[vision] svg describe error: %s", e)
|
||||
return None
|
||||
if not result:
|
||||
return None
|
||||
result["logo_images"] = {"circle": None, "horizontal": svg_url, "korean": None}
|
||||
return result
|
||||
|
||||
async def analyze_brand_assets(
|
||||
self,
|
||||
logo_url: str | None,
|
||||
homepage_url: str | None,
|
||||
additional_images: list[str] | None = None,
|
||||
) -> dict:
|
||||
"""로고 이미지를 보고 정성 분석. 정확한 hex는 color_extractor가 따로 처리하므로 여기선 안 뽑음."""
|
||||
urls = [u for u in [logo_url] + list(additional_images or []) if u]
|
||||
if not urls:
|
||||
return {}
|
||||
prompt = (
|
||||
"당신은 브랜드 로고 시각 분석가입니다. 첨부된 이미지(첫 번째가 병원의 대표 로고)를 보고 "
|
||||
"아래 JSON 스키마로만 응답하세요. 코드펜스 없이 순수 JSON만 출력.\n"
|
||||
"{\n"
|
||||
' "logo_description": "로고를 1~2문장으로 설명 (심볼 형태 + 워드마크 + 전반적 톤). 예: \'둥근 잎사귀를 감싼 추상 심볼에 세리프 한글 워드마크, 차분하고 고급스러운 톤\'",\n'
|
||||
' "logo_style": "minimal | illustrative | typographic | abstract 중 하나",\n'
|
||||
' "has_symbol": "심볼/아이콘이 있으면 true, 글자만 있으면 false (boolean)",\n'
|
||||
' "logo_symbol": "심볼이 묘사하는 대상 (예: \'잎사귀\', \'추상 곡선\'). 없으면 빈 문자열",\n'
|
||||
' "logo_text": "로고에 보이는 워드마크 텍스트 그대로 (한글/영문). 없으면 빈 문자열",\n'
|
||||
' "logo_colors_desc": "로고에 쓰인 색감을 사람이 부르는 이름으로 서술 (예: \'딥네이비 + 골드\'). 정확한 hex는 출력하지 말 것"\n'
|
||||
"}\n"
|
||||
"주의: 색상 hex 값이나 logo URL 같은 필드는 출력하지 마세요 (별도 추출 로직이 처리).\n"
|
||||
"모든 설명/텍스트 값은 반드시 한국어로 작성하세요 (영어 금지)."
|
||||
)
|
||||
result = await self._ask(urls, prompt)
|
||||
if not result:
|
||||
return {}
|
||||
# logo_images는 우리가 직접 채움 (Vision은 묘사만)
|
||||
result["logo_images"] = {"circle": None, "horizontal": logo_url, "korean": None}
|
||||
return result
|
||||
|
||||
async def describe_channel_logos(
|
||||
self,
|
||||
official_logo_url: str | None,
|
||||
channel_logos: list[dict],
|
||||
) -> dict | None:
|
||||
"""채널별 프로필 이미지(로고)를 보고 각각 설명 + 공식 로고와 일치 여부 평가.
|
||||
channel_logos: [{"channel": "Instagram", "url": "..."}, ...]
|
||||
반환: {"channel_logos": [{"channel","logo_description","is_official"}], "inconsistency_summary", "recommendation"}
|
||||
|
||||
**3채널씩 묶어 병렬 호출** (한 번에 다 묶으면 LLM이 채널-이미지 매칭 헷갈려 같은 묘사를
|
||||
여러 채널에 복사하는 문제 — VIEW 한국페북·영문인스타가 둘 다 "공식 로고" 묘사로 잘못
|
||||
박혔던 케이스 — 가 있어서 분리. 1채널씩 N번보다 가성비 좋음)."""
|
||||
items = [c for c in channel_logos if c.get("url")]
|
||||
if not items:
|
||||
return None
|
||||
|
||||
CHUNK = 3
|
||||
|
||||
async def _chunk(batch: list[dict]) -> list[dict]:
|
||||
urls = [official_logo_url] + [c["url"] for c in batch] if official_logo_url else [c["url"] for c in batch]
|
||||
n = len(batch)
|
||||
# 이미지 번호 ↔ 채널 매핑 명시
|
||||
if official_logo_url:
|
||||
mapping = "이미지 1 = 공식 로고\n" + "\n".join(
|
||||
f"이미지 {i+2} = {c.get('channel','?')} 채널 프로필" for i, c in enumerate(batch)
|
||||
)
|
||||
instruction = (
|
||||
f"{mapping}\n\n"
|
||||
f"이미지 2~{n+1}(채널 프로필 {n}개)을 각각 **그 이미지에 실제로 보이는 그대로** "
|
||||
"한국어 1문장으로 묘사하세요 (색·형태·텍스트·배경 그대로).\n"
|
||||
"❗ 공식 로고(이미지 1) 묘사를 절대 복사하지 마세요. 각 채널 이미지에 보이는 실제 특징만.\n"
|
||||
"각 채널이 공식 로고와 시각적으로 거의 동일하면 is_official=true, "
|
||||
"심볼/색/배경/텍스트가 다르거나 모델 사진이면 false.\n"
|
||||
)
|
||||
else:
|
||||
mapping = "\n".join(f"이미지 {i+1} = {c.get('channel','?')} 채널 프로필" for i, c in enumerate(batch))
|
||||
instruction = (
|
||||
f"{mapping}\n\n"
|
||||
f"각 이미지를 보이는 그대로 한국어 1문장으로 묘사 (색·형태·텍스트·배경).\n"
|
||||
)
|
||||
schema_lines = ",\n".join(
|
||||
f' {{"channel": "{c.get("channel","?")}", "logo_description": "...", "is_official": true}}'
|
||||
for c in batch
|
||||
)
|
||||
p = (
|
||||
instruction
|
||||
+ "\n아래 JSON으로만 응답 (코드펜스 없이, 순수 JSON):\n{\n"
|
||||
+ f' "channel_logos": [\n{schema_lines}\n ]\n'
|
||||
+ "}\n"
|
||||
+ f"channel 필드는 위 매핑 그대로 ({', '.join(c.get('channel','?') for c in batch)}). "
|
||||
+ "logo_description은 반드시 한국어 (영어 금지)."
|
||||
)
|
||||
r = await self._ask(urls, p)
|
||||
if not r:
|
||||
return []
|
||||
out = []
|
||||
for c in r.get("channel_logos", []):
|
||||
out.append({
|
||||
"channel": c.get("channel", ""),
|
||||
"logo_description": c.get("logo_description", ""),
|
||||
"is_official": bool(c.get("is_official", False)) if official_logo_url else None,
|
||||
})
|
||||
return out
|
||||
|
||||
# 3개씩 청크 → 병렬
|
||||
chunks = [items[i:i+CHUNK] for i in range(0, len(items), CHUNK)]
|
||||
results = await asyncio.gather(*[_chunk(b) for b in chunks], return_exceptions=True)
|
||||
channel_logos_out: list[dict] = []
|
||||
for r in results:
|
||||
if isinstance(r, Exception):
|
||||
logger.warning("[vision] channel_logo chunk error: %s", r)
|
||||
continue
|
||||
channel_logos_out.extend(r)
|
||||
if not channel_logos_out:
|
||||
return None
|
||||
|
||||
# 일관성 요약 + 권고는 결정적 산출 (LLM 한번 더 안 부름)
|
||||
if official_logo_url:
|
||||
mismatches = [c["channel"] for c in channel_logos_out if not c.get("is_official")]
|
||||
if not mismatches:
|
||||
summary = "모든 채널이 공식 로고를 일관되게 사용하고 있습니다."
|
||||
rec = "현재 일관성 유지."
|
||||
else:
|
||||
summary = f"{len(mismatches)}개 채널({', '.join(mismatches)})이 공식 로고와 다른 이미지를 사용해 브랜드 일관성이 부족합니다."
|
||||
rec = "비공식 채널 프로필을 공식 로고로 통일 권고."
|
||||
else:
|
||||
summary, rec = "", ""
|
||||
|
||||
return {
|
||||
"channel_logos": channel_logos_out,
|
||||
"inconsistency_summary": summary,
|
||||
"recommendation": rec,
|
||||
}
|
||||
@@ -98,9 +98,11 @@ class YouTubeClient:
|
||||
ch = raw["channel"]
|
||||
stats = ch.get("statistics", {})
|
||||
snippet = ch.get("snippet", {})
|
||||
thumbs = snippet.get("thumbnails", {})
|
||||
return {
|
||||
"channelId": raw["channelId"],
|
||||
"channelName": snippet.get("title"),
|
||||
"profileImage": (thumbs.get("high") or thumbs.get("medium") or thumbs.get("default") or {}).get("url"),
|
||||
"handle": snippet.get("customUrl"),
|
||||
"description": snippet.get("description", ""),
|
||||
"publishedAt": snippet.get("publishedAt"),
|
||||
|
||||
Reference in new issue
Block a user