svjack commited on
Commit
ef41b32
·
verified ·
1 Parent(s): fff6dc8

Upload 10 files

Browse files
Files changed (10) hide show
  1. cogvideox_i2v_colab.py +78 -0
  2. cogvideox_t2v_colab.py +91 -0
  3. cogvideox_v2v_colab.py +100 -0
  4. i2v_app.py +333 -0
  5. i2v_app_t4.py +346 -0
  6. readme.py +429 -0
  7. t2v_app.py +311 -0
  8. t2v_app_t4.py +329 -0
  9. v2v_app.py +332 -0
  10. v2v_app_t4.py +352 -0
cogvideox_i2v_colab.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """CogVideoX-I2V-Colab.ipynb
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/17CqYCqSwz39nZAX2YyonDxosVKUZGzcX
8
+
9
+ ## CogVideoX Image-to-Video
10
+
11
+ This notebook demonstrates how to run [CogVideoX-5b-I2V](https://huggingface.co/THUDM/CogVideoX-5b-I2V) with 🧨 Diffusers on a free-tier Colab GPU.
12
+
13
+ Additional resources:
14
+ - [Docs](https://huggingface.co/docs/diffusers/en/api/pipelines/cogvideox)
15
+ - [Quantization with TorchAO](https://github.com/sayakpaul/diffusers-torchao/)
16
+ - [Quantization with Quanto](https://gist.github.com/a-r-r-o-w/31be62828b00a9292821b85c1017effa)
17
+
18
+ Note: If, for whatever reason, you randomly get an OOM error, give it a try on Kaggle T4 instances instead. I've found that Colab free-tier T4 can be unreliable at times. Sometimes, the notebook will run smoothly, but other times it will crash with an error 🤷🏻‍♂️
19
+
20
+ #### Install the necessary requirements
21
+ """
22
+
23
+ !pip install diffusers transformers hf_transfer
24
+
25
+ # !pip install git+https://github.com/huggingface/accelerate
26
+ !pip install accelerate==0.33.0
27
+
28
+ """#### Import required libraries
29
+
30
+ The following block is optional but if enabled, downloading models from the HF Hub will be much faster
31
+ """
32
+
33
+ import os
34
+ os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
35
+
36
+ import torch
37
+ from diffusers import AutoencoderKLCogVideoX, CogVideoXImageToVideoPipeline, CogVideoXTransformer3DModel
38
+ from diffusers.utils import export_to_video, load_image
39
+ from transformers import T5EncoderModel
40
+
41
+ """#### Load models and create pipeline
42
+
43
+ Note: `bfloat16`, which is the recommended dtype for running "CogVideoX-5b-I2V" will cause OOM errors due to lack of efficient support on Turing GPUs.
44
+
45
+ Therefore, we must use `float16`, which might result in poorer generation quality. The recommended solution is to use Ampere or above GPUs, which also support efficient quantization kernels from [TorchAO](https://github.com/pytorch/ao) :(
46
+ """
47
+
48
+ model_id = "THUDM/CogVideoX-5b-I2V"
49
+
50
+ transformer = CogVideoXTransformer3DModel.from_pretrained(model_id, subfolder="transformer", torch_dtype=torch.float16)
51
+ text_encoder = T5EncoderModel.from_pretrained(model_id, subfolder="text_encoder", torch_dtype=torch.float16)
52
+ vae = AutoencoderKLCogVideoX.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float16)
53
+
54
+ # Create pipeline and run inference
55
+ pipe = CogVideoXImageToVideoPipeline.from_pretrained(
56
+ model_id,
57
+ text_encoder=text_encoder,
58
+ transformer=transformer,
59
+ vae=vae,
60
+ torch_dtype=torch.float16,
61
+ )
62
+
63
+ """#### Enable memory optimizations
64
+
65
+ Note that sequential cpu offloading is necessary for being able to run the model on Turing or lower architectures. It aggressively maintains everything on the CPU and only moves the currently executing nn.Module to the GPU. This saves a lot of VRAM but adds a lot of overhead for inference, making generations extremely slow (1 hour+). Unfortunately, this is the only solution for running the model on Colab until efficient kernels are supported.
66
+ """
67
+
68
+ pipe.enable_sequential_cpu_offload()
69
+ # pipe.vae.enable_tiling()
70
+
71
+ """#### Generate!"""
72
+
73
+ prompt = "An astronaut hatching from an egg, on the surface of the moon, the darkness and depth of space realised in the background. High quality, ultrarealistic detail and breath-taking movie-like camera shot."
74
+ image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg")
75
+
76
+ video = pipe(image=image, prompt=prompt, guidance_scale=6, use_dynamic_cfg=True, num_inference_steps=50).frames[0]
77
+
78
+ export_to_video(video, "output.mp4", fps=8)
cogvideox_t2v_colab.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """CogVideoX-T2V-Colab.ipynb
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1pCe5s0bC_xuXbBlpvIH1z0kfdTLQPzCS
8
+
9
+ ## CogVideoX Text-to-Video
10
+
11
+ This notebook demonstrates how to run [CogVideoX-2b](https://huggingface.co/THUDM/CogVideoX-2b) and [CogVideoX-5b](https://huggingface.co/THUDM/CogVideoX-5b) with 🧨 Diffusers on a free-tier Colab GPU.
12
+
13
+ Additional resources:
14
+ - [Docs](https://huggingface.co/docs/diffusers/en/api/pipelines/cogvideox)
15
+ - [Quantization with TorchAO](https://github.com/sayakpaul/diffusers-torchao/)
16
+ - [Quantization with Quanto](https://gist.github.com/a-r-r-o-w/31be62828b00a9292821b85c1017effa)
17
+
18
+ Note: If, for whatever reason, you randomly get an OOM error, give it a try on Kaggle T4 instances instead. I've found that Colab free-tier T4 can be unreliable at times. Sometimes, the notebook will run smoothly, but other times it will crash with an error 🤷🏻‍♂️
19
+
20
+ #### Install the necessary requirements
21
+ """
22
+
23
+ !pip install diffusers transformers hf_transfer
24
+
25
+ # !pip install git+https://github.com/huggingface/accelerate
26
+ !pip install accelerate==0.33.0
27
+
28
+ """#### Import required libraries
29
+
30
+ The following block is optional but if enabled, downloading models from the HF Hub will be much faster
31
+ """
32
+
33
+ import os
34
+ os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
35
+
36
+ import torch
37
+ from diffusers import AutoencoderKLCogVideoX, CogVideoXPipeline, CogVideoXTransformer3DModel
38
+ from diffusers.utils import export_to_video
39
+ from transformers import T5EncoderModel
40
+
41
+ """#### Load models and create pipeline
42
+
43
+ Note: `bfloat16`, which is the recommended dtype for running "CogVideoX-5b" will cause OOM errors due to lack of efficient support on Turing GPUs.
44
+
45
+ Therefore, we must use `float16`, which might result in poorer generation quality. The recommended solution is to use Ampere or above GPUs, which also support efficient quantization kernels from [TorchAO](https://github.com/pytorch/ao) :(
46
+ """
47
+
48
+ # Models: "THUDM/CogVideoX-2b" or "THUDM/CogVideoX-5b"
49
+ model_id = "THUDM/CogVideoX-5b"
50
+
51
+ # Thank you [@camenduru](https://github.com/camenduru)!
52
+ # The reason for using checkpoints hosted by Camenduru instead of the original is because they exported
53
+ # with a max_shard_size of "5GB" when saving the model with `.save_pretrained`. The original converted
54
+ # model was saved with "10GB" as the max shard size, which causes the Colab CPU RAM to be insufficient
55
+ # leading to OOM (on the CPU)
56
+
57
+ transformer = CogVideoXTransformer3DModel.from_pretrained("camenduru/cogvideox-5b-float16", subfolder="transformer", torch_dtype=torch.float16)
58
+ text_encoder = T5EncoderModel.from_pretrained("camenduru/cogvideox-5b-float16", subfolder="text_encoder", torch_dtype=torch.float16)
59
+ vae = AutoencoderKLCogVideoX.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float16)
60
+
61
+ # Create pipeline and run inference
62
+ pipe = CogVideoXPipeline.from_pretrained(
63
+ model_id,
64
+ text_encoder=text_encoder,
65
+ transformer=transformer,
66
+ vae=vae,
67
+ torch_dtype=torch.float16,
68
+ )
69
+
70
+ """#### Enable memory optimizations
71
+
72
+ Note that sequential cpu offloading is necessary for being able to run the model on Turing or lower architectures. It aggressively maintains everything on the CPU and only moves the currently executing nn.Module to the GPU. This saves a lot of VRAM but adds a lot of overhead for inference, making generations extremely slow (1 hour+). Unfortunately, this is the only solution for running the model on Colab until efficient kernels are supported.
73
+ """
74
+
75
+ pipe.enable_sequential_cpu_offload()
76
+ # pipe.vae.enable_tiling()
77
+
78
+ """#### Generate!"""
79
+
80
+ prompt = (
81
+ "A panda, dressed in a small, red jacket and a tiny hat, sits on a wooden stool in a serene bamboo forest. "
82
+ "The panda's fluffy paws strum a miniature acoustic guitar, producing soft, melodic tunes. Nearby, a few other "
83
+ "pandas gather, watching curiously and some clapping in rhythm. Sunlight filters through the tall bamboo, "
84
+ "casting a gentle glow on the scene. The panda's face is expressive, showing concentration and joy as it plays. "
85
+ "The background includes a small, flowing stream and vibrant green foliage, enhancing the peaceful and magical "
86
+ "atmosphere of this unique musical performance."
87
+ )
88
+
89
+ video = pipe(prompt=prompt, guidance_scale=6, use_dynamic_cfg=True, num_inference_steps=50).frames[0]
90
+
91
+ export_to_video(video, "output.mp4", fps=8)
cogvideox_v2v_colab.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """CogVideoX-V2V-Colab
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1comfGAUJnChl5NwPuO8Ox5_6WCy4kbNN
8
+
9
+ ## CogVideoX Video-to-Video
10
+
11
+ This notebook demonstrates how to run [CogVideoX-2b](https://huggingface.co/THUDM/CogVideoX-2b) and [CogVideoX-5b](https://huggingface.co/THUDM/CogVideoX-5b) with 🧨 Diffusers on a free-tier Colab GPU.
12
+
13
+ Additional resources:
14
+ - [Docs](https://huggingface.co/docs/diffusers/en/api/pipelines/cogvideox)
15
+ - [Quantization with TorchAO](https://github.com/sayakpaul/diffusers-torchao/)
16
+ - [Quantization with Quanto](https://gist.github.com/a-r-r-o-w/31be62828b00a9292821b85c1017effa)
17
+
18
+ #### Install the necessary requirements
19
+ """
20
+
21
+ !pip install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/cu121
22
+
23
+ !pip install diffusers transformers hf_transfer
24
+
25
+ !pip install git+https://github.com/huggingface/accelerate
26
+
27
+ """#### Import required libraries
28
+
29
+ The following block is optional but if enabled, downloading models from the HF Hub will be much faster
30
+ """
31
+
32
+ !pip install imageio-ffmpeg
33
+
34
+ import os
35
+ os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
36
+
37
+ import torch
38
+ from diffusers import AutoencoderKLCogVideoX, CogVideoXVideoToVideoPipeline, CogVideoXTransformer3DModel, CogVideoXDPMScheduler
39
+ from diffusers.utils import export_to_video, load_video
40
+ from transformers import T5EncoderModel
41
+
42
+ """#### Load models and create pipeline
43
+
44
+ Note: `bfloat16`, which is the recommended dtype for running "CogVideoX-5b" will cause OOM errors due to lack of efficient support on Turing GPUs.
45
+
46
+ Therefore, we must use `float16`, which might result in poorer generation quality. The recommended solution is to use Ampere or above GPUs, which also support memory efficient quantization kernels from [TorchAO](https://github.com/pytorch/ao) :(
47
+ """
48
+
49
+ # Models: "THUDM/CogVideoX-2b" or "THUDM/CogVideoX-5b"
50
+ model_id = "THUDM/CogVideoX-5b"
51
+
52
+ # Thank you [@camenduru](https://github.com/camenduru)!
53
+ # The reason for using checkpoints hosted by Camenduru instead of the original is because they exported
54
+ # with a max_shard_size of "5GB" when saving the model with `.save_pretrained`. The original converted
55
+ # model was saved with "10GB" as the max shard size, which causes the Colab CPU RAM to be insufficient
56
+ # leading to OOM (on the CPU)
57
+
58
+ transformer = CogVideoXTransformer3DModel.from_pretrained("camenduru/cogvideox-5b-float16", subfolder="transformer", torch_dtype=torch.float16)
59
+ text_encoder = T5EncoderModel.from_pretrained("camenduru/cogvideox-5b-float16", subfolder="text_encoder", torch_dtype=torch.float16)
60
+ vae = AutoencoderKLCogVideoX.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float16)
61
+
62
+ # Create pipeline and run inference
63
+ pipe = CogVideoXVideoToVideoPipeline.from_pretrained(
64
+ model_id,
65
+ text_encoder=text_encoder,
66
+ transformer=transformer,
67
+ vae=vae,
68
+ torch_dtype=torch.float16,
69
+ )
70
+ pipe.scheduler = CogVideoXDPMScheduler.from_config(pipe.scheduler.config)
71
+
72
+ """#### Enable memory optimizations
73
+
74
+ Note that sequential cpu offloading is necessary for being able to run the model on Turing or lower architectures. It aggressively maintains everything on the CPU and only moves the currently executing nn.Module to the GPU. This saves a lot of VRAM but adds a lot of overhead for inference, making generations extremely slow (30 minutes+). Unfortunately, this is the only solution for running the model on Colab until efficient kernels are supported.
75
+ """
76
+
77
+ pipe.enable_sequential_cpu_offload()
78
+ pipe.vae.enable_tiling()
79
+
80
+ """#### Generate!"""
81
+
82
+ input_video = load_video(
83
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/hiker.mp4"
84
+ )
85
+ prompt = (
86
+ "An astronaut stands triumphantly at the peak of a towering mountain. Panorama of rugged peaks and "
87
+ "valleys. Very futuristic vibe and animated aesthetic. Highlights of purple and golden colors in "
88
+ "the scene. The sky is looks like an animated/cartoonish dream of galaxies, nebulae, stars, planets, "
89
+ "moons, but the remainder of the scene is mostly realistic."
90
+ )
91
+
92
+ video = pipe(video=input_video, prompt=prompt, strength=0.7, guidance_scale=6, use_dynamic_cfg=True, num_inference_steps=50).frames[0]
93
+
94
+ export_to_video(video, "output.mp4", fps=8)
95
+
96
+ export_to_video(input_video, "input.mp4", fps=8)
97
+
98
+ from IPython.display import display, Video
99
+ display(Video("input.mp4", embed=True))
100
+ display(Video("output.mp4", embed=True))
i2v_app.py ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ import random
4
+ import threading
5
+ import time
6
+ import cv2
7
+ import tempfile
8
+ import imageio_ffmpeg
9
+ import gradio as gr
10
+ import torch
11
+ from PIL import Image
12
+ from diffusers import (
13
+ CogVideoXPipeline,
14
+ CogVideoXDPMScheduler,
15
+ CogVideoXImageToVideoPipeline,
16
+ CogVideoXTransformer3DModel,
17
+ )
18
+ from diffusers.utils import load_video, load_image
19
+ from datetime import datetime, timedelta
20
+ from diffusers.image_processor import VaeImageProcessor
21
+ from openai import OpenAI
22
+ import moviepy.editor as mp
23
+ import utils
24
+ from rife_model import load_rife_model, rife_inference_with_latents
25
+ from huggingface_hub import hf_hub_download, snapshot_download
26
+ import gc
27
+
28
+ device = "cuda" if torch.cuda.is_available() else "cpu"
29
+
30
+ hf_hub_download(repo_id="ai-forever/Real-ESRGAN", filename="RealESRGAN_x4.pth", local_dir="model_real_esran")
31
+ snapshot_download(repo_id="AlexWortega/RIFE", local_dir="model_rife")
32
+
33
+ pipe = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-5b", torch_dtype=torch.bfloat16).to("cpu")
34
+ pipe.scheduler = CogVideoXDPMScheduler.from_config(pipe.scheduler.config, timestep_spacing="trailing")
35
+
36
+ i2v_transformer = CogVideoXTransformer3DModel.from_pretrained(
37
+ "THUDM/CogVideoX-5b-I2V", subfolder="transformer", torch_dtype=torch.bfloat16
38
+ )
39
+
40
+ os.makedirs("./output", exist_ok=True)
41
+ os.makedirs("./gradio_tmp", exist_ok=True)
42
+
43
+ upscale_model = utils.load_sd_upscale("model_real_esran/RealESRGAN_x4.pth", device)
44
+ frame_interpolation_model = load_rife_model("model_rife")
45
+
46
+ 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.
47
+ 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.
48
+ There are a few rules to follow:
49
+ You will only ever output a single video description per user request.
50
+ When modifications are requested , you should not simply make the description longer . You should refactor the entire description to integrate the suggestions.
51
+ 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.
52
+ Video descriptions must have the same num of words as examples below. Extra words will be ignored.
53
+ """
54
+
55
+ def convert_prompt(prompt: str, retry_times: int = 3) -> str:
56
+ if not os.environ.get("OPENAI_API_KEY"):
57
+ return prompt
58
+ client = OpenAI()
59
+ text = prompt.strip()
60
+
61
+ for i in range(retry_times):
62
+ response = client.chat.completions.create(
63
+ messages=[
64
+ {"role": "system", "content": sys_prompt},
65
+ {
66
+ "role": "user",
67
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "a girl is on the beach"',
68
+ },
69
+ {
70
+ "role": "assistant",
71
+ "content": "A radiant woman stands on a deserted beach, arms outstretched, wearing a beige trench coat, white blouse, light blue jeans, and chic boots, against a backdrop of soft sky and sea. Moments later, she is seen mid-twirl, arms exuberant, with the lighting suggesting dawn or dusk. Then, she runs along the beach, her attire complemented by an off-white scarf and black ankle boots, the tranquil sea behind her. Finally, she holds a paper airplane, her pose reflecting joy and freedom, with the ocean's gentle waves and the sky's soft pastel hues enhancing the serene ambiance.",
72
+ },
73
+ {
74
+ "role": "user",
75
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "A man jogging on a football field"',
76
+ },
77
+ {
78
+ "role": "assistant",
79
+ "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.",
80
+ },
81
+ {
82
+ "role": "user",
83
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : " A woman is dancing, HD footage, close-up"',
84
+ },
85
+ {
86
+ "role": "assistant",
87
+ "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.",
88
+ },
89
+ {
90
+ "role": "user",
91
+ "content": f'Create an imaginative video descriptive caption or modify an earlier caption in ENGLISH for the user input: "{text}"',
92
+ },
93
+ ],
94
+ model="glm-4-plus",
95
+ temperature=0.01,
96
+ top_p=0.7,
97
+ stream=False,
98
+ max_tokens=200,
99
+ )
100
+ if response.choices:
101
+ return response.choices[0].message.content
102
+ return prompt
103
+
104
+ def infer(
105
+ prompt: str,
106
+ image_input: str,
107
+ seed: int = -1,
108
+ progress=gr.Progress(track_tqdm=True),
109
+ ):
110
+ if seed == -1:
111
+ seed = random.randint(0, 2**8 - 1)
112
+
113
+ pipe_image = CogVideoXImageToVideoPipeline.from_pretrained(
114
+ "THUDM/CogVideoX-5b-I2V",
115
+ transformer=i2v_transformer,
116
+ vae=pipe.vae,
117
+ scheduler=pipe.scheduler,
118
+ tokenizer=pipe.tokenizer,
119
+ text_encoder=pipe.text_encoder,
120
+ torch_dtype=torch.bfloat16
121
+ ).to(device)
122
+ image_input = Image.fromarray(image_input).resize(size=(720, 480)) # Convert to PIL
123
+ image = load_image(image_input)
124
+ video_pt = pipe_image(
125
+ image=image,
126
+ prompt=prompt,
127
+ num_inference_steps=50,
128
+ num_videos_per_prompt=1,
129
+ use_dynamic_cfg=True,
130
+ output_type="pt",
131
+ guidance_scale=7.0,
132
+ generator=torch.Generator(device="cpu").manual_seed(seed),
133
+ ).frames
134
+ pipe_image.to("cpu")
135
+ del pipe_image
136
+ gc.collect()
137
+ torch.cuda.empty_cache()
138
+ return (video_pt, seed)
139
+
140
+ def convert_to_gif(video_path):
141
+ clip = mp.VideoFileClip(video_path)
142
+ clip = clip.set_fps(8)
143
+ clip = clip.resize(height=240)
144
+ gif_path = video_path.replace(".mp4", ".gif")
145
+ clip.write_gif(gif_path, fps=8)
146
+ return gif_path
147
+
148
+ def delete_old_files():
149
+ while True:
150
+ now = datetime.now()
151
+ cutoff = now - timedelta(minutes=10)
152
+ directories = ["./output", "./gradio_tmp"]
153
+
154
+ for directory in directories:
155
+ for filename in os.listdir(directory):
156
+ file_path = os.path.join(directory, filename)
157
+ if os.path.isfile(file_path):
158
+ file_mtime = datetime.fromtimestamp(os.path.getmtime(file_path))
159
+ if file_mtime < cutoff:
160
+ os.remove(file_path)
161
+ time.sleep(600)
162
+
163
+ threading.Thread(target=delete_old_files, daemon=True).start()
164
+
165
+ with gr.Blocks() as demo:
166
+ gr.Markdown("""
167
+ <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
168
+ CogVideoX-5B Huggingface Space🤗
169
+ </div>
170
+ <div style="text-align: center;">
171
+ <a href="https://huggingface.co/THUDM/CogVideoX-5B">🤗 5B(T2V) Model Hub</a> |
172
+ <a href="https://huggingface.co/THUDM/CogVideoX-5B-I2V">🤗 5B(I2V) Model Hub</a> |
173
+ <a href="https://github.com/THUDM/CogVideo">🌐 Github</a> |
174
+ <a href="https://arxiv.org/pdf/2408.06072">📜 arxiv </a>
175
+ </div>
176
+ <div style="text-align: center;display: flex;justify-content: center;align-items: center;margin-top: 1em;margin-bottom: .5em;">
177
+ <span>If the Space is too busy, duplicate it to use privately</span>
178
+ <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="
179
+ margin-left: .75em;
180
+ "></a>
181
+ </div>
182
+ <div style="text-align: center; font-size: 15px; font-weight: bold; color: red; margin-bottom: 20px;">
183
+ ⚠️ This demo is for academic research and experiential use only.
184
+ </div>
185
+ """)
186
+ with gr.Row():
187
+ with gr.Column():
188
+ with gr.Accordion("I2V: Image Input (cannot be used simultaneously with video input)", open=False):
189
+ image_input = gr.Image(label="Input Image (will be cropped to 720 * 480)")
190
+ prompt = gr.Textbox(label="Prompt (Less than 200 Words)", placeholder="Enter your prompt here", lines=5)
191
+
192
+ with gr.Row():
193
+ gr.Markdown(
194
+ "✨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."
195
+ )
196
+ enhance_button = gr.Button("✨ Enhance Prompt(Optional)")
197
+ with gr.Group():
198
+ with gr.Column():
199
+ with gr.Row():
200
+ seed_param = gr.Number(
201
+ label="Inference Seed (Enter a positive number, -1 for random)", value=-1
202
+ )
203
+ with gr.Row():
204
+ enable_scale = gr.Checkbox(label="Super-Resolution (720 × 480 -> 2880 × 1920)", value=False)
205
+ enable_rife = gr.Checkbox(label="Frame Interpolation (8fps -> 16fps)", value=False)
206
+ gr.Markdown(
207
+ "✨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."
208
+ )
209
+
210
+ generate_button = gr.Button("🎬 Generate Video")
211
+
212
+ with gr.Column():
213
+ video_output = gr.Video(label="CogVideoX Generate Video", width=720, height=480)
214
+ with gr.Row():
215
+ download_video_button = gr.File(label="📥 Download Video", visible=False)
216
+ download_gif_button = gr.File(label="📥 Download GIF", visible=False)
217
+ seed_text = gr.Number(label="Seed Used for Video Generation", visible=False)
218
+
219
+ gr.Markdown("""
220
+ <table border="0" style="width: 100%; text-align: left; margin-top: 20px;">
221
+ <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
222
+ 🎥 Video Gallery
223
+ </div>
224
+ <tr>
225
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
226
+ <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>
227
+ </td>
228
+ <td style="width: 25%; vertical-align: top;">
229
+ <video src="https://github.com/user-attachments/assets/cf5953ea-96d3-48fd-9907-c4708752c714" width="100%" controls autoplay loop></video>
230
+ </td>
231
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
232
+ <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>
233
+ </td>
234
+ <td style="width: 25%; vertical-align: top;">
235
+ <video src="https://github.com/user-attachments/assets/fe0a78e6-b669-4800-8cf0-b5f9b5145b52" width="100%" controls autoplay loop></video>
236
+ </td>
237
+ </tr>
238
+ <tr>
239
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
240
+ <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>
241
+ </td>
242
+ <td style="width: 25%; vertical-align: top;">
243
+ <video src="https://github.com/user-attachments/assets/c182f606-8f8c-421d-b414-8487070fcfcb" width="100%" controls autoplay loop></video>
244
+ </td>
245
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
246
+ <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>
247
+ </td>
248
+ <td style="width: 25%; vertical-align: top;">
249
+ <video src="https://github.com/user-attachments/assets/7db2bbce-194d-434d-a605-350254b6c298" width="100%" controls autoplay loop></video>
250
+ </td>
251
+ </tr>
252
+ <tr>
253
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
254
+ <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>
255
+ </td>
256
+ <td style="width: 25%; vertical-align: top;">
257
+ <video src="https://github.com/user-attachments/assets/62b01046-8cab-44cc-bd45-4d965bb615ec" width="100%" controls autoplay loop></video>
258
+ </td>
259
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
260
+ <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>
261
+ </td>
262
+ <td style="width: 25%; vertical-align: top;">
263
+ <video src="https://github.com/user-attachments/assets/d78e552a-4b3f-4b81-ac3f-3898079554f6" width="100%" controls autoplay loop></video>
264
+ </td>
265
+ </tr>
266
+ <tr>
267
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
268
+ <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>
269
+ </td>
270
+ <td style="width: 25%; vertical-align: top;">
271
+ <video src="https://github.com/user-attachments/assets/30894f12-c741-44a2-9e6e-ddcacc231e5b" width="100%" controls autoplay loop></video>
272
+ </td>
273
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
274
+ <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>
275
+ </td>
276
+ <td style="width: 25%; vertical-align: top;">
277
+ <video src="https://github.com/user-attachments/assets/926575ca-7150-435b-a0ff-4900a963297b" width="100%" controls autoplay loop></video>
278
+ </td>
279
+ </tr>
280
+ </table>
281
+ """)
282
+
283
+ def generate(
284
+ prompt,
285
+ image_input,
286
+ seed_value,
287
+ scale_status,
288
+ rife_status,
289
+ progress=gr.Progress(track_tqdm=True)
290
+ ):
291
+ latents, seed = infer(
292
+ prompt,
293
+ image_input,
294
+ seed=seed_value,
295
+ progress=progress,
296
+ )
297
+ if scale_status:
298
+ latents = utils.upscale_batch_and_concatenate(upscale_model, latents, device)
299
+ if rife_status:
300
+ latents = rife_inference_with_latents(frame_interpolation_model, latents)
301
+
302
+ batch_size = latents.shape[0]
303
+ batch_video_frames = []
304
+ for batch_idx in range(batch_size):
305
+ pt_image = latents[batch_idx]
306
+ pt_image = torch.stack([pt_image[i] for i in range(pt_image.shape[0])])
307
+
308
+ image_np = VaeImageProcessor.pt_to_numpy(pt_image)
309
+ image_pil = VaeImageProcessor.numpy_to_pil(image_np)
310
+ batch_video_frames.append(image_pil)
311
+
312
+ video_path = utils.save_video(batch_video_frames[0], fps=math.ceil((len(batch_video_frames[0]) - 1) / 6))
313
+ video_update = gr.update(visible=True, value=video_path)
314
+ gif_path = convert_to_gif(video_path)
315
+ gif_update = gr.update(visible=True, value=gif_path)
316
+ seed_update = gr.update(visible=True, value=seed)
317
+
318
+ return video_path, video_update, gif_update, seed_update
319
+
320
+ def enhance_prompt_func(prompt):
321
+ return convert_prompt(prompt, retry_times=1)
322
+
323
+ generate_button.click(
324
+ generate,
325
+ inputs=[prompt, image_input, seed_param, enable_scale, enable_rife],
326
+ outputs=[video_output, download_video_button, download_gif_button, seed_text],
327
+ )
328
+
329
+ enhance_button.click(enhance_prompt_func, inputs=[prompt], outputs=[prompt])
330
+
331
+ if __name__ == "__main__":
332
+ demo.queue(max_size=15)
333
+ demo.launch(share = True)
i2v_app_t4.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ import random
4
+ import threading
5
+ import time
6
+ import cv2
7
+ import tempfile
8
+ import imageio_ffmpeg
9
+ import gradio as gr
10
+ import torch
11
+ from PIL import Image
12
+ from diffusers import (
13
+ CogVideoXPipeline,
14
+ CogVideoXDPMScheduler,
15
+ CogVideoXImageToVideoPipeline,
16
+ CogVideoXTransformer3DModel,
17
+ AutoencoderKLCogVideoX,
18
+ )
19
+ from diffusers.utils import load_video, load_image
20
+ from datetime import datetime, timedelta
21
+ from diffusers.image_processor import VaeImageProcessor
22
+ from transformers import T5EncoderModel
23
+ from openai import OpenAI
24
+ import moviepy.editor as mp
25
+ import utils
26
+ from rife_model import load_rife_model, rife_inference_with_latents
27
+ from huggingface_hub import hf_hub_download, snapshot_download
28
+ import gc
29
+
30
+ device = "cuda" if torch.cuda.is_available() else "cpu"
31
+
32
+ hf_hub_download(repo_id="ai-forever/Real-ESRGAN", filename="RealESRGAN_x4.pth", local_dir="model_real_esran")
33
+ snapshot_download(repo_id="AlexWortega/RIFE", local_dir="model_rife")
34
+
35
+ # 初始化 transformer, text_encoder 和 vae
36
+ model_id = "THUDM/CogVideoX-5b-I2V"
37
+ transformer = CogVideoXTransformer3DModel.from_pretrained(model_id, subfolder="transformer", torch_dtype=torch.float16)
38
+ text_encoder = T5EncoderModel.from_pretrained(model_id, subfolder="text_encoder", torch_dtype=torch.float16)
39
+ vae = AutoencoderKLCogVideoX.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float16)
40
+
41
+ # 创建管道
42
+ pipe = CogVideoXImageToVideoPipeline.from_pretrained(
43
+ model_id,
44
+ text_encoder=text_encoder,
45
+ transformer=transformer,
46
+ vae=vae,
47
+ torch_dtype=torch.float16,
48
+ )
49
+
50
+ # 启用内存优化
51
+ pipe.enable_sequential_cpu_offload()
52
+
53
+ os.makedirs("./output", exist_ok=True)
54
+ os.makedirs("./gradio_tmp", exist_ok=True)
55
+
56
+ upscale_model = utils.load_sd_upscale("model_real_esran/RealESRGAN_x4.pth", device)
57
+ frame_interpolation_model = load_rife_model("model_rife")
58
+
59
+ 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.
60
+ 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.
61
+ There are a few rules to follow:
62
+ You will only ever output a single video description per user request.
63
+ When modifications are requested , you should not simply make the description longer . You should refactor the entire description to integrate the suggestions.
64
+ 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.
65
+ Video descriptions must have the same num of words as examples below. Extra words will be ignored.
66
+ """
67
+
68
+ def convert_prompt(prompt: str, retry_times: int = 3) -> str:
69
+ if not os.environ.get("OPENAI_API_KEY"):
70
+ return prompt
71
+ client = OpenAI()
72
+ text = prompt.strip()
73
+
74
+ for i in range(retry_times):
75
+ response = client.chat.completions.create(
76
+ messages=[
77
+ {"role": "system", "content": sys_prompt},
78
+ {
79
+ "role": "user",
80
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "a girl is on the beach"',
81
+ },
82
+ {
83
+ "role": "assistant",
84
+ "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.",
85
+ },
86
+ {
87
+ "role": "user",
88
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "A man jogging on a football field"',
89
+ },
90
+ {
91
+ "role": "assistant",
92
+ "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.",
93
+ },
94
+ {
95
+ "role": "user",
96
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : " A woman is dancing, HD footage, close-up"',
97
+ },
98
+ {
99
+ "role": "assistant",
100
+ "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.",
101
+ },
102
+ {
103
+ "role": "user",
104
+ "content": f'Create an imaginative video descriptive caption or modify an earlier caption in ENGLISH for the user input: "{text}"',
105
+ },
106
+ ],
107
+ model="glm-4-plus",
108
+ temperature=0.01,
109
+ top_p=0.7,
110
+ stream=False,
111
+ max_tokens=200,
112
+ )
113
+ if response.choices:
114
+ return response.choices[0].message.content
115
+ return prompt
116
+
117
+ def infer(
118
+ prompt: str,
119
+ image_input: str,
120
+ seed: int = -1,
121
+ progress=gr.Progress(track_tqdm=True),
122
+ ):
123
+ if seed == -1:
124
+ seed = random.randint(0, 2**8 - 1)
125
+
126
+ pipe_image = CogVideoXImageToVideoPipeline.from_pretrained(
127
+ "THUDM/CogVideoX-5b-I2V",
128
+ transformer=transformer,
129
+ vae=vae,
130
+ scheduler=pipe.scheduler,
131
+ tokenizer=pipe.tokenizer,
132
+ text_encoder=text_encoder,
133
+ torch_dtype=torch.float16
134
+ ).to(device)
135
+ image_input = Image.fromarray(image_input).resize(size=(720, 480)) # Convert to PIL
136
+ image = load_image(image_input)
137
+ video_pt = pipe_image(
138
+ image=image,
139
+ prompt=prompt,
140
+ num_inference_steps=50,
141
+ num_videos_per_prompt=1,
142
+ use_dynamic_cfg=True,
143
+ output_type="pt",
144
+ guidance_scale=7.0,
145
+ generator=torch.Generator(device="cpu").manual_seed(seed),
146
+ ).frames
147
+ pipe_image.to("cpu")
148
+ del pipe_image
149
+ gc.collect()
150
+ torch.cuda.empty_cache()
151
+ return (video_pt, seed)
152
+
153
+ def convert_to_gif(video_path):
154
+ clip = mp.VideoFileClip(video_path)
155
+ clip = clip.set_fps(8)
156
+ clip = clip.resize(height=240)
157
+ gif_path = video_path.replace(".mp4", ".gif")
158
+ clip.write_gif(gif_path, fps=8)
159
+ return gif_path
160
+
161
+ def delete_old_files():
162
+ while True:
163
+ now = datetime.now()
164
+ cutoff = now - timedelta(minutes=10)
165
+ directories = ["./output", "./gradio_tmp"]
166
+
167
+ for directory in directories:
168
+ for filename in os.listdir(directory):
169
+ file_path = os.path.join(directory, filename)
170
+ if os.path.isfile(file_path):
171
+ file_mtime = datetime.fromtimestamp(os.path.getmtime(file_path))
172
+ if file_mtime < cutoff:
173
+ os.remove(file_path)
174
+ time.sleep(600)
175
+
176
+ threading.Thread(target=delete_old_files, daemon=True).start()
177
+
178
+ with gr.Blocks() as demo:
179
+ gr.Markdown("""
180
+ <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
181
+ CogVideoX-5B Huggingface Space🤗
182
+ </div>
183
+ <div style="text-align: center;">
184
+ <a href="https://huggingface.co/THUDM/CogVideoX-5B">🤗 5B(T2V) Model Hub</a> |
185
+ <a href="https://huggingface.co/THUDM/CogVideoX-5B-I2V">🤗 5B(I2V) Model Hub</a> |
186
+ <a href="https://github.com/THUDM/CogVideo">🌐 Github</a> |
187
+ <a href="https://arxiv.org/pdf/2408.06072">📜 arxiv </a>
188
+ </div>
189
+ <div style="text-align: center;display: flex;justify-content: center;align-items: center;margin-top: 1em;margin-bottom: .5em;">
190
+ <span>If the Space is too busy, duplicate it to use privately</span>
191
+ <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="
192
+ margin-left: .75em;
193
+ "></a>
194
+ </div>
195
+ <div style="text-align: center; font-size: 15px; font-weight: bold; color: red; margin-bottom: 20px;">
196
+ ⚠️ This demo is for academic research and experiential use only.
197
+ </div>
198
+ """)
199
+ with gr.Row():
200
+ with gr.Column():
201
+ with gr.Accordion("I2V: Image Input (cannot be used simultaneously with video input)", open=False):
202
+ image_input = gr.Image(label="Input Image (will be cropped to 720 * 480)")
203
+ prompt = gr.Textbox(label="Prompt (Less than 200 Words)", placeholder="Enter your prompt here", lines=5)
204
+
205
+ with gr.Row():
206
+ gr.Markdown(
207
+ "✨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."
208
+ )
209
+ enhance_button = gr.Button("✨ Enhance Prompt(Optional)")
210
+ with gr.Group():
211
+ with gr.Column():
212
+ with gr.Row():
213
+ seed_param = gr.Number(
214
+ label="Inference Seed (Enter a positive number, -1 for random)", value=-1
215
+ )
216
+ with gr.Row():
217
+ enable_scale = gr.Checkbox(label="Super-Resolution (720 × 480 -> 2880 × 1920)", value=False)
218
+ enable_rife = gr.Checkbox(label="Frame Interpolation (8fps -> 16fps)", value=False)
219
+ gr.Markdown(
220
+ "✨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."
221
+ )
222
+
223
+ generate_button = gr.Button("🎬 Generate Video")
224
+
225
+ with gr.Column():
226
+ video_output = gr.Video(label="CogVideoX Generate Video", width=720, height=480)
227
+ with gr.Row():
228
+ download_video_button = gr.File(label="📥 Download Video", visible=False)
229
+ download_gif_button = gr.File(label="📥 Download GIF", visible=False)
230
+ seed_text = gr.Number(label="Seed Used for Video Generation", visible=False)
231
+
232
+ gr.Markdown("""
233
+ <table border="0" style="width: 100%; text-align: left; margin-top: 20px;">
234
+ <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
235
+ 🎥 Video Gallery
236
+ </div>
237
+ <tr>
238
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
239
+ <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>
240
+ </td>
241
+ <td style="width: 25%; vertical-align: top;">
242
+ <video src="https://github.com/user-attachments/assets/cf5953ea-96d3-48fd-9907-c4708752c714" width="100%" controls autoplay loop></video>
243
+ </td>
244
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
245
+ <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>
246
+ </td>
247
+ <td style="width: 25%; vertical-align: top;">
248
+ <video src="https://github.com/user-attachments/assets/fe0a78e6-b669-4800-8cf0-b5f9b5145b52" width="100%" controls autoplay loop></video>
249
+ </td>
250
+ </tr>
251
+ <tr>
252
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
253
+ <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>
254
+ </td>
255
+ <td style="width: 25%; vertical-align: top;">
256
+ <video src="https://github.com/user-attachments/assets/c182f606-8f8c-421d-b414-8487070fcfcb" width="100%" controls autoplay loop></video>
257
+ </td>
258
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
259
+ <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>
260
+ </td>
261
+ <td style="width: 25%; vertical-align: top;">
262
+ <video src="https://github.com/user-attachments/assets/7db2bbce-194d-434d-a605-350254b6c298" width="100%" controls autoplay loop></video>
263
+ </td>
264
+ </tr>
265
+ <tr>
266
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
267
+ <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>
268
+ </td>
269
+ <td style="width: 25%; vertical-align: top;">
270
+ <video src="https://github.com/user-attachments/assets/62b01046-8cab-44cc-bd45-4d965bb615ec" width="100%" controls autoplay loop></video>
271
+ </td>
272
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
273
+ <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>
274
+ </td>
275
+ <td style="width: 25%; vertical-align: top;">
276
+ <video src="https://github.com/user-attachments/assets/d78e552a-4b3f-4b81-ac3f-3898079554f6" width="100%" controls autoplay loop></video>
277
+ </td>
278
+ </tr>
279
+ <tr>
280
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
281
+ <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>
282
+ </td>
283
+ <td style="width: 25%; vertical-align: top;">
284
+ <video src="https://github.com/user-attachments/assets/30894f12-c741-44a2-9e6e-ddcacc231e5b" width="100%" controls autoplay loop></video>
285
+ </td>
286
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
287
+ <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>
288
+ </td>
289
+ <td style="width: 25%; vertical-align: top;">
290
+ <video src="https://github.com/user-attachments/assets/926575ca-7150-435b-a0ff-4900a963297b" width="100%" controls autoplay loop></video>
291
+ </td>
292
+ </tr>
293
+ </table>
294
+ """)
295
+
296
+ def generate(
297
+ prompt,
298
+ image_input,
299
+ seed_value,
300
+ scale_status,
301
+ rife_status,
302
+ progress=gr.Progress(track_tqdm=True)
303
+ ):
304
+ latents, seed = infer(
305
+ prompt,
306
+ image_input,
307
+ seed=seed_value,
308
+ progress=progress,
309
+ )
310
+ if scale_status:
311
+ latents = utils.upscale_batch_and_concatenate(upscale_model, latents, device)
312
+ if rife_status:
313
+ latents = rife_inference_with_latents(frame_interpolation_model, latents)
314
+
315
+ batch_size = latents.shape[0]
316
+ batch_video_frames = []
317
+ for batch_idx in range(batch_size):
318
+ pt_image = latents[batch_idx]
319
+ pt_image = torch.stack([pt_image[i] for i in range(pt_image.shape[0])])
320
+
321
+ image_np = VaeImageProcessor.pt_to_numpy(pt_image)
322
+ image_pil = VaeImageProcessor.numpy_to_pil(image_np)
323
+ batch_video_frames.append(image_pil)
324
+
325
+ video_path = utils.save_video(batch_video_frames[0], fps=math.ceil((len(batch_video_frames[0]) - 1) / 6))
326
+ video_update = gr.update(visible=True, value=video_path)
327
+ gif_path = convert_to_gif(video_path)
328
+ gif_update = gr.update(visible=True, value=gif_path)
329
+ seed_update = gr.update(visible=True, value=seed)
330
+
331
+ return video_path, video_update, gif_update, seed_update
332
+
333
+ def enhance_prompt_func(prompt):
334
+ return convert_prompt(prompt, retry_times=1)
335
+
336
+ generate_button.click(
337
+ generate,
338
+ inputs=[prompt, image_input, seed_param, enable_scale, enable_rife],
339
+ outputs=[video_output, download_video_button, download_gif_button, seed_text],
340
+ )
341
+
342
+ enhance_button.click(enhance_prompt_func, inputs=[prompt], outputs=[prompt])
343
+
344
+ if __name__ == "__main__":
345
+ demo.queue(max_size=15)
346
+ demo.launch(share = True)
readme.py ADDED
@@ -0,0 +1,429 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ 在colab T4 上进行推导的一些notebook
3
+ https://github.com/THUDM/CogVideo
4
+ ->
5
+
6
+ T2V
7
+ https://colab.research.google.com/drive/1pCe5s0bC_xuXbBlpvIH1z0kfdTLQPzCS?usp=sharing
8
+ V2V
9
+ https://colab.research.google.com/drive/1comfGAUJnChl5NwPuO8Ox5_6WCy4kbNN?usp=sharing
10
+ I2V
11
+ https://colab.research.google.com/drive/17CqYCqSwz39nZAX2YyonDxosVKUZGzcX?usp=sharing
12
+ '''
13
+
14
+ 依据下面的模型导入和推导方式修改后面的gradio app 代码,以节约显存
15
+
16
+ # -*- coding: utf-8 -*-
17
+ """CogVideoX-I2V-Colab.ipynb
18
+
19
+ Automatically generated by Colab.
20
+
21
+ Original file is located at
22
+ https://colab.research.google.com/drive/17CqYCqSwz39nZAX2YyonDxosVKUZGzcX
23
+
24
+ ## CogVideoX Image-to-Video
25
+
26
+ This notebook demonstrates how to run [CogVideoX-5b-I2V](https://huggingface.co/THUDM/CogVideoX-5b-I2V) with 🧨 Diffusers on a free-tier Colab GPU.
27
+
28
+ Additional resources:
29
+ - [Docs](https://huggingface.co/docs/diffusers/en/api/pipelines/cogvideox)
30
+ - [Quantization with TorchAO](https://github.com/sayakpaul/diffusers-torchao/)
31
+ - [Quantization with Quanto](https://gist.github.com/a-r-r-o-w/31be62828b00a9292821b85c1017effa)
32
+
33
+ Note: If, for whatever reason, you randomly get an OOM error, give it a try on Kaggle T4 instances instead. I've found that Colab free-tier T4 can be unreliable at times. Sometimes, the notebook will run smoothly, but other times it will crash with an error 🤷🏻‍♂️
34
+
35
+ #### Install the necessary requirements
36
+ """
37
+
38
+ !pip install diffusers transformers hf_transfer
39
+
40
+ # !pip install git+https://github.com/huggingface/accelerate
41
+ !pip install accelerate==0.33.0
42
+
43
+ """#### Import required libraries
44
+
45
+ The following block is optional but if enabled, downloading models from the HF Hub will be much faster
46
+ """
47
+
48
+ import os
49
+ os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
50
+
51
+ import torch
52
+ from diffusers import AutoencoderKLCogVideoX, CogVideoXImageToVideoPipeline, CogVideoXTransformer3DModel
53
+ from diffusers.utils import export_to_video, load_image
54
+ from transformers import T5EncoderModel
55
+
56
+ """#### Load models and create pipeline
57
+
58
+ Note: `bfloat16`, which is the recommended dtype for running "CogVideoX-5b-I2V" will cause OOM errors due to lack of efficient support on Turing GPUs.
59
+
60
+ Therefore, we must use `float16`, which might result in poorer generation quality. The recommended solution is to use Ampere or above GPUs, which also support efficient quantization kernels from [TorchAO](https://github.com/pytorch/ao) :(
61
+ """
62
+
63
+ model_id = "THUDM/CogVideoX-5b-I2V"
64
+
65
+ transformer = CogVideoXTransformer3DModel.from_pretrained(model_id, subfolder="transformer", torch_dtype=torch.float16)
66
+ text_encoder = T5EncoderModel.from_pretrained(model_id, subfolder="text_encoder", torch_dtype=torch.float16)
67
+ vae = AutoencoderKLCogVideoX.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float16)
68
+
69
+ # Create pipeline and run inference
70
+ pipe = CogVideoXImageToVideoPipeline.from_pretrained(
71
+ model_id,
72
+ text_encoder=text_encoder,
73
+ transformer=transformer,
74
+ vae=vae,
75
+ torch_dtype=torch.float16,
76
+ )
77
+
78
+ """#### Enable memory optimizations
79
+
80
+ Note that sequential cpu offloading is necessary for being able to run the model on Turing or lower architectures. It aggressively maintains everything on the CPU and only moves the currently executing nn.Module to the GPU. This saves a lot of VRAM but adds a lot of overhead for inference, making generations extremely slow (1 hour+). Unfortunately, this is the only solution for running the model on Colab until efficient kernels are supported.
81
+ """
82
+
83
+ pipe.enable_sequential_cpu_offload()
84
+ # pipe.vae.enable_tiling()
85
+
86
+ """#### Generate!"""
87
+
88
+ prompt = "An astronaut hatching from an egg, on the surface of the moon, the darkness and depth of space realised in the background. High quality, ultrarealistic detail and breath-taking movie-like camera shot."
89
+ image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg")
90
+
91
+ video = pipe(image=image, prompt=prompt, guidance_scale=6, use_dynamic_cfg=True, num_inference_steps=50).frames[0]
92
+
93
+ export_to_video(video, "output.mp4", fps=8)
94
+
95
+ gradio_app 代码
96
+
97
+ import math
98
+ import os
99
+ import random
100
+ import threading
101
+ import time
102
+ import cv2
103
+ import tempfile
104
+ import imageio_ffmpeg
105
+ import gradio as gr
106
+ import torch
107
+ from PIL import Image
108
+ from diffusers import (
109
+ CogVideoXPipeline,
110
+ CogVideoXDPMScheduler,
111
+ CogVideoXImageToVideoPipeline,
112
+ CogVideoXTransformer3DModel,
113
+ )
114
+ from diffusers.utils import load_video, load_image
115
+ from datetime import datetime, timedelta
116
+ from diffusers.image_processor import VaeImageProcessor
117
+ from openai import OpenAI
118
+ import moviepy.editor as mp
119
+ import utils
120
+ from rife_model import load_rife_model, rife_inference_with_latents
121
+ from huggingface_hub import hf_hub_download, snapshot_download
122
+ import gc
123
+
124
+ device = "cuda" if torch.cuda.is_available() else "cpu"
125
+
126
+ hf_hub_download(repo_id="ai-forever/Real-ESRGAN", filename="RealESRGAN_x4.pth", local_dir="model_real_esran")
127
+ snapshot_download(repo_id="AlexWortega/RIFE", local_dir="model_rife")
128
+
129
+ pipe = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-5b", torch_dtype=torch.bfloat16).to("cpu")
130
+ pipe.scheduler = CogVideoXDPMScheduler.from_config(pipe.scheduler.config, timestep_spacing="trailing")
131
+
132
+ i2v_transformer = CogVideoXTransformer3DModel.from_pretrained(
133
+ "THUDM/CogVideoX-5b-I2V", subfolder="transformer", torch_dtype=torch.bfloat16
134
+ )
135
+
136
+ os.makedirs("./output", exist_ok=True)
137
+ os.makedirs("./gradio_tmp", exist_ok=True)
138
+
139
+ upscale_model = utils.load_sd_upscale("model_real_esran/RealESRGAN_x4.pth", device)
140
+ frame_interpolation_model = load_rife_model("model_rife")
141
+
142
+ 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.
143
+ 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.
144
+ There are a few rules to follow:
145
+ You will only ever output a single video description per user request.
146
+ When modifications are requested , you should not simply make the description longer . You should refactor the entire description to integrate the suggestions.
147
+ 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.
148
+ Video descriptions must have the same num of words as examples below. Extra words will be ignored.
149
+ """
150
+
151
+ def convert_prompt(prompt: str, retry_times: int = 3) -> str:
152
+ if not os.environ.get("OPENAI_API_KEY"):
153
+ return prompt
154
+ client = OpenAI()
155
+ text = prompt.strip()
156
+
157
+ for i in range(retry_times):
158
+ response = client.chat.completions.create(
159
+ messages=[
160
+ {"role": "system", "content": sys_prompt},
161
+ {
162
+ "role": "user",
163
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "a girl is on the beach"',
164
+ },
165
+ {
166
+ "role": "assistant",
167
+ "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.",
168
+ },
169
+ {
170
+ "role": "user",
171
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "A man jogging on a football field"',
172
+ },
173
+ {
174
+ "role": "assistant",
175
+ "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.",
176
+ },
177
+ {
178
+ "role": "user",
179
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : " A woman is dancing, HD footage, close-up"',
180
+ },
181
+ {
182
+ "role": "assistant",
183
+ "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.",
184
+ },
185
+ {
186
+ "role": "user",
187
+ "content": f'Create an imaginative video descriptive caption or modify an earlier caption in ENGLISH for the user input: "{text}"',
188
+ },
189
+ ],
190
+ model="glm-4-plus",
191
+ temperature=0.01,
192
+ top_p=0.7,
193
+ stream=False,
194
+ max_tokens=200,
195
+ )
196
+ if response.choices:
197
+ return response.choices[0].message.content
198
+ return prompt
199
+
200
+ def infer(
201
+ prompt: str,
202
+ image_input: str,
203
+ seed: int = -1,
204
+ progress=gr.Progress(track_tqdm=True),
205
+ ):
206
+ if seed == -1:
207
+ seed = random.randint(0, 2**8 - 1)
208
+
209
+ pipe_image = CogVideoXImageToVideoPipeline.from_pretrained(
210
+ "THUDM/CogVideoX-5b-I2V",
211
+ transformer=i2v_transformer,
212
+ vae=pipe.vae,
213
+ scheduler=pipe.scheduler,
214
+ tokenizer=pipe.tokenizer,
215
+ text_encoder=pipe.text_encoder,
216
+ torch_dtype=torch.bfloat16
217
+ ).to(device)
218
+ image_input = Image.fromarray(image_input).resize(size=(720, 480)) # Convert to PIL
219
+ image = load_image(image_input)
220
+ video_pt = pipe_image(
221
+ image=image,
222
+ prompt=prompt,
223
+ num_inference_steps=50,
224
+ num_videos_per_prompt=1,
225
+ use_dynamic_cfg=True,
226
+ output_type="pt",
227
+ guidance_scale=7.0,
228
+ generator=torch.Generator(device="cpu").manual_seed(seed),
229
+ ).frames
230
+ pipe_image.to("cpu")
231
+ del pipe_image
232
+ gc.collect()
233
+ torch.cuda.empty_cache()
234
+ return (video_pt, seed)
235
+
236
+ def convert_to_gif(video_path):
237
+ clip = mp.VideoFileClip(video_path)
238
+ clip = clip.set_fps(8)
239
+ clip = clip.resize(height=240)
240
+ gif_path = video_path.replace(".mp4", ".gif")
241
+ clip.write_gif(gif_path, fps=8)
242
+ return gif_path
243
+
244
+ def delete_old_files():
245
+ while True:
246
+ now = datetime.now()
247
+ cutoff = now - timedelta(minutes=10)
248
+ directories = ["./output", "./gradio_tmp"]
249
+
250
+ for directory in directories:
251
+ for filename in os.listdir(directory):
252
+ file_path = os.path.join(directory, filename)
253
+ if os.path.isfile(file_path):
254
+ file_mtime = datetime.fromtimestamp(os.path.getmtime(file_path))
255
+ if file_mtime < cutoff:
256
+ os.remove(file_path)
257
+ time.sleep(600)
258
+
259
+ threading.Thread(target=delete_old_files, daemon=True).start()
260
+
261
+ with gr.Blocks() as demo:
262
+ gr.Markdown("""
263
+ <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
264
+ CogVideoX-5B Huggingface Space🤗
265
+ </div>
266
+ <div style="text-align: center;">
267
+ <a href="https://huggingface.co/THUDM/CogVideoX-5B">🤗 5B(T2V) Model Hub</a> |
268
+ <a href="https://huggingface.co/THUDM/CogVideoX-5B-I2V">🤗 5B(I2V) Model Hub</a> |
269
+ <a href="https://github.com/THUDM/CogVideo">🌐 Github</a> |
270
+ <a href="https://arxiv.org/pdf/2408.06072">📜 arxiv </a>
271
+ </div>
272
+ <div style="text-align: center;display: flex;justify-content: center;align-items: center;margin-top: 1em;margin-bottom: .5em;">
273
+ <span>If the Space is too busy, duplicate it to use privately</span>
274
+ <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="
275
+ margin-left: .75em;
276
+ "></a>
277
+ </div>
278
+ <div style="text-align: center; font-size: 15px; font-weight: bold; color: red; margin-bottom: 20px;">
279
+ ⚠️ This demo is for academic research and experiential use only.
280
+ </div>
281
+ """)
282
+ with gr.Row():
283
+ with gr.Column():
284
+ with gr.Accordion("I2V: Image Input (cannot be used simultaneously with video input)", open=False):
285
+ image_input = gr.Image(label="Input Image (will be cropped to 720 * 480)")
286
+ prompt = gr.Textbox(label="Prompt (Less than 200 Words)", placeholder="Enter your prompt here", lines=5)
287
+
288
+ with gr.Row():
289
+ gr.Markdown(
290
+ "✨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."
291
+ )
292
+ enhance_button = gr.Button("✨ Enhance Prompt(Optional)")
293
+ with gr.Group():
294
+ with gr.Column():
295
+ with gr.Row():
296
+ seed_param = gr.Number(
297
+ label="Inference Seed (Enter a positive number, -1 for random)", value=-1
298
+ )
299
+ with gr.Row():
300
+ enable_scale = gr.Checkbox(label="Super-Resolution (720 × 480 -> 2880 × 1920)", value=False)
301
+ enable_rife = gr.Checkbox(label="Frame Interpolation (8fps -> 16fps)", value=False)
302
+ gr.Markdown(
303
+ "✨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."
304
+ )
305
+
306
+ generate_button = gr.Button("🎬 Generate Video")
307
+
308
+ with gr.Column():
309
+ video_output = gr.Video(label="CogVideoX Generate Video", width=720, height=480)
310
+ with gr.Row():
311
+ download_video_button = gr.File(label="📥 Download Video", visible=False)
312
+ download_gif_button = gr.File(label="📥 Download GIF", visible=False)
313
+ seed_text = gr.Number(label="Seed Used for Video Generation", visible=False)
314
+
315
+ gr.Markdown("""
316
+ <table border="0" style="width: 100%; text-align: left; margin-top: 20px;">
317
+ <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
318
+ 🎥 Video Gallery
319
+ </div>
320
+ <tr>
321
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
322
+ <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>
323
+ </td>
324
+ <td style="width: 25%; vertical-align: top;">
325
+ <video src="https://github.com/user-attachments/assets/cf5953ea-96d3-48fd-9907-c4708752c714" width="100%" controls autoplay loop></video>
326
+ </td>
327
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
328
+ <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>
329
+ </td>
330
+ <td style="width: 25%; vertical-align: top;">
331
+ <video src="https://github.com/user-attachments/assets/fe0a78e6-b669-4800-8cf0-b5f9b5145b52" width="100%" controls autoplay loop></video>
332
+ </td>
333
+ </tr>
334
+ <tr>
335
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
336
+ <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>
337
+ </td>
338
+ <td style="width: 25%; vertical-align: top;">
339
+ <video src="https://github.com/user-attachments/assets/c182f606-8f8c-421d-b414-8487070fcfcb" width="100%" controls autoplay loop></video>
340
+ </td>
341
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
342
+ <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>
343
+ </td>
344
+ <td style="width: 25%; vertical-align: top;">
345
+ <video src="https://github.com/user-attachments/assets/7db2bbce-194d-434d-a605-350254b6c298" width="100%" controls autoplay loop></video>
346
+ </td>
347
+ </tr>
348
+ <tr>
349
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
350
+ <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>
351
+ </td>
352
+ <td style="width: 25%; vertical-align: top;">
353
+ <video src="https://github.com/user-attachments/assets/62b01046-8cab-44cc-bd45-4d965bb615ec" width="100%" controls autoplay loop></video>
354
+ </td>
355
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
356
+ <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>
357
+ </td>
358
+ <td style="width: 25%; vertical-align: top;">
359
+ <video src="https://github.com/user-attachments/assets/d78e552a-4b3f-4b81-ac3f-3898079554f6" width="100%" controls autoplay loop></video>
360
+ </td>
361
+ </tr>
362
+ <tr>
363
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
364
+ <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>
365
+ </td>
366
+ <td style="width: 25%; vertical-align: top;">
367
+ <video src="https://github.com/user-attachments/assets/30894f12-c741-44a2-9e6e-ddcacc231e5b" width="100%" controls autoplay loop></video>
368
+ </td>
369
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
370
+ <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>
371
+ </td>
372
+ <td style="width: 25%; vertical-align: top;">
373
+ <video src="https://github.com/user-attachments/assets/926575ca-7150-435b-a0ff-4900a963297b" width="100%" controls autoplay loop></video>
374
+ </td>
375
+ </tr>
376
+ </table>
377
+ """)
378
+
379
+ def generate(
380
+ prompt,
381
+ image_input,
382
+ seed_value,
383
+ scale_status,
384
+ rife_status,
385
+ progress=gr.Progress(track_tqdm=True)
386
+ ):
387
+ latents, seed = infer(
388
+ prompt,
389
+ image_input,
390
+ seed=seed_value,
391
+ progress=progress,
392
+ )
393
+ if scale_status:
394
+ latents = utils.upscale_batch_and_concatenate(upscale_model, latents, device)
395
+ if rife_status:
396
+ latents = rife_inference_with_latents(frame_interpolation_model, latents)
397
+
398
+ batch_size = latents.shape[0]
399
+ batch_video_frames = []
400
+ for batch_idx in range(batch_size):
401
+ pt_image = latents[batch_idx]
402
+ pt_image = torch.stack([pt_image[i] for i in range(pt_image.shape[0])])
403
+
404
+ image_np = VaeImageProcessor.pt_to_numpy(pt_image)
405
+ image_pil = VaeImageProcessor.numpy_to_pil(image_np)
406
+ batch_video_frames.append(image_pil)
407
+
408
+ video_path = utils.save_video(batch_video_frames[0], fps=math.ceil((len(batch_video_frames[0]) - 1) / 6))
409
+ video_update = gr.update(visible=True, value=video_path)
410
+ gif_path = convert_to_gif(video_path)
411
+ gif_update = gr.update(visible=True, value=gif_path)
412
+ seed_update = gr.update(visible=True, value=seed)
413
+
414
+ return video_path, video_update, gif_update, seed_update
415
+
416
+ def enhance_prompt_func(prompt):
417
+ return convert_prompt(prompt, retry_times=1)
418
+
419
+ generate_button.click(
420
+ generate,
421
+ inputs=[prompt, image_input, seed_param, enable_scale, enable_rife],
422
+ outputs=[video_output, download_video_button, download_gif_button, seed_text],
423
+ )
424
+
425
+ enhance_button.click(enhance_prompt_func, inputs=[prompt], outputs=[prompt])
426
+
427
+ if __name__ == "__main__":
428
+ demo.queue(max_size=15)
429
+ demo.launch(share = True)
t2v_app.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ import random
4
+ import threading
5
+ import time
6
+ import cv2
7
+ import tempfile
8
+ import imageio_ffmpeg
9
+ import gradio as gr
10
+ import torch
11
+ from PIL import Image
12
+ from diffusers import (
13
+ CogVideoXPipeline,
14
+ CogVideoXDPMScheduler,
15
+ )
16
+ from diffusers.utils import load_video, load_image
17
+ from datetime import datetime, timedelta
18
+ from diffusers.image_processor import VaeImageProcessor
19
+ from openai import OpenAI
20
+ import moviepy.editor as mp
21
+ import utils
22
+ from rife_model import load_rife_model, rife_inference_with_latents
23
+ from huggingface_hub import hf_hub_download, snapshot_download
24
+ import gc
25
+
26
+ device = "cuda" if torch.cuda.is_available() else "cpu"
27
+
28
+ hf_hub_download(repo_id="ai-forever/Real-ESRGAN", filename="RealESRGAN_x4.pth", local_dir="model_real_esran")
29
+ snapshot_download(repo_id="AlexWortega/RIFE", local_dir="model_rife")
30
+
31
+ pipe = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-5b", torch_dtype=torch.bfloat16).to("cpu")
32
+ pipe.scheduler = CogVideoXDPMScheduler.from_config(pipe.scheduler.config, timestep_spacing="trailing")
33
+
34
+ os.makedirs("./output", exist_ok=True)
35
+ os.makedirs("./gradio_tmp", exist_ok=True)
36
+
37
+ upscale_model = utils.load_sd_upscale("model_real_esran/RealESRGAN_x4.pth", device)
38
+ frame_interpolation_model = load_rife_model("model_rife")
39
+
40
+ 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.
41
+ 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.
42
+ There are a few rules to follow:
43
+ You will only ever output a single video description per user request.
44
+ When modifications are requested , you should not simply make the description longer . You should refactor the entire description to integrate the suggestions.
45
+ 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.
46
+ Video descriptions must have the same num of words as examples below. Extra words will be ignored.
47
+ """
48
+
49
+ def convert_prompt(prompt: str, retry_times: int = 3) -> str:
50
+ if not os.environ.get("OPENAI_API_KEY"):
51
+ return prompt
52
+ client = OpenAI()
53
+ text = prompt.strip()
54
+
55
+ for i in range(retry_times):
56
+ response = client.chat.completions.create(
57
+ messages=[
58
+ {"role": "system", "content": sys_prompt},
59
+ {
60
+ "role": "user",
61
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "a girl is on the beach"',
62
+ },
63
+ {
64
+ "role": "assistant",
65
+ "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.",
66
+ },
67
+ {
68
+ "role": "user",
69
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "A man jogging on a football field"',
70
+ },
71
+ {
72
+ "role": "assistant",
73
+ "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.",
74
+ },
75
+ {
76
+ "role": "user",
77
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : " A woman is dancing, HD footage, close-up"',
78
+ },
79
+ {
80
+ "role": "assistant",
81
+ "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.",
82
+ },
83
+ {
84
+ "role": "user",
85
+ "content": f'Create an imaginative video descriptive caption or modify an earlier caption in ENGLISH for the user input: "{text}"',
86
+ },
87
+ ],
88
+ model="glm-4-plus",
89
+ temperature=0.01,
90
+ top_p=0.7,
91
+ stream=False,
92
+ max_tokens=200,
93
+ )
94
+ if response.choices:
95
+ return response.choices[0].message.content
96
+ return prompt
97
+
98
+ def infer(
99
+ prompt: str,
100
+ seed: int = -1,
101
+ progress=gr.Progress(track_tqdm=True),
102
+ ):
103
+ if seed == -1:
104
+ seed = random.randint(0, 2**8 - 1)
105
+
106
+ pipe.to(device)
107
+ video_pt = pipe(
108
+ prompt=prompt,
109
+ num_videos_per_prompt=1,
110
+ num_inference_steps=50,
111
+ num_frames=49,
112
+ use_dynamic_cfg=True,
113
+ output_type="pt",
114
+ guidance_scale=7.0,
115
+ generator=torch.Generator(device="cpu").manual_seed(seed),
116
+ ).frames
117
+ pipe.to("cpu")
118
+ gc.collect()
119
+ torch.cuda.empty_cache()
120
+ return (video_pt, seed)
121
+
122
+ def convert_to_gif(video_path):
123
+ clip = mp.VideoFileClip(video_path)
124
+ clip = clip.set_fps(8)
125
+ clip = clip.resize(height=240)
126
+ gif_path = video_path.replace(".mp4", ".gif")
127
+ clip.write_gif(gif_path, fps=8)
128
+ return gif_path
129
+
130
+ def delete_old_files():
131
+ while True:
132
+ now = datetime.now()
133
+ cutoff = now - timedelta(minutes=10)
134
+ directories = ["./output", "./gradio_tmp"]
135
+
136
+ for directory in directories:
137
+ for filename in os.listdir(directory):
138
+ file_path = os.path.join(directory, filename)
139
+ if os.path.isfile(file_path):
140
+ file_mtime = datetime.fromtimestamp(os.path.getmtime(file_path))
141
+ if file_mtime < cutoff:
142
+ os.remove(file_path)
143
+ time.sleep(600)
144
+
145
+ threading.Thread(target=delete_old_files, daemon=True).start()
146
+
147
+ with gr.Blocks() as demo:
148
+ gr.Markdown("""
149
+ <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
150
+ CogVideoX-5B Huggingface Space🤗
151
+ </div>
152
+ <div style="text-align: center;">
153
+ <a href="https://huggingface.co/THUDM/CogVideoX-5B">🤗 5B(T2V) Model Hub</a> |
154
+ <a href="https://huggingface.co/THUDM/CogVideoX-5B-I2V">🤗 5B(I2V) Model Hub</a> |
155
+ <a href="https://github.com/THUDM/CogVideo">🌐 Github</a> |
156
+ <a href="https://arxiv.org/pdf/2408.06072">📜 arxiv </a>
157
+ </div>
158
+ <div style="text-align: center;display: flex;justify-content: center;align-items: center;margin-top: 1em;margin-bottom: .5em;">
159
+ <span>If the Space is too busy, duplicate it to use privately</span>
160
+ <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="
161
+ margin-left: .75em;
162
+ "></a>
163
+ </div>
164
+ <div style="text-align: center; font-size: 15px; font-weight: bold; color: red; margin-bottom: 20px;">
165
+ ⚠️ This demo is for academic research and experiential use only.
166
+ </div>
167
+ """)
168
+ with gr.Row():
169
+ with gr.Column():
170
+ prompt = gr.Textbox(label="Prompt (Less than 200 Words)", placeholder="Enter your prompt here", lines=5)
171
+
172
+ with gr.Row():
173
+ gr.Markdown(
174
+ "✨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."
175
+ )
176
+ enhance_button = gr.Button("✨ Enhance Prompt(Optional)")
177
+ with gr.Group():
178
+ with gr.Column():
179
+ with gr.Row():
180
+ seed_param = gr.Number(
181
+ label="Inference Seed (Enter a positive number, -1 for random)", value=-1
182
+ )
183
+ with gr.Row():
184
+ enable_scale = gr.Checkbox(label="Super-Resolution (720 × 480 -> 2880 × 1920)", value=False)
185
+ enable_rife = gr.Checkbox(label="Frame Interpolation (8fps -> 16fps)", value=False)
186
+ gr.Markdown(
187
+ "✨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."
188
+ )
189
+
190
+ generate_button = gr.Button("🎬 Generate Video")
191
+
192
+ with gr.Column():
193
+ video_output = gr.Video(label="CogVideoX Generate Video", width=720, height=480)
194
+ with gr.Row():
195
+ download_video_button = gr.File(label="📥 Download Video", visible=False)
196
+ download_gif_button = gr.File(label="📥 Download GIF", visible=False)
197
+ seed_text = gr.Number(label="Seed Used for Video Generation", visible=False)
198
+
199
+ gr.Markdown("""
200
+ <table border="0" style="width: 100%; text-align: left; margin-top: 20px;">
201
+ <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
202
+ 🎥 Video Gallery
203
+ </div>
204
+ <tr>
205
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
206
+ <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>
207
+ </td>
208
+ <td style="width: 25%; vertical-align: top;">
209
+ <video src="https://github.com/user-attachments/assets/cf5953ea-96d3-48fd-9907-c4708752c714" width="100%" controls autoplay loop></video>
210
+ </td>
211
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
212
+ <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>
213
+ </td>
214
+ <td style="width: 25%; vertical-align: top;">
215
+ <video src="https://github.com/user-attachments/assets/fe0a78e6-b669-4800-8cf0-b5f9b5145b52" width="100%" controls autoplay loop></video>
216
+ </td>
217
+ </tr>
218
+ <tr>
219
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
220
+ <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>
221
+ </td>
222
+ <td style="width: 25%; vertical-align: top;">
223
+ <video src="https://github.com/user-attachments/assets/c182f606-8f8c-421d-b414-8487070fcfcb" width="100%" controls autoplay loop></video>
224
+ </td>
225
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
226
+ <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>
227
+ </td>
228
+ <td style="width: 25%; vertical-align: top;">
229
+ <video src="https://github.com/user-attachments/assets/7db2bbce-194d-434d-a605-350254b6c298" width="100%" controls autoplay loop></video>
230
+ </td>
231
+ </tr>
232
+ <tr>
233
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
234
+ <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>
235
+ </td>
236
+ <td style="width: 25%; vertical-align: top;">
237
+ <video src="https://github.com/user-attachments/assets/62b01046-8cab-44cc-bd45-4d965bb615ec" width="100%" controls autoplay loop></video>
238
+ </td>
239
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
240
+ <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>
241
+ </td>
242
+ <td style="width: 25%; vertical-align: top;">
243
+ <video src="https://github.com/user-attachments/assets/d78e552a-4b3f-4b81-ac3f-3898079554f6" width="100%" controls autoplay loop></video>
244
+ </td>
245
+ </tr>
246
+ <tr>
247
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
248
+ <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>
249
+ </td>
250
+ <td style="width: 25%; vertical-align: top;">
251
+ <video src="https://github.com/user-attachments/assets/30894f12-c741-44a2-9e6e-ddcacc231e5b" width="100%" controls autoplay loop></video>
252
+ </td>
253
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
254
+ <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>
255
+ </td>
256
+ <td style="width: 25%; vertical-align: top;">
257
+ <video src="https://github.com/user-attachments/assets/926575ca-7150-435b-a0ff-4900a963297b" width="100%" controls autoplay loop></video>
258
+ </td>
259
+ </tr>
260
+ </table>
261
+ """)
262
+
263
+ def generate(
264
+ prompt,
265
+ seed_value,
266
+ scale_status,
267
+ rife_status,
268
+ progress=gr.Progress(track_tqdm=True)
269
+ ):
270
+ latents, seed = infer(
271
+ prompt,
272
+ seed=seed_value,
273
+ progress=progress,
274
+ )
275
+ if scale_status:
276
+ latents = utils.upscale_batch_and_concatenate(upscale_model, latents, device)
277
+ if rife_status:
278
+ latents = rife_inference_with_latents(frame_interpolation_model, latents)
279
+
280
+ batch_size = latents.shape[0]
281
+ batch_video_frames = []
282
+ for batch_idx in range(batch_size):
283
+ pt_image = latents[batch_idx]
284
+ pt_image = torch.stack([pt_image[i] for i in range(pt_image.shape[0])])
285
+
286
+ image_np = VaeImageProcessor.pt_to_numpy(pt_image)
287
+ image_pil = VaeImageProcessor.numpy_to_pil(image_np)
288
+ batch_video_frames.append(image_pil)
289
+
290
+ video_path = utils.save_video(batch_video_frames[0], fps=math.ceil((len(batch_video_frames[0]) - 1) / 6))
291
+ video_update = gr.update(visible=True, value=video_path)
292
+ gif_path = convert_to_gif(video_path)
293
+ gif_update = gr.update(visible=True, value=gif_path)
294
+ seed_update = gr.update(visible=True, value=seed)
295
+
296
+ return video_path, video_update, gif_update, seed_update
297
+
298
+ def enhance_prompt_func(prompt):
299
+ return convert_prompt(prompt, retry_times=1)
300
+
301
+ generate_button.click(
302
+ generate,
303
+ inputs=[prompt, seed_param, enable_scale, enable_rife],
304
+ outputs=[video_output, download_video_button, download_gif_button, seed_text],
305
+ )
306
+
307
+ enhance_button.click(enhance_prompt_func, inputs=[prompt], outputs=[prompt])
308
+
309
+ if __name__ == "__main__":
310
+ demo.queue(max_size=15)
311
+ demo.launch(share = True)
t2v_app_t4.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ import random
4
+ import threading
5
+ import time
6
+ import cv2
7
+ import tempfile
8
+ import imageio_ffmpeg
9
+ import gradio as gr
10
+ import torch
11
+ from PIL import Image
12
+ from diffusers import (
13
+ CogVideoXPipeline,
14
+ CogVideoXDPMScheduler,
15
+ CogVideoXTransformer3DModel,
16
+ AutoencoderKLCogVideoX,
17
+ )
18
+ from diffusers.utils import load_video, load_image
19
+ from datetime import datetime, timedelta
20
+ from diffusers.image_processor import VaeImageProcessor
21
+ from transformers import T5EncoderModel
22
+ from openai import OpenAI
23
+ import moviepy.editor as mp
24
+ import utils
25
+ from rife_model import load_rife_model, rife_inference_with_latents
26
+ from huggingface_hub import hf_hub_download, snapshot_download
27
+ import gc
28
+
29
+ device = "cuda" if torch.cuda.is_available() else "cpu"
30
+
31
+ hf_hub_download(repo_id="ai-forever/Real-ESRGAN", filename="RealESRGAN_x4.pth", local_dir="model_real_esran")
32
+ snapshot_download(repo_id="AlexWortega/RIFE", local_dir="model_rife")
33
+
34
+ # 初始化 transformer, text_encoder 和 vae
35
+ model_id = "THUDM/CogVideoX-5b"
36
+ transformer = CogVideoXTransformer3DModel.from_pretrained("camenduru/cogvideox-5b-float16", subfolder="transformer", torch_dtype=torch.float16)
37
+ text_encoder = T5EncoderModel.from_pretrained("camenduru/cogvideox-5b-float16", subfolder="text_encoder", torch_dtype=torch.float16)
38
+ vae = AutoencoderKLCogVideoX.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float16)
39
+
40
+ # 创建管道
41
+ pipe = CogVideoXPipeline.from_pretrained(
42
+ model_id,
43
+ text_encoder=text_encoder,
44
+ transformer=transformer,
45
+ vae=vae,
46
+ torch_dtype=torch.float16,
47
+ )
48
+
49
+ # 启用内存优化
50
+ pipe.enable_sequential_cpu_offload()
51
+
52
+ os.makedirs("./output", exist_ok=True)
53
+ os.makedirs("./gradio_tmp", exist_ok=True)
54
+
55
+ upscale_model = utils.load_sd_upscale("model_real_esran/RealESRGAN_x4.pth", device)
56
+ frame_interpolation_model = load_rife_model("model_rife")
57
+
58
+ 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.
59
+ 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.
60
+ There are a few rules to follow:
61
+ You will only ever output a single video description per user request.
62
+ When modifications are requested , you should not simply make the description longer . You should refactor the entire description to integrate the suggestions.
63
+ 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.
64
+ Video descriptions must have the same num of words as examples below. Extra words will be ignored.
65
+ """
66
+
67
+ def convert_prompt(prompt: str, retry_times: int = 3) -> str:
68
+ if not os.environ.get("OPENAI_API_KEY"):
69
+ return prompt
70
+ client = OpenAI()
71
+ text = prompt.strip()
72
+
73
+ for i in range(retry_times):
74
+ response = client.chat.completions.create(
75
+ messages=[
76
+ {"role": "system", "content": sys_prompt},
77
+ {
78
+ "role": "user",
79
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "a girl is on the beach"',
80
+ },
81
+ {
82
+ "role": "assistant",
83
+ "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.",
84
+ },
85
+ {
86
+ "role": "user",
87
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "A man jogging on a football field"',
88
+ },
89
+ {
90
+ "role": "assistant",
91
+ "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.",
92
+ },
93
+ {
94
+ "role": "user",
95
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : " A woman is dancing, HD footage, close-up"',
96
+ },
97
+ {
98
+ "role": "assistant",
99
+ "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.",
100
+ },
101
+ {
102
+ "role": "user",
103
+ "content": f'Create an imaginative video descriptive caption or modify an earlier caption in ENGLISH for the user input: "{text}"',
104
+ },
105
+ ],
106
+ model="glm-4-plus",
107
+ temperature=0.01,
108
+ top_p=0.7,
109
+ stream=False,
110
+ max_tokens=200,
111
+ )
112
+ if response.choices:
113
+ return response.choices[0].message.content
114
+ return prompt
115
+
116
+ def infer(
117
+ prompt: str,
118
+ seed: int = -1,
119
+ progress=gr.Progress(track_tqdm=True),
120
+ ):
121
+ if seed == -1:
122
+ seed = random.randint(0, 2**8 - 1)
123
+
124
+ pipe.to(device)
125
+ video_pt = pipe(
126
+ prompt=prompt,
127
+ num_videos_per_prompt=1,
128
+ num_inference_steps=50,
129
+ num_frames=49,
130
+ use_dynamic_cfg=True,
131
+ output_type="pt",
132
+ guidance_scale=7.0,
133
+ generator=torch.Generator(device="cpu").manual_seed(seed),
134
+ ).frames
135
+ pipe.to("cpu")
136
+ gc.collect()
137
+ torch.cuda.empty_cache()
138
+ return (video_pt, seed)
139
+
140
+ def convert_to_gif(video_path):
141
+ clip = mp.VideoFileClip(video_path)
142
+ clip = clip.set_fps(8)
143
+ clip = clip.resize(height=240)
144
+ gif_path = video_path.replace(".mp4", ".gif")
145
+ clip.write_gif(gif_path, fps=8)
146
+ return gif_path
147
+
148
+ def delete_old_files():
149
+ while True:
150
+ now = datetime.now()
151
+ cutoff = now - timedelta(minutes=10)
152
+ directories = ["./output", "./gradio_tmp"]
153
+
154
+ for directory in directories:
155
+ for filename in os.listdir(directory):
156
+ file_path = os.path.join(directory, filename)
157
+ if os.path.isfile(file_path):
158
+ file_mtime = datetime.fromtimestamp(os.path.getmtime(file_path))
159
+ if file_mtime < cutoff:
160
+ os.remove(file_path)
161
+ time.sleep(600)
162
+
163
+ threading.Thread(target=delete_old_files, daemon=True).start()
164
+
165
+ with gr.Blocks() as demo:
166
+ gr.Markdown("""
167
+ <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
168
+ CogVideoX-5B Huggingface Space🤗
169
+ </div>
170
+ <div style="text-align: center;">
171
+ <a href="https://huggingface.co/THUDM/CogVideoX-5B">🤗 5B(T2V) Model Hub</a> |
172
+ <a href="https://huggingface.co/THUDM/CogVideoX-5B-I2V">🤗 5B(I2V) Model Hub</a> |
173
+ <a href="https://github.com/THUDM/CogVideo">🌐 Github</a> |
174
+ <a href="https://arxiv.org/pdf/2408.06072">📜 arxiv </a>
175
+ </div>
176
+ <div style="text-align: center;display: flex;justify-content: center;align-items: center;margin-top: 1em;margin-bottom: .5em;">
177
+ <span>If the Space is too busy, duplicate it to use privately</span>
178
+ <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="
179
+ margin-left: .75em;
180
+ "></a>
181
+ </div>
182
+ <div style="text-align: center; font-size: 15px; font-weight: bold; color: red; margin-bottom: 20px;">
183
+ ⚠️ This demo is for academic research and experiential use only.
184
+ </div>
185
+ """)
186
+ with gr.Row():
187
+ with gr.Column():
188
+ prompt = gr.Textbox(label="Prompt (Less than 200 Words)", placeholder="Enter your prompt here", lines=5)
189
+
190
+ with gr.Row():
191
+ gr.Markdown(
192
+ "✨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."
193
+ )
194
+ enhance_button = gr.Button("✨ Enhance Prompt(Optional)")
195
+ with gr.Group():
196
+ with gr.Column():
197
+ with gr.Row():
198
+ seed_param = gr.Number(
199
+ label="Inference Seed (Enter a positive number, -1 for random)", value=-1
200
+ )
201
+ with gr.Row():
202
+ enable_scale = gr.Checkbox(label="Super-Resolution (720 × 480 -> 2880 × 1920)", value=False)
203
+ enable_rife = gr.Checkbox(label="Frame Interpolation (8fps -> 16fps)", value=False)
204
+ gr.Markdown(
205
+ "✨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."
206
+ )
207
+
208
+ generate_button = gr.Button("🎬 Generate Video")
209
+
210
+ with gr.Column():
211
+ video_output = gr.Video(label="CogVideoX Generate Video", width=720, height=480)
212
+ with gr.Row():
213
+ download_video_button = gr.File(label="📥 Download Video", visible=False)
214
+ download_gif_button = gr.File(label="📥 Download GIF", visible=False)
215
+ seed_text = gr.Number(label="Seed Used for Video Generation", visible=False)
216
+
217
+ gr.Markdown("""
218
+ <table border="0" style="width: 100%; text-align: left; margin-top: 20px;">
219
+ <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
220
+ 🎥 Video Gallery
221
+ </div>
222
+ <tr>
223
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
224
+ <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>
225
+ </td>
226
+ <td style="width: 25%; vertical-align: top;">
227
+ <video src="https://github.com/user-attachments/assets/cf5953ea-96d3-48fd-9907-c4708752c714" width="100%" controls autoplay loop></video>
228
+ </td>
229
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
230
+ <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>
231
+ </td>
232
+ <td style="width: 25%; vertical-align: top;">
233
+ <video src="https://github.com/user-attachments/assets/fe0a78e6-b669-4800-8cf0-b5f9b5145b52" width="100%" controls autoplay loop></video>
234
+ </td>
235
+ </tr>
236
+ <tr>
237
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
238
+ <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>
239
+ </td>
240
+ <td style="width: 25%; vertical-align: top;">
241
+ <video src="https://github.com/user-attachments/assets/c182f606-8f8c-421d-b414-8487070fcfcb" width="100%" controls autoplay loop></video>
242
+ </td>
243
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
244
+ <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>
245
+ </td>
246
+ <td style="width: 25%; vertical-align: top;">
247
+ <video src="https://github.com/user-attachments/assets/7db2bbce-194d-434d-a605-350254b6c298" width="100%" controls autoplay loop></video>
248
+ </td>
249
+ </tr>
250
+ <tr>
251
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
252
+ <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>
253
+ </td>
254
+ <td style="width: 25%; vertical-align: top;">
255
+ <video src="https://github.com/user-attachments/assets/62b01046-8cab-44cc-bd45-4d965bb615ec" width="100%" controls autoplay loop></video>
256
+ </td>
257
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
258
+ <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>
259
+ </td>
260
+ <td style="width: 25%; vertical-align: top;">
261
+ <video src="https://github.com/user-attachments/assets/d78e552a-4b3f-4b81-ac3f-3898079554f6" width="100%" controls autoplay loop></video>
262
+ </td>
263
+ </tr>
264
+ <tr>
265
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
266
+ <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>
267
+ </td>
268
+ <td style="width: 25%; vertical-align: top;">
269
+ <video src="https://github.com/user-attachments/assets/30894f12-c741-44a2-9e6e-ddcacc231e5b" width="100%" controls autoplay loop></video>
270
+ </td>
271
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
272
+ <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>
273
+ </td>
274
+ <td style="width: 25%; vertical-align: top;">
275
+ <video src="https://github.com/user-attachments/assets/926575ca-7150-435b-a0ff-4900a963297b" width="100%" controls autoplay loop></video>
276
+ </td>
277
+ </tr>
278
+ </table>
279
+ """)
280
+
281
+ def generate(
282
+ prompt,
283
+ seed_value,
284
+ scale_status,
285
+ rife_status,
286
+ progress=gr.Progress(track_tqdm=True)
287
+ ):
288
+ latents, seed = infer(
289
+ prompt,
290
+ seed=seed_value,
291
+ progress=progress,
292
+ )
293
+ if scale_status:
294
+ latents = utils.upscale_batch_and_concatenate(upscale_model, latents, device)
295
+ if rife_status:
296
+ latents = rife_inference_with_latents(frame_interpolation_model, latents)
297
+
298
+ batch_size = latents.shape[0]
299
+ batch_video_frames = []
300
+ for batch_idx in range(batch_size):
301
+ pt_image = latents[batch_idx]
302
+ pt_image = torch.stack([pt_image[i] for i in range(pt_image.shape[0])])
303
+
304
+ image_np = VaeImageProcessor.pt_to_numpy(pt_image)
305
+ image_pil = VaeImageProcessor.numpy_to_pil(image_np)
306
+ batch_video_frames.append(image_pil)
307
+
308
+ video_path = utils.save_video(batch_video_frames[0], fps=math.ceil((len(batch_video_frames[0]) - 1) / 6))
309
+ video_update = gr.update(visible=True, value=video_path)
310
+ gif_path = convert_to_gif(video_path)
311
+ gif_update = gr.update(visible=True, value=gif_path)
312
+ seed_update = gr.update(visible=True, value=seed)
313
+
314
+ return video_path, video_update, gif_update, seed_update
315
+
316
+ def enhance_prompt_func(prompt):
317
+ return convert_prompt(prompt, retry_times=1)
318
+
319
+ generate_button.click(
320
+ generate,
321
+ inputs=[prompt, seed_param, enable_scale, enable_rife],
322
+ outputs=[video_output, download_video_button, download_gif_button, seed_text],
323
+ )
324
+
325
+ enhance_button.click(enhance_prompt_func, inputs=[prompt], outputs=[prompt])
326
+
327
+ if __name__ == "__main__":
328
+ demo.queue(max_size=15)
329
+ demo.launch(share = True)
v2v_app.py ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ import random
4
+ import threading
5
+ import time
6
+ import cv2
7
+ import tempfile
8
+ import imageio_ffmpeg
9
+ import gradio as gr
10
+ import torch
11
+ from PIL import Image
12
+ from diffusers import (
13
+ CogVideoXPipeline,
14
+ CogVideoXDPMScheduler,
15
+ CogVideoXVideoToVideoPipeline,
16
+ )
17
+ from diffusers.utils import load_video, load_image
18
+ from datetime import datetime, timedelta
19
+ from diffusers.image_processor import VaeImageProcessor
20
+ from openai import OpenAI
21
+ import moviepy.editor as mp
22
+ import utils
23
+ from rife_model import load_rife_model, rife_inference_with_latents
24
+ from huggingface_hub import hf_hub_download, snapshot_download
25
+ import gc
26
+
27
+ device = "cuda" if torch.cuda.is_available() else "cpu"
28
+
29
+ hf_hub_download(repo_id="ai-forever/Real-ESRGAN", filename="RealESRGAN_x4.pth", local_dir="model_real_esran")
30
+ snapshot_download(repo_id="AlexWortega/RIFE", local_dir="model_rife")
31
+
32
+ pipe = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-5b", torch_dtype=torch.bfloat16).to("cpu")
33
+ pipe.scheduler = CogVideoXDPMScheduler.from_config(pipe.scheduler.config, timestep_spacing="trailing")
34
+
35
+ os.makedirs("./output", exist_ok=True)
36
+ os.makedirs("./gradio_tmp", exist_ok=True)
37
+
38
+ upscale_model = utils.load_sd_upscale("model_real_esran/RealESRGAN_x4.pth", device)
39
+ frame_interpolation_model = load_rife_model("model_rife")
40
+
41
+ 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.
42
+ 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.
43
+ There are a few rules to follow:
44
+ You will only ever output a single video description per user request.
45
+ When modifications are requested , you should not simply make the description longer . You should refactor the entire description to integrate the suggestions.
46
+ 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.
47
+ Video descriptions must have the same num of words as examples below. Extra words will be ignored.
48
+ """
49
+
50
+ def convert_prompt(prompt: str, retry_times: int = 3) -> str:
51
+ if not os.environ.get("OPENAI_API_KEY"):
52
+ return prompt
53
+ client = OpenAI()
54
+ text = prompt.strip()
55
+
56
+ for i in range(retry_times):
57
+ response = client.chat.completions.create(
58
+ messages=[
59
+ {"role": "system", "content": sys_prompt},
60
+ {
61
+ "role": "user",
62
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "a girl is on the beach"',
63
+ },
64
+ {
65
+ "role": "assistant",
66
+ "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.",
67
+ },
68
+ {
69
+ "role": "user",
70
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "A man jogging on a football field"',
71
+ },
72
+ {
73
+ "role": "assistant",
74
+ "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.",
75
+ },
76
+ {
77
+ "role": "user",
78
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : " A woman is dancing, HD footage, close-up"',
79
+ },
80
+ {
81
+ "role": "assistant",
82
+ "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.",
83
+ },
84
+ {
85
+ "role": "user",
86
+ "content": f'Create an imaginative video descriptive caption or modify an earlier caption in ENGLISH for the user input: "{text}"',
87
+ },
88
+ ],
89
+ model="glm-4-plus",
90
+ temperature=0.01,
91
+ top_p=0.7,
92
+ stream=False,
93
+ max_tokens=200,
94
+ )
95
+ if response.choices:
96
+ return response.choices[0].message.content
97
+ return prompt
98
+
99
+ def infer(
100
+ prompt: str,
101
+ video_input: str,
102
+ video_strenght: float,
103
+ seed: int = -1,
104
+ progress=gr.Progress(track_tqdm=True),
105
+ ):
106
+ if seed == -1:
107
+ seed = random.randint(0, 2**8 - 1)
108
+
109
+ video = load_video(video_input)[:49] # Limit to 49 frames
110
+ pipe_video = CogVideoXVideoToVideoPipeline.from_pretrained(
111
+ "THUDM/CogVideoX-5b",
112
+ transformer=pipe.transformer,
113
+ vae=pipe.vae,
114
+ scheduler=pipe.scheduler,
115
+ tokenizer=pipe.tokenizer,
116
+ text_encoder=pipe.text_encoder,
117
+ torch_dtype=torch.bfloat16
118
+ ).to(device)
119
+ video_pt = pipe_video(
120
+ video=video,
121
+ prompt=prompt,
122
+ num_inference_steps=50,
123
+ num_videos_per_prompt=1,
124
+ strength=video_strenght,
125
+ use_dynamic_cfg=True,
126
+ output_type="pt",
127
+ guidance_scale=7.0,
128
+ generator=torch.Generator(device="cpu").manual_seed(seed),
129
+ ).frames
130
+ pipe_video.to("cpu")
131
+ del pipe_video
132
+ gc.collect()
133
+ torch.cuda.empty_cache()
134
+ return (video_pt, seed)
135
+
136
+ def convert_to_gif(video_path):
137
+ clip = mp.VideoFileClip(video_path)
138
+ clip = clip.set_fps(8)
139
+ clip = clip.resize(height=240)
140
+ gif_path = video_path.replace(".mp4", ".gif")
141
+ clip.write_gif(gif_path, fps=8)
142
+ return gif_path
143
+
144
+ def delete_old_files():
145
+ while True:
146
+ now = datetime.now()
147
+ cutoff = now - timedelta(minutes=10)
148
+ directories = ["./output", "./gradio_tmp"]
149
+
150
+ for directory in directories:
151
+ for filename in os.listdir(directory):
152
+ file_path = os.path.join(directory, filename)
153
+ if os.path.isfile(file_path):
154
+ file_mtime = datetime.fromtimestamp(os.path.getmtime(file_path))
155
+ if file_mtime < cutoff:
156
+ os.remove(file_path)
157
+ time.sleep(600)
158
+
159
+ threading.Thread(target=delete_old_files, daemon=True).start()
160
+
161
+ with gr.Blocks() as demo:
162
+ gr.Markdown("""
163
+ <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
164
+ CogVideoX-5B Huggingface Space🤗
165
+ </div>
166
+ <div style="text-align: center;">
167
+ <a href="https://huggingface.co/THUDM/CogVideoX-5B">🤗 5B(T2V) Model Hub</a> |
168
+ <a href="https://huggingface.co/THUDM/CogVideoX-5B-I2V">🤗 5B(I2V) Model Hub</a> |
169
+ <a href="https://github.com/THUDM/CogVideo">🌐 Github</a> |
170
+ <a href="https://arxiv.org/pdf/2408.06072">📜 arxiv </a>
171
+ </div>
172
+ <div style="text-align: center;display: flex;justify-content: center;align-items: center;margin-top: 1em;margin-bottom: .5em;">
173
+ <span>If the Space is too busy, duplicate it to use privately</span>
174
+ <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="
175
+ margin-left: .75em;
176
+ "></a>
177
+ </div>
178
+ <div style="text-align: center; font-size: 15px; font-weight: bold; color: red; margin-bottom: 20px;">
179
+ ⚠️ This demo is for academic research and experiential use only.
180
+ </div>
181
+ """)
182
+ with gr.Row():
183
+ with gr.Column():
184
+ with gr.Accordion("V2V: Video Input (cannot be used simultaneously with image input)", open=False):
185
+ video_input = gr.Video(label="Input Video (will be cropped to 49 frames, 6 seconds at 8fps)")
186
+ strength = gr.Slider(0.1, 1.0, value=0.8, step=0.01, label="Strength")
187
+ prompt = gr.Textbox(label="Prompt (Less than 200 Words)", placeholder="Enter your prompt here", lines=5)
188
+
189
+ with gr.Row():
190
+ gr.Markdown(
191
+ "✨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."
192
+ )
193
+ enhance_button = gr.Button("✨ Enhance Prompt(Optional)")
194
+ with gr.Group():
195
+ with gr.Column():
196
+ with gr.Row():
197
+ seed_param = gr.Number(
198
+ label="Inference Seed (Enter a positive number, -1 for random)", value=-1
199
+ )
200
+ with gr.Row():
201
+ enable_scale = gr.Checkbox(label="Super-Resolution (720 × 480 -> 2880 × 1920)", value=False)
202
+ enable_rife = gr.Checkbox(label="Frame Interpolation (8fps -> 16fps)", value=False)
203
+ gr.Markdown(
204
+ "✨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."
205
+ )
206
+
207
+ generate_button = gr.Button("🎬 Generate Video")
208
+
209
+ with gr.Column():
210
+ video_output = gr.Video(label="CogVideoX Generate Video", width=720, height=480)
211
+ with gr.Row():
212
+ download_video_button = gr.File(label="📥 Download Video", visible=False)
213
+ download_gif_button = gr.File(label="📥 Download GIF", visible=False)
214
+ seed_text = gr.Number(label="Seed Used for Video Generation", visible=False)
215
+
216
+ gr.Markdown("""
217
+ <table border="0" style="width: 100%; text-align: left; margin-top: 20px;">
218
+ <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
219
+ 🎥 Video Gallery
220
+ </div>
221
+ <tr>
222
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
223
+ <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>
224
+ </td>
225
+ <td style="width: 25%; vertical-align: top;">
226
+ <video src="https://github.com/user-attachments/assets/cf5953ea-96d3-48fd-9907-c4708752c714" width="100%" controls autoplay loop></video>
227
+ </td>
228
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
229
+ <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>
230
+ </td>
231
+ <td style="width: 25%; vertical-align: top;">
232
+ <video src="https://github.com/user-attachments/assets/fe0a78e6-b669-4800-8cf0-b5f9b5145b52" width="100%" controls autoplay loop></video>
233
+ </td>
234
+ </tr>
235
+ <tr>
236
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
237
+ <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>
238
+ </td>
239
+ <td style="width: 25%; vertical-align: top;">
240
+ <video src="https://github.com/user-attachments/assets/c182f606-8f8c-421d-b414-8487070fcfcb" width="100%" controls autoplay loop></video>
241
+ </td>
242
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
243
+ <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>
244
+ </td>
245
+ <td style="width: 25%; vertical-align: top;">
246
+ <video src="https://github.com/user-attachments/assets/7db2bbce-194d-434d-a605-350254b6c298" width="100%" controls autoplay loop></video>
247
+ </td>
248
+ </tr>
249
+ <tr>
250
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
251
+ <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>
252
+ </td>
253
+ <td style="width: 25%; vertical-align: top;">
254
+ <video src="https://github.com/user-attachments/assets/62b01046-8cab-44cc-bd45-4d965bb615ec" width="100%" controls autoplay loop></video>
255
+ </td>
256
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
257
+ <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>
258
+ </td>
259
+ <td style="width: 25%; vertical-align: top;">
260
+ <video src="https://github.com/user-attachments/assets/d78e552a-4b3f-4b81-ac3f-3898079554f6" width="100%" controls autoplay loop></video>
261
+ </td>
262
+ </tr>
263
+ <tr>
264
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
265
+ <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>
266
+ </td>
267
+ <td style="width: 25%; vertical-align: top;">
268
+ <video src="https://github.com/user-attachments/assets/30894f12-c741-44a2-9e6e-ddcacc231e5b" width="100%" controls autoplay loop></video>
269
+ </td>
270
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
271
+ <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>
272
+ </td>
273
+ <td style="width: 25%; vertical-align: top;">
274
+ <video src="https://github.com/user-attachments/assets/926575ca-7150-435b-a0ff-4900a963297b" width="100%" controls autoplay loop></video>
275
+ </td>
276
+ </tr>
277
+ </table>
278
+ """)
279
+
280
+ def generate(
281
+ prompt,
282
+ video_input,
283
+ video_strength,
284
+ seed_value,
285
+ scale_status,
286
+ rife_status,
287
+ progress=gr.Progress(track_tqdm=True)
288
+ ):
289
+ latents, seed = infer(
290
+ prompt,
291
+ video_input,
292
+ video_strength,
293
+ seed=seed_value,
294
+ progress=progress,
295
+ )
296
+ if scale_status:
297
+ latents = utils.upscale_batch_and_concatenate(upscale_model, latents, device)
298
+ if rife_status:
299
+ latents = rife_inference_with_latents(frame_interpolation_model, latents)
300
+
301
+ batch_size = latents.shape[0]
302
+ batch_video_frames = []
303
+ for batch_idx in range(batch_size):
304
+ pt_image = latents[batch_idx]
305
+ pt_image = torch.stack([pt_image[i] for i in range(pt_image.shape[0])])
306
+
307
+ image_np = VaeImageProcessor.pt_to_numpy(pt_image)
308
+ image_pil = VaeImageProcessor.numpy_to_pil(image_np)
309
+ batch_video_frames.append(image_pil)
310
+
311
+ video_path = utils.save_video(batch_video_frames[0], fps=math.ceil((len(batch_video_frames[0]) - 1) / 6))
312
+ video_update = gr.update(visible=True, value=video_path)
313
+ gif_path = convert_to_gif(video_path)
314
+ gif_update = gr.update(visible=True, value=gif_path)
315
+ seed_update = gr.update(visible=True, value=seed)
316
+
317
+ return video_path, video_update, gif_update, seed_update
318
+
319
+ def enhance_prompt_func(prompt):
320
+ return convert_prompt(prompt, retry_times=1)
321
+
322
+ generate_button.click(
323
+ generate,
324
+ inputs=[prompt, video_input, strength, seed_param, enable_scale, enable_rife],
325
+ outputs=[video_output, download_video_button, download_gif_button, seed_text],
326
+ )
327
+
328
+ enhance_button.click(enhance_prompt_func, inputs=[prompt], outputs=[prompt])
329
+
330
+ if __name__ == "__main__":
331
+ demo.queue(max_size=15)
332
+ demo.launch(share = True)
v2v_app_t4.py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ import random
4
+ import threading
5
+ import time
6
+ import cv2
7
+ import tempfile
8
+ import imageio_ffmpeg
9
+ import gradio as gr
10
+ import torch
11
+ from PIL import Image
12
+ from diffusers import (
13
+ CogVideoXPipeline,
14
+ CogVideoXDPMScheduler,
15
+ CogVideoXVideoToVideoPipeline,
16
+ CogVideoXTransformer3DModel,
17
+ AutoencoderKLCogVideoX,
18
+ )
19
+ from diffusers.utils import load_video, load_image
20
+ from datetime import datetime, timedelta
21
+ from diffusers.image_processor import VaeImageProcessor
22
+ from transformers import T5EncoderModel
23
+ from openai import OpenAI
24
+ import moviepy.editor as mp
25
+ import utils
26
+ from rife_model import load_rife_model, rife_inference_with_latents
27
+ from huggingface_hub import hf_hub_download, snapshot_download
28
+ import gc
29
+
30
+ device = "cuda" if torch.cuda.is_available() else "cpu"
31
+
32
+ hf_hub_download(repo_id="ai-forever/Real-ESRGAN", filename="RealESRGAN_x4.pth", local_dir="model_real_esran")
33
+ snapshot_download(repo_id="AlexWortega/RIFE", local_dir="model_rife")
34
+
35
+ # 初始化 transformer, text_encoder 和 vae
36
+ model_id = "THUDM/CogVideoX-5b"
37
+ transformer = CogVideoXTransformer3DModel.from_pretrained("camenduru/cogvideox-5b-float16", subfolder="transformer", torch_dtype=torch.float16)
38
+ text_encoder = T5EncoderModel.from_pretrained("camenduru/cogvideox-5b-float16", subfolder="text_encoder", torch_dtype=torch.float16)
39
+ vae = AutoencoderKLCogVideoX.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float16)
40
+
41
+ # 创建管道
42
+ pipe = CogVideoXVideoToVideoPipeline.from_pretrained(
43
+ model_id,
44
+ text_encoder=text_encoder,
45
+ transformer=transformer,
46
+ vae=vae,
47
+ torch_dtype=torch.float16,
48
+ )
49
+ pipe.scheduler = CogVideoXDPMScheduler.from_config(pipe.scheduler.config)
50
+
51
+ # 启用内存优化
52
+ pipe.enable_sequential_cpu_offload()
53
+ pipe.vae.enable_tiling()
54
+
55
+ os.makedirs("./output", exist_ok=True)
56
+ os.makedirs("./gradio_tmp", exist_ok=True)
57
+
58
+ upscale_model = utils.load_sd_upscale("model_real_esran/RealESRGAN_x4.pth", device)
59
+ frame_interpolation_model = load_rife_model("model_rife")
60
+
61
+ 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.
62
+ 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.
63
+ There are a few rules to follow:
64
+ You will only ever output a single video description per user request.
65
+ When modifications are requested , you should not simply make the description longer . You should refactor the entire description to integrate the suggestions.
66
+ 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.
67
+ Video descriptions must have the same num of words as examples below. Extra words will be ignored.
68
+ """
69
+
70
+ def convert_prompt(prompt: str, retry_times: int = 3) -> str:
71
+ if not os.environ.get("OPENAI_API_KEY"):
72
+ return prompt
73
+ client = OpenAI()
74
+ text = prompt.strip()
75
+
76
+ for i in range(retry_times):
77
+ response = client.chat.completions.create(
78
+ messages=[
79
+ {"role": "system", "content": sys_prompt},
80
+ {
81
+ "role": "user",
82
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "a girl is on the beach"',
83
+ },
84
+ {
85
+ "role": "assistant",
86
+ "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.",
87
+ },
88
+ {
89
+ "role": "user",
90
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "A man jogging on a football field"',
91
+ },
92
+ {
93
+ "role": "assistant",
94
+ "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.",
95
+ },
96
+ {
97
+ "role": "user",
98
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : " A woman is dancing, HD footage, close-up"',
99
+ },
100
+ {
101
+ "role": "assistant",
102
+ "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.",
103
+ },
104
+ {
105
+ "role": "user",
106
+ "content": f'Create an imaginative video descriptive caption or modify an earlier caption in ENGLISH for the user input: "{text}"',
107
+ },
108
+ ],
109
+ model="glm-4-plus",
110
+ temperature=0.01,
111
+ top_p=0.7,
112
+ stream=False,
113
+ max_tokens=200,
114
+ )
115
+ if response.choices:
116
+ return response.choices[0].message.content
117
+ return prompt
118
+
119
+ def infer(
120
+ prompt: str,
121
+ video_input: str,
122
+ video_strength: float,
123
+ seed: int = -1,
124
+ progress=gr.Progress(track_tqdm=True),
125
+ ):
126
+ if seed == -1:
127
+ seed = random.randint(0, 2**8 - 1)
128
+
129
+ video = load_video(video_input)[:49] # Limit to 49 frames
130
+ pipe_video = CogVideoXVideoToVideoPipeline.from_pretrained(
131
+ "THUDM/CogVideoX-5b",
132
+ transformer=transformer,
133
+ vae=vae,
134
+ scheduler=pipe.scheduler,
135
+ tokenizer=pipe.tokenizer,
136
+ text_encoder=text_encoder,
137
+ torch_dtype=torch.float16
138
+ ).to(device)
139
+ video_pt = pipe_video(
140
+ video=video,
141
+ prompt=prompt,
142
+ num_inference_steps=50,
143
+ num_videos_per_prompt=1,
144
+ strength=video_strength,
145
+ use_dynamic_cfg=True,
146
+ output_type="pt",
147
+ guidance_scale=7.0,
148
+ generator=torch.Generator(device="cpu").manual_seed(seed),
149
+ ).frames
150
+ pipe_video.to("cpu")
151
+ del pipe_video
152
+ gc.collect()
153
+ torch.cuda.empty_cache()
154
+ return (video_pt, seed)
155
+
156
+ def convert_to_gif(video_path):
157
+ clip = mp.VideoFileClip(video_path)
158
+ clip = clip.set_fps(8)
159
+ clip = clip.resize(height=240)
160
+ gif_path = video_path.replace(".mp4", ".gif")
161
+ clip.write_gif(gif_path, fps=8)
162
+ return gif_path
163
+
164
+ def delete_old_files():
165
+ while True:
166
+ now = datetime.now()
167
+ cutoff = now - timedelta(minutes=10)
168
+ directories = ["./output", "./gradio_tmp"]
169
+
170
+ for directory in directories:
171
+ for filename in os.listdir(directory):
172
+ file_path = os.path.join(directory, filename)
173
+ if os.path.isfile(file_path):
174
+ file_mtime = datetime.fromtimestamp(os.path.getmtime(file_path))
175
+ if file_mtime < cutoff:
176
+ os.remove(file_path)
177
+ time.sleep(600)
178
+
179
+ threading.Thread(target=delete_old_files, daemon=True).start()
180
+
181
+ with gr.Blocks() as demo:
182
+ gr.Markdown("""
183
+ <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
184
+ CogVideoX-5B Huggingface Space🤗
185
+ </div>
186
+ <div style="text-align: center;">
187
+ <a href="https://huggingface.co/THUDM/CogVideoX-5B">🤗 5B(T2V) Model Hub</a> |
188
+ <a href="https://huggingface.co/THUDM/CogVideoX-5B-I2V">🤗 5B(I2V) Model Hub</a> |
189
+ <a href="https://github.com/THUDM/CogVideo">🌐 Github</a> |
190
+ <a href="https://arxiv.org/pdf/2408.06072">📜 arxiv </a>
191
+ </div>
192
+ <div style="text-align: center;display: flex;justify-content: center;align-items: center;margin-top: 1em;margin-bottom: .5em;">
193
+ <span>If the Space is too busy, duplicate it to use privately</span>
194
+ <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="
195
+ margin-left: .75em;
196
+ "></a>
197
+ </div>
198
+ <div style="text-align: center; font-size: 15px; font-weight: bold; color: red; margin-bottom: 20px;">
199
+ ⚠️ This demo is for academic research and experiential use only.
200
+ </div>
201
+ """)
202
+ with gr.Row():
203
+ with gr.Column():
204
+ with gr.Accordion("V2V: Video Input (cannot be used simultaneously with image input)", open=False):
205
+ video_input = gr.Video(label="Input Video (will be cropped to 49 frames, 6 seconds at 8fps)")
206
+ strength = gr.Slider(0.1, 1.0, value=0.8, step=0.01, label="Strength")
207
+ prompt = gr.Textbox(label="Prompt (Less than 200 Words)", placeholder="Enter your prompt here", lines=5)
208
+
209
+ with gr.Row():
210
+ gr.Markdown(
211
+ "✨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."
212
+ )
213
+ enhance_button = gr.Button("✨ Enhance Prompt(Optional)")
214
+ with gr.Group():
215
+ with gr.Column():
216
+ with gr.Row():
217
+ seed_param = gr.Number(
218
+ label="Inference Seed (Enter a positive number, -1 for random)", value=-1
219
+ )
220
+ with gr.Row():
221
+ enable_scale = gr.Checkbox(label="Super-Resolution (720 × 480 -> 2880 × 1920)", value=False)
222
+ enable_rife = gr.Checkbox(label="Frame Interpolation (8fps -> 16fps)", value=False)
223
+ gr.Markdown(
224
+ "✨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."
225
+ )
226
+
227
+ generate_button = gr.Button("🎬 Generate Video")
228
+
229
+ with gr.Column():
230
+ video_output = gr.Video(label="CogVideoX Generate Video", width=720, height=480)
231
+ with gr.Row():
232
+ download_video_button = gr.File(label="📥 Download Video", visible=False)
233
+ download_gif_button = gr.File(label="📥 Download GIF", visible=False)
234
+ seed_text = gr.Number(label="Seed Used for Video Generation", visible=False)
235
+
236
+ gr.Markdown("""
237
+ <table border="0" style="width: 100%; text-align: left; margin-top: 20px;">
238
+ <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
239
+ 🎥 Video Gallery
240
+ </div>
241
+ <tr>
242
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
243
+ <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>
244
+ </td>
245
+ <td style="width: 25%; vertical-align: top;">
246
+ <video src="https://github.com/user-attachments/assets/cf5953ea-96d3-48fd-9907-c4708752c714" width="100%" controls autoplay loop></video>
247
+ </td>
248
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
249
+ <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>
250
+ </td>
251
+ <td style="width: 25%; vertical-align: top;">
252
+ <video src="https://github.com/user-attachments/assets/fe0a78e6-b669-4800-8cf0-b5f9b5145b52" width="100%" controls autoplay loop></video>
253
+ </td>
254
+ </tr>
255
+ <tr>
256
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
257
+ <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>
258
+ </td>
259
+ <td style="width: 25%; vertical-align: top;">
260
+ <video src="https://github.com/user-attachments/assets/c182f606-8f8c-421d-b414-8487070fcfcb" width="100%" controls autoplay loop></video>
261
+ </td>
262
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
263
+ <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>
264
+ </td>
265
+ <td style="width: 25%; vertical-align: top;">
266
+ <video src="https://github.com/user-attachments/assets/7db2bbce-194d-434d-a605-350254b6c298" width="100%" controls autoplay loop></video>
267
+ </td>
268
+ </tr>
269
+ <tr>
270
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
271
+ <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>
272
+ </td>
273
+ <td style="width: 25%; vertical-align: top;">
274
+ <video src="https://github.com/user-attachments/assets/62b01046-8cab-44cc-bd45-4d965bb615ec" width="100%" controls autoplay loop></video>
275
+ </td>
276
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
277
+ <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>
278
+ </td>
279
+ <td style="width: 25%; vertical-align: top;">
280
+ <video src="https://github.com/user-attachments/assets/d78e552a-4b3f-4b81-ac3f-3898079554f6" width="100%" controls autoplay loop></video>
281
+ </td>
282
+ </tr>
283
+ <tr>
284
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
285
+ <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>
286
+ </td>
287
+ <td style="width: 25%; vertical-align: top;">
288
+ <video src="https://github.com/user-attachments/assets/30894f12-c741-44a2-9e6e-ddcacc231e5b" width="100%" controls autoplay loop></video>
289
+ </td>
290
+ <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
291
+ <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>
292
+ </td>
293
+ <td style="width: 25%; vertical-align: top;">
294
+ <video src="https://github.com/user-attachments/assets/926575ca-7150-435b-a0ff-4900a963297b" width="100%" controls autoplay loop></video>
295
+ </td>
296
+ </tr>
297
+ </table>
298
+ """)
299
+
300
+ def generate(
301
+ prompt,
302
+ video_input,
303
+ video_strength,
304
+ seed_value,
305
+ scale_status,
306
+ rife_status,
307
+ progress=gr.Progress(track_tqdm=True)
308
+ ):
309
+ latents, seed = infer(
310
+ prompt,
311
+ video_input,
312
+ video_strength,
313
+ seed=seed_value,
314
+ progress=progress,
315
+ )
316
+ if scale_status:
317
+ latents = utils.upscale_batch_and_concatenate(upscale_model, latents, device)
318
+ if rife_status:
319
+ latents = rife_inference_with_latents(frame_interpolation_model, latents)
320
+
321
+ batch_size = latents.shape[0]
322
+ batch_video_frames = []
323
+ for batch_idx in range(batch_size):
324
+ pt_image = latents[batch_idx]
325
+ pt_image = torch.stack([pt_image[i] for i in range(pt_image.shape[0])])
326
+
327
+ image_np = VaeImageProcessor.pt_to_numpy(pt_image)
328
+ image_pil = VaeImageProcessor.numpy_to_pil(image_np)
329
+ batch_video_frames.append(image_pil)
330
+
331
+ video_path = utils.save_video(batch_video_frames[0], fps=math.ceil((len(batch_video_frames[0]) - 1) / 6))
332
+ video_update = gr.update(visible=True, value=video_path)
333
+ gif_path = convert_to_gif(video_path)
334
+ gif_update = gr.update(visible=True, value=gif_path)
335
+ seed_update = gr.update(visible=True, value=seed)
336
+
337
+ return video_path, video_update, gif_update, seed_update
338
+
339
+ def enhance_prompt_func(prompt):
340
+ return convert_prompt(prompt, retry_times=1)
341
+
342
+ generate_button.click(
343
+ generate,
344
+ inputs=[prompt, video_input, strength, seed_param, enable_scale, enable_rife],
345
+ outputs=[video_output, download_video_button, download_gif_button, seed_text],
346
+ )
347
+
348
+ enhance_button.click(enhance_prompt_func, inputs=[prompt], outputs=[prompt])
349
+
350
+ if __name__ == "__main__":
351
+ demo.queue(max_size=15)
352
+ demo.launch(share = True)