Cotton code
528 lines · 22.8 KB · PythonRaw
#!/usr/bin/env python3"""Measure speech models on a folder of audio, offline, with sherpa-onnx.    pnpm voice:measure <model[,model...]> <set> [--lang xx] [--limit N] [--threads 4] [--live] [--out DIR]<model>  a model id: a folder <models>/<id>/ holding model.json (scripts/voice/fetch.py         writes it), or a path to such a folder. A comma list runs each in turn.<set>    a folder of audio (wav, flac, ogg; m4a/mp3 too where afconvert or ffmpeg is on         the PATH), or a name under <sets>/. References, when there are any, come from         refs.tsv (file<TAB>text) or a .txt beside each audio file. set.json may name         the language ({"language": "te"}). With no references the run is a side by         side: every model's text per file, nothing scored.Nothing here touches the network: models and audio are read from disk only.Roots: VOICE_MODELS (default ~/.cache/cotton-voice/models), VOICE_SETS(default ~/.cache/cotton-voice/sets), VOICE_OUT (default ~/.cache/cotton-voice/runs).Per model and set it writes <out>/<set>/<model>.json (the summary) and .tsv (everyfile's reference and hypothesis), and prints one table row. Word error rate isscored on text normalised the same way for every model (lower case, punctuation andsymbols dropped, Unicode NFKC); Japanese, Chinese and Thai are scored by character.Speed is the real-time factor on --threads threads, pinned to the first --threadsCPUs on Linux, or to VOICE_CPUS (e.g. 4-7) (macOS cannot pin; it says so in thesummary); rtf_cpu is CPU seconds per audio second over the threads, steadier thanwall time on a shared machine. Memory is the peakresident size of the process that ran the model, and its rise over the processbefore the model was loaded. Audio peaking under 0.1 is raised to a 0.5 peak first,as a phone's input levelling would.--live feeds audio in 100 ms chunks as a microphone would, replaying a real-timeclock, and also reports the delay from the start of speech to the first word shownand how often a shown word later changes. A streaming model (online-*) runs as itwould; an offline model re-reads the growing audio every --step ms once voicedetection would have heard speech (Silero VAD onset + 250 ms)."""from __future__ import annotationsimport argparseimport jsonimport osimport platformimport reimport resourceimport shutilimport subprocessimport sysimport tempfileimport timeimport unicodedatafrom pathlib import PathHOME = Path.home() / ".cache" / "cotton-voice"MODELS = Path(os.environ.get("VOICE_MODELS", HOME / "models"))SETS = Path(os.environ.get("VOICE_SETS", HOME / "sets"))OUT = Path(os.environ.get("VOICE_OUT", HOME / "runs"))AUDIO = {".wav", ".flac", ".ogg", ".m4a", ".mp3", ".aac", ".caf", ".aiff", ".opus", ".webm"}CHAR_LANGS = {"ja", "zh", "th", "yue", "ko-char", "my", "km", "lo"}SR = 16000# ---------------------------------------------------------------- textdef normalise(text: str) -> str:    text = unicodedata.normalize("NFKC", text).lower()    # Drop tags some models emit (<|ja|>, [noise], (laughs)).    text = re.sub(r"<\|[^|]*\|>|\[[^\]]*\]", " ", text)    out = []    for ch in text:        cat = unicodedata.category(ch)        if cat[0] in "PS":            out.append(" ")        elif cat[0] == "Z" or ch in "\t\n\r":            out.append(" ")        else:            out.append(ch)    return " ".join("".join(out).split())def units(text: str, lang: str) -> list[str]:    norm = normalise(text)    if lang in CHAR_LANGS:        return [c for c in norm if c != " "]    return norm.split()def edit_distance(ref: list[str], hyp: list[str]) -> int:    prev = list(range(len(hyp) + 1))    for i, r in enumerate(ref, 1):        cur = [i] + [0] * len(hyp)        for j, h in enumerate(hyp, 1):            cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (r != h))        prev = cur    return prev[-1]# ---------------------------------------------------------------- audiodef read_audio(path: Path):    import numpy as np    import soundfile as sf    try:        data, sr = sf.read(str(path), dtype="float32", always_2d=True)    except Exception:        tmp = Path(tempfile.mkdtemp()) / "a.wav"        if shutil.which("afconvert"):            cmd = ["afconvert", "-f", "WAVE", "-d", "LEI16@16000", "-c", "1", str(path), str(tmp)]        elif shutil.which("ffmpeg"):            cmd = ["ffmpeg", "-loglevel", "error", "-y", "-i", str(path), "-ac", "1", "-ar", "16000", str(tmp)]        else:            raise SystemExit(f"cannot read {path}: install ffmpeg (or run on a Mac, which has afconvert)")        subprocess.run(cmd, check=True)        data, sr = sf.read(str(tmp), dtype="float32", always_2d=True)        shutil.rmtree(tmp.parent, ignore_errors=True)    mono = data.mean(axis=1)    if sr != SR:        import soxr        mono = soxr.resample(mono, sr, SR)    # A phone's microphone path levels its input; some test recordings peak near    # 0.006, which models without their own normalisation (zipformer) hear as    # silence. Quiet audio is raised to a 0.5 peak for every model alike.    peak = float(np.abs(mono).max()) if len(mono) else 0.0    if 0 < peak < 0.1:        mono = mono * (0.5 / peak)    return np.ascontiguousarray(mono, dtype=np.float32)def load_set(arg: str, lang: str | None, limit: int | None):    folder = Path(arg)    if not folder.is_dir():        folder = SETS / arg    if not folder.is_dir():        raise SystemExit(f"no set folder {arg} (nor {SETS / arg})")    meta = json.loads((folder / "set.json").read_text()) if (folder / "set.json").exists() else {}    refs: dict[str, str] = {}    if (folder / "refs.tsv").exists():        for line in (folder / "refs.tsv").read_text(encoding="utf-8").splitlines():            if "\t" in line:                name, text = line.split("\t", 1)                refs[name] = text    files = sorted(p for p in folder.rglob("*") if p.suffix.lower() in AUDIO)    items = []    for p in files:        rel = str(p.relative_to(folder))        ref = refs.get(rel)        if ref is None and p.with_suffix(".txt").exists():            ref = p.with_suffix(".txt").read_text(encoding="utf-8").strip()        items.append((rel, p, ref))    if refs:        items = [i for i in items if i[2] is not None] or items    if limit:        items = items[:limit]    return folder.name, folder, lang or meta.get("language"), items# ---------------------------------------------------------------- modelsdef model_dir(arg: str) -> Path:    p = Path(arg)    if (p / "model.json").exists():        return p    if (MODELS / arg / "model.json").exists():        return MODELS / arg    raise SystemExit(f"no model {arg}: expected {MODELS / arg}/model.json (scripts/voice/fetch.py {arg})")def recogniser(mdir: Path, lang: str | None, threads: int):    import sherpa_onnx as so    spec = json.loads((mdir / "model.json").read_text())    kind, f, o = spec["kind"], {k: str(mdir / v) for k, v in spec["files"].items()}, dict(spec.get("options", {}))    lang_opt = (spec.get("language_codes") or {}).get(lang or "", lang or "")    if kind == "online-transducer":        return spec, so.OnlineRecognizer.from_transducer(f["tokens"], f["encoder"], f["decoder"], f["joiner"],                                                         num_threads=threads, **o)    if kind == "online-nemo-ctc":        return spec, so.OnlineRecognizer.from_nemo_ctc(f["tokens"], f["model"], num_threads=threads, **o)    if kind == "online-zipformer2-ctc":        return spec, so.OnlineRecognizer.from_zipformer2_ctc(f["tokens"], f["model"], num_threads=threads, **o)    O = so.OfflineRecognizer    build = {        "offline-transducer": lambda: O.from_transducer(f["encoder"], f["decoder"], f["joiner"], f["tokens"], num_threads=threads, **o),        "offline-nemo-ctc": lambda: O.from_nemo_ctc(f["model"], f["tokens"], num_threads=threads, **o),        "offline-whisper": lambda: O.from_whisper(f["encoder"], f["decoder"], f["tokens"], language=lang_opt, task="transcribe", num_threads=threads, **o),        "offline-sense-voice": lambda: O.from_sense_voice(f["model"], f["tokens"], language=lang_opt, num_threads=threads, **o),        "offline-moonshine": lambda: O.from_moonshine(f["preprocessor"], f["encoder"], f["uncached_decoder"], f["cached_decoder"], f["tokens"], num_threads=threads, **o),        "offline-moonshine-v2": lambda: O.from_moonshine_v2(f["encoder"], f["decoder"], f["tokens"], num_threads=threads, **o),        "offline-omnilingual-ctc": lambda: O.from_omnilingual_asr_ctc(f["model"], f["tokens"], num_threads=threads, **o),        "offline-dolphin-ctc": lambda: O.from_dolphin_ctc(f["model"], f["tokens"], num_threads=threads, **o),        "offline-qwen3-asr": lambda: O.from_qwen3_asr(f["conv_frontend"], f["encoder"], f["decoder"], f["tokenizer"], num_threads=threads, **o),        "offline-canary": lambda: O.from_nemo_canary(f["encoder"], f["decoder"], f["tokens"], src_lang=lang_opt, tgt_lang=lang_opt, num_threads=threads, **o),        "offline-cohere": lambda: O.from_cohere_transcribe(f["encoder"], f["decoder"], f["tokens"], language=lang_opt, use_punct=False, use_itn=False, num_threads=threads, **o),    }    if kind not in build:        raise SystemExit(f"{mdir}: unknown kind {kind}")    return spec, build[kind]()def speech_onset(samples, vad_path: Path | None) -> float:    """Seconds to the first speech, by Silero VAD when its file is at hand, else by energy."""    import numpy as np    if vad_path and vad_path.exists():        import sherpa_onnx as so        cfg = so.VadModelConfig()        cfg.silero_vad.model = str(vad_path)        cfg.silero_vad.min_silence_duration = 0.25        cfg.sample_rate = SR        vad = so.VoiceActivityDetector(cfg, buffer_size_in_seconds=120)        w = cfg.silero_vad.window_size        for i in range(0, len(samples) - w, w):            vad.accept_waveform(samples[i:i + w])            if not vad.empty():                return vad.front.start / SR            if vad.is_speech_detected():                # The segment's start is known only when it closes; walk on to it.                pass        vad.flush()        if not vad.empty():            return vad.front.start / SR    frame = SR // 50    energy = [float(np.sqrt(np.mean(samples[i:i + frame] ** 2))) for i in range(0, len(samples) - frame, frame)]    if not energy:        return 0.0    gate = max(energy) * 0.1    for k, e in enumerate(energy):        if e > gate:            return k * frame / SR    return 0.0def segments(samples, vad_path: Path | None, longest: float):    """Audio longer than `longest` seconds cut on its pauses (Silero VAD), for models with a window."""    if len(samples) <= longest * SR or not (vad_path and vad_path.exists()):        return [samples]    import numpy as np    import sherpa_onnx as so    cfg = so.VadModelConfig()    cfg.silero_vad.model = str(vad_path)    cfg.silero_vad.max_speech_duration = longest    cfg.sample_rate = SR    vad = so.VoiceActivityDetector(cfg, buffer_size_in_seconds=int(len(samples) / SR) + 10)    w = cfg.silero_vad.window_size    out = []    for i in range(0, len(samples), w):        vad.accept_waveform(samples[i:i + w])        while not vad.empty():            out.append(np.array(vad.front.samples, dtype=np.float32))            vad.pop()    vad.flush()    while not vad.empty():        out.append(np.array(vad.front.samples, dtype=np.float32))        vad.pop()    return out or [samples]def cpu_s() -> float:    r = resource.getrusage(resource.RUSAGE_SELF)    return r.ru_utime + r.ru_stimedef stream(spec, rec, lang):    """A stream with the model's per-stream options ({lang} filled in), e.g. Nemotron's language."""    s = rec.create_stream()    for k, v in (spec.get("stream_options") or {}).items():        s.set_option(k, v.replace("{lang}", lang or "auto"))    return sdef decode_offline(rec, samples):    s = rec.create_stream()    s.accept_waveform(SR, samples)    rec.decode_stream(s)    return s.result.textdef run_live(spec, rec, samples, lang, step_ms, vad_path):    """Replays a microphone: returns (final text, first word ms from speech onset, words shown, words changed)."""    import numpy as np    chunk = SR // 10    online = spec["kind"].startswith("online-")    clock = 0.0           # simulated wall time, seconds    shown: list[str] = []    changed = 0    first = None    onset = speech_onset(samples, vad_path)    tail = np.zeros(int(0.8 * SR), dtype=np.float32)    if online:        s = stream(spec, rec, lang)    next_decode = step_ms / 1000.0    pos = 0    audio = np.concatenate([samples, tail])    while pos < len(audio):        piece = audio[pos:pos + chunk]        pos += len(piece)        arrival = pos / SR        clock = max(clock, arrival)        t0 = time.perf_counter()        if online:            s.accept_waveform(SR, piece)            if pos >= len(audio):                s.input_finished()            while rec.is_ready(s):                rec.decode_stream(s)            text = rec.get_result(s)        else:            # An offline model runs behind voice detection on a phone: nothing is            # read before the detector has heard speech (its onset plus ~250 ms).            if (arrival + 1e-9 < next_decode or arrival < onset + 0.25) and pos < len(audio):                continue            next_decode = arrival + step_ms / 1000.0            text = decode_offline(rec, audio[:pos])        clock += time.perf_counter() - t0        words = units(text, lang or "")        k = 0        while k < min(len(words), len(shown)) and words[k] == shown[k]:            k += 1        changed += len(shown) - k        if words and first is None:            first = (clock - onset) * 1000.0        shown = words    final = rec.get_result(s) if online else decode_offline(rec, samples)    return final, first, max(len(units(final, lang or "")), 1), changed# ---------------------------------------------------------------- one model, one set (a child process)def worker(args) -> dict:    if hasattr(os, "sched_setaffinity"):        cpus = cpu_list(os.environ.get("VOICE_CPUS")) or sorted(os.sched_getaffinity(0))[: args.threads]        os.sched_setaffinity(0, set(cpus))        pinned = f"pinned to CPUs {cpus}"    else:        pinned = "not pinned (this OS cannot)"    import numpy as np  # noqa: F401  (loaded before the baseline)    import sherpa_onnx  # noqa: F401    set_name, folder, lang, items = load_set(args.set, args.lang, args.limit)    mdir = model_dir(args.model)    vad_path = next((p for p in [MODELS / "silero-vad-v5" / "silero_vad.onnx", mdir.parent / "silero-vad-v5" / "silero_vad.onnx"] if p.exists()), None)    base = rss_mb()    t0 = time.perf_counter()    spec, rec = recogniser(mdir, lang, args.threads)    load_s = time.perf_counter() - t0    after_load = rss_mb()    longest = float(spec.get("longest_s", 28.0))    rows, audio_s, compute_s, cpu_total = [], 0.0, 0.0, 0.0    errs = refs_n = cerr = cref = 0    firsts, shown_n, changed_n = [], 0, 0    for rel, path, ref in items:        samples = read_audio(path)        dur = len(samples) / SR        audio_s += dur        t, c = time.perf_counter(), cpu_s()        if spec["kind"].startswith("online-"):            s = stream(spec, rec, lang)            s.accept_waveform(SR, samples)            import numpy as np            s.accept_waveform(SR, np.zeros(int(0.8 * SR), dtype=np.float32))            s.input_finished()            while rec.is_ready(s):                rec.decode_stream(s)            hyp = rec.get_result(s)        else:            hyp = " ".join(decode_offline(rec, seg) for seg in segments(samples, vad_path, longest))        compute_s += time.perf_counter() - t        cpu_total += cpu_s() - c        row = {"file": rel, "seconds": round(dur, 2), "ref": ref, "hyp": hyp.strip()}        if args.live:            _, first, shown, changed = run_live(spec, rec, samples, lang, args.step, vad_path)            row.update(first_word_ms=None if first is None else round(first), changed=changed)            if first is not None:                firsts.append(first)            shown_n += shown            changed_n += changed        if ref is not None:            r, h = units(ref, lang or ""), units(hyp, lang or "")            e = edit_distance(r, h)            rc, hc = [c for c in normalise(ref) if c != " "], [c for c in normalise(hyp) if c != " "]            ce = edit_distance(rc, hc)            errs, refs_n, cerr, cref = errs + e, refs_n + len(r), cerr + ce, cref + len(rc)            row.update(errors=e, ref_units=len(r))        rows.append(row)        if args.verbose:            print(f"  {rel}: {row['hyp'][:80]}", file=sys.stderr)    files_bytes = sum(f["bytes"] for f in spec.get("file_list", [])) or sum(        (mdir / v).stat().st_size for v in spec["files"].values() if (mdir / v).is_file())    summary = {        "model": spec.get("id", mdir.name), "set": set_name, "language": lang, "files": len(rows),        "audio_s": round(audio_s, 1),        "metric": ("cer" if (lang or "") in CHAR_LANGS else "wer") if refs_n else None,        "error_rate": round(errs / refs_n, 4) if refs_n else None,        "cer": round(cerr / cref, 4) if cref else None,        "rtf": round(compute_s / audio_s, 4) if audio_s else None,        # CPU seconds per audio second over the threads: the real-time factor the        # model would have on that many free cores, steadier than wall time on a        # shared machine.        "rtf_cpu": round(cpu_total / audio_s / args.threads, 4) if audio_s else None,        "load_avg": round(os.getloadavg()[0], 1) if hasattr(os, "getloadavg") else None,        "threads": args.threads, "cpu": cpu_name(), "pinning": pinned,        "load_s": round(load_s, 2), "rss_peak_mb": round(peak_mb()), "rss_model_mb": round(after_load - base),        "bytes": files_bytes, "kind": spec["kind"], "quantisation": spec.get("quantisation"),    }    if args.live:        firsts.sort()        summary.update(            live_step_ms=None if spec["kind"].startswith("online-") else args.step,            first_word_ms_median=round(firsts[len(firsts) // 2]) if firsts else None,            first_word_ms_p90=round(firsts[int(len(firsts) * 0.9)]) if firsts else None,            rewrite_rate=round(changed_n / shown_n, 4) if shown_n else None,        )    out = Path(args.out) / set_name    out.mkdir(parents=True, exist_ok=True)    stem = summary["model"] + (".live" if args.live else "")    (out / f"{stem}.json").write_text(json.dumps(summary, indent=2, ensure_ascii=False))    with open(out / f"{stem}.tsv", "w", encoding="utf-8") as fh:        fh.write("file\tseconds\terrors\tref_units\tfirst_word_ms\tref\thyp\n")        for r in rows:            fh.write("\t".join(str(r.get(k, "")) if r.get(k) is not None else "" for k in                               ["file", "seconds", "errors", "ref_units", "first_word_ms", "ref", "hyp"]) + "\n")    return summarydef cpu_list(spec: str | None) -> list[int]:    """VOICE_CPUS="4-7" or "0,2,4,6": the CPUs to pin to, so two runs can share a machine."""    out: list[int] = []    for part in (spec or "").split(","):        if "-" in part:            a, b = part.split("-")            out += range(int(a), int(b) + 1)        elif part.strip():            out.append(int(part))    return outdef rss_mb() -> float:    try:        for line in open("/proc/self/status"):            if line.startswith("VmRSS:"):                return int(line.split()[1]) / 1024    except OSError:        pass    return peak_mb()def peak_mb() -> float:    peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss    return peak / (1024 * 1024) if platform.system() == "Darwin" else peak / 1024def cpu_name() -> str:    try:        for line in open("/proc/cpuinfo"):            if line.startswith("model name"):                return line.split(":", 1)[1].strip()    except OSError:        pass    try:        return subprocess.run(["sysctl", "-n", "machdep.cpu.brand_string"], capture_output=True, text=True).stdout.strip()    except OSError:        return platform.processor()# ---------------------------------------------------------------- maindef main() -> None:    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)    ap.add_argument("model")    ap.add_argument("set")    ap.add_argument("--lang")    ap.add_argument("--limit", type=int)    ap.add_argument("--threads", type=int, default=4)    ap.add_argument("--live", action="store_true")    ap.add_argument("--step", type=int, default=500, help="ms between re-reads when an offline model runs live")    ap.add_argument("--out", default=str(OUT))    ap.add_argument("--verbose", action="store_true")    ap.add_argument("--worker", action="store_true", help=argparse.SUPPRESS)    args = ap.parse_args()    if args.worker:        print(json.dumps(worker(args), ensure_ascii=False))        return    models = [m for m in args.model.split(",") if m]    results = []    for m in models:        cmd = [sys.executable, "-I", __file__, m, args.set, "--threads", str(args.threads), "--out", args.out,               "--step", str(args.step), "--worker"]        for flag, val in (("--lang", args.lang), ("--limit", args.limit)):            if val:                cmd += [flag, str(val)]        if args.live:            cmd.append("--live")        if args.verbose:            cmd.append("--verbose")        p = subprocess.run(cmd, capture_output=True, text=True)        if p.returncode != 0:            print(f"{m}: failed\n{p.stderr[-2000:]}", file=sys.stderr)            continue        s = json.loads(p.stdout.strip().splitlines()[-1])        results.append(s)        rate = f"{s['metric']} {s['error_rate'] * 100:.1f}%" if s["error_rate"] is not None else "unscored"        live = (f"  first word {s['first_word_ms_median']} ms (p90 {s['first_word_ms_p90']})  rewrites {s['rewrite_rate'] * 100:.1f}%"                if args.live and s.get("rewrite_rate") is not None else "")        print(f"{s['model']:<48} {s['set']:<14} {rate:<12} rtf {s['rtf']:<7} cpu-rtf {s['rtf_cpu']:<7} rss {s['rss_peak_mb']} MB  "              f"{s['bytes'] / 1e6:.0f} MB{live}", flush=True)    if results and all(r["error_rate"] is None for r in results):        side_by_side(args, results)def side_by_side(args, results) -> None:    out = Path(args.out) / results[0]["set"]    texts = {}    for r in results:        stem = r["model"] + (".live" if args.live else "")        for line in (out / f"{stem}.tsv").read_text(encoding="utf-8").splitlines()[1:]:            cols = line.split("\t")            texts.setdefault(cols[0], {})[r["model"]] = cols[-1]    md = [f"# Side by side: {results[0]['set']}", ""]    for f, by in texts.items():        md += [f"## {f}", ""] + [f"- **{m}**: {t}" for m, t in by.items()] + [""]    (out / "side-by-side.md").write_text("\n".join(md), encoding="utf-8")    print(f"side by side: {out / 'side-by-side.md'}")if __name__ == "__main__":    main()