FSSQ888 commited on
Commit
7a3cd20
·
verified ·
1 Parent(s): b612b38

Upload InfiniteTalk app.py and requirements.txt

Browse files
Files changed (2) hide show
  1. app.py +815 -66
  2. requirements.txt +21 -0
app.py CHANGED
@@ -1,70 +1,819 @@
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
-
5
- def respond(
6
- message,
7
- history: list[dict[str, str]],
8
- system_message,
9
- max_tokens,
10
- temperature,
11
- top_p,
12
- hf_token: gr.OAuthToken,
13
- ):
14
- """
15
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
16
- """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
18
-
19
- messages = [{"role": "system", "content": system_message}]
20
-
21
- messages.extend(history)
22
-
23
- messages.append({"role": "user", "content": message})
24
-
25
- response = ""
26
-
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
- ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- chatbot = gr.ChatInterface(
47
- respond,
48
- type="messages",
49
- additional_inputs=[
50
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
51
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
52
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
53
- gr.Slider(
54
- minimum=0.1,
55
- maximum=1.0,
56
- value=0.95,
57
- step=0.05,
58
- label="Top-p (nucleus sampling)",
59
- ),
60
- ],
61
- )
62
-
63
- with gr.Blocks() as demo:
64
- with gr.Sidebar():
65
- gr.LoginButton()
66
- chatbot.render()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
 
69
  if __name__ == "__main__":
70
- demo.launch()
 
 
 
1
+ # Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
2
+ import argparse
3
+ import logging
4
+ import os
5
+ os.environ["no_proxy"] = "localhost,127.0.0.1,::1"
6
+ import sys
7
+ import json
8
+ import warnings
9
+ from datetime import datetime
10
+
11
  import gradio as gr
