Download scripts/calls.py from matthiastl/sava-telephony: direct link, hf CLI and curl.
- Browser
- Download file 16 kB
-
https://huggingface.co/matthiastl/sava-telephony/resolve/main/scripts/calls.py
- Command line
-
hf download hf://matthiastl/sava-telephony/scripts/calls.py
-
curl -L -o calls.py https://huggingface.co/matthiastl/sava-telephony/resolve/main/scripts/calls.py
16 kB
| """Score SAVA versions on recordings of real phone calls. | |
| CallHome English (TalkBank, ``talkbank/callhome``): telephone calls with hand-marked times of who | |
| spoke when, most of them between two people. Each system hears a call as one stream from its | |
| start; audio at another rate is resampled to 16 kHz first (the dataset already ships 16 kHz). Two questions, both asked only inside the part of a call that was | |
| annotated: | |
| speech is each 40 ms frame speech? A frame is speech when a marked segment covers its centre. | |
| turns at a pause, will the same person go on (hold) or does the other take over (shift)? | |
| The score is the model's end-of-turn probability a fixed time into the pause. | |
| python -I calls.py score --data data/callhome/eng/data-00000-of-00005.parquet \ | |
| --checkpoints runs/phone-1/best.safetensors --out results/callhome | |
| python -I calls.py report --out results/callhome | |
| Any set in the same layout works. With ``--conditions clean phone gsm`` every system also hears | |
| each recording through the simulated lines of ``channels.py``, which shows what a phone line costs | |
| on wideband conversation (``diarizers-community/ami``); those systems are named ``original:phone``. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import io | |
| import json | |
| import multiprocessing | |
| import sys | |
| import time | |
| from pathlib import Path | |
| import numpy as np | |
| sys.path.insert(0, str(Path(__file__).parent)) # for bench and sava_onnx when run with python -I | |
| import bench # noqa: E402 | |
| FRAME_SECONDS = bench.FRAME_SECONDS | |
| MIN_PAUSE = 0.5 # seconds nobody speaks, for a pause to count | |
| CLEAR_BEFORE = 0.5 # only one person may speak in this long before the pause | |
| MIN_SPEECH = 1.0 # the segment before a pause, and the other person's reply, must last this long: no backchannels | |
| OFFSETS = (0.4, 0.2) # seconds into the pause at which the end-of-turn probability is read; first is primary | |
| SAME_HOLD_RATE = 0.4 # systems are also compared with thresholds at which each fires at this share of holds | |
| _systems: dict = {} | |
| _smart_turn: dict = {} | |
| _conditions: list[str] = [] | |
| def pauses(starts: list[float], ends: list[float], speakers: list[str]) -> list[tuple[float, bool]]: | |
| """``(pause start, is a shift)`` for every pause that is clearly a hold or a shift. | |
| A pause is a stretch of at least ``MIN_PAUSE`` in which nobody speaks. It counts when one person | |
| alone spoke in the ``CLEAR_BEFORE`` before it and the segment it follows lasted at least | |
| ``MIN_SPEECH``. Hold: that person speaks next. Shift: the other person speaks next, for at least | |
| ``MIN_SPEECH``. Short segments on either side are backchannels ("mhm") and are left out. | |
| """ | |
| segments = sorted(zip(starts, ends, speakers)) | |
| events = [] | |
| reach, length = segments[0][1], segments[0][1] - segments[0][0] # latest end so far, and that segment's length | |
| for index, (start, end, speaker) in enumerate(segments[1:], 1): | |
| if start - reach >= MIN_PAUSE and length >= MIN_SPEECH: | |
| before = {s for a, b, s in segments[:index] if b > reach - CLEAR_BEFORE} | |
| if len(before) == 1: | |
| last = next(iter(before)) | |
| if speaker == last: | |
| events.append((reach, False)) | |
| elif end - start >= MIN_SPEECH: | |
| events.append((reach, True)) | |
| if end > reach: | |
| reach, length = end, end - start | |
| return events | |
| def to_16k(samples: np.ndarray, rate: int) -> np.ndarray: | |
| """Mono float32 at 16 kHz, resampled the way the fine-tuning lines were.""" | |
| from math import gcd | |
| from scipy.signal import resample_poly | |
| mono = samples.mean(axis=1) if samples.ndim == 2 else samples | |
| if rate == 16000: | |
| return mono.astype(np.float32) | |
| common = gcd(16000, rate) | |
| return resample_poly(mono.astype(np.float64), 16000 // common, rate // common).astype(np.float32) | |
| def streamed(model, samples: np.ndarray) -> tuple[np.ndarray, np.ndarray]: | |
| """``sava.run`` in one-minute pushes: the same curves, in memory that does not grow with length.""" | |
| from inworld import sava | |
| session = sava.Session(model) | |
| step = 60 * 16000 | |
| parts = [session.push(samples[i : i + step]) for i in range(0, samples.size, step)] + [session.flush()] | |
| speech = np.concatenate([part.speech for part in parts]) | |
| turn = np.concatenate([part.turn for part in parts]) | |
| lag = session.lag # speech verdicts arrive this many frames late; flush adds as many frames | |
| return speech[lag:], turn[: turn.size - lag] | |
| def _init_worker(args: argparse.Namespace) -> None: | |
| _systems.update(bench.load_systems(args, whole=streamed)) | |
| if args.smart_turn: | |
| _smart_turn.update(bench.load_smart_turn(args.smart_turn)) | |
| _conditions.extend(args.conditions) | |
| def _score_call(job: tuple[Path, int, int, Path]) -> str: | |
| """Score one call (one parquet row) into an ``.npz`` file.""" | |
| import soundfile | |
| from pyarrow import parquet | |
| shard, group, index, out_dir = job | |
| out_path = out_dir / f"{shard.stem}-{group:03d}-{index:03d}.npz" | |
| if out_path.exists(): | |
| return out_path.name | |
| row = parquet.ParquetFile(shard).read_row_group(group).slice(index, 1).to_pylist()[0] | |
| samples, rate = soundfile.read(io.BytesIO(row["audio"]["bytes"]), dtype="float32", always_2d=True) | |
| audio = to_16k(samples, rate) | |
| starts, ends, speakers = row["timestamps_start"], row["timestamps_end"], row["speakers"] | |
| record = { | |
| "rate": rate, | |
| "channels": samples.shape[1], | |
| "seconds": audio.size / 16000, | |
| "span": np.array([min(starts), max(ends)]), | |
| "segments": np.array([starts, ends]).T, | |
| "speakers": np.array(speakers), | |
| } | |
| events = [(t, shift) for t, shift in pauses(starts, ends, speakers) if t + max(OFFSETS) < audio.size / 16000] | |
| record["pause_start"] = np.array([t for t, _ in events]) | |
| record["shift"] = np.array([shift for _, shift in events], dtype=bool) | |
| heard = {"": audio} if _conditions == ["asis"] else {f":{c}": a for c, a in bench.conditions_of(audio, _conditions).items()} | |
| for suffix, line in heard.items(): | |
| for name, run in _systems.items(): | |
| speech, turn = run(line) | |
| record[f"speech/{name}{suffix}"] = speech.astype(np.float32) | |
| record[f"turn/{name}{suffix}"] = turn.astype(np.float32) | |
| for name, run in _smart_turn.items(): | |
| # Smart Turn judges a clip's end, so it gets the audio up to each reading point. | |
| for offset in OFFSETS: | |
| record[f"pause@{offset}/{name}{suffix}"] = np.array( | |
| [run(line[: int(round((t + offset) * 16000))])[1][-1] for t, _ in events], dtype=np.float32 | |
| ) | |
| np.savez_compressed(out_path, **record) | |
| return out_path.name | |
| def run_score(args: argparse.Namespace) -> None: | |
| from pyarrow import parquet | |
| args.out.mkdir(parents=True, exist_ok=True) | |
| jobs = [] | |
| for shard in args.data: | |
| table = parquet.ParquetFile(shard) | |
| for group in range(table.num_row_groups): | |
| jobs += [(shard, group, index, args.out) for index in range(table.metadata.row_group(group).num_rows)] | |
| jobs = jobs[: args.limit] | |
| started = time.time() | |
| with multiprocessing.Pool(args.workers, _init_worker, (args,)) as pool: | |
| for name in pool.imap_unordered(_score_call, jobs): | |
| print(f"{name} done, {time.time() - started:.0f} s", file=sys.stderr, flush=True) | |
| run_report(args) | |
| def run_report(args: argparse.Namespace) -> None: | |
| from sklearn import metrics | |
| calls = [dict(np.load(path)) for path in sorted(args.out.glob("*.npz"))] | |
| systems = sorted(key.split("/", 1)[1] for key in calls[0] if key.startswith("speech/")) | |
| extra = sorted({key.split("/", 1)[1] for key in calls[0] if key.startswith("pause@")}) | |
| rng = np.random.default_rng(0) | |
| draws = rng.integers(0, len(calls), (args.resamples, len(calls))) | |
| # Speech: frames inside each call's annotated span. | |
| labels, speech = [], {name: [] for name in systems} | |
| for call in calls: | |
| frames = call[f"speech/{systems[0]}"].size | |
| centres = (np.arange(frames) + 0.5) * FRAME_SECONDS | |
| inside = (centres >= call["span"][0]) & (centres < call["span"][1]) | |
| labels.append(bench.frame_labels(frames, [tuple(s) for s in call["segments"]])[inside]) | |
| for name in systems: | |
| speech[name].append(call[f"speech/{name}"][inside]) | |
| # Turns: the end-of-turn probability a fixed time into each pause. | |
| shifts = [call["shift"] for call in calls] | |
| at_pause = {} | |
| for offset in OFFSETS: | |
| for name in systems: | |
| at_pause[offset, name] = [ | |
| call[f"turn/{name}"][np.minimum(((call["pause_start"] + offset) / FRAME_SECONDS).astype(int), call[f"turn/{name}"].size - 1)] | |
| for call in calls | |
| ] | |
| for name in extra: | |
| at_pause[offset, name] = [call[f"pause@{offset}/{name}"] for call in calls] | |
| def auc(truth: list[np.ndarray], scores: list[np.ndarray], picks=None) -> float: | |
| picks = range(len(truth)) if picks is None else picks | |
| return float(metrics.roc_auc_score(np.concatenate([truth[i] for i in picks]), np.concatenate([scores[i] for i in picks]))) | |
| def against(truth, scores, base, label="original") -> dict: | |
| diffs = np.array([auc(truth, scores, d) - auc(truth, base, d) for d in draws]) | |
| return { | |
| f"auc_minus_{label}": auc(truth, scores) - auc(truth, base), | |
| f"auc_minus_{label}_ci": [float(np.percentile(diffs, 2.5)), float(np.percentile(diffs, 97.5))], | |
| } | |
| def reference(name: str) -> str | None: | |
| """The original that heard the same line, unless ``name`` is that original.""" | |
| base = "original" + (":" + name.split(":", 1)[1] if ":" in name else "") | |
| return base if base != name and base in systems else None | |
| def clean_reference(name: str) -> str | None: | |
| """The original on the recording as published, for systems that heard it through a line.""" | |
| return "original:clean" if "original:clean" in systems and name != "original:clean" else None | |
| pooled = np.concatenate(labels) | |
| pooled_shifts = np.concatenate(shifts) | |
| result = { | |
| "calls": len(calls), | |
| "hours_annotated": float(sum(c["span"][1] - c["span"][0] for c in calls) / 3600), | |
| "source_rates": sorted({int(c["rate"]) for c in calls}), | |
| "frames": int(pooled.size), | |
| "speech_fraction": float(pooled.mean()), | |
| "pauses": int(pooled_shifts.size), | |
| "shift_fraction": float(pooled_shifts.mean()), | |
| "speech": {}, | |
| "turns": {}, | |
| } | |
| for name in systems: | |
| probs = np.concatenate(speech[name]) | |
| scores = { | |
| "auc": auc(labels, speech[name]), | |
| "f1": float(metrics.f1_score(pooled, probs > 0.5)), | |
| "accuracy": float(((probs > 0.5) == pooled).mean()), | |
| "missed_speech": float((probs[pooled] <= 0.5).mean()), | |
| "false_alarm": float((probs[~pooled] > 0.5).mean()), | |
| } | |
| if clean_reference(name): | |
| scores |= against(labels, speech[name], speech["original:clean"], "clean_original") | |
| if reference(name): | |
| scores |= against(labels, speech[name], speech[reference(name)]) | |
| # Accuracy at threshold 0.5, paired over calls. | |
| right = [np.array([((s[i] > 0.5) == labels[i]).sum() for i in range(len(calls))]) for s in (speech[name], speech[reference(name)])] | |
| sizes = np.array([label.size for label in labels]) | |
| diffs = (right[0][draws].sum(axis=1) - right[1][draws].sum(axis=1)) / sizes[draws].sum(axis=1) | |
| scores["accuracy_minus_original"] = float((right[0].sum() - right[1].sum()) / sizes.sum()) | |
| scores["accuracy_minus_original_ci"] = [float(np.percentile(diffs, 2.5)), float(np.percentile(diffs, 97.5))] | |
| scores["calls_more_accurate"] = int((right[0] > right[1]).sum()) | |
| # Is it only readier to say "speech"? The original, with its threshold moved until it | |
| # says "speech" on as many frames as this system does at 0.5. | |
| base = np.concatenate(speech[reference(name)]) | |
| threshold = float(np.quantile(base, 1 - (probs > 0.5).mean())) | |
| scores["original_at_same_speech_rate"] = { | |
| "threshold": threshold, | |
| "accuracy": float(((base > threshold) == pooled).mean()), | |
| "missed_speech": float((base[pooled] <= threshold).mean()), | |
| "false_alarm": float((base[~pooled] > threshold).mean()), | |
| } | |
| result["speech"][name] = scores | |
| for offset in OFFSETS: | |
| for name in systems + extra: | |
| probs = np.concatenate(at_pause[offset, name]) | |
| scores = { | |
| "auc": auc(shifts, at_pause[offset, name]), | |
| "fires_at_shift": float((probs[pooled_shifts] > 0.5).mean()), | |
| "fires_at_hold": float((probs[~pooled_shifts] > 0.5).mean()), | |
| # With the threshold set so it fires at SAME_HOLD_RATE of the holds. | |
| "shifts_caught_at_same_hold_rate": float( | |
| (probs[pooled_shifts] > np.quantile(probs[~pooled_shifts], 1 - SAME_HOLD_RATE)).mean() | |
| ), | |
| } | |
| if clean_reference(name): | |
| scores |= against(shifts, at_pause[offset, name], at_pause[offset, "original:clean"], "clean_original") | |
| if reference(name): | |
| scores |= against(shifts, at_pause[offset, name], at_pause[offset, reference(name)]) | |
| # How much more often it says "ended" than the original, paired over calls. | |
| for kind, want in (("shift", True), ("hold", False)): | |
| fired = [ | |
| np.array([(p[i][shifts[i] == want] > 0.5).sum() for i in range(len(calls))]) | |
| for p in (at_pause[offset, name], at_pause[offset, reference(name)]) | |
| ] | |
| sizes = np.array([(s == want).sum() for s in shifts]) | |
| diffs = (fired[0][draws].sum(axis=1) - fired[1][draws].sum(axis=1)) / sizes[draws].sum(axis=1) | |
| scores[f"fires_at_{kind}_minus_original"] = float((fired[0].sum() - fired[1].sum()) / sizes.sum()) | |
| scores[f"fires_at_{kind}_minus_original_ci"] = [float(np.percentile(diffs, 2.5)), float(np.percentile(diffs, 97.5))] | |
| result["turns"][f"{name}@{offset}s"] = scores | |
| (args.out / "summary.json").write_text(json.dumps(result, indent=1) + "\n", encoding="utf-8") | |
| print(json.dumps(result, indent=1)) | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) | |
| commands = parser.add_subparsers(dest="command", required=True) | |
| for name in ("score", "report"): | |
| command = commands.add_parser(name) | |
| command.add_argument("--data", type=Path, nargs="+", help="parquet files of talkbank/callhome") | |
| command.add_argument("--out", type=Path, required=True) | |
| command.add_argument("--versions", type=Path, nargs="*", default=[], help="ONNX files") | |
| command.add_argument("--checkpoints", type=Path, nargs="*", default=[], help="fine-tuned safetensors files") | |
| command.add_argument("--no-original", action="store_true") | |
| command.add_argument("--conditions", nargs="+", default=["asis"], help="'asis', or lines from channels.TEST_CONDITIONS") | |
| command.add_argument("--smart-turn", type=Path, default=None, help="also score pipecat's smart-turn ONNX file at the pauses") | |
| command.add_argument("--resamples", type=int, default=2000) | |
| command.add_argument("--workers", type=int, default=4) | |
| command.add_argument("--limit", type=int, default=None, help="calls to score") | |
| args = parser.parse_args() | |
| {"score": run_score, "report": run_report}[args.command](args) | |
| if __name__ == "__main__": | |
| main() | |