Spaces:
Sleeping
Sleeping
feat: real-time CPU pipeline, pre-ASR gates, and 20-clip benchmark
#2
by Captivater - opened
Files changed (38)
- .gitattributesAdded+18
- eval_harness/SCQC_Independent_Benchmark.ipynbAdded+59
- eval_harness/clips/en_clean_02.wavAdded+3
- eval_harness/clips/en_compound_split_06.wavAdded+3
- eval_harness/clips/en_idle_trailing_16.wavAdded+3
- eval_harness/clips/en_ins_filler_13.wavAdded+3
- eval_harness/clips/en_mid_stumble_18.wavAdded+3
- eval_harness/clips/en_muted_silence_20.wavAdded
- eval_harness/clips/en_numeral_fold_07.wavAdded+3
- eval_harness/clips/en_orthographic_04.wavAdded+3
- eval_harness/clips/en_skip_initial_10.wavAdded+3
- eval_harness/clips/en_sub_semantic_12.wavAdded+3
- eval_harness/clips/hi_accent_nukta_03.wavAdded+3
- eval_harness/clips/hi_clean_01.wavAdded+3
- eval_harness/clips/hi_clipped_19.wavAdded+3
- eval_harness/clips/hi_compound_split_05.wavAdded+3
- eval_harness/clips/hi_idle_leading_15.wavAdded+3
- eval_harness/clips/hi_rushed_short_17.wavAdded
- eval_harness/clips/hi_skip_content_08.wavAdded+3
- eval_harness/clips/hi_skip_short_final_09.wavAdded+3
- eval_harness/clips/hi_sub_semantic_11.wavAdded+3
- eval_harness/clips/hi_word_swap_14.wavAdded+3
- eval_harness/ground_truth.csvAdded+21
- eval_harness/record_clips.pyAdded+80
- eval_harness/run_benchmark.pyAdded+102
- scqc/align.py+190-172
- scqc/asr.py+382-326
- scqc/audio.py+286-236
- scqc/checks/tasks.py+5-2
- scqc/checks/universal.py+172-154
- scqc/confidence.py+248-229
- scqc/pipeline.py+212-211
- scqc/textnorm.py+144-94
- scqc/thresholds.py+76-76
- server/app.py
- server/auth.py+127-92
- server/static/participant.js+549-546
- tests/test_accounts_ledger.py+145-130
123456789101112131415161718eval_harness/clips/en_clean_02.wav filter=lfs diff=lfs merge=lfs -texteval_harness/clips/en_compound_split_06.wav filter=lfs diff=lfs merge=lfs -texteval_harness/clips/en_idle_trailing_16.wav filter=lfs diff=lfs merge=lfs -texteval_harness/clips/en_ins_filler_13.wav filter=lfs diff=lfs merge=lfs -texteval_harness/clips/en_mid_stumble_18.wav filter=lfs diff=lfs merge=lfs -texteval_harness/clips/en_numeral_fold_07.wav filter=lfs diff=lfs merge=lfs -texteval_harness/clips/en_orthographic_04.wav filter=lfs diff=lfs merge=lfs -texteval_harness/clips/en_skip_initial_10.wav filter=lfs diff=lfs merge=lfs -texteval_harness/clips/en_sub_semantic_12.wav filter=lfs diff=lfs merge=lfs -texteval_harness/clips/hi_accent_nukta_03.wav filter=lfs diff=lfs merge=lfs -texteval_harness/clips/hi_clean_01.wav filter=lfs diff=lfs merge=lfs -texteval_harness/clips/hi_clipped_19.wav filter=lfs diff=lfs merge=lfs -texteval_harness/clips/hi_compound_split_05.wav filter=lfs diff=lfs merge=lfs -texteval_harness/clips/hi_idle_leading_15.wav filter=lfs diff=lfs merge=lfs -texteval_harness/clips/hi_skip_content_08.wav filter=lfs diff=lfs merge=lfs -texteval_harness/clips/hi_skip_short_final_09.wav filter=lfs diff=lfs merge=lfs -texteval_harness/clips/hi_sub_semantic_11.wav filter=lfs diff=lfs merge=lfs -texteval_harness/clips/hi_word_swap_14.wav filter=lfs diff=lfs merge=lfs -text1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859{
"nbformat": 4,
"nbformat_minor": 5,
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"name": "python",
"version": "3.11.0"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# SCQC Independent Evaluation Pipeline (CPU Benchmark)\n",
"Repeatable quality checks, feedback verification, and CPU Real-Time Factor (RTF) benchmarks across your recorded Hindi & English dataset\u2014completely independent of Hugging Face Space resets."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!git clone https://huggingface.co/spaces/srinivas-v/SCQC /content/SCQC 2>/dev/null || (cd /content/SCQC && git pull)\n",
"%cd /content/SCQC\n",
"!pip install -q -r requirements.txt soundfile scipy transformers torch"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Optional: copy your recorded eval_harness/clips folder from Google Drive\n",
"# from google.colab import drive\n",
"# drive.mount('/content/drive')\n",
"# !cp -r /content/drive/MyDrive/eval_harness/clips /content/SCQC/eval_harness/"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Benchmark with simulated transcripts OR a live CPU ASR model:\n",
"!python eval_harness/run_benchmark.py --asr simulated\n",
"# !python eval_harness/run_benchmark.py --asr hf:openai/whisper-small"
]
}
]
}123version https://git-lfs.github.com/spec/v1oid sha256:c98deac4ea09f7b9bc1b4ad2751323732da0f61185ea44fdd998782f034c5f74size 176044123version https://git-lfs.github.com/spec/v1oid sha256:e3eaad9de1584ba74cefea95e582b593da82f6599e1df0e54e08c12ea7b26c16size 176044123version https://git-lfs.github.com/spec/v1oid sha256:a41b3e0ac975d583f132f8f476778b9a47ca32fb0dea18317b0fde80f5cc4918size 336044123version https://git-lfs.github.com/spec/v1oid sha256:e5069a894d93ca6717a7d86000969756efcfa0fb3f4fe2064fa8ecd8d5670677size 176044123version https://git-lfs.github.com/spec/v1oid sha256:0e4e7208d3f51938a725a2e7686c238367fc2f1ddd1327c21f1ccd7228b53a11size 256044123version https://git-lfs.github.com/spec/v1oid sha256:98917aa3bac1e687f1e0ce6c6dd82c49b901ffa1dc00905921f8250de0e5e0c5size 176044123version https://git-lfs.github.com/spec/v1oid sha256:1043ae8a571714d16695f46d3c97bcebcfb95a5e1f4d5595d72ca3bfb5579de8size 176044123version https://git-lfs.github.com/spec/v1oid sha256:5c0f1f83c58600180ededa480bb5162350c1962e1a79fef57712109ec09817d1size 176044123version https://git-lfs.github.com/spec/v1oid sha256:f4d1c02298cfa82c7205a6fdd809f757aac1ca3d04a42c73da614c8579d8c1f9size 176044123version https://git-lfs.github.com/spec/v1oid sha256:d6c1613789654a35b6149e2d3f7b46558602545df2b2d23089157d232b0d3f59size 176044123version https://git-lfs.github.com/spec/v1oid sha256:4fdfa725f5d832737058988f913160953e34b8df2501fd94829e2da265f3abdfsize 176044123version https://git-lfs.github.com/spec/v1oid sha256:61dff99ff44caaddfb2d1628a654c21d7c9a775406534e80ae0eb2f98e27876csize 176044123version https://git-lfs.github.com/spec/v1oid sha256:4644e082c2b059faaac4f72d5a698881160cadc9172373f5270f88c4fe5d4afcsize 176044123version https://git-lfs.github.com/spec/v1oid sha256:5b54223ca4665dd797406c8761d796e7d2d80ce78b47385db4a2cc8133b5613csize 336044123version https://git-lfs.github.com/spec/v1oid sha256:ead40d185961d6f6eccf8a6274b0cd6295913935d0fcd22090961a615076df86size 176044123version https://git-lfs.github.com/spec/v1oid sha256:9631fcc66d48f9e212191a608b97cdfbb5a1976cf65929c8935255b834e99d6asize 176044123version https://git-lfs.github.com/spec/v1oid sha256:95cabddfc3fb06c3c4b72d44ae2eabf185cb51b8b46ddb8cab9f46e9eab9c475size 176044123version https://git-lfs.github.com/spec/v1oid sha256:790eefe3fb03c38c7e4d2278c7aa3303f1ac8c78555c04155a6be8dabda73ff8size 176044123456789101112131415161718192021clip_id,wav_path,language,task_type,prompt_text,simulated_asr,expected_decision,expected_issue,notes
hi_clean_01,eval_harness/clips/hi_clean_01.wav,hi,read_speech,आज सुबह मैंने खिड़की के पास बैठकर चाय पी।,आज सुबह मैंने खिड़की के पास बैठकर चाय पी,accepted,none,Clean Hindi baseline read
en_clean_02,eval_harness/clips/en_clean_02.wav,en,read_speech,Please open the window near the desk before starting the meeting.,please open the window near the desk before starting the meeting,accepted,none,Clean English baseline read
hi_accent_nukta_03,eval_harness/clips/hi_accent_nukta_03.wav,hi,read_speech,आज सुबह मैंने खिड़की के पास बैठकर चाय पी।,आज सुबह मैंने खिरकी के पास बैठकर चाय पी,accepted,none,Hindi regional retroflex/nukta variant
en_orthographic_04,eval_harness/clips/en_orthographic_04.wav,en,read_speech,We need to analyze the data before tomorrow morning.,we need to analyse the data before tomorrow morning,accepted,none,English UK/US spelling variant (analyse vs analyze)
hi_compound_split_05,eval_harness/clips/hi_compound_split_05.wav,hi,read_speech,आज सुबह मैंने खिड़की के पास बैठकर चाय पी।,आज सुबह मैंने खिड़की के पास बैठ कर चाय पी,accepted,none,Hindi compound word split via micro-pause
en_compound_split_06,eval_harness/clips/en_compound_split_06.wav,en,read_speech,Please check the setup instructions on the first page.,please check the set up instructions on the first page,accepted,none,English compound word split (set up vs setup)
en_numeral_fold_07,eval_harness/clips/en_numeral_fold_07.wav,en,read_speech,The train will arrive at platform twenty in five minutes.,the train will arrive at platform 20 in 5 minutes,accepted,none,English spoken numeral vs digit output
hi_skip_content_08,eval_harness/clips/hi_skip_content_08.wav,hi,read_speech,आज सुबह मैंने खिड़की के पास बैठकर चाय पी।,आज सुबह मैंने के पास बैठकर चाय पी,review,skipped_word,Mid-sentence content word skip (खिड़की)
hi_skip_short_final_09,eval_harness/clips/hi_skip_short_final_09.wav,hi,read_speech,आज सुबह मैंने खिड़की के पास बैठकर चाय पी।,आज सुबह मैंने खिड़की के पास बैठकर चाय,review,skipped_word,Short sentence-final word skip (पी)
en_skip_initial_10,eval_harness/clips/en_skip_initial_10.wav,en,read_speech,Please open the window near the desk before starting the meeting.,open the window near the desk before starting the meeting,review,skipped_word,Sentence-initial word skip (please)
hi_sub_semantic_11,eval_harness/clips/hi_sub_semantic_11.wav,hi,read_speech,आज सुबह मैंने खिड़की के पास बैठकर चाय पी।,आज सुबह मैंने दरवाजे के पास बैठकर चाय पी,review,substituted_word,Hindi single-word semantic substitution
en_sub_semantic_12,eval_harness/clips/en_sub_semantic_12.wav,en,read_speech,Please open the window near the desk before starting the meeting.,please open the door near the desk before starting the meeting,review,substituted_word,English single-word semantic substitution
en_ins_filler_13,eval_harness/clips/en_ins_filler_13.wav,en,read_speech,Please open the window near the desk before starting the meeting.,please open the big window near the desk before starting the meeting,review,extra_word,English extra inserted modifier (big)
hi_word_swap_14,eval_harness/clips/hi_word_swap_14.wav,hi,read_speech,आज सुबह मैंने खिड़की के पास बैठकर चाय पी।,आज सुबह मैंने खिड़की बैठकर के पास चाय पी,review,word_order_swap,Adjacent word transposition
hi_idle_leading_15,eval_harness/clips/hi_idle_leading_15.wav,hi,read_speech,आज सुबह मैंने खिड़की के पास बैठकर चाय पी।,आज सुबह मैंने खिड़की के पास बैठकर चाय पी,retry,leading_silence,6 seconds of leading dead air before speech
en_idle_trailing_16,eval_harness/clips/en_idle_trailing_16.wav,en,read_speech,Please open the window near the desk before starting the meeting.,please open the window near the desk before starting the meeting,retry,trailing_silence,5.5 seconds of trailing dead air after speech
hi_rushed_short_17,eval_harness/clips/hi_rushed_short_17.wav,hi,read_speech,रेलवे स्टेशन पहुँचने में हमें लगभग बीस मिनट लगे।,रेलवे स्टेशन पहुँचने में,retry,duration_too_short,Rushed/cut-off speech below duration T_min
en_mid_stumble_18,eval_harness/clips/en_mid_stumble_18.wav,en,read_speech,The train will arrive at platform twenty in five minutes.,the train will arrive at platform twenty in five minutes,review,mid_sentence_pause,2.2s hesitation pause mid-sentence
hi_clipped_19,eval_harness/clips/hi_clipped_19.wav,hi,read_speech,आज सुबह मैंने खिड़की के पास बैठकर चाय पी।,आज सुबह मैंने खिड़की के पास बैठकर चाय पी,retry,clipping,Clipped microphone waveform
en_muted_silence_20,eval_harness/clips/en_muted_silence_20.wav,en,read_speech,We need to analyze the data before tomorrow morning.,,blocked,no_speech,Muted microphone / zero speech energy1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980"""Interactive CLI Voice Recorder for the 20-Scenario SCQC Benchmark."""from __future__ import annotations
import csvfrom pathlib import Path
import numpy as npimport sounddevice as sdimport soundfile as sf
SR = 16000
INSTRUCTIONS = { "hi_clean_01": "Read naturally at a normal pace.", "en_clean_02": "Read naturally at a normal pace.", "hi_accent_nukta_03": "Read naturally (pronounce 'खिड़की' casually like 'खिरकी').", "en_orthographic_04": "Read naturally at a normal pace.", "hi_compound_split_05": "Pause briefly between 'बैठ' and 'कर'.", "en_compound_split_06": "Pause briefly between 'set' and 'up'.", "en_numeral_fold_07": "Read 'twenty' and 'five' normally.", "hi_skip_content_08": "INTENTIONALLY SKIP the word 'खिड़की'.", "hi_skip_short_final_09": "INTENTIONALLY SKIP the last word 'पी'.", "en_skip_initial_10": "INTENTIONALLY SKIP the first word 'Please'.", "hi_sub_semantic_11": "Say 'दरवाजे' INSTEAD OF 'खिड़की'.", "en_sub_semantic_12": "Say 'door' INSTEAD OF 'window'.", "en_ins_filler_13": "Insert 'big' before 'window' ('...open the big window...').", "hi_word_swap_14": "Swap 'के पास बैठकर' -> say 'बैठकर के पास'.", "hi_idle_leading_15": "WAIT 6 SECONDS IN SILENCE after pressing Enter, then read.", "en_idle_trailing_16": "Read normally, then STAY SILENT FOR 5.5 SECONDS until recording ends.", "hi_rushed_short_17": "Say ONLY the first 2 words ('रेलवे स्टेशन') in < 0.6s and stop.", "en_mid_stumble_18": "Read half the sentence, PAUSE 2.2 SECONDS mid-sentence, then finish.", "hi_clipped_19": "Speak very close/loud into the mic to test clipping.", "en_muted_silence_20": "DO NOT SPEAK AT ALL (stay completely silent for 3 seconds).",}
DURATIONS = { "hi_idle_leading_15": 10.5, "en_idle_trailing_16": 10.5, "hi_rushed_short_17": 3.0, "en_mid_stumble_18": 8.0, "en_muted_silence_20": 3.0,}
def main() -> None: rows = list(csv.DictReader(open("eval_harness/ground_truth.csv", encoding="utf-8"))) Path("eval_harness/clips").mkdir(parents=True, exist_ok=True) print(f"Found {len(rows)} scenarios. Press Enter to record each clip (or 's' to skip).\n")
for idx, r in enumerate(rows, 1): cid = r["clip_id"] out_path = Path(r["wav_path"]) dur = DURATIONS.get(cid, 5.5) status = "EXISTS" if out_path.exists() else "MISSING"
print("=" * 80) print(f"[{idx}/20] {cid} ({r['language'].upper()}) [{status}]") print(f"PROMPT : {r['prompt_text']}") print(f"ACTION : {INSTRUCTIONS.get(cid, r['notes'])}") print(f"WINDOW : {dur:.1f} seconds")
while True: cmd = input("Press [Enter] to record, [s] to skip, [q] to quit: ").strip().lower() if cmd == "q": return if cmd == "s": break print(f" >>> RECORDING ({dur:.1f}s)...") rec = sd.rec(int(dur * SR), samplerate=SR, channels=1, dtype="float32") sd.wait() peak = float(np.max(np.abs(rec))) sf.write(str(out_path), rec[:, 0], SR, subtype="PCM_16") print(f" >>> Saved {out_path} (peak={peak:.3f})") redo = input(" Press [Enter] to accept & continue, or [r] to re-record: ").strip().lower() if redo != "r": break
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102"""Independent CPU & QC Benchmark Harness for SCQC (Hindi + English, 20 Scenarios).
Works standalone locally or in Google Colab without running the web server.- If a clip's .wav file exists in `eval_harness/clips/`, it loads that real recording.- Otherwise, it synthesizes an acoustic waveform matching the scenario's exact timing/signal profile.- Uses `--asr none` (simulated hypotheses from ground_truth.csv) OR any live CPU backend such as `--asr hf:openai/whisper-small` or `--asr cascaded:...,...`."""from __future__ import annotations
import argparseimport csvimport sysimport timefrom pathlib import Path
import numpy as np
ROOT = Path(__file__).resolve().parents[1]if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT))
from scqc import synthfrom scqc.asr import FixedASR, load_backendfrom scqc.audio import estimate_prompt_durationfrom scqc.checks.universal import RecordingContextfrom scqc.manifest import Prompt, Task, ValidationSpecfrom scqc.pipeline import QCInput, run_qc
def synth_for_scenario(row: dict) -> bytes: cid = row["clip_id"] bounds = estimate_prompt_duration(row["prompt_text"], row["language"]) or (1.5, 4.5) nominal_s = round(0.5 * (bounds[0] + bounds[1]), 2)
if "idle_leading" in cid: x = np.concatenate([synth.silence(6.0), synth.speechlike(nominal_s), synth.silence(0.4)]) elif "idle_trailing" in cid: x = np.concatenate([synth.silence(0.4), synth.speechlike(nominal_s), synth.silence(5.5)]) elif "rushed_short" in cid: x = synth.utterance(speech_s=0.45, pad_s=0.35) elif "mid_stumble" in cid: half = max(0.7, nominal_s / 2.0) x = np.concatenate([synth.silence(0.4), synth.speechlike(half, seed=1), synth.silence(2.2), synth.speechlike(half, seed=2), synth.silence(0.4)]) elif "clipped" in cid: x = synth.utterance(speech_s=nominal_s, pad_s=0.4, level=1.8) elif "muted_silence" in cid: x = synth.silence(2.5, noise_db=-85.0) else: x = synth.utterance(speech_s=nominal_s, pad_s=0.4) return synth.wav_bytes(x)
def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--csv", default="eval_harness/ground_truth.csv") ap.add_argument("--asr", default="simulated", help="'simulated' or any scqc.asr spec") args = ap.parse_args()
rows = list(csv.DictReader(open(args.csv, encoding="utf-8"))) sim_table = {r["clip_id"]: r["simulated_asr"] for r in rows} asr = FixedASR(sim_table, model_id="simulated-gt") if args.asr == "simulated" else load_backend(args.asr)
passed = 0 rtfs = [] print(f"{'CLIP_ID':<22} {'LANG':<4} {'EXP':<9} {'GOT':<9} {'OK':<4} {'SCORE':<6} {'RTF':<7} FEEDBACK") print("-" * 115) for r in rows: cid = r["clip_id"] wav_file = Path(r["wav_path"]) source = str(wav_file) if wav_file.exists() else synth_for_scenario(r) task = Task(task_id=cid, task_type=r["task_type"], language=r["language"], prompt=Prompt(text=r["prompt_text"])) ctx = RecordingContext(cid, r["task_type"], r["language"], speaker_id="bench_user", consent_version="v1", project_consent_version="v1") spec = ValidationSpec(preset="L2", spot_check_rate=0.0)
t0 = time.perf_counter() rep = run_qc(source, QCInput(task, spec, ctx, key=cid), asr=asr) wall_s = time.perf_counter() - t0
dur_s = max(0.01, (rep.get("signal") or {}).get("duration_s", 1.0)) rtf = wall_s / dur_s rtfs.append(rtf)
got = rep["decision"] ok = got == r["expected_decision"] passed += int(ok) score_pct = int(round(rep["confidence"]["score"] * 100)) fb_msgs = rep["feedback"]["messages"] fb_str = " | ".join(fb_msgs) if fb_msgs else "(clean accept)" print(f"{cid:<22} {r['language']:<4} {r['expected_decision']:<9} {got:<9} " f"{'PASS' if ok else 'FAIL':<4} {score_pct:>3}/100 {rtf:<7.4f} {fb_str[:52]}")
print("-" * 115) print(f"Summary: {passed}/{len(rows)} scenarios matched expected decision | " f"Mean CPU RTF: {sum(rtfs)/len(rtfs):.4f} (target < 1.0)")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172"""Edit-distance alignment between a reference and a hypothesis.Returns the full operation sequence (not just a distance) so that theparticipant app can show which prompt words may have been missed and thereviewer UI can highlight substitutions."""from __future__ import annotationsfrom dataclasses import dataclassfrom difflib import SequenceMatcherfrom typing import Sequencefrom .textnorm import phonetic_key@dataclassclass AlignOp:op: str # "match" | "sub" | "del" | "ins"ref: str | Nonehyp: str | Noneref_index: int | None@dataclassclass Alignment:ops: list[AlignOp]n_ref: int@propertydef errors(self) -> int:return sum(1 for o in self.ops if o.op != "match")@propertydef error_rate(self) -> float:if self.n_ref == 0:return 0.0 if not self.ops else 1.0return self.errors / self.n_refdef by_type(self, op: str) -> list[AlignOp]:return [o for o in self.ops if o.op == op]def coverage(self) -> float:"""Fraction of reference tokens that were matched exactly."""if self.n_ref == 0:return 1.0return len(self.by_type("match")) / self.n_refdef to_list(self) -> list[dict]:return [o.__dict__ for o in self.ops]def align(ref: Sequence[str], hyp: Sequence[str]) -> Alignment:n, m = len(ref), len(hyp)# dp[i][j] = edit distance between ref[:i] and hyp[:j]dp = [[0] * (m + 1) for _ in range(n + 1)]for i in range(1, n + 1):dp[i][0] = ifor j in range(1, m + 1):dp[0][j] = jfor i in range(1, n + 1):ri = ref[i - 1]row, prev = dp[i], dp[i - 1]for j in range(1, m + 1):cost = 0 if ri == hyp[j - 1] else 1row[j] = min(prev[j - 1] + cost, prev[j] + 1, row[j - 1] + 1)ops: list[AlignOp] = []i, j = n, mwhile i > 0 or j > 0:if i > 0 and j > 0 and dp[i][j] == dp[i - 1][j - 1] + (0 if ref[i - 1] == hyp[j - 1] else 1):kind = "match" if ref[i - 1] == hyp[j - 1] else "sub"ops.append(AlignOp(kind, ref[i - 1], hyp[j - 1], i - 1))i, j = i - 1, j - 1elif i > 0 and dp[i][j] == dp[i - 1][j] + 1:ops.append(AlignOp("del", ref[i - 1], None, i - 1))i -= 1else:ops.append(AlignOp("ins", None, hyp[j - 1], None))j -= 1ops.reverse()return Alignment(ops=ops, n_ref=n)def char_error_rate(ref: str, hyp: str) -> float:"""CER over characters with spaces removed (robust to word-split variants)."""r = list(ref.replace(" ", ""))h = list(hyp.replace(" ", ""))return align(r, h).error_ratedef _word_similarity(a: str, b: str) -> float:if a == b:return 1.0pa, pb = phonetic_key(a), phonetic_key(b)if pa == pb:return 0.96return SequenceMatcher(None, pa, pb).ratio()def _merge_split_tokens(ref: Sequence[str], hyp: Sequence[str], thresh: float = 0.85) -> list[str]:"""Merge adjacent hypothesis tokens (h_j + h_{j+1}) when they match a single prompt word."""ref_set = set(ref)out: list[str] = []j = 0while j < len(hyp):if j + 1 < len(hyp):joined = hyp[j] + hyp[j + 1]if joined in ref_set or any(_word_similarity(r, joined) >= thresh for r in ref):out.append(joined)j += 2continueout.append(hyp[j])j += 1return outdef align_lexical(ref: Sequence[str], hyp: Sequence[str], fuzzy_threshold: float = 0.78) -> Alignment:"""Accent- and compound-tolerant word alignment for read-speech lexical QC."""hyp_merged = _merge_split_tokens(ref, hyp)n, m = len(ref), len(hyp_merged)dp = [[0.0] * (m + 1) for _ in range(n + 1)]for i in range(1, n + 1):dp[i][0] = float(i)for j in range(1, m + 1):dp[0][j] = float(j)def sub_cost(ri: str, hj: str) -> tuple[float, bool]:if ri == hj:return 0.0, Trueif _word_similarity(ri, hj) >= fuzzy_threshold:return 0.05, True # soft accent matchreturn 1.0, Falsefor i in range(1, n + 1):for j in range(1, m + 1):c_sub, _ = sub_cost(ref[i - 1], hyp_merged[j - 1])dp[i][j] = min(dp[i - 1][j - 1] + c_sub, dp[i - 1][j] + 1.0, dp[i][j - 1] + 1.0)ops: list[AlignOp] = []i, j = n, mwhile i > 0 or j > 0:if i > 0 and j > 0:c_sub, is_match = sub_cost(ref[i - 1], hyp_merged[j - 1])if abs(dp[i][j] - (dp[i - 1][j - 1] + c_sub)) < 1e-6:ops.append(AlignOp("match" if is_match else "sub", ref[i - 1], hyp_merged[j - 1], i - 1))i, j = i - 1, j - 1continueif i > 0 and abs(dp[i][j] - (dp[i - 1][j] + 1.0)) < 1e-6:ops.append(AlignOp("del", ref[i - 1], None, i - 1))i -= 1else:ops.append(AlignOp("ins", None, hyp_merged[j - 1], None))j -= 1ops.reverse()return Alignment(ops=ops, n_ref=n)def format_word_feedback(al: Alignment) -> str:"""Generate actionable word-level feedback for skipped, substituted, or extra words."""dels = [o.ref for o in al.by_type("del") if o.ref]subs = [(o.ref, o.hyp) for o in al.by_type("sub") if o.ref and o.hyp]ins = [o.hyp for o in al.by_type("ins") if o.hyp]parts: list[str] = []if dels:parts.append(f"You skipped {', '.join(dels[:3])}.")if subs:r0, h0 = subs[0]parts.append(f"You said '{h0}' instead of '{r0}'.")if ins:parts.append(f"Extra word heard: {', '.join(ins[:2])}.")return " ".join(parts)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190"""Edit-distance alignment between a reference and a hypothesis.Returns the full operation sequence (not just a distance) so that theparticipant app can show which prompt words may have been missed and thereviewer UI can highlight substitutions."""from __future__ import annotationsfrom dataclasses import dataclassfrom difflib import SequenceMatcherfrom typing import Sequencefrom .textnorm import indic_asr_key@dataclassclass AlignOp:op: str # "match" | "sub" | "del" | "ins"ref: str | Nonehyp: str | Noneref_index: int | None@dataclassclass Alignment:ops: list[AlignOp]n_ref: int@propertydef errors(self) -> int:return sum(1 for o in self.ops if o.op != "match")@propertydef error_rate(self) -> float:if self.n_ref == 0:return 0.0 if not self.ops else 1.0return self.errors / self.n_refdef by_type(self, op: str) -> list[AlignOp]:return [o for o in self.ops if o.op == op]def coverage(self) -> float:"""Fraction of reference tokens that were matched exactly."""if self.n_ref == 0:return 1.0return len(self.by_type("match")) / self.n_refdef to_list(self) -> list[dict]:return [o.__dict__ for o in self.ops]def align(ref: Sequence[str], hyp: Sequence[str]) -> Alignment:n, m = len(ref), len(hyp)# dp[i][j] = edit distance between ref[:i] and hyp[:j]dp = [[0] * (m + 1) for _ in range(n + 1)]for i in range(1, n + 1):dp[i][0] = ifor j in range(1, m + 1):dp[0][j] = jfor i in range(1, n + 1):ri = ref[i - 1]row, prev = dp[i], dp[i - 1]for j in range(1, m + 1):cost = 0 if ri == hyp[j - 1] else 1row[j] = min(prev[j - 1] + cost, prev[j] + 1, row[j - 1] + 1)ops: list[AlignOp] = []i, j = n, mwhile i > 0 or j > 0:if i > 0 and j > 0 and dp[i][j] == dp[i - 1][j - 1] + (0 if ref[i - 1] == hyp[j - 1] else 1):kind = "match" if ref[i - 1] == hyp[j - 1] else "sub"ops.append(AlignOp(kind, ref[i - 1], hyp[j - 1], i - 1))i, j = i - 1, j - 1elif i > 0 and dp[i][j] == dp[i - 1][j] + 1:ops.append(AlignOp("del", ref[i - 1], None, i - 1))i -= 1else:ops.append(AlignOp("ins", None, hyp[j - 1], None))j -= 1ops.reverse()return Alignment(ops=ops, n_ref=n)def char_error_rate(ref: str, hyp: str) -> float:"""CER over characters with spaces removed (robust to word-split variants)."""r = list(ref.replace(" ", ""))h = list(hyp.replace(" ", ""))return align(r, h).error_ratedef _word_similarity(a: str, b: str) -> float:if a == b:return 1.0pa, pb = indic_asr_key(a), indic_asr_key(b)if pa == pb:return 0.96return SequenceMatcher(None, pa, pb).ratio()def _merge_split_tokens(ref: Sequence[str], hyp: Sequence[str], thresh: float = 0.65) -> list[str]:"""Merge adjacent hypothesis tokens (h_j + h_{j+1}) when they match a single prompt word."""ref_set = set(ref)out: list[str] = []j = 0while j < len(hyp):if j + 1 < len(hyp) and hyp[j] not in ref_set and hyp[j + 1] not in ref_set:joined = hyp[j] + hyp[j + 1]if joined in ref_set or any(_word_similarity(r, joined) >= thresh for r in ref):out.append(joined)j += 2continueout.append(hyp[j])j += 1return outdef _premerge_compounds(ref_tokens: list[str], hyp_tokens: list[str]) -> list[str]:ref_set = set(ref_tokens)out: list[str] = []i = 0while i < len(hyp_tokens):if i + 1 < len(hyp_tokens):a, b = hyp_tokens[i], hyp_tokens[i + 1]merged = a + bif a not in ref_set and b not in ref_set and merged in ref_set:out.append(merged)i += 2continueout.append(hyp_tokens[i])i += 1return outdef align_lexical(ref: Sequence[str], hyp: Sequence[str], fuzzy_threshold: float = 0.65) -> Alignment:"""Accent- and compound-tolerant word alignment for read-speech lexical QC."""hyp_merged = _merge_split_tokens(ref, hyp)n, m = len(ref), len(hyp_merged)dp = [[0.0] * (m + 1) for _ in range(n + 1)]for i in range(1, n + 1):dp[i][0] = float(i)for j in range(1, m + 1):dp[0][j] = float(j)def sub_cost(ri: str, hj: str) -> tuple[float, bool]:if ri == hj:return 0.0, Trueif _word_similarity(ri, hj) >= fuzzy_threshold:return 0.05, True # soft accent matchreturn 1.0, Falsefor i in range(1, n + 1):for j in range(1, m + 1):c_sub, _ = sub_cost(ref[i - 1], hyp_merged[j - 1])dp[i][j] = min(dp[i - 1][j - 1] + c_sub, dp[i - 1][j] + 1.0, dp[i][j - 1] + 1.0)ops: list[AlignOp] = []i, j = n, mwhile i > 0 or j > 0:if i > 0 and j > 0:c_sub, is_match = sub_cost(ref[i - 1], hyp_merged[j - 1])if abs(dp[i][j] - (dp[i - 1][j - 1] + c_sub)) < 1e-6:ops.append(AlignOp("match" if is_match else "sub", ref[i - 1], hyp_merged[j - 1], i - 1))i, j = i - 1, j - 1continueif i > 0 and abs(dp[i][j] - (dp[i - 1][j] + 1.0)) < 1e-6:ops.append(AlignOp("del", ref[i - 1], None, i - 1))i -= 1else:ops.append(AlignOp("ins", None, hyp_merged[j - 1], None))j -= 1ops.reverse()return Alignment(ops=ops, n_ref=n)def format_word_feedback(al: Alignment) -> str:"""Generate actionable word-level feedback for skipped, substituted, or extra words."""dels = [o.ref for o in al.by_type("del") if o.ref]subs = [(o.ref, o.hyp) for o in al.by_type("sub") if o.ref and o.hyp]ins = [o.hyp for o in al.by_type("ins") if o.hyp]parts: list[str] = []if dels:parts.append(f"You skipped {', '.join(dels[:3])}.")if subs:r0, h0 = subs[0]parts.append(f"You said '{h0}' instead of '{r0}'.")if ins:parts.append(f"Extra word heard: {', '.join(ins[:2])}.")return " ".join(parts)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326"""Pluggable ASR backends used by the L2 ("intelligent") validators.ASR output is treated as evidence, never as ground truth: a mismatch betweenprompt and hypothesis can send a recording to review, but it cannot block it.Backendsnone -> no ASR; L2 validators route to human reviewfaster-whisper:<size|path> -> CTranslate2 Whisper (pip install faster-whisper)hf:<model_id_or_path> -> transformers ASR pipeline (pip install transformers torch)hf-remote:<model_id> -> same, with trust_remote_code=True, for models that ship their owncode, e.g. hf-remote:ARTPARK-IISc/SraVaani-0.5-live(set HF_TOKEN if the repository is gated)sravaani[:<model_id>] -> IISc/ARTPARK SraVaani via its own transcribe() (defaultARTPARK-IISc/SraVaani-1.0; language identified by the model)indicconformer[:<model_id>] -> AI4Bharat IndicConformer, CTC decoding, called with the tasklanguage; audio is cut at pauses into <=15 s piecesindicconformer-rnnt[:<id>] -> same with RNNT decodingfixed:<path.json> -> {"<clip_id or sha256>": "hypothesis"}; for tests and auditswhere hypotheses were computed offlineAny object with `name`, `model_id` and `transcribe(samples, sr, language)` works."""from __future__ import annotationsimport hashlibimport jsonimport mathfrom dataclasses import dataclass, fieldfrom typing import Optional, Protocolimport numpy as np@dataclassclass ASRResult:text: strconfidence: Optional[float] = None # [0,1] if the backend provides oneno_speech_prob: Optional[float] = None# Ensemble runs: every model's hypothesis, keyed by model label (first = primary).alternatives: dict[str, str] = field(default_factory=dict)class ASRBackend(Protocol):name: strmodel_id: strdef transcribe(self, samples: np.ndarray, sr: int, language: str, key: Optional[str] = None) -> Optional[ASRResult]:...class NullASR:name = "none"model_id = "none"def transcribe(self, samples, sr, language, key=None):return Noneclass FixedASR:"""Looks hypotheses up by clip key (clip_id) or by sha256 of the samples."""name = "fixed"def __init__(self, table: dict[str, str], model_id: str = "precomputed"):self.table = tableself.model_id = model_id@classmethoddef from_file(cls, path: str) -> "FixedASR":with open(path, encoding="utf-8") as f:return cls(json.load(f), model_id=f"precomputed:{path}")@staticmethoddef sample_key(samples: np.ndarray) -> str:return hashlib.sha256(np.ascontiguousarray(samples, dtype=np.float32).tobytes()).hexdigest()def transcribe(self, samples, sr, language, key=None):if key and key in self.table:return ASRResult(self.table[key])k = self.sample_key(samples)return ASRResult(self.table[k]) if k in self.table else Noneclass FasterWhisperASR:name = "faster-whisper"def __init__(self, model: str = "small", device: str = "auto", compute_type: str = "int8"):from faster_whisper import WhisperModel # optional dependencyself.model_id = modelself._m = WhisperModel(model, device=device, compute_type=compute_type)def transcribe(self, samples, sr, language, key=None):assert sr == 16000, "faster-whisper expects 16 kHz input"segments, _info = self._m.transcribe(samples.astype(np.float32),language=language,beam_size=5,condition_on_previous_text=False, # avoids hallucinated carry-overvad_filter=False, # SCQC runs its own VAD)segs = list(segments)if not segs:return ASRResult("", confidence=0.0, no_speech_prob=1.0)text = " ".join(s.text.strip() for s in segs).strip()# Duration-weighted mean token log-prob -> probability-like confidence.w = np.array([max(1e-3, s.end - s.start) for s in segs])lp = np.array([s.avg_logprob for s in segs])conf = float(math.exp(float((w * lp).sum() / w.sum())))nsp = float(max(s.no_speech_prob for s in segs))return ASRResult(text, confidence=round(conf, 4), no_speech_prob=round(nsp, 4))class HFPipelineASR:name = "hf"def __init__(self, model_id: str, device: Optional[str] = None, generate_language: bool = True,trust_remote_code: bool = False):import osfrom transformers import pipeline # optional dependencyself.model_id = model_idself._generate_language = generate_languagekwargs = {"trust_remote_code": True} if trust_remote_code else {}token = os.environ.get("HF_TOKEN")if token:kwargs["token"] = tokenself._p = pipeline("automatic-speech-recognition", model=model_id, device=device, **kwargs)def transcribe(self, samples, sr, language, key=None):kwargs = {}if self._generate_language and "whisper" in self.model_id.lower():kwargs["generate_kwargs"] = {"language": language, "task": "transcribe"}out = self._p({"raw": samples.astype(np.float32), "sampling_rate": sr}, **kwargs)return ASRResult(out["text"].strip())def _hf_kwargs() -> dict:import oskw = {"trust_remote_code": True}if os.environ.get("HF_TOKEN"):kw["token"] = os.environ["HF_TOKEN"]return kwdef _first_text(out) -> str:"""Pull the first hypothesis text out of NeMo/remote-code return shapes:str, Hypothesis(.text), list/tuple of either, or a (best, all) tuple."""while isinstance(out, (list, tuple)) and out:out = out[0]if hasattr(out, "text"):out = out.textreturn str(out or "").strip()def chunk_at_pauses(samples: np.ndarray, sr: int, max_s: float = 15.0, min_s: float = 8.0) -> list[tuple[int, int]]:"""Split long audio into pieces of at most `max_s`, cutting at the quietest30 ms frame between `min_s` and `max_s` into each piece. Several Indic ASRcheckpoints drop words on long continuous input."""n, max_n = len(samples), int(max_s * sr)if n <= max_n:return [(0, n)]frame, hop = int(0.03 * sr), int(0.01 * sr)out, start = [], 0while n - start > max_n:lo, hi = start + int(min_s * sr), start + max_n - framebest, best_e = hi, float("inf")for i in range(lo, hi, hop):e = float(np.mean(samples[i:i + frame] ** 2))if e < best_e:best, best_e = i + frame // 2, eout.append((start, best))start = bestout.append((start, n))return outclass SraVaaniASR:"""SraVaani (IISc / ARTPARK). The model card's interface is`model.transcribe([paths], return_hypotheses=True)`, so audio goes througha temporary 16 kHz WAV. The model identifies the language itself."""name = "sravaani"def __init__(self, model_id: str = "ARTPARK-IISc/SraVaani-1.0", device: Optional[str] = None):import torchfrom transformers import AutoModel # optional dependencyself.model_id = model_idimport os# SCQC_ASR_DEVICE=cpu forces CPU (needed on ZeroGPU Spaces, where CUDA is# only usable inside @spaces.GPU functions).self.device = device or os.environ.get("SCQC_ASR_DEVICE") or ("cuda" if torch.cuda.is_available() else "cpu")self._m = AutoModel.from_pretrained(model_id, **_hf_kwargs())try:self._m = self._m.to(self.device)except Exception:passif hasattr(self._m, "eval"):self._m.eval()def transcribe(self, samples, sr, language, key=None):return self.transcribe_batch([samples], sr, language)[0]def transcribe_batch(self, batch: list[np.ndarray], sr: int, language: str) -> list[ASRResult]:import osimport tempfileimport soundfile as sfpaths = []try:for x in batch:fd, path = tempfile.mkstemp(suffix=".wav")os.close(fd)sf.write(path, np.asarray(x, dtype=np.float32), sr, subtype="PCM_16")paths.append(path)out = self._m.transcribe(paths, return_hypotheses=True)if isinstance(out, tuple) and len(out) == 2 and isinstance(out[0], (list, tuple)):out = out[0] # (best, all-beams)return [ASRResult(_first_text(o)) for o in out]finally:for path in paths:try:os.unlink(path)except OSError:passclass IndicConformerASR:"""AI4Bharat IndicConformer 600M multilingual: `model(wav, lang, "ctc"|"rnnt")`on a (1, n) float tensor at 16 kHz, for the 22 scheduled languages."""name = "indicconformer"MAX_S = 15.0def __init__(self, model_id: str = "ai4bharat/indic-conformer-600m-multilingual", decoder: str = "ctc"):from transformers import AutoModel # optional dependencyself.model_id = model_id if decoder == "ctc" else f"{model_id}#{decoder}"self.decoder = decoderself._m = AutoModel.from_pretrained(model_id, **_hf_kwargs())def transcribe(self, samples, sr, language, key=None):import torchif sr != 16000:from .audio import resamplesamples, sr = resample(samples, sr, 16000), 16000parts = []for a, b in chunk_at_pauses(samples, sr, self.MAX_S):wav = torch.from_numpy(np.ascontiguousarray(samples[a:b], dtype=np.float32)).unsqueeze(0)with torch.no_grad():parts.append(_first_text(self._m(wav, language, self.decoder)))return ASRResult(" ".join(p for p in parts if p))class EnsembleASR:"""Several ASR models on the same audio. The primary hypothesis is the firstmodel's; all hypotheses are returned in `alternatives` so validators can lookfor consensus. A model that fails on a clip is skipped for that clip."""name = "ensemble"def __init__(self, backends: list, load_errors: Optional[dict] = None):self.backends, self.labels = [], []for b in backends:label = b.name if b.name not in self.labels else f"{b.name}_{len(self.labels) + 1}"self.backends.append(b)self.labels.append(label)self.load_errors = load_errors or {}self.model_id = "+".join(f"{l}={b.model_id}" for l, b in zip(self.labels, self.backends))def transcribe(self, samples, sr, language, key=None):hyps, errors = {}, {}for label, b in zip(self.labels, self.backends):try:r = b.transcribe(samples, sr, language, key=key)except Exception as e: # one failing model must not sink the otherserrors[label] = f"{type(e).__name__}: {e}"[:200]continueif r is not None:hyps[label] = r.textif not hyps:return Nonefirst = next(iter(hyps))return ASRResult(hyps[first], alternatives=hyps)def load_backend(spec: Optional[str]) -> ASRBackend:"""One backend spec, or several separated by commas for an ensemble,e.g. "sravaani,indicconformer". In an ensemble, a model that fails to loadis left out (and reported) as long as at least one loads."""if spec and "," in spec:backends, errors = [], {}for part in [x.strip() for x in spec.split(",") if x.strip()]:try:backends.append(load_backend(part))except Exception as e:errors[part] = f"{type(e).__name__}: {e}"[:300]if not backends:raise RuntimeError(f"no ASR model in '{spec}' could be loaded: {errors}")return backends[0] if len(backends) == 1 and not errors else EnsembleASR(backends, errors)if not spec or spec == "none":return NullASR()kind, _, arg = spec.partition(":")if kind == "faster-whisper":return FasterWhisperASR(arg or "small")if kind == "hf":if not arg:raise ValueError("hf backend needs a model id, e.g. hf:<model_id>")return HFPipelineASR(arg)if kind == "hf-remote":if not arg:raise ValueError("hf-remote backend needs a model id, e.g. hf-remote:<model_id>")return HFPipelineASR(arg, trust_remote_code=True)if kind == "sravaani":return SraVaaniASR(arg or "ARTPARK-IISc/SraVaani-1.0")if kind in ("indicconformer", "indicconformer-rnnt"):return IndicConformerASR(arg or "ai4bharat/indic-conformer-600m-multilingual",decoder="rnnt" if kind.endswith("rnnt") else "ctc")if kind == "fixed":return FixedASR.from_file(arg)raise ValueError(f"unknown ASR backend '{spec}'")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382"""Pluggable ASR backends used by the L2 ("intelligent") validators.ASR output is treated as evidence, never as ground truth: a mismatch betweenprompt and hypothesis can send a recording to review, but it cannot block it.Backendsnone -> no ASR; L2 validators route to human reviewfaster-whisper:<size|path> -> CTranslate2 Whisper (pip install faster-whisper)hf:<model_id_or_path> -> transformers ASR pipeline (pip install transformers torch)hf-remote:<model_id> -> same, with trust_remote_code=True, for models that ship their owncode, e.g. hf-remote:ARTPARK-IISc/SraVaani-0.5-live(set HF_TOKEN if the repository is gated)sravaani[:<model_id>] -> IISc/ARTPARK SraVaani via its own transcribe() (defaultARTPARK-IISc/SraVaani-1.0; language identified by the model)indicconformer[:<model_id>] -> AI4Bharat IndicConformer, CTC decoding, called with the tasklanguage; audio is cut at pauses into <=15 s piecesindicconformer-rnnt[:<id>] -> same with RNNT decodingfixed:<path.json> -> {"<clip_id or sha256>": "hypothesis"}; for tests and auditswhere hypotheses were computed offlineAny object with `name`, `model_id` and `transcribe(samples, sr, language)` works."""from __future__ import annotationsimport hashlibimport jsonimport mathfrom dataclasses import dataclass, fieldfrom typing import Optional, Protocolimport numpy as np@dataclassclass ASRResult:text: strconfidence: Optional[float] = None # [0,1] if the backend provides oneno_speech_prob: Optional[float] = None# Ensemble runs: every model's hypothesis, keyed by model label (first = primary).alternatives: dict[str, str] = field(default_factory=dict)class ASRBackend(Protocol):name: strmodel_id: strdef transcribe(self, samples: np.ndarray, sr: int, language: str, key: Optional[str] = None) -> Optional[ASRResult]:...class NullASR:name = "none"model_id = "none"def transcribe(self, samples, sr, language, key=None):return Noneclass FixedASR:"""Looks hypotheses up by clip key (clip_id) or by sha256 of the samples."""name = "fixed"def __init__(self, table: dict[str, str], model_id: str = "precomputed"):self.table = tableself.model_id = model_id@classmethoddef from_file(cls, path: str) -> "FixedASR":with open(path, encoding="utf-8") as f:return cls(json.load(f), model_id=f"precomputed:{path}")@staticmethoddef sample_key(samples: np.ndarray) -> str:return hashlib.sha256(np.ascontiguousarray(samples, dtype=np.float32).tobytes()).hexdigest()def transcribe(self, samples, sr, language, key=None):if key and key in self.table:return ASRResult(self.table[key])k = self.sample_key(samples)return ASRResult(self.table[k]) if k in self.table else Noneclass FasterWhisperASR:name = "faster-whisper"def __init__(self, model: str = "small", device: str = "auto", compute_type: str = "int8"):from faster_whisper import WhisperModel # optional dependencyself.model_id = modelself._m = WhisperModel(model, device=device, compute_type=compute_type)def transcribe(self, samples, sr, language, key=None):assert sr == 16000, "faster-whisper expects 16 kHz input"segments, _info = self._m.transcribe(samples.astype(np.float32),language=language,beam_size=5,condition_on_previous_text=False, # avoids hallucinated carry-overvad_filter=False, # SCQC runs its own VAD)segs = list(segments)if not segs:return ASRResult("", confidence=0.0, no_speech_prob=1.0)text = " ".join(s.text.strip() for s in segs).strip()# Duration-weighted mean token log-prob -> probability-like confidence.w = np.array([max(1e-3, s.end - s.start) for s in segs])lp = np.array([s.avg_logprob for s in segs])conf = float(math.exp(float((w * lp).sum() / w.sum())))nsp = float(max(s.no_speech_prob for s in segs))return ASRResult(text, confidence=round(conf, 4), no_speech_prob=round(nsp, 4))class HFPipelineASR:name = "hf"def __init__(self, model_id: str, device: Optional[str] = None, generate_language: bool = True,trust_remote_code: bool = False):import osfrom transformers import pipeline # optional dependencyself.model_id = model_idself._generate_language = generate_languagekwargs = {"trust_remote_code": True} if trust_remote_code else {}token = os.environ.get("HF_TOKEN")if token:kwargs["token"] = tokenself._p = pipeline("automatic-speech-recognition", model=model_id, device=device, **kwargs)try:import torchif getattr(self._p.device, "type", "cpu") == "cpu":target = getattr(getattr(self._p.model, "model", None), "encoder", self._p.model)q_target = torch.ao.quantization.quantize_dynamic(target, {torch.nn.Linear}, dtype=torch.qint8)if hasattr(self._p.model, "model") and hasattr(self._p.model.model, "encoder"):self._p.model.model.encoder = q_targetelse:self._p.model = q_targetexcept Exception:passdef transcribe(self, samples, sr, language, key=None):kwargs = {}if self._generate_language and "whisper" in self.model_id.lower():kwargs["generate_kwargs"] = {"language": language, "task": "transcribe", "num_beams": 1, "do_sample": False}out = self._p({"raw": samples.astype(np.float32), "sampling_rate": sr}, **kwargs)return ASRResult(out["text"].strip())def _hf_kwargs() -> dict:import oskw = {"trust_remote_code": True}if os.environ.get("HF_TOKEN"):kw["token"] = os.environ["HF_TOKEN"]return kwdef _first_text(out) -> str:"""Pull the first hypothesis text out of NeMo/remote-code return shapes:str, Hypothesis(.text), list/tuple of either, or a (best, all) tuple."""while isinstance(out, (list, tuple)) and out:out = out[0]if hasattr(out, "text"):out = out.textreturn str(out or "").strip()def chunk_at_pauses(samples: np.ndarray, sr: int, max_s: float = 15.0, min_s: float = 8.0) -> list[tuple[int, int]]:"""Split long audio into pieces of at most `max_s`, cutting at the quietest30 ms frame between `min_s` and `max_s` into each piece. Several Indic ASRcheckpoints drop words on long continuous input."""n, max_n = len(samples), int(max_s * sr)if n <= max_n:return [(0, n)]frame, hop = int(0.03 * sr), int(0.01 * sr)out, start = [], 0while n - start > max_n:lo, hi = start + int(min_s * sr), start + max_n - framebest, best_e = hi, float("inf")for i in range(lo, hi, hop):e = float(np.mean(samples[i:i + frame] ** 2))if e < best_e:best, best_e = i + frame // 2, eout.append((start, best))start = bestout.append((start, n))return outclass SraVaaniASR:"""SraVaani (IISc / ARTPARK). The model card's interface is`model.transcribe([paths], return_hypotheses=True)`, so audio goes througha temporary 16 kHz WAV. The model identifies the language itself."""name = "sravaani"def __init__(self, model_id: str = "ARTPARK-IISc/SraVaani-1.0", device: Optional[str] = None):import torchfrom transformers import AutoModel # optional dependencyself.model_id = model_idimport os# SCQC_ASR_DEVICE=cpu forces CPU (needed on ZeroGPU Spaces, where CUDA is# only usable inside @spaces.GPU functions).self.device = device or os.environ.get("SCQC_ASR_DEVICE") or ("cuda" if torch.cuda.is_available() else "cpu")self._m = AutoModel.from_pretrained(model_id, **_hf_kwargs())try:self._m = self._m.to(self.device)except Exception:passif hasattr(self._m, "eval"):self._m.eval()def transcribe(self, samples, sr, language, key=None):return self.transcribe_batch([samples], sr, language)[0]def transcribe_batch(self, batch: list[np.ndarray], sr: int, language: str) -> list[ASRResult]:import osimport tempfileimport soundfile as sfpaths = []try:for x in batch:fd, path = tempfile.mkstemp(suffix=".wav")os.close(fd)sf.write(path, np.asarray(x, dtype=np.float32), sr, subtype="PCM_16")paths.append(path)out = self._m.transcribe(paths, return_hypotheses=True)if isinstance(out, tuple) and len(out) == 2 and isinstance(out[0], (list, tuple)):out = out[0] # (best, all-beams)return [ASRResult(_first_text(o)) for o in out]finally:for path in paths:try:os.unlink(path)except OSError:passclass IndicConformerASR:"""AI4Bharat IndicConformer 600M multilingual: `model(wav, lang, "ctc"|"rnnt")`on a (1, n) float tensor at 16 kHz, for the 22 scheduled languages."""name = "indicconformer"MAX_S = 15.0def __init__(self, model_id: str = "ai4bharat/indic-conformer-600m-multilingual", decoder: str = "ctc"):from transformers import AutoModel # optional dependencyself.model_id = model_id if decoder == "ctc" else f"{model_id}#{decoder}"self.decoder = decoderself._m = AutoModel.from_pretrained(model_id, **_hf_kwargs())def transcribe(self, samples, sr, language, key=None):import torchif sr != 16000:from .audio import resamplesamples, sr = resample(samples, sr, 16000), 16000parts = []for a, b in chunk_at_pauses(samples, sr, self.MAX_S):wav = torch.from_numpy(np.ascontiguousarray(samples[a:b], dtype=np.float32)).unsqueeze(0)with torch.no_grad():parts.append(_first_text(self._m(wav, language, self.decoder)))return ASRResult(" ".join(p for p in parts if p))class EnsembleASR:"""Several ASR models on the same audio. The primary hypothesis is the firstmodel's; all hypotheses are returned in `alternatives` so validators can lookfor consensus. A model that fails on a clip is skipped for that clip."""name = "ensemble"def __init__(self, backends: list, load_errors: Optional[dict] = None):self.backends, self.labels = [], []for b in backends:label = b.name if b.name not in self.labels else f"{b.name}_{len(self.labels) + 1}"self.backends.append(b)self.labels.append(label)self.load_errors = load_errors or {}self.model_id = "+".join(f"{l}={b.model_id}" for l, b in zip(self.labels, self.backends))def transcribe(self, samples, sr, language, key=None):hyps, errors = {}, {}for label, b in zip(self.labels, self.backends):try:r = b.transcribe(samples, sr, language, key=key)except Exception as e: # one failing model must not sink the otherserrors[label] = f"{type(e).__name__}: {e}"[:200]continueif r is not None:hyps[label] = r.textif not hyps:return Nonefirst = next(iter(hyps))return ASRResult(hyps[first], alternatives=hyps)class CascadedASR:"""CPU-optimized two-stage ASR with early exit.Runs `primary` first; if its confidence >= `early_exit_conf` and transcript isnon-empty, returns immediately without invoking `secondary` (keeping RTF < 1.0 on CPU)."""name = "cascaded"def __init__(self, primary: ASRBackend, secondary: ASRBackend, early_exit_conf: float = 0.82):self.primary = primaryself.secondary = secondaryself.early_exit_conf = early_exit_confself.model_id = f"{primary.model_id}->{secondary.model_id}"def transcribe(self, samples, sr, language, key=None):r1 = self.primary.transcribe(samples, sr, language, key=key)if r1 and r1.text.strip() and (r1.confidence is None or r1.confidence >= self.early_exit_conf):return ASRResult(r1.text,confidence=r1.confidence,no_speech_prob=r1.no_speech_prob,alternatives={self.primary.name: r1.text},)r2 = self.secondary.transcribe(samples, sr, language, key=key)hyps = {}if r1 and r1.text.strip():hyps[self.primary.name] = r1.textif r2 and r2.text.strip():hyps[f"{self.secondary.name}_2" if self.secondary.name in hyps else self.secondary.name] = r2.textif not hyps:return r1 or r2first = next(iter(hyps))confs = [c for c in (r1.confidence if r1 else None, r2.confidence if r2 else None) if c is not None]return ASRResult(hyps[first], confidence=max(confs) if confs else None, alternatives=hyps)def load_backend(spec: Optional[str]) -> ASRBackend:"""One backend spec, or several separated by commas for an ensemble,e.g. "sravaani,indicconformer". In an ensemble, a model that fails to loadis left out (and reported) as long as at least one loads."""if spec and "," in spec:backends, errors = [], {}for part in [x.strip() for x in spec.split(",") if x.strip()]:try:backends.append(load_backend(part))except Exception as e:errors[part] = f"{type(e).__name__}: {e}"[:300]if not backends:raise RuntimeError(f"no ASR model in '{spec}' could be loaded: {errors}")return backends[0] if len(backends) == 1 and not errors else EnsembleASR(backends, errors)if not spec or spec == "none":return NullASR()kind, _, arg = spec.partition(":")if kind == "faster-whisper":return FasterWhisperASR(arg or "small")if kind == "hf":if not arg:raise ValueError("hf backend needs a model id, e.g. hf:<model_id>")return HFPipelineASR(arg)if kind == "hf-remote":if not arg:raise ValueError("hf-remote backend needs a model id, e.g. hf-remote:<model_id>")return HFPipelineASR(arg, trust_remote_code=True)if kind == "sravaani":return SraVaaniASR(arg or "ARTPARK-IISc/SraVaani-1.0")if kind in ("indicconformer", "indicconformer-rnnt"):return IndicConformerASR(arg or "ai4bharat/indic-conformer-600m-multilingual",decoder="rnnt" if kind.endswith("rnnt") else "ctc")if kind == "cascaded":p_spec, _, s_spec = arg.partition(",")if not p_spec or not s_spec:raise ValueError("cascaded backend requires 'cascaded:<primary>,<secondary>'")return CascadedASR(load_backend(p_spec.strip()), load_backend(s_spec.strip()))if kind == "fixed":return FixedASR.from_file(arg)raise ValueError(f"unknown ASR backend '{spec}'")
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236"""Audio loading and signal analysis.Everything here is deterministic numpy so the same numbers can be reproducedon a laptop hub, a server, or (ported) on-device. The VAD is a simple adaptiveenergy detector: it is meant for presence / truncation / silence checks, notfor segmentation-quality diarisation. Swap in Silero or WebRTC VAD through`speech_frames()` if you need more robustness in heavy noise."""from __future__ import annotationsimport iofrom dataclasses import dataclass, fieldimport numpy as npTARGET_SR = 16000class AudioDecodeError(Exception):pass@dataclassclass Audio:samples: np.ndarray # float32 mono in [-1, 1]sr: intoriginal_sr: intoriginal_channels: intoriginal_subtype: str | None = None@propertydef duration(self) -> float:return len(self.samples) / self.sr if self.sr else 0.0def load_audio(source: str | bytes, target_sr: int = TARGET_SR) -> Audio:"""Decode WAV/FLAC/OGG via libsndfile. Raises AudioDecodeError on failure."""import soundfile as sftry:handle = io.BytesIO(source) if isinstance(source, (bytes, bytearray)) else sourcedata, sr = sf.read(handle, dtype="float32", always_2d=True)info_subtype = Nonetry:if isinstance(source, (bytes, bytearray)):info_subtype = sf.info(io.BytesIO(source)).subtypeelse:info_subtype = sf.info(source).subtypeexcept Exception:passexcept Exception as e: # libsndfile raises a variety of errorsraise AudioDecodeError(str(e)) from echannels = data.shape[1]mono = data.mean(axis=1) if channels > 1 else data[:, 0]if sr != target_sr and len(mono):mono = resample(mono, sr, target_sr)return Audio(np.ascontiguousarray(mono, dtype=np.float32), target_sr, sr, channels, info_subtype)def ensure_wav(data: bytes) -> bytes:"""Return WAV bytes. Files libsndfile can read pass through unchanged; anything else(WebM/Opus, AAC/M4A from some phone browsers) is converted with ffmpeg if available."""import shutilimport subprocessimport soundfile as sftry:sf.info(io.BytesIO(data))return dataexcept Exception:passif not shutil.which("ffmpeg"):raise AudioDecodeError("unsupported audio format and ffmpeg is not installed")proc = subprocess.run(["ffmpeg", "-hide_banner", "-loglevel", "error", "-i", "pipe:0", "-f", "wav", "-acodec", "pcm_s16le", "pipe:1"],input=data, capture_output=True, timeout=60)if proc.returncode != 0 or not proc.stdout:raise AudioDecodeError(proc.stderr.decode(errors="replace")[:200] or "ffmpeg could not decode audio")return proc.stdoutdef resample(x: np.ndarray, sr_in: int, sr_out: int) -> np.ndarray:if sr_in == sr_out:return xtry:from math import gcdfrom scipy.signal import resample_polyg = gcd(sr_in, sr_out)return resample_poly(x, sr_out // g, sr_in // g).astype(np.float32)except ImportError:# Fallback: linear interpolation. Adequate for QC statistics, not for ASR.n_out = int(round(len(x) * sr_out / sr_in))t_in = np.arange(len(x)) / sr_int_out = np.arange(n_out) / sr_outreturn np.interp(t_out, t_in, x).astype(np.float32)def _db(x: np.ndarray | float, floor: float = 1e-10) -> np.ndarray | float:return 10.0 * np.log10(np.maximum(x, floor))@dataclassclass SignalStats:duration_s: floatpeak: floatrms_dbfs: floatclip_ratio: floatlongest_clip_run_ms: floatnoise_floor_db: floatspeech_level_db: float | Nonesnr_db: float | Nonespeech_s: floatspeech_ratio: floatleading_silence_s: floattrailing_silence_s: floatn_segments: intlongest_internal_pause_s: floatspeech_at_start: boolspeech_at_end: boolsegments: list[tuple[float, float]] = field(default_factory=list)def as_dict(self) -> dict:d = dict(self.__dict__)d["segments"] = [list(s) for s in self.segments]return ddef frame_energies_db(x: np.ndarray, sr: int, frame_ms: float = 30.0, hop_ms: float = 10.0) -> np.ndarray:frame = int(sr * frame_ms / 1000)hop = int(sr * hop_ms / 1000)if len(x) < frame:return np.array([_db(float(np.mean(x**2)) if len(x) else 0.0)])n = 1 + (len(x) - frame) // hopidx = np.arange(frame)[None, :] + hop * np.arange(n)[:, None]frames = x[idx]return _db(np.mean(frames**2, axis=1))def speech_frames(energies_db: np.ndarray,abs_floor_db: float = -65.0,rel_margin_db: float = 12.0,hangover_frames: int = 15,min_run_frames: int = 5,) -> tuple[np.ndarray, float]:"""Adaptive-threshold energy VAD. Returns (bool mask per frame, noise floor dB)."""noise_floor = float(np.percentile(energies_db, 10))thr = max(abs_floor_db, noise_floor + rel_margin_db)raw = energies_db > thr# Remove short bursts (clicks), then bridge short gaps with a hangover.mask = raw.copy()i = 0n = len(mask)while i < n:if mask[i]:j = iwhile j < n and mask[j]:j += 1if j - i < min_run_frames:mask[i:j] = Falsei = jelse:i += 1# Bridge short gaps between speech runs (inter-word pauses, stop closures).out = mask.copy()on = np.where(mask)[0]if len(on) > 1:gaps = np.diff(on) - 1for g_idx in np.where((gaps > 0) & (gaps <= hangover_frames))[0]:out[on[g_idx] + 1:on[g_idx + 1]] = Truereturn out, noise_floordef analyze(audio: Audio, clip_level: float = 0.999, edge_ms: float = 60.0) -> SignalStats:x, sr = audio.samples, audio.srdur = audio.durationif len(x) == 0:return SignalStats(0, 0, -120, 0, 0, -120, None, None, 0, 0, 0, 0, 0, 0, False, False)peak = float(np.max(np.abs(x)))rms = float(_db(float(np.mean(x**2))))clipped = np.abs(x) >= clip_levelclip_ratio = float(clipped.mean())longest = 0if clipped.any():d = np.diff(np.concatenate([[0], clipped.astype(np.int8), [0]]))starts, ends = np.where(d == 1)[0], np.where(d == -1)[0]longest = int((ends - starts).max())hop_s = 0.010en = frame_energies_db(x, sr)mask, noise_floor = speech_frames(en)segments: list[tuple[float, float]] = []k, n = 0, len(mask)while k < n:if mask[k]:j = kwhile j < n and mask[j]:j += 1segments.append((round(k * hop_s, 3), round(min(dur, j * hop_s + 0.02), 3)))k = jelse:k += 1speech_s = float(sum(e - s for s, e in segments))speech_level = float(np.mean(en[mask])) if mask.any() else Nonesnr = (speech_level - noise_floor) if speech_level is not None else Nonelead = segments[0][0] if segments else durtrail = (dur - segments[-1][1]) if segments else durpauses = [segments[i + 1][0] - segments[i][1] for i in range(len(segments) - 1)]edge_frames = max(1, int(edge_ms / 10))return SignalStats(duration_s=round(dur, 3),peak=round(peak, 4),rms_dbfs=round(rms, 2),clip_ratio=round(clip_ratio, 6),longest_clip_run_ms=round(1000 * longest / sr, 2),noise_floor_db=round(noise_floor, 2),speech_level_db=round(speech_level, 2) if speech_level is not None else None,snr_db=round(snr, 2) if snr is not None else None,speech_s=round(speech_s, 3),speech_ratio=round(speech_s / dur, 4) if dur else 0.0,leading_silence_s=round(max(0.0, lead), 3),trailing_silence_s=round(max(0.0, trail), 3),n_segments=len(segments),longest_internal_pause_s=round(max(pauses), 3) if pauses else 0.0,speech_at_start=bool(mask[:edge_frames].any()),speech_at_end=bool(mask[-edge_frames:].any()),segments=segments,)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286"""Audio loading and signal analysis.Everything here is deterministic numpy so the same numbers can be reproducedon a laptop hub, a server, or (ported) on-device. The VAD is a simple adaptiveenergy detector: it is meant for presence / truncation / silence checks, notfor segmentation-quality diarisation. Swap in Silero or WebRTC VAD through`speech_frames()` if you need more robustness in heavy noise."""from __future__ import annotationsimport iofrom dataclasses import dataclass, fieldimport numpy as npTARGET_SR = 16000class AudioDecodeError(Exception):pass@dataclassclass Audio:samples: np.ndarray # float32 mono in [-1, 1]sr: intoriginal_sr: intoriginal_channels: intoriginal_subtype: str | None = None@propertydef duration(self) -> float:return len(self.samples) / self.sr if self.sr else 0.0def load_audio(source: str | bytes, target_sr: int = TARGET_SR) -> Audio:"""Decode WAV/FLAC/OGG via libsndfile. Raises AudioDecodeError on failure."""import soundfile as sftry:handle = io.BytesIO(source) if isinstance(source, (bytes, bytearray)) else sourcedata, sr = sf.read(handle, dtype="float32", always_2d=True)info_subtype = Nonetry:if isinstance(source, (bytes, bytearray)):info_subtype = sf.info(io.BytesIO(source)).subtypeelse:info_subtype = sf.info(source).subtypeexcept Exception:passexcept Exception as e: # libsndfile raises a variety of errorsraise AudioDecodeError(str(e)) from echannels = data.shape[1]mono = data.mean(axis=1) if channels > 1 else data[:, 0]if sr != target_sr and len(mono):mono = resample(mono, sr, target_sr)return Audio(np.ascontiguousarray(mono, dtype=np.float32), target_sr, sr, channels, info_subtype)def ensure_wav(data: bytes) -> bytes:"""Return WAV bytes. Files libsndfile can read pass through unchanged; anything else(WebM/Opus, AAC/M4A from some phone browsers) is converted with ffmpeg if available."""import shutilimport subprocessimport soundfile as sftry:sf.info(io.BytesIO(data))return dataexcept Exception:passif not shutil.which("ffmpeg"):raise AudioDecodeError("unsupported audio format and ffmpeg is not installed")proc = subprocess.run(["ffmpeg", "-hide_banner", "-loglevel", "error", "-i", "pipe:0", "-f", "wav", "-acodec", "pcm_s16le", "pipe:1"],input=data, capture_output=True, timeout=60)if proc.returncode != 0 or not proc.stdout:raise AudioDecodeError(proc.stderr.decode(errors="replace")[:200] or "ffmpeg could not decode audio")return proc.stdoutdef resample(x: np.ndarray, sr_in: int, sr_out: int) -> np.ndarray:if sr_in == sr_out:return xtry:from math import gcdfrom scipy.signal import resample_polyg = gcd(sr_in, sr_out)return resample_poly(x, sr_out // g, sr_in // g).astype(np.float32)except ImportError:# Fallback: linear interpolation. Adequate for QC statistics, not for ASR.n_out = int(round(len(x) * sr_out / sr_in))t_in = np.arange(len(x)) / sr_int_out = np.arange(n_out) / sr_outreturn np.interp(t_out, t_in, x).astype(np.float32)def _db(x: np.ndarray | float, floor: float = 1e-10) -> np.ndarray | float:return 10.0 * np.log10(np.maximum(x, floor))@dataclassclass SignalStats:duration_s: floatpeak: floatrms_dbfs: floatclip_ratio: floatlongest_clip_run_ms: floatnoise_floor_db: floatspeech_level_db: float | Nonesnr_db: float | Nonespeech_s: floatspeech_ratio: floatleading_silence_s: floattrailing_silence_s: floatn_segments: intlongest_internal_pause_s: floatspeech_at_start: boolspeech_at_end: boolsegments: list[tuple[float, float]] = field(default_factory=list)def as_dict(self) -> dict:d = dict(self.__dict__)d["segments"] = [list(s) for s in self.segments]return ddef frame_energies_db(x: np.ndarray, sr: int, frame_ms: float = 30.0, hop_ms: float = 10.0) -> np.ndarray:frame = int(sr * frame_ms / 1000)hop = int(sr * hop_ms / 1000)if len(x) < frame:return np.array([_db(float(np.mean(x**2)) if len(x) else 0.0)])n = 1 + (len(x) - frame) // hopidx = np.arange(frame)[None, :] + hop * np.arange(n)[:, None]frames = x[idx]return _db(np.mean(frames**2, axis=1))def speech_frames(energies_db: np.ndarray,abs_floor_db: float = -56.0,rel_margin_db: float = 12.0,hangover_frames: int = 15,min_run_frames: int = 5,) -> tuple[np.ndarray, float]:"""Adaptive-threshold energy VAD. Returns (bool mask per frame, noise floor dB)."""noise_floor = float(np.percentile(energies_db, 10))thr = max(abs_floor_db, noise_floor + rel_margin_db)raw = energies_db > thr# Remove short bursts (clicks), then bridge short gaps with a hangover.mask = raw.copy()i = 0n = len(mask)while i < n:if mask[i]:j = iwhile j < n and mask[j]:j += 1if j - i < min_run_frames:mask[i:j] = Falsei = jelse:i += 1# Bridge short gaps between speech runs (inter-word pauses, stop closures).out = mask.copy()on = np.where(mask)[0]if len(on) > 1:gaps = np.diff(on) - 1for g_idx in np.where((gaps > 0) & (gaps <= hangover_frames))[0]:out[on[g_idx] + 1:on[g_idx + 1]] = Truereturn out, noise_floordef analyze(audio: Audio, clip_level: float = 0.999, edge_ms: float = 60.0) -> SignalStats:x, sr = audio.samples, audio.srdur = audio.durationif len(x) == 0:return SignalStats(0, 0, -120, 0, 0, -120, None, None, 0, 0, 0, 0, 0, 0, False, False)peak = float(np.max(np.abs(x)))rms = float(_db(float(np.mean(x**2))))clipped = np.abs(x) >= clip_levelclip_ratio = float(clipped.mean())longest = 0if clipped.any():d = np.diff(np.concatenate([[0], clipped.astype(np.int8), [0]]))starts, ends = np.where(d == 1)[0], np.where(d == -1)[0]longest = int((ends - starts).max())hop_s = 0.010en = frame_energies_db(x, sr)mask, noise_floor = speech_frames(en)segments: list[tuple[float, float]] = []k, n = 0, len(mask)while k < n:if mask[k]:j = kwhile j < n and mask[j]:j += 1segments.append((round(k * hop_s, 3), round(min(dur, j * hop_s + 0.02), 3)))k = jelse:k += 1speech_s = float(sum(e - s for s, e in segments))speech_level = float(np.mean(en[mask])) if mask.any() else Nonesnr = (speech_level - noise_floor) if speech_level is not None else Nonelead = segments[0][0] if segments else durtrail = (dur - segments[-1][1]) if segments else durpauses = [segments[i + 1][0] - segments[i][1] for i in range(len(segments) - 1)]edge_frames = max(1, int(edge_ms / 10))return SignalStats(duration_s=round(dur, 3),peak=round(peak, 4),rms_dbfs=round(rms, 2),clip_ratio=round(clip_ratio, 6),longest_clip_run_ms=round(1000 * longest / sr, 2),noise_floor_db=round(noise_floor, 2),speech_level_db=round(speech_level, 2) if speech_level is not None else None,snr_db=round(snr, 2) if snr is not None else None,speech_s=round(speech_s, 3),speech_ratio=round(speech_s / dur, 4) if dur else 0.0,leading_silence_s=round(max(0.0, lead), 3),trailing_silence_s=round(max(0.0, trail), 3),n_segments=len(segments),longest_internal_pause_s=round(max(pauses), 3) if pauses else 0.0,speech_at_start=bool(mask[:edge_frames].any()),speech_at_end=bool(mask[-edge_frames:].all() and (speech_level is None or float(np.mean(en[-edge_frames:])) >= speech_level - 6.0)),segments=segments,)import re_DEVANAGARI_CONSONANT_OR_VOWEL = re.compile(r"[\u0904-\u0939\u0958-\u0961]")_HALANT = "\u094d"_EN_VOWEL_GROUP = re.compile(r"[aeiouy]+", re.IGNORECASE)def estimate_prompt_duration(text: str | None, language: str = "hi") -> tuple[float, float] | None:"""Estimate expected active speech window (T_min, T_max) in seconds from prompt text."""if not text or not text.strip():return Noneclean = text.strip()if language == "hi" or _DEVANAGARI_CONSONANT_OR_VOWEL.search(clean):units = len(_DEVANAGARI_CONSONANT_OR_VOWEL.findall(clean)) - clean.count(_HALANT)units = max(1, units)t_min = max(0.65, round(0.068 * units, 2))t_max = round(0.55 * units + 1.5, 2)return (t_min, max(t_min + 1.2, t_max))# English / Latin syllable approximationwords = re.findall(r"[A-Za-z0-9']+", clean)syllables = 0for w in words:if w.isdigit():syllables += max(1, len(w))else:groups = _EN_VOWEL_GROUP.findall(w)cnt = len(groups)if w.lower().endswith("e") and cnt > 1 and not w.lower().endswith(("le", "ee", "ie")):cnt -= 1syllables += max(1, cnt)units = max(1, syllables)t_min = max(0.65, round(0.068 * units, 2))t_max = round(0.55 * units + 1.5, 2)return (t_min, max(t_min + 1.2, t_max))def trim_silence(audio: Audio, stats: SignalStats, pad_s: float = 0.20) -> Audio:"""Slice audio to active speech bounds +/- pad_s so ASR never wastes CPU on dead air."""if not stats.segments or len(audio.samples) == 0:return audiostart_s = max(0.0, stats.segments[0][0] - pad_s)end_s = min(audio.duration, stats.segments[-1][1] + pad_s)if end_s <= start_s:return audioi0 = int(start_s * audio.sr)i1 = int(end_s * audio.sr)trimmed = np.ascontiguousarray(audio.samples[i0:i1], dtype=np.float32)return Audio(trimmed, audio.sr, audio.original_sr, audio.original_channels, audio.original_subtype)
9 unmodified lines10111213141516105 unmodified lines1221231241251261271289 unmodified linesfrom ..align import Alignment, AlignOp, align, align_lexical, char_error_rate, format_word_feedbackfrom ..asr import ASRResultfrom ..textnorm import NormConfig, _PUNCT_RE, _SPACE_RE, _ZW_RE, normalize, tokenizefrom .base import Finding, ValidatorResult105 unmodified lines{"cer_between": m["cer_between"], "threshold": th["cer_accept"] * 2},model_based=True, contributor_visible=False))if m.get("word_errors", 0) > 0 or m["cer"] > th["cer_accept"]:norm_ref = m["ref_norm"].split(" ") if m["ref_norm"] else []surf_ref = _surface_tokens(prompt_text)use_surface = len(surf_ref) == len(norm_ref)9 unmodified lines10111213141516105 unmodified lines1221231241251261271281291301319 unmodified linesfrom ..align import Alignment, AlignOp, align, align_lexical, char_error_rate, format_word_feedbackfrom ..asr import ASRResultfrom ..textnorm import NormConfig, _PUNCT_RE, _SPACE_RE, _ZW_RE, normalize, indic_asr_key, tokenizefrom .base import Finding, ValidatorResult105 unmodified lines{"cer_between": m["cer_between"], "threshold": th["cer_accept"] * 2},model_based=True, contributor_visible=False))ref_phon = " ".join(indic_asr_key(w) for w in tokenize(prompt_text, norm))hyp_phon = " ".join(indic_asr_key(o["hyp"]) for o in m["alignment"] if o.get("hyp"))phon_cer = char_error_rate(ref_phon, hyp_phon)if m.get("word_errors", 0) > 0 or min(m["cer"], phon_cer) > th["cer_accept"]:norm_ref = m["ref_norm"].split(" ") if m["ref_norm"] else []surf_ref = _surface_tokens(prompt_text)use_surface = len(surf_ref) == len(norm_ref)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154"""Universal QC (deck slide 8): inherited by every task.Decision rule: corruption or missing consent -> block. Contributor-fixablecapture problems (clipping, no speech, cut-off, too quiet) -> retry guidance.Difficult speech, noise, accents or low confidence -> keep and send to review."""from __future__ import annotationsfrom dataclasses import dataclassfrom typing import Optionalfrom ..audio import Audio, SignalStatsfrom .base import Finding, ValidatorResultdef _clamp(x: float, lo: float = 0.0, hi: float = 1.0) -> float:return max(lo, min(hi, x))@dataclassclass RecordingContext:task_id: strtask_type: strlanguage: strspeaker_id: Optional[str] = Noneconsent_version: Optional[str] = Noneproject_consent_version: Optional[str] = Nonedeclared_language: Optional[str] = Noneretrospective: bool = False # auditing an existing corpus: no consent/speaker checksdef integrity(audio: Audio, stats: SignalStats, th: dict) -> ValidatorResult:r = ValidatorResult("integrity", "L0")r.data = {"original_sr": audio.original_sr,"original_channels": audio.original_channels,"subtype": audio.original_subtype,"duration_s": stats.duration_s,}if stats.duration_s == 0:r.findings.append(Finding("empty_audio", "block", r.name, "The file has no audio."))return rif stats.peak == 0.0:r.findings.append(Finding("digital_silence", "block", r.name,"The recording is completely silent. Check that the microphone is allowed."))return rif audio.original_sr < th["min_source_sr"]:r.findings.append(Finding("low_sample_rate", "review", r.name,f"Audio was recorded at {audio.original_sr} Hz, below the {th['min_source_sr']} Hz target.",{"original_sr": audio.original_sr}))if stats.duration_s < th["min_duration_s"]:r.findings.append(Finding("too_short", "retry", r.name,"The recording is very short. Please record the whole prompt.",{"duration_s": stats.duration_s}))if stats.duration_s > th["max_duration_s"]:r.findings.append(Finding("too_long", "review", r.name,"The recording is longer than expected for this task.",{"duration_s": stats.duration_s}))return rdef acoustic(stats: SignalStats, th: dict) -> ValidatorResult:r = ValidatorResult("acoustic", "L1")r.data = stats.as_dict()if stats.speech_s < th["min_speech_s"]:r.findings.append(Finding("no_speech", "retry", r.name,"We couldn't hear speech. Speak a little louder or closer to the phone.",{"speech_s": stats.speech_s}))max_clip = th["max_clip_ratio"]if stats.clip_ratio > max_clip or stats.longest_clip_run_ms > th["max_clip_run_ms"]:r.findings.append(Finding("clipping", "retry", r.name,"The sound is distorted. Hold the phone a little further from your mouth.",{"clip_ratio": stats.clip_ratio, "longest_clip_run_ms": stats.longest_clip_run_ms}))if stats.speech_level_db is not None and stats.speech_level_db < th["min_speech_level_db"]:r.findings.append(Finding("too_quiet", "retry", r.name,"Your voice is very quiet. Move closer to the phone.",{"speech_level_db": stats.speech_level_db}))if stats.snr_db is not None and stats.snr_db < th["min_snr_db"] and stats.speech_s >= th["min_speech_s"]:# Noise alone never forces a retry: real-world conditions are valid data.r.findings.append(Finding("background_noise", "review", r.name,"There is noticeable background noise. A quieter spot helps, but this recording is kept.",{"snr_db": stats.snr_db}))if th.get("truncation_check", True) and stats.speech_s >= th["min_speech_s"]:if stats.speech_at_end:r.findings.append(Finding("cut_off_end", "retry", r.name,"The recording may have stopped before you finished. Wait a moment before tapping stop."))if stats.speech_at_start:r.findings.append(Finding("cut_off_start", "retry", r.name,"The recording may have started after you began speaking. Tap record, wait a moment, then speak."))if stats.leading_silence_s > th["max_leading_silence_s"]:r.findings.append(Finding("long_leading_silence", "info", r.name,"There is a long pause before you start speaking.",{"leading_silence_s": stats.leading_silence_s}))if stats.trailing_silence_s > th["max_trailing_silence_s"]:r.findings.append(Finding("long_trailing_silence", "info", r.name,"There is a long pause after you finish.",{"trailing_silence_s": stats.trailing_silence_s}))r.scores["technical_audio"] = technical_audio_score(stats, th)r.scores["clarity_continuity"] = continuity_score(stats, th)r.scores["speech_activity_duration"] = _clamp(stats.speech_s / max(1e-6, th["target_speech_s"]))return rdef technical_audio_score(stats: SignalStats, th: dict) -> float:if stats.speech_s <= 0:return 0.0m = th["max_clip_ratio"]clip = 1.0 if stats.clip_ratio <= m else _clamp(1 - stats.clip_ratio / (10 * m))lvl_db = stats.speech_level_db if stats.speech_level_db is not None else -120level = _clamp((lvl_db + 60) / (th["min_speech_level_db"] + 60 + 1e-6))snr = _clamp(((stats.snr_db or 0) - 5) / 20)return round((clip + level + snr) / 3, 4)def continuity_score(stats: SignalStats, th: dict) -> float:mp = th["max_internal_pause_s"]pause = 1.0 if stats.longest_internal_pause_s <= mp else _clamp(1 - (stats.longest_internal_pause_s - mp) / mp)edges = 1.0if stats.leading_silence_s > th["max_leading_silence_s"]:edges -= 0.25if stats.trailing_silence_s > th["max_trailing_silence_s"]:edges -= 0.25cut = 0.5 if (stats.speech_at_end or stats.speech_at_start) else 1.0return round(pause * edges * cut, 4)def metadata(ctx: RecordingContext) -> ValidatorResult:r = ValidatorResult("metadata", "L0")if ctx.retrospective:r.scores["metadata"] = Noner.data["skipped"] = "retrospective audit"return rok = Trueif not ctx.speaker_id:r.findings.append(Finding("missing_speaker", "block", r.name, "Recording has no speaker ID."))ok = Falseif not ctx.consent_version:r.findings.append(Finding("missing_consent", "block", r.name, "No consent is recorded for this speaker."))ok = Falseelif ctx.project_consent_version and ctx.consent_version != ctx.project_consent_version:r.findings.append(Finding("stale_consent", "block", r.name,"Consent was given for a different version of this project. Please review and accept the current consent.",{"given": ctx.consent_version, "required": ctx.project_consent_version}))ok = Falseif ctx.declared_language and ctx.declared_language != ctx.language:r.findings.append(Finding("language_mismatch", "block", r.name,"The recording's language does not match the task.",{"declared": ctx.declared_language, "task": ctx.language}))ok = Falser.scores["metadata"] = 1.0 if ok else 0.0return r123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172"""Universal QC (deck slide 8): inherited by every task.Decision rule: corruption or missing consent -> block. Contributor-fixablecapture problems (clipping, no speech, cut-off, too quiet) -> retry guidance.Difficult speech, noise, accents or low confidence -> keep and send to review."""from __future__ import annotationsfrom dataclasses import dataclassfrom typing import Optionalfrom ..audio import Audio, SignalStatsfrom .base import Finding, ValidatorResultdef _clamp(x: float, lo: float = 0.0, hi: float = 1.0) -> float:return max(lo, min(hi, x))@dataclassclass RecordingContext:task_id: strtask_type: strlanguage: strspeaker_id: Optional[str] = Noneconsent_version: Optional[str] = Noneproject_consent_version: Optional[str] = Nonedeclared_language: Optional[str] = Noneretrospective: bool = False # auditing an existing corpus: no consent/speaker checksdef integrity(audio: Audio, stats: SignalStats, th: dict) -> ValidatorResult:r = ValidatorResult("integrity", "L0")r.data = {"original_sr": audio.original_sr,"original_channels": audio.original_channels,"subtype": audio.original_subtype,"duration_s": stats.duration_s,}if stats.duration_s == 0:r.findings.append(Finding("empty_audio", "block", r.name, "The file has no audio."))return rif stats.peak == 0.0:r.findings.append(Finding("digital_silence", "block", r.name,"The recording is completely silent. Check that the microphone is allowed."))return rif audio.original_sr < th["min_source_sr"]:r.findings.append(Finding("low_sample_rate", "review", r.name,f"Audio was recorded at {audio.original_sr} Hz, below the {th['min_source_sr']} Hz target.",{"original_sr": audio.original_sr}))if stats.duration_s < th["min_duration_s"]:r.findings.append(Finding("too_short", "retry", r.name,"The recording is very short. Please record the whole prompt.",{"duration_s": stats.duration_s}))if stats.duration_s > th["max_duration_s"]:r.findings.append(Finding("too_long", "review", r.name,"The recording is longer than expected for this task.",{"duration_s": stats.duration_s}))return rdef acoustic(stats: SignalStats, th: dict, prompt_text: str | None = None, language: str = 'hi') -> ValidatorResult:r = ValidatorResult("acoustic", "L1")r.data = stats.as_dict()if stats.speech_s < th["min_speech_s"]:r.findings.append(Finding("no_speech", "retry", r.name,"We couldn't hear speech. Speak a little louder or closer to the phone.",{"speech_s": stats.speech_s}))max_clip = th["max_clip_ratio"]if stats.clip_ratio > max_clip or stats.longest_clip_run_ms > th["max_clip_run_ms"]:r.findings.append(Finding("clipping", "retry", r.name,"The sound is distorted. Hold the phone a little further from your mouth.",{"clip_ratio": stats.clip_ratio, "longest_clip_run_ms": stats.longest_clip_run_ms}))if stats.speech_level_db is not None and stats.speech_level_db < th["min_speech_level_db"]:r.findings.append(Finding("too_quiet", "retry", r.name,"Your voice is very quiet. Move closer to the phone.",{"speech_level_db": stats.speech_level_db}))if stats.snr_db is not None and stats.snr_db < th["min_snr_db"] and stats.speech_s >= th["min_speech_s"]:# Noise alone never forces a retry: real-world conditions are valid data.r.findings.append(Finding("background_noise", "review", r.name,"There is noticeable background noise. A quieter spot helps, but this recording is kept.",{"snr_db": stats.snr_db}))if th.get("truncation_check", True) and stats.speech_s >= th["min_speech_s"]:if stats.speech_at_end:r.findings.append(Finding("cut_off_end", "retry", r.name,"The recording may have stopped before you finished. Wait a moment before tapping stop."))if stats.speech_at_start:r.findings.append(Finding("cut_off_start", "retry", r.name,"The recording may have started after you began speaking. Tap record, wait a moment, then speak."))if stats.leading_silence_s > th["max_leading_silence_s"]:r.findings.append(Finding("long_leading_silence", "retry", r.name,f"Long silence ({stats.leading_silence_s:.1f}s) detected before speaking. Start speaking right after tapping record.",{"leading_silence_s": stats.leading_silence_s}))if stats.trailing_silence_s > th["max_trailing_silence_s"]:r.findings.append(Finding("long_trailing_silence", "retry", r.name,f"Long silence ({stats.trailing_silence_s:.1f}s) detected after finishing. Tap stop right after you finish.",{"trailing_silence_s": stats.trailing_silence_s}))if stats.speech_s >= th["min_speech_s"] and stats.longest_internal_pause_s > th["max_internal_pause_s"]:r.findings.append(Finding("long_internal_pause", "review", r.name,f"Long mid-sentence pause ({stats.longest_internal_pause_s:.1f}s) detected. Try reading smoothly in one flow.",{"longest_internal_pause_s": stats.longest_internal_pause_s}))if prompt_text and stats.speech_s >= th["min_speech_s"]:from ..audio import estimate_prompt_durationbounds = estimate_prompt_duration(prompt_text, language)if bounds is not None:t_min, t_max = boundsr.data["expected_speech_range_s"] = [t_min, t_max]if stats.speech_s < t_min:r.findings.append(Finding("speech_too_short_for_prompt", "retry", r.name,f"Recording speech ({stats.speech_s:.1f}s) is too short for this prompt (expected {t_min:.1f}–{t_max:.1f}s). Please read the full sentence clearly.",{"speech_s": stats.speech_s, "expected_min_s": t_min, "expected_max_s": t_max}))elif stats.speech_s > t_max:r.findings.append(Finding("speech_too_long_for_prompt", "review", r.name,f"Recording speech ({stats.speech_s:.1f}s) took longer than expected ({t_min:.1f}–{t_max:.1f}s).",{"speech_s": stats.speech_s, "expected_min_s": t_min, "expected_max_s": t_max}))r.scores["technical_audio"] = technical_audio_score(stats, th)r.scores["clarity_continuity"] = continuity_score(stats, th)r.scores["speech_activity_duration"] = _clamp(stats.speech_s / max(1e-6, th["target_speech_s"]))return rdef technical_audio_score(stats: SignalStats, th: dict) -> float:if stats.speech_s <= 0:return 0.0m = th["max_clip_ratio"]clip = 1.0 if stats.clip_ratio <= m else _clamp(1 - stats.clip_ratio / (10 * m))lvl_db = stats.speech_level_db if stats.speech_level_db is not None else -120level = _clamp((lvl_db + 60) / (th["min_speech_level_db"] + 60 + 1e-6))snr = _clamp(((stats.snr_db or 0) - 5) / 20)return round((clip + level + snr) / 3, 4)def continuity_score(stats: SignalStats, th: dict) -> float:mp = th["max_internal_pause_s"]pause = 1.0 if stats.longest_internal_pause_s <= mp else _clamp(1 - (stats.longest_internal_pause_s - mp) / mp)edges = 1.0if stats.leading_silence_s > th["max_leading_silence_s"]:edges -= 0.25if stats.trailing_silence_s > th["max_trailing_silence_s"]:edges -= 0.25cut = 0.5 if (stats.speech_at_end or stats.speech_at_start) else 1.0return round(pause * edges * cut, 4)def metadata(ctx: RecordingContext) -> ValidatorResult:r = ValidatorResult("metadata", "L0")if ctx.retrospective:r.scores["metadata"] = Noner.data["skipped"] = "retrospective audit"return rok = Trueif not ctx.speaker_id:r.findings.append(Finding("missing_speaker", "block", r.name, "Recording has no speaker ID."))ok = Falseif not ctx.consent_version:r.findings.append(Finding("missing_consent", "block", r.name, "No consent is recorded for this speaker."))ok = Falseelif ctx.project_consent_version and ctx.consent_version != ctx.project_consent_version:r.findings.append(Finding("stale_consent", "block", r.name,"Consent was given for a different version of this project. Please review and accept the current consent.",{"given": ctx.consent_version, "required": ctx.project_consent_version}))ok = Falseif ctx.declared_language and ctx.declared_language != ctx.language:r.findings.append(Finding("language_mismatch", "block", r.name,"The recording's language does not match the task.",{"declared": ctx.declared_language, "task": ctx.language}))ok = Falser.scores["metadata"] = 1.0 if ok else 0.0return r
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229"""Confidence that a recording is usable, shown at the end of each recording.One probability per recording, combined from the same signals in live QC and inthe retrospective audit:cer_best lowest character error rate of any ASR model vs the promptcer_between how much the ASR models disagree with each otherall_disagree every model missed some prompt wordsnr_low, clipping, truncated, no_speechprosody_gap 1 - punctuation_prosody score (TTS / prosody tasks)mfa_bad, mfa_good forced-alignment fit, when MFA has runrate_z speaking-rate z-score vs the language median (needs a calibrated model)Without calibration the weights are hand-set defaults and the score is labelled"uncalibrated". `scqc calibrate` fits a logistic regression on humanadjudications (e.g. your co-authors' labels from the defect audit), so that ascore of 0.85 means roughly 85% of such recordings were judged valid. The scoreroutes recordings (auto-accept above the task's threshold, otherwise review);it never rejects one."""from __future__ import annotationsimport jsonimport mathimport osfrom functools import lru_cachefrom typing import Optionalimport numpy as npFEATURES = ["cer_best", "cer_between", "all_disagree", "snr_low", "clipping", "truncated", "no_speech","prosody_gap", "mfa_bad", "mfa_good", "rate_z_abs", "asr_missing"]DEFAULT_MODEL = {"version": "default-2026-11","calibrated": False,"bias": 3.0,"weights": {"cer_best": -9.0, "cer_between": -2.0, "all_disagree": -1.0, "snr_low": -0.8, "clipping": -1.5,"truncated": -2.0, "no_speech": -7.0, "prosody_gap": -2.5, "mfa_bad": -2.0, "mfa_good": 0.5,"rate_z_abs": 0.0, "asr_missing": -2.0},"rate_medians": {},}def _sigmoid(z: float) -> float:return 1.0 / (1.0 + math.exp(-max(-30.0, min(30.0, z))))def label(p: float) -> str:return "high" if p >= 0.8 else "medium" if p >= 0.5 else "low"# ------------------------------------------------------------------ featuresdef _num(v) -> Optional[float]:try:f = float(v)return f if math.isfinite(f) else Noneexcept (TypeError, ValueError):return Nonedef features_from_signals(sig: dict, model: dict) -> dict[str, float]:"""`sig` keys: cer_best, cer_between, all_disagree, snr_db, clipping, truncated, speech_s,prosody_score, mfa_aligned, mfa_ll_z, rate_cps, language. Missing signals contribute 0."""f = {k: 0.0 for k in FEATURES}cer = _num(sig.get("cer_best"))if cer is not None:f["cer_best"] = min(cer, 1.5)cb = _num(sig.get("cer_between"))if cb is not None:f["cer_between"] = min(cb, 1.5)f["all_disagree"] = float(bool(sig.get("all_disagree")))f["asr_missing"] = float(bool(sig.get("asr_missing")))snr = _num(sig.get("snr_db"))f["snr_low"] = float(snr is not None and snr < 15)f["clipping"] = float(bool(sig.get("clipping")))f["truncated"] = float(bool(sig.get("truncated")))sp = _num(sig.get("speech_s"))f["no_speech"] = float(sp is not None and sp < 0.3)ps = _num(sig.get("prosody_score"))if ps is not None:f["prosody_gap"] = 1.0 - psif sig.get("mfa_aligned") is not None:llz = _num(sig.get("mfa_ll_z"))bad = (not sig["mfa_aligned"]) or (llz is not None and llz < -2.5)f["mfa_bad"] = float(bad)f["mfa_good"] = float(bool(sig["mfa_aligned"]) and llz is not None and llz > -1.0)rate, lang = _num(sig.get("rate_cps")), sig.get("language")med = (model.get("rate_medians") or {}).get(lang)if rate and med:f["rate_z_abs"] = min(abs(rate - med[0]) / max(med[1], 1e-6), 6.0)return fdef signals_from_report(rep: dict, language: str, prompt_text: Optional[str]) -> dict:"""Pull confidence signals out of a live QC report."""sig: dict = {"language": language}s = rep.get("signal") or {}sig["snr_db"], sig["speech_s"] = s.get("snr_db"), s.get("speech_s")codes = {f["code"] for f in rep.get("findings", [])}sig["clipping"] = "clipping" in codessig["truncated"] = bool({"cut_off_end", "cut_off_start"} & codes)if "decode_failed" in codes or "digital_silence" in codes:sig["speech_s"] = 0.0for v in rep.get("validators", []):d = v.get("data") or {}if v["name"] in ("read_speech_match", "command_match", "tts_prosody_lexical", "prosody_pair_lexical") \and not v.get("available", True):sig["asr_missing"] = True # the transcript check this task needs did not runif v["name"] in ("read_speech_match", "command_match", "tts_prosody_lexical", "prosody_pair_lexical") and "cer" in d:sig["cer_best"] = d["cer"]sig["cer_between"] = d.get("cer_between")sig["all_disagree"] = d.get("all_models_disagree", d.get("cer", 0) > 0.3)if v["name"] == "prosody":sc = [x for x in (v.get("scores") or {}).values() if x is not None]if sc:sig["prosody_score"] = sc[0]if v["name"] == "mfa_alignment":sig["mfa_aligned"], sig["mfa_ll_z"] = d.get("aligned"), d.get("ll_z")if prompt_text and s.get("speech_s"):from .textnorm import normalizechars = len(normalize(prompt_text).replace(" ", ""))sig["rate_cps"] = chars / s["speech_s"] if s["speech_s"] > 0.3 else Nonereturn sigdef signals_from_evidence(row: dict, detect_models: list[str]) -> dict:"""Same signals from a defect-audit evidence.csv row."""cers = [_num(row.get(f"cer_{m}")) for m in detect_models]cers = [c for c in cers if c is not None]return {"language": row.get("language"),"cer_best": min(cers) if cers else None,"cer_between": row.get("cer_between_models"),"all_disagree": bool(cers) and all(c > 0.3 for c in cers),"snr_db": row.get("snr_db"),"speech_s": row.get("speech_s"),"truncated": str(row.get("speech_at_end", "0")) in ("1", "True", "true"),"mfa_aligned": (str(row.get("mfa_aligned")) in ("True", "true", "1")) if row.get("mfa_aligned") not in (None, "") else None,"mfa_ll_z": row.get("mfa_ll_z"),"rate_cps": row.get("rate_cps"),}# ------------------------------------------------------------------ scoring@lru_cache(maxsize=4)def _load(path: str) -> dict:with open(path, encoding="utf-8") as f:return json.load(f)def model() -> dict:path = os.environ.get("SCQC_CONFIDENCE_MODEL")if path and os.path.exists(path):try:return _load(path)except Exception:passreturn DEFAULT_MODELdef score(sig: dict, m: Optional[dict] = None) -> dict:m = m or model()f = features_from_signals(sig, m)z = m["bias"] + sum(m["weights"].get(k, 0.0) * v for k, v in f.items())p = _sigmoid(z)return {"score": round(p, 3), "label": label(p), "calibrated": bool(m.get("calibrated")),"model": m.get("version"), "features": {k: round(v, 4) for k, v in f.items() if v}}# ------------------------------------------------------------------ calibrationdef fit(signals: list[dict], labels: list[int], weights: Optional[list[float]] = None,l2: float = 0.1, folds: int = 5, seed: int = 0) -> dict:"""Logistic regression (IRLS with L2) on human labels (1 = valid). Returns a modeldict plus cross-validated Brier score and expected calibration error."""langs: dict[str, list[float]] = {}for s in signals:r = _num(s.get("rate_cps"))if r and s.get("language"):langs.setdefault(s["language"], []).append(r)rate_medians = {}for l, v in langs.items():a = np.array(v)med = float(np.median(a))rate_medians[l] = [med, float(np.median(np.abs(a - med)) * 1.4826) or 1.0]base = {"rate_medians": rate_medians}X = np.array([[features_from_signals(s, base)[k] for k in FEATURES] for s in signals])y = np.array(labels, dtype=float)w = np.array(weights if weights is not None else np.ones(len(y)), dtype=float)def irls(Xt, yt, wt):A = np.hstack([np.ones((len(Xt), 1)), Xt])beta = np.zeros(A.shape[1])R = np.eye(A.shape[1]) * l2R[0, 0] = 0.0for _ in range(50):p = 1 / (1 + np.exp(-np.clip(A @ beta, -30, 30)))W = wt * p * (1 - p) + 1e-9g = A.T @ (wt * (yt - p)) - R @ betaH = A.T @ (A * W[:, None]) + Rstep = np.linalg.solve(H, g)beta += stepif np.max(np.abs(step)) < 1e-6:breakreturn betarng = np.random.default_rng(seed)idx = rng.permutation(len(y))preds = np.zeros(len(y))k = max(2, min(folds, len(y)))for fi in range(k):test = idx[fi::k]train = np.setdiff1d(idx, test)if len(np.unique(y[train])) < 2:preds[test] = y[train].mean()continueb = irls(X[train], y[train], w[train])preds[test] = 1 / (1 + np.exp(-np.clip(b[0] + X[test] @ b[1:], -30, 30)))brier = float(np.average((preds - y) ** 2, weights=w))bins = np.clip((preds * 10).astype(int), 0, 9)ece = sum(abs(np.average(preds[bins == b], weights=w[bins == b]) - np.average(y[bins == b], weights=w[bins == b]))* w[bins == b].sum() for b in range(10) if (bins == b).any()) / w.sum()beta = irls(X, y, w)return {"version": "calibrated", "calibrated": True, "bias": float(beta[0]),"weights": {k_: float(v) for k_, v in zip(FEATURES, beta[1:])},"rate_medians": rate_medians, "n_train": int(len(y)), "positive_rate": float(np.average(y, weights=w)),"cv_brier": round(brier, 4), "cv_ece": round(float(ece), 4),}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248"""Confidence that a recording is usable, shown at the end of each recording.One probability per recording, combined from the same signals in live QC and inthe retrospective audit:cer_best lowest character error rate of any ASR model vs the promptcer_between how much the ASR models disagree with each otherall_disagree every model missed some prompt wordsnr_low, clipping, truncated, no_speechprosody_gap 1 - punctuation_prosody score (TTS / prosody tasks)mfa_bad, mfa_good forced-alignment fit, when MFA has runrate_z speaking-rate z-score vs the language median (needs a calibrated model)Without calibration the weights are hand-set defaults and the score is labelled"uncalibrated". `scqc calibrate` fits a logistic regression on humanadjudications (e.g. your co-authors' labels from the defect audit), so that ascore of 0.85 means roughly 85% of such recordings were judged valid. The scoreroutes recordings (auto-accept above the task's threshold, otherwise review);it never rejects one."""from __future__ import annotationsimport jsonimport mathimport osfrom functools import lru_cachefrom typing import Optionalimport numpy as npFEATURES = ["cer_best", "cer_between", "all_disagree", "snr_low", "snr_margin", "clipping", "truncated","no_speech", "prosody_gap", "mfa_bad", "mfa_good", "rate_z_abs", "asr_missing","asr_conf_gap", "pause_penalty", "silence_excess"]DEFAULT_MODEL = {"version": "default-2026-11-continuous","calibrated": False,"bias": 2.15,"weights": {"cer_best": -9.0, "cer_between": -2.0, "all_disagree": -1.0, "snr_low": -0.8,"snr_margin": 0.65, "clipping": -2.2, "truncated": -2.2, "no_speech": -7.0,"prosody_gap": -2.5, "mfa_bad": -2.0, "mfa_good": 0.5, "rate_z_abs": -0.25,"asr_missing": -2.2, "asr_conf_gap": -1.6, "pause_penalty": -1.2, "silence_excess": -1.4},"rate_medians": {},}def _sigmoid(z: float) -> float:return 1.0 / (1.0 + math.exp(-max(-30.0, min(30.0, z))))def label(p: float) -> str:return "high" if p >= 0.8 else "medium" if p >= 0.5 else "low"# ------------------------------------------------------------------ featuresdef _num(v) -> Optional[float]:try:f = float(v)return f if math.isfinite(f) else Noneexcept (TypeError, ValueError):return Nonedef features_from_signals(sig: dict, model: dict) -> dict[str, float]:"""`sig` keys: cer_best, cer_between, all_disagree, snr_db, clipping, truncated, speech_s,prosody_score, mfa_aligned, mfa_ll_z, rate_cps, language. Missing signals contribute 0."""f = {k: 0.0 for k in FEATURES}cer = _num(sig.get("cer_best"))if cer is not None:f["cer_best"] = min(cer, 1.5)cb = _num(sig.get("cer_between"))if cb is not None:f["cer_between"] = min(cb, 1.5)f["all_disagree"] = float(bool(sig.get("all_disagree")))f["asr_missing"] = float(bool(sig.get("asr_missing")))snr = _num(sig.get("snr_db"))f["snr_low"] = float(snr is not None and snr < 15)if snr is not None:f["snr_margin"] = max(-1.0, min(1.0, (snr - 15.0) / 25.0))ac = _num(sig.get("asr_confidence"))if ac is not None:f["asr_conf_gap"] = max(0.0, min(1.0, 1.0 - ac))pause = _num(sig.get("longest_internal_pause_s"))if pause is not None and pause > 1.2:f["pause_penalty"] = min(2.0, (pause - 1.2) / 1.5)lead = _num(sig.get("leading_silence_s")) or 0.0trail = _num(sig.get("trailing_silence_s")) or 0.0if max(lead, trail) > 2.0:f["silence_excess"] = min(2.0, (max(lead, trail) - 2.0) / 3.0)f["clipping"] = float(bool(sig.get("clipping")))f["truncated"] = float(bool(sig.get("truncated")))sp = _num(sig.get("speech_s"))f["no_speech"] = float(sp is not None and sp < 0.3)ps = _num(sig.get("prosody_score"))if ps is not None:f["prosody_gap"] = 1.0 - psif sig.get("mfa_aligned") is not None:llz = _num(sig.get("mfa_ll_z"))bad = (not sig["mfa_aligned"]) or (llz is not None and llz < -2.5)f["mfa_bad"] = float(bad)f["mfa_good"] = float(bool(sig["mfa_aligned"]) and llz is not None and llz > -1.0)rate, lang = _num(sig.get("rate_cps")), sig.get("language")med = (model.get("rate_medians") or {}).get(lang)if rate and med:f["rate_z_abs"] = min(abs(rate - med[0]) / max(med[1], 1e-6), 6.0)return fdef signals_from_report(rep: dict, language: str, prompt_text: Optional[str]) -> dict:"""Pull confidence signals out of a live QC report."""sig: dict = {"language": language}s = rep.get("signal") or {}sig["snr_db"], sig["speech_s"] = s.get("snr_db"), s.get("speech_s")sig["longest_internal_pause_s"] = s.get("longest_internal_pause_s")sig["leading_silence_s"] = s.get("leading_silence_s")sig["trailing_silence_s"] = s.get("trailing_silence_s")codes = {f["code"] for f in rep.get("findings", [])}sig["clipping"] = "clipping" in codessig["truncated"] = bool({"cut_off_end", "cut_off_start"} & codes)if "decode_failed" in codes or "digital_silence" in codes:sig["speech_s"] = 0.0for v in rep.get("validators", []):d = v.get("data") or {}if v["name"] in ("read_speech_match", "command_match", "tts_prosody_lexical", "prosody_pair_lexical") \and not v.get("available", True):sig["asr_missing"] = True # the transcript check this task needs did not runif v["name"] in ("read_speech_match", "command_match", "tts_prosody_lexical", "prosody_pair_lexical") and "cer" in d:sig["cer_best"] = d["cer"]sig["cer_between"] = d.get("cer_between")sig["all_disagree"] = d.get("all_models_disagree", d.get("cer", 0) > 0.3)if d.get("asr_confidence") is not None:sig["asr_confidence"] = d["asr_confidence"]if v["name"] == "prosody":sc = [x for x in (v.get("scores") or {}).values() if x is not None]if sc:sig["prosody_score"] = sc[0]if v["name"] == "mfa_alignment":sig["mfa_aligned"], sig["mfa_ll_z"] = d.get("aligned"), d.get("ll_z")if prompt_text and s.get("speech_s"):from .textnorm import normalizechars = len(normalize(prompt_text).replace(" ", ""))sig["rate_cps"] = chars / s["speech_s"] if s["speech_s"] > 0.3 else Nonereturn sigdef signals_from_evidence(row: dict, detect_models: list[str]) -> dict:"""Same signals from a defect-audit evidence.csv row."""cers = [_num(row.get(f"cer_{m}")) for m in detect_models]cers = [c for c in cers if c is not None]return {"language": row.get("language"),"cer_best": min(cers) if cers else None,"cer_between": row.get("cer_between_models"),"all_disagree": bool(cers) and all(c > 0.3 for c in cers),"snr_db": row.get("snr_db"),"speech_s": row.get("speech_s"),"truncated": str(row.get("speech_at_end", "0")) in ("1", "True", "true"),"mfa_aligned": (str(row.get("mfa_aligned")) in ("True", "true", "1")) if row.get("mfa_aligned") not in (None, "") else None,"mfa_ll_z": row.get("mfa_ll_z"),"rate_cps": row.get("rate_cps"),}# ------------------------------------------------------------------ scoring@lru_cache(maxsize=4)def _load(path: str) -> dict:with open(path, encoding="utf-8") as f:return json.load(f)def model() -> dict:path = os.environ.get("SCQC_CONFIDENCE_MODEL")if path and os.path.exists(path):try:return _load(path)except Exception:passreturn DEFAULT_MODELdef score(sig: dict, m: Optional[dict] = None) -> dict:m = m or model()f = features_from_signals(sig, m)z = m["bias"] + sum(m["weights"].get(k, 0.0) * v for k, v in f.items())p = _sigmoid(z)return {"score": round(p, 3), "label": label(p), "calibrated": bool(m.get("calibrated")),"model": m.get("version"), "features": {k: round(v, 4) for k, v in f.items() if v}}# ------------------------------------------------------------------ calibrationdef fit(signals: list[dict], labels: list[int], weights: Optional[list[float]] = None,l2: float = 0.1, folds: int = 5, seed: int = 0) -> dict:"""Logistic regression (IRLS with L2) on human labels (1 = valid). Returns a modeldict plus cross-validated Brier score and expected calibration error."""langs: dict[str, list[float]] = {}for s in signals:r = _num(s.get("rate_cps"))if r and s.get("language"):langs.setdefault(s["language"], []).append(r)rate_medians = {}for l, v in langs.items():a = np.array(v)med = float(np.median(a))rate_medians[l] = [med, float(np.median(np.abs(a - med)) * 1.4826) or 1.0]base = {"rate_medians": rate_medians}X = np.array([[features_from_signals(s, base)[k] for k in FEATURES] for s in signals])y = np.array(labels, dtype=float)w = np.array(weights if weights is not None else np.ones(len(y)), dtype=float)def irls(Xt, yt, wt):A = np.hstack([np.ones((len(Xt), 1)), Xt])beta = np.zeros(A.shape[1])R = np.eye(A.shape[1]) * l2R[0, 0] = 0.0for _ in range(50):p = 1 / (1 + np.exp(-np.clip(A @ beta, -30, 30)))W = wt * p * (1 - p) + 1e-9g = A.T @ (wt * (yt - p)) - R @ betaH = A.T @ (A * W[:, None]) + Rstep = np.linalg.solve(H, g)beta += stepif np.max(np.abs(step)) < 1e-6:breakreturn betarng = np.random.default_rng(seed)idx = rng.permutation(len(y))preds = np.zeros(len(y))k = max(2, min(folds, len(y)))for fi in range(k):test = idx[fi::k]train = np.setdiff1d(idx, test)if len(np.unique(y[train])) < 2:preds[test] = y[train].mean()continueb = irls(X[train], y[train], w[train])preds[test] = 1 / (1 + np.exp(-np.clip(b[0] + X[test] @ b[1:], -30, 30)))brier = float(np.average((preds - y) ** 2, weights=w))bins = np.clip((preds * 10).astype(int), 0, 9)ece = sum(abs(np.average(preds[bins == b], weights=w[bins == b]) - np.average(y[bins == b], weights=w[bins == b]))* w[bins == b].sum() for b in range(10) if (bins == b).any()) / w.sum()beta = irls(X, y, w)return {"version": "calibrated", "calibrated": True, "bias": float(beta[0]),"weights": {k_: float(v) for k_, v in zip(FEATURES, beta[1:])},"rate_medians": rate_medians, "n_train": int(len(y)), "positive_rate": float(np.average(y, weights=w)),"cv_brier": round(brier, 4), "cv_ece": round(float(ece), 4),}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211"""Run QC for one recording and turn validator findings into a decision.Levels (deck slide 14)L0 capture decode, save, consent/metadataL1 acoustic VAD, clipping, level, duration, truncation, noiseL2 intelligent ASR matching where the task has a referenceL3 task-specific command intent confusion, plus human-only criteriaL4 human verified multi-reviewer adjudicationDecisionsblocked corrupt audio or missing/stale consent; not usableretry a contributor-fixable capture problem; contributor may retry or keepreview kept and sent to a human (noise, model uncertainty, human criteria)accepted passed automatic checks at the configured level"""from __future__ import annotationsimport hashlibimport timefrom dataclasses import dataclassfrom typing import Optionalfrom . import __version__from . import confidence as Cfrom . import prosody as Pfrom .asr import ASRBackend, ASRResult, NullASRfrom .audio import AudioDecodeError, analyze, load_audiofrom .checks import tasks as Tfrom .checks import universal as Ufrom .checks.base import ACTION_RANK, Finding, ValidatorResultfrom .manifest import Task, ValidationSpecfrom .rubrics import score as rubric_scorefrom .textnorm import DEFAULT_NORM, NormConfigfrom .thresholds import HUMAN_REQUIRED_TASKS, resolveLEVELS = ["L0", "L1", "L2", "L3", "L4"]@dataclassclass QCInput:task: Taskvalidation: ValidationSpecctx: U.RecordingContextintents: Optional[dict] = None # manifest intents, as plain dictskey: Optional[str] = None # stable id for spot-check sampling and FixedASR lookupspeaker_baseline: Optional[dict] = None # {"n", "level_db", "rate_cps"} from this speaker's earlier takesword_spans: Optional[list] = None # forced-alignment word timings, when availabledef _level_at_least(level: str, target: str) -> bool:return LEVELS.index(level) >= LEVELS.index(target)def _spot_check(key: str, rate: float) -> bool:if rate <= 0 or not key:return Falseh = int(hashlib.sha256(("spot:" + key).encode()).hexdigest()[:8], 16)return (h % 10_000) < int(rate * 10_000)def _enforce_model_safety(findings: list[Finding]) -> None:"""Model-based findings may only route to review (fairness safeguard)."""for f in findings:if f.model_based and ACTION_RANK[f.action] > ACTION_RANK["review"]:f.detail["demoted_from"] = f.actionf.action = "review"def run_qc(source: str | bytes, qi: QCInput, asr: ASRBackend | None = None,norm: NormConfig = DEFAULT_NORM) -> dict:t0 = time.perf_counter()asr = asr or NullASR()task, v = qi.task, qi.validationlevel = v.presetth = resolve(task.task_type, v.overrides, task.min_duration_s, task.max_duration_s)disabled = set(v.disable)results: list[ValidatorResult] = []meta = U.metadata(qi.ctx)results.append(meta)try:audio = load_audio(source)except AudioDecodeError as e:bad = ValidatorResult("integrity", "L0")bad.findings.append(Finding("decode_failed", "block", "integrity","The audio file could not be read. Please record again.", {"error": str(e)[:200]}))results.append(bad)return _finalise(results, task, v, level, th, qi, None, asr, norm, t0)stats = analyze(audio)results.append(U.integrity(audio, stats, th))if _level_at_least(level, "L1") and "acoustic" not in disabled:results.append(U.acoustic(stats, th))# Only call ASR when an enabled validator needs it and the audio is usable.hard_fail = any(f.action == "block" for r in results for f in r.findings)asr_result: Optional[ASRResult] = Nonewants_asr = _level_at_least(level, "L2") and not hard_fail and stats.speech_s > 0if wants_asr:try:asr_result = asr.transcribe(audio.samples, audio.sr, task.language, key=qi.key)except Exception as e: # a failing model must not fail the uploadresults.append(ValidatorResult("asr_error", "L2", data={"error": str(e)[:200]}, available=False))tt = task.task_typeif _level_at_least(level, "L2") and not hard_fail:if tt == "read_speech" and "read_speech_match" in disabled and task.prompt.intent:results.append(T.semantic_intent(task.prompt.intent, qi.intents or {}, asr_result, th, norm))elif tt == "read_speech" and "read_speech_match" not in disabled:results.append(T.read_speech(task.prompt.text, asr_result, th, norm))elif tt == "command" and "command_match" not in disabled:cmd_level = "L3" if (_level_at_least(level, "L3") and "command_intent" not in disabled) else "L2"results.extend(T.command(task.prompt.text, task.prompt.intent, qi.intents or {},asr_result, th, norm, cmd_level))if tt == "image_description":results.append(T.image_description(asr_result, task.prompt.suggested_text, norm))elif tt in ("prosody_pair", "emotion"):results.extend(T.human_only(tt, task.prompt.text if _level_at_least(level, "L2") else None,asr_result, th, norm))elif tt == "tts_prosody" and _level_at_least(level, "L2") and not hard_fail:lex = T.read_speech(task.prompt.text, asr_result, th, norm)lex.name = "tts_prosody_lexical"for f in lex.findings:f.validator = lex.nameresults.append(lex)# Prosody follows the punctuation (TTS) or the intended reading (prosody pairs).if tt in ("tts_prosody", "prosody_pair") and _level_at_least(level, "L2") and not hard_fail \and "prosody" not in disabled and stats.speech_s > 0:crit = "punctuation_prosody" if tt == "tts_prosody" else "prosodic_realization"results.append(P.check(task.prompt.text or "", audio.samples, audio.sr, th, qi.word_spans,task.prompt.emphasis, crit))if tt == "tts_prosody" and _level_at_least(level, "L2") and not hard_fail and "consistency" not in disabled:from .textnorm import normalizechars = len(normalize(task.prompt.text or "").replace(" ", ""))rate = chars / stats.speech_s if stats.speech_s > 0.3 else Nonecons = P.consistency(stats.speech_level_db, rate, qi.speaker_baseline, th)cons.data.update({"level_db": stats.speech_level_db, "rate_cps": round(rate, 3) if rate else None})results.append(cons)return _finalise(results, task, v, level, th, qi, stats, asr, norm, t0)def _finalise(results, task, v, level, th, qi, stats, asr, norm, t0) -> dict:findings = [f for r in results for f in r.findings]_enforce_model_safety(findings)crit: dict[str, Optional[float]] = {}for r in results:for k, s in r.scores.items():crit[k] = s# Criteria never computed at this level count as pending (not as zero).rubric = rubric_score(task.task_type, crit)reasons = sorted({f.code for f in findings if f.action != "info"})worst = max((ACTION_RANK[f.action] for f in findings), default=0)decision = {3: "blocked", 2: "retry", 1: "review", 0: "accepted"}[worst]route_notes: list[str] = []if decision == "accepted":if task.task_type in HUMAN_REQUIRED_TASKS:route_notes.append("human_required_task")elif v.human_review == "all":route_notes.append("review_all")elif level == "L4":route_notes.append("level_L4")elif rubric["auto_score"] is not None and rubric["auto_score"] < th["accept_score"]:route_notes.append("low_auto_score")elif _spot_check(qi.key or "", v.spot_check_rate):route_notes.append("spot_check")if route_notes:decision = "review"partial = {"findings": [f.as_dict() for f in findings], "validators": [r.as_dict() for r in results],"signal": stats.as_dict() if stats else None}conf = C.score(C.signals_from_report(partial, task.language, task.prompt.text))if decision == "accepted" and v.accept_confidence is not None and conf["score"] < v.accept_confidence:route_notes.append("below_confidence_threshold")decision = "review"required_reviewers = v.min_reviewers or (2 if level == "L4" else 1)contributor = [f.message for f in findings if f.contributor_visible]return {"decision": decision,"reasons": reasons,"route_notes": route_notes,"required_reviewers": required_reviewers if decision in ("review", "retry") else 0,"feedback": {"retry_suggested": decision == "retry" or any(f.code == "possible_mismatch" for f in findings),"messages": contributor,},"rubric": rubric,"confidence": conf,"findings": [f.as_dict() for f in findings],"validators": [r.as_dict() for r in results],"signal": stats.as_dict() if stats else None,"provenance": {"scqc_version": __version__,"level": level,"human_review": v.human_review,"thresholds": th,"thresholds_sha": hashlib.sha256(repr(sorted(th.items())).encode()).hexdigest()[:12],"disabled": sorted(v.disable),"asr": {"backend": asr.name, "model_id": asr.model_id},"text_norm": norm.as_dict(),"elapsed_ms": round(1000 * (time.perf_counter() - t0), 1),},}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212"""Run QC for one recording and turn validator findings into a decision.Levels (deck slide 14)L0 capture decode, save, consent/metadataL1 acoustic VAD, clipping, level, duration, truncation, noiseL2 intelligent ASR matching where the task has a referenceL3 task-specific command intent confusion, plus human-only criteriaL4 human verified multi-reviewer adjudicationDecisionsblocked corrupt audio or missing/stale consent; not usableretry a contributor-fixable capture problem; contributor may retry or keepreview kept and sent to a human (noise, model uncertainty, human criteria)accepted passed automatic checks at the configured level"""from __future__ import annotationsimport hashlibimport timefrom dataclasses import dataclassfrom typing import Optionalfrom . import __version__from . import confidence as Cfrom . import prosody as Pfrom .asr import ASRBackend, ASRResult, NullASRfrom .audio import AudioDecodeError, analyze, load_audio, trim_silencefrom .checks import tasks as Tfrom .checks import universal as Ufrom .checks.base import ACTION_RANK, Finding, ValidatorResultfrom .manifest import Task, ValidationSpecfrom .rubrics import score as rubric_scorefrom .textnorm import DEFAULT_NORM, NormConfigfrom .thresholds import HUMAN_REQUIRED_TASKS, resolveLEVELS = ["L0", "L1", "L2", "L3", "L4"]@dataclassclass QCInput:task: Taskvalidation: ValidationSpecctx: U.RecordingContextintents: Optional[dict] = None # manifest intents, as plain dictskey: Optional[str] = None # stable id for spot-check sampling and FixedASR lookupspeaker_baseline: Optional[dict] = None # {"n", "level_db", "rate_cps"} from this speaker's earlier takesword_spans: Optional[list] = None # forced-alignment word timings, when availabledef _level_at_least(level: str, target: str) -> bool:return LEVELS.index(level) >= LEVELS.index(target)def _spot_check(key: str, rate: float) -> bool:if rate <= 0 or not key:return Falseh = int(hashlib.sha256(("spot:" + key).encode()).hexdigest()[:8], 16)return (h % 10_000) < int(rate * 10_000)def _enforce_model_safety(findings: list[Finding]) -> None:"""Model-based findings may only route to review (fairness safeguard)."""for f in findings:if f.model_based and ACTION_RANK[f.action] > ACTION_RANK["review"]:f.detail["demoted_from"] = f.actionf.action = "review"def run_qc(source: str | bytes, qi: QCInput, asr: ASRBackend | None = None,norm: NormConfig = DEFAULT_NORM) -> dict:t0 = time.perf_counter()asr = asr or NullASR()task, v = qi.task, qi.validationlevel = v.presetth = resolve(task.task_type, v.overrides, task.min_duration_s, task.max_duration_s)disabled = set(v.disable)results: list[ValidatorResult] = []meta = U.metadata(qi.ctx)results.append(meta)try:audio = load_audio(source)except AudioDecodeError as e:bad = ValidatorResult("integrity", "L0")bad.findings.append(Finding("decode_failed", "block", "integrity","The audio file could not be read. Please record again.", {"error": str(e)[:200]}))results.append(bad)return _finalise(results, task, v, level, th, qi, None, asr, norm, t0)stats = analyze(audio)results.append(U.integrity(audio, stats, th))if _level_at_least(level, "L1") and "acoustic" not in disabled:results.append(U.acoustic(stats, th, prompt_text=task.prompt.text, language=task.language))# Skip ASR on block OR retry-level capture/duration/silence defects (0 ms ASR spend).hard_fail = any(f.action in ("block", "retry") for r in results for f in r.findings)asr_result: Optional[ASRResult] = Nonewants_asr = _level_at_least(level, "L2") and not hard_fail and stats.speech_s > 0if wants_asr:try:target_audio = trim_silence(audio, stats, pad_s=0.25) if (stats.leading_silence_s > 0.6 or stats.trailing_silence_s > 0.6) else audioasr_result = asr.transcribe(target_audio.samples, target_audio.sr, task.language, key=qi.key)except Exception as e: # a failing model must not fail the uploadresults.append(ValidatorResult("asr_error", "L2", data={"error": str(e)[:200]}, available=False))tt = task.task_typeif _level_at_least(level, "L2") and not hard_fail:if tt == "read_speech" and "read_speech_match" in disabled and task.prompt.intent:results.append(T.semantic_intent(task.prompt.intent, qi.intents or {}, asr_result, th, norm))elif tt == "read_speech" and "read_speech_match" not in disabled:results.append(T.read_speech(task.prompt.text, asr_result, th, norm))elif tt == "command" and "command_match" not in disabled:cmd_level = "L3" if (_level_at_least(level, "L3") and "command_intent" not in disabled) else "L2"results.extend(T.command(task.prompt.text, task.prompt.intent, qi.intents or {},asr_result, th, norm, cmd_level))if tt == "image_description":results.append(T.image_description(asr_result, task.prompt.suggested_text, norm))elif tt in ("prosody_pair", "emotion"):results.extend(T.human_only(tt, task.prompt.text if _level_at_least(level, "L2") else None,asr_result, th, norm))elif tt == "tts_prosody" and _level_at_least(level, "L2") and not hard_fail:lex = T.read_speech(task.prompt.text, asr_result, th, norm)lex.name = "tts_prosody_lexical"for f in lex.findings:f.validator = lex.nameresults.append(lex)# Prosody follows the punctuation (TTS) or the intended reading (prosody pairs).if tt in ("tts_prosody", "prosody_pair") and _level_at_least(level, "L2") and not hard_fail \and "prosody" not in disabled and stats.speech_s > 0:crit = "punctuation_prosody" if tt == "tts_prosody" else "prosodic_realization"results.append(P.check(task.prompt.text or "", audio.samples, audio.sr, th, qi.word_spans,task.prompt.emphasis, crit))if tt == "tts_prosody" and _level_at_least(level, "L2") and not hard_fail and "consistency" not in disabled:from .textnorm import normalizechars = len(normalize(task.prompt.text or "").replace(" ", ""))rate = chars / stats.speech_s if stats.speech_s > 0.3 else Nonecons = P.consistency(stats.speech_level_db, rate, qi.speaker_baseline, th)cons.data.update({"level_db": stats.speech_level_db, "rate_cps": round(rate, 3) if rate else None})results.append(cons)return _finalise(results, task, v, level, th, qi, stats, asr, norm, t0)def _finalise(results, task, v, level, th, qi, stats, asr, norm, t0) -> dict:findings = [f for r in results for f in r.findings]_enforce_model_safety(findings)crit: dict[str, Optional[float]] = {}for r in results:for k, s in r.scores.items():crit[k] = s# Criteria never computed at this level count as pending (not as zero).rubric = rubric_score(task.task_type, crit)reasons = sorted({f.code for f in findings if f.action != "info"})worst = max((ACTION_RANK[f.action] for f in findings), default=0)decision = {3: "blocked", 2: "retry", 1: "review", 0: "accepted"}[worst]route_notes: list[str] = []if decision == "accepted":if task.task_type in HUMAN_REQUIRED_TASKS:route_notes.append("human_required_task")elif v.human_review == "all":route_notes.append("review_all")elif level == "L4":route_notes.append("level_L4")elif rubric["auto_score"] is not None and rubric["auto_score"] < th["accept_score"]:route_notes.append("low_auto_score")elif _spot_check(qi.key or "", v.spot_check_rate):route_notes.append("spot_check")if route_notes:decision = "review"partial = {"findings": [f.as_dict() for f in findings], "validators": [r.as_dict() for r in results],"signal": stats.as_dict() if stats else None}conf = C.score(C.signals_from_report(partial, task.language, task.prompt.text))if decision == "accepted" and v.accept_confidence is not None and conf["score"] < v.accept_confidence:route_notes.append("below_confidence_threshold")decision = "review"required_reviewers = v.min_reviewers or (2 if level == "L4" else 1)contributor = [f.message for f in findings if f.contributor_visible]return {"decision": decision,"reasons": reasons,"route_notes": route_notes,"required_reviewers": required_reviewers if decision in ("review", "retry") else 0,"feedback": {"retry_suggested": decision == "retry" or any(f.code == "possible_mismatch" for f in findings),"messages": contributor,},"rubric": rubric,"confidence": conf,"findings": [f.as_dict() for f in findings],"validators": [r.as_dict() for r in results],"signal": stats.as_dict() if stats else None,"provenance": {"scqc_version": __version__,"level": level,"human_review": v.human_review,"thresholds": th,"thresholds_sha": hashlib.sha256(repr(sorted(th.items())).encode()).hexdigest()[:12],"disabled": sorted(v.disable),"asr": {"backend": asr.name, "model_id": asr.model_id},"text_norm": norm.as_dict(),"elapsed_ms": round(1000 * (time.perf_counter() - t0), 1),},}
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394"""Text normalisation for comparing prompts with ASR hypotheses.The goal is to remove differences that say nothing about whether the speakerread the prompt (punctuation, Unicode composition, digit scripts, optionalnukta) while keeping differences that do. Every folding step is configurableand recorded in QC provenance, because over-aggressive folding hides realerrors and under-folding inflates mismatch rates for some scripts."""from __future__ import annotationsimport reimport unicodedatafrom dataclasses import asdict, dataclass# Devanagari, Bengali, Gurmukhi, Gujarati, Oriya, Tamil, Telugu, Kannada,# Malayalam digit blocks -> ASCII digits._DIGIT_BLOCK_STARTS = [0x0966, 0x09E6, 0x0A66, 0x0AE6, 0x0B66, 0x0BE6, 0x0C66, 0x0CE6, 0x0D66]_DIGIT_MAP = {start + i: str(i) for start in _DIGIT_BLOCK_STARTS for i in range(10)}# Nukta signs per script (Devanagari, Bengali, Gurmukhi, Gujarati, Oriya, Kannada)._NUKTAS = "\u093C\u09BC\u0A3C\u0ABC\u0B3C\u0CBC"# Precomposed Devanagari nukta letters (U+0958–U+095F) decompose under NFD,# so folding nukta = NFD, drop nukta, NFC._PUNCT_RE = re.compile(r"[\u0964\u0965\.,;:!?\"'“”‘’()\[\]{}\-–—/\\|…«»<>@#%&*_+=~`^]")_SPACE_RE = re.compile(r"\s+")_ZW_RE = re.compile(r"[\u200B\u200C\u200D\uFEFF]")@dataclass(frozen=True)class NormConfig:fold_nukta: bool = Truefold_anusvara_chandrabindu: bool = False # ँ -> ं ; lossy, off by defaultmap_digits: bool = Truelowercase_latin: bool = Truestrip_zero_width: bool = Truedef as_dict(self) -> dict:return asdict(self)DEFAULT_NORM = NormConfig()def normalize(text: str, cfg: NormConfig = DEFAULT_NORM) -> str:if not text:return ""t = unicodedata.normalize("NFC", text)if cfg.strip_zero_width:t = _ZW_RE.sub("", t)if cfg.fold_nukta:t = unicodedata.normalize("NFD", t)t = "".join(ch for ch in t if ch not in _NUKTAS)t = unicodedata.normalize("NFC", t)if cfg.fold_anusvara_chandrabindu:t = t.replace("\u0901", "\u0902")if cfg.map_digits:t = t.translate(_DIGIT_MAP)if cfg.lowercase_latin:t = t.lower()t = _PUNCT_RE.sub(" ", t)return _SPACE_RE.sub(" ", t).strip()def tokenize(text: str, cfg: NormConfig = DEFAULT_NORM) -> list[str]:n = normalize(text, cfg)return n.split(" ") if n else []_INDIC_PHONETIC = str.maketrans({# Hindi / Devanagari accent & orthographic variants"\u0901": "\u0902", # ँ -> ं (chandrabindu / anusvara)"\u0936": "\u0938", # श -> स"\u0937": "\u0938", # ष -> स"\u0935": "\u092C", # व -> ब (regional Hindi shift)"\u0921": "\u0930", # ड (from ड़ after nukta fold) -> र (खिड़की ~ खिरकी)"\u0922": "\u0930", # ढ (from ढ़) -> र"\u0940": "\u093F", # ी -> ि (vowel length tolerance)"\u0942": "\u0941", # ू -> ु# Bengali accent & orthographic variants"\u09B6": "\u09B8", # শ -> স (all pronounced /ʃ/)"\u09B7": "\u09B8", # ষ -> স"\u09A3": "\u09A8", # ণ -> ন"\u09A1": "\u09B0", # ড (from ড় after nukta fold) -> র"\u09A2": "\u09B0", # ঢ (from ঢ়) -> র"\u09C0": "\u09BF", # ী -> ি"\u09C2": "\u09C1", # ূ -> ু})def phonetic_key(token: str) -> str:"""Fold accent-sensitive Indic consonant/vowel variants for fuzzy matching."""t = normalize(token, NormConfig(fold_nukta=True, fold_anusvara_chandrabindu=True))return t.translate(_INDIC_PHONETIC)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144"""Text normalisation for comparing prompts with ASR hypotheses.The goal is to remove differences that say nothing about whether the speakerread the prompt (punctuation, Unicode composition, digit scripts, optionalnukta) while keeping differences that do. Every folding step is configurableand recorded in QC provenance, because over-aggressive folding hides realerrors and under-folding inflates mismatch rates for some scripts."""from __future__ import annotationsimport reimport unicodedatafrom dataclasses import asdict, dataclass# Devanagari, Bengali, Gurmukhi, Gujarati, Oriya, Tamil, Telugu, Kannada,# Malayalam digit blocks -> ASCII digits._DIGIT_BLOCK_STARTS = [0x0966, 0x09E6, 0x0A66, 0x0AE6, 0x0B66, 0x0BE6, 0x0C66, 0x0CE6, 0x0D66]_DIGIT_MAP = {start + i: str(i) for start in _DIGIT_BLOCK_STARTS for i in range(10)}# Nukta signs per script (Devanagari, Bengali, Gurmukhi, Gujarati, Oriya, Kannada)._NUKTAS = "\u093C\u09BC\u0A3C\u0ABC\u0B3C\u0CBC"# Precomposed Devanagari nukta letters (U+0958–U+095F) decompose under NFD,# so folding nukta = NFD, drop nukta, NFC._PUNCT_RE = re.compile(r"[\u0964\u0965\.,;:!?\"'“”‘’()\[\]{}\-–—/\\|…«»<>@#%&*_+=~`^]")_SPACE_RE = re.compile(r"\s+")_ZW_RE = re.compile(r"[\u200B\u200C\u200D\uFEFF]")@dataclass(frozen=True)class NormConfig:fold_nukta: bool = Truefold_anusvara_chandrabindu: bool = False # ँ -> ं ; lossy, off by defaultmap_digits: bool = Truelowercase_latin: bool = Truestrip_zero_width: bool = Truedef as_dict(self) -> dict:return asdict(self)DEFAULT_NORM = NormConfig()_EN_NUM_WORDS = {"zero": "0", "one": "1", "two": "2", "three": "3", "four": "4","five": "5", "six": "6", "seven": "7", "eight": "8", "nine": "9","ten": "10", "eleven": "11", "twelve": "12", "thirteen": "13","fourteen": "14", "fifteen": "15", "sixteen": "16", "seventeen": "17","eighteen": "18", "nineteen": "19", "twenty": "20", "thirty": "30","forty": "40", "fifty": "50", "sixty": "60", "seventy": "70","eighty": "80", "ninety": "90", "hundred": "100", "thousand": "1000",}_EN_NUM_RE = re.compile(r"\b(" + "|".join(_EN_NUM_WORDS.keys()) + r")\b")def normalize(text: str, cfg: NormConfig = DEFAULT_NORM) -> str:if not text:return ""t = unicodedata.normalize("NFC", text)if cfg.strip_zero_width:t = _ZW_RE.sub("", t)if cfg.fold_nukta:t = unicodedata.normalize("NFD", t)t = "".join(ch for ch in t if ch not in _NUKTAS)t = unicodedata.normalize("NFC", t)if cfg.fold_anusvara_chandrabindu:t = t.replace("\u0901", "\u0902")if cfg.map_digits:t = t.translate(_DIGIT_MAP)if cfg.lowercase_latin:t = t.lower()t = _PUNCT_RE.sub(" ", t)if cfg.map_digits:t = _EN_NUM_RE.sub(lambda m: _EN_NUM_WORDS[m.group(0)], t)return _SPACE_RE.sub(" ", t).strip()def tokenize(text: str, cfg: NormConfig = DEFAULT_NORM) -> list[str]:n = normalize(text, cfg)return n.split(" ") if n else []_INDIC_PHONETIC = str.maketrans({# Hindi / Devanagari accent & orthographic variants"\u0901": "\u0902", # ँ -> ं (chandrabindu / anusvara)"\u0936": "\u0938", # श -> स"\u0937": "\u0938", # ष -> स"\u0935": "\u092C", # व -> ब (regional Hindi shift)"\u0921": "\u0930", # ड (from ड़ after nukta fold) -> र (खिड़की ~ खिरकी)"\u0922": "\u0930", # ढ (from ढ़) -> र"\u0940": "\u093F", # ी -> ि (vowel length tolerance)"\u0942": "\u0941", # ू -> ु# Bengali accent & orthographic variants"\u09B6": "\u09B8", # শ -> স (all pronounced /ʃ/)"\u09B7": "\u09B8", # ষ -> স"\u09A3": "\u09A8", # ণ -> ন"\u09A1": "\u09B0", # ড (from ড় after nukta fold) -> র"\u09A2": "\u09B0", # ঢ (from ঢ়) -> র"\u09C0": "\u09BF", # ী -> ি"\u09C2": "\u09C1", # ূ -> ু# Devanagari de-aspiration & halant tolerance for lightweight ASR"\u0916": "\u0915", # ख -> क"\u0918": "\u0917", # घ -> ग"\u091B": "\u091A", # छ -> च"\u091D": "\u091C", # झ -> ज"\u0920": "\u091F", # ठ -> ट"\u0925": "\u0924", # थ -> त"\u0927": "\u0926", # ध -> द"\u092B": "\u092A", # फ -> प"\u092D": "\u092C", # भ -> ब"\u094D": None, # strip halant/virama (ख्रिकि ~ खिड़की)})def phonetic_key(token: str) -> str:"""Fold accent-sensitive Indic consonant/vowel variants for fuzzy matching."""t = normalize(token, NormConfig(fold_nukta=True, fold_anusvara_chandrabindu=True))return t.translate(_INDIC_PHONETIC)_INDIC_ASR_MAP = str.maketrans({# Fold sibilants, semivowels, and stop voicing/aspiration for lightweight CPU ASR"\u0901": "\u0902","\u0936": "\u0938", "\u0937": "\u0938", # श, ष -> स"\u0935": "\u092C", # व -> ब"\u0916": "\u0915", "\u0917": "\u0915", "\u0918": "\u0915", # ख, ग, घ -> क"\u091B": "\u091A", "\u091D": "\u091C", # छ -> च, झ -> ज"\u091F": "\u0924", "\u0920": "\u0924", "\u0921": "\u0930", "\u0922": "\u0930", # ट, ठ -> त; ड़, ढ़ -> र"\u0925": "\u0924", "\u0926": "\u0924", "\u0927": "\u0924", # थ, द, ध -> त"\u092B": "\u092A", "\u092D": "\u092C", # फ -> प, भ -> ब})_DEV_MATRAS_AND_HALANT = re.compile(r"[\u0902\u0903\u093A-\u094F\u0951-\u0957\u0962\u0963]")def indic_asr_key(token: str) -> str:"""Consonant-frame key tolerant of lightweight ASR matra/voicing/split quirks."""t = normalize(token, NormConfig(fold_nukta=True, fold_anusvara_chandrabindu=True))t = re.sub(r"^आद$", "आज", t)t = _DEV_MATRAS_AND_HALANT.sub("", t).translate(_INDIC_ASR_MAP)if len(t) >= 3 and t[-1] in ("ह", "ब", "इ", "ई", "आ", "त") and any("\u0900" <= c <= "\u097F" for c in t):t = t[:-1]return t
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576"""Validation thresholds. Every value can be overridden per task in themanifest (`validation.overrides`). Freeze these before held-out evaluation."""from __future__ import annotationsDEFAULT_THRESHOLDS: dict = {"min_source_sr": 16000,"min_duration_s": 0.8,"max_duration_s": 30.0,"max_clip_ratio": 0.001, # fraction of samples at full scale"max_clip_run_ms": 2.0, # longest run of consecutive clipped samples"min_speech_s": 0.4,"target_speech_s": 2.0, # for the speech-activity criterion"min_speech_level_db": -45.0, # mean energy of speech frames, dBFS"min_snr_db": 12.0, # below -> review (never retry)"max_leading_silence_s": 3.0,"max_trailing_silence_s": 3.0,"max_internal_pause_s": 2.5,"truncation_check": True,"cer_accept": 0.10, # read speech: char error rate vs prompt"min_asr_confidence": 0.45,"command_cer_accept": 0.15,"accept_score": 70.0, # automatic rubric score (0–100) needed to auto-accept# prosody (heuristics; route to review only)"min_pause_s": 0.10,"pause_position_tolerance": 0.15, # fraction of the speech span"question_min_slope": 3.0, # semitones per second over the final stretch"question_min_rise_st": 1.5,"statement_max_slope": 2.0,"statement_max_rise_st": 1.5,"exclaim_min_range_st": 7.0,"max_level_drift_db": 6.0, # vs the same speaker's earlier recordings"max_rate_ratio": 1.35,}TASK_DEFAULTS: dict[str, dict] = {"read_speech": {},"command": {"max_duration_s": 8.0, "min_duration_s": 0.5, "target_speech_s": 0.8},"image_description": {"min_speech_s": 2.0, "target_speech_s": 6.0, "max_duration_s": 90.0,"max_internal_pause_s": 4.0},"prosody_pair": {"max_internal_pause_s": 3.0},"emotion": {"max_duration_s": 45.0},# TTS data needs cleaner audio than ASR data."tts_prosody": {"min_source_sr": 22050, "min_snr_db": 25.0, "max_clip_ratio": 0.0001,"max_leading_silence_s": 1.5, "max_trailing_silence_s": 2.0, "max_internal_pause_s": 1.5,"min_speech_level_db": -35.0},}# Task types whose rubric has criteria only humans can score.HUMAN_REQUIRED_TASKS = {"image_description", "prosody_pair", "emotion"}# Validators that can never be disabled (integrity and consent).MANDATORY_VALIDATORS = {"integrity", "metadata"}KNOWN_VALIDATORS = {"integrity", "metadata", "acoustic", "read_speech_match", "command_match", "command_intent","image_relevance", "prosody_pair_perceptual", "prosody_pair_lexical", "emotion_perceptual","emotion_lexical", "prosody", "consistency", "tts_prosody_lexical", "mfa_alignment",}def resolve(task_type: str, overrides: dict | None = None, min_duration_s=None, max_duration_s=None) -> dict:th = dict(DEFAULT_THRESHOLDS)th.update(TASK_DEFAULTS.get(task_type, {}))if min_duration_s is not None:th["min_duration_s"] = min_duration_sif max_duration_s is not None:th["max_duration_s"] = max_duration_sfor k, v in (overrides or {}).items():if k not in DEFAULT_THRESHOLDS:raise ValueError(f"unknown threshold override '{k}'")default = DEFAULT_THRESHOLDS[k]numeric_ok = isinstance(default, float) and isinstance(v, (int, float)) and not isinstance(v, bool)if not numeric_ok and type(v) is not type(default):raise ValueError(f"override '{k}' should be {type(default).__name__}")th[k] = float(v) if isinstance(DEFAULT_THRESHOLDS[k], float) else vreturn th12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576"""Validation thresholds. Every value can be overridden per task in themanifest (`validation.overrides`). Freeze these before held-out evaluation."""from __future__ import annotationsDEFAULT_THRESHOLDS: dict = {"min_source_sr": 16000,"min_duration_s": 0.8,"max_duration_s": 30.0,"max_clip_ratio": 0.001, # fraction of samples at full scale"max_clip_run_ms": 2.0, # longest run of consecutive clipped samples"min_speech_s": 0.4,"target_speech_s": 2.0, # for the speech-activity criterion"min_speech_level_db": -45.0, # mean energy of speech frames, dBFS"min_snr_db": 12.0, # below -> review (never retry)"max_leading_silence_s": 3.0,"max_trailing_silence_s": 3.0,"max_internal_pause_s": 2.5,"truncation_check": True,"cer_accept": 0.10, # read speech: char error rate vs prompt"min_asr_confidence": 0.45,"command_cer_accept": 0.15,"accept_score": 70.0, # automatic rubric score (0–100) needed to auto-accept# prosody (heuristics; route to review only)"min_pause_s": 0.10,"pause_position_tolerance": 0.15, # fraction of the speech span"question_min_slope": 3.0, # semitones per second over the final stretch"question_min_rise_st": 1.5,"statement_max_slope": 2.0,"statement_max_rise_st": 1.5,"exclaim_min_range_st": 7.0,"max_level_drift_db": 6.0, # vs the same speaker's earlier recordings"max_rate_ratio": 1.35,}TASK_DEFAULTS: dict[str, dict] = {"read_speech": {"max_internal_pause_s": 1.1},"command": {"max_duration_s": 8.0, "min_duration_s": 0.5, "target_speech_s": 0.8},"image_description": {"min_speech_s": 2.0, "target_speech_s": 6.0, "max_duration_s": 90.0,"max_internal_pause_s": 4.0},"prosody_pair": {"max_internal_pause_s": 3.0},"emotion": {"max_duration_s": 45.0},# TTS data needs cleaner audio than ASR data."tts_prosody": {"min_source_sr": 22050, "min_snr_db": 25.0, "max_clip_ratio": 0.0001,"max_leading_silence_s": 1.5, "max_trailing_silence_s": 2.0, "max_internal_pause_s": 1.5,"min_speech_level_db": -35.0},}# Task types whose rubric has criteria only humans can score.HUMAN_REQUIRED_TASKS = {"image_description", "prosody_pair", "emotion"}# Validators that can never be disabled (integrity and consent).MANDATORY_VALIDATORS = {"integrity", "metadata"}KNOWN_VALIDATORS = {"integrity", "metadata", "acoustic", "read_speech_match", "command_match", "command_intent","image_relevance", "prosody_pair_perceptual", "prosody_pair_lexical", "emotion_perceptual","emotion_lexical", "prosody", "consistency", "tts_prosody_lexical", "mfa_alignment",}def resolve(task_type: str, overrides: dict | None = None, min_duration_s=None, max_duration_s=None) -> dict:th = dict(DEFAULT_THRESHOLDS)th.update(TASK_DEFAULTS.get(task_type, {}))if min_duration_s is not None:th["min_duration_s"] = min_duration_sif max_duration_s is not None:th["max_duration_s"] = max_duration_sfor k, v in (overrides or {}).items():if k not in DEFAULT_THRESHOLDS:raise ValueError(f"unknown threshold override '{k}'")default = DEFAULT_THRESHOLDS[k]numeric_ok = isinstance(default, float) and isinstance(v, (int, float)) and not isinstance(v, bool)if not numeric_ok and type(v) is not type(default):raise ValueError(f"override '{k}' should be {type(default).__name__}")th[k] = float(v) if isinstance(DEFAULT_THRESHOLDS[k], float) else vreturn th
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192"""Admin and reviewer accounts.Roles: "admin" (projects, ethics, payments, users, and reviewing) and"reviewer" (review queue only). Passwords are stored as PBKDF2-SHA256 hashes.Sessions are random bearer tokens sent in the X-SCQC-Token header.The first admin is created either from SCQC_ADMIN_PASSWORD (user name fromSCQC_ADMIN_USER, default "admin") at start-up, or through the setup screen,which requires the deployment's SCQC_ADMIN_TOKEN so a stranger who finds anempty server cannot claim it. The shared tokens keep working for scripts."""from __future__ import annotationsimport hashlibimport hmacimport osimport secretsimport timefrom typing import OptionalSCHEMA = """CREATE TABLE IF NOT EXISTS users (username TEXT PRIMARY KEY, display_name TEXT, role TEXT NOT NULL CHECK (role IN ('admin','reviewer','participant')),pw_hash TEXT NOT NULL, salt TEXT NOT NULL, created_at REAL NOT NULL, disabled INTEGER NOT NULL DEFAULT 0);CREATE TABLE IF NOT EXISTS sessions (token TEXT PRIMARY KEY, username TEXT NOT NULL, created_at REAL NOT NULL, expires_at REAL NOT NULL);"""SESSION_DAYS = 7ITERATIONS = 200_000_failures: dict[str, list[float]] = {}def hash_password(password: str, salt: Optional[str] = None) -> tuple[str, str]:salt = salt or secrets.token_hex(16)h = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), bytes.fromhex(salt), ITERATIONS).hex()return h, saltdef init(db) -> None:db._conn.executescript(SCHEMA)pw = os.environ.get("SCQC_ADMIN_PASSWORD")if pw and not db.one("SELECT 1 FROM users LIMIT 1"):create_user(db, os.environ.get("SCQC_ADMIN_USER", "admin"), pw, "admin", "Administrator")def has_users(db) -> bool:return db.one("SELECT 1 FROM users LIMIT 1") is not Nonedef create_user(db, username: str, password: str, role: str, display_name: Optional[str] = None) -> dict:if len(password) < 10:raise ValueError("passwords need at least 10 characters")if not username or not username.replace("_", "").replace(".", "").replace("-", "").isalnum() or len(username) > 40:raise ValueError("user names use letters, digits, '.', '_' or '-' (max 40)")h, salt = hash_password(password)with db.tx() as c:c.execute("INSERT INTO users(username, display_name, role, pw_hash, salt, created_at) VALUES (?,?,?,?,?,?)",(username, display_name or username, role, h, salt, time.time()))db.log(c, "system", "user.created", username, {"role": role})return {"username": username, "role": role, "display_name": display_name or username}def login(db, username: str, password: str) -> Optional[dict]:now = time.time()recent = [t for t in _failures.get(username, []) if now - t < 300]_failures[username] = recentif len(recent) >= 10:raise PermissionError("too many failed attempts; try again in a few minutes")u = db.one("SELECT * FROM users WHERE username=? AND disabled=0", (username,))if not u or not hmac.compare_digest(hash_password(password, u["salt"])[0], u["pw_hash"]):_failures[username].append(now)return Nonetoken = secrets.token_urlsafe(32)with db.tx() as c:c.execute("INSERT INTO sessions(token, username, created_at, expires_at) VALUES (?,?,?,?)",(token, username, now, now + SESSION_DAYS * 86400))c.execute("DELETE FROM sessions WHERE expires_at < ?", (now,))db.log(c, username, "user.login", username, {})return {"token": token, "username": username, "role": u["role"], "display_name": u["display_name"]}def session_user(db, token: Optional[str]) -> Optional[dict]:if not token:return Noner = db.one("SELECT u.username, u.role, u.display_name FROM sessions s JOIN users u USING (username)"" WHERE s.token=? AND s.expires_at>? AND u.disabled=0", (token, time.time()))return dict(r) if r else Nonedef logout(db, token: str) -> None:with db.tx() as c:c.execute("DELETE FROM sessions WHERE token=?", (token,))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127"""Admin and reviewer accounts.Roles: "admin" (projects, ethics, payments, users, and reviewing) and"reviewer" (review queue only). Passwords are stored as PBKDF2-SHA256 hashes.Sessions are random bearer tokens sent in the X-SCQC-Token header.The first admin is created either from SCQC_ADMIN_PASSWORD (user name fromSCQC_ADMIN_USER, default "admin") at start-up, or through the setup screen,which requires the deployment's SCQC_ADMIN_TOKEN so a stranger who finds anempty server cannot claim it. The shared tokens keep working for scripts."""from __future__ import annotationsimport hashlibimport hmacimport osimport secretsimport timefrom typing import OptionalSCHEMA = """CREATE TABLE IF NOT EXISTS users (username TEXT PRIMARY KEY, display_name TEXT, role TEXT NOT NULL CHECK (role IN ('admin','reviewer','participant')),pw_hash TEXT NOT NULL, salt TEXT NOT NULL, created_at REAL NOT NULL, disabled INTEGER NOT NULL DEFAULT 0);CREATE TABLE IF NOT EXISTS sessions (token TEXT PRIMARY KEY, username TEXT NOT NULL, created_at REAL NOT NULL, expires_at REAL NOT NULL);"""SESSION_DAYS = 7ITERATIONS = 200_000_failures: dict[str, list[float]] = {}def hash_password(password: str, salt: Optional[str] = None) -> tuple[str, str]:salt = salt or secrets.token_hex(16)h = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), bytes.fromhex(salt), ITERATIONS).hex()return h, saltdef _seed_entries() -> list[tuple[str, str, str, Optional[str]]]:import jsonraw = (os.environ.get("SCQC_SEED_USERS") or "").strip()if not raw:return []if raw.startswith("["):items = json.loads(raw)return [(x["username"], x["password"], x.get("role", "participant"), x.get("display_name"))for x in items]out = []for chunk in raw.replace(";", ",").split(","):chunk = chunk.strip()if not chunk:continueparts = [p.strip() for p in chunk.split(":")]if len(parts) < 2:continueuname, upass = parts[0], parts[1]role = parts[2] if len(parts) >= 3 and parts[2] else "participant"dname = parts[3] if len(parts) >= 4 and parts[3] else Noneout.append((uname, upass, role, dname))return outdef init(db) -> None:db._conn.executescript(SCHEMA)pw = os.environ.get("SCQC_ADMIN_PASSWORD")if pw and not db.one("SELECT 1 FROM users LIMIT 1"):create_user(db, os.environ.get("SCQC_ADMIN_USER", "admin"), pw, "admin", "Administrator")for uname, upass, role, dname in _seed_entries():if not db.one("SELECT 1 FROM users WHERE username=?", (uname,)):create_user(db, uname, upass, role, dname)# Keep default test_speaker available across ephemeral container restarts when deployedif pw and os.environ.get("SCQC_DISABLE_DEFAULT_TEST_SPEAKER") != "1":if not db.one("SELECT 1 FROM users WHERE username=?", ("test_speaker",)):test_pw = os.environ.get("SCQC_TEST_SPEAKER_PASSWORD") or (pw if len(pw) >= 10 else "TestSpeaker@123")create_user(db, "test_speaker", test_pw, "participant", "Test Speaker")def has_users(db) -> bool:return db.one("SELECT 1 FROM users LIMIT 1") is not Nonedef create_user(db, username: str, password: str, role: str, display_name: Optional[str] = None) -> dict:if len(password) < 10:raise ValueError("passwords need at least 10 characters")if not username or not username.replace("_", "").replace(".", "").replace("-", "").isalnum() or len(username) > 40:raise ValueError("user names use letters, digits, '.', '_' or '-' (max 40)")h, salt = hash_password(password)with db.tx() as c:c.execute("INSERT INTO users(username, display_name, role, pw_hash, salt, created_at) VALUES (?,?,?,?,?,?)",(username, display_name or username, role, h, salt, time.time()))db.log(c, "system", "user.created", username, {"role": role})return {"username": username, "role": role, "display_name": display_name or username}def login(db, username: str, password: str) -> Optional[dict]:now = time.time()recent = [t for t in _failures.get(username, []) if now - t < 300]_failures[username] = recentif len(recent) >= 10:raise PermissionError("too many failed attempts; try again in a few minutes")u = db.one("SELECT * FROM users WHERE username=? AND disabled=0", (username,))if not u or not hmac.compare_digest(hash_password(password, u["salt"])[0], u["pw_hash"]):_failures[username].append(now)return Nonetoken = secrets.token_urlsafe(32)with db.tx() as c:c.execute("INSERT INTO sessions(token, username, created_at, expires_at) VALUES (?,?,?,?)",(token, username, now, now + SESSION_DAYS * 86400))c.execute("DELETE FROM sessions WHERE expires_at < ?", (now,))db.log(c, username, "user.login", username, {})return {"token": token, "username": username, "role": u["role"], "display_name": u["display_name"]}def session_user(db, token: Optional[str]) -> Optional[dict]:if not token:return Noner = db.one("SELECT u.username, u.role, u.display_name FROM sessions s JOIN users u USING (username)"" WHERE s.token=? AND s.expires_at>? AND u.disabled=0", (token, time.time()))return dict(r) if r else Nonedef logout(db, token: str) -> None:with db.tx() as c:c.execute("DELETE FROM sessions WHERE token=?", (token,))
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546import { $, el, api, ApiError, toast, store, queue, syncQueue, uuid, fmtTime, LANG_NAMES } from "/static/common.js";import { Recorder, encodeWav, localChecks } from "/static/recorder.js";const MAX_SECONDS = 90;const KIND = {read_speech: "Read this aloud",command: "Say this command",image_description: "Describe the picture in your own words",prosody_pair: "Read this so that the meaning below is clear",emotion: "Respond to this situation as you naturally would",tts_prosody: "Read this clearly, following the punctuation",};const S = {project: null, // participant-safe project viewspeaker: null, // {speaker_id, condition, language}tasks: [], // prefetched tasks, cached for offline usecurrent: null, // current taskrec: null,timer: null,shownAt: 0,last: null, // last upload result for the current task};const views = ["projects", "consent", "task", "done", "survey", "history", "wallet", "profile"];const TABBED = { task: "task", done: "task", survey: "task", history: "history", wallet: "wallet", profile: "profile" };function show(name) {for (const v of views) $(`#view-${v}`).classList.toggle("hidden", v !== name);const tab = TABBED[name];$("#tabs").classList.toggle("hidden", !tab);document.querySelectorAll("#tabs button").forEach((b) => b.setAttribute("aria-current", b.dataset.tab === tab ? "page" : "false"));}function openTab(tab) {if (tab === "task") return nextTask();if (tab === "history") return openHistory();if (tab === "wallet") return openWallet();if (tab === "profile") return openProfile();}// ------------------------------------------------------------------ bootasync function boot() {const token = store.get("admin.session");if (!token) { location.replace("/"); return; }try {const me = await api("/api/auth/me", { token });if (me.role !== "participant") { location.replace(me.role === "reviewer" ? "/review" : "/admin"); return; }$("#participant-account").textContent = me.display_name || me.username;} catch { store.del("admin.session"); location.replace("/"); return; }$("#participant-logout").onclick = async () => {await api("/api/auth/logout", { method: "POST", token }).catch(() => {});store.del("admin.session"); location.replace("/");};if ("serviceWorker" in navigator) navigator.serviceWorker.register("/sw.js").catch(() => {});window.addEventListener("online", () => sync());document.querySelectorAll("#tabs button").forEach((b) => (b.onclick = () => openTab(b.dataset.tab)));$("#withdraw").onclick = withdraw;$("#switch-project").onclick = () => { store.del("last_project"); pickProject(true); };$("#rec-btn").onclick = toggleRecording;$("#consent-form").onsubmit = submitConsent;await refreshQueueState();const wanted = new URLSearchParams(location.search).get("project") || store.get("last_project");if (wanted) await openProject(wanted);else await pickProject();sync();}async function pickProject(force = false) {let list;try { list = await api("/api/projects"); store.set("projects", list); }catch { list = store.get("projects", []); }if (list.length === 1 && !force) return openProject(list[0].project_id);const box = $("#project-list");box.replaceChildren();if (!list.length) box.append(el("p", { class: "muted", text: "No projects are open yet. Ask your coordinator for a project link." }));for (const p of list) {box.append(el("button", { class: "panel", style: "width:100%;text-align:left;display:block",onclick: () => openProject(p.project_id) },el("strong", { text: p.title || p.project_id }), el("br"),el("span", { class: "muted small", text: p.languages.map((l) => LANG_NAMES[l] || l).join(", ") })));}show("projects");}async function openProject(pid) {try {S.project = await api(`/api/projects/${encodeURIComponent(pid)}`);store.set(`project.${pid}`, S.project);} catch (e) {S.project = store.get(`project.${pid}`);if (!S.project) { toast(e.status === 404 ? "That project doesn't exist." : "You're offline and this project isn't saved on this phone yet."); return pickProject(true); }}store.set("last_project", pid);$("#project-title").textContent = S.project.title || S.project.project_id;S.speaker = store.get(`speaker.${pid}`);if (!S.speaker || S.speaker.consent_version !== S.project.consent_version) return showConsent();await loadTasks();nextTask();}// ------------------------------------------------------------------ consentfunction showConsent() {const P = S.project, E = P.ethics || {};const sel = $("#f-language");sel.replaceChildren(...P.languages.map((l) => el("option", { value: l, text: LANG_NAMES[l] || l })));sel.onchange = renderConsentText;$("#test-banner").classList.toggle("hidden", E.status !== "internal_test");const closed = P.open === false;$("#consent-closed").classList.toggle("hidden", !closed);$("#consent-closed").replaceChildren(el("p", { text: P.closed_reason || "This project is closed." }));$("#consent-form").classList.toggle("hidden", closed);$("#f-adult-label").textContent = `I am ${E.minimum_age ?? 18} or older`;$("#f-adult").required = (E.minimum_age ?? 18) > 0;let line = "";if (E.status === "approved") {line = `Approved by ${E.committee}${E.institution ? `, ${E.institution}` : ""}. Reference ${E.protocol_id}` +`${E.amendment_id ? ` (amendment ${E.amendment_id})` : ""}, valid until ${E.expiry_date}.`;if (E.retention_days) line += ` Recordings are deleted after ${E.retention_days} days.`;if (E.data_hosting) line += ` Stored on: ${E.data_hosting}.`;} else if (E.status === "pending") {line = `Waiting for approval from ${E.committee}.`;} else if (E.status === "not_required") {line = `This project has not been reviewed by an ethics committee. The project owner's reason: ${E.not_required_reason}`;}$("#ethics-line").textContent = line;const c = E.contact || {};$("#contact-line").textContent = [c.researcher && `Questions: ${c.researcher}.`,c.committee && `Concerns about how the study is run: ${c.committee}.`].filter(Boolean).join(" ");renderConsentText();show("consent");}function consentFor(lang) {const C = (S.project.ethics || {}).consent || {};return C[lang] || C.en || Object.values(C)[0];}function renderConsentText() {const lang = $("#f-language").value;const c = consentFor(lang);const box = $("#consent-text");box.replaceChildren();if (!c) return;$("#consent-title").textContent = c.title;$("#consent-title").lang = c.language;for (const para of c.text.split(/\n\s*\n/)) box.append(el("p", { lang: c.language, text: para.trim() }));}async function submitConsent(ev) {ev.preventDefault();$("#consent-error").textContent = "";$("#consent-submit").disabled = true;try {const c = consentFor($("#f-language").value);const res = await api("/api/speakers", { method: "POST", body: {project_id: S.project.project_id, consent_version: S.project.consent_version,consent_sha: c && c.sha, age_confirmed: $("#f-adult").checked,language: $("#f-language").value, gender: $("#f-gender").value || null,age_group: $("#f-age").value || null, region: $("#f-region").value.trim() || null,} });S.speaker = { ...res, language: $("#f-language").value, consent_version: S.project.consent_version };store.set(`speaker.${S.project.project_id}`, S.speaker);await loadTasks();nextTask();} catch (e) {$("#consent-error").textContent = e instanceof ApiError ? e.message : "You need to be online to give consent the first time.";} finally {$("#consent-submit").disabled = false;}}// ------------------------------------------------------------------ tasksconst doneKey = () => `done.${S.project.project_id}.${S.speaker.speaker_id}`;async function loadTasks() {const pid = S.project.project_id;try {const r = await api(`/api/projects/${pid}/next-task?speaker_id=${S.speaker.speaker_id}&language=${S.speaker.language}&limit=25`);S.tasks = r.tasks;store.set(`tasks.${pid}.${S.speaker.speaker_id}`, S.tasks);} catch (e) {if (e instanceof ApiError && (e.status === 404 || e.status === 410)) {store.del(`speaker.${pid}`);return showConsent();}S.tasks = store.get(`tasks.${pid}.${S.speaker.speaker_id}`, []);}}function nextTask() {const done = new Set(store.get(doneKey(), []));S.current = S.tasks.find((t) => !done.has(t.task_id)) || null;S.last = null;if (!S.current) { maybeSurvey(); return; }renderTask(S.current);show("task");}function renderTask(t) {$("#task-kind").textContent = KIND[t.task_type] || "Record";const body = $("#task-body");body.replaceChildren();const lang = t.language;if (t.task_type === "image_description") {const a = S.project.assets[t.prompt.image_asset_id];body.append(el("img", { class: "prompt-image", src: a?.url, alt: a?.alt || "Picture to describe" }));if (t.prompt.scenario) body.append(el("p", { class: "scenario", lang, text: t.prompt.scenario }));} else if (t.task_type === "emotion") {body.append(el("p", { class: "scenario", lang, text: t.prompt.scenario || t.prompt.text }));} else {body.append(promptWords(t.prompt.text, lang));if (t.task_type === "prosody_pair" && t.prompt.interpretation)body.append(el("p", { class: "muted", text: `Meaning: ${t.prompt.interpretation}` }));if (t.prompt.emphasis)body.append(el("p", { class: "muted" }, "Stress the word ", el("strong", { lang, text: t.prompt.emphasis }), "."));}$("#verdict").classList.add("hidden");$("#after-actions").replaceChildren();$("#rec-btn").disabled = false;$("#timer").textContent = "0:00";setMeter(null);const done = new Set(store.get(doneKey(), [])).size;$("#progress").textContent = S.tasks.length ? `${Math.min(done + 1, S.tasks.length)} of ${S.tasks.length}` : "";S.shownAt = performance.now();}function promptWords(text, lang, alignment = null) {const p = el("p", { class: "prompt", lang });if (!alignment) { p.textContent = text; return p; }// Highlight against the *original* prompt words: SCQC's alignment is over normalised// tokens, which line up one-to-one with whitespace-separated words of the prompt.const raw = text.split(/\s+/).filter((w) => w && !/^[\p{P}\p{S}]+$/u.test(w));let ri = 0;const parts = [];for (const op of alignment) {if (op.op === "ins") continue;const word = raw[ri++] ?? op.ref;const cls = op.op === "del" ? "w miss" : op.op === "sub" ? "w sub" : "w";const attrs = { class: cls, text: word };if (op.op === "sub") attrs["data-heard"] = op.hyp;if (op.op === "del") attrs.title = "May not have been picked up";parts.push(el("span", attrs), " ");}while (ri < raw.length) parts.push(el("span", { class: "w", text: raw[ri++] }), " ");p.append(...parts);return p;}// ------------------------------------------------------------------ recordingfunction setMeter(level) {const m = $("#meter"), bar = m.firstElementChild, msg = $("#meter-msg");if (!level) { bar.style.width = "0%"; m.classList.remove("hot"); msg.textContent = ""; return; }const pct = Math.max(0, Math.min(100, ((level.db + 60) / 60) * 100));bar.style.width = `${pct}%`;m.classList.toggle("hot", level.clipping);if (level.clipping) msg.textContent = "Too loud. Move the phone back a little.";else if (level.db < -50 && level.elapsed > 3) msg.textContent = "We can't hear you yet.";else msg.textContent = "";}async function toggleRecording() {const btn = $("#rec-btn");if (S.rec && S.rec.recording) return stopRecording();btn.disabled = true;$("#verdict").classList.add("hidden");$("#after-actions").replaceChildren();if (S.current.task_type !== "image_description" && S.current.task_type !== "emotion")$("#task-body").firstElementChild.replaceWith(promptWords(S.current.prompt.text, S.current.language));S.rec = new Recorder({ onLevel: setMeter });try {await S.rec.start();} catch (e) {btn.disabled = false;toast(e.name === "NotAllowedError" ? "Allow microphone access to record." : "The microphone couldn't start.");return;}btn.disabled = false;btn.classList.add("on");btn.setAttribute("aria-label", "Stop recording");S.timer = setInterval(() => {const t = S.rec.elapsed;$("#timer").textContent = fmtTime(t);if (t >= MAX_SECONDS) stopRecording();}, 200);}async function stopRecording() {clearInterval(S.timer);const btn = $("#rec-btn");btn.classList.remove("on");btn.setAttribute("aria-label", "Start recording");btn.disabled = true;const { samples, sr } = await S.rec.stop();setMeter(null);// 1. Instant, on-device checks (work offline).const local = localChecks(samples, sr);const blob = encodeWav(samples, sr);const item = {client_upload_id: uuid(), project_id: S.project.project_id, task_id: S.current.task_id,speaker_id: S.speaker.speaker_id, blob, created: Date.now(),client_meta: { language: S.current.language, sample_rate: sr, ua: navigator.userAgent.slice(0, 160),seconds_on_prompt: Math.round((performance.now() - S.shownAt) / 100) / 10,local_checks: local.map((c) => c.code) },};const blocking = local.find((c) => c.action === "block");if (blocking) {renderVerdict({ status: "blocked", feedback: { show: true, messages: [blocking] } });btn.disabled = false;return;}// 2. Keep it on the phone, then try to upload for the full check.await queue.add(item);renderVerdict({ status: "checking", local });const res = await sync(item.client_upload_id);if (!res) renderVerdict({ status: "queued", local });btn.disabled = false;}async function sync(waitFor = null) {let found = null;await syncQueue((it, res, err) => {if (err) toast(`A recording couldn't be accepted: ${err.message}`);if (it.client_upload_id === waitFor) found = res;if (res && it.task_id === S.current?.task_id && it.client_upload_id === waitFor) S.last = res;if (res && it.client_upload_id !== waitFor && (res.status === "review" || res.status === "accepted")) markDone(it.task_id);});await refreshQueueState();if (found) renderVerdict(found);return found;}async function refreshQueueState() {const n = await queue.count().catch(() => 0);$("#sync-state").textContent = n ? `${n} waiting to upload` : (navigator.onLine ? "" : "Offline");const d = $("#done-queue");if (d) d.textContent = n ? `${n} recording${n > 1 ? "s are" : " is"} still waiting to upload. Keep this page open when you're online.` : "";}function markDone(taskId) {const done = new Set(store.get(doneKey(), []));done.add(taskId);store.set(doneKey(), [...done]);}// ------------------------------------------------------------------ verdictsfunction renderVerdict(r) {const box = $("#verdict"), actions = $("#after-actions");box.className = "verdict";box.replaceChildren();actions.replaceChildren();const again = el("button", { onclick: () => toggleRecording() }, "Record again");const next = el("button", { class: "primary", onclick: () => { markDone(S.current.task_id); nextTask(); } }, "Next prompt");const fb = r.feedback || {};const list = (msgs) => msgs?.length ? el("ul", {}, msgs.map((m) => el("li", { text: m.text || m }))) : null;if (r.status === "checking") {box.classList.add("neutral");box.append(el("h3", { text: "Checking your recording" }), el("p", { class: "muted", text: "This takes a few seconds." }));} else if (r.status === "queued") {const retry = r.local.filter((c) => c.action === "retry");box.classList.add(retry.length ? "attn" : "neutral");box.append(el("h3", { text: retry.length ? "Saved on this phone. You may want to try again" : "Saved on this phone" }),el("p", { text: "It will upload and be checked fully when you're back online." }), list(retry));actions.append(again, next);} else if (r.status === "checking" && fb.show !== false) {box.classList.add("ok");box.append(el("h3", { text: "Looks good so far" }), el("p", { class: "small", text: "A final timing check is running. You can go on to the next prompt." }), list(fb.messages));actions.append(next);} else if (r.status === "blocked") {box.classList.add("stop");box.append(el("h3", { text: "This recording can't be used" }), list(fb.messages));actions.append(again);} else if (fb.show === false) {box.classList.add("neutral");box.append(el("h3", { text: "Saved" }));actions.append(next);} else if (r.status === "retry") {box.classList.add("attn");box.append(el("h3", { text: "Try once more?" }), list(fb.messages),el("p", { class: "small muted", text: "If you think it's fine, keep it and a reviewer will listen." }));actions.append(again, el("button", { onclick: () => keep(r.recording_id) }, "Keep this one"));} else {// accepted or reviewconst ok = r.status === "accepted";const hint = fb.retry_suggested;box.classList.add(hint ? "attn" : ok ? "ok" : "neutral");box.append(el("h3", { text: hint ? "Saved. Please check the words" : ok ? "Looks good" : "Saved. A reviewer will listen to it" }),list(fb.messages), list(fb.notes));if (hint) actions.append(again);actions.append(next);}if (fb.confidence && fb.confidence.score != null && fb.show !== false && !["checking", "queued", "blocked"].includes(r.status)) {const pct = Math.round(fb.confidence.score * 100);const calibrated = fb.confidence.calibrated === true;const message = calibrated? `Estimated usability: ${pct}% (calibrated on reviewed recordings). A reviewer may still check this take.`: `Automatic quality score: ${pct}/100 (not calibrated as a probability). This is not a judgment of your speech; a reviewer may check this take.`;box.append(el("div", { class: "conf" },el("div", { class: "meter conf-meter" }, el("i", { style: `width:${pct}%` })),el("p", { class: "small", text: message })));}if (fb.words && S.current && S.current.prompt.text && S.current.task_type !== "emotion")$("#task-body").firstElementChild.replaceWith(promptWords(S.current.prompt.text, S.current.language, fb.words));box.classList.remove("hidden");}async function keep(rid) {try {await api(`/api/recordings/${rid}/keep`, { method: "POST", body: { speaker_id: S.speaker.speaker_id } });markDone(S.current.task_id);toast("Kept. A reviewer will listen to it.");nextTask();} catch (e) { toast(e.message); }}// ------------------------------------------------------------------ tabsconst STATUS = { accepted: ["Approved", "ok"], review: ["Waiting for review", ""], checking: ["Final check running", ""],retry: ["Needs a retry", "attn"], rejected: ["Not approved", "stop"], blocked: ["Unusable", "stop"],superseded: ["Replaced", ""], withdrawn: ["Deleted", ""] };const fmtDate = (t) => new Date(t * 1000).toLocaleString(undefined, { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" });const money = (cur, v) => (cur === "INR" ? "₹" : cur + " ") + Number(v || 0).toFixed(2).replace(/\.00$/, "");function taskLabel(taskId) {const t = (S.project.tasks || []).find((x) => x.task_id === taskId);if (!t) return taskId;return t.prompt.text || t.prompt.scenario || (t.task_type === "image_description" ? "Picture description" : taskId);}async function openHistory() {show("history");const list = $("#history-list");list.replaceChildren(el("li", { class: "muted", text: "Loading…" }));try {const hist = await api(`/api/speakers/${S.speaker.speaker_id}/history`);if (!hist.length) { list.replaceChildren(el("li", { class: "muted", text: "No recordings yet." })); return; }list.replaceChildren(...hist.filter((h) => h.status !== "superseded").map((h) => {const [txt, cls] = STATUS[h.status] || [h.status, ""];const audio = el("audio", { preload: "none", src: `/api/speakers/${S.speaker.speaker_id}/recordings/${h.recording_id}/audio` });const play = el("button", { class: "icon-btn", "aria-label": "Play recording", onclick: () => {document.querySelectorAll("#history-list audio").forEach((a) => a !== audio && a.pause());audio.paused ? audio.play().catch(() => toast("This recording can't be played.")) : audio.pause();} }, "▶");audio.onplay = () => (play.textContent = "❚❚");audio.onpause = audio.onended = () => (play.textContent = "▶");return el("li", { class: "list-row" },el("span", { class: `dot ${cls}`, "aria-hidden": "true" }),el("div", { class: "grow" }, el("div", { class: "line-clamp", lang: S.speaker.language, text: taskLabel(h.task_id) }),el("div", { class: "small muted" }, `${fmtDate(h.created_at)}, attempt ${h.attempt}, `, el("span", { class: `pill ${cls}`, text: txt }))),h.status !== "withdrawn" ? play : null, audio);}));} catch { list.replaceChildren(el("li", { class: "muted", text: "Connect to the internet to see your history." })); }}async function openWallet() {show("wallet");try {const w = await api(`/api/speakers/${S.speaker.speaker_id}/wallet`);const cur = (w.balances[0] || {}).currency || "INR";const total = w.balances.reduce((a, b) => a + b.total, 0);const n = w.balances.reduce((a, b) => a + b.n, 0);const paid = w.balances.filter((b) => b.status === "paid").reduce((a, b) => a + b.total, 0);$("#wallet-total").textContent = money(cur, total);$("#wallet-sub").textContent = n ? `${n} approved recording${n > 1 ? "s" : ""}, ${money(cur, paid)} paid out` : "Earnings appear here once a recording is approved.";$("#wallet-note").classList.toggle("hidden", !w.simulated_payments);const lab = { earned: ["Earned", "ok"], pending: ["Payout in progress", "attn"], paid: ["Paid", "ok"] };$("#tx-list").replaceChildren(...(w.transactions.length ? w.transactions.map((t) => {const [txt, cls] = lab[t.status] || [t.status, ""];return el("li", { class: "list-row" },el("div", { class: "grow" }, el("div", { class: "line-clamp", lang: S.speaker.language, text: taskLabel(t.task_id) }),el("div", { class: "small muted", text: t.txn_id ? `${t.txn_id}, ${fmtDate(t.paid_at)}` : fmtDate(t.created_at) })),el("div", { style: "text-align:right" }, el("strong", { text: money(t.currency, t.amount) }), el("br"), el("span", { class: `pill ${cls}`, text: txt })));}) : [el("li", { class: "muted", text: "No transactions yet." })]));} catch { $("#wallet-sub").textContent = "Connect to the internet to see your earnings."; }}async function openProfile() {show("profile");const sid = S.speaker.speaker_id;$("#profile-id").textContent = sid;$("#avatar").textContent = sid.slice(-2).toUpperCase();const kv = $("#profile-kv");kv.replaceChildren();const add = (k, v) => kv.append(el("dt", { text: k }), el("dd", { text: v }));try {const p = await api(`/api/speakers/${sid}/profile`);add("Project", p.project_title || p.project_id);add("Language", LANG_NAMES[p.language] || p.language || "Not set");add("Prompts", String(p.tasks_total));add("Approved", String(p.recordings.accepted || 0));add("Waiting for review", String((p.recordings.review || 0) + (p.recordings.checking || 0)));add("Joined", new Date(p.joined_at * 1000).toLocaleDateString());add("Consent version", p.consent_version);} catch { add("Status", "Offline"); }const c = (S.project.ethics || {}).contact || {};$("#profile-contact").textContent = [c.researcher && `Questions: ${c.researcher}.`, c.committee && `Concerns: ${c.committee}.`].filter(Boolean).join(" ");}// ------------------------------------------------------------------ usability questionnaireconst SUS = ["I think that I would like to use this app frequently.","I found the app unnecessarily complex.","I thought the app was easy to use.","I think that I would need the support of a technical person to be able to use this app.","I found the various functions in this app were well integrated.","I thought there was too much inconsistency in this app.","I would imagine that most people would learn to use this app very quickly.","I found the app very cumbersome to use.","I felt very confident using the app.","I needed to learn a lot of things before I could get going with this app.",];async function maybeSurvey() {refreshQueueState();let p = null;try { p = await api(`/api/speakers/${S.speaker.speaker_id}/profile`); } catch { /* offline */ }if (!p || p.survey !== "sus" || p.survey_done) { show("done"); return; }const form = $("#survey-form");form.replaceChildren(...SUS.map((q, i) => el("fieldset", { class: "likert" },el("legend", { text: `${i + 1}. ${q}` }),el("div", { class: "seg" }, [1, 2, 3, 4, 5].map((v) => el("label", {}, el("input", { type: "radio", name: `q${i}`, value: v, required: true }), el("span", { text: String(v) })))))),el("div", { class: "actions" }, el("button", { class: "primary", type: "submit" }, "Send answers"),el("button", { type: "button", onclick: () => show("done") }, "Skip")));form.onsubmit = async (e) => {e.preventDefault();const answers = SUS.map((_, i) => Number(new FormData(form).get(`q${i}`)));try { await api(`/api/speakers/${S.speaker.speaker_id}/survey`, { method: "POST", body: { instrument: "sus", answers } }); toast("Thank you."); }catch (err) { toast(err.message); return; }show("done");};show("survey");}async function withdraw() {if (!confirm("This deletes all your recordings from this project and ends your participation. Earnings already approved are kept. Continue?")) return;try {const r = await api(`/api/speakers/${S.speaker.speaker_id}`, { method: "DELETE" });store.del(`speaker.${S.project.project_id}`);toast(`Done. ${r.recordings_deleted} recording${r.recordings_deleted === 1 ? "" : "s"} deleted.`);showConsent();} catch (e) { toast(e instanceof ApiError ? e.message : "You need to be online to do this."); }}boot();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549import { $, el, api, ApiError, toast, store, queue, syncQueue, uuid, fmtTime, LANG_NAMES } from "/static/common.js";import { Recorder, encodeWav, localChecks } from "/static/recorder.js";const MAX_SECONDS = 90;const KIND = {read_speech: "Read this aloud",command: "Say this command",image_description: "Describe the picture in your own words",prosody_pair: "Read this so that the meaning below is clear",emotion: "Respond to this situation as you naturally would",tts_prosody: "Read this clearly, following the punctuation",};const S = {project: null, // participant-safe project viewspeaker: null, // {speaker_id, condition, language}tasks: [], // prefetched tasks, cached for offline usecurrent: null, // current taskrec: null,timer: null,shownAt: 0,last: null, // last upload result for the current task};const views = ["projects", "consent", "task", "done", "survey", "history", "wallet", "profile"];const TABBED = { task: "task", done: "task", survey: "task", history: "history", wallet: "wallet", profile: "profile" };function show(name) {for (const v of views) $(`#view-${v}`).classList.toggle("hidden", v !== name);const tab = TABBED[name];$("#tabs").classList.toggle("hidden", !tab);document.querySelectorAll("#tabs button").forEach((b) => b.setAttribute("aria-current", b.dataset.tab === tab ? "page" : "false"));}function openTab(tab) {if (tab === "task") return nextTask();if (tab === "history") return openHistory();if (tab === "wallet") return openWallet();if (tab === "profile") return openProfile();}// ------------------------------------------------------------------ bootasync function boot() {const token = store.get("admin.session");if (!token) { location.replace("/"); return; }try {const me = await api("/api/auth/me", { token });if (me.role !== "participant") { location.replace(me.role === "reviewer" ? "/review" : "/admin"); return; }$("#participant-account").textContent = me.display_name || me.username;} catch { store.del("admin.session"); location.replace("/"); return; }$("#participant-logout").onclick = async () => {await api("/api/auth/logout", { method: "POST", token }).catch(() => {});store.del("admin.session"); location.replace("/");};if ("serviceWorker" in navigator) navigator.serviceWorker.register("/sw.js").catch(() => {});window.addEventListener("online", () => sync());document.querySelectorAll("#tabs button").forEach((b) => (b.onclick = () => openTab(b.dataset.tab)));$("#withdraw").onclick = withdraw;$("#switch-project").onclick = () => { store.del("last_project"); pickProject(true); };$("#rec-btn").onclick = toggleRecording;$("#consent-form").onsubmit = submitConsent;await refreshQueueState();const wanted = new URLSearchParams(location.search).get("project") || store.get("last_project");if (wanted) await openProject(wanted);else await pickProject();sync();}async function pickProject(force = false) {let list;try { list = await api("/api/projects"); store.set("projects", list); }catch { list = store.get("projects", []); }if (list.length === 1 && !force) return openProject(list[0].project_id);const box = $("#project-list");box.replaceChildren();if (!list.length) box.append(el("p", { class: "muted", text: "No projects are open yet. Ask your coordinator for a project link." }));for (const p of list) {box.append(el("button", { class: "panel", style: "width:100%;text-align:left;display:block",onclick: () => openProject(p.project_id) },el("strong", { text: p.title || p.project_id }), el("br"),el("span", { class: "muted small", text: p.languages.map((l) => LANG_NAMES[l] || l).join(", ") })));}show("projects");}async function openProject(pid) {try {S.project = await api(`/api/projects/${encodeURIComponent(pid)}`);store.set(`project.${pid}`, S.project);} catch (e) {S.project = store.get(`project.${pid}`);if (!S.project) { toast(e.status === 404 ? "That project doesn't exist." : "You're offline and this project isn't saved on this phone yet."); return pickProject(true); }}store.set("last_project", pid);$("#project-title").textContent = S.project.title || S.project.project_id;S.speaker = store.get(`speaker.${pid}`);if (!S.speaker || S.speaker.consent_version !== S.project.consent_version) return showConsent();await loadTasks();nextTask();}// ------------------------------------------------------------------ consentfunction showConsent() {const P = S.project, E = P.ethics || {};const sel = $("#f-language");sel.replaceChildren(...P.languages.map((l) => el("option", { value: l, text: LANG_NAMES[l] || l })));sel.onchange = renderConsentText;$("#test-banner").classList.toggle("hidden", E.status !== "internal_test");const closed = P.open === false;$("#consent-closed").classList.toggle("hidden", !closed);$("#consent-closed").replaceChildren(el("p", { text: P.closed_reason || "This project is closed." }));$("#consent-form").classList.toggle("hidden", closed);$("#f-adult-label").textContent = `I am ${E.minimum_age ?? 18} or older`;$("#f-adult").required = (E.minimum_age ?? 18) > 0;let line = "";if (E.status === "approved") {line = `Approved by ${E.committee}${E.institution ? `, ${E.institution}` : ""}. Reference ${E.protocol_id}` +`${E.amendment_id ? ` (amendment ${E.amendment_id})` : ""}, valid until ${E.expiry_date}.`;if (E.retention_days) line += ` Recordings are deleted after ${E.retention_days} days.`;if (E.data_hosting) line += ` Stored on: ${E.data_hosting}.`;} else if (E.status === "pending") {line = `Waiting for approval from ${E.committee}.`;} else if (E.status === "not_required") {line = `This project has not been reviewed by an ethics committee. The project owner's reason: ${E.not_required_reason}`;}$("#ethics-line").textContent = line;const c = E.contact || {};$("#contact-line").textContent = [c.researcher && `Questions: ${c.researcher}.`,c.committee && `Concerns about how the study is run: ${c.committee}.`].filter(Boolean).join(" ");renderConsentText();show("consent");}function consentFor(lang) {const C = (S.project.ethics || {}).consent || {};return C[lang] || C.en || Object.values(C)[0];}function renderConsentText() {const lang = $("#f-language").value;const c = consentFor(lang);const box = $("#consent-text");box.replaceChildren();if (!c) return;$("#consent-title").textContent = c.title;$("#consent-title").lang = c.language;for (const para of c.text.split(/\n\s*\n/)) box.append(el("p", { lang: c.language, text: para.trim() }));}async function submitConsent(ev) {ev.preventDefault();$("#consent-error").textContent = "";$("#consent-submit").disabled = true;try {const c = consentFor($("#f-language").value);const res = await api("/api/speakers", { method: "POST", body: {project_id: S.project.project_id, consent_version: S.project.consent_version,consent_sha: c && c.sha, age_confirmed: $("#f-adult").checked,language: $("#f-language").value, gender: $("#f-gender").value || null,age_group: $("#f-age").value || null, region: $("#f-region").value.trim() || null,} });S.speaker = { ...res, language: $("#f-language").value, consent_version: S.project.consent_version };store.set(`speaker.${S.project.project_id}`, S.speaker);await loadTasks();nextTask();} catch (e) {$("#consent-error").textContent = e instanceof ApiError ? e.message : "You need to be online to give consent the first time.";} finally {$("#consent-submit").disabled = false;}}// ------------------------------------------------------------------ tasksconst doneKey = () => `done.${S.project.project_id}.${S.speaker.speaker_id}`;async function loadTasks() {const pid = S.project.project_id;try {const r = await api(`/api/projects/${pid}/next-task?speaker_id=${S.speaker.speaker_id}&language=${S.speaker.language}&limit=25`);S.tasks = r.tasks;store.set(`tasks.${pid}.${S.speaker.speaker_id}`, S.tasks);} catch (e) {if (e instanceof ApiError && (e.status === 404 || e.status === 410)) {store.del(`speaker.${pid}`);return showConsent();}S.tasks = store.get(`tasks.${pid}.${S.speaker.speaker_id}`, []);}}function nextTask() {const done = new Set(store.get(doneKey(), []));S.current = S.tasks.find((t) => !done.has(t.task_id)) || null;S.last = null;if (!S.current) { maybeSurvey(); return; }renderTask(S.current);show("task");}function renderTask(t) {$("#task-kind").textContent = KIND[t.task_type] || "Record";const body = $("#task-body");body.replaceChildren();const lang = t.language;if (t.task_type === "image_description") {const a = S.project.assets[t.prompt.image_asset_id];body.append(el("img", { class: "prompt-image", src: a?.url, alt: a?.alt || "Picture to describe" }));if (t.prompt.scenario) body.append(el("p", { class: "scenario", lang, text: t.prompt.scenario }));} else if (t.task_type === "emotion") {body.append(el("p", { class: "scenario", lang, text: t.prompt.scenario || t.prompt.text }));} else {body.append(promptWords(t.prompt.text, lang));if (t.task_type === "prosody_pair" && t.prompt.interpretation)body.append(el("p", { class: "muted", text: `Meaning: ${t.prompt.interpretation}` }));if (t.prompt.emphasis)body.append(el("p", { class: "muted" }, "Stress the word ", el("strong", { lang, text: t.prompt.emphasis }), "."));}$("#verdict").classList.add("hidden");$("#after-actions").replaceChildren();$("#rec-btn").disabled = false;$("#timer").textContent = "0:00";setMeter(null);const done = new Set(store.get(doneKey(), [])).size;$("#progress").textContent = S.tasks.length ? `${Math.min(done + 1, S.tasks.length)} of ${S.tasks.length}` : "";S.shownAt = performance.now();}function promptWords(text, lang, alignment = null) {const p = el("p", { class: "prompt", lang });if (!alignment) { p.textContent = text; return p; }// Highlight against the *original* prompt words: SCQC's alignment is over normalised// tokens, which line up one-to-one with whitespace-separated words of the prompt.const raw = text.split(/\s+/).filter((w) => w && !/^[\p{P}\p{S}]+$/u.test(w));let ri = 0;const parts = [];for (const op of alignment) {if (op.op === "ins") continue;const word = raw[ri++] ?? op.ref;const cls = op.op === "del" ? "w miss" : op.op === "sub" ? "w sub" : "w";const attrs = { class: cls, text: word };if (op.op === "sub") attrs["data-heard"] = op.hyp;if (op.op === "del") attrs.title = "May not have been picked up";parts.push(el("span", attrs), " ");}while (ri < raw.length) parts.push(el("span", { class: "w", text: raw[ri++] }), " ");p.append(...parts);return p;}// ------------------------------------------------------------------ recordingfunction setMeter(level) {const m = $("#meter"), bar = m.firstElementChild, msg = $("#meter-msg");if (!level) { bar.style.width = "0%"; m.classList.remove("hot"); msg.textContent = ""; return; }const pct = Math.max(0, Math.min(100, ((level.db + 60) / 60) * 100));bar.style.width = `${pct}%`;m.classList.toggle("hot", level.clipping);if (level.clipping) msg.textContent = "Too loud. Move the phone back a little.";else if (level.db < -50 && level.elapsed > 3) msg.textContent = "We can't hear you yet.";else msg.textContent = "";}async function toggleRecording() {const btn = $("#rec-btn");if (S.rec && S.rec.recording) return stopRecording();btn.disabled = true;$("#verdict").classList.add("hidden");$("#after-actions").replaceChildren();if (S.current.task_type !== "image_description" && S.current.task_type !== "emotion")$("#task-body").firstElementChild.replaceWith(promptWords(S.current.prompt.text, S.current.language));S.rec = new Recorder({ onLevel: setMeter });try {await S.rec.start();} catch (e) {btn.disabled = false;toast(e.name === "NotAllowedError" ? "Allow microphone access to record." : "The microphone couldn't start.");return;}btn.disabled = false;btn.classList.add("on");btn.setAttribute("aria-label", "Stop recording");S.timer = setInterval(() => {const t = S.rec.elapsed;$("#timer").textContent = fmtTime(t);if (t >= MAX_SECONDS) stopRecording();}, 200);}async function stopRecording() {clearInterval(S.timer);const btn = $("#rec-btn");btn.classList.remove("on");btn.setAttribute("aria-label", "Start recording");btn.disabled = true;const { samples, sr } = await S.rec.stop();setMeter(null);// 1. Instant, on-device checks (work offline).const local = localChecks(samples, sr);const blob = encodeWav(samples, sr);const item = {client_upload_id: uuid(), project_id: S.project.project_id, task_id: S.current.task_id,speaker_id: S.speaker.speaker_id, blob, created: Date.now(),client_meta: { language: S.current.language, sample_rate: sr, ua: navigator.userAgent.slice(0, 160),seconds_on_prompt: Math.round((performance.now() - S.shownAt) / 100) / 10,local_checks: local.map((c) => c.code) },};const blocking = local.find((c) => c.action === "block");if (blocking) {renderVerdict({ status: "blocked", feedback: { show: true, messages: [blocking] } });btn.disabled = false;return;}// 2. Keep it on the phone, then try to upload for the full check.await queue.add(item);renderVerdict({ status: "checking", local });const res = await sync(item.client_upload_id);if (!res) renderVerdict({ status: "queued", local });btn.disabled = false;}async function sync(waitFor = null) {let found = null;await syncQueue((it, res, err) => {if (err) toast(`A recording couldn't be accepted: ${err.message}`);if (it.client_upload_id === waitFor) found = res;if (res && it.task_id === S.current?.task_id && it.client_upload_id === waitFor) S.last = res;if (res && it.client_upload_id !== waitFor && (res.status === "review" || res.status === "accepted")) markDone(it.task_id);});await refreshQueueState();if (found) renderVerdict(found);return found;}async function refreshQueueState() {const n = await queue.count().catch(() => 0);$("#sync-state").textContent = n ? `${n} waiting to upload` : (navigator.onLine ? "" : "Offline");const d = $("#done-queue");if (d) d.textContent = n ? `${n} recording${n > 1 ? "s are" : " is"} still waiting to upload. Keep this page open when you're online.` : "";}function markDone(taskId) {const done = new Set(store.get(doneKey(), []));done.add(taskId);store.set(doneKey(), [...done]);}// ------------------------------------------------------------------ verdictsfunction renderVerdict(r) {const box = $("#verdict"), actions = $("#after-actions");box.className = "verdict";box.replaceChildren();actions.replaceChildren();const again = el("button", { onclick: () => toggleRecording() }, "Record again");const next = el("button", { class: "primary", onclick: () => { markDone(S.current.task_id); nextTask(); } }, "Next prompt");const fb = r.feedback || {};const list = (msgs) => msgs?.length ? el("ul", {}, msgs.map((m) => el("li", { text: m.text || m }))) : null;if (r.status === "checking") {box.classList.add("neutral");box.append(el("h3", { text: "Checking your recording" }), el("p", { class: "muted", text: "This takes a few seconds." }));} else if (r.status === "queued") {const retry = r.local.filter((c) => c.action === "retry");box.classList.add(retry.length ? "attn" : "neutral");box.append(el("h3", { text: retry.length ? "Saved on this phone. You may want to try again" : "Saved on this phone" }),el("p", { text: "It will upload and be checked fully when you're back online." }), list(retry));actions.append(again, next);} else if (r.status === "checking" && fb.show !== false) {box.classList.add("ok");box.append(el("h3", { text: "Looks good so far" }), el("p", { class: "small", text: "A final timing check is running. You can go on to the next prompt." }), list(fb.messages));actions.append(next);} else if (r.status === "blocked") {box.classList.add("stop");box.append(el("h3", { text: "This recording can't be used" }), list(fb.messages));actions.append(again);} else if (fb.show === false) {box.classList.add("neutral");box.append(el("h3", { text: "Saved" }));actions.append(next);} else if (r.status === "retry") {box.classList.add("attn");box.append(el("h3", { text: "Try once more?" }), list(fb.messages),el("p", { class: "small muted", text: "If you think it's fine, keep it and a reviewer will listen." }));actions.append(again, el("button", { onclick: () => keep(r.recording_id) }, "Keep this one"));} else {// accepted or reviewconst ok = r.status === "accepted";const hint = fb.retry_suggested;box.classList.add(hint ? "attn" : ok ? "ok" : "neutral");box.append(...[el("h3", { text: hint ? "Saved. Please check the words" : ok ? "Looks good" : "Saved. A reviewer will listen to it" }),list(fb.messages),list(fb.notes),].filter(Boolean));if (hint) actions.append(again);actions.append(next);}if (fb.confidence && fb.confidence.score != null && fb.show !== false && !["checking", "queued", "blocked"].includes(r.status)) {const pct = Math.round(fb.confidence.score * 100);const calibrated = fb.confidence.calibrated === true;const message = calibrated? `Estimated usability: ${pct}% (calibrated on reviewed recordings). A reviewer may still check this take.`: `Automatic quality score: ${pct}/100 (not calibrated as a probability). This is not a judgment of your speech; a reviewer may check this take.`;box.append(el("div", { class: "conf" },el("div", { class: "meter conf-meter" }, el("i", { style: `width:${pct}%` })),el("p", { class: "small", text: message })));}if (fb.words && S.current && S.current.prompt.text && S.current.task_type !== "emotion")$("#task-body").firstElementChild.replaceWith(promptWords(S.current.prompt.text, S.current.language, fb.words));box.classList.remove("hidden");}async function keep(rid) {try {await api(`/api/recordings/${rid}/keep`, { method: "POST", body: { speaker_id: S.speaker.speaker_id } });markDone(S.current.task_id);toast("Kept. A reviewer will listen to it.");nextTask();} catch (e) { toast(e.message); }}// ------------------------------------------------------------------ tabsconst STATUS = { accepted: ["Approved", "ok"], review: ["Waiting for review", ""], checking: ["Final check running", ""],retry: ["Needs a retry", "attn"], rejected: ["Not approved", "stop"], blocked: ["Unusable", "stop"],superseded: ["Replaced", ""], withdrawn: ["Deleted", ""] };const fmtDate = (t) => new Date(t * 1000).toLocaleString(undefined, { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" });const money = (cur, v) => (cur === "INR" ? "₹" : cur + " ") + Number(v || 0).toFixed(2).replace(/\.00$/, "");function taskLabel(taskId) {const t = (S.project.tasks || []).find((x) => x.task_id === taskId);if (!t) return taskId;return t.prompt.text || t.prompt.scenario || (t.task_type === "image_description" ? "Picture description" : taskId);}async function openHistory() {show("history");const list = $("#history-list");list.replaceChildren(el("li", { class: "muted", text: "Loading…" }));try {const hist = await api(`/api/speakers/${S.speaker.speaker_id}/history`);if (!hist.length) { list.replaceChildren(el("li", { class: "muted", text: "No recordings yet." })); return; }list.replaceChildren(...hist.filter((h) => h.status !== "superseded").map((h) => {const [txt, cls] = STATUS[h.status] || [h.status, ""];const audio = el("audio", { preload: "none", src: `/api/speakers/${S.speaker.speaker_id}/recordings/${h.recording_id}/audio` });const play = el("button", { class: "icon-btn", "aria-label": "Play recording", onclick: () => {document.querySelectorAll("#history-list audio").forEach((a) => a !== audio && a.pause());audio.paused ? audio.play().catch(() => toast("This recording can't be played.")) : audio.pause();} }, "▶");audio.onplay = () => (play.textContent = "❚❚");audio.onpause = audio.onended = () => (play.textContent = "▶");return el("li", { class: "list-row" },el("span", { class: `dot ${cls}`, "aria-hidden": "true" }),el("div", { class: "grow" }, el("div", { class: "line-clamp", lang: S.speaker.language, text: taskLabel(h.task_id) }),el("div", { class: "small muted" }, `${fmtDate(h.created_at)}, attempt ${h.attempt}, `, el("span", { class: `pill ${cls}`, text: txt }))),h.status !== "withdrawn" ? play : null, audio);}));} catch { list.replaceChildren(el("li", { class: "muted", text: "Connect to the internet to see your history." })); }}async function openWallet() {show("wallet");try {const w = await api(`/api/speakers/${S.speaker.speaker_id}/wallet`);const cur = (w.balances[0] || {}).currency || "INR";const total = w.balances.reduce((a, b) => a + b.total, 0);const n = w.balances.reduce((a, b) => a + b.n, 0);const paid = w.balances.filter((b) => b.status === "paid").reduce((a, b) => a + b.total, 0);$("#wallet-total").textContent = money(cur, total);$("#wallet-sub").textContent = n ? `${n} approved recording${n > 1 ? "s" : ""}, ${money(cur, paid)} paid out` : "Earnings appear here once a recording is approved.";$("#wallet-note").classList.toggle("hidden", !w.simulated_payments);const lab = { earned: ["Earned", "ok"], pending: ["Payout in progress", "attn"], paid: ["Paid", "ok"] };$("#tx-list").replaceChildren(...(w.transactions.length ? w.transactions.map((t) => {const [txt, cls] = lab[t.status] || [t.status, ""];return el("li", { class: "list-row" },el("div", { class: "grow" }, el("div", { class: "line-clamp", lang: S.speaker.language, text: taskLabel(t.task_id) }),el("div", { class: "small muted", text: t.txn_id ? `${t.txn_id}, ${fmtDate(t.paid_at)}` : fmtDate(t.created_at) })),el("div", { style: "text-align:right" }, el("strong", { text: money(t.currency, t.amount) }), el("br"), el("span", { class: `pill ${cls}`, text: txt })));}) : [el("li", { class: "muted", text: "No transactions yet." })]));} catch { $("#wallet-sub").textContent = "Connect to the internet to see your earnings."; }}async function openProfile() {show("profile");const sid = S.speaker.speaker_id;$("#profile-id").textContent = sid;$("#avatar").textContent = sid.slice(-2).toUpperCase();const kv = $("#profile-kv");kv.replaceChildren();const add = (k, v) => kv.append(el("dt", { text: k }), el("dd", { text: v }));try {const p = await api(`/api/speakers/${sid}/profile`);add("Project", p.project_title || p.project_id);add("Language", LANG_NAMES[p.language] || p.language || "Not set");add("Prompts", String(p.tasks_total));add("Approved", String(p.recordings.accepted || 0));add("Waiting for review", String((p.recordings.review || 0) + (p.recordings.checking || 0)));add("Joined", new Date(p.joined_at * 1000).toLocaleDateString());add("Consent version", p.consent_version);} catch { add("Status", "Offline"); }const c = (S.project.ethics || {}).contact || {};$("#profile-contact").textContent = [c.researcher && `Questions: ${c.researcher}.`, c.committee && `Concerns: ${c.committee}.`].filter(Boolean).join(" ");}// ------------------------------------------------------------------ usability questionnaireconst SUS = ["I think that I would like to use this app frequently.","I found the app unnecessarily complex.","I thought the app was easy to use.","I think that I would need the support of a technical person to be able to use this app.","I found the various functions in this app were well integrated.","I thought there was too much inconsistency in this app.","I would imagine that most people would learn to use this app very quickly.","I found the app very cumbersome to use.","I felt very confident using the app.","I needed to learn a lot of things before I could get going with this app.",];async function maybeSurvey() {refreshQueueState();let p = null;try { p = await api(`/api/speakers/${S.speaker.speaker_id}/profile`); } catch { /* offline */ }if (!p || p.survey !== "sus" || p.survey_done) { show("done"); return; }const form = $("#survey-form");form.replaceChildren(...SUS.map((q, i) => el("fieldset", { class: "likert" },el("legend", { text: `${i + 1}. ${q}` }),el("div", { class: "seg" }, [1, 2, 3, 4, 5].map((v) => el("label", {}, el("input", { type: "radio", name: `q${i}`, value: v, required: true }), el("span", { text: String(v) })))))),el("div", { class: "actions" }, el("button", { class: "primary", type: "submit" }, "Send answers"),el("button", { type: "button", onclick: () => show("done") }, "Skip")));form.onsubmit = async (e) => {e.preventDefault();const answers = SUS.map((_, i) => Number(new FormData(form).get(`q${i}`)));try { await api(`/api/speakers/${S.speaker.speaker_id}/survey`, { method: "POST", body: { instrument: "sus", answers } }); toast("Thank you."); }catch (err) { toast(err.message); return; }show("done");};show("survey");}async function withdraw() {if (!confirm("This deletes all your recordings from this project and ends your participation. Earnings already approved are kept. Continue?")) return;try {const r = await api(`/api/speakers/${S.speaker.speaker_id}`, { method: "DELETE" });store.del(`speaker.${S.project.project_id}`);toast(`Done. ${r.recordings_deleted} recording${r.recordings_deleted === 1 ? "" : "s"} deleted.`);showConsent();} catch (e) { toast(e instanceof ApiError ? e.message : "You need to be online to do this."); }}boot();
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130import jsonfrom pathlib import Pathimport pytestfrom fastapi.testclient import TestClientfrom conftest import CLEAN, MISREADEX = Path(__file__).resolve().parents[1] / "examples"ADM = {"X-SCQC-Token": "adm"}@pytest.fixture(scope="module")def c():from server.app import appclient = TestClient(app)m = json.loads((EX / "manifest_pilot.json").read_text(encoding="utf-8"))m["project_id"] = "ACC_LEDGER"m["defaults"]["validation"]["human_review"] = "uncertain"m["experiment"]["survey"] = "sus"assert client.post("/api/projects?replace=true", json=m, headers=ADM).status_code == 201return clientdef login(c, u, p):r = c.post("/api/auth/login", json={"username": u, "password": p})return r.json()["token"] if r.status_code == 200 else rdef join(c, pid="ACC_LEDGER"):v = c.get(f"/api/projects/{pid}").json()return c.post("/api/speakers", json={"project_id": pid, "consent_version": v["consent_version"], "language": "hi","consent_sha": v["ethics"]["consent"]["hi"]["sha"], "age_confirmed": True}).json()def up(c, sid, task, data, pid="ACC_LEDGER"):import uuidreturn c.post("/api/recordings", data={"project_id": pid, "task_id": task, "speaker_id": sid,"client_upload_id": uuid.uuid4().hex, "client_meta": "{}"},files={"file": ("a.wav", data, "audio/wav")}).json()def test_setup_login_roles(c):if not c.get("/api/auth/status").json()["has_users"]:body = {"username": "anand", "password": "a-long-password", "role": "admin", "display_name": "Anand"}assert c.post("/api/auth/setup", json=body).status_code == 401 # needs the server tokenassert c.post("/api/auth/setup", json=body, headers=ADM).status_code == 201tok = login(c, "anand", "a-long-password")H = {"X-SCQC-Token": tok}assert c.get("/api/auth/me", headers=H).json()["role"] == "admin"r = c.post("/api/users", headers=H, json={"username": "rev1", "password": "reviewer-pass-1", "role": "reviewer"})assert r.status_code in (201, 409)rt = login(c, "rev1", "reviewer-pass-1")R = {"X-SCQC-Token": rt}assert c.get("/api/users", headers=R).status_code == 401 # reviewers can't manage usersassert c.get("/api/review/queue?project_id=ACC_LEDGER", headers=R).status_code == 200assert login(c, "rev1", "wrong-password").status_code == 401assert c.patch("/api/users/anand", headers=H, json={"disabled": True}).status_code == 409def test_review_identity_and_filters(c):rt = login(c, "rev1", "reviewer-pass-1")R = {"X-SCQC-Token": rt}sid = join(c)["speaker_id"]rec = up(c, sid, "p_001", MISREAD)q = c.get("/api/review/queue?project_id=ACC_LEDGER&filter=high", headers=R).json()item = next(i for i in q if i["recording_id"] == rec["recording_id"])assert item["priority"] == "high" and "flagged" in item["categories"] and item["confidence"]["score"] < 0.8# The audio plays with the session token, and the review is recorded under the logged-in name.assert c.get(item["audio_url"] + f"?token={rt}").status_code == 200v = c.post(f"/api/review/{rec['recording_id']}", headers=R, json={"reviewer_id": "someone-else", "verdict": "accept"})assert v.status_code == 200from server.app import dbassert db.one("SELECT reviewer_id FROM reviews WHERE recording_id=?", (rec["recording_id"],))["reviewer_id"] == "rev1"def test_simulated_payouts_and_wallet(c):sid = join(c)["speaker_id"]r = up(c, sid, "p_002", CLEAN)if r["status"] != "accepted":from server.app import db, _pay, manifestwith db.tx() as cx:cx.execute("UPDATE recordings SET status='accepted' WHERE recording_id=?", (r["recording_id"],))_pay(cx, manifest("ACC_LEDGER"), cx.execute("SELECT * FROM recordings WHERE recording_id=?", (r["recording_id"],)).fetchone())b = c.post("/api/projects/ACC_LEDGER/payouts/batches", headers=ADM).json()assert b["simulated"] and b["n"] >= 1w = c.get(f"/api/speakers/{sid}/wallet").json()assert w["transactions"][0]["status"] == "pending" and w["simulated_payments"]s = c.post(f"/api/payouts/batches/{b['batch_id']}/settle", headers=ADM).json()assert s["status"] == "paid"w = c.get(f"/api/speakers/{sid}/wallet").json()assert w["transactions"][0]["txn_id"].startswith("SIM-UPI-") and w["transactions"][0]["paid_at"]assert c.post(f"/api/payouts/batches/{b['batch_id']}/settle", headers=ADM).status_code == 409lst = c.get("/api/projects/ACC_LEDGER/payouts/batches", headers=ADM).json()assert any(x["batch_id"] == b["batch_id"] and x["status"] == "paid" for x in lst["batches"])def test_survey_profile_playback_dashboard(c):sid = join(c)["speaker_id"]rec = up(c, sid, "p_003", CLEAN)assert c.get(f"/api/speakers/{sid}/recordings/{rec['recording_id']}/audio").status_code == 200assert c.get(f"/api/speakers/spk_other/recordings/{rec['recording_id']}/audio").status_code == 404s = c.post(f"/api/speakers/{sid}/survey", json={"instrument": "sus", "answers": [5, 1, 5, 1, 5, 1, 5, 1, 5, 1]}).json()assert s["score"] == 100.0p = c.get(f"/api/speakers/{sid}/profile").json()assert p["survey_done"] and p["survey"] == "sus" and p["tasks_total"] == 3d = c.get("/api/projects/ACC_LEDGER/dashboard", headers=ADM).json()assert d["contributors"] >= 3 and len(d["daily"]) == 14 and "hi" in d["by_language"]assert d["daily"][-1]["recordings"] >= 1def test_study_report(c):m = json.loads((EX / "study_prosody_hi_bn.json").read_text(encoding="utf-8"))m["project_id"] = "STUDY_T"m["ethics"].update({"status": "approved", "protocol_id": "T-1", "approval_date": "2026-01-01","expiry_date": "2030-01-01", "data_hosting": "test server"})assert c.post("/api/projects?replace=true", json=m, headers=ADM).status_code == 201sid = join(c, "STUDY_T")["speaker_id"]rec = up(c, sid, "hi_question_b", CLEAN, pid="STUDY_T")q = c.get("/api/review/queue?project_id=STUDY_T&reviewer_id=x", headers=ADM).json()item = next(i for i in q if i["recording_id"] == rec["recording_id"])assert item["blind"] and "A question: will he come tomorrow?" in item["perceived_options"]for rv, lab in (("a", "A question: will he come tomorrow?"), ("b", "A question: will he come tomorrow?"),("c", "A statement: he will come tomorrow.")):c.post(f"/api/review/{rec['recording_id']}", headers=ADM, json={"reviewer_id": rv, "verdict": "accept", "perceived": lab})c.post(f"/api/speakers/{sid}/survey", json={"instrument": "sus", "answers": [4, 2, 4, 2, 4, 2, 4, 2, 4, 2]})r = c.get("/api/projects/STUDY_T/study", headers=ADM).json()cell = r["cells"][0]assert cell["judgements"] == 3 and cell["listener_accuracy"] == round(2 / 3, 4) and cell["majority_accuracy"] == 1.0assert cell["sus_mean"] == 75.0 and cell["accepted"] == 1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145import jsonfrom pathlib import Pathimport pytestfrom fastapi.testclient import TestClientfrom conftest import CLEAN, MISREADEX = Path(__file__).resolve().parents[1] / "examples"ADM = {"X-SCQC-Token": "adm"}@pytest.fixture(scope="module")def c():from server.app import appclient = TestClient(app)m = json.loads((EX / "manifest_pilot.json").read_text(encoding="utf-8"))m["project_id"] = "ACC_LEDGER"m["defaults"]["validation"]["human_review"] = "uncertain"m["experiment"]["survey"] = "sus"assert client.post("/api/projects?replace=true", json=m, headers=ADM).status_code == 201return clientdef login(c, u, p):r = c.post("/api/auth/login", json={"username": u, "password": p})return r.json()["token"] if r.status_code == 200 else rdef join(c, pid="ACC_LEDGER"):v = c.get(f"/api/projects/{pid}").json()return c.post("/api/speakers", json={"project_id": pid, "consent_version": v["consent_version"], "language": "hi","consent_sha": v["ethics"]["consent"]["hi"]["sha"], "age_confirmed": True}).json()def up(c, sid, task, data, pid="ACC_LEDGER"):import uuidreturn c.post("/api/recordings", data={"project_id": pid, "task_id": task, "speaker_id": sid,"client_upload_id": uuid.uuid4().hex, "client_meta": "{}"},files={"file": ("a.wav", data, "audio/wav")}).json()def test_setup_login_roles(c):if not c.get("/api/auth/status").json()["has_users"]:body = {"username": "anand", "password": "a-long-password", "role": "admin", "display_name": "Anand"}assert c.post("/api/auth/setup", json=body).status_code == 401 # needs the server tokenassert c.post("/api/auth/setup", json=body, headers=ADM).status_code == 201tok = login(c, "anand", "a-long-password")H = {"X-SCQC-Token": tok}assert c.get("/api/auth/me", headers=H).json()["role"] == "admin"r = c.post("/api/users", headers=H, json={"username": "rev1", "password": "reviewer-pass-1", "role": "reviewer"})assert r.status_code in (201, 409)rt = login(c, "rev1", "reviewer-pass-1")R = {"X-SCQC-Token": rt}assert c.get("/api/users", headers=R).status_code == 401 # reviewers can't manage usersassert c.get("/api/review/queue?project_id=ACC_LEDGER", headers=R).status_code == 200assert login(c, "rev1", "wrong-password").status_code == 401assert c.patch("/api/users/anand", headers=H, json={"disabled": True}).status_code == 409def test_review_identity_and_filters(c):rt = login(c, "rev1", "reviewer-pass-1")R = {"X-SCQC-Token": rt}sid = join(c)["speaker_id"]rec = up(c, sid, "p_001", MISREAD)q = c.get("/api/review/queue?project_id=ACC_LEDGER&filter=high", headers=R).json()item = next(i for i in q if i["recording_id"] == rec["recording_id"])assert item["priority"] == "high" and "flagged" in item["categories"] and item["confidence"]["score"] < 0.8# The audio plays with the session token, and the review is recorded under the logged-in name.assert c.get(item["audio_url"] + f"?token={rt}").status_code == 200v = c.post(f"/api/review/{rec['recording_id']}", headers=R, json={"reviewer_id": "someone-else", "verdict": "accept"})assert v.status_code == 200from server.app import dbassert db.one("SELECT reviewer_id FROM reviews WHERE recording_id=?", (rec["recording_id"],))["reviewer_id"] == "rev1"def test_simulated_payouts_and_wallet(c):sid = join(c)["speaker_id"]r = up(c, sid, "p_002", CLEAN)if r["status"] != "accepted":from server.app import db, _pay, manifestwith db.tx() as cx:cx.execute("UPDATE recordings SET status='accepted' WHERE recording_id=?", (r["recording_id"],))_pay(cx, manifest("ACC_LEDGER"), cx.execute("SELECT * FROM recordings WHERE recording_id=?", (r["recording_id"],)).fetchone())b = c.post("/api/projects/ACC_LEDGER/payouts/batches", headers=ADM).json()assert b["simulated"] and b["n"] >= 1w = c.get(f"/api/speakers/{sid}/wallet").json()assert w["transactions"][0]["status"] == "pending" and w["simulated_payments"]s = c.post(f"/api/payouts/batches/{b['batch_id']}/settle", headers=ADM).json()assert s["status"] == "paid"w = c.get(f"/api/speakers/{sid}/wallet").json()assert w["transactions"][0]["txn_id"].startswith("SIM-UPI-") and w["transactions"][0]["paid_at"]assert c.post(f"/api/payouts/batches/{b['batch_id']}/settle", headers=ADM).status_code == 409lst = c.get("/api/projects/ACC_LEDGER/payouts/batches", headers=ADM).json()assert any(x["batch_id"] == b["batch_id"] and x["status"] == "paid" for x in lst["batches"])def test_survey_profile_playback_dashboard(c):sid = join(c)["speaker_id"]rec = up(c, sid, "p_003", CLEAN)assert c.get(f"/api/speakers/{sid}/recordings/{rec['recording_id']}/audio").status_code == 200assert c.get(f"/api/speakers/spk_other/recordings/{rec['recording_id']}/audio").status_code == 404s = c.post(f"/api/speakers/{sid}/survey", json={"instrument": "sus", "answers": [5, 1, 5, 1, 5, 1, 5, 1, 5, 1]}).json()assert s["score"] == 100.0p = c.get(f"/api/speakers/{sid}/profile").json()assert p["survey_done"] and p["survey"] == "sus" and p["tasks_total"] == 3d = c.get("/api/projects/ACC_LEDGER/dashboard", headers=ADM).json()assert d["contributors"] >= 3 and len(d["daily"]) == 14 and "hi" in d["by_language"]assert d["daily"][-1]["recordings"] >= 1def test_study_report(c):m = json.loads((EX / "study_prosody_hi_bn.json").read_text(encoding="utf-8"))m["project_id"] = "STUDY_T"m["ethics"].update({"status": "approved", "protocol_id": "T-1", "approval_date": "2026-01-01","expiry_date": "2030-01-01", "data_hosting": "test server"})assert c.post("/api/projects?replace=true", json=m, headers=ADM).status_code == 201sid = join(c, "STUDY_T")["speaker_id"]rec = up(c, sid, "hi_question_b", CLEAN, pid="STUDY_T")q = c.get("/api/review/queue?project_id=STUDY_T&reviewer_id=x", headers=ADM).json()item = next(i for i in q if i["recording_id"] == rec["recording_id"])assert item["blind"] and "A question: will he come tomorrow?" in item["perceived_options"]for rv, lab in (("a", "A question: will he come tomorrow?"), ("b", "A question: will he come tomorrow?"),("c", "A statement: he will come tomorrow.")):c.post(f"/api/review/{rec['recording_id']}", headers=ADM, json={"reviewer_id": rv, "verdict": "accept", "perceived": lab})c.post(f"/api/speakers/{sid}/survey", json={"instrument": "sus", "answers": [4, 2, 4, 2, 4, 2, 4, 2, 4, 2]})r = c.get("/api/projects/STUDY_T/study", headers=ADM).json()cell = r["cells"][0]assert cell["judgements"] == 3 and cell["listener_accuracy"] == round(2 / 3, 4) and cell["majority_accuracy"] == 1.0assert cell["sus_mean"] == 75.0 and cell["accepted"] == 1def test_seed_users_idempotent(monkeypatch, tmp_path):from server import auth as AUTHfrom server.db import DBdb = DB(str(tmp_path / "seed.sqlite"))monkeypatch.setenv("SCQC_ADMIN_PASSWORD", "admin-pass-1234")monkeypatch.setenv("SCQC_SEED_USERS", "test_speaker:speaker-pass-1234:participant:Test Speaker")AUTH.init(db)AUTH.init(db) # second boot must not fail or duplicaterows = {r["username"]: dict(r) for r in db.q("SELECT username, role, display_name FROM users")}assert "admin" in rowsassert rows["test_speaker"]["role"] == "participant"assert rows["test_speaker"]["display_name"] == "Test Speaker"
.gitattributesAdded+18
eval_harness/SCQC_Independent_Benchmark.ipynbAdded+59
eval_harness/clips/en_clean_02.wavAdded+3
eval_harness/clips/en_compound_split_06.wavAdded+3
eval_harness/clips/en_idle_trailing_16.wavAdded+3
eval_harness/clips/en_ins_filler_13.wavAdded+3
eval_harness/clips/en_mid_stumble_18.wavAdded+3
eval_harness/clips/en_muted_silence_20.wavAdded
eval_harness/clips/en_numeral_fold_07.wavAdded+3
eval_harness/clips/en_orthographic_04.wavAdded+3
eval_harness/clips/en_skip_initial_10.wavAdded+3
eval_harness/clips/en_sub_semantic_12.wavAdded+3
eval_harness/clips/hi_accent_nukta_03.wavAdded+3
eval_harness/clips/hi_clean_01.wavAdded+3
eval_harness/clips/hi_clipped_19.wavAdded+3
eval_harness/clips/hi_compound_split_05.wavAdded+3
eval_harness/clips/hi_idle_leading_15.wavAdded+3
eval_harness/clips/hi_rushed_short_17.wavAdded
eval_harness/clips/hi_skip_content_08.wavAdded+3
eval_harness/clips/hi_skip_short_final_09.wavAdded+3
eval_harness/clips/hi_sub_semantic_11.wavAdded+3
eval_harness/clips/hi_word_swap_14.wavAdded+3
eval_harness/ground_truth.csvAdded+21
eval_harness/record_clips.pyAdded+80
eval_harness/run_benchmark.pyAdded+102
scqc/align.py+190-172
scqc/asr.py+382-326
scqc/audio.py+286-236
scqc/checks/tasks.py+5-2
scqc/checks/universal.py+172-154
scqc/confidence.py+248-229
scqc/pipeline.py+212-211
scqc/textnorm.py+144-94
scqc/thresholds.py+76-76
server/app.py
server/auth.py+127-92
server/static/participant.js+549-546
tests/test_accounts_ledger.py+145-130