woak commited on
Commit
3a55fb8
·
1 Parent(s): abec288
app.py CHANGED
@@ -2,17 +2,14 @@ import os
2
  import os.path as osp
3
  import sys
4
  import tempfile
 
5
 
6
  import gradio as gr
7
- import librosa
8
  import soundfile
9
  import torch
10
  import torch.nn.functional as F
11
- import torchaudio
12
  from huggingface_hub import snapshot_download
13
- from moviepy import VideoFileClip
14
- from pydub import AudioSegment
15
- from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, AutoTokenizer, pipeline
16
 
17
  from src.internvl.eval import load_video
18
  from src.moviedubber.infer.utils_infer import (
@@ -22,7 +19,7 @@ from src.moviedubber.infer.utils_infer import (
22
  sway_sampling_coef,
23
  )
24
  from src.moviedubber.infer.video_preprocess import VideoFeatureExtractor
25
- from src.moviedubber.infer_with_mmlm_result import concat_movie_with_audio, get_spk_emb, load_models
26
  from src.moviedubber.model.utils import convert_char_to_pinyin
27
 
28
 
@@ -32,25 +29,6 @@ sys.path.append("src/third_party/BigVGAN")
32
  from InternVL.internvl_chat.internvl.model.internvl_chat.modeling_internvl_chat import InternVLChatModel # type: ignore
33
 
34
 
35
- def load_asr_model(model_id="openai/whisper-large-v3-turbo"):
36
- torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
37
- model = AutoModelForSpeechSeq2Seq.from_pretrained(
38
- model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, use_safetensors=True
39
- ).to(device)
40
-
41
- processor = AutoProcessor.from_pretrained(model_id)
42
-
43
- pipe = pipeline(
44
- "automatic-speech-recognition",
45
- model=model,
46
- tokenizer=processor.tokenizer,
47
- feature_extractor=processor.feature_extractor,
48
- torch_dtype=torch_dtype,
49
- device=device,
50
- )
51
- return pipe
52
-
53
-
54
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
55
 
56
  repo_local_path = snapshot_download(repo_id="woak-oa/DeepDubber-V1")
@@ -69,7 +47,6 @@ generation_config = dict(max_new_tokens=1024, do_sample=False)
69
 
70
 
71
  ema_model, vocoder, ort_session = load_models(repo_local_path, device=device)
72
- asr_pipe = load_asr_model()
73
 
74
  videofeature_extractor = VideoFeatureExtractor(device=device)
75
 
@@ -106,60 +83,26 @@ def deepdubber(video_path: str, subtitle_text: str, audio_path: str = None) -> s
106
  gen_clip = videofeature_extractor.extract_features(video_path)
107
  gen_text = subtitle_text
108
 
109
- clip = VideoFileClip(video_path)
110
- gen_audio_len = int(clip.duration * 24000 // 256)
111
 
112
  gen_clip = gen_clip.unsqueeze(0).to(device=device, dtype=torch.float32).transpose(1, 2)
113
  gen_clip = F.interpolate(gen_clip, size=(gen_audio_len,), mode="linear", align_corners=False).transpose(1, 2)
114
 
115
- ref_audio_len = None
116
  if audio_path is not None:
117
- print("reference audio is not None, dubbing with reference audio")
118
-
119
- if audio_path.endswith(".mp3"):
120
- audio = AudioSegment.from_mp3(audio_path)
121
-
122
- wav_file = audio_path.replace(".mp3", ".wav")
123
- audio.export(wav_file, format="wav")
124
- else:
125
- wav_file = audio_path
126
-
127
- ref_text = asr_pipe(librosa.load(wav_file, sr=16000)[0], generate_kwargs={"language": "english"})["text"]
128
- ref_text = ref_text.replace("\n", " ").replace("\r", " ")
129
- print(f"Reference text: {ref_text}")
130
-
131
- spk_emb = get_spk_emb(wav_file, ort_session)
132
  spk_emb = torch.tensor(spk_emb).to(device=device, dtype=torch.float32).unsqueeze(0).unsqueeze(0)
133
-
134
- audio_data, sr = torchaudio.load(wav_file)
135
- resampler = torchaudio.transforms.Resample(sr, 24000)
136
- if sr != 24000:
137
- audio_data = resampler(audio_data)
138
-
139
- if audio_data.shape[0] > 1:
140
- audio_data = torch.mean(audio_data, dim=0, keepdim=True)
141
-
142
- audio_data = audio_data.to(device)
143
-
144
- ref_audio_len = int(audio_data.shape[-1] // 256)
145
- ref_clip = torch.zeros((1, ref_audio_len, 768)).to(device=device)
146
-
147
- gen_clip = torch.cat((gen_clip, ref_clip), dim=1)
148
-
149
- gen_audio_len = ref_audio_len + gen_audio_len
150
-
151
- gen_text = ref_text + " " + gen_text
152
-
153
  else:
154
- spk_emb = torch.zeros((1, 1, 192)).to(device=device)
155
- audio_data = torch.zeros((1, gen_audio_len, 100)).to(device=device)
156
 
157
  gen_text_batches = chunk_text(gen_text, max_chars=1024)
158
  final_text_list = convert_char_to_pinyin(gen_text_batches)
159
 
 
 
160
  with torch.inference_mode():
161
  generated, _ = ema_model.sample(
162
- cond=audio_data,
163
  text=final_text_list,
164
  clip=gen_clip,
165
  spk_emb=spk_emb,
@@ -167,14 +110,11 @@ def deepdubber(video_path: str, subtitle_text: str, audio_path: str = None) -> s
167
  steps=nfe_step,
168
  cfg_strength=cfg_strength,
169
  sway_sampling_coef=sway_sampling_coef,
170
- no_ref_audio=False,
171
  )
172
 
173
  generated = generated.to(torch.float32)
174
 
175
- if ref_audio_len is not None:
176
- generated = generated[:, ref_audio_len:, :]
177
-
178
  generated_mel_spec = generated.permute(0, 2, 1)
179
  generated_wave = vocoder(generated_mel_spec)
180
 
@@ -185,7 +125,10 @@ def deepdubber(video_path: str, subtitle_text: str, audio_path: str = None) -> s
185
  temp_wav_path = temp_wav_file.name
186
  soundfile.write(temp_wav_path, generated_wave, samplerate=24000)
187
 
188
- concated_video = concat_movie_with_audio(temp_wav_path, video_path, ".")
 
 
 
189
 
190
  # Ensure the temporary file is deleted after use
191
  os.remove(temp_wav_path)
@@ -194,7 +137,9 @@ def deepdubber(video_path: str, subtitle_text: str, audio_path: str = None) -> s
194
  return response, concated_video
195
 
196
 
197
- def process_video_dubbing(video_path: str, subtitle_text: str, audio_path: str = None) -> str:
 
 
198
  try:
199
  if not os.path.exists(video_path):
200
  raise ValueError("Video file does not exist")
@@ -227,6 +172,7 @@ def create_ui():
227
  label="Enter the subtitle", placeholder="Enter the subtitle to be dubbed...", lines=5
228
  )
229
  audio_input = gr.Audio(label="Upload speech prompt (Optional)", type="filepath")
 
230
 
231
  process_btn = gr.Button("Start Dubbing")
232
 
@@ -240,16 +186,19 @@ def create_ui():
240
  "datasets/CoTMovieDubbing/demo/v01input.mp4",
241
  "it isn't simply a question of creating a robot who can love",
242
  "datasets/CoTMovieDubbing/demo/speech_prompt_01.mp3",
 
243
  ],
244
  [
245
  "datasets/CoTMovieDubbing/demo/v02input.mp4",
246
  "Me, I'd be happy with one who's not... fixed.",
247
  "datasets/CoTMovieDubbing/demo/speech_prompt_02.mp3",
 
248
  ],
249
  [
250
  "datasets/CoTMovieDubbing/demo/v03input.mp4",
251
  "Man, Papi. What am I gonna do?",
252
  "datasets/CoTMovieDubbing/demo/speech_prompt_03.mp3",
 
253
  ],
254
  ]
