Spaces:
Runtime error
Runtime error
Update app.py
Browse files145 unmodified lines14614714814915015115277 unmodified lines2302312322332342352362376 unmodified lines2442452462472482492502512522532542552562572582592602612622632642654 unmodified lines27027127227327427527627727827946 unmodified lines326327328329330331332333334335336337338339340341342145 unmodified lines# --- Frame Streaming Video Generation Handler ---@torch.no_grad()@spaces.GPUdef video_generation_handler(prompt, seed, fps, progress=gr.Progress()):"""Generator function that yields RGB frames for display in gr.Image.Includes timing delays for smooth playback.77 unmodified linesprint(f"πΉ Decoded pixels shape: {pixels.shape}")# Yield individual frames with timing delaysfor frame_idx in range(pixels.shape[1]):frame_tensor = pixels[0, frame_idx] # Get single frame [C, H, W]# Normalize from [-1, 1] to [0, 255]6 unmodified linesall_frames_for_video.append(frame_np)total_frames_yielded += 1# Calculate progresstotal_expected_frames = num_blocks * pipeline.num_frame_per_blockcurrent_frame_count = (idx * pipeline.num_frame_per_block) + frame_idx + 1frame_progress = current_frame_count / total_expected_frames# Update progressprogress(frame_progress, desc=f"Frame {total_frames_yielded} | Block {idx+1}/{num_blocks}")print(f"πΊ Yielding frame {total_frames_yielded}: shape {frame_np.shape}")# Yield frame with timing delayyield gr.update(visible=True, frame_np), gr.update(visible=False)# Sleep between frames for smooth playback (except for the last frame)if not (frame_idx == pixels.shape[1] - 1 and idx + 1 == num_blocks):time.sleep(frame_delay)current_start_frame += current_num_frames4 unmodified linesvideo_path = f"gradio_tmp/{seed}_{hashlib.md5(prompt.encode()).hexdigest()}.mp4"imageio.mimwrite(video_path, all_frames_for_video, fps=fps, quality=8)print(f"β Video saved to {video_path}")return gr.update(visible=False), gr.update(value=video_path, visible=True)except Exception as e:print(f"β οΈ Could not save final video: {e}")return None, None# --- Gradio UI Layout ---with gr.Blocks(theme=gr.themes.Soft(), title="Self-Forcing Frame Streaming Demo") as demo:46 unmodified linesfinal_video = gr.Video(label="Final Rendered Video",visible=True,interactive=False,height=400)# Connect the generator to the image displaystart_btn.click(fn=video_generation_handler,inputs=[prompt, seed, fps],outputs=[frame_display, final_video],show_progress="full")# --- Launch App ---145 unmodified lines14614714814915015115277 unmodified lines2302312322332342352362372382392406 unmodified lines2472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922934 unmodified lines29829930030130230330430530630730830931031131231331431531631731831932032132232346 unmodified lines370371372373374375376377378379380381382383384385386387388389390391145 unmodified lines# --- Frame Streaming Video Generation Handler ---@torch.no_grad()@spaces.GPUdef video_generation_handler(prompt, seed, fps):"""Generator function that yields RGB frames for display in gr.Image.Includes timing delays for smooth playback.77 unmodified linesprint(f"πΉ Decoded pixels shape: {pixels.shape}")# Calculate actual frames that will be yielded for this blockactual_frames_this_block = pixels.shape[1]# Yield individual frames with timing delaysfor frame_idx in range(actual_frames_this_block):frame_tensor = pixels[0, frame_idx] # Get single frame [C, H, W]# Normalize from [-1, 1] to [0, 255]6 unmodified linesall_frames_for_video.append(frame_np)total_frames_yielded += 1# Calculate progress based on blocks completed + current block progressblocks_completed = idxcurrent_block_progress = (frame_idx + 1) / actual_frames_this_blocktotal_block_progress = (blocks_completed + current_block_progress) / num_blocksframe_progress_percent = total_block_progress * 100# Cap at 100% to avoid going overframe_progress_percent = min(frame_progress_percent, 100.0)print(f"πΊ Yielding frame {total_frames_yielded}: shape {frame_np.shape}")# Create HTML status updateif frame_idx == actual_frames_this_block - 1 and idx + 1 == num_blocks: # Last framestatus_html = (f"<div style='padding: 16px; border: 1px solid #198754; background-color: #d1e7dd; border-radius: 8px; font-family: sans-serif; text-align: center;'>"f" <h4 style='margin: 0 0 8px 0; color: #0f5132; font-size: 18px;'>π Generation Complete!</h4>"f" <p style='margin: 0; color: #0f5132;'>"f" Total frames: {total_frames_yielded}. The final video is now available."f" </p>"f"</div>")else: # Regular framesstatus_html = (f"<div style='padding: 10px; border: 1px solid #ddd; border-radius: 8px; font-family: sans-serif;'>"f" <p style='margin: 0 0 8px 0; font-size: 16px; font-weight: bold;'>Generating Video...</p>"f" <div style='background: #e9ecef; border-radius: 4px; width: 100%; overflow: hidden;'>"f" <div style='width: {frame_progress_percent:.1f}%; height: 20px; background-color: #0d6efd; transition: width 0.2s;'></div>"f" </div>"f" <p style='margin: 8px 0 0 0; color: #555; font-size: 14px; text-align: right;'>"f" Block {idx+1}/{num_blocks} | Frame {total_frames_yielded} | {frame_progress_percent:.1f}%"f" </p>"f"</div>")# Yield frame with a small delay to ensure UI updatesyield gr.update(visible=True, value=frame_np), gr.update(visible=False), status_html# Sleep between frames for smooth playback (except for the last frame)# Add minimum delay to ensure UI can updateif not (frame_idx == actual_frames_this_block - 1 and idx + 1 == num_blocks):time.sleep(max(frame_delay, 0.1)) # Minimum 100ms delaycurrent_start_frame += current_num_frames4 unmodified linesvideo_path = f"gradio_tmp/{seed}_{hashlib.md5(prompt.encode()).hexdigest()}.mp4"imageio.mimwrite(video_path, all_frames_for_video, fps=fps, quality=8)print(f"β Video saved to {video_path}")final_status_html = (f"<div style='padding: 16px; border: 1px solid #198754; background-color: #d1e7dd; border-radius: 8px; font-family: sans-serif; text-align: center;'>"f" <h4 style='margin: 0 0 8px 0; color: #0f5132; font-size: 18px;'>π Generation Complete!</h4>"f" <p style='margin: 0; color: #0f5132;'>"f" Video saved successfully with {total_frames_yielded} frames at {fps} FPS."f" </p>"f"</div>")yield gr.update(visible=False), gr.update(value=video_path, visible=True), final_status_htmlexcept Exception as e:print(f"β οΈ Could not save final video: {e}")error_status_html = (f"<div style='padding: 16px; border: 1px solid #dc3545; background-color: #f8d7da; border-radius: 8px; font-family: sans-serif; text-align: center;'>"f" <h4 style='margin: 0 0 8px 0; color: #721c24; font-size: 18px;'>β οΈ Video Save Error</h4>"f" <p style='margin: 0; color: #721c24;'>"f" Could not save final video: {str(e)}"f" </p>"f"</div>")yield None, None, error_status_html# --- Gradio UI Layout ---with gr.Blocks(theme=gr.themes.Soft(), title="Self-Forcing Frame Streaming Demo") as demo:46 unmodified linesfinal_video = gr.Video(label="Final Rendered Video",visible=False,interactive=False,height=400,autoplay=True)status_html = gr.HTML(value="<div style='text-align: center; padding: 20px; color: #666;'>Ready to start generation...</div>",label="Generation Status")# Connect the generator to the image displaystart_btn.click(fn=video_generation_handler,inputs=[prompt, seed, fps],outputs=[frame_display, final_video, status_html])# --- Launch App ---
app.py+67-18