Merge branch 'main' into feature-ssulbox
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
commit
fde48e8674
24 files changed
+793
-104
No files matched your search
@@ -7,7 +7,7 @@ SEO 관련 엔드포인트를 제공합니다.
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database.session import get_session
|
||||
@@ -32,9 +32,21 @@ async def youtube_seo_description(
|
||||
current_user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> YoutubeDescriptionResponse:
|
||||
if request_body.content_type == "ssul":
|
||||
content_id = request_body.video_id
|
||||
if content_id is None:
|
||||
try:
|
||||
content_id = int(request_body.task_id)
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="썰박스 SEO 에는 video_id 또는 숫자 task_id 가 필요합니다.",
|
||||
)
|
||||
return await seo_service.get_ssul_seo(content_id, current_user, session)
|
||||
|
||||
return await seo_service.get_youtube_seo_description(
|
||||
request_body.task_id,
|
||||
current_user,
|
||||
session,
|
||||
content_type=request_body.content_type,
|
||||
video_id=request_body.video_id,
|
||||
task_id=request_body.task_id,
|
||||
)
|
||||
@@ -95,8 +95,6 @@ YOUTUBE_SCOPES = [
|
||||
"https://www.googleapis.com/auth/userinfo.profile", # 사용자 프로필
|
||||
]
|
||||
|
||||
YOUTUBE_SEO_HASH = "SEO_Describtion_YT"
|
||||
|
||||
# =============================================================================
|
||||
# Instagram/Facebook OAuth Scopes (추후 구현)
|
||||
# =============================================================================
|
||||
|
||||
@@ -2,25 +2,36 @@
|
||||
소셜 SEO 관련 Pydantic 스키마
|
||||
"""
|
||||
|
||||
from typing import Literal
|
||||
from typing import Literal, Optional
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
|
||||
class YoutubeDescriptionRequest(BaseModel):
|
||||
"""유튜브 SEO 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)")
|
||||
video_id: Optional[int] = Field(
|
||||
None, description="ADO2 video.id 또는 썰박스 ssul_content.id"
|
||||
)
|
||||
task_id: Optional[str] = Field(
|
||||
None,
|
||||
description="ADO2 작업 UUID. 썰박스는 ssul_content.id 문자열도 허용",
|
||||
)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def require_identifier(self) -> "YoutubeDescriptionRequest":
|
||||
if self.video_id is None and not self.task_id:
|
||||
raise ValueError("video_id 또는 task_id 가 필요합니다.")
|
||||
return self
|
||||
|
||||
model_config = ConfigDict(
|
||||
json_schema_extra={
|
||||
"example": {
|
||||
"task_id": "019c739f-65fc-7d15-8c88-b31be00e588e"
|
||||
"content_type": "video",
|
||||
"video_id": 123,
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
@@ -1,93 +1,84 @@
|
||||
"""
|
||||
유튜브 SEO 서비스
|
||||
|
||||
SEO description 생성 및 Redis 캐싱 로직을 처리합니다.
|
||||
ADO2 영상은 제목/설명/해시태그를 video 테이블에 저장합니다.
|
||||
썰박스는 별도 프롬프트로 생성합니다.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
|
||||
from fastapi import HTTPException
|
||||
from redis.asyncio import Redis
|
||||
from fastapi import HTTPException, status
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from config import db_settings
|
||||
from app.home.models import MarketingIntel, Project
|
||||
from app.social.constants import YOUTUBE_SEO_HASH
|
||||
from app.social.schemas import YoutubeDescriptionResponse
|
||||
from app.social.services.sns_metadata import apply_sns_metadata, has_stored_sns_metadata
|
||||
from app.ssulbox.models import SsulContent
|
||||
from app.user.models import User
|
||||
from app.utils.prompts.chatgpt_prompt import ChatgptService
|
||||
from app.utils.prompts.prompts import yt_upload_prompt
|
||||
from app.video.models import Video
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
redis_seo_client = Redis(
|
||||
host=db_settings.REDIS_HOST,
|
||||
port=db_settings.REDIS_PORT,
|
||||
db=0,
|
||||
decode_responses=True,
|
||||
)
|
||||
|
||||
|
||||
class SeoService:
|
||||
"""유튜브 SEO 비즈니스 로직 서비스"""
|
||||
|
||||
async def get_youtube_seo_description(
|
||||
self,
|
||||
task_id: str,
|
||||
current_user: User,
|
||||
session: AsyncSession,
|
||||
content_type: str = "video",
|
||||
video_id: int | None = None,
|
||||
task_id: str | None = None,
|
||||
) -> YoutubeDescriptionResponse:
|
||||
"""
|
||||
유튜브 SEO description 생성
|
||||
"""저장된 SNS 메타데이터를 반환하거나, 없으면 생성 후 video에 저장합니다."""
|
||||
video = None
|
||||
if video_id is not None:
|
||||
video = await self._get_owned_video(video_id, current_user.user_uuid, session)
|
||||
elif task_id:
|
||||
video = await self._get_owned_video_by_task(
|
||||
task_id, current_user.user_uuid, session
|
||||
)
|
||||
|
||||
Redis 캐시 확인 후 miss이면 GPT로 생성하고 캐싱.
|
||||
if video is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="해당하는 영상을 찾을 수 없습니다.",
|
||||
)
|
||||
|
||||
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} / key: {cache_key}"
|
||||
f"[SEO_SERVICE] Load metadata - user: {current_user.user_uuid} / video_id: {video.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}")
|
||||
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)
|
||||
if has_stored_sns_metadata(video):
|
||||
return self._response_from_video(video)
|
||||
|
||||
result = await self.generate_and_save_for_video(video.id, session)
|
||||
if result is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"video_id '{video.id}'에 해당하는 영상을 찾을 수 없습니다.",
|
||||
)
|
||||
await session.commit()
|
||||
return result
|
||||
|
||||
async def _generate_ssul_seo(
|
||||
async def get_ssul_seo(
|
||||
self,
|
||||
content_id: str,
|
||||
content_id: int,
|
||||
current_user: User,
|
||||
session: AsyncSession,
|
||||
) -> YoutubeDescriptionResponse:
|
||||
"""썰박스 콘텐츠용 SEO 생성 — ADO2 와 **다른 프롬프트**(시트 ssul_upload)를 쓴다.
|
||||
|
||||
ADO2 는 업장 마케팅 분석 보고서 기반의 광고 영상 SEO 지만, 썰박스는
|
||||
병맛 역사 썰툰이라 톤이 완전히 다르다. 태그도 GPT 가 함께 만든다
|
||||
(ADO2 처럼 재사용할 마케팅 분석 target_keywords 가 없다).
|
||||
"""
|
||||
"""썰박스 콘텐츠용 SEO 생성 — ADO2 와 다른 프롬프트(시트 ssul_upload)를 쓴다."""
|
||||
from app.ssulbox.constants import SCENARIO_NAMES
|
||||
from app.ssulbox.models import SsulContent
|
||||
from app.utils.prompts.chatgpt_prompt import ChatgptService
|
||||
from app.utils.prompts.prompts import get_ssul_upload_prompt
|
||||
|
||||
try:
|
||||
content = (
|
||||
await session.execute(
|
||||
select(SsulContent).where(
|
||||
SsulContent.id == int(content_id),
|
||||
SsulContent.id == content_id,
|
||||
SsulContent.user_uuid == current_user.user_uuid,
|
||||
SsulContent.is_deleted.is_(False),
|
||||
)
|
||||
@@ -125,31 +116,97 @@ class SeoService:
|
||||
detail=f"썰박스 SEO 생성에 실패했습니다. : {str(e)}",
|
||||
)
|
||||
|
||||
async def generate_and_save_for_video(
|
||||
self,
|
||||
video_id: int,
|
||||
session: AsyncSession,
|
||||
) -> YoutubeDescriptionResponse | None:
|
||||
"""GPT로 SEO를 생성해 지정한 video 행에 저장합니다. 워커/온디맨드 공용."""
|
||||
video_result = await session.execute(select(Video).where(Video.id == video_id))
|
||||
video = video_result.scalar_one_or_none()
|
||||
if video is None:
|
||||
logger.warning(f"[SEO_SERVICE] Video NOT FOUND - video_id: {video_id}")
|
||||
return None
|
||||
|
||||
if has_stored_sns_metadata(video):
|
||||
return self._response_from_video(video)
|
||||
|
||||
result = await self._generate_seo_description(video.task_id, session)
|
||||
apply_sns_metadata(video, result.title, result.description, result.keywords)
|
||||
await session.flush()
|
||||
logger.info(f"[SEO_SERVICE] Saved metadata - video_id: {video_id}")
|
||||
return result
|
||||
|
||||
async def _get_owned_video(
|
||||
self,
|
||||
video_id: int,
|
||||
user_uuid: str,
|
||||
session: AsyncSession,
|
||||
) -> Video | None:
|
||||
result = await session.execute(
|
||||
select(Video)
|
||||
.join(Project, Project.id == Video.project_id)
|
||||
.where(
|
||||
Video.id == video_id,
|
||||
Project.user_uuid == user_uuid,
|
||||
Video.is_deleted.is_(False),
|
||||
)
|
||||
)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
async def _get_owned_video_by_task(
|
||||
self,
|
||||
task_id: str,
|
||||
user_uuid: str,
|
||||
session: AsyncSession,
|
||||
) -> Video | None:
|
||||
result = await session.execute(
|
||||
select(Video)
|
||||
.join(Project, Project.id == Video.project_id)
|
||||
.where(
|
||||
Video.task_id == task_id,
|
||||
Project.user_uuid == user_uuid,
|
||||
Video.is_deleted.is_(False),
|
||||
)
|
||||
.order_by(Video.created_at.desc())
|
||||
.limit(1)
|
||||
)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
async def _generate_seo_description(
|
||||
self,
|
||||
task_id: str,
|
||||
current_user: User,
|
||||
session: AsyncSession,
|
||||
) -> YoutubeDescriptionResponse:
|
||||
"""GPT를 사용하여 SEO description 생성"""
|
||||
logger.info(f"[SEO_SERVICE] Generating SEO - user: {current_user.user_uuid}")
|
||||
from app.utils.prompts.chatgpt_prompt import ChatgptService
|
||||
from app.utils.prompts.prompts import yt_upload_prompt
|
||||
|
||||
logger.info(f"[SEO_SERVICE] Generating SEO - task_id: {task_id}")
|
||||
|
||||
try:
|
||||
project_result = await session.execute(
|
||||
select(Project)
|
||||
.where(
|
||||
Project.task_id == task_id,
|
||||
Project.user_uuid == current_user.user_uuid,
|
||||
)
|
||||
.where(Project.task_id == task_id)
|
||||
.order_by(Project.created_at.desc())
|
||||
.limit(1)
|
||||
)
|
||||
project = project_result.scalar_one_or_none()
|
||||
if project is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"task_id '{task_id}'에 해당하는 Project를 찾을 수 없습니다.",
|
||||
)
|
||||
|
||||
marketing_result = await session.execute(
|
||||
select(MarketingIntel).where(MarketingIntel.id == project.marketing_intelligence)
|
||||
)
|
||||
marketing_intelligence = marketing_result.scalar_one_or_none()
|
||||
if marketing_intelligence is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="마케팅 인텔리전스를 찾을 수 없습니다.",
|
||||
)
|
||||
|
||||
hashtags = marketing_intelligence.intel_result["target_keywords"]
|
||||
|
||||
@@ -161,12 +218,13 @@ class SeoService:
|
||||
),
|
||||
"language": project.language,
|
||||
"target_keywords": hashtags,
|
||||
"industry": project.industry or "", # 크롤 시 분류해 Project에 저장한 업종 enum
|
||||
"industry": project.industry or "",
|
||||
}
|
||||
|
||||
# 업종 분기는 프롬프트 내부 {industry}로 처리하므로 단일 프롬프트 사용
|
||||
chatgpt = ChatgptService(timeout=180)
|
||||
yt_seo_output = await chatgpt.generate_structured_output(yt_upload_prompt, yt_seo_input_data)
|
||||
yt_seo_output = await chatgpt.generate_structured_output(
|
||||
yt_upload_prompt, yt_seo_input_data
|
||||
)
|
||||
|
||||
return YoutubeDescriptionResponse(
|
||||
title=yt_seo_output.title,
|
||||
@@ -174,6 +232,8 @@ class SeoService:
|
||||
keywords=hashtags,
|
||||
)
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"[SEO_SERVICE] EXCEPTION - error: {e}")
|
||||
raise HTTPException(
|
||||
@@ -181,18 +241,12 @@ class SeoService:
|
||||
detail=f"유튜브 SEO 생성에 실패했습니다. : {str(e)}",
|
||||
)
|
||||
|
||||
async def _get_from_redis(self, task_id: str) -> YoutubeDescriptionResponse | None:
|
||||
field = f"task_id:{task_id}"
|
||||
yt_seo_info = await redis_seo_client.hget(YOUTUBE_SEO_HASH, field)
|
||||
if yt_seo_info:
|
||||
return YoutubeDescriptionResponse(**json.loads(yt_seo_info))
|
||||
return None
|
||||
|
||||
async def _set_to_redis(self, task_id: str, yt_seo: YoutubeDescriptionResponse) -> None:
|
||||
field = f"task_id:{task_id}"
|
||||
yt_seo_info = json.dumps(yt_seo.model_dump(), ensure_ascii=False)
|
||||
await redis_seo_client.hset(YOUTUBE_SEO_HASH, field, yt_seo_info)
|
||||
await redis_seo_client.expire(YOUTUBE_SEO_HASH, 3600)
|
||||
def _response_from_video(self, video: Video) -> YoutubeDescriptionResponse:
|
||||
return YoutubeDescriptionResponse(
|
||||
title=video.title or "",
|
||||
description=video.description or "",
|
||||
keywords=list(video.hashtags or []),
|
||||
)
|
||||
|
||||
|
||||
seo_service = SeoService()
|
||||
@@ -0,0 +1,36 @@
|
||||
"""SNS 업로드용 영상 메타데이터 비교/반영 헬퍼."""
|
||||
|
||||
from app.video.models import Video
|
||||
|
||||
|
||||
def has_stored_sns_metadata(video: Video) -> bool:
|
||||
"""video 행에 SNS 제목이 이미 저장되어 있는지 확인합니다."""
|
||||
return bool(video.title)
|
||||
|
||||
|
||||
def sns_metadata_changed(
|
||||
video: Video,
|
||||
title: str,
|
||||
description: str | None,
|
||||
tags: list[str] | None,
|
||||
) -> bool:
|
||||
"""게시 폼 값이 저장된 SNS 메타데이터와 다른지 비교합니다."""
|
||||
stored_tags = list(video.hashtags or [])
|
||||
incoming_tags = list(tags or [])
|
||||
return (
|
||||
(video.title or "") != title
|
||||
or (video.description or "") != (description or "")
|
||||
or stored_tags != incoming_tags
|
||||
)
|
||||
|
||||
|
||||
def apply_sns_metadata(
|
||||
video: Video,
|
||||
title: str,
|
||||
description: str | None,
|
||||
hashtags: list[str] | None,
|
||||
) -> None:
|
||||
"""video 행에 SNS 메타데이터를 반영합니다."""
|
||||
video.title = title
|
||||
video.description = description
|
||||
video.hashtags = list(hashtags or [])
|
||||
@@ -26,6 +26,7 @@ from app.social.schemas import (
|
||||
SocialUploadRequest,
|
||||
)
|
||||
from app.social.services.account_service import SocialAccountService
|
||||
from app.social.services.sns_metadata import apply_sns_metadata, sns_metadata_changed
|
||||
from app.social.worker.upload_task import process_social_upload
|
||||
from app.user.models import User
|
||||
from app.home.models import Project
|
||||
@@ -113,6 +114,14 @@ class SocialUploadService:
|
||||
detail="영상이 아직 준비되지 않았습니다. 영상 생성이 완료된 후 시도해주세요.",
|
||||
)
|
||||
|
||||
if body.content_type != "ssul" and sns_metadata_changed(
|
||||
video, body.title, body.description, body.tags
|
||||
):
|
||||
apply_sns_metadata(video, body.title, body.description, body.tags)
|
||||
logger.info(
|
||||
f"[UPLOAD_SERVICE] video SNS 메타데이터 갱신 - video_id: {body.video_id}"
|
||||
)
|
||||
|
||||
# 2. 소셜 계정 조회 및 소유권 검증
|
||||
account = await self._account_service.get_account_by_id(
|
||||
user_uuid=current_user.user_uuid,
|
||||
|
||||
Reference in new issue
Block a user