Cotton code
331 lines · 13.8 KB · PythonRaw
#!/usr/bin/env python3"""Cotton Meetings' transcription engine: audio in, heard windows out.    engine.py check [--languages en,hi]             -> {"ok", "models": {...}, "missing": [id...]}    engine.py speech <audio>                        -> {"duration_ms", "speech": [{start_ms, end_ms}]}    engine.py hear <audio> <windows.json|->         -> {"by", "windows": [WindowHeard...], "speakers": n}Every model the step runs is the catalogue's and is read from one folder laid outas `pnpm voice:fetch` lays it (<models>/<model id>/model.json): the catalogue's`vad`, `lid`, `speakers` (segmentation, embedding and their clustering threshold)and per language `languages.<lang>.second`. Nothing about the choice comes fromanywhere else, so `--file` and `--queue` choose alike; `check` names what a runfor these languages needs and what is missing, and a missing model stops the run(it is never swapped for another one).The windows come from the core (cotton_rules::meetings::windows, over `speech`);what comes back goes to cotton_rules::meetings::merge. Rules never live here:this script only runs the open models, through sherpa-onnx, one runtime for all:  * voice activity: Silero VAD (catalogue `silero-vad-v5`), gating what is read;  * speaker separation over the WHOLE recording (pyannote segmentation 3.0 and an    embedding model, fast clustering, number of speakers unknown), so a voice is    one speaker from the first window to the last; each window says its voices    with a one-hot embedding of that recording-wide speaker, which merge matches    exactly. The embedding is the cluster's index, never a voice print, and    nothing about a voice outlives this run;  * language per window (Whisper tiny's language identification, read among the    person's languages, a near language taken for theirs; per speech segment instead, the default once the person has two    or more languages, so a switch between turns is followed);  * the catalogue's second-pass model per detected language    (crates/cotton-core/kits/shell/voice/models.json `languages.<lang>.second`),    Whisper turbo only for a language the catalogue does not name.Each speech segment inside a window becomes one line, split where the speakerchanges. Options (JSON on the windows document or flags): languages (1 to 3,ordered; default the catalogue's), threads (default 4).Models are read from $MEETINGS_MODELS (else $VOICE_MODELS, else~/.cache/cotton-voice/models, where `pnpm voice:fetch` puts them). Nothingtouches the network."""import argparseimport jsonimport osimport sysimport timefrom pathlib import PathHERE = Path(__file__).resolve().parentROOT = HERE.parent.parentsys.path.insert(0, str(ROOT / "scripts" / "voice"))SR = 16000CATALOGUE = ROOT / "crates" / "cotton-core" / "kits" / "shell" / "voice" / "models.json"# Whisper turbo reads a language the catalogue names no model for.UNNAMED = "whisper-large-v3-turbo-int8"def models_dir() -> Path:    for key in ("MEETINGS_MODELS", "VOICE_MODELS"):        if os.environ.get(key):            return Path(os.environ[key])    return Path.home() / ".cache" / "cotton-voice" / "models"def catalogue() -> dict:    return json.loads(CATALOGUE.read_text())def held(model: str) -> bool:    return (models_dir() / model / "model.json").exists()def model_file(model: str, part: str = "model") -> str:    """A held model's file playing `part`, from its laid-out model.json."""    spec = json.loads((models_dir() / model / "model.json").read_text())    return str(models_dir() / model / spec["files"][part])def second_for(cat: dict, lang: str) -> str:    """The model that reads `lang`: the catalogue's second pass, or Whisper turbo for a    language the catalogue does not name. Never another model because one is missing."""    return ((cat.get("languages") or {}).get(lang) or {}).get("second") or UNNAMEDdef needs(languages: list[str]) -> dict:    """Every model a run for these languages reads, by part."""    cat = catalogue()    sp = cat.get("speakers") or {}    out = {"vad": cat["vad"], "segmentation": sp.get("segmentation"), "embedding": sp.get("embedding")}    if len(languages) > 1:        out["lid"] = cat.get("lid")    for lang in languages:        out[f"second:{lang}"] = second_for(cat, lang)    return outdef check(languages: list[str]) -> dict:    models = needs(languages)    missing = sorted({m for m in models.values() if not m or not held(m)}, key=str)    return {"ok": not missing, "models": models, "threshold": (catalogue().get("speakers") or {}).get("threshold"),            "folder": str(models_dir()), "missing": missing}def threshold() -> float:    return float(catalogue()["speakers"]["threshold"])# Spoken languages Whisper often names for one another: Hindustani heard as Urdu# is Hindi to a person who speaks Hindi, and the other way round.CLOSE = {"ur": ("hi",), "hi": ("ur",), "pa": ("hi",), "ne": ("hi",), "mr": ("hi",), "no": ("da", "sv"), "da": ("no", "sv"), "sv": ("no", "da"), "gl": ("es", "pt"), "ca": ("es",)}def read_audio(path: str):    import measure  # scripts/voice/measure.py: one reader for every lane    return measure.read_audio(Path(path))def speech_spans(samples, threads: int):    import sherpa_onnx as so    cfg = so.VadModelConfig()    cfg.silero_vad.model = model_file(catalogue()["vad"])    cfg.silero_vad.min_silence_duration = 0.3    cfg.silero_vad.min_speech_duration = 0.25    cfg.silero_vad.max_speech_duration = 20    cfg.sample_rate = SR    cfg.num_threads = threads    vad = so.VoiceActivityDetector(cfg, buffer_size_in_seconds=int(len(samples) / SR) + 30)    w = cfg.silero_vad.window_size    spans = []    def drain():        while not vad.empty():            start = vad.front.start            spans.append({"start_ms": int(start * 1000 / SR), "end_ms": int((start + len(vad.front.samples)) * 1000 / SR)})            vad.pop()    for i in range(0, len(samples), w):        vad.accept_waveform(samples[i:i + w])        drain()    vad.flush()    drain()    return spansdef diarize(samples, threads: int, threshold: float):    import sherpa_onnx as so    sp = catalogue()["speakers"]    cfg = so.OfflineSpeakerDiarizationConfig(        segmentation=so.OfflineSpeakerSegmentationModelConfig(            pyannote=so.OfflineSpeakerSegmentationPyannoteModelConfig(model=model_file(sp["segmentation"])),            num_threads=threads,        ),        embedding=so.SpeakerEmbeddingExtractorConfig(model=model_file(sp["embedding"]), num_threads=threads),        clustering=so.FastClusteringConfig(num_clusters=-1, threshold=threshold),        min_duration_on=0.3,        min_duration_off=0.5,    )    if not cfg.validate():        raise SystemExit(f"speaker models not found under {models_dir()}")    sdz = so.OfflineSpeakerDiarization(cfg)    result = sdz.process(samples).sort_by_start_time()    return [(int(r.start * 1000), int(r.end * 1000), int(r.speaker)) for r in result]class Engines:    """Recognisers made once each, by catalogue model id."""    def __init__(self, threads: int, languages: list[str]):        self.threads = threads        self.catalogue = catalogue()        self.languages = languages        self.made = {}        self.lid = None    def model_for(self, lang: str) -> str:        model = second_for(self.catalogue, lang)        if not held(model):            raise SystemExit(f"model {model} for {lang} is not under {models_dir()}: pnpm voice:fetch {model}")        return model    def recogniser(self, lang: str):        import measure        model = self.model_for(lang)        key = (model, lang if model == UNNAMED else "")        if key not in self.made:            spec, rec = measure.recogniser(models_dir() / model, lang, self.threads)            self.made[key] = (model, rec)        return self.made[key]    def identify(self, samples) -> str:        """The likeliest of the person's languages for these samples (Whisper tiny's language ID)."""        if len(self.languages) == 1:            return self.languages[0]        import sherpa_onnx as so        if self.lid is None:            lid = self.catalogue["lid"]            cfg = so.SpokenLanguageIdentificationConfig(                whisper=so.SpokenLanguageIdentificationWhisperConfig(encoder=model_file(lid, "encoder"), decoder=model_file(lid, "decoder")),                num_threads=self.threads,            )            self.lid = so.SpokenLanguageIdentification(cfg)        stream = self.lid.create_stream()        stream.accept_waveform(SR, samples[: 30 * SR])        heard = self.lid.compute(stream)        if heard in self.languages:            return heard        for near in CLOSE.get(heard, ()):            if near in self.languages:                return near        return self.languages[0]    def hear(self, samples, lang: str) -> str:        model, rec = self.recogniser(lang)        stream = rec.create_stream()        stream.accept_waveform(SR, samples)        rec.decode_stream(stream)        return stream.result.text.strip()def speaker_at(turns, start: int, end: int) -> int:    best, most = 0, -1    for a, b, s in turns:        shared = min(b, end) - max(a, start)        if shared > most:            best, most = s, shared    return bestdef pieces(turns, start: int, end: int, shortest: int = 600):    """A speech segment cut where the speaker changes; tiny turns join a neighbour."""    cuts = sorted({a for a, _, _ in turns if start < a < end} | {b for _, b, _ in turns if start < b < end})    edges = [start] + cuts + [end]    out = []    for a, b in zip(edges, edges[1:]):        s = speaker_at(turns, a, b)        if out and (out[-1][2] == s or b - a < shortest):            out[-1] = (out[-1][0], b, out[-1][2])        else:            out.append((a, b, s))    if len(out) > 1 and out[0][1] - out[0][0] < shortest:        out[1] = (out[0][0], out[1][1], out[1][2])        out.pop(0)    return outdef hear(audio: str, ask: dict) -> dict:    threads = int(ask.get("threads") or 4)    samples = read_audio(audio)    duration_ms = int(len(samples) * 1000 / SR)    languages = ask.get("languages") or default_languages()    ready = check(languages)    if not ready["ok"]:        raise SystemExit(f"missing models under {ready['folder']}: {' '.join(ready['missing'])} (pnpm voice:fetch them)")    engines = Engines(threads, languages)    t0 = time.time()    speech = ask.get("speech") or speech_spans(samples, threads)    turns = diarize(samples, threads, float(ask.get("threshold") or threshold()))    t_diar = time.time() - t0    count = max([s for _, _, s in turns], default=-1) + 1    # A language per speech segment once the person speaks two or more: measured on the    # mixed meeting, per window put English lines of a Hindi window into Devanagari    # (WER 45 %, 79 % of lines in the right language); per segment 27 %, 95 %.    per_line = ask.get("per_line_language")    per_line = len(languages) > 1 if per_line is None else bool(per_line)    out = []    used = set()    for w in ask["windows"]:        ws, we = int(w["start_ms"]), int(w["end_ms"])        inside = [(max(ws, s["start_ms"]), min(we, s["end_ms"])) for s in speech if s["end_ms"] > ws and s["start_ms"] < we]        inside = [(a, b) for a, b in inside if b - a >= 200]        if not inside:            out.append({"index": w["index"], "start_ms": ws, "end_ms": we, "lines": [], "speakers": []})            continue        window_lang = engines.identify(samples[ws * SR // 1000: we * SR // 1000]) if not per_line else None        lines, voices = [], set()        for a, b in inside:            for pa, pb, s in pieces(turns, a, b) if turns else [(a, b, 0)]:                clip = samples[pa * SR // 1000: pb * SR // 1000]                lang = window_lang or (engines.identify(clip) if pb - pa >= 1500 else (lines[-1]["language"] if lines else languages[0]))                text = engines.hear(clip, lang)                used.add(engines.model_for(lang))                if text:                    lines.append({"speaker": f"spk{s}", "start_ms": pa, "end_ms": pb, "text": text, "language": lang})                    voices.add(s)        heard = {            "index": w["index"], "start_ms": ws, "end_ms": we, "lines": lines,            "speakers": [{"label": f"spk{s}", "embedding": [1.0 if k == s else 0.0 for k in range(max(count, 1))]} for s in sorted(voices)],        }        if window_lang:            heard["language"] = window_lang        out.append(heard)    took = time.time() - t0    return {        "by": "sherpa:" + "+".join(sorted(used)) if used else "sherpa",        "windows": out,        "speakers": count,        "seconds": {"audio": duration_ms / 1000, "diarization": round(t_diar, 2), "total": round(took, 2)},    }def default_languages() -> list[str]:    return [l for l in (catalogue().get("languages") or {})][:1] or ["en"]def main() -> None:    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)    sub = p.add_subparsers(dest="cmd", required=True)    c = sub.add_parser("check")    c.add_argument("--languages", default="")    s = sub.add_parser("speech")    s.add_argument("audio")    s.add_argument("--threads", type=int, default=4)    h = sub.add_parser("hear")    h.add_argument("audio")    h.add_argument("windows", help="JSON: {windows, speech?, languages?, threads?, per_line_language?} or - for stdin")    a = p.parse_args()    if a.cmd == "check":        print(json.dumps(check([l for l in a.languages.split(",") if l] or default_languages())))    elif a.cmd == "speech":        samples = read_audio(a.audio)        print(json.dumps({"duration_ms": int(len(samples) * 1000 / SR), "speech": speech_spans(samples, a.threads)}))    else:        ask = json.loads(sys.stdin.read() if a.windows == "-" else Path(a.windows).read_text())        print(json.dumps(hear(a.audio, ask), ensure_ascii=False))if __name__ == "__main__":    main()