seawolf2357 commited on
Commit
c7a9993
·
verified ·
1 Parent(s): fff6dc8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -159
app.py CHANGED
@@ -1,11 +1,3 @@
1
- """
2
- THis is the main file for the gradio web demo. It uses the CogVideoX-5B model to generate videos gradio web demo.
3
- set environment variable OPENAI_API_KEY to use the OpenAI API to enhance the prompt.
4
-
5
- Usage:
6
- OpenAI_API_KEY=your_openai_api_key OPENAI_BASE_URL=https://api.openai.com/v1 python inference/gradio_web_demo.py
7
- """
8
-
9
  import math
10
  import os
11
  import random
@@ -29,13 +21,17 @@ from diffusers.utils import load_video, load_image
29
  from datetime import datetime, timedelta
30
 
31
  from diffusers.image_processor import VaeImageProcessor
32
- from openai import OpenAI
33
  import moviepy.editor as mp
34
  import utils
35
  from rife_model import load_rife_model, rife_inference_with_latents
36
  from huggingface_hub import hf_hub_download, snapshot_download
 
37
  import gc
38
 
 
 
 
 
39
  device = "cuda" if torch.cuda.is_available() else "cpu"
40
 
41
  hf_hub_download(repo_id="ai-forever/Real-ESRGAN", filename="RealESRGAN_x4.pth", local_dir="model_real_esran")
@@ -48,30 +44,52 @@ i2v_transformer = CogVideoXTransformer3DModel.from_pretrained(
48
  "THUDM/CogVideoX-5b-I2V", subfolder="transformer", torch_dtype=torch.bfloat16
49
  )
50
 
51
- # pipe.transformer.to(memory_format=torch.channels_last)
52
- # pipe.transformer = torch.compile(pipe.transformer, mode="max-autotune", fullgraph=True)
53
- # pipe_image.transformer.to(memory_format=torch.channels_last)
54
- # pipe_image.transformer = torch.compile(pipe_image.transformer, mode="max-autotune", fullgraph=True)
55
-
56
  os.makedirs("./output", exist_ok=True)
57
  os.makedirs("./gradio_tmp", exist_ok=True)
58
 
59
  upscale_model = utils.load_sd_upscale("model_real_esran/RealESRGAN_x4.pth", device)
60
  frame_interpolation_model = load_rife_model("model_rife")
61
 
62
- 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.
 
 
 
 
 
 
 
63
 
64
- 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.
 
 
 
 
 
 
 
 
 
65
  There are a few rules to follow:
66
 
67
  You will only ever output a single video description per user request.
68
 
69
- When modifications are requested , you should not simply make the description longer . You should refactor the entire description to integrate the suggestions.
70
- 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.
71
 
72
  Video descriptions must have the same num of words as examples below. Extra words will be ignored.
