diff --git a/backend/answers/cast_answer.py b/backend/answers/cast_answer.py new file mode 100644 index 0000000..000663b --- /dev/null +++ b/backend/answers/cast_answer.py @@ -0,0 +1,6 @@ +"""출연진 이름 수집 응답 스키마.""" +from pydantic import BaseModel + + +class CastAnswer(BaseModel): + cast: list[str] diff --git a/backend/answers/detail_section_tag_answer.py b/backend/answers/detail_section_tag_answer.py new file mode 100644 index 0000000..8502575 --- /dev/null +++ b/backend/answers/detail_section_tag_answer.py @@ -0,0 +1,16 @@ +"""② split 단계 — 상세페이지 섹션 분류 응답 스키마. + +호출 실패 시 쓰는 'untagged'는 어휘에 넣지 않는다 — 모델이 고를 값이 아니라 우리가 채우는 값이다. +""" +from typing import Literal + +from pydantic import BaseModel + +DetailSectionTag = Literal[ + "notice", "event", "keyvisual", "still", "synopsis", "cast", + "creative", "schedule", "discount", "crossbanner", "info", "fragment", +] + + +class DetailSectionTagAnswer(BaseModel): + tag: DetailSectionTag diff --git a/backend/models/analysis.py b/backend/models/analysis.py new file mode 100644 index 0000000..5ebee5d --- /dev/null +++ b/backend/models/analysis.py @@ -0,0 +1,31 @@ +from dataclasses import dataclass + +from PIL import Image +from pydantic import BaseModel + +from models.motion import MotionPlan + + +class MotionChoice(BaseModel): + """검수 화면의 토글 하나. on이 꺼진 것은 VLM이 확신하지 못해 탈락시킨 요소다.""" + key: str + label: str + what: str + on: bool + + +class FixedLayer(BaseModel): + key: str + label: str + on: bool = True + + +@dataclass +class PosterAnalysis: + grid: Image.Image # 사람이 요소를 지목하는 격자 + movable: list[MotionChoice] + fixed: list[FixedLayer] + model: str + ip_risk: bool + has_qr: bool + plan: MotionPlan # 사람이 고르기 전의 VLM 제안 원본 diff --git a/backend/models/cast.py b/backend/models/cast.py new file mode 100644 index 0000000..e2ace9b --- /dev/null +++ b/backend/models/cast.py @@ -0,0 +1,12 @@ +from typing import Literal + +from pydantic import BaseModel + + +class CastExtraction(BaseModel): + """NOL meta에는 출연진 필드가 없어 상세페이지에서 읽는다. + + 실패해도 잡을 멈추지 않고 source로 남겨 검수 게이트에서 사람이 판단하게 한다. + """ + names: list[str] = [] + source: Literal["vlm", "failed", "none"] = "none" diff --git a/backend/models/detail_section.py b/backend/models/detail_section.py new file mode 100644 index 0000000..89c0c50 --- /dev/null +++ b/backend/models/detail_section.py @@ -0,0 +1,25 @@ +from dataclasses import dataclass + +from PIL import Image + +UNTAGGED = "untagged" + + +@dataclass +class DetailSection: + source: str # 잘라낸 원본 이름 (detail_01 …) + index: int # 그 원본 안에서의 순번 + y0: int + y1: int + image: Image.Image + tag: str = UNTAGGED + + @property + def name(self) -> str: + return f"{self.source}_s{self.index:02d}" + + +@dataclass +class DetailSplitResult: + sections: list[DetailSection] + sheet: Image.Image # 육안 검수용 컨택트 시트 diff --git a/backend/models/nol.py b/backend/models/nol.py new file mode 100644 index 0000000..eae3e2b --- /dev/null +++ b/backend/models/nol.py @@ -0,0 +1,40 @@ +from dataclasses import dataclass, field + +from pydantic import BaseModel, ConfigDict, Field + + +class NolMeta(BaseModel): + """상품 페이지 SSR HTML에서 긁어낸 공연 정보.""" + model_config = ConfigDict(populate_by_name=True) + + goods_id: str + url: str + goods_name: str | None = Field(None, alias="goodsName") + place_name: str | None = Field(None, alias="placeName") + play_start_date: str | None = Field(None, alias="playStartDate") + play_end_date: str | None = Field(None, alias="playEndDate") + running_time: str | None = Field(None, alias="runningTime") + inter_mission_time: str | None = Field(None, alias="interMissionTime") + view_rate_name: str | None = Field(None, alias="viewRateName") + genre_name: str | None = Field(None, alias="genreName") + sub_genre_name: str | None = Field(None, alias="subGenreName") + corporation_name: str | None = Field(None, alias="corporationName") + poster_image_url: str | None = Field(None, alias="posterImageUrl") + booking_open_time: str | None = Field(None, alias="bookingOpenTime") + min_price: int | None = None + detail_image_urls: list[str] = [] + + +@dataclass +class FetchedImage: + url: str + data: bytes + extension: str # 확장자가 .gif여도 실제 바이트로 판별한 값 + + +@dataclass +class NolProduct: + meta: NolMeta + poster: FetchedImage | None + details: list[FetchedImage] + failed_urls: list[str] = field(default_factory=list) diff --git a/backend/models/upscale.py b/backend/models/upscale.py new file mode 100644 index 0000000..59297ed --- /dev/null +++ b/backend/models/upscale.py @@ -0,0 +1,8 @@ +from dataclasses import dataclass + + +@dataclass +class UpscaleResult: + image: bytes + credits: int + variant: str diff --git a/backend/raw_prompt/detail_section_tag.txt b/backend/raw_prompt/detail_section_tag.txt new file mode 100644 index 0000000..bdbbbfe --- /dev/null +++ b/backend/raw_prompt/detail_section_tag.txt @@ -0,0 +1,6 @@ +공연 예매 상세페이지에서 잘라낸 이미지 한 장이다. 아래 중 가장 맞는 태그 하나만 답하라. + +notice 공지·안내문 / event 이벤트·프로모션 / keyvisual 포스터·타이틀 키비주얼 / still 공연 무대 사진 +synopsis 시놉시스·작품 소개 글 / cast 배우 프로필 사진 그리드 / creative 제작진 명단 +schedule 회차별 캐스팅 스케줄 표 / discount 할인 안내 표 / crossbanner 다른 공연 배너 +info 예매·관람 안내 / fragment 의미 없는 조각 diff --git a/backend/raw_prompt/extract_cast.txt b/backend/raw_prompt/extract_cast.txt new file mode 100644 index 0000000..2029e78 --- /dev/null +++ b/backend/raw_prompt/extract_cast.txt @@ -0,0 +1,2 @@ +이 이미지는 한국 공연 상세페이지의 '출연진' 구간이다. 실제로 적혀 있는 배우 이름만 읽어라. +역할명·직책·제작진·문구는 넣지 마라. 없으면 빈 배열. diff --git a/backend/services/analyze_poster.py b/backend/services/analyze_poster.py new file mode 100644 index 0000000..11296c9 --- /dev/null +++ b/backend/services/analyze_poster.py @@ -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, + ) diff --git a/backend/services/detect.py b/backend/services/detect.py index 6b5b7a2..8d9353e 100644 --- a/backend/services/detect.py +++ b/backend/services/detect.py @@ -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) diff --git a/backend/services/extract_cast.py b/backend/services/extract_cast.py new file mode 100644 index 0000000..6994046 --- /dev/null +++ b/backend/services/extract_cast.py @@ -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") diff --git a/backend/services/fetch_nol.py b/backend/services/fetch_nol.py new file mode 100644 index 0000000..a5a98db --- /dev/null +++ b/backend/services/fetch_nol.py @@ -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']+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]) diff --git a/backend/services/i2v.py b/backend/services/i2v.py index 83b240c..53f31c9 100644 --- a/backend/services/i2v.py +++ b/backend/services/i2v.py @@ -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 단계를 먼저 돌릴 것") diff --git a/backend/services/split_detail.py b/backend/services/split_detail.py new file mode 100644 index 0000000..221b76b --- /dev/null +++ b/backend/services/split_detail.py @@ -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)) diff --git a/backend/services/upscale_poster.py b/backend/services/upscale_poster.py new file mode 100644 index 0000000..793090f --- /dev/null +++ b/backend/services/upscale_poster.py @@ -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) diff --git a/backend/tests/playreel/test_analyze_poster.py b/backend/tests/playreel/test_analyze_poster.py new file mode 100644 index 0000000..7a44951 --- /dev/null +++ b/backend/tests/playreel/test_analyze_poster.py @@ -0,0 +1,70 @@ +"""analyze 수동 확인용. + +사용: uv run python -m tests.playreel.test_analyze_poster +test_result/playreel/nol_/upscaled.png 을 쓰고, 없으면 poster.* 로 떨어진다. +ip_risk는 meta.json 의 goods_name 으로 판정한다. +결과는 같은 폴더의 analysis.json 과 review_grid.jpg. +""" +import asyncio +import json +import sys +from pathlib import Path + +from models.nol import NolMeta +from services.analyze_poster import analyze_poster + +TEST_RESULT_DIR = Path(__file__).parent.parent / "test_result" / "playreel" + + +def find_poster(product_dir: Path) -> Path: + upscaled = product_dir / "upscaled.png" + if upscaled.exists(): + return upscaled + originals = sorted(product_dir.glob("poster.*")) + if not originals: + raise SystemExit(f"{product_dir}에 포스터가 없다 — test_fetch_nol 을 먼저 돌릴 것") + print("※ upscaled.png 가 없어 원본 포스터를 쓴다") + return originals[0] + + +def load_title(product_dir: Path) -> str: + meta_path = product_dir / "meta.json" + if not meta_path.exists(): + return "" + return NolMeta.model_validate_json(meta_path.read_text(encoding="utf-8")).goods_name or "" + + +async def main() -> None: + goods_id = sys.argv[1] + product_dir = TEST_RESULT_DIR / f"nol_{goods_id}" + poster_path = find_poster(product_dir) + title = load_title(product_dir) + print(f"{title or '(공연명 없음)'} · {poster_path.name}") + + analysis = await analyze_poster(poster_path, title) + + grid_path = product_dir / "review_grid.jpg" + summary_path = product_dir / "analysis.json" + analysis.grid.save(grid_path, quality=90) + summary_path.write_text(json.dumps({ + "model": analysis.model, + "ip_risk": analysis.ip_risk, + "has_qr": analysis.has_qr, + "movable": [choice.model_dump() for choice in analysis.movable], + "fixed": [layer.model_dump() for layer in analysis.fixed], + "prompt": analysis.plan.prompt, + }, ensure_ascii=False, indent=2), encoding="utf-8") + + print(f"모델 {analysis.model} · QR {'있음' if analysis.has_qr else '없음'}" + f" · IP 위험 {'있음' if analysis.ip_risk else '없음'}") + print("움직일 요소:") + for choice in analysis.movable: + print(f" {'[o]' if choice.on else '[ ]'} {choice.label:10} {choice.what}") + print("고정 요소: " + " ".join(layer.label for layer in analysis.fixed)) + if not any(choice.on for choice in analysis.movable): + print("\n※ 켜진 요소가 없다 — 검수 화면에서 사람이 켜야 i2v로 갈 수 있다") + print(f"\n{grid_path}\n{summary_path}") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/backend/tests/playreel/test_extract_cast.py b/backend/tests/playreel/test_extract_cast.py new file mode 100644 index 0000000..4ab8ce6 --- /dev/null +++ b/backend/tests/playreel/test_extract_cast.py @@ -0,0 +1,52 @@ +"""캐스트 수집 수동 확인용. + +사용: uv run python -m tests.playreel.test_extract_cast +test_result/nol_/sections/index.json 을 되읽어 cast 태그 섹션에서 이름을 뽑는다. +결과는 같은 폴더의 cast.json. +""" +import asyncio +import json +import sys +from pathlib import Path + +from PIL import Image + +from models.detail_section import DetailSection +from services.extract_cast import CAST_TAG, extract_cast + +TEST_RESULT_DIR = Path(__file__).parent.parent / "test_result" / "playreel" + + +def load_sections(sections_dir: Path) -> list[DetailSection]: + index_path = sections_dir / "index.json" + if not index_path.exists(): + raise SystemExit(f"{index_path} 없음 — test_split_detail 을 먼저 돌릴 것") + return [DetailSection(source=item["source"], index=item["index"], + y0=item["y0"], y1=item["y1"], + image=Image.open(sections_dir / item["file"]), + tag=item["tag"]) + for item in json.loads(index_path.read_text(encoding="utf-8"))] + + +async def main() -> None: + goods_id = sys.argv[1] + product_dir = TEST_RESULT_DIR / f"nol_{goods_id}" + sections = load_sections(product_dir / "sections") + + tagged = [section.name for section in sections if section.tag == CAST_TAG] + print(f"섹션 {len(sections)}개 / cast 태그 {len(tagged)}개 {tagged}") + + result = await extract_cast(sections) + cast_path = product_dir / "cast.json" + cast_path.write_text(result.model_dump_json(indent=2), encoding="utf-8") + + print(f"source={result.source} · {len(result.names)}명") + for name in result.names: + print(f" {name}") + if result.source == "none": + print("※ cast 태그 섹션이 없다 — 태깅이 놓쳤거나 상세페이지에 출연진 구간이 없다") + print(f"\n{cast_path}") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/backend/tests/playreel/test_fetch_nol.py b/backend/tests/playreel/test_fetch_nol.py new file mode 100644 index 0000000..82b6e3d --- /dev/null +++ b/backend/tests/playreel/test_fetch_nol.py @@ -0,0 +1,42 @@ +"""fetch 수동 확인용. + +사용: uv run python -m tests.playreel.test_fetch_nol +결과는 test_result/nol_/ 에 meta.json · poster. · detail_NN.. +""" +import asyncio +import sys +from pathlib import Path + +from services.fetch_nol import fetch_product + +TEST_RESULT_DIR = Path(__file__).parent.parent / "test_result" / "playreel" + + +async def main() -> None: + goods_id = sys.argv[1] + output_dir = TEST_RESULT_DIR / f"nol_{goods_id}" + output_dir.mkdir(parents=True, exist_ok=True) + + product = await fetch_product(goods_id) + meta = product.meta + + (output_dir / "meta.json").write_text(meta.model_dump_json(indent=2), encoding="utf-8") + if product.poster: + (output_dir / f"poster.{product.poster.extension}").write_bytes(product.poster.data) + for index, image in enumerate(product.details, 1): + (output_dir / f"detail_{index:02d}.{image.extension}").write_bytes(image.data) + + print(f"{meta.goods_name} / {meta.place_name}") + print(f" {meta.play_start_date} ~ {meta.play_end_date} · {meta.running_time}" + f" · {meta.view_rate_name} · 최저 {meta.min_price}원") + poster_size = len(product.poster.data) if product.poster else 0 + print(f" 포스터 {poster_size / 1e3:.0f}KB" + f" / 상세 {len(product.details)}장" + f" / 실패 {len(product.failed_urls)}건") + for url in product.failed_urls: + print(f" ✗ {url}") + print(f"\n{output_dir}") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/backend/tests/playreel/test_split_detail.py b/backend/tests/playreel/test_split_detail.py new file mode 100644 index 0000000..c60e6e2 --- /dev/null +++ b/backend/tests/playreel/test_split_detail.py @@ -0,0 +1,67 @@ +"""split 수동 확인용. + +사용: uv run python -m tests.playreel.test_split_detail +test_result/nol_/detail_* 를 재사용하고, 없으면 fetch부터 돌린다. +결과는 같은 폴더의 sections/ 에 조각 PNG · index.json · _sheet.jpg. +""" +import asyncio +import json +import sys +from pathlib import Path + +from services.fetch_nol import fetch_product +from services.split_detail import split_details + +TEST_RESULT_DIR = Path(__file__).parent.parent / "test_result" / "playreel" +IMAGE_SUFFIXES = (".jpg", ".jpeg", ".png", ".webp", ".gif") + + +async def load_details(goods_id: str, product_dir: Path) -> list[bytes]: + existing = sorted(path for path in product_dir.glob("detail_*") + if path.suffix.lower() in IMAGE_SUFFIXES) + if existing: + return [path.read_bytes() for path in existing] + + product_dir.mkdir(parents=True, exist_ok=True) + product = await fetch_product(goods_id) + (product_dir / "meta.json").write_text(product.meta.model_dump_json(indent=2), + encoding="utf-8") + if product.poster: + (product_dir / f"poster.{product.poster.extension}").write_bytes(product.poster.data) + for index, image in enumerate(product.details, 1): + (product_dir / f"detail_{index:02d}.{image.extension}").write_bytes(image.data) + return [image.data for image in product.details] + + +async def main() -> None: + goods_id = sys.argv[1] + product_dir = TEST_RESULT_DIR / f"nol_{goods_id}" + details = await load_details(goods_id, product_dir) + print(f"상세 이미지 {len(details)}장 → 분할") + + result = await split_details(details) + + sections_dir = product_dir / "sections" + sections_dir.mkdir(exist_ok=True) + index = [] + for section in result.sections: + section.image.save(sections_dir / f"{section.name}.png") + index.append({"file": f"{section.name}.png", "source": section.source, + "index": section.index, "y0": section.y0, "y1": section.y1, + "width": section.image.width, "height": section.image.height, + "tag": section.tag}) + (sections_dir / "index.json").write_text( + json.dumps(index, ensure_ascii=False, indent=2), encoding="utf-8") + result.sheet.save(sections_dir / "_sheet.jpg", quality=80) + + counts: dict[str, int] = {} + for section in result.sections: + counts[section.tag] = counts.get(section.tag, 0) + 1 + print(f"조각 {len(result.sections)}개") + for tag, count in sorted(counts.items(), key=lambda item: -item[1]): + print(f" {tag:12} {count}") + print(f"\n{sections_dir}") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/backend/tests/playreel/test_upscale_poster.py b/backend/tests/playreel/test_upscale_poster.py new file mode 100644 index 0000000..0d797b6 --- /dev/null +++ b/backend/tests/playreel/test_upscale_poster.py @@ -0,0 +1,41 @@ +"""업스케일 수동 확인용. **2크레딧이 나간다.** + +사용: uv run python -m tests.playreel.test_upscale_poster +test_result/nol_/poster.* 를 Topaz Text Refine 2배로 올린다. +결과는 같은 폴더의 upscaled.png. +""" +import asyncio +import io +import sys +from pathlib import Path + +from PIL import Image + +from services.upscale_poster import upscale_poster + +TEST_RESULT_DIR = Path(__file__).parent.parent / "test_result" / "playreel" + + +async def main() -> None: + goods_id = sys.argv[1] + product_dir = TEST_RESULT_DIR / f"nol_{goods_id}" + posters = sorted(product_dir.glob("poster.*")) + if not posters: + raise SystemExit(f"{product_dir}/poster.* 없음 — test_fetch_nol 을 먼저 돌릴 것") + + source = posters[0] + with Image.open(source) as image: + print(f"{source.name} {image.size} → Topaz Text Refine 2x (2크레딧)") + + result = await upscale_poster(source.read_bytes()) + + output_path = product_dir / "upscaled.png" + output_path.write_bytes(result.image) + with Image.open(io.BytesIO(result.image)) as upscaled: + print(f"{result.variant} · {upscaled.size} · {len(result.image) / 1e6:.1f}MB " + f"· {result.credits}크레딧") + print(f"\n{output_path}") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/backend/tests/test_bgm.py b/backend/tests/poster_alive/test_bgm.py similarity index 91% rename from backend/tests/test_bgm.py rename to backend/tests/poster_alive/test_bgm.py index 02d413e..7ef6b1d 100644 --- a/backend/tests/test_bgm.py +++ b/backend/tests/poster_alive/test_bgm.py @@ -1,6 +1,6 @@ """bgm 수동 확인용. **Suno는 실제 과금이 나간다.** -사용: uv run python -m tests.test_bgm <포스터경로> +사용: uv run python -m tests.poster_alive.test_bgm <포스터경로> test_result/<이름>.narration.txt(bgm_style)와 <이름>.tts.txt(total)를 재사용한다. 없으면 앞 단계부터 돌린다. 결과는 <이름>.bgm.mp3 와 <이름>.bgm.txt. """ @@ -12,9 +12,9 @@ from pathlib import Path from models.tts import NarrationTimeline from services.bgm import generate_bgm from services.tts import synthesize -from tests.test_tts import load_narration +from tests.poster_alive.test_tts import load_narration -TEST_RESULT_DIR = Path(__file__).parent / "test_result" +TEST_RESULT_DIR = Path(__file__).parent.parent / "test_result" / "poster_alive" async def load_timeline(sentences: list[str], voice: str, timeline_path: Path diff --git a/backend/tests/test_detect.py b/backend/tests/poster_alive/test_detect.py similarity index 84% rename from backend/tests/test_detect.py rename to backend/tests/poster_alive/test_detect.py index 77f2401..4550f75 100644 --- a/backend/tests/test_detect.py +++ b/backend/tests/poster_alive/test_detect.py @@ -1,6 +1,6 @@ """detect 수동 확인용. -사용: uv run python -m tests.test_detect <포스터경로> +사용: uv run python -m tests.poster_alive.test_detect <포스터경로> 결과는 test_result/ 아래에 .detect.txt / .grid.jpg / .check.jpg 세 파일로 떨어진다. """ import asyncio @@ -9,7 +9,7 @@ from pathlib import Path from services.detect import detect -TEST_RESULT_DIR = Path(__file__).parent / "test_result" +TEST_RESULT_DIR = Path(__file__).parent.parent / "test_result" / "poster_alive" async def main() -> None: diff --git a/backend/tests/test_i2v.py b/backend/tests/poster_alive/test_i2v.py similarity index 82% rename from backend/tests/test_i2v.py rename to backend/tests/poster_alive/test_i2v.py index 5a7712b..d7e38bb 100644 --- a/backend/tests/test_i2v.py +++ b/backend/tests/poster_alive/test_i2v.py @@ -1,6 +1,6 @@ """i2v 수동 확인용. -사용: uv run python -m tests.test_i2v <포스터경로> +사용: uv run python -m tests.poster_alive.test_i2v <포스터경로> test_result/<이름>.i2v.txt(프롬프트)와 <이름>.detect.txt(영역)를 쓴다. 결과는 <이름>.clip.mp4 와 <이름>.title_gate.txt. """ @@ -9,10 +9,10 @@ import sys from pathlib import Path from models.detect import Regions -from services.i2v import DEFAULT_MODEL, animate, cli_args -from utils.higgsfield import run_cli +from services.i2v import animate, cli_args +from utils.higgsfield import KLING_3_0, run_cli -TEST_RESULT_DIR = Path(__file__).parent / "test_result" +TEST_RESULT_DIR = Path(__file__).parent.parent / "test_result" / "poster_alive" async def main() -> None: @@ -28,8 +28,8 @@ async def main() -> None: prompt = prompt_path.read_text(encoding="utf-8").strip() regions = Regions.model_validate_json(detect_path.read_text(encoding="utf-8")) - raw = await run_cli("generate", "cost", DEFAULT_MODEL, - *cli_args(prompt, poster_path, DEFAULT_MODEL), "--json", timeout=300) + raw = await run_cli("generate", "cost", KLING_3_0, + *cli_args(prompt, poster_path, KLING_3_0), "--json", timeout=300) print(f"=== generate cost 원본 출력 ({len(raw)}자) ===\n{raw}\n=== 끝 ===\n") result = await animate(prompt, poster_path, regions) diff --git a/backend/tests/test_motion.py b/backend/tests/poster_alive/test_motion.py similarity index 89% rename from backend/tests/test_motion.py rename to backend/tests/poster_alive/test_motion.py index 3baea76..a724c1d 100644 --- a/backend/tests/test_motion.py +++ b/backend/tests/poster_alive/test_motion.py @@ -1,6 +1,6 @@ """motion 수동 확인용. -사용: uv run python -m tests.test_motion <포스터경로> [모션키,쉼표구분] +사용: uv run python -m tests.poster_alive.test_motion <포스터경로> [모션키,쉼표구분] 모션키를 주면 VLM을 건너뛰고 그 목록으로 프롬프트를 만든다(빈 문자열이면 0종). 결과는 test_result/<이름>.motion.txt(채택·탈락)와 <이름>.i2v.txt(프롬프트 원문)로 떨어진다. """ @@ -10,7 +10,7 @@ from pathlib import Path from services.motion import plan_motion -TEST_RESULT_DIR = Path(__file__).parent / "test_result" +TEST_RESULT_DIR = Path(__file__).parent.parent / "test_result" / "poster_alive" async def main() -> None: diff --git a/backend/tests/test_narration.py b/backend/tests/poster_alive/test_narration.py similarity index 88% rename from backend/tests/test_narration.py rename to backend/tests/poster_alive/test_narration.py index 287e065..be78261 100644 --- a/backend/tests/test_narration.py +++ b/backend/tests/poster_alive/test_narration.py @@ -1,6 +1,6 @@ """narration 수동 확인용. -사용: uv run python -m tests.test_narration <포스터경로> +사용: uv run python -m tests.poster_alive.test_narration <포스터경로> 같은 포스터의 test_result/<이름>.detect.txt 가 있으면 재사용하고, 없으면 detect부터 돌린다. 결과는 test_result/<이름>.narration.txt 로 떨어진다. """ @@ -12,7 +12,7 @@ from models.detect import Regions from services.detect import detect from services.narration import generate_narration -TEST_RESULT_DIR = Path(__file__).parent / "test_result" +TEST_RESULT_DIR = Path(__file__).parent.parent / "test_result" / "poster_alive" async def load_regions(poster_path: Path, detect_path: Path) -> Regions: diff --git a/backend/tests/test_render.py b/backend/tests/poster_alive/test_render.py similarity index 91% rename from backend/tests/test_render.py rename to backend/tests/poster_alive/test_render.py index 2508309..781e9ac 100644 --- a/backend/tests/test_render.py +++ b/backend/tests/poster_alive/test_render.py @@ -1,6 +1,6 @@ """render 수동 확인용. -사용: uv run python -m tests.test_render <포스터경로> [클립경로] +사용: uv run python -m tests.poster_alive.test_render <포스터경로> [클립경로] 클립을 생략하면 test_result/<이름>.clip.mp4 를 쓴다. 나레이션(.tts.mp3)·타임라인(.tts.txt)·BGM(.bgm.mp3)은 있으면 얹고 없으면 건너뛴다. 결과는 <이름>.final.mp4 와 <이름>.thumb.jpg. @@ -11,7 +11,7 @@ from pathlib import Path from models.tts import NarrationTimeline from services.render import render -TEST_RESULT_DIR = Path(__file__).parent / "test_result" +TEST_RESULT_DIR = Path(__file__).parent.parent / "test_result" / "poster_alive" def read_if_exists(path: Path) -> bytes | None: diff --git a/backend/tests/test_tts.py b/backend/tests/poster_alive/test_tts.py similarity index 90% rename from backend/tests/test_tts.py rename to backend/tests/poster_alive/test_tts.py index 4ec71c9..aa1475b 100644 --- a/backend/tests/test_tts.py +++ b/backend/tests/poster_alive/test_tts.py @@ -1,6 +1,6 @@ """tts 수동 확인용. -사용: uv run python -m tests.test_tts <포스터경로> +사용: uv run python -m tests.poster_alive.test_tts <포스터경로> test_result/<이름>.narration.txt 가 있으면 재사용하고, 없으면 앞 단계부터 돌린다. 결과는 <이름>.tts.mp3(합쳐진 나레이션)와 <이름>.tts.txt(타임라인)로 떨어진다. """ @@ -11,9 +11,9 @@ from pathlib import Path from answers.narration_answer import NarrationAnswer from services.narration import generate_narration from services.tts import synthesize -from tests.test_narration import load_regions +from tests.poster_alive.test_narration import load_regions -TEST_RESULT_DIR = Path(__file__).parent / "test_result" +TEST_RESULT_DIR = Path(__file__).parent.parent / "test_result" / "poster_alive" async def load_narration(poster_path: Path, output_base: Path) -> NarrationAnswer: diff --git a/backend/tests/run_playreel.sh b/backend/tests/run_playreel.sh new file mode 100755 index 0000000..cb98e01 --- /dev/null +++ b/backend/tests/run_playreel.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# Playreel 롱컷 — 게이트 ①(fetch_confirm) 직전까지 돌린다. +# 사용: tests/run_playreel.sh +set -euo pipefail +cd "$(dirname "$0")/.." + +goods_id="${1:?사용: $0 }" + +run() { echo; echo "── $1 ──"; shift; uv run python -m "$@"; } + +run "① fetch" tests.playreel.test_fetch_nol "$goods_id" +run "② split" tests.playreel.test_split_detail "$goods_id" +run "②-부속 캐스트" tests.playreel.test_extract_cast "$goods_id" + +cat < +set -euo pipefail +cd "$(dirname "$0")/.." + +goods_id="${1:?사용: $0 }" + +run() { echo; echo "── $1 ──"; shift; uv run python -m "$@"; } + +run "③ upscale" tests.playreel.test_upscale_poster "$goods_id" +run "④ analyze" tests.playreel.test_analyze_poster "$goods_id" + +cat < +set -euo pipefail +cd "$(dirname "$0")/.." + +poster="${1:?사용: $0 <포스터경로>}" +[ -f "$poster" ] || { echo "포스터 없음: $poster" >&2; exit 1; } + +run() { echo; echo "── $1 ──"; shift; uv run python -m "$@"; } + +run "① detect" tests.poster_alive.test_detect "$poster" +run "② narration_text" tests.poster_alive.test_narration "$poster" +run "③ motion" tests.poster_alive.test_motion "$poster" + +cat < + +승인 후 — 여기부터는 사람 개입 없이 끝까지 간다 + uv run python -m tests.poster_alive.test_tts "$poster" + uv run python -m tests.poster_alive.test_bgm "$poster" + uv run python -m tests.poster_alive.test_i2v "$poster" + uv run python -m tests.poster_alive.test_render "$poster" +EOF diff --git a/backend/tests/run_poster_alive_after_gate.sh b/backend/tests/run_poster_alive_after_gate.sh new file mode 100755 index 0000000..204dd57 --- /dev/null +++ b/backend/tests/run_poster_alive_after_gate.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# 축제 숏폼 — 검수 게이트 승인 뒤. 여기부터 끝까지 사람 개입이 없다. +# 사용: tests/run_poster_alive_after_gate.sh <포스터경로> +set -euo pipefail +cd "$(dirname "$0")/.." + +poster="${1:?사용: $0 <포스터경로>}" +[ -f "$poster" ] || { echo "포스터 없음: $poster" >&2; exit 1; } + +run() { echo; echo "── $1 ──"; shift; uv run python -m "$@"; } + +run "④ tts" tests.poster_alive.test_tts "$poster" +run "⑤ bgm" tests.poster_alive.test_bgm "$poster" +run "⑥ i2v" tests.poster_alive.test_i2v "$poster" +run "⑦ render" tests.poster_alive.test_render "$poster" + +echo +echo "══ 완성 ══ test_result/poster_alive/ 의 .final.mp4 · .thumb.jpg" diff --git a/backend/utils/higgsfield.py b/backend/utils/higgsfield.py index 0b29e43..825ad6c 100644 --- a/backend/utils/higgsfield.py +++ b/backend/utils/higgsfield.py @@ -11,6 +11,12 @@ import re CLI = "higgsfield" CLI_TIMEOUT = 2100 +# Higgsfield가 제공하는 모델 식별자. 어느 단계가 무엇을 쓸지는 그 단계가 정한다. +KLING_3_0 = "kling3_0" +VEO_3_1 = "veo3_1" +TOPAZ_IMAGE = "topaz_image" +TOPAZ_TEXT_REFINE = "Text Refine" + RESULT_URL_PATTERN = re.compile(r'"result_url"\s*:\s*"([^"]+)"') CREDITS_PATTERN = re.compile(r'"credits(?:_exact)?"\s*:\s*([0-9.]+)') PLAIN_CREDITS_PATTERN = re.compile(r"([0-9.]+)\s*credits") diff --git a/backend/utils/image.py b/backend/utils/image.py index b34d50d..ba9c036 100644 --- a/backend/utils/image.py +++ b/backend/utils/image.py @@ -2,15 +2,29 @@ import base64 import io import numpy as np -from PIL import Image, ImageDraw +from PIL import Image, ImageDraw, ImageFont Image.MAX_IMAGE_PIXELS = None +IMAGE_SIGNATURES = ((b"\xff\xd8\xff", "jpg"), (b"\x89PNG\r\n\x1a\n", "png"), + (b"GIF87a", "gif"), (b"GIF89a", "gif")) + LOGO_BAR_SEARCH_FROM = 0.88 # 하단 12%에서만 밝은 띠를 찾는다 LOGO_BAR_BRIGHTNESS = 200 LOGO_BAR_MIN_ROWS = 20 +def sniff_extension(data: bytes) -> str: + """확장자가 .gif여도 실제 바이트는 JPEG·PNG인 경우가 많아 매직 넘버로 판별한다.""" + head = data[:12] + for signature, extension in IMAGE_SIGNATURES: + if head.startswith(signature): + return extension + if head[:4] == b"RIFF" and head[8:12] == b"WEBP": + return "webp" + return "bin" + + def content_box(frame: Image.Image) -> tuple[int, int, int, int]: """레터박스(검정·흰 여백)를 걷어낸 실제 포스터 영역.""" brightness = np.asarray(frame.convert("RGB")).astype(np.float32).mean(2) @@ -20,6 +34,44 @@ def content_box(frame: Image.Image) -> tuple[int, int, int, int]: return int(cols.min()), int(rows.min()), int(cols.max()) + 1, int(rows.max()) + 1 +def vlm_grid_overlay(poster: Image.Image) -> Image.Image: + """VLM이 눈금을 읽어 좌표를 답하게 하는 격자. + + 숫자가 없으면 모델이 선을 세야 하는데 그걸 못한다. 축을 구분하려고 색도 둘로 나눈다 — + 프롬프트가 '빨간 가로선 = 세로 위치, 하늘색 세로선 = 가로 위치'로 못박고 있다. + """ + 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 review_grid_overlay(poster: Image.Image) -> Image.Image: + """사람이 검수 화면에서 요소를 지목하는 격자. + + 읽는 게 아니라 가리키는 용도라 라벨이 필요 없고, 촘촘할수록 좋아서 가로도 5%로 둔다. + """ + overlay = poster.convert("RGB").copy() + width, height = overlay.size + draw = ImageDraw.Draw(overlay) + line_width = max(1, width // 900) + for step in range(1, 20): + x, y = width * step / 20, height * step / 20 + draw.line([(x, 0), (x, height)], fill=(255, 0, 128), width=line_width) + draw.line([(0, y), (width, y)], fill=(255, 0, 128), width=line_width) + return overlay + + def bar_box(poster: Image.Image) -> tuple[int, int, int, int] | None: """하단 주최·주관·후원 로고 띠(밝은 가로 밴드)의 bbox.""" pixels = np.asarray(poster.convert("RGB")).astype(np.float32) diff --git a/known_issue.md b/known_issue.md index 199ed60..cd19e6b 100644 --- a/known_issue.md +++ b/known_issue.md @@ -1,7 +1,12 @@ # known_issue.md -이슈는 파이프라인 단계별로 묶는다. -단계: ① detect ② narration_text ③ motion ④ tts ⑤ bgm ⑥ i2v ⑦ render. +이슈는 파이프라인·단계별로 묶는다. 제목에 표시가 없으면 축제 숏폼이다. + +- 축제 숏폼: ① detect ② narration_text ③ motion ④ tts ⑤ bgm ⑥ i2v ⑦ render +- Playreel 롱컷: ① fetch ② split ③ upscale ④ analyze ⑤ motion ⑥ narration ⑦ tts + ⑧ bgm ⑨ i2v ⑩ hybrid ⑪ compose ⑫ review + +두 파이프라인은 motion·tts·bgm·i2v를 같은 컴포넌트로 공유한다. 어느 단계에도 속하지 않으면 공통에 둔다. ## ① detect @@ -141,3 +146,29 @@ aspect_ratio·sound는 실질 문제가 아닐 수 있다. Kling은 9:16을 지 이 머신에 higgsfield CLI가 없다. `result_url`·`credits` 정규식 파싱은 원본을 옮겼을 뿐 실제 CLI 출력으로 확인한 것이 아니다. + +## [Playreel] ③ upscale + +### CLI가 파일 경로만 받아 임시 파일이 생긴다 + +`utils/higgsfield.py`를 타는 두 곳이 파일 경로를 요구한다 — 업스케일의 `--image`와 +i2v의 `--start-image`. 나머지 단계는 전부 bytes로 도는데 여기서만 디스크에 닿는다. + +`upscale_poster()`는 bytes를 받으면 `NamedTemporaryFile`로 잠깐 내렸다가 지운다. +`animate()`는 아예 `Path`만 받아 호출측에 떠넘긴다 — 두 곳의 처리가 다르다. + +CLI를 계속 쓰는 한 없앨 수 없다. Higgsfield HTTP API로 가면 presigned URL 업로드라 +파일이 필요 없지만, 그쪽은 8초와 Kling 3.0을 못 준다(⑥ i2v 항목 참조). + +### 원본은 업스케일 결과를 받아오지 않는다 + +원본 `stage_upscale`은 CLI에 출력 경로를 주지 않고 곧바로 +`upscale/topaz_textrefine_2x.png`가 있는지 검사한다. 그 파일을 만드는 코드가 없다. +`animate_poster.py`처럼 `result_url`을 파싱해 내려받는 단계가 빠진 것으로 보인다. + +우리 `upscale_poster()`는 i2v와 같은 방식으로 `result_url`을 받아 bytes로 돌려준다. + +### 크레딧 2가 상수로 박혀 있다 + +CLI `generate create` 응답에 크레딧 필드가 없어서(⑥ i2v에서 확인) 원본이 쓰던 값 2를 +그대로 상수로 뒀다. 요금이 바뀌면 조용히 틀린 값이 기록된다.