# CUDA_VISIBLE_DEVICES=7 python app.py import gradio as gr import os import random from datetime import datetime import string import json import theme from openai import OpenAI import logging from argparse import ArgumentParser from datetime import datetime from fractions import Fraction from pathlib import Path # 设置环境变量 os.environ["no_proxy"] = "localhost,127.0.0.1,::1" # 设置参数 style = theme.Style() zhipu_api_key = "xxx" # 润色prompt def convert_prompt(prompt, retry_times=3): client = OpenAI( api_key=zhipu_api_key, base_url="https://open.bigmodel.cn/api/paas/v4/" ) text = prompt.strip() sys_prompt_en = """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. """ for i in range(retry_times): response = client.chat.completions.create( messages=[ {"role": "system", "content": sys_prompt_en}, { "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-flash", temperature=0.01, top_p=0.7, stream=False, max_tokens=512, ) if response.choices: return response.choices[0].message.content return prompt def convert_prompt_zh(prompt, retry_times=3): client = OpenAI( api_key=zhipu_api_key, base_url="https://open.bigmodel.cn/api/paas/v4/" ) text = prompt.strip() sys_prompt_zh = """你是一个制作视频的机器人团队的一员。你与一个辅助机器人协同工作,辅助机器人会根据你方括号内所述内容绘制出相应画面。 例如,输出“树林中美好的清晨,阳光透过树木洒下”,就会触发你的伙伴机器人输出一段如描述那般的森林清晨视频。寻求制作详细、精彩视频的人们会向你发出提示信息。要达成这一目标,需将他们简短的提示内容变得极为详细且富有描述性。 有几条规则需要遵循: 针对每个用户请求,你每次只输出一个视频描述。 当被要求进行修改时,你不应只是简单地把描述内容加长。而应该重新构建整个描述内容,将建议融入其中。 其他时候,用户可能不想要修改内容,而是想要一个新画面。在这种情况下,你应该忽略之前与该用户的对话内容。 视频描述的字数必须与以下示例的字数相同。多余的字数将被忽略。 """ for i in range(retry_times): response = client.chat.completions.create( messages=[ {"role": "system", "content": sys_prompt_zh}, { "role": "user", "content": '为用户输入的“一个女孩在海滩上”创建一个富有想象力的视频描述性字幕,或修改之前的字幕', }, { "role": "assistant", "content": "一位容光焕发的女子站在人迹罕至的海滩上,双臂张开,身着米色风衣、白色衬衫、浅蓝色牛仔裤和别致的靴子,身后是柔和的天空与大海。片刻之后,只见她欢快地旋转着,双臂舒展,此时的光线表明正值黎明或黄昏。接着,她沿着海滩奔跑,一身装扮搭配着米白色围巾和黑色短靴,身后是平静的大海。最后,她手持一架纸飞机,姿态中洋溢着喜悦与自由,大海的轻柔海浪和天空柔和的淡色调更添宁静氛围。", }, { "role": "user", "content": '为用户输入的“一个男人在足球场上慢跑”创建一个富有想象力的视频描述性字幕,或修改之前的字幕', }, { "role": "assistant", "content": "一个神情坚定的男人身着运动装,包括一件蓝色长袖衬衫、黑色短裤和蓝色袜子,在积雪覆盖的足球场上慢跑,在静谧、阴天的环境中独自锻炼。他那长长的脏辫、专注的神情,与宁静的冬日背景相互映衬,彰显出他对健身的执着。他跑动时,身上的蓝色运动卫衣、黑色运动裤、手套和运动鞋紧紧抓着雪地。可以看到他跑过围着操场区域的铁丝网,那里有一个篮球架和儿童滑梯,仿佛是在空旷的场地上独自锻炼的片刻时光。", }, { "role": "user", "content": '为用户输入的“一个女人正在跳舞,高清镜头,特写”创建一个富有想象力的视频描述性字幕,或修改之前的字幕', }, { "role": "assistant", "content": "一位梳着发髻、身着蓝绿色连帽衫的年轻女子站在浅色背景前,起初带着若有所思的神情扭头回望。接着,她自信地微微舞动,展现出韵律与动感。随后,她仪态优雅、神情专注,直视镜头。她的目光微微向下,神情转为内省。最后,她充满自信地翩翩起舞,左手放在心口,营造出动人的时刻,自始至终,她都身着那件蓝绿色连帽衫,身后是素净的浅色背景。", }, { "role": "user", "content": f'为用户输入的“{text}”用中文创建一个富有想象力的视频描述性字幕,或修改之前的字幕', }, ], model="glm-4-flash", temperature=0.01, top_p=0.7, stream=False, max_tokens=512, ) if response.choices: return response.choices[0].message.content return prompt def positive_prompt(prompt, retry_times=3): client = OpenAI( api_key=zhipu_api_key, base_url="https://open.bigmodel.cn/api/paas/v4/" ) text = prompt.strip() sys_prompt = """You are an expert in extracting key information from video subtitles, capable of identifying crucial entities within a video based on the input scene descriptions. Here are some examples to demonstrate this capability. Do not list in a bullet point format. """ for i in range(retry_times): response = client.chat.completions.create( messages=[ {"role": "system", "content": sys_prompt}, { "role": "user", "content": 'Extract key entities from the user input "a girl on the beach", with the number of entities between 2 to 5.', }, { "role": "assistant", "content": "gril, beach", }, { "role": "user", "content": 'Extract key entities from the user input " A woman is dancing, HD footage, close-up", with the number of entities between 2 to 5.', }, { "role": "assistant", "content": "young woman, dancing", }, { "role": "user", "content": 'Extract key entities from the user input “A man is jogging on the soccer field.”, with the number of entities between 2 to 5.', }, { "role": "assistant", "content": "man, jogging, soccer field", }, { "role": "user", "content": f'Extract key entities from the user input “{text}”, with the number of entities between 2 to 5.', }, ], model="glm-4-flash", temperature=0.01, top_p=0.7, stream=False, max_tokens=512, ) if response.choices: return response.choices[0].message.content return prompt def toggle_audio_options(enable_audio): return gr.update(visible=enable_audio) def toggle_speech_options(enable_speech): return gr.update(visible=enable_speech) with gr.Blocks(theme=style, title="Medical Sora Demo Space") as battle_page: # gr.Markdown(""" #
# Medical Sora Demo Space🤗 #
#
# 📜 arxiv | # 🤗 Model Hub | # 🌐 Github | # 📦 Dataset #
#
# ⚠️ This demo is for academic research and experiential use only. #
# """) # title_markdown = """ # ## 📃How to use it? #
#
# #
#
# """ # gr.Markdown(title_markdown) with gr.Row(): with gr.Column(): prompt = gr.Textbox(label="Prompt", placeholder="Enter your prompt here", lines=5) with gr.Row(): gr.Markdown( "✨Upon pressing the enhanced prompt button, we will use `GLM-4-Flash` model to polish the prompt and overwrite the original one.", ) enhance_button = gr.Button("✨ Enhance EN Prompt (Optional)", scale=1) enhance_button_zh = gr.Button("✨ Enhance ZH Prompt (Optional)", scale=1) with gr.Row(): hunyuan_video_seed = gr.Number(value=42, label="Seed") hunyuan_video_height = gr.Number(value=320, label="Height") hunyuan_video_width = gr.Number(value=512, label="Width") with gr.Row(): hunyuan_video_num_frames = gr.Number(value=61, label="Num Frames") hunyuan_video_num_inference_steps = gr.Number(value=6, label="Num Inference Steps") hunyuan_video_fps = gr.Number(value=15, label="FPS") with gr.Accordion("Add Synchronized Audio", open=False): enable_audio = gr.Checkbox(label="Add Synchronized Audio", value=False) with gr.Column(visible=False) as audio_options: with gr.Row(): mmaudio_positive_prompt = gr.Text(label='Positive prompt', placeholder="To help generate more accurate synchronized audio, optional.", value='', scale=2) gen_positive_button = gr.Button("✨ Generate Positive Prompt(Optional)", scale=1) mmaudio_negative_prompt = gr.Text(label='Negative prompt', placeholder="To help generate more accurate synchronized audio, optional.", value='') mmaudio_seed = gr.Slider(label='Seed', value=0, minimum=-1) mmaudio_num_steps = gr.Slider(label='Num steps', value=25, minimum=1) mmaudio_guidance_strength = gr.Slider(label='Guidance Strength', value=4.5, minimum=1) mmaudio_duration = gr.Slider(label='Duration (sec)', value=8, minimum=1) with gr.Accordion("Add Speech Synthesis", open=False): enable_speech = gr.Checkbox(label="Add Speech Synthesis", value=False) with gr.Column(visible=False) as speech_options: cosyvoice2_refer_audio = gr.Audio(sources='upload', type='filepath', label='Speech Reference', value="/sds_wangby/models/cjy/wrs/gradio/CosyVoice/zero_shot_prompt.wav") cosyvoice2_language = gr.Dropdown(["en", "zh"], label="Language") generate_button = gr.Button("🎬 Generate Video") with gr.Column(): # status_text = gr.Textbox(label="Runing Status", interactive=False, show_label=True) video_output = gr.Video(label="Medical Sora Generate Video", width=720, height=480, autoplay=True, loop=True) with gr.Row(): download_video_button = gr.File(label="📥 Download Video", visible=False) with gr.Accordion("🎥 Expand to see video gallery", open=False): gr.Markdown("""

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.

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.

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.

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.

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.

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.

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.

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.

