"""Shared helpers: paths, models, decode settings, normaliser, WER, thermal logging.""" import json import os import subprocess import time from pathlib import Path HERE = Path(__file__).resolve().parent DATA = HERE / "data" RAW = HERE / "raw" LOGS = HERE / "logs" # Model order defines the labels A, B, C used by the rotation schedule. MODELS = { "large-v3": "mlx-community/whisper-large-v3-mlx", "turbo": "mlx-community/whisper-large-v3-turbo", "tiny": "mlx-community/whisper-tiny-mlx", } ROTATIONS = [["large-v3", "turbo", "tiny"], ["turbo", "tiny", "large-v3"], ["tiny", "large-v3", "turbo"]] # Pinned decode settings shared by every model (mlx-whisper 0.4.3 defaults written out explicitly). BASE_DECODE = dict( language="en", task="transcribe", fp16=True, temperature=(0.0, 0.2, 0.4, 0.6, 0.8, 1.0), compression_ratio_threshold=2.4, logprob_threshold=-1.0, no_speech_threshold=0.6, condition_on_previous_text=True, initial_prompt=None, verbose=None, ) # Hallucination-test settings. "default" == mlx-whisper defaults (gates on). Because the # spec's "thresholds explicitly applied" variant is identical to the defaults, we instead run # a "gates_off" variant (no_speech/logprob gates disabled) to show what the gates are worth. HALLUC_SETTINGS = { "default": {}, "gates_off": dict(no_speech_threshold=None, logprob_threshold=None), "no_condition": dict(condition_on_previous_text=False), } SEED = 20261103 def model_path(repo: str) -> str: """Local model dir. Prefers ./models/ (snapshot_download(local_dir=...)), else the HF cache. Never touches the network.""" local = HERE / "models" / repo.split("/")[-1] if (local / "config.json").exists() and any(local.glob("weights.*")): return str(local) from huggingface_hub import snapshot_download p = snapshot_download(repo, local_files_only=True) if not any(Path(p).glob("weights.*")): raise FileNotFoundError(f"{repo}: no weights file in {p}") return p def rotation(i: int): return ROTATIONS[i % 3] def get_normalizer(): # whisper.normalizers is the reference normaliser used in the Whisper paper. from whisper.normalizers import EnglishTextNormalizer return EnglishTextNormalizer() def word_errors(ref_norm: str, hyp_norm: str): """Return (errors, n_ref_words, subs, dels, ins, trailing_insertions, trailing_text).""" import jiwer ref_words = ref_norm.split() hyp_words = hyp_norm.split() if not ref_words: return len(hyp_words), 0, 0, 0, len(hyp_words), len(hyp_words), " ".join(hyp_words) if not hyp_words: return len(ref_words), len(ref_words), 0, len(ref_words), 0, 0, "" out = jiwer.process_words(ref_norm, hyp_norm) s, d, i = out.substitutions, out.deletions, out.insertions # Insertions after the last reference word = invented trailing text. trailing, trailing_words = 0, [] chunks = out.alignments[0] if chunks and chunks[-1].type == "insert" and chunks[-1].ref_end_idx == len(ref_words): c = chunks[-1] trailing = c.hyp_end_idx - c.hyp_start_idx trailing_words = hyp_words[c.hyp_start_idx : c.hyp_end_idx] return s + d + i, len(ref_words), s, d, i, trailing, " ".join(trailing_words) def sh(cmd, timeout=30): try: return subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout).stdout.strip() except Exception as e: # noqa: BLE001 return f"ERROR: {e}" def log_thermal(tag: str): """Append `pmset -g therm` to logs/thermal.jsonl (called before/after each block).""" LOGS.mkdir(exist_ok=True) rec = {"t": time.time(), "tag": tag, "therm": sh("pmset -g therm"), "batt": sh("pmset -g batt | head -1")} with open(LOGS / "thermal.jsonl", "a") as f: f.write(json.dumps(rec) + "\n") return rec def deadline_left(deadline: float) -> float: return deadline - time.time() if deadline else float("inf") def append_csv(path: Path, row: dict): """Append one row to a raw CSV (header written on first row). Flushed per row so partial blocks survive a deadline cut-off.""" import csv path.parent.mkdir(parents=True, exist_ok=True) if path.exists(): with open(path, newline="") as f: header = next(csv.reader(f), []) missing = [k for k in row if k not in header] if missing: # e.g. first row was a failure row with fewer columns: widen the header old = read_csv(path) header = header + missing with open(path, "w", newline="") as f: w = csv.DictWriter(f, fieldnames=header, restval="") w.writeheader() w.writerows(old) with open(path, "a", newline="") as f: csv.DictWriter(f, fieldnames=header, restval="").writerow(row) else: with open(path, "w", newline="") as f: w = csv.DictWriter(f, fieldnames=list(row.keys())) w.writeheader() w.writerow(row) def read_csv(path: Path): import csv if not path.exists(): return [] with open(path, newline="") as f: return list(csv.DictReader(f)) def env_flag(name): return os.environ.get(name, "") not in ("", "0")