7 Commits
8 changed files with 166 additions and 158 deletions

No files matched your search

+3 -1
View File
@@ -43,4 +43,6 @@ Thumbs.db
# Alembic # Alembic
alembic/versions/*.pyc alembic/versions/*.pyc
test_results/ test_results/
app/test*
+6 -27
View File
@@ -26,12 +26,6 @@ async def get_pool() -> aiomysql.Pool:
# 쓰기 (INSERT/UPDATE/DELETE) # 쓰기 (INSERT/UPDATE/DELETE)
async def execute(sql: str, args: tuple = ()) -> int: async def execute(sql: str, args: tuple = ()) -> int:
pool = await get_pool() 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: async with pool.acquire() as conn:
try: try:
async with conn.cursor() as cur: async with conn.cursor() as cur:
@@ -45,12 +39,6 @@ async def execute(sql: str, args: tuple = ()) -> int:
# 읽기 (SELECT) # 읽기 (SELECT)
async def fetchone(sql: str, args: tuple = ()) -> dict | None: async def fetchone(sql: str, args: tuple = ()) -> dict | None:
pool = await get_pool() 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: async with pool.acquire() as conn:
try: try:
async with conn.cursor(aiomysql.DictCursor) as cur: async with conn.cursor(aiomysql.DictCursor) as cur:
@@ -70,15 +58,6 @@ async def fetchall(sql: str, args: tuple = ()) -> list[dict]:
finally: finally:
conn.close() 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: 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)) 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" 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: if row_id is None:
return None return None
row = await fetchone(f"SELECT raw_data FROM {table} WHERE id = %s", (row_id,)) 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,), (analysis_run_id,),
) )
return { return {
"instagram": await _fetch_raw("instagram_data", run["instagram_data_id"]), "instagram": await fetch_raw("instagram_data", run["instagram_data_id"]),
"facebook": await _fetch_raw("facebook_data", run["facebook_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"]), "naver_blog": await fetch_raw("naver_blog_data", run["naver_blog_data_id"]),
"youtube": await _fetch_raw("youtube_data", run["youtube_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"]), "gangnam_unni": await fetch_raw("gangnam_unni_data", run["gangnam_unni_data_id"]),
} }
-44
View File
@@ -1,5 +1,4 @@
import os import os
import re
import asyncio import asyncio
from http import HTTPMethod from http import HTTPMethod
import httpx import httpx
@@ -38,46 +37,3 @@ async def http_request(
print(f" [error] {label} → {e}") print(f" [error] {label} → {e}")
return None return None
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
+13 -13
View File
@@ -38,8 +38,8 @@ class ApifyClient:
items = await self._run_actor("apify~instagram-profile-scraper", {"usernames": [username], "resultsLimit": 12}) items = await self._run_actor("apify~instagram-profile-scraper", {"usernames": [username], "resultsLimit": 12})
return items[0] if items else None return items[0] if items else None
async def get_instagram_profile(self, handle: str) -> dict | None: async def get_instagram_profile(self, url: str) -> dict | None:
profile = await self.fetch_instagram_profile(handle) profile = await self.fetch_instagram_profile(url)
if not profile or profile.get("error"): if not profile or profile.get("error"):
return None return None
return { return {
@@ -49,7 +49,7 @@ class ApifyClient:
"posts": profile.get("postsCount", 0), "posts": profile.get("postsCount", 0),
"bio": profile.get("biography", ""), "bio": profile.get("biography", ""),
"isBusinessAccount": profile.get("isBusinessAccount", False), "isBusinessAccount": profile.get("isBusinessAccount", False),
"externalUrl": profile.get("externalUrl"), #"externalUrl": profile.get("externalUrl"), LLM에 혼동을 주는 듯 하여 비활성화
"latestPosts": [ "latestPosts": [
{ {
"type": p.get("type"), "type": p.get("type"),
@@ -62,15 +62,15 @@ class ApifyClient:
], ],
} }
async def fetch_instagram_posts(self, handle: str, limit: int = 20) -> list[dict]: async def fetch_instagram_posts(self, url: str, limit: int = 20) -> list[dict]:
clean = handle.lstrip("@") username = urlparse(url).path.strip("/").split("/")[0] if "://" in url else url.lstrip("@")
return await self._run_actor("apify~instagram-post-scraper", { return await self._run_actor("apify~instagram-post-scraper", {
"directUrls": [f"https://www.instagram.com/{clean}/"], "directUrls": [f"https://www.instagram.com/{username}/"],
"resultsLimit": limit, "resultsLimit": limit,
}) })
async def get_instagram_posts(self, handle: str, limit: int = 20) -> dict: async def get_instagram_posts(self, url: str, limit: int = 20) -> dict:
items = await self.fetch_instagram_posts(handle, limit) items = await self.fetch_instagram_posts(url, limit)
posts = [ posts = [
{ {
"id": p["id"], "id": p["id"],
@@ -92,15 +92,15 @@ class ApifyClient:
"avgComments": round(sum(p["commentsCount"] for p in posts) / n), "avgComments": round(sum(p["commentsCount"] for p in posts) / n),
} }
async def fetch_instagram_reels(self, handle: str, limit: int = 15) -> list[dict]: async def fetch_instagram_reels(self, url: str, limit: int = 15) -> list[dict]:
clean = handle.lstrip("@") username = urlparse(url).path.strip("/").split("/")[0] if "://" in url else url.lstrip("@")
return await self._run_actor("apify~instagram-reel-scraper", { return await self._run_actor("apify~instagram-reel-scraper", {
"directUrls": [f"https://www.instagram.com/{clean}/reels/"], "directUrls": [f"https://www.instagram.com/{username}/reels/"],
"resultsLimit": limit, "resultsLimit": limit,
}) })
async def get_instagram_reels(self, handle: str, limit: int = 15) -> dict: async def get_instagram_reels(self, url: str, limit: int = 15) -> dict:
items = await self.fetch_instagram_reels(handle, limit) items = await self.fetch_instagram_reels(url, limit)
reels = [ reels = [
{ {
"id": r["id"], "id": r["id"],
+5 -3
View File
@@ -76,7 +76,7 @@ class FirecrawlClient:
"url": url, "url": url,
"formats": ["json", "links"], "formats": ["json", "links"],
"jsonOptions": { "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": { "schema": {
"type": "object", "type": "object",
"properties": { "properties": {
@@ -158,13 +158,14 @@ class FirecrawlClient:
"url": hospital_url, "url": hospital_url,
"formats": ["json"], "formats": ["json"],
"jsonOptions": { "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": { "schema": {
"type": "object", "type": "object",
"properties": { "properties": {
"hospitalName": {"type": "string"}, "hospitalName": {"type": "string"},
"rating": {"type": "number"}, "rating": {"type": "number"},
"totalReviews": {"type": "number"}, "totalReviews": {"type": "number"},
"totalMajorStaffs" : {"type" : "number"},
"doctors": { "doctors": {
"type": "array", "type": "array",
"items": { "items": {
@@ -202,7 +203,8 @@ class FirecrawlClient:
"rating": raw.get("rating"), "rating": raw.get("rating"),
"ratingScale": "/10", "ratingScale": "/10",
"totalReviews": raw.get("totalReviews", 0), "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", []), "procedures": raw.get("procedures", []),
"address": raw.get("address", ""), "address": raw.get("address", ""),
"badges": raw.get("badges", []), "badges": raw.get("badges", []),
+28 -14
View File
@@ -1,5 +1,4 @@
from http import HTTPMethod from http import HTTPMethod
from urllib.parse import urlparse
from common.utils import http_request from common.utils import http_request
YT = "https://www.googleapis.com/youtube/v3" YT = "https://www.googleapis.com/youtube/v3"
@@ -9,25 +8,40 @@ class YouTubeClient:
def __init__(self, api_key: str): def __init__(self, api_key: str):
self.api_key = api_key self.api_key = api_key
async def _resolve_channel_id(self, handle: str) -> str: async def _resolve_channel_id(self, url: str) -> str:
h = urlparse(handle).path.strip("/").lstrip("@") if "://" in handle else handle.lstrip("@") print("input yt url : ", url)
if h.startswith("UC") and len(h) == 24:
return h # /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"): for param in ("forHandle", "forUsername"):
resp = await http_request( resp = await http_request(
HTTPMethod.GET, HTTPMethod.GET,
url=f"{YT}/channels", 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", label="yt-resolve",
) )
if resp and resp.is_success: if resp and resp.is_success and (items := resp.json().get("items", [])):
items = resp.json().get("items", []) print("items : ", items)
if items: return items[0]["id"]
return items[0]["id"] print("YT NOT FOUND")
return "" return ""
async def fetch_channel(self, handle_or_id: str) -> dict | None: async def fetch_channel(self, url: str) -> dict | None:
channel_id = await self._resolve_channel_id(handle_or_id) channel_id = await self._resolve_channel_id(url)
if not channel_id: if not channel_id:
return None return None
@@ -67,8 +81,8 @@ class YouTubeClient:
return {"channelId": channel_id, "channel": channel, "videos": videos} return {"channelId": channel_id, "channel": channel, "videos": videos}
async def get_channel(self, handle_or_id: str) -> dict | None: async def get_channel(self, url: str) -> dict | None:
raw = await self.fetch_channel(handle_or_id) raw = await self.fetch_channel(url)
if not raw: if not raw:
return None return None
ch = raw["channel"] ch = raw["channel"]
+111 -2
View File
@@ -1,6 +1,6 @@
import json import json
import logging import logging
from common.db import fetchone, execute, get_analysis_raw_data, save_analysis_report, get_market_analysis 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.llm_service import LLMService
from integrations.llm.prompt import report_prompt, plan_prompt from integrations.llm.prompt import report_prompt, plan_prompt
from integrations.llm.schemas.report import ReportOutput from integrations.llm.schemas.report import ReportOutput
@@ -47,7 +47,6 @@ async def generate_report(analysis_run_id: str) -> ReportOutput:
return await LLMService(provider="perplexity").generate(report_prompt, input_data) 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:
run = await fetchone( run = await fetchone(
"SELECT hospital_id, report_data FROM analysis_runs WHERE analysis_run_id = %s", "SELECT hospital_id, report_data FROM analysis_runs WHERE analysis_run_id = %s",
@@ -84,9 +83,119 @@ 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)
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 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 {}
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 = {}
# ── gangnam_unni ──────────────────────────────────────────────────────────
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 gangnam_unni.get("rating"): snapshot["overall_rating"] = gangnam_unni["rating"]
if gangnam_unni.get("totalReviews"): snapshot["total_reviews"] = gangnam_unni["totalReviews"]
if gangnam_unni.get("address"): snapshot["location"] = gangnam_unni["address"]
if gangnam_unni.get("badges"): snapshot["certifications"] = gangnam_unni["badges"]
if gangnam_unni.get("totalMajorStaffs"): snapshot["staff_count"] = gangnam_unni["totalMajorStaffs"]
if lead:
snapshot["lead_doctor"] = {
"name": lead.get("name"),
"credentials": lead.get("specialty"),
"rating": lead.get("rating"),
"review_count": lead.get("reviews"),
}
# ── instagram ─────────────────────────────────────────────────────────────
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"]
# ── youtube ───────────────────────────────────────────────────────────────
yt_patch: dict = {}
if youtube.get("channelName"): yt_patch["channel_name"] = youtube["channelName"]
if youtube.get("handle"): yt_patch["handle"] = youtube["handle"]
if youtube.get("subscribers"): yt_patch["subscribers"] = youtube["subscribers"]
if youtube.get("totalVideos"): yt_patch["total_videos"] = youtube["totalVideos"]
if youtube.get("totalViews"): yt_patch["total_views"] = youtube["totalViews"]
if youtube.get("publishedAt"): yt_patch["channel_created_date"] = youtube["publishedAt"][:10]
if youtube.get("description"): yt_patch["channel_description"] = youtube["description"]
if youtube.get("videos"):
yt_patch["top_videos"] = [
{
"title": v["title"],
"views": v["views"],
"duration": v.get("duration"),
"type": "Short" if "M" not in v.get("duration", "") else "Long",
"uploaded_ago": v.get("date", "")[:10],
}
for v in youtube["videos"]
]
overrides: dict = {}
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)
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)
result = await generate_report(analysis_run_id) 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()) await save_analysis_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)
-54
View File
@@ -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())