""") gr.Markdown(""" ## 🔔Terms of service Users are required to agree to the following terms before using the service: The service is a research preview. It only provides limited safety measures and may generate offensive content. ## 📬Connect with us If you have any questions, please feel free to contact us. Our email is name@email.com . """) def all_generate( prompt, enable_audio, enable_speech, hunyuan_video_seed, hunyuan_video_height, hunyuan_video_width, hunyuan_video_num_frames, hunyuan_video_num_inference_steps, hunyuan_video_fps, mmaudio_positive_prompt, mmaudio_negative_prompt, mmaudio_seed, mmaudio_num_steps, mmaudio_guidance_strength, mmaudio_duration, cosyvoice2_refer_audio, cosyvoice2_language ): gen_video_path = fastvideo_infer( prompt, hunyuan_video_seed, hunyuan_video_height, hunyuan_video_width, hunyuan_video_num_frames, hunyuan_video_num_inference_steps, hunyuan_video_fps ) if enable_audio: # mmaudio_infer(video, prompt, negative_prompt, seed, num_steps, cfg_strength, duration) gen_video_path = mmaudio_infer( gen_video_path, mmaudio_positive_prompt, mmaudio_negative_prompt, mmaudio_seed, mmaudio_num_steps, mmaudio_guidance_strength, mmaudio_duration ) if enable_speech: # refer_audio, prompt_audio, language, subtitle gen_video_path = cosyvoice2_infer( cosyvoice2_refer_audio, prompt, cosyvoice2_language, cosyvoice2_subtitle ) video_update = gr.update(visible=True, value=gen_video_path) return gen_video_path, video_update def enhance_prompt_func(prompt): return convert_prompt(prompt, retry_times=1) def enhance_prompt_zh_func(prompt): return convert_prompt_zh(prompt, retry_times=1) def gen_pos_prompt_func(prompt): return positive_prompt(prompt, retry_times=1) generate_button.click( all_generate, inputs=[ prompt, enable_audio, enable_speech, hunyuan_video_seed, hunyuan_video_height, hunyuan_video_width, hunyuan_video_num_frames, hunyuan_video_num_inference_steps, hunyuan_video_fps, mmaudio_positive_prompt, mmaudio_negative_prompt, mmaudio_seed, mmaudio_num_steps, mmaudio_guidance_strength, mmaudio_duration, cosyvoice2_refer_audio, cosyvoice2_language ], outputs=[video_output, download_video_button], ) enhance_button.click(enhance_prompt_func, inputs=[prompt], outputs=[prompt]) enhance_button_zh.click(enhance_prompt_zh_func, inputs=[prompt], outputs=[prompt]) gen_positive_button.click(gen_pos_prompt_func, inputs=[prompt], outputs=[mmaudio_positive_prompt]) enable_audio.change(fn=toggle_audio_options, inputs=[enable_audio], outputs=[audio_options]) enable_speech.change(fn=toggle_speech_options, inputs=[enable_speech], outputs=[speech_options]) battle_page.queue().launch(enable_monitoring=True, ) # favicon_path="assets/images/favicons/favicon-64x64.png"