5 Commits
31 changed files with 1699 additions and 254 deletions

No files matched your search

+35
View File
@@ -152,6 +152,23 @@ CREATE INDEX IX_analysis_runs_2
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
CREATE TABLE hospital_history
(
@@ -179,3 +196,21 @@ CREATE INDEX IX_hospital_history_1
CREATE INDEX IX_hospital_history_2
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
View File
@@ -1,6 +1,6 @@
from .clinics import router as clinics_router
from .analysis import router as analysis_router
from .reports import router as reports_router
from .plans import router as plans_router
from .report import router as report_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]
+32 -16
View File
@@ -1,11 +1,13 @@
import logging
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.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.file import FileListItem, FileType, FileUploadResponse
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
router = APIRouter(prefix="/api/analysis", tags=["analysis"], dependencies=[Depends(verify_api_key)])
logger = logging.getLogger(__name__)
@@ -24,7 +26,6 @@ async def start_analysis(body: AnalysisCreate, background_tasks: BackgroundTasks
)
if not hospital:
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
fb_id = await insert_facebook_row(hospital_id, body.channels.facebook) if body.channels.facebook else None
@@ -32,20 +33,12 @@ 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
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"])
if ig_id:
background_tasks.add_task(collect_instagram, analysis_run_id, ig_id, body.channels.instagram)
if fb_id:
background_tasks.add_task(collect_facebook, analysis_run_id, fb_id, body.channels.facebook)
if nb_id:
background_tasks.add_task(collect_naver_blog, analysis_run_id, nb_id, body.channels.naver_blog)
if yt_id:
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)
background_tasks.add_task(run_pipeline, analysis_run_id)
return AnalysisStartResponse(
analysis_run_id=analysis_run_id,
@@ -56,6 +49,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)
async def get_analysis_status(run_id: str):
logger.info("GET /api/analysis/%s/status", run_id)
+36
View File
@@ -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(),
)
-21
View File
@@ -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)
+36
View File
@@ -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"}),
)
-24
View File
@@ -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)
+68 -6
View File
@@ -26,22 +26,58 @@ async def get_pool() -> aiomysql.Pool:
# 쓰기 (INSERT/UPDATE/DELETE)
async def execute(sql: str, args: tuple = ()) -> int:
pool = await get_pool()
print(
f"[Pool] size={pool.size} "
f"free={pool.freesize} "
f"used={pool.size - pool.freesize} "
f"max={pool.maxsize}"
)
async with pool.acquire() as conn:
await conn.ping(reconnect=True)
async with conn.cursor() as cur:
await cur.execute(sql, args)
await conn.commit()
return cur.lastrowid
try:
async with conn.cursor() as cur:
await cur.execute(sql, args)
await conn.commit()
return cur.lastrowid
finally:
conn.close()
# 읽기 (SELECT)
async def fetchone(sql: str, args: tuple = ()) -> dict | None:
pool = await get_pool()
print(
f"[Pool] size={pool.size} "
f"free={pool.freesize} "
f"used={pool.size - pool.freesize} "
f"max={pool.maxsize}"
)
async with pool.acquire() as conn:
try:
async with conn.cursor(aiomysql.DictCursor) as cur:
await cur.execute(sql, args)
return await cur.fetchone()
finally:
conn.close()
async def fetchall(sql: str, args: tuple = ()) -> list[dict]:
pool = await get_pool()
async with pool.acquire() as conn:
try:
async with conn.cursor(aiomysql.DictCursor) as cur:
await cur.execute(sql, args)
return await cur.fetchall()
finally:
conn.close()
async def fetchall(sql: str, args: tuple = ()) -> list[dict]:
pool = await get_pool()
async with pool.acquire() as conn:
await conn.ping(reconnect=True)
async with conn.cursor(aiomysql.DictCursor) as cur:
await cur.execute(sql, args)
return await cur.fetchone()
return list(await cur.fetchall())
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))
@@ -63,6 +99,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))
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(
analysis_run_id: str,
hospital_id: str,
@@ -231,3 +282,14 @@ async def save_hospital_raw_data(hospital_id: str, data: dict, analysis_run_id:
),
)
await _insert_hospital_history(hospital_id, analysis_run_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
}
+1
View File
@@ -7,6 +7,7 @@ import httpx
REQUEST_TIMEOUT = 60
def get_env(key: str) -> str:
v = os.environ.get(key, "")
if not v:
+79
View File
@@ -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
+1
View File
@@ -45,6 +45,7 @@ class LLMService:
response = await self.client.chat.completions.create(
model=prompt.model,
messages=[{"role": "user", "content": prompt_text}],
max_tokens=16000,
response_format={
"type": "json_schema",
"json_schema": {"name": prompt.output_class.__name__, "schema": prompt.output_class.model_json_schema()},
+34
View File
@@ -3,6 +3,12 @@ from pydantic import BaseModel
from common.utils import get_env
from integrations.llm.schemas.report import ReportInput, ReportOutput
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")
@@ -46,3 +52,31 @@ plan_prompt = Prompt(
input_class=PlanInput,
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,
)
+61
View File
@@ -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]
+51 -80
View File
@@ -11,6 +11,10 @@ class PlanInput(BaseModel):
services: str | None = None
doctors: 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
# --- BrandGuide ---
@@ -25,7 +29,7 @@ class FontSpec(BaseModel):
family: str
weight: str
usage: str
sampleText: str
sample_text: str
class LogoUsageRule(BaseModel):
@@ -36,29 +40,29 @@ class LogoUsageRule(BaseModel):
class ToneOfVoice(BaseModel):
personality: list[str]
communicationStyle: str
doExamples: list[str]
dontExamples: list[str]
communication_style: str
do_examples: list[str]
dont_examples: list[str]
class ChannelBrandingRule(BaseModel):
channel: str
icon: str
profilePhoto: str
bannerSpec: str
bioTemplate: str
currentStatus: Literal["correct", "incorrect", "missing"]
profile_photo: str
banner_spec: str
bio_template: str
current_status: Literal["correct", "incorrect", "missing"]
class BrandInconsistencyValue(BaseModel):
class BrandPlanInconsistencyValue(BaseModel):
channel: str
value: str
isCorrect: bool
is_correct: bool
class BrandInconsistency(BaseModel):
class BrandPlanInconsistency(BaseModel):
field: str
values: list[BrandInconsistencyValue]
values: list[BrandPlanInconsistencyValue]
impact: str
recommendation: str
@@ -66,26 +70,26 @@ class BrandInconsistency(BaseModel):
class BrandGuide(BaseModel):
colors: list[ColorSwatch]
fonts: list[FontSpec]
logoRules: list[LogoUsageRule]
toneOfVoice: ToneOfVoice
channelBranding: list[ChannelBrandingRule]
brandInconsistencies: list[BrandInconsistency]
logo_rules: list[LogoUsageRule]
tone_of_voice: ToneOfVoice
channel_branding: list[ChannelBrandingRule]
brand_inconsistencies: list[BrandPlanInconsistency]
# --- ChannelStrategy ---
class ChannelStrategyCard(BaseModel):
channelId: str
channelName: str
channel_id: str
channel_name: str
icon: str
currentStatus: str
targetGoal: str
contentTypes: list[str]
postingFrequency: str
current_status: str
target_goal: str
content_types: list[str]
posting_frequency: str
tone: str
formatGuidelines: list[str]
format_guidelines: list[str]
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 ---
@@ -93,8 +97,8 @@ class ChannelStrategyCard(BaseModel):
class ContentPillar(BaseModel):
title: str
description: str
relatedUSP: str
exampleTopics: list[str]
related_usp: str
example_topics: list[str]
color: str
@@ -121,30 +125,30 @@ class RepurposingOutput(BaseModel):
class ContentStrategyData(BaseModel):
pillars: list[ContentPillar]
typeMatrix: list[ContentTypeRow]
type_matrix: list[ContentTypeRow]
workflow: list[WorkflowStep]
repurposingSource: str
repurposingOutputs: list[RepurposingOutput]
repurposing_source: str
repurposing_outputs: list[RepurposingOutput]
# --- Calendar ---
class CalendarEntry(BaseModel):
dayOfWeek: int
day_of_week: int
channel: str
channelIcon: str
contentType: Literal["video", "blog", "social", "ad"]
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
isManualEdit: bool | None = None
aiPromptSeed: str | None = None
is_manual_edit: bool | None = None
ai_prompt_seed: str | None = None
class CalendarWeek(BaseModel):
weekNumber: int
week_number: int
label: str
entries: list[CalendarEntry]
@@ -158,7 +162,7 @@ class ContentCountSummary(BaseModel):
class CalendarData(BaseModel):
weeks: list[CalendarWeek]
monthlySummary: list[ContentCountSummary]
monthly_summary: list[ContentCountSummary]
# --- AssetCollection ---
@@ -166,11 +170,11 @@ class CalendarData(BaseModel):
class AssetCard(BaseModel):
id: str
source: Literal["homepage", "naver_place", "blog", "social", "youtube"]
sourceLabel: str
source_label: str
type: Literal["photo", "video", "text"]
title: str
description: str
repurposingSuggestions: list[str]
repurposing_suggestions: list[str]
status: Literal["collected", "pending", "needs_creation"]
@@ -178,62 +182,29 @@ class YouTubeRepurposeItem(BaseModel):
title: str
views: int
type: Literal["Short", "Long"]
repurposeAs: list[str]
repurpose_as: list[str]
class AssetCollectionData(BaseModel):
assets: list[AssetCard]
youtubeRepurpose: list[YouTubeRepurposeItem]
youtube_repurpose: list[YouTubeRepurposeItem]
# --- Repurposing ---
class RepurposingProposalItem(BaseModel):
sourceVideo: YouTubeRepurposeItem
source_video: YouTubeRepurposeItem
outputs: list[RepurposingOutput]
estimatedEffort: Literal["low", "medium", "high"]
estimated_effort: Literal["low", "medium", "high"]
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 ---
class PlanOutput(BaseModel):
brandGuide: BrandGuide
channelStrategies: list[ChannelStrategyCard]
contentStrategy: ContentStrategyData
brand_guide: BrandGuide
channel_strategies: list[ChannelStrategyCard]
content_strategy: ContentStrategyData
calendar: CalendarData
assetCollection: AssetCollectionData
repurposingProposals: list[RepurposingProposalItem] | None = None
#workflow: WorkflowData | None = None
asset_collection: AssetCollectionData
repurposing_proposals: list[RepurposingProposalItem] | None = None
+327 -23
View File
@@ -1,8 +1,309 @@
from __future__ import annotations
from pydantic import BaseModel
from models.status import Severity, ChannelStatus, DataSource, Language, VideoType, AnnotationType
# template.format(**model_dump()) 에 삽입될 변수들
# 각 채널 raw_data를 호출부에서 json.dumps()로 직렬화해서 넘겨야 함
class ScreenshotAnnotation(BaseModel):
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):
clinic_name: str | None = None
clinic_name_en: str | None = None
@@ -16,28 +317,31 @@ class ReportInput(BaseModel):
naver_blog: str | None = None
youtube: 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
class ChannelScore(BaseModel):
score: int
summary: str
strengths: list[str]
weaknesses: list[str]
# --- MarketingReport ---
class ConversionStrategy(BaseModel):
summary: str
actions: list[str]
# response_format으로 OpenAI structured output에 전달 — dict 필드 사용 불가
class ReportOutput(BaseModel):
class MarketingReport(BaseModel):
id: str
created_at: str
target_url: str
overall_score: int
instagram: ChannelScore | None = None
facebook: ChannelScore | None = None
naver_blog: ChannelScore | None = None
youtube: ChannelScore | None = None
gangnam_unni: ChannelScore | None = None
conversion_strategy: ConversionStrategy
roadmap: list[str]
kpis: list[str]
clinic_snapshot: ClinicSnapshot
channel_scores: list[ChannelScore]
youtube_audit: YouTubeAudit
instagram_audit: InstagramAudit
facebook_audit: FacebookAudit
other_channels: list[OtherChannel]
website_audit: WebsiteAudit
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,6 +15,20 @@
- 시술: {services}
- 의료진: {doctors}
## 시장 분석 데이터
### 경쟁 병원
{market_competitors}
### 검색 키워드 트렌드
{market_keywords}
### 시장 트렌드
{market_trend}
### 잠재 고객 분석
{market_target_audience}
## 분석 리포트
{report}
@@ -12,6 +12,20 @@
- 시술: {services}
- 의료진: {doctors}
## 시장 분석 데이터
### 경쟁 병원
{market_competitors}
### 검색 키워드 트렌드
{market_keywords}
### 시장 트렌드
{market_trend}
### 잠재 고객 분석
{market_target_audience}
## 채널 데이터
### 인스타그램
+10
View File
@@ -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)
+29
View File
@@ -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
View File
@@ -1,16 +1,200 @@
from pydantic import BaseModel
from typing import Literal
from models.common import CamelModel
class PlanCreate(BaseModel):
report_id: str
regenerate: bool = False
class BrandPlanInconsistencyValue(CamelModel):
channel: str
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
analysis_run_id: str
brand_guide: dict
channel_strategies: list
content_strategy: dict
calendar: list
source: Literal["homepage", "naver_place", "blog", "social", "youtube"]
source_label: str
type: Literal["photo", "video", "text"]
title: str
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
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
View File
@@ -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
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
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
clinic: ClinicInfo
clinic_name: str | None = None
clinic_name_en: str | None = None
created_at: str
target_url: str
overall_score: int
youtube: dict
instagram: dict
facebook: dict
naver_place: dict
naver_blog: dict
gangnam_unni: dict
conversion_strategy: dict
roadmap: list
kpis: list
generated_at: str
clinic_snapshot: ClinicSnapshot
channel_scores: list[ChannelScore]
youtube_audit: YouTubeAudit
instagram_audit: InstagramAudit
facebook_audit: FacebookAudit
other_channels: list[OtherChannel]
website_audit: WebsiteAudit
problem_diagnosis: list[DiagnosisItem]
transformation: TransformationProposal
roadmap: list[RoadmapMonth]
kpi_dashboard: list[KPIMetric]
screenshots: list[ScreenshotEvidence] | None = None
+36
View File
@@ -14,3 +14,39 @@ class TaskStatus(StrEnum):
START = "start"
PROCESSING = "processing"
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"
+40 -50
View File
@@ -1,7 +1,6 @@
import asyncio
import json
import logging
from common.db import fetchone, execute, is_done, get_analysis_raw_data, save_analysis_report
from common.db import fetchone, execute, get_analysis_raw_data, save_analysis_report, get_market_analysis
from integrations.llm.llm_service import LLMService
from integrations.llm.prompt import report_prompt, plan_prompt
from integrations.llm.schemas.report import ReportOutput
@@ -23,17 +22,25 @@ async def generate_report(analysis_run_id: str) -> ReportOutput:
raw_data = clinic_row["raw_data"] if clinic_row else None
clinic = json.loads(raw_data) if isinstance(raw_data, str) else (raw_data or {})
raw = await get_analysis_raw_data(analysis_run_id)
market = await get_market_analysis(analysis_run_id)
def _json(v) -> str | None:
return json.dumps(v, ensure_ascii=False) if v else None
input_data = {
"clinic_name": clinic.get("clinicName"),
"clinic_name_en": clinic.get("clinicNameEn"),
"address": clinic.get("address"),
"phone": clinic.get("phone"),
"slogan": clinic.get("slogan"),
"services": json.dumps(clinic.get("services", []), ensure_ascii=False),
"doctors": json.dumps(clinic.get("doctors", []), ensure_ascii=False),
"clinic_name": clinic.get("clinicName"),
"clinic_name_en": clinic.get("clinicNameEn"),
"address": clinic.get("address"),
"phone": clinic.get("phone"),
"slogan": clinic.get("slogan"),
"services": json.dumps(clinic.get("services", []), 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")),
**{
channel: json.dumps(data, ensure_ascii=False) if data else None
channel: _json(data)
for channel, data in raw.items()
},
}
@@ -54,58 +61,41 @@ async def generate_plan(analysis_run_id: str) -> PlanOutput:
clinic = json.loads(raw_data) if isinstance(raw_data, str) else (raw_data or {})
report_data = run["report_data"]
report = json.loads(report_data) if isinstance(report_data, str) else report_data
market = await get_market_analysis(analysis_run_id)
def _json(v) -> str | None:
return json.dumps(v, ensure_ascii=False) if v else None
input_data = {
"clinic_name": clinic.get("clinicName"),
"clinic_name_en": clinic.get("clinicNameEn"),
"address": clinic.get("address"),
"phone": clinic.get("phone"),
"slogan": clinic.get("slogan"),
"services": json.dumps(clinic.get("services", []), ensure_ascii=False),
"doctors": json.dumps(clinic.get("doctors", []), ensure_ascii=False),
"report": json.dumps(report, ensure_ascii=False) if report else None,
"clinic_name": clinic.get("clinicName"),
"clinic_name_en": clinic.get("clinicNameEn"),
"address": clinic.get("address"),
"phone": clinic.get("phone"),
"slogan": clinic.get("slogan"),
"services": json.dumps(clinic.get("services", []), ensure_ascii=False),
"doctors": json.dumps(clinic.get("doctors", []), ensure_ascii=False),
"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")),
}
return await LLMService(provider="perplexity").generate(plan_prompt, input_data)
async def run_plan_task(analysis_run_id: str) -> None:
logger.info("[plan] start run=%s", analysis_run_id)
result = await generate_plan(analysis_run_id)
await execute(
"UPDATE analysis_runs SET plan_data = %s, status = %s WHERE analysis_run_id = %s",
(json.dumps(result.model_dump(), ensure_ascii=False), AnalysisStatus.COMPLETED, analysis_run_id),
)
logger.info("[plan] done run=%s", analysis_run_id)
async def run_report_task(analysis_run_id: str) -> None:
logger.info("[report] start run=%s", analysis_run_id)
result = await generate_report(analysis_run_id)
await save_analysis_report(analysis_run_id, result.model_dump())
await execute("UPDATE analysis_runs SET status = %s WHERE analysis_run_id = %s", (AnalysisStatus.PLANNING, analysis_run_id))
logger.info("[report] done run=%s", analysis_run_id)
asyncio.create_task(run_plan_task(analysis_run_id))
async def check_and_advance_analysis(analysis_run_id: str) -> None:
run = await fetchone(
"SELECT hospital_id, instagram_data_id, facebook_data_id, naver_blog_data_id, youtube_data_id, gangnam_unni_data_id"
" FROM analysis_runs WHERE analysis_run_id = %s",
(analysis_run_id,),
async def run_plan_task(analysis_run_id: str) -> None:
logger.info("[plan] start run=%s", analysis_run_id)
result = await generate_plan(analysis_run_id)
await execute(
"UPDATE analysis_runs SET plan_data = %s WHERE analysis_run_id = %s",
(json.dumps(result.model_dump(), ensure_ascii=False), analysis_run_id),
)
clinic_row = await fetchone(
"SELECT status FROM hospital_baseinfo WHERE hospital_id = %s",
(run["hospital_id"],),
)
results = [
clinic_row["status"] == "done" if clinic_row else False,
await is_done("instagram_data", run["instagram_data_id"]),
await is_done("facebook_data", run["facebook_data_id"]),
await is_done("naver_blog_data", run["naver_blog_data_id"]),
await is_done("youtube_data", run["youtube_data_id"]),
await is_done("gangnam_unni_data", run["gangnam_unni_data_id"]),
]
if all(results):
await execute("UPDATE analysis_runs SET status = %s WHERE analysis_run_id = %s", (AnalysisStatus.ANALYZING, analysis_run_id))
asyncio.create_task(run_report_task(analysis_run_id))
logger.info("[plan] done run=%s", analysis_run_id)
+32 -7
View File
@@ -1,4 +1,6 @@
import asyncio
import logging
from common.db import fetchone
from common.db import (
set_instagram_status, save_instagram_raw_data,
set_facebook_status, save_facebook_raw_data,
@@ -8,7 +10,6 @@ from common.db import (
execute, save_hospital_raw_data,
)
from common.utils import get_env
from services.analysis import check_and_advance_analysis
from integrations.apify import ApifyClient
from integrations.naver import NaverClient
from integrations.youtube import YouTubeClient
@@ -23,7 +24,6 @@ async def collect_instagram(analysis_run_id: str, row_id: int, url: str) -> None
data = await ApifyClient(get_env("APIFY_API_TOKEN")).get_instagram_profile(url)
await save_instagram_raw_data(row_id, data)
logger.info("[instagram] done run=%s", analysis_run_id)
await check_and_advance_analysis(analysis_run_id)
async def collect_facebook(analysis_run_id: str, row_id: int, url: str) -> None:
@@ -32,7 +32,6 @@ async def collect_facebook(analysis_run_id: str, row_id: int, url: str) -> None:
data = await ApifyClient(get_env("APIFY_API_TOKEN")).get_facebook_page(url)
await save_facebook_raw_data(row_id, data)
logger.info("[facebook] done run=%s", analysis_run_id)
await check_and_advance_analysis(analysis_run_id)
async def collect_naver_blog(analysis_run_id: str, row_id: int, url: str) -> None:
@@ -41,7 +40,6 @@ async def collect_naver_blog(analysis_run_id: str, row_id: int, url: str) -> Non
data = await NaverClient(get_env("NAVER_CLIENT_ID"), get_env("NAVER_CLIENT_SECRET")).get_blog_rss(url)
await save_naver_blog_raw_data(row_id, data)
logger.info("[naver_blog] done run=%s", analysis_run_id)
await check_and_advance_analysis(analysis_run_id)
async def collect_youtube(analysis_run_id: str, row_id: int, url: str) -> None:
@@ -50,7 +48,6 @@ async def collect_youtube(analysis_run_id: str, row_id: int, url: str) -> None:
data = await YouTubeClient(get_env("YOUTUBE_API_KEY")).get_channel(url)
await save_youtube_raw_data(row_id, data)
logger.info("[youtube] done run=%s", analysis_run_id)
await check_and_advance_analysis(analysis_run_id)
async def collect_gangnam_unni(analysis_run_id: str, row_id: int, url: str) -> None:
@@ -59,7 +56,6 @@ async def collect_gangnam_unni(analysis_run_id: str, row_id: int, url: str) -> N
data = await FirecrawlClient(get_env("FIRECRAWL_API_KEY")).get_gangnam_unni(url)
await save_gangnam_unni_raw_data(row_id, data)
logger.info("[gangnam_unni] done run=%s", analysis_run_id)
await check_and_advance_analysis(analysis_run_id)
async def collect_clinic_info(analysis_run_id: str, hospital_id: str, url: str) -> None:
@@ -68,4 +64,33 @@ async def collect_clinic_info(analysis_run_id: str, hospital_id: str, url: str)
data = await FirecrawlClient(get_env("FIRECRAWL_API_KEY")).fetch_clinic_info(url)
await save_hospital_raw_data(hospital_id, data, analysis_run_id=analysis_run_id)
logger.info("[clinic] done run=%s", analysis_run_id)
await check_and_advance_analysis(analysis_run_id)
async def collect_all(
analysis_run_id: str,
hospital_id: str,
instagram_id: int | None = None,
facebook_id: int | None = None,
naver_blog_id: int | None = None,
youtube_id: int | None = None,
gangnam_unni_id: int | None = None,
) -> None:
async def _url(table: str, row_id: int) -> str:
row = await fetchone(f"SELECT url FROM {table} WHERE id = %s", (row_id,))
return row["url"] if row else ""
hospital = await fetchone("SELECT url FROM hospital_baseinfo WHERE hospital_id = %s", (hospital_id,))
tasks = [collect_clinic_info(analysis_run_id, hospital_id, hospital["url"])]
if instagram_id:
tasks.append(collect_instagram(analysis_run_id, instagram_id, await _url("instagram_data", instagram_id)))
if facebook_id:
tasks.append(collect_facebook(analysis_run_id, facebook_id, await _url("facebook_data", facebook_id)))
if naver_blog_id:
tasks.append(collect_naver_blog(analysis_run_id, naver_blog_id, await _url("naver_blog_data", naver_blog_id)))
if youtube_id:
tasks.append(collect_youtube(analysis_run_id, youtube_id, await _url("youtube_data", youtube_id)))
if gangnam_unni_id:
tasks.append(collect_gangnam_unni(analysis_run_id, gangnam_unni_id, await _url("gangnam_unni_data", gangnam_unni_id)))
await asyncio.gather(*tasks, return_exceptions=True)
+123
View File
@@ -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)
+84
View File
@@ -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)
+52
View File
@@ -0,0 +1,52 @@
import logging
from common.db import fetchone, execute
from models.status import AnalysisStatus
from services.collect import collect_all
from services.market import run_market_analysis
from services.analysis import run_report_task, run_plan_task
logger = logging.getLogger(__name__)
async def run_pipeline(analysis_run_id: str) -> None:
logger.info("[pipeline] start run=%s", analysis_run_id)
# ── 1. Collect ──────────────────────────────────────────────────────────
run = await fetchone(
"SELECT hospital_id, instagram_data_id, facebook_data_id,"
" naver_blog_data_id, youtube_data_id, gangnam_unni_data_id"
" FROM analysis_runs WHERE analysis_run_id = %s",
(analysis_run_id,),
)
await collect_all(
analysis_run_id,
hospital_id=run["hospital_id"],
instagram_id=run["instagram_data_id"],
facebook_id=run["facebook_data_id"],
naver_blog_id=run["naver_blog_data_id"],
youtube_id=run["youtube_data_id"],
gangnam_unni_id=run["gangnam_unni_data_id"],
)
# ── 2. Market ────────────────────────────────────────────────────────────
await execute(
"UPDATE analysis_runs SET status = %s WHERE analysis_run_id = %s",
(AnalysisStatus.ANALYZING, analysis_run_id),
)
await run_market_analysis(analysis_run_id)
# ── 3. Report ────────────────────────────────────────────────────────────
await run_report_task(analysis_run_id)
# ── 4. Plan ──────────────────────────────────────────────────────────────
await execute(
"UPDATE analysis_runs SET status = %s WHERE analysis_run_id = %s",
(AnalysisStatus.PLANNING, analysis_run_id),
)
await run_plan_task(analysis_run_id)
await execute(
"UPDATE analysis_runs SET status = %s WHERE analysis_run_id = %s",
(AnalysisStatus.COMPLETED, analysis_run_id),
)
logger.info("[pipeline] done run=%s", analysis_run_id)