seedance 적용.

This commit is contained in:
HyeongBaeYang committed 2026-06-01 13:41:51 +09:00
1 parent 4deefff061
commit 154bf5b992
18 files changed
+942 -179

No files matched your search

+86
View File
@@ -0,0 +1,86 @@
"""fal.ai 백엔드 — Seedance 2.0 reference-to-video (멀티이미지 9장, 9:16 세로).
Higgsfield platform API 가 모든 모델(dop/seedance v1/kling)을 단일 이미지로만 노출하는
한계를 우회한다. 업로드한 사진 여러 장을 그대로 넣어 ① AI 환각(안 보이는 공간 창작)을
줄이고 ② 여러 공간을 둘러보는 영상을 만든다.
흐름: 로컬 사진 → fal 업로드(URL) → subscribe(자동 폴링) → 결과 video.url → 다운로드.
인증: fal SDK 가 FAL_KEY("keyid:secret") 를 환경에서 읽음(config 에서 주입).
dry_run=True 면 호출 없이 번들 데모 클립 반환.
"""
from __future__ import annotations
import os
import uuid
from pathlib import Path
import httpx
from app import config as cfg
ENGINE = Path(__file__).resolve().parents[3] # engine/higgsfield_shorts
TMP = ENGINE / "server" / ".tmp"
DEMO_VIDEO = cfg.WEBAPP_DIR / "demo" / "mumum.mp4"
def _download(url: str) -> Path:
# httpx + 브라우저 UA (CDN이 기본 UA를 403 차단하는 경우 대비)
TMP.mkdir(parents=True, exist_ok=True)
dest = TMP / f"base_{uuid.uuid4().hex[:8]}.mp4"
with httpx.stream("GET", url, follow_redirects=True, timeout=180.0,
headers={"User-Agent": "Mozilla/5.0"}) as r:
r.raise_for_status()
with dest.open("wb") as f:
for chunk in r.iter_bytes():
f.write(chunk)
return dest
def generate(
prompt: str,
image_paths: list[Path],
duration: int | None = None,
dry_run: bool = False,
**_,
) -> tuple[Path, float]:
"""Return (local mp4 path, credits). credits 는 fal 응답에 없어 0.0."""
if dry_run:
return DEMO_VIDEO, 0.0
try:
import fal_client
except ImportError as e:
raise RuntimeError(
"fal-client 미설치. `pip install fal-client` 또는 이미지 재빌드 필요."
) from e
if not os.environ.get("FAL_KEY"):
raise RuntimeError(
"FAL_KEY 없음. .env 에 FAL_KEY='keyid:secret'(또는 FAL_API_KEY) 설정 필요."
)
# 1) 입력 사진 업로드 → URL. Seedance 2.0 는 최대 9장.
image_urls = [fal_client.upload_file(str(p)) for p in image_paths[:cfg.FAL_MAX_IMAGES]]
if not image_urls:
raise RuntimeError("업로드된 입력 이미지가 없습니다.")
# 2) 요청 인자. duration 은 "auto" 또는 4~12 정수.
arguments: dict = {
"prompt": prompt,
"image_urls": image_urls,
"aspect_ratio": cfg.FAL_ASPECT_RATIO,
"resolution": cfg.FAL_RESOLUTION,
}
dur = duration if duration is not None else cfg.FAL_DURATION
if str(dur).lower() != "auto":
arguments["duration"] = int(dur)
# 3) 동기 호출(자동 폴링). subscribe 가 완료까지 블록.
result = fal_client.subscribe(cfg.FAL_MODEL_ID, arguments=arguments)
# 4) 결과 영상 URL 추출 → 다운로드. (응답: {"video": {"url": ...}, "seed": ...})
video = result.get("video") if isinstance(result, dict) else None
url = video.get("url") if isinstance(video, dict) else None
if not url:
raise RuntimeError(f"fal 결과에서 영상 URL을 찾지 못함: {result!r}")
return _download(url), 0.0
+161 -25
View File
@@ -1,37 +1,67 @@
"""② 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.
두 가지 백엔드를 지원한다 (cfg.HIGGSFIELD_BACKEND):
· "cli" — 기존 검증 경로. `higgsfield` CLI 를 subprocess 로 호출.
~/.higgsfield 디바이스 로그인 인증 필요(컨테이너 비친화).
· "api" — 공식 Python SDK(higgsfield-client). HF_KEY 환경변수 인증.
컨테이너/서버리스 친화. 공개 문서 기준 DoP image2video 사용.
dry_run=True 면 양쪽 모두 건너뛰고 번들된 데모 클립을 반환(크레딧 0).
API 백엔드는 DoP image2video(POST {app} → job set, GET /v1/job-sets/{id} 폴링,
jobs[0].results.raw.url 추출)로 실측 검증됨. 단가/오디오 특성이 CLI(marketing_studio,
tv_spot)와 다르므로 app/variant 는 env(cfg.HIGGSFIELD_API_APP/VARIANT)로 교체 가능.
"""
from __future__ import annotations
import json
import os
import re
import subprocess
import urllib.request
import time
import uuid
from pathlib import Path
import httpx
from app import config as cfg
ENGINE = Path(__file__).resolve().parents[3] # engine/higgsfield_shorts
DEMO_VIDEO = ENGINE / "webapp" / "demo" / "mumum.mp4"
DEMO_VIDEO = cfg.WEBAPP_DIR / "demo" / "mumum.mp4"
TMP = ENGINE / "server" / ".tmp"
MODEL = "marketing_studio_video"
MODEL = cfg.HIGGSFIELD_MODEL
_URL_RE = re.compile(r'"result_url"\s*:\s*"([^"]+)"')
_CREDITS_RE = re.compile(r'"credits(?:_exact)?"\s*:\s*([0-9.]+)')
def _download(url: str) -> Path:
# httpx + 브라우저 UA 로 받음. (CDN이 urllib 기본 UA를 403 차단 — 실측 확인)
TMP.mkdir(parents=True, exist_ok=True)
dest = TMP / f"base_{uuid.uuid4().hex[:8]}.mp4"
with httpx.stream("GET", url, follow_redirects=True, timeout=120.0,
headers={"User-Agent": "Mozilla/5.0"}) as r:
r.raise_for_status()
with dest.open("wb") as f:
for chunk in r.iter_bytes():
f.write(chunk)
return dest
# ============================ CLI 백엔드 ============================
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"]
args += ["--mode", cfg.HIGGSFIELD_MODE, "--duration", str(duration),
"--generate_audio", cfg.HIGGSFIELD_GENERATE_AUDIO,
"--aspect_ratio", cfg.HIGGSFIELD_ASPECT_RATIO]
return args
def cost(prompt: str, image_paths: list[Path], duration: int = 8) -> float:
def cost(prompt: str, image_paths: list[Path], duration: int = cfg.HIGGSFIELD_DURATION) -> float:
"""CLI 백엔드 전용 — 생성 전 크레딧 선확인."""
out = subprocess.run(
["higgsfield", "generate", "cost", MODEL, *_base_args(prompt, image_paths, duration), "--json"],
capture_output=True, text=True, check=True,
@@ -40,17 +70,9 @@ def cost(prompt: str, image_paths: list[Path], duration: int = 8) -> float:
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",
def _generate_cli(
prompt: str, image_paths: list[Path], duration: int, wait_timeout: str,
) -> 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),
@@ -60,11 +82,125 @@ def generate(
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
return _download(m.group(1)), credits
TMP.mkdir(parents=True, exist_ok=True)
dest = TMP / f"base_{uuid.uuid4().hex[:8]}.mp4"
urllib.request.urlretrieve(url, dest)
return dest, credits
# ============================ API 백엔드 ============================
#
# DoP image2video 응답은 공식 SDK의 generic submit() 가정(request_id)과 달라
# 'job set' 구조다(실측 확인). 따라서 SDK 의 저수준 클라이언트(인증·base_url)만
# 빌려 직접 흐름을 구현한다:
# POST {app} → {"id": <job_set_id>, "jobs": [{status, results}]}
# GET /v1/job-sets/{id} → jobs[0].status / jobs[0].results.{raw,min}.url
#
_TERMINAL = {"completed", "failed", "nsfw", "canceled", "cancelled"}
def _parse_timeout(value: str) -> float:
"""'15m' / '900s' / '900' → 초(float)."""
v = str(value).strip().lower()
try:
if v.endswith("m"):
return float(v[:-1]) * 60
if v.endswith("s"):
return float(v[:-1])
return float(v)
except ValueError:
return 900.0
def _extract_url(results) -> str:
"""job 의 results 에서 영상 URL 추출. raw(풀화질) 우선, 없으면 min."""
if isinstance(results, dict):
for key in ("raw", "min", "result", "output"):
v = results.get(key)
if isinstance(v, dict) and v.get("url"):
return v["url"]
if isinstance(v, str):
return v
raise RuntimeError(f"Higgsfield 결과에서 영상 URL을 찾지 못함: {results!r}")
def _generate_api(
prompt: str, image_paths: list[Path], duration: int, wait_timeout: str,
) -> tuple[Path, float]:
try:
import higgsfield_client as hf # 공식 SDK (업로드/인증)
from higgsfield_client.http.client import SyncClient
except ImportError as e:
raise RuntimeError(
"higgsfield-client 미설치. `pip install higgsfield-client` 또는 이미지 재빌드 필요."
) from e
if not (os.environ.get("HF_KEY") or
(os.environ.get("HF_API_KEY") and os.environ.get("HF_API_SECRET"))):
raise RuntimeError(
"Higgsfield API 자격증명 없음. HF_KEY='key:secret' 또는 "
"HIGGSFIELD_API_KEY/HIGGSFIELD_API_SECRET(.env) 설정 필요."
)
# 1) 입력 사진 업로드 → URL.
image_urls = [hf.upload_file(str(p)) for p in image_paths[:cfg.HIGGSFIELD_API_MAX_IMAGES]]
if not image_urls:
raise RuntimeError("업로드된 입력 이미지가 없습니다.")
# 2) 생성 요청. 실인자는 'params' 로 감싼다(실측: 미래핑 시 422).
# 엔드포인트별 이미지 필드 구조가 다름(platform API 실측):
# · DoP : input_images (복수 배열)
# · Seedance : input_image (단수 object). model enum=seedance_pro|seedance_lite,
# aspect_ratio 9:16 네이티브 지원, duration 3~12.
common = {
"model": cfg.HIGGSFIELD_API_VARIANT,
"prompt": prompt,
"aspect_ratio": cfg.HIGGSFIELD_ASPECT_RATIO,
"duration": duration,
}
if "seedance" in cfg.HIGGSFIELD_API_APP.lower():
params = {**common, "input_image": {"type": "image_url", "image_url": image_urls[0]}}
else:
params = {**common,
"input_images": [{"type": "image_url", "image_url": u} for u in image_urls]}
body = {"params": params}
http = SyncClient()._client # 인증·base_url 설정된 httpx.Client
resp = http.post(cfg.HIGGSFIELD_API_APP, json=body)
resp.raise_for_status()
job_set_id = resp.json()["id"]
# 3) 완료까지 폴링
timeout_s = _parse_timeout(wait_timeout)
waited, interval = 0.0, 5.0
while True:
js = http.get(f"/v1/job-sets/{job_set_id}")
js.raise_for_status()
job = js.json()["jobs"][0]
status = (job.get("status") or "").lower()
if status == "completed":
break
if status in _TERMINAL:
raise RuntimeError(f"Higgsfield 생성 실패: status={status} (job_set {job_set_id})")
if waited >= timeout_s:
raise RuntimeError(f"Higgsfield 생성 타임아웃({wait_timeout}, job_set {job_set_id})")
time.sleep(interval)
waited += interval
# 4) 결과 영상 다운로드 (credits 는 응답에 없어 0.0)
return _download(_extract_url(job["results"])), 0.0
# ============================ 디스패처 ============================
def generate(
prompt: str,
image_paths: list[Path],
duration: int = cfg.HIGGSFIELD_DURATION,
dry_run: bool = False,
wait_timeout: str = cfg.HIGGSFIELD_WAIT_TIMEOUT,
) -> tuple[Path, float]:
"""Return (local mp4 path, credits spent). 백엔드는 cfg.HIGGSFIELD_BACKEND."""
if dry_run:
return DEMO_VIDEO, 0.0
if cfg.HIGGSFIELD_BACKEND == "api":
return _generate_api(prompt, image_paths, duration, wait_timeout)
return _generate_cli(prompt, image_paths, duration, wait_timeout)
+29 -12
View File
@@ -12,6 +12,7 @@ import subprocess
import uuid
from pathlib import Path
from app import config as cfg
from app.schemas import VideoSpec
ENGINE = Path(__file__).resolve().parents[3] # engine/higgsfield_shorts
@@ -19,7 +20,7 @@ REMOTION = ENGINE / "remotion"
PUBLIC = REMOTION / "public"
OUT_DIR = REMOTION / "out"
FPS = 30
FPS = cfg.REMOTION_FPS
def _probe_frames(video_path: Path, fps: int = FPS) -> tuple[int, int, int]:
@@ -38,14 +39,23 @@ def _probe_frames(video_path: Path, fps: int = FPS) -> tuple[int, int, int]:
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))
"""4-beat 레이아웃을 실제 프레임 수에 비례 스케일.
240프레임(8초 @30fps)을 기준으로 설계됐으나, 영상이 그보다 짧거나 길어도
각 구간 비율이 유지되도록 sc()로 선형 변환한다.
고정값 clamp 방식은 짧은 영상에서 brandLines 창이 너무 좁아져
interpolate 범위가 뒤집히는 크래시를 유발했음.
"""
REF = 240 # 기준 총 프레임 (8s @30fps)
def sc(f: int) -> int:
return max(0, min(round(f * total / REF), 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},
"hook": {"fromFrame": 0, "toFrame": sc(78)},
"sellingPoint": {"fromFrame": sc(80), "toFrame": sc(138)},
"brandLines": {"fromFrame": sc(138), "toFrame": sc(196)},
"endCard": {"fromFrame": max(0, total - sc(49)), "toFrame": total},
}
@@ -74,17 +84,24 @@ def build_props(spec: VideoSpec, base_video: Path) -> tuple[dict, str]:
return props, job
def render(spec: VideoSpec, base_video: Path) -> Path:
def render(spec: VideoSpec, base_video: Path) -> tuple[Path, list[Path]]:
"""렌더 후 호출자가 지울 임시 파일 목록도 함께 반환한다.
반환값: (최종 mp4, [삭제 대상 임시 파일])
호출자는 최종 mp4를 outputs/ 로 복사한 뒤 반환된 목록을 삭제해야 한다.
"""
OUT_DIR.mkdir(parents=True, exist_ok=True)
props, _ = build_props(spec, base_video)
props, pub_job_name = 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),
["npx", "remotion", "render", cfg.REMOTION_COMPOSITION, str(out_file),
f"--props={props_file}"],
cwd=str(REMOTION), check=True,
)
return out_file
# 임시 파일: remotion/public/ 의 베이스 복사본 + props JSON (out_file 은 별도 반환)
temps = [PUBLIC / pub_job_name, props_file]
return out_file, temps
+58 -50
View File
@@ -1,19 +1,20 @@
"""① LLM step — interview answers → VideoSpec (JSON).
"""① LLM step — interview answers → VideoSpec / ScriptResult (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.
Uses the OpenAI SDK with Structured Outputs (response_format json_schema, strict)
so the result is guaranteed to match the Remotion data contract. The stable
guardrail system prompt benefits from OpenAI's automatic prompt caching.
"""
from __future__ import annotations
import json
import anthropic
from openai import OpenAI
from app import config as cfg
from app.schemas import GenerateRequest, VideoSpec, ScriptResult
MODEL = "claude-opus-4-7"
MODEL = cfg.OPENAI_MODEL
# Stable, cacheable guardrail + role prompt.
# Stable guardrail + role prompt (automatic prompt caching applies to this prefix).
SYSTEM_PROMPT = """\
당신은 한국 로컬 비즈니스(숙소·매장·제품)의 8초 세로형 숏폼 광고 카피 디렉터입니다.
사장/마케터가 직접 답한 정보만으로, 영상 사양(VideoSpec)을 설계합니다. 복잡한 분석은 하지 않습니다.
@@ -41,10 +42,19 @@ SYSTEM_PROMPT = """\
- 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" 포함.
[higgsfield_prompt] 영문. marketing_studio_video 용 고품질 프롬프트. 아래 구조를 반드시 따를 것.
① 포맷 명시: "VERTICAL 9:16 portrait format, mobile short-form."
② 카메라 무브 (place 유형): 드론/핸드헬드 하이브리드로 실내외를 역동적으로 순회.
예시 패턴: "smooth drone glide through entrance → quick crash-zoom onto hero detail → kinetic handheld reveal of interior space → pull-back drone shot of exterior"
product 유형: "macro crash-zoom onto product → slow orbit reveal → snappy cut to detail closeup"
③ 분위기: 시간대(twilight/golden hour/daylight)·색감(teal-and-orange grade 또는 유형에 맞는 톤)·질감(subtle film grain, quiet luxury)을 구체적으로 명시.
④ 반드시 포함할 문구: "photorealistic, no AI artifacts, keep architecture and objects structurally accurate, do not warp or distort walls floors or furniture, no morphing, no hallucinated details."
⑤ 마지막 문장: "Hook viewer in first second. Beat-driven energetic edit."
유형(place/product/message)과 업체 분위기에 맞게 세부 내용을 구체화할 것. 절대 짧거나 추상적인 문장으로 끝내지 말 것.
"""
# Structured-output JSON schema (additionalProperties:false everywhere).
# Structured-output JSON schema (strict: additionalProperties:false + all props required).
_SPEC_SCHEMA = {
"type": "object",
"additionalProperties": False,
@@ -83,36 +93,50 @@ _SPEC_SCHEMA = {
}
def build_spec(req: GenerateRequest, client: anthropic.Anthropic | None = None) -> VideoSpec:
client = client or anthropic.Anthropic()
def _kind_label(kind: str) -> str:
return {
"place": "장소",
"message": "메시지(축하·안부·홍보)",
"product": "물건(제품·음식 등 정적 아이템)",
}.get(kind, kind)
user_msg = (
f"유형: {'장소' if req.kind == 'place' else '메시지(축하·안부·홍보)' if req.kind == 'message' else '물건(제품·음식 등 정적 아이템)'}\n"
def _user_msg(req: GenerateRequest, tail: str) -> str:
return (
f"유형: {_kind_label(req.kind)}\n"
f"업체/상품명: {req.biz_name}\n"
f"주소/판매URL: {req.addr or '(없음)'}\n"
f"가격: {req.price or '(없음)'}\n"
f"강력한 한방 셀링포인트: {req.selling}\n\n"
"위 정보로 VideoSpec을 설계해줘."
f"{tail}"
)
resp = client.messages.create(
def _complete(client: OpenAI, system: str, user: str, schema_name: str,
schema: dict, max_tokens: int) -> dict:
"""OpenAI Structured Outputs 호출 → 검증된 JSON(dict) 반환."""
resp = client.chat.completions.create(
model=MODEL,
max_tokens=2048,
thinking={"type": "adaptive"},
output_config={
"effort": "medium",
"format": {"type": "json_schema", "name": "video_spec", "schema": _SPEC_SCHEMA},
max_completion_tokens=max_tokens,
response_format={
"type": "json_schema",
"json_schema": {"name": schema_name, "strict": True, "schema": schema},
},
system=[{
"type": "text",
"text": SYSTEM_PROMPT,
"cache_control": {"type": "ephemeral"},
}],
messages=[{"role": "user", "content": user_msg}],
messages=[
{"role": "system", "content": system},
{"role": "user", "content": user},
],
)
return json.loads(resp.choices[0].message.content)
text = "".join(b.text for b in resp.content if b.type == "text")
return VideoSpec.model_validate(json.loads(text))
def build_spec(req: GenerateRequest, client: OpenAI | None = None) -> VideoSpec:
client = client or OpenAI()
data = _complete(
client, SYSTEM_PROMPT, _user_msg(req, "위 정보로 VideoSpec을 설계해줘."),
"video_spec", _SPEC_SCHEMA, max_tokens=2048,
)
return VideoSpec.model_validate(data)
# ---------- 자막 스크립트 4블록 ----------
@@ -146,26 +170,10 @@ _SCRIPT_SCHEMA = {
}
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블록 자막 스크립트를 만들어줘."
def build_script(req: GenerateRequest, client: OpenAI | None = None) -> ScriptResult:
client = client or OpenAI()
data = _complete(
client, SCRIPT_SYSTEM, _user_msg(req, "위 정보로 4블록 자막 스크립트를 만들어줘."),
"script", _SCRIPT_SCHEMA, max_tokens=1024,
)
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))
return ScriptResult.model_validate(data)