alibabasglab commited on
Commit
303de59
·
verified ·
1 Parent(s): 6526105

Upload 19 files

Browse files
utils/__pycache__/__init__.cpython-36.pyc ADDED
Binary file (245 Bytes). View file
 
utils/__pycache__/__init__.cpython-37.pyc ADDED
Binary file (268 Bytes). View file
 
utils/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (270 Bytes). View file
 
utils/__pycache__/bandwidth_sub.cpython-312.pyc ADDED
Binary file (6.12 kB). View file
 
utils/__pycache__/decode.cpython-312.pyc ADDED
Binary file (28.1 kB). View file
 
utils/__pycache__/decode.cpython-38.pyc ADDED
Binary file (13.4 kB). View file
 
utils/__pycache__/misc.cpython-312.pyc ADDED
Binary file (17.1 kB). View file
 
utils/__pycache__/misc.cpython-36.pyc ADDED
Binary file (3.23 kB). View file
 
utils/__pycache__/misc.cpython-37.pyc ADDED
Binary file (3.25 kB). View file
 
utils/__pycache__/misc.cpython-38.pyc ADDED
Binary file (11.4 kB). View file
 
utils/__pycache__/time_dataset.cpython-36.pyc ADDED
Binary file (5.8 kB). View file
 
utils/__pycache__/time_dataset.cpython-37.pyc ADDED
Binary file (6.09 kB). View file
 
utils/__pycache__/time_dataset.cpython-38.pyc ADDED
Binary file (6.15 kB). View file
 
utils/__pycache__/video_process.cpython-312.pyc ADDED
Binary file (26.5 kB). View file
 
utils/__pycache__/video_process.cpython-38.pyc ADDED
Binary file (12.3 kB). View file
 
