300 lines
11 KiB
Python
300 lines
11 KiB
Python
"""
|
|
Unit tests for long-track chunked separation (Phase 5).
|
|
|
|
Tests cover:
|
|
- Chunk planning logic (boundary alignment, edge cases)
|
|
- Activation policy (auto/always/off modes)
|
|
- Overlap-add reconstruction (trapezoidal window correctness)
|
|
- Integration with separator service (mocked inference)
|
|
"""
|
|
import unittest
|
|
import numpy as np
|
|
from pathlib import Path
|
|
from typing import Dict, List, Tuple
|
|
|
|
# Import chunking module
|
|
import sys
|
|
sys.path.insert(0, str(Path(__file__).parent.parent))
|
|
|
|
from services.separation.chunking import (
|
|
ChunkPlan,
|
|
plan_chunks,
|
|
should_chunk,
|
|
extract_chunk,
|
|
overlap_add_reconstruct,
|
|
)
|
|
|
|
|
|
class TestChunkPlanning(unittest.TestCase):
|
|
"""Test chunk boundary planning."""
|
|
|
|
def test_plan_chunks_basic(self):
|
|
"""Basic chunk plan for 10-second audio at 44.1 kHz with 3s chunks, 0.5s overlap."""
|
|
total_samples = 441000 # 10 seconds at 44.1 kHz
|
|
sample_rate = 44100
|
|
chunk_secs = 3
|
|
overlap_secs = 0.5
|
|
|
|
plan = plan_chunks(total_samples, sample_rate, chunk_secs, overlap_secs)
|
|
|
|
self.assertEqual(plan.total_samples, total_samples)
|
|
self.assertEqual(plan.sample_rate, sample_rate)
|
|
self.assertEqual(plan.chunk_samples, 132300) # 3s @ 44.1k
|
|
self.assertEqual(plan.overlap_samples, 22050) # 0.5s @ 44.1k
|
|
self.assertGreater(len(plan.chunks), 0)
|
|
|
|
def test_plan_chunks_exact_multiple(self):
|
|
"""Chunk plan when total duration is exact multiple of chunk size."""
|
|
total_samples = 440000 # Exactly 10s at 40k Hz
|
|
sample_rate = 40000
|
|
chunk_secs = 2
|
|
overlap_secs = 0.2
|
|
|
|
plan = plan_chunks(total_samples, sample_rate, chunk_secs, overlap_secs)
|
|
|
|
# Should have 5+ chunks to cover 10s with 2s chunks
|
|
self.assertGreaterEqual(len(plan.chunks), 5)
|
|
# Last chunk should end at or near total_samples
|
|
self.assertLessEqual(plan.chunks[-1][1], total_samples + 1)
|
|
|
|
def test_plan_chunks_short_audio(self):
|
|
"""Chunk plan for audio shorter than chunk size."""
|
|
total_samples = 22050 # 0.5 seconds at 44.1 kHz
|
|
sample_rate = 44100
|
|
chunk_secs = 1
|
|
overlap_secs = 0.1
|
|
|
|
plan = plan_chunks(total_samples, sample_rate, chunk_secs, overlap_secs)
|
|
|
|
# Should have at least 1 chunk
|
|
self.assertGreaterEqual(len(plan.chunks), 1)
|
|
# Chunk should cover the full audio
|
|
self.assertGreaterEqual(plan.chunks[0][1], total_samples)
|
|
|
|
def test_plan_chunks_overlap_consistency(self):
|
|
"""Verify overlap windows are consistent across chunks."""
|
|
total_samples = 882000 # 20 seconds at 44.1 kHz
|
|
sample_rate = 44100
|
|
chunk_secs = 3
|
|
overlap_secs = 0.5
|
|
|
|
plan = plan_chunks(total_samples, sample_rate, chunk_secs, overlap_secs)
|
|
|
|
# Each consecutive pair should have overlap
|
|
for i in range(len(plan.chunks) - 1):
|
|
curr_end = plan.chunks[i][1]
|
|
next_start = plan.chunks[i + 1][0]
|
|
# Should have overlap (next_start < curr_end)
|
|
self.assertLess(next_start, curr_end)
|
|
# Overlap should be approximately overlap_samples
|
|
overlap_actual = curr_end - next_start
|
|
# Allow some tolerance
|
|
self.assertLess(abs(overlap_actual - plan.overlap_samples), 2)
|
|
|
|
|
|
class TestChunkActivationPolicy(unittest.TestCase):
|
|
"""Test should_chunk activation logic."""
|
|
|
|
def test_should_chunk_auto_below_threshold(self):
|
|
"""Auto mode: short track should not chunk."""
|
|
duration = 300 # 5 minutes
|
|
threshold = 480 # 8 minutes
|
|
result = should_chunk(duration, "auto", threshold)
|
|
self.assertFalse(result)
|
|
|
|
def test_should_chunk_auto_above_threshold(self):
|
|
"""Auto mode: long track should chunk."""
|
|
duration = 600 # 10 minutes
|
|
threshold = 480 # 8 minutes
|
|
result = should_chunk(duration, "auto", threshold)
|
|
self.assertTrue(result)
|
|
|
|
def test_should_chunk_always(self):
|
|
"""Always mode: always chunk regardless of duration."""
|
|
result = should_chunk(60, "always", 480)
|
|
self.assertTrue(result)
|
|
|
|
def test_should_chunk_off(self):
|
|
"""Off mode: never chunk regardless of duration."""
|
|
result = should_chunk(600, "off", 480)
|
|
self.assertFalse(result)
|
|
|
|
def test_should_chunk_invalid_mode_defaults_to_auto(self):
|
|
"""Invalid mode should default to auto behavior."""
|
|
result = should_chunk(600, "invalid", 480)
|
|
# Should treat as auto and return True for long track
|
|
self.assertTrue(result)
|
|
|
|
|
|
class TestExtractChunk(unittest.TestCase):
|
|
"""Test time-domain chunk extraction."""
|
|
|
|
def test_extract_chunk_within_bounds(self):
|
|
"""Extract a chunk from the middle of audio."""
|
|
audio = np.random.randn(2, 44100) # 1 second stereo
|
|
chunk = extract_chunk(audio, 11025, 22050) # 0.25s to 0.5s
|
|
|
|
self.assertEqual(chunk.shape[0], 2)
|
|
# Chunk size should be approximately end - start
|
|
self.assertEqual(chunk.shape[1], 11025)
|
|
|
|
def test_extract_chunk_start_boundary(self):
|
|
"""Extract from the start of audio."""
|
|
audio = np.random.randn(2, 44100)
|
|
chunk = extract_chunk(audio, 0, 22050)
|
|
|
|
self.assertEqual(chunk.shape[0], 2)
|
|
self.assertGreaterEqual(chunk.shape[1], 22050)
|
|
|
|
def test_extract_chunk_end_boundary(self):
|
|
"""Extract from the end of audio (should pad)."""
|
|
audio = np.random.randn(2, 44100)
|
|
chunk = extract_chunk(audio, 40000, 50000)
|
|
|
|
self.assertEqual(chunk.shape[0], 2)
|
|
# Should have requested size or be padded
|
|
self.assertGreaterEqual(chunk.shape[1], 10000)
|
|
|
|
def test_extract_chunk_preserves_values(self):
|
|
"""Verify extracted chunk contains correct audio data."""
|
|
audio = np.arange(44100, dtype=np.float32).reshape(1, 44100)
|
|
chunk = extract_chunk(audio, 1000, 2000)
|
|
|
|
# Non-padded portion should match original
|
|
self.assertEqual(chunk[0, 0], 1000)
|
|
|
|
|
|
class TestOverlapAddReconstruction(unittest.TestCase):
|
|
"""Test trapezoidal OLA reconstruction."""
|
|
|
|
def test_reconstruct_single_chunk(self):
|
|
"""Reconstruct from a single chunk (no overlap)."""
|
|
plan = plan_chunks(44100, 44100, 10, 0.5)
|
|
chunk_outputs = []
|
|
for start, end in plan.chunks:
|
|
size = end - start
|
|
chunk_outputs.append(
|
|
{"stem1": np.random.randn(2, size), "stem2": np.random.randn(2, size)}
|
|
)
|
|
|
|
result = overlap_add_reconstruct(chunk_outputs, plan, ["stem1", "stem2"])
|
|
|
|
self.assertIn("stem1", result)
|
|
self.assertIn("stem2", result)
|
|
self.assertEqual(result["stem1"].shape[0], 2)
|
|
self.assertGreaterEqual(result["stem1"].shape[1], 44100)
|
|
|
|
def test_reconstruct_multiple_chunks(self):
|
|
"""Reconstruct from multiple overlapping chunks."""
|
|
total_samples = 441000 # 10 seconds at 44.1 kHz
|
|
plan = plan_chunks(total_samples, 44100, 3, 0.5)
|
|
|
|
# Create mock chunk outputs
|
|
chunk_outputs = []
|
|
for start, end in plan.chunks:
|
|
size = end - start
|
|
chunk_outputs.append({
|
|
"stem1": np.random.randn(2, size),
|
|
"stem2": np.random.randn(2, size),
|
|
})
|
|
|
|
result = overlap_add_reconstruct(chunk_outputs, plan, ["stem1", "stem2"])
|
|
|
|
# Reconstructed audio should be approximately full length
|
|
self.assertEqual(result["stem1"].shape[0], 2)
|
|
self.assertGreaterEqual(result["stem1"].shape[1], total_samples - 1000)
|
|
self.assertLessEqual(result["stem1"].shape[1], total_samples + 1000)
|
|
|
|
def test_reconstruct_overlap_add_amplitude(self):
|
|
"""Verify OLA crossfade doesn't cause amplitude imbalance."""
|
|
# Create a simple constant-value audio to verify OLA amplitude
|
|
plan = plan_chunks(88200, 44100, 1, 0.2) # 2s @ 44.1k, 1s chunks, 0.2s overlap
|
|
|
|
# Create constant-value chunks (should sum to ~1.0 in overlap regions)
|
|
chunk_outputs = []
|
|
for start, end in plan.chunks:
|
|
size = end - start
|
|
chunk_outputs.append({"test": np.ones((2, size), dtype=np.float32)})
|
|
|
|
result = overlap_add_reconstruct(chunk_outputs, plan, ["test"])
|
|
|
|
# In non-overlapping regions, amplitude should be ~1.0
|
|
# In overlapping regions, crossfade should keep amplitude at 1.0
|
|
reconstructed = result["test"]
|
|
# Check a sample far from edges (no pad effects)
|
|
mid_sample = reconstructed.shape[1] // 2
|
|
self.assertAlmostEqual(float(reconstructed[0, mid_sample]), 1.0, places=1)
|
|
|
|
def test_reconstruct_preserves_stem_count(self):
|
|
"""Verify all stems are reconstructed."""
|
|
plan = plan_chunks(44100, 44100, 2, 0.2)
|
|
stems = ["vocals", "drums", "bass", "other"]
|
|
|
|
chunk_outputs = []
|
|
for start, end in plan.chunks:
|
|
size = end - start
|
|
chunk_outputs.append({
|
|
stem: np.random.randn(2, size) for stem in stems
|
|
})
|
|
|
|
result = overlap_add_reconstruct(chunk_outputs, plan, stems)
|
|
|
|
for stem in stems:
|
|
self.assertIn(stem, result)
|
|
|
|
|
|
class TestIntegrationChunking(unittest.TestCase):
|
|
"""Integration tests for chunking end-to-end."""
|
|
|
|
def test_full_chunking_pipeline(self):
|
|
"""Test complete chunking pipeline: plan -> extract -> reconstruct."""
|
|
# Setup
|
|
total_samples = 441000 # 10 seconds at 44.1 kHz
|
|
sample_rate = 44100
|
|
audio = np.random.randn(2, total_samples)
|
|
|
|
# Plan chunks
|
|
plan = plan_chunks(total_samples, sample_rate, 3, 0.5)
|
|
self.assertGreater(len(plan.chunks), 1, "Should have multiple chunks for 10s audio")
|
|
|
|
# Extract and process each chunk
|
|
chunk_outputs = []
|
|
for start, end in plan.chunks:
|
|
chunk = extract_chunk(audio, start, end)
|
|
# Simulate processing (e.g., mock separation)
|
|
processed = {"stem1": chunk.copy(), "stem2": chunk.copy()}
|
|
chunk_outputs.append(processed)
|
|
|
|
# Reconstruct
|
|
result = overlap_add_reconstruct(chunk_outputs, plan, ["stem1", "stem2"])
|
|
|
|
# Verify
|
|
self.assertEqual(len(result), 2)
|
|
for stem_name in ["stem1", "stem2"]:
|
|
self.assertIn(stem_name, result)
|
|
# Reconstructed should be roughly same length as input
|
|
self.assertEqual(result[stem_name].shape[0], 2)
|
|
self.assertGreater(result[stem_name].shape[1], total_samples - 2000)
|
|
|
|
def test_chunking_decision_tree(self):
|
|
"""Test the decision logic for when to chunk."""
|
|
short_track = 200 # 3 min 20 sec
|
|
long_track = 600 # 10 minutes
|
|
threshold = 480 # 8 minutes
|
|
|
|
# Short track: no chunking in auto mode
|
|
self.assertFalse(should_chunk(short_track, "auto", threshold))
|
|
|
|
# Long track: always chunk if mode is always
|
|
self.assertTrue(should_chunk(long_track, "always", threshold))
|
|
|
|
# Long track with auto: should chunk
|
|
self.assertTrue(should_chunk(long_track, "auto", threshold))
|
|
|
|
# Disable with off mode
|
|
self.assertFalse(should_chunk(long_track, "off", threshold))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|