Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,198 +1,220 @@
|
|
| 1 |
-
"""
|
| 2 |
-
AI Story-to-Video Generator — FastAPI Backend
|
| 3 |
-
CPU-safe: orchestration only. Heavy models routed to external APIs.
|
| 4 |
-
"""
|
| 5 |
-
|
| 6 |
-
# Load .env FIRST before any other imports that read os.getenv()
|
| 7 |
-
from dotenv import load_dotenv
|
| 8 |
-
load_dotenv()
|
| 9 |
-
|
| 10 |
-
import asyncio
|
| 11 |
-
import os
|
| 12 |
-
import sys
|
| 13 |
-
|
| 14 |
-
# Windows-specific: ensure ProactorEventLoop is used for subprocess support
|
| 15 |
-
if sys.platform == 'win32':
|
| 16 |
-
asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
|
| 17 |
-
from contextlib import asynccontextmanager
|
| 18 |
-
from fastapi import FastAPI, BackgroundTasks, HTTPException
|
| 19 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 20 |
-
from fastapi.staticfiles import StaticFiles
|
| 21 |
-
from pydantic import BaseModel, Field
|
| 22 |
-
from typing import Optional
|
| 23 |
-
|
| 24 |
-
from utils.job_manager import JobManager
|
| 25 |
-
from utils.storage import ensure_dirs
|
| 26 |
-
from pipeline.script_engine import ScriptEngine
|
| 27 |
-
from pipeline.image_engine import ImageEngine
|
| 28 |
-
from pipeline.video_engine import VideoEngine
|
| 29 |
-
from pipeline.tts_engine import TTSEngine
|
| 30 |
-
from pipeline.merge_engine import MergeEngine
|
| 31 |
-
|
| 32 |
-
# ---------------------------------------------------------------------------
|
| 33 |
-
# Lifespan
|
| 34 |
-
# ---------------------------------------------------------------------------
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
)
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
)
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
# ---------------------------------------------------------------------------
|
| 87 |
-
#
|
| 88 |
-
# ---------------------------------------------------------------------------
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
update(
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
)
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
AI Story-to-Video Generator — FastAPI Backend
|
| 3 |
+
CPU-safe: orchestration only. Heavy models routed to external APIs.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
# Load .env FIRST before any other imports that read os.getenv()
|
| 7 |
+
from dotenv import load_dotenv
|
| 8 |
+
load_dotenv()
|
| 9 |
+
|
| 10 |
+
import asyncio
|
| 11 |
+
import os
|
| 12 |
+
import sys
|
| 13 |
+
|
| 14 |
+
# Windows-specific: ensure ProactorEventLoop is used for subprocess support
|
| 15 |
+
if sys.platform == 'win32':
|
| 16 |
+
asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
|
| 17 |
+
from contextlib import asynccontextmanager
|
| 18 |
+
from fastapi import FastAPI, BackgroundTasks, HTTPException
|
| 19 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 20 |
+
from fastapi.staticfiles import StaticFiles
|
| 21 |
+
from pydantic import BaseModel, Field
|
| 22 |
+
from typing import Optional
|
| 23 |
+
|
| 24 |
+
from utils.job_manager import JobManager
|
| 25 |
+
from utils.storage import ensure_dirs
|
| 26 |
+
from pipeline.script_engine import ScriptEngine
|
| 27 |
+
from pipeline.image_engine import ImageEngine
|
| 28 |
+
from pipeline.video_engine import VideoEngine
|
| 29 |
+
from pipeline.tts_engine import TTSEngine
|
| 30 |
+
from pipeline.merge_engine import MergeEngine
|
| 31 |
+
|
| 32 |
+
# ---------------------------------------------------------------------------
|
| 33 |
+
# Lifespan
|
| 34 |
+
# ---------------------------------------------------------------------------
|
| 35 |
+
async def cleanup_task():
|
| 36 |
+
"""Background task to delete old temp files and outputs every hour."""
|
| 37 |
+
import shutil
|
| 38 |
+
import time
|
| 39 |
+
while True:
|
| 40 |
+
try:
|
| 41 |
+
now = time.time()
|
| 42 |
+
# Clean /temp and /outputs older than 2 hours
|
| 43 |
+
for folder in ["temp", "outputs"]:
|
| 44 |
+
if os.path.exists(folder):
|
| 45 |
+
for item in os.listdir(folder):
|
| 46 |
+
path = os.path.join(folder, item)
|
| 47 |
+
if os.path.getmtime(path) < now - (2 * 3600):
|
| 48 |
+
if os.path.isdir(path):
|
| 49 |
+
shutil.rmtree(path)
|
| 50 |
+
else:
|
| 51 |
+
os.remove(path)
|
| 52 |
+
except Exception as e:
|
| 53 |
+
print(f"🧹 Cleanup error: {e}")
|
| 54 |
+
await asyncio.sleep(3600) # Sleep 1 hour
|
| 55 |
+
|
| 56 |
+
@asynccontextmanager
|
| 57 |
+
async def lifespan(app: FastAPI):
|
| 58 |
+
ensure_dirs()
|
| 59 |
+
asyncio.create_task(cleanup_task())
|
| 60 |
+
yield
|
| 61 |
+
|
| 62 |
+
app = FastAPI(
|
| 63 |
+
title="AI Story-to-Video Generator",
|
| 64 |
+
description="CPU-safe pipeline: orchestrates LLM, image, video, and TTS APIs.",
|
| 65 |
+
version="1.0.0",
|
| 66 |
+
lifespan=lifespan,
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
app.add_middleware(
|
| 70 |
+
CORSMiddleware,
|
| 71 |
+
allow_origins=["*"],
|
| 72 |
+
allow_credentials=True,
|
| 73 |
+
allow_methods=["*"],
|
| 74 |
+
allow_headers=["*"],
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
# Serve finished videos
|
| 78 |
+
os.makedirs("outputs", exist_ok=True)
|
| 79 |
+
app.mount("/outputs", StaticFiles(directory="outputs"), name="outputs")
|
| 80 |
+
|
| 81 |
+
# ---------------------------------------------------------------------------
|
| 82 |
+
# Shared state
|
| 83 |
+
# ---------------------------------------------------------------------------
|
| 84 |
+
job_manager = JobManager()
|
| 85 |
+
|
| 86 |
+
# ---------------------------------------------------------------------------
|
| 87 |
+
# Request / Response schemas
|
| 88 |
+
# ---------------------------------------------------------------------------
|
| 89 |
+
class GenerateRequest(BaseModel):
|
| 90 |
+
story: str = Field(..., min_length=10, max_length=4000, description="User story or prompt")
|
| 91 |
+
style: str = Field(default="cinematic", description="Visual style (cinematic, anime, watercolor, …)")
|
| 92 |
+
duration: int = Field(default=30, ge=10, le=60, description="Target video duration in seconds")
|
| 93 |
+
aspect_ratio: str = Field(default="16:9", description="Output aspect ratio: 16:9 or 9:16")
|
| 94 |
+
|
| 95 |
+
class GenerateResponse(BaseModel):
|
| 96 |
+
job_id: str
|
| 97 |
+
message: str
|
| 98 |
+
|
| 99 |
+
class StatusResponse(BaseModel):
|
| 100 |
+
job_id: str
|
| 101 |
+
status: str # queued | running | completed | failed
|
| 102 |
+
progress: int # 0-100
|
| 103 |
+
stage: str
|
| 104 |
+
video_url: Optional[str] = None
|
| 105 |
+
script: Optional[dict] = None
|
| 106 |
+
error: Optional[str] = None
|
| 107 |
+
|
| 108 |
+
# ---------------------------------------------------------------------------
|
| 109 |
+
# Background pipeline
|
| 110 |
+
# ---------------------------------------------------------------------------
|
| 111 |
+
async def run_pipeline(job_id: str, req: GenerateRequest):
|
| 112 |
+
"""Full async pipeline executed in the background."""
|
| 113 |
+
def update(progress: int, stage: str):
|
| 114 |
+
job_manager.update(job_id, progress=progress, stage=stage)
|
| 115 |
+
|
| 116 |
+
try:
|
| 117 |
+
job_manager.update(job_id, status="running", progress=5, stage="Generating screenplay…")
|
| 118 |
+
|
| 119 |
+
# STEP 1 — Script
|
| 120 |
+
script = await ScriptEngine().generate(
|
| 121 |
+
story=req.story,
|
| 122 |
+
style=req.style,
|
| 123 |
+
duration=req.duration,
|
| 124 |
+
)
|
| 125 |
+
job_manager.update(job_id, progress=15, stage="Screenplay ready", script=script)
|
| 126 |
+
|
| 127 |
+
scenes = script.get("scenes", [])
|
| 128 |
+
if not scenes:
|
| 129 |
+
raise ValueError("Script engine returned no scenes.")
|
| 130 |
+
|
| 131 |
+
# Clamp to 6-8 scenes
|
| 132 |
+
scenes = scenes[:8]
|
| 133 |
+
script["scenes"] = scenes
|
| 134 |
+
|
| 135 |
+
# STEP 2 — Character images
|
| 136 |
+
update(20, "Generating character references…")
|
| 137 |
+
image_engine = ImageEngine()
|
| 138 |
+
char_images = await image_engine.generate_characters(
|
| 139 |
+
characters=script.get("characters", []),
|
| 140 |
+
style=req.style,
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
# STEP 3 — Storyboard keyframes (parallel)
|
| 144 |
+
update(35, "Generating storyboard frames…")
|
| 145 |
+
frame_paths = await image_engine.generate_storyboard(
|
| 146 |
+
scenes=scenes,
|
| 147 |
+
char_images=char_images,
|
| 148 |
+
style=req.style,
|
| 149 |
+
job_id=job_id,
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
# STEP 4 — Video clips
|
| 153 |
+
update(55, "Animating scenes…")
|
| 154 |
+
video_engine = VideoEngine()
|
| 155 |
+
clip_paths = await video_engine.animate_scenes(
|
| 156 |
+
frame_paths=frame_paths,
|
| 157 |
+
scenes=scenes,
|
| 158 |
+
job_id=job_id,
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
# STEP 5 — TTS narration
|
| 162 |
+
update(75, "Generating narration audio…")
|
| 163 |
+
tts_engine = TTSEngine()
|
| 164 |
+
audio_path = await tts_engine.generate(
|
| 165 |
+
script=script,
|
| 166 |
+
job_id=job_id,
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
# STEP 6 — Merge
|
| 170 |
+
update(88, "Merging final video…")
|
| 171 |
+
merge_engine = MergeEngine()
|
| 172 |
+
output_path = await merge_engine.merge(
|
| 173 |
+
clip_paths=clip_paths,
|
| 174 |
+
audio_path=audio_path,
|
| 175 |
+
aspect_ratio=req.aspect_ratio,
|
| 176 |
+
job_id=job_id,
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
video_url = f"/outputs/{os.path.basename(output_path)}"
|
| 180 |
+
job_manager.update(
|
| 181 |
+
job_id,
|
| 182 |
+
status="completed",
|
| 183 |
+
progress=100,
|
| 184 |
+
stage="Done!",
|
| 185 |
+
video_url=video_url,
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
except Exception as exc:
|
| 189 |
+
import traceback
|
| 190 |
+
tb = traceback.format_exc()
|
| 191 |
+
error_msg = str(exc) or tb.split("\n")[-2] if tb else "Unknown error"
|
| 192 |
+
print(f"\n❌ PIPELINE ERROR (job {job_id}):\n{tb}")
|
| 193 |
+
job_manager.update(job_id, status="failed", stage="Pipeline error", error=error_msg)
|
| 194 |
+
|
| 195 |
+
# ---------------------------------------------------------------------------
|
| 196 |
+
# Routes
|
| 197 |
+
# ---------------------------------------------------------------------------
|
| 198 |
+
@app.post("/generate", response_model=GenerateResponse, status_code=202)
|
| 199 |
+
async def generate(req: GenerateRequest, background_tasks: BackgroundTasks):
|
| 200 |
+
"""Start a video generation job. Returns job_id immediately."""
|
| 201 |
+
if job_manager.active_count() >= int(os.getenv("MAX_CONCURRENT_JOBS", "2")):
|
| 202 |
+
raise HTTPException(status_code=429, detail="Server busy. Try again shortly.")
|
| 203 |
+
|
| 204 |
+
job_id = job_manager.create()
|
| 205 |
+
background_tasks.add_task(run_pipeline, job_id, req)
|
| 206 |
+
return GenerateResponse(job_id=job_id, message="Job queued successfully.")
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
@app.get("/status/{job_id}", response_model=StatusResponse)
|
| 210 |
+
async def status(job_id: str):
|
| 211 |
+
"""Poll job status."""
|
| 212 |
+
job = job_manager.get(job_id)
|
| 213 |
+
if not job:
|
| 214 |
+
raise HTTPException(status_code=404, detail="Job not found.")
|
| 215 |
+
return StatusResponse(job_id=job_id, **job)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
@app.get("/health")
|
| 219 |
+
async def health():
|
| 220 |
+
return {"status": "ok", "active_jobs": job_manager.active_count()}
|