sayeed105236 commited on
Commit
b7691c7
·
1 Parent(s): d47df1b

Upgrade UI: gallery, progress tracking, tabs, image preview, polished design

Browse files
Files changed (1) hide show
  1. app.py +395 -159
app.py CHANGED
@@ -1,39 +1,58 @@
1
  """
2
  Wan2.2 TI2V 5B — Text-to-Video & Image-to-Video
3
- FastAPI app for Hugging Face Docker Space.
4
  """
5
 
6
  import os
7
  import io
8
  import gc
9
- import tempfile
10
- import shutil
 
 
11
  from pathlib import Path
12
  from contextlib import asynccontextmanager
 
 
13
 
14
  import torch
15
  import numpy as np
16
- from fastapi import FastAPI, Form, UploadFile, File, HTTPException
17
- from fastapi.responses import FileResponse, HTMLResponse
 
18
  from diffusers import WanPipeline, AutoencoderKLWan
19
  from diffusers.utils import export_to_video
20
 
21
- # ---------- Model config ----------
22
  MODEL_ID = os.getenv("MODEL_ID", "Wan-AI/Wan2.2-TI2V-5B-Diffusers")
23
  HF_CACHE = Path(os.getenv("HF_HOME", os.path.expanduser("~/.cache/huggingface")))
24
  OUTPUT_DIR = Path("/tmp/outputs")
25
  OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
 
26
 
27
- # Device — will be set at startup
28
  DEVICE = None
29
  DTYPE = torch.bfloat16
30
-
31
- # Global pipeline placeholder
32
  pipe = None
33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
  def free_memory():
36
- """Aggressively free GPU / CPU memory."""
37
  gc.collect()
38
  if torch.cuda.is_available():
39
  torch.cuda.empty_cache()
@@ -43,206 +62,423 @@ def free_memory():
43
  @asynccontextmanager
44
  async def lifespan(app: FastAPI):
45
  global DEVICE, pipe
 
46
  DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
47
- print(f"[startup] device={DEVICE}")
48
-
49
  if not torch.cuda.is_available():
50
- raise RuntimeError("CUDA GPU is required. Please add a GPU to this Space.")
51
-
52
- print(f"[startup] VRAM: {torch.cuda.get_device_properties(0).total_mem / 1e9:.1f} GB")
53
- print(f"[startup] Loading Wan2.2-TI2V-5B from {MODEL_ID} …")
54
-
55
- # VAE must be float32 for decoding quality
56
- vae = AutoencoderKLWan.from_pretrained(
57
- MODEL_ID,
58
- subfolder="vae",
59
- torch_dtype=torch.float32,
60
- cache_dir=str(HF_CACHE),
61
- )
62
-
63
- pipe = WanPipeline.from_pretrained(
64
- MODEL_ID,
65
- vae=vae,
66
- torch_dtype=DTYPE,
67
- cache_dir=str(HF_CACHE),
68
- )
69
- pipe.to(DEVICE)
70
 
71
- print("[startup] Model loaded. Ready.")
72
- yield
 
73
 
74
- # Shutdown
 
 
 
 
75
  free_memory()
76
- print("[shutdown] Cleaned up.")
77
 
78
 
79
  app = FastAPI(lifespan=lifespan, title="Wan2.2 TI2V 5B")
80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
- # ---------- HTML homepage ----------
 
83
  @app.get("/", response_class=HTMLResponse)
84
  def index():
