VictorKai1996NUS commited on
Commit
bac0d32
1 Parent(s): 4e64fd4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -361
app.py CHANGED
@@ -1,345 +1,5 @@
1
- # import os
2
-
3
- # os.environ["GRADIO_TEMP_DIR"] = os.path.join(os.getcwd(), ".tmp_outputs")
4
-
5
- # import torch
6
- # from openai import OpenAI
7
- # from time import time
8
- # import tempfile
9
- # import uuid
10
- # import logging
11
- # import gradio as gr
12
- # from videosys import CogVideoConfig, VideoSysEngine
13
- # from videosys.models.cogvideo.pipeline import CogVideoPABConfig
14
- # import psutil
15
- # import GPUtil
16
-
17
- # logging.basicConfig(level=logging.INFO)
18
- # logger = logging.getLogger(__name__)
19
-
20
- # dtype = torch.bfloat16
21
- # 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.
22
-
23
- # 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.
24
- # There are a few rules to follow:
25
-
26
- # You will only ever output a single video description per user request.
27
-
28
- # When modifications are requested , you should not simply make the description longer . You should refactor the entire description to integrate the suggestions.
29
- # 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.
30
-
31
- # Video descriptions must have the same num of words as examples below. Extra words will be ignored.
32
- # """
33
-
34
- # def convert_prompt(prompt: str, retry_times: int = 3) -> str:
35
- # if not os.environ.get("OPENAI_API_KEY"):
36
- # return prompt
37
- # client = OpenAI()
38
- # text = prompt.strip()
39
-
40
- # for i in range(retry_times):
41
- # response = client.chat.completions.create(
42
- # messages=[
43
- # {"role": "system", "content": sys_prompt},
44
- # {
45
- # "role": "user",
46
- # "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "a girl is on the beach"',
47
- # },
48
- # {
49
- # "role": "assistant",
50
- # "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.",
51
- # },
52
- # {
53
- # "role": "user",
54
- # "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "A man jogging on a football field"',
55
- # },
56
- # {
57
- # "role": "assistant",
58
- # "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.",
59
- # },
60
- # {
61
- # "role": "user",
62
- # "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : " A woman is dancing, HD footage, close-up"',
63
- # },
64
- # {
65
- # "role": "assistant",
66
- # "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.",
67
- # },
68
- # {
69
- # "role": "user",
70
- # "content": f'Create an imaginative video descriptive caption or modify an earlier caption in ENGLISH for the user input: "{text}"',
71
- # },
72
- # ],
73
- # model="glm-4-0520",
74
- # temperature=0.01,
75
- # top_p=0.7,
76
- # stream=False,
77
- # max_tokens=250,
78
- # )
79
- # if response.choices:
80
- # return response.choices[0].message.content
81
- # return prompt
82
-
83
- # def load_model(enable_video_sys=False, pab_threshold=[100, 850], pab_gap=2):
84
- # pab_config = CogVideoPABConfig(full_threshold=pab_threshold, full_gap=pab_gap)
85
- # config = CogVideoConfig(world_size=1, enable_pab=enable_video_sys, pab_config=pab_config)
86
- # engine = VideoSysEngine(config)
87
- # return engine
88
-
89
- # def generate(engine, prompt, num_inference_steps=50, guidance_scale=6.0):
90
- # try:
91
- # video = engine.generate(prompt, num_inference_steps=num_inference_steps, guidance_scale=guidance_scale).video[0]
92
-
93
- # with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as temp_file:
94
- # temp_file.name
95
- # unique_filename = f"{uuid.uuid4().hex}.mp4"
96
- # output_path = os.path.join("./temp_outputs", unique_filename)
97
-
98
- # engine.save_video(video, output_path)
99
- # return output_path
100
- # except Exception as e:
101
- # logger.error(f"An error occurred: {str(e)}")
102
- # return None
103
-
104
-
105
- # def get_server_status():
106
- # cpu_percent = psutil.cpu_percent()
107
- # memory = psutil.virtual_memory()
108
- # disk = psutil.disk_usage('/')
109
- # gpus = GPUtil.getGPUs()
110
- # gpu_info = []
111
- # for gpu in gpus:
112
- # gpu_info.append({
113
- # 'id': gpu.id,
114
- # 'name': gpu.name,
115
- # 'load': f"{gpu.load*100:.1f}%",
116
- # 'memory_used': f"{gpu.memoryUsed}MB",
117
- # 'memory_total': f"{gpu.memoryTotal}MB"
118
- # })
119
-
120
- # return {
121
- # 'cpu': f"{cpu_percent}%",
122
- # 'memory': f"{memory.percent}%",
123
- # 'disk': f"{disk.percent}%",
124
- # 'gpu': gpu_info
125
- # }
126
-
127
-
128
-
129
- # css = """
130
- # body {
131
- # font-family: Arial, sans-serif;
132
- # line-height: 1.6;
133
- # color: #333;
134
- # margin: 0 auto;
135
- # padding: 20px;
136
- # }
137
-
138
- # .container {
139
- # display: flex;
140
- # flex-direction: column;
141
- # gap: 20px;
142
- # }
143
-
144
- # .row {
145
- # display: flex;
146
- # flex-wrap: wrap;
147
- # gap: 20px;
148
- # }
149
-
150
- # .column {
151
- # flex: 1;
152
- # min-width: 0;
153
- # }
154
-
155
- # .video-output {
156
- # width: 100%;
157
- # max-width: 720px;
158
- # height: auto;
159
- # margin: 0 auto;
160
- # }
161
-
162
- # .server-status {
163
- # margin-top: 20px;
164
- # background-color: white;
165
- # padding: 10px;
166
- # border-radius: 5px;
167
- # box-shadow: 0 1px 3px rgba(0,0,0,0.1);
168
- # font-size: 0.9em;
169
- # width: 100%;
170
- # }
171
-
172
- # .server-status h4 {
173
- # margin: 0 0 10px 0;
174
- # font-size: 1em;
175
- # font-weight: bold;
176
- # }
177
-
178
- # .server-status-details {
179
- # margin-top: 10px;
180
- # }
181
-
182
- # @media (max-width: 768px) {
183
- # .row {
184
- # flex-direction: column;
185
- # }
186
- # .column {
187
- # width: 100%;
188
- # }
189
- # .video-output {
190
- # width: 100%;
191
- # height: auto;
192
- # }
193
- # }
194
- # """
195
-
196
- # with gr.Blocks(css=css) as demo:
197
- # gr.HTML("""
198
- # <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
199
- # VideoSys Huggingface Space🤗
200
- # </div>
201
- # <div style="text-align: center; font-size: 15px;">
202
- # 🌐 Github: <a href="https://github.com/NUS-HPC-AI-Lab/VideoSys">https://github.com/NUS-HPC-AI-Lab/VideoSys</a><br>
203
-
204
- # ⚠️ This demo is for academic research and experiential use only.
205
- # Users should strictly adhere to local laws and ethics.<br>
206
-
207
- # 💡 This demo only demonstrates single-device inference. To experience the full power of VideoSys, please deploy it with multiple devices.<br><br>
208
- # </div>
209
- # </div>
210
- # """)
211
-
212
- # with gr.Row():
213
- # with gr.Column():
214
- # prompt = gr.Textbox(label="Prompt (Less than 200 Words)", value="Sunset over the sea.", lines=5)
215
- # with gr.Row():
216
- # gr.Markdown(
217
- # "✨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."
218
- # )
219
- # enhance_button = gr.Button("✨ Enhance Prompt(Optional)")
220
-
221
- # with gr.Column():
222
- # gr.Markdown(
223
- # "**Optional Parameters** (default values are recommended)<br>"
224
- # "Turn Inference Steps larger if you want more detailed video, but it will be slower.<br>"
225
- # "50 steps are recommended for most cases. will cause 120 seconds for inference.<br>"
226
- # )
227
- # with gr.Row():
228
- # num_inference_steps = gr.Number(label="Inference Steps", value=50)
229
- # guidance_scale = gr.Number(label="Guidance Scale", value=6.0)
230
- # pab_gap = gr.Number(label="PAB Gap", value=2, precision=0)
231
- # pab_threshold = gr.Textbox(label="PAB Threshold", value="100,850", lines=1)
232
- # with gr.Row():
233
- # generate_button = gr.Button("🎬 Generate Video")
234
- # generate_button_vs = gr.Button("⚡️ Generate Video with VideoSys (Faster)")
235
- # with gr.Row(elem_classes="server-status"):
236
- # gr.Markdown("#### Server Status")
237
- # with gr.Row():
238
- # cpu_status = gr.Textbox(label="CPU", scale=1)
239
- # memory_status = gr.Textbox(label="Memory", scale=1)
240
- # disk_status = gr.Textbox(label="Disk", scale=1)
241
- # gpu_status = gr.Textbox(label="GPU Memory", scale=1)
242
- # refresh_button = gr.Button("Refresh", scale=1, size="sm")
243
-
244
- # with gr.Column():
245
- # with gr.Row():
246
- # video_output = gr.Video(label="CogVideoX", width=720, height=480)
247
- # with gr.Row():
248
- # download_video_button = gr.File(label="📥 Download Video", visible=False)
249
- # elapsed_time = gr.Textbox(label="Elapsed Time", value="0s", visible=False)
250
- # with gr.Row():
251
- # video_output_vs = gr.Video(label="CogVideoX with VideoSys", width=720, height=480)
252
- # with gr.Row():
253
- # download_video_button_vs = gr.File(label="📥 Download Video", visible=False)
254
- # elapsed_time_vs = gr.Textbox(label="Elapsed Time", value="0s", visible=False)
255
-
256
-
257
-
258
-
259
- # def generate_vanilla(prompt, num_inference_steps, guidance_scale, progress=gr.Progress(track_tqdm=True)):
260
- # engine = load_model()
261
- # t = time()
262
- # video_path = generate(engine, prompt, num_inference_steps, guidance_scale)
263
- # elapsed_time = time() - t
264
- # video_update = gr.update(visible=True, value=video_path)
265
- # elapsed_time = gr.update(visible=True, value=f"{elapsed_time:.2f}s")
266
-
267
- # return video_path, video_update, elapsed_time
268
-
269
- # def generate_vs(prompt, num_inference_steps, guidance_scale, threshold, gap, progress=gr.Progress(track_tqdm=True)):
270
- # threshold = [int(i) for i in threshold.split(",")]
271
- # gap = int(gap)
272
- # engine = load_model(enable_video_sys=True, pab_threshold=threshold, pab_gap=gap)
273
- # t = time()
274
- # video_path = generate(engine, prompt, num_inference_steps, guidance_scale)
275
- # elapsed_time = time() - t
276
- # video_update = gr.update(visible=True, value=video_path)
277
- # elapsed_time = gr.update(visible=True, value=f"{elapsed_time:.2f}s")
278
-
279
- # return video_path, video_update, elapsed_time
280
-
281
- # def enhance_prompt_func(prompt):
282
- # return convert_prompt(prompt, retry_times=1)
283
-
284
- # def get_server_status():
285
- # cpu_percent = psutil.cpu_percent()
286
- # memory = psutil.virtual_memory()
287
- # disk = psutil.disk_usage('/')
288
- # try:
289
- # gpus = GPUtil.getGPUs()
290
- # if gpus:
291
- # gpu = gpus[0] # 只获取第一个GPU的信息
292
- # gpu_memory = f"{gpu.memoryUsed}/{gpu.memoryTotal}MB ({gpu.memoryUtil*100:.1f}%)"
293
- # else:
294
- # gpu_memory = "No GPU found"
295
- # except:
296
- # gpu_memory = "GPU information unavailable"
297
-
298
- # return {
299
- # 'cpu': f"{cpu_percent}%",
300
- # 'memory': f"{memory.percent}%",
301
- # 'disk': f"{disk.percent}%",
302
- # 'gpu_memory': gpu_memory
303
- # }
304
-
305
-
306
- # def update_server_status():
307
- # status = get_server_status()
308
- # return (
309
- # status['cpu'],
310
- # status['memory'],
311
- # status['disk'],
312
- # status['gpu_memory']
313
- # )
314
-
315
-
316
- # generate_button.click(
317
- # generate_vanilla,
318
- # inputs=[prompt, num_inference_steps, guidance_scale],
319
- # outputs=[video_output, download_video_button, elapsed_time],
320
- # )
321
-
322
- # generate_button_vs.click(
323
- # generate_vs,
324
- # inputs=[prompt, num_inference_steps, guidance_scale, pab_threshold, pab_gap],
325
- # outputs=[video_output_vs, download_video_button_vs, elapsed_time_vs],
326
- # )
327
-
328
- # enhance_button.click(enhance_prompt_func, inputs=[prompt], outputs=[prompt])
329
-
330
-
331
- # refresh_button.click(update_server_status, outputs=[cpu_status, memory_status, disk_status, gpu_status])
332
- # demo.load(update_server_status, outputs=[cpu_status, memory_status, disk_status, gpu_status], every=1)
333
-
334
- # if __name__ == "__main__":
335
- # demo.queue(max_size=10, default_concurrency_limit=1)
336
- # demo.launch()
337
-
338
-
339
-
340
-
341
-
342
  import os
 
