File size: 17,053 Bytes
edc8e43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
#!/usr/bin/env python3
"""
test_api_benchmark.py β€” Test the Local DE Coach backend API **like a real user**:
send random audio clips from the private HF dataset Local-DE-Coach/dataset
(Thorsten-DE v0.2 sorted by CEFR) straight to `POST /api/score` and measure

  * RESPONSE TIME  β€” client wall time per request (mean / p50 / p95 / max),
                     plus the server's own latency_ms and inference_ms
  * QUALITY        β€” HTTP success rate, JSON schema completeness, the
                     project's score + passed flag, and WER/CER of the
                     returned transcript vs the reference text
  * RELIABILITY    β€” stuck-request detection, 503 warm-up handling,
                     decode failures (422), per-clip ID tracing

A "real user session" looks like:  GET /api/health  ->  GET /api/status
(wait for model)  ->  N x POST /api/score with random audio.

Every result row carries the clip `file_id`, so any slow / broken / bad
clip can be retried and debugged directly:

      python scripts/test_api_benchmark.py --ids <file_id> [<file_id> ...]

Usage
-----
# 1) start the backend (default http://127.0.0.1:22111):
cd backend && uvicorn server:app --host 127.0.0.1 --port 22111

# 2) run the benchmark (15 random clips x 3 CEFR levels by default):
export HF_TOKEN=hf_YOUR_TOKEN
python scripts/test_api_benchmark.py --per-bucket 15
python scripts/test_api_benchmark.py --buckets Easy_A1_A2 --seed 42
python scripts/test_api_benchmark.py --ids 3a3675eb63255a6bd7d30   # retry by ID
"""
from __future__ import annotations

import argparse
import io
import json
import os
import re
import sys
import time
from pathlib import Path

import pandas as pd
import requests

BUCKETS = ["Easy_A1_A2", "Medium_B1_B2", "Hard_C1"]
REPO = "Local-DE-Coach/dataset"
CACHE = Path(__file__).resolve().parent / "hf_test_cache"

# every field a healthy /api/score response must contain (v2.1.1 contract)
REQUIRED_FIELDS = [
    "session_id", "score", "level", "passed", "threshold", "transcribed",
    "audio_duration_s", "layers", "feedback", "srs_updated", "latency_ms",
    "engine", "inference_ms",
]

PUNCT = re.compile(r"[^\w\sÀâüß]", re.IGNORECASE)


def norm(s: str) -> str:
    """Same normalisation as scripts/test_random_hf.py (comparable WERs)."""
    s = PUNCT.sub(" ", str(s).lower())
    return re.sub(r"\s+", " ", s).strip()


# ─────────────────────────── dataset access ───────────────────────────

def fetch_metadata(bucket: str, token: str) -> pd.DataFrame:
    url = f"https://huggingface.co/datasets/{REPO}/resolve/main/{bucket}/metadata.csv"
    r = requests.get(url, headers={"Authorization": f"Bearer {token}"}, timeout=120)
    r.raise_for_status()
    return pd.read_csv(io.BytesIO(r.content))


def get_wav(bucket: str, file_name: str, token: str) -> bytes:
    p = CACHE / bucket / file_name
    if p.is_file():
        return p.read_bytes()
    p.parent.mkdir(parents=True, exist_ok=True)
    url = f"https://huggingface.co/datasets/{REPO}/resolve/main/{bucket}/{file_name}"
    r = requests.get(url, headers={"Authorization": f"Bearer {token}"}, timeout=120)
    r.raise_for_status()
    p.write_bytes(r.content)
    return r.content


# ─────────────────────── real-user API session ────────────────────────

def preflight(api: str) -> dict:
    """The first thing a real client does: check service + model state."""
    out = {}
    for name, path in (("root", "/"), ("health", "/api/health"), ("status", "/api/status")):
        t0 = time.perf_counter()
        try:
            r = requests.get(f"{api}{path}", timeout=10)
            out[name] = {"status": r.status_code,
                         "ms": round((time.perf_counter() - t0) * 1000)}
            if path == "/api/status" and r.status_code == 200:
                j = r.json()
                out["model_state"] = j.get("model_state")
                out["backend_health"] = j.get("health")
                out["score_model"] = j.get("score_model")
                out["score_model_engine"] = j.get("score_model_engine")
                out["worker_ram_mb"] = j.get("worker_ram_mb")
        except Exception as e:  # noqa: BLE001
            out[name] = {"status": f"ERR {type(e).__name__}", "ms": None}
    return out


