render까지 8초 shortform pipeline 형성

This commit is contained in:
jaehwang committed 2026-09-03 16:50:44 +09:00
1 parent 05747f6b8f
commit 659fd53b97
30 files changed
+1203 -30

No files matched your search

+81
View File
@@ -0,0 +1,81 @@
"""⑤ bgm — Suno V5 인스트루멘털 BGM.
보컬이 있으면 나레이션과 주파수·의미가 겹쳐 둘 다 안 들리므로 반드시 instrumental로 뽑고,
목표 길이는 나레이션 실측 길이에서 역산한다.
"""
import asyncio
import httpx
from answers.narration_answer import BgmStyle
from models.bgm import BgmAudio
from settings import settings
SUNO_API = "https://api.sunoapi.org/api/v1"
SUNO_MODEL = "V5_5" # duration 파라미터가 V5_5 + customMode에서만 먹는다
POLL_INTERVAL = 15
POLL_ATTEMPTS = 20
MIN_SECONDS, MAX_SECONDS = 10, 30 # duration 허용 범위 하한이 10초다
SECONDS_MARGIN = 2
def target_seconds(narration_total: float) -> int:
return int(min(MAX_SECONDS, max(MIN_SECONDS, round(narration_total) + SECONDS_MARGIN)))
async def request_generation(client: httpx.AsyncClient, style: BgmStyle, seconds: int,
title: str) -> str:
response = await client.post(
f"{SUNO_API}/generate",
json={
"model": SUNO_MODEL,
"customMode": True,
"instrumental": True,
"duration": seconds,
"prompt": style.prompt,
"style": style.style,
"title": title,
"callBackUrl": settings.suno_callback_url,
})
response.raise_for_status()
task_id = (response.json().get("data") or {}).get("taskId", "")
if not task_id:
raise RuntimeError(f"Suno가 taskId를 안 줬다: {response.text[:300]}")
return task_id
async def wait_for_tracks(client: httpx.AsyncClient, task_id: str) -> list[dict]:
for _ in range(POLL_ATTEMPTS):
await asyncio.sleep(POLL_INTERVAL)
response = await client.get(f"{SUNO_API}/generate/record-info", params={"taskId": task_id})
response.raise_for_status()
data = response.json().get("data") or {}
status = data.get("status", "")
if status == "SUCCESS":
tracks = (data.get("response") or {}).get("sunoData", [])
if not tracks:
raise RuntimeError(f"트랙 없음 (taskId={task_id})")
return tracks
if "FAIL" in status or "ERROR" in status:
raise RuntimeError(f"Suno 생성 실패: {status} (taskId={task_id})")
raise RuntimeError(f"Suno 타임아웃 {POLL_INTERVAL * POLL_ATTEMPTS}초 (taskId={task_id})")
async def generate_bgm(style: BgmStyle, narration_total: float,
title: str = "festival bgm") -> BgmAudio:
if not settings.suno_api_key:
raise RuntimeError("SUNO_API_KEY 없음")
seconds = target_seconds(narration_total)
async with httpx.AsyncClient(
timeout=180, headers={"Authorization": f"Bearer {settings.suno_api_key}"}) as client:
task_id = await request_generation(client, style, seconds, title)
tracks = await wait_for_tracks(client, task_id)
# 목표 길이에 가장 가까운 트랙 — 가장 긴 것이 아니다
track = min(tracks, key=lambda t: abs((t.get("duration") or 0) - seconds))
download = await client.get(track["audioUrl"], follow_redirects=True)
download.raise_for_status()
return BgmAudio(mp3=download.content, seconds=seconds,
duration=float(track.get("duration") or 0), task_id=task_id)
+142
View File
@@ -0,0 +1,142 @@
"""① detect — 포스터에서 카메라가 겨냥할 영역을 검출한다.
격자 위에서 VLM이 대략 읽고, 그 주변에서만 잉크 경계로 다듬는다.
"""
from pathlib import Path
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from scipy import ndimage
from answers.detect_answer import DetectAnswer, GridBox
from models.detect import Box, DetectResult, Focal, Regions
from settings import settings
from utils.common_llm import StructuredLLM
from utils.image import to_data_uri
from utils.prompt import load_prompt
Image.MAX_IMAGE_PIXELS = None
WORK_WIDTH_PX = 1100
REGION_KINDS = ("title", "datetime", "place", "logo")
REGION_COLORS = {"title": (255, 60, 60), "datetime": (60, 220, 255),
"place": (140, 255, 140), "logo": (255, 200, 60)}
DETECT_PROMPT = load_prompt("detect")
detect_llm = StructuredLLM("gpt-4o", settings.chatgpt_api_key)
def grid_overlay(poster: Image.Image) -> Image.Image:
overlay = poster.convert("RGB").copy()
width, height = overlay.size
draw = ImageDraw.Draw(overlay, "RGBA")
font = ImageFont.load_default(max(14, width // 55))
for row in range(1, 20):
y = int(height * row * 0.05)
draw.line([(0, y), (width, y)], fill=(255, 0, 80, 150), width=max(1, width // 700))
if row % 2 == 0:
draw.text((4, y + 2), f"{row * 5}", font=font, fill=(255, 255, 0, 255))
for col in range(1, 10):
x = int(width * col * 0.10)
draw.line([(x, 0), (x, height)], fill=(0, 220, 255, 130), width=max(1, width // 700))
draw.text((x + 3, 3), f"{col * 10}", font=font, fill=(0, 255, 255, 255))
return overlay
def check_overlay(poster: Image.Image, regions: dict[str, Box],
focal_points: list[Focal]) -> Image.Image:
overlay = poster.convert("RGB").copy()
width, height = overlay.size
draw = ImageDraw.Draw(overlay)
font = ImageFont.load_default(max(16, width // 45))
for kind, box in regions.items():
color = REGION_COLORS.get(kind, (255, 255, 255))
draw.rectangle([box.x0 * width, box.y0 * height, box.x1 * width, box.y1 * height],
outline=color, width=max(3, width // 300))
draw.text((box.x0 * width + 6, box.y0 * height + 4), kind, font=font, fill=color)
for focal in focal_points:
x, y = focal.cx * width, focal.cy * height
radius = max(10, width // 60)
draw.ellipse([x - radius, y - radius, x + radius, y + radius],
outline=(255, 255, 0), width=max(3, width // 300))
draw.text((x + radius + 4, y - radius), focal.name, font=font, fill=(255, 255, 0))
return overlay
def ink_mask(poster: Image.Image) -> np.ndarray:
"""다중 스케일 국소 대비. 창이 획 두께보다 커야 굵은 글씨가 안 빠진다."""
brightness = np.asarray(poster).astype(np.float32).max(2)
height, width = brightness.shape
mask = np.zeros((height, width), bool)
for window in (width // 40, width // 12, width // 5):
local_mean = ndimage.uniform_filter(brightness, max(11, window) | 1)
mask |= brightness > local_mean + 18
mask |= brightness < local_mean - 36
return mask
def tighten_box(answer_box: GridBox, ink: np.ndarray,
pad_ratio: float = 0.03) -> dict[str, float] | None:
"""VLM이 준 대략 박스 주변에서만 잉크 경계를 찾아 정규화 좌표로 조인다."""
height, width = ink.shape
left = int(max(0, (answer_box.x0 / 100 - pad_ratio) * width))
right = int(min(width, (answer_box.x1 / 100 + pad_ratio) * width))
top = int(max(0, (answer_box.y0 / 100 - pad_ratio) * height))
bottom = int(min(height, (answer_box.y1 / 100 + pad_ratio) * height))
if right <= left or bottom <= top:
return None
patch = ink[top:bottom, left:right]
if patch.sum() < 50:
return None
row_density, col_density = patch.mean(1), patch.mean(0)
ink_rows = np.where(row_density > max(0.02, row_density.max() * 0.12))[0]
ink_cols = np.where(col_density > max(0.02, col_density.max() * 0.12))[0]
if len(ink_rows) == 0 or len(ink_cols) == 0:
return None
return {"x0": round((left + ink_cols.min()) / width, 4),
"x1": round((left + ink_cols.max() + 1) / width, 4),
"y0": round((top + ink_rows.min()) / height, 4),
"y1": round((top + ink_rows.max() + 1) / height, 4)}
async def detect(poster: Path | Image.Image) -> DetectResult:
source = (Image.open(poster) if isinstance(poster, Path) else poster).convert("RGB")
work_image = source.copy()
work_image.thumbnail((WORK_WIDTH_PX, WORK_WIDTH_PX * 3), Image.LANCZOS)
grid_image = grid_overlay(work_image)
answer = await detect_llm.ask_with_images(
DetectAnswer, DETECT_PROMPT, [("격자를 씌운 포스터:", to_data_uri(grid_image))])
ink = ink_mask(work_image)
regions: dict[str, Box] = {}
vlm_raw: dict = {}
for kind in REGION_KINDS:
answer_box: GridBox | None = getattr(answer, kind)
if answer_box is None:
continue
vlm_raw[kind] = answer_box.model_dump()
# 다듬기 실패 시 VLM 값을 그대로 쓴다
box = tighten_box(answer_box, ink) or {
corner: round(getattr(answer_box, corner) / 100, 4)
for corner in ("x0", "y0", "x1", "y1")}
regions[kind] = Box(**box, cx=round((box["x0"] + box["x1"]) / 2, 4),
cy=round((box["y0"] + box["y1"]) / 2, 4), text=answer_box.text)
focal_points = [Focal(name=focal.name, cx=round(focal.x / 100, 4), cy=round(focal.y / 100, 4))
for focal in answer.focal_points]
return DetectResult(
data=Regions(
festival_name=answer.festival_name,
title_style=answer.title_style,
recommended_mode="layered" if answer.title_style == "calligraphy" else "camera",
poster_size=source.size,
regions=regions,
focal_points=focal_points,
vlm_raw=vlm_raw,
),
grid=grid_image,
check=check_overlay(work_image, regions, focal_points),
)
+74
View File
@@ -0,0 +1,74 @@
"""⑥ i2v — 포스터 + 모션 프롬프트 → 생성형 애니메이션 클립.
생성 전에 계정 가드와 저해상 거절, 생성 후에 제목 훼손 게이트가 붙는다.
"""
from pathlib import Path
import httpx
from PIL import Image
from models.detect import Regions
from models.i2v import I2vResult
from services.title_gate import check_title
from settings import settings
from utils.higgsfield import assert_account, parse_credits, parse_result_url, run_cli
# 프로덕션 표준은 Kling 3.0 pro. veo3_1은 저작권 콜백·실패 과금 사례로 제외.
DEFAULT_MODEL = "kling3_0"
VEO_QUALITY = "high"
CLIP_SECONDS = 8
ASPECT_RATIO = "9:16"
MAX_CREDITS = 60.0
MIN_LONG_EDGE_PX = 1000 # 긴 변이 이보다 짧으면 확대 시 뭉개진다
MIN_CLIP_BYTES = 10_000
def reject_low_resolution(poster: Path) -> None:
"""검출·나레이션·TTS·BGM은 해상도와 무관하게 유효하므로 i2v에서만 거절한다."""
with Image.open(poster) as image:
if max(image.size) < MIN_LONG_EDGE_PX:
raise RuntimeError(
f"저해상 포스터 {image.size} — 확대 시 뭉개져 애니메이션을 건너뜁니다. "
"고해상 원본으로 다시 올려주세요.")
def cli_args(prompt: str, poster: Path, model: str) -> list[str]:
args = ["--prompt", prompt, "--start-image", str(poster),
"--duration", str(CLIP_SECONDS), "--aspect_ratio", ASPECT_RATIO]
if model == "kling3_0":
# Kling은 9:16을 지정해도 포스터 비율로 출력한다 — 합성 단계에서 맞춘다
return args + ["--mode", "pro", "--sound", "off"]
return args + ["--quality", VEO_QUALITY]
async def estimate_credits(prompt: str, poster: Path, model: str = DEFAULT_MODEL) -> float:
return parse_credits(await run_cli(
"generate", "cost", model, *cli_args(prompt, poster, model), "--json", timeout=300))
async def animate(prompt: str, poster: Path, regions: Regions, *,
model: str = DEFAULT_MODEL,
max_credits: float = MAX_CREDITS) -> I2vResult:
if not prompt.strip():
raise ValueError("i2v 프롬프트가 비어 있다 — motion 단계를 먼저 돌릴 것")
reject_low_resolution(poster)
await assert_account(settings.higgsfield_account) # 크레딧 쓰기 전에
credits = await estimate_credits(prompt, poster, model)
if credits > max_credits:
raise RuntimeError(f"비용 {credits:g}크레딧이 상한 {max_credits:g}를 넘는다 — 설정 확인")
output = await run_cli("generate", "create", model, *cli_args(prompt, poster, model),
"--wait", "--wait-timeout", "25m", "--json")
async with httpx.AsyncClient(timeout=600, follow_redirects=True) as client:
response = await client.get(parse_result_url(output))
response.raise_for_status()
clip = response.content
if len(clip) < MIN_CLIP_BYTES:
raise RuntimeError(f"클립이 너무 작다 ({len(clip)}바이트) — 다운로드 실패로 본다")
verdict = await check_title(clip, regions)
if not verdict.passed:
raise RuntimeError(f"제목 훼손 감지 — {verdict.reason} "
"(재렌더하거나 모션 요소를 줄여보세요)")
return I2vResult(clip=clip, credits=credits, model=model, title_gate=verdict)
+85
View File
@@ -0,0 +1,85 @@
"""③ motion — 포스터에서 움직일 요소를 골라 i2v 프롬프트를 만든다.
모션 어휘를 카탈로그로 나열하면 모델이 포스터에 없는 관람차까지 그려 넣으므로,
무엇이 있는지만 VLM에게 묻고 어떻게 움직이는지는 검증된 문구로 고정한다.
"""
from pathlib import Path
from typing import get_args
from PIL import Image
from answers.motion_answer import MotionAnswer, MotionElement, MotionKey
from models.motion import DroppedMotion, MotionItem, MotionPlan
from settings import settings
from utils.common_llm import StructuredLLM
from utils.image import to_data_uri
from utils.prompt import load_prompt, load_prompt_json
from utils.qr import qr_box
Image.MAX_IMAGE_PIXELS = None
POSTER_MAX_SIZE = (1100, 1600)
MOTION_PHRASES: dict[str, str] = load_prompt_json("motion_phrase")
MOTION_QR_BLOCKS: dict[str, dict[str, str]] = load_prompt_json("motion_qr")
MOTION_FRAME = load_prompt("motion_frame")
MOTION_VLM_PROMPT = load_prompt("motion_vlm")
motion_llm = StructuredLLM("gpt-4o", settings.chatgpt_api_key)
_missing_phrases = set(get_args(MotionKey)) - MOTION_PHRASES.keys()
if _missing_phrases:
raise RuntimeError(f"motion_phrase.json에 문구가 없는 모션 키: {sorted(_missing_phrases)}")
def build_prompt(elements: list[MotionElement], has_qr: bool, extra: str = "") -> MotionPlan:
"""확신 있는 요소만 남기고, 같은 종류는 한 번만 지시한다."""
kept, dropped = [], []
for element in elements:
if element.confident:
kept.append(MotionItem(motion=element.motion, what=element.what))
else:
# 애매하면 안 움직이는 쪽이 기본값
dropped.append(DroppedMotion(motion=element.motion, what=element.what, why="확신없음"))
seen: set[str] = set()
lines = []
for item in kept:
if item.motion in seen:
continue
seen.add(item.motion)
lines.append(MOTION_PHRASES[item.motion])
body = "\n\n".join(lines)
if extra: # 포스터별 고정 지시
body += "\n\n" + extra.strip()
qr_blocks = MOTION_QR_BLOCKS["present" if has_qr else "absent"]
return MotionPlan(
prompt=MOTION_FRAME.format(body=body, **qr_blocks),
has_qr=has_qr,
kept=kept,
dropped=dropped,
)
async def plan_motion(poster: Path | Image.Image, *, has_qr: bool | None = None,
force_motions: list[str] | None = None, extra: str = "") -> MotionPlan:
"""force_motions를 주면 VLM을 건너뛰고 그 목록으로 만든다(검수 게이트 수동 지정, 빈 리스트면 0종)."""
source = (Image.open(poster) if isinstance(poster, Path) else poster).convert("RGB")
if force_motions is None:
answer = await motion_llm.ask_with_images(
MotionAnswer, MOTION_VLM_PROMPT,
[("포스터:", to_data_uri(source, POSTER_MAX_SIZE))])
elements = answer.elements
else:
unknown = [key for key in force_motions if key not in MOTION_PHRASES]
if unknown:
raise ValueError(f"미지의 모션 키: {unknown} — 허용: {', '.join(MOTION_PHRASES)}")
elements = [MotionElement(motion=key, what="검수 게이트 수동 지정", confident=True)
for key in force_motions]
# QR 언급은 주문서다 — 없는 포스터에 보존 문구를 넣으면 모델이 QR을 그려 넣는다
if has_qr is None:
has_qr = qr_box(source) is not None
return build_prompt(elements, has_qr, extra)
+86
View File
@@ -0,0 +1,86 @@
"""② narration_text — 나레이션 3문장 + voice + BGM 스타일 + 메타태그.
상류 오독을 프롬프트에 넣으면 하류가 이미지를 다시 보지 않고 베껴 쓰므로,
앞 단계가 읽은 글자 대신 좌표만 넘기고 글자는 확대 크롭에서 직접 읽게 한다.
"""
import json
from pathlib import Path
from PIL import Image
from pydantic import ValidationError
from answers.narration_answer import NarrationAnswer
from models.detect import Box, Regions
from settings import settings
from utils.common_llm import StructuredLLM
from utils.image import to_data_uri
from utils.prompt import load_prompt
Image.MAX_IMAGE_PIXELS = None
# 글자를 읽어야 하는 영역만 잘라 확대해 따로 보여준다 (장식 서체 오독 방지)
CROP_LABELS = (("② 제목 영역 확대", "title"),
("③ 일시 영역 확대", "datetime"),
("④ 장소 영역 확대", "place"))
CROP_LONG_EDGE = 1024
POSTER_MAX_SIZE = (1024, 1024)
NARRATION_TEMPERATURE = 0.6
NARRATION_SYSTEM_PROMPT = load_prompt("narration")
NARRATION_RETRY_PROMPT = load_prompt("narration_retry")
narration_llm = StructuredLLM("gpt-4o", settings.chatgpt_api_key)
def crop_region(poster: Image.Image, box: Box, pad: float = 0.03) -> Image.Image | None:
"""전체 한 장으로는 장식 서체의 획 간격을 놓치므로 해당 영역만 잘라 확대한다."""
width, height = poster.size
left = int(max(0.0, box.x0 - pad) * width)
right = int(min(1.0, box.x1 + pad) * width)
top = int(max(0.0, box.y0 - pad) * height)
bottom = int(min(1.0, box.y1 + pad) * height)
if right - left < 16 or bottom - top < 16:
return None
crop = poster.crop((left, top, right, bottom))
scale = CROP_LONG_EDGE / max(crop.size)
if scale > 1:
crop = crop.resize((round(crop.width * scale), round(crop.height * scale)), Image.LANCZOS)
return crop
def build_images(poster: Image.Image, regions: Regions) -> list[tuple[str, str]]:
images = [("① 포스터 전체:", to_data_uri(poster, POSTER_MAX_SIZE))]
for label, kind in CROP_LABELS:
box = regions.regions.get(kind)
crop = crop_region(poster, box) if box else None
if crop is None:
continue
images.append((f"{label} (여기 적힌 글자를 한 자씩 읽어라):",
to_data_uri(crop, (CROP_LONG_EDGE, CROP_LONG_EDGE))))
return images
def build_prompt(regions: Regions) -> str:
"""좌표만 넘긴다 — 앞 단계가 읽은 text는 뺀다."""
slim = {
"title_style": regions.title_style,
"regions": {kind: {"x0": box.x0, "x1": box.x1, "y0": box.y0, "y1": box.y1}
for kind, box in regions.regions.items()},
}
return "영역 분석 JSON:\n" + json.dumps(slim, ensure_ascii=False)
async def generate_narration(poster: Path | Image.Image, regions: Regions) -> NarrationAnswer:
"""검증 실패 시 사유를 피드백으로 넣어 1회만 재생성하고, 2회째 실패는 그대로 올린다."""
source = (Image.open(poster) if isinstance(poster, Path) else poster).convert("RGB")
images = build_images(source, regions)
prompt = build_prompt(regions)
try:
return await narration_llm.ask_with_images(
NarrationAnswer, prompt, images,
system=NARRATION_SYSTEM_PROMPT, temperature=NARRATION_TEMPERATURE)
except ValidationError as first_error:
return await narration_llm.ask_with_images(
NarrationAnswer, prompt + NARRATION_RETRY_PROMPT.format(error=first_error), images,
system=NARRATION_SYSTEM_PROMPT, temperature=NARRATION_TEMPERATURE)
+276
View File
@@ -0,0 +1,276 @@
"""⑦ render — i2v 클립을 1080x1920 배포본으로 합성한다.
QR은 프롬프트로 못 살린다. 원본 3071px → 출력 1248px 축소만으로도 데이터 모듈이 뭉개져
스캔이 안 되므로, 원본에서 오려 다시 얹는다. 기관 로고바도 같은 이유·같은 방법이고,
포스터 영역 안쪽에 뭉갠 채 남은 것들도 제자리에 덮는다.
루프는 핑퐁이 아니라 크로스페이드다. 생성형 불꽃은 터짐→소멸이라는 방향이 있는 사건이라
역재생이 눈에 보인다.
"""
import io
from collections import deque
from collections.abc import Iterator
from dataclasses import dataclass
from itertools import chain
from pathlib import Path
import numpy as np
from PIL import Image
from models.render import RenderResult
from models.tts import NarrationTimeline
from utils.audio import SAMPLE_RATE, apply_limiter, decode_audio, decode_mp3
from utils.image import bar_box, content_box, logo_bar, round_mask
from utils.qr import qr_box, qr_card
from utils.video import decode_frames, encode_mp4
OUT_W, OUT_H = 1080, 1920
FPS = 24
POSTER_W = 1000 # 9:16 안에서 포스터가 차지할 폭 (좌우 40px 여백)
TOP_PAD = 86
LOOP_OVERLAP = 16 # 겹침 프레임. 소재가 잔잔할수록 키워야 이음매가 죽는다
MIN_LOOP_SECONDS = 3
NARRATION_VOL, SFX_VOL, BGM_VOL = 1.45, 0.35, 0.20
BGM_FADE_IN = 1.0
BGM_FADE_OUT = 1.5
TAIL_FADE = 0.125
QR_DRIFT_RATIO = 0.04 # plate에서 찾은 QR이 이보다 어긋나면 패치를 포기한다
QR_SEARCH_PAD = 0.06
BAND_QR_MAX_H = 190
BAND_SIDE_PAD = 74
BAND_GAP = 60
@dataclass
class Layout:
"""0번 프레임에서 한 번 구해두고 모든 프레임에 그대로 적용한다."""
plate: tuple[int, int, int, int]
poster_size: tuple[int, int]
poster_top: int
background: tuple[int, ...]
band_y: int
band_h: int
bar_patch: tuple[Image.Image, tuple[int, int]] | None = None
qr_patch: tuple[Image.Image, tuple[int, int], Image.Image] | None = None
band_qr: tuple[Image.Image, tuple[int, int]] | None = None
band_bar: tuple[Image.Image, tuple[int, int]] | None = None
def norm_to_out(nx: float, ny: float, source: tuple[int, int], out_w: int) -> tuple[int, int]:
"""원본 정규좌표 → 출력 포스터 이미지 안의 픽셀 좌표."""
source_w, source_h = source
return round(nx * out_w), round(ny * out_w * source_h / source_w)
def band_colour(frame: Image.Image, plate: tuple[int, int, int, int]) -> tuple[int, ...]:
"""포스터 상단에서 뽑은 색은 채도가 높아 포스터와 경쟁하므로 밝기만 죽인다."""
left, top, right, bottom = plate
pixels = np.asarray(frame.convert("RGB")).astype(np.float32)
median = np.median(pixels[top:top + (bottom - top) // 5, left:right].reshape(-1, 3), axis=0)
return tuple(int(value * 0.34) for value in median)
def build_layout(frame: Image.Image, poster: Image.Image) -> Layout:
left, top, right, bottom = content_box(frame)
plate_w = right - left
source_w, source_h = poster.size
full_h = plate_w * source_h / source_w
source_bar = bar_box(poster)
source_qr = qr_box(poster)
has_band = bool(source_qr or source_bar)
if has_band:
poster_w = POSTER_W
poster_h = round(poster_w * (bottom - top) / plate_w)
poster_top = TOP_PAD
if TOP_PAD + poster_h >= OUT_H - 80:
raise RuntimeError(f"포스터가 너무 길다(밴드 {OUT_H - TOP_PAD - poster_h}px)")
else:
# 얹을 게 없으면 밴드는 존재 이유가 없다 — 포스터를 폭까지 키우고 상하 균등 여백
poster_w = OUT_W
poster_h = round(poster_w * (bottom - top) / plate_w)
if poster_h > OUT_H - 2 * TOP_PAD:
poster_h = OUT_H - 2 * TOP_PAD
poster_w = round(poster_h * plate_w / (bottom - top))
poster_top = (OUT_H - poster_h) // 2
layout = Layout(plate=(left, top, right, bottom), poster_size=(poster_w, poster_h),
poster_top=poster_top, background=band_colour(frame, (left, top, right, bottom)),
band_y=poster_top + poster_h, band_h=OUT_H - poster_top - poster_h)
if source_bar:
_, bar_y0 = norm_to_out(0.0, source_bar[1] / source_h, poster.size, poster_w)
_, bar_y1 = norm_to_out(0.0, source_bar[3] / source_h, poster.size, poster_w)
if 0 < bar_y0 < poster_h:
layout.bar_patch = (poster.crop(source_bar).resize((poster_w, bar_y1 - bar_y0),
Image.LANCZOS), (0, bar_y0))
if source_qr:
layout.qr_patch = inner_qr_patch(frame, poster, source_qr, layout, full_h)
if has_band:
layout.band_qr, layout.band_bar = band_assets(poster, layout)
return layout
def inner_qr_patch(frame: Image.Image, poster: Image.Image, source_qr: tuple[int, int, int, int],
layout: Layout, full_h: float):
"""포스터 안쪽 QR은 잘라낼 수 없으므로(그림 위에 얹혀 있다) 원본에서 오려 제자리에 덮는다."""
left, top, right, _ = layout.plate
plate_w = right - left
source_w, source_h = poster.size
poster_w, poster_h = layout.poster_size
x0, y0 = norm_to_out(source_qr[0] / source_w, source_qr[1] / source_h, poster.size, poster_w)
x1, y1 = norm_to_out(source_qr[2] / source_w, source_qr[3] / source_h, poster.size, poster_w)
# 네 귀퉁이를 다 뒤지면 엉뚱한 흰 덩어리를 찾았다고 오인해 drift 검사가 무의미해진다
window = (max(0.0, source_qr[0] / source_w - QR_SEARCH_PAD),
max(0.0, source_qr[1] / source_h - QR_SEARCH_PAD),
min(1.0, source_qr[2] / source_w + QR_SEARCH_PAD),
min(1.0, source_qr[3] / source_h + QR_SEARCH_PAD))
seen = qr_box(frame.crop((left, top, right, top + round(full_h))), strict=False, window=window)
if seen is None:
return None
drift = float(np.hypot(
(seen[0] + seen[2]) / 2 - (source_qr[0] + source_qr[2]) / 2 / source_w * plate_w,
(seen[1] + seen[3]) / 2 - (source_qr[1] + source_qr[3]) / 2 / source_h * full_h))
if drift > QR_DRIFT_RATIO * plate_w or y1 >= poster_h:
# 엉뚱한 자리에 QR을 찍는 것보다 안 찍는 게 낫다
return None
card = qr_card(poster, pad=0)
if card is None:
return None
patch = card.resize((x1 - x0, y1 - y0), Image.LANCZOS)
return patch, (x0, y0), round_mask(patch.size)
def band_assets(poster: Image.Image, layout: Layout):
"""밴드에 키워서 얹을 QR과 로고바. 밴드의 큰 QR이 스캔용이다."""
card = qr_card(poster)
band_qr = None
next_x = BAND_SIDE_PAD
if card:
height = min(BAND_QR_MAX_H, layout.band_h - 40)
resized = card.resize((round(card.width * height / card.height), height), Image.LANCZOS)
band_qr = (resized, (BAND_SIDE_PAD,
layout.band_y + (layout.band_h - resized.height) // 2))
next_x += resized.width + BAND_GAP
band_bar = None
bar = logo_bar(poster)
if bar:
width = OUT_W - next_x - BAND_SIDE_PAD
resized = bar.resize((width, round(bar.height * width / bar.width)), Image.LANCZOS)
band_bar = (resized, (next_x, layout.band_y + (layout.band_h - resized.height) // 2))
return band_qr, band_bar
def composite(frame: Image.Image, layout: Layout) -> Image.Image:
poster_area = frame.convert("RGB").crop(layout.plate).resize(layout.poster_size, Image.LANCZOS)
if layout.bar_patch:
poster_area.paste(*layout.bar_patch)
if layout.qr_patch:
patch, position, mask = layout.qr_patch
poster_area.paste(patch, position, mask)
canvas = Image.new("RGB", (OUT_W, OUT_H), layout.background)
canvas.paste(poster_area, ((OUT_W - layout.poster_size[0]) // 2, layout.poster_top))
if layout.band_qr:
canvas.paste(*layout.band_qr)
if layout.band_bar:
canvas.paste(*layout.band_bar)
return canvas
def loop_frames(clip: bytes, layout: Layout, tail: list[Image.Image],
loop_length: int, overlap: int) -> Iterator[Image.Image]:
"""머리에 꼬리를 녹여 마지막 프레임이 첫 프레임으로 자연스럽게 이어지게 한다."""
for index, frame in enumerate(decode_frames(clip)):
if index >= loop_length:
return
composited = composite(frame, layout)
if index < overlap:
weight = (index + 1) / (overlap + 1)
blended = (np.asarray(composited).astype(np.float32) * weight
+ np.asarray(tail[index]).astype(np.float32) * (1 - weight))
composited = Image.fromarray(np.clip(blended, 0, 255).astype(np.uint8))
yield composited
def fade(pcm: np.ndarray, seconds: float, out: bool) -> np.ndarray:
length = min(len(pcm), round(seconds * SAMPLE_RATE))
if length <= 0:
return pcm
ramp = np.linspace(0.0, 1.0, length, dtype=np.float32)
faded = pcm.astype(np.float32)
if out:
faded[len(pcm) - length:] *= ramp[::-1]
else:
faded[:length] *= ramp
return faded
def mix_audio(clip: bytes, narration: bytes | None, bgm: bytes | None,
duration: float) -> np.ndarray:
"""나레이션 1.45 / SFX 0.35 / BGM 0.20. 리미터가 컴프레서처럼 작동해 목소리가 또렷해진다."""
total = round(duration * SAMPLE_RATE)
track = np.zeros(total, dtype=np.float32)
sfx = decode_audio(clip)
if sfx is not None:
sfx = sfx[:total]
track[:len(sfx)] += sfx.astype(np.float32) * SFX_VOL
if narration:
voice = decode_mp3(narration)[:total]
track[:len(voice)] += voice.astype(np.float32) * NARRATION_VOL
if bgm:
music = decode_mp3(bgm)
if len(music) < total:
music = np.tile(music, total // len(music) + 1)
music = fade(fade(music[:total].astype(np.float32) * BGM_VOL, BGM_FADE_IN, out=False),
BGM_FADE_OUT, out=True)
track += music
track = fade(track, TAIL_FADE, out=True)
return apply_limiter(np.clip(track, -32768, 32767).astype(np.int16))
def render(clip: bytes, poster: Path | Image.Image, *,
narration: bytes | None = None, bgm: bytes | None = None,
timeline: NarrationTimeline | None = None,
overlap: int = LOOP_OVERLAP) -> RenderResult:
source = (Image.open(poster) if isinstance(poster, Path) else poster).convert("RGB")
# 1회차 — 레이아웃을 잡고 꼬리 프레임만 남긴다. 전부 들고 있으면 1GB를 넘는다.
layout, tail_frames, frame_count = None, deque(maxlen=overlap), 0
for frame in decode_frames(clip):
if layout is None:
layout = build_layout(frame, source)
tail_frames.append(frame)
frame_count += 1
if layout is None:
raise RuntimeError("클립에서 프레임을 못 뽑았다")
tail = [composite(frame, layout) for frame in tail_frames]
loop_length = frame_count - overlap
if loop_length < FPS * MIN_LOOP_SECONDS:
raise RuntimeError(f"루프 길이가 너무 짧다 ({loop_length}프레임) — overlap을 줄일 것")
duration = loop_length / FPS
if timeline and timeline.cues[-1].end > duration:
raise RuntimeError(f"나레이션이 {timeline.cues[-1].end:.2f}초로 영상 {duration:.2f}초를 "
"넘는다 — overlap을 줄이거나 나레이션을 짧게")
# 2회차 — 순서대로 합성해 인코더에 바로 밀어넣는다
frames = loop_frames(clip, layout, tail, loop_length, overlap)
first = next(frames)
thumbnail = io.BytesIO()
first.save(thumbnail, "JPEG", quality=92)
video = encode_mp4(chain([first], frames), (OUT_W, OUT_H),
mix_audio(clip, narration, bgm, duration), fps=FPS)
return RenderResult(video=video, thumbnail=thumbnail.getvalue(), duration=duration,
frames=loop_length, width=OUT_W, height=OUT_H)
+126
View File
@@ -0,0 +1,126 @@
"""⑥ 제목 훼손 게이트 — 픽셀 하드컷 + VLM 가독성 2단.
"파일이 존재하는가"만 보던 검증 탓에 구름이 제목을 덮은 클립이 검수대까지 간 적이 있다.
픽셀 지표 하나로는 갈리지 않아서 — 영역 평균차는 제목 뒤 불꽃과 제목 위 구름을 구분 못 하고
글리프 휘도차는 흰 구름이 흰 글자를 덮으면 0에 수렴한다 — 2단을 VLM 가독성 판정으로 둔다.
"""
import numpy as np
from PIL import Image
from answers.title_gate_answer import TitleGateAnswer
from models.detect import Regions
from models.i2v import FrameVerdict, TitleGateVerdict
from settings import settings
from utils.common_llm import StructuredLLM
from utils.image import content_box, to_data_uri
from utils.prompt import load_prompt
from utils.qr import otsu_threshold
from utils.video import duration, frames_at
PIXEL_HARD_FAIL = 40.0 # 정상 최대 17.02, 재작화 81.28 (실측)
SAMPLE_FRACTIONS = (0.0, 0.25, 0.45, 0.70, 0.93)
MIN_TITLE_BOX_PX = 24
MIN_GLYPH_PIXELS = 300
ALIGN_RADIUS_PX = 14
CROP_MAX_SIZE = (640, 640)
TITLE_GATE_PROMPT = load_prompt("title_gate")
title_gate_llm = StructuredLLM("gpt-4o", settings.chatgpt_api_key)
def title_box_in_plate(frame: Image.Image, regions: Regions) -> tuple[int, int, int, int] | None:
"""원본 정규좌표 → 클립 프레임 안의 제목 상자.
content_box가 완전히 희거나 검은 행만 걷어내는 탓에 plate 높이가 원본 비율과 어긋나므로,
믿을 수 있는 가로를 기준으로 잡고 세로 배율은 원본 종횡비에서 유도한다.
"""
box = regions.regions.get("title")
if box is None:
return None
left, top, right, bottom = content_box(frame)
plate_width = right - left
source_width, source_height = regions.poster_size
full_height = plate_width * source_height / source_width
title = (left + round(box.x0 * plate_width),
top + round(box.y0 * full_height),
left + round(box.x1 * plate_width),
min(bottom, top + round(box.y1 * full_height)))
if title[2] - title[0] < MIN_TITLE_BOX_PX or title[3] - title[1] < MIN_TITLE_BOX_PX:
return None
return title
def align(gray: np.ndarray, reference: np.ndarray, mask: np.ndarray) -> np.ndarray:
"""생성 클립은 프레임 전체가 2~3% 드리프트해서 정렬 없이 재면 글자가 멀쩡해도
컷오프를 넘으므로(실측 41.9 → 정렬 후 24.9), ±14px 평행이동을 그리드로 찾아 되돌린다."""
best_score, best_dx, best_dy = None, 0, 0
for dy in range(-ALIGN_RADIUS_PX, ALIGN_RADIUS_PX + 1, 2):
for dx in range(-ALIGN_RADIUS_PX, ALIGN_RADIUS_PX + 1, 2):
shifted = np.roll(np.roll(gray, dy, axis=0), dx, axis=1)
score = float(np.abs(shifted[mask] - reference[mask]).mean())
if best_score is None or score < best_score:
best_score, best_dx, best_dy = score, dx, dy
return np.roll(np.roll(gray, best_dy, axis=0), best_dx, axis=1)
def pixel_score(crops: list[Image.Image]) -> float | None:
"""글리프 휘도차 A. 같은 색 가림은 못 잡아서 재작화·소거 하드컷에만 쓴다."""
reference = np.asarray(crops[0].convert("L"), dtype=np.float32)
dark = reference < otsu_threshold(reference)
mask = dark if dark.mean() <= 0.5 else ~dark
if mask.sum() < MIN_GLYPH_PIXELS:
return None
return max(float(np.abs(align(np.asarray(crop.convert("L"), dtype=np.float32),
reference, mask)[mask] - reference[mask]).mean())
for crop in crops[1:])
async def ask_legibility(crops: list[Image.Image], times: list[float],
title: str) -> TitleGateAnswer:
images = [(f"[{index}] t={at}s:", to_data_uri(crop, CROP_MAX_SIZE))
for index, (crop, at) in enumerate(zip(crops, times, strict=True))]
return await title_gate_llm.ask_with_images(
TitleGateAnswer,
f"기대 제목: {title!r}\n시점 {len(crops)}장. 각 이미지를 순서대로 판정하라.",
images, system=TITLE_GATE_PROMPT)
async def check_title(clip: bytes, regions: Regions) -> TitleGateVerdict:
"""판단 근거가 없으면(제목 상자·텍스트 없음) 통과시키고 사유를 남긴다."""
clip_seconds = duration(clip)
times = [round(max(0.0, min(clip_seconds - 0.05, fraction * clip_seconds)), 2)
for fraction in SAMPLE_FRACTIONS]
frames = frames_at(clip, times)
box = title_box_in_plate(frames[0], regions)
if box is None:
return TitleGateVerdict(passed=True, skip="title 상자가 없거나 너무 작음")
crops = [frame.crop(box) for frame in frames]
score = pixel_score(crops)
title = (regions.regions["title"].text or "").strip()
verdict = TitleGateVerdict(passed=True, samples=times,
pixel_score=round(score, 2) if score is not None else None)
if score is not None and score > PIXEL_HARD_FAIL:
# 정렬 후에도 넘는 값은 대개 배경 통과라 즉시 실패시키지 않고 VLM으로 넘긴다
verdict.pixel_hard = True
if not title:
verdict.passed = False
verdict.reason = f"획변화 {score:.1f} > {PIXEL_HARD_FAIL}, title.text 없어 VLM 판정 불가"
return verdict
if not title:
verdict.skip = "title.text 없음 — VLM 가독성 판정 불가"
return verdict
answer = await ask_legibility(crops, times, title)
verdict.frames = [FrameVerdict(index=frame.index, time=times[frame.index],
legible=frame.legible, broken=frame.broken)
for frame in answer.frames if frame.index < len(times)]
broken = [frame for frame in verdict.frames if not frame.legible]
if broken:
verdict.passed = False
verdict.reason = "제목 가독 훼손: " + "; ".join(
f"t={frame.time}s {frame.broken}" for frame in broken)
return verdict
+109
View File
@@ -0,0 +1,109 @@
"""④ tts — 나레이션 음성 + 실측 타임라인.
영상 비트를 먼저 못 박고 음성을 우겨넣으면 말이 잘리거나 비므로, 문장별 실측 길이를
먼저 재고 그 큐에 씬·카메라를 맞춘다. 트림·합성·인코딩까지 전부 메모리에서 처리한다.
"""
import asyncio
import httpx
import numpy as np
from openai import AsyncOpenAI
from models.tts import NarrationAudio, NarrationCue, NarrationTimeline, TypecastVoice
from settings import settings
from utils.audio import SAMPLE_RATE, decode_mp3, encode_mp3, trim_silence
from utils.prompt import load_prompt
TYPECAST_API = "https://api.typecast.ai/v1/text-to-speech"
OPENAI_TTS_MODEL = "gpt-4o-mini-tts"
TYPECAST_MODEL = "ssfm-v30"
# "천천히"라고 지시하면 TTS가 과하게 늘어진다. 톤은 지시문으로, 속도는 파라미터로 통제한다.
TTS_INSTRUCTIONS = load_prompt("tts_instructions")
DEFAULT_SPEED = 1.28
DEFAULT_PAUSES = (0.35, 0.35, 0.30)
DEFAULT_LEAD_IN = 0.35
DEFAULT_TAIL = 1.7
async def speak_openai(text: str, voice: str, speed: float, instructions: str) -> bytes:
response = await AsyncOpenAI(api_key=settings.chatgpt_api_key).audio.speech.create(
model=OPENAI_TTS_MODEL,
voice=voice,
input=text,
instructions=instructions,
speed=speed,
response_format="mp3",
)
return await response.aread()
async def speak_typecast(text: str, typecast: TypecastVoice) -> bytes:
if not settings.typecast_api_key:
raise RuntimeError("TYPECAST_API_KEY 없음 — typecast 엔진을 쓰려면 필요하다")
async with httpx.AsyncClient(timeout=90) as client:
response = await client.post(
TYPECAST_API,
headers={"X-API-KEY": settings.typecast_api_key},
json={
"text": text,
"model": TYPECAST_MODEL,
"voice_id": typecast.voice_id,
"language": "kor",
"prompt": {"emotion_type": "preset",
"emotion_preset": typecast.emotion,
"emotion_intensity": typecast.emotion_intensity},
"output": {"audio_format": "mp3", "volume": 100,
"audio_tempo": typecast.tempo},
})
response.raise_for_status()
return response.content
def merge_clips(clips: list[np.ndarray], starts: list[float], total: float) -> np.ndarray:
"""큐가 겹치지 않으므로 시작 시각에 그대로 덮어써 한 트랙으로 만든다."""
track = np.zeros(round(total * SAMPLE_RATE), dtype=np.int16)
for clip, start in zip(clips, starts, strict=True):
offset = round(start * SAMPLE_RATE)
track[offset:offset + len(clip)] = clip[:max(0, len(track) - offset)]
return track
async def synthesize(sentences: list[str], voice: str = "nova", *,
speed: float = DEFAULT_SPEED,
instructions: str = TTS_INSTRUCTIONS,
typecast: TypecastVoice | None = None,
pauses: tuple[float, ...] = DEFAULT_PAUSES,
lead_in: float = DEFAULT_LEAD_IN,
tail: float = DEFAULT_TAIL) -> NarrationAudio:
"""typecast를 주면 그 엔진으로 가므로, voice_id 없이 typecast를 고를 수 없다."""
if not sentences:
raise ValueError("나레이션 문장이 없다")
if typecast:
spoken = await asyncio.gather(*(speak_typecast(text, typecast) for text in sentences))
else:
spoken = await asyncio.gather(
*(speak_openai(text, voice, speed, instructions) for text in sentences))
# TTS가 문장 끝에 붙이는 최대 1.2초 공백이 그대로 영상 길이가 되면 훅 직후에 침묵이 생긴다
clips = [trim_silence(decode_mp3(mp3)) for mp3 in spoken]
cues, starts = [], []
cursor = lead_in
for index, (text, clip) in enumerate(zip(sentences, clips, strict=True)):
duration = len(clip) / SAMPLE_RATE
pause = pauses[index] if index < len(pauses) else pauses[-1]
starts.append(cursor)
cues.append(NarrationCue(index=index, text=text, start=round(cursor, 3),
duration=round(duration, 3), end=round(cursor + duration, 3),
pause_after=pause))
cursor += duration + pause
total = round(cues[-1].end + tail, 2)
return NarrationAudio(
timeline=NarrationTimeline(
engine="typecast" if typecast else "openai",
voice=typecast.voice_id if typecast else voice,
lead_in=lead_in, tail=tail, total=total, cues=cues),
mp3=encode_mp3(merge_clips(clips, starts, total)),
)