diff --git a/backend/models/hybrid.py b/backend/models/hybrid.py new file mode 100644 index 0000000..fc95910 --- /dev/null +++ b/backend/models/hybrid.py @@ -0,0 +1,45 @@ +from dataclasses import dataclass + +from PIL import Image +from pydantic import BaseModel, Field + +Rect = tuple[float, float, float, float] + + +class MaskSpec(BaseModel): + """rect — 사각 전체 고정(밝은 배경 포스터. 베벨·그림자까지 덮는다). + glyph — 사각 안 글자 픽셀만. 검정 포스터용이며 register와 함께 써야 한다.""" + mode: str = "rect" + ink_min: int = 55 + thin_dilate: int = 9 + thick_dilate: int = 25 + thick_from_y: float = 0.85 + + +class HybridSpec(BaseModel): + clip: str | None = None + clip_crop: str | None = None # "x0,y0,w,h" — 9:16 캔버스에 얹힌 클립용 + register: bool = False + + +class LayerConfig(BaseModel): + """작품별 좌표. 아직 사람이 손으로 쓴다 — 신규 공연은 여기서 멈추는 게 정상이다.""" + mask: MaskSpec = MaskSpec() + fixed_rects: list[Rect] = [] + sil_box: Rect = (0.0, 0.0, 0.0, 0.0) + sil_poly: list[tuple[float, float]] = [] + glyphs: dict[str, Rect] = {} + sweep_at: dict[str, float] = {} + punches: list[tuple[Rect, float, float]] = [] # (사각, 시작초, 피크배율) + glows: list[tuple[Rect, float]] = [] + protect: list[Rect] = [] + glyph_dark_ink: bool = True + hybrid: HybridSpec = Field(default_factory=HybridSpec) + + +@dataclass +class HybridResult: + video: bytes + frames: int + duration: float + proof: Image.Image | None = None # 8시점 컨택트 시트 diff --git a/backend/models/narration_slots.py b/backend/models/narration_slots.py new file mode 100644 index 0000000..30cd610 --- /dev/null +++ b/backend/models/narration_slots.py @@ -0,0 +1,17 @@ +from pydantic import BaseModel + +NARRATION_SLOTS = ("훅1", "훅2", "수상", "넘버", "캐스팅스케줄", "일시", "CTA") + + +class NarrationLine(BaseModel): + slot: str + text: str + + +class SlotNarration(BaseModel): + """롱컷 나레이션 7문장. 게이트 ③에서 사람이 고치면 그것이 읽히는 문장이 된다.""" + lines: list[NarrationLine] + + @property + def texts(self) -> list[str]: + return [line.text for line in self.lines] diff --git a/backend/models/tts.py b/backend/models/tts.py index f7746a3..015b78e 100644 --- a/backend/models/tts.py +++ b/backend/models/tts.py @@ -3,9 +3,13 @@ from dataclasses import dataclass from pydantic import BaseModel +# Typecast 카탈로그 id. 롱컷 나레이션 보이스 정본이다. +TYPECAST_YENA = "tc_61e748d0fd9fb2d2cacbb04d" + + class TypecastVoice(BaseModel): """Typecast(ssfm-v30) 설정. 주면 엔진이 typecast가 된다.""" - voice_id: str + voice_id: str = TYPECAST_YENA emotion: str = "normal" emotion_intensity: float = 1.0 tempo: float = 1.0 # OpenAI의 speed에 대응 diff --git a/backend/services/bgm.py b/backend/services/bgm.py index d7b58f6..c33efba 100644 --- a/backend/services/bgm.py +++ b/backend/services/bgm.py @@ -20,6 +20,17 @@ MIN_SECONDS, MAX_SECONDS = 10, 30 # duration 허용 범위 하한이 10초 SECONDS_MARGIN = 2 +# 나레이션을 VLM이 쓰지 않는 흐름(Playreel)은 스타일도 따로 안 나오므로 이 값을 쓴다. +# 잔잔한 앰비언트는 광고에서 늘어진다. +DEFAULT_BGM_STYLE = BgmStyle( + style=("modern korean fusion gugak, gayageum and haegeum hooks over driving " + "janggu percussion and punchy modern beat, bright festival energy, " + "128 bpm, instrumental"), + prompt=("Starts hard on beat one - no intro ramp. Bright festival energy, " + "driving groove throughout, brief lift at two thirds, clean ending."), +) + + def target_seconds(narration_total: float) -> int: return int(min(MAX_SECONDS, max(MIN_SECONDS, round(narration_total) + SECONDS_MARGIN))) diff --git a/backend/services/hybrid_poster.py b/backend/services/hybrid_poster.py new file mode 100644 index 0000000..6295ac8 --- /dev/null +++ b/backend/services/hybrid_poster.py @@ -0,0 +1,311 @@ +"""⑩ hybrid — 생성 클립 아트워크 위에 원본 고정층을 다시 덮는다. + +Kling 단독은 생동감이 있지만 제목대가 7~17 드리프트하고, 레이어 단독은 글자가 0px이지만 +훅이 약하다. 그래서 Kling을 아트워크 층으로 쓰고 원본에서 오려낸 마스크를 위에 얹는다. +⑦ render의 QR·로고바 패치를 마스크 전체로 일반화한 것이고 추가 크레딧은 0이다. +""" +import io +import math +from collections.abc import Iterator +from pathlib import Path + +import numpy as np +from PIL import Image, ImageDraw, ImageFilter + +from models.hybrid import HybridResult, LayerConfig, Rect +from utils.video import decode_frames, encode_mp4 + +FPS = 24 +DURATION = 8.0 +HOLD_SECONDS = 0.5 # 첫 0.5초는 원본 정지 — 첫 프레임이 곧 썸네일이다 +CRF = 17 + +FEATHER_PX = 30 +SIL_DARK_MAX = 120 +GLYPH_BRIGHT_MIN = 165 +SWEEP_SECONDS = 0.8 +SWEEP_GAIN = 120 +GLOW_SECONDS = 0.9 +GLOW_GAIN = 110 +PROOF_COUNT = 8 +PROOF_SIZE = (300, 400) + + +def ease_sine(t: float) -> float: + return 0.5 - 0.5 * math.cos(math.pi * min(max(t, 0.0), 1.0)) + + +def punch_scale(t: float, peak: float) -> float: + """1.0 → peak(0.22s) → 유지(0.12s) → 0.96(0.18s, 지나침) → 1.0. 오버슈트가 팝의 정체다.""" + if t < 0 or t > 0.64: + return 1.0 + if t < 0.22: + return 1.0 + (peak - 1.0) * (1 - (1 - t / 0.22) ** 3) + if t < 0.34: + return peak + if t < 0.52: + return peak + (0.96 - peak) * ease_sine((t - 0.34) / 0.18) + return 0.96 + 0.04 * ease_sine((t - 0.52) / 0.12) + + +def to_pixels(rect: Rect, size: tuple[int, int]) -> tuple[int, int, int, int]: + width, height = size + return (int(rect[0] * width), int(rect[1] * height), + int(rect[2] * width), int(rect[3] * height)) + + +def feather_rect_mask(size: tuple[int, int], rect: Rect) -> Image.Image: + mask = Image.new("L", size, 0) + ImageDraw.Draw(mask).rectangle(to_pixels(rect, size), fill=255) + return mask.filter(ImageFilter.GaussianBlur(FEATHER_PX / 2)) + + +def glyph_alpha(poster: Image.Image, rect: Rect, dark_ink: bool = True) -> Image.Image: + """사각 안의 글자 픽셀만 알파로. 펀치 중 이웃을 원본에서 다시 얹을 때 쓴다. + + dark_ink는 어두운 베벨·그림자도 글자로 본다(밝은 배경 포스터). + 검정 포스터에서 켜면 배경 전체가 글자가 되어 검은 상자가 된다. + """ + width, height = poster.size + x0, y0, x1, y1 = to_pixels(rect, poster.size) + luminance = np.asarray(poster.convert("L")).astype(np.float32) + mask = np.zeros((height, width), np.uint8) + patch = luminance[y0:y1, x0:x1] + mask[y0:y1, x0:x1] = (((patch > GLYPH_BRIGHT_MIN) | (patch < 75)) * 255 if dark_ink + else (patch > 55) * 255) + return Image.fromarray(mask).filter(ImageFilter.MaxFilter(13)).filter( + ImageFilter.GaussianBlur(2)) + + +def build_masks(poster: Image.Image, config: LayerConfig) -> dict: + width, height = poster.size + pixels = np.asarray(poster).astype(np.float32) + luminance = pixels.mean(axis=2) + + fixed = np.zeros((height, width), np.float32) + for rect in config.fixed_rects: + fixed = np.maximum(fixed, np.asarray(feather_rect_mask(poster.size, rect)) / 255.0) + + x0, y0, x1, y1 = to_pixels(config.sil_box, poster.size) + silhouette = np.zeros((height, width), np.uint8) + silhouette[y0:y1, x0:x1] = (pixels.max(axis=2) < SIL_DARK_MAX)[y0:y1, x0:x1] * 255 + if config.sil_poly: + # 밝은 의상은 어두운 픽셀 임계로 안 잡혀서 다각형과 합친다 + polygon = Image.new("L", poster.size, 0) + ImageDraw.Draw(polygon).polygon( + [(int(x * width), int(y * height)) for x, y in config.sil_poly], fill=255) + silhouette = np.maximum(silhouette, np.asarray(polygon)) + silhouette = np.asarray(Image.fromarray(silhouette) + .filter(ImageFilter.MaxFilter(7)) + .filter(ImageFilter.GaussianBlur(4))) / 255.0 + + glyphs = {} + for name, rect in config.glyphs.items(): + gx0, gy0, gx1, gy1 = to_pixels(rect, poster.size) + patch = np.zeros((height, width), np.uint8) + patch[gy0:gy1, gx0:gx1] = (luminance[gy0:gy1, gx0:gx1] > GLYPH_BRIGHT_MIN) * 255 + glyphs[name] = np.asarray( + Image.fromarray(patch).filter(ImageFilter.GaussianBlur(1.2))) / 255.0 + + glyph_union = (np.max(np.stack(list(glyphs.values())), axis=0) if glyphs + else np.zeros((height, width), np.float32)) + hold = np.clip(fixed + silhouette + glyph_union, 0, 1) + + if config.mask.mode == "glyph": + hold = glyph_hold_mask(poster, config) + silhouette = np.zeros_like(silhouette) + return {"hold": hold, "glyph": glyphs, "sil": silhouette} + + +def glyph_hold_mask(poster: Image.Image, config: LayerConfig) -> np.ndarray: + """검정 포스터용. 사각 고정층이 검은 상자가 되므로 글자 픽셀만 얇게 잡는다.""" + width, height = poster.size + spec = config.mask + luminance = np.asarray(poster.convert("L")).astype(np.float32) + thin = np.zeros((height, width), np.uint8) + thick = np.zeros((height, width), np.uint8) + for rect in config.fixed_rects: + x0, y0, x1, y1 = to_pixels(rect, poster.size) + target = thick if rect[1] >= spec.thick_from_y else thin + target[y0:y1, x0:x1] = (luminance[y0:y1, x0:x1] > spec.ink_min) * 255 + thin_mask = Image.fromarray(thin).filter( + ImageFilter.MaxFilter(spec.thin_dilate)).filter(ImageFilter.GaussianBlur(2)) + thick_mask = Image.fromarray(thick).filter( + ImageFilter.MaxFilter(spec.thick_dilate)).filter(ImageFilter.GaussianBlur(3)) + return np.maximum(np.asarray(thin_mask), np.asarray(thick_mask)) / 255.0 + + +def pop_rect(frame: Image.Image, poster: Image.Image, rect: Rect, scale: float) -> None: + """원본의 사각 영역을 오려 중심 기준으로 배율을 먹여 덮는다.""" + x0, y0, x1, y1 = to_pixels(rect, poster.size) + crop = poster.crop((x0, y0, x1, y1)) + scaled_w, scaled_h = int(crop.width * scale), int(crop.height * scale) + crop = crop.resize((scaled_w, scaled_h), Image.LANCZOS) + mask = Image.new("L", crop.size, 0) + ImageDraw.Draw(mask).rectangle((6, 6, scaled_w - 7, scaled_h - 7), fill=255) + mask = mask.filter(ImageFilter.GaussianBlur(4)) + frame.paste(crop, ((x0 + x1) // 2 - scaled_w // 2, (y0 + y1) // 2 - scaled_h // 2), mask) + + +def register(frame: np.ndarray, base: np.ndarray, weight: np.ndarray, + previous=(1.0, 0, 0)) -> tuple[np.ndarray, tuple, float]: + """생성 클립을 원본에 정합한다. + + 모델이 프레임 전체를 2~3% 드리프트시키므로, 정합 없이 글자만 얇게 고정하면 + 클립의 글자가 옆에 비쳐 겹쳐 보인다. 고정층 영역에서 MAE가 최소인 스케일·이동을 찾는다. + """ + height, width = base.shape[:2] + step = 6 # 1/6 축소에서 탐색 + small = (width // step, height // step) + base_small = np.asarray(Image.fromarray(base.astype(np.uint8)).resize( + small, Image.BILINEAR), np.float32) + frame_small = Image.fromarray(frame.astype(np.uint8)).resize(small, Image.BILINEAR) + weight_small = np.asarray(Image.fromarray((weight * 255).astype(np.uint8)).resize( + small, Image.BILINEAR), np.float32) / 255.0 + weight_sum = weight_small.sum() + 1e-6 + small_h, small_w = base_small.shape[:2] + + def cost(scale, dx, dy): + inverse = 1 / scale + moved = frame_small.transform( + frame_small.size, Image.AFFINE, + (inverse, 0, small_w / 2 * (1 - inverse) - dx / step * inverse, + 0, inverse, small_h / 2 * (1 - inverse) - dy / step * inverse), Image.BILINEAR) + diff = np.abs(np.asarray(moved, np.float32) - base_small).mean(axis=2) + return (diff * weight_small).sum() / weight_sum + + best = (cost(*previous), *previous) + for scale in (previous[0] - 0.02, previous[0] - 0.01, previous[0], + previous[0] + 0.01, previous[0] + 0.02): + for dx in range(previous[1] - 24, previous[1] + 25, 8): + for dy in range(previous[2] - 24, previous[2] + 25, 8): + score = cost(scale, dx, dy) + if score < best[0]: + best = (score, scale, dx, dy) + _, scale, dx, dy = best + for fine_scale in (scale - 0.005, scale, scale + 0.005): + for fine_dx in range(dx - 4, dx + 5, 2): + for fine_dy in range(dy - 4, dy + 5, 2): + score = cost(fine_scale, fine_dx, fine_dy) + if score < best[0]: + best = (score, fine_scale, fine_dx, fine_dy) + _, scale, dx, dy = best + + inverse = 1 / scale + warped = Image.fromarray(frame.astype(np.uint8)).transform( + (width, height), Image.AFFINE, + (inverse, 0, width / 2 * (1 - inverse) - dx * inverse, + 0, inverse, height / 2 * (1 - inverse) - dy * inverse), Image.BICUBIC) + return np.asarray(warped, np.float32), (scale, dx, dy), best[0] + + +def clip_frame_reader(clip: bytes | Path, size: tuple[int, int], crop: str | None): + """클립 프레임을 순서대로 하나씩만 메모리에 올린다. 인덱스는 단조 증가한다.""" + frames = decode_frames(clip) + state = {"index": -1, "image": None} + + def read(wanted: int) -> np.ndarray: + while state["index"] < wanted: + try: + frame = next(frames) + except StopIteration: + break + state["index"] += 1 + state["image"] = frame + image = state["image"] + if crop: + x0, y0, w, h = (int(v) for v in crop.split(",")) + image = image.crop((x0, y0, x0 + w, y0 + h)) + return np.asarray(image.convert("RGB").resize(size, Image.LANCZOS)).astype(np.float32) + + return read + + +def compose_frames(poster: Image.Image, config: LayerConfig, clip: bytes | Path, + masks: dict, do_register: bool) -> Iterator[Image.Image]: + width, height = poster.size + base = np.asarray(poster).astype(np.float32) + hold = masks["hold"][..., None] + read_clip = clip_frame_reader(clip, poster.size, config.hybrid.clip_crop) + + xs = np.arange(width, dtype=np.float32)[None, :] + ys = np.arange(height, dtype=np.float32)[:, None] + hold_frames = int(HOLD_SECONDS * FPS) + total = int(DURATION * FPS) + glow_masks: dict = {} + # 펀치 안 하는 이웃도 항상 보호한다 — 펀치된 크롭의 배경이 이웃 글자를 덮는다 + text_elements = [(rect, glyph_alpha(poster, rect, config.glyph_dark_ink)) + for rect, _, _ in config.punches] + text_elements += [(rect, glyph_alpha(poster, rect, config.glyph_dark_ink)) + for rect in config.protect] + registration = (1.0, 0, 0) + + for index in range(total): + seconds = index / FPS + if index < hold_frames: + artwork = base + else: + artwork = read_clip(index - hold_frames) + if do_register: + artwork, registration, _ = register(artwork, base, masks["hold"], registration) + + frame = artwork * (1 - hold) + base * hold + + for name, rect in config.glyphs.items(): + progress = (seconds - config.sweep_at.get(name, 0.0)) / SWEEP_SECONDS + if 0 <= progress <= 1: + gx0, gx1 = rect[0] * width, rect[2] * width + band_x = gx0 - 120 + (gx1 - gx0 + 240) * progress + band = np.exp(-((xs - 0.35 * (ys - rect[1] * height)) - band_x) ** 2 + / (2 * 55.0 ** 2)) + frame = frame + SWEEP_GAIN * (band * masks["glyph"][name])[..., None] + + for rect, at in config.glows: + progress = (seconds - at) / GLOW_SECONDS + if 0 <= progress <= 1: + glow = glow_masks.setdefault( + rect, np.asarray(glyph_alpha(poster, rect, config.glyph_dark_ink)) / 255.0) + frame = frame + GLOW_GAIN * math.sin(math.pi * progress) * glow[..., None] + + image = Image.fromarray(np.clip(frame, 0, 255).astype(np.uint8)) + active = [] + for order, (rect, at, peak) in enumerate(config.punches): + scale = punch_scale(seconds - at, peak) + if scale != 1.0: + pop_rect(image, poster, rect, scale) + active.append(order) + if active: + for order, (_, alpha) in enumerate(text_elements): + if order not in active: + image.paste(poster, (0, 0), alpha) + yield image + + +def render_hybrid(poster: bytes | Path | Image.Image, clip: bytes | Path, + config: LayerConfig, *, preview: bool = False) -> HybridResult: + if isinstance(poster, Image.Image): + source = poster.convert("RGB") + else: + source = Image.open(poster if isinstance(poster, Path) + else io.BytesIO(poster)).convert("RGB") + masks = build_masks(source, config) + do_register = config.hybrid.register or config.mask.mode == "glyph" + + proof_at = {round(step * DURATION * FPS / PROOF_COUNT) for step in range(PROOF_COUNT)} + proof_tiles: list[Image.Image] = [] + + def frames() -> Iterator[Image.Image]: + for index, image in enumerate(compose_frames(source, config, clip, masks, do_register)): + if preview and index in proof_at: + proof_tiles.append(image.resize(PROOF_SIZE)) + yield image + + video = encode_mp4(frames(), source.size, fps=FPS, crf=CRF) + + sheet = None + if proof_tiles: + sheet = Image.new("RGB", ((PROOF_SIZE[0] + 10) * len(proof_tiles), PROOF_SIZE[1]), "black") + for order, tile in enumerate(proof_tiles): + sheet.paste(tile, (order * (PROOF_SIZE[0] + 10), 0)) + + return HybridResult(video=video, frames=int(DURATION * FPS), duration=DURATION, proof=sheet) diff --git a/backend/services/i2v.py b/backend/services/i2v.py index 53f31c9..046abcc 100644 --- a/backend/services/i2v.py +++ b/backend/services/i2v.py @@ -8,7 +8,7 @@ import httpx from PIL import Image from models.detect import Regions -from models.i2v import I2vResult +from models.i2v import I2vResult, TitleGateVerdict from services.title_gate import check_title from settings import settings from utils.higgsfield import (KLING_3_0, assert_account, parse_credits, parse_result_url, @@ -45,7 +45,7 @@ async def estimate_credits(prompt: str, poster: Path, model: str = KLING_3_0) -> "generate", "cost", model, *cli_args(prompt, poster, model), "--json", timeout=300)) -async def animate(prompt: str, poster: Path, regions: Regions, *, +async def animate(prompt: str, poster: Path, regions: Regions | None = None, *, model: str = KLING_3_0, max_credits: float = MAX_CREDITS) -> I2vResult: if not prompt.strip(): @@ -66,7 +66,9 @@ async def animate(prompt: str, poster: Path, regions: Regions, *, if len(clip) < MIN_CLIP_BYTES: raise RuntimeError(f"클립이 너무 작다 ({len(clip)}바이트) — 다운로드 실패로 본다") - verdict = await check_title(clip, regions) + # 영역 좌표가 없으면 제목 훼손을 잴 근거가 없다. 통과시키되 그 사실을 남긴다 + verdict = (await check_title(clip, regions) if regions + else TitleGateVerdict(passed=True, skip="regions 없음 — 제목 게이트 미실행")) if not verdict.passed: raise RuntimeError(f"제목 훼손 감지 — {verdict.reason} " "(재렌더하거나 모션 요소를 줄여보세요)") diff --git a/backend/services/narration_slots.py b/backend/services/narration_slots.py new file mode 100644 index 0000000..b3266a7 --- /dev/null +++ b/backend/services/narration_slots.py @@ -0,0 +1,36 @@ +"""⑥ narration — 롱컷 나레이션 7문장. + +축제 3문장이 VLM 생성인 것과 달리 여기는 meta에서 채우는 고정 슬롯이다. +캐스팅 스케줄 문장은 예매 전에 확인하는 정보라 빠지면 안 된다. +""" +from models.cast import CastExtraction +from models.narration_slots import NARRATION_SLOTS, NarrationLine, SlotNarration +from models.nol import NolMeta + +MAX_CAST_IN_LINE = 3 +DEFAULT_GENRE = "공연" + + +def period_text(meta: NolMeta) -> str: + start, end = meta.play_start_date or "", meta.play_end_date or "" + period = f"{start} ~ {end}".strip(" ~") if (start or end) else "" + return period.replace("-", ".") + + +def build_narration(meta: NolMeta, cast: CastExtraction | None = None) -> SlotNarration: + title = meta.goods_name or "" + names = "·".join((cast.names if cast else [])[:MAX_CAST_IN_LINE]) + date_text = period_text(meta) + place = meta.place_name or "" + + texts = [ + f"{title}, 무대에서 만나세요.", + "포스터가 움직이기 시작합니다.", + f"{meta.genre_name or DEFAULT_GENRE}의 한 장면을 미리 봅니다.", + f"{names} 출연." if names else "출연진을 상세페이지에서 확인하세요.", + "캐스팅 스케줄은 상세페이지에서 확인하세요.", + f"{date_text} {place}".strip() + ".", + "지금 예매하세요.", + ] + return SlotNarration(lines=[NarrationLine(slot=slot, text=text) + for slot, text in zip(NARRATION_SLOTS, texts, strict=True)]) diff --git a/backend/tests/playreel/test_bgm.py b/backend/tests/playreel/test_bgm.py new file mode 100644 index 0000000..2a2960a --- /dev/null +++ b/backend/tests/playreel/test_bgm.py @@ -0,0 +1,46 @@ +"""⑧ bgm 수동 확인용. **Suno는 실제 과금이 나간다.** + +사용: uv run python -m tests.playreel.test_bgm +롱컷은 나레이션을 VLM이 쓰지 않아 BGM 스타일도 안 나오므로 기본 스타일을 쓴다. +결과는 nol_/bgm.mp3 와 bgm.json. +""" +import asyncio +import json +import sys +from pathlib import Path + +from models.tts import NarrationTimeline +from services.bgm import DEFAULT_BGM_STYLE, generate_bgm + +TEST_RESULT_DIR = Path(__file__).parent.parent / "test_result" / "playreel" + + +async def main() -> None: + goods_id = sys.argv[1] + product_dir = TEST_RESULT_DIR / f"nol_{goods_id}" + timeline_path = product_dir / "timeline.json" + if not timeline_path.exists(): + raise SystemExit(f"{timeline_path} 없음 — test_tts 를 먼저 돌릴 것") + + timeline = NarrationTimeline.model_validate_json( + timeline_path.read_text(encoding="utf-8")) + print(f"나레이션 {timeline.total}s → BGM 요청 (기본 스타일)") + print(f" style : {DEFAULT_BGM_STYLE.style}") + print("Suno 생성 시작 — 최대 5분 폴링, 과금됩니다.") + + audio = await generate_bgm(DEFAULT_BGM_STYLE, timeline.total, title=f"nol_{goods_id}") + + mp3_path = product_dir / "bgm.mp3" + meta_path = product_dir / "bgm.json" + mp3_path.write_bytes(audio.mp3) + meta_path.write_text(json.dumps( + {"task_id": audio.task_id, "seconds": audio.seconds, "duration": audio.duration, + "style": DEFAULT_BGM_STYLE.style, "prompt": DEFAULT_BGM_STYLE.prompt}, + ensure_ascii=False, indent=2), encoding="utf-8") + + print(f"\n목표 {audio.seconds}s → 실제 {audio.duration}s (taskId={audio.task_id})") + print(f"{mp3_path}\n{meta_path}") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/backend/tests/playreel/test_hybrid_poster.py b/backend/tests/playreel/test_hybrid_poster.py new file mode 100644 index 0000000..5fa559f --- /dev/null +++ b/backend/tests/playreel/test_hybrid_poster.py @@ -0,0 +1,43 @@ +"""⑩ hybrid 수동 확인용 — 생성 클립 위에 원본 고정층을 덮는다. + +사용: uv run python -m tests.playreel.test_hybrid_poster +config는 작품별 좌표 파일이다(fixed_rects·sil_poly·glyphs·punches). 아직 사람이 쓴다. +결과는 nol_/hybrid.mp4 와 hybrid_proof.jpg. +""" +import sys +from pathlib import Path + +from models.hybrid import LayerConfig +from services.hybrid_poster import render_hybrid + +TEST_RESULT_DIR = Path(__file__).parent.parent / "test_result" / "playreel" + + +def main() -> None: + goods_id, config_path = sys.argv[1], Path(sys.argv[2]) + product_dir = TEST_RESULT_DIR / f"nol_{goods_id}" + poster_path = product_dir / "upscaled.png" + clip_path = product_dir / "clip.mp4" + for required in (poster_path, clip_path, config_path): + if not required.exists(): + raise SystemExit(f"{required} 없음") + + config = LayerConfig.model_validate_json(config_path.read_text(encoding="utf-8")) + print(f"config {config_path.name} · mask={config.mask.mode}" + f" · 고정사각 {len(config.fixed_rects)} · 글리프 {len(config.glyphs)}" + f" · 펀치 {len(config.punches)} · 정합 {config.hybrid.register}") + + result = render_hybrid(poster_path, clip_path.read_bytes(), config, preview=True) + + video_path = product_dir / "hybrid.mp4" + video_path.write_bytes(result.video) + print(f"{result.frames}프레임 · {result.duration}초 · {len(result.video) / 1e6:.1f}MB") + if result.proof: + proof_path = product_dir / "hybrid_proof.jpg" + result.proof.save(proof_path, quality=85) + print(f"{proof_path}") + print(f"{video_path}") + + +if __name__ == "__main__": + main() diff --git a/backend/tests/playreel/test_i2v.py b/backend/tests/playreel/test_i2v.py new file mode 100644 index 0000000..2c1f362 --- /dev/null +++ b/backend/tests/playreel/test_i2v.py @@ -0,0 +1,44 @@ +"""⑨ i2v 수동 확인용 — 되돌릴 수 없는 지점이다. + +사용: uv run python -m tests.playreel.test_i2v +업스케일 포스터와 ⑤에서 확정한 프롬프트를 쓴다. +detect를 안 거쳐 regions가 없으므로 제목 훼손 게이트는 돌지 않는다. +결과는 nol_/clip.mp4 와 i2v.json. +""" +import asyncio +import json +import sys +from pathlib import Path + +from services.i2v import animate + +TEST_RESULT_DIR = Path(__file__).parent.parent / "test_result" / "playreel" + + +async def main() -> None: + goods_id = sys.argv[1] + product_dir = TEST_RESULT_DIR / f"nol_{goods_id}" + poster_path = product_dir / "upscaled.png" + prompt_path = product_dir / "i2v_prompt.txt" + for required in (poster_path, prompt_path): + if not required.exists(): + raise SystemExit(f"{required} 없음 — 앞 단계를 먼저 돌릴 것") + + result = await animate(prompt_path.read_text(encoding="utf-8").strip(), poster_path) + + clip_path = product_dir / "clip.mp4" + summary_path = product_dir / "i2v.json" + clip_path.write_bytes(result.clip) + summary_path.write_text(json.dumps( + {"model": result.model, "credits": result.credits, + "title_gate": result.title_gate.model_dump()}, + ensure_ascii=False, indent=2), encoding="utf-8") + + print(f"{result.model} · {result.credits}크레딧 · {len(result.clip) / 1e6:.1f}MB") + if result.title_gate.skip: + print(f"제목 게이트: {result.title_gate.skip}") + print(f"\n{clip_path}\n{summary_path}") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/backend/tests/playreel/test_motion.py b/backend/tests/playreel/test_motion.py new file mode 100644 index 0000000..5e41338 --- /dev/null +++ b/backend/tests/playreel/test_motion.py @@ -0,0 +1,55 @@ +"""⑤ motion 수동 확인용 — 게이트 ②에서 사람이 고른 요소로 프롬프트를 확정한다. + +사용: uv run python -m tests.playreel.test_motion [모션키,쉼표구분] +모션키를 생략하면 analysis.json 에서 켜진(on) 요소를 그대로 쓴다. +결과는 nol_/i2v_prompt.txt 와 motion.json. +""" +import asyncio +import json +import sys +from pathlib import Path + +from services.motion import plan_motion + +TEST_RESULT_DIR = Path(__file__).parent.parent / "test_result" / "playreel" + + +def chosen_motions(product_dir: Path) -> list[str]: + analysis_path = product_dir / "analysis.json" + if not analysis_path.exists(): + raise SystemExit(f"{analysis_path} 없음 — test_analyze_poster 를 먼저 돌릴 것") + analysis = json.loads(analysis_path.read_text(encoding="utf-8")) + return [choice["key"] for choice in analysis["movable"] if choice["on"]] + + +async def main() -> None: + goods_id = sys.argv[1] + product_dir = TEST_RESULT_DIR / f"nol_{goods_id}" + poster_path = product_dir / "upscaled.png" + if not poster_path.exists(): + raise SystemExit(f"{poster_path} 없음 — test_upscale_poster 를 먼저 돌릴 것") + + if len(sys.argv) > 2: + keys = [key.strip() for key in sys.argv[2].split(",") if key.strip()] + else: + keys = chosen_motions(product_dir) + print(f"고른 요소 {keys or '(없음)'}") + + plan = await plan_motion(poster_path, force_motions=keys) + + prompt_path = product_dir / "i2v_prompt.txt" + summary_path = product_dir / "motion.json" + prompt_path.write_text(plan.prompt, encoding="utf-8") + summary_path.write_text(plan.model_dump_json(indent=2, exclude={"prompt"}), + encoding="utf-8") + + print(f"QR {'있음' if plan.has_qr else '없음'} · 채택 {len(plan.kept)}종") + for item in plan.kept: + print(f" ✓ {item.motion:9} {item.what}") + if not plan.kept: + print("\n※ 요소가 0종이다 — i2v가 정지 이미지를 애니메이션하지 못한다") + print(f"\n{prompt_path}\n{summary_path}") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/backend/tests/playreel/test_narration_slots.py b/backend/tests/playreel/test_narration_slots.py new file mode 100644 index 0000000..aee465e --- /dev/null +++ b/backend/tests/playreel/test_narration_slots.py @@ -0,0 +1,42 @@ +"""⑥ narration 수동 확인용 — meta와 캐스트로 7문장을 채운다. + +사용: uv run python -m tests.playreel.test_narration_slots +결과는 nol_/narration.json. +""" +import sys +from pathlib import Path + +from models.cast import CastExtraction +from models.nol import NolMeta +from services.narration_slots import build_narration + +TEST_RESULT_DIR = Path(__file__).parent.parent / "test_result" / "playreel" + + +def main() -> None: + goods_id = sys.argv[1] + product_dir = TEST_RESULT_DIR / f"nol_{goods_id}" + meta_path = product_dir / "meta.json" + if not meta_path.exists(): + raise SystemExit(f"{meta_path} 없음 — test_fetch_nol 을 먼저 돌릴 것") + + meta = NolMeta.model_validate_json(meta_path.read_text(encoding="utf-8")) + cast_path = product_dir / "cast.json" + cast = (CastExtraction.model_validate_json(cast_path.read_text(encoding="utf-8")) + if cast_path.exists() else None) + + narration = build_narration(meta, cast) + narration_path = product_dir / "narration.json" + narration_path.write_text(narration.model_dump_json(indent=2), encoding="utf-8") + + total_chars = sum(len(line.text) for line in narration.lines) + for line in narration.lines: + print(f" {line.slot:12} {line.text}") + print(f"\n7문장 {total_chars}자") + if cast is None or cast.source != "vlm": + print("※ 캐스트가 없어 4번 문장이 안내 문구로 대체됐다") + print(f"\n{narration_path}") + + +if __name__ == "__main__": + main() diff --git a/backend/tests/playreel/test_tts.py b/backend/tests/playreel/test_tts.py new file mode 100644 index 0000000..59eb7e2 --- /dev/null +++ b/backend/tests/playreel/test_tts.py @@ -0,0 +1,46 @@ +"""⑦ tts 수동 확인용 — Typecast로 7문장을 읽는다. + +사용: uv run python -m tests.playreel.test_tts +.env 의 TYPECAST_API_KEY 와 TYPECAST_VOICE_ID 가 필요하다. +결과는 nol_/narration.mp3 와 timeline.json. +""" +import asyncio +import sys +from pathlib import Path + +from models.narration_slots import SlotNarration +from models.tts import TypecastVoice +from services.tts import synthesize +from settings import settings + +TEST_RESULT_DIR = Path(__file__).parent.parent / "test_result" / "playreel" +LONGCUT_SECONDS = 30 + + +async def main() -> None: + goods_id = sys.argv[1] + product_dir = TEST_RESULT_DIR / f"nol_{goods_id}" + narration_path = product_dir / "narration.json" + if not narration_path.exists(): + raise SystemExit(f"{narration_path} 없음 — test_narration_slots 를 먼저 돌릴 것") + if not settings.typecast_api_key: + raise SystemExit("TYPECAST_API_KEY 없음 — 롱컷은 Typecast 고정이다") + + narration = SlotNarration.model_validate_json(narration_path.read_text(encoding="utf-8")) + audio = await synthesize(narration.texts, typecast=TypecastVoice()) + + mp3_path = product_dir / "narration.mp3" + timeline_path = product_dir / "timeline.json" + mp3_path.write_bytes(audio.mp3) + timeline_path.write_text(audio.timeline.model_dump_json(indent=2), encoding="utf-8") + + for cue in audio.timeline.cues: + print(f" [{cue.index}] {cue.start:5.2f}s +{cue.duration:4.2f}s {cue.text}") + print(f"\n총 {audio.timeline.total}s") + if audio.timeline.total > LONGCUT_SECONDS: + print(f"※ {LONGCUT_SECONDS}초를 넘는다 — 문장을 줄이거나 속도를 올려야 한다") + print(f"\n{mp3_path}\n{timeline_path}") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/backend/tests/run_playreel_after_gate2.sh b/backend/tests/run_playreel_after_gate2.sh new file mode 100755 index 0000000..02e0cc4 --- /dev/null +++ b/backend/tests/run_playreel_after_gate2.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# Playreel 롱컷 — 게이트 ② 승인 뒤, 게이트 ③(narration_confirm) 직전까지. +# 사용: tests/run_playreel_after_gate2.sh [모션키,쉼표구분] +set -euo pipefail +cd "$(dirname "$0")/.." + +goods_id="${1:?사용: $0 [모션키,쉼표구분]}" + +run() { echo; echo "── $1 ──"; shift; uv run python -m "$@"; } + +run "⑤ motion" tests.playreel.test_motion "$goods_id" ${2+"$2"} +run "⑥ narration" tests.playreel.test_narration_slots "$goods_id" + +cat < +set -euo pipefail +cd "$(dirname "$0")/.." + +goods_id="${1:?사용: $0 }" + +run() { echo; echo "── $1 ──"; shift; uv run python -m "$@"; } + +run "⑦ tts" tests.playreel.test_tts "$goods_id" +run "⑧ bgm" tests.playreel.test_bgm "$goods_id" +run "⑨ i2v" tests.playreel.test_i2v "$goods_id" + +cat <