Compare commits

..
Author SHA1 Message Date
Haewon KamandClaude Opus 5 fb9c84aa62 style(web): 무빙포스터 로고를 Playreel과 같은 세로 락업으로
ADO2 로고 옆에 워드마크를 붙이던 인라인 배치를 Playreel 셸(.pr-wordmark)과
같은 문법으로 바꾼다 — ADO2 로고가 위, 제품 워드마크가 아래, 아래 줄을 로고
폭에 맞춰 락업이 사각형으로 앉는다.

MOVING POSTER 는 PLAYREEL 보다 글자가 길어 같은 18px 를 쓰면 로고 폭을
넘는다. 브라우저에서 재서 16.4px + 자간 0.14em 으로 잡았다.
자간은 마지막 글자 뒤에도 붙으므로 음수 마진으로 걷어내야 오른쪽 끝이 맞는다.

실측(로고 h24 = 162.54px):
  락업 컨테이너 폭 162.54px — 로고와 정확히 일치
  워드마크 잉크 폭 162.34px — 오른쪽 끝 오차 0.2px
  (참고: Playreel 자체 워드마크는 같은 기준에서 2.75px 어긋나 있다)
  390px 모바일 행: 헤더 71.4px, 메뉴 가로 스크롤 유지, 잘림 없음

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-10 12:04:55 +09:00
Haewon KamandClaude Opus 5 d50dc52c39 fix(web): 게이트 ① 구획 선택에 썸네일을 그린다
thumb_url을 백엔드가 내려보내는데 화면은 라벨 칩만 그렸다.
실물은 19조각에 라벨이 겹쳐서("유의사항" 일곱 개) 무엇을 고르는지
알 수 없는 상태였다.

- SectionPicker: 썸네일 그리드(auto-fill 84px, 390px에서 4열).
  번호 배지 · 선택 표시 · 잠금(캐스팅 스케줄) · 높이 툴팁
- 문구를 새 동작에 맞춘다 — 조각을 잘라 붙이는 것이 아니라
  고른 지점부터 상세페이지를 이어서 훑는다
- 목 데이터를 실측 19조각으로 교체. 6개짜리 깔끔한 목을 두었던 탓에
  라벨이 겹치는 실물 모양을 개발 중에 못 봤다

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-09 15:24:58 +09:00
Haewon KamandClaude Opus 5 0e53fa294b fix(compose): 상세페이지 스크롤을 롱이미지로 되돌린다
조각을 화면에 얹는 방식이라 스크롤이 한 번도 일어나지 않았다.
심규선 상세페이지 실측 — 19조각 중 1920px를 넘는 것이 0개라
scroll_scene의 span이 항상 0이었다. 화면의 13~44%만 조각이고
나머지는 블러 포스터로 남았으며, 같은 정지컷이 6초 넘게 이어졌다.

정본(tech_spec §5)에 있던 extend_to_height가 이식에서 빠진 것이 원인이다.
그것이 없으니 조각이 짧을 때 블러 배경에 상단 정렬로 얹는 수밖에 없었다.

- to_surface: 롱이미지를 폭 1080으로. trim_blank를 태우지 않는다 —
  위를 깎으면 섹션 y좌표가 전부 어긋난다
- extend_to_height + blank_band: 글자 없는 배경 띠를 거울 타일링,
  이음매 페더 40px. 프레임보다 짧아도 풀프레임을 채운다
- scroll_scene: 배경 합성 없이 surface.crop() — 블러가 섞일 여지를 없앤다
- build_scene_plan: 섹션은 훑기 시작점, 큐 길이가 훑는 거리.
  섹션이 떨어지면 앞 씬이 멈춘 자리에서 이어 읽는다(커서)
- SCROLL_TAG_PRIORITY에서 notice·crossbanner 제거 — 약관을 읽히는 영상이 아니다
- final_checks: 씬 종류가 scroll이라고 적힌 것이 아니라 실제 이동 거리를 본다.
  이 검사가 물러서 0픽셀 스크롤이 게이트를 통과했다