255
 
@@ -259,6 +208,7 @@ def create_ui():
259
  outputs=[output_response, output_video],
260
  )
261
 
 
262
  gr.Examples(examples=examples, inputs=[video_input, subtitle_input, audio_input])
263
 
264
  return app
 
2
  import os.path as osp
3
  import sys
4
  import tempfile
5
+ from uuid import uuid4
6
 
7
  import gradio as gr
 
8
  import soundfile
9
  import torch
10
  import torch.nn.functional as F
 
11
  from huggingface_hub import snapshot_download
12
+ from transformers import AutoTokenizer
 
 
13
 
14
  from src.internvl.eval import load_video
15
  from src.moviedubber.infer.utils_infer import (
 
19
  sway_sampling_coef,
20
  )
21
  from src.moviedubber.infer.video_preprocess import VideoFeatureExtractor
22
+ from src.moviedubber.infer_with_mmlm_result import get_spk_emb, get_video_duration, load_models, merge_video_audio
23
  from src.moviedubber.model.utils import convert_char_to_pinyin
24
 
25
 
 
29
  from InternVL.internvl_chat.internvl.model.internvl_chat.modeling_internvl_chat import InternVLChatModel # type: ignore
30
 
31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
33
 
34
  repo_local_path = snapshot_download(repo_id="woak-oa/DeepDubber-V1")
 
