Spaces:
Build error
Build error
Julian Bilcke commited on
Commit ·
ca9df37
1
Parent(s): 2f28683
improving the preview_tab
Browse filesFiles changed (2)
84 unmodified lines8586878889909192939448 unmodified lines14314414514614714814915015115215315491 unmodified lines246247248249250251252253254255256114 unmodified lines371372373374375376377378379108 unmodified lines48848949049149249349449549684 unmodified lines# Return updated log string for UI updatesreturn "\n".join(log_messages)# Find latest LoRA weightslora_path = self.find_latest_lora_weights()if not lora_path:return None, "Error: No LoRA weights found", log("Error: No LoRA weights found in output directory")# Add prefix to promptif prompt_prefix and not prompt.startswith(prompt_prefix):48 unmodified lineslog(f"Generating video with model type: {internal_model_type}")log(f"Using model version: {model_version}")log(f"Using LoRA weights from: {lora_path}")log(f"Resolution: {width}x{height}, Frames: {num_frames}, FPS: {fps}")log(f"Guidance Scale: {guidance_scale}, Flow Shift: {flow_shift}, LoRA Weight: {lora_weight}")log(f"Generation Seed: {seed}")log(f"Prompt: {full_prompt}")log(f"Negative Prompt: {negative_prompt}")# Import required components based on model typeif internal_model_type == "wan":91 unmodified lineslog_fn("Enabling model CPU offload...")pipe.enable_model_cpu_offload()log_fn(f"Loading LoRA weights from {lora_path} with weight {lora_weight}...")pipe.load_lora_weights(lora_path)# TODO: Set the lora scale directly instead of using fuse_lora#pipe._lora_scale = lora_weight# Create temporary file for the outputwith tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as temp_file:114 unmodified lineslog_fn("Enabling model CPU offload...")pipe.enable_model_cpu_offload()log_fn(f"Loading LoRA weights from {lora_path} with weight {lora_weight}...")pipe.load_lora_weights(lora_path)pipe.fuse_lora(lora_weight)# Create temporary file for the outputwith tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as temp_file:108 unmodified lineslog_fn("Enabling model CPU offload...")pipe.enable_model_cpu_offload()log_fn(f"Loading LoRA weights from {lora_path} with weight {lora_weight}...")pipe.load_lora_weights(lora_path)pipe.fuse_lora(lora_weight)# Create temporary file for the outputwith tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as temp_file:84 unmodified lines85868788899091929394959697989910010148 unmodified lines15015115215315415515615715815916016116291 unmodified lines254255256257258259260261262263264265266267114 unmodified lines382383384385386387388389390391392393394108 unmodified lines50350450550650750850951051151251351451584 unmodified lines# Return updated log string for UI updatesreturn "\n".join(log_messages)# Find latest LoRA weights if lora_weight > 0lora_path = Noneusing_lora = lora_weight > 0if using_lora:lora_path = self.find_latest_lora_weights()if not lora_path:return None, "Error: No LoRA weights found", log("Error: No LoRA weights found in output directory")log(f"Using LoRA weights with weight {lora_weight}")else:log("Using original model without LoRA weights")# Add prefix to promptif prompt_prefix and not prompt.startswith(prompt_prefix):48 unmodified lineslog(f"Generating video with model type: {internal_model_type}")log(f"Using model version: {model_version}")if using_lora and lora_path:log(f"Using LoRA weights from: {lora_path}")log(f"Resolution: {width}x{height}, Frames: {num_frames}, FPS: {fps}")log(f"Guidance Scale: {guidance_scale}, Flow Shift: {flow_shift}, LoRA Weight: {lora_weight if using_lora else 0}")log(f"Generation Seed: {seed}")#log(f"Prompt: {full_prompt}")#log(f"Negative Prompt: {negative_prompt}")# Import required components based on model typeif internal_model_type == "wan":91 unmodified lineslog_fn("Enabling model CPU offload...")pipe.enable_model_cpu_offload()# Apply LoRA weights if using themif lora_weight > 0 and lora_path:log_fn(f"Loading LoRA weights from {lora_path} with weight {lora_weight}...")pipe.load_lora_weights(lora_path)# TODO: Set the lora scale directly instead of using fuse_lora#pipe._lora_scale = lora_weightelse:log_fn("Using base model without LoRA weights")# Create temporary file for the outputwith tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as temp_file:114 unmodified lineslog_fn("Enabling model CPU offload...")pipe.enable_model_cpu_offload()# Apply LoRA weights if using themif lora_weight > 0 and lora_path:log_fn(f"Loading LoRA weights from {lora_path} with weight {lora_weight}...")pipe.load_lora_weights(lora_path)pipe.fuse_lora(lora_weight)else:log_fn("Using base model without LoRA weights")# Create temporary file for the outputwith tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as temp_file:108 unmodified lineslog_fn("Enabling model CPU offload...")pipe.enable_model_cpu_offload()# Apply LoRA weights if using themif lora_weight > 0 and lora_path:log_fn(f"Loading LoRA weights from {lora_path} with weight {lora_weight}...")pipe.load_lora_weights(lora_path)pipe.fuse_lora(lora_weight)else:log_fn("Using base model without LoRA weights")# Create temporary file for the outputwith tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as temp_file:
51 unmodified lines5253545556575859606162636416 unmodified lines81828384858661 unmodified lines1481491501511521531541 unmodified line15615715815916016116216316416516616716 unmodified lines184185186187188189190191192193131 unmodified lines32532632732832933012 unmodified lines3433443453463473483491 unmodified line35135235335435535635720 unmodified lines37837938038138238338459 unmodified lines4444454464474484497 unmodified lines4574584594604614624633 unmodified lines46746846947047147247348 unmodified lines52252352452552652752821 unmodified lines5505515525535545555567 unmodified lines5645655665675685695705 unmodified lines57657757857958058158258358458558651 unmodified linesvalue=DEFAULT_PROMPT_PREFIX)self.components["seed"] = gr.Slider(label="Generation Seed (-1 for random)",minimum=-1,maximum=2147483647, # 2^31 - 1step=1,value=-1,info="Set to -1 for random seed or specific value for reproducible results")with gr.Row():16 unmodified linesvalue=self.get_default_model_version(default_model))# Add image input for image-to-video modelsself.components["conditioning_image"] = gr.Image(label="Conditioning Image (for Image-to-Video models)",61 unmodified linesminimum=0.0,maximum=1.0,step=0.01,value=0.7)self.components["inference_steps"] = gr.Slider(1 unmodified lineminimum=1,maximum=100,step=1,value=30)self.components["enable_cpu_offload"] = gr.Checkbox(label="Enable Model CPU Offload (for low-VRAM GPUs)",value=True)self.components["generate_btn"] = gr.Button(16 unmodified linesself.components["log"] = gr.TextArea(label="Generation Log",interactive=False,lines=15)return tabdef get_model_version_choices(self, model_type: str) -> List[str]:"""Get model version choices based on model type"""131 unmodified lines])# Load preview UI state when the tab is selectedif hasattr(self.app, 'tabs_component') and self.app.tabs_component is not None:self.app.tabs_component.select(12 unmodified linesself.components["lora_weight"],self.components["inference_steps"],self.components["enable_cpu_offload"],self.components["model_version"]])1 unmodified linefor component_name in ["prompt", "negative_prompt", "prompt_prefix", "model_version", "resolution_preset","width", "height", "num_frames", "fps", "guidance_scale", "flow_shift","lora_weight", "inference_steps", "enable_cpu_offload"]:if component_name in self.components:self.components[component_name].change(20 unmodified linesself.components["inference_steps"],self.components["enable_cpu_offload"],self.components["fps"],self.components["conditioning_image"]],outputs=[self.components["preview_video"],59 unmodified linesif model_version not in model_version_choices and model_version_choices:model_version = model_version_choices[0]return (preview_state.get("prompt", ""),preview_state.get("negative_prompt", "worst quality, low quality, blurry, jittery, distorted, ugly, deformed, disfigured, messy background"),7 unmodified linespreview_state.get("lora_weight", 0.7),preview_state.get("inference_steps", 30),preview_state.get("enable_cpu_offload", True),model_version)except Exception as e:logger.error(f"Error loading preview state: {e}")3 unmodified lines"worst quality, low quality, blurry, jittery, distorted, ugly, deformed, disfigured, messy background",DEFAULT_PROMPT_PREFIX,832, 480, 49, 16, 5.0, 3.0, 0.7, 30, True,self.get_default_model_version(self.get_default_model_type()))def save_preview_state_value(self, value: Any) -> None:48 unmodified linesinference_steps: int,enable_cpu_offload: bool,fps: int,conditioning_image: Optional[str] = None) -> Tuple[Optional[str], str, str]:"""Handler for generate button click, delegates to preview service"""# Save all the parameters to preview state before generating21 unmodified lines"flow_shift": flow_shift,"lora_weight": lora_weight,"inference_steps": inference_steps,"enable_cpu_offload": enable_cpu_offload}state["preview"] = preview_state7 unmodified lines# Initial UI updatevideo_path, status, log = None, "Initializing generation...", "Starting video generation process..."# Start actual generationresult = self.app.previewing.generate_video(model_type=model_type,model_version=model_version_id,5 unmodified linesnum_frames=num_frames,guidance_scale=guidance_scale,flow_shift=flow_shift,lora_weight=lora_weight,inference_steps=inference_steps,enable_cpu_offload=enable_cpu_offload,fps=fps,conditioning_image=conditioning_image)# Return final result51 unmodified lines52535455565758596061626364656616 unmodified lines838485868788899091929394959697989910010110210310410510661 unmodified lines1681691701711721731741751 unmodified line17717817918018118218318418518618718816 unmodified lines205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241131 unmodified lines37337437537637737837938038138238338438512 unmodified lines3983994004014024034044054061 unmodified line40840941041141241341420 unmodified lines43543643743843944044144244359 unmodified lines5035045055065075085095105115125135145155165175185195205215225235245255265275287 unmodified lines5365375385395405415425435443 unmodified lines54854955055155255355455555648 unmodified lines60560660760860961061161261321 unmodified lines6356366376386396406416426437 unmodified lines6516526536546556566576586596606616626635 unmodified lines66967067167267367467567667767867968051 unmodified linesvalue=DEFAULT_PROMPT_PREFIX)# Ensure seed is interactive with a sliderself.components["seed"] = gr.Slider(label="Generation Seed (-1 for random)",minimum=-1,maximum=2147483647, # 2^31 - 1step=1,value=-1,info="Set to -1 for random seed or specific value for reproducible results",interactive=True)with gr.Row():16 unmodified linesvalue=self.get_default_model_version(default_model))# Add dropdown to choose between LoRA and original modelhas_lora = self.check_lora_model_exists()lora_choices = []default_lora_choice = ""if has_lora:lora_choices = ["Use LoRA model", "Use original model"]default_lora_choice = "Use LoRA model"else:lora_choices = ["Cannot find LoRA model", "Use original model"]default_lora_choice = "Use original model"self.components["use_lora"] = gr.Dropdown(choices=lora_choices,label="Model Selection",value=default_lora_choice)# Add image input for image-to-video modelsself.components["conditioning_image"] = gr.Image(label="Conditioning Image (for Image-to-Video models)",61 unmodified linesminimum=0.0,maximum=1.0,step=0.01,value=0.7,visible=has_lora # Only visible if using LoRA)self.components["inference_steps"] = gr.Slider(1 unmodified lineminimum=1,maximum=100,step=1,value=20)self.components["enable_cpu_offload"] = gr.Checkbox(label="Enable Model CPU Offload (for low-VRAM GPUs)",value=False # let's assume user is using a video model training rig with a good GPU)self.components["generate_btn"] = gr.Button(16 unmodified linesself.components["log"] = gr.TextArea(label="Generation Log",interactive=False,lines=20)return tabdef check_lora_model_exists(self) -> bool:"""Check if any LoRA model files exist in the output directory"""# Look for the standard LoRA weights filelora_path = OUTPUT_PATH / "pytorch_lora_weights.safetensors"if lora_path.exists():return True# If not found in the expected location, try to find in checkpointscheckpoints = list(OUTPUT_PATH.glob("checkpoint-*"))if not checkpoints:return Falsefor checkpoint in checkpoints:lora_path = checkpoint / "pytorch_lora_weights.safetensors"if lora_path.exists():return Truereturn Falsedef update_lora_ui(self, use_lora_value: str) -> Dict[str, Any]:"""Update UI based on LoRA selection"""is_using_lora = "Use LoRA model" in use_lora_valuereturn {self.components["lora_weight"]: gr.Slider(visible=is_using_lora)}def get_model_version_choices(self, model_type: str) -> List[str]:"""Get model version choices based on model type"""131 unmodified lines])# Connect LoRA selection dropdown to update LoRA weight visibilityself.components["use_lora"].change(fn=self.update_lora_ui,inputs=[self.components["use_lora"]],outputs=[self.components["lora_weight"]])# Load preview UI state when the tab is selectedif hasattr(self.app, 'tabs_component') and self.app.tabs_component is not None:self.app.tabs_component.select(12 unmodified linesself.components["lora_weight"],self.components["inference_steps"],self.components["enable_cpu_offload"],self.components["model_version"],self.components["seed"],self.components["use_lora"]])1 unmodified linefor component_name in ["prompt", "negative_prompt", "prompt_prefix", "model_version", "resolution_preset","width", "height", "num_frames", "fps", "guidance_scale", "flow_shift","lora_weight", "inference_steps", "enable_cpu_offload", "seed", "use_lora"]:if component_name in self.components:self.components[component_name].change(20 unmodified linesself.components["inference_steps"],self.components["enable_cpu_offload"],self.components["fps"],self.components["conditioning_image"],self.components["seed"],self.components["use_lora"]],outputs=[self.components["preview_video"],59 unmodified linesif model_version not in model_version_choices and model_version_choices:model_version = model_version_choices[0]# Check if LoRA exists and set appropriate dropdown optionshas_lora = self.check_lora_model_exists()use_lora = preview_state.get("use_lora", "")# Validate use_lora value against current stateif has_lora:valid_choices = ["Use LoRA model", "Use original model"]if use_lora not in valid_choices:use_lora = "Use LoRA model" # Default when LoRA existselse:valid_choices = ["Cannot find LoRA model", "Use original model"]if use_lora not in valid_choices:use_lora = "Use original model" # Default when no LoRA# Update the dropdown choices in the UItry:self.components["use_lora"].choices = valid_choicesexcept Exception as e:logger.error(f"Failed to update use_lora choices: {e}")return (preview_state.get("prompt", ""),preview_state.get("negative_prompt", "worst quality, low quality, blurry, jittery, distorted, ugly, deformed, disfigured, messy background"),7 unmodified linespreview_state.get("lora_weight", 0.7),preview_state.get("inference_steps", 30),preview_state.get("enable_cpu_offload", True),model_version,preview_state.get("seed", -1),use_lora)except Exception as e:logger.error(f"Error loading preview state: {e}")3 unmodified lines"worst quality, low quality, blurry, jittery, distorted, ugly, deformed, disfigured, messy background",DEFAULT_PROMPT_PREFIX,832, 480, 49, 16, 5.0, 3.0, 0.7, 30, True,self.get_default_model_version(self.get_default_model_type()),-1,"Use original model" if not self.check_lora_model_exists() else "Use LoRA model")def save_preview_state_value(self, value: Any) -> None:48 unmodified linesinference_steps: int,enable_cpu_offload: bool,fps: int,conditioning_image: Optional[str] = None,seed: int = -1,use_lora: str = "Use LoRA model") -> Tuple[Optional[str], str, str]:"""Handler for generate button click, delegates to preview service"""# Save all the parameters to preview state before generating21 unmodified lines"flow_shift": flow_shift,"lora_weight": lora_weight,"inference_steps": inference_steps,"enable_cpu_offload": enable_cpu_offload,"seed": seed,"use_lora": use_lora}state["preview"] = preview_state7 unmodified lines# Initial UI updatevideo_path, status, log = None, "Initializing generation...", "Starting video generation process..."# Set lora_path to None if not using LoRAuse_lora_model = use_lora == "Use LoRA model"# Start actual generation# If not using LoRA, set lora_weight to 0 to disable iteffective_lora_weight = lora_weight if use_lora_model else 0.0result = self.app.previewing.generate_video(model_type=model_type,model_version=model_version_id,5 unmodified linesnum_frames=num_frames,guidance_scale=guidance_scale,flow_shift=flow_shift,lora_weight=effective_lora_weight, # Use 0.0 if not using LoRAinference_steps=inference_steps,enable_cpu_offload=enable_cpu_offload,fps=fps,conditioning_image=conditioning_image,seed=seed)# Return final result
vms/ui/project/services/previewing.py+38-19
vms/ui/project/tabs/preview_tab.py+108-14