Compare commits

...
17 Commits
Author SHA1 Message Date
skkim 3854aef320 feat: 삭제된 콘텐츠의 대기·예약 업로드 정리와 실행 가드 추가 2026-10-16 11:29:42 +09:00
skkim cf6949acf7 fix: 무빙 포스터 목록의 SNS 메타데이터 노출 2026-10-16 11:29:42 +09:00
skkim 550dfd5709 chore: 마이그레이션 SQL 적용 스크립트 추가 2026-10-16 11:12:33 +09:00
skkim 1ede2d8e18 fix: p2v SEO 생성 대상을 완료(done) 상태로 제한 2026-10-16 10:40:08 +09:00
skkim 1ab978f02a feat: content_type 에 p2v_video 를 열어 업로드·SEO 를 활성화 2026-10-16 10:32:28 +09:00
skkim 142c459c26 docs: p2v_upload 시트 B3 를 yt_upload 형식 문안으로 교체 2026-10-16 10:30:13 +09:00
skkim c0540c2230 docs: p2v_upload 시트 문안 추가 2026-10-16 10:26:26 +09:00
skkim 6890c7c2bb feat: p2v 공유 페이지가 저장된 제목·설명을 우선 사용 2026-10-16 10:26:03 +09:00
skkim 81a554193c feat: 업로드 워커가 p2v_video 원본 URL 을 읽도록 분기 추가 2026-10-16 10:25:36 +09:00
skkim 951a1721b5 feat: 업로드 서비스에 p2v_video 대상 분기 추가 2026-10-16 10:24:42 +09:00
skkim ccf80b2cbf feat: p2v_video SNS SEO 생성·저장 서비스 추가 2026-10-16 10:23:38 +09:00
skkim 1b700bd1bb feat: p2v_upload SEO 프롬프트 스키마와 입력 구성 추가 2026-10-16 10:22:43 +09:00
skkim c7e1c4c81b feat: p2v_video 업로드용 스키마와 모델 컬럼 추가 2026-10-16 10:21:54 +09:00
skkim 073b6b302f docs: p2v_video YouTube 업로드 구현 계획 추가 2026-10-16 10:19:08 +09:00
skkim b17f1949cb docs: p2v_video YouTube 업로드 연동 설계 추가 2026-10-16 10:13:21 +09:00
skkim 71ed33d047 refactor: p2v credits_used 컬럼을 higgsfield_credits로 변경 2026-10-16 10:12:58 +09:00
skkim 23a2ab4013 feat: p2v_video 공유 페이지 설명에 내레이션 사용 2026-10-15 16:47:39 +09:00
27 changed files with 2006 additions and 41 deletions

No files matched your search

