Julian Bilcke commited on
Commit ·
b08a534
1
Parent(s): df4b03a
debugging the preview tab
Browse filesFiles changed (3)
- vms/config.py+40-1
- vms/services/previewing.py+110-44
- vms/tabs/preview_tab.py+330-27
57 unmodified lines585960616263646 unmodified lines71727374757657 unmodified linesraise ValueError("NORMALIZE_IMAGES_TO must be either 'png' or 'jpg'")JPEG_QUALITY = int(os.environ.get('JPEG_QUALITY', '97'))# Expanded model types to include Wan-2.1-T2VMODEL_TYPES = {"HunyuanVideo": "hunyuan_video","LTX-Video": "ltx_video",6 unmodified lines"Full Finetune": "full-finetune"}DEFAULT_SEED = 42DEFAULT_REMOVE_COMMON_LLM_CAPTION_PREFIXES = True57 unmodified lines5859606162636 unmodified lines70717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411557 unmodified linesraise ValueError("NORMALIZE_IMAGES_TO must be either 'png' or 'jpg'")JPEG_QUALITY = int(os.environ.get('JPEG_QUALITY', '97'))MODEL_TYPES = {"HunyuanVideo": "hunyuan_video","LTX-Video": "ltx_video",6 unmodified lines"Full Finetune": "full-finetune"}# Model variants for each model typeMODEL_VARIANTS = {"wan": {"Wan-AI/Wan2.1-T2V-1.3B-Diffusers": {"name": "Wan 2.1 T2V 1.3B (text-only, smaller)","type": "text-to-video","description": "Faster, smaller model (1.3B parameters)"},"Wan-AI/Wan2.1-T2V-14B-Diffusers": {"name": "Wan 2.1 T2V 14B (text-only, larger)","type": "text-to-video","description": "Higher quality but slower (14B parameters)"},"Wan-AI/Wan2.1-I2V-14B-480P-Diffusers": {"name": "Wan 2.1 I2V 480p (image+text)","type": "image-to-video","description": "Image conditioning at 480p resolution"},"Wan-AI/Wan2.1-I2V-14B-720P-Diffusers": {"name": "Wan 2.1 I2V 720p (image+text)","type": "image-to-video","description": "Image conditioning at 720p resolution"}},"ltx_video": {"Lightricks/LTX-Video": {"name": "LTX Video (official)","type": "text-to-video","description": "Official LTX Video model"}},"hunyuan_video": {"hunyuanvideo-community/HunyuanVideo": {"name": "Hunyuan Video (official)","type": "text-to-video","description": "Official Hunyuan Video model"}}}DEFAULT_SEED = 42DEFAULT_REMOVE_COMMON_LLM_CAPTION_PREFIXES = True
5 unmodified lines678910111213141516171829 unmodified lines4849505152535455565 unmodified lines626364656667682 unmodified lines71727374757618 unmodified lines95969798991001015 unmodified lines10710810911011111211311411511611711811912012112212312412516 unmodified lines14214314414514614714814915015115215315415515615715815916016116216316416516616716816919 unmodified lines18919019119219319419519619719819920020120220332 unmodified lines23623723823924024124224324424524624724824925025125225325425525625725813 unmodified lines27227327427527627743 unmodified lines32132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035119 unmodified lines3713723733743753763773783795 unmodified linesimport loggingimport tempfileimport torchfrom pathlib import Pathfrom typing import Dict, Any, List, Optional, Tuple, Callablefrom vms.config import (OUTPUT_PATH, STORAGE_PATH, MODEL_TYPES, TRAINING_PATH,DEFAULT_PROMPT_PREFIX)from vms.utils import format_time29 unmodified lineslogger.error(f"Error finding LoRA weights: {e}")return Nonedef generate_video(self,model_type: str,prompt: str,negative_prompt: str,prompt_prefix: str,5 unmodified lineslora_weight: float,inference_steps: int,enable_cpu_offload: bool,fps: int) -> Tuple[Optional[str], str, str]:"""Generate a video using the trained model"""try:2 unmodified linesdef log(msg: str):log_messages.append(msg)logger.info(msg)return "\n".join(log_messages)# Find latest LoRA weights18 unmodified linesif not internal_model_type:return None, f"Error: Invalid model type {model_type}", log(f"Error: Invalid model type {model_type}")log(f"Generating video with model type: {internal_model_type}")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}")5 unmodified linesreturn self.generate_wan_video(full_prompt, negative_prompt, width, height, num_frames,guidance_scale, flow_shift, lora_path, lora_weight,inference_steps, enable_cpu_offload, fps, log)elif internal_model_type == "ltx_video":return self.generate_ltx_video(full_prompt, negative_prompt, width, height, num_frames,guidance_scale, flow_shift, lora_path, lora_weight,inference_steps, enable_cpu_offload, fps, log)elif internal_model_type == "hunyuan_video":return self.generate_hunyuan_video(full_prompt, negative_prompt, width, height, num_frames,guidance_scale, flow_shift, lora_path, lora_weight,inference_steps, enable_cpu_offload, fps, log)else:return None, f"Error: Unsupported model type {internal_model_type}", log(f"Error: Unsupported model type {internal_model_type}")16 unmodified linesinference_steps: int,enable_cpu_offload: bool,fps: int,log_fn: Callable) -> Tuple[Optional[str], str, str]:"""Generate video using Wan model"""start_time = torch.cuda.Event(enable_timing=True)end_time = torch.cuda.Event(enable_timing=True)try:import torchfrom diffusers import AutoencoderKLWan, WanPipelinefrom diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepSchedulerfrom diffusers.utils import export_to_videolog_fn("Importing Wan model components...")# Use the smaller model for faster inferencemodel_id = "Wan-AI/Wan2.1-T2V-1.3B-Diffusers"log_fn(f"Loading VAE from {model_id}...")vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)log_fn(f"Loading transformer from {model_id}...")pipe = WanPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16)log_fn(f"Configuring scheduler with flow_shift={flow_shift}...")pipe.scheduler = UniPCMultistepScheduler.from_config(19 unmodified lineslog_fn("Starting video generation...")start_time.record()output = pipe(prompt=prompt,negative_prompt=negative_prompt,height=height,width=width,num_frames=num_frames,guidance_scale=guidance_scale,num_inference_steps=inference_steps,).frames[0]end_time.record()torch.cuda.synchronize()32 unmodified linesinference_steps: int,enable_cpu_offload: bool,fps: int,log_fn: Callable) -> Tuple[Optional[str], str, str]:"""Generate video using LTX model"""start_time = torch.cuda.Event(enable_timing=True)end_time = torch.cuda.Event(enable_timing=True)try:import torchfrom diffusers import LTXPipelinefrom diffusers.utils import export_to_videolog_fn("Importing LTX model components...")model_id = "Lightricks/LTX-Video"log_fn(f"Loading pipeline from {model_id}...")pipe = LTXPipeline.from_pretrained(model_id, torch_dtype=torch.bfloat16)log_fn("Moving pipeline to CUDA device...")pipe.to("cuda")13 unmodified lineslog_fn("Starting video generation...")start_time.record()video = pipe(prompt=prompt,negative_prompt=negative_prompt,43 unmodified linesinference_steps: int,enable_cpu_offload: bool,fps: int,log_fn: Callable) -> Tuple[Optional[str], str, str]:"""Generate video using HunyuanVideo model"""start_time = torch.cuda.Event(enable_timing=True)end_time = torch.cuda.Event(enable_timing=True)try:import torchfrom diffusers import HunyuanVideoPipeline, HunyuanVideoTransformer3DModel, AutoencoderKLHunyuanVideofrom diffusers.utils import export_to_videolog_fn("Importing HunyuanVideo model components...")model_id = "hunyuanvideo-community/HunyuanVideo"log_fn(f"Loading transformer from {model_id}...")transformer = HunyuanVideoTransformer3DModel.from_pretrained(model_id,subfolder="transformer",torch_dtype=torch.bfloat16)log_fn(f"Loading pipeline from {model_id}...")pipe = HunyuanVideoPipeline.from_pretrained(model_id,transformer=transformer,torch_dtype=torch.float16)19 unmodified lineslog_fn("Starting video generation...")start_time.record()output = pipe(prompt=prompt,negative_prompt=negative_prompt if negative_prompt else None,height=height,width=width,num_frames=num_frames,5 unmodified lines678910111213141516171829 unmodified lines48495051525354555657585960615 unmodified lines67686970717273742 unmodified lines7778798081828318 unmodified lines1021031041051061071081091101111121131141151161171181191201211221231241251261271281291301315 unmodified lines13713813914014114214314414514614714814915015115215315415515615715816 unmodified lines17517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420519 unmodified lines22522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926032 unmodified lines29329429529629729829930030130230330430530630730830931031131231331431531631713 unmodified lines33133233333433533633743 unmodified lines38138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241319 unmodified lines4334344354364374384394404414424434444455 unmodified linesimport loggingimport tempfilefrom pathlib import Pathfrom typing import Dict, Any, List, Optional, Tuple, Callableimport timefrom vms.config import (OUTPUT_PATH, STORAGE_PATH, MODEL_TYPES, TRAINING_PATH,DEFAULT_PROMPT_PREFIX, MODEL_VARIANTS)from vms.utils import format_time29 unmodified lineslogger.error(f"Error finding LoRA weights: {e}")return Nonedef get_model_variants(self, model_type: str) -> Dict[str, Dict[str, str]]:"""Get available model variants for the given model type"""return MODEL_VARIANTS.get(model_type, {})def generate_video(self,model_type: str,model_variant: str,prompt: str,negative_prompt: str,prompt_prefix: str,5 unmodified lineslora_weight: float,inference_steps: int,enable_cpu_offload: bool,fps: int,conditioning_image: Optional[str] = None) -> Tuple[Optional[str], str, str]:"""Generate a video using the trained model"""try:2 unmodified linesdef log(msg: str):log_messages.append(msg)logger.info(msg)# Return updated log string for UI updatesreturn "\n".join(log_messages)# Find latest LoRA weights18 unmodified linesif not internal_model_type:return None, f"Error: Invalid model type {model_type}", log(f"Error: Invalid model type {model_type}")# Check if model variant is valid for this model typevariants = self.get_model_variants(internal_model_type)if model_variant not in variants:# Use default variant if specified one is invalidif len(variants) > 0:model_variant = next(iter(variants.keys()))log(f"Warning: Invalid model variant, using default: {model_variant}")else:# Fall back to default IDs if no variants definedif internal_model_type == "wan":model_variant = "Wan-AI/Wan2.1-T2V-1.3B-Diffusers"elif internal_model_type == "ltx_video":model_variant = "Lightricks/LTX-Video"elif internal_model_type == "hunyuan_video":model_variant = "hunyuanvideo-community/HunyuanVideo"log(f"Warning: No variants defined for model type, using default: {model_variant}")# Check if this is an image-to-video model but no image was providedvariant_info = variants.get(model_variant, {})if variant_info.get("type") == "image-to-video" and not conditioning_image:return None, "Error: This model requires a conditioning image", log("Error: This model variant requires a conditioning image but none was provided")log(f"Generating video with model type: {internal_model_type}")log(f"Using model variant: {model_variant}")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}")5 unmodified linesreturn self.generate_wan_video(full_prompt, negative_prompt, width, height, num_frames,guidance_scale, flow_shift, lora_path, lora_weight,inference_steps, enable_cpu_offload, fps, log,model_variant, conditioning_image)elif internal_model_type == "ltx_video":return self.generate_ltx_video(full_prompt, negative_prompt, width, height, num_frames,guidance_scale, flow_shift, lora_path, lora_weight,inference_steps, enable_cpu_offload, fps, log,model_variant, conditioning_image)elif internal_model_type == "hunyuan_video":return self.generate_hunyuan_video(full_prompt, negative_prompt, width, height, num_frames,guidance_scale, flow_shift, lora_path, lora_weight,inference_steps, enable_cpu_offload, fps, log,model_variant, conditioning_image)else:return None, f"Error: Unsupported model type {internal_model_type}", log(f"Error: Unsupported model type {internal_model_type}")16 unmodified linesinference_steps: int,enable_cpu_offload: bool,fps: int,log_fn: Callable,model_variant: str = "Wan-AI/Wan2.1-T2V-1.3B-Diffusers",conditioning_image: Optional[str] = None) -> Tuple[Optional[str], str, str]:"""Generate video using Wan model"""try:import torchfrom diffusers import AutoencoderKLWan, WanPipelinefrom diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepSchedulerfrom diffusers.utils import export_to_videofrom PIL import Imageimport osstart_time = torch.cuda.Event(enable_timing=True)end_time = torch.cuda.Event(enable_timing=True)log_fn("Importing Wan model components...")log_fn(f"Loading VAE from {model_variant}...")vae = AutoencoderKLWan.from_pretrained(model_variant, subfolder="vae", torch_dtype=torch.float32)log_fn(f"Loading transformer from {model_variant}...")pipe = WanPipeline.from_pretrained(model_variant, vae=vae, torch_dtype=torch.bfloat16)log_fn(f"Configuring scheduler with flow_shift={flow_shift}...")pipe.scheduler = UniPCMultistepScheduler.from_config(19 unmodified lineslog_fn("Starting video generation...")start_time.record()# Check if this is an image-to-video modelis_i2v = "I2V" in model_variantif is_i2v and conditioning_image:log_fn(f"Loading conditioning image from {conditioning_image}...")image = Image.open(conditioning_image).convert("RGB")image = image.resize((width, height))log_fn("Generating video with image conditioning...")output = pipe(prompt=prompt,negative_prompt=negative_prompt,image=image,height=height,width=width,num_frames=num_frames,guidance_scale=guidance_scale,num_inference_steps=inference_steps,).frames[0]else:log_fn("Generating video with text-only conditioning...")output = pipe(prompt=prompt,negative_prompt=negative_prompt,height=height,width=width,num_frames=num_frames,guidance_scale=guidance_scale,num_inference_steps=inference_steps,).frames[0]end_time.record()torch.cuda.synchronize()32 unmodified linesinference_steps: int,enable_cpu_offload: bool,fps: int,log_fn: Callable,model_variant: str = "Lightricks/LTX-Video",conditioning_image: Optional[str] = None) -> Tuple[Optional[str], str, str]:"""Generate video using LTX model"""try:import torchfrom diffusers import LTXPipelinefrom diffusers.utils import export_to_videofrom PIL import Imagestart_time = torch.cuda.Event(enable_timing=True)end_time = torch.cuda.Event(enable_timing=True)log_fn("Importing LTX model components...")log_fn(f"Loading pipeline from {model_variant}...")pipe = LTXPipeline.from_pretrained(model_variant, torch_dtype=torch.bfloat16)log_fn("Moving pipeline to CUDA device...")pipe.to("cuda")13 unmodified lineslog_fn("Starting video generation...")start_time.record()# LTX doesn't currently support image conditioning in the standard wayvideo = pipe(prompt=prompt,negative_prompt=negative_prompt,43 unmodified linesinference_steps: int,enable_cpu_offload: bool,fps: int,log_fn: Callable,model_variant: str = "hunyuanvideo-community/HunyuanVideo",conditioning_image: Optional[str] = None) -> Tuple[Optional[str], str, str]:"""Generate video using HunyuanVideo model"""try:import torchfrom diffusers import HunyuanVideoPipeline, HunyuanVideoTransformer3DModel, AutoencoderKLHunyuanVideofrom diffusers.utils import export_to_videostart_time = torch.cuda.Event(enable_timing=True)end_time = torch.cuda.Event(enable_timing=True)log_fn("Importing HunyuanVideo model components...")log_fn(f"Loading transformer from {model_variant}...")transformer = HunyuanVideoTransformer3DModel.from_pretrained(model_variant,subfolder="transformer",torch_dtype=torch.bfloat16)log_fn(f"Loading pipeline from {model_variant}...")pipe = HunyuanVideoPipeline.from_pretrained(model_variant,transformer=transformer,torch_dtype=torch.float16)19 unmodified lineslog_fn("Starting video generation...")start_time.record()# Fix for Issue #2: The pipe() expected list rather than float# Make sure negative_prompt is a list or Noneneg_prompt = [negative_prompt] if negative_prompt else Noneoutput = pipe(prompt=prompt,negative_prompt=neg_prompt,height=height,width=width,num_frames=num_frames,
5 unmodified lines678910111213146 unmodified lines2122232425262728293022 unmodified lines53545556575859606162636485 unmodified lines1501511521531541551561571581591601611621631647 unmodified lines1721731741751761771781791801811825 unmodified lines1881891901911921931942 unmodified lines1971981992002012023 unmodified lines2062072082092102112122132145 unmodified lines2202212222232242252262272282292302312322332342352362372382392405 unmodified linesimport loggingfrom pathlib import Pathfrom typing import Dict, Any, List, Optional, Tuplefrom vms.tabs import BaseTabfrom vms.config import (MODEL_TYPES, DEFAULT_PROMPT_PREFIX)6 unmodified linessuper().__init__(app_state)self.id = "preview_tab"self.title = "6️⃣ Preview"# Get reference to the preview service from app_stateself.previewing_service = app_state.previewingdef create(self, parent=None) -> gr.TabItem:"""Create the Preview tab UI components"""with gr.TabItem(self.title, id=self.id) as tab:22 unmodified lines)with gr.Row():self.components["model_type"] = gr.Dropdown(choices=list(MODEL_TYPES.keys()),label="Model Type",value=list(MODEL_TYPES.keys())[0])self.components["resolution_preset"] = gr.Dropdown(choices=["480p", "720p"],label="Resolution Preset",85 unmodified linesinteractive=False)with gr.Accordion("Log", open=False):self.components["log"] = gr.TextArea(label="Generation Log",interactive=False,lines=10)return tabdef connect_events(self) -> None:"""Connect event handlers to UI components"""# Update resolution when preset changes7 unmodified lines])# Generate button clickself.components["generate_btn"].click(fn=self.generate_video,inputs=[self.components["model_type"],self.components["prompt"],self.components["negative_prompt"],self.components["prompt_prefix"],5 unmodified linesself.components["lora_weight"],self.components["inference_steps"],self.components["enable_cpu_offload"],self.components["fps"]],outputs=[self.components["preview_video"],2 unmodified lines])def update_resolution(self, preset: str) -> Tuple[int, int, float]:"""Update resolution and flow shift based on preset"""if preset == "480p":3 unmodified lineselse:return 832, 480, 3.0def generate_video(self,model_type: str,prompt: str,negative_prompt: str,prompt_prefix: str,5 unmodified lineslora_weight: float,inference_steps: int,enable_cpu_offload: bool,fps: int) -> Tuple[Optional[str], str, str]:"""Handler for generate button click, delegates to preview service"""return self.preview_service.generate_video(model_type=model_type,prompt=prompt,negative_prompt=negative_prompt,prompt_prefix=prompt_prefix,width=width,height=height,num_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)5 unmodified lines67891011121314156 unmodified lines2223242526272822 unmodified lines515253545556575859606162636465666768697071727374757677787980818285 unmodified lines1681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552567 unmodified lines2642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323335 unmodified lines3393403413423433443453462 unmodified lines3493503513523533543553563573583593603613623633643653663673683693703713 unmodified lines3753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614625 unmodified lines4684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435 unmodified linesimport loggingfrom pathlib import Pathfrom typing import Dict, Any, List, Optional, Tupleimport timefrom .base_tab import BaseTabfrom ..config import (MODEL_TYPES, DEFAULT_PROMPT_PREFIX)6 unmodified linessuper().__init__(app_state)self.id = "preview_tab"self.title = "6️⃣ Preview"def create(self, parent=None) -> gr.TabItem:"""Create the Preview tab UI components"""with gr.TabItem(self.title, id=self.id) as tab:22 unmodified lines)with gr.Row():# Get the currently selected model type from training tab if possibledefault_model = self.get_default_model_type()# Make model_type read-only (disabled), as it must match what was trainedself.components["model_type"] = gr.Dropdown(choices=list(MODEL_TYPES.keys()),label="Model Type (from training)",value=default_model,interactive=False)# Add model variant selection based on model typeself.components["model_variant"] = gr.Dropdown(label="Model Variant",choices=self.get_variant_choices(default_model),value=self.get_default_variant(default_model))# Add image input for image-to-video modelsself.components["conditioning_image"] = gr.Image(label="Conditioning Image (for Image-to-Video models)",type="filepath",visible=False)with gr.Row():self.components["resolution_preset"] = gr.Dropdown(choices=["480p", "720p"],label="Resolution Preset",85 unmodified linesinteractive=False)with gr.Accordion("Log", open=True):self.components["log"] = gr.TextArea(label="Generation Log",interactive=False,lines=15)return tabdef get_variant_choices(self, model_type: str) -> List[str]:"""Get model variant choices based on model type"""# Convert UI display name to internal nameinternal_type = MODEL_TYPES.get(model_type)if not internal_type:return []# Get variants from preview servicevariants = self.app.previewing.get_model_variants(internal_type)if not variants:return []# Format choices with display name and descriptionchoices = []for model_id, info in variants.items():choices.append(f"{model_id} - {info.get('name', '')}")return choicesdef get_default_variant(self, model_type: str) -> str:"""Get default model variant for the model type"""choices = self.get_variant_choices(model_type)if choices:return choices[0]return ""def get_default_model_type(self) -> str:"""Get the currently selected model type from training tab"""try:# Try to get the model type from UI stateui_state = self.app.training.load_ui_state()model_type = ui_state.get("model_type")# Make sure it's a valid model typeif model_type in MODEL_TYPES:return model_type# If we couldn't get a valid model type, try to get it from the training tab directlyif hasattr(self.app, 'tabs') and 'train_tab' in self.app.tabs:train_tab = self.app.tabs['train_tab']if hasattr(train_tab, 'components') and 'model_type' in train_tab.components:train_model_type = train_tab.components['model_type'].valueif train_model_type in MODEL_TYPES:return train_model_type# Fallback to first model typereturn list(MODEL_TYPES.keys())[0]except Exception as e:logger.warning(f"Failed to get default model type: {e}")return list(MODEL_TYPES.keys())[0]def extract_model_id(self, variant_choice: str) -> str:"""Extract model ID from variant choice string"""if " - " in variant_choice:return variant_choice.split(" - ")[0].strip()return variant_choicedef get_variant_type(self, model_type: str, model_variant: str) -> str:"""Get the variant type (text-to-video or image-to-video)"""# Convert UI display name to internal nameinternal_type = MODEL_TYPES.get(model_type)if not internal_type:return "text-to-video"# Extract model_id from variant choicemodel_id = self.extract_model_id(model_variant)# Get variants from preview servicevariants = self.app.previewing.get_model_variants(internal_type)variant_info = variants.get(model_id, {})# Return the variant type or default to text-to-videoreturn variant_info.get("type", "text-to-video")def connect_events(self) -> None:"""Connect event handlers to UI components"""# Update resolution when preset changes7 unmodified lines])# Update model_variant choices when model_type changes or tab is selectedif hasattr(self.app, 'tabs_component') and self.app.tabs_component is not None:self.app.tabs_component.select(fn=self.sync_model_type_and_variants,inputs=[],outputs=[self.components["model_type"],self.components["model_variant"]])# Update variant-specific UI elements when variant changesself.components["model_variant"].change(fn=self.update_variant_ui,inputs=[self.components["model_type"],self.components["model_variant"]],outputs=[self.components["conditioning_image"]])# 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(fn=self.load_preview_state,inputs=[],outputs=[self.components["prompt"],self.components["negative_prompt"],self.components["prompt_prefix"],self.components["width"],self.components["height"],self.components["num_frames"],self.components["fps"],self.components["guidance_scale"],self.components["flow_shift"],self.components["lora_weight"],self.components["inference_steps"],self.components["enable_cpu_offload"],self.components["model_variant"]])# Save preview UI state when values changefor component_name in ["prompt", "negative_prompt", "prompt_prefix", "model_variant", "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(fn=self.save_preview_state_value,inputs=[self.components[component_name]],outputs=[])# Generate button clickself.components["generate_btn"].click(fn=self.generate_video,inputs=[self.components["model_type"],self.components["model_variant"],self.components["prompt"],self.components["negative_prompt"],self.components["prompt_prefix"],5 unmodified linesself.components["lora_weight"],self.components["inference_steps"],self.components["enable_cpu_offload"],self.components["fps"],self.components["conditioning_image"]],outputs=[self.components["preview_video"],2 unmodified lines])def update_variant_ui(self, model_type: str, model_variant: str) -> Dict[str, Any]:"""Update UI based on the selected model variant"""variant_type = self.get_variant_type(model_type, model_variant)# Show conditioning image input only for image-to-video modelsshow_conditioning_image = variant_type == "image-to-video"return {self.components["conditioning_image"]: gr.Image(visible=show_conditioning_image)}def sync_model_type_and_variants(self) -> Tuple[str, str]:"""Sync model type with training tab when preview tab is selected and update variant choices"""model_type = self.get_default_model_type()model_variant = self.get_default_variant(model_type)return model_type, model_variantdef update_resolution(self, preset: str) -> Tuple[int, int, float]:"""Update resolution and flow shift based on preset"""if preset == "480p":3 unmodified lineselse:return 832, 480, 3.0def load_preview_state(self) -> Tuple:"""Load saved preview UI state"""# Try to get the saved statetry:state = self.app.training.load_ui_state()preview_state = state.get("preview", {})# Get model type (can't be changed in UI)model_type = self.get_default_model_type()# If model_variant not in choices for current model_type, use defaultmodel_variant = preview_state.get("model_variant", "")variant_choices = self.get_variant_choices(model_type)if model_variant not in variant_choices and variant_choices:model_variant = variant_choices[0]return (preview_state.get("prompt", ""),preview_state.get("negative_prompt", "worst quality, low quality, blurry, jittery, distorted, ugly, deformed, disfigured, messy background"),preview_state.get("prompt_prefix", DEFAULT_PROMPT_PREFIX),preview_state.get("width", 832),preview_state.get("height", 480),preview_state.get("num_frames", 49),preview_state.get("fps", 16),preview_state.get("guidance_scale", 5.0),preview_state.get("flow_shift", 3.0),preview_state.get("lora_weight", 0.7),preview_state.get("inference_steps", 30),preview_state.get("enable_cpu_offload", True),model_variant)except Exception as e:logger.error(f"Error loading preview state: {e}")# Return defaults if loading failsreturn ("","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_variant(self.get_default_model_type()))def save_preview_state_value(self, value: Any) -> None:"""Save an individual preview state value"""try:# Get the component name from the event contextimport inspectframe = inspect.currentframe()frame = inspect.getouterframes(frame)[1]event_context = frame.frame.f_localscomponent = event_context.get('component')if component is None:return# Find the component namecomponent_name = Nonefor name, comp in self.components.items():if comp == component:component_name = namebreakif component_name is None:return# Load current statestate = self.app.training.load_ui_state()if "preview" not in state:state["preview"] = {}# Update the valuestate["preview"][component_name] = value# Save stateself.app.training.save_ui_state(state)except Exception as e:logger.error(f"Error saving preview state: {e}")def generate_video(self,model_type: str,model_variant: str,prompt: str,negative_prompt: str,prompt_prefix: str,5 unmodified lineslora_weight: float,inference_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 generatingtry:state = self.app.training.load_ui_state()if "preview" not in state:state["preview"] = {}# Extract model ID from variant choicemodel_variant_id = self.extract_model_id(model_variant)# Update all valuespreview_state = {"prompt": prompt,"negative_prompt": negative_prompt,"prompt_prefix": prompt_prefix,"model_type": model_type,"model_variant": model_variant,"width": width,"height": height,"num_frames": num_frames,"fps": fps,"guidance_scale": guidance_scale,"flow_shift": flow_shift,"lora_weight": lora_weight,"inference_steps": inference_steps,"enable_cpu_offload": enable_cpu_offload}state["preview"] = preview_stateself.app.training.save_ui_state(state)except Exception as e:logger.error(f"Error saving preview state before generation: {e}")# Clear the log display at the start to make room for new logs# Yield and sleep briefly to allow UI updateyield None, "Starting generation...", ""time.sleep(0.1)# Extract model ID from variant choice stringmodel_variant_id = self.extract_model_id(model_variant)# Use streaming updates to provide real-time feedback during generationdef generate_with_updates():# Initial UI updateyield None, "Initializing generation...", "Starting video generation process..."# Start actual generationresult = self.app.previewing.generate_video(model_type=model_type,model_variant=model_variant_id,prompt=prompt,negative_prompt=negative_prompt,prompt_prefix=prompt_prefix,width=width,height=height,num_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 resultreturn result# Return the generator for streaming updatesreturn generate_with_updates()
vms/config.py+40-1
vms/services/previewing.py+110-44
vms/tabs/preview_tab.py+330-27