feat(ssulbox): SNS 업로드 제목·설명·태그 자동 생성
This commit is contained in:
1 parent
fb8febe462
commit
50dc7af5bc
7 files changed
+234
-6
No files matched your search
@@ -33,5 +33,8 @@ async def youtube_seo_description(
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> YoutubeDescriptionResponse:
|
||||
return await seo_service.get_youtube_seo_description(
|
||||
request_body.task_id, current_user, session
|
||||
request_body.task_id,
|
||||
current_user,
|
||||
session,
|
||||
content_type=request_body.content_type,
|
||||
)
|
||||
@@ -2,13 +2,20 @@
|
||||
소셜 SEO 관련 Pydantic 스키마
|
||||
"""
|
||||
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class YoutubeDescriptionRequest(BaseModel):
|
||||
"""유튜브 SEO Description 제안 요청"""
|
||||
|
||||
task_id: str = Field(..., description="작업 고유 식별자")
|
||||
# 썰박스 콘텐츠의 SEO 를 요청할 때는 "ssul" + task_id 자리에 ssul_content.id.
|
||||
# 종류를 안 밝히면 video 로 간주된다 (기존 호출 호환).
|
||||
content_type: Literal["video", "ssul"] = Field(
|
||||
default="video", description="콘텐츠 종류"
|
||||
)
|
||||
task_id: str = Field(..., description="작업 고유 식별자 (ssul 이면 ssul_content.id)")
|
||||
|
||||
model_config = ConfigDict(
|
||||
json_schema_extra={
|
||||
|
||||
@@ -38,26 +38,93 @@ class SeoService:
|
||||
task_id: str,
|
||||
current_user: User,
|
||||
session: AsyncSession,
|
||||
content_type: str = "video",
|
||||
) -> YoutubeDescriptionResponse:
|
||||
"""
|
||||
유튜브 SEO description 생성
|
||||
|
||||
Redis 캐시 확인 후 miss이면 GPT로 생성하고 캐싱.
|
||||
|
||||
content_type="ssul" 이면 task_id 자리에 ssul_content.id(문자열)가 온다.
|
||||
캐시 키에 종류 접두를 붙인다 — ADO2 task_id(UUID)와 썰박스 id(숫자)는
|
||||
형식이 달라 실제로 겹치진 않지만, 형식 우연에 기대지 않는다.
|
||||
"""
|
||||
cache_key = f"ssul:{task_id}" if content_type == "ssul" else task_id
|
||||
logger.info(
|
||||
f"[SEO_SERVICE] Try Cache - user: {current_user.user_uuid} / task_id: {task_id}"
|
||||
f"[SEO_SERVICE] Try Cache - user: {current_user.user_uuid} / key: {cache_key}"
|
||||
)
|
||||
|
||||
cached = await self._get_from_redis(task_id)
|
||||
cached = await self._get_from_redis(cache_key)
|
||||
if cached:
|
||||
return cached
|
||||
|
||||
logger.info(f"[SEO_SERVICE] Cache miss - user: {current_user.user_uuid}")
|
||||
result = await self._generate_seo_description(task_id, current_user, session)
|
||||
await self._set_to_redis(task_id, result)
|
||||
if content_type == "ssul":
|
||||
result = await self._generate_ssul_seo(task_id, current_user, session)
|
||||
else:
|
||||
result = await self._generate_seo_description(task_id, current_user, session)
|
||||
await self._set_to_redis(cache_key, result)
|
||||
|
||||
return result
|
||||
|
||||
async def _generate_ssul_seo(
|
||||
self,
|
||||
content_id: str,
|
||||
current_user: User,
|
||||
session: AsyncSession,
|
||||
) -> YoutubeDescriptionResponse:
|
||||
"""썰박스 콘텐츠용 SEO 생성 — ADO2 와 **다른 프롬프트**(시트 ssul_upload)를 쓴다.
|
||||
|
||||
ADO2 는 업장 마케팅 분석 보고서 기반의 광고 영상 SEO 지만, 썰박스는
|
||||
병맛 역사 썰툰이라 톤이 완전히 다르다. 태그도 GPT 가 함께 만든다
|
||||
(ADO2 처럼 재사용할 마케팅 분석 target_keywords 가 없다).
|
||||
"""
|
||||
from app.ssulbox.constants import SCENARIO_NAMES
|
||||
from app.ssulbox.models import SsulContent
|
||||
from app.utils.prompts.prompts import get_ssul_upload_prompt
|
||||
|
||||
try:
|
||||
content = (
|
||||
await session.execute(
|
||||
select(SsulContent).where(
|
||||
SsulContent.id == int(content_id),
|
||||
SsulContent.user_uuid == current_user.user_uuid,
|
||||
SsulContent.is_deleted.is_(False),
|
||||
)
|
||||
)
|
||||
).scalar_one_or_none()
|
||||
|
||||
if content is None:
|
||||
raise HTTPException(
|
||||
status_code=404, detail="콘텐츠를 찾을 수 없습니다."
|
||||
)
|
||||
|
||||
input_data = {
|
||||
"store_name": content.store_name or "",
|
||||
"region": content.region or "",
|
||||
"scenario_name": SCENARIO_NAMES.get(content.scenario, content.scenario),
|
||||
}
|
||||
|
||||
chatgpt = ChatgptService(timeout=180)
|
||||
out = await chatgpt.generate_structured_output(
|
||||
get_ssul_upload_prompt(), input_data
|
||||
)
|
||||
|
||||
return YoutubeDescriptionResponse(
|
||||
title=out.title,
|
||||
description=out.description,
|
||||
keywords=out.keywords,
|
||||
)
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"[SEO_SERVICE] SSUL EXCEPTION - error: {e}")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=f"썰박스 SEO 생성에 실패했습니다. : {str(e)}",
|
||||
)
|
||||
|
||||
async def _generate_seo_description(
|
||||
self,
|
||||
task_id: str,
|
||||
|
||||
@@ -113,6 +113,32 @@ image_autotag_prompt = Prompt(
|
||||
prompt_output_class=ImageTagPromptOutput,
|
||||
)
|
||||
|
||||
@lru_cache()
|
||||
def get_ssul_upload_prompt() -> Prompt:
|
||||
"""썰박스 SNS 업로드 SEO 프롬프트 (시트: ssul_upload).
|
||||
|
||||
**lazy 로 만드는 이유**: 모듈 레벨 Prompt() 는 import 시점에 시트를 읽는다 —
|
||||
스프레드시트에 `ssul_upload` 시트가 아직 없으면 **앱 기동 자체가 죽는다.**
|
||||
lazy 면 시트가 없어도 앱은 살고, 썰박스 SEO 요청만 500 이 난다.
|
||||
(그래서 _preload_all_sheets 목록에도 넣지 않았다 — preload 는 실패를
|
||||
경고로 삼키지만, 이후 Prompt() 생성 시 worksheet() 폴백에서 죽는 건 같다)
|
||||
|
||||
ADO2(yt_upload)와 다른 프롬프트를 쓴다: 광고 영상 SEO 가 아니라
|
||||
병맛 역사 썰툰 톤의 제목·설명·태그를 만든다.
|
||||
템플릿 변수: {store_name} {region} {scenario_name}
|
||||
"""
|
||||
from app.utils.prompts.schemas import (
|
||||
SsulUploadPromptInput,
|
||||
SsulUploadPromptOutput,
|
||||
)
|
||||
|
||||
return Prompt(
|
||||
sheet_name="ssul_upload",
|
||||
prompt_input_class=SsulUploadPromptInput,
|
||||
prompt_output_class=SsulUploadPromptOutput,
|
||||
)
|
||||
|
||||
|
||||
@lru_cache()
|
||||
def create_dynamic_subtitle_prompt(length: int, industry: str = "") -> Prompt:
|
||||
# industry 인자는 캐시 구분/하위 호환용. 시트는 단일 'subtitle'로 통합됨.
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from .lyric import LyricPromptInput, LyricPromptOutput
|
||||
from .marketing import MarketingPromptInput, MarketingPromptOutput
|
||||
from .ssulbox import SsulUploadPromptInput, SsulUploadPromptOutput
|
||||
from .youtube import YTUploadPromptInput, YTUploadPromptOutput
|
||||
from .image import *
|
||||
from .subtitle import SubtitlePromptInput, SubtitlePromptOutput
|
||||
@@ -0,0 +1,28 @@
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import List
|
||||
|
||||
|
||||
# Input 정의
|
||||
class SsulUploadPromptInput(BaseModel):
|
||||
"""썰박스 SNS 업로드 SEO 프롬프트 입력.
|
||||
|
||||
ADO2(yt_upload)와 별도 프롬프트를 쓴다 — ADO2 는 업장 마케팅 분석 보고서 기반의
|
||||
광고 영상이지만, 썰박스는 "병맛 역사 썰툰"이라 제목·설명의 톤이 완전히 다르다.
|
||||
스프레드시트 시트명: `ssul_upload` (B2=모델, B3=템플릿).
|
||||
템플릿에서 쓸 수 있는 변수: {store_name} {region} {scenario_name}
|
||||
"""
|
||||
|
||||
store_name: str = Field(..., description="마케팅 대상 업장명 (모르면 빈 문자열)")
|
||||
region: str = Field(default="", description="업장 지역 (모르면 빈 문자열)")
|
||||
scenario_name: str = Field(
|
||||
..., description="시나리오 한글명 (조선왕/삼국지/그리스·로마 신화/오디세이)"
|
||||
)
|
||||
|
||||
|
||||
# Output 정의
|
||||
class SsulUploadPromptOutput(BaseModel):
|
||||
title: str = Field(..., description="쇼츠 제목 - 병맛 톤 + SEO")
|
||||
description: str = Field(..., description="업로드 설명 - 병맛 톤 + SEO/해시태그 포함")
|
||||
# ADO2 는 마케팅 분석의 target_keywords 를 태그로 재사용하지만 썰박스에는
|
||||
# 그 분석이 없다 — GPT 가 태그까지 함께 만든다.
|
||||
keywords: List[str] = Field(..., description="태그 키워드 리스트")
|
||||
Reference in new issue
Block a user