alvinichi commited on
Commit
7491096
·
1 Parent(s): 275b8a1

udpate lib

Browse files
Files changed (2) hide show
  1. app.py +110 -87
  2. requirements.txt +7 -9
app.py CHANGED
@@ -1,85 +1,108 @@
1
  import gradio as gr
2
  import torch
3
- import os
4
- import requests
5
- import tempfile
6
- from PIL import Image
7
  import numpy as np
8
- from huggingface_hub import hf_hub_download
9
- from moviepy.editor import ImageSequenceClip
 
 
 
 
 
10
 
11
- # Tải các mô hình cần thiết
12
- def download_models():
13
- # Tải mô hình tạo khung xương (pose model)
14
- pose_model_path = hf_hub_download(
15
- repo_id="magic-animate/magic-animate",
16
- filename="dw-ll_ucoco_384.onnx",
17
- subfolder="reference/openpose"
18
- )
19
 
20
- # Tải mô hình MagicAnimate
21
- magic_animate_path = hf_hub_download(
22
- repo_id="magic-animate/magic-animate",
23
- filename="model.ckpt",
24
- subfolder="checkpoints"
25
- )
26
-
27
- return pose_model_path, magic_animate_path
28
-
29
- # Hàm trích xuất khung xương từ video tham chiếu
30
- def extract_pose(reference_video_path):
31
- # Giả lập trích xuất khung xương từ video tham chiếu
32
- # Trong thực tế, đây sẽ sử dụng mô hình pose estimation
33
- return "pose_sequence.json"
34
 
35
- # Hàm chính để tạo video người chuyển động
36
- def animate_person_magic(image, reference_choice, custom_video=None):
37
- if image is None:
38
- return None, "Vui lòng tải lên một hình ảnh."
39
 
40
  try:
41
- # Chuẩn bị hình ảnh
42
- if image.mode != "RGB":
43
- image = image.convert("RGB")
44
 
45
- # Resize hình ảnh
46
- image = image.resize((512, 512))
 
47
 
48
- # Chọn video tham chiếu dựa trên lựa chọn
49
- reference_videos = {
50
- "Đi bộ": "walking.mp4",
51
- "Nhảy múa": "dancing.mp4",
52
- "Vẫy tay": "waving.mp4",
53
- "Ngồi xuống": "sitting.mp4",
54
- "Tùy chỉnh": custom_video
55
- }
56
-
57
- video_path = reference_videos[reference_choice]
58
- if reference_choice == "Tùy chỉnh" and custom_video is None:
59
- return None, "Vui lòng tải lên video tham chiếu hoặc chọn một tùy chọn khác."
60
-
61
- # Trong thực tế, đây sẽ gọi mô hình MagicAnimate
62
- # Đây là phiên bản mô phỏng
63
-
64
- # Tạo các khung hình (mô phỏng kết quả)
65
- frames = []
66
- for i in range(24):
67
- # Mô phỏng frame - thực tế sẽ được tạo từ mô hình
68
- # Đây chỉ là hiệu ứng thay thế để minh họa
69
 
70
- # Hiệu ứng đơn giản: Dịch chuyển ảnh theo chuyển động
71
- offset_x = int(np.sin(i/24 * 2 * np.pi) * 20)
72
- offset_y = int(np.sin(i/12 * 2 * np.pi) * 10)
73
 
74
- # Tạo ảnh mới với offset
75
- frame = Image.new('RGB', (512, 512))
76
- frame.paste(image, (offset_x + 256 - image.width//2, offset_y + 256 - image.height//2))
77
- frames.append(np.array(frame))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
 
79
- # Tạo video từ frames
80
- output_path = "animated_person_magic.mp4"
81
- clip = ImageSequenceClip(frames, fps=8)
82
- clip.write_videofile(output_path, codec="libx264")
83
 
84
  return output_path, "Video được tạo thành công!"
85
 
@@ -87,22 +110,22 @@ def animate_person_magic(image, reference_choice, custom_video=None):
87
  return None, f"Lỗi: {str(e)}"
88
 
89
  # Tạo giao diện Gradio
90
- with gr.Blocks(title="MagicAnimate - Làm động người từ ảnh") as demo:
91
- gr.Markdown("# MagicAnimate - Tạo video người chuyển động từ ảnh")
92
- gr.Markdown("Tải lên ảnh người chọn kiểu chuyển động để tạo video chân thực")
93
 
94
  with gr.Row():
95
  with gr.Column():
96
- image_input = gr.Image(type="pil", label="Tải lên ảnh người")
97
 
98
  with gr.Row():
99
- reference_choice = gr.Radio(
100
- ["Đi bộ", "Nhảy múa", "Vẫy tay", "Ngồi xuống", "Tùy chỉnh"],
101
  label="Chọn kiểu chuyển động",
102
- value="Đi bộ"
103
  )
104
 
105
- custom_video_input = gr.Video(
106
  label="Tải lên video tham chiếu (chỉ khi chọn 'Tùy chỉnh')"
107
  )
108
 
@@ -113,19 +136,19 @@ with gr.Blocks(title="MagicAnimate - Làm động người từ ảnh") as demo:
113
  output_message = gr.Textbox(label="Thông báo")
114
 
115
  submit_btn.click(
116
- fn=animate_person_magic,
117
- inputs=[image_input, reference_choice, custom_video_input],
118
  outputs=[output_video, output_message]
119
  )
120
 
121
- gr.Markdown("### Cách hoạt động")
122
- gr.Markdown("1. Ứng dụng sẽ phân tích ảnh của bạn để xác định vị trí của người")
123
- gr.Markdown("2. Sau đó áp dụng chuyển động từ video tham chiếu lên người trong ảnh")
124
- gr.Markdown("3. Kết quả là một video tự nhiên với người trong ảnh của bạn thực hiện chuyển động")
125
 
126
- gr.Markdown("### Mẹo để có kết quả tốt")
127
- gr.Markdown("- Sử dụng ảnh người cả người, ràng, không bị che khuất")
128
- gr.Markdown("- Tránh ảnh với nhiều người hoặc nền quá phức tạp")
129
- gr.Markdown("- Thử các kiểu chuyển động khác nhau để tìm kết quả tốt nhất")
130
 
131
  demo.launch()
 
1
  import gradio as gr
2
  import torch
 
 
 
 
3
  import numpy as np
4
+ import imageio
5
+ import os
6
+ import gdown
7
+ import cv2
8
+ from skimage.transform import resize
9
+ from skimage import img_as_ubyte
10
+ from first_order_model.demo import load_checkpoints, make_animation
11
 
12
+ # Tải cài đặt mô hình
13
+ def download_model():
14
+ model_path = 'first_order_model/vox-cpk.pth.tar'
15
+ if not os.path.exists(model_path):
16
+ os.makedirs('first_order_model', exist_ok=True)
17
+ url = 'https://drive.google.com/uc?id=1PyQJmkdCsAkOYwUyaj_l-l0as-iLDgeH'
18
+ gdown.download(url, model_path, quiet=False)
 
19
 
20
+ if not os.path.exists('first_order_model/config/vox-256.yaml'):
21
+ os.makedirs('first_order_model/config', exist_ok=True)
22
+ config_url = 'https://drive.google.com/uc?id=1PmYZrk1MLyfYFa5vgRy0HVfkWTR42NMj'
23
+ gdown.download(config_url, 'first_order_model/config/vox-256.yaml', quiet=False)
 
 
 
 
 
 
 
 
 
 
24
 
25
+ # Tạo video người chuyển động
26
+ def animate_person(source_image, driving_video=None, movement_type="Mặc định"):
27
+ if source_image is None:
28
+ return None, "Vui lòng tải lên một hình ảnh người."
29
 
30
  try:
31
+ # Tải hình
32
+ download_model()
 
33
 
34
+ # Chuẩn bị hình ảnh nguồn
35
+ source_image_path = "source_image.jpg"
36
+ cv2.imwrite(source_image_path, cv2.cvtColor(np.array(source_image), cv2.COLOR_RGB2BGR))
37
 
38
+ # Chuẩn bị video tham chiếu
39
+ if driving_video is None or movement_type != "Tùy chỉnh":
40
+ # Sử dụng video mẫu dựa trên loại chuyển động
41
+ driving_videos = {
42
+ "Mặc định": "driving_videos/default.mp4",
43
+ "Nói chuyện": "driving_videos/talking.mp4",
44
+ "Quay đầu": "driving_videos/head_turning.mp4",
45
+ "Cười": "driving_videos/smiling.mp4"
46
+ }
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
+ # Tạo thư mục cho video mẫu
49
+ os.makedirs("driving_videos", exist_ok=True)
 
50
 
51
+ # Tạo video mẫu đơn giản nếu chưa có
52
+ if not os.path.exists(driving_videos[movement_type]):
53
+ # Tạo một video mẫu đơn giản với OpenCV
54
+ # Trong thực tế, bạn sẽ tải video m���u từ nguồn khác
55
+ video_path = driving_videos[movement_type]
56
+ out = cv2.VideoWriter(video_path, cv2.VideoWriter_fourcc(*'mp4v'), 25, (256, 256))
57
+
58
+ # Tạo 100 khung hình với chuyển động đơn giản
59
+ for i in range(100):
60
+ frame = np.zeros((256, 256, 3), dtype=np.uint8)
61
+ if movement_type == "Nói chuyện":
62
+ cv2.ellipse(frame, (128, 180), (30 + i % 10, 20), 0, 0, 360, (255, 255, 255), -1)
63
+ elif movement_type == "Quay đầu":
64
+ cv2.ellipse(frame, (128 + int(np.sin(i/10) * 30), 128), (60, 80), 0, 0, 360, (255, 255, 255), -1)
65
+ elif movement_type == "Cười":
66
+ cv2.ellipse(frame, (128, 128), (60, 80), 0, 0, 360, (255, 255, 255), -1)
67
+ cv2.ellipse(frame, (128, 160 - i % 15), (40, 20), 0, 0, 180, (0, 0, 0), -1)
68
+ else: # Mặc định
69
+ cv2.ellipse(frame, (128, 128), (60, 80), 0, 0, 360, (255, 255, 255), -1)
70
+ cv2.circle(frame, (110, 110), 10, (0, 0, 0), -1)
71
+ cv2.circle(frame, (146, 110), 10, (0, 0, 0), -1)
72
+
73
+ out.write(frame)
74
+
75
+ out.release()
76
+
77
+ driving_video_path = driving_videos[movement_type]
78
+ else:
79
+ # Sử dụng video do người dùng tải lên
80
+ driving_video_path = "driving_video.mp4"
81
+ # Lưu video tải lên
82
+ with open(driving_video_path, 'wb') as f:
83
+ f.write(driving_video)
84
+
85
+ # Tải mô hình và cấu hình
86
+ generator, kp_detector = load_checkpoints(
87
+ config_path='first_order_model/config/vox-256.yaml',
88
+ checkpoint_path='first_order_model/vox-cpk.pth.tar',
89
+ device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
90
+ )
91
+
92
+ # Tạo animation
93
+ predictions = make_animation(
94
+ source_image=source_image_path,
95
+ driving_video=driving_video_path,
96
+ generator=generator,
97
+ kp_detector=kp_detector,
98
+ relative=True,
99
+ adapt_movement_scale=True,
100
+ device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
101
+ )
102
 
103
+ # Lưu video kết quả
104
+ output_path = "animated_person.mp4"
105
+ imageio.mimsave(output_path, [img_as_ubyte(frame) for frame in predictions], fps=25)
 
106
 
107
  return output_path, "Video được tạo thành công!"
108
 
 
110
  return None, f"Lỗi: {str(e)}"
111
 
112
  # Tạo giao diện Gradio
113
+ with gr.Blocks(title="Ứng dụng tạo chuyển động cho người trong ảnh") as demo:
114
+ gr.Markdown("# Tạo video người chuyển động từ ảnh")
115
+ gr.Markdown("Tạo video trong đó người/khuôn mặt trong ảnh của bạn chuyển động tự nhiên")
116
 
117
  with gr.Row():
118
  with gr.Column():
119
+ source_image = gr.Image(type="numpy", label="Tải lên ảnh người")
120
 
121
  with gr.Row():
122
+ movement_choice = gr.Radio(
123
+ ["Mặc định", "Nói chuyện", "Quay đầu", "Cười", "Tùy chỉnh"],
124
  label="Chọn kiểu chuyển động",
125
+ value="Mặc định"
126
  )
127
 
128
+ driving_video = gr.Video(
129
  label="Tải lên video tham chiếu (chỉ khi chọn 'Tùy chỉnh')"
130
  )
131
 
 
136
  output_message = gr.Textbox(label="Thông báo")
137
 
138
  submit_btn.click(
139
+ fn=animate_person,
140
+ inputs=[source_image, driving_video, movement_choice],
141
  outputs=[output_video, output_message]
142
  )
143
 
144
+ gr.Markdown("### Cách thức hoạt động")
145
+ gr.Markdown("1. Ứng dụng sử dụng hình First Order Motion Model để phân tích chuyển động")
146
+ gr.Markdown("2. hình áp dụng chuyển động từ video tham chiếu vào đối tượng trong ảnh của bạn")
147
+ gr.Markdown("3. Kết quả là một video với người/đối tượng trong ảnh của bạn chuyển động tự nhiên")
148
 
149
+ gr.Markdown("### Lưu ý")
150
+ gr.Markdown("- Kết quả tốt nhất với ảnh chụp chính diện, nền đơn giản")
151
+ gr.Markdown("- Khuôn mặt/người cần ràng không bị che khuất")
152
+ gr.Markdown("- Nếu bạn chọn 'Tùy chỉnh', hãy tải lên video chuyển động bạn muốn áp dụng")
153
 
154
  demo.launch()
requirements.txt CHANGED
@@ -1,12 +1,10 @@
1
  gradio==4.0.2
2
- torch
 
3
  numpy
4
- Pillow
5
- huggingface_hub
6
- moviepy==1.0.3
7
- imageio==2.31.1
8
  imageio-ffmpeg
9
- decorator>=4.0.2
10
- tqdm>=4.11.2
11
- proglog<=1.0.0
12
- requests
 
1
  gradio==4.0.2
2
+ torch==1.7.1
3
+ torchvision==0.8.2
4
  numpy
5
+ imageio==2.9.0
 
 
 
6
  imageio-ffmpeg
7
+ scikit-image
8
+ opencv-python
9
+ gdown
10
+ pyyaml