From 073b6b302f9a80d3b529671cc506e1e0df661d8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=84=B1=EA=B2=BD?= Date: Fri, 16 Oct 2026 10:19:08 +0900 Subject: [PATCH] =?UTF-8?q?docs:=20p2v=5Fvideo=20YouTube=20=EC=97=85?= =?UTF-8?q?=EB=A1=9C=EB=93=9C=20=EA=B5=AC=ED=98=84=20=EA=B3=84=ED=9A=8D=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../plans/2026-10-16-p2v-youtube-upload.md | 1203 +++++++++++++++++ 1 file changed, 1203 insertions(+) create mode 100644 docs/superpowers/plans/2026-10-16-p2v-youtube-upload.md diff --git a/docs/superpowers/plans/2026-10-16-p2v-youtube-upload.md b/docs/superpowers/plans/2026-10-16-p2v-youtube-upload.md new file mode 100644 index 0000000..0b57103 --- /dev/null +++ b/docs/superpowers/plans/2026-10-16-p2v-youtube-upload.md @@ -0,0 +1,1203 @@ +# p2v_video YouTube 업로드 연동 Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** `p2v_video`(포스터 → 8초 숏폼) 영상을 ADO2·썰박스처럼 YouTube 에 업로드하고, 공유 페이지에 저장된 제목·설명을 쓴다. + +**Architecture:** `social_upload` 에 `p2v_video_id` FK 컬럼을 추가한다(CHECK 는 "세 대상 중 정확히 하나"). 제목·설명·해시태그는 시트 `p2v_upload` 프롬프트(lazy)로 생성해 `p2v_video` 행에 저장한다. 업로드를 여는 `content_type` Literal 변경은 **마지막 태스크**에서만 한다. + +**Tech Stack:** Python 3.13, FastAPI, SQLAlchemy(async), MySQL 8.0.16+, pydantic v2, gspread(시트 읽기 전용), pytest + pytest-asyncio, uv. + +**Spec:** `docs/superpowers/specs/2026-10-16-p2v-youtube-upload-design.md` + +## Global Constraints + +- 모든 DB 작업은 async/await. 타입 힌트 필수. Pydantic v2. +- 이 프로젝트는 Alembic 을 쓰지 않는다. 스키마 변경은 `docs/database-schema/` 에 SQL 파일로 쓰고 **사람이 수동 적용**한다. 에이전트는 운영·dev DB 에 직접 실행하지 않는다. +- 테스트 파일은 `zzz/` 아래에 둔다. 실행은 `uv run python -m pytest zzz/ -q` (`uv run pytest` 단독은 `config` import 실패). +- 린트: `uv run ruff check <파일>`. +- 커밋 메시지: `: <요약>` (feat/fix/refactor/docs/test/chore). main/master/develop 에 직접 커밋하지 않는다(현재 브랜치 `feature-three`). +- SNS 제목은 100자 이내(`SocialUploadRequest.title max_length=100`, 컬럼 `VARCHAR(100)`). +- 대상 조회에는 **소유자(`user_id`) + `is_deleted = False`** 필터가 필수다(없으면 타인 영상 업로드 IDOR). +- 범위는 `p2v_video`(`PosterAliveTask`)만. `p2v_playreel` 은 건드리지 않는다. +- 에이전트는 YouTube 실업로드·운영 DB 실행을 하지 않는다. 가짜 값만 테스트에 쓴다(실제 개인정보 금지). +- 관련 없는 포매팅·이름 변경을 섞지 않는다. 발견한 별도 문제는 코드를 고치지 말고 최종 보고에 적는다. + +## Review Focus + +1. 다른 사용자의 `p2v_video` id 로 업로드 요청 → 404(`VideoNotFoundError`), 업로드 레코드 미생성. (Task 4 테스트) +2. `video.id`·`ssul_content.id`·`p2v_video.id` 가 같은 값일 때 `content_type` 으로만 테이블이 갈리고 `social_upload` 에는 정확히 한 컬럼만 채워진다. (Task 4 테스트) +3. `poster_metadata` 가 비어 있거나 `event_name` 이 없으면 SEO 생성이 시트·GPT 호출 전에 409 로 끝난다. (Task 2·3 테스트) +4. GPT 제목이 100자를 넘으면 저장·업로드 전에 100자로 잘린다. (Task 2 테스트) +5. 시트 `p2v_upload` 가 없으면 앱 기동은 되고 P2V SEO 요청만 실패한다(`get_p2v_upload_prompt` lazy). (Task 2 테스트) +6. `Literal` 을 열기 전에는 `content_type="p2v_video"` 요청이 검증 단계에서 거부된다. (Task 7 시작 전 확인 테스트 / Task 7 에서 허용으로 전환) + +## File Structure + +| 파일 | 역할 | +|---|---| +| `docs/database-schema/migration_2026-10-16_p2v_youtube_upload.sql` (신규) | `p2v_video` 메타 컬럼, `social_upload.p2v_video_id`, CHECK 교체, ROLLBACK | +| `app/p2v/models.py` (수정) | `PosterAliveTask` 에 `title/description/hashtags` | +| `app/social/models.py` (수정) | `SocialUpload.p2v_video_id`, CHECK/Index | +| `app/utils/prompts/schemas/p2v.py` (신규), `schemas/__init__.py` (수정) | `P2vUploadPromptInput/Output` | +| `app/utils/prompts/prompts.py` (수정) | `get_p2v_upload_prompt()` lazy | +| `app/p2v/services/seo_input.py` (신규) | 순수 함수 `build_seo_input(row)`, `clamp_title(title)` | +| `app/social/services/seo_service.py` (수정) | `get_p2v_seo`, `generate_and_save_for_p2v` | +| `app/social/services/upload_service.py` (수정) | `p2v_video` 대상 분기·응답 매핑 | +| `app/social/worker/upload_task.py` (수정) | 원본 URL 분기 | +| `app/video/services/share_page.py`, `app/p2v/api/routers/v1/public.py` (수정) | 공유 제목·설명 우선순위 | +| `docs/prompts/p2v_upload_sheet.md` (신규) | 시트 B2/B3 문안(사용자가 붙여넣음) | +| `app/social/schemas/upload_schema.py`, `seo_schema.py`, `api/routers/v1/seo.py` (수정) | **마지막**: Literal 열기·응답 필드·라우터 분기 | +| `zzz/test_p2v_upload_*.py` (신규) | 태스크별 테스트 | + +--- + +### Task 1: 마이그레이션 SQL 과 모델 컬럼 + +**Files:** +- Create: `docs/database-schema/migration_2026-10-16_p2v_youtube_upload.sql` +- Modify: `app/p2v/models.py` (`PosterAliveTask`, `# ⑦ render` 블록 아래) +- Modify: `app/social/models.py` (`__table_args__`, `p2v_video_id` 컬럼, docstring) +- Test: `zzz/test_p2v_upload_models.py` + +**Interfaces:** +- Produces: `PosterAliveTask.title: str | None`, `.description: str | None`, `.hashtags: list | None`; + `SocialUpload.p2v_video_id: int | None`. 이후 태스크가 이 이름을 그대로 쓴다. + +- [ ] **Step 1: Write the failing test** + +```python +# zzz/test_p2v_upload_models.py +"""모델 메타데이터 검증 — DB 접속 없이 매핑만 본다. + + uv run python -m pytest zzz/test_p2v_upload_models.py -q +""" +from sqlalchemy import BigInteger, CheckConstraint, String, Text + +from app.p2v.models import PosterAliveTask +from app.social.models import SocialUpload + + +def test_p2v_video_has_sns_metadata_columns(): + cols = PosterAliveTask.__table__.c + assert isinstance(cols.title.type, String) and cols.title.type.length == 100 + assert isinstance(cols.description.type, Text) + assert "hashtags" in cols + assert cols.title.nullable and cols.description.nullable and cols.hashtags.nullable + + +def test_social_upload_has_p2v_video_id_fk(): + col = SocialUpload.__table__.c.p2v_video_id + assert isinstance(col.type, BigInteger) + assert col.nullable + targets = {fk.target_fullname for fk in col.foreign_keys} + assert targets == {"p2v_video.id"} + + +def test_social_upload_check_requires_exactly_one_target(): + checks = [c for c in SocialUpload.__table__.constraints if isinstance(c, CheckConstraint)] + one_target = next(c for c in checks if c.name == "ck_social_upload_one_target") + sql = str(one_target.sqltext) + for column in ("video_id", "content_id", "p2v_video_id"): + assert f"{column} IS NOT NULL" in sql + assert sql.rstrip().endswith("= 1") +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `uv run python -m pytest zzz/test_p2v_upload_models.py -q` +Expected: FAIL (`AttributeError`/`KeyError`: `title`, `p2v_video_id` 없음) + +- [ ] **Step 3: Write minimal implementation** + +`app/p2v/models.py` — import 에 `JSON`, `String`, `Text` 는 이미 있다. `PosterAliveTask` 의 `video_height` 아래에 추가: + +```python + # ⑧ 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) +``` + +`app/social/models.py` — `__table_args__` 의 CHECK 를 교체하고 인덱스를 추가: + +```python + # ADO2 영상 · 썰박스 콘텐츠 · P2V 무빙 포스터를 함께 담는다. + # 대상은 video_id / content_id / p2v_video_id 중 **정확히 하나**만 채워진다. + CheckConstraint( + "(video_id IS NOT NULL) + (content_id IS NOT NULL) " + "+ (p2v_video_id IS NOT NULL) = 1", + name="ck_social_upload_one_target", + ), +``` + +`idx_social_upload_content_seq` 인덱스 바로 아래에 추가: + +```python + Index( + "idx_social_upload_p2v_video_seq", + "p2v_video_id", + "social_account_id", + "upload_seq", + ), +``` + +`content_id` 컬럼 정의 바로 아래에 추가: + +```python + 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)", + ) +``` + +클래스 docstring 의 `video_id: Video 외래키` 줄 아래에 `p2v_video_id: P2V 무빙 포스터 외래키` 를 한 줄 추가한다. + +신규 `docs/database-schema/migration_2026-10-16_p2v_youtube_upload.sql`: + +```sql +-- ============================================================ +-- 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; +``` + +- [ ] **Step 4: Run test to verify it passes** + +Run: `uv run python -m pytest zzz/test_p2v_upload_models.py -q` → Expected: 3 passed +Run: `uv run ruff check app/p2v/models.py app/social/models.py` → Expected: All checks passed + +- [ ] **Step 5: Commit** + +```bash +git add docs/database-schema/migration_2026-10-16_p2v_youtube_upload.sql app/p2v/models.py app/social/models.py +git commit -m "feat: p2v_video 업로드용 스키마와 모델 컬럼 추가" +``` + +> ⚠️ SQL 파일은 작성만 한다. 적용은 사용자가 한다. 적용 전에는 코드를 배포하지 않는다 +> (새 모델 컬럼이 DB 에 없으면 `p2v_video` 조회가 `Unknown column` 으로 실패). +> **Task 1 커밋 이후 Task 2~6 구현은 로컬 테스트로 진행하고, 사용자가 SQL 적용을 알려오면 Task 7 로 간다.** + +--- + +### Task 2: P2V SEO 프롬프트 스키마와 입력 구성 + +**Files:** +- Create: `app/utils/prompts/schemas/p2v.py`, `app/p2v/services/seo_input.py` +- Modify: `app/utils/prompts/schemas/__init__.py`, `app/utils/prompts/prompts.py` +- Test: `zzz/test_p2v_upload_seo_input.py` + +**Interfaces:** +- Consumes: `narration_text_of(ctype, row)` (`app/p2v/services/public_content.py`), `JOB_TYPE_VIDEO`. +- Produces: + - `P2vUploadPromptInput(event_name, date_text, place, category, keywords: str, region_guess, narration)` + - `P2vUploadPromptOutput(title: str, description: str, keywords: list[str])` + - `get_p2v_upload_prompt() -> Prompt` (lazy, `lru_cache`) + - `build_seo_input(row) -> dict` — `poster_metadata.event_name` 없으면 `ValueError` + - `clamp_title(title: str, limit: int = 100) -> str` + +- [ ] **Step 1: Write the failing test** + +```python +# zzz/test_p2v_upload_seo_input.py +"""P2V SEO 입력 구성 검증 (순수 함수, DB·시트 없이). + + uv run python -m pytest zzz/test_p2v_upload_seo_input.py -q +""" +from types import SimpleNamespace + +import pytest + +from app.p2v.services.seo_input import build_seo_input, clamp_title +from app.utils.prompts.schemas import P2vUploadPromptInput, P2vUploadPromptOutput + +METADATA = { + "event_name": "테스트 재즈 페스티벌", + "date_text": "8월 30일 오후 7시", + "place": "테스트 야외무대", + "category": "축제", + "keywords": ["재즈", "야외공연"], + "region_guess": "테스트시", +} + + +def row(metadata=METADATA, lines=("첫 문장.", "둘째 문장.")): + return SimpleNamespace(poster_metadata=metadata, narration_lines=list(lines)) + + +def test_build_seo_input_maps_metadata_and_narration(): + data = build_seo_input(row()) + assert data["event_name"] == "테스트 재즈 페스티벌" + assert data["keywords"] == "재즈, 야외공연" + assert data["narration"] == "첫 문장. 둘째 문장." + P2vUploadPromptInput(**data) # 프롬프트 입력 스키마를 통과해야 한다 + + +@pytest.mark.parametrize("metadata", [None, {}, {"event_name": " "}]) +def test_build_seo_input_requires_event_name(metadata): + with pytest.raises(ValueError): + build_seo_input(row(metadata=metadata)) + + +def test_build_seo_input_without_narration_is_empty_string(): + assert build_seo_input(row(lines=()))["narration"] == "" + + +def test_clamp_title_cuts_to_limit(): + assert clamp_title("가" * 150) == "가" * 100 + assert clamp_title(" 짧은 제목 ") == "짧은 제목" + + +def test_output_schema_requires_all_fields(): + with pytest.raises(Exception): + P2vUploadPromptOutput(title="t", description="d") + + +def test_prompt_is_lazy_not_loaded_at_import(): + import app.utils.prompts.prompts as prompts + + assert "p2v_upload" not in prompts._sheet_cache # 시트는 호출 시점에만 읽는다 +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `uv run python -m pytest zzz/test_p2v_upload_seo_input.py -q` +Expected: FAIL (`ModuleNotFoundError: app.p2v.services.seo_input`) + +- [ ] **Step 3: Write minimal implementation** + +`app/utils/prompts/schemas/p2v.py`: + +```python +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="태그 키워드 리스트") +``` + +`app/utils/prompts/schemas/__init__.py` — 썰박스 import 줄(3행) 아래에 추가: + +```python +from .p2v import P2vUploadPromptInput, P2vUploadPromptOutput +``` + +`app/utils/prompts/prompts.py` — `get_ssul_upload_prompt()` 바로 아래(`create_dynamic_subtitle_prompt` 위)에 추가: + +```python +@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, + ) +``` + +`app/p2v/services/seo_input.py`: + +```python +"""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] +``` + +- [ ] **Step 4: Run test to verify it passes** + +Run: `uv run python -m pytest zzz/test_p2v_upload_seo_input.py -q` → Expected: 9 passed +Run: `uv run ruff check app/p2v/services/seo_input.py app/utils/prompts/schemas/p2v.py` → Expected: All checks passed + +- [ ] **Step 5: Commit** + +```bash +git add app/utils/prompts/schemas/p2v.py app/utils/prompts/schemas/__init__.py app/utils/prompts/prompts.py app/p2v/services/seo_input.py +git commit -m "feat: p2v_upload SEO 프롬프트 스키마와 입력 구성 추가" +``` + +--- + +### Task 3: SEO 서비스 — p2v_video 생성·저장 + +**Files:** +- Modify: `app/social/services/seo_service.py` +- Test: `zzz/test_p2v_upload_seo_service.py` + +**Interfaces:** +- Consumes: `build_seo_input`, `clamp_title` (Task 2), `get_p2v_upload_prompt` (Task 2), `has_stored_sns_metadata`, `apply_sns_metadata`, `PosterAliveTask` (Task 1 컬럼). +- Produces: `SeoService.get_p2v_seo(content_id: int, current_user, session) -> YoutubeDescriptionResponse`, + `SeoService.generate_and_save_for_p2v(content_id: int, session) -> YoutubeDescriptionResponse | None`, + `SeoService._generate_p2v_seo_description(row) -> YoutubeDescriptionResponse`. + +- [ ] **Step 1: Write the failing test** + +```python +# zzz/test_p2v_upload_seo_service.py +"""p2v_video SEO 서비스 검증 — GPT·시트·DB 는 가짜로 대체한다. + + uv run python -m pytest zzz/test_p2v_upload_seo_service.py -q +""" +from types import SimpleNamespace +from unittest.mock import AsyncMock, patch + +import pytest +from fastapi import HTTPException + +from app.social.schemas import YoutubeDescriptionResponse +from app.social.services.seo_service import SeoService + +METADATA = {"event_name": "테스트 페스티벌", "date_text": "", "place": "테스트장", + "category": "축제", "keywords": ["재즈"], "region_guess": ""} + + +def make_row(**kw): + base = dict(id=7, poster_metadata=METADATA, narration_lines=["문장."], + title=None, description=None, hashtags=None) + base.update(kw) + return SimpleNamespace(**base) + + +class FakeSession: + def __init__(self, row): + self.row, self.flushed, self.committed, self.statements = row, 0, 0, [] + + async def get(self, model, key): + return self.row + + async def execute(self, stmt): + self.statements.append(stmt) + return SimpleNamespace(scalar_one_or_none=lambda: self.row) + + async def flush(self): + self.flushed += 1 + + async def commit(self): + self.committed += 1 + + +@pytest.mark.asyncio +async def test_generate_saves_clamped_title_and_metadata(): + row = make_row() + gpt = YoutubeDescriptionResponse(title="가" * 150, description="설명", keywords=["a", "b"]) + service = SeoService() + with patch.object(service, "_generate_p2v_seo_description", AsyncMock(return_value=gpt)): + result = await service.generate_and_save_for_p2v(7, FakeSession(row)) + assert row.title == "가" * 100 + assert row.description == "설명" and row.hashtags == ["a", "b"] + assert result.title == "가" * 100 + + +@pytest.mark.asyncio +async def test_stored_metadata_is_reused_without_gpt(): + row = make_row(title="저장 제목", description="저장 설명", hashtags=["x"]) + service = SeoService() + gen = AsyncMock() + with patch.object(service, "_generate_p2v_seo_description", gen): + result = await service.generate_and_save_for_p2v(7, FakeSession(row)) + gen.assert_not_called() + assert result.title == "저장 제목" and result.keywords == ["x"] + + +@pytest.mark.asyncio +async def test_missing_metadata_returns_409_before_gpt(): + row = make_row(poster_metadata=None) + service = SeoService() + user = SimpleNamespace(user_uuid="u-1") + with pytest.raises(HTTPException) as err: + await service.get_p2v_seo(7, user, FakeSession(row)) + assert err.value.status_code == 409 + + +@pytest.mark.asyncio +async def test_get_p2v_seo_filters_by_owner_and_not_deleted(): + session = FakeSession(make_row(title="t", description="d", hashtags=[])) + await SeoService().get_p2v_seo(7, SimpleNamespace(user_uuid="u-1"), session) + sql = str(session.statements[0]) + assert "p2v_video.user_uuid" in sql and "p2v_video.is_deleted" in sql + + +@pytest.mark.asyncio +async def test_unknown_row_is_404(): + with pytest.raises(HTTPException) as err: + await SeoService().get_p2v_seo(7, SimpleNamespace(user_uuid="u-1"), FakeSession(None)) + assert err.value.status_code == 404 +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `uv run python -m pytest zzz/test_p2v_upload_seo_service.py -q` +Expected: FAIL (`AttributeError: 'SeoService' object has no attribute 'generate_and_save_for_p2v'`) + +- [ ] **Step 3: Write minimal implementation** + +`app/social/services/seo_service.py` — import 추가(기존 `from app.ssulbox.models import SsulContent` 근처): + +```python +from app.p2v.models import PosterAliveTask +from app.p2v.services.seo_input import build_seo_input, clamp_title +``` + +모듈 docstring 의 "썰박스는 별도 프롬프트로 생성합니다." 아래에 "P2V 무빙 포스터는 시트 p2v_upload 프롬프트로 생성합니다." 한 줄 추가. + +`generate_and_save_for_video` 메서드 바로 위(`get_ssul_seo` 계열 아래)에 메서드 3개 추가: + +```python + 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), + ) + ) + ).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, + ) +``` + +- [ ] **Step 4: Run test to verify it passes** + +Run: `uv run python -m pytest zzz/test_p2v_upload_seo_service.py -q` → Expected: 5 passed +Run: `uv run ruff check app/social/services/seo_service.py` → Expected: All checks passed + +- [ ] **Step 5: Commit** + +```bash +git add app/social/services/seo_service.py +git commit -m "feat: p2v_video SNS SEO 생성·저장 서비스 추가" +``` + +--- + +### Task 4: 업로드 서비스 — p2v_video 대상 분기 + +**Files:** +- Modify: `app/social/services/upload_service.py` +- Test: `zzz/test_p2v_upload_service.py` + +**Interfaces:** +- Consumes: `PosterAliveTask` (Task 1 컬럼), `SocialUpload.p2v_video_id` (Task 1). +- Produces: `request_upload` 가 `body.content_type == "p2v_video"` 를 처리한다 + (`SocialUpload(p2v_video_id=body.video_id, video_id=None, content_id=None)`). + 요청 필드명 `body.video_id` 는 content_type 안에서의 id 를 뜻한다(기존 규칙 유지). + +- [ ] **Step 1: Write the failing test** + +```python +# zzz/test_p2v_upload_service.py +"""upload_service 의 p2v_video 분기 검증 — DB·계정 서비스는 가짜로 대체한다. + +Literal 이 아직 열리지 않았으므로 요청은 model_construct 로 만든다(검증 우회). + + uv run python -m pytest zzz/test_p2v_upload_service.py -q +""" +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock + +import pytest +from fastapi import BackgroundTasks + +from app.social.constants import PrivacyStatus +from app.social.exceptions import VideoNotFoundError +from app.social.schemas import SocialUploadRequest +from app.social.services.upload_service import SocialUploadService + + +def make_body(content_type="p2v_video", video_id=7): + return SocialUploadRequest.model_construct( + content_type=content_type, video_id=video_id, social_account_id=3, + title="테스트 제목", description="설명", tags=["a"], + privacy_status=PrivacyStatus.PRIVATE, scheduled_at=None, platform_options=None, + ) + + +class FakeSession: + """execute 호출 순서: 대상 조회 → (계정은 서비스 목) → 진행 중 → 예약 → 최대 순번.""" + + def __init__(self, target): + self.target, self.statements, self.added = target, [], [] + self._calls = 0 + + async def execute(self, stmt): + self.statements.append(stmt) + self._calls += 1 + if self._calls == 1: + return SimpleNamespace(scalar_one_or_none=lambda: self.target) + return SimpleNamespace(scalar_one_or_none=lambda: None, scalar=lambda: 0) + + def add(self, obj): + self.added.append(obj) + + async def commit(self): + pass + + async def refresh(self, obj): + obj.id = 99 + + +def make_service(): + accounts = MagicMock() + accounts.get_account_by_id = AsyncMock( + return_value=SimpleNamespace(id=3, platform="youtube")) + return SocialUploadService(accounts) + + +USER = SimpleNamespace(user_uuid="u-1") +READY = SimpleNamespace(id=7, status="done", video_url="https://blob.example.com/v.mp4", + title=None, description=None, hashtags=None) + + +@pytest.mark.asyncio +async def test_p2v_upload_fills_only_p2v_video_id(): + session = FakeSession(READY) + resp = await make_service().request_upload(make_body(), USER, session, BackgroundTasks()) + record = session.added[0] + assert resp.success and resp.upload_id == 99 + assert record.p2v_video_id == 7 + assert record.video_id is None and record.content_id is None + assert READY.title == "테스트 제목" # 게시 폼 값이 행에 반영된다 + + +@pytest.mark.asyncio +async def test_p2v_target_query_filters_owner_and_deleted(): + session = FakeSession(READY) + await make_service().request_upload(make_body(), USER, session, BackgroundTasks()) + sql = str(session.statements[0]) + assert "p2v_video.user_uuid" in sql and "p2v_video.is_deleted" in sql + + +@pytest.mark.asyncio +async def test_other_users_or_missing_p2v_video_is_not_found_and_not_recorded(): + session = FakeSession(None) # 소유자 필터에 걸리면 조회 결과가 없다 + with pytest.raises(VideoNotFoundError): + await make_service().request_upload(make_body(), USER, session, BackgroundTasks()) + assert session.added == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("row", [ + SimpleNamespace(id=7, status="running", video_url="https://x/v.mp4", + title=None, description=None, hashtags=None), + SimpleNamespace(id=7, status="done", video_url=None, + title=None, description=None, hashtags=None), +]) +async def test_unfinished_p2v_video_is_rejected(row): + with pytest.raises(VideoNotFoundError): + await make_service().request_upload( + make_body(), USER, FakeSession(row), BackgroundTasks()) +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `uv run python -m pytest zzz/test_p2v_upload_service.py -q` +Expected: FAIL (p2v 분기가 없어 ADO2 `Video` 쿼리로 떨어져 `record.p2v_video_id` AttributeError 또는 잘못된 쿼리) + +- [ ] **Step 3: Write minimal implementation** + +`app/social/services/upload_service.py` — import 추가: + +```python +from app.p2v.models import PosterAliveTask +``` + +`request_upload` 의 대상 분기를 `if body.content_type == "ssul": ... else: ...` 에서 3분기로 바꾼다. `if body.content_type == "ssul":` 블록 **앞**에 새 분기를 두고 기존 `if` 를 `elif` 로 바꾼다: + +```python + 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": +``` + +(기존 `if body.content_type == "ssul":` 한 줄만 `elif` 로 바뀌고 본문은 그대로.) + +`SocialUpload(...)` 생성부의 대상 컬럼 3줄을 교체: + +```python + # 종류에 따라 셋 중 하나만 채운다 (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, +``` + +- [ ] **Step 4: Run test to verify it passes** + +Run: `uv run python -m pytest zzz/test_p2v_upload_service.py -q` → Expected: 5 passed +Run: `uv run ruff check app/social/services/upload_service.py` → Expected: All checks passed + +- [ ] **Step 5: Commit** + +```bash +git add app/social/services/upload_service.py +git commit -m "feat: 업로드 서비스에 p2v_video 대상 분기 추가" +``` + +--- + +### Task 5: 업로드 워커 — 원본 URL 분기 + +**Files:** +- Modify: `app/social/worker/upload_task.py` (`# 2. 대상 영상 조회` 블록, import) +- Test: `zzz/test_p2v_upload_task.py` + +**Interfaces:** +- Consumes: `SocialUpload.p2v_video_id`, `PosterAliveTask.video_url` (Task 1). +- Produces: `async def _resolve_source_url(session, upload) -> str | None` — 업로드가 가리키는 종류의 영상 URL 을 반환한다 + (`p2v_video_id` → `PosterAliveTask.video_url`, `content_id` → `SsulContent.video_url`, 그 외 → `Video.result_movie_url`). + +- [ ] **Step 1: Write the failing test** + +```python +# zzz/test_p2v_upload_task.py +"""upload_task 의 원본 URL 분기 검증 — 세션은 가짜로 대체한다. + + uv run python -m pytest zzz/test_p2v_upload_task.py -q +""" +from types import SimpleNamespace + +import pytest + +from app.social.worker.upload_task import _resolve_source_url + + +class FakeSession: + def __init__(self, row): + self.row, self.statements = row, [] + + async def execute(self, stmt): + self.statements.append(str(stmt)) + return SimpleNamespace(scalar_one_or_none=lambda: self.row) + + +def upload(**kw): + base = dict(video_id=None, content_id=None, p2v_video_id=None) + base.update(kw) + return SimpleNamespace(**base) + + +@pytest.mark.asyncio +async def test_p2v_upload_reads_p2v_video_url(): + session = FakeSession(SimpleNamespace(video_url="https://blob.example.com/p2v.mp4")) + url = await _resolve_source_url(session, upload(p2v_video_id=7)) + assert url == "https://blob.example.com/p2v.mp4" + assert "p2v_video" in session.statements[0] + + +@pytest.mark.asyncio +async def test_ssul_upload_reads_ssul_video_url(): + session = FakeSession(SimpleNamespace(video_url="https://blob.example.com/ssul.mp4")) + assert await _resolve_source_url(session, upload(content_id=5)) == \ + "https://blob.example.com/ssul.mp4" + assert "ssul_content" in session.statements[0] + + +@pytest.mark.asyncio +async def test_ado2_upload_reads_result_movie_url(): + session = FakeSession(SimpleNamespace(result_movie_url="https://blob.example.com/ado2.mp4")) + assert await _resolve_source_url(session, upload(video_id=3)) == \ + "https://blob.example.com/ado2.mp4" + + +@pytest.mark.asyncio +async def test_missing_row_returns_none(): + assert await _resolve_source_url(FakeSession(None), upload(p2v_video_id=7)) is None +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `uv run python -m pytest zzz/test_p2v_upload_task.py -q` +Expected: FAIL (`ImportError: cannot import name '_resolve_source_url'`) + +- [ ] **Step 3: Write minimal implementation** + +`app/social/worker/upload_task.py` — import 추가: `from app.p2v.models import PosterAliveTask`. + +`process_social_upload` 위(`_download_video` 아래)에 함수 추가: + +```python +async def _resolve_source_url(session, upload: SocialUpload) -> Optional[str]: + """업로드가 가리키는 콘텐츠 종류의 영상 URL. 병합 스키마라 채워진 FK 가 곧 종류다.""" + 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 if row else None + 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 if row else None + row = ( + await session.execute(select(Video).where(Video.id == upload.video_id)) + ).scalar_one_or_none() + return row.result_movie_url if row else None +``` + +`process_social_upload` 의 `# 2. 대상 영상 조회` 블록(`if upload.content_id is not None: ... else: ...` 전체)을 다음으로 교체: + +```python + # 2. 대상 영상 조회. video_id / content_id / p2v_video_id 중 정확히 하나만 채워져 있다(CHECK). + source_url = await _resolve_source_url(session, upload) +``` + +오류 로그의 `f"video_id: {upload.video_id}, content_id: {upload.content_id}"` 에 `p2v_video_id: {upload.p2v_video_id}` 를 덧붙인다. + +- [ ] **Step 4: Run test to verify it passes** + +Run: `uv run python -m pytest zzz/test_p2v_upload_task.py -q` → Expected: 4 passed +Run: `uv run ruff check app/social/worker/upload_task.py` → Expected: All checks passed + +- [ ] **Step 5: Commit** + +```bash +git add app/social/worker/upload_task.py +git commit -m "feat: 업로드 워커가 p2v_video 원본 URL 을 읽도록 분기 추가" +``` + +--- + +### Task 6: 공유 페이지 — 저장된 제목·설명 우선 + +**Files:** +- Modify: `app/video/services/share_page.py` (`P2vShareData`, `build_p2v_share_html`) +- Modify: `app/p2v/api/routers/v1/public.py` (`share_page`) +- Modify: `zzz/test_p2v_share_description.py` (기존 테스트에 케이스 추가) + +**Interfaces:** +- Consumes: `PosterAliveTask.title/description` (Task 1), `narration_text_of`. +- Produces: `P2vShareData.title: str | None = None`. + 제목 = `data.title` → `data.name` → 폴백. 설명 = `data.description`(라우터가 `row.description` → 내레이션 순으로 채움) → 기본 문구. + +- [ ] **Step 1: Write the failing test** — `zzz/test_p2v_share_description.py` 끝에 추가: + +```python +def build_with(title, name, description): + return build_p2v_share_html( + P2vShareData(ctype=JOB_TYPE_VIDEO, content_id=7, poster_url=None, + name=name, title=title, description=description), + share_url="https://example.com/api/p2v/f1/share/7", + frontend_base_url="https://example.com", + ) + + +def test_stored_title_wins_over_name(): + assert og(build_with("저장 제목", "작업 이름", None), "og:title") == "저장 제목" + + +def test_name_used_when_no_stored_title(): + assert og(build_with(None, "작업 이름", None), "og:title") == "작업 이름" +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `uv run python -m pytest zzz/test_p2v_share_description.py -q` +Expected: FAIL (`TypeError: P2vShareData.__init__() got an unexpected keyword argument 'title'`) + +- [ ] **Step 3: Write minimal implementation** + +`share_page.py` — `P2vShareData` 에 `title: str | None = None` 을 `name` 아래에 추가. `build_p2v_share_html` 의 제목 인자를 교체: + +```python + title=_share_title(data.title or data.name, fallback_title, fallback_store=fallback_title), +``` + +`public.py` — `share_page()` 의 `P2vShareData(...)` 호출을 교체: + +```python + P2vShareData(ctype=ctype, content_id=row.id, poster_url=poster_of(ctype, row), + name=row.name, title=getattr(row, "title", None), + description=(getattr(row, "description", None) + or narration_text_of(ctype, row))), +``` + +(`PlayreelTask` 에는 `title`/`description` 속성이 없어 `getattr` 기본값 `None` 이 쓰인다 — 롱컷 동작은 변하지 않는다.) + +- [ ] **Step 4: Run test to verify it passes** + +Run: `uv run python -m pytest zzz/test_p2v_share_description.py -q` → Expected: 8 passed +Run: `uv run ruff check app/video/services/share_page.py app/p2v/api/routers/v1/public.py` → Expected: All checks passed + +- [ ] **Step 5: Commit** + +```bash +git add app/video/services/share_page.py app/p2v/api/routers/v1/public.py +git commit -m "feat: p2v 공유 페이지가 저장된 제목·설명을 우선 사용" +``` + +> `zzz/` 테스트 파일은 지금까지처럼 사용자가 요청하지 않는 한 커밋하지 않는다(이전 커밋 관례). + +--- + +### Task 7: 시트 문안 파일 → 사용자 적용 확인 → 업로드 열기 + +**Files:** +- Create: `docs/prompts/p2v_upload_sheet.md` +- Modify (열기, 마지막): `app/social/schemas/upload_schema.py`, `app/social/schemas/seo_schema.py`, `app/social/api/routers/v1/seo.py`, `app/social/services/upload_service.py` (응답 매핑 2곳) +- Test: `zzz/test_p2v_upload_open.py` + +**Interfaces:** +- Consumes: `seo_service.get_p2v_seo` (Task 3), `request_upload` p2v 분기 (Task 4). +- Produces: `SocialUploadRequest.content_type` / `YoutubeDescriptionRequest.content_type` 가 `"p2v_video"` 허용, + `SocialUploadStatusResponse`/`SocialUploadHistoryItem` 에 `p2v_video_id: Optional[int]`. + +**게이트(체크포인트):** 7-A~7-B 를 끝내면 **멈추고** 사용자에게 (1) 마이그레이션 SQL 적용, (2) 시트 `p2v_upload` 붙여넣기 완료 여부를 확인받는다. 둘 다 확인되기 전에는 7-C 로 가지 않는다. + +#### 7-A. 시트 문안 파일 + +- [ ] **Step 1: `docs/prompts/p2v_upload_sheet.md` 작성** — 아래 구조로 만든다(문안은 실제 값, 변수는 `{event_name}` 등 `{영문}` 형식만 사용; JSON 예시의 리터럴 `{ }` 는 `Prompt.build_prompt` 가 보존한다): + +````markdown +# 시트 `p2v_upload` 문안 + +스프레드시트(`PROMPT_SPREADSHEET`)에 `p2v_upload` 시트를 만들고 아래 값을 붙여넣는다. +**B2 = 모델, B3 = 템플릿** (다른 셀은 코드가 읽지 않는다). + +## B2 (모델) +`gpt-5-mini` ← 기존 `ssul_upload` 시트 B2 와 같은 값으로 맞출 것 (다르면 그 값을 따른다) + +## B3 (템플릿) +``` +너는 한국어 유튜브 쇼츠 SEO 카피라이터다. 아래 공연·행사 포스터 정보로 쇼츠 제목, 설명, 태그를 만든다. + +[행사 정보] +- 행사명: {event_name} +- 일시: {date_text} +- 장소: {place} +- 분류: {category} +- 지역: {region_guess} +- 키워드: {keywords} +- 영상 내레이션: {narration} + +[규칙] +1. title: 100자 이내(공백 포함). 행사명을 앞에 두고, 호기심을 끄는 한 구절을 덧붙인다. 이모지는 최대 1개. +2. description: 3~5문장. 첫 문장에 행사명·일시·장소를 넣고, 내레이션의 분위기를 살려 요약한다. + 마지막 줄에 해시태그 5~8개를 `#태그` 형식으로 붙인다. +3. keywords: 해시태그와 같은 단어를 `#` 없이 5~8개 리스트로 낸다. +4. 정보가 비어 있는 항목(일시·장소 등)은 지어내지 말고 문장에서 생략한다. +5. 광고성 과장·허위 정보·예매 링크 날조를 금지한다. +``` +```` + +- [ ] **Step 2: Commit** + +```bash +git add docs/prompts/p2v_upload_sheet.md +git commit -m "docs: p2v_upload 시트 문안 추가" +``` + +#### 7-B. 체크포인트 (사용자 확인) + +- [ ] **Step 3: 멈추고 사용자에게 묻는다** — "마이그레이션 `migration_2026-10-16_p2v_youtube_upload.sql` 적용과 시트 `p2v_upload` 붙여넣기를 마쳤나요?" 확인 전에는 7-C 로 가지 않는다. +- [ ] **Step 4: (사용자 확인 후) 읽기 전용 점검** — `uv run python -c "from app.utils.prompts.prompts import get_p2v_upload_prompt as g; p=g(); print(p.prompt_model, len(p.prompt_template))"` 가 오류 없이 모델명과 길이를 출력하는지 본다. 실패하면 시트 이름·B2/B3 위치를 사용자에게 알린다. + +#### 7-C. Literal 열기 (업로드 오픈) + +- [ ] **Step 5: Write the failing test** + +```python +# zzz/test_p2v_upload_open.py +"""content_type 에 p2v_video 가 열렸는지, 응답이 p2v_video_id 를 담는지 검증. + + uv run python -m pytest zzz/test_p2v_upload_open.py -q +""" +import pytest +from pydantic import ValidationError + +from app.social.schemas import ( + SocialUploadHistoryItem, + SocialUploadRequest, + SocialUploadStatusResponse, + YoutubeDescriptionRequest, +) + + +def test_upload_request_accepts_p2v_video(): + body = SocialUploadRequest(content_type="p2v_video", video_id=1, + social_account_id=1, title="t") + assert body.content_type == "p2v_video" + + +def test_upload_request_still_rejects_unknown_type(): + with pytest.raises(ValidationError): + SocialUploadRequest(content_type="p2v_playreel", video_id=1, + social_account_id=1, title="t") + + +def test_seo_request_accepts_p2v_video(): + req = YoutubeDescriptionRequest(content_type="p2v_video", video_id=1) + assert req.content_type == "p2v_video" + + +def test_responses_expose_p2v_video_id(): + assert "p2v_video_id" in SocialUploadStatusResponse.model_fields + assert "p2v_video_id" in SocialUploadHistoryItem.model_fields +``` + +- [ ] **Step 6: Run test to verify it fails** + +Run: `uv run python -m pytest zzz/test_p2v_upload_open.py -q` +Expected: FAIL (`ValidationError` 또는 `p2v_video_id` 필드 없음) + +- [ ] **Step 7: Write minimal implementation** + +`upload_schema.py` — `SocialUploadRequest` 의 `content_type` 을 교체하고 주석을 보강: + +```python + # ⚠️ video_id 는 content_type 안에서만 유일하다 — video.id · ssul_content.id · p2v_video.id 는 + # 각각 1부터 시작하는 독립 시퀀스라 값이 겹친다. content_type 없이 다른 종류의 id 를 + # 보내면 **id 가 겹치는 남의 ADO2 영상이 업로드된다.** + content_type: Literal["video", "ssul", "p2v_video"] = Field( + default="video", + description="콘텐츠 종류 (video: ADO2 영상, ssul: 썰박스, p2v_video: P2V 무빙 포스터)", + ) +``` + +같은 파일의 `SocialUploadStatusResponse` 와 `SocialUploadHistoryItem` 의 `content_id` 필드 바로 아래에 각각 추가: + +```python + p2v_video_id: Optional[int] = Field(None, description="P2V 무빙 포스터 ID (다른 종류면 None)") +``` + +`seo_schema.py` — `content_type: Literal["video", "ssul", "p2v_video"]` 로 바꾸고 `video_id` 설명에 "또는 p2v_video.id" 를 덧붙인다. + +`upload_service.py` — `get_upload_status` 의 `SocialUploadStatusResponse(...)` 와 이력의 `SocialUploadHistoryItem(...)` 에서 `content_id=upload.content_id,` 바로 아래에 `p2v_video_id=upload.p2v_video_id,` 를 추가한다(2곳). + +`seo.py` — `if request_body.content_type == "ssul":` 블록 아래, 기본 반환 위에 추가: + +```python + 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) +``` + +- [ ] **Step 8: Run tests to verify they pass** + +Run: `uv run python -m pytest zzz/test_p2v_upload_open.py zzz/test_p2v_upload_models.py zzz/test_p2v_upload_seo_input.py zzz/test_p2v_upload_seo_service.py zzz/test_p2v_upload_service.py zzz/test_p2v_upload_task.py zzz/test_p2v_share_description.py -q` +Expected: 전부 passed (이 파일들의 합계) +Run: `uv run ruff check app/social app/p2v app/video/services/share_page.py app/utils/prompts` → Expected: All checks passed + +- [ ] **Step 9: Commit** + +```bash +git add app/social/schemas/upload_schema.py app/social/schemas/seo_schema.py app/social/api/routers/v1/seo.py app/social/services/upload_service.py +git commit -m "feat: content_type 에 p2v_video 를 열어 업로드·SEO 를 활성화" +``` + +> 이 커밋부터 `content_type="p2v_video"` 요청이 통과한다. 배포 전 `git revert` 한 번이면 다시 닫힌다. + +--- + +## 최종 검증 (모든 태스크 후) + +- [ ] `uv run python -m pytest zzz/test_p2v_upload_*.py zzz/test_p2v_share_description.py -q` 전부 통과 +- [ ] `uv run ruff check app/` — 이번 변경 파일에서 새 경고 없음 +- [ ] 사용자에게 보고: 마이그레이션·시트 적용 여부, 프론트엔드(`content_type: "p2v_video"` 전송) 미적용, 실제 YouTube 업로드는 미실행 + +## Self-Review 결과 + +- **Spec coverage**: DB(Task 1) · SEO 생성(2·3) · 업로드 경로(4·5) · 공유(6) · 시트 문안(7-A) · 롤아웃 순서(Literal 마지막, 7-C) · 소유자 필터(4) · 제목 100자(2·3) 모두 태스크가 있다. 응답 스키마의 `p2v_video_id` 는 spec 에 없지만 이력·상태 조회에서 P2V 업로드가 `video_id`·`content_id` 둘 다 None 으로 보이는 모호함을 막으려고 7-C 에 포함했다. +- **Placeholder scan**: TBD/TODO 없음. 시트 B2 모델명은 기존 시트 값에 맞추도록 문안에 명시(사용자가 시트 B2 를 확인해 채움). +- **Type consistency**: `build_seo_input`/`clamp_title`(Task 2) ↔ Task 3 호출, `_resolve_source_url`(Task 5), `P2vShareData.title`(Task 6), `p2v_video_id`(Task 1) ↔ Task 4·5·7 이름이 일치한다. +- **Review Focus 매핑**: 1·2 → Task 4, 3·4 → Task 2·3, 5 → Task 2(`test_prompt_is_lazy_not_loaded_at_import`), 6 → Task 7(`test_upload_request_still_rejects_unknown_type`; 열기 전에는 Task 4 가 `model_construct` 로 우회).