Compare commits
10
Commits
upload
..
eed57729d9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eed57729d9 | ||
|
|
d1293f9188 | ||
|
|
0e68cbe71b | ||
|
|
cb798f7acc | ||
|
|
84fd854d15 | ||
|
|
8e5ce3e012 | ||
|
|
b921a0803e | ||
|
|
e8406dc0ee | ||
|
|
09bb7a71ee | ||
|
|
1f45b3e53d |
No files matched your search
+3
-1
@@ -43,4 +43,6 @@ Thumbs.db
|
||||
# Alembic
|
||||
alembic/versions/*.pyc
|
||||
|
||||
test_results/
|
||||
test_results/
|
||||
|
||||
app/test*
|
||||
+6
-27
@@ -26,12 +26,6 @@ async def get_pool() -> aiomysql.Pool:
|
||||
# 쓰기 (INSERT/UPDATE/DELETE)
|
||||
async def execute(sql: str, args: tuple = ()) -> int:
|
||||
pool = await get_pool()
|
||||
print(
|
||||
f"[Pool] size={pool.size} "
|
||||
f"free={pool.freesize} "
|
||||
f"used={pool.size - pool.freesize} "
|
||||
f"max={pool.maxsize}"
|
||||
)
|
||||
async with pool.acquire() as conn:
|
||||
try:
|
||||
async with conn.cursor() as cur:
|
||||
@@ -45,12 +39,6 @@ async def execute(sql: str, args: tuple = ()) -> int:
|
||||
# 읽기 (SELECT)
|
||||
async def fetchone(sql: str, args: tuple = ()) -> dict | None:
|
||||
pool = await get_pool()
|
||||
print(
|
||||
f"[Pool] size={pool.size} "
|
||||
f"free={pool.freesize} "
|
||||
f"used={pool.size - pool.freesize} "
|
||||
f"max={pool.maxsize}"
|
||||
)
|
||||
async with pool.acquire() as conn:
|
||||
try:
|
||||
async with conn.cursor(aiomysql.DictCursor) as cur:
|
||||
@@ -70,15 +58,6 @@ async def fetchall(sql: str, args: tuple = ()) -> list[dict]:
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
async def fetchall(sql: str, args: tuple = ()) -> list[dict]:
|
||||
pool = await get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
await conn.ping(reconnect=True)
|
||||
async with conn.cursor(aiomysql.DictCursor) as cur:
|
||||
await cur.execute(sql, args)
|
||||
return list(await cur.fetchall())
|
||||
|
||||
async def insert_instagram_row(hospital_id: str, url: str) -> int:
|
||||
return await execute("INSERT INTO instagram_data (hospital_id, url) VALUES (%s, %s)", (hospital_id, url))
|
||||
|
||||
@@ -148,7 +127,7 @@ async def is_done(table: str, row_id: int | None) -> bool:
|
||||
return r["status"] == "done"
|
||||
|
||||
|
||||
async def _fetch_raw(table: str, row_id: int | None) -> dict | None:
|
||||
async def fetch_raw(table: str, row_id: int | None) -> dict | None:
|
||||
if row_id is None:
|
||||
return None
|
||||
row = await fetchone(f"SELECT raw_data FROM {table} WHERE id = %s", (row_id,))
|
||||
@@ -164,11 +143,11 @@ async def get_analysis_raw_data(analysis_run_id: str) -> dict:
|
||||
(analysis_run_id,),
|
||||
)
|
||||
return {
|
||||
"instagram": await _fetch_raw("instagram_data", run["instagram_data_id"]),
|
||||
"facebook": await _fetch_raw("facebook_data", run["facebook_data_id"]),
|
||||
"naver_blog": await _fetch_raw("naver_blog_data", run["naver_blog_data_id"]),
|
||||
"youtube": await _fetch_raw("youtube_data", run["youtube_data_id"]),
|
||||
"gangnam_unni": await _fetch_raw("gangnam_unni_data", run["gangnam_unni_data_id"]),
|
||||
"instagram": await fetch_raw("instagram_data", run["instagram_data_id"]),
|
||||
"facebook": await fetch_raw("facebook_data", run["facebook_data_id"]),
|
||||
"naver_blog": await fetch_raw("naver_blog_data", run["naver_blog_data_id"]),
|
||||
"youtube": await fetch_raw("youtube_data", run["youtube_data_id"]),
|
||||
"gangnam_unni": await fetch_raw("gangnam_unni_data", run["gangnam_unni_data_id"]),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import os
|
||||
import re
|
||||
import asyncio
|
||||
from http import HTTPMethod
|
||||
import httpx
|
||||
@@ -38,46 +37,3 @@ async def http_request(
|
||||
print(f" [error] {label} → {e}")
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
_SKIP_IG = {"p", "reel", "stories", "explore", "accounts", "about", "directory"}
|
||||
_SKIP_FB = {"sharer", "share", "dialog", "plugins", "groups", "events", "watch", "help"}
|
||||
|
||||
|
||||
def extract_social_handles(urls: list[str]) -> dict[str, list[str]]:
|
||||
result: dict[str, list[str]] = {"instagram": [], "youtube": [], "facebook": [], "naver_blog": [], "tiktok": []}
|
||||
|
||||
for url in urls:
|
||||
if not url:
|
||||
continue
|
||||
m = re.search(r"instagram\.com/([a-zA-Z0-9._]+)", url)
|
||||
if m and m.group(1).lower() not in _SKIP_IG:
|
||||
result["instagram"].append(m.group(1))
|
||||
|
||||
m = re.search(r"youtube\.com/(?:@([a-zA-Z0-9._-]+)|channel/(UC[a-zA-Z0-9_-]+)|c/([a-zA-Z0-9._-]+))", url)
|
||||
if m:
|
||||
result["youtube"].append(f"@{m.group(1)}" if m.group(1) else (m.group(2) or m.group(3) or ""))
|
||||
|
||||
m = re.search(r"facebook\.com/([a-zA-Z0-9._-]+)", url)
|
||||
if m and m.group(1).lower() not in _SKIP_FB:
|
||||
result["facebook"].append(m.group(1))
|
||||
|
||||
m = re.search(r"blog\.naver\.com/([a-zA-Z0-9_-]+)", url)
|
||||
if m:
|
||||
result["naver_blog"].append(m.group(1))
|
||||
|
||||
m = re.search(r"tiktok\.com/@([a-zA-Z0-9._-]+)", url)
|
||||
if m:
|
||||
result["tiktok"].append(m.group(1))
|
||||
|
||||
return {k: list(set(v)) for k, v in result.items()}
|
||||
|
||||
|
||||
def normalize_handle(platform: str, value: str) -> str:
|
||||
"""URL이 들어오면 핸들을 추출하고, 이미 핸들이면 그대로 반환."""
|
||||
if not value:
|
||||
return value
|
||||
if "://" in value or value.startswith("www."):
|
||||
handles = extract_social_handles([value]).get(platform, [])
|
||||
value = handles[0] if handles else value
|
||||
return value.lstrip("@") if platform != "youtube" else value
|
||||
+14
-13
@@ -38,8 +38,8 @@ class ApifyClient:
|
||||
items = await self._run_actor("apify~instagram-profile-scraper", {"usernames": [username], "resultsLimit": 12})
|
||||
return items[0] if items else None
|
||||
|
||||
async def get_instagram_profile(self, handle: str) -> dict | None:
|
||||
profile = await self.fetch_instagram_profile(handle)
|
||||
async def get_instagram_profile(self, url: str) -> dict | None:
|
||||
profile = await self.fetch_instagram_profile(url)
|
||||
if not profile or profile.get("error"):
|
||||
return None
|
||||
return {
|
||||
@@ -49,7 +49,7 @@ class ApifyClient:
|
||||
"posts": profile.get("postsCount", 0),
|
||||
"bio": profile.get("biography", ""),
|
||||
"isBusinessAccount": profile.get("isBusinessAccount", False),
|
||||
"externalUrl": profile.get("externalUrl"),
|
||||
#"externalUrl": profile.get("externalUrl"), LLM에 혼동을 주는 듯 하여 비활성화
|
||||
"latestPosts": [
|
||||
{
|
||||
"type": p.get("type"),
|
||||
@@ -62,15 +62,15 @@ class ApifyClient:
|
||||
],
|
||||
}
|
||||
|
||||
async def fetch_instagram_posts(self, handle: str, limit: int = 20) -> list[dict]:
|
||||
clean = handle.lstrip("@")
|
||||
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/{clean}/"],
|
||||
"username": [f"https://www.instagram.com/{username}/"],
|
||||
"resultsLimit": limit,
|
||||
})
|
||||
|
||||
async def get_instagram_posts(self, handle: str, limit: int = 20) -> dict:
|
||||
items = await self.fetch_instagram_posts(handle, 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"],
|
||||
@@ -92,15 +92,16 @@ class ApifyClient:
|
||||
"avgComments": round(sum(p["commentsCount"] for p in posts) / n),
|
||||
}
|
||||
|
||||
async def fetch_instagram_reels(self, handle: str, limit: int = 15) -> list[dict]:
|
||||
clean = handle.lstrip("@")
|
||||
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", {
|
||||
"directUrls": [f"https://www.instagram.com/{clean}/reels/"],
|
||||
"username": [f"https://www.instagram.com/{username}/reels/"],
|
||||
"resultsLimit": limit,
|
||||
})
|
||||
|
||||
async def get_instagram_reels(self, handle: str, limit: int = 15) -> dict:
|
||||
items = await self.fetch_instagram_reels(handle, 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"],
|
||||
|
||||
@@ -76,7 +76,7 @@ class FirecrawlClient:
|
||||
"url": url,
|
||||
"formats": ["json", "links"],
|
||||
"jsonOptions": {
|
||||
"prompt": "Extract: clinic name (Korean), clinic name (English), address, phone, 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, favicon URL)",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -158,13 +158,14 @@ class FirecrawlClient:
|
||||
"url": hospital_url,
|
||||
"formats": ["json"],
|
||||
"jsonOptions": {
|
||||
"prompt": "Extract: hospital name, overall rating (out of 10), total review count, doctors with names/ratings/review counts/specialties, procedures, address, badges",
|
||||
"prompt": "Extract: hospital name, overall rating (out of 10), total review count, number of major staffs, all doctor with names/ratings/review counts/specialties(please check html, there are not only 4 doctors!), procedures, address, badges.",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"hospitalName": {"type": "string"},
|
||||
"rating": {"type": "number"},
|
||||
"totalReviews": {"type": "number"},
|
||||
"totalMajorStaffs" : {"type" : "number"},
|
||||
"doctors": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
@@ -202,7 +203,8 @@ class FirecrawlClient:
|
||||
"rating": raw.get("rating"),
|
||||
"ratingScale": "/10",
|
||||
"totalReviews": raw.get("totalReviews", 0),
|
||||
"doctors": (raw.get("doctors") or [])[:10],
|
||||
"doctors": (raw.get("doctors") or []),
|
||||
"totalMajorStaffs": raw.get("totalMajorStaffs", 0),
|
||||
"procedures": raw.get("procedures", []),
|
||||
"address": raw.get("address", ""),
|
||||
"badges": raw.get("badges", []),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import os
|
||||
from pydantic import BaseModel
|
||||
from common.utils import get_env
|
||||
from integrations.llm.schemas.report import ReportInput, ReportOutput
|
||||
from integrations.llm.schemas.report import ReportInput, ReportOutput, YouTubeDiagnosisInput, YouTubeDiagnosisOutput
|
||||
from integrations.llm.schemas.plan import PlanInput, PlanOutput
|
||||
from integrations.llm.schemas.market import (
|
||||
MarketCompetitorsInput, MarketCompetitorsOutput,
|
||||
@@ -80,3 +80,10 @@ market_target_audience_prompt = Prompt(
|
||||
input_class=MarketTargetAudienceInput,
|
||||
output_class=MarketTargetAudienceOutput,
|
||||
)
|
||||
|
||||
youtube_diagnosis_prompt = Prompt(
|
||||
file_name="youtube_diagnosis_prompt.txt",
|
||||
prompt_model="REPORT_MODEL",
|
||||
input_class=YouTubeDiagnosisInput,
|
||||
output_class=YouTubeDiagnosisOutput,
|
||||
)
|
||||
@@ -70,18 +70,12 @@ class RegistryData(BaseModel):
|
||||
class ClinicSnapshot(BaseModel):
|
||||
name: str
|
||||
name_en: str
|
||||
established: str
|
||||
years_in_business: int
|
||||
staff_count: int
|
||||
lead_doctor: LeadDoctor
|
||||
overall_rating: float
|
||||
total_reviews: int
|
||||
price_range: PriceRange
|
||||
certifications: list[str]
|
||||
media_appearances: list[str]
|
||||
medical_tourism: list[str]
|
||||
location: str
|
||||
nearest_station: str
|
||||
phone: str
|
||||
domain: str
|
||||
logo_images: LogoImages | None = None
|
||||
@@ -137,7 +131,6 @@ class YouTubeAudit(BaseModel):
|
||||
avg_video_length: str
|
||||
upload_frequency: str
|
||||
channel_created_date: str
|
||||
subscriber_rank: str
|
||||
channel_description: str
|
||||
linked_urls: list[LinkedUrl]
|
||||
playlists: list[str]
|
||||
@@ -345,3 +338,20 @@ class MarketingReport(BaseModel):
|
||||
|
||||
|
||||
ReportOutput = MarketingReport
|
||||
|
||||
|
||||
# --- YouTubeDiagnosis ---
|
||||
|
||||
class YouTubeDiagnosisInput(BaseModel):
|
||||
channel_name: str | None = None
|
||||
subscribers: int | None = None
|
||||
total_videos: int | None = None
|
||||
total_views: int | None = None
|
||||
avg_video_length: str | None = None
|
||||
upload_frequency: str | None = None
|
||||
top_videos: str | None = None
|
||||
playlists: str | None = None
|
||||
|
||||
|
||||
class YouTubeDiagnosisOutput(BaseModel):
|
||||
diagnosis: list[DiagnosisItem]
|
||||
@@ -0,0 +1,24 @@
|
||||
다음은 성형외과/피부과 유튜브 채널 데이터입니다.
|
||||
|
||||
채널명: {channel_name}
|
||||
구독자 수: {subscribers}
|
||||
총 영상 수: {total_videos}
|
||||
총 조회수: {total_views}
|
||||
평균 영상 길이: {avg_video_length}
|
||||
업로드 주기: {upload_frequency}
|
||||
인기 영상 목록: {top_videos}
|
||||
플레이리스트: {playlists}
|
||||
|
||||
위 데이터를 바탕으로 이 채널의 마케팅 문제점과 개선사항을 진단해줘.
|
||||
각 항목은 category(진단 카테고리), detail(상세 설명), severity(critical/warning/info) 형식의 JSON 배열로 출력해줘.
|
||||
|
||||
진단 카테고리들은 다음과 같아. :
|
||||
구독자 대비 조회수 비율,
|
||||
최근 롱폼 조회수,
|
||||
Shorts 조회수,
|
||||
업로드 빈도,
|
||||
콘텐츠 톤앤매너,
|
||||
썸네일 디자인,
|
||||
최고 성과 Shorts
|
||||
|
||||
출처 번호([1], [2] 등)는 굳이 포함하지 마.
|
||||
+44
-15
@@ -1,5 +1,4 @@
|
||||
from http import HTTPMethod
|
||||
from urllib.parse import urlparse
|
||||
from common.utils import http_request
|
||||
|
||||
YT = "https://www.googleapis.com/youtube/v3"
|
||||
@@ -9,25 +8,40 @@ class YouTubeClient:
|
||||
def __init__(self, api_key: str):
|
||||
self.api_key = api_key
|
||||
|
||||
async def _resolve_channel_id(self, handle: str) -> str:
|
||||
h = urlparse(handle).path.strip("/").lstrip("@") if "://" in handle else handle.lstrip("@")
|
||||
if h.startswith("UC") and len(h) == 24:
|
||||
return h
|
||||
async def _resolve_channel_id(self, url: str) -> str:
|
||||
print("input yt url : ", url)
|
||||
|
||||
# /channel/UCxxxxx → 채널 ID 직접 반환
|
||||
if "/channel/" in url:
|
||||
return url.split("/channel/")[1].split("/")[0]
|
||||
|
||||
if "/@" in url:
|
||||
val = "@" + url.split("/@")[1].split("/")[0]
|
||||
elif "/c/" in url:
|
||||
val = url.split("/c/")[1].split("/")[0]
|
||||
elif "/user/" in url:
|
||||
val = url.split("/user/")[1].split("/")[0]
|
||||
elif url.startswith("UC") and len(url) == 24:
|
||||
return url
|
||||
else:
|
||||
val = url
|
||||
|
||||
print("val : ", val)
|
||||
for param in ("forHandle", "forUsername"):
|
||||
resp = await http_request(
|
||||
HTTPMethod.GET,
|
||||
url=f"{YT}/channels",
|
||||
params={"part": "id", param: h, "key": self.api_key},
|
||||
params={"part": "id", param: val, "key": self.api_key},
|
||||
label="yt-resolve",
|
||||
)
|
||||
if resp and resp.is_success:
|
||||
items = resp.json().get("items", [])
|
||||
if items:
|
||||
return items[0]["id"]
|
||||
if resp and resp.is_success and (items := resp.json().get("items", [])):
|
||||
print("items : ", items)
|
||||
return items[0]["id"]
|
||||
print("YT NOT FOUND")
|
||||
return ""
|
||||
|
||||
async def fetch_channel(self, handle_or_id: str) -> dict | None:
|
||||
channel_id = await self._resolve_channel_id(handle_or_id)
|
||||
async def fetch_channel(self, url: str) -> dict | None:
|
||||
channel_id = await self._resolve_channel_id(url)
|
||||
if not channel_id:
|
||||
return None
|
||||
|
||||
@@ -65,10 +79,20 @@ class YouTubeClient:
|
||||
if resp and resp.is_success:
|
||||
videos = resp.json().get("items", [])[:10]
|
||||
|
||||
return {"channelId": channel_id, "channel": channel, "videos": videos}
|
||||
playlists: list[dict] = []
|
||||
resp = await http_request(
|
||||
HTTPMethod.GET,
|
||||
url=f"{YT}/playlists",
|
||||
params={"part": "snippet", "channelId": channel_id, "maxResults": 50, "key": self.api_key},
|
||||
label="yt-playlists",
|
||||
)
|
||||
if resp and resp.is_success:
|
||||
playlists = resp.json().get("items", [])
|
||||
|
||||
async def get_channel(self, handle_or_id: str) -> dict | None:
|
||||
raw = await self.fetch_channel(handle_or_id)
|
||||
return {"channelId": channel_id, "channel": channel, "videos": videos, "playlists": playlists}
|
||||
|
||||
async def get_channel(self, url: str) -> dict | None:
|
||||
raw = await self.fetch_channel(url)
|
||||
if not raw:
|
||||
return None
|
||||
ch = raw["channel"]
|
||||
@@ -95,6 +119,11 @@ class YouTubeClient:
|
||||
}
|
||||
for v in raw["videos"]
|
||||
],
|
||||
"playlists": [
|
||||
p.get("snippet", {}).get("title")
|
||||
for p in raw["playlists"]
|
||||
if p.get("snippet", {}).get("title")
|
||||
],
|
||||
}
|
||||
|
||||
async def search_channels(self, query: str, max_results: int = 3) -> list[str]:
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -68,18 +68,12 @@ class RegistryData(CamelModel):
|
||||
class ClinicSnapshot(CamelModel):
|
||||
name: str
|
||||
name_en: str
|
||||
established: str
|
||||
years_in_business: int
|
||||
staff_count: int
|
||||
lead_doctor: LeadDoctor
|
||||
overall_rating: float
|
||||
total_reviews: int
|
||||
price_range: PriceRange
|
||||
certifications: list[str]
|
||||
media_appearances: list[str]
|
||||
medical_tourism: list[str]
|
||||
location: str
|
||||
nearest_station: str
|
||||
phone: str
|
||||
domain: str
|
||||
logo_images: LogoImages | None = None
|
||||
@@ -131,7 +125,6 @@ class YouTubeAudit(CamelModel):
|
||||
avg_video_length: str
|
||||
upload_frequency: str
|
||||
channel_created_date: str
|
||||
subscriber_rank: str
|
||||
channel_description: str
|
||||
linked_urls: list[LinkedUrl]
|
||||
playlists: list[str]
|
||||
|
||||
+253
-6
@@ -1,9 +1,12 @@
|
||||
import json
|
||||
import logging
|
||||
from common.db import fetchone, execute, get_analysis_raw_data, save_analysis_report, get_market_analysis
|
||||
import os
|
||||
import re
|
||||
from datetime import datetime
|
||||
from common.db import fetchone, execute, fetch_raw, get_analysis_raw_data, save_analysis_report, get_market_analysis
|
||||
from integrations.llm.llm_service import LLMService
|
||||
from integrations.llm.prompt import report_prompt, plan_prompt
|
||||
from integrations.llm.schemas.report import ReportOutput
|
||||
from integrations.llm.prompt import report_prompt, plan_prompt, youtube_diagnosis_prompt
|
||||
from integrations.llm.schemas.report import ReportOutput, ClinicSnapshot, YouTubeAudit
|
||||
from integrations.llm.schemas.plan import PlanOutput
|
||||
from models.status import AnalysisStatus
|
||||
|
||||
@@ -47,7 +50,6 @@ async def generate_report(analysis_run_id: str) -> ReportOutput:
|
||||
|
||||
return await LLMService(provider="perplexity").generate(report_prompt, input_data)
|
||||
|
||||
|
||||
async def generate_plan(analysis_run_id: str) -> PlanOutput:
|
||||
run = await fetchone(
|
||||
"SELECT hospital_id, report_data FROM analysis_runs WHERE analysis_run_id = %s",
|
||||
@@ -84,16 +86,261 @@ async def generate_plan(analysis_run_id: str) -> PlanOutput:
|
||||
return await LLMService(provider="perplexity").generate(plan_prompt, input_data)
|
||||
|
||||
|
||||
def _build_clinic_snapshot(gangnam_unni: dict, hospital: dict) -> dict:
|
||||
snapshot: dict = {}
|
||||
doctors = gangnam_unni.get("doctors", [])
|
||||
lead = max(doctors, key=lambda d: d.get("reviews", 0)) if doctors else None
|
||||
if gangnam_unni.get("name"): snapshot["name"] = gangnam_unni["name"]
|
||||
if hospital.get("clinicNameEn"): snapshot["name_en"] = hospital["clinicNameEn"]
|
||||
if hospital.get("phone"): snapshot["phone"] = hospital["phone"]
|
||||
if hospital.get("domain"): snapshot["domain"] = hospital["domain"]
|
||||
if gangnam_unni.get("rating"): snapshot["overall_rating"] = gangnam_unni["rating"]
|
||||
if gangnam_unni.get("totalReviews"): snapshot["total_reviews"] = gangnam_unni["totalReviews"]
|
||||
if gangnam_unni.get("address"): snapshot["location"] = gangnam_unni["address"]
|
||||
if gangnam_unni.get("badges"): snapshot["certifications"] = gangnam_unni["badges"]
|
||||
if gangnam_unni.get("totalMajorStaffs"): snapshot["staff_count"] = gangnam_unni["totalMajorStaffs"]
|
||||
if lead:
|
||||
snapshot["lead_doctor"] = {
|
||||
"name": lead.get("name"),
|
||||
"credentials": lead.get("specialty"),
|
||||
"rating": lead.get("rating"),
|
||||
"review_count": lead.get("reviews"),
|
||||
}
|
||||
return ClinicSnapshot.model_validate(snapshot).model_dump()
|
||||
|
||||
|
||||
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", [])
|
||||
yt_patch: dict = {
|
||||
"weekly_view_growth": {"absolute": 0, "percentage": 0.0},
|
||||
"estimated_monthly_revenue": {"min": 0, "max": 0},
|
||||
"linked_urls": [],
|
||||
"avg_video_length": _calc_avg_video_length(videos),
|
||||
"upload_frequency": _calc_upload_frequency(videos),
|
||||
}
|
||||
if youtube.get("channelName"): yt_patch["channel_name"] = youtube["channelName"]
|
||||
if youtube.get("handle"): yt_patch["handle"] = youtube["handle"]
|
||||
if youtube.get("subscribers"): yt_patch["subscribers"] = youtube["subscribers"]
|
||||
if youtube.get("totalVideos"): yt_patch["total_videos"] = youtube["totalVideos"]
|
||||
if youtube.get("totalViews"): yt_patch["total_views"] = youtube["totalViews"]
|
||||
if youtube.get("publishedAt"): yt_patch["channel_created_date"] = youtube["publishedAt"][:10]
|
||||
if youtube.get("description"): yt_patch["channel_description"] = youtube["description"]
|
||||
if youtube.get("playlists"): yt_patch["playlists"] = youtube["playlists"]
|
||||
if videos:
|
||||
yt_patch["top_videos"] = [
|
||||
{
|
||||
"title": v["title"],
|
||||
"views": v["views"],
|
||||
"duration": _format_clock(_parse_iso_duration_seconds(v.get("duration", ""))),
|
||||
"type": "Short" if "M" not in v.get("duration", "") else "Long",
|
||||
"uploaded_ago": _relative_date(v.get("date", "")),
|
||||
}
|
||||
for v in videos
|
||||
]
|
||||
|
||||
diagnosis_result = await LLMService(provider="perplexity").generate(
|
||||
youtube_diagnosis_prompt,
|
||||
{
|
||||
"channel_name": yt_patch.get("channel_name"),
|
||||
"subscribers": yt_patch.get("subscribers"),
|
||||
"total_videos": yt_patch.get("total_videos"),
|
||||
"total_views": yt_patch.get("total_views"),
|
||||
"avg_video_length": yt_patch.get("avg_video_length"),
|
||||
"upload_frequency": yt_patch.get("upload_frequency"),
|
||||
"top_videos": json.dumps(yt_patch.get("top_videos", []), ensure_ascii=False),
|
||||
"playlists": json.dumps(yt_patch.get("playlists", []), ensure_ascii=False),
|
||||
},
|
||||
)
|
||||
yt_patch["diagnosis"] = [item.model_dump() for item in diagnosis_result.diagnosis]
|
||||
|
||||
return YouTubeAudit.model_validate(yt_patch).model_dump()
|
||||
|
||||
|
||||
async def _build_overrides(analysis_run_id: str) -> dict:
|
||||
run = await fetchone(
|
||||
"SELECT hospital_id, instagram_data_id, facebook_data_id,"
|
||||
" naver_blog_data_id, youtube_data_id, gangnam_unni_data_id"
|
||||
" FROM analysis_runs WHERE analysis_run_id = %s",
|
||||
(analysis_run_id,),
|
||||
)
|
||||
if not run:
|
||||
return {}
|
||||
|
||||
hospital_row = await fetchone(
|
||||
"SELECT raw_data, url FROM hospital_baseinfo WHERE hospital_id = %s",
|
||||
(run["hospital_id"],),
|
||||
)
|
||||
hospital = json.loads(hospital_row["raw_data"]) if hospital_row and isinstance(hospital_row.get("raw_data"), str) else (hospital_row or {}).get("raw_data") or {}
|
||||
hospital["domain"] = (hospital_row or {}).get("url") or ""
|
||||
instagram = await fetch_raw("instagram_data", run["instagram_data_id"]) or {}
|
||||
facebook = await fetch_raw("facebook_data", run["facebook_data_id"]) or {}
|
||||
naver_blog = await fetch_raw("naver_blog_data", run["naver_blog_data_id"]) or {}
|
||||
youtube = await fetch_raw("youtube_data", run["youtube_data_id"]) or {}
|
||||
gangnam_unni = await fetch_raw("gangnam_unni_data", run["gangnam_unni_data_id"]) or {}
|
||||
|
||||
snapshot: dict = _build_clinic_snapshot(gangnam_unni, hospital)
|
||||
yt_patch: dict = await _build_youtube_audit(youtube)
|
||||
|
||||
# ── instagram ─────────────────────────────────────────────────────────────
|
||||
ig_patch: dict = {}
|
||||
if instagram.get("username"): ig_patch["handle"] = instagram["username"]
|
||||
if instagram.get("posts"): ig_patch["posts"] = instagram["posts"]
|
||||
if instagram.get("followers"): ig_patch["followers"] = instagram["followers"]
|
||||
if instagram.get("following"): ig_patch["following"] = instagram["following"]
|
||||
if instagram.get("bio"): ig_patch["bio"] = instagram["bio"]
|
||||
if instagram.get("username"): ig_patch["profile_link"] = f"https://www.instagram.com/{instagram['username']}/"
|
||||
|
||||
# ── facebook ──────────────────────────────────────────────────────────────
|
||||
fb_patch: dict = {}
|
||||
if facebook.get("pageUrl"): fb_patch["url"] = facebook["pageUrl"]
|
||||
if facebook.get("pageUrl"): fb_patch["link"] = facebook["pageUrl"]
|
||||
if facebook.get("pageName"): fb_patch["page_name"] = facebook["pageName"]
|
||||
if facebook.get("followers"): fb_patch["followers"] = facebook["followers"]
|
||||
if facebook.get("intro"): fb_patch["bio"] = facebook["intro"]
|
||||
if facebook.get("categories"): fb_patch["category"] = ", ".join(facebook["categories"])
|
||||
if facebook.get("website"): fb_patch["linked_domain"] = facebook["website"]
|
||||
|
||||
|
||||
overrides: dict = {}
|
||||
if snapshot:
|
||||
overrides["clinic_snapshot"] = snapshot
|
||||
if ig_patch:
|
||||
overrides["instagram_audit"] = {"accounts": [ig_patch]}
|
||||
if fb_patch:
|
||||
overrides["facebook_audit"] = {"pages": [fb_patch]}
|
||||
if yt_patch:
|
||||
overrides["youtube_audit"] = yt_patch
|
||||
return overrides
|
||||
|
||||
|
||||
def _deep_merge(base: dict, overrides: dict) -> dict:
|
||||
for k, v in overrides.items():
|
||||
if isinstance(v, dict) and isinstance(base.get(k), dict):
|
||||
_deep_merge(base[k], v)
|
||||
elif isinstance(v, list) and isinstance(base.get(k), list):
|
||||
for i, item in enumerate(v):
|
||||
if i < len(base[k]) and isinstance(item, dict) and isinstance(base[k][i], dict):
|
||||
_deep_merge(base[k][i], item)
|
||||
else:
|
||||
base[k] = v
|
||||
return base
|
||||
|
||||
def _patch_report(result: ReportOutput, overrides: dict) -> ReportOutput:
|
||||
merged = _deep_merge(result.model_dump(), overrides)
|
||||
return ReportOutput(**merged)
|
||||
|
||||
|
||||
_MOCK_DOMAINS = {"viewclinic.com"}
|
||||
_MOCK_REPORT_PATH = os.path.join(os.path.dirname(__file__), "../mock/report_viewclinic.json")
|
||||
|
||||
|
||||
async def _is_mock(analysis_run_id: str) -> bool:
|
||||
row = await fetchone(
|
||||
"SELECT h.url FROM analysis_runs ar JOIN hospital_baseinfo h USING (hospital_id)"
|
||||
" WHERE ar.analysis_run_id = %s",
|
||||
(analysis_run_id,),
|
||||
)
|
||||
url = (row or {}).get("url") or ""
|
||||
return any(domain in url for domain in _MOCK_DOMAINS)
|
||||
|
||||
|
||||
def _load_mock_report() -> ReportOutput:
|
||||
with open(_MOCK_REPORT_PATH, encoding="utf-8") as f:
|
||||
return ReportOutput(**json.load(f))
|
||||
|
||||
|
||||
_MOCK_PLAN_PATH = os.path.join(os.path.dirname(__file__), "../mock/plan_viewclinic.json")
|
||||
|
||||
|
||||
def _load_mock_plan() -> PlanOutput:
|
||||
with open(_MOCK_PLAN_PATH, encoding="utf-8") as f:
|
||||
return PlanOutput(**json.load(f))
|
||||
|
||||
|
||||
async def run_report_task(analysis_run_id: str) -> None:
|
||||
logger.info("[report] start run=%s", analysis_run_id)
|
||||
result = await generate_report(analysis_run_id)
|
||||
if await _is_mock(analysis_run_id):
|
||||
logger.info("[report] mock mode run=%s", analysis_run_id)
|
||||
result = _load_mock_report()
|
||||
result.youtube_audit.linked_urls = []
|
||||
else:
|
||||
result = await generate_report(analysis_run_id)
|
||||
result = _patch_report(result, await _build_overrides(analysis_run_id))
|
||||
await save_analysis_report(analysis_run_id, result.model_dump())
|
||||
logger.info("[report] done run=%s", analysis_run_id)
|
||||
|
||||
|
||||
async def run_plan_task(analysis_run_id: str) -> None:
|
||||
logger.info("[plan] start run=%s", analysis_run_id)
|
||||
result = await generate_plan(analysis_run_id)
|
||||
if await _is_mock(analysis_run_id):
|
||||
logger.info("[plan] mock mode run=%s", analysis_run_id)
|
||||
result = _load_mock_plan()
|
||||
else:
|
||||
result = await generate_plan(analysis_run_id)
|
||||
await execute(
|
||||
"UPDATE analysis_runs SET plan_data = %s WHERE analysis_run_id = %s",
|
||||
(json.dumps(result.model_dump(), ensure_ascii=False), analysis_run_id),
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv("../.env")
|
||||
|
||||
from common.utils import normalize_handle
|
||||
from integrations.youtube import YouTubeClient
|
||||
from integrations.apify import ApifyClient
|
||||
from integrations.naver import NaverClient
|
||||
from integrations.firecrawl import FirecrawlClient
|
||||
|
||||
INPUT = {
|
||||
"youtube": "@banobagips",
|
||||
"instagram": ["@banobagi_ps"],
|
||||
"facebook": "BanobagiPlasticSurgery",
|
||||
"naver_blog": "https://blog.naver.com/banobagiprs",
|
||||
"gangnam_unni": "https://www.gangnamunni.com/hospitals/23",
|
||||
}
|
||||
|
||||
OUT_DIR = "../test_results"
|
||||
|
||||
|
||||
def save(name: str, data) -> None:
|
||||
os.makedirs(OUT_DIR, exist_ok=True)
|
||||
path = os.path.join(OUT_DIR, f"{name}.json")
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, ensure_ascii=False)
|
||||
print(f"saved → {path}")
|
||||
|
||||
|
||||
async def main():
|
||||
yt = YouTubeClient(api_key=os.environ["YOUTUBE_API_KEY"])
|
||||
apify = ApifyClient(token=os.environ["APIFY_API_TOKEN"])
|
||||
naver = NaverClient(client_id=os.environ["NAVER_CLIENT_ID"], client_secret=os.environ["NAVER_CLIENT_SECRET"])
|
||||
firecrawl = FirecrawlClient(api_key=os.environ["FIRECRAWL_API_KEY"])
|
||||
|
||||
yt_handle = normalize_handle("youtube", INPUT["youtube"])
|
||||
ig_handle = normalize_handle("instagram", INPUT["instagram"][0])
|
||||
fb_handle = normalize_handle("facebook", INPUT["facebook"])
|
||||
naver_handle = normalize_handle("naver_blog", INPUT["naver_blog"])
|
||||
|
||||
save("youtube", await yt.fetch_channel(yt_handle))
|
||||
save("instagram_profile", await apify.fetch_instagram_profile(ig_handle))
|
||||
# save("instagram_posts", await apify.fetch_instagram_posts(ig_handle))
|
||||
# save("instagram_reels", await apify.fetch_instagram_reels(ig_handle))
|
||||
save("facebook", await apify.fetch_facebook_page(f"https://www.facebook.com/{fb_handle}"))
|
||||
save("naver_blog", await naver.fetch_blog_rss(naver_handle))
|
||||
save("gangnam_unni", await firecrawl.fetch_gangnam_unni(INPUT["gangnam_unni"]))
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
Reference in new issue
Block a user