Spaces:
Sleeping
Sleeping
File size: 5,564 Bytes
ea2601f | 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 | #!/usr/bin/env python3
"""TotTalk Cry Eval — real-time multi-model baby cry classifier."""
from __future__ import annotations
import json
import queue
from pathlib import Path
import click
import numpy as np
import sounddevice as sd
from rich.console import Console
from rich.progress import Progress, SpinnerColumn, TextColumn
from audio.capture import FileCapture, MicCapture
from audio.preprocess import SAMPLE_RATE, compute_rms, is_silent, normalize_audio
from display.table import CryDisplay
from models.ensemble import EnsembleClassifier
console = Console(stderr=True)
def _print_audio_devices() -> None:
"""Print available audio devices for reference."""
console.print("\n[bold]Audio devices:[/bold]")
try:
devices = sd.query_devices()
default_in = sd.default.device[0]
for i, d in enumerate(devices):
marker = " ← default input" if i == default_in else ""
if d["max_input_channels"] > 0:
console.print(f" [{i}] {d['name']} (in:{d['max_input_channels']}){marker}")
except Exception as exc:
console.print(f" [red]Could not query devices: {exc}[/red]")
def _load_models(ensemble: EnsembleClassifier) -> None:
"""Load all models with a rich progress spinner."""
console.print()
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console,
) as progress:
task = progress.add_task("Loading models…", total=None)
results = ensemble.load_all()
progress.update(task, description="Models loaded.")
for name, error in results.items():
if error:
console.print(f" [red]✗ {name}: {error}[/red]")
else:
console.print(f" [green]✓ {name}[/green]")
console.print()
@click.command()
@click.option(
"--file", "audio_file", default=None, type=click.Path(exists=True),
help="Path to a WAV/FLAC/MP3 file (loops in sliding windows instead of mic).",
)
@click.option(
"--models", "model_names", default=None,
help="Comma-separated subset of models to run: svc,hubert,kibalama,yamnet",
)
@click.option(
"--no-yamnet-gate", is_flag=True, default=False,
help="Disable YAMNet gating (always run reason classifiers).",
)
@click.option(
"--save-log", default=None, type=click.Path(),
help="Append JSONL predictions to this file.",
)
@click.option(
"--sensitivity", default=None, type=float,
help="Silence RMS threshold override (default 0.001). Lower = more sensitive.",
)
def cli(
audio_file: str | None,
model_names: str | None,
no_yamnet_gate: bool,
save_log: str | None,
sensitivity: float | None,
) -> None:
"""🍼 TotTalk Cry Eval — real-time multi-model baby cry classifier."""
console.print("[bold cyan]🍼 TotTalk Cry Eval[/bold cyan]")
# Override silence threshold if requested
if sensitivity is not None:
import audio.preprocess as _ap
_ap.SILENCE_RMS_THRESHOLD = sensitivity
console.print(f"[dim]Silence threshold set to {sensitivity}[/dim]")
# Parse model list
selected = model_names.split(",") if model_names else None
# Init ensemble
ensemble = EnsembleClassifier(
model_names=selected,
use_yamnet_gate=not no_yamnet_gate,
)
# Print device info
if audio_file is None:
_print_audio_devices()
# Load models
_load_models(ensemble)
# Log file handle
log_fh = None
if save_log:
log_fh = open(save_log, "a") # noqa: SIM115
# Set up audio source
if audio_file:
source_label = f"file: {Path(audio_file).name}"
capture = FileCapture(audio_file)
else:
source_label = "mic"
capture = MicCapture()
# Display
display = CryDisplay()
try:
capture.start()
display.start()
console.print(f"[dim]Listening ({source_label})… Press Ctrl+C to stop.[/dim]\n")
while True:
try:
window: np.ndarray = capture.window_queue.get(timeout=3.0)
except queue.Empty:
continue
rms = compute_rms(window)
silent = is_silent(window)
if silent:
display.update([], rms, source_label=source_label, is_silent=True)
continue
# Peak-normalize so quiet phone playback reaches model-friendly levels
window = normalize_audio(window)
predictions = ensemble.predict_all(window, SAMPLE_RATE)
display.update(predictions, rms, source_label=source_label)
# Optional JSONL log
if log_fh is not None:
record = {
"window": display._window_count,
"rms": rms,
"predictions": [
{
"model": p.model_name,
"label": p.label,
"confidence": p.confidence,
"latency_ms": p.latency_ms,
"error": p.error,
}
for p in predictions
],
}
log_fh.write(json.dumps(record) + "\n")
log_fh.flush()
except KeyboardInterrupt:
console.print("\n[yellow]Stopped.[/yellow]")
finally:
capture.stop()
display.stop()
if log_fh is not None:
log_fh.close()
if __name__ == "__main__":
cli()
|