Spaces:
Runtime error
Runtime error
some improvements
#2
by linoyts HF Staff - opened
Files changed (4)
35 unmodified lines36373835 unmodified linesastronaut.jpg filter=lfs diff=lfs merge=lfs -textkill_bill.jpeg filter=lfs diff=lfs merge=lfs -textcat_selfie.JPG filter=lfs diff=lfs merge=lfs -text35 unmodified lines3637383935 unmodified linesastronaut.jpg filter=lfs diff=lfs merge=lfs -textkill_bill.jpeg filter=lfs diff=lfs merge=lfs -textcat_selfie.JPG filter=lfs diff=lfs merge=lfs -textwednesday.png filter=lfs diff=lfs merge=lfs -text
8 unmodified lines9101112131418 unmodified lines333435363738394041424324 unmodified lines6869707172737475767778798081828384858687888990919293949511 unmodified lines1071081091101111121131141151161171181191201211221231241251269 unmodified lines13613713813914014124 unmodified lines16616716816917017117217317417517617717821 unmodified lines20020120220320420520626 unmodified lines2332342352362372389 unmodified lines2482492502512522532542552562572582592602618 unmodified linesimport randomimport spacesimport gradio as grfrom typing import Optionalfrom huggingface_hub import hf_hub_downloadfrom ltx_pipelines.ti2vid_two_stages import TI2VidTwoStagesPipeline18 unmodified lines# HuggingFace Hub defaultsDEFAULT_REPO_ID = "Lightricks/LTX-2"DEFAULT_GEMMA_REPO_ID = "google/gemma-3-12b-it-qat-q4_0-unquantized"DEFAULT_CHECKPOINT_FILENAME = "ltx-2-19b-dev-fp8.safetensors"DEFAULT_DISTILLED_LORA_FILENAME = "ltx-2-19b-distilled-lora-384.safetensors"DEFAULT_SPATIAL_UPSAMPLER_FILENAME = "ltx-2-spatial-upscaler-x2-1.0.safetensors"def get_hub_or_local_checkpoint(repo_id: Optional[str] = None, filename: Optional[str] = None):"""Download from HuggingFace Hub or use local checkpoint."""if repo_id is None and filename is None:24 unmodified linesprint(f" checkpoint_path={checkpoint_path}")print(f" distilled_lora_path={distilled_lora_path}")print(f" spatial_upsampler_path={spatial_upsampler_path}")print(f" gemma_root={DEFAULT_GEMMA_REPO_ID}")pipeline = TI2VidTwoStagesPipeline(checkpoint_path=checkpoint_path,distilled_lora_path=distilled_lora_path,distilled_lora_strength=DEFAULT_LORA_STRENGTH,spatial_upsampler_path=spatial_upsampler_path,gemma_root=DEFAULT_GEMMA_REPO_ID,loras=[],fp8transformer=False,local_files_only=False)@spaces.GPU(duration=300)def generate_video(input_image,prompt: str,duration: float,negative_prompt: str = DEFAULT_NEGATIVE_PROMPT,seed: int = 42,randomize_seed: bool = True,num_inference_steps: int = DEFAULT_NUM_INFERENCE_STEPS,cfg_guidance_scale: float = DEFAULT_CFG_GUIDANCE_SCALE,height: int = DEFAULT_HEIGHT,width: int = DEFAULT_WIDTH,11 unmodified lines# Create output directory if it doesn't existoutput_dir = Path("outputs")output_dir.mkdir(exist_ok=True)output_path = output_dir / f"video_{seed}.mp4"# Handle image inputimages = []if input_image is not None:# Save uploaded image temporarilytemp_image_path = output_dir / f"temp_input_{seed}.jpg"if hasattr(input_image, 'save'):input_image.save(temp_image_path)else:# If it's a file path alreadytemp_image_path = input_image# Format: (image_path, frame_idx, strength)images = [(str(temp_image_path), 0, 1.0)]# Run inference - progress automatically tracks tqdm from pipelinepipeline(9 unmodified linescfg_guidance_scale=cfg_guidance_scale,images=images,tiling_config=TilingConfig.default(),)return str(output_path), current_seed24 unmodified linesplaceholder="Describe the motion and animation you want...")duration = gr.Slider(label="Duration (seconds)",minimum=1.0,maximum=10.0,value=3.0,step=0.1)generate_btn = gr.Button("Generate Video", variant="primary")21 unmodified lineslabel="Inference Steps",minimum=1,maximum=100,value=DEFAULT_NUM_INFERENCE_STEPS,step=1)26 unmodified linesinput_image,prompt,duration,negative_prompt,seed,randomize_seed,9 unmodified linesgr.Examples(examples=[["astronaut.jpg","An astronaut hatches from a fragile egg on the surface of the Moon, the shell cracking and peeling apart in gentle low-gravity motion. Fine lunar dust lifts and drifts outward with each movement, floating in slow arcs before settling back onto the ground. The astronaut pushes free in a deliberate, weightless motion, small fragments of the egg tumbling and spinning through the air. In the background, the deep darkness of space subtly shifts as stars glide with the camera's movement, emphasizing vast depth and scale. The camera performs a smooth, cinematic slow push-in, with natural parallax between the foreground dust, the astronaut, and the distant starfield. Ultra-realistic detail, physically accurate low-gravity motion, cinematic lighting, and a breath-taking, movie-like shot.",5.0,],["kill_bill.jpeg","A low, subsonic drone pulses as Uma Thurman's character, Beatrix Kiddo, holds her razor-sharp katana blade steady in the cinematic lighting. A faint electrical hum fills the silence. Suddenly, accompanied by a deep metallic groan, the polished steel begins to soften and distort, like heated metal starting to lose its structural integrity. Discordant strings swell as the blade's perfect edge slowly warps and droops, molten steel beginning to flow downward in silvery rivulets while maintaining its metallic sheen—each drip producing a wet, viscous stretching sound. The transformation starts subtly at first—a slight bend in the blade—then accelerates as the metal becomes increasingly fluid, the groaning intensifying. The camera holds steady on her face as her piercing eyes gradually narrow, not with lethal focus, but with confusion and growing alarm as she watches her weapon dissolve before her eyes. She whispers under her breath, voice flat with disbelief: 'Wait, what?' Her heartbeat rises in the mix—thump... thump-thump—as her breathing quickens slightly while she witnesses this impossible transformation. Sharp violin stabs punctuate each breath. The melting intensifies, the katana's perfect form becoming increasingly abstract, dripping like liquid mercury from her grip. Molten droplets fall to the ground with soft, bell-like pings. Unintelligible whispers fade in and out as her expression shifts from calm readiness to bewilderment and concern, her heartbeat now pounding like a war drum, as her legendary instrument of vengeance literally liquefies in her hands, leaving her defenseless and disoriented. All sound cuts to silence—then a single devastating bass drop as the final droplet falls, leaving only her unsteady breathing in the dark.",5.0,]],fn=generate_video,8 unmodified lines9101112131415161718 unmodified lines3637383940414243444546474824 unmodified lines73747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211 unmodified lines1241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861879 unmodified lines19719819920020120220320420520624 unmodified lines23123223323423523623723823924024124224324424524624724821 unmodified lines27027127227327427527626 unmodified lines3033043053063073083099 unmodified lines3193203213223233243253263273283293303313323333343353363378 unmodified linesimport randomimport spacesimport gradio as grfrom gradio_client import Client, handle_fileimport torchfrom pathlib import Pathfrom typing import Optionalfrom huggingface_hub import hf_hub_downloadfrom ltx_pipelines.ti2vid_two_stages import TI2VidTwoStagesPipeline18 unmodified lines# HuggingFace Hub defaultsDEFAULT_REPO_ID = "Lightricks/LTX-2"DEFAULT_CHECKPOINT_FILENAME = "ltx-2-19b-dev-fp8.safetensors"DEFAULT_DISTILLED_LORA_FILENAME = "ltx-2-19b-distilled-lora-384.safetensors"DEFAULT_SPATIAL_UPSAMPLER_FILENAME = "ltx-2-spatial-upscaler-x2-1.0.safetensors"# Text encoder space URLTEXT_ENCODER_SPACE = "linoyts/gemma-text-encoder"def get_hub_or_local_checkpoint(repo_id: Optional[str] = None, filename: Optional[str] = None):"""Download from HuggingFace Hub or use local checkpoint."""if repo_id is None and filename is None:24 unmodified linesprint(f" checkpoint_path={checkpoint_path}")print(f" distilled_lora_path={distilled_lora_path}")print(f" spatial_upsampler_path={spatial_upsampler_path}")print(f" text_encoder_space={TEXT_ENCODER_SPACE}")# Initialize pipeline WITHOUT text encoder (gemma_root=None)# Text encoding will be done by external spacepipeline = TI2VidTwoStagesPipeline(checkpoint_path=checkpoint_path,distilled_lora_path=distilled_lora_path,distilled_lora_strength=DEFAULT_LORA_STRENGTH,spatial_upsampler_path=spatial_upsampler_path,gemma_root=None,loras=[],fp8transformer=False,local_files_only=False)# Initialize text encoder clientprint(f"Connecting to text encoder space: {TEXT_ENCODER_SPACE}")try:text_encoder_client = Client(TEXT_ENCODER_SPACE)print("✓ Text encoder client connected!")except Exception as e:print(f"⚠ Warning: Could not connect to text encoder space: {e}")text_encoder_client = None@spaces.GPU(duration=300)def generate_video(input_image,prompt: str,duration: float,enhance_prompt: bool = True,negative_prompt: str = DEFAULT_NEGATIVE_PROMPT,seed: int = 42,randomize_seed: bool = True,num_inference_steps: int = 25,cfg_guidance_scale: float = DEFAULT_CFG_GUIDANCE_SCALE,height: int = DEFAULT_HEIGHT,width: int = DEFAULT_WIDTH,11 unmodified lines# Create output directory if it doesn't existoutput_dir = Path("outputs")output_dir.mkdir(exist_ok=True)output_path = output_dir / f"video_{current_seed}.mp4"# Handle image inputimages = []temp_image_path = None # Initialize to Noneif input_image is not None:# Save uploaded image temporarilytemp_image_path = output_dir / f"temp_input_{current_seed}.jpg"if hasattr(input_image, 'save'):input_image.save(temp_image_path)else:# If it's a file path alreadytemp_image_path = Path(input_image)# Format: (image_path, frame_idx, strength)images = [(str(temp_image_path), 0, 1.0)]# Get embeddings from text encoder spaceprint(f"Encoding prompt: {prompt}")if text_encoder_client is None:raise RuntimeError(f"Text encoder client not connected. Please ensure the text encoder space "f"({TEXT_ENCODER_SPACE}) is running and accessible.")try:# Prepare image for upload if it existsimage_input = Noneif temp_image_path is not None:image_input = handle_file(str(temp_image_path))result = text_encoder_client.predict(prompt=prompt,enhance_prompt=enhance_prompt,input_image=image_input,seed=current_seed,negative_prompt=negative_prompt,api_name="/encode_prompt")embedding_path = result[0] # Path to .pt fileprint(f"Embeddings received from: {embedding_path}")# Load embeddingsembeddings = torch.load(embedding_path)video_context_positive = embeddings['video_context']audio_context_positive = embeddings['audio_context']# Load negative contexts if availablevideo_context_negative = embeddings.get('video_context_negative', None)audio_context_negative = embeddings.get('audio_context_negative', None)print("✓ Embeddings loaded successfully")if video_context_negative is not None:print(" ✓ Negative prompt embeddings also loaded")except Exception as e:raise RuntimeError(f"Failed to get embeddings from text encoder space: {e}\n"f"Please ensure {TEXT_ENCODER_SPACE} is running properly.")# Run inference - progress automatically tracks tqdm from pipelinepipeline(9 unmodified linescfg_guidance_scale=cfg_guidance_scale,images=images,tiling_config=TilingConfig.default(),video_context_positive=video_context_positive,audio_context_positive=audio_context_positive,video_context_negative=video_context_negative,audio_context_negative=audio_context_negative,)return str(output_path), current_seed24 unmodified linesplaceholder="Describe the motion and animation you want...")with gr.Row():duration = gr.Slider(label="Duration (seconds)",minimum=1.0,maximum=10.0,value=3.0,step=0.1)enhance_prompt = gr.Checkbox(label="Enhance Prompt",value=True)generate_btn = gr.Button("Generate Video", variant="primary")21 unmodified lineslabel="Inference Steps",minimum=1,maximum=100,value=25,step=1)26 unmodified linesinput_image,prompt,duration,enhance_prompt,negative_prompt,seed,randomize_seed,9 unmodified linesgr.Examples(examples=[["kill_bill.jpeg","A low, subsonic drone pulses as Uma Thurman's character, Beatrix Kiddo, holds her razor-sharp katana blade steady in the cinematic lighting. A faint electrical hum fills the silence. Suddenly, accompanied by a deep metallic groan, the polished steel begins to soften and distort, like heated metal starting to lose its structural integrity. Discordant strings swell as the blade's perfect edge slowly warps and droops, molten steel beginning to flow downward in silvery rivulets while maintaining its metallic sheen—each drip producing a wet, viscous stretching sound. The transformation starts subtly at first—a slight bend in the blade—then accelerates as the metal becomes increasingly fluid, the groaning intensifying. The camera holds steady on her face as her piercing eyes gradually narrow, not with lethal focus, but with confusion and growing alarm as she watches her weapon dissolve before her eyes. She whispers under her breath, voice flat with disbelief: 'Wait, what?' Her heartbeat rises in the mix—thump... thump-thump—as her breathing quickens slightly while she witnesses this impossible transformation. Sharp violin stabs punctuate each breath. The melting intensifies, the katana's perfect form becoming increasingly abstract, dripping like liquid mercury from her grip. Molten droplets fall to the ground with soft, bell-like pings. Unintelligible whispers fade in and out as her expression shifts from calm readiness to bewilderment and concern, her heartbeat now pounding like a war drum, as her legendary instrument of vengeance literally liquefies in her hands, leaving her defenseless and disoriented. All sound cuts to silence—then a single devastating bass drop as the final droplet falls, leaving only her unsteady breathing in the dark.",5.0,],["wednesday.png","A cinematic close-up of Wednesday Addams frozen mid-dance on a dark, blue-lit ballroom floor as students move indistinctly behind her, their footsteps and muffled music reduced to a distant, underwater thrum; the audio foregrounds her steady breathing and the faint rustle of fabric as she slowly raises one arm, never breaking eye contact with the camera, then after a deliberately long silence she speaks in a flat, dry, perfectly controlled voice, “I don’t dance… I vibe code,” each word crisp and unemotional, followed by an abrupt cutoff of her voice as the background sound swells slightly, reinforcing the deadpan humor, with precise lip sync, minimal facial movement, stark gothic lighting, and cinematic realism.",5.0,],["astronaut.jpg","An astronaut hatches from a fragile egg on the surface of the Moon, the shell cracking and peeling apart in gentle low-gravity motion. Fine lunar dust lifts and drifts outward with each movement, floating in slow arcs before settling back onto the ground. The astronaut pushes free in a deliberate, weightless motion, small fragments of the egg tumbling and spinning through the air. In the background, the deep darkness of space subtly shifts as stars glide with the camera's movement, emphasizing vast depth and scale. The camera performs a smooth, cinematic slow push-in, with natural parallax between the foreground dust, the astronaut, and the distant starfield. Ultra-realistic detail, physically accurate low-gravity motion, cinematic lighting, and a breath-taking, movie-like shot.",3.0,]],fn=generate_video,
21 unmodified lines22232425262762 unmodified lines9091929394951 unmodified line97989910010110210310410510610710810911059 unmodified lines1701711721731741751763 unmodified lines18018118218318418521 unmodified linesdenoise_audio_video,encode_text,euler_denoising_loop,guider_denoising_func,simple_denoising_func,)62 unmodified linescfg_guidance_scale: float,images: list[tuple[str, int, float]],tiling_config: TilingConfig | None = None,) -> None:generator = torch.Generator(device=self.device).manual_seed(seed)noiser = GaussianNoiser(generator=generator)1 unmodified linecfg_guider = CFGGuider(cfg_guidance_scale)dtype = torch.bfloat16text_encoder = self.stage_1_model_ledger.text_encoder()context_p, context_n = encode_text(text_encoder, prompts=[prompt, negative_prompt])v_context_p, a_context_p = context_pv_context_n, a_context_n = context_ntorch.cuda.synchronize()del text_encoderutils.cleanup_memory()# Stage 1: Initial low resolution video generation.video_encoder = self.stage_1_model_ledger.video_encoder()59 unmodified linesdef second_stage_denoising_loop(sigmas: torch.Tensor, video_state: LatentState, audio_state: LatentState, stepper: DiffusionStepProtocol) -> tuple[LatentState, LatentState]:return euler_denoising_loop(sigmas=sigmas,video_state=video_state,audio_state=audio_state,3 unmodified linesaudio_context=a_context_p,transformer=transformer, # noqa: F821),)stage_2_output_shape = VideoPixelShape(21 unmodified lines2223242526272862 unmodified lines9192939495969798991001 unmodified line10210310410510610710810911011111211311411511611711811912012112212312459 unmodified lines1841851861871881891901911921931941951961971981992002013 unmodified lines20520620720820921021121 unmodified linesdenoise_audio_video,encode_text,euler_denoising_loop,gradient_estimating_euler_denoising_loop,guider_denoising_func,simple_denoising_func,)62 unmodified linescfg_guidance_scale: float,images: list[tuple[str, int, float]],tiling_config: TilingConfig | None = None,video_context_positive: torch.Tensor | None = None,audio_context_positive: torch.Tensor | None = None,video_context_negative: torch.Tensor | None = None,audio_context_negative: torch.Tensor | None = None,) -> None:generator = torch.Generator(device=self.device).manual_seed(seed)noiser = GaussianNoiser(generator=generator)1 unmodified linecfg_guider = CFGGuider(cfg_guidance_scale)dtype = torch.bfloat16# Use pre-computed embeddings if provided, otherwise encode textif (video_context_positive is None or audio_context_positive is None orvideo_context_negative is None or audio_context_negative is None):text_encoder = self.stage_1_model_ledger.text_encoder()context_p, context_n = encode_text(text_encoder, prompts=[prompt, negative_prompt])v_context_p, a_context_p = context_pv_context_n, a_context_n = context_ntorch.cuda.synchronize()del text_encoderutils.cleanup_memory()else:# Move pre-computed embeddings to device if neededv_context_p = video_context_positive.to(self.device)a_context_p = audio_context_positive.to(self.device)v_context_n = video_context_negative.to(self.device)a_context_n = audio_context_negative.to(self.device)# Stage 1: Initial low resolution video generation.video_encoder = self.stage_1_model_ledger.video_encoder()59 unmodified linesdef second_stage_denoising_loop(sigmas: torch.Tensor, video_state: LatentState, audio_state: LatentState, stepper: DiffusionStepProtocol) -> tuple[LatentState, LatentState]:# return euler_denoising_loop(# sigmas=sigmas,# video_state=video_state,# audio_state=audio_state,# stepper=stepper,# denoise_fn=simple_denoising_func(# video_context=v_context_p,# audio_context=a_context_p,# transformer=transformer, # noqa: F821# ),# )return gradient_estimating_euler_denoising_loop(sigmas=sigmas,video_state=video_state,audio_state=audio_state,3 unmodified linesaudio_context=a_context_p,transformer=transformer, # noqa: F821),ge_gamma=2.0, # Gradient estimation coefficient)stage_2_output_shape = VideoPixelShape(
.gitattributes+1
app.py+95-19
packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages.py+34-8
wednesday.pngAdded

Large File Pointer Details
- SHA256: 27193cae97c24a31ab574a21fc3c598627c28ab60edb0c60209acdb8071cf1ea
- Pointer size: 132 Bytes
- Size of remote file: 1.36 MB