alibabasglab commited on
Commit
dc79b90
·
verified ·
1 Parent(s): d151b09

Upload network_wrapper.py

Browse files
Files changed (1) hide show
  1. network_wrapper.py +228 -0
network_wrapper.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import yamlargparse
4
+ import torch.nn as nn
5
+
6
+ class network_wrapper(nn.Module):
7
+ """
8
+ A wrapper class for loading different neural network models for tasks such as
9
+ speech enhancement (SE), speech separation (SS), and target speaker extraction (TSE).
10
+ It manages argument parsing, model configuration loading, and model instantiation
11
+ based on the task and model name.
12
+ """
13
+
14
+ def __init__(self):
15
+ """
16
+ Initializes the network wrapper without any predefined model or arguments.
17
+ """
18
+ super(network_wrapper, self).__init__()
19
+ self.args = None # Placeholder for command-line arguments
20
+ self.config_path = None # Path to the YAML configuration file
21
+ self.model_name = None # Model name to be loaded based on the task
22
+
23
+ def load_args_se(self):
24
+ """
25
+ Loads the arguments for the speech enhancement task using a YAML config file.
26
+ Sets the configuration path and parses all the required parameters such as
27
+ input/output paths, model settings, and FFT parameters.
28
+ """
29
+ self.config_path = 'config/inference/' + self.model_name + '.yaml'
30
+ parser = yamlargparse.ArgumentParser("Settings")
31
+
32
+ # General model and inference settings
33
+ parser.add_argument('--config', help='Config file path', action=yamlargparse.ActionConfigFile)
34
+ parser.add_argument('--mode', type=str, default='inference', help='Modes: train or inference')
35
+ parser.add_argument('--checkpoint-dir', dest='checkpoint_dir', type=str, default='checkpoints/FRCRN_SE_16K', help='Checkpoint directory')
36
+ parser.add_argument('--input-path', dest='input_path', type=str, help='Path for noisy audio input')
37
+ parser.add_argument('--output-dir', dest='output_dir', type=str, help='Directory for enhanced audio output')
38
+ parser.add_argument('--use-cuda', dest='use_cuda', default=1, type=int, help='Enable CUDA (1=True, 0=False)')
39
+ parser.add_argument('--num-gpu', dest='num_gpu', type=int, default=1, help='Number of GPUs to use')
40
+
41
+ # Model-specific settings
42
+ parser.add_argument('--network', type=str, help='Select SE models: FRCRN_SE_16K, MossFormer2_SE_48K')
43
+ parser.add_argument('--sampling-rate', dest='sampling_rate', type=int, default=16000, help='Sampling rate')
44
+ parser.add_argument('--one-time-decode-length', dest='one_time_decode_length', type=float, default=60.0, help='Max segment length for one-pass decoding')
45
+ parser.add_argument('--decode-window', dest='decode_window', type=float, default=1.0, help='Decoding chunk size')
46
+
47
+ # FFT parameters for feature extraction
48
+ parser.add_argument('--window-len', dest='win_len', type=int, default=400, help='Window length for framing')
49
+ parser.add_argument('--window-inc', dest='win_inc', type=int, default=100, help='Window shift for framing')
50
+ parser.add_argument('--fft-len', dest='fft_len', type=int, default=512, help='FFT length for feature extraction')
51
+ parser.add_argument('--num-mels', dest='num_mels', type=int, default=60, help='Number of mel-spectrogram bins')
52
+ parser.add_argument('--window-type', dest='win_type', type=str, default='hamming', help='Window type: hamming or hanning')
53
+
54
+ # Parse arguments from the config file
55
+ self.args = parser.parse_args(['--config', self.config_path])
56
+
57
+ def load_args_ss(self):
58
+ """
59
+ Loads the arguments for the speech separation task using a YAML config file.
60
+ This method sets parameters such as input/output paths, model configurations,
61
+ and encoder/decoder settings for the MossFormer2-based speech separation model.
62
+ """
63
+ self.config_path = 'config/inference/' + self.model_name + '.yaml'
64
+ parser = yamlargparse.ArgumentParser("Settings")
65
+
66
+ # General model and inference settings
67
+ parser.add_argument('--config', default=self.config_path, help='Config file path', action=yamlargparse.ActionConfigFile)
68
+ parser.add_argument('--mode', type=str, default='inference', help='Modes: train or inference')
69
+ parser.add_argument('--checkpoint-dir', dest='checkpoint_dir', type=str, default='checkpoints/FRCRN_SE_16K', help='Checkpoint directory')
70
+ parser.add_argument('--input-path', dest='input_path', type=str, help='Path for mixed audio input')
71
+ parser.add_argument('--output-dir', dest='output_dir', type=str, help='Directory for separated audio output')
72
+ parser.add_argument('--use-cuda', dest='use_cuda', default=1, type=int, help='Enable CUDA (1=True, 0=False)')
73
+ parser.add_argument('--num-gpu', dest='num_gpu', type=int, default=1, help='Number of GPUs to use')
74
+
75
+ # Model-specific settings for speech separation
76
+ parser.add_argument('--network', type=str, help='Select SS models: MossFormer2_SS_16K')
77
+ parser.add_argument('--sampling-rate', dest='sampling_rate', type=int, default=16000, help='Sampling rate')
78
+ parser.add_argument('--num-spks', dest='num_spks', type=int, default=2, help='Number of speakers to separate')
79
+ parser.add_argument('--one-time-decode-length', dest='one_time_decode_length', type=float, default=60.0, help='Max segment length for one-pass decoding')
80
+ parser.add_argument('--decode-window', dest='decode_window', type=float, default=1.0, help='Decoding chunk size')
81
+
82
+ # Encoder settings
83
+ parser.add_argument('--encoder_kernel-size', dest='encoder_kernel_size', type=int, default=16, help='Kernel size for Conv1D encoder')
84
+ parser.add_argument('--encoder-embedding-dim', dest='encoder_embedding_dim', type=int, default=512, help='Embedding dimension from encoder')
85
+
86
+ # MossFormer model parameters
87
+ parser.add_argument('--mossformer-squence-dim', dest='mossformer_sequence_dim', type=int, default=512, help='Sequence dimension for MossFormer')
88
+ parser.add_argument('--num-mossformer_layer', dest='num_mossformer_layer', type=int, default=24, help='Number of MossFormer layers')
89
+
90
+ # Parse arguments from the config file
91
+ self.args = parser.parse_args(['--config', self.config_path])
92
+
93
+ def load_config_json(self, config_json_path):
94
+ with open(config_json_path, 'r') as file:
95
+ return json.load(file)
96
+
97
+ def combine_config_and_args(self, json_config, args):
98
+ # Convert argparse.Namespace to a dictionary
99
+ args_dict = vars(args)
100
+
101
+ # Remove `config` key from args_dict (it's the path to the JSON file)
102
+ args_dict.pop("config", None)
103
+
104
+ # Combine JSON config and args_dict, prioritizing args_dict
105
+ combined_config = {**json_config, **{k: v for k, v in args_dict.items() if v is not None}}
106
+ return combined_config
107
+
108
+ def load_args_sr(self):
109
+ """
110
+ Loads the arguments for the speech super-resolution task using a YAML config file.
111
+ Sets the configuration path and parses all the required parameters such as
112
+ input/output paths, model settings, and FFT parameters.
113
+ """
114
+ self.config_path = 'config/inference/' + self.model_name + '.yaml'
115
+ parser = yamlargparse.ArgumentParser("Settings")
116
+
117
+ # General model and inference settings
118
+ parser.add_argument('--config', help='Config file path', action=yamlargparse.ActionConfigFile)
119
+ parser.add_argument('--config_json', type=str, help='Path to the config.json file')
120
+ parser.add_argument('--mode', type=str, default='inference', help='Modes: train or inference')
121
+ parser.add_argument('--checkpoint-dir', dest='checkpoint_dir', type=str, default='checkpoints/FRCRN_SE_16K', help='Checkpoint directory')
122
+ parser.add_argument('--input-path', dest='input_path', type=str, help='Path for noisy audio input')
123
+ parser.add_argument('--output-dir', dest='output_dir', type=str, help='Directory for enhanced audio output')
124
+ parser.add_argument('--use-cuda', dest='use_cuda', default=1, type=int, help='Enable CUDA (1=True, 0=False)')
125
+ parser.add_argument('--num-gpu', dest='num_gpu', type=int, default=1, help='Number of GPUs to use')
126
+
127
+ # Model-specific settings
128
+ parser.add_argument('--network', type=str, help='Select SE models: FRCRN_SE_16K, MossFormer2_SE_48K')
129
+ parser.add_argument('--sampling-rate', dest='sampling_rate', type=int, default=16000, help='Sampling rate')
130
+ parser.add_argument('--one-time-decode-length', dest='one_time_decode_length', type=float, default=60.0, help='Max segment length for one-pass decoding')
131
+ parser.add_argument('--decode-window', dest='decode_window', type=float, default=1.0, help='Decoding chunk size')
132
+
133
+ # Parse arguments from the config file
134
+ self.args = parser.parse_args(['--config', self.config_path])
135
+ json_config = self.load_config_json(self.args.config_json)
136
+ self.args = self.combine_config_and_args(json_config, self.args)
137
+ self.args = argparse.Namespace(**self.args)
138
+
139
+ def load_args_tse(self):
140
+ """
141
+ Loads the arguments for the target speaker extraction (TSE) task using a YAML config file.
142
+ Parameters include input/output paths, CUDA configurations, and decoding parameters.
143
+ """
144
+ self.config_path = 'config/inference/' + self.model_name + '.yaml'
145
+ parser = yamlargparse.ArgumentParser("Settings")
146
+
147
+ # General model and inference settings
148
+ parser.add_argument('--config', default=self.config_path, help='Config file path', action=yamlargparse.ActionConfigFile)
149
+ parser.add_argument('--mode', type=str, default='inference', help='Modes: train or inference')
150
+ parser.add_argument('--checkpoint-dir', dest='checkpoint_dir', type=str, default='checkpoint_dir/AV_MossFormer2_TSE_16K', help='Checkpoint directory')
151
+ parser.add_argument('--input-path', dest='input_path', type=str, help='Path for mixed audio input')
152
+ parser.add_argument('--output-dir', dest='output_dir', type=str, help='Directory for separated audio output')
153
+ parser.add_argument('--use-cuda', dest='use_cuda', default=1, type=int, help='Enable CUDA (1=True, 0=False)')
154
+ parser.add_argument('--num-gpu', dest='num_gpu', type=int, default=1, help='Number of GPUs to use')
155
+
156
+ # Model-specific settings for target speaker extraction
157
+ parser.add_argument('--network', type=str, help='Select TSE models(currently supports AV_MossFormer2_TSE_16K)')
158
+ parser.add_argument('--sampling-rate', dest='sampling_rate', type=int, default=16000, help='Sampling rate (currently supports 16 kHz)')
159
+ parser.add_argument('--network_reference', type=dict, help='a dictionary that contains the parameters of auxilary reference signal')
160
+ parser.add_argument('--network_audio', type=dict, help='a dictionary that contains the network parameters')
161
+
162
+ # Decode parameters for streaming or chunk-based decoding
163
+ parser.add_argument('--one-time-decode-length', dest='one_time_decode_length', type=int, default=60, help='Max segment length for one-pass decoding')
164
+ parser.add_argument('--decode-window', dest='decode_window', type=int, default=1, help='Chunk length for streaming')
165
+
166
+ # Parse arguments from the config file
167
+ self.args = parser.parse_args(['--config', self.config_path])
168
+
169
+ def __call__(self, task, model_name):
170
+ """
171
+ Calls the appropriate argument-loading function based on the task type
172
+ (e.g., 'speech_enhancement', 'speech_separation', or 'target_speaker_extraction').
173
+ It then loads the corresponding model based on the selected task and model name.
174
+
175
+ Args:
176
+ - task (str): The task type ('speech_enhancement', 'speech_separation', 'target_speaker_extraction').
177
+ - model_name (str): The name of the model to load (e.g., 'FRCRN_SE_16K').
178
+
179
+ Returns:
180
+ - self.network: The instantiated neural network model.
181
+ """
182
+
183
+ self.model_name = model_name # Set the model name based on user input
184
+
185
+ # Load arguments specific to the task
186
+ if task == 'speech_enhancement':
187
+ self.load_args_se() # Load arguments for speech enhancement
188
+ elif task == 'speech_separation':
189
+ self.load_args_ss() # Load arguments for speech separation
190
+ elif task == 'speech_super_resolution':
191
+ self.load_args_sr() #load aurguments for speech super-resolution
192
+ elif task == 'target_speaker_extraction':
193
+ self.load_args_tse() # Load arguments for target speaker extraction
194
+ else:
195
+ # Print error message if the task is unsupported
196
+ print(f'{task} is not supported, please select from: '
197
+ 'speech_enhancement, speech_separation, or target_speaker_extraction')
198
+ return
199
+
200
+ #print(self.args) # Display the parsed arguments
201
+ self.args.task = task
202
+ self.args.network = self.model_name # Set the network name to the model name
203
+
204
+ # Initialize the corresponding network based on the selected model
205
+ if self.args.network == 'FRCRN_SE_16K':
206
+ from networks import CLS_FRCRN_SE_16K
207
+ self.network = CLS_FRCRN_SE_16K(self.args) # Load FRCRN model
208
+ elif self.args.network == 'MossFormer2_SE_48K':
209
+ from networks import CLS_MossFormer2_SE_48K
210
+ self.network = CLS_MossFormer2_SE_48K(self.args) # Load MossFormer2_SE model
211
+ elif self.args.network == 'MossFormer2_SR_48K':
212
+ from networks import CLS_MossFormer2_SR_48K
213
+ self.network = CLS_MossFormer2_SR_48K(self.args) #Load MossFormer2_SR model
214
+ elif self.args.network == 'MossFormerGAN_SE_16K':
215
+ from networks import CLS_MossFormerGAN_SE_16K
216
+ self.network = CLS_MossFormerGAN_SE_16K(self.args) # Load MossFormerGAN model
217
+ elif self.args.network == 'MossFormer2_SS_16K':
218
+ from networks import CLS_MossFormer2_SS_16K
219
+ self.network = CLS_MossFormer2_SS_16K(self.args) # Load MossFormer2 for separation
220
+ elif self.args.network == 'AV_MossFormer2_TSE_16K':
221
+ from networks import CLS_AV_MossFormer2_TSE_16K
222
+ self.network = CLS_AV_MossFormer2_TSE_16K(self.args) # Load AV MossFormer2 model for target speaker extraction
223
+ else:
224
+ # Print error message if no matching network is found
225
+ print("No network found!")
226
+ return
227
+
228
+ return self.network # Return the instantiated network model