svjack commited on
Commit
ff7fc6a
1 Parent(s): f14ca3c

Upload 6 files

Browse files
Files changed (3) hide show
  1. i2v_app_qm.py +431 -0
  2. t2v_app_qm.py +3 -3
  3. v2v_app_qm.py +443 -0
i2v_app_qm.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import math
3
+ import os
4
+ import random
5
+ import threading
6
+ import time
7
+ import cv2
8
+ import tempfile
9
+ import imageio_ffmpeg
10
+ import gradio as gr
11
+ import torch
12
+ from PIL import Image
13
+ from diffusers import (
14
+ CogVideoXPipeline,
15
+ CogVideoXDPMScheduler,
16
+ CogVideoXImageToVideoPipeline,
17
+ CogVideoXTransformer3DModel,
18
+ AutoencoderKLCogVideoX,
19
+ CogVideoXDDIMScheduler,
20
+ )
21
+ from diffusers.utils import load_video, load_image, export_to_video
22
+ from datetime import datetime, timedelta
23
+ from diffusers.image_processor import VaeImageProcessor
24
+ from openai import OpenAI
25
+ import moviepy.editor as mp
26
+ import utils
27
+ from rife_model import load_rife_model, rife_inference_with_latents
28
+ from huggingface_hub import hf_hub_download, snapshot_download
29
+ import gc
30
+ import torch._dynamo
31
+ from transformers import T5EncoderModel
32
+ from torchao.quantization import (
33
+ autoquant,
34
+ quantize_,
35
+ int8_weight_only,
36
+ int8_dynamic_activation_int8_weight,
37
+ int8_dynamic_activation_int4_weight,
38
+ int8_dynamic_activation_int8_semi_sparse_weight,
39
+ int4_weight_only,
40
+ float8_dynamic_activation_float8_weight,
41
+ float8_weight_only,
42
+ fpx_weight_only,
43
+ )
44
+ from torchao.quantization.quant_api import PerRow
45
+ from torchao.sparsity import sparsify_
46
+
47
+ os.environ["TORCH_LOGS"] = "+dynamo,output_code,graph_breaks,recompiles"
48
+ torch._dynamo.config.suppress_errors = True
49
+ torch.set_float32_matmul_precision("high")
50
+ torch._inductor.config.conv_1x1_as_mm = True
51
+ torch._inductor.config.coordinate_descent_tuning = True
52
+ torch._inductor.config.epilogue_fusion = False
53
+ torch._inductor.config.coordinate_descent_check_all_directions = True
54
+
55
+ # Set high precision for float32 matrix multiplications.
56
+ # This setting optimizes performance on NVIDIA GPUs with Ampere architecture (e.g., A100, RTX 30 series) or newer.
57
+ torch.set_float32_matmul_precision("high")
58
+
59
+ CONVERT_DTYPE = {
60
+ "fp16": lambda module: module.to(dtype=torch.float16),
61
+ "bf16": lambda module: module.to(dtype=torch.bfloat16),
62
+ "fp8wo": lambda module: quantize_(module, float8_weight_only()),
63
+ "fp8dq": lambda module: quantize_(module, float8_dynamic_activation_float8_weight()),
64
+ "fp8dqrow": lambda module: quantize_(module, float8_dynamic_activation_float8_weight(granularity=PerRow())),
65
+ "fp6_e3m2": lambda module: quantize_(module, fpx_weight_only(3, 2)),
66
+ "fp5_e2m2": lambda module: quantize_(module, fpx_weight_only(2, 2)),
67
+ "fp4_e2m1": lambda module: quantize_(module, fpx_weight_only(2, 1)),
68
+ "int8wo": lambda module: quantize_(module, int8_weight_only()),
69
+ "int8dq": lambda module: quantize_(module, int8_dynamic_activation_int8_weight()),
70
+ "int4dq": lambda module: quantize_(module, int8_dynamic_activation_int4_weight()),
71
+ "int4wo": lambda module: quantize_(module, int4_weight_only()),
72
+ "autoquant": lambda module: autoquant(module, error_on_unseen=False),
73
+ "sparsify": lambda module: sparsify_(module, int8_dynamic_activation_int8_semi_sparse_weight()),
74
+ }
75
+
76
+ device = "cuda" if torch.cuda.is_available() else "cpu"
77
+
78
+ hf_hub_download(repo_id="ai-forever/Real-ESRGAN", filename="RealESRGAN_x4.pth", local_dir="model_real_esran")
79
+ snapshot_download(repo_id="AlexWortega/RIFE", local_dir="model_rife")
80
+
81
+ # 解析命令行参数
82
+ parser = argparse.ArgumentParser(description="Generate a video from an image using CogVideoX")
83
+ parser.add_argument("--quantization_scheme", type=str, default="fp8", choices=list(CONVERT_DTYPE.keys()), help="The quantization scheme to use")
84
+ parser.add_argument("--dtype", type=str, default="bfloat16", help="The data type for computation (e.g., 'float16', 'bfloat16')")
85
+ args = parser.parse_args()
86
+
87
+ quantization_scheme = args.quantization_scheme
88
+ dtype = torch.float16 if args.dtype == "float16" else torch.bfloat16
89
+
90
+ # 量化模型函数
91
+ def quantize_model(part, quantization_scheme):
92
+ if quantization_scheme in CONVERT_DTYPE:
93
+ return CONVERT_DTYPE[quantization_scheme](part)
94
+ else:
95
+ raise ValueError(f"Unsupported quantization scheme: {quantization_scheme}")
96
+
97
+ # 加载并量化模型组件
98
+ transformer = CogVideoXTransformer3DModel.from_pretrained("THUDM/CogVideoX-5b", subfolder="transformer", torch_dtype=dtype)
99
+ quantize_model(part=transformer, quantization_scheme=quantization_scheme)
100
+
101
+ # 加载并量化模型组件
102
+ text_encoder = T5EncoderModel.from_pretrained("THUDM/CogVideoX-5b-I2V", subfolder="text_encoder", torch_dtype=dtype)
103
+ quantize_model(part=text_encoder, quantization_scheme=quantization_scheme)
104
+ transformer = CogVideoXTransformer3DModel.from_pretrained("THUDM/CogVideoX-5b-I2V", subfolder="transformer", torch_dtype=dtype)
105
+ quantize_model(part=transformer, quantization_scheme=quantization_scheme)
106
+ vae = AutoencoderKLCogVideoX.from_pretrained("THUDM/CogVideoX-5b-I2V", subfolder="vae", torch_dtype=dtype)
107
+ quantize_model(part=vae, quantization_scheme=quantization_scheme)
108
+
109
+ # 初始化管道
110
+ #pipe = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-5b", text_encoder=text_encoder, transformer=transformer, vae=vae, torch_dtype=dtype)
111
+ #pipe.scheduler = CogVideoXDDIMScheduler.from_config(pipe.scheduler.config, timestep_spacing="trailing")
112
+
113
+ pipe_image = CogVideoXImageToVideoPipeline.from_pretrained(
114
+ "THUDM/CogVideoX-5b-I2V",
115
+ transformer=transformer,
116
+ vae=vae,
117
+ #scheduler=pipe.scheduler,
118
+ #tokenizer=pipe.tokenizer,
119
+ text_encoder=text_encoder,
120
+ torch_dtype=dtype
121
+ )
122
+
123
+ # 启用模型CPU卸载
124
+ pipe_image.enable_model_cpu_offload()
125
+
126
+ # 启用VAE切片和平铺
127
+ #pipe_image.vae.enable_slicing()
128
+ #pipe_image.vae.enable_tiling()
129
+
130
+
131
+ os.makedirs("./output", exist_ok=True)
132
+ os.makedirs("./gradio_tmp", exist_ok=True)
133
+
134
+ upscale_model = utils.load_sd_upscale("model_real_esran/RealESRGAN_x4.pth", device)
135
+ frame_interpolation_model = load_rife_model("model_rife")
136
+
137
+ 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.
138
+ 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.
139
+ There are a few rules to follow:
140
+ You will only ever output a single video description per user request.
141
+ When modifications are requested , you should not simply make the description longer . You should refactor the entire description to integrate the suggestions.
142
+ 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.
143
+ Video descriptions must have the same num of words as examples below. Extra words will be ignored.
144
+ """
145
+
146
+ def convert_prompt(prompt: str, retry_times: int = 3) -> str:
147
+ if not os.environ.get("OPENAI_API_KEY"):
148
+ return prompt
149
+ client = OpenAI()
150
+ text = prompt.strip()
151
+
152
+ for i in range(retry_times):
153
+ response = client.chat.completions.create(
154
+ messages=[
155
+ {"role": "system", "content": sys_prompt},
156
+ {
157
+ "role": "user",
158
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "a girl is on the beach"',
159
+ },
160
+ {
161
+ "role": "assistant",
162
+ "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.",
163
+ },
164
+ {
165
+ "role": "user",
166
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "A man jogging on a football field"',
167
+ },
168
+ {
169
+ "role": "assistant",
170
+ "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.",
171
+ },
172
+ {
173
+ "role": "user",
174
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : " A woman is dancing, HD footage, close-up"',
175
+ },
176
+ {
177
+ "role": "assistant",
178
+ "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.",
179
+ },
180
+ {
181
+ "role": "user",
182
+ "content": f'Create an imaginative video descriptive caption or modify an earlier caption in ENGLISH for the user input: "{text}"',
183
+ },
184
+ ],
185
+ model="glm-4-plus",
186
+ temperature=0.01,
187
+ top_p=0.7,
188
+ stream=False,
189
+ max_tokens=200,
190
+ )
191
+ if response.choices:
192
+ return response.choices[0].message.content
193
+ return prompt
194
+
195
+ def infer(
196
+ prompt: str,
197
+ image_input: str,
198
+ seed: int = -1,
199
+ progress=gr.Progress(track_tqdm=True),
200
+ ):
201
+ if seed == -1:
202
+ seed = random.randint(0, 2**8 - 1)
203
+ #print("image input in infer :")
204
+ #print(image_input)
205
+ image_input = Image.fromarray(image_input).resize(size=(720, 480)) # Convert to PIL
206
+ #print("fa :")
207
+ #print(image_input)
208
+ image = load_image(image_input)
209
+ #print("image :")
210
+ #print(image)
211
+ video_pt = pipe_image(
212
+ image=image,
213
+ prompt=prompt,
214
+ num_inference_steps=50,
215
+ num_videos_per_prompt=1,
216
+ use_dynamic_cfg=True,
217
+ output_type="pt",
218
+ guidance_scale=7.0,
219
+ generator=torch.Generator(device="cuda").manual_seed(seed),
220
+ ).frames
221
+ #pipe_image.to("cpu")
222
+ gc.collect()
223
+ torch.cuda.empty_cache()
224
+ return (video_pt, seed)
225
+
226
+ def convert_to_gif(video_path):
227
+ clip = mp.VideoFileClip(video_path)
228
+ clip = clip.set_fps(8)
229
+ clip = clip.resize(height=240)
230
+ gif_path = video_path.replace(".mp4", ".gif")
231
+ clip.write_gif(gif_path, fps=8)
232
+ return gif_path
233
+
234
+ def delete_old_files():
235
+ while True:
236
+ now = datetime.now()
237
+ cutoff = now - timedelta(minutes=10)
238
+ directories = ["./output", "./gradio_tmp"]
239
+
240
+ for directory in directories:
241
+ for filename in os.listdir(directory):
242
+ file_path = os.path.join(directory, filename)
243
+ if os.path.isfile(file_path):
244
+ file_mtime = datetime.fromtimestamp(os.path.getmtime(file_path))
245
+ if file_mtime < cutoff:
246
+ os.remove(file_path)
247
+ time.sleep(600)
248
+
249
+ threading.Thread(target=delete_old_files, daemon=True).start()
250
+
251
+ with gr.Blocks() as demo:
252
+ gr.Markdown("""
253
+ <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
254
+ CogVideoX-5B Huggingface Space🤗
255
+ </div>
256
+ <div style="text-align: center;">
257
+ <a href="https://huggingface.co/THUDM/CogVideoX-5B">🤗 5B(T2V) Model Hub</a> |
258
+ <a href="https://huggingface.co/THUDM/CogVideoX-5B-I2V">🤗 5B(I2V) Model Hub</a> |
259
+ <a href="https://github.com/THUDM/CogVideo">🌐 Github</a> |
260
+ <a href="https://arxiv.org/pdf/2408.06072">📜 arxiv </a>
261
+ </div>
262
+ <div style="text-align: center;display: flex;justify-content: center;align-items: center;margin-top: 1em;margin-bottom: .5em;">
263
+ <span>If the Space is too busy, duplicate it to use privately</span>
264
+ <a href="https://huggingface.co/spaces/THUDM/CogVideoX-5B-Space?duplicate=true"><img src="https://huggingface.co/datasets/huggingface/badges/resolve/main/duplicate-this-space-lg.svg" width="160" style="
265
+ margin-left: .75em;
266
+ "></a>
267
+ </div>
268
+ <div style="text-align: center; font-size: 15px; font-weight: bold; color: red; margin-bottom: 20px;">
269
+ ⚠️ This demo is for academic research and experiential use only.
270
+ </div>
271
+ """)
272
+ with gr.Row():
273
+ with gr.Column():
274
+ with gr.Accordion("I2V: Image Input (cannot be used simultaneously with video input)", open=False):
275
+ image_input = gr.Image(label="Input Image (will be cropped to 720 * 480)")
276
+ prompt = gr.Textbox(label="Prompt (Less than 200 Words)", placeholder="Enter your prompt here", lines=5)
277
+
278
+ with gr.Row():
279
+ gr.Markdown(
280
+ "✨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."
281
+ )
282
+ enhance_button = gr.Button("✨ Enhance Prompt(Optional)")
283
+ with gr.Group():
284
+ with gr.Column():
285
+ with gr.Row():
286
+ seed_param = gr.Number(
287
+ label="Inference Seed (Enter a positive number, -1 for random)", value=-1
288
+ )
289
+ with gr.Row():
290
+ enable_scale = gr.Checkbox(label="Super-Resolution (720 × 480 -> 2880 × 1920)", value=False)
291
+ enable_rife = gr.Checkbox(label="Frame Interpolation (8fps -> 16fps)", value=False)
292
+ gr.Markdown(
293
+ "✨In this demo, we use [RIFE](https://github.com/hzwer/ECCV2022-RIFE) for frame interpolation and [Real-ESRGAN](https://github.com/xinntao/Real-ESRGAN) for upscaling(Super-Resolution).<br>&nbsp;&nbsp;&nbsp;&nbsp;The entire process is based on open-source solutions."
294
+ )
295
+
296
+ generate_button = gr.Button("🎬 Generate Video")
297
+
298
+ with gr.Column():
299
+ video_output = gr.Video(label="CogVideoX Generate Video", width=720, height=480)
300
+ with gr.Row():
301
+ download_video_button = gr.File(label="📥 Download Video", visible=False)
302
+ download_gif_button = gr.File(label="📥 Download GIF", visible=False)
303
+ seed_text = gr.Number(label="Seed Used for Video Generation", visible=False)
304
+
305
+ gr.Markdown("""
306
+ <table border="0" style="width: 100%; text-align: left; margin-top: 20px;">
307
+ <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
308
+ 🎥 Video Gallery
309
+ </div>
310
+ <tr>
311
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
312
+ <p>A garden comes to life as a kaleidoscope of butterflies flutters amidst the blossoms, their delicate wings casting shadows on the petals below. In the background, a grand fountain cascades water with a gentle splendor, its rhythmic sound providing a soothing backdrop. Beneath the cool shade of a mature tree, a solitary wooden chair invites solitude and reflection, its smooth surface worn by the touch of countless visitors seeking a moment of tranquility in nature's embrace.</p>
313
+ </td>
314
+ <td style="width: 25%; vertical-align: top;">
315
+ <video src="https://github.com/user-attachments/assets/cf5953ea-96d3-48fd-9907-c4708752c714" width="100%" controls autoplay loop></video>
316
+ </td>
317
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
318
+ <p>A small boy, head bowed and determination etched on his face, sprints through the torrential downpour as lightning crackles and thunder rumbles in the distance. The relentless rain pounds the ground, creating a chaotic dance of water droplets that mirror the dramatic sky's anger. In the far background, the silhouette of a cozy home beckons, a faint beacon of safety and warmth amidst the fierce weather. The scene is one of perseverance and the unyielding spirit of a child braving the elements.</p>
319
+ </td>
320
+ <td style="width: 25%; vertical-align: top;">
321
+ <video src="https://github.com/user-attachments/assets/fe0a78e6-b669-4800-8cf0-b5f9b5145b52" width="100%" controls autoplay loop></video>
322
+ </td>
323
+ </tr>
324
+ <tr>
325
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
326
+ <p>A suited astronaut, with the red dust of Mars clinging to their boots, reaches out to shake hands with an alien being, their skin a shimmering blue, under the pink-tinged sky of the fourth planet. In the background, a sleek silver rocket, a beacon of human ingenuity, stands tall, its engines powered down, as the two representatives of different worlds exchange a historic greeting amidst the desolate beauty of the Martian landscape.</p>
327
+ </td>
328
+ <td style="width: 25%; vertical-align: top;">
329
+ <video src="https://github.com/user-attachments/assets/c182f606-8f8c-421d-b414-8487070fcfcb" width="100%" controls autoplay loop></video>
330
+ </td>
331
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
332
+ <p>An elderly gentleman, with a serene expression, sits at the water's edge, a steaming cup of tea by his side. He is engrossed in his artwork, brush in hand, as he renders an oil painting on a canvas that's propped up against a small, weathered table. The sea breeze whispers through his silver hair, gently billowing his loose-fitting white shirt, while the salty air adds an intangible element to his masterpiece in progress. The scene is one of tranquility and inspiration, with the artist's canvas capturing the vibrant hues of the setting sun reflecting off the tranquil sea.</p>
333
+ </td>
334
+ <td style="width: 25%; vertical-align: top;">
335
+ <video src="https://github.com/user-attachments/assets/7db2bbce-194d-434d-a605-350254b6c298" width="100%" controls autoplay loop></video>
336
+ </td>
337
+ </tr>
338
+ <tr>
339
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
340
+ <p>In a dimly lit bar, purplish light bathes the face of a mature man, his eyes blinking thoughtfully as he ponders in close-up, the background artfully blurred to focus on his introspective expression, the ambiance of the bar a mere suggestion of shadows and soft lighting.</p>
341
+ </td>
342
+ <td style="width: 25%; vertical-align: top;">
343
+ <video src="https://github.com/user-attachments/assets/62b01046-8cab-44cc-bd45-4d965bb615ec" width="100%" controls autoplay loop></video>
344
+ </td>
345
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
346
+ <p>A golden retriever, sporting sleek black sunglasses, with its lengthy fur flowing in the breeze, sprints playfully across a rooftop terrace, recently refreshed by a light rain. The scene unfolds from a distance, the dog's energetic bounds growing larger as it approaches the camera, its tail wagging with unrestrained joy, while droplets of water glisten on the concrete behind it. The overcast sky provides a dramatic backdrop, emphasizing the vibrant golden coat of the canine as it dashes towards the viewer.</p>
347
+ </td>
348
+ <td style="width: 25%; vertical-align: top;">
349
+ <video src="https://github.com/user-attachments/assets/d78e552a-4b3f-4b81-ac3f-3898079554f6" width="100%" controls autoplay loop></video>
350
+ </td>
351
+ </tr>
352
+ <tr>
353
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
354
+ <p>On a brilliant sunny day, the lakeshore is lined with an array of willow trees, their slender branches swaying gently in the soft breeze. The tranquil surface of the lake reflects the clear blue sky, while several elegant swans glide gracefully through the still water, leaving behind delicate ripples that disturb the mirror-like quality of the lake. The scene is one of serene beauty, with the willows' greenery providing a picturesque frame for the peaceful avian visitors.</p>
355
+ </td>
356
+ <td style="width: 25%; vertical-align: top;">
357
+ <video src="https://github.com/user-attachments/assets/30894f12-c741-44a2-9e6e-ddcacc231e5b" width="100%" controls autoplay loop></video>
358
+ </td>
359
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
360
+ <p>A Chinese mother, draped in a soft, pastel-colored robe, gently rocks back and forth in a cozy rocking chair positioned in the tranquil setting of a nursery. The dimly lit bedroom is adorned with whimsical mobiles dangling from the ceiling, casting shadows that dance on the walls. Her baby, swaddled in a delicate, patterned blanket, rests against her chest, the child's earlier cries now replaced by contented coos as the mother's soothing voice lulls the little one to sleep. The scent of lavender fills the air, adding to the serene atmosphere, while a warm, orange glow from a nearby nightlight illuminates the scene with a gentle hue, capturing a moment of tender love and comfort.</p>
361
+ </td>
362
+ <td style="width: 25%; vertical-align: top;">
363
+ <video src="https://github.com/user-attachments/assets/926575ca-7150-435b-a0ff-4900a963297b" width="100%" controls autoplay loop></video>
364
+ </td>
365
+ </tr>
366
+ </table>
367
+ """)
368
+
369
+ def generate(
370
+ prompt,
371
+ image_input,
372
+ seed_value,
373
+ scale_status,
374
+ rife_status,
375
+ progress=gr.Progress(track_tqdm=True)
376
+ ):
377
+ latents, seed = infer(
378
+ prompt,
379
+ image_input,
380
+ seed=seed_value,
381
+ progress=progress,
382
+ )
383
+ if scale_status:
384
+ latents = utils.upscale_batch_and_concatenate(upscale_model, latents, device)
385
+ if rife_status:
386
+ latents = rife_inference_with_latents(frame_interpolation_model, latents)
387
+
388
+ batch_size = latents.shape[0]
389
+ batch_video_frames = []
390
+ for batch_idx in range(batch_size):
391
+ pt_image = latents[batch_idx]
392
+ pt_image = torch.stack([pt_image[i] for i in range(pt_image.shape[0])])
393
+
394
+ image_np = VaeImageProcessor.pt_to_numpy(pt_image)
395
+ image_pil = VaeImageProcessor.numpy_to_pil(image_np)
396
+ batch_video_frames.append(image_pil)
397
+
398
+ video_path = utils.save_video(batch_video_frames[0], fps=math.ceil((len(batch_video_frames[0]) - 1) / 6))
399
+ video_update = gr.update(visible=True, value=video_path)
400
+ gif_path = convert_to_gif(video_path)
401
+ gif_update = gr.update(visible=True, value=gif_path)
402
+ seed_update = gr.update(visible=True, value=seed)
403
+
404
+ return video_path, video_update, gif_update, seed_update
405
+
406
+ def enhance_prompt_func(prompt):
407
+ return convert_prompt(prompt, retry_times=1)
408
+
409
+ generate_button.click(
410
+ generate,
411
+ inputs=[prompt, image_input, seed_param, enable_scale, enable_rife],
412
+ outputs=[video_output, download_video_button, download_gif_button, seed_text],
413
+ )
414
+
415
+ enhance_button.click(enhance_prompt_func, inputs=[prompt], outputs=[prompt])
416
+
417
+ demo.queue(max_size=15)
418
+ demo.launch(share=True)
419
+
420
+ '''
421
+ https://github.com/THUDM/CogVideo/issues/245
422
+ torch>=2.5.0
423
+ torchao==0.5
424
+
425
+ don't use float16, should use bfloat16
426
+
427
+ python i2v_app_qm.py --quantization_scheme int8wo --dtype bfloat16
428
+ python i2v_app_qm.py --quantization_scheme fp8wo --dtype bfloat16
429
+ python i2v_app_qm.py --quantization_scheme bf16 --dtype bfloat16
430
+ python i2v_app_qm.py --quantization_scheme fp16 --dtype float16
431
+ '''
t2v_app_qm.py CHANGED
@@ -97,11 +97,11 @@ def quantize_model(part, quantization_scheme):
97
 
98
  # 加载并量化模型组件
99
  text_encoder = T5EncoderModel.from_pretrained("THUDM/CogVideoX-5b", subfolder="text_encoder", torch_dtype=dtype)
100
- text_encoder = quantize_model(part=text_encoder, quantization_scheme=quantization_scheme)
101
  transformer = CogVideoXTransformer3DModel.from_pretrained("THUDM/CogVideoX-5b", subfolder="transformer", torch_dtype=dtype)
102
- transformer = quantize_model(part=transformer, quantization_scheme=quantization_scheme)
103
  vae = AutoencoderKLCogVideoX.from_pretrained("THUDM/CogVideoX-5b", subfolder="vae", torch_dtype=dtype)
104
- vae = quantize_model(part=vae, quantization_scheme=quantization_scheme)
105
 
106
  # 初始化管道
107
  pipe = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-5b", text_encoder=text_encoder, transformer=transformer, vae=vae, torch_dtype=dtype)
 
97
 
98
  # 加载并量化模型组件
99
  text_encoder = T5EncoderModel.from_pretrained("THUDM/CogVideoX-5b", subfolder="text_encoder", torch_dtype=dtype)
100
+ quantize_model(part=text_encoder, quantization_scheme=quantization_scheme)
101
  transformer = CogVideoXTransformer3DModel.from_pretrained("THUDM/CogVideoX-5b", subfolder="transformer", torch_dtype=dtype)
102
+ quantize_model(part=transformer, quantization_scheme=quantization_scheme)
103
  vae = AutoencoderKLCogVideoX.from_pretrained("THUDM/CogVideoX-5b", subfolder="vae", torch_dtype=dtype)
104
+ quantize_model(part=vae, quantization_scheme=quantization_scheme)
105
 
106
  # 初始化管道
107
  pipe = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-5b", text_encoder=text_encoder, transformer=transformer, vae=vae, torch_dtype=dtype)
v2v_app_qm.py ADDED
@@ -0,0 +1,443 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import math
3
+ import os
4
+ import random
5
+ import threading
6
+ import time
7
+ import cv2
8
+ import tempfile
9
+ import imageio_ffmpeg
10
+ import gradio as gr
11
+ import torch
12
+ from PIL import Image
13
+ from diffusers import (
14
+ CogVideoXPipeline,
15
+ CogVideoXDPMScheduler,
16
+ CogVideoXVideoToVideoPipeline,
17
+ CogVideoXImageToVideoPipeline,
18
+ CogVideoXTransformer3DModel,
19
+ AutoencoderKLCogVideoX,
20
+ CogVideoXDDIMScheduler,
21
+ )
22
+ from diffusers.utils import load_video, load_image, export_to_video
23
+ from datetime import datetime, timedelta
24
+ from diffusers.image_processor import VaeImageProcessor
25
+ from transformers import T5EncoderModel
26
+ from openai import OpenAI
27
+ import moviepy.editor as mp
28
+ import utils
29
+ from rife_model import load_rife_model, rife_inference_with_latents
30
+ from huggingface_hub import hf_hub_download, snapshot_download
31
+ import gc
32
+ import torch._dynamo
33
+ from torchao.quantization import (
34
+ autoquant,
35
+ quantize_,
36
+ int8_weight_only,
37
+ int8_dynamic_activation_int8_weight,
38
+ int8_dynamic_activation_int4_weight,
39
+ int8_dynamic_activation_int8_semi_sparse_weight,
40
+ int4_weight_only,
41
+ float8_dynamic_activation_float8_weight,
42
+ float8_weight_only,
43
+ fpx_weight_only,
44
+ )
45
+ from torchao.quantization.quant_api import PerRow
46
+ from torchao.sparsity import sparsify_
47
+
48
+ os.environ["TORCH_LOGS"] = "+dynamo,output_code,graph_breaks,recompiles"
49
+ torch._dynamo.config.suppress_errors = True
50
+ torch.set_float32_matmul_precision("high")
51
+ torch._inductor.config.conv_1x1_as_mm = True
52
+ torch._inductor.config.coordinate_descent_tuning = True
53
+ torch._inductor.config.epilogue_fusion = False
54
+ torch._inductor.config.coordinate_descent_check_all_directions = True
55
+
56
+ # Set high precision for float32 matrix multiplications.
57
+ # This setting optimizes performance on NVIDIA GPUs with Ampere architecture (e.g., A100, RTX 30 series) or newer.
58
+ torch.set_float32_matmul_precision("high")
59
+
60
+ CONVERT_DTYPE = {
61
+ "fp16": lambda module: module.to(dtype=torch.float16),
62
+ "bf16": lambda module: module.to(dtype=torch.bfloat16),
63
+ "fp8wo": lambda module: quantize_(module, float8_weight_only()),
64
+ "fp8dq": lambda module: quantize_(module, float8_dynamic_activation_float8_weight()),
65
+ "fp8dqrow": lambda module: quantize_(module, float8_dynamic_activation_float8_weight(granularity=PerRow())),
66
+ "fp6_e3m2": lambda module: quantize_(module, fpx_weight_only(3, 2)),
67
+ "fp5_e2m2": lambda module: quantize_(module, fpx_weight_only(2, 2)),
68
+ "fp4_e2m1": lambda module: quantize_(module, fpx_weight_only(2, 1)),
69
+ "int8wo": lambda module: quantize_(module, int8_weight_only()),
70
+ "int8dq": lambda module: quantize_(module, int8_dynamic_activation_int8_weight()),
71
+ "int4dq": lambda module: quantize_(module, int8_dynamic_activation_int4_weight()),
72
+ "int4wo": lambda module: quantize_(module, int4_weight_only()),
73
+ "autoquant": lambda module: autoquant(module, error_on_unseen=False),
74
+ "sparsify": lambda module: sparsify_(module, int8_dynamic_activation_int8_semi_sparse_weight()),
75
+ }
76
+
77
+
78
+ device = "cuda" if torch.cuda.is_available() else "cpu"
79
+
80
+ hf_hub_download(repo_id="ai-forever/Real-ESRGAN", filename="RealESRGAN_x4.pth", local_dir="model_real_esran")
81
+ snapshot_download(repo_id="AlexWortega/RIFE", local_dir="model_rife")
82
+
83
+ # 解析命令行参数
84
+ parser = argparse.ArgumentParser(description="Generate a video from an image using CogVideoX")
85
+ parser.add_argument("--quantization_scheme", type=str, default="fp8", choices=list(CONVERT_DTYPE.keys()), help="The quantization scheme to use")
86
+ parser.add_argument("--dtype", type=str, default="bfloat16", help="The data type for computation (e.g., 'float16', 'bfloat16')")
87
+ args = parser.parse_args()
88
+
89
+ quantization_scheme = args.quantization_scheme
90
+ dtype = torch.float16 if args.dtype == "float16" else torch.bfloat16
91
+
92
+ # 量化模型函数
93
+ def quantize_model(part, quantization_scheme):
94
+ if quantization_scheme in CONVERT_DTYPE:
95
+ return CONVERT_DTYPE[quantization_scheme](part)
96
+ else:
97
+ raise ValueError(f"Unsupported quantization scheme: {quantization_scheme}")
98
+
99
+ # 初始化 transformer, text_encoder 和 vae
100
+ model_id = "THUDM/CogVideoX-5b"
101
+ transformer = CogVideoXTransformer3DModel.from_pretrained(model_id, subfolder="transformer", torch_dtype=dtype)
102
+ quantize_model(part=transformer, quantization_scheme=quantization_scheme)
103
+ text_encoder = T5EncoderModel.from_pretrained(model_id, subfolder="text_encoder", torch_dtype=dtype)
104
+ quantize_model(part=text_encoder, quantization_scheme=quantization_scheme)
105
+ vae = AutoencoderKLCogVideoX.from_pretrained(model_id, subfolder="vae", torch_dtype=dtype)
106
+ quantize_model(part=vae, quantization_scheme=quantization_scheme)
107
+
108
+ # 创建管道
109
+ pipe_video = CogVideoXVideoToVideoPipeline.from_pretrained(
110
+ model_id,
111
+ text_encoder=text_encoder,
112
+ transformer=transformer,
113
+ vae=vae,
114
+ torch_dtype=dtype,
115
+ )
116
+ #pipe_video.scheduler = CogVideoXDPMScheduler.from_config(pipe.scheduler.config)
117
+
118
+ # 启用内存优化
119
+ pipe_video.enable_sequential_cpu_offload()
120
+ pipe_video.vae.enable_tiling()
121
+
122
+ os.makedirs("./output", exist_ok=True)
123
+ os.makedirs("./gradio_tmp", exist_ok=True)
124
+
125
+ upscale_model = utils.load_sd_upscale("model_real_esran/RealESRGAN_x4.pth", device)
126
+ frame_interpolation_model = load_rife_model("model_rife")
127
+
128
+ 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.
129
+ 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.
130
+ There are a few rules to follow:
131
+ You will only ever output a single video description per user request.
132
+ When modifications are requested , you should not simply make the description longer . You should refactor the entire description to integrate the suggestions.
133
+ 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.
134
+ Video descriptions must have the same num of words as examples below. Extra words will be ignored.
135
+ """
136
+
137
+ def convert_prompt(prompt: str, retry_times: int = 3) -> str:
138
+ if not os.environ.get("OPENAI_API_KEY"):
139
+ return prompt
140
+ client = OpenAI()
141
+ text = prompt.strip()
142
+
143
+ for i in range(retry_times):
144
+ response = client.chat.completions.create(
145
+ messages=[
146
+ {"role": "system", "content": sys_prompt},
147
+ {
148
+ "role": "user",
149
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "a girl is on the beach"',
150
+ },
151
+ {
152
+ "role": "assistant",
153
+ "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.",
154
+ },
155
+ {
156
+ "role": "user",
157
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "A man jogging on a football field"',
158
+ },
159
+ {
160
+ "role": "assistant",
161
+ "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.",
162
+ },
163
+ {
164
+ "role": "user",
165
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : " A woman is dancing, HD footage, close-up"',
166
+ },
167
+ {
168
+ "role": "assistant",
169
+ "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.",
170
+ },
171
+ {
172
+ "role": "user",
173
+ "content": f'Create an imaginative video descriptive caption or modify an earlier caption in ENGLISH for the user input: "{text}"',
174
+ },
175
+ ],
176
+ model="glm-4-plus",
177
+ temperature=0.01,
178
+ top_p=0.7,
179
+ stream=False,
180
+ max_tokens=200,
181
+ )
182
+ if response.choices:
183
+ return response.choices[0].message.content
184
+ return prompt
185
+
186
+ def infer(
187
+ prompt: str,
188
+ video_input: str,
189
+ video_strength: float,
190
+ seed: int = -1,
191
+ progress=gr.Progress(track_tqdm=True),
192
+ ):
193
+ if seed == -1:
194
+ seed = random.randint(0, 2**8 - 1)
195
+
196
+ video = load_video(video_input)[:49] # Limit to 49 frames
197
+ '''
198
+ pipe_video = CogVideoXVideoToVideoPipeline.from_pretrained(
199
+ "THUDM/CogVideoX-5b",
200
+ transformer=transformer,
201
+ vae=vae,
202
+ scheduler=pipe.scheduler,
203
+ tokenizer=pipe.tokenizer,
204
+ text_encoder=text_encoder,
205
+ torch_dtype=torch.float16
206
+ ).to(device)
207
+ pipe_video = CogVideoXVideoToVideoPipeline.from_pretrained(
208
+ "THUDM/CogVideoX-5b",
209
+ transformer=transformer,
210
+ vae=vae,
211
+ scheduler=pipe.scheduler,
212
+ tokenizer=pipe.tokenizer,
213
+ text_encoder=text_encoder,
214
+ torch_dtype=torch.float16
215
+ )
216
+ '''
217
+ video_pt = pipe_video(
218
+ video=video,
219
+ prompt=prompt,
220
+ num_inference_steps=50,
221
+ num_videos_per_prompt=1,
222
+ strength=video_strength,
223
+ use_dynamic_cfg=True,
224
+ output_type="pt",
225
+ guidance_scale=7.0,
226
+ generator=torch.Generator(device="cpu").manual_seed(seed),
227
+ ).frames
228
+ #pipe_video.to("cpu")
229
+ #del pipe_video
230
+ gc.collect()
231
+ torch.cuda.empty_cache()
232
+ return (video_pt, seed)
233
+
234
+ def convert_to_gif(video_path):
235
+ clip = mp.VideoFileClip(video_path)
236
+ clip = clip.set_fps(8)
237
+ clip = clip.resize(height=240)
238
+ gif_path = video_path.replace(".mp4", ".gif")
239
+ clip.write_gif(gif_path, fps=8)
240
+ return gif_path
241
+
242
+ def delete_old_files():
243
+ while True:
244
+ now = datetime.now()
245
+ cutoff = now - timedelta(minutes=10)
246
+ directories = ["./output", "./gradio_tmp"]
247
+
248
+ for directory in directories:
249
+ for filename in os.listdir(directory):
250
+ file_path = os.path.join(directory, filename)
251
+ if os.path.isfile(file_path):
252
+ file_mtime = datetime.fromtimestamp(os.path.getmtime(file_path))
253
+ if file_mtime < cutoff:
254
+ os.remove(file_path)
255
+ time.sleep(600)
256
+
257
+ threading.Thread(target=delete_old_files, daemon=True).start()
258
+
259
+ with gr.Blocks() as demo:
260
+ gr.Markdown("""
261
+ <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
262
+ CogVideoX-5B Huggingface Space🤗
263
+ </div>
264
+ <div style="text-align: center;">
265
+ <a href="https://huggingface.co/THUDM/CogVideoX-5B">🤗 5B(T2V) Model Hub</a> |
266
+ <a href="https://huggingface.co/THUDM/CogVideoX-5B-I2V">🤗 5B(I2V) Model Hub</a> |
267
+ <a href="https://github.com/THUDM/CogVideo">🌐 Github</a> |
268
+ <a href="https://arxiv.org/pdf/2408.06072">📜 arxiv </a>
269
+ </div>
270
+ <div style="text-align: center;display: flex;justify-content: center;align-items: center;margin-top: 1em;margin-bottom: .5em;">
271
+ <span>If the Space is too busy, duplicate it to use privately</span>
272
+ <a href="https://huggingface.co/spaces/THUDM/CogVideoX-5B-Space?duplicate=true"><img src="https://huggingface.co/datasets/huggingface/badges/resolve/main/duplicate-this-space-lg.svg" width="160" style="
273
+ margin-left: .75em;
274
+ "></a>
275
+ </div>
276
+ <div style="text-align: center; font-size: 15px; font-weight: bold; color: red; margin-bottom: 20px;">
277
+ ⚠️ This demo is for academic research and experiential use only.
278
+ </div>
279
+ """)
280
+ with gr.Row():
281
+ with gr.Column():
282
+ with gr.Accordion("V2V: Video Input (cannot be used simultaneously with image input)", open=False):
283
+ video_input = gr.Video(label="Input Video (will be cropped to 49 frames, 6 seconds at 8fps)")
284
+ strength = gr.Slider(0.1, 1.0, value=0.8, step=0.01, label="Strength")
285
+ prompt = gr.Textbox(label="Prompt (Less than 200 Words)", placeholder="Enter your prompt here", lines=5)
286
+
287
+ with gr.Row():
288
+ gr.Markdown(
289
+ "✨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."
290
+ )
291
+ enhance_button = gr.Button("✨ Enhance Prompt(Optional)")
292
+ with gr.Group():
293
+ with gr.Column():
294
+ with gr.Row():
295
+ seed_param = gr.Number(
296
+ label="Inference Seed (Enter a positive number, -1 for random)", value=-1
297
+ )
298
+ with gr.Row():
299
+ enable_scale = gr.Checkbox(label="Super-Resolution (720 × 480 -> 2880 × 1920)", value=False)
300
+ enable_rife = gr.Checkbox(label="Frame Interpolation (8fps -> 16fps)", value=False)
301
+ gr.Markdown(
302
+ "✨In this demo, we use [RIFE](https://github.com/hzwer/ECCV2022-RIFE) for frame interpolation and [Real-ESRGAN](https://github.com/xinntao/Real-ESRGAN) for upscaling(Super-Resolution).<br>&nbsp;&nbsp;&nbsp;&nbsp;The entire process is based on open-source solutions."
303
+ )
304
+
305
+ generate_button = gr.Button("🎬 Generate Video")
306
+
307
+ with gr.Column():
308
+ video_output = gr.Video(label="CogVideoX Generate Video", width=720, height=480)
309
+ with gr.Row():
310
+ download_video_button = gr.File(label="📥 Download Video", visible=False)
311
+ download_gif_button = gr.File(label="📥 Download GIF", visible=False)
312
+ seed_text = gr.Number(label="Seed Used for Video Generation", visible=False)
313
+
314
+ gr.Markdown("""
315
+ <table border="0" style="width: 100%; text-align: left; margin-top: 20px;">
316
+ <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
317
+ 🎥 Video Gallery
318
+ </div>
319
+ <tr>
320
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
321
+ <p>A garden comes to life as a kaleidoscope of butterflies flutters amidst the blossoms, their delicate wings casting shadows on the petals below. In the background, a grand fountain cascades water with a gentle splendor, its rhythmic sound providing a soothing backdrop. Beneath the cool shade of a mature tree, a solitary wooden chair invites solitude and reflection, its smooth surface worn by the touch of countless visitors seeking a moment of tranquility in nature's embrace.</p>
322
+ </td>
323
+ <td style="width: 25%; vertical-align: top;">
324
+ <video src="https://github.com/user-attachments/assets/cf5953ea-96d3-48fd-9907-c4708752c714" width="100%" controls autoplay loop></video>
325
+ </td>
326
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
327
+ <p>A small boy, head bowed and determination etched on his face, sprints through the torrential downpour as lightning crackles and thunder rumbles in the distance. The relentless rain pounds the ground, creating a chaotic dance of water droplets that mirror the dramatic sky's anger. In the far background, the silhouette of a cozy home beckons, a faint beacon of safety and warmth amidst the fierce weather. The scene is one of perseverance and the unyielding spirit of a child braving the elements.</p>
328
+ </td>
329
+ <td style="width: 25%; vertical-align: top;">
330
+ <video src="https://github.com/user-attachments/assets/fe0a78e6-b669-4800-8cf0-b5f9b5145b52" width="100%" controls autoplay loop></video>
331
+ </td>
332
+ </tr>
333
+ <tr>
334
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
335
+ <p>A suited astronaut, with the red dust of Mars clinging to their boots, reaches out to shake hands with an alien being, their skin a shimmering blue, under the pink-tinged sky of the fourth planet. In the background, a sleek silver rocket, a beacon of human ingenuity, stands tall, its engines powered down, as the two representatives of different worlds exchange a historic greeting amidst the desolate beauty of the Martian landscape.</p>
336
+ </td>
337
+ <td style="width: 25%; vertical-align: top;">
338
+ <video src="https://github.com/user-attachments/assets/c182f606-8f8c-421d-b414-8487070fcfcb" width="100%" controls autoplay loop></video>
339
+ </td>
340
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
341
+ <p>An elderly gentleman, with a serene expression, sits at the water's edge, a steaming cup of tea by his side. He is engrossed in his artwork, brush in hand, as he renders an oil painting on a canvas that's propped up against a small, weathered table. The sea breeze whispers through his silver hair, gently billowing his loose-fitting white shirt, while the salty air adds an intangible element to his masterpiece in progress. The scene is one of tranquility and inspiration, with the artist's canvas capturing the vibrant hues of the setting sun reflecting off the tranquil sea.</p>
342
+ </td>
343
+ <td style="width: 25%; vertical-align: top;">
344
+ <video src="https://github.com/user-attachments/assets/7db2bbce-194d-434d-a605-350254b6c298" width="100%" controls autoplay loop></video>
345
+ </td>
346
+ </tr>
347
+ <tr>
348
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
349
+ <p>In a dimly lit bar, purplish light bathes the face of a mature man, his eyes blinking thoughtfully as he ponders in close-up, the background artfully blurred to focus on his introspective expression, the ambiance of the bar a mere suggestion of shadows and soft lighting.</p>
350
+ </td>
351
+ <td style="width: 25%; vertical-align: top;">
352
+ <video src="https://github.com/user-attachments/assets/62b01046-8cab-44cc-bd45-4d965bb615ec" width="100%" controls autoplay loop></video>
353
+ </td>
354
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
355
+ <p>A golden retriever, sporting sleek black sunglasses, with its lengthy fur flowing in the breeze, sprints playfully across a rooftop terrace, recently refreshed by a light rain. The scene unfolds from a distance, the dog's energetic bounds growing larger as it approaches the camera, its tail wagging with unrestrained joy, while droplets of water glisten on the concrete behind it. The overcast sky provides a dramatic backdrop, emphasizing the vibrant golden coat of the canine as it dashes towards the viewer.</p>
356
+ </td>
357
+ <td style="width: 25%; vertical-align: top;">
358
+ <video src="https://github.com/user-attachments/assets/d78e552a-4b3f-4b81-ac3f-3898079554f6" width="100%" controls autoplay loop></video>
359
+ </td>
360
+ </tr>
361
+ <tr>
362
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
363
+ <p>On a brilliant sunny day, the lakeshore is lined with an array of willow trees, their slender branches swaying gently in the soft breeze. The tranquil surface of the lake reflects the clear blue sky, while several elegant swans glide gracefully through the still water, leaving behind delicate ripples that disturb the mirror-like quality of the lake. The scene is one of serene beauty, with the willows' greenery providing a picturesque frame for the peaceful avian visitors.</p>
364
+ </td>
365
+ <td style="width: 25%; vertical-align: top;">
366
+ <video src="https://github.com/user-attachments/assets/30894f12-c741-44a2-9e6e-ddcacc231e5b" width="100%" controls autoplay loop></video>
367
+ </td>
368
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
369
+ <p>A Chinese mother, draped in a soft, pastel-colored robe, gently rocks back and forth in a cozy rocking chair positioned in the tranquil setting of a nursery. The dimly lit bedroom is adorned with whimsical mobiles dangling from the ceiling, casting shadows that dance on the walls. Her baby, swaddled in a delicate, patterned blanket, rests against her chest, the child's earlier cries now replaced by contented coos as the mother's soothing voice lulls the little one to sleep. The scent of lavender fills the air, adding to the serene atmosphere, while a warm, orange glow from a nearby nightlight illuminates the scene with a gentle hue, capturing a moment of tender love and comfort.</p>
370
+ </td>
371
+ <td style="width: 25%; vertical-align: top;">
372
+ <video src="https://github.com/user-attachments/assets/926575ca-7150-435b-a0ff-4900a963297b" width="100%" controls autoplay loop></video>
373
+ </td>
374
+ </tr>
375
+ </table>
376
+ """)
377
+
378
+ def generate(
379
+ prompt,
380
+ video_input,
381
+ video_strength,
382
+ seed_value,
383
+ scale_status,
384
+ rife_status,
385
+ progress=gr.Progress(track_tqdm=True)
386
+ ):
387
+ latents, seed = infer(
388
+ prompt,
389
+ video_input,
390
+ video_strength,
391
+ seed=seed_value,
392
+ progress=progress,
393
+ )
394
+ if scale_status:
395
+ latents = utils.upscale_batch_and_concatenate(upscale_model, latents, device)
396
+ if rife_status:
397
+ latents = rife_inference_with_latents(frame_interpolation_model, latents)
398
+
399
+ batch_size = latents.shape[0]
400
+ batch_video_frames = []
401
+ for batch_idx in range(batch_size):
402
+ pt_image = latents[batch_idx]
403
+ pt_image = torch.stack([pt_image[i] for i in range(pt_image.shape[0])])
404
+
405
+ image_np = VaeImageProcessor.pt_to_numpy(pt_image)
406
+ image_pil = VaeImageProcessor.numpy_to_pil(image_np)
407
+ batch_video_frames.append(image_pil)
408
+
409
+ video_path = utils.save_video(batch_video_frames[0], fps=math.ceil((len(batch_video_frames[0]) - 1) / 6))
410
+ video_update = gr.update(visible=True, value=video_path)
411
+ gif_path = convert_to_gif(video_path)
412
+ gif_update = gr.update(visible=True, value=gif_path)
413
+ seed_update = gr.update(visible=True, value=seed)
414
+
415
+ return video_path, video_update, gif_update, seed_update
416
+
417
+ def enhance_prompt_func(prompt):
418
+ return convert_prompt(prompt, retry_times=1)
419
+
420
+ generate_button.click(
421
+ generate,
422
+ inputs=[prompt, video_input, strength, seed_param, enable_scale, enable_rife],
423
+ outputs=[video_output, download_video_button, download_gif_button, seed_text],
424
+ )
425
+
426
+ enhance_button.click(enhance_prompt_func, inputs=[prompt], outputs=[prompt])
427
+
428
+
429
+ demo.queue(max_size=15)
430
+ demo.launch(share = True)
431
+
432
+ '''
433
+ https://github.com/THUDM/CogVideo/issues/245
434
+ torch>=2.5.0
435
+ torchao==0.5
436
+
437
+ don't use float16, should use bfloat16
438
+
439
+ python v2v_app_qm.py --quantization_scheme int8wo --dtype bfloat16
440
+ python v2v_app_qm.py --quantization_scheme fp8wo --dtype bfloat16
441
+ python v2v_app_qm.py --quantization_scheme bf16 --dtype bfloat16
442
+ python v2v_app_qm.py --quantization_scheme fp16 --dtype float16
443
+ '''