#!/usr/bin/env python3 """Offline end-to-end test for the harness. Builds a synthetic dataset with the SAME schema as modulate/entity-transcription-benchmark (id, subset, transcript, entities, entity_types, entity_tiers, entity_offsets, n_entities, duration_s, audio), stands up a fake STT endpoint, and runs the real CLIs against the real matcher_v5. No network and no API keys required. python test_harness.py """ from __future__ import annotations import io import json import os import shutil import subprocess import sys import tempfile import threading import time from http.server import BaseHTTPRequestHandler, HTTPServer import numpy as np HERE = os.path.dirname(os.path.abspath(__file__)) # id, transcript, entities, types, per-span tiers, subset, what the fake STT returns CLIPS = [ ("c001", "Nadia Boulanger taught in Paris", ["Nadia Boulanger", "Paris"], ["PERSON", "GPE"], ["A", "A"], "synthetic", "nadia boulanger taught in paris"), ("c002", "Addenbrooke's Hospital is in Cambridge", ["Addenbrooke's Hospital", "Cambridge"], ["ORG", "GPE"], ["A", "B"], "meetings", "addenbrookes hospital is in cambridge"), ("c003", "The Mapuche live in Chile", ["Mapuche", "Chile"], ["NORP", "GPE"], ["A", "A"], "belebele", "the mapoochay live in chilly"), ("c004", "Ikeda visited Osaka", ["Ikeda", "Osaka"], ["PERSON", "GPE"], ["A", "B"], "synthetic", "ikeda visited osaka"), ("c005", "nothing named here at all", [], [], [], "meetings", "nothing named here at all"), ("c006", "Trivial mention of London", ["London"], ["GPE"], ["B"], "belebele", "trivial mention of london"), ] class FakeSTT(BaseHTTPRequestHandler): order: list[str] = [] served = 0 def do_POST(self): # noqa: N802 self.rfile.read(int(self.headers.get("Content-Length", 0))) if self.headers.get("Authorization") != "Bearer test-key-123": self.send_response(401) self.end_headers() self.wfile.write(b'{"error":"bad key"}') return cls = type(self) body = json.dumps({"result": {"transcript": cls.order[cls.served % len(cls.order)]}}).encode() cls.served += 1 self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def log_message(self, *args): pass def build_dataset(path: str) -> None: import soundfile as sf from datasets import Audio, Dataset rng = np.random.default_rng(0) rows: dict[str, list] = {k: [] for k in ( "audio", "id", "subset", "transcript", "entities", "entity_types", "n_entities", "duration_s", "entity_tiers", "entity_offsets")} for clip_id, text, entities, types, tiers, subset, _ in CLIPS: buf = io.BytesIO() sf.write(buf, rng.normal(0, 0.01, 8000).astype(np.float32), 16000, format="WAV", subtype="PCM_16") rows["audio"].append({"bytes": buf.getvalue(), "path": f"{clip_id}.wav"}) rows["id"].append(f"named_entities-{subset}-{clip_id}") rows["subset"].append(subset) rows["transcript"].append(text) # stored as JSON strings, exactly as the published parquet does rows["entities"].append(json.dumps(entities)) rows["entity_types"].append(json.dumps(types)) rows["entity_tiers"].append(json.dumps(tiers)) rows["n_entities"].append(len(entities)) rows["duration_s"].append(0.5) rows["entity_offsets"].append(json.dumps( [{"start": text.find(e), "end": text.find(e) + len(e), "label": t, "text": e} for e, t in zip(entities, types)])) Dataset.from_dict(rows).cast_column("audio", Audio(decode=False)).save_to_disk(path) def run(cmd: list[str], env: dict) -> subprocess.CompletedProcess: return subprocess.run(cmd, cwd=HERE, env={**os.environ, **env}, capture_output=True, text=True) def main() -> int: matcher_path = os.path.join(HERE, "matcher_v5.py") if not os.path.exists(matcher_path): print("matcher_v5.py is not next to this script -- copy it in first:") print(" cp ../bench2/matcher_v5.py .") return 2 sys.path.insert(0, HERE) import matcher_v5 # noqa: E402 work = tempfile.mkdtemp(prefix="ebench_") dataset_path = os.path.join(work, "ds") hyps = os.path.join(work, "run.jsonl") failures: list[str] = [] def check(label: str, ok: bool, detail: str = "") -> None: print(f" [{'ok' if ok else 'FAIL'}] {label}" + (f" -- {detail}" if detail and not ok else "")) if not ok: failures.append(label) # Ground truth computed by calling the matcher directly, so the test checks # the harness plumbing (tier filter, join, aggregation) not the match rule. tier_a, tier_all = [], [] for clip_id, _, entities, types, tiers, _, hypothesis in CLIPS: for entity, tier in zip(entities, tiers): outcome = bool(matcher_v5.hit(entity, hypothesis)) tier_all.append(outcome) if tier == "A": tier_a.append(outcome) expect_a_spans, expect_a_hits = len(tier_a), sum(tier_a) expect_all_spans = len(tier_all) print(f"matcher_v5 self-test: {matcher_v5.validate(verbose=False)} ({len(matcher_v5.CASES)} cases)") print(f"expected tier-A: {expect_a_hits}/{expect_a_spans} spans; all tiers: {expect_all_spans} spans\n") print("building fixture dataset...") build_dataset(dataset_path) FakeSTT.order = [c[6] for c in CLIPS] server = HTTPServer(("127.0.0.1", 0), FakeSTT) port = server.server_address[1] threading.Thread(target=server.serve_forever, daemon=True).start() time.sleep(0.2) base = [ sys.executable, "run_benchmark.py", "--provider", "http", "--endpoint", f"http://127.0.0.1:{port}/stt", "--api-key-env", "TEST_STT_KEY", "--response-path", "result.transcript", "--local-path", dataset_path, "--workers", "1", ] good = {"TEST_STT_KEY": "test-key-123"} print("collection:") proc = run(base + ["--out", hyps], good) check("run_benchmark exits clean", proc.returncode == 0, proc.stderr[-600:]) check("columns resolved from real schema", "transcript" in proc.stderr and "entity_tiers" in proc.stderr, proc.stderr[:400]) records = [json.loads(l) for l in open(hyps)] if os.path.exists(hyps) else [] check("all 6 clips transcribed by default", len(records) == 6, f"got {len(records)}") check("no failed clips", all(r.get("hypothesis") is not None for r in records)) check("manifest written", os.path.exists(os.path.splitext(hyps)[0] + ".manifest.json")) print("\nauth failure surfaces:") bad = run(base + ["--out", os.path.join(work, "bad.jsonl")], {"TEST_STT_KEY": "wrong"}) check("bad key does not silently score", bad.returncode != 0 or "401" in bad.stderr) print("\nresume:") before = len(open(hyps).readlines()) again = run(base + ["--out", hyps], good) check("rerun is a no-op", again.returncode == 0 and len(open(hyps).readlines()) == before) print("\nscoring (tier A, the published protocol):") scored = run([sys.executable, "score_benchmark.py", "--hyps", hyps, "--local-path", dataset_path], {}) check("score_benchmark exits clean", scored.returncode == 0, scored.stderr[-700:]) summary_path = os.path.splitext(hyps)[0] + ".summary.json" summary = json.load(open(summary_path)) if os.path.exists(summary_path) else {} check("summary written", bool(summary)) if summary: check(f"tier-A spans only ({expect_a_spans})", summary["entity_spans"] == expect_a_spans, str(summary.get("entity_spans"))) check(f"hits match direct matcher calls ({expect_a_hits})", summary["entity_hits"] == expect_a_hits, str(summary.get("entity_hits"))) check("tier-B spans excluded", summary["entity_spans"] < expect_all_spans) check("matcher self-test gate = 49/49", summary["matcher_self_test"] == f"{len(matcher_v5.CASES)}/{len(matcher_v5.CASES)}", str(summary.get("matcher_self_test"))) check("WER covers every transcribed clip", summary["clips_with_hypothesis"] == 6) check("WER computed", summary["wer"] is not None) check("subset breakdown present", bool(summary["by_subset"]) and set(summary["by_subset"]) <= {"synthetic", "meetings", "belebele"}) check("provider recorded", summary["provider"] == "http") hits_csv = os.path.splitext(hyps)[0] + ".hits.csv" check("per-span hits CSV written", os.path.exists(hits_csv)) if os.path.exists(hits_csv): check("hits CSV carries tier column", "tier" in open(hits_csv).readline()) print("\nscoring (tier all):") every = run([sys.executable, "score_benchmark.py", "--hyps", hyps, "--local-path", dataset_path, "--tier", "all", "--out-prefix", os.path.join(work, "all")], {}) all_summary = os.path.join(work, "all.summary.json") ok = os.path.exists(all_summary) and json.load(open(all_summary))["entity_spans"] == expect_all_spans check(f"tier all scores every span ({expect_all_spans})", every.returncode == 0 and ok, every.stderr[-400:]) print("\ncompare / diff:") diffed = run([sys.executable, "score_benchmark.py", "--hyps", hyps, "--local-path", dataset_path, "--compare", hits_csv], {}) check("self-diff reports zero disagreements", "disagreements 0" in diffed.stdout, diffed.stdout[-400:]) print("\nmissing matcher is fatal, not silent:") nomatcher = run([sys.executable, "score_benchmark.py", "--hyps", hyps, "--local-path", dataset_path, "--matcher-path", os.path.join(work, "nope.py")], {}) check("refuses to score without a real matcher path", nomatcher.returncode != 0) print("\nclip-level tier filter (collection):") a_only = os.path.join(work, "a.jsonl") FakeSTT.served = 0 filt = run(base + ["--tier", "A", "--out", a_only], good) expect_clips = sum(1 for c in CLIPS if "A" in c[4]) check(f"--tier A skips clips with no A span ({expect_clips})", filt.returncode == 0 and len(open(a_only).readlines()) == expect_clips, filt.stderr[-400:]) server.shutdown() shutil.rmtree(work, ignore_errors=True) print() if failures: print(f"{len(failures)} FAILED: {failures}") return 1 print("all checks passed") return 0 if __name__ == "__main__": sys.exit(main())