시장 조사 llm 추가 및 파이프라인 정리, db 커넥션 풀 문제 처리
This commit is contained in:
1 parent
42e09ae2d1
commit
cda518c027
13 files changed
+328
-65
No files matched your search
@@ -1,7 +1,6 @@
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from common.db import fetchone, execute, is_done, get_analysis_raw_data, save_analysis_report
|
||||
from common.db import fetchone, execute, get_analysis_raw_data, save_analysis_report
|
||||
from integrations.llm.llm_service import LLMService
|
||||
from integrations.llm.prompt import report_prompt, plan_prompt
|
||||
from integrations.llm.schemas.report import ReportOutput
|
||||
@@ -69,43 +68,18 @@ async def generate_plan(analysis_run_id: str) -> PlanOutput:
|
||||
return await LLMService(provider="perplexity").generate(plan_prompt, input_data)
|
||||
|
||||
|
||||
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)
|
||||
await execute(
|
||||
"UPDATE analysis_runs SET plan_data = %s, status = %s WHERE analysis_run_id = %s",
|
||||
(json.dumps(result.model_dump(), ensure_ascii=False), AnalysisStatus.COMPLETED, analysis_run_id),
|
||||
)
|
||||
logger.info("[plan] done run=%s", analysis_run_id)
|
||||
|
||||
|
||||
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)
|
||||
await save_analysis_report(analysis_run_id, result.model_dump())
|
||||
await execute("UPDATE analysis_runs SET status = %s WHERE analysis_run_id = %s", (AnalysisStatus.PLANNING, analysis_run_id))
|
||||
logger.info("[report] done run=%s", analysis_run_id)
|
||||
asyncio.create_task(run_plan_task(analysis_run_id))
|
||||
|
||||
|
||||
async def check_and_advance_analysis(analysis_run_id: str) -> None:
|
||||
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,),
|
||||
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)
|
||||
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),
|
||||
)
|
||||
clinic_row = await fetchone(
|
||||
"SELECT status FROM hospital_baseinfo WHERE hospital_id = %s",
|
||||
(run["hospital_id"],),
|
||||
)
|
||||
results = [
|
||||
clinic_row["status"] == "done" if clinic_row else False,
|
||||
await is_done("instagram_data", run["instagram_data_id"]),
|
||||
await is_done("facebook_data", run["facebook_data_id"]),
|
||||
await is_done("naver_blog_data", run["naver_blog_data_id"]),
|
||||
await is_done("youtube_data", run["youtube_data_id"]),
|
||||
await is_done("gangnam_unni_data", run["gangnam_unni_data_id"]),
|
||||
]
|
||||
if all(results):
|
||||
await execute("UPDATE analysis_runs SET status = %s WHERE analysis_run_id = %s", (AnalysisStatus.ANALYZING, analysis_run_id))
|
||||
asyncio.create_task(run_report_task(analysis_run_id))
|
||||
logger.info("[plan] done run=%s", analysis_run_id)
|
||||
+32
-7
@@ -1,4 +1,6 @@
|
||||
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,
|
||||
@@ -8,7 +10,6 @@ from common.db import (
|
||||
execute, save_hospital_raw_data,
|
||||
)
|
||||
from common.utils import get_env
|
||||
from services.analysis import check_and_advance_analysis
|
||||
from integrations.apify import ApifyClient
|
||||
from integrations.naver import NaverClient
|
||||
from integrations.youtube import YouTubeClient
|
||||
@@ -23,7 +24,6 @@ async def collect_instagram(analysis_run_id: str, row_id: int, url: str) -> None
|
||||
data = await ApifyClient(get_env("APIFY_API_TOKEN")).get_instagram_profile(url)
|
||||
await save_instagram_raw_data(row_id, data)
|
||||
logger.info("[instagram] done run=%s", analysis_run_id)
|
||||
await check_and_advance_analysis(analysis_run_id)
|
||||
|
||||
|
||||
async def collect_facebook(analysis_run_id: str, row_id: int, url: str) -> None:
|
||||
@@ -32,7 +32,6 @@ async def collect_facebook(analysis_run_id: str, row_id: int, url: str) -> None:
|
||||
data = await ApifyClient(get_env("APIFY_API_TOKEN")).get_facebook_page(url)
|
||||
await save_facebook_raw_data(row_id, data)
|
||||
logger.info("[facebook] done run=%s", analysis_run_id)
|
||||
await check_and_advance_analysis(analysis_run_id)
|
||||
|
||||
|
||||
async def collect_naver_blog(analysis_run_id: str, row_id: int, url: str) -> None:
|
||||
@@ -41,7 +40,6 @@ async def collect_naver_blog(analysis_run_id: str, row_id: int, url: str) -> Non
|
||||
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)
|
||||
logger.info("[naver_blog] done run=%s", analysis_run_id)
|
||||
await check_and_advance_analysis(analysis_run_id)
|
||||
|
||||
|
||||
async def collect_youtube(analysis_run_id: str, row_id: int, url: str) -> None:
|
||||
@@ -50,7 +48,6 @@ async def collect_youtube(analysis_run_id: str, row_id: int, url: str) -> None:
|
||||
data = await YouTubeClient(get_env("YOUTUBE_API_KEY")).get_channel(url)
|
||||
await save_youtube_raw_data(row_id, data)
|
||||
logger.info("[youtube] done run=%s", analysis_run_id)
|
||||
await check_and_advance_analysis(analysis_run_id)
|
||||
|
||||
|
||||
async def collect_gangnam_unni(analysis_run_id: str, row_id: int, url: str) -> None:
|
||||
@@ -59,7 +56,6 @@ async def collect_gangnam_unni(analysis_run_id: str, row_id: int, url: str) -> N
|
||||
data = await FirecrawlClient(get_env("FIRECRAWL_API_KEY")).get_gangnam_unni(url)
|
||||
await save_gangnam_unni_raw_data(row_id, data)
|
||||
logger.info("[gangnam_unni] done run=%s", analysis_run_id)
|
||||
await check_and_advance_analysis(analysis_run_id)
|
||||
|
||||
|
||||
async def collect_clinic_info(analysis_run_id: str, hospital_id: str, url: str) -> None:
|
||||
@@ -68,4 +64,33 @@ async def collect_clinic_info(analysis_run_id: str, hospital_id: str, url: str)
|
||||
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)
|
||||
await check_and_advance_analysis(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 ""
|
||||
|
||||
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"])]
|
||||
|
||||
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)))
|
||||
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
@@ -0,0 +1,84 @@
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from common.db import fetchone, execute
|
||||
from integrations.llm.llm_service import LLMService
|
||||
from integrations.llm.prompt import (
|
||||
market_competitors_prompt,
|
||||
market_keywords_prompt,
|
||||
market_trend_prompt,
|
||||
market_target_audience_prompt,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_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),
|
||||
)
|
||||
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)),
|
||||
)
|
||||
|
||||
|
||||
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"],),
|
||||
)
|
||||
|
||||
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", [])
|
||||
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),
|
||||
)
|
||||
|
||||
llm = LLMService(provider="perplexity")
|
||||
results = await asyncio.gather(
|
||||
llm.generate(market_competitors_prompt, {"address": address, "services": services_str}),
|
||||
llm.generate(market_keywords_prompt, {"services": services_str}),
|
||||
llm.generate(market_trend_prompt, {"service": primary_service}),
|
||||
llm.generate(market_target_audience_prompt, {"clinic_name": clinic_name}),
|
||||
return_exceptions=True,
|
||||
)
|
||||
# 그다지 좋은 방식은 아님
|
||||
await asyncio.gather(*[
|
||||
_save(
|
||||
analysis_run_id,
|
||||
analysis_type,
|
||||
result=None if isinstance(r, Exception) else r,
|
||||
exc=r if isinstance(r, Exception) else None,
|
||||
)
|
||||
for analysis_type, r in zip(_TYPES, results)
|
||||
])
|
||||
|
||||
logger.info("[market] done run=%s", analysis_run_id)
|
||||
@@ -0,0 +1,52 @@
|
||||
import logging
|
||||
from common.db import fetchone, execute
|
||||
from models.status import AnalysisStatus
|
||||
from services.collect import collect_all
|
||||
from services.market import run_market_analysis
|
||||
from services.analysis import run_report_task, run_plan_task
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
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"],
|
||||
)
|
||||
|
||||
# ── 2. Market ────────────────────────────────────────────────────────────
|
||||
await execute(
|
||||
"UPDATE analysis_runs SET status = %s WHERE analysis_run_id = %s",
|
||||
(AnalysisStatus.ANALYZING, analysis_run_id),
|
||||
)
|
||||
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 run_plan_task(analysis_run_id)
|
||||
|
||||
await execute(
|
||||
"UPDATE analysis_runs SET status = %s WHERE analysis_run_id = %s",
|
||||
(AnalysisStatus.COMPLETED, analysis_run_id),
|
||||
)
|
||||
logger.info("[pipeline] done run=%s", analysis_run_id)
|
||||
Reference in new issue
Block a user