343
  os.environ["GRADIO_TEMP_DIR"] = os.path.join(os.getcwd(), ".tmp_outputs")
344
 
345
  import torch
@@ -353,8 +13,6 @@ from videosys import CogVideoConfig, VideoSysEngine
353
  from videosys.models.cogvideo.pipeline import CogVideoPABConfig
354
  import psutil
355
  import GPUtil
356
- import threading
357
- from queue import Queue
358
 
359
  logging.basicConfig(level=logging.INFO)
360
  logger = logging.getLogger(__name__)
@@ -373,17 +31,6 @@ Other times the user will not want modifications , but instead want a new image
373
  Video descriptions must have the same num of words as examples below. Extra words will be ignored.
374
  """
375
 
376
- task_queue = Queue()
377
-
378
- def process_task():
379
- while True:
380
- task = task_queue.get()
381
- result = task['function'](*task['args'])
382
- task['callback'](result)
383
- task_queue.task_done()
384
-
385
- threading.Thread(target=process_task, daemon=True).start()
386
-
387
  def convert_prompt(prompt: str, retry_times: int = 3) -> str:
388
  if not os.environ.get("OPENAI_API_KEY"):
389
  return prompt
@@ -454,6 +101,7 @@ def generate(engine, prompt, num_inference_steps=50, guidance_scale=6.0):
454
  logger.error(f"An error occurred: {str(e)}")
455
  return None
456
 
 
457
  def get_server_status():
458
  cpu_percent = psutil.cpu_percent()
459
  memory = psutil.virtual_memory()
@@ -476,6 +124,8 @@ def get_server_status():
476
  'gpu': gpu_info
477
  }
478
 
 
 
479
  css = """