47
 
48
 
49
  ema_model, vocoder, ort_session = load_models(repo_local_path, device=device)
 
50
 
51
  videofeature_extractor = VideoFeatureExtractor(device=device)
52
 
 
83
  gen_clip = videofeature_extractor.extract_features(video_path)
84
  gen_text = subtitle_text
85
 
86
+ v_dur = get_video_duration(video_path)
87
+ gen_audio_len = int(v_dur * 24000 // 256)
88
 
89
  gen_clip = gen_clip.unsqueeze(0).to(device=device, dtype=torch.float32).transpose(1, 2)
90
  gen_clip = F.interpolate(gen_clip, size=(gen_audio_len,), mode="linear", align_corners=False).transpose(1, 2)
91
 
 
92
  if audio_path is not None:
93
+ spk_emb = get_spk_emb(audio_path, ort_session)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  spk_emb = torch.tensor(spk_emb).to(device=device, dtype=torch.float32).unsqueeze(0).unsqueeze(0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  else:
96
+ spk_emb = torch.zeros(1, 1, 256).to(device=device, dtype=torch.float32)
 
97
 
98
  gen_text_batches = chunk_text(gen_text, max_chars=1024)
99
  final_text_list = convert_char_to_pinyin(gen_text_batches)
100
 
101
+ cond = torch.zeros(1, gen_audio_len, 100).to(device)
102
+
103
  with torch.inference_mode():
104
  generated, _ = ema_model.sample(
105
+ cond=cond,
106
  text=final_text_list,
107
  clip=gen_clip,
108
  spk_emb=spk_emb,
 
110
  steps=nfe_step,
111
  cfg_strength=cfg_strength,
112
  sway_sampling_coef=sway_sampling_coef,
113
+ no_ref_audio=True,
114
  )
115
 
116
  generated = generated.to(torch.float32)
117
 
 
 
 
118
  generated_mel_spec = generated.permute(0, 2, 1)
119
  generated_wave = vocoder(generated_mel_spec)
120
 
 
125
  temp_wav_path = temp_wav_file.name
126
  soundfile.write(temp_wav_path, generated_wave, samplerate=24000)
127
 
128
+ video_out_path = os.path.join(out_dir, f"dubbed_video_{uuid4[:6]}.mp4")
129
+ concated_video = merge_video_audio(
130
+ video_path, temp_wav_path, video_out_path, 0, soundfile.info(temp_wav_path).duration
131
+ )
132
 
133
  # Ensure the temporary file is deleted after use
134
  os.remove(temp_wav_path)
 
137
  return response, concated_video
138
 
139
 
140
+ def process_video_dubbing(
141
+ video_path: str, subtitle_text: str, audio_path: str = None, caption_input: str = None
142
+ ) -> str:
143
  try:
144
  if not os.path.exists(video_path):
145
  raise ValueError("Video file does not exist")
 
172
  label="Enter the subtitle", placeholder="Enter the subtitle to be dubbed...", lines=5
173
  )
174
  audio_input = gr.Audio(label="Upload speech prompt (Optional)", type="filepath")
175
+ # caption_input = gr.Textbox(label="Enter the description of Video (Optional)", lines=1)
176
 
177
  process_btn = gr.Button("Start Dubbing")
178
 
 
186
  "datasets/CoTMovieDubbing/demo/v01input.mp4",
187
  "it isn't simply a question of creating a robot who can love",
188
  "datasets/CoTMovieDubbing/demo/speech_prompt_01.mp3",
189
+ # "datasets/CoTMovieDubbing/demo/speech_prompt_01.mp3",
190
  ],
