-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsongprocessor.py
More file actions
61 lines (52 loc) · 2.31 KB
/
songprocessor.py
File metadata and controls
61 lines (52 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import torch
import torchaudio
from demucs.pretrained import get_model
from demucs.apply import apply_model
from youtubedl import YouTubeAudioDownloader
import soundfile as sf
import numpy as np
# Use MPS (Apple's GPU acceleration) if available, otherwise CPU
device = 'mps' if torch.backends.mps.is_available() else 'cpu'
# Load model once
model = get_model('htdemucs').to(device)
model.eval()
def remove_drums(input_path, output_path):
# Use soundfile to load mp3
audio_data, sr = sf.read(input_path)
# Convert to torch tensor and transpose to (channels, samples)
wav = torch.from_numpy(audio_data.T).float()
if wav.shape[0] == 1:
wav = wav.repeat(2, 1)
with torch.no_grad():
sources = apply_model(
model,
wav[None].to(device),
device=device,
shifts=1, # Lower for speed
overlap=0.25
)
# Remove drums (index 0)
no_drums = sources[0, 1:].sum(0).cpu()
# Save as WAV (torchaudio can save WAV natively)
output_path = output_path.replace('.mp3', '.wav')
torchaudio.save(output_path, no_drums, sr)
#returns path of processed file based on youtube search
def download_and_process(search, temp_folder="temp_music", output_folder="output_music", processing_queue=None, position_in_queue=None):
try:
downloader = YouTubeAudioDownloader(output_dir=temp_folder)
audio_path = downloader.download_from_search(search,output_format='mp3')
print(f"Downloaded to {audio_path}")
# Change extension to .wav since remove_drums saves as WAV
output_path = f"{output_folder}/{audio_path.split('/')[-1]}".replace('.mp3', '.wav')
remove_drums(audio_path, output_path)
temp_song = None
if processing_queue is not None and position_in_queue is not None and len(processing_queue) > position_in_queue:
temp_song = processing_queue.pop(position_in_queue)
temp_song['location'] = output_path
return temp_song #store user and search term
except Exception as e:
print(f"Failed to process '{search}': {e}")
# Remove from queue on failure
if processing_queue is not None and position_in_queue is not None and len(processing_queue) > position_in_queue:
processing_queue.pop(position_in_queue)
return None