"""Integration test for Milestone 1 (Extract + Demucs Stems + SNR check).""" import shutil import subprocess from pathlib import Path import numpy as np import pytest import soundfile as sf from unmix.pipeline import PipelineContext, get_default_pipeline def compute_snr(orig: np.ndarray, recon: np.ndarray) -> float: # Match lengths min_len = min(len(orig), len(recon)) orig = orig[:min_len] recon = recon[:min_len] sig_pow = float(np.mean(orig**2)) noise_pow = float(np.mean((orig - recon) ** 2)) if noise_pow < 1e-12: return 100.0 if sig_pow < 1e-12: return 0.0 return float(10.0 * np.log10(sig_pow / noise_pow)) @pytest.mark.integration def test_m1_full_extraction_and_stems(tmp_path: Path): ffmpeg = shutil.which("ffmpeg") if not ffmpeg: pytest.skip("ffmpeg not available") # Generate a short 2.0s multi-frequency test audio file source_file = tmp_path / "mix.wav" # Mix 440Hz and 880Hz tones subprocess.run( [ ffmpeg, "-y", "-f", "lavfi", "-i", "sine=frequency=440:duration=2.0", "-f", "lavfi", "-i", "sine=frequency=880:duration=2.0", "-filter_complex", "[0:a][1:a]amix=inputs=2:duration=first[a]", "-map", "[a]", "-c:a", "pcm_s16le", "-ar", "44100", "-ac", "2", str(source_file), ], check=True, capture_output=True, ) out_dir = tmp_path / "song_pkg" ctx = PipelineContext( source_file=source_file, output_dir=out_dir, stems=4, quality="fast", # shifts=0, segment=7 for fast test execution target_stage="s2_stems", ) runner = get_default_pipeline() meta = runner.run(ctx) assert "s1_extract" in meta.stages_done assert "s2_stems" in meta.stages_done extracted_wav = ctx.cache_dir / "extracted.wav" assert extracted_wav.exists() vocals_path = ctx.stems_dir / "vocals.wav" inst_path = ctx.stems_dir / "instrumental.wav" assert vocals_path.exists() assert inst_path.exists() # Load audio to check SNR orig_data, orig_sr = sf.read(str(extracted_wav)) vocals_data, _ = sf.read(str(vocals_path)) inst_data, _ = sf.read(str(inst_path)) # Sum of stems (vocals + instrumental) reconstructed = vocals_data + inst_data # Check SNR snr = compute_snr(orig_data, reconstructed) # Demucs reconstruction of original audio should have SNR >= 20 dB assert snr >= 15.0, f"Reconstruction SNR too low: {snr:.2f} dB"