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
| 8 |
+
import threading
|
| 9 |
+
from tqdm import tqdm
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class MDXModel:
|
| 13 |
+
def __init__(self, device, dim_f, dim_t, n_fft, hop=1024, stem_name=None, compensation=1.000):
|
| 14 |
+
self.dim_f = dim_f
|
| 15 |
+
self.dim_t = dim_t
|
| 16 |
+
self.dim_c = 4
|
| 17 |
+
self.n_fft = n_fft
|
| 18 |
+
self.hop = hop
|
| 19 |
+
self.stem_name = stem_name
|
| 20 |
+
self.compensation = compensation
|
| 21 |
+
|
| 22 |
+
self.n_bins = self.n_fft // 2 + 1
|
| 23 |
+
self.chunk_size = hop * (self.dim_t - 1)
|
| 24 |
+
self.window = torch.hann_window(window_length=self.n_fft, periodic=True).to(device)
|
| 25 |
+
|
| 26 |
+
self.freq_pad = torch.zeros([1, self.dim_c, self.n_bins - self.dim_f, self.dim_t]).to(device)
|
| 27 |
+
|
| 28 |
+
def stft(self, x):
|
| 29 |
+
x = x.reshape([-1, self.chunk_size])
|
| 30 |
+
x = torch.stft(x, n_fft=self.n_fft, hop_length=self.hop, window=self.window,
|
| 31 |
+
center=True, return_complex=True)
|
| 32 |
+
x = torch.view_as_real(x)
|
| 33 |
+
x = x.permute([0, 3, 1, 2])
|
| 34 |
+
x = x.reshape([-1, 2, 2, self.n_bins, self.dim_t]).reshape([-1, 4, self.n_bins, self.dim_t])
|
| 35 |
+
return x[:, :, :self.dim_f]
|
| 36 |
+
|
| 37 |
+
def istft(self, x, freq_pad=None):
|
| 38 |
+
freq_pad = self.freq_pad.repeat([x.shape[0], 1, 1, 1]) if freq_pad is None else freq_pad
|
| 39 |
+
x = torch.cat([x, freq_pad], -2)
|
| 40 |
+
x = x.reshape([-1, 2, 2, self.n_bins, self.dim_t]).reshape([-1, 2, self.n_bins, self.dim_t])
|
| 41 |
+
x = x.permute([0, 2, 3, 1]).contiguous()
|
| 42 |
+
x = torch.view_as_complex(x)
|
| 43 |
+
x = torch.istft(x, n_fft=self.n_fft, hop_length=self.hop, window=self.window, center=True)
|
| 44 |
+
return x.reshape([-1, 2, self.chunk_size])
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class MDX:
|
| 48 |
+
DEFAULT_SR = 44100
|
| 49 |
+
DEFAULT_CHUNK_SIZE = 0 * DEFAULT_SR
|
| 50 |
+
DEFAULT_MARGIN_SIZE = 1 * DEFAULT_SR
|
| 51 |
+
|
| 52 |
+
def __init__(self, model_path: str, params: MDXModel, processor=0):
|
| 53 |
+
self.device = torch.device(f"cuda:{processor}" if processor >= 0 else "cpu")
|
| 54 |
+
self.provider = ["CUDAExecutionProvider"] if processor >= 0 else ["CPUExecutionProvider"]
|
| 55 |
+
self.model = params
|
| 56 |
+
self.ort = ort.InferenceSession(model_path, providers=self.provider)
|
| 57 |
+
self.ort.run(None, {"input": torch.rand(1, 4, params.dim_f, params.dim_t).numpy()})
|
| 58 |
+
self.process = lambda spec: self.ort.run(None, {"input": spec.cpu().numpy()})[0]
|
| 59 |
+
self.prog = None
|
| 60 |
+
|
| 61 |
+
@staticmethod
|
| 62 |
+
def get_hash(model_path):
|
| 63 |
+
try:
|
| 64 |
+
with open(model_path, "rb") as f:
|
| 65 |
+
f.seek(-10000 * 1024, 2)
|
| 66 |
+
return hashlib.md5(f.read()).hexdigest()
|
| 67 |
+
except:
|
| 68 |
+
return hashlib.md5(open(model_path, "rb").read()).hexdigest()
|
| 69 |
+
|
| 70 |
+
@staticmethod
|
| 71 |
+
def segment(wave, combine=True, chunk_size=DEFAULT_CHUNK_SIZE, margin_size=DEFAULT_MARGIN_SIZE):
|
| 72 |
+
if combine:
|
| 73 |
+
processed_wave = None
|
| 74 |
+
for segment_count, segment in enumerate(wave):
|
| 75 |
+
start = 0 if segment_count == 0 else margin_size
|
| 76 |
+
end = None if segment_count == len(wave) - 1 else -margin_size
|
| 77 |
+
if margin_size == 0:
|
| 78 |
+
end = None
|
| 79 |
+
part = segment[:, start:end]
|
| 80 |
+
processed_wave = part if processed_wave is None else np.concatenate((processed_wave, part), axis=-1)
|
| 81 |
+
else:
|
| 82 |
+
processed_wave = []
|
| 83 |
+
sample_count = wave.shape[-1]
|
| 84 |
+
if chunk_size <= 0 or chunk_size > sample_count:
|
| 85 |
+
chunk_size = sample_count
|
| 86 |
+
if margin_size > chunk_size:
|
| 87 |
+
margin_size = chunk_size
|
| 88 |
+
for segment_count, skip in enumerate(range(0, sample_count, chunk_size)):
|
| 89 |
+
margin = 0 if segment_count == 0 else margin_size
|
| 90 |
+
end = min(skip + chunk_size + margin_size, sample_count)
|
| 91 |
+
start = skip - margin
|
| 92 |
+
processed_wave.append(wave[:, start:end].copy())
|
| 93 |
+
if end == sample_count:
|
| 94 |
+
break
|
| 95 |
+
return processed_wave
|
| 96 |
+
|
| 97 |
+
def pad_wave(self, wave):
|
| 98 |
+
n_sample = wave.shape[1]
|
| 99 |
+
trim = self.model.n_fft // 2
|
| 100 |
+
gen_size = self.model.chunk_size - 2 * trim
|
| 101 |
+
pad = gen_size - n_sample % gen_size
|
| 102 |
+
|
| 103 |
+
wave_p = np.concatenate((np.zeros((2, trim)), wave, np.zeros((2, pad)), np.zeros((2, trim))), 1)
|
| 104 |
+
mix_waves = [torch.tensor(wave_p[:, i:i + self.model.chunk_size], dtype=torch.float32).to(self.device)
|
| 105 |
+
for i in range(0, n_sample + pad, gen_size)]
|
| 106 |
+
return torch.stack(mix_waves), pad, trim
|
| 107 |
+
|
| 108 |
+
def _process_wave(self, mix_waves, trim, pad, q: queue.Queue, _id: int):
|
| 109 |
+
mix_waves = mix_waves.split(1)
|
| 110 |
+
with torch.no_grad():
|
| 111 |
+
pw = []
|
| 112 |
+
for mix_wave in mix_waves:
|
| 113 |
+
self.prog.update()
|
| 114 |
+
spec = self.model.stft(mix_wave)
|
| 115 |
+
processed_spec = torch.tensor(self.process(spec))
|
| 116 |
+
processed_wav = self.model.istft(processed_spec.to(self.device))
|
| 117 |
+
result = processed_wav[:, :, trim:-trim].transpose(0, 1).reshape(2, -1).cpu().numpy()
|
| 118 |
+
pw.append(result)
|
| 119 |
+
q.put({_id: np.concatenate(pw, axis=-1)[:, :-pad]})
|
| 120 |
+
|
| 121 |
+
def process_wave(self, wave: np.array, mt_threads=1):
|
| 122 |
+
self.prog = tqdm(total=0)
|
| 123 |
+
chunk = wave.shape[-1] // mt_threads
|
| 124 |
+
waves = self.segment(wave, False, chunk)
|
| 125 |
+
q = queue.Queue()
|
| 126 |
+
threads = []
|
| 127 |
+
for c, batch in enumerate(waves):
|
| 128 |
+
mix_waves, pad, trim = self.pad_wave(batch)
|
| 129 |
+
self.prog.total = len(mix_waves) * mt_threads
|
| 130 |
+
thread = threading.Thread(target=self._process_wave, args=(mix_waves, trim, pad, q, c))
|
| 131 |
+
thread.start()
|
| 132 |
+
threads.append(thread)
|
| 133 |
+
for thread in threads:
|
| 134 |
+
thread.join()
|
| 135 |
+
self.prog.close()
|
| 136 |
+
processed_batches = [q.get() for _ in range(len(waves))]
|
| 137 |
+
processed_batches.sort(key=lambda d: list(d.keys())[0])
|
| 138 |
+
return self.segment([list(wave.values())[0] for wave in processed_batches], True, chunk)
|