Instructions to use Neptune9728/sound-insight-models with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Keras
How to use Neptune9728/sound-insight-models with Keras:
# !pip install -U keras tensorflow huggingface_hub # Keras needs TensorFlow installed to read "hf://" paths, so the tensorflow backend is selected here; # "jax" and "torch" also work for computation once TensorFlow is installed. import os os.environ["KERAS_BACKEND"] = "tensorflow" import keras model = keras.saving.load_model("hf://Neptune9728/sound-insight-models") - Notebooks
- Google Colab
- Kaggle
Sound Insight models 2026-07-01
Browse files- .gitattributes +1 -0
- .gitignore +5 -0
- Dockerfile +14 -0
- README.md +38 -0
- app.py +725 -0
- models/baby/classifier.weights.h5 +2 -2
- models/baby/labels.json +2 -2
- models/cat/final_classifier.keras +3 -0
- models/cat/labels.json +2 -2
- models/dog/classifier.weights.h5 +2 -2
- models/dog/labels.json +4 -3
- requirements.txt +12 -0
- test_predict.py +19 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
models/cat/final_classifier.keras filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.pyc
|
| 3 |
+
.env
|
| 4 |
+
env/
|
| 5 |
+
.venv/
|
Dockerfile
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.10-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
RUN apt-get update && apt-get install -y --no-install-recommends ffmpeg libsndfile1 && rm -rf /var/lib/apt/lists/*
|
| 6 |
+
|
| 7 |
+
COPY requirements.txt /app/requirements.txt
|
| 8 |
+
RUN pip install --no-cache-dir --upgrade pip && pip install --no-cache-dir -r /app/requirements.txt
|
| 9 |
+
|
| 10 |
+
COPY . /app
|
| 11 |
+
|
| 12 |
+
EXPOSE 7860
|
| 13 |
+
|
| 14 |
+
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
|
README.md
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Sound Insight V3.2 API
|
| 3 |
+
emoji: 🎙️
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: purple
|
| 6 |
+
sdk: docker
|
| 7 |
+
app_port: 7860
|
| 8 |
+
pinned: false
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
# Sound Insight V3.2 API
|
| 12 |
+
|
| 13 |
+
Pipeline:
|
| 14 |
+
|
| 15 |
+
```text
|
| 16 |
+
audio quality check
|
| 17 |
+
→ YAMNet AudioSet rule guard
|
| 18 |
+
→ selected Baby/Cat/Dog match
|
| 19 |
+
→ selected state classifier
|
| 20 |
+
```
|
| 21 |
+
|
| 22 |
+
No separate Source Guard model is required.
|
| 23 |
+
|
| 24 |
+
Health:
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import csv
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import shutil
|
| 7 |
+
import tempfile
|
| 8 |
+
import threading
|
| 9 |
+
import time
|
| 10 |
+
import uuid
|
| 11 |
+
import zipfile
|
| 12 |
+
from datetime import datetime, timedelta, timezone
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from typing import Dict, List
|
| 15 |
+
|
| 16 |
+
os.environ.setdefault("TF_CPP_MIN_LOG_LEVEL", "2")
|
| 17 |
+
|
| 18 |
+
import librosa
|
| 19 |
+
import numpy as np
|
| 20 |
+
import tensorflow as tf
|
| 21 |
+
import tensorflow_hub as hub
|
| 22 |
+
from fastapi import FastAPI, File, Form, Header, HTTPException, UploadFile
|
| 23 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 24 |
+
from fastapi.responses import FileResponse
|
| 25 |
+
from pydantic import BaseModel
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
BASE_DIR = Path(__file__).resolve().parent
|
| 29 |
+
MODELS_DIR = BASE_DIR / "models"
|
| 30 |
+
TRAINING_UPLOADS_DIR = BASE_DIR / "training_uploads"
|
| 31 |
+
TRAINING_UPLOADS_DIR.mkdir(parents=True, exist_ok=True)
|
| 32 |
+
|
| 33 |
+
MAX_AUDIO_SECONDS = 60.0
|
| 34 |
+
TRAINING_RETENTION_HOURS = 24
|
| 35 |
+
ADMIN_TOKEN = os.getenv("TRAINING_ADMIN_TOKEN", "change-me-before-public-use")
|
| 36 |
+
|
| 37 |
+
STATE_MODEL_CONFIG = {
|
| 38 |
+
"cat": {"dir": MODELS_DIR / "cat", "display_name": "Cat Model"},
|
| 39 |
+
"baby": {"dir": MODELS_DIR / "baby", "display_name": "Baby Model"},
|
| 40 |
+
"dog": {"dir": MODELS_DIR / "dog", "display_name": "Dog Model"},
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
TRAINING_TAGS = {
|
| 44 |
+
"baby": ["Hungry", "Sleepy", "Need_Burping", "Discomfort"],
|
| 45 |
+
"cat": ["Angry", "Hungry", "Mating", "Paining", "Relaxed"],
|
| 46 |
+
"dog": [
|
| 47 |
+
"Aggression",
|
| 48 |
+
"Sad_Distress",
|
| 49 |
+
"PainLike",
|
| 50 |
+
"Happy_Excitement",
|
| 51 |
+
"Hungry_Attention",
|
| 52 |
+
"Kennel_CoughLike",
|
| 53 |
+
"Reverse_SneezeLike",
|
| 54 |
+
"Tracheal_CollapseLike",
|
| 55 |
+
],
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
DISPLAY_LABELS = {
|
| 59 |
+
"Paining": "Pain / Discomfort",
|
| 60 |
+
"Need_Burping": "Need Burping",
|
| 61 |
+
"Aggression": "Aggression",
|
| 62 |
+
"Sad_Distress": "Sad / Distress",
|
| 63 |
+
"PainLike": "Pain-like",
|
| 64 |
+
"Happy_Excitement": "Happy / Excitement",
|
| 65 |
+
"Hungry_Attention": "Hungry / Attention",
|
| 66 |
+
"Kennel_CoughLike": "Kennel cough-like",
|
| 67 |
+
"Reverse_SneezeLike": "Reverse sneeze-like",
|
| 68 |
+
"Tracheal_CollapseLike": "Tracheal collapse-like",
|
| 69 |
+
"Aggressive_Alert": "Aggressive / Alert",
|
| 70 |
+
"Calm_Other": "Calm / Other",
|
| 71 |
+
"Distress_PainLike": "Distress / Pain-like",
|
| 72 |
+
"Happy_Excited": "Happy / Excited",
|
| 73 |
+
"Uncertain_Dog_Vocalization": "Uncertain Dog Vocalization",
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
# YAMNet AudioSet rule groups. Names must match class_map.csv display names.
|
| 77 |
+
SOURCE_GROUPS = {
|
| 78 |
+
"baby": [
|
| 79 |
+
"Baby cry, infant cry",
|
| 80 |
+
"Crying, sobbing",
|
| 81 |
+
"Whimper",
|
| 82 |
+
],
|
| 83 |
+
"cat": [
|
| 84 |
+
"Cat",
|
| 85 |
+
"Meow",
|
| 86 |
+
"Purr",
|
| 87 |
+
"Hiss",
|
| 88 |
+
"Caterwaul",
|
| 89 |
+
],
|
| 90 |
+
"dog": [
|
| 91 |
+
"Dog",
|
| 92 |
+
"Bark",
|
| 93 |
+
"Yip",
|
| 94 |
+
"Howl",
|
| 95 |
+
"Growling",
|
| 96 |
+
"Whimper",
|
| 97 |
+
"Bow-wow",
|
| 98 |
+
],
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
OTHER_HINTS = [
|
| 102 |
+
"Speech",
|
| 103 |
+
"Conversation",
|
| 104 |
+
"Narration, monologue",
|
| 105 |
+
"Music",
|
| 106 |
+
"Vehicle",
|
| 107 |
+
"Car",
|
| 108 |
+
"Bus",
|
| 109 |
+
"Train",
|
| 110 |
+
"Aircraft",
|
| 111 |
+
"Rain",
|
| 112 |
+
"Water",
|
| 113 |
+
"Silence",
|
| 114 |
+
"Inside, small room",
|
| 115 |
+
"Keyboard (musical)",
|
| 116 |
+
"Typing",
|
| 117 |
+
"Vacuum cleaner",
|
| 118 |
+
"Air conditioning",
|
| 119 |
+
"Television",
|
| 120 |
+
"Radio",
|
| 121 |
+
]
|
| 122 |
+
|
| 123 |
+
# These are deliberately permissive for a demo. Tune from debug logs.
|
| 124 |
+
MIN_SELECTED_SOURCE_SCORE = 0.08
|
| 125 |
+
MIN_SELECTED_OVER_OTHER = -0.02
|
| 126 |
+
MIN_SELECTED_MARGIN = 0.01
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class ProbabilityItem(BaseModel):
|
| 130 |
+
label: str
|
| 131 |
+
display_label: str
|
| 132 |
+
probability: float
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
class SourceScoreItem(BaseModel):
|
| 136 |
+
label: str
|
| 137 |
+
score: float
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class PredictResponse(BaseModel):
|
| 141 |
+
status: str
|
| 142 |
+
model: str
|
| 143 |
+
model_display_name: str | None = None
|
| 144 |
+
top_label: str | None = None
|
| 145 |
+
top_display_label: str | None = None
|
| 146 |
+
top_probability: float | None = None
|
| 147 |
+
probabilities: List[ProbabilityItem] = []
|
| 148 |
+
model_version: str | None = None
|
| 149 |
+
|
| 150 |
+
reason: str | None = None
|
| 151 |
+
message: str | None = None
|
| 152 |
+
detected_source: str | None = None
|
| 153 |
+
source_scores: List[SourceScoreItem] = []
|
| 154 |
+
yamnet_top_classes: List[SourceScoreItem] = []
|
| 155 |
+
quality: dict | None = None
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def now_utc() -> datetime:
|
| 159 |
+
return datetime.now(timezone.utc)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def display_label(label: str) -> str:
|
| 163 |
+
return DISPLAY_LABELS.get(label, label.replace("_", " "))
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def cleanup_expired_uploads() -> int:
|
| 167 |
+
cutoff = now_utc() - timedelta(hours=TRAINING_RETENTION_HOURS)
|
| 168 |
+
removed = 0
|
| 169 |
+
for meta_path in TRAINING_UPLOADS_DIR.rglob("*.json"):
|
| 170 |
+
try:
|
| 171 |
+
meta = json.loads(meta_path.read_text(encoding="utf-8"))
|
| 172 |
+
uploaded_at = datetime.fromisoformat(meta["uploaded_at"])
|
| 173 |
+
if uploaded_at.tzinfo is None:
|
| 174 |
+
uploaded_at = uploaded_at.replace(tzinfo=timezone.utc)
|
| 175 |
+
if uploaded_at >= cutoff:
|
| 176 |
+
continue
|
| 177 |
+
suffix = meta.get("audio_suffix", ".wav")
|
| 178 |
+
meta_path.with_suffix(suffix).unlink(missing_ok=True)
|
| 179 |
+
meta_path.unlink(missing_ok=True)
|
| 180 |
+
removed += 1
|
| 181 |
+
except Exception:
|
| 182 |
+
pass
|
| 183 |
+
return removed
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def cleanup_worker() -> None:
|
| 187 |
+
while True:
|
| 188 |
+
try:
|
| 189 |
+
cleanup_expired_uploads()
|
| 190 |
+
except Exception as exc:
|
| 191 |
+
print("Cleanup warning:", exc)
|
| 192 |
+
time.sleep(3600)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def find_labels_file(model_dir: Path) -> Path:
|
| 196 |
+
for candidate in [model_dir / "labels.json", *model_dir.glob("*labels*.json")]:
|
| 197 |
+
if candidate.exists():
|
| 198 |
+
return candidate
|
| 199 |
+
raise FileNotFoundError(f"No labels JSON found in {model_dir}")
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def find_weights_file(model_dir: Path) -> Path | None:
|
| 203 |
+
for candidate in [
|
| 204 |
+
model_dir / "classifier.weights.h5",
|
| 205 |
+
model_dir / "final_classifier.weights.h5",
|
| 206 |
+
*model_dir.glob("*.weights.h5"),
|
| 207 |
+
]:
|
| 208 |
+
if candidate.exists():
|
| 209 |
+
return candidate
|
| 210 |
+
return None
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def find_model_file(model_dir: Path) -> Path:
|
| 214 |
+
for candidate in [
|
| 215 |
+
model_dir / "classifier.keras",
|
| 216 |
+
model_dir / "final_classifier.keras",
|
| 217 |
+
*model_dir.glob("*.keras"),
|
| 218 |
+
]:
|
| 219 |
+
if candidate.exists():
|
| 220 |
+
return candidate
|
| 221 |
+
raise FileNotFoundError(f"No .keras model found in {model_dir}")
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def build_classifier(num_classes: int) -> tf.keras.Model:
|
| 225 |
+
model = tf.keras.Sequential(
|
| 226 |
+
[
|
| 227 |
+
tf.keras.layers.Input(shape=(2048,), name="yamnet_file_feature"),
|
| 228 |
+
tf.keras.layers.BatchNormalization(name="batch_normalization"),
|
| 229 |
+
tf.keras.layers.Dense(256, activation="relu", name="dense"),
|
| 230 |
+
tf.keras.layers.Dropout(0.35),
|
| 231 |
+
tf.keras.layers.Dense(128, activation="relu", name="dense_1"),
|
| 232 |
+
tf.keras.layers.Dropout(0.25),
|
| 233 |
+
tf.keras.layers.Dense(
|
| 234 |
+
num_classes,
|
| 235 |
+
activation="softmax",
|
| 236 |
+
name="state_probabilities",
|
| 237 |
+
),
|
| 238 |
+
],
|
| 239 |
+
name="sequential",
|
| 240 |
+
)
|
| 241 |
+
model(np.zeros((1, 2048), dtype=np.float32), training=False)
|
| 242 |
+
return model
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def extract_weights_from_keras_archive(
|
| 246 |
+
keras_archive: Path,
|
| 247 |
+
destination_dir: Path,
|
| 248 |
+
) -> Path:
|
| 249 |
+
with zipfile.ZipFile(keras_archive) as archive:
|
| 250 |
+
names = [
|
| 251 |
+
n for n in archive.namelist()
|
| 252 |
+
if n.endswith("model.weights.h5") or n.endswith(".weights.h5")
|
| 253 |
+
]
|
| 254 |
+
if not names:
|
| 255 |
+
raise ValueError("No weights found inside .keras archive")
|
| 256 |
+
output = destination_dir / "model.weights.h5"
|
| 257 |
+
with archive.open(names[0]) as source:
|
| 258 |
+
output.write_bytes(source.read())
|
| 259 |
+
return output
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def load_classifier(model_dir: Path, labels: list[str]) -> tf.keras.Model:
|
| 263 |
+
weights_file = find_weights_file(model_dir)
|
| 264 |
+
if weights_file is not None:
|
| 265 |
+
model = build_classifier(len(labels))
|
| 266 |
+
model.load_weights(weights_file)
|
| 267 |
+
return model
|
| 268 |
+
|
| 269 |
+
model_file = find_model_file(model_dir)
|
| 270 |
+
try:
|
| 271 |
+
model = tf.keras.models.load_model(model_file, compile=False)
|
| 272 |
+
if model.output_shape[-1] != len(labels):
|
| 273 |
+
raise ValueError("Model output count does not match labels")
|
| 274 |
+
return model
|
| 275 |
+
except Exception as exc:
|
| 276 |
+
print(f"Normal load failed for {model_file.name}: {exc}")
|
| 277 |
+
model = build_classifier(len(labels))
|
| 278 |
+
with tempfile.TemporaryDirectory() as td:
|
| 279 |
+
extracted = extract_weights_from_keras_archive(model_file, Path(td))
|
| 280 |
+
model.load_weights(extracted)
|
| 281 |
+
return model
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def load_audio_16k_mono(path: Path) -> np.ndarray:
|
| 285 |
+
waveform, _ = librosa.load(
|
| 286 |
+
str(path),
|
| 287 |
+
sr=16000,
|
| 288 |
+
mono=True,
|
| 289 |
+
duration=MAX_AUDIO_SECONDS,
|
| 290 |
+
)
|
| 291 |
+
waveform = np.nan_to_num(np.asarray(waveform, dtype=np.float32))
|
| 292 |
+
if waveform.size < 3200:
|
| 293 |
+
raise ValueError("Audio is too short")
|
| 294 |
+
return np.clip(waveform, -1.0, 1.0)
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def analyze_audio_quality(waveform: np.ndarray) -> dict:
|
| 298 |
+
duration = len(waveform) / 16000.0
|
| 299 |
+
rms = float(np.sqrt(np.mean(waveform ** 2) + 1e-12))
|
| 300 |
+
rms_db = float(20 * np.log10(max(rms, 1e-8)))
|
| 301 |
+
clipping_ratio = float(np.mean(np.abs(waveform) >= 0.995))
|
| 302 |
+
|
| 303 |
+
frame = 400
|
| 304 |
+
hop = 160
|
| 305 |
+
energies = []
|
| 306 |
+
for start in range(0, max(1, len(waveform) - frame + 1), hop):
|
| 307 |
+
chunk = waveform[start:start + frame]
|
| 308 |
+
if len(chunk) < frame:
|
| 309 |
+
break
|
| 310 |
+
energies.append(np.sqrt(np.mean(chunk ** 2) + 1e-12))
|
| 311 |
+
|
| 312 |
+
if energies:
|
| 313 |
+
energies = np.asarray(energies)
|
| 314 |
+
threshold = max(
|
| 315 |
+
10 ** (-45 / 20),
|
| 316 |
+
float(np.percentile(energies, 20)) * 2.0,
|
| 317 |
+
)
|
| 318 |
+
active_ratio = float(np.mean(energies >= threshold))
|
| 319 |
+
else:
|
| 320 |
+
active_ratio = 0.0
|
| 321 |
+
|
| 322 |
+
passed = (
|
| 323 |
+
duration >= 0.5
|
| 324 |
+
and rms_db >= -50.0
|
| 325 |
+
and active_ratio >= 0.08
|
| 326 |
+
and clipping_ratio <= 0.20
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
reason = None
|
| 330 |
+
if duration < 0.5:
|
| 331 |
+
reason = "audio_too_short"
|
| 332 |
+
elif rms_db < -50.0:
|
| 333 |
+
reason = "audio_too_quiet"
|
| 334 |
+
elif active_ratio < 0.08:
|
| 335 |
+
reason = "not_enough_active_audio"
|
| 336 |
+
elif clipping_ratio > 0.20:
|
| 337 |
+
reason = "audio_clipped"
|
| 338 |
+
|
| 339 |
+
return {
|
| 340 |
+
"passed": passed,
|
| 341 |
+
"reason": reason,
|
| 342 |
+
"duration_seconds": duration,
|
| 343 |
+
"rms_db": rms_db,
|
| 344 |
+
"active_ratio": active_ratio,
|
| 345 |
+
"clipping_ratio": clipping_ratio,
|
| 346 |
+
}
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def extract_file_feature_and_scores(
|
| 350 |
+
waveform: np.ndarray,
|
| 351 |
+
) -> tuple[np.ndarray, np.ndarray]:
|
| 352 |
+
scores, embeddings, _ = YAMNET(waveform)
|
| 353 |
+
feature = tf.concat(
|
| 354 |
+
[
|
| 355 |
+
tf.reduce_mean(embeddings, axis=0),
|
| 356 |
+
tf.reduce_max(embeddings, axis=0),
|
| 357 |
+
],
|
| 358 |
+
axis=0,
|
| 359 |
+
).numpy().astype(np.float32)
|
| 360 |
+
|
| 361 |
+
mean_scores = tf.reduce_mean(scores, axis=0).numpy().astype(np.float32)
|
| 362 |
+
max_scores = tf.reduce_max(scores, axis=0).numpy().astype(np.float32)
|
| 363 |
+
combined_scores = 0.5 * mean_scores + 0.5 * max_scores
|
| 364 |
+
|
| 365 |
+
return feature, combined_scores
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def load_yamnet_class_names() -> list[str]:
|
| 369 |
+
class_map_path = YAMNET.class_map_path().numpy().decode("utf-8")
|
| 370 |
+
names = []
|
| 371 |
+
with tf.io.gfile.GFile(class_map_path) as csvfile:
|
| 372 |
+
reader = csv.DictReader(csvfile)
|
| 373 |
+
for row in reader:
|
| 374 |
+
names.append(row["display_name"])
|
| 375 |
+
return names
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def class_score(score_vector: np.ndarray, name: str) -> float:
|
| 379 |
+
idx = YAMNET_CLASS_INDEX.get(name)
|
| 380 |
+
if idx is None:
|
| 381 |
+
return 0.0
|
| 382 |
+
return float(score_vector[idx])
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def aggregate_source_scores(score_vector: np.ndarray) -> dict:
|
| 386 |
+
grouped = {}
|
| 387 |
+
|
| 388 |
+
for source_name, class_names in SOURCE_GROUPS.items():
|
| 389 |
+
vals = [class_score(score_vector, name) for name in class_names]
|
| 390 |
+
vals = sorted(vals, reverse=True)
|
| 391 |
+
grouped[source_name] = float(
|
| 392 |
+
vals[0] + 0.35 * sum(vals[1:3])
|
| 393 |
+
) if vals else 0.0
|
| 394 |
+
|
| 395 |
+
other_vals = [
|
| 396 |
+
class_score(score_vector, name)
|
| 397 |
+
for name in OTHER_HINTS
|
| 398 |
+
]
|
| 399 |
+
other_vals = sorted(other_vals, reverse=True)
|
| 400 |
+
explicit_other = (
|
| 401 |
+
other_vals[0] + 0.25 * sum(other_vals[1:4])
|
| 402 |
+
if other_vals else 0.0
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
strongest_target = max(grouped.values()) if grouped else 0.0
|
| 406 |
+
residual_other = max(0.0, 0.18 - strongest_target)
|
| 407 |
+
grouped["other"] = float(max(explicit_other, residual_other))
|
| 408 |
+
|
| 409 |
+
return grouped
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
def source_decision(
|
| 413 |
+
selected_model: str,
|
| 414 |
+
source_scores: dict,
|
| 415 |
+
) -> tuple[bool, str, str]:
|
| 416 |
+
ordered = sorted(
|
| 417 |
+
source_scores.items(),
|
| 418 |
+
key=lambda x: x[1],
|
| 419 |
+
reverse=True,
|
| 420 |
+
)
|
| 421 |
+
detected_source = ordered[0][0]
|
| 422 |
+
selected_score = float(source_scores.get(selected_model, 0.0))
|
| 423 |
+
other_score = float(source_scores.get("other", 0.0))
|
| 424 |
+
competing_targets = [
|
| 425 |
+
score
|
| 426 |
+
for name, score in source_scores.items()
|
| 427 |
+
if name not in {selected_model, "other"}
|
| 428 |
+
]
|
| 429 |
+
next_target_score = max(competing_targets) if competing_targets else 0.0
|
| 430 |
+
|
| 431 |
+
accepted = (
|
| 432 |
+
detected_source == selected_model
|
| 433 |
+
and selected_score >= MIN_SELECTED_SOURCE_SCORE
|
| 434 |
+
and selected_score - other_score >= MIN_SELECTED_OVER_OTHER
|
| 435 |
+
and selected_score - next_target_score >= MIN_SELECTED_MARGIN
|
| 436 |
+
)
|
| 437 |
+
|
| 438 |
+
if accepted:
|
| 439 |
+
return True, detected_source, "ok"
|
| 440 |
+
|
| 441 |
+
if detected_source != selected_model:
|
| 442 |
+
return False, detected_source, "species_mismatch"
|
| 443 |
+
|
| 444 |
+
return False, detected_source, "source_uncertain"
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def yamnet_top_classes(
|
| 448 |
+
score_vector: np.ndarray,
|
| 449 |
+
count: int = 8,
|
| 450 |
+
) -> list[dict]:
|
| 451 |
+
order = np.argsort(score_vector)[::-1][:count]
|
| 452 |
+
return [
|
| 453 |
+
{
|
| 454 |
+
"label": YAMNET_CLASS_NAMES[int(i)],
|
| 455 |
+
"score": float(score_vector[int(i)]),
|
| 456 |
+
}
|
| 457 |
+
for i in order
|
| 458 |
+
]
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
print("Loading YAMNet...")
|
| 462 |
+
YAMNET = hub.load("https://tfhub.dev/google/yamnet/1")
|
| 463 |
+
YAMNET_CLASS_NAMES = load_yamnet_class_names()
|
| 464 |
+
YAMNET_CLASS_INDEX = {
|
| 465 |
+
name: i
|
| 466 |
+
for i, name in enumerate(YAMNET_CLASS_NAMES)
|
| 467 |
+
}
|
| 468 |
+
print("YAMNet loaded with", len(YAMNET_CLASS_NAMES), "classes.")
|
| 469 |
+
|
| 470 |
+
LOADED_MODELS: Dict[str, Dict[str, object]] = {}
|
| 471 |
+
for key, cfg in STATE_MODEL_CONFIG.items():
|
| 472 |
+
try:
|
| 473 |
+
labels_file = find_labels_file(cfg["dir"])
|
| 474 |
+
labels = json.loads(labels_file.read_text(encoding="utf-8"))
|
| 475 |
+
classifier = load_classifier(cfg["dir"], labels)
|
| 476 |
+
LOADED_MODELS[key] = {
|
| 477 |
+
"classifier": classifier,
|
| 478 |
+
"labels": labels,
|
| 479 |
+
"display_name": cfg["display_name"],
|
| 480 |
+
"version": f"{key}_{int(labels_file.stat().st_mtime)}",
|
| 481 |
+
}
|
| 482 |
+
print(f"Loaded {key}: {labels}")
|
| 483 |
+
except Exception as exc:
|
| 484 |
+
print(f"Skipped {key}: {type(exc).__name__}: {exc}")
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
app = FastAPI(
|
| 488 |
+
title="Sound Insight V3.2 YAMNet Guard API",
|
| 489 |
+
version="0.3.2",
|
| 490 |
+
)
|
| 491 |
+
|
| 492 |
+
app.add_middleware(
|
| 493 |
+
CORSMiddleware,
|
| 494 |
+
allow_origins=["*"],
|
| 495 |
+
allow_credentials=False,
|
| 496 |
+
allow_methods=["*"],
|
| 497 |
+
allow_headers=["*"],
|
| 498 |
+
)
|
| 499 |
+
|
| 500 |
+
threading.Thread(target=cleanup_worker, daemon=True).start()
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
@app.get("/")
|
| 504 |
+
def root():
|
| 505 |
+
return {
|
| 506 |
+
"status": "ok",
|
| 507 |
+
"loaded_models": list(LOADED_MODELS.keys()),
|
| 508 |
+
"guard_mode": "yamnet_audioset_rules",
|
| 509 |
+
"guard_thresholds": {
|
| 510 |
+
"min_selected_source_score": MIN_SELECTED_SOURCE_SCORE,
|
| 511 |
+
"min_selected_over_other": MIN_SELECTED_OVER_OTHER,
|
| 512 |
+
"min_selected_margin": MIN_SELECTED_MARGIN,
|
| 513 |
+
},
|
| 514 |
+
}
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
@app.get("/health")
|
| 518 |
+
def health():
|
| 519 |
+
return {
|
| 520 |
+
"status": "ok",
|
| 521 |
+
"loaded_models": list(LOADED_MODELS.keys()),
|
| 522 |
+
"guard_mode": "yamnet_audioset_rules",
|
| 523 |
+
}
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
@app.get("/training-tags")
|
| 527 |
+
def training_tags():
|
| 528 |
+
return TRAINING_TAGS
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
@app.post("/predict", response_model=PredictResponse)
|
| 532 |
+
async def predict(
|
| 533 |
+
model: str = Form(...),
|
| 534 |
+
audio: UploadFile = File(...),
|
| 535 |
+
):
|
| 536 |
+
model = model.strip().lower()
|
| 537 |
+
|
| 538 |
+
if model not in LOADED_MODELS:
|
| 539 |
+
raise HTTPException(400, f"Model not loaded: {model}")
|
| 540 |
+
|
| 541 |
+
suffix = Path(audio.filename or "recording.m4a").suffix or ".m4a"
|
| 542 |
+
with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
|
| 543 |
+
temp_path = Path(tmp.name)
|
| 544 |
+
tmp.write(await audio.read())
|
| 545 |
+
|
| 546 |
+
try:
|
| 547 |
+
waveform = load_audio_16k_mono(temp_path)
|
| 548 |
+
quality = analyze_audio_quality(waveform)
|
| 549 |
+
|
| 550 |
+
if not quality["passed"]:
|
| 551 |
+
return PredictResponse(
|
| 552 |
+
status="rejected",
|
| 553 |
+
model=model,
|
| 554 |
+
reason=quality["reason"],
|
| 555 |
+
message="No clear usable sound was detected. Please record again.",
|
| 556 |
+
quality=quality,
|
| 557 |
+
)
|
| 558 |
+
|
| 559 |
+
feature, yamnet_scores = extract_file_feature_and_scores(waveform)
|
| 560 |
+
source_scores = aggregate_source_scores(yamnet_scores)
|
| 561 |
+
accepted, detected_source, reason = source_decision(
|
| 562 |
+
model,
|
| 563 |
+
source_scores,
|
| 564 |
+
)
|
| 565 |
+
|
| 566 |
+
source_score_items = [
|
| 567 |
+
SourceScoreItem(label=name, score=float(score))
|
| 568 |
+
for name, score in sorted(
|
| 569 |
+
source_scores.items(),
|
| 570 |
+
key=lambda x: x[1],
|
| 571 |
+
reverse=True,
|
| 572 |
+
)
|
| 573 |
+
]
|
| 574 |
+
top_class_items = [
|
| 575 |
+
SourceScoreItem(**item)
|
| 576 |
+
for item in yamnet_top_classes(yamnet_scores)
|
| 577 |
+
]
|
| 578 |
+
|
| 579 |
+
if not accepted:
|
| 580 |
+
return PredictResponse(
|
| 581 |
+
status="rejected",
|
| 582 |
+
model=model,
|
| 583 |
+
reason=reason,
|
| 584 |
+
message="The recording does not contain a clear matching sound. Please try again.",
|
| 585 |
+
detected_source=detected_source,
|
| 586 |
+
source_scores=source_score_items,
|
| 587 |
+
yamnet_top_classes=top_class_items,
|
| 588 |
+
quality=quality,
|
| 589 |
+
)
|
| 590 |
+
|
| 591 |
+
selected = LOADED_MODELS[model]
|
| 592 |
+
probabilities = selected["classifier"].predict(
|
| 593 |
+
feature[None, :],
|
| 594 |
+
verbose=0,
|
| 595 |
+
)[0]
|
| 596 |
+
|
| 597 |
+
labels = selected["labels"]
|
| 598 |
+
order = np.argsort(probabilities)[::-1]
|
| 599 |
+
top_index = int(order[0])
|
| 600 |
+
|
| 601 |
+
return PredictResponse(
|
| 602 |
+
status="ok",
|
| 603 |
+
model=model,
|
| 604 |
+
model_display_name=selected["display_name"],
|
| 605 |
+
top_label=labels[top_index],
|
| 606 |
+
top_display_label=display_label(labels[top_index]),
|
| 607 |
+
top_probability=float(probabilities[top_index]),
|
| 608 |
+
probabilities=[
|
| 609 |
+
ProbabilityItem(
|
| 610 |
+
label=labels[int(i)],
|
| 611 |
+
display_label=display_label(labels[int(i)]),
|
| 612 |
+
probability=float(probabilities[int(i)]),
|
| 613 |
+
)
|
| 614 |
+
for i in order
|
| 615 |
+
],
|
| 616 |
+
model_version=str(selected["version"]),
|
| 617 |
+
detected_source=detected_source,
|
| 618 |
+
source_scores=source_score_items,
|
| 619 |
+
yamnet_top_classes=top_class_items,
|
| 620 |
+
quality=quality,
|
| 621 |
+
)
|
| 622 |
+
|
| 623 |
+
except Exception as exc:
|
| 624 |
+
raise HTTPException(
|
| 625 |
+
500,
|
| 626 |
+
f"{type(exc).__name__}: {exc}",
|
| 627 |
+
) from exc
|
| 628 |
+
|
| 629 |
+
finally:
|
| 630 |
+
temp_path.unlink(missing_ok=True)
|
| 631 |
+
|
| 632 |
+
|
| 633 |
+
@app.post("/training-samples")
|
| 634 |
+
async def upload_training_sample(
|
| 635 |
+
species: str = Form(...),
|
| 636 |
+
tag: str = Form(...),
|
| 637 |
+
audio: UploadFile = File(...),
|
| 638 |
+
):
|
| 639 |
+
cleanup_expired_uploads()
|
| 640 |
+
species = species.strip().lower()
|
| 641 |
+
tag = tag.strip()
|
| 642 |
+
|
| 643 |
+
if species not in TRAINING_TAGS:
|
| 644 |
+
raise HTTPException(400, "Invalid species")
|
| 645 |
+
if tag not in TRAINING_TAGS[species]:
|
| 646 |
+
raise HTTPException(400, "Invalid tag for species")
|
| 647 |
+
|
| 648 |
+
sample_id = uuid.uuid4().hex
|
| 649 |
+
suffix = Path(audio.filename or "recording.m4a").suffix.lower() or ".m4a"
|
| 650 |
+
target_dir = TRAINING_UPLOADS_DIR / species / tag
|
| 651 |
+
target_dir.mkdir(parents=True, exist_ok=True)
|
| 652 |
+
|
| 653 |
+
audio_path = target_dir / f"{sample_id}{suffix}"
|
| 654 |
+
meta_path = target_dir / f"{sample_id}.json"
|
| 655 |
+
content = await audio.read()
|
| 656 |
+
|
| 657 |
+
if not content:
|
| 658 |
+
raise HTTPException(400, "Empty audio file")
|
| 659 |
+
if len(content) > 30 * 1024 * 1024:
|
| 660 |
+
raise HTTPException(413, "Audio file exceeds 30 MB")
|
| 661 |
+
|
| 662 |
+
audio_path.write_bytes(content)
|
| 663 |
+
uploaded_at = now_utc()
|
| 664 |
+
meta = {
|
| 665 |
+
"id": sample_id,
|
| 666 |
+
"species": species,
|
| 667 |
+
"tag": tag,
|
| 668 |
+
"uploaded_at": uploaded_at.isoformat(),
|
| 669 |
+
"expires_at": (
|
| 670 |
+
uploaded_at + timedelta(hours=TRAINING_RETENTION_HOURS)
|
| 671 |
+
).isoformat(),
|
| 672 |
+
"original_filename": audio.filename,
|
| 673 |
+
"audio_suffix": suffix,
|
| 674 |
+
}
|
| 675 |
+
meta_path.write_text(
|
| 676 |
+
json.dumps(meta, ensure_ascii=False, indent=2),
|
| 677 |
+
encoding="utf-8",
|
| 678 |
+
)
|
| 679 |
+
return {
|
| 680 |
+
"status": "uploaded",
|
| 681 |
+
"id": sample_id,
|
| 682 |
+
"expires_at": meta["expires_at"],
|
| 683 |
+
}
|
| 684 |
+
|
| 685 |
+
|
| 686 |
+
def check_admin_token(token: str | None) -> None:
|
| 687 |
+
if not token or token != ADMIN_TOKEN:
|
| 688 |
+
raise HTTPException(401, "Invalid admin token")
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
@app.get("/admin/training-samples/download")
|
| 692 |
+
def download_training_samples(
|
| 693 |
+
x_admin_token: str | None = Header(default=None),
|
| 694 |
+
):
|
| 695 |
+
check_admin_token(x_admin_token)
|
| 696 |
+
cleanup_expired_uploads()
|
| 697 |
+
|
| 698 |
+
temp_dir = Path(tempfile.mkdtemp())
|
| 699 |
+
zip_path = temp_dir / (
|
| 700 |
+
f"training_samples_{now_utc().strftime('%Y%m%d_%H%M%S')}.zip"
|
| 701 |
+
)
|
| 702 |
+
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as archive:
|
| 703 |
+
for path in TRAINING_UPLOADS_DIR.rglob("*"):
|
| 704 |
+
if path.is_file():
|
| 705 |
+
archive.write(
|
| 706 |
+
path,
|
| 707 |
+
path.relative_to(TRAINING_UPLOADS_DIR),
|
| 708 |
+
)
|
| 709 |
+
|
| 710 |
+
return FileResponse(
|
| 711 |
+
zip_path,
|
| 712 |
+
filename=zip_path.name,
|
| 713 |
+
media_type="application/zip",
|
| 714 |
+
)
|
| 715 |
+
|
| 716 |
+
|
| 717 |
+
@app.delete("/admin/training-samples")
|
| 718 |
+
def delete_all_training_samples(
|
| 719 |
+
x_admin_token: str | None = Header(default=None),
|
| 720 |
+
):
|
| 721 |
+
check_admin_token(x_admin_token)
|
| 722 |
+
if TRAINING_UPLOADS_DIR.exists():
|
| 723 |
+
shutil.rmtree(TRAINING_UPLOADS_DIR)
|
| 724 |
+
TRAINING_UPLOADS_DIR.mkdir(parents=True, exist_ok=True)
|
| 725 |
+
return {"status": "deleted"}
|
models/baby/classifier.weights.h5
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8628373d1200fbe1860f2a4c7d6da6d256edd90fb353dbc3dca42e1a782fe5a8
|
| 3 |
+
size 2287312
|
models/baby/labels.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
[
|
|
|
|
| 2 |
"Hungry",
|
| 3 |
-
"Sleepy",
|
| 4 |
"Need_Burping",
|
| 5 |
-
"
|
| 6 |
]
|
|
|
|
| 1 |
[
|
| 2 |
+
"Discomfort",
|
| 3 |
"Hungry",
|
|
|
|
| 4 |
"Need_Burping",
|
| 5 |
+
"Sleepy"
|
| 6 |
]
|
models/cat/final_classifier.keras
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b04e0702207a79317dd1fef19652ac7040677289567f3e56706023bad4d32fa7
|
| 3 |
+
size 6798227
|
models/cat/labels.json
CHANGED
|
@@ -2,6 +2,6 @@
|
|
| 2 |
"Angry",
|
| 3 |
"Hungry",
|
| 4 |
"Mating",
|
| 5 |
-
"
|
| 6 |
-
"
|
| 7 |
]
|
|
|
|
| 2 |
"Angry",
|
| 3 |
"Hungry",
|
| 4 |
"Mating",
|
| 5 |
+
"Paining",
|
| 6 |
+
"Relaxed"
|
| 7 |
]
|
models/dog/classifier.weights.h5
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f937a363a9ccdafd49ad6f032231fb69bb5f187dbc272448df4c7524d8e9391d
|
| 3 |
+
size 2287824
|
models/dog/labels.json
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
[
|
| 2 |
-
"
|
|
|
|
| 3 |
"Distress_PainLike",
|
| 4 |
-
"
|
| 5 |
-
"
|
| 6 |
]
|
|
|
|
| 1 |
[
|
| 2 |
+
"Aggressive_Alert",
|
| 3 |
+
"Calm_Other",
|
| 4 |
"Distress_PainLike",
|
| 5 |
+
"Happy_Excited",
|
| 6 |
+
"Uncertain_Dog_Vocalization"
|
| 7 |
]
|
requirements.txt
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
setuptools==80.9.0
|
| 2 |
+
fastapi==0.115.6
|
| 3 |
+
uvicorn[standard]==0.34.0
|
| 4 |
+
python-multipart==0.0.20
|
| 5 |
+
tensorflow==2.17.1
|
| 6 |
+
tf-keras==2.17.0
|
| 7 |
+
tensorflow-hub==0.16.1
|
| 8 |
+
librosa==0.10.2.post1
|
| 9 |
+
soundfile==0.12.1
|
| 10 |
+
numpy==1.26.4
|
| 11 |
+
scipy==1.13.1
|
| 12 |
+
h5py==3.11.0
|
test_predict.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import requests
|
| 3 |
+
|
| 4 |
+
parser = argparse.ArgumentParser()
|
| 5 |
+
parser.add_argument('--url', default='http://127.0.0.1:8000/predict')
|
| 6 |
+
parser.add_argument('--model', choices=['cat', 'baby', 'dog'], required=True)
|
| 7 |
+
parser.add_argument('--audio', required=True)
|
| 8 |
+
args = parser.parse_args()
|
| 9 |
+
|
| 10 |
+
with open(args.audio, 'rb') as f:
|
| 11 |
+
response = requests.post(
|
| 12 |
+
args.url,
|
| 13 |
+
data={'model': args.model},
|
| 14 |
+
files={'audio': (args.audio, f, 'audio/wav')},
|
| 15 |
+
timeout=120,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
print(response.status_code)
|
| 19 |
+
print(response.text)
|