FlashSR -fix/UtilAudio.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Literal, Union, Final, List
2
+ from numpy import ndarray
3
+
4
+ import os
5
+ from tqdm import tqdm
6
+ import numpy as np
7
+ import soundfile as sf
8
+ import librosa
9
+ from scipy.signal import resample_poly
10
+
11
+ try: import torch
12
+ except: print('import error: torch')
13
+ try: from torch import Tensor
14
+ except: print('')
15
+ try: import torchaudio
16
+ except: print('import error: torch')
17
+ try: from pydub import AudioSegment
18
+ except: print('import error: pydub')
19
+
20
+ from TorchJaekwon.Util.UtilData import UtilData
21
+
22
+ DATA_TYPE_MIN_MAX_DICT:Final[dict] = {'float32':(-1,1), 'float64':(-1,1), 'int16':(-2**15, 2**15-1), 'int32':(-2**31,2**31-1)}
23
+
24
+ class UtilAudio:
25
+ @staticmethod
26
+ def change_dtype(audio:ndarray,
27
+ current_dtype:Literal['float32', 'float64', 'int16', 'int32'],
28
+ target_dtype:Literal['float32', 'float64', 'int16', 'int32']
29
+ ) -> ndarray:
30
+ audio = np.clip(audio, a_min = DATA_TYPE_MIN_MAX_DICT[current_dtype][0], a_max = DATA_TYPE_MIN_MAX_DICT[current_dtype][1])
31
+ audio = audio / DATA_TYPE_MIN_MAX_DICT[current_dtype][1]
32
+ audio = (audio * DATA_TYPE_MIN_MAX_DICT[target_dtype][1])
33
+ audio = audio.astype(getattr(np,target_dtype))
34
+ return audio
35
+
36
+ @staticmethod
37
+ def resample_audio(audio:Union[ndarray, Tensor],
38
+ origin_sr:int,
39
+ target_sr:int,
40
+ resample_module:Literal['librosa', 'resample_poly', 'torchaudio'] = 'librosa',
41
+ resample_type:str = "kaiser_fast",
42
+ audio_path:Optional[str] = None):
43
+ if(origin_sr == target_sr): return audio
44
+ if resample_module == 'librosa':
45
+ return librosa.resample(audio, orig_sr=origin_sr, target_sr=target_sr, res_type=resample_type)
46
+ elif resample_module == 'resample_poly':
47
+ return resample_poly(x = audio, up = target_sr, down = origin_sr)
48
+ elif resample_module == 'torchaudio':
49
+ return torchaudio.transforms.Resample(orig_freq = origin_sr, new_freq = target_sr)(audio)
50
+
51
+ @staticmethod
52
+ def read(audio_path:str,
53
+ sample_rate:Optional[int] = None,
54
+ mono:Optional[bool] = None,
55
+ start_idx:int = 0,
56
+ end_idx:Optional[int] = None,
57
+ module_name:Literal['soundfile','librosa', 'torchaudio'] = 'torchaudio',
58
+ return_type:Union[ndarray, Tensor] = ndarray
59
+ ) -> Union[ndarray, Tensor]:
60
+
61
+ if module_name == "soundfile":
62
+ audio_data, original_samplerate = sf.read(audio_path)
63
+ if len(audio_data.shape) > 1 : audio_data = audio_data.T
64
+
65
+ if sample_rate is not None and sample_rate != original_samplerate:
66
+ audio_data = UtilAudio.resample_audio(audio_data,original_samplerate,sample_rate)
67
+
68
+ elif module_name == "librosa":
69
+ print(f"read audio sr: {sample_rate}")
70
+ audio_data, original_samplerate = librosa.load(audio_path, sr=sample_rate, mono=mono)
71
+
72
+ elif module_name == 'torchaudio':
73
+ if end_idx is not None: assert end_idx > start_idx, f'[Error] end_idx must be larger than start_idx'
74
+ audio_data, original_samplerate = torchaudio.load(audio_path,
75
+ frame_offset = start_idx,
76
+ num_frames = -1 if end_idx is None else end_idx - start_idx)
77
+ if sample_rate is not None and sample_rate != original_samplerate:
78
+ audio_data = UtilAudio.resample_audio(audio = audio_data, origin_sr=original_samplerate, target_sr = sample_rate, resample_module='torchaudio', audio_path = audio_path)
79
+
80
+ if mono is not None:
81
+ if mono and len(audio_data.shape) == 2 and audio_data.shape[0] == 2:
82
+ audio_data = torch.mean(audio_data,axis=0) if isinstance(audio_data, torch.Tensor) else np.mean(audio_data,axis=0)
83
+ elif not mono and (len(audio_data.shape) == 1 or audio_data.shape[0] == 1):
84
+ stereo_audio = torch.zeros((2,len(audio_data.squeeze())))
85
+ stereo_audio[0,...] = audio_data.squeeze()
86
+ stereo_audio[1,...] = audio_data.squeeze()
87
+ audio_data = stereo_audio
88
+
89
+ assert ((len(audio_data.shape)==1) or ((len(audio_data.shape)==2) and audio_data.shape[0] in [1,2])),f'[read audio shape problem] path: {audio_path} shape: {audio_data.shape}'
90
+
91
+ return audio_data, original_samplerate if sample_rate is None else sample_rate
92
+
93
+ @staticmethod
94
+ def write(audio_path: str,
95
+ audio: Union[ndarray, Tensor],
96
+ sample_rate: int,
97
+ source_path: str = None) -> None:
98
+ """
99
+ Saves audio in the same format as the original source file if possible.
100
+ Falls back to WAV if source is unknown.
101
+ """
102
+ import subprocess
103
+ import tempfile
104
+
105
+ os.makedirs(os.path.dirname(audio_path), exist_ok=True)
106
+
107
+ # Auto-detect extension from source_path if provided
108
+ if source_path:
109
+ ext = os.path.splitext(source_path)[1].lower()
110
+ audio_path = os.path.splitext(audio_path)[0] + ext
111
+ else:
112
+ ext = os.path.splitext(audio_path)[1].lower()
113
+
114
+ if isinstance(audio, Tensor):
115
+ audio = audio.squeeze().cpu().detach().numpy()
116
+ assert len(audio.shape) <= 2, f'[Error] shape of {audio_path}: {audio.shape}'
117
+ if len(audio.shape) == 2 and audio.shape[0] < audio.shape[1]:
118
+ audio = audio.T
119
+
120
+ sf_formats = [".wav", ".flac", ".ogg", ".aiff", ".aif"]
121
+
122
+ if ext in sf_formats:
123
+ sf.write(file=audio_path, data=audio, samplerate=sample_rate)
124
+ else:
125
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp_wav:
126
+ sf.write(file=tmp_wav.name, data=audio, samplerate=sample_rate)
127
+ tmp_wav_path = tmp_wav.name
128
+ try:
129
+ subprocess.run([
130
+ "ffmpeg", "-y", "-i", tmp_wav_path, audio_path
131
+ ], check=True)
132
+ finally:
133
+ os.remove(tmp_wav_path)
134
+
135
+ @staticmethod
136
+ def stereo_to_mono(audio_data:Union[ndarray, Tensor]) -> Union[ndarray, Tensor]:
137
+ audio_data = np.mean(audio_data,axis=1)
138
+ return audio_data
139
+
140
+ @staticmethod
141
+ def mono_to_stereo(audio_data:Union[ndarray, Tensor]) -> Union[ndarray, Tensor]:
142
+ stereo_audio = np.zeros((2,len(audio_data)))
143
+ stereo_audio[0,...] = audio_data
144
+ stereo_audio[1,...] = audio_data
145
+ audio_data = stereo_audio
146
+ return audio_data
147
+
148
+ @staticmethod
149
+ def normalize_volume(audio_input:ndarray,sr:int, target_dBFS = -30):
150
+ audio = UtilAudio.change_dtype(audio=audio_input,current_dtype='float64',target_dtype='int32')
151
+ audio_segment = AudioSegment(audio.tobytes(), frame_rate=sr, sample_width=audio.dtype.itemsize, channels=1)
152
+ change_in_dBFS = target_dBFS - audio_segment.dBFS
153
+ normalizedsound = audio_segment.apply_gain(change_in_dBFS)
154
+ return UtilAudio.change_dtype(audio=np.array(normalizedsound.get_array_of_samples()),current_dtype='int32',target_dtype='float64')
155
+
156
+ @staticmethod
157
+ def normalize_by_fro_norm(audio_input:Tensor) -> Tensor:
158
+ original_shape:tuple = audio_input.shape
159
+ audio = audio_input.reshape(original_shape[0], -1)
160
+ audio = audio/torch.norm(audio, p="fro", dim=1, keepdim=True)
161
+ audio = audio.reshape(*original_shape)
162
+ return audio
163
+
164
+ @staticmethod
165
+ def energy_unify(estimated, original, eps = 1e-12):
166
+ target = UtilAudio.pow_norm(estimated, original) * original
167
+ target /= UtilAudio.pow_p_norm(original) + eps
168
+ return estimated, target
169
+
170
+ @staticmethod
171
+ def pow_norm(s1, s2):
172
+ return torch.sum(s1 * s2)
173
+
174
+ @staticmethod
175
+ def pow_p_norm(signal):
176
+ return torch.pow(torch.norm(signal, p=2), 2)
177
+
178
+ @staticmethod
179
+ def get_segment_index_list(audio:ndarray,
180
+ sample_rate:int,
181
+ segment_sample_length:int,
182
+ hop_seconds:float = 0.1) -> list:
183
+ begin_sample:int = 0
184
+ hop_samples = int(hop_seconds * sample_rate)
185
+ segment_index_list = list()
186
+ while (begin_sample == 0) or (begin_sample + segment_sample_length < len(audio)):
187
+ segment_index_list.append({'begin':begin_sample, 'end':begin_sample + segment_sample_length})
188
+ begin_sample += hop_samples
189
+ return segment_index_list
190
+
191
+ @staticmethod
192
+ def audio_to_batch(audio:Tensor,
193
+ segment_length:int,
194
+ overlap_length:int = 48000):
195
+ assert len(audio.shape) == 1, f'[Error] audio shape must be 1, but {audio.shape}'
196
+ start_idx:int = 0
197
+ audio_list = list()
198
+ while start_idx < len(audio):
199
+ audio_segment = audio[start_idx:start_idx+segment_length]
200
+ audio_segment = UtilData.fix_length(audio_segment, segment_length)
201
+ audio_list.append(audio_segment)
202
+ start_idx += segment_length - overlap_length
203
+ return torch.stack(audio_list)
204
+
205
+ @staticmethod
206
+ def merge_batch_w_cross_fade(batch_audio:Union[List[ndarray],ndarray,Tensor],
207
+ segment_length:int,
208
+ overlap_length:int = 48000) -> ndarray:
209
+ if isinstance(batch_audio, ndarray) and len(batch_audio.shape) == 1:
210
+ batch_audio = [batch_audio]
211
+ output_audio_length:int = len(batch_audio) * segment_length - (len(batch_audio) - 1) * overlap_length
212
+ output_audio:Union[ndarray,Tensor] = torch.zeros(output_audio_length) if isinstance(batch_audio, torch.Tensor) else np.zeros(output_audio_length)
213
+ hop_length:int = segment_length - overlap_length
214
+
215
+ cross_fade_in:ndarray = np.linspace(0, 1, overlap_length)
216
+ cross_fade_out:ndarray = 1 - cross_fade_in
217
+ if isinstance(batch_audio, torch.Tensor):
218
+ cross_fade_in = torch.tensor(cross_fade_in, device = batch_audio.device)
219
+ cross_fade_out = torch.tensor(cross_fade_out, device = batch_audio.device)
220
+
221
+ for i in range(0,len(batch_audio)):
222
+ start_idx:int = i * hop_length
223
+ if i != 0:
224
+ batch_audio[i][:overlap_length] *= cross_fade_in
225
+ if i != len(batch_audio) - 1:
226
+ batch_audio[i][-overlap_length:] *= cross_fade_out
227
+ output_audio[start_idx:start_idx+segment_length] += batch_audio[i]
228
+ return output_audio
229
+
230
+ @staticmethod
231
+ def analyze_audio_dataset(data_dir:str,
232
+ result_save_dir:str,
233
+ sanity_check_sr:Union[int,List[int]] = None,
234
+ save_each_meta:bool = False) -> None:
235
+ total_meta_dict:dict = {
236
+ 'total_duration_second': 0,
237
+ 'total_duration_minutes': 0,
238
+ 'total_duration_hours': 0,
239
+ 'longest_sample_meta': {
240
+ 'file_name': '',
241
+ 'duration_second':0
242
+ },
243
+ 'error_file_list': list()
244
+ }
245
+ if sanity_check_sr is not None: total_meta_dict['sample_rate'] = sanity_check_sr
246
+
247
+ audio_meta_data_list = UtilData.walk(dir_name=data_dir, ext=['.wav', '.mp3', '.flac'])
248
+ for meta_data in tqdm(audio_meta_data_list):
249
+ try:
250
+ audio, sr = UtilAudio.read(meta_data['file_path'], mono=True)
251
+ except:
252
+ print(f'Error: {meta_data["file_path"]}')
253
+ total_meta_dict['error_file_list'].append(meta_data['file_path'])
254
+ continue
255
+ if sanity_check_sr is not None:
256
+ if isinstance(sanity_check_sr, int): assert sr == sanity_check_sr, f'''{meta_data['file_path']}'s sample rate is {sr}'''
257
+ if isinstance(sanity_check_sr, list): assert sr in sanity_check_sr, f'''{meta_data['file_path']}'s sample rate is {sr}'''
258
+
259
+ meta_data_of_this_file = {
260
+ 'file_name': meta_data['file_name'],
261
+ 'file_path': os.path.abspath(meta_data['file_path']),
262
+ 'sample_length': audio.shape[-1],
263
+ 'sample_rate': sr,
264
+ }
265
+ meta_data_of_this_file['duration_second'] = meta_data_of_this_file['sample_length'] / meta_data_of_this_file['sample_rate']
266
+
267
+ save_dir:str = meta_data['dir_path'].replace(data_dir, result_save_dir)
268
+ if save_each_meta: UtilData.pickle_save(f'''{save_dir}/{meta_data['file_name']}.pkl''', meta_data_of_this_file)
269
+
270
+ total_meta_dict['total_duration_second'] += meta_data_of_this_file['duration_second']
271
+ if total_meta_dict['longest_sample_meta']['duration_second'] < meta_data_of_this_file['duration_second']:
272
+ total_meta_dict['longest_sample_meta'] = meta_data_of_this_file
273
+
274
+ total_meta_dict['total_duration_minutes'] = total_meta_dict['total_duration_second'] / 60
275
+ total_meta_dict['total_duration_hours'] = total_meta_dict['total_duration_second'] / 3600
276
+ UtilData.yaml_save(save_path = f'{result_save_dir}/meta.yaml', data = total_meta_dict)
FlashSR -fix/UtilAudioLowPassFilter.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ #from TorchJaekwon.Util.Util import Util
3
+ #Util.set_sys_path_to_parent_dir(__file__, 2)
4
+
5
+ from typing import Literal
6
+ from numpy import ndarray
7
+
8
+ import numpy as np
9
+ from scipy.signal import butter, cheby1, cheby2, ellip, bessel, sosfiltfilt, resample_poly
10
+
11
+ class UtilAudioLowPassFilter:
12
+ # this code is refactored version of https://github.com/haoheliu/ssr_eval
13
+
14
+ @staticmethod
15
+ def lowpass(audio:ndarray, #[time] 1d array
16
+ sr:int,
17
+ filter_name:Literal["cheby","butter","bessel","ellip"],
18
+ filter_order:int,
19
+ cutoff_freq:int,
20
+ upsample_to_original:bool = True
21
+ ):
22
+ assert len(audio.shape) == 1 or (len(audio.shape) == 2 and (audio.shape[0] == 1 or audio.shape[0] == 2))
23
+ if filter_name == "cheby": filter_name = "cheby1"
24
+ assert filter_order >= 2 and filter_order <= 10, f"filter_order should be between 2 and 10, but {filter_order} is given"
25
+ if cutoff_freq >= sr: cutoff_freq = sr - 1 # avoid Nyquist overflow
26
+ if len(audio.shape) == 2:
27
+ lowpassed_audio = np.zeros_like(audio)
28
+ for i in range(audio.shape[0]):
29
+ lowpassed_audio[i] = UtilAudioLowPassFilter.lowpass_filter(
30
+ x=audio[i],
31
+ highcutoff_freq=int(cutoff_freq),
32
+ fs=sr,
33
+ order=filter_order,
34
+ ftype=filter_name,
35
+ upsample_to_original = upsample_to_original)
36
+ else:
37
+ lowpassed_audio = UtilAudioLowPassFilter.lowpass_filter(
38
+ x=audio,
39
+ highcutoff_freq=int(cutoff_freq),
40
+ fs=sr,
41
+ order=filter_order,
42
+ ftype=filter_name,
43
+ upsample_to_original = upsample_to_original)
44
+ if upsample_to_original:
45
+ assert lowpassed_audio.shape == audio.shape, f'error lowpass_butterworth: {str((lowpassed_audio.shape, audio.shape))}'
46
+ return lowpassed_audio.copy() # avoid the problem [Torch.from_numpy not support negative strides]
47
+
48
+
49
+ @staticmethod
50
+ def lowpass_filter(x:ndarray, #[time] 1d array
51
+ highcutoff_freq:float, #high cutoff frequency
52
+ fs:int,
53
+ order:int, #the order of filter
54
+ ftype:Literal['butter', 'cheby1', 'cheby2', 'ellip', 'bessel'],
55
+ upsample_to_original:bool = True
56
+ ) -> ndarray: #[time] 1d array
57
+ nyq = 0.5 * fs
58
+ hi = highcutoff_freq / nyq
59
+
60
+ # Clamp and debug
61
+ hi_clamped = min(max(hi, 1e-6), 0.99) # ensure 0 < hi < 1
62
+ print(f"[DEBUG] Filter: {ftype}, Original hi: {hi:.6f}, Clamped hi: {hi_clamped:.6f}")
63
+
64
+ if ftype == "butter":
65
+ sos = butter(order, hi_clamped, btype="low", output="sos")
66
+ elif ftype == "cheby1":
67
+ sos = cheby1(order, 0.1, hi_clamped, btype="low", output="sos")
68
+ elif ftype == "cheby2":
69
+ sos = cheby2(order, 60, hi_clamped, btype="low", output="sos")
70
+ elif ftype == "ellip":
71
+ sos = ellip(order, 0.1, 60, hi_clamped, btype="low", output="sos")
72
+ elif ftype == "bessel":
73
+ sos = bessel(order, hi_clamped, btype="low", output="sos")
74
+ else:
75
+ raise Exception(f"The lowpass filter {ftype} is not supported!")
76
+
77
+ y = sosfiltfilt(sos, x)
78
+
79
+ if len(y) != len(x):
80
+ y = UtilAudioLowPassFilter.align_length(x, y)
81
+
82
+ y = UtilAudioLowPassFilter.subsampling(
83
+ y,
84
+ lowpass_ratio=highcutoff_freq / int(fs / 2),
85
+ fs_ori=fs,
86
+ upsample_to_original=upsample_to_original
87
+ )
88
+ return y
89
+
90
+ @staticmethod
91
+ def align_length(x, y):
92
+ """align the length of y to that of x"""
93
+ Lx = len(x)
94
+ Ly = len(y)
95
+
96
+ if Lx == Ly:
97
+ return y
98
+ elif Lx > Ly:
99
+ return np.pad(y, (0, Lx - Ly), mode="constant")
100
+ else:
101
+ return y[:Lx]
102
+
103
+ @staticmethod
104
+ def subsampling(data, lowpass_ratio, fs_ori=44100, upsample_to_original:bool = True):
105
+ assert len(data.shape) == 1
106
+ fs_down = int(lowpass_ratio * fs_ori)
107
+ y = resample_poly(data, fs_down, fs_ori)
108
+
109
+ if upsample_to_original:
110
+ y = resample_poly(y, fs_ori, fs_down)
111
+ if len(y) != len(data):
112
+ y = UtilAudioLowPassFilter.align_length(data, y)
113
+ return y
114
+
115
+ if __name__ == "__main__":
116
+ util = UtilAudioLowPassFilter()
117
+ util.lowpass(np.zeros(24000), 48000, filter_name="cheby", filter_order=8, cutoff_freq=8000)
FlashSR -fix/inference.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import torch
3
+ import numpy as np
4
+ from TorchJaekwon.Util.UtilAudio import UtilAudio
5
+ from TorchJaekwon.Util.UtilData import UtilData
6
+ from tqdm import tqdm
7
+ from FlashSR.FlashSR import FlashSR
8
+ import warnings
9
+ import math
10
+ import os
11
+ from pathlib import Path
12
+ import glob
13
+
14
+ warnings.filterwarnings("ignore")
15
+
16
+
17
+ def _getWindowingArray(window_size, fade_size):
18
+ fadein = torch.linspace(0, 1, fade_size)
19
+ fadeout = torch.linspace(1, 0, fade_size)
20
+ window = torch.ones(window_size)
21
+ window[-fade_size:] *= fadeout
22
+ window[:fade_size] *= fadein
23
+ return window
24
+
25
+ def process_audio(input_path, output_path, overlap, flashsr, device):
26
+ audio, sr = UtilAudio.read(input_path, sample_rate=48000)
27
+ audio = audio.to(device)
28
+
29
+ C = 245760 # chunk_size
30
+ N = overlap
31
+ step = C // N
32
+ fade_size = C // 10
33
+ print(f"N = {N} | C = {C} | step = {step} | fade_size = {fade_size}")
34
+
35
+ border = C - step
36
+
37
+ if len(audio.shape) == 1:
38
+ audio = audio.unsqueeze(0)
39
+
40
+ if audio.shape[1] > 2 * border and (border > 0):
41
+ audio = torch.nn.functional.pad(audio, (border, border), mode='reflect')
42
+
43
+ total_chunks = math.ceil(audio.size(1) / step)
44
+ print(total_chunks)
45
+
46
+ windowingArray = _getWindowingArray(C, fade_size)
47
+
48
+ result = torch.zeros((1,) + tuple(audio.shape), dtype=torch.float32)
49
+ counter = torch.zeros((1,) + tuple(audio.shape), dtype=torch.float32)
50
+
51
+ i = 0
52
+ progress_bar = tqdm(total=total_chunks, desc="Processing audio chunks", leave=False, unit="chunk")
53
+
54
+ while i < audio.shape[1]:
55
+ part = audio[:, i:i + C]
56
+ length = part.shape[-1]
57
+ if length < C:
58
+ if length > C // 2 + 1:
59
+ part = torch.nn.functional.pad(input=part, pad=(0, C - length), mode='reflect')
60
+ else:
61
+ part = torch.nn.functional.pad(input=part, pad=(0, C - length, 0, 0), mode='constant', value=0)
62
+
63
+ out = flashsr(part, lowpass_input=True).cpu()
64
+
65
+ window = windowingArray
66
+ if i == 0:
67
+ window[:fade_size] = 1
68
+ elif i + C >= audio.shape[1]:
69
+ window[-fade_size:] = 1
70
+
71
+ result[..., i:i + length] += out[..., :length] * window[..., :length]
72
+ counter[..., i:i + length] += window[..., :length]
73
+
74
+ i += step
75
+ progress_bar.update(1)
76
+
77
+ progress_bar.close()
78
+
79
+ final_output = result / counter
80
+ final_output = final_output.squeeze(0).numpy()
81
+ np.nan_to_num(final_output, copy=False, nan=0.0)
82
+
83
+ if audio.shape[1] > 2 * border and (border > 0):
84
+ final_output = final_output[..., border:-border]
85
+
86
+ # FIX: changed file_path to input_path
87
+ UtilAudio.write(output_path, final_output, 48000, source_path=input_path)
88
+ print(f'Success! Output file saved as {output_path}')
89
+
90
+
91
+ def main(input, output, overlap):
92
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
93
+
94
+ student_ldm_ckpt_path = './ckpts/student_ldm.pth'
95
+ sr_vocoder_ckpt_path = './ckpts/sr_vocoder.pth'
96
+ vae_ckpt_path = './ckpts/vae.pth'
97
+ flashsr = FlashSR(student_ldm_ckpt_path, sr_vocoder_ckpt_path, vae_ckpt_path)
98
+ flashsr = flashsr.to(device)
99
+
100
+ if Path(input).is_file():
101
+ file_path = input
102
+ filename = Path(input).name
103
+ Path(output).mkdir(parents=True, exist_ok=True)
104
+ process_audio(file_path, os.path.join(output, filename), overlap, flashsr, device)
105
+ else:
106
+ for file_path in sorted(glob.glob(os.path.join(input, "*"))):
107
+ filename = Path(file_path).name
108
+ Path(output).mkdir(parents=True, exist_ok=True)
109
+ process_audio(file_path, os.path.join(output, filename), overlap, flashsr, device)
110
+
111
+
112
+ if __name__ == "__main__":
113
+ parser = argparse.ArgumentParser(description="Audio Inference Script")
114
+ parser.add_argument("--input", type=str, required=True, help="Path to input wav file or folder")
115
+ parser.add_argument("--output", type=str, required=True, help="Path to output folder")
116
+ parser.add_argument("--overlap", type=int, help="Overlap", default=2)
117
+
118
+ args = parser.parse_args()
119
+
120
+ main(args.input, args.output, args.overlap)