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

+18
View File
@@ -0,0 +1,18 @@
# poster-alive
## Requirements
### Higgsfield CLI
⑥ i2v는 Higgsfield CLI를 서브프로세스로 부른다. 인증이 API 키가 아니라
`~/.config/higgsfield/credentials.json`의 CLI 토큰이라 머신마다 한 번씩 로그인해야 한다.
```bash
npm i -g @higgsfield/cli
higgsfield auth login
higgsfield workspace set <workspace-id>
```
로그인 후 `higgsfield account status --json`이 돌려주는 이메일을 `.env`의
`HIGGSFIELD_ACCOUNT`에 넣는다. 계정 가드가 이 값과 대조해, 다른 계정 토큰으로
남의 크레딧이 빠지는 것을 막는다.
+12
View File
@@ -0,0 +1,12 @@
"""⑥ 제목 훼손 게이트 2단(VLM 가독성) 응답 스키마."""
from pydantic import BaseModel
class FrameLegibility(BaseModel):
index: int
legible: bool
broken: str
class TitleGateAnswer(BaseModel):
frames: list[FrameLegibility]
+9
View File
@@ -0,0 +1,9 @@
from dataclasses import dataclass
@dataclass
class BgmAudio:
mp3: bytes
seconds: int # 요청한 목표 길이
duration: float # Suno가 돌려준 실제 길이
task_id: str
+28
View File
@@ -0,0 +1,28 @@
from dataclasses import dataclass
from pydantic import BaseModel
class FrameVerdict(BaseModel):
index: int
time: float
legible: bool
broken: str
class TitleGateVerdict(BaseModel):
passed: bool
reason: str = ""
skip: str = "" # 판단 근거가 없어 통과시킨 사유
pixel_score: float | None = None # 글리프 휘도차 A
pixel_hard: bool = False # 하드컷 초과 — VLM 2단으로 넘어감
samples: list[float] = []
frames: list[FrameVerdict] = []
@dataclass
class I2vResult:
clip: bytes
credits: float # generate create 응답에 크레딧이 없어 cost 조회값을 쓴다
model: str
title_gate: TitleGateVerdict
+11
View File
@@ -0,0 +1,11 @@
from dataclasses import dataclass
@dataclass
class RenderResult:
video: bytes
thumbnail: bytes # 첫 프레임. 정지 광고판 컷이 곧 썸네일이다
duration: float
frames: int
width: int
height: int
+1 -1
View File
@@ -21,7 +21,7 @@ class NarrationCue(BaseModel):
class NarrationTimeline(BaseModel):
"""씬·카메라 비트가 이 큐에 맞춰진다. 오디오가 타이밍을 결정한다."""
"""씬·카메라 비트를 여기 큐에 맞춘다."""
engine: str
voice: str
lead_in: float
+9
View File
@@ -0,0 +1,9 @@
포스터 영상의 서로 다른 시점에서 잘라낸 '제목 영역' 이미지들이다.
질문은 하나다: **각 시점에서 제목 글자가 온전히 읽히는가.**
판정 기준:
- 글자 자체가 온전하면 legible=true. 배경이 변한 것(불꽃·구름·빛이 글자 **뒤로** 지나감)은
훼손이 아니다.
- 글자가 다른 그림에 **가려짐**, 획이 지워짐·뭉개짐, 다른 글자로 변형, 재작화됐으면 legible=false.
- 기대 제목의 일부 글자만 훼손돼도 false다. broken에 어떤 글자가 어떻게 됐는지 짧게 쓴다.
- index는 이미지에 붙은 번호 그대로 쓴다. 훼손이 없으면 broken은 빈 문자열.
+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)
File renamed without changes.
+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)
@@ -1,8 +1,7 @@
"""③ motion — 포스터에서 움직일 요소를 골라 i2v 프롬프트를 만든다.
모션 어휘를 고정 카탈로그로 나열했더니 모델이 포스터에 없는 관람차를 그려 넣었다.
생성 모델에게 조건문은 주문서로 읽힌다. 그래서 역할을 나눈다 —
**무엇이 있는가**는 VLM이 그림을 보고 답하고, **어떻게 움직이는가**는 검증된 문구가 정한다.
모션 어휘를 카탈로그로 나열하면 모델이 포스터에 없는 관람차까지 그려 넣으므로,
무엇이 있는지만 VLM에게 묻고 어떻게 움직이는지는 검증된 문구로 고정한다.
"""
from pathlib import Path
from typing import get_args
@@ -65,7 +64,7 @@ def build_prompt(elements: list[MotionElement], has_qr: bool, extra: str = "") -
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종."""
"""force_motions를 주면 VLM을 건너뛰고 그 목록으로 만든다(검수 게이트 수동 지정, 빈 리스트면 0종)."""
source = (Image.open(poster) if isinstance(poster, Path) else poster).convert("RGB")
if force_motions is None:
@@ -1,7 +1,7 @@
"""② narration_text — 나레이션 3문장 + voice + BGM 스타일 + 메타태그.
앞 단계가 읽은 글자는 넘기지 않는다. 좌표만 넘기고 글자는 확대 크롭에서 직접 읽게 한다.
상류 모델의 오독을 프롬프트에 넣으면 하류가 이미지를 다시 안 보고 그대로 베낀다.
상류 오독을 프롬프트에 넣으면 하류가 이미지를 다시 보지 않고 베껴 쓰므로,
앞 단계가 읽은 글자 대신 좌표만 넘기고 글자는 확대 크롭에서 직접 읽게 한다.
"""
import json
from pathlib import Path
@@ -33,7 +33,7 @@ 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)
@@ -71,7 +71,7 @@ def build_prompt(regions: Regions) -> str:
async def generate_narration(poster: Path | Image.Image, regions: Regions) -> NarrationAnswer:
"""검증 실패 시 사유를 피드백으로 넣어 1회만 재생성한다. 2회째 실패는 그대로 올린다."""
"""검증 실패 시 사유를 피드백으로 넣어 1회만 재생성하고, 2회째 실패는 그대로 올린다."""
source = (Image.open(poster) if isinstance(poster, Path) else poster).convert("RGB")
images = build_images(source, regions)
prompt = build_prompt(regions)
+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
+4 -6
View File
@@ -1,9 +1,7 @@
"""④ tts — 나레이션 음성 + 실측 타임라인.
**오디오가 타이밍을 결정한다.** 영상 비트를 먼저 못 박고 음성을 우겨넣으면 말이 잘리거나 빈다.
문장별로 만들어 실제 길이를 재고, 그 큐에 씬·카메라를 맞춘다. 순서를 뒤집지 않는다.
파일도 서브프로세스도 없다. TTS 응답을 받아 메모리에서 트림·합성·인코딩한다.
영상 비트를 먼저 못 박고 음성을 우겨넣으면 말이 잘리거나 비므로, 문장별 실측 길이를
먼저 재고 그 큐에 씬·카메라를 맞춘다. 트림·합성·인코딩까지 전부 메모리에서 처리한다.
"""
import asyncio
@@ -63,7 +61,7 @@ async def speak_typecast(text: str, typecast: TypecastVoice) -> bytes:
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)
@@ -78,7 +76,7 @@ async def synthesize(sentences: list[str], voice: str = "nova", *,
pauses: tuple[float, ...] = DEFAULT_PAUSES,
lead_in: float = DEFAULT_LEAD_IN,
tail: float = DEFAULT_TAIL) -> NarrationAudio:
"""typecast를 주면 그 엔진으로 간다 — voice_id 없이 typecast를 고를 수 없다."""
"""typecast를 주면 그 엔진으로 가므로, voice_id 없이 typecast를 고를 수 없다."""
if not sentences:
raise ValueError("나레이션 문장이 없다")
+3
View File
@@ -6,6 +6,9 @@ class Settings(BaseSettings):
chatgpt_api_key: str
typecast_api_key: str = "" # typecast 엔진을 쓸 때만 필요
suno_api_key: str = ""
suno_callback_url: str = "" # Suno가 요구하는 값. 결과는 폴링으로 받는다
higgsfield_account: str = "" # CLI 토큰이 이 계정 것인지 확인만 한다
settings = Settings()
+58
View File
@@ -0,0 +1,58 @@
"""bgm 수동 확인용. **Suno는 실제 과금이 나간다.**
사용: uv run python test_bgm.py <포스터경로>
test_result/<이름>.narration.txt(bgm_style)와 <이름>.tts.txt(total)를 재사용한다.
없으면 앞 단계부터 돌린다. 결과는 <이름>.bgm.mp3 와 <이름>.bgm.txt.
"""
import asyncio
import json
import sys
from pathlib import Path
from models.tts import NarrationTimeline
from services.bgm import generate_bgm
from services.tts import synthesize
from test_tts import load_narration
TEST_RESULT_DIR = Path(__file__).parent / "test_result"
async def load_timeline(sentences: list[str], voice: str, timeline_path: Path
) -> NarrationTimeline:
if timeline_path.exists():
return NarrationTimeline.model_validate_json(timeline_path.read_text(encoding="utf-8"))
audio = await synthesize(sentences, voice)
timeline_path.write_text(audio.timeline.model_dump_json(indent=2), encoding="utf-8")
return audio.timeline
async def main() -> None:
poster_path = Path(sys.argv[1])
TEST_RESULT_DIR.mkdir(exist_ok=True)
output_base = TEST_RESULT_DIR / poster_path.stem
answer = await load_narration(poster_path, output_base)
timeline = await load_timeline(answer.narration, answer.voice,
output_base.with_suffix(".tts.txt"))
print(f"나레이션 {timeline.total}s → BGM 요청")
print(f" style : {answer.bgm_style.style}")
print(f" prompt: {answer.bgm_style.prompt}")
print("Suno 생성 시작 — 최대 5분 폴링, 과금됩니다.")
audio = await generate_bgm(answer.bgm_style, timeline.total, title=poster_path.stem)
mp3_path = output_base.with_suffix(".bgm.mp3")
meta_path = output_base.with_suffix(".bgm.txt")
mp3_path.write_bytes(audio.mp3)
meta_path.write_text(json.dumps(
{"task_id": audio.task_id, "seconds": audio.seconds, "duration": audio.duration,
"style": answer.bgm_style.style, "prompt": answer.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())
+1 -1
View File
@@ -7,7 +7,7 @@ import asyncio
import sys
from pathlib import Path
from detect import detect
from services.detect import detect
TEST_RESULT_DIR = Path(__file__).parent / "test_result"
+54
View File
@@ -0,0 +1,54 @@
"""i2v 수동 확인용.
사용: uv run python test_i2v.py <포스터경로>
test_result/<이름>.i2v.txt(프롬프트)와 <이름>.detect.txt(영역)를 쓴다.
결과는 <이름>.clip.mp4 와 <이름>.title_gate.txt.
"""
import asyncio
import sys
from pathlib import Path
from models.detect import Regions
from services.i2v import DEFAULT_MODEL, animate, cli_args
from utils.higgsfield import run_cli
TEST_RESULT_DIR = Path(__file__).parent / "test_result"
async def main() -> None:
poster_path = Path(sys.argv[1])
output_base = TEST_RESULT_DIR / poster_path.stem
prompt_path = output_base.with_suffix(".i2v.txt")
detect_path = output_base.with_suffix(".detect.txt")
for required in (prompt_path, detect_path):
if not required.exists():
raise SystemExit(f"{required} 없음 — 앞 단계를 먼저 돌릴 것")
prompt = prompt_path.read_text(encoding="utf-8").strip()
regions = Regions.model_validate_json(detect_path.read_text(encoding="utf-8"))
raw = await run_cli("generate", "cost", DEFAULT_MODEL,
*cli_args(prompt, poster_path, DEFAULT_MODEL), "--json", timeout=300)
print(f"=== generate cost 원본 출력 ({len(raw)}자) ===\n{raw}\n=== 끝 ===\n")
result = await animate(prompt, poster_path, regions)
clip_path = output_base.with_suffix(".clip.mp4")
verdict_path = output_base.with_suffix(".title_gate.txt")
clip_path.write_bytes(result.clip)
verdict_path.write_text(result.title_gate.model_dump_json(indent=2), encoding="utf-8")
verdict = result.title_gate
print(f"{result.model} · {result.credits} 크레딧 · {len(result.clip) / 1e6:.1f}MB")
print(f"제목 게이트 {'통과' if verdict.passed else '실패'} 픽셀 A={verdict.pixel_score}"
f"{' (하드컷 초과)' if verdict.pixel_hard else ''}")
if verdict.skip:
print(f" 판정 생략: {verdict.skip}")
for frame in verdict.frames:
print(f" {'✓' if frame.legible else '✗'} t={frame.time}s {frame.broken}")
print(f"\n{clip_path}\n{verdict_path}")
if __name__ == "__main__":
asyncio.run(main())
+1 -1
View File
@@ -8,7 +8,7 @@ import asyncio
import sys
from pathlib import Path
from motion import plan_motion
from services.motion import plan_motion
TEST_RESULT_DIR = Path(__file__).parent / "test_result"
+2 -2
View File
@@ -8,9 +8,9 @@ import asyncio
import sys
from pathlib import Path
from detect import detect
from models.detect import Regions
from narration import generate_narration
from services.detect import detect
from services.narration import generate_narration
TEST_RESULT_DIR = Path(__file__).parent / "test_result"
+50
View File
@@ -0,0 +1,50 @@
"""render 수동 확인용.
사용: uv run python test_render.py <포스터경로> [클립경로]
클립을 생략하면 test_result/<이름>.clip.mp4 를 쓴다.
나레이션(.tts.mp3)·타임라인(.tts.txt)·BGM(.bgm.mp3)은 있으면 얹고 없으면 건너뛴다.
결과는 <이름>.final.mp4 와 <이름>.thumb.jpg.
"""
import sys
from pathlib import Path
from models.tts import NarrationTimeline
from services.render import render
TEST_RESULT_DIR = Path(__file__).parent / "test_result"
def read_if_exists(path: Path) -> bytes | None:
return path.read_bytes() if path.exists() else None
def main() -> None:
poster_path = Path(sys.argv[1])
output_base = TEST_RESULT_DIR / poster_path.stem
clip_path = Path(sys.argv[2]) if len(sys.argv) > 2 else output_base.with_suffix(".clip.mp4")
if not clip_path.exists():
raise SystemExit(f"클립 없음: {clip_path}")
timeline_path = output_base.with_suffix(".tts.txt")
timeline = (NarrationTimeline.model_validate_json(timeline_path.read_text(encoding="utf-8"))
if timeline_path.exists() else None)
narration = read_if_exists(output_base.with_suffix(".tts.mp3"))
bgm = read_if_exists(output_base.with_suffix(".bgm.mp3"))
print(f"클립 {clip_path.name} / 나레이션 {'있음' if narration else '없음'}"
f" / BGM {'있음' if bgm else '없음'}")
result = render(clip_path.read_bytes(), poster_path,
narration=narration, bgm=bgm, timeline=timeline)
video_path = output_base.with_suffix(".final.mp4")
thumb_path = output_base.with_suffix(".thumb.jpg")
video_path.write_bytes(result.video)
thumb_path.write_bytes(result.thumbnail)
print(f"{result.width}x{result.height} · {result.frames}프레임 · {result.duration:.2f}초 "
f"· {len(result.video) / 1e6:.1f}MB")
print(f"\n{video_path}\n{thumb_path}")
if __name__ == "__main__":
main()
+2 -2
View File
@@ -9,9 +9,9 @@ import sys
from pathlib import Path
from answers.narration_answer import NarrationAnswer
from narration import generate_narration
from services.narration import generate_narration
from services.tts import synthesize
from test_narration import load_regions
from tts import synthesize
TEST_RESULT_DIR = Path(__file__).parent / "test_result"
+51 -1
View File
@@ -1,5 +1,6 @@
"""메모리 위에서만 도는 오디오 처리. 파일도 서브프로세스도 없다."""
"""파일도 서브프로세스도 없이 메모리에서 처리하는 오디오 유틸."""
import io
from fractions import Fraction
import av
import numpy as np
@@ -40,6 +41,55 @@ def encode_mp3(pcm: np.ndarray, sample_rate: int = SAMPLE_RATE) -> bytes:
return buffer.getvalue()
def decode_audio(media: bytes, sample_rate: int = SAMPLE_RATE) -> np.ndarray | None:
"""비디오·오디오 컨테이너에서 오디오 트랙을 꺼낸다. 트랙이 없으면 None."""
container = av.open(io.BytesIO(media))
try:
if not container.streams.audio:
return None
resampler = av.audio.resampler.AudioResampler(
format="s16", layout="mono", rate=sample_rate)
chunks = []
for frame in container.decode(audio=0):
for resampled in resampler.resample(frame):
chunks.append(resampled.to_ndarray().reshape(-1))
for resampled in resampler.resample(None):
chunks.append(resampled.to_ndarray().reshape(-1))
finally:
container.close()
return np.concatenate(chunks) if chunks else None
def apply_limiter(pcm: np.ndarray, sample_rate: int = SAMPLE_RATE,
limit: float = 0.94, attack: int = 5, release: int = 60) -> np.ndarray:
"""ffmpeg alimiter를 그대로 태운다. 리미터가 컴프레서처럼 작동해 목소리가 또렷해진다."""
graph = av.filter.Graph()
source = graph.add_abuffer(format="s16", layout="mono", sample_rate=sample_rate,
time_base=Fraction(1, sample_rate))
limiter = graph.add("alimiter", f"limit={limit}:attack={attack}:release={release}")
# alimiter는 부동소수로 처리하므로 싱크 앞에서 s16으로 되돌린다
to_s16 = graph.add("aformat", "sample_fmts=s16:channel_layouts=mono")
sink = graph.add("abuffersink")
source.link_to(limiter)
limiter.link_to(to_s16)
to_s16.link_to(sink)
graph.configure()
frame = av.AudioFrame.from_ndarray(pcm.reshape(1, -1), format="s16", layout="mono")
frame.rate = sample_rate
frame.time_base = Fraction(1, sample_rate)
graph.push(frame)
graph.push(None)
chunks = []
while True:
try:
chunks.append(sink.pull().to_ndarray().reshape(-1))
except (av.error.EOFError, av.error.BlockingIOError):
break
return np.concatenate(chunks).astype(np.int16) if chunks else pcm
def trim_silence(pcm: np.ndarray, threshold_db: float = -45,
keep_lead: float = 0.05, keep_trail: float = 0.12,
sample_rate: int = SAMPLE_RATE) -> np.ndarray:
+1 -1
View File
@@ -1,7 +1,7 @@
"""structured output 공용 래퍼.
OpenAI 호환 /chat/completions를 쓰는 프로바이더면 base_url만 바꿔 그대로 쓴다.
이미지는 이미 인코딩된 URL(data URI 또는 http)로 받는다 — 인코딩은 호출측 책임.
이미지 인코딩은 호출측 책임이라 여기서는 URL(data URI 또는 http)만 받는다.
"""
from collections.abc import Sequence
from typing import TypeVar
+72
View File
@@ -0,0 +1,72 @@
"""Higgsfield CLI 래퍼.
인증이 `~/.config/higgsfield/credentials.json`의 CLI 토큰이라 서브프로세스를 피할 수 없고,
머신마다 사람이 한 번 로그인해야 한다:
`npm i -g @higgsfield/cli` → `higgsfield auth login` → `higgsfield workspace set <id>`
"""
import asyncio
import json
import re
CLI = "higgsfield"
CLI_TIMEOUT = 2100
RESULT_URL_PATTERN = re.compile(r'"result_url"\s*:\s*"([^"]+)"')
CREDITS_PATTERN = re.compile(r'"credits(?:_exact)?"\s*:\s*([0-9.]+)')
PLAIN_CREDITS_PATTERN = re.compile(r"([0-9.]+)\s*credits")
async def run_cli(*args: str, timeout: int = CLI_TIMEOUT) -> str:
try:
process = await asyncio.create_subprocess_exec(
CLI, *args,
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
except FileNotFoundError:
raise RuntimeError(
"higgsfield CLI가 없다 — `npm i -g @higgsfield/cli` 후 `higgsfield auth login`")
try:
stdout, stderr = await asyncio.wait_for(process.communicate(), timeout)
except TimeoutError:
process.kill()
raise RuntimeError(f"higgsfield {args[0]} 타임아웃 {timeout}초")
if process.returncode != 0:
detail = (stderr or stdout).decode(errors="ignore")[-600:]
raise RuntimeError(f"higgsfield {args[0]} 실패:\n{detail}")
return stdout.decode(errors="ignore")
async def account_status() -> dict:
output = await run_cli("account", "status", "--json", timeout=60)
try:
return json.loads(output)
except json.JSONDecodeError:
raise RuntimeError(f"account status 응답을 파싱할 수 없다:\n{output[-400:]}")
async def assert_account(expected: str) -> dict:
"""다른 계정으로 로그인하면 토큰이 조용히 바뀌어 그 계정 크레딧이 빠지므로,
편당 22크레딧을 쓰기 직전에 로그인 계정을 확인하고 어긋나면 죽는다."""
status = await account_status()
email = (status.get("email") or "").strip().lower()
if email != expected.lower():
raise RuntimeError(
f"[가드] Higgsfield 계정 불일치 — 로그인: {email or '(없음)'} / 기대: {expected}\n"
f"크레딧이 다른 계정에서 빠진다. logout 후 {expected}로 다시 로그인할 것. "
f"의도한 전환이면 HIGGSFIELD_ACCOUNT={email} 로 명시할 것.")
return status
def parse_credits(output: str) -> float:
"""못 찾으면 죽는다. 0.0으로 때우면 CLI 출력 포맷이 바뀌어도 "0 크레딧 썼다"로 통과한다."""
match = CREDITS_PATTERN.search(output) or PLAIN_CREDITS_PATTERN.search(output)
if not match:
raise RuntimeError(f"CLI 출력에서 크레딧을 못 읽었다 — 포맷이 바뀌었는지 확인할 것:\n"
f"{output[-600:]}")
return float(match.group(1))
def parse_result_url(output: str) -> str:
match = RESULT_URL_PATTERN.search(output)
if not match:
raise RuntimeError(f"result_url 없음 — 생성 실패:\n{output[-1200:]}")
return match.group(1)
+41 -1
View File
@@ -1,10 +1,50 @@
import base64
import io
from PIL import Image
import numpy as np
from PIL import Image, ImageDraw
Image.MAX_IMAGE_PIXELS = None
LOGO_BAR_SEARCH_FROM = 0.88 # 하단 12%에서만 밝은 띠를 찾는다
LOGO_BAR_BRIGHTNESS = 200
LOGO_BAR_MIN_ROWS = 20
def content_box(frame: Image.Image) -> tuple[int, int, int, int]:
"""레터박스(검정·흰 여백)를 걷어낸 실제 포스터 영역."""
brightness = np.asarray(frame.convert("RGB")).astype(np.float32).mean(2)
live = (brightness > 14) & (brightness < 244)
cols = np.nonzero(live.any(0))[0]
rows = np.nonzero(live.any(1))[0]
return int(cols.min()), int(rows.min()), int(cols.max()) + 1, int(rows.max()) + 1
def bar_box(poster: Image.Image) -> tuple[int, int, int, int] | None:
"""하단 주최·주관·후원 로고 띠(밝은 가로 밴드)의 bbox."""
pixels = np.asarray(poster.convert("RGB")).astype(np.float32)
height, width = pixels.shape[:2]
search_from = int(height * LOGO_BAR_SEARCH_FROM)
rows = np.nonzero(pixels[search_from:].mean(axis=(1, 2)) > LOGO_BAR_BRIGHTNESS)[0]
if len(rows) < LOGO_BAR_MIN_ROWS:
return None
return 0, search_from + rows.min() - 4, width, min(height, search_from + rows.max() + 5)
def logo_bar(poster: Image.Image) -> Image.Image | None:
box = bar_box(poster)
return poster.crop(box) if box else None
def round_mask(size: tuple[int, int], radius_ratio: float = 0.08) -> Image.Image:
"""사각 패치를 둥근 카드 위에 얹을 때 모서리가 튀는 것을 막는 알파 마스크."""
width, height = size
mask = Image.new("L", size, 0)
ImageDraw.Draw(mask).rounded_rectangle(
(0, 0, width - 1, height - 1),
radius=max(1, round(min(width, height) * radius_ratio)), fill=255)
return mask
def to_data_uri(image: Image.Image, max_size: tuple[int, int] = (1100, 1600)) -> str:
image = image.copy()
+26 -6
View File
@@ -1,13 +1,13 @@
"""포스터에서 QR 흰 카드를 찾는다.
"우상단에서 가장 큰 흰 블롭"을 QR로 삼던 검출기는 하늘 그러데이션·흰 글자띠·색 체크무늬를
줄줄이 걸었다. 배치 27장으로 캘리브레이션해 파인더 패턴(1:1:3:1:1)까지 확인한다.
"우상단에서 가장 큰 흰 블롭"으로 잡던 검출기가 하늘 그러데이션·흰 글자띠·색 체크무늬까지
걸어서, 배치 27장으로 캘리브레이션한 뒤 파인더 패턴(1:1:3:1:1)까지 확인한다.
"""
import numpy as np
from PIL import Image
from scipy import ndimage
# QR은 우상단에만 있지 않다 — 우하단에 단 포스터를 통째로 놓친 적이 있다. 네 귀퉁이를 다 본다.
# 우하단에 QR을 단 포스터를 통째로 놓친 적이 있어 네 귀퉁이를 다 본다
CORNER_WINDOWS = ((0.70, 0.00, 1.00, 0.18), (0.70, 0.82, 1.00, 1.00),
(0.00, 0.00, 0.30, 0.18), (0.00, 0.82, 0.30, 1.00))
FINDER_HIT_THRESHOLD = 30
@@ -98,12 +98,32 @@ def qr_box(poster: Image.Image, strict: bool = True,
) -> tuple[int, int, int, int] | None:
"""QR 흰 카드의 bbox. 없으면 None.
strict=True(원본 포스터용): is_qr을 통과한 블롭만. QR의 유무는 원본이 정한다.
strict=False(모델 출력 검증용): 창 안의 가장 큰 흰 블롭. 모델이 뭉갠 QR은 파인더가
살아남지 못하므로, 묻는 것은 "QR인가"가 아니라 "예상한 자리에 흰 카드가 있는가"다.
strict=True(원본 포스터용)는 is_qr을 통과한 블롭만 돌려준다.
strict=False(모델 출력 검증용)는 창 안의 가장 큰 흰 블롭을 돌려주는데, 모델이 뭉갠 QR은
파인더가 살아남지 못해 "예상한 자리에 흰 카드가 있는가"만 물을 수 있기 때문이다.
"""
for corner in ((window,) if window else CORNER_WINDOWS):
for box in find_white_blobs(poster, corner):
if not strict or is_qr(poster, box):
return box
return None
def qr_card(poster: Image.Image, pad: int = 14) -> Image.Image | None:
"""QR 흰 카드를 오려낸다. 둥근 모서리라 사각 크롭엔 배경이 딸려와 채도로 걷어낸다.
pad는 카드 둘레에 덧대는 흰 여백(quiet zone). 포스터 안쪽 제자리에 덮을 때는
카드 자체에 여백이 있으므로 0을 준다.
"""
box = qr_box(poster)
if box is None:
return None
card = np.asarray(poster.crop(box).convert("RGB")).astype(np.float32)
card[(card.max(2) - card.min(2)) > 35] = 255.0 # 유채색 프린지 → 흰색
cropped = Image.fromarray(card.astype(np.uint8))
if pad == 0:
return cropped
padded = Image.new("RGB", (cropped.width + pad * 2, cropped.height + pad * 2),
(255, 255, 255))
padded.paste(cropped, (pad, pad))
return padded
+104
View File
@@ -0,0 +1,104 @@
"""프레임 PNG를 디스크에 풀지 않고 메모리에서 디코드·인코드하는 비디오 유틸."""
import io
from collections.abc import Iterable, Iterator, Sequence
from fractions import Fraction
from pathlib import Path
import av
import numpy as np
from PIL import Image
AAC_FRAME_SIZE = 1024
def open_clip(clip: bytes | Path):
return av.open(io.BytesIO(clip) if isinstance(clip, bytes) else str(clip))
def duration(clip: bytes | Path) -> float:
container = open_clip(clip)
try:
if container.duration is None:
raise RuntimeError("클립 길이를 읽을 수 없다")
return container.duration / av.time_base
finally:
container.close()
def frames_at(clip: bytes | Path, times: Sequence[float]) -> list[Image.Image]:
"""지정한 시각들의 프레임. seek은 키프레임 단위라 그 이후 첫 프레임을 취한다."""
container = open_clip(clip)
stream = container.streams.video[0]
frames = []
try:
for at in times:
container.seek(int(at / stream.time_base), stream=stream)
picked = None
for frame in container.decode(stream):
picked = frame
if frame.time is not None and frame.time >= at - 1e-3:
break
if picked is None:
raise RuntimeError(f"t={at}s 프레임을 못 뽑았다")
frames.append(picked.to_image())
finally:
container.close()
return frames
def decode_frames(clip: bytes | Path) -> Iterator[Image.Image]:
"""모든 프레임을 순서대로 흘려보낸다. 한 장씩만 메모리에 올라간다."""
container = open_clip(clip)
try:
for frame in container.decode(video=0):
yield frame.to_image()
finally:
container.close()
def encode_mp4(frames: Iterable[Image.Image], size: tuple[int, int],
audio: np.ndarray | None = None, *, fps: int = 24,
sample_rate: int = 44100, crf: int = 18,
audio_bit_rate: int = 192000) -> bytes:
"""H.264 영상 + AAC 스테레오 오디오를 mp4 바이트로 뽑는다. 모노 오디오는 양 채널에 복제한다."""
buffer = io.BytesIO()
container = av.open(buffer, "w", format="mp4")
video_stream = container.add_stream("libx264", rate=fps)
video_stream.width, video_stream.height = size
video_stream.pix_fmt = "yuv420p"
video_stream.options = {"crf": str(crf), "preset": "medium"}
audio_stream = None
if audio is not None:
audio_stream = container.add_stream("aac", rate=sample_rate)
audio_stream.layout = "stereo"
audio_stream.bit_rate = audio_bit_rate
for index, image in enumerate(frames):
frame = av.VideoFrame.from_image(image)
frame.pts = index
for packet in video_stream.encode(frame):
container.mux(packet)
for packet in video_stream.encode():
container.mux(packet)
if audio_stream is not None:
interleaved = np.repeat(audio, 2)
block_size = audio_stream.frame_size or AAC_FRAME_SIZE
for start in range(0, len(audio), block_size):
block = interleaved[start * 2:(start + block_size) * 2]
if len(block) < block_size * 2:
block = np.pad(block, (0, block_size * 2 - len(block)))
frame = av.AudioFrame.from_ndarray(block.reshape(1, -1),
format="s16", layout="stereo")
frame.rate = sample_rate
frame.pts = start
frame.time_base = Fraction(1, sample_rate)
for packet in audio_stream.encode(frame):
container.mux(packet)
for packet in audio_stream.encode():
container.mux(packet)
container.close()
return buffer.getvalue()
+81
View File
@@ -60,3 +60,84 @@ detect와 달리 후처리가 없어 LLM 응답이 곧 결과이고, 지금 모
대신 `answers` 타입이 이 단계의 공개 반환 타입이 되어 LLM 레이어가 위로 새어나간다.
API 레이어가 다른 형태를 요구하면 그때 `models/narration.py`를 만들고 변환을 넣는다.
### metadata에서 괄호 내용이 사라진다
`concert_poster_image` 실측 — 포스터 표기와 metadata가 다르다.
| 필드 | 포스터 | metadata |
|---|---|---|
| date_text | `2023. 1. 26(THU) 7:30PM` | `2023. 1. 26THU 7:30PM` |
| place | `영도문화예술회관 봉래홀(대공연장)` | `영도문화예술회관 봉래홀` |
둘 다 괄호가 걸렸다. 나레이션에만 걸리는 금지문자 규칙(`( )` 금지)을 모델이 metadata까지
적용한 것으로 보인다. 밸리데이터는 나레이션만 검사하므로 그대로 통과한다.
**영상에는 영향이 없다.** date_text·place는 아카이브 메타태그일 뿐 TTS도 렌더도 쓰지 않는다.
문제는 신호 쪽이다 — 모델이 표기를 그대로 옮기지 않고 "정리"하고 있다는 뜻이고, 같은
메커니즘이 숫자·지명에 걸리면 연도 오독(2026→2036)처럼 조용히 틀린 값이 아카이브에 남는다.
프롬프트에서 metadata는 금지문자 규칙 대상이 아니며 괄호까지 그대로 옮기라고 못박아야 한다.
## ⑤ bgm
### Suno가 요청한 길이를 무시하고 풀 트랙을 준다
`festival_poster_image` 실측 — `[Song Duration: Around 15 seconds]`를 넣었는데 128초짜리가
왔다. 트랙 선택은 목표 길이에 가장 가까운 것을 고르지만, 후보가 전부 길면 소용이 없다.
⑦이 그 트랙의 앞부분을 영상 길이만큼 잘라 쓴다. 어디가 쓸 만한 구간인지는 보지 않으므로
인트로가 걸리면 그대로 인트로가 깔린다.
## ⑥ i2v
### CLI와 HTTP API가 서로 다른 모델을 준다
이식한 코드는 `higgsfield` CLI를 서브프로세스로 부른다. CLI 토큰 인증이라 머신마다 사람이
로그인해야 하고 컨테이너 배포가 막힌다. 공식 SDK(`higgsfield-client`)는 API 키를 쓰므로
그 문제가 없고 업로드도 presigned URL이라 로컬 파일이 필요 없다.
그런데 `openapi.json` 확인 결과 **API에 Kling 3.0이 없다.** 2.1과 2.5-turbo뿐이다.
| | CLI | HTTP API |
|---|---|---|
| 모델 | kling3_0 | kling-video 2.5-turbo까지 |
| duration | 정수 자유 (8 사용) | **5 또는 10만** |
| aspect_ratio | 지정 가능 | 파라미터 없음 |
| sound | off 지정 가능 | 파라미터 없음 |
| 비용 사전조회 | `generate cost` | 없음 |
**duration 5/10이 걸림돌이다.** 파이프라인 전체가 8초 고정을 전제로 한다 — ②의 "7초 안에
읽혀야 한다", ④ 타임라인, ⑤ BGM 길이가 모두 거기서 나왔다.
aspect_ratio·sound는 실질 문제가 아닐 수 있다. Kling은 9:16을 지정해도 입력 이미지 비율로
출력하고, 오디오는 렌더에서 새로 얹는다.
**비용 사전조회가 없는 것은 실질 손실이다.** `max_credits` 오설정 방어가 사라진다.
**결정: CLI를 유지한다.** 8초와 Kling 3.0을 지키는 쪽을 택했고, 서브프로세스·머신별 로그인·
컨테이너 제약은 그 대가로 안고 간다. API가 8초나 Kling 3.0을 지원하면 그때 다시 본다.
### 배포에 Node 런타임이 딸려온다
`@higgsfield/cli`가 npm 패키지라 파이썬 이미지에 바이너리 하나 때문에 Node를 통째로 넣어야
한다. 이미지 안에서 `higgsfield auth login`을 사람이 할 수 없으므로
`~/.config/higgsfield/credentials.json`을 볼륨이나 시크릿으로 주입하는 방식이 된다.
토큰 만료·계정 전환을 배포 파이프라인이 감당해야 한다.
### CLI 버전을 고정하지 않았다
`npm i -g @higgsfield/cli`는 항상 최신을 깐다. `utils/higgsfield.py`가 `--json`을 주고도
정규식으로 stdout을 긁는 이유가 원본 주석에 있다 — "`--json`이 평문을 돌려줄 때가 있다".
출력 포맷이 바뀌면 `parse_result_url`과 `parse_credits`가 함께 깨진다.
### 계정 가드는 CLI 경로에만 필요하다
`utils/higgsfield.py`의 `assert_account()`는 CLI 토큰이 조용히 바뀌어 남의 크레딧이 빠지는
사고를 막는 장치다. API 키로 가면 키가 곧 계정이라 이 가드 자체가 불필요해진다.
`higgsfield_account` 설정도 같이 없어진다.
### 생성부를 실행 검증하지 못했다
이 머신에 higgsfield CLI가 없다. `result_url`·`credits` 정규식 파싱은 원본을 옮겼을 뿐
실제 CLI 출력으로 확인한 것이 아니다.