실측(심규선 자산 전체 합성, 569프레임 23.72초):
  콘텐츠 비율 t=8s 23%→99% · t=11s 13%→92% · t=17s 44%→99%
  프레임 간 변화량 0.01(정지) → 22~31

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-09 15:24:58 +09:00
jaehwang a2543e19d4 posteralive gate 조정 2026-09-09 11:32:24 +09:00
jaehwang 3ee1c3bdfc low resolution 예외처리 앞으로 2026-09-09 11:13:13 +09:00
jaehwang 2140f7d5c8 스타일링 1차 기능 추가 2026-09-09 10:34:58 +09:00
jaehwang 3555fa05a2 update archive thumbnail 2026-09-09 09:51:50 +09:00
jaehwang ca9e40f43d feature update 2026-09-09 09:27:15 +09:00
jaehwang 7a667d8a5f add archive 2026-09-09 09:19:22 +09:00
jaehwang 2c13e75a92 rollback ip configuration for apache 2026-09-08 16:13:54 +09:00
jaehwang 9bb46f7004 fix frontend bug 2026-09-08 15:57:35 +09:00
34 changed files with 1089 additions and 140 deletions

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
"""스타일링 ① — 포스터에 인쇄된 글자 판독 응답 스키마
이미지 생성 모델이 한글을 다시 그리며 자모를 바꾸므로(맥주축제 → 백주축제)
읽기 잘하는 모델에 먼저 읽히고 그 문자열을 생성 프롬프트에 못 박는다.
"""
from pydantic import BaseModel
MAX_EXTRA_LINES = 3
class PosterTextAnswer(BaseModel):
title: str
slogan: str
date: str
time: str
place: str
extra: list[str]
+21
View File
@@ -0,0 +1,21 @@
"""스타일링 ② — 레퍼런스 화풍 분석 응답 스키마
무드 형용사는 픽셀로 번역되지 않아 팔레트·조명·질감·타이포·구도 다섯을 요구한다.
짧게 나오면 다섯 중 빠진 것이 있다는 뜻이라 통과시키지 않는다.
"""
from pydantic import BaseModel, field_validator
MIN_STYLE_PROMPT_CHARS = 200
class StylePromptAnswer(BaseModel):
style_prompt: str
@field_validator("style_prompt")
@classmethod
def must_cover_five_elements(cls, style_prompt: str) -> str:
text = style_prompt.strip()
if len(text) < MIN_STYLE_PROMPT_CHARS:
raise ValueError(f"style_prompt가 {len(text)}자로 너무 짧음 "
f"({MIN_STYLE_PROMPT_CHARS}자 이상) — 5요소가 다 안 나옴")
return text
+2 -1
View File
@@ -3,7 +3,7 @@ from contextlib import asynccontextmanager
from fastapi import FastAPI from fastapi import FastAPI
from pipelines import worker from pipelines import worker
from routers import f1, playreel from routers import archive, f1, playreel
from utils import blob from utils import blob
from utils.database import close_engine, create_missing_tables from utils.database import close_engine, create_missing_tables
@@ -23,6 +23,7 @@ app = FastAPI(title="poster-alive", lifespan=lifespan)
app.include_router(f1.router) app.include_router(f1.router)
app.include_router(playreel.router) app.include_router(playreel.router)
app.include_router(archive.router)
@app.get("/api/health") @app.get("/api/health")
+2 -1
View File
@@ -11,7 +11,8 @@ class DetailSection:
index: int # 그 원본 안에서의 순번 index: int # 그 원본 안에서의 순번
y0: int y0: int
y1: int y1: int
image: Image.Image # compose는 좌표만 쓴다 — 조각 그림 없이 만들어도 된다
image: Image.Image | None = None
tag: str = UNTAGGED tag: str = UNTAGGED
@property @property
+6 -1
View File
@@ -11,8 +11,12 @@ class Scene(BaseModel):
"""나레이션 큐 하나에 대응하는 화면.""" """나레이션 큐 하나에 대응하는 화면."""
cue: int cue: int
kind: SceneKind kind: SceneKind
section: str | None = None # scroll일 때 쓸 섹션 이름 section: str | None = None # scroll 시작점이 된 섹션 이름
tag: str | None = None # 그 섹션의 태그. 왜 골랐는지 남긴다 tag: str | None = None # 그 섹션의 태그. 왜 골랐는지 남긴다
# scroll은 조각이 아니라 롱이미지 위에서 일어난다. 아래 셋이 그 좌표다
source: str | None = None # 훑을 롱이미지 (detail_01 …)
y0: float | None = None # 시작 위치. 롱이미지 높이 대비 0~1
y1: float | None = None # 끝 위치
class LongcutPlan(BaseModel): class LongcutPlan(BaseModel):
@@ -28,6 +32,7 @@ class EndBandInfo(BaseModel):
@dataclass @dataclass
class LongcutResult: class LongcutResult:
video: bytes video: bytes
thumbnail: bytes # 첫 프레임. 0초가 포스터 원본이라 그대로 정지컷이 된다
duration: float duration: float
frames: int frames: int
plan: LongcutPlan plan: LongcutPlan
+60
View File
@@ -0,0 +1,60 @@
"""포스터 스타일링 — 화풍 레퍼런스로 포스터를 다시 그린다"""
from dataclasses import dataclass
from enum import StrEnum
from pydantic import BaseModel
class TemplateLicense(StrEnum):
"""끄는 조건이 달라 등급을 나눈다
PUBLIC은 보호기간이 끝나 외부 공개가 되고
INTERNAL은 번들 레퍼런스의 권리가 남아 배포 시 감추며
USER는 올린 사람 책임이라 막지 않고 고지만 한다
"""
PUBLIC = "public-domain"
INTERNAL = "internal-only"
USER = "user-uploaded"
class TemplateCategory(StrEnum):
FINE_ART = "fine_art"
ORIENTAL = "oriental"
FILM = "film"
USER = "user"
class StyleTemplate(BaseModel):
"""번들과 사용자 레퍼런스가 같은 모양을 쓴다"""
id: str
name_ko: str
category: TemplateCategory
license: TemplateLicense
style_prompt: str
reference_url: str # 전이에 넣는 고해상본
thumbnail_url: str
attribution: str = ""
license_note: str = ""
small_reference: bool = False # 레퍼런스가 작아 결과가 나빠질 수 있음
class OutputFormat(BaseModel):
"""gpt-image가 내는 크기로 만든 뒤 필요하면 센터 크롭한다"""
id: str
label: str
generated_size: str
crop: tuple[int, int] | None = None
@dataclass
class ReferenceVariants:
reference: bytes # 긴 변 REFERENCE_LONG_EDGE
thumbnail: bytes
size: tuple[int, int]
@dataclass
class TransferResult:
image: bytes
format_id: str
style_prompt: str
has_info_band: bool # 날짜·장소를 밴드로 얹었는가
+13 -2
View File
@@ -9,13 +9,24 @@ from utils import blob
JPEG_QUALITY = 90 JPEG_QUALITY = 90
# 이름이 고정된 산출물. 경로가 정해져 있어 컬럼에 다시 적지 않고 만들어 쓴다
THUMBNAIL = "thumbnail.jpg"
def artifact_path(pipeline: str, task_id: str, name: str) -> str: def artifact_path(pipeline: str, task_id: str, name: str) -> str:
return f"{pipeline}/{task_id}/{name}" return f"{pipeline}/{task_id}/{name}"
async def store_bytes(pipeline: str, task_id: str, name: str, data: bytes) -> str: def artifact_url(pipeline: str, task_id: str, name: str) -> str:
return await blob.upload_bytes(data, artifact_path(pipeline, task_id, name)) return blob.public_url(artifact_path(pipeline, task_id, name))
async def store_bytes(pipeline: str, task_id: str, name: str, data: bytes, *,
download_as: str | None = None) -> str:
"""download_as를 주면 브라우저가 그 주소를 열 때 그 이름으로 내려받는다"""
return await blob.upload_bytes(
data, artifact_path(pipeline, task_id, name),
disposition=blob.as_attachment(download_as) if download_as else None)
async def store_image(pipeline: str, task_id: str, name: str, image: Image.Image) -> str: async def store_image(pipeline: str, task_id: str, name: str, image: Image.Image) -> str:
+12 -7
View File
@@ -135,17 +135,21 @@ def clip_review(task: PlayreelTask) -> dict:
def final_checks(task: PlayreelTask) -> list[dict]: def final_checks(task: PlayreelTask) -> list[dict]:
"""컬럼으로 확인되는 것만 낸다 — 완성본을 다시 열어 본 결과가 아니다.""" """컬럼으로 확인되는 것만 낸다 — 완성본을 다시 열어 본 결과가 아니다.
verdict = TitleGateVerdict.model_validate(task.title_gate or {"passed": True})
제목 훼손 검사는 넣지 않는다. 비교 기준이 되는 좌표를 detect가 만드는데
playreel에는 그 단계가 없어 검사 자체가 돌지 않는다.
"""
plan = LongcutPlan.model_validate(task.scene_plan or {"scenes": []}) plan = LongcutPlan.model_validate(task.scene_plan or {"scenes": []})
scroll_tags = {scene.tag for scene in plan.scenes if scene.kind == "scroll"} scrolls = [scene for scene in plan.scenes if scene.kind == "scroll"]
scroll_tags = {scene.tag for scene in scrolls}
return [ return [
{"key": "hybrid", "label": "원본 글자 합성", {"key": "hybrid", "label": "원본 글자 합성",
"ok": bool(task.hybrid_clip_url)}, "ok": bool(task.hybrid_clip_url)},
{"key": "title", "label": "제목 훼손 검사", # 씬 종류가 scroll이라고 적힌 것만으로는 부족하다 — 실제로 훑은 거리를 본다.
"ok": verdict.passed and not verdict.skip}, # 조각이 화면보다 짧아 한 픽셀도 안 움직인 채 통과한 적이 있다
{"key": "scroll", "label": "상세페이지 스크롤", {"key": "scroll", "label": "상세페이지 스크롤",
"ok": any(scene.kind == "scroll" for scene in plan.scenes)}, "ok": any((scene.y1 or 0.0) > (scene.y0 or 0.0) for scene in scrolls)},
{"key": "schedule", "label": "캐스팅 스케줄 포함", {"key": "schedule", "label": "캐스팅 스케줄 포함",
"ok": REQUIRED_SECTION_TAG in scroll_tags}, "ok": REQUIRED_SECTION_TAG in scroll_tags},
{"key": "bgm", "label": "배경음악", {"key": "bgm", "label": "배경음악",
@@ -156,7 +160,8 @@ def final_checks(task: PlayreelTask) -> list[dict]:
def final_review(task: PlayreelTask) -> dict: def final_review(task: PlayreelTask) -> dict:
return { return {
"video_url": task.video_url or "", "video_url": task.video_url or "",
"proof_url": task.compose_proof_url or task.hybrid_proof_url or "", # hybrid 시트는 앞 8초짜리라 완성본 검수 자리에 대신 세우지 않는다
"proof_url": task.compose_proof_url or "",
"duration": task.video_duration or 0.0, "duration": task.video_duration or 0.0,
"checks": final_checks(task), "checks": final_checks(task),
"version": task.version + 1, "version": task.version + 1,
+30 -6
View File
@@ -17,8 +17,8 @@ from models.motion import MotionPlan
from models.nol import NolMeta from models.nol import NolMeta
from models.pipeline_state import PlayreelState, initial_timings from models.pipeline_state import PlayreelState, initial_timings
from models.tts import NarrationTimeline, TypecastVoice from models.tts import NarrationTimeline, TypecastVoice
from pipelines.artifact import (contact_sheet, load_image, load_optional, store_bytes, from pipelines.artifact import (THUMBNAIL, artifact_url, contact_sheet, load_image,
store_image) load_optional, store_bytes, store_image)
from services.analyze_poster import analyze_poster from services.analyze_poster import analyze_poster
from services.bgm import DEFAULT_BGM_STYLE, generate_bgm from services.bgm import DEFAULT_BGM_STYLE, generate_bgm
from services.build_layer_config import build_layer_config from services.build_layer_config import build_layer_config
@@ -55,11 +55,30 @@ async def load_sections(entries: list[dict]) -> list[DetailSection]:
for entry in entries] for entry in entries]
def section_specs(entries: list[dict]) -> list[DetailSection]:
"""compose용 — 조각 그림은 안 받는다. 스크롤은 롱이미지 위에서 일어나고
섹션은 어디부터 훑을지를 정하는 좌표로만 쓰인다"""
return [DetailSection(source=entry["source"], index=entry["index"],
y0=entry["y0"], y1=entry["y1"], tag=entry["tag"])
for entry in entries]
async def load_details(task: PlayreelTask) -> dict[str, Image.Image]:
"""상세페이지 롱이미지. 이름은 split이 붙인 source와 같아야 한다"""
return {f"detail_{order:02d}": Image.open(io.BytesIO(await blob.download_bytes(url)))
for order, url in enumerate(task.detail_image_urls or [], 1)}
def working_poster_url(task: PlayreelTask) -> str: def working_poster_url(task: PlayreelTask) -> str:
"""업스케일이 있으면 그것이 이후 단계의 원본이 됨""" """업스케일이 있으면 그것이 이후 단계의 원본이 됨"""
return task.upscaled_poster_url or task.poster_url return task.upscaled_poster_url or task.poster_url
def thumbnail_url(task: PlayreelTask) -> str | None:
"""compose가 끝났으면 정지컷이 정해진 경로에 있다"""
return artifact_url(PIPELINE, task.id, THUMBNAIL) if task.video_url else None
async def create_task(session: AsyncSession, url: str, goods_id: str, async def create_task(session: AsyncSession, url: str, goods_id: str,
slug: str) -> PlayreelTask: slug: str) -> PlayreelTask:
task = PlayreelTask(source_url=url, goods_id=goods_id, slug=slug, task = PlayreelTask(source_url=url, goods_id=goods_id, slug=slug,
@@ -229,7 +248,8 @@ async def run_compose(session: AsyncSession, task: PlayreelTask) -> None:
meta = NolMeta.model_validate(task.nol_meta) meta = NolMeta.model_validate(task.nol_meta)
timeline = NarrationTimeline.model_validate(task.narration_timeline) timeline = NarrationTimeline.model_validate(task.narration_timeline)
selected = [entry for entry in task.detail_sections or [] if entry["selected"]] selected = [entry for entry in task.detail_sections or [] if entry["selected"]]
sections = await load_sections(selected) sections = section_specs(selected)
details = await load_details(task)
# 하이브리드 합성을 못 거친 클립은 제목이 흔들림 # 하이브리드 합성을 못 거친 클립은 제목이 흔들림
clip = await blob.download_bytes(task.hybrid_clip_url or task.clip_url) clip = await blob.download_bytes(task.hybrid_clip_url or task.clip_url)
@@ -240,10 +260,14 @@ async def run_compose(session: AsyncSession, task: PlayreelTask) -> None:
result = await asyncio.to_thread( result = await asyncio.to_thread(
compose_longcut, poster, clip, timeline, narration, sections, band_info(meta), compose_longcut, poster, clip, timeline, narration, sections, band_info(meta),
bgm_mp3=bgm, qr=Image.open(qr_path) if qr_path.exists() else None) details=details, bgm_mp3=bgm,
qr=Image.open(qr_path) if qr_path.exists() else None, preview=True)
task.video_url = await store_bytes(PIPELINE, task.id, filename = f"{task.slug}_30_v{task.version + 1}.mp4"
f"longcut_v{task.version + 1}.mp4", result.video) task.video_url = await store_bytes(PIPELINE, task.id, filename, result.video,
download_as=filename)
# 경로가 고정이라 URL은 남기지 않는다. 읽는 쪽이 thumbnail_url()로 만든다
await store_bytes(PIPELINE, task.id, THUMBNAIL, result.thumbnail)
task.scene_plan = result.plan.model_dump() task.scene_plan = result.plan.model_dump()
task.video_duration = result.duration task.video_duration = result.duration
task.video_frames = result.frames task.video_frames = result.frames
+7 -2
View File
@@ -67,6 +67,9 @@ async def run_narration_text(session: AsyncSession, task: PosterAliveTask) -> No
task.narration_voice = answer.voice task.narration_voice = answer.voice
task.bgm_style = answer.bgm_style.model_dump() task.bgm_style = answer.bgm_style.model_dump()
task.poster_metadata = answer.metadata.model_dump() task.poster_metadata = answer.metadata.model_dump()
# 올릴 때 이름을 안 줬으면 포스터에서 읽은 행사명이 이름이 된다
if not task.name:
task.name = answer.metadata.event_name
task.state = PosterAliveState.MOTION task.state = PosterAliveState.MOTION
await session.commit() await session.commit()
@@ -131,9 +134,11 @@ async def run_render(session: AsyncSession, task: PosterAliveTask) -> None:
result = await asyncio.to_thread(render, clip, poster, narration=narration, bgm=bgm, result = await asyncio.to_thread(render, clip, poster, narration=narration, bgm=bgm,
timeline=timeline) timeline=timeline)
task.video_url = await store_bytes(PIPELINE, task.id, "final.mp4", result.video) task.video_url = await store_bytes(PIPELINE, task.id, "final.mp4", result.video,
download_as=f"{task.name}.mp4")
task.thumbnail_url = await store_bytes(PIPELINE, task.id, "thumbnail.jpg", task.thumbnail_url = await store_bytes(PIPELINE, task.id, "thumbnail.jpg",
result.thumbnail) result.thumbnail,
download_as=f"{task.name}.jpg")
task.video_duration = result.duration task.video_duration = result.duration
task.video_frames = result.frames task.video_frames = result.frames
task.video_width = result.width task.video_width = result.width
+17
View File
@@ -0,0 +1,17 @@
포스터에 인쇄된 글자를 정확히 읽어라.
주의:
- 장식 서체는 획이 붙거나 끊겨 다른 글자로 보인다. `맥주축제`를 `백주축제`로 읽는 실수가 실제로 났다.
ㅁ/ㅂ, ㅈ/ㅊ, ㅌ/ㄷ을 한 자씩 확인하라.
- 영문·로마자 병기가 있으면 대조해 검산하라.
- 읽어낸 말이 한국어로 뜻이 통하지 않으면 오독이다. 이미지 내용과도 맞는지 확인하라
(맥주잔이 그려져 있으면 `백주축제`가 아니라 `맥주축제`다).
- 없는 항목은 빈 문자열로 둔다. 지어내지 마라.
각 항목:
- title — 행사명. 가장 크게 인쇄된 제목 글자 그대로
- slogan — 따옴표 안 슬로건 등 부제
- date — 날짜 표기 그대로
- time — 시간 표기 그대로
- place — 장소 표기 그대로
- extra — 그 밖에 포스터에 크게 박힌 문구 최대 3개
+30
View File
@@ -0,0 +1,30 @@
You write style specifications for an image-generation model.
You will see one reference artwork. Produce an English spec that another model can follow to
REDRAW an unrelated poster in this exact visual language. The spec must be executable — every
clause has to translate into pixels.
Cover all five elements, in this order, in one flowing paragraph of 5-7 sentences:
1. PALETTE — name 3-5 actual colours as a painter would ("cobalt blue, chrome yellow, deep
viridian"), plus how they are distributed (dominant / accent / shadow).
2. LIGHTING — direction, hardness and contrast of the light. If the work has no single light
source, say so and say what carries the luminance instead.
3. TEXTURE / MEDIUM — the physical medium and mark-making: brush size and direction, impasto,
woodblock keyline, glaze, film grain, canvas or paper weave.
4. TYPOGRAPHY TREATMENT — how a title would be lettered IN THIS IDIOM **while remaining fully
legible in Korean Hangul**. Derive the colour, the surface it sits on and its placement from
the medium (the reference may contain no lettering at all — derive it anyway; never omit this).
But the letterforms themselves are constrained, because Hangul stacks two to four jamo inside
one square and a lost stroke turns it into a different word: demand EVEN, UNBROKEN stroke
weight, open counters, and generous spacing between characters. Explicitly forbid tapering or
dry-brush stroke ends, hand-brushed irregularity, hairline serifs, distressed or eroded edges,
and lettering that blends into the artwork. Say the title must read as clean, solid shapes
even though the rest of the image is in this medium.
5. COMPOSITION MOTIF — horizon placement, dominant shape and its direction of movement, figure
scale relative to frame, use of empty space, any repeating pattern.
BANNED: mood adjectives standing alone ("epic", "dreamy", "haunting", "vibrant", "unsettling",
"atmospheric"). A mood word is only allowed if the same sentence names the colour, direction,
medium or shape that produces it. Do not name the artwork, the artist or the art movement —
describe what is on the surface, because the generating model may not know the reference.
+11 -6
View File
@@ -1,9 +1,14 @@
포스터 영상의 서로 다른 시점에서 잘라낸 '제목 영역' 이미지들이다. 포스터 영상의 서로 다른 시점에서 같은 자리를 잘라낸 '제목 영역' 이미지들이다.
질문은 하나다: **각 시점에서 제목 글자가 온전히 읽히는가.** [0]은 생성 전 원본이고 [1]부터가 생성된 프레임이다.
질문은 하나다: **[0]에 보이는 글자가 각 시점에서도 그대로 읽히는가.**
판정 기준: 판정 기준:
- 글자 자체가 온전하면 legible=true. 배경이 변한 것(불꽃·구름·빛이 글자 **뒤로** 지나감)은 - [0]에 없는 글자는 판정 대상이 아니다. 상자가 제목의 일부만 덮고 있을 수 있고,
훼손이 아니다. 잘려 나간 글자를 '없어졌다'고 하면 안 된다.
- 글자가 다른 그림에 **가려짐**, 획이 지워짐·뭉개짐, 다른 글자로 변형, 재작화됐으면 legible=false. - [0]에 있던 글자가 다른 그림에 가려짐, 획이 지워짐·뭉개짐, 다른 글자로 변형,
- 기대 제목의 일부 글자만 훼손돼도 false다. broken에 어떤 글자가 어떻게 됐는지 짧게 쓴다. 재작화됐으면 legible=false.
- 배경만 변한 것은 훼손이 아니다. 불꽃·구름·빛이 글자 뒤로 지나가는 것은 그대로 통과다.
- [0]은 원본이므로 항상 legible=true다.
- index는 이미지에 붙은 번호 그대로 쓴다. 훼손이 없으면 broken은 빈 문자열. - index는 이미지에 붙은 번호 그대로 쓴다. 훼손이 없으면 broken은 빈 문자열.
- broken에는 [0]의 어떤 글자가 어떻게 됐는지 짧게 쓴다.
+81
View File
@@ -0,0 +1,81 @@
"""/api/archive — 완료된 잡을 한 목록으로 보여준다
별도 저장소를 두지 않는다. 두 잡 테이블에서 끝난 것만 골라 그때그때 만든다.
필드는 web/lib/api.ts 의 ArchiveEntry 와 맞춘다.
"""
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from models.nol import NolMeta
from pipelines.gate import period_text
from pipelines.playreel import thumbnail_url
from pipelines.runner import DONE
from routers.view import UNNAMED
from tables.task import PlayreelTask, PosterAliveTask
from utils.database import get_session
router = APIRouter(prefix="/api/archive", tags=["archive"])
def poster_alive_entry(task: PosterAliveTask) -> dict:
return {
"slug": task.id,
"kind": "f1",
"name": task.name or UNNAMED,
"source": None,
"metadata": task.poster_metadata,
"narration": task.narration_lines,
"poster_url": task.poster_url,
"video_url": task.video_url,
"thumbnail_url": task.thumbnail_url,
"version": None,
"credits_used": task.credits_used,
"f2_variants": [],
"created_at": task.created_at.timestamp(),
}
def playreel_entry(task: PlayreelTask) -> dict:
meta = NolMeta.model_validate(task.nol_meta) if task.nol_meta else None
return {
"slug": task.id,
"kind": "playreel",
"name": task.name or UNNAMED,
"source": {"url": task.source_url, "goods_id": task.goods_id, "slug": task.slug},
"metadata": None if meta is None else {
"event_name": meta.goods_name or "",
"date_text": period_text(meta),
"place": meta.place_name or "",
"category": meta.genre_name or "",
"keywords": [],
},
"narration": [line["text"] for line in task.narration_lines or []] or None,
"poster_url": task.upscaled_poster_url or task.poster_url,
"video_url": task.video_url,
"thumbnail_url": thumbnail_url(task),
"version": task.version,
"credits_used": task.credits_used,
"f2_variants": [],
"created_at": task.created_at.timestamp(),
}
@router.get("")
async def list_entries(session: AsyncSession = Depends(get_session)):
entries = [playreel_entry(task) for task in await session.scalars(
select(PlayreelTask).where(PlayreelTask.status == DONE))]
entries += [poster_alive_entry(task) for task in await session.scalars(
select(PosterAliveTask).where(PosterAliveTask.status == DONE))]
return sorted(entries, key=lambda entry: entry["created_at"], reverse=True)
@router.get("/{slug}")
async def get_entry(slug: str, session: AsyncSession = Depends(get_session)):
playreel = await session.get(PlayreelTask, slug)
if playreel is not None:
return playreel_entry(playreel)
poster_alive = await session.get(PosterAliveTask, slug)
if poster_alive is not None:
return poster_alive_entry(poster_alive)
raise HTTPException(404, "아카이브에 없는 항목입니다")
+15 -3
View File
@@ -12,6 +12,7 @@ from pipelines import poster_alive
from pipelines.artifact import load_image from pipelines.artifact import load_image
from pipelines.runner import AWAITING_REVIEW, FAILED, QUEUED, RUNNING, reset_from from pipelines.runner import AWAITING_REVIEW, FAILED, QUEUED, RUNNING, reset_from
from routers.view import motion_elements, poster_alive_view from routers.view import motion_elements, poster_alive_view
from services.i2v import MIN_LONG_EDGE_PX
from services.motion import plan_motion from services.motion import plan_motion
from tables.task import PosterAliveTask from tables.task import PosterAliveTask
from utils.database import get_session from utils.database import get_session
@@ -66,12 +67,21 @@ async def create(poster: UploadFile = File(...), name: str = Form(""),
if len(raw) > MAX_UPLOAD_BYTES: if len(raw) > MAX_UPLOAD_BYTES:
raise HTTPException(413, "30MB 이하만 올릴 수 있습니다") raise HTTPException(413, "30MB 이하만 올릴 수 있습니다")
try: try:
Image.open(io.BytesIO(raw)).verify() with Image.open(io.BytesIO(raw)) as image:
width, height = image.size
image.verify()
except Exception: except Exception:
raise HTTPException(422, "이미지 파일을 열 수 없습니다") raise HTTPException(422, "이미지 파일을 열 수 없습니다")
task = await poster_alive.create_task(session, name.strip() or "이름 없는 행사", raw, # i2v가 확대 시 뭉개져 거절한다. 거기까지 가면 나레이션·TTS·BGM을 다 쓰고 터지므로
skip_review=auto) # 같은 기준을 업로드에서 먼저 건다
if max(width, height) < MIN_LONG_EDGE_PX:
raise HTTPException(
422, f"포스터 긴 변이 {MIN_LONG_EDGE_PX}px 이상이어야 합니다 "
f"(받은 것: {width}x{height}). 고해상 원본으로 올려주세요.")
# 이름을 비워 두면 narration_text 가 포스터에서 읽은 행사명으로 채운다
task = await poster_alive.create_task(session, name.strip(), raw, skip_review=auto)
return {"id": task.id, "ahead": 0} return {"id": task.id, "ahead": 0}
@@ -120,6 +130,8 @@ async def edit_metadata(task_id: str, body: MetadataBody,
if body.keywords is not None: if body.keywords is not None:
metadata["keywords"] = [word.strip() for word in body.keywords if word.strip()] metadata["keywords"] = [word.strip() for word in body.keywords if word.strip()]
task.poster_metadata = metadata task.poster_metadata = metadata
# 잡 이름이 곧 내려받는 파일명이라 고친 행사명을 따라간다
task.name = metadata["event_name"]
await session.commit() await session.commit()
return poster_alive_view(task) return poster_alive_view(task)
+6 -1
View File
@@ -10,7 +10,7 @@ from models.pipeline_state import PlayreelState
from pipelines import playreel from pipelines import playreel
from pipelines.gate import (REVERSIBLE_GATES, PlayreelGate, apply_playreel_edits, from pipelines.gate import (REVERSIBLE_GATES, PlayreelGate, apply_playreel_edits,
previous_gate, resume_stage) previous_gate, resume_stage)
from pipelines.runner import AWAITING_REVIEW, FAILED, QUEUED, RUNNING, reset_from from pipelines.runner import AWAITING_REVIEW, DONE, FAILED, QUEUED, RUNNING, reset_from
from routers.view import playreel_view from routers.view import playreel_view
from tables.task import PlayreelTask from tables.task import PlayreelTask
from utils.database import get_session from utils.database import get_session
@@ -19,6 +19,8 @@ router = APIRouter(prefix="/api/playreel", tags=["playreel"])
# 프론트 parseGoodsId와 같은 규칙. 프론트 검사는 입력 도중의 안내이고 판정은 여기서 한다 # 프론트 parseGoodsId와 같은 규칙. 프론트 검사는 입력 도중의 안내이고 판정은 여기서 한다
GOODS_ID_PATTERNS = ( GOODS_ID_PATTERNS = (
# 인터파크 주소는 야놀자로 리다이렉트된다. 상품 번호는 양쪽이 같다
r"nol\.yanolja\.com/ticket/products/(\d{5,})",
r"tickets\.interpark\.com/goods/(\d{5,})", r"tickets\.interpark\.com/goods/(\d{5,})",
r"nol\.interpark\.com/[^?]*?(\d{8,})", r"nol\.interpark\.com/[^?]*?(\d{8,})",
r"[?&]goodsCode=(\d{5,})", r"[?&]goodsCode=(\d{5,})",
@@ -119,6 +121,9 @@ async def back(task_id: str, session: AsyncSession = Depends(get_session)):
async def retry(task_id: str, session: AsyncSession = Depends(get_session)): async def retry(task_id: str, session: AsyncSession = Depends(get_session)):
"""실패 재시도와 클립 재생성. i2v를 다시 돌리면 크레딧이 다시 든다""" """실패 재시도와 클립 재생성. i2v를 다시 돌리면 크레딧이 다시 든다"""
task = await find_task(session, task_id) task = await find_task(session, task_id)
# 끝난 것을 다시 돌리면 크레딧만 나간다. 새로 만들 거면 새 잡이다
if task.status == DONE:
raise HTTPException(409, "이미 끝난 작업입니다")
restart = (PlayreelState.I2V.value if task.gate == PlayreelGate.CLIP_CONFIRM restart = (PlayreelState.I2V.value if task.gate == PlayreelGate.CLIP_CONFIRM
else task.error_stage or PlayreelState.FETCH.value) else task.error_stage or PlayreelState.FETCH.value)
reset_from(task, restart) reset_from(task, restart)
+18 -4
View File
@@ -2,8 +2,9 @@
필드는 web/lib/api.ts 의 Job, web/lib/playreel.ts 의 PlayreelJob 과 맞춤 필드는 web/lib/api.ts 의 Job, web/lib/playreel.ts 의 PlayreelJob 과 맞춤
""" """
from models.motion import MotionPlan from models.motion import MotionPlan
from models.pipeline_state import PlayreelState, PosterAliveState, initial_timings from models.pipeline_state import PlayreelState, PosterAliveState, stage_keys
from pipelines.gate import build_review from pipelines.gate import build_review
from pipelines.playreel import thumbnail_url
from tables.task import PlayreelTask, PosterAliveTask from tables.task import PlayreelTask, PosterAliveTask
@@ -24,13 +25,26 @@ def motion_elements(motion_plan: dict | None) -> list[str] | None:
return [item.motion for item in MotionPlan.model_validate(motion_plan).kept] return [item.motion for item in MotionPlan.model_validate(motion_plan).kept]
IDLE = {"status": "idle", "started": None, "ended": None}
# 이름은 narration_text 가 포스터에서 읽어 채운다. 그 전까지 화면에 쓸 말
UNNAMED = "이름 없는 행사"
def ordered_stages(task, state_type) -> dict:
"""스테퍼가 키 순서대로 그리므로 실행 순서로 다시 세운다.
JSON 객체는 순서를 담는 자리가 아니고, 순서의 정본은 state enum이다.
"""
stored = task.stage_timings or {}
return {key: stored.get(key, IDLE) for key in stage_keys(state_type)}
def base_view(task, state_type) -> dict: def base_view(task, state_type) -> dict:
return { return {
"id": task.id, "id": task.id,
"name": task.name, "name": task.name or UNNAMED,
"status": task.status, "status": task.status,
"stage": current_stage(task), "stage": current_stage(task),
"stages": task.stage_timings or initial_timings(state_type), "stages": ordered_stages(task, state_type),
"error": error_view(task), "error": error_view(task),
"created_at": task.created_at.timestamp(), "created_at": task.created_at.timestamp(),
"credits_used": task.credits_used, "credits_used": task.credits_used,
@@ -68,6 +82,6 @@ def playreel_view(task: PlayreelTask) -> dict:
"metadata": None, "metadata": None,
"artifacts": {key: url for key, url in ( "artifacts": {key: url for key, url in (
("video", task.video_url), ("video", task.video_url),
("thumbnail", task.analysis_grid_url), ("thumbnail", thumbnail_url(task)),
) if url}, ) if url},
} }
+193 -55
View File
@@ -1,8 +1,9 @@
"""⑪ compose — 무빙포스터 훅 + 상세페이지 스크롤로 30초 롱컷을 조립한다. """⑪ compose — 무빙포스터 훅 + 상세페이지 스크롤로 30초 롱컷을 조립한다.
씬 경계는 나레이션 큐다. 0초는 포스터 원본이라 첫 프레임이 곧 썸네일이 된다. 씬 경계는 나레이션 큐다. 0초는 포스터 원본이라 첫 프레임이 곧 썸네일이 된다.
상세페이지는 잘라 붙이지 않고 롱이미지를 실제로 스크롤한다. 상세페이지는 잘라 붙이지 않고 롱이미지를 실제로 스크롤한다 — 조각은 "어디부터 읽을지"를
포스터·롱이미지는 세로 롱이라 9:16을 못 채워서 포스터 블러판 위에 얹는다. 정하는 시작점일 뿐이고, 화면에 흐르는 것은 언제나 원본 롱이미지다.
포스터는 세로 롱이라 9:16을 못 채워서 포스터 블러판 위에 얹는다.
텍스트 오버레이는 넣지 않는다. 남는 글자는 엔드밴드뿐이다. 텍스트 오버레이는 넣지 않는다. 남는 글자는 엔드밴드뿐이다.
""" """
@@ -12,7 +13,7 @@ from collections.abc import Iterator, Sequence
from pathlib import Path from pathlib import Path
import numpy as np import numpy as np
from PIL import Image, ImageDraw, ImageFilter from PIL import Image, ImageDraw, ImageFilter, ImageOps
from models.detail_section import DetailSection from models.detail_section import DetailSection
from models.longcut import EndBandInfo, LongcutPlan, LongcutResult, Scene from models.longcut import EndBandInfo, LongcutPlan, LongcutResult, Scene
@@ -30,9 +31,20 @@ DUCK_THRESHOLD = 0.03
DUCK_ATTACK_MS, DUCK_RELEASE_MS = 60, 500 DUCK_ATTACK_MS, DUCK_RELEASE_MS = 60, 500
BGM_FADE_OUT = 1.2 BGM_FADE_OUT = 1.2
# 큐 1초당 화면 높이의 몇 배를 훑을지. 원본은 사람이 구간을 골랐다(known_issue 참조). # 큐 1초당 화면 높이의 몇 배를 훑을지. 5초 씬에 이미지 높이의 15~30%가 읽기 좋은 속도다
SCROLL_SCREENS_PER_SECOND = 0.35 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_HEIGHT = 300
BAND_RISE_SECONDS = 0.6 BAND_RISE_SECONDS = 0.6
NOL_BLUE = (0x41, 0x54, 0xFF) NOL_BLUE = (0x41, 0x54, 0xFF)
@@ -41,7 +53,8 @@ NOL_WORDMARK = ASSET_DIR / "nol_wordmark_white.png"
# 큐 순서대로 채울 씬. 앞 둘은 클립, 마지막은 포스터, 나머지는 이 태그 우선순위로 고른다. # 큐 순서대로 채울 씬. 앞 둘은 클립, 마지막은 포스터, 나머지는 이 태그 우선순위로 고른다.
CLIP_CUES = 2 CLIP_CUES = 2
SCROLL_TAG_PRIORITY = ("synopsis", "still", "cast", "schedule", "discount", "event", "notice") # 공지·교차배너는 스크롤 시작점으로 쓰지 않는다 — 약관을 읽히려고 만드는 영상이 아니다
SCROLL_TAG_PRIORITY = ("synopsis", "still", "cast", "schedule", "discount", "event", "info")
REQUIRED_TAGS = ("schedule",) # 캐스팅 스케줄은 예매 전에 확인하는 정보라 빠지면 안 된다 REQUIRED_TAGS = ("schedule",) # 캐스팅 스케줄은 예매 전에 확인하는 정보라 빠지면 안 된다
@@ -56,20 +69,78 @@ def blurred_bg(poster: Image.Image) -> Image.Image:
return Image.eval(blurred, lambda v: int(v * 0.45)) return Image.eval(blurred, lambda v: int(v * 0.45))
def trim_blank(image: Image.Image, threshold: int = 235) -> Image.Image: def ink_rows(image: Image.Image) -> np.ndarray:
"""상하단 흰·균일 여백 제거. split이 남긴 12px 여백이 화면에 흰 줄로 보인다.""" """행마다 글자·그림이 있는지. 배경 중앙값에서 벗어난 픽셀의 비율로 본다."""
pixels = np.asarray(image.convert("RGB")).astype(int) pixels = np.asarray(image.convert("L")).astype(np.int16)
white = (pixels.min(axis=2) > threshold).mean(axis=1) > 0.98 background = np.median(pixels)
uniform = pixels.std(axis=1).max(axis=1) < 4 return (np.abs(pixels - background) > INK_DEVIATION).mean(axis=1) > INK_ROW_RATIO
content = np.where(~(white | uniform))[0]
if len(content) == 0:
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 return image
return image.crop((0, int(content[0]), image.width, int(content[-1]) + 1))
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 fit_width(image: Image.Image) -> Image.Image: def _feather_seam(canvas: Image.Image, seam: int, width: int,
image = trim_blank(image) feather: int = EXTEND_FEATHER) -> None:
return image.resize((W, max(1, round(image.height * W / image.width))), Image.LANCZOS) """이음매 위아래를 선형 혼합해 가로줄이 보이지 않게 한다."""
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: def still_scene(still: Image.Image, progress: float, index: int) -> Image.Image:
@@ -90,15 +161,17 @@ def still_scene(still: Image.Image, progress: float, index: int) -> Image.Image:
return frame return frame
def scroll_scene(image: Image.Image, background: Image.Image, progress: float, def scroll_top(surface: Image.Image, fraction: float) -> int:
duration: float) -> Image.Image: """이미지 높이 대비 비율을 실제 crop 시작 y로. 끝을 넘지 않게 묶는다."""
"""읽는 속도로 훑는다. 이미지가 길면 위쪽만 보여준다.""" span = max(0, surface.height - H)
span = max(0, image.height - H) return min(max(0, round(surface.height * fraction)), span)
reach = min(span, round(duration * SCROLL_SCREENS_PER_SECOND * H))
top = int(reach * ease_sine(progress))
frame = background.copy() def scroll_scene(surface: Image.Image, progress: float, y0: float, y1: float) -> Image.Image:
frame.paste(image.crop((0, top, W, min(image.height, top + H))), (0, 0)) """롱이미지를 y0~y1 구간까지 훑는다. 프레임을 가득 채운다 — 배경이 비지 않는다."""
return frame 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: def poster_scene(poster: Image.Image, background: Image.Image, progress: float) -> Image.Image:
@@ -144,10 +217,19 @@ def end_band(frame: Image.Image, info: EndBandInfo, seconds: float,
draw.text((60, top + offset + slide), text, font=font(weight, size), fill=fill) draw.text((60, top + offset + slide), text, font=font(weight, size), fill=fill)
def build_scene_plan(sections: Sequence[DetailSection], cue_count: int) -> LongcutPlan: 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]] = {} by_tag: dict[str, list[DetailSection]] = {}
for section in sections: for section in usable:
by_tag.setdefault(section.tag, []).append(section) by_tag.setdefault(section.tag, []).append(section)
ordered: list[DetailSection] = [] ordered: list[DetailSection] = []
@@ -157,18 +239,48 @@ def build_scene_plan(sections: Sequence[DetailSection], cue_count: int) -> Longc
for section in by_tag.get(tag, []): for section in by_tag.get(tag, []):
if section not in ordered: if section not in ordered:
ordered.append(section) ordered.append(section)
return ordered
scenes = []
scroll_index = 0 def scroll_window(section: DetailSection, source: Image.Image, surface: Image.Image,
for cue in range(cue_count): seconds: float) -> tuple[float, float]:
"""섹션이 시작점, 큐 길이가 훑는 거리. 둘 다 롱이미지 높이 대비 비율로 돌려준다."""
scale = W / source.width
start = round(section.y0 * scale)
reach = round(seconds * SCROLL_SCREENS_PER_SECOND * H)
return start / surface.height, (start + reach) / surface.height
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
cursor = 0.0 # 폴백이 이어 읽을 지점
for cue, (start, end) in enumerate(spans):
if cue < CLIP_CUES: if cue < CLIP_CUES:
scenes.append(Scene(cue=cue, kind="clip")) scenes.append(Scene(cue=cue, kind="clip"))
elif cue == cue_count - 1: elif cue == len(spans) - 1:
scenes.append(Scene(cue=cue, kind="poster")) scenes.append(Scene(cue=cue, kind="poster"))
elif scroll_index < len(ordered): elif index < len(ordered):
section = ordered[scroll_index] section = ordered[index]
scenes.append(Scene(cue=cue, kind="scroll", section=section.name, tag=section.tag)) y0, y1 = scroll_window(section, sources[section.source],
scroll_index += 1 surfaces[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, cursor = index + 1, y1
elif fallback is not None:
# 쓸 섹션이 떨어져도 포스터로 때우지 않는다. 앞 씬이 멈춘 자리에서 이어 읽어야
# 같은 화면이 두 번 나오지 않는다
reach = round((end - start) * SCROLL_SCREENS_PER_SECOND * H)
y1 = cursor + reach / surfaces[fallback].height
scenes.append(Scene(cue=cue, kind="scroll", source=fallback,
y0=cursor, y1=y1))
cursor = y1
else: else:
scenes.append(Scene(cue=cue, kind="poster")) scenes.append(Scene(cue=cue, kind="poster"))
return LongcutPlan(scenes=scenes) return LongcutPlan(scenes=scenes)
@@ -209,13 +321,11 @@ def mix_audio(narration_mp3: bytes, bgm_mp3: bytes | None, duration: float) -> n
def compose_frames(timeline: NarrationTimeline, plan: LongcutPlan, poster: Image.Image, def compose_frames(timeline: NarrationTimeline, plan: LongcutPlan, poster: Image.Image,
clip: bytes, sections: dict[str, Image.Image], clip: bytes, surfaces: dict[str, Image.Image],
info: EndBandInfo, qr: Image.Image | None) -> Iterator[Image.Image]: info: EndBandInfo, qr: Image.Image | None) -> Iterator[Image.Image]:
background = blurred_bg(poster) background = blurred_bg(poster)
starts = [0.0] + [cue.start for cue in timeline.cues[1:]] spans = cue_spans(timeline)
bounds = [cue.start for cue in timeline.cues[1:]] + [timeline.total]
clip_frames = list(decode_frames(clip)) clip_frames = list(decode_frames(clip))
scroll_images = {name: fit_width(image) for name, image in sections.items()}
scenes = {scene.cue: scene for scene in plan.scenes} scenes = {scene.cue: scene for scene in plan.scenes}
def frame_at(cue: int, at: float) -> Image.Image: def frame_at(cue: int, at: float) -> Image.Image:
@@ -226,43 +336,71 @@ def compose_frames(timeline: NarrationTimeline, plan: LongcutPlan, poster: Image
frame = background.copy() frame = background.copy()
frame.paste(fitted, (0, (H - fitted.height) // 2)) frame.paste(fitted, (0, (H - fitted.height) // 2))
return frame return frame
start, end = starts[cue], bounds[cue] start, end = spans[cue]
progress = (at - start) / max(end - start, 0.01) progress = (at - start) / max(end - start, 0.01)
if scene.kind == "scroll" and scene.section in scroll_images: if scene.kind == "scroll" and scene.source in surfaces:
return scroll_scene(scroll_images[scene.section], background, progress, end - start) return scroll_scene(surfaces[scene.source], progress,
scene.y0 or 0.0, scene.y1 or 0.0)
return poster_scene(poster, background, progress) return poster_scene(poster, background, progress)
total_frames = round(timeline.total * FPS) total_frames = round(timeline.total * FPS)
for index in range(total_frames): for index in range(total_frames):
at = index / FPS at = index / FPS
cue = max(order for order in range(len(timeline.cues)) if at >= starts[order]) cue = max(order for order, (start, _) in enumerate(spans) if at >= start)
image = frame_at(cue, at) image = frame_at(cue, at)
remaining = (bounds[cue] - at) * FPS remaining = (spans[cue][1] - at) * FPS
if cue < len(timeline.cues) - 1 and remaining < CROSSFADE_FRAMES \ if cue < len(spans) - 1 and remaining < CROSSFADE_FRAMES \
and scenes[cue + 1].kind != "clip": and scenes[cue + 1].kind != "clip":
image = Image.blend(image, frame_at(cue + 1, at), 1 - remaining / CROSSFADE_FRAMES) image = Image.blend(image, frame_at(cue + 1, at), 1 - remaining / CROSSFADE_FRAMES)
if scenes[cue].kind == "poster": if scenes[cue].kind == "poster":
end_band(image, info, at - starts[cue], qr) end_band(image, info, at - spans[cue][0], qr)
yield image 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, def compose_longcut(poster: bytes | Path | Image.Image, clip: bytes,
timeline: NarrationTimeline, narration_mp3: bytes, timeline: NarrationTimeline, narration_mp3: bytes,
sections: Sequence[DetailSection], info: EndBandInfo, *, sections: Sequence[DetailSection], info: EndBandInfo, *,
details: dict[str, Image.Image] | None = None,
bgm_mp3: bytes | None = None, qr: Image.Image | None = None, bgm_mp3: bytes | None = None, qr: Image.Image | None = None,
plan: LongcutPlan | None = None) -> LongcutResult: plan: LongcutPlan | None = None,
preview: bool = False) -> LongcutResult:
"""details는 source 이름(detail_01…) → 상세페이지 롱이미지. 스크롤은 이 위에서 일어난다."""
if isinstance(poster, Image.Image): if isinstance(poster, Image.Image):
source = poster.convert("RGB") source = poster.convert("RGB")
else: else:
source = Image.open(poster if isinstance(poster, Path) source = Image.open(poster if isinstance(poster, Path)
else io.BytesIO(poster)).convert("RGB") else io.BytesIO(poster)).convert("RGB")
plan = plan or build_scene_plan(sections, len(timeline.cues)) sources = dict(details or {})
used = {scene.section for scene in plan.scenes if scene.section} surfaces = {name: to_surface(image) for name, image in sources.items()}
images = {section.name: section.image for section in sections if section.name in used} spans = cue_spans(timeline)
plan = plan or build_scene_plan(sections, spans, sources, surfaces)
frames = compose_frames(timeline, plan, source, clip, images, info, qr) total_frames = round(timeline.total * FPS)
video = encode_mp4(frames, (W, H), mix_audio(narration_mp3, bgm_mp3, timeline.total), # 훅 구간만 보면 뒤쪽 스크롤과 엔드밴드를 검수할 수 없어 전체에서 고르게 뽑는다
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) fps=FPS)
return LongcutResult(video=video, duration=timeline.total, return LongcutResult(video=video, thumbnail=thumbnail.getvalue(),
frames=round(timeline.total * FPS), plan=plan) duration=timeline.total, frames=total_frames,
plan=plan, proof=proof_sheet(tiles) if tiles else None)
+126
View File
@@ -0,0 +1,126 @@
"""스타일링 ③ — 생성된 포스터 하단에 정보 밴드를 그린다
큰 제목은 생성 모델이 대체로 맞추지만 작은 글자에서 자모를 흘린다
(동대문구 → 몽대문구, 체험존 → 채헐존). 프롬프트로는 더 못 밀어낸다.
그래서 날짜·시간·장소는 모델에 맡기지 않고 실제 폰트로 직접 그린다.
밴드 색은 이미지 하단에서 뽑아 얹은 티를 줄인다.
"""
from PIL import Image, ImageDraw, ImageFilter, ImageFont
from answers.poster_text_answer import PosterTextAnswer
from 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
+37
View File
@@ -0,0 +1,37 @@
"""스타일링 ① — 포스터에 인쇄된 글자를 읽는다
이미지 생성 모델은 한글을 다시 그리며 자모를 바꾼다(맥주축제 → 백주축제).
프롬프트로는 못 막으므로 읽기를 먼저 하고 그 문자열을 생성 프롬프트에 못 박는다.
"""
from PIL import Image
from answers.poster_text_answer import PosterTextAnswer
from settings import settings
from utils.common_llm import StructuredLLM
from utils.image import to_data_uri
from 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", 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 answers.style_prompt_answer import StylePromptAnswer
from models.styling import ReferenceVariants
from settings import settings
from utils.common_llm import StructuredLLM
from utils.image import to_data_uri
from 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", 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
+144
View File
@@ -0,0 +1,144 @@
"""스타일링 ④ — 포스터를 레퍼런스 화풍으로 다시 그린다
내부 검토용이다. 번들 레퍼런스의 권리가 남아 있어 결과물을 그대로 밖에 내지 않는다.
"""
import base64
import io
import httpx
from PIL import Image
from answers.poster_text_answer import PosterTextAnswer
from models.styling import OutputFormat, StyleTemplate, TransferResult
from services.styling.info_band import compose_info_band
from services.styling.poster_text import read_poster_text
from settings import 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 {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)
+13 -15
View File
@@ -3,6 +3,9 @@
"파일이 존재하는가"만 보던 검증 탓에 구름이 제목을 덮은 클립이 검수대까지 간 적이 있다. "파일이 존재하는가"만 보던 검증 탓에 구름이 제목을 덮은 클립이 검수대까지 간 적이 있다.
픽셀 지표 하나로는 갈리지 않아서 — 영역 평균차는 제목 뒤 불꽃과 제목 위 구름을 구분 못 하고 픽셀 지표 하나로는 갈리지 않아서 — 영역 평균차는 제목 뒤 불꽃과 제목 위 구름을 구분 못 하고
글리프 휘도차는 흰 구름이 흰 글자를 덮으면 0에 수렴한다 — 2단을 VLM 가독성 판정으로 둔다. 글리프 휘도차는 흰 구름이 흰 글자를 덮으면 0에 수렴한다 — 2단을 VLM 가독성 판정으로 둔다.
두 단 모두 첫 프레임을 기준으로 삼는다. detect가 읽은 제목 문자열과는 대조하지 않는다 —
상자가 제목의 일부만 덮으면 잘려 나간 글자를 훼손으로 오인한다.
""" """
import numpy as np import numpy as np
from PIL import Image from PIL import Image
@@ -76,18 +79,20 @@ def pixel_score(crops: list[Image.Image]) -> float | None:
for crop in crops[1:]) for crop in crops[1:])
async def ask_legibility(crops: list[Image.Image], times: list[float], async def ask_legibility(crops: list[Image.Image], times: list[float]) -> TitleGateAnswer:
title: str) -> TitleGateAnswer: """[0]이 기준이다. 옮겨 적은 제목과 대조하지 않는다 —
images = [(f"[{index}] t={at}s:", to_data_uri(crop, CROP_MAX_SIZE)) 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))] for index, (crop, at) in enumerate(zip(crops, times, strict=True))]
return await title_gate_llm.ask_with_images( return await title_gate_llm.ask_with_images(
TitleGateAnswer, TitleGateAnswer,
f"기대 제목: {title!r}\n시점 {len(crops)}장. 각 이미지를 순서대로 판정하라.", f"시점 {len(crops)}장. [0]을 기준으로 각 이미지를 순서대로 판정하라.",
images, system=TITLE_GATE_PROMPT) images, system=TITLE_GATE_PROMPT)
async def check_title(clip: bytes, regions: Regions) -> TitleGateVerdict: async def check_title(clip: bytes, regions: Regions) -> TitleGateVerdict:
"""판단 근거가 없으면(제목 상자·텍스트 없음) 통과시키고 사유를 남긴다.""" """제목 상자가 없으면 판단 근거가 없으므로 통과시키고 사유를 남긴다."""
clip_seconds = duration(clip) clip_seconds = duration(clip)
times = [round(max(0.0, min(clip_seconds - 0.05, fraction * clip_seconds)), 2) times = [round(max(0.0, min(clip_seconds - 0.05, fraction * clip_seconds)), 2)
for fraction in SAMPLE_FRACTIONS] for fraction in SAMPLE_FRACTIONS]
@@ -99,26 +104,19 @@ async def check_title(clip: bytes, regions: Regions) -> TitleGateVerdict:
crops = [frame.crop(box) for frame in frames] crops = [frame.crop(box) for frame in frames]
score = pixel_score(crops) score = pixel_score(crops)
title = (regions.regions["title"].text or "").strip()
verdict = TitleGateVerdict(passed=True, samples=times, verdict = TitleGateVerdict(passed=True, samples=times,
pixel_score=round(score, 2) if score is not None else None) pixel_score=round(score, 2) if score is not None else None)
if score is not None and score > PIXEL_HARD_FAIL: if score is not None and score > PIXEL_HARD_FAIL:
# 정렬 후에도 넘는 값은 대개 배경 통과라 즉시 실패시키지 않고 VLM으로 넘긴다 # 정렬 후에도 넘는 값은 대개 배경 통과라 즉시 실패시키지 않고 VLM으로 넘긴다
verdict.pixel_hard = True verdict.pixel_hard = True
if not title:
verdict.passed = False
verdict.reason = f"획변화 {score:.1f} > {PIXEL_HARD_FAIL}, title.text 없어 VLM 판정 불가"
return verdict
if not title:
verdict.skip = "title.text 없음 — VLM 가독성 판정 불가"
return verdict
answer = await ask_legibility(crops, times, title) answer = await ask_legibility(crops, times)
verdict.frames = [FrameVerdict(index=frame.index, time=times[frame.index], verdict.frames = [FrameVerdict(index=frame.index, time=times[frame.index],
legible=frame.legible, broken=frame.broken) legible=frame.legible, broken=frame.broken)
for frame in answer.frames if frame.index < len(times)] for frame in answer.frames if frame.index < len(times)]
broken = [frame for frame in verdict.frames if not frame.legible] # [0]은 원본이라 판정 대상이 아니다
broken = [frame for frame in verdict.frames if not frame.legible and frame.index > 0]
if broken: if broken:
verdict.passed = False verdict.passed = False
verdict.reason = "제목 가독 훼손: " + "; ".join( verdict.reason = "제목 가독 훼손: " + "; ".join(
+14 -1
View File
@@ -31,6 +31,16 @@ def load_sections(sections_dir: Path) -> list[DetailSection]:
for item in json.loads(index_path.read_text(encoding="utf-8"))] for item in json.loads(index_path.read_text(encoding="utf-8"))]
def load_details(product_dir: Path) -> dict[str, Image.Image]:
"""상세페이지 롱이미지. 스크롤은 조각이 아니라 이 위에서 일어난다."""
details = {}
for path in sorted((product_dir / "details").glob("detail_*.*")):
details[path.stem] = Image.open(path)
if not details:
raise SystemExit(f"{product_dir / 'details'} 비었음 — test_fetch_nol 을 먼저 돌릴 것")
return details
def band_info(meta: NolMeta) -> EndBandInfo: def band_info(meta: NolMeta) -> EndBandInfo:
period = f"{meta.play_start_date or ''} ~ {meta.play_end_date or ''}".strip(" ~") period = f"{meta.play_start_date or ''} ~ {meta.play_end_date or ''}".strip(" ~")
detail = " · ".join(part for part in (period.replace("-", "."), meta.place_name) if part) detail = " · ".join(part for part in (period.replace("-", "."), meta.place_name) if part)
@@ -66,6 +76,7 @@ def main() -> None:
product_dir / "upscaled.png", clip_path.read_bytes(), timeline, product_dir / "upscaled.png", clip_path.read_bytes(), timeline,
(product_dir / "narration.mp3").read_bytes(), (product_dir / "narration.mp3").read_bytes(),
load_sections(product_dir / "sections"), band_info(meta), load_sections(product_dir / "sections"), band_info(meta),
details=load_details(product_dir),
bgm_mp3=bgm_path.read_bytes() if bgm_path.exists() else None, bgm_mp3=bgm_path.read_bytes() if bgm_path.exists() else None,
qr=Image.open(qr_path) if qr_path.exists() else None) qr=Image.open(qr_path) if qr_path.exists() else None)
@@ -75,7 +86,9 @@ def main() -> None:
for scene in result.plan.scenes: for scene in result.plan.scenes:
label = f"{scene.section} [{scene.tag}]" if scene.section else "" label = f"{scene.section} [{scene.tag}]" if scene.section else ""
print(f" 큐{scene.cue} {scene.kind:7} {label}") span = (f" {scene.source} {scene.y0:.3f}→{scene.y1:.3f}"
if scene.kind == "scroll" else "")
print(f" 큐{scene.cue} {scene.kind:7} {label}{span}")
if not qr_path.exists(): if not qr_path.exists():
print(f"※ {qr_path.name} 없음 — 엔드밴드에 QR을 안 넣는다") print(f"※ {qr_path.name} 없음 — 엔드밴드에 QR을 안 넣는다")
print(f"\n{result.frames}프레임 · {result.duration:.2f}초 · {len(result.video) / 1e6:.1f}MB") print(f"\n{result.frames}프레임 · {result.duration:.2f}초 · {len(result.video) / 1e6:.1f}MB")
+16 -1
View File
@@ -5,6 +5,7 @@ SAS 토큰을 붙인 URL로 PUT 한 번. 경로 규칙은 부르는 쪽이 정
""" """
import mimetypes import mimetypes
from pathlib import Path from pathlib import Path
from urllib.parse import quote
import httpx import httpx
@@ -60,12 +61,26 @@ def with_sas(url: str) -> str:
return url return url
async def upload_bytes(data: bytes, path: str, content_type: str | None = None) -> str: def as_attachment(filename: str) -> str:
"""이 값이 붙은 blob은 브라우저가 열면 내려받기가 된다.
<a download>은 다른 출처에 안 먹어 완성본은 이 길로 간다.
한글 파일명은 RFC 5987 형식이라야 온전히 건너간다.
"""
return f"attachment; filename*=UTF-8''{quote(filename)}"
async def upload_bytes(data: bytes, path: str, content_type: str | None = None,
disposition: str | None = None) -> str:
"""path 예: playreel/nol_26007416/clip.mp4. 공개 URL을 돌려준다.""" """path 예: playreel/nol_26007416/clip.mp4. 공개 URL을 돌려준다."""
if not settings.azure_blob_base_url or not settings.azure_blob_sas_token: if not settings.azure_blob_base_url or not settings.azure_blob_sas_token:
raise RuntimeError("AZURE_BLOB_BASE_URL / AZURE_BLOB_SAS_TOKEN 없음") raise RuntimeError("AZURE_BLOB_BASE_URL / AZURE_BLOB_SAS_TOKEN 없음")
headers = {"Content-Type": content_type or guess_content_type(path), **BLOB_TYPE_HEADER} headers = {"Content-Type": content_type or guess_content_type(path), **BLOB_TYPE_HEADER}
if disposition:
# 헤더 이름이 Content-Disposition이면 이 요청 본문의 성격으로 읽힌다.
# blob 속성으로 저장되는 것은 x-ms- 쪽이다
headers["x-ms-blob-content-disposition"] = disposition
response = await get_client().put(upload_url(path), content=data, headers=headers) response = await get_client().put(upload_url(path), content=data, headers=headers)
if response.status_code not in (200, 201): if response.status_code not in (200, 201):
print(f"[blob] 업로드 실패 {response.status_code} {path}: {response.text[:300]}", print(f"[blob] 업로드 실패 {response.status_code} {path}: {response.text[:300]}",
+4 -1
View File
@@ -1,3 +1,5 @@
# 앞에 아파치가 선다 (playreel.o2o.kr → / 는 30100, /api 는 30101).
# 아파치가 다른 장비라 포트는 열어두고, 그 장비만 오도록 막는 것은 방화벽이 맡는다.
services: services:
backend: backend:
build: ./backend build: ./backend
@@ -18,7 +20,8 @@ services:
ports: ports:
- "30100:30100" - "30100:30100"
environment: environment:
# Next 리라이트가 /api/* 를 여기로 넘긴다 # 아파치가 /api 를 백엔드로 바로 보내므로 운영에서는 안 쓰인다.
# 아파치 없이 띄울 때 proxy.ts 가 이 값으로 넘긴다.
API_ORIGIN: http://backend:30101 API_ORIGIN: http://backend:30101
depends_on: depends_on:
- backend - backend
+3 -3
View File
@@ -14,9 +14,9 @@ export default function Ado2Layout({ children }: { children: React.ReactNode })
<> <>
<aside className="sidebar"> <aside className="sidebar">
<div className="sidebar-logo"> <div className="sidebar-logo">
<Link href="/" style={{ color: "var(--color-text-white)", display: "inline-flex", alignItems: "baseline", gap: 8, textDecoration: "none" }}> <Link href="/" className="mp-wordmark">
<Ado2Logo height={20} /> <Ado2Logo height={24} />
<span className="sidebar-product">MOVING POSTER</span> <span className="mp-mark">MOVING POSTER</span>
</Link> </Link>
</div> </div>
<nav className="sidebar-menu"> <nav className="sidebar-menu">
+11 -3
View File
@@ -5,7 +5,7 @@ import Link from "next/link";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import StageStepper, { stageProgress } from "@/components/stage-stepper"; import StageStepper, { stageProgress } from "@/components/stage-stepper";
import MetadataCard from "@/components/metadata-card"; import MetadataCard from "@/components/metadata-card";
import { apiFetch, useJob } from "@/lib/api"; import { apiFetch, useJob, type Job } from "@/lib/api";
const SUBTITLES: Record<string, string> = { const SUBTITLES: Record<string, string> = {
queued: "대기 중입니다. 앞선 작업이 끝나면 자동으로 시작됩니다", queued: "대기 중입니다. 앞선 작업이 끝나면 자동으로 시작됩니다",
@@ -115,6 +115,12 @@ export default function JobPage({ params }: { params: Promise<{ id: string }> })
}); });
refresh(); refresh();
} catch (e) { } catch (e) {
// 실패 화면을 띄워둔 사이에 끝났을 수 있다. 그때는 에러 대신 결과를 보여준다
const latest = await apiFetch<Job>(`/api/f1/jobs/${id}`).catch(() => null);
if (latest?.status === "done") {
refresh();
return;
}
setActionError((e as Error).message); setActionError((e as Error).message);
} finally { } finally {
setBusy(false); setBusy(false);
@@ -316,10 +322,12 @@ export default function JobPage({ params }: { params: Promise<{ id: string }> })
</div> </div>
)} )}
<div style={{ marginTop: "auto", paddingTop: "1.5rem", display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0.75rem" }}> <div style={{ marginTop: "auto", paddingTop: "1.5rem", display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0.75rem" }}>
{/* blob에 Content-Disposition이 박혀 있어 주소만 열면 내려받기가 된다.
<a download>은 다른 출처에 안 먹으므로 이 속성에 기대지 않는다 */}
{job.artifacts.thumbnail ? ( {job.artifacts.thumbnail ? (
<a href={job.artifacts.thumbnail} download className="btn-tonal-mint">정지 컷 JPG</a> <a href={job.artifacts.thumbnail} className="btn-tonal-mint">정지 컷 JPG</a>
) : <span />} ) : <span />}
<a href={job.artifacts.video} download className="btn-cta" <a href={job.artifacts.video} className="btn-cta"
style={{ padding: "0.75rem 1rem", fontSize: "var(--text-base)", borderRadius: "var(--radius-xl)", textDecoration: "none" }}> style={{ padding: "0.75rem 1rem", fontSize: "var(--text-base)", borderRadius: "var(--radius-xl)", textDecoration: "none" }}>
MP4 다운로드 MP4 다운로드
</a> </a>
+10 -2
View File
@@ -6,7 +6,7 @@ import { useRouter, useSearchParams } from "next/navigation";
import StageStepper, { stageProgress } from "@/components/stage-stepper"; import StageStepper, { stageProgress } from "@/components/stage-stepper";
import { GateBody, GateShell } from "@/components/gate-card"; import { GateBody, GateShell } from "@/components/gate-card";
import { apiFetch } from "@/lib/api"; import { apiFetch } from "@/lib/api";
import { GATE_META, PLAYREEL_STAGE_LABELS, usePlayreelJob } from "@/lib/playreel"; import { GATE_META, PLAYREEL_STAGE_LABELS, usePlayreelJob, type PlayreelJob } from "@/lib/playreel";
import { useAutoApprove } from "@/lib/prefs"; import { useAutoApprove } from "@/lib/prefs";
import { isAutoApprovable } from "@/components/auto-approve"; import { isAutoApprovable } from "@/components/auto-approve";
@@ -70,6 +70,12 @@ export default function PlayreelJobPage({ params }: { params: Promise<{ id: stri
edits.current = null; edits.current = null;
refresh(); refresh();
} catch (e) { } catch (e) {
// 실패 화면을 띄워둔 사이에 끝났을 수 있다. 그때는 에러 대신 결과를 보여준다
const latest = await apiFetch<PlayreelJob>(`/api/playreel/jobs/${id}`).catch(() => null);
if (latest?.status === "done") {
refresh();
return;
}
setActionError((e as Error).message); setActionError((e as Error).message);
} finally { } finally {
setBusy(false); setBusy(false);
@@ -170,7 +176,9 @@ export default function PlayreelJobPage({ params }: { params: Promise<{ id: stri
<p style={{ margin: 0, fontSize: "var(--text-sm)", color: "var(--color-text-gray-400)" }}>출처 · <a href={job.source.url} target="_blank" rel="noreferrer" style={{ color: "var(--color-mint)" }}>공연 상품페이지 열기 →</a></p> <p style={{ margin: 0, fontSize: "var(--text-sm)", color: "var(--color-text-gray-400)" }}>출처 · <a href={job.source.url} target="_blank" rel="noreferrer" style={{ color: "var(--color-mint)" }}>공연 상품페이지 열기 →</a></p>
<div className="result-actions"> <div className="result-actions">
<Link href="/" className="btn-tonal-mint" style={{ textDecoration: "none", textAlign: "center" }}>새 버전 만들기</Link> <Link href="/" className="btn-tonal-mint" style={{ textDecoration: "none", textAlign: "center" }}>새 버전 만들기</Link>
<a href={job.artifacts.video} download className="btn-cta" style={{ padding: "0.75rem 1rem", fontSize: "var(--text-base)", borderRadius: "var(--radius-xl)", textDecoration: "none" }}>MP4 다운로드</a> {/* blob에 Content-Disposition이 박혀 있어 주소만 열면 내려받기가 된다.
<a download>은 다른 출처에 안 먹으므로 이 속성에 기대지 않는다 */}
<a href={job.artifacts.video} className="btn-cta" style={{ padding: "0.75rem 1rem", fontSize: "var(--text-base)", borderRadius: "var(--radius-xl)", textDecoration: "none" }}>MP4 다운로드</a>
</div> </div>
</div> </div>
</div> </div>
+14
View File
@@ -419,6 +419,19 @@ body { margin: 0; -webkit-font-smoothing: antialiased; letter-spacing: -0.006em;
.note a { color: var(--color-mint); } .note a { color: var(--color-mint); }
.sidebar-product { font-size: 10px; font-weight: 800; letter-spacing: 0.1em; color: var(--color-mint); white-space: nowrap; } .sidebar-product { font-size: 10px; font-weight: 800; letter-spacing: 0.1em; color: var(--color-mint); white-space: nowrap; }
/* ── (ado2) 셸 워드마크 — Playreel 락업(.pr-wordmark)과 같은 문법 ──
ADO2 로고 위 · 제품 워드마크 아래. 아래 줄을 로고 폭에 맞춰 락업이 사각형으로 앉는다.
로고 폭은 height × 149/22 이므로 h24 = 162.5px. MOVING POSTER 는 PLAYREEL 보다
글자가 길어 자간·크기를 그 폭에 맞게 따로 잡았다(실측으로 맞춤). */
.mp-wordmark { display: inline-flex; flex-direction: column; gap: 6px; text-decoration: none; align-items: flex-start; }
.mp-wordmark svg { color: var(--color-text-gray-300); }
.mp-mark {
/* 16.4px + 0.14em 에서 글자 잉크 폭이 162.3px — 로고(h24 = 162.5px)와 0.2px 차이다.
자간은 마지막 글자 뒤에도 붙으므로 그만큼 음수 마진으로 걷어내야 오른쪽 끝이 맞는다. */
font-size: 16.4px; font-weight: 800; letter-spacing: 0.14em; margin-right: -0.14em;
color: var(--color-text-white); line-height: 1; white-space: nowrap;
}
.entry-stack { display: flex; flex-direction: column; gap: 0.75rem; width: 100%; max-width: 560px; margin-top: 1.5rem; } .entry-stack { display: flex; flex-direction: column; gap: 0.75rem; width: 100%; max-width: 560px; margin-top: 1.5rem; }
.entry { display: flex; flex-direction: column; gap: 0.85rem; padding: 1.25rem; position: relative; } .entry { display: flex; flex-direction: column; gap: 0.85rem; padding: 1.25rem; position: relative; }
.entry--hot { border-color: var(--color-mint-30); } .entry--hot { border-color: var(--color-mint-30); }
@@ -471,6 +484,7 @@ body { margin: 0; -webkit-font-smoothing: antialiased; letter-spacing: -0.006em;
.sidebar-menu { flex: 1; min-width: 0; overflow-x: auto; scrollbar-width: none; } .sidebar-menu { flex: 1; min-width: 0; overflow-x: auto; scrollbar-width: none; }
.sidebar-menu::-webkit-scrollbar { display: none; } .sidebar-menu::-webkit-scrollbar { display: none; }
.sidebar-product { display: none; } .sidebar-product { display: none; }
/* 워드마크는 남긴다 — Playreel 셸(.pr-mark)과 같은 처리 */
.playreel-steps { grid-template-columns: repeat(2, 1fr); } .playreel-steps { grid-template-columns: repeat(2, 1fr); }
.result-grid { grid-template-columns: 1fr; } .result-grid { grid-template-columns: 1fr; }
.result-grid .result-video { min-height: 240px; } .result-grid .result-video { min-height: 240px; }
+47 -14
View File
@@ -8,8 +8,8 @@
import { useState } from "react"; import { useState } from "react";
import { import {
GATE_META, type AnalysisReview, type ClipReview, type FetchReview, type FinalReview, GATE_META, type AnalysisReview, type ClipReview, type DetailSection, type FetchReview,
type GateKey, type GateReview, type NarrationReview, type FinalReview, type GateKey, type GateReview, type NarrationReview,
} from "@/lib/playreel"; } from "@/lib/playreel";
// ── 공통 셸 ────────────────────────────────────────────────────────── // ── 공통 셸 ──────────────────────────────────────────────────────────
@@ -85,6 +85,46 @@ function Warn({ children }: { children: React.ReactNode }) {
const two = { display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: "var(--spacing-page-md)", alignItems: "start" } as const; const two = { display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: "var(--spacing-page-md)", alignItems: "start" } as const;
// 상세페이지 조각은 라벨이 겹친다 — "유의사항"만 일곱 개인 페이지가 흔하다.
// 칩으로 그리면 같은 글자가 줄줄이 서서 무엇을 고르는지 알 수 없어 썸네일을 그린다.
function SectionPicker({ sections, onToggle }: {
sections: DetailSection[]; onToggle: (id: string) => void;
}) {
const chosen = sections.filter((s) => s.selected).length;
return (
<>
<p className="field-label" style={{ margin: "1.5rem 0 0.35rem" }}>상세페이지에서 훑기 시작할 지점</p>
<p style={{ margin: "0 0 0.7rem", fontSize: "var(--text-xs)", color: "var(--color-text-gray-500)", lineHeight: 1.5 }}>
고른 지점부터 상세페이지를 이어서 훑습니다. 조각을 잘라 붙이는 것이 아닙니다.
</p>
<div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(84px, 1fr))", gap: 8, maxHeight: 340, overflowY: "auto", paddingRight: 4 }}>
{sections.map((s, i) => (
<button key={s.id} type="button" title={`${s.label} · ${s.height.toLocaleString()}px`}
onClick={s.required ? undefined : () => onToggle(s.id)}
style={{
position: "relative", padding: 0, borderRadius: "var(--radius-md)", overflow: "hidden",
cursor: s.required ? "default" : "pointer", textAlign: "left", background: "transparent",
border: s.selected ? "2px solid var(--color-mint)" : "2px solid var(--color-border-white-10)",
opacity: s.selected ? 1 : 0.5,
}}>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={s.thumb_url} alt={s.label}
style={{ width: "100%", aspectRatio: "3 / 4", objectFit: "cover", objectPosition: "top", display: "block", background: "#000" }} />
<span style={{ position: "absolute", top: 4, left: 4, minWidth: 16, padding: "1px 4px", borderRadius: 4, background: "rgba(0,0,0,0.65)", color: "#fff", fontSize: 10, textAlign: "center" }}>{i + 1}</span>
<span style={{ display: "flex", alignItems: "center", gap: 4, padding: "3px 5px", fontSize: 10, lineHeight: 1.3, background: "rgba(0,0,0,0.65)", color: s.selected ? "var(--color-mint)" : "var(--color-text-gray-400)" }}>
{s.required ? <Lock size={10} /> : s.selected ? <Ico d={CHECK} size={10} /> : <Ico d={PLUS} size={10} />}
<span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{s.label}</span>
</span>
</button>
))}
</div>
<p style={{ margin: "0.6rem 0 0", fontSize: "var(--text-xs)", color: "var(--color-text-gray-500)", display: "flex", alignItems: "center", gap: 6 }}>
<Lock size={11} /> {sections.length}개 중 {chosen}개 선택 · 캐스팅 스케줄은 항상 포함됩니다.
</p>
</>
);
}
// ── ① 수집 확인 ─────────────────────────────────────────────────────── // ── ① 수집 확인 ───────────────────────────────────────────────────────
export function FetchGate({ data, onChange }: { data: FetchReview; onChange: (edits: { sections: string[]; meta: FetchReview["meta"] }) => void }) { export function FetchGate({ data, onChange }: { data: FetchReview; onChange: (edits: { sections: string[]; meta: FetchReview["meta"] }) => void }) {
const [sections, setSections] = useState(data.sections); const [sections, setSections] = useState(data.sections);
@@ -106,18 +146,11 @@ export function FetchGate({ data, onChange }: { data: FetchReview; onChange: (ed
캐스트 · {meta.cast.join(", ")} 캐스트 · {meta.cast.join(", ")}
</p> </p>
<p className="field-label" style={{ margin: "1.5rem 0 0.5rem" }}>영상에 넣을 상세페이지 부분</p> <SectionPicker sections={sections}
<div style={{ display: "flex", flexWrap: "wrap", gap: "0.5rem" }}> onToggle={(id) => {
{sections.map((s) => ( const n = sections.map((x) => x.id === id ? { ...x, selected: !x.selected } : x);
<Chip key={s.id} on={s.selected} locked={s.required} setSections(n); emit(n);
onClick={() => { const n = sections.map((x) => x.id === s.id ? { ...x, selected: !x.selected } : x); setSections(n); emit(n); }}> }} />
{s.label}
</Chip>
))}
</div>
<p style={{ margin: "0.6rem 0 0", fontSize: "var(--text-xs)", color: "var(--color-text-gray-500)", display: "flex", alignItems: "center", gap: 6 }}>
<Lock size={11} /> 캐스팅 스케줄은 항상 포함됩니다.
</p>
{data.poster_width <= 800 && ( {data.poster_width <= 800 && (
<Warn>포스터가 {data.poster_width}px로 작습니다. 다음 단계에서 화질을 2배 보정합니다(2크레딧). 원본 파일이 있으면 무빙포스터 경로에서 직접 올리는 편이 더 선명합니다.</Warn> <Warn>포스터가 {data.poster_width}px로 작습니다. 다음 단계에서 화질을 2배 보정합니다(2크레딧). 원본 파일이 있으면 무빙포스터 경로에서 직접 올리는 편이 더 선명합니다.</Warn>
)} )}
+2 -3
View File
@@ -3,10 +3,9 @@
* 백엔드에 대응하는 API가 없는 화면을 여기서 끈다 — 페이지 코드는 그대로 두고 * 백엔드에 대응하는 API가 없는 화면을 여기서 끈다 — 페이지 코드는 그대로 두고
* 네비게이션에서 감추고 본문 대신 안내를 띄운다. * 네비게이션에서 감추고 본문 대신 안내를 띄운다.
* *
* styling /studio — /api/f2 없음 * styling /studio — /api/f2 없음
* archive /archive · /playreel/archive — /api/archive 없음
*/ */
export const FEATURES = { export const FEATURES = {
styling: false, styling: false,
archive: false, archive: true,
} as const; } as const;
+20 -8
View File
@@ -101,6 +101,8 @@ export function parseGoodsId(url: string): string | null {
const s = url.trim(); const s = url.trim();
if (!s) return null; if (!s) return null;
const m = const m =
// 인터파크 주소는 야놀자로 리다이렉트된다. 상품 번호는 양쪽이 같다
s.match(/nol\.yanolja\.com\/ticket\/products\/(\d{5,})/i) ??
s.match(/tickets\.interpark\.com\/goods\/(\d{5,})/i) ?? s.match(/tickets\.interpark\.com\/goods\/(\d{5,})/i) ??
s.match(/nol\.interpark\.com\/[^?]*?(\d{8,})/i) ?? s.match(/nol\.interpark\.com\/[^?]*?(\d{8,})/i) ??
s.match(/[?&]goodsCode=(\d{5,})/i) ?? s.match(/[?&]goodsCode=(\d{5,})/i) ??
@@ -156,6 +158,23 @@ const PH = (w: number, h: number, text: string) =>
`<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}"><rect width="100%" height="100%" fill="#003538"/><text x="50%" y="50%" fill="#a6ffea" font-size="20" font-family="sans-serif" text-anchor="middle" dominant-baseline="middle">${text}</text></svg>`, `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}"><rect width="100%" height="100%" fill="#003538"/><text x="50%" y="50%" fill="#a6ffea" font-size="20" font-family="sans-serif" text-anchor="middle" dominant-baseline="middle">${text}</text></svg>`,
)}`; )}`;
// 실물이 오는 모양. 심규선 콘서트 상세페이지 실측 19조각이다 — 라벨이 겹치고 대부분 공지다.
// 이 자리에 6개짜리 깔끔한 목을 두었다가 게이트 ①이 같은 글자 열아홉 개만 뱉는 걸 놓쳤다.
const MOCK_SECTIONS: DetailSection[] = ([
["keyvisual", "키비주얼", 1108], ["synopsis", "작품 소개", 313], ["fragment", "조각", 244],
["info", "관람 정보", 270], ["notice", "유의사항", 608], ["info", "관람 정보", 346],
["fragment", "조각", 270], ["notice", "유의사항", 887], ["schedule", "캐스팅 스케줄", 582],
["notice", "유의사항", 1149], ["notice", "유의사항", 968], ["info", "관람 정보", 383],
["discount", "할인 안내", 473], ["fragment", "조각", 285], ["notice", "유의사항", 875],
["notice", "유의사항", 1063], ["fragment", "조각", 152], ["notice", "유의사항", 1068],
["info", "관람 정보", 371],
] as const).map(([tag, label, height], i) => ({
id: `detail_01_s${String(i + 1).padStart(2, "0")}`,
tag, label, height, thumb_url: PH(180, 240, String(i + 1)),
required: tag === "schedule" || undefined,
selected: tag !== "fragment",
}));
export function mockJob(gate: GateKey | "running" | "done" | "failed"): PlayreelJob { export function mockJob(gate: GateKey | "running" | "done" | "failed"): PlayreelJob {
const base: PlayreelJob = { const base: PlayreelJob = {
id: "mock", kind: "playreel", name: "뮤지컬 〈겨울왕국〉", status: "awaiting_review", stage: null, id: "mock", kind: "playreel", name: "뮤지컬 〈겨울왕국〉", status: "awaiting_review", stage: null,
@@ -176,14 +195,7 @@ export function mockJob(gate: GateKey | "running" | "done" | "failed"): Playreel
return { ...base, gate, stages: stages(2), review: { gate, data: { return { ...base, gate, stages: stages(2), review: { gate, data: {
poster_url: PH(300, 420, "포스터 750px"), poster_width: 750, poster_url: PH(300, 420, "포스터 750px"), poster_width: 750,
meta: { title: "뮤지컬 〈겨울왕국〉", date_text: "2026.11.25 ~ 2027.03.01", place: "샤롯데씨어터", cast: ["박혜나", "정선아", "이지혜"], genre: "뮤지컬" }, meta: { title: "뮤지컬 〈겨울왕국〉", date_text: "2026.11.25 ~ 2027.03.01", place: "샤롯데씨어터", cast: ["박혜나", "정선아", "이지혜"], genre: "뮤지컬" },
sections: [ sections: MOCK_SECTIONS,
{ id: "s1", tag: "story", label: "작품 소개", thumb_url: PH(160, 90, "소개"), height: 1800, selected: true },
{ id: "s2", tag: "awards", label: "수상·세계관", thumb_url: PH(160, 90, "수상"), height: 900, selected: true },
{ id: "s3", tag: "cast", label: "캐스트", thumb_url: PH(160, 90, "캐스트"), height: 1400, selected: true },
{ id: "s4", tag: "schedule", label: "캐스팅 스케줄", thumb_url: PH(160, 90, "스케줄"), height: 2200, required: true, selected: true },
{ id: "s5", tag: "discount", label: "할인 안내", thumb_url: PH(160, 90, "할인"), height: 700, selected: true },
{ id: "s6", tag: "notice", label: "유의사항", thumb_url: PH(160, 90, "유의"), height: 1200, selected: false },
],
} } }; } } };
case "analysis_confirm": case "analysis_confirm":
return { ...base, gate, stages: stages(4), credits_used: 2, review: { gate, data: { return { ...base, gate, stages: stages(4), credits_used: 2, review: { gate, data: {
+30
View File
@@ -147,6 +147,18 @@ aspect_ratio·sound는 실질 문제가 아닐 수 있다. Kling은 9:16을 지
이 머신에 higgsfield CLI가 없다. `result_url`·`credits` 정규식 파싱은 원본을 옮겼을 뿐 이 머신에 higgsfield CLI가 없다. `result_url`·`credits` 정규식 파싱은 원본을 옮겼을 뿐
실제 CLI 출력으로 확인한 것이 아니다. 실제 CLI 출력으로 확인한 것이 아니다.
## 잡 테이블
### is_low_resolution 컬럼이 항상 False다
저해상 거절이 ⑥ i2v에 있어서, 거기까지 가면 detect·나레이션·TTS·BGM을 다 쓰고 터졌다.
같은 기준(`MIN_LONG_EDGE_PX = 1000`)을 업로드 시점으로 옮겨 422로 막는다.
그래서 저해상 포스터는 잡이 아예 안 만들어지고 컬럼은 켜질 일이 없다.
`routers/view.py`가 `low_res`로 내보내지만 프론트는 읽지 않는다.
`i2v.reject_low_resolution`은 서비스를 직접 부르는 경로를 위해 남겨뒀다.
## [Playreel] ③ upscale ## [Playreel] ③ upscale
### CLI가 파일 경로만 받아 임시 파일이 생긴다 ### CLI가 파일 경로만 받아 임시 파일이 생긴다
@@ -173,6 +185,24 @@ CLI를 계속 쓰는 한 없앨 수 없다. Higgsfield HTTP API로 가면 presig
CLI `generate create` 응답에 크레딧 필드가 없어서(⑥ i2v에서 확인) 원본이 쓰던 값 2를 CLI `generate create` 응답에 크레딧 필드가 없어서(⑥ i2v에서 확인) 원본이 쓰던 값 2를
그대로 상수로 뒀다. 요금이 바뀌면 조용히 틀린 값이 기록된다. 그대로 상수로 뒀다. 요금이 바뀌면 조용히 틀린 값이 기록된다.
## [Playreel] ⑥ narration
### 나레이션이 템플릿이라 작품이 달라도 문장이 같다
7문장 중 다섯이 고정 문자열이고, 값이 들어가는 자리는 공연명·장르·출연진·기간·장소뿐이다.
축제 3문장은 VLM이 포스터를 보고 쓰는데 여기는 `meta`를 문자열에 끼워 넣는다.
슬롯 이름과 내용도 어긋난다. `수상` 자리에 장르 문장이, `넘버` 자리에 출연진 문장이 들어간다.
원본도 같다. `playreel_pipeline._narration_lines`가 문장까지 동일하다.
다만 원본에는 데모용 `FAKE_LINES`가 따로 있고 거기에는 "브로드웨이가 사랑한 무대가
서울에 옵니다", "렛 잇 고, 그 순간을 눈앞에서" 같은 문장이 손으로 적혀 있다.
프론트 목 데이터도 그 톤이다. 슬롯 이름이 `수상`·`넘버`인 이유가 그것이고,
그 문장을 만들어내는 코드는 원본에도 없다.
재료는 이미 있다. ② split이 `synopsis`·`cast`·`still`·`discount` 태그로 잘라두고
이미지도 blob에 있다. `extract_cast`가 cast 섹션을 VLM에 물어보는 방식을 그대로 쓸 수 있다.
## [Playreel] ⑪ compose ## [Playreel] ⑪ compose
### 스크롤 범위를 사람이 정하는 경로가 없다 ### 스크롤 범위를 사람이 정하는 경로가 없다