File size: 9,992 Bytes
cadfcff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
"""Score SAVA versions against labeled data, on clean audio and through a simulated phone line.

Two of the test sets from the SAVA repository's benchmark, scored the way its scripts score them:

    tenvad    TEN-VAD's 30 hand-labeled recordings: is each 40 ms frame speech?
    pipecat   pipecat's smart-turn test clips: is the turn complete at the clip's end?

Each system is run on every recording from its start. ``original`` is the PyTorch model, run on
the whole recording at once by the upstream package's ``run()``; the others are ONNX files run as
a stream, one frame at a time, by ``sava_onnx``.
"""

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 sava_onnx and telephony when run with python -I

CONDITIONS = ("clean", "phone")
FRAME_SECONDS = 0.04
_systems: dict = {}


def load_systems(versions: list[Path]) -> dict:
    """``{name: samples -> (speech, turn)}`` for the PyTorch original and each ONNX file."""
    import torch
    from inworld import sava

    import sava_onnx

    torch.set_num_threads(1)
    model = sava.load("inworld/sava").eval()

    def original(samples: np.ndarray):
        curves = sava.run(model, samples)
        return curves.speech, curves.turn

    systems = {"original": original}
    for path in versions:
        systems[path.stem.removeprefix("sava.").replace("sava", "onnx")] = sava_onnx.Session(str(path)).run
    return systems


def conditions_of(samples: np.ndarray) -> dict[str, np.ndarray]:
    from telephony import telephone_channel

    return {"clean": samples, "phone": telephone_channel(samples)}


# --- TEN-VAD: frame-level speech detection ---------------------------------------------------


def tenvad_recordings(root: Path):
    from inworld.sava import audio

    for label_path in sorted(root.glob("*.scv")):
        fields = label_path.read_text(encoding="utf-8").strip().split(",")
        triples = [fields[i : i + 3] for i in range(1, len(fields) - 2, 3)]
        segments = [(float(s), float(e)) for s, e, label in triples if label.strip() == "1"]
        yield label_path.stem, audio.load(str(label_path.with_suffix(".wav"))), segments


def frame_labels(frames: int, segments: list[tuple[float, float]]) -> np.ndarray:
    """A frame is speech when a labeled segment covers its centre."""
    centres = (np.arange(frames) + 0.5) * FRAME_SECONDS
    labels = np.zeros(frames, dtype=bool)
    for start, end in segments:
        labels |= (centres >= start) & (centres < end)
    return labels


def run_tenvad(args: argparse.Namespace) -> None:
    from sklearn import metrics

    systems = load_systems(args.versions)
    labels, curves = [], {(s, c): [] for s in systems for c in CONDITIONS}
    for name, samples, segments in tenvad_recordings(args.root):
        for condition, audio in conditions_of(samples).items():
            for system, run in systems.items():
                curves[system, condition].append(run(audio)[0])
        labels.append(frame_labels(curves["original", "clean"][-1].size, segments))
        print(f"{name}: {labels[-1].size} frames", file=sys.stderr, flush=True)

    pooled = np.concatenate(labels)
    rng = np.random.default_rng(0)
    draws = [rng.integers(0, len(labels), len(labels)) for _ in range(args.resamples)]

    def auc(curve_list: list[np.ndarray], picks=None) -> float:
        if picks is None:
            return float(metrics.roc_auc_score(pooled, np.concatenate(curve_list)))
        return float(
            metrics.roc_auc_score(
                np.concatenate([labels[i] for i in picks]), np.concatenate([curve_list[i] for i in picks])
            )
        )

    result = {"recordings": len(labels), "frames": int(pooled.size), "speech_fraction": float(pooled.mean()), "systems": {}}
    for (system, condition), curve_list in curves.items():
        probs = np.concatenate(curve_list)
        scores = {
            "auc": auc(curve_list),
            "f1": float(metrics.f1_score(pooled, probs > 0.5)),
            "accuracy": float(((probs > 0.5) == pooled).mean()),
        }
        if system != "original":
            base = curves["original", condition]
            diffs = np.array([auc(curve_list, d) - auc(base, d) for d in draws])
            scores["auc_minus_original"] = scores["auc"] - auc(base)
            scores["auc_minus_original_ci"] = [float(np.percentile(diffs, 2.5)), float(np.percentile(diffs, 97.5))]
            scores["frames_flipped"] = float(((probs > 0.5) != (np.concatenate(base) > 0.5)).mean())
        result["systems"][f"{system}/{condition}"] = scores
    args.out.parent.mkdir(parents=True, exist_ok=True)
    args.out.write_text(json.dumps(result, indent=1) + "\n", encoding="utf-8")
    print(json.dumps(result, indent=1))


