cpuai commited on
Commit
d0a9eb9
·
verified ·
1 Parent(s): cf02bea

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +196 -120
app.py CHANGED
@@ -1,40 +1,48 @@
1
  # coding: utf-8
2
 
3
  """
4
- The entrance of the gradio
 
 
 
 
5
  """
6
 
7
- import tyro
8
- import gradio as gr
9
  import os.path as osp
 
 
 
10
  import torch
 
11
  from gradio_client import utils as gradio_client_utils
12
- from src.utils.helper import load_description
13
- from src.gradio_pipeline import GradioPipeline
14
- from src.config.crop_config import CropConfig
15
  from src.config.argument_config import ArgumentConfig
 
16
  from src.config.inference_config import InferenceConfig
17
- import cv2
 
18
 
19
  try:
20
  import spaces
21
  except ImportError:
22
  spaces = None
23
 
24
- # import gdown
25
- # folder_url = f"https://drive.google.com/drive/folders/1UtKgzKjFAOmZkhNK-OYT0caJ_w2XAnib"
26
- # gdown.download_folder(url=folder_url, output="pretrained_weights", quiet=False)
27
 
28
  def partial_fields(target_class, kwargs):
 
 
 
29
  return target_class(**{k: v for k, v in kwargs.items() if hasattr(target_class, k)})
30
 
31
- # set tyro theme
 
32
  tyro.extras.set_accent_color("bright_cyan")
33
  args = tyro.cli(ArgumentConfig)
34
 
35
- # specify configs for inference
36
- inference_cfg = partial_fields(InferenceConfig, args.__dict__) # use attribute of args to initial InferenceConfig
37
- crop_cfg = partial_fields(CropConfig, args.__dict__) # use attribute of args to initial CropConfig
38
 
39
  gradio_pipeline = GradioPipeline(
40
  inference_cfg=inference_cfg,
@@ -42,12 +50,18 @@ gradio_pipeline = GradioPipeline(
42
  args=args
43
  )
44
 
 
45
  def maybe_gpu(fn):
 
 
 
 
46
  if spaces is not None and torch.cuda.is_available():
47
  return spaces.GPU(fn)
48
  return fn
49
 
50
 
 
51
  _original_json_schema_to_python_type = gradio_client_utils._json_schema_to_python_type
52
 
53
 
@@ -59,66 +73,168 @@ def _patched_json_schema_to_python_type(schema, defs):
59
 
60
  gradio_client_utils._json_schema_to_python_type = _patched_json_schema_to_python_type
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  @maybe_gpu
63
- def gpu_wrapped_execute_video(
64
- input_image_path,
65
- input_video_path,
66
- flag_relative_input,
67
- flag_do_crop_input,
68
- flag_remap_input,
69
  ):
70
- return gradio_pipeline.execute_video(
71
- input_image_path,
72
- input_video_path,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  flag_relative_input,
74
  flag_do_crop_input,
75
  flag_remap_input,
76
  )
77
 
78
- @maybe_gpu
79
- def gpu_wrapped_execute_image(input_eye_ratio: float, input_lip_ratio: float):
80
- return gradio_pipeline.execute_image(input_eye_ratio, input_lip_ratio)
 
 
 
 
 
 
 
 
 
 
 
81
 
82
- def is_square_video(video_path):
83
  video = cv2.VideoCapture(video_path)
84
-
85
  width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
86
  height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
87
-
88
  video.release()
 
89
  if width != height:
90
  raise gr.Error("Error: the video does not have a square aspect ratio. We currently only support square videos")
91
-
92
  return gr.update(visible=True)
93
 
94
- # assets
 
95
  title_md = "assets/gradio_title.md"
96
  example_portrait_dir = "assets/examples/source"
97
  example_video_dir = "assets/examples/driving"
 
 
98
  data_examples = [
99
- [osp.join(example_portrait_dir, "s9.jpg"), osp.join(example_video_dir, "d0.mp4"), True, True, True],
100
- [osp.join(example_portrait_dir, "s6.jpg"), osp.join(example_video_dir, "d0.mp4"), True, True, True],
101
- [osp.join(example_portrait_dir, "s10.jpg"), osp.join(example_video_dir, "d5.mp4"), True, True, True],
102
- [osp.join(example_portrait_dir, "s5.jpg"), osp.join(example_video_dir, "d6.mp4"), True, True, True],
103
- [osp.join(example_portrait_dir, "s7.jpg"), osp.join(example_video_dir, "d7.mp4"), True, True, True],
104
  ]
105
- #################### interface logic ####################
106
-
107
- # Define components first
108
- eye_retargeting_slider = gr.Slider(minimum=0, maximum=0.8, step=0.01, label="target eyes-open ratio")
109
- lip_retargeting_slider = gr.Slider(minimum=0, maximum=0.8, step=0.01, label="target lip-open ratio")
110
- retargeting_input_image = gr.Image(type="numpy")
111
- output_image = gr.Image(type="numpy")
112
- output_image_paste_back = gr.Image(type="numpy")
113
- output_video = gr.Video()
114
- output_video_concat = gr.Video()
115
-
116
- with gr.Blocks(theme=gr.themes.Soft(),title="LivePortrait: Revolutionary AI-Powered Portrait Animation Technology") as demo:
117
  gr.HTML(load_description(title_md))
118
- gr.Markdown(load_description("assets/gradio_description_upload.md"))
 
 
 
 
 
 
 
 
119
  with gr.Row():
120
  with gr.Accordion(open=True, label="Source Portrait"):
121
- image_input = gr.Image(type="numpy")
 
 
 
 
122
  gr.Examples(
123
  examples=[
124
  [osp.join(example_portrait_dir, "s9.jpg")],
@@ -130,8 +246,12 @@ with gr.Blocks(theme=gr.themes.Soft(),title="LivePortrait: Revolutionary AI-Powe
130
  inputs=[image_input],
131
  cache_examples=False,
132
  )
 
133
  with gr.Accordion(open=True, label="Driving Video"):
134
- video_input = gr.Video()
 
 
 
135
  gr.Examples(
136
  examples=[
137
  [osp.join(example_video_dir, "d0.mp4")],
@@ -142,103 +262,59 @@ with gr.Blocks(theme=gr.themes.Soft(),title="LivePortrait: Revolutionary AI-Powe
142
  inputs=[video_input],
143
  cache_examples=False,
144
  )
 
145
  with gr.Row():
146
- with gr.Accordion(open=False, label="Animation Instructions and Options"):
147
- gr.Markdown(load_description("assets/gradio_description_animation.md"))
148
- with gr.Row():
149
- flag_relative_input = gr.Checkbox(value=True, label="relative motion")
150
- flag_do_crop_input = gr.Checkbox(value=True, label="do crop")
151
- flag_remap_input = gr.Checkbox(value=True, label="paste-back")
152
- with gr.Row():
153
- with gr.Column():
154
- process_button_animation = gr.Button("🚀 Animate", variant="primary")
155
- with gr.Column():
156
- process_button_reset = gr.ClearButton([image_input, video_input, output_video, output_video_concat], value="🧹 Clear")
157
  with gr.Row():
158
- with gr.Column():
159
- with gr.Accordion(open=True, label="The animated video in the original image space"):
160
- output_video.render()
161
- with gr.Column():
162
- with gr.Accordion(open=True, label="The animated video"):
163
- output_video_concat.render()
164
  with gr.Row():
165
- # Examples
166
- gr.Markdown("## You could choose the examples below ⬇️")
167
  with gr.Row():
168
  gr.Examples(
169
  examples=data_examples,
170
- fn=gpu_wrapped_execute_video,
171
  inputs=[
172
  image_input,
173
  video_input,
174
- flag_relative_input,
175
- flag_do_crop_input,
176
- flag_remap_input
177
  ],
178
- outputs=[output_video, output_video_concat],
179
  examples_per_page=5,
180
  cache_examples=False,
181
  )
182
- gr.Markdown(load_description("assets/gradio_description_retargeting.md"), visible=False)
183
- with gr.Row(visible=False):
184
- eye_retargeting_slider.render()
185
- lip_retargeting_slider.render()
186
- with gr.Row(visible=False):
187
- process_button_retargeting = gr.Button("🚗 Retargeting", variant="primary")
188
- process_button_reset_retargeting = gr.ClearButton(
189
- [
190
- eye_retargeting_slider,
191
- lip_retargeting_slider,
192
- retargeting_input_image,
193
- output_image,
194
- output_image_paste_back
195
- ],
196
- value="🧹 Clear"
197
- )
198
- with gr.Row(visible=False):
199
- with gr.Column():
200
- with gr.Accordion(open=True, label="Retargeting Input"):
201
- retargeting_input_image.render()
202
- with gr.Column():
203
- with gr.Accordion(open=True, label="Retargeting Result"):
204
- output_image.render()
205
- with gr.Column():
206
- with gr.Accordion(open=True, label="Paste-back Result"):
207
- output_image_paste_back.render()
208
- # binding functions for buttons
209
- process_button_retargeting.click(
210
- # fn=gradio_pipeline.execute_image,
211
- fn=gpu_wrapped_execute_image,
212
- inputs=[eye_retargeting_slider, lip_retargeting_slider],
213
- outputs=[output_image, output_image_paste_back],
214
- show_progress=True
215
- )
216
  process_button_animation.click(
217
- fn=gpu_wrapped_execute_video,
218
  inputs=[
219
  image_input,
220
  video_input,
221
- flag_relative_input,
222
- flag_do_crop_input,
223
- flag_remap_input
224
  ],
225
- outputs=[output_video, output_video_concat],
226
  show_progress=True
227
  )
228
- image_input.change(
229
- fn=gradio_pipeline.prepare_retargeting,
230
- inputs=image_input,
231
- outputs=[eye_retargeting_slider, lip_retargeting_slider, retargeting_input_image]
232
- )
233
  video_input.upload(
234
  fn=is_square_video,
235
  inputs=video_input,
236
  outputs=video_input
237
  )
238
 
 
239
  demo.launch(
240
  server_port=args.server_port,
241
  share=args.share,
242
  server_name=args.server_name,
243
  show_api=True
244
- )
 
1
  # coding: utf-8
2
 
3
  """
4
+ 简化版 Gradio 入口:
5
+ 只生成并输出最终头像动画视频。
6
+ 不再生成:
7
+ 1. The animated video in the original image space
8
+ 2. 对比/拼接类 The animated video
9
  """
10
 
11
+ import os
 
12
  import os.path as osp
13
+
14
+ import cv2
15
+ import gradio as gr
16
  import torch
17
+ import tyro
18
  from gradio_client import utils as gradio_client_utils
19
+
 
 
20
  from src.config.argument_config import ArgumentConfig
21
+ from src.config.crop_config import CropConfig
22
  from src.config.inference_config import InferenceConfig
23
+ from src.gradio_pipeline import GradioPipeline
24
+ from src.utils.helper import load_description
25
 
26
  try:
27
  import spaces
28
  except ImportError:
29
  spaces = None
30
 
 
 
 
31
 
32
  def partial_fields(target_class, kwargs):
33
+ """
34
+ 只把目标配置类中存在的字段传进去,避免参数不匹配。
35
+ """
36
  return target_class(**{k: v for k, v in kwargs.items() if hasattr(target_class, k)})
37
 
38
+
39
+ # 设置 tyro 主题颜色
40
  tyro.extras.set_accent_color("bright_cyan")
41
  args = tyro.cli(ArgumentConfig)
42
 
43
+ # 初始化推理配置
44
+ inference_cfg = partial_fields(InferenceConfig, args.__dict__)
45
+ crop_cfg = partial_fields(CropConfig, args.__dict__)
46
 
47
  gradio_pipeline = GradioPipeline(
48
  inference_cfg=inference_cfg,
 
50
  args=args
51
  )
52
 
53
+
54
  def maybe_gpu(fn):
55
+ """
56
+ Hugging Face Spaces GPU 环境下自动使用 spaces.GPU。
57
+ CPU 空间下则直接运行。
58
+ """
59
  if spaces is not None and torch.cuda.is_available():
60
  return spaces.GPU(fn)
61
  return fn
62
 
63
 
64
+ # 修复部分 gradio_client schema 兼容问题
65
  _original_json_schema_to_python_type = gradio_client_utils._json_schema_to_python_type
66
 
67
 
 
73
 
74
  gradio_client_utils._json_schema_to_python_type = _patched_json_schema_to_python_type
75
 
76
+
77
+ def get_video_path(video_input):
78
+ """
79
+ 兼容不同 Gradio 版本的 gr.Video 返回格式。
80
+ 有些版本返回字符串路径,有些版本返回 dict。
81
+ """
82
+ if isinstance(video_input, dict):
83
+ return video_input.get("name") or video_input.get("path") or video_input.get("video")
84
+ return video_input
85
+
86
+
87
+ def pick_avatar_video(result):
88
+ """
89
+ 从 gradio_pipeline.execute_video 的返回结果中挑选最终头像动画视频。
90
+
91
+ 原始 execute_video 通常会返回:
92
+ - 第 1 个:动画视频路径
93
+ - 第 2 个:concat / 对比视频路径
94
+
95
+ 本函数会优先选择非 concat、非 compare、非 pasteback 的视频。
96
+ """
97
+ if result is None:
98
+ raise gr.Error("生成失败:没有返回任何视频结果。")
99
+
100
+ if isinstance(result, (list, tuple)):
101
+ candidates = []
102
+
103
+ for item in result:
104
+ if item is None:
105
+ continue
106
+
107
+ item_str = str(item)
108
+
109
+ if item_str.lower().endswith((".mp4", ".mov", ".avi", ".webm")):
110
+ candidates.append(item_str)
111
+
112
+ if not candidates:
113
+ raise gr.Error("生成失败:没有找到可用的视频文件。")
114
+
115
+ # 优先排除拼接、对比、原图空间相关视频
116
+ clean_candidates = []
117
+ for path in candidates:
118
+ name = os.path.basename(path).lower()
119
+
120
+ if (
121
+ "concat" not in name
122
+ and "compare" not in name
123
+ and "paste" not in name
124
+ and "pasteback" not in name
125
+ ):
126
+ clean_candidates.append(path)
127
+
128
+ if clean_candidates:
129
+ return clean_candidates[0]
130
+
131
+ # 如果无法判断,就返回第一个视频
132
+ return candidates[0]
133
+
134
+ return str(result)
135
+
136
+
137
  @maybe_gpu
138
+ def gpu_wrapped_execute_avatar_video(
139
+ input_image,
140
+ input_video,
 
 
 
141
  ):
142
+ """
143
+ 只生成最终头像动画视频。
144
+
145
+ 关键修改:
146
+ 1. relative motion 固定为 True
147
+ 2. do crop 固定为 True
148
+ 3. paste-back / remap 固定为 False
149
+
150
+ 这样不会再生成原图空间动画,只保留头像区域动画。
151
+ """
152
+ if input_image is None:
153
+ raise gr.Error("请先上传 Source Portrait 头像图片。")
154
+
155
+ if input_video is None:
156
+ raise gr.Error("请先上传 Driving Video 驱动视频。")
157
+
158
+ # 固定参数,减少用户选项,也减少不必要生成内容
159
+ flag_relative_input = True
160
+ flag_do_crop_input = True
161
+
162
+ # 关键:False 表示不做 paste-back,不生成 original image space 视频
163
+ flag_remap_input = False
164
+
165
+ result = gradio_pipeline.execute_video(
166
+ input_image,
167
+ input_video,
168
  flag_relative_input,
169
  flag_do_crop_input,
170
  flag_remap_input,
171
  )
172
 
173
+ avatar_video_path = pick_avatar_video(result)
174
+
175
+ return avatar_video_path
176
+
177
+
178
+ def is_square_video(video_input):
179
+ """
180
+ 检查驱动视频是否为正方形。
181
+ 当前项目通常只支持正方形驱动视频。
182
+ """
183
+ video_path = get_video_path(video_input)
184
+
185
+ if not video_path:
186
+ raise gr.Error("无法读取视频文件,请重新上传。")
187
 
 
188
  video = cv2.VideoCapture(video_path)
189
+
190
  width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
191
  height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
192
+
193
  video.release()
194
+
195
  if width != height:
196
  raise gr.Error("Error: the video does not have a square aspect ratio. We currently only support square videos")
197
+
198
  return gr.update(visible=True)
199
 
200
+
201
+ # 资源路径
202
  title_md = "assets/gradio_title.md"
203
  example_portrait_dir = "assets/examples/source"
204
  example_video_dir = "assets/examples/driving"
205
+
206
+ # 示例数据只保留图片和驱动视频,不再包含多余参数
207
  data_examples = [
208
+ [osp.join(example_portrait_dir, "s9.jpg"), osp.join(example_video_dir, "d0.mp4")],
209
+ [osp.join(example_portrait_dir, "s6.jpg"), osp.join(example_video_dir, "d0.mp4")],
210
+ [osp.join(example_portrait_dir, "s10.jpg"), osp.join(example_video_dir, "d5.mp4")],
211
+ [osp.join(example_portrait_dir, "s5.jpg"), osp.join(example_video_dir, "d6.mp4")],
212
+ [osp.join(example_portrait_dir, "s7.jpg"), osp.join(example_video_dir, "d7.mp4")],
213
  ]
214
+
215
+
216
+ with gr.Blocks(
217
+ theme=gr.themes.Soft(),
218
+ title="LivePortrait Avatar Animation"
219
+ ) as demo:
220
+
 
 
 
 
 
221
  gr.HTML(load_description(title_md))
222
+
223
+ gr.Markdown(
224
+ """
225
+ ## Avatar Animation
226
+
227
+ 上传一张头像图片和一个驱动视频,系统只输出最终头像动画视频。
228
+ """
229
+ )
230
+
231
  with gr.Row():
232
  with gr.Accordion(open=True, label="Source Portrait"):
233
+ image_input = gr.Image(
234
+ type="numpy",
235
+ label="Upload Source Portrait"
236
+ )
237
+
238
  gr.Examples(
239
  examples=[
240
  [osp.join(example_portrait_dir, "s9.jpg")],
 
246
  inputs=[image_input],
247
  cache_examples=False,
248
  )
249
+
250
  with gr.Accordion(open=True, label="Driving Video"):
251
+ video_input = gr.Video(
252
+ label="Upload Driving Video"
253
+ )
254
+
255
  gr.Examples(
256
  examples=[
257
  [osp.join(example_video_dir, "d0.mp4")],
 
262
  inputs=[video_input],
263
  cache_examples=False,
264
  )
265
+
266
  with gr.Row():
267
+ process_button_animation = gr.Button(
268
+ "🚀 Animate Avatar",
269
+ variant="primary"
270
+ )
271
+
272
+ process_button_reset = gr.ClearButton(
273
+ [image_input, video_input],
274
+ value="🧹 Clear"
275
+ )
276
+
 
277
  with gr.Row():
278
+ output_avatar_video = gr.Video(
279
+ label="The final avatar animated video"
280
+ )
281
+
 
 
282
  with gr.Row():
283
+ gr.Markdown("## Examples")
284
+
285
  with gr.Row():
286
  gr.Examples(
287
  examples=data_examples,
288
+ fn=gpu_wrapped_execute_avatar_video,
289
  inputs=[
290
  image_input,
291
  video_input,
 
 
 
292
  ],
293
+ outputs=[output_avatar_video],
294
  examples_per_page=5,
295
  cache_examples=False,
296
  )
297
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
298
  process_button_animation.click(
299
+ fn=gpu_wrapped_execute_avatar_video,
300
  inputs=[
301
  image_input,
302
  video_input,
 
 
 
303
  ],
304
+ outputs=[output_avatar_video],
305
  show_progress=True
306
  )
307
+
 
 
 
 
308
  video_input.upload(
309
  fn=is_square_video,
310
  inputs=video_input,
311
  outputs=video_input
312
  )
313
 
314
+
315
  demo.launch(
316
  server_port=args.server_port,
317
  share=args.share,
318
  server_name=args.server_name,
319
  show_api=True
320
+ )