File size: 8,803 Bytes
0041cfd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb1b7b7
 
 
 
 
 
0041cfd
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
"""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 <name>."
        )
    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)