12
+ warnings.filterwarnings('ignore')
13
+
14
+ import random
15
+
16
+ import torch
17
+ import torch.distributed as dist
18
+ from PIL import Image
19
+ import subprocess
20
+
21
+ import wan
22
+ from wan.configs import SIZE_CONFIGS, SUPPORTED_SIZES, WAN_CONFIGS
23
+ from wan.utils.utils import cache_image, cache_video, str2bool
24
+ from wan.utils.multitalk_utils import save_video_ffmpeg
25
+ from kokoro import KPipeline
26
+ from transformers import Wav2Vec2FeatureExtractor
27
+ from src.audio_analysis.wav2vec2 import Wav2Vec2Model
28
+
29
+ import librosa
30
+ import pyloudnorm as pyln
31
+ import numpy as np
32
+ from einops import rearrange
33
+ import soundfile as sf
34
+ import re
35
+
36
+ def _validate_args(args):
37
+ # Basic check
38
+ assert args.ckpt_dir is not None, "Please specify the checkpoint directory."
39
+ assert args.task in WAN_CONFIGS, f"Unsupport task: {args.task}"
40
+
41
+ # The default sampling steps are 40 for image-to-video tasks and 50 for text-to-video tasks.
42
+ if args.sample_steps is None:
43
+ args.sample_steps = 40
44
+
45
+ if args.sample_shift is None:
46
+ if args.size == 'infinitetalk-480':
47
+ args.sample_shift = 7
48
+ elif args.size == 'infinitetalk-720':
49
+ args.sample_shift = 11
50
+ else:
51
+ raise NotImplementedError(f'Not supported size')
52
+
53
+ args.base_seed = args.base_seed if args.base_seed >= 0 else random.randint(
54
+ 0, 99999999)
55
+ # Size check
56
+ assert args.size in SUPPORTED_SIZES[
57
+ args.
58
+ task], f"Unsupport size {args.size} for task {args.task}, supported sizes are: {', '.join(SUPPORTED_SIZES[args.task])}"
59
+
60
+
61
+ def _parse_args():
62
+ parser = argparse.ArgumentParser(
63
+ description="Generate a image or video from a text prompt or image using Wan"
64
+ )
65
+ parser.add_argument(
66
+ "--task",
67
+ type=str,
68
+ default="infinitetalk-14B",
69
+ choices=list(WAN_CONFIGS.keys()),
70
+ help="The task to run.")
71
+ parser.add_argument(
72
+ "--size",
73
+ type=str,
74
+ default="infinitetalk-480",
75
+ choices=list(SIZE_CONFIGS.keys()),
76
+ help="The buckget size of the generated video. The aspect ratio of the output video will follow that of the input image."
77
+ )
78
+ parser.add_argument(
79
+ "--frame_num",
80
+ type=int,
81
+ default=81,
82
+ help="How many frames to be generated in one clip. The number should be 4n+1"
83
+ )
84
+ parser.add_argument(
85
+ "--ckpt_dir",
86
+ type=str,
87
+ default='./weights/Wan2.1-I2V-14B-480P',
88
+ help="The path to the Wan checkpoint directory.")
89
+ parser.add_argument(
90
+ "--quant_dir",
91
+ type=str,
92
+ default=None,
93
+ help="The path to the Wan quant checkpoint directory.")
94
+ parser.add_argument(
95
+ "--infinitetalk_dir",
96
+ type=str,
97
+ default='weights/InfiniteTalk/single/infinitetalk.safetensors',
98
+ help="The path to the InfiniteTalk checkpoint directory.")
99
+ parser.add_argument(
100
+ "--wav2vec_dir",
101
+ type=str,
102
+ default='./weights/chinese-wav2vec2-base',
103
+ help="The path to the wav2vec checkpoint directory.")
104
+ parser.add_argument(
105
+ "--dit_path",
106
+ type=str,
107
+ default=None,
108
+ help="The path to the Wan checkpoint directory.")
109
+ parser.add_argument(
110
+ "--lora_dir",
111
+ type=str,
112
+ nargs='+',
113
+ default=None,
114
+ help="The path to the LoRA checkpoint directory.")
115
+ parser.add_argument(
116
+ "--lora_scale",
117
+ type=float,
118
+ nargs='+',
119
+ default=[1.2],
120
+ help="Controls how much to influence the outputs with the LoRA parameters. Accepts multiple float values."
121
+ )
122
+ parser.add_argument(
123
+ "--offload_model",
124
+ type=str2bool,
125
+ default=None,
126
+ help="Whether to offload the model to CPU after each model forward, reducing GPU memory usage."
127
+ )
128
+ parser.add_argument(
129
+ "--ulysses_size",
130
+ type=int,
131
+ default=1,
132
+ help="The size of the ulysses parallelism in DiT.")
133
+ parser.add_argument(
134
+ "--ring_size",
135
+ type=int,
136
+ default=1,
137
+ help="The size of the ring attention parallelism in DiT.")
138
+ parser.add_argument(
139
+ "--t5_fsdp",
140
+ action="store_true",
141
+ default=False,
142
+ help="Whether to use FSDP for T5.")
143
+ parser.add_argument(
144
+ "--t5_cpu",
145
+ action="store_true",
146
+ default=False,
147
+ help="Whether to place T5 model on CPU.")
148
+ parser.add_argument(
149
+ "--dit_fsdp",
150
+ action="store_true",
151
+ default=False,
152
+ help="Whether to use FSDP for DiT.")
153
+ parser.add_argument(
154
+ "--save_file",
155
+ type=str,
156
+ default=None,
157
+ help="The file to save the generated image or video to.")
158
+ parser.add_argument(
159
+ "--audio_save_dir",
160
+ type=str,
161
+ default='save_audio/gradio',
162
+ help="The path to save the audio embedding.")
163
+ parser.add_argument(
164
+ "--base_seed",
165
+ type=int,
166
+ default=42,
167
+ help="The seed to use for generating the image or video.")
168
+ parser.add_argument(
169
+ "--input_json",
170
+ type=str,
171
+ default='examples.json',
172
+ help="[meta file] The condition path to generate the video.")
173
+ parser.add_argument(
174
+ "--motion_frame",
175
+ type=int,
176
+ default=9,
177
+ help="Driven frame length used in the mode of long video genration.")
178
+ parser.add_argument(
179
+ "--mode",
180
+ type=str,
181
+ default="streaming",
182
+ choices=['clip', 'streaming'],
183
+ help="clip: generate one video chunk, streaming: long video generation")
184
+ parser.add_argument(
185
+ "--sample_steps", type=int, default=None, help="The sampling steps.")
186
+ parser.add_argument(
187
+ "--sample_shift",
188
+ type=float,
189
+ default=None,
190
+ help="Sampling shift factor for flow matching schedulers.")
191
+ parser.add_argument(
192
+ "--sample_text_guide_scale",
193
+ type=float,
194
+ default=5.0,
195
+ help="Classifier free guidance scale for text control.")
196
+ parser.add_argument(
197
+ "--sample_audio_guide_scale",
198
+ type=float,
199
+ default=4.0,
200
+ help="Classifier free guidance scale for audio control.")
201
+ parser.add_argument(
202
+ "--num_persistent_param_in_dit",
203
+ type=int,
204
+ default=None,
205
+ required=False,
206
+ help="Maximum parameter quantity retained in video memory, small number to reduce VRAM required",
207
+ )
208
+ parser.add_argument(
209
+ "--use_teacache",
210
+ action="store_true",
211
+ default=False,
212
+ help="Enable teacache for video generation."
213
+ )
214
+ parser.add_argument(
215
+ "--teacache_thresh",
216
+ type=float,
217
+ default=0.2,
218
+ help="Threshold for teacache."
219
+ )
220
+ parser.add_argument(
221
+ "--use_apg",
222
+ action="store_true",
223
+ default=False,
224
+ help="Enable adaptive projected guidance for video generation (APG)."
225
+ )
226
+ parser.add_argument(
227
+ "--apg_momentum",
228
+ type=float,
229
+ default=-0.75,
230
+ help="Momentum used in adaptive projected guidance (APG)."
231
+ )
232
+ parser.add_argument(
233
+ "--apg_norm_threshold",
234
+ type=float,
235
+ default=55,
236
+ help="Norm threshold used in adaptive projected guidance (APG)."
237
+ )
238
+ parser.add_argument(
239
+ "--color_correction_strength",
240
+ type=float,
241
+ default=1.0,
242
+ help="strength for color correction [0.0 -- 1.0]."
243
+ )
244
+
245
+ parser.add_argument(
246
+ "--quant",
247
+ type=str,
248
+ default=None,
249
+ help="Quantization type, must be 'int8' or 'fp8'."
250
+ )
251
+ args = parser.parse_args()
252
+ _validate_args(args)
253
+ return args
254
+
255
+
256
+ def custom_init(device, wav2vec):
257
+ audio_encoder = Wav2Vec2Model.from_pretrained(wav2vec, local_files_only=True).to(device)
258
+ audio_encoder.feature_extractor._freeze_parameters()
259
+ wav2vec_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(wav2vec, local_files_only=True)
260
+ return wav2vec_feature_extractor, audio_encoder
261
+
262
+ def loudness_norm(audio_array, sr=16000, lufs=-23):
263
+ meter = pyln.Meter(sr)
264
+ loudness = meter.integrated_loudness(audio_array)
265
+ if abs(loudness) > 100:
266
+ return audio_array
267
+ normalized_audio = pyln.normalize.loudness(audio_array, loudness, lufs)
268
+ return normalized_audio
269
+
270
+ def audio_prepare_multi(left_path, right_path, audio_type, sample_rate=16000):
271
+ if not (left_path=='None' or right_path=='None'):
272
+ human_speech_array1 = audio_prepare_single(left_path)
273
+ human_speech_array2 = audio_prepare_single(right_path)
274
+ elif left_path=='None':
275
+ human_speech_array2 = audio_prepare_single(right_path)
276
+ human_speech_array1 = np.zeros(human_speech_array2.shape[0])
277
+ elif right_path=='None':
278
+ human_speech_array1 = audio_prepare_single(left_path)
279
+ human_speech_array2 = np.zeros(human_speech_array1.shape[0])
280
+
281
+ if audio_type=='para':
282
+ new_human_speech1 = human_speech_array1
283
+ new_human_speech2 = human_speech_array2
284
+ elif audio_type=='add':
285
+ new_human_speech1 = np.concatenate([human_speech_array1[: human_speech_array1.shape[0]], np.zeros(human_speech_array2.shape[0])])
286
+ new_human_speech2 = np.concatenate([np.zeros(human_speech_array1.shape[0]), human_speech_array2[:human_speech_array2.shape[0]]])
287
+ sum_human_speechs = new_human_speech1 + new_human_speech2
288
+ return new_human_speech1, new_human_speech2, sum_human_speechs
289
+
290
+ def _init_logging(rank):
291
+ # logging
292
+ if rank == 0:
293
+ # set format
294
+ logging.basicConfig(
295
+ level=logging.INFO,
296
+ format="[%(asctime)s] %(levelname)s: %(message)s",
297
+ handlers=[logging.StreamHandler(stream=sys.stdout)])
298
+ else:
299
+ logging.basicConfig(level=logging.ERROR)
300
+
301
+ def get_embedding(speech_array, wav2vec_feature_extractor, audio_encoder, sr=16000, device='cpu'):
302
+ audio_duration = len(speech_array) / sr
303
+ video_length = audio_duration * 25 # Assume the video fps is 25
304
+
305
+ # wav2vec_feature_extractor
306
+ audio_feature = np.squeeze(
307
+ wav2vec_feature_extractor(speech_array, sampling_rate=sr).input_values
308
+ )
309
+ audio_feature = torch.from_numpy(audio_feature).float().to(device=device)
310
+ audio_feature = audio_feature.unsqueeze(0)
311
+
312
+ # audio encoder
313
+ with torch.no_grad():
314
+ embeddings = audio_encoder(audio_feature, seq_len=int(video_length), output_hidden_states=True)
315
+
316
+ if len(embeddings) == 0:
317
+ print("Fail to extract audio embedding")
318
+ return None
319
+
320
+ audio_emb = torch.stack(embeddings.hidden_states[1:], dim=1).squeeze(0)
321
+ audio_emb = rearrange(audio_emb, "b s d -> s b d")
322
+
323
+ audio_emb = audio_emb.cpu().detach()
324
+ return audio_emb
325
+
326
+ def extract_audio_from_video(filename, sample_rate):
327
+ raw_audio_path = filename.split('/')[-1].split('.')[0]+'.wav'
328
+ ffmpeg_command = [
329
+ "ffmpeg",
330
+ "-y",
331
+ "-i",
332
+ str(filename),
333
+ "-vn",
334
+ "-acodec",
335
+ "pcm_s16le",
336
+ "-ar",
337
+ "16000",
338
+ "-ac",
339
+ "2",
340
+ str(raw_audio_path),
341
+ ]
342
+ subprocess.run(ffmpeg_command, check=True)
343
+ human_speech_array, sr = librosa.load(raw_audio_path, sr=sample_rate)
344
+ human_speech_array = loudness_norm(human_speech_array, sr)
345
+ os.remove(raw_audio_path)
346
+
347
+ return human_speech_array
348
+
349
+ def audio_prepare_single(audio_path, sample_rate=16000):
350
+ ext = os.path.splitext(audio_path)[1].lower()
351
+ if ext in ['.mp4', '.mov', '.avi', '.mkv']:
352
+ human_speech_array = extract_audio_from_video(audio_path, sample_rate)
353
+ return human_speech_array
354
+ else:
355
+ human_speech_array, sr = librosa.load(audio_path, sr=sample_rate)
356
+ human_speech_array = loudness_norm(human_speech_array, sr)
357
+ return human_speech_array
358
+
359
+ def process_tts_single(text, save_dir, voice1):
360
+ s1_sentences = []
361
+
362
+ pipeline = KPipeline(lang_code='a', repo_id='weights/Kokoro-82M')
363
+
364
+ voice_tensor = torch.load(voice1, weights_only=True)
365
+ generator = pipeline(
366
+ text, voice=voice_tensor, # <= change voice here
367
+ speed=1, split_pattern=r'\n+'
368
+ )
369
+ audios = []
370
+ for i, (gs, ps, audio) in enumerate(generator):
371
+ audios.append(audio)
372
+ audios = torch.concat(audios, dim=0)
373
+ s1_sentences.append(audios)
374
+ s1_sentences = torch.concat(s1_sentences, dim=0)
375
+ save_path1 =f'{save_dir}/s1.wav'
376
+ sf.write(save_path1, s1_sentences, 24000) # save each audio file
377
+ s1, _ = librosa.load(save_path1, sr=16000)
378
+ return s1, save_path1
379
+
380
+
381
+
382
+ def process_tts_multi(text, save_dir, voice1, voice2):
383
+ pattern = r'\(s(\d+)\)\s*(.*?)(?=\s*\(s\d+\)|$)'
384
+ matches = re.findall(pattern, text, re.DOTALL)
385
+
386
+ s1_sentences = []
387
+ s2_sentences = []
388
+
389
+ pipeline = KPipeline(lang_code='a', repo_id='weights/Kokoro-82M')
390
+ for idx, (speaker, content) in enumerate(matches):
391
+ if speaker == '1':
392
+ voice_tensor = torch.load(voice1, weights_only=True)
393
+ generator = pipeline(
394
+ content, voice=voice_tensor, # <= change voice here
395
+ speed=1, split_pattern=r'\n+'
396
+ )
397
+ audios = []
398
+ for i, (gs, ps, audio) in enumerate(generator):
399
+ audios.append(audio)
400
+ audios = torch.concat(audios, dim=0)
401
+ s1_sentences.append(audios)
402
+ s2_sentences.append(torch.zeros_like(audios))
403
+ elif speaker == '2':
404
+ voice_tensor = torch.load(voice2, weights_only=True)
405
+ generator = pipeline(
406
+ content, voice=voice_tensor, # <= change voice here
407
+ speed=1, split_pattern=r'\n+'
408
+ )
409
+ audios = []
410
+ for i, (gs, ps, audio) in enumerate(generator):
411
+ audios.append(audio)
412
+ audios = torch.concat(audios, dim=0)
413
+ s2_sentences.append(audios)
414
+ s1_sentences.append(torch.zeros_like(audios))
415
+
416
+ s1_sentences = torch.concat(s1_sentences, dim=0)
417
+ s2_sentences = torch.concat(s2_sentences, dim=0)
418
+ sum_sentences = s1_sentences + s2_sentences
419
+ save_path1 =f'{save_dir}/s1.wav'
420
+ save_path2 =f'{save_dir}/s2.wav'
421
+ save_path_sum = f'{save_dir}/sum.wav'
422
+ sf.write(save_path1, s1_sentences, 24000) # save each audio file
423
+ sf.write(save_path2, s2_sentences, 24000)
424
+ sf.write(save_path_sum, sum_sentences, 24000)
425
+
426
+ s1, _ = librosa.load(save_path1, sr=16000)
427
+ s2, _ = librosa.load(save_path2, sr=16000)
428
+ # sum, _ = librosa.load(save_path_sum, sr=16000)
429
+ return s1, s2, save_path_sum
430
+
431
+ def run_graio_demo(args):
432
+ rank = int(os.getenv("RANK", 0))
433
+ world_size = int(os.getenv("WORLD_SIZE", 1))
434
+ local_rank = int(os.getenv("LOCAL_RANK", 0))
435
+ device = local_rank
436
+ _init_logging(rank)
437
+
438
+ if args.offload_model is None:
439
+ args.offload_model = False if world_size > 1 else True
440
+ logging.info(
441
+ f"offload_model is not specified, set to {args.offload_model}.")
442
+ if world_size > 1:
443
+ torch.cuda.set_device(local_rank)
444
+ dist.init_process_group(
445
+ backend="nccl",
446
+ init_method="env://",
447
+ rank=rank,
448
+ world_size=world_size)
449
+ else:
450
+ assert not (
451
+ args.t5_fsdp or args.dit_fsdp
452
+ ), f"t5_fsdp and dit_fsdp are not supported in non-distributed environments."
453
+ assert not (
454
+ args.ulysses_size > 1 or args.ring_size > 1
455
+ ), f"context parallel are not supported in non-distributed environments."
456
+
457
+ if args.ulysses_size > 1 or args.ring_size > 1:
458
+ assert args.ulysses_size * args.ring_size == world_size, f"The number of ulysses_size and ring_size should be equal to the world size."
459
+ from xfuser.core.distributed import (
460
+ init_distributed_environment,
461
+ initialize_model_parallel,
462
+ )
463
+ init_distributed_environment(
464
+ rank=dist.get_rank(), world_size=dist.get_world_size())
465
+
466
+ initialize_model_parallel(
467
+ sequence_parallel_degree=dist.get_world_size(),
468
+ ring_degree=args.ring_size,
469
+ ulysses_degree=args.ulysses_size,
470
+ )
471
+
472
+
473
+ cfg = WAN_CONFIGS[args.task]
474
+ if args.ulysses_size > 1:
475
+ assert cfg.num_heads % args.ulysses_size == 0, f"`{cfg.num_heads=}` cannot be divided evenly by `{args.ulysses_size=}`."
476
+
477
+ logging.info(f"Generation job args: {args}")
478
+ logging.info(f"Generation model config: {cfg}")
479
+
480
+ if dist.is_initialized():
481
+ base_seed = [args.base_seed] if rank == 0 else [None]
482
+ dist.broadcast_object_list(base_seed, src=0)
483
+ args.base_seed = base_seed[0]
484
+
485
+ assert args.task == "infinitetalk-14B", 'You should choose multitalk in args.task.'
486
+
487
+
488
+
489
+ wav2vec_feature_extractor, audio_encoder= custom_init('cpu', args.wav2vec_dir)
490
+ os.makedirs(args.audio_save_dir,exist_ok=True)
491
+
492
+
493
+ logging.info("Creating MultiTalk pipeline.")
494
+ wan_i2v = wan.InfiniteTalkPipeline(
495
+ config=cfg,
496
+ checkpoint_dir=args.ckpt_dir,
497
+ quant_dir=args.quant_dir,
498
+ device_id=device,
499
+ rank=rank,
500
+ t5_fsdp=args.t5_fsdp,
501
+ dit_fsdp=args.dit_fsdp,
502
+ use_usp=(args.ulysses_size > 1 or args.ring_size > 1),
503
+ t5_cpu=args.t5_cpu,
504
+ lora_dir=args.lora_dir,
505
+ lora_scales=args.lora_scale,
506
+ quant=args.quant,
507
+ dit_path=args.dit_path,
508
+ infinitetalk_dir=args.infinitetalk_dir
509
+ )
510
+
511
+ if args.num_persistent_param_in_dit is not None:
512
+ wan_i2v.vram_management = True
513
+ wan_i2v.enable_vram_management(
514
+ num_persistent_param_in_dit=args.num_persistent_param_in_dit
515
+ )
516
+
517
+
518
+
519
+ def generate_video(img2vid_image, vid2vid_vid, task_mode, img2vid_prompt, n_prompt, img2vid_audio_1, img2vid_audio_2,
520
+ sd_steps, seed, text_guide_scale, audio_guide_scale, mode_selector, tts_text, resolution_select, human1_voice, human2_voice):
521
+ input_data = {}
522
+ input_data["prompt"] = img2vid_prompt
523
+ if task_mode=='VideoDubbing':
524
+ input_data["cond_video"] = vid2vid_vid
525
+ else:
526
+ input_data["cond_video"] = img2vid_image
527
+ person = {}
528
+ if mode_selector == "Single Person(Local File)":
529
+ person['person1'] = img2vid_audio_1
530
+ elif mode_selector == "Single Person(TTS)":
531
+ tts_audio = {}
532
+ tts_audio['text'] = tts_text
533
+ tts_audio['human1_voice'] = human1_voice
534
+ input_data["tts_audio"] = tts_audio
535
+ elif mode_selector == "Multi Person(Local File, audio add)":
536
+ person['person1'] = img2vid_audio_1
537
+ person['person2'] = img2vid_audio_2
538
+ input_data["audio_type"] = 'add'
539
+ elif mode_selector == "Multi Person(Local File, audio parallel)":
540
+ person['person1'] = img2vid_audio_1
541
+ person['person2'] = img2vid_audio_2
542
+ input_data["audio_type"] = 'para'
543
+ else:
544
+ tts_audio = {}
545
+ tts_audio['text'] = tts_text
546
+ tts_audio['human1_voice'] = human1_voice
547
+ tts_audio['human2_voice'] = human2_voice
548
+ input_data["tts_audio"] = tts_audio
549
+
550
+ input_data["cond_audio"] = person
551
+
552
+ if 'Local File' in mode_selector:
553
+ if len(input_data['cond_audio'])==2:
554
+ new_human_speech1, new_human_speech2, sum_human_speechs = audio_prepare_multi(input_data['cond_audio']['person1'], input_data['cond_audio']['person2'], input_data['audio_type'])
555
+ audio_embedding_1 = get_embedding(new_human_speech1, wav2vec_feature_extractor, audio_encoder)
556
+ audio_embedding_2 = get_embedding(new_human_speech2, wav2vec_feature_extractor, audio_encoder)
557
+ emb1_path = os.path.join(args.audio_save_dir, '1.pt')
558
+ emb2_path = os.path.join(args.audio_save_dir, '2.pt')
559
+ sum_audio = os.path.join(args.audio_save_dir, 'sum.wav')
560
+ sf.write(sum_audio, sum_human_speechs, 16000)
561
+ torch.save(audio_embedding_1, emb1_path)
562
+ torch.save(audio_embedding_2, emb2_path)
563
+ input_data['cond_audio']['person1'] = emb1_path
564
+ input_data['cond_audio']['person2'] = emb2_path
565
+ input_data['video_audio'] = sum_audio
566
+ elif len(input_data['cond_audio'])==1:
567
+ human_speech = audio_prepare_single(input_data['cond_audio']['person1'])
568
+ audio_embedding = get_embedding(human_speech, wav2vec_feature_extractor, audio_encoder)
569
+ emb_path = os.path.join(args.audio_save_dir, '1.pt')
570
+ sum_audio = os.path.join(args.audio_save_dir, 'sum.wav')
571
+ sf.write(sum_audio, human_speech, 16000)
572
+ torch.save(audio_embedding, emb_path)
573
+ input_data['cond_audio']['person1'] = emb_path
574
+ input_data['video_audio'] = sum_audio
575
+ elif 'TTS' in mode_selector:
576
+ if 'human2_voice' not in input_data['tts_audio'].keys():
577
+ new_human_speech1, sum_audio = process_tts_single(input_data['tts_audio']['text'], args.audio_save_dir, input_data['tts_audio']['human1_voice'])
578
+ audio_embedding_1 = get_embedding(new_human_speech1, wav2vec_feature_extractor, audio_encoder)
579
+ emb1_path = os.path.join(args.audio_save_dir, '1.pt')
580
+ torch.save(audio_embedding_1, emb1_path)
581
+ input_data['cond_audio']['person1'] = emb1_path
582
+ input_data['video_audio'] = sum_audio
583
+ else:
584
+ new_human_speech1, new_human_speech2, sum_audio = process_tts_multi(input_data['tts_audio']['text'], args.audio_save_dir, input_data['tts_audio']['human1_voice'], input_data['tts_audio']['human2_voice'])
585
+ audio_embedding_1 = get_embedding(new_human_speech1, wav2vec_feature_extractor, audio_encoder)
586
+ audio_embedding_2 = get_embedding(new_human_speech2, wav2vec_feature_extractor, audio_encoder)
587
+ emb1_path = os.path.join(args.audio_save_dir, '1.pt')
588
+ emb2_path = os.path.join(args.audio_save_dir, '2.pt')
589
+ torch.save(audio_embedding_1, emb1_path)
590
+ torch.save(audio_embedding_2, emb2_path)
591
+ input_data['cond_audio']['person1'] = emb1_path
592
+ input_data['cond_audio']['person2'] = emb2_path
593
+ input_data['video_audio'] = sum_audio
594
+
595
+
596
+ # if len(input_data['cond_audio'])==2:
597
+ # new_human_speech1, new_human_speech2, sum_human_speechs = audio_prepare_multi(input_data['cond_audio']['person1'], input_data['cond_audio']['person2'], input_data['audio_type'])
598
+ # audio_embedding_1 = get_embedding(new_human_speech1, wav2vec_feature_extractor, audio_encoder)
599
+ # audio_embedding_2 = get_embedding(new_human_speech2, wav2vec_feature_extractor, audio_encoder)
600
+ # emb1_path = os.path.join(args.audio_save_dir, '1.pt')
601
+ # emb2_path = os.path.join(args.audio_save_dir, '2.pt')
602
+ # sum_audio = os.path.join(args.audio_save_dir, 'sum.wav')
603
+ # sf.write(sum_audio, sum_human_speechs, 16000)
604
+ # torch.save(audio_embedding_1, emb1_path)
605
+ # torch.save(audio_embedding_2, emb2_path)
606
+ # input_data['cond_audio']['person1'] = emb1_path
607
+ # input_data['cond_audio']['person2'] = emb2_path
608
+ # input_data['video_audio'] = sum_audio
609
+ # elif len(input_data['cond_audio'])==1:
610
+ # human_speech = audio_prepare_single(input_data['cond_audio']['person1'])
611
+ # audio_embedding = get_embedding(human_speech, wav2vec_feature_extractor, audio_encoder)
612
+ # emb_path = os.path.join(args.audio_save_dir, '1.pt')
613
+ # sum_audio = os.path.join(args.audio_save_dir, 'sum.wav')
614
+ # sf.write(sum_audio, human_speech, 16000)
615
+ # torch.save(audio_embedding, emb_path)
616
+ # input_data['cond_audio']['person1'] = emb_path
617
+ # input_data['video_audio'] = sum_audio
618
+
619
+ logging.info("Generating video ...")
620
+ video = wan_i2v.generate_infinitetalk(
621
+ input_data,
622
+ size_buckget=resolution_select,
623
+ motion_frame=args.motion_frame,
624
+ frame_num=args.frame_num,
625
+ shift=args.sample_shift,
626
+ sampling_steps=sd_steps,
627
+ text_guide_scale=text_guide_scale,
628
+ audio_guide_scale=audio_guide_scale,
629
+ seed=seed,
630
+ n_prompt=n_prompt,
631
+ offload_model=args.offload_model,
632
+ max_frames_num=args.frame_num if args.mode == 'clip' else 1000,
633
+ color_correction_strength = args.color_correction_strength,
634
+ extra_args=args,
635
+ )
636
+
637
+
638
+ if args.save_file is None:
639
+ formatted_time = datetime.now().strftime("%Y%m%d_%H%M%S")
640
+ formatted_prompt = input_data['prompt'].replace(" ", "_").replace("/",
641
+ "_")[:50]
642
+ args.save_file = f"{args.task}_{args.size.replace('*','x') if sys.platform=='win32' else args.size}_{args.ulysses_size}_{args.ring_size}_{formatted_prompt}_{formatted_time}"
643
+
644
+ logging.info(f"Saving generated video to {args.save_file}.mp4")
645
+ save_video_ffmpeg(video, args.save_file, [input_data['video_audio']], high_quality_save=False)
646
+ logging.info("Finished.")
647
+
648
+ return args.save_file + '.mp4'
649
+
650
+ def toggle_audio_mode(mode):
651
+ if 'TTS' in mode:
652
+ return [
653
+ gr.Audio(visible=False, interactive=False),
654
+ gr.Audio(visible=False, interactive=False),
655
+ gr.Textbox(visible=True, interactive=True)
656
+ ]
657
+ elif 'Single' in mode:
658
+ return [
659
+ gr.Audio(visible=True, interactive=True),
660
+ gr.Audio(visible=False, interactive=False),
661
+ gr.Textbox(visible=False, interactive=False)
662
+ ]
663
+ else:
664
+ return [
665
+ gr.Audio(visible=True, interactive=True),
666
+ gr.Audio(visible=True, interactive=True),
667
+ gr.Textbox(visible=False, interactive=False)
668
+ ]
669
+
670
+ def show_upload(mode):
671
+ if mode == "SingleImageDriven":
672
+ return gr.update(visible=True), gr.update(visible=False)
673
+ else:
674
+ return gr.update(visible=False), gr.update(visible=True)
675
+
676
+
677
+ with gr.Blocks() as demo:
678
+
679
+ gr.Markdown("""
680
+ <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
681
+ MeiGen-InfiniteTalk
682
+ </div>
683
+ <div style="text-align: center; font-size: 16px; font-weight: normal; margin-bottom: 20px;">
684
+ InfiniteTalk: Audio-driven Video Generation for Spare-Frame Video Dubbing.
685
+ </div>
686
+ <div style="display: flex; justify-content: center; gap: 10px; flex-wrap: wrap;">
687
+ <a href=''><img src='https://img.shields.io/badge/Project-Page-blue'></a>
688
+ <a href=''><img src='https://img.shields.io/badge/%F0%9F%A4%97%20HuggingFace-Model-yellow'></a>
689
+ <a href=''><img src='https://img.shields.io/badge/Paper-Arxiv-red'></a>
690
+ </div>
691
+
692
+
693
+ """)
694
+
695
+ with gr.Row():
696
+ with gr.Column(scale=1):
697
+ task_mode = gr.Radio(
698
+ choices=["SingleImageDriven", "VideoDubbing"],
699
+ label="Choose SingleImageDriven task or VideoDubbing task",
700
+ value="VideoDubbing"
701
+ )
702
+ vid2vid_vid = gr.Video(
703
+ label="Upload Input Video",
704
+ visible=True)
705
+ img2vid_image = gr.Image(
706
+ type="filepath",
707
+ label="Upload Input Image",
708
+ elem_id="image_upload",
709
+ visible=False
710
+ )
711
+ img2vid_prompt = gr.Textbox(
712
+ label="Prompt",
713
+ placeholder="Describe the video you want to generate",
714
+ )
715
+ task_mode.change(
716
+ fn=show_upload,
717
+ inputs=task_mode,
718
+ outputs=[img2vid_image, vid2vid_vid]
719
+ )
720
+
721
+
722
+ with gr.Accordion("Audio Options", open=True):
723
+ mode_selector = gr.Radio(
724
+ choices=["Single Person(Local File)", "Single Person(TTS)", "Multi Person(Local File, audio add)", "Multi Person(Local File, audio parallel)", "Multi Person(TTS)"],
725
+ label="Select person and audio mode.",
726
+ value="Single Person(Local File)"
727
+ )
728
+ resolution_select = gr.Radio(
729
+ choices=["infinitetalk-480", "infinitetalk-720"],
730
+ label="Select resolution.",
731
+ value="infinitetalk-480"
732
+ )
733
+ img2vid_audio_1 = gr.Audio(label="Conditioning Audio for speaker 1", type="filepath", visible=True)
734
+ img2vid_audio_2 = gr.Audio(label="Conditioning Audio for speaker 2", type="filepath", visible=False)
735
+ tts_text = gr.Textbox(
736
+ label="Text for TTS",
737
+ placeholder="Refer to the format in the examples",
738
+ visible=False,
739
+ interactive=False
740
+ )
741
+ mode_selector.change(
742
+ fn=toggle_audio_mode,
743
+ inputs=mode_selector,
744
+ outputs=[img2vid_audio_1, img2vid_audio_2, tts_text]
745
+ )
746
+
747
+ with gr.Accordion("Advanced Options", open=False):
748
+ with gr.Row():
749
+ sd_steps = gr.Slider(
750
+ label="Diffusion steps",
751
+ minimum=1,
752
+ maximum=1000,
753
+ value=8,
754
+ step=1)
755
+ seed = gr.Slider(
756
+ label="Seed",
757
+ minimum=-1,
758
+ maximum=2147483647,
759
+ step=1,
760
+ value=42)
761
+ with gr.Row():
762
+ text_guide_scale = gr.Slider(
763
+ label="Text Guide scale",
764
+ minimum=0,
765
+ maximum=20,
766
+ value=1.0,
767
+ step=1)
768
+ audio_guide_scale = gr.Slider(
769
+ label="Audio Guide scale",
770
+ minimum=0,
771
+ maximum=20,
772
+ value=2.0,
773
+ step=1)
774
+ with gr.Row():
775
+ human1_voice = gr.Textbox(
776
+ label="Voice for the left person",
777
+ value="weights/Kokoro-82M/voices/am_adam.pt",
778
+ )
779
+ human2_voice = gr.Textbox(
780
+ label="Voice for right person",
781
+ value="weights/Kokoro-82M/voices/af_heart.pt"
782
+ )
783
+ # with gr.Row():
784
+ n_prompt = gr.Textbox(
785
+ label="Negative Prompt",
786
+ placeholder="Describe the negative prompt you want to add",
787
+ value="bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards"
788
+ )
789
+
790
+ run_i2v_button = gr.Button("Generate Video")
791
+
792
+ with gr.Column(scale=2):
793
+ result_gallery = gr.Video(
794
+ label='Generated Video', interactive=False, height=600, )
795
+
796
+ gr.Examples(
797
+ examples = [
798
+ ['SingleImageDriven', 'examples/single/ref_image.png', None, "A woman is passionately singing into a professional microphone in a recording studio. She wears large black headphones and a dark cardigan over a gray top. Her long, wavy brown hair frames her face as she looks slightly upwards, her mouth open mid-song. The studio is equipped with various audio equipment, including a mixing console and a keyboard, with soundproofing panels on the walls. The lighting is warm and focused on her, creating a professional and intimate atmosphere. A close-up shot captures her expressive performance.", "Single Person(Local File)", "examples/single/1.wav", None, None],
799
+ ['VideoDubbing', None, 'examples/single/ref_video.mp4', "A man is talking", "Single Person(Local File)", "examples/single/1.wav", None, None],
800
+
801
+ ],
802
+ inputs = [task_mode, img2vid_image, vid2vid_vid, img2vid_prompt, mode_selector, img2vid_audio_1, img2vid_audio_2, tts_text],
803
+ )
804
+
805
+
806
+ run_i2v_button.click(
807
+ fn=generate_video,
808
+ inputs=[img2vid_image, vid2vid_vid, task_mode, img2vid_prompt, n_prompt, img2vid_audio_1, img2vid_audio_2,sd_steps, seed, text_guide_scale, audio_guide_scale, mode_selector, tts_text, resolution_select, human1_voice, human2_voice],
809
+ outputs=[result_gallery],
810
+ )
811
+ demo.launch(server_name="0.0.0.0", debug=True, server_port=8418)
812
+
813
+
814
 
815
 
816
  if __name__ == "__main__":
817
+ args = _parse_args()
818
+ run_graio_demo(args)
819
+
requirements.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ opencv-python>=4.9.0.80
2
+ diffusers>=0.31.0
3
+ transformers>=4.49.0
4
+ tokenizers>=0.20.3
5
+ accelerate>=1.1.1
6
+ tqdm
7
+ imageio
8
+ easydict
9
+ ftfy
10
+ dashscope
11
+ imageio-ffmpeg
12
+ scikit-image
13
+ loguru
14
+ gradio>=5.0.0
15
+ numpy>=1.23.5,<2
16
+ xfuser>=0.4.1
17
+ pyloudnorm
18
+ optimum-quanto==0.2.6
19
+ scenedetect
20
+ moviepy==1.0.3
21
+ decord