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

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

No files matched your search

@@ -0,0 +1,70 @@
"""analyze 수동 확인용.
사용: uv run python -m tests.playreel.test_analyze_poster <goods_id>
test_result/playreel/nol_<goods_id>/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())
@@ -0,0 +1,52 @@
"""캐스트 수집 수동 확인용.
사용: uv run python -m tests.playreel.test_extract_cast <goods_id>
test_result/nol_<goods_id>/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())
+42
View File
@@ -0,0 +1,42 @@
"""fetch 수동 확인용.
사용: uv run python -m tests.playreel.test_fetch_nol <goods_id>
결과는 test_result/nol_<goods_id>/ 에 meta.json · poster.<ext> · detail_NN.<ext>.
"""
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())
@@ -0,0 +1,67 @@
"""split 수동 확인용.
사용: uv run python -m tests.playreel.test_split_detail <goods_id>
test_result/nol_<goods_id>/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())
@@ -0,0 +1,41 @@
"""업스케일 수동 확인용. **2크레딧이 나간다.**
사용: uv run python -m tests.playreel.test_upscale_poster <goods_id>
test_result/nol_<goods_id>/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())
@@ -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
@@ -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:
@@ -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)
@@ -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:
@@ -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:
@@ -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:
@@ -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:
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env bash
# Playreel 롱컷 — 게이트 ①(fetch_confirm) 직전까지 돌린다.
# 사용: tests/run_playreel.sh <goods_id>
set -euo pipefail
cd "$(dirname "$0")/.."
goods_id="${1:?사용: $0 <goods_id>}"
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 <<EOF
══ 게이트 ① fetch_confirm — 사람이 정해야 이어진다 ══
확인할 것
meta.json 공연명·장소·기간이 맞는지
sections/_sheet.jpg 섹션 태그가 맞는지 (실측 7/9 일치라 육안 검수가 필요하다)
cast.json source 가 failed 면 출연진을 사람이 채워야 한다
승인 후 — 게이트 ②까지 간다
uv run python -m tests.playreel.test_upscale_poster "$goods_id"
uv run python -m tests.playreel.test_analyze_poster "$goods_id"
══ 게이트 ② analysis_confirm ══
analysis.json 의 movable 을 사람이 켜고 끈다. review_grid.jpg 로 요소를 지목한다.
ip_risk 가 켜져 있으면 생성 모델이 거부할 수 있다.
EOF
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env bash
# Playreel 롱컷 — 게이트 ① 승인 뒤, 게이트 ②(analysis_confirm) 직전까지.
# 사용: tests/run_playreel_after_gate1.sh <goods_id>
set -euo pipefail
cd "$(dirname "$0")/.."
goods_id="${1:?사용: $0 <goods_id>}"
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 <<EOF
══ 게이트 ② analysis_confirm — 사람이 정해야 이어진다 ══
확인할 것
analysis.json movable 을 켜고 끈다. 여기 승인이 i2v 지출을 확정한다
review_grid.jpg 격자로 요소 위치를 지목한다
ip_risk 켜져 있으면 생성 모델이 거부할 수 있다
⑤ motion 이후는 아직 서비스가 없다 (⑥ narration · ⑩ hybrid · ⑪ compose).
EOF
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env bash
# 축제 숏폼 — 검수 게이트 직전까지 돌린다.
# 사용: tests/run_poster_alive.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 "① 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 <<EOF
══ 검수 게이트 — 사람이 정해야 이어진다 ══
확인할 것
.narration.txt 나레이션 3문장 · 행사명이 슬로건과 바뀌지 않았는지 · metadata
.check.jpg 검출된 영역이 글자에 맞았는지
.motion.txt 움직일 요소. VLM이 0종을 골랐으면 여기서 사람이 넣어야 한다
모션을 다시 정하려면
uv run python -m tests.poster_alive.test_motion "$poster" <모션키,쉼표구분>
승인 후 — 여기부터는 사람 개입 없이 끝까지 간다
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
+18
View File
@@ -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"