neuralleap/CogVideoX-5B-API-V2
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 39from fastapi import FastAPI, HTTPException40from fastapi.middleware.cors import CORSMiddleware41from fastapi.responses import FileResponse42from huggingface_hub import hf_hub_download, snapshot_download43 44from data_class.GenerateResponse import GenerateResponse45from data_class.GenerateRequest import GenerateRequest46 47app = FastAPI()48 49# CORS Configuration50app.add_middleware(51 CORSMiddleware,52 allow_origins=["*"],53 allow_credentials=True,54 allow_methods=["*"],55 allow_headers=["*"],56)57 58@app.get("/info")59def get_root():60 return {"message": "TestInfo"}61 62device = "cuda" if torch.cuda.is_available() else "cpu"63 64hf_hub_download(repo_id="ai-forever/Real-ESRGAN", filename="RealESRGAN_x4.pth", local_dir="model_real_esran")65snapshot_download(repo_id="AlexWortega/RIFE", local_dir="model_rife")66 67pipe = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-5b", torch_dtype=torch.bfloat16).to("cpu")68pipe.scheduler = CogVideoXDPMScheduler.from_config(pipe.scheduler.config, timestep_spacing="trailing")69 70i2v_transformer = CogVideoXTransformer3DModel.from_pretrained(71 "THUDM/CogVideoX-5b-I2V", subfolder="transformer", torch_dtype=torch.bfloat1672)73 74# pipe.transformer.to(memory_format=torch.channels_last)75# pipe.transformer = torch.compile(pipe.transformer, mode="max-autotune", fullgraph=True)76# pipe_image.transformer.to(memory_format=torch.channels_last)77# pipe_image.transformer = torch.compile(pipe_image.transformer, mode="max-autotune", fullgraph=True)78 79os.makedirs("./output", exist_ok=True)80os.makedirs("./gradio_tmp", exist_ok=True)81 82upscale_model = utils.load_sd_upscale("model_real_esran/RealESRGAN_x4.pth", device)83frame_interpolation_model = load_rife_model("model_rife")84 85sys_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.86 87For 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.88There are a few rules to follow:89 90You will only ever output a single video description per user request.91 92When modifications are requested , you should not simply make the description longer . You should refactor the entire description to integrate the suggestions.93Other 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.94 95Video descriptions must have the same num of words as examples below. Extra words will be ignored.96"""97 98 99def resize_if_unfit(input_video, progress=gr.Progress(track_tqdm=True)):100 width, height = get_video_dimensions(input_video)101 102 if width == 720 and height == 480:103 processed_video = input_video104 else:105 processed_video = center_crop_resize(input_video)106 return processed_video107 108 109def get_video_dimensions(input_video_path):110 reader = imageio_ffmpeg.read_frames(input_video_path)111 metadata = next(reader)112 return metadata["size"]113 114 115def center_crop_resize(input_video_path, target_width=720, target_height=480):116 cap = cv2.VideoCapture(input_video_path)117 118 orig_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))119 orig_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))120 orig_fps = cap.get(cv2.CAP_PROP_FPS)121 total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))122 123 width_factor = target_width / orig_width124 height_factor = target_height / orig_height125 resize_factor = max(width_factor, height_factor)126 127 inter_width = int(orig_width * resize_factor)128 inter_height = int(orig_height * resize_factor)129 130 target_fps = 8131 ideal_skip = max(0, math.ceil(orig_fps / target_fps) - 1)132 skip = min(5, ideal_skip) # Cap at 5133 134 while (total_frames / (skip + 1)) < 49 and skip > 0:135 skip -= 1136 137 processed_frames = []138 frame_count = 0139 total_read = 0140 141 while frame_count < 49 and total_read < total_frames:142 ret, frame = cap.read()143 if not ret:144 break145 146 if total_read % (skip + 1) == 0:147 resized = cv2.resize(frame, (inter_width, inter_height), interpolation=cv2.INTER_AREA)148 149 start_x = (inter_width - target_width) // 2150 start_y = (inter_height - target_height) // 2151 cropped = resized[start_y : start_y + target_height, start_x : start_x + target_width]152 153 processed_frames.append(cropped)154 frame_count += 1155 156 total_read += 1157 158 cap.release()159 160 with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as temp_file:161 temp_video_path = temp_file.name162 fourcc = cv2.VideoWriter_fourcc(*"mp4v")163 out = cv2.VideoWriter(temp_video_path, fourcc, target_fps, (target_width, target_height))164 165 for frame in processed_frames:166 out.write(frame)167 168 out.release()169 170 return temp_video_path171 172 173def convert_prompt(prompt: str, retry_times: int = 3) -> str:174 if not os.environ.get("OPENAI_API_KEY"):175 return prompt176 client = OpenAI()177 text = prompt.strip()178 179 for i in range(retry_times):180 response = client.chat.completions.create(181 messages=[182 {"role": "system", "content": sys_prompt},183 {184 "role": "user",185 "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "a girl is on the beach"',186 },187 {188 "role": "assistant",189 "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.",190 },191 {192 "role": "user",193 "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "A man jogging on a football field"',194 },195 {196 "role": "assistant",197 "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.",198 },199 {200 "role": "user",201 "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : " A woman is dancing, HD footage, close-up"',202 },203 {204 "role": "assistant",205 "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.",206 },207 {208 "role": "user",209 "content": f'Create an imaginative video descriptive caption or modify an earlier caption in ENGLISH for the user input: "{text}"',210 },211 ],212 model="glm-4-plus",213 temperature=0.01,214 top_p=0.7,215 stream=False,216 max_tokens=200,217 )218 if response.choices:219 return response.choices[0].message.content220 return prompt221 222 223def infer(224 prompt: str,225 image_input: str,226 video_input: str,227 video_strenght: float,228 num_inference_steps: int,229 guidance_scale: float,230 seed: int = -1,231 progress=gr.Progress(track_tqdm=True),232):233 if seed == -1:234 seed = random.randint(0, 2**8 - 1)235 236 if video_input is not None:237 video = load_video(video_input)[:49] # Limit to 49 frames238 pipe_video = CogVideoXVideoToVideoPipeline.from_pretrained(239 "THUDM/CogVideoX-5b",240 transformer=pipe.transformer,241 vae=pipe.vae,242 scheduler=pipe.scheduler,243 tokenizer=pipe.tokenizer,244 text_encoder=pipe.text_encoder,245 torch_dtype=torch.bfloat16,246 ).to(device)247 video_pt = pipe_video(248 video=video,249 prompt=prompt,250 num_inference_steps=num_inference_steps,251 num_videos_per_prompt=1,252 strength=video_strenght,253 use_dynamic_cfg=True,254 output_type="pt",255 guidance_scale=guidance_scale,256 generator=torch.Generator(device="cpu").manual_seed(seed),257 ).frames258 pipe_video.to("cpu")259 del pipe_video260 gc.collect()261 torch.cuda.empty_cache()262 elif image_input is not None:263 pipe_image = CogVideoXImageToVideoPipeline.from_pretrained(264 "THUDM/CogVideoX-5b-I2V",265 transformer=i2v_transformer,266 vae=pipe.vae,267 scheduler=pipe.scheduler,268 tokenizer=pipe.tokenizer,269 text_encoder=pipe.text_encoder,270 torch_dtype=torch.bfloat16,271 ).to(device)272 image_input = Image.fromarray(image_input).resize(size=(720, 480)) # Convert to PIL273 image = load_image(image_input)274 video_pt = pipe_image(275 image=image,276 prompt=prompt,277 num_inference_steps=num_inference_steps,278 num_videos_per_prompt=1,279 use_dynamic_cfg=True,280 output_type="pt",281 guidance_scale=guidance_scale,282 generator=torch.Generator(device="cpu").manual_seed(seed),283 ).frames284 pipe_image.to("cpu")285 del pipe_image286 gc.collect()287 torch.cuda.empty_cache()288 else:289 pipe.to(device)290 video_pt = pipe(291 prompt=prompt,292 num_videos_per_prompt=1,293 num_inference_steps=num_inference_steps,294 num_frames=49,295 use_dynamic_cfg=True,296 output_type="pt",297 guidance_scale=guidance_scale,298 generator=torch.Generator(device="cpu").manual_seed(seed),299 ).frames300 pipe.to("cpu")301 gc.collect()302 return (video_pt, seed)303 304 305def convert_to_gif(video_path):306 clip = mp.VideoFileClip(video_path)307 clip = clip.set_fps(8)308 clip = clip.resize(height=240)309 gif_path = video_path.replace(".mp4", ".gif")310 clip.write_gif(gif_path, fps=8)311 return gif_path312 313 314def delete_old_files():315 while True:316 now = datetime.now()317 cutoff = now - timedelta(minutes=10)318 directories = ["./output", "./gradio_tmp"]319 320 for directory in directories:321 for filename in os.listdir(directory):322 file_path = os.path.join(directory, filename)323 if os.path.isfile(file_path):324 file_mtime = datetime.fromtimestamp(os.path.getmtime(file_path))325 if file_mtime < cutoff:326 os.remove(file_path)327 time.sleep(600)328 329 330threading.Thread(target=delete_old_files, daemon=True).start()331examples_videos = [["example_videos/horse.mp4"], ["example_videos/kitten.mp4"], ["example_videos/train_running.mp4"]]332examples_images = [["example_images/beach.png"], ["example_images/street.png"], ["example_images/camping.png"]]333 334with gr.Blocks() as demo:335 gr.Markdown("""336 <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">337 CogVideoX-5B Huggingface Space🤗338 </div>339 <div style="text-align: center;">340 <a href="https://huggingface.co/THUDM/CogVideoX-5B">🤗 5B(T2V) Model Hub</a> |341 <a href="https://huggingface.co/THUDM/CogVideoX-5B-I2V">🤗 5B(I2V) Model Hub</a> |342 <a href="https://github.com/THUDM/CogVideo">🌐 Github</a> |343 <a href="https://arxiv.org/pdf/2408.06072">📜 arxiv </a>344 </div>345 <div style="text-align: center;display: flex;justify-content: center;align-items: center;margin-top: 1em;margin-bottom: .5em;">346 <span>If the Space is too busy, duplicate it to use privately</span>347 <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="348 margin-left: .75em;349 "></a>350 </div>351 <div style="text-align: center; font-size: 15px; font-weight: bold; color: red; margin-bottom: 20px;">352 ⚠️ This demo is for academic research and experiential use only. 353 </div>354 """)355 with gr.Row():356 with gr.Column():357 with gr.Accordion("I2V: Image Input (cannot be used simultaneously with video input)", open=False):358 image_input = gr.Image(label="Input Image (will be cropped to 720 * 480)")359 examples_component_images = gr.Examples(examples_images, inputs=[image_input], cache_examples=False)360 with gr.Accordion("V2V: Video Input (cannot be used simultaneously with image input)", open=False):361 video_input = gr.Video(label="Input Video (will be cropped to 49 frames, 6 seconds at 8fps)")362 strength = gr.Slider(0.1, 1.0, value=0.8, step=0.01, label="Strength")363 examples_component_videos = gr.Examples(examples_videos, inputs=[video_input], cache_examples=False)364 prompt = gr.Textbox(label="Prompt (Less than 200 Words)", placeholder="Enter your prompt here", lines=5)365 366 with gr.Row():367 gr.Markdown(368 "✨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."369 )370 enhance_button = gr.Button("✨ Enhance Prompt(Optional)")371 with gr.Group():372 with gr.Column():373 with gr.Row():374 seed_param = gr.Number(375 label="Inference Seed (Enter a positive number, -1 for random)", value=-1376 )377 with gr.Row():378 enable_scale = gr.Checkbox(label="Super-Resolution (720 × 480 -> 2880 × 1920)", value=False)379 enable_rife = gr.Checkbox(label="Frame Interpolation (8fps -> 16fps)", value=False)380 gr.Markdown(381 "✨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."382 )383 384 generate_button = gr.Button("🎬 Generate Video")385 386 with gr.Column():387 video_output = gr.Video(label="CogVideoX Generate Video", width=720, height=480)388 with gr.Row():389 download_video_button = gr.File(label="📥 Download Video", visible=False)390 download_gif_button = gr.File(label="📥 Download GIF", visible=False)391 seed_text = gr.Number(label="Seed Used for Video Generation", visible=False)392 393 gr.Markdown("""394 <table border="0" style="width: 100%; text-align: left; margin-top: 20px;">395 <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">396 🎥 Video Gallery397 </div>398 <tr>399 <td style="width: 25%; vertical-align: top; font-size: 0.9em;">400 <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>401 </td>402 <td style="width: 25%; vertical-align: top;">403 <video src="https://github.com/user-attachments/assets/cf5953ea-96d3-48fd-9907-c4708752c714" width="100%" controls autoplay loop></video>404 </td>405 <td style="width: 25%; vertical-align: top; font-size: 0.9em;">406 <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>407 </td>408 <td style="width: 25%; vertical-align: top;">409 <video src="https://github.com/user-attachments/assets/fe0a78e6-b669-4800-8cf0-b5f9b5145b52" width="100%" controls autoplay loop></video>410 </td>411 </tr>412 <tr>413 <td style="width: 25%; vertical-align: top; font-size: 0.9em;">414 <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>415 </td>416 <td style="width: 25%; vertical-align: top;">417 <video src="https://github.com/user-attachments/assets/c182f606-8f8c-421d-b414-8487070fcfcb" width="100%" controls autoplay loop></video>418 </td>419 <td style="width: 25%; vertical-align: top; font-size: 0.9em;">420 <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>421 </td>422 <td style="width: 25%; vertical-align: top;">423 <video src="https://github.com/user-attachments/assets/7db2bbce-194d-434d-a605-350254b6c298" width="100%" controls autoplay loop></video>424 </td>425 </tr>426 <tr>427 <td style="width: 25%; vertical-align: top; font-size: 0.9em;">428 <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>429 </td>430 <td style="width: 25%; vertical-align: top;">431 <video src="https://github.com/user-attachments/assets/62b01046-8cab-44cc-bd45-4d965bb615ec" width="100%" controls autoplay loop></video>432 </td>433 <td style="width: 25%; vertical-align: top; font-size: 0.9em;">434 <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>435 </td>436 <td style="width: 25%; vertical-align: top;">437 <video src="https://github.com/user-attachments/assets/d78e552a-4b3f-4b81-ac3f-3898079554f6" width="100%" controls autoplay loop></video>438 </td>439 </tr>440 <tr>441 <td style="width: 25%; vertical-align: top; font-size: 0.9em;">442 <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>443 </td>444 <td style="width: 25%; vertical-align: top;">445 <video src="https://github.com/user-attachments/assets/30894f12-c741-44a2-9e6e-ddcacc231e5b" width="100%" controls autoplay loop></video>446 </td>447 <td style="width: 25%; vertical-align: top; font-size: 0.9em;">448 <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>449 </td>450 <td style="width: 25%; vertical-align: top;">451 <video src="https://github.com/user-attachments/assets/926575ca-7150-435b-a0ff-4900a963297b" width="100%" controls autoplay loop></video>452 </td>453 </tr>454 </table>455 """)456 457 def generate(458 prompt,459 image_input,460 video_input,461 video_strength,462 seed_value,463 scale_status,464 rife_status,465 progress=gr.Progress(track_tqdm=True)466 ):467 latents, seed = infer(468 prompt,469 image_input,470 video_input,471 video_strength,472 num_inference_steps=50, # NOT Changed473 guidance_scale=7.0, # NOT Changed474 seed=seed_value,475 progress=progress,476 )477 if scale_status:478 latents = utils.upscale_batch_and_concatenate(upscale_model, latents, device)479 if rife_status:480 latents = rife_inference_with_latents(frame_interpolation_model, latents)481 482 batch_size = latents.shape[0]483 batch_video_frames = []484 for batch_idx in range(batch_size):485 pt_image = latents[batch_idx]486 pt_image = torch.stack([pt_image[i] for i in range(pt_image.shape[0])])487 488 image_np = VaeImageProcessor.pt_to_numpy(pt_image)489 image_pil = VaeImageProcessor.numpy_to_pil(image_np)490 batch_video_frames.append(image_pil)491 492 video_path = utils.save_video(batch_video_frames[0], fps=math.ceil((len(batch_video_frames[0]) - 1) / 6))493 video_update = gr.update(visible=True, value=video_path)494 gif_path = convert_to_gif(video_path)495 gif_update = gr.update(visible=True, value=gif_path)496 seed_update = gr.update(visible=True, value=seed)497 498 return video_path, video_update, gif_update, seed_update499 500 def enhance_prompt_func(prompt):501 return convert_prompt(prompt, retry_times=1)502 503 generate_button.click(504 generate,505 inputs=[prompt, image_input, video_input, strength, seed_param, enable_scale, enable_rife],506 outputs=[video_output, download_video_button, download_gif_button, seed_text],507 )508 509 enhance_button.click(enhance_prompt_func, inputs=[prompt], outputs=[prompt])510 video_input.upload(resize_if_unfit, inputs=[video_input], outputs=[video_input])511 512@app.get("/health")513def health_check():514 """Simple health check endpoint"""515 return {"status": "OK"}516 517 518if __name__ == "__main__":519 demo.queue(max_size=15)520 demo.launch()521 