tsqn commited on
Commit
b023352
·
verified ·
1 Parent(s): 83f66db

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +12 -258
app.py CHANGED
@@ -32,25 +32,15 @@ from diffusers import (
32
  from diffusers.utils import load_video, load_image
33
  from datetime import datetime, timedelta
34
  from diffusers.image_processor import VaeImageProcessor
35
- #from openai import OpenAI
36
  import moviepy.editor as mp
37
  import utils
38
- #from rife_model import load_rife_model, rife_inference_with_latents
39
- #from huggingface_hub import hf_hub_download, snapshot_download
40
- import gc
41
 
42
- #device = "cuda" if torch.cuda.is_available() else "cpu"
43
-
44
- #hf_hub_download(repo_id="ai-forever/Real-ESRGAN", filename="RealESRGAN_x4.pth", local_dir="model_real_esran")
45
- #snapshot_download(repo_id="AlexWortega/RIFE", local_dir="model_rife")
46
- quantization = int8_weight_only
47
 
48
  transformer = CogVideoXTransformer3DModel.from_pretrained("THUDM/CogVideoX-5B", subfolder="transformer", torch_dtype=torch.bfloat16)
49
  text_encoder = T5EncoderModel.from_pretrained("THUDM/CogVideoX-5B", subfolder="text_encoder", torch_dtype=torch.bfloat16)
50
  vae = AutoencoderKLCogVideoX.from_pretrained("THUDM/CogVideoX-5B", subfolder="vae", torch_dtype=torch.bfloat16)
51
- quantize_(transformer, quantization())
52
- quantize_(text_encoder, quantization())
53
- # quantize_(vae, quantization())
54
 
55
  pipe = CogVideoXPipeline.from_pretrained(
56
  "THUDM/CogVideoX-5B",
@@ -58,34 +48,14 @@ pipe = CogVideoXPipeline.from_pretrained(
58
  transformer=transformer,
59
  vae=vae,
60
  torch_dtype=torch.bfloat16
61
- ).to("cpu")
62
  pipe.scheduler = CogVideoXDPMScheduler.from_config(pipe.scheduler.config, timestep_spacing="trailing")
63
 
64
- pipe.enable_model_cpu_offload()
65
  pipe.vae.enable_tiling()
66
- pipe.vae.enable_slicing()
67
-
68
- # i2v_transformer = CogVideoXTransformer3DModel.from_pretrained(
69
- # "THUDM/CogVideoX-5B-I2V", subfolder="transformer", torch_dtype=torch.bfloat16
70
- # )
71
- # i2v_text_encoder = T5EncoderModel.from_pretrained("THUDM/CogVideoX-5B-I2V", subfolder="text_encoder", torch_dtype=torch.bfloat16)
72
- # i2v_vae = AutoencoderKLCogVideoX.from_pretrained("THUDM/CogVideoX-5B-I2V", subfolder="vae", torch_dtype=torch.bfloat16)
73
-
74
- # quantize_(i2v_transformer, quantization())
75
- # quantize_(i2v_text_encoder, quantization())
76
- # quantize_(i2v_vae, quantization())
77
-
78
- # pipe.transformer.to(memory_format=torch.channels_last)
79
- # pipe.transformer = torch.compile(pipe.transformer, mode="max-autotune", fullgraph=True)
80
- # pipe_image.transformer.to(memory_format=torch.channels_last)
81
- # pipe_image.transformer = torch.compile(pipe_image.transformer, mode="max-autotune", fullgraph=True)
82
 
83
  os.makedirs("./output", exist_ok=True)
84
  os.makedirs("./gradio_tmp", exist_ok=True)
85
 
86
- #upscale_model = utils.load_sd_upscale("model_real_esran/RealESRGAN_x4.pth", device)
87
- #frame_interpolation_model = load_rife_model("model_rife")
88
-
89
  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.
90
 
91
  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.
@@ -100,135 +70,8 @@ Video descriptions must have the same num of words as examples below. Extra word
100
  """
101
 
102
 
103
- # def resize_if_unfit(input_video, progress=gr.Progress(track_tqdm=True)):
104
- # width, height = get_video_dimensions(input_video)
105
-
106
- # if width == 720 and height == 480:
107
- # processed_video = input_video
108
- # else:
109
- # processed_video = center_crop_resize(input_video)
110
- # return processed_video
111
-
112
-
113
- # def get_video_dimensions(input_video_path):
114
- # reader = imageio_ffmpeg.read_frames(input_video_path)
115
- # metadata = next(reader)
116
- # return metadata["size"]
117
-
118
-
119
- # def center_crop_resize(input_video_path, target_width=720, target_height=480):
120
- # cap = cv2.VideoCapture(input_video_path)
121
-
122
- # orig_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
123
- # orig_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
124
- # orig_fps = cap.get(cv2.CAP_PROP_FPS)
125
- # total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
126
-
127
- # width_factor = target_width / orig_width
128
- # height_factor = target_height / orig_height
129
- # resize_factor = max(width_factor, height_factor)
130
-
131
- # inter_width = int(orig_width * resize_factor)
132
- # inter_height = int(orig_height * resize_factor)
133
-
134
- # target_fps = 8
135
- # ideal_skip = max(0, math.ceil(orig_fps / target_fps) - 1)
136
- # skip = min(5, ideal_skip) # Cap at 5
137
-
138
- # while (total_frames / (skip + 1)) < 49 and skip > 0:
139
- # skip -= 1
140
-
141
- # processed_frames = []
142
- # frame_count = 0
143
- # total_read = 0
144
-
145
- # while frame_count < 49 and total_read < total_frames:
146
- # ret, frame = cap.read()
147
- # if not ret:
148
- # break
149
-
150
- # if total_read % (skip + 1) == 0:
151
- # resized = cv2.resize(frame, (inter_width, inter_height), interpolation=cv2.INTER_AREA)
152
-
153
- # start_x = (inter_width - target_width) // 2
154
- # start_y = (inter_height - target_height) // 2
155
- # cropped = resized[start_y : start_y + target_height, start_x : start_x + target_width]
156
-
157
- # processed_frames.append(cropped)
158
- # frame_count += 1
159
-
160
- # total_read += 1
161
-
162
- # cap.release()
163
-
164
- # with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as temp_file:
165
- # temp_video_path = temp_file.name
166
- # fourcc = cv2.VideoWriter_fourcc(*"mp4v")
167
- # out = cv2.VideoWriter(temp_video_path, fourcc, target_fps, (target_width, target_height))
168
-
169
- # for frame in processed_frames:
170
- # out.write(frame)
171
-
172
- # out.release()
173
-
174
- # return temp_video_path
175
-
176
-
177
- # def convert_prompt(prompt: str, retry_times: int = 3) -> str:
178
- # if not os.environ.get("OPENAI_API_KEY"):
179
- # return prompt
180
- # client = OpenAI()
181
- # text = prompt.strip()
182
-
183
- # for i in range(retry_times):
184
- # response = client.chat.completions.create(
185
- # messages=[
186
- # {"role": "system", "content": sys_prompt},
187
- # {
188
- # "role": "user",
189
- # "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "a girl is on the beach"',
190
- # },
191
- # {
192
- # "role": "assistant",
193
- # "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.",
194
- # },
195
- # {
196
- # "role": "user",
197
- # "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "A man jogging on a football field"',
198
- # },
199
- # {
200
- # "role": "assistant",
201
- # "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.",
202
- # },
203
- # {
204
- # "role": "user",
205
- # "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : " A woman is dancing, HD footage, close-up"',
206
- # },
207
- # {
208
- # "role": "assistant",
209
- # "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.",
210
- # },
211
- # {
212
- # "role": "user",
213
- # "content": f'Create an imaginative video descriptive caption or modify an earlier caption in ENGLISH for the user input: "{text}"',
214
- # },
215
- # ],
216
- # model="glm-4-plus",
217
- # temperature=0.01,
218
- # top_p=0.7,
219
- # stream=False,
220
- # max_tokens=200,
221
- # )
222
- # if response.choices:
223
- # return response.choices[0].message.content
224
- # return prompt
225
-
226
-
227
  def infer(
228
  prompt: str,
229
- # image_input: str,
230
- # video_input: str,
231
- # video_strenght: float,
232
  num_inference_steps: int,
233
  guidance_scale: float,
234
  seed: int = -1,
@@ -237,64 +80,7 @@ def infer(
237
  if seed == -1:
238
  seed = random.randint(0, 2**8 - 1)
239
 
240
- # if video_input is not None:
241
- # video = load_video(video_input)[:49] # Limit to 49 frames
242
- # pipe_video = CogVideoXVideoToVideoPipeline.from_pretrained(
243
- # "THUDM/CogVideoX-5B",
244
- # transformer=transformer,
245
- # vae=vae,
246
- # scheduler=pipe.scheduler,
247
- # tokenizer=pipe.tokenizer,
248
- # text_encoder=text_encoder,
249
- # torch_dtype=torch.bfloat16,
250
- # ).to(device)
251
-
252
- # # pipe_video.enable_model_cpu_offload()
253
- # pipe_video.vae.enable_tiling()
254
- # pipe_video.vae.enable_slicing()
255
- # video_pt = pipe_video(
256
- # video=video,
257
- # prompt=prompt,
258
- # num_inference_steps=num_inference_steps,
259
- # num_videos_per_prompt=1,
260
- # strength=video_strenght,
261
- # use_dynamic_cfg=True,
262
- # output_type="pt",
263
- # guidance_scale=guidance_scale,
264
- # generator=torch.Generator(device="cpu").manual_seed(seed),
265
- # ).frames
266
- # pipe_video.to("cpu")
267
- # del pipe_video
268
- # gc.collect()
269
- # torch.cuda.empty_cache()
270
- # elif image_input is not None:
271
- # pipe_image = CogVideoXImageToVideoPipeline.from_pretrained(
272
- # "THUDM/CogVideoX-5B-I2V",
273
- # transformer=i2v_transformer,
274
- # vae=i2v_vae,
275
- # scheduler=pipe.scheduler,
276
- # tokenizer=pipe.tokenizer,
277
- # text_encoder=i2v_text_encoder,
278
- # torch_dtype=torch.bfloat16,
279
- # ).to(device)
280
- # image_input = Image.fromarray(image_input).resize(size=(720, 480)) # Convert to PIL
281
- # image = load_image(image_input)
282
- # video_pt = pipe_image(
283
- # image=image,
284
- # prompt=prompt,
285
- # num_inference_steps=num_inference_steps,
286
- # num_videos_per_prompt=1,
287
- # use_dynamic_cfg=True,
288
- # output_type="pt",
289
- # guidance_scale=guidance_scale,
290
- # generator=torch.Generator(device="cpu").manual_seed(seed),
291
- # ).frames
292
- # pipe_image.to("cpu")
293
- # del pipe_image
294
- # gc.collect()
295
- # torch.cuda.empty_cache()
296
- # else:
297
- pipe.to("cpu")
298
  video_pt = pipe(
299
  prompt=prompt,
300
  num_videos_per_prompt=1,
@@ -303,9 +89,10 @@ def infer(
303
  use_dynamic_cfg=True,
304
  output_type="pt",
305
  guidance_scale=guidance_scale,
306
- generator=torch.Generator(device="cpu").manual_seed(seed),
307
  ).frames
308
- pipe.to("cpu")
 
309
  gc.collect()
310
  return (video_pt, seed)
311
 
@@ -362,32 +149,14 @@ with gr.Blocks() as demo:
362
  """)
363
  with gr.Row():
364
  with gr.Column():
365
- # with gr.Accordion("I2V: Image Input (cannot be used simultaneously with video input)", open=False):
366
- # image_input = gr.Image(label="Input Image (will be cropped to 720 * 480)")
367
- # examples_component_images = gr.Examples(examples_images, inputs=[image_input], cache_examples=False)
368
- # with gr.Accordion("V2V: Video Input (cannot be used simultaneously with image input)", open=False):
369
- # video_input = gr.Video(label="Input Video (will be cropped to 49 frames, 6 seconds at 8fps)")
370
- # strength = gr.Slider(0.1, 1.0, value=0.8, step=0.01, label="Strength")
371
- # examples_component_videos = gr.Examples(examples_videos, inputs=[video_input], cache_examples=False)
372
  prompt = gr.Textbox(label="Prompt (Less than 200 Words)", placeholder="Enter your prompt here", lines=5)
373
 
374
- # with gr.Row():
375
- # gr.Markdown(
376
- # "✨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."
377
- # )
378
- # enhance_button = gr.Button("✨ Enhance Prompt(Optional)")
379
  with gr.Group():
380
  with gr.Column():
381
  with gr.Row():
382
  seed_param = gr.Number(
383
  label="Inference Seed (Enter a positive number, -1 for random)", value=-1
384
  )
385
- # with gr.Row():
386
- # enable_scale = gr.Checkbox(label="Super-Resolution (720 × 480 -> 2880 × 1920)", value=False)
387
- # enable_rife = gr.Checkbox(label="Frame Interpolation (8fps -> 16fps)", value=False)
388
- # gr.Markdown(
389
- # "✨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."
390
- # )
391
 
392
  generate_button = gr.Button("🎬 Generate Video")
393
 
@@ -463,30 +232,22 @@ with gr.Blocks() as demo:
463
  """)
464
 
465
  @spaces.GPU(duration=120)
 
466
  def generate(
467
  prompt,
468
- # image_input,
469
- # video_input,
470
- # video_strength,
471
  seed_value,
472
- # scale_status,
473
- # rife_status,
474
  progress=gr.Progress(track_tqdm=True)
475
  ):
 
 
 
476
  latents, seed = infer(
477
  prompt,
478
- # image_input,
479
- # video_input,
480
- # video_strength,
481
  num_inference_steps=20, # Changed from 50
482
  guidance_scale=7.0, # NOT Changed
483
  seed=seed_value,
484
  progress=progress,
485
  )
486
- # if scale_status:
487
- # latents = utils.upscale_batch_and_concatenate(upscale_model, latents, device)
488
- # if rife_status:
489
- # latents = rife_inference_with_latents(frame_interpolation_model, latents)
490
 
491
  batch_size = latents.shape[0]
492
  batch_video_frames = []
@@ -506,21 +267,14 @@ with gr.Blocks() as demo:
506
 
507
  return video_path, video_update, gif_update, seed_update
508
 
509
- # def enhance_prompt_func(prompt):
510
- # return convert_prompt(prompt, retry_times=1)
511
 
512
  generate_button.click(
513
  generate,
514
  inputs=[prompt, seed_param],
515
- # inputs=[prompt, image_input, video_input, strength, seed_param],
516
- # inputs=[prompt, image_input, video_input, strength, seed_param, enable_scale, enable_rife],
517
  outputs=[video_output, download_video_button, download_gif_button, seed_text],
518
  )
519
 
520
- # enhance_button.click(enhance_prompt_func, inputs=[prompt], outputs=[prompt])
521
- # video_input.upload(resize_if_unfit, inputs=[video_input], outputs=[video_input])
522
-
523
  if __name__ == "__main__":
524
  utils.install_packages()
525
- demo.queue(max_size=15)
526
  demo.launch()
 
32
  from diffusers.utils import load_video, load_image
33
  from datetime import datetime, timedelta
34
  from diffusers.image_processor import VaeImageProcessor
35
+
36
  import moviepy.editor as mp
37
  import utils
 
 
 
38
 
39
+ import gc
 
 
 
 
40
 
41
  transformer = CogVideoXTransformer3DModel.from_pretrained("THUDM/CogVideoX-5B", subfolder="transformer", torch_dtype=torch.bfloat16)
42
  text_encoder = T5EncoderModel.from_pretrained("THUDM/CogVideoX-5B", subfolder="text_encoder", torch_dtype=torch.bfloat16)
43
  vae = AutoencoderKLCogVideoX.from_pretrained("THUDM/CogVideoX-5B", subfolder="vae", torch_dtype=torch.bfloat16)
 
 
 
44
 
45
  pipe = CogVideoXPipeline.from_pretrained(
46
  "THUDM/CogVideoX-5B",
 
48
  transformer=transformer,
49
  vae=vae,
50
  torch_dtype=torch.bfloat16
51
+ ).to("cuda")
52
  pipe.scheduler = CogVideoXDPMScheduler.from_config(pipe.scheduler.config, timestep_spacing="trailing")
53
 
 
54
  pipe.vae.enable_tiling()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
  os.makedirs("./output", exist_ok=True)
57
  os.makedirs("./gradio_tmp", exist_ok=True)
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
 
61
  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.
 
70
  """
71
 
72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  def infer(
74
  prompt: str,
 
 
 
75
  num_inference_steps: int,
76
  guidance_scale: float,
77
  seed: int = -1,
 
80
  if seed == -1:
81
  seed = random.randint(0, 2**8 - 1)
82
 
83
+ pipe.to("cuda")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  video_pt = pipe(
85
  prompt=prompt,
86
  num_videos_per_prompt=1,
 
89
  use_dynamic_cfg=True,
90
  output_type="pt",
91
  guidance_scale=guidance_scale,
92
+ generator=torch.Generator(device="cuda").manual_seed(seed),
93
  ).frames
94
+ pipe.to("cuda")
95
+ torch.cuda.empty_cache()
96
  gc.collect()
97
  return (video_pt, seed)
98
 
 
149
  """)
150
  with gr.Row():
151
  with gr.Column():
 
 
 
 
 
 
 
152
  prompt = gr.Textbox(label="Prompt (Less than 200 Words)", placeholder="Enter your prompt here", lines=5)
153
 
 
 
 
 
 
154
  with gr.Group():
155
  with gr.Column():
156
  with gr.Row():
157
  seed_param = gr.Number(
158
  label="Inference Seed (Enter a positive number, -1 for random)", value=-1
159
  )
 
 
 
 
 
 
160
 
161
  generate_button = gr.Button("🎬 Generate Video")
162
 
 
232
  """)
233
 
234
  @spaces.GPU(duration=120)
235
+ @torch.inference_mode()
236
  def generate(
237
  prompt,
 
 
 
238
  seed_value,
 
 
239
  progress=gr.Progress(track_tqdm=True)
240
  ):
241
+ torch.cuda.empty_cache()
242
+ torch.cuda.synchronize()
243
+
244
  latents, seed = infer(
245
  prompt,
 
 
 
246
  num_inference_steps=20, # Changed from 50
247
  guidance_scale=7.0, # NOT Changed
248
  seed=seed_value,
249
  progress=progress,
250
  )
 
 
 
 
251
 
252
  batch_size = latents.shape[0]
253
  batch_video_frames = []
 
267
 
268
  return video_path, video_update, gif_update, seed_update
269
 
 
 
270
 
271
  generate_button.click(
272
  generate,
273
  inputs=[prompt, seed_param],
 
 
274
  outputs=[video_output, download_video_button, download_gif_button, seed_text],
275
  )
276
 
 
 
 
277
  if __name__ == "__main__":
278
  utils.install_packages()
279
+ demo.queue(max_size=1)
280
  demo.launch()