191
  [
192
  "datasets/CoTMovieDubbing/demo/v02input.mp4",
193
  "Me, I'd be happy with one who's not... fixed.",
194
  "datasets/CoTMovieDubbing/demo/speech_prompt_02.mp3",
195
+ # "datasets/CoTMovieDubbing/demo/speech_prompt_02.mp3",
196
  ],
197
  [
198
  "datasets/CoTMovieDubbing/demo/v03input.mp4",
199
  "Man, Papi. What am I gonna do?",
200
  "datasets/CoTMovieDubbing/demo/speech_prompt_03.mp3",
201
+ # "datasets/CoTMovieDubbing/demo/speech_prompt_02.mp3",
202
  ],
203
  ]
204
 
 
208
  outputs=[output_response, output_video],
209
  )
210
 
211
+ # gr.Examples(examples=examples, inputs=[video_input, subtitle_input, audio_input, caption_input])
212
  gr.Examples(examples=examples, inputs=[video_input, subtitle_input, audio_input])
213
 
214
  return app
src/moviedubber/infer/utils_infer.py CHANGED
@@ -89,48 +89,11 @@ def load_vocoder(local_path, device=device):
89
  # load model checkpoint for inference
90
 
91
 
92
- def load_checkpoint(model, ckpt_path, device: str, dtype=None, use_ema=True):
93
- if dtype is None:
94
- dtype = (
95
- torch.float16
96
- if "cuda" in device
97
- and torch.cuda.get_device_properties(device).major >= 6
98
- and not torch.cuda.get_device_name().endswith("[ZLUDA]")
99
- else torch.float32
100
- )
101
  model = model.to(dtype)
102
 
103
- ckpt_type = ckpt_path.split(".")[-1]
104
- if ckpt_type == "safetensors":
105
- from safetensors.torch import load_file
106
-
107
- checkpoint = load_file(ckpt_path, device=device)
108
- else:
109
- checkpoint = torch.load(ckpt_path, map_location=device, weights_only=True)
110
-
111
- if use_ema:
112
- if ckpt_type == "safetensors":
113
- checkpoint = {"ema_model_state_dict": checkpoint}
114
- checkpoint["model_state_dict"] = {
115
- k.replace("ema_model.", ""): v
116
- for k, v in checkpoint["ema_model_state_dict"].items()
117
- if k not in ["initted", "step"]
118
- }
119
-
120
- # patch for backward compatibility, 305e3ea
121
- for key in ["mel_spec.mel_stft.mel_scale.fb", "mel_spec.mel_stft.spectrogram.window"]:
122
- if key in checkpoint["model_state_dict"]:
123
- del checkpoint["model_state_dict"][key]
124
-
125
- state_dict_result = model.load_state_dict(checkpoint["model_state_dict"], strict=False)
126
- if state_dict_result.unexpected_keys:
127
- print("\nUnexpected keys in state_dict:", state_dict_result.unexpected_keys)
128
- if state_dict_result.missing_keys:
129
- print("\nMissing keys in state_dict:", state_dict_result.missing_keys)
130
- else:
131
- if ckpt_type == "safetensors":
132
- checkpoint = {"model_state_dict": checkpoint}
133
- model.load_state_dict(checkpoint["model_state_dict"], strict=True)
134
 
135
  del checkpoint
136
  torch.cuda.empty_cache()
@@ -149,7 +112,6 @@ def load_model(
149
  mel_spec_type=mel_spec_type,
150
  vocab_file="",
151
  ode_method=ode_method,
152
- use_ema=True,
153
  device=device,
154
  ):
155
  tokenizer = "custom"
@@ -181,7 +143,7 @@ def load_model(
181
  ).to(device)
182
 
183
  dtype = torch.float32 if mel_spec_type == "bigvgan" else None
184
- model = load_checkpoint(model, ckpt_path, device, dtype=dtype, use_ema=use_ema)
185
 
186
  return model
187
 
 
89
  # load model checkpoint for inference
