wangrongsheng commited on
Commit
60e8c86
·
verified ·
1 Parent(s): 66d7075

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +212 -30
app.py CHANGED
@@ -6,19 +6,201 @@ from datetime import datetime
6
  import string
7
  import json
8
  import theme
 
9
  import logging
10
  from argparse import ArgumentParser
11
  from datetime import datetime
12
  from fractions import Fraction
13
  from pathlib import Path
14
 
15
- # os.system("pip install gradio==4.44.1")
16
-
17
  # 设置环境变量
18
  os.environ["no_proxy"] = "localhost,127.0.0.1,::1"
19
 
20
  # 设置参数
21
  style = theme.Style()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
  def toggle_audio_options(enable_audio):
24
  return gr.update(visible=enable_audio)
@@ -26,36 +208,35 @@ def toggle_audio_options(enable_audio):
26
  def toggle_speech_options(enable_speech):
27
  return gr.update(visible=enable_speech)
28
 
29
- with gr.Blocks(theme=style) as battle_page:
30
- # gr.Markdown("""
31
- # <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
32
- # Medical Sora Demo Space🤗
33
- # </div>
34
- # <div style="text-align: center;">
35
- # <a href="">📜 arxiv </a> |
36
- # <a href="">🤗 Model Hub</a> |
37
- # <a href="">🌐 Github</a> |
38
- # <a href="">📦 Dataset</a>
39
- # </div>
40
- # <div style="text-align: center; font-size: 15px; font-weight: bold; color: red; margin-bottom: 20px;">
41
- # ⚠️ This demo is for academic research and experiential use only.
42
- # </div>
43
- # """)
44
 
