Initial commit: ADO2 Hookit — 8초 후킹 숏폼 생성 파이프라인

3-엔진 오케스트레이션(Claude → Higgsfield → Remotion) PoC + 셀프 웹앱.
백엔드 개발자 핸드오프 문서(HANDOFF.md) 포함.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
o2oadminandClaude Opus 4.7 committed 2026-05-29 12:03:48 +09:00
commit 4deefff061
50 files changed
+5962

No files matched your search

View File
Whitespace-only changes.
+70
View File
@@ -0,0 +1,70 @@
"""② Higgsfield step — photos + prompt → completed 8s base video.
Thin wrapper around the verified CLI flow:
higgsfield generate cost/create marketing_studio_video --mode tv_spot ...
dry_run=True returns a bundled demo clip and spends no credits.
"""
from __future__ import annotations
import json
import re
import subprocess
import urllib.request
import uuid
from pathlib import Path
ENGINE = Path(__file__).resolve().parents[3] # engine/higgsfield_shorts
DEMO_VIDEO = ENGINE / "webapp" / "demo" / "mumum.mp4"
TMP = ENGINE / "server" / ".tmp"
MODEL = "marketing_studio_video"
_URL_RE = re.compile(r'"result_url"\s*:\s*"([^"]+)"')
_CREDITS_RE = re.compile(r'"credits(?:_exact)?"\s*:\s*([0-9.]+)')
def _base_args(prompt: str, image_paths: list[Path], duration: int) -> list[str]:
args = ["--prompt", prompt]
for p in image_paths:
args += ["--image", str(p)]
args += ["--mode", "tv_spot", "--duration", str(duration),
"--generate_audio", "true", "--aspect_ratio", "9:16"]
return args
def cost(prompt: str, image_paths: list[Path], duration: int = 8) -> float:
out = subprocess.run(
["higgsfield", "generate", "cost", MODEL, *_base_args(prompt, image_paths, duration), "--json"],
capture_output=True, text=True, check=True,
)
m = _CREDITS_RE.search(out.stdout)
return float(m.group(1)) if m else 0.0
def generate(
prompt: str,
image_paths: list[Path],
duration: int = 8,
dry_run: bool = False,
wait_timeout: str = "15m",
) -> tuple[Path, float]:
"""Return (local mp4 path, credits spent)."""
if dry_run:
return DEMO_VIDEO, 0.0
out = subprocess.run(
["higgsfield", "generate", "create", MODEL,
*_base_args(prompt, image_paths, duration),
"--wait", "--wait-timeout", wait_timeout, "--json"],
capture_output=True, text=True, check=True,
)
m = _URL_RE.search(out.stdout)
if not m:
raise RuntimeError(f"Higgsfield returned no result_url:\n{out.stdout[-2000:]}")
url = m.group(1)
credits_m = _CREDITS_RE.search(out.stdout)
credits = float(credits_m.group(1)) if credits_m else 0.0
TMP.mkdir(parents=True, exist_ok=True)
dest = TMP / f"base_{uuid.uuid4().hex[:8]}.mp4"
urllib.request.urlretrieve(url, dest)
return dest, credits
+90
View File
@@ -0,0 +1,90 @@
"""③ Remotion step — VideoSpec + base video → final mp4 with overlays.
Generalized: builds a props JSON (video config + default timings + spec content)
and runs `npx remotion render MumumShort <out> --props=<file>`. The base video is
copied into remotion/public/ so OffthreadVideo's staticFile() can resolve it.
"""
from __future__ import annotations
import json
import shutil
import subprocess
import uuid
from pathlib import Path
from app.schemas import VideoSpec
ENGINE = Path(__file__).resolve().parents[3] # engine/higgsfield_shorts
REMOTION = ENGINE / "remotion"
PUBLIC = REMOTION / "public"
OUT_DIR = REMOTION / "out"
FPS = 30
def _probe_frames(video_path: Path, fps: int = FPS) -> tuple[int, int, int]:
"""Return (durationInFrames, width, height) via ffprobe."""
out = subprocess.run(
["ffprobe", "-v", "error", "-select_streams", "v:0",
"-show_entries", "stream=width,height,duration",
"-of", "json", str(video_path)],
capture_output=True, text=True, check=True,
)
info = json.loads(out.stdout)["streams"][0]
width = int(info["width"])
height = int(info["height"])
seconds = float(info.get("duration", 8.0))
return max(1, round(seconds * fps)), width, height
def _timings(total: int) -> dict:
"""Default 4-beat layout, clamped to the actual video length."""
def clamp(f: int) -> int:
return max(0, min(f, total))
return {
"hook": {"fromFrame": 0, "toFrame": clamp(78)},
"sellingPoint": {"fromFrame": clamp(80), "toFrame": clamp(138)},
"brandLines": {"fromFrame": clamp(138), "toFrame": clamp(196)},
"endCard": {"fromFrame": clamp(total - 49), "toFrame": total},
}
def build_props(spec: VideoSpec, base_video: Path) -> tuple[dict, str]:
"""Copy base video into public/ and assemble the Remotion props dict."""
PUBLIC.mkdir(parents=True, exist_ok=True)
job = f"job_{uuid.uuid4().hex[:8]}.mp4"
shutil.copy(base_video, PUBLIC / job)
frames, width, height = _probe_frames(PUBLIC / job)
t = _timings(frames)
props = {
"videoSrc": job,
"fps": FPS, "width": width, "height": height, "durationInFrames": frames,
"hook": {"eyebrow": spec.hook.eyebrow, "title": spec.hook.title, **t["hook"]},
"sellingPoint": {"items": spec.selling_point.items, **t["sellingPoint"]},
"brandLines": {"lines": spec.brand_lines, **t["brandLines"]},
"endCard": {
"brand": spec.end_card.brand,
"location": spec.end_card.location,
"disclosure": spec.end_card.disclosure,
**t["endCard"],
},
}
return props, job
def render(spec: VideoSpec, base_video: Path) -> Path:
OUT_DIR.mkdir(parents=True, exist_ok=True)
props, _ = build_props(spec, base_video)
props_file = OUT_DIR / f"props_{uuid.uuid4().hex[:8]}.json"
props_file.write_text(json.dumps(props, ensure_ascii=False), encoding="utf-8")
out_file = OUT_DIR / f"final_{uuid.uuid4().hex[:8]}.mp4"
subprocess.run(
["npx", "remotion", "render", "MumumShort", str(out_file),
f"--props={props_file}"],
cwd=str(REMOTION), check=True,
)
return out_file
+171
View File
@@ -0,0 +1,171 @@
"""① LLM step — interview answers → VideoSpec (JSON).
Uses the Anthropic Python SDK (claude-opus-4-7) with structured outputs so the
result is guaranteed to match the Remotion data contract. The guardrail system
prompt is cached (stable prefix) to cut cost/latency across requests.
"""
from __future__ import annotations
import json
import anthropic
from app.schemas import GenerateRequest, VideoSpec, ScriptResult
MODEL = "claude-opus-4-7"
# Stable, cacheable guardrail + role prompt.
SYSTEM_PROMPT = """\
당신은 한국 로컬 비즈니스(숙소·매장·제품)의 8초 세로형 숏폼 광고 카피 디렉터입니다.
사장/마케터가 직접 답한 정보만으로, 영상 사양(VideoSpec)을 설계합니다. 복잡한 분석은 하지 않습니다.
[절대 가드레일]
1. 식민지 유산·역사정치 민감 용어 금지: "적산가옥", "일제", "식민지", "근대사" 등 → 미학·경험 어휘로 대체.
2. 거짓·과장 금지: 사용자가 주지 않은 거리(예: "서울 40분")·효능·수치를 지어내지 않는다. 주어진 정보만 사용.
3. 자막은 흰색 모노크롬 전제 — 카피에 색 지시어를 넣지 않는다.
4. AI 디스클로저는 end_card.disclosure에 고정 문구로 포함.
[hook 작성 — 레퍼런스 바이럴 공식 "[반전/호기심] + [한방]"]
- eyebrow: 짧은 도발/맥락 한 줄 (예: "아무도 모르는 군산").
- title: 굵은 한방 헤드라인. 사용자의 셀링포인트를 가장 강하게 압축.
[selling_point.items] 정확히 3개. 사용자 한방 셀링포인트 + 유형 기반의 구체 명사구(짧게). 이모지 금지.
[brand_lines] 감성 2줄 (각 줄 짧게). 한 덩어리로 읽히게.
[end_card] brand=업체/상품명, location=주소나 URL(없으면 빈 문자열 ""), disclosure 고정.
[caption] 업로드용. 정보(업체/주소/가격) + 짧은 감성 + 해시태그 5~8개. 유형에 맞는 해시태그.
[profile 선택]
- place + 정적/프라이빗/힐링 → "Still Cinema"
- place + 뷰/활동성/포토스팟, 또는 product 일반 → "Rhythm Reveal"
- 파티/워터파크/대형 액티비티 → "Maximum Viral"
[higgsfield_prompt] 영문. marketing_studio_video tv_spot용. 빠르고 역동적인 카메라(quick punchy moves, crash zoom, kinetic glide). 유형 반영: place=공간 투어, product=제품 쇼케이스. 반드시 "keep structure realistic, do not distort" 포함.
"""
# Structured-output JSON schema (additionalProperties:false everywhere).
_SPEC_SCHEMA = {
"type": "object",
"additionalProperties": False,
"properties": {
"profile": {"type": "string", "enum": ["Still Cinema", "Rhythm Reveal", "Maximum Viral"]},
"higgsfield_prompt": {"type": "string"},
"hook": {
"type": "object",
"additionalProperties": False,
"properties": {"eyebrow": {"type": "string"}, "title": {"type": "string"}},
"required": ["eyebrow", "title"],
},
"selling_point": {
"type": "object",
"additionalProperties": False,
"properties": {"items": {"type": "array", "items": {"type": "string"}}},
"required": ["items"],
},
"brand_lines": {"type": "array", "items": {"type": "string"}},
"end_card": {
"type": "object",
"additionalProperties": False,
"properties": {
"brand": {"type": "string"},
"location": {"type": "string"},
"disclosure": {"type": "string"},
},
"required": ["brand", "location", "disclosure"],
},
"caption": {"type": "string"},
},
"required": [
"profile", "higgsfield_prompt", "hook", "selling_point",
"brand_lines", "end_card", "caption",
],
}
def build_spec(req: GenerateRequest, client: anthropic.Anthropic | None = None) -> VideoSpec:
client = client or anthropic.Anthropic()
user_msg = (
f"유형: {'장소' if req.kind == 'place' else '메시지(축하·안부·홍보)' if req.kind == 'message' else '물건(제품·음식 등 정적 아이템)'}\n"
f"업체/상품명: {req.biz_name}\n"
f"주소/판매URL: {req.addr or '(없음)'}\n"
f"가격: {req.price or '(없음)'}\n"
f"강력한 한방 셀링포인트: {req.selling}\n\n"
"위 정보로 VideoSpec을 설계해줘."
)
resp = client.messages.create(
model=MODEL,
max_tokens=2048,
thinking={"type": "adaptive"},
output_config={
"effort": "medium",
"format": {"type": "json_schema", "name": "video_spec", "schema": _SPEC_SCHEMA},
},
system=[{
"type": "text",
"text": SYSTEM_PROMPT,
"cache_control": {"type": "ephemeral"},
}],
messages=[{"role": "user", "content": user_msg}],
)
text = "".join(b.text for b in resp.content if b.type == "text")
return VideoSpec.model_validate(json.loads(text))
# ---------- 자막 스크립트 4블록 ----------
SCRIPT_SYSTEM = """\
당신은 한국 로컬 비즈니스 숏폼 광고의 자막 스크립트 작가입니다.
사장/마케터가 답한 정보로, 영상에 얹을 4개 블록을 만듭니다.
[4블록]
- intro: 첫 1~2초 후킹. 호기심·반전을 거는 짧은 한 줄.
- selling: 가장 강력한 셀링포인트를 한 문장으로 압축.
- story: 감성 스토리. 고객이 그 공간/제품에서 느낄 감정을 1~2문장으로.
- cta: 행동 유도. 예약·구매·방문으로 자연스럽게.
[가드레일]
- 거짓·과장 금지(주어지지 않은 거리·효능·수치 X). 주어진 정보만.
- 식민지 유산 어휘(적산가옥/일제/식민지 등) 금지 → 미학·경험 어휘로.
- 자막은 흰색 모노크롬 전제 — 색 지시어 넣지 않음. 이모지 남발 금지.
- 각 블록은 짧고 입에 붙게. 한국어.
"""
_SCRIPT_SCHEMA = {
"type": "object",
"additionalProperties": False,
"properties": {
"intro": {"type": "string"},
"selling": {"type": "string"},
"story": {"type": "string"},
"cta": {"type": "string"},
},
"required": ["intro", "selling", "story", "cta"],
}
def build_script(req: GenerateRequest, client: anthropic.Anthropic | None = None) -> ScriptResult:
client = client or anthropic.Anthropic()
user_msg = (
f"유형: {'장소' if req.kind == 'place' else '메시지(축하·안부·홍보)' if req.kind == 'message' else '물건(제품·음식 등 정적 아이템)'}\n"
f"업체/상품명: {req.biz_name}\n"
f"주소/판매URL: {req.addr or '(없음)'}\n"
f"가격: {req.price or '(없음)'}\n"
f"강력한 한방 셀링포인트: {req.selling}\n\n"
"위 정보로 4블록 자막 스크립트를 만들어줘."
)
resp = client.messages.create(
model=MODEL,
max_tokens=1024,
thinking={"type": "adaptive"},
output_config={
"effort": "low",
"format": {"type": "json_schema", "name": "script", "schema": _SCRIPT_SCHEMA},
},
system=[{"type": "text", "text": SCRIPT_SYSTEM, "cache_control": {"type": "ephemeral"}}],
messages=[{"role": "user", "content": user_msg}],
)
text = "".join(b.text for b in resp.content if b.type == "text")
return ScriptResult.model_validate(json.loads(text))