LexDF/CogVideoX-5B-Space
0
1"""2THis is the main file for the gradio web demo. It uses the CogVideoX-5B model to generate videos gradio web demo.3set environment variable OPENAI_API_KEY to use the OpenAI API to enhance the prompt.4 5Usage:6 OpenAI_API_KEY=your_openai_api_key OPENAI_BASE_URL=https://api.openai.com/v1 python inference/gradio_web_demo.py7"""8 9import math10import os11import random12import threading13import time14 15import cv216import tempfile17import imageio_ffmpeg18import gradio as gr19import torch20from PIL import Image21from diffusers import (22 CogVideoXPipeline,23 CogVideoXDPMScheduler,24 CogVideoXVideoToVideoPipeline,25 CogVideoXImageToVideoPipeline,26 CogVideoXTransformer3DModel,27)28from diffusers.utils import load_video, load_image29from datetime import datetime, timedelta30 31from diffusers.image_processor import VaeImageProcessor32from openai import OpenAI33import moviepy.editor as mp34import utils35from rife_model import load_rife_model, rife_inference_with_latents36from huggingface_hub import hf_hub_download, snapshot_download37import gc38 39device = "cuda" if torch.cuda.is_available() else "cpu"40 41hf_hub_download(repo_id="ai-forever/Real-ESRGAN", filename="RealESRGAN_x4.pth", local_dir="model_real_esran")42snapshot_download(repo_id="AlexWortega/RIFE", local_dir="model_rife")43 44pipe = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-5b", torch_dtype=torch.bfloat16).to("cpu")45pipe.scheduler = CogVideoXDPMScheduler.from_config(pipe.scheduler.config, timestep_spacing="trailing")46 47i2v_transformer = CogVideoXTransformer3DModel.from_pretrained(48 "THUDM/CogVideoX-5b-I2V", subfolder="transformer", torch_dtype=torch.bfloat1649)50 51# pipe.transformer.to(memory_format=torch.channels_last)52# pipe.transformer = torch.compile(pipe.transformer, mode="max-autotune", fullgraph=True)53# pipe_image.transformer.to(memory_format=torch.channels_last)54# pipe_image.transformer = torch.compile(pipe_image.transformer, mode="max-autotune", fullgraph=True)55 56os.makedirs("./output", exist_ok=True)57os.makedirs("./gradio_tmp", exist_ok=True)58 59upscale_model = utils.load_sd_upscale("model_real_esran/RealESRGAN_x4.pth", device)60frame_interpolation_model = load_rife_model("model_rife")61 62sys_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.63 64For 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.65There are a few rules to follow:66 67You will only ever output a single video description per user request.68 69When modifications are requested , you should not simply make the description longer . You should refactor the entire description to integrate the suggestions.70Other 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.71 72Video descriptions must have the same num of words as examples below. Extra words will be ignored.73"""74 75 76def resize_if_unfit(input_video, progress=gr.Progress(track_tqdm=True)):77 width, height = get_video_dimensions(input_video)78 79 if width == 720 and height == 480:80 processed_video = input_video81 else:82 processed_video = center_crop_resize(input_video)83 return processed_video84 85 86def get_video_dimensions(input_video_path):87 reader = imageio_ffmpeg.read_frames(input_video_path)88 metadata = next(reader)89 return metadata["size"]90 91 92def center_crop_resize(input_video_path, target_width=720, target_height=480):93 cap = cv2.VideoCapture(input_video_path)94 95 orig_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))96 orig_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))97 orig_fps = cap.get(cv2.CAP_PROP_FPS)98 total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))99 100 width_factor = target_width / orig_width101 height_factor = target_height / orig_height102 resize_factor = max(width_factor, height_factor)103 104 inter_width = int(orig_width * resize_factor)105 inter_height = int(orig_height * resize_factor)106 107 target_fps = 8108 ideal_skip = max(0, math.ceil(orig_fps / target_fps) - 1)109 skip = min(5, ideal_skip) # Cap at 5110 111 while (total_frames / (skip + 1)) < 49 and skip > 0:112 skip -= 1113 114 processed_frames = []115 frame_count = 0116 total_read = 0117 118 while frame_count < 49 and total_read < total_frames:119 ret, frame = cap.read()120 if not ret:121 break122 123 if total_read % (skip + 1) == 0:124 resized = cv2.resize(frame, (inter_width, inter_height), interpolation=cv2.INTER_AREA)125 126 start_x = (inter_width - target_width) // 2127 start_y = (inter_height - target_height) // 2128 cropped = resized[start_y : start_y + target_height, start_x : start_x + target_width]129 130 processed_frames.append(cropped)131 frame_count += 1132 133 total_read += 1134 135 cap.release()136 137 with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as temp_file:138 temp_video_path = temp_file.name139 fourcc = cv2.VideoWriter_fourcc(*"mp4v")140 out = cv2.VideoWriter(temp_video_path, fourcc, target_fps, (target_width, target_height))141 142 for frame in processed_frames:143 out.write(frame)144 145 out.release()146 147 return temp_video_path148 149 150def convert_prompt(prompt: str, retry_times: int = 3) -> str:151 if not os.environ.get("OPENAI_API_KEY"):152 return prompt153 client = OpenAI()154 text = prompt.strip()155 156 for i in range(retry_times):157 response = client.chat.completions.create(158 messages=[159 {"role": "system", "content": sys_prompt},160 {161 "role": "user",162 "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "a girl is on the beach"',163 },164 {165 "role": "assistant",166 "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.",167 },168 {169 "role": "user",170 "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "A man jogging on a football field"',171 },172 {173 "role": "assistant",174 "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.",175 },176 {177 "role": "user",178 "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : " A woman is dancing, HD footage, close-up"',179 },180 {181 "role": "assistant",182 "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.",183 },184 {185 "role": "user",186 "content": f'Create an imaginative video descriptive caption or modify an earlier caption in ENGLISH for the user input: "{text}"',187 },188 ],189 model="glm-4-plus",190 temperature=0.01,191 top_p=0.7,192 stream=False,193 max_tokens=200,194 )195 if response.choices:196 return response.choices[0].message.content197 return prompt198 199 200def infer(201 prompt: str,202 image_input: str,203 video_input: str,204 video_strenght: float,205 num_inference_steps: int,206 guidance_scale: float,207 seed: int = -1,208 progress=gr.Progress(track_tqdm=True),209):210 if seed == -1:211 seed = random.randint(0, 2**8 - 1)212 213 if video_input is not None:214 video = load_video(video_input)[:49] # Limit to 49 frames215 pipe_video = CogVideoXVideoToVideoPipeline.from_pretrained(216 "THUDM/CogVideoX-5b",217 transformer=pipe.transformer,218 vae=pipe.vae,219 scheduler=pipe.scheduler,220 tokenizer=pipe.tokenizer,221 text_encoder=pipe.text_encoder,222 torch_dtype=torch.bfloat16,223 ).to(device)224 video_pt = pipe_video(225 video=video,226 prompt=prompt,227 num_inference_steps=num_inference_steps,228 num_videos_per_prompt=1,229 strength=video_strenght,230 use_dynamic_cfg=True,231 output_type="pt",232 guidance_scale=guidance_scale,233 generator=torch.Generator(device="cpu").manual_seed(seed),234 ).frames235 pipe_video.to("cpu")236 del pipe_video237 gc.collect()238 torch.cuda.empty_cache()239 elif image_input is not None:240 pipe_image = CogVideoXImageToVideoPipeline.from_pretrained(241 "THUDM/CogVideoX-5b-I2V",242 transformer=i2v_transformer,243 vae=pipe.vae,244 scheduler=pipe.scheduler,245 tokenizer=pipe.tokenizer,246 text_encoder=pipe.text_encoder,247 torch_dtype=torch.bfloat16,248 ).to(device)249 image_input = Image.fromarray(image_input).resize(size=(720, 480)) # Convert to PIL250 image = load_image(image_input)251 video_pt = pipe_image(252 image=image,253 prompt=prompt,254 num_inference_steps=num_inference_steps,255 num_videos_per_prompt=1,256 use_dynamic_cfg=True,257 output_type="pt",258 guidance_scale=guidance_scale,259 generator=torch.Generator(device="cpu").manual_seed(seed),260 ).frames261 pipe_image.to("cpu")262 del pipe_image263 gc.collect()264 torch.cuda.empty_cache()265 else:266 pipe.to(device)267 video_pt = pipe(268 prompt=prompt,269 num_videos_per_prompt=1,270 num_inference_steps=num_inference_steps,271 num_frames=49,272 use_dynamic_cfg=True,273 output_type="pt",274 guidance_scale=guidance_scale,275 generator=torch.Generator(device="cpu").manual_seed(seed),276 ).frames277 pipe.to("cpu")278 gc.collect()279 return (video_pt, seed)280 281 282def convert_to_gif(video_path):283 clip = mp.VideoFileClip(video_path)284 clip = clip.set_fps(8)285 clip = clip.resize(height=240)286 gif_path = video_path.replace(".mp4", ".gif")287 clip.write_gif(gif_path, fps=8)288 return gif_path289 290 291def delete_old_files():292 while True:293 now = datetime.now()294 cutoff = now - timedelta(minutes=10)295 directories = ["./output", "./gradio_tmp"]296 297 for directory in directories:298 for filename in os.listdir(directory):299 file_path = os.path.join(directory, filename)300 if os.path.isfile(file_path):301 file_mtime = datetime.fromtimestamp(os.path.getmtime(file_path))302 if file_mtime < cutoff:303 os.remove(file_path)304 time.sleep(600)305 306 307threading.Thread(target=delete_old_files, daemon=True).start()308examples_videos = [["example_videos/horse.mp4"], ["example_videos/kitten.mp4"], ["example_videos/train_running.mp4"]]309examples_images = [["example_images/beach.png"], ["example_images/street.png"], ["example_images/camping.png"]]310 311with gr.Blocks() as demo:312 gr.Markdown("""313 <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">314 CogVideoX-5B Huggingface Space🤗315 </div>316 <div style="text-align: center;">317 <a href="https://huggingface.co/THUDM/CogVideoX-5B">🤗 5B(T2V) Model Hub</a> |318 <a href="https://huggingface.co/THUDM/CogVideoX-5B-I2V">🤗 5B(I2V) Model Hub</a> |319 <a href="https://github.com/THUDM/CogVideo">🌐 Github</a> |320 <a href="https://arxiv.org/pdf/2408.06072">📜 arxiv </a>321 </div>322 <div style="text-align: center;display: flex;justify-content: center;align-items: center;margin-top: 1em;margin-bottom: .5em;">323 <span>If the Space is too busy, duplicate it to use privately</span>324 <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="325 margin-left: .75em;326 "></a>327 </div>328 <div style="text-align: center; font-size: 15px; font-weight: bold; color: red; margin-bottom: 20px;">329 ⚠️ This demo is for academic research and experiential use only. 330 </div>331 """)332 with gr.Row():333 with gr.Column():334 with gr.Accordion("I2V: Image Input (cannot be used simultaneously with video input)", open=False):335 image_input = gr.Image(label="Input Image (will be cropped to 720 * 480)")336 examples_component_images = gr.Examples(examples_images, inputs=[image_input], cache_examples=False)337 with gr.Accordion("V2V: Video Input (cannot be used simultaneously with image input)", open=False):338 video_input = gr.Video(label="Input Video (will be cropped to 49 frames, 6 seconds at 8fps)")339 strength = gr.Slider(0.1, 1.0, value=0.8, step=0.01, label="Strength")340 examples_component_videos = gr.Examples(examples_videos, inputs=[video_input], cache_examples=False)341 prompt = gr.Textbox(label="Prompt (Less than 200 Words)", placeholder="Enter your prompt here", lines=5)342 343 with gr.Row():344 gr.Markdown(345 "✨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."346 )347 enhance_button = gr.Button("✨ Enhance Prompt(Optional)")348 with gr.Group():349 with gr.Column():350 with gr.Row():351 seed_param = gr.Number(352 label="Inference Seed (Enter a positive number, -1 for random)", value=-1353 )354 with gr.Row():355 enable_scale = gr.Checkbox(label="Super-Resolution (720 × 480 -> 2880 × 1920)", value=False)356 enable_rife = gr.Checkbox(label="Frame Interpolation (8fps -> 16fps)", value=False)357 gr.Markdown(358 "✨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> The entire process is based on open-source solutions."359 )360 361 generate_button = gr.Button("🎬 Generate Video")362 363 with gr.Column():364 video_output = gr.Video(label="CogVideoX Generate Video", width=720, height=480)365 with gr.Row():366 download_video_button = gr.File(label="📥 Download Video", visible=False)367 download_gif_button = gr.File(label="📥 Download GIF", visible=False)368 seed_text = gr.Number(label="Seed Used for Video Generation", visible=False)369 370 gr.Markdown("""371 <table border="0" style="width: 100%; text-align: left; margin-top: 20px;">372 <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">373 🎥 Video Gallery374 </div>375 <tr>376 <td style="width: 25%; vertical-align: top; font-size: 0.9em;">377 <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>378 </td>379 <td style="width: 25%; vertical-align: top;">380 <video src="https://github.com/user-attachments/assets/cf5953ea-96d3-48fd-9907-c4708752c714" width="100%" controls autoplay loop></video>381 </td>382 <td style="width: 25%; vertical-align: top; font-size: 0.9em;">383 <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>384 </td>385 <td style="width: 25%; vertical-align: top;">386 <video src="https://github.com/user-attachments/assets/fe0a78e6-b669-4800-8cf0-b5f9b5145b52" width="100%" controls autoplay loop></video>387 </td>388 </tr>389 <tr>390 <td style="width: 25%; vertical-align: top; font-size: 0.9em;">391 <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>392 </td>393 <td style="width: 25%; vertical-align: top;">394 <video src="https://github.com/user-attachments/assets/c182f606-8f8c-421d-b414-8487070fcfcb" width="100%" controls autoplay loop></video>395 </td>396 <td style="width: 25%; vertical-align: top; font-size: 0.9em;">397 <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>398 </td>399 <td style="width: 25%; vertical-align: top;">400 <video src="https://github.com/user-attachments/assets/7db2bbce-194d-434d-a605-350254b6c298" width="100%" controls autoplay loop></video>401 </td>402 </tr>403 <tr>404 <td style="width: 25%; vertical-align: top; font-size: 0.9em;">405 <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>406 </td>407 <td style="width: 25%; vertical-align: top;">408 <video src="https://github.com/user-attachments/assets/62b01046-8cab-44cc-bd45-4d965bb615ec" width="100%" controls autoplay loop></video>409 </td>410 <td style="width: 25%; vertical-align: top; font-size: 0.9em;">411 <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>412 </td>413 <td style="width: 25%; vertical-align: top;">414 <video src="https://github.com/user-attachments/assets/d78e552a-4b3f-4b81-ac3f-3898079554f6" width="100%" controls autoplay loop></video>415 </td>416 </tr>417 <tr>418 <td style="width: 25%; vertical-align: top; font-size: 0.9em;">419 <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>420 </td>421 <td style="width: 25%; vertical-align: top;">422 <video src="https://github.com/user-attachments/assets/30894f12-c741-44a2-9e6e-ddcacc231e5b" width="100%" controls autoplay loop></video>423 </td>424 <td style="width: 25%; vertical-align: top; font-size: 0.9em;">425 <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>426 </td>427 <td style="width: 25%; vertical-align: top;">428 <video src="https://github.com/user-attachments/assets/926575ca-7150-435b-a0ff-4900a963297b" width="100%" controls autoplay loop></video>429 </td>430 </tr>431 </table>432 """)433 434 def generate(435 prompt,436 image_input,437 video_input,438 video_strength,439 seed_value,440 scale_status,441 rife_status,442 progress=gr.Progress(track_tqdm=True)443 ):444 latents, seed = infer(445 prompt,446 image_input,447 video_input,448 video_strength,449 num_inference_steps=50, # NOT Changed450 guidance_scale=7.0, # NOT Changed451 seed=seed_value,452 progress=progress,453 )454 if scale_status:455 latents = utils.upscale_batch_and_concatenate(upscale_model, latents, device)456 if rife_status:457 latents = rife_inference_with_latents(frame_interpolation_model, latents)458 459 batch_size = latents.shape[0]460 batch_video_frames = []461 for batch_idx in range(batch_size):462 pt_image = latents[batch_idx]463 pt_image = torch.stack([pt_image[i] for i in range(pt_image.shape[0])])464 465 image_np = VaeImageProcessor.pt_to_numpy(pt_image)466 image_pil = VaeImageProcessor.numpy_to_pil(image_np)467 batch_video_frames.append(image_pil)468 469 video_path = utils.save_video(batch_video_frames[0], fps=math.ceil((len(batch_video_frames[0]) - 1) / 6))470 video_update = gr.update(visible=True, value=video_path)471 gif_path = convert_to_gif(video_path)472 gif_update = gr.update(visible=True, value=gif_path)473 seed_update = gr.update(visible=True, value=seed)474 475 return video_path, video_update, gif_update, seed_update476 477 def enhance_prompt_func(prompt):478 return convert_prompt(prompt, retry_times=1)479 480 generate_button.click(481 generate,482 inputs=[prompt, image_input, video_input, strength, seed_param, enable_scale, enable_rife],483 outputs=[video_output, download_video_button, download_gif_button, seed_text],484 )485 486 enhance_button.click(enhance_prompt_func, inputs=[prompt], outputs=[prompt])487 video_input.upload(resize_if_unfit, inputs=[video_input], outputs=[video_input])488 489if __name__ == "__main__":490 demo.queue(max_size=15)491 demo.launch()492 