Compare commits
10
Commits
upload
...
ab215395c6
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ab215395c6 | ||
|
|
d1293f9188 | ||
|
|
0e68cbe71b | ||
|
|
cb798f7acc | ||
|
|
84fd854d15 | ||
|
|
8e5ce3e012 | ||
|
|
b921a0803e | ||
|
|
e8406dc0ee | ||
|
|
09bb7a71ee | ||
|
|
1f45b3e53d |
No files matched your search
@@ -44,3 +44,5 @@ Thumbs.db
|
|||||||
alembic/versions/*.pyc
|
alembic/versions/*.pyc
|
||||||
|
|
||||||
test_results/
|
test_results/
|
||||||
|
|
||||||
|
app/test*
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
-- user_info
|
||||||
|
CREATE TABLE user_info
|
||||||
|
(
|
||||||
|
`user_id` INT NOT NULL AUTO_INCREMENT,
|
||||||
|
`username` VARCHAR(50) NOT NULL,
|
||||||
|
`password` VARCHAR(50) NOT NULL,
|
||||||
|
`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
`updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
PRIMARY KEY (user_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
|
-- hospital_baseinfo
|
||||||
|
CREATE TABLE hospital_baseinfo
|
||||||
|
(
|
||||||
|
`hospital_id` CHAR(36) NOT NULL,
|
||||||
|
`owner_user_id` INT NOT NULL,
|
||||||
|
`hospital_name` VARCHAR(50) NOT NULL,
|
||||||
|
`hospital_name_en` VARCHAR(50) NULL,
|
||||||
|
`brn` VARCHAR(50) NOT NULL,
|
||||||
|
`road_address` VARCHAR(100) NULL,
|
||||||
|
`site_address` VARCHAR(100) NULL,
|
||||||
|
`status` VARCHAR(20) NOT NULL DEFAULT 'start',
|
||||||
|
`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
`updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
PRIMARY KEY (hospital_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IX_hospital_baseinfo_1 ON hospital_baseinfo (owner_user_id);
|
||||||
|
|
||||||
|
|
||||||
|
-- remote_source: 병원별 채널 소스 정보 (instagram/facebook/naver_blog/youtube/gangnam_unni 등)
|
||||||
|
CREATE TABLE remote_source
|
||||||
|
(
|
||||||
|
`source_id` INT NOT NULL AUTO_INCREMENT,
|
||||||
|
`hospital_id` CHAR(36) NOT NULL,
|
||||||
|
`source_type` VARCHAR(50) NOT NULL,
|
||||||
|
`url` VARCHAR(500) NOT NULL,
|
||||||
|
`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
PRIMARY KEY (source_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IX_remote_source_1 ON remote_source (hospital_id);
|
||||||
|
CREATE INDEX IX_remote_source_2 ON remote_source (hospital_id, source_type);
|
||||||
|
|
||||||
|
|
||||||
|
-- analysis_runs
|
||||||
|
CREATE TABLE analysis_runs
|
||||||
|
(
|
||||||
|
`analysis_run_id` CHAR(36) NOT NULL,
|
||||||
|
`hospital_id` CHAR(36) NOT NULL,
|
||||||
|
`owner_user_id` INT NOT NULL DEFAULT 0,
|
||||||
|
`status` VARCHAR(50) NOT NULL DEFAULT 'discovering',
|
||||||
|
`report_data` JSON NULL,
|
||||||
|
`plan_data` JSON NULL,
|
||||||
|
`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
`updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
PRIMARY KEY (analysis_run_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IX_analysis_runs_1 ON analysis_runs (hospital_id);
|
||||||
|
CREATE INDEX IX_analysis_runs_2 ON analysis_runs (owner_user_id);
|
||||||
|
|
||||||
|
|
||||||
|
-- raw_info: 분석 실행별 수집 원시 데이터
|
||||||
|
CREATE TABLE raw_info
|
||||||
|
(
|
||||||
|
`info_id` INT NOT NULL AUTO_INCREMENT,
|
||||||
|
`source_id` INT NOT NULL,
|
||||||
|
`analysis_run_id` CHAR(36) NOT NULL,
|
||||||
|
`data_tag` VARCHAR(50) NOT NULL DEFAULT 'default',
|
||||||
|
`status` VARCHAR(20) NOT NULL DEFAULT 'start',
|
||||||
|
`raw_data` JSON NULL,
|
||||||
|
`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
`updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
PRIMARY KEY (info_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IX_raw_info_1 ON raw_info (analysis_run_id);
|
||||||
|
CREATE INDEX IX_raw_info_2 ON raw_info (source_id);
|
||||||
|
|
||||||
|
|
||||||
|
-- file_data
|
||||||
|
CREATE TABLE file_data
|
||||||
|
(
|
||||||
|
`id` INT NOT NULL AUTO_INCREMENT,
|
||||||
|
`analysis_run_id` CHAR(36) NOT NULL,
|
||||||
|
`hospital_id` CHAR(36) NULL,
|
||||||
|
`file_type` ENUM('image','video','audio','document','file') NOT NULL DEFAULT 'file',
|
||||||
|
`file_name` VARCHAR(255) NOT NULL,
|
||||||
|
`file_url` VARCHAR(2048) NOT NULL,
|
||||||
|
`size_bytes` BIGINT NULL,
|
||||||
|
`is_deleted` BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
PRIMARY KEY (id),
|
||||||
|
INDEX IX_file_data_1 (analysis_run_id, is_deleted)
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
|
-- hospital_history
|
||||||
|
CREATE TABLE hospital_history
|
||||||
|
(
|
||||||
|
`id` INT NOT NULL AUTO_INCREMENT,
|
||||||
|
`hospital_id` CHAR(36) NOT NULL,
|
||||||
|
`owner_user_id` INT NOT NULL,
|
||||||
|
`hospital_name` VARCHAR(50) NOT NULL,
|
||||||
|
`hospital_name_en` VARCHAR(50) NULL,
|
||||||
|
`brn` VARCHAR(50) NOT NULL,
|
||||||
|
`road_address` VARCHAR(100) NULL,
|
||||||
|
`site_address` VARCHAR(100) NULL,
|
||||||
|
`status` VARCHAR(20) NOT NULL,
|
||||||
|
`analysis_run_id` CHAR(36) NULL,
|
||||||
|
`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
PRIMARY KEY (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IX_hospital_history_1 ON hospital_history (hospital_id);
|
||||||
|
CREATE INDEX IX_hospital_history_2 ON hospital_history (analysis_run_id);
|
||||||
|
|
||||||
|
|
||||||
|
-- market_analysis
|
||||||
|
CREATE TABLE market_analysis
|
||||||
|
(
|
||||||
|
`id` INT NOT NULL AUTO_INCREMENT,
|
||||||
|
`analysis_run_id` CHAR(36) NOT NULL,
|
||||||
|
`analysis_type` VARCHAR(50) NOT NULL,
|
||||||
|
`status` VARCHAR(20) NOT NULL DEFAULT 'start',
|
||||||
|
`data` JSON NULL,
|
||||||
|
`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
PRIMARY KEY (id),
|
||||||
|
UNIQUE KEY UQ_market_analysis (analysis_run_id, analysis_type)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IX_market_analysis_1 ON market_analysis (analysis_run_id);
|
||||||
+6
-27
@@ -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"]),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,236 @@
|
|||||||
|
import json
|
||||||
|
import os
|
||||||
|
import aiomysql
|
||||||
|
from common.utils import get_env
|
||||||
|
|
||||||
|
_pool: aiomysql.Pool | None = None
|
||||||
|
|
||||||
|
|
||||||
|
async def get_pool() -> aiomysql.Pool:
|
||||||
|
global _pool
|
||||||
|
if _pool is None:
|
||||||
|
_pool = await aiomysql.create_pool(
|
||||||
|
host=get_env("MYSQL_HOST"),
|
||||||
|
port=int(os.getenv("MYSQL_PORT", "3306")),
|
||||||
|
user=get_env("MYSQL_USER"),
|
||||||
|
password=get_env("MYSQL_PASSWORD"),
|
||||||
|
db=get_env("MYSQL_DB"),
|
||||||
|
charset="utf8mb4",
|
||||||
|
minsize=0,
|
||||||
|
maxsize=30,
|
||||||
|
connect_timeout=10,
|
||||||
|
)
|
||||||
|
return _pool
|
||||||
|
|
||||||
|
|
||||||
|
async def execute(sql: str, args: tuple = ()) -> int:
|
||||||
|
pool = await get_pool()
|
||||||
|
async with pool.acquire() as conn:
|
||||||
|
try:
|
||||||
|
async with conn.cursor() as cur:
|
||||||
|
await cur.execute(sql, args)
|
||||||
|
await conn.commit()
|
||||||
|
return cur.lastrowid
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
async def fetchone(sql: str, args: tuple = ()) -> dict | None:
|
||||||
|
pool = await get_pool()
|
||||||
|
async with pool.acquire() as conn:
|
||||||
|
try:
|
||||||
|
async with conn.cursor(aiomysql.DictCursor) as cur:
|
||||||
|
await cur.execute(sql, args)
|
||||||
|
return await cur.fetchone()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
async def fetchall(sql: str, args: tuple = ()) -> list[dict]:
|
||||||
|
pool = await get_pool()
|
||||||
|
async with pool.acquire() as conn:
|
||||||
|
try:
|
||||||
|
async with conn.cursor(aiomysql.DictCursor) as cur:
|
||||||
|
await cur.execute(sql, args)
|
||||||
|
return await cur.fetchall()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
# ── remote_source ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async def insert_source(hospital_id: str, source_type: str, url: str) -> int:
|
||||||
|
return await execute(
|
||||||
|
"INSERT INTO remote_source (hospital_id, source_type, url) VALUES (%s, %s, %s)",
|
||||||
|
(hospital_id, source_type, url),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ── raw_info ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async def insert_raw_info(source_id: int, analysis_run_id: str, data_tag: str = "default") -> int:
|
||||||
|
return await execute(
|
||||||
|
"INSERT INTO raw_info (source_id, analysis_run_id, data_tag) VALUES (%s, %s, %s)",
|
||||||
|
(source_id, analysis_run_id, data_tag),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def set_raw_info_status(info_id: int, status: str) -> None:
|
||||||
|
await execute("UPDATE raw_info SET status = %s WHERE info_id = %s", (status, info_id))
|
||||||
|
|
||||||
|
|
||||||
|
async def save_raw_info(info_id: int, data: dict) -> None:
|
||||||
|
await execute(
|
||||||
|
"UPDATE raw_info SET raw_data = %s, status = 'done' WHERE info_id = %s",
|
||||||
|
(json.dumps(data, ensure_ascii=False), info_id),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def fetch_raw(info_id: int | None) -> dict | None:
|
||||||
|
if info_id is None:
|
||||||
|
return None
|
||||||
|
row = await fetchone("SELECT raw_data FROM raw_info WHERE info_id = %s", (info_id,))
|
||||||
|
if not row or not row["raw_data"]:
|
||||||
|
return None
|
||||||
|
return json.loads(row["raw_data"]) if isinstance(row["raw_data"], str) else row["raw_data"]
|
||||||
|
|
||||||
|
|
||||||
|
async def is_done(info_id: int | None) -> bool:
|
||||||
|
if info_id is None:
|
||||||
|
return True
|
||||||
|
r = await fetchone("SELECT status FROM raw_info WHERE info_id = %s", (info_id,))
|
||||||
|
return r["status"] == "done"
|
||||||
|
|
||||||
|
|
||||||
|
async def get_analysis_raw_data(analysis_run_id: str) -> dict:
|
||||||
|
rows = await fetchall(
|
||||||
|
"SELECT rs.source_type, ri.raw_data"
|
||||||
|
" FROM raw_info ri JOIN remote_source rs USING (source_id)"
|
||||||
|
" WHERE ri.analysis_run_id = %s",
|
||||||
|
(analysis_run_id,),
|
||||||
|
)
|
||||||
|
result: dict = {}
|
||||||
|
for row in rows:
|
||||||
|
raw = row["raw_data"]
|
||||||
|
result[row["source_type"]] = json.loads(raw) if isinstance(raw, str) else raw
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
# ── analysis_runs ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async def insert_analysis_run(
|
||||||
|
analysis_run_id: str,
|
||||||
|
hospital_id: str,
|
||||||
|
owner_user_id: int,
|
||||||
|
) -> str:
|
||||||
|
await execute(
|
||||||
|
"INSERT INTO analysis_runs (analysis_run_id, hospital_id, owner_user_id)"
|
||||||
|
" VALUES (%s, %s, %s)",
|
||||||
|
(analysis_run_id, hospital_id, owner_user_id),
|
||||||
|
)
|
||||||
|
return analysis_run_id
|
||||||
|
|
||||||
|
|
||||||
|
async def save_analysis_report(analysis_run_id: str, data: dict) -> None:
|
||||||
|
await execute(
|
||||||
|
"UPDATE analysis_runs SET report_data = %s WHERE analysis_run_id = %s",
|
||||||
|
(json.dumps(data, ensure_ascii=False), analysis_run_id),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ── hospital_baseinfo ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async def _insert_hospital_history(hospital_id: str, analysis_run_id: str | None) -> None:
|
||||||
|
row = await fetchone(
|
||||||
|
"SELECT owner_user_id, hospital_name, hospital_name_en, brn, road_address, site_address, status"
|
||||||
|
" FROM hospital_baseinfo WHERE hospital_id = %s",
|
||||||
|
(hospital_id,),
|
||||||
|
)
|
||||||
|
if not row:
|
||||||
|
return
|
||||||
|
await execute(
|
||||||
|
"INSERT INTO hospital_history"
|
||||||
|
" (hospital_id, owner_user_id, hospital_name, hospital_name_en, brn, road_address, site_address, status, analysis_run_id)"
|
||||||
|
" VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)",
|
||||||
|
(
|
||||||
|
hospital_id,
|
||||||
|
row["owner_user_id"],
|
||||||
|
row["hospital_name"],
|
||||||
|
row["hospital_name_en"],
|
||||||
|
row["brn"],
|
||||||
|
row["road_address"],
|
||||||
|
row["site_address"],
|
||||||
|
row["status"],
|
||||||
|
analysis_run_id,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def insert_hospital(
|
||||||
|
hospital_id: str,
|
||||||
|
name: str,
|
||||||
|
name_en: str | None = None,
|
||||||
|
road_address: str | None = None,
|
||||||
|
site_address: str | None = None,
|
||||||
|
owner_user_id: int = 0,
|
||||||
|
brn: str = "",
|
||||||
|
) -> dict:
|
||||||
|
await execute(
|
||||||
|
"INSERT INTO hospital_baseinfo (hospital_id, hospital_name, hospital_name_en, road_address, site_address, status, owner_user_id, brn)"
|
||||||
|
" VALUES (%s, %s, %s, %s, %s, 'done', %s, %s)",
|
||||||
|
(hospital_id, name, name_en, road_address, site_address, owner_user_id, brn),
|
||||||
|
)
|
||||||
|
await _insert_hospital_history(hospital_id, analysis_run_id=None)
|
||||||
|
return await fetchone(
|
||||||
|
"SELECT created_at FROM hospital_baseinfo WHERE hospital_id = %s",
|
||||||
|
(hospital_id,),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def update_hospital_info(hospital_id: str, data: dict, analysis_run_id: str | None = None) -> None:
|
||||||
|
"""clinic 스크래핑 후 hospital_baseinfo의 기본 필드 업데이트."""
|
||||||
|
await execute(
|
||||||
|
"UPDATE hospital_baseinfo"
|
||||||
|
" SET status = 'done',"
|
||||||
|
" hospital_name = COALESCE(%s, hospital_name),"
|
||||||
|
" hospital_name_en = COALESCE(%s, hospital_name_en),"
|
||||||
|
" road_address = COALESCE(%s, road_address)"
|
||||||
|
" WHERE hospital_id = %s",
|
||||||
|
(
|
||||||
|
data.get("clinicName"),
|
||||||
|
data.get("clinicNameEn"),
|
||||||
|
data.get("address"),
|
||||||
|
hospital_id,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
await _insert_hospital_history(hospital_id, analysis_run_id)
|
||||||
|
|
||||||
|
|
||||||
|
# ── file_data ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async def insert_file_row(
|
||||||
|
analysis_run_id: str,
|
||||||
|
file_type: str,
|
||||||
|
file_name: str,
|
||||||
|
file_url: str,
|
||||||
|
size_bytes: int | None = None,
|
||||||
|
hospital_id: str | None = None,
|
||||||
|
) -> int:
|
||||||
|
return await execute(
|
||||||
|
"INSERT INTO file_data (analysis_run_id, hospital_id, file_type, file_name, file_url, size_bytes)"
|
||||||
|
" VALUES (%s, %s, %s, %s, %s, %s)",
|
||||||
|
(analysis_run_id, hospital_id, file_type, file_name, file_url, size_bytes),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ── market_analysis ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async def get_market_analysis(analysis_run_id: str) -> dict:
|
||||||
|
rows = await fetchall(
|
||||||
|
"SELECT analysis_type, data FROM market_analysis WHERE analysis_run_id = %s AND status = 'done'",
|
||||||
|
(analysis_run_id,),
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
row["analysis_type"]: json.loads(row["data"]) if isinstance(row["data"], str) else row["data"]
|
||||||
|
for row in rows
|
||||||
|
}
|
||||||
@@ -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
|
|
||||||
+14
-13
@@ -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}/"],
|
"username": [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,16 @@ 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("@")
|
||||||
|
print(username)
|
||||||
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/"],
|
"username": [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"],
|
||||||
|
|||||||
@@ -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", []),
|
||||||
|
|||||||
+27
-13
@@ -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"]
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+147
-2
@@ -1,6 +1,7 @@
|
|||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
from common.db import fetchone, execute, get_analysis_raw_data, save_analysis_report, get_market_analysis
|
import os
|
||||||
|
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 +48,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,15 +84,160 @@ 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)
|
||||||
|
|
||||||
|
|
||||||
|
_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:
|
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)
|
||||||
|
if await _is_mock(analysis_run_id):
|
||||||
|
logger.info("[report] mock mode run=%s", analysis_run_id)
|
||||||
|
result = _load_mock_report()
|
||||||
|
else:
|
||||||
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)
|
||||||
|
|
||||||
|
|
||||||
async def run_plan_task(analysis_run_id: str) -> None:
|
async def run_plan_task(analysis_run_id: str) -> None:
|
||||||
logger.info("[plan] start run=%s", analysis_run_id)
|
logger.info("[plan] start run=%s", analysis_run_id)
|
||||||
|
if await _is_mock(analysis_run_id):
|
||||||
|
logger.info("[plan] mock mode run=%s", analysis_run_id)
|
||||||
|
result = _load_mock_plan()
|
||||||
|
else:
|
||||||
result = await generate_plan(analysis_run_id)
|
result = await generate_plan(analysis_run_id)
|
||||||
await execute(
|
await execute(
|
||||||
"UPDATE analysis_runs SET plan_data = %s WHERE analysis_run_id = %s",
|
"UPDATE analysis_runs SET plan_data = %s WHERE analysis_run_id = %s",
|
||||||
|
|||||||
@@ -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