pltobing commited on
Commit
fab9ab0
·
1 Parent(s): 61fc10e

feat(mfa): add forced alignment backend

Browse files

- Add typed MFA configuration, corpus materialization, subprocess execution, and TextGrid parsing
- Preserve authoritative transcripts with reversible MFA-specific normalization and lexical mapping
- Add strict handling for OOVs, silence intervals, malformed output, and timestamp validation
- Keep MFA isolated in its dedicated Conda environment and behind the shared backend protocol
- Add deterministic unit, architecture, coverage, and opt-in real integration tests
- Record the real five-row MFA evaluation with 5/5 successes and 0.0162 s first-word-end MAE
- Document runtime, model, dictionary, G2P, provenance, and Stage 4 readiness

README.md CHANGED
@@ -8,10 +8,11 @@ A library-first, backend-neutral framework for locating the words of an authorit
8
  English transcript in WAV audio. The framework preserves the input transcript and
9
  metadata exactly; it never substitutes an independently recognized ASR transcript.
10
 
11
- ## Stage 2 scope
12
 
13
  The current implementation provides the accepted shared infrastructure plus an
14
- NVIDIA NeMo Forced Aligner (NFA) backend:
 
15
 
16
  - immutable alignment requests, word results, failures, diagnostics, and provenance;
17
  - Unicode lexical extraction, reversible text plans, exact monotonic reconciliation,
@@ -23,10 +24,14 @@ NVIDIA NeMo Forced Aligner (NFA) backend:
23
  - an immutable lazy backend registry and thin CLI composition adapters;
24
  - exact reference-text NeMo JSONL, pinned subprocess invocation, word CTM parsing,
25
  native diagnostics/provenance, and optional native-artifact retention.
 
 
 
26
 
27
- The NeMo adapter invokes an isolated runtime and never imports NeMo or Torch in the
28
- parent process. MFA and WhisperX remain unimplemented at this stage. Their registry
29
- entries stay lazy, so missing optional runtimes do not break neutral imports or NeMo.
 
30
 
31
  NFA is pinned to NeMo Speech 3.0.0 source revision
32
  `fd6a877539710e2b98f28c43272ff81312f83417`. The selected English model is
@@ -36,6 +41,12 @@ the authoritative transcript as manifest `text`, forces
36
  `align_using_pred_text=false`, requests CTM output, and leaves
37
  `minimum_timestamp_duration=0` so timestamps are not enlarged.
38
 
 
 
 
 
 
 
39
  ## Public Python API
40
 
41
  The main reusable calls are:
@@ -99,6 +110,36 @@ configuration, and command identities. Set `artifact_policy="always"` and a
99
  `retention_root` to preserve input/output manifests and CTMs; retained paths also flow
100
  into benchmark JSON and Markdown reports.
101
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  ### Complete fake-backend example
103
 
104
  This minimal example creates synthetic metadata/audio and annotates it entirely through
@@ -176,19 +217,19 @@ python -m speech_text_data_aligners.cli.main benchmark --help
176
  ```
177
 
178
  The command adapters parse arguments, lazily construct a selected backend, and call the
179
- same application services shown above. A NeMo composition uses its typed configuration
180
  through JSON, for example:
181
 
182
  ```bash
183
  PYTHONPATH=src python -m speech_text_data_aligners.cli.main annotate \
184
- metadata.csv wavs annotated.csv --backend nemo \
185
- --backend-config-json '{"align_script":"/opt/nemo-speech/tools/nemo_forced_aligner/align.py","python_executable":"/opt/nemo-speech/.venv/bin/python","model_path":"/opt/nemo-models/stt_en_fastconformer_hybrid_large_pc.nemo","transcribe_device":"cuda","viterbi_device":"cuda"}'
186
  ```
187
 
188
- See [the Stage 2 report](docs/STAGE_2_REPORT.md) for the exact pinned installation,
189
- model materialization, real smoke-test, and five-row benchmark commands. The empirical
190
- run is currently marked blocked because this host has no NeMo runtime, checkpoint, or
191
- GPU; no timestamps or accuracy metrics have been fabricated.
192
 
193
  ## Deterministic development gates
194
 
@@ -207,4 +248,4 @@ PYTHONPATH=src lint-imports
207
  ```
208
 
209
  Ordinary tests use no network, GPU, model downloads, or external aligner runtimes.
210
- See `docs/STAGE_2_REPORT.md` for the NeMo module/test map and acceptance evidence.
 
8
  English transcript in WAV audio. The framework preserves the input transcript and
9
  metadata exactly; it never substitutes an independently recognized ASR transcript.
10
 
11
+ ## Stage 3 scope
12
 
13
  The current implementation provides the accepted shared infrastructure plus an
14
+ NVIDIA NeMo Forced Aligner (NFA) backend and a Montreal Forced Aligner (MFA) 3.x
15
+ backend:
16
 
17
  - immutable alignment requests, word results, failures, diagnostics, and provenance;
18
  - Unicode lexical extraction, reversible text plans, exact monotonic reconciliation,
 
24
  - an immutable lazy backend registry and thin CLI composition adapters;
25
  - exact reference-text NeMo JSONL, pinned subprocess invocation, word CTM parsing,
26
  native diagnostics/provenance, and optional native-artifact retention.
27
+ - deterministic copied MFA corpora, reversible MFA text normalization, a pinned
28
+ `align_hf` invocation, strict word-tier TextGrid parsing, OOV/G2P policy,
29
+ diagnostics/provenance, and optional native-artifact retention.
30
 
31
+ Both adapters invoke isolated runtimes and do not import heavyweight aligner packages
32
+ in the parent process. WhisperX remains unimplemented at this stage. Registry entries
33
+ stay lazy, so missing optional runtimes do not break neutral imports or another
34
+ backend.
35
 
36
  NFA is pinned to NeMo Speech 3.0.0 source revision
37
  `fd6a877539710e2b98f28c43272ff81312f83417`. The selected English model is
 
41
  `align_using_pred_text=false`, requests CTM output, and leaves
42
  `minimum_timestamp_duration=0` so timestamps are not enlarged.
43
 
44
+ MFA is pinned to `montreal-forced-aligner=3.4.2` in a dedicated Conda environment.
45
+ The adapter uses the commit-qualified `MontrealCorpusTools/english_mfa` Hugging Face
46
+ model with its `english_us_mfa` dictionary and bundled G2P, copies WAVs into a
47
+ temporary corpus, and invokes `mfa align_hf` with long TextGrid output. Source WAVs,
48
+ CSV cells, and authoritative transcripts are never modified.
49
+
50
  ## Public Python API
51
 
52
  The main reusable calls are:
 
110
  `retention_root` to preserve input/output manifests and CTMs; retained paths also flow
111
  into benchmark JSON and Markdown reports.
112
 
113
+ ### Direct MFA backend use
114
+
115
+ MFA defaults to the dedicated Conda environment named `speech-aligners-mfa`:
116
+
117
+ ```python
118
+ from pathlib import Path
119
+
120
+ from speech_text_data_aligners.backends.mfa.backend import MfaBackend
121
+ from speech_text_data_aligners.backends.mfa.config import MfaConfig
122
+ from speech_text_data_aligners.data.audio import make_alignment_request
123
+
124
+ backend = MfaBackend(
125
+ MfaConfig(
126
+ artifact_policy="on_failure",
127
+ retention_root=Path("mfa-failures"),
128
+ )
129
+ )
130
+ request = make_alignment_request(
131
+ request_id="example",
132
+ audio_path=Path("example.wav"),
133
+ transcript="The authoritative transcript.",
134
+ )
135
+ result = backend.align(request)
136
+ ```
137
+
138
+ Use `environment_prefix=Path(...)` with `environment_name=None` when selecting an
139
+ explicit Conda prefix. The backend probes exact MFA/Kaldi/Kalpy/OpenFst/Python builds
140
+ before alignment and records them along with model, dictionary, G2P, command, label,
141
+ and TextGrid hashes.
142
+
143
  ### Complete fake-backend example
144
 
145
  This minimal example creates synthetic metadata/audio and annotates it entirely through
 
217
  ```
218
 
219
  The command adapters parse arguments, lazily construct a selected backend, and call the
220
+ same application services shown above. An MFA composition uses its typed configuration
221
  through JSON, for example:
222
 
223
  ```bash
224
  PYTHONPATH=src python -m speech_text_data_aligners.cli.main annotate \
225
+ metadata.csv wavs annotated.csv --backend mfa \
226
+ --backend-config-json '{"environment_name":"speech-aligners-mfa","artifact_policy":"on_failure","retention_root":"mfa-failures"}'
227
  ```
228
 
229
+ See [the Stage 3 report](docs/STAGE_3_REPORT.md) for the verified dedicated environment,
230
+ exact model revision, normalization/mapping policy, real smoke test, five-row benchmark,
231
+ architecture evidence, and module-to-test-to-coverage mapping. The prior NeMo work is
232
+ documented in [the Stage 2 report](docs/STAGE_2_REPORT.md).
233
 
234
  ## Deterministic development gates
235
 
 
248
  ```
249
 
250
  Ordinary tests use no network, GPU, model downloads, or external aligner runtimes.
