multimodalart HF Staff commited on
Commit
28b2dac
·
verified ·
1 Parent(s): 56321d9

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +317 -0
app.py ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import os
4
+ import numpy as np
5
+ from PIL import Image
6
+ import cv2
7
+ import tempfile
8
+ import moviepy.editor as mp
9
+ from facexlib.utils.face_restoration_helper import FaceRestoreHelper
10
+ from diffusers.utils import export_to_video, load_image
11
+
12
+ # Import required modules from SkyReels
13
+ from skyreels_a1.models.transformer3d import CogVideoXTransformer3DModel
14
+ from skyreels_a1.skyreels_a1_i2v_pipeline import SkyReelsA1ImagePoseToVideoPipeline
15
+ from skyreels_a1.pre_process_lmk3d import FaceAnimationProcessor
16
+ from skyreels_a1.src.media_pipe.mp_utils import LMKExtractor
17
+ from skyreels_a1.src.media_pipe.draw_util_2d import FaceMeshVisualizer2d
18
+
19
+ from diffusers.models import AutoencoderKLCogVideoX
20
+ from transformers import SiglipImageProcessor, SiglipVisionModel
21
+ from diffposetalk.diffposetalk import DiffPoseTalk
22
+
23
+ from huggingface_hub import snapshot_download
24
+
25
+ os.system("pip install pytorch3d -f https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/py310_cu121_pyt221/download.html")
26
+
27
+ os.makedirs("pretrained_models", exist_ok=True)
28
+
29
+ snapshot_download(
30
+ repo_id="multimodalart/diffposetalk",
31
+ local_dir="pretrained_models/diffposetalk"
32
+ )
33
+
34
+ snapshot_download(
35
+ repo_id="Skywork/SkyReels-A1",
36
+ local_dir="pretrained_models/FLAME",
37
+ allow_patterns="extra_models/FLAME/**"
38
+ )
39
+
40
+ snapshot_download(
41
+ repo_id="Skywork/SkyReels-A1",
42
+ local_dir="pretrained_models/mediapipe",
43
+ allow_patterns="extra_models/mediapipe/**"
44
+ )
45
+
46
+ snapshot_download(
47
+ repo_id="Skywork/SkyReels-A1",
48
+ local_dir="pretrained_models/smirk",
49
+ allow_patterns="extra_models/smirk/**"
50
+ )
51
+
52
+ snapshot_download(
53
+ repo_id="Skywork/SkyReels-A1",
54
+ local_dir="pretrained_models/SkyReels-A1-5B",
55
+ allow_patterns="SkyReels-A1-5B/**"
56
+ )
57
+
58
+
59
+ # Helper functions from the original script
60
+ def parse_video(driving_frames, max_frame_num, fps=25):
61
+ video_length = len(driving_frames)
62
+ duration = video_length / fps
63
+ target_times = np.arange(0, duration, 1/12)
64
+ frame_indices = (target_times * fps).astype(np.int32)
65
+
66
+ frame_indices = frame_indices[frame_indices < video_length]
67
+ new_driving_frames = []
68
+ for idx in frame_indices:
69
+ new_driving_frames.append(driving_frames[idx])
70
+ if len(new_driving_frames) >= max_frame_num - 1:
71
+ break
72
+
73
+ video_lenght_add = max_frame_num - len(new_driving_frames) - 1
74
+ new_driving_frames = [new_driving_frames[0]]*2 + new_driving_frames[1:len(new_driving_frames)-1] + [new_driving_frames[-1]] * video_lenght_add
75
+ return new_driving_frames
76
+
77
+ def write_mp4(video_path, samples, fps=12):
78
+ clip = mp.ImageSequenceClip(samples, fps=fps)
79
+ clip.write_videofile(video_path, audio_codec="aac", codec="libx264",
80
+ ffmpeg_params=["-crf", "18", "-preset", "slow"])
81
+
82
+ def save_video_with_audio(video_path, audio_path, save_path):
83
+ video_clip = mp.VideoFileClip(video_path)
84
+ audio_clip = mp.AudioFileClip(audio_path)
85
+
86
+ if audio_clip.duration > video_clip.duration:
87
+ audio_clip = audio_clip.subclip(0, video_clip.duration)
88
+
89
+ video_with_audio = video_clip.set_audio(audio_clip)
90
+ video_with_audio.write_videofile(save_path, fps=12, codec="libx264", audio_codec="aac")
91
+
92
+ # Clean up
93
+ video_clip.close()
94
+ audio_clip.close()
95
+ return save_path
96
+
97
+ # Global parameters
98
+ model_name = "pretrained_models/SkyReels-A1-5B/"
99
+ siglip_name = "pretrained_models/SkyReels-A1-5B/siglip-so400m-patch14-384"
100
+ weight_dtype = torch.bfloat16
101
+ max_frame_num = 49
102
+ sample_size = [480, 720]
103
+
104
+ # Preload all models in global context
105
+ print("Loading models...")
106
+
107
+ # Load LMK extractor and processors
108
+ lmk_extractor = LMKExtractor()
109
+ processor = FaceAnimationProcessor(checkpoint='pretrained_models/smirk/SMIRK_em1.pt')
110
+ vis = FaceMeshVisualizer2d(forehead_edge=False, draw_head=False, draw_iris=False)
111
+ face_helper = FaceRestoreHelper(upscale_factor=1, face_size=512, crop_ratio=(1, 1),
112
+ det_model='retinaface_resnet50', save_ext='png', device="cuda")
113
+
114
+ # Load siglip visual encoder
115
+ siglip = SiglipVisionModel.from_pretrained(siglip_name)
116
+ siglip_normalize = SiglipImageProcessor.from_pretrained(siglip_name)
117
+
118
+ # Load diffposetalk
119
+ diffposetalk = DiffPoseTalk()
120
+
121
+ # Load SkyReels models
122
+ transformer = CogVideoXTransformer3DModel.from_pretrained(
123
+ model_name,
124
+ subfolder="transformer"
125
+ ).to(weight_dtype)
126
+
127
+ vae = AutoencoderKLCogVideoX.from_pretrained(
128
+ model_name,
129
+ subfolder="vae"
130
+ ).to(weight_dtype)
131
+
132
+ lmk_encoder = AutoencoderKLCogVideoX.from_pretrained(
133
+ model_name,
134
+ subfolder="pose_guider",
135
+ ).to(weight_dtype)
136
+
137
+ # Set up pipeline
138
+ pipe = SkyReelsA1ImagePoseToVideoPipeline.from_pretrained(
139
+ model_name,
140
+ transformer=transformer,
141
+ vae=vae,
142
+ lmk_encoder=lmk_encoder,
143
+ image_encoder=siglip,
144
+ feature_extractor=siglip_normalize,
145
+ torch_dtype=torch.bfloat16
146
+ )
147
+ pipe.to("cuda")
148
+ pipe.transformer = torch.compile(pipe.transformer)
149
+ pipe.vae = torch.compile(pipe.vae)
150
+ # pipe.enable_model_cpu_offload()
151
+ # pipe.vae.enable_tiling()
152
+
153
+ print("Models loaded successfully!")
154
+
155
+ def process_image_audio(image_path, audio_path, guidance_scale=3.0, steps=10, progress=gr.Progress()):
156
+ progress(0.1, desc="Processing inputs...")
157
+ # Create a directory for outputs if it doesn't exist
158
+ output_dir = "gradio_outputs"
159
+ os.makedirs(output_dir, exist_ok=True)
160
+
161
+ # Create temp files for processing
162
+ with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as temp_video_file, \
163
+ tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as temp_output_file:
164
+ temp_video_path = temp_video_file.name
165
+ final_output_path = temp_output_file.name
166
+
167
+ # Set seed
168
+ seed = 43
169
+ generator = torch.Generator(device="cuda").manual_seed(seed)
170
+
171
+ progress(0.2, desc="Processing image...")
172
+ # Load and process image
173
+ image = load_image(image=image_path)
174
+ image = processor.crop_and_resize(image, sample_size[0], sample_size[1])
175
+
176
+ # Crop face
177
+ ref_image, x1, y1 = processor.face_crop(np.array(image))
178
+ face_h, face_w, _ = ref_image.shape
179
+ source_image = ref_image
180
+
181
+ progress(0.3, desc="Processing facial landmarks...")
182
+ # Process source image
183
+ source_outputs, source_tform, image_original = processor.process_source_image(source_image)
184
+
185
+ progress(0.4, desc="Processing audio...")
186
+ # Process audio and generate driving outputs
187
+ driving_outputs = diffposetalk.infer_from_file(
188
+ audio_path,
189
+ source_outputs["shape_params"].view(-1)[:100].detach().cpu().numpy()
190
+ )
191
+
192
+ progress(0.5, desc="Processing landmarks from coefficients...")
193
+ # Process landmarks
194
+ out_frames = processor.preprocess_lmk3d_from_coef(
195
+ source_outputs, source_tform, image_original.shape, driving_outputs
196
+ )
197
+ out_frames = parse_video(out_frames, max_frame_num)
198
+
199
+ rescale_motions = np.zeros_like(image)[np.newaxis, :].repeat(48, axis=0)
200
+ for ii in range(rescale_motions.shape[0]):
201
+ rescale_motions[ii][y1:y1+face_h, x1:x1+face_w] = out_frames[ii]
202
+
203
+ ref_image_resized = cv2.resize(ref_image, (512, 512))
204
+ ref_lmk = lmk_extractor(ref_image_resized[:, :, ::-1])
205
+
206
+ ref_img = vis.draw_landmarks_v3(
207
+ (512, 512), (face_w, face_h),
208
+ ref_lmk['lmks'].astype(np.float32), normed=True
209
+ )
210
+
211
+ first_motion = np.zeros_like(np.array(image))
212
+ first_motion[y1:y1+face_h, x1:x1+face_w] = ref_img
213
+ first_motion = first_motion[np.newaxis, :]
214
+
215
+ motions = np.concatenate([first_motion, rescale_motions])
216
+ input_video = motions[:max_frame_num]
217
+
218
+ # Face alignment
219
+ face_helper.clean_all()
220
+ face_helper.read_image(np.array(image)[:, :, ::-1])
221
+ face_helper.get_face_landmarks_5(only_center_face=True)
222
+ face_helper.align_warp_face()
223
+ align_face = face_helper.cropped_faces[0]
224
+ image_face = align_face[:, :, ::-1]
225
+
226
+ # Prepare input video
227
+ input_video = torch.from_numpy(np.array(input_video)).permute([3, 0, 1, 2]).unsqueeze(0)
228
+ input_video = input_video / 255
229
+
230
+ progress(0.6, desc="Generating animation (this may take a while)...")
231
+ # Generate video
232
+ #with torch.no_grad():
233
+ sample = pipe(
234
+ image=image,
235
+ image_face=image_face,
236
+ control_video=input_video,
237
+ prompt="",
238
+ negative_prompt="",
239
+ height=480,
240
+ width=720,
241
+ num_frames=49,
242
+ generator=generator,
243
+ guidance_scale=guidance_scale,
244
+ num_inference_steps=steps,
245
+ )
246
+ out_samples = sample.frames[0]
247
+
248
+ out_samples = out_samples[2:] # Skip first two frames
249
+
250
+ progress(0.8, desc="Creating output video...")
251
+ # Export video
252
+ export_to_video(out_samples, temp_video_path, fps=12)
253
+
254
+ progress(0.9, desc="Adding audio to video...")
255
+ # Add audio to video
256
+ result_path = save_video_with_audio(temp_video_path, audio_path, final_output_path)
257
+
258
+ # Create side-by-side comparison
259
+ target_h, target_w = sample_size[0], sample_size[1]
260
+ final_images = []
261
+ for i in range(len(out_samples)):
262
+ frame1 = image
263
+ frame2 = Image.fromarray(np.array(out_samples[i])).convert("RGB")
264
+
265
+ result = Image.new('RGB', (target_w * 2, target_h))
266
+ result.paste(frame1, (0, 0))
267
+ result.paste(frame2, (target_w, 0))
268
+ final_images.append(np.array(result))
269
+
270
+ comparison_path = os.path.join(output_dir, "comparison.mp4")
271
+ write_mp4(comparison_path, final_images, fps=12)
272
+
273
+ # Add audio to comparison video
274
+ comparison_with_audio = os.path.join(output_dir, "comparison_with_audio.mp4")
275
+ comparison_with_audio = save_video_with_audio(comparison_path, audio_path, comparison_with_audio)
276
+
277
+ progress(1.0, desc="Done!")
278
+ return result_path, comparison_with_audio
279
+
280
+ # Create Gradio interface
281
+ with gr.Blocks(title="SkyReels A1 Face Animation") as app:
282
+ gr.Markdown("# SkyReels A1 Face Animation")
283
+ gr.Markdown("Upload a portrait image and an audio file to animate the face")
284
+
285
+ with gr.Row():
286
+ with gr.Column():
287
+ image_input = gr.Image(type="filepath", label="Portrait Image")
288
+ audio_input = gr.Audio(type="filepath", label="Driving Audio")
289
+
290
+ with gr.Row():
291
+ guidance_scale = gr.Slider(minimum=1.0, maximum=7.0, value=3.0, step=0.1, label="Guidance Scale")
292
+ inference_steps = gr.Slider(minimum=5, maximum=30, value=10, step=1, label="Inference Steps")
293
+
294
+ generate_button = gr.Button("Generate Animation", variant="primary")
295
+
296
+ with gr.Column():
297
+ output_video = gr.Video(label="Animation Result")
298
+ comparison_video = gr.Video(label="Side-by-Side Comparison")
299
+
300
+ generate_button.click(
301
+ fn=process_image_audio,
302
+ inputs=[image_input, audio_input, guidance_scale, inference_steps],
303
+ outputs=[output_video, comparison_video]
304
+ )
305
+
306
+ gr.Markdown("""
307
+ ## Instructions
308
+ 1. Upload a portrait image (frontal face works best)
309
+ 2. Upload an audio file (wav format recommended)
310
+ 3. Adjust parameters if needed
311
+ 4. Click "Generate Animation" to create the video
312
+
313
+ Note: Processing may take several minutes depending on your hardware.
314
+ """)
315
+
316
+ if __name__ == "__main__":
317
+ app.launch(share=True)