def wait_for_model(api: str, max_s: float = 120.0) -> bool:
    """Poll /api/status until the ASR model is loaded (real users wait too)."""
    t0 = time.perf_counter()
    while time.perf_counter() - t0 < max_s:
        try:
            j = requests.get(f"{api}/api/status", timeout=10).json()
            state = j.get("model_state") or (j.get("model") or {}).get("state")
            if state in ("loaded", "ready", None):
                return True
            print(f"  [warm-up] model_state={state} … waiting")
        except Exception:  # noqa: BLE001
            pass
        time.sleep(3)
    return False


def post_score(api: str, wav: bytes, ref: str, level: str, timeout: float,
               wait_ready_s: float = 90.0):
    """One user pressing 'record & check'. Returns (result_dict, status, wall_ms).
    status: ok | STUCK_TIMEOUT | CONN_ERROR | DECODE_FAIL_422 | HTTP_xxx"""
    files = {"audio": ("clip.wav", wav, "audio/wav")}
    data = {"target_text": ref, "level": level}
    t0 = time.perf_counter()
    try:
        r = requests.post(f"{api}/api/score", files=files, data=data,
                          timeout=(5, timeout))
    except requests.exceptions.Timeout:
        return None, "STUCK_TIMEOUT", round((time.perf_counter() - t0) * 1000)
    except requests.exceptions.ConnectionError:
        return None, "CONN_ERROR", round((time.perf_counter() - t0) * 1000)
    wall_ms = round((time.perf_counter() - t0) * 1000)

    # 503 while the model is still warming up: poll like a patient client
    waited = 0.0
    while r.status_code == 503 and waited < wait_ready_s:
        time.sleep(5)
        waited += 5
        t1 = time.perf_counter()
        try:
            r = requests.post(f"{api}/api/score", files=files, data=data,
                              timeout=(5, timeout))
        except requests.exceptions.Timeout:
            return None, "STUCK_TIMEOUT", round((time.perf_counter() - t1) * 1000)
    wall_ms = round(wall_ms + waited * 1000)  # warm-up wait counts as UX time

    if r.status_code == 422:
        return None, "DECODE_FAIL_422", wall_ms
    if r.status_code >= 500:
        return None, f"HTTP_{r.status_code}", wall_ms
    if r.status_code >= 400:
        return {"error": r.text[:200]}, f"HTTP_{r.status_code}", wall_ms
    try:
        out = r.json()
    except ValueError:
        return None, "BAD_JSON", wall_ms
    return out, "ok", wall_ms


# ───────────────────────────── reporting ──────────────────────────────

def _num(series: pd.Series) -> pd.Series:
    return pd.to_numeric(series, errors="coerce")


def summarize(df: pd.DataFrame, label: str) -> dict:
    ok = df[df["status"] == "ok"]
    n = len(df)
    s: dict = {"group": label, "clips": n}
    s["http_ok"] = len(ok)
    s["ok_rate"] = round(100 * len(ok) / n, 1) if n else None
    w = _num(ok["wall_ms"]) if len(ok) else pd.Series(dtype=float)
    inf = _num(ok["inference_ms"]) if len(ok) else pd.Series(dtype=float)
    lat = _num(ok["latency_ms"]) if len(ok) else pd.Series(dtype=float)
    if len(w.dropna()):
        s["wall_ms_mean"] = round(w.mean())
        s["wall_ms_p50"] = round(w.quantile(0.50))
        s["wall_ms_p95"] = round(w.quantile(0.95))
        s["wall_ms_max"] = round(w.max())
    else:
        for k in ("wall_ms_mean", "wall_ms_p50", "wall_ms_p95", "wall_ms_max"):
            s[k] = None
    s["inference_ms_mean"] = (round(inf.mean())
                              if len(inf.dropna()) else None)  # null in v2.1.1
    s["server_ms_mean"] = (round(lat.mean())
                           if len(lat.dropna()) else None)
    if len(inf.dropna()):
        rtf = (inf / 1000) / _num(ok["audio_duration_s"])
        s["realtime_factor"] = round(rtf.mean(), 3)   # <1 = faster than speech
    else:
        s["realtime_factor"] = None
    s["schema_complete"] = int(ok["schema_ok"].sum()) if len(ok) else 0
    s["schema_rate"] = round(100 * ok["schema_ok"].mean(), 1) if len(ok) else None
    s["mean_score"] = (round(_num(ok["project_score"]).mean(), 1)
                       if ok["project_score"].notna().any() else None)
    s["pass_rate"] = (round(100 * ok["passed"].astype(bool).mean(), 1)
                      if len(ok) else None)
    s["mean_WER"] = (round(_num(ok["wer"]).mean(), 1)
                     if ok["wer"].notna().any() else None)
    s["mean_CER"] = (round(_num(ok["cer"]).mean(), 1)
                     if ok["cer"].notna().any() else None)
    return s


