Reformule esse código deixando no menor tamanho possível deixando exatamente as mesmas funcionalidades
python
import os
import sys
import torch
import soundfile as sf
from pydub import AudioSegment
import mel
import numpy as np
# Constants for configuration
MODEL = 'model_bs_roformer_ep_128_sdr_12.7876'
OVERLAP = 2
TIPO = 'vocals' # 'vocals', 'instrumental', or 'all'
# Initialize demixer outside functions for efficiency
demixer = mel.AudioDemixer(model_name=MODEL, device_ids=0, overlap=OVERLAP)
def process_audio(input_file):
"""Processes an audio file, handling conversion, separation, and mixing."""
converted_file = convert_to_wav(input_file)
output_file = create_output_file(converted_file)
run_mdx_net(converted_file, output_file)
vocals_file = output_file.replace(".wav", "_vocals.wav")
invert_phase(vocals_file)
mix_files(vocals_file, converted_file, output_file.replace(".wav", "_instrumental.wav"))
invert_phase(vocals_file) # Restore original phase
remove_unneeded_files(output_file)
def convert_to_wav(input_file):
"""Converts an audio file to WAV format if necessary."""
if input_file.lower().endswith('.wav'):
return input_file
audio = AudioSegment.from_file(input_file)
wav_file = os.path.splitext(input_file)[0] + ".wav"
audio.export(wav_file, format="wav", parameters=["-acodec", "pcm_s16le"])
os.remove(input_file)
return wav_file
def create_output_file(input_file):
"""Creates an output file path based on the input file."""
input_dir, input_file_name = os.path.split(input_file)
output_file_name = os.path.splitext(input_file_name)[0] + ".wav"
return os.path.join(input_dir, output_file_name)
def run_mdx_net(input_file, output_file):
"""Runs the MDX network to separate audio sources."""
mix, sr = sf.read(input_file)
mixture = torch.tensor(mix.T, dtype=torch.float32)
res = demixer.demix_track(mixture)
for instr in demixer.config.training.instruments:
if TIPO == 'instrumental' and instr != 'vocals':
continue
if instr in res:
output_file_instr = output_file.replace(".wav", f"_{instr}.wav")
sf.write(output_file_instr, res[instr].T, sr, subtype='PCM_16')
def invert_phase(input_file):
"""Inverts the phase of an audio file."""
data, sr = sf.read(input_file)
data = -data
sf.write(input_file, data, sr, subtype='PCM_16')
def mix_files(input_file_1, input_file_2, output_file):
"""Mixes two audio files with the same sample rate and size."""
data_1, sr_1 = sf.read(input_file_1)
data_2, sr_2 = sf.read(input_file_2)
assert sr_1 == sr_2, "Files must have the same sample rate."
assert data_1.shape == data_2.shape, "Files must have the same size."
data = data_1 + data_2
data = np.clip(data, -1, 1) # Limit values to avoid distortion
sf.write(output_file, data, sr_1, subtype='PCM_16')
def remove_unneeded_files(output_file):
"""Removes intermediate files that are no longer needed."""
if TIPO == 'vocals':
os.remove(output_file.replace(".wav", "_instrumental.wav"))
elif TIPO == 'instrumental':
os.remove(output_file.replace(".wav", "_vocals.wav"))
if __name__ == "__main__":
input_files = sys.argv[1:]
for input_file in input_files:
process_audio(input_file)
Assistant
python
import os, sys, torch, soundfile as sf, mel, numpy as np
from pydub import AudioSegment
MODEL, OVERLAP, TIPO = 'model_bs_roformer_ep_128_sdr_12.7876', 2, 'vocals'
demixer = mel.AudioDemixer(model_name=MODEL, device_ids=0, overlap=OVERLAP)
def process_audio(input_file):
converted_file = convert_to_wav(input_file)
output_file = create_output_file(converted_file)
run_mdx_net(converted_file, output_file)
vocals_file = output_file.replace(".wav", "_vocals.wav")
invert_phase(vocals_file)
mix_files(vocals_file, converted_file, output_file.replace(".wav", "_instrumental.wav"))
invert_phase(vocals_file)
remove_unneeded_files(output_file)
def convert_to_wav(input_file):
if input_file.lower().endswith('.wav'): return input_file
audio = AudioSegment.from_file(input_file)
wav_file = os.path.splitext(input_file)[0] + ".wav"
audio.export(wav_file, format="wav", parameters=["-acodec", "pcm_s16le"])
os.remove(input_file)
return wav_file
def create_output_file(input_file):
input_dir, input_file_name = os.path.split(input_file)
output_file_name = os.path.splitext(input_file_name)[0] + ".wav"
return os.path.join(input_dir, output_file_name)
def run_mdx_net(input_file, output_file):
mix, sr = sf.read(input_file)
mixture = torch.tensor(mix.T, dtype=torch.float32)
res = demixer.demix_track(mixture)
for instr in demixer.config.training.instruments:
if TIPO == 'instrumental' and instr != 'vocals': continue
if instr in res:
output_file_instr = output_file.replace(".wav", f"_{instr}.wav")
sf.write(output_file_instr, res[instr].T, sr, subtype='PCM_16')
def invert_phase(input_file):
data, sr = sf.read(input_file)
data = -data
sf.write(input_file, data, sr, subtype='PCM_16')
def mix_files(input_file_1, input_file_2, output_file):
data_1, sr_1 = sf.read(input_file_1)
data_2, sr_2 = sf.read(input_file_2)
assert sr_1 == sr_2, "Files must have the same sample rate."
assert data_1.shape == data_2.shape, "Files must have the same size."
data = data_1 + data_2
data = np.clip(data, -1, 1)
sf.write(output_file, data, sr_1, subtype='PCM_16')
def remove_unneeded_files(output_file):
if TIPO == 'vocals': os.remove(output_file.replace(".wav", "_instrumental.wav"))
elif TIPO == 'instrumental': os.remove(output_file.replace(".wav", "_vocals.wav"))
if __name__ == "__main__":
input_files = sys.argv[1:]
for input_file in input_files: process_audio(input_file)