90
 
91
 
92
+ def load_checkpoint(model, ckpt_path, device: str, dtype=torch.float32):
 
 
 
 
 
 
 
 
93
  model = model.to(dtype)
94
 
95
+ checkpoint = torch.load(ckpt_path, map_location=device, weights_only=True)
96
+ model.load_state_dict(checkpoint, strict=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
 
98
  del checkpoint
99
  torch.cuda.empty_cache()
 
112
  mel_spec_type=mel_spec_type,
113
  vocab_file="",
114
  ode_method=ode_method,
 
115
  device=device,
116
  ):
117
  tokenizer = "custom"
 
143
  ).to(device)
144
 
145
  dtype = torch.float32 if mel_spec_type == "bigvgan" else None
146
+ model = load_checkpoint(model, ckpt_path, device, dtype=dtype)
147
 
148
  return model
149
 
src/moviedubber/infer_with_mmlm_result.py CHANGED
@@ -1,9 +1,10 @@
1
  import os
 
2
 
 
3
  import onnxruntime
4
  import torchaudio
5
  import torchaudio.compliance.kaldi as kaldi
6
- from moviepy import AudioFileClip, VideoFileClip
7
  from omegaconf import OmegaConf
8
 
9
  from src.moviedubber.infer.utils_infer import (
@@ -13,31 +14,50 @@ from src.moviedubber.infer.utils_infer import (
13
  from src.moviedubber.model import ControlNetDiT, DiT
14
 
15
 
16
- def concat_movie_with_audio(wav, video_path, out_dir):
17
- with (
18
- AudioFileClip(str(wav)) as audio_clip,
19
- VideoFileClip(str(video_path)) as video_clip,
20
- ):
21
- duration = min(video_clip.duration, audio_clip.duration)
22
-
23
- video_subclip = video_clip.subclipped(0, duration)
24
- audio_subclip = audio_clip.subclipped(0, duration)
25
-
26
- final_video = video_subclip.with_audio(audio_subclip)
27
-
28
- output_path = wav.replace(".wav", ".mp4")
29
-
30
- final_video.write_videofile(
31
- str(output_path),
32
- codec="libx264",
33
- audio_codec="mp3",
34
- fps=25,
35
- logger=None,
36
- threads=1,
37
- temp_audiofile_path=out_dir,
38
- )
39
-
40
- return output_path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
 
43
  def get_spk_emb(audio_path, ort_session):
 
1
  import os
2
+ import subprocess as sp
3
 
4
+ import cv2
5
  import onnxruntime
6
  import torchaudio
7
  import torchaudio.compliance.kaldi as kaldi
 
8
  from omegaconf import OmegaConf
9
 
10
  from src.moviedubber.infer.utils_infer import (
 
14
  from src.moviedubber.model import ControlNetDiT, DiT
15
 
16
 
17
+ def get_video_duration(video_path):
18
+ cap = cv2.VideoCapture(video_path)
19
+
20
+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
21
+
22
+ fps = cap.get(cv2.CAP_PROP_FPS)
23
+
24
+ duration = total_frames / fps
25
+ return duration
26
+
27
+
28
+ def merge_video_audio(video_path, audio_path, output_path, start_time, duration):
29
+ command = [
30
+ "ffmpeg",
31
+ "-y",
32
+ "-ss",
33
+ str(start_time),
34
+ "-t",
35
+ str(duration),
36
+ "-i",
37
+ video_path,
38
+ "-i",
39
+ audio_path,
40
+ "-c:v",
41
+ "copy",
42
+ "-c:a",
43
+ "aac",
44
+ "-map",
45
+ "0:v:0",
46
+ "-map",
47
+ "1:a:0",
48
+ "-shortest",
49
+ "-strict",
50
+ "experimental",
51
+ output_path,
52
+ ]
53
+
54
+ try:
55
+ sp.run(command, check=True, stdout=sp.DEVNULL, stderr=sp.DEVNULL, stdin=sp.DEVNULL)
56
+ print(f"Successfully merged audio and video into {output_path}")
57
+ return output_path
58
+ except sp.CalledProcessError as e:
59
+ print(f"Error merging audio and video: {e}")
60
+ return None
61
 
62
 
63
  def get_spk_emb(audio_path, ort_session):