zRzRzRzRzRzRzR commited on
Commit
1aceaa0
1 Parent(s): 8f538ef
Files changed (7) hide show
  1. .gitattributes +2 -0
  2. .gitignore +2 -0
  3. README.md +39 -6
  4. app.py +285 -0
  5. requirements.txt +21 -0
  6. rife_model.py +141 -0
  7. utils.py +221 -0
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ models/RealESRGAN_x4.pth filter=lfs diff=lfs merge=lfs -text
37
+ models/flownet.pkl filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ .venv
2
+ .idea
README.md CHANGED
@@ -1,12 +1,45 @@
1
  ---
2
- title: CogVideoX 5B
3
- emoji: 👀
4
- colorFrom: green
5
- colorTo: yellow
6
  sdk: gradio
7
  sdk_version: 4.42.0
 
 
 
8
  app_file: app.py
9
- pinned: false
 
 
 
 
 
 
 
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: CogVideoX-5B
3
+ emoji: 🎥
4
+ colorFrom: yellow
5
+ colorTo: blue
6
  sdk: gradio
7
  sdk_version: 4.42.0
8
+ suggested_hardware: a10g-large
9
+ suggested_storage: large
10
+ app_port: 7860
11
  app_file: app.py
12
+ models:
13
+ - THUDM/CogVideoX-5b
14
+ tags:
15
+ - cogvideox
16
+ - video-generation
17
+ - thudm
18
+ short_description: Text-to-Video
19
+ disable_embedding: false
20
  ---
21
 
