테스트 파일 정리 및 일부 함수 재구조화, playreel analyze까지

This commit is contained in:
jaehwang committed 2026-09-07 14:27:59 +09:00
1 parent 5c84733a8b
commit 53f308eac2
35 files changed
+1019 -49

No files matched your search

+52
View File
@@ -0,0 +1,52 @@
"""④ analyze — 검수 게이트에 올릴 재료를 만든다.
여기서 사람이 움직일 요소를 확정하고, 그 승인이 14크레딧 지출을 확정한다.
실제 프롬프트는 ⑤ motion에서 사람이 고른 키로 다시 쓴다.
"""
import re
from pathlib import Path
from PIL import Image
from models.analysis import FixedLayer, MotionChoice, PosterAnalysis
from services.motion import plan_motion
from utils.higgsfield import KLING_3_0
from 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,
)
+2 -19
View File
@@ -12,7 +12,7 @@ from answers.detect_answer import DetectAnswer, GridBox
from models.detect import Box, DetectResult, Focal, Regions
from settings import settings
from utils.common_llm import StructuredLLM
from utils.image import to_data_uri
from utils.image import to_data_uri, vlm_grid_overlay
from utils.prompt import load_prompt
Image.MAX_IMAGE_PIXELS = None
@@ -27,23 +27,6 @@ DETECT_PROMPT = load_prompt("detect")
detect_llm = StructuredLLM("gpt-4o", settings.chatgpt_api_key)
def grid_overlay(poster: Image.Image) -> Image.Image:
overlay = poster.convert("RGB").copy()
width, height = overlay.size
draw = ImageDraw.Draw(overlay, "RGBA")
font = ImageFont.load_default(max(14, width // 55))
for row in range(1, 20):
y = int(height * row * 0.05)
draw.line([(0, y), (width, y)], fill=(255, 0, 80, 150), width=max(1, width // 700))
if row % 2 == 0:
draw.text((4, y + 2), f"{row * 5}", font=font, fill=(255, 255, 0, 255))
for col in range(1, 10):
x = int(width * col * 0.10)
draw.line([(x, 0), (x, height)], fill=(0, 220, 255, 130), width=max(1, width // 700))
draw.text((x + 3, 3), f"{col * 10}", font=font, fill=(0, 255, 255, 255))
return overlay
def check_overlay(poster: Image.Image, regions: dict[str, Box],
focal_points: list[Focal]) -> Image.Image:
overlay = poster.convert("RGB").copy()
@@ -105,7 +88,7 @@ async def detect(poster: Path | Image.Image) -> DetectResult:
work_image = source.copy()
work_image.thumbnail((WORK_WIDTH_PX, WORK_WIDTH_PX * 3), Image.LANCZOS)
grid_image = grid_overlay(work_image)
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)
+36
View File
@@ -0,0 +1,36 @@
"""② split 부속 — cast 태그 섹션에서 배우 이름을 읽는다.
NOL meta에는 출연진 필드가 아예 없어 상세페이지 이미지에서 읽는 수밖에 없다.
캐스트는 영상의 필수 재료가 아니므로 실패해도 멈추지 않고 source로 남긴다.
"""
from collections.abc import Sequence
from answers.cast_answer import CastAnswer
from models.cast import CastExtraction
from models.detail_section import DetailSection
from settings import settings
from utils.common_llm import StructuredLLM
from utils.image import to_data_uri
from 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", 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")
+83
View File
@@ -0,0 +1,83 @@
"""① fetch — NOL 티켓(인터파크) 상품 페이지에서 포스터·상세 이미지·메타를 수집한다.
상품 페이지가 Next.js SSR이라 첫 HTML 안에 상품 JSON과 상세 소개 HTML이 통째로 들어 있어
브라우저 없이 정적으로 뽑는다.
meta를 못 읽으면 상품페이지 구조가 바뀌었거나 goodsId가 틀렸다는 뜻이라 즉시 실패한다.
"""
import asyncio
import re
import httpx
from models.nol import FetchedImage, NolMeta, NolProduct
from 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])
+6 -7
View File
@@ -11,11 +11,10 @@ from models.detect import Regions
from models.i2v import I2vResult
from services.title_gate import check_title
from settings import settings
from utils.higgsfield import assert_account, parse_credits, parse_result_url, run_cli
from utils.higgsfield import (KLING_3_0, assert_account, parse_credits, parse_result_url,
run_cli)
# 프로덕션 표준은 Kling 3.0 pro. veo3_1은 저작권 콜백·실패 과금 사례로 제외.
DEFAULT_MODEL = "kling3_0"
VEO_QUALITY = "high"
VEO_QUALITY = "high" # veo 전용
CLIP_SECONDS = 8
ASPECT_RATIO = "9:16"
MAX_CREDITS = 60.0
@@ -35,19 +34,19 @@ def reject_low_resolution(poster: Path) -> None:
def cli_args(prompt: str, poster: Path, model: str) -> list[str]:
args = ["--prompt", prompt, "--start-image", str(poster),
"--duration", str(CLIP_SECONDS), "--aspect_ratio", ASPECT_RATIO]
if model == "kling3_0":
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 = DEFAULT_MODEL) -> float:
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, *,
model: str = DEFAULT_MODEL,
model: str = KLING_3_0,
max_credits: float = MAX_CREDITS) -> I2vResult:
if not prompt.strip():
raise ValueError("i2v 프롬프트가 비어 있다 — motion 단계를 먼저 돌릴 것")
+150
View File
@@ -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 answers.detail_section_tag_answer import DetailSectionTagAnswer
from models.detail_section import UNTAGGED, DetailSection, DetailSplitResult
from settings import settings
from utils.common_llm import StructuredLLM
from utils.image import to_data_uri
from utils.prompt import load_prompt
Image.MAX_IMAGE_PIXELS = None
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", 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))
+57
View File
@@ -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 models.upscale import UpscaleResult
from settings import settings
from 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(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)