#!/usr/bin/env python3 """Audio tagging for common/lib/clips/scan.mjs (release 35 C1): the laugh scan. WAV files in, per-window class probabilities out, as JSON. Nothing else: which audio, the windows' clock, the laugh family's sum, the events and the cache all live in the .mjs caller, so this file stays a thin shell over sherpa-onnx's AudioTagging (CED-mini, AudioSet's 527 classes) — modelled on scripts/speaker-embed.py. stdout is JSON ONLY; progress goes to stderr. Usage: audio-tag.py --model --labels [--threads N] [--classes 16,18,19,20,21] request.json: {"items": [{"id": "...", "wav": "/abs/path.wav", "window": 1.0, "hop": 0.5}, ...]} Each wav is 16-bit PCM, mono, 16 kHz (the caller decodes to it). With a `window` (seconds) the wav is scored window by window, every `hop` seconds (default: the window), as many whole windows as fit; without one, the whole wav is one window. Output: {"model": "", "version": "", "classes": [...], "names": [...], "items": [{"id", "seconds", "window", "hop", "scores": [[p, ...], ...] | null, "error"?: "..."}]} `scores` has one row per window, one probability per requested class, in `classes` order, rounded to 4 decimals (the same input prints the same bytes). One thread by default, as speaker-embed.py: a CPU reduction split across threads is where an ONNX run can differ in its last bits. """ import argparse, csv, json, os, sys, wave def read_wav(np, path): with wave.open(path, "rb") as w: rate = w.getframerate() width = w.getsampwidth() chans = w.getnchannels() raw = w.readframes(w.getnframes()) if width != 2: raise ValueError(f"{os.path.basename(path)}: {width * 8}-bit wav, want 16-bit PCM") x = np.frombuffer(raw, dtype=" 1: x = x.reshape(-1, chans).mean(axis=1) return x, rate def read_labels(path): names = {} with open(path, "r", encoding="utf8") as f: for row in csv.DictReader(f): names[int(row["index"])] = row["display_name"] return names def main(): ap = argparse.ArgumentParser() ap.add_argument("request") ap.add_argument("--model", required=True) ap.add_argument("--labels", required=True) ap.add_argument("--threads", type=int, default=1) ap.add_argument("--classes", default="16,18,19,20,21") args = ap.parse_args() try: import numpy as np import sherpa_onnx except ImportError as e: print(f"audio-tag: missing dependency: {e}", file=sys.stderr) return 3 classes = [int(c) for c in args.classes.split(",") if c.strip() != ""] names = read_labels(args.labels) with open(args.request, "r", encoding="utf8") as f: req = json.load(f) items = req.get("items") or [] cfg = sherpa_onnx.AudioTaggingConfig( model=sherpa_onnx.AudioTaggingModelConfig(ced=args.model, num_threads=args.threads), labels=args.labels, top_k=max(len(names), 1), ) if not cfg.validate(): print("audio-tag: invalid model config", file=sys.stderr) return 2 tagger = sherpa_onnx.AudioTagging(cfg) def probs(rate, x): stream = tagger.create_stream() stream.accept_waveform(rate, x) by = {e.index: e.prob for e in tagger.compute(stream)} return [round(float(by.get(c, 0.0)), 4) for c in classes] out = [] done = 0 for item in items: rec = {"id": item.get("id"), "seconds": 0.0, "window": None, "hop": None, "scores": None} try: x, rate = read_wav(np, item["wav"]) rec["seconds"] = round(x.size / rate, 3) win = item.get("window") if win is None: rec["scores"] = [probs(rate, x)] if x.size else [] else: win = float(win) hop = float(item.get("hop") or win) rec["window"] = win rec["hop"] = hop n_win = int(round(win * rate)) n_hop = max(1, int(round(hop * rate))) rows = [] a = 0 while a + n_win <= x.size: rows.append(probs(rate, x[a:a + n_win])) a += n_hop rec["scores"] = rows except Exception as e: # one bad file is that item's error, not the run's rec["error"] = str(e) out.append(rec) done += 1 print(f"audio-tag: {done}/{len(items)}", file=sys.stderr, flush=True) json.dump( { "model": os.path.basename(args.model), "version": getattr(sherpa_onnx, "__version__", None), "classes": classes, "names": [names.get(c, str(c)) for c in classes], "items": out, }, sys.stdout, ) return 0 if __name__ == "__main__": sys.exit(main())