seedance 적용.
This commit is contained in:
1 parent
4deefff061
commit
154bf5b992
18 files changed
+942
-179
No files matched your search
@@ -0,0 +1,91 @@
|
||||
"""Centralized runtime configuration — env-driven, no hardcoded constants.
|
||||
|
||||
Every value has a sensible default so local/dev runs work with zero config;
|
||||
override any of them via environment variables (see server/.env.example).
|
||||
Import as `from app import config as cfg` and read `cfg.<NAME>`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
ENGINE = Path(__file__).resolve().parents[2] # engine/higgsfield_shorts
|
||||
|
||||
|
||||
def _csv(name: str, default: str) -> list[str]:
|
||||
raw = os.getenv(name, default)
|
||||
return [s.strip() for s in raw.split(",") if s.strip()]
|
||||
|
||||
|
||||
def _path(name: str, default: Path) -> Path:
|
||||
val = os.getenv(name)
|
||||
return Path(val) if val else default
|
||||
|
||||
|
||||
# ---- HTTP / CORS ----
|
||||
PORT = int(os.getenv("PORT", "10001"))
|
||||
CORS_ORIGINS = _csv("CORS_ORIGINS", "*") # 콤마구분. 운영 시 도메인으로 제한.
|
||||
|
||||
# ---- 비동기 작업 큐 (인메모리 스레드풀) ----
|
||||
# 동시에 실제로 생성을 돌릴 작업 수. 초과분은 큐에서 대기(status=queued).
|
||||
# Higgsfield/Remotion이 무거우므로(CPU·메모리·외부 단가) 보수적으로 둔다.
|
||||
MAX_CONCURRENT_JOBS = int(os.getenv("MAX_CONCURRENT_JOBS", "2"))
|
||||
# 완료/실패한 작업 레코드를 메모리에 보관할 시간(초). 지나면 폴링 GET 시 청소.
|
||||
JOB_RETENTION_SECONDS = int(os.getenv("JOB_RETENTION_SECONDS", "3600"))
|
||||
|
||||
# ---- LLM (OpenAI) ----
|
||||
# 인증: SDK가 OPENAI_API_KEY 를 환경에서 읽음.
|
||||
OPENAI_MODEL = os.getenv("OPENAI_MODEL", "gpt-4o")
|
||||
|
||||
# ---- 비디오 생성 백엔드 선택 ----
|
||||
# "higgsfield" — Higgsfield(dop/seedance v1/kling). 입력 이미지 1장만 사용.
|
||||
# "fal" — fal.ai Seedance 2.0 reference-to-video. 입력 이미지 최대 9장(멀티) + 9:16 세로.
|
||||
VIDEO_BACKEND = os.getenv("VIDEO_BACKEND", "higgsfield").lower()
|
||||
|
||||
# ---- Higgsfield (공통) ----
|
||||
# 백엔드 선택: "cli"(기존 검증 경로, ~/.higgsfield 디바이스 로그인) | "api"(공식 SDK, 컨테이너 친화)
|
||||
HIGGSFIELD_BACKEND = os.getenv("HIGGSFIELD_BACKEND", "cli").lower()
|
||||
HIGGSFIELD_ASPECT_RATIO = os.getenv("HIGGSFIELD_ASPECT_RATIO", "9:16")
|
||||
HIGGSFIELD_DURATION = int(os.getenv("HIGGSFIELD_DURATION", "8"))
|
||||
HIGGSFIELD_WAIT_TIMEOUT = os.getenv("HIGGSFIELD_WAIT_TIMEOUT", "15m")
|
||||
|
||||
# ---- Higgsfield: CLI 백엔드 (subprocess) ----
|
||||
HIGGSFIELD_MODEL = os.getenv("HIGGSFIELD_MODEL", "marketing_studio_video")
|
||||
HIGGSFIELD_MODE = os.getenv("HIGGSFIELD_MODE", "tv_spot")
|
||||
HIGGSFIELD_GENERATE_AUDIO = os.getenv("HIGGSFIELD_GENERATE_AUDIO", "true")
|
||||
|
||||
# ---- Higgsfield: API 백엔드 (공식 higgsfield-client SDK) ----
|
||||
# 인증: SDK가 HF_KEY="key:secret" 또는 HF_API_KEY/HF_API_SECRET 를 환경에서 읽음.
|
||||
# 편의상 HIGGSFIELD_API_KEY/SECRET 로 줘도 아래에서 HF_* 로 매핑.
|
||||
# 주의: 공개 문서가 다루는 비디오 모델은 DoP image2video. marketing_studio_video 가
|
||||
# API로 노출되는지는 미검증 → app/variant 를 env로 빼둠(대시보드 확인 후 교체).
|
||||
HIGGSFIELD_API_APP = os.getenv("HIGGSFIELD_API_APP", "/v1/image2video/dop")
|
||||
HIGGSFIELD_API_VARIANT = os.getenv("HIGGSFIELD_API_VARIANT", "dop-turbo")
|
||||
# DoP image2video 는 입력 이미지 정확히 1장만 허용(실측). 모델 교체 시 늘릴 수 있음.
|
||||
HIGGSFIELD_API_MAX_IMAGES = int(os.getenv("HIGGSFIELD_API_MAX_IMAGES", "1"))
|
||||
_hf_key = os.getenv("HIGGSFIELD_API_KEY")
|
||||
_hf_secret = os.getenv("HIGGSFIELD_API_SECRET")
|
||||
if _hf_key and not os.getenv("HF_API_KEY"):
|
||||
os.environ["HF_API_KEY"] = _hf_key
|
||||
if _hf_secret and not os.getenv("HF_API_SECRET"):
|
||||
os.environ["HF_API_SECRET"] = _hf_secret
|
||||
|
||||
# ---- fal.ai (Seedance 2.0 reference-to-video, VIDEO_BACKEND=fal) ----
|
||||
# 인증: SDK가 FAL_KEY("keyid:secret")를 환경에서 읽음. 편의상 FAL_API_KEY 로 줘도 매핑.
|
||||
FAL_MODEL_ID = os.getenv("FAL_MODEL_ID", "bytedance/seedance-2.0/reference-to-video")
|
||||
FAL_MAX_IMAGES = int(os.getenv("FAL_MAX_IMAGES", "9")) # Seedance 2.0 멀티이미지 최대 9장
|
||||
FAL_ASPECT_RATIO = os.getenv("FAL_ASPECT_RATIO", "9:16") # auto/16:9/9:16/4:3/3:4/1:1/21:9
|
||||
FAL_RESOLUTION = os.getenv("FAL_RESOLUTION", "720p") # 480p/720p/1080p
|
||||
FAL_DURATION = os.getenv("FAL_DURATION", "8") # "auto" 또는 4~15(초)
|
||||
_fal_key = os.getenv("FAL_API_KEY")
|
||||
if _fal_key and not os.getenv("FAL_KEY"):
|
||||
os.environ["FAL_KEY"] = _fal_key
|
||||
|
||||
# ---- Remotion (Node render) ----
|
||||
REMOTION_FPS = int(os.getenv("REMOTION_FPS", "30"))
|
||||
REMOTION_COMPOSITION = os.getenv("REMOTION_COMPOSITION", "MumumShort")
|
||||
|
||||
# ---- Paths (Docker는 환경변수로 오버라이드) ----
|
||||
WEBAPP_DIR = _path("WEBAPP_DIR", ENGINE / "webapp")
|
||||
OUTPUTS_DIR = _path("OUTPUTS_DIR", ENGINE / "server" / "outputs")
|
||||
UPLOADS_DIR = _path("UPLOADS_DIR", ENGINE / "server" / ".uploads")
|
||||
@@ -0,0 +1,181 @@
|
||||
"""비동기 작업 큐 — 인메모리 레지스트리 + 스레드풀.
|
||||
|
||||
`/api/generate` 는 더 이상 파이프라인을 동기 블로킹하지 않는다. 대신:
|
||||
|
||||
submit(req, photo_paths, dry_run) → job_id 즉시 반환
|
||||
ThreadPoolExecutor(max_workers=cfg.MAX_CONCURRENT_JOBS) 위에서 _run() 실행
|
||||
get(job_id) → 현재 상태(JobStatus dict) — 프론트가 폴링
|
||||
|
||||
동시성: 워커 수만큼 동시에 생성하고, 초과분은 풀의 큐에서 status="queued" 로 대기한다.
|
||||
영속성: 인메모리이므로 단일 프로세스 한정. 서버 재시작 시 진행 중 작업은 사라진다.
|
||||
(단일 컨테이너·단일 uvicorn 배포 전제. 멀티프로세스/스케일아웃이 필요해지면
|
||||
Redis 등 외부 스토어로 교체.)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
from app import config as cfg
|
||||
from app.schemas import GenerateRequest
|
||||
from app.pipeline import spec_builder, higgsfield_client, fal_client, remotion_render
|
||||
|
||||
OUTPUTS = cfg.OUTPUTS_DIR
|
||||
|
||||
# 단계 → (stage_index, 진입 시 표시할 대략 진행률). 프론트 진행바 3개와 1:1 매핑.
|
||||
_STAGE_PROGRESS = {"spec": (0, 10), "higgsfield": (1, 40), "remotion": (2, 80)}
|
||||
|
||||
_executor = ThreadPoolExecutor(
|
||||
max_workers=cfg.MAX_CONCURRENT_JOBS, thread_name_prefix="gen"
|
||||
)
|
||||
_jobs: dict[str, dict] = {}
|
||||
_lock = threading.Lock()
|
||||
|
||||
|
||||
def _now() -> float:
|
||||
return time.time()
|
||||
|
||||
|
||||
def _set(job_id: str, **fields) -> None:
|
||||
"""레지스트리의 작업 레코드를 스레드 안전하게 부분 갱신."""
|
||||
with _lock:
|
||||
job = _jobs.get(job_id)
|
||||
if job is not None:
|
||||
job.update(fields, updated_at=_now())
|
||||
|
||||
|
||||
def _stage(job_id: str, stage: str) -> None:
|
||||
idx, progress = _STAGE_PROGRESS[stage]
|
||||
_set(job_id, status="running", stage=stage, stage_index=idx, progress=progress)
|
||||
|
||||
|
||||
def _purge_expired() -> None:
|
||||
"""완료/실패 후 보존시간이 지난 레코드를 청소(메모리 누수 방지)."""
|
||||
cutoff = _now() - cfg.JOB_RETENTION_SECONDS
|
||||
with _lock:
|
||||
stale = [
|
||||
jid for jid, j in _jobs.items()
|
||||
if j["status"] in ("done", "error") and j["updated_at"] < cutoff
|
||||
]
|
||||
for jid in stale:
|
||||
_jobs.pop(jid, None)
|
||||
|
||||
|
||||
def _cleanup(
|
||||
upload_dir: Path | None,
|
||||
base_video: Path | None,
|
||||
remotion_out: Path | None,
|
||||
remotion_temps: list[Path],
|
||||
) -> None:
|
||||
"""작업 완료·실패 후 임시 파일 전부 삭제. 오류는 무시(정리 실패가 메인 흐름에 영향 없게)."""
|
||||
# 업로드 사진 폴더 통째로
|
||||
if upload_dir and upload_dir.exists():
|
||||
shutil.rmtree(upload_dir, ignore_errors=True)
|
||||
# Higgsfield가 받아둔 베이스 영상 (.tmp/). dry_run 데모 파일은 제외
|
||||
if base_video and base_video != higgsfield_client.DEMO_VIDEO:
|
||||
try:
|
||||
base_video.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
# Remotion 중간 파일들 (remotion/public/ 복사본, props JSON)
|
||||
for p in remotion_temps:
|
||||
try:
|
||||
p.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
# Remotion 최종 출력 (outputs/ 로 복사 완료된 뒤 원본 삭제)
|
||||
if remotion_out:
|
||||
try:
|
||||
remotion_out.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _run(job_id: str, req: GenerateRequest, photo_paths: list[Path], dry_run: bool) -> None:
|
||||
"""워커 스레드 본체 — 기존 동기 파이프라인을 단계별 상태 갱신과 함께 실행."""
|
||||
upload_dir = photo_paths[0].parent if photo_paths else None
|
||||
base_video: Path | None = None
|
||||
remotion_out: Path | None = None
|
||||
remotion_temps: list[Path] = []
|
||||
|
||||
try:
|
||||
# 1. LLM → spec
|
||||
_stage(job_id, "spec")
|
||||
spec = spec_builder.build_spec(req)
|
||||
_set(job_id, caption=spec.caption, profile=spec.profile)
|
||||
|
||||
# 2. 비디오 생성 → 베이스 영상 (백엔드 선택)
|
||||
# fal: Seedance 2.0 멀티이미지(9장) / higgsfield: 단일 이미지
|
||||
_stage(job_id, "higgsfield")
|
||||
backend = fal_client if cfg.VIDEO_BACKEND == "fal" else higgsfield_client
|
||||
base_video, credits = backend.generate(
|
||||
spec.higgsfield_prompt, photo_paths, dry_run=dry_run
|
||||
)
|
||||
_set(job_id, cost_credits=credits)
|
||||
|
||||
# Higgsfield 완료 즉시 outputs/ 에 저장.
|
||||
# Remotion 이 실패해도 베이스 영상은 접근 가능하고,
|
||||
# Remotion 이 성공하면 같은 경로에 최종본을 덮어쓴다.
|
||||
OUTPUTS.mkdir(parents=True, exist_ok=True)
|
||||
served = OUTPUTS / f"{job_id}.mp4"
|
||||
if base_video != higgsfield_client.DEMO_VIDEO:
|
||||
shutil.copy(base_video, served)
|
||||
else:
|
||||
shutil.copy(base_video, served) # dry_run 데모도 동일하게 복사
|
||||
_set(job_id, video_url=f"/outputs/{job_id}.mp4")
|
||||
|
||||
# 3. Remotion → 자막 합성
|
||||
_stage(job_id, "remotion")
|
||||
remotion_out, remotion_temps = remotion_render.render(spec, base_video)
|
||||
|
||||
# Remotion 성공 → 자막 합성본으로 덮어쓰기
|
||||
shutil.copy(remotion_out, served)
|
||||
|
||||
_set(
|
||||
job_id, status="done", stage=None, stage_index=2, progress=100,
|
||||
video_url=f"/outputs/{job_id}.mp4",
|
||||
)
|
||||
except Exception as e:
|
||||
# 어떤 단계에서 왜 실패했는지 uvicorn 콘솔에 전체 스택을 남긴다(디버깅 필수).
|
||||
print(f"[job {job_id}] FAILED at stage={get(job_id).get('stage') if get(job_id) else '?'}: {e}")
|
||||
traceback.print_exc()
|
||||
_set(job_id, status="error", error=str(e))
|
||||
finally:
|
||||
# 완료·실패 어느 쪽이든 임시 파일 정리 (outputs/ 의 최종본은 건드리지 않음)
|
||||
_cleanup(upload_dir, base_video, remotion_out, remotion_temps)
|
||||
|
||||
|
||||
def submit(req: GenerateRequest, photo_paths: list[Path], dry_run: bool) -> str:
|
||||
"""작업을 큐에 등록하고 job_id 를 즉시 반환(논블로킹)."""
|
||||
_purge_expired()
|
||||
job_id = uuid.uuid4().hex[:8]
|
||||
now = _now()
|
||||
with _lock:
|
||||
_jobs[job_id] = {
|
||||
"job_id": job_id,
|
||||
"status": "queued",
|
||||
"stage": None,
|
||||
"stage_index": 0,
|
||||
"progress": 0,
|
||||
"video_url": None,
|
||||
"caption": None,
|
||||
"profile": None,
|
||||
"cost_credits": 0.0,
|
||||
"error": None,
|
||||
"created_at": now,
|
||||
"updated_at": now,
|
||||
}
|
||||
_executor.submit(_run, job_id, req, photo_paths, dry_run)
|
||||
return job_id
|
||||
|
||||
|
||||
def get(job_id: str) -> dict | None:
|
||||
"""작업 상태 스냅샷(복사본) 반환. 없으면 None."""
|
||||
with _lock:
|
||||
job = _jobs.get(job_id)
|
||||
return dict(job) if job is not None else None
|
||||
+32
-44
@@ -1,7 +1,8 @@
|
||||
"""④ FastAPI orchestration — LLM → Higgsfield → Remotion wrapper.
|
||||
|
||||
POST /api/generate (multipart: photos[] + interview fields)
|
||||
→ build_spec (Claude) → higgsfield.generate → remotion.render → mp4
|
||||
POST /api/generate (multipart: photos[] + interview fields) → job_id 즉시 반환
|
||||
백그라운드 워커: build_spec (OpenAI) → higgsfield.generate → remotion.render → mp4
|
||||
GET /api/jobs/{id} 작업 상태 폴링 (queued | running | done | error)
|
||||
GET /api/health
|
||||
Static: /outputs/<file> (final videos), / (the web app)
|
||||
"""
|
||||
@@ -16,18 +17,18 @@ from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import FileResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from app.schemas import GenerateRequest, GenerateResult, ScriptResult
|
||||
from app.pipeline import spec_builder, higgsfield_client, remotion_render
|
||||
from app import config as cfg, jobs
|
||||
from app.schemas import GenerateRequest, JobStatus, ScriptResult
|
||||
from app.pipeline import spec_builder
|
||||
|
||||
ENGINE = Path(__file__).resolve().parents[2] # engine/higgsfield_shorts
|
||||
WEBAPP = ENGINE / "webapp"
|
||||
OUTPUTS = ENGINE / "server" / "outputs"
|
||||
UPLOADS = ENGINE / "server" / ".uploads"
|
||||
WEBAPP = cfg.WEBAPP_DIR
|
||||
OUTPUTS = cfg.OUTPUTS_DIR
|
||||
UPLOADS = cfg.UPLOADS_DIR
|
||||
OUTPUTS.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
app = FastAPI(title="ADO2 Higgsfield Shorts")
|
||||
app.add_middleware(
|
||||
CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"],
|
||||
CORSMiddleware, allow_origins=cfg.CORS_ORIGINS, allow_methods=["*"], allow_headers=["*"],
|
||||
)
|
||||
|
||||
|
||||
@@ -38,15 +39,15 @@ def health():
|
||||
|
||||
@app.post("/api/captions", response_model=ScriptResult)
|
||||
def captions(req: GenerateRequest):
|
||||
"""인터뷰 답변 → 인트로·셀링포인트·감성스토리·CTA 4블록 (Claude)."""
|
||||
"""인터뷰 답변 → 인트로·셀링포인트·감성스토리·CTA 4블록 (OpenAI)."""
|
||||
try:
|
||||
return spec_builder.build_script(req)
|
||||
except Exception as e:
|
||||
raise HTTPException(502, f"자막 생성 실패: {e}") from e
|
||||
|
||||
|
||||
@app.post("/api/generate", response_model=GenerateResult)
|
||||
async def generate(
|
||||
@app.post("/api/generate", response_model=JobStatus, status_code=202)
|
||||
def generate( # 논블로킹: 사진만 저장하고 작업을 큐에 넣은 뒤 job_id 반환
|
||||
photos: list[UploadFile] = File(...),
|
||||
kind: str = Form(...),
|
||||
biz_name: str = Form(...),
|
||||
@@ -58,49 +59,36 @@ async def generate(
|
||||
if len(photos) < 4:
|
||||
raise HTTPException(400, "사진 4장 이상이 필요합니다.")
|
||||
|
||||
# 1. Persist uploaded photos
|
||||
job = uuid.uuid4().hex[:8]
|
||||
job_dir = UPLOADS / job
|
||||
# 업로드 사진을 디스크에 저장 (워커 스레드가 경로로 읽음).
|
||||
# UploadFile 의 스트림은 요청 종료 후 닫히므로 반드시 여기서 영속화한다.
|
||||
upload_id = uuid.uuid4().hex[:8]
|
||||
job_dir = UPLOADS / upload_id
|
||||
job_dir.mkdir(parents=True, exist_ok=True)
|
||||
photo_paths: list[Path] = []
|
||||
for i, up in enumerate(photos):
|
||||
dest = job_dir / f"{i:02d}_{Path(up.filename or 'img').name}"
|
||||
# 원본 파일명에 한글·유니코드 문자가 있으면 fal 업로드 클라이언트가 ASCII 에러를 냄.
|
||||
# 확장자만 보존하고 나머지는 순수 숫자로 대체한다.
|
||||
suffix = Path(up.filename or "img.jpg").suffix.lower() or ".jpg"
|
||||
dest = job_dir / f"{i:02d}{suffix}"
|
||||
with dest.open("wb") as f:
|
||||
shutil.copyfileobj(up.file, f)
|
||||
photo_paths.append(dest)
|
||||
|
||||
req = GenerateRequest(kind=kind, biz_name=biz_name, addr=addr, price=price, selling=selling)
|
||||
|
||||
# 2. LLM → spec
|
||||
try:
|
||||
spec = spec_builder.build_spec(req)
|
||||
except Exception as e: # surface as a clean 502, don't swallow
|
||||
raise HTTPException(502, f"spec 생성 실패: {e}") from e
|
||||
# 파이프라인은 백그라운드 워커에서 실행 → 즉시 queued 상태를 돌려준다.
|
||||
job_id = jobs.submit(req, photo_paths, dry_run=dry_run)
|
||||
status = jobs.get(job_id)
|
||||
return JobStatus(**{k: status[k] for k in JobStatus.model_fields})
|
||||
|
||||
# 3. Higgsfield → base video
|
||||
try:
|
||||
base_video, credits = higgsfield_client.generate(
|
||||
spec.higgsfield_prompt, photo_paths, dry_run=dry_run
|
||||
)
|
||||
except Exception as e:
|
||||
raise HTTPException(502, f"Higgsfield 생성 실패: {e}") from e
|
||||
|
||||
# 4. Remotion → final with overlays
|
||||
try:
|
||||
final = remotion_render.render(spec, base_video)
|
||||
except Exception as e:
|
||||
raise HTTPException(502, f"Remotion 합성 실패: {e}") from e
|
||||
|
||||
served = OUTPUTS / f"{job}.mp4"
|
||||
shutil.copy(final, served)
|
||||
|
||||
return GenerateResult(
|
||||
video_url=f"/outputs/{job}.mp4",
|
||||
caption=spec.caption,
|
||||
profile=spec.profile,
|
||||
cost_credits=credits,
|
||||
job_id=job,
|
||||
)
|
||||
@app.get("/api/jobs/{job_id}", response_model=JobStatus)
|
||||
def job_status(job_id: str):
|
||||
"""작업 진행 상태 폴링. 프론트가 주기적으로 호출."""
|
||||
status = jobs.get(job_id)
|
||||
if status is None:
|
||||
raise HTTPException(404, "작업을 찾을 수 없습니다(만료되었거나 잘못된 ID).")
|
||||
return JobStatus(**{k: status[k] for k in JobStatus.model_fields})
|
||||
|
||||
|
||||
# Static mounts (after API routes)
|
||||
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -62,3 +62,20 @@ class GenerateResult(BaseModel):
|
||||
profile: str
|
||||
cost_credits: float = 0.0
|
||||
job_id: Optional[str] = None
|
||||
|
||||
|
||||
# ---------- Outbound: 비동기 작업 상태 (폴링) ----------
|
||||
class JobStatus(BaseModel):
|
||||
job_id: str
|
||||
# queued: 큐 대기 / running: 생성 중 / done: 완료 / error: 실패
|
||||
status: Literal["queued", "running", "done", "error"]
|
||||
stage: Optional[str] = Field(None, description="현재 단계: spec | higgsfield | remotion")
|
||||
stage_index: int = Field(0, description="단계 인덱스 0..2 (프론트 진행바 매핑)")
|
||||
progress: int = Field(0, description="전체 진행률 0..100 (대략)")
|
||||
# 완료 시 채워지는 결과 필드 (GenerateResult 와 동일 의미)
|
||||
video_url: Optional[str] = None
|
||||
caption: Optional[str] = None
|
||||
profile: Optional[str] = None
|
||||
cost_credits: float = 0.0
|
||||
# 실패 시 사용자에게 보여줄 메시지
|
||||
error: Optional[str] = None
|
||||
Reference in new issue
Block a user