85
- return HTMLResponse("""
86
- <!DOCTYPE html>
87
  <html lang="en">
88
  <head>
89
- <meta charset="utf-8" />
90
- <meta name="viewport" content="width=device-width, initial-scale=1" />
91
  <title>Wan2.2 TI2V 5B — Video Generator</title>
92
  <style>
93
- * { box-sizing: border-box; margin: 0; padding: 0; }
94
- body {
95
- font-family: -apple-system, 'Segoe UI', Roboto, sans-serif;
96
- background: #0b0b12;
97
- color: #e0e0e0;
98
- min-height: 100vh;
99
- display: flex; align-items: center; justify-content: center;
100
- }
101
- .card {
102
- background: #1a1a2e;
103
- border-radius: 16px;
104
- padding: 2.5rem;
105
- max-width: 640px;
106
- width: 100%;
107
- box-shadow: 0 4px 40px rgba(100, 60, 255, 0.12);
108
- }
109
- h1 { font-size: 1.6rem; margin-bottom: 0.25rem; }
110
- .sub { color: #888; font-size: 0.9rem; margin-bottom: 1.5rem; }
111
- label { display: block; margin-top: 1rem; margin-bottom: 0.35rem; font-weight: 600; }
112
- textarea, input {
113
- width: 100%; padding: 0.7rem 0.9rem;
114
- border-radius: 10px; border: 1px solid #333;
115
- background: #12121f; color: #e0e0e0;
116
- font-size: 0.95rem;
117
- }
118
- textarea { resize: vertical; min-height: 80px; }
119
- button {
120
- margin-top: 1.5rem; width: 100%; padding: 0.8rem;
121
- border: none; border-radius: 10px;
122
- background: linear-gradient(135deg, #6c3ef0, #4a2fb0);
123
- color: #fff; font-weight: 700; font-size: 1rem;
124
- cursor: pointer; transition: opacity .2s;
125
- }
126
- button:hover { opacity: 0.92; }
127
- button:disabled { opacity: 0.5; cursor: not-allowed; }
128
- .note { margin-top: 1.2rem; font-size: 0.78rem; color: #666; }
129
- .result { margin-top: 1.5rem; }
130
- .result video { width: 100%; border-radius: 10px; }
131
- a { color: #9f7aea; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  </style>
133
  </head>
134
  <body>
135
- <div class="card">
136
- <h1>🐳 Wan2.2 TI2V 5B</h1>
137
- <p class="sub">Text-to-Video &amp; Image-to-Video &mdash; 720p @ 24 fps</p>
138
- <form action="/generate" method="post" enctype="multipart/form-data">
139
- <label for="prompt">Prompt</label>
140
- <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>
141
-
142
- <label for="image">Image (optional — enables image-to-video)</label>
143
- <input type="file" name="image" id="image" accept="image/*" />
144
-
145
- <label for="steps">Steps (20–50, lower = faster)</label>
146
- <input type="number" name="steps" id="steps" value="30" min="20" max="50" />
147
-
148
- <button type="submit">Generate Video</button>
149
- </form>
150
- <p class="note">
151
- ⚡ First run downloads model (~54 GB). Subsequent runs are faster.
152
- <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>
153
- </p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
  </body>
156
- </html>
157
- """)
158
 
159
 
160
  # ---------- Generate endpoint ----------
161
  @app.post("/generate")
162
  async def generate(
163
- prompt: str = Form(..., description="Text prompt for generation"),
164
  image: UploadFile = File(None),
165
  steps: int = Form(30, ge=20, le=50),
 
166
  guidance_scale: float = Form(5.0),
 
167
  ):
168
  global pipe
169
  if pipe is None:
170
- raise HTTPException(503, "Model still loading — please wait and retry.")
171
 
172
- # Load reference image if provided
173
  input_image = None
174
  if image and image.filename:
175
  try:
176
- contents = await image.read()
177
  from PIL import Image as PILImage
 
178
  input_image = PILImage.open(io.BytesIO(contents)).convert("RGB")
179
  except Exception as e:
180
  raise HTTPException(400, f"Failed to read image: {e}")
181
 
182
- height, width = 704, 1280
183
- num_frames = 81 # ~3.4 sec at 24 fps
184
- output_name = "output.mp4"
185
- output_path = OUTPUT_DIR / output_name
 
 
 
 
 
 
 
 
 
186
 
187
- print(f"[generate] prompt={prompt[:100]!r} | image={input_image is not None} | steps={steps}")
 
188
 
189
- try:
190
- if input_image is not None:
191
- # Image-to-Video: aspect ratio follows input image
192
- aspect = input_image.height / input_image.width
193
- max_area = height * width
194
- mod = pipe.vae_scale_factor_spatial * pipe.transformer.config.patch_size[1]
195
- h = round(np.sqrt(max_area * aspect)) // mod * mod
196
- w = round(np.sqrt(max_area / aspect)) // mod * mod
197
- input_image = input_image.resize((w, h))
198
 
