"""
THis is the main file for the gradio web demo. It uses the CogVideoX-2B model to generate videos gradio web demo.
set environment variable OPENAI_API_KEY to use the OpenAI API to enhance the prompt.
Usage:
OpenAI_API_KEY=your_openai_api_key OpenAI_BASE_URL=https://api.openai.com/v1 python inference/gradio_web_demo.py
"""
import math
import os
import random
import threading
import time
import cv2
import tempfile
import imageio_ffmpeg
import gradio as gr
import torch
from PIL import Image
from diffusers import (
CogVideoXPipeline,
CogVideoXDPMScheduler,
CogVideoXVideoToVideoPipeline,
CogVideoXImageToVideoPipeline,
CogVideoXTransformer3DModel,
)
from diffusers.utils import export_to_video, load_video, load_image
from datetime import datetime, timedelta
from diffusers.image_processor import VaeImageProcessor
from openai import OpenAI
import moviepy.editor as mp
import utils
from rife_model import load_rife_model, rife_inference_with_latents
from huggingface_hub import hf_hub_download, snapshot_download
import gc
pipe = None
pipe_image = None
pipe_video = None
device = "cuda" if torch.cuda.is_available() else "cpu"
hf_hub_download(repo_id="ai-forever/Real-ESRGAN", filename="RealESRGAN_x4.pth", local_dir="model_real_esran")
snapshot_download(repo_id="AlexWortega/RIFE", local_dir="model_rife")
initialized = None
def init(name, image_input, video_input, dtype_str, full_gpu):
if image_input is not None:
# img2vid
init_img2vid(name, dtype_str, full_gpu)
elif video_input is not None:
# vid2vid
init_vid2vid(name, dtype_str, full_gpu)
else:
# txt2vid
init_txt2vid(name, dtype_str, full_gpu)
def init_core(name, dtype_str):
global pipe
torch.cuda.empty_cache()
if dtype_str == "bfloat16":
dtype = torch.bfloat16
elif dtype_str == "float16":
dtype = torch.float16
if pipe == None:
pipe = CogVideoXPipeline.from_pretrained(name, torch_dtype=dtype).to(device)
pipe.scheduler = CogVideoXDPMScheduler.from_config(pipe.scheduler.config, timestep_spacing="trailing")
return dtype
def optimize(_pipe, full_gpu):
print('optimizing')
_pipe.vae.enable_slicing()
_pipe.vae.enable_tiling()
if not full_gpu:
_pipe.enable_model_cpu_offload()
_pipe.enable_sequential_cpu_offload()
print('done')
# 1. initialize core pipe
def init_txt2vid(name, dtype_str, full_gpu):
global pipe
dtype = init_core(name, dtype_str)
optimize(pipe, full_gpu)
# 2. initialize vid2vid pipe
def init_vid2vid(name, dtype_str, full_gpu):
global pipe
global pipe_video
dtype = init_core(name, dtype_str)
if pipe_video == None:
pipe_video = CogVideoXVideoToVideoPipeline.from_pretrained(
name,
transformer=pipe.transformer,
vae=pipe.vae,
scheduler=pipe.scheduler,
tokenizer=pipe.tokenizer,
text_encoder=pipe.text_encoder,
torch_dtype=dtype
)#.to(device)
optimize(pipe_video, full_gpu)
# 3. initialize img2vid pipe
def init_img2vid(name, dtype_str, full_gpu):
global pipe
global pipe_image
torch.cuda.empty_cache()
print("init cogvideox pipeline")
if dtype_str == "bfloat16":
dtype = torch.bfloat16
elif dtype_str == "float16":
dtype = torch.float16
core_pipe = CogVideoXPipeline.from_pretrained(name, torch_dtype=dtype).to("cpu")
core_pipe.scheduler = CogVideoXDPMScheduler.from_config(core_pipe.scheduler.config, timestep_spacing="trailing")
if pipe_image == None:
print("init i2v_transformer pipeline")
i2v_transformer = CogVideoXTransformer3DModel.from_pretrained("THUDM/CogVideoX-5b-I2V", subfolder="transformer", torch_dtype=dtype).to("cpu")
print("init cogvideox image2video pipeline")
pipe_image = CogVideoXImageToVideoPipeline.from_pretrained(
"THUDM/CogVideoX-5b-I2V",
transformer=i2v_transformer,
vae=core_pipe.vae,
scheduler=core_pipe.scheduler,
tokenizer=core_pipe.tokenizer,
text_encoder=core_pipe.text_encoder,
torch_dtype=dtype
)#.to(device)
print("done")
optimize(pipe_image, full_gpu)
os.makedirs("./output", exist_ok=True)
os.makedirs("./gradio_tmp", exist_ok=True)
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.
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.
There are a few rules to follow:
You will only ever output a single video description per user request.
When modifications are requested , you should not simply make the description longer . You should refactor the entire description to integrate the suggestions.
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.
Video descriptions must have the same num of words as examples below. Extra words will be ignored.
"""
def convert_prompt(prompt: str, retry_times: int = 3) -> str:
if not os.environ.get("OPENAI_API_KEY"):
return prompt
client = OpenAI()
text = prompt.strip()
for i in range(retry_times):
response = client.chat.completions.create(
messages=[
{"role": "system", "content": sys_prompt},
{
"role": "user",
"content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "a girl is on the beach"',
},
{
"role": "assistant",
"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.",
},
{
"role": "user",
"content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "A man jogging on a football field"',
},
{
"role": "assistant",
"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.",
},
{
"role": "user",
"content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : " A woman is dancing, HD footage, close-up"',
},
{
"role": "assistant",
"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.",
},
{
"role": "user",
"content": f'Create an imaginative video descriptive caption or modify an earlier caption in ENGLISH for the user input: "{text}"',
},
],
model="gpt-4o",
temperature=0.01,
top_p=0.7,
stream=False,
max_tokens=250,
)
if response.choices:
return response.choices[0].message.content
return prompt
def infer(
name: str,
prompt: str,
image_input: str,
video_input: str,
strength: float,
num_inference_steps: int,
guidance_scale: float,
dtype: str,
full_gpu: bool,
seed: int = -1,
progress=gr.Progress(track_tqdm=True),
):
global pipe
global pipe_video
global pipe_image
init(name, image_input, video_input, dtype, full_gpu)
if seed == -1:
seed = random.randint(0, 2**8 - 1)
if video_input is not None:
resized_video_input = resize_video(video_input)
video = load_video(resized_video_input)[:49] # Limit to 49 frames
video_pt = pipe_video(
video=video,
prompt=prompt,
num_inference_steps=num_inference_steps,
num_videos_per_prompt=1,
strength=strength,
use_dynamic_cfg=True,
output_type="pt",
guidance_scale=guidance_scale,
generator=torch.Generator(device="cpu").manual_seed(seed),
).frames
# pipe_video = None
# pipe = None
# gc.collect()
torch.cuda.empty_cache()
elif image_input is not None:
image_input = resize_image(Image.fromarray(image_input), (720, 480))
image = load_image(image_input)
video_pt = pipe_image(
image=image,
prompt=prompt,
num_inference_steps=num_inference_steps,
num_videos_per_prompt=1,
use_dynamic_cfg=True,
output_type="pt",
guidance_scale=guidance_scale,
generator=torch.Generator(device="cpu").manual_seed(seed),
).frames
# pipe_image = None
# pipe = None
# gc.collect()
torch.cuda.empty_cache()
else:
video_pt = pipe(
prompt=prompt,
num_videos_per_prompt=1,
num_inference_steps=num_inference_steps,
num_frames=49,
use_dynamic_cfg=True,
output_type="pt",
guidance_scale=guidance_scale,
generator=torch.Generator(device="cpu").manual_seed(seed),
).frames
# pipe = None
# gc.collect()
torch.cuda.empty_cache()
return (video_pt, seed)
def resize_image(img, target_size):
# Unpack the target size
target_width, target_height = target_size
# Resize the image to match the target height while maintaining the aspect ratio
img_ratio = img.width / img.height
new_height = target_height
new_width = int(new_height * img_ratio)
# Resize the image
resized_img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
# Create a black background with the target size
background = Image.new("RGB", target_size, (0, 0, 0))
# Calculate the position to paste the image (centered horizontally)
x_offset = (target_width - new_width) // 2
y_offset = 0 # No offset for vertical since we match height
# Paste the resized image onto the black background
background.paste(resized_img, (x_offset, y_offset))
return background
def resize_video(input_path, target_size=(720, 480)):
# Load the video clip
clip = mp.VideoFileClip(input_path)
# Remove audio
clip = clip.without_audio()
# Calculate the scaling factor
width_ratio = target_size[0] / clip.w
height_ratio = target_size[1] / clip.h
scale_factor = min(width_ratio, height_ratio)
# Resize the clip
resized_clip = clip.resize(scale_factor)
# If the resized clip is smaller than the target size, pad it
if resized_clip.w < target_size[0] or resized_clip.h < target_size[1]:
resized_clip = resized_clip.on_color(
size=target_size,
color=(0, 0, 0), # Black padding
pos='center'
)
# Save to a temporary file
input_dir = os.path.dirname(input_path)
temp_output = os.path.join(input_dir, "temp_video.mp4")
resized_clip.write_videofile(temp_output, fps=8)
# Close the clips
clip.close()
resized_clip.close()
return temp_output
def save_video(tensor):
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
video_path = f"./output/{timestamp}.mp4"
os.makedirs(os.path.dirname(video_path), exist_ok=True)
export_to_video(tensor, video_path)
return video_path
def convert_to_gif(video_path):
clip = mp.VideoFileClip(video_path)
clip = clip.set_fps(8)
clip = clip.resize(height=240)
gif_path = video_path.replace(".mp4", ".gif")
clip.write_gif(gif_path, fps=8)
return gif_path
def delete_old_files():
while True:
now = datetime.now()
cutoff = now - timedelta(minutes=10)
directories = ["./output", "./gradio_tmp"]
for directory in directories:
for filename in os.listdir(directory):
file_path = os.path.join(directory, filename)
if os.path.isfile(file_path):
file_mtime = datetime.fromtimestamp(os.path.getmtime(file_path))
if file_mtime < cutoff:
os.remove(file_path)
time.sleep(600)
def refresh_generated_videos():
time.sleep(2)
html = generated_videos()
return html
def generated_videos():
try:
files = os.listdir("output")
vids = [os.path.join("output", item) for item in files if item.endswith(".mp4")]
vids.sort(key=lambda file: os.path.getctime(file), reverse=True)
vids = vids[:50]
vidhtml = ""
for vid in vids:
vidhtml = vidhtml + f""
return vidhtml
except Exception as e:
return ""
#threading.Thread(target=delete_old_files, daemon=True).start()
css="""
.info{ padding: 15px; font-weight: bold; background: rgba(0, 0, 0, 0.04); }
.btn { background: royalblue; color: white; }
"""
with gr.Blocks(fill_width=True, fill_height=True, css=css) as demo:
# gr.Markdown("""
#
# ⚠️ This demo is for academic research and experiential use only.
# Users should strictly adhere to local laws and ethics.
#
# """)
with gr.Row():
with gr.Column(scale=7):
with gr.Tabs(selected=0) as tabs:
with gr.TabItem("text-to-video", id=0):
gr.HTML("
Generate a video from a prompt
")
with gr.Row():
with gr.Column():
with gr.Row():
generate_button = gr.Button("Generate Video", elem_id="gen1", elem_classes='btn')
#cancel_button = gr.Button("Cancel", visible=False)
forever1 = gr.Checkbox(label="generate forever", value=False, elem_id='forever1')
prompt = gr.Textbox(label="Prompt (Less than 200 Words. The more detailed the better.)", placeholder="Enter your prompt here", lines=5)
image = gr.Image(visible=False)
video = gr.Video(visible=False)
strength = gr.Number(value=0.8, minimum=0.1, maximum=1.0, step=0.01, label="Strength", visible=False)
with gr.Row():
gr.Markdown(
"✨ To enhance the prompt, either set the OPENAI_API_KEY variable from the Configure menu (if you have an OpenAI API key), or just use chatgpt to enhance the prompt manually (Recommended)",
)
enhance_button = gr.Button("✨ Enhance Prompt(Optional)")
with gr.Row():
model_choice = gr.Dropdown(["THUDM/CogVideoX-2b", "THUDM/CogVideoX-5b"], value="THUDM/CogVideoX-2b", label="Model")
with gr.Row():
num_inference_steps = gr.Number(label="Inference Steps", value=50)
guidance_scale = gr.Number(label="Guidance Scale", value=6.0)
with gr.Row():
dtype_choice = gr.Radio(["bfloat16", "float16"], label="dtype (older machines may not support bfloat16. try float16 if bfloat16 doesn't work)", value="bfloat16")
with gr.Row():
seed_param = gr.Number(
label="Inference Seed (Enter a positive number, -1 for random)", value=-1
)
with gr.Row():
enable_scale = gr.Checkbox(label="Super-Resolution (720 × 480 -> 2880 × 1920)", value=False)
enable_rife = gr.Checkbox(label="Frame Interpolation (8fps -> 16fps)", value=False, visible=False)
full_gpu = gr.Checkbox(label="Don't use CPU offload", info="If you have a lot of GPU VRAM, check this option for faster generation", value=False)
with gr.Column():
video_output = gr.Video(label="Generated", width=720, height=480, interactive=False)
with gr.Row():
download_video_button = gr.File(label="📥 Download Video", visible=False)
download_gif_button = gr.File(label="📥 Download GIF", visible=False)
seed_text = gr.Number(label="Seed used for generation", visible=False)
with gr.Row():
send_to_vid2vid_button = gr.Button("Send to video-to-video", visible=False)
send_to_extendvid_button = gr.Button("Send to extend-video", visible=False)
gr.Markdown("""
Demo Videos with 50 Inference Steps and 6.0 Guidance Scale.
A detailed wooden toy ship with intricately carved masts and sails is seen gliding smoothly over a plush, blue carpet that mimics the waves of the sea. The ship's hull is painted a rich brown, with tiny windows. The carpet, soft and textured, provides a perfect backdrop, resembling an oceanic expanse. Surrounding the ship are various other toys and children's items, hinting at a playful environment. The scene captures the innocence and imagination of childhood, with the toy ship's journey symbolizing endless adventures in a whimsical, indoor setting.
The camera follows behind a white vintage SUV with a black roof rack as it speeds up a steep dirt road surrounded by pine trees on a steep mountain slope, dust kicks up from its tires, the sunlight shines on the SUV as it speeds along the dirt road, casting a warm glow over the scene. The dirt road curves gently into the distance, with no other cars or vehicles in sight. The trees on either side of the road are redwoods, with patches of greenery scattered throughout. The car is seen from the rear following the curve with ease, making it seem as if it is on a rugged drive through the rugged terrain. The dirt road itself is surrounded by steep hills and mountains, with a clear blue sky above with wispy clouds.
A street artist, clad in a worn-out denim jacket and a colorful bandana, stands before a vast concrete wall in the heart, holding a can of spray paint, spray-painting a colorful bird on a mottled wall.
In the haunting backdrop of a war-torn city, where ruins and crumbled walls tell a story of devastation, a poignant close-up frames a young girl. Her face is smudged with ash, a silent testament to the chaos around her. Her eyes glistening with a mix of sorrow and resilience, capturing the raw emotion of a world that has lost its innocence to the ravages of conflict.
""")
with gr.TabItem("video-to-video", id=1):
gr.HTML("
Transform a video with a prompt
")
with gr.Row():
with gr.Column():
with gr.Row():
generate_button2 = gr.Button("Generate Video", elem_id="gen2", elem_classes='btn')
#cancel_button2 = gr.Button("Cancel", visible=False)
forever2 = gr.Checkbox(label="generate forever", value=False, elem_id='forever2')
image2 = gr.Image(visible=False)
video2 = gr.Video(label="Driving Video")
full_gpu2 = gr.Checkbox(label="Use Full GPU", info="If you have a lot of GPU VRAM, check this option for faster generation", value=False, visible=False)
strength2 = gr.Number(value=0.8, minimum=0.1, maximum=1.0, step=0.01, label="Strength")
prompt2 = gr.Textbox(label="Prompt (Less than 200 Words. The more detailed the better.)", placeholder="Enter your prompt here", lines=5)
with gr.Row():
gr.Markdown(
"✨ To enhance the prompt, either set the OPENAI_API_KEY variable from the Configure menu (if you have an OpenAI API key), or just use chatgpt to enhance the prompt manually (Recommended)",
)
enhance_button2 = gr.Button("✨ Enhance Prompt(Optional)")
with gr.Row():
model_choice2 = gr.Dropdown(["THUDM/CogVideoX-2b", "THUDM/CogVideoX-5b"], value="THUDM/CogVideoX-2b", label="Model")
with gr.Row():
num_inference_steps2 = gr.Number(label="Inference Steps", value=50)
guidance_scale2 = gr.Number(label="Guidance Scale", value=6.0)
with gr.Row():
dtype_choice2 = gr.Radio(["bfloat16", "float16"], label="dtype (older machines may not support bfloat16. try float16 if bfloat16 doesn't work)", value="bfloat16")
with gr.Row():
seed_param2 = gr.Number(
label="Inference Seed (Enter a positive number, -1 for random)", value=-1
)
with gr.Row():
enable_scale2 = gr.Checkbox(label="Super-Resolution (720 × 480 -> 2880 × 1920)", value=False)
enable_rife2 = gr.Checkbox(label="Frame Interpolation (8fps -> 16fps)", value=False, visible=False)
with gr.Column():
video_output2 = gr.Video(label="Generated", width=720, height=480, interactive=False)
with gr.Row():
download_video_button2 = gr.File(label="📥 Download Video", visible=False)
download_gif_button2 = gr.File(label="📥 Download GIF", visible=False)
seed_text2 = gr.Number(label="Seed used for generation", visible=False)
with gr.Row():
send_to_vid2vid_button2 = gr.Button("Send to video-to-video", visible=False)
send_to_extendvid_button2 = gr.Button("Send to extend-video", visible=False)
with gr.TabItem("image-to-video", id=2):
gr.HTML("
Generate 6 second videos starting from an image
")
with gr.Row():
with gr.Column():
with gr.Row():
generate_button3 = gr.Button("Generate Video", elem_id="gen3", elem_classes='btn')
#cancel_button3 = gr.Button("Cancel", visible=False)
forever3 = gr.Checkbox(label="generate forever", value=False, elem_id="forever3")
image3 = gr.Image(label="Driving Image")
video3 = gr.Video(visible=False)
full_gpu3 = gr.Checkbox(label="Use Full GPU", info="If you have a lot of GPU VRAM, check this option for faster generation", value=False, visible=False)
strength3 = gr.Number(value=0.8, minimum=0.1, maximum=1.0, step=0.01, label="Strength")
prompt3 = gr.Textbox(label="Prompt (Less than 200 Words. The more detailed the better.)", placeholder="Enter your prompt here", lines=5)
with gr.Row():
gr.Markdown(
"✨ To enhance the prompt, either set the OPENAI_API_KEY variable from the Configure menu (if you have an OpenAI API key), or just use chatgpt to enhance the prompt manually (Recommended)",
)
enhance_button3 = gr.Button("✨ Enhance Prompt(Optional)")
with gr.Row():
model_choice3 = gr.Dropdown(["THUDM/CogVideoX-2b", "THUDM/CogVideoX-5b"], value="THUDM/CogVideoX-5b", label="Model", visible=False)
with gr.Row():
num_inference_steps3 = gr.Number(label="Inference Steps", value=50)
guidance_scale3 = gr.Number(label="Guidance Scale", value=6.0)
with gr.Row():
dtype_choice3 = gr.Radio(["bfloat16", "float16"], label="dtype (older machines may not support bfloat16. try float16 if bfloat16 doesn't work)", value="bfloat16")
with gr.Row():
seed_param3 = gr.Number(
label="Inference Seed (Enter a positive number, -1 for random)", value=-1
)
with gr.Row():
enable_scale3 = gr.Checkbox(label="Super-Resolution (720 × 480 -> 2880 × 1920)", value=False)
enable_rife3 = gr.Checkbox(label="Frame Interpolation (8fps -> 16fps)", value=False, visible=False)
with gr.Column():
video_output3 = gr.Video(label="Generated", width=720, height=480, interactive=False)
with gr.Row():
download_video_button3 = gr.File(label="📥 Download Video", visible=False)
download_gif_button3 = gr.File(label="📥 Download GIF", visible=False)
seed_text3 = gr.Number(label="Seed used for generation", visible=False)
with gr.Row():
send_to_vid2vid_button3 = gr.Button("Send to video-to-video", visible=False)
send_to_extendvid_button3 = gr.Button("Send to extend-video", visible=False)
with gr.TabItem("extend-video", id=3):
gr.HTML("