251
+ The real MFA smoke test is explicitly opt-in; see `docs/STAGE_3_REPORT.md`.
docs/STAGE_3_REPORT.md ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Stage 3 report: Montreal Forced Aligner backend
2
+
3
+ Status: **implementation, deterministic acceptance, dedicated-environment verification,
4
+ and real five-row MFA evaluation complete.** No WhisperX implementation was started.
5
+
6
+ ## Backend choice and authoritative workflow
7
+
8
+ The adapter uses Montreal Forced Aligner 3.4.2's `align_hf` workflow. The selected
9
+ model is the commit-qualified `MontrealCorpusTools/english_mfa` bundle at revision
10
+ `1009e3c6c689f10875146a5e4e5c2233f8eaf922`. Its acoustic metadata declares model
11
+ version 3.3.0; the selected dialect is `english_us_mfa`, including its dictionary and
12
+ bundled G2P model. Sources checked on 2026-09-03:
13
+
14
+ - [MFA installation documentation](https://montreal-forced-aligner.readthedocs.io/en/latest/installation.html)
15
+ - [MFA model versioning documentation](https://montreal-forced-aligner.readthedocs.io/en/stable/user_guide/models/model_versions.html)
16
+ - [MFA alignment workflow documentation](https://montreal-forced-aligner.readthedocs.io/en/latest/user_guide/workflows/alignment.html)
17
+ - [`MontrealCorpusTools/english_mfa`](https://huggingface.co/MontrealCorpusTools/english_mfa)
18
+
19
+ Every source WAV is copied into a unique temporary corpus as `rNNNNNN.wav`. Its
20
+ same-stem `.lab` contains only a deterministic MFA-facing rendering of the exact
21
+ authoritative `en_transcript`. The source CSV, source cells, transcripts, and source
22
+ WAVs are never changed. MFA output cannot replace the transcript: each word-tier
23
+ interval must reconcile exactly and monotonically through the recorded text plan to
24
+ every original lexical word before it becomes a `WordAlignment`.
25
+
26
+ ## Module flow and responsibilities
27
+
28
+ ```text
29
+ MfaConfig
30
+ -> build_corpus (copied WAV + normalized .lab + reversible TextPlan)
31
+ -> run_mfa (dedicated Conda probe + shared ProcessRunner + align_hf)
32
+ -> parse_word_textgrid (strict words IntervalTier)
33
+ -> reconcile_word_units + validate_alignment_result
34
+ -> AlignmentResult / AlignmentFailure
35
+ ```
36
+
37
+ The Stage 3 package and focused tests are:
38
+
39
+ ```text
40
+ src/speech_text_data_aligners/backends/mfa/
41
+ ├── __init__.py
42
+ ├── backend.py
43
+ ├── config.py
44
+ ├── corpus.py
45
+ ├── runner.py
46
+ └── textgrid.py
47
+ tests/
48
+ ├── integration/mfa/test_mfa_real.py
49
+ └── unit/backends/mfa/
50
+ ├── test_backend.py
51
+ ├── test_config.py
52
+ ├── test_corpus.py
53
+ ├── test_runner.py
54
+ └── test_textgrid.py
55
+ ```
56
+
57
+ | MFA module | Responsibility | Focused test | Line coverage |
58
+ |---|---|---|---:|
59
+ | `backends.mfa.config` | Typed dedicated-environment, immutable model/dialect, process, and artifact policy | `tests/unit/backends/mfa/test_config.py` | 99.03% |
60
+ | `backends.mfa.corpus` | Deterministic normalization, reversible token ownership, and copied flat corpus materialization | `tests/unit/backends/mfa/test_corpus.py` | 99.19% |
61
+ | `backends.mfa.runner` | Exact Conda-package probe, shared shell-free process invocation, logs, and model/dictionary/G2P evidence | `tests/unit/backends/mfa/test_runner.py` | 98.62% |
62
+ | `backends.mfa.textgrid` | Independent strict long/short TextGrid word-tier parsing, timing checks, and lexical reconciliation | `tests/unit/backends/mfa/test_textgrid.py` | 97.91% |
63
+ | `backends.mfa.backend` | Batch workspace/process/parser orchestration and neutral result/failure/provenance construction | `tests/unit/backends/mfa/test_backend.py` | 100.00% |
64
+
65
+ `backends.mfa.__init__` is a deliberately empty package marker excluded by the
66
+ documented per-file gate.
67
+
68
+ ## Transcript normalization and mapping
69
+
70
+ The common lexicalizer first identifies the original words and their exact source
71
+ spans. MFA normalization then applies Unicode NFKC, canonical curly apostrophes and
72
+ dashes, and case folding. Hyphenated compounds become multiple units, dotted
73
+ abbreviations become letter units, and supported cardinals, ordinals, decimals, and
74
+ four-digit years become deterministic English pronunciation units. Every emitted unit
75
+ retains ownership of one original word in `TextPlan`; no heuristic post-alignment text
76
+ search is used.
77
+
78
+ The parser requires exactly one case-insensitive `words` `IntervalTier`. It supports
79
+ Praat long and short TextGrid bodies, validates quoting, counts, sequential indices,
80
+ finite non-negative bounds, tier containment, monotonic order, and non-overlap. Empty
81
+ and explicit silence intervals are skipped. Punctuation-only intervals are explicitly
82
+ ignorable. `<unk>`, `<oov>`, and `spn`, multiword labels, missing lexical intervals,
83
+ extra words, wrong repeated-word order, missing TextGrids, malformed tiers, and invalid
84
+ timestamps fail with typed errors; timestamps are never invented.
85
+
86
+ OOV handling is explicit. The default command enables the bundle's selected-dialect
87
+ G2P with `--use_g2p`. Disabling it emits a warning diagnostic, and any unresolved OOV
88
+ marker still fails exact mapping.
89
+
90
+ ## Dedicated reproducible environment
91
+
92
+ `MfaConfig` defaults to the dedicated Conda environment name
93
+ `speech-aligners-mfa`; it cannot select both a name and a prefix. The checked
94
+ linux-64 specification is [`environments/mfa.yml`](../environments/mfa.yml). Create it
95
+ with the current MFA 3.x recommended Conda-forge path:
96
+
97
+ ```bash
98
+ conda env create --solver libmamba --file environments/mfa.yml
99
+ conda run --name speech-aligners-mfa mfa version
100
+ ```
101
+
102
+ Because the operator environment did not allow registration in its home Conda config,
103
+ the real Stage 3 verification used the equivalent isolated prefix:
104
+
105
+ ```bash
106
+ XDG_CACHE_HOME=/tmp/speech-aligners-mfa-xdg \
107
+ CONDA_PKGS_DIRS=/tmp/speech-aligners-mfa-pkgs \
108
+ CONDA_ENVS_PATH=/tmp/speech-aligners-mfa-envs \
109
+ conda env create --solver libmamba \
110
+ --prefix /tmp/speech-aligners-mfa-stage3 --file environments/mfa.yml
111
+ ```
112
+
113
+ Exact installed packages probed on 2026-09-03 were:
114
+
115
+ | Package | Version | Conda build | Channel |
116
+ |---|---:|---|---|
117
+ | Python | 3.12.14 | `h5f976f7_3_cpython` | conda-forge |
118
+ | Montreal Forced Aligner | 3.4.2 | `pyhd8ed1ab_0` | conda-forge |
119
+ | Kaldi | 5.5.1172 | `cpu_h5f874f2_5` | conda-forge |
120
+ | Kalpy | 0.10.5 | `py312ha5105d2_0` | conda-forge |
121
+ | OpenFst | 1.8.4 | `h84d6215_1` | conda-forge |
122
+
123
+ The package additionally records the MFA 3.4.2 source-tag commit
124
+ `d2dc283bd79667e086b1f93050a1855349f63f1f`. Before each run, `conda list --json`
125
+ must match the configured MFA/Kaldi/Kalpy/OpenFst versions. The parent process imports
126
+ none of those packages.
127
+
128
+ ## Native command, diagnostics, and provenance
129
+
130
+ `run_mfa` delegates both the package probe and native execution to the shared injected
131
+ `ProcessRunner`. It never starts a shell. The alignment argument vector is equivalent
132
+ to:
133
+
134
+ ```text
135
+ conda run --no-capture-output <environment-selector> mfa align_hf
136
+ <copied-corpus>
137
+ MontrealCorpusTools/english_mfa@1009e3c6c689f10875146a5e4e5c2233f8eaf922
138
+ <output>
139
+ --dialect english_us_mfa
140
+ --output_format long_textgrid
141
+ --no_tokenization
142
+ --temporary_directory <workspace>/runtime/work
143
+ --num_jobs 1
144
+ --clean --no_final_clean --overwrite --verbose --no_use_postgres --use_g2p
145
+ ```
146
+
147
+ `MFA_ROOT_DIR` and `HF_HOME` are unique workspace-local paths. Full package JSON,
148
+ stdout, stderr, labels, model snapshot, and available TextGrids are retained according
149
+ to `never`, `on_failure`, or `always`. Failed batches mark the workspace failed before
150
+ cleanup. Raised subprocess failures also include the persistent retained directory.
151
+
152
+ Every result records exact runtime builds, the immutable model ID/revision/version,
153
+ selected dictionary ID/revision, bundle/dictionary/G2P content hashes, canonical
154
+ configuration hash, native argument-vector hash, normalized-label hash, TextGrid hash,
155
+ device, bounded process diagnostics, runtime, and retained artifact paths. A supplied
156
+ `expected_model_sha256` can enforce the complete deterministic snapshot-tree digest.
157
+
158
+ ## Direct library and CLI composition
159
+
160
+ Direct construction stays independent of the CLI:
161
+
162
+ ```python
163
+ from pathlib import Path
164
+
165
+ from speech_text_data_aligners.backends.mfa.backend import MfaBackend
166
+ from speech_text_data_aligners.backends.mfa.config import MfaConfig
167
+
168
+ backend = MfaBackend(
169
+ MfaConfig(
170
+ environment_name=None,
171
+ environment_prefix=Path("/opt/conda/envs/speech-aligners-mfa"),
172
+ artifact_policy="on_failure",
173
+ retention_root=Path("results/mfa/failures"),
174
+ )
175
+ )
176
+ result = backend.align(request)
177
+ run = annotate_metadata(
178
+ metadata_csv=metadata_csv,
179
+ audio_dir=audio_dir,
180
+ output_csv=output_csv,
181
+ backend=backend,
182
+ )
183
+ ```
184
+
185
+ The default registry resolves the same constructor lazily. CLI composition passes a
186
+ JSON-friendly mapping without introducing MFA branches in application, data, core, or
187
+ benchmark code:
188
+
189
+ ```bash
190
+ PYTHONPATH=src python -m speech_text_data_aligners.cli.main annotate \
191
+ metadata.csv wavs annotated.csv --backend mfa \
192
+ --backend-config-json \
193
+ '{"environment_name":"speech-aligners-mfa","artifact_policy":"on_failure","retention_root":"results/mfa/failures"}'
194
+ ```
195
+
196
+ ## Real opt-in integration smoke test
197
+
198
+ [`tests/integration/mfa/test_mfa_real.py`](../tests/integration/mfa/test_mfa_real.py)
199
+ is marked `integration` and `mfa`. It skips unless the isolated runtime, WAV, and exact
200
+ authoritative transcript are explicit:
201
+
202
+ ```bash
203
+ export RUN_MFA_INTEGRATION=1
204
+ export MFA_CONDA_PREFIX=/absolute/path/to/speech-aligners-mfa
205
+ export MFA_SMOKE_WAV=/absolute/path/to/example.wav
206
+ export MFA_SMOKE_TRANSCRIPT='The exact authoritative transcript.'
207
+ PYTHONPATH=src python -m pytest tests/integration/mfa/test_mfa_real.py \
208
+ -m 'integration and mfa' -v
209
+ ```
210
+
211
+ The assertion requires the returned lexical sequence to equal the authoritative
212
+ sequence, nonempty content-hash provenance, and a neutral `mfa` backend identity.
213
+ Ordinary tests never run MFA, download models, or require Conda.
214
+
215
+ ## Exact five-row evaluation and measured result
216
+
217
+ The immutable inputs retain their supplied hashes:
218
+
219
+ | Input | SHA-256 |
220
+ |---|---|
221
+ | main metadata CSV | `024cdaa4a74be649cc70e3fbfa0af6d06e1c3341485c992d16fec91e0114fa69` |
222
+ | five-row gold/reference CSV | `60386910850def52a1465540ccb553b4ddfa310105db68182deee651810f4e12` |
223
+
224
+ All five referenced WAVs were present. The successful real command was:
225
+
226
+ ```bash
227
+ PYTHONPATH=src python -m speech_text_data_aligners.cli.main benchmark \
228
+ /mnt/d/vertox/codex-runs/speech-text-aligners/speech-text-data-aligners-codex-kit-v2/inputs/voxtral-first5-first-word.csv \
229
+ /mnt/d/vertox/codex-runs/speech-text-aligners/speech-text-data-aligners-codex-kit-v2/inputs/voxtral-first5-first-word.csv \
230
+ /mnt/d/vertox/data/selected_data_deduplicated \
231
+ --backend mfa \
232
+ --backend-config-json \
233
+ '{"mfa":{"environment_prefix":"/tmp/speech-aligners-mfa-stage3","artifact_policy":"on_failure","retention_root":"/tmp/speech-aligners-mfa-failure-artifacts","run_id":"mfa-five-row-20260903","num_jobs":1,"timeout_s":3600}}' \
234
+ --output-base results/mfa/five-row-evaluation --overwrite
235
+ ```
236
+
237
+ This cold-cache run downloaded the pinned bundle and completed all five rows in one
238
+ MFA process:
239
+
240
+ | Metric | Measured value |
241
+ |---|---:|
242
+ | successes / failures | 5 / 0 |
243
+ | exact authoritative text matches | 5 / 5 (100%) |
244
+ | first-word-end reference coverage | 5 / 5 |
245
+ | first-word-end MAE | 0.0162 s |
246
+ | first-word-end median absolute error | 0.0110 s |
247
+ | first-word-end maximum absolute error | 0.0300 s |
248
+ | total cold-run runtime | 274.9569 s |
249
+ | mean attributed runtime | 54.9914 s/row |
250
+
251
+ The reproducible outputs are
252
+ [`five-row-evaluation.json`](../results/mfa/five-row-evaluation.json),
253
+ [`five-row-evaluation.csv`](../results/mfa/five-row-evaluation.csv), and
254
+ [`five-row-evaluation.md`](../results/mfa/five-row-evaluation.md). Artifact policy was
255
+ `on_failure`; because every row succeeded, no model cache, native TextGrid, or WAV copy
256
+ was retained in the repository.
257
+
258
+ ## Acceptance evidence
259
+
260
+ Final deterministic checks on 2026-09-03:
261
+
262
+ - `ruff format --check .`: 86 files already formatted.
263
+ - `ruff check .`: passed.
264
+ - `mypy src`: passed for 39 source files.
265
+ - CLI `--help`: passed.
266
+ - `coverage run -m pytest tests/unit tests/architecture`: 394 passed.
267
+ - `coverage report --show-missing`: 99.17% overall; every in-scope file at least
268
+ 95.45%, every MFA file at least 97.91%.
269
+ - `tests/quality/test_per_file_coverage.py`: passed.
270
+ - import-linter 2.14: 39 files, 97 dependencies, all six contracts kept, including
271
+ MFA isolation.
272
+
273
+ Architecture tests additionally parse all production imports, reject heavyweight
274
+ imports from neutral layers, reject MFA imports of NeMo or WhisperX, verify lazy
275
+ registry factories, and import neutral/NeMo modules while blocking MFA-related module
276
+ names. MFA absence therefore cannot break backend-neutral or sibling-backend imports.
277
+
278
+ ## Complete implementation-to-test coverage map
279
+
280
+ Empty package markers are excluded explicitly; no implementation file is hidden by an
281
+ aggregate-only report.
282
+
283
+ | Implementation | Focused test | Coverage |
284
+ |---|---|---:|
285
+ | `speech_text_data_aligners.__init__` | `tests/unit/test_public_api.py` | 100.00% |
286
+ | `application.annotate` | `tests/unit/application/test_annotate.py` | 98.00% |
287
+ | `application.benchmark` | `tests/unit/application/test_benchmark.py` | 100.00% |
288
+ | `backends.registry` | `tests/unit/backends/test_registry.py` | 100.00% |
289
+ | `backends.mfa.backend` | `tests/unit/backends/mfa/test_backend.py` | 100.00% |
290
+ | `backends.mfa.config` | `tests/unit/backends/mfa/test_config.py` | 99.03% |
291
+ | `backends.mfa.corpus` | `tests/unit/backends/mfa/test_corpus.py` | 99.19% |
292
+ | `backends.mfa.runner` | `tests/unit/backends/mfa/test_runner.py` | 98.62% |
293
+ | `backends.mfa.textgrid` | `tests/unit/backends/mfa/test_textgrid.py` | 97.91% |
294
+ | `backends.nemo.backend` | `tests/unit/backends/nemo/test_backend.py` | 100.00% |
295
+ | `backends.nemo.config` | `tests/unit/backends/nemo/test_config.py` | 98.11% |
296
+ | `backends.nemo.ctm` | `tests/unit/backends/nemo/test_ctm.py` | 100.00% |
297
+ | `backends.nemo.manifest` | `tests/unit/backends/nemo/test_manifest.py` | 100.00% |
298
+ | `backends.nemo.runner` | `tests/unit/backends/nemo/test_runner.py` | 100.00% |
299
+ | `benchmarking.metrics` | `tests/unit/benchmarking/test_metrics.py` | 100.00% |
300
+ | `benchmarking.reports` | `tests/unit/benchmarking/test_reports.py` | 98.84% |
301
+ | `cli.annotate` | `tests/unit/cli/test_annotate.py` | 100.00% |
302
+ | `cli.benchmark` | `tests/unit/cli/test_benchmark.py` | 100.00% |
303
+ | `cli.main` | `tests/unit/cli/test_main.py` | 95.45% |
304
+ | `core.errors` | `tests/unit/core/test_errors.py` | 100.00% |
305
+ | `core.extraction` | `tests/unit/core/test_extraction.py` | 95.65% |
306
+ | `core.models` | `tests/unit/core/test_models.py` | 100.00% |
307
+ | `core.normalization` | `tests/unit/core/test_normalization.py` | 100.00% |
308
+ | `core.protocols` | `tests/unit/core/test_protocols.py` | 100.00% |
309
+ | `core.validation` | `tests/unit/core/test_validation.py` | 98.33% |
310
+ | `data.audio` | `tests/unit/data/test_audio.py` | 97.37% |
311
+ | `data.metadata` | `tests/unit/data/test_metadata.py` | 98.08% |
312
+ | `runtime.artifacts` | `tests/unit/runtime/test_artifacts.py` | 100.00% |
313
+ | `runtime.process` | `tests/unit/runtime/test_process.py` | 100.00% |
314
+ | `runtime.receipts` | `tests/unit/runtime/test_receipts.py` | 100.00% |
environments/mfa.yml CHANGED
@@ -1,12 +1,12 @@
1
- # Stage 0 UNVERIFIED constraint skeleton. Keep MFA/Kaldi isolated from all
2
- # PyTorch environments and generate a linux-64 lock after a successful solve.
3
  name: speech-aligners-mfa
4
  channels:
5
  - conda-forge
6
  - nodefaults
7
  dependencies:
8
- - python=3.12.14
9
- - montreal-forced-aligner=3.4.2
10
- - kaldi=5.5.1172=cpu_*
11
- - kalpy=0.10.5
12
- - openfst=1.8.4
 
1
+ # Stage 3 verified dedicated MFA environment. The exact linux-64 builds installed
2
+ # on 2026-09-03 are recorded in docs/STAGE_3_REPORT.md.
3
  name: speech-aligners-mfa
4
  channels:
5
  - conda-forge
6
  - nodefaults
7
  dependencies:
8
+ - python=3.12.14=h5f976f7_3_cpython
9
+ - montreal-forced-aligner=3.4.2=pyhd8ed1ab_0
10
+ - kaldi=5.5.1172=cpu_h5f874f2_5
11
+ - kalpy=0.10.5=py312ha5105d2_0
12
+ - openfst=1.8.4=h84d6215_1
pyproject.toml CHANGED
@@ -121,3 +121,16 @@ forbidden_modules = [
121
  "speech_text_data_aligners.backends.mfa",
122
  "speech_text_data_aligners.backends.whisperx",
123
  ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  "speech_text_data_aligners.backends.mfa",
122
  "speech_text_data_aligners.backends.whisperx",
123
  ]
124
+
125
+ [[tool.importlinter.contracts]]
126
+ name = "MFA backend is isolated from outer and sibling backend layers"
127
+ type = "forbidden"
128
+ source_modules = ["speech_text_data_aligners.backends.mfa"]
129
+ forbidden_modules = [
130
+ "speech_text_data_aligners.application",
131
+ "speech_text_data_aligners.benchmarking",
132
+ "speech_text_data_aligners.cli",
133
+ "speech_text_data_aligners.data",
134
+ "speech_text_data_aligners.backends.nemo",
135
+ "speech_text_data_aligners.backends.whisperx",
136
+ ]
results/mfa/five-row-evaluation.csv ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ scope,metric,value
2
+ mfa,success_count,5
3
+ mfa,failure_count,0
4
+ mfa,referenced_rows,5
5
+ mfa,missing_reference_rows,0
6
+ mfa,text_reference_count,5
7
+ mfa,missing_text_reference_count,0
8
+ mfa,exact_text_match_count,5
9
+ mfa,exact_text_match_rate,1.0
10
+ mfa,first_end_reference_count,5
11
+ mfa,missing_first_end_reference_count,0
12
+ mfa,first_end_scored_count,5
13
+ mfa,first_end_mae_s,0.016199999999999992
14
+ mfa,first_end_median_s,0.01100000000000012
15
+ mfa,first_end_max_s,0.030000000000000027
16
+ mfa,total_runtime_s,274.9568500280002
17
+ mfa,mean_runtime_s,54.99137000560004
results/mfa/five-row-evaluation.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"backend_reports":[{"backend_name":"mfa","gold_metrics":{"exact_text_match_count":5,"exact_text_match_rate":1.0,"failure_count":0,"first_end_errors":{"count":5,"mae":0.016199999999999992,"maximum":0.030000000000000027,"median":0.01100000000000012},"first_end_reference_count":5,"mean_runtime_s":54.99137000560004,"missing_first_end_reference_count":0,"missing_reference_rows":0,"missing_text_reference_count":0,"referenced_rows":5,"success_count":5,"text_reference_count":5,"total_rows":5,"total_runtime_s":274.9568500280002},"observations":[{"audio_id":"mim_02484_01416200252","backend_name":"mfa","boundaries":{"first_word_end_s":1.43,"first_word_start_s":1.01,"first_word_text":"Effects","last_word_end_s":9.35,"last_word_start_s":8.64,"last_word_text":"identity"},"failure_code":null,"line_id":"EN0032","native_artifacts":[],"runtime_s":54.99137000560004},{"audio_id":"mim_02484_01200690643","backend_name":"mfa","boundaries":{"first_word_end_s":1.06,"first_word_start_s":0.9,"first_word_text":"As","last_word_end_s":8.28,"last_word_start_s":7.81,"last_word_text":"design"},"failure_code":null,"line_id":"EN1162","native_artifacts":[],"runtime_s":54.99137000560004},{"audio_id":"mim_03397_00876280561","backend_name":"mfa","boundaries":{"first_word_end_s":1.34,"first_word_start_s":0.95,"first_word_text":"Personal","last_word_end_s":8.68,"last_word_start_s":7.83,"last_word_text":"notifications"},"failure_code":null,"line_id":"EN0609","native_artifacts":[],"runtime_s":54.99137000560004},{"audio_id":"mim_02484_01233863243","backend_name":"mfa","boundaries":{"first_word_end_s":0.97,"first_word_start_s":0.91,"first_word_text":"It","last_word_end_s":8.81,"last_word_start_s":8.31,"last_word_text":"games"},"failure_code":null,"line_id":"EN0949","native_artifacts":[],"runtime_s":54.99137000560004},{"audio_id":"mim_04310_01682036526","backend_name":"mfa","boundaries":{"first_word_end_s":1.38,"first_word_start_s":0.96,"first_word_text":"Traditional","last_word_end_s":10.55,"last_word_start_s":9.68,"last_word_text":"recitation"},"failure_code":null,"line_id":"EN0898","native_artifacts":[],"runtime_s":54.99137000560004}]}],"pairwise_metrics":[]}
results/mfa/five-row-evaluation.md ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ | Scope | Metric | Value |
2
+ |---|---|---:|
3
+ | mfa | success_count | 5 |
4
+ | mfa | failure_count | 0 |
5
+ | mfa | referenced_rows | 5 |
6
+ | mfa | missing_reference_rows | 0 |
7
+ | mfa | text_reference_count | 5 |
8
+ | mfa | missing_text_reference_count | 0 |
9
+ | mfa | exact_text_match_count | 5 |
10
+ | mfa | exact_text_match_rate | 1.0 |
11
+ | mfa | first_end_reference_count | 5 |
12
+ | mfa | missing_first_end_reference_count | 0 |
13
+ | mfa | first_end_scored_count | 5 |
14
+ | mfa | first_end_mae_s | 0.016199999999999992 |
15
+ | mfa | first_end_median_s | 0.01100000000000012 |
16
+ | mfa | first_end_max_s | 0.030000000000000027 |
17
+ | mfa | total_runtime_s | 274.9568500280002 |
18
+ | mfa | mean_runtime_s | 54.99137000560004 |
src/speech_text_data_aligners/backends/mfa/__init__.py ADDED
File without changes
src/speech_text_data_aligners/backends/mfa/backend.py ADDED
@@ -0,0 +1,508 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Adapt isolated Montreal Forced Aligner batches to the neutral protocol."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping, Sequence
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+
9
+ from speech_text_data_aligners.backends.mfa.config import (
10
+ MFA_SOURCE_REVISION,
11
+ MfaConfig,
12
+ )
13
+ from speech_text_data_aligners.backends.mfa.corpus import (
14
+ MfaCorpus,
15
+ MfaCorpusEntry,
16
+ build_corpus,
17
+ )
18
+ from speech_text_data_aligners.backends.mfa.runner import MfaRun, run_mfa
19
+ from speech_text_data_aligners.backends.mfa.textgrid import parse_word_textgrid
20
+ from speech_text_data_aligners.core.errors import (
21
+ AlignmentValidationError,
22
+ AudioError,
23
+ BackendExecutionError,
24
+ BackendOutputError,
25
+ BackendUnavailableError,
26
+ ConfigurationError,
27
+ SpeechTextAlignerError,
28
+ TranscriptError,
29
+ TranscriptMappingError,
30
+ )
31
+ from speech_text_data_aligners.core.models import (
32
+ AlignmentFailure,
33
+ AlignmentOutcome,
34
+ AlignmentProvenance,
35
+ AlignmentRequest,
36
+ AlignmentResult,
37
+ Diagnostic,
38
+ DiagnosticSeverity,
39
+ WordAlignment,
40
+ )
41
+ from speech_text_data_aligners.core.validation import validate_alignment_result
42
+ from speech_text_data_aligners.runtime.artifacts import (
43
+ ArtifactPolicy,
44
+ Workspace,
45
+ workspace,
46
+ )
47
+ from speech_text_data_aligners.runtime.process import ProcessRunner, SubprocessRunner
48
+ from speech_text_data_aligners.runtime.receipts import (
49
+ canonical_fingerprint,
50
+ sha256_file,
51
+ )
52
+
53
+ _ADAPTER_VERSION = "0.1.0"
54
+
55
+
56
+ @dataclass(frozen=True, slots=True)
57
+ class _ParsedRow:
58
+ """Hold one corpus row's parsed words, native hashes, or typed failure.
59
+
60
+ Parameters
61
+ ----------
62
+ entry: Authoritative request and native corpus association.
63
+ textgrid_path: Expected workspace-local aligned output path.
64
+ words: Parsed neutral words, or ``None`` after a row-local failure.
65
+ lab_sha256: Hash of the emitted normalized reference label.
66
+ textgrid_sha256: TextGrid hash when output parsing/hashing succeeded.
67
+ error: Typed row-local output/mapping/validation failure, or ``None``.
68
+
69
+ """
70
+
71
+ entry: MfaCorpusEntry
72
+ textgrid_path: Path
73
+ words: tuple[WordAlignment, ...] | None
74
+ lab_sha256: str
75
+ textgrid_sha256: str | None
76
+ error: SpeechTextAlignerError | None
77
+
78
+
79
+ def _retained_artifact(
80
+ path: Path,
81
+ *,
82
+ workspace_path: Path,
83
+ retained_path: Path | None,
84
+ ) -> str | None:
85
+ """Map a temporary native path to its retained copy when available.
86
+
87
+ Parameters
88
+ ----------
89
+ path: Native file or directory inside the temporary workspace.
90
+ workspace_path: Temporary workspace root.
91
+ retained_path: Copied workspace root after cleanup, when retained.
92
+
93
+ Returns
94
+ -------
95
+ Persistent retained path string, or ``None`` when artifacts were discarded.
96
+
97
+ """
98
+ if retained_path is None:
99
+ return None
100
+ return str(retained_path / path.relative_to(workspace_path))
101
+
102
+
103
+ def _raise_failure(failure: AlignmentFailure) -> None:
104
+ """Recreate the most specific typed exception for the single-request API.
105
+
106
+ Parameters
107
+ ----------
108
+ failure: Structured row-local failure produced by batch execution.
109
+
110
+ Raises
111
+ ------
112
+ SpeechTextAlignerError: Always, retaining retry and artifact context.
113
+
114
+ """
115
+ error_types: dict[str, type[SpeechTextAlignerError]] = {
116
+ AudioError.code: AudioError,
117
+ BackendExecutionError.code: BackendExecutionError,
118
+ BackendOutputError.code: BackendOutputError,
119
+ BackendUnavailableError.code: BackendUnavailableError,
120
+ ConfigurationError.code: ConfigurationError,
121
+ TranscriptError.code: TranscriptError,
122
+ TranscriptMappingError.code: TranscriptMappingError,
123
+ AlignmentValidationError.code: AlignmentValidationError,
124
+ }
125
+ error_type = error_types.get(failure.code, SpeechTextAlignerError)
126
+ artifacts = failure.provenance.artifacts if failure.provenance else ()
127
+ raise error_type(
128
+ failure.message,
129
+ context=(("request_id", failure.request_id), ("native_artifacts", artifacts)),
130
+ retryable=failure.retryable,
131
+ )
132
+
133
+
134
+ class MfaBackend:
135
+ """Run revision-pinned MFA corpus batches and return validated neutral results.
136
+
137
+ Parameters
138
+ ----------
139
+ config: Typed dedicated-environment/model/dialect/artifact configuration.
140
+ process_runner: Injectable command boundary; defaults to the shared shell-free
141
+ subprocess runner.
142
+
143
+ Invariants
144
+ ----------
145
+ Source WAVs and transcripts remain immutable. Native labels are explicit text
146
+ plans, all successful rows cover every original lexical word, and no missing
147
+ timestamp is fabricated.
148
+
149
+ """
150
+
151
+ def __init__(
152
+ self,
153
+ config: MfaConfig,
154
+ *,
155
+ process_runner: ProcessRunner | None = None,
156
+ ) -> None:
157
+ """Initialize an adapter without importing or starting MFA.
158
+
159
+ Parameters
160
+ ----------
161
+ config: Validated typed MFA configuration.
162
+ process_runner: Optional fake/alternate native command executor.
163
+
164
+ """
165
+ self.config = config
166
+ self._process_runner = process_runner or SubprocessRunner()
167
+
168
+ @property
169
+ def name(self) -> str:
170
+ """Return the stable registry/report backend name.
171
+
172
+ Returns
173
+ -------
174
+ The literal backend name ``mfa``.
175
+
176
+ """
177
+ return "mfa"
178
+
179
+ def _provenance(
180
+ self,
181
+ *,
182
+ mfa_run: MfaRun,
183
+ row: _ParsedRow,
184
+ workspace_state: Workspace,
185
+ ) -> AlignmentProvenance:
186
+ """Build immutable runtime/model/dictionary/artifact provenance.
187
+
188
+ Parameters
189
+ ----------
190
+ mfa_run: Completed command plus exact package/model evidence.
191
+ row: Parsed row and native hashes.
192
+ workspace_state: Closed workspace with optional retained-copy location.
193
+
194
+ Returns
195
+ -------
196
+ Backend-neutral provenance containing only persistent artifact paths.
197
+
198
+ """
199
+ native_paths = [
200
+ row.entry.lab_path,
201
+ mfa_run.stdout_log,
202
+ mfa_run.stderr_log,
203
+ mfa_run.package_log,
204
+ mfa_run.model_snapshot,
205
+ ]
206
+ if row.textgrid_sha256 is not None:
207
+ native_paths.append(row.textgrid_path)
208
+ artifacts = tuple(
209
+ retained
210
+ for path in native_paths
211
+ if (
212
+ retained := _retained_artifact(
213
+ path,
214
+ workspace_path=workspace_state.path,
215
+ retained_path=workspace_state.retained_path,
216
+ )
217
+ )
218
+ is not None
219
+ )
220
+ runtime = mfa_run.runtime
221
+ return AlignmentProvenance(
222
+ backend_name=self.name,
223
+ backend_version=runtime.mfa.version,
224
+ adapter_version=_ADAPTER_VERSION,
225
+ model_id=self.config.model_id,
226
+ model_revision=self.config.model_revision,
227
+ model_sha256=mfa_run.model_sha256,
228
+ dictionary_id=f"{self.config.model_id}:{self.config.dialect}",
229
+ dictionary_revision=self.config.model_revision,
230
+ dictionary_sha256=mfa_run.dictionary_sha256,
231
+ python_version=runtime.python.version,
232
+ device="cpu",
233
+ config_sha256=canonical_fingerprint(self.config.fingerprint_values()),
234
+ native_command_sha256=mfa_run.command_sha256,
235
+ artifacts=artifacts,
236
+ attributes=(
237
+ ("mfa_source_revision", MFA_SOURCE_REVISION),
238
+ ("model_version", self.config.model_version),
239
+ ("dialect", self.config.dialect),
240
+ ("use_g2p", self.config.use_g2p),
241
+ ("g2p_sha256", mfa_run.g2p_sha256),
242
+ ("kaldi_version", runtime.kaldi.version),
243
+ ("kaldi_build", runtime.kaldi.build),
244
+ ("kalpy_version", runtime.kalpy.version),
245
+ ("kalpy_build", runtime.kalpy.build),
246
+ ("openfst_version", runtime.openfst.version),
247
+ ("openfst_build", runtime.openfst.build),
248
+ ("mfa_build", runtime.mfa.build),
249
+ ("conda_environment", runtime.environment),
250
+ ("lab_sha256", row.lab_sha256),
251
+ ("textgrid_sha256", row.textgrid_sha256),
252
+ ("reference_text_authoritative", True),
253
+ ),
254
+ )
255
+
256
+ def _diagnostics(
257
+ self,
258
+ *,
259
+ mfa_run: MfaRun,
260
+ provenance: AlignmentProvenance,
261
+ ) -> tuple[Diagnostic, ...]:
262
+ """Create bounded process and explicit OOV-policy diagnostics.
263
+
264
+ Parameters
265
+ ----------
266
+ mfa_run: Completed native invocation.
267
+ provenance: Row provenance containing retained artifact paths.
268
+
269
+ Returns
270
+ -------
271
+ Process completion plus G2P-enabled/disabled OOV policy diagnostics.
272
+
273
+ """
274
+ oov_enabled = self.config.use_g2p
275
+ return (
276
+ Diagnostic(
277
+ code="mfa_process_completed",
278
+ severity=DiagnosticSeverity.INFO,
279
+ message="Montreal Forced Aligner process completed successfully",
280
+ stage="backend_execution",
281
+ details=(
282
+ ("returncode", mfa_run.result.returncode),
283
+ ("duration_s", mfa_run.result.duration_s),
284
+ ("stdout_tail", mfa_run.result.stdout[-2000:]),
285
+ ("stderr_tail", mfa_run.result.stderr[-2000:]),
286
+ ("native_artifacts", provenance.artifacts),
287
+ ),
288
+ ),
289
+ Diagnostic(
290
+ code="mfa_oov_g2p_enabled" if oov_enabled else "mfa_oov_g2p_disabled",
291
+ severity=(
292
+ DiagnosticSeverity.INFO
293
+ if oov_enabled
294
+ else DiagnosticSeverity.WARNING
295
+ ),
296
+ message=(
297
+ "Bundled dialect G2P was enabled for dictionary OOV words"
298
+ if oov_enabled
299
+ else "G2P was disabled; unresolved dictionary OOV words fail mapping"
300
+ ),
301
+ stage="transcript_normalization",
302
+ details=(("dialect", self.config.dialect),),
303
+ ),
304
+ )
305
+
306
+ def _execute_batch(
307
+ self, requests: tuple[AlignmentRequest, ...]
308
+ ) -> tuple[AlignmentOutcome, ...]:
309
+ """Execute one non-empty MFA batch and structure row-local output failures.
310
+
311
+ Parameters
312
+ ----------
313
+ requests: Ordered authoritative requests.
314
+
315
+ Returns
316
+ -------
317
+ Ordered complete results or TextGrid/mapping/validation failures.
318
+
319
+ Raises
320
+ ------
321
+ SpeechTextAlignerError: If corpus construction, environment/model probing,
322
+ process execution, provenance, or artifact cleanup fails for the batch.
323
+
324
+ Side Effects:
325
+ Creates a temporary copied corpus, invokes MFA once, and retains a copy
326
+ according to ``artifact_policy``.
327
+
328
+ """
329
+ state: Workspace | None = None
330
+ corpus: MfaCorpus
331
+ mfa_run: MfaRun
332
+ parsed_rows: list[_ParsedRow] = []
333
+ try:
334
+ with workspace(
335
+ run_id=self.config.run_id,
336
+ policy=ArtifactPolicy(self.config.artifact_policy),
337
+ temporary_root=self.config.temporary_root,
338
+ retention_root=self.config.retention_root,
339
+ ) as state:
340
+ corpus = build_corpus(requests, state.path / "corpus")
341
+ output_dir = state.path / "output"
342
+ mfa_run = run_mfa(
343
+ self.config,
344
+ corpus.path,
345
+ output_dir,
346
+ state.path / "runtime",
347
+ process_runner=self._process_runner,
348
+ )
349
+ runtime_per_row = mfa_run.result.duration_s / len(corpus.entries)
350
+ provisional = AlignmentProvenance(backend_name=self.name)
351
+ for entry in corpus.entries:
352
+ textgrid_path = output_dir / f"{entry.stem}.TextGrid"
353
+ lab_sha256 = sha256_file(entry.lab_path)
354
+ try:
355
+ words = parse_word_textgrid(textgrid_path, entry.text_plan)
356
+ textgrid_sha256 = sha256_file(textgrid_path)
357
+ validate_alignment_result(
358
+ entry.request,
359
+ AlignmentResult(
360
+ request_id=entry.request.request_id,
361
+ words=words,
362
+ provenance=provisional,
363
+ runtime_s=runtime_per_row,
364
+ ),
365
+ )
366
+ except SpeechTextAlignerError as error:
367
+ state.mark_failed()
368
+ parsed_rows.append(
369
+ _ParsedRow(
370
+ entry, textgrid_path, None, lab_sha256, None, error
371
+ )
372
+ )
373
+ else:
374
+ parsed_rows.append(
375
+ _ParsedRow(
376
+ entry,
377
+ textgrid_path,
378
+ words,
379
+ lab_sha256,
380
+ textgrid_sha256,
381
+ None,
382
+ )
383
+ )
384
+ except SpeechTextAlignerError as error:
385
+ if state is not None and state.retained_path is not None:
386
+ raise type(error)(
387
+ str(error),
388
+ context=(
389
+ *error.context,
390
+ ("native_artifact_dir", str(state.retained_path)),
391
+ ),
392
+ retryable=error.retryable,
393
+ ) from error
394
+ raise
395
+
396
+ assert state is not None
397
+ outcomes: list[AlignmentOutcome] = []
398
+ runtime_per_row = mfa_run.result.duration_s / len(parsed_rows)
399
+ for row in parsed_rows:
400
+ provenance = self._provenance(
401
+ mfa_run=mfa_run,
402
+ row=row,
403
+ workspace_state=state,
404
+ )
405
+ diagnostics = self._diagnostics(mfa_run=mfa_run, provenance=provenance)
406
+ request_id = row.entry.request.request_id
407
+ if row.error is not None:
408
+ outcomes.append(
409
+ AlignmentOutcome(
410
+ failure=AlignmentFailure(
411
+ request_id=request_id,
412
+ code=row.error.code,
413
+ category=row.error.category,
414
+ message=str(row.error),
415
+ retryable=row.error.retryable,
416
+ diagnostics=diagnostics,
417
+ provenance=provenance,
418
+ )
419
+ )
420
+ )
421
+ else:
422
+ assert row.words is not None
423
+ outcomes.append(
424
+ AlignmentOutcome(
425
+ result=AlignmentResult(
426
+ request_id=request_id,
427
+ words=row.words,
428
+ provenance=provenance,
429
+ diagnostics=diagnostics,
430
+ runtime_s=runtime_per_row,
431
+ )
432
+ )
433
+ )
434
+ return tuple(outcomes)
435
+
436
+ def align(self, request: AlignmentRequest) -> AlignmentResult:
437
+ """Align one authoritative transcript against its WAV through MFA.
438
+
439
+ Parameters
440
+ ----------
441
+ request: Fully populated backend-neutral alignment request.
442
+
443
+ Returns
444
+ -------
445
+ Complete, mapped, semantically validated word alignment.
446
+
447
+ Raises
448
+ ------
449
+ SpeechTextAlignerError: If input, execution, native output, mapping,
450
+ validation, model evidence, or artifact handling fails.
451
+
452
+ """
453
+ outcome = self._execute_batch((request,))[0]
454
+ if outcome.failure is not None:
455
+ _raise_failure(outcome.failure)
456
+ assert outcome.result is not None
457
+ return outcome.result
458
+
459
+ def align_batch(
460
+ self, requests: Sequence[AlignmentRequest]
461
+ ) -> tuple[AlignmentOutcome, ...]:
462
+ """Align an ordered request batch in one MFA corpus process.
463
+
464
+ Parameters
465
+ ----------
466
+ requests: Ordered authoritative requests. Empty input is a no-op.
467
+
468
+ Returns
469
+ -------
470
+ Exactly one ordered result or row-local failure per request.
471
+
472
+ Raises
473
+ ------
474
+ SpeechTextAlignerError: For whole-batch corpus, runtime, model,
475
+ provenance, or artifact failures.
476
+
477
+ """
478
+ batch = tuple(requests)
479
+ if not batch:
480
+ return ()
481
+ return self._execute_batch(batch)
482
+
483
+
484
+ def create_backend(
485
+ *,
486
+ config: Mapping[str, object] | MfaConfig,
487
+ process_runner: ProcessRunner | None = None,
488
+ ) -> MfaBackend:
489
+ """Construct the lazily selected MFA adapter without importing MFA.
490
+
491
+ Parameters
492
+ ----------
493
+ config: Typed MFA configuration or JSON-friendly CLI mapping.
494
+ process_runner: Optional injected process boundary for deterministic tests.
495
+
496
+ Returns
497
+ -------
498
+ Protocol-compatible MFA backend instance.
499
+
500
+ Raises
501
+ ------
502
+ ConfigurationError: If a supplied mapping is invalid.
503
+
504
+ """
505
+ typed_config = (
506
+ config if isinstance(config, MfaConfig) else MfaConfig.from_mapping(config)
507
+ )
508
+ return MfaBackend(typed_config, process_runner=process_runner)
src/speech_text_data_aligners/backends/mfa/config.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Define validated configuration for isolated Montreal Forced Aligner runs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import re
7
+ from collections.abc import Mapping
8
+ from dataclasses import asdict, dataclass
9
+ from pathlib import Path
10
+ from typing import Literal, cast
11
+
12
+ from speech_text_data_aligners.core.errors import ConfigurationError
13
+
14
+ MFA_VERSION = "3.4.2"
15
+ MFA_SOURCE_REVISION = "d2dc283bd79667e086b1f93050a1855349f63f1f"
16
+ KALDI_VERSION = "5.5.1172"
17
+ KALPY_VERSION = "0.10.5"
18
+ OPENFST_VERSION = "1.8.4"
19
+ DEFAULT_MODEL_ID = "MontrealCorpusTools/english_mfa"
20
+ DEFAULT_MODEL_REVISION = "1009e3c6c689f10875146a5e4e5c2233f8eaf922"
21
+ DEFAULT_MODEL_VERSION = "3.3.0"
22
+ DEFAULT_DIALECT = "english_us_mfa"
23
+
24
+ type ArtifactPolicyName = Literal["never", "on_failure", "always"]
25
+
26
+
27
+ @dataclass(frozen=True, slots=True)
28
+ class MfaConfig:
29
+ """Configure one revision-pinned MFA ``align_hf`` adapter.
30
+
31
+ Parameters
32
+ ----------
33
+ conda_executable: Conda executable path or PATH-resolved command name.
34
+ environment_name: Dedicated Conda environment name, mutually exclusive with
35
+ ``environment_prefix``.
36
+ environment_prefix: Dedicated Conda environment prefix, mutually exclusive
37
+ with ``environment_name``.
38
+ mfa_executable: MFA command name inside the selected environment.
39
+ model_id: Hugging Face MFA alignment-model repository identifier.
40
+ model_revision: Immutable forty-character Hugging Face commit revision.
41
+ model_version: Model's declared acoustic-model version for provenance.
42
+ dialect: Dictionary/G2P dialect contained in the model bundle.
43
+ use_g2p: Generate pronunciations for dictionary OOVs using the bundled G2P.
44
+ expected_mfa_version: Required installed MFA distribution version.
45
+ expected_kaldi_version: Required installed Conda Kaldi version.
46
+ expected_kalpy_version: Required installed Kalpy distribution version.
47
+ expected_openfst_version: Required installed OpenFst version.
48
+ expected_model_sha256: Optional required deterministic model-tree hash.
49
+ num_jobs: Positive number of MFA worker processes.
50
+ timeout_s: Positive timeout applied separately to probe and alignment commands.
51
+ artifact_policy: Retain native workspace never, on failure, or always.
52
+ temporary_root: Optional parent for unique adapter workspaces.
53
+ retention_root: Required retained-artifact parent when retention is enabled.
54
+ run_id: Safe single path component used for retained workspace naming.
55
+
56
+ Invariants
57
+ ----------
58
+ Exactly one dedicated Conda environment selector is present. The model is
59
+ always commit-qualified and MFA output is always long TextGrid; those safety
60
+ decisions are intentionally not configurable.
61
+
62
+ """
63
+
64
+ conda_executable: str = "conda"
65
+ environment_name: str | None = "speech-aligners-mfa"
66
+ environment_prefix: Path | None = None
67
+ mfa_executable: str = "mfa"
68
+ model_id: str = DEFAULT_MODEL_ID
69
+ model_revision: str = DEFAULT_MODEL_REVISION
70
+ model_version: str = DEFAULT_MODEL_VERSION
71
+ dialect: str = DEFAULT_DIALECT
72
+ use_g2p: bool = True
73
+ expected_mfa_version: str = MFA_VERSION
74
+ expected_kaldi_version: str = KALDI_VERSION
75
+ expected_kalpy_version: str = KALPY_VERSION
76
+ expected_openfst_version: str = OPENFST_VERSION
77
+ expected_model_sha256: str | None = None
78
+ num_jobs: int = 1
79
+ timeout_s: float = 3600.0
80
+ artifact_policy: ArtifactPolicyName = "never"
81
+ temporary_root: Path | None = None
82
+ retention_root: Path | None = None
83
+ run_id: str = "mfa-run"
84
+
85
+ def __post_init__(self) -> None:
86
+ """Enforce environment, identity, version, process, and artifact invariants.
87
+
88
+ Raises
89
+ ------
90
+ ConfigurationError: If a field is ambiguous, unpinned, or unsafe.
91
+
92
+ """
93
+ if not self.conda_executable.strip() or not self.mfa_executable.strip():
94
+ raise ConfigurationError(
95
+ "MFA Conda and executable commands cannot be empty"
96
+ )
97
+ if (self.environment_name is None) == (self.environment_prefix is None):
98
+ raise ConfigurationError(
99
+ "exactly one MFA Conda environment name or prefix is required"
100
+ )
101
+ if self.environment_name is not None and not re.fullmatch(
102
+ r"[A-Za-z0-9_.-]+", self.environment_name
103
+ ):
104
+ raise ConfigurationError("MFA environment_name is not a safe Conda name")
105
+ identity_fields = (
106
+ self.model_id,
107
+ self.model_version,
108
+ self.dialect,
109
+ self.expected_mfa_version,
110
+ self.expected_kaldi_version,
111
+ self.expected_kalpy_version,
112
+ self.expected_openfst_version,
113
+ )
114
+ if any(not value.strip() for value in identity_fields):
115
+ raise ConfigurationError(
116
+ "MFA model, dialect, and version fields cannot be empty"
117
+ )
118
+ if "@" in self.model_id or any(
119
+ character.isspace() for character in self.model_id
120
+ ):
121
+ raise ConfigurationError(
122
+ "MFA model_id must not contain a revision or whitespace"
123
+ )
124
+ if not re.fullmatch(r"[0-9a-f]{40}", self.model_revision):
125
+ raise ConfigurationError(
126
+ "MFA model_revision must be a full lowercase commit"
127
+ )
128
+ if not isinstance(self.use_g2p, bool):
129
+ raise ConfigurationError("MFA use_g2p must be a boolean")
130
+ if self.expected_model_sha256 is not None and not re.fullmatch(
131
+ r"[0-9a-f]{64}", self.expected_model_sha256
132
+ ):
133
+ raise ConfigurationError(
134
+ "MFA expected_model_sha256 must be lowercase SHA-256"
135
+ )
136
+ if (
137
+ isinstance(self.num_jobs, bool)
138
+ or not isinstance(self.num_jobs, int)
139
+ or self.num_jobs < 1
140
+ ):
141
+ raise ConfigurationError("MFA num_jobs must be a positive integer")
142
+ if (
143
+ isinstance(self.timeout_s, bool)
144
+ or not isinstance(self.timeout_s, (int, float))
145
+ or not math.isfinite(self.timeout_s)
146
+ or self.timeout_s <= 0
147
+ ):
148
+ raise ConfigurationError("MFA timeout_s must be finite and positive")
149
+ if self.artifact_policy not in {"never", "on_failure", "always"}:
150
+ raise ConfigurationError("MFA artifact_policy is invalid")
151
+ if self.artifact_policy != "never" and self.retention_root is None:
152
+ raise ConfigurationError(
153
+ "MFA retention_root is required when artifacts may be retained"
154
+ )
155
+ if (
156
+ not self.run_id
157
+ or Path(self.run_id).name != self.run_id
158
+ or self.run_id in {".", ".."}
159
+ ):
160
+ raise ConfigurationError("MFA run_id must be one safe path component")
161
+
162
+ @property
163
+ def model_spec(self) -> str:
164
+ """Return the immutable model argument passed to ``mfa align_hf``.
165
+
166
+ Returns
167
+ -------
168
+ Repository identifier suffixed by the configured commit revision.
169
+
170
+ """
171
+ return f"{self.model_id}@{self.model_revision}"
172
+
173
+ @classmethod
174
+ def from_mapping(cls, values: Mapping[str, object]) -> MfaConfig:
175
+ """Parse JSON-friendly CLI values into validated typed configuration.
176
+
177
+ Parameters
178
+ ----------
179
+ values: Configuration mapping with no unknown fields.
180
+
181
+ Returns
182
+ -------
183
+ Validated immutable MFA configuration.
184
+
185
+ Raises
186
+ ------
187
+ ConfigurationError: If keys or primitive field types are invalid.
188
+
189
+ """
190
+ allowed = {field_name for field_name in cls.__dataclass_fields__}
191
+ unknown = set(values).difference(allowed)
192
+ if unknown:
193
+ raise ConfigurationError(
194
+ f"unknown MFA configuration field: {sorted(unknown)[0]}"
195
+ )
196
+ data = dict(values)
197
+ if "environment_prefix" in data and "environment_name" not in data:
198
+ data["environment_name"] = None
199
+ for field_name in ("environment_prefix", "temporary_root", "retention_root"):
200
+ value = data.get(field_name)
201
+ if value is not None:
202
+ if not isinstance(value, (str, Path)) or not str(value):
203
+ raise ConfigurationError(
204
+ f"MFA {field_name} must be a non-empty path"
205
+ )
206
+ data[field_name] = Path(value)
207
+ string_fields = (
208
+ "conda_executable",
209
+ "environment_name",
210
+ "mfa_executable",
211
+ "model_id",
212
+ "model_revision",
213
+ "model_version",
214
+ "dialect",
215
+ "expected_mfa_version",
216
+ "expected_kaldi_version",
217
+ "expected_kalpy_version",
218
+ "expected_openfst_version",
219
+ "expected_model_sha256",
220
+ "artifact_policy",
221
+ "run_id",
222
+ )
223
+ for field_name in string_fields:
224
+ if (
225
+ field_name in data
226
+ and data[field_name] is not None
227
+ and not isinstance(data[field_name], str)
228
+ ):
229
+ raise ConfigurationError(f"MFA {field_name} must be a string or null")
230
+ if "use_g2p" in data and not isinstance(data["use_g2p"], bool):
231
+ raise ConfigurationError("MFA use_g2p must be a boolean")
232
+ if "num_jobs" in data and (
233
+ isinstance(data["num_jobs"], bool) or not isinstance(data["num_jobs"], int)
234
+ ):
235
+ raise ConfigurationError("MFA num_jobs must be an integer")
236
+ if "timeout_s" in data and (
237
+ isinstance(data["timeout_s"], bool)
238
+ or not isinstance(data["timeout_s"], (int, float))
239
+ ):
240
+ raise ConfigurationError("MFA timeout_s must be numeric")
241
+ return cls(
242
+ conda_executable=cast("str", data.get("conda_executable", "conda")),
243
+ environment_name=cast(
244
+ "str | None", data.get("environment_name", "speech-aligners-mfa")
245
+ ),
246
+ environment_prefix=cast("Path | None", data.get("environment_prefix")),
247
+ mfa_executable=cast("str", data.get("mfa_executable", "mfa")),
248
+ model_id=cast("str", data.get("model_id", DEFAULT_MODEL_ID)),
249
+ model_revision=cast(
250
+ "str", data.get("model_revision", DEFAULT_MODEL_REVISION)
251
+ ),
252
+ model_version=cast("str", data.get("model_version", DEFAULT_MODEL_VERSION)),
253
+ dialect=cast("str", data.get("dialect", DEFAULT_DIALECT)),
254
+ use_g2p=cast("bool", data.get("use_g2p", True)),
255
+ expected_mfa_version=cast(
256
+ "str", data.get("expected_mfa_version", MFA_VERSION)
257
+ ),
258
+ expected_kaldi_version=cast(
259
+ "str", data.get("expected_kaldi_version", KALDI_VERSION)
260
+ ),
261
+ expected_kalpy_version=cast(
262
+ "str", data.get("expected_kalpy_version", KALPY_VERSION)
263
+ ),
264
+ expected_openfst_version=cast(
265
+ "str", data.get("expected_openfst_version", OPENFST_VERSION)
266
+ ),
267
+ expected_model_sha256=cast("str | None", data.get("expected_model_sha256")),
268
+ num_jobs=cast("int", data.get("num_jobs", 1)),
269
+ timeout_s=float(cast("int | float", data.get("timeout_s", 3600.0))),
270
+ artifact_policy=cast(
271
+ "ArtifactPolicyName", data.get("artifact_policy", "never")
272
+ ),
273
+ temporary_root=cast("Path | None", data.get("temporary_root")),
274
+ retention_root=cast("Path | None", data.get("retention_root")),
275
+ run_id=cast("str", data.get("run_id", "mfa-run")),
276
+ )
277
+
278
+ def fingerprint_values(self) -> dict[str, object]:
279
+ """Return JSON-safe configuration values for receipt fingerprinting.
280
+
281
+ Returns
282
+ -------
283
+ All fields with optional filesystem paths converted to strings.
284
+
285
+ """
286
+ values = asdict(self)
287
+ for field_name in ("environment_prefix", "temporary_root", "retention_root"):
288
+ value = values[field_name]
289
+ values[field_name] = None if value is None else str(value)
290
+ return values
src/speech_text_data_aligners/backends/mfa/corpus.py ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Normalize reference text and materialize deterministic temporary MFA corpora."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import shutil
7
+ import unicodedata
8
+ from collections.abc import Sequence
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+
12
+ from speech_text_data_aligners.core.errors import AudioError, BackendOutputError
13
+ from speech_text_data_aligners.core.models import AlignmentRequest
14
+ from speech_text_data_aligners.core.normalization import TextPlan, make_text_plan
15
+
16
+ _CANONICAL_PUNCTUATION = str.maketrans(
17
+ {
18
+ "\u2018": "'",
19
+ "\u2019": "'",
20
+ "\u02bc": "'",
21
+ "\uff07": "'",
22
+ "\u2010": "-",
23
+ "\u2011": "-",
24
+ "\u2012": "-",
25
+ "\u2013": "-",
26
+ "\u2014": "-",
27
+ "\u2212": "-",
28
+ }
29
+ )
30
+ _ONES = (
31
+ "zero",
32
+ "one",
33
+ "two",
34
+ "three",
35
+ "four",
36
+ "five",
37
+ "six",
38
+ "seven",
39
+ "eight",
40
+ "nine",
41
+ )
42
+ _TEENS = (
43
+ "ten",
44
+ "eleven",
45
+ "twelve",
46
+ "thirteen",
47
+ "fourteen",
48
+ "fifteen",
49
+ "sixteen",
50
+ "seventeen",
51
+ "eighteen",
52
+ "nineteen",
53
+ )
54
+ _TENS = (
55
+ "",
56
+ "",
57
+ "twenty",
58
+ "thirty",
59
+ "forty",
60
+ "fifty",
61
+ "sixty",
62
+ "seventy",
63
+ "eighty",
64
+ "ninety",
65
+ )
66
+ _ORDINAL_ENDINGS = {
67
+ "one": "first",
68
+ "two": "second",
69
+ "three": "third",
70
+ "five": "fifth",
71
+ "eight": "eighth",
72
+ "nine": "ninth",
73
+ "twelve": "twelfth",
74
+ "twenty": "twentieth",
75
+ "thirty": "thirtieth",
76
+ "forty": "fortieth",
77
+ "fifty": "fiftieth",
78
+ "sixty": "sixtieth",
79
+ "seventy": "seventieth",
80
+ "eighty": "eightieth",
81
+ "ninety": "ninetieth",
82
+ "hundred": "hundredth",
83
+ "thousand": "thousandth",
84
+ "million": "millionth",
85
+ }
86
+
87
+
88
+ @dataclass(frozen=True, slots=True)
89
+ class MfaCorpusEntry:
90
+ """Associate one copied WAV/label pair with its request and text plan.
91
+
92
+ Parameters
93
+ ----------
94
+ request: Original backend-neutral request.
95
+ stem: Deterministic native file stem derived only from row ordinal.
96
+ wav_path: Workspace-local copied WAV path.
97
+ lab_path: Workspace-local normalized reference label path.
98
+ text_plan: Reversible mapping from emitted MFA tokens to original words.
99
+
100
+ """
101
+
102
+ request: AlignmentRequest
103
+ stem: str
104
+ wav_path: Path
105
+ lab_path: Path
106
+ text_plan: TextPlan
107
+
108
+
109
+ @dataclass(frozen=True, slots=True)
110
+ class MfaCorpus:
111
+ """Describe a materialized MFA corpus and its ordered row associations.
112
+
113
+ Parameters
114
+ ----------
115
+ path: Absolute flat corpus directory containing same-stem WAV/label pairs.
116
+ entries: Ordered request/native associations.
117
+
118
+ """
119
+
120
+ path: Path
121
+ entries: tuple[MfaCorpusEntry, ...]
122
+
123
+
124
+ def _under_thousand(value: int) -> tuple[str, ...]:
125
+ """Convert an integer below one thousand to English cardinal units.
126
+
127
+ Parameters
128
+ ----------
129
+ value: Integer in the inclusive range zero through 999.
130
+
131
+ Returns
132
+ -------
133
+ Space-delimited pronunciation units represented as a tuple.
134
+
135
+ """
136
+ if value < 10:
137
+ return (_ONES[value],)
138
+ if value < 20:
139
+ return (_TEENS[value - 10],)
140
+ if value < 100:
141
+ tens, remainder = divmod(value, 10)
142
+ return (_TENS[tens],) + (() if remainder == 0 else (_ONES[remainder],))
143
+ hundreds, remainder = divmod(value, 100)
144
+ return (_ONES[hundreds], "hundred") + (
145
+ () if remainder == 0 else _under_thousand(remainder)
146
+ )
147
+
148
+
149
+ def _cardinal_units(value: int) -> tuple[str, ...]:
150
+ """Convert a supported non-negative integer to English cardinal units.
151
+
152
+ Parameters
153
+ ----------
154
+ value: Integer from zero through 999,999,999.
155
+
156
+ Returns
157
+ -------
158
+ Deterministic English pronunciation units without conjunctions.
159
+
160
+ Raises
161
+ ------
162
+ BackendOutputError: If the integer exceeds the documented normalization range.
163
+
164
+ """
165
+ if value > 999_999_999:
166
+ raise BackendOutputError(
167
+ "MFA numeric token exceeds supported normalization range"
168
+ )
169
+ if value < 1000:
170
+ return _under_thousand(value)
171
+ units: list[str] = []
172
+ for scale, label in ((1_000_000, "million"), (1000, "thousand")):
173
+ quotient, value = divmod(value, scale)
174
+ if quotient:
175
+ units.extend(_under_thousand(quotient))
176
+ units.append(label)
177
+ if value:
178
+ units.extend(_under_thousand(value))
179
+ return tuple(units)
180
+
181
+
182
+ def _year_units(value: int) -> tuple[str, ...]:
183
+ """Convert a four-digit year-like value to conventional spoken units.
184
+
185
+ Parameters
186
+ ----------
187
+ value: Integer from 1001 through 2099, excluding round 1000.
188
+
189
+ Returns
190
+ -------
191
+ Conventional English year pronunciation such as ``nineteen sixty two``.
192
+
193
+ """
194
+ if value < 2000:
195
+ century, remainder = divmod(value, 100)
196
+ return _under_thousand(century) + (
197
+ ("hundred",) if remainder == 0 else _under_thousand(remainder)
198
+ )
199
+ if value < 2010:
200
+ return ("two", "thousand") + (
201
+ () if value == 2000 else _under_thousand(value - 2000)
202
+ )
203
+ return ("twenty",) + _under_thousand(value - 2000)
204
+
205
+
206
+ def _ordinal_units(value: int) -> tuple[str, ...]:
207
+ """Convert a supported integer to deterministic English ordinal units.
208
+
209
+ Parameters
210
+ ----------
211
+ value: Non-negative integer within the cardinal conversion range.
212
+
213
+ Returns
214
+ -------
215
+ English units with the final cardinal unit converted to ordinal form.
216
+
217
+ """
218
+ units = list(_cardinal_units(value))
219
+ final = units[-1]
220
+ units[-1] = _ORDINAL_ENDINGS.get(final, f"{final}th")
221
+ return tuple(units)
222
+
223
+
224
+ def _numeric_units(surface: str) -> tuple[str, ...] | None:
225
+ """Expand one numeric lexical surface when it uses a supported form.
226
+
227
+ Parameters
228
+ ----------
229
+ surface: Canonical case-folded lexical token.
230
+
231
+ Returns
232
+ -------
233
+ Pronunciation units for integers, decimals, and ordinal suffixes, or ``None``
234
+ when the surface is not numeric.
235
+
236
+ """
237
+ ordinal_match = re.fullmatch(r"(\d+)(st|nd|rd|th)", surface)
238
+ if ordinal_match:
239
+ return _ordinal_units(int(ordinal_match.group(1)))
240
+ if re.fullmatch(r"\d+\.\d+", surface):
241
+ integer, fractional = surface.split(".", maxsplit=1)
242
+ return (
243
+ _cardinal_units(int(integer))
244
+ + ("point",)
245
+ + tuple(_ONES[int(digit)] for digit in fractional)
246
+ )
247
+ if surface.isdecimal():
248
+ value = int(surface)
249
+ if len(surface) == 4 and 1000 < value < 2100:
250
+ return _year_units(value)
251
+ return _cardinal_units(value)
252
+ return None
253
+
254
+
255
+ def _normalized_units(surface: str) -> tuple[str, ...]:
256
+ """Normalize one original lexical surface for deterministic MFA input.
257
+
258
+ Parameters
259
+ ----------
260
+ surface: Exact original-facing lexical word.
261
+
262
+ Returns
263
+ -------
264
+ One or more whitespace-free lowercase MFA tokens. Hyphenated compounds and
265
+ dotted abbreviations expand to multiple owned units.
266
+
267
+ Raises
268
+ ------
269
+ BackendOutputError: If normalization cannot produce safe MFA units.
270
+
271
+ """
272
+ canonical = (
273
+ unicodedata.normalize("NFKC", surface)
274
+ .translate(_CANONICAL_PUNCTUATION)
275
+ .casefold()
276
+ )
277
+ if re.fullmatch(r"(?:[a-z]\.){2,}", canonical):
278
+ units = tuple(character for character in canonical if character.isalpha())
279
+ elif (numeric := _numeric_units(canonical)) is not None:
280
+ units = numeric
281
+ else:
282
+ units = tuple(part for part in canonical.split("-") if part)
283
+ if not units or any(
284
+ not unit or any(character.isspace() for character in unit) for unit in units
285
+ ):
286
+ raise BackendOutputError(
287
+ "MFA transcript normalization produced an invalid unit"
288
+ )
289
+ return units
290
+
291
+
292
+ def make_mfa_text_plan(transcript: str) -> TextPlan:
293
+ """Build MFA-normalized text with a reversible original-word mapping.
294
+
295
+ Parameters
296
+ ----------
297
+ transcript: Exact authoritative transcript.
298
+
299
+ Returns
300
+ -------
301
+ Text plan whose emitted text is punctuation-free at boundaries, case-folded,
302
+ and explicitly expanded where MFA pronunciation lookup benefits.
303
+
304
+ Raises
305
+ ------
306
+ TranscriptError: If common lexicalization finds no authoritative words.
307
+ BackendOutputError: If a lexical token cannot be normalized safely.
308
+
309
+ """
310
+ initial = make_text_plan(transcript)
311
+ expansions = {
312
+ word.index: _normalized_units(word.text) for word in initial.lexical_words
313
+ }
314
+ return make_text_plan(transcript, expansions=expansions)
315
+
316
+
317
+ def build_corpus(requests: Sequence[AlignmentRequest], path: Path) -> MfaCorpus:
318
+ """Copy WAVs and write normalized same-stem labels into a new flat corpus.
319
+
320
+ Parameters
321
+ ----------
322
+ requests: Non-empty ordered alignment requests with unique identities/audio.
323
+ path: New workspace-local corpus directory.
324
+
325
+ Returns
326
+ -------
327
+ Materialized corpus and deterministic ordinal associations.
328
+
329
+ Raises
330
+ ------
331
+ AudioError: If a source WAV is missing, duplicated, or not a regular file.
332
+ TranscriptError: If an authoritative transcript has no lexical words.
333
+ BackendOutputError: If identifiers duplicate or native artifacts cannot be
334
+ created.
335
+
336
+ Side Effects:
337
+ Creates ``path`` and copies source WAV bytes; source WAVs are never mutated.
338
+
339
+ """
340
+ if not requests:
341
+ raise BackendOutputError("MFA corpus requires at least one request")
342
+ try:
343
+ path.mkdir(parents=True, exist_ok=False)
344
+ except OSError as error:
345
+ raise BackendOutputError(
346
+ f"cannot create MFA corpus directory: {path}"
347
+ ) from error
348
+
349
+ entries: list[MfaCorpusEntry] = []
350
+ request_ids: set[str] = set()
351
+ audio_paths: set[Path] = set()
352
+ for ordinal, request in enumerate(requests):
353
+ if request.request_id in request_ids:
354
+ raise BackendOutputError("MFA corpus request identifiers are duplicated")
355
+ try:
356
+ source = request.audio_path.resolve(strict=True)
357
+ except (OSError, RuntimeError, ValueError) as error:
358
+ raise AudioError(f"WAV file is missing: {request.audio_path}") from error
359
+ if not source.is_file():
360
+ raise AudioError(f"WAV path is not a regular file: {request.audio_path}")
361
+ if source in audio_paths:
362
+ raise AudioError("MFA corpus audio paths are duplicated")
363
+ plan = make_mfa_text_plan(request.transcript)
364
+ stem = f"r{ordinal:06d}"
365
+ wav_path = path / f"{stem}.wav"
366
+ lab_path = path / f"{stem}.lab"
367
+ try:
368
+ shutil.copyfile(source, wav_path)
369
+ lab_path.write_text(
370
+ f"{plan.emitted_text}\n", encoding="utf-8", newline="\n"
371
+ )
372
+ except (OSError, UnicodeError) as error:
373
+ raise BackendOutputError(
374
+ f"cannot materialize MFA corpus row {ordinal}"
375
+ ) from error
376
+ entries.append(MfaCorpusEntry(request, stem, wav_path, lab_path, plan))
377
+ request_ids.add(request.request_id)
378
+ audio_paths.add(source)
379
+ return MfaCorpus(path.resolve(), tuple(entries))
src/speech_text_data_aligners/backends/mfa/runner.py ADDED
@@ -0,0 +1,495 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Probe and invoke MFA through the shared shell-free process abstraction."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+ from speech_text_data_aligners.backends.mfa.config import MfaConfig
11
+ from speech_text_data_aligners.core.errors import (
12
+ BackendExecutionError,
13
+ BackendOutputError,
14
+ BackendUnavailableError,
15
+ ConfigurationError,
16
+ )
17
+ from speech_text_data_aligners.runtime.process import (
18
+ Command,
19
+ CommandResult,
20
+ ProcessRunner,
21
+ SubprocessRunner,
22
+ )
23
+ from speech_text_data_aligners.runtime.receipts import sha256_file
24
+
25
+
26
+ @dataclass(frozen=True, slots=True)
27
+ class CondaPackageInfo:
28
+ """Record one exact package identity reported by the dedicated environment.
29
+
30
+ Parameters
31
+ ----------
32
+ name: Conda package name.
33
+ version: Installed package version.
34
+ build: Installed Conda build string.
35
+ channel: Source channel URL/name reported by Conda.
36
+
37
+ """
38
+
39
+ name: str
40
+ version: str
41
+ build: str
42
+ channel: str
43
+
44
+
45
+ @dataclass(frozen=True, slots=True)
46
+ class MfaRuntimeInfo:
47
+ """Capture exact relevant package versions from the selected Conda environment.
48
+
49
+ Parameters
50
+ ----------
51
+ python: Installed Python package identity.
52
+ mfa: Installed Montreal Forced Aligner package identity.
53
+ kaldi: Installed Kaldi package identity.
54
+ kalpy: Installed Kalpy package identity.
55
+ openfst: Installed OpenFst package identity.
56
+ environment: Explicit Conda name or absolute prefix used for execution.
57
+
58
+ """
59
+
60
+ python: CondaPackageInfo
61
+ mfa: CondaPackageInfo
62
+ kaldi: CondaPackageInfo
63
+ kalpy: CondaPackageInfo
64
+ openfst: CondaPackageInfo
65
+ environment: str
66
+
67
+
68
+ @dataclass(frozen=True, slots=True)
69
+ class MfaRun:
70
+ """Describe one completed MFA invocation and its reproducibility evidence.
71
+
72
+ Parameters
73
+ ----------
74
+ result: Captured MFA process streams, status, arguments, and duration.
75
+ runtime: Exact relevant package identities from the dedicated environment.
76
+ command_sha256: Hash of the canonical native argument vector.
77
+ model_sha256: Deterministic hash of all files in the resolved model snapshot.
78
+ dictionary_sha256: Hash of the selected dialect dictionary.
79
+ g2p_sha256: Tree hash of the selected dialect G2P model when enabled.
80
+ model_snapshot: Resolved Hugging Face cache snapshot directory.
81
+ stdout_log: Workspace-local complete MFA standard-output log.
82
+ stderr_log: Workspace-local complete MFA standard-error log.
83
+ package_log: Workspace-local exact Conda package-list JSON.
84
+
85
+ """
86
+
87
+ result: CommandResult
88
+ runtime: MfaRuntimeInfo
89
+ command_sha256: str
90
+ model_sha256: str
91
+ dictionary_sha256: str
92
+ g2p_sha256: str | None
93
+ model_snapshot: Path
94
+ stdout_log: Path
95
+ stderr_log: Path
96
+ package_log: Path
97
+
98
+
99
+ def _environment_arguments(config: MfaConfig) -> tuple[str, str]:
100
+ """Build the exact Conda selector shared by probe and execution commands.
101
+
102
+ Parameters
103
+ ----------
104
+ config: Validated MFA configuration.
105
+
106
+ Returns
107
+ -------
108
+ ``--name`` plus environment name, or ``--prefix`` plus absolute prefix.
109
+
110
+ """
111
+ if config.environment_prefix is not None:
112
+ return "--prefix", str(config.environment_prefix.resolve())
113
+ assert config.environment_name is not None
114
+ return "--name", config.environment_name
115
+
116
+
117
+ def _write_log(path: Path, text: str) -> None:
118
+ """Write one complete captured native stream as a UTF-8 diagnostic artifact.
119
+
120
+ Parameters
121
+ ----------
122
+ path: Workspace-local new log path.
123
+ text: Captured process text.
124
+
125
+ Raises
126
+ ------
127
+ BackendOutputError: If the diagnostic artifact cannot be written.
128
+
129
+ Side Effects:
130
+ Creates the parent directory and writes ``path``.
131
+
132
+ """
133
+ try:
134
+ path.parent.mkdir(parents=True, exist_ok=True)
135
+ path.write_text(text, encoding="utf-8", newline="\n")
136
+ except (OSError, UnicodeError) as error:
137
+ raise BackendOutputError(f"cannot write MFA diagnostic log: {path}") from error
138
+
139
+
140
+ def _package_info(payload: object, name: str) -> CondaPackageInfo:
141
+ """Extract one unique, complete package identity from Conda JSON.
142
+
143
+ Parameters
144
+ ----------
145
+ payload: Parsed ``conda list --json`` value.
146
+ name: Required package name.
147
+
148
+ Returns
149
+ -------
150
+ Exact installed package identity.
151
+
152
+ Raises
153
+ ------
154
+ BackendOutputError: If the package list is malformed, missing, or duplicated.
155
+
156
+ """
157
+ if not isinstance(payload, list):
158
+ raise BackendOutputError("MFA Conda package probe must return a JSON array")
159
+ matches = [
160
+ item for item in payload if isinstance(item, dict) and item.get("name") == name
161
+ ]
162
+ if len(matches) != 1:
163
+ raise BackendOutputError(f"MFA Conda package probe did not identify {name}")
164
+ item = matches[0]
165
+ required = ("name", "version", "build_string", "channel")
166
+ if any(
167
+ not isinstance(item.get(field), str) or not item[field] for field in required
168
+ ):
169
+ raise BackendOutputError(f"MFA Conda package identity for {name} is incomplete")
170
+ return CondaPackageInfo(
171
+ name=item["name"],
172
+ version=item["version"],
173
+ build=item["build_string"],
174
+ channel=item["channel"],
175
+ )
176
+
177
+
178
+ def _parse_package_probe(result: CommandResult, config: MfaConfig) -> MfaRuntimeInfo:
179
+ """Parse and validate exact pinned packages from a successful Conda probe.
180
+
181
+ Parameters
182
+ ----------
183
+ result: Captured ``conda list --json`` result.
184
+ config: Required package version pins and environment selector.
185
+
186
+ Returns
187
+ -------
188
+ Relevant exact runtime identities.
189
+
190
+ Raises
191
+ ------
192
+ BackendOutputError: If JSON/package records are malformed or incomplete.
193
+ BackendUnavailableError: If an installed version differs from its pin.
194
+
195
+ """
196
+ try:
197
+ payload = json.loads(result.stdout)
198
+ except json.JSONDecodeError as error:
199
+ raise BackendOutputError(
200
+ "MFA Conda package probe emitted malformed JSON"
201
+ ) from error
202
+ packages = {
203
+ "python": _package_info(payload, "python"),
204
+ "mfa": _package_info(payload, "montreal-forced-aligner"),
205
+ "kaldi": _package_info(payload, "kaldi"),
206
+ "kalpy": _package_info(payload, "kalpy"),
207
+ "openfst": _package_info(payload, "openfst"),
208
+ }
209
+ expected = {
210
+ "mfa": config.expected_mfa_version,
211
+ "kaldi": config.expected_kaldi_version,
212
+ "kalpy": config.expected_kalpy_version,
213
+ "openfst": config.expected_openfst_version,
214
+ }
215
+ for key, version in expected.items():
216
+ if packages[key].version != version:
217
+ raise BackendUnavailableError(
218
+ f"installed MFA {key} version does not match expected version {version}"
219
+ )
220
+ environment = _environment_arguments(config)[1]
221
+ return MfaRuntimeInfo(environment=environment, **packages)
222
+
223
+
224
+ def _alignment_command(
225
+ config: MfaConfig,
226
+ corpus_path: Path,
227
+ output_dir: Path,
228
+ temporary_dir: Path,
229
+ *,
230
+ mfa_root: Path,
231
+ huggingface_home: Path,
232
+ ) -> Command:
233
+ """Build the explicit revision-pinned ``mfa align_hf`` command.
234
+
235
+ Parameters
236
+ ----------
237
+ config: Validated MFA configuration.
238
+ corpus_path: Materialized flat MFA corpus.
239
+ output_dir: New aligned TextGrid output directory.
240
+ temporary_dir: Workspace-local MFA working directory.
241
+ mfa_root: Workspace-local MFA configuration/log root.
242
+ huggingface_home: Workspace-local Hugging Face cache root.
243
+
244
+ Returns
245
+ -------
246
+ Shell-free command using supplied reference labels, G2P policy, dialect, and
247
+ deterministic long-TextGrid output.
248
+
249
+ """
250
+ arguments = [
251
+ config.conda_executable,
252
+ "run",
253
+ "--no-capture-output",
254
+ *_environment_arguments(config),
255
+ config.mfa_executable,
256
+ "align_hf",
257
+ str(corpus_path.resolve()),
258
+ config.model_spec,
259
+ str(output_dir.resolve()),
260
+ "--dialect",
261
+ config.dialect,
262
+ "--output_format",
263
+ "long_textgrid",
264
+ "--no_tokenization",
265
+ "--temporary_directory",
266
+ str(temporary_dir.resolve()),
267
+ "--num_jobs",
268
+ str(config.num_jobs),
269
+ "--clean",
270
+ "--no_final_clean",
271
+ "--overwrite",
272
+ "--verbose",
273
+ "--no_use_postgres",
274
+ ]
275
+ if config.use_g2p:
276
+ arguments.append("--use_g2p")
277
+ return Command(
278
+ argv=tuple(arguments),
279
+ environment=(
280
+ ("MFA_ROOT_DIR", str(mfa_root.resolve())),
281
+ ("HF_HOME", str(huggingface_home.resolve())),
282
+ ),
283
+ timeout_s=config.timeout_s,
284
+ check=False,
285
+ )
286
+
287
+
288
+ def _hash_tree(path: Path) -> str:
289
+ """Hash a model directory by relative file names and content digests.
290
+
291
+ Parameters
292
+ ----------
293
+ path: Existing model directory; symbolic links are hashed by target content.
294
+
295
+ Returns
296
+ -------
297
+ Lowercase deterministic SHA-256 tree digest.
298
+
299
+ Raises
300
+ ------
301
+ BackendOutputError: If the directory is missing, empty, or unreadable.
302
+
303
+ """
304
+ if not path.is_dir():
305
+ raise BackendOutputError(f"MFA model directory is missing: {path}")
306
+ files = tuple(sorted(item for item in path.rglob("*") if item.is_file()))
307
+ if not files:
308
+ raise BackendOutputError(f"MFA model directory is empty: {path}")
309
+ digest = hashlib.sha256()
310
+ for file_path in files:
311
+ try:
312
+ file_hash = sha256_file(file_path)
313
+ except ConfigurationError as error:
314
+ raise BackendOutputError(
315
+ f"MFA model file is unreadable: {file_path}"
316
+ ) from error
317
+ digest.update(file_path.relative_to(path).as_posix().encode("utf-8"))
318
+ digest.update(b"\0")
319
+ digest.update(file_hash.encode("ascii"))
320
+ digest.update(b"\n")
321
+ return digest.hexdigest()
322
+
323
+
324
+ def _model_evidence(
325
+ config: MfaConfig, huggingface_home: Path
326
+ ) -> tuple[Path, str, str, str | None]:
327
+ """Locate and hash the exact downloaded model/dictionary/G2P snapshot.
328
+
329
+ Parameters
330
+ ----------
331
+ config: Commit-qualified model and selected dialect.
332
+ huggingface_home: Cache root supplied to the MFA subprocess.
333
+
334
+ Returns
335
+ -------
336
+ Snapshot path, bundle tree hash, dictionary hash, and optional G2P tree hash.
337
+
338
+ Raises
339
+ ------
340
+ BackendOutputError: If expected snapshot structure or metadata is absent.
341
+ BackendUnavailableError: If model version/hash differs from configuration.
342
+
343
+ """
344
+ repository = config.model_id.replace("/", "--")
345
+ snapshot = (
346
+ huggingface_home
347
+ / "hub"
348
+ / f"models--{repository}"
349
+ / "snapshots"
350
+ / config.model_revision
351
+ )
352
+ meta_path = snapshot / "acoustic" / "meta.json"
353
+ try:
354
+ metadata = json.loads(meta_path.read_text(encoding="utf-8"))
355
+ except (OSError, UnicodeError, json.JSONDecodeError) as error:
356
+ raise BackendOutputError(
357
+ "MFA model acoustic metadata is missing or malformed"
358
+ ) from error
359
+ if (
360
+ not isinstance(metadata, dict)
361
+ or metadata.get("version") != config.model_version
362
+ ):
363
+ raise BackendUnavailableError(
364
+ f"MFA model version does not match expected version {config.model_version}"
365
+ )
366
+ model_sha256 = _hash_tree(snapshot)
367
+ if (
368
+ config.expected_model_sha256 is not None
369
+ and model_sha256 != config.expected_model_sha256
370
+ ):
371
+ raise BackendUnavailableError(
372
+ "MFA model tree hash does not match configured pin"
373
+ )
374
+ dictionary_path = snapshot / "dictionary" / f"{config.dialect}.dict"
375
+ try:
376
+ dictionary_sha256 = sha256_file(dictionary_path)
377
+ except ConfigurationError as error:
378
+ raise BackendOutputError(
379
+ "MFA selected dialect dictionary is unavailable"
380
+ ) from error
381
+ g2p_sha256 = None
382
+ if config.use_g2p:
383
+ g2p_sha256 = _hash_tree(snapshot / "g2p" / config.dialect)
384
+ return snapshot.resolve(), model_sha256, dictionary_sha256, g2p_sha256
385
+
386
+
387
+ def run_mfa(
388
+ config: MfaConfig,
389
+ corpus_path: Path,
390
+ output_dir: Path,
391
+ runtime_dir: Path,
392
+ *,
393
+ process_runner: ProcessRunner | None = None,
394
+ ) -> MfaRun:
395
+ """Probe the dedicated Conda environment and execute one MFA corpus batch.
396
+
397
+ Parameters
398
+ ----------
399
+ config: Validated environment/model/dialect/process configuration.
400
+ corpus_path: Materialized reference-text corpus.
401
+ output_dir: Workspace-local native TextGrid output directory.
402
+ runtime_dir: Workspace-local root for MFA state, caches, work, and logs.
403
+ process_runner: Optional fake or alternate process boundary.
404
+
405
+ Returns
406
+ -------
407
+ Completed process evidence including exact packages and model hashes.
408
+
409
+ Raises
410
+ ------
411
+ BackendUnavailableError: If Conda/MFA/packages/model pins are unavailable.
412
+ BackendExecutionError: If the package probe or alignment exits non-zero.
413
+ BackendOutputError: If runtime/model evidence or diagnostic output is malformed.
414
+
415
+ Side Effects:
416
+ Creates runtime/output directories, downloads the revision-pinned model on a
417
+ cold cache, and writes complete process logs. It never imports MFA in-process.
418
+
419
+ """
420
+ if not corpus_path.is_dir():
421
+ raise BackendUnavailableError(f"MFA corpus is unavailable: {corpus_path}")
422
+ try:
423
+ output_dir.mkdir(parents=True, exist_ok=False)
424
+ runtime_dir.mkdir(parents=True, exist_ok=False)
425
+ except OSError as error:
426
+ raise BackendOutputError(
427
+ "cannot create MFA native runtime directories"
428
+ ) from error
429
+ runner = process_runner or SubprocessRunner()
430
+ package_log = runtime_dir / "conda-packages.json"
431
+ probe = runner.run(
432
+ Command(
433
+ argv=(
434
+ config.conda_executable,
435
+ "list",
436
+ "--json",
437
+ *_environment_arguments(config),
438
+ ),
439
+ timeout_s=config.timeout_s,
440
+ check=False,
441
+ )
442
+ )
443
+ _write_log(package_log, probe.stdout)
444
+ _write_log(runtime_dir / "conda-packages.stderr.log", probe.stderr)
445
+ if probe.returncode != 0:
446
+ raise BackendExecutionError(
447
+ f"MFA Conda package probe exited with status {probe.returncode}"
448
+ )
449
+ runtime = _parse_package_probe(probe, config)
450
+
451
+ mfa_root = runtime_dir / "mfa-root"
452
+ huggingface_home = runtime_dir / "huggingface"
453
+ temporary_dir = runtime_dir / "work"
454
+ for directory in (mfa_root, huggingface_home, temporary_dir):
455
+ directory.mkdir(parents=True, exist_ok=True)
456
+ command = _alignment_command(
457
+ config,
458
+ corpus_path,
459
+ output_dir,
460
+ temporary_dir,
461
+ mfa_root=mfa_root,
462
+ huggingface_home=huggingface_home,
463
+ )
464
+ result = runner.run(command)
465
+ stdout_log = runtime_dir / "mfa.stdout.log"
466
+ stderr_log = runtime_dir / "mfa.stderr.log"
467
+ _write_log(stdout_log, result.stdout)
468
+ _write_log(stderr_log, result.stderr)
469
+ if result.returncode != 0:
470
+ raise BackendExecutionError(
471
+ f"Montreal Forced Aligner exited with status {result.returncode}",
472
+ context=(
473
+ ("returncode", result.returncode),
474
+ ("stdout_log", str(stdout_log)),
475
+ ("stderr_log", str(stderr_log)),
476
+ ),
477
+ )
478
+ snapshot, model_hash, dictionary_hash, g2p_hash = _model_evidence(
479
+ config, huggingface_home
480
+ )
481
+ command_payload = json.dumps(
482
+ command.argv, ensure_ascii=False, separators=(",", ":")
483
+ ).encode()
484
+ return MfaRun(
485
+ result=result,
486
+ runtime=runtime,
487
+ command_sha256=hashlib.sha256(command_payload).hexdigest(),
488
+ model_sha256=model_hash,
489
+ dictionary_sha256=dictionary_hash,
490
+ g2p_sha256=g2p_hash,
491
+ model_snapshot=snapshot,
492
+ stdout_log=stdout_log,
493
+ stderr_log=stderr_log,
494
+ package_log=package_log,
495
+ )
src/speech_text_data_aligners/backends/mfa/textgrid.py ADDED
@@ -0,0 +1,496 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Parse MFA word tiers and map native intervals to authoritative lexical words."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import re
7
+ from dataclasses import dataclass
8
+ from decimal import Decimal, InvalidOperation
9
+ from pathlib import Path
10
+
11
+ from speech_text_data_aligners.core.errors import (
12
+ BackendOutputError,
13
+ TranscriptError,
14
+ TranscriptMappingError,
15
+ )
16
+ from speech_text_data_aligners.core.models import WordAlignment
17
+ from speech_text_data_aligners.core.normalization import (
18
+ ObservedWordUnit,
19
+ TextPlan,
20
+ lexicalize,
21
+ reconcile_word_units,
22
+ )
23
+
24
+ _SILENCE_LABELS = frozenset({"", "<eps>", "<sil>", "sil", "sp"})
25
+ _OOV_LABELS = frozenset({"<unk>", "<oov>", "spn"})
26
+
27
+
28
+ @dataclass(frozen=True, slots=True)
29
+ class _Interval:
30
+ """Hold one parsed native interval before lexical filtering.
31
+
32
+ Parameters
33
+ ----------
34
+ index: One-based native interval position.
35
+ start_s: Native interval start in seconds.
36
+ end_s: Native interval end in seconds.
37
+ text: Exact unescaped native label.
38
+
39
+ """
40
+
41
+ index: int
42
+ start_s: float
43
+ end_s: float
44
+ text: str
45
+
46
+
47
+ def _unquote(value: str, *, context: str) -> str:
48
+ """Decode one Praat quoted string with doubled-quote escaping.
49
+
50
+ Parameters
51
+ ----------
52
+ value: Quoted token, optionally following a long-format assignment.
53
+ context: Safe field description for parse diagnostics.
54
+
55
+ Returns
56
+ -------
57
+ Unescaped string value.
58
+
59
+ Raises
60
+ ------
61
+ BackendOutputError: If quoting or doubled-quote escaping is malformed.
62
+
63
+ """
64
+ token = value.split("=", maxsplit=1)[-1].strip()
65
+ if len(token) < 2 or not token.startswith('"') or not token.endswith('"'):
66
+ raise BackendOutputError(f"MFA TextGrid {context} is not a quoted string")
67
+ body = token[1:-1]
68
+ result: list[str] = []
69
+ cursor = 0
70
+ while cursor < len(body):
71
+ if body[cursor] != '"':
72
+ result.append(body[cursor])
73
+ cursor += 1
74
+ continue
75
+ if cursor + 1 >= len(body) or body[cursor + 1] != '"':
76
+ raise BackendOutputError(f"MFA TextGrid {context} has malformed quoting")
77
+ result.append('"')
78
+ cursor += 2
79
+ return "".join(result)
80
+
81
+
82
+ def _decimal(value: str, *, context: str) -> Decimal:
83
+ """Parse one finite non-negative TextGrid decimal.
84
+
85
+ Parameters
86
+ ----------
87
+ value: Numeric token, optionally following an assignment.
88
+ context: Safe field description for parse diagnostics.
89
+
90
+ Returns
91
+ -------
92
+ Exact finite non-negative decimal value.
93
+
94
+ Raises
95
+ ------
96
+ BackendOutputError: If the token is malformed, negative, or non-finite.
97
+
98
+ """
99
+ token = value.split("=", maxsplit=1)[-1].strip()
100
+ try:
101
+ parsed = Decimal(token)
102
+ except InvalidOperation as error:
103
+ raise BackendOutputError(f"MFA TextGrid {context} is not numeric") from error
104
+ if not parsed.is_finite() or parsed < 0:
105
+ raise BackendOutputError(f"MFA TextGrid {context} is negative or non-finite")
106
+ return parsed
107
+
108
+
109
+ def _count(value: str, *, context: str) -> int:
110
+ """Parse one non-negative integer TextGrid size/index value.
111
+
112
+ Parameters
113
+ ----------
114
+ value: Integer token, optionally following an assignment.
115
+ context: Safe field description for parse diagnostics.
116
+
117
+ Returns
118
+ -------
119
+ Non-negative integer.
120
+
121
+ Raises
122
+ ------
123
+ BackendOutputError: If the token is not a non-negative integer.
124
+
125
+ """
126
+ token = value.split("=", maxsplit=1)[-1].strip()
127
+ if not token.isdecimal():
128
+ raise BackendOutputError(f"MFA TextGrid {context} is not an integer")
129
+ return int(token)
130
+
131
+
132
+ def _assignment(lines: list[str], name: str, *, context: str) -> str:
133
+ """Find exactly one named long-format assignment in a line block.
134
+
135
+ Parameters
136
+ ----------
137
+ lines: Long-format tier or interval lines.
138
+ name: Literal assignment name.
139
+ context: Safe block description for diagnostics.
140
+
141
+ Returns
142
+ -------
143
+ Right-hand source token including any whitespace.
144
+
145
+ Raises
146
+ ------
147
+ BackendOutputError: If the assignment is missing or duplicated.
148
+
149
+ """
150
+ pattern = re.compile(rf"^\s*{re.escape(name)}\s*=\s*(.*?)\s*$")
151
+ matches = [match.group(1) for line in lines if (match := pattern.match(line))]
152
+ if len(matches) != 1:
153
+ raise BackendOutputError(
154
+ f"MFA TextGrid {context} must contain one {name} assignment"
155
+ )
156
+ return matches[0]
157
+
158
+
159
+ def _validate_intervals(
160
+ intervals: tuple[_Interval, ...], *, tier_min: Decimal, tier_max: Decimal
161
+ ) -> tuple[_Interval, ...]:
162
+ """Validate word-tier interval bounds and monotonic non-overlap.
163
+
164
+ Parameters
165
+ ----------
166
+ intervals: Parsed intervals in native order.
167
+ tier_min: Declared tier minimum.
168
+ tier_max: Declared tier maximum.
169
+
170
+ Returns
171
+ -------
172
+ Unchanged intervals when all timing invariants hold.
173
+
174
+ Raises
175
+ ------
176
+ BackendOutputError: If tier bounds or interval timing is invalid.
177
+
178
+ """
179
+ if tier_min > tier_max:
180
+ raise BackendOutputError("MFA TextGrid word tier has reversed bounds")
181
+ previous_end = tier_min
182
+ for interval in intervals:
183
+ start = Decimal(str(interval.start_s))
184
+ end = Decimal(str(interval.end_s))
185
+ if start > end:
186
+ raise BackendOutputError("MFA TextGrid word interval is reversed")
187
+ if start < tier_min or end > tier_max:
188
+ raise BackendOutputError("MFA TextGrid word interval exceeds tier bounds")
189
+ if start < previous_end:
190
+ raise BackendOutputError(
191
+ "MFA TextGrid word intervals overlap or are non-monotonic"
192
+ )
193
+ previous_end = end
194
+ return intervals
195
+
196
+
197
+ def _long_word_tier(lines: list[str]) -> tuple[_Interval, ...]:
198
+ """Parse exactly one ``words`` IntervalTier from long TextGrid lines.
199
+
200
+ Parameters
201
+ ----------
202
+ lines: Complete non-empty source lines including the header.
203
+
204
+ Returns
205
+ -------
206
+ Ordered native word-tier intervals, including empty intervals.
207
+
208
+ Raises
209
+ ------
210
+ BackendOutputError: If item/tier/interval structure is malformed.
211
+
212
+ """
213
+ item_starts = [
214
+ index
215
+ for index, line in enumerate(lines)
216
+ if re.fullmatch(r"\s*item \[\d+\]:\s*", line)
217
+ ]
218
+ if not item_starts:
219
+ raise BackendOutputError("MFA TextGrid long format contains no tiers")
220
+ word_blocks: list[list[str]] = []
221
+ for ordinal, start in enumerate(item_starts):
222
+ stop = (
223
+ item_starts[ordinal + 1] if ordinal + 1 < len(item_starts) else len(lines)
224
+ )
225
+ block = lines[start:stop]
226
+ tier_class = _unquote(
227
+ _assignment(block, "class", context="tier"), context="tier class"
228
+ )
229
+ tier_name = _unquote(
230
+ _assignment(block, "name", context="tier"), context="tier name"
231
+ )
232
+ if tier_name.casefold() == "words":
233
+ if tier_class != "IntervalTier":
234
+ raise BackendOutputError(
235
+ "MFA TextGrid words tier is not an IntervalTier"
236
+ )
237
+ word_blocks.append(block)
238
+ if len(word_blocks) != 1:
239
+ raise BackendOutputError("MFA TextGrid must contain exactly one words tier")
240
+
241
+ block = word_blocks[0]
242
+ starts = [
243
+ index
244
+ for index, line in enumerate(block)
245
+ if re.fullmatch(r"\s*intervals \[\d+\]:\s*", line)
246
+ ]
247
+ header = block[: starts[0] if starts else len(block)]
248
+ tier_min = _decimal(
249
+ _assignment(header, "xmin", context="words tier"), context="word-tier xmin"
250
+ )
251
+ tier_max = _decimal(
252
+ _assignment(header, "xmax", context="words tier"), context="word-tier xmax"
253
+ )
254
+ size_pattern = re.compile(r"^\s*intervals:\s*size\s*=\s*(\d+)\s*$")
255
+ sizes = [
256
+ int(match.group(1)) for line in header if (match := size_pattern.match(line))
257
+ ]
258
+ if len(sizes) != 1:
259
+ raise BackendOutputError("MFA TextGrid words tier has malformed interval size")
260
+ if len(starts) != sizes[0]:
261
+ raise BackendOutputError(
262
+ "MFA TextGrid words tier interval count is inconsistent"
263
+ )
264
+ intervals: list[_Interval] = []
265
+ for ordinal, start in enumerate(starts, start=1):
266
+ match = re.fullmatch(r"\s*intervals \[(\d+)\]:\s*", block[start])
267
+ assert match is not None
268
+ if int(match.group(1)) != ordinal:
269
+ raise BackendOutputError(
270
+ "MFA TextGrid word interval indices are non-sequential"
271
+ )
272
+ stop = starts[ordinal] if ordinal < len(starts) else len(block)
273
+ interval_lines = block[start:stop]
274
+ interval_start = _decimal(
275
+ _assignment(interval_lines, "xmin", context="word interval"),
276
+ context="word interval xmin",
277
+ )
278
+ interval_end = _decimal(
279
+ _assignment(interval_lines, "xmax", context="word interval"),
280
+ context="word interval xmax",
281
+ )
282
+ label = _unquote(
283
+ _assignment(interval_lines, "text", context="word interval"),
284
+ context="word interval text",
285
+ )
286
+ intervals.append(
287
+ _Interval(ordinal, float(interval_start), float(interval_end), label)
288
+ )
289
+ return _validate_intervals(tuple(intervals), tier_min=tier_min, tier_max=tier_max)
290
+
291
+
292
+ def _short_word_tier(lines: list[str]) -> tuple[_Interval, ...]:
293
+ """Parse exactly one ``words`` IntervalTier from short TextGrid lines.
294
+
295
+ Parameters
296
+ ----------
297
+ lines: Complete non-empty short-format source lines including the header.
298
+
299
+ Returns
300
+ -------
301
+ Ordered native word-tier intervals, including empty intervals.
302
+
303
+ Raises
304
+ ------
305
+ BackendOutputError: If tier counts, types, fields, or bounds are malformed.
306
+
307
+ """
308
+ if len(lines) < 6:
309
+ raise BackendOutputError("MFA short TextGrid is incomplete")
310
+ grid_min = _decimal(lines[2], context="grid xmin")
311
+ grid_max = _decimal(lines[3], context="grid xmax")
312
+ if lines[4].strip() != "<exists>" or grid_min > grid_max:
313
+ raise BackendOutputError("MFA short TextGrid has malformed grid bounds")
314
+ tier_count = _count(lines[5], context="tier count")
315
+ cursor = 6
316
+ found: list[tuple[tuple[_Interval, ...], Decimal, Decimal]] = []
317
+ for _ in range(tier_count):
318
+ if cursor + 5 > len(lines):
319
+ raise BackendOutputError("MFA short TextGrid tier header is incomplete")
320
+ tier_class = _unquote(lines[cursor], context="tier class")
321
+ tier_name = _unquote(lines[cursor + 1], context="tier name")
322
+ tier_min = _decimal(lines[cursor + 2], context="tier xmin")
323
+ tier_max = _decimal(lines[cursor + 3], context="tier xmax")
324
+ entry_count = _count(lines[cursor + 4], context="tier entry count")
325
+ cursor += 5
326
+ if tier_class == "IntervalTier":
327
+ needed = entry_count * 3
328
+ if cursor + needed > len(lines):
329
+ raise BackendOutputError(
330
+ "MFA short TextGrid interval data is incomplete"
331
+ )
332
+ intervals = tuple(
333
+ _Interval(
334
+ index + 1,
335
+ float(_decimal(lines[cursor + index * 3], context="interval xmin")),
336
+ float(
337
+ _decimal(lines[cursor + index * 3 + 1], context="interval xmax")
338
+ ),
339
+ _unquote(lines[cursor + index * 3 + 2], context="interval text"),
340
+ )
341
+ for index in range(entry_count)
342
+ )
343
+ cursor += needed
344
+ elif tier_class == "TextTier":
345
+ needed = entry_count * 2
346
+ if cursor + needed > len(lines):
347
+ raise BackendOutputError("MFA short TextGrid point data is incomplete")
348
+ cursor += needed
349
+ intervals = ()
350
+ else:
351
+ raise BackendOutputError(
352
+ "MFA short TextGrid contains an unsupported tier class"
353
+ )
354
+ if tier_name.casefold() == "words":
355
+ if tier_class != "IntervalTier":
356
+ raise BackendOutputError(
357
+ "MFA TextGrid words tier is not an IntervalTier"
358
+ )
359
+ found.append((intervals, tier_min, tier_max))
360
+ if cursor != len(lines):
361
+ raise BackendOutputError("MFA short TextGrid contains trailing data")
362
+ if len(found) != 1:
363
+ raise BackendOutputError("MFA TextGrid must contain exactly one words tier")
364
+ intervals, tier_min, tier_max = found[0]
365
+ return _validate_intervals(intervals, tier_min=tier_min, tier_max=tier_max)
366
+
367
+
368
+ def _read_word_tier(path: Path) -> tuple[_Interval, ...]:
369
+ """Read a TextGrid and route its long/short body to the strict parser.
370
+
371
+ Parameters
372
+ ----------
373
+ path: Native aligned TextGrid path.
374
+
375
+ Returns
376
+ -------
377
+ Parsed word-tier intervals.
378
+
379
+ Raises
380
+ ------
381
+ BackendOutputError: If the file/header/encoding/body is missing or malformed.
382
+
383
+ """
384
+ try:
385
+ lines = [
386
+ line
387
+ for line in path.read_text(encoding="utf-8-sig").splitlines()
388
+ if line.strip()
389
+ ]
390
+ except (OSError, UnicodeError) as error:
391
+ raise BackendOutputError(
392
+ f"MFA TextGrid is missing or unreadable: {path}"
393
+ ) from error
394
+ if len(lines) < 2:
395
+ raise BackendOutputError("MFA TextGrid header is incomplete")
396
+ file_type = _unquote(lines[0], context="file type")
397
+ object_class = _unquote(lines[1], context="object class")
398
+ if (
399
+ file_type not in {"ooTextFile", "ooTextFile short"}
400
+ or object_class != "TextGrid"
401
+ ):
402
+ raise BackendOutputError("MFA TextGrid header is invalid")
403
+ if len(lines) > 2 and re.match(r"^\s*xmin\s*=", lines[2]):
404
+ return _long_word_tier(lines)
405
+ return _short_word_tier(lines)
406
+
407
+
408
+ def _mapping_surface(label: str, *, interval_index: int) -> tuple[str, bool]:
409
+ """Convert one native word label to a comparison surface.
410
+
411
+ Parameters
412
+ ----------
413
+ label: Exact non-silence TextGrid interval label.
414
+ interval_index: One-based interval position for diagnostics.
415
+
416
+ Returns
417
+ -------
418
+ Single lexical surface and whether it is punctuation-only/ignorable.
419
+
420
+ Raises
421
+ ------
422
+ TranscriptMappingError: If the label is an OOV marker or contains multiple
423
+ lexical words.
424
+
425
+ """
426
+ if label.casefold() in _OOV_LABELS:
427
+ raise TranscriptMappingError(
428
+ f"MFA word interval {interval_index} contains an unresolved OOV marker"
429
+ )
430
+ try:
431
+ words = lexicalize(label)
432
+ except TranscriptError:
433
+ return label, True
434
+ if len(words) != 1:
435
+ raise TranscriptMappingError(
436
+ f"MFA word interval {interval_index} contains multiple lexical words"
437
+ )
438
+ return words[0].text, False
439
+
440
+
441
+ def parse_word_textgrid(path: Path, text_plan: TextPlan) -> tuple[WordAlignment, ...]:
442
+ """Parse one MFA TextGrid word tier and reconcile it to original words.
443
+
444
+ Empty and explicit silence intervals are ignored. Punctuation-only intervals are
445
+ explicitly authorized as ignorable observations; unresolved OOV markers, malformed
446
+ tiers, incomplete mappings, overlaps, and non-finite timings fail without guessed
447
+ timestamps.
448
+
449
+ Parameters
450
+ ----------
451
+ path: MFA long- or short-format TextGrid output.
452
+ text_plan: Exact normalized-to-authoritative mapping used to create the label.
453
+
454
+ Returns
455
+ -------
456
+ One ordered backend-neutral alignment per authoritative lexical word.
457
+
458
+ Raises
459
+ ------
460
+ BackendOutputError: If native TextGrid structure or timing is invalid.
461
+ TranscriptMappingError: If native word labels cannot map exactly and
462
+ monotonically to the text plan.
463
+
464
+ """
465
+ intervals = _read_word_tier(path)
466
+ observed: list[ObservedWordUnit] = []
467
+ ignorable: set[int] = set()
468
+ for interval in intervals:
469
+ if interval.text.strip().casefold() in _SILENCE_LABELS:
470
+ continue
471
+ if not math.isfinite(interval.start_s) or not math.isfinite(interval.end_s):
472
+ raise BackendOutputError("MFA word interval has non-finite timing")
473
+ surface, punctuation_only = _mapping_surface(
474
+ interval.text, interval_index=interval.index
475
+ )
476
+ observed.append(
477
+ ObservedWordUnit(
478
+ text=surface,
479
+ start_s=interval.start_s,
480
+ end_s=interval.end_s,
481
+ attributes=(
482
+ ("native_text", interval.text),
483
+ ("tier", "words"),
484
+ ("interval_index", interval.index),
485
+ ),
486
+ )
487
+ )
488
+ if punctuation_only:
489
+ ignorable.add(len(observed) - 1)
490
+ if not observed:
491
+ raise BackendOutputError(
492
+ "MFA TextGrid words tier contains no lexical intervals"
493
+ )
494
+ return reconcile_word_units(
495
+ text_plan, observed, ignorable_observed_indices=ignorable
496
+ )
tests/architecture/test_import_boundaries.py CHANGED
@@ -71,6 +71,23 @@ def test_nemo_backend_imports_no_outer_or_sibling_backend_layer() -> None:
71
  ), f"{module_name(path)} illegally imports {prefix}"
72
 
73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  def test_registry_contains_exact_dotted_factories_but_no_static_backend_imports() -> (
75
  None
76
  ):
 
71
  ), f"{module_name(path)} illegally imports {prefix}"
72
 
73
 
74
+ def test_mfa_backend_imports_no_outer_or_sibling_backend_layer() -> None:
75
+ forbidden = (
76
+ "speech_text_data_aligners.application",
77
+ "speech_text_data_aligners.benchmarking",
78
+ "speech_text_data_aligners.cli",
79
+ "speech_text_data_aligners.data",
80
+ "speech_text_data_aligners.backends.nemo",
81
+ "speech_text_data_aligners.backends.whisperx",
82
+ )
83
+ for path in (PACKAGE_ROOT / "backends" / "mfa").glob("*.py"):
84
+ imports = imported_modules(path)
85
+ for prefix in forbidden:
86
+ assert not any(
87
+ name == prefix or name.startswith(f"{prefix}.") for name in imports
88
+ ), f"{module_name(path)} illegally imports {prefix}"
89
+
90
+
91
  def test_registry_contains_exact_dotted_factories_but_no_static_backend_imports() -> (
92
  None
93
  ):
tests/integration/mfa/test_mfa_real.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from pathlib import Path
5
+
6
+ import pytest
7
+
8
+ from speech_text_data_aligners.backends.mfa.backend import MfaBackend
9
+ from speech_text_data_aligners.backends.mfa.config import MfaConfig
10
+ from speech_text_data_aligners.core.normalization import lexicalize
11
+ from speech_text_data_aligners.data.audio import make_alignment_request
12
+
13
+ pytestmark = [pytest.mark.integration, pytest.mark.mfa]
14
+
15
+
16
+ def test_real_mfa_aligns_one_authoritative_transcript() -> None:
17
+ if os.environ.get("RUN_MFA_INTEGRATION") != "1":
18
+ pytest.skip("set RUN_MFA_INTEGRATION=1 to invoke the isolated MFA runtime")
19
+ prefix = os.environ.get("MFA_CONDA_PREFIX")
20
+ wav_value = os.environ.get("MFA_SMOKE_WAV")
21
+ transcript = os.environ.get("MFA_SMOKE_TRANSCRIPT")
22
+ if not prefix or not wav_value or not transcript:
23
+ pytest.skip(
24
+ "MFA_CONDA_PREFIX, MFA_SMOKE_WAV, and MFA_SMOKE_TRANSCRIPT are required"
25
+ )
26
+
27
+ request = make_alignment_request(
28
+ request_id="mfa-smoke",
29
+ audio_path=Path(wav_value),
30
+ transcript=transcript,
31
+ )
32
+ result = MfaBackend(
33
+ MfaConfig(
34
+ environment_name=None,
35
+ environment_prefix=Path(prefix),
36
+ run_id="mfa-integration-smoke",
37
+ )
38
+ ).align(request)
39
+
40
+ assert result.request_id == request.request_id
41
+ assert tuple(item.lexical_word for item in result.words) == lexicalize(transcript)
42
+ assert result.provenance.backend_name == "mfa"
43
+ assert result.provenance.model_sha256
tests/quality/test_per_file_coverage.py CHANGED
@@ -12,6 +12,7 @@ EMPTY_MARKERS = {
12
  PACKAGE_ROOT / "runtime" / "__init__.py",
13
  PACKAGE_ROOT / "backends" / "__init__.py",
14
  PACKAGE_ROOT / "backends" / "nemo" / "__init__.py",
 
15
  PACKAGE_ROOT / "cli" / "__init__.py",
16
  }
17
  SHARED_PREFIXES = ("core/", "data/", "application/", "benchmarking/", "runtime/")
 
12
  PACKAGE_ROOT / "runtime" / "__init__.py",
13
  PACKAGE_ROOT / "backends" / "__init__.py",
14
  PACKAGE_ROOT / "backends" / "nemo" / "__init__.py",
15
+ PACKAGE_ROOT / "backends" / "mfa" / "__init__.py",
16
  PACKAGE_ROOT / "cli" / "__init__.py",
17
  }
