| """ |
| 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) |
|
|
| |
| 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 |
|
|
| |
| 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: |
| |
| 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] |
|
|
| |
| 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") |
|
|
| |
| ok = extract_clip(url, start, original_path) |
| if not ok: |
| sys.exit(1) |
|
|
| |
| model, processor, device = load_model() |
| separate(model, processor, device, original_path, prompt, output_dir) |
|
|
| |
| 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") |
|
|