480
  body {
481
  font-family: Arial, sans-serif;
@@ -603,12 +253,18 @@ with gr.Blocks(css=css) as demo:
603
  download_video_button_vs = gr.File(label="📥 Download Video", visible=False)
604
  elapsed_time_vs = gr.Textbox(label="Elapsed Time", value="0s", visible=False)
605
 
 
 
 
606
  def generate_vanilla(prompt, num_inference_steps, guidance_scale, progress=gr.Progress(track_tqdm=True)):
607
  engine = load_model()
608
  t = time()
609
  video_path = generate(engine, prompt, num_inference_steps, guidance_scale)
610
  elapsed_time = time() - t
611
- return video_path, gr.update(visible=True, value=video_path), gr.update(visible=True, value=f"{elapsed_time:.2f}s")
 
 
 
612
 
613
  def generate_vs(prompt, num_inference_steps, guidance_scale, threshold, gap, progress=gr.Progress(track_tqdm=True)):
614
  threshold = [int(i) for i in threshold.split(",")]
@@ -617,7 +273,10 @@ with gr.Blocks(css=css) as demo:
617
  t = time()
618
  video_path = generate(engine, prompt, num_inference_steps, guidance_scale)
619
  elapsed_time = time() - t
620
- return video_path, gr.update(visible=True, value=video_path), gr.update(visible=True, value=f"{elapsed_time:.2f}s")
 
 
 
621
 
622
  def enhance_prompt_func(prompt):
623
  return convert_prompt(prompt, retry_times=1)
@@ -642,6 +301,7 @@ with gr.Blocks(css=css) as demo:
642
  'disk': f"{disk.percent}%",
643
  'gpu_memory': gpu_memory
644
  }
 
