File size: 8,487 Bytes
58a923b | 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 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 | # backend/ml_models/validate_models.py
"""
Model validation script to test inference pipeline.
Run this before deploying to production.
"""
import os
import sys
import torch
import numpy as np
import soundfile as sf
from pathlib import Path
# Add backend to path
BACKEND_DIR = Path(__file__).parent.parent
sys.path.insert(0, str(BACKEND_DIR))
from ml_models import TranscriptionEngine, WEIGHTS_DIR
def generate_test_audio(duration=5.0, sr=16000, frequency=440.0):
"""Generate test sine wave."""
t = np.linspace(0, duration, int(sr * duration))
audio = 0.5 * np.sin(2 * np.pi * frequency * t)
return audio.astype(np.float32)
def generate_silence(duration=5.0, sr=16000):
"""Generate silence."""
return np.zeros(int(sr * duration), dtype=np.float32)
def validate_bass_model(engine, test_dir):
"""Validate bass model."""
print("\n" + "=" * 60)
print("Testing BASS Model")
print("=" * 60)
# Test 1: Silence (should produce 0 or very few notes)
print("\nTest 1: Silence")
silence_path = test_dir / "silence.wav"
sf.write(silence_path, generate_silence(), 16000)
try:
result = engine.transcribe_bass(str(silence_path))
notes = result[0]
metadata = result[1]
print(f" Notes detected: {len(notes)}")
print(f" Metadata: {metadata}")
if len(notes) > 20:
print(f" β WARNING: Too many false positives in silence!")
return False
else:
print(f" β PASS: Acceptable false positive rate")
except Exception as e:
print(f" β FAIL: {e}")
import traceback
traceback.print_exc()
return False
# Test 2: Pure tone outside bass range (should be empty)
print("\nTest 2: High frequency (A440 - out of bass range)")
tone_path = test_dir / "tone_high.wav"
sf.write(tone_path, generate_test_audio(frequency=440), 16000)
try:
result = engine.transcribe_bass(str(tone_path))
notes = result[0]
print(f" Notes detected: {len(notes)}")
if len(notes) > 10:
print(f" β WARNING: Detecting out-of-range frequencies!")
return False
else:
print(f" β PASS: Correctly ignoring out-of-range")
except Exception as e:
print(f" β FAIL: {e}")
return False
# Test 3: Bass frequency (E1 = 41.2 Hz)
print("\nTest 3: Bass frequency (E1 = 41.2 Hz)")
bass_path = test_dir / "tone_bass.wav"
sf.write(bass_path, generate_test_audio(frequency=41.2), 16000)
try:
result = engine.transcribe_bass(str(bass_path))
notes = result[0]
print(f" Notes detected: {len(notes)}")
if len(notes) == 0:
print(f" β WARNING: Not detecting bass frequencies!")
return False
elif len(notes) > 5:
print(f" β PASS: Detecting bass (note: may split sustained tone)")
else:
print(f" β PASS: Detecting bass")
except Exception as e:
print(f" β FAIL: {e}")
return False
print("\nβ Bass model validation PASSED")
return True
def validate_vocal_model(engine, test_dir):
"""Validate vocal model."""
print("\n" + "=" * 60)
print("Testing VOCAL Model")
print("=" * 60)
# Test 1: Silence
print("\nTest 1: Silence")
silence_path = test_dir / "silence.wav"
try:
result = engine.transcribe_vocals(str(silence_path))
notes = result[0]
metadata = result[1]
print(f" Notes detected: {len(notes)}")
print(f" Voiced ratio: {metadata.get('voiced_ratio', 0):.3f}")
if metadata.get('voiced_ratio', 0) > 0.3:
print(f" β WARNING: High voiced ratio in silence!")
return False
else:
print(f" β PASS: Low false positive rate")
except Exception as e:
print(f" β FAIL: {e}")
return False
# Test 2: Vocal range frequency
print("\nTest 2: Vocal frequency (C4 = 261.6 Hz)")
vocal_path = test_dir / "tone_vocal.wav"
sf.write(vocal_path, generate_test_audio(frequency=261.6), 16000)
try:
result = engine.transcribe_vocals(str(vocal_path))
notes = result[0]
metadata = result[1]
print(f" Notes detected: {len(notes)}")
print(f" Voiced ratio: {metadata.get('voiced_ratio', 0):.3f}")
if len(notes) == 0:
print(f" β WARNING: Not detecting vocal frequencies!")
return False
else:
print(f" β PASS: Detecting vocal frequencies")
except Exception as e:
print(f" β FAIL: {e}")
return False
print("\nβ Vocal model validation PASSED")
return True
def validate_drum_model(engine, test_dir):
"""Validate drum model."""
print("\n" + "=" * 60)
print("Testing DRUM Model")
print("=" * 60)
# Test 1: Silence
print("\nTest 1: Silence")
silence_path = test_dir / "silence.wav"
try:
result = engine.transcribe_drums(str(silence_path))
hits = result[0]
metadata = result[1]
print(f" Hits detected: {len(hits)}")
print(f" Hits per class: {metadata.get('hits_per_class', {})}")
if len(hits) > 50:
print(f" β WARNING: Too many false positives in silence!")
return False
else:
print(f" β PASS: Low false positive rate")
except Exception as e:
print(f" β FAIL: {e}")
return False
# Test 2: Impulse (should detect as drum hit)
print("\nTest 2: Impulse (synthetic drum)")
impulse_path = test_dir / "impulse.wav"
# Create impulse train
impulse = np.zeros(16000 * 3)
for i in range(0, len(impulse), 16000): # 1 Hz impulses
impulse[i:i + 100] = 0.8 * np.random.randn(100) # Noisy impulse
sf.write(impulse_path, impulse.astype(np.float32), 16000)
try:
result = engine.transcribe_drums(str(impulse_path))
hits = result[0]
print(f" Hits detected: {len(hits)}")
if len(hits) == 0:
print(f" β WARNING: Not detecting impulses!")
return False
else:
print(f" β PASS: Detecting impulses")
except Exception as e:
print(f" β FAIL: {e}")
return False
print("\nβ Drum model validation PASSED")
return True
def main():
"""Run all validation tests."""
print("=" * 60)
print("MODEL VALIDATION SUITE")
print("=" * 60)
# Setup
if torch.cuda.is_available():
device = 'cuda'
elif torch.backends.mps.is_available():
device = 'mps'
else:
device = 'cpu'
print(f"\nDevice: {device}")
print(f"Weights directory: {WEIGHTS_DIR}")
# Create test directory
test_dir = Path("test_audio")
test_dir.mkdir(exist_ok=True)
# Initialize engine
try:
engine = TranscriptionEngine(str(WEIGHTS_DIR), device=device)
except Exception as e:
print(f"\nβ CRITICAL: Could not initialize TranscriptionEngine")
print(f"Error: {e}")
import traceback
traceback.print_exc()
return False
# Run tests
results = {}
if engine.is_model_available('bass'):
results['bass'] = validate_bass_model(engine, test_dir)
else:
print("\nβ Bass model not available, skipping")
results['bass'] = None
if engine.is_model_available('vocals'):
results['vocals'] = validate_vocal_model(engine, test_dir)
else:
print("\nβ Vocal model not available, skipping")
results['vocals'] = None
if engine.is_model_available('drums'):
results['drums'] = validate_drum_model(engine, test_dir)
else:
print("\nβ Drum model not available, skipping")
results['drums'] = None
# Summary
print("\n" + "=" * 60)
print("VALIDATION SUMMARY")
print("=" * 60)
for model, result in results.items():
if result is None:
status = "SKIPPED"
elif result:
status = "β PASSED"
else:
status = "β FAILED"
print(f" {model}: {status}")
all_passed = all(r for r in results.values() if r is not None)
if all_passed:
print("\nβ ALL TESTS PASSED")
return True
else:
print("\nβ SOME TESTS FAILED")
return False
if __name__ == "__main__":
success = main()
sys.exit(0 if success else 1) |