morisp commited on
Commit
02fccc4
·
verified ·
1 Parent(s): 0742d78

create app.py

Browse files
Files changed (1) hide show
  1. app.py +198 -0
app.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Text-to-Video con AnimateDiff (Stable Diffusion 1.5) para Hugging Face Spaces
3
+ con ZeroGPU (@spaces.GPU).
4
+
5
+ - Modelo base: runwayml/stable-diffusion-v1-5
6
+ - Adaptador de movimiento: guoyww/animatediff-motion-adapter-v1-5-2
7
+ - Precisión: torch.float16 + VAE slicing para reducir el uso de VRAM
8
+ - Exportación: MP4 mediante diffusers.utils.export_to_video
9
+ """
10
+
11
+ import os
12
+ import tempfile
13
+
14
+ import gradio as gr
15
+ import spaces
16
+ import torch
17
+ from diffusers import AnimateDiffPipeline, DDIMScheduler, MotionAdapter
18
+ from diffusers.utils import export_to_video
19
+
20
+ # ---------------------------------------------------------------------------
21
+ # Configuración global
22
+ # ---------------------------------------------------------------------------
23
+
24
+ BASE_MODEL = "runwayml/stable-diffusion-v1-5"
25
+ MOTION_ADAPTER = "guoyww/animatediff-motion-adapter-v1-5-2"
26
+ DTYPE = torch.float16
27
+ MAX_SEED = 2**31 - 1
28
+
29
+ # ---------------------------------------------------------------------------
30
+ # Carga del pipeline en CPU (ZeroGPU no permite usar CUDA fuera de @spaces.GPU)
31
+ # ---------------------------------------------------------------------------
32
+
33
+ adapter = MotionAdapter.from_pretrained(MOTION_ADAPTER, torch_dtype=DTYPE)
34
+
35
+ pipe = AnimateDiffPipeline.from_pretrained(
36
+ BASE_MODEL,
37
+ motion_adapter=adapter,
38
+ torch_dtype=DTYPE,
39
+ )
40
+
41
+ # DDIMScheduler configurado para generación de video rápida y estable.
42
+ pipe.scheduler = DDIMScheduler.from_pretrained(
43
+ BASE_MODEL,
44
+ subfolder="scheduler",
45
+ clip_sample=False,
46
+ timestep_spacing="linspace",
47
+ beta_schedule="linear",
48
+ steps_offset=1,
49
+ )
50
+
51
+ # Optimizaciones de memoria.
52
+ pipe.enable_vae_slicing()
53
+ pipe.set_progress_bar_config(disable=True)
54
+
55
+
56
+ # ---------------------------------------------------------------------------
57
+ # Inferencia en GPU (ZeroGPU)
58
+ # ---------------------------------------------------------------------------
59
+
60
+ @spaces.GPU(duration=120)
61
+ def generate_video(
62
+ prompt: str,
63
+ negative_prompt: str,
64
+ num_frames: int,
65
+ num_inference_steps: int,
66
+ guidance_scale: float,
67
+ seed: int,
68
+ randomize_seed: bool,
69
+ progress=gr.Progress(track_tqdm=True),
70
+ ):
71
+ """Genera un video MP4 corto a partir de un prompt de texto."""
72
+ if not prompt or not prompt.strip():
73
+ raise gr.Error("Escribe un prompt para generar el video.")
74
+
75
+ # Mover el pipeline a CUDA dentro de la función decorada.
76
+ pipe.to("cuda")
77
+
78
+ if randomize_seed:
79
+ seed = int(torch.randint(0, MAX_SEED, (1,)).item())
80
+ generator = torch.Generator(device="cuda").manual_seed(int(seed))
81
+
82
+ output = pipe(
83
+ prompt=prompt.strip(),
84
+ negative_prompt=(negative_prompt or "").strip() or None,
85
+ num_frames=int(num_frames),
86
+ num_inference_steps=int(num_inference_steps),
87
+ guidance_scale=float(guidance_scale),
88
+ generator=generator,
89
+ )
90
+
91
+ frames = output.frames[0]
92
+
93
+ # Exportar los frames a un archivo MP4 temporal (8 fps).
94
+ out_path = os.path.join(tempfile.mkdtemp(), "animatediff.mp4")
95
+ export_to_video(frames, out_path, fps=8)
96
+
97
+ return out_path, int(seed)
98
+
99
+
100
+ # ---------------------------------------------------------------------------
101
+ # Interfaz Gradio
102
+ # ---------------------------------------------------------------------------
103
+
104
+ CSS = """
105
+ #col-container { max-width: 900px; margin: 0 auto; }
106
+ #title { text-align: center; }
107
+ """
108
+
109
+ EXAMPLES = [
110
+ ["a corgi running on the beach at sunset, cinematic, 4k", "blurry, low quality, watermark", 16, 20],
111
+ ["timelapse of clouds over snowy mountains, dramatic lighting", "blurry, distorted, text", 16, 25],
112
+ ["a neon cyberpunk street with rain, reflections, moody", "low quality, deformed", 24, 25],
113
+ ]
114
+
115
+ with gr.Blocks(theme=gr.themes.Soft(), css=CSS, title="AnimateDiff Text-to-Video") as demo:
116
+ with gr.Column(elem_id="col-container"):
117
+ gr.Markdown(
118
+ """
119
+ # 🎬 AnimateDiff · Text-to-Video
120
+ Genera clips cortos a partir de texto con **Stable Diffusion 1.5** y el
121
+ adaptador de movimiento **AnimateDiff v1.5-2**, acelerado con **ZeroGPU**.
122
+ """,
123
+ elem_id="title",
124
+ )
125
+
126
+ with gr.Row():
127
+ with gr.Column(scale=1):
128
+ prompt = gr.Textbox(
129
+ label="Prompt",
130
+ placeholder="Describe el video que quieres generar…",
131
+ lines=3,
132
+ )
133
+ negative_prompt = gr.Textbox(
134
+ label="Negative Prompt",
135
+ value="blurry, low quality, distorted, watermark, text",
136
+ lines=2,
137
+ )
138
+ num_frames = gr.Slider(
139
+ label="Frames", minimum=8, maximum=24, step=1, value=16
140
+ )
141
+ num_inference_steps = gr.Slider(
142
+ label="Pasos de inferencia", minimum=10, maximum=30, step=1, value=20
143
+ )
144
+ with gr.Accordion("Opciones avanzadas", open=False):
145
+ guidance_scale = gr.Slider(
146
+ label="Guidance scale", minimum=1.0, maximum=12.0, step=0.5, value=7.5
147
+ )
148
+ seed = gr.Slider(
149
+ label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0
150
+ )
151
+ randomize_seed = gr.Checkbox(label="Seed aleatoria", value=True)
152
+
153
+ run_button = gr.Button("🚀 Generar Video", variant="primary", size="lg")
154
+
155
+ with gr.Column(scale=1):
156
+ video_out = gr.Video(
157
+ label="Video generado",
158
+ autoplay=True,
159
+ show_download_button=True,
160
+ )
161
+ used_seed = gr.Number(label="Seed utilizada", interactive=False)
162
+
163
+ gr.Examples(
164
+ examples=EXAMPLES,
165
+ inputs=[prompt, negative_prompt, num_frames, num_inference_steps],
166
+ label="Ejemplos",
167
+ )
168
+
169
+ run_button.click(
170
+ fn=generate_video,
171
+ inputs=[
172
+ prompt,
173
+ negative_prompt,
174
+ num_frames,
175
+ num_inference_steps,
176
+ guidance_scale,
177
+ seed,
178
+ randomize_seed,
179
+ ],
180
+ outputs=[video_out, used_seed],
181
+ )
182
+ prompt.submit(
183
+ fn=generate_video,
184
+ inputs=[
185
+ prompt,
186
+ negative_prompt,
187
+ num_frames,
188
+ num_inference_steps,
189
+ guidance_scale,
190
+ seed,
191
+ randomize_seed,
192
+ ],
193
+ outputs=[video_out, used_seed],
194
+ )
195
+
196
+
197
+ if __name__ == "__main__":
198
+ demo.queue(max_size=12).launch()