Spaces:
Running
on
Zero
Running
on
Zero
File size: 29,489 Bytes
0c14fd5 61bd18b 0c14fd5 61bd18b 07c6a04 374c3a9 d6e8791 0c14fd5 07c6a04 0c14fd5 07c6a04 374c3a9 07c6a04 efc27db 61bd18b efc27db 61bd18b efc27db 07c6a04 efc27db b967c01 0af4f53 b967c01 efc27db b967c01 efc27db b967c01 efc27db b967c01 efc27db b967c01 efc27db b967c01 efc27db b967c01 07c6a04 9b08739 07c6a04 9b08739 07c6a04 374c3a9 07c6a04 b71d548 0af4f53 b71d548 07c6a04 61bd18b 07c6a04 61bd18b 07c6a04 61bd18b efc27db 0af4f53 efc27db 0c14fd5 efc27db 07c6a04 0c14fd5 07c6a04 61bd18b 07c6a04 0c14fd5 07c6a04 61bd18b 07c6a04 61bd18b 07c6a04 61bd18b 0af4f53 efc27db 07c6a04 61bd18b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 |
# import os
# os.environ["GRADIO_TEMP_DIR"] = os.path.join(os.getcwd(), ".tmp_outputs")
# import torch
# from openai import OpenAI
# from time import time
# import tempfile
# import uuid
# import logging
# import gradio as gr
# from videosys import CogVideoConfig, VideoSysEngine
# from videosys.models.cogvideo.pipeline import CogVideoPABConfig
# import psutil
# import GPUtil
# logging.basicConfig(level=logging.INFO)
# logger = logging.getLogger(__name__)
# dtype = torch.bfloat16
# 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.
# 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.
# There are a few rules to follow:
# You will only ever output a single video description per user request.
# When modifications are requested , you should not simply make the description longer . You should refactor the entire description to integrate the suggestions.
# 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.
# Video descriptions must have the same num of words as examples below. Extra words will be ignored.
# """
# def convert_prompt(prompt: str, retry_times: int = 3) -> str:
# if not os.environ.get("OPENAI_API_KEY"):
# return prompt
# client = OpenAI()
# text = prompt.strip()
# for i in range(retry_times):
# response = client.chat.completions.create(
# messages=[
# {"role": "system", "content": sys_prompt},
# {
# "role": "user",
# "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "a girl is on the beach"',
# },
# {
# "role": "assistant",
# "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.",
# },
# {
# "role": "user",
# "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "A man jogging on a football field"',
# },
# {
# "role": "assistant",
# "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.",
# },
# {
# "role": "user",
# "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : " A woman is dancing, HD footage, close-up"',
# },
# {
# "role": "assistant",
# "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.",
# },
# {
# "role": "user",
# "content": f'Create an imaginative video descriptive caption or modify an earlier caption in ENGLISH for the user input: "{text}"',
# },
# ],
# model="glm-4-0520",
# temperature=0.01,
# top_p=0.7,
# stream=False,
# max_tokens=250,
# )
# if response.choices:
# return response.choices[0].message.content
# return prompt
# def load_model(enable_video_sys=False, pab_threshold=[100, 850], pab_gap=2):
# pab_config = CogVideoPABConfig(full_threshold=pab_threshold, full_gap=pab_gap)
# config = CogVideoConfig(world_size=1, enable_pab=enable_video_sys, pab_config=pab_config)
# engine = VideoSysEngine(config)
# return engine
# def generate(engine, prompt, num_inference_steps=50, guidance_scale=6.0):
# try:
# video = engine.generate(prompt, num_inference_steps=num_inference_steps, guidance_scale=guidance_scale).video[0]
# with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as temp_file:
# temp_file.name
# unique_filename = f"{uuid.uuid4().hex}.mp4"
# output_path = os.path.join("./temp_outputs", unique_filename)
# engine.save_video(video, output_path)
# return output_path
# except Exception as e:
# logger.error(f"An error occurred: {str(e)}")
# return None
# def get_server_status():
# cpu_percent = psutil.cpu_percent()
# memory = psutil.virtual_memory()
# disk = psutil.disk_usage('/')
# gpus = GPUtil.getGPUs()
# gpu_info = []
# for gpu in gpus:
# gpu_info.append({
# 'id': gpu.id,
# 'name': gpu.name,
# 'load': f"{gpu.load*100:.1f}%",
# 'memory_used': f"{gpu.memoryUsed}MB",
# 'memory_total': f"{gpu.memoryTotal}MB"
# })
# return {
# 'cpu': f"{cpu_percent}%",
# 'memory': f"{memory.percent}%",
# 'disk': f"{disk.percent}%",
# 'gpu': gpu_info
# }
# css = """
# body {
# font-family: Arial, sans-serif;
# line-height: 1.6;
# color: #333;
# margin: 0 auto;
# padding: 20px;
# }
# .container {
# display: flex;
# flex-direction: column;
# gap: 20px;
# }
# .row {
# display: flex;
# flex-wrap: wrap;
# gap: 20px;
# }
# .column {
# flex: 1;
# min-width: 0;
# }
# .video-output {
# width: 100%;
# max-width: 720px;
# height: auto;
# margin: 0 auto;
# }
# .server-status {
# margin-top: 20px;
# background-color: white;
# padding: 10px;
# border-radius: 5px;
# box-shadow: 0 1px 3px rgba(0,0,0,0.1);
# font-size: 0.9em;
# width: 100%;
# }
# .server-status h4 {
# margin: 0 0 10px 0;
# font-size: 1em;
# font-weight: bold;
# }
# .server-status-details {
# margin-top: 10px;
# }
# @media (max-width: 768px) {
# .row {
# flex-direction: column;
# }
# .column {
# width: 100%;
# }
# .video-output {
# width: 100%;
# height: auto;
# }
# }
# """
# with gr.Blocks(css=css) as demo:
# gr.HTML("""
# <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
# VideoSys Huggingface Space🤗
# </div>
# <div style="text-align: center; font-size: 15px;">
# 🌐 Github: <a href="https://github.com/NUS-HPC-AI-Lab/VideoSys">https://github.com/NUS-HPC-AI-Lab/VideoSys</a><br>
# ⚠️ This demo is for academic research and experiential use only.
# Users should strictly adhere to local laws and ethics.<br>
# 💡 This demo only demonstrates single-device inference. To experience the full power of VideoSys, please deploy it with multiple devices.<br><br>
# </div>
# </div>
# """)
# with gr.Row():
# with gr.Column():
# prompt = gr.Textbox(label="Prompt (Less than 200 Words)", value="Sunset over the sea.", lines=5)
# with gr.Row():
# gr.Markdown(
# "✨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."
# )
# enhance_button = gr.Button("✨ Enhance Prompt(Optional)")
# with gr.Column():
# gr.Markdown(
# "**Optional Parameters** (default values are recommended)<br>"
# "Turn Inference Steps larger if you want more detailed video, but it will be slower.<br>"
# "50 steps are recommended for most cases. will cause 120 seconds for inference.<br>"
# )
# with gr.Row():
# num_inference_steps = gr.Number(label="Inference Steps", value=50)
# guidance_scale = gr.Number(label="Guidance Scale", value=6.0)
# pab_gap = gr.Number(label="PAB Gap", value=2, precision=0)
# pab_threshold = gr.Textbox(label="PAB Threshold", value="100,850", lines=1)
# with gr.Row():
# generate_button = gr.Button("🎬 Generate Video")
# generate_button_vs = gr.Button("⚡️ Generate Video with VideoSys (Faster)")
# with gr.Row(elem_classes="server-status"):
# gr.Markdown("#### Server Status")
# with gr.Row():
# cpu_status = gr.Textbox(label="CPU", scale=1)
# memory_status = gr.Textbox(label="Memory", scale=1)
# disk_status = gr.Textbox(label="Disk", scale=1)
# gpu_status = gr.Textbox(label="GPU Memory", scale=1)
# refresh_button = gr.Button("Refresh", scale=1, size="sm")
# with gr.Column():
# with gr.Row():
# video_output = gr.Video(label="CogVideoX", width=720, height=480)
# with gr.Row():
# download_video_button = gr.File(label="📥 Download Video", visible=False)
# elapsed_time = gr.Textbox(label="Elapsed Time", value="0s", visible=False)
# with gr.Row():
# video_output_vs = gr.Video(label="CogVideoX with VideoSys", width=720, height=480)
# with gr.Row():
# download_video_button_vs = gr.File(label="📥 Download Video", visible=False)
# elapsed_time_vs = gr.Textbox(label="Elapsed Time", value="0s", visible=False)
# def generate_vanilla(prompt, num_inference_steps, guidance_scale, progress=gr.Progress(track_tqdm=True)):
# engine = load_model()
# t = time()
# video_path = generate(engine, prompt, num_inference_steps, guidance_scale)
# elapsed_time = time() - t
# video_update = gr.update(visible=True, value=video_path)
# elapsed_time = gr.update(visible=True, value=f"{elapsed_time:.2f}s")
# return video_path, video_update, elapsed_time
# def generate_vs(prompt, num_inference_steps, guidance_scale, threshold, gap, progress=gr.Progress(track_tqdm=True)):
# threshold = [int(i) for i in threshold.split(",")]
# gap = int(gap)
# engine = load_model(enable_video_sys=True, pab_threshold=threshold, pab_gap=gap)
# t = time()
# video_path = generate(engine, prompt, num_inference_steps, guidance_scale)
# elapsed_time = time() - t
# video_update = gr.update(visible=True, value=video_path)
# elapsed_time = gr.update(visible=True, value=f"{elapsed_time:.2f}s")
# return video_path, video_update, elapsed_time
# def enhance_prompt_func(prompt):
# return convert_prompt(prompt, retry_times=1)
# def get_server_status():
# cpu_percent = psutil.cpu_percent()
# memory = psutil.virtual_memory()
# disk = psutil.disk_usage('/')
# try:
# gpus = GPUtil.getGPUs()
# if gpus:
# gpu = gpus[0] # 只获取第一个GPU的信息
# gpu_memory = f"{gpu.memoryUsed}/{gpu.memoryTotal}MB ({gpu.memoryUtil*100:.1f}%)"
# else:
# gpu_memory = "No GPU found"
# except:
# gpu_memory = "GPU information unavailable"
# return {
# 'cpu': f"{cpu_percent}%",
# 'memory': f"{memory.percent}%",
# 'disk': f"{disk.percent}%",
# 'gpu_memory': gpu_memory
# }
# def update_server_status():
# status = get_server_status()
# return (
# status['cpu'],
# status['memory'],
# status['disk'],
# status['gpu_memory']
# )
# generate_button.click(
# generate_vanilla,
# inputs=[prompt, num_inference_steps, guidance_scale],
# outputs=[video_output, download_video_button, elapsed_time],
# )
# generate_button_vs.click(
# generate_vs,
# inputs=[prompt, num_inference_steps, guidance_scale, pab_threshold, pab_gap],
# outputs=[video_output_vs, download_video_button_vs, elapsed_time_vs],
# )
# enhance_button.click(enhance_prompt_func, inputs=[prompt], outputs=[prompt])
# refresh_button.click(update_server_status, outputs=[cpu_status, memory_status, disk_status, gpu_status])
# demo.load(update_server_status, outputs=[cpu_status, memory_status, disk_status, gpu_status], every=1)
# if __name__ == "__main__":
# demo.queue(max_size=10, default_concurrency_limit=1)
# demo.launch()
import os
os.environ["GRADIO_TEMP_DIR"] = os.path.join(os.getcwd(), ".tmp_outputs")
import torch
from openai import OpenAI
from time import time
import tempfile
import uuid
import logging
import gradio as gr
from videosys import CogVideoConfig, VideoSysEngine
from videosys.models.cogvideo.pipeline import CogVideoPABConfig
import psutil
import GPUtil
import threading
from queue import Queue
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
dtype = torch.bfloat16
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.
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.
There are a few rules to follow:
You will only ever output a single video description per user request.
When modifications are requested , you should not simply make the description longer . You should refactor the entire description to integrate the suggestions.
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.
Video descriptions must have the same num of words as examples below. Extra words will be ignored.
"""
task_semaphore = threading.Semaphore(1)
task_queue = Queue()
def process_task():
while True:
task = task_queue.get()
with task_semaphore:
result = task['function'](*task['args'])
task['callback'](result)
task_queue.task_done()
threading.Thread(target=process_task, daemon=True).start()
def convert_prompt(prompt: str, retry_times: int = 3) -> str:
if not os.environ.get("OPENAI_API_KEY"):
return prompt
client = OpenAI()
text = prompt.strip()
for i in range(retry_times):
response = client.chat.completions.create(
messages=[
{"role": "system", "content": sys_prompt},
{
"role": "user",
"content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "a girl is on the beach"',
},
{
"role": "assistant",
"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.",
},
{
"role": "user",
"content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "A man jogging on a football field"',
},
{
"role": "assistant",
"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.",
},
{
"role": "user",
"content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : " A woman is dancing, HD footage, close-up"',
},
{
"role": "assistant",
"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.",
},
{
"role": "user",
"content": f'Create an imaginative video descriptive caption or modify an earlier caption in ENGLISH for the user input: "{text}"',
},
],
model="glm-4-0520",
temperature=0.01,
top_p=0.7,
stream=False,
max_tokens=250,
)
if response.choices:
return response.choices[0].message.content
return prompt
def load_model(enable_video_sys=False, pab_threshold=[100, 850], pab_gap=2):
pab_config = CogVideoPABConfig(full_threshold=pab_threshold, full_gap=pab_gap)
config = CogVideoConfig(world_size=1, enable_pab=enable_video_sys, pab_config=pab_config)
engine = VideoSysEngine(config)
return engine
def generate(engine, prompt, num_inference_steps=50, guidance_scale=6.0):
try:
video = engine.generate(prompt, num_inference_steps=num_inference_steps, guidance_scale=guidance_scale).video[0]
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as temp_file:
temp_file.name
unique_filename = f"{uuid.uuid4().hex}.mp4"
output_path = os.path.join("./temp_outputs", unique_filename)
engine.save_video(video, output_path)
return output_path
except Exception as e:
logger.error(f"An error occurred: {str(e)}")
return None
def get_server_status():
cpu_percent = psutil.cpu_percent()
memory = psutil.virtual_memory()
disk = psutil.disk_usage('/')
gpus = GPUtil.getGPUs()
gpu_info = []
for gpu in gpus:
gpu_info.append({
'id': gpu.id,
'name': gpu.name,
'load': f"{gpu.load*100:.1f}%",
'memory_used': f"{gpu.memoryUsed}MB",
'memory_total': f"{gpu.memoryTotal}MB"
})
return {
'cpu': f"{cpu_percent}%",
'memory': f"{memory.percent}%",
'disk': f"{disk.percent}%",
'gpu': gpu_info
}
css = """
body {
font-family: Arial, sans-serif;
line-height: 1.6;
color: #333;
margin: 0 auto;
padding: 20px;
}
.container {
display: flex;
flex-direction: column;
gap: 20px;
}
.row {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.column {
flex: 1;
min-width: 0;
}
.video-output {
width: 100%;
max-width: 720px;
height: auto;
margin: 0 auto;
}
.server-status {
margin-top: 20px;
background-color: white;
padding: 10px;
border-radius: 5px;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
font-size: 0.9em;
width: 100%;
}
.server-status h4 {
margin: 0 0 10px 0;
font-size: 1em;
font-weight: bold;
}
.server-status-details {
margin-top: 10px;
}
@media (max-width: 768px) {
.row {
flex-direction: column;
}
.column {
width: 100%;
}
.video-output {
width: 100%;
height: auto;
}
}
"""
with gr.Blocks(css=css) as demo:
gr.HTML("""
<div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
VideoSys Huggingface Space🤗
</div>
<div style="text-align: center; font-size: 15px;">
🌐 Github: <a href="https://github.com/NUS-HPC-AI-Lab/VideoSys">https://github.com/NUS-HPC-AI-Lab/VideoSys</a><br>
⚠️ This demo is for academic research and experiential use only.
Users should strictly adhere to local laws and ethics.<br>
💡 This demo only demonstrates single-device inference. To experience the full power of VideoSys, please deploy it with multiple devices.<br><br>
</div>
</div>
""")
with gr.Row():
with gr.Column():
prompt = gr.Textbox(label="Prompt (Less than 200 Words)", value="Sunset over the sea.", lines=5)
with gr.Row():
gr.Markdown(
"✨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."
)
enhance_button = gr.Button("✨ Enhance Prompt(Optional)")
with gr.Column():
gr.Markdown(
"**Optional Parameters** (default values are recommended)<br>"
"Turn Inference Steps larger if you want more detailed video, but it will be slower.<br>"
"50 steps are recommended for most cases. will cause 120 seconds for inference.<br>"
)
with gr.Row():
num_inference_steps = gr.Number(label="Inference Steps", value=50)
guidance_scale = gr.Number(label="Guidance Scale", value=6.0)
pab_gap = gr.Number(label="PAB Gap", value=2, precision=0)
pab_threshold = gr.Textbox(label="PAB Threshold", value="100,850", lines=1)
with gr.Row():
generate_button = gr.Button("🎬 Generate Video")
generate_button_vs = gr.Button("⚡️ Generate Video with VideoSys (Faster)")
with gr.Row(elem_classes="server-status"):
gr.Markdown("#### Server Status")
with gr.Row():
cpu_status = gr.Textbox(label="CPU", scale=1)
memory_status = gr.Textbox(label="Memory", scale=1)
disk_status = gr.Textbox(label="Disk", scale=1)
gpu_status = gr.Textbox(label="GPU Memory", scale=1)
refresh_button = gr.Button("Refresh", scale=1, size="sm")
with gr.Column():
with gr.Row():
video_output = gr.Video(label="CogVideoX", width=720, height=480)
with gr.Row():
download_video_button = gr.File(label="📥 Download Video", visible=False)
elapsed_time = gr.Textbox(label="Elapsed Time", value="0s", visible=False)
with gr.Row():
video_output_vs = gr.Video(label="CogVideoX with VideoSys", width=720, height=480)
with gr.Row():
download_video_button_vs = gr.File(label="📥 Download Video", visible=False)
elapsed_time_vs = gr.Textbox(label="Elapsed Time", value="0s", visible=False)
def generate_vanilla(prompt, num_inference_steps, guidance_scale, progress=gr.Progress(track_tqdm=True)):
engine = load_model()
t = time()
video_path = generate(engine, prompt, num_inference_steps, guidance_scale)
elapsed_time = time() - t
video_update = gr.update(visible=True, value=video_path)
elapsed_time = gr.update(visible=True, value=f"{elapsed_time:.2f}s")
return video_path, video_update, elapsed_time
def generate_vs(prompt, num_inference_steps, guidance_scale, threshold, gap, progress=gr.Progress(track_tqdm=True)):
threshold = [int(i) for i in threshold.split(",")]
gap = int(gap)
engine = load_model(enable_video_sys=True, pab_threshold=threshold, pab_gap=gap)
t = time()
video_path = generate(engine, prompt, num_inference_steps, guidance_scale)
elapsed_time = time() - t
video_update = gr.update(visible=True, value=video_path)
elapsed_time = gr.update(visible=True, value=f"{elapsed_time:.2f}s")
return video_path, video_update, elapsed_time
def enhance_prompt_func(prompt):
return convert_prompt(prompt, retry_times=1)
def get_server_status():
cpu_percent = psutil.cpu_percent()
memory = psutil.virtual_memory()
disk = psutil.disk_usage('/')
try:
gpus = GPUtil.getGPUs()
if gpus:
gpu = gpus[0] # 只获取第一个GPU的信息
gpu_memory = f"{gpu.memoryUsed}/{gpu.memoryTotal}MB ({gpu.memoryUtil*100:.1f}%)"
else:
gpu_memory = "No GPU found"
except:
gpu_memory = "GPU information unavailable"
return {
'cpu': f"{cpu_percent}%",
'memory': f"{memory.percent}%",
'disk': f"{disk.percent}%",
'gpu_memory': gpu_memory
}
def update_server_status():
status = get_server_status()
return (
status['cpu'],
status['memory'],
status['disk'],
status['gpu_memory']
)
def queue_task(func, args, callback):
task = {'function': func, 'args': args, 'callback': callback}
task_queue.put(task)
def on_generate_button_click(prompt, num_inference_steps, guidance_scale):
queue_task(generate_vanilla, (prompt, num_inference_steps, guidance_scale), lambda result: gr.update(*result))
def on_generate_button_vs_click(prompt, num_inference_steps, guidance_scale, threshold, gap):
queue_task(generate_vs, (prompt, num_inference_steps, guidance_scale, threshold, gap), lambda result: gr.update(*result))
generate_button.click(
on_generate_button_click,
inputs=[prompt, num_inference_steps, guidance_scale],
outputs=[video_output, download_video_button, elapsed_time],
)
generate_button_vs.click(
on_generate_button_vs_click,
inputs=[prompt, num_inference_steps, guidance_scale, pab_threshold, pab_gap],
outputs=[video_output_vs, download_video_button_vs, elapsed_time_vs],
)
enhance_button.click(enhance_prompt_func, inputs=[prompt], outputs=[prompt])
refresh_button.click(update_server_status, outputs=[cpu_status, memory_status, disk_status, gpu_status])
demo.load(update_server_status, outputs=[cpu_status, memory_status, disk_status, gpu_status], every=1)
if __name__ == "__main__":
demo.queue(max_size=10, default_concurrency_limit=1)
demo.launch() |