199
- frames = pipe(
200
- prompt=prompt,
201
- image=input_image,
202
- height=h,
203
- width=w,
204
- num_frames=num_frames,
205
- num_inference_steps=steps,
206
- guidance_scale=guidance_scale,
207
- ).frames[0]
208
- else:
209
- # Text-to-Video
210
- frames = pipe(
211
- prompt=prompt,
212
- height=height,
213
- width=width,
214
- num_frames=num_frames,
215
- num_inference_steps=steps,
216
- guidance_scale=guidance_scale,
217
- ).frames[0]
218
-
219
- export_to_video(frames, str(output_path), fps=24)
220
- except torch.cuda.OutOfMemoryError:
221
- free_memory()
222
- raise HTTPException(
223
- 507,
224
- "GPU out of memory. Try fewer frames (num_frames=41) or switch to a larger GPU tier (L4 / A10G)."
225
- )
226
- except Exception as e:
227
- free_memory()
228
- raise HTTPException(500, f"Generation failed: {e}")
229
 
230
- free_memory()
231
- return FileResponse(
232
- output_path,
233
- media_type="video/mp4",
234
- filename=output_name,
235
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
 
237
 
238
- # ---------- Health check ----------
239
  @app.get("/health")
240
  def health():
241
- gpu_ok = torch.cuda.is_available()
242
  return {
243
- "status": "ok" if gpu_ok and pipe is not None else "loading",
244
- "gpu": gpu_ok,
 
 
245
  "model_loaded": pipe is not None,
 
 
246
  }
247
 
248
 
 
1
  """
2
  Wan2.2 TI2V 5B — Text-to-Video & Image-to-Video
3
+ Production FastAPI app for Hugging Face Docker Space.
4
  """
5
 
6
  import os
7
  import io
8
  import gc
9
+ import json
10
+ import uuid
11
+ import time
12
+ import asyncio
13
  from pathlib import Path
14
  from contextlib import asynccontextmanager
15
+ from datetime import datetime
16
+ from typing import Optional
17
 
18
  import torch
19
  import numpy as np
20
+ from fastapi import FastAPI, Form, UploadFile, File, HTTPException, Query
21
+ from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
22
+ from fastapi.staticfiles import StaticFiles
23
  from diffusers import WanPipeline, AutoencoderKLWan
24
  from diffusers.utils import export_to_video
25
 
26
+ # ---------- Config ----------
27
  MODEL_ID = os.getenv("MODEL_ID", "Wan-AI/Wan2.2-TI2V-5B-Diffusers")
28
  HF_CACHE = Path(os.getenv("HF_HOME", os.path.expanduser("~/.cache/huggingface")))
29
  OUTPUT_DIR = Path("/tmp/outputs")
30
  OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
31
+ JOBS_FILE = OUTPUT_DIR / "jobs.json"
32
 
 
33
  DEVICE = None
34
  DTYPE = torch.bfloat16
 
 
35
  pipe = None
36
 
37
+ # Job store (in-memory + persisted)
38
+ _jobs: dict = {}
39
+ _job_lock = asyncio.Lock()
40
+
41
+
42
+ def _load_jobs():
43
+ global _jobs
44
+ if JOBS_FILE.exists():
45
+ try:
46
+ _jobs = json.loads(JOBS_FILE.read_text())
47
+ except Exception:
48
+ _jobs = {}
49
+
50
+
51
+ def _save_jobs():
52
+ JOBS_FILE.write_text(json.dumps(_jobs, default=str))
53
+
54
 
55
  def free_memory():
 
56
  gc.collect()
57
  if torch.cuda.is_available():
58
  torch.cuda.empty_cache()
 
62
  @asynccontextmanager
63
  async def lifespan(app: FastAPI):
64
  global DEVICE, pipe
65
+ _load_jobs()
66
  DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
 
 
67
  if not torch.cuda.is_available():
68
+ raise RuntimeError("CUDA GPU required — add a GPU to this Space (Settings → Hardware).")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
+ vram_gb = torch.cuda.get_device_properties(0).total_mem / 1e9
71
+ print(f"[startup] GPU: {torch.cuda.get_device_name(0)} ({vram_gb:.1f} GB VRAM)")
72
+ print(f"[startup] Loading {MODEL_ID} …")
73
 
74
+ vae = AutoencoderKLWan.from_pretrained(MODEL_ID, subfolder="vae", torch_dtype=torch.float32, cache_dir=str(HF_CACHE))
75
+ pipe = WanPipeline.from_pretrained(MODEL_ID, vae=vae, torch_dtype=DTYPE, cache_dir=str(HF_CACHE))
76
+ pipe.to(DEVICE)
77
+ print("[startup] Ready.")
78
+ yield
79
  free_memory()
 
80
 
81
 
82
  app = FastAPI(lifespan=lifespan, title="Wan2.2 TI2V 5B")
83
 
84
+ # ----- Serving -----
85
+
86
+ async def _run_generation(job_id: str, prompt: str, input_image, steps: int, guidance_scale: float,
87
+ num_frames: int, seed: Optional[int]):
88
+ _jobs[job_id]["status"] = "running"
89
+ _jobs[job_id]["started_at"] = time.time()
90
+ _save_jobs()
91
+
92
+ out_name = f"{job_id}.mp4"
93
+ out_path = OUTPUT_DIR / out_name
94
+
95
+ try:
96
+ height, width = 704, 1280
97
+
98
+ if input_image is not None:
99
+ aspect = input_image.height / input_image.width
100
+ max_area = height * width
101
+ mod = pipe.vae_scale_factor_spatial * pipe.transformer.config.patch_size[1]
102
+ h = round(np.sqrt(max_area * aspect)) // mod * mod
103
+ w = round(np.sqrt(max_area / aspect)) // mod * mod
104
+ input_image = input_image.resize((w, h))
105
+ height, width = h, w
106
+
107
+ gen_kwargs = dict(
108
+ prompt=prompt,
109
+ height=height,
110
+ width=width,
111
+ num_frames=num_frames,
112
+ num_inference_steps=steps,
113
+ guidance_scale=guidance_scale,
114
+ )
115
+ if input_image is not None:
116
+ gen_kwargs["image"] = input_image
117
+ if seed is not None:
118
+ gen_kwargs["generator"] = torch.Generator(device=DEVICE).manual_seed(seed)
119
+
120
+ frames = pipe(**gen_kwargs).frames[0]
121
+ export_to_video(frames, str(out_path), fps=24)
122
+
123
+ duration = round(time.time() - _jobs[job_id]["started_at"], 1)
124
+ _jobs[job_id]["status"] = "done"
125
+ _jobs[job_id]["duration"] = duration
126
+ _jobs[job_id]["output"] = f"/output/{out_name}"
127
+ _jobs[job_id]["width"] = width
128
+ _jobs[job_id]["height"] = height
129
+
130
+ except torch.cuda.OutOfMemoryError:
131
+ _jobs[job_id]["status"] = "error"
132
+ _jobs[job_id]["error"] = "GPU out of memory. Try fewer frames or upgrade GPU tier."
133
+ except Exception as e:
134
+ _jobs[job_id]["status"] = "error"
135
+ _jobs[job_id]["error"] = str(e)
136
+ finally:
137
+ free_memory()
138
+ _save_jobs()
139
 
140
+
141
+ # ---------- UI ----------
142
  @app.get("/", response_class=HTMLResponse)
143
  def index():
144
+ return HTMLResponse("""<!DOCTYPE html>
 
145
  <html lang="en">
146
  <head>
147
+ <meta charset="utf-8"/>
148
+ <meta name="viewport" content="width=device-width,initial-scale=1"/>
149
  <title>Wan2.2 TI2V 5B — Video Generator</title>
150
  <style>
151
+ :root {
152
+ --bg: #0a0a14; --surface: #13132a; --surface2: #1c1c3a;
153
+ --border: #2a2a4a; --text: #e2e2f0; --text2: #8888aa;
154
+ --accent: #7c4dff; --accent2: #b388ff; --danger: #ff5252;
155
+ --radius: 14px; --shadow: 0 4px 40px rgba(124,77,255,0.08);
156
+ }
157
+ *{box-sizing:border-box;margin:0;padding:0}
158
+ body{font-family:-apple-system,'Segoe UI',Roboto,sans-serif;background:var(--bg);color:var(--text);min-height:100vh}
159
+ .app{max-width:1100px;margin:0 auto;padding:1.5rem}
160
+ header{text-align:center;padding:1.5rem 0}
161
+ header h1{font-size:2rem;background:linear-gradient(135deg,var(--accent),var(--accent2));-webkit-background-clip:text;-webkit-text-fill-color:transparent}
162
+ header .tagline{color:var(--text2);margin-top:.4rem;font-size:.95rem}
163
+ .layout{display:grid;grid-template-columns:1fr 1fr;gap:1.5rem;align-items:start}
164
+ @media(max-width:800px){.layout{grid-template-columns:1fr}}
165
+ .card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:1.5rem;box-shadow:var(--shadow)}
166
+ .card h2{font-size:1.15rem;margin-bottom:1rem;display:flex;align-items:center;gap:.5rem}
167
+ .field{margin-bottom:1rem}
168
+ .field label{display:block;font-weight:600;margin-bottom:.35rem;font-size:.88rem;color:var(--text2)}
169
+ .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}
170
+ .field textarea{resize:vertical;min-height:90px}
171
+ .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)}
172
+ .row{display:grid;grid-template-columns:1fr 1fr;gap:1rem}
173
+ .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}
174
+ .btn-primary{background:linear-gradient(135deg,var(--accent),#5e3fcc);color:#fff;width:100%}
175
+ .btn-primary:hover{opacity:.92;transform:translateY(-1px)}
176
+ .btn-primary:disabled{opacity:.45;cursor:not-allowed;transform:none}
177
+ .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}
178
+ .file-upload:hover{border-color:var(--accent)}
179
+ .file-upload .icon{font-size:2rem;margin-bottom:.5rem}
180
+ .file-upload .hint{color:var(--text2);font-size:.85rem}
181
+ .file-upload input[type=file]{position:absolute;inset:0;opacity:0;cursor:pointer}
182
+ .file-upload.has-image{padding:.5rem}
183
+ .file-upload img{max-height:140px;border-radius:8px}
184
+ .preview-name{font-size:.85rem;color:var(--accent2);margin-top:.3rem}
185
+ /* Gallery */
186
+ .gallery{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:.75rem;max-height:70vh;overflow-y:auto;padding-right:.3rem}
187
+ .job-card{background:var(--surface2);border:1px solid var(--border);border-radius:10px;overflow:hidden}
188
+ .job-card video{width:100%;display:block;border-radius:10px 10px 0 0;background:#000}
189
+ .job-card .meta{padding:.6rem .8rem;font-size:.8rem}
190
+ .job-card .prompt{color:var(--text);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-bottom:.2rem}
191
+ .job-card .info{color:var(--text2);display:flex;justify-content:space-between}
192
+ .job-card .status{font-weight:600}
193
+ .job-card .status.running{color:#ffab40}
194
+ .job-card .status.done{color:#69f0ae}
195
+ .job-card .status.error{color:var(--danger)}
196
+ .job-card .status.queued{color:var(--text2)}
197
+ .empty-state{text-align:center;padding:2.5rem 1rem;color:var(--text2)}
198
+ .empty-state .icon{font-size:3rem;margin-bottom:.8rem}
199
+ .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}
200
+ @keyframes spin{to{transform:rotate(360deg)}}
201
+ .progress-bar{height:4px;background:var(--border);border-radius:2px;margin-top:.5rem;overflow:hidden}
202
+ .progress-bar .fill{height:100%;background:linear-gradient(90deg,var(--accent),var(--accent2));border-radius:2px;transition:width .3s}
203
+ #status-msg{font-size:.85rem;color:var(--accent2);margin-top:.75rem;min-height:1.2em}
204
+ .tabs{display:flex;gap:.25rem;margin-bottom:1rem;background:var(--surface2);border-radius:10px;padding:3px}
205
+ .tab{padding:.5rem 1rem;border-radius:8px;cursor:pointer;font-size:.88rem;font-weight:600;color:var(--text2);transition:.15s}
206
+ .tab.active{background:var(--accent);color:#fff}
207
+ .tab:hover:not(.active){color:var(--text)}
208
+ footer{text-align:center;padding:2rem 1rem;color:var(--text2);font-size:.8rem}
209
+ footer a{color:var(--accent2)}
210
  </style>
211
  </head>
212
  <body>
213
+ <div class="app">
214
+ <header>
215
+ <h1>🎬 Wan2.2 TI2V 5B</h1>
216
+ <p class="tagline">Text-to-Video &amp; Image-to-Video · 720p @ 24fps · Single-GPU</p>
217
+ </header>
218
+
219
+ <div class="layout">
220
+ <!-- Left: Generation Form -->
221
+ <div class="card">
222
+ <h2>✨ Create Video</h2>
223
+ <form id="gen-form">
224
+ <div class="field">
225
+ <label for="prompt">Prompt</label>
226
+ <textarea id="prompt" name="prompt" placeholder="Describe what you want to see…" required></textarea>
227
+ </div>
228
+ <div class="field">
229
+ <label>Reference Image <span style="color:var(--text2);font-weight:400">(optional — enables image-to-video)</span></label>
230
+ <div class="file-upload" id="file-area">
231
+ <div id="file-placeholder">
232
+ <div class="icon">🖼️</div>
233
+ <p class="hint">Click or drag to upload an image</p>
234
+ </div>
235
+ <img id="preview-img" style="display:none" alt=""/>
236
+ <div class="preview-name" id="preview-name" style="display:none"></div>
237
+ <input type="file" id="image" name="image" accept="image/*"/>
238
+ </div>
239
+ </div>
240
+ <div class="row">
241
+ <div class="field">
242
+ <label for="steps">Steps <span style="color:var(--text2);font-weight:400">(20–50)</span></label>
243
+ <input type="number" id="steps" value="30" min="20" max="50"/>
244
+ </div>
245
+ <div class="field">
246
+ <label for="frames">Frames <span style="color:var(--text2);font-weight:400">(9–121)</span></label>
247
+ <input type="number" id="frames" value="81" min="9" max="121"/>
248
+ </div>
249
+ </div>
250
+ <div class="row">
251
+ <div class="field">
252
+ <label for="guidance">Guidance Scale</label>
253
+ <input type="number" id="guidance" value="5" min="1" max="10" step="0.5"/>
254
+ </div>
255
+ <div class="field">
256
+ <label for="seed">Seed <span style="color:var(--text2);font-weight:400">(empty = random)</span></label>
257
+ <input type="number" id="seed" placeholder="Random"/>
258
+ </div>
259
+ </div>
260
+ <button type="submit" class="btn btn-primary" id="submit-btn">🎬 Generate Video</button>
261
+ <div id="status-msg"></div>
262
+ <div class="progress-bar" id="progress-bar" style="display:none"><div class="fill" style="width:0%"></div></div>
263
+ </form>
264
+ </div>
265
+
266
+ <!-- Right: Gallery -->
267
+ <div class="card">
268
+ <div class="tabs">
269
+ <div class="tab active" data-tab="gallery">📽️ Gallery</div>
270
+ <div class="tab" data-tab="api">📡 API</div>
271
+ </div>
272
+ <div id="tab-gallery">
273
+ <div class="gallery" id="gallery"></div>
274
+ <div class="empty-state" id="empty-state"><div class="icon">🎞️</div><p>Your generated videos will appear here</p></div>
275
+ </div>
276
+ <div id="tab-api" style="display:none">
277
+ <h2 style="font-size:1rem;margin-bottom:.5rem">API Usage</h2>
278
+ <p style="color:var(--text2);font-size:.85rem;margin-bottom:1rem">The <code>/generate</code> endpoint accepts form-data POST:</p>
279
+ <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>
280
+ curl -X POST <span id="api-url">…</span>/generate \\
281
+ -F "prompt=A cat astronaut in space" \\
282
+ -F "steps=30" -F "num_frames=81" \\
283
+ -o video.mp4
284
+
285
+ <b># Image-to-Video</b>
286
+ curl -X POST <span id="api-url2">…</span>/generate \\
287
+ -F "prompt=Animate this scene" \\
288
+ -F "image=@cat.jpg" \\
289
+ -F "steps=30" -o video.mp4
290
+
291
+ <b># Check status</b>
292
+ curl <span id="api-url3">…</span>/health | jq</pre>
293
+ </div>
294
+ </div>
295
+ </div>
296
+
297
+ <footer>
298
+ Powered by <a href="https://huggingface.co/Wan-AI/Wan2.2-TI2V-5B-Diffusers" target="_blank">Wan-AI/Wan2.2-TI2V-5B</a>
299
+ &middot; Apache 2.0 &middot; Diffusers
300
+ </footer>
301
  </div>
302
+
303
+ <script>
304
+ const API = window.location.origin;
305
+ document.querySelectorAll('#api-url,#api-url2,#api-url3').forEach(e=>e.textContent=API);
306
+
307
+ const form = document.getElementById('gen-form');
308
+ const submitBtn = document.getElementById('submit-btn');
309
+ const statusMsg = document.getElementById('status-msg');
310
+ const progressBar = document.getElementById('progress-bar');
311
+ const progressFill = progressBar.querySelector('.fill');
312
+ const gallery = document.getElementById('gallery');
313
+ const emptyState = document.getElementById('empty-state');
314
+
315
+ // File preview
316
+ const imageInput = document.getElementById('image');
317
+ const previewImg = document.getElementById('preview-img');
318
+ const previewName = document.getElementById('preview-name');
319
+ const filePlaceholder = document.getElementById('file-placeholder');
320
+ const fileArea = document.getElementById('file-area');
321
+
322
+ imageInput.addEventListener('change',()=>{
323
+ const f=imageInput.files[0];
324
+ if(!f){previewImg.style.display='none';previewName.style.display='none';filePlaceholder.style.display='';fileArea.classList.remove('has-image');return}
325
+ fileArea.classList.add('has-image');filePlaceholder.style.display='none';
326
+ previewImg.style.display='';previewName.style.display='';previewName.textContent=f.name;
327
+ const r=new FileReader();r.onload=e=>{previewImg.src=e.target.result};r.readAsDataURL(f);
328
+ });
329
+
330
+ // Tabs
331
+ document.querySelectorAll('.tab').forEach(t=>t.addEventListener('click',()=>{
332
+ document.querySelectorAll('.tab').forEach(x=>x.classList.remove('active'));
333
+ t.classList.add('active');
334
+ document.getElementById('tab-gallery').style.display=t.dataset.tab==='gallery'?'':'none';
335
+ document.getElementById('tab-api').style.display=t.dataset.tab==='api'?'':'none';
336
+ }));
337
+
338
+ // Submit
339
+ form.addEventListener('submit',async e=>{
340
+ e.preventDefault();
341
+ submitBtn.disabled=true;
342
+ statusMsg.textContent='⏳ Queuing…';
343
+ progressBar.style.display='';progressFill.style.width='10%';
344
+
345
+ const fd=new FormData(form);
346
+ try{
347
+ const res=await fetch(API+'/generate',{method:'POST',body:fd});
348
+ if(!res.ok){const t=await res.text();throw new Error(t||res.statusText)}
349
+ progressFill.style.width='95%';
350
+ statusMsg.textContent='✅ Done! Refreshing gallery…';
351
+ setTimeout(loadGallery,1500);
352
+ }catch(err){
353
+ statusMsg.textContent='❌ '+err.message;
354
+ progressBar.style.display='none';
355
+ }finally{
356
+ submitBtn.disabled=false;
357
+ setTimeout(()=>{progressBar.style.display='none';statusMsg.textContent=''},4000);
358
+ }
359
+ });
360
+
361
+ // Load gallery
362
+ async function loadGallery(){
363
+ try{
364
+ const res=await fetch(API+'/jobs');
365
+ const jobs=await res.json();
366
+ if(!jobs||!jobs.length){gallery.innerHTML='';emptyState.style.display='';return}
367
+ emptyState.style.display='none';
368
+ gallery.innerHTML=jobs.reverse().map(j=>{
369
+ const dur=j.duration?j.duration+'s':'';
370
+ const statusCls=j.status;
371
+ if(j.status==='done'&&j.output){
372
+ 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>`;
373
+ }else if(j.status==='running'){
374
+ 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>`;
375
+ }else if(j.status==='queued'){
376
+ 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>`;
377
+ }else{
378
+ 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>`;
379
+ }
380
+ }).join('');
381
+ }catch(e){console.error(e)}
382
+ }
383
+ function esc(s){const d=document.createElement('div');d.textContent=s||'';return d.innerHTML}
384
+
385
+ // Poll running jobs
386
+ setInterval(loadGallery,5000);
387
+ loadGallery();
388
+ </script>
389
  </body>
390
+ </html>""")
 
391
 
392
 
393
  # ---------- Generate endpoint ----------
394
  @app.post("/generate")
395
  async def generate(
396
+ prompt: str = Form(...),
397
  image: UploadFile = File(None),
398
  steps: int = Form(30, ge=20, le=50),
399
+ num_frames: int = Form(81, ge=9, le=121),
400
  guidance_scale: float = Form(5.0),
401
+ seed: Optional[int] = Form(None),
402
  ):
403
  global pipe
404
  if pipe is None:
405
+ raise HTTPException(503, "Model still loading — try again in a moment.")
406
 
 
407
  input_image = None
408
  if image and image.filename:
409
  try:
 
410
  from PIL import Image as PILImage
411
+ contents = await image.read()
412
  input_image = PILImage.open(io.BytesIO(contents)).convert("RGB")
413
  except Exception as e:
414
  raise HTTPException(400, f"Failed to read image: {e}")
415
 
416
+ job_id = uuid.uuid4().hex[:12]
417
+ _jobs[job_id] = {
418
+ "id": job_id,
419
+ "prompt": prompt[:300],
420
+ "status": "queued",
421
+ "steps": steps,
422
+ "num_frames": num_frames,
423
+ "guidance_scale": guidance_scale,
424
+ "seed": seed,
425
+ "has_image": input_image is not None,
426
+ "created_at": datetime.utcnow().isoformat(),
427
+ }
428
+ _save_jobs()
429
 
430
+ # Run generation in background
431
+ asyncio.create_task(_run_generation(job_id, prompt, input_image, steps, guidance_scale, num_frames, seed))
432
 
433
+ # Poll until done (max 10 minutes)
434
+ for _ in range(600):
435
+ await asyncio.sleep(1)
436
+ status = _jobs.get(job_id, {}).get("status")
437
+ if status == "done":
438
+ return FileResponse(str(OUTPUT_DIR / f"{job_id}.mp4"), media_type="video/mp4", filename=f"wan2.2_{job_id}.mp4")
439
+ if status == "error":
440
+ raise HTTPException(500, _jobs[job_id].get("error", "Unknown error"))
 
441
 
442
+ raise HTTPException(504, "Generation timed out after 10 minutes.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
443
 
444
+
445
+ # ---------- Gallery / Jobs API ----------
446
+ @app.get("/jobs")
447
+ async def list_jobs():
448
+ jobs = sorted(_jobs.values(), key=lambda j: j.get("created_at", ""), reverse=True)
449
+ # Strip sensitive / large fields
450
+ return [{k: v for k, v in j.items() if k != "error" or v} for j in jobs]
451
+
452
+
453
+ @app.get("/jobs/{job_id}")
454
+ async def get_job(job_id: str):
455
+ j = _jobs.get(job_id)
456
+ if not j:
457
+ raise HTTPException(404, "Job not found")
458
+ return j
459
+
460
+
461
+ # ---------- Serve outputs ----------
462
+ @app.get("/output/{filename}")
463
+ async def serve_output(filename: str):
464
+ fp = OUTPUT_DIR / filename
465
+ if not fp.exists():
466
+ raise HTTPException(404, "File not found")
467
+ return FileResponse(str(fp), media_type="video/mp4")
468
 
469
 
470
+ # ---------- Health ----------
471
  @app.get("/health")
472
  def health():
473
+ gpu = torch.cuda.is_available()
474
  return {
475
+ "status": "ok" if gpu and pipe is not None else "loading",
476
+ "gpu": gpu,
477
+ "gpu_name": torch.cuda.get_device_name(0) if gpu else None,
478
+ "vram_gb": round(torch.cuda.get_device_properties(0).total_mem / 1e9, 1) if gpu else None,
479
  "model_loaded": pipe is not None,
480
+ "model_id": MODEL_ID,
481
+ "jobs_count": len(_jobs),
482
  }
483
 
484