def flush(rows: list, out_csv: Path) -> None:
    pd.DataFrame(rows).to_csv(out_csv, index=False)


# ──────────────────────────────── main ────────────────────────────────

def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("--api-url", default="http://127.0.0.1:22111")
    ap.add_argument("--token", default=os.environ.get("HF_TOKEN"))
    ap.add_argument("--per-bucket", type=int, default=15)
    ap.add_argument("--seed", type=int, default=21)
    ap.add_argument("--buckets", nargs="+", default=BUCKETS, choices=BUCKETS)
    ap.add_argument("--ids", nargs="+", default=None,
                    help="test exactly these clip file_ids (ignore --per-bucket)")
    ap.add_argument("--timeout", type=float, default=60.0,
                    help="per-request read timeout in seconds (stuck detection)")
    ap.add_argument("--out", default="api_benchmark_results.csv")
    args = ap.parse_args()

    if not args.token:
        sys.exit("No HF token: pass --token or set HF_TOKEN")
    out_csv = Path(args.out)
    out_summary = out_csv.with_name(out_csv.stem + "_summary.csv")
    out_report = out_csv.with_name(out_csv.stem + "_report.json")

    from jiwer import cer, wer

    # ── Phase 0: what every real client does first ──
    print(f"== Preflight {args.api_url} ==")
    pre = preflight(args.api_url)
    print(json.dumps(pre, indent=2))
    if pre.get("health", {}).get("status") != 200:
        sys.exit("Backend not reachable/healthy β€” is `uvicorn server:app` running?")
    if pre.get("model_state") not in ("loaded", "ready", None):
        wait_for_model(args.api_url)

    rows, summaries = [], []
    print(f"\n== Sending random clips ({args.per_bucket}/bucket, seed {args.seed}) ==")
    for bucket in args.buckets:
        meta = fetch_metadata(bucket, args.token)
        if args.ids:
            sub = meta[meta["file_id"].isin(args.ids)]
            if sub.empty:
                print(f"[warn] none of --ids found in {bucket}")
                continue
        else:
            sub = meta.sample(n=min(args.per_bucket, len(meta)),
                              random_state=args.seed)

        print(f"\n=== {bucket}: {len(sub)} clips ===")
        for _, r in sub.iterrows():
            fid = str(r["file_id"])
            ref_raw = str(r["sentence"])
            level = str(r["cefr"])
            try:
                wav = get_wav(bucket, str(r["file_name"]), args.token)
            except Exception as e:  # noqa: BLE001
                print(f"  [download-fail] {fid}: {str(e)[:80]}")
                rows.append({"file_id": fid, "bucket": bucket, "cefr": level,
                             "status": "DOWNLOAD_FAIL", "error": str(e)[:120]})
                continue

            res, status, wall_ms = post_score(args.api_url, wav, ref_raw,
                                              level, args.timeout)
            if res is None:
                print(f"  !! {fid} -> {status} after {wall_ms} ms")
                rows.append({"file_id": fid, "bucket": bucket, "cefr": level,
                             "readability": r["score"], "ref": ref_raw,
                             "wall_ms": wall_ms, "status": status})
            elif status != "ok":
                print(f"  [http] {fid} -> {status}: {str(res.get('error',''))[:80]}")
                rows.append({"file_id": fid, "bucket": bucket, "cefr": level,
                             "readability": r["score"], "ref": ref_raw,
                             "wall_ms": wall_ms, "status": status,
                             "error": str(res.get("error", ""))[:120]})
            else:
                hyp = str(res.get("transcribed", ""))
                w = wer(norm(ref_raw), norm(hyp)) * 100
                c = cer(norm(ref_raw), norm(hyp)) * 100
                schema_ok = all(k in res for k in REQUIRED_FIELDS)
                audio_s = float(res.get("audio_duration_s") or 0)
                rows.append({
                    "file_id": fid, "bucket": bucket, "cefr": level,
                    "readability": r["score"], "ref": ref_raw, "hyp": hyp,
                    "wer": round(w, 2), "cer": round(c, 2),
                    "project_score": res.get("score"),
                    "passed": res.get("passed"),
                    "engine": res.get("engine"),
                    "audio_duration_s": audio_s,
                    "inference_ms": res.get("inference_ms"),
                    "latency_ms": res.get("latency_ms"),
                    "wall_ms": wall_ms,
                    "realtime_factor": round(
                        float(res["inference_ms"]) / 1000 / audio_s, 3
                    ) if (res.get("inference_ms") is not None
                          and audio_s > 0) else None,
                    "schema_ok": schema_ok,
                    "n_feedback_layers": len(res.get("layers") or {}),
                    "status": "ok",
                })
                print(f"  {fid[:12]}… L={level:2} wall={wall_ms:5} ms  "
                      f"inf={res.get('inference_ms')} ms  WER={w:5.1f}%  "
                      f"score={res.get('score'):>3}")
            if len(rows) % 10 == 0:
                flush(rows, out_csv)          # partial save on timeouts
        flush(rows, out_csv)

    df = pd.DataFrame(rows)
    flush(rows, out_csv)
    print(f"\nPer-clip results -> {out_csv}  (every row has file_id for retries)")

    for b in args.buckets:
        part = df[df["bucket"] == b]
        if len(part):
            summaries.append(summarize(part, b))
    if len(df):
        summaries.append(summarize(df, "ALL"))

    summ_df = pd.DataFrame(summaries)
    summ_df.to_csv(out_summary, index=False)
    print("\n===== API BENCHMARK SUMMARY =====")
    cols = ["group", "clips", "ok_rate", "wall_ms_mean", "wall_ms_p50",
            "wall_ms_p95", "wall_ms_max", "inference_ms_mean",
            "realtime_factor", "schema_rate", "mean_score", "pass_rate",
            "mean_WER"]
    print(summ_df[[c for c in cols if c in summ_df]].to_string(index=False))

    bad = df[df["status"] != "ok"]
    slow = df[(df["status"] == "ok") &
              (df["wall_ms"].astype(float) > 5000)] if len(df) else []
    lowq = df[(df["status"] == "ok") &
              (df["wer"].astype(float) > 60)] if len(df) else []
    report = {
        "generated": time.strftime("%Y-%m-%d %H:%M:%S"),
        "api_url": args.api_url, "seed": args.seed,
        "backend": {"score_model": pre.get("score_model"),
                    "engine": pre.get("score_model_engine"),
                    "health": pre.get("backend_health"),
                    "worker_ram_mb": pre.get("worker_ram_mb")},
        "preflight": pre,
        "summary": summaries,
        "problem_clips": bad[["file_id", "bucket", "status", "wall_ms"]].to_dict("records"),
        "slow_clips_gt5s": (slow[["file_id", "bucket", "wall_ms"]].to_dict("records")
                            if len(slow) else []),
        "low_quality_clips_wer_gt60": (lowq[["file_id", "bucket", "wer",
                                             "project_score", "ref", "hyp"]]
                                       .to_dict("records") if len(lowq) else []),
    }
    out_report.write_text(json.dumps(report, indent=2, ensure_ascii=False))
    print(f"Report JSON -> {out_report}")

    if len(bad):
        print(f"\n===== {len(bad)} problem clip(s) β€” trace by ID =====")
        print(bad[["file_id", "bucket", "status", "wall_ms"]].to_string(index=False))
    if len(slow):
        print(f"\n===== {len(slow)} slow clip(s) (>5 s wall) =====")
        print(slow[["file_id", "bucket", "wall_ms", "inference_ms"]].to_string(index=False))
    if len(lowq):
        print(f"\n===== {len(lowq)} low-quality clip(s) (WER>60%) β€” IDs for retry =====")
        print(lowq[["file_id", "bucket", "wer", "project_score"]].to_string(index=False))


if __name__ == "__main__":
    main()