muhammadtlha944 commited on
Commit
03a0f2f
Β·
verified Β·
1 Parent(s): aa2dadf

Add main app with CogVideoX-5B I2V + ZeroGPU

Browse files
Files changed (1) hide show
  1. app.py +262 -0
app.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 🎬 Image-to-Video AI Studio β€” Real AI Animation
3
+ Uses CogVideoX-5B-I2V diffusion model to generate REAL animated videos from images.
4
+ Runs on HuggingFace ZeroGPU (free) β€” actual AI video generation, not zoom/warp tricks.
5
+ """
6
+
7
+ import spaces
8
+ import torch
9
+ import gradio as gr
10
+ import tempfile
11
+ import gc
12
+ from PIL import Image
13
+ from diffusers import CogVideoXImageToVideoPipeline
14
+ from diffusers.utils import export_to_video, load_image
15
+
16
+ # ─── Model Loading (CPU at startup, GPU inside @spaces.GPU) ─────────────────
17
+ print("πŸ“¦ Loading CogVideoX-5B-I2V pipeline to CPU...")
18
+ pipe = CogVideoXImageToVideoPipeline.from_pretrained(
19
+ "THUDM/CogVideoX-5b-I2V",
20
+ torch_dtype=torch.bfloat16,
21
+ )
22
+ print("βœ… Pipeline loaded to CPU successfully!")
23
+
24
+
25
+ # ─── Prompt Templates ────────────────────────────────────────────────────────
26
+ CAMERA_PROMPTS = {
27
+ "None (Auto)": "",
28
+ "Static Shot": "static camera, no camera movement, steady shot",
29
+ "Slow Zoom In": "camera slowly zooms in, push in shot",
30
+ "Slow Zoom Out": "camera slowly zooms out, pull back reveal",
31
+ "Pan Left": "camera pans slowly to the left, horizontal tracking",
32
+ "Pan Right": "camera pans slowly to the right, horizontal tracking",
33
+ "Tilt Up": "camera tilts upward slowly, revealing the sky",
34
+ "Tilt Down": "camera tilts downward slowly",
35
+ "Orbit Shot": "camera orbits around the subject slowly",
36
+ "Dolly Forward": "camera moves forward smoothly, dolly shot",
37
+ "Crane Up": "camera rises upward, crane shot, aerial movement",
38
+ "Handheld": "slight handheld camera movement, natural sway",
39
+ }
40
+
41
+ STYLE_PROMPTS = {
42
+ "Cinematic": "cinematic lighting, film grain, dramatic, movie quality, 4K",
43
+ "Realistic": "photorealistic, natural lighting, high detail, sharp focus",
44
+ "Dreamy": "soft focus, ethereal glow, dreamy atmosphere, gentle lighting",
45
+ "Dynamic": "fast motion, energetic, vibrant, dynamic movement",
46
+ "Slow Motion": "slow motion, graceful movement, smooth, elegant",
47
+ "Nature Documentary": "nature documentary style, wildlife, natural beauty, BBC quality",
48
+ "Anime / Artistic": "anime style, artistic, vibrant colors, stylized movement",
49
+ }
50
+
51
+ DURATION_FRAMES = {
52
+ "~3 seconds (24 frames)": 24,
53
+ "~6 seconds (49 frames)": 49,
54
+ }
55
+
56
+
57
+ # ─── Core Video Generation ───────────────────────────────────────────────────
58
+ @spaces.GPU(duration=300)
59
+ def generate_video(
60
+ image,
61
+ prompt,
62
+ camera_motion,
63
+ style,
64
+ duration,
65
+ num_inference_steps,
66
+ guidance_scale,
67
+ seed,
68
+ use_random_seed,
69
+ progress=gr.Progress(track_tqdm=True),
70
+ ):
71
+ """Generate real animated video using CogVideoX-5B-I2V diffusion model."""
72
+
73
+ if image is None:
74
+ raise gr.Error("⚠️ Please upload an image first!")
75
+
76
+ if not prompt or prompt.strip() == "":
77
+ raise gr.Error("⚠️ Please describe what animation you want!")
78
+
79
+ # Move pipeline to GPU
80
+ pipe.to("cuda")
81
+ pipe.vae.enable_tiling()
82
+ pipe.vae.enable_slicing()
83
+
84
+ # Build the full prompt
85
+ parts = [prompt.strip()]
86
+ camera_desc = CAMERA_PROMPTS.get(camera_motion, "")
87
+ if camera_desc:
88
+ parts.append(camera_desc)
89
+ style_desc = STYLE_PROMPTS.get(style, "")
90
+ if style_desc:
91
+ parts.append(style_desc)
92
+ parts.append("high quality, detailed, smooth motion")
93
+ full_prompt = ". ".join(parts)
94
+
95
+ print(f"🎬 Prompt: {full_prompt}")
96
+
97
+ # Seed
98
+ if use_random_seed:
99
+ seed = torch.randint(0, 2**32, (1,)).item()
100
+ generator = torch.Generator(device="cuda").manual_seed(int(seed))
101
+
102
+ # Frames
103
+ num_frames = DURATION_FRAMES.get(duration, 49)
104
+
105
+ # Resize image (CogVideoX native: 720x480 landscape, 480x720 portrait)
106
+ if isinstance(image, str):
107
+ image = load_image(image)
108
+ img_w, img_h = image.size
109
+ if img_w >= img_h:
110
+ target_w, target_h = 720, 480
111
+ else:
112
+ target_w, target_h = 480, 720
113
+ image_resized = image.resize((target_w, target_h), Image.LANCZOS)
114
+
115
+ # Generate
116
+ print(f"πŸš€ Generating: {num_frames} frames, {num_inference_steps} steps")
117
+ result = pipe(
118
+ prompt=full_prompt,
119
+ image=image_resized,
120
+ num_videos_per_prompt=1,
121
+ num_inference_steps=int(num_inference_steps),
122
+ num_frames=num_frames,
123
+ guidance_scale=float(guidance_scale),
124
+ generator=generator,
125
+ ).frames[0]
126
+
127
+ # Export to MP4
128
+ out_path = tempfile.mktemp(suffix=".mp4")
129
+ export_to_video(result, out_path, fps=8)
130
+
131
+ # Cleanup
132
+ pipe.to("cpu")
133
+ gc.collect()
134
+ torch.cuda.empty_cache()
135
+
136
+ print(f"βœ… Video saved: {out_path}")
137
+ return out_path, f"🎲 Seed: {seed} | Frames: {num_frames} | Steps: {num_inference_steps}"
138
+
139
+
140
+ # ─── Gradio UI ───────────────────────────────────────────────────────────────
141
+ CSS = """
142
+ .main-header { text-align: center; padding: 20px 0 10px 0; }
143
+ .main-header h1 {
144
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
145
+ -webkit-background-clip: text; -webkit-text-fill-color: transparent;
146
+ font-size: 2.2em; margin-bottom: 5px;
147
+ }
148
+ .note-box {
149
+ background: linear-gradient(135deg, #fff3cd 0%, #ffeeba 100%);
150
+ border-left: 4px solid #ffc107; border-radius: 8px;
151
+ padding: 12px 16px; margin: 10px 0;
152
+ }
153
+ .info-box {
154
+ background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
155
+ border-radius: 10px; padding: 15px; margin: 10px 0;
156
+ }
157
+ footer { display: none !important; }
158
+ """
159
+
160
+ with gr.Blocks(title="🎬 Image-to-Video AI") as demo:
161
+
162
+ gr.HTML("""
163
+ <div class="main-header">
164
+ <h1>🎬 Image-to-Video AI</h1>
165
+ <p style="color: #666; font-size: 1.15em;">
166
+ Transform any image into a <b>real animated video</b> with AI
167
+ </p>
168
+ <p style="color: #999; font-size: 0.85em;">
169
+ CogVideoX-5B Β· Free ZeroGPU Β· Real Diffusion Animation
170
+ </p>
171
+ </div>
172
+ """)
173
+
174
+ gr.HTML("""
175
+ <div class="note-box">
176
+ ⚑ <b>Real AI Animation:</b> This uses a 5-billion parameter diffusion model to generate
177
+ <b>actual new video frames</b> β€” not zoom/pan tricks. Water flows, hair blows,
178
+ people walk, clouds drift. Takes ~2-4 min per video on free GPU.
179
+ </div>
180
+ """)
181
+
182
+ with gr.Row():
183
+ with gr.Column(scale=1):
184
+ image_input = gr.Image(label="πŸ“Έ Upload Image", type="pil", height=320)
185
+
186
+ prompt_input = gr.Textbox(
187
+ label="✍️ Animation Prompt β€” describe what should move",
188
+ placeholder="e.g., 'The river flows gently, trees sway in the breeze, clouds drift across the sky'",
189
+ lines=3,
190
+ )
191
+
192
+ with gr.Row():
193
+ camera_motion = gr.Dropdown(
194
+ choices=list(CAMERA_PROMPTS.keys()),
195
+ value="None (Auto)", label="πŸŽ₯ Camera Motion",
196
+ )
197
+ style = gr.Dropdown(
198
+ choices=list(STYLE_PROMPTS.keys()),
199
+ value="Cinematic", label="🎭 Style",
200
+ )
201
+
202
+ duration = gr.Radio(
203
+ choices=list(DURATION_FRAMES.keys()),
204
+ value="~6 seconds (49 frames)", label="⏱️ Duration",
205
+ )
206
+
207
+ with gr.Accordion("βš™οΈ Advanced", open=False):
208
+ num_inference_steps = gr.Slider(
209
+ minimum=10, maximum=50, value=30, step=5,
210
+ label="πŸ”„ Steps (15=fast, 30=good, 50=best)",
211
+ )
212
+ guidance_scale = gr.Slider(
213
+ minimum=1.0, maximum=12.0, value=6.0, step=0.5,
214
+ label="🎯 Guidance Scale",
215
+ )
216
+ with gr.Row():
217
+ seed = gr.Number(label="🎲 Seed", value=42, precision=0)
218
+ use_random_seed = gr.Checkbox(label="Random", value=True)
219
+
220
+ generate_btn = gr.Button("🎬 Generate Video", variant="primary", size="lg")
221
+
222
+ with gr.Column(scale=1):
223
+ video_output = gr.Video(label="πŸŽ₯ Generated Video", autoplay=True, loop=True, height=420)
224
+ gen_info = gr.Textbox(label="Info", interactive=False)
225
+
226
+ gr.HTML("""
227
+ <div class="info-box">
228
+ <b>🧠 How it works:</b>
229
+ <ul style="margin: 5px 0; padding-left: 18px; color: #555;">
230
+ <li>CogVideoX-5B generates <b>real new video frames</b> using diffusion</li>
231
+ <li>Objects actually move β€” water, people, animals, particles</li>
232
+ <li>Your prompt controls <b>what</b> animates and <b>how</b></li>
233
+ <li>Camera motion and style are added to the AI prompt</li>
234
+ </ul>
235
+ <p style="color: #888; font-size: 0.85em; margin-top: 8px;">
236
+ <a href="https://huggingface.co/THUDM/CogVideoX-5b-I2V" target="_blank">CogVideoX-5B-I2V</a>
237
+ by Tsinghua University Β· ZeroGPU (Free A10G)
238
+ </p>
239
+ </div>
240
+ """)
241
+
242
+ generate_btn.click(
243
+ fn=generate_video,
244
+ inputs=[image_input, prompt_input, camera_motion, style, duration,
245
+ num_inference_steps, guidance_scale, seed, use_random_seed],
246
+ outputs=[video_output, gen_info],
247
+ )
248
+
249
+ gr.Markdown("### πŸ’‘ Example Prompts")
250
+ gr.Markdown("""
251
+ | Image Type | Example Prompt |
252
+ |-----------|---------------|
253
+ | 🏞️ Landscape | *"The river flows gently, clouds drift, trees sway in breeze"* |
254
+ | πŸ‘€ Portrait | *"She smiles and turns her head, hair flowing in the wind"* |
255
+ | 🌊 Ocean | *"Waves crash on shore, sea foam bubbles, seagulls fly"* |
256
+ | πŸ™οΈ City | *"Cars drive, pedestrians walk, city lights flicker"* |
257
+ | 🐾 Animals | *"The cat stretches, yawns, then walks forward"* |
258
+ | 🌸 Nature | *"Petals sway in breeze, butterfly lands on flower"* |
259
+ """)
260
+
261
+ if __name__ == "__main__":
262
+ demo.launch(css=CSS)