jbilcke-hf HF Staff commited on
Commit
096063a
Β·
verified Β·
1 Parent(s): 3e39c84

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +20 -2
  2. app_last_working.py +460 -0
app.py CHANGED
@@ -199,7 +199,7 @@ pipeline = CausalInferencePipeline(
199
  pipeline.to(dtype=torch.float16).to(gpu)
200
 
201
  @torch.no_grad()
202
- def video_generation_handler_streaming(prompt, seed=42, fps=15):
203
  """
204
  Generator function that yields .ts video chunks using PyAV for streaming.
205
  Now optimized for block-based processing.
@@ -408,6 +408,24 @@ with gr.Blocks(title="Self-Forcing Streaming Demo") as demo:
408
  info="Frames per second for playback"
409
  )
410
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
411
  with gr.Column(scale=3):
412
  gr.Markdown("### πŸ“Ί Video Stream")
413
 
@@ -433,7 +451,7 @@ with gr.Blocks(title="Self-Forcing Streaming Demo") as demo:
433
  # Connect the generator to the streaming video
434
  start_btn.click(
435
  fn=video_generation_handler_streaming,
436
- inputs=[prompt, seed, fps],
437
  outputs=[streaming_video, status_display]
438
  )
439
 
 
199
  pipeline.to(dtype=torch.float16).to(gpu)
200
 
201
  @torch.no_grad()
202
+ def video_generation_handler_streaming(prompt, seed=42, fps=15, width=400, height=224):
203
  """
204
  Generator function that yields .ts video chunks using PyAV for streaming.
205
  Now optimized for block-based processing.
 
408
  info="Frames per second for playback"
409
  )
410
 
411
+ with gr.Row():
412
+ width = gr.Slider(
413
+ label="Width",
414
+ minimum=320,
415
+ maximum=720,
416
+ value=400,
417
+ step=8,
418
+ info="Video width in pixels (8px steps)"
419
+ )
420
+ height = gr.Slider(
421
+ label="Height",
422
+ minimum=320,
423
+ maximum=720,
424
+ value=224,
425
+ step=8,
426
+ info="Video height in pixels (8px steps)"
427
+ )
428
+
429
  with gr.Column(scale=3):
430
  gr.Markdown("### πŸ“Ί Video Stream")
431
 
 
451
  # Connect the generator to the streaming video
452
  start_btn.click(
453
  fn=video_generation_handler_streaming,
454
+ inputs=[prompt, seed, fps, width, height],
455
  outputs=[streaming_video, status_display]
456
  )
457
 