73
  """
74
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
  def resize_if_unfit(input_video, progress=gr.Progress(track_tqdm=True)):
77
  width, height = get_video_dimensions(input_video)
@@ -82,13 +100,11 @@ def resize_if_unfit(input_video, progress=gr.Progress(track_tqdm=True)):
82
  processed_video = center_crop_resize(input_video)
83
  return processed_video
84
 
85
-
86
  def get_video_dimensions(input_video_path):
87
  reader = imageio_ffmpeg.read_frames(input_video_path)
88
  metadata = next(reader)
89
  return metadata["size"]
90
 
91
-
92
  def center_crop_resize(input_video_path, target_width=720, target_height=480):
93
  cap = cv2.VideoCapture(input_video_path)
94
 
@@ -146,57 +162,6 @@ def center_crop_resize(input_video_path, target_width=720, target_height=480):
146
 
147
  return temp_video_path
148
 
149
-
150
- def convert_prompt(prompt: str, retry_times: int = 3) -> str:
151
- if not os.environ.get("OPENAI_API_KEY"):
152
- return prompt
153
- client = OpenAI()
154
- text = prompt.strip()
155
-
156
- for i in range(retry_times):
157
- response = client.chat.completions.create(
158
- messages=[
159
- {"role": "system", "content": sys_prompt},
160
- {
161
- "role": "user",
162
- "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "a girl is on the beach"',
163
- },
164
- {
165
- "role": "assistant",
166
- "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.",
167
- },
168
- {
169
- "role": "user",
170
- "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "A man jogging on a football field"',
171
- },
172
- {
173
- "role": "assistant",
174
- "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.",
175
- },
176
- {
177
- "role": "user",
178
- "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : " A woman is dancing, HD footage, close-up"',
179
- },
180
- {
181
- "role": "assistant",
182
- "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.",
183
- },
184
- {
185
- "role": "user",
186
- "content": f'Create an imaginative video descriptive caption or modify an earlier caption in ENGLISH for the user input: "{text}"',
187
- },
188
- ],
189
- model="glm-4-plus",
190
- temperature=0.01,
191
- top_p=0.7,
192
- stream=False,
193
- max_tokens=200,
194
- )
195
- if response.choices:
196
- return response.choices[0].message.content
197
- return prompt
198
-
199
-
200
  def infer(
201
  prompt: str,
202
  image_input: str,
@@ -278,7 +243,6 @@ def infer(
278
  gc.collect()
279
  return (video_pt, seed)
280
 
281
-
282
  def convert_to_gif(video_path):
283
  clip = mp.VideoFileClip(video_path)
284
  clip = clip.set_fps(8)
@@ -287,7 +251,6 @@ def convert_to_gif(video_path):
287
  clip.write_gif(gif_path, fps=8)
288
  return gif_path
289
 
290
-
291
  def delete_old_files():
292
  while True:
293
  now = datetime.now()
@@ -303,32 +266,12 @@ def delete_old_files():
303
  os.remove(file_path)
304
  time.sleep(600)
305
 
306
-
307
  threading.Thread(target=delete_old_files, daemon=True).start()
308
  examples_videos = [["example_videos/horse.mp4"], ["example_videos/kitten.mp4"], ["example_videos/train_running.mp4"]]
309
  examples_images = [["example_images/beach.png"], ["example_images/street.png"], ["example_images/camping.png"]]
310
 
311
- with gr.Blocks() as demo:
312
- gr.Markdown("""
313
- <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
314
- CogVideoX-5B Huggingface Space🤗
315
- </div>
316
- <div style="text-align: center;">
317
- <a href="https://huggingface.co/THUDM/CogVideoX-5B">🤗 5B(T2V) Model Hub</a> |
318
- <a href="https://huggingface.co/THUDM/CogVideoX-5B-I2V">🤗 5B(I2V) Model Hub</a> |
319
- <a href="https://github.com/THUDM/CogVideo">🌐 Github</a> |
320
- <a href="https://arxiv.org/pdf/2408.06072">📜 arxiv </a>
321
- </div>
322
- <div style="text-align: center;display: flex;justify-content: center;align-items: center;margin-top: 1em;margin-bottom: .5em;">
323
- <span>If the Space is too busy, duplicate it to use privately</span>
324
- <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="
325
- margin-left: .75em;
326
- "></a>
327
- </div>
328
- <div style="text-align: center; font-size: 15px; font-weight: bold; color: red; margin-bottom: 20px;">
329
- ⚠️ This demo is for academic research and experiential use only.
330
- </div>
331
- """)
332
  with gr.Row():
333
  with gr.Column():
334
  with gr.Accordion("I2V: Image Input (cannot be used simultaneously with video input)", open=False):
@@ -367,70 +310,6 @@ with gr.Blocks() as demo:
367
  download_gif_button = gr.File(label="📥 Download GIF", visible=False)
368
  seed_text = gr.Number(label="Seed Used for Video Generation", visible=False)
369
 
370
- gr.Markdown("""
371
- <table border="0" style="width: 100%; text-align: left; margin-top: 20px;">
372
- <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
373
- 🎥 Video Gallery
374
- </div>
375
- <tr>
376
- <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
377
- <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>
378
- </td>
379
- <td style="width: 25%; vertical-align: top;">
380
- <video src="https://github.com/user-attachments/assets/cf5953ea-96d3-48fd-9907-c4708752c714" width="100%" controls autoplay loop></video>
381
- </td>
382
- <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
383
- <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>
384
- </td>
385
- <td style="width: 25%; vertical-align: top;">
386
- <video src="https://github.com/user-attachments/assets/fe0a78e6-b669-4800-8cf0-b5f9b5145b52" width="100%" controls autoplay loop></video>
387
- </td>
388
- </tr>
389
- <tr>
390
- <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
391
- <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>
392
- </td>
393
- <td style="width: 25%; vertical-align: top;">
394
- <video src="https://github.com/user-attachments/assets/c182f606-8f8c-421d-b414-8487070fcfcb" width="100%" controls autoplay loop></video>
395
- </td>
396
- <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
397
- <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>
398
- </td>
399
- <td style="width: 25%; vertical-align: top;">
400
- <video src="https://github.com/user-attachments/assets/7db2bbce-194d-434d-a605-350254b6c298" width="100%" controls autoplay loop></video>
401
- </td>
402
- </tr>
403
- <tr>
404
- <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
405
- <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>
406
- </td>
407
- <td style="width: 25%; vertical-align: top;">
408
- <video src="https://github.com/user-attachments/assets/62b01046-8cab-44cc-bd45-4d965bb615ec" width="100%" controls autoplay loop></video>
409
- </td>
410
- <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
411
- <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>
412
- </td>
413
- <td style="width: 25%; vertical-align: top;">
414
- <video src="https://github.com/user-attachments/assets/d78e552a-4b3f-4b81-ac3f-3898079554f6" width="100%" controls autoplay loop></video>
415
- </td>
416
- </tr>
417
- <tr>
418
- <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
419
- <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>
420
- </td>
421
- <td style="width: 25%; vertical-align: top;">
422
- <video src="https://github.com/user-attachments/assets/30894f12-c741-44a2-9e6e-ddcacc231e5b" width="100%" controls autoplay loop></video>
423
- </td>
424
- <td style="width: 25%; vertical-align: top; font-size: 0.9em;">
425
- <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>
426
- </td>
427
- <td style="width: 25%; vertical-align: top;">
428
- <video src="https://github.com/user-attachments/assets/926575ca-7150-435b-a0ff-4900a963297b" width="100%" controls autoplay loop></video>
429
- </td>
430
- </tr>
431
- </table>
432
- """)
433
-
434
  def generate(
435
  prompt,
436
  image_input,
@@ -489,3 +368,8 @@ with gr.Blocks() as demo:
489
  if __name__ == "__main__":
490
  demo.queue(max_size=15)
491
  demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import math
2
  import os
3
  import random
 
21
  from datetime import datetime, timedelta
22
 
23
  from diffusers.image_processor import VaeImageProcessor
 
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
+ from transformers import pipeline
29
  import gc
30
 
31
+ # Set CUDA device and enable cuDNN
32
+ torch.cuda.set_device(2)
33
+ torch.backends.cudnn.enabled = True
34
+
35
  device = "cuda" if torch.cuda.is_available() else "cpu"
36
 
37
  hf_hub_download(repo_id="ai-forever/Real-ESRGAN", filename="RealESRGAN_x4.pth", local_dir="model_real_esran")
 
44
  "THUDM/CogVideoX-5b-I2V", subfolder="transformer", torch_dtype=torch.bfloat16
45
  )
46
 
 
 
 
 
 
47
  os.makedirs("./output", exist_ok=True)
48
  os.makedirs("./gradio_tmp", exist_ok=True)
49
 
50
  upscale_model = utils.load_sd_upscale("model_real_esran/RealESRGAN_x4.pth", device)
51
  frame_interpolation_model = load_rife_model("model_rife")
52
 
53
+ # Load the translation model
54
+ translator = pipeline("translation", model="Helsinki-NLP/opus-mt-ko-en")
55
+
56
+ # Load the LLM model
57
+ from transformers import AutoTokenizer, AutoModelForCausalLM
58
+
59
+ tokenizer = AutoTokenizer.from_pretrained("CohereForAI/c4ai-command-r-plus-08-2024")
60
+ model = AutoModelForCausalLM.from_pretrained("CohereForAI/c4ai-command-r-plus-08-2024").to(device)
61
 
62
+ def convert_prompt(prompt: str, retry_times: int = 3) -> str:
63
+ text = prompt.strip()
64
+
65
+ # Check if the input is in Korean and translate if necessary
66
+ if any('\u3131' <= char <= '\u318E' or '\uAC00' <= char <= '\uD7A3' for char in text):
67
+ text = translator(text)[0]['translation_text']
68
+
69
+ system_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.
70
+
71
+ For example, outputting "a beautiful morning in the woods with the sun peaking through the trees" will trigger your partner bot to output a 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.
72
  There are a few rules to follow:
73
 
74
  You will only ever output a single video description per user request.
75
 
76
+ When modifications are requested, you should not simply make the description longer. You should refactor the entire description to integrate the suggestions.
77
+ 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.
78
 
79
  Video descriptions must have the same num of words as examples below. Extra words will be ignored.
80
  """