22
+ # Gradio Composite Demo
23
+
24
+ This Gradio demo integrates the CogVideoX-5B model, allowing you to perform video inference directly in your browser. It
25
+ supports features like UpScale, RIFE, and other functionalities.
26
+
27
+ ## Environment Setup
28
+
29
+ Set the following environment variables in your system:
30
+
31
+ + OPENAI_API_KEY = your_api_key
32
+ + OPENAI_BASE_URL= your_base_url
33
+ + GRADIO_TEMP_DIR= gradio_tmp
34
+
35
+ ## Installation
36
+
37
+ ```bash
38
+ pip install -r requirements.txt
39
+ ```
40
+
41
+ ## Running the code
42
+
43
+ ```bash
44
+ python gradio_web_demo.py
45
+ ```
app.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ import random
4
+ import threading
5
+ import time
6
+
7
+ import gradio as gr
8
+ import torch
9
+ from diffusers import CogVideoXPipeline, CogVideoXDDIMScheduler
10
+ from datetime import datetime, timedelta
11
+
12
+ from diffusers.image_processor import VaeImageProcessor
13
+ from openai import OpenAI
14
+ import moviepy.editor as mp
15
+ import utils
16
+ from rife_model import load_rife_model, rife_inference_with_latents
17
+ from huggingface_hub import hf_hub_download, snapshot_download
18
+
19
+ device = "cuda" if torch.cuda.is_available() else "cpu"
20
+
21
+ hf_hub_download(repo_id="ai-forever/Real-ESRGAN", filename="RealESRGAN_x4.pth", local_dir="model_real_esran")
22
+ snapshot_download(repo_id="AlexWortega/RIFE", local_dir="model_rife")
23
+
24
+ pipe = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-5b", torch_dtype=torch.bfloat16).to(device)
25
+ pipe.scheduler = CogVideoXDDIMScheduler.from_config(pipe.scheduler.config, timestep_spacing="trailing")
26
+
27
+ os.makedirs("./output", exist_ok=True)
28
+ os.makedirs("./gradio_tmp", exist_ok=True)
29
+
30
+ upscale_model = utils.load_sd_upscale("model_real_esran/RealESRGAN_x4.pth", device)
31
+ frame_interpolation_model = load_rife_model("model_rife")
32
+
33
+ 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.
34
+
35
+ 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.
36
+ There are a few rules to follow:
37
+
38
+ You will only ever output a single video description per user request.
39
+
40
+ When modifications are requested , you should not simply make the description longer . You should refactor the entire description to integrate the suggestions.
41
+ 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.
42
+
43
+ Video descriptions must have the same num of words as examples below. Extra words will be ignored.
44
+ """
45
+
46
+
47
+ def convert_prompt(prompt: str, retry_times: int = 3) -> str:
48
+ if not os.environ.get("OPENAI_API_KEY"):
49
+ return prompt
50
+ client = OpenAI()
51
+ text = prompt.strip()
52
+
53
+ for i in range(retry_times):
54
+ response = client.chat.completions.create(
55
+ messages=[
56
+ {"role": "system", "content": sys_prompt},
57
+ {
58
+ "role": "user",
59
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "a girl is on the beach"',
60
+ },
61
+ {
62
+ "role": "assistant",
63
+ "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.",
64
+ },
65
+ {
66
+ "role": "user",
67
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "A man jogging on a football field"',
68
+ },
69
+ {
70
+ "role": "assistant",
71
+ "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.",
72
+ },
73
+ {
74
+ "role": "user",
75
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : " A woman is dancing, HD footage, close-up"',
76
+ },
77
+ {
78
+ "role": "assistant",
79
+ "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.",
80
+ },
81
+ {
82
+ "role": "user",
83
+ "content": f'Create an imaginative video descriptive caption or modify an earlier caption in ENGLISH for the user input: "{text}"',
84
+ },
85
+ ],
86
+ model="glm-4-0520",
87
+ temperature=0.01,
88
+ top_p=0.7,
89
+ stream=False,
90
+ max_tokens=200,
91
+ )
92
+ if response.choices:
93
+ return response.choices[0].message.content
94
+ return prompt
95
+
96
+
97
+ def infer(
98
+ prompt: str,
99
+ num_inference_steps: int,
100
+ guidance_scale: float,
101
+ seed: int = -1,
102
+ progress=gr.Progress(track_tqdm=True),
103
+ ):
104
+ if seed == -1:
105
+ seed = random.randint(0, 2 ** 8 - 1)
106
+ video_pt = pipe(
107
+ prompt=prompt,
108
+ num_videos_per_prompt=1,
109
+ num_inference_steps=num_inference_steps,
110
+ num_frames=49,
111
+ output_type="pt",
112
+ guidance_scale=guidance_scale,
113
+ generator=torch.Generator(device=device).manual_seed(seed),
114
+ ).frames
115
+
116
+ return (video_pt, seed)
117
+
118
+
119
+ def convert_to_gif(video_path):
120
+ clip = mp.VideoFileClip(video_path)
121
+ clip = clip.set_fps(8)
122
+ clip = clip.resize(height=240)
123
+ gif_path = video_path.replace(".mp4", ".gif")
124
+ clip.write_gif(gif_path, fps=8)
125
+ return gif_path
126
+
127
+
128
+ def delete_old_files():
129
+ while True:
130
+ now = datetime.now()
131
+ cutoff = now - timedelta(minutes=10)
132
+ directories = ["./output", "./gradio_tmp"]
133
+
134
+ for directory in directories:
135
+ for filename in os.listdir(directory):
136
+ file_path = os.path.join(directory, filename)
137
+ if os.path.isfile(file_path):
138
+ file_mtime = datetime.fromtimestamp(os.path.getmtime(file_path))
139
+ if file_mtime < cutoff:
140
+ os.remove(file_path)
141
+ time.sleep(600)
142
+
143
+
144
+ threading.Thread(target=delete_old_files, daemon=True).start()
145
+
146
+ with gr.Blocks() as demo:
147
+ gr.Markdown("""
148
+ <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
149
+ CogVideoX-5B Huggingface Space🤗
150
+ </div>
151
+ <div style="text-align: center;">
152
+ <a href="https://huggingface.co/THUDM/CogVideoX-5B">🤗 5B Model Hub</a> |
153
+ <a href="https://github.com/THUDM/CogVideo">🌐 Github</a> |
154
+ <a href="https://arxiv.org/pdf/2408.06072">📜 arxiv </a>
155
+ </div>
156
+
157
+ <div style="text-align: center; font-size: 15px; font-weight: bold; color: red; margin-bottom: 20px;">
158
+ ⚠️ This demo is for academic research and experiential use only.
159
+ </div>
160
+ """)
161
+ with gr.Row():
162
+ with gr.Column():
163
+ prompt = gr.Textbox(label="Prompt (Less than 200 Words)", placeholder="Enter your prompt here", lines=5)
164
+
165
+ with gr.Row():
166
+ gr.Markdown(
167
+ "✨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."
168
+ )
169
+ enhance_button = gr.Button("✨ Enhance Prompt(Optional)")
170
+
171
+ gr.Markdown(
172
+ "<span style='color:red; font-weight:bold;'>For the CogVideoX-5B model, 50 steps will take approximately 300 seconds.</span>"
173
+ )
174
+
175
+ with gr.Group():
176
+ with gr.Column():
177
+ with gr.Row():
178
+ seed_param = gr.Number(
179
+ label="Inference Seed (Enter a positive number, -1 for random)", value=-1
180
+ )
181
+ with gr.Row():
182
+ enable_scale = gr.Checkbox(label="Super-Resolution (720 × 480 -> 1440 × 960)", value=False)
183
+ enable_rife = gr.Checkbox(label="Frame Interpolation (8fps -> 16fps)", value=False)
184
+ gr.Markdown(
185
+ "✨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."
186
+ )
187
+
188
+ generate_button = gr.Button("🎬 Generate Video")
189
+
190
+ with gr.Column():
191
+ video_output = gr.Video(label="CogVideoX Generate Video", width=720, height=480)
192
+ with gr.Row():
193
+ download_video_button = gr.File(label="📥 Download Video", visible=False)
194
+ download_gif_button = gr.File(label="📥 Download GIF", visible=False)
195
+ seed_text = gr.Number(label="Seed Used for Video Generation", visible=False)
196
+
197
+ gr.Markdown("""
198
+ <table border="0" style="width: 100%; text-align: left; margin-top: 20px;">
199
+ <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
200
+ 🎥 Video Gallery
201
+ </div>
202
+ <div style="text-align: center; font-size: 18px; font-weight: bold; margin-bottom: 20px;">
203
+ The following videos were generated purely by CogVideoX-5B without using super-resolution or frame interpolation techniques. 🌟
204
+ <br>
205
+ <span style="color: pink;">seed=42, num_inference_steps=50 and guidance_scale=6.0.</span>
206
+ </div>
207
+ <tr>
208
+ <td style="width: 25%; vertical-align: top; font-size: 0.8em;">
209
+ <p>A detailed wooden toy ship with intricately carved masts and sails is seen gliding smoothly over a plush, blue carpet that mimics the waves of the sea. The ship's hull is painted a rich brown, with tiny windows. The carpet, soft and textured, provides a perfect backdrop, resembling an oceanic expanse. Surrounding the ship are various other toys and children's items, hinting at a playful environment. The scene captures the innocence and imagination of childhood, with the toy ship's journey symbolizing endless adventures in a whimsical, indoor setting.</p>
210
+ </td>
211
+ <td style="width: 25%; vertical-align: top;">
212
+ <video src="https://github.com/user-attachments/assets/ea3af39a-3160-4999-90ec-2f7863c5b0e9" width="100%" controls autoplay loop></video>
213
+ </td>
214
+ <td style="width: 25%; vertical-align: top; font-size: 0.8em;">
215
+ <p>The camera follows behind a white vintage SUV with a black roof rack as it speeds up a steep dirt road surrounded by pine trees on a steep mountain slope, dust kicks up from its tires, the sunlight shines on the SUV as it speeds along the dirt road, casting a warm glow over the scene. The dirt road curves gently into the distance, with no other cars or vehicles in sight. The trees on either side of the road are redwoods, with patches of greenery scattered throughout. The car is seen from the rear following the curve with ease, making it seem as if it is on a rugged drive through the rugged terrain. The dirt road itself is surrounded by steep hills and mountains, with a clear blue sky above with wispy clouds.</p>
216
+ </td>
217
+ <td style="width: 25%; vertical-align: top;">
218
+ <video src="https://github.com/user-attachments/assets/9de41efd-d4d1-4095-aeda-246dd834e91d" width="100%" controls autoplay loop></video>
219
+ </td>
220
+ </tr>
221
+ <tr>
222
+ <td style="width: 25%; vertical-align: top; font-size: 0.8em;">
223
+ <p>A street artist, clad in a worn-out denim jacket and a colorful bandana, stands before a vast concrete wall in the heart, holding a can of spray paint, spray-painting a colorful bird on a mottled wall.</p>
224
+ </td>
225
+ <td style="width: 25%; vertical-align: top;">
226
+ <video src="https://github.com/user-attachments/assets/941d6661-6a8d-4a1b-b912-59606f0b2841" width="100%" controls autoplay loop></video>
227
+ </td>
228
+ <td style="width: 25%; vertical-align: top; font-size: 0.8em;">
229
+ <p>In the haunting backdrop of a war-torn city, where ruins and crumbled walls tell a story of devastation, a poignant close-up frames a young girl. Her face is smudged with ash, a silent testament to the chaos around her. Her eyes glistening with a mix of sorrow and resilience, capturing the raw emotion of a world that has lost its innocence to the ravages of conflict.</p>
230
+ </td>
231
+ <td style="width: 25%; vertical-align: top;">
232
+ <video src="https://github.com/user-attachments/assets/938529c4-91ae-4f60-b96b-3c3947fa63cb" width="100%" controls autoplay loop></video>
233
+ </td>
234
+ </tr>
235
+ </table>
236
+ """)
237
+
238
+
239
+ def generate(prompt, seed_value, scale_status, rife_status, progress=gr.Progress(track_tqdm=True)):
240
+
241
+ latents, seed = infer(
242
+ prompt,
243
+ num_inference_steps=50, # NOT Changed
244
+ guidance_scale=6, # NOT Changed
245
+ seed=seed_value,
246
+ progress=progress,
247
+ )
248
+ if scale_status:
249
+ latents = utils.upscale_batch_and_concatenate(upscale_model, latents, device)
250
+ if rife_status:
251
+ latents = rife_inference_with_latents(frame_interpolation_model, latents)
252
+
253
+ batch_size = latents.shape[0]
254
+ batch_video_frames = []
255
+ for batch_idx in range(batch_size):
256
+ pt_image = latents[batch_idx]
257
+ pt_image = torch.stack([pt_image[i] for i in range(pt_image.shape[0])])
258
+
259
+ image_np = VaeImageProcessor.pt_to_numpy(pt_image)
260
+ image_pil = VaeImageProcessor.numpy_to_pil(image_np)
261
+ batch_video_frames.append(image_pil)
262
+
263
+ video_path = utils.save_video(batch_video_frames[0], fps=math.ceil((len(batch_video_frames[0]) - 1) / 6))
264
+ video_update = gr.update(visible=True, value=video_path)
265
+ gif_path = convert_to_gif(video_path)
266
+ gif_update = gr.update(visible=True, value=gif_path)
267
+ seed_update = gr.update(visible=True, value=seed)
268
+
269
+ return video_path, video_update, gif_update, seed_update
270
+
271
+
272
+ def enhance_prompt_func(prompt):
273
+ return convert_prompt(prompt, retry_times=1)
274
+
275
+
276
+ generate_button.click(
277
+ generate,
278
+ inputs=[prompt, seed_param, enable_scale, enable_rife],
279
+ outputs=[video_output, download_video_button, download_gif_button, seed_text],
280
+ )
281
+
282
+ enhance_button.click(enhance_prompt_func, inputs=[prompt], outputs=[prompt])
283
+
284
+ if __name__ == "__main__":
285
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ spaces==0.29.3
2
+ safetensors>=0.4.4
3
+ spandrel>=0.3.4
4
+ tqdm>=4.66.5
5
+ opencv-python>=4.10.0.84
6
+ scikit-video>=1.1.11
7
+ diffusers>=0.30.1
8
+ transformers>=4.44.0
9
+ accelerate>=0.33.0
10
+ sentencepiece>=0.2.0
11
+ SwissArmyTransformer>=0.4.12
12
+ numpy==1.26.0
13
+ torch>=2.4.0
14
+ torchvision>=0.19.0
15
+ gradio>=4.42.0
16
+ streamlit>=1.37.1
17
+ imageio==2.34.2
18
+ imageio-ffmpeg==0.5.1
19
+ openai>=1.42.0
20
+ moviepy==1.0.3
21
+ pillow==9.5.0
rife_model.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffusers.image_processor import VaeImageProcessor
3
+ from torch.nn import functional as F
4
+ import cv2
5
+ import utils
6
+ from rife.pytorch_msssim import ssim_matlab
7
+ import numpy as np
8
+ import logging
9
+ import skvideo.io
10
+ from rife.RIFE_HDv3 import Model
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+ device = "cuda" if torch.cuda.is_available() else "cpu"
15
+
16
+
17
+ def pad_image(img, scale):
18
+ _, _, h, w = img.shape
19
+ tmp = max(32, int(32 / scale))
20
+ ph = ((h - 1) // tmp + 1) * tmp
21
+ pw = ((w - 1) // tmp + 1) * tmp
22
+ padding = (0, 0, pw - w, ph - h)
23
+ return F.pad(img, padding)
24
+
25
+
26
+ def make_inference(model, I0, I1, upscale_amount, n):
27
+ middle = model.inference(I0, I1, upscale_amount)
28
+ if n == 1:
29
+ return [middle]
30
+ first_half = make_inference(model, I0, middle, upscale_amount, n=n // 2)
31
+ second_half = make_inference(model, middle, I1, upscale_amount, n=n // 2)
32
+ if n % 2:
33
+ return [*first_half, middle, *second_half]
34
+ else:
35
+ return [*first_half, *second_half]
36
+
37
+
38
+ @torch.inference_mode()
39
+ def ssim_interpolation_rife(model, samples, exp=1, upscale_amount=1, output_device="cpu"):
40
+ print(f"samples dtype:{samples.dtype}")
41
+ print(f"samples shape:{samples.shape}")
42
+ output = []
43
+ # [f, c, h, w]
44
+ for b in range(samples.shape[0]):
45
+ frame = samples[b : b + 1]
46
+ _, _, h, w = frame.shape
47
+ I0 = samples[b : b + 1]
48
+ I1 = samples[b + 1 : b + 2] if b + 2 < samples.shape[0] else samples[-1:]
49
+ I1 = pad_image(I1, upscale_amount)
50
+ # [c, h, w]
51
+ I0_small = F.interpolate(I0, (32, 32), mode="bilinear", align_corners=False)
52
+ I1_small = F.interpolate(I1, (32, 32), mode="bilinear", align_corners=False)
53
+
54
+ ssim = ssim_matlab(I0_small[:, :3], I1_small[:, :3])
55
+
56
+ if ssim > 0.996:
57
+ I1 = I0
58
+ I1 = pad_image(I1, upscale_amount)
59
+ I1 = make_inference(model, I0, I1, upscale_amount, 1)
60
+
61
+ I1_small = F.interpolate(I1[0], (32, 32), mode="bilinear", align_corners=False)
62
+ ssim = ssim_matlab(I0_small[:, :3], I1_small[:, :3])
63
+ frame = I1[0]
64
+ I1 = I1[0]
65
+
66
+ tmp_output = []
67
+ if ssim < 0.2:
68
+ for i in range((2**exp) - 1):
69
+ tmp_output.append(I0)
70
+
71
+ else:
72
+ tmp_output = make_inference(model, I0, I1, upscale_amount, 2**exp - 1) if exp else []
73
+
74
+ frame = pad_image(frame, upscale_amount)
75
+ tmp_output = [frame] + tmp_output
76
+ for i, frame in enumerate(tmp_output):
77
+ output.append(frame.to(output_device))
78
+ return output
79
+
80
+
81
+ def load_rife_model(model_path):
82
+ torch.set_grad_enabled(False)
83
+ if torch.cuda.is_available():
84
+ torch.backends.cudnn.enabled = True
85
+ torch.backends.cudnn.benchmark = True
86
+ torch.set_default_tensor_type(torch.cuda.FloatTensor)
87
+
88
+ model = Model()
89
+ model.load_model(model_path, -1)
90
+ model.eval()
91
+ print("Loaded v3.x HD model.")
92
+
93
+ return model
94
+
95
+
96
+ # Create a generator that yields each frame, similar to cv2.VideoCapture
97
+ def frame_generator(video_capture):
98
+ while True:
99
+ ret, frame = video_capture.read()
100
+ if not ret:
101
+ break
102
+ yield frame
103
+ video_capture.release()
104
+
105
+
106
+ def rife_inference_with_path(model, video_path):
107
+ video_capture = cv2.VideoCapture(video_path)
108
+ tot_frame = video_capture.get(cv2.CAP_PROP_FRAME_COUNT)
109
+ pt_frame_data = []
110
+ pt_frame = skvideo.io.vreader(video_path)
111
+ for frame in pt_frame:
112
+ pt_frame_data.append(
113
+ torch.from_numpy(np.transpose(frame, (2, 0, 1))).to("cpu", non_blocking=True).float() / 255.0
114
+ )
115
+
116
+ pt_frame = torch.from_numpy(np.stack(pt_frame_data))
117
+ pt_frame = pt_frame.to(device)
118
+ pbar = utils.ProgressBar(tot_frame, desc="RIFE inference")
119
+ frames = ssim_interpolation_rife(model, pt_frame)
120
+ pt_image = torch.stack([frames[i].squeeze(0) for i in range(len(frames))])
121
+ image_np = VaeImageProcessor.pt_to_numpy(pt_image) # (to [49, 512, 480, 3])
122
+ image_pil = VaeImageProcessor.numpy_to_pil(image_np)
123
+ video_path = utils.save_video(image_pil, fps=16)
124
+ if pbar:
125
+ pbar.update(1)
126
+ return video_path
127
+
128
+
129
+ def rife_inference_with_latents(model, latents):
130
+ pbar = utils.ProgressBar(latents.shape[1], desc="RIFE inference")
131
+ rife_results = []
132
+ latents = latents.to(device)
133
+ for i in range(latents.size(0)):
134
+ # [f, c, w, h]
135
+ latent = latents[i]
136
+
137
+ frames = ssim_interpolation_rife(model, latent)
138
+ pt_image = torch.stack([frames[i].squeeze(0) for i in range(len(frames))]) # (to [f, c, w, h])
139
+ rife_results.append(pt_image)
140
+
141
+ return torch.stack(rife_results)
utils.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import Union, List
3
+
4
+ import torch
5
+ import os
6
+ from datetime import datetime
7
+ import numpy as np
8
+ import itertools
9
+ import PIL.Image
10
+ import safetensors.torch
11
+ import tqdm
12
+ import logging
13
+ from diffusers.utils import export_to_video
14
+ from spandrel import ModelLoader
15
+
16
+ logger = logging.getLogger(__file__)
17
+
18
+
19
+ def load_torch_file(ckpt, device=None, dtype=torch.float16):
20
+ if device is None:
21
+ device = torch.device("cpu")
22
+ if ckpt.lower().endswith(".safetensors") or ckpt.lower().endswith(".sft"):
23
+ sd = safetensors.torch.load_file(ckpt, device=device.type)
24
+ else:
25
+ if not "weights_only" in torch.load.__code__.co_varnames:
26
+ logger.warning(
27
+ "Warning torch.load doesn't support weights_only on this pytorch version, loading unsafely."
28
+ )
29
+
30
+ pl_sd = torch.load(ckpt, map_location=device, weights_only=True)
31
+ if "global_step" in pl_sd:
32
+ logger.debug(f"Global Step: {pl_sd['global_step']}")
33
+ if "state_dict" in pl_sd:
34
+ sd = pl_sd["state_dict"]
35
+ elif "params_ema" in pl_sd:
36
+ sd = pl_sd["params_ema"]
37
+ else:
38
+ sd = pl_sd
39
+
40
+ sd = {k: v.to(dtype) for k, v in sd.items()}
41
+ return sd
42
+
43
+
44
+ def state_dict_prefix_replace(state_dict, replace_prefix, filter_keys=False):
45
+ if filter_keys:
46
+ out = {}
47
+ else:
48
+ out = state_dict
49
+ for rp in replace_prefix:
50
+ replace = list(
51
+ map(
52
+ lambda a: (a, "{}{}".format(replace_prefix[rp], a[len(rp) :])),
53
+ filter(lambda a: a.startswith(rp), state_dict.keys()),
54
+ )
55
+ )
56
+ for x in replace:
57
+ w = state_dict.pop(x[0])
58
+ out[x[1]] = w
59
+ return out
60
+
61
+
62
+ def module_size(module):
63
+ module_mem = 0
64
+ sd = module.state_dict()
65
+ for k in sd:
66
+ t = sd[k]
67
+ module_mem += t.nelement() * t.element_size()
68
+ return module_mem
69
+
70
+
71
+ def get_tiled_scale_steps(width, height, tile_x, tile_y, overlap):
72
+ return math.ceil((height / (tile_y - overlap))) * math.ceil((width / (tile_x - overlap)))
73
+
74
+
75
+ @torch.inference_mode()
76
+ def tiled_scale_multidim(
77
+ samples, function, tile=(64, 64), overlap=8, upscale_amount=4, out_channels=3, output_device="cpu", pbar=None
78
+ ):
79
+ dims = len(tile)
80
+ print(f"samples dtype:{samples.dtype}")
81
+ output = torch.empty(
82
+ [samples.shape[0], out_channels] + list(map(lambda a: round(a * upscale_amount), samples.shape[2:])),
83
+ device=output_device,
84
+ )
85
+
86
+ for b in range(samples.shape[0]):
87
+ s = samples[b : b + 1]
88
+ out = torch.zeros(
89
+ [s.shape[0], out_channels] + list(map(lambda a: round(a * upscale_amount), s.shape[2:])),
90
+ device=output_device,
91
+ )
92
+ out_div = torch.zeros(
93
+ [s.shape[0], out_channels] + list(map(lambda a: round(a * upscale_amount), s.shape[2:])),
94
+ device=output_device,
95
+ )
96
+
97
+ for it in itertools.product(*map(lambda a: range(0, a[0], a[1] - overlap), zip(s.shape[2:], tile))):
98
+ s_in = s
99
+ upscaled = []
100
+
101
+ for d in range(dims):
102
+ pos = max(0, min(s.shape[d + 2] - overlap, it[d]))
103
+ l = min(tile[d], s.shape[d + 2] - pos)
104
+ s_in = s_in.narrow(d + 2, pos, l)
105
+ upscaled.append(round(pos * upscale_amount))
106
+
107
+ ps = function(s_in).to(output_device)
108
+ mask = torch.ones_like(ps)
109
+ feather = round(overlap * upscale_amount)
110
+ for t in range(feather):
111
+ for d in range(2, dims + 2):
112
+ m = mask.narrow(d, t, 1)
113
+ m *= (1.0 / feather) * (t + 1)
114
+ m = mask.narrow(d, mask.shape[d] - 1 - t, 1)
115
+ m *= (1.0 / feather) * (t + 1)
116
+
117
+ o = out
118
+ o_d = out_div
119
+ for d in range(dims):
120
+ o = o.narrow(d + 2, upscaled[d], mask.shape[d + 2])
121
+ o_d = o_d.narrow(d + 2, upscaled[d], mask.shape[d + 2])
122
+
123
+ o += ps * mask
124
+ o_d += mask
125
+
126
+ if pbar is not None:
127
+ pbar.update(1)
128
+
129
+ output[b : b + 1] = out / out_div
130
+ return output
131
+
132
+
133
+ def tiled_scale(
134
+ samples,
135
+ function,
136
+ tile_x=64,
137
+ tile_y=64,
138
+ overlap=8,
139
+ upscale_amount=4,
140
+ out_channels=3,
141
+ output_device="cpu",
142
+ pbar=None,
143
+ ):
144
+ return tiled_scale_multidim(
145
+ samples, function, (tile_y, tile_x), overlap, upscale_amount, out_channels, output_device, pbar
146
+ )
147
+
148
+
149
+ def load_sd_upscale(ckpt, inf_device):
150
+ sd = load_torch_file(ckpt, device=inf_device)
151
+ if "module.layers.0.residual_group.blocks.0.norm1.weight" in sd:
152
+ sd = state_dict_prefix_replace(sd, {"module.": ""})
153
+ out = ModelLoader().load_from_state_dict(sd).half()
154
+ return out
155
+
156
+
157
+ def upscale(upscale_model, tensor: torch.Tensor, inf_device, output_device="cpu") -> torch.Tensor:
158
+ memory_required = module_size(upscale_model.model)
159
+ memory_required += (
160
+ (512 * 512 * 3) * tensor.element_size() * max(upscale_model.scale, 1.0) * 384.0
161
+ ) # The 384.0 is an estimate of how much some of these models take, TODO: make it more accurate
162
+ memory_required += tensor.nelement() * tensor.element_size()
163
+ print(f"UPScaleMemory required: {memory_required / 1024 / 1024 / 1024} GB")
164
+
165
+ upscale_model.to(inf_device)
166
+ tile = 512
167
+ overlap = 32
168
+
169
+ steps = tensor.shape[0] * get_tiled_scale_steps(
170
+ tensor.shape[3], tensor.shape[2], tile_x=tile, tile_y=tile, overlap=overlap
171
+ )
172
+
173
+ pbar = ProgressBar(steps, desc="Tiling and Upscaling")
174
+
175
+ s = tiled_scale(
176
+ samples=tensor.to(torch.float16),
177
+ function=lambda a: upscale_model(a),
178
+ tile_x=tile,
179
+ tile_y=tile,
180
+ overlap=overlap,
181
+ upscale_amount=upscale_model.scale,
182
+ pbar=pbar,
183
+ )
184
+
185
+ upscale_model.to(output_device)
186
+ return s
187
+
188
+
189
+ def upscale_batch_and_concatenate(upscale_model, latents, inf_device, output_device="cpu") -> torch.Tensor:
190
+ upscaled_latents = []
191
+ for i in range(latents.size(0)):
192
+ latent = latents[i]
193
+ upscaled_latent = upscale(upscale_model, latent, inf_device, output_device)
194
+ upscaled_latents.append(upscaled_latent)
195
+ return torch.stack(upscaled_latents)
196
+
197
+
198
+ def save_video(tensor: Union[List[np.ndarray], List[PIL.Image.Image]], fps: int = 8):
199
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
200
+ video_path = f"./output/{timestamp}.mp4"
201
+ os.makedirs(os.path.dirname(video_path), exist_ok=True)
202
+ export_to_video(tensor, video_path, fps=fps)
203
+ return video_path
204
+
205
+
206
+ class ProgressBar:
207
+ def __init__(self, total, desc=None):
208
+ self.total = total
209
+ self.current = 0
210
+ self.b_unit = tqdm.tqdm(total=total, desc="ProgressBar context index: 0" if desc is None else desc)
211
+
212
+ def update(self, value):
213
+ if value > self.total:
214
+ value = self.total
215
+ self.current = value
216
+ if self.b_unit is not None:
217
+ self.b_unit.set_description("ProgressBar context index: {}".format(self.current))
218
+ self.b_unit.refresh()
219
+
220
+ # 更新进度
221
+ self.b_unit.update(self.current)