"""
HyperFrames HTML Composition Compiler v3.0 (`html_builder.py`)
Supports:
- 10 Procedural Canvas + Theme Background Presets (`--bg`, incl. `wireframe_globe`, `isometric_hud_grid`, `auto`, `cycle`)
- 3 HUD Styles (`--hud-style`: `chapter_tabs`, `tech_briefing`, `minimal`)
- 6 Subtitle / Caption Styles (`--caption-style`: `glass_dual`, `briefing_clean`, `pill_karaoke`, `cinema_minimal`, `neon_bar_left`, `kinetic_pop`)
- 16 Visual Motion Scene Archetypes (incl. IT톡톡 Deep-Dive Briefings, Text Scramble, Real Video/Image PiP Frames, Vertical Changelog, 3D Mission Staircase, /swarm Network Graph, Pricing Matrix, Bento Grid, 3D Open-Book Flip, Spiral Notebook, etc.)
"""
from __future__ import annotations
import html
import json
import math
import re
import shutil
import subprocess
import urllib.request
from pathlib import Path
from typing import Any
from deck_video_pipeline.themes_and_presets import (
BACKGROUND_PRESETS,
CANVAS_RENDERERS_JS,
auto_select_background,
)
from deck_video_pipeline.pronunciation_engine import balance_subtitle_lines
PIPELINE_ROOT = Path(__file__).resolve().parent
PRETENDARD_URL = "https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/packages/pretendard/dist/web/variable/woff2/PretendardVariable.woff2"
GSAP_URL = "https://cdn.jsdelivr.net/npm/gsap@3.14.2/dist/gsap.min.js"
def _ensure_static_vendor_assets(offline: bool = True) -> tuple[Path, Path]:
font_src = PIPELINE_ROOT / "assets" / "fonts" / "PretendardVariable.woff2"
gsap_src = PIPELINE_ROOT / "assets" / "js" / "gsap.min.js"
font_src.parent.mkdir(parents=True, exist_ok=True)
gsap_src.parent.mkdir(parents=True, exist_ok=True)
if offline:
return font_src, gsap_src
if not font_src.exists() or font_src.stat().st_size < 100_000:
urllib.request.urlretrieve(PRETENDARD_URL, str(font_src))
if not gsap_src.exists() or gsap_src.stat().st_size < 10_000:
urllib.request.urlretrieve(GSAP_URL, str(gsap_src))
return font_src, gsap_src
def _esc(val: Any) -> str:
return html.escape(str(val or ""), quote=True)
def _esc_balanced_sub(val: Any, lang: str = "ko") -> str:
balanced = balance_subtitle_lines(str(val or ""), lang=lang)
return " ".join(_esc(part) for part in balanced.split("\n"))
def _split_card_item(raw: str, idx: int) -> tuple[str, str]:
if "|" in raw:
parts = [x.strip() for x in raw.split("|")]
return parts[0], " · ".join(parts[1:])
if "·" in raw:
left, right = [x.strip() for x in raw.split("·", 1)]
return left, right
words = raw.strip().split()
if len(words) >= 3:
return " ".join(words[:2]), " ".join(words[2:])
return f"포인트 {idx + 1:02d}", raw.strip()
# ---------------------------------------------------------------------------
# 6 New IT톡톡 Tech-Briefing Scene Renderers (v3.0)
# ---------------------------------------------------------------------------
def _render_hero_3d_briefing_scene(slide: dict[str, Any], s_idx: int) -> str:
sid = f"s{s_idx + 1}"
hero_word = slide.get("hero_word") or slide.get("title", "TECH BRIEFING")
sub_line = slide.get("subtitle") or slide.get("highlight_quote") or ""
bullets = slide.get("bullets") or ["화면", "음성", "모델", "/swarm", "워크플로", "요금"]
pill_colors = [
("#34d399", "rgba(6, 78, 59, 0.78)"),
("#a78bfa", "rgba(46, 16, 101, 0.78)"),
("#38bdf8", "rgba(12, 74, 110, 0.78)"),
("#fbbf24", "rgba(120, 53, 15, 0.78)"),
("#fb7185", "rgba(136, 19, 55, 0.78)"),
("#fdba74", "rgba(124, 45, 18, 0.78)"),
("#cbd5e1", "rgba(30, 41, 59, 0.82)"),
]
tags_html = []
for i, b in enumerate(bullets[:7]):
label = b.split("|")[0].strip()[:12]
b_col, bg_col = pill_colors[i % len(pill_colors)]
tags_html.append(
f'{_esc(label)}'
)
src_note = (
f'
{_esc(slide["source_note"])}
'
if slide.get("source_note")
else ""
)
return f"""
{_esc(slide.get("badge", "DEEP DIVE BRIEFING"))}
{_esc(hero_word)}
{_esc(sub_line)}
{"".join(tags_html)}
{src_note}
"""
def _render_media_showcase_split_scene(
slide: dict[str, Any],
s_idx: int,
rel_media_path: str,
media_kind: str,
) -> str:
sid = f"s{s_idx + 1}"
bullets = slide.get("bullets") or []
quote_line = slide.get("highlight_quote") or (bullets[0] if bullets else slide.get("title", ""))
hero_kw = slide.get("hero_word") or "LIVE"
scramble_target = slide.get("scramble_text") or slide.get("subtitle") or (bullets[1] if len(bullets) > 1 else slide.get("title", ""))
extra_desc = bullets[2] if len(bullets) > 2 else (bullets[0] if bullets and bullets[0] != quote_line else "")
media_cap = slide.get("media_caption") or slide.get("source_note") or "실시간 시연 화면"
if media_kind == "image" and rel_media_path:
frame_body = f''
elif media_kind == "video" and rel_media_path:
# Video element itself is mounted as a top-level sibling clip at exact same coordinates
frame_body = ''
else:
# Built-in crisp live UI preview card when no external file is attached
sim_rows = "".join(
f'
{_esc(b.replace("|", " · "))}
'
for b in (bullets[:3] or [slide.get("title", "Live Demo")])
)
frame_body = f"""
● New Session● LIVE
{sim_rows}
"""
extra_html = f'
{_esc(extra_desc.replace("|", " · "))}
' if extra_desc else ""
frame_extra_cls = " video-host-hidden" if (media_kind == "video" and rel_media_path) else ""
return f"""
{_esc(slide.get("badge", "FEATURE SHOWCASE"))}
“{_esc(quote_line.replace("|", " · "))}”
{_esc(hero_kw)}
{_esc(scramble_target)}
{extra_html}
{frame_body}
{_esc(media_cap)}
"""
def _render_dossier_stamp_scene(slide: dict[str, Any], s_idx: int) -> str:
"""Documentary official folder / patent dossier card with tilted rubber stamp (설명좋아하는아저씨 스타일)."""
sid = f"s{s_idx + 1}"
bullets = (slide.get("bullets") or ["핵심 항목 | 세부 내용 요약"])[:4]
title = slide.get("title", "공식 문서 요약")
combined_hdr = (title + " " + slide.get("badge", "") + " " + slide.get("stamp_text", "")).lower()
is_statement = any(k in combined_hdr for k in ["해명", "공식 입장", "statement", "우려", "논란", "없음", "불가", "반박"])
is_patent = (not is_statement) and any(k in combined_hdr for k in ["특허", "patent", "uspto", "등록"])
folder_cls = "dossier-card-white" if is_patent else "dossier-card-kraft"
tab_label = slide.get("badge") if slide.get("badge") and not slide.get("badge", "").startswith("SECTION") else (
"USPTO REGISTERED PATENT" if is_patent else "OFFICIAL STATEMENT · 공식 문서 요약"
)
stamp_txt = slide.get("stamp_text") or ("PATENT REGISTERED" if is_patent else "핵심 쟁점 확인")
stamp_cls = "rubber-stamp stamp-blue" if is_patent else "rubber-stamp stamp-red"
rows_html = []
for i, raw in enumerate(bullets):
k_txt, v_txt = _split_card_item(raw, i)
rows_html.append(f"""
{_esc(k_txt)}{_esc(v_txt)}
""")
meta_right = slide.get("source_note") or slide.get("subtitle") or ""
meta_html = f'{_esc(meta_right)}' if meta_right else ""
return f"""
{_esc(tab_label)}
{_esc(title)}
{meta_html}
{"".join(rows_html)}
{_esc(stamp_txt)}
"""
def _render_cinema_broll_scene(
slide: dict[str, Any],
s_idx: int,
rel_media_path: str,
media_kind: str,
) -> str:
"""Full-screen documentary B-Roll (image Ken-Burns or sibling video) with dark cinema vignette."""
sid = f"s{s_idx + 1}"
kicker = slide.get("badge") if slide.get("badge") and not slide.get("badge", "").startswith("SECTION") else ""
kicker_html = f'
{_esc(kicker)}
' if kicker else ""
if media_kind == "image" and rel_media_path:
bg_layer = f''
center_card = ""
elif media_kind == "video" and rel_media_path:
bg_layer = ""
center_card = ""
else:
bg_layer = ""
center_card = f"""
{kicker_html}
{_esc(slide.get("title", ""))}
"""
return f"""
{bg_layer}
{center_card}
"""
def _render_depth_cross_section_scene(slide: dict[str, Any], s_idx: int) -> str:
"""DeepFactLab-style cross-section depth exploration + descending yellow submersible + evidence quote card."""
sid = f"s{s_idx + 1}"
bullets = slide.get("bullets") or [
"수면 0m | 해발 약 2,189m 칼데라 호수",
"수심 40m | 빛과 카메라가 멈추는 한계선",
"수심 384m | 설악산 대청봉보다 높은 맨 바닥",
]
sticker_main = slide.get("subtitle") or slide.get("title", "수심 단면 탐사")
sticker_sub = (
slide.get("badge")
if slide.get("badge") and not slide.get("badge", "").startswith("SECTION")
else "가상 탐사 · 설명용 단면"
)
quote_raw = slide.get("highlight_quote") or (bullets[-1].replace("|", " — ") if bullets else slide.get("title", ""))
src_foot = slide.get("source_note") or "설명용 단면도 · 공식 기록 요지"
depth_labels = []
y_positions = [132, 232, 336, 428]
for i, b in enumerate(bullets[:4]):
head, desc = _split_card_item(b, i)
yp = y_positions[i]
depth_labels.append(
f''
f''
f''
f'{_esc(head[:11])}'
f'{_esc(desc[:28])}'
f''
)
return f"""
{_esc(sticker_main[:28])}
{_esc(sticker_sub[:24])}
📄 탐사 기록 · 팩트 검증
“{_esc(quote_raw[:68])}
— {_esc(src_foot)}
"""
def _render_sonar_factcheck_map_scene(
slide: dict[str, Any],
s_idx: int,
rel_media_path: str,
media_kind: str,
) -> str:
"""DeepFactLab-style Multi-Beam Bathymetric Sonar Contour Map OR Photo Zone ①②③ Fact-Check Stage."""
sid = f"s{s_idx + 1}"
bullets = (slide.get("bullets") or ["굳은 마그마 둑 | 화산 분화 흔적", "바닥 웅덩이 | 온천 용출 지점", "무너진 칼데라 벽 | 암석 퇴적 지대"])[:4]
verdict_txt = slide.get("stamp_text") or slide.get("hero_word") or "기록 검증 완료"
is_false_claim = any(k in (verdict_txt + " " + slide.get("title", "")).lower() for k in ["없", "아님", "거짓", "오해", "불가", "괴물", "x", "✕"])
src_foot = slide.get("source_note") or "다중빔 음향 측심 · 현장 조사 기록 재구성"
if media_kind == "image" and rel_media_path:
# Photo + Numbered Dashed Yellow Investigation Polygons (f_370.jpg style)
zone_polys = [
("160,150 310,120 430,275 315,330 190,260", 290, 230, 485, 305),
("365,135 520,185 605,310 510,335 420,245", 485, 250, 665, 325),
("555,105 705,145 735,230 635,245 555,180", 645, 178, 795, 225),
("265,355 595,365 695,435 550,465 280,450", 475, 412, 765, 405),
]
zones_svg = []
for i in range(min(len(bullets), 4)):
pts, cx, cy, ax, ay = zone_polys[i]
zones_svg.append(
f''
f''
f''
f''
f'{i + 1}'
f''
)
legend_rows = "".join(
f'
{i + 1}{_esc(b.replace("|", " · "))}
'
for i, b in enumerate(bullets)
)
visual_left = f"""
"""
else:
# Pure SVG Multi-Beam Sonar Contour Map + Callout Pointers + Red X / Check Verdict (f_465.jpg style)
callouts_cfg = [
(118, 175, 365, 228, "#b45309"),
(690, 128, 520, 215, "#1d4ed8"),
(128, 392, 345, 355, "#475569"),
(685, 388, 545, 338, "#0f766e"),
]
callouts_svg = []
for i, b in enumerate(bullets):
head, _ = _split_card_item(b, i)
bx, by, tx, ty, col = callouts_cfg[i % len(callouts_cfg)]
lx = bx + 158 if bx < 400 else bx
callouts_svg.append(
f''
f''
f''
f'{_esc(head[:10])}'
f''
)
mark_svg = (
f''
f''
f''
f''
f''
if is_false_claim
else f''
f''
f''
f''
)
legend_rows = "".join(
f'
{i + 1}{_esc(b.replace("|", " · "))}
'
for i, b in enumerate(bullets)
)
visual_left = f"""