45
  title_markdown = """
46
  ## 📃How to use it?
47
-
48
  <div style="display: flex; justify-content: left; align-items: flex-start; text-align: left; background: linear-gradient(45deg, rgba(220,220,220, 1), rgba(255,255,255, 1)); border-radius: 10px; box-shadow: 0 8px 16px 0 rgba(0,0,0,0.1); padding: 20px;">
49
  <div>
50
  <ul>
51
  <p style="color: black; font-weight: bold; margin-top: 10px;">
52
- <li>Inter your prompt and adjust the parameters for generating the video.</li>
53
  </p>
54
  <p style="color: black; font-weight: bold; margin-bottom: 0;">
55
- <li>Click <strong>"Add Synchronized Audio"</strong> to add background sound to the generated video.</li>
56
  </p>
57
  <p style="color: black; font-weight: bold; margin-bottom: 0;">
58
- <li>Click <strong>"Add Speech Synthesis"</strong> to add spoken language descriptions to the generated video.</li>
59
  </p>
60
  </ul>
61
  </div>
@@ -73,6 +254,7 @@ with gr.Blocks(theme=style) as battle_page:
73
  enhance_button = gr.Button("✨ Enhance EN Prompt (Optional)", scale=1)
74
  enhance_button_zh = gr.Button("✨ Enhance ZH Prompt (Optional)", scale=1)
75
  with gr.Row():
 
76
  hunyuan_video_height = gr.Number(value=320, label="Height")
77
  hunyuan_video_width = gr.Number(value=512, label="Width")
78
  with gr.Row():
@@ -94,13 +276,12 @@ with gr.Blocks(theme=style) as battle_page:
94
  enable_speech = gr.Checkbox(label="Add Speech Synthesis", value=False)
95
  with gr.Column(visible=False) as speech_options:
96
  cosyvoice2_refer_audio = gr.Audio(sources='upload', type='filepath', label='Speech Reference', value="/sds_wangby/models/cjy/wrs/gradio/CosyVoice/zero_shot_prompt.wav")
97
- cosyvoice2_language = gr.Dropdown(["EN", "ZH"], label="Language")
98
- with gr.Column():
99
- cosyvoice2_subtitle = gr.Checkbox(label="Add the speech content to the video subtitles", value=False)
100
 
101
  generate_button = gr.Button("🎬 Generate Video")
102
 
103
  with gr.Column():
 
104
  video_output = gr.Video(label="Medical Sora Generate Video", width=720, height=480, autoplay=True, loop=True)
105
  with gr.Row():
106
  download_video_button = gr.File(label="📥 Download Video", visible=False)
@@ -181,6 +362,7 @@ with gr.Blocks(theme=style) as battle_page:
181
  prompt,
182
  enable_audio,
183
  enable_speech,
 
184
  hunyuan_video_height,
185
  hunyuan_video_width,
186
  hunyuan_video_num_frames,
@@ -193,11 +375,11 @@ with gr.Blocks(theme=style) as battle_page:
193
  mmaudio_guidance_strength,
194
  mmaudio_duration,
195
  cosyvoice2_refer_audio,
196
- cosyvoice2_language,
197
- cosyvoice2_subtitle
198
  ):
199
  gen_video_path = fastvideo_infer(
200
  prompt,
 
201
  hunyuan_video_height,
202
  hunyuan_video_width,
203
  hunyuan_video_num_frames,
@@ -243,7 +425,8 @@ with gr.Blocks(theme=style) as battle_page:
243
  inputs=[
244
  prompt,
245
  enable_audio,
246
- enable_speech,
 
247
  hunyuan_video_height,
248
  hunyuan_video_width,
249
  hunyuan_video_num_frames,
@@ -256,8 +439,7 @@ with gr.Blocks(theme=style) as battle_page:
256
  mmaudio_guidance_strength,
257
  mmaudio_duration,
258
  cosyvoice2_refer_audio,
259
- cosyvoice2_language,
260
- cosyvoice2_subtitle
261
  ],
262
  outputs=[video_output, download_video_button],
263
  )
@@ -270,4 +452,4 @@ with gr.Blocks(theme=style) as battle_page:
270
  enable_audio.change(fn=toggle_audio_options, inputs=[enable_audio], outputs=[audio_options])
271
  enable_speech.change(fn=toggle_speech_options, inputs=[enable_speech], outputs=[speech_options])
272
 
273
- battle_page.queue().launch(enable_monitoring=True)
 
6
  import string
7
  import json
8
  import theme
9
+ from openai import OpenAI
10
  import logging
11
  from argparse import ArgumentParser
12
  from datetime import datetime
13
  from fractions import Fraction
14
  from pathlib import Path
15
 
 
 
16
  # 设置环境变量
17
  os.environ["no_proxy"] = "localhost,127.0.0.1,::1"
18
 
19
  # 设置参数
20
  style = theme.Style()
21
+ zhipu_api_key = "xxx"
22
+
23
+ # 润色prompt
24
+ def convert_prompt(prompt, retry_times=3):
25
+ client = OpenAI(
26
+ api_key=zhipu_api_key,
27
+ base_url="https://open.bigmodel.cn/api/paas/v4/"
28
+ )
29
+ text = prompt.strip()
30
+
31
+ 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.
32
+
33
+ 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.
34
+
35
+ There are a few rules to follow:
36
+
37
+ You will only ever output a single video description per user request.
38
+
39
+ When modifications are requested , you should not simply make the description longer . You should refactor the entire description to integrate the suggestions.
40
+ 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.
41
+ Video descriptions must have the same num of words as examples below. Extra words will be ignored.
42
+ """
43
+
44
+ for i in range(retry_times):
45
+ response = client.chat.completions.create(
46
+ messages=[
47
+ {"role": "system", "content": sys_prompt_en},
48
+ {
49
+ "role": "user",
50
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "a girl is on the beach"',
51
+ },
52
+ {
53
+ "role": "assistant",
54
+ "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.",
55
+ },
56
+ {
57
+ "role": "user",
58
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "A man jogging on a football field"',
59
+ },
60
+ {
61
+ "role": "assistant",
62
+ "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.",
63
+ },
64
+ {
65
+ "role": "user",
66
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : " A woman is dancing, HD footage, close-up"',
67
+ },
68
+ {
69
+ "role": "assistant",
70
+ "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.",
71
+ },
72
+ {
73
+ "role": "user",
74
+ "content": f'Create an imaginative video descriptive caption or modify an earlier caption in ENGLISH for the user input: "{text}"',
75
+ },
76
+ ],
77
+ model="glm-4-flash",
78
+ temperature=0.01,
79
+ top_p=0.7,
80
+ stream=False,
81
+ max_tokens=512,
82
+ )
83
+ if response.choices:
84
+ return response.choices[0].message.content
85
+ return prompt
86
+
87
+ def convert_prompt_zh(prompt, retry_times=3):
88
+ client = OpenAI(
89
+ api_key=zhipu_api_key,
90
+ base_url="https://open.bigmodel.cn/api/paas/v4/"
91
+ )
92
+ text = prompt.strip()
93
+ sys_prompt_zh = """你是一个制作视频的机器人团队的一员。你与一个辅助机器人协同工作,辅助机器人会根据你方括号内所述内容绘制出相应画面。
94
+
95
+ 例如,输出“树林中美好的清晨,阳光透过树木洒下”,就会触发你的伙伴机器人输出一段如描述那般的森林清晨视频。寻求制作详细、精彩视频的人们会向你发出提示信息。要达成这一目标,需将他们简短的提示内容变得极为详细且富有描述性。
96
+
97
+ 有几条规则需要遵循:
98
+
99
+ 针对每个用户请求,你每次只输出一个视频描述。
100
+
101
+ 当被要求进行修改时,你不应只是简单地把描述内容加长。而应该重新构建整个描述内容,将建议融入其中。
102
+
103
+ 其他时候,用户可能不想要修改内容,而是想要一个新画面。在这种情况下,你应该忽略之前与该用户的对话内容。
104
+
105
+ 视频描述的字数必须与以下示例的字数相同。多余的字数将被忽略。
106
+ """
107
+
108
+ for i in range(retry_times):
109
+ response = client.chat.completions.create(
110
+ messages=[
111
+ {"role": "system", "content": sys_prompt_zh},
112
+ {
113
+ "role": "user",
114
+ "content": '为用户输入的“一个女孩在海滩上”创建一个富有想象力的视频描述性字幕,或修改之前的字幕',
115
+ },
116
+ {
117
+ "role": "assistant",
118
+ "content": "一位容光焕发的女子站在人迹罕至的海滩上,双臂张开,身着米色风衣、白色衬衫、浅蓝色牛仔裤和别致的靴子,身后是柔和的天空与大海。片刻之后,只见她欢快地旋转着,双臂舒展,此时的光线表明正值黎明或黄昏。接着,她沿着海滩奔跑,一身装扮搭配着米白色围巾和黑色短靴,身后是平静的大海。最后,她手持一架纸飞机,姿态中洋溢着喜悦与自由,大海的轻柔海浪和天空柔和的淡色调更添宁静氛围。",
119
+ },
120
+ {
121
+ "role": "user",
122
+ "content": '为用户输入的“一个男人在足球场上慢跑”创建一个富有想象力的视频描述性字幕,或修改之前的字幕',
123
+ },
124
+ {
125
+ "role": "assistant",
126
+ "content": "一个神情坚定的男人身着运动装,包括一件蓝色长袖衬衫、黑色短裤和蓝色袜子,在积雪覆盖的足球场上慢跑,在静谧、阴天的环境中独自锻炼。他那长长的脏辫、专注的神情,与宁静的冬日背景相互映衬,彰显出他对健身的执着。他跑动时,身上的蓝色运动卫衣、黑色运动裤、手套和运动鞋紧紧抓着雪地。可以看到他跑过围着操场区域的铁丝网,那里有一个篮球架和儿童滑梯,仿佛是在空旷的场地上独自锻炼的片刻时光。",
127
+ },
128
+ {
129
+ "role": "user",
130
+ "content": '为用户输入的“一个女人正在跳舞,高清镜头,特写”创建一个富有想象力的视频描述性字幕,或修改之前的字幕',
131
+ },
132
+ {
133
+ "role": "assistant",
134
+ "content": "一位梳着发髻、身着蓝绿色连帽衫的年轻女子站在浅色背景前,起初带着若有所思的神情扭头回望。接着,她自信地微微舞动,展现出韵律与动感。随后,她仪态优雅、神情专注,直视镜头。她的目光微微向下,神情转为内省。最后,她充满自信地翩翩起舞,左手放在心口,营造出动人的时刻,自始至终,她都身着那件蓝绿色连帽衫,身后是素净的浅色背景。",
135
+ },
136
+ {
137
+ "role": "user",
138
+ "content": f'为用户输入的“{text}”用中文创建一个富有想象力的视频描述性字幕,或修改之前的字幕',
139
+ },
140
+ ],
141
+ model="glm-4-flash",
142
+ temperature=0.01,
143
+ top_p=0.7,
144
+ stream=False,
145
+ max_tokens=512,
146
+ )
147
+ if response.choices:
148
+ return response.choices[0].message.content
149
+ return prompt
150
+
151
+ def positive_prompt(prompt, retry_times=3):
152
+ client = OpenAI(
153
+ api_key=zhipu_api_key,
154
+ base_url="https://open.bigmodel.cn/api/paas/v4/"
155
+ )
156
+ text = prompt.strip()
157
+ 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.
158
+
159
+ Do not list in a bullet point format.
160
+ """
161
+
162
+ for i in range(retry_times):
163
+ response = client.chat.completions.create(
164
+ messages=[
165
+ {"role": "system", "content": sys_prompt},
166
+ {
167
+ "role": "user",
168
+ "content": 'Extract key entities from the user input "a girl on the beach", with the number of entities between 2 to 5.',
169
+ },
170
+ {
171
+ "role": "assistant",
172
+ "content": "gril, beach",
173
+ },
174
+ {
175
+ "role": "user",
176
+ "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.',
177
+ },
178
+ {
179
+ "role": "assistant",
180
+ "content": "young woman, dancing",
181
+ },
182
+ {
183
+ "role": "user",
184
+ "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.',
185
+ },
186
+ {
187
+ "role": "assistant",
188
+ "content": "man, jogging, soccer field",
189
+ },
190
+ {
191
+ "role": "user",
192
+ "content": f'Extract key entities from the user input “{text}”, with the number of entities between 2 to 5.',
193
+ },
194
+ ],
195
+ model="glm-4-flash",
196
+ temperature=0.01,
197
+ top_p=0.7,
198
+ stream=False,
199
+ max_tokens=512,
200
+ )
201
+ if response.choices:
202
+ return response.choices[0].message.content
203
+ return prompt
204
 
205
  def toggle_audio_options(enable_audio):
206
  return gr.update(visible=enable_audio)
 
208
  def toggle_speech_options(enable_speech):
209
  return gr.update(visible=enable_speech)
210
 
211
+ with gr.Blocks(theme=style, title="Medical Sora Demo Space") as battle_page:
212
+ gr.Markdown("""
213
+ <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
214
+ Medical Sora Demo Space🤗
215
+ </div>
216
+ <div style="text-align: center;">
217
+ <a href="">📜 arxiv </a> |
218
+ <a href="">🤗 Model Hub</a> |
219
+ <a href="">🌐 Github</a> |
220
+ <a href="">📦 Dataset</a>
221
+ </div>
222
+ <div style="text-align: center; font-size: 15px; font-weight: bold; color: red; margin-bottom: 20px;">
223
+ ⚠️ This demo is for academic research and experiential use only.
224
+ </div>
225
+ """)
226
 
227
  title_markdown = """
