"""Shared helpers for the Entity Transcription Benchmark harness. Dataset loading, schema resolution, tier filtering and text normalization. Kept dependency-light on purpose: datasets + soundfile + jiwer. """ from __future__ import annotations import io import json import os import re import sys from dataclasses import dataclass, asdict from typing import Any, Iterable DEFAULT_DATASET = "modulate/entity-transcription-benchmark" DEFAULT_SPLIT = "test" # Candidate column names, in priority order. Resolution is printed at startup # and can always be overridden from the CLI. CANDIDATES = { "audio": ["audio", "wav", "speech"], "reference": ["text", "transcript", "transcription", "reference", "sentence", "normalized_text"], "entities": ["entities", "named_entities", "spans"], "entity_types": ["entity_types", "types", "labels", "entity_labels"], # entity_tiers is a PER-SPAN parallel array in this dataset, not a clip-level label "tier": ["entity_tiers", "tier", "difficulty", "difficulty_tier", "tier_label"], "clip_id": ["id", "clip_id", "clip", "audio_id", "file", "filename", "utt_id"], "subset": ["subset", "source", "corpus", "dataset", "origin", "source_dataset"], } @dataclass class Schema: audio: str reference: str entities: str entity_types: str | None tier: str | None clip_id: str | None subset: str | None def pretty(self) -> str: return "\n".join(f" {k:<13} -> {v}" for k, v in asdict(self).items()) def resolve_schema(columns: Iterable[str], overrides: dict[str, str] | None = None) -> Schema: cols = list(columns) lower = {c.lower(): c for c in cols} overrides = {k: v for k, v in (overrides or {}).items() if v} picked: dict[str, str | None] = {} for field, options in CANDIDATES.items(): if field in overrides: if overrides[field] not in cols: raise SystemExit(f"--{field}-column '{overrides[field]}' not in dataset: {cols}") picked[field] = overrides[field] continue picked[field] = next((lower[o] for o in options if o in lower), None) for required in ("audio", "entities"): if picked[required] is None: raise SystemExit( f"Could not find a '{required}' column. Columns are: {cols}\n" f"Pass --{required}-column explicitly." ) if picked["reference"] is None: # WER is optional; entity accuracy is not. picked["reference"] = "" return Schema(**picked) # type: ignore[arg-type] def load_bench( dataset: str = DEFAULT_DATASET, split: str = DEFAULT_SPLIT, revision: str | None = None, local_path: str | None = None, ): from datasets import load_dataset, load_from_disk if local_path: ds = load_from_disk(local_path) if hasattr(ds, "keys"): # DatasetDict ds = ds[split] if split in ds else ds[list(ds.keys())[0]] return ds return load_dataset(dataset, split=split, revision=revision) def parse_list_field(value: Any) -> list[str]: """Annotations ship as parallel JSON arrays; tolerate a stringified array.""" if value is None: return [] if isinstance(value, list): return [str(v) for v in value] if isinstance(value, str): value = value.strip() if not value: return [] if value.startswith("["): try: return [str(v) for v in json.loads(value)] except json.JSONDecodeError: pass return [value] return [str(value)] def span_tiers(row: dict, schema: Schema, n_spans: int) -> list[str | None]: """Tier labels aligned to the entity list. This dataset stores tiers as a per-span parallel array (entity_tiers). A clip-level scalar column is also supported: it is broadcast to every span. """ if not schema.tier: return [None] * n_spans values = parse_list_field(row[schema.tier]) if len(values) == 1 and n_spans != 1: values = values * n_spans values = [v.strip().upper() if isinstance(v, str) else v for v in values] if len(values) < n_spans: values += [None] * (n_spans - len(values)) return values[:n_spans] def row_has_tier(row: dict, schema: Schema, tier: str | None) -> bool: """True when the clip contains at least one span of the requested tier.""" if not tier or tier.lower() == "all": return True if schema.tier is None: raise SystemExit( "Requested a tier filter but no tier column was found. " "Pass --tier all, or --tier-column ." ) entities = parse_list_field(row[schema.entities]) want = tier.strip().upper() return any(t == want for t in span_tiers(row, schema, len(entities))) def row_id(row: dict, schema: Schema, index: int) -> str: if schema.clip_id and row.get(schema.clip_id) not in (None, ""): return str(row[schema.clip_id]) audio = row.get(schema.audio) if isinstance(audio, dict) and audio.get("path"): return os.path.basename(str(audio["path"])) return f"row_{index:05d}" def undecode_audio(ds, schema: Schema): """Ask datasets for the raw encoded bytes instead of a decoded waveform. Two reasons: every provider then receives byte-identical audio (no re-encode in the middle of the benchmark), and it drops the torchcodec / torchaudio dependency that datasets>=4 pulls in for decoding. """ try: from datasets import Audio return ds.cast_column(schema.audio, Audio(decode=False)) except Exception as exc: # noqa: BLE001 -- fall back to whatever decoding is available eprint(f" (note: could not disable audio decoding: {exc})") return ds def audio_to_wav_bytes(audio) -> tuple[bytes, int]: """Normalize whatever the audio column yields into encoded bytes.""" if isinstance(audio, (bytes, bytearray)): return bytes(audio), 0 if isinstance(audio, dict): if audio.get("bytes"): return bytes(audio["bytes"]), int(audio.get("sampling_rate") or 0) if audio.get("array") is not None: import soundfile as sf buf = io.BytesIO() sf.write(buf, audio["array"], int(audio["sampling_rate"]), format="WAV", subtype="PCM_16") return buf.getvalue(), int(audio["sampling_rate"]) if audio.get("path"): with open(audio["path"], "rb") as fh: return fh.read(), int(audio.get("sampling_rate") or 0) # datasets>=4 may hand back a torchcodec AudioDecoder if hasattr(audio, "get_all_samples"): import numpy as np import soundfile as sf samples = audio.get_all_samples() array = np.asarray(samples.data).squeeze() rate = int(samples.sample_rate) buf = io.BytesIO() sf.write(buf, array.T if array.ndim > 1 else array, rate, format="WAV", subtype="PCM_16") return buf.getvalue(), rate raise TypeError(f"unsupported audio value of type {type(audio)}") # -------------------------------------------------------------------------- # Text normalization for the WER column. The entity matcher does its own # normalization -- do not apply these to entity matching. # -------------------------------------------------------------------------- _PUNCT = re.compile(r"[^\w\s']", flags=re.UNICODE) _WS = re.compile(r"\s+") def normalize_basic(text: str) -> str: text = text.lower().replace("\u2019", "'") text = _PUNCT.sub(" ", text) return _WS.sub(" ", text).strip() def get_normalizer(name: str): name = (name or "basic").lower() if name == "none": return lambda t: t.strip() if name == "basic": return normalize_basic if name in ("whisper", "whisper_english", "english"): try: from whisper_normalizer.english import EnglishTextNormalizer # type: ignore except ImportError: try: from transformers.models.whisper.english_normalizer import ( # type: ignore EnglishTextNormalizer, ) except ImportError: raise SystemExit( "whisper normalizer unavailable. `pip install whisper_normalizer` " "or use --wer-normalizer basic." ) # whisper_normalizer's class takes no arguments; the transformers port # takes a spelling-correction mapping. Support both. try: norm = EnglishTextNormalizer() except TypeError: norm = EnglishTextNormalizer({}) return lambda t: norm(t) raise SystemExit(f"Unknown normalizer: {name}") def eprint(*args): print(*args, file=sys.stderr, flush=True)