+4
View File
@@ -15,6 +15,8 @@ from app.p2v.services.i2v import MIN_LONG_EDGE_PX
from app.p2v.services.motion import plan_motion
from app.p2v.models import PosterAliveTask
from app.database.session import get_session
from app.social.models import SocialUpload
from app.social.upload_cleanup import delete_pending_uploads
from app.user.dependencies.auth import get_current_user
from app.user.models import User
@@ -171,5 +173,7 @@ async def delete(task_id: int, user: User = Depends(get_current_user),
if task.status in (QUEUED, RUNNING):
raise HTTPException(409, "대기 중이거나 진행 중인 작업은 삭제할 수 없습니다. 끝난 뒤 지워주세요")
task.is_deleted = True
# 소프트 삭제라 FK CASCADE 가 안 돈다 — 아직 게시되지 않은(대기·예약) 업로드를 같이 지운다
await delete_pending_uploads(session, SocialUpload.p2v_video_id, task_id)
await session.commit()
return {"id": task_id, "removed": True}
+5 -2
View File
@@ -11,7 +11,8 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.database.session import get_session
from app.p2v.constants import JOB_TYPE_PLAYREEL, JOB_TYPE_VIDEO
from app.p2v.schemas.public import P2vDetailResponse
from app.p2v.services.public_content import fetch_public, like_state, poster_of
from app.p2v.services.public_content import (fetch_public, like_state, narration_text_of,
poster_of)
from app.user.dependencies.auth import get_current_user_optional
from app.user.models import User
from app.utils.upload_blob_as_request import to_playback_url
@@ -57,7 +58,9 @@ async def share_page(
raise HTTPException(404, "공유 가능한 콘텐츠를 찾을 수 없습니다.")
html = build_p2v_share_html(
P2vShareData(ctype=ctype, content_id=row.id, poster_url=poster_of(ctype, row),
name=row.name),
name=row.name, title=getattr(row, "title", None),
description=(getattr(row, "description", None)
or narration_text_of(ctype, row))),
share_url=resolve_share_url(
request.headers,
str(request.url).split("?", maxsplit=1)[0],
+1 -1
View File
@@ -48,7 +48,7 @@ def base_view(task, state_type) -> dict:
"stages": ordered_stages(task, state_type),
"error": error_view(task),
"created_at": task.created_at.timestamp(),
"credits_used": task.credits_used,
"credits_used": task.higgsfield_credits,
"queue_size": 0,
}
+7 -1
View File
@@ -56,7 +56,8 @@ class TaskBase(Base):
error_stage: Mapped[str | None] = mapped_column(String(32))
error_detail: Mapped[str | None] = mapped_column("error", Text)
credits_used: Mapped[float] = mapped_column(Float, default=0.0)
# Higgsfield 등 외부 생성에 쓴 크레딧. 사용자 크레딧(credit_transaction)과 별개
higgsfield_credits: Mapped[float] = mapped_column(Float, default=0.0)
# 좋아요·댓글이 붙는 콘텐츠라 행을 지우지 않고 숨긴다 (썰박스와 같은 소프트 삭제)
is_deleted: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False,
@@ -122,6 +123,11 @@ class PosterAliveTask(TaskBase):
video_width: Mapped[int | None] = mapped_column(Integer)
video_height: Mapped[int | None] = mapped_column(Integer)
# ⑧ SNS 업로드 메타데이터 — p2v_upload 프롬프트가 만들어 저장한다 (video / ssul_content 와 같은 이름)
title: Mapped[str | None] = mapped_column(String(100))
description: Mapped[str | None] = mapped_column(Text)
hashtags: Mapped[list | None] = mapped_column(JSON)
class PlayreelTask(TaskBase):
"""공연 상품페이지 URL → 30초 롱컷"""
+8
View File
@@ -60,6 +60,14 @@ def poster_of(ctype: str, row) -> str | None:
return row.thumbnail_url if ctype == JOB_TYPE_VIDEO else playreel_thumbnail_url(row)
def narration_text_of(ctype: str, row) -> str | None:
"""공유 설명으로 쓰는 내레이션 한 줄. 무빙 포스터만 지원하고 없으면 None."""
if ctype != JOB_TYPE_VIDEO:
return None
lines = [str(line).strip() for line in row.narration_lines or [] if line]
return " ".join(line for line in lines if line) or None
async def like_state(
session: AsyncSession, ctype: str, content_id: int, user_uuid: str | None
) -> tuple[int, bool]:
+30
View File
@@ -0,0 +1,30 @@
"""p2v_video SNS SEO 프롬프트 입력 구성 — 순수 함수만 둔다(DB·시트 접근 없음)."""
from app.p2v.constants import JOB_TYPE_VIDEO
from app.p2v.services.public_content import narration_text_of
TITLE_LIMIT = 100 # SocialUploadRequest.title max_length 및 p2v_video.title 컬럼 길이
def build_seo_input(row) -> dict:
"""`poster_metadata` + 내레이션으로 P2vUploadPromptInput 용 dict 를 만든다.
포스터 분석이 아직 없으면(event_name 없음) ValueError — GPT 호출 전에 막는다.
"""
metadata = row.poster_metadata or {}
event_name = str(metadata.get("event_name") or "").strip()
if not event_name:
raise ValueError("포스터 분석 정보(event_name)가 아직 없습니다.")
return {
"event_name": event_name,
"date_text": str(metadata.get("date_text") or ""),
"place": str(metadata.get("place") or ""),
"category": str(metadata.get("category") or ""),
"keywords": ", ".join(str(k) for k in metadata.get("keywords") or []),
"region_guess": str(metadata.get("region_guess") or ""),
"narration": narration_text_of(JOB_TYPE_VIDEO, row) or "",
}
def clamp_title(title: str, limit: int = TITLE_LIMIT) -> str:
"""GPT 가 만든 제목이 업로드 제한(100자)을 넘으면 잘라 낸다."""
return title.strip()[:limit]
+2 -2
View File
@@ -142,7 +142,7 @@ async def run_upscale(session: AsyncSession, task: PlayreelTask) -> None:
result.image)
task.upscale_credits = result.credits
task.upscale_variant = result.variant
task.credits_used += result.credits
task.higgsfield_credits += result.credits
task.state = PlayreelState.ANALYZE
await session.commit()
@@ -227,7 +227,7 @@ async def run_i2v(session: AsyncSession, task: PlayreelTask) -> None:
task.clip_model = result.model
task.clip_credits = result.credits
task.title_gate = result.title_gate.model_dump()
task.credits_used += result.credits
task.higgsfield_credits += result.credits
task.state = PlayreelState.HYBRID
await session.commit()
+1 -1
View File
@@ -124,7 +124,7 @@ async def run_i2v(session: AsyncSession, task: PosterAliveTask) -> None:
task.clip_model = result.model
task.clip_credits = result.credits
task.title_gate = result.title_gate.model_dump()
task.credits_used += result.credits
task.higgsfield_credits += result.credits
task.state = PosterAliveState.RENDER
await session.commit()
+12
View File
@@ -44,6 +44,18 @@ async def youtube_seo_description(
)
return await seo_service.get_ssul_seo(content_id, current_user, session)
if request_body.content_type == "p2v_video":
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="P2V SEO 에는 video_id 또는 숫자 task_id 가 필요합니다.",
)
return await seo_service.get_p2v_seo(content_id, current_user, session)
return await seo_service.get_youtube_seo_description(
current_user,
session,
+18 -4
View File
@@ -38,6 +38,7 @@ class SocialUpload(Base):
id: 고유 식별자 (자동 증가)
user_uuid: 사용자 UUID (User.user_uuid 참조)
video_id: Video 외래키
p2v_video_id: P2V 무빙 포스터 외래키
social_account_id: SocialAccount 외래키
upload_seq: 업로드 순번 (동일 영상+채널 조합 내 순번, 관리자 추적용)
platform: 플랫폼 구분 (youtube, instagram, facebook, tiktok)
@@ -63,11 +64,11 @@ class SocialUpload(Base):
__tablename__ = "social_upload"
__table_args__ = (
# ADO2 영상과 썰박스 콘텐츠를 함께 담는다(2026-07-30 병합,
# docs/database-schema/migration_2026-07-30_social_upload_merge.sql).
# 대상은 video_id / content_id 중 **정확히 하나**만 채워진다.
# ADO2 영상 · 썰박스 콘텐츠 · P2V 무빙 포스터를 함께 담는다.
# 대상은 video_id / content_id / p2v_video_id 중 **정확히 하나**만 채워진다.
CheckConstraint(
"(video_id IS NULL) <> (content_id IS NULL)",
"(video_id IS NOT NULL) + (content_id IS NOT NULL) "
"+ (p2v_video_id IS NOT NULL) = 1",
name="ck_social_upload_one_target",
),
Index("idx_social_upload_user_uuid", "user_uuid"),
@@ -86,6 +87,12 @@ class SocialUpload(Base):
"social_account_id",
"upload_seq",
),
Index(
"idx_social_upload_p2v_video_seq",
"p2v_video_id",
"social_account_id",
"upload_seq",
),
{
"mysql_engine": "InnoDB",
"mysql_charset": "utf8mb4",
@@ -128,6 +135,13 @@ class SocialUpload(Base):
nullable=True,
comment="썰박스 콘텐츠 id (ADO2 업로드면 NULL)",
)
p2v_video_id: Mapped[Optional[int]] = mapped_column(
# p2v_video.id 는 BIGINT 다 (FK 타입 불일치 방지).
BigInteger,
ForeignKey("p2v_video.id", ondelete="CASCADE"),
nullable=True,
comment="P2V 무빙 포스터 id (다른 종류 업로드면 NULL)",
)
social_account_id: Mapped[int] = mapped_column(
Integer,
+2 -2
View File
@@ -10,11 +10,11 @@ from pydantic import BaseModel, ConfigDict, Field, model_validator
class YoutubeDescriptionRequest(BaseModel):
"""유튜브 SEO Description 제안 요청"""
content_type: Literal["video", "ssul"] = Field(
content_type: Literal["video", "ssul", "p2v_video"] = Field(
default="video", description="콘텐츠 종류"
)
video_id: Optional[int] = Field(
None, description="ADO2 video.id 또는 썰박스 ssul_content.id"
None, description="ADO2 video.id, 썰박스 ssul_content.id 또는 p2v_video.id"
)
task_id: Optional[str] = Field(
None,
+6 -4
View File
@@ -13,12 +13,12 @@ from app.social.constants import PrivacyStatus, UploadStatus
class SocialUploadRequest(BaseModel):
"""소셜 업로드 요청"""
# ⚠️ video_id 는 content_type 안에서만 유일하다 — video.id 와 ssul_content.id 는
# 각각 1부터 시작하는 독립 시퀀스라 값이 겹친다. content_type 없이 썰박스 id 를
# ⚠️ video_id 는 content_type 안에서만 유일하다 — video.id · ssul_content.id · p2v_video.id 는
# 각각 1부터 시작하는 독립 시퀀스라 값이 겹친다. content_type 없이 다른 종류의 id 를
# 보내면 **id 가 겹치는 남의 ADO2 영상이 업로드된다.**
content_type: Literal["video", "ssul"] = Field(
content_type: Literal["video", "ssul", "p2v_video"] = Field(
default="video",
description="콘텐츠 종류 (video: ADO2 영상, ssul: 썰박스)",
description="콘텐츠 종류 (video: ADO2 영상, ssul: 썰박스, p2v_video: P2V 무빙 포스터)",
)
video_id: int = Field(..., description="업로드할 콘텐츠 ID (content_type 안에서만 유일)")
social_account_id: int = Field(..., description="업로드할 소셜 계정 ID (연동 계정 목록의 id)")
@@ -87,6 +87,7 @@ class SocialUploadStatusResponse(BaseModel):
# 썰박스 업로드면 video_id 가 None 이고 content_id 가 채워진다 (정확히 하나만)
video_id: Optional[int] = Field(None, description="ADO2 영상 ID (썰박스면 None)")
content_id: Optional[int] = Field(None, description="썰박스 콘텐츠 ID (ADO2 면 None)")
p2v_video_id: Optional[int] = Field(None, description="P2V 무빙 포스터 ID (다른 종류면 None)")
social_account_id: int = Field(..., description="소셜 계정 ID")
upload_seq: int = Field(..., description="업로드 순번 (동일 영상+채널 조합 내 순번)")
platform: str = Field(..., description="플랫폼명")
@@ -131,6 +132,7 @@ class SocialUploadHistoryItem(BaseModel):
# 썰박스 업로드면 video_id 가 None 이고 content_id 가 채워진다 (정확히 하나만)
video_id: Optional[int] = Field(None, description="ADO2 영상 ID (썰박스면 None)")
content_id: Optional[int] = Field(None, description="썰박스 콘텐츠 ID (ADO2 면 None)")
p2v_video_id: Optional[int] = Field(None, description="P2V 무빙 포스터 ID (다른 종류면 None)")
social_account_id: int = Field(..., description="소셜 계정 ID")
upload_seq: int = Field(..., description="업로드 순번 (동일 영상+채널 조합 내 순번)")
platform: str = Field(..., description="플랫폼명")
+84
View File
@@ -3,6 +3,7 @@
ADO2 영상은 제목/설명/해시태그를 video 테이블에 저장합니다.
썰박스는 별도 프롬프트로 생성합니다.
P2V 무빙 포스터는 시트 p2v_upload 프롬프트로 생성합니다.
"""
import json
@@ -14,6 +15,8 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.home.models import MarketingIntel, Project
from app.social.schemas import YoutubeDescriptionResponse
from app.p2v.models import PosterAliveTask
from app.p2v.services.seo_input import build_seo_input, clamp_title
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
@@ -150,6 +153,87 @@ class SeoService:
keywords=out.keywords,
)
async def get_p2v_seo(
self,
content_id: int,
current_user: User,
session: AsyncSession,
) -> YoutubeDescriptionResponse:
"""P2V 무빙 포스터용 SEO 생성 — 시트 p2v_upload 프롬프트를 쓴다."""
row = (
await session.execute(
select(PosterAliveTask).where(
PosterAliveTask.id == content_id,
PosterAliveTask.user_id == current_user.user_uuid,
PosterAliveTask.is_deleted.is_(False),
PosterAliveTask.status == "done",
)
)
).scalar_one_or_none()
if row is None:
raise HTTPException(status_code=404, detail="콘텐츠를 찾을 수 없습니다.")
if has_stored_sns_metadata(row):
return self._response_from_row(row)
try:
result = await self.generate_and_save_for_p2v(content_id, session)
except ValueError as e:
# 포스터 분석(poster_metadata)이 아직 없다 — GPT 를 부르기 전에 막는다
raise HTTPException(status_code=409, detail=str(e))
except HTTPException:
raise
except Exception as e:
logger.error(f"[SEO_SERVICE] P2V EXCEPTION - error: {e}")
raise HTTPException(
status_code=500,
detail=f"P2V SEO 생성에 실패했습니다. : {str(e)}",
)
if result is None:
raise HTTPException(status_code=404, detail="콘텐츠를 찾을 수 없습니다.")
await session.commit()
return result
async def generate_and_save_for_p2v(
self,
content_id: int,
session: AsyncSession,
) -> YoutubeDescriptionResponse | None:
"""GPT로 P2V SNS 메타데이터를 생성해 저장합니다 (제목은 100자로 자름)."""
row = await session.get(PosterAliveTask, content_id)
if row is None:
logger.warning(f"[SEO_SERVICE] p2v_video NOT FOUND - id: {content_id}")
return None
if has_stored_sns_metadata(row):
return self._response_from_row(row)
result = await self._generate_p2v_seo_description(row)
title = clamp_title(result.title)
apply_sns_metadata(row, title, result.description, result.keywords)
await session.flush()
logger.info(f"[SEO_SERVICE] Saved p2v metadata - id: {content_id}")
return YoutubeDescriptionResponse(
title=title, description=result.description, keywords=result.keywords
)
async def _generate_p2v_seo_description(
self,
row: PosterAliveTask,
) -> YoutubeDescriptionResponse:
"""p2v_upload 프롬프트로 제목/설명/해시태그를 생성합니다."""
from app.utils.prompts.chatgpt_prompt import ChatgptService
from app.utils.prompts.prompts import get_p2v_upload_prompt
input_data = build_seo_input(row) # event_name 없으면 ValueError (GPT 호출 전)
chatgpt = ChatgptService(timeout=180)
out = await chatgpt.generate_structured_output(get_p2v_upload_prompt(), input_data)
return YoutubeDescriptionResponse(
title=out.title,
description=out.description,
keywords=out.keywords,
)
async def generate_and_save_for_video(
self,
video_id: int,
+29 -2
View File
@@ -30,6 +30,7 @@ from app.social.services.sns_metadata import apply_sns_metadata, sns_metadata_ch
from app.social.worker.upload_task import process_social_upload
from app.user.models import User
from app.home.models import Project
from app.p2v.models import PosterAliveTask
from app.ssulbox.models import SsulContent
from app.video.models import Video
@@ -69,7 +70,30 @@ class SocialUploadService:
# ⚠️ 소유자 필터가 필수다. 대상 id 는 클라이언트가 보내는 값이라, 안 거르면
# **남의 콘텐츠를 자기 SNS 채널에 업로드**할 수 있다(계정 소유권만 검증하고
# 콘텐츠 소유권을 안 보면 IDOR 이 된다).
if body.content_type == "ssul":
if body.content_type == "p2v_video":
target_col = SocialUpload.p2v_video_id
# ⚠️ 소유자·삭제 필터 필수 — 안 거르면 남의 영상이 내 채널에 올라간다(IDOR).
# PosterAliveTask.user_id 는 user_uuid 컬럼의 속성 이름이다.
p2v_row = (
await session.execute(
select(PosterAliveTask).where(
PosterAliveTask.id == body.video_id,
PosterAliveTask.user_id == current_user.user_uuid,
PosterAliveTask.is_deleted.is_(False),
)
)
).scalar_one_or_none()
if not p2v_row:
logger.warning(f"[UPLOAD_SERVICE] P2V 영상 없음 - id: {body.video_id}")
raise VideoNotFoundError(video_id=body.video_id)
if p2v_row.status != "done" or not p2v_row.video_url:
logger.warning(f"[UPLOAD_SERVICE] P2V 영상 미완성 - id: {body.video_id}")
raise VideoNotFoundError(
video_id=body.video_id,
detail="영상이 아직 준비되지 않았습니다. 영상 생성이 완료된 후 시도해주세요.",
)
target = p2v_row
elif body.content_type == "ssul":
target_col = SocialUpload.content_id
content = (
await session.execute(
@@ -203,9 +227,10 @@ class SocialUploadService:
# 5. 새 업로드 레코드 생성
social_upload = SocialUpload(
user_uuid=current_user.user_uuid,
# 종류에 따라 둘 중 하나만 채운다 (CHECK ck_social_upload_one_target 이 강제)
# 종류에 따라 셋 중 하나만 채운다 (CHECK ck_social_upload_one_target 이 강제)
video_id=body.video_id if body.content_type == "video" else None,
content_id=body.video_id if body.content_type == "ssul" else None,
p2v_video_id=body.video_id if body.content_type == "p2v_video" else None,
social_account_id=account.id,
upload_seq=next_seq,
platform=account.platform,
@@ -274,6 +299,7 @@ class SocialUploadService:
upload_id=upload.id,
video_id=upload.video_id,
content_id=upload.content_id,
p2v_video_id=upload.p2v_video_id,
social_account_id=upload.social_account_id,
upload_seq=upload.upload_seq,
platform=upload.platform,
@@ -368,6 +394,7 @@ class SocialUploadService:
upload_id=upload.id,
video_id=upload.video_id,
content_id=upload.content_id,
p2v_video_id=upload.p2v_video_id,
social_account_id=upload.social_account_id,
upload_seq=upload.upload_seq,
platform=upload.platform,
+44
View File
@@ -0,0 +1,44 @@
"""콘텐츠 삭제 시 아직 게시되지 않은 소셜 업로드 정리.
콘텐츠는 소프트 삭제(`is_deleted=True`)라 `social_upload` 의 FK `ON DELETE CASCADE` 가
작동하지 않는다. 지우지 않으면 예약 시각에 삭제된 영상이 게시된다.
가벼운 모듈로 둔다: `app.social.services` 패키지를 import 하면 업로드 서비스·워커까지
딸려 와서 P2V 라우터 등과 순환 import 가 생길 수 있다.
"""
import logging
from sqlalchemy import delete
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import InstrumentedAttribute
from app.social.constants import UploadStatus
from app.social.models import SocialUpload
logger = logging.getLogger(__name__)
async def delete_pending_uploads(
session: AsyncSession,
target_column: InstrumentedAttribute,
target_id: int,
) -> int:
"""대상 콘텐츠의 대기 중(PENDING) 업로드 — 즉시 대기와 예약 — 를 삭제하고 삭제한 수를 돌려준다.
`target_column` 은 `SocialUpload.video_id` / `content_id` / `p2v_video_id` 중 하나다.
게시 중(UPLOADING)과 이미 끝난 기록(COMPLETED/FAILED/CANCELLED)은 건드리지 않는다.
커밋하지 않는다 — 호출부가 소프트 삭제와 같은 트랜잭션으로 커밋한다.
"""
result = await session.execute(
delete(SocialUpload).where(
target_column == target_id,
SocialUpload.status == UploadStatus.PENDING.value,
)
)
removed = result.rowcount or 0
if removed:
logger.info(
f"[UPLOAD_CLEANUP] 삭제된 콘텐츠의 대기 업로드 제거 - "
f"column: {target_column.key}, id: {target_id}, count: {removed}"
)
return removed
+39 -14
View File
@@ -20,6 +20,7 @@ from app.dashboard.tasks import insert_dashboard
from app.database.session import BackgroundSessionLocal
from app.social.constants import SocialPlatform, UploadStatus
from app.social.exceptions import TokenExpiredError, UploadQuotaExceededError
from app.p2v.models import PosterAliveTask
from app.social.models import SocialUpload
from app.social.services import social_account_service
from app.social.uploader import get_uploader
@@ -143,6 +144,31 @@ async def _increment_retry_count(upload_id: int) -> int:
return 0
async def _resolve_source(session, upload: SocialUpload) -> tuple[Optional[str], bool]:
"""업로드가 가리키는 콘텐츠의 (영상 URL, 삭제 여부). 병합 스키마라 채워진 FK 가 곧 종류다.
콘텐츠 행이 없으면 (None, False) — 삭제가 아니라 "찾을 수 없음"으로 구분한다.
"""
if upload.p2v_video_id is not None:
row = (
await session.execute(
select(PosterAliveTask).where(PosterAliveTask.id == upload.p2v_video_id)
)
).scalar_one_or_none()
return (row.video_url, bool(row.is_deleted)) if row else (None, False)
if upload.content_id is not None:
row = (
await session.execute(
select(SsulContent).where(SsulContent.id == upload.content_id)
)
).scalar_one_or_none()
return (row.video_url, bool(row.is_deleted)) if row else (None, False)
row = (
await session.execute(select(Video).where(Video.id == upload.video_id))
).scalar_one_or_none()
return (row.result_movie_url, bool(row.is_deleted)) if row else (None, False)
async def process_social_upload(upload_id: int) -> None:
"""
소셜 미디어 업로드 처리
@@ -168,27 +194,26 @@ async def process_social_upload(upload_id: int) -> None:
logger.error(f"[SOCIAL_UPLOAD] 업로드 레코드 없음 - upload_id: {upload_id}")
return
# 2. 대상 영상 조회.
# 병합 스키마: video_id / content_id 중 정확히 하나만 채워져 있다(CHECK).
# 채워진 쪽이 곧 종류다 — 썰박스면 ssul_content.video_url 을 쓴다.
if upload.content_id is not None:
content_result = await session.execute(
select(SsulContent).where(SsulContent.id == upload.content_id)
# 2. 대상 영상 조회. video_id / content_id / p2v_video_id 중 정확히 하나만 채워져 있다(CHECK).
source_url, target_deleted = await _resolve_source(session, upload)
# 삭제된 콘텐츠는 올리지 않는다 — 소프트 삭제라 예약·재시도 업로드가 남아 있을 수 있다.
if target_deleted:
logger.warning(
f"[SOCIAL_UPLOAD] 삭제된 콘텐츠라 업로드하지 않음 - upload_id: {upload_id}"
)
content = content_result.scalar_one_or_none()
source_url = content.video_url if content else None
else:
video_result = await session.execute(
select(Video).where(Video.id == upload.video_id)
await _update_upload_status(
upload_id=upload_id,
status=UploadStatus.CANCELLED,
error_message="삭제된 콘텐츠라 업로드하지 않았습니다.",
)
video = video_result.scalar_one_or_none()
source_url = video.result_movie_url if video else None
return
if not source_url:
logger.error(
f"[SOCIAL_UPLOAD] 영상 없음 또는 URL 없음 - "
f"upload_id: {upload_id}, video_id: {upload.video_id}, "
f"content_id: {upload.content_id}"
f"content_id: {upload.content_id}, p2v_video_id: {upload.p2v_video_id}"
)
await _update_upload_status(
upload_id=upload_id,
+17
View File
@@ -139,6 +139,23 @@ def get_ssul_upload_prompt() -> Prompt:
)
@lru_cache()
def get_p2v_upload_prompt() -> Prompt:
"""P2V 무빙 포스터 SNS 업로드 SEO 프롬프트 (시트: p2v_upload).
get_ssul_upload_prompt 와 같은 이유로 lazy 다 — 시트가 아직 없어도 앱 기동은 살고
P2V SEO 요청만 실패한다. _preload_all_sheets 목록에는 넣지 않는다.
템플릿 변수: {event_name} {date_text} {place} {category} {keywords} {region_guess} {narration}
"""
from app.utils.prompts.schemas import P2vUploadPromptInput, P2vUploadPromptOutput
return Prompt(
sheet_name="p2v_upload",
prompt_input_class=P2vUploadPromptInput,
prompt_output_class=P2vUploadPromptOutput,
)
@lru_cache()
def create_dynamic_subtitle_prompt(length: int, industry: str = "") -> Prompt:
# industry 인자는 캐시 구분/하위 호환용. 시트는 단일 'subtitle'로 통합됨.
+1
View File
@@ -1,6 +1,7 @@
from .lyric import LyricPromptInput, LyricPromptOutput
from .marketing import MarketingPromptInput, MarketingPromptOutput
from .ssulbox import SsulUploadPromptInput, SsulUploadPromptOutput
from .p2v import P2vUploadPromptInput, P2vUploadPromptOutput
from .youtube import YTUploadPromptInput, YTUploadPromptOutput
from .image import *
from .subtitle import SubtitlePromptInput, SubtitlePromptOutput
+28
View File
@@ -0,0 +1,28 @@
from typing import List
from pydantic import BaseModel, Field
# Input 정의
class P2vUploadPromptInput(BaseModel):
"""P2V 무빙 포스터 SNS 업로드 SEO 프롬프트 입력.
스프레드시트 시트명: `p2v_upload` (B2=모델, B3=템플릿).
템플릿에서 쓸 수 있는 변수:
{event_name} {date_text} {place} {category} {keywords} {region_guess} {narration}
"""
event_name: str = Field(..., description="행사·공연명")
date_text: str = Field(default="", description="일시 문구 (모르면 빈 문자열)")
place: str = Field(default="", description="장소")
category: str = Field(default="", description="분류 (축제/공연/전시/마켓/기타)")
keywords: str = Field(default="", description="포스터 분석 키워드 (쉼표로 이은 문자열)")
region_guess: str = Field(default="", description="추정 지역")
narration: str = Field(default="", description="영상 내레이션 문장 합본")
# Output 정의
class P2vUploadPromptOutput(BaseModel):
title: str = Field(..., description="쇼츠 제목 - 100자 이내, SEO")
description: str = Field(..., description="업로드 설명 - SEO/해시태그 포함")
keywords: List[str] = Field(..., description="태그 키워드 리스트")
+4 -2
View File
@@ -166,6 +166,8 @@ class P2vShareData:
content_id: int
poster_url: str | None
name: str | None = None
title: str | None = None
description: str | None = None
def build_p2v_share_html(
@@ -180,8 +182,8 @@ def build_p2v_share_html(
return _build_share_html(
detail_path=f"{path_prefix}/{data.content_id}",
poster_url=data.poster_url,
title=_share_title(data.name, fallback_title, fallback_store=fallback_title),
description=_share_description(None),
title=_share_title(data.title or data.name, fallback_title, fallback_store=fallback_title),
description=_share_description(data.description),
share_url=share_url,
frontend_base_url=frontend_base_url,
configured_default_image_url=configured_default_image_url,
+14 -6
View File
@@ -269,8 +269,15 @@ def _ssul_branch(where: list, sort_by: str) -> Select:
return select(*cols).where(*where)
def _p2v_branch(ctype: str, model, video_col, poster_col, sort_by: str) -> Select:
"""무빙 포스터·롱컷 공용. 포스터 컬럼이 없는 종류(롱컷)는 NULL 로 두고 `_to_items` 가 채운다."""
def _p2v_branch(
ctype: str, model, video_col, poster_col, sort_by: str, *, has_sns_metadata: bool = False
) -> Select:
"""무빙 포스터·롱컷 공용. 포스터 컬럼이 없는 종류(롱컷)는 NULL 로 두고 `_to_items` 가 채운다.
`has_sns_metadata` 인 종류(무빙 포스터)는 title/description/hashtags 를 **저장된 SNS 메타데이터**로
내려보낸다(ADO2·썰박스와 같은 의미 — 없으면 NULL). 작업 이름을 title 로 내리면 업로드 모달이
SEO 자동 채움을 건너뛰고 빈 설명·태그로 업로드해 저장값을 덮어쓴다.
"""
cols = [
literal(ctype).label("ctype"),
model.id.label("cid"),
@@ -280,9 +287,9 @@ def _p2v_branch(ctype: str, model, video_col, poster_col, sort_by: str) -> Selec
model.created_at.label("created_at"),
literal("").label("task_id"),
(poster_col if poster_col is not None else literal(None, String)).label("poster_url"),
model.name.label("title"),
literal(None, String).label("description"),
literal(None, String).label("hashtags"),
(model.title if has_sns_metadata else model.name).label("title"),
(model.description if has_sns_metadata else literal(None, String)).label("description"),
(model.hashtags if has_sns_metadata else literal(None, String)).label("hashtags"),
]
if sort_by == SORT_LIKE:
cols.append(_p2v_like_subq(ctype, model).label("sort_value"))
@@ -293,7 +300,8 @@ def _p2v_branch(ctype: str, model, video_col, poster_col, sort_by: str) -> Selec
def _p2v_video_branch(where: list, sort_by: str) -> Select:
return _p2v_branch(CT_P2V_VIDEO, PosterAliveTask, PosterAliveTask.video_url,
PosterAliveTask.thumbnail_url, sort_by).where(*where)
PosterAliveTask.thumbnail_url, sort_by,
has_sns_metadata=True).where(*where)
def _p2v_playreel_branch(where: list, sort_by: str) -> Select:
@@ -0,0 +1,30 @@
-- ============================================================
-- Migration: P2V 잡 테이블 credits_used → higgsfield_credits 이름 변경
-- Date: 2026-10-16
-- Description: credits_used 가 사용자 크레딧(credit_transaction, P2V_CREDITS_*)과
-- 혼동돼 Higgsfield 등 외부 생성 비용임이 드러나도록 이름을 바꾼다.
-- 값·타입은 그대로다 (FLOAT NOT NULL DEFAULT 0).
-- 선행 조건: migration_2026-10-14_p2v_pipeline.sql 또는
-- migration_2026-10-15_p2v_bootstrap.sql 적용 완료
-- 주의: 코드(app/p2v/models.py 의 higgsfield_credits)와 같은 배포에서 적용한다.
-- SQL 만 먼저 적용되면 옛 코드가, 코드만 먼저 나가면 새 코드가 컬럼을 못 찾는다.
-- 워커를 멈춘 상태에서 적용하고 새 코드로 다시 올린다.
-- ============================================================
-- 0) 확인: 컬럼 존재
-- SHOW COLUMNS FROM p2v_video LIKE 'credits_used';
-- SHOW COLUMNS FROM p2v_playreel LIKE 'credits_used';
ALTER TABLE p2v_video
CHANGE COLUMN credits_used higgsfield_credits FLOAT NOT NULL DEFAULT 0
COMMENT 'Higgsfield 등 외부 생성에 쓴 크레딧 (castad 크레딧과 별개)';
ALTER TABLE p2v_playreel
CHANGE COLUMN credits_used higgsfield_credits FLOAT NOT NULL DEFAULT 0
COMMENT 'Higgsfield 등 외부 생성에 쓴 크레딧 (castad 크레딧과 별개)';
-- ROLLBACK
-- ALTER TABLE p2v_video
-- CHANGE COLUMN higgsfield_credits credits_used FLOAT NOT NULL DEFAULT 0;
-- ALTER TABLE p2v_playreel
-- CHANGE COLUMN higgsfield_credits credits_used FLOAT NOT NULL DEFAULT 0;
@@ -0,0 +1,46 @@
-- ============================================================
-- Migration: p2v_video YouTube 업로드 연동
-- Date: 2026-10-16
-- Description: - p2v_video 에 SNS 메타데이터(title/description/hashtags) 추가
-- - social_upload 에 p2v_video_id 추가, 대상 CHECK 를 "세 대상 중 정확히 하나"로 교체
-- 선행 조건: migration_2026-07-30_social_upload_merge.sql, migration_2026-10-15_p2v_bootstrap.sql 적용 완료
-- 대상: MySQL 8.0.16+ (CHECK 가 실제로 강제되는 버전)
-- 주의: 코드 배포와 같은 창에서 적용한다. SQL 만 먼저 적용돼도 옛 코드는 영향이 없다
-- (새 컬럼은 NULL 허용, 옛 CHECK 식은 새 CHECK 로 대체되며 기존 행은 모두 만족한다).
-- ============================================================
-- 0) 확인: 기존 행이 새 CHECK 를 만족하는지 (0 이어야 한다)
-- SELECT COUNT(*) FROM social_upload WHERE (video_id IS NOT NULL) + (content_id IS NOT NULL) <> 1;
-- SHOW COLUMNS FROM p2v_video LIKE 'title'; -- 비어 있어야 한다(아직 없음)
-- SHOW COLUMNS FROM social_upload LIKE 'p2v_video_id'; -- 비어 있어야 한다
-- 1) p2v_video — SNS 메타데이터
ALTER TABLE p2v_video
ADD COLUMN title VARCHAR(100) NULL COMMENT 'SNS 업로드 제목',
ADD COLUMN description TEXT NULL COMMENT 'SNS 업로드 설명',
ADD COLUMN hashtags JSON NULL COMMENT 'SNS 해시태그 목록';
-- 2) social_upload — P2V 대상 컬럼 + FK + 순번 인덱스(FK 인덱스 겸용)
ALTER TABLE social_upload
ADD COLUMN p2v_video_id BIGINT NULL
COMMENT 'P2V 무빙 포스터 id (다른 종류 업로드면 NULL)' AFTER content_id,
ADD CONSTRAINT fk_social_upload_p2v_video
FOREIGN KEY (p2v_video_id) REFERENCES p2v_video (id) ON DELETE CASCADE,
ADD INDEX idx_social_upload_p2v_video_seq (p2v_video_id, social_account_id, upload_seq);
-- 3) 대상 CHECK 교체
ALTER TABLE social_upload DROP CHECK ck_social_upload_one_target;
ALTER TABLE social_upload
ADD CONSTRAINT ck_social_upload_one_target CHECK (
(video_id IS NOT NULL) + (content_id IS NOT NULL) + (p2v_video_id IS NOT NULL) = 1);
-- ROLLBACK (p2v_video 업로드 행이 있으면 먼저 지운다)
-- DELETE FROM social_upload WHERE p2v_video_id IS NOT NULL;
-- ALTER TABLE social_upload DROP CHECK ck_social_upload_one_target;
-- ALTER TABLE social_upload
-- ADD CONSTRAINT ck_social_upload_one_target CHECK ((video_id IS NULL) <> (content_id IS NULL));
-- ALTER TABLE social_upload
-- DROP FOREIGN KEY fk_social_upload_p2v_video,
-- DROP INDEX idx_social_upload_p2v_video_seq,
-- DROP COLUMN p2v_video_id;
-- ALTER TABLE p2v_video DROP COLUMN title, DROP COLUMN description, DROP COLUMN hashtags;
+112
View File
@@ -0,0 +1,112 @@
# 시트 `p2v_upload` 문안
스프레드시트(`PROMPT_SPREADSHEET`)에 `p2v_upload` 시트를 만들고 아래 값을 붙여넣는다.
**B2 = 모델, B3 = 템플릿** (다른 셀은 코드가 읽지 않는다).
문안 원본 사본: `zzz/prompt/p2v_upload.txt` (`yt_upload.txt` 형식, gitignore 대상이라 이 문서가 기준).
코드: `app/utils/prompts/prompts.py` 의 `get_p2v_upload_prompt()` (lazy — 시트가 없으면 P2V SEO 요청만 실패).
## B2 (모델)
```
gpt-5.4-mini-2026-03-17
```
기존 `ssul_upload`, `yt_upload` 시트 B2 와 같은 값이다(2026-10-16 확인). 바꾸려면 그 시트와 같이 맞출 것.
## B3 (템플릿)
```
[ROLE]
You are a YouTube Shorts SEO/AEO content strategist who specializes in Korean local events, performances, exhibitions, festivals and markets.
First read {category}, then specialize as the expert for that category.
You create search-optimized, emotionally appealing, and action-driving titles, descriptions and tags for a short poster-motion video, based on the event information and the video narration.
Your goal is to:
- Increase search visibility
- Improve click-through rate
- Reflect the event's mood and positioning
- Trigger emotional interest
- Encourage the category's primary action (visit / attend / check details) through a subtle CTA
[INPUT]
Event Name: {event_name}
Date: {date_text}
Place: {place}
Region: {region_guess}
Category: {category} // one of: 축제 | 공연 | 전시 | 마켓 | 기타
Poster Keywords: {keywords}
Video Narration: {narration}
[MISSING INFORMATION RULE]
Date, Place, Region, Poster Keywords and Video Narration may be empty. Never invent missing information.
Do not state dates, times, places, prices, ticket/booking links, line-ups, or phone numbers that are not in [INPUT].
If a field is empty, simply leave that part out of the sentence. Never output an empty placeholder or a bare label.
[CATEGORY ADAPTATION] — Read {category}, then apply the matching profile.
- 축제: context=설렘·현장감·함께하는 시간 | action=방문 | CTA tone='이번 주말, 어디로 떠날지 고민 중이신가요?'
- 공연: context=몰입·감동·특별한 하루 | action=관람·예매 확인 | CTA tone='감동이 있는 무대를 찾고 계신가요?'
- 전시: context=영감·여유·감상 | action=관람 | CTA tone='조용히 영감을 채울 전시를 찾고 계신가요?'
- 마켓: context=발견·구경하는 재미·취향 | action=방문 | CTA tone='취향 가득한 마켓을 찾고 계신가요?'
- 기타: context=새로운 경험·궁금증 | action=확인·방문 | CTA tone='새로운 경험을 찾고 계신가요?'
[INTERNAL ANALYSIS – DO NOT OUTPUT]
Analyze from the event information and the narration (interpreted for {category}):
- Core concept and mood of the event
- Main emotional promise to the viewer
- Likely target audience
- Top 2–3 appeal points that are actually stated in [INPUT]
- Search intent behind the poster keywords and the region
- The moment that would make the viewer want to attend
Use these to guide: Title tone, Opening CTA line, Emotional hook in the first sentences.
[TITLE GENERATION RULES]
The title must:
- Include the event name; wrap the event name in single quotes (e.g. '행사명')
- Include 1–2 high-intent keywords (region, category, or a poster keyword) when natural
- Reflect the emotional positioning of the {category}
- Suggest a desirable moment relevant to the event
- Sound like a natural YouTube title, not an advertisement
- Contain no hashtags (#); tags go only in keywords
Length rules: Hard limit 100 chars (the upload is rejected above 100); target 45–65 chars; event name or primary keyword in the first half.
Avoid: ALL CAPS, excessive symbols, more than one emoji, price/promotion language, hard-sell expressions.
[DESCRIPTION GENERATION RULES]
Character rules: Max 1,000 chars; critical info (event name, date, place) within the first 150 chars when those are provided.
Language style (mandatory): Polite Korean honorific style; replace '있나요?' with '있으신가요?'; do not start sentences with '이곳은'; always wrap the event name in single quotes; avoid vague location words alone (use specific phrasing from {place} and {region_guess} when provided).
Structure:
1. Opening CTA (first line): a question or gentle suggestion in honorific tone, using the {category} CTA tone.
2. Core Introduction: event name in quotes + date + place (only those provided) + main keyword.
3. Mood & Experience: reflect the tone of {narration}; paraphrase it, do not copy it word for word.
4. Key Highlights (2–3 short lines): only appeal points that are stated in [INPUT].
5. Soft Closing Line: one gentle, non-salesy recommendation-tone sentence. Do not add booking links or contact details.
6. Last line: 5–8 hashtags in '#tag' form, ending with #shorts.
[SEO & AEO RULES]
Naturally integrate 2–4 words from {keywords} and the region; avoid keyword stuffing; use conversational, search-like phrasing; optimize for YouTube search, Google video results, and AI answer summaries.
Keywords appear in: Title (1–2), first 150 chars of description, highlights.
[KEYWORDS RULES]
- 8–12 items, each a plain keyword string WITHOUT '#'.
- Composition: event name → region/place (only if provided) → category → poster keywords → shorts.
- Joined with commas, the whole list must not exceed 500 chars.
[LANGUAGE RULE]
All output written entirely in Korean. No mixed languages (the tag 'shorts' is allowed).
[OUTPUT FORMAT – STRICT]
title:
description:
keywords:
No explanations. No headings. No extra text.
```
## 사용 가능한 변수
`{event_name}` `{date_text}` `{place}` `{category}` `{keywords}` `{region_guess}` `{narration}`
(`app/utils/prompts/schemas/p2v.py` 의 `P2vUploadPromptInput`). 목록에 없는 `{...}` 는 치환되지 않고 그대로 남는다.
## 출력 형식
코드의 `P2vUploadPromptOutput` 이 강제한다: `title`(str), `description`(str), `keywords`(list[str]).
제목이 100자를 넘으면 서비스가 저장 전에 100자로 자른다.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,70 @@
# p2v_video YouTube 업로드 연동 설계
작성일: 2026-10-16 / 상태: 설계 승인됨(사용자), 구현 전
## 목표
`p2v_video`(포스터 → 8초 숏폼) 영상을 ADO2·썰박스 영상처럼 YouTube 에 업로드한다.
제목·설명·해시태그는 구글 시트 `p2v_upload` 프롬프트로 생성해 `p2v_video` 행에 저장하고,
업로드 흐름(예약·중복 방지·소유자 검증)과 공유 페이지(썸네일·제목·설명)는 기존 콘텐츠와 같게 한다.
## 범위
- 포함: `p2v_video` 만. 백엔드(`o2o-castad-backend`).
- 제외: `p2v_playreel`(롱컷), 프론트엔드의 업로드 UI(`content_type: "p2v_video"` 전송), 실제 YouTube 업로드 실행.
## 결정 사항
- `social_upload` 대상 지정은 **컬럼 추가**(`p2v_video_id`). 다형 컬럼은 쓰지 않는다.
- 업로드는 롤아웃 **마지막 단계**에서만 연다(`content_type` Literal 에 `"p2v_video"` 추가).
- 공유 우선순위: 제목 = 저장된 `title` → `name`, 설명 = 저장된 `description` → 내레이션 → 기본 문구.
- 시트 `p2v_upload` 는 서비스 계정이 readonly 라 코드로 만들 수 없다. 문안 파일을 만들어 사용자가 시트에 붙여넣는다.
## 설계
### 1. DB (마이그레이션 SQL 작성만, 적용은 사용자 확인 후)
파일: `docs/database-schema/migration_2026-10-16_p2v_youtube_upload.sql`
- `p2v_video` 추가: `title VARCHAR(100) NULL`, `description TEXT NULL`, `hashtags JSON NULL` (`ssul_content` 와 같은 타입).
- `social_upload` 추가: `p2v_video_id BIGINT NULL`, FK `p2v_video(id)` ON DELETE CASCADE,
인덱스 `(p2v_video_id, social_account_id, upload_seq)`.
- CHECK `ck_social_upload_one_target` 을 DROP 후 재생성: 세 대상 중 정확히 하나만 NOT NULL
(`(video_id IS NOT NULL) + (content_id IS NOT NULL) + (p2v_video_id IS NOT NULL) = 1`). MySQL 8.0.16+ 전제.
- ROLLBACK SQL 을 파일 하단에 둔다.
### 2. SEO 생성
- `app/utils/prompts/prompts.py`: `get_p2v_upload_prompt()` — `lru_cache` lazy. 시트가 없어도 앱은 기동하고 P2V SEO 요청만 500.
`_preload_all_sheets` 목록에는 넣지 않는다(썰박스와 동일).
- `app/utils/prompts/schemas/`: `P2vUploadPromptInput` / `P2vUploadPromptOutput`.
- 입력: `event_name`, `date_text`, `place`, `category`, `keywords`, `region_guess`(출처 `poster_metadata`), `narration`(내레이션 문장 합본).
- 출력: `title`, `description`, `keywords`.
- `seo_service`: `get_p2v_seo` / `generate_and_save_for_p2v` (소유자·`is_deleted`·`status` 검증 후 생성·저장, 저장값 있으면 재사용).
제목은 100자 초과 시 저장 전에 잘라 업로드 제한(`max_length=100`)과 맞춘다.
- `seo.py` 라우터: `content_type == "p2v_video"` 분기.
### 3. 업로드 경로
- `upload_schema.py`, `seo_schema.py`: `content_type` Literal 에 `"p2v_video"` 추가(**롤아웃 마지막**).
- `upload_service.py`: `p2v_video` 를 `user_id == 현재 사용자`, `is_deleted = False`, `status = 'done'`, `video_url` 존재로 조회.
소유자 필터는 필수(없으면 타인 영상 업로드 IDOR). 중복 확인·순번 채번은 `target_col = SocialUpload.p2v_video_id`.
- `upload_task.py`: `upload.p2v_video_id` 가 채워진 업로드는 `p2v_video.video_url` 을 원본으로 사용.
- `social/models.py`: `p2v_video_id` 매핑. `p2v/models.py`: `title`/`description`/`hashtags` 매핑.
### 4. 공유 연결
- `P2vShareData` 에 `title` 추가. `build_p2v_share_html` 이 저장된 제목·설명을 우선 사용.
- `public.py` 가 `row.title`, `row.description` 을 전달(`p2v_video` 한정, `getattr` 로 playreel 은 None).
### 5. 시트 문안
- `docs/` 아래에 `p2v_upload` 시트의 B2(모델)·B3(템플릿) 문안 파일을 만든다. 변수: `{event_name} {date_text} {place} {category} {keywords} {region_guess} {narration}`.
- 출력 형식·제목 100자 이내·해시태그 규칙을 문안에 명시한다.
## 롤아웃 순서
1. (완료) `credits_used` → `higgsfield_credits` 이름 변경 커밋.
2. 마이그레이션 SQL 작성 → 사용자가 적용.
3. 모델·SEO·서비스·워커·공유 코드 추가(Literal 은 열지 않음 → 업로드는 계속 막힌 상태).
4. 시트 문안 파일 작성 → 사용자가 시트에 붙여넣기 → SEO 호출로 확인.
5. 마지막에 Literal 에 `"p2v_video"` 추가(이 시점에 업로드가 열림).
## 검증
- `zzz/` 에 테스트: 프롬프트 입력 구성, 제목 길이 처리, 공유 우선순위, 서비스 분기(모킹).
- `uv run python -m pytest zzz/...`, `uv run ruff check`.
- YouTube 실업로드·운영 DB 실행은 하지 않는다(사용자 확인 필요).
## 위험
- 마이그레이션과 코드 배포 순서가 어긋나면 `p2v_video` 조회가 `Unknown column` 으로 실패한다 → 워커 중지 후 SQL 적용 → 새 코드.
- 시트 `p2v_upload` 가 없으면 P2V SEO 가 500 이다(앱 기동은 영향 없음).
+189
View File
@@ -0,0 +1,189 @@
#!/usr/bin/env bash
# 마이그레이션 SQL 적용 스크립트.
#
# 이 프로젝트는 Alembic 을 쓰지 않는다 — docs/database-schema/*.sql 을 이 스크립트로 적용한다.
# 접속 정보는 앱(config.py DatabaseSettings)과 같은 환경변수를 쓴다:
# MYSQL_HOST (기본 localhost) / MYSQL_PORT (3306) / MYSQL_USER / MYSQL_PASSWORD / MYSQL_DB
# 우선순위: 이미 설정된 환경변수 > .env 파일 > 기본값.
# 저장소 루트의 .env 를 자동으로 읽는다(위 5개 키만. source 하지 않고 파싱하므로 다른 값은 건드리지 않는다).
# 비밀번호는 명령줄 인자로 넘기지 않는다(프로세스 목록에 노출). MYSQL_PASSWORD 가 없으면 프롬프트로 받는다.
#
# 사용법:
# scripts/apply_migration.sh [옵션] <sql 파일>
#
# 옵션:
# --dry-run 접속하지 않고 대상과 실행될 문장만 보여 준다 (기본으로 먼저 해 볼 것)
# --check-absent T.C 적용 전에 컬럼 T.C(테이블.컬럼)가 **없어야** 한다. 이미 있으면 중단 (여러 번 지정 가능)
# --allow-destructive DROP TABLE / DELETE FROM / TRUNCATE 가 포함된 파일도 허용
# --env-file PATH 읽을 .env 파일 (기본: 저장소 루트의 .env, 없으면 건너뜀)
# --no-env-file .env 를 읽지 않는다 (환경변수만 사용)
# --docker-image IMAGE mysql 클라이언트가 없을 때 쓸 이미지 (기본 mysql:8.4, docker 필요)
# -h, --help 이 도움말
#
# 예) 2026-10-16 p2v YouTube 업로드 마이그레이션:
# scripts/apply_migration.sh --dry-run \
# --check-absent p2v_video.title --check-absent social_upload.p2v_video_id \
# docs/database-schema/migration_2026-10-16_p2v_youtube_upload.sql
# (dry-run 이 의도대로면 --dry-run 을 빼고 실행. mysql 클라이언트가 없으면 docker 로 실행하며 localhost 는 host.docker.internal 로 자동 변환)
#
# ⚠️ MySQL DDL 은 트랜잭션으로 묶이지 않는다. 파일 중간에서 실패하면 앞 문장은 이미 적용된 상태다.
# 그래서 --check-absent 로 사전 점검하고, 실패하면 SQL 파일 하단의 ROLLBACK 주석을 참고해 수동 복구한다.
# ⚠️ 확인 프롬프트 없이 바로 적용한다 — 먼저 --dry-run 으로 대상 DB 를 확인할 것.
# ⚠️ 운영 DB 는 적용 전에 백업(runbook 의 mysqldump)과 워커 중지를 먼저 할 것.
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
ENV_FILE="$REPO_ROOT/.env"
USE_ENV_FILE=1
DOCKER_IMAGE="mysql:8.4"
DRY_RUN=0
ALLOW_DESTRUCTIVE=0
CHECK_ABSENT=()
SQL_FILE=""
usage() { sed -n '2,/^set -euo/p' "$0" | sed '$d' | sed 's/^# \{0,1\}//'; }
die() { echo "오류: $*" >&2; exit 1; }
while [[ $# -gt 0 ]]; do
case "$1" in
--dry-run) DRY_RUN=1 ;;
--allow-destructive) ALLOW_DESTRUCTIVE=1 ;;
--check-absent)
[[ $# -ge 2 ]] || die "--check-absent 에는 테이블.컬럼 값이 필요합니다"
[[ "$2" =~ ^[A-Za-z0-9_]+\.[A-Za-z0-9_]+$ ]] || die "--check-absent 형식은 테이블.컬럼 입니다: $2"
CHECK_ABSENT+=("$2"); shift ;;
--env-file)
[[ $# -ge 2 ]] || die "--env-file 에는 파일 경로가 필요합니다"
ENV_FILE="$2"; shift ;;
--no-env-file) USE_ENV_FILE=0 ;;
--docker-image)
[[ $# -ge 2 ]] || die "--docker-image 에는 이미지 이름이 필요합니다"
DOCKER_IMAGE="$2"; shift ;;
-h|--help) usage; exit 0 ;;
-*) die "알 수 없는 옵션: $1 (--help 참고)" ;;
*) [[ -z "$SQL_FILE" ]] || die "SQL 파일은 하나만 지정할 수 있습니다"; SQL_FILE="$1" ;;
esac
shift
done
[[ -n "$SQL_FILE" ]] || { usage; die "SQL 파일을 지정하세요"; }
[[ -f "$SQL_FILE" ]] || die "파일이 없습니다: $SQL_FILE"
# .env 에서 MYSQL_* 키만 읽는다. source 하지 않는다 — 값에 공백·특수문자가 있어도 깨지지 않고,
# 파일 안의 다른 내용이 셸 명령으로 실행되지 않는다. 이미 설정된 환경변수는 덮어쓰지 않는다.
# 값은 출력하지 않는다(비밀번호 노출 방지) — 어떤 키를 읽었는지만 알린다.
LOADED_FROM_ENV_FILE=()
load_env_file() {
local file="$1" line key value
while IFS= read -r line || [[ -n "$line" ]]; do
line="${line%$'\r'}" # Windows 줄바꿈(CRLF) 제거
[[ "$line" =~ ^[[:space:]]*(export[[:space:]]+)?(MYSQL_(HOST|PORT|USER|PASSWORD|DB))[[:space:]]*=(.*)$ ]] || continue
key="${BASH_REMATCH[2]}"
value="${BASH_REMATCH[4]}"
value="${value#"${value%%[![:space:]]*}"}" # 앞 공백 제거
if [[ "$value" =~ ^\"(.*)\"[[:space:]]*$ ]] || [[ "$value" =~ ^\'(.*)\'[[:space:]]*$ ]]; then
value="${BASH_REMATCH[1]}" # 양쪽 따옴표 제거
fi
if [[ -z "${!key:-}" ]]; then # 환경변수가 없거나 비어 있을 때만
export "$key=$value"
LOADED_FROM_ENV_FILE+=("$key")
fi
done < "$file"
}
if [[ "$USE_ENV_FILE" -eq 1 ]]; then
if [[ -f "$ENV_FILE" ]]; then
load_env_file "$ENV_FILE"
elif [[ "$ENV_FILE" != "$REPO_ROOT/.env" ]]; then
die "--env-file 로 지정한 파일이 없습니다: $ENV_FILE" # 명시한 파일이 없으면 오류, 기본 .env 가 없는 건 허용
fi
fi
MYSQL_HOST="${MYSQL_HOST:-localhost}"
MYSQL_PORT="${MYSQL_PORT:-3306}"
MYSQL_USER="${MYSQL_USER:-}"
MYSQL_DB="${MYSQL_DB:-}"
[[ -n "$MYSQL_USER" ]] || die "MYSQL_USER 가 필요합니다"
[[ -n "$MYSQL_DB" ]] || die "MYSQL_DB 가 필요합니다"
# 주석(-- ...)과 빈 줄을 뺀 실행 대상 문장만 본다. (SQL 파일의 ROLLBACK 은 주석이라 여기 안 잡힌다)
# (전부 주석이면 grep 이 1 을 반환해 set -e 로 조용히 죽으므로 || true 로 아래 안내 메시지까지 가게 한다)
ACTIVE_SQL="$( { grep -vE '^[[:space:]]*--' "$SQL_FILE" || true; } | sed 's/[[:space:]]--[[:space:]].*$//' | sed '/^[[:space:]]*$/d')"
[[ -n "$ACTIVE_SQL" ]] || die "실행할 문장이 없습니다(전부 주석): $SQL_FILE"
STATEMENT_COUNT="$(printf '%s\n' "$ACTIVE_SQL" | grep -c ';' || true)"
if [[ "$ALLOW_DESTRUCTIVE" -eq 0 ]] \
&& printf '%s\n' "$ACTIVE_SQL" | grep -Eiq '(DROP[[:space:]]+(TABLE|DATABASE)|TRUNCATE|DELETE[[:space:]]+FROM)'; then
die "데이터를 지우는 문장(DROP TABLE / DROP DATABASE / TRUNCATE / DELETE FROM)이 있습니다. 의도한 것이면 --allow-destructive 를 붙이세요."
fi
echo "== 마이그레이션 적용 대상 =="
echo " 파일 : $SQL_FILE (실행 문장 약 ${STATEMENT_COUNT}개)"
echo " DB : ${MYSQL_USER}@${MYSQL_HOST}:${MYSQL_PORT}/${MYSQL_DB}"
if [[ ${#LOADED_FROM_ENV_FILE[@]} -gt 0 ]]; then
echo " 접속값 : ${ENV_FILE} 에서 읽음 (${LOADED_FROM_ENV_FILE[*]})"
else
echo " 접속값 : 환경변수 사용 (.env 에서 읽은 값 없음)"
fi
echo " 사전점검: ${CHECK_ABSENT[*]:-없음}"
echo
echo "== 실행될 문장 =="
printf '%s\n' "$ACTIVE_SQL"
echo
if [[ "$DRY_RUN" -eq 1 ]]; then
echo "[dry-run] DB 에 접속하지 않았습니다. 위 내용이 의도대로면 --dry-run 을 빼고 다시 실행하세요."
exit 0
fi
# 클라이언트 선택: 로컬 mysql 이 있으면 그것을, 없으면 docker 의 mysql 이미지를 쓴다.
CONNECT_HOST="$MYSQL_HOST" # docker 클라이언트일 때만 아래에서 바뀐다
if command -v mysql >/dev/null 2>&1; then
CLIENT=(mysql)
elif command -v docker >/dev/null 2>&1; then
# 컨테이너 안의 localhost 는 PC 가 아니라 컨테이너 자신이다 — PC 에서 도는 DB 를 가리키도록 바꾼다.
# (Docker Desktop 은 host.docker.internal 을 기본 제공, Linux 엔진은 --add-host 로 연결한다)
case "$MYSQL_HOST" in
localhost|127.0.0.1|::1)
echo "알림: docker 클라이언트라 접속 호스트 ${MYSQL_HOST} → host.docker.internal 로 바꿔 접속합니다 (PC 에서 실행 중인 DB)." >&2
CONNECT_HOST="host.docker.internal" ;;
esac
CLIENT=(docker run --rm -i --add-host=host.docker.internal:host-gateway -e MYSQL_PWD "$DOCKER_IMAGE" mysql)
else
die "mysql 클라이언트도 docker 도 없습니다. 'sudo apt install mysql-client' 로 설치하거나 docker 를 준비하세요."
fi
if [[ -z "${MYSQL_PASSWORD:-}" ]]; then
[[ -t 0 ]] || die "MYSQL_PASSWORD 가 없고 입력할 터미널도 없습니다"
read -r -s -p "DB 비밀번호(${MYSQL_USER}@${MYSQL_HOST}): " MYSQL_PASSWORD
echo
fi
export MYSQL_PWD="$MYSQL_PASSWORD"
run_mysql() {
"${CLIENT[@]}" -h "$CONNECT_HOST" -P "$MYSQL_PORT" -u "$MYSQL_USER" \
--default-character-set=utf8mb4 "$MYSQL_DB" "$@"
}
echo "접속 확인 중..."
run_mysql -N -B -e "SELECT CONCAT('connected: ', VERSION(), ' / ', DATABASE());" \
|| die "DB 접속에 실패했습니다"
for target in "${CHECK_ABSENT[@]:-}"; do
[[ -n "$target" ]] || continue
table="${target%%.*}"; column="${target##*.}"
found="$(run_mysql -N -B -e "SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = '${table}' AND column_name = '${column}';")"
if [[ "$found" != "0" ]]; then
die "이미 적용된 것으로 보입니다 — ${target} 컬럼이 존재합니다. 일부만 적용된 상태일 수 있으니 SQL 파일과 현재 스키마를 비교하세요."
fi
echo " 사전점검 통과: ${target} 없음"
done
echo "적용 중..."
if run_mysql --show-warnings < "$SQL_FILE"; then
echo "완료: $SQL_FILE → ${MYSQL_DB}"
else
echo "실패: 일부 문장만 적용됐을 수 있습니다. SQL 파일 하단의 ROLLBACK 주석을 참고해 상태를 확인하세요." >&2
exit 1
fi