645
 
646
  def update_server_status():
647
  status = get_server_status()
@@ -652,9 +312,6 @@ with gr.Blocks(css=css) as demo:
652
  status['gpu_memory']
653
  )
654
 
655
- def queue_task(func, args, callback):
656
- task = {'function': func, 'args': args, 'callback': callback}
657
- task_queue.put(task)
658
 
659
  generate_button.click(
660
  generate_vanilla,
@@ -670,9 +327,10 @@ with gr.Blocks(css=css) as demo:
670
 
671
  enhance_button.click(enhance_prompt_func, inputs=[prompt], outputs=[prompt])
672
 
 
673
  refresh_button.click(update_server_status, outputs=[cpu_status, memory_status, disk_status, gpu_status])
674
  demo.load(update_server_status, outputs=[cpu_status, memory_status, disk_status, gpu_status], every=1)
675
 
676
  if __name__ == "__main__":
677
- demo.queue(concurrency_count=1, max_size=10)
678
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
+
3
  os.environ["GRADIO_TEMP_DIR"] = os.path.join(os.getcwd(), ".tmp_outputs")
4
 
5
  import torch
 
13
  from videosys.models.cogvideo.pipeline import CogVideoPABConfig
14
  import psutil
15
  import GPUtil
 
 
16
 
17
  logging.basicConfig(level=logging.INFO)
18
  logger = logging.getLogger(__name__)
 
31
  Video descriptions must have the same num of words as examples below. Extra words will be ignored.
32
  """
33
 
 
 
 
 
 
 
 
 
 
 
 
34
  def convert_prompt(prompt: str, retry_times: int = 3) -> str:
35
  if not os.environ.get("OPENAI_API_KEY"):
36
  return prompt
 
101
  logger.error(f"An error occurred: {str(e)}")
102
  return None
103
 
104
+
105
  def get_server_status():
106
  cpu_percent = psutil.cpu_percent()
107
  memory = psutil.virtual_memory()
 
124
  'gpu': gpu_info
125
  }
126
 
127
+
128
+
129
  css = """
130
  body {
131
  font-family: Arial, sans-serif;
 
253
  download_video_button_vs = gr.File(label="📥 Download Video", visible=False)
254
  elapsed_time_vs = gr.Textbox(label="Elapsed Time", value="0s", visible=False)
255
 
256
+
257
+
258
+
259
  def generate_vanilla(prompt, num_inference_steps, guidance_scale, progress=gr.Progress(track_tqdm=True)):
260
  engine = load_model()
261
  t = time()
262
  video_path = generate(engine, prompt, num_inference_steps, guidance_scale)
263
  elapsed_time = time() - t
264
+ video_update = gr.update(visible=True, value=video_path)
265
+ elapsed_time = gr.update(visible=True, value=f"{elapsed_time:.2f}s")
266
+
267
+ return video_path, video_update, elapsed_time
268
 
269
  def generate_vs(prompt, num_inference_steps, guidance_scale, threshold, gap, progress=gr.Progress(track_tqdm=True)):
270
  threshold = [int(i) for i in threshold.split(",")]
 
273
  t = time()
274
  video_path = generate(engine, prompt, num_inference_steps, guidance_scale)
275
  elapsed_time = time() - t
276
+ video_update = gr.update(visible=True, value=video_path)
277
+ elapsed_time = gr.update(visible=True, value=f"{elapsed_time:.2f}s")
278
+
279
+ return video_path, video_update, elapsed_time
280
 
281
  def enhance_prompt_func(prompt):
282
  return convert_prompt(prompt, retry_times=1)
 
301
  'disk': f"{disk.percent}%",
302
  'gpu_memory': gpu_memory
303
  }
304
+
305
 
306
  def update_server_status():
307
  status = get_server_status()
 
312
  status['gpu_memory']
313
  )
314
 
 
 
 
315
 
316
  generate_button.click(
317
  generate_vanilla,
 
327
 
328
  enhance_button.click(enhance_prompt_func, inputs=[prompt], outputs=[prompt])
329
 
330
+
331
  refresh_button.click(update_server_status, outputs=[cpu_status, memory_status, disk_status, gpu_status])
332
  demo.load(update_server_status, outputs=[cpu_status, memory_status, disk_status, gpu_status], every=1)
333
 
334
  if __name__ == "__main__":
335
+ demo.queue(max_size=10, default_concurrency_limit=1)
336
+ demo.launch()