Files changed (3) hide show
  1. README.md +51 -6
  2. app.py +277 -54
  3. requirements.txt +11 -6
README.md CHANGED
@@ -1,8 +1,53 @@
1
  ---
2
- license: apache-2.0
3
- title: AI Movie Factory
4
- sdk: gradio
5
- emoji: ✨🎞
6
- colorFrom: blue
7
  colorTo: green
8
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: CogVideoX-2B
3
+ emoji: 🎥
4
+ colorFrom: yellow
 
 
5
  colorTo: green
6
+ sdk: gradio
7
+ sdk_version: 4.41.0
8
+ suggested_hardware: a10g-large
9
+ suggested_storage: large
10
+ app_port: 7860
11
+ app_file: app.py
12
+ models:
13
+ - THUDM/CogVideoX-2b
14
+ tags:
15
+ - cogvideox
16
+ - video-generation
17
+ - thudm
18
+ short_description: Text-to-Video
19
+ disable_embedding: false
20
+ ---
21
+
22
+ # CogVideoX HF Space
23
+
24
+ ## How to run this space
25
+
26
+ CogVideoX does not rely on any external API models.
27
+ However, during the training of CogVideoX, we used relatively long prompts. To enable users to achieve rendering with
28
+ shorter prompts, we integrated an LLM to refine the prompts for better results.
29
+ This step is not mandatory, but we recommend using an LLM to enhance the prompts.
30
+
31
+ ### Using with GLM-4 Model
32
+
33
+ ```shell
34
+ OPENAI_BASE_URL=https://open.bigmodel.cn/api/paas/v4/ OPENAI_API_KEY="ZHIPUAI_API_KEY" python gradio_demo.py
35
+ ```
36
+
37
+ ### Using with OpenAI GPT-4 Model
38
+
39
+ ```shell
40
+ OPENAI_API_KEY="OPENAI_API_KEY" python gradio_demo.py
41
+ ```
42
+
43
+ and change `app.py` here:
44
+
45
+ ```
46
+ model="glm-4-0520" # change to GPT-4o
47
+ ```
48
+
49
+ ### Not using LLM to refine prompts.
50
+
51
+ ```shell
52
+ python app.py
53
+ ```
app.py CHANGED
@@ -1,57 +1,280 @@
 
 
 
 
 
1
  import gradio as gr
2
- import moviepy.editor as mp
3
- from diffusers import DiffusionPipeline
 
 
 
 
4
  import spaces
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- # Load diffusion pipelines
7
- image_pipeline = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo")
8
- video_pipeline = DiffusionPipeline.from_pretrained("stabilityai/stable-video-diffusion-img2vid-xt")
9
-
10
- @spaces.GPU(duration=120)
11
- def generate_images(prompt, num_images):
12
- """Generates images using the image pipeline."""
13
- images = []
14
- for _ in range(num_images):
15
- generated_image = image_pipeline(prompt=prompt).images[0]
16
- images.append(generated_image)
17
- return images
18
-
19
- @spaces.GPU(duration=120)
20
- def generate_videos(images):
21
- """Generates videos from a list of images using the video pipeline."""
22
- videos = []
23
- for image in images:
24
- # Wrap the image in a list as expected by the pipeline
25
- generated_video = video_pipeline(images=[image]).images[0]
26
- videos.append(generated_video)
27
- return videos
28
-
29
- def combine_videos(video_clips):
30
- """Combines video clips into a single video using moviepy."""
31
- final_clip = mp.concatenate_videoclips(video_clips)
32
- return final_clip
33
-
34
- def generate(prompt):
35
- """Generates and combines images and videos."""
36
- images = generate_images(prompt, 2)
37
- video_clips = generate_videos(images)
38
- combined_video = combine_videos(video_clips)
39
- return combined_video
40
-
41
- # Gradio interface with improved formatting and video output
42
- interface = gr.Interface(
43
- fn=generate,
44
- inputs="text",
45
- outputs="video",
46
- title="AI Video Generation",
47
- description="Enter a prompt to generate a video using diffusion models.",
48
- css="""
49
- .output-video {
50
- width: 100%; /* Adjust width as needed */
51
- height: 400px; /* Adjust height as desired */
52
- }
53
- """,
54
- )
55
-
56
- # Launch the interface
57
- interface.launch()
 
