File size: 6,565 Bytes
a80c2b2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 | """
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)
# ---------------------------------------------------------------------------
@spaces.GPU(duration=120)
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()
|