Merge branch 'db-migration': remote_source + raw_info 통합 스키마
- common/db.py 단일 파일 → common/db/ 패키지로 분리 (hospital/source/run/market/file_data) - 모든 채널 데이터를 raw_info 단일 테이블로 통일 (hospital_baseinfo.raw_data / 채널별 *_data 테이블 제거) - 부가 채널(tiktok/instagram_en/facebook_en/kakaotalk/naver_cafe)도 remote_source+raw_info 로 일원화 - EN 채널은 같은 source_type + language='EN' 으로 구분, select_run_raw_data 가 합성키로 반환 - SourceType.BRANDING 추가 — brand_assets/channel_logos 결과를 하나의 raw_info entry 에 머지 - collect.collect_all: main wave gather → branding 2단계 순차 실행 - mock_urls 매칭 + _with_scheme 보정 유지 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
commit
c23e620fb4
21 files changed
+849
-891
No files matched your search
+48
-40
@@ -2,21 +2,22 @@ import logging
|
||||
import uuid6
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, File, Form, HTTPException, UploadFile, status
|
||||
from common.deps import verify_api_key
|
||||
from common.db import fetchone, insert_instagram_row, insert_facebook_row, insert_naver_blog_row, insert_youtube_row, insert_gangnam_unni_row, insert_analysis_run
|
||||
from common.db.hospital import select_hospital
|
||||
from common.db.source import select_source_mainpage, insert_source, insert_raw_info
|
||||
from common.db.run import insert_run, select_run_status
|
||||
from common.utils import _normalize_homepage, _with_scheme
|
||||
from models.analysis import AnalysisCreate, AnalysisStartResponse, AnalysisStatusResponse
|
||||
from models.file import FileListItem, FileType, FileUploadResponse
|
||||
from models.status import AnalysisStatus
|
||||
from models.status import AnalysisStatus, SourceType
|
||||
from services.pipeline import run_pipeline
|
||||
from services.file import get_analysis_files_response, handle_analysis_file_upload, soft_delete_analysis_file
|
||||
from services.file_data import get_analysis_files_response, handle_analysis_file_upload, soft_delete_analysis_file
|
||||
from mock_urls import MOCK_CLINICS
|
||||
from common.utils import _normalize_homepage, _with_scheme
|
||||
|
||||
router = APIRouter(prefix="/api/analysis", tags=["analysis"], dependencies=[Depends(verify_api_key)])
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 추후 DB에 클리닉별로 매핑할 채널들 — 지금은 mock_urls에서 homepage 매칭으로 보충.
|
||||
# 메인 채널(IG/FB/YT/네이버블로그/강남언니) + 부가 채널(틱톡/영문 IG·FB/카카오/네이버카페) 모두 포함.
|
||||
# 클라가 일부만 보내거나 빈 값이면 mock에서 동일 hospital을 찾아 채워줌.
|
||||
|
||||
# 클라가 일부만 보내거나 빈 값이면 mock_urls 의 동일 homepage 매칭으로 채워줌 (메인 + 부가 채널 동일 규칙).
|
||||
def _channels_from_mockurls(homepage_url: str) -> dict:
|
||||
target = _normalize_homepage(homepage_url)
|
||||
if not target:
|
||||
@@ -47,44 +48,51 @@ async def start_analysis(body: AnalysisCreate, background_tasks: BackgroundTasks
|
||||
analysis_run_id = str(uuid6.uuid7())
|
||||
hospital_id = body.clinic_id
|
||||
|
||||
# 사실 hospital과 owner_user_id 비교 후 검증이 필요한 거지만 일단 PoC 니까. 나중에 바꿉니다.
|
||||
hospital = await fetchone(
|
||||
"SELECT owner_user_id, url FROM hospital_baseinfo WHERE hospital_id = %s",
|
||||
(hospital_id,),
|
||||
)
|
||||
# 사실 hospital 과 owner_user_id 비교 후 검증이 필요한 거지만 일단 PoC 니까. 나중에 바꿉니다.
|
||||
hospital = await select_hospital(hospital_id)
|
||||
if not hospital:
|
||||
raise HTTPException(status_code=409, detail="Clinic not found")
|
||||
|
||||
# 클라가 안 보낸 채널은 mock_urls에서 homepage 매칭으로 보충 (main + extra 동일 규칙)
|
||||
mock = _channels_from_mockurls(hospital["url"])
|
||||
analysis_run_id = await insert_run(analysis_run_id, hospital_id, hospital["owner_user_id"])
|
||||
|
||||
# 사용자가 'gangnamunni.com/...' 같이 scheme/www 없이 줘도 _with_scheme이 https://www. 보강.
|
||||
ig_url = _with_scheme(body.channels.instagram) or mock.get("instagram")
|
||||
fb_url = _with_scheme(body.channels.facebook) or mock.get("facebook")
|
||||
nb_url = _with_scheme(body.channels.naver_blog) or mock.get("naver_blog")
|
||||
yt_url = _with_scheme(body.channels.youtube) or mock.get("youtube")
|
||||
gu_url = _with_scheme(body.channels.gangnam_unni) or mock.get("gangnam_unni")
|
||||
mainpage = await select_source_mainpage(hospital_id)
|
||||
if mainpage:
|
||||
await insert_raw_info(mainpage["source_id"], analysis_run_id, data_tag=SourceType.MAINPAGE)
|
||||
# branding (HTML/CSS + Vision 로고 매칭) — mainpage 와 같은 homepage URL 을 source 로 사용.
|
||||
branding_id = await insert_source(hospital_id, SourceType.BRANDING, mainpage["url"])
|
||||
await insert_raw_info(branding_id, analysis_run_id, data_tag=SourceType.BRANDING)
|
||||
|
||||
ig_id = await insert_instagram_row(hospital_id, ig_url) if ig_url else None
|
||||
fb_id = await insert_facebook_row(hospital_id, fb_url) if fb_url else None
|
||||
nb_id = await insert_naver_blog_row(hospital_id, nb_url) if nb_url else None
|
||||
yt_id = await insert_youtube_row(hospital_id, yt_url) if yt_url else None
|
||||
gu_id = await insert_gangnam_unni_row(hospital_id, gu_url) if gu_url else None
|
||||
# 클라가 안 보낸 채널은 mock_urls 에서 homepage 매칭으로 보충 (main + extra 동일 규칙).
|
||||
mock = _channels_from_mockurls((mainpage or {}).get("url") or "")
|
||||
|
||||
analysis_run_id = await insert_analysis_run(
|
||||
analysis_run_id, hospital_id, hospital["owner_user_id"],
|
||||
ig_id, fb_id, nb_id, yt_id, gu_id,
|
||||
)
|
||||
# 메인 5채널 (KR). _with_scheme 으로 'gangnamunni.com/...' 같이 scheme/www 없이 와도 보강.
|
||||
main_channels = [
|
||||
(SourceType.INSTAGRAM, _with_scheme(body.channels.instagram) or mock.get("instagram")),
|
||||
(SourceType.FACEBOOK, _with_scheme(body.channels.facebook) or mock.get("facebook")),
|
||||
(SourceType.NAVER_BLOG, _with_scheme(body.channels.naver_blog) or mock.get("naver_blog")),
|
||||
(SourceType.YOUTUBE, _with_scheme(body.channels.youtube) or mock.get("youtube")),
|
||||
(SourceType.GANGNAM_UNNI, _with_scheme(body.channels.gangnam_unni) or mock.get("gangnam_unni")),
|
||||
]
|
||||
for source_type, url in main_channels:
|
||||
if url:
|
||||
source_id = await insert_source(hospital_id, source_type, url)
|
||||
await insert_raw_info(source_id, analysis_run_id, data_tag=source_type)
|
||||
|
||||
# 부가 채널 — instagram_en/facebook_en 은 동일 source_type 에 language='EN' 으로 구분, 나머지는 자체 source_type.
|
||||
extra_channels = [
|
||||
(SourceType.INSTAGRAM, "EN", _with_scheme(body.channels.instagram_en) or mock.get("instagram_en")),
|
||||
(SourceType.FACEBOOK, "EN", _with_scheme(body.channels.facebook_en) or mock.get("facebook_en")),
|
||||
(SourceType.TIKTOK, None, _with_scheme(body.channels.tiktok) or mock.get("tiktok")),
|
||||
(SourceType.KAKAOTALK, None, _with_scheme(body.channels.kakao_talk) or mock.get("kakao_talk")),
|
||||
(SourceType.NAVER_CAFE, None, _with_scheme(body.channels.naver_cafe) or mock.get("naver_cafe")),
|
||||
]
|
||||
for source_type, language, url in extra_channels:
|
||||
if url:
|
||||
source_id = await insert_source(hospital_id, source_type, url, language=language)
|
||||
await insert_raw_info(source_id, analysis_run_id, data_tag=source_type)
|
||||
|
||||
extra_channels = {
|
||||
"tiktok": body.channels.tiktok or mock.get("tiktok"),
|
||||
"instagram_en": body.channels.instagram_en or mock.get("instagram_en"),
|
||||
"facebook_en": body.channels.facebook_en or mock.get("facebook_en"),
|
||||
"kakao_talk": body.channels.kakao_talk or mock.get("kakao_talk"),
|
||||
"naver_cafe": body.channels.naver_cafe or mock.get("naver_cafe"),
|
||||
}
|
||||
logger.info("[analysis] main+extra channels resolved (mock_matched=%s)", bool(mock))
|
||||
background_tasks.add_task(run_pipeline, analysis_run_id, extra_channels)
|
||||
background_tasks.add_task(run_pipeline, analysis_run_id)
|
||||
|
||||
return AnalysisStartResponse(
|
||||
analysis_run_id=analysis_run_id,
|
||||
@@ -121,12 +129,12 @@ async def delete_analysis_run_file(run_id: str, file_id: int) -> None:
|
||||
@router.get("/{run_id}/status", response_model=AnalysisStatusResponse)
|
||||
async def get_analysis_status(run_id: str):
|
||||
logger.info("GET /api/analysis/%s/status", run_id)
|
||||
row = await fetchone("SELECT status FROM analysis_runs WHERE analysis_run_id = %s", (run_id,))
|
||||
if not row:
|
||||
run_status = await select_run_status(run_id)
|
||||
if run_status is None:
|
||||
raise HTTPException(status_code=404, detail="Run not found")
|
||||
return AnalysisStatusResponse(
|
||||
analysis_run_id=run_id,
|
||||
status=AnalysisStatus(row["status"]),
|
||||
status=AnalysisStatus(run_status),
|
||||
progress=50.0,
|
||||
current_step="",
|
||||
channel_errors={},
|
||||
|
||||
+4
-8
@@ -2,7 +2,8 @@ import logging
|
||||
import uuid6
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from common.deps import verify_api_key
|
||||
from common.db import insert_hospital, fetchone
|
||||
from common.db.hospital import select_hospital, insert_hospital
|
||||
from common.db.source import insert_source
|
||||
from common.utils import get_env
|
||||
from integrations.firecrawl import FirecrawlClient
|
||||
from models.clinic import ClinicCreate, ClinicCreateResponse, ClinicResponse, ClinicHistoryResponse, RunSummary
|
||||
@@ -30,9 +31,8 @@ async def create_clinic(body: ClinicCreate):
|
||||
name=info["clinicName"],
|
||||
name_en=info.get("clinicNameEn"),
|
||||
road_address=info.get("address"),
|
||||
url=body.url,
|
||||
raw_data=info,
|
||||
)
|
||||
await insert_source(hospital_id, "mainpage", body.url)
|
||||
return ClinicCreateResponse(
|
||||
id=hospital_id,
|
||||
url=body.url,
|
||||
@@ -44,11 +44,7 @@ async def create_clinic(body: ClinicCreate):
|
||||
@router.get("/{hospital_id}", response_model=ClinicResponse)
|
||||
async def get_clinic(hospital_id: str):
|
||||
logger.info("GET /api/clinics/%s", hospital_id)
|
||||
row = await fetchone(
|
||||
"SELECT hospital_id, hospital_name, hospital_name_en, road_address, url, status, raw_data, created_at, updated_at"
|
||||
" FROM hospital_baseinfo WHERE hospital_id = %s",
|
||||
(hospital_id,),
|
||||
)
|
||||
row = await select_hospital(hospital_id)
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Clinic not found")
|
||||
return ClinicResponse(**{**row, "created_at": str(row["created_at"]), "updated_at": str(row["updated_at"])})
|
||||
|
||||
+8
-11
@@ -1,11 +1,13 @@
|
||||
import json
|
||||
import logging
|
||||
from fastapi import APIRouter, Depends, HTTPException, Response
|
||||
from common.db import fetchone, fetch_raw
|
||||
from common.db.run import select_run_with_clinic
|
||||
from common.db.source import select_run_source_raw
|
||||
from common.deps import verify_api_key
|
||||
from common.utils import _with_scheme
|
||||
from integrations.llm.schemas.plan import PlanOutput
|
||||
from models.plan import PlanApiResponse
|
||||
from models.status import SourceType
|
||||
|
||||
router = APIRouter(prefix="/api/plan", tags=["plan"], dependencies=[Depends(verify_api_key)])
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -14,26 +16,21 @@ logger = logging.getLogger(__name__)
|
||||
@router.get("/{run_id}", response_model=PlanApiResponse, response_model_by_alias=True)
|
||||
async def get_plan(run_id: str):
|
||||
logger.info("GET /api/plan/%s", run_id)
|
||||
row = await fetchone(
|
||||
"SELECT ar.plan_data, ar.created_at, ar.gangnam_unni_data_id, h.hospital_name, h.hospital_name_en, h.url"
|
||||
" FROM analysis_runs ar"
|
||||
" JOIN hospital_baseinfo h ON ar.hospital_id = h.hospital_id"
|
||||
" WHERE ar.analysis_run_id = %s",
|
||||
(run_id,),
|
||||
)
|
||||
row = await select_run_with_clinic(run_id)
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404, detail="Run not found")
|
||||
if row["plan_data"] is None:
|
||||
return Response(status_code=204)
|
||||
data = json.loads(row["plan_data"]) if isinstance(row["plan_data"], str) else row["plan_data"]
|
||||
plan = PlanOutput(**data)
|
||||
gangnam_unni = await fetch_raw("gangnam_unni_data", row["gangnam_unni_data_id"]) or {}
|
||||
clinic_name = gangnam_unni.get("name") or row["hospital_name"]
|
||||
# 강남언니에서 긁어온 이름이 있으면 우선 (hospital_baseinfo 의 정식 이름보다 강남언니가 더 광고용 표기).
|
||||
gu = await select_run_source_raw(run_id, SourceType.GANGNAM_UNNI) or {}
|
||||
clinic_name = gu.get("name") or row["hospital_name"]
|
||||
return PlanApiResponse(
|
||||
id=run_id,
|
||||
clinic_name=clinic_name,
|
||||
clinic_name_en=row["hospital_name_en"],
|
||||
created_at=str(row["created_at"]),
|
||||
target_url=_with_scheme(row["url"]),
|
||||
target_url=_with_scheme(row["target_url"]),
|
||||
**plan.model_dump(),
|
||||
)
|
||||
+3
-9
@@ -1,7 +1,7 @@
|
||||
import json
|
||||
import logging
|
||||
from fastapi import APIRouter, Depends, HTTPException, Response
|
||||
from common.db import fetchone
|
||||
from common.db.run import select_run_with_clinic
|
||||
from common.deps import verify_api_key
|
||||
from common.utils import _with_scheme
|
||||
from integrations.llm.schemas.report import ReportOutput
|
||||
@@ -14,13 +14,7 @@ logger = logging.getLogger(__name__)
|
||||
@router.get("/{run_id}", response_model=MarketingReportResponse, response_model_by_alias=True)
|
||||
async def get_report(run_id: str):
|
||||
logger.info("GET /api/report/%s", run_id)
|
||||
row = await fetchone(
|
||||
"SELECT ar.report_data, ar.created_at, h.hospital_name, h.hospital_name_en, h.url"
|
||||
" FROM analysis_runs ar"
|
||||
" JOIN hospital_baseinfo h ON ar.hospital_id = h.hospital_id"
|
||||
" WHERE ar.analysis_run_id = %s",
|
||||
(run_id,),
|
||||
)
|
||||
row = await select_run_with_clinic(run_id)
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404, detail="Run not found")
|
||||
if row["report_data"] is None:
|
||||
@@ -32,6 +26,6 @@ async def get_report(run_id: str):
|
||||
clinic_name=row["hospital_name"],
|
||||
clinic_name_en=row["hospital_name_en"],
|
||||
created_at=str(row["created_at"]),
|
||||
target_url=_with_scheme(row["url"]),
|
||||
target_url=_with_scheme(row["target_url"]),
|
||||
**llm_output.model_dump(exclude={"id", "created_at", "target_url"}),
|
||||
)
|
||||
Reference in new issue
Block a user