# --- pipecat smart-turn test: is the turn complete at the clip's end? -------------------------

PIPECAT_COLUMNS = ("id", "language", "endpoint_bool", "synthetic", "dataset", "audio")


def _init_worker(versions: list[Path]) -> None:
    _systems.update(load_systems(versions))


def _score_shard(job: tuple[Path, Path, int | None]) -> int:
    """Score one parquet shard into a JSONL file; clips already in the file are skipped."""
    import soundfile
    from inworld.sava import audio
    from pyarrow import parquet

    shard, out_path, limit = job
    done = set()
    if out_path.exists():
        done = {json.loads(line)["id"] for line in out_path.read_text(encoding="utf-8").splitlines() if line}
    table = parquet.ParquetFile(shard)
    count = 0
    with open(out_path, "a", encoding="utf-8") as out:
        for group in range(table.num_row_groups):
            for row in table.read_row_group(group, columns=list(PIPECAT_COLUMNS)).to_pylist():
                count += 1
                if limit is not None and count > limit:
                    return count - 1
                if row["id"] in done:
                    continue
                samples, rate = soundfile.read(io.BytesIO(row["audio"]["bytes"]), dtype="float32", always_2d=True)
                samples = audio.to_model_rate(samples, rate)
                record = {key: row[key] for key in PIPECAT_COLUMNS if key != "audio"}
                record["seconds"] = samples.size / 16000
                for condition, heard in conditions_of(samples).items():
                    for system, run in _systems.items():
                        # The clip's score is the end-of-turn probability at its last frame.
                        record[f"{system}/{condition}"] = float(run(heard)[1][-1])
                out.write(json.dumps(record) + "\n")
                out.flush()
    return count


def run_pipecat(args: argparse.Namespace) -> None:
    shards = sorted(args.root.rglob("*.parquet"))
    if not shards:
        raise FileNotFoundError(f"no parquet shards under {args.root}")
    args.out.mkdir(parents=True, exist_ok=True)
    jobs = [(shard, args.out / f"{shard.stem}.jsonl", args.limit) for shard in shards]
    started = time.time()
    with multiprocessing.Pool(args.workers, _init_worker, (args.versions,)) as pool:
        for clips in pool.imap_unordered(_score_shard, jobs):
            print(f"shard done: {clips} clips, {time.time() - started:.0f} s", file=sys.stderr, flush=True)
    report_pipecat(args)


def report_pipecat(args: argparse.Namespace) -> None:
    from sklearn import metrics

    rows = [json.loads(line) for path in sorted(args.out.glob("*.jsonl")) for line in path.read_text().splitlines() if line]
    labels = np.array([r["endpoint_bool"] for r in rows], dtype=bool)
    keys = [k for k in rows[0] if "/" in k]
    rng = np.random.default_rng(0)
    draws = rng.integers(0, len(rows), (args.resamples, len(rows)))
    result = {"clips": len(rows), "hours": sum(r["seconds"] for r in rows) / 3600, "complete_fraction": float(labels.mean()), "systems": {}}
    correct = {k: (np.array([r[k] for r in rows]) > 0.5) == labels for k in keys}
    for key in keys:
        probs = np.array([r[key] for r in rows])
        scores = {"accuracy": float(correct[key].mean()), "auc": float(metrics.roc_auc_score(labels, probs))}
        system, condition = key.split("/")
        if system != "original":
            base_key = f"original/{condition}"
            base = np.array([r[base_key] for r in rows])
            diffs = correct[key][draws].mean(axis=1) - correct[base_key][draws].mean(axis=1)
            scores["accuracy_minus_original"] = scores["accuracy"] - float(correct[base_key].mean())
            scores["accuracy_minus_original_ci"] = [float(np.percentile(diffs, 2.5)), float(np.percentile(diffs, 97.5))]
            scores["clips_flipped"] = float(((probs > 0.5) != (base > 0.5)).mean())
            scores["mean_change"] = float(np.abs(probs - base).mean())
        result["systems"][key] = 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 ("tenvad", "pipecat", "pipecat-report"):
        command = commands.add_parser(name)
        command.add_argument("--root", type=Path, help="the dataset download")
        command.add_argument("--out", type=Path, required=True)
        command.add_argument("--versions", type=Path, nargs="+", default=[Path("build/sava.onnx"), Path("build/sava.int8.onnx")])
        command.add_argument("--resamples", type=int, default=2000)
        command.add_argument("--workers", type=int, default=8)
        command.add_argument("--limit", type=int, default=None, help="clips per shard (pipecat)")
    args = parser.parse_args()
    {"tenvad": run_tenvad, "pipecat": run_pipecat, "pipecat-report": report_pipecat}[args.command](args)


if __name__ == "__main__":
    main()