feat: P2V 파이프라인 연동 및 좋아요·댓글·공유 지원
- 무빙 포스터(p2v_video)·롱컷(p2v_playreel) 파이프라인과 워커, 갤러리·내 콘텐츠 노출 - 좋아요·댓글: comment/video_reaction에 p2v_playreel_id 추가, 종류별 CHECK 확장 - P2V 소프트 삭제(is_deleted), queued/running 삭제 차단 - 공개 상세·공유 OG 페이지 추가 - 삭제된 부모 댓글이 목록에서 사라지던 has_live_reply 서브쿼리 버그 수정 - 마이그레이션: migration_2026-10-15_p2v_reactions.sql
This commit is contained in:
1 parent
bb1ea12958
commit
b16d4a8f1b
126 files changed
+6921
-62
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,52 @@
|
||||
"""④ analyze — 검수 게이트에 올릴 재료를 만든다.
|
||||
|
||||
여기서 사람이 움직일 요소를 확정하고, 그 승인이 14크레딧 지출을 확정한다.
|
||||
실제 프롬프트는 ⑤ motion에서 사람이 고른 키로 다시 쓴다.
|
||||
"""
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from app.p2v.schemas.analysis import FixedLayer, MotionChoice, PosterAnalysis
|
||||
from app.p2v.services.motion import plan_motion
|
||||
from app.p2v.utils.higgsfield import KLING_3_0
|
||||
from app.p2v.utils.image import review_grid_overlay
|
||||
|
||||
MOTION_LABELS = {
|
||||
"ray": "광선", "snow": "눈", "fog": "안개", "glow": "발광", "light": "조명",
|
||||
"star": "별", "cloud": "구름", "smoke": "연기", "water": "물", "wave": "파도",
|
||||
"moon": "달", "sun": "해", "flag": "깃발", "foliage": "나뭇잎", "vessel": "배",
|
||||
"crowd": "사람 무리", "wheel": "바퀴·관람차", "firework": "불꽃놀이",
|
||||
}
|
||||
FIXED_LABELS = {"title": "제목", "logo": "로고", "date": "일시",
|
||||
"person": "인물", "sponsor": "후원 바"}
|
||||
|
||||
# veo·seedance가 디즈니 IP 작품을 거부한 이력이 있어, 크레딧을 쓰기 전에 경고만 띄운다.
|
||||
# 한국어 표기 몇 개만 보는 어림짐작이라 판정이 아니다.
|
||||
IP_RISK_PATTERN = re.compile(r"디즈니|겨울왕국|라이온킹|알라딘|마블")
|
||||
|
||||
|
||||
def motion_choices(kept, dropped) -> list[MotionChoice]:
|
||||
"""VLM이 고른 것은 켜고, 확신 없어 탈락한 것은 꺼서 함께 보여준다."""
|
||||
chosen = {item.motion for item in kept}
|
||||
choices = [MotionChoice(key=item.motion, label=MOTION_LABELS.get(item.motion, item.motion),
|
||||
what=item.what, on=True) for item in kept]
|
||||
choices += [MotionChoice(key=item.motion, label=MOTION_LABELS.get(item.motion, item.motion),
|
||||
what=item.what, on=False)
|
||||
for item in dropped if item.motion not in chosen]
|
||||
return choices
|
||||
|
||||
|
||||
async def analyze_poster(poster: Path | Image.Image, title: str = "") -> PosterAnalysis:
|
||||
source = (Image.open(poster) if isinstance(poster, Path) else poster).convert("RGB")
|
||||
plan = await plan_motion(source)
|
||||
return PosterAnalysis(
|
||||
grid=review_grid_overlay(source),
|
||||
movable=motion_choices(plan.kept, plan.dropped),
|
||||
fixed=[FixedLayer(key=key, label=label) for key, label in FIXED_LABELS.items()],
|
||||
model=KLING_3_0,
|
||||
ip_risk=bool(IP_RISK_PATTERN.search(title)),
|
||||
has_qr=plan.has_qr,
|
||||
plan=plan,
|
||||
)
|
||||
@@ -0,0 +1,92 @@
|
||||
"""⑤ bgm — Suno V5 인스트루멘털 BGM.
|
||||
|
||||
보컬이 있으면 나레이션과 주파수·의미가 겹쳐 둘 다 안 들리므로 반드시 instrumental로 뽑고,
|
||||
목표 길이는 나레이션 실측 길이에서 역산한다.
|
||||
"""
|
||||
import asyncio
|
||||
|
||||
import httpx
|
||||
|
||||
from app.p2v.answers.narration_answer import BgmStyle
|
||||
from app.p2v.schemas.bgm import BgmAudio
|
||||
from config import apikey_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
|
||||
|
||||
|
||||
# 나레이션을 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)))
|
||||
|
||||
|
||||
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": apikey_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 apikey_settings.SUNO_API_KEY:
|
||||
raise RuntimeError("SUNO_API_KEY 없음")
|
||||
seconds = target_seconds(narration_total)
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
timeout=180, headers={"Authorization": f"Bearer {apikey_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)
|
||||
@@ -0,0 +1,112 @@
|
||||
"""⑩ hybrid 설정을 포스터에서 뽑는다.
|
||||
|
||||
원본은 이 값을 사람이 손으로 재서 configs/nol_<slug>.json에 적었고, 신규 공연은 거기서
|
||||
멈췄다. 좌표는 detect가 이미 찾은 영역을 쓰고, 인물 사각만 따로 묻는다.
|
||||
|
||||
타이밍(punches·sweep·glows)은 이미지에서 잴 수 있는 값이 아니라 기본 템플릿이다.
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
from app.p2v.answers.person_box_answer import PersonBoxAnswer
|
||||
from app.p2v.schemas.detect import Box, Regions
|
||||
from app.p2v.schemas.hybrid import LayerConfig, MaskSpec, Rect
|
||||
from app.p2v.services.detect import detect
|
||||
from config import apikey_settings
|
||||
from app.p2v.utils.common_llm import StructuredLLM
|
||||
from app.p2v.utils.image import to_data_uri, vlm_grid_overlay
|
||||
from app.p2v.utils.prompt import load_prompt
|
||||
|
||||
# 고정층은 글리프보다 넓게 잡는다. 글자만 덮으면 베벨·그림자가 밀려 겹쳐 보인다.
|
||||
FIXED_RECT_PAD = 0.012
|
||||
DARK_POSTER_LUMINANCE = 60 # 이보다 어두우면 사각 고정층이 검은 상자가 된다
|
||||
|
||||
SWEEP_AT = 2.4
|
||||
FIRST_PUNCH_AT = 3.1
|
||||
PUNCH_GAP = 0.7 # 겹치면 이웃 복원이 안 된다
|
||||
DATE_PUNCH_AT = 5.5
|
||||
PUNCH_PEAK_MAX = 1.5
|
||||
PUNCH_PEAK_MIN = 1.05
|
||||
|
||||
PUNCH_KINDS = ("title", "datetime")
|
||||
PROTECT_KINDS = ("place", "logo")
|
||||
|
||||
PERSON_BOX_PROMPT = load_prompt("person_box")
|
||||
|
||||
person_llm = StructuredLLM("gpt-4o", apikey_settings.CHATGPT_API_KEY)
|
||||
|
||||
|
||||
def padded_rect(box: Box, pad: float = FIXED_RECT_PAD) -> Rect:
|
||||
return (max(0.0, box.x0 - pad), max(0.0, box.y0 - pad),
|
||||
min(1.0, box.x1 + pad), min(1.0, box.y1 + pad))
|
||||
|
||||
|
||||
def punch_peak(rect: Rect) -> float:
|
||||
"""넓은 블록일수록 덜 키운다 — 키운 크롭이 프레임을 넘으면 잘린다."""
|
||||
width = max(rect[2] - rect[0], 1e-3)
|
||||
return round(min(PUNCH_PEAK_MAX, max(PUNCH_PEAK_MIN, 1 / width)), 2)
|
||||
|
||||
|
||||
def is_dark_poster(poster: Image.Image) -> bool:
|
||||
return float(np.asarray(poster.convert("L")).mean()) < DARK_POSTER_LUMINANCE
|
||||
|
||||
|
||||
async def ask_person_box(poster: Image.Image) -> Rect | None:
|
||||
answer = await person_llm.ask_with_images(
|
||||
PersonBoxAnswer, PERSON_BOX_PROMPT,
|
||||
[("격자를 씌운 포스터:", to_data_uri(vlm_grid_overlay(poster)))])
|
||||
if answer.person is None:
|
||||
return None
|
||||
box = answer.person
|
||||
return (box.x0 / 100, box.y0 / 100, box.x1 / 100, box.y1 / 100)
|
||||
|
||||
|
||||
def emphasis(regions: Regions, dark: bool) -> tuple[list, list]:
|
||||
"""밝은 포스터는 펀치로, 검정 포스터는 glow로 강조한다.
|
||||
|
||||
검정 포스터에서 사각을 키워 덮으면 그 사각이 검은 상자로 보인다.
|
||||
"""
|
||||
punches, glows = [], []
|
||||
at = FIRST_PUNCH_AT
|
||||
for kind in PUNCH_KINDS:
|
||||
box = regions.regions.get(kind)
|
||||
if box is None:
|
||||
continue
|
||||
rect = padded_rect(box)
|
||||
when = DATE_PUNCH_AT if kind == "datetime" else at
|
||||
if dark:
|
||||
glows.append((rect, when))
|
||||
else:
|
||||
punches.append((rect, when, punch_peak(rect)))
|
||||
at += PUNCH_GAP
|
||||
return punches, glows
|
||||
|
||||
|
||||
def build_from_regions(regions: Regions, person: Rect | None, dark: bool) -> LayerConfig:
|
||||
fixed_rects = [padded_rect(box) for box in regions.regions.values()]
|
||||
title = regions.regions.get("title")
|
||||
punches, glows = emphasis(regions, dark)
|
||||
|
||||
return LayerConfig(
|
||||
mask=MaskSpec(mode="glyph" if dark else "rect"),
|
||||
fixed_rects=fixed_rects,
|
||||
sil_box=person or (0.0, 0.0, 0.0, 0.0),
|
||||
sil_poly=[], # 다각형은 손으로 그려야 해서 비운다
|
||||
glyphs={"title": padded_rect(title)} if title else {},
|
||||
sweep_at={"title": SWEEP_AT} if title else {},
|
||||
punches=punches,
|
||||
glows=glows,
|
||||
protect=[padded_rect(regions.regions[kind]) for kind in PROTECT_KINDS
|
||||
if kind in regions.regions],
|
||||
glyph_dark_ink=not dark,
|
||||
)
|
||||
|
||||
|
||||
async def build_layer_config(poster: Path | Image.Image,
|
||||
regions: Regions | None = None) -> LayerConfig:
|
||||
source = (Image.open(poster) if isinstance(poster, Path) else poster).convert("RGB")
|
||||
if regions is None:
|
||||
regions = (await detect(source)).data
|
||||
return build_from_regions(regions, await ask_person_box(source), is_dark_poster(source))
|
||||
@@ -0,0 +1,419 @@
|
||||
"""⑪ compose — 무빙포스터 훅 + 상세페이지 스크롤로 30초 롱컷을 조립한다.
|
||||
|
||||
씬 경계는 나레이션 큐다. 0초는 포스터 원본이라 첫 프레임이 곧 썸네일이 된다.
|
||||
상세페이지는 잘라 붙이지 않고 롱이미지를 실제로 스크롤한다 — 조각은 "어디부터 읽을지"를
|
||||
정하는 시작점일 뿐이고, 화면에 흐르는 것은 언제나 원본 롱이미지다.
|
||||
포스터는 세로 롱이라 9:16을 못 채워서 포스터 블러판 위에 얹는다.
|
||||
|
||||
텍스트 오버레이는 넣지 않는다. 남는 글자는 엔드밴드뿐이다.
|
||||
"""
|
||||
import io
|
||||
import math
|
||||
from collections.abc import Iterator, Sequence
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image, ImageDraw, ImageFilter, ImageOps
|
||||
|
||||
from app.p2v.schemas.detail_section import DetailSection
|
||||
from app.p2v.schemas.longcut import EndBandInfo, LongcutPlan, LongcutResult, Scene
|
||||
from app.p2v.schemas.tts import NarrationTimeline
|
||||
from app.p2v.utils.audio import SAMPLE_RATE, apply_limiter, decode_mp3
|
||||
from app.p2v.utils.font import font
|
||||
from app.p2v.utils.video import decode_frames, encode_mp4
|
||||
|
||||
W, H, FPS = 1080, 1920, 24
|
||||
CROSSFADE_FRAMES = 10
|
||||
|
||||
NARRATION_VOL, BGM_VOL = 1.45, 0.55
|
||||
DUCK_DEPTH = 0.25 # 나레이션 구간에서 BGM을 이 배까지 누른다 (약 -12dB)
|
||||
DUCK_THRESHOLD = 0.03
|
||||
DUCK_ATTACK_MS, DUCK_RELEASE_MS = 60, 500
|
||||
BGM_FADE_OUT = 1.2
|
||||
|
||||
# 큐 1초당 화면 높이의 몇 배를 훑을지. 5초 씬에 이미지 높이의 15~30%가 읽기 좋은 속도다
|
||||
SCROLL_SCREENS_PER_SECOND = 0.35
|
||||
|
||||
# 프레임보다 짧은 롱이미지를 늘릴 때 쓰는 값. 글자 없는 배경 띠를 거울 타일링한다
|
||||
INK_DEVIATION = 32 # 배경색에서 이만큼 벗어난 픽셀을 잉크로 본다
|
||||
INK_ROW_RATIO = 0.003 # 행의 잉크 비율이 이 미만이면 글자 없는 행
|
||||
EXTEND_FEATHER = 40 # 이음매를 이만큼 겹쳐 섞는다
|
||||
MIN_BLANK_BAND = 24 # 늘리기에 쓸 배경 띠의 최소 높이
|
||||
|
||||
PROOF_COUNT = 8 # 완성본 전체에서 고르게 뽑는 시점 수
|
||||
PROOF_SIZE = (180, 320)
|
||||
PROOF_GAP = 10
|
||||
THUMBNAIL_QUALITY = 90
|
||||
|
||||
BAND_HEIGHT = 300
|
||||
BAND_RISE_SECONDS = 0.6
|
||||
NOL_BLUE = (0x41, 0x54, 0xFF)
|
||||
ASSET_DIR = Path(__file__).resolve().parent.parent / "assets" / "nol"
|
||||
NOL_WORDMARK = ASSET_DIR / "nol_wordmark_white.png"
|
||||
|
||||
# 큐 순서대로 채울 씬. 앞 둘은 클립, 마지막은 포스터, 나머지는 이 태그 우선순위로 고른다.
|
||||
CLIP_CUES = 2
|
||||
# 여기 없는 태그는 시작점이 안 된다 — 유의사항·제작진·타 공연 배너·조각은 읽힐 내용이
|
||||
# 아니고, 키비주얼은 앞 큐의 포스터와 겹친다. 관람 정보는 러닝타임·관람등급이라 남긴다
|
||||
SCROLL_TAG_PRIORITY = ("synopsis", "still", "cast", "schedule", "discount", "event", "info")
|
||||
REQUIRED_TAGS = ("schedule",) # 캐스팅 스케줄은 예매 전에 확인하는 정보라 빠지면 안 된다
|
||||
|
||||
|
||||
def ease_sine(t: float) -> float:
|
||||
return 0.5 - 0.5 * math.cos(math.pi * min(max(t, 0.0), 1.0))
|
||||
|
||||
|
||||
def blurred_bg(poster: Image.Image) -> Image.Image:
|
||||
small = poster.copy()
|
||||
small.thumbnail((270, 480))
|
||||
blurred = small.resize((W, H), Image.LANCZOS).filter(ImageFilter.GaussianBlur(28))
|
||||
return Image.eval(blurred, lambda v: int(v * 0.45))
|
||||
|
||||
|
||||
def ink_rows(image: Image.Image) -> np.ndarray:
|
||||
"""행마다 글자·그림이 있는지. 배경 중앙값에서 벗어난 픽셀의 비율로 본다."""
|
||||
pixels = np.asarray(image.convert("L")).astype(np.int16)
|
||||
background = np.median(pixels)
|
||||
return (np.abs(pixels - background) > INK_DEVIATION).mean(axis=1) > INK_ROW_RATIO
|
||||
|
||||
|
||||
def blank_band(image: Image.Image) -> tuple[int, int]:
|
||||
"""늘리기에 쓸, 글자 없는 가장 긴 행 구간. 없으면 맨 아래 띠를 쓴다."""
|
||||
blank = ~ink_rows(image)
|
||||
best = (0, 0)
|
||||
start = None
|
||||
for y, empty in enumerate(np.append(blank, False)):
|
||||
if empty and start is None:
|
||||
start = y
|
||||
elif not empty and start is not None:
|
||||
if y - start > best[1] - best[0]:
|
||||
best = (start, y)
|
||||
start = None
|
||||
if best[1] - best[0] >= MIN_BLANK_BAND:
|
||||
return best
|
||||
return max(0, image.height - MIN_BLANK_BAND), image.height
|
||||
|
||||
|
||||
def extend_to_height(image: Image.Image, height: int = H) -> Image.Image:
|
||||
"""프레임보다 짧은 롱이미지를 배경 띠의 거울 타일링으로 늘린다.
|
||||
|
||||
짧다고 블러 배경 위에 얹으면 화면 절반이 포스터로 남는다. 배경만 이어 붙여
|
||||
풀프레임을 채우고, 이음매는 페더로 지운다.
|
||||
"""
|
||||
if image.height >= height:
|
||||
return image
|
||||
|
||||
top, bottom = blank_band(image)
|
||||
band = image.crop((0, top, image.width, bottom))
|
||||
canvas = Image.new("RGB", (image.width, height))
|
||||
canvas.paste(image, (0, 0))
|
||||
|
||||
y, flipped = image.height, True
|
||||
while y < height:
|
||||
tile = ImageOps.flip(band) if flipped else band
|
||||
tile = tile.crop((0, 0, tile.width, min(tile.height, height - y)))
|
||||
canvas.paste(tile, (0, y))
|
||||
_feather_seam(canvas, y, image.width)
|
||||
y += tile.height
|
||||
flipped = not flipped
|
||||
return canvas
|
||||
|
||||
|
||||
def _feather_seam(canvas: Image.Image, seam: int, width: int,
|
||||
feather: int = EXTEND_FEATHER) -> None:
|
||||
"""이음매 위아래를 선형 혼합해 가로줄이 보이지 않게 한다."""
|
||||
top, bottom = max(0, seam - feather), min(canvas.height, seam + feather)
|
||||
if bottom - top < 2:
|
||||
return
|
||||
patch = np.asarray(canvas.crop((0, top, width, bottom))).astype(np.float32)
|
||||
blurred = np.asarray(
|
||||
canvas.crop((0, top, width, bottom)).filter(ImageFilter.GaussianBlur(6))
|
||||
).astype(np.float32)
|
||||
weight = 1.0 - np.abs(np.linspace(-1.0, 1.0, bottom - top))
|
||||
mixed = patch + (blurred - patch) * weight[:, None, None]
|
||||
canvas.paste(Image.fromarray(mixed.clip(0, 255).astype(np.uint8)), (0, top))
|
||||
|
||||
|
||||
def to_surface(image: Image.Image) -> Image.Image:
|
||||
"""롱이미지를 폭 1080에 맞추고 프레임 높이까지 늘린다.
|
||||
|
||||
자르지 않는다 — 섹션 y좌표가 이 이미지 기준이라 위를 깎으면 시작점이 어긋난다.
|
||||
"""
|
||||
scaled = image.convert("RGB").resize(
|
||||
(W, max(1, round(image.height * W / image.width))), Image.LANCZOS)
|
||||
return extend_to_height(scaled, H)
|
||||
|
||||
|
||||
def still_scene(still: Image.Image, progress: float, index: int) -> Image.Image:
|
||||
"""켄번즈. 가로형은 높이를 채워 좌우로 팬하고, 세로형은 폭을 채워 위아래로 민다."""
|
||||
width, height = still.size
|
||||
if width / height >= W / H:
|
||||
scale = H / height * (1.0 + 0.04 * ease_sine(progress))
|
||||
scaled_w, scaled_h = int(width * scale), int(height * scale)
|
||||
span = max(0, scaled_w - W)
|
||||
shift = ease_sine(progress) if index % 2 == 0 else 1 - ease_sine(progress)
|
||||
x, y = -int(span * shift), -(scaled_h - H) // 2
|
||||
else:
|
||||
scale = W / width * (1.0 + 0.04 * ease_sine(progress))
|
||||
scaled_w, scaled_h = int(width * scale), int(height * scale)
|
||||
x, y = -(scaled_w - W) // 2, -int(max(0, scaled_h - H) * ease_sine(progress))
|
||||
frame = Image.new("RGB", (W, H), (0, 0, 0))
|
||||
frame.paste(still.resize((scaled_w, scaled_h), Image.LANCZOS), (x, y))
|
||||
return frame
|
||||
|
||||
|
||||
def scroll_top(surface: Image.Image, fraction: float) -> int:
|
||||
"""이미지 높이 대비 비율을 실제 crop 시작 y로. 끝을 넘지 않게 묶는다."""
|
||||
span = max(0, surface.height - H)
|
||||
return min(max(0, round(surface.height * fraction)), span)
|
||||
|
||||
|
||||
def scroll_scene(surface: Image.Image, progress: float, y0: float, y1: float) -> Image.Image:
|
||||
"""롱이미지를 y0~y1 구간까지 훑는다. 프레임을 가득 채운다 — 배경이 비지 않는다."""
|
||||
start, end = scroll_top(surface, y0), scroll_top(surface, y1)
|
||||
top = start + round((end - start) * ease_sine(progress))
|
||||
return surface.crop((0, top, W, top + H))
|
||||
|
||||
|
||||
def poster_scene(poster: Image.Image, background: Image.Image, progress: float) -> Image.Image:
|
||||
"""정착 — 전체를 보여주며 아주 천천히 밀어 넣는다."""
|
||||
width, height = poster.size
|
||||
scale = W / width * 0.93 * (1.0 + 0.02 * progress)
|
||||
scaled = poster.resize((int(width * scale), int(height * scale)), Image.LANCZOS)
|
||||
frame = background.copy()
|
||||
frame.paste(scaled, ((W - scaled.width) // 2, (H - scaled.height) // 2))
|
||||
return frame
|
||||
|
||||
|
||||
def end_band(frame: Image.Image, info: EndBandInfo, seconds: float,
|
||||
qr: Image.Image | None) -> None:
|
||||
"""하단 NOL 밴드가 0.6초에 걸쳐 올라오고, 그 뒤 CTA와 정보 두 줄이 들어온다."""
|
||||
top = H - int(BAND_HEIGHT * ease_sine(seconds / BAND_RISE_SECONDS))
|
||||
ImageDraw.Draw(frame).rectangle((0, top, W, H), fill=NOL_BLUE)
|
||||
if seconds < BAND_RISE_SECONDS:
|
||||
return
|
||||
|
||||
next_x = 60
|
||||
if NOL_WORDMARK.exists():
|
||||
mark = Image.open(NOL_WORDMARK).convert("RGBA")
|
||||
mark_h = 78
|
||||
mark = mark.resize((int(mark.width * mark_h / mark.height), mark_h), Image.LANCZOS)
|
||||
frame.paste(mark, (next_x, top + 44), mark)
|
||||
next_x += mark.width + 26
|
||||
|
||||
draw = ImageDraw.Draw(frame)
|
||||
draw.text((next_x, top + 44), "티켓 예매", font=font("Bold", 58), fill=(255, 255, 255))
|
||||
if qr is not None:
|
||||
size = BAND_HEIGHT - 80
|
||||
frame.paste(qr.convert("RGB").resize((size, size), Image.NEAREST),
|
||||
(W - 60 - size, top + 40))
|
||||
|
||||
for order, (text, weight, size, offset, fill) in enumerate((
|
||||
(info.title, "SemiBold", 40, 150, (255, 255, 255)),
|
||||
(info.detail, "Medium", 36, 208, (225, 230, 255)))):
|
||||
appear = seconds - 0.7 - 0.16 * order
|
||||
if appear < 0:
|
||||
continue
|
||||
slide = int((1 - ease_sine(appear / 0.45)) * 30)
|
||||
draw.text((60, top + offset + slide), text, font=font(weight, size), fill=fill)
|
||||
|
||||
|
||||
def cue_spans(timeline: NarrationTimeline) -> list[tuple[float, float]]:
|
||||
"""큐마다 (시작, 끝). 0번은 0초에서 시작해야 첫 프레임이 포스터가 된다."""
|
||||
starts = [0.0] + [cue.start for cue in timeline.cues[1:]]
|
||||
ends = [cue.start for cue in timeline.cues[1:]] + [timeline.total]
|
||||
return list(zip(starts, ends, strict=True))
|
||||
|
||||
|
||||
def scroll_starts(sections: Sequence[DetailSection],
|
||||
surfaces: dict[str, Image.Image]) -> list[DetailSection]:
|
||||
"""훑기 시작점이 될 섹션을 태그 우선순위대로. 롱이미지가 없는 섹션은 뺀다."""
|
||||
usable = [section for section in sections if section.source in surfaces]
|
||||
by_tag: dict[str, list[DetailSection]] = {}
|
||||
for section in usable:
|
||||
by_tag.setdefault(section.tag, []).append(section)
|
||||
|
||||
ordered: list[DetailSection] = []
|
||||
for tag in REQUIRED_TAGS: # 빠지면 안 되는 것부터 자리를 잡는다
|
||||
ordered += by_tag.get(tag, [])[:1]
|
||||
for tag in SCROLL_TAG_PRIORITY:
|
||||
for section in by_tag.get(tag, []):
|
||||
if section not in ordered:
|
||||
ordered.append(section)
|
||||
return ordered
|
||||
|
||||
|
||||
def scroll_window(surface: Image.Image, start_px: int, seconds: float) -> tuple[float, float]:
|
||||
"""시작 픽셀과 큐 길이로 훑을 구간을 정한다. 롱이미지 높이 대비 비율로 돌려준다.
|
||||
|
||||
여기서 crop 가능한 범위로 묶는다 — 플랜에 남는 값이 곧 실제 이동량이어야
|
||||
게이트가 0픽셀 스크롤을 걸러낼 수 있다.
|
||||
"""
|
||||
span = max(0, surface.height - H)
|
||||
start = min(max(0, start_px), span)
|
||||
end = min(start + round(seconds * SCROLL_SCREENS_PER_SECOND * H), span)
|
||||
return start / surface.height, end / surface.height
|
||||
|
||||
|
||||
def section_start_px(section: DetailSection, source: Image.Image) -> int:
|
||||
"""섹션 y좌표는 원본 롱이미지 기준이라 폭 1080 환산 배율을 곱한다."""
|
||||
return round(section.y0 * W / source.width)
|
||||
|
||||
|
||||
def build_scene_plan(sections: Sequence[DetailSection], spans: Sequence[tuple[float, float]],
|
||||
sources: dict[str, Image.Image],
|
||||
surfaces: dict[str, Image.Image]) -> LongcutPlan:
|
||||
"""큐 앞 둘은 클립, 마지막은 포스터, 사이는 롱이미지를 훑는다."""
|
||||
ordered = scroll_starts(sections, surfaces)
|
||||
fallback = max(surfaces, key=lambda name: surfaces[name].height, default=None)
|
||||
|
||||
scenes: list[Scene] = []
|
||||
index = 0
|
||||
# 롱이미지마다 어디까지 읽었는지 픽셀로 따로 센다. 비율은 이미지 높이가 다르면
|
||||
# 서로 다른 자리를 가리키므로 이어 읽기 지점으로 쓸 수 없다
|
||||
read_to: dict[str, int] = {}
|
||||
for cue, (start, end) in enumerate(spans):
|
||||
if cue < CLIP_CUES:
|
||||
scenes.append(Scene(cue=cue, kind="clip"))
|
||||
elif cue == len(spans) - 1:
|
||||
scenes.append(Scene(cue=cue, kind="poster"))
|
||||
elif index < len(ordered):
|
||||
section = ordered[index]
|
||||
surface = surfaces[section.source]
|
||||
y0, y1 = scroll_window(surface,
|
||||
section_start_px(section, sources[section.source]),
|
||||
end - start)
|
||||
scenes.append(Scene(cue=cue, kind="scroll", section=section.name,
|
||||
tag=section.tag, source=section.source, y0=y0, y1=y1))
|
||||
index = index + 1
|
||||
read_to[section.source] = round(y1 * surface.height)
|
||||
elif fallback is not None:
|
||||
# 쓸 섹션이 떨어져도 포스터로 때우지 않는다. 그 롱이미지를 읽던 자리에서
|
||||
# 이어 읽어야 같은 화면이 두 번 나오지 않는다
|
||||
surface = surfaces[fallback]
|
||||
y0, y1 = scroll_window(surface, read_to.get(fallback, 0), end - start)
|
||||
scenes.append(Scene(cue=cue, kind="scroll", source=fallback, y0=y0, y1=y1))
|
||||
read_to[fallback] = round(y1 * surface.height)
|
||||
else:
|
||||
scenes.append(Scene(cue=cue, kind="poster"))
|
||||
return LongcutPlan(scenes=scenes)
|
||||
|
||||
|
||||
def duck(bgm: np.ndarray, narration: np.ndarray) -> np.ndarray:
|
||||
"""나레이션이 나오는 동안 BGM을 누른다. 원본의 sidechaincompress를 대신한다."""
|
||||
level = np.abs(narration).astype(np.float32) / 32768.0
|
||||
attack = 1.0 / max(1, DUCK_ATTACK_MS * SAMPLE_RATE // 1000)
|
||||
release = 1.0 / max(1, DUCK_RELEASE_MS * SAMPLE_RATE // 1000)
|
||||
envelope = np.zeros_like(level)
|
||||
current = 0.0
|
||||
for index, value in enumerate(level):
|
||||
rate = attack if value > current else release
|
||||
current += (value - current) * rate
|
||||
envelope[index] = current
|
||||
over = np.clip((envelope - DUCK_THRESHOLD) / DUCK_THRESHOLD, 0.0, 1.0)
|
||||
return bgm * (1.0 - (1.0 - DUCK_DEPTH) * over)
|
||||
|
||||
|
||||
def mix_audio(narration_mp3: bytes, bgm_mp3: bytes | None, duration: float) -> np.ndarray:
|
||||
total = round(duration * SAMPLE_RATE)
|
||||
narration = np.zeros(total, dtype=np.float32)
|
||||
voice = decode_mp3(narration_mp3)[:total]
|
||||
narration[:len(voice)] = voice.astype(np.float32) * NARRATION_VOL
|
||||
|
||||
track = narration.copy()
|
||||
if bgm_mp3:
|
||||
music = decode_mp3(bgm_mp3)
|
||||
if len(music) < total:
|
||||
music = np.tile(music, total // len(music) + 1)
|
||||
music = music[:total].astype(np.float32) * BGM_VOL
|
||||
fade = min(total, round(BGM_FADE_OUT * SAMPLE_RATE))
|
||||
music[total - fade:] *= np.linspace(1.0, 0.0, fade, dtype=np.float32)
|
||||
track = track + duck(music, narration)
|
||||
|
||||
return apply_limiter(np.clip(track, -32768, 32767).astype(np.int16))
|
||||
|
||||
|
||||
def compose_frames(timeline: NarrationTimeline, plan: LongcutPlan, poster: Image.Image,
|
||||
clip: bytes, surfaces: dict[str, Image.Image],
|
||||
info: EndBandInfo, qr: Image.Image | None) -> Iterator[Image.Image]:
|
||||
background = blurred_bg(poster)
|
||||
spans = cue_spans(timeline)
|
||||
clip_frames = list(decode_frames(clip))
|
||||
scenes = {scene.cue: scene for scene in plan.scenes}
|
||||
|
||||
def frame_at(cue: int, at: float) -> Image.Image:
|
||||
scene = scenes[cue]
|
||||
if scene.kind == "clip":
|
||||
source = clip_frames[min(int(at * FPS), len(clip_frames) - 1)]
|
||||
fitted = source.resize((W, round(source.height * W / source.width)), Image.LANCZOS)
|
||||
frame = background.copy()
|
||||
frame.paste(fitted, (0, (H - fitted.height) // 2))
|
||||
return frame
|
||||
start, end = spans[cue]
|
||||
progress = (at - start) / max(end - start, 0.01)
|
||||
if scene.kind == "scroll" and scene.source in surfaces:
|
||||
return scroll_scene(surfaces[scene.source], progress,
|
||||
scene.y0 or 0.0, scene.y1 or 0.0)
|
||||
return poster_scene(poster, background, progress)
|
||||
|
||||
total_frames = round(timeline.total * FPS)
|
||||
for index in range(total_frames):
|
||||
at = index / FPS
|
||||
cue = max(order for order, (start, _) in enumerate(spans) if at >= start)
|
||||
image = frame_at(cue, at)
|
||||
remaining = (spans[cue][1] - at) * FPS
|
||||
if cue < len(spans) - 1 and remaining < CROSSFADE_FRAMES \
|
||||
and scenes[cue + 1].kind != "clip":
|
||||
image = Image.blend(image, frame_at(cue + 1, at), 1 - remaining / CROSSFADE_FRAMES)
|
||||
if scenes[cue].kind == "poster":
|
||||
end_band(image, info, at - spans[cue][0], qr)
|
||||
yield image
|
||||
|
||||
|
||||
def proof_sheet(tiles: list[Image.Image]) -> Image.Image:
|
||||
width = (PROOF_SIZE[0] + PROOF_GAP) * len(tiles) - PROOF_GAP
|
||||
sheet = Image.new("RGB", (width, PROOF_SIZE[1]), "black")
|
||||
for order, tile in enumerate(tiles):
|
||||
sheet.paste(tile, (order * (PROOF_SIZE[0] + PROOF_GAP), 0))
|
||||
return sheet
|
||||
|
||||
|
||||
def compose_longcut(poster: bytes | Path | Image.Image, clip: bytes,
|
||||
timeline: NarrationTimeline, narration_mp3: bytes,
|
||||
sections: Sequence[DetailSection], info: EndBandInfo, *,
|
||||
details: dict[str, Image.Image] | None = None,
|
||||
bgm_mp3: bytes | None = None, qr: Image.Image | None = None,
|
||||
plan: LongcutPlan | None = None,
|
||||
preview: bool = False) -> LongcutResult:
|
||||
"""details는 source 이름(detail_01…) → 상세페이지 롱이미지. 스크롤은 이 위에서 일어난다."""
|
||||
if isinstance(poster, Image.Image):
|
||||
source = poster.convert("RGB")
|
||||
else:
|
||||
source = Image.open(poster if isinstance(poster, Path)
|
||||
else io.BytesIO(poster)).convert("RGB")
|
||||
|
||||
sources = dict(details or {})
|
||||
surfaces = {name: to_surface(image) for name, image in sources.items()}
|
||||
spans = cue_spans(timeline)
|
||||
plan = plan or build_scene_plan(sections, spans, sources, surfaces)
|
||||
|
||||
total_frames = round(timeline.total * FPS)
|
||||
# 훅 구간만 보면 뒤쪽 스크롤과 엔드밴드를 검수할 수 없어 전체에서 고르게 뽑는다
|
||||
proof_at = {round(step * total_frames / PROOF_COUNT) for step in range(PROOF_COUNT)}
|
||||
tiles: list[Image.Image] = []
|
||||
thumbnail = io.BytesIO()
|
||||
|
||||
def frames() -> Iterator[Image.Image]:
|
||||
for index, frame in enumerate(
|
||||
compose_frames(timeline, plan, source, clip, surfaces, info, qr)):
|
||||
if index == 0:
|
||||
frame.save(thumbnail, "JPEG", quality=THUMBNAIL_QUALITY)
|
||||
if preview and index in proof_at:
|
||||
tiles.append(frame.resize(PROOF_SIZE))
|
||||
yield frame
|
||||
|
||||
video = encode_mp4(frames(), (W, H), mix_audio(narration_mp3, bgm_mp3, timeline.total),
|
||||
fps=FPS)
|
||||
return LongcutResult(video=video, thumbnail=thumbnail.getvalue(),
|
||||
duration=timeline.total, frames=total_frames,
|
||||
plan=plan, proof=proof_sheet(tiles) if tiles else None)
|
||||
@@ -0,0 +1,125 @@
|
||||
"""① detect — 포스터에서 카메라가 겨냥할 영역을 검출한다.
|
||||
|
||||
격자 위에서 VLM이 대략 읽고, 그 주변에서만 잉크 경계로 다듬는다.
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
from scipy import ndimage
|
||||
|
||||
from app.p2v.answers.detect_answer import DetectAnswer, GridBox
|
||||
from app.p2v.schemas.detect import Box, DetectResult, Focal, Regions
|
||||
from config import apikey_settings
|
||||
from app.p2v.utils.common_llm import StructuredLLM
|
||||
from app.p2v.utils.image import to_data_uri, vlm_grid_overlay
|
||||
from app.p2v.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", apikey_settings.CHATGPT_API_KEY)
|
||||
|
||||
|
||||
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 = vlm_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),
|
||||
)
|
||||
@@ -0,0 +1,36 @@
|
||||
"""② split 부속 — cast 태그 섹션에서 배우 이름을 읽는다.
|
||||
|
||||
NOL meta에는 출연진 필드가 아예 없어 상세페이지 이미지에서 읽는 수밖에 없다.
|
||||
캐스트는 영상의 필수 재료가 아니므로 실패해도 멈추지 않고 source로 남긴다.
|
||||
"""
|
||||
from collections.abc import Sequence
|
||||
|
||||
from app.p2v.answers.cast_answer import CastAnswer
|
||||
from app.p2v.schemas.cast import CastExtraction
|
||||
from app.p2v.schemas.detail_section import DetailSection
|
||||
from config import apikey_settings
|
||||
from app.p2v.utils.common_llm import StructuredLLM
|
||||
from app.p2v.utils.image import to_data_uri
|
||||
from app.p2v.utils.prompt import load_prompt
|
||||
|
||||
CAST_TAG = "cast"
|
||||
CAST_IMAGE_MAX_SIZE = (640, 2000) # 세로 4천px짜리가 온다
|
||||
MAX_NAMES = 12
|
||||
|
||||
EXTRACT_CAST_PROMPT = load_prompt("extract_cast")
|
||||
|
||||
cast_llm = StructuredLLM("gpt-4o", apikey_settings.CHATGPT_API_KEY)
|
||||
|
||||
|
||||
async def extract_cast(sections: Sequence[DetailSection]) -> CastExtraction:
|
||||
section = next((item for item in sections if item.tag == CAST_TAG), None)
|
||||
if section is None:
|
||||
return CastExtraction()
|
||||
try:
|
||||
answer = await cast_llm.ask_with_images(
|
||||
CastAnswer, EXTRACT_CAST_PROMPT,
|
||||
[("출연진 구간:", to_data_uri(section.image, CAST_IMAGE_MAX_SIZE))])
|
||||
except Exception:
|
||||
return CastExtraction(source="failed")
|
||||
names = [name.strip() for name in answer.cast if name.strip()][:MAX_NAMES]
|
||||
return CastExtraction(names=names, source="vlm")
|
||||
@@ -0,0 +1,83 @@
|
||||
"""① fetch — NOL 티켓(인터파크) 상품 페이지에서 포스터·상세 이미지·메타를 수집한다.
|
||||
|
||||
상품 페이지가 Next.js SSR이라 첫 HTML 안에 상품 JSON과 상세 소개 HTML이 통째로 들어 있어
|
||||
브라우저 없이 정적으로 뽑는다.
|
||||
|
||||
meta를 못 읽으면 상품페이지 구조가 바뀌었거나 goodsId가 틀렸다는 뜻이라 즉시 실패한다.
|
||||
"""
|
||||
import asyncio
|
||||
import re
|
||||
|
||||
import httpx
|
||||
|
||||
from app.p2v.schemas.nol import FetchedImage, NolMeta, NolProduct
|
||||
from app.p2v.utils.image import sniff_extension
|
||||
|
||||
PRODUCT_URL = "https://nol.yanolja.com/ticket/products/{goods_id}"
|
||||
USER_AGENT = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/120 Safari/537.36")
|
||||
|
||||
# 상품 JSON에서 뽑을 키. NolMeta의 alias와 같아야 한다.
|
||||
META_KEYS = ("goodsName", "placeName", "playStartDate", "playEndDate", "runningTime",
|
||||
"interMissionTime", "viewRateName", "genreName", "subGenreName",
|
||||
"corporationName", "posterImageUrl", "bookingOpenTime")
|
||||
|
||||
# 배우 프로필 썸네일·공연장 사진은 영상 소재가 아니다
|
||||
SKIP_PATTERN = re.compile(r"PlayDictionary|Play/Place/|favicon|yaimg\.yanolja")
|
||||
POSTER_PATH = "/Play/image/large/"
|
||||
DETAIL_IMG_PATTERN = re.compile(
|
||||
r'<img[^>]+src="(https?://ticketimage\.interpark\.com/[^"]+)"')
|
||||
|
||||
def parse_product(html: str, goods_id: str) -> NolMeta:
|
||||
unescaped = html.replace("\\u0026", "&").replace('\\"', '"').replace("\\/", "/")
|
||||
raw: dict = {}
|
||||
for key in META_KEYS:
|
||||
found = re.search(key + r'":"([^"]*)"', unescaped)
|
||||
raw[key] = found.group(1) if found else None
|
||||
price = re.search(r'"price":(\d+)', unescaped)
|
||||
|
||||
seen: set[str] = set()
|
||||
detail_urls = []
|
||||
for url in DETAIL_IMG_PATTERN.findall(unescaped): # 등장 순서 유지, 중복 제거
|
||||
if SKIP_PATTERN.search(url) or POSTER_PATH in url or url in seen:
|
||||
continue
|
||||
seen.add(url)
|
||||
detail_urls.append(url.replace("http://", "https://"))
|
||||
|
||||
return NolMeta(goods_id=goods_id, url=PRODUCT_URL.format(goods_id=goods_id),
|
||||
min_price=int(price.group(1)) if price else None,
|
||||
detail_image_urls=detail_urls, **raw)
|
||||
|
||||
|
||||
async def download(client: httpx.AsyncClient, url: str) -> FetchedImage | None:
|
||||
try:
|
||||
response = await client.get(url)
|
||||
response.raise_for_status()
|
||||
except httpx.HTTPError:
|
||||
return None
|
||||
if not response.content:
|
||||
return None
|
||||
return FetchedImage(url=url, data=response.content,
|
||||
extension=sniff_extension(response.content))
|
||||
|
||||
|
||||
async def fetch_product(goods_id: str) -> NolProduct:
|
||||
async with httpx.AsyncClient(timeout=90, follow_redirects=True,
|
||||
headers={"User-Agent": USER_AGENT}) as client:
|
||||
page = await client.get(PRODUCT_URL.format(goods_id=goods_id))
|
||||
page.raise_for_status()
|
||||
meta = parse_product(page.text, goods_id)
|
||||
if not meta.goods_name:
|
||||
raise RuntimeError(f"상품 정보를 못 읽었다 (goodsId={goods_id}) — "
|
||||
"페이지 구조가 바뀌었거나 id가 틀렸다")
|
||||
|
||||
poster = (await download(client, meta.poster_image_url)
|
||||
if meta.poster_image_url else None)
|
||||
details = await asyncio.gather(
|
||||
*(download(client, url) for url in meta.detail_image_urls))
|
||||
|
||||
return NolProduct(
|
||||
meta=meta, poster=poster,
|
||||
details=[image for image in details if image],
|
||||
failed_urls=[url for url, image in zip(meta.detail_image_urls, details, strict=True)
|
||||
if image is None])
|
||||
@@ -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 app.p2v.schemas.hybrid import HybridResult, LayerConfig, Rect
|
||||
from app.p2v.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_frames 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)
|
||||
@@ -0,0 +1,75 @@
|
||||
"""⑥ i2v — 포스터 + 모션 프롬프트 → 생성형 애니메이션 클립.
|
||||
|
||||
생성 전에 계정 가드와 저해상 거절, 생성 후에 제목 훼손 게이트가 붙는다.
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
from PIL import Image
|
||||
|
||||
from app.p2v.schemas.detect import Regions
|
||||
from app.p2v.schemas.i2v import I2vResult, TitleGateVerdict
|
||||
from app.p2v.services.title_gate import check_title
|
||||
from config import p2v_settings
|
||||
from app.p2v.utils.higgsfield import (KLING_3_0, assert_account, parse_credits, parse_result_url,
|
||||
run_cli)
|
||||
|
||||
VEO_QUALITY = "high" # veo 전용
|
||||
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 == KLING_3_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 = KLING_3_0) -> 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 | None = None, *,
|
||||
model: str = KLING_3_0,
|
||||
max_credits: float = MAX_CREDITS) -> I2vResult:
|
||||
if not prompt.strip():
|
||||
raise ValueError("i2v 프롬프트가 비어 있다 — motion 단계를 먼저 돌릴 것")
|
||||
reject_low_resolution(poster)
|
||||
await assert_account(p2v_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 regions
|
||||
else TitleGateVerdict(passed=True, skip="regions 없음 — 제목 게이트 미실행"))
|
||||
if not verdict.passed:
|
||||
raise RuntimeError(f"제목 훼손 감지 — {verdict.reason} "
|
||||
"(재렌더하거나 모션 요소를 줄여보세요)")
|
||||
return I2vResult(clip=clip, credits=credits, model=model, title_gate=verdict)
|
||||
@@ -0,0 +1,85 @@
|
||||
"""③ motion — 포스터에서 움직일 요소를 골라 i2v 프롬프트를 만든다.
|
||||
|
||||
모션 어휘를 카탈로그로 나열하면 모델이 포스터에 없는 관람차까지 그려 넣으므로,
|
||||
무엇이 있는지만 VLM에게 묻고 어떻게 움직이는지는 검증된 문구로 고정한다.
|
||||
"""
|
||||
from pathlib import Path
|
||||
from typing import get_args
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from app.p2v.answers.motion_answer import MotionAnswer, MotionElement, MotionKey
|
||||
from app.p2v.schemas.motion import DroppedMotion, MotionItem, MotionPlan
|
||||
from config import apikey_settings
|
||||
from app.p2v.utils.common_llm import StructuredLLM
|
||||
from app.p2v.utils.image import to_data_uri
|
||||
from app.p2v.utils.prompt import load_prompt, load_prompt_json
|
||||
from app.p2v.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", apikey_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)
|
||||
@@ -0,0 +1,86 @@
|
||||
"""② narration_text — 나레이션 3문장 + voice + BGM 스타일 + 메타태그.
|
||||
|
||||
상류 오독을 프롬프트에 넣으면 하류가 이미지를 다시 보지 않고 베껴 쓰므로,
|
||||
앞 단계가 읽은 글자 대신 좌표만 넘기고 글자는 확대 크롭에서 직접 읽게 한다.
|
||||
"""
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.p2v.answers.narration_answer import NarrationAnswer
|
||||
from app.p2v.schemas.detect import Box, Regions
|
||||
from config import apikey_settings
|
||||
from app.p2v.utils.common_llm import StructuredLLM
|
||||
from app.p2v.utils.image import to_data_uri
|
||||
from app.p2v.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", apikey_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)
|
||||
@@ -0,0 +1,36 @@
|
||||
"""⑥ narration — 롱컷 나레이션 7문장.
|
||||
|
||||
축제 3문장이 VLM 생성인 것과 달리 여기는 meta에서 채우는 고정 슬롯이다.
|
||||
캐스팅 스케줄 문장은 예매 전에 확인하는 정보라 빠지면 안 된다.
|
||||
"""
|
||||
from app.p2v.schemas.cast import CastExtraction
|
||||
from app.p2v.schemas.narration_slots import NARRATION_SLOTS, NarrationLine, SlotNarration
|
||||
from app.p2v.schemas.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)])
|
||||
@@ -0,0 +1,90 @@
|
||||
"""공개된 P2V 콘텐츠 조회 — 좋아요·댓글·공유·공개 상세가 같은 기준을 쓴다.
|
||||
|
||||
공개 = 완료(done) + 삭제되지 않음 + 영상 URL 있음. 이 조건이 갈라지면
|
||||
목록에는 보이는데 좋아요·공유는 404 인 콘텐츠가 생긴다.
|
||||
"""
|
||||
from sqlalchemy import Select, func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database.like_cache import (
|
||||
get_like_count,
|
||||
is_user_liked,
|
||||
set_like_count,
|
||||
)
|
||||
from app.p2v.constants import JOB_TYPE_PLAYREEL, JOB_TYPE_VIDEO
|
||||
from app.p2v.models import PlayreelTask, PosterAliveTask
|
||||
from app.p2v.worker.playreel import thumbnail_url as playreel_thumbnail_url
|
||||
from app.video.models import VideoReaction
|
||||
|
||||
#: 콘텐츠 종류 → 잡 테이블 모델. 종류 문자열은 like_cache 의 ctype 과 같다
|
||||
MODELS = {
|
||||
JOB_TYPE_VIDEO: PosterAliveTask,
|
||||
JOB_TYPE_PLAYREEL: PlayreelTask,
|
||||
}
|
||||
|
||||
P2V_TYPES = tuple(MODELS)
|
||||
|
||||
#: 종류 → video_reaction 에서 이 종류가 쓰는 대상 컬럼
|
||||
REACTION_COLUMN = {
|
||||
JOB_TYPE_VIDEO: VideoReaction.p2v_video_id,
|
||||
JOB_TYPE_PLAYREEL: VideoReaction.p2v_playreel_id,
|
||||
}
|
||||
|
||||
|
||||
def _public_conditions(model, content_id: int) -> list:
|
||||
return [
|
||||
model.id == content_id,
|
||||
model.status == "done",
|
||||
model.is_deleted.is_(False),
|
||||
model.video_url.is_not(None),
|
||||
model.video_url != "",
|
||||
]
|
||||
|
||||
|
||||
def public_exists_query(ctype: str, content_id: int) -> Select:
|
||||
"""이 종류의 공개 콘텐츠 한 건을 id 로 찾는 쿼리(존재 확인용)."""
|
||||
model = MODELS[ctype]
|
||||
return select(model.id).where(*_public_conditions(model, content_id))
|
||||
|
||||
|
||||
async def fetch_public(session: AsyncSession, ctype: str, content_id: int):
|
||||
"""공개 콘텐츠 행. 없거나 비공개면 None."""
|
||||
model = MODELS[ctype]
|
||||
return (
|
||||
await session.execute(select(model).where(*_public_conditions(model, content_id)))
|
||||
).scalar_one_or_none()
|
||||
|
||||
|
||||
def poster_of(ctype: str, row) -> str | None:
|
||||
"""무빙 포스터는 컬럼에, 롱컷은 정해진 경로에 썸네일이 있다."""
|
||||
return row.thumbnail_url if ctype == JOB_TYPE_VIDEO else playreel_thumbnail_url(row)
|
||||
|
||||
|
||||
async def like_state(
|
||||
session: AsyncSession, ctype: str, content_id: int, user_uuid: str | None
|
||||
) -> tuple[int, bool]:
|
||||
"""(좋아요 수, 내 좋아요 여부). Redis 우선, 미스면 DB 로 보정하고 캐시를 채운다."""
|
||||
column = REACTION_COLUMN[ctype]
|
||||
like_count = await get_like_count(content_id, ctype=ctype)
|
||||
if like_count is None:
|
||||
like_count = (
|
||||
await session.execute(
|
||||
select(func.count(VideoReaction.id)).where(column == content_id)
|
||||
)
|
||||
).scalar() or 0
|
||||
await set_like_count(content_id, like_count, ctype=ctype)
|
||||
|
||||
if not user_uuid:
|
||||
return like_count, False
|
||||
cached = await is_user_liked(content_id, user_uuid, ctype=ctype)
|
||||
if cached is not None:
|
||||
return like_count, cached
|
||||
# user-set 콜드 미스 — 응답 정확성만 필요하므로 DB 존재 확인으로 대체한다
|
||||
liked = (
|
||||
await session.execute(
|
||||
select(VideoReaction.id).where(
|
||||
column == content_id, VideoReaction.user_uuid == user_uuid
|
||||
)
|
||||
)
|
||||
).scalar_one_or_none() is not None
|
||||
return like_count, liked
|
||||
@@ -0,0 +1,278 @@
|
||||
"""⑦ 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 app.p2v.schemas.render import RenderResult
|
||||
from app.p2v.schemas.tts import NarrationTimeline
|
||||
from app.p2v.utils.audio import SAMPLE_RATE, apply_limiter, decode_audio, decode_mp3
|
||||
from app.p2v.utils.image import bar_box, content_box, logo_bar, round_mask
|
||||
from app.p2v.utils.qr import qr_box, qr_card
|
||||
from app.p2v.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_OVERFLOW_TOLERANCE = 1 / FPS
|
||||
|
||||
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 + NARRATION_OVERFLOW_TOLERANCE:
|
||||
raise RuntimeError(f"나레이션이 {timeline.cues[-1].end:.3f}초로 영상 {duration:.3f}초를 "
|
||||
"넘는다 — 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)
|
||||
@@ -0,0 +1,150 @@
|
||||
"""② split — 상세페이지 롱이미지를 섹션 조각으로 자르고 태깅한다.
|
||||
|
||||
공지·이벤트·스틸·시놉시스·캐스트·스케줄이 한 장(세로 수천~1만px)에 세로로 붙어 있어
|
||||
영상 씬으로 쓰려면 잘라야 한다.
|
||||
|
||||
경계는 대개 한 색으로 균일한 가로 띠라, 행마다 표준편차를 재서 균일한 행이 gap_min 이상
|
||||
이어지면 경계로 본다. 검정 배경처럼 배경 자체가 균일하면 구분이 약해지므로 그 띠 안에서
|
||||
좌우 끝 색이 바뀌는 지점을 우선한다.
|
||||
"""
|
||||
import asyncio
|
||||
import io
|
||||
from collections.abc import Sequence
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
from app.p2v.answers.detail_section_tag_answer import DetailSectionTagAnswer
|
||||
from app.p2v.schemas.detail_section import UNTAGGED, DetailSection, DetailSplitResult
|
||||
from config import apikey_settings
|
||||
from app.p2v.utils.common_llm import StructuredLLM
|
||||
from app.p2v.utils.image import to_data_uri
|
||||
from app.p2v.utils.prompt import load_prompt
|
||||
|
||||
Image.MAX_IMAGE_PIXELS = None
|
||||
|
||||
UNIFORM_STD_THRESHOLD = 6.0 # 행 내 RGB 표준편차가 이 아래면 '한 색'으로 본다
|
||||
DEFAULT_GAP_MIN = 40 # 경계로 볼 균일 띠 최소 높이
|
||||
DEFAULT_MIN_HEIGHT = 260 # 조각 최소 높이. 미만이면 앞 조각에 병합
|
||||
COLOUR_SHIFT_THRESHOLD = 30 # 균일 띠 안에서 배경색이 바뀌었다고 볼 차이
|
||||
TRIM_KEEP_PX = 12 # 조각 위아래에 남길 여백
|
||||
|
||||
SHEET_TILE_W = 180
|
||||
SHEET_TILE_MAX_H = 900
|
||||
SHEET_MAX_COLS = 14
|
||||
SHEET_GAP = 8
|
||||
TAG_IMAGE_MAX_SIZE = (360, 1200)
|
||||
|
||||
DETAIL_SECTION_TAG_PROMPT = load_prompt("detail_section_tag")
|
||||
|
||||
detail_section_llm = StructuredLLM("gpt-4o", apikey_settings.CHATGPT_API_KEY)
|
||||
|
||||
|
||||
def uniform_rows(pixels: np.ndarray, threshold: float = UNIFORM_STD_THRESHOLD) -> np.ndarray:
|
||||
"""각 행이 한 색에 가까운지."""
|
||||
return pixels.std(axis=1).max(axis=1) <= threshold
|
||||
|
||||
|
||||
def split_bounds(image: Image.Image, gap_min: int = DEFAULT_GAP_MIN,
|
||||
min_height: int = DEFAULT_MIN_HEIGHT) -> list[tuple[int, int]]:
|
||||
pixels = np.asarray(image.convert("RGB")).astype(np.float32)
|
||||
height = pixels.shape[0]
|
||||
uniform = uniform_rows(pixels)
|
||||
|
||||
cuts = []
|
||||
y = 0
|
||||
while y < height:
|
||||
if not uniform[y]:
|
||||
y += 1
|
||||
continue
|
||||
band_start = y
|
||||
while y < height and uniform[y]:
|
||||
y += 1
|
||||
if y - band_start < gap_min:
|
||||
continue
|
||||
# 경계는 여백 한가운데. 여백 안에서 배경색이 바뀌면 그 지점을 우선한다
|
||||
edge = pixels[band_start:y, 0, :]
|
||||
shift = np.abs(np.diff(edge, axis=0)).sum(axis=1)
|
||||
peak = int(shift.argmax())
|
||||
cuts.append(band_start + peak + 1 if shift[peak] > COLOUR_SHIFT_THRESHOLD
|
||||
else (band_start + y) // 2)
|
||||
|
||||
bounds = []
|
||||
previous = 0
|
||||
for cut in cuts + [height]:
|
||||
if cut - previous >= min_height:
|
||||
bounds.append((previous, cut))
|
||||
previous = cut
|
||||
if previous < height:
|
||||
# 남은 꼬리는 마지막 조각에 붙인다 — 얇은 구분선 때문에 쪼개지는 것을 막는다
|
||||
if bounds:
|
||||
bounds[-1] = (bounds[-1][0], height)
|
||||
else:
|
||||
bounds.append((0, height))
|
||||
return bounds
|
||||
|
||||
|
||||
def trim_uniform(image: Image.Image, keep: int = TRIM_KEEP_PX) -> Image.Image:
|
||||
"""조각 위아래의 균일 여백을 keep px만 남기고 걷어낸다."""
|
||||
uniform = uniform_rows(np.asarray(image.convert("RGB")).astype(np.float32))
|
||||
content = np.where(~uniform)[0]
|
||||
if len(content) == 0:
|
||||
return image
|
||||
top = max(0, content[0] - keep)
|
||||
bottom = min(image.height, content[-1] + 1 + keep)
|
||||
return image.crop((0, top, image.width, bottom))
|
||||
|
||||
|
||||
def contact_sheet(sections: Sequence[DetailSection]) -> Image.Image:
|
||||
"""조각을 폭 180으로 줄여 타일로 붙인다. 긴 조각은 900px 단위로 끊는다."""
|
||||
tiles = []
|
||||
for section in sections:
|
||||
scaled = section.image.resize(
|
||||
(SHEET_TILE_W, max(1, round(section.image.height * SHEET_TILE_W
|
||||
/ section.image.width))))
|
||||
for top in range(0, scaled.height, SHEET_TILE_MAX_H):
|
||||
tiles.append(scaled.crop((0, top, SHEET_TILE_W,
|
||||
min(top + SHEET_TILE_MAX_H, scaled.height))))
|
||||
if not tiles:
|
||||
return Image.new("RGB", (SHEET_TILE_W, SHEET_TILE_MAX_H), "white")
|
||||
|
||||
cols = min(len(tiles), SHEET_MAX_COLS)
|
||||
rows = (len(tiles) + cols - 1) // cols
|
||||
sheet = Image.new("RGB", (cols * (SHEET_TILE_W + SHEET_GAP),
|
||||
rows * (SHEET_TILE_MAX_H + SHEET_GAP)), "white")
|
||||
for order, tile in enumerate(tiles):
|
||||
sheet.paste(tile, ((order % cols) * (SHEET_TILE_W + SHEET_GAP),
|
||||
(order // cols) * (SHEET_TILE_MAX_H + SHEET_GAP)))
|
||||
return sheet
|
||||
|
||||
|
||||
async def tag_section(section: DetailSection) -> str:
|
||||
"""태깅 실패가 분할을 막지 않도록 실패는 untagged로 흘린다."""
|
||||
try:
|
||||
answer = await detail_section_llm.ask_with_images(
|
||||
DetailSectionTagAnswer, DETAIL_SECTION_TAG_PROMPT,
|
||||
[("조각:", to_data_uri(section.image, TAG_IMAGE_MAX_SIZE))], detail="low")
|
||||
except Exception:
|
||||
return UNTAGGED
|
||||
return answer.tag
|
||||
|
||||
|
||||
async def split_details(details: Sequence[bytes | Image.Image], *, tag: bool = True,
|
||||
gap_min: int = DEFAULT_GAP_MIN,
|
||||
min_height: int = DEFAULT_MIN_HEIGHT) -> DetailSplitResult:
|
||||
sections: list[DetailSection] = []
|
||||
for order, detail in enumerate(details, 1):
|
||||
image = (Image.open(io.BytesIO(detail)) if isinstance(detail, bytes)
|
||||
else detail).convert("RGB")
|
||||
source = f"detail_{order:02d}"
|
||||
for index, (y0, y1) in enumerate(split_bounds(image, gap_min, min_height), 1):
|
||||
piece = trim_uniform(image.crop((0, y0, image.width, y1)))
|
||||
sections.append(DetailSection(source=source, index=index, y0=y0, y1=y1,
|
||||
image=piece))
|
||||
|
||||
if tag:
|
||||
tags = await asyncio.gather(*(tag_section(section) for section in sections))
|
||||
for section, resolved in zip(sections, tags, strict=True):
|
||||
section.tag = resolved
|
||||
|
||||
return DetailSplitResult(sections=sections, sheet=contact_sheet(sections))
|
||||
Whitespace-only changes.
@@ -0,0 +1,126 @@
|
||||
"""스타일링 ③ — 생성된 포스터 하단에 정보 밴드를 그린다
|
||||
|
||||
큰 제목은 생성 모델이 대체로 맞추지만 작은 글자에서 자모를 흘린다
|
||||
(동대문구 → 몽대문구, 체험존 → 채헐존). 프롬프트로는 더 못 밀어낸다.
|
||||
그래서 날짜·시간·장소는 모델에 맡기지 않고 실제 폰트로 직접 그린다.
|
||||
|
||||
밴드 색은 이미지 하단에서 뽑아 얹은 티를 줄인다.
|
||||
"""
|
||||
from PIL import Image, ImageDraw, ImageFilter, ImageFont
|
||||
|
||||
from app.p2v.answers.poster_text_answer import PosterTextAnswer
|
||||
from app.p2v.utils.font import font
|
||||
|
||||
PAD_RATIO = 0.055
|
||||
BAND_RATIO_WITH_SLOGAN = 0.165
|
||||
BAND_RATIO = 0.13
|
||||
FEATHER_RATIO = 0.42
|
||||
FEATHER_CURVE = 1.4
|
||||
FEATHER_BLUR = 3
|
||||
|
||||
DARK_LUMINANCE = 118 # 이보다 어두우면 밝은 글자를 얹는다
|
||||
DARK_BACKGROUND_GAIN = 0.42
|
||||
LIGHT_BACKGROUND_GAIN, LIGHT_BACKGROUND_LIFT = 1.06, 26
|
||||
LIGHT_INK = (245, 243, 238)
|
||||
DARK_INK = (26, 24, 22)
|
||||
|
||||
MIN_FONT_SIZE = 12
|
||||
FONT_STEP = 2
|
||||
ROW_GAP_RATIO = 0.085
|
||||
|
||||
QUOTE_MARKS = '"“”'
|
||||
|
||||
|
||||
def band_palette(image: Image.Image, band_top: int) -> tuple[tuple, tuple]:
|
||||
"""밴드 배경색과 글자색을 이미지 하단 평균색에서 뽑는다"""
|
||||
width, height = image.size
|
||||
strip = image.crop((0, band_top, width, height)).resize((1, 1), Image.LANCZOS)
|
||||
red, green, blue = strip.getpixel((0, 0))[:3]
|
||||
luminance = 0.299 * red + 0.587 * green + 0.114 * blue
|
||||
|
||||
if luminance < DARK_LUMINANCE:
|
||||
background = tuple(int(channel * DARK_BACKGROUND_GAIN)
|
||||
for channel in (red, green, blue))
|
||||
return background, LIGHT_INK
|
||||
background = tuple(min(255, int(channel * LIGHT_BACKGROUND_GAIN + LIGHT_BACKGROUND_LIFT))
|
||||
for channel in (red, green, blue))
|
||||
return background, DARK_INK
|
||||
|
||||
|
||||
def fit_font(draw: ImageDraw.ImageDraw, text: str, weight: str, max_width: int,
|
||||
start_size: int) -> ImageFont.FreeTypeFont:
|
||||
"""max_width 안에 들어가는 가장 큰 크기를 찾는다"""
|
||||
size = start_size
|
||||
while size > MIN_FONT_SIZE:
|
||||
candidate = font(weight, size)
|
||||
if draw.textlength(text, font=candidate) <= max_width:
|
||||
return candidate
|
||||
size -= FONT_STEP
|
||||
return font(weight, MIN_FONT_SIZE)
|
||||
|
||||
|
||||
def band_rows(text: PosterTextAnswer, band_height: int) -> list[tuple[str, str, int, float]]:
|
||||
"""슬로건 → 날짜+시간 → 장소 순. 날짜를 가장 크게 잡는다
|
||||
|
||||
슬로건은 원래 제목 근처에 놓이는 문구지만 생성 결과의 제목 위치가 매번 달라
|
||||
상단에 얹으면 아트워크와 부딪힌다. 밴드 첫 줄로 내려 항상 읽히게 한다.
|
||||
"""
|
||||
slogan = text.slogan.strip().strip(QUOTE_MARKS)
|
||||
datetime_line = text.date.strip() + (f" {text.time.strip()}" if text.time.strip() else "")
|
||||
|
||||
rows = []
|
||||
if slogan:
|
||||
rows.append((f"“{slogan}”", "SemiBold", round(band_height * 0.20), 0.72))
|
||||
if datetime_line:
|
||||
rows.append((datetime_line, "Bold", round(band_height * 0.33), 1.0))
|
||||
if text.place.strip():
|
||||
rows.append((text.place.strip(), "SemiBold", round(band_height * 0.21), 0.92))
|
||||
return rows
|
||||
|
||||
|
||||
def paint_scrim(image: Image.Image, band_top: int, band_height: int,
|
||||
background: tuple) -> None:
|
||||
"""위쪽 경계가 칼같이 잘리면 얹은 티가 난다. 그라데이션으로 이어 붙인다"""
|
||||
width = image.width
|
||||
scrim = Image.new("RGB", (width, band_height), background)
|
||||
mask = Image.new("L", (width, band_height), 255)
|
||||
mask_draw = ImageDraw.Draw(mask)
|
||||
feather = round(band_height * FEATHER_RATIO)
|
||||
for row in range(feather):
|
||||
mask_draw.line([(0, row), (width, row)],
|
||||
fill=int(255 * (row / feather) ** FEATHER_CURVE))
|
||||
image.paste(scrim, (0, band_top), mask.filter(ImageFilter.GaussianBlur(FEATHER_BLUR)))
|
||||
|
||||
|
||||
def compose_info_band(poster: Image.Image, text: PosterTextAnswer) -> Image.Image | None:
|
||||
"""밴드를 얹은 이미지를 돌려준다. 그릴 내용이 없으면 None"""
|
||||
if not (text.date.strip() or text.place.strip()):
|
||||
return None
|
||||
|
||||
image = poster.convert("RGB")
|
||||
width, height = image.size
|
||||
band_height = round(height * (BAND_RATIO_WITH_SLOGAN if text.slogan.strip()
|
||||
else BAND_RATIO))
|
||||
band_top = height - band_height
|
||||
background, ink = band_palette(image, band_top)
|
||||
paint_scrim(image, band_top, band_height, background)
|
||||
|
||||
draw = ImageDraw.Draw(image)
|
||||
inner_width = width - round(width * PAD_RATIO) * 2
|
||||
rows = band_rows(text, band_height)
|
||||
fitted = [(line, fit_font(draw, line, weight, inner_width, size), opacity)
|
||||
for line, weight, size, opacity in rows]
|
||||
|
||||
gap = round(band_height * ROW_GAP_RATIO)
|
||||
heights = [chosen.getbbox(line)[3] - chosen.getbbox(line)[1]
|
||||
for line, chosen, _ in fitted]
|
||||
top = band_top + (band_height - (sum(heights) + gap * (len(fitted) - 1))) // 2 \
|
||||
- round(band_height * 0.03)
|
||||
|
||||
for (line, chosen, opacity), line_height in zip(fitted, heights, strict=True):
|
||||
colour = ink if opacity >= 1.0 else tuple(
|
||||
round(channel * opacity + background[index] * (1 - opacity))
|
||||
for index, channel in enumerate(ink))
|
||||
draw.text((width // 2, top), line, font=chosen, fill=colour, anchor="ma")
|
||||
top += line_height + gap
|
||||
return image
|
||||
@@ -0,0 +1,37 @@
|
||||
"""스타일링 ① — 포스터에 인쇄된 글자를 읽는다
|
||||
|
||||
이미지 생성 모델은 한글을 다시 그리며 자모를 바꾼다(맥주축제 → 백주축제).
|
||||
프롬프트로는 못 막으므로 읽기를 먼저 하고 그 문자열을 생성 프롬프트에 못 박는다.
|
||||
"""
|
||||
from PIL import Image
|
||||
|
||||
from app.p2v.answers.poster_text_answer import PosterTextAnswer
|
||||
from config import apikey_settings
|
||||
from app.p2v.utils.common_llm import StructuredLLM
|
||||
from app.p2v.utils.image import to_data_uri
|
||||
from app.p2v.utils.prompt import load_prompt
|
||||
|
||||
# 자모가 보일 만큼은 키워서 넣는다
|
||||
MIN_LONG_EDGE = 1400
|
||||
MAX_SIZE = (1536, 1536)
|
||||
|
||||
POSTER_TEXT_PROMPT = load_prompt("poster_text")
|
||||
|
||||
poster_text_llm = StructuredLLM("gpt-4o", apikey_settings.CHATGPT_API_KEY)
|
||||
|
||||
|
||||
def readable_copy(poster: Image.Image) -> Image.Image:
|
||||
source = poster.convert("RGB")
|
||||
if max(source.size) < MIN_LONG_EDGE:
|
||||
scale = MIN_LONG_EDGE / max(source.size)
|
||||
source = source.resize((round(source.width * scale), round(source.height * scale)),
|
||||
Image.LANCZOS)
|
||||
source.thumbnail(MAX_SIZE, Image.LANCZOS)
|
||||
return source
|
||||
|
||||
|
||||
async def read_poster_text(poster: Image.Image) -> PosterTextAnswer:
|
||||
image = readable_copy(poster)
|
||||
return await poster_text_llm.ask_with_images(
|
||||
PosterTextAnswer, POSTER_TEXT_PROMPT, [("포스터", to_data_uri(image))],
|
||||
temperature=0.1)
|
||||
@@ -0,0 +1,57 @@
|
||||
"""스타일링 ② — 레퍼런스 이미지에서 화풍 명세를 뽑는다
|
||||
|
||||
번들 템플릿 빌드와 사용자 업로드가 같은 경로를 탄다.
|
||||
둘이 갈라지면 사용자 템플릿만 품질이 떨어지고 원인을 찾기 어려워진다.
|
||||
"""
|
||||
import io
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from app.p2v.answers.style_prompt_answer import StylePromptAnswer
|
||||
from app.p2v.schemas.styling import ReferenceVariants
|
||||
from config import apikey_settings
|
||||
from app.p2v.utils.common_llm import StructuredLLM
|
||||
from app.p2v.utils.image import to_data_uri
|
||||
from app.p2v.utils.prompt import load_prompt
|
||||
|
||||
REFERENCE_LONG_EDGE = 2400 # 붓질이 보이는 최소선
|
||||
THUMBNAIL_LONG_EDGE = 600 # 화면 카드
|
||||
VISION_SIZE = (1536, 1536)
|
||||
SMALL_REFERENCE_WARN = 600 # 이보다 작으면 결과가 나빠진다. 막지는 않는다
|
||||
|
||||
REFERENCE_QUALITY = 92
|
||||
THUMBNAIL_QUALITY = 88
|
||||
|
||||
STYLE_PROMPT_PROMPT = load_prompt("style_prompt")
|
||||
|
||||
style_llm = StructuredLLM("gpt-4o", apikey_settings.CHATGPT_API_KEY)
|
||||
|
||||
|
||||
def encode(image: Image.Image, quality: int) -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
image.save(buffer, "JPEG", quality=quality, optimize=True)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def build_variants(raw: bytes) -> ReferenceVariants:
|
||||
"""올린 바이트에서 전이용 고해상본과 카드용 썸네일을 만든다"""
|
||||
Image.MAX_IMAGE_PIXELS = None
|
||||
source = Image.open(io.BytesIO(raw)).convert("RGB")
|
||||
source.thumbnail((REFERENCE_LONG_EDGE, REFERENCE_LONG_EDGE), Image.LANCZOS)
|
||||
|
||||
thumbnail = source.copy()
|
||||
thumbnail.thumbnail((THUMBNAIL_LONG_EDGE, THUMBNAIL_LONG_EDGE), Image.LANCZOS)
|
||||
|
||||
return ReferenceVariants(reference=encode(source, REFERENCE_QUALITY),
|
||||
thumbnail=encode(thumbnail, THUMBNAIL_QUALITY),
|
||||
size=source.size)
|
||||
|
||||
|
||||
async def analyze_style(reference: bytes) -> str:
|
||||
Image.MAX_IMAGE_PIXELS = None
|
||||
image = Image.open(io.BytesIO(reference)).convert("RGB")
|
||||
|
||||
answer = await style_llm.ask_with_images(
|
||||
StylePromptAnswer, STYLE_PROMPT_PROMPT,
|
||||
[("레퍼런스", to_data_uri(image, VISION_SIZE))], temperature=0.2)
|
||||
return answer.style_prompt
|
||||
@@ -0,0 +1,144 @@
|
||||
"""스타일링 ④ — 포스터를 레퍼런스 화풍으로 다시 그린다
|
||||
|
||||
내부 검토용이다. 번들 레퍼런스의 권리가 남아 있어 결과물을 그대로 밖에 내지 않는다.
|
||||
"""
|
||||
import base64
|
||||
import io
|
||||
|
||||
import httpx
|
||||
from PIL import Image
|
||||
|
||||
from app.p2v.answers.poster_text_answer import PosterTextAnswer
|
||||
from app.p2v.schemas.styling import OutputFormat, StyleTemplate, TransferResult
|
||||
from app.p2v.services.styling.info_band import compose_info_band
|
||||
from app.p2v.services.styling.poster_text import read_poster_text
|
||||
from config import apikey_settings
|
||||
|
||||
IMAGES_EDIT_API = "https://api.openai.com/v1/images/edits"
|
||||
IMAGE_MODEL = "gpt-image-2" # gpt-image-1은 한글 제목 끝자를 흘렸다
|
||||
IMAGE_QUALITY = "high"
|
||||
REQUEST_TIMEOUT = httpx.Timeout(300.0, connect=10.0)
|
||||
|
||||
# gpt-image가 내는 크기로 생성한 뒤 필요하면 센터 크롭한다
|
||||
OUTPUT_FORMATS = (
|
||||
OutputFormat(id="poster", label="포스터 2:3", generated_size="1024x1536"),
|
||||
OutputFormat(id="story", label="스토리 9:16", generated_size="1024x1536",
|
||||
crop=(864, 1536)),
|
||||
OutputFormat(id="feed", label="피드 4:5", generated_size="1024x1536",
|
||||
crop=(1024, 1280)),
|
||||
OutputFormat(id="square", label="정방형 1:1", generated_size="1024x1024"),
|
||||
)
|
||||
FORMATS_BY_ID = {output.id: output for output in OUTPUT_FORMATS}
|
||||
|
||||
SQUARE_SIZE = "1024x1024"
|
||||
RESERVED_BOTTOM = "22%" # 정보 밴드가 들어갈 자리
|
||||
|
||||
# 성공한 프롬프트만 "그릴 수 있는 말"로 돼 있었다. 무드 형용사는 픽셀로 번역되지 않는다.
|
||||
# 또 하나 — 성공 사례는 스타일만 얹은 게 아니라 그 화법으로 장면을 다시 그렸다.
|
||||
TRANSFER_PROMPT = (
|
||||
"Redraw the first image as a brand-new movie-style poster, fully committing to the "
|
||||
"visual language described below. Do not merely apply a color filter — rebuild the "
|
||||
"illustration, lighting, texture and title lettering from scratch in that style.\n\n"
|
||||
"STYLE TO ADOPT: {style_prompt}\n\n"
|
||||
"KEEP FROM THE ORIGINAL: the event name and the subject matter of the artwork (what the "
|
||||
"event is about). The people, objects and scenery may be re-staged and re-drawn in the "
|
||||
"new style.\n\n"
|
||||
"{text_manifest}"
|
||||
"TEXT RULE: render Korean text sharp and legible. Do not swap visually similar jamo "
|
||||
"(ㅁ/ㅂ, ㅈ/ㅊ), do not drop trailing characters, and do not invent words. {orientation}"
|
||||
)
|
||||
|
||||
TITLE_MANIFEST = (
|
||||
"TEXT TO RENDER — the poster must contain exactly ONE piece of text, the main "
|
||||
"title, rendered character-for-character as written here. This is the correct "
|
||||
"reading; if the original image looks different, trust this line:\n"
|
||||
" Main title: 「{title}」\n"
|
||||
# 위치를 안 박으면 제목을 하단 예약 영역에 놓아 정보 밴드와 겹친다
|
||||
" Placement: put this title in the UPPER THIRD of the poster, near the top "
|
||||
"edge. It must not appear in the lower half.\n\n"
|
||||
)
|
||||
|
||||
# 작은 글자는 모델이 자모를 흘린다(주류 → 중류). 제목만 그리게 하고 나머지는 밴드로 얹는다.
|
||||
NO_OTHER_TEXT = (
|
||||
"DO NOT RENDER any other text. No tagline or slogan, no date, no time, no venue "
|
||||
"name, no programme or zone labels, no admission info, no phone numbers, no URLs, "
|
||||
"no organiser or sponsor credits, no logos with lettering. Apart from the single "
|
||||
f"title line the poster must be free of characters. Leave the bottom {RESERVED_BOTTOM} "
|
||||
"as artwork or background only — that area is reserved and will be filled in afterwards.\n\n"
|
||||
)
|
||||
|
||||
|
||||
def text_manifest(text: PosterTextAnswer) -> str:
|
||||
title = TITLE_MANIFEST.format(title=text.title) if text.title.strip() else ""
|
||||
return title + NO_OTHER_TEXT
|
||||
|
||||
|
||||
def build_prompt(template: StyleTemplate, text: PosterTextAnswer,
|
||||
output: OutputFormat) -> str:
|
||||
orientation = ("Square 1:1 poster." if output.generated_size == SQUARE_SIZE
|
||||
else "Vertical 2:3 poster.")
|
||||
return TRANSFER_PROMPT.format(style_prompt=template.style_prompt,
|
||||
text_manifest=text_manifest(text),
|
||||
orientation=orientation)
|
||||
|
||||
|
||||
def center_crop(image: Image.Image, size: tuple[int, int]) -> Image.Image:
|
||||
target_width, target_height = size
|
||||
scale = max(target_width / image.width, target_height / image.height)
|
||||
scaled = image.resize((round(image.width * scale), round(image.height * scale)),
|
||||
Image.LANCZOS)
|
||||
left = (scaled.width - target_width) // 2
|
||||
top = (scaled.height - target_height) // 2
|
||||
return scaled.crop((left, top, left + target_width, top + target_height))
|
||||
|
||||
|
||||
def encode_png(image: Image.Image) -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
image.save(buffer, "PNG")
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
async def request_edit(poster: bytes, reference: bytes, prompt: str,
|
||||
generated_size: str) -> bytes:
|
||||
files = [
|
||||
("image[]", ("poster.jpg", poster, "image/jpeg")),
|
||||
("image[]", ("reference.jpg", reference, "image/jpeg")),
|
||||
]
|
||||
data = {"model": IMAGE_MODEL, "prompt": prompt, "size": generated_size,
|
||||
"quality": IMAGE_QUALITY, "n": "1"}
|
||||
|
||||
async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client:
|
||||
response = await client.post(
|
||||
IMAGES_EDIT_API, files=files, data=data,
|
||||
headers={"Authorization": f"Bearer {apikey_settings.CHATGPT_API_KEY}"})
|
||||
if response.status_code != 200:
|
||||
raise RuntimeError(f"{IMAGE_MODEL} 호출 실패 {response.status_code}: "
|
||||
f"{response.text[:400]}")
|
||||
|
||||
items = response.json().get("data") or []
|
||||
if not items or not items[0].get("b64_json"):
|
||||
raise RuntimeError(f"{IMAGE_MODEL} 빈 응답 — 거절되었을 수 있다")
|
||||
return base64.b64decode(items[0]["b64_json"])
|
||||
|
||||
|
||||
async def transfer_style(poster: bytes, template: StyleTemplate, reference: bytes, *,
|
||||
format_id: str = "poster",
|
||||
text: PosterTextAnswer | None = None) -> TransferResult:
|
||||
output = FORMATS_BY_ID.get(format_id)
|
||||
if output is None:
|
||||
raise ValueError(f"미지의 format: {format_id!r} (허용: {list(FORMATS_BY_ID)})")
|
||||
|
||||
text = text or await read_poster_text(Image.open(io.BytesIO(poster)))
|
||||
prompt = build_prompt(template, text, output)
|
||||
generated = Image.open(io.BytesIO(
|
||||
await request_edit(poster, reference, prompt, output.generated_size)))
|
||||
|
||||
if output.crop:
|
||||
generated = center_crop(generated, output.crop)
|
||||
# 날짜·시간·장소는 모델이 안 그렸다. 실제 폰트로 얹는다
|
||||
with_band = compose_info_band(generated, text)
|
||||
|
||||
return TransferResult(image=encode_png(with_band or generated),
|
||||
format_id=output.id,
|
||||
style_prompt=template.style_prompt,
|
||||
has_info_band=with_band is not None)
|
||||
@@ -0,0 +1,124 @@
|
||||
"""⑥ 제목 훼손 게이트 — 픽셀 하드컷 + VLM 가독성 2단.
|
||||
|
||||
"파일이 존재하는가"만 보던 검증 탓에 구름이 제목을 덮은 클립이 검수대까지 간 적이 있다.
|
||||
픽셀 지표 하나로는 갈리지 않아서 — 영역 평균차는 제목 뒤 불꽃과 제목 위 구름을 구분 못 하고
|
||||
글리프 휘도차는 흰 구름이 흰 글자를 덮으면 0에 수렴한다 — 2단을 VLM 가독성 판정으로 둔다.
|
||||
|
||||
두 단 모두 첫 프레임을 기준으로 삼는다. detect가 읽은 제목 문자열과는 대조하지 않는다 —
|
||||
상자가 제목의 일부만 덮으면 잘려 나간 글자를 훼손으로 오인한다.
|
||||
"""
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
from app.p2v.answers.title_gate_answer import TitleGateAnswer
|
||||
from app.p2v.schemas.detect import Regions
|
||||
from app.p2v.schemas.i2v import FrameVerdict, TitleGateVerdict
|
||||
from config import apikey_settings
|
||||
from app.p2v.utils.common_llm import StructuredLLM
|
||||
from app.p2v.utils.image import content_box, to_data_uri
|
||||
from app.p2v.utils.prompt import load_prompt
|
||||
from app.p2v.utils.qr import otsu_threshold
|
||||
from app.p2v.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", apikey_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]) -> TitleGateAnswer:
|
||||
"""[0]이 기준이다. 옮겨 적은 제목과 대조하지 않는다 —
|
||||
detect가 읽은 글자와 detect가 잡은 상자가 어긋나면 그 차이를 훼손으로 오인한다."""
|
||||
images = [(f"[{index}] t={at}s{' (원본)' if index == 0 else ''}:",
|
||||
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"시점 {len(crops)}장. [0]을 기준으로 각 이미지를 순서대로 판정하라.",
|
||||
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)
|
||||
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
|
||||
|
||||
answer = await ask_legibility(crops, times)
|
||||
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)]
|
||||
# [0]은 원본이라 판정 대상이 아니다
|
||||
broken = [frame for frame in verdict.frames if not frame.legible and frame.index > 0]
|
||||
if broken:
|
||||
verdict.passed = False
|
||||
verdict.reason = "제목 가독 훼손: " + "; ".join(
|
||||
f"t={frame.time}s {frame.broken}" for frame in broken)
|
||||
return verdict
|
||||
@@ -0,0 +1,110 @@
|
||||
"""④ tts — 나레이션 음성 + 실측 타임라인.
|
||||
|
||||
영상 비트를 먼저 못 박고 음성을 우겨넣으면 말이 잘리거나 비므로, 문장별 실측 길이를
|
||||
먼저 재고 그 큐에 씬·카메라를 맞춘다. 트림·합성·인코딩까지 전부 메모리에서 처리한다.
|
||||
"""
|
||||
import asyncio
|
||||
|
||||
import httpx
|
||||
import numpy as np
|
||||
from openai import AsyncOpenAI
|
||||
|
||||
from app.p2v.schemas.tts import NarrationAudio, NarrationCue, NarrationTimeline, TypecastVoice
|
||||
from config import apikey_settings, p2v_settings
|
||||
from app.p2v.utils.audio import SAMPLE_RATE, decode_mp3, encode_mp3, trim_silence
|
||||
from app.p2v.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=apikey_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 p2v_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": p2v_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:
|
||||
# Typecast는 동시 요청에 429를 준다. 원본도 순차로 돈다.
|
||||
spoken = [await 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)),
|
||||
)
|
||||
@@ -0,0 +1,57 @@
|
||||
"""③ upscale — Topaz Text Refine 2배.
|
||||
|
||||
공개 채널의 공연 포스터는 전부 750px대라 그대로는 못 쓴다. Bytedance Upscale은 광선을
|
||||
재작화하고 글자에 없던 무늬를 그려서(MAE 13 vs 5) Text Refine만 쓴다.
|
||||
목적은 확대보다 GIF 128색 밴딩 해소다 — 밴딩이 남으면 생성 모델이 그것을 무늬로 읽는다.
|
||||
"""
|
||||
import io
|
||||
import tempfile
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
from PIL import Image
|
||||
|
||||
from app.p2v.schemas.upscale import UpscaleResult
|
||||
from config import p2v_settings
|
||||
from app.p2v.utils.higgsfield import (TOPAZ_IMAGE, TOPAZ_TEXT_REFINE, assert_account,
|
||||
parse_result_url, run_cli)
|
||||
|
||||
OUTPUT_WIDTH, OUTPUT_HEIGHT = 1500, 2000
|
||||
UPSCALE_CREDITS = 2
|
||||
CLI_TIMEOUT = 420
|
||||
MIN_IMAGE_BYTES = 10_000
|
||||
|
||||
|
||||
@contextmanager
|
||||
def as_png_path(image: bytes | Path):
|
||||
"""CLI의 --image가 파일 경로만 받으므로 임시 파일로 내린다.
|
||||
|
||||
NOL 포스터는 팔레트 GIF(모드 P)로 오는데 그대로 올리면 잡이 failed로 돌아온다.
|
||||
RGB PNG로 정규화해 보낸다.
|
||||
"""
|
||||
source = Image.open(image if isinstance(image, Path) else io.BytesIO(image))
|
||||
with tempfile.NamedTemporaryFile(suffix=".png") as handle:
|
||||
source.convert("RGB").save(handle, "PNG")
|
||||
handle.flush()
|
||||
yield Path(handle.name)
|
||||
|
||||
|
||||
async def upscale_poster(poster: bytes | Path) -> UpscaleResult:
|
||||
await assert_account(p2v_settings.HIGGSFIELD_ACCOUNT) # 크레딧 쓰기 전에
|
||||
|
||||
with as_png_path(poster) as source:
|
||||
output = await run_cli(
|
||||
"generate", "create", TOPAZ_IMAGE, "--image", str(source),
|
||||
"--output_width", str(OUTPUT_WIDTH), "--output_height", str(OUTPUT_HEIGHT),
|
||||
"--variant", TOPAZ_TEXT_REFINE, "--wait", "--wait-timeout", "4m", "--json",
|
||||
timeout=CLI_TIMEOUT)
|
||||
|
||||
async with httpx.AsyncClient(timeout=300, follow_redirects=True) as client:
|
||||
response = await client.get(parse_result_url(output))
|
||||
response.raise_for_status()
|
||||
if len(response.content) < MIN_IMAGE_BYTES:
|
||||
raise RuntimeError(f"업스케일 결과가 너무 작다 ({len(response.content)}바이트)")
|
||||
|
||||
return UpscaleResult(image=response.content, credits=UPSCALE_CREDITS,
|
||||
variant=TOPAZ_TEXT_REFINE)
|
||||
Reference in new issue
Block a user