db migration done
This commit is contained in:
1 parent
c9c5ee9177
commit
3b4c154fb2
23 files changed
+622
-1049
No files matched your search
+27
-57
@@ -3,7 +3,10 @@ import logging
|
||||
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 urllib.parse import urlparse
|
||||
from common.db.run import select_run, update_run_report, update_run_plan
|
||||
from common.db.source import select_run_raw_data, select_run_mainpage_url
|
||||
from common.db.market import select_market
|
||||
from integrations.llm.llm_service import LLMService
|
||||
from integrations.llm.prompt import report_prompt, plan_prompt, youtube_diagnosis_prompt
|
||||
from integrations.llm.schemas.report import ReportOutput, ClinicSnapshot, YouTubeAudit
|
||||
@@ -14,18 +17,9 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def generate_report(analysis_run_id: str) -> ReportOutput:
|
||||
run = await fetchone(
|
||||
"SELECT hospital_id FROM analysis_runs WHERE analysis_run_id = %s",
|
||||
(analysis_run_id,),
|
||||
)
|
||||
clinic_row = await fetchone(
|
||||
"SELECT raw_data FROM hospital_baseinfo WHERE hospital_id = %s",
|
||||
(run["hospital_id"],),
|
||||
)
|
||||
raw_data = clinic_row["raw_data"] if clinic_row else None
|
||||
clinic = json.loads(raw_data) if isinstance(raw_data, str) else (raw_data or {})
|
||||
raw = await get_analysis_raw_data(analysis_run_id)
|
||||
market = await get_market_analysis(analysis_run_id)
|
||||
raw = await select_run_raw_data(analysis_run_id)
|
||||
clinic = raw.get("mainpage") or {}
|
||||
market = await select_market(analysis_run_id)
|
||||
|
||||
def _json(v) -> str | None:
|
||||
return json.dumps(v, ensure_ascii=False) if v else None
|
||||
@@ -43,27 +37,21 @@ async def generate_report(analysis_run_id: str) -> ReportOutput:
|
||||
"market_trend": _json(market.get("trend")),
|
||||
"market_target_audience": _json(market.get("target_audience")),
|
||||
**{
|
||||
channel: _json(data)
|
||||
for channel, data in raw.items()
|
||||
source_type: _json(data)
|
||||
for source_type, data in raw.items()
|
||||
if source_type != "mainpage"
|
||||
},
|
||||
}
|
||||
|
||||
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",
|
||||
(analysis_run_id,),
|
||||
)
|
||||
clinic_row = await fetchone(
|
||||
"SELECT raw_data FROM hospital_baseinfo WHERE hospital_id = %s",
|
||||
(run["hospital_id"],),
|
||||
)
|
||||
raw_data = clinic_row["raw_data"] if clinic_row else None
|
||||
clinic = json.loads(raw_data) if isinstance(raw_data, str) else (raw_data or {})
|
||||
run = await select_run(analysis_run_id)
|
||||
raw = await select_run_raw_data(analysis_run_id)
|
||||
clinic = raw.get("mainpage") or {}
|
||||
report_data = run["report_data"]
|
||||
report = json.loads(report_data) if isinstance(report_data, str) else report_data
|
||||
market = await get_market_analysis(analysis_run_id)
|
||||
market = await select_market(analysis_run_id)
|
||||
|
||||
def _json(v) -> str | None:
|
||||
return json.dumps(v, ensure_ascii=False) if v else None
|
||||
@@ -93,7 +81,8 @@ def _build_clinic_snapshot(gangnam_unni: dict, hospital: dict) -> dict:
|
||||
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"]
|
||||
domain = hospital.get("domain") or urlparse(hospital.get("sourceUrl") or "").netloc
|
||||
if domain: snapshot["domain"] = 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"]
|
||||
@@ -221,28 +210,17 @@ async def _build_youtube_audit(youtube: dict) -> dict:
|
||||
|
||||
|
||||
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:
|
||||
raw = await select_run_raw_data(analysis_run_id)
|
||||
if not raw:
|
||||
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 {}
|
||||
mainpage = raw.get("mainpage", {}) or {}
|
||||
instagram = raw.get("instagram", {}) or {}
|
||||
facebook = raw.get("facebook", {}) or {}
|
||||
youtube = raw.get("youtube", {}) or {}
|
||||
gangnam_unni = raw.get("gangnam_unni", {}) or {}
|
||||
|
||||
snapshot: dict = _build_clinic_snapshot(gangnam_unni, hospital)
|
||||
snapshot: dict = _build_clinic_snapshot(gangnam_unni, mainpage)
|
||||
yt_patch: dict = await _build_youtube_audit(youtube)
|
||||
|
||||
# ── instagram ─────────────────────────────────────────────────────────────
|
||||
@@ -299,12 +277,7 @@ _MOCK_REPORT_PATH = os.path.join(os.path.dirname(__file__), "../mock/report_view
|
||||
|
||||
|
||||
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 ""
|
||||
url = await select_run_mainpage_url(analysis_run_id)
|
||||
return any(domain in url for domain in _MOCK_DOMAINS)
|
||||
|
||||
|
||||
@@ -330,7 +303,7 @@ async def run_report_task(analysis_run_id: str) -> None:
|
||||
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())
|
||||
await update_run_report(analysis_run_id, result.model_dump())
|
||||
logger.info("[report] done run=%s", analysis_run_id)
|
||||
|
||||
|
||||
@@ -341,8 +314,5 @@ async def run_plan_task(analysis_run_id: str) -> None:
|
||||
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),
|
||||
)
|
||||
await update_run_plan(analysis_run_id, result.model_dump())
|
||||
logger.info("[plan] done run=%s", analysis_run_id)
|
||||
+67
-53
@@ -1,96 +1,110 @@
|
||||
import asyncio
|
||||
import logging
|
||||
from common.db import fetchone
|
||||
from common.db import (
|
||||
set_instagram_status, save_instagram_raw_data,
|
||||
set_facebook_status, save_facebook_raw_data,
|
||||
set_naver_blog_status, save_naver_blog_raw_data,
|
||||
set_youtube_status, save_youtube_raw_data,
|
||||
set_gangnam_unni_status, save_gangnam_unni_raw_data,
|
||||
execute, save_hospital_raw_data,
|
||||
)
|
||||
from common.db.hospital import update_hospital_status, update_hospital
|
||||
from common.db.source import select_run_sources, update_raw_info_status, update_raw_info
|
||||
from common.utils import get_env
|
||||
from integrations.apify import ApifyClient
|
||||
from integrations.naver import NaverClient
|
||||
from integrations.youtube import YouTubeClient
|
||||
from integrations.firecrawl import FirecrawlClient
|
||||
from models.status import SourceType
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def collect_instagram(analysis_run_id: str, row_id: int, url: str) -> None:
|
||||
async def collect_instagram(analysis_run_id: str, info_id: int, url: str) -> None:
|
||||
logger.info("[instagram] start run=%s url=%s", analysis_run_id, url)
|
||||
await set_instagram_status(row_id, "processing")
|
||||
await update_raw_info_status(info_id, "processing")
|
||||
data = await ApifyClient(get_env("APIFY_API_TOKEN")).get_instagram_profile(url)
|
||||
await save_instagram_raw_data(row_id, data)
|
||||
if data is None:
|
||||
await update_raw_info_status(info_id, "failed")
|
||||
logger.warning("[instagram] failed run=%s", analysis_run_id)
|
||||
return
|
||||
await update_raw_info(info_id, data)
|
||||
logger.info("[instagram] done run=%s", analysis_run_id)
|
||||
|
||||
|
||||
async def collect_facebook(analysis_run_id: str, row_id: int, url: str) -> None:
|
||||
async def collect_facebook(analysis_run_id: str, info_id: int, url: str) -> None:
|
||||
logger.info("[facebook] start run=%s url=%s", analysis_run_id, url)
|
||||
await set_facebook_status(row_id, "processing")
|
||||
await update_raw_info_status(info_id, "processing")
|
||||
data = await ApifyClient(get_env("APIFY_API_TOKEN")).get_facebook_page(url)
|
||||
await save_facebook_raw_data(row_id, data)
|
||||
if data is None:
|
||||
await update_raw_info_status(info_id, "failed")
|
||||
logger.warning("[facebook] failed run=%s", analysis_run_id)
|
||||
return
|
||||
await update_raw_info(info_id, data)
|
||||
logger.info("[facebook] done run=%s", analysis_run_id)
|
||||
|
||||
|
||||
async def collect_naver_blog(analysis_run_id: str, row_id: int, url: str) -> None:
|
||||
async def collect_naver_blog(analysis_run_id: str, info_id: int, url: str) -> None:
|
||||
logger.info("[naver_blog] start run=%s url=%s", analysis_run_id, url)
|
||||
await set_naver_blog_status(row_id, "processing")
|
||||
await update_raw_info_status(info_id, "processing")
|
||||
data = await NaverClient(get_env("NAVER_CLIENT_ID"), get_env("NAVER_CLIENT_SECRET")).get_blog_rss(url)
|
||||
await save_naver_blog_raw_data(row_id, data)
|
||||
if data is None:
|
||||
await update_raw_info_status(info_id, "failed")
|
||||
logger.warning("[naver_blog] failed run=%s", analysis_run_id)
|
||||
return
|
||||
await update_raw_info(info_id, data)
|
||||
logger.info("[naver_blog] done run=%s", analysis_run_id)
|
||||
|
||||
|
||||
async def collect_youtube(analysis_run_id: str, row_id: int, url: str) -> None:
|
||||
async def collect_youtube(analysis_run_id: str, info_id: int, url: str) -> None:
|
||||
logger.info("[youtube] start run=%s url=%s", analysis_run_id, url)
|
||||
await set_youtube_status(row_id, "processing")
|
||||
await update_raw_info_status(info_id, "processing")
|
||||
data = await YouTubeClient(get_env("YOUTUBE_API_KEY")).get_channel(url)
|
||||
await save_youtube_raw_data(row_id, data)
|
||||
if data is None:
|
||||
await update_raw_info_status(info_id, "failed")
|
||||
logger.warning("[youtube] failed run=%s", analysis_run_id)
|
||||
return
|
||||
await update_raw_info(info_id, data)
|
||||
logger.info("[youtube] done run=%s", analysis_run_id)
|
||||
|
||||
|
||||
async def collect_gangnam_unni(analysis_run_id: str, row_id: int, url: str) -> None:
|
||||
async def collect_gangnam_unni(analysis_run_id: str, info_id: int, url: str) -> None:
|
||||
logger.info("[gangnam_unni] start run=%s url=%s", analysis_run_id, url)
|
||||
await set_gangnam_unni_status(row_id, "processing")
|
||||
await update_raw_info_status(info_id, "processing")
|
||||
data = await FirecrawlClient(get_env("FIRECRAWL_API_KEY")).get_gangnam_unni(url)
|
||||
await save_gangnam_unni_raw_data(row_id, data)
|
||||
if data is None:
|
||||
await update_raw_info_status(info_id, "failed")
|
||||
logger.warning("[gangnam_unni] failed run=%s", analysis_run_id)
|
||||
return
|
||||
await update_raw_info(info_id, data)
|
||||
logger.info("[gangnam_unni] done run=%s", analysis_run_id)
|
||||
|
||||
|
||||
async def collect_clinic_info(analysis_run_id: str, hospital_id: str, url: str) -> None:
|
||||
logger.info("[clinic] start run=%s url=%s", analysis_run_id, url)
|
||||
await execute("UPDATE hospital_baseinfo SET status = 'processing' WHERE hospital_id = %s", (hospital_id,))
|
||||
async def collect_mainpage(analysis_run_id: str, info_id: int, hospital_id: str, url: str) -> None:
|
||||
logger.info("[mainpage] start run=%s url=%s", analysis_run_id, url)
|
||||
await update_raw_info_status(info_id, "processing")
|
||||
await update_hospital_status(hospital_id, "processing")
|
||||
data = await FirecrawlClient(get_env("FIRECRAWL_API_KEY")).fetch_clinic_info(url)
|
||||
await save_hospital_raw_data(hospital_id, data, analysis_run_id=analysis_run_id)
|
||||
logger.info("[clinic] done run=%s", analysis_run_id)
|
||||
if data is None:
|
||||
await update_raw_info_status(info_id, "failed")
|
||||
logger.warning("[mainpage] failed run=%s", analysis_run_id)
|
||||
return
|
||||
await update_raw_info(info_id, data)
|
||||
await update_hospital(hospital_id, data, analysis_run_id=analysis_run_id)
|
||||
logger.info("[mainpage] done run=%s", analysis_run_id)
|
||||
|
||||
|
||||
async def collect_all(
|
||||
analysis_run_id: str,
|
||||
hospital_id: str,
|
||||
instagram_id: int | None = None,
|
||||
facebook_id: int | None = None,
|
||||
naver_blog_id: int | None = None,
|
||||
youtube_id: int | None = None,
|
||||
gangnam_unni_id: int | None = None,
|
||||
) -> None:
|
||||
async def _url(table: str, row_id: int) -> str:
|
||||
row = await fetchone(f"SELECT url FROM {table} WHERE id = %s", (row_id,))
|
||||
return row["url"] if row else ""
|
||||
async def collect_all(analysis_run_id: str, hospital_id: str) -> None:
|
||||
rows = await select_run_sources(analysis_run_id)
|
||||
|
||||
hospital = await fetchone("SELECT url FROM hospital_baseinfo WHERE hospital_id = %s", (hospital_id,))
|
||||
tasks = [collect_clinic_info(analysis_run_id, hospital_id, hospital["url"])]
|
||||
_collectors = {
|
||||
SourceType.INSTAGRAM: collect_instagram,
|
||||
SourceType.FACEBOOK: collect_facebook,
|
||||
SourceType.NAVER_BLOG: collect_naver_blog,
|
||||
SourceType.YOUTUBE: collect_youtube,
|
||||
SourceType.GANGNAM_UNNI: collect_gangnam_unni,
|
||||
}
|
||||
|
||||
if instagram_id:
|
||||
tasks.append(collect_instagram(analysis_run_id, instagram_id, await _url("instagram_data", instagram_id)))
|
||||
if facebook_id:
|
||||
tasks.append(collect_facebook(analysis_run_id, facebook_id, await _url("facebook_data", facebook_id)))
|
||||
if naver_blog_id:
|
||||
tasks.append(collect_naver_blog(analysis_run_id, naver_blog_id, await _url("naver_blog_data", naver_blog_id)))
|
||||
if youtube_id:
|
||||
tasks.append(collect_youtube(analysis_run_id, youtube_id, await _url("youtube_data", youtube_id)))
|
||||
if gangnam_unni_id:
|
||||
tasks.append(collect_gangnam_unni(analysis_run_id, gangnam_unni_id, await _url("gangnam_unni_data", gangnam_unni_id)))
|
||||
tasks = []
|
||||
for row in rows:
|
||||
info_id = row["info_id"]
|
||||
source_type = row["source_type"]
|
||||
url = row["url"]
|
||||
if source_type == SourceType.MAINPAGE:
|
||||
tasks.append(collect_mainpage(analysis_run_id, info_id, hospital_id, url))
|
||||
elif source_type in _collectors:
|
||||
tasks.append(_collectors[source_type](analysis_run_id, info_id, url))
|
||||
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
@@ -2,7 +2,8 @@ import logging
|
||||
|
||||
from fastapi import HTTPException, UploadFile
|
||||
|
||||
from common.db import execute, fetchall, fetchone, insert_file_row
|
||||
from common.db.run import select_run
|
||||
from common.db.file_data import insert_file, select_run_files, select_file, delete_file
|
||||
from integrations.azure_blob import AzureBlobUploader
|
||||
from models.file import FileListItem, FileType, FileUploadResponse
|
||||
|
||||
@@ -31,10 +32,7 @@ async def upload_analysis_file(
|
||||
content_type: str | None = None,
|
||||
) -> tuple[int, str]:
|
||||
"""analysis_run에 딸린 파일 업로드. Blob 업로드 + file_data row 생성. (file_id, url) 반환."""
|
||||
run = await fetchone(
|
||||
"SELECT hospital_id FROM analysis_runs WHERE analysis_run_id = %s",
|
||||
(analysis_run_id,),
|
||||
)
|
||||
run = await select_run(analysis_run_id)
|
||||
if not run:
|
||||
raise HTTPException(status_code=404, detail="analysis_run not found")
|
||||
hospital_id = run["hospital_id"]
|
||||
@@ -47,7 +45,7 @@ async def upload_analysis_file(
|
||||
content_type=content_type,
|
||||
)
|
||||
|
||||
file_id = await insert_file_row(
|
||||
file_id = await insert_file(
|
||||
analysis_run_id=analysis_run_id,
|
||||
hospital_id=hospital_id,
|
||||
file_type=file_type,
|
||||
@@ -61,12 +59,7 @@ async def upload_analysis_file(
|
||||
|
||||
async def list_analysis_files(analysis_run_id: str) -> list[dict]:
|
||||
"""analysis_run에 딸린 (삭제 안 된) 파일 목록."""
|
||||
return await fetchall(
|
||||
"SELECT id, file_type, file_name, file_url, size_bytes, created_at FROM file_data"
|
||||
" WHERE analysis_run_id = %s AND is_deleted = FALSE"
|
||||
" ORDER BY created_at DESC",
|
||||
(analysis_run_id,),
|
||||
)
|
||||
return await select_run_files(analysis_run_id)
|
||||
|
||||
|
||||
async def handle_analysis_file_upload(
|
||||
@@ -102,7 +95,7 @@ async def handle_analysis_file_upload(
|
||||
|
||||
async def get_analysis_files_response(analysis_run_id: str) -> list[FileListItem]:
|
||||
"""run 존재 확인 + 응답 모델 생성."""
|
||||
if not await fetchone("SELECT 1 FROM analysis_runs WHERE analysis_run_id = %s", (analysis_run_id,)):
|
||||
if not await select_run(analysis_run_id):
|
||||
raise HTTPException(status_code=404, detail="analysis_run not found")
|
||||
rows = await list_analysis_files(analysis_run_id)
|
||||
return [FileListItem(**{**r, "created_at": str(r["created_at"])}) for r in rows]
|
||||
@@ -110,14 +103,8 @@ async def get_analysis_files_response(analysis_run_id: str) -> list[FileListItem
|
||||
|
||||
async def soft_delete_analysis_file(analysis_run_id: str, file_id: int) -> None:
|
||||
"""analysis_run에 딸린 파일을 소프트 삭제. 멱등성 보장."""
|
||||
row = await fetchone(
|
||||
"SELECT id FROM file_data WHERE id = %s AND analysis_run_id = %s",
|
||||
(file_id, analysis_run_id),
|
||||
)
|
||||
row = await select_file(file_id, analysis_run_id)
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="file not found")
|
||||
await execute(
|
||||
"UPDATE file_data SET is_deleted = TRUE WHERE id = %s AND is_deleted = FALSE",
|
||||
(file_id,),
|
||||
)
|
||||
await delete_file(file_id)
|
||||
logger.info("soft-deleted analysis file run=%s file_id=%s", analysis_run_id, file_id)
|
||||
+14
-34
@@ -1,7 +1,9 @@
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from common.db import fetchone, execute
|
||||
from common.db.run import select_run
|
||||
from common.db.hospital import select_hospital
|
||||
from common.db.market import upsert_market_status, upsert_market_result
|
||||
from common.db.source import select_run_raw_data
|
||||
from integrations.llm.llm_service import LLMService
|
||||
from integrations.llm.prompt import (
|
||||
market_competitors_prompt,
|
||||
@@ -18,49 +20,27 @@ _TYPES = ["competitors", "keywords", "trend", "target_audience"]
|
||||
async def _save(analysis_run_id: str, analysis_type: str, result, exc: Exception | None) -> None:
|
||||
if exc:
|
||||
logger.warning("[market] %s failed run=%s: %s", analysis_type, analysis_run_id, exc)
|
||||
await execute(
|
||||
"INSERT INTO market_analysis (analysis_run_id, analysis_type, status)"
|
||||
" VALUES (%s, %s, 'failed')"
|
||||
" ON DUPLICATE KEY UPDATE status = 'failed'",
|
||||
(analysis_run_id, analysis_type),
|
||||
)
|
||||
await upsert_market_status(analysis_run_id, analysis_type, "failed")
|
||||
else:
|
||||
await execute(
|
||||
"INSERT INTO market_analysis (analysis_run_id, analysis_type, status, data)"
|
||||
" VALUES (%s, %s, 'done', %s)"
|
||||
" ON DUPLICATE KEY UPDATE status = 'done', data = VALUES(data)",
|
||||
(analysis_run_id, analysis_type, json.dumps(result.model_dump(), ensure_ascii=False)),
|
||||
)
|
||||
await upsert_market_result(analysis_run_id, analysis_type, result.model_dump())
|
||||
|
||||
|
||||
async def run_market_analysis(analysis_run_id: str) -> None:
|
||||
logger.info("[market] start run=%s", analysis_run_id)
|
||||
|
||||
run = await fetchone(
|
||||
"SELECT hospital_id FROM analysis_runs WHERE analysis_run_id = %s",
|
||||
(analysis_run_id,),
|
||||
)
|
||||
clinic = await fetchone(
|
||||
"SELECT hospital_name, road_address, raw_data FROM hospital_baseinfo WHERE hospital_id = %s",
|
||||
(run["hospital_id"],),
|
||||
)
|
||||
run = await select_run(analysis_run_id)
|
||||
clinic = await select_hospital(run["hospital_id"])
|
||||
raw = await select_run_raw_data(analysis_run_id)
|
||||
mainpage = raw.get("mainpage") or {}
|
||||
|
||||
raw_data = clinic["raw_data"]
|
||||
clinic_data = json.loads(raw_data) if isinstance(raw_data, str) else (raw_data or {})
|
||||
|
||||
clinic_name = clinic["hospital_name"] or ""
|
||||
address = clinic["road_address"] or ""
|
||||
services = clinic_data.get("services", [])
|
||||
clinic_name = (clinic or {}).get("hospital_name") or ""
|
||||
address = (clinic or {}).get("road_address") or ""
|
||||
services = mainpage.get("services", [])
|
||||
services_str = ", ".join(services[:3])
|
||||
primary_service = services[0] if services else ""
|
||||
|
||||
for analysis_type in _TYPES:
|
||||
await execute(
|
||||
"INSERT INTO market_analysis (analysis_run_id, analysis_type, status)"
|
||||
" VALUES (%s, %s, 'processing')"
|
||||
" ON DUPLICATE KEY UPDATE status = 'processing'",
|
||||
(analysis_run_id, analysis_type),
|
||||
)
|
||||
await upsert_market_status(analysis_run_id, analysis_type, "processing")
|
||||
|
||||
llm = LLMService(provider="perplexity")
|
||||
results = await asyncio.gather(
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import logging
|
||||
from common.db import fetchone, execute
|
||||
from common.db.run import select_run, update_run_status
|
||||
from models.status import AnalysisStatus
|
||||
from services.collect import collect_all
|
||||
from services.market import run_market_analysis
|
||||
@@ -12,41 +12,19 @@ async def run_pipeline(analysis_run_id: str) -> None:
|
||||
logger.info("[pipeline] start run=%s", analysis_run_id)
|
||||
|
||||
# ── 1. Collect ──────────────────────────────────────────────────────────
|
||||
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,),
|
||||
)
|
||||
await collect_all(
|
||||
analysis_run_id,
|
||||
hospital_id=run["hospital_id"],
|
||||
instagram_id=run["instagram_data_id"],
|
||||
facebook_id=run["facebook_data_id"],
|
||||
naver_blog_id=run["naver_blog_data_id"],
|
||||
youtube_id=run["youtube_data_id"],
|
||||
gangnam_unni_id=run["gangnam_unni_data_id"],
|
||||
)
|
||||
run = await select_run(analysis_run_id)
|
||||
await collect_all(analysis_run_id, hospital_id=run["hospital_id"])
|
||||
|
||||
# ── 2. Market ────────────────────────────────────────────────────────────
|
||||
await execute(
|
||||
"UPDATE analysis_runs SET status = %s WHERE analysis_run_id = %s",
|
||||
(AnalysisStatus.ANALYZING, analysis_run_id),
|
||||
)
|
||||
await update_run_status(analysis_run_id, AnalysisStatus.ANALYZING)
|
||||
await run_market_analysis(analysis_run_id)
|
||||
|
||||
# ── 3. Report ────────────────────────────────────────────────────────────
|
||||
await run_report_task(analysis_run_id)
|
||||
|
||||
# ── 4. Plan ──────────────────────────────────────────────────────────────
|
||||
await execute(
|
||||
"UPDATE analysis_runs SET status = %s WHERE analysis_run_id = %s",
|
||||
(AnalysisStatus.PLANNING, analysis_run_id),
|
||||
)
|
||||
await update_run_status(analysis_run_id, AnalysisStatus.PLANNING)
|
||||
await run_plan_task(analysis_run_id)
|
||||
|
||||
await execute(
|
||||
"UPDATE analysis_runs SET status = %s WHERE analysis_run_id = %s",
|
||||
(AnalysisStatus.COMPLETED, analysis_run_id),
|
||||
)
|
||||
await update_run_status(analysis_run_id, AnalysisStatus.COMPLETED)
|
||||
logger.info("[pipeline] done run=%s", analysis_run_id)
|
||||
Reference in new issue
Block a user