Download scripts/calibrate_source_guard.py from Neptune9728/sound-insight-api: direct link, hf CLI and curl.
- Browser
- Download file 5.8 kB
-
https://huggingface.co/spaces/Neptune9728/sound-insight-api/resolve/main/scripts/calibrate_source_guard.py
- Command line
-
hf download hf://spaces/Neptune9728/sound-insight-api/scripts/calibrate_source_guard.py
-
curl -L -o calibrate_source_guard.py https://huggingface.co/spaces/Neptune9728/sound-insight-api/resolve/main/scripts/calibrate_source_guard.py
5.8 kB
| #!/usr/bin/env python3 | |
| """Collect EchoCare source evidence and suggest balanced guard thresholds. | |
| Dataset layout: | |
| validation/ | |
| baby/*.wav | |
| cat/*.wav | |
| dog/*.wav | |
| other/*.wav | |
| silence/*.wav | |
| The script calls /predict with guard_mode=off so it can read YAMNet source scores | |
| without changing the user's selected model. It then sweeps thresholds and writes a | |
| JSON fragment that can replace `source_thresholds.balanced` in guard_config.json. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import itertools | |
| import json | |
| from pathlib import Path | |
| import requests | |
| AUDIO_SUFFIXES = {".wav", ".mp3", ".m4a", ".aac", ".ogg", ".webm", ".mp4"} | |
| TARGETS = ("baby", "cat", "dog") | |
| def collect(api_url: str, dataset: Path, model_revision: str) -> list[dict]: | |
| rows: list[dict] = [] | |
| for expected_dir in sorted(path for path in dataset.iterdir() if path.is_dir()): | |
| expected = expected_dir.name.lower() | |
| for path in sorted(expected_dir.rglob("*")): | |
| if path.suffix.lower() not in AUDIO_SUFFIXES: | |
| continue | |
| selected = expected if expected in TARGETS else "cat" | |
| with path.open("rb") as handle: | |
| response = requests.post( | |
| f"{api_url.rstrip('/')}/predict", | |
| data={ | |
| "model": selected, | |
| "model_version": model_revision, | |
| "guard_mode": "off", | |
| }, | |
| files={"audio": (path.name, handle, "application/octet-stream")}, | |
| timeout=120, | |
| ) | |
| payload = response.json() | |
| if response.status_code >= 400: | |
| raise RuntimeError(f"{path}: {response.status_code} {payload}") | |
| scores = {item["label"]: float(item["score"]) for item in payload.get("source_scores", [])} | |
| source_guard = (payload.get("quality") or {}).get("source_guard") or {} | |
| rows.append( | |
| { | |
| "file": str(path), | |
| "expected": expected, | |
| "quality_passed": bool((payload.get("quality") or {}).get("passed")), | |
| "scores": scores, | |
| "votes": source_guard.get("window_vote_ratios") or {}, | |
| "top_frames": { | |
| selected: float(source_guard.get("selected_top_frame_score") or 0.0) | |
| }, | |
| } | |
| ) | |
| print(f"Collected {expected:7s} {path.name}") | |
| return rows | |
| def accepts(row: dict, selected: str, cfg: dict) -> bool: | |
| if not row["quality_passed"]: | |
| return False | |
| scores = row["scores"] | |
| votes = row["votes"] | |
| selected_score = float(scores.get(selected, 0.0)) | |
| selected_vote = float(votes.get(selected, 0.0)) | |
| if selected_score < cfg["min_score"] or selected_vote < cfg["min_vote"]: | |
| return False | |
| rivals = [(name, float(scores.get(name, 0.0))) for name in TARGETS if name != selected] | |
| _rival_name, rival_score = max(rivals, key=lambda item: item[1]) | |
| if rival_score >= cfg["mismatch_score"] and rival_score - selected_score >= cfg["mismatch_margin"]: | |
| return False | |
| other_score = float(scores.get("other", 0.0)) | |
| if other_score >= max(0.16, selected_score + 0.04) and float(votes.get("other", 0.0)) >= 0.45: | |
| return False | |
| return True | |
| def evaluate(rows: list[dict], cfg: dict) -> dict: | |
| recalls = [] | |
| false_accepts = [] | |
| per_target = {} | |
| for selected in TARGETS: | |
| positives = [row for row in rows if row["expected"] == selected] | |
| negatives = [row for row in rows if row["expected"] != selected] | |
| tp = sum(accepts(row, selected, cfg) for row in positives) | |
| fp = sum(accepts(row, selected, cfg) for row in negatives) | |
| recall = tp / max(1, len(positives)) | |
| far = fp / max(1, len(negatives)) | |
| recalls.append(recall) | |
| false_accepts.append(far) | |
| per_target[selected] = {"recall": recall, "false_accept_rate": far, "positive_count": len(positives), "negative_count": len(negatives)} | |
| macro_recall = sum(recalls) / len(recalls) | |
| macro_far = sum(false_accepts) / len(false_accepts) | |
| return {"macro_recall": macro_recall, "macro_false_accept_rate": macro_far, "per_target": per_target} | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("dataset", type=Path) | |
| parser.add_argument("--api-url", required=True) | |
| parser.add_argument("--model-revision", default="bundled") | |
| parser.add_argument("--out", type=Path, default=Path("guard_calibration_result.json")) | |
| args = parser.parse_args() | |
| rows = collect(args.api_url, args.dataset, args.model_revision) | |
| candidates = [] | |
| for values in itertools.product( | |
| [0.045, 0.055, 0.065, 0.075, 0.09, 0.11], | |
| [0.30, 0.35, 0.40, 0.45, 0.50, 0.55], | |
| [0.08, 0.10, 0.12, 0.15], | |
| [0.02, 0.03, 0.04, 0.06], | |
| ): | |
| cfg = dict(zip(("min_score", "min_vote", "mismatch_score", "mismatch_margin"), values)) | |
| metrics = evaluate(rows, cfg) | |
| # False accepts are more damaging than asking the user to record again. | |
| score = metrics["macro_recall"] - 2.5 * metrics["macro_false_accept_rate"] | |
| candidates.append((score, cfg, metrics)) | |
| candidates.sort(key=lambda item: item[0], reverse=True) | |
| best_score, best_cfg, best_metrics = candidates[0] | |
| result = { | |
| "balanced": best_cfg, | |
| "metrics": best_metrics, | |
| "objective": best_score, | |
| "sample_count": len(rows), | |
| "notes": "Validate on separate phone recordings before production deployment.", | |
| } | |
| args.out.write_text(json.dumps(result, indent=2), encoding="utf-8") | |
| print(json.dumps(result, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |