Spaces:
Paused
Paused
Commit ·
b7691c7
1
Parent(s): d47df1b
Upgrade UI: gallery, progress tracking, tabs, image preview, polished design
Browse files1234567891011121314151617181920212223242526272829303132333435363738393 unmodified lines434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248"""Wan2.2 TI2V 5B — Text-to-Video & Image-to-VideoFastAPI app for Hugging Face Docker Space."""import osimport ioimport gcimport tempfileimport shutilfrom pathlib import Pathfrom contextlib import asynccontextmanagerimport torchimport numpy as npfrom fastapi import FastAPI, Form, UploadFile, File, HTTPExceptionfrom fastapi.responses import FileResponse, HTMLResponsefrom diffusers import WanPipeline, AutoencoderKLWanfrom diffusers.utils import export_to_video# ---------- Model config ----------MODEL_ID = os.getenv("MODEL_ID", "Wan-AI/Wan2.2-TI2V-5B-Diffusers")HF_CACHE = Path(os.getenv("HF_HOME", os.path.expanduser("~/.cache/huggingface")))OUTPUT_DIR = Path("/tmp/outputs")OUTPUT_DIR.mkdir(parents=True, exist_ok=True)# Device — will be set at startupDEVICE = NoneDTYPE = torch.bfloat16# Global pipeline placeholderpipe = Nonedef free_memory():"""Aggressively free GPU / CPU memory."""gc.collect()if torch.cuda.is_available():torch.cuda.empty_cache()3 unmodified lines@asynccontextmanagerasync def lifespan(app: FastAPI):global DEVICE, pipeDEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")print(f"[startup] device={DEVICE}")if not torch.cuda.is_available():raise RuntimeError("CUDA GPU is required. Please add a GPU to this Space.")print(f"[startup] VRAM: {torch.cuda.get_device_properties(0).total_mem / 1e9:.1f} GB")print(f"[startup] Loading Wan2.2-TI2V-5B from {MODEL_ID} …")# VAE must be float32 for decoding qualityvae = AutoencoderKLWan.from_pretrained(MODEL_ID,subfolder="vae",torch_dtype=torch.float32,cache_dir=str(HF_CACHE),)pipe = WanPipeline.from_pretrained(MODEL_ID,vae=vae,torch_dtype=DTYPE,cache_dir=str(HF_CACHE),)pipe.to(DEVICE)print("[startup] Model loaded. Ready.")yield# Shutdownfree_memory()print("[shutdown] Cleaned up.")app = FastAPI(lifespan=lifespan, title="Wan2.2 TI2V 5B")# ---------- HTML homepage ----------@app.get("/", response_class=HTMLResponse)def index():return HTMLResponse("""<!DOCTYPE html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>Wan2.2 TI2V 5B — Video Generator</title><style>* { box-sizing: border-box; margin: 0; padding: 0; }body {font-family: -apple-system, 'Segoe UI', Roboto, sans-serif;background: #0b0b12;color: #e0e0e0;min-height: 100vh;display: flex; align-items: center; justify-content: center;}.card {background: #1a1a2e;border-radius: 16px;padding: 2.5rem;max-width: 640px;width: 100%;box-shadow: 0 4px 40px rgba(100, 60, 255, 0.12);}h1 { font-size: 1.6rem; margin-bottom: 0.25rem; }.sub { color: #888; font-size: 0.9rem; margin-bottom: 1.5rem; }label { display: block; margin-top: 1rem; margin-bottom: 0.35rem; font-weight: 600; }textarea, input {width: 100%; padding: 0.7rem 0.9rem;border-radius: 10px; border: 1px solid #333;background: #12121f; color: #e0e0e0;font-size: 0.95rem;}textarea { resize: vertical; min-height: 80px; }button {margin-top: 1.5rem; width: 100%; padding: 0.8rem;border: none; border-radius: 10px;background: linear-gradient(135deg, #6c3ef0, #4a2fb0);color: #fff; font-weight: 700; font-size: 1rem;cursor: pointer; transition: opacity .2s;}button:hover { opacity: 0.92; }button:disabled { opacity: 0.5; cursor: not-allowed; }.note { margin-top: 1.2rem; font-size: 0.78rem; color: #666; }.result { margin-top: 1.5rem; }.result video { width: 100%; border-radius: 10px; }a { color: #9f7aea; }</style></head><body><div class="card"><h1>🐳 Wan2.2 TI2V 5B</h1><p class="sub">Text-to-Video & Image-to-Video — 720p @ 24 fps</p><form action="/generate" method="post" enctype="multipart/form-data"><label for="prompt">Prompt</label><textarea name="prompt" id="prompt" placeholder="Describe what you want to see…" required>A cat wearing a spacesuit floating through a colorful nebula, cinematic lighting, 4K</textarea><label for="image">Image (optional — enables image-to-video)</label><input type="file" name="image" id="image" accept="image/*" /><label for="steps">Steps (20–50, lower = faster)</label><input type="number" name="steps" id="steps" value="30" min="20" max="50" /><button type="submit">Generate Video</button></form><p class="note">⚡ First run downloads model (~54 GB). Subsequent runs are faster.<br />🔧 Built on <a href="https://huggingface.co/Wan-AI/Wan2.2-TI2V-5B-Diffusers" target="_blank">Wan-AI/Wan2.2-TI2V-5B-Diffusers</a></p></div></body></html>""")# ---------- Generate endpoint ----------@app.post("/generate")async def generate(prompt: str = Form(..., description="Text prompt for generation"),image: UploadFile = File(None),steps: int = Form(30, ge=20, le=50),guidance_scale: float = Form(5.0),):global pipeif pipe is None:raise HTTPException(503, "Model still loading — please wait and retry.")# Load reference image if providedinput_image = Noneif image and image.filename:try:contents = await image.read()from PIL import Image as PILImageinput_image = PILImage.open(io.BytesIO(contents)).convert("RGB")except Exception as e:raise HTTPException(400, f"Failed to read image: {e}")height, width = 704, 1280num_frames = 81 # ~3.4 sec at 24 fpsoutput_name = "output.mp4"output_path = OUTPUT_DIR / output_nameprint(f"[generate] prompt={prompt[:100]!r} | image={input_image is not None} | steps={steps}")try:if input_image is not None:# Image-to-Video: aspect ratio follows input imageaspect = input_image.height / input_image.widthmax_area = height * widthmod = pipe.vae_scale_factor_spatial * pipe.transformer.config.patch_size[1]h = round(np.sqrt(max_area * aspect)) // mod * modw = round(np.sqrt(max_area / aspect)) // mod * modinput_image = input_image.resize((w, h))frames = pipe(prompt=prompt,image=input_image,height=h,width=w,num_frames=num_frames,num_inference_steps=steps,guidance_scale=guidance_scale,).frames[0]else:# Text-to-Videoframes = pipe(prompt=prompt,height=height,width=width,num_frames=num_frames,num_inference_steps=steps,guidance_scale=guidance_scale,).frames[0]export_to_video(frames, str(output_path), fps=24)except torch.cuda.OutOfMemoryError:free_memory()raise HTTPException(507,"GPU out of memory. Try fewer frames (num_frames=41) or switch to a larger GPU tier (L4 / A10G).")except Exception as e:free_memory()raise HTTPException(500, f"Generation failed: {e}")free_memory()return FileResponse(output_path,media_type="video/mp4",filename=output_name,)# ---------- Health check ----------@app.get("/health")def health():gpu_ok = torch.cuda.is_available()return {"status": "ok" if gpu_ok and pipe is not None else "loading","gpu": gpu_ok,"model_loaded": pipe is not None,}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657583 unmodified lines6263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484"""Wan2.2 TI2V 5B — Text-to-Video & Image-to-VideoProduction FastAPI app for Hugging Face Docker Space."""import osimport ioimport gcimport jsonimport uuidimport timeimport asynciofrom pathlib import Pathfrom contextlib import asynccontextmanagerfrom datetime import datetimefrom typing import Optionalimport torchimport numpy as npfrom fastapi import FastAPI, Form, UploadFile, File, HTTPException, Queryfrom fastapi.responses import FileResponse, HTMLResponse, JSONResponsefrom fastapi.staticfiles import StaticFilesfrom diffusers import WanPipeline, AutoencoderKLWanfrom diffusers.utils import export_to_video# ---------- Config ----------MODEL_ID = os.getenv("MODEL_ID", "Wan-AI/Wan2.2-TI2V-5B-Diffusers")HF_CACHE = Path(os.getenv("HF_HOME", os.path.expanduser("~/.cache/huggingface")))OUTPUT_DIR = Path("/tmp/outputs")OUTPUT_DIR.mkdir(parents=True, exist_ok=True)JOBS_FILE = OUTPUT_DIR / "jobs.json"DEVICE = NoneDTYPE = torch.bfloat16pipe = None# Job store (in-memory + persisted)_jobs: dict = {}_job_lock = asyncio.Lock()def _load_jobs():global _jobsif JOBS_FILE.exists():try:_jobs = json.loads(JOBS_FILE.read_text())except Exception:_jobs = {}def _save_jobs():JOBS_FILE.write_text(json.dumps(_jobs, default=str))def free_memory():gc.collect()if torch.cuda.is_available():torch.cuda.empty_cache()3 unmodified lines@asynccontextmanagerasync def lifespan(app: FastAPI):global DEVICE, pipe_load_jobs()DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")if not torch.cuda.is_available():raise RuntimeError("CUDA GPU required — add a GPU to this Space (Settings → Hardware).")vram_gb = torch.cuda.get_device_properties(0).total_mem / 1e9print(f"[startup] GPU: {torch.cuda.get_device_name(0)} ({vram_gb:.1f} GB VRAM)")print(f"[startup] Loading {MODEL_ID} …")vae = AutoencoderKLWan.from_pretrained(MODEL_ID, subfolder="vae", torch_dtype=torch.float32, cache_dir=str(HF_CACHE))pipe = WanPipeline.from_pretrained(MODEL_ID, vae=vae, torch_dtype=DTYPE, cache_dir=str(HF_CACHE))pipe.to(DEVICE)print("[startup] Ready.")yieldfree_memory()app = FastAPI(lifespan=lifespan, title="Wan2.2 TI2V 5B")# ----- Serving -----async def _run_generation(job_id: str, prompt: str, input_image, steps: int, guidance_scale: float,num_frames: int, seed: Optional[int]):_jobs[job_id]["status"] = "running"_jobs[job_id]["started_at"] = time.time()_save_jobs()out_name = f"{job_id}.mp4"out_path = OUTPUT_DIR / out_nametry:height, width = 704, 1280if input_image is not None:aspect = input_image.height / input_image.widthmax_area = height * widthmod = pipe.vae_scale_factor_spatial * pipe.transformer.config.patch_size[1]h = round(np.sqrt(max_area * aspect)) // mod * modw = round(np.sqrt(max_area / aspect)) // mod * modinput_image = input_image.resize((w, h))height, width = h, wgen_kwargs = dict(prompt=prompt,height=height,width=width,num_frames=num_frames,num_inference_steps=steps,guidance_scale=guidance_scale,)if input_image is not None:gen_kwargs["image"] = input_imageif seed is not None:gen_kwargs["generator"] = torch.Generator(device=DEVICE).manual_seed(seed)frames = pipe(**gen_kwargs).frames[0]export_to_video(frames, str(out_path), fps=24)duration = round(time.time() - _jobs[job_id]["started_at"], 1)_jobs[job_id]["status"] = "done"_jobs[job_id]["duration"] = duration_jobs[job_id]["output"] = f"/output/{out_name}"_jobs[job_id]["width"] = width_jobs[job_id]["height"] = heightexcept torch.cuda.OutOfMemoryError:_jobs[job_id]["status"] = "error"_jobs[job_id]["error"] = "GPU out of memory. Try fewer frames or upgrade GPU tier."except Exception as e:_jobs[job_id]["status"] = "error"_jobs[job_id]["error"] = str(e)finally:free_memory()_save_jobs()# ---------- UI ----------@app.get("/", response_class=HTMLResponse)def index():return HTMLResponse("""<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/><title>Wan2.2 TI2V 5B — Video Generator</title><style>:root {--bg: #0a0a14; --surface: #13132a; --surface2: #1c1c3a;--border: #2a2a4a; --text: #e2e2f0; --text2: #8888aa;--accent: #7c4dff; --accent2: #b388ff; --danger: #ff5252;--radius: 14px; --shadow: 0 4px 40px rgba(124,77,255,0.08);}*{box-sizing:border-box;margin:0;padding:0}body{font-family:-apple-system,'Segoe UI',Roboto,sans-serif;background:var(--bg);color:var(--text);min-height:100vh}.app{max-width:1100px;margin:0 auto;padding:1.5rem}header{text-align:center;padding:1.5rem 0}header h1{font-size:2rem;background:linear-gradient(135deg,var(--accent),var(--accent2));-webkit-background-clip:text;-webkit-text-fill-color:transparent}header .tagline{color:var(--text2);margin-top:.4rem;font-size:.95rem}.layout{display:grid;grid-template-columns:1fr 1fr;gap:1.5rem;align-items:start}@media(max-width:800px){.layout{grid-template-columns:1fr}}.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:1.5rem;box-shadow:var(--shadow)}.card h2{font-size:1.15rem;margin-bottom:1rem;display:flex;align-items:center;gap:.5rem}.field{margin-bottom:1rem}.field label{display:block;font-weight:600;margin-bottom:.35rem;font-size:.88rem;color:var(--text2)}.field textarea,.field input,.field select{width:100%;padding:.7rem .85rem;border-radius:10px;border:1px solid var(--border);background:var(--surface2);color:var(--text);font-size:.93rem;font-family:inherit}.field textarea{resize:vertical;min-height:90px}.field textarea:focus,.field input:focus,.field select:focus{outline:none;border-color:var(--accent);box-shadow:0 0 0 3px rgba(124,77,255,.15)}.row{display:grid;grid-template-columns:1fr 1fr;gap:1rem}.btn{display:inline-flex;align-items:center;justify-content:center;gap:.5rem;padding:.75rem 1.5rem;border:none;border-radius:10px;font-weight:700;font-size:.95rem;cursor:pointer;transition:all .2s}.btn-primary{background:linear-gradient(135deg,var(--accent),#5e3fcc);color:#fff;width:100%}.btn-primary:hover{opacity:.92;transform:translateY(-1px)}.btn-primary:disabled{opacity:.45;cursor:not-allowed;transform:none}.file-upload{border:2px dashed var(--border);border-radius:var(--radius);padding:1.5rem;text-align:center;cursor:pointer;transition:border-color .2s;position:relative}.file-upload:hover{border-color:var(--accent)}.file-upload .icon{font-size:2rem;margin-bottom:.5rem}.file-upload .hint{color:var(--text2);font-size:.85rem}.file-upload input[type=file]{position:absolute;inset:0;opacity:0;cursor:pointer}.file-upload.has-image{padding:.5rem}.file-upload img{max-height:140px;border-radius:8px}.preview-name{font-size:.85rem;color:var(--accent2);margin-top:.3rem}/* Gallery */.gallery{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:.75rem;max-height:70vh;overflow-y:auto;padding-right:.3rem}.job-card{background:var(--surface2);border:1px solid var(--border);border-radius:10px;overflow:hidden}.job-card video{width:100%;display:block;border-radius:10px 10px 0 0;background:#000}.job-card .meta{padding:.6rem .8rem;font-size:.8rem}.job-card .prompt{color:var(--text);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-bottom:.2rem}.job-card .info{color:var(--text2);display:flex;justify-content:space-between}.job-card .status{font-weight:600}.job-card .status.running{color:#ffab40}.job-card .status.done{color:#69f0ae}.job-card .status.error{color:var(--danger)}.job-card .status.queued{color:var(--text2)}.empty-state{text-align:center;padding:2.5rem 1rem;color:var(--text2)}.empty-state .icon{font-size:3rem;margin-bottom:.8rem}.spinner{display:inline-block;width:1rem;height:1rem;border:2px solid var(--text2);border-top-color:var(--accent);border-radius:50%;animation:spin .7s linear infinite}@keyframes spin{to{transform:rotate(360deg)}}.progress-bar{height:4px;background:var(--border);border-radius:2px;margin-top:.5rem;overflow:hidden}.progress-bar .fill{height:100%;background:linear-gradient(90deg,var(--accent),var(--accent2));border-radius:2px;transition:width .3s}#status-msg{font-size:.85rem;color:var(--accent2);margin-top:.75rem;min-height:1.2em}.tabs{display:flex;gap:.25rem;margin-bottom:1rem;background:var(--surface2);border-radius:10px;padding:3px}.tab{padding:.5rem 1rem;border-radius:8px;cursor:pointer;font-size:.88rem;font-weight:600;color:var(--text2);transition:.15s}.tab.active{background:var(--accent);color:#fff}.tab:hover:not(.active){color:var(--text)}footer{text-align:center;padding:2rem 1rem;color:var(--text2);font-size:.8rem}footer a{color:var(--accent2)}</style></head><body><div class="app"><header><h1>🎬 Wan2.2 TI2V 5B</h1><p class="tagline">Text-to-Video & Image-to-Video · 720p @ 24fps · Single-GPU</p></header><div class="layout"><!-- Left: Generation Form --><div class="card"><h2>✨ Create Video</h2><form id="gen-form"><div class="field"><label for="prompt">Prompt</label><textarea id="prompt" name="prompt" placeholder="Describe what you want to see…" required></textarea></div><div class="field"><label>Reference Image <span style="color:var(--text2);font-weight:400">(optional — enables image-to-video)</span></label><div class="file-upload" id="file-area"><div id="file-placeholder"><div class="icon">🖼️</div><p class="hint">Click or drag to upload an image</p></div><img id="preview-img" style="display:none" alt=""/><div class="preview-name" id="preview-name" style="display:none"></div><input type="file" id="image" name="image" accept="image/*"/></div></div><div class="row"><div class="field"><label for="steps">Steps <span style="color:var(--text2);font-weight:400">(20–50)</span></label><input type="number" id="steps" value="30" min="20" max="50"/></div><div class="field"><label for="frames">Frames <span style="color:var(--text2);font-weight:400">(9–121)</span></label><input type="number" id="frames" value="81" min="9" max="121"/></div></div><div class="row"><div class="field"><label for="guidance">Guidance Scale</label><input type="number" id="guidance" value="5" min="1" max="10" step="0.5"/></div><div class="field"><label for="seed">Seed <span style="color:var(--text2);font-weight:400">(empty = random)</span></label><input type="number" id="seed" placeholder="Random"/></div></div><button type="submit" class="btn btn-primary" id="submit-btn">🎬 Generate Video</button><div id="status-msg"></div><div class="progress-bar" id="progress-bar" style="display:none"><div class="fill" style="width:0%"></div></div></form></div><!-- Right: Gallery --><div class="card"><div class="tabs"><div class="tab active" data-tab="gallery">📽️ Gallery</div><div class="tab" data-tab="api">📡 API</div></div><div id="tab-gallery"><div class="gallery" id="gallery"></div><div class="empty-state" id="empty-state"><div class="icon">🎞️</div><p>Your generated videos will appear here</p></div></div><div id="tab-api" style="display:none"><h2 style="font-size:1rem;margin-bottom:.5rem">API Usage</h2><p style="color:var(--text2);font-size:.85rem;margin-bottom:1rem">The <code>/generate</code> endpoint accepts form-data POST:</p><pre style="background:var(--surface2);padding:1rem;border-radius:10px;overflow-x:auto;font-size:.8rem;line-height:1.5;color:var(--text)"><b># Text-to-Video</b>curl -X POST <span id="api-url">…</span>/generate \\-F "prompt=A cat astronaut in space" \\-F "steps=30" -F "num_frames=81" \\-o video.mp4<b># Image-to-Video</b>curl -X POST <span id="api-url2">…</span>/generate \\-F "prompt=Animate this scene" \\-F "image=@cat.jpg" \\-F "steps=30" -o video.mp4<b># Check status</b>curl <span id="api-url3">…</span>/health | jq</pre></div></div></div><footer>Powered by <a href="https://huggingface.co/Wan-AI/Wan2.2-TI2V-5B-Diffusers" target="_blank">Wan-AI/Wan2.2-TI2V-5B</a>· Apache 2.0 · Diffusers</footer></div><script>const API = window.location.origin;document.querySelectorAll('#api-url,#api-url2,#api-url3').forEach(e=>e.textContent=API);const form = document.getElementById('gen-form');const submitBtn = document.getElementById('submit-btn');const statusMsg = document.getElementById('status-msg');const progressBar = document.getElementById('progress-bar');const progressFill = progressBar.querySelector('.fill');const gallery = document.getElementById('gallery');const emptyState = document.getElementById('empty-state');// File previewconst imageInput = document.getElementById('image');const previewImg = document.getElementById('preview-img');const previewName = document.getElementById('preview-name');const filePlaceholder = document.getElementById('file-placeholder');const fileArea = document.getElementById('file-area');imageInput.addEventListener('change',()=>{const f=imageInput.files[0];if(!f){previewImg.style.display='none';previewName.style.display='none';filePlaceholder.style.display='';fileArea.classList.remove('has-image');return}fileArea.classList.add('has-image');filePlaceholder.style.display='none';previewImg.style.display='';previewName.style.display='';previewName.textContent=f.name;const r=new FileReader();r.onload=e=>{previewImg.src=e.target.result};r.readAsDataURL(f);});// Tabsdocument.querySelectorAll('.tab').forEach(t=>t.addEventListener('click',()=>{document.querySelectorAll('.tab').forEach(x=>x.classList.remove('active'));t.classList.add('active');document.getElementById('tab-gallery').style.display=t.dataset.tab==='gallery'?'':'none';document.getElementById('tab-api').style.display=t.dataset.tab==='api'?'':'none';}));// Submitform.addEventListener('submit',async e=>{e.preventDefault();submitBtn.disabled=true;statusMsg.textContent='⏳ Queuing…';progressBar.style.display='';progressFill.style.width='10%';const fd=new FormData(form);try{const res=await fetch(API+'/generate',{method:'POST',body:fd});if(!res.ok){const t=await res.text();throw new Error(t||res.statusText)}progressFill.style.width='95%';statusMsg.textContent='✅ Done! Refreshing gallery…';setTimeout(loadGallery,1500);}catch(err){statusMsg.textContent='❌ '+err.message;progressBar.style.display='none';}finally{submitBtn.disabled=false;setTimeout(()=>{progressBar.style.display='none';statusMsg.textContent=''},4000);}});// Load galleryasync function loadGallery(){try{const res=await fetch(API+'/jobs');const jobs=await res.json();if(!jobs||!jobs.length){gallery.innerHTML='';emptyState.style.display='';return}emptyState.style.display='none';gallery.innerHTML=jobs.reverse().map(j=>{const dur=j.duration?j.duration+'s':'';const statusCls=j.status;if(j.status==='done'&&j.output){return `<div class="job-card"><video src="${j.output}" controls preload="metadata"></video><div class="meta"><div class="prompt">${esc(j.prompt)}</div><div class="info"><span class="status ${statusCls}">✓ Done</span><span>${dur}</span></div></div></div>`;}else if(j.status==='running'){return `<div class="job-card" style="padding:2rem;text-align:center"><div class="spinner"></div><div class="meta" style="margin-top:.5rem"><div class="prompt">${esc(j.prompt)}</div><div class="info"><span class="status running">Generating…</span></div></div></div>`;}else if(j.status==='queued'){return `<div class="job-card" style="padding:2rem;text-align:center"><div style="font-size:2rem">⏳</div><div class="meta"><div class="prompt">${esc(j.prompt)}</div><div class="info"><span class="status queued">Queued</span></div></div></div>`;}else{return `<div class="job-card" style="padding:1.5rem;text-align:center"><div style="font-size:1.5rem">⚠️</div><div class="meta"><div class="prompt">${esc(j.prompt)}</div><div class="info"><span class="status error">Error</span><span>${esc(j.error||'')}</span></div></div></div>`;}}).join('');}catch(e){console.error(e)}}function esc(s){const d=document.createElement('div');d.textContent=s||'';return d.innerHTML}// Poll running jobssetInterval(loadGallery,5000);loadGallery();</script></body></html>""")# ---------- Generate endpoint ----------@app.post("/generate")async def generate(prompt: str = Form(...),image: UploadFile = File(None),steps: int = Form(30, ge=20, le=50),num_frames: int = Form(81, ge=9, le=121),guidance_scale: float = Form(5.0),seed: Optional[int] = Form(None),):global pipeif pipe is None:raise HTTPException(503, "Model still loading — try again in a moment.")input_image = Noneif image and image.filename:try:from PIL import Image as PILImagecontents = await image.read()input_image = PILImage.open(io.BytesIO(contents)).convert("RGB")except Exception as e:raise HTTPException(400, f"Failed to read image: {e}")job_id = uuid.uuid4().hex[:12]_jobs[job_id] = {"id": job_id,"prompt": prompt[:300],"status": "queued","steps": steps,"num_frames": num_frames,"guidance_scale": guidance_scale,"seed": seed,"has_image": input_image is not None,"created_at": datetime.utcnow().isoformat(),}_save_jobs()# Run generation in backgroundasyncio.create_task(_run_generation(job_id, prompt, input_image, steps, guidance_scale, num_frames, seed))# Poll until done (max 10 minutes)for _ in range(600):await asyncio.sleep(1)status = _jobs.get(job_id, {}).get("status")if status == "done":return FileResponse(str(OUTPUT_DIR / f"{job_id}.mp4"), media_type="video/mp4", filename=f"wan2.2_{job_id}.mp4")if status == "error":raise HTTPException(500, _jobs[job_id].get("error", "Unknown error"))raise HTTPException(504, "Generation timed out after 10 minutes.")# ---------- Gallery / Jobs API ----------@app.get("/jobs")async def list_jobs():jobs = sorted(_jobs.values(), key=lambda j: j.get("created_at", ""), reverse=True)# Strip sensitive / large fieldsreturn [{k: v for k, v in j.items() if k != "error" or v} for j in jobs]@app.get("/jobs/{job_id}")async def get_job(job_id: str):j = _jobs.get(job_id)if not j:raise HTTPException(404, "Job not found")return j# ---------- Serve outputs ----------@app.get("/output/{filename}")async def serve_output(filename: str):fp = OUTPUT_DIR / filenameif not fp.exists():raise HTTPException(404, "File not found")return FileResponse(str(fp), media_type="video/mp4")# ---------- Health ----------@app.get("/health")def health():gpu = torch.cuda.is_available()return {"status": "ok" if gpu and pipe is not None else "loading","gpu": gpu,"gpu_name": torch.cuda.get_device_name(0) if gpu else None,"vram_gb": round(torch.cuda.get_device_properties(0).total_mem / 1e9, 1) if gpu else None,"model_loaded": pipe is not None,"model_id": MODEL_ID,"jobs_count": len(_jobs),}
app.py+395-159