File size: 5,852 Bytes
384ee4a | 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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 | """
Extract 10-sec clip from YouTube and run SAM Audio separation.
Usage:
python run_test.py <youtube_url> <start_time> <folder_name> <prompt>
Examples:
python run_test.py "https://youtube.com/watch?v=xxx" 01:23 sitar_tanpura "sitar"
python run_test.py "https://youtube.com/watch?v=xxx" 00:45 panche_baja "shehnai"
python run_test.py "https://youtube.com/watch?v=xxx" 30 tabla_madal "tabla"
Output structure:
tests/
test1_sitar_tanpura/
original.wav
target.wav
residual.wav
prompt.txt
"""
import subprocess
import sys
import os
import torch
import torchaudio
from sam_audio import SAMAudio, SAMAudioProcessor
def extract_clip(url, start_time, output_path, duration=20):
print(f"Downloading {duration}s from {start_time}...")
cmd = [
"yt-dlp",
"-x",
"--audio-format",
"wav",
"--download-sections",
f"*{start_time}-{start_time}+{duration}",
"-o",
output_path,
"--force-overwrite",
"--no-playlist",
url,
]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0 or not os.path.exists(output_path):
print("Section download failed. Downloading full audio then trimming...")
temp_path = output_path + ".temp"
cmd_dl = [
"yt-dlp",
"-x",
"--audio-format",
"wav",
"-o",
f"{temp_path}.%(ext)s",
"--force-overwrite",
"--no-playlist",
url,
]
subprocess.run(cmd_dl, check=True)
# Find downloaded file
temp_dir = os.path.dirname(temp_path)
temp_name = os.path.basename(temp_path)
temp_file = None
for f in os.listdir(temp_dir):
if f.startswith(os.path.basename(temp_path)):
temp_file = os.path.join(temp_dir, f)
break
if not temp_file:
print("Error: download failed")
return False
# Trim with ffmpeg
cmd_trim = [
"ffmpeg",
"-y",
"-i",
temp_file,
"-ss",
str(start_time),
"-t",
str(duration),
"-ar",
"48000",
"-ac",
"1",
output_path,
]
subprocess.run(cmd_trim, check=True)
os.remove(temp_file)
else:
# Convert to 48kHz mono for SAM Audio
tmp = output_path + ".tmp.wav"
cmd_convert = [
"ffmpeg",
"-y",
"-i",
output_path,
"-ar",
"48000",
"-ac",
"1",
tmp,
]
subprocess.run(cmd_convert, capture_output=True)
if os.path.exists(tmp):
os.replace(tmp, output_path)
if os.path.exists(output_path):
size = os.path.getsize(output_path) / 1024
print(f"Saved: {output_path} ({size:.0f} KB)")
return True
print("Error: clip not created")
return False
def load_model():
print("Loading SAM Audio base model...")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = (
SAMAudio.from_pretrained(
"facebook/sam-audio-base",
visual_ranker=None,
audio_ranker=None,
)
.to(device)
.eval()
)
processor = SAMAudioProcessor.from_pretrained("facebook/sam-audio-base")
print(f"Model loaded on {device}!")
return model, processor, device
def separate(model, processor, device, audio_path, prompt, output_dir):
print(f'Separating with prompt: "{prompt}"')
inputs = processor(audios=[audio_path], descriptions=[prompt]).to(device)
with torch.inference_mode():
result = model.separate(inputs, predict_spans=True)
sr = processor.audio_sampling_rate
target_path = os.path.join(output_dir, "target.wav")
residual_path = os.path.join(output_dir, "residual.wav")
torchaudio.save(target_path, result.target[0].unsqueeze(0).cpu(), sr)
torchaudio.save(residual_path, result.residual[0].unsqueeze(0).cpu(), sr)
print(f"Target: {target_path}")
print(f"Residual: {residual_path}")
if __name__ == "__main__":
if len(sys.argv) < 5:
print(
'Usage: python run_test.py <youtube_url> <start_time> <folder_name> "<prompt>"'
)
print(
'Example: python run_test.py "https://youtube.com/watch?v=xxx" 01:23 sitar_tanpura "sitar"'
)
sys.exit(1)
url = sys.argv[1]
start = sys.argv[2]
folder_name = sys.argv[3]
prompt = sys.argv[4]
# Create output folder with test prefix
test_num = 1
while os.path.exists(os.path.join("tests", f"test{test_num}_{folder_name}")):
test_num += 1
output_dir = os.path.join("tests", f"test{test_num}_{folder_name}")
os.makedirs(output_dir, exist_ok=True)
original_path = os.path.join(output_dir, "original.wav")
# Extract clip
ok = extract_clip(url, start, original_path)
if not ok:
sys.exit(1)
# Load model and separate
model, processor, device = load_model()
separate(model, processor, device, original_path, prompt, output_dir)
# Save prompt and metadata to txt file
prompt_path = os.path.join(output_dir, "prompt.txt")
with open(prompt_path, "w") as f:
f.write(f"Prompt: {prompt}\n")
f.write(f"YouTube URL: {url}\n")
f.write(f"Start time: {start}\n")
f.write(f"Duration: 10 seconds\n")
print(f"\nDone! Check: {output_dir}/")
print(f" original.wav — input clip")
print(f" target.wav — isolated '{prompt}'")
print(f" residual.wav — everything else")
print(f" prompt.txt — input details")
|