228
  ## 📃How to use it?
 
229
  <div style="display: flex; justify-content: left; align-items: flex-start; text-align: left; background: linear-gradient(45deg, rgba(220,220,220, 1), rgba(255,255,255, 1)); border-radius: 10px; box-shadow: 0 8px 16px 0 rgba(0,0,0,0.1); padding: 20px;">
230
  <div>
231
  <ul>
232
  <p style="color: black; font-weight: bold; margin-top: 10px;">
233
+ <li>Input your prompt and adjust the parameters for generating the video.</li>
234
  </p>
235
  <p style="color: black; font-weight: bold; margin-bottom: 0;">
236
+ <li>Click <strong>"Add Synchronized Audio"</strong> to add background sound to the generated video. (Optional) </li>
237
  </p>
238
  <p style="color: black; font-weight: bold; margin-bottom: 0;">
239
+ <li>Click <strong>"Add Speech Synthesis"</strong> to add spoken language descriptions to the generated video. (Optional) </li>
240
  </p>
241
  </ul>
242
  </div>
 
254
  enhance_button = gr.Button("✨ Enhance EN Prompt (Optional)", scale=1)
255
  enhance_button_zh = gr.Button("✨ Enhance ZH Prompt (Optional)", scale=1)
256
  with gr.Row():
