Download app.py from morisp/video: direct link, hf CLI and curl.
- Browser
- Download file 6.57 kB
-
https://huggingface.co/spaces/morisp/video/resolve/main/app.py
- Command line
-
hf download hf://spaces/morisp/video/app.py
-
curl -L -o app.py https://huggingface.co/spaces/morisp/video/resolve/main/app.py
6.57 kB
| """ | |
| Text-to-Video con AnimateDiff (Stable Diffusion 1.5) para Hugging Face Spaces | |
| con ZeroGPU (@spaces.GPU). | |
| - Modelo base: runwayml/stable-diffusion-v1-5 | |
| - Adaptador de movimiento: guoyww/animatediff-motion-adapter-v1-5-2 | |
| - Precisión: torch.float16 + VAE slicing para reducir el uso de VRAM | |
| - Exportación: MP4 mediante diffusers.utils.export_to_video | |
| """ | |
| import os | |
| import tempfile | |
| import gradio as gr | |
| import spaces | |
| import torch | |
| from diffusers import AnimateDiffPipeline, DDIMScheduler, MotionAdapter | |
| from diffusers.utils import export_to_video | |
| # --------------------------------------------------------------------------- | |
| # Configuración global | |
| # --------------------------------------------------------------------------- | |
| BASE_MODEL = "runwayml/stable-diffusion-v1-5" | |
| MOTION_ADAPTER = "guoyww/animatediff-motion-adapter-v1-5-2" | |
| DTYPE = torch.float16 | |
| MAX_SEED = 2**31 - 1 | |
| # --------------------------------------------------------------------------- | |
| # Carga del pipeline en CPU (ZeroGPU no permite usar CUDA fuera de @spaces.GPU) | |
| # --------------------------------------------------------------------------- | |
| adapter = MotionAdapter.from_pretrained(MOTION_ADAPTER, torch_dtype=DTYPE) | |
| pipe = AnimateDiffPipeline.from_pretrained( | |
| BASE_MODEL, | |
| motion_adapter=adapter, | |
| torch_dtype=DTYPE, | |
| ) | |
| # DDIMScheduler configurado para generación de video rápida y estable. | |
| pipe.scheduler = DDIMScheduler.from_pretrained( | |
| BASE_MODEL, | |
| subfolder="scheduler", | |
| clip_sample=False, | |
| timestep_spacing="linspace", | |
| beta_schedule="linear", | |
| steps_offset=1, | |
| ) | |
| # Optimizaciones de memoria. | |
| pipe.enable_vae_slicing() | |
| pipe.set_progress_bar_config(disable=True) | |
| # --------------------------------------------------------------------------- | |
| # Inferencia en GPU (ZeroGPU) | |
| # --------------------------------------------------------------------------- | |
| def generate_video( | |
| prompt: str, | |
| negative_prompt: str, | |
| num_frames: int, | |
| num_inference_steps: int, | |
| guidance_scale: float, | |
| seed: int, | |
| randomize_seed: bool, | |
| progress=gr.Progress(track_tqdm=True), | |
| ): | |
| """Genera un video MP4 corto a partir de un prompt de texto.""" | |
| if not prompt or not prompt.strip(): | |
| raise gr.Error("Escribe un prompt para generar el video.") | |
| # Mover el pipeline a CUDA dentro de la función decorada. | |
| pipe.to("cuda") | |
| if randomize_seed: | |
| seed = int(torch.randint(0, MAX_SEED, (1,)).item()) | |
| generator = torch.Generator(device="cuda").manual_seed(int(seed)) | |
| output = pipe( | |
| prompt=prompt.strip(), | |
| negative_prompt=(negative_prompt or "").strip() or None, | |
| num_frames=int(num_frames), | |
| num_inference_steps=int(num_inference_steps), | |
| guidance_scale=float(guidance_scale), | |
| generator=generator, | |
| ) | |
| frames = output.frames[0] | |
| # Exportar los frames a un archivo MP4 temporal (8 fps). | |
| out_path = os.path.join(tempfile.mkdtemp(), "animatediff.mp4") | |
| export_to_video(frames, out_path, fps=8) | |
| return out_path, int(seed) | |
| # --------------------------------------------------------------------------- | |
| # Interfaz Gradio | |
| # --------------------------------------------------------------------------- | |
| CSS = """ | |
| #col-container { max-width: 900px; margin: 0 auto; } | |
| #title { text-align: center; } | |
| """ | |
| EXAMPLES = [ | |
| ["a corgi running on the beach at sunset, cinematic, 4k", "blurry, low quality, watermark", 16, 20], | |
| ["timelapse of clouds over snowy mountains, dramatic lighting", "blurry, distorted, text", 16, 25], | |
| ["a neon cyberpunk street with rain, reflections, moody", "low quality, deformed", 24, 25], | |
| ] | |
| with gr.Blocks(theme=gr.themes.Soft(), css=CSS, title="AnimateDiff Text-to-Video") as demo: | |
| with gr.Column(elem_id="col-container"): | |
| gr.Markdown( | |
| """ | |
| # 🎬 AnimateDiff · Text-to-Video | |
| Genera clips cortos a partir de texto con **Stable Diffusion 1.5** y el | |
| adaptador de movimiento **AnimateDiff v1.5-2**, acelerado con **ZeroGPU**. | |
| """, | |
| elem_id="title", | |
| ) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| prompt = gr.Textbox( | |
| label="Prompt", | |
| placeholder="Describe el video que quieres generar…", | |
| lines=3, | |
| ) | |
| negative_prompt = gr.Textbox( | |
| label="Negative Prompt", | |
| value="blurry, low quality, distorted, watermark, text", | |
| lines=2, | |
| ) | |
| num_frames = gr.Slider( | |
| label="Frames", minimum=8, maximum=24, step=1, value=16 | |
| ) | |
| num_inference_steps = gr.Slider( | |
| label="Pasos de inferencia", minimum=10, maximum=30, step=1, value=20 | |
| ) | |
| with gr.Accordion("Opciones avanzadas", open=False): | |
| guidance_scale = gr.Slider( | |
| label="Guidance scale", minimum=1.0, maximum=12.0, step=0.5, value=7.5 | |
| ) | |
| seed = gr.Slider( | |
| label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0 | |
| ) | |
| randomize_seed = gr.Checkbox(label="Seed aleatoria", value=True) | |
| run_button = gr.Button("🚀 Generar Video", variant="primary", size="lg") | |
| with gr.Column(scale=1): | |
| video_out = gr.Video( | |
| label="Video generado", | |
| autoplay=True, | |
| show_download_button=True, | |
| ) | |
| used_seed = gr.Number(label="Seed utilizada", interactive=False) | |
| gr.Examples( | |
| examples=EXAMPLES, | |
| inputs=[prompt, negative_prompt, num_frames, num_inference_steps], | |
| label="Ejemplos", | |
| ) | |
| run_button.click( | |
| fn=generate_video, | |
| inputs=[ | |
| prompt, | |
| negative_prompt, | |
| num_frames, | |
| num_inference_steps, | |
| guidance_scale, | |
| seed, | |
| randomize_seed, | |
| ], | |
| outputs=[video_out, used_seed], | |
| ) | |
| prompt.submit( | |
| fn=generate_video, | |
| inputs=[ | |
| prompt, | |
| negative_prompt, | |
| num_frames, | |
| num_inference_steps, | |
| guidance_scale, | |
| seed, | |
| randomize_seed, | |
| ], | |
| outputs=[video_out, used_seed], | |
| ) | |
| if __name__ == "__main__": | |
| demo.queue(max_size=12).launch() | |