81
 
82
+ for i in range(retry_times):
83
+ input_text = f"{system_prompt}\n\nUser: Create an imaginative video descriptive caption or modify an earlier caption in ENGLISH for the user input: '{text}'\n\nAssistant:"
84
+
85
+ inputs = tokenizer(input_text, return_tensors="pt").to(device)
86
+ outputs = model.generate(**inputs, max_new_tokens=200, temperature=0.01, top_p=0.7)
87
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
88
+
89
+ if response:
90
+ return response.split("Assistant:")[-1].strip()
91
+
92
+ return prompt
93
 
94
  def resize_if_unfit(input_video, progress=gr.Progress(track_tqdm=True)):
95
  width, height = get_video_dimensions(input_video)
 
100
  processed_video = center_crop_resize(input_video)
101
  return processed_video
102
 
 
103
  def get_video_dimensions(input_video_path):
104
  reader = imageio_ffmpeg.read_frames(input_video_path)
105
  metadata = next(reader)
106
  return metadata["size"]
107
 
 
108
  def center_crop_resize(input_video_path, target_width=720, target_height=480):
109
  cap = cv2.VideoCapture(input_video_path)
110
 
 
162
 
163
  return temp_video_path
164
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
  def infer(
166
  prompt: str,
167
  image_input: str,
 
243
  gc.collect()
244
  return (video_pt, seed)
245
 
 
246
  def convert_to_gif(video_path):
247
  clip = mp.VideoFileClip(video_path)
248
  clip = clip.set_fps(8)
 
251
  clip.write_gif(gif_path, fps=8)
252
  return gif_path
253
 
 
254
  def delete_old_files():
255
  while True:
256
  now = datetime.now()
 
266
  os.remove(file_path)
267
  time.sleep(600)
268
 
 
269
  threading.Thread(target=delete_old_files, daemon=True).start()
270
  examples_videos = [["example_videos/horse.mp4"], ["example_videos/kitten.mp4"], ["example_videos/train_running.mp4"]]
271
  examples_images = [["example_images/beach.png"], ["example_images/street.png"], ["example_images/camping.png"]]
272
 
273
+ with gr.Blocks(theme="Nymbo/Nymbo_Theme") as demo:
274
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
275
  with gr.Row():
276
  with gr.Column():
277
  with gr.Accordion("I2V: Image Input (cannot be used simultaneously with video input)", open=False):
 
310
  download_gif_button = gr.File(label="📥 Download GIF", visible=False)
311
  seed_text = gr.Number(label="Seed Used for Video Generation", visible=False)
312
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
313
  def generate(
314
  prompt,
315
  image_input,
 
368
  if __name__ == "__main__":
369
  demo.queue(max_size=15)
370
  demo.launch()
371
+
372
+
373
+
374
+
375
+