257
+ hunyuan_video_seed = gr.Number(value=42, label="Seed")
258
  hunyuan_video_height = gr.Number(value=320, label="Height")
259
  hunyuan_video_width = gr.Number(value=512, label="Width")
260
  with gr.Row():
 
276
  enable_speech = gr.Checkbox(label="Add Speech Synthesis", value=False)
277
  with gr.Column(visible=False) as speech_options:
278
  cosyvoice2_refer_audio = gr.Audio(sources='upload', type='filepath', label='Speech Reference', value="/sds_wangby/models/cjy/wrs/gradio/CosyVoice/zero_shot_prompt.wav")
279
+ cosyvoice2_language = gr.Dropdown(["en", "zh"], label="Language")
 
 
280
 
281
  generate_button = gr.Button("🎬 Generate Video")
282
 
283
  with gr.Column():
284
+ # status_text = gr.Textbox(label="Runing Status", interactive=False, show_label=True)
285
  video_output = gr.Video(label="Medical Sora Generate Video", width=720, height=480, autoplay=True, loop=True)
286
  with gr.Row():
287
  download_video_button = gr.File(label="📥 Download Video", visible=False)
 
362
  prompt,
363
  enable_audio,
364
  enable_speech,
365
+ hunyuan_video_seed,
366
  hunyuan_video_height,