18
  SHARED_PREFIXES = ("core/", "data/", "application/", "benchmarking/", "runtime/")
tests/unit/backends/mfa/test_backend.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ from pathlib import Path
5
+
6
+ import pytest
7
+
8
+ from speech_text_data_aligners.backends.mfa import backend as backend_module
9
+ from speech_text_data_aligners.backends.mfa.backend import MfaBackend, create_backend
10
+ from speech_text_data_aligners.backends.mfa.config import MfaConfig
11
+ from speech_text_data_aligners.backends.mfa.runner import (
12
+ CondaPackageInfo,
13
+ MfaRun,
14
+ MfaRuntimeInfo,
15
+ )
16
+ from speech_text_data_aligners.core.errors import (
17
+ AlignmentValidationError,
18
+ AudioError,
19
+ BackendExecutionError,
20
+ BackendOutputError,
21
+ TranscriptMappingError,
22
+ )
23
+ from speech_text_data_aligners.core.models import AlignmentRequest, DiagnosticSeverity
24
+ from speech_text_data_aligners.core.protocols import AlignmentBackend
25
+ from speech_text_data_aligners.runtime.process import CommandResult
26
+
27
+
28
+ def textgrid(words: list[str], *, duration: float = 3.0, offset: float = 0.0) -> str:
29
+ intervals: list[tuple[float, float, str]] = [(0.0, offset + 0.1, "")]
30
+ for index, word in enumerate(words):
31
+ intervals.append((offset + 0.1 + index * 0.2, offset + 0.3 + index * 0.2, word))
32
+ intervals.append((intervals[-1][1], duration, ""))
33
+ lines = [
34
+ 'File type = "ooTextFile"',
35
+ 'Object class = "TextGrid"',
36
+ "",
37
+ "xmin = 0",
38
+ f"xmax = {duration}",
39
+ "tiers? <exists>",
40
+ "size = 1",
41
+ "item []:",
42
+ " item [1]:",
43
+ ' class = "IntervalTier"',
44
+ ' name = "words"',
45
+ " xmin = 0",
46
+ f" xmax = {duration}",
47
+ f" intervals: size = {len(intervals)}",
48
+ ]
49
+ for index, (start, end, label) in enumerate(intervals, start=1):
50
+ lines.extend(
51
+ [
52
+ f" intervals [{index}]:",
53
+ f" xmin = {start}",
54
+ f" xmax = {end}",
55
+ f' text = "{label}"',
56
+ ]
57
+ )
58
+ return "\n".join(lines) + "\n"
59
+
60
+
61
+ def package(name: str, version: str) -> CondaPackageInfo:
62
+ return CondaPackageInfo(name, version, f"build-{name}", "conda-forge")
63
+
64
+
65
+ class MaterializingMfa:
66
+ def __init__(
67
+ self,
68
+ *,
69
+ bad_stems: set[str] | None = None,
70
+ missing_stems: set[str] | None = None,
71
+ invalid_stems: set[str] | None = None,
72
+ fail: bool = False,
73
+ duration_s: float = 4.0,
74
+ ) -> None:
75
+ self.bad_stems = bad_stems or set()
76
+ self.missing_stems = missing_stems or set()
77
+ self.invalid_stems = invalid_stems or set()
78
+ self.fail = fail
79
+ self.duration_s = duration_s
80
+ self.calls: list[tuple[Path, Path, Path]] = []
81
+
82
+ def __call__(
83
+ self,
84
+ config: MfaConfig,
85
+ corpus_path: Path,
86
+ output_dir: Path,
87
+ runtime_dir: Path,
88
+ *,
89
+ process_runner: object,
90
+ ) -> MfaRun:
91
+ self.calls.append((corpus_path, output_dir, runtime_dir))
92
+ runtime_dir.mkdir()
93
+ (runtime_dir / "mfa.stdout.log").write_text("stdout")
94
+ (runtime_dir / "mfa.stderr.log").write_text("stderr")
95
+ (runtime_dir / "conda-packages.json").write_text("[]")
96
+ if self.fail:
97
+ raise BackendExecutionError("simulated MFA failure", retryable=True)
98
+ output_dir.mkdir()
99
+ for lab in sorted(corpus_path.glob("*.lab")):
100
+ if lab.stem in self.missing_stems:
101
+ continue
102
+ words = lab.read_text().split()
103
+ if lab.stem in self.bad_stems:
104
+ words[0] = "mismatch"
105
+ invalid = lab.stem in self.invalid_stems
106
+ duration = 10.0 if invalid else 3.0
107
+ (output_dir / f"{lab.stem}.TextGrid").write_text(
108
+ textgrid(words, duration=duration, offset=4.0 if invalid else 0.0),
109
+ encoding="utf-8",
110
+ )
111
+ snapshot = runtime_dir / "model"
112
+ snapshot.mkdir()
113
+ (snapshot / "model.bin").write_bytes(b"model")
114
+ runtime = MfaRuntimeInfo(
115
+ python=package("python", "3.12.14"),
116
+ mfa=package("montreal-forced-aligner", "3.4.2"),
117
+ kaldi=package("kaldi", "5.5.1172"),
118
+ kalpy=package("kalpy", "0.10.5"),
119
+ openfst=package("openfst", "1.8.4"),
120
+ environment=(
121
+ str(config.environment_prefix)
122
+ if config.environment_prefix is not None
123
+ else str(config.environment_name)
124
+ ),
125
+ )
126
+ command = ("conda", "run", "mfa", "align_hf")
127
+ return MfaRun(
128
+ result=CommandResult(command, 0, "stdout", "stderr", self.duration_s),
129
+ runtime=runtime,
130
+ command_sha256="c" * 64,
131
+ model_sha256=hashlib.sha256(b"model").hexdigest(),
132
+ dictionary_sha256="d" * 64,
133
+ g2p_sha256="g" * 64 if config.use_g2p else None,
134
+ model_snapshot=snapshot,
135
+ stdout_log=runtime_dir / "mfa.stdout.log",
136
+ stderr_log=runtime_dir / "mfa.stderr.log",
137
+ package_log=runtime_dir / "conda-packages.json",
138
+ )
139
+
140
+
141
+ def config(
142
+ tmp_path: Path,
143
+ *,
144
+ artifact_policy: str = "never",
145
+ use_g2p: bool = True,
146
+ run_id: str = "test-run",
147
+ ) -> MfaConfig:
148
+ return MfaConfig(
149
+ environment_name=None,
150
+ environment_prefix=tmp_path / "mfa-env",
151
+ artifact_policy=artifact_policy, # type: ignore[arg-type]
152
+ retention_root=tmp_path / "retained" if artifact_policy != "never" else None,
153
+ use_g2p=use_g2p,
154
+ run_id=run_id,
155
+ )
156
+
157
+
158
+ def request(
159
+ tmp_path: Path, name: str, transcript: str = "Hello world"
160
+ ) -> AlignmentRequest:
161
+ path = tmp_path / f"{name}.wav"
162
+ path.write_bytes(b"wav")
163
+ return AlignmentRequest(name, path, transcript, 3.0)
164
+
165
+
166
+ def test_direct_library_alignment_records_versions_models_and_original_mapping(
167
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
168
+ ) -> None:
169
+ fake = MaterializingMfa(duration_s=1.5)
170
+ monkeypatch.setattr(backend_module, "run_mfa", fake)
171
+ backend = MfaBackend(config(tmp_path), process_runner=object()) # type: ignore[arg-type]
172
+
173
+ result = backend.align(request(tmp_path, "clip", "Hello, X-Files!"))
174
+
175
+ assert [word.lexical_word.text for word in result.words] == ["Hello", "X-Files"]
176
+ assert result.words[1].start_s == pytest.approx(0.3)
177
+ assert result.words[1].end_s == pytest.approx(0.7)
178
+ assert result.runtime_s == 1.5
179
+ assert result.provenance.backend_name == "mfa"
180
+ assert result.provenance.backend_version == "3.4.2"
181
+ assert result.provenance.model_revision == config(tmp_path).model_revision
182
+ assert result.provenance.dictionary_id.endswith(":english_us_mfa")
183
+ assert result.provenance.dictionary_sha256 == "d" * 64
184
+ assert result.provenance.artifacts == ()
185
+ attributes = dict(result.provenance.attributes)
186
+ assert attributes["reference_text_authoritative"] is True
187
+ assert attributes["kaldi_version"] == "5.5.1172"
188
+ assert {diagnostic.code for diagnostic in result.diagnostics} == {
189
+ "mfa_process_completed",
190
+ "mfa_oov_g2p_enabled",
191
+ }
192
+
193
+
194
+ def test_batch_retains_native_artifacts_and_allocates_runtime(
195
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
196
+ ) -> None:
197
+ fake = MaterializingMfa(duration_s=4.0)
198
+ monkeypatch.setattr(backend_module, "run_mfa", fake)
199
+ backend = MfaBackend(
200
+ config(tmp_path, artifact_policy="always", use_g2p=False),
201
+ process_runner=object(), # type: ignore[arg-type]
202
+ )
203
+ requests = (request(tmp_path, "one"), request(tmp_path, "two", "go go"))
204
+
205
+ outcomes = backend.align_batch(requests)
206
+
207
+ assert all(outcome.result is not None for outcome in outcomes)
208
+ for outcome in outcomes:
209
+ assert outcome.result is not None
210
+ assert outcome.result.runtime_s == 2.0
211
+ assert all(Path(path).exists() for path in outcome.result.provenance.artifacts)
212
+ assert len(outcome.result.provenance.artifacts) == 6
213
+ oov = next(item for item in outcome.result.diagnostics if "oov" in item.code)
214
+ assert oov.code == "mfa_oov_g2p_disabled"
215
+ assert oov.severity is DiagnosticSeverity.WARNING
216
+ assert dict(outcome.result.provenance.attributes)["g2p_sha256"] is None
217
+
218
+
219
+ def test_row_mapping_missing_output_and_validation_failures_are_structured(
220
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
221
+ ) -> None:
222
+ fake = MaterializingMfa(
223
+ bad_stems={"r000001"},
224
+ missing_stems={"r000002"},
225
+ invalid_stems={"r000003"},
226
+ )
227
+ monkeypatch.setattr(backend_module, "run_mfa", fake)
228
+ backend = MfaBackend(
229
+ config(tmp_path, artifact_policy="on_failure"),
230
+ process_runner=object(), # type: ignore[arg-type]
231
+ )
232
+ requests = tuple(request(tmp_path, f"row-{index}") for index in range(4))
233
+
234
+ outcomes = backend.align_batch(requests)
235
+
236
+ assert outcomes[0].succeeded
237
+ assert outcomes[1].failure is not None
238
+ assert outcomes[1].failure.code == TranscriptMappingError.code
239
+ assert outcomes[2].failure is not None
240
+ assert outcomes[2].failure.code == BackendOutputError.code
241
+ assert outcomes[3].failure is not None
242
+ assert outcomes[3].failure.code == AlignmentValidationError.code
243
+ for outcome in outcomes[1:]:
244
+ assert outcome.failure is not None
245
+ assert outcome.failure.provenance is not None
246
+ assert outcome.failure.provenance.artifacts
247
+
248
+
249
+ def test_single_alignment_re_raises_specific_row_failure(
250
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
251
+ ) -> None:
252
+ monkeypatch.setattr(
253
+ backend_module, "run_mfa", MaterializingMfa(bad_stems={"r000000"})
254
+ )
255
+ backend = MfaBackend(config(tmp_path), process_runner=object()) # type: ignore[arg-type]
256
+ with pytest.raises(TranscriptMappingError, match="cannot cover") as raised:
257
+ backend.align(request(tmp_path, "bad"))
258
+ assert dict(raised.value.context)["request_id"] == "bad"
259
+
260
+
261
+ def test_whole_process_failure_retains_diagnostics_in_error_context(
262
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
263
+ ) -> None:
264
+ monkeypatch.setattr(backend_module, "run_mfa", MaterializingMfa(fail=True))
265
+ backend = MfaBackend(
266
+ config(tmp_path, artifact_policy="on_failure"),
267
+ process_runner=object(), # type: ignore[arg-type]
268
+ )
269
+ with pytest.raises(BackendExecutionError, match="simulated") as raised:
270
+ backend.align_batch((request(tmp_path, "clip"),))
271
+ retained = Path(dict(raised.value.context)["native_artifact_dir"])
272
+ assert (retained / "runtime" / "mfa.stdout.log").read_text() == "stdout"
273
+
274
+
275
+ def test_missing_wav_and_empty_batch_are_explicit(
276
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
277
+ ) -> None:
278
+ monkeypatch.setattr(backend_module, "run_mfa", MaterializingMfa())
279
+ backend = MfaBackend(config(tmp_path), process_runner=object()) # type: ignore[arg-type]
280
+ assert backend.align_batch(()) == ()
281
+ with pytest.raises(AudioError, match="missing"):
282
+ backend.align(
283
+ AlignmentRequest("missing", tmp_path / "missing.wav", "Hello", 1.0)
284
+ )
285
+
286
+
287
+ def test_factory_accepts_typed_and_mapping_config_without_vendor_imports(
288
+ tmp_path: Path,
289
+ ) -> None:
290
+ typed = create_backend(config=config(tmp_path), process_runner=object()) # type: ignore[arg-type]
291
+ mapped = create_backend(
292
+ config={"environment_prefix": str(tmp_path / "other-env")},
293
+ process_runner=object(), # type: ignore[arg-type]
294
+ )
295
+ assert isinstance(typed, AlignmentBackend)
296
+ assert isinstance(mapped, AlignmentBackend)
tests/unit/backends/mfa/test_config.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ import pytest
6
+
7
+ from speech_text_data_aligners.backends.mfa.config import (
8
+ DEFAULT_MODEL_ID,
9
+ DEFAULT_MODEL_REVISION,
10
+ MfaConfig,
11
+ )
12
+ from speech_text_data_aligners.core.errors import ConfigurationError
13
+
14
+
15
+ def test_defaults_pin_dedicated_environment_and_revision() -> None:
16
+ config = MfaConfig()
17
+ assert config.environment_name == "speech-aligners-mfa"
18
+ assert config.environment_prefix is None
19
+ assert config.model_spec == f"{DEFAULT_MODEL_ID}@{DEFAULT_MODEL_REVISION}"
20
+ assert config.use_g2p is True
21
+ assert config.expected_mfa_version == "3.4.2"
22
+ assert config.expected_kaldi_version == "5.5.1172"
23
+
24
+
25
+ def test_mapping_converts_paths_and_prefix_replaces_default_name(
26
+ tmp_path: Path,
27
+ ) -> None:
28
+ config = MfaConfig.from_mapping(
29
+ {
30
+ "environment_prefix": str(tmp_path / "mfa"),
31
+ "temporary_root": str(tmp_path / "temporary"),
32
+ "retention_root": str(tmp_path / "retained"),
33
+ "artifact_policy": "always",
34
+ "num_jobs": 2,
35
+ "timeout_s": 12,
36
+ "use_g2p": False,
37
+ }
38
+ )
39
+ assert config.environment_name is None
40
+ assert config.environment_prefix == tmp_path / "mfa"
41
+ assert config.timeout_s == 12.0
42
+ assert config.fingerprint_values()["environment_prefix"] == str(tmp_path / "mfa")
43
+ assert config.fingerprint_values()["retention_root"] == str(tmp_path / "retained")
44
+
45
+
46
+ @pytest.mark.parametrize(
47
+ "values",
48
+ [
49
+ {"unknown": True},
50
+ {"conda_executable": ""},
51
+ {"mfa_executable": ""},
52
+ {"environment_name": None},
53
+ {"environment_prefix": "/tmp/mfa", "environment_name": "also"},
54
+ {"environment_name": "../unsafe"},
55
+ {"model_id": ""},
56
+ {"model_id": "org/model@tag"},
57
+ {"model_id": "org/model name"},
58
+ {"model_revision": "short"},
59
+ {"model_version": ""},
60
+ {"dialect": ""},
61
+ {"expected_mfa_version": ""},
62
+ {"use_g2p": 1},
63
+ {"expected_model_sha256": "ABC"},
64
+ {"num_jobs": True},
65
+ {"num_jobs": 0},
66
+ {"timeout_s": True},
67
+ {"timeout_s": 0},
68
+ {"timeout_s": float("inf")},
69
+ {"artifact_policy": "sometimes"},
70
+ {"artifact_policy": "always"},
71
+ {"run_id": ""},
72
+ {"run_id": "../bad"},
73
+ ],
74
+ )
75
+ def test_invalid_semantic_configurations_are_rejected(
76
+ values: dict[str, object],
77
+ ) -> None:
78
+ with pytest.raises(ConfigurationError):
79
+ MfaConfig.from_mapping(values)
80
+
81
+
82
+ @pytest.mark.parametrize(
83
+ "field,value",
84
+ [
85
+ ("environment_prefix", 4),
86
+ ("temporary_root", ""),
87
+ ("conda_executable", 4),
88
+ ("environment_name", 4),
89
+ ("expected_model_sha256", 4),
90
+ ("num_jobs", "2"),
91
+ ("timeout_s", "2"),
92
+ ],
93
+ )
94
+ def test_mapping_rejects_wrong_primitive_types(field: str, value: object) -> None:
95
+ with pytest.raises(ConfigurationError):
96
+ MfaConfig.from_mapping({field: value})
97
+
98
+
99
+ def test_valid_expected_hash_and_explicit_name_are_preserved() -> None:
100
+ digest = "a" * 64
101
+ config = MfaConfig.from_mapping(
102
+ {
103
+ "environment_name": "isolated_mfa-1",
104
+ "expected_model_sha256": digest,
105
+ "run_id": "stable-run",
106
+ }
107
+ )
108
+ assert config.expected_model_sha256 == digest
109
+ assert config.run_id == "stable-run"
tests/unit/backends/mfa/test_corpus.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ import pytest
6
+
7
+ from speech_text_data_aligners.backends.mfa import corpus as corpus_module
8
+ from speech_text_data_aligners.backends.mfa.corpus import (
9
+ build_corpus,
10
+ make_mfa_text_plan,
11
+ )
12
+ from speech_text_data_aligners.core.errors import AudioError, BackendOutputError
13
+ from speech_text_data_aligners.core.models import AlignmentRequest
14
+
15
+
16
+ def request(path: Path, request_id: str, transcript: str) -> AlignmentRequest:
17
+ return AlignmentRequest(request_id, path, transcript, 4.0)
18
+
19
+
20
+ def test_normalization_is_reversible_for_punctuation_compounds_and_numbers() -> None:
21
+ transcript = "U.S. X–Files can't 17th 1962 2002 24 1.05!"
22
+ plan = make_mfa_text_plan(transcript)
23
+ assert plan.emitted_text == (
24
+ "u s x files can't seventeenth nineteen sixty two two thousand two "
25
+ "twenty four one point zero five"
26
+ )
27
+ assert [word.text for word in plan.lexical_words] == [
28
+ "U.S.",
29
+ "X–Files",
30
+ "can't",
31
+ "17th",
32
+ "1962",
33
+ "2002",
34
+ "24",
35
+ "1.05",
36
+ ]
37
+ owners = [unit.lexical_index for unit in plan.units]
38
+ assert owners[:4] == [0, 0, 1, 1]
39
+ assert owners[-5:] == [6, 7, 7, 7, 7]
40
+
41
+
42
+ @pytest.mark.parametrize(
43
+ ("surface", "emitted"),
44
+ [
45
+ ("0", "zero"),
46
+ ("9", "nine"),
47
+ ("10", "ten"),
48
+ ("19", "nineteen"),
49
+ ("20", "twenty"),
50
+ ("42", "forty two"),
51
+ ("100", "one hundred"),
52
+ ("105", "one hundred five"),
53
+ ("1000", "one thousand"),
54
+ ("1000001", "one million one"),
55
+ ("1900", "nineteen hundred"),
56
+ ("2010", "twenty ten"),
57
+ ("2099", "twenty ninety nine"),
58
+ ("1st", "first"),
59
+ ("2nd", "second"),
60
+ ("3rd", "third"),
61
+ ("8th", "eighth"),
62
+ ("12th", "twelfth"),
63
+ ("20th", "twentieth"),
64
+ ("100th", "one hundredth"),
65
+ ("1000th", "one thousandth"),
66
+ ("1000000th", "one millionth"),
67
+ ],
68
+ )
69
+ def test_numeric_normalization_cases(surface: str, emitted: str) -> None:
70
+ assert make_mfa_text_plan(surface).emitted_text == emitted
71
+
72
+
73
+ def test_numeric_normalization_rejects_unsupported_magnitude() -> None:
74
+ with pytest.raises(BackendOutputError, match="exceeds"):
75
+ make_mfa_text_plan("1000000000")
76
+
77
+
78
+ def test_build_corpus_copies_bytes_and_preserves_sources(tmp_path: Path) -> None:
79
+ first = tmp_path / "source one.wav"
80
+ second = tmp_path / "source two.wav"
81
+ first.write_bytes(b"first wav")
82
+ second.write_bytes(b"second wav")
83
+ requests = (
84
+ request(first, "row-a", "Hello, X-Files!"),
85
+ request(second, "row-b", "go go"),
86
+ )
87
+
88
+ corpus = build_corpus(requests, tmp_path / "native")
89
+
90
+ assert corpus.path == (tmp_path / "native").resolve()
91
+ assert [entry.stem for entry in corpus.entries] == ["r000000", "r000001"]
92
+ assert (corpus.path / "r000000.wav").read_bytes() == b"first wav"
93
+ assert (corpus.path / "r000000.lab").read_text() == "hello x files\n"
94
+ assert (corpus.path / "r000001.lab").read_text() == "go go\n"
95
+ assert first.read_bytes() == b"first wav"
96
+ assert second.read_bytes() == b"second wav"
97
+ assert corpus.entries[0].wav_path.stat().st_ino != first.stat().st_ino
98
+
99
+
100
+ def test_build_corpus_rejects_empty_existing_and_duplicate_inputs(
101
+ tmp_path: Path,
102
+ ) -> None:
103
+ with pytest.raises(BackendOutputError, match="at least one"):
104
+ build_corpus((), tmp_path / "empty")
105
+ wav = tmp_path / "a.wav"
106
+ wav.write_bytes(b"wav")
107
+ occupied = tmp_path / "occupied"
108
+ occupied.mkdir()
109
+ with pytest.raises(BackendOutputError, match="cannot create"):
110
+ build_corpus((request(wav, "occupied", "one"),), occupied)
111
+
112
+ with pytest.raises(BackendOutputError, match="identifiers"):
113
+ build_corpus(
114
+ (request(wav, "same", "one"), request(tmp_path / "b.wav", "same", "two")),
115
+ tmp_path / "duplicate-id",
116
+ )
117
+ with pytest.raises(AudioError, match="duplicated"):
118
+ build_corpus(
119
+ (request(wav, "one", "one"), request(wav, "two", "two")),
120
+ tmp_path / "duplicate-audio",
121
+ )
122
+
123
+
124
+ def test_build_corpus_rejects_missing_and_non_file_audio(tmp_path: Path) -> None:
125
+ with pytest.raises(AudioError, match="missing"):
126
+ build_corpus(
127
+ (request(tmp_path / "missing.wav", "missing", "one"),),
128
+ tmp_path / "missing-corpus",
129
+ )
130
+ directory = tmp_path / "directory.wav"
131
+ directory.mkdir()
132
+ with pytest.raises(AudioError, match="regular file"):
133
+ build_corpus(
134
+ (request(directory, "directory", "one"),),
135
+ tmp_path / "directory-corpus",
136
+ )
137
+
138
+
139
+ def test_build_corpus_translates_copy_failure(
140
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
141
+ ) -> None:
142
+ wav = tmp_path / "a.wav"
143
+ wav.write_bytes(b"wav")
144
+
145
+ def fail_copy(source: Path, destination: Path) -> None:
146
+ raise OSError("disk failure")
147
+
148
+ monkeypatch.setattr(corpus_module.shutil, "copyfile", fail_copy)
149
+ with pytest.raises(BackendOutputError, match="row 0"):
150
+ build_corpus((request(wav, "one", "one"),), tmp_path / "corpus")
tests/unit/backends/mfa/test_runner.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+ import pytest
7
+
8
+ from speech_text_data_aligners.backends.mfa import runner as runner_module
9
+ from speech_text_data_aligners.backends.mfa.config import MfaConfig
10
+ from speech_text_data_aligners.backends.mfa.runner import run_mfa
11
+ from speech_text_data_aligners.core.errors import (
12
+ BackendExecutionError,
13
+ BackendOutputError,
14
+ BackendUnavailableError,
15
+ )
16
+ from speech_text_data_aligners.runtime.process import Command, CommandResult
17
+
18
+
19
+ def package_payload(*, mfa_version: str = "3.4.2") -> list[dict[str, str]]:
20
+ versions = {
21
+ "python": "3.12.14",
22
+ "montreal-forced-aligner": mfa_version,
23
+ "kaldi": "5.5.1172",
24
+ "kalpy": "0.10.5",
25
+ "openfst": "1.8.4",
26
+ }
27
+ return [
28
+ {
29
+ "name": name,
30
+ "version": version,
31
+ "build_string": f"build-{name}",
32
+ "channel": "https://conda.anaconda.org/conda-forge",
33
+ }
34
+ for name, version in versions.items()
35
+ ]
36
+
37
+
38
+ def materialize_model(
39
+ huggingface_home: Path,
40
+ config: MfaConfig,
41
+ *,
42
+ model_version: str | None = None,
43
+ dictionary: bool = True,
44
+ g2p: bool = True,
45
+ ) -> Path:
46
+ snapshot = (
47
+ huggingface_home
48
+ / "hub"
49
+ / "models--MontrealCorpusTools--english_mfa"
50
+ / "snapshots"
51
+ / config.model_revision
52
+ )
53
+ (snapshot / "acoustic").mkdir(parents=True)
54
+ (snapshot / "acoustic" / "meta.json").write_text(
55
+ json.dumps({"version": model_version or config.model_version}), encoding="utf-8"
56
+ )
57
+ (snapshot / "acoustic" / "final.mdl").write_bytes(b"model")
58
+ if dictionary:
59
+ (snapshot / "dictionary").mkdir()
60
+ (snapshot / "dictionary" / f"{config.dialect}.dict").write_text(
61
+ "hello\th e l o\n", encoding="utf-8"
62
+ )
63
+ if g2p:
64
+ (snapshot / "g2p" / config.dialect).mkdir(parents=True)
65
+ (snapshot / "g2p" / config.dialect / "model.fst").write_bytes(b"g2p")
66
+ return snapshot
67
+
68
+
69
+ class FakeRunner:
70
+ def __init__(
71
+ self,
72
+ *,
73
+ probe_returncode: int = 0,
74
+ align_returncode: int = 0,
75
+ package_text: str | None = None,
76
+ mfa_version: str = "3.4.2",
77
+ model_version: str | None = None,
78
+ ) -> None:
79
+ self.probe_returncode = probe_returncode
80
+ self.align_returncode = align_returncode
81
+ self.package_text = package_text
82
+ self.mfa_version = mfa_version
83
+ self.model_version = model_version
84
+ self.commands: list[Command] = []
85
+
86
+ def run(self, command: Command) -> CommandResult:
87
+ self.commands.append(command)
88
+ if len(command.argv) > 1 and command.argv[1] == "list":
89
+ stdout = self.package_text
90
+ if stdout is None:
91
+ stdout = json.dumps(package_payload(mfa_version=self.mfa_version))
92
+ return CommandResult(
93
+ command.argv, self.probe_returncode, stdout, "probe stderr", 0.1
94
+ )
95
+ if self.align_returncode == 0:
96
+ environment = dict(command.environment)
97
+ config = MfaConfig(
98
+ environment_name=None,
99
+ environment_prefix=Path(command.argv[5]),
100
+ )
101
+ materialize_model(
102
+ Path(environment["HF_HOME"]),
103
+ config,
104
+ model_version=self.model_version,
105
+ )
106
+ return CommandResult(
107
+ command.argv,
108
+ self.align_returncode,
109
+ "alignment stdout",
110
+ "alignment stderr",
111
+ 2.5,
112
+ )
113
+
114
+
115
+ def configured(tmp_path: Path, **values: object) -> MfaConfig:
116
+ defaults: dict[str, object] = {
117
+ "environment_name": None,
118
+ "environment_prefix": tmp_path / "mfa-env",
119
+ }
120
+ defaults.update(values)
121
+ return MfaConfig(**defaults) # type: ignore[arg-type]
122
+
123
+
124
+ def test_run_mfa_probes_environment_invokes_frozen_mode_and_hashes_model(
125
+ tmp_path: Path,
126
+ ) -> None:
127
+ corpus = tmp_path / "corpus"
128
+ corpus.mkdir()
129
+ fake = FakeRunner()
130
+ config = configured(tmp_path, num_jobs=3)
131
+
132
+ result = run_mfa(
133
+ config,
134
+ corpus,
135
+ tmp_path / "output",
136
+ tmp_path / "runtime",
137
+ process_runner=fake,
138
+ )
139
+
140
+ assert result.runtime.mfa.version == "3.4.2"
141
+ assert result.runtime.python.version == "3.12.14"
142
+ assert result.runtime.kaldi.build == "build-kaldi"
143
+ assert result.result.duration_s == 2.5
144
+ assert len(result.model_sha256) == 64
145
+ assert len(result.dictionary_sha256) == 64
146
+ assert result.g2p_sha256 and len(result.g2p_sha256) == 64
147
+ assert result.package_log.is_file()
148
+ assert result.stdout_log.read_text() == "alignment stdout"
149
+ assert result.stderr_log.read_text() == "alignment stderr"
150
+ command = fake.commands[1]
151
+ assert command.check is False
152
+ assert "align_hf" in command.argv
153
+ assert config.model_spec in command.argv
154
+ assert "--no_tokenization" in command.argv
155
+ assert "--use_g2p" in command.argv
156
+ assert "--no_use_postgres" in command.argv
157
+ assert command.environment[0][0] == "MFA_ROOT_DIR"
158
+
159
+
160
+ def test_named_environment_and_disabled_g2p_change_command_and_evidence(
161
+ tmp_path: Path,
162
+ ) -> None:
163
+ corpus = tmp_path / "corpus"
164
+ corpus.mkdir()
165
+ config = MfaConfig(environment_name="dedicated", use_g2p=False)
166
+ fake = FakeRunner()
167
+
168
+ result = run_mfa(
169
+ config,
170
+ corpus,
171
+ tmp_path / "output",
172
+ tmp_path / "runtime",
173
+ process_runner=fake,
174
+ )
175
+
176
+ assert fake.commands[0].argv[-2:] == ("--name", "dedicated")
177
+ assert "--use_g2p" not in fake.commands[1].argv
178
+ assert result.g2p_sha256 is None
179
+
180
+
181
+ @pytest.mark.parametrize(
182
+ ("runner", "error", "match"),
183
+ [
184
+ (FakeRunner(probe_returncode=2), BackendExecutionError, "package probe"),
185
+ (FakeRunner(package_text="not-json"), BackendOutputError, "malformed JSON"),
186
+ (FakeRunner(package_text="{}"), BackendOutputError, "JSON array"),
187
+ (FakeRunner(package_text="[]"), BackendOutputError, "identify python"),
188
+ (FakeRunner(mfa_version="3.4.1"), BackendUnavailableError, "expected version"),
189
+ (FakeRunner(align_returncode=4), BackendExecutionError, "exited with status"),
190
+ (FakeRunner(model_version="wrong"), BackendUnavailableError, "model version"),
191
+ ],
192
+ )
193
+ def test_run_mfa_translates_probe_process_and_model_failures(
194
+ tmp_path: Path, runner: FakeRunner, error: type[Exception], match: str
195
+ ) -> None:
196
+ corpus = tmp_path / "corpus"
197
+ corpus.mkdir()
198
+ with pytest.raises(error, match=match):
199
+ run_mfa(
200
+ configured(tmp_path),
201
+ corpus,
202
+ tmp_path / "output",
203
+ tmp_path / "runtime",
204
+ process_runner=runner,
205
+ )
206
+ if runner.align_returncode:
207
+ assert (tmp_path / "runtime" / "mfa.stdout.log").is_file()
208
+ assert (tmp_path / "runtime" / "mfa.stderr.log").is_file()
209
+
210
+
211
+ def test_package_probe_rejects_duplicate_and_incomplete_records(tmp_path: Path) -> None:
212
+ corpus = tmp_path / "corpus"
213
+ corpus.mkdir()
214
+ duplicate = package_payload()
215
+ duplicate.append(dict(duplicate[0]))
216
+ with pytest.raises(BackendOutputError, match="identify python"):
217
+ run_mfa(
218
+ configured(tmp_path),
219
+ corpus,
220
+ tmp_path / "out-duplicate",
221
+ tmp_path / "runtime-duplicate",
222
+ process_runner=FakeRunner(package_text=json.dumps(duplicate)),
223
+ )
224
+ incomplete = package_payload()
225
+ del incomplete[0]["channel"]
226
+ with pytest.raises(BackendOutputError, match="incomplete"):
227
+ run_mfa(
228
+ configured(tmp_path),
229
+ corpus,
230
+ tmp_path / "out-incomplete",
231
+ tmp_path / "runtime-incomplete",
232
+ process_runner=FakeRunner(package_text=json.dumps(incomplete)),
233
+ )
234
+
235
+
236
+ def test_model_evidence_rejects_missing_structure_and_hash_mismatch(
237
+ tmp_path: Path,
238
+ ) -> None:
239
+ config = configured(tmp_path)
240
+ home = tmp_path / "hf"
241
+ with pytest.raises(BackendOutputError, match="metadata"):
242
+ runner_module._model_evidence(config, home)
243
+ snapshot = materialize_model(home, config, dictionary=False)
244
+ with pytest.raises(BackendOutputError, match="dictionary"):
245
+ runner_module._model_evidence(config, home)
246
+ (snapshot / "dictionary").mkdir()
247
+ (snapshot / "dictionary" / f"{config.dialect}.dict").write_text("word\tw\n")
248
+ (snapshot / "g2p" / config.dialect).rename(snapshot / "g2p" / "other")
249
+ with pytest.raises(BackendOutputError, match="directory is missing"):
250
+ runner_module._model_evidence(config, home)
251
+ (snapshot / "g2p" / "other").rename(snapshot / "g2p" / config.dialect)
252
+ mismatched = configured(tmp_path, expected_model_sha256="a" * 64)
253
+ with pytest.raises(BackendUnavailableError, match="tree hash"):
254
+ runner_module._model_evidence(mismatched, home)
255
+
256
+
257
+ def test_tree_hash_and_log_helpers_reject_invalid_targets(tmp_path: Path) -> None:
258
+ with pytest.raises(BackendOutputError, match="missing"):
259
+ runner_module._hash_tree(tmp_path / "missing")
260
+ empty = tmp_path / "empty"
261
+ empty.mkdir()
262
+ with pytest.raises(BackendOutputError, match="empty"):
263
+ runner_module._hash_tree(empty)
264
+ blocked_parent = tmp_path / "blocked"
265
+ blocked_parent.write_text("file")
266
+ with pytest.raises(BackendOutputError, match="diagnostic"):
267
+ runner_module._write_log(blocked_parent / "child.log", "text")
268
+
269
+
270
+ def test_run_mfa_rejects_missing_corpus_and_existing_native_directories(
271
+ tmp_path: Path,
272
+ ) -> None:
273
+ with pytest.raises(BackendUnavailableError, match="corpus"):
274
+ run_mfa(
275
+ configured(tmp_path),
276
+ tmp_path / "missing",
277
+ tmp_path / "output",
278
+ tmp_path / "runtime",
279
+ process_runner=FakeRunner(),
280
+ )
281
+ corpus = tmp_path / "corpus"
282
+ corpus.mkdir()
283
+ output = tmp_path / "existing"
284
+ output.mkdir()
285
+ with pytest.raises(BackendOutputError, match="runtime directories"):
286
+ run_mfa(
287
+ configured(tmp_path),
288
+ corpus,
289
+ output,
290
+ tmp_path / "runtime-two",
291
+ process_runner=FakeRunner(),
292
+ )
tests/unit/backends/mfa/test_textgrid.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ import pytest
6
+
7
+ from speech_text_data_aligners.backends.mfa.corpus import make_mfa_text_plan
8
+ from speech_text_data_aligners.backends.mfa.textgrid import parse_word_textgrid
9
+ from speech_text_data_aligners.core.errors import (
10
+ BackendOutputError,
11
+ TranscriptMappingError,
12
+ )
13
+
14
+ type NativeInterval = tuple[float, float, str]
15
+
16
+
17
+ def praat_quote(value: str) -> str:
18
+ return value.replace('"', '""')
19
+
20
+
21
+ def long_textgrid(
22
+ tiers: list[tuple[str, str, list[NativeInterval]]],
23
+ *,
24
+ tier_min: str = "0",
25
+ tier_max: str = "4",
26
+ ) -> str:
27
+ lines = [
28
+ 'File type = "ooTextFile"',
29
+ 'Object class = "TextGrid"',
30
+ "",
31
+ f"xmin = {tier_min}",
32
+ f"xmax = {tier_max}",
33
+ "tiers? <exists>",
34
+ f"size = {len(tiers)}",
35
+ "item []:",
36
+ ]
37
+ for tier_index, (name, tier_class, intervals) in enumerate(tiers, start=1):
38
+ lines.extend(
39
+ [
40
+ f" item [{tier_index}]:",
41
+ f' class = "{tier_class}"',
42
+ f' name = "{praat_quote(name)}"',
43
+ f" xmin = {tier_min}",
44
+ f" xmax = {tier_max}",
45
+ f" intervals: size = {len(intervals)}",
46
+ ]
47
+ )
48
+ for interval_index, (start, end, label) in enumerate(intervals, start=1):
49
+ lines.extend(
50
+ [
51
+ f" intervals [{interval_index}]:",
52
+ f" xmin = {start}",
53
+ f" xmax = {end}",
54
+ f' text = "{praat_quote(label)}"',
55
+ ]
56
+ )
57
+ return "\n".join(lines) + "\n"
58
+
59
+
60
+ def short_textgrid(
61
+ tiers: list[tuple[str, str, list[NativeInterval]]],
62
+ ) -> str:
63
+ lines = [
64
+ 'File type = "ooTextFile"',
65
+ 'Object class = "TextGrid"',
66
+ "0",
67
+ "4",
68
+ "<exists>",
69
+ str(len(tiers)),
70
+ ]
71
+ for name, tier_class, entries in tiers:
72
+ lines.extend([f'"{tier_class}"', f'"{name}"', "0", "4", str(len(entries))])
73
+ if tier_class == "IntervalTier":
74
+ for start, end, label in entries:
75
+ lines.extend([str(start), str(end), f'"{praat_quote(label)}"'])
76
+ else:
77
+ for start, _, label in entries:
78
+ lines.extend([str(start), f'"{praat_quote(label)}"'])
79
+ return "\n".join(lines) + "\n"
80
+
81
+
82
+ def write(path: Path, text: str) -> Path:
83
+ path.write_text(text, encoding="utf-8")
84
+ return path
85
+
86
+
87
+ def test_long_parser_ignores_silence_and_punctuation_and_maps_repeated_words(
88
+ tmp_path: Path,
89
+ ) -> None:
90
+ plan = make_mfa_text_plan("Go, go X-Files!")
91
+ text = long_textgrid(
92
+ [
93
+ ("phones", "IntervalTier", [(0.0, 0.1, "sil")]),
94
+ (
95
+ "words",
96
+ "IntervalTier",
97
+ [
98
+ (0.0, 0.2, ""),
99
+ (0.2, 0.5, "go"),
100
+ (0.5, 0.6, "."),
101
+ (0.6, 0.9, "go"),
102
+ (0.9, 1.1, "x"),
103
+ (1.1, 1.5, "files"),
104
+ (1.5, 4.0, "<eps>"),
105
+ ],
106
+ ),
107
+ ]
108
+ )
109
+ alignments = parse_word_textgrid(write(tmp_path / "a.TextGrid", text), plan)
110
+ assert [item.lexical_word.text for item in alignments] == ["Go", "go", "X-Files"]
111
+ assert [(item.start_s, item.end_s) for item in alignments] == [
112
+ (0.2, 0.5),
113
+ (0.6, 0.9),
114
+ (0.9, 1.5),
115
+ ]
116
+
117
+
118
+ def test_short_parser_handles_point_tier_and_escaped_quote(tmp_path: Path) -> None:
119
+ plan = make_mfa_text_plan("hello")
120
+ text = short_textgrid(
121
+ [
122
+ ("notes", "TextTier", [(0.1, 0.1, "marker")]),
123
+ (
124
+ "words",
125
+ "IntervalTier",
126
+ [(0.0, 0.1, '"'), (0.1, 0.8, "hello"), (0.8, 4.0, "")],
127
+ ),
128
+ ]
129
+ )
130
+ alignments = parse_word_textgrid(write(tmp_path / "short.TextGrid", text), plan)
131
+ assert [item.lexical_word.text for item in alignments] == ["hello"]
132
+
133
+
134
+ def test_short_header_marker_is_accepted(tmp_path: Path) -> None:
135
+ plan = make_mfa_text_plan("hello")
136
+ text = short_textgrid([("words", "IntervalTier", [(0.0, 1.0, "hello")])])
137
+ text = text.replace('File type = "ooTextFile"', 'File type = "ooTextFile short"')
138
+ result = parse_word_textgrid(write(tmp_path / "marker.TextGrid", text), plan)
139
+ assert result[0].lexical_word.text == "hello"
140
+
141
+
142
+ @pytest.mark.parametrize("label", ["<unk>", "<oov>", "spn"])
143
+ def test_unresolved_oov_markers_fail_explicitly(tmp_path: Path, label: str) -> None:
144
+ plan = make_mfa_text_plan("unknown")
145
+ text = long_textgrid([("words", "IntervalTier", [(0.0, 1.0, label)])])
146
+ with pytest.raises(TranscriptMappingError, match="OOV"):
147
+ parse_word_textgrid(write(tmp_path / f"{label}.TextGrid", text), plan)
148
+
149
+
150
+ def test_mapping_mismatch_and_multiword_interval_fail(tmp_path: Path) -> None:
151
+ plan = make_mfa_text_plan("hello world")
152
+ mismatch = long_textgrid(
153
+ [("words", "IntervalTier", [(0.0, 0.5, "goodbye"), (0.5, 1.0, "world")])]
154
+ )
155
+ with pytest.raises(TranscriptMappingError, match="cannot cover"):
156
+ parse_word_textgrid(write(tmp_path / "mismatch.TextGrid", mismatch), plan)
157
+ multiple = long_textgrid([("words", "IntervalTier", [(0.0, 1.0, "hello world")])])
158
+ with pytest.raises(TranscriptMappingError, match="multiple lexical"):
159
+ parse_word_textgrid(write(tmp_path / "multiple.TextGrid", multiple), plan)
160
+
161
+
162
+ @pytest.mark.parametrize(
163
+ ("name", "transform", "match"),
164
+ [
165
+ ("bad-header", lambda text: text.replace("TextGrid", "Other", 1), "header"),
166
+ (
167
+ "bad-class",
168
+ lambda text: text.replace('class = "IntervalTier"', 'class = "TextTier"'),
169
+ "not an IntervalTier",
170
+ ),
171
+ (
172
+ "bad-name-quote",
173
+ lambda text: text.replace('name = "words"', "name = words"),
174
+ "quoted",
175
+ ),
176
+ (
177
+ "bad-name-escape",
178
+ lambda text: text.replace('name = "words"', 'name = "wo"rds"'),
179
+ "quoting",
180
+ ),
181
+ (
182
+ "bad-number",
183
+ lambda text: text.replace("xmin = 0.0", "xmin = nope", 1),
184
+ "not numeric",
185
+ ),
186
+ (
187
+ "negative",
188
+ lambda text: text.replace("xmin = 0.0", "xmin = -1", 1),
189
+ "negative",
190
+ ),
191
+ (
192
+ "non-finite",
193
+ lambda text: text.replace("xmin = 0.0", "xmin = NaN", 1),
194
+ "non-finite",
195
+ ),
196
+ (
197
+ "bad-size",
198
+ lambda text: text.replace("intervals: size = 2", "intervals: size = x"),
199
+ "interval size",
200
+ ),
201
+ (
202
+ "wrong-size",
203
+ lambda text: text.replace("intervals: size = 2", "intervals: size = 3"),
204
+ "count",
205
+ ),
206
+ (
207
+ "bad-index",
208
+ lambda text: text.replace("intervals [2]", "intervals [3]"),
209
+ "non-sequential",
210
+ ),
211
+ (
212
+ "missing-text",
213
+ lambda text: text.replace('text = "world"', "label = world"),
214
+ "text assignment",
215
+ ),
216
+ (
217
+ "reversed",
218
+ lambda text: text.replace("xmin = 0.0", "xmin = 0.6", 1),
219
+ "reversed",
220
+ ),
221
+ (
222
+ "outside",
223
+ lambda text: text.replace("xmax = 1.0", "xmax = 5.0", 1),
224
+ "exceeds",
225
+ ),
226
+ (
227
+ "overlap",
228
+ lambda text: text.replace("xmin = 0.5", "xmin = 0.4", 1),
229
+ "overlap",
230
+ ),
231
+ ],
232
+ )
233
+ def test_long_format_malformed_fields_fail(
234
+ tmp_path: Path, name: str, transform: object, match: str
235
+ ) -> None:
236
+ plan = make_mfa_text_plan("hello world")
237
+ valid = long_textgrid(
238
+ [("words", "IntervalTier", [(0.0, 0.5, "hello"), (0.5, 1.0, "world")])]
239
+ )
240
+ changed = transform(valid) # type: ignore[operator]
241
+ with pytest.raises(BackendOutputError, match=match):
242
+ parse_word_textgrid(write(tmp_path / f"{name}.TextGrid", changed), plan)
243
+
244
+
245
+ def test_long_format_requires_exactly_one_words_tier(tmp_path: Path) -> None:
246
+ plan = make_mfa_text_plan("hello")
247
+ missing = long_textgrid([("phones", "IntervalTier", [(0.0, 1.0, "h")])])
248
+ duplicate = long_textgrid(
249
+ [
250
+ ("words", "IntervalTier", [(0.0, 1.0, "hello")]),
251
+ ("WORDS", "IntervalTier", [(0.0, 1.0, "hello")]),
252
+ ]
253
+ )
254
+ for name, text in (("missing", missing), ("duplicate", duplicate)):
255
+ with pytest.raises(BackendOutputError, match="exactly one"):
256
+ parse_word_textgrid(write(tmp_path / f"{name}.TextGrid", text), plan)
257
+ no_items = long_textgrid([])
258
+ with pytest.raises(BackendOutputError, match="no tiers"):
259
+ parse_word_textgrid(write(tmp_path / "none.TextGrid", no_items), plan)
260
+
261
+
262
+ def test_empty_word_tier_and_missing_file_fail(tmp_path: Path) -> None:
263
+ plan = make_mfa_text_plan("hello")
264
+ empty = long_textgrid([("words", "IntervalTier", [(0.0, 4.0, "")])])
265
+ with pytest.raises(BackendOutputError, match="no lexical"):
266
+ parse_word_textgrid(write(tmp_path / "empty.TextGrid", empty), plan)
267
+ with pytest.raises(BackendOutputError, match="missing or unreadable"):
268
+ parse_word_textgrid(tmp_path / "missing.TextGrid", plan)
269
+
270
+
271
+ @pytest.mark.parametrize(
272
+ ("name", "text", "match"),
273
+ [
274
+ ("incomplete-header", 'File type = "ooTextFile"\n', "header"),
275
+ ("invalid-object", 'File type = "ooTextFile"\n"Other"\n', "header"),
276
+ ("incomplete", 'File type = "ooTextFile"\n"TextGrid"\n0\n', "incomplete"),
277
+ ],
278
+ )
279
+ def test_general_malformed_files_fail(
280
+ tmp_path: Path, name: str, text: str, match: str
281
+ ) -> None:
282
+ with pytest.raises(BackendOutputError, match=match):
283
+ parse_word_textgrid(
284
+ write(tmp_path / f"{name}.TextGrid", text), make_mfa_text_plan("hello")
285
+ )
286
+
287
+
288
+ @pytest.mark.parametrize(
289
+ ("name", "transform", "match"),
290
+ [
291
+ (
292
+ "bad-exists",
293
+ lambda text: text.replace("<exists>", "<absent>"),
294
+ "grid bounds",
295
+ ),
296
+ (
297
+ "bad-tier-count",
298
+ lambda text: text.replace('\n1\n"IntervalTier"', '\nx\n"IntervalTier"'),
299
+ "not an integer",
300
+ ),
301
+ (
302
+ "short-header",
303
+ lambda text: "\n".join(text.splitlines()[:7]) + "\n",
304
+ "tier header",
305
+ ),
306
+ (
307
+ "interval-incomplete",
308
+ lambda text: "\n".join(text.splitlines()[:-1]) + "\n",
309
+ "interval data",
310
+ ),
311
+ (
312
+ "unknown-tier",
313
+ lambda text: text.replace('"IntervalTier"', '"UnknownTier"'),
314
+ "unsupported",
315
+ ),
316
+ ("trailing", lambda text: text + "trailing\n", "trailing"),
317
+ ],
318
+ )
319
+ def test_short_format_malformed_fields_fail(
320
+ tmp_path: Path, name: str, transform: object, match: str
321
+ ) -> None:
322
+ valid = short_textgrid([("words", "IntervalTier", [(0.0, 1.0, "hello")])])
323
+ changed = transform(valid) # type: ignore[operator]
324
+ with pytest.raises(BackendOutputError, match=match):
325
+ parse_word_textgrid(
326
+ write(tmp_path / f"{name}.TextGrid", changed), make_mfa_text_plan("hello")
327
+ )
328
+
329
+
330
+ def test_short_format_rejects_point_words_and_incomplete_points(tmp_path: Path) -> None:
331
+ point_words = short_textgrid([("words", "TextTier", [(0.2, 0.2, "hello")])])
332
+ with pytest.raises(BackendOutputError, match="not an IntervalTier"):
333
+ parse_word_textgrid(
334
+ write(tmp_path / "point-words.TextGrid", point_words),
335
+ make_mfa_text_plan("hello"),
336
+ )
337
+ incomplete = short_textgrid(
338
+ [
339
+ ("notes", "TextTier", [(0.2, 0.2, "note")]),
340
+ ("words", "IntervalTier", [(0.0, 1.0, "hello")]),
341
+ ]
342
+ )
343
+ lines = incomplete.splitlines()
344
+ del lines[11]
345
+ with pytest.raises(BackendOutputError):
346
+ parse_word_textgrid(
347
+ write(tmp_path / "point-incomplete.TextGrid", "\n".join(lines) + "\n"),
348
+ make_mfa_text_plan("hello"),
349
+ )
tests/unit/backends/test_registry.py CHANGED
@@ -75,6 +75,7 @@ def test_registry_default_entries_are_exact_lazy_strings() -> None:
75
  registry = default_backend_registry()
76
  assert registry.names == ("nemo", "mfa", "whisperx")
77
  assert dict(registry.entries)["nemo"].endswith(".nemo.backend:create_backend")
 
78
 
79
 
80
  def test_registry_rejects_unknown_missing_attribute_and_bad_result(
 
75
  registry = default_backend_registry()
76
  assert registry.names == ("nemo", "mfa", "whisperx")
77
  assert dict(registry.entries)["nemo"].endswith(".nemo.backend:create_backend")
78
+ assert dict(registry.entries)["mfa"].endswith(".mfa.backend:create_backend")
79
 
80
 
81
  def test_registry_rejects_unknown_missing_attribute_and_bad_result(