Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4f756cf001 | ||
|
|
163e9d1c02 | ||
|
|
4855d44381 | ||
|
|
843ccdb806 | ||
|
|
9817b53be1 | ||
|
|
cb798f7acc | ||
|
|
84fd854d15 | ||
|
|
8e5ce3e012 | ||
|
|
b921a0803e | ||
|
|
e8406dc0ee | ||
|
|
09bb7a71ee | ||
|
|
1f45b3e53d | ||
|
|
18d01357c0 | ||
|
|
20fdf53264 | ||
|
|
cda518c027 | ||
|
|
42e09ae2d1 | ||
|
|
9b4e99abf9 |
No files matched your search
+3
-1
@@ -43,4 +43,6 @@ Thumbs.db
|
|||||||
# Alembic
|
# Alembic
|
||||||
alembic/versions/*.pyc
|
alembic/versions/*.pyc
|
||||||
|
|
||||||
test_results/
|
test_results/
|
||||||
|
|
||||||
|
app/test*
|
||||||
@@ -152,6 +152,23 @@ CREATE INDEX IX_analysis_runs_2
|
|||||||
ON analysis_runs(owner_user_id);
|
ON analysis_runs(owner_user_id);
|
||||||
|
|
||||||
|
|
||||||
|
-- file_data Table Create SQL
|
||||||
|
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 Table Create SQL
|
-- hospital_history Table Create SQL
|
||||||
CREATE TABLE hospital_history
|
CREATE TABLE hospital_history
|
||||||
(
|
(
|
||||||
@@ -179,3 +196,21 @@ CREATE INDEX IX_hospital_history_1
|
|||||||
CREATE INDEX IX_hospital_history_2
|
CREATE INDEX IX_hospital_history_2
|
||||||
ON hospital_history(analysis_run_id);
|
ON hospital_history(analysis_run_id);
|
||||||
|
|
||||||
|
|
||||||
|
-- market_analysis Table Create SQL
|
||||||
|
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)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Index 설정 SQL - market_analysis(analysis_run_id)
|
||||||
|
CREATE INDEX IX_market_analysis_1
|
||||||
|
ON market_analysis(analysis_run_id);
|
||||||
|
|
||||||
+3
-3
@@ -1,6 +1,6 @@
|
|||||||
from .clinics import router as clinics_router
|
from .clinics import router as clinics_router
|
||||||
from .analysis import router as analysis_router
|
from .analysis import router as analysis_router
|
||||||
from .reports import router as reports_router
|
from .report import router as report_router
|
||||||
from .plans import router as plans_router
|
from .plan import router as plan_router
|
||||||
|
|
||||||
routers = [clinics_router, analysis_router, reports_router, plans_router]
|
routers = [clinics_router, analysis_router, report_router, plan_router]
|
||||||
+58
-16
@@ -1,15 +1,35 @@
|
|||||||
import logging
|
import logging
|
||||||
import uuid6
|
import uuid6
|
||||||
from fastapi import APIRouter, BackgroundTasks, Depends, status, HTTPException
|
from fastapi import APIRouter, BackgroundTasks, Depends, File, Form, HTTPException, UploadFile, status
|
||||||
from common.deps import verify_api_key
|
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 import fetchone, insert_instagram_row, insert_facebook_row, insert_naver_blog_row, insert_youtube_row, insert_gangnam_unni_row, insert_analysis_run
|
||||||
from models.analysis import AnalysisCreate, AnalysisStartResponse, AnalysisStatusResponse
|
from models.analysis import AnalysisCreate, AnalysisStartResponse, AnalysisStatusResponse
|
||||||
|
from models.file import FileListItem, FileType, FileUploadResponse
|
||||||
from models.status import AnalysisStatus
|
from models.status import AnalysisStatus
|
||||||
from services.collect import collect_instagram, collect_facebook, collect_naver_blog, collect_youtube, collect_gangnam_unni, collect_clinic_info
|
from services.pipeline import run_pipeline
|
||||||
|
from services.file 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)])
|
router = APIRouter(prefix="/api/analysis", tags=["analysis"], dependencies=[Depends(verify_api_key)])
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# 추후 DB에 클리닉별로 매핑할 채널(틱톡/영문 인스타·페북). 지금은 mock_urls에서 homepage 매칭으로 보충.
|
||||||
|
def _extra_channels_from_mockurls(homepage_url: str) -> dict:
|
||||||
|
"""homepage로 mock_urls에서 클리닉을 찾아 틱톡/영문 인스타·페북 URL 반환 (없으면 {})."""
|
||||||
|
target = _normalize_homepage(homepage_url)
|
||||||
|
if not target:
|
||||||
|
return {}
|
||||||
|
for c in MOCK_CLINICS:
|
||||||
|
urls = c["urls"]
|
||||||
|
if _normalize_homepage(urls.get("homepage", "")) == target:
|
||||||
|
return {
|
||||||
|
"tiktok": _with_scheme(urls.get("tiktok")),
|
||||||
|
"instagram_en": _with_scheme(urls.get("instagramEn")),
|
||||||
|
"facebook_en": _with_scheme(urls.get("facebookEn")),
|
||||||
|
}
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
@router.post("", status_code=status.HTTP_202_ACCEPTED, response_model=AnalysisStartResponse)
|
@router.post("", status_code=status.HTTP_202_ACCEPTED, response_model=AnalysisStartResponse)
|
||||||
async def start_analysis(body: AnalysisCreate, background_tasks: BackgroundTasks):
|
async def start_analysis(body: AnalysisCreate, background_tasks: BackgroundTasks):
|
||||||
@@ -24,7 +44,6 @@ async def start_analysis(body: AnalysisCreate, background_tasks: BackgroundTasks
|
|||||||
)
|
)
|
||||||
if not hospital:
|
if not hospital:
|
||||||
raise HTTPException(status_code=409, detail="Clinic not found")
|
raise HTTPException(status_code=409, detail="Clinic not found")
|
||||||
owner_user_id = hospital["owner_user_id"] if hospital else 0
|
|
||||||
|
|
||||||
ig_id = await insert_instagram_row(hospital_id, body.channels.instagram) if body.channels.instagram else None
|
ig_id = await insert_instagram_row(hospital_id, body.channels.instagram) if body.channels.instagram else None
|
||||||
fb_id = await insert_facebook_row(hospital_id, body.channels.facebook) if body.channels.facebook else None
|
fb_id = await insert_facebook_row(hospital_id, body.channels.facebook) if body.channels.facebook else None
|
||||||
@@ -32,20 +51,20 @@ async def start_analysis(body: AnalysisCreate, background_tasks: BackgroundTasks
|
|||||||
yt_id = await insert_youtube_row(hospital_id, body.channels.youtube) if body.channels.youtube else None
|
yt_id = await insert_youtube_row(hospital_id, body.channels.youtube) if body.channels.youtube else None
|
||||||
gu_id = await insert_gangnam_unni_row(hospital_id, body.channels.gangnam_unni) if body.channels.gangnam_unni else None
|
gu_id = await insert_gangnam_unni_row(hospital_id, body.channels.gangnam_unni) if body.channels.gangnam_unni else None
|
||||||
|
|
||||||
analysis_run_id = await insert_analysis_run(analysis_run_id, hospital_id, owner_user_id, ig_id, fb_id, nb_id, yt_id, gu_id)
|
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,
|
||||||
|
)
|
||||||
|
|
||||||
background_tasks.add_task(collect_clinic_info, analysis_run_id, hospital_id, hospital["url"])
|
# 클라 값 우선, 없으면 보충 (추후 DB에서 클리닉별로 가져올 값)
|
||||||
|
mock_extra = _extra_channels_from_mockurls(hospital["url"])
|
||||||
if ig_id:
|
extra_channels = {
|
||||||
background_tasks.add_task(collect_instagram, analysis_run_id, ig_id, body.channels.instagram)
|
"tiktok": body.channels.tiktok or mock_extra.get("tiktok"),
|
||||||
if fb_id:
|
"instagram_en": body.channels.instagram_en or mock_extra.get("instagram_en"),
|
||||||
background_tasks.add_task(collect_facebook, analysis_run_id, fb_id, body.channels.facebook)
|
"facebook_en": body.channels.facebook_en or mock_extra.get("facebook_en"),
|
||||||
if nb_id:
|
}
|
||||||
background_tasks.add_task(collect_naver_blog, analysis_run_id, nb_id, body.channels.naver_blog)
|
logger.info("[analysis] extra_channels=%s (mock_matched=%s)", extra_channels, bool(mock_extra))
|
||||||
if yt_id:
|
background_tasks.add_task(run_pipeline, analysis_run_id, extra_channels)
|
||||||
background_tasks.add_task(collect_youtube, analysis_run_id, yt_id, body.channels.youtube)
|
|
||||||
if gu_id:
|
|
||||||
background_tasks.add_task(collect_gangnam_unni, analysis_run_id, gu_id, body.channels.gangnam_unni)
|
|
||||||
|
|
||||||
return AnalysisStartResponse(
|
return AnalysisStartResponse(
|
||||||
analysis_run_id=analysis_run_id,
|
analysis_run_id=analysis_run_id,
|
||||||
@@ -56,6 +75,29 @@ async def start_analysis(body: AnalysisCreate, background_tasks: BackgroundTasks
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{run_id}/files", status_code=status.HTTP_201_CREATED, response_model=FileUploadResponse)
|
||||||
|
async def upload_analysis_run_file(
|
||||||
|
run_id: str,
|
||||||
|
file: UploadFile = File(..., description="업로드할 파일"),
|
||||||
|
file_type: FileType = Form(default=FileType.FILE, description="파일 타입 (image/video/audio/document/file)"),
|
||||||
|
) -> FileUploadResponse:
|
||||||
|
logger.info("POST /api/analysis/%s/files name=%s file_type=%s", run_id, file.filename, file_type.value)
|
||||||
|
return await handle_analysis_file_upload(run_id, file, file_type)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{run_id}/files", response_model=list[FileListItem])
|
||||||
|
async def get_analysis_run_files(run_id: str) -> list[FileListItem]:
|
||||||
|
logger.info("GET /api/analysis/%s/files", run_id)
|
||||||
|
return await get_analysis_files_response(run_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{run_id}/files/{file_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||||
|
async def delete_analysis_run_file(run_id: str, file_id: int) -> None:
|
||||||
|
logger.info("DELETE /api/analysis/%s/files/%s", run_id, file_id)
|
||||||
|
await soft_delete_analysis_file(analysis_run_id=run_id, file_id=file_id)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
@router.get("/{run_id}/status", response_model=AnalysisStatusResponse)
|
@router.get("/{run_id}/status", response_model=AnalysisStatusResponse)
|
||||||
async def get_analysis_status(run_id: str):
|
async def get_analysis_status(run_id: str):
|
||||||
logger.info("GET /api/analysis/%s/status", run_id)
|
logger.info("GET /api/analysis/%s/status", run_id)
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import json
|
||||||
|
import logging
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Response
|
||||||
|
from common.db import fetchone
|
||||||
|
from common.deps import verify_api_key
|
||||||
|
from integrations.llm.schemas.plan import PlanOutput
|
||||||
|
from models.plan import PlanApiResponse
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/plan", tags=["plan"], dependencies=[Depends(verify_api_key)])
|
||||||
|
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, 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,),
|
||||||
|
)
|
||||||
|
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)
|
||||||
|
return PlanApiResponse(
|
||||||
|
id=run_id,
|
||||||
|
clinic_name=row["hospital_name"],
|
||||||
|
clinic_name_en=row["hospital_name_en"],
|
||||||
|
created_at=str(row["created_at"]),
|
||||||
|
target_url=row["url"],
|
||||||
|
**plan.model_dump(),
|
||||||
|
)
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
import json
|
|
||||||
import logging
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Response
|
|
||||||
from common.db import fetchone
|
|
||||||
from common.deps import verify_api_key
|
|
||||||
from integrations.llm.schemas.plan import PlanOutput
|
|
||||||
|
|
||||||
router = APIRouter(prefix="/api/plans", tags=["plans"], dependencies=[Depends(verify_api_key)])
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/{run_id}", response_model=PlanOutput | None)
|
|
||||||
async def get_plan(run_id: str):
|
|
||||||
logger.info("GET /api/plans/%s", run_id)
|
|
||||||
row = await fetchone("SELECT plan_data FROM analysis_runs WHERE analysis_run_id = %s", (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"]
|
|
||||||
return PlanOutput(**data)
|
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import json
|
||||||
|
import logging
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Response
|
||||||
|
from common.db import fetchone
|
||||||
|
from common.deps import verify_api_key
|
||||||
|
from integrations.llm.schemas.report import ReportOutput
|
||||||
|
from models.report import MarketingReportResponse
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/report", tags=["report"], dependencies=[Depends(verify_api_key)])
|
||||||
|
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,),
|
||||||
|
)
|
||||||
|
if row is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Run not found")
|
||||||
|
if row["report_data"] is None:
|
||||||
|
return Response(status_code=204)
|
||||||
|
data = json.loads(row["report_data"]) if isinstance(row["report_data"], str) else row["report_data"]
|
||||||
|
llm_output = ReportOutput(**data)
|
||||||
|
return MarketingReportResponse(
|
||||||
|
id=run_id,
|
||||||
|
clinic_name=row["hospital_name"],
|
||||||
|
clinic_name_en=row["hospital_name_en"],
|
||||||
|
created_at=str(row["created_at"]),
|
||||||
|
target_url=row["url"],
|
||||||
|
**llm_output.model_dump(exclude={"id", "created_at", "target_url"}),
|
||||||
|
)
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
import json
|
|
||||||
import logging
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Response
|
|
||||||
from common.db import fetchone
|
|
||||||
from common.deps import verify_api_key
|
|
||||||
from integrations.llm.schemas.report import ReportOutput
|
|
||||||
|
|
||||||
router = APIRouter(prefix="/api/reports", tags=["reports"], dependencies=[Depends(verify_api_key)])
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/{run_id}", response_model=ReportOutput | None)
|
|
||||||
async def get_report(run_id: str):
|
|
||||||
logger.info("GET /api/reports/%s", run_id)
|
|
||||||
row = await fetchone(
|
|
||||||
"SELECT report_data FROM analysis_runs WHERE analysis_run_id = %s",
|
|
||||||
(run_id,),
|
|
||||||
)
|
|
||||||
if row is None:
|
|
||||||
raise HTTPException(status_code=404, detail="Run not found")
|
|
||||||
if row["report_data"] is None:
|
|
||||||
return Response(status_code=204)
|
|
||||||
data = json.loads(row["report_data"]) if isinstance(row["report_data"], str) else row["report_data"]
|
|
||||||
return ReportOutput(**data)
|
|
||||||
+69
-15
@@ -27,21 +27,36 @@ async def get_pool() -> aiomysql.Pool:
|
|||||||
async def execute(sql: str, args: tuple = ()) -> int:
|
async def execute(sql: str, args: tuple = ()) -> int:
|
||||||
pool = await get_pool()
|
pool = await get_pool()
|
||||||
async with pool.acquire() as conn:
|
async with pool.acquire() as conn:
|
||||||
await conn.ping(reconnect=True)
|
try:
|
||||||
async with conn.cursor() as cur:
|
async with conn.cursor() as cur:
|
||||||
await cur.execute(sql, args)
|
await cur.execute(sql, args)
|
||||||
await conn.commit()
|
await conn.commit()
|
||||||
return cur.lastrowid
|
return cur.lastrowid
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
# 읽기 (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()
|
||||||
async with pool.acquire() as conn:
|
async with pool.acquire() as conn:
|
||||||
await conn.ping(reconnect=True)
|
try:
|
||||||
async with conn.cursor(aiomysql.DictCursor) as cur:
|
async with conn.cursor(aiomysql.DictCursor) as cur:
|
||||||
await cur.execute(sql, args)
|
await cur.execute(sql, args)
|
||||||
return await cur.fetchone()
|
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()
|
||||||
|
|
||||||
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))
|
||||||
@@ -63,6 +78,21 @@ async def insert_gangnam_unni_row(hospital_id: str, url: str) -> int:
|
|||||||
return await execute("INSERT INTO gangnam_unni_data (hospital_id, url) VALUES (%s, %s)", (hospital_id, url))
|
return await execute("INSERT INTO gangnam_unni_data (hospital_id, url) VALUES (%s, %s)", (hospital_id, url))
|
||||||
|
|
||||||
|
|
||||||
|
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),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
async def insert_analysis_run(
|
async def insert_analysis_run(
|
||||||
analysis_run_id: str,
|
analysis_run_id: str,
|
||||||
hospital_id: str,
|
hospital_id: str,
|
||||||
@@ -97,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,))
|
||||||
@@ -113,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"]),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -231,3 +261,27 @@ async def save_hospital_raw_data(hospital_id: str, data: dict, analysis_run_id:
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
await _insert_hospital_history(hospital_id, analysis_run_id)
|
await _insert_hospital_history(hospital_id, analysis_run_id)
|
||||||
|
|
||||||
|
|
||||||
|
async def merge_hospital_raw_data(hospital_id: str, patch: dict) -> None:
|
||||||
|
"""hospital_baseinfo.raw_data를 읽어 patch를 top-level 병합 후 저장 (read-modify-write).
|
||||||
|
부가 수집 단계들이 순차로 raw_data에 키를 덧붙일 때 사용."""
|
||||||
|
row = await fetchone("SELECT raw_data FROM hospital_baseinfo WHERE hospital_id = %s", (hospital_id,))
|
||||||
|
raw = row["raw_data"] if row else None
|
||||||
|
raw_data = json.loads(raw) if isinstance(raw, str) else (raw or {})
|
||||||
|
raw_data.update(patch)
|
||||||
|
await execute(
|
||||||
|
"UPDATE hospital_baseinfo SET raw_data = %s WHERE hospital_id = %s",
|
||||||
|
(json.dumps(raw_data, ensure_ascii=False), hospital_id),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
+22
-38
@@ -1,12 +1,15 @@
|
|||||||
import os
|
import os
|
||||||
import re
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import logging
|
||||||
from http import HTTPMethod
|
from http import HTTPMethod
|
||||||
import httpx
|
import httpx
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
REQUEST_TIMEOUT = 60
|
REQUEST_TIMEOUT = 60
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def get_env(key: str) -> str:
|
def get_env(key: str) -> str:
|
||||||
v = os.environ.get(key, "")
|
v = os.environ.get(key, "")
|
||||||
if not v:
|
if not v:
|
||||||
@@ -39,44 +42,25 @@ async def http_request(
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
_SKIP_IG = {"p", "reel", "stories", "explore", "accounts", "about", "directory"}
|
async def _run_optional_step(coro, label: str) -> None:
|
||||||
_SKIP_FB = {"sharer", "share", "dialog", "plugins", "groups", "events", "watch", "help"}
|
"""부가 단계 실행 헬퍼: 예외를 삼키고 경고 로그만 남겨 호출측 흐름이 멈추지 않게 격리."""
|
||||||
|
try:
|
||||||
|
await coro
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("%s 실패 (무시하고 진행): %s", label, e)
|
||||||
|
|
||||||
|
|
||||||
def extract_social_handles(urls: list[str]) -> dict[str, list[str]]:
|
def _normalize_homepage(url: str) -> str:
|
||||||
result: dict[str, list[str]] = {"instagram": [], "youtube": [], "facebook": [], "naver_blog": [], "tiktok": []}
|
"""URL을 scheme/www/끝슬래시 제거 + 소문자로 정규화 (homepage 매칭용)."""
|
||||||
|
u = (url or "").strip().lower()
|
||||||
for url in urls:
|
for p in ("https://", "http://"):
|
||||||
if not url:
|
if u.startswith(p):
|
||||||
continue
|
u = u[len(p):]
|
||||||
m = re.search(r"instagram\.com/([a-zA-Z0-9._]+)", url)
|
if u.startswith("www."):
|
||||||
if m and m.group(1).lower() not in _SKIP_IG:
|
u = u[4:]
|
||||||
result["instagram"].append(m.group(1))
|
return u.rstrip("/")
|
||||||
|
|
||||||
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:
|
def _with_scheme(u: str | None) -> str | None:
|
||||||
"""URL이 들어오면 핸들을 추출하고, 이미 핸들이면 그대로 반환."""
|
"""scheme 없는 URL에 https:// 보정 (수집기 파싱용). 빈 값은 None."""
|
||||||
if not value:
|
return (u if "://" in u else "https://" + u) if u else None
|
||||||
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
|
|
||||||
+103
-69
@@ -1,9 +1,18 @@
|
|||||||
|
import asyncio
|
||||||
from http import HTTPMethod
|
from http import HTTPMethod
|
||||||
from urllib.parse import urlparse
|
from urllib.parse import urlparse
|
||||||
from common.utils import http_request
|
from common.utils import http_request
|
||||||
|
|
||||||
APIFY_BASE = "https://api.apify.com/v2"
|
APIFY_BASE = "https://api.apify.com/v2"
|
||||||
|
|
||||||
|
# Instagram: profile + highlights 두 actor 직접 호출.
|
||||||
|
IG_PROFILE_ACTOR = "coderx~instagram-profile-scraper-bio-posts"
|
||||||
|
IG_HIGHLIGHTS_ACTOR = "igview-owner~instagram-highlights-scraper"
|
||||||
|
|
||||||
|
|
||||||
|
def _ig_username(url: str) -> str:
|
||||||
|
return urlparse(url).path.strip("/").split("/")[0] if "://" in url else url.lstrip("@")
|
||||||
|
|
||||||
|
|
||||||
class ApifyClient:
|
class ApifyClient:
|
||||||
def __init__(self, token: str, wait_for_finish: int = 120):
|
def __init__(self, token: str, wait_for_finish: int = 120):
|
||||||
@@ -33,26 +42,39 @@ class ApifyClient:
|
|||||||
return []
|
return []
|
||||||
return items_resp.json()
|
return items_resp.json()
|
||||||
|
|
||||||
async def fetch_instagram_profile(self, url: str) -> dict | None:
|
async def fetch_instagram_profile(self, username: str) -> dict | None:
|
||||||
username = urlparse(url).path.strip("/").split("/")[0] if "://" in url else url.lstrip("@")
|
items = await self._run_actor(IG_PROFILE_ACTOR, {"usernames": [username]})
|
||||||
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 fetch_instagram_highlights(self, username: str) -> list[dict]:
|
||||||
profile = await self.fetch_instagram_profile(handle)
|
return await self._run_actor(IG_HIGHLIGHTS_ACTOR, {"usernames": [username]})
|
||||||
if not profile or profile.get("error"):
|
|
||||||
|
async def get_instagram_profile(self, url: str) -> dict | None:
|
||||||
|
username = _ig_username(url)
|
||||||
|
# profile·highlights 두 actor를 병렬 호출 (highlights 실패해도 profile만 있으면 진행)
|
||||||
|
profile, highlights = await asyncio.gather(
|
||||||
|
self.fetch_instagram_profile(username),
|
||||||
|
self.fetch_instagram_highlights(username),
|
||||||
|
return_exceptions=True,
|
||||||
|
)
|
||||||
|
if isinstance(profile, Exception) or not profile or profile.get("error"):
|
||||||
return None
|
return None
|
||||||
|
if isinstance(highlights, Exception):
|
||||||
|
highlights = []
|
||||||
return {
|
return {
|
||||||
"username": profile["username"],
|
"username": profile["username"],
|
||||||
|
"profileImage": profile.get("hdProfilePicUrl") or profile.get("profilePicUrl"),
|
||||||
"followers": profile.get("followersCount", 0),
|
"followers": profile.get("followersCount", 0),
|
||||||
"following": profile.get("followsCount", 0),
|
"following": profile.get("followsCount", 0),
|
||||||
"posts": profile.get("postsCount", 0),
|
"posts": profile.get("postsCount", 0),
|
||||||
"bio": profile.get("biography", ""),
|
"bio": profile.get("biography", ""),
|
||||||
|
"category": profile.get("businessCategoryName") or "",
|
||||||
"isBusinessAccount": profile.get("isBusinessAccount", False),
|
"isBusinessAccount": profile.get("isBusinessAccount", False),
|
||||||
"externalUrl": profile.get("externalUrl"),
|
#"externalUrl": profile.get("externalUrl"), LLM에 혼동을 주는 듯 하여 비활성화
|
||||||
|
"highlights": [h["highlightTitle"] for h in (highlights or []) if isinstance(h, dict) and h.get("highlightTitle")],
|
||||||
"latestPosts": [
|
"latestPosts": [
|
||||||
{
|
{
|
||||||
"type": p.get("type"),
|
"type": p.get("mediaType") or p.get("type"),
|
||||||
"likes": p.get("likesCount", 0),
|
"likes": p.get("likesCount", 0),
|
||||||
"comments": p.get("commentsCount", 0),
|
"comments": p.get("commentsCount", 0),
|
||||||
"caption": (p.get("caption") or "")[:500],
|
"caption": (p.get("caption") or "")[:500],
|
||||||
@@ -62,67 +84,36 @@ class ApifyClient:
|
|||||||
],
|
],
|
||||||
}
|
}
|
||||||
|
|
||||||
async def fetch_instagram_posts(self, handle: str, limit: int = 20) -> list[dict]:
|
# 인스타 post 스크래퍼는 현재 파이프라인 미사용 — 비활성화 (필요 시 복구)
|
||||||
clean = handle.lstrip("@")
|
# async def fetch_instagram_posts(self, url: str, limit: int = 20) -> list[dict]:
|
||||||
return await self._run_actor("apify~instagram-post-scraper", {
|
# username = urlparse(url).path.strip("/").split("/")[0] if "://" in url else url.lstrip("@")
|
||||||
"directUrls": [f"https://www.instagram.com/{clean}/"],
|
# return await self._run_actor("apify~instagram-post-scraper", {
|
||||||
"resultsLimit": limit,
|
# "directUrls": [f"https://www.instagram.com/{username}/"],
|
||||||
})
|
# "resultsLimit": limit,
|
||||||
|
# })
|
||||||
async def get_instagram_posts(self, handle: str, limit: int = 20) -> dict:
|
#
|
||||||
items = await self.fetch_instagram_posts(handle, limit)
|
# async def get_instagram_posts(self, url: str, limit: int = 20) -> dict:
|
||||||
posts = [
|
# items = await self.fetch_instagram_posts(url, limit)
|
||||||
{
|
# posts = [
|
||||||
"id": p["id"],
|
# {
|
||||||
"type": p.get("type"),
|
# "id": p["id"],
|
||||||
"url": p.get("url"),
|
# "type": p.get("type"),
|
||||||
"caption": (p.get("caption") or "")[:500],
|
# "url": p.get("url"),
|
||||||
"hashtags": p.get("hashtags", []),
|
# "caption": (p.get("caption") or "")[:500],
|
||||||
"likesCount": p.get("likesCount", 0),
|
# "hashtags": p.get("hashtags", []),
|
||||||
"commentsCount": p.get("commentsCount", 0),
|
# "likesCount": p.get("likesCount", 0),
|
||||||
"timestamp": p.get("timestamp"),
|
# "commentsCount": p.get("commentsCount", 0),
|
||||||
}
|
# "timestamp": p.get("timestamp"),
|
||||||
for p in items
|
# }
|
||||||
]
|
# for p in items
|
||||||
n = len(posts) or 1
|
# ]
|
||||||
return {
|
# n = len(posts) or 1
|
||||||
"posts": posts,
|
# return {
|
||||||
"totalPosts": len(posts),
|
# "posts": posts,
|
||||||
"avgLikes": round(sum(p["likesCount"] for p in posts) / n),
|
# "totalPosts": len(posts),
|
||||||
"avgComments": round(sum(p["commentsCount"] for p in posts) / n),
|
# "avgLikes": round(sum(p["likesCount"] 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]:
|
|
||||||
clean = handle.lstrip("@")
|
|
||||||
return await self._run_actor("apify~instagram-reel-scraper", {
|
|
||||||
"directUrls": [f"https://www.instagram.com/{clean}/reels/"],
|
|
||||||
"resultsLimit": limit,
|
|
||||||
})
|
|
||||||
|
|
||||||
async def get_instagram_reels(self, handle: str, limit: int = 15) -> dict:
|
|
||||||
items = await self.fetch_instagram_reels(handle, limit)
|
|
||||||
reels = [
|
|
||||||
{
|
|
||||||
"id": r["id"],
|
|
||||||
"url": r.get("url"),
|
|
||||||
"caption": (r.get("caption") or "")[:500],
|
|
||||||
"hashtags": r.get("hashtags", []),
|
|
||||||
"likesCount": r.get("likesCount", 0),
|
|
||||||
"commentsCount": r.get("commentsCount", 0),
|
|
||||||
"videoViewCount": r.get("videoViewCount", 0),
|
|
||||||
"videoPlayCount": r.get("videoPlayCount", 0),
|
|
||||||
"videoDuration": r.get("videoDuration", 0),
|
|
||||||
"timestamp": r.get("timestamp"),
|
|
||||||
}
|
|
||||||
for r in items
|
|
||||||
]
|
|
||||||
n = len(reels) or 1
|
|
||||||
return {
|
|
||||||
"reels": reels,
|
|
||||||
"totalReels": len(reels),
|
|
||||||
"avgViews": round(sum(r["videoViewCount"] for r in reels) / n),
|
|
||||||
"avgPlays": round(sum(r["videoPlayCount"] for r in reels) / n),
|
|
||||||
}
|
|
||||||
|
|
||||||
async def fetch_facebook_page(self, page_url: str) -> dict | None:
|
async def fetch_facebook_page(self, page_url: str) -> dict | None:
|
||||||
items = await self._run_actor("apify~facebook-pages-scraper", {"startUrls": [{"url": page_url}]})
|
items = await self._run_actor("apify~facebook-pages-scraper", {"startUrls": [{"url": page_url}]})
|
||||||
@@ -134,6 +125,7 @@ class ApifyClient:
|
|||||||
return None
|
return None
|
||||||
return {
|
return {
|
||||||
"pageName": page.get("title") or page.get("name"),
|
"pageName": page.get("title") or page.get("name"),
|
||||||
|
"profileImage": page.get("profilePictureUrl") or page.get("profilePhoto") or page.get("profilePic"),
|
||||||
"pageUrl": page.get("pageUrl", page_url),
|
"pageUrl": page.get("pageUrl", page_url),
|
||||||
"followers": page.get("followers", 0),
|
"followers": page.get("followers", 0),
|
||||||
"likes": page.get("likes", 0),
|
"likes": page.get("likes", 0),
|
||||||
@@ -145,3 +137,45 @@ class ApifyClient:
|
|||||||
"intro": page.get("intro"),
|
"intro": page.get("intro"),
|
||||||
"rating": page.get("rating"),
|
"rating": page.get("rating"),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async def fetch_tiktok_profile(self, url: str) -> list[dict]:
|
||||||
|
user = urlparse(url).path.strip("/").lstrip("@").split("/")[0] if "://" in url else url.lstrip("@")
|
||||||
|
return await self._run_actor("clockworks~tiktok-scraper", {
|
||||||
|
"profiles": [user],
|
||||||
|
"resultsPerPage": 10,
|
||||||
|
"profileScrapeSections": ["videos"],
|
||||||
|
"profileSorting": "latest",
|
||||||
|
"shouldDownloadVideos": False,
|
||||||
|
"shouldDownloadCovers": False,
|
||||||
|
"shouldDownloadSubtitles": False,
|
||||||
|
})
|
||||||
|
|
||||||
|
async def get_tiktok_profile(self, url: str) -> dict | None:
|
||||||
|
items = await self.fetch_tiktok_profile(url)
|
||||||
|
if not items:
|
||||||
|
return None
|
||||||
|
author = (items[0] or {}).get("authorMeta") or {}
|
||||||
|
videos = [
|
||||||
|
{
|
||||||
|
"title": (v.get("text") or "")[:300],
|
||||||
|
"playCount": v.get("playCount", 0),
|
||||||
|
"diggCount": v.get("diggCount", 0),
|
||||||
|
"commentCount": v.get("commentCount", 0),
|
||||||
|
"shareCount": v.get("shareCount", 0),
|
||||||
|
"createTime": v.get("createTimeISO"),
|
||||||
|
"url": v.get("webVideoUrl"),
|
||||||
|
}
|
||||||
|
for v in items if isinstance(v, dict)
|
||||||
|
]
|
||||||
|
return {
|
||||||
|
"handle": author.get("name"),
|
||||||
|
"profileImage": author.get("avatar"),
|
||||||
|
"nickname": author.get("nickName"),
|
||||||
|
"followers": author.get("fans", 0),
|
||||||
|
"following": author.get("following", 0),
|
||||||
|
"likes": author.get("heart", 0),
|
||||||
|
"videoCount": author.get("video", 0),
|
||||||
|
"verified": author.get("verified", False),
|
||||||
|
"bio": author.get("signature", ""),
|
||||||
|
"recentVideos": videos[:10],
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from common.utils import get_env
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_DEFAULT_CONTENT_TYPE = "application/octet-stream"
|
||||||
|
_CONTENT_TYPES = {
|
||||||
|
".jpg": "image/jpeg",
|
||||||
|
".jpeg": "image/jpeg",
|
||||||
|
".png": "image/png",
|
||||||
|
".gif": "image/gif",
|
||||||
|
".webp": "image/webp",
|
||||||
|
".bmp": "image/bmp",
|
||||||
|
".mp3": "audio/mpeg",
|
||||||
|
".mp4": "video/mp4",
|
||||||
|
".mov": "video/quicktime",
|
||||||
|
".pdf": "application/pdf",
|
||||||
|
".txt": "text/plain",
|
||||||
|
".json": "application/json",
|
||||||
|
".csv": "text/csv",
|
||||||
|
}
|
||||||
|
|
||||||
|
_shared_client: httpx.AsyncClient | None = None
|
||||||
|
|
||||||
|
|
||||||
|
async def _get_client() -> httpx.AsyncClient:
|
||||||
|
global _shared_client
|
||||||
|
if _shared_client is None or _shared_client.is_closed:
|
||||||
|
_shared_client = httpx.AsyncClient(
|
||||||
|
timeout=httpx.Timeout(180.0, connect=10.0),
|
||||||
|
limits=httpx.Limits(max_keepalive_connections=10, max_connections=20),
|
||||||
|
)
|
||||||
|
return _shared_client
|
||||||
|
|
||||||
|
|
||||||
|
def _sanitize_filename(file_name: str) -> str:
|
||||||
|
stem = Path(file_name).stem
|
||||||
|
suffix = Path(file_name).suffix
|
||||||
|
sanitized = re.sub(r"[^가-힣a-zA-Z0-9]", "", stem) or "file"
|
||||||
|
return f"{sanitized}{suffix}"
|
||||||
|
|
||||||
|
|
||||||
|
def _guess_content_type(file_name: str) -> str:
|
||||||
|
return _CONTENT_TYPES.get(Path(file_name).suffix.lower(), _DEFAULT_CONTENT_TYPE)
|
||||||
|
|
||||||
|
|
||||||
|
class AzureBlobUploader:
|
||||||
|
def __init__(self, group: str, category: str = "file"):
|
||||||
|
self._group = group
|
||||||
|
self._category = category
|
||||||
|
self._base_url = get_env("AZURE_BLOB_BASE_URL")
|
||||||
|
self._sas_token = get_env("AZURE_BLOB_SAS_TOKEN").strip("?'\"")
|
||||||
|
|
||||||
|
def _public_url(self, file_name: str) -> str:
|
||||||
|
return f"{self._base_url}/{self._group}/{self._category}/{file_name}"
|
||||||
|
|
||||||
|
def _upload_url(self, file_name: str) -> str:
|
||||||
|
return f"{self._public_url(file_name)}?{self._sas_token}"
|
||||||
|
|
||||||
|
async def upload_bytes(self, content: bytes, file_name: str, content_type: str | None = None) -> str:
|
||||||
|
file_name = _sanitize_filename(file_name)
|
||||||
|
ct = content_type or _guess_content_type(file_name)
|
||||||
|
url = self._upload_url(file_name)
|
||||||
|
headers = {"Content-Type": ct, "x-ms-blob-type": "BlockBlob"}
|
||||||
|
|
||||||
|
client = await _get_client()
|
||||||
|
resp = await client.put(url, content=content, headers=headers)
|
||||||
|
if resp.status_code not in (200, 201):
|
||||||
|
logger.error("Azure Blob upload failed status=%s body=%s", resp.status_code, resp.text[:500])
|
||||||
|
raise RuntimeError(f"Azure Blob upload failed: {resp.status_code}")
|
||||||
|
|
||||||
|
public_url = self._public_url(file_name)
|
||||||
|
logger.info("Azure Blob uploaded url=%s size=%s", public_url, len(content))
|
||||||
|
return public_url
|
||||||
@@ -0,0 +1,250 @@
|
|||||||
|
"""홈페이지 HTML/CSS에서 hex 색상 직접 추출 + 빈도 기반 brand palette 산출.
|
||||||
|
|
||||||
|
Vision LLM에 의존하지 않고 페이지의 실제 CSS 값을 정규식으로 잡음.
|
||||||
|
로고만 분석하는 Vision보다 사이트 전체 컬러 시스템 (primary/secondary/background/text)을 더 정확히 추출.
|
||||||
|
"""
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
import ssl
|
||||||
|
from collections import Counter
|
||||||
|
from urllib.parse import urljoin, urlparse
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _make_ssl_context() -> ssl.SSLContext:
|
||||||
|
"""오래된 한국 의료 사이트들이 SSL DH_KEY_TOO_SMALL / cipher 약함 등으로 차단되는 문제 우회.
|
||||||
|
보안 등급 1로 낮춤 + cert 검증 유지."""
|
||||||
|
ctx = ssl.create_default_context()
|
||||||
|
try:
|
||||||
|
ctx.set_ciphers("DEFAULT@SECLEVEL=1")
|
||||||
|
except ssl.SSLError:
|
||||||
|
pass
|
||||||
|
return ctx
|
||||||
|
|
||||||
|
|
||||||
|
async def _fetch_html(url: str, timeout: float = 20.0) -> tuple[int, str]:
|
||||||
|
"""SSL/검증 단계별 fallback으로 HTML 받기. 그랜드/톡스앤필 같은 oldsite 대응."""
|
||||||
|
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36"}
|
||||||
|
# 1차: 표준 검증
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True, headers=headers) as c:
|
||||||
|
r = await c.get(url)
|
||||||
|
return r.status_code, r.text
|
||||||
|
except (httpx.ConnectError, httpx.ReadError, ssl.SSLError) as e:
|
||||||
|
logger.info("[fetch] %s standard SSL failed: %s — fallback to weak cipher", url, e)
|
||||||
|
# 2차: 약한 cipher 허용
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True, headers=headers, verify=_make_ssl_context()) as c:
|
||||||
|
r = await c.get(url)
|
||||||
|
return r.status_code, r.text
|
||||||
|
except (httpx.ConnectError, httpx.ReadError, ssl.SSLError) as e:
|
||||||
|
logger.info("[fetch] %s weak cipher failed: %s — fallback to verify=False", url, e)
|
||||||
|
# 3차: SSL 검증 끔 (host mismatch 등)
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True, headers=headers, verify=False) as c:
|
||||||
|
r = await c.get(url)
|
||||||
|
return r.status_code, r.text
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("[fetch] %s all fallbacks failed: %s", url, e)
|
||||||
|
return 0, ""
|
||||||
|
|
||||||
|
LOGO_IMG_PATTERNS = [
|
||||||
|
# 1) <img class="...logo..." src="...">
|
||||||
|
re.compile(r'<img[^>]*\bclass=["\'][^"\']*\blogo\b[^"\']*["\'][^>]*\bsrc=["\']([^"\']+)["\']', re.IGNORECASE),
|
||||||
|
# 2) <img src="..." class="...logo...">
|
||||||
|
re.compile(r'<img[^>]*\bsrc=["\']([^"\']+)["\'][^>]*\bclass=["\'][^"\']*\blogo\b[^"\']*["\']', re.IGNORECASE),
|
||||||
|
# 3) <img id="...logo..." src="...">
|
||||||
|
re.compile(r'<img[^>]*\bid=["\'][^"\']*\blogo\b[^"\']*["\'][^>]*\bsrc=["\']([^"\']+)["\']', re.IGNORECASE),
|
||||||
|
# 4) <img alt="...logo..." src="...">
|
||||||
|
re.compile(r'<img[^>]*\balt=["\'][^"\']*\blogo\b[^"\']*["\'][^>]*\bsrc=["\']([^"\']+)["\']', re.IGNORECASE),
|
||||||
|
# 5) <a/h1 class="logo"><...nested...><img src="...">
|
||||||
|
re.compile(r'<(?:a|h[1-6]|div|span)[^>]*\b(?:class|id)=["\'][^"\']*\blogo\b[^"\']*["\'][^>]*>(?:[^<]|<(?!img))*<img[^>]*\bsrc=["\']([^"\']+)["\']', re.IGNORECASE | re.DOTALL),
|
||||||
|
# 6) inline background-image: <a/div class="logo" style="background-image: url(...)">
|
||||||
|
re.compile(r'<(?:a|div|span|h[1-6])[^>]*\b(?:class|id)=["\'][^"\']*\blogo\b[^"\']*["\'][^>]*\bstyle=["\'][^"\']*background(?:-image)?\s*:\s*url\(\s*["\']?([^"\')\s]+)', re.IGNORECASE),
|
||||||
|
# 7) inline background-image: <a/div style="background-image: url(...)" class="logo"> (속성 순서 반대)
|
||||||
|
re.compile(r'<(?:a|div|span|h[1-6])[^>]*\bstyle=["\'][^"\']*background(?:-image)?\s*:\s*url\(\s*["\']?([^"\')\s]+)[^"\']*["\'][^>]*\b(?:class|id)=["\'][^"\']*\blogo\b', re.IGNORECASE),
|
||||||
|
# 8) src 자체에 "logo" 포함 (header_logo.png, brand-logo.svg 등)
|
||||||
|
re.compile(r'<img[^>]*\bsrc=["\']([^"\']*\blogo\b[^"\']*\.(?:png|svg|jpe?g|webp)[^"\']*)["\']', re.IGNORECASE),
|
||||||
|
# 9) <header>...<img src="..."> (헤더 영역 첫 img)
|
||||||
|
re.compile(r'<header\b[^>]*>(?:[^<]|<(?!img))*<img[^>]*\bsrc=["\']([^"\']+\.(?:png|svg|jpe?g|webp)[^"\']*)["\']', re.IGNORECASE | re.DOTALL),
|
||||||
|
# 10) <nav>...<img src="..."> (nav 영역 첫 img)
|
||||||
|
re.compile(r'<nav\b[^>]*>(?:[^<]|<(?!img))*<img[^>]*\bsrc=["\']([^"\']+\.(?:png|svg|jpe?g|webp)[^"\']*)["\']', re.IGNORECASE | re.DOTALL),
|
||||||
|
# 11) Open Graph image (대표 이미지) - 최후 fallback
|
||||||
|
re.compile(r'<meta[^>]*\bproperty=["\']og:image["\'][^>]*\bcontent=["\']([^"\']+)["\']', re.IGNORECASE),
|
||||||
|
re.compile(r'<meta[^>]*\bcontent=["\']([^"\']+)["\'][^>]*\bproperty=["\']og:image["\']', re.IGNORECASE),
|
||||||
|
]
|
||||||
|
|
||||||
|
# CSS 파일에서 .logo { background-image: url(...) } 추출용
|
||||||
|
LOGO_CSS_PATTERN = re.compile(
|
||||||
|
r'\.[\w-]*\blogo\b[\w-]*\s*(?:,\s*\.[\w-]+\s*)*\{[^}]*background(?:-image)?\s*:\s*url\(\s*["\']?([^"\')\s]+)',
|
||||||
|
re.IGNORECASE | re.DOTALL,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def find_logo_url_in_html(html: str, base_url: str, css_texts: list[str] | None = None) -> str | None:
|
||||||
|
"""HTML에서 logo URL 찾기. class/id/alt → 부모 + 중첩 img → background-image → src에 logo → header/nav → og:image 순."""
|
||||||
|
for pat in LOGO_IMG_PATTERNS:
|
||||||
|
for m in pat.finditer(html):
|
||||||
|
src = m.group(1)
|
||||||
|
if not src or src.startswith("data:"):
|
||||||
|
continue
|
||||||
|
if re.search(r"(blank|spacer|pixel|transparent|1x1)\b", src, re.IGNORECASE):
|
||||||
|
continue
|
||||||
|
return urljoin(base_url, src)
|
||||||
|
# 외부 CSS에서 .logo background-image 추출
|
||||||
|
for css in (css_texts or []):
|
||||||
|
m = LOGO_CSS_PATTERN.search(css)
|
||||||
|
if m:
|
||||||
|
src = m.group(1)
|
||||||
|
if src and not src.startswith("data:"):
|
||||||
|
return urljoin(base_url, src)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
HEX6 = re.compile(r"#([0-9a-fA-F]{6})\b")
|
||||||
|
HEX3 = re.compile(r"#([0-9a-fA-F]{3})\b(?![0-9a-fA-F])")
|
||||||
|
RGB = re.compile(r"rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*[\d.]+\s*)?\)")
|
||||||
|
CSS_VAR_HEX = re.compile(r"--[\w-]+\s*:\s*(#[0-9a-fA-F]{3,8})", re.IGNORECASE)
|
||||||
|
CSS_LINK = re.compile(r'<link[^>]+rel=["\']stylesheet["\'][^>]+href=["\']([^"\']+)["\']', re.IGNORECASE)
|
||||||
|
STYLE_BLOCK = re.compile(r"<style[^>]*>(.*?)</style>", re.IGNORECASE | re.DOTALL)
|
||||||
|
|
||||||
|
# 무채색·아주 흔한 노이즈 컬러 (이런 건 brand color로 잡지 않음)
|
||||||
|
NOISE = {
|
||||||
|
"#ffffff", "#000000", "#fff", "#000",
|
||||||
|
"#333", "#222", "#111", "#444", "#555", "#666", "#777", "#888", "#999",
|
||||||
|
"#aaa", "#bbb", "#ccc", "#ddd", "#eee", "#f0f0f0", "#f5f5f5", "#fafafa",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize(hex_str: str) -> str:
|
||||||
|
h = hex_str.lstrip("#").lower()
|
||||||
|
if len(h) == 3:
|
||||||
|
h = "".join(c * 2 for c in h)
|
||||||
|
if len(h) == 8:
|
||||||
|
h = h[:6]
|
||||||
|
return f"#{h}"
|
||||||
|
|
||||||
|
|
||||||
|
def _rgb_to_hex(r: int, g: int, b: int) -> str:
|
||||||
|
return f"#{r:02x}{g:02x}{b:02x}"
|
||||||
|
|
||||||
|
|
||||||
|
def _hex_to_rgb(h: str) -> tuple[int, int, int]:
|
||||||
|
h = h.lstrip("#")
|
||||||
|
return int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)
|
||||||
|
|
||||||
|
|
||||||
|
def _distance(a: str, b: str) -> float:
|
||||||
|
ar, ag, ab = _hex_to_rgb(a)
|
||||||
|
br, bg, bb = _hex_to_rgb(b)
|
||||||
|
return ((ar - br) ** 2 + (ag - bg) ** 2 + (ab - bb) ** 2) ** 0.5
|
||||||
|
|
||||||
|
|
||||||
|
def _is_grayscale(h: str, tol: int = 12) -> bool:
|
||||||
|
r, g, b = _hex_to_rgb(h)
|
||||||
|
return max(r, g, b) - min(r, g, b) < tol
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_hex(text: str) -> list[str]:
|
||||||
|
"""텍스트에서 모든 hex 색상 추출 (정규화)."""
|
||||||
|
out: list[str] = []
|
||||||
|
out.extend(_normalize(m.group(0)) for m in HEX6.finditer(text))
|
||||||
|
out.extend(_normalize(m.group(0)) for m in HEX3.finditer(text))
|
||||||
|
for m in RGB.finditer(text):
|
||||||
|
r, g, b = int(m.group(1)), int(m.group(2)), int(m.group(3))
|
||||||
|
if 0 <= r <= 255 and 0 <= g <= 255 and 0 <= b <= 255:
|
||||||
|
out.append(_rgb_to_hex(r, g, b))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _cluster(colors: Counter, threshold: float = 25.0) -> list[tuple[str, int]]:
|
||||||
|
"""비슷한 색은 묶음. 가장 빈도 높은 색을 대표로."""
|
||||||
|
ranked = colors.most_common()
|
||||||
|
clusters: list[tuple[str, int]] = []
|
||||||
|
for color, count in ranked:
|
||||||
|
merged = False
|
||||||
|
for i, (rep, rep_count) in enumerate(clusters):
|
||||||
|
if _distance(color, rep) < threshold:
|
||||||
|
clusters[i] = (rep, rep_count + count)
|
||||||
|
merged = True
|
||||||
|
break
|
||||||
|
if not merged:
|
||||||
|
clusters.append((color, count))
|
||||||
|
return clusters
|
||||||
|
|
||||||
|
|
||||||
|
async def _fetch_html_and_css(homepage_url: str, max_css_files: int = 8) -> tuple[str, list[str]]:
|
||||||
|
"""홈페이지 HTML + 외부 CSS(Top N)를 한 번에 fetch. 로고/색상 추출이 사이트를 중복으로 긁지 않도록 공유.
|
||||||
|
_fetch_html이 SSL 약함/host mismatch까지 fallback 처리. 실패 시 ("", [])."""
|
||||||
|
status, html = await _fetch_html(homepage_url)
|
||||||
|
if status != 200 or not html:
|
||||||
|
logger.warning("[color_extractor] homepage fetch failed status=%s url=%s", status, homepage_url)
|
||||||
|
return "", []
|
||||||
|
css_texts: list[str] = []
|
||||||
|
for css_href in CSS_LINK.findall(html)[:max_css_files]:
|
||||||
|
cstatus, ctext = await _fetch_html(urljoin(homepage_url, css_href), timeout=15.0)
|
||||||
|
if cstatus == 200 and ctext:
|
||||||
|
css_texts.append(ctext)
|
||||||
|
return html, css_texts
|
||||||
|
|
||||||
|
|
||||||
|
def _colors_from_text(html: str, css_texts: list[str], source_url: str = "") -> dict:
|
||||||
|
"""이미 받아온 HTML + CSS 텍스트에서 hex 빈도 분석 → primary/accent/text + palette. (fetch 없음, 순수 계산)"""
|
||||||
|
# 1. HTML 내 <style> 블록 + 통째(inline style="color:#...") + 외부 CSS
|
||||||
|
all_text_chunks: list[str] = list(STYLE_BLOCK.findall(html))
|
||||||
|
all_text_chunks.append(html)
|
||||||
|
all_text_chunks.extend(css_texts)
|
||||||
|
|
||||||
|
# 2. 모든 hex 추출 (NOISE 제외)
|
||||||
|
counter: Counter = Counter()
|
||||||
|
for text in all_text_chunks:
|
||||||
|
for color in _extract_hex(text):
|
||||||
|
if color in NOISE:
|
||||||
|
continue
|
||||||
|
counter[color] += 1
|
||||||
|
|
||||||
|
if not counter:
|
||||||
|
logger.info("[color_extractor] no colors extracted from %s", source_url)
|
||||||
|
return {}
|
||||||
|
|
||||||
|
# 3. 비슷한 색 클러스터링
|
||||||
|
clustered = _cluster(counter)
|
||||||
|
|
||||||
|
# 4. primary = 빈도 높은 채도 있는 색 / accent = 두번째 채도 있는 색 / text = 빈도 높은 무채색
|
||||||
|
chromatic = [c for c, _ in clustered if not _is_grayscale(c)]
|
||||||
|
grayscale = [c for c, _ in clustered if _is_grayscale(c)]
|
||||||
|
|
||||||
|
palette_top = clustered[:8]
|
||||||
|
palette = [{"name": f"색상 {i+1}", "hex": h, "usage": f"빈도 {n}"} for i, (h, n) in enumerate(palette_top)]
|
||||||
|
|
||||||
|
return {
|
||||||
|
"brand_colors": {
|
||||||
|
"primary": chromatic[0] if chromatic else None,
|
||||||
|
"accent": chromatic[1] if len(chromatic) > 1 else None,
|
||||||
|
"text": grayscale[0] if grayscale else None,
|
||||||
|
},
|
||||||
|
"color_palette": palette,
|
||||||
|
"extracted_from": "html+css",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def extract_brand_colors_from_site(homepage_url: str, max_css_files: int = 8) -> dict:
|
||||||
|
"""홈페이지 HTML + 외부 CSS fetch → hex 색상 빈도 분석 → primary/accent/text + palette 5종."""
|
||||||
|
html, css_texts = await _fetch_html_and_css(homepage_url, max_css_files)
|
||||||
|
if not html:
|
||||||
|
return {}
|
||||||
|
return _colors_from_text(html, css_texts, homepage_url)
|
||||||
|
|
||||||
|
|
||||||
|
async def extract_brand_assets_from_site(homepage_url: str, max_css_files: int = 8) -> dict:
|
||||||
|
"""사이트를 한 번만 fetch해서 로고 URL과 brand 색상을 함께 추출.
|
||||||
|
반환: {"logo_url": str | None, "colors": {brand_colors, color_palette, ...} | {}}"""
|
||||||
|
html, css_texts = await _fetch_html_and_css(homepage_url, max_css_files)
|
||||||
|
if not html:
|
||||||
|
return {"logo_url": None, "colors": {}}
|
||||||
|
return {
|
||||||
|
"logo_url": find_logo_url_in_html(html, homepage_url, css_texts=css_texts),
|
||||||
|
"colors": _colors_from_text(html, css_texts, homepage_url),
|
||||||
|
}
|
||||||
@@ -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 from the actual header/main <img> src, og:image from <meta property='og:image'> content, favicon URL)",
|
||||||
"schema": {
|
"schema": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
@@ -119,6 +119,7 @@ class FirecrawlClient:
|
|||||||
"headingFont": {"type": "string"},
|
"headingFont": {"type": "string"},
|
||||||
"bodyFont": {"type": "string"},
|
"bodyFont": {"type": "string"},
|
||||||
"logoUrl": {"type": "string"},
|
"logoUrl": {"type": "string"},
|
||||||
|
"ogImage": {"type": "string"},
|
||||||
"faviconUrl": {"type": "string"},
|
"faviconUrl": {"type": "string"},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -158,13 +159,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 +204,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", []),
|
||||||
|
|||||||
@@ -45,6 +45,7 @@ class LLMService:
|
|||||||
response = await self.client.chat.completions.create(
|
response = await self.client.chat.completions.create(
|
||||||
model=prompt.model,
|
model=prompt.model,
|
||||||
messages=[{"role": "user", "content": prompt_text}],
|
messages=[{"role": "user", "content": prompt_text}],
|
||||||
|
max_tokens=16000,
|
||||||
response_format={
|
response_format={
|
||||||
"type": "json_schema",
|
"type": "json_schema",
|
||||||
"json_schema": {"name": prompt.output_class.__name__, "schema": prompt.output_class.model_json_schema()},
|
"json_schema": {"name": prompt.output_class.__name__, "schema": prompt.output_class.model_json_schema()},
|
||||||
|
|||||||
@@ -3,6 +3,12 @@ from pydantic import BaseModel
|
|||||||
from common.utils import get_env
|
from common.utils import get_env
|
||||||
from integrations.llm.schemas.report import ReportInput, ReportOutput
|
from integrations.llm.schemas.report import ReportInput, ReportOutput
|
||||||
from integrations.llm.schemas.plan import PlanInput, PlanOutput
|
from integrations.llm.schemas.plan import PlanInput, PlanOutput
|
||||||
|
from integrations.llm.schemas.market import (
|
||||||
|
MarketCompetitorsInput, MarketCompetitorsOutput,
|
||||||
|
MarketKeywordsInput, MarketKeywordsOutput,
|
||||||
|
MarketTrendInput, MarketTrendOutput,
|
||||||
|
MarketTargetAudienceInput, MarketTargetAudienceOutput,
|
||||||
|
)
|
||||||
|
|
||||||
_PROMPT_DIR = os.path.join(os.path.dirname(__file__), "temp-prompt")
|
_PROMPT_DIR = os.path.join(os.path.dirname(__file__), "temp-prompt")
|
||||||
|
|
||||||
@@ -46,3 +52,31 @@ plan_prompt = Prompt(
|
|||||||
input_class=PlanInput,
|
input_class=PlanInput,
|
||||||
output_class=PlanOutput,
|
output_class=PlanOutput,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
market_competitors_prompt = Prompt(
|
||||||
|
file_name="market_competitors_prompt.txt",
|
||||||
|
prompt_model="MARKET_MODEL",
|
||||||
|
input_class=MarketCompetitorsInput,
|
||||||
|
output_class=MarketCompetitorsOutput,
|
||||||
|
)
|
||||||
|
|
||||||
|
market_keywords_prompt = Prompt(
|
||||||
|
file_name="market_keywords_prompt.txt",
|
||||||
|
prompt_model="MARKET_MODEL",
|
||||||
|
input_class=MarketKeywordsInput,
|
||||||
|
output_class=MarketKeywordsOutput,
|
||||||
|
)
|
||||||
|
|
||||||
|
market_trend_prompt = Prompt(
|
||||||
|
file_name="market_trend_prompt.txt",
|
||||||
|
prompt_model="MARKET_MODEL",
|
||||||
|
input_class=MarketTrendInput,
|
||||||
|
output_class=MarketTrendOutput,
|
||||||
|
)
|
||||||
|
|
||||||
|
market_target_audience_prompt = Prompt(
|
||||||
|
file_name="market_target_audience_prompt.txt",
|
||||||
|
prompt_model="MARKET_MODEL",
|
||||||
|
input_class=MarketTargetAudienceInput,
|
||||||
|
output_class=MarketTargetAudienceOutput,
|
||||||
|
)
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
|
||||||
|
class MarketCompetitorsInput(BaseModel):
|
||||||
|
address: str
|
||||||
|
services: str
|
||||||
|
|
||||||
|
|
||||||
|
class MarketKeywordsInput(BaseModel):
|
||||||
|
services: str
|
||||||
|
|
||||||
|
|
||||||
|
class MarketTrendInput(BaseModel):
|
||||||
|
service: str
|
||||||
|
|
||||||
|
|
||||||
|
class MarketTargetAudienceInput(BaseModel):
|
||||||
|
clinic_name: str
|
||||||
|
|
||||||
|
|
||||||
|
# --- Output ---
|
||||||
|
|
||||||
|
class Competitor(BaseModel):
|
||||||
|
name: str
|
||||||
|
procedures: list[str]
|
||||||
|
reputation: str
|
||||||
|
marketing_channels: list[str]
|
||||||
|
|
||||||
|
|
||||||
|
class MarketCompetitorsOutput(BaseModel):
|
||||||
|
competitors: list[Competitor]
|
||||||
|
|
||||||
|
|
||||||
|
class Keyword(BaseModel):
|
||||||
|
keyword: str
|
||||||
|
monthly_volume: str
|
||||||
|
competition: str
|
||||||
|
|
||||||
|
|
||||||
|
class MarketKeywordsOutput(BaseModel):
|
||||||
|
keywords: list[Keyword]
|
||||||
|
long_tail_keywords: list[str]
|
||||||
|
|
||||||
|
|
||||||
|
class MarketTrendOutput(BaseModel):
|
||||||
|
market_size: str
|
||||||
|
growth_rate: str
|
||||||
|
key_trends: list[str]
|
||||||
|
channel_effectiveness: list[str]
|
||||||
|
|
||||||
|
|
||||||
|
class AudienceSegment(BaseModel):
|
||||||
|
age_group: str
|
||||||
|
gender: str
|
||||||
|
interested_procedures: list[str]
|
||||||
|
info_channels: list[str]
|
||||||
|
decision_factors: list[str]
|
||||||
|
|
||||||
|
|
||||||
|
class MarketTargetAudienceOutput(BaseModel):
|
||||||
|
segments: list[AudienceSegment]
|
||||||
@@ -11,6 +11,15 @@ class PlanInput(BaseModel):
|
|||||||
services: str | None = None
|
services: str | None = None
|
||||||
doctors: str | None = None
|
doctors: str | None = None
|
||||||
report: str | None = None
|
report: str | None = None
|
||||||
|
market_competitors: str | None = None
|
||||||
|
market_keywords: str | None = None
|
||||||
|
market_trend: str | None = None
|
||||||
|
market_target_audience: str | None = None
|
||||||
|
tiktok: str | None = None
|
||||||
|
instagram_en: str | None = None
|
||||||
|
facebook_en: str | None = None
|
||||||
|
channel_logos: str | None = None
|
||||||
|
brand_assets: str | None = None
|
||||||
|
|
||||||
|
|
||||||
# --- BrandGuide ---
|
# --- BrandGuide ---
|
||||||
@@ -25,7 +34,7 @@ class FontSpec(BaseModel):
|
|||||||
family: str
|
family: str
|
||||||
weight: str
|
weight: str
|
||||||
usage: str
|
usage: str
|
||||||
sampleText: str
|
sample_text: str
|
||||||
|
|
||||||
|
|
||||||
class LogoUsageRule(BaseModel):
|
class LogoUsageRule(BaseModel):
|
||||||
@@ -36,29 +45,29 @@ class LogoUsageRule(BaseModel):
|
|||||||
|
|
||||||
class ToneOfVoice(BaseModel):
|
class ToneOfVoice(BaseModel):
|
||||||
personality: list[str]
|
personality: list[str]
|
||||||
communicationStyle: str
|
communication_style: str
|
||||||
doExamples: list[str]
|
do_examples: list[str]
|
||||||
dontExamples: list[str]
|
dont_examples: list[str]
|
||||||
|
|
||||||
|
|
||||||
class ChannelBrandingRule(BaseModel):
|
class ChannelBrandingRule(BaseModel):
|
||||||
channel: str
|
channel: str
|
||||||
icon: str
|
icon: str
|
||||||
profilePhoto: str
|
profile_photo: str
|
||||||
bannerSpec: str
|
banner_spec: str
|
||||||
bioTemplate: str
|
bio_template: str
|
||||||
currentStatus: Literal["correct", "incorrect", "missing"]
|
current_status: Literal["correct", "incorrect", "missing"]
|
||||||
|
|
||||||
|
|
||||||
class BrandInconsistencyValue(BaseModel):
|
class BrandPlanInconsistencyValue(BaseModel):
|
||||||
channel: str
|
channel: str
|
||||||
value: str
|
value: str
|
||||||
isCorrect: bool
|
is_correct: bool
|
||||||
|
|
||||||
|
|
||||||
class BrandInconsistency(BaseModel):
|
class BrandPlanInconsistency(BaseModel):
|
||||||
field: str
|
field: str
|
||||||
values: list[BrandInconsistencyValue]
|
values: list[BrandPlanInconsistencyValue]
|
||||||
impact: str
|
impact: str
|
||||||
recommendation: str
|
recommendation: str
|
||||||
|
|
||||||
@@ -66,26 +75,26 @@ class BrandInconsistency(BaseModel):
|
|||||||
class BrandGuide(BaseModel):
|
class BrandGuide(BaseModel):
|
||||||
colors: list[ColorSwatch]
|
colors: list[ColorSwatch]
|
||||||
fonts: list[FontSpec]
|
fonts: list[FontSpec]
|
||||||
logoRules: list[LogoUsageRule]
|
logo_rules: list[LogoUsageRule]
|
||||||
toneOfVoice: ToneOfVoice
|
tone_of_voice: ToneOfVoice
|
||||||
channelBranding: list[ChannelBrandingRule]
|
channel_branding: list[ChannelBrandingRule]
|
||||||
brandInconsistencies: list[BrandInconsistency]
|
brand_inconsistencies: list[BrandPlanInconsistency]
|
||||||
|
|
||||||
|
|
||||||
# --- ChannelStrategy ---
|
# --- ChannelStrategy ---
|
||||||
|
|
||||||
class ChannelStrategyCard(BaseModel):
|
class ChannelStrategyCard(BaseModel):
|
||||||
channelId: str
|
channel_id: str
|
||||||
channelName: str
|
channel_name: str
|
||||||
icon: str
|
icon: str
|
||||||
currentStatus: str
|
current_status: str
|
||||||
targetGoal: str
|
target_goal: str
|
||||||
contentTypes: list[str]
|
content_types: list[str]
|
||||||
postingFrequency: str
|
posting_frequency: str
|
||||||
tone: str
|
tone: str
|
||||||
formatGuidelines: list[str]
|
format_guidelines: list[str]
|
||||||
priority: Literal["P0", "P1", "P2"]
|
priority: Literal["P0", "P1", "P2"]
|
||||||
customerJourneyStage: Literal["awareness", "interest", "consideration", "conversion", "loyalty"] | None = None
|
customer_journey_stage: Literal["awareness", "interest", "consideration", "conversion", "loyalty"] | None = None
|
||||||
|
|
||||||
|
|
||||||
# --- ContentStrategy ---
|
# --- ContentStrategy ---
|
||||||
@@ -93,8 +102,8 @@ class ChannelStrategyCard(BaseModel):
|
|||||||
class ContentPillar(BaseModel):
|
class ContentPillar(BaseModel):
|
||||||
title: str
|
title: str
|
||||||
description: str
|
description: str
|
||||||
relatedUSP: str
|
related_usp: str
|
||||||
exampleTopics: list[str]
|
example_topics: list[str]
|
||||||
color: str
|
color: str
|
||||||
|
|
||||||
|
|
||||||
@@ -121,30 +130,30 @@ class RepurposingOutput(BaseModel):
|
|||||||
|
|
||||||
class ContentStrategyData(BaseModel):
|
class ContentStrategyData(BaseModel):
|
||||||
pillars: list[ContentPillar]
|
pillars: list[ContentPillar]
|
||||||
typeMatrix: list[ContentTypeRow]
|
type_matrix: list[ContentTypeRow]
|
||||||
workflow: list[WorkflowStep]
|
workflow: list[WorkflowStep]
|
||||||
repurposingSource: str
|
repurposing_source: str
|
||||||
repurposingOutputs: list[RepurposingOutput]
|
repurposing_outputs: list[RepurposingOutput]
|
||||||
|
|
||||||
|
|
||||||
# --- Calendar ---
|
# --- Calendar ---
|
||||||
|
|
||||||
class CalendarEntry(BaseModel):
|
class CalendarEntry(BaseModel):
|
||||||
dayOfWeek: int
|
day_of_week: int
|
||||||
channel: str
|
channel: str
|
||||||
channelIcon: str
|
channel_icon: str
|
||||||
contentType: Literal["video", "blog", "social", "ad"]
|
content_type: Literal["video", "blog", "social", "ad"]
|
||||||
title: str
|
title: str
|
||||||
id: str | None = None
|
id: str | None = None
|
||||||
description: str | None = None
|
description: str | None = None
|
||||||
pillar: str | None = None
|
pillar: str | None = None
|
||||||
status: Literal["draft", "approved", "published"] | None = None
|
status: Literal["draft", "approved", "published"] | None = None
|
||||||
isManualEdit: bool | None = None
|
is_manual_edit: bool | None = None
|
||||||
aiPromptSeed: str | None = None
|
ai_prompt_seed: str | None = None
|
||||||
|
|
||||||
|
|
||||||
class CalendarWeek(BaseModel):
|
class CalendarWeek(BaseModel):
|
||||||
weekNumber: int
|
week_number: int
|
||||||
label: str
|
label: str
|
||||||
entries: list[CalendarEntry]
|
entries: list[CalendarEntry]
|
||||||
|
|
||||||
@@ -158,7 +167,7 @@ class ContentCountSummary(BaseModel):
|
|||||||
|
|
||||||
class CalendarData(BaseModel):
|
class CalendarData(BaseModel):
|
||||||
weeks: list[CalendarWeek]
|
weeks: list[CalendarWeek]
|
||||||
monthlySummary: list[ContentCountSummary]
|
monthly_summary: list[ContentCountSummary]
|
||||||
|
|
||||||
|
|
||||||
# --- AssetCollection ---
|
# --- AssetCollection ---
|
||||||
@@ -166,11 +175,11 @@ class CalendarData(BaseModel):
|
|||||||
class AssetCard(BaseModel):
|
class AssetCard(BaseModel):
|
||||||
id: str
|
id: str
|
||||||
source: Literal["homepage", "naver_place", "blog", "social", "youtube"]
|
source: Literal["homepage", "naver_place", "blog", "social", "youtube"]
|
||||||
sourceLabel: str
|
source_label: str
|
||||||
type: Literal["photo", "video", "text"]
|
type: Literal["photo", "video", "text"]
|
||||||
title: str
|
title: str
|
||||||
description: str
|
description: str
|
||||||
repurposingSuggestions: list[str]
|
repurposing_suggestions: list[str]
|
||||||
status: Literal["collected", "pending", "needs_creation"]
|
status: Literal["collected", "pending", "needs_creation"]
|
||||||
|
|
||||||
|
|
||||||
@@ -178,62 +187,29 @@ class YouTubeRepurposeItem(BaseModel):
|
|||||||
title: str
|
title: str
|
||||||
views: int
|
views: int
|
||||||
type: Literal["Short", "Long"]
|
type: Literal["Short", "Long"]
|
||||||
repurposeAs: list[str]
|
repurpose_as: list[str]
|
||||||
|
|
||||||
|
|
||||||
class AssetCollectionData(BaseModel):
|
class AssetCollectionData(BaseModel):
|
||||||
assets: list[AssetCard]
|
assets: list[AssetCard]
|
||||||
youtubeRepurpose: list[YouTubeRepurposeItem]
|
youtube_repurpose: list[YouTubeRepurposeItem]
|
||||||
|
|
||||||
|
|
||||||
# --- Repurposing ---
|
# --- Repurposing ---
|
||||||
|
|
||||||
class RepurposingProposalItem(BaseModel):
|
class RepurposingProposalItem(BaseModel):
|
||||||
sourceVideo: YouTubeRepurposeItem
|
source_video: YouTubeRepurposeItem
|
||||||
outputs: list[RepurposingOutput]
|
outputs: list[RepurposingOutput]
|
||||||
estimatedEffort: Literal["low", "medium", "high"]
|
estimated_effort: Literal["low", "medium", "high"]
|
||||||
priority: Literal["high", "medium", "low"]
|
priority: Literal["high", "medium", "low"]
|
||||||
|
|
||||||
|
|
||||||
# --- Workflow ---
|
|
||||||
|
|
||||||
class WorkflowVideoDraft(BaseModel):
|
|
||||||
script: str
|
|
||||||
shootingGuide: list[str]
|
|
||||||
duration: str
|
|
||||||
|
|
||||||
|
|
||||||
# class WorkflowImageTextDraft(BaseModel):
|
|
||||||
# type: Literal["cardnews", "blog"]
|
|
||||||
# headline: str
|
|
||||||
# copy: list[str]
|
|
||||||
# layoutHint: str | None = None
|
|
||||||
|
|
||||||
|
|
||||||
# class WorkflowItem(BaseModel):
|
|
||||||
# id: str
|
|
||||||
# title: str
|
|
||||||
# contentType: Literal["video", "image-text"]
|
|
||||||
# channel: str
|
|
||||||
# channelIcon: str
|
|
||||||
# stage: Literal["planning", "ai-draft", "review", "approved", "scheduled"]
|
|
||||||
# userNotes: str | None = None
|
|
||||||
# videoDraft: WorkflowVideoDraft | None = None
|
|
||||||
# imageTextDraft: WorkflowImageTextDraft | None = None
|
|
||||||
# scheduledDate: str | None = None
|
|
||||||
|
|
||||||
|
|
||||||
# class WorkflowData(BaseModel):
|
|
||||||
# items: list[WorkflowItem]
|
|
||||||
|
|
||||||
|
|
||||||
# --- PlanOutput ---
|
# --- PlanOutput ---
|
||||||
|
|
||||||
class PlanOutput(BaseModel):
|
class PlanOutput(BaseModel):
|
||||||
brandGuide: BrandGuide
|
brand_guide: BrandGuide
|
||||||
channelStrategies: list[ChannelStrategyCard]
|
channel_strategies: list[ChannelStrategyCard]
|
||||||
contentStrategy: ContentStrategyData
|
content_strategy: ContentStrategyData
|
||||||
calendar: CalendarData
|
calendar: CalendarData
|
||||||
assetCollection: AssetCollectionData
|
asset_collection: AssetCollectionData
|
||||||
repurposingProposals: list[RepurposingProposalItem] | None = None
|
repurposing_proposals: list[RepurposingProposalItem] | None = None
|
||||||
#workflow: WorkflowData | None = None
|
|
||||||
@@ -1,8 +1,309 @@
|
|||||||
|
from __future__ import annotations
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
from models.status import Severity, ChannelStatus, DataSource, Language, VideoType, AnnotationType
|
||||||
|
|
||||||
|
|
||||||
# template.format(**model_dump()) 에 삽입될 변수들
|
class ScreenshotAnnotation(BaseModel):
|
||||||
# 각 채널 raw_data를 호출부에서 json.dumps()로 직렬화해서 넘겨야 함
|
type: AnnotationType
|
||||||
|
x: float
|
||||||
|
y: float
|
||||||
|
width: float | None = None
|
||||||
|
height: float | None = None
|
||||||
|
label: str | None = None
|
||||||
|
color: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class ScreenshotEvidence(BaseModel):
|
||||||
|
id: str
|
||||||
|
url: str
|
||||||
|
channel: str
|
||||||
|
captured_at: str
|
||||||
|
caption: str
|
||||||
|
source_url: str | None = None
|
||||||
|
annotations: list[ScreenshotAnnotation] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class DiagnosisItem(BaseModel):
|
||||||
|
category: str
|
||||||
|
detail: str
|
||||||
|
severity: Severity
|
||||||
|
evidence_ids: list[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
# --- ClinicSnapshot ---
|
||||||
|
|
||||||
|
class LeadDoctor(BaseModel):
|
||||||
|
name: str
|
||||||
|
credentials: str
|
||||||
|
rating: float
|
||||||
|
review_count: int
|
||||||
|
|
||||||
|
|
||||||
|
class PriceRange(BaseModel):
|
||||||
|
min: str
|
||||||
|
max: str
|
||||||
|
currency: str
|
||||||
|
|
||||||
|
|
||||||
|
class LogoImages(BaseModel):
|
||||||
|
circle: str | None = None
|
||||||
|
horizontal: str | None = None
|
||||||
|
korean: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class BrandColors(BaseModel):
|
||||||
|
primary: str
|
||||||
|
accent: str
|
||||||
|
text: str
|
||||||
|
|
||||||
|
|
||||||
|
class RegistryData(BaseModel):
|
||||||
|
district: str | None = None
|
||||||
|
branches: str | None = None
|
||||||
|
brand_group: str | None = None
|
||||||
|
website_en: str | None = None
|
||||||
|
naver_place_url: str | None = None
|
||||||
|
gangnam_unni_url: str | None = None
|
||||||
|
google_maps_url: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class ClinicSnapshot(BaseModel):
|
||||||
|
name: str
|
||||||
|
name_en: str
|
||||||
|
established: str
|
||||||
|
years_in_business: int
|
||||||
|
staff_count: int
|
||||||
|
lead_doctor: LeadDoctor
|
||||||
|
overall_rating: float
|
||||||
|
total_reviews: int
|
||||||
|
price_range: PriceRange
|
||||||
|
certifications: list[str]
|
||||||
|
media_appearances: list[str]
|
||||||
|
medical_tourism: list[str]
|
||||||
|
location: str
|
||||||
|
nearest_station: str
|
||||||
|
phone: str
|
||||||
|
domain: str
|
||||||
|
logo_images: LogoImages | None = None
|
||||||
|
brand_colors: BrandColors | None = None
|
||||||
|
source: DataSource | None = None
|
||||||
|
registry_data: RegistryData | None = None
|
||||||
|
|
||||||
|
|
||||||
|
# --- ChannelScore ---
|
||||||
|
|
||||||
|
class ChannelScore(BaseModel):
|
||||||
|
channel: str
|
||||||
|
icon: str
|
||||||
|
score: int
|
||||||
|
max_score: int
|
||||||
|
status: Severity
|
||||||
|
headline: str
|
||||||
|
|
||||||
|
|
||||||
|
# --- YouTube ---
|
||||||
|
|
||||||
|
class WeeklyViewGrowth(BaseModel):
|
||||||
|
absolute: int
|
||||||
|
percentage: float
|
||||||
|
|
||||||
|
|
||||||
|
class EstimatedRevenue(BaseModel):
|
||||||
|
min: int
|
||||||
|
max: int
|
||||||
|
|
||||||
|
|
||||||
|
class LinkedUrl(BaseModel):
|
||||||
|
label: str
|
||||||
|
url: str
|
||||||
|
|
||||||
|
|
||||||
|
class TopVideo(BaseModel):
|
||||||
|
title: str
|
||||||
|
views: int
|
||||||
|
uploaded_ago: str
|
||||||
|
type: VideoType
|
||||||
|
duration: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class YouTubeAudit(BaseModel):
|
||||||
|
channel_name: str
|
||||||
|
handle: str
|
||||||
|
subscribers: int
|
||||||
|
total_videos: int
|
||||||
|
total_views: int
|
||||||
|
weekly_view_growth: WeeklyViewGrowth
|
||||||
|
estimated_monthly_revenue: EstimatedRevenue
|
||||||
|
avg_video_length: str
|
||||||
|
upload_frequency: str
|
||||||
|
channel_created_date: str
|
||||||
|
subscriber_rank: str
|
||||||
|
channel_description: str
|
||||||
|
linked_urls: list[LinkedUrl]
|
||||||
|
playlists: list[str]
|
||||||
|
top_videos: list[TopVideo]
|
||||||
|
diagnosis: list[DiagnosisItem]
|
||||||
|
|
||||||
|
|
||||||
|
# --- Instagram ---
|
||||||
|
|
||||||
|
class InstagramAccount(BaseModel):
|
||||||
|
handle: str
|
||||||
|
language: Language
|
||||||
|
label: str
|
||||||
|
posts: int
|
||||||
|
followers: int
|
||||||
|
following: int
|
||||||
|
category: str
|
||||||
|
profile_link: str
|
||||||
|
highlights: list[str]
|
||||||
|
reels_count: int
|
||||||
|
content_format: str
|
||||||
|
profile_photo: str
|
||||||
|
bio: str
|
||||||
|
|
||||||
|
|
||||||
|
class InstagramAudit(BaseModel):
|
||||||
|
accounts: list[InstagramAccount]
|
||||||
|
diagnosis: list[DiagnosisItem]
|
||||||
|
|
||||||
|
|
||||||
|
# --- Facebook ---
|
||||||
|
|
||||||
|
class BrandInconsistencyValue(BaseModel):
|
||||||
|
channel: str
|
||||||
|
value: str
|
||||||
|
is_correct: bool
|
||||||
|
|
||||||
|
|
||||||
|
class BrandInconsistency(BaseModel):
|
||||||
|
field: str
|
||||||
|
values: list[BrandInconsistencyValue]
|
||||||
|
impact: str
|
||||||
|
recommendation: str
|
||||||
|
|
||||||
|
|
||||||
|
class FacebookPage(BaseModel):
|
||||||
|
url: str
|
||||||
|
page_name: str
|
||||||
|
language: Language
|
||||||
|
label: str
|
||||||
|
followers: int
|
||||||
|
following: int
|
||||||
|
category: str
|
||||||
|
bio: str
|
||||||
|
logo: str
|
||||||
|
logo_description: str
|
||||||
|
link: str
|
||||||
|
linked_domain: str
|
||||||
|
reviews: int
|
||||||
|
recent_post_age: str
|
||||||
|
has_whatsapp: bool
|
||||||
|
post_frequency: str | None = None
|
||||||
|
top_content_type: str | None = None
|
||||||
|
engagement: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class FacebookAudit(BaseModel):
|
||||||
|
pages: list[FacebookPage]
|
||||||
|
diagnosis: list[DiagnosisItem]
|
||||||
|
brand_inconsistencies: list[BrandInconsistency]
|
||||||
|
consolidation_recommendation: str
|
||||||
|
|
||||||
|
|
||||||
|
# --- 기타 채널 / 웹사이트 ---
|
||||||
|
|
||||||
|
class OtherChannel(BaseModel):
|
||||||
|
name: str
|
||||||
|
status: ChannelStatus
|
||||||
|
details: str
|
||||||
|
url: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class TrackingPixel(BaseModel):
|
||||||
|
name: str
|
||||||
|
installed: bool
|
||||||
|
details: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class SnsLink(BaseModel):
|
||||||
|
platform: str
|
||||||
|
url: str
|
||||||
|
location: str
|
||||||
|
|
||||||
|
|
||||||
|
class AdditionalDomain(BaseModel):
|
||||||
|
domain: str
|
||||||
|
purpose: str
|
||||||
|
|
||||||
|
|
||||||
|
class WebsiteAudit(BaseModel):
|
||||||
|
primary_domain: str
|
||||||
|
additional_domains: list[AdditionalDomain]
|
||||||
|
sns_links_on_site: bool
|
||||||
|
sns_links_detail: list[SnsLink] | None = None
|
||||||
|
tracking_pixels: list[TrackingPixel]
|
||||||
|
main_cta: str
|
||||||
|
|
||||||
|
|
||||||
|
# --- Transformation ---
|
||||||
|
|
||||||
|
class AsIsToBeItem(BaseModel):
|
||||||
|
area: str
|
||||||
|
as_is: str
|
||||||
|
to_be: str
|
||||||
|
|
||||||
|
|
||||||
|
class StrategyDetail(BaseModel):
|
||||||
|
strategy: str
|
||||||
|
detail: str
|
||||||
|
|
||||||
|
|
||||||
|
class PlatformStrategy(BaseModel):
|
||||||
|
platform: str
|
||||||
|
icon: str
|
||||||
|
current_metric: str
|
||||||
|
target_metric: str
|
||||||
|
strategies: list[StrategyDetail]
|
||||||
|
|
||||||
|
|
||||||
|
class NewChannelProposal(BaseModel):
|
||||||
|
channel: str
|
||||||
|
priority: str
|
||||||
|
rationale: str
|
||||||
|
|
||||||
|
|
||||||
|
class TransformationProposal(BaseModel):
|
||||||
|
brand_identity: list[AsIsToBeItem]
|
||||||
|
content_strategy: list[AsIsToBeItem]
|
||||||
|
platform_strategies: list[PlatformStrategy]
|
||||||
|
website_improvements: list[AsIsToBeItem]
|
||||||
|
new_channel_proposals: list[NewChannelProposal]
|
||||||
|
|
||||||
|
|
||||||
|
# --- Roadmap / KPI ---
|
||||||
|
|
||||||
|
class RoadmapTask(BaseModel):
|
||||||
|
task: str
|
||||||
|
completed: bool
|
||||||
|
|
||||||
|
|
||||||
|
class RoadmapMonth(BaseModel):
|
||||||
|
month: int
|
||||||
|
title: str
|
||||||
|
subtitle: str
|
||||||
|
tasks: list[RoadmapTask]
|
||||||
|
|
||||||
|
|
||||||
|
class KPIMetric(BaseModel):
|
||||||
|
metric: str
|
||||||
|
current: str
|
||||||
|
target_3_month: str
|
||||||
|
target_12_month: str
|
||||||
|
|
||||||
|
|
||||||
|
# --- ReportInput (prompt 템플릿 변수) ---
|
||||||
|
|
||||||
class ReportInput(BaseModel):
|
class ReportInput(BaseModel):
|
||||||
clinic_name: str | None = None
|
clinic_name: str | None = None
|
||||||
clinic_name_en: str | None = None
|
clinic_name_en: str | None = None
|
||||||
@@ -16,28 +317,37 @@ class ReportInput(BaseModel):
|
|||||||
naver_blog: str | None = None
|
naver_blog: str | None = None
|
||||||
youtube: str | None = None
|
youtube: str | None = None
|
||||||
gangnam_unni: str | None = None
|
gangnam_unni: str | None = None
|
||||||
|
market_competitors: str | None = None
|
||||||
|
market_keywords: str | None = None
|
||||||
|
market_trend: str | None = None
|
||||||
|
market_target_audience: str | None = None
|
||||||
|
branding: str | None = None
|
||||||
|
brand_assets: str | None = None
|
||||||
|
tiktok: str | None = None
|
||||||
|
instagram_en: str | None = None
|
||||||
|
facebook_en: str | None = None
|
||||||
|
channel_logos: str | None = None
|
||||||
|
|
||||||
|
|
||||||
class ChannelScore(BaseModel):
|
# --- MarketingReport ---
|
||||||
score: int
|
|
||||||
summary: str
|
|
||||||
strengths: list[str]
|
|
||||||
weaknesses: list[str]
|
|
||||||
|
|
||||||
|
class MarketingReport(BaseModel):
|
||||||
class ConversionStrategy(BaseModel):
|
id: str
|
||||||
summary: str
|
created_at: str
|
||||||
actions: list[str]
|
target_url: str
|
||||||
|
|
||||||
|
|
||||||
# response_format으로 OpenAI structured output에 전달 — dict 필드 사용 불가
|
|
||||||
class ReportOutput(BaseModel):
|
|
||||||
overall_score: int
|
overall_score: int
|
||||||
instagram: ChannelScore | None = None
|
clinic_snapshot: ClinicSnapshot
|
||||||
facebook: ChannelScore | None = None
|
channel_scores: list[ChannelScore]
|
||||||
naver_blog: ChannelScore | None = None
|
youtube_audit: YouTubeAudit
|
||||||
youtube: ChannelScore | None = None
|
instagram_audit: InstagramAudit
|
||||||
gangnam_unni: ChannelScore | None = None
|
facebook_audit: FacebookAudit
|
||||||
conversion_strategy: ConversionStrategy
|
other_channels: list[OtherChannel]
|
||||||
roadmap: list[str]
|
website_audit: WebsiteAudit
|
||||||
kpis: list[str]
|
problem_diagnosis: list[DiagnosisItem]
|
||||||
|
transformation: TransformationProposal
|
||||||
|
roadmap: list[RoadmapMonth]
|
||||||
|
kpi_dashboard: list[KPIMetric]
|
||||||
|
screenshots: list[ScreenshotEvidence] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
ReportOutput = MarketingReport
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
{address} 근처 {services} 전문 성형외과/피부과 경쟁 병원 5곳을 분석해줘.
|
||||||
|
각 병원의 이름, 주요 시술, 온라인 평판, 마케팅 채널을 JSON 형식으로 제공해줘.
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
한국 {services} 관련 검색 키워드 트렌드.
|
||||||
|
네이버와 구글에서 월간 검색량이 높은 키워드 20개, 경쟁 강도, 추천 롱테일 키워드를 JSON 형식으로 제공해줘.
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
{clinic_name}의 잠재 고객 분석.
|
||||||
|
연령대별, 성별, 관심 시술, 정보 탐색 채널, 의사결정 요인을 JSON 형식으로 제공해줘.
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
한국 {service} 시장 트렌드 2025-2026.
|
||||||
|
시장 규모, 성장률, 주요 트렌드, 마케팅 채널별 효과를 JSON 형식으로 제공해줘.
|
||||||
@@ -15,22 +15,64 @@
|
|||||||
- 시술: {services}
|
- 시술: {services}
|
||||||
- 의료진: {doctors}
|
- 의료진: {doctors}
|
||||||
|
|
||||||
|
## 시장 분석 데이터
|
||||||
|
|
||||||
|
### 경쟁 병원
|
||||||
|
{market_competitors}
|
||||||
|
|
||||||
|
### 검색 키워드 트렌드
|
||||||
|
{market_keywords}
|
||||||
|
|
||||||
|
### 시장 트렌드
|
||||||
|
{market_trend}
|
||||||
|
|
||||||
|
### 잠재 고객 분석
|
||||||
|
{market_target_audience}
|
||||||
|
|
||||||
## 분석 리포트
|
## 분석 리포트
|
||||||
{report}
|
{report}
|
||||||
|
|
||||||
|
## 추가 채널 데이터 (틱톡 / 인스타그램 EN / 페이스북 EN)
|
||||||
|
아래에 데이터가 있는 채널은 channelStrategies와 channelBranding에 **반드시 포함**하세요 (틱톡, 영문 인스타그램, 영문 페이스북). null이면 제외.
|
||||||
|
|
||||||
|
### 틱톡 (TikTok)
|
||||||
|
{tiktok}
|
||||||
|
|
||||||
|
### 인스타그램 (영문 계정)
|
||||||
|
{instagram_en}
|
||||||
|
|
||||||
|
### 페이스북 (영문 페이지)
|
||||||
|
{facebook_en}
|
||||||
|
|
||||||
|
## 채널별 로고 분석 (Gemini Vision) — 채널룰/일관성의 근거
|
||||||
|
{channel_logos}
|
||||||
|
- 위 channel_logos[]의 각 항목: channel(채널명), logo_description(프로필이 어떻게 생겼는지), is_official(공식 로고와 일치 여부).
|
||||||
|
- **channelBranding[]를 이 데이터로 채우세요**: 채널별로 profilePhoto=해당 채널의 logo_description, currentStatus=is_official이 true면 "correct" / false면 "incorrect" (데이터 없는 채널은 "missing"). bannerSpec은 권장 배너 규격(크기/디자인)을 작성.
|
||||||
|
- **brandInconsistencies[]에 "로고" 항목을 반드시 만드세요**: values[]에 채널마다 channel(채널명) / value(logo_description 그대로) / is_correct(is_official 값) 세 필드를 넣고, impact는 inconsistency_summary, recommendation은 channel_logos.recommendation 기반으로 작성 (공식 로고로 통일 권고 포함).
|
||||||
|
|
||||||
|
## 브랜드 자산 (홈페이지 CSS에서 추출 — 결정적 데이터)
|
||||||
|
{brand_assets}
|
||||||
|
- brand_assets.color_palette[]의 hex와 brand_assets.brand_colors(primary/accent/text)는 **홈페이지 CSS에서 실제로 추출한 값**입니다.
|
||||||
|
- **brandGuide.colors의 hex는 반드시 이 추출값을 그대로 사용하세요. hex를 새로 지어내거나 변형하지 마세요** (매 실행마다 동일해야 함). name/usage 설명은 의미있게 써도 되지만 hex 값 자체는 추출값으로 고정.
|
||||||
|
|
||||||
## 섹션별 작성 지침
|
## 섹션별 작성 지침
|
||||||
|
|
||||||
### Section 1: brandGuide
|
### Section 1: brandGuide
|
||||||
- colors: 병원 아이덴티티에 맞는 컬러 팔레트 3~5개 (hex + 사용 가이드)
|
- colors: **brand_assets.color_palette / brand_colors의 hex를 그대로 사용** (홈페이지 CSS 추출값, 지어내기 금지). 3~5개, 각 hex에 name/usage 부여
|
||||||
- fonts: 제목/본문/캡션용 폰트 시스템 (한글/영문 포함)
|
- fonts: 제목/본문/캡션용 폰트 시스템 (한글/영문 포함)
|
||||||
- logoRules: DO/DON'T 형식의 로고 사용 규칙 4~6개
|
- logoRules: 로고 사용 규칙 4~6개. 각 항목은 rule / description / correct 3개 필드로 구성:
|
||||||
|
- rule: 규칙을 요약한 **구체적인 제목**. "DO"·"DON'T" 같은 단어를 그대로 넣지 말 것. 실제 규칙 내용을 쓸 것 (예: "보라색+골드 깃털 로고 통일 사용", "모델 사진 프로필 금지", "비공식 변형 로고 사용 금지", "로고 주변 여백 확보").
|
||||||
|
- description: 해당 규칙의 상세 설명.
|
||||||
|
- correct: 권장 규칙(DO)이면 true, 금지/지양 규칙(DON'T)이면 false. 권장(true)과 금지(false)를 섞어서 작성.
|
||||||
- toneOfVoice: 브랜드 성격 키워드, 커뮤니케이션 스타일, 권장/지양 표현 예시
|
- toneOfVoice: 브랜드 성격 키워드, 커뮤니케이션 스타일, 권장/지양 표현 예시
|
||||||
- channelBranding: 리포트에 존재하는 채널별 브랜딩 적용 규칙
|
- channelBranding: 리포트에 존재하는 채널별 브랜딩 적용 규칙
|
||||||
- brandInconsistencies: 채널 간 브랜딩 불일치 항목 및 개선 권고
|
- brandInconsistencies: 채널 간 브랜딩 불일치 항목 및 개선 권고
|
||||||
|
|
||||||
### Section 2: channelStrategies
|
### Section 2: channelStrategies
|
||||||
- 리포트에 데이터가 있는 채널만 포함
|
- 리포트에 데이터가 있는 채널만 포함
|
||||||
- 각 채널의 우선순위(P0/P1/P2), 목표, 콘텐츠 유형, 게시 빈도, 포맷 가이드라인 작성
|
- **currentStatus는 현재 채널 상태를 실제 수치로 서술** (예: "14,047 팔로워, Reels 0개", "104K 구독자, 주 2~3회 업로드"). `excellent`/`warning`/`good` 같은 등급·평가어를 절대 쓰지 마세요.
|
||||||
|
- targetGoal은 구체적 목표 수치로 작성 (예: "50K 팔로워, Reels 주 5개")
|
||||||
|
- 각 채널의 우선순위(P0/P1/P2), 콘텐츠 유형, 게시 빈도, 포맷 가이드라인 작성
|
||||||
- customerJourneyStage는 해당 채널의 주요 기여 단계로 설정
|
- customerJourneyStage는 해당 채널의 주요 기여 단계로 설정
|
||||||
|
|
||||||
### Section 3: contentStrategy
|
### Section 3: contentStrategy
|
||||||
|
|||||||
@@ -12,6 +12,31 @@
|
|||||||
- 시술: {services}
|
- 시술: {services}
|
||||||
- 의료진: {doctors}
|
- 의료진: {doctors}
|
||||||
|
|
||||||
|
## 브랜드 자산 (홈페이지에서 자동 추출)
|
||||||
|
|
||||||
|
### Firecrawl branding (로고 URL / 색상 / 폰트)
|
||||||
|
{branding}
|
||||||
|
|
||||||
|
### 추출된 브랜드 자산 (로고 묘사 + CSS 색상 팔레트)
|
||||||
|
{brand_assets}
|
||||||
|
|
||||||
|
⚠️ clinic_snapshot.logo_images / brand_colors는 위 추출값(brand_assets.logo_images, brand_assets.brand_colors)을 **그대로** 사용하세요. hex나 로고 URL을 절대 추측하지 마세요. 추출값이 null이면 해당 필드도 null로 두세요.
|
||||||
|
로고에 대한 정성 평가(심볼/워드마크/톤)는 brand_assets.logo_description을 근거로 하고, 채널 프로필 이미지가 공식 로고와 일치하는지 판단할 때도 이 묘사를 기준으로 삼으세요.
|
||||||
|
|
||||||
|
## 시장 분석 데이터
|
||||||
|
|
||||||
|
### 경쟁 병원
|
||||||
|
{market_competitors}
|
||||||
|
|
||||||
|
### 검색 키워드 트렌드
|
||||||
|
{market_keywords}
|
||||||
|
|
||||||
|
### 시장 트렌드
|
||||||
|
{market_trend}
|
||||||
|
|
||||||
|
### 잠재 고객 분석
|
||||||
|
{market_target_audience}
|
||||||
|
|
||||||
## 채널 데이터
|
## 채널 데이터
|
||||||
|
|
||||||
### 인스타그램
|
### 인스타그램
|
||||||
@@ -29,9 +54,44 @@
|
|||||||
### 강남언니
|
### 강남언니
|
||||||
{gangnam_unni}
|
{gangnam_unni}
|
||||||
|
|
||||||
|
### 틱톡 (TikTok)
|
||||||
|
{tiktok}
|
||||||
|
|
||||||
|
### 인스타그램 (영문 계정)
|
||||||
|
{instagram_en}
|
||||||
|
|
||||||
|
### 페이스북 (영문 페이지)
|
||||||
|
{facebook_en}
|
||||||
|
|
||||||
|
### 채널별 로고 분석 (Gemini Vision)
|
||||||
|
{channel_logos}
|
||||||
|
- channel_logos.channel_logos[]에 각 채널의 로고 설명(logo_description)과 공식 로고 일치 여부(is_official)가 있습니다.
|
||||||
|
- **facebook_audit.pages[].logo** 는 짧은 판정 타이틀로: is_official=true면 `"일치 (공식 로고)"`, false면 `"불일치 (비공식 변형)"`. 그리고 **facebook_audit.pages[].logo_description** 에 해당 채널의 logo_description(설명문)을 넣으세요.
|
||||||
|
- 위 값들은 channel_logos 데이터 기반으로만 작성하고 추측하지 마세요.
|
||||||
|
- 채널 간 로고 불일치(is_official=false)는 brand 일관성 진단(problem_diagnosis/weaknesses)에 반영하세요.
|
||||||
|
|
||||||
|
## clinic_snapshot / 채널 audit 작성 지침 (수집 데이터 그대로, 추측 금지)
|
||||||
|
- clinic_snapshot.name 은 {clinic_name} 을 **그대로** 사용 (강남언니 표기명 '-본원' 등으로 바꾸지 말 것).
|
||||||
|
- clinic_snapshot 의 overall_rating/total_reviews/staff_count/location/certifications/lead_doctor 는 강남언니({gangnam_unni}) 데이터의 값을 그대로 사용.
|
||||||
|
- **instagram_audit.accounts 는 반드시 빈 배열 []로 두세요.** 계정 정보는 시스템이 수집 데이터로 직접 채우니 LLM은 만들지 말고, instagram_audit.diagnosis(진단)만 작성하세요.
|
||||||
|
- facebook_audit.pages: KR 페북({facebook})·영문 페북({facebook_en}) 데이터가 있으면 **각각 별도 페이지**로 넣고, url/page_name/followers 등은 그 데이터 그대로. language/label 동일 규칙.
|
||||||
|
- 위 수치·URL·이름은 제공된 데이터에서 그대로 쓰고 절대 지어내지 마세요.
|
||||||
|
|
||||||
|
## 기타 채널 현황 (other_channels) 작성 지침
|
||||||
|
- other_channels에는 메인 audit(YouTube/Instagram/Facebook/Website)에 **포함되지 않은** 채널만 넣으세요.
|
||||||
|
- 위 '채널 데이터'에 **실제 수집된 데이터가 있는 채널만** status=active와 실제 url로 일관되게 포함: 네이버 블로그, 강남언니, 틱톡, 영문 인스타그램({instagram_en}), 영문 페이스북({facebook_en}).
|
||||||
|
- **영문 인스타그램·영문 페이스북은 KR 메인 audit(Instagram/Facebook)과 별개 계정이므로, 데이터가 있으면 반드시 other_channels에 "Instagram EN" / "Facebook EN"으로 각각 포함하세요 (절대 누락 금지).**
|
||||||
|
- **수집 데이터에 없는 채널(카카오톡/네이버플레이스/네이버카페/Threads 등)은 절대 임의로 만들지 마세요.** 데이터 없으면 그 채널은 생략 (랜덤 생성·추측 금지).
|
||||||
|
- url은 수집 데이터의 실제 URL만 사용. 없으면 빈 문자열.
|
||||||
|
|
||||||
## 분석 지침
|
## 분석 지침
|
||||||
|
|
||||||
- 점수는 0~100 기준입니다.
|
- 점수는 0~100 기준입니다.
|
||||||
|
- **channel_scores(채널 종합도)에는 데이터가 있는 모든 채널을 각각 별도 항목으로 만드세요. 같은 플랫폼이라도 한국 계정과 영문 계정을 절대 하나로 합치지 마세요:**
|
||||||
|
- 인스타그램 KR → channel "Instagram", 영문 인스타그램({instagram_en}) 데이터가 있으면 → channel "Instagram EN" (별도 항목)
|
||||||
|
- 페이스북 KR → channel "Facebook", 영문 페이스북({facebook_en}) 데이터가 있으면 → channel "Facebook EN" (별도 항목)
|
||||||
|
- 틱톡({tiktok}) 데이터가 있으면 → channel "TikTok" (별도 항목)
|
||||||
|
- 데이터가 null인 계정은 항목을 만들지 마세요. icon은 instagram/facebook/video 등 플랫폼에 맞게 설정.
|
||||||
- strengths와 weaknesses는 각 3개 이상 작성하세요.
|
- strengths와 weaknesses는 각 3개 이상 작성하세요.
|
||||||
- roadmap은 우선순위 순으로 실행 가능한 액션으로 작성하세요.
|
- roadmap은 우선순위 순으로 실행 가능한 액션으로 작성하세요.
|
||||||
- kpis는 실제 수집된 수치 기반으로 현실적인 측정 가능 지표로 작성하세요.
|
- kpis는 실제 수집된 수치 기반으로 현실적인 측정 가능 지표로 작성하세요.
|
||||||
|
|||||||
@@ -0,0 +1,173 @@
|
|||||||
|
"""Gemini Vision — 로고/브랜드 비주얼 자동 분석 (OpenAI 호환 모드).
|
||||||
|
|
||||||
|
정확한 hex 색상은 color_extractor가 CSS에서 직접 뽑음 (Vision은 근사값밖에 못 냄).
|
||||||
|
Vision은 사람이 봐야 알 수 있는 정성 정보 — 심볼 형태/워드마크/톤 — 를 담당.
|
||||||
|
"""
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
import httpx
|
||||||
|
from openai import AsyncOpenAI
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
DEFAULT_MODEL = "gemini-2.5-flash"
|
||||||
|
|
||||||
|
|
||||||
|
class VisionClient:
|
||||||
|
"""Gemini Vision을 OpenAI 호환 endpoint로 호출. GEMINI_API_KEY만 필요."""
|
||||||
|
|
||||||
|
def __init__(self, api_key: str, model: str = DEFAULT_MODEL, timeout: float = 30.0, max_retries: int = 2):
|
||||||
|
self.client = AsyncOpenAI(
|
||||||
|
api_key=api_key,
|
||||||
|
base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
|
||||||
|
timeout=timeout,
|
||||||
|
max_retries=max_retries,
|
||||||
|
)
|
||||||
|
self.model = model
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _extract_json(text: str) -> dict | None:
|
||||||
|
if not text:
|
||||||
|
return None
|
||||||
|
m = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", text, re.DOTALL)
|
||||||
|
if m:
|
||||||
|
try:
|
||||||
|
return json.loads(m.group(1))
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
pass
|
||||||
|
m = re.search(r"\{.*\}", text, re.DOTALL)
|
||||||
|
if m:
|
||||||
|
try:
|
||||||
|
return json.loads(m.group(0))
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return None
|
||||||
|
return None
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
async def _fetch_as_data_url(url: str) -> str | None:
|
||||||
|
"""Gemini는 URL 직접 fetch가 막힌 호스트가 많아 base64 인라인으로 변환.
|
||||||
|
+ 'image does not exist' 같은 placeholder 이미지 거부 (작은 bytes / 잘못된 content-type)."""
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(timeout=15.0, follow_redirects=True) as c:
|
||||||
|
resp = await c.get(url)
|
||||||
|
if resp.status_code != 200:
|
||||||
|
logger.warning("[vision] fetch %s status=%s", url, resp.status_code)
|
||||||
|
return None
|
||||||
|
mime = resp.headers.get("content-type", "").split(";")[0].strip()
|
||||||
|
# 실제 이미지가 아니면 거부 (HTML 페이지가 404 대신 200으로 리다이렉트 되는 경우)
|
||||||
|
if not mime.startswith("image/"):
|
||||||
|
logger.warning("[vision] %s not an image (content-type=%s)", url, mime)
|
||||||
|
return None
|
||||||
|
size = len(resp.content)
|
||||||
|
if size < 500:
|
||||||
|
logger.warning("[vision] %s too small (%d bytes) — likely placeholder", url, size)
|
||||||
|
return None
|
||||||
|
b64 = base64.b64encode(resp.content).decode("ascii")
|
||||||
|
return f"data:{mime};base64,{b64}"
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("[vision] fetch error %s: %s", url, e)
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def _ask(self, image_urls: list[str], prompt: str, max_tokens: int = 4000) -> dict | None:
|
||||||
|
content: list[dict] = []
|
||||||
|
for u in image_urls:
|
||||||
|
if not u:
|
||||||
|
continue
|
||||||
|
data_url = await self._fetch_as_data_url(u)
|
||||||
|
if not data_url:
|
||||||
|
continue
|
||||||
|
content.append({"type": "image_url", "image_url": {"url": data_url}})
|
||||||
|
if not any(c.get("type") == "image_url" for c in content):
|
||||||
|
logger.warning("[vision] no images could be fetched")
|
||||||
|
return None
|
||||||
|
content.append({"type": "text", "text": prompt})
|
||||||
|
|
||||||
|
try:
|
||||||
|
resp = await self.client.chat.completions.create(
|
||||||
|
model=self.model,
|
||||||
|
messages=[{"role": "user", "content": content}],
|
||||||
|
max_tokens=max_tokens,
|
||||||
|
)
|
||||||
|
choice = resp.choices[0]
|
||||||
|
if choice.finish_reason != "stop":
|
||||||
|
logger.warning("[vision] unexpected finish_reason=%s", choice.finish_reason)
|
||||||
|
return self._extract_json(choice.message.content or "")
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("[vision] error: %s", e)
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def analyze_brand_assets(
|
||||||
|
self,
|
||||||
|
logo_url: str | None,
|
||||||
|
homepage_url: str | None,
|
||||||
|
additional_images: list[str] | None = None,
|
||||||
|
) -> dict:
|
||||||
|
"""로고 이미지를 보고 정성 분석. 정확한 hex는 color_extractor가 따로 처리하므로 여기선 안 뽑음."""
|
||||||
|
urls = [u for u in [logo_url] + list(additional_images or []) if u]
|
||||||
|
if not urls:
|
||||||
|
return {}
|
||||||
|
prompt = (
|
||||||
|
"당신은 브랜드 로고 시각 분석가입니다. 첨부된 이미지(첫 번째가 병원의 대표 로고)를 보고 "
|
||||||
|
"아래 JSON 스키마로만 응답하세요. 코드펜스 없이 순수 JSON만 출력.\n"
|
||||||
|
"{\n"
|
||||||
|
' "logo_description": "로고를 1~2문장으로 설명 (심볼 형태 + 워드마크 + 전반적 톤). 예: \'둥근 잎사귀를 감싼 추상 심볼에 세리프 한글 워드마크, 차분하고 고급스러운 톤\'",\n'
|
||||||
|
' "logo_style": "minimal | illustrative | typographic | abstract 중 하나",\n'
|
||||||
|
' "has_symbol": "심볼/아이콘이 있으면 true, 글자만 있으면 false (boolean)",\n'
|
||||||
|
' "logo_symbol": "심볼이 묘사하는 대상 (예: \'잎사귀\', \'추상 곡선\'). 없으면 빈 문자열",\n'
|
||||||
|
' "logo_text": "로고에 보이는 워드마크 텍스트 그대로 (한글/영문). 없으면 빈 문자열",\n'
|
||||||
|
' "logo_colors_desc": "로고에 쓰인 색감을 사람이 부르는 이름으로 서술 (예: \'딥네이비 + 골드\'). 정확한 hex는 출력하지 말 것"\n'
|
||||||
|
"}\n"
|
||||||
|
"주의: 색상 hex 값이나 logo URL 같은 필드는 출력하지 마세요 (별도 추출 로직이 처리).\n"
|
||||||
|
"모든 설명/텍스트 값은 반드시 한국어로 작성하세요 (영어 금지)."
|
||||||
|
)
|
||||||
|
result = await self._ask(urls, prompt)
|
||||||
|
if not result:
|
||||||
|
return {}
|
||||||
|
# logo_images는 우리가 직접 채움 (Vision은 묘사만)
|
||||||
|
result["logo_images"] = {"circle": None, "horizontal": logo_url, "korean": None}
|
||||||
|
return result
|
||||||
|
|
||||||
|
async def describe_channel_logos(
|
||||||
|
self,
|
||||||
|
official_logo_url: str | None,
|
||||||
|
channel_logos: list[dict],
|
||||||
|
) -> dict | None:
|
||||||
|
"""채널별 프로필 이미지(로고)를 보고 각각 설명 + 공식 로고와 일치 여부 평가.
|
||||||
|
channel_logos: [{"channel": "Instagram", "url": "..."}, ...]
|
||||||
|
반환: {"channel_logos": [{"channel","logo_description","is_official"}], "inconsistency_summary", "recommendation"}"""
|
||||||
|
items = [c for c in channel_logos if c.get("url")]
|
||||||
|
if not items:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# 공식 로고가 있으면 맨 앞에 두고 기준으로 삼음
|
||||||
|
urls: list[str] = []
|
||||||
|
if official_logo_url:
|
||||||
|
urls.append(official_logo_url)
|
||||||
|
urls.extend(c["url"] for c in items)
|
||||||
|
channel_order = ", ".join(c.get("channel", "?") for c in items)
|
||||||
|
|
||||||
|
if official_logo_url:
|
||||||
|
header = (
|
||||||
|
"첨부 이미지 중 **첫 번째가 이 병원의 공식 로고**입니다. "
|
||||||
|
f"이어지는 이미지들은 채널별 프로필 이미지이며 순서는: {channel_order}.\n"
|
||||||
|
"각 채널 로고를 1문장으로 설명하고, 공식 로고(첫 번째)와 일치하면 is_official=true, "
|
||||||
|
"비공식 변형/모델사진/다른 이미지면 false로 평가하세요.\n"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
header = (
|
||||||
|
f"첨부 이미지는 한 병원의 채널별 프로필 이미지입니다. 순서: {channel_order}.\n"
|
||||||
|
"각 채널 로고를 1문장으로 설명하세요 (공식 로고 기준이 없으므로 is_official은 판단 가능하면만).\n"
|
||||||
|
)
|
||||||
|
prompt = (
|
||||||
|
header
|
||||||
|
+ "아래 JSON으로만 응답 (코드펜스 없이 순수 JSON):\n"
|
||||||
|
"{\n"
|
||||||
|
' "channel_logos": [{"channel": "...", "logo_description": "...", "is_official": true}],\n'
|
||||||
|
' "inconsistency_summary": "채널 간 로고 일관성 1~2문장 요약",\n'
|
||||||
|
' "recommendation": "통합 권고 1문장"\n'
|
||||||
|
"}\n"
|
||||||
|
"모든 logo_description·inconsistency_summary·recommendation은 반드시 한국어로 작성하세요 (영어 금지)."
|
||||||
|
)
|
||||||
|
return await self._ask(urls, prompt)
|
||||||
+30
-14
@@ -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,16 +81,18 @@ 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"]
|
||||||
stats = ch.get("statistics", {})
|
stats = ch.get("statistics", {})
|
||||||
snippet = ch.get("snippet", {})
|
snippet = ch.get("snippet", {})
|
||||||
|
thumbs = snippet.get("thumbnails", {})
|
||||||
return {
|
return {
|
||||||
"channelId": raw["channelId"],
|
"channelId": raw["channelId"],
|
||||||
"channelName": snippet.get("title"),
|
"channelName": snippet.get("title"),
|
||||||
|
"profileImage": (thumbs.get("high") or thumbs.get("medium") or thumbs.get("default") or {}).get("url"),
|
||||||
"handle": snippet.get("customUrl"),
|
"handle": snippet.get("customUrl"),
|
||||||
"description": snippet.get("description", ""),
|
"description": snippet.get("description", ""),
|
||||||
"publishedAt": snippet.get("publishedAt"),
|
"publishedAt": snippet.get("publishedAt"),
|
||||||
|
|||||||
@@ -0,0 +1,141 @@
|
|||||||
|
# 프론트가 아직 안 보내는 채널(틱톡/영문 인스타·페북)을 homepage로 매칭해 보충하는 임시 mock 데이터.
|
||||||
|
# 기존 mockUrls.json을 파이썬 모듈로 전환 — 런타임 파일 I/O 없이 직접 import.
|
||||||
|
|
||||||
|
MOCK_CLINICS = [
|
||||||
|
{
|
||||||
|
"label": "뷰성형외과",
|
||||||
|
"urls": {
|
||||||
|
"homepage": "viewclinic.com",
|
||||||
|
"youtube": "youtube.com/channel/UCQqqH3Klj2HQSHNNSVug-CQ",
|
||||||
|
"instagram": "instagram.com/viewplastic",
|
||||||
|
"facebook": "facebook.com/viewps1",
|
||||||
|
"naverPlace": "https://naver.me/x9BxGXkK",
|
||||||
|
"naverBlog": "blog.naver.com/viewclinicps",
|
||||||
|
"gangnamUnni": "gangnamunni.com/hospitals/189",
|
||||||
|
"tiktok": "tiktok.com/@viewplastic",
|
||||||
|
"tiktokEn": "tiktok.com/@viewplasticsurgery",
|
||||||
|
"instagramEn": "instagram.com/view_plastic_surgery",
|
||||||
|
"facebookEn": "facebook.com/viewclinic"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "바노바기 성형외과",
|
||||||
|
"urls": {
|
||||||
|
"homepage": "banobagi.com",
|
||||||
|
"youtube": "youtube.com/c/banobagips",
|
||||||
|
"instagram": "instagram.com/banobagi_ps",
|
||||||
|
"facebook": "facebook.com/BanobagiPlasticSurgery",
|
||||||
|
"naverPlace": "https://naver.me/xxY2yLr5",
|
||||||
|
"naverBlog": "blog.naver.com/banobagiprs",
|
||||||
|
"gangnamUnni": "gangnamunni.com/hospitals/23",
|
||||||
|
"tiktok": "",
|
||||||
|
"instagramEn": "instagram.com/english_banobagi",
|
||||||
|
"facebookEn": "facebook.com/englishbanobagi"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "ID 성형외과",
|
||||||
|
"urls": {
|
||||||
|
"homepage": "idhospital.com",
|
||||||
|
"youtube": "youtube.com/user/IDhospital",
|
||||||
|
"instagram": "instagram.com/idhospital",
|
||||||
|
"facebook": "facebook.com/idhospital0050",
|
||||||
|
"naverPlace": "https://naver.me/GtURpCEn",
|
||||||
|
"naverBlog": "",
|
||||||
|
"gangnamUnni": "gangnamunni.com/hospitals/257",
|
||||||
|
"tiktok": "tiktok.com/@idhospitalkorea",
|
||||||
|
"instagramEn": "instagram.com/idhospitalkorea",
|
||||||
|
"facebookEn": "facebook.com/idhospital.eng"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "JK 성형외과",
|
||||||
|
"urls": {
|
||||||
|
"homepage": "jkplastic.com",
|
||||||
|
"youtube": "youtube.com/channel/UC5F8dEt32hdp3cTeFyls4qg",
|
||||||
|
"instagram": "instagram.com/jkplasticsurgery_kr",
|
||||||
|
"facebook": "facebook.com/jkmedicalgroup",
|
||||||
|
"naverPlace": "https://naver.me/x67y6cAc",
|
||||||
|
"naverBlog": "blog.naver.com/jkstory1",
|
||||||
|
"gangnamUnni": "gangnamunni.com/hospitals/858",
|
||||||
|
"tiktok": "tiktok.com/@jkplastic",
|
||||||
|
"instagramEn": "instagram.com/jkplasticsurgery",
|
||||||
|
"facebookEn": "facebook.com/jkplastic"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "그랜드 성형외과",
|
||||||
|
"urls": {
|
||||||
|
"homepage": "grandsurgery.com",
|
||||||
|
"youtube": "youtube.com/channel/UCU2o_aHqsNFuqwtdzVM3xbQ",
|
||||||
|
"instagram": "instagram.com/grand_korea",
|
||||||
|
"facebook": "facebook.com/grandps.korea",
|
||||||
|
"naverPlace": "https://naver.me/Fw7MYKWK",
|
||||||
|
"naverBlog": "blog.naver.com/grandprs",
|
||||||
|
"gangnamUnni": "gangnamunni.com/hospitals/62",
|
||||||
|
"tiktok": "",
|
||||||
|
"instagramEn": "instagram.com/grandps_eng",
|
||||||
|
"facebookEn": "facebook.com/grandplasticsurgery"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "BK 성형외과",
|
||||||
|
"urls": {
|
||||||
|
"homepage": "bkhospital.com",
|
||||||
|
"youtube": "youtube.com/channel/UChJONft3hemy5DGbXUveTFg",
|
||||||
|
"instagram": "instagram.com/bkhospital_korea",
|
||||||
|
"facebook": "",
|
||||||
|
"naverPlace": "https://naver.me/517CTH3W",
|
||||||
|
"naverBlog": "",
|
||||||
|
"gangnamUnni": "",
|
||||||
|
"tiktok": "",
|
||||||
|
"instagramEn": "instagram.com/english_bkhospital",
|
||||||
|
"facebookEn": "facebook.com/BKPSKoreaE"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "톡스앤필",
|
||||||
|
"urls": {
|
||||||
|
"homepage": "toxnfill.com",
|
||||||
|
"youtube": "youtube.com/channel/UCFpFZkm7mclD-z_-j7FTUag",
|
||||||
|
"instagram": "instagram.com/toxnfill_official",
|
||||||
|
"facebook": "facebook.com/toxnfill.official",
|
||||||
|
"naverPlace": "https://naver.me/FvEmJIHA",
|
||||||
|
"naverBlog": "blog.naver.com/toxnfill",
|
||||||
|
"gangnamUnni": "gangnamunni.com/hospitals/3702",
|
||||||
|
"tiktok": "tiktok.com/@toxnfillglobal",
|
||||||
|
"instagramEn": "instagram.com/toxnfill_global",
|
||||||
|
"facebookEn": "facebook.com/p/Toxnfill-Global-61557593068252"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "더 압구정 성형외과",
|
||||||
|
"urls": {
|
||||||
|
"homepage": "theclinic.co.kr",
|
||||||
|
"youtube": "youtube.com/user/theplasticsurgery1",
|
||||||
|
"instagram": "instagram.com/the_plasticsurgery",
|
||||||
|
"facebook": "facebook.com/THEPS16445998",
|
||||||
|
"naverPlace": "",
|
||||||
|
"naverBlog": "blog.naver.com/with_theps",
|
||||||
|
"gangnamUnni": "gangnamunni.com/hospitals/30",
|
||||||
|
"tiktok": "",
|
||||||
|
"instagramEn": "instagram.com/the_plasticsurgery.en",
|
||||||
|
"facebookEn": "facebook.com/theps.english"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "오라클 성형외과",
|
||||||
|
"urls": {
|
||||||
|
"homepage": "oracleclinic.com",
|
||||||
|
"youtube": "youtube.com/@oracle_medical_group",
|
||||||
|
"instagram": "instagram.com/oraclemedicalgroup",
|
||||||
|
"facebook": "facebook.com/oracleclinickr",
|
||||||
|
"naverPlace": "https://naver.me/GhbU3VtK",
|
||||||
|
"naverBlog": "",
|
||||||
|
"gangnamUnni": "gangnamunni.com/hospitals/125",
|
||||||
|
"tiktok": "tiktok.com/@oracleclinic_usa",
|
||||||
|
"instagramEn": "instagram.com/oracleclinic_global",
|
||||||
|
"facebookEn": "facebook.com/oracleclinicglobal"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
@@ -8,6 +8,9 @@ class Channels(BaseModel):
|
|||||||
facebook: str | None = None
|
facebook: str | None = None
|
||||||
naver_blog: str | None = None
|
naver_blog: str | None = None
|
||||||
gangnam_unni: str | None = None
|
gangnam_unni: str | None = None
|
||||||
|
tiktok: str | None = None
|
||||||
|
instagram_en: str | None = None
|
||||||
|
facebook_en: str | None = None
|
||||||
|
|
||||||
|
|
||||||
class AnalysisOptions(BaseModel):
|
class AnalysisOptions(BaseModel):
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
from pydantic import BaseModel, ConfigDict
|
||||||
|
|
||||||
|
|
||||||
|
def _to_camel(s: str) -> str:
|
||||||
|
head, *tail = s.split("_")
|
||||||
|
return head + "".join(w.capitalize() for w in tail)
|
||||||
|
|
||||||
|
|
||||||
|
class CamelModel(BaseModel):
|
||||||
|
model_config = ConfigDict(populate_by_name=True, alias_generator=_to_camel)
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
from enum import Enum
|
||||||
|
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
|
||||||
|
class FileType(str, Enum):
|
||||||
|
IMAGE = "image"
|
||||||
|
VIDEO = "video"
|
||||||
|
AUDIO = "audio"
|
||||||
|
DOCUMENT = "document"
|
||||||
|
FILE = "file"
|
||||||
|
|
||||||
|
|
||||||
|
class FileUploadResponse(BaseModel):
|
||||||
|
id: int
|
||||||
|
analysis_run_id: str
|
||||||
|
file_type: FileType
|
||||||
|
file_name: str
|
||||||
|
file_url: str
|
||||||
|
size_bytes: int | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class FileListItem(BaseModel):
|
||||||
|
id: int
|
||||||
|
file_type: FileType
|
||||||
|
file_name: str
|
||||||
|
file_url: str
|
||||||
|
size_bytes: int | None = None
|
||||||
|
created_at: str
|
||||||
+194
-10
@@ -1,16 +1,200 @@
|
|||||||
from pydantic import BaseModel
|
from typing import Literal
|
||||||
|
from models.common import CamelModel
|
||||||
|
|
||||||
|
|
||||||
class PlanCreate(BaseModel):
|
class BrandPlanInconsistencyValue(CamelModel):
|
||||||
report_id: str
|
channel: str
|
||||||
regenerate: bool = False
|
value: str
|
||||||
|
is_correct: bool
|
||||||
|
|
||||||
|
|
||||||
class PlanResponse(BaseModel):
|
class BrandPlanInconsistency(CamelModel):
|
||||||
|
field: str
|
||||||
|
values: list[BrandPlanInconsistencyValue]
|
||||||
|
impact: str
|
||||||
|
recommendation: str
|
||||||
|
|
||||||
|
|
||||||
|
# --- BrandGuide ---
|
||||||
|
|
||||||
|
class ColorSwatch(CamelModel):
|
||||||
|
name: str
|
||||||
|
hex: str
|
||||||
|
usage: str
|
||||||
|
|
||||||
|
|
||||||
|
class FontSpec(CamelModel):
|
||||||
|
family: str
|
||||||
|
weight: str
|
||||||
|
usage: str
|
||||||
|
sample_text: str
|
||||||
|
|
||||||
|
|
||||||
|
class LogoUsageRule(CamelModel):
|
||||||
|
rule: str
|
||||||
|
description: str
|
||||||
|
correct: bool
|
||||||
|
|
||||||
|
|
||||||
|
class ToneOfVoice(CamelModel):
|
||||||
|
personality: list[str]
|
||||||
|
communication_style: str
|
||||||
|
do_examples: list[str]
|
||||||
|
dont_examples: list[str]
|
||||||
|
|
||||||
|
|
||||||
|
class ChannelBrandingRule(CamelModel):
|
||||||
|
channel: str
|
||||||
|
icon: str
|
||||||
|
profile_photo: str
|
||||||
|
banner_spec: str
|
||||||
|
bio_template: str
|
||||||
|
current_status: Literal["correct", "incorrect", "missing"]
|
||||||
|
|
||||||
|
|
||||||
|
class BrandGuide(CamelModel):
|
||||||
|
colors: list[ColorSwatch]
|
||||||
|
fonts: list[FontSpec]
|
||||||
|
logo_rules: list[LogoUsageRule]
|
||||||
|
tone_of_voice: ToneOfVoice
|
||||||
|
channel_branding: list[ChannelBrandingRule]
|
||||||
|
brand_inconsistencies: list[BrandPlanInconsistency]
|
||||||
|
|
||||||
|
|
||||||
|
# --- ChannelStrategy ---
|
||||||
|
|
||||||
|
class ChannelStrategyCard(CamelModel):
|
||||||
|
channel_id: str
|
||||||
|
channel_name: str
|
||||||
|
icon: str
|
||||||
|
current_status: str
|
||||||
|
target_goal: str
|
||||||
|
content_types: list[str]
|
||||||
|
posting_frequency: str
|
||||||
|
tone: str
|
||||||
|
format_guidelines: list[str]
|
||||||
|
priority: Literal["P0", "P1", "P2"]
|
||||||
|
customer_journey_stage: Literal["awareness", "interest", "consideration", "conversion", "loyalty"] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
# --- ContentStrategy ---
|
||||||
|
|
||||||
|
class ContentPillar(CamelModel):
|
||||||
|
title: str
|
||||||
|
description: str
|
||||||
|
related_usp: str
|
||||||
|
example_topics: list[str]
|
||||||
|
color: str
|
||||||
|
|
||||||
|
|
||||||
|
class ContentTypeRow(CamelModel):
|
||||||
|
format: str
|
||||||
|
channels: list[str]
|
||||||
|
frequency: str
|
||||||
|
purpose: str
|
||||||
|
|
||||||
|
|
||||||
|
class WorkflowStep(CamelModel):
|
||||||
|
step: int
|
||||||
|
name: str
|
||||||
|
description: str
|
||||||
|
owner: str
|
||||||
|
duration: str
|
||||||
|
|
||||||
|
|
||||||
|
class RepurposingOutput(CamelModel):
|
||||||
|
format: str
|
||||||
|
channel: str
|
||||||
|
description: str
|
||||||
|
|
||||||
|
|
||||||
|
class ContentStrategyData(CamelModel):
|
||||||
|
pillars: list[ContentPillar]
|
||||||
|
type_matrix: list[ContentTypeRow]
|
||||||
|
workflow: list[WorkflowStep]
|
||||||
|
repurposing_source: str
|
||||||
|
repurposing_outputs: list[RepurposingOutput]
|
||||||
|
|
||||||
|
|
||||||
|
# --- Calendar ---
|
||||||
|
|
||||||
|
class CalendarEntry(CamelModel):
|
||||||
|
day_of_week: int
|
||||||
|
channel: str
|
||||||
|
channel_icon: str
|
||||||
|
content_type: Literal["video", "blog", "social", "ad"]
|
||||||
|
title: str
|
||||||
|
id: str | None = None
|
||||||
|
description: str | None = None
|
||||||
|
pillar: str | None = None
|
||||||
|
status: Literal["draft", "approved", "published"] | None = None
|
||||||
|
is_manual_edit: bool | None = None
|
||||||
|
ai_prompt_seed: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class CalendarWeek(CamelModel):
|
||||||
|
week_number: int
|
||||||
|
label: str
|
||||||
|
entries: list[CalendarEntry]
|
||||||
|
|
||||||
|
|
||||||
|
class ContentCountSummary(CamelModel):
|
||||||
|
type: Literal["video", "blog", "social", "ad"]
|
||||||
|
label: str
|
||||||
|
count: int
|
||||||
|
color: str
|
||||||
|
|
||||||
|
|
||||||
|
class CalendarData(CamelModel):
|
||||||
|
weeks: list[CalendarWeek]
|
||||||
|
monthly_summary: list[ContentCountSummary]
|
||||||
|
|
||||||
|
|
||||||
|
# --- AssetCollection ---
|
||||||
|
|
||||||
|
class AssetCard(CamelModel):
|
||||||
id: str
|
id: str
|
||||||
analysis_run_id: str
|
source: Literal["homepage", "naver_place", "blog", "social", "youtube"]
|
||||||
brand_guide: dict
|
source_label: str
|
||||||
channel_strategies: list
|
type: Literal["photo", "video", "text"]
|
||||||
content_strategy: dict
|
title: str
|
||||||
calendar: list
|
description: str
|
||||||
|
repurposing_suggestions: list[str]
|
||||||
|
status: Literal["collected", "pending", "needs_creation"]
|
||||||
|
|
||||||
|
|
||||||
|
class YouTubeRepurposeItem(CamelModel):
|
||||||
|
title: str
|
||||||
|
views: int
|
||||||
|
type: Literal["Short", "Long"]
|
||||||
|
repurpose_as: list[str]
|
||||||
|
|
||||||
|
|
||||||
|
class AssetCollectionData(CamelModel):
|
||||||
|
assets: list[AssetCard]
|
||||||
|
youtube_repurpose: list[YouTubeRepurposeItem]
|
||||||
|
|
||||||
|
|
||||||
|
# --- Repurposing ---
|
||||||
|
|
||||||
|
class RepurposingProposalItem(CamelModel):
|
||||||
|
source_video: YouTubeRepurposeItem
|
||||||
|
outputs: list[RepurposingOutput]
|
||||||
|
estimated_effort: Literal["low", "medium", "high"]
|
||||||
|
priority: Literal["high", "medium", "low"]
|
||||||
|
|
||||||
|
|
||||||
|
# --- PlanApiResponse ---
|
||||||
|
|
||||||
|
class PlanApiResponse(CamelModel):
|
||||||
|
id: str
|
||||||
|
clinic_name: str | None = None
|
||||||
|
clinic_name_en: str | None = None
|
||||||
created_at: str
|
created_at: str
|
||||||
|
target_url: str
|
||||||
|
brand_guide: BrandGuide
|
||||||
|
channel_strategies: list[ChannelStrategyCard]
|
||||||
|
content_strategy: ContentStrategyData
|
||||||
|
calendar: CalendarData
|
||||||
|
asset_collection: AssetCollectionData
|
||||||
|
repurposing_proposals: list[RepurposingProposalItem] | None = None
|
||||||
+299
-14
@@ -1,22 +1,307 @@
|
|||||||
from pydantic import BaseModel
|
from __future__ import annotations
|
||||||
|
from models.common import CamelModel
|
||||||
|
from models.status import Severity, ChannelStatus, DataSource, Language, VideoType, AnnotationType
|
||||||
|
|
||||||
|
|
||||||
class ClinicInfo(BaseModel):
|
class ScreenshotAnnotation(CamelModel):
|
||||||
|
type: AnnotationType
|
||||||
|
x: float
|
||||||
|
y: float
|
||||||
|
width: float | None = None
|
||||||
|
height: float | None = None
|
||||||
|
label: str | None = None
|
||||||
|
color: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class ScreenshotEvidence(CamelModel):
|
||||||
|
id: str
|
||||||
|
url: str
|
||||||
|
channel: str
|
||||||
|
captured_at: str
|
||||||
|
caption: str
|
||||||
|
source_url: str | None = None
|
||||||
|
annotations: list[ScreenshotAnnotation] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class DiagnosisItem(CamelModel):
|
||||||
|
category: str
|
||||||
|
detail: str
|
||||||
|
severity: Severity
|
||||||
|
evidence_ids: list[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class LeadDoctor(CamelModel):
|
||||||
name: str
|
name: str
|
||||||
|
credentials: str
|
||||||
|
rating: float
|
||||||
|
review_count: int
|
||||||
|
|
||||||
|
|
||||||
|
class PriceRange(CamelModel):
|
||||||
|
min: str
|
||||||
|
max: str
|
||||||
|
currency: str
|
||||||
|
|
||||||
|
|
||||||
|
class LogoImages(CamelModel):
|
||||||
|
circle: str | None = None
|
||||||
|
horizontal: str | None = None
|
||||||
|
korean: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class BrandColors(CamelModel):
|
||||||
|
primary: str
|
||||||
|
accent: str
|
||||||
|
text: str
|
||||||
|
|
||||||
|
|
||||||
|
class RegistryData(CamelModel):
|
||||||
|
district: str | None = None
|
||||||
|
branches: str | None = None
|
||||||
|
brand_group: str | None = None
|
||||||
|
website_en: str | None = None
|
||||||
|
naver_place_url: str | None = None
|
||||||
|
gangnam_unni_url: str | None = None
|
||||||
|
google_maps_url: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class ClinicSnapshot(CamelModel):
|
||||||
|
name: str
|
||||||
|
name_en: str
|
||||||
|
established: str
|
||||||
|
years_in_business: int
|
||||||
|
staff_count: int
|
||||||
|
lead_doctor: LeadDoctor
|
||||||
|
overall_rating: float
|
||||||
|
total_reviews: int
|
||||||
|
price_range: PriceRange
|
||||||
|
certifications: list[str]
|
||||||
|
media_appearances: list[str]
|
||||||
|
medical_tourism: list[str]
|
||||||
|
location: str
|
||||||
|
nearest_station: str
|
||||||
|
phone: str
|
||||||
|
domain: str
|
||||||
|
logo_images: LogoImages | None = None
|
||||||
|
brand_colors: BrandColors | None = None
|
||||||
|
source: DataSource | None = None
|
||||||
|
registry_data: RegistryData | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class ChannelScore(CamelModel):
|
||||||
|
channel: str
|
||||||
|
icon: str
|
||||||
|
score: int
|
||||||
|
max_score: int
|
||||||
|
status: Severity
|
||||||
|
headline: str
|
||||||
|
|
||||||
|
|
||||||
|
class WeeklyViewGrowth(CamelModel):
|
||||||
|
absolute: int
|
||||||
|
percentage: float
|
||||||
|
|
||||||
|
|
||||||
|
class EstimatedRevenue(CamelModel):
|
||||||
|
min: int
|
||||||
|
max: int
|
||||||
|
|
||||||
|
|
||||||
|
class LinkedUrl(CamelModel):
|
||||||
|
label: str
|
||||||
url: str
|
url: str
|
||||||
|
|
||||||
|
|
||||||
class ReportResponse(BaseModel):
|
class TopVideo(CamelModel):
|
||||||
|
title: str
|
||||||
|
views: int
|
||||||
|
uploaded_ago: str
|
||||||
|
type: VideoType
|
||||||
|
duration: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class YouTubeAudit(CamelModel):
|
||||||
|
channel_name: str
|
||||||
|
handle: str
|
||||||
|
subscribers: int
|
||||||
|
total_videos: int
|
||||||
|
total_views: int
|
||||||
|
weekly_view_growth: WeeklyViewGrowth
|
||||||
|
estimated_monthly_revenue: EstimatedRevenue
|
||||||
|
avg_video_length: str
|
||||||
|
upload_frequency: str
|
||||||
|
channel_created_date: str
|
||||||
|
subscriber_rank: str
|
||||||
|
channel_description: str
|
||||||
|
linked_urls: list[LinkedUrl]
|
||||||
|
playlists: list[str]
|
||||||
|
top_videos: list[TopVideo]
|
||||||
|
diagnosis: list[DiagnosisItem]
|
||||||
|
|
||||||
|
|
||||||
|
class InstagramAccount(CamelModel):
|
||||||
|
handle: str
|
||||||
|
language: Language
|
||||||
|
label: str
|
||||||
|
posts: int
|
||||||
|
followers: int
|
||||||
|
following: int
|
||||||
|
category: str
|
||||||
|
profile_link: str
|
||||||
|
highlights: list[str]
|
||||||
|
reels_count: int
|
||||||
|
content_format: str
|
||||||
|
profile_photo: str
|
||||||
|
bio: str
|
||||||
|
|
||||||
|
|
||||||
|
class InstagramAudit(CamelModel):
|
||||||
|
accounts: list[InstagramAccount]
|
||||||
|
diagnosis: list[DiagnosisItem]
|
||||||
|
|
||||||
|
|
||||||
|
class BrandInconsistencyValue(CamelModel):
|
||||||
|
channel: str
|
||||||
|
value: str
|
||||||
|
is_correct: bool
|
||||||
|
|
||||||
|
|
||||||
|
class BrandInconsistency(CamelModel):
|
||||||
|
field: str
|
||||||
|
values: list[BrandInconsistencyValue]
|
||||||
|
impact: str
|
||||||
|
recommendation: str
|
||||||
|
|
||||||
|
|
||||||
|
class FacebookPage(CamelModel):
|
||||||
|
url: str
|
||||||
|
page_name: str
|
||||||
|
language: Language
|
||||||
|
label: str
|
||||||
|
followers: int
|
||||||
|
following: int
|
||||||
|
category: str
|
||||||
|
bio: str
|
||||||
|
logo: str
|
||||||
|
logo_description: str
|
||||||
|
link: str
|
||||||
|
linked_domain: str
|
||||||
|
reviews: int
|
||||||
|
recent_post_age: str
|
||||||
|
has_whatsapp: bool
|
||||||
|
post_frequency: str | None = None
|
||||||
|
top_content_type: str | None = None
|
||||||
|
engagement: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class FacebookAudit(CamelModel):
|
||||||
|
pages: list[FacebookPage]
|
||||||
|
diagnosis: list[DiagnosisItem]
|
||||||
|
brand_inconsistencies: list[BrandInconsistency]
|
||||||
|
consolidation_recommendation: str
|
||||||
|
|
||||||
|
|
||||||
|
class OtherChannel(CamelModel):
|
||||||
|
name: str
|
||||||
|
status: ChannelStatus
|
||||||
|
details: str
|
||||||
|
url: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class TrackingPixel(CamelModel):
|
||||||
|
name: str
|
||||||
|
installed: bool
|
||||||
|
details: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class SnsLink(CamelModel):
|
||||||
|
platform: str
|
||||||
|
url: str
|
||||||
|
location: str
|
||||||
|
|
||||||
|
|
||||||
|
class AdditionalDomain(CamelModel):
|
||||||
|
domain: str
|
||||||
|
purpose: str
|
||||||
|
|
||||||
|
|
||||||
|
class WebsiteAudit(CamelModel):
|
||||||
|
primary_domain: str
|
||||||
|
additional_domains: list[AdditionalDomain]
|
||||||
|
sns_links_on_site: bool
|
||||||
|
sns_links_detail: list[SnsLink] | None = None
|
||||||
|
tracking_pixels: list[TrackingPixel]
|
||||||
|
main_cta: str
|
||||||
|
|
||||||
|
|
||||||
|
class AsIsToBeItem(CamelModel):
|
||||||
|
area: str
|
||||||
|
as_is: str
|
||||||
|
to_be: str
|
||||||
|
|
||||||
|
|
||||||
|
class StrategyDetail(CamelModel):
|
||||||
|
strategy: str
|
||||||
|
detail: str
|
||||||
|
|
||||||
|
|
||||||
|
class PlatformStrategy(CamelModel):
|
||||||
|
platform: str
|
||||||
|
icon: str
|
||||||
|
current_metric: str
|
||||||
|
target_metric: str
|
||||||
|
strategies: list[StrategyDetail]
|
||||||
|
|
||||||
|
|
||||||
|
class NewChannelProposal(CamelModel):
|
||||||
|
channel: str
|
||||||
|
priority: str
|
||||||
|
rationale: str
|
||||||
|
|
||||||
|
|
||||||
|
class TransformationProposal(CamelModel):
|
||||||
|
brand_identity: list[AsIsToBeItem]
|
||||||
|
content_strategy: list[AsIsToBeItem]
|
||||||
|
platform_strategies: list[PlatformStrategy]
|
||||||
|
website_improvements: list[AsIsToBeItem]
|
||||||
|
new_channel_proposals: list[NewChannelProposal]
|
||||||
|
|
||||||
|
|
||||||
|
class RoadmapTask(CamelModel):
|
||||||
|
task: str
|
||||||
|
completed: bool
|
||||||
|
|
||||||
|
|
||||||
|
class RoadmapMonth(CamelModel):
|
||||||
|
month: int
|
||||||
|
title: str
|
||||||
|
subtitle: str
|
||||||
|
tasks: list[RoadmapTask]
|
||||||
|
|
||||||
|
|
||||||
|
class KPIMetric(CamelModel):
|
||||||
|
metric: str
|
||||||
|
current: str
|
||||||
|
target_3_month: str
|
||||||
|
target_12_month: str
|
||||||
|
|
||||||
|
|
||||||
|
class MarketingReportResponse(CamelModel):
|
||||||
id: str
|
id: str
|
||||||
clinic: ClinicInfo
|
clinic_name: str | None = None
|
||||||
|
clinic_name_en: str | None = None
|
||||||
|
created_at: str
|
||||||
|
target_url: str
|
||||||
overall_score: int
|
overall_score: int
|
||||||
youtube: dict
|
clinic_snapshot: ClinicSnapshot
|
||||||
instagram: dict
|
channel_scores: list[ChannelScore]
|
||||||
facebook: dict
|
youtube_audit: YouTubeAudit
|
||||||
naver_place: dict
|
instagram_audit: InstagramAudit
|
||||||
naver_blog: dict
|
facebook_audit: FacebookAudit
|
||||||
gangnam_unni: dict
|
other_channels: list[OtherChannel]
|
||||||
conversion_strategy: dict
|
website_audit: WebsiteAudit
|
||||||
roadmap: list
|
problem_diagnosis: list[DiagnosisItem]
|
||||||
kpis: list
|
transformation: TransformationProposal
|
||||||
generated_at: str
|
roadmap: list[RoadmapMonth]
|
||||||
|
kpi_dashboard: list[KPIMetric]
|
||||||
|
screenshots: list[ScreenshotEvidence] | None = None
|
||||||
@@ -14,3 +14,39 @@ class TaskStatus(StrEnum):
|
|||||||
START = "start"
|
START = "start"
|
||||||
PROCESSING = "processing"
|
PROCESSING = "processing"
|
||||||
DONE = "done"
|
DONE = "done"
|
||||||
|
|
||||||
|
|
||||||
|
class Severity(StrEnum):
|
||||||
|
CRITICAL = "critical"
|
||||||
|
WARNING = "warning"
|
||||||
|
GOOD = "good"
|
||||||
|
EXCELLENT = "excellent"
|
||||||
|
UNKNOWN = "unknown"
|
||||||
|
|
||||||
|
|
||||||
|
class ChannelStatus(StrEnum):
|
||||||
|
ACTIVE = "active"
|
||||||
|
INACTIVE = "inactive"
|
||||||
|
UNKNOWN = "unknown"
|
||||||
|
NOT_FOUND = "not_found"
|
||||||
|
|
||||||
|
|
||||||
|
class DataSource(StrEnum):
|
||||||
|
REGISTRY = "registry"
|
||||||
|
SCRAPE = "scrape"
|
||||||
|
|
||||||
|
|
||||||
|
class Language(StrEnum):
|
||||||
|
KR = "KR"
|
||||||
|
EN = "EN"
|
||||||
|
|
||||||
|
|
||||||
|
class VideoType(StrEnum):
|
||||||
|
SHORT = "Short"
|
||||||
|
LONG = "Long"
|
||||||
|
|
||||||
|
|
||||||
|
class AnnotationType(StrEnum):
|
||||||
|
HIGHLIGHT = "highlight"
|
||||||
|
ARROW = "arrow"
|
||||||
|
TEXT = "text"
|
||||||
+162
-53
@@ -1,10 +1,10 @@
|
|||||||
import asyncio
|
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
from common.db import fetchone, execute, is_done, get_analysis_raw_data, save_analysis_report
|
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
|
||||||
|
from services.instagram_audit import build_instagram_accounts
|
||||||
from integrations.llm.schemas.plan import PlanOutput
|
from integrations.llm.schemas.plan import PlanOutput
|
||||||
from models.status import AnalysisStatus
|
from models.status import AnalysisStatus
|
||||||
|
|
||||||
@@ -23,24 +23,37 @@ async def generate_report(analysis_run_id: str) -> ReportOutput:
|
|||||||
raw_data = clinic_row["raw_data"] if clinic_row else None
|
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 {})
|
clinic = json.loads(raw_data) if isinstance(raw_data, str) else (raw_data or {})
|
||||||
raw = await get_analysis_raw_data(analysis_run_id)
|
raw = await get_analysis_raw_data(analysis_run_id)
|
||||||
|
market = await get_market_analysis(analysis_run_id)
|
||||||
|
|
||||||
|
def _json(v) -> str | None:
|
||||||
|
return json.dumps(v, ensure_ascii=False) if v else None
|
||||||
|
|
||||||
input_data = {
|
input_data = {
|
||||||
"clinic_name": clinic.get("clinicName"),
|
"clinic_name": clinic.get("clinicName"),
|
||||||
"clinic_name_en": clinic.get("clinicNameEn"),
|
"clinic_name_en": clinic.get("clinicNameEn"),
|
||||||
"address": clinic.get("address"),
|
"address": clinic.get("address"),
|
||||||
"phone": clinic.get("phone"),
|
"phone": clinic.get("phone"),
|
||||||
"slogan": clinic.get("slogan"),
|
"slogan": clinic.get("slogan"),
|
||||||
"services": json.dumps(clinic.get("services", []), ensure_ascii=False),
|
"services": json.dumps(clinic.get("services", []), ensure_ascii=False),
|
||||||
"doctors": json.dumps(clinic.get("doctors", []), ensure_ascii=False),
|
"doctors": json.dumps(clinic.get("doctors", []), ensure_ascii=False),
|
||||||
|
"market_competitors": _json(market.get("competitors")),
|
||||||
|
"market_keywords": _json(market.get("keywords")),
|
||||||
|
"market_trend": _json(market.get("trend")),
|
||||||
|
"market_target_audience": _json(market.get("target_audience")),
|
||||||
|
"branding": _json(clinic.get("branding")),
|
||||||
|
"brand_assets": _json(clinic.get("brandAssets")),
|
||||||
|
"tiktok": _json(clinic.get("tiktok")),
|
||||||
|
"instagram_en": _json(clinic.get("instagramEn")),
|
||||||
|
"facebook_en": _json(clinic.get("facebookEn")),
|
||||||
|
"channel_logos": _json(clinic.get("channelLogos")),
|
||||||
**{
|
**{
|
||||||
channel: json.dumps(data, ensure_ascii=False) if data else None
|
channel: _json(data)
|
||||||
for channel, data in raw.items()
|
for channel, data in raw.items()
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
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",
|
||||||
@@ -54,58 +67,154 @@ async def generate_plan(analysis_run_id: str) -> PlanOutput:
|
|||||||
clinic = json.loads(raw_data) if isinstance(raw_data, str) else (raw_data or {})
|
clinic = json.loads(raw_data) if isinstance(raw_data, str) else (raw_data or {})
|
||||||
report_data = run["report_data"]
|
report_data = run["report_data"]
|
||||||
report = json.loads(report_data) if isinstance(report_data, str) else report_data
|
report = json.loads(report_data) if isinstance(report_data, str) else report_data
|
||||||
|
market = await get_market_analysis(analysis_run_id)
|
||||||
|
|
||||||
|
def _json(v) -> str | None:
|
||||||
|
return json.dumps(v, ensure_ascii=False) if v else None
|
||||||
|
|
||||||
input_data = {
|
input_data = {
|
||||||
"clinic_name": clinic.get("clinicName"),
|
"clinic_name": clinic.get("clinicName"),
|
||||||
"clinic_name_en": clinic.get("clinicNameEn"),
|
"clinic_name_en": clinic.get("clinicNameEn"),
|
||||||
"address": clinic.get("address"),
|
"address": clinic.get("address"),
|
||||||
"phone": clinic.get("phone"),
|
"phone": clinic.get("phone"),
|
||||||
"slogan": clinic.get("slogan"),
|
"slogan": clinic.get("slogan"),
|
||||||
"services": json.dumps(clinic.get("services", []), ensure_ascii=False),
|
"services": json.dumps(clinic.get("services", []), ensure_ascii=False),
|
||||||
"doctors": json.dumps(clinic.get("doctors", []), ensure_ascii=False),
|
"doctors": json.dumps(clinic.get("doctors", []), ensure_ascii=False),
|
||||||
"report": json.dumps(report, ensure_ascii=False) if report else None,
|
"report": _json(report),
|
||||||
|
"market_competitors": _json(market.get("competitors")),
|
||||||
|
"market_keywords": _json(market.get("keywords")),
|
||||||
|
"market_trend": _json(market.get("trend")),
|
||||||
|
"market_target_audience": _json(market.get("target_audience")),
|
||||||
|
"tiktok": _json(clinic.get("tiktok")),
|
||||||
|
"instagram_en": _json(clinic.get("instagramEn")),
|
||||||
|
"facebook_en": _json(clinic.get("facebookEn")),
|
||||||
|
"channel_logos": _json(clinic.get("channelLogos")),
|
||||||
|
"brand_assets": _json(clinic.get("brandAssets")),
|
||||||
}
|
}
|
||||||
|
|
||||||
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 (KR·EN 계정을 코드에서 구성 → LLM 출력 무시하고 교체) ──────────────
|
||||||
|
ig_patch = build_instagram_accounts(
|
||||||
|
instagram, hospital.get("instagramEn") or {}, hospital.get("channelLogos") or {},
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── 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)
|
||||||
|
# 인스타 계정은 프롬프트에서 LLM이 []로 두게 했고, 코드가 수집 데이터로 채운다 (데이터 없으면 빈 리스트)
|
||||||
|
merged.setdefault("instagram_audit", {})["accounts"] = (overrides.get("instagram_audit") or {}).get("accounts") or []
|
||||||
|
return ReportOutput(**merged)
|
||||||
|
|
||||||
|
|
||||||
|
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)
|
||||||
|
result = _patch_report(result, await _build_overrides(analysis_run_id))
|
||||||
|
await save_analysis_report(analysis_run_id, result.model_dump())
|
||||||
|
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)
|
||||||
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, status = %s WHERE analysis_run_id = %s",
|
"UPDATE analysis_runs SET plan_data = %s WHERE analysis_run_id = %s",
|
||||||
(json.dumps(result.model_dump(), ensure_ascii=False), AnalysisStatus.COMPLETED, analysis_run_id),
|
(json.dumps(result.model_dump(), ensure_ascii=False), analysis_run_id),
|
||||||
)
|
)
|
||||||
logger.info("[plan] done run=%s", 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,),
|
|
||||||
)
|
|
||||||
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))
|
|
||||||
+52
-8
@@ -1,5 +1,7 @@
|
|||||||
|
import asyncio
|
||||||
import logging
|
import logging
|
||||||
from common.db import (
|
from common.db import (
|
||||||
|
fetchone,
|
||||||
set_instagram_status, save_instagram_raw_data,
|
set_instagram_status, save_instagram_raw_data,
|
||||||
set_facebook_status, save_facebook_raw_data,
|
set_facebook_status, save_facebook_raw_data,
|
||||||
set_naver_blog_status, save_naver_blog_raw_data,
|
set_naver_blog_status, save_naver_blog_raw_data,
|
||||||
@@ -7,12 +9,12 @@ from common.db import (
|
|||||||
set_gangnam_unni_status, save_gangnam_unni_raw_data,
|
set_gangnam_unni_status, save_gangnam_unni_raw_data,
|
||||||
execute, save_hospital_raw_data,
|
execute, save_hospital_raw_data,
|
||||||
)
|
)
|
||||||
from common.utils import get_env
|
from common.utils import get_env, _run_optional_step
|
||||||
from services.analysis import check_and_advance_analysis
|
|
||||||
from integrations.apify import ApifyClient
|
from integrations.apify import ApifyClient
|
||||||
from integrations.naver import NaverClient
|
from integrations.naver import NaverClient
|
||||||
from integrations.youtube import YouTubeClient
|
from integrations.youtube import YouTubeClient
|
||||||
from integrations.firecrawl import FirecrawlClient
|
from integrations.firecrawl import FirecrawlClient
|
||||||
|
from services.enrichment import collect_brand_assets, collect_extra_channels, collect_channel_logos
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -23,7 +25,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)
|
data = await ApifyClient(get_env("APIFY_API_TOKEN")).get_instagram_profile(url)
|
||||||
await save_instagram_raw_data(row_id, data)
|
await save_instagram_raw_data(row_id, data)
|
||||||
logger.info("[instagram] done run=%s", analysis_run_id)
|
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:
|
async def collect_facebook(analysis_run_id: str, row_id: int, url: str) -> None:
|
||||||
@@ -32,7 +33,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)
|
data = await ApifyClient(get_env("APIFY_API_TOKEN")).get_facebook_page(url)
|
||||||
await save_facebook_raw_data(row_id, data)
|
await save_facebook_raw_data(row_id, data)
|
||||||
logger.info("[facebook] done run=%s", analysis_run_id)
|
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:
|
async def collect_naver_blog(analysis_run_id: str, row_id: int, url: str) -> None:
|
||||||
@@ -41,7 +41,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)
|
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)
|
await save_naver_blog_raw_data(row_id, data)
|
||||||
logger.info("[naver_blog] done run=%s", analysis_run_id)
|
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:
|
async def collect_youtube(analysis_run_id: str, row_id: int, url: str) -> None:
|
||||||
@@ -50,7 +49,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)
|
data = await YouTubeClient(get_env("YOUTUBE_API_KEY")).get_channel(url)
|
||||||
await save_youtube_raw_data(row_id, data)
|
await save_youtube_raw_data(row_id, data)
|
||||||
logger.info("[youtube] done run=%s", analysis_run_id)
|
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:
|
async def collect_gangnam_unni(analysis_run_id: str, row_id: int, url: str) -> None:
|
||||||
@@ -59,7 +57,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)
|
data = await FirecrawlClient(get_env("FIRECRAWL_API_KEY")).get_gangnam_unni(url)
|
||||||
await save_gangnam_unni_raw_data(row_id, data)
|
await save_gangnam_unni_raw_data(row_id, data)
|
||||||
logger.info("[gangnam_unni] done run=%s", analysis_run_id)
|
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:
|
async def collect_clinic_info(analysis_run_id: str, hospital_id: str, url: str) -> None:
|
||||||
@@ -68,4 +65,51 @@ 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)
|
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)
|
await save_hospital_raw_data(hospital_id, data, analysis_run_id=analysis_run_id)
|
||||||
logger.info("[clinic] done run=%s", 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,
|
||||||
|
tiktok_url: str | None = None,
|
||||||
|
instagram_en_url: str | None = None,
|
||||||
|
facebook_en_url: str | 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)
|
||||||
|
|
||||||
|
# 아래 3단계는 모두 hospital raw_data를 read-modify-write 하므로 race 방지 위해 순차.
|
||||||
|
# brand_assets : clinic_info가 채운 branding.logoUrl로 공식 로고/hex 추출
|
||||||
|
# extra_channels: 틱톡/인스타EN/페북EN 수집
|
||||||
|
# channel_logos : 공식 로고(brand_assets)+채널 profileImage(extra_channels) 채워진 뒤 Vision 비교
|
||||||
|
# 부가 기능이라 실패해도 리포트는 나와야 하므로 _run_optional_step으로 각각 격리.
|
||||||
|
await _run_optional_step(collect_brand_assets(analysis_run_id, hospital_id), "brand_assets")
|
||||||
|
await _run_optional_step(
|
||||||
|
collect_extra_channels(
|
||||||
|
analysis_run_id, hospital_id,
|
||||||
|
tiktok_url=tiktok_url, instagram_en_url=instagram_en_url, facebook_en_url=facebook_en_url,
|
||||||
|
),
|
||||||
|
"extra_channels",
|
||||||
|
)
|
||||||
|
await _run_optional_step(collect_channel_logos(analysis_run_id, hospital_id), "channel_logos")
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
from common.db import fetchone, fetch_raw, merge_hospital_raw_data
|
||||||
|
from common.utils import get_env
|
||||||
|
from integrations.apify import ApifyClient
|
||||||
|
from integrations.vision import VisionClient
|
||||||
|
from integrations.color_extractor import extract_brand_assets_from_site
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
async def collect_brand_assets(analysis_run_id: str, hospital_id: str) -> None:
|
||||||
|
"""홈페이지에서 로고 URL + brand hex 색상을 뽑아 raw_data["brandAssets"]에 저장.
|
||||||
|
- 로고 URL/hex: HTML·CSS 정규식 (color_extractor) — Vision 의존 X, 사이트 전체 컬러 시스템이 더 정확.
|
||||||
|
- 로고 정성 묘사(심볼/워드마크/톤): Gemini Vision (GEMINI_API_KEY 없으면 색상만 저장하고 skip).
|
||||||
|
"""
|
||||||
|
logger.info("[brand_assets] start run=%s", analysis_run_id)
|
||||||
|
row = await fetchone(
|
||||||
|
"SELECT raw_data, url FROM hospital_baseinfo WHERE hospital_id = %s",
|
||||||
|
(hospital_id,),
|
||||||
|
)
|
||||||
|
if not row:
|
||||||
|
return
|
||||||
|
raw = row["raw_data"]
|
||||||
|
raw_data = json.loads(raw) if isinstance(raw, str) else (raw or {})
|
||||||
|
branding = raw_data.get("branding") or {}
|
||||||
|
homepage_url = row["url"]
|
||||||
|
|
||||||
|
# 0~1. 사이트 1회 fetch로 logo URL + brand hex 동시 추출 (img/background-image/CSS .logo, Vision 의존 X)
|
||||||
|
site = await extract_brand_assets_from_site(homepage_url) if homepage_url else {}
|
||||||
|
html_logo_url = site.get("logo_url")
|
||||||
|
css_colors = site.get("colors") or {}
|
||||||
|
if html_logo_url:
|
||||||
|
logger.info("[brand_assets] HTML logo found: %s", html_logo_url)
|
||||||
|
if css_colors:
|
||||||
|
logger.info("[brand_assets] css colors: %s", css_colors.get("brand_colors"))
|
||||||
|
|
||||||
|
# 2. 로고/대표 이미지 후보 (logo → og:image → favicon 순)
|
||||||
|
logo_url = html_logo_url or branding.get("logoUrl")
|
||||||
|
og_image = branding.get("ogImage")
|
||||||
|
favicon = branding.get("faviconUrl")
|
||||||
|
candidates: list[tuple[str, str]] = []
|
||||||
|
if logo_url: candidates.append(("logo", logo_url))
|
||||||
|
if og_image: candidates.append(("og", og_image))
|
||||||
|
if favicon: candidates.append(("favicon", favicon))
|
||||||
|
if homepage_url:
|
||||||
|
parsed = urlparse(homepage_url)
|
||||||
|
if parsed.scheme and parsed.netloc:
|
||||||
|
candidates.append(("favicon", f"{parsed.scheme}://{parsed.netloc}/favicon.ico"))
|
||||||
|
|
||||||
|
if not candidates and not css_colors:
|
||||||
|
logger.info("[brand_assets] skip — no logo/og/favicon candidates and no CSS colors")
|
||||||
|
return
|
||||||
|
|
||||||
|
# 3. Vision은 로고 정성 묘사만 (hex는 CSS 추출이 더 정확). 키 없으면 색상만 저장.
|
||||||
|
result: dict = {}
|
||||||
|
used_kind: str | None = None
|
||||||
|
api_key = os.getenv("GEMINI_API_KEY")
|
||||||
|
if api_key and candidates:
|
||||||
|
vc = VisionClient(api_key)
|
||||||
|
for kind, cand in candidates:
|
||||||
|
result = await vc.analyze_brand_assets(logo_url=cand, homepage_url=homepage_url)
|
||||||
|
if result:
|
||||||
|
used_kind = kind
|
||||||
|
break
|
||||||
|
# favicon으로만 분석된 경우 진짜 로고가 아니므로 logo URL은 박지 않음 (묘사는 OK)
|
||||||
|
if result and used_kind == "favicon" and result.get("logo_images"):
|
||||||
|
result["logo_images"] = {"circle": None, "horizontal": None, "korean": None}
|
||||||
|
elif not api_key:
|
||||||
|
logger.info("[brand_assets] GEMINI_API_KEY not set — 색상만 저장, Vision 묘사 skip")
|
||||||
|
|
||||||
|
# 4. CSS에서 추출한 brand_colors/palette를 Vision보다 우선 사용
|
||||||
|
if css_colors:
|
||||||
|
if css_colors.get("brand_colors"):
|
||||||
|
result["brand_colors"] = css_colors["brand_colors"]
|
||||||
|
if css_colors.get("color_palette"):
|
||||||
|
result["color_palette"] = css_colors["color_palette"]
|
||||||
|
result["color_source"] = "html+css"
|
||||||
|
elif result:
|
||||||
|
result["color_source"] = "vision"
|
||||||
|
|
||||||
|
if result:
|
||||||
|
result["logo_source"] = used_kind or "none"
|
||||||
|
await merge_hospital_raw_data(hospital_id, {"brandAssets": result})
|
||||||
|
logger.info("[brand_assets] done keys=%s", list(result.keys()) if result else None)
|
||||||
|
|
||||||
|
|
||||||
|
async def collect_extra_channels(
|
||||||
|
analysis_run_id: str,
|
||||||
|
hospital_id: str,
|
||||||
|
tiktok_url: str | None = None,
|
||||||
|
instagram_en_url: str | None = None,
|
||||||
|
facebook_en_url: str | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""틱톡 / 인스타 EN / 페북 EN 수집 → hospital raw_data에 저장 (별도 테이블 없이).
|
||||||
|
인스타EN·페북EN은 기존 Apify 수집기 재사용, 틱톡은 신규 액터."""
|
||||||
|
apify = ApifyClient(get_env("APIFY_API_TOKEN"))
|
||||||
|
jobs: dict = {}
|
||||||
|
if instagram_en_url:
|
||||||
|
jobs["instagramEn"] = apify.get_instagram_profile(instagram_en_url)
|
||||||
|
if facebook_en_url:
|
||||||
|
jobs["facebookEn"] = apify.get_facebook_page(facebook_en_url)
|
||||||
|
if tiktok_url:
|
||||||
|
jobs["tiktok"] = apify.get_tiktok_profile(tiktok_url)
|
||||||
|
if not jobs:
|
||||||
|
return
|
||||||
|
|
||||||
|
logger.info("[extra_channels] start run=%s channels=%s", analysis_run_id, list(jobs))
|
||||||
|
done = await asyncio.gather(*jobs.values(), return_exceptions=True)
|
||||||
|
results: dict = {}
|
||||||
|
for key, res in zip(jobs.keys(), done):
|
||||||
|
if isinstance(res, Exception):
|
||||||
|
logger.warning("[extra_channels] %s 수집 실패: %s", key, res)
|
||||||
|
elif res:
|
||||||
|
results[key] = res
|
||||||
|
if not results:
|
||||||
|
logger.info("[extra_channels] 수집 결과 없음 run=%s", analysis_run_id)
|
||||||
|
return
|
||||||
|
|
||||||
|
await merge_hospital_raw_data(hospital_id, results)
|
||||||
|
logger.info("[extra_channels] done run=%s keys=%s", analysis_run_id, list(results))
|
||||||
|
|
||||||
|
|
||||||
|
async def collect_channel_logos(analysis_run_id: str, hospital_id: str) -> None:
|
||||||
|
"""채널별 프로필 이미지(로고)를 모아 Gemini Vision으로 설명 + 공식 로고 일치 여부 평가.
|
||||||
|
→ hospital raw_data["channelLogos"]에 저장. GEMINI_API_KEY 없으면 skip.
|
||||||
|
brand_assets(공식 로고)·extra_channels(틱톡/EN profileImage) 다음에 실행돼야 함."""
|
||||||
|
api_key = os.getenv("GEMINI_API_KEY")
|
||||||
|
if not api_key:
|
||||||
|
logger.info("[channel_logos] skip — GEMINI_API_KEY 없음")
|
||||||
|
return
|
||||||
|
|
||||||
|
hrow = await fetchone("SELECT raw_data FROM hospital_baseinfo WHERE hospital_id = %s", (hospital_id,))
|
||||||
|
raw = hrow["raw_data"] if hrow else None
|
||||||
|
raw_data = json.loads(raw) if isinstance(raw, str) else (raw or {})
|
||||||
|
official = ((raw_data.get("brandAssets") or {}).get("logo_images") or {}).get("horizontal")
|
||||||
|
|
||||||
|
run = await fetchone(
|
||||||
|
"SELECT instagram_data_id, facebook_data_id, youtube_data_id"
|
||||||
|
" FROM analysis_runs WHERE analysis_run_id = %s",
|
||||||
|
(analysis_run_id,),
|
||||||
|
)
|
||||||
|
logos: list[dict] = []
|
||||||
|
# 전용 테이블 채널 (KR)
|
||||||
|
for ch, table, col in [
|
||||||
|
("Instagram", "instagram_data", "instagram_data_id"),
|
||||||
|
("Facebook", "facebook_data", "facebook_data_id"),
|
||||||
|
("YouTube", "youtube_data", "youtube_data_id"),
|
||||||
|
]:
|
||||||
|
rid = (run or {}).get(col)
|
||||||
|
if rid:
|
||||||
|
d = await fetch_raw(table, rid) or {}
|
||||||
|
if d.get("profileImage"):
|
||||||
|
logos.append({"channel": ch, "url": d["profileImage"]})
|
||||||
|
# 추가 채널 (hospital raw_data)
|
||||||
|
for ch, key in [("Instagram EN", "instagramEn"), ("Facebook EN", "facebookEn"), ("TikTok", "tiktok")]:
|
||||||
|
img = (raw_data.get(key) or {}).get("profileImage")
|
||||||
|
if img:
|
||||||
|
logos.append({"channel": ch, "url": img})
|
||||||
|
|
||||||
|
if not logos:
|
||||||
|
logger.info("[channel_logos] skip — 채널 프로필 이미지 없음")
|
||||||
|
return
|
||||||
|
|
||||||
|
logger.info("[channel_logos] start run=%s channels=%s official=%s", analysis_run_id,
|
||||||
|
[l["channel"] for l in logos], bool(official))
|
||||||
|
result = await VisionClient(api_key).describe_channel_logos(official, logos)
|
||||||
|
if result:
|
||||||
|
# Vision이 못 본 채널도 url은 채워둠 (프론트에서 이미지 표시용)
|
||||||
|
result["logos"] = logos
|
||||||
|
await merge_hospital_raw_data(hospital_id, {"channelLogos": result})
|
||||||
|
logger.info("[channel_logos] done run=%s keys=%s", analysis_run_id, list(result.keys()) if result else None)
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
import logging
|
||||||
|
|
||||||
|
from fastapi import HTTPException, UploadFile
|
||||||
|
|
||||||
|
from common.db import execute, fetchall, fetchone, insert_file_row
|
||||||
|
from integrations.azure_blob import AzureBlobUploader
|
||||||
|
from models.file import FileListItem, FileType, FileUploadResponse
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_MAX_UPLOAD_BYTES = 50 * 1024 * 1024 # 50MB
|
||||||
|
|
||||||
|
|
||||||
|
async def upload_file_to_blob(
|
||||||
|
content: bytes,
|
||||||
|
file_name: str,
|
||||||
|
group: str,
|
||||||
|
category: str = "file",
|
||||||
|
content_type: str | None = None,
|
||||||
|
) -> str:
|
||||||
|
"""Azure Blob에 파일을 업로드하고 public URL을 반환. DB는 건드리지 않음."""
|
||||||
|
uploader = AzureBlobUploader(group=group, category=category)
|
||||||
|
return await uploader.upload_bytes(content=content, file_name=file_name, content_type=content_type)
|
||||||
|
|
||||||
|
|
||||||
|
async def upload_analysis_file(
|
||||||
|
analysis_run_id: str,
|
||||||
|
content: bytes,
|
||||||
|
file_name: str,
|
||||||
|
file_type: str = "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,),
|
||||||
|
)
|
||||||
|
if not run:
|
||||||
|
raise HTTPException(status_code=404, detail="analysis_run not found")
|
||||||
|
hospital_id = run["hospital_id"]
|
||||||
|
|
||||||
|
public_url = await upload_file_to_blob(
|
||||||
|
content=content,
|
||||||
|
file_name=file_name,
|
||||||
|
group=analysis_run_id,
|
||||||
|
category=file_type,
|
||||||
|
content_type=content_type,
|
||||||
|
)
|
||||||
|
|
||||||
|
file_id = await insert_file_row(
|
||||||
|
analysis_run_id=analysis_run_id,
|
||||||
|
hospital_id=hospital_id,
|
||||||
|
file_type=file_type,
|
||||||
|
file_name=file_name,
|
||||||
|
file_url=public_url,
|
||||||
|
size_bytes=len(content),
|
||||||
|
)
|
||||||
|
logger.info("uploaded analysis file run=%s file_id=%s url=%s", analysis_run_id, file_id, public_url)
|
||||||
|
return file_id, public_url
|
||||||
|
|
||||||
|
|
||||||
|
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,),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def handle_analysis_file_upload(
|
||||||
|
analysis_run_id: str,
|
||||||
|
upload: UploadFile,
|
||||||
|
file_type: FileType,
|
||||||
|
) -> FileUploadResponse:
|
||||||
|
"""multipart UploadFile 검증 + 업로드 + 응답 모델 생성."""
|
||||||
|
if not upload.filename:
|
||||||
|
raise HTTPException(status_code=400, detail="filename is required")
|
||||||
|
content = await upload.read()
|
||||||
|
if not content:
|
||||||
|
raise HTTPException(status_code=400, detail="empty file")
|
||||||
|
if len(content) > _MAX_UPLOAD_BYTES:
|
||||||
|
raise HTTPException(status_code=413, detail=f"file too large (max {_MAX_UPLOAD_BYTES} bytes)")
|
||||||
|
|
||||||
|
file_id, public_url = await upload_analysis_file(
|
||||||
|
analysis_run_id=analysis_run_id,
|
||||||
|
content=content,
|
||||||
|
file_name=upload.filename,
|
||||||
|
file_type=file_type.value,
|
||||||
|
content_type=upload.content_type,
|
||||||
|
)
|
||||||
|
return FileUploadResponse(
|
||||||
|
id=file_id,
|
||||||
|
analysis_run_id=analysis_run_id,
|
||||||
|
file_type=file_type,
|
||||||
|
file_name=upload.filename,
|
||||||
|
file_url=public_url,
|
||||||
|
size_bytes=len(content),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
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,)):
|
||||||
|
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]
|
||||||
|
|
||||||
|
|
||||||
|
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),
|
||||||
|
)
|
||||||
|
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,),
|
||||||
|
)
|
||||||
|
logger.info("soft-deleted analysis file run=%s file_id=%s", analysis_run_id, file_id)
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
"""Instagram audit 계정(KR·EN)을 수집 데이터로 구성.
|
||||||
|
fix 값(handle/followers/highlights/content_format 등)은 전부 코드에서 박는다 — LLM 출력 무시."""
|
||||||
|
|
||||||
|
_MEDIA = {"GraphImage": "이미지", "GraphSidecar": "카드뉴스", "GraphVideo": "영상/릴스"}
|
||||||
|
|
||||||
|
|
||||||
|
def _content_format(data: dict) -> str:
|
||||||
|
"""latestPosts 미디어 타입으로 콘텐츠 포맷 도출 (표기 순서는 _MEDIA 정의 순서로 고정)."""
|
||||||
|
present = {_MEDIA.get(p.get("type")) for p in (data.get("latestPosts") or [])}
|
||||||
|
return "/".join(m for m in _MEDIA.values() if m in present)
|
||||||
|
|
||||||
|
|
||||||
|
def _logo_desc(channel_logos: dict, channel: str) -> str:
|
||||||
|
"""channelLogos(비전 결과)에서 해당 채널 로고 설명만 가져온다."""
|
||||||
|
for c in (channel_logos or {}).get("channel_logos", []):
|
||||||
|
if c.get("channel") == channel:
|
||||||
|
return c.get("logo_description") or ""
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _account(data: dict, language: str, label: str, channel: str, channel_logos: dict) -> dict:
|
||||||
|
"""스크래퍼 수집값으로 InstagramAccount 전 필드를 구성."""
|
||||||
|
handle = data.get("username") or ""
|
||||||
|
return {
|
||||||
|
"handle": handle,
|
||||||
|
"language": language,
|
||||||
|
"label": label,
|
||||||
|
"posts": data.get("posts", 0),
|
||||||
|
"followers": data.get("followers", 0),
|
||||||
|
"following": data.get("following", 0),
|
||||||
|
"category": data.get("category", ""),
|
||||||
|
"profile_link": f"https://www.instagram.com/{handle}/" if handle else "",
|
||||||
|
"highlights": data.get("highlights") or [],
|
||||||
|
"reels_count": 0, # 릴스 스크래퍼 미사용
|
||||||
|
"content_format": _content_format(data),
|
||||||
|
"profile_photo": _logo_desc(channel_logos, channel),
|
||||||
|
"bio": data.get("bio", ""),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def build_instagram_accounts(instagram: dict, instagram_en: dict, channel_logos: dict) -> list[dict]:
|
||||||
|
"""KR·EN 인스타 계정 리스트 구성 (username 있는 것만)."""
|
||||||
|
accounts: list[dict] = []
|
||||||
|
if instagram.get("username"):
|
||||||
|
accounts.append(_account(instagram, "KR", "인스타그램 KR", "Instagram", channel_logos))
|
||||||
|
if instagram_en.get("username"):
|
||||||
|
accounts.append(_account(instagram_en, "EN", "인스타그램 EN", "Instagram EN", channel_logos))
|
||||||
|
return accounts
|
||||||
@@ -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,56 @@
|
|||||||
|
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, extra_channels: dict | None = None) -> None:
|
||||||
|
logger.info("[pipeline] start run=%s", analysis_run_id)
|
||||||
|
extra_channels = extra_channels or {}
|
||||||
|
|
||||||
|
# ── 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"],
|
||||||
|
tiktok_url=extra_channels.get("tiktok"),
|
||||||
|
instagram_en_url=extra_channels.get("instagram_en"),
|
||||||
|
facebook_en_url=extra_channels.get("facebook_en"),
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── 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)
|
||||||
@@ -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