utils/bandwidth_sub.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import soundfile as sf
3
+ import librosa
4
+ import os
5
+ from scipy.signal import butter, filtfilt, stft, istft
6
+
7
+ # Step 1: Load audio files
8
+ def load_audio(audio_path):
9
+ audio, sr = librosa.load(audio_path, sr=48000)
10
+ #audio, fs = sf.read(audio_path)
11
+ return audio, sr
12
+
13
+ # Step 2: Detect effective signal bandwidth
14
+ def detect_bandwidth_org(signal, fs, energy_threshold=0.95):
15
+ f, t, Zxx = stft(signal, fs=fs)
16
+ psd = np.abs(Zxx)**2
17
+ total_energy = np.sum(psd)
18
+ cumulative_energy = np.cumsum(np.sum(psd, axis=1)) / total_energy
19
+ f_low = f[np.argmax(cumulative_energy > (1 - energy_threshold))]
20
+ f_high = f[np.argmax(cumulative_energy >= energy_threshold)]
21
+ return f_low, f_high
22
+
23
+ def detect_bandwidth(signal, fs, energy_threshold=0.99):
24
+ f, t, Zxx = stft(signal, fs=fs)
25
+ psd = np.abs(Zxx)**2
26
+ total_energy = np.sum(psd)
27
+ cumulative_energy = np.cumsum(np.sum(psd, axis=1)) / total_energy
28
+
29
+ # Exclude DC component (0 Hz)
30
+ valid_indices = np.where(f > 0)[0]
31
+ f_low = f[valid_indices][np.argmax(cumulative_energy[valid_indices] > (1 - energy_threshold))]
32
+ f_high = f[np.argmax(cumulative_energy >= energy_threshold)]
33
+ return f_low, f_high
34
+
35
+ # Step 3: Apply bandpass and lowpass filters
36
+ def bandpass_filter(signal, fs, f_low, f_high):
37
+ nyquist = 0.5 * fs
38
+ low = f_low / nyquist
39
+ high = f_high / nyquist
40
+ b, a = butter(N=4, Wn=[low, high], btype='band')
41
+ return filtfilt(b, a, signal)
42
+
43
+ def lowpass_filter(signal, fs, cutoff):
44
+ nyquist = 0.5 * fs
45
+ cutoff_normalized = cutoff / nyquist
46
+ b, a = butter(N=4, Wn=cutoff_normalized, btype='low')
47
+ return filtfilt(b, a, signal)
48
+
49
+ def highpass_filter(signal, fs, cutoff):
50
+ nyquist = 0.5 * fs
51
+ cutoff_normalized = cutoff / nyquist
52
+ b, a = butter(N=4, Wn=cutoff_normalized, btype='high')
53
+ return filtfilt(b, a, signal)
54
+
55
+ # Step 4: Replace bandwidth
56
+ def replace_bandwidth(signal1, signal2, fs, f_low, f_high):
57
+ # Extract effective band from signal1
58
+ #effective_band = bandpass_filter(signal1, fs, f_low, f_high)
59
+ effective_band = lowpass_filter(signal1, fs, f_high)
60
+ # Extract lowpass band from signal2
61
+ #signal2_lowpass = lowpass_filter(signal2, fs, f_high)
62
+ signal2_highpass = highpass_filter(signal2, fs, f_high)
63
+
64
+ # Match lengths of the two signals
65
+ min_length = min(len(effective_band), len(signal2_highpass))
66
+ effective_band = effective_band[:min_length]
67
+ signal2_highpass = signal2_highpass[:min_length]
68
+
69
+ # Combine the two signals
70
+ return signal2_highpass + effective_band
71
+
72
+ # Step 5: Smooth transitions
73
+ def smooth_transition(signal1, signal2, fs, transition_band=100):
74
+ fade = np.linspace(0, 1, int(transition_band * fs / 1000))
75
+ crossfade = np.concatenate([fade, np.ones(len(signal1) - len(fade))])
76
+ min_length = min(len(signal1), len(signal2))
77
+ smoothed_signal = (1 - crossfade) * signal2[:min_length] + crossfade * signal1[:min_length]
78
+ return smoothed_signal
79
+
80
+ # Step 6: Save audio
81
+ def save_audio(file_path, audio, fs):
82
+ sf.write(file_path, audio, fs)
83
+
84
+
85
+ def bandwidth_sub(low_bandwidth_audio, high_bandwidth_audio, fs=48000):
86
+ # Detect effective bandwidth of the first signal
87
+ f_low, f_high = detect_bandwidth(low_bandwidth_audio, fs)
88
+
89
+ # Replace the lower frequency of the second audio
90
+ substituted_audio = replace_bandwidth(low_bandwidth_audio, high_bandwidth_audio, fs, f_low, f_high)
91
+
92
+ # Optional: Smooth the transition
93
+ smoothed_audio = smooth_transition(substituted_audio, low_bandwidth_audio, fs)
94
+ return smoothed_audio
95
+
96
+ # Main process
97
+ if __name__ == "__main__":
98
+ low_spectra_dir = 'LJSpeech_22k'
99
+ upper_spectra_dir = 'LJSpeech_22k_hifi-sr_speech_g_03925000'
100
+ output_dir = upper_spectra_dir+'_restored'
101
+ if not os.path.exists(output_dir):
102
+ os.mkdir(output_dir)
103
+
104
+ filelist = [file for file in os.listdir(low_spectra_dir) if file.endswith('.wav')]
105
+ for audio_name in filelist:
106
+ audio1, fs1 = load_audio(low_spectra_dir + "/" + audio_name) # Source for effective bandwidth
107
+ audio2, fs2 = load_audio(upper_spectra_dir + "/" + audio_name.replace('.wav', '_generated.wav')) # Target audio to replace lower frequencies
108
+
109
+ if fs1 != 48000 or fs2 != 48000:
110
+ raise ValueError("Both audio files must have a sampling rate of 48 kHz.")
111
+
112
+ # Detect effective bandwidth of the first signal
113
+ f_low, f_high = detect_bandwidth(audio1, fs1)
114
+ print(f"Effective bandwidth: {f_low} Hz to {f_high} Hz")
115
+
116
+ # Replace the lower frequency of the second audio
117
+ replaced_audio = replace_bandwidth(audio1, audio2, fs2, f_low, f_high)
118
+
119
+ # Optional: Smooth the transition
120
+ smoothed_audio = smooth_transition(replaced_audio, audio1, fs1)
121
+
122
+ # Save the result
123
+ save_audio(output_dir+"/"+audio_name, smoothed_audio, fs2)
utils/decode.py ADDED
@@ -0,0 +1,609 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python -u
2
+ # -*- coding: utf-8 -*-
3
+ # Authors: Shengkui Zhao, Zexu Pan
4
+
5
+ from __future__ import absolute_import
6
+ from __future__ import division
7
+ from __future__ import print_function
8
+ import torch
9
+ import torch.nn as nn
10
+ import numpy as np
11
+ import os
12
+ import sys
13
+ import librosa
14
+ import torchaudio
15
+ from utils.misc import power_compress, power_uncompress, stft, istft, compute_fbank
16
+ from utils.bandwidth_sub import bandwidth_sub
17
+ from dataloader.meldataset import mel_spectrogram
18
+
19
+ # Constant for normalizing audio values
20
+ MAX_WAV_VALUE = 32768.0
21
+
22
+ def decode_one_audio(model, device, inputs, args):
23
+ """Decodes audio using the specified model based on the provided network type.
24
+
25
+ This function selects the appropriate decoding function based on the specified
26
+ network in the arguments and processes the input audio data accordingly.
27
+
28
+ Args:
29
+ model (nn.Module): The trained model used for decoding.
30
+ device (torch.device): The device (CPU or GPU) to perform computations on.
31
+ inputs (torch.Tensor): Input audio tensor.
32
+ args (Namespace): Contains arguments for network configuration.
33
+
34
+ Returns:
35
+ list: A list of decoded audio outputs for each speaker.
36
+ """
37
+ # Select decoding function based on the network type specified in args
38
+ if args.network == 'FRCRN_SE_16K':
39
+ return decode_one_audio_frcrn_se_16k(model, device, inputs, args)
40
+ elif args.network == 'MossFormer2_SE_48K':
41
+ return decode_one_audio_mossformer2_se_48k(model, device, inputs, args)
42
+ elif args.network == 'MossFormerGAN_SE_16K':
43
+ return decode_one_audio_mossformergan_se_16k(model, device, inputs, args)
44
+ elif args.network == 'MossFormer2_SS_16K':
45
+ return decode_one_audio_mossformer2_ss_16k(model, device, inputs, args)
46
+ elif args.network == 'MossFormer2_SR_48K':
47
+ return decode_one_audio_mossformer2_sr_48k(model, device, inputs, args)
48
+ else:
49
+ print("No network found!") # Print error message if no valid network is specified
50
+ return
51
+
52
+ def decode_one_audio_mossformer2_ss_16k(model, device, inputs, args):
53
+ """Decodes audio using the MossFormer2 model for speech separation at 16kHz.
54
+
55
+ This function handles the audio decoding process by processing the input tensor
56
+ in segments, if necessary, and applies the model to obtain separated audio outputs.
57
+
58
+ Args:
59
+ model (nn.Module): The trained MossFormer2 model for decoding.
60
+ device (torch.device): The device (CPU or GPU) to perform computations on.
61
+ inputs (torch.Tensor): Input audio tensor of shape (B, T), where B is the batch size
62
+ and T is the number of time steps.
63
+ args (Namespace): Contains arguments for decoding configuration.
64
+
65
+ Returns:
66
+ list: A list of decoded audio outputs for each speaker.
67
+ """
68
+ out = [] # Initialize the list to store outputs
69
+ decode_do_segment = False # Flag to determine if segmentation is needed
70
+ window = int(args.sampling_rate * args.decode_window) # Decoding window length
71
+ stride = int(window * 0.75) # Decoding stride if segmentation is used
72
+ b, t = inputs.shape # Get batch size and input length
73
+
74
+ rms_input = (inputs ** 2).mean() ** 0.5
75
+
76
+ # Check if input length exceeds one-time decode length to decide on segmentation
77
+ if t > args.sampling_rate * args.one_time_decode_length:
78
+ decode_do_segment = True # Enable segment decoding for long sequences
79
+
80
+ # Pad the inputs to ensure they meet the decoding window length requirements
81
+ if t < window:
82
+ inputs = np.concatenate([inputs, np.zeros((inputs.shape[0], window - t))], axis=1)
83
+ elif t < window + stride:
84
+ padding = window + stride - t
85
+ inputs = np.concatenate([inputs, np.zeros((inputs.shape[0], padding))], axis=1)
86
+ else:
87
+ if (t - window) % stride != 0:
88
+ padding = t - (t - window) // stride * stride
89
+ inputs = np.concatenate([inputs, np.zeros((inputs.shape[0], padding))], axis=1)
90
+
91
+ inputs = torch.from_numpy(np.float32(inputs)).to(device) # Convert inputs to torch tensor and move to device
92
+ b, t = inputs.shape # Update batch size and input length after conversion
93
+
94
+ # Process the inputs in segments if necessary
95
+ if decode_do_segment:
96
+ outputs = np.zeros((args.num_spks, t)) # Initialize output array for each speaker
97
+ give_up_length = (window - stride) // 2 # Calculate length to give up at each segment
98
+ current_idx = 0 # Initialize current index for segmentation
99
+ while current_idx + window <= t:
100
+ tmp_input = inputs[:, current_idx:current_idx + window] # Get segment input
101
+ tmp_out_list = model(tmp_input) # Forward pass through the model
102
+ for spk in range(args.num_spks):
103
+ # Convert output for the current speaker to numpy
104
+ tmp_out_list[spk] = tmp_out_list[spk][0, :].detach().cpu().numpy()
105
+ if current_idx == 0:
106
+ # For the first segment, use the whole segment minus the give-up length
107
+ outputs[spk, current_idx:current_idx + window - give_up_length] = tmp_out_list[spk][:-give_up_length]
108
+ else:
109
+ # For subsequent segments, account for the give-up length at both ends
110
+ outputs[spk, current_idx + give_up_length:current_idx + window - give_up_length] = tmp_out_list[spk][give_up_length:-give_up_length]
111
+ current_idx += stride # Move to the next segment
112
+ for spk in range(args.num_spks):
113
+ out.append(outputs[spk, :]) # Append outputs for each speaker
114
+ else:
115
+ # If no segmentation is required, process the entire input
116
+ out_list = model(inputs)
117
+ for spk in range(args.num_spks):
118
+ out.append(out_list[spk][0, :].detach().cpu().numpy()) # Append output for each speaker
119
+
120
+ # Normalize the outputs back to the input magnitude for each speaker
121
+ for spk in range(args.num_spks):
122
+ rms_out = (out[spk] ** 2).mean() ** 0.5
123
+ out[spk] = out[spk] / rms_out * rms_input
124
+ return out # Return the list of normalized outputs
125
+
126
+ def decode_one_audio_frcrn_se_16k(model, device, inputs, args):
127
+ """Decodes audio using the FRCRN model for speech enhancement at 16kHz.
128
+
129
+ This function processes the input audio tensor either in segments or as a whole,
130
+ depending on the length of the input. The model's inference method is applied
131
+ to obtain the enhanced audio output.
132
+
133
+ Args:
134
+ model (nn.Module): The trained FRCRN model used for decoding.
135
+ device (torch.device): The device (CPU or GPU) to perform computations on.
136
+ inputs (torch.Tensor): Input audio tensor of shape (B, T), where B is the batch size
137
+ and T is the number of time steps.
138
+ args (Namespace): Contains arguments for decoding configuration.
139
+
140
+ Returns:
141
+ numpy.ndarray: The decoded audio output, which has been enhanced by the model.
142
+ """
143
+ decode_do_segment = False # Flag to determine if segmentation is needed
144
+
145
+ window = int(args.sampling_rate * args.decode_window) # Decoding window length
146
+ stride = int(window * 0.75) # Decoding stride for segmenting the input
147
+ b, t = inputs.shape # Get batch size (b) and input length (t)
148
+
149
+ # Check if input length exceeds one-time decode length to decide on segmentation
150
+ if t > args.sampling_rate * args.one_time_decode_length:
151
+ decode_do_segment = True # Enable segment decoding for long sequences
152
+
153
+ # Pad the inputs to meet the decoding window length requirements
154
+ if t < window:
155
+ # Pad with zeros if the input length is less than the window size
156
+ inputs = np.concatenate([inputs, np.zeros((inputs.shape[0], window - t))], axis=1)
157
+ elif t < window + stride:
158
+ # Pad the input if its length is less than the window plus stride
159
+ padding = window + stride - t
160
+ inputs = np.concatenate([inputs, np.zeros((inputs.shape[0], padding))], axis=1)
161
+ else:
162
+ # Ensure the input length is a multiple of the stride
163
+ if (t - window) % stride != 0:
164
+ padding = t - (t - window) // stride * stride
165
+ inputs = np.concatenate([inputs, np.zeros((inputs.shape[0], padding))], axis=1)
166
+
167
+ # Convert inputs to a PyTorch tensor and move to the specified device
168
+ inputs = torch.from_numpy(np.float32(inputs)).to(device)
169
+ b, t = inputs.shape # Update batch size and input length after conversion
170
+
171
+ # Process the inputs in segments if necessary
172
+ if decode_do_segment:
173
+ outputs = np.zeros(t) # Initialize the output array
174
+ give_up_length = (window - stride) // 2 # Calculate length to give up at each segment
175
+ current_idx = 0 # Initialize current index for segmentation
176
+
177
+ while current_idx + window <= t:
178
+ tmp_input = inputs[:, current_idx:current_idx + window] # Get segment input
179
+ tmp_output = model.inference(tmp_input).detach().cpu().numpy() # Inference on segment
180
+
181
+ # For the first segment, use the whole segment minus the give-up length
182
+ if current_idx == 0:
183
+ outputs[current_idx:current_idx + window - give_up_length] = tmp_output[:-give_up_length]
184
+ else:
185
+ # For subsequent segments, account for the give-up length
186
+ outputs[current_idx + give_up_length:current_idx + window - give_up_length] = tmp_output[give_up_length:-give_up_length]
187
+
188
+ current_idx += stride # Move to the next segment
189
+ else:
190
+ # If no segmentation is required, process the entire input
191
+ outputs = model.inference(inputs).detach().cpu().numpy() # Inference on full input
192
+
193
+ return outputs # Return the decoded audio output
194
+
195
+ def decode_one_audio_mossformergan_se_16k(model, device, inputs, args):
196
+ """Decodes audio using the MossFormerGAN model for speech enhancement at 16kHz.
197
+
198
+ This function processes the input audio tensor either in segments or as a whole,
199
+ depending on the length of the input. The `_decode_one_audio_mossformergan_se_16k`
200
+ function is called to perform the model inference and return the enhanced audio output.
201
+
202
+ Args:
203
+ model (nn.Module): The trained MossFormerGAN model used for decoding.
204
+ device (torch.device): The device (CPU or GPU) for computation.
205
+ inputs (torch.Tensor): Input audio tensor of shape (B, T), where B is the batch size
206
+ and T is the number of time steps.
207
+ args (Namespace): Contains arguments for decoding configuration.
208
+
209
+ Returns:
210
+ numpy.ndarray: The decoded audio output, which has been enhanced by the model.
211
+ """
212
+ decode_do_segment = False # Flag to determine if segmentation is needed
213
+ window = int(args.sampling_rate * args.decode_window) # Decoding window length
214
+ stride = int(window * 0.75) # Decoding stride for segmenting the input
215
+ b, t = inputs.shape # Get batch size (b) and input length (t)
216
+
217
+ # Check if input length exceeds one-time decode length to decide on segmentation
218
+ if t > args.sampling_rate * args.one_time_decode_length:
219
+ decode_do_segment = True # Enable segment decoding for long sequences
220
+
221
+ # Convert inputs to a PyTorch tensor and move to the specified device
222
+ inputs = torch.from_numpy(np.float32(inputs)).to(device)
223
+
224
+ # Compute normalization factor based on the input
225
+ norm_factor = torch.sqrt(inputs.size(-1) / torch.sum((inputs ** 2.0), dim=-1))
226
+
227
+ b, t = inputs.shape # Update batch size and input length after conversion
228
+
229
+ # Process the inputs in segments if necessary
230
+ if decode_do_segment:
231
+ outputs = np.zeros(t) # Initialize the output array
232
+ give_up_length = (window - stride) // 2 # Calculate length to give up at each segment
233
+ current_idx = 0 # Initialize current index for segmentation
234
+
235
+ while current_idx + window <= t:
236
+ tmp_input = inputs[:, current_idx:current_idx + window] # Get segment input
237
+ tmp_output = _decode_one_audio_mossformergan_se_16k(model, device, tmp_input, norm_factor, args) # Inference on segment
238
+
239
+ # For the first segment, use the whole segment minus the give-up length
240
+ if current_idx == 0:
241
+ outputs[current_idx:current_idx + window - give_up_length] = tmp_output[:-give_up_length]
242
+ else:
243
+ # For subsequent segments, account for the give-up length
244
+ outputs[current_idx + give_up_length:current_idx + window - give_up_length] = tmp_output[give_up_length:-give_up_length]
245
+
246
+ current_idx += stride # Move to the next segment
247
+
248
+ return outputs # Return the accumulated outputs from segments
249
+ else:
250
+ # If no segmentation is required, process the entire input
251
+ return _decode_one_audio_mossformergan_se_16k(model, device, inputs, norm_factor, args) # Inference on full input
252
+
253
+ @torch.no_grad()
254
+ def _decode_one_audio_mossformergan_se_16k(model, device, inputs, norm_factor, args):
255
+ """Processes audio inputs through the MossFormerGAN model for speech enhancement.
256
+
257
+ This function performs the following steps:
258
+ 1. Pads the input audio tensor to fit the model requirements.
259
+ 2. Computes a normalization factor for the input tensor.
260
+ 3. Applies Short-Time Fourier Transform (STFT) to convert the audio into the frequency domain.
261
+ 4. Processes the STFT representation through the model to predict the real and imaginary components.
262
+ 5. Uncompresses the predicted spectrogram and applies Inverse STFT (iSTFT) to convert back to time domain audio.
263
+ 6. Normalizes the output audio.
264
+
265
+ Args:
266
+ model (nn.Module): The trained MossFormerGAN model used for decoding.
267
+ device (torch.device): The device (CPU or GPU) for computation.
268
+ inputs (torch.Tensor): Input audio tensor of shape (B, T), where B is the batch size and T is the number of time steps.
269
+ norm_factor (torch.Tensor): A norm tensor to regularize input amplitude
270
+ args (Namespace): Contains arguments for STFT parameters and normalization.
271
+
272
+ Returns:
273
+ numpy.ndarray: The decoded audio output, which has been enhanced by the model.
274
+ """
275
+ input_len = inputs.size(-1) # Get the length of the input audio
276
+ nframe = int(np.ceil(input_len / args.win_inc)) # Calculate the number of frames based on window increment
277
+ padded_len = int(nframe * args.win_inc) # Calculate the padded length to fit the model
278
+ padding_len = padded_len - input_len # Determine how much padding is needed
279
+
280
+ # Pad the input audio with the beginning of the input
281
+ inputs = torch.cat([inputs, inputs[:, :padding_len]], dim=-1)
282
+
283
+ # Prepare inputs for STFT by transposing and normalizing
284
+ inputs = torch.transpose(inputs, 0, 1) # Change shape for STFT
285
+ inputs = torch.transpose(inputs * norm_factor, 0, 1) # Apply normalization factor and transpose back
286
+
287
+ # Perform Short-Time Fourier Transform (STFT) on the normalized inputs
288
+ inputs_spec = stft(inputs, args, center=True, periodic=True, onesided=True)
289
+ inputs_spec = inputs_spec.to(torch.float32) # Ensure the spectrogram is in float32 format
290
+
291
+ # Compress the power of the spectrogram to improve model performance
292
+ inputs_spec = power_compress(inputs_spec).permute(0, 1, 3, 2)
293
+
294
+ # Pass the compressed spectrogram through the model to get predicted real and imaginary parts
295
+ out_list = model(inputs_spec)
296
+ pred_real, pred_imag = out_list[0].permute(0, 1, 3, 2), out_list[1].permute(0, 1, 3, 2)
297
+
298
+ # Uncompress the predicted spectrogram to get the magnitude and phase
299
+ pred_spec_uncompress = power_uncompress(pred_real, pred_imag).squeeze(1)
300
+
301
+ # Perform Inverse STFT (iSTFT) to convert back to time domain audio
302
+ outputs = istft(pred_spec_uncompress, args, center=True, periodic=True, onesided=True)
303
+
304
+ # Normalize the output audio by dividing by the normalization factor
305
+ outputs = outputs.squeeze(0) / norm_factor
306
+
307
+ return outputs[:input_len].detach().cpu().numpy() # Return the output as a numpy array
308
+
309
+ def decode_one_audio_mossformer2_se_48k(model, device, inputs, args):
310
+ """Processes audio inputs through the MossFormer2 model for speech enhancement at 48kHz.
311
+
312
+ This function decodes audio input using the following steps:
313
+ 1. Normalizes the audio input to a maximum WAV value.
314
+ 2. Checks the length of the input to decide between online decoding and batch processing.
315
+ 3. For longer inputs, processes the audio in segments using a sliding window.
316
+ 4. Computes filter banks and their deltas for the audio segment.
317
+ 5. Passes the filter banks through the model to get a predicted mask.
318
+ 6. Applies the mask to the spectrogram of the audio segment and reconstructs the audio.
319
+ 7. For shorter inputs, processes them in one go without segmentation.
320
+
321
+ Args:
322
+ model (nn.Module): The trained MossFormer2 model used for decoding.
323
+ device (torch.device): The device (CPU or GPU) for computation.
324
+ inputs (torch.Tensor): Input audio tensor of shape (B, T), where B is the batch size and T is the number of time steps.
325
+ args (Namespace): Contains arguments for sampling rate, window size, and other parameters.
326
+
327
+ Returns:
328
+ numpy.ndarray: The decoded audio output, normalized to the range [-1, 1].
329
+ """
330
+ inputs = inputs[0, :] # Extract the first element from the input tensor
331
+ input_len = inputs.shape[0] # Get the length of the input audio
332
+ inputs = inputs * MAX_WAV_VALUE # Normalize the input to the maximum WAV value
333
+
334
+ # Check if input length exceeds the defined threshold for online decoding
335
+ if input_len > args.sampling_rate * args.one_time_decode_length: # 20 seconds
336
+ online_decoding = True
337
+ if online_decoding:
338
+ window = int(args.sampling_rate * args.decode_window) # Define window length (e.g., 4s for 48kHz)
339
+ stride = int(window * 0.75) # Define stride length (e.g., 3s for 48kHz)
340
+ t = inputs.shape[0] # Update length after potential padding
341
+
342
+ # Pad input if necessary to match window size
343
+ if t < window:
344
+ inputs = np.concatenate([inputs, np.zeros(window - t)], 0)
345
+ elif t < window + stride:
346
+ padding = window + stride - t
347
+ inputs = np.concatenate([inputs, np.zeros(padding)], 0)
348
+ else:
349
+ if (t - window) % stride != 0:
350
+ padding = t - (t - window) // stride * stride
351
+ inputs = np.concatenate([inputs, np.zeros(padding)], 0)
352
+
353
+ audio = torch.from_numpy(inputs).type(torch.FloatTensor) # Convert to Torch tensor
354
+ t = audio.shape[0] # Update length after conversion
355
+ outputs = torch.from_numpy(np.zeros(t)) # Initialize output tensor
356
+ give_up_length = (window - stride) // 2 # Determine length to ignore at the edges
357
+ dfsmn_memory_length = 0 # Placeholder for potential memory length
358
+ current_idx = 0 # Initialize current index for sliding window
359
+
360
+ # Process audio in sliding window segments
361
+ while current_idx + window <= t:
362
+ # Select appropriate segment of audio for processing
363
+ if current_idx < dfsmn_memory_length:
364
+ audio_segment = audio[0:current_idx + window]
365
+ else:
366
+ audio_segment = audio[current_idx - dfsmn_memory_length:current_idx + window]
367
+
368
+ # Compute filter banks for the audio segment
369
+ fbanks = compute_fbank(audio_segment.unsqueeze(0), args)
370
+
371
+ # Compute deltas for filter banks
372
+ fbank_tr = torch.transpose(fbanks, 0, 1) # Transpose for delta computation
373
+ fbank_delta = torchaudio.functional.compute_deltas(fbank_tr) # First-order delta
374
+ fbank_delta_delta = torchaudio.functional.compute_deltas(fbank_delta) # Second-order delta
375
+
376
+ # Transpose back to original shape
377
+ fbank_delta = torch.transpose(fbank_delta, 0, 1)
378
+ fbank_delta_delta = torch.transpose(fbank_delta_delta, 0, 1)
379
+
380
+ # Concatenate the original filter banks with their deltas
381
+ fbanks = torch.cat([fbanks, fbank_delta, fbank_delta_delta], dim=1)
382
+ fbanks = fbanks.unsqueeze(0).to(device) # Add batch dimension and move to device
383
+
384
+ # Pass filter banks through the model
385
+ Out_List = model(fbanks)
386
+ pred_mask = Out_List[-1] # Get the predicted mask from the output
387
+
388
+ # Apply STFT to the audio segment
389
+ spectrum = stft(audio_segment, args)
390
+ pred_mask = pred_mask.permute(2, 1, 0) # Permute dimensions for masking
391
+ masked_spec = spectrum.cpu() * pred_mask.detach().cpu() # Apply mask to the spectrum
392
+ masked_spec_complex = masked_spec[:, :, 0] + 1j * masked_spec[:, :, 1] # Convert to complex form
393
+
394
+ # Reconstruct audio from the masked spectrogram
395
+ output_segment = istft(masked_spec_complex, args, len(audio_segment))
396
+
397
+ # Store the output segment in the output tensor
398
+ if current_idx == 0:
399
+ outputs[current_idx:current_idx + window - give_up_length] = output_segment[:-give_up_length]
400
+ else:
401
+ output_segment = output_segment[-window:] # Get the latest window of output
402
+ outputs[current_idx + give_up_length:current_idx + window - give_up_length] = output_segment[give_up_length:-give_up_length]
403
+
404
+ current_idx += stride # Move to the next segment
405
+
406
+ else:
407
+ # Process the entire audio at once if it is shorter than the threshold
408
+ audio = torch.from_numpy(inputs).type(torch.FloatTensor)
409
+ fbanks = compute_fbank(audio.unsqueeze(0), args)
410
+
411
+ # Compute deltas for filter banks
412
+ fbank_tr = torch.transpose(fbanks, 0, 1)
413
+ fbank_delta = torchaudio.functional.compute_deltas(fbank_tr)
414
+ fbank_delta_delta = torchaudio.functional.compute_deltas(fbank_delta)
415
+ fbank_delta = torch.transpose(fbank_delta, 0, 1)
416
+ fbank_delta_delta = torch.transpose(fbank_delta_delta, 0, 1)
417
+
418
+ # Concatenate the original filter banks with their deltas
419
+ fbanks = torch.cat([fbanks, fbank_delta, fbank_delta_delta], dim=1)
420
+ fbanks = fbanks.unsqueeze(0).to(device) # Add batch dimension and move to device
421
+
422
+ # Pass filter banks through the model
423
+ Out_List = model(fbanks)
424
+ pred_mask = Out_List[-1] # Get the predicted mask
425
+ spectrum = stft(audio, args) # Apply STFT to the audio
426
+ pred_mask = pred_mask.permute(2, 1, 0) # Permute dimensions for masking
427
+ masked_spec = spectrum * pred_mask.detach().cpu() # Apply mask to the spectrum
428
+ masked_spec_complex = masked_spec[:, :, 0] + 1j * masked_spec[:, :, 1] # Convert to complex form
429
+
430
+ # Reconstruct audio from the masked spectrogram
431
+ outputs = istft(masked_spec_complex, args, len(audio))
432
+
433
+ return outputs.numpy() / MAX_WAV_VALUE # Return the output normalized to [-1, 1]
434
+
435
+ def get_mel(x, args):
436
+ """
437
+ Calls mel_spectrogram() and returns the mel-spectrogram output
438
+ """
439
+
440
+ return mel_spectrogram(x, args.n_fft, args.num_mels, args.sampling_rate, args.hop_size, args.win_size, args.fmin, args.fmax)
441
+
442
+ def decode_one_audio_mossformer2_sr_48k(model, device, inputs, args):
443
+ """
444
+ This function decodes a single audio input using a two-stage speech super-resolution model.
445
+ Supports both offline decoding (for short audio) and online decoding (for long audio)
446
+ with a sliding window approach.
447
+
448
+ Parameters:
449
+ -----------
450
+ model : list
451
+ A list of two-stage models:
452
+ - model[0]: The transformer-based Mossformer model for feature enhancement.
453
+ - model[1]: The vocoder for generating high-resolution waveforms.
454
+ device : str or torch.device
455
+ The computation device ('cpu' or 'cuda') where the models will run.
456
+ inputs : torch.Tensor
457
+ A tensor of shape (batch_size, num_samples) containing low-resolution audio signals.
458
+ Only the first audio (inputs[0, :]) is processed.
459
+ args : Namespace
460
+ An object containing the following attributes:
461
+ - sampling_rate: Sampling rate of the input audio (e.g., 48,000 Hz).
462
+ - one_time_decode_length: Maximum duration (in seconds) for offline decoding.
463
+ - decode_window: Window size (in seconds) for sliding window processing.
464
+ - Other optional attributes used for Mel spectrogram extraction.
465
+
466
+ Returns:
467
+ --------
468
+ numpy.ndarray
469
+ The high-resolution audio waveform as a NumPy array, refined and upsampled.
470
+ """
471
+ inputs = inputs[0, :] # Extract the first element from the input tensor
472
+ input_len = inputs.shape[0] # Get the length of the input audio
473
+ #inputs = inputs * MAX_WAV_VALUE # Normalize the input to the maximum WAV value
474
+
475
+ # Check if input length exceeds the defined threshold for online decoding
476
+ if input_len > args.sampling_rate * args.one_time_decode_length: # 20 seconds
477
+ online_decoding = True
478
+ if online_decoding:
479
+ window = int(args.sampling_rate * args.decode_window) # Define window length (e.g., 4s for 48kHz)
480
+ stride = int(window * 0.75) # Define stride length (e.g., 3s for 48kHz)
481
+ t = inputs.shape[0] # Update length after potential padding
482
+
483
+ # Pad input if necessary to match window size
484
+ if t < window:
485
+ inputs = np.concatenate([inputs, np.zeros(window - t)], 0)
486
+ elif t < window + stride:
487
+ padding = window + stride - t
488
+ inputs = np.concatenate([inputs, np.zeros(padding)], 0)
489
+ else:
490
+ if (t - window) % stride != 0:
491
+ padding = t - (t - window) // stride * stride
492
+ inputs = np.concatenate([inputs, np.zeros(padding)], 0)
493
+
494
+ audio = torch.from_numpy(inputs).type(torch.FloatTensor) # Convert to Torch tensor
495
+ t = audio.shape[0] # Update length after conversion
496
+ outputs = torch.from_numpy(np.zeros(t)) # Initialize output tensor
497
+ give_up_length = (window - stride) // 2 # Determine length to ignore at the edges
498
+ dfsmn_memory_length = 0 # Placeholder for potential memory length
499
+ current_idx = 0 # Initialize current index for sliding window
500
+
501
+ # Process audio in sliding window segments
502
+ while current_idx + window <= t:
503
+ # Select appropriate segment of audio for processing
504
+ if current_idx < dfsmn_memory_length:
505
+ audio_segment = audio[0:current_idx + window]
506
+ else:
507
+ audio_segment = audio[current_idx - dfsmn_memory_length:current_idx + window]
508
+
509
+ # Pass filter banks through the model
510
+ mel_segment = get_mel(audio_segment.unsqueeze(0), args)
511
+ mossformer_output_segment = model[0](mel_segment.to(device))
512
+ generator_output_segment = model[1](mossformer_output_segment)
513
+ generator_output_segment = generator_output_segment.squeeze()
514
+ offset = len(audio_segment) - len(generator_output_segment)
515
+ # Store the output segment in the output tensor
516
+ if current_idx == 0:
517
+ outputs[current_idx:current_idx + window - give_up_length] = generator_output_segment[:-give_up_length+offset]
518
+ else:
519
+ generator_output_segment = generator_output_segment[-window:] # Get the latest window of output
520
+ outputs[current_idx + give_up_length:current_idx + window - give_up_length] = generator_output_segment[give_up_length:-give_up_length+offset]
521
+
522
+ current_idx += stride # Move to the next segment
523
+
524
+ else:
525
+ # Process the entire audio at once if it is shorter than the threshold
526
+ audio = torch.from_numpy(inputs).type(torch.FloatTensor)
527
+ mel_input = get_mel(audio.unsqueeze(0), args)
528
+ mossformer_output = model[0](mel_input.to(device))
529
+ generator_output = model[1](mossformer_output)
530
+ outputs = generator_output.squeeze()
531
+
532
+ outputs = outputs.cpu().numpy()
533
+ outputs = bandwidth_sub(inputs, outputs)
534
+ return outputs
535
+
536
+ def decode_one_audio_AV_MossFormer2_TSE_16K(model, inputs, args):
537
+ """Processes video inputs through the AV mossformer2 model with Target speaker extraction (TSE) for decoding at 16kHz.
538
+
539
+ This function decodes audio input using the following steps:
540
+ 1. Checks if the input audio length requires segmentation or can be processed in one go.
541
+ 2. If the input audio is long enough, processes it in overlapping segments using a sliding window approach.
542
+ 3. Applies the model to each segment or the entire input, and collects the output.
543
+
544
+ Args:
545
+ model (nn.Module): The trained SpEx model for speech enhancement.
546
+ inputs (numpy.ndarray): Input audio and visual data
547
+ args (Namespace): Contains arguments for sampling rate, window size, and other parameters.
548
+
549
+ Returns:
550
+ numpy.ndarray: The decoded audio output as a NumPy array.
551
+ """
552
+
553
+ audio, visual = inputs
554
+ max_val = np.max(np.abs(audio))
555
+ if max_val > 1:
556
+ audio /= max_val
557
+
558
+ b, t = audio.shape # Get batch size (b) and input length (t)
559
+
560
+ decode_do_segement = False # Flag to determine if segmentation is needed
561
+ # Check if the input length exceeds the defined threshold for segmentation
562
+ if t > args.sampling_rate * args.one_time_decode_length:
563
+ decode_do_segement = True # Enable segmentation for long inputs
564
+
565
+ # Convert inputs to a PyTorch tensor and move to the specified device
566
+ audio = torch.from_numpy(np.float32(audio)).to(args.device)
567
+ visual = torch.from_numpy(np.float32(visual)).to(args.device)
568
+
569
+ print(audio.shape)
570
+ print(visual.shape)
571
+
572
+ if decode_do_segement:
573
+ print('********')
574
+ outputs = np.zeros(t) # Initialize output array
575
+ window = args.sampling_rate * args.decode_window # Window length for processing
576
+ window_v = 25 * args.decode_window
577
+ stride = int(window * 0.6) # Decoding stride for segmenting the input
578
+ give_up_length = (window - stride) // 2 # Calculate length to give up at each segment
579
+ current_idx = 0 # Initialize current index for sliding window
580
+
581
+ # Process the audio in overlapping segments
582
+ while current_idx + window < t:
583
+ tmp_audio = audio[:, current_idx:current_idx + window] # Select current audio segment
584
+
585
+ current_idx_v = int(current_idx/args.sampling_rate*25) # Select current video segment index
586
+ tmp_video = visual[:, current_idx_v:current_idx_v + window_v, :, :] # Select current video segment
587
+
588
+ tmp_output = model(tmp_audio, tmp_video).detach().squeeze().cpu().numpy() # Apply model to the segment
589
+
590
+ # For the first segment, use the whole segment minus the give-up length
591
+ if current_idx == 0:
592
+ outputs[current_idx:current_idx + window - give_up_length] = tmp_output[:-give_up_length]
593
+ else:
594
+ # For subsequent segments, account for the give-up length
595
+ outputs[current_idx + give_up_length:current_idx + window - give_up_length] = tmp_output[give_up_length:-give_up_length]
596
+
597
+ current_idx += stride # Move to the next segment
598
+
599
+ # Process the last window of audio
600
+ tmp_audio = audio[:, -window:]
601
+ tmp_video = visual[:, -window_v:, :, :]
602
+ tmp_output = model(tmp_audio, tmp_video).detach().squeeze().cpu().numpy() # Apply model to the segment
603
+ outputs[-window + give_up_length:] = tmp_output[give_up_length:]
604
+ else:
605
+ # Process the entire input at once if segmentation is not needed
606
+ outputs = model(audio, visual).detach().squeeze().cpu().numpy()
607
+
608
+
609
+ return outputs # Return the decoded audio output as a NumPy array
utils/misc.py ADDED
@@ -0,0 +1,380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python -u
2
+ # -*- coding: utf-8 -*-
3
+
4
+ # Import future compatibility features for Python 2/3
5
+ from __future__ import absolute_import
6
+ from __future__ import division
7
+ from __future__ import print_function
8
+
9
+ # Import necessary libraries
10
+ import torch
11
+ import torch.nn as nn
12
+ import numpy as np
13
+ from joblib import Parallel, delayed
14
+ from pesq import pesq # PESQ metric for speech quality evaluation
15
+ import os
16
+ import sys
17
+ import librosa # Library for audio processing
18
+ import torchaudio # Library for audio processing with PyTorch
19
+
20
+ # Constants
21
+ MAX_WAV_VALUE = 32768.0 # Maximum value for WAV files
22
+ EPS = 1e-6 # Small value to avoid division by zero
23
+
24
+ def read_and_config_file(input_path, decode=0):
25
+ """Reads input paths from a file or directory and configures them for processing.
26
+
27
+ Args:
28
+ input_path (str): Path to the input directory or file.
29
+ decode (int): Flag indicating if decoding should occur (1 for decode, 0 for standard read).
30
+
31
+ Returns:
32
+ list: A list of processed paths or dictionaries containing input and label paths.
33
+ """
34
+ processed_list = []
35
+
36
+ # If decoding is requested, find files in a directory
37
+ if decode:
38
+ if os.path.isdir(input_path):
39
+ processed_list = librosa.util.find_files(input_path, ext="wav") # Look for WAV files
40
+ if len(processed_list) == 0:
41
+ processed_list = librosa.util.find_files(input_path, ext="flac") # Fallback to FLAC files
42
+ else:
43
+ # Read paths from a file
44
+ with open(input_path) as fid:
45
+ for line in fid:
46
+ path_s = line.strip().split() # Split line into parts
47
+ processed_list.append(path_s[0]) # Append the first part (input path)
48
+ return processed_list
49
+
50
+ # Read input-label pairs from a file
51
+ with open(input_path) as fid:
52
+ for line in fid:
53
+ tmp_paths = line.strip().split() # Split line into parts
54
+ if len(tmp_paths) == 3: # Expecting input, label, and duration
55
+ sample = {'inputs': tmp_paths[0], 'labels': tmp_paths[1], 'duration': float(tmp_paths[2])}
56
+ elif len(tmp_paths) == 2: # Expecting input and label only
57
+ sample = {'inputs': tmp_paths[0], 'labels': tmp_paths[1]}
58
+ processed_list.append(sample) # Append the sample dictionary
59
+ return processed_list
60
+
61
+ def load_checkpoint(checkpoint_path, use_cuda):
62
+ """Loads the model checkpoint from the specified path.
63
+
64
+ Args:
65
+ checkpoint_path (str): Path to the checkpoint file.
66
+ use_cuda (bool): Flag indicating whether to use CUDA for loading.
67
+
68
+ Returns:
69
+ dict: The loaded checkpoint containing model parameters.
70
+ """
71
+ #if use_cuda:
72
+ # checkpoint = torch.load(checkpoint_path) # Load using CUDA
73
+ #else:
74
+ checkpoint = torch.load(checkpoint_path, map_location=lambda storage, loc: storage) # Load to CPU
75
+ return checkpoint
76
+
77
+ def get_learning_rate(optimizer):
78
+ """Retrieves the current learning rate from the optimizer.
79
+
80
+ Args:
81
+ optimizer (torch.optim.Optimizer): The optimizer instance.
82
+
83
+ Returns:
84
+ float: The current learning rate.
85
+ """
86
+ return optimizer.param_groups[0]["lr"]
87
+
88
+ def reload_for_eval(model, checkpoint_dir, use_cuda):
89
+ """Reloads a model for evaluation from the specified checkpoint directory.
90
+
91
+ Args:
92
+ model (nn.Module): The model to be reloaded.
93
+ checkpoint_dir (str): Directory containing checkpoints.
94
+ use_cuda (bool): Flag indicating whether to use CUDA.
95
+
96
+ Returns:
97
+ None
98
+ """
99
+ print('Reloading from: {}'.format(checkpoint_dir))
100
+ best_name = os.path.join(checkpoint_dir, 'last_best_checkpoint') # Path to the best checkpoint
101
+ ckpt_name = os.path.join(checkpoint_dir, 'last_checkpoint') # Path to the last checkpoint
102
+ if os.path.isfile(best_name):
103
+ name = best_name
104
+ elif os.path.isfile(ckpt_name):
105
+ name = ckpt_name
106
+ else:
107
+ print('Warning: No existing checkpoint or best_model found!')
108
+ return
109
+
110
+ with open(name, 'r') as f:
111
+ model_name = f.readline().strip() # Read the model name from the checkpoint file
112
+ checkpoint_path = os.path.join(checkpoint_dir, model_name) # Construct full checkpoint path
113
+ print('Checkpoint path: {}'.format(checkpoint_path))
114
+ checkpoint = load_checkpoint(checkpoint_path, use_cuda) # Load the checkpoint
115
+ '''
116
+ if 'model' in checkpoint:
117
+ model.load_state_dict(checkpoint['model'], strict=False) # Load model parameters
118
+ else:
119
+ model.load_state_dict(checkpoint, strict=False)
120
+ '''
121
+ if 'model' in checkpoint:
122
+ pretrained_model = checkpoint['model']
123
+ else:
124
+ pretrained_model = checkpoint
125
+ state = model.state_dict()
126
+ for key in state.keys():
127
+ if key in pretrained_model and state[key].shape == pretrained_model[key].shape:
128
+ state[key] = pretrained_model[key]
129
+ elif key.replace('module.', '') in pretrained_model and state[key].shape == pretrained_model[key.replace('module.', '')].shape:
130
+ state[key] = pretrained_model[key.replace('module.', '')]
131
+ elif 'module.'+key in pretrained_model and state[key].shape == pretrained_model['module.'+key].shape:
132
+ state[key] = pretrained_model['module.'+key]
133
+ elif self.print: print(f'{key} not loaded')
134
+ model.load_state_dict(state)
135
+
136
+ print('=> Reload well-trained model {} for decoding.'.format(model_name))
137
+
138
+
139
+ def reload_model(model, optimizer, checkpoint_dir, use_cuda=True, strict=True):
140
+ """Reloads the model and optimizer state from a checkpoint.
141
+
142
+ Args:
143
+ model (nn.Module): The model to be reloaded.
144
+ optimizer (torch.optim.Optimizer): The optimizer to be reloaded.
145
+ checkpoint_dir (str): Directory containing checkpoints.
146
+ use_cuda (bool): Flag indicating whether to use CUDA.
147
+ strict (bool): If True, requires keys in state_dict to match exactly.
148
+
149
+ Returns:
150
+ tuple: Current epoch and step.
151
+ """
152
+ ckpt_name = os.path.join(checkpoint_dir, 'checkpoint') # Path to the checkpoint file
153
+ if os.path.isfile(ckpt_name):
154
+ with open(ckpt_name, 'r') as f:
155
+ model_name = f.readline().strip() # Read model name from checkpoint file
156
+ checkpoint_path = os.path.join(checkpoint_dir, model_name) # Construct full checkpoint path
157
+ checkpoint = load_checkpoint(checkpoint_path, use_cuda) # Load the checkpoint
158
+ model.load_state_dict(checkpoint['model'], strict=strict) # Load model parameters
159
+ optimizer.load_state_dict(checkpoint['optimizer']) # Load optimizer parameters
160
+ epoch = checkpoint['epoch'] # Get current epoch
161
+ step = checkpoint['step'] # Get current step
162
+ print('=> Reloaded previous model and optimizer.')
163
+ else:
164
+ print('[!] Checkpoint directory is empty. Train a new model ...')
165
+ epoch = 0 # Initialize epoch
166
+ step = 0 # Initialize step
167
+ return epoch, step
168
+
169
+ def save_checkpoint(model, optimizer, epoch, step, checkpoint_dir, mode='checkpoint'):
170
+ """Saves the model and optimizer state to a checkpoint file.
171
+
172
+ Args:
173
+ model (nn.Module): The model to be saved.
174
+ optimizer (torch.optim.Optimizer): The optimizer to be saved.
175
+ epoch (int): Current epoch number.
176
+ step (int): Current training step number.
177
+ checkpoint_dir (str): Directory to save the checkpoint.
178
+ mode (str): Mode of the checkpoint ('checkpoint' or other).
179
+
180
+ Returns:
181
+ None
182
+ """
183
+ checkpoint_path = os.path.join(
184
+ checkpoint_dir, 'model.ckpt-{}-{}.pt'.format(epoch, step)) # Construct checkpoint file path
185
+ torch.save({'model': model.state_dict(), # Save model parameters
186
+ 'optimizer': optimizer.state_dict(), # Save optimizer parameters
187
+ 'epoch': epoch, # Save epoch
188
+ 'step': step}, checkpoint_path) # Save checkpoint to file
189
+
190
+ # Save the checkpoint name to a file for easy access
191
+ with open(os.path.join(checkpoint_dir, mode), 'w') as f:
192
+ f.write('model.ckpt-{}-{}.pt'.format(epoch, step))
193
+ print("=> Saved checkpoint:", checkpoint_path)
194
+
195
+ def setup_lr(opt, lr):
196
+ """Sets the learning rate for all parameter groups in the optimizer.
197
+
198
+ Args:
199
+ opt (torch.optim.Optimizer): The optimizer instance whose learning rate needs to be set.
200
+ lr (float): The new learning rate to be assigned.
201
+
202
+ Returns:
203
+ None
204
+ """
205
+ for param_group in opt.param_groups:
206
+ param_group['lr'] = lr # Update the learning rate for each parameter group
207
+
208
+
209
+ def pesq_loss(clean, noisy, sr=16000):
210
+ """Calculates the PESQ (Perceptual Evaluation of Speech Quality) score between clean and noisy signals.
211
+
212
+ Args:
213
+ clean (ndarray): The clean audio signal.
214
+ noisy (ndarray): The noisy audio signal.
215
+ sr (int): Sample rate of the audio signals (default is 16000 Hz).
216
+
217
+ Returns:
218
+ float: The PESQ score or -1 in case of an error.
219
+ """
220
+ try:
221
+ pesq_score = pesq(sr, clean, noisy, 'wb') # Compute PESQ score
222
+ except:
223
+ # PESQ may fail due to silent periods in audio
224
+ pesq_score = -1 # Assign -1 to indicate error
225
+ return pesq_score
226
+
227
+
228
+ def batch_pesq(clean, noisy):
229
+ """Computes the PESQ scores for batches of clean and noisy audio signals.
230
+
231
+ Args:
232
+ clean (list of ndarray): List of clean audio signals.
233
+ noisy (list of ndarray): List of noisy audio signals.
234
+
235
+ Returns:
236
+ torch.FloatTensor: A tensor of normalized PESQ scores or None if any score is -1.
237
+ """
238
+ # Parallel processing for calculating PESQ scores for each pair of clean and noisy signals
239
+ pesq_score = Parallel(n_jobs=-1)(delayed(pesq_loss)(c, n) for c, n in zip(clean, noisy))
240
+ pesq_score = np.array(pesq_score) # Convert to NumPy array
241
+
242
+ if -1 in pesq_score: # Check for errors in PESQ calculations
243
+ return None
244
+
245
+ # Normalize PESQ scores to a scale of 0 to 1
246
+ pesq_score = (pesq_score - 1) / 3.5
247
+ return torch.FloatTensor(pesq_score).to('cuda') # Return normalized scores as a tensor
248
+
249
+
250
+ def power_compress(x):
251
+ """Compresses the power of a complex spectrogram.
252
+
253
+ Args:
254
+ x (torch.Tensor): Input tensor with real and imaginary components.
255
+
256
+ Returns:
257
+ torch.Tensor: Compressed magnitude and phase representation of the input.
258
+ """
259
+ real = x[..., 0] # Extract real part
260
+ imag = x[..., 1] # Extract imaginary part
261
+ spec = torch.complex(real, imag) # Create complex tensor from real and imaginary parts
262
+ mag = torch.abs(spec) # Compute magnitude
263
+ phase = torch.angle(spec) # Compute phase
264
+
265
+ mag = mag**0.3 # Compress magnitude using power of 0.3
266
+ real_compress = mag * torch.cos(phase) # Reconstruct real part
267
+ imag_compress = mag * torch.sin(phase) # Reconstruct imaginary part
268
+ return torch.stack([real_compress, imag_compress], 1) # Stack compressed parts
269
+
270
+
271
+ def power_uncompress(real, imag):
272
+ """Uncompresses the power of a compressed complex spectrogram.
273
+
274
+ Args:
275
+ real (torch.Tensor): Compressed real component.
276
+ imag (torch.Tensor): Compressed imaginary component.
277
+
278
+ Returns:
279
+ torch.Tensor: Uncompressed complex spectrogram.
280
+ """
281
+ spec = torch.complex(real, imag) # Create complex tensor from real and imaginary parts
282
+ mag = torch.abs(spec) # Compute magnitude
283
+ phase = torch.angle(spec) # Compute phase
284
+
285
+ mag = mag**(1./0.3) # Uncompress magnitude by raising to the power of 1/0.3
286
+ real_uncompress = mag * torch.cos(phase) # Reconstruct real part
287
+ imag_uncompress = mag * torch.sin(phase) # Reconstruct imaginary part
288
+ return torch.stack([real_uncompress, imag_uncompress], -1) # Stack uncompressed parts
289
+
290
+
291
+ def stft(x, args, center=False, periodic=False, onesided=None):
292
+ """Computes the Short-Time Fourier Transform (STFT) of an audio signal.
293
+
294
+ Args:
295
+ x (torch.Tensor): Input audio signal.
296
+ args (Namespace): Configuration arguments containing window type and lengths.
297
+ center (bool): Whether to center the window.
298
+
299
+ Returns:
300
+ torch.Tensor: The computed STFT of the input signal.
301
+ """
302
+ win_type = args.win_type
303
+ win_len = args.win_len
304
+ win_inc = args.win_inc
305
+ fft_len = args.fft_len
306
+
307
+ # Select window type and create window tensor
308
+ if win_type == 'hamming':
309
+ window = torch.hamming_window(win_len, periodic=periodic).to(x.device)
310
+ elif win_type == 'hanning':
311
+ window = torch.hann_window(win_len, periodic=periodic).to(x.device)
312
+ else:
313
+ print(f"In STFT, {win_type} is not supported!")
314
+ return
315
+
316
+ # Compute and return the STFT
317
+ return torch.stft(x, fft_len, win_inc, win_len, center=center, window=window, onesided=onesided, return_complex=False)
318
+
319
+ def istft(x, args, slen=None, center=False, normalized=False, periodic=False, onesided=None, return_complex=False):
320
+ """Computes the inverse Short-Time Fourier Transform (ISTFT) of a complex spectrogram.
321
+
322
+ Args:
323
+ x (torch.Tensor): Input complex spectrogram.
324
+ args (Namespace): Configuration arguments containing window type and lengths.
325
+ slen (int, optional): Length of the output signal.
326
+ center (bool): Whether to center the window.
327
+ normalized (bool): Whether to normalize the output.
328
+ onesided (bool, optional): If True, computes only the one-sided transform.
329
+ return_complex (bool): If True, returns complex output.
330
+
331
+ Returns:
332
+ torch.Tensor: The reconstructed audio signal from the spectrogram.
333
+ """
334
+ win_type = args.win_type
335
+ win_len = args.win_len
336
+ win_inc = args.win_inc
337
+ fft_len = args.fft_len
338
+
339
+ # Select window type and create window tensor
340
+ if win_type == 'hamming':
341
+ window = torch.hamming_window(win_len, periodic=periodic).to(x.device)
342
+ elif win_type == 'hanning':
343
+ window = torch.hann_window(win_len, periodic=periodic).to(x.device)
344
+ else:
345
+ print(f"In ISTFT, {win_type} is not supported!")
346
+ return
347
+
348
+ try:
349
+ # Attempt to compute ISTFT
350
+ output = torch.istft(x, n_fft=fft_len, hop_length=win_inc, win_length=win_len,
351
+ window=window, center=center, normalized=normalized,
352
+ onesided=onesided, length=slen, return_complex=False)
353
+ except:
354
+ # Handle potential errors by converting x to a complex tensor
355
+ x_complex = torch.view_as_complex(x)
356
+ output = torch.istft(x_complex, n_fft=fft_len, hop_length=win_inc, win_length=win_len,
357
+ window=window, center=center, normalized=normalized,
358
+ onesided=onesided, length=slen, return_complex=False)
359
+ return output
360
+
361
+ def compute_fbank(audio_in, args):
362
+ """Computes the filter bank features from an audio signal.
363
+
364
+ Args:
365
+ audio_in (torch.Tensor): Input audio signal.
366
+ args (Namespace): Configuration arguments containing window length, shift, and sampling rate.
367
+
368
+ Returns:
369
+ torch.Tensor: Computed filter bank features.
370
+ """
371
+ frame_length = args.win_len / args.sampling_rate * 1000 # Frame length in milliseconds
372
+ frame_shift = args.win_inc / args.sampling_rate * 1000 # Frame shift in milliseconds
373
+
374
+ # Compute and return filter bank features using Kaldi's implementation
375
+ return torchaudio.compliance.kaldi.fbank(audio_in, dither=1.0, frame_length=frame_length,
376
+ frame_shift=frame_shift, num_mel_bins=args.num_mels,
377
+ sample_frequency=args.sampling_rate, window_type=args.win_type)
378
+
379
+
380
+
utils/video_process.py ADDED
@@ -0,0 +1,361 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ import sys, time, os, tqdm, torch, argparse, glob, subprocess, warnings, cv2, pickle, pdb, math, python_speech_features
4
+ import numpy as np
5
+ from scipy import signal
6
+ from shutil import rmtree
7
+ from scipy.io import wavfile
8
+ from scipy.interpolate import interp1d
9
+ from sklearn.metrics import accuracy_score, f1_score
10
+ import soundfile as sf
11
+
12
+ from scenedetect.video_manager import VideoManager
13
+ from scenedetect.scene_manager import SceneManager
14
+ from scenedetect.frame_timecode import FrameTimecode
15
+ from scenedetect.stats_manager import StatsManager
16
+ from scenedetect.detectors import ContentDetector
17
+
18
+ from models.av_mossformer2_tse.faceDetector.s3fd import S3FD
19
+
20
+ from .decode import decode_one_audio_AV_MossFormer2_TSE_16K
21
+
22
+
23
+
24
+ def process_tse(args, model, device, data_reader, output_wave_dir):
25
+ video_args = args_param()
26
+ video_args.model = model
27
+ video_args.device = device
28
+ video_args.sampling_rate = args.sampling_rate
29
+ args.device = device
30
+ assert args.sampling_rate == 16000
31
+ with torch.no_grad():
32
+ for videoPath in data_reader: # Loop over all video samples
33
+ savFolder = videoPath.split(os.path.sep)[-1]
34
+ video_args.savePath = f'{output_wave_dir}/{savFolder.split(".")[0]}/'
35
+ video_args.videoPath = videoPath
36
+ main(video_args, args)
37
+
38
+
39
+
40
+ def args_param():
41
+ warnings.filterwarnings("ignore")
42
+ parser = argparse.ArgumentParser()
43
+ parser.add_argument('--nDataLoaderThread', type=int, default=10, help='Number of workers')
44
+ parser.add_argument('--facedetScale', type=float, default=0.25, help='Scale factor for face detection, the frames will be scale to 0.25 orig')
45
+ parser.add_argument('--minTrack', type=int, default=50, help='Number of min frames for each shot')
46
+ parser.add_argument('--numFailedDet', type=int, default=10, help='Number of missed detections allowed before tracking is stopped')
47
+ parser.add_argument('--minFaceSize', type=int, default=1, help='Minimum face size in pixels')
48
+ parser.add_argument('--cropScale', type=float, default=0.40, help='Scale bounding box')
49
+ parser.add_argument('--start', type=int, default=0, help='The start time of the video')
50
+ parser.add_argument('--duration', type=int, default=0, help='The duration of the video, when set as 0, will extract the whole video')
51
+ video_args = parser.parse_args()
52
+ return video_args
53
+
54
+
55
+ # Main function
56
+ def main(video_args, args):
57
+ # Initialization
58
+ video_args.pyaviPath = os.path.join(video_args.savePath, 'py_video')
59
+ video_args.pyframesPath = os.path.join(video_args.savePath, 'pyframes')
60
+ video_args.pyworkPath = os.path.join(video_args.savePath, 'pywork')
61
+ video_args.pycropPath = os.path.join(video_args.savePath, 'py_faceTracks')
62
+ if os.path.exists(video_args.savePath):
63
+ rmtree(video_args.savePath)
64
+ os.makedirs(video_args.pyaviPath, exist_ok = True) # The path for the input video, input audio, output video
65
+ os.makedirs(video_args.pyframesPath, exist_ok = True) # Save all the video frames
66
+ os.makedirs(video_args.pyworkPath, exist_ok = True) # Save the results in this process by the pckl method
67
+ os.makedirs(video_args.pycropPath, exist_ok = True) # Save the detected face clips (audio+video) in this process
68
+
69
+ # Extract video
70
+ video_args.videoFilePath = os.path.join(video_args.pyaviPath, 'video.avi')
71
+ # If duration did not set, extract the whole video, otherwise extract the video from 'video_args.start' to 'video_args.start + video_args.duration'
72
+ if video_args.duration == 0:
73
+ command = ("ffmpeg -y -i %s -qscale:v 2 -threads %d -async 1 -r 25 %s -loglevel panic" % \
74
+ (video_args.videoPath, video_args.nDataLoaderThread, video_args.videoFilePath))
75
+ else:
76
+ command = ("ffmpeg -y -i %s -qscale:v 2 -threads %d -ss %.3f -to %.3f -async 1 -r 25 %s -loglevel panic" % \
77
+ (video_args.videoPath, video_args.nDataLoaderThread, video_args.start, video_args.start + video_args.duration, video_args.videoFilePath))
78
+ subprocess.call(command, shell=True, stdout=None)
79
+ sys.stderr.write(time.strftime("%Y-%m-%d %H:%M:%S") + " Extract the video and save in %s \r\n" %(video_args.videoFilePath))
80
+
81
+ # Extract audio
82
+ video_args.audioFilePath = os.path.join(video_args.pyaviPath, 'audio.wav')
83
+ command = ("ffmpeg -y -i %s -qscale:a 0 -ac 1 -vn -threads %d -ar 16000 %s -loglevel panic" % \
84
+ (video_args.videoFilePath, video_args.nDataLoaderThread, video_args.audioFilePath))
85
+ subprocess.call(command, shell=True, stdout=None)
86
+ sys.stderr.write(time.strftime("%Y-%m-%d %H:%M:%S") + " Extract the audio and save in %s \r\n" %(video_args.audioFilePath))
87
+
88
+ # Extract the video frames
89
+ command = ("ffmpeg -y -i %s -qscale:v 2 -threads %d -f image2 %s -loglevel panic" % \
90
+ (video_args.videoFilePath, video_args.nDataLoaderThread, os.path.join(video_args.pyframesPath, '%06d.jpg')))
91
+ subprocess.call(command, shell=True, stdout=None)
92
+ sys.stderr.write(time.strftime("%Y-%m-%d %H:%M:%S") + " Extract the frames and save in %s \r\n" %(video_args.pyframesPath))
93
+
94
+ # Scene detection for the video frames
95
+ scene = scene_detect(video_args)
96
+ sys.stderr.write(time.strftime("%Y-%m-%d %H:%M:%S") + " Scene detection and save in %s \r\n" %(video_args.pyworkPath))
97
+
98
+ # Face detection for the video frames
99
+ faces = inference_video(video_args)
100
+ sys.stderr.write(time.strftime("%Y-%m-%d %H:%M:%S") + " Face detection and save in %s \r\n" %(video_args.pyworkPath))
101
+
102
+ # Face tracking
103
+ allTracks, vidTracks = [], []
104
+ for shot in scene:
105
+ if shot[1].frame_num - shot[0].frame_num >= video_args.minTrack: # Discard the shot frames less than minTrack frames
106
+ allTracks.extend(track_shot(video_args, faces[shot[0].frame_num:shot[1].frame_num])) # 'frames' to present this tracks' timestep, 'bbox' presents the location of the faces
107
+ sys.stderr.write(time.strftime("%Y-%m-%d %H:%M:%S") + " Face track and detected %d tracks \r\n" %len(allTracks))
108
+
109
+ # Face clips cropping
110
+ for ii, track in tqdm.tqdm(enumerate(allTracks), total = len(allTracks)):
111
+ vidTracks.append(crop_video(video_args, track, os.path.join(video_args.pycropPath, '%05d'%ii)))
112
+ savePath = os.path.join(video_args.pyworkPath, 'tracks.pckl')
113
+ with open(savePath, 'wb') as fil:
114
+ pickle.dump(vidTracks, fil)
115
+ sys.stderr.write(time.strftime("%Y-%m-%d %H:%M:%S") + " Face Crop and saved in %s tracks \r\n" %video_args.pycropPath)
116
+ fil = open(savePath, 'rb')
117
+ vidTracks = pickle.load(fil)
118
+ fil.close()
119
+
120
+ # AVSE
121
+ files = glob.glob("%s/*.avi"%video_args.pycropPath)
122
+ files.sort()
123
+
124
+ est_sources = evaluate_network(files, video_args, args)
125
+
126
+ visualization(vidTracks, est_sources, video_args)
127
+
128
+ # combine files in pycrop
129
+ for idx, file in enumerate(files):
130
+ print(file)
131
+ command = f"ffmpeg -i {file} {file[:-9]}orig_{idx}.mp4 ;"
132
+ command += f"rm {file} ;"
133
+ command += f"rm {file.replace('.avi', '.wav')} ;"
134
+
135
+ command += f"ffmpeg -i {file[:-9]}orig_{idx}.mp4 -i {file[:-9]}est_{idx}.wav -c:v copy -map 0:v:0 -map 1:a:0 -shortest {file[:-9]}est_{idx}.mp4 ;"
136
+ # command += f"rm {file[:-9]}est_{idx}.wav ;"
137
+
138
+ output = subprocess.call(command, shell=True, stdout=None)
139
+
140
+ rmtree(video_args.pyworkPath)
141
+ rmtree(video_args.pyframesPath)
142
+
143
+
144
+
145
+
146
+ def scene_detect(video_args):
147
+ # CPU: Scene detection, output is the list of each shot's time duration
148
+ videoManager = VideoManager([video_args.videoFilePath])
149
+ statsManager = StatsManager()
150
+ sceneManager = SceneManager(statsManager)
151
+ sceneManager.add_detector(ContentDetector())
152
+ baseTimecode = videoManager.get_base_timecode()
153
+ videoManager.set_downscale_factor()
154
+ videoManager.start()
155
+ sceneManager.detect_scenes(frame_source = videoManager)
156
+ sceneList = sceneManager.get_scene_list(baseTimecode)
157
+ savePath = os.path.join(video_args.pyworkPath, 'scene.pckl')
158
+ if sceneList == []:
159
+ sceneList = [(videoManager.get_base_timecode(),videoManager.get_current_timecode())]
160
+ with open(savePath, 'wb') as fil:
161
+ pickle.dump(sceneList, fil)
162
+ sys.stderr.write('%s - scenes detected %d\n'%(video_args.videoFilePath, len(sceneList)))
163
+ return sceneList
164
+
165
+ def inference_video(video_args):
166
+ # GPU: Face detection, output is the list contains the face location and score in this frame
167
+ DET = S3FD(device=video_args.device)
168
+ flist = glob.glob(os.path.join(video_args.pyframesPath, '*.jpg'))
169
+ flist.sort()
170
+ dets = []
171
+ for fidx, fname in enumerate(flist):
172
+ image = cv2.imread(fname)
173
+ imageNumpy = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
174
+ bboxes = DET.detect_faces(imageNumpy, conf_th=0.9, scales=[video_args.facedetScale])
175
+ dets.append([])
176
+ for bbox in bboxes:
177
+ dets[-1].append({'frame':fidx, 'bbox':(bbox[:-1]).tolist(), 'conf':bbox[-1]}) # dets has the frames info, bbox info, conf info
178
+ sys.stderr.write('%s-%05d; %d dets\r' % (video_args.videoFilePath, fidx, len(dets[-1])))
179
+ savePath = os.path.join(video_args.pyworkPath,'faces.pckl')
180
+ with open(savePath, 'wb') as fil:
181
+ pickle.dump(dets, fil)
182
+ return dets
183
+
184
+ def bb_intersection_over_union(boxA, boxB, evalCol = False):
185
+ # CPU: IOU Function to calculate overlap between two image
186
+ xA = max(boxA[0], boxB[0])
187
+ yA = max(boxA[1], boxB[1])
188
+ xB = min(boxA[2], boxB[2])
189
+ yB = min(boxA[3], boxB[3])
190
+ interArea = max(0, xB - xA) * max(0, yB - yA)
191
+ boxAArea = (boxA[2] - boxA[0]) * (boxA[3] - boxA[1])
192
+ boxBArea = (boxB[2] - boxB[0]) * (boxB[3] - boxB[1])
193
+ if evalCol == True:
194
+ iou = interArea / float(boxAArea)
195
+ else:
196
+ iou = interArea / float(boxAArea + boxBArea - interArea)
197
+ return iou
198
+
199
+ def track_shot(video_args, sceneFaces):
200
+ # CPU: Face tracking
201
+ iouThres = 0.5 # Minimum IOU between consecutive face detections
202
+ tracks = []
203
+ while True:
204
+ track = []
205
+ for frameFaces in sceneFaces:
206
+ for face in frameFaces:
207
+ if track == []:
208
+ track.append(face)
209
+ frameFaces.remove(face)
210
+ elif face['frame'] - track[-1]['frame'] <= video_args.numFailedDet:
211
+ iou = bb_intersection_over_union(face['bbox'], track[-1]['bbox'])
212
+ if iou > iouThres:
213
+ track.append(face)
214
+ frameFaces.remove(face)
215
+ continue
216
+ else:
217
+ break
218
+ if track == []:
219
+ break
220
+ elif len(track) > video_args.minTrack:
221
+ frameNum = np.array([ f['frame'] for f in track ])
222
+ bboxes = np.array([np.array(f['bbox']) for f in track])
223
+ frameI = np.arange(frameNum[0],frameNum[-1]+1)
224
+ bboxesI = []
225
+ for ij in range(0,4):
226
+ interpfn = interp1d(frameNum, bboxes[:,ij])
227
+ bboxesI.append(interpfn(frameI))
228
+ bboxesI = np.stack(bboxesI, axis=1)
229
+ if max(np.mean(bboxesI[:,2]-bboxesI[:,0]), np.mean(bboxesI[:,3]-bboxesI[:,1])) > video_args.minFaceSize:
230
+ tracks.append({'frame':frameI,'bbox':bboxesI})
231
+ return tracks
232
+
233
+ def crop_video(video_args, track, cropFile):
234
+ # CPU: crop the face clips
235
+ flist = glob.glob(os.path.join(video_args.pyframesPath, '*.jpg')) # Read the frames
236
+ flist.sort()
237
+ vOut = cv2.VideoWriter(cropFile + 't.avi', cv2.VideoWriter_fourcc(*'XVID'), 25, (224,224))# Write video
238
+ dets = {'x':[], 'y':[], 's':[]}
239
+ for det in track['bbox']: # Read the tracks
240
+ dets['s'].append(max((det[3]-det[1]), (det[2]-det[0]))/2)
241
+ dets['y'].append((det[1]+det[3])/2) # crop center x
242
+ dets['x'].append((det[0]+det[2])/2) # crop center y
243
+ dets['s'] = signal.medfilt(dets['s'], kernel_size=13) # Smooth detections
244
+ dets['x'] = signal.medfilt(dets['x'], kernel_size=13)
245
+ dets['y'] = signal.medfilt(dets['y'], kernel_size=13)
246
+ for fidx, frame in enumerate(track['frame']):
247
+ cs = video_args.cropScale
248
+ bs = dets['s'][fidx] # Detection box size
249
+ bsi = int(bs * (1 + 2 * cs)) # Pad videos by this amount
250
+ image = cv2.imread(flist[frame])
251
+ frame = np.pad(image, ((bsi,bsi), (bsi,bsi), (0, 0)), 'constant', constant_values=(110, 110))
252
+ my = dets['y'][fidx] + bsi # BBox center Y
253
+ mx = dets['x'][fidx] + bsi # BBox center X
254
+ face = frame[int(my-bs):int(my+bs*(1+2*cs)),int(mx-bs*(1+cs)):int(mx+bs*(1+cs))]
255
+ vOut.write(cv2.resize(face, (224, 224)))
256
+ audioTmp = cropFile + '.wav'
257
+ audioStart = (track['frame'][0]) / 25
258
+ audioEnd = (track['frame'][-1]+1) / 25
259
+ vOut.release()
260
+ command = ("ffmpeg -y -i %s -async 1 -ac 1 -vn -acodec pcm_s16le -ar 16000 -threads %d -ss %.3f -to %.3f %s -loglevel panic" % \
261
+ (video_args.audioFilePath, video_args.nDataLoaderThread, audioStart, audioEnd, audioTmp))
262
+ output = subprocess.call(command, shell=True, stdout=None) # Crop audio file
263
+ _, audio = wavfile.read(audioTmp)
264
+ command = ("ffmpeg -y -i %st.avi -i %s -threads %d -c:v copy -c:a copy %s.avi -loglevel panic" % \
265
+ (cropFile, audioTmp, video_args.nDataLoaderThread, cropFile)) # Combine audio and video file
266
+ output = subprocess.call(command, shell=True, stdout=None)
267
+ os.remove(cropFile + 't.avi')
268
+ return {'track':track, 'proc_track':dets}
269
+
270
+
271
+ def evaluate_network(files, video_args, args):
272
+
273
+ est_sources = []
274
+ for file in tqdm.tqdm(files, total = len(files)):
275
+
276
+ fileName = os.path.splitext(file.split(os.path.sep)[-1])[0] # Load audio and video
277
+ audio, _ = sf.read(os.path.join(video_args.pycropPath, fileName + '.wav'), dtype='float32')
278
+
279
+ video = cv2.VideoCapture(os.path.join(video_args.pycropPath, fileName + '.avi'))
280
+ videoFeature = []
281
+ while video.isOpened():
282
+ ret, frames = video.read()
283
+ if ret == True:
284
+ face = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY)
285
+ face = cv2.resize(face, (224,224))
286
+ face = face[int(112-(112/2)):int(112+(112/2)), int(112-(112/2)):int(112+(112/2))]
287
+ videoFeature.append(face)
288
+ else:
289
+ break
290
+
291
+ video.release()
292
+ visual = np.array(videoFeature)/255.0
293
+ visual = (visual - 0.4161)/0.1688
294
+
295
+ length = int(audio.shape[0]/16000*25)
296
+ if visual.shape[0] < length:
297
+ visual = np.pad(visual, ((0,int(length - visual.shape[0])),(0,0),(0,0)), mode = 'edge')
298
+
299
+ audio /= np.max(np.abs(audio))
300
+ audio = np.expand_dims(audio, axis=0)
301
+ visual = np.expand_dims(visual, axis=0)
302
+
303
+ inputs = (audio, visual)
304
+ est_source = decode_one_audio_AV_MossFormer2_TSE_16K(video_args.model, inputs, args)
305
+
306
+ est_sources.append(est_source)
307
+
308
+ return est_sources
309
+
310
+ def visualization(tracks, est_sources, video_args):
311
+ # CPU: visulize the result for video format
312
+ flist = glob.glob(os.path.join(video_args.pyframesPath, '*.jpg'))
313
+ flist.sort()
314
+
315
+
316
+ for idx, audio in enumerate(est_sources):
317
+ max_value = np.max(np.abs(audio))
318
+ if max_value >1:
319
+ audio /= max_value
320
+ sf.write(video_args.pycropPath +'/est_%s.wav' %idx, audio, 16000)
321
+
322
+ for tidx, track in enumerate(tracks):
323
+ faces = [[] for i in range(len(flist))]
324
+ for fidx, frame in enumerate(track['track']['frame'].tolist()):
325
+ faces[frame].append({'track':tidx, 's':track['proc_track']['s'][fidx], 'x':track['proc_track']['x'][fidx], 'y':track['proc_track']['y'][fidx]})
326
+
327
+ firstImage = cv2.imread(flist[0])
328
+ fw = firstImage.shape[1]
329
+ fh = firstImage.shape[0]
330
+ vOut = cv2.VideoWriter(os.path.join(video_args.pyaviPath, 'video_only.avi'), cv2.VideoWriter_fourcc(*'XVID'), 25, (fw,fh))
331
+ for fidx, fname in tqdm.tqdm(enumerate(flist), total = len(flist)):
332
+ image = cv2.imread(fname)
333
+ for face in faces[fidx]:
334
+ cv2.rectangle(image, (int(face['x']-face['s']), int(face['y']-face['s'])), (int(face['x']+face['s']), int(face['y']+face['s'])),(0,255,0),10)
335
+ vOut.write(image)
336
+ vOut.release()
337
+
338
+ command = ("ffmpeg -y -i %s -i %s -threads %d -c:v copy -c:a copy %s -loglevel panic" % \
339
+ (os.path.join(video_args.pyaviPath, 'video_only.avi'), (video_args.pycropPath +'/est_%s.wav' %tidx), \
340
+ video_args.nDataLoaderThread, os.path.join(video_args.pyaviPath,'video_out_%s.avi'%tidx)))
341
+ output = subprocess.call(command, shell=True, stdout=None)
342
+
343
+
344
+
345
+
346
+ command = "ffmpeg -i %s %s ;" % (
347
+ os.path.join(video_args.pyaviPath, 'video_out_%s.avi' % tidx),
348
+ os.path.join(video_args.pyaviPath, 'video_est_%s.mp4' % tidx)
349
+ )
350
+ command += f"rm {os.path.join(video_args.pyaviPath, 'video_out_%s.avi' % tidx)}"
351
+ output = subprocess.call(command, shell=True, stdout=None)
352
+
353
+
354
+ command = "ffmpeg -i %s %s ;" % (
355
+ os.path.join(video_args.pyaviPath, 'video.avi'),
356
+ os.path.join(video_args.pyaviPath, 'video_orig.mp4')
357
+ )
358
+ command += f"rm {os.path.join(video_args.pyaviPath, 'video_only.avi')} ;"
359
+ command += f"rm {os.path.join(video_args.pyaviPath, 'video.avi')} ;"
360
+ command += f"rm {os.path.join(video_args.pyaviPath, 'audio.wav')} ;"
361
+ output = subprocess.call(command, shell=True, stdout=None)