367
  hunyuan_video_width,
368
  hunyuan_video_num_frames,
 
375
  mmaudio_guidance_strength,
376
  mmaudio_duration,
377
  cosyvoice2_refer_audio,
378
+ cosyvoice2_language
 
379
  ):
380
  gen_video_path = fastvideo_infer(
381
  prompt,
382
+ hunyuan_video_seed,
383
  hunyuan_video_height,
384
  hunyuan_video_width,
385
  hunyuan_video_num_frames,
 
425
  inputs=[
426
  prompt,
427
  enable_audio,
428
+ enable_speech,
429
+ hunyuan_video_seed,
430
  hunyuan_video_height,
431
  hunyuan_video_width,
432
  hunyuan_video_num_frames,
 
439
  mmaudio_guidance_strength,
440
  mmaudio_duration,
441
  cosyvoice2_refer_audio,
442
+ cosyvoice2_language
 
443
  ],
444
  outputs=[video_output, download_video_button],
445
  )
 
452
  enable_audio.change(fn=toggle_audio_options, inputs=[enable_audio], outputs=[audio_options])
453
  enable_speech.change(fn=toggle_speech_options, inputs=[enable_speech], outputs=[speech_options])
454
 
455
+ battle_page.queue().launch(enable_monitoring=True, ) # favicon_path="assets/images/favicons/favicon-64x64.png"