alibabasglab commited on
Commit
6526105
·
verified ·
1 Parent(s): 126c408

Delete utils

Browse files
utils/__pycache__/__init__.cpython-36.pyc DELETED
Binary file (245 Bytes)
 
utils/__pycache__/__init__.cpython-37.pyc DELETED
Binary file (268 Bytes)
 
utils/__pycache__/__init__.cpython-38.pyc DELETED
Binary file (270 Bytes)
 
utils/__pycache__/decode.cpython-38.pyc DELETED
Binary file (13.4 kB)
 
utils/__pycache__/misc.cpython-36.pyc DELETED
Binary file (3.23 kB)
 
utils/__pycache__/misc.cpython-37.pyc DELETED
Binary file (3.25 kB)
 
utils/__pycache__/misc.cpython-38.pyc DELETED
Binary file (11.5 kB)
 
utils/__pycache__/time_dataset.cpython-36.pyc DELETED
Binary file (5.8 kB)
 
utils/__pycache__/time_dataset.cpython-37.pyc DELETED
Binary file (6.09 kB)
 
utils/__pycache__/time_dataset.cpython-38.pyc DELETED
Binary file (6.15 kB)
 
utils/decode.py DELETED
@@ -1,532 +0,0 @@
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
-
17
- # Constant for normalizing audio values
18
- MAX_WAV_VALUE = 32768.0
19
-
20
- def decode_one_audio(model, device, inputs, args):
21
- """Decodes audio using the specified model based on the provided network type.
22
-
23
- This function selects the appropriate decoding function based on the specified
24
- network in the arguments and processes the input audio data accordingly.
25
-
26
- Args:
27
- model (nn.Module): The trained model used for decoding.
28
- device (torch.device): The device (CPU or GPU) to perform computations on.
29
- inputs (torch.Tensor): Input audio tensor.
30
- args (Namespace): Contains arguments for network configuration.
31
-
32
- Returns:
33
- list: A list of decoded audio outputs for each speaker.
34
- """
35
- # Select decoding function based on the network type specified in args
36
- if args.network == 'FRCRN_SE_16K':
37
- return decode_one_audio_frcrn_se_16k(model, device, inputs, args)
38
- elif args.network == 'MossFormer2_SE_48K':
39
- return decode_one_audio_mossformer2_se_48k(model, device, inputs, args)
40
- elif args.network == 'MossFormerGAN_SE_16K':
41
- return decode_one_audio_mossformergan_se_16k(model, device, inputs, args)
42
- elif args.network == 'MossFormer2_SS_16K':
43
- return decode_one_audio_mossformer2_ss_16k(model, device, inputs, args)
44
- else:
45
- print("No network found!") # Print error message if no valid network is specified
46
- return
47
-
48
- def decode_one_audio_mossformer2_ss_16k(model, device, inputs, args):
49
- """Decodes audio using the MossFormer2 model for speech separation at 16kHz.
50
-
51
- This function handles the audio decoding process by processing the input tensor
52
- in segments, if necessary, and applies the model to obtain separated audio outputs.
53
-
54
- Args:
55
- model (nn.Module): The trained MossFormer2 model for decoding.
56
- device (torch.device): The device (CPU or GPU) to perform computations on.
57
- inputs (torch.Tensor): Input audio tensor of shape (B, T), where B is the batch size
58
- and T is the number of time steps.
59
- args (Namespace): Contains arguments for decoding configuration.
60
-
61
- Returns:
62
- list: A list of decoded audio outputs for each speaker.
63
- """
64
- out = [] # Initialize the list to store outputs
65
- decode_do_segment = False # Flag to determine if segmentation is needed
66
- window = int(args.sampling_rate * args.decode_window) # Decoding window length
67
- stride = int(window * 0.75) # Decoding stride if segmentation is used
68
- b, t = inputs.shape # Get batch size and input length
69
-
70
- rms_input = (inputs ** 2).mean() ** 0.5
71
-
72
- # Check if input length exceeds one-time decode length to decide on segmentation
73
- if t > args.sampling_rate * args.one_time_decode_length:
74
- decode_do_segment = True # Enable segment decoding for long sequences
75
-
76
- # Pad the inputs to ensure they meet the decoding window length requirements
77
- if t < window:
78
- inputs = np.concatenate([inputs, np.zeros((inputs.shape[0], window - t))], axis=1)
79
- elif t < window + stride:
80
- padding = window + stride - t
81
- inputs = np.concatenate([inputs, np.zeros((inputs.shape[0], padding))], axis=1)
82
- else:
83
- if (t - window) % stride != 0:
84
- padding = t - (t - window) // stride * stride
85
- inputs = np.concatenate([inputs, np.zeros((inputs.shape[0], padding))], axis=1)
86
-
87
- inputs = torch.from_numpy(np.float32(inputs)).to(device) # Convert inputs to torch tensor and move to device
88
- b, t = inputs.shape # Update batch size and input length after conversion
89
-
90
- # Process the inputs in segments if necessary
91
- if decode_do_segment:
92
- outputs = np.zeros((args.num_spks, t)) # Initialize output array for each speaker
93
- give_up_length = (window - stride) // 2 # Calculate length to give up at each segment
94
- current_idx = 0 # Initialize current index for segmentation
95
- while current_idx + window <= t:
96
- tmp_input = inputs[:, current_idx:current_idx + window] # Get segment input
97
- tmp_out_list = model(tmp_input) # Forward pass through the model
98
- for spk in range(args.num_spks):
99
- # Convert output for the current speaker to numpy
100
- tmp_out_list[spk] = tmp_out_list[spk][0, :].detach().cpu().numpy()
101
- if current_idx == 0:
102
- # For the first segment, use the whole segment minus the give-up length
103
- outputs[spk, current_idx:current_idx + window - give_up_length] = tmp_out_list[spk][:-give_up_length]
104
- else:
105
- # For subsequent segments, account for the give-up length at both ends
106
- outputs[spk, current_idx + give_up_length:current_idx + window - give_up_length] = tmp_out_list[spk][give_up_length:-give_up_length]
107
- current_idx += stride # Move to the next segment
108
- for spk in range(args.num_spks):
109
- out.append(outputs[spk, :]) # Append outputs for each speaker
110
- else:
111
- # If no segmentation is required, process the entire input
112
- out_list = model(inputs)
113
- for spk in range(args.num_spks):
114
- out.append(out_list[spk][0, :].detach().cpu().numpy()) # Append output for each speaker
115
-
116
- # Normalize the outputs to the maximum absolute value for each speaker
117
- '''
118
- max_abs = 0
119
- for spk in range(args.num_spks):
120
- if max_abs < max(abs(out[spk])):
121
- max_abs = max(abs(out[spk]))
122
- for spk in range(args.num_spks):
123
- out[spk] = out[spk] / max_abs # Normalize output by max absolute value
124
- '''
125
- # Normalize the outputs back to the input magnitude for each speaker
126
- for spk in range(args.num_spks):
127
- rms_out = (out[spk] ** 2).mean() ** 0.5
128
- out[spk] = out[spk] / rms_out * rms_input
129
- return out # Return the list of normalized outputs
130
-
131
- def decode_one_audio_frcrn_se_16k(model, device, inputs, args):
132
- """Decodes audio using the FRCRN model for speech enhancement at 16kHz.
133
-
134
- This function processes the input audio tensor either in segments or as a whole,
135
- depending on the length of the input. The model's inference method is applied
136
- to obtain the enhanced audio output.
137
-
138
- Args:
139
- model (nn.Module): The trained FRCRN model used for decoding.
140
- device (torch.device): The device (CPU or GPU) to perform computations on.
141
- inputs (torch.Tensor): Input audio tensor of shape (B, T), where B is the batch size
142
- and T is the number of time steps.
143
- args (Namespace): Contains arguments for decoding configuration.
144
-
145
- Returns:
146
- numpy.ndarray: The decoded audio output, which has been enhanced by the model.
147
- """
148
- decode_do_segment = False # Flag to determine if segmentation is needed
149
-
150
- window = int(args.sampling_rate * args.decode_window) # Decoding window length
151
- stride = int(window * 0.75) # Decoding stride for segmenting the input
152
- b, t = inputs.shape # Get batch size (b) and input length (t)
153
-
154
- # Check if input length exceeds one-time decode length to decide on segmentation
155
- if t > args.sampling_rate * args.one_time_decode_length:
156
- decode_do_segment = True # Enable segment decoding for long sequences
157
-
158
- # Pad the inputs to meet the decoding window length requirements
159
- if t < window:
160
- # Pad with zeros if the input length is less than the window size
161
- inputs = np.concatenate([inputs, np.zeros((inputs.shape[0], window - t))], axis=1)
162
- elif t < window + stride:
163
- # Pad the input if its length is less than the window plus stride
164
- padding = window + stride - t
165
- inputs = np.concatenate([inputs, np.zeros((inputs.shape[0], padding))], axis=1)
166
- else:
167
- # Ensure the input length is a multiple of the stride
168
- if (t - window) % stride != 0:
169
- padding = t - (t - window) // stride * stride
170
- inputs = np.concatenate([inputs, np.zeros((inputs.shape[0], padding))], axis=1)
171
-
172
- # Convert inputs to a PyTorch tensor and move to the specified device
173
- inputs = torch.from_numpy(np.float32(inputs)).to(device)
174
- b, t = inputs.shape # Update batch size and input length after conversion
175
-
176
- # Process the inputs in segments if necessary
177
- if decode_do_segment:
178
- outputs = np.zeros(t) # Initialize the output array
179
- give_up_length = (window - stride) // 2 # Calculate length to give up at each segment
180
- current_idx = 0 # Initialize current index for segmentation
181
-
182
- while current_idx + window <= t:
183
- tmp_input = inputs[:, current_idx:current_idx + window] # Get segment input
184
- tmp_output = model.inference(tmp_input).detach().cpu().numpy() # Inference on segment
185
-
186
- # For the first segment, use the whole segment minus the give-up length
187
- if current_idx == 0:
188
- outputs[current_idx:current_idx + window - give_up_length] = tmp_output[:-give_up_length]
189
- else:
190
- # For subsequent segments, account for the give-up length
191
- outputs[current_idx + give_up_length:current_idx + window - give_up_length] = tmp_output[give_up_length:-give_up_length]
192
-
193
- current_idx += stride # Move to the next segment
194
- else:
195
- # If no segmentation is required, process the entire input
196
- outputs = model.inference(inputs).detach().cpu().numpy() # Inference on full input
197
-
198
- #normalize outputs
199
- #max_abs = max(max(abs(outputs)), 1e-6)
200
- #outputs = outputs / max_abs
201
- return outputs # Return the decoded audio output
202
-
203
- def decode_one_audio_mossformergan_se_16k(model, device, inputs, args):
204
- """Decodes audio using the MossFormerGAN model for speech enhancement at 16kHz.
205
-
206
- This function processes the input audio tensor either in segments or as a whole,
207
- depending on the length of the input. The `_decode_one_audio_mossformergan_se_16k`
208
- function is called to perform the model inference and return the enhanced audio output.
209
-
210
- Args:
211
- model (nn.Module): The trained MossFormerGAN model used for decoding.
212
- device (torch.device): The device (CPU or GPU) for computation.
213
- inputs (torch.Tensor): Input audio tensor of shape (B, T), where B is the batch size
214
- and T is the number of time steps.
215
- args (Namespace): Contains arguments for decoding configuration.
216
-
217
- Returns:
218
- numpy.ndarray: The decoded audio output, which has been enhanced by the model.
219
- """
220
- decode_do_segment = False # Flag to determine if segmentation is needed
221
- window = int(args.sampling_rate * args.decode_window) # Decoding window length
222
- stride = int(window * 0.75) # Decoding stride for segmenting the input
223
- b, t = inputs.shape # Get batch size (b) and input length (t)
224
-
225
- # Check if input length exceeds one-time decode length to decide on segmentation
226
- if t > args.sampling_rate * args.one_time_decode_length:
227
- decode_do_segment = True # Enable segment decoding for long sequences
228
-
229
- # Pad the inputs to meet the decoding window length requirements
230
- if t < window:
231
- # Pad with zeros if the input length is less than the window size
232
- inputs = np.concatenate([inputs, np.zeros((inputs.shape[0], window - t))], axis=1)
233
- elif t < window + stride:
234
- # Pad the input if its length is less than the window plus stride
235
- padding = window + stride - t
236
- inputs = np.concatenate([inputs, np.zeros((inputs.shape[0], padding))], axis=1)
237
- else:
238
- # Ensure the input length is a multiple of the stride
239
- if (t - window) % stride != 0:
240
- padding = t - (t - window) // stride * stride
241
- inputs = np.concatenate([inputs, np.zeros((inputs.shape[0], padding))], axis=1)
242
-
243
- # Convert inputs to a PyTorch tensor and move to the specified device
244
- inputs = torch.from_numpy(np.float32(inputs)).to(device)
245
- b, t = inputs.shape # Update batch size and input length after conversion
246
-
247
- # Process the inputs in segments if necessary
248
- if decode_do_segment:
249
- outputs = np.zeros(t) # Initialize the output array
250
- give_up_length = (window - stride) // 2 # Calculate length to give up at each segment
251
- current_idx = 0 # Initialize current index for segmentation
252
-
253
- while current_idx + window <= t:
254
- tmp_input = inputs[:, current_idx:current_idx + window] # Get segment input
255
- tmp_output = _decode_one_audio_mossformergan_se_16k(model, device, tmp_input, args) # Inference on segment
256
-
257
- # For the first segment, use the whole segment minus the give-up length
258
- if current_idx == 0:
259
- outputs[current_idx:current_idx + window - give_up_length] = tmp_output[:-give_up_length]
260
- else:
261
- # For subsequent segments, account for the give-up length
262
- outputs[current_idx + give_up_length:current_idx + window - give_up_length] = tmp_output[give_up_length:-give_up_length]
263
-
264
- current_idx += stride # Move to the next segment
265
-
266
- return outputs # Return the accumulated outputs from segments
267
- else:
268
- # If no segmentation is required, process the entire input
269
- return _decode_one_audio_mossformergan_se_16k(model, device, inputs, args) # Inference on full input
270
-
271
- def _decode_one_audio_mossformergan_se_16k(model, device, inputs, args):
272
- """Processes audio inputs through the MossFormerGAN model for speech enhancement.
273
-
274
- This function performs the following steps:
275
- 1. Pads the input audio tensor to fit the model requirements.
276
- 2. Computes a normalization factor for the input tensor.
277
- 3. Applies Short-Time Fourier Transform (STFT) to convert the audio into the frequency domain.
278
- 4. Processes the STFT representation through the model to predict the real and imaginary components.
279
- 5. Uncompresses the predicted spectrogram and applies Inverse STFT (iSTFT) to convert back to time domain audio.
280
- 6. Normalizes the output audio.
281
-
282
- Args:
283
- model (nn.Module): The trained MossFormerGAN model used for decoding.
284
- device (torch.device): The device (CPU or GPU) for computation.
285
- inputs (torch.Tensor): Input audio tensor of shape (B, T), where B is the batch size and T is the number of time steps.
286
- args (Namespace): Contains arguments for STFT parameters and normalization.
287
-
288
- Returns:
289
- numpy.ndarray: The decoded audio output, which has been enhanced by the model.
290
- """
291
- input_len = inputs.size(-1) # Get the length of the input audio
292
- nframe = int(np.ceil(input_len / args.win_inc)) # Calculate the number of frames based on window increment
293
- padded_len = int(nframe * args.win_inc) # Calculate the padded length to fit the model
294
- padding_len = padded_len - input_len # Determine how much padding is needed
295
-
296
- # Pad the input audio with the beginning of the input
297
- inputs = torch.cat([inputs, inputs[:, :padding_len]], dim=-1)
298
-
299
- # Compute normalization factor based on the input
300
- c = torch.sqrt(inputs.size(-1) / torch.sum((inputs ** 2.0), dim=-1))
301
-
302
- # Prepare inputs for STFT by transposing and normalizing
303
- inputs = torch.transpose(inputs, 0, 1) # Change shape for STFT
304
- inputs = torch.transpose(inputs * c, 0, 1) # Apply normalization factor and transpose back
305
-
306
- # Perform Short-Time Fourier Transform (STFT) on the normalized inputs
307
- inputs_spec = stft(inputs, args, center=True)
308
- inputs_spec = inputs_spec.to(torch.float32) # Ensure the spectrogram is in float32 format
309
-
310
- # Compress the power of the spectrogram to improve model performance
311
- inputs_spec = power_compress(inputs_spec).permute(0, 1, 3, 2)
312
-
313
- # Pass the compressed spectrogram through the model to get predicted real and imaginary parts
314
- out_list = model(inputs_spec)
315
- pred_real, pred_imag = out_list[0].permute(0, 1, 3, 2), out_list[1].permute(0, 1, 3, 2)
316
-
317
- # Uncompress the predicted spectrogram to get the magnitude and phase
318
- pred_spec_uncompress = power_uncompress(pred_real, pred_imag).squeeze(1)
319
-
320
- # Perform Inverse STFT (iSTFT) to convert back to time domain audio
321
- outputs = istft(pred_spec_uncompress, args)
322
-
323
- # Normalize the output audio by dividing by the normalization factor
324
- outputs = outputs.squeeze(0) / c
325
-
326
- return outputs[:input_len].detach().cpu().numpy() # Return the output as a numpy array
327
-
328
- def decode_one_audio_mossformer2_se_48k(model, device, inputs, args):
329
- """Processes audio inputs through the MossFormer2 model for speech enhancement at 48kHz.
330
-
331
- This function decodes audio input using the following steps:
332
- 1. Normalizes the audio input to a maximum WAV value.
333
- 2. Checks the length of the input to decide between online decoding and batch processing.
334
- 3. For longer inputs, processes the audio in segments using a sliding window.
335
- 4. Computes filter banks and their deltas for the audio segment.
336
- 5. Passes the filter banks through the model to get a predicted mask.
337
- 6. Applies the mask to the spectrogram of the audio segment and reconstructs the audio.
338
- 7. For shorter inputs, processes them in one go without segmentation.
339
-
340
- Args:
341
- model (nn.Module): The trained MossFormer2 model used for decoding.
342
- device (torch.device): The device (CPU or GPU) for computation.
343
- inputs (torch.Tensor): Input audio tensor of shape (B, T), where B is the batch size and T is the number of time steps.
344
- args (Namespace): Contains arguments for sampling rate, window size, and other parameters.
345
-
346
- Returns:
347
- numpy.ndarray: The decoded audio output, normalized to the range [-1, 1].
348
- """
349
- inputs = inputs[0, :] # Extract the first element from the input tensor
350
- input_len = inputs.shape[0] # Get the length of the input audio
351
- inputs = inputs * MAX_WAV_VALUE # Normalize the input to the maximum WAV value
352
-
353
- # Check if input length exceeds the defined threshold for online decoding
354
- if input_len > args.sampling_rate * args.one_time_decode_length: # 20 seconds
355
- online_decoding = True
356
- if online_decoding:
357
- window = int(args.sampling_rate * args.decode_window) # Define window length (e.g., 4s for 48kHz)
358
- stride = int(window * 0.75) # Define stride length (e.g., 3s for 48kHz)
359
- t = inputs.shape[0] # Update length after potential padding
360
-
361
- # Pad input if necessary to match window size
362
- if t < window:
363
- inputs = np.concatenate([inputs, np.zeros(window - t)], 0)
364
- elif t < window + stride:
365
- padding = window + stride - t
366
- inputs = np.concatenate([inputs, np.zeros(padding)], 0)
367
- else:
368
- if (t - window) % stride != 0:
369
- padding = t - (t - window) // stride * stride
370
- inputs = np.concatenate([inputs, np.zeros(padding)], 0)
371
-
372
- audio = torch.from_numpy(inputs).type(torch.FloatTensor) # Convert to Torch tensor
373
- t = audio.shape[0] # Update length after conversion
374
- outputs = torch.from_numpy(np.zeros(t)) # Initialize output tensor
375
- give_up_length = (window - stride) // 2 # Determine length to ignore at the edges
376
- dfsmn_memory_length = 0 # Placeholder for potential memory length
377
- current_idx = 0 # Initialize current index for sliding window
378
-
379
- # Process audio in sliding window segments
380
- while current_idx + window <= t:
381
- # Select appropriate segment of audio for processing
382
- if current_idx < dfsmn_memory_length:
383
- audio_segment = audio[0:current_idx + window]
384
- else:
385
- audio_segment = audio[current_idx - dfsmn_memory_length:current_idx + window]
386
-
387
- # Compute filter banks for the audio segment
388
- fbanks = compute_fbank(audio_segment.unsqueeze(0), args)
389
-
390
- # Compute deltas for filter banks
391
- fbank_tr = torch.transpose(fbanks, 0, 1) # Transpose for delta computation
392
- fbank_delta = torchaudio.functional.compute_deltas(fbank_tr) # First-order delta
393
- fbank_delta_delta = torchaudio.functional.compute_deltas(fbank_delta) # Second-order delta
394
-
395
- # Transpose back to original shape
396
- fbank_delta = torch.transpose(fbank_delta, 0, 1)
397
- fbank_delta_delta = torch.transpose(fbank_delta_delta, 0, 1)
398
-
399
- # Concatenate the original filter banks with their deltas
400
- fbanks = torch.cat([fbanks, fbank_delta, fbank_delta_delta], dim=1)
401
- fbanks = fbanks.unsqueeze(0).to(device) # Add batch dimension and move to device
402
-
403
- # Pass filter banks through the model
404
- Out_List = model(fbanks)
405
- pred_mask = Out_List[-1] # Get the predicted mask from the output
406
-
407
- # Apply STFT to the audio segment
408
- spectrum = stft(audio_segment, args)
409
- pred_mask = pred_mask.permute(2, 1, 0) # Permute dimensions for masking
410
- masked_spec = spectrum.cpu() * pred_mask.detach().cpu() # Apply mask to the spectrum
411
- masked_spec_complex = masked_spec[:, :, 0] + 1j * masked_spec[:, :, 1] # Convert to complex form
412
-
413
- # Reconstruct audio from the masked spectrogram
414
- output_segment = istft(masked_spec_complex, args, len(audio_segment))
415
-
416
- # Store the output segment in the output tensor
417
- if current_idx == 0:
418
- outputs[current_idx:current_idx + window - give_up_length] = output_segment[:-give_up_length]
419
- else:
420
- output_segment = output_segment[-window:] # Get the latest window of output
421
- outputs[current_idx + give_up_length:current_idx + window - give_up_length] = output_segment[give_up_length:-give_up_length]
422
-
423
- current_idx += stride # Move to the next segment
424
-
425
- else:
426
- # Process the entire audio at once if it is shorter than the threshold
427
- audio = torch.from_numpy(inputs).type(torch.FloatTensor)
428
- fbanks = compute_fbank(audio.unsqueeze(0), args)
429
-
430
- # Compute deltas for filter banks
431
- fbank_tr = torch.transpose(fbanks, 0, 1)
432
- fbank_delta = torchaudio.functional.compute_deltas(fbank_tr)
433
- fbank_delta_delta = torchaudio.functional.compute_deltas(fbank_delta)
434
- fbank_delta = torch.transpose(fbank_delta, 0, 1)
435
- fbank_delta_delta = torch.transpose(fbank_delta_delta, 0, 1)
436
-
437
- # Concatenate the original filter banks with their deltas
438
- fbanks = torch.cat([fbanks, fbank_delta, fbank_delta_delta], dim=1)
439
- fbanks = fbanks.unsqueeze(0).to(device) # Add batch dimension and move to device
440
-
441
- # Pass filter banks through the model
442
- Out_List = model(fbanks)
443
- pred_mask = Out_List[-1] # Get the predicted mask
444
- spectrum = stft(audio, args) # Apply STFT to the audio
445
- pred_mask = pred_mask.permute(2, 1, 0) # Permute dimensions for masking
446
- masked_spec = spectrum * pred_mask.detach().cpu() # Apply mask to the spectrum
447
- masked_spec_complex = masked_spec[:, :, 0] + 1j * masked_spec[:, :, 1] # Convert to complex form
448
-
449
- # Reconstruct audio from the masked spectrogram
450
- outputs = istft(masked_spec_complex, args, len(audio))
451
-
452
- outpus = outputs.numpy() / MAX_WAV_VALUE # Return the output normalized to [-1, 1]
453
- #normalize outputs
454
- max_abs = max(max(abs(outputs)), 1e-6)
455
- outputs = outputs / max_abs
456
-
457
- return outputs
458
-
459
- def decode_one_audio_AV_MossFormer2_TSE_16K(model, inputs, args):
460
- """Processes video inputs through the AV mossformer2 model with Target speaker extraction (TSE) for decoding at 16kHz.
461
-
462
- This function decodes audio input using the following steps:
463
- 1. Checks if the input audio length requires segmentation or can be processed in one go.
464
- 2. If the input audio is long enough, processes it in overlapping segments using a sliding window approach.
465
- 3. Applies the model to each segment or the entire input, and collects the output.
466
-
467
- Args:
468
- model (nn.Module): The trained SpEx model for speech enhancement.
469
- inputs (numpy.ndarray): Input audio and visual data
470
- args (Namespace): Contains arguments for sampling rate, window size, and other parameters.
471
-
472
- Returns:
473
- numpy.ndarray: The decoded audio output as a NumPy array.
474
- """
475
-
476
- audio, visual = inputs
477
- max_val = np.max(np.abs(audio))
478
- if max_val > 1:
479
- audio /= max_val
480
-
481
- b, t = audio.shape # Get batch size (b) and input length (t)
482
-
483
- decode_do_segement = False # Flag to determine if segmentation is needed
484
- # Check if the input length exceeds the defined threshold for segmentation
485
- if t > args.sampling_rate * args.one_time_decode_length:
486
- decode_do_segement = True # Enable segmentation for long inputs
487
-
488
- # Convert inputs to a PyTorch tensor and move to the specified device
489
- audio = torch.from_numpy(np.float32(audio)).to(args.device)
490
- visual = torch.from_numpy(np.float32(visual)).to(args.device)
491
-
492
- print(audio.shape)
493
- print(visual.shape)
494
-
495
- if decode_do_segement:
496
- print('********')
497
- outputs = np.zeros(t) # Initialize output array
498
- window = args.sampling_rate * args.decode_window # Window length for processing
499
- window_v = 25 * args.decode_window
500
- stride = int(window * 0.6) # Decoding stride for segmenting the input
501
- give_up_length = (window - stride) // 2 # Calculate length to give up at each segment
502
- current_idx = 0 # Initialize current index for sliding window
503
-
504
- # Process the audio in overlapping segments
505
- while current_idx + window < t:
506
- tmp_audio = audio[:, current_idx:current_idx + window] # Select current audio segment
507
-
508
- current_idx_v = int(current_idx/args.sampling_rate*25) # Select current video segment index
509
- tmp_video = visual[:, current_idx_v:current_idx_v + window_v, :, :] # Select current video segment
510
-
511
- tmp_output = model(tmp_audio, tmp_video).detach().squeeze().cpu().numpy() # Apply model to the segment
512
-
513
- # For the first segment, use the whole segment minus the give-up length
514
- if current_idx == 0:
515
- outputs[current_idx:current_idx + window - give_up_length] = tmp_output[:-give_up_length]
516
- else:
517
- # For subsequent segments, account for the give-up length
518
- outputs[current_idx + give_up_length:current_idx + window - give_up_length] = tmp_output[give_up_length:-give_up_length]
519
-
520
- current_idx += stride # Move to the next segment
521
-
522
- # Process the last window of audio
523
- tmp_audio = audio[:, -window:]
524
- tmp_video = visual[:, -window_v:, :, :]
525
- tmp_output = model(tmp_audio, tmp_video).detach().squeeze().cpu().numpy() # Apply model to the segment
526
- outputs[-window + give_up_length:] = tmp_output[give_up_length:]
527
- else:
528
- # Process the entire input at once if segmentation is not needed
529
- outputs = model(audio, visual).detach().squeeze().cpu().numpy()
530
-
531
-
532
- return outputs # Return the decoded audio output as a NumPy array
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
utils/misc.py DELETED
@@ -1,378 +0,0 @@
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 = torch.load(checkpoint_path, map_location=lambda storage, loc: storage)
115
- #checkpoint = load_checkpoint(checkpoint_path, use_cuda) # Load the checkpoint
116
- '''
117
- if 'model' in checkpoint:
118
- model.load_state_dict(checkpoint['model'], strict=False) # Load model parameters
119
- else:
120
- model.load_state_dict(checkpoint, strict=False)
121
- '''
122
- if 'model' in checkpoint:
123
- pretrained_model = checkpoint['model']
124
- else:
125
- pretrained_model = checkpoint
126
- state = model.state_dict()
127
- for key in state.keys():
128
- if key in pretrained_model and state[key].shape == pretrained_model[key].shape:
129
- state[key] = pretrained_model[key]
130
- elif key.replace('module.', '') in pretrained_model and state[key].shape == pretrained_model[key.replace('module.', '')].shape:
131
- state[key] = pretrained_model[key.replace('module.', '')]
132
- elif 'module.'+key in pretrained_model and state[key].shape == pretrained_model['module.'+key].shape:
133
- state[key] = pretrained_model['module.'+key]
134
- model.load_state_dict(state)
135
- print('=> Reloaded well-trained model {} for decoding.'.format(model_name))
136
-
137
- def reload_model(model, optimizer, checkpoint_dir, use_cuda=True, strict=True):
138
- """Reloads the model and optimizer state from a checkpoint.
139
-
140
- Args:
141
- model (nn.Module): The model to be reloaded.
142
- optimizer (torch.optim.Optimizer): The optimizer to be reloaded.
143
- checkpoint_dir (str): Directory containing checkpoints.
144
- use_cuda (bool): Flag indicating whether to use CUDA.
145
- strict (bool): If True, requires keys in state_dict to match exactly.
146
-
147
- Returns:
148
- tuple: Current epoch and step.
149
- """
150
- ckpt_name = os.path.join(checkpoint_dir, 'checkpoint') # Path to the checkpoint file
151
- if os.path.isfile(ckpt_name):
152
- with open(ckpt_name, 'r') as f:
153
- model_name = f.readline().strip() # Read model name from checkpoint file
154
- checkpoint_path = os.path.join(checkpoint_dir, model_name) # Construct full checkpoint path
155
- checkpoint = load_checkpoint(checkpoint_path, use_cuda) # Load the checkpoint
156
- model.load_state_dict(checkpoint['model'], strict=strict) # Load model parameters
157
- optimizer.load_state_dict(checkpoint['optimizer']) # Load optimizer parameters
158
- epoch = checkpoint['epoch'] # Get current epoch
159
- step = checkpoint['step'] # Get current step
160
- print('=> Reloaded previous model and optimizer.')
161
- else:
162
- print('[!] Checkpoint directory is empty. Train a new model ...')
163
- epoch = 0 # Initialize epoch
164
- step = 0 # Initialize step
165
- return epoch, step
166
-
167
- def save_checkpoint(model, optimizer, epoch, step, checkpoint_dir, mode='checkpoint'):
168
- """Saves the model and optimizer state to a checkpoint file.
169
-
170
- Args:
171
- model (nn.Module): The model to be saved.
172
- optimizer (torch.optim.Optimizer): The optimizer to be saved.
173
- epoch (int): Current epoch number.
174
- step (int): Current training step number.
175
- checkpoint_dir (str): Directory to save the checkpoint.
176
- mode (str): Mode of the checkpoint ('checkpoint' or other).
177
-
178
- Returns:
179
- None
180
- """
181
- checkpoint_path = os.path.join(
182
- checkpoint_dir, 'model.ckpt-{}-{}.pt'.format(epoch, step)) # Construct checkpoint file path
183
- torch.save({'model': model.state_dict(), # Save model parameters
184
- 'optimizer': optimizer.state_dict(), # Save optimizer parameters
185
- 'epoch': epoch, # Save epoch
186
- 'step': step}, checkpoint_path) # Save checkpoint to file
187
-
188
- # Save the checkpoint name to a file for easy access
189
- with open(os.path.join(checkpoint_dir, mode), 'w') as f:
190
- f.write('model.ckpt-{}-{}.pt'.format(epoch, step))
191
- print("=> Saved checkpoint:", checkpoint_path)
192
-
193
- def setup_lr(opt, lr):
194
- """Sets the learning rate for all parameter groups in the optimizer.
195
-
196
- Args:
197
- opt (torch.optim.Optimizer): The optimizer instance whose learning rate needs to be set.
198
- lr (float): The new learning rate to be assigned.
199
-
200
- Returns:
201
- None
202
- """
203
- for param_group in opt.param_groups:
204
- param_group['lr'] = lr # Update the learning rate for each parameter group
205
-
206
-
207
- def pesq_loss(clean, noisy, sr=16000):
208
- """Calculates the PESQ (Perceptual Evaluation of Speech Quality) score between clean and noisy signals.
209
-
210
- Args:
211
- clean (ndarray): The clean audio signal.
212
- noisy (ndarray): The noisy audio signal.
213
- sr (int): Sample rate of the audio signals (default is 16000 Hz).
214
-
215
- Returns:
216
- float: The PESQ score or -1 in case of an error.
217
- """
218
- try:
219
- pesq_score = pesq(sr, clean, noisy, 'wb') # Compute PESQ score
220
- except:
221
- # PESQ may fail due to silent periods in audio
222
- pesq_score = -1 # Assign -1 to indicate error
223
- return pesq_score
224
-
225
-
226
- def batch_pesq(clean, noisy):
227
- """Computes the PESQ scores for batches of clean and noisy audio signals.
228
-
229
- Args:
230
- clean (list of ndarray): List of clean audio signals.
231
- noisy (list of ndarray): List of noisy audio signals.
232
-
233
- Returns:
234
- torch.FloatTensor: A tensor of normalized PESQ scores or None if any score is -1.
235
- """
236
- # Parallel processing for calculating PESQ scores for each pair of clean and noisy signals
237
- pesq_score = Parallel(n_jobs=-1)(delayed(pesq_loss)(c, n) for c, n in zip(clean, noisy))
238
- pesq_score = np.array(pesq_score) # Convert to NumPy array
239
-
240
- if -1 in pesq_score: # Check for errors in PESQ calculations
241
- return None
242
-
243
- # Normalize PESQ scores to a scale of 0 to 1
244
- pesq_score = (pesq_score - 1) / 3.5
245
- return torch.FloatTensor(pesq_score).to('cuda') # Return normalized scores as a tensor
246
-
247
-
248
- def power_compress(x):
249
- """Compresses the power of a complex spectrogram.
250
-
251
- Args:
252
- x (torch.Tensor): Input tensor with real and imaginary components.
253
-
254
- Returns:
255
- torch.Tensor: Compressed magnitude and phase representation of the input.
256
- """
257
- real = x[..., 0] # Extract real part
258
- imag = x[..., 1] # Extract imaginary part
259
- spec = torch.complex(real, imag) # Create complex tensor from real and imaginary parts
260
- mag = torch.abs(spec) # Compute magnitude
261
- phase = torch.angle(spec) # Compute phase
262
-
263
- mag = mag**0.3 # Compress magnitude using power of 0.3
264
- real_compress = mag * torch.cos(phase) # Reconstruct real part
265
- imag_compress = mag * torch.sin(phase) # Reconstruct imaginary part
266
- return torch.stack([real_compress, imag_compress], 1) # Stack compressed parts
267
-
268
-
269
- def power_uncompress(real, imag):
270
- """Uncompresses the power of a compressed complex spectrogram.
271
-
272
- Args:
273
- real (torch.Tensor): Compressed real component.
274
- imag (torch.Tensor): Compressed imaginary component.
275
-
276
- Returns:
277
- torch.Tensor: Uncompressed complex spectrogram.
278
- """
279
- spec = torch.complex(real, imag) # Create complex tensor from real and imaginary parts
280
- mag = torch.abs(spec) # Compute magnitude
281
- phase = torch.angle(spec) # Compute phase
282
-
283
- mag = mag**(1./0.3) # Uncompress magnitude by raising to the power of 1/0.3
284
- real_uncompress = mag * torch.cos(phase) # Reconstruct real part
285
- imag_uncompress = mag * torch.sin(phase) # Reconstruct imaginary part
286
- return torch.stack([real_uncompress, imag_uncompress], -1) # Stack uncompressed parts
287
-
288
-
289
- def stft(x, args, center=False):
290
- """Computes the Short-Time Fourier Transform (STFT) of an audio signal.
291
-
292
- Args:
293
- x (torch.Tensor): Input audio signal.
294
- args (Namespace): Configuration arguments containing window type and lengths.
295
- center (bool): Whether to center the window.
296
-
297
- Returns:
298
- torch.Tensor: The computed STFT of the input signal.
299
- """
300
- win_type = args.win_type
301
- win_len = args.win_len
302
- win_inc = args.win_inc
303
- fft_len = args.fft_len
304
-
305
- # Select window type and create window tensor
306
- if win_type == 'hamming':
307
- window = torch.hamming_window(win_len, periodic=False).to(x.device)
308
- elif win_type == 'hanning':
309
- window = torch.hann_window(win_len, periodic=False).to(x.device)
310
- else:
311
- print(f"In STFT, {win_type} is not supported!")
312
- return
313
-
314
- # Compute and return the STFT
315
- return torch.stft(x, fft_len, win_inc, win_len, center=center, window=window, return_complex=False)
316
-
317
-
318
- def istft(x, args, slen=None, center=False, normalized=False, onsided=None, return_complex=False):
319
- """Computes the inverse Short-Time Fourier Transform (ISTFT) of a complex spectrogram.
320
-
321
- Args:
322
- x (torch.Tensor): Input complex spectrogram.
323
- args (Namespace): Configuration arguments containing window type and lengths.
324
- slen (int, optional): Length of the output signal.
325
- center (bool): Whether to center the window.
326
- normalized (bool): Whether to normalize the output.
327
- onsided (bool, optional): If True, computes only the one-sided transform.
328
- return_complex (bool): If True, returns complex output.
329
-
330
- Returns:
331
- torch.Tensor: The reconstructed audio signal from the spectrogram.
332
- """
333
- win_type = args.win_type
334
- win_len = args.win_len
335
- win_inc = args.win_inc
336
- fft_len = args.fft_len
337
-
338
- # Select window type and create window tensor
339
- if win_type == 'hamming':
340
- window = torch.hamming_window(win_len, periodic=False).to(x.device)
341
- elif win_type == 'hanning':
342
- window = torch.hann_window(win_len, periodic=False).to(x.device)
343
- else:
344
- print(f"In ISTFT, {win_type} is not supported!")
345
- return
346
-
347
- try:
348
- # Attempt to compute ISTFT
349
- output = torch.istft(x, n_fft=fft_len, hop_length=win_inc, win_length=win_len,
350
- window=window, center=center, normalized=normalized,
351
- onesided=onsided, length=slen, return_complex=False)
352
- except:
353
- # Handle potential errors by converting x to a complex tensor
354
- x_complex = torch.view_as_complex(x)
355
- output = torch.istft(x_complex, n_fft=fft_len, hop_length=win_inc, win_length=win_len,
356
- window=window, center=center, normalized=normalized,
357
- onesided=onsided, length=slen, return_complex=False)
358
- return output
359
-
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
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
utils/video_process.py DELETED
@@ -1,363 +0,0 @@
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('/')[-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
-
166
- def inference_video(video_args):
167
- # GPU: Face detection, output is the list contains the face location and score in this frame
168
- DET = S3FD(device=video_args.device)
169
- flist = glob.glob(os.path.join(video_args.pyframesPath, '*.jpg'))
170
- flist.sort()
171
- dets = []
172
- for fidx, fname in enumerate(flist):
173
- image = cv2.imread(fname)
174
- imageNumpy = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
175
- bboxes = DET.detect_faces(imageNumpy, conf_th=0.9, scales=[video_args.facedetScale])
176
- dets.append([])
177
- for bbox in bboxes:
178
- dets[-1].append({'frame':fidx, 'bbox':(bbox[:-1]).tolist(), 'conf':bbox[-1]}) # dets has the frames info, bbox info, conf info
179
- sys.stderr.write('%s-%05d; %d dets\r' % (video_args.videoFilePath, fidx, len(dets[-1])))
180
- savePath = os.path.join(video_args.pyworkPath,'faces.pckl')
181
- with open(savePath, 'wb') as fil:
182
- pickle.dump(dets, fil)
183
- return dets
184
-
185
-
186
- def bb_intersection_over_union(boxA, boxB, evalCol = False):
187
- # CPU: IOU Function to calculate overlap between two image
188
- xA = max(boxA[0], boxB[0])
189
- yA = max(boxA[1], boxB[1])
190
- xB = min(boxA[2], boxB[2])
191
- yB = min(boxA[3], boxB[3])
192
- interArea = max(0, xB - xA) * max(0, yB - yA)
193
- boxAArea = (boxA[2] - boxA[0]) * (boxA[3] - boxA[1])
194
- boxBArea = (boxB[2] - boxB[0]) * (boxB[3] - boxB[1])
195
- if evalCol == True:
196
- iou = interArea / float(boxAArea)
197
- else:
198
- iou = interArea / float(boxAArea + boxBArea - interArea)
199
- return iou
200
-
201
- def track_shot(video_args, sceneFaces):
202
- # CPU: Face tracking
203
- iouThres = 0.5 # Minimum IOU between consecutive face detections
204
- tracks = []
205
- while True:
206
- track = []
207
- for frameFaces in sceneFaces:
208
- for face in frameFaces:
209
- if track == []:
210
- track.append(face)
211
- frameFaces.remove(face)
212
- elif face['frame'] - track[-1]['frame'] <= video_args.numFailedDet:
213
- iou = bb_intersection_over_union(face['bbox'], track[-1]['bbox'])
214
- if iou > iouThres:
215
- track.append(face)
216
- frameFaces.remove(face)
217
- continue
218
- else:
219
- break
220
- if track == []:
221
- break
222
- elif len(track) > video_args.minTrack:
223
- frameNum = np.array([ f['frame'] for f in track ])
224
- bboxes = np.array([np.array(f['bbox']) for f in track])
225
- frameI = np.arange(frameNum[0],frameNum[-1]+1)
226
- bboxesI = []
227
- for ij in range(0,4):
228
- interpfn = interp1d(frameNum, bboxes[:,ij])
229
- bboxesI.append(interpfn(frameI))
230
- bboxesI = np.stack(bboxesI, axis=1)
231
- if max(np.mean(bboxesI[:,2]-bboxesI[:,0]), np.mean(bboxesI[:,3]-bboxesI[:,1])) > video_args.minFaceSize:
232
- tracks.append({'frame':frameI,'bbox':bboxesI})
233
- return tracks
234
-
235
- def crop_video(video_args, track, cropFile):
236
- # CPU: crop the face clips
237
- flist = glob.glob(os.path.join(video_args.pyframesPath, '*.jpg')) # Read the frames
238
- flist.sort()
239
- vOut = cv2.VideoWriter(cropFile + 't.avi', cv2.VideoWriter_fourcc(*'XVID'), 25, (224,224))# Write video
240
- dets = {'x':[], 'y':[], 's':[]}
241
- for det in track['bbox']: # Read the tracks
242
- dets['s'].append(max((det[3]-det[1]), (det[2]-det[0]))/2)
243
- dets['y'].append((det[1]+det[3])/2) # crop center x
244
- dets['x'].append((det[0]+det[2])/2) # crop center y
245
- dets['s'] = signal.medfilt(dets['s'], kernel_size=13) # Smooth detections
246
- dets['x'] = signal.medfilt(dets['x'], kernel_size=13)
247
- dets['y'] = signal.medfilt(dets['y'], kernel_size=13)
248
- for fidx, frame in enumerate(track['frame']):
249
- cs = video_args.cropScale
250
- bs = dets['s'][fidx] # Detection box size
251
- bsi = int(bs * (1 + 2 * cs)) # Pad videos by this amount
252
- image = cv2.imread(flist[frame])
253
- frame = np.pad(image, ((bsi,bsi), (bsi,bsi), (0, 0)), 'constant', constant_values=(110, 110))
254
- my = dets['y'][fidx] + bsi # BBox center Y
255
- mx = dets['x'][fidx] + bsi # BBox center X
256
- face = frame[int(my-bs):int(my+bs*(1+2*cs)),int(mx-bs*(1+cs)):int(mx+bs*(1+cs))]
257
- vOut.write(cv2.resize(face, (224, 224)))
258
- audioTmp = cropFile + '.wav'
259
- audioStart = (track['frame'][0]) / 25
260
- audioEnd = (track['frame'][-1]+1) / 25
261
- vOut.release()
262
- command = ("ffmpeg -y -i %s -async 1 -ac 1 -vn -acodec pcm_s16le -ar 16000 -threads %d -ss %.3f -to %.3f %s -loglevel panic" % \
263
- (video_args.audioFilePath, video_args.nDataLoaderThread, audioStart, audioEnd, audioTmp))
264
- output = subprocess.call(command, shell=True, stdout=None) # Crop audio file
265
- _, audio = wavfile.read(audioTmp)
266
- command = ("ffmpeg -y -i %st.avi -i %s -threads %d -c:v copy -c:a copy %s.avi -loglevel panic" % \
267
- (cropFile, audioTmp, video_args.nDataLoaderThread, cropFile)) # Combine audio and video file
268
- output = subprocess.call(command, shell=True, stdout=None)
269
- os.remove(cropFile + 't.avi')
270
- return {'track':track, 'proc_track':dets}
271
-
272
-
273
-
274
- def evaluate_network(files, video_args, args):
275
-
276
- est_sources = []
277
- for file in tqdm.tqdm(files, total = len(files)):
278
-
279
- fileName = os.path.splitext(file.split('/')[-1])[0] # Load audio and video
280
- audio, _ = sf.read(os.path.join(video_args.pycropPath, fileName + '.wav'), dtype='float32')
281
-
282
- video = cv2.VideoCapture(os.path.join(video_args.pycropPath, fileName + '.avi'))
283
- videoFeature = []
284
- while video.isOpened():
285
- ret, frames = video.read()
286
- if ret == True:
287
- face = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY)
288
- face = cv2.resize(face, (224,224))
289
- face = face[int(112-(112/2)):int(112+(112/2)), int(112-(112/2)):int(112+(112/2))]
290
- videoFeature.append(face)
291
- else:
292
- break
293
-
294
- video.release()
295
- visual = np.array(videoFeature)/255.0
296
- visual = (visual - 0.4161)/0.1688
297
-
298
- length = int(audio.shape[0]/16000*25)
299
- if visual.shape[0] < length:
300
- visual = np.pad(visual, ((0,int(length - visual.shape[0])),(0,0),(0,0)), mode = 'edge')
301
-
302
- audio = np.expand_dims(audio, axis=0)
303
- visual = np.expand_dims(visual, axis=0)
304
-
305
- inputs = (audio, visual)
306
- est_source = decode_one_audio_AV_MossFormer2_TSE_16K(video_args.model, inputs, args)
307
-
308
- est_sources.append(est_source)
309
-
310
- return est_sources
311
-
312
- def visualization(tracks, est_sources, video_args):
313
- # CPU: visulize the result for video format
314
- flist = glob.glob(os.path.join(video_args.pyframesPath, '*.jpg'))
315
- flist.sort()
316
-
317
-
318
- for idx, audio in enumerate(est_sources):
319
- max_value = np.max(np.abs(audio))
320
- if max_value >1:
321
- audio /= max_value
322
- sf.write(video_args.pycropPath +'/est_%s.wav' %idx, audio, 16000)
323
-
324
- for tidx, track in enumerate(tracks):
325
- faces = [[] for i in range(len(flist))]
326
- for fidx, frame in enumerate(track['track']['frame'].tolist()):
327
- faces[frame].append({'track':tidx, 's':track['proc_track']['s'][fidx], 'x':track['proc_track']['x'][fidx], 'y':track['proc_track']['y'][fidx]})
328
-
329
- firstImage = cv2.imread(flist[0])
330
- fw = firstImage.shape[1]
331
- fh = firstImage.shape[0]
332
- vOut = cv2.VideoWriter(os.path.join(video_args.pyaviPath, 'video_only.avi'), cv2.VideoWriter_fourcc(*'XVID'), 25, (fw,fh))
333
- for fidx, fname in tqdm.tqdm(enumerate(flist), total = len(flist)):
334
- image = cv2.imread(fname)
335
- for face in faces[fidx]:
336
- 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)
337
- vOut.write(image)
338
- vOut.release()
339
-
340
- command = ("ffmpeg -y -i %s -i %s -threads %d -c:v copy -c:a copy %s -loglevel panic" % \
341
- (os.path.join(video_args.pyaviPath, 'video_only.avi'), (video_args.pycropPath +'/est_%s.wav' %tidx), \
342
- video_args.nDataLoaderThread, os.path.join(video_args.pyaviPath,'video_out_%s.avi'%tidx)))
343
- output = subprocess.call(command, shell=True, stdout=None)
344
-
345
-
346
-
347
-
348
- command = "ffmpeg -i %s %s ;" % (
349
- os.path.join(video_args.pyaviPath, 'video_out_%s.avi' % tidx),
350
- os.path.join(video_args.pyaviPath, 'video_est_%s.mp4' % tidx)
351
- )
352
- command += f"rm {os.path.join(video_args.pyaviPath, 'video_out_%s.avi' % tidx)}"
353
- output = subprocess.call(command, shell=True, stdout=None)
354
-
355
-
356
- command = "ffmpeg -i %s %s ;" % (
357
- os.path.join(video_args.pyaviPath, 'video.avi'),
358
- os.path.join(video_args.pyaviPath, 'video_orig.mp4')
359
- )
360
- command += f"rm {os.path.join(video_args.pyaviPath, 'video_only.avi')} ;"
361
- command += f"rm {os.path.join(video_args.pyaviPath, 'video.avi')} ;"
362
- command += f"rm {os.path.join(video_args.pyaviPath, 'audio.wav')} ;"
363
- output = subprocess.call(command, shell=True, stdout=None)