1
+ import os
2
+ import tempfile
3
+ import threading
4
+ import time
5
+
6
  import gradio as gr
7
+ import numpy as np
8
+ import torch
9
+ import random
10
+ from diffusers import CogVideoXPipeline
11
+ from datetime import datetime, timedelta
12
+ from openai import OpenAI
13
  import spaces
14
+ import imageio
15
+ import moviepy.editor as mp
16
+ from typing import List, Union
17
+ import PIL
18
+
19
+ max_64_bit_int = np.iinfo(np.int32).max
20
+
21
+ dtype = torch.float16
22
+ device = "cuda" if torch.cuda.is_available() else "cpu"
23
+ pipe = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-2b", torch_dtype=dtype).to(device)
24
+
25
+ sys_prompt = """You are part of a team of bots that creates videos. You work with an assistant bot that will draw anything you say in square brackets.
26
+
27
+ For example , outputting " a beautiful morning in the woods with the sun peaking through the trees " will trigger your partner bot to output an video of a forest morning , as described. You will be prompted by people looking to create detailed , amazing videos. The way to accomplish this is to take their short prompts and make them extremely detailed and descriptive.
28
+ There are a few rules to follow:
29
+
30
+ You will only ever output a single video description per user request.
31
+
32
+ When modifications are requested , you should not simply make the description longer . You should refactor the entire description to integrate the suggestions.
33
+ Other times the user will not want modifications , but instead want a new image . In this case , you should ignore your previous conversation with the user.
34
+
35
+ Video descriptions must have the same num of words as examples below. Extra words will be ignored.
36
+ """
37
+
38
+
39
+ def export_to_video_imageio(
40
+ video_frames: Union[List[np.ndarray], List[PIL.Image.Image]], output_video_path: str = None, fps: int = 8
41
+ ) -> str:
42
+ """
43
+ Export the video frames to a video file using imageio lib to Avoid "green screen" issue (for example CogVideoX)
44
+ """
45
+ if output_video_path is None:
46
+ output_video_path = tempfile.NamedTemporaryFile(suffix=".mp4").name
47
+
48
+ if isinstance(video_frames[0], PIL.Image.Image):
49
+ video_frames = [np.array(frame) for frame in video_frames]
50
+
51
+ with imageio.get_writer(output_video_path, fps=fps) as writer:
52
+ for frame in video_frames:
53
+ writer.append_data(frame)
54
+
55
+ return output_video_path
56
+
57
+
58
+ def convert_prompt(prompt: str, retry_times: int = 3) -> str:
59
+ if not os.environ.get("OPENAI_API_KEY"):
60
+ return prompt
61
+ client = OpenAI()
62
+ text = prompt.strip()
63
+
64
+ for i in range(retry_times):
65
+ response = client.chat.completions.create(
66
+ messages=[
67
+ {"role": "system", "content": sys_prompt},
68
+ {"role": "user",
69
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "a girl is on the beach"'},
70
+ {"role": "assistant",
71
+ "content": "A radiant woman stands on a deserted beach, arms outstretched, wearing a beige trench coat, white blouse, light blue jeans, and chic boots, against a backdrop of soft sky and sea. Moments later, she is seen mid-twirl, arms exuberant, with the lighting suggesting dawn or dusk. Then, she runs along the beach, her attire complemented by an off-white scarf and black ankle boots, the tranquil sea behind her. Finally, she holds a paper airplane, her pose reflecting joy and freedom, with the ocean's gentle waves and the sky's soft pastel hues enhancing the serene ambiance."},
72
+ {"role": "user",
73
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "A man jogging on a football field"'},
74
+ {"role": "assistant",
75
+ "content": "A determined man in athletic attire, including a blue long-sleeve shirt, black shorts, and blue socks, jogs around a snow-covered soccer field, showcasing his solitary exercise in a quiet, overcast setting. His long dreadlocks, focused expression, and the serene winter backdrop highlight his dedication to fitness. As he moves, his attire, consisting of a blue sports sweatshirt, black athletic pants, gloves, and sneakers, grips the snowy ground. He is seen running past a chain-link fence enclosing the playground area, with a basketball hoop and children's slide, suggesting a moment of solitary exercise amidst the empty field."},
76
+ {"role": "user",
77
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : " A woman is dancing, HD footage, close-up"'},
78
+ {"role": "assistant",
79
+ "content": "A young woman with her hair in an updo and wearing a teal hoodie stands against a light backdrop, initially looking over her shoulder with a contemplative expression. She then confidently makes a subtle dance move, suggesting rhythm and movement. Next, she appears poised and focused, looking directly at the camera. Her expression shifts to one of introspection as she gazes downward slightly. Finally, she dances with confidence, her left hand over her heart, symbolizing a poignant moment, all while dressed in the same teal hoodie against a plain, light-colored background."},
80
+ {"role": "user",
81
+ "content": f'Create an imaginative video descriptive caption or modify an earlier caption in ENGLISH for the user input: "{text}"'},
82
+ ],
83
+ model="glm-4-0520",
84
+ temperature=0.01,
85
+ top_p=0.7,
86
+ stream=False,
87
+ max_tokens=250,
88
+ )
89
+ if response.choices:
90
+ return response.choices[0].message.content
91
+ return prompt
92
+
93
+
94
+ @spaces.GPU(duration=240)
95
+ def infer(
96
+ prompt: str,
97
+ negative_prompt: str,
98
+ num_inference_steps: int,
99
+ guidance_scale: float,
100
+ progress=gr.Progress(track_tqdm=True)
101
+ ):
102
+ torch.cuda.empty_cache()
103
+
104
+ prompt_embeds, _ = pipe.encode_prompt(
105
+ prompt=prompt,
106
+ negative_prompt=negative_prompt,
107
+ do_classifier_free_guidance=True,
108
+ num_videos_per_prompt=1,
109
+ max_sequence_length=226,
110
+ device=device,
111
+ dtype=dtype,
112
+ )
113
+
114
+ video = pipe(
115
+ num_inference_steps=num_inference_steps,
116
+ guidance_scale=guidance_scale,
117
+ prompt_embeds=prompt_embeds,
118
+ negative_prompt_embeds=torch.zeros_like(prompt_embeds),
119
+ ).frames[0]
120
+
121
+
122
+ return video
123
+
124
+
125
+ def save_video(tensor, fps):
126
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
127
+ video_path = f"./output/{timestamp}.mp4"
128
+ os.makedirs(os.path.dirname(video_path), exist_ok=True)
129
+ export_to_video_imageio(tensor[1:], video_path, fps)
130
+ return video_path
131
+
132
+ def convert_to_gif(video_path, fps):
133
+ clip = mp.VideoFileClip(video_path)
134
+ clip = clip.set_fps(fps)
135
+ clip = clip.resize(height=240)
136
+ gif_path = video_path.replace('.mp4', '.gif')
137
+ clip.write_gif(gif_path, fps=fps)
138
+ return gif_path
139
+
140
+
141
+ def delete_old_files():
142
+ while True:
143
+ now = datetime.now()
144
+ cutoff = now - timedelta(minutes=10)
145
+ output_dir = './output'
146
+ for filename in os.listdir(output_dir):
147
+ file_path = os.path.join(output_dir, filename)
148
+ if os.path.isfile(file_path):
149
+ file_mtime = datetime.fromtimestamp(os.path.getmtime(file_path))
150
+ if file_mtime < cutoff:
151
+ os.remove(file_path)
152
+ time.sleep(600) # Sleep for 10 minutes
153
+
154
+
155
+ threading.Thread(target=delete_old_files, daemon=True).start()
156
+
157
+ with gr.Blocks() as demo:
158
+ gr.Markdown("""
159
+ <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 10px;">
160
+ CogVideoX-2B
161
+ </div>
162
+ <div style="text-align: center; margin-bottom: 20px;">
163
+ Generates a 720x480 video of 50 frames based on your description
164
+ </div>
165
+ <div style="text-align: center;">
166
+ <a href="https://huggingface.co/THUDM/CogVideoX-2b">🤗 Model Hub</a> |
167
+ <a href="https://github.com/THUDM/CogVideo">🌐 Github</a> |
168
+ <a href="https://arxiv.org/pdf/2408.06072">📜 arxiv </a>
169
+ </div>
170
+
171
+ <div style="text-align: center; font-size: 15px; font-weight: bold; color: red; margin-bottom: 20px;">
172
+ ⚠️ This demo is for academic research and experiential use only.
173
+ Users should strictly adhere to local laws and ethics.
174
+ </div>
175
+ """)
176
+ with gr.Row():
177
+ with gr.Column():
178
+ prompt = gr.Textbox(label="Prompt (less than 200 words)", placeholder="Enter your prompt here", lines=5)
179
+ with gr.Row():
180
+ gr.Markdown(
181
+ "✨Upon pressing the enhanced prompt button, we will use [GLM-4 Model](https://github.com/THUDM/GLM-4) to polish the prompt and overwrite the original one.")
182
+ enhance_button = gr.Button("✨ Enhance Prompt (optional)")
183
+
184
+ with gr.Accordion("Advanced options", open=False):
185
+ negative_prompt = gr.Textbox(label="Negative prompt",
186
+ info="Disambiguate by listing what the video does NOT represent",
187
+ value='blurring, aliasing, unsharp, weird textures, ugly, dirty, messy, '
188
+ 'worst quality, low quality, frames, watermark, signature, jpeg artifacts, '
189
+ 'deformed, lowres, over-smooth',
190
+ lines=5)
191
+ fps = gr.Slider(label="Frames per second", info="Do not alter the frame generation", value=8, minimum=5, maximum=30)
192
+ num_inference_steps = gr.Number(label="Inference Steps", info = "lower=fast generation, higher=detailed video; 50 steps are recommended for most cases; will cause 120 seconds for inference", value=50, minimum=1)
193
+ guidance_scale = gr.Number(label="Guidance Scale", info = "lower=video quality, higher=follow the prompt; default is highly recommended", value=6.0)
194
+ randomize_seed = gr.Checkbox(label = "\U0001F3B2 Randomize seed", value = True, info = "If checked, result is always different")
195
+ seed = gr.Slider(minimum = 0, maximum = max_64_bit_int, step = 1, randomize = True, label = "Seed")
196
+ generate_button = gr.Button("🎬 Generate Video", variant="primary")
197
+
198
+ with gr.Column():
199
+ video_output = gr.Video(label="Generated video", width=720, height=480, autoplay=True)
200
+ with gr.Row():
201
+ download_video_button = gr.File(label="📥 Download Video", visible=False)
202
+ download_gif_button = gr.File(label="📥 Download GIF", visible=False)
203
+
204
+ gr.Markdown("""
205
+ <table border="1" style="width: 100%; text-align: left; margin-top: 20px;">
206
+ <tr>
207
+ <th>Prompt</th>
208
+ <th>Video URL</th>
209
+ <th>Inference Steps</th>
210
+ <th>Guidance Scale</th>
211
+ </tr>
212
+ <tr>
213
+ <td>A detailed wooden toy ship with intricately carved masts and sails is seen gliding smoothly over a plush, blue carpet that mimics the waves of the sea. The ship's hull is painted a rich brown, with tiny windows. The carpet, soft and textured, provides a perfect backdrop, resembling an oceanic expanse. Surrounding the ship are various other toys and children's items, hinting at a playful environment. The scene captures the innocence and imagination of childhood, with the toy ship's journey symbolizing endless adventures in a whimsical, indoor setting.</td>
214
+ <td><a href="https://github.com/THUDM/CogVideo/raw/main/resources/videos/1.mp4">Video 1</a></td>
215
+ <td>50</td>
216
+ <td>6</td>
217
+ </tr>
218
+ <tr>
219
+ <td>The camera follows behind a white vintage SUV with a black roof rack as it speeds up a steep dirt road surrounded by pine trees on a steep mountain slope, dust kicks up from it’s tires, the sunlight shines on the SUV as it speeds along the dirt road, casting a warm glow over the scene. The dirt road curves gently into the distance, with no other cars or vehicles in sight. The trees on either side of the road are redwoods, with patches of greenery scattered throughout. The car is seen from the rear following the curve with ease, making it seem as if it is on a rugged drive through the rugged terrain. The dirt road itself is surrounded by steep hills and mountains, with a clear blue sky above with wispy clouds.</td>
220
+ <td><a href="https://github.com/THUDM/CogVideo/raw/main/resources/videos/2.mp4">Video 2</a></td>
221
+ <td>50</td>
222
+ <td>6</td>
223
+ </tr>
224
+ <tr>
225
+ <td>A street artist, clad in a worn-out denim jacket and a colorful bandana, stands before a vast concrete wall in the heart, holding a can of spray paint, spray-painting a colorful bird on a mottled wall.</td>
226
+ <td><a href="https://github.com/THUDM/CogVideo/raw/main/resources/videos/3.mp4">Video 3</a></td>
227
+ <td>50</td>
228
+ <td>6</td>
229
+ </tr>
230
+ <tr>
231
+ <td>In the haunting backdrop of a war-torn city, where ruins and crumbled walls tell a story of devastation, a poignant close-up frames a young girl. Her face is smudged with ash, a silent testament to the chaos around her. Her eyes glistening with a mix of sorrow and resilience, capturing the raw emotion of a world that has lost its innocence to the ravages of conflict.</td>
232
+ <td><a href="https://github.com/THUDM/CogVideo/raw/main/resources/videos/4.mp4">Video 4</a></td>
233
+ <td>50</td>
234
+ <td>6</td>
235
+ </tr>
236
+ </table>
237
+ """)
238
+
239
+ def update_seed(is_randomize_seed, seed):
240
+ if is_randomize_seed:
241
+ return random.randint(0, max_64_bit_int)
242
+ return seed
243
+
244
+
245
+ def generate(prompt, negative_prompt, num_inference_steps, guidance_scale, fps, seed, progress=gr.Progress(track_tqdm=True)):
246
+ random.seed(seed)
247
+ torch.manual_seed(seed)
248
+
249
+ tensor = infer(prompt, negative_prompt, num_inference_steps, guidance_scale, progress=progress)
250
+ video_path = save_video(tensor, fps)
251
+ video_update = gr.update(visible=True, value=video_path)
252
+ gif_path = convert_to_gif(video_path, fps)
253
+ gif_update = gr.update(visible=True, value=gif_path)
254
+
255
+ return video_path, video_update, gif_update
256
+
257
+
258
+ def enhance_prompt_func(prompt):
259
+ return convert_prompt(prompt, retry_times=1)
260
+
261
+
262
+ generate_button.click(fn = update_seed, inputs = [
263
+ randomize_seed,
264
+ seed
265
+ ], outputs = [
266
+ seed
267
+ ], queue = False, show_progress = False).then(
268
+ generate,
269
+ inputs=[prompt, negative_prompt, num_inference_steps, guidance_scale, fps, seed],
270
+ outputs=[video_output, download_video_button, download_gif_button]
271
+ )
272
+
273
+ enhance_button.click(
274
+ enhance_prompt_func,
275
+ inputs=[prompt],
276
+ outputs=[prompt]
277
+ )
278
 
279
+ if __name__ == "__main__":
280
+ demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -1,6 +1,11 @@
1
- accelerate
2
- diffusers
3
- spaces
4
- transformers
5
- torch
6
- moviepy
 
 
 
 
 
 
1
+ gradio==4.41.0
2
+ imageio-ffmpeg==0.5.1
3
+ torch==2.2.0
4
+ git+https://github.com/huggingface/diffusers.git@main#egg=diffusers
5
+ transformers==4.42.0
6
+ spaces==0.29.2
7
+ moviepy==1.0.3
8
+ openai==1.40.3
9
+ git+https://github.com/huggingface/accelerate.git@main#egg=accelerate
10
+ sentencepiece==0.2.0
11
+ Pillow==9.5.0