app_last_working.py ADDED
@@ -0,0 +1,460 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ # not sure why it works in the original space but says "pip not found" in mine
3
+ #subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
4
+
5
+ from huggingface_hub import snapshot_download, hf_hub_download
6
+
7
+ snapshot_download(
8
+ repo_id="Wan-AI/Wan2.1-T2V-1.3B",
9
+ local_dir="wan_models/Wan2.1-T2V-1.3B",
10
+ local_dir_use_symlinks=False,
11
+ resume_download=True,
12
+ repo_type="model"
13
+ )
14
+
15
+ hf_hub_download(
16
+ repo_id="gdhe17/Self-Forcing",
17
+ filename="checkpoints/self_forcing_dmd.pt",
18
+ local_dir=".",
19
+ local_dir_use_symlinks=False
20
+ )
21
+
22
+ import os
23
+ import re
24
+ import random
25
+ import argparse
26
+ import hashlib
27
+ import urllib.request
28
+ import time
29
+ from PIL import Image
30
+ import torch
31
+ import gradio as gr
32
+ from omegaconf import OmegaConf
33
+ from tqdm import tqdm
34
+ import imageio
35
+ import av
36
+ import uuid
37
+
38
+ from pipeline import CausalInferencePipeline
39
+ from demo_utils.constant import ZERO_VAE_CACHE
40
+ from demo_utils.vae_block3 import VAEDecoderWrapper
41
+ from utils.wan_wrapper import WanDiffusionWrapper, WanTextEncoder
42
+
43
+ from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM #, BitsAndBytesConfig
44
+ import numpy as np
45
+
46
+ device = "cuda" if torch.cuda.is_available() else "cpu"
47
+
48
+ # --- Argument Parsing ---
49
+ parser = argparse.ArgumentParser(description="Gradio Demo for Self-Forcing with Frame Streaming")
50
+ parser.add_argument('--port', type=int, default=7860, help="Port to run the Gradio app on.")
51
+ parser.add_argument('--host', type=str, default='0.0.0.0', help="Host to bind the Gradio app to.")
52
+ parser.add_argument("--checkpoint_path", type=str, default='./checkpoints/self_forcing_dmd.pt', help="Path to the model checkpoint.")
53
+ parser.add_argument("--config_path", type=str, default='./configs/self_forcing_dmd.yaml', help="Path to the model config.")
54
+ parser.add_argument('--share', action='store_true', help="Create a public Gradio link.")
55
+ parser.add_argument('--trt', action='store_true', help="Use TensorRT optimized VAE decoder.")
56
+ parser.add_argument('--fps', type=float, default=15.0, help="Playback FPS for frame streaming.")
57
+ args = parser.parse_args()
58
+
59
+ gpu = "cuda"
60
+
61
+ try:
62
+ config = OmegaConf.load(args.config_path)
63
+ default_config = OmegaConf.load("configs/default_config.yaml")
64
+ config = OmegaConf.merge(default_config, config)
65
+ except FileNotFoundError as e:
66
+ print(f"Error loading config file: {e}\n. Please ensure config files are in the correct path.")
67
+ exit(1)
68
+
69
+ # Initialize Models
70
+ print("Initializing models...")
71
+ text_encoder = WanTextEncoder()
72
+ transformer = WanDiffusionWrapper(is_causal=True)
73
+
74
+ try:
75
+ state_dict = torch.load(args.checkpoint_path, map_location="cpu")
76
+ transformer.load_state_dict(state_dict.get('generator_ema', state_dict.get('generator')))
77
+ except FileNotFoundError as e:
78
+ print(f"Error loading checkpoint: {e}\nPlease ensure the checkpoint '{args.checkpoint_path}' exists.")
79
+ exit(1)
80
+
81
+ text_encoder.eval().to(dtype=torch.float16).requires_grad_(False)
82
+ transformer.eval().to(dtype=torch.float16).requires_grad_(False)
83
+
84
+ text_encoder.to(gpu)
85
+ transformer.to(gpu)
86
+
87
+ APP_STATE = {
88
+ "torch_compile_applied": False,
89
+ "fp8_applied": False,
90
+ "current_use_taehv": False,
91
+ "current_vae_decoder": None,
92
+ }
93
+
94
+ def frames_to_ts_file(frames, filepath, fps = 15):
95
+ """
96
+ Convert frames directly to .ts file using PyAV.
97
+
98
+ Args:
99
+ frames: List of numpy arrays (HWC, RGB, uint8)
100
+ filepath: Output file path
101
+ fps: Frames per second
102
+
103
+ Returns:
104
+ The filepath of the created file
105
+ """
106
+ if not frames:
107
+ return filepath
108
+
109
+ height, width = frames[0].shape[:2]
110
+
111
+ # Create container for MPEG-TS format
112
+ container = av.open(filepath, mode='w', format='mpegts')
113
+
114
+ # Add video stream with optimized settings for streaming
115
+ stream = container.add_stream('h264', rate=fps)
116
+ stream.width = width
117
+ stream.height = height
118
+ stream.pix_fmt = 'yuv420p'
119
+
120
+ # Optimize for low latency streaming
121
+ stream.options = {
122
+ 'preset': 'ultrafast',
123
+ 'tune': 'zerolatency',
124
+ 'crf': '23',
125
+ 'profile': 'baseline',
126
+ 'level': '3.0'
127
+ }
128
+
129
+ try:
130
+ for frame_np in frames:
131
+ frame = av.VideoFrame.from_ndarray(frame_np, format='rgb24')
132
+ frame = frame.reformat(format=stream.pix_fmt)
133
+ for packet in stream.encode(frame):
134
+ container.mux(packet)
135
+
136
+ for packet in stream.encode():
137
+ container.mux(packet)
138
+
139
+ finally:
140
+ container.close()
141
+
142
+ return filepath
143
+
144
+ def initialize_vae_decoder(use_taehv=False, use_trt=False):
145
+ if use_trt:
146
+ from demo_utils.vae import VAETRTWrapper
147
+ print("Initializing TensorRT VAE Decoder...")
148
+ vae_decoder = VAETRTWrapper()
149
+ APP_STATE["current_use_taehv"] = False
150
+ elif use_taehv:
151
+ print("Initializing TAEHV VAE Decoder...")
152
+ from demo_utils.taehv import TAEHV
153
+ taehv_checkpoint_path = "checkpoints/taew2_1.pth"
154
+ if not os.path.exists(taehv_checkpoint_path):
155
+ print(f"Downloading TAEHV checkpoint to {taehv_checkpoint_path}...")
156
+ os.makedirs("checkpoints", exist_ok=True)
157
+ download_url = "https://github.com/madebyollin/taehv/raw/main/taew2_1.pth"
158
+ try:
159
+ urllib.request.urlretrieve(download_url, taehv_checkpoint_path)
160
+ except Exception as e:
161
+ raise RuntimeError(f"Failed to download taew2_1.pth: {e}")
162
+
163
+ class DotDict(dict): __getattr__ = dict.get
164
+
165
+ class TAEHVDiffusersWrapper(torch.nn.Module):
166
+ def __init__(self):
167
+ super().__init__()
168
+ self.dtype = torch.float16
169
+ self.taehv = TAEHV(checkpoint_path=taehv_checkpoint_path).to(self.dtype)
170
+ self.config = DotDict(scaling_factor=1.0)
171
+ def decode(self, latents, return_dict=None):
172
+ return self.taehv.decode_video(latents, parallel=not LOW_MEMORY).mul_(2).sub_(1)
173
+
174
+ vae_decoder = TAEHVDiffusersWrapper()
175
+ APP_STATE["current_use_taehv"] = True
176
+ else:
177
+ print("Initializing Default VAE Decoder...")
178
+ vae_decoder = VAEDecoderWrapper()
179
+ try:
180
+ vae_state_dict = torch.load('wan_models/Wan2.1-T2V-1.3B/Wan2.1_VAE.pth', map_location="cpu")
181
+ decoder_state_dict = {k: v for k, v in vae_state_dict.items() if 'decoder.' in k or 'conv2' in k}
182
+ vae_decoder.load_state_dict(decoder_state_dict)
183
+ except FileNotFoundError:
184
+ print("Warning: Default VAE weights not found.")
185
+ APP_STATE["current_use_taehv"] = False
186
+
187
+ vae_decoder.eval().to(dtype=torch.float16).requires_grad_(False).to(gpu)
188
+ APP_STATE["current_vae_decoder"] = vae_decoder
189
+ print(f"βœ… VAE decoder initialized: {'TAEHV' if use_taehv else 'Default VAE'}")
190
+
191
+ # Initialize with default VAE
192
+ initialize_vae_decoder(use_taehv=False, use_trt=args.trt)
193
+
194
+ pipeline = CausalInferencePipeline(
195
+ config, device=gpu, generator=transformer, text_encoder=text_encoder,
196
+ vae=APP_STATE["current_vae_decoder"]
197
+ )
198
+
199
+ pipeline.to(dtype=torch.float16).to(gpu)
200
+
201
+ @torch.no_grad()
202
+ def video_generation_handler_streaming(prompt, seed=42, fps=15):
203
+ """
204
+ Generator function that yields .ts video chunks using PyAV for streaming.
205
+ Now optimized for block-based processing.
206
+ """
207
+ if seed == -1:
208
+ seed = random.randint(0, 2**32 - 1)
209
+
210
+ print(f"🎬 Starting PyAV streaming: '{prompt}', seed: {seed}")
211
+
212
+ # Setup
213
+ conditional_dict = text_encoder(text_prompts=[prompt])
214
+ for key, value in conditional_dict.items():
215
+ conditional_dict[key] = value.to(dtype=torch.float16)
216
+
217
+ rnd = torch.Generator(gpu).manual_seed(int(seed))
218
+ pipeline._initialize_kv_cache(1, torch.float16, device=gpu)
219
+ pipeline._initialize_crossattn_cache(1, torch.float16, device=gpu)
220
+ noise = torch.randn([1, 21, 16, 60, 104], device=gpu, dtype=torch.float16, generator=rnd)
221
+
222
+ vae_cache, latents_cache = None, None
223
+ if not APP_STATE["current_use_taehv"] and not args.trt:
224
+ vae_cache = [c.to(device=gpu, dtype=torch.float16) for c in ZERO_VAE_CACHE]
225
+
226
+ num_blocks = 7
227
+ current_start_frame = 0
228
+ all_num_frames = [pipeline.num_frame_per_block] * num_blocks
229
+
230
+ total_frames_yielded = 0
231
+
232
+ # Ensure temp directory exists
233
+ os.makedirs("gradio_tmp", exist_ok=True)
234
+
235
+ # Generation loop
236
+ for idx, current_num_frames in enumerate(all_num_frames):
237
+ print(f"πŸ“¦ Processing block {idx+1}/{num_blocks}")
238
+
239
+ noisy_input = noise[:, current_start_frame : current_start_frame + current_num_frames]
240
+
241
+ # Denoising steps
242
+ for step_idx, current_timestep in enumerate(pipeline.denoising_step_list):
243
+ timestep = torch.ones([1, current_num_frames], device=noise.device, dtype=torch.int64) * current_timestep
244
+ _, denoised_pred = pipeline.generator(
245
+ noisy_image_or_video=noisy_input, conditional_dict=conditional_dict,
246
+ timestep=timestep, kv_cache=pipeline.kv_cache1,
247
+ crossattn_cache=pipeline.crossattn_cache,
248
+ current_start=current_start_frame * pipeline.frame_seq_length
249
+ )
250
+ if step_idx < len(pipeline.denoising_step_list) - 1:
251
+ next_timestep = pipeline.denoising_step_list[step_idx + 1]
252
+ noisy_input = pipeline.scheduler.add_noise(
253
+ denoised_pred.flatten(0, 1), torch.randn_like(denoised_pred.flatten(0, 1)),
254
+ next_timestep * torch.ones([1 * current_num_frames], device=noise.device, dtype=torch.long)
255
+ ).unflatten(0, denoised_pred.shape[:2])
256
+
257
+ if idx < len(all_num_frames) - 1:
258
+ pipeline.generator(
259
+ noisy_image_or_video=denoised_pred, conditional_dict=conditional_dict,
260
+ timestep=torch.zeros_like(timestep), kv_cache=pipeline.kv_cache1,
261
+ crossattn_cache=pipeline.crossattn_cache,
262
+ current_start=current_start_frame * pipeline.frame_seq_length,
263
+ )
264
+
265
+ # Decode to pixels
266
+ if args.trt:
267
+ pixels, vae_cache = pipeline.vae.forward(denoised_pred.half(), *vae_cache)
268
+ elif APP_STATE["current_use_taehv"]:
269
+ if latents_cache is None:
270
+ latents_cache = denoised_pred
271
+ else:
272
+ denoised_pred = torch.cat([latents_cache, denoised_pred], dim=1)
273
+ latents_cache = denoised_pred[:, -3:]
274
+ pixels = pipeline.vae.decode(denoised_pred)
275
+ else:
276
+ pixels, vae_cache = pipeline.vae(denoised_pred.half(), *vae_cache)
277
+
278
+ # Handle frame skipping
279
+ if idx == 0 and not args.trt:
280
+ pixels = pixels[:, 3:]
281
+ elif APP_STATE["current_use_taehv"] and idx > 0:
282
+ pixels = pixels[:, 12:]
283
+
284
+ print(f"πŸ” DEBUG Block {idx}: Pixels shape after skipping: {pixels.shape}")
285
+
286
+ # Process all frames from this block at once
287
+ all_frames_from_block = []
288
+ for frame_idx in range(pixels.shape[1]):
289
+ frame_tensor = pixels[0, frame_idx]
290
+
291
+ # Convert to numpy (HWC, RGB, uint8)
292
+ frame_np = torch.clamp(frame_tensor.float(), -1., 1.) * 127.5 + 127.5
293
+ frame_np = frame_np.to(torch.uint8).cpu().numpy()
294
+ frame_np = np.transpose(frame_np, (1, 2, 0)) # CHW -> HWC
295
+
296
+ all_frames_from_block.append(frame_np)
297
+ total_frames_yielded += 1
298
+
299
+ # Yield status update for each frame (cute tracking!)
300
+ blocks_completed = idx
301
+ current_block_progress = (frame_idx + 1) / pixels.shape[1]
302
+ total_progress = (blocks_completed + current_block_progress) / num_blocks * 100
303
+
304
+ # Cap at 100% to avoid going over
305
+ total_progress = min(total_progress, 100.0)
306
+
307
+ frame_status_html = (
308
+ f"<div style='padding: 10px; border: 1px solid #ddd; border-radius: 8px; font-family: sans-serif;'>"
309
+ f" <p style='margin: 0 0 8px 0; font-size: 16px; font-weight: bold;'>Generating Video...</p>"
310
+ f" <div style='background: #e9ecef; border-radius: 4px; width: 100%; overflow: hidden;'>"
311
+ f" <div style='width: {total_progress:.1f}%; height: 20px; background-color: #0d6efd; transition: width 0.2s;'></div>"
312
+ f" </div>"
313
+ f" <p style='margin: 8px 0 0 0; color: #555; font-size: 14px; text-align: right;'>"
314
+ f" Block {idx+1}/{num_blocks} | Frame {total_frames_yielded} | {total_progress:.1f}%"
315
+ f" </p>"
316
+ f"</div>"
317
+ )
318
+
319
+ # Yield None for video but update status (frame-by-frame tracking)
320
+ yield None, frame_status_html
321
+
322
+ # Encode entire block as one chunk immediately
323
+ if all_frames_from_block:
324
+ print(f"πŸ“Ή Encoding block {idx} with {len(all_frames_from_block)} frames")
325
+
326
+ try:
327
+ chunk_uuid = str(uuid.uuid4())[:8]
328
+ ts_filename = f"block_{idx:04d}_{chunk_uuid}.ts"
329
+ ts_path = os.path.join("gradio_tmp", ts_filename)
330
+
331
+ frames_to_ts_file(all_frames_from_block, ts_path, fps)
332
+
333
+ # Calculate final progress for this block
334
+ total_progress = (idx + 1) / num_blocks * 100
335
+
336
+ # Yield the actual video chunk
337
+ yield ts_path, gr.update()
338
+
339
+ except Exception as e:
340
+ print(f"⚠️ Error encoding block {idx}: {e}")
341
+ import traceback
342
+ traceback.print_exc()
343
+
344
+ current_start_frame += current_num_frames
345
+
346
+ # Final completion status
347
+ final_status_html = (
348
+ f"<div style='padding: 16px; border: 1px solid #198754; background: linear-gradient(135deg, #d1e7dd, #f8f9fa); border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);'>"
349
+ f" <div style='display: flex; align-items: center; margin-bottom: 8px;'>"
350
+ f" <span style='font-size: 24px; margin-right: 12px;'>πŸŽ‰</span>"
351
+ f" <h4 style='margin: 0; color: #0f5132; font-size: 18px;'>Stream Complete!</h4>"
352
+ f" </div>"
353
+ f" <div style='background: rgba(255,255,255,0.7); padding: 8px; border-radius: 4px;'>"
354
+ f" <p style='margin: 0; color: #0f5132; font-weight: 500;'>"
355
+ f" πŸ“Š Generated {total_frames_yielded} frames across {num_blocks} blocks"
356
+ f" </p>"
357
+ f" <p style='margin: 4px 0 0 0; color: #0f5132; font-size: 14px;'>"
358
+ f" 🎬 Playback: {fps} FPS β€’ πŸ“ Format: MPEG-TS/H.264"
359
+ f" </p>"
360
+ f" </div>"
361
+ f"</div>"
362
+ )
363
+ yield None, final_status_html
364
+ print(f"βœ… PyAV streaming complete! {total_frames_yielded} frames across {num_blocks} blocks")
365
+
366
+ # --- Gradio UI Layout ---
367
+ with gr.Blocks(title="Self-Forcing Streaming Demo") as demo:
368
+ gr.Markdown("# πŸš€ Self-Forcing Video Generation")
369
+ gr.Markdown("Real-time video generation with distilled Wan2-1 1.3B [[Model]](https://huggingface.co/gdhe17/Self-Forcing), [[Project page]](https://self-forcing.github.io), [[Paper]](https://huggingface.co/papers/2506.08009)")
370
+
371
+ with gr.Row():
372
+ with gr.Column(scale=2):
373
+ with gr.Group():
374
+ prompt = gr.Textbox(
375
+ label="Prompt",
376
+ placeholder="A stylish woman walks down a Tokyo street...",
377
+ lines=4,
378
+ value=""
379
+ )
380
+
381
+ start_btn = gr.Button("🎬 Start Streaming", variant="primary", size="lg")
382
+
383
+ gr.Markdown("### 🎯 Examples")
384
+ gr.Examples(
385
+ examples=[
386
+ "A close-up shot of a ceramic teacup slowly pouring water into a glass mug.",
387
+ "A playful cat is seen playing an electronic guitar, strumming the strings with its front paws. The cat has distinctive black facial markings and a bushy tail. It sits comfortably on a small stool, its body slightly tilted as it focuses intently on the instrument. The setting is a cozy, dimly lit room with vintage posters on the walls, adding a retro vibe. The cat's expressive eyes convey a sense of joy and concentration. Medium close-up shot, focusing on the cat's face and hands interacting with the guitar.",
388
+ "A dynamic over-the-shoulder perspective of a chef meticulously plating a dish in a bustling kitchen. The chef, a middle-aged woman, deftly arranges ingredients on a pristine white plate. Her hands move with precision, each gesture deliberate and practiced. The background shows a crowded kitchen with steaming pots, whirring blenders, and the clatter of utensils. Bright lights highlight the scene, casting shadows across the busy workspace. The camera angle captures the chef's detailed work from behind, emphasizing his skill and dedication.",
389
+ ],
390
+ inputs=[prompt],
391
+ )
392
+
393
+ gr.Markdown("### βš™οΈ Settings")
394
+ with gr.Row():
395
+ seed = gr.Number(
396
+ label="Seed",
397
+ value=-1,
398
+ info="Use -1 for random seed",
399
+ precision=0
400
+ )
401
+ fps = gr.Slider(
402
+ label="Playback FPS",
403
+ minimum=1,
404
+ maximum=30,
405
+ value=args.fps,
406
+ step=1,
407
+ visible=False,
408
+ info="Frames per second for playback"
409
+ )
410
+
411
+ with gr.Column(scale=3):
412
+ gr.Markdown("### πŸ“Ί Video Stream")
413
+
414
+ streaming_video = gr.Video(
415
+ label="Live Stream",
416
+ streaming=True,
417
+ loop=True,
418
+ height=400,
419
+ autoplay=True,
420
+ show_label=False
421
+ )
422
+
423
+ status_display = gr.HTML(
424
+ value=(
425
+ "<div style='text-align: center; padding: 20px; color: #666; border: 1px dashed #ddd; border-radius: 8px;'>"
426
+ "🎬 Ready to start streaming...<br>"
427
+ "<small>Configure your prompt and click 'Start Streaming'</small>"
428
+ "</div>"
429
+ ),
430
+ label="Generation Status"
431
+ )
432
+
433
+ # Connect the generator to the streaming video
434
+ start_btn.click(
435
+ fn=video_generation_handler_streaming,
436
+ inputs=[prompt, seed, fps],
437
+ outputs=[streaming_video, status_display]
438
+ )
439
+
440
+
441
+ # --- Launch App ---
442
+ if __name__ == "__main__":
443
+ if os.path.exists("gradio_tmp"):
444
+ import shutil
445
+ shutil.rmtree("gradio_tmp")
446
+ os.makedirs("gradio_tmp", exist_ok=True)
447
+
448
+ print("πŸš€ Starting Self-Forcing Streaming Demo")
449
+ print(f"πŸ“ Temporary files will be stored in: gradio_tmp/")
450
+ print(f"🎯 Chunk encoding: PyAV (MPEG-TS/H.264)")
451
+ print(f"⚑ GPU acceleration: {gpu}")
452
+
453
+ demo.queue().launch(
454
+ server_name=args.host,
455
+ server_port=args.port,
456
+ share=args.share,
457
+ show_error=True,
458
+ max_threads=40,
459
+ mcp_server=True
460
+ )