Nida v0.5 (research preview): weights, 16 voices, code, model card
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+16
- LICENSEAdded+202
- README.mdAdded+129
- nida-v05-ema.ptAdded+3
- pyproject.tomlAdded+68
- requirements.txtAdded+11
- src/nida/__init__.pyAdded+7
- src/nida/bench/__init__.pyAdded+1
- src/nida/bench/audiometrics.pyAdded+570
- src/nida/bench/b1.pyAdded+622
- src/nida/bench/b2.pyAdded+684
- src/nida/bench/clips.pyAdded+510
- src/nida/bench/envs.pyAdded+351
- src/nida/bench/expresso.pyAdded+301
- src/nida/bench/fetch.pyAdded+704
- src/nida/bench/panel.pyAdded+817
- src/nida/bench/phase0.pyAdded+358
- src/nida/bench/prepare.pyAdded+450
- src/nida/bench/protocol.pyAdded+325
- src/nida/bench/registry.pyAdded+166
- src/nida/bench/report.pyAdded+276
- src/nida/bench/textmetrics.pyAdded+464
- src/nida/bench/workers/__init__.pyAdded+7
- src/nida/bench/workers/asr_hf.pyAdded+103
- src/nida/bench/workers/asr_omni.pyAdded+42
- src/nida/bench/workers/asr_qwen.pyAdded+55
- src/nida/bench/workers/common.pyAdded+74
- src/nida/bench/workers/quality_audiobox.pyAdded+46
- src/nida/bench/workers/runner.pyAdded+340
- src/nida/bench/workers/vae_voxcpm.pyAdded+146
- src/nida/cli.pyAdded+929
- src/nida/data/__init__.pyAdded+5
- src/nida/data/acoustic.pyAdded+1002
- src/nida/data/align.pyAdded+261
- src/nida/data/asr_filter.pyAdded+283
- src/nida/data/ears.pyAdded+1307
- src/nida/data/enhance.pyAdded+593
- src/nida/data/envs.pyAdded+229
- src/nida/data/events.pyAdded+183
- src/nida/data/fillers_ctc.pyAdded+227
- src/nida/data/fusion.pyAdded+842
- src/nida/data/importer/__init__.pyAdded+118
- src/nida/data/importer/archives.pyAdded+296
- src/nida/data/importer/audio.pyAdded+146
- src/nida/data/importer/config.pyAdded+474
- src/nida/data/importer/corpora.pyAdded+801
- src/nida/data/importer/hub.pyAdded+150
- src/nida/data/importer/pipeline.pyAdded+1326
- src/nida/data/importer/sources.pyAdded+776
- src/nida/data/importer/text.pyAdded+110
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353637383940414243444546474849505132 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textvoices/ada.wav filter=lfs diff=lfs merge=lfs -textvoices/asli.wav filter=lfs diff=lfs merge=lfs -textvoices/can.wav filter=lfs diff=lfs merge=lfs -textvoices/defne.wav filter=lfs diff=lfs merge=lfs -textvoices/duru.wav filter=lfs diff=lfs merge=lfs -textvoices/efe.wav filter=lfs diff=lfs merge=lfs -textvoices/elif.wav filter=lfs diff=lfs merge=lfs -textvoices/emre.wav filter=lfs diff=lfs merge=lfs -textvoices/haluk.wav filter=lfs diff=lfs merge=lfs -textvoices/leyla.wav filter=lfs diff=lfs merge=lfs -textvoices/mert.wav filter=lfs diff=lfs merge=lfs -textvoices/nermin.wav filter=lfs diff=lfs merge=lfs -textvoices/nihat.wav filter=lfs diff=lfs merge=lfs -textvoices/orhan.wav filter=lfs diff=lfs merge=lfs -textvoices/selim.wav filter=lfs diff=lfs merge=lfs -textvoices/su.wav filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129---license: cc-by-nc-4.0language:- trpipeline_tag: text-to-speechtags:- text-to-speech- turkish- flow-matching- zero-shot---
# Nida v0.5 — Turkish text-to-speech (research preview)
**Nida** (*nida*: an exclamation, a call) is an open, non-commercial Turkish text-to-speech modeltrained **from scratch**. v0.5 is an early research preview: it reads Turkish clearly and stably,including numbers, dates and abbreviations, with sixteen bundled voices. Its prosody is still flat("reads rather than speaks"). Expressive speech (emotion, laughter, sighs) and better voicecloning are the goals of later versions.
> Türkçe özet: Nida, sıfırdan eğitilmiş, açık ve ticari olmayan bir Türkçe metinden-sese modelidir.> v0.5 bir araştırma önizlemesidir: sayı, tarih ve kısaltmalar dahil Türkçeyi net ve kararlı okur,> 16 hazır sesle gelir. Tonlaması henüz düzdür. Duygu, sözsüz sesler ve daha iyi ses klonlama> sonraki sürümlerin hedefidir.
## What it is
| | ||---|---|| Architecture | Diffusion transformer (DiT), flow matching on audio latents, explicit per-character durations with windowed Gaussian alignment || Parameters | 201 M || Audio latents | VoxCPM2 AudioVAE V2 (25 Hz × 64), decoded to 48 kHz || Training data | ~380 h: ~210 h Turkish YouTube speech (YODAS, CC-BY-3.0) + ~170 h synthetic multi-voice Turkish (alania, CC-BY-4.0) || Training | 200k steps, single GPU || Voices | sixteen bundled voices; a custom 3–8 s reference clip also works but is **experimental** |
## Measured quality (v0.5)
- Intelligibility: character error rate of an ASR read-back (Qwen3-ASR) **0.1–1.2 %** on narration and long-form text, **4.5–7 %** on short assistant sentences (numbers, proper names).- Speaker similarity with a custom reference clip (experimental; ECAPA-TDNN cosine, generated vs. reference): **~0.55** (the same real speaker scores ~0.8, different speakers ≤ 0.36; the audio codec alone keeps 0.955). The voice is recognisably close but not a faithful copy.- Long-form: stable over 2-minute paragraphs (no drift between sentences in our tests).- **TR-Zor** (155 hard Turkish sentences: numbers, dates, times, money, units, abbreviations, acronyms, ordinals; [ahenk-turkish-tts](https://github.com/ozguradmin/ahenk-turkish-tts), Apache-2.0), judge Whisper large-v3-turbo, word error rate with the set's spoken form as input: **2.36 %** (voice *deniz*, an earlier voice not in the final set; 141/155 sentences perfect), **3.15 %** (voice *emre*, 133/155). For reference, the same set reports Ahenk 2.54 % and Trendyol-TTS 3.98 % (both 2B VoxCPM2 fine-tunes, measured by their authors with their own text normaliser; our evaluation normaliser and Whisper backend differ, so treat the comparison as indicative).
## Known limitations
- Flat, read-like prosody; little emotion even when requested.- Custom voices (your own reference clip) are experimental: similarity is moderate and depends a lot on the clip. The bundled voices are the supported way to use v0.5.- Input text is normalised automatically (numbers, ordinals, dates, clock times, money, units, common abbreviations, acronyms spelled with Turkish letter names, phone/ID numbers). Ambiguous cases (e.g. `8.30` without context, unknown all-caps words) are reported; dangerous ones stop generation instead of producing wrong speech. `--no-normalize` turns it off.- Each sentence plus the reference must fit 20 seconds; sentences longer than ~96 spoken characters are split at a comma, semicolon or colon (never inside quotes or tags).- Trained mostly on Turkish; other languages are not supported.
## Bundled voices
Sixteen synthetic voices ship in `voices/`: `voices.tsv` lists all of them (`<wav>\t<transcript>`),and `voices/<name>.tsv` selects one. None of them is a recording of a real person.
| Voice | | Notes ||---|---|---|| leyla, duru | female | the cleanest voices; a good default || ada, defne, elif, nermin, su, aslı (`asli`) | female | || nihat | male | warm and calm || emre | male | lively || mert | male | sounds like a phone line; suits an assistant || can, haluk, selim, orhan, efe | male | |
can, elif, emre, haluk, nermin, nihat, selim, leyla, defne and ada come from the alania dataset(`voice_type: designed-identity`, generated with VoxCPM2 from text descriptions). su, aslı, duru,mert, orhan and efe were designed for this release the same way, with VoxCPM2 voice design froma text description (no reference audio).
## Usage
```bashpip install -r requirements.txt # torch (CUDA build recommended), transformers, soundfile, ...pip install -e . # the nida packagenida say --checkpoint nida-v05-ema.pt --prompt-list voices/leyla.tsv \ --text "Merhaba! Toplantı saat 14:30'da, 3. katta." --out out --single-env --no-asr```
Run it from the release folder: the voice lists use paths relative to the working directory.The audio is written to `out/ext-*.wav`, and `out/say.html` plays it. `--prompt-listvoices/voices.tsv` reads the text with all sixteen voices; `--text-file` reads a text file.
Script syntax inside `--text` / `--text-file`:
- Sentences are split on `. ! ? …`; long ones also at `, ; :`.- `[duraksama:0.3]` inserts exactly 0.3 s of silence; `[kısa duraksama]` / `[duraksama]` let the model pause.
The first run downloads the VoxCPM2 AudioVAE and a Turkish CTC aligner from Hugging Face. Laterruns can skip the Hub's network checks with `HF_HUB_OFFLINE=1` (useful on slow or IPv6-brokennetworks). Each `nida say` call loads the models again (about a minute on an RTX 5070); thesynthesis itself takes a few seconds.
## Related work
[FreyaTTS](https://arxiv.org/abs/2607.09530) (2026) is a Turkish text-to-speech model with asimilar recipe: a non-autoregressive flow-matching DiT on frozen AudioVAE2 latents with a Turkishcharacter vocabulary, 183 M parameters. Its numbers are on a different test set and are notdirectly comparable with ours.
## Responsible use
**Do not use Nida to imitate a real person's voice without their explicit consent**, to deceive,or to impersonate anyone (including public figures). Generated audio must not be presented as areal recording of a person. By using the model you agree to these terms in addition to theCC-BY-NC-4.0 license (non-commercial use only).
## Licenses and attribution
- Model weights: CC-BY-NC-4.0. Code: Apache-2.0.- YODAS (espnet/yodas, CC-BY-3.0), alania synthetic speech (cloud0day3/alania-synthetic-speech-tr, CC-BY-4.0), VoxCPM2 AudioVAE and voice design (openbmb/VoxCPM2, Apache-2.0), Turkish CTC aligner (mpoyraz/wav2vec2-xls-r-300m-cv7-turkish, CC-BY-4.0).123version https://git-lfs.github.com/spec/v1oid sha256:bd7ff9d7166f99b7df64a5e4ac30c43bce72868138d80bb97cca4e8ca3b939a3size 8052760811234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768[build-system]requires = ["hatchling>=1.24"]build-backend = "hatchling.build"
[project]name = "nida"version = "0.5.0"description = "Nida: expressive Turkish text-to-speech (research, non-commercial weights)"readme = "README.md"requires-python = ">=3.11"# Core carries only the text normaliser base (turkificate, MIT, pure Python). torch is not a# core dependency: Colab ships its own CUDA build; the `model` extra (ADR-0005) is for local CPU tests only.dependencies = ["turkificate==0.2.0"]
[project.optional-dependencies]# Phase 0 benchmarks (nida.bench); model libraries live only in isolated worker envs.bench = ["numpy>=2.0", "scipy>=1.13", "soundfile>=0.12", "pyyaml>=6.0"]# Phase 1 data pipeline (nida.data): Parquet stage manifests.data = ["nida[bench]", "pyarrow>=17"]# Phase 2 model code, local CPU tests (ADR-0005): same torch as Colab's runtime (2.11.0).model = ["torch==2.11.0"]
[dependency-groups]# PEP 735 group: uv installs it by default for `uv sync` / `uv run`.dev = [ "nida[data,model]", "pytest>=8.0", "hypothesis>=6.100", "ruff>=0.6", "mypy>=1.10",]
[project.scripts]nida = "nida.cli:main"
[tool.hatch.build.targets.wheel]packages = ["src/nida"]
[tool.ruff]line-length = 100target-version = "py311"src = ["src", "tests", "lab", "lab/akan"]
[tool.ruff.lint]select = ["E", "F", "W", "I", "B", "UP", "SIM", "RUF", "PTH", "BLE"]# Turkish dotless "ı" is a real letter here, not a confusable.allowed-confusables = ["ı", "–", "−", "×"]
[tool.mypy]python_version = "3.11"strict = truefiles = ["src/nida", "tests", "lab/akan"]# lab/akan holds the `akan` package (lab/akan/akan); `lab` is listed for later lab experiments.mypy_path = ["src", "lab/akan", "lab"]
[[tool.mypy.overrides]]# turkificate (text normaliser base, MIT) ships no py.typed marker; nida.text.normalize wraps it.module = ["turkificate", "turkificate.*"]ignore_missing_imports = true
[tool.pytest.ini_options]testpaths = ["tests"]pythonpath = ["src", "lab/akan", "lab"]addopts = "-q --strict-markers -m 'not gpu'"markers = [ "gpu: requires a CUDA GPU (deselected by default; run with -m gpu)", "slow: long-running test",]1234567891011# Nida v0.5 inference (`nida say --single-env`). Install torch + torchaudio first, a CUDA# build for your GPU (https://pytorch.org/get-started/locally/), e.g.:# pip install torch torchaudio --index-url https://download.pytorch.org/whl/cu128# then: pip install -r requirements.txt && pip install -e .transformers==4.57.6huggingface-hubnumpyscipysoundfilepydanticpyyaml1234567"""Nida: expressive Turkish text-to-speech."""
from __future__ import annotations
__all__ = ["__version__"]
__version__ = "0.0.1"1"""Phase 0 benchmarks (B1 ASR comparison, B2 VAE reconstruction) and listening panels."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570"""Objective audio metrics for comparing an original waveform with a reconstruction (B2).
All functions are pure and CPU-only (numpy + scipy). Conventions:
* Waveforms are 1-D float arrays of shape ``(num_samples,)``. Any floating dtype is accepted and converted to ``float64``; integer and complex dtypes are rejected.* Sample rates are integers in Hz (``sample_rate_hz``), frequencies are in Hz (``*_hz``), lengths are in samples (``*_samples``).* Spectrograms are laid out as ``(frames, bins)``.* Inputs are validated at the module boundary and violations raise :class:`ValueError` with the offending argument named."""
from __future__ import annotations
import mathfrom typing import TypeAlias
import numpy as npimport numpy.typing as npt
# scipy ships no type stubs; the ignore is scoped to this single import.from scipy import signal # type: ignore[import-untyped]
__all__ = [ "FloatArray", "align", "band_energy_ratio", "band_log_spectral_distance", "band_power_db", "estimate_delay_samples", "log_mel_l1", "mel_filterbank", "resample", "stft_magnitude",]
FloatArray: TypeAlias = npt.NDArray[np.float64]
# Relative tolerance under which two cross-correlation values count as tied in# ``estimate_delay_samples`` (FFT round-off makes exact float ties unreliable)._TIE_RTOL = 1e-9
# --------------------------------------------------------------------------------------# Validation helpers# --------------------------------------------------------------------------------------
def _as_waveform(x: npt.ArrayLike, name: str) -> FloatArray: """Validate ``x`` as a non-empty, finite 1-D float waveform and return it as float64.""" arr = np.asarray(x) if arr.dtype.kind != "f": raise ValueError(f"{name} must have a floating dtype, got {arr.dtype}") if arr.ndim != 1: raise ValueError(f"{name} must be 1-D, got shape {arr.shape}") if arr.size == 0: raise ValueError(f"{name} must not be empty") out = arr.astype(np.float64) if not np.isfinite(out).all(): raise ValueError(f"{name} contains non-finite values (NaN or inf)") return out
def _check_int(value: int, name: str) -> int: if isinstance(value, bool) or not isinstance(value, int | np.integer): raise ValueError(f"{name} must be an int, got {value!r}") return int(value)
def _check_positive_int(value: int, name: str) -> int: ivalue = _check_int(value, name) if ivalue <= 0: raise ValueError(f"{name} must be > 0, got {ivalue}") return ivalue
def _check_positive_float(value: float, name: str) -> float: fvalue = float(value) if not (math.isfinite(fvalue) and fvalue > 0.0): raise ValueError(f"{name} must be a finite number > 0, got {value!r}") return fvalue
def _check_band(sample_rate_hz: int, low_hz: float, high_hz: float) -> None: nyquist_hz = sample_rate_hz / 2 # Written as a negated chain so NaN bounds are rejected too. if not (0.0 <= low_hz < high_hz <= nyquist_hz): raise ValueError( f"frequency band must satisfy 0 <= low_hz < high_hz <= {nyquist_hz} " f"(sample_rate_hz/2), got low_hz={low_hz}, high_hz={high_hz}" )
def _trim_to_common_length(ref: FloatArray, est: FloatArray) -> tuple[FloatArray, FloatArray]: num_samples = min(ref.shape[0], est.shape[0]) return ref[:num_samples], est[:num_samples]
# --------------------------------------------------------------------------------------# Resampling# --------------------------------------------------------------------------------------
def resample(x: npt.ArrayLike, sample_rate_hz: int, target_rate_hz: int) -> FloatArray: """Resample a waveform with a polyphase filter.
Uses :func:`scipy.signal.resample_poly` with the up/down factors reduced by their gcd. When the rates are equal a copy of the input is returned.
Args: x: Waveform, shape ``(num_samples,)``, any float dtype. sample_rate_hz: Source sample rate in Hz (> 0). target_rate_hz: Target sample rate in Hz (> 0).
Returns: ``float64`` array of shape ``(ceil(num_samples * target_rate_hz / sample_rate_hz),)``.
Raises: ValueError: If ``x`` is not a finite non-empty 1-D float array or a rate is <= 0. """ wave = _as_waveform(x, "x") source_hz = _check_positive_int(sample_rate_hz, "sample_rate_hz") target_hz = _check_positive_int(target_rate_hz, "target_rate_hz") if source_hz == target_hz: return wave.copy() divisor = math.gcd(source_hz, target_hz) up = target_hz // divisor down = source_hz // divisor out = np.asarray(signal.resample_poly(wave, up, down), dtype=np.float64) return out
# --------------------------------------------------------------------------------------# Spectral front end# --------------------------------------------------------------------------------------
def _hz_to_mel(freq_hz: FloatArray) -> FloatArray: return np.asarray(2595.0 * np.log10(1.0 + freq_hz / 700.0), dtype=np.float64)
def _mel_to_hz(mel: FloatArray) -> FloatArray: return np.asarray(700.0 * (10.0 ** (mel / 2595.0) - 1.0), dtype=np.float64)
def _bin_frequencies_hz(sample_rate_hz: int, n_fft: int) -> FloatArray: return np.arange(n_fft // 2 + 1, dtype=np.float64) * sample_rate_hz / n_fft
def mel_filterbank( sample_rate_hz: int, n_fft: int, n_mels: int, fmin_hz: float = 0.0, fmax_hz: float | None = None,) -> FloatArray: """Build a triangular HTK mel filterbank.
The mel scale is ``2595 * log10(1 + f / 700)``. ``n_mels + 2`` points equally spaced on the mel axis between ``fmin_hz`` and ``fmax_hz`` define the filters: filter ``i`` rises linearly from point ``i`` to point ``i + 1`` and falls linearly to point ``i + 2``. Filters are *not* area-normalised, so the continuous peak is 1.0 (a sampled filter reaches 1.0 only when an FFT bin sits exactly on its centre).
Args: sample_rate_hz: Sample rate in Hz (> 0). n_fft: FFT size in samples (> 0). n_mels: Number of mel filters (> 0). fmin_hz: Lowest filter edge in Hz, ``0 <= fmin_hz < fmax_hz``. fmax_hz: Highest filter edge in Hz, ``<= sample_rate_hz / 2``. Defaults to ``sample_rate_hz / 2``.
Returns: Array of shape ``(n_mels, n_fft // 2 + 1)``, non-negative, ``float64``.
Raises: ValueError: On invalid arguments, or if some filter covers no FFT bin (``n_mels`` is too large for ``n_fft``), since such a filter would silently output zeros. """ rate_hz = _check_positive_int(sample_rate_hz, "sample_rate_hz") fft_size = _check_positive_int(n_fft, "n_fft") num_mels = _check_positive_int(n_mels, "n_mels") top_hz = rate_hz / 2 if fmax_hz is None else float(fmax_hz) _check_band(rate_hz, float(fmin_hz), top_hz)
mel_points = np.linspace( _hz_to_mel(np.asarray(float(fmin_hz))), _hz_to_mel(np.asarray(top_hz)), num_mels + 2, dtype=np.float64, ) edges_hz = _mel_to_hz(mel_points) left_hz = edges_hz[:-2, np.newaxis] centre_hz = edges_hz[1:-1, np.newaxis] right_hz = edges_hz[2:, np.newaxis] freqs_hz = _bin_frequencies_hz(rate_hz, fft_size)[np.newaxis, :]
rising = (freqs_hz - left_hz) / (centre_hz - left_hz) falling = (right_hz - freqs_hz) / (right_hz - centre_hz) bank = np.maximum(0.0, np.minimum(rising, falling)).astype(np.float64)
empty = np.flatnonzero(bank.max(axis=1) <= 0.0) if empty.size > 0: raise ValueError( f"{empty.size} of {num_mels} mel filters cover no FFT bin " f"(first empty index {int(empty[0])}); n_fft={fft_size} is too small for " f"n_mels={num_mels} at sample_rate_hz={rate_hz}" ) return np.asarray(bank, dtype=np.float64)
def stft_magnitude(x: npt.ArrayLike, n_fft: int, hop_samples: int) -> FloatArray: """Magnitude STFT with a periodic Hann window and no centering.
Frame ``t`` covers samples ``[t * hop_samples, t * hop_samples + n_fft)``. The tail is zero-padded so the last partial frame is included, and inputs shorter than ``n_fft`` are zero-padded to a single frame.
Args: x: Waveform, shape ``(num_samples,)``, any float dtype. n_fft: FFT and window size in samples (> 0). hop_samples: Hop between frames in samples (> 0).
Returns: Array of shape ``(frames, n_fft // 2 + 1)`` with ``frames = 1 + ceil(max(0, num_samples - n_fft) / hop_samples)``.
Raises: ValueError: If ``x`` is invalid or ``n_fft`` / ``hop_samples`` is <= 0. """ wave = _as_waveform(x, "x") fft_size = _check_positive_int(n_fft, "n_fft") hop = _check_positive_int(hop_samples, "hop_samples")
num_samples = wave.shape[0] num_frames = 1 + -(-max(0, num_samples - fft_size) // hop) padded_samples = (num_frames - 1) * hop + fft_size padded = np.zeros(padded_samples, dtype=np.float64) padded[:num_samples] = wave
window = np.asarray(signal.get_window("hann", fft_size, fftbins=True), dtype=np.float64) frames = np.lib.stride_tricks.sliding_window_view(padded, fft_size)[::hop] spectrum = np.fft.rfft(frames * window, axis=1) return np.abs(spectrum).astype(np.float64)
# --------------------------------------------------------------------------------------# Metrics# --------------------------------------------------------------------------------------
def log_mel_l1( ref: npt.ArrayLike, est: npt.ArrayLike, sample_rate_hz: int, n_fft: int, hop_samples: int, n_mels: int, eps: float = 1e-5,) -> float: """Log-mel L1 distance between a reference and an estimate.
Both waveforms are trimmed to the shorter length, converted to magnitude STFTs, projected through the mel filterbank (magnitude, not power), floored at ``eps`` and compared in ``log10``. The result is the mean absolute difference over all frames and mel bands.
Args: ref: Reference waveform, shape ``(num_samples,)``. est: Estimated waveform, shape ``(num_samples,)``; may differ in length from ``ref``. sample_rate_hz: Sample rate of both signals in Hz. n_fft: FFT size in samples. hop_samples: STFT hop in samples. n_mels: Number of mel bands. eps: Floor applied to the mel magnitudes before ``log10`` (> 0).
Returns: Mean absolute difference in log10 mel magnitude (dimensionless, >= 0).
Raises: ValueError: On invalid waveforms or arguments (see :func:`mel_filterbank` and :func:`stft_magnitude`). """ ref_wave = _as_waveform(ref, "ref") est_wave = _as_waveform(est, "est") floor = _check_positive_float(eps, "eps") bank = mel_filterbank(sample_rate_hz, n_fft, n_mels) ref_wave, est_wave = _trim_to_common_length(ref_wave, est_wave)
ref_mel = stft_magnitude(ref_wave, n_fft, hop_samples) @ bank.T est_mel = stft_magnitude(est_wave, n_fft, hop_samples) @ bank.T diff = np.log10(np.maximum(ref_mel, floor)) - np.log10(np.maximum(est_mel, floor)) return float(np.mean(np.abs(diff)))
def _band_mask( sample_rate_hz: int, n_fft: int, low_hz: float, high_hz: float) -> npt.NDArray[np.bool_]: """Boolean mask over FFT bins belonging to the band (see :func:`band_power_db`).""" freqs_hz = _bin_frequencies_hz(sample_rate_hz, n_fft) upper = freqs_hz <= high_hz if high_hz == sample_rate_hz / 2 else freqs_hz < high_hz mask: npt.NDArray[np.bool_] = (freqs_hz >= low_hz) & upper if not mask.any(): raise ValueError( f"no FFT bin falls in [{low_hz}, {high_hz}) Hz with n_fft={n_fft} at " f"sample_rate_hz={sample_rate_hz} (bin spacing {sample_rate_hz / n_fft} Hz)" ) return mask
def _band_power( x: FloatArray, sample_rate_hz: int, n_fft: int, hop_samples: int, mask: npt.NDArray[np.bool_]) -> FloatArray: """Power spectrogram restricted to in-band bins, shape ``(frames, num_band_bins)``.""" power = stft_magnitude(x, n_fft, hop_samples) ** 2 return np.asarray(power[:, mask], dtype=np.float64)
def band_power_db( x: npt.ArrayLike, sample_rate_hz: int, low_hz: float, high_hz: float, n_fft: int = 2048, hop_samples: int = 512, eps: float = 1e-10,) -> FloatArray: """Per-frame mean power in a frequency band, in dB.
The band contains the FFT bins ``k`` with centre frequency ``f_k = k * sample_rate_hz / n_fft`` satisfying ``low_hz <= f_k < high_hz``. When ``high_hz == sample_rate_hz / 2`` the upper edge is inclusive so the Nyquist bin belongs to the band. For each frame the result is ``10 * log10(mean_k(|X_k|^2) + eps)`` where ``X`` is the Hann-windowed STFT from :func:`stft_magnitude` (unnormalised, so absolute values depend on ``n_fft``; compare like with like).
Args: x: Waveform, shape ``(num_samples,)``. sample_rate_hz: Sample rate in Hz. low_hz: Lower band edge in Hz, ``0 <= low_hz < high_hz``. high_hz: Upper band edge in Hz, ``<= sample_rate_hz / 2``. n_fft: FFT size in samples. hop_samples: STFT hop in samples. eps: Power floor added before the logarithm (> 0).
Returns: Array of shape ``(frames,)`` in dB.
Raises: ValueError: On invalid arguments, or if no FFT bin falls in the band. """ wave = _as_waveform(x, "x") rate_hz = _check_positive_int(sample_rate_hz, "sample_rate_hz") fft_size = _check_positive_int(n_fft, "n_fft") hop = _check_positive_int(hop_samples, "hop_samples") floor = _check_positive_float(eps, "eps") _check_band(rate_hz, float(low_hz), float(high_hz)) mask = _band_mask(rate_hz, fft_size, float(low_hz), float(high_hz))
in_band = _band_power(wave, rate_hz, fft_size, hop, mask) return np.asarray(10.0 * np.log10(in_band.mean(axis=1) + floor), dtype=np.float64)
def band_log_spectral_distance( ref: npt.ArrayLike, est: npt.ArrayLike, sample_rate_hz: int, low_hz: float, high_hz: float, n_fft: int = 2048, hop_samples: int = 512, eps: float = 1e-10, active_within_db: float | None = None,) -> float: """Log-spectral distance (RMS over in-band bins, mean over frames) in dB.
With ``active_within_db`` only *active* frames are averaged: frames whose full-band reference power is within that many dB of the loudest reference frame. This keeps silence and noise-floor frames (where ``eps`` dominates) from swamping the average.
Both waveforms are trimmed to the shorter length. Per frame the distance is ``sqrt(mean_k((10 log10(P_ref[k] + eps) - 10 log10(P_est[k] + eps))^2))`` over the in-band bins ``k`` (band definition: see :func:`band_power_db`); the result is the mean over frames.
Args: ref: Reference waveform, shape ``(num_samples,)``. est: Estimated waveform, shape ``(num_samples,)``; may differ in length from ``ref``. sample_rate_hz: Sample rate of both signals in Hz. low_hz: Lower band edge in Hz. high_hz: Upper band edge in Hz. n_fft: FFT size in samples. hop_samples: STFT hop in samples. eps: Power floor added before the logarithm (> 0). active_within_db: If set (> 0), average only over active frames (see above).
Returns: Distance in dB (>= 0; 0 for identical signals).
Raises: ValueError: On invalid arguments, or if no FFT bin falls in the band. """ ref_wave = _as_waveform(ref, "ref") est_wave = _as_waveform(est, "est") rate_hz = _check_positive_int(sample_rate_hz, "sample_rate_hz") fft_size = _check_positive_int(n_fft, "n_fft") hop = _check_positive_int(hop_samples, "hop_samples") floor = _check_positive_float(eps, "eps") _check_band(rate_hz, float(low_hz), float(high_hz)) mask = _band_mask(rate_hz, fft_size, float(low_hz), float(high_hz)) ref_wave, est_wave = _trim_to_common_length(ref_wave, est_wave)
ref_power = _band_power(ref_wave, rate_hz, fft_size, hop, mask) est_power = _band_power(est_wave, rate_hz, fft_size, hop, mask) diff_db = 10.0 * np.log10(ref_power + floor) - 10.0 * np.log10(est_power + floor) per_frame = np.sqrt(np.mean(diff_db**2, axis=1)) if active_within_db is not None: window_db = _check_positive_float(active_within_db, "active_within_db") full_power = np.sum(stft_magnitude(ref_wave, fft_size, hop) ** 2, axis=1) full_db = 10.0 * np.log10(full_power + floor) active = full_db >= float(np.max(full_db)) - window_db per_frame = per_frame[active] return float(np.mean(per_frame))
def band_energy_ratio( ref: npt.ArrayLike, est: npt.ArrayLike, sample_rate_hz: int, low_hz: float, high_hz: float, n_fft: int = 2048, hop_samples: int = 512,) -> float: """Ratio of in-band energy of the estimate to that of the reference.
Both waveforms are trimmed to the shorter length. The energy of a signal is the sum of ``|X_k|^2`` over all frames and all in-band bins ``k`` (band definition: see :func:`band_power_db`).
Args: ref: Reference waveform, shape ``(num_samples,)``. est: Estimated waveform, shape ``(num_samples,)``; may differ in length from ``ref``. sample_rate_hz: Sample rate of both signals in Hz. low_hz: Lower band edge in Hz. high_hz: Upper band edge in Hz. n_fft: FFT size in samples. hop_samples: STFT hop in samples.
Returns: ``E_est / E_ref`` (dimensionless, >= 0; 1 for identical signals).
Raises: ValueError: On invalid arguments, if no FFT bin falls in the band, or if the reference has zero in-band energy (the ratio would be undefined). """ ref_wave = _as_waveform(ref, "ref") est_wave = _as_waveform(est, "est") rate_hz = _check_positive_int(sample_rate_hz, "sample_rate_hz") fft_size = _check_positive_int(n_fft, "n_fft") hop = _check_positive_int(hop_samples, "hop_samples") _check_band(rate_hz, float(low_hz), float(high_hz)) mask = _band_mask(rate_hz, fft_size, float(low_hz), float(high_hz)) ref_wave, est_wave = _trim_to_common_length(ref_wave, est_wave)
ref_energy = float(np.sum(_band_power(ref_wave, rate_hz, fft_size, hop, mask))) est_energy = float(np.sum(_band_power(est_wave, rate_hz, fft_size, hop, mask))) if ref_energy == 0.0: raise ValueError( f"reference has zero energy in [{low_hz}, {high_hz}) Hz; energy ratio is undefined" ) return est_energy / ref_energy
# --------------------------------------------------------------------------------------# Alignment# --------------------------------------------------------------------------------------
def estimate_delay_samples(ref: npt.ArrayLike, est: npt.ArrayLike, max_lag_samples: int) -> int: """Estimate the delay of ``est`` relative to ``ref`` by cross-correlation.
The cross-correlation ``c[lag] = sum_n est[n] * ref[n - lag]`` is computed with FFTs (zero-padded, so there is no circular wrap-around) and maximised over ``-max_lag_samples <= lag <= +max_lag_samples``, further limited to lags for which the signals overlap. A positive result means ``est`` is delayed: ``est[n] ~ ref[n - lag]``.
Ties (values within a relative tolerance of ``1e-9`` of the best) resolve to the smallest ``|lag|``; between ``+k`` and ``-k`` the positive lag wins. Two all-zero signals yield 0.
Args: ref: Reference waveform, shape ``(num_ref_samples,)``. est: Estimated waveform, shape ``(num_est_samples,)``. max_lag_samples: Largest absolute lag to consider (>= 0).
Returns: Delay in samples (``int``) in ``[-max_lag_samples, +max_lag_samples]``.
Raises: ValueError: On invalid waveforms or negative / non-integer ``max_lag_samples``. """ ref_wave = _as_waveform(ref, "ref") est_wave = _as_waveform(est, "est") max_lag = _check_int(max_lag_samples, "max_lag_samples") if max_lag < 0: raise ValueError(f"max_lag_samples must be >= 0, got {max_lag}")
num_ref = ref_wave.shape[0] num_est = est_wave.shape[0] max_positive = min(max_lag, num_est - 1) # est[n] needs n = lag + m with m >= 0 max_negative = min(max_lag, num_ref - 1)
fft_size = 1 << (num_ref + num_est - 1).bit_length() est_spectrum = np.fft.rfft(est_wave, fft_size) ref_spectrum = np.fft.rfft(ref_wave, fft_size) corr = np.fft.irfft(est_spectrum * np.conj(ref_spectrum), fft_size)
# Candidate lags ordered by |lag| (0, +1, -1, +2, -2, ...), so the first maximal entry # is the smallest-|lag| tie winner. lags: list[int] = [0] for k in range(1, max(max_positive, max_negative) + 1): if k <= max_positive: lags.append(k) if k <= max_negative: lags.append(-k) lag_arr = np.asarray(lags, dtype=np.int64) values = corr[lag_arr % fft_size] # negative lags wrap to the end of the circular buffer
peak = float(values.max()) tolerance = _TIE_RTOL * float(np.abs(values).max()) best = int(np.argmax(values >= peak - tolerance)) return int(lag_arr[best])
def align( ref: npt.ArrayLike, est: npt.ArrayLike, delay_samples: int) -> tuple[FloatArray, FloatArray]: """Compensate a known delay of ``est`` and trim both signals to a common length.
With ``delay_samples = d > 0`` (``est`` lags ``ref``) the first ``d`` samples of ``est`` are dropped; with ``d < 0`` (``est`` leads) the first ``|d|`` samples of ``ref`` are dropped. Both outputs are then cut to the shorter of the two remaining lengths.
Args: ref: Reference waveform, shape ``(num_ref_samples,)``. est: Estimated waveform, shape ``(num_est_samples,)``. delay_samples: Delay of ``est`` relative to ``ref``, as returned by :func:`estimate_delay_samples`.
Returns: ``(ref_aligned, est_aligned)``, two ``float64`` copies of identical length >= 1.
Raises: ValueError: On invalid waveforms, non-integer ``delay_samples``, or if no samples remain after compensating the delay. """ ref_wave = _as_waveform(ref, "ref") est_wave = _as_waveform(est, "est") delay = _check_int(delay_samples, "delay_samples")
if delay >= 0: ref_part, est_part = ref_wave, est_wave[delay:] else: ref_part, est_part = ref_wave[-delay:], est_wave ref_part, est_part = _trim_to_common_length(ref_part, est_part) if ref_part.shape[0] < 1: raise ValueError( f"no samples left after compensating delay_samples={delay} " f"(ref has {ref_wave.shape[0]}, est has {est_wave.shape[0]} samples)" ) return ref_part.copy(), est_part.copy()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622"""Benchmark B1: Turkish ASR comparison (docs/benchmarks/B1-B2-tasarim.md §1).
Stages (each idempotent and resumable):
1. ``prepare`` — :func:`nida.bench.prepare.prepare_b1` (layers A, B and the C pool).
2. ``asr`` — every system transcribes every clip in its own environment.
3. ``panel`` — choose the final layer-C clips (filler-rich, once) and build the
transcription panel; the user's corrected transcripts become C references.
4. ``score`` — metrics, paired bootstrap and the pre-registered decision rule.
Failed worker items are scored as empty hypotheses (all deletions) and counted, so a
system can never look better by failing on hard clips.
"""
from __future__ import annotations
import itertools
import json
import logging
import subprocess
from collections.abc import Callable, Mapping, Sequence
from contextvars import ContextVar
from dataclasses import dataclass, field
from pathlib import Path
from nida.bench.clips import Clip, select_yodas_final, text_has_filler
from nida.bench.panel import (
AudioRef,
PanelItem,
PanelResult,
PanelSpec,
Question,
write_panel,
)
from nida.bench.prepare import Workspace, clip_audio_path
from nida.bench.protocol import (
WorkerSummary,
WorkRequest,
WorkResult,
load_results,
read_summary,
write_requests,
)
from nida.bench.registry import System
from nida.bench.textmetrics import (
FILLERS,
EditCounts,
cer_counts,
corpus_rate,
filler_score,
has_digits,
is_hallucination,
normalize_for_scoring,
paired_bootstrap,
strip_fillers,
wer_counts,
)
from nida.utils.io import atomic_write_json
__all__ = [
"C_PANEL_QUESTIONS",
"DecisionRule",
"FillerProvenance",
"build_c_panel",
"c_references_from_panel",
"choose_systems",
"hypotheses",
"load_c_selection",
"run_system",
"score_b1",
]
log = logging.getLogger(__name__)
MAX_ERROR_FRACTION = 0.05
N_C_FINAL = 50
# Pre-registered 25; lowered to 20 before any score was seen (pool had 23 filler clips,
# run 20261008-122110-bench-phase0-b301; docs/benchmarks/B1-B2-tasarim.md §1.1).
MIN_C_FILLER_CLIPS = 20
C_REVIEWED_ANSWERS = ("tamam", "emin değilim")
C_SKIP_ANSWER = "konuşma değil — atla"
C_PANEL_QUESTIONS = (
Question(
"durum",
"Bu klip için durum",
"choice",
(*C_REVIEWED_ANSWERS, C_SKIP_ANSWER),
required=True,
),
)
C_PANEL_INSTRUCTIONS = (
"Her klibi dinleyin ve metin kutusundaki taslağı duyduğunuz şekilde, kelimesi kelimesine "
"düzeltin. Taslak YouTube altyazısıdır, hatalı olabilir. Dolgu seslerini şu yazımlarla "
"ekleyin: ıı, ee, hmm, ımm, aa (ve of, uf, ah, oh, vay, hıı). Sayıları yazıyla yazın. "
"Noktalama önemli değil. Her klip için bir durum seçin: düzelttiyseniz 'tamam', "
"anlaşılmayan yer kaldıysa 'emin değilim', konuşma yoksa ya da müzik baskınsa "
"'konuşma değil — atla'. Durumu seçilmeyen klipler kullanılmaz."
)
Runner = Callable[[Sequence[str]], int]
#: Tag put in front of every line :func:`_stream_runner` logs. Callers that run several
#: workers at the same time set it (per thread) to the job name so the interleaved lines
#: stay attributable; empty (the default) logs exactly as before.
LOG_TAG: ContextVar[str] = ContextVar("nida_worker_log_tag", default="")
def _stream_runner(cmd: Sequence[str]) -> int:
tag = LOG_TAG.get()
prefix = f"[{tag}] " if tag else ""
log.info("%s$ %s", prefix, " ".join(cmd))
with subprocess.Popen(
list(cmd), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1
) as proc:
assert proc.stdout is not None # stdout=PIPE guarantees a stream
for line in proc.stdout:
log.info("%s | %s", prefix, line.rstrip())
return proc.wait()
def _worker_dir(workspace: Workspace, system: System, variant: str) -> Path:
name = system.system_id if not variant else f"{system.system_id}__{variant}"
return workspace.workers / name
def run_system(
workspace: Workspace,
clips: Sequence[Clip],
system: System,
python_exe: Path,
*,
variant: str = "",
context: str = "",
retry_failed: bool = False,
runner: Runner = _stream_runner,
) -> WorkerSummary:
"""Run one ASR system over ``clips`` (resumable) and return its summary.
Raises:
RuntimeError: if the worker exits non-zero or more than 5% of items failed.
"""
out_dir = _worker_dir(workspace, system, variant)
requests = [
WorkRequest(
clip.clip_id,
str(clip_audio_path(workspace, clip)),
{"language": clip.language, **({"context": context} if context else {})},
)
for clip in clips
]
write_requests(out_dir / "requests.jsonl", requests)
cmd = [
str(python_exe),
"-m",
f"nida.bench.workers.{system.worker}",
"--requests",
str(out_dir / "requests.jsonl"),
"--results",
str(out_dir / "results.jsonl"),
"--model-id",
system.model_id,
"--revision",
system.revision,
"--batch-size",
str(system.batch_size),
"--device",
"cuda",
*(["--retry-failed"] if retry_failed else []),
]
code = runner(cmd)
if code != 0:
raise RuntimeError(f"{system.system_id}: worker exited with code {code}")
summary = read_summary(out_dir / "results.summary.json")
total = summary.n_ok + summary.n_error
if total != len(clips):
raise RuntimeError(f"{system.system_id}: {total} results for {len(clips)} clips")
if summary.n_error > MAX_ERROR_FRACTION * total:
raise RuntimeError(
f"{system.system_id}: {summary.n_error}/{total} items failed (> 5%); "
"rerun with --retry-failed after fixing the cause"
)
return summary
def hypotheses(workspace: Workspace, system: System, variant: str = "") -> dict[str, WorkResult]:
return load_results(_worker_dir(workspace, system, variant) / "results.jsonl")
def _hyp_text(result: WorkResult | None) -> str:
if result is None or result.output is None:
return ""
text = result.output.get("text", "")
return text if isinstance(text, str) else ""
# --------------------------------------------------------------------------- C panel
@dataclass(frozen=True)
class FillerProvenance:
"""Why a layer-C clip may have been selected (used to de-bias filler recall).
Attributes:
caption: The YouTube caption contains a filler.
systems: Systems whose hypothesis contains a filler.
"""
caption: bool
systems: frozenset[str] = field(default_factory=frozenset)
def counts_for(self, system_id: str) -> bool:
"""True if the clip's selection does not depend solely on ``system_id``'s output.
Filler-signal clips are favoured during selection. If the only signal was this
system's own hypothesis, scoring its filler recall on the clip would reward it for
having caused the selection, so such clips are left out of its recall.
"""
return self.caption or not self.systems or bool(self.systems - {system_id})
def _filler_provenance(
clips: Sequence[Clip], all_hypotheses: Mapping[str, Mapping[str, WorkResult]]
) -> dict[str, FillerProvenance]:
out: dict[str, FillerProvenance] = {}
for clip in clips:
systems = frozenset(
system_id
for system_id, results in all_hypotheses.items()
if text_has_filler(_hyp_text(results.get(clip.clip_id)))
)
out[clip.clip_id] = FillerProvenance(text_has_filler(clip.meta.get("caption", "")), systems)
return out
def _selection_path(workspace: Workspace) -> Path:
return workspace.manifests / "b1_c_final.json"
def load_c_selection(workspace: Workspace, seed: int | None = None) -> dict[str, FillerProvenance]:
"""Read the stored layer-C selection: ``{clip_id: provenance}`` in selection order.
Raises:
ValueError: if ``seed`` is given and differs from the seed the selection used.
"""
obj = json.loads(_selection_path(workspace).read_text(encoding="utf-8"))
if seed is not None and obj.get("seed") != seed:
raise ValueError(f"stored C selection used seed {obj.get('seed')}, not {seed}")
return {
row["clip_id"]: FillerProvenance(bool(row["caption_filler"]), frozenset(row["systems"]))
for row in obj["clips"]
}
def build_c_panel(
workspace: Workspace,
pool: Sequence[Clip],
all_hypotheses: Mapping[str, Mapping[str, WorkResult]],
seed: int,
) -> tuple[list[Clip], Path]:
"""Select the final layer-C clips (once) and write their transcription panel.
The selection is stored once in ``manifests/b1_c_final.json`` together with each
clip's filler provenance and is never re-drawn: a rerun rebuilds the panel for the same
clips. Before the first selection every system must have a result for every pool clip.
The draft text is the YouTube caption, never a candidate system's output, so
references are not anchored to one of the systems under test.
Raises:
RuntimeError: if some system has not transcribed the whole pool, or the stored
selection does not belong to this pool.
"""
import soundfile # type: ignore[import-untyped] # bench extra
by_id = {c.clip_id: c for c in pool}
if _selection_path(workspace).exists():
selection = load_c_selection(workspace, seed)
stray = [cid for cid in selection if cid not in by_id]
if stray:
raise RuntimeError(f"stored C selection has clips outside the pool: {stray[:3]}")
final = [by_id[cid] for cid in selection]
else:
incomplete = sorted(
s for s, results in all_hypotheses.items() if not set(by_id) <= set(results)
)
if incomplete:
raise RuntimeError(f"systems have not transcribed the whole C pool: {incomplete}")
texts: dict[str, list[str]] = {}
for results in all_hypotheses.values():
for clip_id, result in results.items():
texts.setdefault(clip_id, []).append(_hyp_text(result))
final = list(
select_yodas_final(pool, texts, N_C_FINAL, seed, min_filler_clips=MIN_C_FILLER_CLIPS)
)
provenance = _filler_provenance(final, all_hypotheses)
atomic_write_json(
_selection_path(workspace),
{
"seed": seed,
"clips": [
{
"clip_id": c.clip_id,
"caption_filler": provenance[c.clip_id].caption,
"systems": sorted(provenance[c.clip_id].systems),
}
for c in final
],
},
)
panel_id = f"b1c-{seed}"
audio_dir = workspace.cache / "panel_audio" / panel_id
items: list[PanelItem] = []
for clip in final:
flac = audio_dir / f"{clip.clip_id}.flac"
if not flac.exists():
audio, rate_hz = soundfile.read(str(clip_audio_path(workspace, clip)), dtype="int16")
flac.parent.mkdir(parents=True, exist_ok=True)
soundfile.write(str(flac), audio, rate_hz, subtype="PCM_16")
items.append(
PanelItem(
item_id=clip.clip_id,
audios=(AudioRef("Klip", flac),),
text=clip.meta.get("caption", ""),
editable_text=True,
info=f"YODAS · {clip.duration_ms / 1000:.1f} s",
)
)
spec = PanelSpec(
panel_id=panel_id,
title="B1 — Doğal konuşma transkripsiyonu",
instructions=C_PANEL_INSTRUCTIONS,
questions=C_PANEL_QUESTIONS,
items=tuple(items),
)
return final, write_panel(spec, workspace.panels / panel_id)
def c_references_from_panel(results: Sequence[PanelResult]) -> dict[str, str]:
"""Usable C references: items explicitly reviewed (``tamam`` / ``emin değilim``).
Unreviewed items are excluded even though their CSV row carries the caption draft: an
untouched caption is not a reference (glued words, fillers almost never written).
"""
refs: dict[str, str] = {}
for result in results:
if result.answers.get("durum") not in C_REVIEWED_ANSWERS:
continue
text = (result.text or "").strip()
if text:
refs[result.item_id] = text
return refs
# --------------------------------------------------------------------------- scoring
@dataclass(frozen=True)
class DecisionRule:
"""Pre-registered rule (design note §1.4), fixed before results are seen.
Attributes:
min_filler_recall: Primary must reach this C filler recall (leave-one-out).
min_reviewed_c: With fewer reviewed C references the rule is not applied.
min_filler_ref_tokens: With fewer reference fillers in C the rule is not applied.
min_loo_ref_tokens: Per-system minimum of reference fillers left after the
leave-one-out exclusion (the denominator of the recall the rule uses).
max_failed_ab: Most failed worker items allowed per system on A+B; failed items are
scored as empty hypotheses, so any more would distort the CER ranking.
max_failed_c: Same for layer C, where a failed item turns its reference fillers into
misses and would distort the filler recall the rule depends on.
"""
min_filler_recall: float = 0.6
min_reviewed_c: int = 35
min_filler_ref_tokens: int = 30
min_loo_ref_tokens: int = 20
max_failed_ab: int = 0
max_failed_c: int = 0
def _layer_scores(
clips: Sequence[Clip],
refs: Mapping[str, str],
hyps: Mapping[str, WorkResult],
eligible_for_fillers: frozenset[str] | None = None,
) -> tuple[dict[str, object], list[EditCounts]]:
content_cer: list[EditCounts] = []
content_wer: list[EditCounts] = []
full_cer: list[EditCounts] = []
full_wer: list[EditCounts] = []
pairs: list[tuple[list[str], list[str]]] = []
loo_pairs: list[tuple[list[str], list[str]]] = []
n_failed = n_halluc = n_digits = 0
infer_s = audio_s = 0.0
for clip in clips:
ref_text = refs[clip.clip_id]
result = hyps.get(clip.clip_id)
hyp_text = _hyp_text(result)
if result is None or not result.ok:
n_failed += 1
else:
infer_s += result.infer_seconds
audio_s += clip.duration_ms / 1000
n_halluc += is_hallucination(ref_text, hyp_text)
n_digits += has_digits(hyp_text)
ref_tokens = normalize_for_scoring(ref_text)
hyp_tokens = normalize_for_scoring(hyp_text)
content_cer.append(cer_counts(strip_fillers(ref_tokens), strip_fillers(hyp_tokens)))
content_wer.append(wer_counts(strip_fillers(ref_tokens), strip_fillers(hyp_tokens)))
full_cer.append(cer_counts(ref_tokens, hyp_tokens))
full_wer.append(wer_counts(ref_tokens, hyp_tokens))
pairs.append((ref_tokens, hyp_tokens))
if eligible_for_fillers is None or clip.clip_id in eligible_for_fillers:
loo_pairs.append((ref_tokens, hyp_tokens))
fillers = filler_score(pairs)
loo = filler_score(loo_pairs)
n_ok = len(clips) - n_failed
scores: dict[str, object] = {
"n": len(clips),
"n_failed": n_failed,
"content_cer": corpus_rate(content_cer),
"content_wer": corpus_rate(content_wer),
"full_cer": corpus_rate(full_cer),
"full_wer": corpus_rate(full_wer),
"hallucination_rate": n_halluc / n_ok if n_ok else None,
"hyp_with_digits": n_digits,
"rtf": infer_s / audio_s if audio_s else None,
"filler_ref_total": fillers.ref_total,
"filler_hyp_total": fillers.hyp_total,
"filler_recall": fillers.recall(),
"filler_precision": fillers.precision(),
"filler_recall_loo": loo.recall(),
"filler_loo_ref_total": loo.ref_total,
"filler_recall_by_type": {
kind: filler_score(pairs, kind).recall()
for kind in sorted(FILLERS)
if filler_score(pairs, kind).ref_total
},
}
return scores, content_cer
def score_b1(
clips: Sequence[Clip],
systems: Sequence[System],
all_hypotheses: Mapping[str, Mapping[str, WorkResult]],
c_references: Mapping[str, str] | None,
*,
seed: int,
summaries: Mapping[str, WorkerSummary] | None = None,
c_provenance: Mapping[str, FillerProvenance] | None = None,
) -> dict[str, object]:
"""Compute B1 metrics per system and layer, plus paired bootstrap on content CER.
Layers: ``A``, ``B``, ``AB`` (A+B together) and ``C`` when ``c_references`` is given
(only reviewed clips present in it are scored). With ``c_provenance`` the C layer's
``filler_recall_loo`` excludes, per system, clips selected only because of that
system's own hypothesis (see :class:`FillerProvenance`).
"""
refs: dict[str, str] = {}
for clip in clips:
if clip.layer in ("A", "B") and clip.reference is not None:
refs[clip.clip_id] = clip.reference
if c_references:
refs.update(c_references)
layers: dict[str, list[Clip]] = {
"A": [c for c in clips if c.layer == "A"],
"B": [c for c in clips if c.layer == "B"],
}
layers["AB"] = layers["A"] + layers["B"]
if c_references:
layers["C"] = [c for c in clips if c.layer == "C" and c.clip_id in c_references]
per_system: dict[str, dict[str, dict[str, object]]] = {}
counts_for_bootstrap: dict[str, dict[str, list[EditCounts]]] = {}
for system in systems:
hyps = all_hypotheses[system.system_id]
per_layer: dict[str, dict[str, object]] = {}
for layer, layer_clips in layers.items():
eligible: frozenset[str] | None = None
if layer == "C" and c_provenance is not None:
eligible = frozenset(
cid for cid, prov in c_provenance.items() if prov.counts_for(system.system_id)
)
scores, counts = _layer_scores(layer_clips, refs, hyps, eligible)
counts_for_bootstrap.setdefault(layer, {})[system.system_id] = counts
per_layer[layer] = scores
worker: dict[str, object] = {"batch_size": system.batch_size, "worker": system.worker}
if summaries and system.system_id in summaries:
summary = summaries[system.system_id]
worker |= {
"peak_vram_gb": summary.peak_vram_gb,
"load_seconds": summary.load_seconds,
"n_error": summary.n_error,
"packages": dict(summary.packages),
}
per_layer["_worker"] = worker
per_system[system.system_id] = per_layer
bootstrap: dict[str, list[dict[str, object]]] = {}
for layer in ("AB", "B", "C"):
if layer not in counts_for_bootstrap or not layers[layer]:
continue
rows: list[dict[str, object]] = []
for a, b in itertools.combinations(sorted(counts_for_bootstrap[layer]), 2):
result = paired_bootstrap(
counts_for_bootstrap[layer][a], counts_for_bootstrap[layer][b], seed=seed
)
rows.append(
{"a": a, "b": b, "delta": result.delta, "low": result.low, "high": result.high}
)
bootstrap[layer] = rows
return {
"systems": per_system,
"bootstrap_content_cer": bootstrap,
"n_c_reviewed": len(layers.get("C", [])),
}
def _as_float(value: object, missing: float) -> float:
return float(value) if isinstance(value, int | float) else missing
def _decide(
systems: Mapping[str, Mapping[str, Mapping[str, object]]],
families: Mapping[str, str],
rule: DecisionRule,
cer_layer: str,
) -> dict[str, object]:
def cer(system_id: str) -> float:
return _as_float(systems[system_id][cer_layer]["content_cer"], float("inf"))
def recall(system_id: str) -> float:
c_layer = systems[system_id]["C"]
return _as_float(c_layer.get("filler_recall_loo", c_layer["filler_recall"]), -1.0)
ranked = sorted(systems, key=cer)
qualified = [s for s in ranked if recall(s) >= rule.min_filler_recall]
primary = qualified[0] if qualified else ranked[0]
others = [s for s in ranked if families[s] != families[primary]]
return {
"cer_layer": cer_layer,
"primary": primary,
"secondary": others[0] if others else None,
"needs_filler_method": not qualified,
"qualified_by_filler_recall": qualified,
}
def choose_systems(
scores: Mapping[str, object],
families: Mapping[str, str],
rule: DecisionRule | None = None,
) -> dict[str, object]:
"""Apply the pre-registered rule; returns the suggestion and its reasoning.
Primary: among systems whose C filler recall (leave-one-out when available) is at least
``rule.min_filler_recall``, the lowest A+B content CER. If none qualifies: the lowest
A+B content CER and ``needs_filler_method``. Secondary: the lowest A+B content CER among
systems of a *different family*. The same rule is also evaluated on layer B alone
(``without_fleurs``) because one candidate (BuzzASR) was trained on FLEURS; the result
says whether the pick changes. Not applied (``ready=False``) without enough reviewed C
references, reference fillers, a system whose leave-one-out filler denominator is below
``rule.min_loo_ref_tokens``, or a system with failed items beyond
``rule.max_failed_ab`` (A+B) / ``rule.max_failed_c`` (C) (the reason names them).
"""
rule = rule if rule is not None else DecisionRule()
systems = scores["systems"]
assert isinstance(systems, dict)
if not all("C" in layers for layers in systems.values()):
return {"ready": False, "reason": "C references (user panel) not available yet"}
n_reviewed = scores.get("n_c_reviewed", 0)
if not isinstance(n_reviewed, int) or n_reviewed < rule.min_reviewed_c:
return {
"ready": False,
"reason": f"only {n_reviewed} reviewed C clips (< {rule.min_reviewed_c})",
}
ref_fillers = min(int(_as_float(v["C"]["filler_ref_total"], 0)) for v in systems.values())
if ref_fillers < rule.min_filler_ref_tokens:
return {
"ready": False,
"reason": f"only {ref_fillers} reference fillers in C (< {rule.min_filler_ref_tokens})",
}
failed = {
f"{system_id}/{layer}": int(_as_float(v[layer].get("n_failed"), 0))
for system_id, v in systems.items()
for layer, limit in (("AB", rule.max_failed_ab), ("C", rule.max_failed_c))
if _as_float(v[layer].get("n_failed"), 0) > limit
}
if failed:
return {
"ready": False,
"reason": f"failed worker items (rerun with --retry-failed): {failed}",
}
thin = {
system_id: int(_as_float(v["C"].get("filler_loo_ref_total"), 0))
for system_id, v in systems.items()
if "filler_loo_ref_total" in v["C"]
and _as_float(v["C"]["filler_loo_ref_total"], 0) < rule.min_loo_ref_tokens
}
if thin:
return {
"ready": False,
"reason": f"leave-one-out filler denominators below {rule.min_loo_ref_tokens}: {thin}",
}
main = _decide(systems, families, rule, "AB")
check = _decide(systems, families, rule, "B")
return {
"ready": True,
**main,
"without_fleurs": check,
"pick_changes_without_fleurs": (main["primary"], main["secondary"])
!= (check["primary"], check["secondary"]),
"rule": {
"min_filler_recall": rule.min_filler_recall,
"min_reviewed_c": rule.min_reviewed_c,
"min_filler_ref_tokens": rule.min_filler_ref_tokens,
"min_loo_ref_tokens": rule.min_loo_ref_tokens,
"max_failed_ab": rule.max_failed_ab,
"max_failed_c": rule.max_failed_c,
},
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684"""Benchmark B2: audio-VAE reconstruction (docs/benchmarks/B1-B2-tasarim.md §2).
Stages (idempotent, resumable):
1. ``prepare`` — Turkish subsets from the B1 manifest + Expresso subsets streamed from the official 36 GB tar; originals written to ``<workspace>/b2/orig`` (16 kHz Turkish, 48 kHz Expresso, 24-bit). They live in the durable workspace (Drive), not the session cache, so a new Colab session resumes without re-streaming 36 GB and without results that point at vanished files.2. ``vae`` — VoxCPM2 AudioVAE V2 round trip (worker) → ``<workspace>/b2/vae`` (48 kHz).3. ``asr`` / ``quality`` — Whisper on 16 kHz copies of original and reconstruction (clips with references), Audiobox Aesthetics on both.4. ``score`` — objective metrics per subset, incl. the "band-16k" baseline (48 kHz → 16 kHz → 48 kHz) that isolates what the VAE's super-resolution adds.5. ``panel`` — 40 *blind* A/B pairs (random order per item; key stored outside the HTML in ``manifests/b2_panel_key-<seed>.json``) and the scoring of the user's answers.
Audiobox resamples to 16 kHz internally, so its scores say nothing about the band above8 kHz; the high-band LSD / energy ratio cover that."""
from __future__ import annotations
import jsonimport loggingimport randomfrom collections.abc import Mapping, Sequencefrom dataclasses import asdict, dataclassfrom pathlib import Pathfrom typing import Any
from nida.bench import fetchfrom nida.bench.audiometrics import ( align, band_energy_ratio, band_log_spectral_distance, estimate_delay_samples, log_mel_l1, resample,)from nida.bench.clips import Clip, clip_from_obj, clip_to_objfrom nida.bench.expresso import ( is_wanted_member, parse_member, parse_read_transcriptions, parse_vad_segments, select_expresso,)from nida.bench.panel import AudioRef, PanelItem, PanelResult, PanelSpec, Question, write_panelfrom nida.bench.prepare import Workspacefrom nida.bench.protocol import WorkRequest, WorkResultfrom nida.bench.registry import DATA_PINSfrom nida.bench.textmetrics import ( cer_counts, corpus_rate, normalize_english, normalize_for_scoring, strip_fillers,)from nida.utils.io import atomic_write_json, atomic_write_text
__all__ = [ "B2Plan", "asr_requests", "b2_paths", "build_b2_panel", "clip_metrics", "load_b2_manifest", "missing_vae_outputs", "prepare_b2", "quality_requests", "score_b2", "score_b2_panel", "vae_requests",]
log = logging.getLogger(__name__)
TR_SUBSETS = {"A": "tr-temiz", "B": "tr-medya"}HIGH_BAND_HZ = (8000.0, 24000.0)MAX_DELAY_MS = 50#: High-band LSD is averaged over frames within this many dB of the loudest frame.ACTIVE_WITHIN_DB = 40.0
@dataclass(frozen=True)class B2Plan: seed: int = 20261008 n_tr_per_layer: int = 30 n_whisper: int = 25 n_laughing: int = 25 n_projected: int = 25 n_nonverbal: int = 15 n_default: int = 10 n_panel_per_subset: int = 8 expresso_url: str = DATA_PINS["expresso_url"]
def expresso_counts(self) -> dict[str, int]: return { "whisper": self.n_whisper, "laughing": self.n_laughing, "projected": self.n_projected, "nonverbal": self.n_nonverbal, "default": self.n_default, }
@dataclass(frozen=True)class B2Paths: orig: Path vae: Path asr16k: Path
def b2_paths(workspace: Workspace) -> B2Paths: base = workspace.root / "b2" return B2Paths(base / "orig", base / "vae", base / "asr16k")
def _orig_path(workspace: Workspace, clip: Clip) -> Path: return b2_paths(workspace).orig / f"{clip.clip_id}.wav"
def _vae_path(workspace: Workspace, clip: Clip) -> Path: return b2_paths(workspace).vae / f"{clip.clip_id}.wav"
def _write_expresso_original(source: Path, clip: Clip, dest: Path) -> None: import soundfile # type: ignore[import-untyped] # bench extra
if dest.exists(): return audio: Any audio, rate_hz = soundfile.read(str(source), dtype="float64", always_2d=True) if rate_hz != 48000: raise ValueError(f"{source}: expected 48 kHz, got {rate_hz}") channel_text = clip.meta.get("channel", "0") if channel_text not in ("0", "1", "2"): raise ValueError(f"{clip.clip_id}: unknown channel {channel_text!r} (expected 0, 1 or 2)") channel = int(channel_text) column = 0 if channel in (0, 1) else 1 if channel == 0 and audio.shape[1] != 1: raise ValueError(f"{source}: read speech should be mono, got {audio.shape[1]} channels") if channel in (1, 2) and audio.shape[1] != 2: raise ValueError(f"{source}: conversational audio should be stereo") start = round(clip.start_ms * 48) stop = round(clip.end_ms * 48) if not 0 <= start < stop <= audio.shape[0]: raise ValueError(f"{source}: span {clip.start_ms}..{clip.end_ms} ms outside audio") dest.parent.mkdir(parents=True, exist_ok=True) tmp = dest.with_name(f".{dest.name}.tmp.wav") soundfile.write(str(tmp), audio[start:stop, column], 48000, subtype="PCM_24") tmp.replace(dest)
def prepare_b2( workspace: Workspace, b1_clips: Sequence[Clip], plan: B2Plan | None = None, *, opener: Any = None, # Any: urllib-compatible opener (see nida.bench.fetch)) -> list[Clip]: """Select B2 clips and write originals; the manifest is written once and reused.
Plan and clips are stored together in one atomically written ``b2_manifest.json`` after everything succeeded, so a stored plan and a stored clip list can never disagree, and a failed run leaves no manifest behind. """ import shutil
import soundfile
plan = plan if plan is not None else B2Plan() manifest = _manifest_path(workspace) stored_clips: list[Clip] | None = None if manifest.exists(): stored_plan, stored_clips = load_b2_manifest(workspace) if stored_plan != plan: raise ValueError(f"existing B2 manifest was built with {stored_plan}, not {plan}") rng = random.Random(plan.seed) tr_clips: list[Clip] = [] for layer, subset in TR_SUBSETS.items(): pool = sorted((c for c in b1_clips if c.layer == layer), key=lambda c: c.clip_id) if len(pool) < plan.n_tr_per_layer: raise ValueError(f"B1 layer {layer} has {len(pool)} clips, need {plan.n_tr_per_layer}") for clip in rng.sample(pool, plan.n_tr_per_layer): tr_clips.append( Clip.build( source_id=clip.source_id, layer=subset, file_id=clip.file_id, start_ms=clip.start_ms, end_ms=clip.end_ms, reference=clip.reference, language="tr", meta={**clip.meta, "b1_clip_id": clip.clip_id}, ) )
if stored_clips is not None and all(_orig_path(workspace, c).exists() for c in stored_clips): return stored_clips
exp_dir = workspace.cache / "expresso" extracted = fetch.stream_extract( plan.expresso_url, exp_dir, is_wanted_member, opener=opener if opener is not None else fetch.default_opener, ) by_name = {p.relative_to(exp_dir).as_posix(): p for p in extracted} vad_file = next((p for n, p in by_name.items() if n.endswith("VAD_segments.txt")), None) tr_file = next((p for n, p in by_name.items() if n.endswith("read_transcriptions.txt")), None) if vad_file is None or tr_file is None: raise FileNotFoundError( "Expresso archive lacks VAD_segments.txt or read_transcriptions.txt" ) files: list[tuple[Any, int]] = [] for name, path in sorted(by_name.items()): parsed = parse_member(name) if parsed is not None: info = soundfile.info(str(path)) # Floor, never round up: a length past the last sample makes spans invalid. files.append((parsed, (1000 * info.frames) // info.samplerate)) selection = select_expresso( files, parse_vad_segments(vad_file.read_text(encoding="utf-8")), parse_read_transcriptions(tr_file.read_text(encoding="utf-8")), plan.expresso_counts(), plan.seed, ) for clip in selection.clips: member = clip.file_id.split("#", 1)[0] _write_expresso_original(by_name[member], clip, _orig_path(workspace, clip)) for clip in tr_clips: dest = _orig_path(workspace, clip) if not dest.exists(): source_clip_id = clip.meta["b1_clip_id"] dest.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(workspace.clips16k / f"{source_clip_id}.wav", dest) clips = sorted([*tr_clips, *selection.clips], key=lambda c: (c.layer, c.clip_id)) if stored_clips is not None: if [c.clip_id for c in stored_clips] != [c.clip_id for c in clips]: raise ValueError("re-derived B2 clips differ from the stored manifest") return stored_clips atomic_write_text( workspace.manifests / "b2_quarantine.jsonl", "".join(json.dumps(asdict(q), ensure_ascii=False) + "\n" for q in selection.quarantined), ) atomic_write_json(manifest, {"plan": asdict(plan), "clips": [clip_to_obj(c) for c in clips]}) return clips
def _manifest_path(workspace: Workspace) -> Path: return workspace.manifests / "b2_manifest.json"
def load_b2_manifest(workspace: Workspace) -> tuple[B2Plan, list[Clip]]: """Read ``manifests/b2_manifest.json`` (plan and clips, written together).""" obj = json.loads(_manifest_path(workspace).read_text(encoding="utf-8")) return B2Plan(**obj["plan"]), [clip_from_obj(c) for c in obj["clips"]]
# ------------------------------------------------------------------------ worker inputs
def vae_requests(workspace: Workspace, clips: Sequence[Clip]) -> list[WorkRequest]: return [ WorkRequest( c.clip_id, str(_orig_path(workspace, c)), {"out_path": str(_vae_path(workspace, c))} ) for c in clips ]
def missing_vae_outputs(workspace: Workspace, results: Mapping[str, WorkResult]) -> list[str]: """Ids of successful VAE results whose output file no longer exists (to be redone).""" missing: list[str] = [] for clip_id, result in results.items(): out = result.output.get("out_path") if result.output is not None else None if result.ok and (not isinstance(out, str) or not Path(out).exists()): missing.append(clip_id) return missing
def _write_16k(source: Path, dest: Path) -> None: import soundfile
if dest.exists(): return audio: Any audio, rate_hz = soundfile.read(str(source), dtype="float64") if rate_hz != 16000: audio = resample(audio, int(rate_hz), 16000) peak = float(abs(audio).max()) if peak > 1.0: audio = audio / peak dest.parent.mkdir(parents=True, exist_ok=True) tmp = dest.with_name(f".{dest.name}.tmp.wav") soundfile.write(str(tmp), audio, 16000, subtype="PCM_16") tmp.replace(dest)
def asr_requests( workspace: Workspace, clips: Sequence[Clip], language: str, vae_results: Mapping[str, WorkResult] | None = None,) -> list[WorkRequest]: """Whisper requests for originals and reconstructions of clips with references.
Clips without a usable reconstruction (failed VAE item or missing file) get no requests at all: the CER comparison is paired, and scoring counts them as skipped. """ paths = b2_paths(workspace) requests: list[WorkRequest] = [] for clip in clips: if clip.language != language or not clip.reference: continue if not _usable_reconstruction(workspace, clip, vae_results): continue for kind, source in ( ("orig", _orig_path(workspace, clip)), ("vae", _vae_path(workspace, clip)), ): dest = paths.asr16k / f"{clip.clip_id}__{kind}.wav" _write_16k(source, dest) requests.append( WorkRequest(f"{clip.clip_id}__{kind}", str(dest), {"language": language}) ) return requests
def quality_requests( workspace: Workspace, clips: Sequence[Clip], vae_results: Mapping[str, WorkResult] | None = None,) -> list[WorkRequest]: """Audiobox requests for both members of every clip with a usable reconstruction.""" requests: list[WorkRequest] = [] for clip in clips: if not _usable_reconstruction(workspace, clip, vae_results): continue requests.append(WorkRequest(f"{clip.clip_id}__orig", str(_orig_path(workspace, clip)))) requests.append(WorkRequest(f"{clip.clip_id}__vae", str(_vae_path(workspace, clip)))) return requests
# ------------------------------------------------------------------------------ scoring
def clip_metrics(orig: Any, orig_rate_hz: int, recon: Any, recon_rate_hz: int) -> dict[str, float]: """Objective metrics for one original / reconstruction pair.
``orig`` and ``recon`` are 1-D float arrays (Any: numpy arrays, numpy is a bench extra). Both are compared at 16 kHz (mel @16k); when the original is 48 kHz they are also compared at 48 kHz (mel @48k, high-band LSD and energy ratio). The reconstruction is delay-aligned to the original first (cross-correlation at 16 kHz, ±50 ms). """ o16 = resample(orig, orig_rate_hz, 16000) r16 = resample(recon, recon_rate_hz, 16000) delay = estimate_delay_samples(o16, r16, MAX_DELAY_MS * 16) a16, b16 = align(o16, r16, delay) out: dict[str, float] = { "delay_ms": delay / 16, "mel16_l1": log_mel_l1(a16, b16, 16000, 1024, 256, 80), } if orig_rate_hz == 48000: r48 = resample(recon, recon_rate_hz, 48000) a48, b48 = align(orig, r48, delay * 3) out["mel48_l1"] = log_mel_l1(a48, b48, 48000, 2048, 480, 128) out["hb_lsd_db"] = band_log_spectral_distance( a48, b48, 48000, *HIGH_BAND_HZ, active_within_db=ACTIVE_WITHIN_DB ) out["hb_energy_ratio"] = band_energy_ratio(a48, b48, 48000, *HIGH_BAND_HZ) return out
def _mean(values: Sequence[float]) -> float | None: return sum(values) / len(values) if values else None
def _result_text(result: WorkResult | None) -> str | None: if result is None or result.output is None: return None raw = result.output.get("text") return raw if isinstance(raw, str) else None
def _scoring_tokens(text: str, language: str) -> list[str]: """Content tokens: Turkish pipeline without fillers, or the English normaliser.""" if language == "tr": return strip_fillers(normalize_for_scoring(text)) return normalize_english(text)
def _usable_reconstruction( workspace: Workspace, clip: Clip, vae_results: Mapping[str, WorkResult] | None) -> bool: """A reconstruction counts only if its worker result is ok *and* the file exists.""" if vae_results is not None: result = vae_results.get(clip.clip_id) if result is None or not result.ok: return False return _vae_path(workspace, clip).exists()
def score_b2( workspace: Workspace, clips: Sequence[Clip], asr_results: Mapping[str, WorkResult], quality_results: Mapping[str, WorkResult], vae_results: Mapping[str, WorkResult] | None = None,) -> dict[str, object]: """Aggregate per-subset metrics for the VAE and the band-16k baseline.
Clips without a usable reconstruction (failed worker result or missing file) are skipped and counted (``skipped``); every subset still gets a row (``n_scored`` may be 0). Quality deltas are averaged over *paired* clips (both members scored); CER compares original vs reconstruction only on clips where both transcriptions exist. """ import soundfile
per_subset: dict[str, dict[str, list[float]]] = {} cer_pairs: dict[str, dict[str, list[Any]]] = {} skipped: dict[str, int] = {} for clip in clips: vae_file = _vae_path(workspace, clip) if not _usable_reconstruction(workspace, clip, vae_results): skipped["missing_reconstruction"] = skipped.get("missing_reconstruction", 0) + 1 continue bucket = per_subset.setdefault(clip.layer, {}) bucket.setdefault("_n_scored", []).append(1.0) orig, orig_rate = soundfile.read(str(_orig_path(workspace, clip)), dtype="float64") recon, recon_rate = soundfile.read(str(vae_file), dtype="float64") for key, value in clip_metrics(orig, int(orig_rate), recon, int(recon_rate)).items(): bucket.setdefault(f"vae_{key}", []).append(value) if int(orig_rate) == 48000: band = resample(resample(orig, 48000, 16000), 16000, 48000) for key, value in clip_metrics(orig, 48000, band, 48000).items(): bucket.setdefault(f"band16k_{key}", []).append(value) pair = [quality_results.get(f"{clip.clip_id}__{kind}") for kind in ("orig", "vae")] if all(q is not None and q.output is not None for q in pair): non_numeric = False for axis in ("PQ", "CE"): scored = [q.output.get(axis) for q in pair if q is not None and q.output] numeric = [ v for v in scored if isinstance(v, int | float) and not isinstance(v, bool) ] if len(numeric) != 2: non_numeric = True else: orig_score, vae_score = float(numeric[0]), float(numeric[1]) bucket.setdefault(f"orig_{axis}", []).append(orig_score) bucket.setdefault(f"vae_{axis}", []).append(vae_score) bucket.setdefault(f"delta_{axis}", []).append(vae_score - orig_score) if non_numeric: # counted once per clip, not per axis skipped["non_numeric_quality"] = skipped.get("non_numeric_quality", 0) + 1 else: skipped["missing_quality_pair"] = skipped.get("missing_quality_pair", 0) + 1 if clip.reference: orig_text = _result_text(asr_results.get(f"{clip.clip_id}__orig")) vae_text = _result_text(asr_results.get(f"{clip.clip_id}__vae")) if orig_text is None or vae_text is None: skipped["missing_asr_pair"] = skipped.get("missing_asr_pair", 0) + 1 else: ref_tokens = _scoring_tokens(clip.reference, clip.language) for kind, text in (("orig", orig_text), ("vae", vae_text)): cer_pairs.setdefault(clip.layer, {}).setdefault(kind, []).append( cer_counts(ref_tokens, _scoring_tokens(text, clip.language)) ) for clip in clips: # subsets with nothing usable still get an (empty) row per_subset.setdefault(clip.layer, {}) summary: dict[str, dict[str, float | int | None]] = {} for subset, values in sorted(per_subset.items()): row: dict[str, float | int | None] = { "n": sum(1 for c in clips if c.layer == subset), "n_scored": len(values.pop("_n_scored", [])), } row.update({key: _mean(vals) for key, vals in sorted(values.items())}) pairs = cer_pairs.get(subset) if pairs: row["cer_orig"] = corpus_rate(pairs["orig"]) row["cer_vae"] = corpus_rate(pairs["vae"]) row["n_cer_pairs"] = len(pairs["orig"]) summary[subset] = row return {"subsets": summary, "skipped": skipped}
# -------------------------------------------------------------------------------- panel
B2_QUESTIONS = ( Question( "ayni_ifade", "A ve B aynı ifadeyi (fısıltı / gülme / bağırma / sözsüz ses / ton) taşıyor mu?", "choice", ("evet", "kısmen", "hayır"), ), Question( "kalite_a", "A'nın ses kalitesi (1 kötü, 5 kusursuz)", "scale", ("1", "2", "3", "4", "5") ), Question( "kalite_b", "B'nin ses kalitesi (1 kötü, 5 kusursuz)", "scale", ("1", "2", "3", "4", "5") ),)#: Pre-registered acceptance (design §2.4): per expressive subset, the share of "evet"#: ("kısmen" counts as *not* preserved) and the mean quality gap original − VAE.MIN_PRESERVED_SHARE = 0.8MAX_QUALITY_GAP = 1.0PANEL_SUBSETS = ("tr", "whisper", "laughing", "projected", "nonverbal")
def _panel_subset(clip: Clip) -> str: return "tr" if clip.layer.startswith("tr-") else clip.layer
def _key_path(workspace: Workspace, plan: B2Plan) -> Path: return workspace.manifests / f"b2_panel_key-{plan.seed}.json"
def build_b2_panel( workspace: Workspace, clips: Sequence[Clip], plan: B2Plan, vae_results: Mapping[str, WorkResult] | None = None,) -> Path: """Write the blind 40-pair listening panel and its answer key.
Per item the order of original and reconstruction is random and both are labelled neutrally ("A", "B"); the key lives in ``manifests/`` and never in the HTML. When either member peaks above full scale, the *same* gain is applied to both so clipping does not bias the comparison; the gain is recorded in the key. """ import numpy as np import soundfile
rng = random.Random(plan.seed + 2) chosen: list[Clip] = [] excluded: dict[str, int] = {} for subset in PANEL_SUBSETS: everything = sorted( (c for c in clips if _panel_subset(c) == subset), key=lambda c: c.clip_id ) pool = [c for c in everything if _usable_reconstruction(workspace, c, vae_results)] if len(pool) < len(everything): excluded[subset] = len(everything) - len(pool) log.warning( "B2 panel: %d %s clips lack a usable reconstruction", excluded[subset], subset ) chosen.extend(rng.sample(pool, min(plan.n_panel_per_subset, len(pool)))) rng.shuffle(chosen) panel_id = f"b2-{plan.seed}" audio_dir = workspace.cache / "panel_audio" / panel_id items: list[PanelItem] = [] key: dict[str, dict[str, object]] = {} for clip in chosen: orig, orig_rate = soundfile.read(str(_orig_path(workspace, clip)), dtype="float64") recon, recon_rate = soundfile.read(str(_vae_path(workspace, clip)), dtype="float64") peak = max(float(np.max(np.abs(orig))), float(np.max(np.abs(recon))), 1e-12) gain = 1.0 / peak if peak > 1.0 else 1.0 first_is_orig = rng.random() < 0.5 members = [("orig", orig, orig_rate), ("vae", recon, recon_rate)] if not first_is_orig: members.reverse() refs: list[AudioRef] = [] for label, (_kind, audio, rate_hz) in zip(("A", "B"), members, strict=True): # Always rewritten: a cached A/B file could disagree with a re-drawn key. dest = audio_dir / f"{clip.clip_id}__{label}.flac" dest.parent.mkdir(parents=True, exist_ok=True) soundfile.write(str(dest), audio * gain, int(rate_hz), subtype="PCM_16") refs.append(AudioRef(label, dest)) key[clip.clip_id] = { "subset": _panel_subset(clip), "a_is": "orig" if first_is_orig else "vae", "gain": gain, } items.append( PanelItem( item_id=clip.clip_id, audios=tuple(refs), text=clip.reference or "", info=f"{clip.layer} · {clip.duration_ms / 1000:.1f} s", ) ) spec = PanelSpec( panel_id=panel_id, title="B2 — Ses kodlayıcı dinleme testi", instructions=( "Her satırda A ve B'yi dinleyin. Biri orijinal kayıt, diğeri modelden geçirilmiş " "hâli; hangisinin hangisi olduğu rastgele ve gizli. İkisinin aynı ifadeyi " "(fısıltı, gülme, bağırma, iç çekme vb.) taşıyıp taşımadığını ve her birinin " "kalitesini işaretleyin. Kulaklıkla dinlemeniz önerilir." ), questions=B2_QUESTIONS, items=tuple(items), ) atomic_write_json( _key_path(workspace, plan), { "panel_id": panel_id, "items": key, "excluded_missing_reconstruction": excluded, "min_per_subset": plan.n_panel_per_subset, }, ) return write_panel(spec, workspace.panels / panel_id)
def score_b2_panel( results: Sequence[PanelResult], key: Mapping[str, Mapping[str, object]], *, min_per_subset: int,) -> dict[str, object]: """Un-blind the panel answers and apply the pre-registered acceptance rule.
Returns per subset: answered items, share of "evet" (preserved), share of "kısmen", mean quality of original and reconstruction, the mean gap (orig − vae) and whether the subset passes (``preserved_share >= 0.8`` and ``quality_gap <= 1``; the ``tr`` subset is reported but carries no expressive-preservation requirement). ``all_pass`` requires all four expressive subsets to be present, *every* key item of every subset to be fully answered, at least ``min_per_subset`` items per expressive subset (pre-registered: the panel size per subset, 8), and every subset to pass — thin or partial evidence never passes.
Raises: ValueError: if an answered item is missing from the key. """ rows: dict[str, dict[str, list[float]]] = {} for result in results: if result.item_id not in key: raise ValueError(f"panel item {result.item_id} not in the answer key") entry = key[result.item_id] same = result.answers.get("ayni_ifade", "") qa, qb = result.answers.get("kalite_a", ""), result.answers.get("kalite_b", "") if not same or not qa or not qb: continue # unanswered rows do not count either way orig_q, vae_q = ( (float(qa), float(qb)) if entry["a_is"] == "orig" else (float(qb), float(qa)) ) bucket = rows.setdefault(str(entry["subset"]), {}) bucket.setdefault("preserved", []).append(1.0 if same == "evet" else 0.0) bucket.setdefault("partial", []).append(1.0 if same == "kısmen" else 0.0) bucket.setdefault("orig_q", []).append(orig_q) bucket.setdefault("vae_q", []).append(vae_q) out: dict[str, dict[str, object]] = {} for subset, bucket in sorted(rows.items()): preserved = _mean(bucket["preserved"]) or 0.0 orig_q = _mean(bucket["orig_q"]) or 0.0 vae_q = _mean(bucket["vae_q"]) or 0.0 gap = orig_q - vae_q passes = gap <= MAX_QUALITY_GAP and (subset == "tr" or preserved >= MIN_PRESERVED_SHARE) out[subset] = { "n_answered": len(bucket["preserved"]), "preserved_share": preserved, "partial_share": _mean(bucket["partial"]), "quality_orig": orig_q, "quality_vae": vae_q, "quality_gap": gap, "passes": passes, } in_key: dict[str, int] = {} for entry in key.values(): in_key[str(entry["subset"])] = in_key.get(str(entry["subset"]), 0) + 1 unanswered = { subset: count - int(str(out.get(subset, {}).get("n_answered", 0))) for subset, count in sorted(in_key.items()) if count > int(str(out.get(subset, {}).get("n_answered", 0))) } expressive = [s for s in PANEL_SUBSETS if s != "tr"] missing_subsets = [s for s in expressive if s not in out] too_few = {s: in_key.get(s, 0) for s in expressive if in_key.get(s, 0) < min_per_subset} return { "subsets": out, "rule": {"min_preserved_share": MIN_PRESERVED_SHARE, "max_quality_gap": MAX_QUALITY_GAP}, "unanswered": unanswered, "missing_subsets": missing_subsets, "too_few_items": too_few, "min_per_subset": min_per_subset, "all_pass": not missing_subsets and not unanswered and not too_few and all(bool(v["passes"]) for v in out.values()), }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510"""Clip records and deterministic clip selection for benchmarks B1 / B2.
Selection functions are pure: they take already-parsed source metadata and a seed, andreturn the chosen clips plus a quarantine list with a machine-readable reason for everycandidate that was rejected (docs/03-data-pipeline.md: nothing is dropped silently).Candidates that are merely *not sampled* are not quarantined; only rule violations are.
Ids follow the pipeline convention ``sha1(source_id, file_id, start_ms, end_ms)[:16]``."""
from __future__ import annotations
import hashlibimport randomfrom collections import defaultdictfrom collections.abc import Iterable, Mapping, Sequencefrom dataclasses import dataclass, fieldfrom typing import Literal
from nida.bench.textmetrics import FILLERS, has_digits, normalize_for_scoringfrom nida.text.turkish import nfc
__all__ = [ "Clip", "FleursRow", "MediaSpeechItem", "Quarantined", "Selection", "YodasUtt", "clip_from_obj", "clip_to_obj", "make_clip_id", "parse_yodas_utt_id", "select_fleurs", "select_mediaspeech", "select_yodas_final", "select_yodas_pool", "text_has_filler", "yodas_video_id",]
Language = Literal["tr", "en"]
#: Gender labels in the FLEURS TSV; anything else is quarantined, never guessed.FLEURS_GENDERS = frozenset({"MALE", "FEMALE"})#: Allowed mismatch between a YODAS duration and the span encoded in its utterance id.YODAS_DURATION_TOLERANCE_MS = 50
def make_clip_id(source_id: str, file_id: str, start_ms: int, end_ms: int) -> str: """Content-addressed clip id (first 16 hex chars of SHA-1).""" if start_ms < 0 or end_ms <= start_ms: raise ValueError(f"invalid span {start_ms}..{end_ms} ms for {source_id}/{file_id}") key = "\x1f".join((source_id, file_id, str(start_ms), str(end_ms))) return hashlib.sha1(key.encode("utf-8")).hexdigest()[:16]
@dataclass(frozen=True)class Clip: """One benchmark clip.
Attributes: clip_id: ``make_clip_id(source_id, file_id, start_ms, end_ms)``. source_id: Id in ``configs/sources.yaml``. layer: Benchmark layer / subset name (e.g. ``"A"``, ``"whisper"``). file_id: File or utterance id inside the source. start_ms: Start inside the source file, milliseconds. end_ms: End inside the source file, milliseconds (exclusive). reference: Reference transcript (raw), or ``None`` when not yet available. language: ISO 639-1 code. meta: Free string metadata (gender, video id, style, ...). """
clip_id: str source_id: str layer: str file_id: str start_ms: int end_ms: int reference: str | None language: Language meta: Mapping[str, str] = field(default_factory=dict)
@property def duration_ms(self) -> int: return self.end_ms - self.start_ms
@staticmethod def build( *, source_id: str, layer: str, file_id: str, start_ms: int, end_ms: int, reference: str | None, language: Language, meta: Mapping[str, str] | None = None, ) -> Clip: return Clip( clip_id=make_clip_id(source_id, file_id, start_ms, end_ms), source_id=source_id, layer=layer, file_id=file_id, start_ms=start_ms, end_ms=end_ms, reference=None if reference is None else nfc(reference), language=language, meta=dict(meta or {}), )
@dataclass(frozen=True)class Quarantined: """A rejected candidate (docs/03-data-pipeline.md quarantine record)."""
item_id: str stage: str reason: str details: str = ""
@dataclass(frozen=True)class Selection: clips: tuple[Clip, ...] quarantined: tuple[Quarantined, ...]
def _check_count(n: int) -> None: if n < 1: raise ValueError(f"requested clip count must be >= 1, got {n}")
def _check_duration_window(min_s: float, max_s: float) -> None: if not 0 < min_s < max_s: raise ValueError(f"invalid duration window {min_s}..{max_s} s")
# ------------------------------------------------------------------------------- FLEURS
@dataclass(frozen=True)class FleursRow: """One row of FLEURS ``<split>.tsv`` (16 kHz audio)."""
sentence_id: str file_name: str raw_transcription: str num_samples: int gender: str
def select_fleurs( rows: Iterable[FleursRow], n: int, seed: int, *, min_s: float = 2.0, max_s: float = 25.0, source_id: str = "fleurs_tr", layer: str = "A",) -> Selection: """Pick ``n`` FLEURS recordings: one per sentence id, gender-balanced.
Rules: duration in ``[min_s, max_s]``; reference non-empty and without digits (number verbalisation is not decided yet, R6); at most one recording per sentence id (several speakers read the same sentence and the TSV has no speaker id). Gender balance: half from ``MALE`` and half from ``FEMALE`` where possible, the remainder from whatever is left.
Raises: ValueError: on invalid arguments or if fewer than ``n`` eligible sentences exist. """ _check_count(n) _check_duration_window(min_s, max_s) quarantined: list[Quarantined] = [] by_sentence: dict[str, list[FleursRow]] = defaultdict(list) for row in rows: duration_s = row.num_samples / 16000 if row.gender not in FLEURS_GENDERS: quarantined.append( Quarantined(row.file_name, "select", "unexpected_gender", row.gender) ) elif not min_s <= duration_s <= max_s: quarantined.append( Quarantined(row.file_name, "select", "duration_out_of_range", f"{duration_s:.2f}s") ) elif not normalize_for_scoring(row.raw_transcription): quarantined.append(Quarantined(row.file_name, "select", "empty_reference")) elif has_digits(row.raw_transcription): quarantined.append(Quarantined(row.file_name, "select", "reference_has_digits")) else: by_sentence[row.sentence_id].append(row) rng = random.Random(seed) one_per_sentence: list[FleursRow] = [] for sentence_id in sorted(by_sentence): recordings = sorted(by_sentence[sentence_id], key=lambda r: r.file_name) one_per_sentence.append(rng.choice(recordings)) if len(one_per_sentence) < n: raise ValueError(f"only {len(one_per_sentence)} eligible FLEURS sentences, need {n}") pools: dict[str, list[FleursRow]] = defaultdict(list) for row in one_per_sentence: pools[row.gender].append(row) for pool in pools.values(): rng.shuffle(pool) chosen: list[FleursRow] = [] half = n // 2 for gender in ("MALE", "FEMALE"): chosen.extend(pools[gender][:half]) del pools[gender][:half] rest = [row for gender in sorted(pools) for row in pools[gender]] rng.shuffle(rest) chosen.extend(rest[: n - len(chosen)]) clips = tuple( Clip.build( source_id=source_id, layer=layer, file_id=row.file_name, start_ms=0, end_ms=round(row.num_samples / 16), reference=row.raw_transcription, language="tr", meta={"gender": row.gender, "sentence_id": row.sentence_id}, ) for row in sorted(chosen, key=lambda r: r.file_name) ) return Selection(clips, tuple(quarantined))
# --------------------------------------------------------------------------- MediaSpeech
@dataclass(frozen=True)class MediaSpeechItem: file_id: str # uuid stem of TR/<uuid>.flac text: str duration_ms: int
def select_mediaspeech( items: Iterable[MediaSpeechItem], n: int, seed: int, *, min_s: float = 2.0, max_s: float = 20.0, source_id: str = "mediaspeech_tr", layer: str = "B",) -> Selection: """Pick ``n`` MediaSpeech segments with the same reference rules as FLEURS.""" _check_count(n) _check_duration_window(min_s, max_s) quarantined: list[Quarantined] = [] eligible: list[MediaSpeechItem] = [] for item in sorted(items, key=lambda i: i.file_id): duration_s = item.duration_ms / 1000 if not min_s <= duration_s <= max_s: quarantined.append( Quarantined(item.file_id, "select", "duration_out_of_range", f"{duration_s:.2f}s") ) elif not normalize_for_scoring(item.text): quarantined.append(Quarantined(item.file_id, "select", "empty_reference")) elif has_digits(item.text): quarantined.append(Quarantined(item.file_id, "select", "reference_has_digits")) else: eligible.append(item) if len(eligible) < n: raise ValueError(f"only {len(eligible)} eligible MediaSpeech items, need {n}") chosen = random.Random(seed).sample(eligible, n) clips = tuple( Clip.build( source_id=source_id, layer=layer, file_id=item.file_id, start_ms=0, end_ms=item.duration_ms, reference=item.text, language="tr", ) for item in sorted(chosen, key=lambda i: i.file_id) ) return Selection(clips, tuple(quarantined))
# --------------------------------------------------------------------------------- YODAS
@dataclass(frozen=True)class YodasUtt: utt_id: str caption: str duration_ms: int shard: str = "" # archive shard holding the audio ("" = unknown / single shard)
def yodas_video_id(utt_id: str) -> str: """Video id of a ``<video>-<seg>-<start_cs>-<end_cs>`` utterance id.
Only the shape is checked, not the span: a listing line with an empty span still names its video (de-duplication must see it; ingest quarantines the utterance).
Raises: ValueError: if the id does not have the expected shape. """ parts = utt_id.rsplit("-", 3) if len(parts) != 4 or not all(p.isdigit() for p in parts[1:]) or not parts[0]: raise ValueError(f"unexpected YODAS utterance id {utt_id!r}") return parts[0]
def parse_yodas_utt_id(utt_id: str) -> tuple[str, int, int]: """Split ``<video>-<seg>-<start_cs>-<end_cs>`` into (video_id, start_ms, end_ms).
YouTube ids may contain ``-``, so the id is split from the right. Times are in centiseconds in the id.
Raises: ValueError: if the id does not have the expected shape. """ video_id = yodas_video_id(utt_id) parts = utt_id.rsplit("-", 3) start_ms, end_ms = int(parts[2]) * 10, int(parts[3]) * 10 if end_ms <= start_ms: raise ValueError(f"empty span in YODAS utterance id {utt_id!r}") return video_id, start_ms, end_ms
def select_yodas_pool( utts: Iterable[YodasUtt], n: int, seed: int, *, min_s: float = 3.0, max_s: float = 15.0, max_per_video: int = 3, source_id: str = "yodas_tr", layer: str = "C",) -> Selection: """Pick a candidate pool for layer C (to be transcribed by every ASR first).
Rules: duration in range; caption non-empty and digit-free (captions become the draft the user corrects, so they must not contain digits either); at most ``max_per_video`` clips per video (the video id stands in for the speaker). ``reference`` is ``None``: captions are not references; the caption is stored in ``meta["caption"]``. """ _check_count(n) _check_duration_window(min_s, max_s) if max_per_video < 1: raise ValueError(f"max_per_video must be >= 1, got {max_per_video}") quarantined: list[Quarantined] = [] by_video: dict[str, list[tuple[YodasUtt, int, int]]] = defaultdict(list) for utt in sorted(utts, key=lambda u: u.utt_id): try: video_id, start_ms, end_ms = parse_yodas_utt_id(utt.utt_id) except ValueError as err: quarantined.append(Quarantined(utt.utt_id, "select", "bad_utt_id", str(err))) continue duration_s = utt.duration_ms / 1000 span_ms = end_ms - start_ms if abs(utt.duration_ms - span_ms) > YODAS_DURATION_TOLERANCE_MS: quarantined.append( Quarantined( utt.utt_id, "select", "duration_mismatch", f"{utt.duration_ms} vs {span_ms} ms" ) ) elif not min_s <= duration_s <= max_s: quarantined.append( Quarantined(utt.utt_id, "select", "duration_out_of_range", f"{duration_s:.2f}s") ) elif not normalize_for_scoring(utt.caption): quarantined.append(Quarantined(utt.utt_id, "select", "empty_caption")) elif has_digits(utt.caption): quarantined.append(Quarantined(utt.utt_id, "select", "caption_has_digits")) else: by_video[video_id].append((utt, start_ms, end_ms)) rng = random.Random(seed) eligible: list[tuple[str, YodasUtt]] = [] for video_id in sorted(by_video): candidates = by_video[video_id] picked = rng.sample(candidates, min(max_per_video, len(candidates))) eligible.extend((video_id, utt) for utt, _, _ in picked) if len(eligible) < n: raise ValueError(f"only {len(eligible)} eligible YODAS utterances, need {n}") chosen = rng.sample(eligible, n) clips = tuple( Clip.build( source_id=source_id, layer=layer, file_id=utt.utt_id, start_ms=0, end_ms=utt.duration_ms, reference=None, language="tr", meta={"video_id": video_id, "caption": nfc(utt.caption)} | ({"shard": utt.shard} if utt.shard else {}), ) for video_id, utt in sorted(chosen, key=lambda pair: pair[1].utt_id) ) return Selection(clips, tuple(quarantined))
def text_has_filler(text: str) -> bool: """True if ``text`` contains a canonical filler (tag-spec section 4).
The single definition of the layer-C "filler signal": used both to select clips and to record why they were selected (``nida.bench.b1.FillerProvenance``). """ return any(token in FILLERS for token in normalize_for_scoring(text))
def select_yodas_final( pool: Sequence[Clip], hypotheses: Mapping[str, Sequence[str]], n: int, seed: int, *, min_filler_clips: int,) -> tuple[Clip, ...]: """Choose the ``n`` layer-C clips the user will transcribe, favouring fillers.
A clip has a *filler signal* if its caption or any model hypothesis contains a canonical filler (tag-spec section 4). Filler-signal clips are taken first (seeded order) up to ``n``; the rest is filled with other pool clips. Hypotheses only steer *which* clips are reviewed, never the reference text itself.
Args: pool: Layer-C pool from :func:`select_yodas_pool`. hypotheses: ``clip_id`` → raw hypothesis texts from every ASR. n: Number of clips to return. seed: RNG seed. min_filler_clips: Required number of filler-signal clips (ValueError if the pool has fewer, so a filler-poor pool is reported instead of silently accepted). """ _check_count(n) if not 0 <= min_filler_clips <= n: raise ValueError(f"min_filler_clips must be in [0, {n}], got {min_filler_clips}") if len(pool) < n: raise ValueError(f"pool has {len(pool)} clips, need {n}")
def has_filler_signal(clip: Clip) -> bool: texts = [clip.meta.get("caption", ""), *hypotheses.get(clip.clip_id, ())] return any(text_has_filler(text) for text in texts)
ordered = sorted(pool, key=lambda c: c.clip_id) with_filler = [c for c in ordered if has_filler_signal(c)] without = [c for c in ordered if not has_filler_signal(c)] if len(with_filler) < min_filler_clips: raise ValueError( f"only {len(with_filler)} pool clips show a filler, need {min_filler_clips}" ) rng = random.Random(seed) rng.shuffle(with_filler) rng.shuffle(without) chosen = (with_filler + without)[:n] return tuple(sorted(chosen, key=lambda c: c.clip_id))
# ------------------------------------------------------------------------- serialisation
def clip_to_obj(clip: Clip) -> dict[str, object]: """JSON-compatible representation of a clip.""" return { "clip_id": clip.clip_id, "source_id": clip.source_id, "layer": clip.layer, "file_id": clip.file_id, "start_ms": clip.start_ms, "end_ms": clip.end_ms, "reference": clip.reference, "language": clip.language, "meta": dict(clip.meta), }
def clip_from_obj(obj: object) -> Clip: """Inverse of :func:`clip_to_obj`; re-derives and checks the content-addressed id.
Raises: ValueError: on missing/mistyped fields or an id that does not match the content. """ if not isinstance(obj, dict): raise ValueError("clip must be a JSON object") try: language = obj["language"] if language not in ("tr", "en"): raise ValueError(f"unsupported language {language!r}") meta = obj.get("meta", {}) if not isinstance(meta, dict) or not all( isinstance(k, str) and isinstance(v, str) for k, v in meta.items() ): raise ValueError("meta must map strings to strings") reference = obj["reference"] if reference is not None and not isinstance(reference, str): raise ValueError("reference must be a string or null") clip = Clip.build( source_id=str(obj["source_id"]), layer=str(obj["layer"]), file_id=str(obj["file_id"]), start_ms=int(obj["start_ms"]), end_ms=int(obj["end_ms"]), reference=reference, language=language, meta=meta, ) except KeyError as err: raise ValueError(f"clip is missing field {err}") from err if clip.clip_id != obj.get("clip_id"): raise ValueError(f"clip_id {obj.get('clip_id')!r} does not match content ({clip.clip_id})") return clip123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351"""Isolated ``uv`` virtual environments for the benchmark workers.
The benchmark workers have conflicting dependency pins (``omnilingual-asr`` needsPython <= 3.12 and ``fairseq2n`` pins ``torch==2.8.0``; ``qwen-asr`` pins``transformers==4.57.6``), so each worker family runs in its own environment built by``uv``. This module only *builds and describes* those environments; it never imports theheavy packages itself and uses the standard library only.
All subprocess calls go through an injectable :data:`CommandRunner` so tests neverexecute ``uv``. An environment is described by an :class:`EnvSpec`; a marker file(``.nida-env.json``) is written last so a half-built environment is always rebuilt."""
from __future__ import annotations
import hashlibimport jsonimport loggingimport reimport shutilimport subprocessimport sysfrom collections.abc import Callable, Mapping, Sequencefrom dataclasses import asdict, dataclassfrom datetime import UTC, datetimefrom pathlib import Pathfrom types import MappingProxyType
from nida.utils.io import atomic_write_json, atomic_write_text
__all__ = [ "ENV_SPECS", "MARKER_NAME", "CommandRunner", "EnvBuildError", "EnvSpec", "ensure_env", "env_for_worker", "find_uv", "freeze_text", "subprocess_runner",]
_LOG = logging.getLogger(__name__)
MARKER_NAME = ".nida-env.json"FREEZE_NAME = "freeze.txt"UV_VERSION = "0.10.4"_SUBPROCESS_TIMEOUT_S = 3600_STDERR_TAIL_CHARS = 2000_NAME_RE = re.compile(r"^[a-z][a-z0-9_-]*$")
class EnvBuildError(RuntimeError): """Raised when an environment cannot be built or a command fails."""
CommandRunner = Callable[[Sequence[str]], str]"""Runs a command and returns its stdout; raises :class:`EnvBuildError` on failure."""
@dataclass(frozen=True)class EnvSpec: """Description of one worker environment.
Attributes: name: Environment directory name (lowercase ``[a-z][a-z0-9_-]*``). python: Python version passed to ``uv venv --python``. torch_packages: Pinned torch packages installed first from ``torch_index_url``. Empty = the packages bring their own torch (or none): the torch step and the torch version guard of :func:`ensure_env` are skipped. torch_index_url: Package index serving the matching CUDA wheels (unused when ``torch_packages`` is empty). packages: Pinned packages installed from the default index after torch. workers: Worker module names (under ``nida.bench.workers``) run in this env. """
name: str python: str torch_packages: tuple[str, ...] torch_index_url: str packages: tuple[str, ...] workers: tuple[str, ...]
def __post_init__(self) -> None: if not _NAME_RE.fullmatch(self.name): raise ValueError(f"invalid environment name {self.name!r}; expected {_NAME_RE.pattern}")
def spec_hash(self) -> str: """Return the sha256 hex digest of a canonical JSON of all fields.
The digest is stable across runs and processes (sorted keys, fixed separators). """ canonical = json.dumps(asdict(self), sort_keys=True, separators=(",", ":")) return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
_PYTHON = "3.12"_TORCH_PACKAGES = ("torch==2.8.0", "torchaudio==2.8.0")_TORCH_INDEX_URL = "https://download.pytorch.org/whl/cu128"
ENV_SPECS: Mapping[str, EnvSpec] = MappingProxyType( { "hf": EnvSpec( name="hf", python=_PYTHON, torch_packages=_TORCH_PACKAGES, torch_index_url=_TORCH_INDEX_URL, packages=("transformers==4.57.6", "huggingface-hub", "soundfile", "numpy"), workers=("asr_hf",), ), "qwen": EnvSpec( name="qwen", python=_PYTHON, torch_packages=_TORCH_PACKAGES, torch_index_url=_TORCH_INDEX_URL, packages=("qwen-asr==0.0.6", "huggingface-hub"), workers=("asr_qwen",), ), "omni": EnvSpec( name="omni", python=_PYTHON, torch_packages=_TORCH_PACKAGES, torch_index_url=_TORCH_INDEX_URL, # omnilingual-asr needs pyarrow>=20 but keeps NumPy 1.26, and pyarrow 26 needs # NumPy 2 ("pyarrow requires NumPy 2.0 or newer, found 1.26.4", fresh env # 2026-10-09). 21.0.0 resolves and imports with NumPy 1.26 (checked on Colab). packages=("omnilingual-asr==0.2.0", "pyarrow==21.0.0"), workers=("asr_omni",), ), "audio": EnvSpec( name="audio", python=_PYTHON, torch_packages=_TORCH_PACKAGES, torch_index_url=_TORCH_INDEX_URL, packages=( "audiobox-aesthetics==0.0.4", "numpy", "pydantic", "soundfile", "huggingface-hub", # audiobox_aesthetics.utils imports requests without declaring it # (run 20261008-124740-bench-phase0-8c6a failed on the import). "requests", ), workers=("vae_voxcpm", "quality_audiobox"), ), })
def env_for_worker(worker: str) -> EnvSpec: """Return the environment spec that runs ``worker``.
Args: worker: Worker module name, e.g. ``"asr_qwen"``.
Raises: ValueError: if no environment lists ``worker``. """ for spec in ENV_SPECS.values(): if worker in spec.workers: return spec known = sorted(w for spec in ENV_SPECS.values() for w in spec.workers) raise ValueError(f"unknown worker {worker!r}; known workers: {known}")
def subprocess_runner(cmd: Sequence[str]) -> str: """Run ``cmd`` with :func:`subprocess.run` and return its stdout.
Args: cmd: Command and arguments (no shell).
Returns: Captured stdout text.
Raises: EnvBuildError: on a non-zero exit code, a timeout, or if the executable is missing. The message carries the command, the exit code and the stderr tail. """ command = list(cmd) try: result = subprocess.run( command, capture_output=True, text=True, check=False, timeout=_SUBPROCESS_TIMEOUT_S, ) except subprocess.TimeoutExpired as exc: raise EnvBuildError(f"command timed out after {_SUBPROCESS_TIMEOUT_S}s: {command}") from exc except OSError as exc: raise EnvBuildError(f"command could not be started: {command}: {exc}") from exc if result.returncode != 0: tail = result.stderr[-_STDERR_TAIL_CHARS:] raise EnvBuildError( f"command failed with exit code {result.returncode}: {command}\nstderr tail:\n{tail}" ) return result.stdout
def find_uv( runner: CommandRunner = subprocess_runner, which: Callable[[str], str | None] = shutil.which,) -> str: """Locate ``uv``, installing it with pip when it is not on ``PATH``.
Args: runner: Command runner used for the pip install. which: Executable lookup (injectable for tests).
Returns: ``"uv"`` if it is already on ``PATH``, otherwise the path found after installing.
Raises: EnvBuildError: if ``uv`` is still missing after the install. """ if which("uv"): return "uv" runner([sys.executable, "-m", "pip", "install", "-q", f"uv=={UV_VERSION}"]) found = which("uv") if not found: raise EnvBuildError(f"uv=={UV_VERSION} was installed with pip but is still not on PATH") return found
def _python_path(env_dir: Path) -> Path: return env_dir / "bin" / "python"
def _remove_env_dir(env_dir: Path, envs_root: Path) -> None: """Delete ``env_dir`` if it exists, refusing anything not strictly inside ``envs_root``.
Raises: EnvBuildError: if ``env_dir`` resolves outside (or equal to) ``envs_root``. """ root = envs_root.resolve() target = env_dir.resolve() if target == root or not target.is_relative_to(root): raise EnvBuildError(f"refusing to delete {env_dir}: not strictly inside {envs_root}") if env_dir.is_symlink(): env_dir.unlink() elif env_dir.exists(): shutil.rmtree(env_dir)
def _is_current(spec: EnvSpec, env_dir: Path) -> bool: """Return True if a complete, up-to-date environment exists at ``env_dir``.""" marker = env_dir / MARKER_NAME if not marker.is_file() or not _python_path(env_dir).exists(): return False try: data = json.loads(marker.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: _LOG.warning("unreadable env marker %s (%s); rebuilding", marker, exc) return False return isinstance(data, dict) and data.get("spec_hash") == spec.spec_hash()
def _expected_torch_version(spec: EnvSpec) -> str: for pkg in spec.torch_packages: if pkg.startswith("torch=="): return pkg.removeprefix("torch==") raise EnvBuildError(f"env {spec.name!r} pins no 'torch==X' in torch_packages")
def ensure_env( spec: EnvSpec, envs_root: Path, repo_dir: Path, runner: CommandRunner = subprocess_runner, uv: str = "uv",) -> Path: """Build the environment for ``spec`` unless an up-to-date one already exists.
The marker ``<envs_root>/<name>/.nida-env.json`` is written last, so any failure leaves no marker and the next call rebuilds from scratch.
Args: spec: Environment description. envs_root: Directory holding all environments. repo_dir: Repository root, installed with ``--no-deps -e`` (nida has no runtime deps). runner: Command runner (injectable). uv: ``uv`` executable.
Returns: Path of the environment's python executable.
Raises: EnvBuildError: if a command fails, the torch version guard trips, or the delete guard refuses the environment directory. """ env_dir = envs_root / spec.name py = _python_path(env_dir) if _is_current(spec, env_dir): _LOG.info("env %s is up to date at %s", spec.name, env_dir) return py
envs_root.mkdir(parents=True, exist_ok=True) _remove_env_dir(env_dir, envs_root)
runner([uv, "venv", "--python", spec.python, str(env_dir)]) if spec.torch_packages: runner( [ uv, "pip", "install", "--python", str(py), "--index-url", spec.torch_index_url, *spec.torch_packages, ] ) runner([uv, "pip", "install", "--python", str(py), *spec.packages]) runner([uv, "pip", "install", "--python", str(py), "--no-deps", "-e", str(repo_dir)])
if spec.torch_packages: expected = _expected_torch_version(spec) torch_version = runner( [str(py), "-c", "import torch, sys; print(torch.__version__)"] ).strip() if not torch_version.startswith(expected): raise EnvBuildError( f"env {spec.name!r}: torch version is {torch_version!r}, expected {expected!r} " "(a later install step probably replaced torch)" )
frozen = runner([uv, "pip", "freeze", "--python", str(py)]) atomic_write_text(env_dir / FREEZE_NAME, frozen)
atomic_write_json( env_dir / MARKER_NAME, { "name": spec.name, "spec_hash": spec.spec_hash(), "spec": asdict(spec), "created_at": datetime.now(UTC).isoformat(), }, ) return py
def freeze_text(spec: EnvSpec, envs_root: Path) -> str: """Return the ``pip freeze`` output recorded when ``spec`` was built.
Raises: FileNotFoundError: if the environment has not been built (no ``freeze.txt``). """ return (envs_root / spec.name / FREEZE_NAME).read_text(encoding="utf-8")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301"""Expresso layout parsing and clip selection for B2 (docs/benchmarks/B1-B2-tasarim.md §2).
Archive layout (textlesslib ``examples/expresso/dataset/README.md``)::
expresso/read_transcriptions.txt expresso/VAD_segments.txt "{stem}/channel{1|2}\t(s, e) (s, e) ..." (mono long-form lines: bare "{stem}", kept as channel 0 and not used by B2) expresso/audio_48khz/read/{spk}/{style}/{base|longform}/{spk}_{style...}_{id}.wav mono expresso/audio_48khz/conversational/{spk1}-{spk2}/{style1[-style2]}/{stem}.wav stereo
In a conversational style folder without a hyphen both channels carry that style; with ahyphen the left style belongs to channel 1 (left speaker) and the right one to channel 2.Subsets used by B2: ``whisper``, ``laughing`` and ``default`` from read speech (they havetranscripts), ``projected`` and ``nonverbal`` from conversational VAD segments of achannel that carries the style. Folder spellings ``non_verbal`` / ``nonverbal`` are bothaccepted."""
from __future__ import annotations
import hashlibimport randomimport refrom collections import defaultdictfrom collections.abc import Iterable, Mapping, Sequencefrom dataclasses import dataclass
from nida.bench.clips import Clip, Quarantined, Selection
__all__ = [ "CONVERSATIONAL_SUBSETS", "READ_SUBSETS", "ExpressoFile", "is_wanted_member", "parse_member", "parse_read_transcriptions", "parse_vad_segments", "select_expresso",]
SOURCE_ID = "expresso"READ_SUBSETS = ("whisper", "laughing", "default")CONVERSATIONAL_SUBSETS = ("projected", "nonverbal")_STYLE_ALIASES = {"non_verbal": "nonverbal"}_AUDIO_ROOT = "audio_48khz/"#: Keep 1 in N default-style read files (default read speech is large; B2 needs ~10).DEFAULT_KEEP_ONE_IN = 8
def _style(name: str) -> str: return _STYLE_ALIASES.get(name, name)
@dataclass(frozen=True)class ExpressoFile: """One audio member of the archive.
Attributes: member: Archive member name (as stored in the tar). kind: ``"read"`` or ``"conversational"``. stem: File name without extension (key of VAD segments and transcripts). speakers: One speaker (read) or (channel1, channel2) speakers. styles: One style (read) or (channel1, channel2) styles. corpus: ``"base"`` or ``"longform"`` for read speech, ``""`` otherwise. """
member: str kind: str stem: str speakers: tuple[str, ...] styles: tuple[str, ...] corpus: str
def parse_member(name: str) -> ExpressoFile | None: """Parse an archive member name; ``None`` for anything that is not a 48 kHz WAV.""" if not name.endswith(".wav") or _AUDIO_ROOT not in name: return None rel = name.split(_AUDIO_ROOT, 1)[1].split("/") stem = rel[-1][: -len(".wav")] if rel[0] == "read" and len(rel) == 5: _, speaker, style, corpus, _ = rel return ExpressoFile(name, "read", stem, (speaker,), (_style(style),), corpus) if rel[0] == "conversational" and len(rel) == 4: _, pair, style_dir, _ = rel speakers = tuple(pair.split("-")) styles = tuple(_style(s) for s in style_dir.split("-")) if len(speakers) != 2 or len(styles) not in (1, 2): return None return ExpressoFile( name, "conversational", stem, speakers, styles if len(styles) == 2 else styles * 2, "" ) return None
def _stable_fraction(text: str) -> float: return int(hashlib.sha1(text.encode("utf-8")).hexdigest()[:8], 16) / 0xFFFFFFFF
def is_wanted_member(name: str) -> bool: """Archive filter for streaming extraction (metadata files + B2 subsets only).""" if name.endswith(("read_transcriptions.txt", "VAD_segments.txt")): return True parsed = parse_member(name) if parsed is None: return False if parsed.kind == "read": if parsed.corpus != "base": return False style = parsed.styles[0] if style == "default": return _stable_fraction(parsed.stem) < 1 / DEFAULT_KEEP_ONE_IN return style in ("whisper", "laughing") return any(style in CONVERSATIONAL_SUBSETS for style in parsed.styles)
_NUMBER = r"\d+(?:\.\d+)?"_SEGMENT_RE = re.compile(rf"\(\s*({_NUMBER})\s*,\s*({_NUMBER})\s*\)")_SEGMENTS_RE = re.compile(rf"\s*(?:\(\s*{_NUMBER}\s*,\s*{_NUMBER}\s*\)\s*)*")
def parse_vad_segments(text: str) -> dict[tuple[str, int], list[tuple[float, float]]]: """Parse ``VAD_segments.txt`` into ``{(stem, channel): [(start_s, end_s), ...]}``.
Conversational keys are ``<stem>/channel1|2``; the official file also lists mono long-form read recordings with a bare ``<stem>`` key, stored here as channel 0.
Raises: ValueError: on a malformed key or a segment with end <= start. """ out: dict[tuple[str, int], list[tuple[float, float]]] = {} for number, line in enumerate(text.splitlines(), start=1): if not line.strip() or line.startswith("#"): continue key, _, segments = line.partition("\t") stem, sep, channel = key.rpartition("/channel") if not sep: stem, channel = key, "0" # mono long-form recording (bare key) elif channel not in ("1", "2"): raise ValueError(f"VAD line {number}: bad key {key!r}") if not stem or "/" in stem or any(ch.isspace() for ch in stem): raise ValueError(f"VAD line {number}: bad key {key!r}") if not _SEGMENTS_RE.fullmatch(segments): raise ValueError(f"VAD line {number}: unparseable segments {segments[:80]!r}") if (stem, int(channel)) in out: raise ValueError(f"VAD line {number}: duplicate key {key!r}") spans: list[tuple[float, float]] = [] for match in _SEGMENT_RE.finditer(segments): start_s, end_s = float(match.group(1)), float(match.group(2)) if end_s <= start_s: raise ValueError(f"VAD line {number}: empty segment ({start_s}, {end_s})") spans.append((start_s, end_s)) out[(stem, int(channel))] = spans return out
def parse_read_transcriptions(text: str) -> dict[str, str]: """Parse ``read_transcriptions.txt`` as ``<stem><TAB or space><text>`` lines.
Raises: ValueError: on duplicate stems. """ out: dict[str, str] = {} for line in text.splitlines(): if not line.strip() or line.startswith("#"): continue sep = "\t" if "\t" in line else " " stem, _, transcript = line.partition(sep) stem = stem.strip() if stem in out: raise ValueError(f"duplicate transcript id {stem}") out[stem] = transcript.strip() return out
def _round_robin_by_speaker( candidates: Sequence[tuple[str, Clip]], n: int, rng: random.Random) -> list[Clip]: by_speaker: dict[str, list[Clip]] = defaultdict(list) for speaker, clip in sorted(candidates, key=lambda pair: pair[1].clip_id): by_speaker[speaker].append(clip) for clips in by_speaker.values(): rng.shuffle(clips) order = sorted(by_speaker) chosen: list[Clip] = [] while len(chosen) < n and any(by_speaker[s] for s in order): for speaker in order: if by_speaker[speaker] and len(chosen) < n: chosen.append(by_speaker[speaker].pop()) return chosen
def select_expresso( files: Iterable[tuple[ExpressoFile, int]], vad: Mapping[tuple[str, int], Sequence[tuple[float, float]]], transcripts: Mapping[str, str], counts: Mapping[str, int], seed: int, *, min_s: float = 3.0, max_s: float = 15.0, long_segment_cut_s: float = 12.0,) -> Selection: """Choose B2 Expresso clips per subset, balanced across speakers.
Args: files: Extracted files with their length in milliseconds. vad: Parsed VAD segments. transcripts: Parsed read transcriptions. counts: Wanted clips per subset name (keys from READ/CONVERSATIONAL_SUBSETS). seed: RNG seed. min_s: Minimum clip duration. max_s: Maximum duration of a read file / VAD segment taken whole. long_segment_cut_s: Longer VAD segments contribute their first this-many seconds.
Raises: ValueError: on unknown subsets or if a subset has fewer candidates than requested. """ unknown = set(counts) - set(READ_SUBSETS) - set(CONVERSATIONAL_SUBSETS) if unknown: raise ValueError(f"unknown Expresso subsets {sorted(unknown)}") if not 0 < min_s < long_segment_cut_s <= max_s: raise ValueError("need 0 < min_s < long_segment_cut_s <= max_s") min_ms, max_ms, cut_ms = (round(v * 1000) for v in (min_s, max_s, long_segment_cut_s)) quarantined: list[Quarantined] = [] candidates: dict[str, list[tuple[str, Clip]]] = defaultdict(list) for item, length_ms in sorted(files, key=lambda pair: pair[0].member): if item.kind == "read": subset = item.styles[0] if subset not in counts: continue if not min_ms <= length_ms <= max_ms: quarantined.append(Quarantined(item.stem, "select", "duration_out_of_range")) continue reference = transcripts.get(item.stem) if not reference: quarantined.append(Quarantined(item.stem, "select", "no_transcript")) continue clip = Clip.build( source_id=SOURCE_ID, layer=subset, file_id=item.member, start_ms=0, end_ms=length_ms, reference=reference, language="en", meta={"speaker": item.speakers[0], "channel": "0"}, ) candidates[subset].append((item.speakers[0], clip)) continue for channel in (1, 2): subset = item.styles[channel - 1] if subset not in counts: continue spans = vad.get((item.stem, channel)) if spans is None: quarantined.append( Quarantined(f"{item.stem}/channel{channel}", "select", "no_vad_segments") ) continue for start_s, end_s in spans: # Integer milliseconds: float seconds would drop exact-length segments # (4.02 - 1.02 < 3.0 in binary floating point). start_ms, end_ms = round(start_s * 1000), round(end_s * 1000) if end_ms - start_ms < min_ms: continue # short VAD islands are expected; not a rule violation if end_ms - start_ms > max_ms: end_ms = start_ms + cut_ms if end_ms > length_ms: if end_ms - length_ms > 1: quarantined.append( Quarantined( item.stem, "select", "vad_beyond_audio", f"{end_ms}>{length_ms}" ) ) continue end_ms = length_ms # ≤ 1 ms of rounding at the very end of the file if end_ms - start_ms < min_ms: continue clip = Clip.build( source_id=SOURCE_ID, layer=subset, file_id=f"{item.member}#ch{channel}", start_ms=start_ms, end_ms=end_ms, reference=None, language="en", meta={"speaker": item.speakers[channel - 1], "channel": str(channel)}, ) candidates[subset].append((item.speakers[channel - 1], clip)) rng = random.Random(seed) chosen: list[Clip] = [] for subset in sorted(counts): wanted = counts[subset] if len(candidates[subset]) < wanted: raise ValueError( f"Expresso subset {subset}: {len(candidates[subset])} candidates, need {wanted}" ) chosen.extend(_round_robin_by_speaker(candidates[subset], wanted, rng)) return Selection(tuple(sorted(chosen, key=lambda c: c.clip_id)), tuple(quarantined))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704"""Reliable, resumable downloads and streaming tar extraction (stdlib only).
Benchmark data lives on public hosts (Hugging Face and others) and ranges from a fewhundred KB to a 36 GB tar. Colab sessions drop connections, so two tools are provided:
* :func:`download` fetches one file to disk. It resumes from a ``<name>.part`` file with an HTTP ``Range`` request, retries transient network failures, verifies size and SHA-256 and only then atomically renames the ``.part`` file to its final name. A completed file is never overwritten and a partial file never looks complete.* :func:`stream_extract` reads a (possibly huge, possibly compressed) tar archive as a stream and writes only the selected regular files to disk, without ever storing the archive itself.
All network access goes through an injectable :data:`Opener`, so tests run offline.:func:`hf_resolve_url` builds revision-pinned Hugging Face download URLs."""
from __future__ import annotations
import hashlibimport http.clientimport loggingimport osimport reimport shutilimport sslimport tarfileimport tempfileimport timeimport urllib.errorimport urllib.parseimport urllib.requestimport zlibfrom collections.abc import Callable, Iteratorfrom contextlib import contextmanagerfrom dataclasses import dataclassfrom pathlib import Pathfrom types import TracebackTypefrom typing import IO, Literal, NoReturn, Protocol, cast
__all__ = [ "Downloaded", "FetchError", "HeadersLike", "Opener", "Response", "default_opener", "download", "hf_resolve_url", "stream_extract",]
logger = logging.getLogger(__name__)
_USER_AGENT = "nida-bench/0"_SHA256_RE = re.compile(r"[0-9a-f]{64}")_COMMIT_SHA_RE = re.compile(r"[0-9a-f]{40}")_CONTENT_RANGE_RE = re.compile(r"bytes (\d+)-(\d+)/(\d+|\*)")_DRIVE_LETTER_RE = re.compile(r"[A-Za-z]:")_MAX_BACKOFF_S = 30.0_COPY_CHUNK_BYTES = 1 << 20# HTTP 4xx codes that are worth retrying; every other 4xx is a permanent client error._RETRYABLE_4XX = frozenset({408, 429})
# Transient network failures. ``HTTPError`` is a ``URLError`` and is classified separately._NETWORK_ERRORS: tuple[type[BaseException], ...] = ( urllib.error.URLError, ConnectionError, TimeoutError, http.client.HTTPException, # includes IncompleteRead ssl.SSLError,)# Everything that can go wrong while reading an archive stream (network or corrupt data)._STREAM_ERRORS: tuple[type[BaseException], ...] = ( *_NETWORK_ERRORS, tarfile.TarError, EOFError, zlib.error,)
class FetchError(RuntimeError): """A download or extraction failed; the message carries URL/path and byte counts."""
class _TransientError(Exception): """Internal: this attempt failed but a resumed attempt may succeed."""
def __init__(self, message: str, *, expected_bytes: int | None = None) -> None: super().__init__(message) self.expected_bytes = expected_bytes
class HeadersLike(Protocol): """Response headers: only ``get`` is used (``http.client.HTTPMessage`` satisfies it)."""
def get(self, name: str, default: str | None = None, /) -> str | None: """Return the header value, or ``default`` when absent.""" ...
class Response(Protocol): """The slice of an HTTP response this module relies on.
``http.client.HTTPResponse`` (what ``urllib.request.urlopen`` returns) satisfies it. """
@property def status(self) -> int: """HTTP status code.""" ...
@property def headers(self) -> HeadersLike: """Response headers.""" ...
def read(self, amt: int = -1, /) -> bytes: """Read up to ``amt`` bytes; ``b""`` means end of stream.""" ...
def __enter__(self) -> Response: """Enter the context.""" ...
def __exit__( self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None, /, ) -> object: """Close the response.""" ...
Opener = Callable[[urllib.request.Request, float], Response]"""Callable performing a request with a timeout in seconds and returning a response."""
def default_opener(request: urllib.request.Request, timeout_s: float) -> Response: """Open ``request`` with :func:`urllib.request.urlopen`.
Args: request: The prepared request. timeout_s: Socket timeout in seconds.
Returns: The open HTTP response (a context manager). """ response: Response = urllib.request.urlopen(request, timeout=timeout_s) return response
@dataclass(frozen=True)class Downloaded: """A completed, verified download.
Attributes: path: Final file path. size_bytes: File size in bytes. sha256: Lowercase hex SHA-256 computed over the final file. url: Source URL. """
path: Path size_bytes: int sha256: str url: str
# --------------------------------------------------------------------------------------# download# --------------------------------------------------------------------------------------
def download( url: str, dest: Path, *, expected_sha256: str | None = None, expected_size: int | None = None, opener: Opener = default_opener, chunk_bytes: int = 1 << 20, timeout_s: float = 60.0, max_attempts: int = 5, sleep: Callable[[float], None] = time.sleep,) -> Downloaded: """Download ``url`` to ``dest``, resuming and retrying as needed.
If ``dest`` already exists it is verified (size and/or SHA-256 when given) and returned without any network access; it is never overwritten. Otherwise the data is written to ``<dest>.part`` and resumed with ``Range: bytes=<n>-`` on every retry. A server that answers 200 instead of 206 to a ranged request makes the download restart from zero. Transient failures (``URLError``, ``ConnectionError``, ``TimeoutError``, short reads, HTTP 5xx/408/429) are retried with backoff of 1, 2, 4, ... seconds (capped at 30). Other HTTP 4xx errors fail immediately. When all attempts are exhausted the ``.part`` file is kept so a later call can resume it.
The SHA-256 is computed over the final file (re-read once at the end), so it also covers bytes written by earlier, interrupted attempts.
Concurrent downloads of the same ``dest`` are not supported.
Args: url: ``http://`` or ``https://`` URL. dest: Final file path; parent directories are created. expected_sha256: Expected lowercase/uppercase hex SHA-256 (64 chars), if known. expected_size: Expected size in bytes, if known. opener: Network access function (injectable for tests). chunk_bytes: Read chunk size in bytes. timeout_s: Socket timeout per request, seconds. max_attempts: Total number of attempts (first try included), at least 1. sleep: Sleep function used for backoff between attempts.
Returns: The verified :class:`Downloaded` record.
Raises: ValueError: On invalid arguments (bad URL scheme, malformed hash, ...). FetchError: On verification failure, permanent HTTP errors or exhausted attempts. OSError: On local filesystem failures (e.g. disk full). """ _require_http_url(url) sha_expected = _normalise_sha256(expected_sha256) if expected_size is not None and expected_size < 0: raise ValueError(f"expected_size must be >= 0, got {expected_size}") if chunk_bytes < 1: raise ValueError(f"chunk_bytes must be >= 1, got {chunk_bytes}") if max_attempts < 1: raise ValueError(f"max_attempts must be >= 1, got {max_attempts}") if timeout_s <= 0: raise ValueError(f"timeout_s must be > 0, got {timeout_s}")
if dest.exists(): return _verify_existing(url, dest, sha_expected, expected_size)
dest.parent.mkdir(parents=True, exist_ok=True) part = dest.with_name(dest.name + ".part")
last_error: _TransientError | None = None known_total = expected_size # best knowledge of the final size, for error messages for attempt in range(1, max_attempts + 1): try: _attempt(url, part, expected_size, opener, chunk_bytes, timeout_s) except _TransientError as exc: last_error = exc if exc.expected_bytes is not None: known_total = exc.expected_bytes part_bytes = part.stat().st_size if part.exists() else 0 logger.warning( "download %s attempt %d/%d failed after %d bytes: %s", url, attempt, max_attempts, part_bytes, exc, ) if attempt < max_attempts: sleep(min(2.0 ** (attempt - 1), _MAX_BACKOFF_S)) continue last_error = None break
if last_error is not None: part_bytes = part.stat().st_size if part.exists() else 0 raise FetchError( f"download of {url} failed after {max_attempts} attempts: {part_bytes} bytes " f"received in {part} (expected " f"{known_total if known_total is not None else 'unknown'}); last error: {last_error}" ) from last_error
size_bytes = part.stat().st_size digest = _sha256_file(part) if sha_expected is not None and digest != sha_expected: part.unlink() raise FetchError( f"sha256 mismatch for {url}: got {digest}, expected {sha_expected} " f"({size_bytes} bytes; partial file deleted)" ) part.replace(dest) logger.info("downloaded %s -> %s (%d bytes, sha256 %s)", url, dest, size_bytes, digest) return Downloaded(path=dest, size_bytes=size_bytes, sha256=digest, url=url)
def _require_http_url(url: str) -> None: if not url.lower().startswith(("http://", "https://")): raise ValueError(f"only http(s) URLs are supported, got {url!r}")
def _normalise_sha256(value: str | None) -> str | None: if value is None: return None lowered = value.strip().lower() if _SHA256_RE.fullmatch(lowered) is None: raise ValueError(f"expected_sha256 must be 64 hex characters, got {value!r}") return lowered
def _sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: while chunk := handle.read(_COPY_CHUNK_BYTES): digest.update(chunk) return digest.hexdigest()
def _verify_existing( url: str, dest: Path, expected_sha256: str | None, expected_size: int | None) -> Downloaded: if not dest.is_file(): raise FetchError(f"destination {dest} exists but is not a regular file (url {url})") size_bytes = dest.stat().st_size if expected_size is not None and size_bytes != expected_size: raise FetchError( f"existing file {dest} has {size_bytes} bytes, expected {expected_size} " f"(url {url}); refusing to overwrite, delete it manually to re-download" ) digest = _sha256_file(dest) if expected_sha256 is not None and digest != expected_sha256: raise FetchError( f"existing file {dest} has sha256 {digest}, expected {expected_sha256} " f"(url {url}); refusing to overwrite, delete it manually to re-download" ) logger.info("download skipped, %s already present (%d bytes)", dest, size_bytes) return Downloaded(path=dest, size_bytes=size_bytes, sha256=digest, url=url)
def _attempt( url: str, part: Path, expected_size: int | None, opener: Opener, chunk_bytes: int, timeout_s: float,) -> None: """Run one (possibly resumed) transfer into ``part``.
Returns normally when ``part`` holds the complete body. Raises ``_TransientError`` when a resumed attempt may help and ``FetchError`` for permanent problems. """ offset = part.stat().st_size if part.exists() else 0 if expected_size is not None: if offset > expected_size: logger.warning("%s is larger than expected size %d, restarting", part, expected_size) part.unlink() offset = 0 elif offset == expected_size: return # everything is already on disk; only verification is left
headers = {"User-Agent": _USER_AGENT} if offset > 0: headers["Range"] = f"bytes={offset}-" request = urllib.request.Request(url, headers=headers)
try: response = opener(request, timeout_s) except urllib.error.HTTPError as exc: code = exc.code exc.close() _raise_for_http_status(url, part, code, offset) except _NETWORK_ERRORS as exc: raise _TransientError(f"connecting to {url} failed: {exc!r}") from exc
with response: status = response.status if status not in (200, 206): raise FetchError(f"unexpected HTTP status {status} from {url}") if status == 200 and offset > 0: logger.warning("server ignored Range for %s, restarting from byte 0", url) offset = 0 total = _expected_total(url, response, status, offset) if total is not None and expected_size is not None and total != expected_size: part.unlink(missing_ok=True) raise FetchError( f"{url} is {total} bytes according to the server, expected {expected_size}" )
position = offset mode = "ab" if (status == 206 and offset > 0) else "wb" with part.open(mode) as handle: try: while chunk := response.read(chunk_bytes): handle.write(chunk) position += len(chunk) if total is not None and position > total: break except _NETWORK_ERRORS as exc: raise _TransientError( f"reading {url} failed at byte {position}: {exc!r}", expected_bytes=total, ) from exc handle.flush() os.fsync(handle.fileno())
if total is not None and position != total: if position > total: part.unlink() raise _TransientError( f"{url} sent more than its Content-Length: {position} bytes, expected {total}", expected_bytes=total, ) raise _TransientError( f"incomplete body from {url}: {position} bytes, expected {total}", expected_bytes=total, ) if expected_size is not None and position != expected_size: if position > expected_size: part.unlink() raise FetchError( f"{url} delivered {position} bytes, expected {expected_size} (partial file deleted)" ) raise _TransientError( f"stream from {url} ended early: {position} bytes, expected {expected_size}", expected_bytes=expected_size, )
def _raise_for_http_status(url: str, part: Path, code: int, offset: int) -> NoReturn: if code == 416 and offset > 0: # The stale .part is at or beyond the end of the remote file: start over. part.unlink(missing_ok=True) raise _TransientError(f"HTTP 416 for ranged request at byte {offset}; restarting") if 400 <= code < 500 and code not in _RETRYABLE_4XX: raise FetchError(f"HTTP {code} for {url}") raise _TransientError(f"HTTP {code} for {url}")
def _parse_length(url: str, name: str, value: str) -> int: try: parsed = int(value) except ValueError: raise FetchError(f"malformed {name} header from {url}: {value!r}") from None if parsed < 0: raise FetchError(f"malformed {name} header from {url}: {value!r}") return parsed
def _expected_total(url: str, response: Response, status: int, offset: int) -> int | None: """Return the total file size implied by the response headers, if the server says.""" length_header = response.headers.get("Content-Length") length = _parse_length(url, "Content-Length", length_header) if length_header else None if status == 200: return length range_header = response.headers.get("Content-Range") if range_header is None: raise FetchError(f"206 response from {url} has no Content-Range header") match = _CONTENT_RANGE_RE.fullmatch(range_header.strip()) if match is None: raise FetchError(f"malformed Content-Range from {url}: {range_header!r}") start = int(match.group(1)) if start != offset: raise FetchError( f"server returned bytes starting at {start} from {url}, requested {offset}" ) if match.group(3) != "*": return int(match.group(3)) return offset + length if length is not None else None
# --------------------------------------------------------------------------------------# stream_extract# --------------------------------------------------------------------------------------
def stream_extract( url_or_path: str | Path, dest_dir: Path, select: Callable[[str], bool], *, opener: Opener = default_opener, timeout_s: float = 60.0,) -> list[Path]: """Extract selected regular files from a tar archive while streaming it.
The archive (plain, gzip, bz2 or xz; auto-detected) is read sequentially from a URL or a local path and is never stored. A stream cannot be resumed mid-archive: if reading fails the call raises :class:`FetchError` and must simply be run again. Files extracted before the failure are kept and skipped quickly on the rerun (the archive is read again from the start, so the whole transfer is repeated).
For every regular-file member the name is normalised (leading ``./`` and empty or ``.`` components removed) and validated. Unsafe names (empty, absolute, containing ``..`` components, backslashes, NUL bytes or a Windows drive prefix) raise :class:`FetchError` even when ``select`` would reject them: an archive with such members is treated as hostile. Selected members are written to ``dest_dir / name`` through a temporary file in the same directory and an atomic rename. A target that already exists with the member's size is left untouched. Non-regular members (directories, symlinks, hard links, devices) are never written; those that ``select`` accepts are counted in the log message. If a name occurs twice in the archive the last occurrence wins, as with ``tar``.
Args: url_or_path: ``http(s)://`` URL (fetched with ``opener``) or a local file path. dest_dir: Output directory; created if missing. select: Predicate on the normalised member name (``/``-separated, relative). opener: Network access function (injectable for tests); unused for local paths. timeout_s: Socket timeout per request, seconds.
Returns: Paths of the extracted or already present files, in archive order, without duplicates.
Raises: FetchError: On unsafe member names, unreadable/corrupt/truncated archives and network failures. OSError: On local filesystem failures (e.g. disk full). """ if timeout_s <= 0: raise ValueError(f"timeout_s must be > 0, got {timeout_s}") dest_dir.mkdir(parents=True, exist_ok=True) root = dest_dir.resolve() label = str(url_or_path)
result: dict[str, Path] = {} # normalised name -> path; insertion order == archive order written_this_run: set[str] = set() scanned = 0 extracted = 0 already_present = 0 ignored_non_regular = 0
with _open_source(url_or_path, opener, timeout_s) as stream: try: # tarfile in "r|*" mode only ever calls ``stream.read``; urllib responses are not # nominally IO[bytes], hence the cast. with tarfile.open(fileobj=cast(IO[bytes], stream), mode="r|*") as archive: for member in archive: scanned += 1 if not member.isreg(): if select(_collapse_name(member.name)): ignored_non_regular += 1 _forget_members(archive) continue name = _safe_member_name(member.name) if select(name): target = _resolve_target(root, dest_dir, name) if ( name not in written_this_run and target.is_file() and target.stat().st_size == member.size ): already_present += 1 else: source = archive.extractfile(member) if source is None: raise FetchError(f"cannot read member {name!r} of archive {label}") _write_member_atomically(source, target, member.size, name, label) written_this_run.add(name) extracted += 1 result.setdefault(name, target) # Streaming mode would otherwise keep every TarInfo alive. _forget_members(archive) except _STREAM_ERRORS as exc: raise FetchError( f"reading archive {label} failed after {scanned} members " f"({extracted} extracted, {already_present} already present): {exc!r}; " "re-run to continue (archives cannot be resumed mid-stream)" ) from exc
logger.info( "stream_extract %s: scanned %d members, extracted %d, already present %d, " "ignored %d selected non-regular members (directories/links/devices)", label, scanned, extracted, already_present, ignored_non_regular, ) return list(result.values())
def _forget_members(archive: tarfile.TarFile) -> None: """Drop ``TarFile``'s per-member cache; streaming a huge archive would otherwise grow it.""" # ``members`` is a runtime attribute that typeshed does not declare. archive.members = [] # type: ignore[attr-defined]
@contextmanagerdef _open_source( url_or_path: str | Path, opener: Opener, timeout_s: float) -> Iterator[Response | IO[bytes]]: if isinstance(url_or_path, str) and url_or_path.lower().startswith(("http://", "https://")): request = urllib.request.Request(url_or_path, headers={"User-Agent": _USER_AGENT}) try: response = opener(request, timeout_s) except _NETWORK_ERRORS as exc: # includes HTTPError raise FetchError(f"opening {url_or_path} failed: {exc!r}") from exc with response: if response.status != 200: raise FetchError(f"unexpected HTTP status {response.status} from {url_or_path}") yield response else: path = Path(url_or_path) if not path.is_file(): raise FetchError(f"archive {path} does not exist or is not a file") with path.open("rb") as handle: yield handle
def _collapse_name(name: str) -> str: """Drop leading ``./`` and empty/``.`` components; performs no safety checks.""" return "/".join(part for part in name.split("/") if part not in ("", "."))
def _safe_member_name(raw_name: str) -> str: """Normalise a regular-file member name or raise ``FetchError`` if it is unsafe.""" reason: str | None = None if "\x00" in raw_name: reason = "contains a NUL byte" elif "\\" in raw_name: reason = "contains a backslash" elif raw_name.startswith("/"): reason = "is an absolute path" elif _DRIVE_LETTER_RE.match(raw_name) is not None: reason = "starts with a drive letter" elif ".." in raw_name.split("/"): reason = "contains a '..' component" else: name = _collapse_name(raw_name) if name: return name reason = "is empty" raise FetchError(f"unsafe tar member name {raw_name!r}: {reason}")
def _resolve_target(root: Path, dest_dir: Path, name: str) -> Path: """Return ``dest_dir / name`` after checking that it stays inside ``dest_dir``.""" target = dest_dir.joinpath(*name.split("/")) try: target.resolve().relative_to(root) except ValueError: raise FetchError(f"tar member {name!r} would be written outside {dest_dir}") from None return target
def _write_member_atomically( source: IO[bytes], target: Path, expected_bytes: int, name: str, label: str) -> None: """Copy ``source`` to ``target`` via a temp file in the same directory and a rename.""" target.parent.mkdir(parents=True, exist_ok=True) fd, tmp_name = tempfile.mkstemp(prefix=f".{target.name}.", suffix=".tmp", dir=target.parent) tmp_path = Path(tmp_name) try: with os.fdopen(fd, "wb") as handle: shutil.copyfileobj(source, handle, _COPY_CHUNK_BYTES) written = handle.tell() if written != expected_bytes: raise FetchError( f"member {name!r} of {label}: wrote {written} bytes, expected {expected_bytes}" ) handle.flush() os.fsync(handle.fileno()) tmp_path.replace(target) except BaseException: tmp_path.unlink(missing_ok=True) raise
# --------------------------------------------------------------------------------------# Hugging Face URLs# --------------------------------------------------------------------------------------
def hf_resolve_url( repo_id: str, revision: str, path_in_repo: str, repo_type: Literal["model", "dataset"],) -> str: """Build a revision-pinned Hugging Face ``resolve`` URL.
Args: repo_id: Repository id such as ``"google/fleurs"``. revision: Full 40-character lowercase hex commit SHA (branches and tags are refused so the downloaded data is pinned). path_in_repo: File path inside the repository (``/``-separated, relative). repo_type: ``"dataset"`` or ``"model"``.
Returns: ``https://huggingface.co/[datasets/]<repo_id>/resolve/<revision>/<path>`` with every path component percent-encoded (``/`` kept).
Raises: ValueError: On a malformed revision, repo id or path, or an unknown repo type. """ if repo_type not in ("model", "dataset"): raise ValueError(f"repo_type must be 'model' or 'dataset', got {repo_type!r}") if _COMMIT_SHA_RE.fullmatch(revision) is None: raise ValueError(f"revision must be a 40-character lowercase hex commit SHA: {revision!r}") _require_clean_path("repo_id", repo_id) _require_clean_path("path_in_repo", path_in_repo) prefix = "datasets/" if repo_type == "dataset" else "" quoted_repo = urllib.parse.quote(repo_id, safe="/") quoted_path = urllib.parse.quote(path_in_repo, safe="/") return f"https://huggingface.co/{prefix}{quoted_repo}/resolve/{revision}/{quoted_path}"
def _require_clean_path(what: str, value: str) -> None: parts = value.split("/") if not value or any(part in ("", ".", "..") for part in parts) or "\\" in value: raise ValueError( f"{what} must be a relative '/'-separated path without empty, '.' or '..' " f"components: {value!r}" )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817"""Self-contained HTML listening panels and a strict parser for their CSV export.
A panel is a single HTML file that a human opens locally in a browser. It embeds the audio(base64 data URIs), shows one card per item with per-item questions, keeps answers in``localStorage`` and exports a CSV through a "CSV indir" button. The panel makes no networkrequests of any kind.
The CSV layout is a contract between the in-page JavaScript (``buildCsv``) and:func:`read_panel_results`::
panel_id,item_id,<question ids in spec order>,[text,]note
``text`` is present only if at least one item has ``editable_text``. The file is UTF-8 witha BOM, fields are quoted per RFC 4180 and lines end with CRLF. Unanswered questions areempty fields.
User-visible UI strings are Turkish; everything else is English."""
from __future__ import annotations
import base64import csvimport htmlimport ioimport jsonimport refrom collections.abc import Mappingfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Literal
from nida.text.turkish import nfcfrom nida.utils.io import atomic_write_json, atomic_write_text
__all__ = [ "AudioRef", "PanelItem", "PanelResult", "PanelSpec", "Question", "build_panel_html", "csv_header", "has_text_column", "load_panel_spec", "missing_required", "read_panel_results", "write_panel",]
QuestionKind = Literal["choice", "scale", "text"]
_QUESTION_KINDS: tuple[str, ...] = ("choice", "scale", "text")_QUESTION_ID_RE = re.compile(r"[a-z][a-z0-9_]{0,31}")_ITEM_ID_RE = re.compile(r"[A-Za-z0-9_.-]{1,64}")_RESERVED_QUESTION_IDS = frozenset({"panel_id", "item_id", "text", "note"})_AUDIO_MIME_BY_SUFFIX: Mapping[str, str] = { ".wav": "audio/wav", ".flac": "audio/flac", ".mp3": "audio/mpeg", ".ogg": "audio/ogg", ".opus": "audio/ogg",}_DEFAULT_MAX_BYTES = 60_000_000_LINE_SEPARATOR = chr(0x2028)_PARAGRAPH_SEPARATOR = chr(0x2029)
def audio_mime(path: Path) -> str: """Return the MIME type for an audio file, chosen by (case-insensitive) suffix.
Raises: ValueError: if the suffix is not one of .wav, .flac, .mp3, .ogg, .opus. """ mime = _AUDIO_MIME_BY_SUFFIX.get(path.suffix.lower()) if mime is None: supported = ", ".join(sorted(_AUDIO_MIME_BY_SUFFIX)) raise ValueError( f"unsupported audio suffix {path.suffix!r} for {path} (supported: {supported})" ) return mime
@dataclass(frozen=True)class AudioRef: """One audio clip shown on a card, with the label the listener sees."""
label: str path: Path
def __post_init__(self) -> None: if not self.label.strip(): raise ValueError(f"AudioRef for {self.path} has an empty label") audio_mime(self.path) # validates the suffix
@dataclass(frozen=True)class Question: """A per-item question.
``choice`` renders radio buttons from ``options``; ``scale`` does the same with the options being the ordered allowed values (e.g. ``("1", "2", "3", "4", "5")``); ``text`` is a free-text box and takes no options. """
id: str prompt: str kind: QuestionKind options: tuple[str, ...] = () required: bool = True
def __post_init__(self) -> None: if _QUESTION_ID_RE.fullmatch(self.id) is None: raise ValueError(f"question id {self.id!r} does not match {_QUESTION_ID_RE.pattern}") if self.id in _RESERVED_QUESTION_IDS: raise ValueError(f"question id {self.id!r} is reserved") if not self.prompt.strip(): raise ValueError(f"question {self.id!r} has an empty prompt") if self.kind not in _QUESTION_KINDS: raise ValueError(f"question {self.id!r} has unknown kind {self.kind!r}") if self.kind == "text": if self.options: raise ValueError(f"text question {self.id!r} must not have options") return if len(self.options) < 2: raise ValueError(f"{self.kind} question {self.id!r} needs at least 2 options") if any(option == "" for option in self.options): raise ValueError(f"{self.kind} question {self.id!r} has an empty option") if len(set(self.options)) != len(self.options): raise ValueError(f"{self.kind} question {self.id!r} has duplicate options")
@dataclass(frozen=True)class PanelItem: """One card: audio clips plus optional (editable) text and a caption."""
item_id: str audios: tuple[AudioRef, ...] text: str = "" editable_text: bool = False info: str = ""
def __post_init__(self) -> None: if _ITEM_ID_RE.fullmatch(self.item_id) is None: raise ValueError(f"item id {self.item_id!r} does not match {_ITEM_ID_RE.pattern}") if not self.audios: raise ValueError(f"item {self.item_id!r} has no audio")
@dataclass(frozen=True)class PanelSpec: """A whole panel: title, instructions, questions and items."""
panel_id: str title: str instructions: str questions: tuple[Question, ...] items: tuple[PanelItem, ...]
def __post_init__(self) -> None: if _ITEM_ID_RE.fullmatch(self.panel_id) is None: raise ValueError(f"panel id {self.panel_id!r} does not match {_ITEM_ID_RE.pattern}") if not self.title.strip(): raise ValueError(f"panel {self.panel_id!r} has an empty title") if not self.items: raise ValueError(f"panel {self.panel_id!r} has no items") _raise_on_duplicates([q.id for q in self.questions], "question id", self.panel_id) _raise_on_duplicates([i.item_id for i in self.items], "item id", self.panel_id)
def _raise_on_duplicates(values: list[str], what: str, panel_id: str) -> None: seen: set[str] = set() duplicates: list[str] = [] for value in values: if value in seen and value not in duplicates: duplicates.append(value) seen.add(value) if duplicates: raise ValueError(f"panel {panel_id!r} has duplicate {what}s: {duplicates}")
def has_text_column(spec: PanelSpec) -> bool: """Whether the CSV has a ``text`` column (any item has ``editable_text``).""" return any(item.editable_text for item in spec.items)
def csv_header(spec: PanelSpec) -> list[str]: """The exact CSV header row produced by the panel for ``spec``.""" header = ["panel_id", "item_id", *(q.id for q in spec.questions)] if has_text_column(spec): header.append("text") header.append("note") return header
# --------------------------------------------------------------------------------------# HTML generation# --------------------------------------------------------------------------------------
_CSS = r""":root { color-scheme: light dark; --bg: #f6f6f3; --fg: #1b1b1a; --muted: #5d5d58; --card: #ffffff; --line: #d7d6cf; --accent: #1d5fd0; --accent-fg: #ffffff; --ok: #1a7f3c; --warn: #b45309; --field: #ffffff;}@media (prefers-color-scheme: dark) { :root { --bg: #151515; --fg: #ececea; --muted: #a3a39d; --card: #1f1f1e; --line: #3a3a37; --accent: #6ea0ff; --accent-fg: #0b0b0b; --ok: #5fcf85; --warn: #f0b05a; --field: #161616; }}* { box-sizing: border-box; }html { -webkit-text-size-adjust: 100%; }body { margin: 0; background: var(--bg); color: var(--fg); font: 16px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;}header.top { padding: 20px 16px 8px; max-width: 760px; margin: 0 auto; }h1 { font-size: 1.4rem; margin: 0 0 8px; }.instructions { white-space: pre-wrap; color: var(--muted); margin: 0 0 8px; }.bar { position: sticky; top: 0; z-index: 5; background: var(--bg); border-bottom: 1px solid var(--line);}.bar-inner { max-width: 760px; margin: 0 auto; padding: 10px 16px; display: flex; gap: 12px; align-items: center; justify-content: space-between; flex-wrap: wrap;}#progress { font-weight: 600; }button.primary { min-height: 44px; padding: 0 18px; border: 0; border-radius: 10px; cursor: pointer; background: var(--accent); color: var(--accent-fg); font: inherit; font-weight: 600;}main { max-width: 760px; margin: 0 auto; padding: 8px 16px 64px; }.card { background: var(--card); border: 1px solid var(--line); border-radius: 14px; padding: 14px; margin: 14px 0;}.card.done { border-color: var(--ok); }.card-head { display: flex; gap: 10px; align-items: baseline; flex-wrap: wrap; }.num { font-weight: 700; font-size: 1.1rem; }.item-id { color: var(--muted); font-size: 0.85rem; word-break: break-all; }.info { color: var(--muted); font-size: 0.9rem; margin: 2px 0 8px; white-space: pre-wrap; }.audio { margin: 10px 0; }.alabel { font-size: 0.9rem; font-weight: 600; margin-bottom: 4px; }audio { width: 100%; }.text { white-space: pre-wrap; margin: 10px 0; padding: 10px 12px; border-radius: 10px; background: var(--bg); border: 1px solid var(--line);}fieldset.q { border: 0; margin: 14px 0 0; padding: 0; min-width: 0; }legend, label.lbl { font-weight: 600; padding: 0; margin-bottom: 6px; display: block; }.req { color: var(--warn); margin-left: 4px; }.opts { display: flex; flex-wrap: wrap; gap: 8px; }.opt { position: relative; }.opt input { position: absolute; opacity: 0; width: 100%; height: 100%; margin: 0; cursor: pointer;}.opt span { display: inline-flex; align-items: center; justify-content: center; min-width: 44px; min-height: 44px; padding: 0 14px; border: 1px solid var(--line); border-radius: 10px; background: var(--field);}.opt input:checked + span { background: var(--accent); color: var(--accent-fg); border-color: var(--accent);}.opt input:focus-visible + span { outline: 2px solid var(--accent); outline-offset: 2px; }textarea { width: 100%; font: inherit; color: var(--fg); background: var(--field); border: 1px solid var(--line); border-radius: 10px; padding: 8px 10px; resize: vertical;}.field { margin-top: 14px; }"""
_JS = r"""(function () { "use strict"; var spec = JSON.parse(document.getElementById("panel-data").textContent); var STORAGE_KEY = "nida-panel:" + spec.panel_id;
/* BEGIN buildCsv */ function own(obj, key) { return obj !== null && obj !== undefined && Object.prototype.hasOwnProperty.call(obj, key) ? obj[key] : undefined; }
function buildCsv(spec, answers) { function field(value) { var s = value === undefined || value === null ? "" : String(value); return /[",\r\n]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s; } var hasText = spec.items.some(function (it) { return it.editable_text; }); var header = ["panel_id", "item_id"]; spec.questions.forEach(function (q) { header.push(q.id); }); if (hasText) { header.push("text"); } header.push("note"); var lines = [header.map(field).join(",")]; spec.items.forEach(function (it) { var a = own(answers, it.item_id); var row = [spec.panel_id, it.item_id]; spec.questions.forEach(function (q) { row.push(own(a, q.id)); }); if (hasText) { var text = own(a, "text"); row.push(it.editable_text ? (text === undefined ? it.text : text) : ""); } row.push(own(a, "note")); lines.push(row.map(field).join(",")); }); return lines.join("\r\n") + "\r\n"; } /* END buildCsv */
/* BEGIN missingRequired */ function missingRequired(spec, answers) { var missing = []; spec.items.forEach(function (it) { var a = own(answers, it.item_id); var absent = spec.questions.some(function (q) { if (!q.required) { return false; } var v = own(a, q.id); return v === undefined || String(v).trim() === ""; }); if (absent) { missing.push(it.item_id); } }); return missing; } /* END missingRequired */
var cards = Array.prototype.slice.call(document.querySelectorAll(".card")); var hasRequired = spec.questions.some(function (q) { return q.required; });
function collect() { var out = Object.create(null); cards.forEach(function (card) { var id = card.getAttribute("data-item"); var a = Object.create(null); spec.questions.forEach(function (q) { if (q.kind === "text") { var ta = card.querySelector('textarea[data-q="' + q.id + '"]'); a[q.id] = ta ? ta.value : ""; } else { var r = card.querySelector('input[data-q="' + q.id + '"]:checked'); a[q.id] = r ? r.value : ""; } }); var t = card.querySelector('textarea[data-field="text"]'); if (t) { a.text = t.value; } var n = card.querySelector('textarea[data-field="note"]'); a.note = n ? n.value : ""; out[id] = a; }); return out; }
function restore(saved) { if (saved === null || typeof saved !== "object") { return; } cards.forEach(function (card) { var a = own(saved, card.getAttribute("data-item")); if (a === null || typeof a !== "object") { return; } spec.questions.forEach(function (q) { var v = own(a, q.id); if (typeof v !== "string") { return; } if (q.kind === "text") { var ta = card.querySelector('textarea[data-q="' + q.id + '"]'); if (ta) { ta.value = v; } } else { var radios = card.querySelectorAll('input[data-q="' + q.id + '"]'); Array.prototype.forEach.call(radios, function (r) { r.checked = (r.value === v); }); } }); var t = card.querySelector('textarea[data-field="text"]'); if (t && typeof own(a, "text") === "string") { t.value = a.text; } var n = card.querySelector('textarea[data-field="note"]'); if (n && typeof own(a, "note") === "string") { n.value = a.note; } }); }
function isComplete(item, a) { if (missingRequired({questions: spec.questions, items: [item]}, {[item.item_id]: a}).length) { return false; } if (hasRequired) { return true; } var touched = spec.questions.some(function (q) { return String(own(a, q.id) || "") !== ""; }); return touched || String(own(a, "note") || "") !== "" || (item.editable_text && own(a, "text") !== item.text); }
function refresh() { var answers = collect(); var done = 0; spec.items.forEach(function (item, i) { var ok = isComplete(item, own(answers, item.item_id)); cards[i].classList.toggle("done", ok); if (ok) { done += 1; } }); document.getElementById("progress").textContent = done + " / " + spec.items.length + " tamamlandı"; try { window.localStorage.setItem(STORAGE_KEY, JSON.stringify(answers)); } catch (e) { /* storage unavailable */ } }
function download() { var answers = collect(); var missing = missingRequired(spec, answers); if (missing.length > 0) { var msg = missing.length + " öğede zorunlu sorular yanıtsız. Yine de CSV indirilsin mi?"; if (!window.confirm(msg)) { return; } } var blob = new Blob(["" + buildCsv(spec, answers)], {type: "text/csv;charset=utf-8"}); var url = URL.createObjectURL(blob); var link = document.createElement("a"); link.href = url; link.download = spec.panel_id + "-results.csv"; document.body.appendChild(link); link.click(); document.body.removeChild(link); setTimeout(function () { URL.revokeObjectURL(url); }, 1000); }
try { var raw = window.localStorage.getItem(STORAGE_KEY); if (raw) { restore(JSON.parse(raw)); } } catch (e) { /* storage unavailable or corrupt: start fresh */ }
document.addEventListener("input", refresh); document.addEventListener("change", refresh); document.addEventListener("play", function (ev) { Array.prototype.forEach.call(document.querySelectorAll("audio"), function (el) { if (el !== ev.target) { el.pause(); } }); }, true); document.getElementById("download").addEventListener("click", download); refresh();})();"""
_HTML_TEMPLATE = """<!DOCTYPE html><html lang="tr"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>@@TITLE@@</title><style>@@CSS@@</style></head><body><header class="top"><h1>@@TITLE@@</h1><p class="instructions">@@INSTRUCTIONS@@</p><p class="instructions">* ile işaretli sorular zorunludur.Yanıtlarınız bu tarayıcıda otomatik kaydedilir.</p></header><div class="bar"><div class="bar-inner"><span id="progress" role="status">0 / @@COUNT@@ tamamlandı</span><button id="download" class="primary" type="button">CSV indir</button></div></div><main>@@CARDS@@</main><script type="application/json" id="panel-data">@@DATA@@</script><script>@@JS@@</script></body></html>"""
def _esc(value: str) -> str: return html.escape(value, quote=True)
def _embed_json(obj: object) -> str: """Serialise ``obj`` for a ``<script type="application/json">`` block.
``<``, ``>``, ``&`` and the JS line separators are escaped so that no text can close the script element or be parsed as markup; the JSON stays valid and decodes identically. """ text = json.dumps(obj, ensure_ascii=False, separators=(",", ":")) return ( text.replace("<", "\\u003c") .replace(">", "\\u003e") .replace("&", "\\u0026") .replace(_LINE_SEPARATOR, "\\u2028") .replace(_PARAGRAPH_SEPARATOR, "\\u2029") )
def _question_to_dict(question: Question) -> dict[str, object]: return { "id": question.id, "prompt": question.prompt, "kind": question.kind, "options": list(question.options), "required": question.required, }
def _spec_to_dict(spec: PanelSpec, *, embed: bool) -> dict[str, object]: """Machine-readable spec. ``embed=True`` is the in-page form (audio MIME types); otherwise audio file names are listed, never bytes.""" items: list[dict[str, object]] = [] for item in spec.items: audios: list[dict[str, str]] = [ {"label": a.label, "mime": audio_mime(a.path)} if embed else {"label": a.label, "file_name": a.path.name} for a in item.audios ] items.append( { "item_id": item.item_id, "audios": audios, "text": item.text, "editable_text": item.editable_text, "info": item.info, } ) return { "panel_id": spec.panel_id, "title": spec.title, "instructions": spec.instructions, "questions": [_question_to_dict(q) for q in spec.questions], "items": items, }
def _audio_html(audio: AudioRef) -> str: payload = base64.b64encode(audio.path.read_bytes()).decode("ascii") src = f"data:{audio_mime(audio.path)};base64,{payload}" return ( f'<div class="audio"><div class="alabel">{_esc(audio.label)}</div>' f'<audio controls preload="none" src="{src}"></audio></div>' )
def _question_html(question: Question, item_index: int) -> str: star = '<span class="req" aria-hidden="true">*</span>' if question.required else "" prompt = _esc(question.prompt) qid = _esc(question.id) if question.kind == "text": field_id = f"t{item_index}_{qid}" return ( f'<div class="field"><label class="lbl" for="{field_id}">{prompt}{star}</label>' f'<textarea id="{field_id}" data-q="{qid}" rows="2"></textarea></div>' ) name = f"r{item_index}_{qid}" options = "".join( f'<label class="opt"><input type="radio" name="{name}" data-q="{qid}" ' f'value="{_esc(option)}"><span>{_esc(option)}</span></label>' for option in question.options ) return ( f'<fieldset class="q"><legend>{prompt}{star}</legend>' f'<div class="opts">{options}</div></fieldset>' )
def _card_html(item: PanelItem, index: int, questions: tuple[Question, ...]) -> str: parts = [ f'<section class="card" data-item="{_esc(item.item_id)}">', f'<div class="card-head"><span class="num">{index + 1}</span>' f'<span class="item-id">{_esc(item.item_id)}</span></div>', ] if item.info: parts.append(f'<div class="info">{_esc(item.info)}</div>') parts.extend(_audio_html(a) for a in item.audios) if item.editable_text: # A single leading newline inside <textarea> is dropped by the HTML parser, so add one # to keep text that itself starts with a newline intact. parts.append( f'<div class="field"><label class="lbl" for="e{index}">' "Metin (düzenleyebilirsiniz)</label>" f'<textarea id="e{index}" data-field="text" rows="3">\n{_esc(item.text)}</textarea>' "</div>" ) elif item.text: parts.append(f'<div class="text">{_esc(item.text)}</div>') parts.extend(_question_html(q, index) for q in questions) parts.append( f'<div class="field"><label class="lbl" for="n{index}">Not (isteğe bağlı)</label>' f'<textarea id="n{index}" data-field="note" rows="2"></textarea></div>' ) parts.append("</section>") return "\n".join(parts)
def build_panel_html(spec: PanelSpec, max_bytes: int = _DEFAULT_MAX_BYTES) -> str: """Render ``spec`` as one self-contained HTML5 document.
Args: spec: The panel definition. max_bytes: Upper bound for the UTF-8 size of the document.
Returns: The HTML text. It references no external resource; audio is embedded as data URIs.
Raises: ValueError: if the document exceeds ``max_bytes`` (the message reports the size). FileNotFoundError: if an audio file is missing. """ cards = "\n".join(_card_html(item, i, spec.questions) for i, item in enumerate(spec.items)) values = { "TITLE": _esc(spec.title), "INSTRUCTIONS": _esc(spec.instructions), "COUNT": str(len(spec.items)), "CSS": _CSS, "CARDS": cards, "DATA": _embed_json(_spec_to_dict(spec, embed=True)), "JS": _JS, } # Single-pass substitution: inserted values are never rescanned for placeholders. document = re.sub(r"@@([A-Z]+)@@", lambda m: values[m.group(1)], _HTML_TEMPLATE) size_bytes = len(document.encode("utf-8")) if size_bytes > max_bytes: raise ValueError( f"panel {spec.panel_id!r} is {size_bytes} bytes, over the limit of {max_bytes} bytes; " "use fewer items or shorter clips" ) return document
def write_panel(spec: PanelSpec, out_dir: Path) -> Path: """Write ``panel.html`` and ``panel.json`` into ``out_dir`` and return the HTML path.""" document = build_panel_html(spec) html_path = out_dir / "panel.html" atomic_write_text(html_path, document) atomic_write_json(out_dir / "panel.json", _spec_to_dict(spec, embed=False)) return html_path
# --------------------------------------------------------------------------------------# CSV parsing# --------------------------------------------------------------------------------------
@dataclass(frozen=True)class PanelResult: """One parsed CSV row.
``answers`` maps every question id to its answer ("" if unanswered). ``text`` is the edited text for items with ``editable_text`` and ``None`` otherwise. """
item_id: str answers: Mapping[str, str] text: str | None note: str
def _describe_header_difference(expected: list[str], actual: list[str]) -> str: missing = [c for c in expected if c not in actual] unexpected = [c for c in actual if c not in expected] parts: list[str] = [] if missing: parts.append(f"missing columns {missing}") if unexpected: parts.append(f"unexpected columns {unexpected}") if not parts: parts.append("columns are the same but in a different order") return "; ".join(parts)
def _decode_csv_bytes(data: bytes, csv_path: Path) -> str: try: text = data.decode("utf-8") except UnicodeDecodeError as exc: raise ValueError(f"{csv_path} is not valid UTF-8: {exc}") from exc return text.removeprefix("")
def read_panel_results(csv_path: Path, spec: PanelSpec) -> list[PanelResult]: """Parse a CSV exported by the panel for ``spec``, strictly.
Free-text fields (``text``, ``note`` and ``text`` questions) are NFC-normalised.
Returns: One :class:`PanelResult` per row, in file order.
Raises: ValueError: on a malformed file, header mismatch, wrong ``panel_id``, unknown or repeated item, an answer that is not one of the options, text in the ``text`` column of a non-editable item, or items of ``spec`` absent from the file. """ text = _decode_csv_bytes(csv_path.read_bytes(), csv_path) reader = csv.reader(io.StringIO(text, newline=""), strict=True) expected = csv_header(spec) questions = {q.id: q for q in spec.questions} items = {item.item_id: item for item in spec.items} with_text = has_text_column(spec)
try: header = next(reader, None) if header is None: raise ValueError(f"{csv_path} is empty; expected header {expected}") if header != expected: raise ValueError( f"{csv_path}: header mismatch ({_describe_header_difference(expected, header)}); " f"expected {expected}, got {header}" ) results: list[PanelResult] = [] seen: set[str] = set() for row in reader: if not row: # blank line (e.g. trailing newline added by an editor) continue where = f"{csv_path} line {reader.line_num}" if len(row) != len(expected): raise ValueError(f"{where}: expected {len(expected)} fields, got {len(row)}") cells = dict(zip(expected, row, strict=True)) if cells["panel_id"] != spec.panel_id: raise ValueError( f"{where}: panel_id {cells['panel_id']!r} does not match {spec.panel_id!r}" ) item_id = cells["item_id"] item = items.get(item_id) if item is None: raise ValueError(f"{where}: unknown item_id {item_id!r}") if item_id in seen: raise ValueError(f"{where}: duplicate item_id {item_id!r}") seen.add(item_id) answers: dict[str, str] = {} for qid, question in questions.items(): value = cells[qid] if question.kind == "text": value = nfc(value) elif value != "" and value not in question.options: raise ValueError( f"{where}: item {item_id!r} question {qid!r}: {value!r} is not one of " f"{list(question.options)}" ) answers[qid] = value edited: str | None = None if with_text: if item.editable_text: edited = nfc(cells["text"]) elif cells["text"] != "": raise ValueError( f"{where}: item {item_id!r} is not editable but has text {cells['text']!r}" ) results.append( PanelResult(item_id=item_id, answers=answers, text=edited, note=nfc(cells["note"])) ) except csv.Error as exc: raise ValueError(f"{csv_path}: malformed CSV near line {reader.line_num}: {exc}") from exc
absent = [item.item_id for item in spec.items if item.item_id not in seen] if absent: raise ValueError(f"{csv_path}: {len(absent)} item(s) missing from the CSV: {absent}") return results
def missing_required(results: list[PanelResult], spec: PanelSpec) -> list[str]: """Item ids (in ``results`` order) whose required questions lack a non-blank answer.""" required = [q.id for q in spec.questions if q.required] return [ result.item_id for result in results if any(not result.answers.get(qid, "").strip() for qid in required) ]
def _bare_name(name: object) -> str: """A stored audio file name must be a plain name inside the panel directory.""" if ( not isinstance(name, str) or name in ("", ".", "..") or "/" in name or "\\" in name or Path(name).name != name ): raise ValueError(f"panel audio file name must be a bare name, got {name!r}") return name
def load_panel_spec(path: Path) -> PanelSpec: """Rebuild a :class:`PanelSpec` from the ``panel.json`` written by :func:`write_panel`.
Audio paths point next to ``panel.json`` (file names only are stored); they are needed for validating results, not for reading audio, so they need not exist.
Raises: ValueError: if the file does not have the expected structure. """ obj = json.loads(path.read_text(encoding="utf-8")) try: questions = tuple( Question( id=q["id"], prompt=q["prompt"], kind=q["kind"], options=tuple(q["options"]), required=bool(q["required"]), ) for q in obj["questions"] ) items = tuple( PanelItem( item_id=i["item_id"], audios=tuple( AudioRef(label=a["label"], path=path.parent / _bare_name(a["file_name"])) for a in i["audios"] ), text=i["text"], editable_text=bool(i["editable_text"]), info=i["info"], ) for i in obj["items"] ) return PanelSpec( panel_id=obj["panel_id"], title=obj["title"], instructions=obj["instructions"], questions=questions, items=items, ) except (KeyError, TypeError) as err: raise ValueError(f"{path}: malformed panel spec ({err})") from err123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358"""Phase 0 benchmark stage runner behind ``nida bench-phase0`` (B1 + B2 on Colab).
Every stage first checks that all sources it touches are ``approved`` in``configs/sources.yaml``. Stages are idempotent and resumable; ``all`` runs the wholeGPU part in one session (one Drive permission), in this order:
check → prepare-b1 → asr-b1 → panel-b1c → score-b1 → prepare-b2 → vae-b2 → asr-b2 → quality-b2 → score-b2 → panel-b2
After the user has answered the panels (no GPU needed):
* ``score-b1`` with ``--c-results <csv>`` adds layer C and applies the decision rule;* ``score-b2-panel`` with ``--b2-panel-results <csv>`` un-blinds and scores the B2 panel."""
from __future__ import annotations
import importlib.metadataimport jsonimport loggingimport shutilfrom collections.abc import Sequencefrom dataclasses import dataclass, fieldfrom pathlib import Path
from nida.bench import b1, b2, envsfrom nida.bench.clips import Clipfrom nida.bench.panel import load_panel_spec, read_panel_resultsfrom nida.bench.prepare import Workspace, load_manifest, prepare_b1from nida.bench.protocol import ( WorkerSummary, WorkRequest, WorkResult, drop_results, load_results, read_summary, write_requests,)from nida.bench.registry import ( ASR_SYSTEMS, QUALITY_SYSTEM, VAE_SYSTEMS, System, load_sources, require_approved,)from nida.bench.report import render_b1, render_b2, render_b2_panelfrom nida.utils.io import atomic_write_json, atomic_write_text
__all__ = ["ALL_STAGES", "STAGES", "Phase0"]
log = logging.getLogger(__name__)
ALL_STAGES = ( "check", "prepare-b1", "asr-b1", "panel-b1c", "score-b1", "prepare-b2", "vae-b2", "asr-b2", "quality-b2", "score-b2", "panel-b2",)STAGES = (*ALL_STAGES, "score-b2-panel")
B1_DATA = ("fleurs_tr", "mediaspeech_tr", "yodas_tr")B2_DATA = ("expresso",)FAMILIES = { "qwen3_asr_1_7b": "qwen", "qwen3_asr_0_6b": "qwen", "omniasr_llm_7b": "omni", "omniasr_ctc_1b": "omni", "whisper_large_v3": "whisper", "buzzasr_turkish": "whisper",}WHISPER_FOR_B2 = ASR_SYSTEMS["whisper_large_v3"]MAIN_PACKAGES = ("numpy", "scipy", "soundfile", "PyYAML", "torch")
def _main_package_versions() -> dict[str, str]: versions: dict[str, str] = {} for name in MAIN_PACKAGES: try: versions[name] = importlib.metadata.version(name) except importlib.metadata.PackageNotFoundError: versions[name] = "not-installed" return versions
@dataclassclass Phase0: workspace: Workspace envs_root: Path repo_dir: Path sources_path: Path systems: tuple[System, ...] = tuple(ASR_SYSTEMS.values()) seed: int = 20261008 uv: str | None = None # located lazily, after the approval gate retry_failed: bool = False _c_results: Path | None = field(default=None, init=False, repr=False) _b2_panel_results: Path | None = field(default=None, init=False, repr=False)
# ------------------------------------------------------------------ helpers
def _require(self, stage: str) -> None: sources = load_sources(self.sources_path) needed: set[str] = set() if stage.endswith("b1") or stage in ("panel-b1c", "check"): needed |= set(B1_DATA) | {s.source_id for s in self.systems} if "b2" in stage or stage == "check": # B2 reuses the Turkish B1 clips (FLEURS, MediaSpeech) as its tr subsets. needed |= set(B2_DATA) | {"fleurs_tr", "mediaspeech_tr"} needed |= {s.source_id for s in VAE_SYSTEMS.values()} needed |= {QUALITY_SYSTEM.source_id, WHISPER_FOR_B2.source_id} require_approved(needed, sources)
def _python(self, worker: str) -> Path: spec = envs.env_for_worker(worker) if self.uv is None: self.uv = envs.find_uv(envs.subprocess_runner) python = envs.ensure_env(spec, self.envs_root, self.repo_dir, uv=self.uv) freeze = self.envs_root / spec.name / "freeze.txt" if freeze.exists(): # keep the exact package set next to the results (durable) dest = self.workspace.root / "envs" / f"{spec.name}-freeze.txt" dest.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(freeze, dest) return python
def _vae_results(self) -> dict[str, WorkResult]: return load_results(self.workspace.workers / "b2_vae" / "results.jsonl")
def _b2_plan(self) -> b2.B2Plan: return b2.B2Plan(seed=self.seed)
def _b1_clips(self) -> list[Clip]: return load_manifest(self.workspace)[1]
def _b2_clips(self) -> list[Clip]: return b2.load_b2_manifest(self.workspace)[1]
def _summaries(self) -> dict[str, WorkerSummary]: out: dict[str, WorkerSummary] = {} for system in self.systems: path = self.workspace.workers / system.system_id / "results.summary.json" if path.exists(): out[system.system_id] = read_summary(path) return out
def _run_aux(self, name: str, system: System, requests: Sequence[WorkRequest]) -> None: """Run a non-B1 worker (VAE, Whisper on B2, Audiobox) over prepared requests.""" if not requests: # Never prune a results file down to nothing: an empty request set means an # upstream input is missing (e.g. the VAE results file), not "no work". raise RuntimeError(f"{name}: no requests; is an upstream stage's output missing?") out_dir = self.workspace.workers / name results_path = out_dir / "results.jsonl" if results_path.exists(): # The request set is the source of truth: results for items that are no longer # requested (e.g. a reconstruction that failed on redo) are removed, not trusted. wanted = {r.clip_id for r in requests} stray = [cid for cid in load_results(results_path, repair=True) if cid not in wanted] if stray: log.warning("%s: removing %d results no longer requested", name, len(stray)) drop_results(results_path, stray) write_requests(out_dir / "requests.jsonl", requests) cmd = [ str(self._python(system.worker)), "-m", f"nida.bench.workers.{system.worker}", "--requests", str(out_dir / "requests.jsonl"), "--results", str(out_dir / "results.jsonl"), "--model-id", system.model_id, "--revision", system.revision, "--batch-size", str(system.batch_size), *(["--retry-failed"] if self.retry_failed else []), ] code = b1._stream_runner(cmd) if code != 0: raise RuntimeError(f"{name}: worker exited with code {code}") summary = read_summary(out_dir / "results.summary.json") if summary.n_ok + summary.n_error != len(requests): raise RuntimeError( f"{name}: {summary.n_ok + summary.n_error} results for {len(requests)} requests" ) if summary.n_error > b1.MAX_ERROR_FRACTION * (summary.n_ok + summary.n_error): raise RuntimeError( f"{name}: {summary.n_error} items failed (> 5%); rerun with --retry-failed" )
# ------------------------------------------------------------------- stages
def run( self, stage: str, *, c_results: Path | None = None, b2_panel_results: Path | None = None, ) -> dict[str, object]: """Run one stage (or ``all``); returns a JSON-compatible summary for metrics.json.""" stages = ALL_STAGES if stage == "all" else (stage,) unknown = [s for s in stages if s not in STAGES] if unknown: raise ValueError(f"unknown stage(s) {unknown}; choose from {STAGES} or 'all'") self._c_results = c_results self._b2_panel_results = b2_panel_results result: dict[str, object] = {"main_packages": _main_package_versions()} for name in stages: log.info("=== stage %s", name) self._require(name) output = getattr(self, "_stage_" + name.replace("-", "_"))() if output is not None: result[name] = output return result
def _stage_check(self) -> dict[str, object]: return {"approved": True}
def _stage_prepare_b1(self) -> dict[str, object]: clips = prepare_b1(self.workspace) counts: dict[str, int] = {} for clip in clips: counts[clip.layer] = counts.get(clip.layer, 0) + 1 return {"clips_per_layer": counts}
def _stage_asr_b1(self) -> dict[str, object]: clips = self._b1_clips() done: dict[str, object] = {} for system in self.systems: summary = b1.run_system( self.workspace, clips, system, self._python(system.worker), retry_failed=self.retry_failed, ) done[system.system_id] = {"n_ok": summary.n_ok, "n_error": summary.n_error} return done
def _stage_panel_b1c(self) -> dict[str, object]: clips = self._b1_clips() pool = [c for c in clips if c.layer == "C"] hyps = {s.system_id: b1.hypotheses(self.workspace, s) for s in self.systems} final, html = b1.build_c_panel(self.workspace, pool, hyps, self.seed) return {"panel": str(html), "n_items": len(final)}
def _stage_score_b1(self) -> dict[str, object]: clips = self._b1_clips() hyps = {s.system_id: b1.hypotheses(self.workspace, s) for s in self.systems} c_refs: dict[str, str] | None = None provenance = None if self._c_results is not None: spec = load_panel_spec(self.workspace.panels / f"b1c-{self.seed}" / "panel.json") c_refs = b1.c_references_from_panel(read_panel_results(self._c_results, spec)) provenance = b1.load_c_selection(self.workspace, self.seed) scores = b1.score_b1( clips, self.systems, hyps, c_refs, seed=self.seed, summaries=self._summaries(), c_provenance=provenance, ) choice = b1.choose_systems(scores, FAMILIES) report_dir = self.workspace.root / "reports" atomic_write_json(report_dir / "b1_metrics.json", {"scores": scores, "choice": choice}) atomic_write_text(report_dir / "b1_report.md", render_b1(scores, choice)) return {"choice": choice}
def _stage_prepare_b2(self) -> dict[str, object]: clips = b2.prepare_b2(self.workspace, self._b1_clips(), self._b2_plan()) counts: dict[str, int] = {} for clip in clips: counts[clip.layer] = counts.get(clip.layer, 0) + 1 return {"clips_per_subset": counts}
def _stage_vae_b2(self) -> dict[str, object]: system = VAE_SYSTEMS["voxcpm2_audiovae_v2"] results_path = self.workspace.workers / "b2_vae" / "results.jsonl" redo = b2.missing_vae_outputs(self.workspace, load_results(results_path, repair=True)) if redo: log.warning("b2_vae: %d reconstructions missing on disk; redoing them", len(redo)) # Invalidate derived data FIRST and the VAE results LAST: if the process dies in # between, the rerun still sees the missing reconstruction and redoes all of it. stale = [f"{clip_id}__vae" for clip_id in redo] for name in ("b2_asr_tr", "b2_asr_en", "b2_quality"): downstream = self.workspace.workers / name / "results.jsonl" if downstream.exists(): drop_results(downstream, stale) for clip_id in redo: (b2.b2_paths(self.workspace).asr16k / f"{clip_id}__vae.wav").unlink(missing_ok=True) drop_results(results_path, redo) self._run_aux("b2_vae", system, b2.vae_requests(self.workspace, self._b2_clips())) return {"redone_missing_outputs": len(redo)}
def _stage_asr_b2(self) -> None: clips = self._b2_clips() for language in ("tr", "en"): requests = b2.asr_requests(self.workspace, clips, language, self._vae_results()) if requests: self._run_aux(f"b2_asr_{language}", WHISPER_FOR_B2, requests)
def _stage_quality_b2(self) -> None: self._run_aux( "b2_quality", QUALITY_SYSTEM, b2.quality_requests(self.workspace, self._b2_clips(), self._vae_results()), )
def _stage_score_b2(self) -> dict[str, object]: asr: dict[str, WorkResult] = {} for language in ("tr", "en"): asr.update( load_results(self.workspace.workers / f"b2_asr_{language}" / "results.jsonl") ) quality = load_results(self.workspace.workers / "b2_quality" / "results.jsonl") scores = b2.score_b2(self.workspace, self._b2_clips(), asr, quality, self._vae_results()) report_dir = self.workspace.root / "reports" atomic_write_json(report_dir / "b2_metrics.json", scores) atomic_write_text(report_dir / "b2_report.md", render_b2(scores)) return scores
def _stage_panel_b2(self) -> dict[str, object]: html = b2.build_b2_panel( self.workspace, self._b2_clips(), self._b2_plan(), self._vae_results() ) return {"panel": str(html)}
def _stage_score_b2_panel(self) -> dict[str, object]: if self._b2_panel_results is None: raise ValueError("score-b2-panel needs --b2-panel-results <csv>") plan = self._b2_plan() spec = load_panel_spec(self.workspace.panels / f"b2-{plan.seed}" / "panel.json") key_obj = json.loads( (self.workspace.manifests / f"b2_panel_key-{plan.seed}.json").read_text( encoding="utf-8" ) ) scores = b2.score_b2_panel( read_panel_results(self._b2_panel_results, spec), key_obj["items"], min_per_subset=int(key_obj.get("min_per_subset", plan.n_panel_per_subset)), ) scores["excluded_missing_reconstruction"] = key_obj.get( "excluded_missing_reconstruction", {} ) report_dir = self.workspace.root / "reports" atomic_write_json(report_dir / "b2_panel_metrics.json", scores) atomic_write_text(report_dir / "b2_panel_report.md", render_b2_panel(scores)) return scores123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450"""B1 data preparation: fetch pinned sources, select clips, write uniform 16 kHz clips.
Layout (``Workspace``):
* ``root`` — durable directory on Google Drive (manifests, worker results, panels).* ``cache`` — local scratch on the Colab disk (downloads, extracted audio, clip WAVs). It may disappear between sessions; everything in it is re-derived deterministically.
Every ASR clip is written as 16 kHz mono 16-bit PCM WAV at ``cache/clips16k/<clip_id>.wav``so all systems see byte-identical input. Selection is deterministic for a given seed andpinned source revision; the resulting manifest is written once to ``root`` and reused."""
from __future__ import annotations
import csvimport jsonimport loggingimport randomimport refrom collections.abc import Callable, Iterable, Sequencefrom dataclasses import asdict, dataclassfrom pathlib import Pathfrom typing import Any
from nida.bench import fetchfrom nida.bench.audiometrics import resamplefrom nida.bench.clips import ( YODAS_DURATION_TOLERANCE_MS, Clip, FleursRow, MediaSpeechItem, Quarantined, Selection, YodasUtt, clip_from_obj, clip_to_obj, select_fleurs, select_mediaspeech, select_yodas_pool,)from nida.bench.registry import DATA_PINSfrom nida.utils.io import atomic_write_text
__all__ = [ "B1Plan", "Workspace", "clip_audio_path", "load_manifest", "parse_fleurs_tsv", "parse_yodas_listing", "prepare_b1", "write_clip_audio",]
log = logging.getLogger(__name__)
ASR_SAMPLE_RATE_HZ = 16000
@dataclass(frozen=True)class Workspace: root: Path cache: Path
@property def manifests(self) -> Path: return self.root / "manifests"
@property def workers(self) -> Path: return self.root / "workers"
@property def panels(self) -> Path: return self.root / "panels"
@property def clips16k(self) -> Path: return self.cache / "clips16k"
@dataclass(frozen=True)class B1Plan: """Parameters that fully determine the B1 clip manifest."""
seed: int = 20261008 n_fleurs: int = 100 n_mediaspeech: int = 75 n_yodas_pool: int = 300 fleurs_revision: str = DATA_PINS["fleurs_revision"] yodas_revision: str = DATA_PINS["yodas_revision"] mediaspeech_url: str = DATA_PINS["mediaspeech_url"] # Comma-separated tr000 shards. One shard (00000000) has only 289 eligible # utterances at <= 3 per video (run 20261008-120354-bench-phase0-69dc), so two. yodas_shards: str = "00000000,00000001" # Extra pool candidates drawn so that clips with broken audio (YODAS has empty wavs, # run 20261008-121509-bench-phase0-1347) can be quarantined without a short pool. yodas_spare: int = 30
def clip_audio_path(workspace: Workspace, clip: Clip) -> Path: return workspace.clips16k / f"{clip.clip_id}.wav"
# ------------------------------------------------------------------------------ parsing
def parse_fleurs_tsv(text: str) -> list[FleursRow]: """Parse FLEURS ``<split>.tsv`` (7 tab-separated columns, no header, no quoting).
Columns: sentence id, file name, raw transcription, normalized transcription, characters, number of samples (16 kHz), gender.
Raises: ValueError: on a row with the wrong number of columns or a non-integer sample count. """ rows: list[FleursRow] = [] reader = csv.reader(text.splitlines(), delimiter="\t", quoting=csv.QUOTE_NONE) for number, cols in enumerate(reader, start=1): if not cols: continue if len(cols) != 7: raise ValueError(f"FLEURS tsv line {number}: expected 7 columns, got {len(cols)}") try: num_samples = int(cols[5]) except ValueError as err: raise ValueError(f"FLEURS tsv line {number}: bad sample count {cols[5]!r}") from err rows.append(FleursRow(cols[0], cols[1], cols[2], num_samples, cols[6])) return rows
def parse_yodas_listing(text_file: str, duration_file: str, shard: str = "") -> list[YodasUtt]: """Join YODAS ``text/<shard>.txt`` (``utt_id caption``) with ``duration/<shard>.txt``.
Raises: ValueError: on malformed lines, duplicate ids or ids missing from either file. """
def split(content: str, what: str) -> dict[str, str]: out: dict[str, str] = {} for number, line in enumerate(content.splitlines(), start=1): if not line.strip(): continue parts = line.split(" ", 1) utt_id = parts[0] value = parts[1] if len(parts) == 2 else "" if utt_id in out: raise ValueError(f"YODAS {what} line {number}: duplicate id {utt_id}") out[utt_id] = value return out
captions = split(text_file, "text") durations = split(duration_file, "duration") if set(captions) != set(durations): diff = sorted(set(captions) ^ set(durations)) raise ValueError(f"YODAS text/duration ids differ, e.g. {diff[:3]}") utts: list[YodasUtt] = [] for utt_id in sorted(captions): try: seconds = float(durations[utt_id]) except ValueError as err: raise ValueError(f"YODAS duration for {utt_id} is not a number") from err utts.append(YodasUtt(utt_id, captions[utt_id].strip(), round(seconds * 1000), shard)) return utts
# -------------------------------------------------------------------------------- audio
def write_clip_audio(source: Path, dest: Path, start_ms: int, end_ms: int | None) -> int: """Write ``source[start_ms:end_ms]`` as 16 kHz mono PCM16 WAV at ``dest``.
Multi-channel input is rejected (callers pick a channel explicitly). Returns the number of samples written. Idempotent: an existing ``dest`` is left untouched.
Raises: ValueError: on multi-channel audio or an empty / out-of-range span. """ import numpy as np import soundfile # type: ignore[import-untyped] # bench extra, untyped
if dest.exists(): return int(soundfile.info(str(dest)).frames) audio: Any audio, rate_hz = soundfile.read(str(source), dtype="float64", always_2d=True) if audio.shape[1] != 1: raise ValueError(f"{source}: expected mono, got {audio.shape[1]} channels") mono = audio[:, 0] start = round(start_ms * rate_hz / 1000) stop = mono.shape[0] if end_ms is None else min(mono.shape[0], round(end_ms * rate_hz / 1000)) if not 0 <= start < stop: raise ValueError(f"{source}: empty span {start_ms}..{end_ms} ms ({mono.shape[0]} samples)") segment = mono[start:stop] if rate_hz != ASR_SAMPLE_RATE_HZ: segment = resample(segment, int(rate_hz), ASR_SAMPLE_RATE_HZ) peak = float(np.max(np.abs(segment))) if peak > 1.0: # resampling overshoot; never wrap around in PCM16 segment = segment / peak dest.parent.mkdir(parents=True, exist_ok=True) tmp = dest.with_name(f".{dest.name}.tmp.wav") soundfile.write(str(tmp), segment, ASR_SAMPLE_RATE_HZ, subtype="PCM_16") tmp.replace(dest) return int(segment.shape[0])
# ----------------------------------------------------------------------------- manifest
def _write_jsonl(path: Path, rows: Iterable[dict[str, object]]) -> None: atomic_write_text( path, "".join(json.dumps(r, ensure_ascii=False, sort_keys=True) + "\n" for r in rows), )
def load_manifest(workspace: Workspace) -> tuple[B1Plan, list[Clip]]: """Read the B1 manifest written by :func:`prepare_b1`.""" plan_obj = json.loads((workspace.manifests / "b1_plan.json").read_text(encoding="utf-8")) clips = [ clip_from_obj(json.loads(line)) for line in (workspace.manifests / "b1_clips.jsonl") .read_text(encoding="utf-8") .splitlines() if line.strip() ] return B1Plan(**plan_obj), clips
# ---------------------------------------------------------------------------- prepare
Opener = Callable[..., Any] # Any: urllib-compatible opener, see nida.bench.fetch
def _require_extracted(wanted: set[str], extracted: Sequence[Path], base: Path, what: str) -> None: """Fail loudly when an archive did not contain every member we selected.""" got = {p.relative_to(base).as_posix() for p in extracted} missing = sorted(wanted - got) if missing: raise FileNotFoundError( f"{what}: {len(missing)} selected members missing from the archive, e.g. {missing[:3]}" )
def _fleurs(plan: B1Plan, ws: Workspace, opener: Opener) -> tuple[Selection, Path]: base = ws.cache / "fleurs" tsv = fetch.download( fetch.hf_resolve_url( "google/fleurs", plan.fleurs_revision, "data/tr_tr/test.tsv", "dataset" ), base / "test.tsv", opener=opener, ) selection = select_fleurs( parse_fleurs_tsv(tsv.path.read_text(encoding="utf-8")), plan.n_fleurs, plan.seed ) wanted = {f"test/{c.file_id}" for c in selection.clips} extracted = fetch.stream_extract( fetch.hf_resolve_url( "google/fleurs", plan.fleurs_revision, "data/tr_tr/audio/test.tar.gz", "dataset" ), base, wanted.__contains__, opener=opener, ) _require_extracted(wanted, extracted, base, "FLEURS") return selection, base / "test"
def _mediaspeech(plan: B1Plan, ws: Workspace, opener: Opener) -> tuple[Selection, Path]: import soundfile
base = ws.cache / "mediaspeech" fetch.stream_extract( plan.mediaspeech_url, base, lambda name: name.startswith("TR/"), opener=opener ) audio_dir = base / "TR" items: list[MediaSpeechItem] = [] for txt in sorted(audio_dir.glob("*.txt")): flac = txt.with_suffix(".flac") if not flac.exists(): raise FileNotFoundError(f"MediaSpeech transcript without audio: {txt.name}") info = soundfile.info(str(flac)) items.append( MediaSpeechItem( txt.stem, txt.read_text(encoding="utf-8").strip(), round(1000 * info.frames / info.samplerate), ) ) if not items: raise FileNotFoundError(f"no MediaSpeech transcripts under {audio_dir}") return select_mediaspeech(items, plan.n_mediaspeech, plan.seed), audio_dir
def _yodas(plan: B1Plan, ws: Workspace, opener: Opener) -> tuple[Selection, Path]: base = ws.cache / "yodas" shards = yodas_shards(plan)
def get(kind: str, shard: str, ext: str) -> Path: name = f"data/tr000/{kind}/{shard}.{ext}" url = fetch.hf_resolve_url("espnet/yodas", plan.yodas_revision, name, "dataset") return fetch.download(url, base / kind / f"{shard}.{ext}", opener=opener).path
utts: list[YodasUtt] = [] seen: set[str] = set() for shard in shards: shard_utts = parse_yodas_listing( get("text", shard, "txt").read_text(encoding="utf-8"), get("duration", shard, "txt").read_text(encoding="utf-8"), shard, ) duplicates = seen & {u.utt_id for u in shard_utts} if duplicates: raise ValueError(f"YODAS utterance ids repeat across shards: {sorted(duplicates)[:3]}") seen |= {u.utt_id for u in shard_utts} utts.extend(shard_utts) if plan.yodas_spare < 0: raise ValueError(f"yodas_spare must be >= 0, got {plan.yodas_spare}") selection = select_yodas_pool(utts, plan.n_yodas_pool + plan.yodas_spare, plan.seed) for shard in shards: wanted = { f"{shard}/{c.file_id}.wav" for c in selection.clips if c.meta.get("shard") == shard } if not wanted: continue audio_url = fetch.hf_resolve_url( "espnet/yodas", plan.yodas_revision, f"data/tr000/audio/{shard}.tar.gz", "dataset" ) extracted = fetch.stream_extract( audio_url, base / "audio", wanted.__contains__, opener=opener ) _require_extracted(wanted, extracted, base / "audio", "YODAS") good: list[Clip] = [] bad: list[Quarantined] = [] for clip in selection.clips: problem = yodas_audio_problem(_source_file(clip, base / "audio"), clip.end_ms) if problem is None: good.append(clip) else: bad.append(Quarantined(clip.file_id, "select", problem[0], problem[1])) if len(good) < plan.n_yodas_pool: raise ValueError( f"only {len(good)} YODAS clips with usable audio, need {plan.n_yodas_pool} " f"({len(bad)} quarantined; raise yodas_spare)" ) chosen = random.Random(plan.seed).sample(good, plan.n_yodas_pool) log.info("YODAS pool: %d usable, %d broken audio, %d chosen", len(good), len(bad), len(chosen)) return ( Selection(tuple(sorted(chosen, key=lambda c: c.file_id)), (*selection.quarantined, *bad)), base / "audio", )
def yodas_audio_problem(path: Path, expected_ms: int) -> tuple[str, str] | None: """``(reason, details)`` if a YODAS wav is unreadable, empty or of the wrong length.""" import soundfile
try: info = soundfile.info(str(path)) except (RuntimeError, soundfile.LibsndfileError) as err: return "unreadable_audio", str(err) if info.frames == 0: return "empty_audio", f"0 frames at {info.samplerate} Hz" actual_ms = round(1000 * info.frames / info.samplerate) if abs(actual_ms - expected_ms) > YODAS_DURATION_TOLERANCE_MS: return "audio_duration_mismatch", f"{actual_ms} vs {expected_ms} ms" return None
def yodas_shards(plan: B1Plan) -> list[str]: """The plan's YODAS shards; each must be an 8-digit shard name, no repeats.""" shards = [s.strip() for s in plan.yodas_shards.split(",")] if not shards or any(re.fullmatch(r"[0-9]{8}", s) is None for s in shards): raise ValueError(f"invalid yodas_shards {plan.yodas_shards!r}") if len(set(shards)) != len(shards): raise ValueError(f"repeated YODAS shard in {plan.yodas_shards!r}") return shards
def _source_file(clip: Clip, audio_dir: Path) -> Path: if clip.source_id == "fleurs_tr": return audio_dir / clip.file_id if clip.source_id == "mediaspeech_tr": return audio_dir / f"{clip.file_id}.flac" if clip.source_id == "yodas_tr": shard = clip.meta.get("shard") if not shard: raise ValueError(f"YODAS clip {clip.clip_id} has no shard in meta") return audio_dir / shard / f"{clip.file_id}.wav" raise ValueError(f"unknown B1 source {clip.source_id}")
def prepare_b1( workspace: Workspace, plan: B1Plan | None = None, *, opener: Opener | None = None,) -> list[Clip]: """Fetch, select and convert all B1 clips; write the manifest once.
If a manifest already exists it must have been produced with the same plan (otherwise ``ValueError``); its clips are reused and only missing clip audio is regenerated (the cache may have been wiped by a new Colab session). """ plan = plan if plan is not None else B1Plan() plan_path = workspace.manifests / "b1_plan.json" if plan_path.exists(): existing_plan, existing = load_manifest(workspace) if existing_plan != plan: raise ValueError(f"existing B1 manifest was built with {existing_plan}, not {plan}") if all(clip_audio_path(workspace, c).exists() for c in existing): log.info("B1 manifest and clip audio present: %d clips", len(existing)) return existing use_opener = opener if opener is not None else fetch.default_opener selections: list[tuple[Selection, Path]] = [ _fleurs(plan, workspace, use_opener), _mediaspeech(plan, workspace, use_opener), _yodas(plan, workspace, use_opener), ] clips: list[Clip] = [] quarantined: list[Quarantined] = [] for selection, audio_dir in selections: quarantined.extend(selection.quarantined) for clip in selection.clips: write_clip_audio( _source_file(clip, audio_dir), clip_audio_path(workspace, clip), clip.start_ms, clip.end_ms, ) clips.append(clip) if plan_path.exists(): _, existing = load_manifest(workspace) if [c.clip_id for c in existing] != [c.clip_id for c in clips]: raise ValueError("re-derived B1 clips differ from the stored manifest") return existing _write_jsonl(workspace.manifests / "b1_clips.jsonl", (clip_to_obj(c) for c in clips)) _write_jsonl(workspace.manifests / "b1_quarantine.jsonl", (asdict(q) for q in quarantined)) atomic_write_text(plan_path, json.dumps(asdict(plan), indent=2, sort_keys=True) + "\n") log.info("B1 manifest written: %d clips, %d quarantined", len(clips), len(quarantined)) return clips
def layer_counts(clips: Sequence[Clip]) -> dict[str, int]: counts: dict[str, int] = {} for clip in clips: counts[clip.layer] = counts.get(clip.layer, 0) + 1 return counts123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325"""JSONL protocol between the benchmark orchestrator and model workers.
Each model family runs in its own virtual environment (dependency pins conflict, seedocs/benchmarks/B1-B2-tasarim.md §1.3), so the orchestrator and the workers only sharefiles. This module is the single definition of those files and must stay stdlib-only:it is imported inside every worker environment.
Layout for one worker invocation::
requests.jsonl one ``WorkRequest`` per line (written by the orchestrator) results.jsonl one ``WorkResult`` per line (appended by the worker) results.summary.json one ``WorkerSummary`` (written by the worker at the end)
Results are appended one line at a time and flushed + fsynced, so an interrupted workerleaves a valid prefix plus at most one partial trailing line. On restart the workercalls :func:`load_results` with ``repair=True``, which drops the partial line, andskips every request whose ``clip_id`` already has a result. Failed items are recordedwith an ``error`` and are never retried silently: callers decide via ``retry_failed``."""
from __future__ import annotations
import jsonimport osfrom collections.abc import Iterable, Iterator, Mappingfrom dataclasses import asdict, dataclass, fieldfrom pathlib import Pathfrom typing import IO
__all__ = [ "ProtocolError", "WorkRequest", "WorkResult", "WorkerSummary", "append_result", "drop_results", "load_requests", "load_results", "pending_requests", "read_summary", "write_requests", "write_summary",]
class ProtocolError(ValueError): """A protocol file is malformed or inconsistent."""
@dataclass(frozen=True)class WorkRequest: """One unit of work for a worker.
Attributes: clip_id: Content-addressed clip id; unique within a requests file. audio_path: Absolute path of the input audio file. params: Worker-specific string parameters (e.g. ``language``, ``context``, ``out_path``). Values are strings so the format stays trivially portable. """
clip_id: str audio_path: str params: Mapping[str, str] = field(default_factory=dict)
def to_json(self) -> str: return json.dumps( {"clip_id": self.clip_id, "audio_path": self.audio_path, "params": dict(self.params)}, ensure_ascii=False, sort_keys=True, )
@staticmethod def from_obj(obj: object, where: str) -> WorkRequest: if not isinstance(obj, dict): raise ProtocolError(f"{where}: request must be a JSON object") clip_id = obj.get("clip_id") audio_path = obj.get("audio_path") params = obj.get("params", {}) if not isinstance(clip_id, str) or not clip_id: raise ProtocolError(f"{where}: clip_id must be a non-empty string") if not isinstance(audio_path, str) or not audio_path: raise ProtocolError(f"{where}: audio_path must be a non-empty string") if not isinstance(params, dict) or not all( isinstance(k, str) and isinstance(v, str) for k, v in params.items() ): raise ProtocolError(f"{where}: params must map strings to strings") return WorkRequest(clip_id=clip_id, audio_path=audio_path, params=dict(params))
@dataclass(frozen=True)class WorkResult: """Outcome for one request: exactly one of ``output`` or ``error`` is set.
Attributes: clip_id: Id of the request this answers. output: Worker-specific JSON-compatible payload (e.g. ``{"text": ...}``). error: ``"<ExceptionType>: <message>"`` when the item failed. infer_seconds: Wall-clock inference time attributed to this item (batch time divided by batch size), excluding model loading. """
clip_id: str output: Mapping[str, object] | None error: str | None infer_seconds: float
def __post_init__(self) -> None: if (self.output is None) == (self.error is None): raise ProtocolError(f"{self.clip_id}: exactly one of output/error must be set") if self.infer_seconds < 0: raise ProtocolError(f"{self.clip_id}: infer_seconds must be >= 0")
@property def ok(self) -> bool: return self.error is None
def to_json(self) -> str: return json.dumps( { "clip_id": self.clip_id, "output": None if self.output is None else dict(self.output), "error": self.error, "infer_seconds": self.infer_seconds, }, ensure_ascii=False, sort_keys=True, )
@staticmethod def from_obj(obj: object, where: str) -> WorkResult: if not isinstance(obj, dict): raise ProtocolError(f"{where}: result must be a JSON object") clip_id = obj.get("clip_id") output = obj.get("output") error = obj.get("error") seconds = obj.get("infer_seconds") if not isinstance(clip_id, str) or not clip_id: raise ProtocolError(f"{where}: clip_id must be a non-empty string") if output is not None and not isinstance(output, dict): raise ProtocolError(f"{where}: output must be an object or null") if error is not None and not isinstance(error, str): raise ProtocolError(f"{where}: error must be a string or null") if isinstance(seconds, bool) or not isinstance(seconds, int | float): raise ProtocolError(f"{where}: infer_seconds must be a number") return WorkResult(clip_id=clip_id, output=output, error=error, infer_seconds=float(seconds))
@dataclass(frozen=True)class WorkerSummary: """Facts about one worker invocation, written once at the end."""
worker: str model_id: str revision: str load_seconds: float peak_vram_gb: float | None n_ok: int n_error: int started_at: str ended_at: str packages: Mapping[str, str] = field(default_factory=dict) extra: Mapping[str, str] = field(default_factory=dict)
def _fsync_line(handle: IO[str], line: str) -> None: handle.write(line + "\n") handle.flush() os.fsync(handle.fileno())
def write_requests(path: Path, requests: Iterable[WorkRequest]) -> int: """Write a requests file atomically and return the number of requests.
Raises: ProtocolError: on duplicate clip ids. """ from nida.utils.io import atomic_write_text # local import: workers never call this
seen: set[str] = set() lines: list[str] = [] for request in requests: if request.clip_id in seen: raise ProtocolError(f"duplicate clip_id in requests: {request.clip_id}") seen.add(request.clip_id) lines.append(request.to_json()) atomic_write_text(path, "".join(line + "\n" for line in lines)) return len(lines)
def _iter_json_lines(path: Path) -> Iterator[tuple[int, str]]: with path.open("r", encoding="utf-8") as handle: yield from enumerate(handle, start=1)
def load_requests(path: Path) -> list[WorkRequest]: """Read and validate a requests file (no partial lines tolerated).""" requests: list[WorkRequest] = [] seen: set[str] = set() for number, line in _iter_json_lines(path): where = f"{path}:{number}" if not line.endswith("\n"): raise ProtocolError(f"{where}: truncated request line") try: obj = json.loads(line) except json.JSONDecodeError as err: raise ProtocolError(f"{where}: invalid JSON ({err.msg})") from err request = WorkRequest.from_obj(obj, where) if request.clip_id in seen: raise ProtocolError(f"{where}: duplicate clip_id {request.clip_id}") seen.add(request.clip_id) requests.append(request) return requests
def load_results(path: Path, *, repair: bool = False) -> dict[str, WorkResult]: """Read a results file into ``{clip_id: result}``.
A missing file yields an empty mapping. Only the *last* line may be incomplete (an interrupted append): with ``repair=True`` it is removed from the file, otherwise a ``ProtocolError`` is raised. Any malformed line before the last one, and any duplicate clip id, is always an error. """ if not path.exists(): return {} raw = path.read_bytes() # Split at the last newline *in bytes*: an interrupted append may end in the middle of # a multi-byte UTF-8 character, so the trailing fragment must not be decoded. keep = raw.rfind(b"\n") + 1 # 0 when there is no complete line body, trailing = raw[:keep], raw[keep:] try: text = body.decode("utf-8") except UnicodeDecodeError as err: raise ProtocolError(f"{path}: complete lines are not valid UTF-8 ({err})") from err lines = text.split("\n")[:-1] if text else [] results: dict[str, WorkResult] = {} for number, line in enumerate(lines, start=1): where = f"{path}:{number}" try: obj = json.loads(line) except json.JSONDecodeError as err: raise ProtocolError(f"{where}: invalid JSON ({err.msg})") from err result = WorkResult.from_obj(obj, where) if result.clip_id in results: raise ProtocolError(f"{where}: duplicate result for {result.clip_id}") results[result.clip_id] = result if trailing: if not repair: raise ProtocolError(f"{path}: incomplete trailing line ({len(trailing)} bytes)") with path.open("r+b") as handle: handle.truncate(keep) handle.flush() os.fsync(handle.fileno()) return results
def pending_requests( requests: Iterable[WorkRequest], results: Mapping[str, WorkResult], *, retry_failed: bool = False,) -> list[WorkRequest]: """Requests that still need work, in input order.
Raises: ProtocolError: if ``results`` contains clip ids that are not in ``requests`` (the results file belongs to a different request set). """ request_list = list(requests) known = {r.clip_id for r in request_list} stray = sorted(set(results) - known) if stray: raise ProtocolError(f"results contain unknown clip ids, e.g. {stray[:3]}") pending: list[WorkRequest] = [] for request in request_list: done = results.get(request.clip_id) if done is None or (retry_failed and not done.ok): pending.append(request) return pending
def append_result(handle: IO[str], result: WorkResult) -> None: """Append one result line and fsync, so an interruption loses at most this line.""" _fsync_line(handle, result.to_json())
def write_summary(path: Path, summary: WorkerSummary) -> None: """Write the summary JSON next to the results (stdlib-only atomic replace).""" tmp = path.with_name(f".{path.name}.tmp") with tmp.open("w", encoding="utf-8") as handle: json.dump(asdict(summary), handle, ensure_ascii=False, indent=2, sort_keys=True) handle.write("\n") handle.flush() os.fsync(handle.fileno()) tmp.replace(path)
def read_summary(path: Path) -> WorkerSummary: """Read and validate a summary file.""" obj = json.loads(path.read_text(encoding="utf-8")) if not isinstance(obj, dict): raise ProtocolError(f"{path}: summary must be a JSON object") try: return WorkerSummary(**obj) except TypeError as err: raise ProtocolError(f"{path}: invalid summary fields ({err})") from err
def drop_results(path: Path, clip_ids: Iterable[str]) -> int: """Remove the given clip ids from a results file (atomic rewrite); returns how many.
Used when a result's side effect is gone (e.g. its output file was lost), so the item becomes pending again instead of being trusted. """ doomed = set(clip_ids) results = load_results(path, repair=True) kept = [r.to_json() + "\n" for cid, r in results.items() if cid not in doomed] removed = len(results) - len(kept) if removed: tmp = path.with_name(f".{path.name}.tmp") with tmp.open("w", encoding="utf-8") as handle: handle.writelines(kept) handle.flush() os.fsync(handle.fileno()) tmp.replace(path) return removed123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166"""Benchmarked systems and their pinned revisions (single source of truth).
Every system maps to a ``configs/sources.yaml`` id; :func:`require_approved` refuses torun anything whose source is not ``approved`` (golden rule 6). Revisions are theHugging Face commit SHAs checked on 2026-10-08; Omnilingual weights are addressed bymodel card through fairseq2 (no hub revision)."""
from __future__ import annotations
from collections.abc import Iterable, Mappingfrom dataclasses import dataclassfrom pathlib import Pathfrom types import MappingProxyTypefrom typing import Any
__all__ = [ "ASR_SYSTEMS", "DATA_PINS", "QUALITY_SYSTEM", "VAE_SYSTEMS", "SourceNotApprovedError", "System", "load_sources", "require_approved",]
@dataclass(frozen=True)class System: """One model under test.
Attributes: system_id: Short id used in file names and reports. source_id: Id in ``configs/sources.yaml``. worker: Worker module name in ``nida.bench.workers``. model_id: Hub id / model card passed to the worker. revision: Pinned revision (``""`` when the worker fetches by model card). batch_size: Worker batch size on an L4 (22 GB). """
system_id: str source_id: str worker: str model_id: str revision: str batch_size: int
def _index(systems: Iterable[System]) -> Mapping[str, System]: out: dict[str, System] = {} for system in systems: if system.system_id in out: raise ValueError(f"duplicate system id {system.system_id}") out[system.system_id] = system return MappingProxyType(out)
ASR_SYSTEMS: Mapping[str, System] = _index( ( System( "qwen3_asr_1_7b", "qwen3_asr_1_7b", "asr_qwen", "Qwen/Qwen3-ASR-1.7B", "7278e1e70fe206f11671096ffdd38061171dd6e5", 16, ), System( "qwen3_asr_0_6b", "qwen3_asr_0_6b", "asr_qwen", "Qwen/Qwen3-ASR-0.6B", "5eb144179a02acc5e5ba31e748d22b0cf3e303b0", 16, ), System("omniasr_llm_7b", "omniasr_llm_7b", "asr_omni", "omniASR_LLM_7B_v2", "", 4), System("omniasr_ctc_1b", "omniasr_ctc_1b", "asr_omni", "omniASR_CTC_1B_v2", "", 16), System( "whisper_large_v3", "whisper_large_v3", "asr_hf", "openai/whisper-large-v3", "06f233fe06e710322aca913c1bc4249a0d71fce1", 8, ), System( "buzzasr_turkish", "buzzasr_turkish", "asr_hf", "BuzzASR/turkish", "928b47596e31776dab9daf1e606ecf76234b9ecd", 8, ), ))
VAE_SYSTEMS: Mapping[str, System] = _index( ( System( "voxcpm2_audiovae_v2", "voxcpm2_audiovae_v2", "vae_voxcpm", "openbmb/VoxCPM2", "32279effe8c19989596f05d353d1447f51d9e915", 1, ), ))
QUALITY_SYSTEM = System( "audiobox_aesthetics", "audiobox_aesthetics", "quality_audiobox", "facebook/audiobox-aesthetics", "9b1dd8e5df9af7216e836a98974fe3b82c56ded6", 16,)
#: Pinned dataset revisions / URLs (checked 2026-10-08).DATA_PINS: Mapping[str, str] = MappingProxyType( { "fleurs_revision": "70bb2e84b976b7e960aa89f1c648e09c59f894dd", "yodas_revision": "52c5a1b9730a136bfd7c4513d4962c70d4e50530", "mediaspeech_url": "https://www.openslr.org/resources/108/TR.tgz", "expresso_url": "https://dl.fbaipublicfiles.com/textless_nlp/expresso/data/expresso.tar", })
class SourceNotApprovedError(RuntimeError): """A source is missing from the registry or not approved by the user."""
def load_sources(path: Path) -> dict[str, Mapping[str, Any]]: """Read ``configs/sources.yaml`` into ``{id: record}``.
Raises: ValueError: on a malformed file or duplicate ids. """ import yaml # type: ignore[import-untyped] # PyYAML: bench extra, no stubs installed
data: Any = yaml.safe_load(path.read_text(encoding="utf-8")) # Any: untyped YAML tree if not isinstance(data, dict) or not isinstance(data.get("sources"), list): raise ValueError(f"{path}: expected a mapping with a 'sources' list") records: dict[str, Mapping[str, Any]] = {} for record in data["sources"]: if not isinstance(record, dict) or not isinstance(record.get("id"), str): raise ValueError(f"{path}: every source needs a string 'id'") if record["id"] in records: raise ValueError(f"{path}: duplicate source id {record['id']}") records[record["id"]] = record return records
def require_approved(source_ids: Iterable[str], sources: Mapping[str, Mapping[str, Any]]) -> None: """Raise unless every id exists in the registry with ``status: approved``.""" problems: list[str] = [] for source_id in sorted(set(source_ids)): record = sources.get(source_id) if record is None: problems.append(f"{source_id}: not in sources.yaml") elif record.get("status") != "approved": problems.append(f"{source_id}: status is {record.get('status')!r}") if problems: raise SourceNotApprovedError("sources not approved: " + "; ".join(problems))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276"""Markdown rendering of B1 / B2 results (Turkish, for the user and the ADRs)."""
from __future__ import annotations
from collections.abc import Mapping, Sequence
__all__ = ["render_b1", "render_b2", "render_b2_panel"]
_B1_LAYER_TITLES = { "A": "A — temiz okuma (FLEURS)", "B": "B — medya (MediaSpeech)", "AB": "A+B", "C": "C — doğal + dolgu (YODAS, kullanıcı referansı)",}
def _fmt(value: object, digits: int = 3, percent: bool = False) -> str: if value is None: return "—" if isinstance(value, bool): return "evet" if value else "hayır" if isinstance(value, int): return str(value) if isinstance(value, float): return f"{100 * value:.1f}%" if percent else f"{value:.{digits}f}" return str(value)
def _pct(value: object) -> str: return _fmt(value, percent=True)
def _row(cells: Sequence[str]) -> str: return "| " + " | ".join(cells) + " |"
def _header(cells: Sequence[str]) -> list[str]: return [_row(cells), _row(["---"] * len(cells))]
def render_b1(scores: Mapping[str, object], choice: Mapping[str, object]) -> str: systems = scores["systems"] assert isinstance(systems, Mapping) lines = [ "# B1 — Türkçe ASR karşılaştırması", "", "Notlar: (1) `buzzasr_turkish` FLEURS ile eğitildi; A katmanında (FLEURS test) iyimser " "olabilir, bu yüzden karar kuralı ayrıca yalnız B katmanıyla da uygulanır. " "(2) Omnilingual CTC dil koşulu almaz (lang yok sayılır). (3) Başarısız öğeler boş " "hipotez (tamamı silme) sayılır; halüsinasyon oranına girmez. (4) RTF, sistemin kendi " "toplu iş (batch) boyutuyla ölçüldü; doğrudan hız karşılaştırması değildir.", "", ] if "n_c_reviewed" in scores: lines += [f"C katmanında incelenmiş (referanslı) klip: {scores['n_c_reviewed']}", ""] for layer, title in _B1_LAYER_TITLES.items(): if not all(layer in v for v in systems.values()): continue lines += [f"## {title}", ""] lines += _header( [ "Sistem", "n", "başarısız", "CER içerik", "WER içerik", "CER tam", "WER tam", "halüsinasyon", "dolgu geri çağırma", "dolgu geri çağırma (LOO)", "LOO payda", "dolgu kesinlik", "rakamlı hipotez", "RTF", ] ) for system_id in sorted(systems): r = systems[system_id][layer] lines.append( _row( [ system_id, _fmt(r["n"]), _fmt(r["n_failed"]), _pct(r["content_cer"]), _pct(r["content_wer"]), _pct(r["full_cer"]), _pct(r["full_wer"]), _pct(r["hallucination_rate"]), _pct(r["filler_recall"]), _pct(r.get("filler_recall_loo")), _fmt(r.get("filler_loo_ref_total")), _pct(r["filler_precision"]), _fmt(r.get("hyp_with_digits")), _fmt(r["rtf"]), ] ) ) lines.append("") workers = {k: v["_worker"] for k, v in systems.items() if "_worker" in v} if workers: lines += ["## Kaynak kullanımı", ""] lines += _header(["Sistem", "batch", "tepe VRAM (GB)", "yükleme (s)", "hata"]) for system_id, w in sorted(workers.items()): lines.append( _row( [ system_id, _fmt(w.get("batch_size")), _fmt(w.get("peak_vram_gb"), 1), _fmt(w.get("load_seconds"), 0), _fmt(w.get("n_error")), ] ) ) lines.append("") boot = scores.get("bootstrap_content_cer") if isinstance(boot, Mapping): for layer, rows in boot.items(): lines += [f"## Eşleştirilmiş bootstrap — içerik CER farkı ({layer}, a − b, %95 GA)", ""] lines += _header(["a", "b", "fark", "alt", "üst", "anlamlı mı"]) for r in rows: significant = r["low"] > 0 or r["high"] < 0 lines.append( _row( [ r["a"], r["b"], _pct(r["delta"]), _pct(r["low"]), _pct(r["high"]), "evet" if significant else "hayır", ] ) ) lines.append("") lines += ["## Önceden sabitlenmiş karar kuralına göre öneri", ""] if not choice.get("ready"): lines.append(f"Henüz uygulanamaz: {choice.get('reason')}.") else: qualified = choice.get("qualified_by_filler_recall") qualified_text = ", ".join(qualified) if isinstance(qualified, list) else "" lines += [ f"- Birincil: **{choice['primary']}**", f"- İkincil (farklı aile): **{choice['secondary'] or 'yok (başka aile yok)'}**", f"- Dolgu için ayrı yöntem gerekir mi: {_fmt(choice['needs_filler_method'])}", f"- Dolgu geri çağırma eşiğini geçenler: {qualified_text or '—'}", ] without = choice.get("without_fleurs") if isinstance(without, Mapping): changed = choice.get("pick_changes_without_fleurs") lines += [ "", "Aynı kural yalnız B katmanıyla (FLEURS hariç): " f"birincil **{without['primary']}**, " f"ikincil **{without['secondary'] or 'yok'}** — " f"seçim {'DEĞİŞİYOR' if changed else 'değişmiyor'}.", ] lines.append("") return "\n".join(lines)
def render_b2(scores: Mapping[str, object]) -> str: subsets = scores["subsets"] assert isinstance(subsets, Mapping) lines = [ "# B2 — VAE yeniden kurma (VoxCPM2 AudioVAE V2)", "", "Mel L1: log10 mel genliği farkı (düşük = iyi). HB: 8–24 kHz bandı. " "`band16k`: 48→16→48 kHz yeniden örnekleme taban çizgisi (8 kHz üstü yok).", "Audiobox 16 kHz'de çalışır; yüksek bant kalitesini ölçmez. HB LSD yalnız etkin " "karelerde (en yüksek karenin 40 dB altına kadar) ortalanır. ΔPQ/ΔCE eşleştirilmiş " "kliplerin farklarının ortalamasıdır (VAE − orijinal).", "", ] skipped = scores.get("skipped") if isinstance(skipped, Mapping) and skipped: lines += ["Atlanan: " + ", ".join(f"{k}={v}" for k, v in sorted(skipped.items())), ""] lines += _header( [ "Alt küme", "n", "puanlanan", "mel16 VAE", "mel48 VAE", "mel48 band16k", "HB LSD VAE (dB)", "HB LSD band16k (dB)", "HB enerji oranı VAE", "ΔPQ", "ΔCE", "CER orijinal", "CER VAE", "gecikme (ms)", ] ) for subset, row in subsets.items(): assert isinstance(row, Mapping) lines.append( _row( [ subset, _fmt(row["n"]), _fmt(row.get("n_scored")), _fmt(row.get("vae_mel16_l1")), _fmt(row.get("vae_mel48_l1")), _fmt(row.get("band16k_mel48_l1")), _fmt(row.get("vae_hb_lsd_db"), 1), _fmt(row.get("band16k_hb_lsd_db"), 1), _fmt(row.get("vae_hb_energy_ratio"), 2), _fmt(row.get("delta_PQ"), 2), _fmt(row.get("delta_CE"), 2), _pct(row.get("cer_orig")), _pct(row.get("cer_vae")), _fmt(row.get("vae_delay_ms"), 1), ] ) ) lines.append("") return "\n".join(lines)
def render_b2_panel(scores: Mapping[str, object]) -> str: """Un-blinded B2 listening-panel results with the pre-registered pass/fail per subset.""" subsets = scores["subsets"] rule = scores.get("rule") assert isinstance(subsets, Mapping) and isinstance(rule, Mapping) lines = [ "# B2 — Dinleme panosu (kör A/B, çözülmüş)", "", f"Kural: ifade korunma oranı ≥ {_pct(rule['min_preserved_share'])} " '("kısmen" korunmamış sayılır; tr hariç) ve kalite farkı (orijinal − VAE) ' f"≤ {_fmt(rule['max_quality_gap'], 1)}.", "", ] lines += _header( [ "Alt küme", "yanıt", "korunmuş", "kısmen", "kalite orijinal", "kalite VAE", "fark", "geçti", ] ) for subset, row in subsets.items(): assert isinstance(row, Mapping) lines.append( _row( [ subset, _fmt(row["n_answered"]), _pct(row["preserved_share"]), _pct(row["partial_share"]), _fmt(row["quality_orig"], 2), _fmt(row["quality_vae"], 2), _fmt(row["quality_gap"], 2), _fmt(row["passes"]), ] ) ) lines += ["", f"Tümü geçti mi: **{_fmt(scores.get('all_pass'))}**", ""] for key, label in ( ("missing_subsets", "Panoda hiç olmayan ifadeli alt kümeler"), ("unanswered", "Yanıtlanmamış satırlar (alt küme: adet)"), ("too_few_items", "En az adedin altında kalan alt kümeler"), ("excluded_missing_reconstruction", "Yeniden kurulamadığı için panoya alınmayan"), ): value = scores.get(key) if value: lines.append(f"- {label}: {value}") lines.append("") return "\n".join(lines)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464"""Text metrics for scoring ASR hypotheses against Turkish references (benchmark B1).
Pure standard-library implementation. The pipeline is:
1. :func:`normalize_for_scoring` turns a raw string into scoring tokens (NFC, Turkish lowercasing, punctuation removal, filler canonicalisation per tag-spec section 4).2. :func:`cer_counts` / :func:`wer_counts` return :class:`EditCounts` per utterance.3. :func:`corpus_rate` aggregates counts over a corpus (sum of errors over sum of reference lengths, *not* a mean of per-utterance rates).4. :func:`filler_score` measures filler recall / precision, and :func:`paired_bootstrap` gives a confidence interval for the difference between two systems."""
from __future__ import annotations
import mathimport randomimport unicodedatafrom collections import Counterfrom collections.abc import Hashable, Iterable, Sequencefrom dataclasses import dataclassfrom typing import TypeVar
from nida.text.fillers import FILLERS, canonical_fillerfrom nida.text.turkish import nfc, tr_lower
__all__ = [ "FILLERS", "BootstrapResult", "EditCounts", "FillerScore", "canonical_filler", "cer_counts", "corpus_rate", "edit_counts", "filler_counts", "filler_score", "has_digits", "is_hallucination", "normalize_english", "normalize_for_scoring", "paired_bootstrap", "strip_fillers", "wer_counts",]
T = TypeVar("T", bound=Hashable)
# Apostrophe-like characters that are deleted (not replaced by a space), so that# "Ankara'da" becomes "ankarada": U+0027, U+2019 and U+02BC (a modifier letter, category Lm)._APOSTROPHES: frozenset[str] = frozenset({"'", "\u2019", "\u02bc"})
# Circumflex letters are optional in modern Turkish spelling ("hala"/"hâlâ"); systems and# references use them inconsistently, so scoring folds them to the plain vowel._CIRCUMFLEX_FOLD = str.maketrans({"â": "a", "î": "i", "û": "u"})
# --------------------------------------------------------------------------------------# Normalisation and fillers# --------------------------------------------------------------------------------------
def normalize_for_scoring(text: str) -> list[str]: """Normalise ``text`` into scoring tokens.
Steps: NFC, Turkish lowercase, fold circumflexes (â/î/û → a/i/u), delete apostrophes (U+0027, U+2019, U+02BC), turn whitespace and every other punctuation (``P*``) or symbol (``S*``) character into a space, split on whitespace, and map each token through :func:`canonical_filler`. Letters and digits are kept as-is. The cleaned string is re-composed to NFC before splitting, because deleting a character can leave a base letter next to a combining mark.
Args: text: Raw reference or hypothesis text.
Returns: List of tokens (possibly empty).
Examples: >>> normalize_for_scoring("Ankara'da, ııı... Hımm!") ['ankarada', 'ıı', 'hmm'] """ chars: list[str] = [] for ch in tr_lower(text).translate(_CIRCUMFLEX_FOLD): if ch in _APOSTROPHES: continue if ch.isspace(): chars.append(" ") continue # Punctuation and symbols become word boundaries, never glue: "merhaba,dünya" must # score as two words, as in common ASR normalisers. if unicodedata.category(ch)[0] in ("P", "S"): chars.append(" ") else: chars.append(ch) tokens = nfc("".join(chars)).split() result: list[str] = [] for token in tokens: canonical = canonical_filler(token) result.append(token if canonical is None else canonical) return result
def strip_fillers(tokens: Sequence[str]) -> list[str]: """Return ``tokens`` without canonical fillers.
Tokens must come from :func:`normalize_for_scoring` (already canonical); membership in :data:`FILLERS` is tested literally. """ return [token for token in tokens if token not in FILLERS]
def has_digits(text: str) -> bool: """Return True if ``text`` (after NFC) contains any Unicode decimal digit.""" return any(ch.isdecimal() for ch in nfc(text))
# --------------------------------------------------------------------------------------# Edit distance# --------------------------------------------------------------------------------------
@dataclass(frozen=True)class EditCounts: """Substitution / deletion / insertion counts against a reference of ``ref_len`` units.
Attributes: substitutions: Reference units replaced by a different hypothesis unit. deletions: Reference units missing from the hypothesis. insertions: Extra hypothesis units not in the reference. ref_len: Number of reference units (characters or tokens). """
substitutions: int deletions: int insertions: int ref_len: int
def __post_init__(self) -> None: for name in ("substitutions", "deletions", "insertions", "ref_len"): value = getattr(self, name) if value < 0: raise ValueError(f"EditCounts.{name} must be >= 0, got {value}")
@property def errors(self) -> int: """Total number of edits (S + D + I).""" return self.substitutions + self.deletions + self.insertions
def rate(self) -> float | None: """Error rate ``errors / ref_len``; ``None`` when ``ref_len`` is 0.""" if self.ref_len == 0: return None return self.errors / self.ref_len
def __add__(self, other: object) -> EditCounts: """Component-wise sum, for corpus aggregation.""" if not isinstance(other, EditCounts): return NotImplemented return EditCounts( substitutions=self.substitutions + other.substitutions, deletions=self.deletions + other.deletions, insertions=self.insertions + other.insertions, ref_len=self.ref_len + other.ref_len, )
def edit_counts(ref: Sequence[T], hyp: Sequence[T]) -> EditCounts: """Levenshtein alignment with unit costs, returning the S/D/I split.
Time is O(len(ref) * len(hyp)); memory is O(len(hyp)) because each DP cell carries its own (cost, S, D, I) tuple instead of keeping the full matrix for backtracking.
Tie-breaking (deterministic): walking back from the end of both sequences, whenever several predecessors give the same minimal total cost the alignment prefers, in order, a substitution/match (diagonal), then a deletion (a reference unit with no hypothesis unit), then an insertion. Carrying counts forward along the per-cell choice is equivalent to that backtracking, because each cell's choice depends only on that cell.
Args: ref: Reference units (characters or tokens). hyp: Hypothesis units.
Returns: Counts with ``ref_len == len(ref)``. """ num_hyp = len(hyp) # Each cell: (cost, substitutions, deletions, insertions). prev: list[tuple[int, int, int, int]] = [(j, 0, 0, j) for j in range(num_hyp + 1)] for i in range(1, len(ref) + 1): ref_unit = ref[i - 1] row: list[tuple[int, int, int, int]] = [(i, 0, i, 0)] for j in range(1, num_hyp + 1): diag = prev[j - 1] up = prev[j] left = row[j - 1] diag_cost = diag[0] + (0 if ref_unit == hyp[j - 1] else 1) up_cost = up[0] + 1 left_cost = left[0] + 1 if diag_cost <= up_cost and diag_cost <= left_cost: mismatch = diag_cost - diag[0] row.append((diag_cost, diag[1] + mismatch, diag[2], diag[3])) elif up_cost <= left_cost: row.append((up_cost, up[1], up[2] + 1, up[3])) else: row.append((left_cost, left[1], left[2], left[3] + 1)) prev = row _, subs, dels, ins = prev[num_hyp] return EditCounts(substitutions=subs, deletions=dels, insertions=ins, ref_len=len(ref))
def cer_counts(ref_tokens: Sequence[str], hyp_tokens: Sequence[str]) -> EditCounts: """Character-level edit counts over ``" ".join(tokens)`` (spaces count as characters).""" return edit_counts(" ".join(ref_tokens), " ".join(hyp_tokens))
def wer_counts(ref_tokens: Sequence[str], hyp_tokens: Sequence[str]) -> EditCounts: """Token-level (word) edit counts.""" return edit_counts(ref_tokens, hyp_tokens)
def corpus_rate(counts: Iterable[EditCounts]) -> float | None: """Corpus-level error rate: ``sum(errors) / sum(ref_len)``.
Returns ``None`` if the total reference length is 0. """ total_errors = 0 total_ref = 0 for item in counts: total_errors += item.errors total_ref += item.ref_len if total_ref == 0: return None return total_errors / total_ref
# --------------------------------------------------------------------------------------# Fillers# --------------------------------------------------------------------------------------
def filler_counts(tokens: Sequence[str]) -> Counter[str]: """Count canonical fillers in ``tokens`` (tokens from :func:`normalize_for_scoring`).""" return Counter(token for token in tokens if token in FILLERS)
@dataclass(frozen=True)class FillerScore: """Filler matching totals.
Attributes: matched: Sum over utterances and types of ``min(n_ref, n_hyp)``. ref_total: Number of reference fillers. hyp_total: Number of hypothesis fillers. """
matched: int ref_total: int hyp_total: int
def recall(self) -> float | None: """``matched / ref_total``; ``None`` when there are no reference fillers.""" if self.ref_total == 0: return None return self.matched / self.ref_total
def precision(self) -> float | None: """``matched / hyp_total``; ``None`` when there are no hypothesis fillers.""" if self.hyp_total == 0: return None return self.matched / self.hyp_total
def filler_score( pairs: Iterable[tuple[Sequence[str], Sequence[str]]], filler: str | None = None) -> FillerScore: """Aggregate filler matches over ``(ref_tokens, hyp_tokens)`` pairs.
Per utterance, ``matched = sum over types of min(n_ref, n_hyp)``.
Args: pairs: Normalised (reference tokens, hypothesis tokens) per utterance. filler: If given, restrict scoring to this canonical filler type.
Raises: ValueError: If ``filler`` is not a member of :data:`FILLERS`. """ if filler is not None and filler not in FILLERS: raise ValueError(f"unknown filler {filler!r}; expected one of {sorted(FILLERS)}") matched = 0 ref_total = 0 hyp_total = 0 for ref_tokens, hyp_tokens in pairs: ref_counter = filler_counts(ref_tokens) hyp_counter = filler_counts(hyp_tokens) types = FILLERS if filler is None else frozenset({filler}) for kind in types: n_ref = ref_counter[kind] n_hyp = hyp_counter[kind] matched += min(n_ref, n_hyp) ref_total += n_ref hyp_total += n_hyp return FillerScore(matched=matched, ref_total=ref_total, hyp_total=hyp_total)
# --------------------------------------------------------------------------------------# Hallucination# --------------------------------------------------------------------------------------
def is_hallucination(ref_text: str, hyp_text: str, max_ratio: float = 1.5) -> bool: """Flag a hypothesis that is empty or far longer than the reference.
Lengths are character counts of ``" ".join(normalize_for_scoring(text))``.
Returns: True if the hypothesis is empty while the reference is not, or if ``len(hyp) > max_ratio * len(ref)`` (reference non-empty). If the reference is empty, True iff the hypothesis is non-empty.
Raises: ValueError: If ``max_ratio`` is not > 0. """ if not max_ratio > 0: raise ValueError(f"max_ratio must be > 0, got {max_ratio}") ref_len = len(" ".join(normalize_for_scoring(ref_text))) hyp_len = len(" ".join(normalize_for_scoring(hyp_text))) if ref_len == 0: return hyp_len > 0 if hyp_len == 0: return True return hyp_len > max_ratio * ref_len
# --------------------------------------------------------------------------------------# Paired bootstrap# --------------------------------------------------------------------------------------
@dataclass(frozen=True)class BootstrapResult: """Result of :func:`paired_bootstrap`.
Attributes: delta: ``corpus_rate(a) - corpus_rate(b)`` on the full set. low: Lower percentile bound of the resampled deltas. high: Upper percentile bound of the resampled deltas. n_resamples: Number of resamples requested. n_skipped: Resamples skipped because their total reference length was 0; the interval is computed from ``n_resamples - n_skipped`` resamples. """
delta: float low: float high: float n_resamples: int n_skipped: int = 0
def _quantile(sorted_values: Sequence[float], q: float) -> float: """Linear-interpolation quantile of an already sorted, non-empty sequence.""" position = q * (len(sorted_values) - 1) lower = math.floor(position) upper = math.ceil(position) if lower == upper: return sorted_values[lower] fraction = position - lower return sorted_values[lower] + (sorted_values[upper] - sorted_values[lower]) * fraction
def paired_bootstrap( a: Sequence[EditCounts], b: Sequence[EditCounts], n_resamples: int = 10000, seed: int = 0, confidence: float = 0.95,) -> BootstrapResult: """Paired bootstrap confidence interval for the corpus error-rate difference a - b.
Utterance indices are resampled with replacement (the same indices for both systems) using ``random.Random(seed)``; the interval is the percentile interval of the resampled ``corpus_rate(a) - corpus_rate(b)``.
Args: a: Per-utterance counts for system A. b: Per-utterance counts for system B, scored against the same references. n_resamples: Number of bootstrap resamples (>= 1). seed: Seed for the resampling RNG. confidence: Confidence level in (0, 1).
Raises: ValueError: On length mismatch, empty input, differing per-index ``ref_len``, invalid ``n_resamples`` / ``confidence``, zero total reference length, or if more than half of the resamples have zero total reference length. """ if len(a) != len(b): raise ValueError(f"a and b must have the same length, got {len(a)} and {len(b)}") if len(a) == 0: raise ValueError("a and b must be non-empty") for index, (item_a, item_b) in enumerate(zip(a, b, strict=True)): if item_a.ref_len != item_b.ref_len: raise ValueError( f"ref_len mismatch at index {index}: {item_a.ref_len} vs {item_b.ref_len}; " "both systems must be scored against the same references" ) if n_resamples < 1: raise ValueError(f"n_resamples must be >= 1, got {n_resamples}") if not 0.0 < confidence < 1.0: raise ValueError(f"confidence must be in (0, 1), got {confidence}") ref_lens = [item.ref_len for item in a] total_ref = sum(ref_lens) if total_ref == 0: raise ValueError("total reference length is 0; the error rate is undefined")
errors_a = [item.errors for item in a] errors_b = [item.errors for item in b] rate_a = corpus_rate(a) rate_b = corpus_rate(b) if rate_a is None or rate_b is None: # unreachable: total_ref > 0 and refs are equal raise ValueError("corpus rate undefined") delta = rate_a - rate_b
num_items = len(a) rng = random.Random(seed) population = range(num_items) deltas: list[float] = [] skipped = 0 for _ in range(n_resamples): indices = rng.choices(population, k=num_items) sample_ref = sum(ref_lens[i] for i in indices) if sample_ref == 0: skipped += 1 continue sample_a = sum(errors_a[i] for i in indices) sample_b = sum(errors_b[i] for i in indices) deltas.append((sample_a - sample_b) / sample_ref) if skipped * 2 > n_resamples: raise ValueError( f"{skipped} of {n_resamples} resamples had zero total reference length " "(more than half); the data has too few non-empty references to bootstrap" ) deltas.sort() alpha = (1.0 - confidence) / 2.0 return BootstrapResult( delta=delta, low=_quantile(deltas, alpha), high=_quantile(deltas, 1.0 - alpha), n_resamples=n_resamples, n_skipped=skipped, )
def normalize_english(text: str) -> list[str]: """Scoring tokens for *English* text (B2 Expresso clips).
NFC, ``str.casefold`` (correct for English; never use it on Turkish text), punctuation and symbols become spaces, apostrophes are deleted, split on whitespace. No filler canonicalisation: Turkish filler spellings ("of", "ah", "oh") are English words here. """ chars: list[str] = [] for ch in nfc(text).casefold(): if ch in _APOSTROPHES: continue chars.append(" " if ch.isspace() or unicodedata.category(ch)[0] in ("P", "S") else ch) return "".join(chars).split()1234567"""Model workers for Phase 0 benchmarks.
Each module here runs inside its own virtual environment (see ``nida.bench.envs``) and isstarted as ``python -m nida.bench.workers.<name> ...``. Workers depend only on thestandard library, ``nida.bench.protocol`` and their model library; heavy imports happeninside ``Adapter.load`` so this package stays importable everywhere."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103"""Whisper-family ASR via the transformers pipeline (whisper-large-v3, BuzzASR/turkish).
Decoding: beam search 5, no sampling, task ``transcribe`` with the language forced.
An optional per-request ``params["prompt"]`` is passed to Whisper as a decoder prompt
(``generate_kwargs["prompt_ids"]``, from ``tokenizer.get_prompt_ids``). With transformers
4.57 the tokenizer drops the prompt tokens when it decodes (``_strip_prompt``), so the pipeline
output normally holds the transcript only; a literal leading copy of the prompt is stripped
here as a safeguard and flagged with ``"prompt_stripped": true``. Without the parameter the
behaviour (and the output) is exactly the unprompted decoding, so earlier results stay
comparable.
"""
from __future__ import annotations
import importlib
from collections.abc import Mapping, Sequence
from typing import Any
from nida.bench.protocol import WorkRequest
from nida.bench.workers.common import language_for, load_mono_16k, snapshot
from nida.bench.workers.runner import Adapter, ModelRef, main_for
NUM_BEAMS = 5
PROMPT_PARAM = "prompt"
def prompt_for(batch: Sequence[WorkRequest]) -> str | None:
"""The prompt shared by every request of ``batch`` (``None`` = unprompted decoding).
Raises:
ValueError: if requests disagree (a prompt and no prompt count as different) or the
prompt is blank.
"""
prompts = {r.params.get(PROMPT_PARAM) for r in batch}
if len(prompts) != 1:
shown = sorted("<none>" if p is None else repr(p) for p in prompts)
raise ValueError(f"mixed prompts in one batch: {shown}")
prompt = next(iter(prompts))
if prompt is not None and not prompt.strip():
raise ValueError("params.prompt is blank; omit it for unprompted decoding")
return prompt
def strip_prompt_prefix(text: str, prompt: str) -> tuple[str, bool]:
"""Remove a literal leading copy of ``prompt`` from ``text``.
Returns:
``(text without the prompt, whether a prefix was removed)``.
"""
text, prompt = text.strip(), prompt.strip()
if text.startswith(prompt):
return text[len(prompt) :].strip(), True
return text, False
class WhisperAdapter(Adapter):
name = "asr_hf"
distributions = ("torch", "transformers", "huggingface-hub", "soundfile", "numpy")
def __init__(self) -> None:
self._pipe: Any = None # Any: transformers pipeline object (untyped here)
self._batch_size = 1
self._device = "cpu"
def load(self, model: ModelRef, device: str, batch_size: int) -> None:
torch = importlib.import_module("torch")
transformers = importlib.import_module("transformers")
self._batch_size = batch_size
self._device = device
self._pipe = transformers.pipeline(
"automatic-speech-recognition",
model=snapshot(model.model_id, model.revision),
torch_dtype=torch.float16,
device=device,
)
def run_batch(self, batch: Sequence[WorkRequest]) -> list[Mapping[str, object]]:
languages = {language_for(r, "whisper") for r in batch}
if len(languages) != 1:
raise ValueError(f"mixed languages in one batch: {sorted(languages)}")
prompt = prompt_for(batch)
generate_kwargs: dict[str, Any] = { # Any: tensors / strings handed to generate()
"language": languages.pop(),
"task": "transcribe",
"num_beams": NUM_BEAMS,
"do_sample": False,
}
if prompt is not None:
# rank-1 tensor (<|startofprev|> + prompt tokens); generate() repeats it per item
prompt_ids = self._pipe.tokenizer.get_prompt_ids(prompt, return_tensors="pt")
generate_kwargs["prompt_ids"] = prompt_ids.to(self._device)
inputs = [{"raw": load_mono_16k(r.audio_path), "sampling_rate": 16000} for r in batch]
outputs = self._pipe(inputs, batch_size=self._batch_size, generate_kwargs=generate_kwargs)
texts = [str(o["text"]).strip() for o in outputs]
if prompt is None:
return [{"text": text} for text in texts]
stripped = [strip_prompt_prefix(text, prompt) for text in texts]
return [{"text": text, "prompt_stripped": was} for text, was in stripped]
if __name__ == "__main__":
raise SystemExit(main_for(WhisperAdapter()))123456789101112131415161718192021222324252627282930313233343536373839404142"""Meta Omnilingual ASR via its inference pipeline (CTC and LLM model cards).
``model_id`` is the model card name (e.g. ``omniASR_LLM_7B_v2``); weights come fromMeta's CDN through fairseq2's asset store, so ``revision`` is recorded but unused.The pipeline rejects audio longer than 40 s; B1 clips are at most 25 s."""
from __future__ import annotations
import importlibfrom collections.abc import Mapping, Sequencefrom typing import Any
from nida.bench.protocol import WorkRequestfrom nida.bench.workers.common import language_forfrom nida.bench.workers.runner import Adapter, ModelRef, main_for
class OmniAdapter(Adapter): name = "asr_omni" distributions = ("torch", "omnilingual-asr", "fairseq2", "fairseq2n")
def __init__(self) -> None: self._pipeline: Any = None # Any: ASRInferencePipeline (untyped) self._batch_size = 1
def load(self, model: ModelRef, device: str, batch_size: int) -> None: module = importlib.import_module("omnilingual_asr.models.inference.pipeline") self._batch_size = batch_size self._pipeline = module.ASRInferencePipeline(model_card=model.model_id, device=device)
def run_batch(self, batch: Sequence[WorkRequest]) -> list[Mapping[str, object]]: texts = self._pipeline.transcribe( [r.audio_path for r in batch], lang=[language_for(r, "omni") for r in batch], batch_size=self._batch_size, ) return [{"text": str(t).strip()} for t in texts]
if __name__ == "__main__": raise SystemExit(main_for(OmniAdapter()))12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455"""Qwen3-ASR via the official ``qwen-asr`` package (transformers backend).
``params["context"]`` (optional) is passed as the system context; B1 uses no context bydefault and a separate, explicitly labelled run for the filler-context variant.``params["language"] == "auto"`` (all items of a batch) lets the model identify thelanguage itself (``language=None``, Qwen3-ASR README); the detected name is returned."""
from __future__ import annotations
import importlibfrom collections.abc import Mapping, Sequencefrom typing import Any
from nida.bench.protocol import WorkRequestfrom nida.bench.workers.common import language_for, snapshotfrom nida.bench.workers.runner import Adapter, ModelRef, main_for
MAX_NEW_TOKENS = 256#: ``params["language"]`` value requesting automatic language identification.AUTO_LANGUAGE = "auto"
class QwenAdapter(Adapter): name = "asr_qwen" distributions = ("torch", "qwen-asr", "transformers", "huggingface-hub")
def __init__(self) -> None: self._model: Any = None # Any: qwen_asr.Qwen3ASRModel (untyped)
def load(self, model: ModelRef, device: str, batch_size: int) -> None: torch = importlib.import_module("torch") qwen_asr = importlib.import_module("qwen_asr") self._model = qwen_asr.Qwen3ASRModel.from_pretrained( snapshot(model.model_id, model.revision), dtype=torch.bfloat16, device_map=device, max_inference_batch_size=batch_size, max_new_tokens=MAX_NEW_TOKENS, )
def run_batch(self, batch: Sequence[WorkRequest]) -> list[Mapping[str, object]]: auto = [r.params.get("language") == AUTO_LANGUAGE for r in batch] if any(auto) and not all(auto): raise ValueError("a batch mixes automatic and forced languages") results = self._model.transcribe( audio=[r.audio_path for r in batch], context=[r.params.get("context", "") for r in batch], language=None if all(auto) else [language_for(r, "qwen") for r in batch], ) return [{"text": str(res.text).strip(), "language": str(res.language)} for res in results]
if __name__ == "__main__": raise SystemExit(main_for(QwenAdapter()))1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374"""Small helpers shared by adapters (stdlib only)."""
from __future__ import annotations
import importlibfrom collections.abc import Mapping, Sequencefrom typing import Any
from nida.bench.protocol import WorkRequest
__all__ = ["HF_WEIGHT_PATTERNS", "LANGUAGES", "language_for", "load_mono_16k", "snapshot"]
#: Files needed to load a transformers checkpoint in safetensors form. Excludes duplicate#: formats (flax, pytorch .bin, fp32 shards) that some repos also ship.HF_WEIGHT_PATTERNS: tuple[str, ...] = ( "*.json", "*.txt", "*.model", "*.tiktoken", "model.safetensors", "model-*.safetensors",)
#: ISO 639-1 code → spelling each model family expects.LANGUAGES: Mapping[str, Mapping[str, str]] = { "tr": {"whisper": "turkish", "qwen": "Turkish", "omni": "tur_Latn"}, "en": {"whisper": "english", "qwen": "English", "omni": "eng_Latn"},}
def language_for(request: WorkRequest, family: str) -> str: """Model-specific language name for ``request.params["language"]`` (required).
Raises: ValueError: if the language parameter is missing or unsupported. """ code = request.params.get("language") if code is None: raise ValueError(f"{request.clip_id}: missing params.language") try: return LANGUAGES[code][family] except KeyError as err: raise ValueError(f"{request.clip_id}: unsupported language {code!r} for {family}") from err
def snapshot( model_id: str, revision: str, allow_patterns: Sequence[str] = HF_WEIGHT_PATTERNS) -> str: """Download (or reuse) a pinned Hugging Face snapshot and return its local path.
An empty ``revision`` is refused: benchmark runs must be reproducible. Only files matching ``allow_patterns`` are fetched. """ if not revision: raise ValueError(f"{model_id}: a pinned revision is required") hub = importlib.import_module("huggingface_hub") path: str = hub.snapshot_download( repo_id=model_id, revision=revision, allow_patterns=list(allow_patterns) ) return path
# Any: numpy is only present inside worker environments and has no stub here.def load_mono_16k(path: str) -> Any: """Read a 16 kHz mono file as float32 (the orchestrator guarantees this format).
Raises: ValueError: if the file is not 16 kHz mono. """ soundfile = importlib.import_module("soundfile") audio, sample_rate_hz = soundfile.read(path, dtype="float32", always_2d=False) if sample_rate_hz != 16000 or audio.ndim != 1: raise ValueError(f"{path}: expected 16 kHz mono, got {sample_rate_hz} Hz, {audio.ndim}-D") return audio12345678910111213141516171819202122232425262728293031323334353637383940414243444546"""Meta Audiobox Aesthetics quality scores (CE, CU, PC, PQ) for B2.
The checkpoint (``checkpoint.pt``, CC-BY-4.0) is taken from the pinned``facebook/audiobox-aesthetics`` revision and passed explicitly, so the package neverfetches an unpinned "latest" model. The predictor resamples input to 16 kHz."""
from __future__ import annotations
import importlibfrom collections.abc import Mapping, Sequencefrom typing import Any
from nida.bench.protocol import WorkRequestfrom nida.bench.workers.common import snapshotfrom nida.bench.workers.runner import Adapter, ModelRef, main_for
AXES = ("CE", "CU", "PC", "PQ")CHECKPOINT_FILE = "checkpoint.pt"
class AudioboxAdapter(Adapter): name = "quality_audiobox" distributions = ("torch", "torchaudio", "audiobox-aesthetics")
def __init__(self) -> None: self._predictor: Any = None # Any: audiobox predictor (untyped)
def load(self, model: ModelRef, device: str, batch_size: int) -> None: infer = importlib.import_module("audiobox_aesthetics.infer") local = snapshot(model.model_id, model.revision, (CHECKPOINT_FILE,)) self._predictor = infer.initialize_predictor(ckpt=f"{local}/{CHECKPOINT_FILE}")
def run_batch(self, batch: Sequence[WorkRequest]) -> list[Mapping[str, object]]: scores = self._predictor.forward([{"path": r.audio_path} for r in batch]) outputs: list[Mapping[str, object]] = [] for score in scores: missing = [axis for axis in AXES if axis not in score] if missing: raise ValueError(f"audiobox output lacks axes {missing}: {score}") outputs.append({axis: float(score[axis]) for axis in AXES}) return outputs
if __name__ == "__main__": raise SystemExit(main_for(AudioboxAdapter()))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340"""Generic worker loop shared by every model adapter.
The loop is model-agnostic: it reads the requests file, resumes from the results file,calls ``Adapter.run_batch`` in fixed-size batches, and appends one fsynced result line perrequest. A failing batch is retried item by item so a single bad clip cannot take itsneighbours down; every failure is recorded with its exception type and message (neverdropped) and counted in the summary. Model loading failures are fatal: they propagate andthe process exits non-zero."""
from __future__ import annotations
import abcimport argparseimport hashlibimport importlibimport importlib.metadataimport jsonimport loggingimport sysimport timeimport tracebackfrom collections.abc import Mapping, Sequencefrom dataclasses import dataclass, replacefrom datetime import UTC, datetimefrom pathlib import Pathfrom typing import ClassVar
from nida.bench.protocol import ( ProtocolError, WorkerSummary, WorkRequest, WorkResult, append_result, drop_results, load_requests, load_results, pending_requests, read_summary, write_summary,)
__all__ = [ "MAX_CONSECUTIVE_FAILURES", "Adapter", "ModelRef", "TooManyFailuresError", "WorkerOptions", "main_for", "run_worker",]
log = logging.getLogger(__name__)
#: Abort when this many items in a row fail: the model/device is broken, not the clips.MAX_CONSECUTIVE_FAILURES = 10#: Progress is logged when this many more items are done (and at the end).PROGRESS_EVERY = 200#: When the *same* failure run (same clip ids) aborts more than this many times in a row,#: it is evidently repeatable rather than transient and is kept as recorded failures so a#: rerun can move past it. Unrelated aborts never accumulate (see ``_abort_count``).MAX_ABORTS_BEFORE_KEEPING = 2
class TooManyFailuresError(RuntimeError): """Consecutive item failures suggest a broken model or device (e.g. CUDA context)."""
@dataclass(frozen=True)class ModelRef: """Which model to load.
Attributes: model_id: Hub id, model card name or local path, interpreted by the adapter. revision: Pinned revision (commit SHA) or ``""`` when the source has none. """
model_id: str revision: str
class Adapter(abc.ABC): """One model family. Subclasses keep heavy imports inside their methods."""
name: ClassVar[str] #: Distribution names whose installed versions are recorded in the summary. distributions: ClassVar[tuple[str, ...]] = ()
@abc.abstractmethod def load(self, model: ModelRef, device: str, batch_size: int) -> None: """Load the model onto ``device``. Exceptions here abort the worker."""
@abc.abstractmethod def run_batch(self, batch: Sequence[WorkRequest]) -> list[Mapping[str, object]]: """Return one JSON-compatible output mapping per request, in the same order."""
def peak_vram_gb(self) -> float | None: """Peak CUDA memory allocated by this process, if torch with CUDA is present.""" try: torch = importlib.import_module("torch") except ImportError: return None if not torch.cuda.is_available(): return None return round(float(torch.cuda.max_memory_allocated()) / 1024**3, 2)
@dataclass(frozen=True)class WorkerOptions: requests: Path results: Path summary: Path model: ModelRef device: str batch_size: int retry_failed: bool
def _now() -> str: return datetime.now(UTC).isoformat(timespec="seconds")
def _describe(err: BaseException) -> str: return f"{type(err).__name__}: {err}"
def _package_versions(names: Sequence[str]) -> dict[str, str]: versions: dict[str, str] = {} for name in names: try: versions[name] = importlib.metadata.version(name) except importlib.metadata.PackageNotFoundError: versions[name] = "not-installed" return versions
def _abort_counter_path(results: Path) -> Path: return results.with_name(results.name + ".aborts.json")
def _abort_count(results: Path, failure_ids: Sequence[str]) -> int: """Record an abort and return how often *this* failure run has aborted in a row.
The counter stores a signature of the failing clip ids: a different failure run restarts at 1, and :func:`_clear_abort_count` removes it after any run that finishes without aborting, so transient incidents in different sessions never add up. """ signature = hashlib.sha1("\n".join(sorted(failure_ids)).encode("utf-8")).hexdigest() path = _abort_counter_path(results) count = 1 if path.exists(): try: previous = json.loads(path.read_text(encoding="utf-8")) if previous.get("signature") == signature: count = int(previous.get("count", 0)) + 1 except (ValueError, AttributeError, TypeError) as err: # A damaged counter must not wedge the worker; recount from this abort. log.warning("ignoring unreadable abort counter %s (%s); restarting at 1", path, err) tmp = path.with_name(f".{path.name}.tmp") tmp.write_text(json.dumps({"signature": signature, "count": count}), encoding="utf-8") tmp.replace(path) return count
def _clear_abort_count(results: Path) -> None: _abort_counter_path(results).unlink(missing_ok=True)
def _drop_failed(path: Path) -> None: """Rewrite the results file without failed entries (for ``--retry-failed``).""" results = load_results(path, repair=True) kept = [r.to_json() + "\n" for r in results.values() if r.ok] tmp = path.with_name(f".{path.name}.tmp") tmp.write_text("".join(kept), encoding="utf-8") tmp.replace(path)
def _validated_outputs(batch: Sequence[WorkRequest], outputs: object) -> list[Mapping[str, object]]: if not isinstance(outputs, list) or len(outputs) != len(batch): got = len(outputs) if isinstance(outputs, list) else type(outputs).__name__ raise ProtocolError(f"adapter returned {got} outputs for a batch of {len(batch)}") for output in outputs: if not isinstance(output, Mapping): raise ProtocolError(f"adapter output must be a mapping, got {type(output).__name__}") return outputs
def _run_one_batch(adapter: Adapter, batch: Sequence[WorkRequest]) -> list[WorkResult]: started = time.perf_counter() try: outputs = _validated_outputs(batch, adapter.run_batch(batch)) except Exception as err: # noqa: BLE001 - recorded per item below, never swallowed if len(batch) == 1: log.warning("item %s failed: %s", batch[0].clip_id, _describe(err)) return [ WorkResult( clip_id=batch[0].clip_id, output=None, error=_describe(err), infer_seconds=time.perf_counter() - started, ) ] log.warning("batch of %d failed (%s); retrying items one by one", len(batch), err) results: list[WorkResult] = [] for request in batch: results.extend(_run_one_batch(adapter, [request])) return results per_item = (time.perf_counter() - started) / len(batch) return [ WorkResult(clip_id=r.clip_id, output=dict(o), error=None, infer_seconds=per_item) for r, o in zip(batch, outputs, strict=True) ]
def run_worker(adapter: Adapter, options: WorkerOptions) -> WorkerSummary: """Process every pending request and write the summary. Returns the summary.""" if options.batch_size < 1: raise ValueError(f"batch_size must be >= 1, got {options.batch_size}") started_at = _now() requests = load_requests(options.requests) if options.retry_failed and options.results.exists(): _drop_failed(options.results) done = load_results(options.results, repair=True) pending = pending_requests(requests, done) log.info( "%s: %d requests, %d already done, %d pending", adapter.name, len(requests), len(done), len(pending), )
previous = read_summary(options.summary) if options.summary.exists() else None load_seconds = 0.0 if pending: load_start = time.perf_counter() adapter.load(options.model, options.device, options.batch_size) load_seconds = time.perf_counter() - load_start options.results.parent.mkdir(parents=True, exist_ok=True) failure_run: list[WorkResult] = [] aborted = False with options.results.open("a", encoding="utf-8") as handle: for start in range(0, len(pending), options.batch_size): batch = pending[start : start + options.batch_size] for result in _run_one_batch(adapter, batch): append_result(handle, result) failure_run = [] if result.ok else [*failure_run, result] if len(failure_run) >= MAX_CONSECUTIVE_FAILURES: aborted = True break if aborted: break finished = start + len(batch) if ( finished == len(pending) or finished // PROGRESS_EVERY != start // PROGRESS_EVERY ): log.info("%s: %d/%d", adapter.name, finished, len(pending)) if aborted: aborts = _abort_count(options.results, [r.clip_id for r in failure_run]) if aborts <= MAX_ABORTS_BEFORE_KEEPING: # Most likely infrastructure (e.g. a broken CUDA context), not bad clips: make # them pending again so a plain rerun retries them instead of scoring them as # empty hypotheses. drop_results(options.results, [r.clip_id for r in failure_run]) outcome = "results removed, they will be retried" else: outcome = ( f"same failure run aborted {aborts} times: kept as recorded failures so " "the next run moves on; use --retry-failed to try them again" ) raise TooManyFailuresError( f"{adapter.name}: {len(failure_run)} consecutive failures ({outcome}), " f"last: {failure_run[-1].error}" )
_clear_abort_count(options.results) # finished without aborting final = load_results(options.results) n_ok = sum(1 for r in final.values() if r.ok) if not pending and previous is not None: # No-op resume: keep the measurements of the invocation that did the work. summary = replace(previous, n_ok=n_ok, n_error=len(final) - n_ok) else: peaks = [v for v in (adapter.peak_vram_gb(), previous and previous.peak_vram_gb) if v] invocations = int(previous.extra.get("invocations", "1")) + 1 if previous else 1 summary = WorkerSummary( worker=adapter.name, model_id=options.model.model_id, revision=options.model.revision, load_seconds=round(load_seconds, 3), peak_vram_gb=max(peaks) if peaks else None, n_ok=n_ok, n_error=len(final) - n_ok, started_at=previous.started_at if previous else started_at, ended_at=_now(), packages=_package_versions(adapter.distributions), extra={ "python": sys.version.split()[0], "device": options.device, "invocations": str(invocations), }, ) write_summary(options.summary, summary) return summary
def _parse(argv: Sequence[str] | None) -> WorkerOptions: parser = argparse.ArgumentParser(description="Run a Nida benchmark worker.") parser.add_argument("--requests", type=Path, required=True) parser.add_argument("--results", type=Path, required=True) parser.add_argument("--summary", type=Path, default=None) parser.add_argument("--model-id", required=True) parser.add_argument("--revision", default="") parser.add_argument("--device", default="cuda") parser.add_argument("--batch-size", type=int, default=8) parser.add_argument("--retry-failed", action="store_true") args = parser.parse_args(argv) summary = args.summary or args.results.with_name(args.results.stem + ".summary.json") return WorkerOptions( requests=args.requests, results=args.results, summary=summary, model=ModelRef(model_id=args.model_id, revision=args.revision), device=args.device, batch_size=args.batch_size, retry_failed=args.retry_failed, )
def main_for(adapter: Adapter, argv: Sequence[str] | None = None) -> int: """CLI entry point used by each worker module's ``__main__`` block.""" logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") options = _parse(argv) try: summary = run_worker(adapter, options) except (ProtocolError, OSError, ValueError, TooManyFailuresError): traceback.print_exc() return 2 print(f"{adapter.name}: ok={summary.n_ok} error={summary.n_error}") return 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146"""VoxCPM2 AudioVAE V2 encode → decode round trip (benchmark B2).
Only the VAE is used. Its model code is a single file in the Apache-2.0 VoxCPM repositorythat needs just torch, numpy and pydantic, so it is fetched at a pinned commit andverified by SHA-256 instead of installing the ``voxcpm`` package (whose dependenciesinclude gradio, funasr and modelscope). Weights and config come from the pinned``openbmb/VoxCPM2`` Hugging Face revision.
Per request: read audio (mono, any rate) → resample to the VAE input rate (16 kHz, asVoxCPM does with ``librosa.load(sr=16000)``) → ``encode`` (posterior mean, deterministic)→ ``decode`` at the default output rate (48 kHz) → trim to ``ceil(n_16k * 48000/16000)``samples → write ``params["out_path"]`` as 32-bit float WAV."""
from __future__ import annotations
import hashlibimport importlibimport importlib.utilimport jsonimport mathimport urllib.requestfrom collections.abc import Mapping, Sequencefrom pathlib import Pathfrom typing import Any
from nida.bench.protocol import WorkRequestfrom nida.bench.workers.common import snapshotfrom nida.bench.workers.runner import Adapter, ModelRef, main_for
VOXCPM_COMMIT = "9d95dd132ad4c54b42ed50561ff878b18e4c75de"VAE_SOURCE_URL = ( "https://raw.githubusercontent.com/OpenBMB/VoxCPM/" f"{VOXCPM_COMMIT}/src/voxcpm/modules/audiovae/audio_vae_v2.py")VAE_SOURCE_SHA256 = "2efdff1708d8ec1471624aae6f232d0f933de26b788b6901c434246847e2d3a8"WEIGHTS_FILE = "audiovae.pth"CONFIG_FILE = "config.json"
def _sha256(data: bytes) -> str: return hashlib.sha256(data).hexdigest()
def fetch_vae_source(cache_dir: Path) -> Path: """Download the pinned ``audio_vae_v2.py`` once and verify its SHA-256.
Raises: ValueError: if the downloaded or cached file does not match the pinned hash. """ path = cache_dir / f"audio_vae_v2-{VOXCPM_COMMIT[:12]}.py" if not path.exists(): with urllib.request.urlopen(VAE_SOURCE_URL, timeout=60) as response: data = response.read() if _sha256(data) != VAE_SOURCE_SHA256: raise ValueError(f"audio_vae_v2.py hash mismatch: {_sha256(data)}") cache_dir.mkdir(parents=True, exist_ok=True) tmp = path.with_suffix(".tmp") tmp.write_bytes(data) tmp.replace(path) if _sha256(path.read_bytes()) != VAE_SOURCE_SHA256: raise ValueError(f"{path}: cached file does not match the pinned hash") return path
def _import_file(path: Path, module_name: str) -> Any: # Any: dynamically loaded module spec = importlib.util.spec_from_file_location(module_name, path) if spec is None or spec.loader is None: raise ImportError(f"cannot import {path}") module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module
class VoxCPMVAEAdapter(Adapter): name = "vae_voxcpm" distributions = ("torch", "torchaudio", "numpy", "pydantic", "soundfile", "huggingface-hub")
def __init__(self, cache_dir: Path | None = None) -> None: self._cache_dir = cache_dir or Path.home() / ".cache" / "nida" self._vae: Any = None # Any: AudioVAE V2 torch module self._torch: Any = None self._device = "cpu"
def load(self, model: ModelRef, device: str, batch_size: int) -> None: torch = importlib.import_module("torch") source = _import_file(fetch_vae_source(self._cache_dir), "nida_audio_vae_v2") local = Path(snapshot(model.model_id, model.revision, (CONFIG_FILE, WEIGHTS_FILE))) config = json.loads((local / CONFIG_FILE).read_text(encoding="utf-8")) vae = source.AudioVAE(config=source.AudioVAEConfig(**config["audio_vae_config"])) checkpoint = torch.load(local / WEIGHTS_FILE, map_location="cpu", weights_only=True) state = checkpoint.get("state_dict", checkpoint) incompatible = vae.load_state_dict(state, strict=False) if incompatible.missing_keys or incompatible.unexpected_keys: raise ValueError( f"state dict mismatch: missing={incompatible.missing_keys[:5]} " f"unexpected={incompatible.unexpected_keys[:5]}" ) self._vae = vae.to(device=device, dtype=torch.float32).eval() self._torch = torch self._device = device
def _round_trip(self, request: WorkRequest) -> Mapping[str, object]: out_path = request.params.get("out_path") if not out_path: raise ValueError(f"{request.clip_id}: missing params.out_path") torch = self._torch soundfile = importlib.import_module("soundfile") functional = importlib.import_module("torchaudio.functional") audio, source_rate_hz = soundfile.read(request.audio_path, dtype="float32") if audio.ndim != 1: raise ValueError(f"{request.clip_id}: expected mono audio, got shape {audio.shape}") in_rate_hz = int(self._vae.sample_rate) out_rate_hz = int(self._vae.out_sample_rate) wave = torch.from_numpy(audio).unsqueeze(0) if source_rate_hz != in_rate_hz: wave = functional.resample(wave, source_rate_hz, in_rate_hz) num_in_samples = int(wave.shape[-1]) with torch.inference_mode(): latents = self._vae.encode(wave.to(self._device), in_rate_hz) # (1, D, frames) decoded = self._vae.decode(latents) # (1, 1, samples) at out_rate_hz num_out_samples = math.ceil(num_in_samples * out_rate_hz / in_rate_hz) out = decoded.reshape(-1)[:num_out_samples].float().cpu().numpy() if out.shape[0] < num_out_samples: raise ValueError(f"{request.clip_id}: decoder returned {out.shape[0]} samples") target = Path(out_path) target.parent.mkdir(parents=True, exist_ok=True) tmp = target.with_name(f".{target.name}.tmp.wav") # never leave a partial output soundfile.write(str(tmp), out, out_rate_hz, subtype="FLOAT") tmp.replace(target) return { "out_path": out_path, "out_sample_rate_hz": out_rate_hz, "num_latent_frames": int(latents.shape[-1]), "latent_dim": int(latents.shape[1]), "latent_mean": float(latents.mean()), "latent_std": float(latents.std()), }
def run_batch(self, batch: Sequence[WorkRequest]) -> list[Mapping[str, object]]: # Clips have different lengths and the VAE is cheap: process one at a time. return [self._round_trip(r) for r in batch]
if __name__ == "__main__": raise SystemExit(main_for(VoxCPMVAEAdapter()))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929"""Nida command-line interface.
Every subcommand accepts the common run flags (``--runs-root``, ``--run-id``,
``--git-commit``) so the Colab runner can call any command the same way.
"""
from __future__ import annotations
import argparse
import json
import logging
import sys
from collections.abc import Sequence
from pathlib import Path
from nida.envreport import collect_env, summarize_env
from nida.runs import RunContext
from nida.utils.io import atomic_write_json, atomic_write_text
__all__ = ["main"]
# src/nida/cli.py → repository root (editable installs, as on Colab).
_REPO_DIR = Path(__file__).resolve().parents[2]
def _common_parser() -> argparse.ArgumentParser:
common = argparse.ArgumentParser(add_help=False)
common.add_argument(
"--runs-root",
type=Path,
default=None,
help="Directory holding run folders. If omitted, nothing is written to disk.",
)
common.add_argument("--run-id", default=None, help="Explicit run id (default: generated).")
common.add_argument("--git-commit", default=None, help="Commit SHA of the code being run.")
return common
def _positive_int(text: str) -> int:
"""argparse type: an integer >= 1 (clear error otherwise)."""
try:
value = int(text)
except ValueError:
raise argparse.ArgumentTypeError(f"expected an integer >= 1, got {text!r}") from None
if value < 1:
raise argparse.ArgumentTypeError(f"expected an integer >= 1, got {value}")
return value
def _build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(prog="nida", description="Nida expressive Turkish TTS.")
sub = parser.add_subparsers(dest="command", required=True)
sub.add_parser(
"env-report",
parents=[_common_parser()],
help="Print (and optionally record) Python/torch/GPU facts.",
)
bench = sub.add_parser(
"bench-phase0",
parents=[_common_parser()],
help="Phase 0 benchmarks B1 (ASR) and B2 (VAE); see docs/benchmarks/B1-B2-tasarim.md.",
)
bench.add_argument("--stage", default="all", help="A stage name or 'all'.")
bench.add_argument(
"--workspace",
type=Path,
default=None,
help="Durable benchmark directory (default: <runs-root>/../bench/phase0).",
)
bench.add_argument("--cache", type=Path, default=Path("/content/nida_cache"))
bench.add_argument("--envs", type=Path, default=Path("/content/nida_envs"))
bench.add_argument(
"--repo", type=Path, default=_REPO_DIR, help="Repository root (for configs and envs)."
)
bench.add_argument("--c-results", type=Path, default=None, help="B1 layer-C panel results CSV.")
bench.add_argument(
"--b2-panel-results", type=Path, default=None, help="B2 listening panel results CSV."
)
bench.add_argument(
"--retry-failed", action="store_true", help="Retry worker items that failed before."
)
pilot = sub.add_parser(
"data-pilot",
parents=[_common_parser()],
help="Phase 1 data pipeline pilot on YODAS (docs/plans/faz-1.md).",
)
pilot.add_argument("--stage", default="all", help="A stage name or 'all'.")
pilot.add_argument(
"--root",
type=Path,
default=None,
help="Durable pilot directory (default: <runs-root>/../data/pilot).",
)
pilot.add_argument("--cache", type=Path, default=Path("/content/nida_cache/pilot"))
pilot.add_argument("--envs", type=Path, default=Path("/content/nida_envs"))
pilot.add_argument("--repo", type=Path, default=_REPO_DIR)
pilot.add_argument(
"--subset",
choices=("tr000", "tr100"), # keep in sync with nida.data.pilot.YODAS_SUBSETS
default="tr000",
help=(
"YODAS Turkish subset: tr000 (manual subtitles, 64 shards) or tr100 (automatic "
"subtitles, 430 shards; videos that occur in tr000 are dropped)."
),
)
pilot.add_argument(
"--shards", default="00000002", help="Comma-separated shards of the chosen subset."
)
pilot.add_argument("--max-hours", type=float, default=10.0)
pilot.add_argument("--asr-primary", default="omniasr_llm_7b")
pilot.add_argument("--asr-secondary", default="qwen3_asr_1_7b")
pilot.add_argument("--retry-failed", action="store_true")
pilot.add_argument(
"--asr-batch-size",
type=int,
default=None,
help="Override the ASR workers' batch size (bench sizes fit a 22 GB L4).",
)
pilot.add_argument(
"--parallel-workers",
type=_positive_int,
default=1,
help=(
"Run up to N of the independent GPU worker stages (sed, diar, both ASR systems, "
"ctc, emotion) at the same time in 'all' (default 1 = one after another)."
),
)
ears = sub.add_parser(
"data-ears",
parents=[_common_parser()],
help="EARS -> latent dataset (ADR-0007; docs/03-data-pipeline.md).",
)
ears.add_argument(
"--root",
type=Path,
default=None,
help="Durable directory (default: <runs-root>/../data/ears); dataset is <root>/dataset.",
)
ears.add_argument(
"--speakers", default="all", help="Comma-separated speakers (p001,p002) or 'all'."
)
ears.add_argument("--cache", type=Path, default=Path("/content/nida_cache/ears"))
ears.add_argument("--envs", type=Path, default=Path("/content/nida_envs"))
ears.add_argument("--repo", type=Path, default=_REPO_DIR)
ears.add_argument("--seed", type=int, default=20261009, help="Speaker split seed.")
ears.add_argument("--config-dir", type=Path, default=None, help="Default: <repo>/configs/data.")
imp = sub.add_parser(
"data-import",
parents=[_common_parser()],
help="External transcribed corpus -> latent dataset (nida.data.importer).",
)
imp.add_argument(
"--source",
# keep in sync with nida.data.importer.sources.SOURCES
choices=("alania", "tr_full", "wavdir", "issai_tsc", "mediaspeech_tr", "common_voice_tr"),
required=True,
help=(
"alania (HF parquet), tr_full (HF data.jsonl + wavs), wavdir (--source-dir), "
"issai_tsc (HF tar.gz), mediaspeech_tr (OpenSLR TR.tgz) or common_voice_tr "
"(--source-dir: a Common Voice release folder or tarball you downloaded)."
),
)
imp.add_argument(
"--stage",
default="all",
help="select | audio | latents | ctc | timings | dataset | report | all.",
)
imp.add_argument(
"--root",
type=Path,
default=None,
help="Durable directory (default: <runs-root>/../data/import-<source>).",
)
imp.add_argument(
"--cache",
type=Path,
default=None,
help="Local scratch (default: /content/nida_cache/import/<root name>).",
)
imp.add_argument("--envs", type=Path, default=Path("/content/nida_envs"))
imp.add_argument("--repo", type=Path, default=_REPO_DIR)
imp.add_argument("--config-dir", type=Path, default=None, help="Default: <repo>/configs/data.")
imp.add_argument("--max-hours", type=float, default=10.0, help="Stop selecting at this many h.")
imp.add_argument(
"--shard-offset",
type=int,
default=0,
help="First work unit (parquet shard / row chunk); roots take disjoint ranges.",
)
imp.add_argument(
"--shards", type=_positive_int, default=None, help="Number of work units (default: rest)."
)
imp.add_argument(
"--source-dir",
type=Path,
default=None,
help="wavdir: folder with manifest.jsonl; common_voice_tr: release folder or tarball.",
)
imp.add_argument(
"--revision",
default=None,
help=(
"Hub commit sha to pin (default: current head, recorded); mediaspeech_tr: sha256 of "
"TR.tgz (default: the one in configs/data/import_corpora.yaml)."
),
)
imp.add_argument("--retry-failed", action="store_true")
imp.add_argument(
"--audio-threads",
type=_positive_int,
default=4,
help="Threads converting raw audio to 16 kHz wavs (does not change the outputs).",
)
train = sub.add_parser(
"train",
parents=[_common_parser()],
help="Phase 2 flow-matching training on a latent dataset (docs/04-architecture.md).",
)
train.add_argument("--config", type=Path, required=True, help="YAML under configs/train/.")
train.add_argument(
"--data",
type=Path,
required=True,
action="append",
help="Latent dataset directory; repeat the flag to train on the union of several.",
)
train.add_argument(
"--out", type=Path, required=True, help="Training workspace (checkpoints, metrics.jsonl)."
)
train.add_argument(
"--resume", action="store_true", help="Continue from the newest checkpoint in --out."
)
train.add_argument("--device", default=None, help="cpu | cuda | auto (default: auto).")
train.add_argument(
"--init-from",
type=Path,
default=None,
help="Fine-tune: start from this checkpoint's weights and latent stats (same model "
"config, except dur_cond none -> emotion) when --out has no checkpoint yet; "
"optimizer and schedule start fresh.",
)
samples = sub.add_parser(
"synth-samples",
parents=[_common_parser()],
help="Listening page: validation items re-spoken by a trained checkpoint.",
)
samples.add_argument(
"--checkpoint", type=Path, required=True, help="ckpt-*.pt or a training workspace."
)
samples.add_argument("--data", type=Path, required=True, help="Latent dataset directory.")
samples.add_argument("--out", type=Path, required=True, help="Output directory.")
samples.add_argument("--n", type=int, default=12, help="Validation items to generate.")
samples.add_argument("--steps", type=int, default=32, help="ODE steps.")
samples.add_argument("--w-text", type=float, default=2.0)
# Keeps 1.0 on purpose (sample CER stays comparable with earlier runs); `say` uses 2.0.
samples.add_argument("--w-emo", type=float, default=1.0)
samples.add_argument("--seed", type=int, default=0)
samples.add_argument("--method", choices=["euler", "midpoint"], default="euler")
samples.add_argument(
"--sway", type=float, default=-1.0, help="Sway time-step warp (0 = uniform steps)."
)
samples.add_argument("--envs", type=Path, default=Path("/content/nida_envs"))
samples.add_argument("--repo", type=Path, default=_REPO_DIR)
samples.add_argument("--device", default=None, help="cpu | cuda | auto (default: auto).")
samples.add_argument(
"--no-asr", action="store_true", help="Skip the Qwen3-ASR read-back (CER) check."
)
say = sub.add_parser(
"say",
parents=[_common_parser()],
help="Speak free text after a validation speaker prompt (aligned checkpoints).",
)
say.add_argument("--checkpoint", type=Path, required=True, help="ckpt-*.pt or a workspace.")
say.add_argument(
"--data",
type=Path,
default=None,
help="Latent dataset (prompt source); not needed with only --prompt-list prompts.",
)
say.add_argument("--out", type=Path, required=True, help="Output directory.")
text = say.add_mutually_exclusive_group(required=True)
text.add_argument(
"--text",
help=(
"Text to speak (sentences split on . ! ? …; long ones also at , ; :). Numbers, "
"%%, TL, clock times, abbreviations and acronyms need not be written out: they are "
"normalised to spoken Turkish first (--no-normalize disables this). "
"'@mutlu:0.8' sets the emotion of the text after it; '[duraksama:0.3]' inserts "
"exactly 0.3 s of silence (it ends the sentence); '[duraksama]' lets the model pause."
),
)
text.add_argument("--text-file", type=Path, help="UTF-8 file with the text to speak.")
say.add_argument(
"--prompt-id", action="append", default=None, help="Validation segment (repeatable)."
)
say.add_argument(
"--n-prompts", type=int, default=3, help="Prompts to pick when no --prompt-id is given."
)
say.add_argument(
"--prompt-list",
type=Path,
default=None,
help="TSV '<wav>\t<transcript>' of prompts from outside the datasets.",
)
say.add_argument(
"--rank-prompts",
type=int,
default=0,
help="Decode this many prompt candidates and keep the cleanest --n-prompts (0 = off).",
)
say.add_argument("--steps", type=int, default=32, help="ODE steps.")
say.add_argument("--w-text", type=float, default=3.0)
say.add_argument("--w-emo", type=float, default=2.0)
say.add_argument("--seed", type=int, default=0)
say.add_argument("--method", choices=["euler", "midpoint"], default="euler")
say.add_argument("--sway", type=float, default=-1.0)
say.add_argument("--speed", type=float, default=1.0, help=">1 faster, <1 slower.")
say.add_argument("--envs", type=Path, default=Path("/content/nida_envs"))
say.add_argument("--repo", type=Path, default=_REPO_DIR)
say.add_argument("--device", default=None, help="cpu | cuda | auto (default: auto).")
say.add_argument("--no-asr", action="store_true", help="Skip the ASR read-back check.")
say.add_argument(
"--no-normalize",
action="store_true",
help=(
"Use the text as written: no expansion of digits, symbols, abbreviations or "
"acronyms (they must then be spelled out, or the text is rejected)."
),
)
say.add_argument(
"--strict-normalize",
action="store_true",
help=(
"Stop on every text-normalisation issue (a guessed acronym, an ambiguous time or "
"ordinal, ...); by default only issues that would be misread stop the run."
),
)
say.add_argument(
"--single-env",
action="store_true",
help=(
"Run every worker (VAE, CTC, ASR) with this interpreter instead of building one "
"venv per worker (a local install with all packages, e.g. a release user)."
),
)
queue = sub.add_parser(
"queue",
parents=[_common_parser()],
help="Run nida.cli commands listed in a file, one after another (nida.jobqueue).",
)
queue.add_argument("--file", type=Path, required=True, help="Queue file (one job a line).")
queue.add_argument(
"--wait-minutes",
type=float,
default=0.0,
help="Keep polling the file this long after the last job before returning.",
)
queue.add_argument(
"--bundle-dir", type=Path, default=None, help="Default: <runs-root>/../code."
)
queue.add_argument("--log-dir", type=Path, default=Path("/content/nida_logs"))
queue.add_argument("--repo", type=Path, default=_REPO_DIR)
return parser
def _env_report_md(metrics: dict[str, object]) -> str:
def show(value: object) -> str:
return "—" if value is None else str(value)
lines = ["# env-report", ""]
if metrics["gpu_name"] is None:
lines.append("- device: CPU only")
else:
lines.append(f"- device: {metrics['gpu_name']} (count {metrics['gpu_count']})")
for key in (
"gpu_memory_gb",
"compute_capability",
"bf16_supported",
"torch_version",
"cuda_version",
"torchaudio_version",
"python",
"cpu_count",
"ram_total_gb",
"disk_free_gb",
):
lines.append(f"- {key}: {show(metrics[key])}")
return "\n".join(lines) + "\n"
def _resolve_device(choice: str | None, cuda_available: bool) -> str:
"""``--device``: ``None`` or ``auto`` → cuda when available, else cpu; other values as is."""
if choice in (None, "auto"):
return "cuda" if cuda_available else "cpu"
return str(choice)
def _cmd_env_report(args: argparse.Namespace) -> int:
env = collect_env()
print(json.dumps(env, ensure_ascii=False, indent=2, sort_keys=True))
if args.runs_root is None:
return 0
with RunContext(
args.runs_root, "env-report", run_id=args.run_id, git_commit=args.git_commit
) as run:
atomic_write_json(run.dir / "env.json", env)
metrics = summarize_env(env)
atomic_write_json(run.dir / "metrics.json", metrics)
atomic_write_text(run.dir / "report.md", _env_report_md(metrics))
print(f"run_id={run.run_id}")
return 0
def _cmd_bench_phase0(args: argparse.Namespace) -> int:
from nida.bench.phase0 import Phase0
from nida.bench.prepare import Workspace
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
workspace_root = args.workspace
if workspace_root is None:
if args.runs_root is None:
raise SystemExit("bench-phase0 needs --workspace or --runs-root")
workspace_root = args.runs_root.parent / "bench" / "phase0"
phase0 = Phase0(
workspace=Workspace(root=workspace_root, cache=args.cache),
envs_root=args.envs,
repo_dir=args.repo,
sources_path=args.repo / "configs" / "sources.yaml",
retry_failed=args.retry_failed,
)
if args.runs_root is None:
result = phase0.run(
args.stage, c_results=args.c_results, b2_panel_results=args.b2_panel_results
)
print(json.dumps(result, ensure_ascii=False, indent=2, default=str))
return 0
with RunContext(
args.runs_root, f"bench-phase0-{args.stage}", run_id=args.run_id, git_commit=args.git_commit
) as run:
result = phase0.run(
args.stage, c_results=args.c_results, b2_panel_results=args.b2_panel_results
)
atomic_write_json(run.dir / "metrics.json", json.loads(json.dumps(result, default=str)))
reports = [
(workspace_root / "reports" / name)
for name in ("b1_report.md", "b2_report.md", "b2_panel_report.md")
if (workspace_root / "reports" / name).exists()
]
body = "\n\n".join(r.read_text(encoding="utf-8") for r in reports)
atomic_write_text(
run.dir / "report.md",
f"# bench-phase0 ({args.stage})\n\nworkspace: {workspace_root}\n\n{body}\n",
)
print(f"run_id={run.run_id}")
return 0
def _cmd_data_pilot(args: argparse.Namespace) -> int:
from nida.data.pilot import Pilot, PilotPlan
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
root = args.root
if root is None:
if args.runs_root is None:
raise SystemExit("data-pilot needs --root or --runs-root")
root = args.runs_root.parent / "data" / "pilot"
pilot = Pilot(
root=root,
cache=args.cache,
envs_root=args.envs,
repo_dir=args.repo,
sources_path=args.repo / "configs" / "sources.yaml",
config_dir=args.repo / "configs" / "data",
plan=PilotPlan(
subset=args.subset,
shards=args.shards,
max_hours=args.max_hours,
asr_primary=args.asr_primary,
asr_secondary=args.asr_secondary,
),
retry_failed=args.retry_failed,
asr_batch_size=args.asr_batch_size,
parallel_workers=args.parallel_workers,
)
if args.runs_root is None:
print(json.dumps(pilot.run(args.stage), ensure_ascii=False, indent=2, default=str))
return 0
with RunContext(
args.runs_root, f"data-pilot-{args.stage}", run_id=args.run_id, git_commit=args.git_commit
) as run:
result = pilot.run(args.stage)
atomic_write_json(run.dir / "metrics.json", json.loads(json.dumps(result, default=str)))
report = root / "reports" / "pilot.md"
body = report.read_text(encoding="utf-8") if report.exists() else ""
result_json = json.dumps(result, ensure_ascii=False, indent=2, default=str)
lines = [
f"# data-pilot ({args.stage})",
"",
f"root: {root}",
"",
"```json",
result_json,
"```",
"",
body,
]
atomic_write_text(run.dir / "report.md", "\n".join(lines) + "\n")
print(f"run_id={run.run_id}")
return 0
def _cmd_data_ears(args: argparse.Namespace) -> int:
from nida.bench import fetch
from nida.bench.b1 import _stream_runner
from nida.data.ears import Ears, load_settings, parse_speakers
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
root = args.root
if root is None:
if args.runs_root is None:
raise SystemExit("data-ears needs --root or --runs-root")
root = args.runs_root.parent / "data" / "ears"
config_dir = args.config_dir or args.repo / "configs" / "data"
speakers = parse_speakers(args.speakers, load_settings(config_dir).ears.n_speakers)
ears = Ears(
root=root,
cache=args.cache,
envs_root=args.envs,
repo_dir=args.repo,
sources_path=args.repo / "configs" / "sources.yaml",
config_dir=config_dir,
seed=args.seed,
runner=_stream_runner,
opener=fetch.default_opener,
)
if args.runs_root is None:
print(json.dumps(ears.run(speakers), ensure_ascii=False, indent=2, default=str))
return 0
with RunContext(
args.runs_root, "data-ears", run_id=args.run_id, git_commit=args.git_commit
) as run:
result = ears.run(speakers)
atomic_write_json(run.dir / "metrics.json", json.loads(json.dumps(result, default=str)))
report = root / "report.md"
body = report.read_text(encoding="utf-8") if report.exists() else ""
result_json = json.dumps(result, ensure_ascii=False, indent=2, default=str)
lines = ["# data-ears", "", f"root: {root}", "", "```json", result_json, "```", "", body]
atomic_write_text(run.dir / "report.md", "\n".join(lines) + "\n")
print(f"run_id={run.run_id}")
return 0
def _cmd_data_import(args: argparse.Namespace) -> int:
from nida.data.importer import Importer, ImportRequest
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
root = args.root
if root is None:
if args.runs_root is None:
raise SystemExit("data-import needs --root or --runs-root")
root = args.runs_root.parent / "data" / f"import-{args.source}"
cache = args.cache or Path("/content/nida_cache/import") / root.name
importer = Importer(
root=root,
cache=cache,
envs_root=args.envs,
repo_dir=args.repo,
request=ImportRequest(
source=args.source,
max_hours=args.max_hours,
unit_offset=args.shard_offset,
unit_count=args.shards,
revision=args.revision,
),
config_dir=args.config_dir,
wavdir=args.source_dir,
retry_failed=args.retry_failed,
audio_threads=args.audio_threads,
)
if args.runs_root is None:
print(json.dumps(importer.run(args.stage), ensure_ascii=False, indent=2, default=str))
return 0
with RunContext(
args.runs_root, f"data-import-{args.stage}", run_id=args.run_id, git_commit=args.git_commit
) as run:
result = importer.run(args.stage)
atomic_write_json(run.dir / "metrics.json", json.loads(json.dumps(result, default=str)))
report = root / "report.md"
body = report.read_text(encoding="utf-8") if report.exists() else ""
result_json = json.dumps(result, ensure_ascii=False, indent=2, default=str)
lines = [
f"# data-import {args.source} ({args.stage})",
"",
f"root: {root}",
"",
"```json",
result_json,
"```",
"",
body,
]
atomic_write_text(run.dir / "report.md", "\n".join(lines) + "\n")
print(f"run_id={run.run_id}")
return 0
#: Exit code of ``nida train`` when a SIGTERM stopped it after saving a checkpoint.
EXIT_TRAIN_INTERRUPTED = 3
def _cmd_train(args: argparse.Namespace) -> int:
from nida.train.runner import TrainOutcome, run_training
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
def execute() -> TrainOutcome:
return run_training(
args.config,
args.data,
args.out,
resume=args.resume,
device=args.device,
git_commit=args.git_commit,
repo_dir=_REPO_DIR,
init_from=args.init_from,
)
if args.runs_root is None:
outcome = execute()
atomic_write_json(args.out / "metrics.json", outcome.metrics)
atomic_write_text(args.out / "report.md", outcome.report_md)
else:
with RunContext(
args.runs_root, "train", run_id=args.run_id, git_commit=args.git_commit
) as run:
outcome = execute()
if outcome.result.stopped_by_signal:
run.status.extra["interrupted"] = "sigterm"
atomic_write_json(run.dir / "metrics.json", outcome.metrics)
atomic_write_text(run.dir / "report.md", outcome.report_md)
print(f"run_id={run.run_id}")
return EXIT_TRAIN_INTERRUPTED if outcome.result.stopped_by_signal else 0
def _cmd_synth_samples(args: argparse.Namespace) -> int:
import torch
from nida.bench import envs as bench_envs
from nida.bench.b1 import _stream_runner
from nida.data.envs import data_env_for_worker
from nida.infer.samples import SampleSettings, make_listening_page
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
settings = SampleSettings(
n_items=args.n,
steps=args.steps,
w_text=args.w_text,
w_emo=args.w_emo,
seed=args.seed,
method=args.method,
sway=args.sway,
)
device = _resolve_device(args.device, torch.cuda.is_available())
def execute() -> Path:
python = bench_envs.ensure_env(
data_env_for_worker("vae_decode"),
args.envs,
args.repo,
uv=bench_envs.find_uv(bench_envs.subprocess_runner),
)
asr_python = None
if not args.no_asr:
asr_python = bench_envs.ensure_env(
bench_envs.env_for_worker("asr_qwen"),
args.envs,
args.repo,
uv=bench_envs.find_uv(bench_envs.subprocess_runner),
)
return make_listening_page(
args.checkpoint,
args.data,
args.out,
settings,
decoder_python=python,
runner=_stream_runner,
device=torch.device(device),
asr_python=asr_python,
)
if args.runs_root is None:
print(execute())
return 0
with RunContext(
args.runs_root, "synth-samples", run_id=args.run_id, git_commit=args.git_commit
) as run:
page = execute()
settings_json = (args.out / "settings.json").read_text(encoding="utf-8")
atomic_write_json(run.dir / "metrics.json", {"page": str(page)})
atomic_write_text(
run.dir / "report.md",
f"# synth-samples\n\npage: {page}\n\n```json\n{settings_json}\n```\n",
)
print(f"run_id={run.run_id}")
return 0
#: Package pins of the isolated worker envs that ``say --single-env`` replaces
#: (``nida.data.envs`` / ``nida.bench.envs``): checked, never installed.
_SINGLE_ENV_PINS = {"transformers": "4.57.6"}
_SINGLE_ENV_ASR_PINS = {"qwen-asr": "0.0.6"}
def _single_env_report(with_asr: bool) -> dict[str, object]:
"""Interpreter and package versions a ``--single-env`` run uses, with every difference
from the worker envs' pins logged as a warning and listed (results may then differ
from Colab runs)."""
from importlib import metadata
pins = {**_SINGLE_ENV_PINS, **(_SINGLE_ENV_ASR_PINS if with_asr else {})}
versions: dict[str, str | None] = {}
for name in ("torch", "torchaudio", *pins):
try:
versions[name] = metadata.version(name)
except metadata.PackageNotFoundError:
versions[name] = None
mismatches = {
name: {"pinned": pin, "installed": versions[name]}
for name, pin in pins.items()
if versions[name] != pin
}
for name, diff in mismatches.items():
logging.getLogger(__name__).warning(
"say --single-env: %s %s installed, worker env pins %s",
name,
diff["installed"],
diff["pinned"],
)
return {
"single_env": True,
"python": sys.executable,
"versions": versions,
"pin_mismatches": mismatches,
}
def _cmd_say(args: argparse.Namespace) -> int:
import torch
from nida.bench import envs as bench_envs
from nida.bench.b1 import _stream_runner
from nida.data.envs import data_env_for_worker
from nida.infer.say import (
SaySettings,
make_say_page,
pick_prompts,
prompt_candidates,
rank_prompts,
)
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
settings = SaySettings(
steps=args.steps,
w_text=args.w_text,
w_emo=args.w_emo,
seed=args.seed,
method=args.method,
sway=args.sway,
speed=args.speed,
normalize_text=not args.no_normalize,
strict_normalize=args.strict_normalize,
)
text = args.text if args.text is not None else args.text_file.read_text(encoding="utf-8")
device = _resolve_device(args.device, torch.cuda.is_available())
if args.data is None and (args.prompt_list is None or args.prompt_id or args.rank_prompts):
raise SystemExit("say: --data is required unless every prompt comes from --prompt-list")
if args.rank_prompts and (args.prompt_list is not None or args.prompt_id):
logging.getLogger(__name__).warning(
"say: --rank-prompts is ignored when --prompt-list or --prompt-id gives the prompts"
)
# make_say_page reads data_dir only for dataset prompt ids, which the guard above rules
# out when --data is missing.
data_dir: Path = args.data if args.data is not None else args.out / "no-dataset"
worker_device = "cuda" if torch.device(device).type == "cuda" else "cpu"
if args.single_env:
args.out.mkdir(parents=True, exist_ok=True)
atomic_write_json(args.out / "environment.json", _single_env_report(not args.no_asr))
else:
(args.out / "environment.json").unlink(missing_ok=True) # never a stale single-env report
def env_python(spec: bench_envs.EnvSpec, uv: str | None) -> Path:
if args.single_env:
return Path(sys.executable)
assert uv is not None
return bench_envs.ensure_env(spec, args.envs, args.repo, uv=uv)
def execute() -> Path:
uv = None if args.single_env else bench_envs.find_uv(bench_envs.subprocess_runner)
python = env_python(data_env_for_worker("vae_decode"), uv)
external = []
if args.prompt_list is not None:
from nida.data.registry import DATA_MODELS
from nida.infer.external_prompt import build_external_prompts, read_prompt_list
ctc_python = env_python(data_env_for_worker(DATA_MODELS["mpoyraz_ctc_tr"].worker), uv)
external = build_external_prompts(
read_prompt_list(args.prompt_list),
args.out / "external",
vae_python=env_python(data_env_for_worker("vae_encode"), uv),
ctc_python=ctc_python,
runner=_stream_runner,
device=worker_device,
)
if args.prompt_id:
prompt_ids = args.prompt_id
elif external:
prompt_ids = []
elif args.rank_prompts > 0:
ranked = rank_prompts(
args.data,
prompt_candidates(args.data, args.rank_prompts),
args.out,
decoder_python=python,
runner=_stream_runner,
device=worker_device,
)
prompt_ids = [str(r["segment_id"]) for r in ranked[: args.n_prompts]]
else:
prompt_ids = pick_prompts(args.data, args.n_prompts)
asr_python = None
if not args.no_asr:
asr_python = env_python(bench_envs.env_for_worker("asr_qwen"), uv)
return make_say_page(
args.checkpoint,
data_dir,
prompt_ids,
text,
args.out,
settings,
decoder_python=python,
runner=_stream_runner,
device=torch.device(device),
asr_python=asr_python,
external=external,
)
if args.runs_root is None:
print(execute())
return 0
with RunContext(args.runs_root, "say", run_id=args.run_id, git_commit=args.git_commit) as run:
page = execute()
settings_json = (args.out / "settings.json").read_text(encoding="utf-8")
atomic_write_json(run.dir / "metrics.json", {"page": str(page)})
atomic_write_text(
run.dir / "report.md", f"# say\n\npage: {page}\n\n```json\n{settings_json}\n```\n"
)
print(f"run_id={run.run_id}")
return 0
def _cmd_queue(args: argparse.Namespace) -> int:
from nida.jobqueue import (
run_git,
run_queue,
state_path_for,
stream_to_log,
summary_markdown,
)
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
if args.runs_root is None or args.git_commit is None:
print("queue needs --runs-root and --git-commit (the Colab runner passes both)")
return 2
bundle_dir = args.bundle_dir or args.runs_root.parent / "code"
with RunContext(args.runs_root, "queue", run_id=args.run_id, git_commit=args.git_commit) as run:
summary = run_queue(
args.file,
runs_root=args.runs_root,
git_commit=args.git_commit,
repo_dir=args.repo,
bundle_dir=bundle_dir,
log_dir=args.log_dir,
runner=stream_to_log,
git=run_git,
wait_minutes=args.wait_minutes,
)
state_file = state_path_for(args.file)
state = json.loads(state_file.read_text(encoding="utf-8")) if state_file.exists() else {}
atomic_write_json(
run.dir / "metrics.json",
{
"jobs": len(summary.outcomes),
"failed": len(summary.failed),
"interrupted": summary.interrupted,
},
)
atomic_write_text(run.dir / "report.md", summary_markdown(summary, state))
if summary.interrupted:
run.status.extra["interrupted"] = str(summary.interrupted_key)
print(f"run_id={run.run_id}")
return EXIT_TRAIN_INTERRUPTED if summary.interrupted else 0
def main(argv: Sequence[str] | None = None) -> int:
"""Entry point. Returns a process exit code."""
args = _build_parser().parse_args(argv)
if args.command == "env-report":
return _cmd_env_report(args)
if args.command == "bench-phase0":
return _cmd_bench_phase0(args)
if args.command == "data-pilot":
return _cmd_data_pilot(args)
if args.command == "data-ears":
return _cmd_data_ears(args)
if args.command == "data-import":
return _cmd_data_import(args)
if args.command == "train":
return _cmd_train(args)
if args.command == "synth-samples":
return _cmd_synth_samples(args)
if args.command == "say":
return _cmd_say(args)
if args.command == "queue":
return _cmd_queue(args)
raise AssertionError(f"unhandled command {args.command!r}") # argparse prevents this
if __name__ == "__main__":
raise SystemExit(main())12345"""Phase 1 data pipeline (docs/03-data-pipeline.md).
Stage logic lives here as pure, CPU-testable functions over the records in:mod:`nida.data.types`; model inference runs in isolated worker environments."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002"""Acoustic measurements for data-pipeline stages S1, S2 and S6 (docs/03-data-pipeline.md).
Everything here is pure, CPU-only numpy/scipy over mono waveforms:
* **S1** :func:`estimate_bandwidth_hz` - effective bandwidth of a file (detects content that was low-passed or upsampled from a lower rate).* **S2** :func:`clipping_ratio`, :func:`silence_ratio`, :func:`loudness_dbfs`.* **S6** :func:`track_pitch` (numpy YIN), :func:`word_features` (per-word voicing, F0, HNR, RMS, spectral tilt), :func:`speaker_baseline`, :func:`whisper_scores`, :func:`shout_scores`.
Conventions: waveforms are 1-D floating arrays (float32 or float64) with samples in``[-1, 1]`` (``1.0`` = full scale); ``sample_rate_hz`` is an int; times are integermilliseconds (``*_ms``) relative to the start of the waveform. All decision parameters comefrom :class:`AcousticConfig` (``configs/data/acoustic.yaml``); the few literals left inthis file are numerical guards (division/log floors), not thresholds.
Invalid input (non-float dtype, not 1-D, empty, NaN/inf, bad rate) raises:class:`ValueError` naming the argument; nothing is silently repaired or dropped."""
from __future__ import annotations
import mathimport typingfrom collections.abc import Mapping, Sequencefrom dataclasses import dataclassfrom itertools import pairwisefrom pathlib import Pathfrom typing import Any, TypeAlias
import numpy as npimport numpy.typing as npt
# scipy ships no type stubs; the ignore is scoped to this single import.from scipy import signal # type: ignore[import-untyped]
from nida.bench.audiometrics import stft_magnitudefrom nida.data.types import TimedWord, WordStyleScore
__all__ = [ "AcousticConfig", "BandwidthParams", "BaselineError", "FloatArray", "PitchTrack", "SilentAudioError", "SpeakerBaseline", "WordFeatures", "clipping_ratio", "estimate_bandwidth_hz", "load_acoustic_config", "loudness_dbfs", "phrase_support", "shout_scores", "silence_ratio", "speaker_baseline", "track_pitch", "whisper_scores", "word_features",]
FloatArray: TypeAlias = npt.NDArray[np.float64]BoolArray: TypeAlias = npt.NDArray[np.bool_]IntArray: TypeAlias = npt.NDArray[np.int64]
WHISPER_SOURCE = "acoustic.whisper.v0"SHOUT_SOURCE = "acoustic.shout.v0"
# Numerical guards (not thresholds): floor under power before log10 / before division._POWER_FLOOR = 1e-24 # -240 dB; makes digital silence a finite number_REL_EPS = 1e-9 # relative floor for "this energy is effectively zero"_LOGISTIC_CLIP = 60.0 # |z| beyond this saturates to 0/1 and would overflow exp()# Frames are processed in chunks to bound the memory of the batched FFTs (an# implementation detail with no effect on results)._CHUNK_FRAMES = 256
class SilentAudioError(ValueError): """The waveform carries no energy, so the requested measurement is undefined."""
class BaselineError(ValueError): """Too few voiced words to estimate a speaker baseline (shout not measurable)."""
# --------------------------------------------------------------------------------------# Config# --------------------------------------------------------------------------------------
def _check_finite(value: float, name: str) -> None: if not math.isfinite(value): raise ValueError(f"{name} must be finite, got {value!r}")
def _check_pos(value: float, name: str) -> None: if not (math.isfinite(value) and value > 0.0): raise ValueError(f"{name} must be a finite number > 0, got {value!r}")
@dataclass(frozen=True)class BandwidthParams: """Analysis parameters of :func:`estimate_bandwidth_hz` (S1).
The field defaults are used only when a caller passes no config; they equal the values in ``configs/data/acoustic.yaml`` at the time of writing.
Attributes: n_fft_samples: FFT size of the long-term average spectrum (LTAS). active_within_db: A frame is *active* when its energy is within this many dB of the loudest frame; only active frames enter the LTAS. ref_low_hz: Lower edge of the reference band. ref_high_hz: Upper edge of the reference band (clipped to Nyquist at run time). The reference level is the median smoothed LTAS level inside this band. smooth_hz: Width of the median filter run over the LTAS; rejects isolated narrow-band spikes (hum, pilot tones) above the true cut-off. A tone is rejected when its spectral footprint (Hann main lobe plus side lobes above the ``floor_db`` threshold) is narrower than half this width; a tone far louder than the in-band level leaks wider than that and counts as bandwidth. """
n_fft_samples: int = 2048 active_within_db: float = 30.0 ref_low_hz: float = 300.0 ref_high_hz: float = 3400.0 smooth_hz: float = 600.0
def __post_init__(self) -> None: if self.n_fft_samples < 16: raise ValueError(f"n_fft_samples must be >= 16, got {self.n_fft_samples}") _check_pos(self.active_within_db, "active_within_db") _check_pos(self.ref_low_hz, "ref_low_hz") _check_pos(self.ref_high_hz, "ref_high_hz") _check_pos(self.smooth_hz, "smooth_hz") if self.ref_low_hz >= self.ref_high_hz: raise ValueError( f"need ref_low_hz < ref_high_hz, got {self.ref_low_hz} >= {self.ref_high_hz}" )
@classmethod def from_mapping(cls, raw: object) -> BandwidthParams: """Build from a mapping; unknown or missing keys raise :class:`ValueError`.""" return cls(**_coerce_fields(cls, raw, "bandwidth")) # type: ignore[arg-type]
@dataclass(frozen=True)class AcousticConfig: """All decision parameters of this module. Values: ``configs/data/acoustic.yaml``.
S1 / S2 measurement parameters (consumed by the stage code, which passes them to the functions below): bandwidth_floor_db: ``floor_db`` for :func:`estimate_bandwidth_hz`. bandwidth: Other bandwidth-estimation parameters (:class:`BandwidthParams`). clipping_threshold: ``threshold`` for :func:`clipping_ratio` (in (0, 1]). silence_frame_ms: ``frame_ms`` for :func:`silence_ratio`. silence_dbfs: ``silence_dbfs`` for :func:`silence_ratio`.
S6 word features: min_word_ms: Words shorter than this get ``None``-marked features. word_end_tolerance_ms: A word may overshoot the end of the audio by at most this much (alignment rounding); it is clipped. More raises ``ValueError``. f0_min_hz, f0_max_hz: Search range of the pitch tracker. f0_frame_ms, f0_hop_ms: YIN analysis window and hop. The window must span at least two periods of ``f0_min_hz``. yin_threshold: Absolute threshold on the cumulative-mean-normalised difference function below which a frame counts as voiced. f0_energy_floor_dbfs: Frames quieter than this (RMS dBFS) are never voiced. hnr_max_db: Per-frame HNR is clipped to ``[-hnr_max_db, +hnr_max_db]``. tilt_low_hz, tilt_high_hz: Frequency range of the spectral-tilt regression (the upper edge is clipped to Nyquist at run time). tilt_num_bands: Number of log-spaced bands the regression is fitted on (>= 3). tilt_n_fft_samples: FFT size for the tilt spectrum.
Whisper score (soft AND of three logistic factors, see :func:`whisper_scores`): whisper_unvoiced_center, whisper_unvoiced_scale: on ``1 - voicing_ratio``. whisper_hnr_center_db, whisper_hnr_scale_db: on ``-hnr_db`` (low HNR -> whisper). whisper_energy_center_dbfs, whisper_energy_scale_db: on ``rms_dbfs`` (energy must be present, otherwise silence would look like a whisper).
Shout score (see :func:`shout_scores`): baseline_min_voicing_ratio: A word is *voiced* for the speaker baseline when its ``voicing_ratio`` is at least this. baseline_min_voiced_words: Fewer voiced words than this -> no baseline. shout_weight_db, shout_weight_f0_semitones, shout_weight_tilt: Weights of the deviations from the speaker baseline in the linear combination. shout_center, shout_scale: Logistic centre/scale on that combination. """
bandwidth_floor_db: float bandwidth: BandwidthParams clipping_threshold: float silence_frame_ms: float silence_dbfs: float
min_word_ms: int word_end_tolerance_ms: int f0_min_hz: float f0_max_hz: float f0_frame_ms: float f0_hop_ms: float yin_threshold: float f0_energy_floor_dbfs: float hnr_max_db: float tilt_low_hz: float tilt_high_hz: float tilt_num_bands: int tilt_n_fft_samples: int
whisper_unvoiced_center: float whisper_unvoiced_scale: float whisper_hnr_center_db: float whisper_hnr_scale_db: float whisper_energy_center_dbfs: float whisper_energy_scale_db: float
baseline_min_voicing_ratio: float baseline_min_voiced_words: int shout_weight_db: float shout_weight_f0_semitones: float shout_weight_tilt: float shout_center: float shout_scale: float
def __post_init__(self) -> None: _check_pos(self.bandwidth_floor_db, "bandwidth_floor_db") if not (math.isfinite(self.clipping_threshold) and 0.0 < self.clipping_threshold <= 1.0): raise ValueError(f"clipping_threshold must be in (0, 1], got {self.clipping_threshold}") _check_pos(self.silence_frame_ms, "silence_frame_ms") _check_finite(self.silence_dbfs, "silence_dbfs")
if self.min_word_ms <= 0: raise ValueError(f"min_word_ms must be > 0, got {self.min_word_ms}") if self.word_end_tolerance_ms < 0: raise ValueError( f"word_end_tolerance_ms must be >= 0, got {self.word_end_tolerance_ms}" ) _check_pos(self.f0_min_hz, "f0_min_hz") _check_pos(self.f0_max_hz, "f0_max_hz") if self.f0_min_hz >= self.f0_max_hz: raise ValueError(f"need f0_min_hz < f0_max_hz, got {self.f0_min_hz}..{self.f0_max_hz}") _check_pos(self.f0_frame_ms, "f0_frame_ms") _check_pos(self.f0_hop_ms, "f0_hop_ms") if not (math.isfinite(self.yin_threshold) and 0.0 < self.yin_threshold < 1.0): raise ValueError(f"yin_threshold must be in (0, 1), got {self.yin_threshold}") _check_finite(self.f0_energy_floor_dbfs, "f0_energy_floor_dbfs") _check_pos(self.hnr_max_db, "hnr_max_db") _check_pos(self.tilt_low_hz, "tilt_low_hz") _check_pos(self.tilt_high_hz, "tilt_high_hz") if self.tilt_low_hz >= self.tilt_high_hz: raise ValueError( f"need tilt_low_hz < tilt_high_hz, got {self.tilt_low_hz}..{self.tilt_high_hz}" ) if self.tilt_num_bands < 3: raise ValueError(f"tilt_num_bands must be >= 3, got {self.tilt_num_bands}") if self.tilt_n_fft_samples < 16: raise ValueError(f"tilt_n_fft_samples must be >= 16, got {self.tilt_n_fft_samples}") if self.min_word_ms < self.f0_hop_ms: raise ValueError( f"min_word_ms ({self.min_word_ms}) must be >= f0_hop_ms ({self.f0_hop_ms}) so " "that every measurable word contains at least one pitch frame" )
for name in ( "whisper_unvoiced_scale", "whisper_hnr_scale_db", "whisper_energy_scale_db", "shout_scale", ): _check_pos(getattr(self, name), name) for name in ( "whisper_unvoiced_center", "whisper_hnr_center_db", "whisper_energy_center_dbfs", "shout_weight_db", "shout_weight_f0_semitones", "shout_weight_tilt", "shout_center", ): _check_finite(getattr(self, name), name) if not ( math.isfinite(self.baseline_min_voicing_ratio) and 0.0 < self.baseline_min_voicing_ratio <= 1.0 ): raise ValueError( "baseline_min_voicing_ratio must be in (0, 1], " f"got {self.baseline_min_voicing_ratio}" ) if self.baseline_min_voiced_words < 1: raise ValueError( f"baseline_min_voiced_words must be >= 1, got {self.baseline_min_voiced_words}" )
@classmethod def from_mapping(cls, raw: object) -> AcousticConfig: """Build from a mapping (e.g. parsed YAML); unknown or missing keys are rejected.""" return cls(**_coerce_fields(cls, raw, "acoustic config")) # type: ignore[arg-type]
def _coerce_fields(cls: type, raw: object, where: str) -> dict[str, object]: """Check ``raw`` against the dataclass ``cls`` and coerce each value to its field type.
Rejects non-mappings, non-string keys, unknown keys, missing keys, bools in numeric fields and non-integral values in int fields. Nested dataclass fields are built recursively. """ if not isinstance(raw, Mapping): raise ValueError(f"{where}: expected a mapping, got {type(raw).__name__}") hints = typing.get_type_hints(cls) bad_keys = [k for k in raw if not isinstance(k, str)] if bad_keys: raise ValueError(f"{where}: non-string keys {bad_keys!r}") unknown = sorted(set(raw) - set(hints)) missing = sorted(set(hints) - set(raw)) if unknown or missing: raise ValueError(f"{where}: unknown keys {unknown}, missing keys {missing}")
out: dict[str, object] = {} for name, hint in hints.items(): value = raw[name] path = f"{where}.{name}" if hint is float: if isinstance(value, bool) or not isinstance(value, int | float): raise ValueError(f"{path}: expected a number, got {value!r}") out[name] = float(value) elif hint is int: if isinstance(value, bool) or not isinstance(value, int): raise ValueError(f"{path}: expected an integer, got {value!r}") out[name] = int(value) elif hint is BandwidthParams: out[name] = BandwidthParams(**_coerce_fields(BandwidthParams, value, path)) # type: ignore[arg-type] else: # pragma: no cover - guards future field types raise TypeError(f"{path}: unsupported field type {hint!r}") return out
def load_acoustic_config(path: Path) -> AcousticConfig: """Read an :class:`AcousticConfig` from a YAML file (``configs/data/acoustic.yaml``).""" import yaml # type: ignore[import-untyped] # PyYAML: bench extra, no stubs installed
data: Any = yaml.safe_load(path.read_text(encoding="utf-8")) # Any: untyped YAML tree try: return AcousticConfig.from_mapping(data) except ValueError as exc: raise ValueError(f"{path}: {exc}") from exc
# --------------------------------------------------------------------------------------# Input validation# --------------------------------------------------------------------------------------
def _as_audio(audio: npt.ArrayLike, name: str = "audio") -> FloatArray: """Validate a mono float waveform and return it as float64.""" arr = np.asarray(audio) if arr.dtype.kind != "f": raise ValueError(f"{name} must have a floating dtype, got {arr.dtype}") if arr.ndim != 1: raise ValueError(f"{name} must be 1-D mono, got shape {arr.shape}") if arr.size == 0: raise ValueError(f"{name} must not be empty") out = arr.astype(np.float64) if not np.isfinite(out).all(): raise ValueError(f"{name} contains non-finite values (NaN or inf)") return out
def _as_rate(sample_rate_hz: int) -> int: if isinstance(sample_rate_hz, bool) or not isinstance(sample_rate_hz, int | np.integer): raise ValueError(f"sample_rate_hz must be an int, got {sample_rate_hz!r}") rate = int(sample_rate_hz) if rate <= 0: raise ValueError(f"sample_rate_hz must be > 0, got {rate}") return rate
def _db_power(power: float) -> float: return 10.0 * math.log10(max(power, _POWER_FLOOR))
# --------------------------------------------------------------------------------------# S1: bandwidth# --------------------------------------------------------------------------------------
def estimate_bandwidth_hz( audio: npt.ArrayLike, sample_rate_hz: int, *, floor_db: float, params: BandwidthParams | None = None,) -> float: """Effective bandwidth: the highest frequency still within ``floor_db`` of the in-band level.
Method: Hann STFT (hop = ``n_fft/2``); keep *active* frames (within ``params.active_within_db`` of the loudest); average their power into a long-term average spectrum (LTAS) in dB; median-filter it over ``params.smooth_hz`` so isolated narrow spikes cannot masquerade as bandwidth; take the reference level as the median of the smoothed LTAS over ``[ref_low_hz, min(ref_high_hz, Nyquist)]``; return the centre frequency of the highest bin whose smoothed level is ``>= reference - floor_db``.
The result is quantised to the FFT bin spacing ``sample_rate_hz / n_fft_samples``. Audio upsampled from 16 kHz to 48 kHz reports about 8 kHz *provided* ``floor_db`` is smaller than the resampler's stop-band attenuation (choose it per resampler/ source).
Args: audio: Mono waveform, shape ``(num_samples,)``. sample_rate_hz: Sample rate in Hz. floor_db: How far below the reference level still counts as "content" (> 0). params: Analysis parameters; defaults to :class:`BandwidthParams` defaults.
Returns: Bandwidth in Hz, in ``(0, sample_rate_hz / 2]``.
Raises: SilentAudioError: if the waveform is digitally silent. ValueError: on invalid input or if the reference band lies above Nyquist. """ x = _as_audio(audio) rate = _as_rate(sample_rate_hz) _check_pos(floor_db, "floor_db") p = BandwidthParams() if params is None else params
n_fft = p.n_fft_samples nyquist_hz = rate / 2 bin_hz = rate / n_fft if p.ref_low_hz >= nyquist_hz: raise ValueError(f"ref_low_hz {p.ref_low_hz} is not below Nyquist {nyquist_hz} Hz")
power = stft_magnitude(x, n_fft, n_fft // 2) ** 2 # (frames, bins) frame_energy = power.sum(axis=1) loudest = float(np.max(frame_energy)) if loudest <= 0.0: raise SilentAudioError("audio is digitally silent; bandwidth is undefined") active = frame_energy >= loudest * 10.0 ** (-p.active_within_db / 10.0) ltas_db = 10.0 * np.log10(power[active].mean(axis=0) + _POWER_FLOOR)
kernel = max(1, round(p.smooth_hz / bin_hz)) | 1 # medfilt needs an odd length half = kernel // 2 padded = np.pad(ltas_db, half, mode="edge") # medfilt zero-pads; edge-pad instead smooth = np.asarray(signal.medfilt(padded, kernel_size=kernel), dtype=np.float64)[ half : half + ltas_db.shape[0] ]
freqs_hz = np.arange(ltas_db.shape[0], dtype=np.float64) * bin_hz ref_band = (freqs_hz >= p.ref_low_hz) & (freqs_hz <= min(p.ref_high_hz, nyquist_hz)) if not ref_band.any(): raise ValueError( f"no FFT bin in the reference band [{p.ref_low_hz}, {p.ref_high_hz}] Hz " f"(n_fft_samples={n_fft}, sample_rate_hz={rate})" ) reference_db = float(np.median(smooth[ref_band])) passing = np.flatnonzero(smooth >= reference_db - floor_db) return float(freqs_hz[int(passing[-1])])
# --------------------------------------------------------------------------------------# S2: clipping, silence, loudness# --------------------------------------------------------------------------------------
def clipping_ratio(audio: npt.ArrayLike, *, threshold: float) -> float: """Fraction of samples with ``|x| >= threshold``.
Args: audio: Mono waveform. threshold: Magnitude counted as clipped, in ``(0, 1]``.
Returns: Ratio in ``[0, 1]``. """ x = _as_audio(audio) if not (math.isfinite(threshold) and 0.0 < threshold <= 1.0): raise ValueError(f"threshold must be in (0, 1], got {threshold!r}") return float(np.mean(np.abs(x) >= threshold))
def silence_ratio( audio: npt.ArrayLike, sample_rate_hz: int, *, frame_ms: float, silence_dbfs: float) -> float: """Fraction of non-overlapping frames whose RMS is below ``silence_dbfs``.
The last, possibly shorter frame is included with its own RMS; audio shorter than one frame forms a single frame.
Args: audio: Mono waveform. sample_rate_hz: Sample rate in Hz. frame_ms: Frame length in ms (> 0). silence_dbfs: RMS level (dBFS) below which a frame is silent.
Returns: Ratio in ``[0, 1]``. """ x = _as_audio(audio) rate = _as_rate(sample_rate_hz) _check_pos(frame_ms, "frame_ms") _check_finite(silence_dbfs, "silence_dbfs") frame_len = max(1, round(rate * frame_ms / 1000.0)) starts = np.arange(0, x.shape[0], frame_len) sums = np.add.reduceat(x * x, starts) counts = np.diff(np.append(starts, x.shape[0])) frame_db = 10.0 * np.log10(sums / counts + _POWER_FLOOR) return float(np.mean(frame_db < silence_dbfs))
def loudness_dbfs(audio: npt.ArrayLike) -> float: """Whole-signal RMS level in dBFS (``20 log10(rms)``, full-scale amplitude 1.0).
This is an unweighted RMS level, *not* LUFS (no K-weighting, no gating). Digital silence returns -240.0 instead of ``-inf``. """ x = _as_audio(audio) return _db_power(float(np.mean(x * x)))
# --------------------------------------------------------------------------------------# S6: pitch tracking (YIN)# --------------------------------------------------------------------------------------
@dataclass(frozen=True)class PitchTrack: """Frame-wise pitch track on a regular grid.
Frame ``t`` is centred on sample ``center_samples[t] = t * hop_samples`` (the signal is zero-padded by half a window at both ends so that the file edges are covered).
Attributes: center_samples: Centre sample of each frame, shape ``(num_frames,)``. voiced: Whether F0 was detected, shape ``(num_frames,)``. f0_hz: F0 in Hz, ``nan`` where unvoiced. hnr_db: Harmonics-to-noise ratio in dB (clipped to +-``hnr_max_db``), ``nan`` where unvoiced. """
center_samples: IntArray voiced: BoolArray f0_hz: FloatArray hnr_db: FloatArray
def _yin_chunk( frames: FloatArray, *, tau_min: int, tau_max: int, threshold: float, energy_floor_dbfs: float, hnr_max_db: float,) -> tuple[BoolArray, FloatArray, FloatArray]: """YIN on a batch of frames ``(F, W)``; returns ``(voiced, f0_samples, hnr_db)``.
``f0_samples`` is the (parabolically refined) period in samples, ``nan`` if unvoiced. """ num_frames, width = frames.shape n_lags = tau_max + 2 # lags 0..tau_max+1 (tau_max+1 is needed for the interpolation) integ = width - n_lags + 1 # integration length so that j + tau stays inside the frame nfft = 1 << (integ + width - 1).bit_length()
head = frames[:, :integ] corr = np.fft.irfft( np.conj(np.fft.rfft(head, nfft, axis=1)) * np.fft.rfft(frames, nfft, axis=1), nfft, axis=1, )[:, :n_lags] csum = np.concatenate( [np.zeros((num_frames, 1)), np.cumsum(frames * frames, axis=1)], axis=1 ) # (F, W + 1) energy0 = csum[:, integ : integ + 1] # (F, 1) taus = np.arange(n_lags) energy1 = csum[:, integ + taus] - csum[:, taus] # (F, n_lags) diff = np.maximum(energy0 + energy1 - 2.0 * corr, 0.0) diff[:, 0] = 0.0
# Cumulative-mean-normalised difference function (YIN step 3). cum = np.cumsum(diff[:, 1:], axis=1) cmnd = np.ones((num_frames, n_lags)) np.divide(diff[:, 1:] * taus[1:], cum, out=cmnd[:, 1:], where=cum > _REL_EPS * energy0)
# Absolute threshold (step 4): first lag below it, then walk down to the local minimum. below = cmnd[:, tau_min : tau_max + 1] < threshold has_dip = below.any(axis=1) idx = np.argmax(below, axis=1) + tau_min rows = np.arange(num_frames) while True: advance = has_dip & (idx < tau_max) & (cmnd[rows, idx + 1] < cmnd[rows, idx]) if not advance.any(): break idx = idx + advance
# Parabolic interpolation (step 5). c_prev, c_mid, c_next = cmnd[rows, idx - 1], cmnd[rows, idx], cmnd[rows, idx + 1] curvature = c_prev - 2.0 * c_mid + c_next shift = np.zeros(num_frames) np.divide(0.5 * (c_prev - c_next), curvature, out=shift, where=np.abs(curvature) > 1e-12) period = idx + np.clip(shift, -1.0, 1.0)
# HNR from the normalised autocorrelation at the period (best of idx-1, idx, idx+1). best_r = np.zeros(num_frames) for offset in (-1, 0, 1): lag = idx + offset denom = np.sqrt(energy0[:, 0] * energy1[rows, lag]) r_norm = np.zeros(num_frames) np.divide(corr[rows, lag], denom, out=r_norm, where=denom > 0.0) best_r = np.maximum(best_r, r_norm) best_r = np.clip(best_r, _REL_EPS, 1.0 - _REL_EPS) hnr = np.clip(10.0 * np.log10(best_r / (1.0 - best_r)), -hnr_max_db, hnr_max_db)
frame_db = 10.0 * np.log10(np.mean(frames * frames, axis=1) + _POWER_FLOOR) voiced = has_dip & (frame_db >= energy_floor_dbfs) return ( voiced, np.where(voiced, period, np.nan), np.where(voiced, hnr, np.nan), )
def track_pitch(audio: npt.ArrayLike, sample_rate_hz: int, cfg: AcousticConfig) -> PitchTrack: """Track F0 and HNR with a numpy YIN implementation.
Per frame (``cfg.f0_frame_ms`` window, ``cfg.f0_hop_ms`` hop): difference function via FFT cross-correlation, cumulative-mean normalisation, first dip below ``cfg.yin_threshold`` within the lag range of ``[f0_min_hz, f0_max_hz]``, descent to the local minimum, parabolic refinement. A frame is voiced when a dip exists *and* its RMS is at least ``cfg.f0_energy_floor_dbfs``. HNR is ``10 log10(r / (1 - r))`` with ``r`` the normalised autocorrelation at the period, clipped to ``+-cfg.hnr_max_db``.
Args: audio: Mono waveform. sample_rate_hz: Sample rate in Hz; must satisfy ``sample_rate_hz >= 4 * f0_max_hz``. cfg: Configuration.
Raises: ValueError: on invalid input, or if the window is shorter than two periods of ``f0_min_hz`` at this sample rate, or the rate is too low for ``f0_max_hz``. """ x = _as_audio(audio) rate = _as_rate(sample_rate_hz) window = round(rate * cfg.f0_frame_ms / 1000.0) hop = round(rate * cfg.f0_hop_ms / 1000.0) tau_max = math.ceil(rate / cfg.f0_min_hz) tau_min = math.ceil(rate / cfg.f0_max_hz) if rate < 4 * cfg.f0_max_hz: raise ValueError( f"sample_rate_hz={rate} is too low for f0_max_hz={cfg.f0_max_hz} " "(need sample_rate_hz >= 4 * f0_max_hz)" ) if hop < 1 or window < 2 * tau_max + 2: raise ValueError( f"f0_frame_ms={cfg.f0_frame_ms} is too short for f0_min_hz={cfg.f0_min_hz} at " f"sample_rate_hz={rate}: need a window of >= {2 * tau_max + 2} samples, " f"got {window}" )
num_samples = x.shape[0] num_frames = (num_samples - 1) // hop + 1 pad = window // 2 padded = np.zeros(num_samples + 2 * pad + window) padded[pad : pad + num_samples] = x windows = np.lib.stride_tricks.sliding_window_view(padded, window)
voiced = np.zeros(num_frames, dtype=np.bool_) f0 = np.full(num_frames, np.nan) hnr = np.full(num_frames, np.nan) for first in range(0, num_frames, _CHUNK_FRAMES): stop = min(first + _CHUNK_FRAMES, num_frames) # Frame t spans padded[t*hop : t*hop + window], i.e. is centred on sample t*hop. chunk = np.ascontiguousarray(windows[first * hop : stop * hop : hop]) v, period, h = _yin_chunk( chunk, tau_min=tau_min, tau_max=tau_max, threshold=cfg.yin_threshold, energy_floor_dbfs=cfg.f0_energy_floor_dbfs, hnr_max_db=cfg.hnr_max_db, ) voiced[first:stop] = v f0[first:stop] = rate / period hnr[first:stop] = h centers = np.arange(num_frames, dtype=np.int64) * hop return PitchTrack(center_samples=centers, voiced=voiced, f0_hz=f0, hnr_db=hnr)
# --------------------------------------------------------------------------------------# S6: per-word features# --------------------------------------------------------------------------------------
@dataclass(frozen=True)class WordFeatures: """Acoustic features of one word. ``None`` means *not measurable*, never zero.
* Word shorter than ``cfg.min_word_ms``: every field except ``duration_ms`` is ``None``. * Word measured but without a single voiced frame: ``voicing_ratio`` is ``0.0`` and ``median_f0_hz`` / ``hnr_db`` are ``None``.
Attributes: duration_ms: Analysed duration (after clipping to the audio end). voicing_ratio: Fraction of the pitch frames centred inside the word that are voiced. median_f0_hz: Median F0 over voiced frames. hnr_db: Median per-frame HNR over voiced frames. rms_dbfs: RMS level of the word's samples. spectral_tilt_db_per_octave: Slope of log power versus log2 frequency (negative = energy falls with frequency; shouted speech is flatter, i.e. less negative). """
duration_ms: int voicing_ratio: float | None median_f0_hz: float | None hnr_db: float | None rms_dbfs: float | None spectral_tilt_db_per_octave: float | None
@property def measurable(self) -> bool: """False when the word was too short to measure.""" return self.voicing_ratio is not None
def _spectral_tilt(word: FloatArray, rate: int, cfg: AcousticConfig) -> float | None: """Slope (dB per octave) of band power versus log2 frequency, or ``None`` if undefined.
The Hann-windowed power spectrum (averaged over ``tilt_n_fft_samples``-long frames for long words; a word shorter than the FFT size gets one window of its own length, zero-padded) is averaged into ``cfg.tilt_num_bands`` bands equally spaced in log2 frequency; a straight line is fitted to band dB versus band-centre log2 frequency. Binning in log-frequency stops the dense high-frequency FFT bins from dominating. """ n_fft = cfg.tilt_n_fft_samples if word.shape[0] <= n_fft: frames = (word * np.hanning(word.shape[0]))[np.newaxis, :] else: win = np.hanning(n_fft) frames = np.lib.stride_tricks.sliding_window_view(word, n_fft)[:: n_fft // 2] * win power = np.mean(np.abs(np.fft.rfft(frames, n_fft, axis=1)) ** 2, axis=0) if float(power.sum()) <= 0.0: return None
freqs_hz = np.arange(power.shape[0]) * rate / n_fft high_hz = min(cfg.tilt_high_hz, rate / 2) if cfg.tilt_low_hz >= high_hz: return None edges = np.linspace(math.log2(cfg.tilt_low_hz), math.log2(high_hz), cfg.tilt_num_bands + 1) centers: list[float] = [] levels_db: list[float] = [] for lo, hi in pairwise(edges): mask = (freqs_hz >= 2.0**lo) & (freqs_hz < 2.0**hi) if mask.any(): centers.append(float(lo + hi) / 2.0) levels_db.append(_db_power(float(power[mask].mean()))) if len(centers) < 3: return None slope = np.polyfit(np.asarray(centers), np.asarray(levels_db), 1)[0] return float(slope)
def word_features( audio: npt.ArrayLike, sample_rate_hz: int, words: Sequence[TimedWord], cfg: AcousticConfig,) -> list[WordFeatures]: """Per-word voicing, F0, HNR, RMS and spectral tilt (S6).
The pitch track is computed once over the whole waveform; a word owns the frames whose centre lies in ``[start, end)`` (so frames at a boundary see a little context from the neighbouring word). RMS and tilt use the word's own samples only.
Args: audio: Mono waveform of the segment. sample_rate_hz: Sample rate in Hz. words: Words with segment-relative ``start_ms`` / ``end_ms``; need not be sorted. cfg: Configuration.
Returns: One :class:`WordFeatures` per word, in input order; ``[]`` for no words.
Raises: ValueError: on invalid audio; if a word starts at or after the end of the audio; or if a word ends more than ``cfg.word_end_tolerance_ms`` after it (smaller overshoots are clipped to the audio end). """ x = _as_audio(audio) rate = _as_rate(sample_rate_hz) if not words: return []
num_samples = x.shape[0] audio_ms = num_samples * 1000.0 / rate track = track_pitch(x, rate, cfg)
out: list[WordFeatures] = [] for word in words: if word.start_ms >= audio_ms: raise ValueError( f"word {word.text!r} starts at {word.start_ms} ms, at or after the end of the " f"audio ({audio_ms:.1f} ms)" ) if word.end_ms > audio_ms + cfg.word_end_tolerance_ms: raise ValueError( f"word {word.text!r} ends at {word.end_ms} ms, more than " f"{cfg.word_end_tolerance_ms} ms after the end of the audio ({audio_ms:.1f} ms)" ) end_ms = min(word.end_ms, math.floor(audio_ms)) duration_ms = max(0, end_ms - word.start_ms) if duration_ms < cfg.min_word_ms: out.append(WordFeatures(duration_ms, None, None, None, None, None)) continue
start = round(word.start_ms * rate / 1000.0) stop = min(round(end_ms * rate / 1000.0), num_samples) samples = x[start:stop] in_word = (track.center_samples >= start) & (track.center_samples < stop) num_frames = int(in_word.sum()) if samples.shape[0] == 0 or num_frames == 0: out.append(WordFeatures(duration_ms, None, None, None, None, None)) continue
voiced = in_word & track.voiced num_voiced = int(voiced.sum()) out.append( WordFeatures( duration_ms=duration_ms, voicing_ratio=num_voiced / num_frames, median_f0_hz=float(np.median(track.f0_hz[voiced])) if num_voiced else None, hnr_db=float(np.median(track.hnr_db[voiced])) if num_voiced else None, rms_dbfs=_db_power(float(np.mean(samples * samples))), spectral_tilt_db_per_octave=_spectral_tilt(samples, rate, cfg), ) ) return out
# --------------------------------------------------------------------------------------# S6: speaker-relative style scores# --------------------------------------------------------------------------------------
def _logistic(value: float, center: float, scale: float) -> float: """``sigmoid((value - center) / scale)``, numerically safe.""" z = max(-_LOGISTIC_CLIP, min(_LOGISTIC_CLIP, (value - center) / scale)) return 1.0 / (1.0 + math.exp(-z))
def whisper_scores(features: Sequence[WordFeatures], cfg: AcousticConfig) -> WordStyleScore: """Per-word whisper probability: unvoiced, noise-like, but with energy present.
``score = f_unvoiced * f_noise * f_energy`` (a soft AND), each factor a logistic ``sigmoid((x - center) / scale)`` with centre/scale from ``cfg``:
* ``f_unvoiced`` on ``x = 1 - voicing_ratio`` (``whisper_unvoiced_*``); * ``f_noise`` on ``x = -hnr_db`` with centre ``-whisper_hnr_center_db`` (low HNR is whisper-like); words with no voiced frame have no HNR and get factor 1.0; * ``f_energy`` on ``x = rms_dbfs`` (``whisper_energy_*``), so silence is not a whisper.
Words that are not measurable (too short) score ``None``. """ scores: list[float | None] = [] for feat in features: if feat.voicing_ratio is None or feat.rms_dbfs is None: scores.append(None) continue f_unvoiced = _logistic( 1.0 - feat.voicing_ratio, cfg.whisper_unvoiced_center, cfg.whisper_unvoiced_scale ) f_noise = ( 1.0 if feat.hnr_db is None else _logistic(-feat.hnr_db, -cfg.whisper_hnr_center_db, cfg.whisper_hnr_scale_db) ) f_energy = _logistic( feat.rms_dbfs, cfg.whisper_energy_center_dbfs, cfg.whisper_energy_scale_db ) scores.append(f_unvoiced * f_noise * f_energy) return WordStyleScore(style="whisper", scores=tuple(scores), source=WHISPER_SOURCE)
@dataclass(frozen=True)class SpeakerBaseline: """A speaker's own reference levels (medians over their voiced words).
Attributes: median_rms_dbfs: Median word RMS level. median_f0_hz: Median of the words' median F0. median_tilt_db_per_octave: Median spectral tilt. num_voiced_words: How many words the medians are based on. """
median_rms_dbfs: float median_f0_hz: float median_tilt_db_per_octave: float num_voiced_words: int
def speaker_baseline(features: Sequence[WordFeatures], cfg: AcousticConfig) -> SpeakerBaseline: """Medians over the speaker's *voiced* words (``voicing_ratio >= baseline_min_voicing_ratio``).
Pass the features of **all** of one speaker's words (many segments), not of a single segment: the median is only a baseline if shouted words are a minority.
Raises: ValueError: if fewer than ``cfg.baseline_min_voiced_words`` voiced words exist. """ voiced = [ f for f in features if f.voicing_ratio is not None and f.voicing_ratio >= cfg.baseline_min_voicing_ratio and f.median_f0_hz is not None and f.rms_dbfs is not None and f.spectral_tilt_db_per_octave is not None ] if len(voiced) < cfg.baseline_min_voiced_words: raise BaselineError( f"speaker baseline needs >= {cfg.baseline_min_voiced_words} voiced words, " f"got {len(voiced)} of {len(features)}" )
def median_of(values: list[float]) -> float: return float(np.median(np.asarray(values)))
return SpeakerBaseline( median_rms_dbfs=median_of([f.rms_dbfs for f in voiced if f.rms_dbfs is not None]), median_f0_hz=median_of([f.median_f0_hz for f in voiced if f.median_f0_hz is not None]), median_tilt_db_per_octave=median_of( [ f.spectral_tilt_db_per_octave for f in voiced if f.spectral_tilt_db_per_octave is not None ] ), num_voiced_words=len(voiced), )
def shout_scores( features: Sequence[WordFeatures], speaker_baseline: SpeakerBaseline, cfg: AcousticConfig,) -> WordStyleScore: """Per-word shout probability relative to the speaker's own baseline (no absolute levels).
With deviations from the baseline
* ``delta_db = rms_dbfs - baseline.median_rms_dbfs``, * ``f0_st = 12 * log2(median_f0_hz / baseline.median_f0_hz)`` (F0 ratio in semitones), * ``delta_tilt = tilt - baseline.median_tilt`` (dB/octave; positive = flatter),
the score is ``sigmoid((z - shout_center) / shout_scale)`` with ``z = w_db * delta_db + w_f0 * f0_st + w_tilt * delta_tilt``.
A word that is too short, or has no F0 (unvoiced), cannot be judged and scores ``None`` ("not marked"), not 0. """ scores: list[float | None] = [] for feat in features: if ( feat.median_f0_hz is None or feat.rms_dbfs is None or feat.spectral_tilt_db_per_octave is None ): scores.append(None) continue delta_db = feat.rms_dbfs - speaker_baseline.median_rms_dbfs f0_st = 12.0 * math.log2(feat.median_f0_hz / speaker_baseline.median_f0_hz) delta_tilt = feat.spectral_tilt_db_per_octave - speaker_baseline.median_tilt_db_per_octave z = ( cfg.shout_weight_db * delta_db + cfg.shout_weight_f0_semitones * f0_st + cfg.shout_weight_tilt * delta_tilt ) scores.append(_logistic(z, cfg.shout_center, cfg.shout_scale)) return WordStyleScore(style="shout", scores=tuple(scores), source=SHOUT_SOURCE)
def phrase_support(style: WordStyleScore) -> WordStyleScore: """Cap each word's style score by its strongest measured neighbour.
Whispering and shouting are properties of a phrase, not of one word. A lone short word ("de", "ve", "bir") scores high easily: its aligned window is mostly a voiceless consonant, or it carries ordinary lexical stress. The pilot smoke run (2026-10-08) lost 42 of 258 segments that way (``short_style_run`` / ``ambiguous_style`` on single words). So ``s'[i] = min(s[i], max(s[i-1], s[i+1]))`` over the neighbours that have a score. A word with no measured neighbour gets ``None`` (not judged). A real style spanning two or more words keeps its scores; two adjacent middle-band words stay ambiguous.
Returns: Same style, scores capped, source suffixed with ``+phrase``. """ raw = style.scores out: list[float | None] = [] for index, score in enumerate(raw): neighbours = [ raw[j] for j in (index - 1, index + 1) if 0 <= j < len(raw) and raw[j] is not None ] if score is None or not neighbours: out.append(None) continue support = max(n for n in neighbours if n is not None) out.append(min(score, support)) return WordStyleScore(style=style.style, scores=tuple(out), source=style.source + "+phrase")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261"""S5 — CTC forced alignment of a transcript to character CTC emissions (Viterbi).
Given log-softmax emissions ``[num_frames, vocab]`` from a character CTC model (e.g.``mpoyraz_ctc_tr``) and the primary transcript, find the single most likely CTC path thatemits exactly the transcript's characters (words separated by the model's word-delimitertoken) and read word intervals off that path. Plain numpy, no torchaudio dependency(``torchaudio.functional.forced_align`` is deprecated in the 2.8 line, R8).
Text handling: each transcript token is NFC + ``tr_lower``-ed, circumflexes are folded(â/î/û → a/i/u: the model has no such letters) and characters outside the vocabulary thatare punctuation are dropped for alignment only. A token with no alignable character(``…``, ``-``) is glued to the previous word (or the next one at the start), so thereturned words keep their original spelling and punctuation. Any other characteroutside the vocabulary (digits, foreign letters) makes the segment unalignable."""
from __future__ import annotations
import itertoolsimport mathimport unicodedatafrom collections.abc import Mapping, Sequencefrom dataclasses import dataclass, fieldfrom typing import TYPE_CHECKING
from nida.data.types import TimedWordfrom nida.text.turkish import nfc, tr_lower
if TYPE_CHECKING: import numpy as np from numpy.typing import NDArray
__all__ = ["AlignmentResult", "align_words", "alignment_units"]
_CIRCUMFLEX_FOLD = str.maketrans({"â": "a", "î": "i", "û": "u"})# Typographic apostrophes (U+2019, U+02BC) are the same letter-joining apostrophe as U+0027._APOSTROPHES = str.maketrans({"\u2019": "'", "\u02bc": "'"})#: Allowed difference between ``num_frames * hop`` and the segment duration, in frames#: (wav2vec2 yields ``floor((samples - 400) / 320) + 1`` frames, i.e. up to ~1 frame short).FRAME_SLACK = 2
@dataclass(frozen=True)class AlignmentResult: """Either ``words`` (aligned) or ``failure`` (a machine-readable reason) is set."""
words: tuple[TimedWord, ...] | None failure: str | None details: Mapping[str, object] = field(default_factory=dict)
def __post_init__(self) -> None: if (self.words is None) == (self.failure is None): raise ValueError("AlignmentResult needs exactly one of words / failure") if self.words is not None and self.details: raise ValueError("an aligned result carries no failure details")
def alignment_units( tokens: Sequence[str], vocab: Mapping[str, int]) -> tuple[list[str], list[str]] | str: """Group transcript tokens into alignable words.
Returns: ``(display_words, alignment_strings)`` of equal length, or a failure string ``"unalignable_chars:<chars>"`` / ``"no_alignable_text"``. Apostrophes join letters only: leading/trailing ones are not aligned, and a token made only of punctuation (``…``, ``—``, ``'``) is glued to the previous word (or the next one at the start) *without* the space between them (``a — b`` → ``a—``, ``b``), because a returned word cannot contain whitespace. """ display: list[str] = [] targets: list[str] = [] pending_prefix = "" bad: set[str] = set() for raw in tokens: token = nfc(raw) if not token or any(ch.isspace() for ch in token): raise ValueError(f"invalid transcript token {raw!r}") chars: list[str] = [] for ch in tr_lower(token).translate(_CIRCUMFLEX_FOLD).translate(_APOSTROPHES): if ch in vocab: chars.append(ch) elif unicodedata.category(ch).startswith("P"): continue else: bad.add(ch) chars = list("".join(chars).strip("'")) if not chars: if display: display[-1] += token else: pending_prefix += token continue display.append(pending_prefix + token) pending_prefix = "" targets.append("".join(chars)) if bad: return "unalignable_chars:" + "".join(sorted(bad)) if not targets: return "no_alignable_text" return display, targets
def _viterbi(log_probs: NDArray[np.float64], labels: Sequence[int], blank: int) -> list[int] | None: """Best CTC state path; ``None`` if the label sequence cannot fit in the frames.
States are the blank-extended sequence ``b l1 b l2 b … lN b`` (index ``2k+1`` is label ``k``). Returns the state index for every frame. """ import numpy as np
num_frames = log_probs.shape[0] ext = np.full(2 * len(labels) + 1, blank, dtype=np.int64) ext[1::2] = labels num_states = ext.shape[0] # A skip s-2 -> s is allowed into a label that differs from the label two back. can_skip = np.zeros(num_states, dtype=bool) can_skip[3::2] = ext[3::2] != ext[1:-2:2] neg_inf = -np.inf score = np.full(num_states, neg_inf) score[0] = log_probs[0, ext[0]] if num_states > 1: score[1] = log_probs[0, ext[1]] back = np.zeros((num_frames, num_states), dtype=np.int8) # 0 stay, 1 step, 2 skip for t in range(1, num_frames): stay = score step = np.concatenate(([neg_inf], score[:-1])) skip = np.concatenate(([neg_inf, neg_inf], score[:-2])) skip = np.where(can_skip, skip, neg_inf) stacked = np.stack([stay, step, skip]) choice = np.argmax(stacked, axis=0) best = np.take_along_axis(stacked, choice[None, :], axis=0)[0] score = best + log_probs[t, ext] back[t] = choice final_candidates = [num_states - 1] + ([num_states - 2] if num_states > 1 else []) end = max(final_candidates, key=lambda s: score[s]) if not math.isfinite(float(score[end])): return None path = [0] * num_frames state = end for t in range(num_frames - 1, -1, -1): path[t] = state state -= int(back[t, state]) return path
def align_words( tokens: Sequence[str], log_probs: NDArray[np.float32], vocab: Mapping[str, int], *, blank_token: str, word_delimiter: str, frame_hop_ms: float, duration_ms: int,) -> AlignmentResult: """Align transcript ``tokens`` (whitespace-split words) to CTC ``log_probs``.
Args: tokens: Transcript words in order. log_probs: ``[num_frames, vocab_size]`` emissions. Log-softmax is re-applied here (idempotent on log-probabilities), so raw logits cannot inflate ``align_score``. ``-inf`` entries are allowed; NaN and ``+inf`` are not. vocab: Token → id (characters, ``blank_token``, ``word_delimiter``). blank_token: CTC blank (``[PAD]`` for wav2vec2 HF models). word_delimiter: Word separator token (``|``). frame_hop_ms: Frame stride in ms (20 for wav2vec2). duration_ms: Segment length. ``num_frames * frame_hop_ms`` must be within :data:`FRAME_SLACK` frames of it (catches unresampled audio); word ends are clamped to it.
Returns: :class:`AlignmentResult` with words carrying ``align_score`` = mean emission probability of the word's character frames, or a failure reason (``unalignable_chars``, ``no_alignable_text``, ``too_few_frames``, ``no_path``, ``words_beyond_audio``).
Raises: ValueError: malformed inputs (shape, vocab ids not ``0..V-1``, NaN/+inf, bad hop, frame count inconsistent with the duration). """ import numpy as np
if log_probs.ndim != 2 or log_probs.shape[1] != len(vocab): raise ValueError(f"log_probs shape {log_probs.shape} does not match vocab {len(vocab)}") if sorted(vocab.values()) != list(range(len(vocab))): raise ValueError("vocab ids must be exactly 0..V-1") if np.any(np.isnan(log_probs)) or np.any(np.isposinf(log_probs)): raise ValueError("log_probs contain NaN or +inf") if blank_token not in vocab or word_delimiter not in vocab: raise ValueError("blank or word delimiter missing from vocab") if not (math.isfinite(frame_hop_ms) and frame_hop_ms >= 1): raise ValueError(f"frame_hop_ms must be a finite number >= 1 ms, got {frame_hop_ms!r}") if type(duration_ms) is not int or duration_ms <= 0: raise ValueError(f"invalid duration_ms {duration_ms!r}") if abs(log_probs.shape[0] * frame_hop_ms - duration_ms) > FRAME_SLACK * frame_hop_ms: raise ValueError( f"{log_probs.shape[0]} frames x {frame_hop_ms} ms do not match {duration_ms} ms" ) with np.errstate(invalid="ignore"): lp = log_probs.astype(np.float64) row_max = np.max(lp, axis=1, keepdims=True) if not np.all(np.isfinite(row_max)): raise ValueError("a frame has no finite log-probability") lp = lp - (row_max + np.log(np.sum(np.exp(lp - row_max), axis=1, keepdims=True))) special = {blank_token, word_delimiter} char_vocab = {tok: idx for tok, idx in vocab.items() if len(tok) == 1 and tok not in special} units = alignment_units(tokens, char_vocab) if isinstance(units, str): reason, _, chars = units.partition(":") return AlignmentResult(None, reason, {"chars": chars} if chars else {}) display, targets = units
labels: list[int] = [] owner: list[int] = [] # word index for each label, -1 for delimiters for index, target in enumerate(targets): if index: labels.append(vocab[word_delimiter]) owner.append(-1) for ch in target: labels.append(char_vocab[ch]) owner.append(index) repeats = sum(1 for a, b in itertools.pairwise(labels) if a == b) if log_probs.shape[0] < len(labels) + repeats: return AlignmentResult( None, "too_few_frames", {"frames": int(log_probs.shape[0]), "needed": len(labels) + repeats}, ) path = _viterbi(lp, labels, vocab[blank_token]) if path is None: return AlignmentResult(None, "no_path")
first: list[int | None] = [None] * len(targets) last: list[int | None] = [None] * len(targets) probs: list[list[float]] = [[] for _ in targets] for frame, state in enumerate(path): if state % 2 == 0: continue word = owner[state // 2] if word < 0: continue if first[word] is None: first[word] = frame last[word] = frame probs[word].append(math.exp(float(lp[frame, labels[state // 2]]))) words: list[TimedWord] = [] for index, text in enumerate(display): start_frame, end_frame = first[index], last[index] if start_frame is None or end_frame is None: return AlignmentResult(None, "no_path", {"word_index": index}) start_ms = min(round(start_frame * frame_hop_ms), duration_ms - 1) end_ms = min(round((end_frame + 1) * frame_hop_ms), duration_ms) end_ms = max(end_ms, start_ms + 1) if words and start_ms < words[-1].end_ms: # Only reachable through the end clamp (emissions slightly longer than the # audio): words squeezed past the end cannot be timed, never let them overlap. return AlignmentResult(None, "words_beyond_audio", {"word_index": index}) score = sum(probs[index]) / len(probs[index]) words.append(TimedWord(text, start_ms, end_ms, score)) return AlignmentResult(tuple(words), None)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283"""S4 / S5 filters: dual-ASR agreement and forced-alignment sanity checks.
Pure functions; every threshold comes from :class:`AsrFilterConfig` (``configs/data/asr_filter.yaml``). A check returns ``None`` when the segment passes and otherwise amachine-readable reason string from a fixed set, which the caller writes to quarantine.
The agreement metric is computed on transcripts **with filler words removed**(docs/03-data-pipeline.md S4): the two ASR models legitimately disagree on fillers, andfiltering on them would throw away exactly the expressive segments we want."""
from __future__ import annotations
import mathfrom collections.abc import Mapping, Sequencefrom dataclasses import dataclassfrom itertools import pairwisefrom typing import Literal, get_args
from nida.bench.textmetrics import cer_counts, normalize_for_scoring, strip_fillersfrom nida.data.types import TimedWord
__all__ = [ "ALIGNMENT_REASONS", "TRANSCRIPT_REASONS", "AlignmentReason", "AsrFilterConfig", "TranscriptReason", "asr_agreement", "check_alignment", "check_transcripts",]
TranscriptReason = Literal["language", "asr_disagreement", "empty_transcript"]AlignmentReason = Literal[ "align_score", "chars_per_s_low", "chars_per_s_high", "word_outside_segment", "words_not_monotonic",]TRANSCRIPT_REASONS: tuple[str, ...] = get_args(TranscriptReason)ALIGNMENT_REASONS: tuple[str, ...] = get_args(AlignmentReason)
_MS_PER_S = 1000 # unit conversion, not a threshold
# ASCII-only case folding for language codes. Built-in case mapping is avoided: "ID" must# not be mapped through Turkish rules ("ID" -> "ıd"), nor through locale-dependent ones._ASCII_LOWER = str.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")
_CONFIG_FIELDS: tuple[str, ...] = ( "max_cer", "allowed_languages", "min_chars_per_s", "max_chars_per_s", "min_align_score",)
def _norm_language(code: str) -> str: return code.strip().translate(_ASCII_LOWER)
def _real_number(mapping: Mapping[str, object], name: str) -> float: value = mapping[name] if isinstance(value, bool) or not isinstance(value, int | float): raise ValueError(f"asr filter config: {name} must be a number, got {value!r}") number = float(value) if not math.isfinite(number): raise ValueError(f"asr filter config: {name} must be finite, got {value!r}") return number
@dataclass(frozen=True)class AsrFilterConfig: """Thresholds of the S4 / S5 filters; load with :meth:`from_mapping`.
Attributes: max_cer: Largest accepted CER between the filler-stripped transcripts, in [0, 1]. A CER exactly equal to it passes. allowed_languages: Accepted detected-language codes (ASCII, stored lowercase). min_chars_per_s: Smallest accepted letters+digits per second of speech span. max_chars_per_s: Largest accepted letters+digits per second of speech span. min_align_score: Smallest accepted mean per-word alignment score; the scale depends on the aligner. """
max_cer: float allowed_languages: tuple[str, ...] min_chars_per_s: float max_chars_per_s: float min_align_score: float
def __post_init__(self) -> None: for name in ("max_cer", "min_chars_per_s", "max_chars_per_s", "min_align_score"): if not math.isfinite(getattr(self, name)): raise ValueError(f"{name} must be finite, got {getattr(self, name)!r}") if not 0.0 <= self.max_cer <= 1.0: raise ValueError(f"max_cer must be in [0, 1], got {self.max_cer}") if self.min_chars_per_s < 0.0: raise ValueError(f"min_chars_per_s must be >= 0, got {self.min_chars_per_s}") if self.max_chars_per_s <= 0.0 or self.max_chars_per_s < self.min_chars_per_s: raise ValueError( f"max_chars_per_s ({self.max_chars_per_s}) must be > 0 and >= " f"min_chars_per_s ({self.min_chars_per_s})" ) if not self.allowed_languages: raise ValueError("allowed_languages must not be empty") for code in self.allowed_languages: if not code or not code.isascii() or not code.replace("-", "").isalpha(): raise ValueError(f"invalid language code {code!r}: expected ASCII letters/'-'") if code != _norm_language(code): raise ValueError(f"language code {code!r} must be lowercase") if len(set(self.allowed_languages)) != len(self.allowed_languages): raise ValueError(f"duplicate entries in allowed_languages {self.allowed_languages}")
@classmethod def from_mapping(cls, mapping: Mapping[str, object]) -> AsrFilterConfig: """Build a config from a parsed YAML mapping.
Language codes are stripped and lowercased (ASCII only).
Raises: ValueError: If ``mapping`` is not a mapping, has unknown or missing keys, a number is not a finite int/float (bools are rejected), or a bound or the language list is invalid. """ if not isinstance(mapping, Mapping): raise ValueError(f"asr filter config must be a mapping, got {type(mapping).__name__}") keys = set(mapping) unknown = sorted(str(key) for key in keys - set(_CONFIG_FIELDS)) missing = sorted(set(_CONFIG_FIELDS) - keys) if unknown or missing: raise ValueError(f"asr filter config: unknown keys {unknown}, missing keys {missing}") raw_languages = mapping["allowed_languages"] if isinstance(raw_languages, str) or not isinstance(raw_languages, Sequence): raise ValueError( f"asr filter config: allowed_languages must be a list, got {raw_languages!r}" ) languages: list[str] = [] for code in raw_languages: if not isinstance(code, str): raise ValueError(f"asr filter config: language code {code!r} is not a string") languages.append(_norm_language(code)) return cls( max_cer=_real_number(mapping, "max_cer"), allowed_languages=tuple(languages), min_chars_per_s=_real_number(mapping, "min_chars_per_s"), max_chars_per_s=_real_number(mapping, "max_chars_per_s"), min_align_score=_real_number(mapping, "min_align_score"), )
# --------------------------------------------------------------------------------------# S4: transcripts# --------------------------------------------------------------------------------------
def asr_agreement(primary: str, secondary: str) -> float: """Character error rate between two transcripts, ignoring fillers.
Both texts go through :func:`~nida.bench.textmetrics.normalize_for_scoring` (NFC, Turkish lowercase, punctuation removed, fillers canonicalised), fillers are removed, and the CER is taken over the space-joined tokens with ``primary`` as the reference.
Returns: 0.0 if both are empty after filler removal (e.g. ``"ıı"`` vs ``""``), 1.0 if exactly one is empty, otherwise the CER capped at 1.0 (lower = better agreement). """ ref = strip_fillers(normalize_for_scoring(primary)) hyp = strip_fillers(normalize_for_scoring(secondary)) if not ref and not hyp: return 0.0 if not ref or not hyp: return 1.0 rate = cer_counts(ref, hyp).rate() if rate is None: # unreachable: ref is non-empty raise ValueError("CER undefined for a non-empty reference") return min(rate, 1.0)
def check_transcripts( primary_text: str, secondary_text: str, language: str | None, cfg: AsrFilterConfig,) -> TranscriptReason | None: """S4 filter: empty transcript, language and dual-ASR agreement.
Checks run in this order and the first failure is returned:
1. ``"empty_transcript"``: the primary transcript has no token at all after normalisation. A fillers-only primary (``"hmm"``) is *not* empty: it is a valid sound-only segment. 2. ``"language"``: ``language`` is ``None`` or not in ``cfg.allowed_languages`` (case-insensitive exact match on the code). 3. ``"asr_disagreement"``: :func:`asr_agreement` is greater than ``cfg.max_cer`` (equal passes).
Args: primary_text: Primary ASR transcript (the label source). secondary_text: Secondary ASR transcript. language: Detected language code of the segment, or ``None`` if unknown. cfg: Thresholds.
Returns: ``None`` if the segment passes, else the reason. """ if not normalize_for_scoring(primary_text): return "empty_transcript" if language is None or _norm_language(language) not in cfg.allowed_languages: return "language" if asr_agreement(primary_text, secondary_text) > cfg.max_cer: return "asr_disagreement" return None
# --------------------------------------------------------------------------------------# S5: alignment# --------------------------------------------------------------------------------------
def _num_chars(text: str) -> int: """Letters and digits of the normalised text (fillers included, spaces excluded).""" return sum(1 for token in normalize_for_scoring(text) for ch in token if ch.isalnum())
def check_alignment( words: Sequence[TimedWord], duration_ms: int, cfg: AsrFilterConfig) -> AlignmentReason | None: """S5 filter: sanity of the forced-alignment output of one segment.
Word times are relative to the segment start. Checks run in this order and the first failure is returned:
1. ``"words_not_monotonic"``: a word starts before the previous one ends (touching is fine). 2. ``"word_outside_segment"``: a word ends after ``duration_ms``. 3. ``"align_score"``: the mean word alignment score is below ``cfg.min_align_score``, or any word has no (or a non-finite) score: a segment whose alignment cannot be verified is not accepted. The mean, not the minimum, is used so that a single hard-to-align filler or laugh does not discard an expressive segment. 4. ``"chars_per_s_low"`` / ``"chars_per_s_high"``: letters+digits of the normalised words (fillers included) per second of speech span (first word start to last word end) is below ``cfg.min_chars_per_s`` / above ``cfg.max_chars_per_s``. An empty word list (or words without any letter or digit) has rate 0 and is reported as ``"chars_per_s_low"`` rather than crashing the pipeline.
Thresholds are inclusive: values exactly equal to a limit pass.
Args: words: Aligned words of the primary transcript, in order. duration_ms: Segment duration in milliseconds, must be > 0. cfg: Thresholds.
Returns: ``None`` if the alignment looks sane, else the reason.
Raises: ValueError: If ``duration_ms`` is not a positive int. """ if isinstance(duration_ms, bool) or not isinstance(duration_ms, int) or duration_ms <= 0: raise ValueError(f"duration_ms must be a positive int, got {duration_ms!r}") if not words: return "chars_per_s_low" for previous, word in pairwise(words): if word.start_ms < previous.end_ms: return "words_not_monotonic" if any(word.end_ms > duration_ms for word in words): return "word_outside_segment" scores = [word.align_score for word in words] known = [score for score in scores if score is not None] if len(known) != len(scores) or not all(math.isfinite(score) for score in known): return "align_score" if math.fsum(known) / len(known) < cfg.min_align_score: return "align_score" span_ms = words[-1].end_ms - words[0].start_ms chars_per_s = sum(_num_chars(word.text) for word in words) * _MS_PER_S / span_ms if chars_per_s < cfg.min_chars_per_s: return "chars_per_s_low" if chars_per_s > cfg.max_chars_per_s: return "chars_per_s_high" return None12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307"""EARS -> latent dataset builder (ADR-0007, ``nida data-ears``).
EARS (Expressive Anechoic Recordings of Speech, CC BY-NC 4.0) provides English emotional,whispered and non-verbal speech. This module turns the selected files into a *latent datasetdirectory* in exactly the format of :mod:`nida.train.data` (records carry the optional key``"language": "en"``), so it can be trained together with Turkish datasets(``train --data A --data B``).
What is used (rules and mappings live in ``configs/data/ears.yaml``):
* ``emo_<emotion>_sentences``: reading transcript, emotion mapped (unmapped -> ``null``);* ``rainbow_NN_<style>`` / ``sentences_NN_<style>``: ``whisper`` -> the whole text wrapped in a whisper span (rendered by :mod:`nida.text.tags`), the plain styles -> plain text;* laughter/crying/screaming/coughing/throat-clearing files: just the event tag;* everything else is skipped and counted by reason.
Per speaker (one remote zip of ~564 MB, read with HTTP Range requests, see:mod:`nida.data.remote_zip`): list the archive -> decide on every member (skip / textquarantine, before any download) -> extract the selected members, convert 48 kHz -> 16 kHz mono-> measure. The speakers are handled in *waves* of ``speakers_per_wave``: one AudioVAE run(the same ``vae_encode`` worker and environment as the pilot, so the model is loaded once perwave, not once per speaker) encodes the wave's audio, then every speaker of the wave gets itsfloat16 shard, index records and ``done.json``. Layout::
<root>/plan.json seed, config digest, VAE pin, transcripts SHA-256 <root>/source/transcripts.json pinned reading transcripts <root>/speakers/pNNN/records.jsonl index rows of the speaker <root>/speakers/pNNN/quarantine.jsonl every quarantined item with its reason <root>/speakers/pNNN/done.json written last: the speaker is finished <root>/workers/vae/ worker requests/results of the current wave <root>/dataset/ latent dataset: index.jsonl, meta.json, shard-pNNN.npy <root>/report.md, <root>/stats.json <cache>/... raw members, 16 kHz wavs and latent arrays (local disk)
Resumable and idempotent: a speaker with ``done.json`` is skipped without any network access, aninterrupted wave continues (worker results are kept, already converted audio is reused), andthe dataset directory is reassembled from all finished speakers at the end of every run, soit is usable after any run. A run on a root made with another seed, config digest or VAE pin,or with different transcripts, is refused."""
from __future__ import annotations
import hashlibimport ioimport jsonimport loggingimport mathimport reimport shutilimport stringimport timefrom bisect import bisect_rightfrom collections import Counterfrom collections.abc import Callable, Mapping, Sequencefrom dataclasses import asdict, dataclass, fieldfrom pathlib import Pathfrom typing import Literal
import numpy as npimport numpy.typing as npt
# scipy ships no type stubs; the ignore is scoped to this single import (as in acoustic.py).from scipy import signal # type: ignore[import-untyped]
from nida.bench import envs as bench_envsfrom nida.bench import fetchfrom nida.bench.b1 import MAX_ERROR_FRACTION, _stream_runnerfrom nida.bench.protocol import ( WorkRequest, WorkResult, drop_results, load_results, read_summary, write_requests,)from nida.bench.registry import load_sources, require_approvedfrom nida.data import acoustic, envsfrom nida.data.ingest import IngestConfigfrom nida.data.pilot import DatasetConfigfrom nida.data.quarantine import QuarantineLogfrom nida.data.registry import DATA_MODELSfrom nida.data.remote_zip import RemoteZip, ZipMemberfrom nida.data.splits import assign_splitsfrom nida.data.types import QuarantineRecord, segment_idfrom nida.model.vocab import encode_textfrom nida.text import tagsfrom nida.text.turkish import nfcfrom nida.train.data import ( EMOTIONS, REJECT_TEXT_TOO_LONG, SPLITS, DataFormatError, load_latent_dataset,)from nida.utils.io import atomic_write_bytes, atomic_write_json, atomic_write_text
__all__ = [ "SOURCE_ID", "AudioFacts", "Ears", "EarsConfig", "EarsSettings", "ItemRejected", "PlannedItem", "Selection", "SelectionPlan", "Skip", "TextRejected", "bucket_of", "build_text", "classify_stem", "convert_to_target_rate", "en_lower", "load_settings", "measure_audio", "normalise_english", "parse_speakers", "rate_chars_per_s", "resample", "select_members", "speaker_split",]
log = logging.getLogger(__name__)
SOURCE_ID = "ears"STAGE = "ears"LANGUAGE = "en"VAE_KEY = "voxcpm2_audiovae_v2"DEFAULT_SEED = 20261009FLOAT16_MAX_ABS = 6.0e4 # latents beyond this would overflow the float16 shards (as in pilot.py)CONFIG_FILE = "ears.yaml"INGEST_FILE = "ingest.yaml" # duration limits shared with the Turkish pilotDATASET_FILE = "dataset.yaml" # fixed condition-bucket edges_ASCII_LOWER = str.maketrans(string.ascii_uppercase, string.ascii_lowercase)_SHA256_RE = re.compile(r"[0-9a-f]{64}")_SPEAKER_RE = re.compile(r"p(\d{3})")_WORD_RE = re.compile(r"[a-z]+")_STEM_RE = re.compile(r"[a-z0-9_]+")_EMO_RE = re.compile(r"emo_([a-z]+)_(sentences|freeform)")_READ_RE = re.compile(r"([a-z]+)_(\d+)_([a-z]+)")_TAG_CHARS = frozenset("[]<>")
Kind = Literal["emotion", "read", "whisper", "event"]FloatArray = npt.NDArray[np.float64]
# --------------------------------------------------------------------------------------# Config# --------------------------------------------------------------------------------------
def _load_yaml(path: Path) -> Mapping[str, object]: import yaml # type: ignore[import-untyped] # PyYAML: bench extra, no stubs installed
obj = yaml.safe_load(path.read_text(encoding="utf-8")) if not isinstance(obj, dict): raise ValueError(f"{path}: expected a mapping") return obj
def _non_negative_int(raw: Mapping[str, object], key: str) -> int: value = raw[key] if isinstance(value, bool) or not isinstance(value, int) or value < 0: raise ValueError(f"{key} must be a non-negative int, got {value!r}") return value
def _positive_int(raw: Mapping[str, object], key: str) -> int: value = raw[key] if isinstance(value, bool) or not isinstance(value, int) or value < 1: raise ValueError(f"{key} must be a positive int, got {value!r}") return value
def _fraction(raw: Mapping[str, object], key: str) -> float: value = raw[key] if isinstance(value, bool) or not isinstance(value, int | float): raise ValueError(f"{key} must be a number, got {value!r}") if not (math.isfinite(value) and 0.0 <= value < 1.0): raise ValueError(f"{key} must be in [0, 1), got {value!r}") return float(value)
def _words(raw: Mapping[str, object], key: str) -> tuple[str, ...]: value = raw[key] if ( not isinstance(value, list) or not value or not all(isinstance(x, str) and _WORD_RE.fullmatch(x) for x in value) or len(set(value)) != len(value) ): raise ValueError(f"{key} must be a non-empty list of distinct lowercase words") return tuple(value)
def _str_map(raw: Mapping[str, object], key: str) -> dict[str, str]: value = raw[key] if not isinstance(value, dict) or not all( isinstance(k, str) and isinstance(v, str) for k, v in value.items() ): raise ValueError(f"{key} must be a mapping of strings") return dict(value)
@dataclass(frozen=True)class EarsConfig: """``configs/data/ears.yaml`` (all keys required; see the file for the meaning)."""
transcripts_url: str transcripts_sha256: str | None archive_url_template: str n_speakers: int expected_sample_rate_hz: int target_sample_rate_hz: int val_speaker_fraction: float test_speaker_fraction: float speakers_per_wave: int read_prefixes: tuple[str, ...] whisper_styles: tuple[str, ...] plain_styles: tuple[str, ...] max_read_per_speaker: int emotion_map: dict[str, str] # plain dicts (not frozen views): ``asdict`` feeds the digest event_map: dict[str, str] char_map: dict[str, str]
def __post_init__(self) -> None: for name in ("transcripts_url", "archive_url_template"): if not getattr(self, name).lower().startswith(("http://", "https://")): raise ValueError(f"{name} must be an http(s) URL") if "{speaker}" not in self.archive_url_template: raise ValueError("archive_url_template must contain {speaker}") if self.transcripts_sha256 is not None and not _SHA256_RE.fullmatch( self.transcripts_sha256 ): raise ValueError("transcripts_sha256 must be null or 64 lowercase hex characters") if self.val_speaker_fraction + self.test_speaker_fraction >= 1.0: raise ValueError("val and test speaker fractions must leave room for train") if set(self.whisper_styles) & set(self.plain_styles): raise ValueError("a style cannot be both whisper and plain") for emotion, mapped in self.emotion_map.items(): if not _WORD_RE.fullmatch(emotion) or mapped not in EMOTIONS: raise ValueError(f"emotion_map {emotion!r}: {mapped!r} is not one of {EMOTIONS}") for stem, event in self.event_map.items(): if not _STEM_RE.fullmatch(stem) or event not in tags.EVENTS: raise ValueError(f"event_map {stem!r}: {event!r} is not a tag-spec event id") for char, replacement in self.char_map.items(): if len(char) != 1 or not replacement: raise ValueError(f"char_map entries map one character to a string: {char!r}")
@classmethod def from_mapping(cls, raw: Mapping[str, object]) -> EarsConfig: expected = set(cls.__dataclass_fields__) if set(raw) != expected: raise ValueError( f"ears config keys: missing={sorted(expected - set(raw))} " f"unknown={sorted(set(raw) - expected)}" ) for key in ("transcripts_url", "archive_url_template"): if not isinstance(raw[key], str): raise ValueError(f"{key} must be a string") sha = raw["transcripts_sha256"] if sha is not None and not isinstance(sha, str): raise ValueError("transcripts_sha256 must be null or a string") return cls( transcripts_url=str(raw["transcripts_url"]), transcripts_sha256=sha, archive_url_template=str(raw["archive_url_template"]), n_speakers=_positive_int(raw, "n_speakers"), expected_sample_rate_hz=_positive_int(raw, "expected_sample_rate_hz"), target_sample_rate_hz=_positive_int(raw, "target_sample_rate_hz"), val_speaker_fraction=_fraction(raw, "val_speaker_fraction"), test_speaker_fraction=_fraction(raw, "test_speaker_fraction"), speakers_per_wave=_positive_int(raw, "speakers_per_wave"), read_prefixes=_words(raw, "read_prefixes"), whisper_styles=_words(raw, "whisper_styles"), plain_styles=_words(raw, "plain_styles"), max_read_per_speaker=_non_negative_int(raw, "max_read_per_speaker"), emotion_map=_str_map(raw, "emotion_map"), event_map=_str_map(raw, "event_map"), char_map=_str_map(raw, "char_map"), )
def archive_url(self, speaker: str) -> str: return self.archive_url_template.replace("{speaker}", speaker)
@dataclass(frozen=True)class EarsSettings: """Everything the builder reads from ``configs/data``."""
ears: EarsConfig min_duration_ms: int max_duration_ms: int dataset: DatasetConfig digest: str
def load_settings(config_dir: Path) -> EarsSettings: """Load ``ears.yaml`` plus the duration limits (``ingest.yaml``) and bucket edges (``dataset.yaml``) it shares with the Turkish pilot.
``digest`` names everything a finished speaker depends on; it ignores ``transcripts_sha256`` so that pinning the hash in the config later is allowed. """ ears = EarsConfig.from_mapping(_load_yaml(config_dir / CONFIG_FILE)) ingest_cfg = IngestConfig.from_mapping(_load_yaml(config_dir / INGEST_FILE)) dataset = DatasetConfig.from_mapping(_load_yaml(config_dir / DATASET_FILE)) body = asdict(ears) del body["transcripts_sha256"] del body["speakers_per_wave"] # operational: does not change any output canonical = json.dumps( { "ears": body, "min_duration_ms": ingest_cfg.min_duration_ms, "max_duration_ms": ingest_cfg.max_duration_ms, "dataset": asdict(dataset), }, sort_keys=True, ensure_ascii=False, ) return EarsSettings( ears=ears, min_duration_ms=ingest_cfg.min_duration_ms, max_duration_ms=ingest_cfg.max_duration_ms, dataset=dataset, digest=hashlib.sha1(canonical.encode("utf-8")).hexdigest()[:12], )
def parse_speakers(spec: str, n_speakers: int) -> list[str]: """``"all"`` or ``"p001,p007"`` -> speaker ids.
Raises: ValueError: on an empty list, a malformed or out-of-range id, or a repeated id. """ if spec.strip() == "all": return [f"p{i:03d}" for i in range(1, n_speakers + 1)] ids = [part.strip() for part in spec.split(",")] for speaker in ids: match = _SPEAKER_RE.fullmatch(speaker) if match is None or not 1 <= int(match.group(1)) <= n_speakers: raise ValueError(f"invalid speaker {speaker!r}: use p001..p{n_speakers:03d} or 'all'") if len(set(ids)) != len(ids): raise ValueError(f"repeated speaker in {spec!r}") return ids
# --------------------------------------------------------------------------------------# Text# --------------------------------------------------------------------------------------
class TextRejected(ValueError): """The text of an item cannot be used; ``reason`` is the quarantine reason."""
def __init__(self, reason: str, detail: str) -> None: super().__init__(f"{reason}: {detail}") self.reason = reason self.detail = detail
def en_lower(text: str) -> str: """Lower-case ``A``-``Z`` only (English). Never use ``tr_lower`` (``I`` -> ``ı``) or ``str.lower`` (``İ`` -> ``i`` + combining dot) on English text: every other character is returned unchanged.""" return text.translate(_ASCII_LOWER)
def normalise_english(text: str, char_map: Mapping[str, str]) -> str: """NFC, ``char_map`` replacements, ASCII lower-case and collapsed whitespace.
Returns ``""`` for text without any non-space character. """ mapped = nfc(text).translate({ord(k): v for k, v in char_map.items()}) return " ".join(en_lower(mapped).split())
@dataclass(frozen=True)class BuiltText: """Model text (tag-spec surface) and the plain words the speaker says (may be empty)."""
tagged: str plain: str
def build_text(selection: Selection, transcript: str | None, cfg: EarsConfig) -> BuiltText: """Build the training text of one selected file.
Raises: TextRejected: with reason ``no_transcript``, ``empty_text``, ``digits``, ``tag_characters``, ``non_ascii_letter`` or ``text_encoding`` (the model vocabulary cannot encode the result). """ if selection.kind == "event": assert selection.event is not None # classify_stem always sets it for events tagged = tags.render([tags.Event(selection.event)]) plain = "" else: if transcript is None: raise TextRejected("no_transcript", f"no entry for {selection.stem!r}") plain = normalise_english(transcript, cfg.char_map) if not plain: raise TextRejected("empty_text", "transcript has no characters") if any(ch.isdigit() for ch in plain): raise TextRejected("digits", plain[:80]) if any(ch in _TAG_CHARS for ch in plain): raise TextRejected("tag_characters", plain[:80]) if any(ch.isalpha() and not ch.isascii() for ch in plain): raise TextRejected("non_ascii_letter", plain[:80]) if selection.kind == "whisper": try: span = tags.Span("whisper", tuple(tags.Word(w) for w in plain.split())) except ValueError as err: raise TextRejected("text_encoding", str(err)) from err tagged = tags.render([span]) else: tagged = plain try: ids = encode_text(tagged) except ValueError as err: # unknown character, bad tag raise TextRejected("text_encoding", str(err)) from err if not ids: raise TextRejected("empty_text", "text encodes to no tokens") return BuiltText(tagged=tagged, plain=plain)
# --------------------------------------------------------------------------------------# Selection# --------------------------------------------------------------------------------------
@dataclass(frozen=True)class Selection: """A file that is used. ``emotion`` is set for ``emotion`` items (may be ``None``), ``event`` for ``event`` items."""
stem: str kind: Kind emotion: str | None = None event: str | None = None
@property def label(self) -> str: """Report category: ``emotion``, ``read``, ``whisper`` or ``event:<id>``.""" return f"event:{self.event}" if self.kind == "event" else self.kind
@dataclass(frozen=True)class Skip: """A file that is not used, with the counted reason."""
stem: str reason: str
def classify_stem(stem: str, cfg: EarsConfig) -> Selection | Skip: """Decide on one file stem (ADR-0007 table). Pure; thresholds and maps come from ``cfg``.
Skip reasons: ``freeform``, ``interjection``, ``melodic``, ``event_unmapped``, ``style_unsupported``, ``unknown_stem``. """ emo = _EMO_RE.fullmatch(stem) if emo is not None: if emo.group(2) != "sentences": return Skip(stem, "freeform") return Selection(stem, "emotion", emotion=cfg.emotion_map.get(emo.group(1))) event = cfg.event_map.get(stem) if event is not None: return Selection(stem, "event", event=event) read = _READ_RE.fullmatch(stem) if read is not None and read.group(1) in cfg.read_prefixes: style = read.group(3) if style in cfg.whisper_styles: return Selection(stem, "whisper") if style in cfg.plain_styles: return Selection(stem, "read") return Skip(stem, "style_unsupported") if stem.startswith("freeform_speech"): return Skip(stem, "freeform") for prefix, reason in ( ("interjection_", "interjection"), ("melodic_", "melodic"), ("nonverbal_", "event_unmapped"), ("vegetative_", "event_unmapped"), ): if stem.startswith(prefix): return Skip(stem, reason) return Skip(stem, "unknown_stem")
@dataclass(frozen=True)class PlannedItem: """A selected archive member with its final text."""
stem: str member: ZipMember selection: Selection text: BuiltText
@dataclassclass SelectionPlan: """Result of :func:`select_members`: nothing is lost, every member is in one of three places."""
items: list[PlannedItem] = field(default_factory=list) skipped: Counter[str] = field(default_factory=Counter) quarantine: list[QuarantineRecord] = field(default_factory=list)
def select_members( speaker: str, members: Sequence[ZipMember], transcripts: Mapping[str, str], cfg: EarsConfig,) -> SelectionPlan: """Decide on every archive member before anything is downloaded.
``items`` come back in archive order (ascending ``header_offset``) so extraction profits from the read-ahead window. Skipped members are counted by reason; text problems become quarantine records (stage ``ears``, item id ``<speaker>/<stem>``). """ plan = SelectionPlan() seen: set[str] = set() for member in sorted(members, key=lambda m: m.header_offset): if member.is_dir: plan.skipped["directory"] += 1 continue parts = member.name.split("/") if len(parts) != 2 or parts[0] != speaker: plan.skipped["outside_speaker_folder"] += 1 continue if not parts[1].endswith(".wav"): plan.skipped["not_wav"] += 1 continue stem = parts[1][: -len(".wav")] decision = classify_stem(stem, cfg) if isinstance(decision, Skip): plan.skipped[decision.reason] += 1 continue item_id = f"{speaker}/{stem}" if stem in seen: plan.quarantine.append( QuarantineRecord(item_id, STAGE, "duplicate_member", {"name": member.name}) ) continue seen.add(stem) try: text = build_text(decision, transcripts.get(stem), cfg) except TextRejected as err: plan.quarantine.append( QuarantineRecord(item_id, STAGE, err.reason, {"detail": err.detail}) ) continue plan.items.append(PlannedItem(stem, member, decision, text)) _cap_reads(plan, speaker, cfg.max_read_per_speaker) return plan
def _cap_reads(plan: SelectionPlan, speaker: str, cap: int) -> None: """Keep at most ``cap`` plain reading items per speaker (0 = no limit; ADR-0007: plain reading is a low share). The kept ones are a deterministic hash choice of the stems; the rest are counted as skipped ``read_cap``.""" reads = [item for item in plan.items if item.selection.kind == "read"] if cap == 0 or len(reads) <= cap: return ranked = sorted(reads, key=lambda it: hashlib.sha1(f"{speaker}/{it.stem}".encode()).hexdigest()) dropped = {id(item) for item in ranked[cap:]} plan.items = [item for item in plan.items if id(item) not in dropped] plan.skipped["read_cap"] += len(dropped)
# --------------------------------------------------------------------------------------# Audio# --------------------------------------------------------------------------------------
class ItemRejected(Exception): """An audio file cannot be used; ``reason`` is the quarantine reason."""
def __init__(self, reason: str, **details: object) -> None: super().__init__(f"{reason}: {details}") self.reason = reason self.details = details
@dataclass(frozen=True)class AudioFacts: """Measurements of a converted file: ``duration_ms`` of the 16 kHz audio, RMS level."""
duration_ms: int loudness_dbfs: float
def resample(audio: FloatArray, rate_hz: int, target_hz: int) -> FloatArray: """Polyphase resampling of a mono signal (anti-aliased) from ``rate_hz`` to ``target_hz``.
Args: audio: ``(num_samples,)`` float signal. rate_hz: Source rate. target_hz: Target rate.
Returns: ``(ceil(num_samples * target_hz / rate_hz),)`` float64 signal. """ if rate_hz == target_hz: return np.asarray(audio, dtype=np.float64) divisor = math.gcd(rate_hz, target_hz) out = signal.resample_poly(audio, target_hz // divisor, rate_hz // divisor) return np.asarray(out, dtype=np.float64)
def convert_to_target_rate(raw: Path, dest: Path, cfg: EarsConfig) -> None: """Read a raw EARS wav, check it, resample to ``target_sample_rate_hz`` mono and write a 32-bit float wav atomically to ``dest``.
Raises: ItemRejected: ``unreadable_audio``, ``not_mono``, ``unexpected_sample_rate``, ``empty_audio`` or ``non_finite_audio``. """ import soundfile # type: ignore[import-untyped] # bench extra, untyped
try: audio, rate_hz = soundfile.read(str(raw), dtype="float64", always_2d=True) except (RuntimeError, soundfile.LibsndfileError) as err: raise ItemRejected("unreadable_audio", error=str(err)) from err if audio.shape[1] != 1: raise ItemRejected("not_mono", channels=int(audio.shape[1])) if rate_hz != cfg.expected_sample_rate_hz: raise ItemRejected("unexpected_sample_rate", sample_rate_hz=int(rate_hz)) mono = np.ascontiguousarray(audio[:, 0]) if mono.shape[0] == 0: raise ItemRejected("empty_audio") if not np.all(np.isfinite(mono)): raise ItemRejected("non_finite_audio") converted = resample(mono, int(rate_hz), cfg.target_sample_rate_hz) buffer = io.BytesIO() soundfile.write(buffer, converted, cfg.target_sample_rate_hz, format="WAV", subtype="FLOAT") atomic_write_bytes(dest, buffer.getvalue())
def measure_audio( path: Path, cfg: EarsConfig, min_duration_ms: int, max_duration_ms: int) -> AudioFacts: """Duration and loudness of a converted wav; enforces the duration limits.
The loudness is :func:`nida.data.acoustic.loudness_dbfs`, the measure the pilot ingest stores, here on the 16 kHz signal the VAE hears.
Raises: ItemRejected: ``unreadable_audio``, ``too_short``, ``too_long`` or ``silent``. ValueError: if the file is not at ``target_sample_rate_hz`` (the cache is inconsistent with the config). """ import soundfile
try: audio, rate_hz = soundfile.read(str(path), dtype="float64", always_2d=True) except (RuntimeError, soundfile.LibsndfileError) as err: raise ItemRejected("unreadable_audio", error=str(err)) from err if rate_hz != cfg.target_sample_rate_hz or audio.shape[1] != 1: raise ValueError( f"{path}: expected {cfg.target_sample_rate_hz} Hz mono, got {rate_hz} Hz x " f"{audio.shape[1]}; delete the cache folder" ) mono = np.ascontiguousarray(audio[:, 0]) duration_ms = round(1000 * mono.shape[0] / rate_hz) if duration_ms < min_duration_ms: raise ItemRejected("too_short", duration_ms=duration_ms) if duration_ms > max_duration_ms: raise ItemRejected("too_long", duration_ms=duration_ms) if float(np.max(np.abs(mono))) == 0.0: raise ItemRejected("silent") return AudioFacts(duration_ms=duration_ms, loudness_dbfs=float(acoustic.loudness_dbfs(mono)))
# --------------------------------------------------------------------------------------# Buckets and splits# --------------------------------------------------------------------------------------
def bucket_of(value: float, edges: Sequence[float]) -> int: """Bucket index of ``value``: the number of ``edges`` that are ``<= value`` (``numpy.searchsorted(edges, value, side="right")``, as the pilot dataset stage).""" return bisect_right(edges, value)
def rate_chars_per_s(plain_text: str, duration_ms: int) -> float: """Alphanumeric characters of the plain text per second of audio (pilot formula).""" return sum(ch.isalnum() for ch in plain_text) / (duration_ms / 1000)
def speaker_split(group: str, val_fraction: float, test_fraction: float, seed: int) -> str: """Split of a speaker group: a pure function of ``(seed, group)`` (:mod:`nida.data.splits`).""" fractions = { "train": 1.0 - val_fraction - test_fraction, "val": val_fraction, "test": test_fraction, } return assign_splits({"speaker": group}, fractions, str(seed))["speaker"]
# --------------------------------------------------------------------------------------# The builder# --------------------------------------------------------------------------------------
@dataclass(frozen=True)class _Measured: item: PlannedItem segment_id: str wav: Path facts: AudioFacts
@dataclassclass _Prepared: """A speaker whose audio is ready for the VAE: nothing is written for it yet."""
plan: SelectionPlan quarantine: list[QuarantineRecord] measured: list[_Measured]
@dataclassclass Ears: """EARS -> latent dataset builder (see the module docstring).
Attributes: root: Durable directory (Drive on Colab). cache: Local scratch for raw members, 16 kHz audio and latent arrays. envs_root: Where the worker virtual environments live. repo_dir: Repository root (environment builds need it). sources_path: ``configs/sources.yaml``. config_dir: ``configs/data``. seed: Split seed (recorded in ``plan.json``). runner: Worker command runner (injectable). opener: Network access (injectable). sleep: Backoff sleep for retries (injectable). """
root: Path cache: Path envs_root: Path repo_dir: Path sources_path: Path config_dir: Path seed: int = DEFAULT_SEED uv: str | None = None runner: Callable[[Sequence[str]], int] = _stream_runner opener: fetch.Opener = fetch.default_opener sleep: Callable[[float], None] = time.sleep _python: Path | None = field(default=None, init=False, repr=False)
# ---------------------------------------------------------------- paths
@property def dataset_dir(self) -> Path: return self.root / "dataset"
def _speaker_dir(self, speaker: str) -> Path: return self.root / "speakers" / speaker
def _npy(self, segment: str) -> Path: return self.cache / "arrays" / "vae" / f"{segment}.npy"
# ---------------------------------------------------------------- run
def run(self, speakers: Sequence[str]) -> dict[str, object]: """Build (or continue) the dataset for ``speakers``.
Finished speakers are skipped. The dataset directory, ``report.md`` and ``stats.json`` are rewritten from *all* finished speakers of the root at the end.
Returns: Summary with ``dataset``, ``speakers_done``, ``segments``, ``hours``, ``skipped`` and ``quarantined`` counts, and ``failed_speakers``.
Raises: SourceNotApprovedError: before any download, if a source is not approved. ValueError: on a plan/config/transcripts mismatch with the root. RuntimeError: if a worker fails, a speaker could not be fetched (after all other speakers were processed and the dataset was assembled), or nothing was built. """ settings = load_settings(self.config_dir) model = DATA_MODELS[VAE_KEY] require_approved({SOURCE_ID, model.source_id}, load_sources(self.sources_path)) wanted = list(speakers) for speaker in wanted: parse_speakers(speaker, settings.ears.n_speakers) transcripts, transcripts_sha = self._prepare_plan(settings) failed: dict[str, str] = {} pending: list[str] = [] for speaker in dict.fromkeys(wanted): if (self._speaker_dir(speaker) / "done.json").is_file(): log.info("EARS %s already done", speaker) else: pending.append(speaker) wave_size = settings.ears.speakers_per_wave for start in range(0, len(pending), wave_size): wave = pending[start : start + wave_size] prepared: dict[str, _Prepared] = {} for speaker in wave: log.info("EARS %s (%d/%d)", speaker, pending.index(speaker) + 1, len(pending)) try: prepared[speaker] = self._prepare_speaker(speaker, settings, transcripts) except fetch.FetchError as err: # network or archive problem: others still run log.error("EARS %s failed: %s", speaker, err) failed[speaker] = str(err) results = self._encode([m for entry in prepared.values() for m in entry.measured]) for speaker, entry in prepared.items(): self._finish_speaker(speaker, settings, entry, results) summary = self._assemble(settings, transcripts_sha, failed) if failed: raise RuntimeError( f"{len(failed)} speaker(s) failed and can be retried by running again: " + "; ".join(f"{s}: {e[:200]}" for s, e in sorted(failed.items())) ) return summary
# ---------------------------------------------------------------- plan and transcripts
def _prepare_plan(self, settings: EarsSettings) -> tuple[dict[str, str], str]: """Check/write ``plan.json`` and fetch the pinned transcripts.""" model = DATA_MODELS[VAE_KEY] core: dict[str, object] = { "seed": self.seed, "config_digest": settings.digest, "archive_url_template": settings.ears.archive_url_template, "transcripts_url": settings.ears.transcripts_url, "vae": [model.ref.model_id, model.ref.revision], } plan_path = self.root / "plan.json" previous: dict[str, object] | None = None if plan_path.is_file(): loaded = json.loads(plan_path.read_text(encoding="utf-8")) previous = dict(loaded) recorded_sha = previous.pop("transcripts_sha256", None) if previous != core: raise ValueError( f"{plan_path} was written for a different plan: {previous} != {core}" ) if ( settings.ears.transcripts_sha256 is not None and recorded_sha is not None and settings.ears.transcripts_sha256 != recorded_sha ): raise ValueError( f"config pins transcripts {settings.ears.transcripts_sha256} but the root " f"was built with {recorded_sha}" ) expected = recorded_sha if isinstance(recorded_sha, str) else None else: expected = None expected = settings.ears.transcripts_sha256 or expected downloaded = fetch.download( settings.ears.transcripts_url, self.root / "source" / "transcripts.json", expected_sha256=expected, opener=self.opener, sleep=self.sleep, ) if previous is None: atomic_write_json(plan_path, {**core, "transcripts_sha256": downloaded.sha256}) return _parse_transcripts(downloaded.path), downloaded.sha256
# ---------------------------------------------------------------- speaker
def _python_exe(self) -> Path: if self._python is None: if self.uv is None: self.uv = bench_envs.find_uv(bench_envs.subprocess_runner) spec = envs.data_env_for_worker(DATA_MODELS[VAE_KEY].worker) self._python = bench_envs.ensure_env(spec, self.envs_root, self.repo_dir, uv=self.uv) return self._python
def _prepare_speaker( self, speaker: str, settings: EarsSettings, transcripts: Mapping[str, str] ) -> _Prepared: """List the archive, decide on every member, fetch + convert + measure the selected.""" cfg = settings.ears QuarantineLog(self._speaker_dir(speaker)).path.unlink(missing_ok=True) # rebuilt below archive = RemoteZip(cfg.archive_url(speaker), opener=self.opener, sleep=self.sleep) members = archive.members() plan = select_members(speaker, members, transcripts, cfg) quarantine = list(plan.quarantine) log.info( "EARS %s: %d members, %d selected, %d quarantined, skipped %s", speaker, len(members), len(plan.items), len(quarantine), dict(plan.skipped), ) measured: list[_Measured] = [] for item in plan.items: # archive order: one read-ahead window serves neighbours item_id = f"{speaker}/{item.stem}" wav = self.cache / "audio16k" / speaker / f"{item.stem}.wav" try: if not wav.is_file(): raw = archive.extract( item.member, self.cache / "raw" / speaker / f"{item.stem}.wav" ) convert_to_target_rate(raw, wav, cfg) raw.unlink() facts = measure_audio(wav, cfg, settings.min_duration_ms, settings.max_duration_ms) except ItemRejected as err: quarantine.append(QuarantineRecord(item_id, STAGE, err.reason, dict(err.details))) continue sid = segment_id(SOURCE_ID, item_id, 0, facts.duration_ms) measured.append(_Measured(item, sid, wav, facts)) return _Prepared(plan, quarantine, measured)
def _finish_speaker( self, speaker: str, settings: EarsSettings, prepared: _Prepared, results: Mapping[str, WorkResult], ) -> None: """Write the speaker's outputs, then drop its scratch files.""" self._write_speaker( speaker, settings, prepared.measured, results, prepared.plan, prepared.quarantine ) for sub in ("raw", "audio16k"): shutil.rmtree(self.cache / sub / speaker, ignore_errors=True) for entry in prepared.measured: self._npy(entry.segment_id).unlink(missing_ok=True)
def _encode(self, measured: Sequence[_Measured]) -> dict[str, WorkResult]: """Run the pilot's ``vae_encode`` worker once over the audio of a wave (resumable).""" if not measured: return {} model = DATA_MODELS[VAE_KEY] python = self._python_exe() out_dir = self.root / "workers" / "vae" results_path = out_dir / "results.jsonl" wanted = {m.segment_id for m in measured} summary_path = out_dir / "results.summary.json" if results_path.exists() and summary_path.exists(): previous = read_summary(summary_path) if (previous.model_id, previous.revision) != (model.ref.model_id, model.ref.revision): raise RuntimeError( f"existing latents come from {previous.model_id}@" f"{previous.revision}, not {model.ref.model_id}@{model.ref.revision}; " "move them away first" ) if results_path.exists(): existing = load_results(results_path, repair=True) stale = [ cid for cid, res in existing.items() if cid not in wanted or res.output is None # failed before: try again (a stuck item fails again) or not Path(str(res.output.get("out_path", ""))).is_file() ] if stale: log.info("dropping %d stray, failed or lost worker results", len(stale)) drop_results(results_path, stale) requests = [ WorkRequest(m.segment_id, str(m.wav), {"out_path": str(self._npy(m.segment_id))}) for m in measured ] write_requests(out_dir / "requests.jsonl", requests) command = [ str(python), "-m", envs.worker_module_name(model.worker), "--requests", str(out_dir / "requests.jsonl"), "--results", str(results_path), "--model-id", model.ref.model_id, "--revision", model.ref.revision, "--batch-size", str(model.batch_size), "--device", "cuda", ] code = self.runner(command) if code != 0: raise RuntimeError(f"vae_encode worker exited with code {code}") summary = read_summary(summary_path) total = summary.n_ok + summary.n_error if total != len(requests): raise RuntimeError(f"{total} latent results for {len(requests)} requests") if summary.n_error > MAX_ERROR_FRACTION * total: raise RuntimeError(f"{summary.n_error}/{total} items failed in the worker") return load_results(results_path)
def _write_speaker( self, speaker: str, settings: EarsSettings, measured: Sequence[_Measured], results: Mapping[str, WorkResult], plan: SelectionPlan, quarantine: list[QuarantineRecord], ) -> dict[str, object]: """Shard, records, quarantine log and finally the done marker of one speaker.""" cfg = settings.ears group = f"ears-{speaker}" split = speaker_split(group, cfg.val_speaker_fraction, cfg.test_speaker_fraction, self.seed) rate_edges = list(settings.dataset.rate_bucket_edges_chars_per_s) loud_edges = list(settings.dataset.loudness_bucket_edges_dbfs) shard_name = f"shard-{speaker}.npy" rows: list[dict[str, object]] = [] arrays: list[npt.NDArray[np.float32]] = [] kinds: dict[str, dict[str, int]] = {} latent_dim: int | None = None frame_hop_ms: float | None = None frames = 0 for entry in sorted(measured, key=lambda m: m.item.stem): item_id = f"{speaker}/{entry.item.stem}" result = results.get(entry.segment_id) if result is None: raise RuntimeError(f"{speaker}: the worker returned no result for {item_id}") if result.output is None: quarantine.append( QuarantineRecord(item_id, STAGE, "vae_error", {"error": str(result.error)}) ) continue array = np.load(str(result.output["out_path"]), allow_pickle=False) hop = float(str(result.output["frame_hop_ms"])) if array.ndim != 2 or array.shape[0] < 1: raise ValueError(f"{item_id}: latents must be 2-D with frames, got {array.shape}") if frame_hop_ms is not None and hop != frame_hop_ms: raise ValueError(f"{item_id}: frame hop {hop} != {frame_hop_ms}") if latent_dim is not None and int(array.shape[1]) != latent_dim: raise ValueError(f"{item_id}: latent_dim {array.shape[1]} != {latent_dim}") frame_hop_ms, latent_dim = hop, int(array.shape[1]) if not np.all(np.isfinite(array)) or float(np.max(np.abs(array))) > FLOAT16_MAX_ABS: quarantine.append(QuarantineRecord(item_id, STAGE, "latents_not_float16", {})) continue num_frames = int(array.shape[0]) n_tokens = len(encode_text(entry.item.text.tagged)) if n_tokens > num_frames: quarantine.append( QuarantineRecord( item_id, STAGE, REJECT_TEXT_TOO_LONG, {"text_tokens": n_tokens, "num_frames": num_frames}, ) ) continue plain = entry.item.text.plain rows.append( { "segment_id": entry.segment_id, "shard": shard_name, "offset": frames, "num_frames": num_frames, "text": entry.item.text.tagged, "emotion": entry.item.selection.emotion, "intensity": None, "rate_bucket": ( bucket_of(rate_chars_per_s(plain, entry.facts.duration_ms), rate_edges) if plain else None ), "loudness_bucket": bucket_of(entry.facts.loudness_dbfs, loud_edges), "group": group, "split": split, "language": LANGUAGE, } ) arrays.append(array.astype(np.float32)) frames += num_frames stat = kinds.setdefault(entry.item.selection.label, {"segments": 0, "audio_ms": 0}) stat["segments"] += 1 stat["audio_ms"] += entry.facts.duration_ms
spk_dir = self._speaker_dir(speaker) if arrays: buffer = io.BytesIO() np.save(buffer, np.concatenate(arrays).astype(np.float16), allow_pickle=False) atomic_write_bytes(self.dataset_dir / shard_name, buffer.getvalue()) atomic_write_text( spk_dir / "records.jsonl", "".join(json.dumps(row, ensure_ascii=False) + "\n" for row in rows), ) QuarantineLog(spk_dir).append(quarantine) marker: dict[str, object] = { "speaker": speaker, "group": group, "split": split, "segments": len(rows), "frames": frames, "audio_ms": sum(s["audio_ms"] for s in kinds.values()), "latent_dim": latent_dim if rows else None, "frame_hop_ms": frame_hop_ms if rows else None, "shard": shard_name if rows else None, "kinds": kinds, "skipped": dict(sorted(plan.skipped.items())), "quarantined": dict(sorted(Counter(q.reason for q in quarantine).items())), } atomic_write_json(spk_dir / "done.json", marker) # written last: the speaker is done return marker
# ---------------------------------------------------------------- assembly
def _assemble( self, settings: EarsSettings, transcripts_sha: str, failed: Mapping[str, str] ) -> dict[str, object]: """Index, meta, report and stats from every finished speaker of the root.""" markers: list[dict[str, object]] = [] speakers_dir = self.root / "speakers" for done_path in sorted(speakers_dir.glob("p*/done.json")) if speakers_dir.is_dir() else []: markers.append(json.loads(done_path.read_text(encoding="utf-8"))) with_data = [m for m in markers if m["segments"]] if not with_data: raise RuntimeError( f"no EARS segment built (speakers done: {len(markers)}, failed: {sorted(failed)})" ) hops = {float(str(m["frame_hop_ms"])) for m in with_data} dims = {int(str(m["latent_dim"])) for m in with_data} if len(hops) != 1 or len(dims) != 1: raise ValueError( f"speakers disagree on frame hop {sorted(hops)} or latent_dim {sorted(dims)}" ) index_lines: list[str] = [] for marker in with_data: lines = ( (self._speaker_dir(str(marker["speaker"])) / "records.jsonl") .read_text(encoding="utf-8") .splitlines(keepends=True) ) if len(lines) != marker["segments"]: raise ValueError(f"{marker['speaker']}: records.jsonl and done.json disagree") if not (self.dataset_dir / str(marker["shard"])).is_file(): raise ValueError(f"{marker['speaker']}: shard {marker['shard']} is missing") index_lines.extend(lines) total_segments = len(index_lines) total_frames = sum(int(str(m["frames"])) for m in with_data) atomic_write_text(self.dataset_dir / "index.jsonl", "".join(index_lines)) source = load_sources(self.sources_path)[SOURCE_ID] model = DATA_MODELS[VAE_KEY] meta: dict[str, object] = { "segments": total_segments, "frames": total_frames, "latent_dim": dims.pop(), "frame_hop_ms": hops.pop(), "rate_bucket_edges_chars_per_s": list(settings.dataset.rate_bucket_edges_chars_per_s), "loudness_bucket_edges_dbfs": list(settings.dataset.loudness_bucket_edges_dbfs), "source": SOURCE_ID, "license": source.get("license"), "language": LANGUAGE, "transcripts_sha256": transcripts_sha, "transcripts_url": settings.ears.transcripts_url, "config_digest": settings.digest, "seed": self.seed, "vae": [model.ref.model_id, model.ref.revision], "speakers": { str(m["speaker"]): {"split": m["split"], "segments": m["segments"]} for m in markers }, } atomic_write_json(self.dataset_dir / "meta.json", meta)
loader = self._check_with_loader() stats = _stats(markers, loader, settings, failed, meta) atomic_write_json(self.root / "stats.json", stats) atomic_write_text(self.root / "report.md", _render_report(stats)) rejected = {s: c for s, c in loader.items() if c["rejected"]} if rejected: raise RuntimeError(f"nida.train.data rejects records the builder accepted: {rejected}") return { "dataset": str(self.dataset_dir), "speakers_done": len(markers), "segments": total_segments, "hours": stats["hours"], "skipped": stats["skipped"], "quarantined": stats["quarantined"], "failed_speakers": dict(failed), }
def _check_with_loader(self) -> dict[str, dict[str, object]]: """Load every split with the training loader; counts per split (must not reject).""" out: dict[str, dict[str, object]] = {} for split in SPLITS: try: dataset, report = load_latent_dataset(self.dataset_dir, split) except DataFormatError as err: raise RuntimeError(f"the assembled dataset is invalid: {err}") from err dataset.close() out[split] = { "records": report.num_in_split, "accepted": report.num_accepted, "rejected": report.num_rejected, "rejection_counts": dict(report.rejection_counts), } return out
# --------------------------------------------------------------------------------------# Reporting# --------------------------------------------------------------------------------------
def _parse_transcripts(path: Path) -> dict[str, str]: obj = json.loads(path.read_text(encoding="utf-8")) if not isinstance(obj, dict) or not obj: raise ValueError(f"{path}: expected a non-empty mapping stem -> text") bad = [k for k, v in obj.items() if not isinstance(k, str) or not isinstance(v, str)] if bad: raise ValueError(f"{path}: entries must map strings to strings, e.g. {bad[:3]}") return dict(obj)
def _sum_counts(markers: Sequence[Mapping[str, object]], key: str) -> dict[str, int]: total: Counter[str] = Counter() for marker in markers: value = marker[key] assert isinstance(value, dict) total.update({str(k): int(v) for k, v in value.items()}) return dict(sorted(total.items(), key=lambda kv: (-kv[1], kv[0])))
def _stats( markers: Sequence[Mapping[str, object]], loader: Mapping[str, Mapping[str, object]], settings: EarsSettings, failed: Mapping[str, str], meta: Mapping[str, object],) -> dict[str, object]: kinds: dict[str, dict[str, int]] = {} for marker in markers: value = marker["kinds"] assert isinstance(value, dict) for label, stat in value.items(): into = kinds.setdefault(label, {"segments": 0, "audio_ms": 0}) into["segments"] += int(stat["segments"]) into["audio_ms"] += int(stat["audio_ms"]) splits: dict[str, dict[str, int]] = {s: {"speakers": 0, "segments": 0} for s in SPLITS} for marker in markers: entry = splits[str(marker["split"])] entry["speakers"] += 1 entry["segments"] += int(str(marker["segments"])) audio_ms = sum(int(str(m["audio_ms"])) for m in markers) return { "speakers_done": len(markers), "speakers_total": settings.ears.n_speakers, "segments": meta["segments"], "frames": meta["frames"], "hours": round(audio_ms / 3_600_000, 3), "kinds": dict(sorted(kinds.items())), "splits": splits, "skipped": _sum_counts(markers, "skipped"), "quarantined": _sum_counts(markers, "quarantined"), "loader": {k: dict(v) for k, v in loader.items()}, "failed_speakers": dict(failed), "transcripts_sha256": meta["transcripts_sha256"], "config_digest": settings.digest, }
def _render_report(stats: Mapping[str, object]) -> str: kinds = stats["kinds"] splits = stats["splits"] loader = stats["loader"] assert isinstance(kinds, dict) and isinstance(splits, dict) and isinstance(loader, dict) lines = [ "# EARS latent veri seti raporu", "", f"- Konuşmacı: {stats['speakers_done']}/{stats['speakers_total']} tamamlandı", f"- Segment: {stats['segments']}, süre: {stats['hours']} sa, kare: {stats['frames']}", f"- Yapılandırma özeti: `{stats['config_digest']}`; transkript SHA-256: " f"`{stats['transcripts_sha256']}`", "", "## Seçilen türler", "", *( f"- {label}: {v['segments']} segment, {v['audio_ms'] / 3_600_000:.3f} sa" for label, v in kinds.items() ), "", "## Bölmeler (konuşmacı-ayrık)", "", *( f"- {name}: {v['speakers']} konuşmacı, {v['segments']} segment" for name, v in splits.items() ), "", "## Atlananlar (neden: sayı)", "", json.dumps(stats["skipped"], ensure_ascii=False), "", "## Karantina (neden: sayı)", "", json.dumps(stats["quarantined"], ensure_ascii=False), "", "## Eğitim yükleyicisi doğrulaması (`nida.train.data`)", "", *( f"- {name}: {v['accepted']}/{v['records']} kabul, ret: {v['rejection_counts']}" for name, v in loader.items() ), ] failed = stats["failed_speakers"] if failed: lines += ["", "## Başarısız konuşmacılar (yeniden çalıştırın)", ""] assert isinstance(failed, dict) lines += [f"- {speaker}: {error[:300]}" for speaker, error in failed.items()] return "\n".join(lines) + "\n"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593"""Optional speech-enhancement step of the data pilot (docs/03-data-pipeline.md).
Everything about enhancement that does not depend on one arm lives here:
* :class:`EnhanceConfig` (``configs/data/enhance.yaml``): which arm (``none`` | ``uvr`` | ``sidon`` | ``dfn``) and how much length difference between the input and the enhanced segment is tolerated;* naming of the arm-specific audio root / dataset suffix;* the pure audio functions shared by the three arm workers (:func:`fit_to_length`, :func:`finish_enhanced_wav`) and the :class:`EnhanceAdapter` template they plug into;* the small checks the arms share (device resolution, pinned-file SHA-256).
The arms themselves are in ``nida.data.workers.enhance_<arm>``; each runs in its own isolatedenvironment (:data:`nida.data.envs.ENHANCE_ENV_SPECS`), because their dependency pinsconflict (numpy 1 vs 2, Python 3.11 vs 3.12). The worker modules and this module are importedinside those environments, so this module imports only the standard library and the stdlib-onlyprotocol/worker helpers at import time; numpy, scipy and soundfile are imported inside thefunctions that need them (all three arm environments install them).
Contract of a worker request: ``audio_path`` is a 16 kHz mono wav; ``params["out_path"]`` isthe ``.wav`` to write; ``params["max_length_diff_ms"]`` is the largest length difference theworker accepts at all. The output is a 16 kHz mono PCM16 wav with **exactly** as many samples asthe input. The difference between the arm's output length (after resampling to 16 kHz) and theinput length is recorded as ``length_diff_samples`` before it is fixed by zero-padding ortrimming; the payload also carries ``peak`` (before clipping) and ``loudness_dbfs`` (RMS level ofthe PCM16 samples actually written, the same measure as the ingest ``loudness_dbfs``).
Who judges the length: the worker only refuses an absurd difference (above``max_length_diff_ms``: a misaligned or truncated output, :class:`EnhanceLengthError`, a faileditem). Everything between the tolerance and that limit is written and recorded, and the pilotalone quarantines it by ``length_tolerance_ms`` (:mod:`nida.data.pilot`), so the tolerance can bechanged without recomputing and tolerated-but-large differences do not count toward the workererror budget."""
from __future__ import annotations
import abcimport hashlibimport ioimport mathimport osfrom collections.abc import Mapping, Sequencefrom dataclasses import dataclassfrom pathlib import Pathfrom typing import TYPE_CHECKING
from nida.bench.protocol import WorkRequestfrom nida.bench.workers.runner import Adapterfrom nida.data.workers import REQUIRED_SAMPLE_RATE_HZ, require_16k_monofrom nida.utils.io import atomic_write_bytes
if TYPE_CHECKING: import numpy as np import numpy.typing as npt
Waveform = npt.NDArray[np.float32]
__all__ = [ "ARMS", "ARM_NONE", "CONFIG_FILENAME", "ENHANCED_ARMS", "NO_ENHANCE", "PAYLOAD_KEYS", "REASON_CLIPPED", "REASON_FAILED", "REASON_LENGTH", "ArmUnavailableError", "EnhanceAdapter", "EnhanceConfig", "EnhanceError", "EnhanceLengthError", "FittedAudio", "arm_suffix", "audio_dir_name", "clipping_threshold_param", "encode_wav_pcm16", "finish_enhanced_wav", "fit_to_length", "is_length_error", "max_length_diff_param", "resample_mono", "resolve_device", "sha256_file", "verify_pinned_sha256", "wav_loudness_dbfs", "wav_out_path_param", "wav_stats",]
ARM_NONE = "none"#: Selectable arms, ``none`` first. The other three have a worker, an environment and a pin.ARMS = (ARM_NONE, "uvr", "sidon", "dfn")ENHANCED_ARMS = ARMS[1:]#: Name of the optional config file in ``configs/data/``; absent = no enhancement.CONFIG_FILENAME = "enhance.yaml"#: Prefix of the local-cache folder (sibling of ``audio``) holding one arm's enhanced wavs.AUDIO_DIR_PREFIX = "audio-enh"#: Quarantine reasons of the pilot ``enhance`` stage.REASON_LENGTH = "enhance_length_mismatch"REASON_FAILED = "enhance_failed"REASON_CLIPPED = "enhance_clipped"#: Prefix of a pinned file hash in ``ModelRef.revision`` (``sha256:<64 hex digits>``).SHA256_REVISION_PREFIX = "sha256:"#: Keys of every successful worker payload (:func:`finish_enhanced_wav`); anything else in a#: payload came from :meth:`EnhanceAdapter.payload_extras`.PAYLOAD_KEYS = frozenset( { "out_path", "sample_rate_hz", "num_samples", "input_num_samples", "length_diff_samples", "peak", "loudness_dbfs", "clipping_ratio", "clipping_threshold", })_SHA256_HEX_LENGTH = 64_HASH_BLOCK_BYTES = 1 << 20
class EnhanceError(ValueError): """An arm returned unusable audio (not 1-D mono, empty or non-finite)."""
class EnhanceLengthError(EnhanceError): """The arm's output length differs from the input by more than the tolerance."""
class ArmUnavailableError(RuntimeError): """The arm cannot start at all (missing library, no GPU, silent CPU fallback)."""
def is_length_error(error: str | None) -> bool: """True if a worker result's ``error`` string (``"<Type>: <message>"``) is a length error.""" return error is not None and error.startswith(f"{EnhanceLengthError.__name__}:")
@dataclass(frozen=True)class EnhanceConfig: """``configs/data/enhance.yaml``.
Attributes: arm: ``none`` (no enhancement, the baseline), ``uvr``, ``sidon`` or ``dfn``. length_tolerance_ms: Largest tolerated difference, in milliseconds, between the enhanced and the input segment length (checked in 16 kHz samples). Larger differences make the segment an ``enhance_length_mismatch`` quarantine record (decided by the pilot from the recorded ``length_diff_samples``). max_length_diff_ms: Differences above this make the *worker* fail the item (also ``enhance_length_mismatch``); between the two limits the wav is still written. Must be >= ``length_tolerance_ms``. max_enhanced_clipping_ratio: Largest fraction of samples of the written (PCM16) wav that may sit at ``|x| >= acoustic.clipping_threshold`` (the S2 definition; the threshold is the one of ``acoustic.yaml``); more makes the segment an ``enhance_clipped`` quarantine record. In ``[0, 1]``. """
arm: str length_tolerance_ms: int max_length_diff_ms: int max_enhanced_clipping_ratio: float
def __post_init__(self) -> None: if self.arm not in ARMS: raise ValueError(f"enhance arm must be one of {ARMS}, got {self.arm!r}") for name in ("length_tolerance_ms", "max_length_diff_ms"): value = getattr(self, name) if isinstance(value, bool) or not isinstance(value, int) or value < 0: raise ValueError(f"{name} must be an integer >= 0, got {value!r}") if self.max_length_diff_ms < self.length_tolerance_ms: raise ValueError( f"max_length_diff_ms ({self.max_length_diff_ms}) must be >= " f"length_tolerance_ms ({self.length_tolerance_ms})" ) ratio = self.max_enhanced_clipping_ratio if isinstance(ratio, bool) or not isinstance(ratio, int | float): raise ValueError(f"max_enhanced_clipping_ratio must be a number, got {ratio!r}") if not (math.isfinite(ratio) and 0.0 <= ratio <= 1.0): raise ValueError(f"max_enhanced_clipping_ratio must be in [0, 1], got {ratio!r}")
@property def enabled(self) -> bool: return self.arm != ARM_NONE
@property def length_tolerance_samples(self) -> int: """The tolerance in 16 kHz samples (exact: 16 samples per millisecond).""" return self.length_tolerance_ms * REQUIRED_SAMPLE_RATE_HZ // 1000
@property def max_length_diff_samples(self) -> int: """The worker's refusal limit in 16 kHz samples.""" return self.max_length_diff_ms * REQUIRED_SAMPLE_RATE_HZ // 1000
@classmethod def from_mapping(cls, raw: Mapping[str, object]) -> EnhanceConfig: expected = { "arm", "length_tolerance_ms", "max_length_diff_ms", "max_enhanced_clipping_ratio", } if set(raw) != expected: raise ValueError( f"enhance config keys: missing={sorted(expected - set(raw))} " f"unknown={sorted(set(raw) - expected)}" ) arm = raw["arm"] if not isinstance(arm, str): raise ValueError(f"enhance arm must be a string, got {arm!r}") limits: dict[str, int] = {} for name in ("length_tolerance_ms", "max_length_diff_ms"): value = raw[name] if not isinstance(value, int): # bool is rejected by __post_init__ raise ValueError(f"{name} must be an integer, got {value!r}") limits[name] = value ratio = raw["max_enhanced_clipping_ratio"] if isinstance(ratio, bool) or not isinstance(ratio, int | float): raise ValueError(f"max_enhanced_clipping_ratio must be a number, got {ratio!r}") return cls(arm=arm, max_enhanced_clipping_ratio=float(ratio), **limits)
#: What a config directory without ``enhance.yaml`` means: the baseline pipeline. The limits are#: never read while the arm is ``none``.NO_ENHANCE = EnhanceConfig( arm=ARM_NONE, length_tolerance_ms=0, max_length_diff_ms=0, max_enhanced_clipping_ratio=0.0)
def audio_dir_name(arm: str) -> str: """Local-cache folder name of ``arm``'s enhanced wavs (``audio-enh-<arm>``).
Raises: ValueError: if ``arm`` is ``none`` or unknown. """ if arm not in ENHANCED_ARMS: raise ValueError(f"no enhanced audio for arm {arm!r}; arms: {ENHANCED_ARMS}") return f"{AUDIO_DIR_PREFIX}-{arm}"
def arm_suffix(arm: str) -> str: """Suffix of the arm-specific names (dataset directory, latent results, arrays).""" audio_dir_name(arm) # validates return f"-enh-{arm}"
# ------------------------------------------------------------------------ audio functions
@dataclass(frozen=True)class FittedAudio: """An arm output forced to the input length.
Attributes: samples: float32 mono at 16 kHz, exactly the expected number of samples. length_diff_samples: ``len(output after resampling) - len(input)`` *before* the pad/trim (positive = the arm returned more samples than the input had). peak: Largest absolute sample value before clipping to ``[-1, 1]``. """
samples: Waveform length_diff_samples: int peak: float
def resample_mono(samples: Waveform, src_hz: int, dst_hz: int) -> Waveform: """Polyphase resample (scipy); the input itself when the rates match.
Raises: ValueError: on a non-positive rate. """ import numpy as np from scipy.signal import resample_poly # type: ignore[import-untyped] # no stubs
if src_hz <= 0 or dst_hz <= 0: raise ValueError(f"sample rates must be positive, got {src_hz} -> {dst_hz}") if src_hz == dst_hz: return samples divisor = math.gcd(src_hz, dst_hz) out = resample_poly(samples.astype(np.float64), dst_hz // divisor, src_hz // divisor) return np.ascontiguousarray(out, dtype=np.float32)
def fit_to_length( samples: npt.ArrayLike, *, source_rate_hz: int, expected_num_samples: int, max_diff_samples: int, what: str,) -> FittedAudio: """Resample an arm output to 16 kHz and force it to ``expected_num_samples``.
Raises: EnhanceError: for non-1-D, empty or non-finite output. EnhanceLengthError: if the resampled length differs from ``expected_num_samples`` by more than ``max_diff_samples`` (nothing is padded or trimmed in that case). ValueError: on a non-positive ``expected_num_samples``, negative limit or bad rate. """ import numpy as np
if expected_num_samples < 1 or max_diff_samples < 0: raise ValueError( f"{what}: invalid expected length / limit: {expected_num_samples} / {max_diff_samples}" ) array = np.asarray(samples) if array.ndim != 1: raise EnhanceError(f"{what}: enhancer returned shape {array.shape}, expected 1-D mono") if array.size == 0: raise EnhanceError(f"{what}: enhancer returned no samples") if not np.isfinite(array).all(): raise EnhanceError(f"{what}: enhancer returned non-finite samples") resampled = resample_mono( array.astype(np.float32, copy=False), source_rate_hz, REQUIRED_SAMPLE_RATE_HZ ) diff = int(resampled.shape[0]) - expected_num_samples if abs(diff) > max_diff_samples: raise EnhanceLengthError( f"{what}: output has {resampled.shape[0]} samples at {REQUIRED_SAMPLE_RATE_HZ} Hz, " f"expected {expected_num_samples} (difference {diff} samples = " f"{1000.0 * diff / REQUIRED_SAMPLE_RATE_HZ:.1f} ms, limit {max_diff_samples} " "samples)" ) if diff >= 0: fitted = np.ascontiguousarray(resampled[:expected_num_samples]) else: fitted = np.pad(resampled, (0, -diff)) return FittedAudio(fitted, diff, float(np.abs(fitted).max()))
def encode_wav_pcm16(samples: Waveform) -> bytes: """The bytes of a 16 kHz mono PCM16 wav; ``samples`` are clipped to ``[-1, 1]`` first.""" import numpy as np import soundfile # type: ignore[import-untyped] # untyped
buffer = io.BytesIO() soundfile.write( buffer, np.clip(samples, -1.0, 1.0), REQUIRED_SAMPLE_RATE_HZ, subtype="PCM_16", format="WAV", ) return buffer.getvalue()
def wav_stats(data: bytes, *, clipping_threshold: float) -> tuple[float, float]: """``(loudness_dbfs, clipping_ratio)`` of the samples a wav file really holds.
Decoded from the bytes, so the numbers describe what was written (PCM16, clipped to ``[-1, 1]``). Both are the ingest (S2) measures, :func:`nida.data.acoustic.loudness_dbfs` and :func:`nida.data.acoustic.clipping_ratio` on the float64 samples, so enhanced and original audio are comparable. """ import soundfile
# numpy + scipy; kept out of the import time of this module from nida.data.acoustic import clipping_ratio, loudness_dbfs
decoded, _ = soundfile.read(io.BytesIO(data), dtype="float64", always_2d=False) return ( float(loudness_dbfs(decoded)), float(clipping_ratio(decoded, threshold=clipping_threshold)), )
def wav_loudness_dbfs(data: bytes) -> float: """RMS level in dBFS of the samples a wav file really holds (see :func:`wav_stats`).""" return wav_stats(data, clipping_threshold=1.0)[0]
def finish_enhanced_wav( *, out_path: Path, samples: npt.ArrayLike, source_rate_hz: int, input_num_samples: int, max_diff_samples: int, clipping_threshold: float, what: str,) -> dict[str, object]: """Fit an arm output to the input length, write it atomically, describe it.
The checks run before the write, so a failing segment leaves no output file.
Returns: Payload: ``out_path``, ``sample_rate_hz``, ``num_samples`` (== ``input_num_samples``), ``input_num_samples``, ``length_diff_samples`` (before the fix), ``peak`` (before clipping to the PCM16 range), ``loudness_dbfs`` and ``clipping_ratio`` (fraction of the PCM16 samples written at ``|x| >= clipping_threshold``, which is echoed back).
Raises: EnhanceError, EnhanceLengthError, ValueError: see :func:`fit_to_length`. """ fitted = fit_to_length( samples, source_rate_hz=source_rate_hz, expected_num_samples=input_num_samples, max_diff_samples=max_diff_samples, what=what, ) data = encode_wav_pcm16(fitted.samples) atomic_write_bytes(out_path, data) loudness, clipping = wav_stats(data, clipping_threshold=clipping_threshold) return { "out_path": str(out_path), "sample_rate_hz": REQUIRED_SAMPLE_RATE_HZ, "num_samples": int(fitted.samples.shape[0]), "input_num_samples": input_num_samples, "length_diff_samples": fitted.length_diff_samples, "peak": round(fitted.peak, 6), "loudness_dbfs": loudness, "clipping_ratio": clipping, "clipping_threshold": clipping_threshold, }
def wav_out_path_param(request: WorkRequest) -> Path: """The ``.wav`` output path named by ``request.params["out_path"]``.
Raises: ValueError: if the parameter is missing or does not end in ``.wav``. """ raw = request.params.get("out_path") if not raw: raise ValueError(f"{request.clip_id}: missing params.out_path") path = Path(raw) if path.suffix != ".wav": raise ValueError(f"{request.clip_id}: params.out_path must end in .wav, got {raw!r}") return path
def max_length_diff_param(request: WorkRequest) -> int: """``params["max_length_diff_ms"]`` converted to 16 kHz samples.
Raises: ValueError: if the parameter is missing, not a non-negative integer, or unreasonable. """ raw = request.params.get("max_length_diff_ms") if raw is None: raise ValueError(f"{request.clip_id}: missing params.max_length_diff_ms") try: milliseconds = int(raw) except ValueError: raise ValueError( f"{request.clip_id}: params.max_length_diff_ms must be an integer, got {raw!r}" ) from None if milliseconds < 0: raise ValueError(f"{request.clip_id}: params.max_length_diff_ms must be >= 0") return milliseconds * REQUIRED_SAMPLE_RATE_HZ // 1000
def clipping_threshold_param(request: WorkRequest) -> float: """``params["clipping_threshold"]``: the magnitude counted as clipped, in ``(0, 1]``.
Raises: ValueError: if the parameter is missing or not a number in ``(0, 1]``. """ raw = request.params.get("clipping_threshold") if raw is None: raise ValueError(f"{request.clip_id}: missing params.clipping_threshold") try: value = float(raw) except ValueError: raise ValueError( f"{request.clip_id}: params.clipping_threshold must be a number, got {raw!r}" ) from None if not (math.isfinite(value) and 0.0 < value <= 1.0): raise ValueError(f"{request.clip_id}: params.clipping_threshold must be in (0, 1]") return value
# ----------------------------------------------------------------------- worker template
class EnhanceAdapter(Adapter): """Template of the three arm workers: subclasses load a model and implement :meth:`enhance`.
Clips are processed one at a time (the arms are not batched), so a failing clip is an error of that clip only: the runner records it and carries on. """
@abc.abstractmethod def enhance(self, request: WorkRequest, wav: Waveform) -> tuple[Waveform, int]: """Enhance one clip.
Args: request: The request (``audio_path`` is the same file ``wav`` was read from). wav: float32 mono samples at 16 kHz, shape ``(num_samples,)``.
Returns: ``(samples, sample_rate_hz)``: a 1-D float waveform at any rate; the caller resamples it to 16 kHz and checks its length. """
def payload_extras(self) -> Mapping[str, object]: """Facts about the loaded model/runtime added to every payload (default: none).
They let the pilot record, e.g., the execution provider that really ran or the digests of model files that are recorded rather than pinned. Keys must not clash with the standard payload keys. """ return {}
def _one(self, request: WorkRequest) -> Mapping[str, object]: import soundfile
info = require_16k_mono(request) out_path = wav_out_path_param(request) max_diff_samples = max_length_diff_param(request) clipping_threshold = clipping_threshold_param(request) wav, _ = soundfile.read(request.audio_path, dtype="float32", always_2d=False) if wav.ndim != 1 or int(wav.shape[0]) != info.num_samples: raise ValueError(f"{request.clip_id}: read {wav.shape}, header says {info.num_samples}") samples, rate_hz = self.enhance(request, wav) extras = self.payload_extras() clash = sorted(set(extras) & PAYLOAD_KEYS) if clash: raise ValueError(f"{request.clip_id}: payload extras clash with {clash}") payload = finish_enhanced_wav( out_path=out_path, samples=samples, source_rate_hz=rate_hz, input_num_samples=info.num_samples, max_diff_samples=max_diff_samples, clipping_threshold=clipping_threshold, what=request.clip_id, ) return {**payload, **extras}
def run_batch(self, batch: Sequence[WorkRequest]) -> list[Mapping[str, object]]: return [self._one(request) for request in batch]
# ----------------------------------------------------------------------- shared arm checks
def resolve_device(device: str) -> str: """Validate ``device`` for this process; ``cpu`` hides CUDA before any library loads.
Raises: ArmUnavailableError: for CUDA requested but unavailable, torch missing, or a device string other than ``cpu`` / ``cuda*``. """ if device == "cpu": os.environ["CUDA_VISIBLE_DEVICES"] = "" return "cpu" if device.startswith("cuda"): try: import torch except ImportError as exc: raise ArmUnavailableError("torch is not installed in this environment") from exc if not torch.cuda.is_available(): raise ArmUnavailableError(f"device {device!r} requested but CUDA is not available here") return device raise ArmUnavailableError(f"unsupported device {device!r} (use cpu or cuda)")
def sha256_file(path: Path) -> str: """Hex SHA-256 of a file, read in 1 MiB blocks.""" digest = hashlib.sha256() with path.open("rb") as handle: for block in iter(lambda: handle.read(_HASH_BLOCK_BYTES), b""): digest.update(block) return digest.hexdigest()
def verify_pinned_sha256(path: Path, revision: str, *, what: str) -> str: """Check that ``path`` hashes to the digest pinned in ``revision`` (``sha256:<hex>``).
Returns: The verified digest.
Raises: ValueError: if ``revision`` is not a ``sha256:`` pin, the file is missing, or the digest differs (the model file is not the one the pipeline was validated with). """ if not revision.startswith(SHA256_REVISION_PREFIX): raise ValueError( f"{what}: revision must be '{SHA256_REVISION_PREFIX}<hex>', got {revision!r}" ) expected = revision.removeprefix(SHA256_REVISION_PREFIX) if len(expected) != _SHA256_HEX_LENGTH or set(expected) - set("0123456789abcdef"): raise ValueError(f"{what}: {revision!r} is not a lowercase SHA-256 hex digest") if not path.is_file(): raise ValueError(f"{what}: expected model file {path} does not exist") actual = sha256_file(path) if actual != expected: raise ValueError(f"{what}: {path.name} has sha256 {actual}, the pinned value is {expected}") return actual123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229"""Isolated ``uv`` environments for the Phase 1 data-pipeline model workers.
Same mechanism as :mod:`nida.bench.envs` (this module only *describes* environments; buildthem with :func:`nida.bench.envs.ensure_env`, which writes the freeze file and the marker):one environment per model family because their dependency stacks conflict (NeMo,FunASR/ModelScope, transformers, panns-inference/librosa). Python and the torch pins aretaken from the Phase 0 ``hf`` environment, so every worker environment runs the same``torch==2.8.0`` (cu128) build.
``EnvSpec.workers`` here are module names under ``nida.data.workers`` (see:func:`worker_module_name`), not under ``nida.bench.workers``.
Version pins (PyPI, looked up 2026-10-08):
* ``panns-inference==0.1.1`` (latest, 2023-03-26) with ``torchlibrosa==0.1.0`` (latest).* ``nemo_toolkit[asr]==3.0.0`` (latest, 2026-08-07; ``torch>=2.6.0`` so the torch 2.8.0 wheel is kept; the build's torch guard would catch a replacement). The model card asks for ``Cython`` and ``packaging`` to be installed first. System packages ``libsndfile1`` and ``ffmpeg`` must exist (present on Colab).* ``funasr==1.4.16`` (latest, 2026-09-18).* ``speechbrain==1.1.1`` (2026-08-27; the latest, 1.1.2, was published on 2026-10-14 and is not pinned yet: one day old). It requires ``torch>=2.1.0`` (the 2.8.0 wheel is kept), and its dependency ``hyperpyyaml==1.2.3`` (pinned explicitly) caps ``ruamel.yaml<0.19`` (0.19.x breaks HyperPyYAML with ``'Loader' object has no attribute 'max_depth'``), which the resolver respects. Importing ``speechbrain`` needs ``torchaudio`` (in the torch pins). Checked locally on CPU with torch and torchaudio 2.11.0 (not with the cu128 2.8.0 pair: unverified).* ``transformers==4.57.6``: **not** the latest (5.19.0, 2026-10-06). That is a new major version never exercised here; 4.57.6 is what the Phase 0 ``hf`` environment already ran with torch 2.8.0.
Unpinned helpers (numpy, soundfile, huggingface-hub, librosa, matplotlib) follow the benchenvironments; the exact resolved versions are recorded in each environment's ``freeze.txt``.
The speech-enhancement arms (:mod:`nida.data.enhance`) have their own mapping,:data:`ENHANCE_ENV_SPECS`, because their pins deliberately differ from the shared stack above(Python 3.11 for ``dfn``, numpy 1 vs 2, no torch pin for ``uvr``). They are the pins of``scripts/enhance_envs.sh`` (exercised for the A/B listening test, 2026-10-13), copiedunchanged; ``tests/test_data_enhance.py`` compares both. Same ``EnvSpec`` mechanism, so``ensure_env`` builds them; :func:`data_env_for_worker` looks in both mappings."""
from __future__ import annotations
from collections.abc import Mappingfrom types import MappingProxyType
from nida.bench.envs import ENV_SPECS as BENCH_ENV_SPECSfrom nida.bench.envs import EnvSpec
__all__ = [ "DATA_ENV_SPECS", "DATA_WORKER_PACKAGE", "ENHANCE_ENV_SPECS", "data_env_for_worker", "worker_module_name",]
#: Package whose modules are the Phase 1 workers.DATA_WORKER_PACKAGE = "nida.data.workers"
_BASE = BENCH_ENV_SPECS["hf"] # python + torch pins shared with Phase 0
DATA_ENV_SPECS: Mapping[str, EnvSpec] = MappingProxyType( { "data_sed": EnvSpec( name="data_sed", python=_BASE.python, torch_packages=_BASE.torch_packages, torch_index_url=_BASE.torch_index_url, packages=( "panns-inference==0.1.1", "torchlibrosa==0.1.0", "librosa", "matplotlib", "numpy", "soundfile", ), workers=("sed_panns",), ), "data_diar": EnvSpec( name="data_diar", python=_BASE.python, torch_packages=_BASE.torch_packages, torch_index_url=_BASE.torch_index_url, packages=( "Cython", "packaging", "nemo_toolkit[asr]==3.0.0", # Unpinned, the resolver picks transformers 4.12 + tokenizers 0.10 (no wheel # for py3.12, Rust build fails on Colab); pin the Phase 0 transformers. "transformers==4.57.6", "huggingface-hub<1.0", "numpy", "soundfile", ), workers=("diar_sortformer",), ), "data_ctc": EnvSpec( name="data_ctc", python=_BASE.python, torch_packages=_BASE.torch_packages, torch_index_url=_BASE.torch_index_url, packages=("transformers==4.57.6", "huggingface-hub", "numpy", "soundfile"), workers=("ctc_emissions",), ), "data_emotion": EnvSpec( name="data_emotion", python=_BASE.python, torch_packages=_BASE.torch_packages, torch_index_url=_BASE.torch_index_url, packages=( "funasr==1.4.16", "transformers==4.57.6", # same resolver trap as data_diar "huggingface-hub<1.0", "numpy", "soundfile", ), workers=("emotion_e2v",), ), # Speaker similarity (evaluation, scripts/speaker_sim.py): SpeechBrain ECAPA-TDNN. # scipy: SpeechBrain depends on it and the script resamples with it. "data_spk": EnvSpec( name="data_spk", python=_BASE.python, torch_packages=_BASE.torch_packages, torch_index_url=_BASE.torch_index_url, packages=( "speechbrain==1.1.1", # The version SpeechBrain 1.1.1 was checked with; it caps ruamel.yaml<0.19. "hyperpyyaml==1.2.3", "huggingface-hub", "numpy", "scipy", "soundfile", ), workers=("spk_ecapa",), ), # S9 latents: the B2 VAE stack (torch + torchaudio for resampling), without the # Audiobox quality model. "data_vae": EnvSpec( name="data_vae", python=_BASE.python, torch_packages=BENCH_ENV_SPECS["audio"].torch_packages, torch_index_url=_BASE.torch_index_url, packages=("numpy", "pydantic", "soundfile", "huggingface-hub"), workers=("vae_encode", "vae_decode"), ), })
#: scripts/enhance_envs.sh, copied: ``torch==2.8.0`` + ``torchaudio==2.8.0`` is the pair of the#: sidon/dfn venvs (PyPI's Linux 2.8.0 wheel is the CUDA 12.8 build, as is the cu128 index#: wheel installed here). ``uvr`` pins no torch: ``audio-separator[gpu]==0.47.0`` resolves its#: own (torch 2.14.1 and onnxruntime-gpu 1.31.0, CUDA 13 builds, NVIDIA driver >= 580; this#: combination was NOT exercised on a GPU: unverified, and to be pinned (torch, onnxruntime-gpu)#: from the first GPU run's freeze file) and ``ensure_env`` skips its torch step for an empty#: ``torch_packages``. ``[gpu]`` is the extra the script picks when ``nvidia-smi`` exists; if#: onnxruntime cannot activate the CUDA provider the worker aborts (it never runs on the CPU#: silently) and the A/B script's ``ENH_UVR_EXTRA=cpu`` variant is the fallback.ENHANCE_ENV_SPECS: Mapping[str, EnvSpec] = MappingProxyType( { "data_enh_uvr": EnvSpec( name="data_enh_uvr", python="3.12", torch_packages=(), torch_index_url="", packages=( "audio-separator[gpu]==0.47.0", "audioread==3.1.0", "numpy==2.5.4", "scipy==1.18.1", "soundfile==0.14.0", ), workers=("enhance_uvr",), ), "data_enh_sidon": EnvSpec( name="data_enh_sidon", python="3.12", torch_packages=_BASE.torch_packages, torch_index_url=_BASE.torch_index_url, packages=( "transformers==5.19.0", "huggingface_hub==2.2.0", "numpy==2.5.4", "scipy==1.18.1", "soundfile==0.14.0", ), workers=("enhance_sidon",), ), "data_enh_dfn": EnvSpec( name="data_enh_dfn", python="3.11", # deepfilterlib 0.5.6 has wheels for cp38..cp311 only torch_packages=_BASE.torch_packages, torch_index_url=_BASE.torch_index_url, packages=( "deepfilternet==0.5.6", "numpy==1.26.4", "scipy==1.17.1", "soundfile==0.14.0", ), workers=("enhance_dfn",), ), })
def data_env_for_worker(worker: str) -> EnvSpec: """Return the environment spec that runs the Phase 1 ``worker``.
Raises: ValueError: if no data (or enhancement) environment lists ``worker``. """ specs = (*DATA_ENV_SPECS.values(), *ENHANCE_ENV_SPECS.values()) for spec in specs: if worker in spec.workers: return spec known = sorted(w for spec in specs for w in spec.workers) raise ValueError(f"unknown data worker {worker!r}; known workers: {known}")
def worker_module_name(worker: str) -> str: """Dotted module to run with ``python -m`` for ``worker``.
Raises: ValueError: if ``worker`` is not a known data worker. """ data_env_for_worker(worker) # validates the name return f"{DATA_WORKER_PACKAGE}.{worker}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183"""S6 — frame-level sound-event probabilities → :class:`EventDetection` intervals.
The tagger (PANNs ``Cnn14_DecisionLevelMax``) gives per-frame probabilities for AudioSetclasses. Each Nida event kind maps to one or more AudioSet classes (tag-spec §2, R3); thekind's frame probability is the maximum over its classes. A detection is a maximal run offrames at or above ``onset`` (gaps up to ``merge_gap_ms`` are bridged); its confidence isthe maximum frame probability inside the run. Fusion (S7) then applies the per-kindconfidence bands, so ``onset`` must not exceed any band's ``low`` — otherwise amiddle-band event could vanish here instead of dropping its segment. Runs shorter thanthe kind's ``min_ms`` are not detections; for each kind the highest confidence among suchblips is returned (``too_short``), never silently discarded — the caller drops a segmentwhose blip reaches the fusion band ``low`` (precision before recall, tag-spec §7)."""
from __future__ import annotations
import mathfrom collections.abc import Mapping, Sequencefrom dataclasses import dataclassfrom typing import TYPE_CHECKING
from nida.data.types import EventDetectionfrom nida.text.tags import EVENTS
if TYPE_CHECKING: import numpy as np from numpy.typing import NDArray
__all__ = ["EventConfig", "FrameDetections", "detect_events"]
_NON_DETECTABLE = frozenset({"pause_short", "pause_long"})
@dataclass(frozen=True)class EventConfig: """configs/data/events.yaml. ``classes[kind]`` lists AudioSet display names."""
classes: Mapping[str, tuple[str, ...]] onset: float merge_gap_ms: int min_ms: Mapping[str, int]
def __post_init__(self) -> None: kinds = set(EVENTS) - _NON_DETECTABLE if set(self.classes) != kinds: raise ValueError( f"classes must map exactly {sorted(kinds)}; " f"missing={sorted(kinds - set(self.classes))} " f"extra={sorted(set(self.classes) - kinds)}" ) if set(self.min_ms) != kinds: raise ValueError("min_ms must have exactly one entry per detectable event kind") seen: dict[str, str] = {} for kind, names in self.classes.items(): if not names: raise ValueError(f"event kind {kind!r} maps to no AudioSet class") for name in names: if name in seen: raise ValueError( f"AudioSet class {name!r} mapped to {seen[name]!r} and {kind!r}" ) seen[name] = kind if not (math.isfinite(self.onset) and 0.0 < self.onset <= 1.0): raise ValueError(f"onset must be in (0, 1], got {self.onset!r}") for name, value in [("merge_gap_ms", self.merge_gap_ms), *self.min_ms.items()]: if isinstance(value, bool) or not isinstance(value, int) or value < 0: raise ValueError(f"{name} must be a non-negative int, got {value!r}")
@classmethod def from_mapping(cls, raw: Mapping[str, object]) -> EventConfig: expected = {"classes", "onset", "merge_gap_ms", "min_ms"} if set(raw) != expected: raise ValueError( f"event config keys: missing={sorted(expected - set(raw))} " f"unknown={sorted(set(raw) - expected)}" ) classes, min_ms, onset, gap = ( raw["classes"], raw["min_ms"], raw["onset"], raw["merge_gap_ms"], ) if not isinstance(classes, Mapping) or not all( isinstance(v, list) and all(isinstance(n, str) for n in v) for v in classes.values() ): raise ValueError("classes must map kinds to lists of class names") if not isinstance(min_ms, Mapping): raise ValueError("min_ms must be a mapping") if isinstance(onset, bool) or not isinstance(onset, int | float): raise ValueError("onset must be a number") if isinstance(gap, bool) or not isinstance(gap, int): raise ValueError("merge_gap_ms must be an int") return cls( classes={str(k): tuple(v) for k, v in classes.items()}, onset=float(onset), merge_gap_ms=gap, min_ms={str(k): v for k, v in min_ms.items()}, # validated in __post_init__ )
def check_onset_against(self, band_lows: Mapping[str, float]) -> None: """Raise if ``onset`` exceeds a fusion band's ``low`` for some event kind.""" missing = sorted(set(self.classes) - set(band_lows)) if missing: raise ValueError(f"no fusion band for event kinds {missing}") too_high = sorted(k for k in self.classes if band_lows[k] < self.onset) if too_high: raise ValueError(f"onset {self.onset} above the fusion band low of {too_high}")
@dataclass(frozen=True)class FrameDetections: detections: tuple[EventDetection, ...] too_short: Mapping[str, float] # kind -> max confidence among too-short runs
def detect_events( probs: NDArray[np.float32], class_names: Sequence[str], *, frame_hop_ms: float, duration_ms: int, cfg: EventConfig, source: str,) -> FrameDetections: """Turn framewise class probabilities ``[num_frames, len(class_names)]`` into detections.
Frame ``t`` covers ``[t * hop, (t + 1) * hop)`` ms, clamped to ``duration_ms``.
Raises: ValueError: shape mismatch, values outside [0, 1] or non-finite, a configured class missing from ``class_names``, a bad hop or duration, or a frame count inconsistent with ``duration_ms`` (more than one frame of slack). """ import numpy as np
if probs.ndim != 2 or probs.shape[1] != len(class_names): raise ValueError(f"probs shape {probs.shape} does not match {len(class_names)} classes") if len(set(class_names)) != len(class_names): raise ValueError("duplicate class names") in_range = probs.size == 0 or (float(np.min(probs)) >= 0.0 and float(np.max(probs)) <= 1.0) if not np.all(np.isfinite(probs)) or not in_range: raise ValueError("probabilities must be finite and in [0, 1]") if not (math.isfinite(frame_hop_ms) and frame_hop_ms >= 1): raise ValueError(f"frame_hop_ms must be a finite number >= 1 ms, got {frame_hop_ms!r}") if type(duration_ms) is not int or duration_ms <= 0: raise ValueError(f"invalid duration_ms {duration_ms!r}") expected_frames = duration_ms / frame_hop_ms if abs(probs.shape[0] - expected_frames) > 1 + 1e-9: raise ValueError( f"{probs.shape[0]} frames for {duration_ms} ms at {frame_hop_ms} ms hop " f"(expected about {expected_frames:.1f})" ) column = {name: i for i, name in enumerate(class_names)} missing = sorted({n for names in cfg.classes.values() for n in names} - set(column)) if missing: raise ValueError(f"tagger output lacks configured classes {missing}") gap_frames = math.floor(cfg.merge_gap_ms / frame_hop_ms)
detections: list[EventDetection] = [] too_short: dict[str, float] = {} for kind in sorted(cfg.classes): kind_probs = probs[:, [column[n] for n in cfg.classes[kind]]].max(axis=1) active = np.flatnonzero(kind_probs >= cfg.onset) if active.size == 0: continue runs: list[tuple[int, int]] = [] # inclusive frame ranges start = prev = int(active[0]) for frame in active[1:].tolist(): if frame - prev - 1 > gap_frames: runs.append((start, prev)) start = frame prev = frame runs.append((start, prev)) for first, last in runs: start_ms = min(round(first * frame_hop_ms), duration_ms - 1) end_ms = min(round((last + 1) * frame_hop_ms), duration_ms) conf = float(np.max(kind_probs[first : last + 1])) if end_ms - start_ms < cfg.min_ms[kind]: too_short[kind] = max(too_short.get(kind, 0.0), conf) continue detections.append(EventDetection(kind, start_ms, end_ms, conf, source)) detections.sort(key=lambda d: (d.start_ms, d.end_ms, d.kind)) return FrameDetections(tuple(detections), too_short)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227"""Filler candidates from CTC emissions in the gaps between aligned words (prototype).
docs/research/dolgu-tespiti-oneri.md, option A. Neither the primary nor the secondary ASRwrites fillers (B1-C), but the character CTC model may still emit their letters where thespeaker hesitates. For every silent-in-the-transcript gap (segment start → first word,between words, last word → end) of at least ``min_gap_ms``, the emissions inside the gapare greedily decoded (argmax, collapse repeats, drop blanks and word delimiters). If thedecoded string is a filler spelling, the gap yields a candidate.
Option A was accepted by the user (2026-10-09). :func:`insert_fillers` turns acceptedcandidates into extra :class:`TimedWord` items before fusion (S7); whether that happens is``configs/data/fillers.yaml`` ``enabled`` (off until the filler listening panel shows theprecision, docs/research/dolgu-tespiti-oneri.md)."""
from __future__ import annotations
import mathfrom collections.abc import Mapping, Sequencefrom dataclasses import dataclassfrom itertools import pairwisefrom typing import TYPE_CHECKING
from nida.data.types import TimedWordfrom nida.text.fillers import canonical_filler
if TYPE_CHECKING: import numpy as np from numpy.typing import NDArray
__all__ = [ "CTC_ONLY_FILLERS", "FillerCandidate", "FillerConfig", "gap_filler_candidates", "insert_fillers",]
#: Greedy CTC collapses doubled letters without a blank between them, so a drawn-out#: "ıı" or "mm" often decodes as a single letter. These single-letter forms are accepted#: *only* inside a gap (never in running text, where "e" is a conjunction).CTC_ONLY_FILLERS: Mapping[str, str] = {"e": "ee", "m": "hmm", "a": "aa"}
@dataclass(frozen=True)class FillerCandidate: """A proposed filler: canonical text, time span (ms) and evidence.
``start_ms``/``end_ms`` is the examined gap; ``speech_start_ms``/``speech_end_ms`` the part of it from the first to the last non-blank frame (where the filler is voiced). ``conf`` is the mean argmax probability over the gap's non-blank frames; ``decoded`` is the raw greedy string. """
text: str start_ms: int end_ms: int conf: float decoded: str speech_start_ms: int speech_end_ms: int
@dataclass(frozen=True)class FillerConfig: """``configs/data/fillers.yaml``. All keys required."""
enabled: bool min_gap_ms: int min_conf: float fillers: frozenset[str]
def __post_init__(self) -> None: if not isinstance(self.enabled, bool): raise ValueError("enabled must be a bool") if isinstance(self.min_gap_ms, bool) or not isinstance(self.min_gap_ms, int): raise ValueError("min_gap_ms must be an int") if self.min_gap_ms < 1: raise ValueError("min_gap_ms must be >= 1") if isinstance(self.min_conf, bool) or not isinstance(self.min_conf, int | float): raise ValueError("min_conf must be a number") if not (math.isfinite(self.min_conf) and 0.0 <= self.min_conf <= 1.0): raise ValueError("min_conf must be in [0, 1]") unknown = sorted(f for f in self.fillers if canonical_filler(f) != f) if unknown or not self.fillers: raise ValueError(f"fillers must be non-empty canonical filler forms, bad: {unknown}")
@classmethod def from_mapping(cls, raw: Mapping[str, object]) -> FillerConfig: expected = {"enabled", "min_gap_ms", "min_conf", "fillers"} if set(raw) != expected: raise ValueError( f"fillers config keys: missing={sorted(expected - set(raw))} " f"unknown={sorted(set(raw) - expected)}" ) fillers = raw["fillers"] if not isinstance(fillers, list) or not all(isinstance(f, str) for f in fillers): raise ValueError("fillers must be a list of strings") return cls( enabled=raw["enabled"], # type: ignore[arg-type] # validated in __post_init__ min_gap_ms=raw["min_gap_ms"], # type: ignore[arg-type] min_conf=raw["min_conf"], # type: ignore[arg-type] fillers=frozenset(fillers), )
def _greedy( log_probs: NDArray[np.float64], skip: set[int], id_to_token: Sequence[str]) -> tuple[str, float, int, int]: """Collapsed argmax string of ``log_probs``, mean prob of its non-skipped frames, and the first / one-past-last non-skipped frame (``0, 0`` when there is none).""" import numpy as np
best = np.argmax(log_probs, axis=1) chars: list[str] = [] probs: list[float] = [] frames: list[int] = [] previous = -1 for frame, token in enumerate(best.tolist()): if token not in skip: probs.append(math.exp(float(log_probs[frame, token]))) frames.append(frame) if token != previous: chars.append(id_to_token[token]) previous = token if not frames: return "", 0.0, 0, 0 return "".join(chars), sum(probs) / len(probs), frames[0], frames[-1] + 1
def gap_filler_candidates( words: Sequence[TimedWord], log_probs: NDArray[np.float32], vocab: Mapping[str, int], *, blank_token: str, word_delimiter: str, frame_hop_ms: float, duration_ms: int, min_gap_ms: int = 150,) -> list[FillerCandidate]: """Filler candidates in the gaps of an aligned segment.
Args: words: Aligned words (relative ms, in order, non-overlapping), possibly empty. log_probs: ``[num_frames, vocab_size]`` CTC emissions (log-softmax re-applied here). vocab: Token → id, ids exactly ``0..V-1``. blank_token, word_delimiter: Special tokens (``[PAD]``, ``|`` for wav2vec2 HF). frame_hop_ms: Frame stride (20 ms for wav2vec2). duration_ms: Segment length. min_gap_ms: Shorter gaps are not examined.
Returns: Candidates in time order.
Raises: ValueError: malformed inputs. """ import numpy as np
if log_probs.ndim != 2 or log_probs.shape[1] != len(vocab): raise ValueError(f"log_probs shape {log_probs.shape} does not match vocab {len(vocab)}") if sorted(vocab.values()) != list(range(len(vocab))): raise ValueError("vocab ids must be exactly 0..V-1") if blank_token not in vocab or word_delimiter not in vocab: raise ValueError("blank or word delimiter missing from vocab") if not (math.isfinite(frame_hop_ms) and frame_hop_ms >= 1): raise ValueError(f"frame_hop_ms must be finite and >= 1, got {frame_hop_ms!r}") if min_gap_ms < 1 or duration_ms <= 0: raise ValueError("min_gap_ms and duration_ms must be positive") lp = log_probs.astype(np.float64) row_max = np.max(lp, axis=1, keepdims=True) if not np.all(np.isfinite(row_max)): raise ValueError("a frame has no finite log-probability") lp = lp - (row_max + np.log(np.sum(np.exp(lp - row_max), axis=1, keepdims=True))) id_to_token = [""] * len(vocab) for token, index in vocab.items(): id_to_token[index] = token skip = {vocab[blank_token], vocab[word_delimiter]}
edges = [0, *[x for w in words for x in (w.start_ms, w.end_ms)], duration_ms] candidates: list[FillerCandidate] = [] for start_ms, end_ms in zip(edges[0::2], edges[1::2], strict=True): if end_ms - start_ms < min_gap_ms: continue first = math.ceil(start_ms / frame_hop_ms) last = min(math.floor(end_ms / frame_hop_ms), lp.shape[0]) if last <= first: continue decoded, conf, voiced_first, voiced_last = _greedy(lp[first:last], skip, id_to_token) if not decoded: continue text = canonical_filler(decoded) or CTC_ONLY_FILLERS.get(decoded) if text is not None: speech_start = max(start_ms, round((first + voiced_first) * frame_hop_ms)) speech_end = min(end_ms, round((first + voiced_last) * frame_hop_ms)) if speech_end <= speech_start: # rounding at a gap edge: keep one ms speech_start = min(speech_start, end_ms - 1) speech_end = speech_start + 1 candidates.append( FillerCandidate(text, start_ms, end_ms, conf, decoded, speech_start, speech_end) ) return candidates
def insert_fillers( words: Sequence[TimedWord], candidates: Sequence[FillerCandidate], cfg: FillerConfig) -> tuple[tuple[TimedWord, ...], list[FillerCandidate]]: """Words with the accepted candidates added as filler words, in time order.
A candidate is accepted when its text is in ``cfg.fillers`` and ``conf >= min_conf``; it becomes ``TimedWord(text, speech_start_ms, speech_end_ms)`` (no alignment score). Candidates come from the gaps of ``words``, so they never overlap a word.
Returns: ``(words_with_fillers, accepted_candidates)``.
Raises: ValueError: a candidate overlaps a word or another candidate (a caller bug). """ accepted = [c for c in candidates if c.text in cfg.fillers and c.conf >= cfg.min_conf] added = [TimedWord(c.text, c.speech_start_ms, c.speech_end_ms) for c in accepted] merged = sorted([*words, *added], key=lambda w: (w.start_ms, w.end_ms)) for a, b in pairwise(merged): if b.start_ms < a.end_ms: raise ValueError(f"filler overlaps a word: {a} / {b}") return tuple(merged), accepted123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842"""S7 — deterministic fusion of transcript, alignment and paralinguistic detections.
Turns one segment's aligned words (S5), event detections and per-word style scores (S6)into tagged text following docs/02-tag-spec.md, or into a quarantine record with amachine-readable reason. No LLM, no randomness: the same inputs always give the sameoutput. Rules (docs/03-data-pipeline.md S7, tag-spec §7):
1. Bands: a detection below ``low`` is ignored (and counted); at or above ``high`` it is used; in the middle band ``[low, high)`` it drops the whole segment (``ambiguous_event`` / ``ambiguous_style``) — unless every millisecond of it is covered by confident detections of the same family (then the event is there anyway).2. Families: ``laugh`` and ``laugh_long`` are one family, every other kind its own. Confident detections of one family that overlap or are at most ``merge_gap_ms`` apart are merged.3. Speech overlap: a laugh/cry detection covering more than ``style_word_overlap`` of a word's duration marks the word ``laughing`` / ``crying``. If its longest non-speech part is at least ``min_residual_event_ms`` it is *also* placed as an event. Any other detection whose speech overlap exceeds ``max_event_speech_overlap`` of its length drops the segment (``event_overlaps_speech``: false positive or overlapped audio).4. Placement: an event is placed at the word gap nearest the middle of its longest non-speech part. A laugh becomes ``laugh_long`` if a detector said so or that placed part lasts at least ``laugh_long_min_ms``. Placed events of different kinds whose parts overlap by more than ``max_cross_kind_overlap`` of the shorter one drop the segment (``conflicting_events``): taggers often fire related classes on one sound.5. Spans: consecutive words marked with the same style form a span if they are at least ``min_span_words`` words or ``min_span_ms`` long; a shorter run drops the segment (``short_style_run``: audible but untaggable). A word with two styles drops the segment (``conflicting_styles``). Per-word score tracks of an ``ignored_styles`` style are discarded before any of this: the detector is known to be unreliable, so it neither tags nor drops anything (unlike ``disabled_tags``, which drop the segment whenever the detector fires at or above ``low``).6. Pauses: measured on the longest part of an inter-word gap not covered by a confident detection. Longer than ``pause_long_ms`` → ``pause_long``; at least ``pause_short_ms`` → ``pause_short`` unless the previous word ends in punctuation. None at segment edges.7. Text: words are NFC; standalone fillers are canonicalised to their lowercase canonical form (tag-spec §4); words with digits drop the segment (``unnormalised_number``) until number normalisation exists; ``[ ] < >`` in a word drops it (``reserved_char_in_text``). The output is validated by round-tripping through :func:`nida.text.tags.parse` (``invalid_output``)."""
from __future__ import annotations
import mathimport unicodedatafrom collections.abc import Mapping, Sequencefrom dataclasses import dataclass, field
from nida.data.types import EventDetection, QuarantineRecord, TimedWord, WordStyleScorefrom nida.text.fillers import canonical_fillerfrom nida.text.tags import EVENTS, SPANS, Event, Item, Span, TagSyntaxError, Word, parse, renderfrom nida.text.turkish import nfc, tr_lower
__all__ = [ "EMOTION_LABELS", "STAGE", "STYLE_FROM_EVENT", "Band", "EmotionCondition", "FusionConfig", "FusionResult", "TagRecord", "emotion_condition", "fuse_segment", "normalise_word",]
STAGE = "fusion"
#: Event families that, when they overlap words, mean the words carry a style (rule 3).STYLE_FROM_EVENT: Mapping[str, str] = {"laugh": "laughing", "cry": "crying"}
#: Output classes of the emotion model (emotion2vec+); ``other``/``unknown`` map to null.EMOTION_LABELS: frozenset[str] = frozenset( {"angry", "disgusted", "fearful", "happy", "neutral", "other", "sad", "surprised", "unknown"})_NULL_EMOTIONS = frozenset({"other", "unknown"})_PAUSE_EVENTS = frozenset({"pause_short", "pause_long"})_RESERVED_CHARS = frozenset("[]<>")
def _family(kind: str) -> str: return "laugh" if kind in {"laugh", "laugh_long"} else kind
@dataclass(frozen=True)class Band: """Confidence band: ``< low`` ignored, ``[low, high)`` ambiguous, ``>= high`` used."""
low: float high: float
def __post_init__(self) -> None: if not (0.0 <= self.low <= self.high <= 1.0): raise ValueError(f"invalid band low={self.low} high={self.high}")
_INT_FIELDS = ( "min_span_words", "min_span_ms", "min_residual_event_ms", "laugh_long_min_ms", "merge_gap_ms", "pause_short_ms", "pause_long_ms",)_FRACTION_FIELDS = ( "style_word_overlap", "max_event_speech_overlap", "max_cross_kind_overlap", "emotion_min_conf",)
@dataclass(frozen=True)class FusionConfig: """Fusion thresholds (configs/data/fusion.yaml). All fields are required."""
bands: Mapping[str, Band] disabled_tags: frozenset[str] ignored_styles: frozenset[str] min_span_words: int min_span_ms: int style_word_overlap: float max_event_speech_overlap: float max_cross_kind_overlap: float min_residual_event_ms: int laugh_long_min_ms: int merge_gap_ms: int pause_short_ms: int pause_long_ms: int emotion_min_conf: float
def __post_init__(self) -> None: required = (set(EVENTS) - _PAUSE_EVENTS) | set(SPANS) if set(self.bands) != required: missing = sorted(required - set(self.bands)) extra = sorted(set(self.bands) - required) raise ValueError(f"bands must cover exactly the detectable tags: {missing=} {extra=}") unknown = self.disabled_tags - (set(EVENTS) | set(SPANS)) if unknown: raise ValueError(f"unknown disabled tags {sorted(unknown)}") # Only styles that come as per-word score tracks can be ignored; laughing/crying # come from events (STYLE_FROM_EVENT) and have no track to discard. scored = set(SPANS) - set(STYLE_FROM_EVENT.values()) not_styles = self.ignored_styles - scored if not_styles: raise ValueError( f"ignored_styles must be span styles with score tracks {sorted(scored)}, " f"got {sorted(not_styles)}" ) both = self.ignored_styles & self.disabled_tags if both: raise ValueError(f"tags both disabled and ignored: {sorted(both)}") for name in _INT_FIELDS: value = getattr(self, name) if isinstance(value, bool) or not isinstance(value, int) or value < 0: raise ValueError(f"{name} must be a non-negative int, got {value!r}") if self.min_span_words < 1: raise ValueError("min_span_words must be >= 1") if self.min_residual_event_ms < 1: raise ValueError("min_residual_event_ms must be >= 1") for name in _FRACTION_FIELDS: value = getattr(self, name) if isinstance(value, bool) or not isinstance(value, int | float): raise ValueError(f"{name} must be a number, got {value!r}") if not (math.isfinite(value) and 0.0 <= value <= 1.0): raise ValueError(f"{name} must be in [0, 1], got {value!r}") if not 0 < self.pause_short_ms <= self.pause_long_ms: raise ValueError("need 0 < pause_short_ms <= pause_long_ms")
@classmethod def from_mapping(cls, raw: Mapping[str, object]) -> FusionConfig: """Build from a parsed YAML mapping; unknown or missing keys are errors.""" expected = {f.name for f in cls.__dataclass_fields__.values()} if set(raw) != expected: raise ValueError( f"fusion config keys: missing={sorted(expected - set(raw))} " f"unknown={sorted(set(raw) - expected)}" ) bands_raw = raw["bands"] if not isinstance(bands_raw, Mapping): raise ValueError("bands must be a mapping") bands: dict[str, Band] = {} for kind, band in bands_raw.items(): if not isinstance(band, Mapping) or set(band) != {"low", "high"}: raise ValueError(f"band {kind!r} must be a mapping with exactly low/high") low, high = band["low"], band["high"] if not all(isinstance(v, int | float) and not isinstance(v, bool) for v in (low, high)): raise ValueError(f"band {kind!r} values must be numbers") bands[str(kind)] = Band(float(low), float(high)) disabled = raw["disabled_tags"] if not isinstance(disabled, list) or not all(isinstance(t, str) for t in disabled): raise ValueError("disabled_tags must be a list of tag ids") ignored = raw["ignored_styles"] if not isinstance(ignored, list) or not all(isinstance(t, str) for t in ignored): raise ValueError("ignored_styles must be a list of style ids") lists = {"bands", "disabled_tags", "ignored_styles"} values = {k: v for k, v in raw.items() if k not in lists} # The remaining values are typed `object` here; __post_init__ validates each one. return cls( bands=bands, disabled_tags=frozenset(disabled), ignored_styles=frozenset(ignored), **values, # type: ignore[arg-type] )
@dataclass(frozen=True)class TagRecord: """Provenance of one emitted tag (tag-spec §7.3): ``{id, start, end, conf, source}``.
``start_ms``/``end_ms`` is what the tag stands for (the placed non-speech part of an event, the words of a span, the silence of a pause); ``det_start_ms``/``det_end_ms`` is the merged detector interval it came from, so it can be checked against the detector output. """
tag: str start_ms: int end_ms: int conf: float source: str det_start_ms: int det_end_ms: int
@dataclass(frozen=True)class FusionResult: """Either ``items``/``text`` (accepted) or ``quarantine`` (dropped), never both."""
segment_id: str items: tuple[Item, ...] | None text: str | None tags: tuple[TagRecord, ...] quarantine: QuarantineRecord | None ignored_detections: int = 0 #: The below-band detections themselves (``len == ignored_detections``), so a caller can #: record what was heard but left untagged (ADR-0010: uncertain breaths keep the segment). ignored_events: tuple[EventDetection, ...] = ()
def __post_init__(self) -> None: accepted = self.items is not None and self.text is not None dropped = self.items is None and self.text is None and not self.tags if self.quarantine is None and not accepted: raise ValueError("accepted result needs items and text") if self.quarantine is not None and not dropped: raise ValueError("quarantined result must not carry items, text or tags")
@property def accepted(self) -> bool: return self.quarantine is None
@dataclass(frozen=True)class EmotionCondition: emotion: str | None intensity: float | None
@dataclassclass _Merged: family: str kinds: set[str] start_ms: int end_ms: int conf: float sources: set[str] = field(default_factory=set)
@property def source(self) -> str: return "+".join(sorted(self.sources))
@dataclass(frozen=True)class _Placed: gap: int kind: str start_ms: int end_ms: int event: _Merged
class _Drop(Exception): """Internal: the segment is quarantined with ``reason``."""
def __init__(self, reason: str, **details: object) -> None: super().__init__(reason) self.reason = reason self.details = details
def _overlap_ms(a_start: int, a_end: int, b_start: int, b_end: int) -> int: return max(0, min(a_end, b_end) - max(a_start, b_start))
def _union(intervals: Sequence[tuple[int, int]]) -> list[tuple[int, int]]: out: list[tuple[int, int]] = [] for start, end in sorted(intervals): if out and start <= out[-1][1]: out[-1] = (out[-1][0], max(out[-1][1], end)) else: out.append((start, end)) return out
def _validate_inputs( words: Sequence[TimedWord], duration_ms: int, events: Sequence[EventDetection], styles: Sequence[WordStyleScore],) -> None: if type(duration_ms) is not int or duration_ms <= 0: raise ValueError(f"duration_ms must be a positive int, got {duration_ms!r}") previous_end = 0 for word in words: if word.start_ms < previous_end: raise ValueError(f"words overlap or are unsorted at {word.text!r} ({word.start_ms} ms)") if word.end_ms > duration_ms: raise ValueError(f"word {word.text!r} ends after the segment ({word.end_ms} ms)") previous_end = word.end_ms for event in events: if event.kind not in EVENTS or event.kind in _PAUSE_EVENTS: raise ValueError(f"not a detectable event kind: {event.kind!r}") if event.end_ms > duration_ms: raise ValueError(f"event {event.kind!r} ends after the segment") seen: set[str] = set() for style in styles: if style.style not in SPANS: raise ValueError(f"unknown style {style.style!r}") if style.style in seen: raise ValueError(f"duplicate style scores for {style.style!r}") seen.add(style.style) if len(style.scores) != len(words): raise ValueError( f"style {style.style!r} has {len(style.scores)} scores for {len(words)} words" )
def _split_by_band( events: Sequence[EventDetection], cfg: FusionConfig) -> tuple[list[EventDetection], list[EventDetection], list[EventDetection]]: """(confident, middle band, ignored = below ``low``).""" confident: list[EventDetection] = [] middle: list[EventDetection] = [] ignored: list[EventDetection] = [] for event in events: band = cfg.bands[event.kind] if event.conf < band.low: ignored.append(event) elif event.conf < band.high: middle.append(event) else: confident.append(event) return confident, middle, ignored
def _merge_confident( confident: Sequence[EventDetection], middle: Sequence[EventDetection], cfg: FusionConfig) -> list[_Merged]: """Rules 1–2: ambiguity check against confident cover, then per-family merging.""" cover: dict[str, list[tuple[int, int]]] = {} for event in confident: cover.setdefault(_family(event.kind), []).append((event.start_ms, event.end_ms)) union = {family: _union(spans) for family, spans in cover.items()} for event in sorted(middle, key=lambda e: (e.start_ms, e.end_ms, e.kind, e.source, e.conf)): if event.kind in cfg.disabled_tags: raise _Drop("disabled_tag", tag=event.kind, start_ms=event.start_ms, conf=event.conf) covered = sum( _overlap_ms(event.start_ms, event.end_ms, a, b) for a, b in union.get(_family(event.kind), []) ) if covered < event.duration_ms: raise _Drop( "ambiguous_event", kind=event.kind, conf=event.conf, start_ms=event.start_ms, end_ms=event.end_ms, source=event.source, ) for event in sorted(confident, key=lambda e: (e.start_ms, e.end_ms, e.kind, e.source)): if event.kind in cfg.disabled_tags: # Checked on the raw kind too: a disabled `laugh` must not survive by being # relabelled `laugh_long` after merging. raise _Drop("disabled_tag", tag=event.kind, start_ms=event.start_ms, conf=event.conf) merged: list[_Merged] = [] ordered = sorted( confident, key=lambda e: (_family(e.kind), e.start_ms, e.end_ms, e.kind, e.source) ) for event in ordered: family = _family(event.kind) last = merged[-1] if merged else None if ( last is not None and last.family == family and event.start_ms <= last.end_ms + cfg.merge_gap_ms ): last.end_ms = max(last.end_ms, event.end_ms) last.conf = max(last.conf, event.conf) last.kinds.add(event.kind) last.sources.add(event.source) else: merged.append( _Merged( family, {event.kind}, event.start_ms, event.end_ms, event.conf, {event.source} ) ) return sorted(merged, key=lambda m: (m.start_ms, m.end_ms, m.family))
def _non_speech_pieces( start_ms: int, end_ms: int, words: Sequence[TimedWord]) -> list[tuple[int, int]]: """Parts of ``[start_ms, end_ms)`` not covered by any word (words are sorted, disjoint).""" pieces: list[tuple[int, int]] = [] cursor = start_ms for word in words: if word.end_ms <= cursor: continue if word.start_ms >= end_ms: break if word.start_ms > cursor: pieces.append((cursor, word.start_ms)) cursor = max(cursor, word.end_ms) if cursor < end_ms: pieces.append((cursor, end_ms)) return pieces
def _nearest_gap(time_ms: float, words: Sequence[TimedWord]) -> int: """Gap ``g`` lies before word ``g`` (``g == len(words)``: after the last word).""" for index, word in enumerate(words): if time_ms <= word.start_ms: return index if time_ms < word.end_ms: # Inside a word (defensive: callers pass the middle of a non-speech piece, which # never lies inside a word): the closer boundary wins; a tie goes after it. return index if time_ms - word.start_ms < word.end_ms - time_ms else index + 1 return len(words)
def _event_kind(event: _Merged, placed_ms: int, cfg: FusionConfig) -> str: if event.family != "laugh": return event.family if "laugh_long" in event.kinds or placed_ms >= cfg.laugh_long_min_ms: return "laugh_long" return "laugh"
def _place_events( merged: Sequence[_Merged], words: Sequence[TimedWord], cfg: FusionConfig) -> tuple[list[_Placed], list[tuple[str, list[int], _Merged]]]: """Rules 3–4. Returns (placed events, style evidence ``(style, word indices, event)``).""" placed: list[_Placed] = [] style_events: list[tuple[str, list[int], _Merged]] = [] for event in merged: length = event.end_ms - event.start_ms style_id = STYLE_FROM_EVENT.get(event.family) styled_words = [ i for i, w in enumerate(words) if style_id is not None and _overlap_ms(event.start_ms, event.end_ms, w.start_ms, w.end_ms) > cfg.style_word_overlap * w.duration_ms ] pieces = _non_speech_pieces(event.start_ms, event.end_ms, words) longest = max(pieces, key=lambda p: (p[1] - p[0], -p[0])) if pieces else None longest_ms = longest[1] - longest[0] if longest is not None else 0 if styled_words: assert style_id is not None # The detection may also cover words it did not mark (overlap <= the style # threshold); that speech is laughed/cried over untagged, so bound it like any # other event's speech overlap. unmarked_ms = sum( _overlap_ms(event.start_ms, event.end_ms, w.start_ms, w.end_ms) for i, w in enumerate(words) if i not in styled_words ) if unmarked_ms > cfg.max_event_speech_overlap * length: raise _Drop( "event_overlaps_speech", kind=sorted(event.kinds), start_ms=event.start_ms, end_ms=event.end_ms, speech_ms=unmarked_ms, ) style_events.append((style_id, styled_words, event)) if longest_ms < cfg.min_residual_event_ms: continue else: speech_ms = length - sum(b - a for a, b in pieces) if longest is None or speech_ms > cfg.max_event_speech_overlap * length: raise _Drop( "event_overlaps_speech", kind=sorted(event.kinds), start_ms=event.start_ms, end_ms=event.end_ms, speech_ms=speech_ms, ) assert longest is not None kind = _event_kind(event, longest_ms, cfg) if kind in cfg.disabled_tags: raise _Drop("disabled_tag", tag=kind, start_ms=event.start_ms, conf=event.conf) placed.append( _Placed(_nearest_gap((longest[0] + longest[1]) / 2, words), kind, *longest, event) ) for i, first in enumerate(placed): for second in placed[i + 1 :]: if first.kind == second.kind: continue shorter = min(first.end_ms - first.start_ms, second.end_ms - second.start_ms) shared = _overlap_ms(first.start_ms, first.end_ms, second.start_ms, second.end_ms) if shared > cfg.max_cross_kind_overlap * shorter: raise _Drop( "conflicting_events", kinds=sorted({first.kind, second.kind}), start_ms=max(first.start_ms, second.start_ms), shared_ms=shared, ) return placed, style_events
def _style_marks( words: Sequence[TimedWord], styles: Sequence[WordStyleScore], style_events: Sequence[tuple[str, list[int], _Merged]], cfg: FusionConfig,) -> tuple[list[str | None], dict[int, tuple[float, str, int, int]]]: """Per-word style (or None) and, per marked word, its evidence ``(conf, source, det_start_ms, det_end_ms)`` (the word itself for acoustic scores).""" marks: list[set[str]] = [set() for _ in words] evidence: list[dict[str, tuple[float, str, int, int]]] = [{} for _ in words] for style in sorted(styles, key=lambda s: s.style): if style.style in cfg.ignored_styles: continue band = cfg.bands[style.style] for index, score in enumerate(style.scores): if score is None or score < band.low: continue if score < band.high: raise _Drop( "ambiguous_style", style=style.style, word_index=index, word=words[index].text, score=score, source=style.source, ) if style.style in cfg.disabled_tags: raise _Drop("disabled_tag", tag=style.style, word_index=index, score=score) marks[index].add(style.style) word = words[index] evidence[index][style.style] = (score, style.source, word.start_ms, word.end_ms) for style_id, indices, event in style_events: if style_id in cfg.disabled_tags: raise _Drop("disabled_tag", tag=style_id, start_ms=event.start_ms, conf=event.conf) for index in indices: marks[index].add(style_id) previous = evidence[index].get(style_id) if previous is None or event.conf > previous[0]: evidence[index][style_id] = ( event.conf, event.source, event.start_ms, event.end_ms, ) resolved: list[str | None] = [] for index, word_marks in enumerate(marks): if len(word_marks) > 1: raise _Drop( "conflicting_styles", word_index=index, word=words[index].text, styles=sorted(word_marks), ) resolved.append(next(iter(word_marks)) if word_marks else None) chosen = { index: evidence[index][style_id] for index, style_id in enumerate(resolved) if style_id is not None } return resolved, chosen
def _style_runs( words: Sequence[TimedWord], marks: Sequence[str | None], cfg: FusionConfig) -> list[tuple[str, int, int]]: """Rule 5: maximal runs ``(style, first, last)`` of equally marked consecutive words.""" runs: list[tuple[str, int, int]] = [] index = 0 while index < len(marks): style_id = marks[index] if style_id is None: index += 1 continue last = index while last + 1 < len(marks) and marks[last + 1] == style_id: last += 1 count = last - index + 1 span_ms = words[last].end_ms - words[index].start_ms if count < cfg.min_span_words and span_ms < cfg.min_span_ms: raise _Drop( "short_style_run", style=style_id, words=[w.text for w in words[index : last + 1]], span_ms=span_ms, ) runs.append((style_id, index, last)) index = last + 1 return runs
def _normalise_word(text: str) -> str: """Rule 7 for one word.""" text = nfc(text) if any(ch in _RESERVED_CHARS for ch in text): raise _Drop("reserved_char_in_text", word=text) if any(unicodedata.category(ch).startswith("N") for ch in text): # 3, ², ½, Ⅳ raise _Drop("unnormalised_number", word=text) start, end = 0, len(text) while start < end and unicodedata.category(text[start]).startswith("P"): start += 1 while end > start and unicodedata.category(text[end - 1]).startswith("P"): end -= 1 core = text[start:end] if not core: return text canonical = canonical_filler(tr_lower(core)) return text if canonical is None else text[:start] + canonical + text[end:]
def normalise_word(text: str) -> str: """Rule 7 for one word, as :func:`fuse_segment` applies it to every aligned word.
Lets later stages (``timings``) compare the words of a stored tagged text with the aligned words they came from.
Raises: ValueError: if fusion would drop the segment for this word (reserved tag character or a digit-like character), with fusion's reason in the message. """ try: return _normalise_word(text) except _Drop as drop: raise ValueError(f"{drop.reason}: {drop.details}") from drop
def _ends_with_punctuation(text: str) -> bool: return unicodedata.category(text[-1]).startswith("P")
def _pauses( words: Sequence[TimedWord], texts: Sequence[str], merged: Sequence[_Merged], cfg: FusionConfig,) -> list[_Placed]: """Rule 6, on the longest part of each gap that no confident detection covers.
A short breath inside a 5 s silence must not hide the pause; the pause tag record spans that uncovered part, and tags in one gap are later ordered by time. """ out: list[_Placed] = [] for gap in range(1, len(words)): gap_start, gap_end = words[gap - 1].end_ms, words[gap].start_ms covered = _union( [ (max(gap_start, e.start_ms), min(gap_end, e.end_ms)) for e in merged if _overlap_ms(gap_start, gap_end, e.start_ms, e.end_ms) > 0 ] ) free: list[tuple[int, int]] = [] cursor = gap_start for a, b in covered: if a > cursor: free.append((cursor, a)) cursor = max(cursor, b) if cursor < gap_end: free.append((cursor, gap_end)) if not free: continue start, end = max(free, key=lambda p: (p[1] - p[0], -p[0])) silence = end - start kind: str | None = None if silence > cfg.pause_long_ms: kind = "pause_long" elif silence >= cfg.pause_short_ms and not _ends_with_punctuation(texts[gap - 1]): kind = "pause_short" if kind is not None: if kind in cfg.disabled_tags: raise _Drop("disabled_tag", tag=kind, start_ms=start) silence_event = _Merged(kind, {kind}, start, end, 1.0, {"alignment"}) out.append(_Placed(gap, kind, start, end, silence_event)) return out
def _build_items( texts: Sequence[str], events_by_gap: Mapping[int, Sequence[_Placed]], runs: Sequence[tuple[str, int, int]],) -> tuple[Item, ...]: run_at = {first: (style_id, last) for style_id, first, last in runs} items: list[Item] = [] index = 0 while True: items.extend(Event(p.kind) for p in events_by_gap.get(index, ())) if index == len(texts): break if index in run_at: style_id, last = run_at[index] children: list[Word | Event] = [] for inner in range(index, last + 1): if inner > index: children.extend(Event(p.kind) for p in events_by_gap.get(inner, ())) children.append(Word(texts[inner])) items.append(Span(style_id, tuple(children))) index = last + 1 else: items.append(Word(texts[index])) index += 1 return tuple(items)
def fuse_segment( segment_id: str, words: Sequence[TimedWord], duration_ms: int, events: Sequence[EventDetection], styles: Sequence[WordStyleScore], cfg: FusionConfig,) -> FusionResult: """Fuse one segment's annotations into tagged text (see module docstring).
Args: segment_id: Content-addressed id (:func:`nida.data.types.segment_id`). words: Aligned words, sorted and non-overlapping, segment-relative ms. duration_ms: Segment length in ms. events: Raw event detections (any confidence; bands are applied here). styles: At most one per-word score track per span style. cfg: Thresholds.
Returns: A :class:`FusionResult`; when ``quarantine`` is set, ``items``/``text`` are None. ``ignored_detections`` counts below-band detections in both cases and ``ignored_events`` holds them.
Raises: ValueError: on inconsistent inputs (a caller bug, not a data property). """ _validate_inputs(words, duration_ms, events, styles) confident, middle, ignored = _split_by_band(events, cfg) try: if not words: raise _Drop("no_words") texts = [_normalise_word(w.text) for w in words] merged = _merge_confident(confident, middle, cfg) placed, style_events = _place_events(merged, words, cfg) marks, evidence = _style_marks(words, styles, style_events, cfg) runs = _style_runs(words, marks, cfg) placed += _pauses(words, texts, merged, cfg)
events_by_gap: dict[int, list[_Placed]] = {} tags: list[TagRecord] = [] for p in sorted(placed, key=lambda p: (p.start_ms, p.end_ms, p.kind)): events_by_gap.setdefault(p.gap, []).append(p) tags.append( TagRecord( p.kind, p.start_ms, p.end_ms, p.event.conf, p.event.source, p.event.start_ms, p.event.end_ms, ) ) for style_id, first, last in runs: run_evidence = [evidence[i] for i in range(first, last + 1)] tags.append( TagRecord( style_id, words[first].start_ms, words[last].end_ms, min(e[0] for e in run_evidence), "+".join(sorted({e[1] for e in run_evidence})), min(e[2] for e in run_evidence), max(e[3] for e in run_evidence), ) ) try: items = _build_items(texts, events_by_gap, runs) text = render(items) if parse(text) != items: raise _Drop("invalid_output", text=text, detail="round-trip mismatch") except (TagSyntaxError, ValueError) as err: raise _Drop("invalid_output", error=str(err)) from err except _Drop as drop: return FusionResult( segment_id=segment_id, items=None, text=None, tags=(), quarantine=QuarantineRecord(segment_id, STAGE, drop.reason, dict(drop.details)), ignored_detections=len(ignored), ignored_events=tuple(ignored), ) return FusionResult( segment_id=segment_id, items=items, text=text, tags=tuple(sorted(tags, key=lambda t: (t.start_ms, t.end_ms, t.tag))), quarantine=None, ignored_detections=len(ignored), ignored_events=tuple(ignored), )
def emotion_condition(scores: Mapping[str, float], cfg: FusionConfig) -> EmotionCondition: """Utterance-level emotion condition from emotion-model class probabilities.
The top class becomes the condition with its probability as intensity. ``other`` / ``unknown`` as top class, or a top probability below ``emotion_min_conf``, give a null condition (not "neutral"; tag-spec §5, ADR-0003). Ties resolve to the alphabetically first label so the result is deterministic.
Raises: ValueError: unknown labels, empty scores, or probabilities outside [0, 1]. """ if not scores: raise ValueError("empty emotion scores") unknown = set(scores) - EMOTION_LABELS if unknown: raise ValueError(f"unknown emotion labels {sorted(unknown)}") for label, prob in scores.items(): if not (math.isfinite(prob) and 0.0 <= prob <= 1.0): raise ValueError(f"emotion {label!r} probability {prob!r} not in [0, 1]") label, prob = min(scores.items(), key=lambda kv: (-kv[1], kv[0])) if label in _NULL_EMOTIONS or prob < cfg.emotion_min_conf: return EmotionCondition(None, None) return EmotionCondition(label, prob)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118"""Import of an already transcribed external Turkish speech corpus (``nida data-import``).
The result is a *latent dataset directory* in exactly the format of :mod:`nida.train.data`(``index.jsonl``, ``shard-NNNNN.npy`` float16, ``meta.json``) plus ``timings.jsonl``(:mod:`nida.data.timings`), so ``load_latent_dataset(dir, split, timings=True)`` accepts it and``train --data A --data B ...`` can mix it with the YODAS pilot datasets. There is no ASR, nofusion and no tag detection: the transcript is trusted, aligned and encoded.
Sources (adapters, :mod:`nida.data.importer.sources`; all must be ``approved`` in``configs/sources.yaml``)::
alania HF cloud0day3/alania-synthetic-speech-tr, config cc-by only (parquet shards, 48 kHz FLAC), QC-filtered, text = ``text_spoken``, group = voice id tr_full HF Taklaxbr/tr-full-dataset (``data.jsonl`` + wavs), language tr only, emotion neutral/angry/sad/happy, group = speaker id wavdir a folder with ``manifest.jsonl`` {file, text, group, source, emotion?}: our own synthetic speech (e.g. ema-lightning); each line's ``source`` must be approved issai_tsc HF issai/Turkish_Speech_Corpus: one 21 GB ``.tar.gz`` (``ISSAI_TSC_218/{Train,Dev,Test}/<n>.wav|.txt``, 16 kHz); no speaker in the corpus, so group = block of running utterance numbers (see import_corpora.yaml) mediaspeech_tr OpenSLR SLR108 ``TR.tgz`` (``TR/<uuid>.flac|.txt``), pinned by the sha256 of the archive (recorded as the plan's revision); the whole corpus is one group common_voice_tr a Common Voice release the user downloaded (``--source-dir``: release folder, its ``tr`` folder, or the tarball): ``validated.tsv`` rows with ``down_votes < up_votes``, MP3 clips, group = hash of ``client_id``
A corpus is cut into deterministic *work units* (a parquet shard, a chunk of rows). A root(``--root``) is bound to one plan (source, pinned Hub commit sha / archive sha256 / sha1 of thelocal manifest, ``--max-hours``, ``--shard-offset``/``--shards`` unit range, config digest)recorded in ``plan.json``; several rootswith disjoint unit ranges select disjoint data, and the split of a group is a pure function ofthe group id, so groups stay disjoint across roots.
Stages (each idempotent and resumable; ``all`` runs them in order)::
select -> audio -> latents -> ctc -> timings -> dataset -> report
* ``select`` (CPU, network): per unit, metadata filters and transcript normalisation (:mod:`nida.data.importer.text`: NFC, text with tag characters rejected, digits spelled out, every character must be in the model vocabulary; fillers are not canonicalised); the raw audio of the selected rows is put in the local cache; stops at ``--max-hours``. Finished units are stored, so an interruption loses at most one unit.* ``audio`` (CPU): 16 kHz mono PCM wav per item in the cache, duration and loudness (dBFS) measured, duration/silence checks. Lost cache files are rebuilt (the unit is fetched again).* ``latents`` / ``ctc`` (GPU): the pilot's ``vae_encode`` and ``ctc_emissions`` workers (same isolated environments, same resumable results protocol, :func:`nida.data.pilot.run_worker_job`).* ``timings`` (CPU): forced alignment of ``text.split()``, the pilot's alignment sanity check (:func:`nida.data.asr_filter.check_alignment`, thresholds in ``import.yaml``) and the unit timeline (:func:`nida.data.timings.build_timings`, no event tags).* ``dataset`` (CPU): ``dataset-<config digest>/`` with only the segments that got a timeline; group-disjoint deterministic splits (a pure function of seed and group id: ~3 % of the groups val, ~2 % test; the same group is in the same split in every root); rate/loudness buckets with the fixed edges of ``configs/data/dataset.yaml``, exactly like the pilot; ``language`` ``tr``; ``segment_id = sha1(source id, item id)[:16]``. Verified with the training loader. ``meta.json`` is written last.* ``report``: ``report.md`` and ``metrics.json``.
Every item a stage drops is written to ``<root>/<stage>/quarantine.jsonl`` with amachine-readable reason (:mod:`nida.data.quarantine`); counts are in the stage results and inthe report. Layout::
<root>/plan.json <root>/select/{manifest.jsonl, quarantine.jsonl, stage.json, units/<digest>.json} <root>/{audio,latents,ctc}/{manifest.jsonl, quarantine.jsonl, stage.json} <root>/timings/{timings.jsonl, quarantine.jsonl, stage.json} <root>/workers/{voxcpm2_audiovae_v2,mpoyraz_ctc_tr}/ worker requests/results/summary <root>/dataset-<digest>/{index.jsonl, shard-NNNNN.npy, timings.jsonl, meta.json} <root>/{report.md, metrics.json} <cache>/hub, raw, audio16k, arrays/ bulky intermediates on local disk, rebuilt when lost
Durable outputs live under ``root`` (Drive), bulky intermediates under ``cache`` (local).Thresholds and mappings are in ``configs/data/import.yaml`` (shared, and the three firstsources) and ``configs/data/import_corpora.yaml`` (the three corpora above; its sections havetheir own config digest, so adding them did not move the digest of the first three sources)."""
from __future__ import annotations
from nida.data.importer.config import ImportConfig, load_import_configfrom nida.data.importer.corpora import CommonVoiceAdapter, IssaiTscAdapter, MediaSpeechAdapterfrom nida.data.importer.hub import HubClient, HuggingFaceHubfrom nida.data.importer.pipeline import STAGES, Importer, ImportPlan, ImportRequestfrom nida.data.importer.sources import ( AlaniaAdapter, Item, SourceAdapter, TrFullAdapter, WavdirAdapter, item_segment_id, make_adapter,)from nida.data.importer.text import TextRejected, normalise_transcript
__all__ = [ "STAGES", "AlaniaAdapter", "CommonVoiceAdapter", "HubClient", "HuggingFaceHub", "ImportConfig", "ImportPlan", "ImportRequest", "Importer", "IssaiTscAdapter", "Item", "MediaSpeechAdapter", "SourceAdapter", "TextRejected", "TrFullAdapter", "WavdirAdapter", "item_segment_id", "load_import_config", "make_adapter", "normalise_transcript",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296"""One streaming pass over a tar archive, for the importer sources that ship as one.
Three sources arrive as an archive (the ISSAI corpus: a 21 GB ``.tar.gz``; MediaSpeech:``TR.tgz``; a Common Voice release tarball). A stream cannot be searched, and the audio andthe transcript of an utterance are far apart in it, so the adapters work in *passes*:
* an *index* pass reads the small transcript members into memory (and notes which audio members exist);* an *extract* pass writes the audio members a work unit needs to the cache.
Both are :func:`scan_archive`. A member is never written to a path derived from its name: acaller-supplied classifier maps a (normalised) member name to a ``(key, kind)`` pair or rejectsit, and audio goes to the path the caller registered for that key. Anything the classifierdoes not know is an error, not a silent skip (the archives are pinned, so a surprise meansthe format changed).
A pass that does not stop early must see the archive *end*: the decompressor is a file objectthat raises on a truncated stream (gzip/bz2/xz trailer), and the tar stream must finish withits zero blocks. A cut inside a header, or exactly between members, is an :class:`ArchiveError`,never a smaller corpus. (``tarfile`` alone ends silently in both cases and does not check thegzip trailer in stream mode.)"""
from __future__ import annotations
import bz2import gzipimport hashlibimport jsonimport lzmaimport tarfileimport zlibfrom collections.abc import Callable, Mappingfrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import IO, Literal, Protocol, cast
from nida.utils.io import atomic_write_bytes, atomic_write_json
__all__ = [ "MAX_AUDIO_BYTES", "MAX_TEXT_BYTES", "ArchiveError", "ArchiveScan", "Classifier", "Kind", "scan_archive", "verify_sha256_once",]
#: A transcript member larger than this is not a transcript (the biggest real text member is#: a Common Voice ``validated.tsv``, tens of MB).MAX_TEXT_BYTES = 512 * 1024 * 1024#: An audio member larger than this is refused instead of being read into memory.MAX_AUDIO_BYTES = 512 * 1024 * 1024#: Names of unexpected members listed in the error message._SHOWN_UNEXPECTED = 5#: A tar archive ends with (at least) two zero blocks of this many bytes._BLOCK_BYTES = 512_END_BYTES = 2 * _BLOCK_BYTES_DRAIN_BYTES = 1 << 20_HASH_CHUNK_BYTES = 1 << 20
Kind = Literal["text", "audio", "ignore"]#: Maps a normalised member name (``/``-separated, no leading ``./``) to ``(key, kind)``, or#: ``None`` for a member that must not exist in the archive.Classifier = Callable[[str], tuple[str, Kind] | None]
class ArchiveError(RuntimeError): """The archive is unreadable, truncated, corrupt or not laid out as expected."""
@dataclassclass ArchiveScan: """What one pass found.
Attributes: texts: ``key -> bytes`` of the ``text`` members (empty unless ``read_text``). audio_heads: ``key -> first bytes`` of the ``audio`` members (see ``audio_head``). audio_keys: Keys of every ``audio`` member seen (an early stop leaves it partial). extracted: Keys of the audio members written to their registered paths. members: Regular-file members visited. complete: ``True`` if the whole archive was read, up to its end blocks (no early stop). """
texts: dict[str, bytes] = field(default_factory=dict) audio_heads: dict[str, bytes] = field(default_factory=dict) audio_keys: set[str] = field(default_factory=set) extracted: set[str] = field(default_factory=set) members: int = 0 complete: bool = True
def _normalise(name: str) -> str: while name.startswith("./"): name = name[2:] return name.rstrip("/")
class _ByteStream(Protocol): def read(self, size: int = -1, /) -> bytes: ...
class _Reader: """The decompressed byte stream ``tarfile`` reads.
Counts the bytes handed out and remembers where the last non-zero byte ended (to check the tar end blocks), and turns every error of the decompressor into :class:`ArchiveError`. Errors of *writing* extracted files are not touched: they happen elsewhere. """
def __init__(self, stream: _ByteStream, archive: Path) -> None: self._stream = stream self._archive = archive self.pos = 0 self.last_nonzero_end = 0
def read(self, size: int = -1) -> bytes: try: data = self._stream.read(size) except (OSError, EOFError, zlib.error, lzma.LZMAError) as err: raise ArchiveError( f"{self._archive}: cannot be read (truncated or corrupt? after " f"{self.pos} bytes): {err!r}" ) from err if data: stripped = data.rstrip(b"\x00") if stripped: self.last_nonzero_end = self.pos + len(stripped) self.pos += len(data) return data
def _decompressed(raw: IO[bytes]) -> _ByteStream: """``raw`` wrapped in the file object of its compression (by magic number), or itself.""" magic = raw.read(6) raw.seek(0) if magic.startswith(b"\x1f\x8b"): return gzip.GzipFile(fileobj=raw) if magic.startswith(b"BZh"): return bz2.BZ2File(raw) if magic.startswith(b"\xfd7zXZ\x00"): return lzma.LZMAFile(raw) return raw
def scan_archive( archive: Path, classify: Classifier, *, read_text: bool, extract: Mapping[str, Path] | None = None, audio_head: int = 0,) -> ArchiveScan: """Read ``archive`` once (plain, gzip, bz2 or xz; auto-detected).
Args: archive: Local tar file. classify: Member classifier (see :data:`Classifier`). read_text: Keep the bytes of every ``text`` member. extract: ``key -> destination`` of the ``audio`` members to write (atomically). When ``read_text`` is false the pass stops as soon as all of them are written. audio_head: Keep the first this many bytes of every ``audio`` member (e.g. a FLAC header, to learn the duration without reading the audio).
Raises: ArchiveError: unreadable/truncated/corrupt archive (including one that ends without its end blocks, or whose compressed stream has no trailer); a member that is neither a regular file nor a directory, or that ``classify`` rejects; a key seen twice; an oversized member. FileNotFoundError: ``archive`` does not exist. OSError: a destination cannot be written (disk full ...). """ scan = ArchiveScan() unexpected: list[str] = [] seen: set[str] = set() wanted = extract or {} try: with archive.open("rb") as raw: reader = _Reader(_decompressed(raw), archive) with tarfile.open( fileobj=cast(IO[bytes], reader), # stream mode only calls ``read`` mode="r|", ) as tar: for member in tar: # Streaming mode keeps every TarInfo alive otherwise (hundreds of thousands). tar.members = [] # type: ignore[attr-defined] # runtime attribute, not typed if member.isdir(): continue name = _normalise(member.name) classified = classify(name) if member.isfile() else None if classified is None: unexpected.append(name) continue key, kind = classified if kind == "ignore": continue if key in seen: raise ArchiveError(f"{archive}: member {name!r} occurs twice") seen.add(key) scan.members += 1 if kind == "text": _check_size(archive, name, member.size, MAX_TEXT_BYTES) if read_text: scan.texts[key] = _read(tar, member, archive) elif key in wanted: _write(tar, member, archive, wanted[key]) scan.extracted.add(key) else: scan.audio_keys.add(key) if audio_head: scan.audio_heads[key] = _read(tar, member, archive, audio_head) if key in wanted: _check_size(archive, name, member.size, MAX_AUDIO_BYTES) _write(tar, member, archive, wanted[key]) scan.extracted.add(key) if not read_text and wanted and len(scan.extracted) == len(wanted): scan.complete = False break if scan.complete: _require_end_blocks(archive, reader, tar.offset) except (tarfile.TarError, EOFError, zlib.error, gzip.BadGzipFile, lzma.LZMAError) as err: raise ArchiveError(f"{archive}: cannot be read as a tar archive: {err!r}") from err if unexpected and scan.complete: shown = ", ".join(repr(n) for n in unexpected[:_SHOWN_UNEXPECTED]) raise ArchiveError( f"{archive}: {len(unexpected)} unexpected member(s) (not a directory or a known " f"file; the format changed?): {shown}" ) return scan
def _require_end_blocks(archive: Path, reader: _Reader, end_offset: int) -> None: """The member loop ended: make sure it ended at the archive's end blocks and read the stream to its true end (that is where gzip/bz2/xz check their trailer).
``end_offset`` is where ``tarfile`` stopped looking for headers. From there on the stream must be zeros only, at least two blocks of them; a cut inside a header leaves non-zero bytes or too few zeros, a cut between members leaves nothing. """ while reader.read(_DRAIN_BYTES): pass if reader.last_nonzero_end > end_offset or reader.pos - end_offset < _END_BYTES: raise ArchiveError( f"{archive}: ends without the tar end-of-archive blocks (truncated?): " f"{reader.pos - end_offset} bytes after the last member at {end_offset}, " f"non-zero data up to {reader.last_nonzero_end}" )
def verify_sha256_once(path: Path, expected: str) -> None: """Check that the file at ``path`` has the SHA-256 ``expected``, hashing it only once.
A marker next to the file (``<name>.verified.json``) records the size, mtime and digest of a verified file; while those still match, the (21 GB) file is not read again.
Raises: ArchiveError: the digest differs (the file is incomplete or not the pinned one). """ marker = path.with_name(path.name + ".verified.json") stat = path.stat() key = {"size": stat.st_size, "mtime_ns": stat.st_mtime_ns, "sha256": expected} if marker.is_file(): try: if json.loads(marker.read_text(encoding="utf-8")) == key: return except json.JSONDecodeError: pass # a damaged marker is only a missing marker: hash again digest = hashlib.sha256() with path.open("rb") as handle: while chunk := handle.read(_HASH_CHUNK_BYTES): digest.update(chunk) if digest.hexdigest() != expected: marker.unlink(missing_ok=True) raise ArchiveError( f"{path}: sha256 {digest.hexdigest()} (size {stat.st_size}) is not the pinned " f"{expected}; the download is incomplete or corrupt - delete it and run again" ) atomic_write_json(marker, key)
def _check_size(archive: Path, name: str, size: int, limit: int) -> None: if size > limit: raise ArchiveError(f"{archive}: member {name!r} has {size} bytes (limit {limit})")
def _read(tar: tarfile.TarFile, member: tarfile.TarInfo, archive: Path, size: int = -1) -> bytes: handle = tar.extractfile(member) if handle is None: raise ArchiveError(f"{archive}: cannot read member {member.name!r}") return handle.read(size)
def _write(tar: tarfile.TarFile, member: tarfile.TarInfo, archive: Path, dest: Path) -> None: atomic_write_bytes(dest, _read(tar, member, archive))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146"""Audio helpers of the import stages: raw file -> 16 kHz mono PCM wav, plus measurements.
The wav is what both model workers read (the CTC model requires 16 kHz mono; the VAE encoderresamples to its own rate itself, from 16 kHz exactly like the pilot's YODAS audio). Channelsare averaged, the signal is resampled with a polyphase filter(:func:`nida.data.ears.resample`) and written as 16-bit PCM atomically."""
from __future__ import annotations
import iofrom dataclasses import dataclassfrom pathlib import Path
import numpy as npimport numpy.typing as npt
from nida.data import acousticfrom nida.data.ears import resamplefrom nida.utils.io import atomic_write_bytes
__all__ = [ "TARGET_RATE_HZ", "AudioFacts", "AudioRejected", "convert_to_wav16k", "measure_wav16k", "raw_duration_ms", "require_audio_format",]
#: Rate of the working copy (CTC requirement).TARGET_RATE_HZ = 16000
class AudioRejected(Exception): """An audio file that cannot be used; ``reason`` is the quarantine reason."""
def __init__(self, reason: str, **details: object) -> None: super().__init__(f"{reason}: {details}") self.reason = reason self.details = dict(details)
@dataclass(frozen=True)class AudioFacts: """Measurements of a 16 kHz working copy.
Attributes: duration_ms: ``round(1000 * samples / 16000)``. loudness_dbfs: Whole-signal RMS level (:func:`nida.data.acoustic.loudness_dbfs`). """
duration_ms: int loudness_dbfs: float
def require_audio_format(name: str) -> None: """Raise unless the installed libsndfile reads the format ``name`` (e.g. ``"MP3"``, which needs libsndfile >= 1.1, bundled with ``soundfile`` >= 0.12).
Raises: RuntimeError: the format is not available (installing a newer ``soundfile`` fixes it). """ import soundfile # type: ignore[import-untyped] # bench extra, untyped
if name not in soundfile.available_formats(): raise RuntimeError( f"this soundfile/libsndfile ({soundfile.__libsndfile_version__}) cannot read " f"{name}; upgrade soundfile (>= 0.12 bundles libsndfile 1.1+)" )
def raw_duration_ms(path: Path) -> int: """Duration of an audio file from its header (no decoding).
Raises: AudioRejected: ``unreadable_audio`` (not an audio file) or ``empty_audio``. """ import soundfile
try: info = soundfile.info(str(path)) except (RuntimeError, OSError) as err: raise AudioRejected("unreadable_audio", error=str(err)) from err if int(info.frames) <= 0 or int(info.samplerate) <= 0: raise AudioRejected("empty_audio") duration_ms: int = round(1000 * int(info.frames) / int(info.samplerate)) return duration_ms
def _read_mono(path: Path) -> tuple[npt.NDArray[np.float64], int]: """``(samples, rate_hz)`` with channels averaged; rejects unreadable/empty/non-finite.""" import soundfile
try: audio, rate_hz = soundfile.read(str(path), dtype="float64", always_2d=True) except (RuntimeError, OSError) as err: raise AudioRejected("unreadable_audio", error=str(err)) from err if audio.shape[0] == 0: raise AudioRejected("empty_audio") mono = np.ascontiguousarray(audio.mean(axis=1)) if not np.all(np.isfinite(mono)): raise AudioRejected("non_finite_audio") return mono, int(rate_hz)
def convert_to_wav16k(raw: Path, wav: Path) -> None: """Write the 16 kHz mono 16-bit PCM copy of ``raw`` atomically to ``wav``.
Raises: AudioRejected: ``unreadable_audio``, ``empty_audio`` or ``non_finite_audio``. """ import soundfile
mono, rate_hz = _read_mono(raw) converted = resample(mono, rate_hz, TARGET_RATE_HZ) buffer = io.BytesIO() soundfile.write( buffer, np.clip(converted, -1.0, 1.0), TARGET_RATE_HZ, format="WAV", subtype="PCM_16" ) atomic_write_bytes(wav, buffer.getvalue())
def measure_wav16k(wav: Path) -> AudioFacts: """Duration and loudness of a working copy.
Raises: AudioRejected: the file is unreadable/empty, or is not a 16 kHz mono file (a stale or foreign cache entry; the caller reconverts it). """ import soundfile
try: info = soundfile.info(str(wav)) except (RuntimeError, OSError) as err: raise AudioRejected("unreadable_audio", error=str(err)) from err if int(info.samplerate) != TARGET_RATE_HZ or int(info.channels) != 1: raise AudioRejected( "bad_working_copy", sample_rate_hz=int(info.samplerate), channels=int(info.channels) ) mono, _ = _read_mono(wav) return AudioFacts( duration_ms=round(1000 * mono.shape[0] / TARGET_RATE_HZ), loudness_dbfs=float(acoustic.loudness_dbfs(mono)), )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474"""``configs/data/import.yaml`` (+ ``dataset.yaml``) as validated, frozen records."""
from __future__ import annotations
import hashlibimport jsonimport mathimport refrom collections.abc import Mappingfrom dataclasses import asdict, dataclassfrom pathlib import Path
from nida.data.asr_filter import AsrFilterConfigfrom nida.data.ears import en_lowerfrom nida.data.pilot import DatasetConfigfrom nida.data.registry import DATA_MODELSfrom nida.train.data import EMOTIONS, SPLITS
__all__ = [ "CORPUS_SOURCES", "LEGACY_SOURCES", "AlaniaConfig", "CommonVoiceConfig", "ImportConfig", "IssaiTscConfig", "MediaSpeechConfig", "TrFullConfig", "WavdirConfig", "load_import_config",]
IMPORT_CONFIG_FILE = "import.yaml"DATASET_CONFIG_FILE = "dataset.yaml"#: Sections of the corpora added after the first three sources (see :func:`load_import_config`).CORPORA_CONFIG_FILE = "import_corpora.yaml"#: Importer sources whose config lives in ``import.yaml``; their digest is the original one.LEGACY_SOURCES = ("alania", "tr_full", "wavdir")#: Importer sources configured in ``import_corpora.yaml`` (a digest scoped per source).CORPUS_SOURCES = ("issai_tsc", "mediaspeech_tr", "common_voice_tr")_SHA256_RE = re.compile(r"[0-9a-f]{64}")
def _load_yaml(path: Path) -> Mapping[str, object]: import yaml # type: ignore[import-untyped] # PyYAML: bench extra, no stubs installed
obj = yaml.safe_load(path.read_text(encoding="utf-8")) if not isinstance(obj, dict): raise ValueError(f"{path}: expected a mapping") return obj
def _keys(raw: Mapping[str, object], expected: set[str], where: str) -> None: if set(raw) != expected: raise ValueError( f"{where}: keys differ: missing={sorted(expected - set(raw))} " f"unknown={sorted(set(raw) - expected)}" )
def _mapping(raw: Mapping[str, object], key: str) -> Mapping[str, object]: value = raw[key] if not isinstance(value, dict) or not all(isinstance(k, str) for k in value): raise ValueError(f"{key} must be a mapping") return value
def _text(raw: Mapping[str, object], key: str, *, allow_empty: bool = False) -> str: value = raw[key] if not isinstance(value, str) or not (value or allow_empty): raise ValueError(f"{key} must be a non-empty string, got {value!r}") return value
def _int(raw: Mapping[str, object], key: str, *, minimum: int) -> int: value = raw[key] if isinstance(value, bool) or not isinstance(value, int) or value < minimum: raise ValueError(f"{key} must be an int >= {minimum}, got {value!r}") return value
def _bool(raw: Mapping[str, object], key: str) -> bool: value = raw[key] if not isinstance(value, bool): raise ValueError(f"{key} must be true or false, got {value!r}") return value
def _float(raw: Mapping[str, object], key: str, *, lo: float, hi: float) -> float: value = raw[key] if isinstance(value, bool) or not isinstance(value, int | float): raise ValueError(f"{key} must be a number, got {value!r}") if not (math.isfinite(value) and lo <= value <= hi): raise ValueError(f"{key} must be in [{lo}, {hi}], got {value!r}") return float(value)
@dataclass(frozen=True)class AlaniaConfig: """``alania:`` block (source ``alania_synth_tr``)."""
repo_id: str parquet_glob: str min_utmos: float max_cer: float license_prefix: str batch_rows: int group_prefix: str
@classmethod def from_mapping(cls, raw: Mapping[str, object]) -> AlaniaConfig: _keys(raw, set(cls.__dataclass_fields__), "alania") return cls( repo_id=_text(raw, "repo_id"), parquet_glob=_text(raw, "parquet_glob"), min_utmos=_float(raw, "min_utmos", lo=0.0, hi=5.0), max_cer=_float(raw, "max_cer", lo=0.0, hi=1.0), license_prefix=_text(raw, "license_prefix"), batch_rows=_int(raw, "batch_rows", minimum=1), group_prefix=_text(raw, "group_prefix", allow_empty=True), )
@dataclass(frozen=True)class TrFullConfig: """``tr_full:`` block (source ``tr_full_dataset``)."""
repo_id: str data_file: str language: str unit_rows: int group_prefix: str
@classmethod def from_mapping(cls, raw: Mapping[str, object]) -> TrFullConfig: _keys(raw, set(cls.__dataclass_fields__), "tr_full") return cls( repo_id=_text(raw, "repo_id"), data_file=_text(raw, "data_file"), language=_text(raw, "language"), unit_rows=_int(raw, "unit_rows", minimum=1), group_prefix=_text(raw, "group_prefix", allow_empty=True), )
@dataclass(frozen=True)class WavdirConfig: """``wavdir:`` block (a folder with ``manifest.jsonl``)."""
unit_rows: int group_prefix: str
@classmethod def from_mapping(cls, raw: Mapping[str, object]) -> WavdirConfig: _keys(raw, set(cls.__dataclass_fields__), "wavdir") return cls( unit_rows=_int(raw, "unit_rows", minimum=1), group_prefix=_text(raw, "group_prefix", allow_empty=True), )
def _str_list(raw: Mapping[str, object], key: str) -> tuple[str, ...]: value = raw[key] if ( not isinstance(value, list) or not value or not all(isinstance(v, str) and v for v in value) or len(set(value)) != len(value) ): raise ValueError(f"{key} must be a non-empty list of distinct non-empty strings") return tuple(value)
def _plain_name(raw: Mapping[str, object], key: str) -> str: """A single path component (no separators, not ``.``/``..``).""" value = _text(raw, key) if "/" in value or "\\" in value or "\x00" in value or value in (".", ".."): raise ValueError(f"{key} must be one plain file or folder name, got {value!r}") return value
def _sha256(raw: Mapping[str, object], key: str) -> str: value = _text(raw, key) if _SHA256_RE.fullmatch(value) is None: raise ValueError(f"{key} must be 64 lower-case hex digits, got {value!r}") return value
def _force_split(raw: Mapping[str, object]) -> str | None: """``force_split``: ``null`` (split by group hash) or the one split every row goes to.""" value = raw["force_split"] if value is not None and value not in SPLITS: raise ValueError(f"force_split must be null or one of {SPLITS}, got {value!r}") return value
@dataclass(frozen=True)class IssaiTscConfig: """``issai_tsc:`` block of ``import_corpora.yaml`` (source ``issai_tsc``).
``group_block_ids``: the corpus names no speaker or session, only a running utterance number that follows the recording order, so ``numeric id // group_block_ids`` is the group (reporting only while ``force_split`` is set). ``archive_sha256`` and ``expected_pairs`` (utterance stems, wav and/or txt) guard against a truncated or changed archive. ``force_split``: every row goes to this split instead of the group hash (the corpus' recordings are contiguous and no group can be pure). """
repo_id: str archive_file: str archive_sha256: str expected_pairs: int archive_root: str splits: tuple[str, ...] unit_rows: int group_block_ids: int group_prefix: str force_split: str | None
@classmethod def from_mapping(cls, raw: Mapping[str, object]) -> IssaiTscConfig: _keys(raw, set(cls.__dataclass_fields__), "issai_tsc") return cls( repo_id=_text(raw, "repo_id"), archive_file=_plain_name(raw, "archive_file"), archive_sha256=_sha256(raw, "archive_sha256"), expected_pairs=_int(raw, "expected_pairs", minimum=1), archive_root=_plain_name(raw, "archive_root"), splits=_str_list(raw, "splits"), unit_rows=_int(raw, "unit_rows", minimum=1), group_block_ids=_int(raw, "group_block_ids", minimum=1), group_prefix=_text(raw, "group_prefix", allow_empty=True), force_split=_force_split(raw), )
@dataclass(frozen=True)class MediaSpeechConfig: """``mediaspeech_tr:`` block of ``import_corpora.yaml`` (OpenSLR SLR108 ``TR.tgz``).
``sha256`` pins the archive (a different file is refused); ``expected_pairs`` is the number of utterance stems it holds; ``group`` is the one group of the whole corpus (file names are random UUIDs: no speaker, channel or video); ``force_split``: see :class:`IssaiTscConfig`; ``reserve_bench_clips``: quarantine the clips the phase-0 B1 benchmark drew from this corpus (``bench_reserved``), so they stay unseen by training. """
url: str sha256: str expected_pairs: int archive_root: str unit_rows: int group: str force_split: str | None reserve_bench_clips: bool
@classmethod def from_mapping(cls, raw: Mapping[str, object]) -> MediaSpeechConfig: _keys(raw, set(cls.__dataclass_fields__), "mediaspeech_tr") url = _text(raw, "url") if not url.startswith("https://"): raise ValueError(f"url must be an https:// URL, got {url!r}") return cls( url=url, sha256=_sha256(raw, "sha256"), expected_pairs=_int(raw, "expected_pairs", minimum=1), archive_root=_plain_name(raw, "archive_root"), unit_rows=_int(raw, "unit_rows", minimum=1), group=_text(raw, "group"), force_split=_force_split(raw), reserve_bench_clips=_bool(raw, "reserve_bench_clips"), )
@dataclass(frozen=True)class CommonVoiceConfig: """``common_voice_tr:`` block of ``import_corpora.yaml`` (a local Common Voice release).
``min_net_votes``: a clip is used when ``up_votes - down_votes >= min_net_votes`` (1 means ``down_votes < up_votes``). The group is a hash of ``client_id`` behind ``group_prefix``. """
locale: str validated_file: str clips_dir: str min_net_votes: int unit_rows: int group_prefix: str
@classmethod def from_mapping(cls, raw: Mapping[str, object]) -> CommonVoiceConfig: _keys(raw, set(cls.__dataclass_fields__), "common_voice_tr") return cls( locale=_text(raw, "locale"), validated_file=_plain_name(raw, "validated_file"), clips_dir=_plain_name(raw, "clips_dir"), min_net_votes=_int(raw, "min_net_votes", minimum=1), unit_rows=_int(raw, "unit_rows", minimum=1), group_prefix=_text(raw, "group_prefix", allow_empty=True), )
@dataclass(frozen=True)class ImportConfig: """Every threshold and mapping of the import stages.
Attributes: seed: Split-hash seed (``str(seed)`` is passed to :func:`nida.data.splits.assign_splits`). val_fraction: Share of groups in the ``val`` split. test_fraction: Share of groups in the ``test`` split. min_duration_ms: Shortest accepted segment. max_duration_ms: Longest accepted segment. min_loudness_dbfs: Segments quieter than this (RMS, dBFS) are ``silent``. alignment: Thresholds of the forced-alignment sanity check (:func:`nida.data.asr_filter.check_alignment`; ``max_cer`` and the languages of that record are unused here). char_map: Single-character replacements applied to transcripts. emotion_map: Source emotion label -> :data:`nida.train.data.EMOTIONS` id. issai_tsc: ``import_corpora.yaml`` section of the ISSAI Turkish Speech Corpus. mediaspeech_tr: ``import_corpora.yaml`` section of MediaSpeech (SLR108). common_voice_tr: ``import_corpora.yaml`` section of Common Voice. dataset: Fixed rate/loudness bucket edges (``dataset.yaml``, shared with the pilot). digest: 12 hex digits over the config files and the VAE/CTC model pins; names the dataset directory and is recorded in ``plan.json``. For ``alania``, ``tr_full``, ``wavdir`` (and when no source is given) it covers ``import.yaml`` and ``dataset.yaml`` only - the value those roots were made with. For a source of ``import_corpora.yaml`` it is derived from that value and the source's own section. """
seed: int val_fraction: float test_fraction: float min_duration_ms: int max_duration_ms: int min_loudness_dbfs: float alignment: AsrFilterConfig char_map: Mapping[str, str] emotion_map: Mapping[str, str] alania: AlaniaConfig tr_full: TrFullConfig wavdir: WavdirConfig issai_tsc: IssaiTscConfig mediaspeech_tr: MediaSpeechConfig common_voice_tr: CommonVoiceConfig dataset: DatasetConfig digest: str
def forced_split(self, source: str) -> str | None: """The split every row of ``source`` goes to (``force_split``), or ``None``.""" if source == "issai_tsc": return self.issai_tsc.force_split if source == "mediaspeech_tr": return self.mediaspeech_tr.force_split return None
@property def split_fractions(self) -> dict[str, float]: """``{"train": 1 - val - test, "val": ..., "test": ...}``.""" return { "train": 1.0 - self.val_fraction - self.test_fraction, "val": self.val_fraction, "test": self.test_fraction, }
def load_import_config(config_dir: Path, source: str | None = None) -> ImportConfig: """Read and validate ``import.yaml``, ``dataset.yaml`` and ``import_corpora.yaml``.
Args: config_dir: Folder with the three files. source: The importer source the config is for; it scopes :attr:`ImportConfig.digest` (``None`` or a legacy source: the digest of ``import.yaml`` + ``dataset.yaml``, unchanged by ``import_corpora.yaml``; a corpus source: that digest combined with the source's own section, so editing one corpus never moves another's roots).
Raises: ValueError: on unknown/missing keys, out-of-range numbers, multi-character ``char_map`` keys, an ``emotion_map`` target that is not an emotion id, or an unknown ``source``. FileNotFoundError: a config file is missing. """ if source is not None and source not in (*LEGACY_SOURCES, *CORPUS_SOURCES): known = (*LEGACY_SOURCES, *CORPUS_SOURCES) raise ValueError(f"unknown source {source!r}; known: {known}") import_path = config_dir / IMPORT_CONFIG_FILE dataset_path = config_dir / DATASET_CONFIG_FILE corpora = _load_yaml(config_dir / CORPORA_CONFIG_FILE) _keys(corpora, set(CORPUS_SOURCES), CORPORA_CONFIG_FILE) raw = _load_yaml(import_path) _keys( raw, { "seed", "val_fraction", "test_fraction", "min_duration_ms", "max_duration_ms", "min_loudness_dbfs", "alignment", "char_map", "emotion_map", "alania", "tr_full", "wavdir", }, IMPORT_CONFIG_FILE, ) char_map = _mapping(raw, "char_map") for key, value in char_map.items(): if len(key) != 1 or not isinstance(value, str): raise ValueError(f"char_map: {key!r} must be one character mapped to a string") emotion_map = _mapping(raw, "emotion_map") for label, emotion in emotion_map.items(): if not label or not label.isascii() or label != en_lower(label) or label != label.strip(): raise ValueError(f"emotion_map: label {label!r} must be ASCII lower-case") if emotion not in EMOTIONS: raise ValueError(f"emotion_map: {label!r} -> {emotion!r} is not one of {EMOTIONS}") val_fraction = _float(raw, "val_fraction", lo=0.0, hi=1.0) test_fraction = _float(raw, "test_fraction", lo=0.0, hi=1.0) if val_fraction + test_fraction >= 1.0: raise ValueError("val_fraction + test_fraction must be < 1") min_duration_ms = _int(raw, "min_duration_ms", minimum=1) max_duration_ms = _int(raw, "max_duration_ms", minimum=1) if max_duration_ms <= min_duration_ms: raise ValueError("max_duration_ms must exceed min_duration_ms") align_raw = _mapping(raw, "alignment") _keys(align_raw, {"min_chars_per_s", "max_chars_per_s", "min_align_score"}, "alignment") alignment = AsrFilterConfig( max_cer=0.0, # S4 only; not used by the importer allowed_languages=("tr",), # S4 only; not used by the importer min_chars_per_s=_float(align_raw, "min_chars_per_s", lo=0.0, hi=1000.0), max_chars_per_s=_float(align_raw, "max_chars_per_s", lo=0.0, hi=1000.0), min_align_score=_float(align_raw, "min_align_score", lo=0.0, hi=1.0), ) digest = hashlib.sha1() for path in (import_path, dataset_path): digest.update(path.name.encode("utf-8") + b"\x00" + path.read_bytes()) refs = { key: [DATA_MODELS[key].ref.model_id, DATA_MODELS[key].ref.revision] for key in ("voxcpm2_audiovae_v2", "mpoyraz_ctc_tr") } digest.update(json.dumps(refs, sort_keys=True).encode("utf-8")) issai_tsc = IssaiTscConfig.from_mapping(_mapping(corpora, "issai_tsc")) mediaspeech_tr = MediaSpeechConfig.from_mapping(_mapping(corpora, "mediaspeech_tr")) common_voice_tr = CommonVoiceConfig.from_mapping(_mapping(corpora, "common_voice_tr")) digest_hex = digest.hexdigest() sections: dict[str, IssaiTscConfig | MediaSpeechConfig | CommonVoiceConfig] = { "issai_tsc": issai_tsc, "mediaspeech_tr": mediaspeech_tr, "common_voice_tr": common_voice_tr, } if source is not None and source in sections: scoped = hashlib.sha1(digest_hex.encode("ascii") + b"\x00" + source.encode("ascii")) section_json = json.dumps(asdict(sections[source]), sort_keys=True) scoped.update(b"\x00" + section_json.encode("utf-8")) digest_hex = scoped.hexdigest() return ImportConfig( seed=_int(raw, "seed", minimum=0), val_fraction=val_fraction, test_fraction=test_fraction, min_duration_ms=min_duration_ms, max_duration_ms=max_duration_ms, min_loudness_dbfs=_float(raw, "min_loudness_dbfs", lo=-240.0, hi=0.0), alignment=alignment, char_map={str(k): str(v) for k, v in char_map.items()}, emotion_map={str(k): str(v) for k, v in emotion_map.items()}, alania=AlaniaConfig.from_mapping(_mapping(raw, "alania")), tr_full=TrFullConfig.from_mapping(_mapping(raw, "tr_full")), wavdir=WavdirConfig.from_mapping(_mapping(raw, "wavdir")), issai_tsc=issai_tsc, mediaspeech_tr=mediaspeech_tr, common_voice_tr=common_voice_tr, dataset=DatasetConfig.from_mapping(_load_yaml(dataset_path)), digest=digest_hex[:12], )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801"""Source adapters for the corpora that ship as an archive or as a Common Voice release.
* :class:`IssaiTscAdapter` - ``issai/Turkish_Speech_Corpus`` (HF; one 21 GB ``.tar.gz``).* :class:`MediaSpeechAdapter` - OpenSLR SLR108 ``TR.tgz`` (pinned by sha256).* :class:`CommonVoiceAdapter` - a Common Voice release directory or tarball the user supplied.
The first two are *archive corpora*. Transcript and audio of an utterance are far apart in atar stream, so an *index pass* (:func:`nida.data.importer.archives.scan_archive`) reads alltranscripts once and notes which audio members exist; the rows are put in a deterministicorder and cut into work units. A unit then costs one *extract pass* that writes the audio ofits selected rows to ``<cache>/raw/<source>/`` (the audio stage deletes each file afterconverting it, :attr:`ephemeral_raw`; a lost file is extracted again).
Every row the adapter cannot turn into an item is quarantined with a reason: ``audio_missing``(no audio member for a transcript), ``text_missing`` (no transcript for an audio member),``bad_encoding`` (transcript is not UTF-8), the text reasons of:func:`~nida.data.importer.text.normalise_transcript`, and per source the ones listed on theclass."""
from __future__ import annotations
import csvimport hashlibimport jsonimport refrom collections.abc import Generator, Mapping, Setfrom dataclasses import dataclassfrom pathlib import Path
from nida.bench import fetchfrom nida.bench.clips import MediaSpeechItem, select_mediaspeechfrom nida.bench.prepare import B1Planfrom nida.data.importer.archives import ( ArchiveError, ArchiveScan, Kind, scan_archive, verify_sha256_once,)from nida.data.importer.audio import require_audio_formatfrom nida.data.importer.config import ( CommonVoiceConfig, ImportConfig, IssaiTscConfig, MediaSpeechConfig,)from nida.data.importer.hub import HubClient, HubErrorfrom nida.data.importer.sources import ( Item, Scalar, UnitListing, _bad_row, _chunk_ids, _chunk_slice, _drop, _first_seen, _text_drop, item_segment_id, safe_relative_path,)from nida.data.importer.text import TextRejected, normalise_transcriptfrom nida.data.types import QuarantineRecordfrom nida.text.turkish import nfcfrom nida.utils.io import atomic_write_text
__all__ = [ "COMMON_VOICE_SOURCE_ID", "ISSAI_TSC_SOURCE_ID", "MEDIASPEECH_SOURCE_ID", "CommonVoiceAdapter", "IssaiTscAdapter", "MediaSpeechAdapter", "find_common_voice_root",]
ISSAI_TSC_SOURCE_ID = "issai_tsc"MEDIASPEECH_SOURCE_ID = "mediaspeech_tr"COMMON_VOICE_SOURCE_ID = "common_voice_tr"
STATE_OK = "ok"STATE_NO_AUDIO = "no_audio"STATE_NO_TEXT = "no_text"STATE_BAD_ENCODING = "bad_encoding"STATE_BENCH_RESERVED = "bench_reserved"_STATES = (STATE_OK, STATE_NO_AUDIO, STATE_NO_TEXT, STATE_BAD_ENCODING, STATE_BENCH_RESERVED)#: FLAC: ``fLaC`` + metadata block header (4 bytes) + STREAMINFO; its bytes 10-17 hold the#: sample rate (20 bits), channels, bit depth and the total sample count (36 bits)._FLAC_HEAD_BYTES = 26_FLAC_STREAMINFO_AT = 18
_ISSAI_MEMBER_RE = re.compile(r"([^/]+)/([^/]+)/([0-9]+)\.(wav|txt)")_MEDIASPEECH_MEMBER_RE = re.compile(r"([^/]+)/([A-Za-z0-9_-]+)\.(flac|txt)")
# ------------------------------------------------------------------------------ rows
@dataclass(frozen=True)class _ArchiveRow: """One utterance of an archive corpus.
Attributes: stem: Name of the utterance without extension (``Train/123``, a UUID). text: Decoded transcript (``None`` unless ``state`` is ``ok``). state: ``ok``, ``no_audio``, ``no_text``, ``bad_encoding`` or ``bench_reserved``. """
stem: str text: str | None state: str
def _pair_rows( texts: Mapping[str, bytes], audio_keys: Set[str], audio_ext: str, text_ext: str) -> list[_ArchiveRow]: """Pair transcripts with audio members by stem (every stem of either kind is a row).""" stems = {k[: -len(audio_ext)] for k in audio_keys} | {k[: -len(text_ext)] for k in texts} rows: list[_ArchiveRow] = [] for stem in stems: raw = texts.get(stem + text_ext) if stem + audio_ext not in audio_keys: rows.append(_ArchiveRow(stem, None, STATE_NO_AUDIO)) elif raw is None: rows.append(_ArchiveRow(stem, None, STATE_NO_TEXT)) else: try: rows.append(_ArchiveRow(stem, raw.decode("utf-8"), STATE_OK)) except UnicodeDecodeError: rows.append(_ArchiveRow(stem, None, STATE_BAD_ENCODING)) return rows
def _order_rows(rows: list[_ArchiveRow]) -> list[_ArchiveRow]: """Deterministic order that does not depend on the order inside the archive: by the sha1 of the stem, so a prefix of the corpus (``--max-hours``) is a spread over all of it rather than its first recordings.""" return sorted(rows, key=lambda r: (hashlib.sha1(r.stem.encode("utf-8")).hexdigest(), r.stem))
def _bad_state_record(sid: str, item_id: str, row: _ArchiveRow) -> QuarantineRecord | None: if row.state == STATE_NO_AUDIO: return _drop(sid, item_id, "audio_missing", where="archive") if row.state == STATE_NO_TEXT: return _drop(sid, item_id, "text_missing") if row.state == STATE_BAD_ENCODING: return _drop(sid, item_id, "bad_encoding") if row.state == STATE_BENCH_RESERVED: return _drop(sid, item_id, "bench_reserved") return None
class _ArchiveCorpusAdapter: """Shared machinery of the archive corpora (see the module docstring).
Subclasses provide the archive, the classifier, the rows and the item mapping. """
ephemeral_raw = True source_id = "" audio_ext = "" text_ext = ""
def __init__(self, cfg: ImportConfig, cache: Path) -> None: self._cfg = cfg self._cache = cache self._rows_cache: list[_ArchiveRow] | None = None
# -- provided by the subclass def _archive(self) -> Path: raise NotImplementedError
def _classify(self, name: str) -> tuple[str, Kind] | None: raise NotImplementedError
def _load_rows(self) -> list[_ArchiveRow]: raise NotImplementedError
def _unit_rows(self) -> int: raise NotImplementedError
def _expected_pairs(self) -> int: raise NotImplementedError
def _group(self, row: _ArchiveRow) -> str: raise NotImplementedError
def _extra(self, row: _ArchiveRow) -> dict[str, Scalar]: return {}
# -- shared @property def source_ids(self) -> frozenset[str]: return frozenset({self.source_id})
def _rows(self) -> list[_ArchiveRow]: if self._rows_cache is None: rows = self._load_rows() if len(rows) != self._expected_pairs(): raise ArchiveError( f"{self._archive()}: {len(rows)} utterances, expected " f"{self._expected_pairs()} (configured): a truncated, changed or wrong " "archive" ) self._rows_cache = _order_rows(rows) return self._rows_cache
def _item_id(self, row: _ArchiveRow) -> str: return row.stem + self.audio_ext
def raw_path(self, item: Item) -> Path: return self._cache / "raw" / self.source_id / item.item_id
def _units(self) -> tuple[str, ...]: return _chunk_ids(len(self._rows()), self._unit_rows())
def iter_unit( self, unit_id: str, only: Set[str] | None = None, exclude: Mapping[str, str] | None = None, ) -> Generator[Item | QuarantineRecord, None, None]: window = _chunk_slice(unit_id, self._unit_rows()) first = dict(exclude or {}) candidates: list[Item] = [] for row in self._rows()[window]: made = self._row(unit_id, row, only, first) if isinstance(made, QuarantineRecord): yield made elif made is not None: candidates.append(made) # The key of an audio member is its item id (see the classifiers). wanted = {c.item_id: self.raw_path(c) for c in candidates if not self.raw_path(c).is_file()} yielded = 0 try: if wanted: scan_archive(self._archive(), self._classify, read_text=False, extract=wanted) for number, item in enumerate(candidates): yielded = number + 1 if self.raw_path(item).is_file(): yield item else: yield _drop(item.segment_id, item.item_id, "audio_missing") finally: # Raw files of rows nobody took (budget reached, or an error): nothing else would # delete them. for item in candidates[yielded:]: self.raw_path(item).unlink(missing_ok=True)
def _row( self, unit_id: str, row: _ArchiveRow, only: Set[str] | None, first: dict[str, str], ) -> Item | QuarantineRecord | None: item_id = self._item_id(row) sid = item_segment_id(self.source_id, item_id) if only is not None and sid not in only: return None bad = _bad_state_record(sid, item_id, row) if bad is not None: return bad assert row.text is not None try: text = normalise_transcript(row.text, self._cfg.char_map) except TextRejected as err: return _text_drop(sid, item_id, err) duplicate = _first_seen(first, sid, item_id, unit_id) if duplicate is not None: return duplicate return Item( source_id=self.source_id, item_id=item_id, segment_id=sid, unit_id=unit_id, text=text, group=nfc(self._group(row)), emotion=None, extra=self._extra(row), )
# ------------------------------------------------------------------------------ ISSAI TSC
class IssaiTscAdapter(_ArchiveCorpusAdapter): """``issai/Turkish_Speech_Corpus``: ``ISSAI_TSC_218.tar.gz`` with ``ISSAI_TSC_218/{Train,Dev,Test}/<number>.wav|.txt`` (layout and numbers: the comments of ``configs/data/import_corpora.yaml``).
The archive is downloaded once to ``<cache>/hub/issai_tsc/`` (pinned by the Hub commit, which fixes the LFS object), indexed once (the index is kept next to it), and read again for every work unit. Rows are ordered by the sha1 of ``<folder>/<number>``; the group is ``issai_tsc.group_prefix + number // group_block_ids`` because the corpus names no speaker. ``extra`` keeps the corpus folder (``corpus_split``) and the number.
Reasons of its own: none beyond the shared ones. """
source_id = ISSAI_TSC_SOURCE_ID audio_ext = ".wav" text_ext = ".txt"
def __init__( self, cfg: ImportConfig, cache: Path, hub: HubClient, revision: str | None ) -> None: super().__init__(cfg, cache) self._hub = hub self.revision = revision self._archive_path: Path | None = None
@property def _c(self) -> IssaiTscConfig: return self._cfg.issai_tsc
def _revision(self) -> str: if self.revision is None: raise HubError("issai_tsc: the revision is not pinned; call list_units() first") return self.revision
def _archive(self) -> Path: if self._archive_path is None or not self._archive_path.is_file(): path = self._hub.download( self._c.repo_id, self._revision(), self._c.archive_file, self._cache / "hub" / "issai_tsc", ) verify_sha256_once(path, self._c.archive_sha256) # raises on a partial download self._archive_path = path return self._archive_path
def _classify(self, name: str) -> tuple[str, Kind] | None: match = _ISSAI_MEMBER_RE.fullmatch(name) if match is None or match.group(1) != self._c.archive_root: return None _, split, number, ext = match.groups() if split not in self._c.splits: return None return f"{split}/{number}.{ext}", ("audio" if ext == "wav" else "text")
def _index_path(self) -> Path: """The index depends on the revision and on how the archive is read (root, folders).""" layout = json.dumps( [self._c.archive_file, self._c.archive_sha256, self._c.archive_root, self._c.splits] ) key = hashlib.sha1(layout.encode("utf-8")).hexdigest()[:8] name = f"index-{self._revision()[:12]}-{key}.jsonl" return self._cache / "hub" / "issai_tsc" / name
def _load_rows(self) -> list[_ArchiveRow]: index = self._index_path() if index.is_file(): return _read_index(index) scan = scan_archive(self._archive(), self._classify, read_text=True) rows = _pair_rows(scan.texts, scan.audio_keys, self.audio_ext, self.text_ext) _write_index(index, rows) return rows
def _unit_rows(self) -> int: return self._c.unit_rows
def _expected_pairs(self) -> int: return self._c.expected_pairs
def _group(self, row: _ArchiveRow) -> str: number = int(row.stem.split("/", 1)[1]) return f"{self._c.group_prefix}{number // self._c.group_block_ids}"
def _extra(self, row: _ArchiveRow) -> dict[str, Scalar]: split, number = row.stem.split("/", 1) return {"corpus_split": split, "utterance_number": int(number)}
def list_units(self) -> UnitListing: repo = self._c.repo_id if self.revision is None: self.revision = self._hub.resolve_revision(repo) files = self._hub.list_files(repo, self.revision) if self._c.archive_file not in files: raise HubError( f"{repo}@{self.revision}: no file {self._c.archive_file!r}; " f"first files: {sorted(files)[:5]}" ) return UnitListing(self.revision, self._units())
def _write_index(path: Path, rows: list[_ArchiveRow]) -> None: lines = [ json.dumps({"stem": r.stem, "text": r.text, "state": r.state}, ensure_ascii=False) for r in sorted(rows, key=lambda r: r.stem) ] atomic_write_text(path, "\n".join(lines) + "\n")
def _read_index(path: Path) -> list[_ArchiveRow]: rows: list[_ArchiveRow] = [] for number, line in enumerate(path.read_text(encoding="utf-8").split("\n"), start=1): if not line: continue try: obj = json.loads(line) except json.JSONDecodeError as err: raise ValueError(f"{path}:{number}: invalid JSON ({err.msg}); delete the file") from err ok = ( isinstance(obj, dict) and set(obj) == {"stem", "text", "state"} and isinstance(obj["stem"], str) and obj["state"] in _STATES and (obj["text"] is None or isinstance(obj["text"], str)) ) if not ok: raise ValueError(f"{path}:{number}: not an index row; delete the file") rows.append(_ArchiveRow(obj["stem"], obj["text"], obj["state"])) return rows
# ------------------------------------------------------------------------------ MediaSpeech
class MediaSpeechAdapter(_ArchiveCorpusAdapter): """OpenSLR SLR108 MediaSpeech Turkish: ``TR.tgz`` with ``TR/<uuid>.flac`` + ``<uuid>.txt``.
The archive is downloaded from the primary OpenSLR URL to ``<cache>/hub/mediaspeech_tr/`` (resumable) and must have the sha256 of the pin: ``revision`` (``--revision``, or the one recorded in ``plan.json``) or ``mediaspeech_tr.sha256``. A different file is an error and is not used. The corpus is one group (``mediaspeech_tr.group``). """
source_id = MEDIASPEECH_SOURCE_ID audio_ext = ".flac" text_ext = ".txt"
def __init__( self, cfg: ImportConfig, cache: Path, opener: fetch.Opener | None, revision: str | None, ) -> None: super().__init__(cfg, cache) self._opener = opener or fetch.default_opener self.revision = revision self._download: fetch.Downloaded | None = None
@property def _c(self) -> MediaSpeechConfig: return self._cfg.mediaspeech_tr
def _archive(self) -> Path: if self._download is None or not self._download.path.is_file(): self._download = fetch.download( self._c.url, self._cache / "hub" / "mediaspeech_tr" / "TR.tgz", expected_sha256=self.revision or self._c.sha256, opener=self._opener, ) return self._download.path
def _classify(self, name: str) -> tuple[str, Kind] | None: match = _MEDIASPEECH_MEMBER_RE.fullmatch(name) if match is None or match.group(1) != self._c.archive_root: return None _, stem, ext = match.groups() return f"{stem}.{ext}", ("audio" if ext == "flac" else "text")
def _load_rows(self) -> list[_ArchiveRow]: head = _FLAC_HEAD_BYTES if self._c.reserve_bench_clips else 0 scan = scan_archive(self._archive(), self._classify, read_text=True, audio_head=head) rows = _pair_rows(scan.texts, scan.audio_keys, self.audio_ext, self.text_ext) if not self._c.reserve_bench_clips: return rows reserved = _bench_reserved_stems(scan) return [ _ArchiveRow(r.stem, None, STATE_BENCH_RESERVED) if r.state == STATE_OK and r.stem in reserved else r for r in rows ]
def _unit_rows(self) -> int: return self._c.unit_rows
def _expected_pairs(self) -> int: return self._c.expected_pairs
def _group(self, row: _ArchiveRow) -> str: return self._c.group
def list_units(self) -> UnitListing: units = self._units() # downloads and verifies the archive assert self._download is not None self.revision = self._download.sha256 return UnitListing(self.revision, units)
def flac_duration_ms(head: bytes) -> int: """Duration of a FLAC file from its first 26 bytes (the STREAMINFO block).
The rounding is the benchmark's (``round(1000 * frames / sample_rate)``).
Raises: ArchiveError: not FLAC, no STREAMINFO first, or a zero sample rate. """ if len(head) < _FLAC_HEAD_BYTES or head[:4] != b"fLaC" or head[4] & 0x7F != 0: raise ArchiveError(f"not a FLAC header with STREAMINFO first: {head[:8]!r}") packed = int.from_bytes(head[_FLAC_STREAMINFO_AT : _FLAC_STREAMINFO_AT + 8], "big") rate_hz, frames = packed >> 44, packed & ((1 << 36) - 1) if rate_hz == 0: raise ArchiveError("FLAC STREAMINFO with sample rate 0") return round(1000 * frames / rate_hz)
def _bench_reserved_stems(scan: ArchiveScan) -> set[str]: """Stems of the clips the phase-0 B1 benchmark drew from MediaSpeech.
The benchmark's selection (:func:`nida.bench.clips.select_mediaspeech` with the default :class:`~nida.bench.prepare.B1Plan`) is recomputed from the archive, exactly as :mod:`nida.bench.prepare` feeds it: every pair, transcript stripped, FLAC duration. """ plan = B1Plan() items: list[MediaSpeechItem] = [] for key, raw in scan.texts.items(): stem = key[: -len(".txt")] head = scan.audio_heads.get(stem + ".flac") if head is None: continue try: text = raw.decode("utf-8").strip() except UnicodeDecodeError: continue items.append(MediaSpeechItem(stem, text, flac_duration_ms(head))) try: selection = select_mediaspeech(items, plan.n_mediaspeech, plan.seed) except ValueError as err: raise ArchiveError(f"cannot reproduce the B1 benchmark selection: {err}") from err return {clip.file_id for clip in selection.clips}
# ------------------------------------------------------------------------------ Common Voice
def find_common_voice_root(source: Path, cfg: CommonVoiceConfig) -> Path: """The folder with ``validated.tsv`` of a Common Voice release directory.
Tries ``source`` itself (the language folder), ``source/<locale>`` and ``source/<release>/<locale>`` (``source`` is a folder of releases).
Raises: FileNotFoundError: none of them has the validated file. """ tried = [source, source / cfg.locale] if source.is_dir(): tried += [d / cfg.locale for d in sorted(source.iterdir()) if d.is_dir()] for folder in tried: if (folder / cfg.validated_file).is_file(): return folder raise FileNotFoundError( f"no {cfg.validated_file} in {source} (tried {[str(t) for t in tried[:4]]}...); " f"--source-dir is the Common Voice release folder or its {cfg.locale!r} folder, " "or the release tarball" )
@dataclass(frozen=True)class _CvRow: """A row of ``validated.tsv`` (only the columns the importer uses).
``problem`` is set (and the other fields are empty) for a row that does not match the header; ``raw`` is then a description of its shape for the quarantine record (never its text: the client id would end up in the quarantine log). """
path: str sentence: str client_id: str up_votes: str down_votes: str locale: str problem: str = "" raw: str = ""
_CV_REQUIRED = ("client_id", "path", "sentence", "up_votes", "down_votes")
def _read_cv_tsv(path: Path) -> list[_CvRow]: """Rows of a Common Voice TSV (tab separated, no quoting).
Raises: ValueError: the header lacks a required column or repeats a column. """ rows: list[_CvRow] = [] with path.open(encoding="utf-8", newline="") as handle: reader = csv.reader(handle, delimiter="\t", quoting=csv.QUOTE_NONE) header = next(reader, None) if header is None: raise ValueError(f"{path}: empty file (no header)") header = [h.strip() for h in header] if len(set(header)) != len(header): raise ValueError(f"{path}: duplicate columns in the header {header}") missing = [c for c in _CV_REQUIRED if c not in header] if missing: raise ValueError(f"{path}: columns missing: {missing}; header is {header}") at = {name: header.index(name) for name in (*_CV_REQUIRED, "locale") if name in header} for fields in reader: if not fields: continue if len(fields) != len(header): # Only the shape of the row is kept: its text may hold the client id. shape = f"{len(fields)} fields, the header has {len(header)}" rows.append(_CvRow("", "", "", "", "", "", "columns", shape)) continue rows.append( _CvRow( path=fields[at["path"]], sentence=fields[at["sentence"]], client_id=fields[at["client_id"]], up_votes=fields[at["up_votes"]], down_votes=fields[at["down_votes"]], locale=fields[at["locale"]] if "locale" in at else "", ) ) return rows
class CommonVoiceAdapter: """A Common Voice release the user downloaded (``--source-dir``): a folder or a tarball.
Rows are the lines of ``validated.tsv``; a clip is used when ``up_votes - down_votes >= common_voice_tr.min_net_votes`` and its ``locale`` is empty or ``common_voice_tr.locale``. The group is ``group_prefix`` + the first 16 hex digits of sha1(``client_id``): the raw client id (a pseudonymous speaker id the MDC terms forbid trying to resolve) never reaches a manifest or dataset. Votes are kept in ``extra``; nothing demographic is.
From a folder the MP3 clips are read in place and never deleted. From a tarball only ``validated.tsv`` is extracted up front (to ``<cache>/raw/common_voice_tr/<id>/``); the clips of a work unit are extracted per unit and deleted by the audio stage like the other archive corpora.
Reasons of its own: ``language`` (another non-empty locale), ``low_votes``, ``no_group``, ``bad_row`` (wrong column count, bad path, non-integer votes). """
source_id = COMMON_VOICE_SOURCE_ID
def __init__(self, cfg: ImportConfig, cache: Path, source: Path) -> None: if not source.exists(): raise FileNotFoundError(f"{source} does not exist (--source-dir)") require_audio_format("MP3") self._cfg = cfg self._cache = cache self._source = source self._tarball = source.is_file() self.ephemeral_raw = self._tarball self._layout_cache: tuple[Path, Path] | None = None self._rows_cache: list[_CvRow] | None = None
@property def _c(self) -> CommonVoiceConfig: return self._cfg.common_voice_tr
@property def source_ids(self) -> frozenset[str]: return frozenset({self.source_id})
def _classify(self, name: str) -> tuple[str, Kind] | None: parts = name.split("/") in_locale = len(parts) < 3 or parts[-3] == self._c.locale if parts[-1] == self._c.validated_file and (len(parts) == 1 or parts[-2] == self._c.locale): return "validated", "text" if len(parts) >= 2 and parts[-2] == self._c.clips_dir and in_locale: return f"{self._c.clips_dir}/{parts[-1]}", "audio" return name, "ignore"
def _layout(self) -> tuple[Path, Path]: """``(validated.tsv, clips folder)`` on disk (a tarball is partly extracted).""" if self._layout_cache is None: if not self._tarball: root = find_common_voice_root(self._source, self._c) else: stat = self._source.stat() identity = f"{self._source.name}\x1f{stat.st_size}\x1f{stat.st_mtime_ns}" ident = hashlib.sha1(identity.encode()).hexdigest() root = self._cache / "raw" / self.source_id / ident[:12] tsv = root / self._c.validated_file if not tsv.is_file(): done = scan_archive( self._source, self._classify, read_text=False, extract={"validated": tsv} ) if "validated" not in done.extracted: raise ArchiveError( f"{self._source}: no {self._c.locale}/{self._c.validated_file}" ) self._layout_cache = (root / self._c.validated_file, root / self._c.clips_dir) return self._layout_cache
def _rows(self) -> list[_CvRow]: if self._rows_cache is None: self._rows_cache = _read_cv_tsv(self._layout()[0]) return self._rows_cache
def list_units(self) -> UnitListing: tsv = self._layout()[0] digest = hashlib.sha1(tsv.read_bytes()).hexdigest() rows = self._rows() if not rows: raise ValueError(f"{tsv}: no row") return UnitListing(None, _chunk_ids(len(rows), self._c.unit_rows), digest)
def raw_path(self, item: Item) -> Path: return self._clip(item.item_id)
def iter_unit( self, unit_id: str, only: Set[str] | None = None, exclude: Mapping[str, str] | None = None, ) -> Generator[Item | QuarantineRecord, None, None]: window = _chunk_slice(unit_id, self._c.unit_rows) first = dict(exclude or {}) candidates: list[Item] = [] for offset, row in enumerate(self._rows()[window]): made = self._row(unit_id, window.start + offset, row, only, first) if isinstance(made, QuarantineRecord): yield made elif made is not None: candidates.append(made) yielded = 0 try: if self._tarball: wanted = { f"{self._c.clips_dir}/{c.item_id}": self.raw_path(c) for c in candidates if not self.raw_path(c).is_file() } if wanted: scan_archive(self._source, self._classify, read_text=False, extract=wanted) for number, item in enumerate(candidates): yielded = number + 1 if self.raw_path(item).is_file(): yield item else: yield _drop(item.segment_id, item.item_id, "audio_missing") finally: if self._tarball: # a cache copy; the user's own clips are never touched for item in candidates[yielded:]: self.raw_path(item).unlink(missing_ok=True)
def _row( self, unit_id: str, position: int, row: _CvRow, only: Set[str] | None, first: dict[str, str], ) -> Item | QuarantineRecord | None: cfg = self._cfg if row.problem: return _bad_row(unit_id, position, row.raw, "bad_row", problem=row.problem) rel = safe_relative_path(row.path) if rel is None or "\x1f" in rel: return _bad_row(unit_id, position, row.path, "bad_row", problem="path") sid = item_segment_id(self.source_id, rel) if only is not None and sid not in only: return None locale = row.locale.strip() if locale and locale != self._c.locale: return _drop(sid, rel, "language", locale=locale) try: up, down = int(row.up_votes), int(row.down_votes) except ValueError: return _drop(sid, rel, "bad_row", problem="votes", up_votes=row.up_votes[:20]) if up - down < self._c.min_net_votes: return _drop(sid, rel, "low_votes", up_votes=up, down_votes=down) client = nfc(row.client_id).strip() if not client: return _drop(sid, rel, "no_group") try: text = normalise_transcript(row.sentence, cfg.char_map) except TextRejected as err: return _text_drop(sid, rel, err) if not self._tarball and not self._clip(rel).is_file(): return _drop(sid, rel, "audio_missing") duplicate = _first_seen(first, sid, rel, unit_id) if duplicate is not None: return duplicate who = hashlib.sha1(f"common-voice-client\x1f{client}".encode()).hexdigest()[:16] return Item( source_id=self.source_id, item_id=rel, segment_id=sid, unit_id=unit_id, text=text, group=nfc(self._c.group_prefix + who), emotion=None, extra={"up_votes": up, "down_votes": down}, )
def _clip(self, item_id: str) -> Path: return self._layout()[1] / item_id123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150"""Hugging Face Hub access of the import adapters, behind a small injectable protocol.
The production implementation uses ``huggingface_hub`` (imported lazily; Colab ships it, it isnot a declared dependency of Nida). Tests inject a fake that serves local files. Everydownload is pinned to a full commit sha: :meth:`HubClient.resolve_revision` turns the currenthead of a dataset into one, once, and the sha is recorded in ``plan.json``."""
from __future__ import annotations
import importlibimport refrom collections.abc import Sequencefrom concurrent.futures import ThreadPoolExecutorfrom pathlib import Pathfrom typing import Any, Protocol
__all__ = ["HubClient", "HubError", "HuggingFaceHub", "require_commit_sha", "require_sha256"]
_SHA_RE = re.compile(r"[0-9a-f]{40}")_SHA256_RE = re.compile(r"[0-9a-f]{64}")#: Parallel file downloads of :meth:`HuggingFaceHub.download_many`.DOWNLOAD_THREADS = 8
class HubError(RuntimeError): """The Hub answered with something the importer cannot use."""
def require_commit_sha(revision: str) -> str: """Return ``revision`` if it is a full 40-character lowercase hex commit sha.
Raises: ValueError: otherwise (branch and tag names are not pins). """ if _SHA_RE.fullmatch(revision) is None: raise ValueError(f"revision must be a 40-character lowercase hex commit sha: {revision!r}") return revision
def require_sha256(value: str) -> str: """Return ``value`` if it is a 64-character lowercase hex SHA-256 digest (the pin of an archive that is not a Hub commit).
Raises: ValueError: otherwise. """ if _SHA256_RE.fullmatch(value) is None: raise ValueError(f"expected a 64-character lowercase hex sha256 digest: {value!r}") return value
class HubClient(Protocol): """What the adapters need from the Hub (dataset repositories only)."""
def resolve_revision(self, repo_id: str) -> str: """Commit sha of the current head of ``repo_id``.""" ...
def list_files(self, repo_id: str, revision: str) -> list[str]: """All file paths of the repository at ``revision`` (unsorted is fine).""" ...
def download(self, repo_id: str, revision: str, filename: str, local_dir: Path) -> Path: """Download one file to ``local_dir / filename``; returns that path.""" ...
def download_many( self, repo_id: str, revision: str, filenames: Sequence[str], local_dir: Path ) -> None: """Download several files to ``local_dir / <name>``; files that do not exist in the repository are skipped silently (the caller checks which ones arrived).""" ...
class HuggingFaceHub: """:class:`HubClient` over ``huggingface_hub`` (public datasets, no token)."""
@staticmethod def _module() -> Any: # Any: huggingface_hub is imported lazily and ships no stubs here try: return importlib.import_module("huggingface_hub") except ImportError as err: raise HubError( "huggingface_hub is required for Hub sources (pip install huggingface_hub)" ) from err
def resolve_revision(self, repo_id: str) -> str: info = self._module().HfApi().dataset_info(repo_id) sha = getattr(info, "sha", None) if not isinstance(sha, str): raise HubError(f"{repo_id}: the Hub returned no commit sha") return require_commit_sha(sha)
def list_files(self, repo_id: str, revision: str) -> list[str]: files = ( self._module() .HfApi() .list_repo_files(repo_id, repo_type="dataset", revision=require_commit_sha(revision)) ) return [str(name) for name in files]
def download(self, repo_id: str, revision: str, filename: str, local_dir: Path) -> Path: path = self._module().hf_hub_download( repo_id=repo_id, filename=filename, repo_type="dataset", revision=require_commit_sha(revision), local_dir=str(local_dir), ) return Path(str(path))
@classmethod def _not_found_error(cls) -> type[BaseException]: """``EntryNotFoundError`` of the installed ``huggingface_hub`` (its module moved).""" for name in ("huggingface_hub.errors", "huggingface_hub.utils"): try: error = getattr(importlib.import_module(name), "EntryNotFoundError") # noqa: B009 except (ImportError, AttributeError): continue if isinstance(error, type) and issubclass(error, BaseException): return error raise HubError("huggingface_hub has no EntryNotFoundError")
def download_many( self, repo_id: str, revision: str, filenames: Sequence[str], local_dir: Path ) -> None: """One ``hf_hub_download`` per file on a small thread pool; a file that is not in the repository is skipped, any other error is raised.""" if not filenames: return module = self._module() pinned = require_commit_sha(revision) missing = self._not_found_error()
def fetch_one(name: str) -> None: try: module.hf_hub_download( repo_id=repo_id, filename=name, repo_type="dataset", revision=pinned, local_dir=str(local_dir), ) except missing: return
with ThreadPoolExecutor(max_workers=DOWNLOAD_THREADS) as pool: for _ in pool.map(fetch_one, filenames): pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326"""The importer: stages, plan and resumability (layout: see :mod:`nida.data.importer`)."""
from __future__ import annotations
import hashlibimport ioimport jsonimport loggingimport mathfrom collections import Counterfrom collections.abc import Callable, Mapping, Sequencefrom concurrent.futures import ThreadPoolExecutorfrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any
import numpy as np
from nida.bench import envs as bench_envsfrom nida.bench import fetchfrom nida.bench.b1 import _stream_runnerfrom nida.bench.protocol import WorkRequest, WorkResult, load_resultsfrom nida.bench.registry import load_sources, require_approvedfrom nida.data import envsfrom nida.data.align import align_wordsfrom nida.data.asr_filter import check_alignmentfrom nida.data.ears import bucket_of, rate_chars_per_sfrom nida.data.importer.audio import ( AudioRejected, convert_to_wav16k, measure_wav16k, raw_duration_ms,)from nida.data.importer.config import ImportConfig, load_import_configfrom nida.data.importer.hub import ( HubClient, HuggingFaceHub, require_commit_sha, require_sha256,)from nida.data.importer.sources import ( HUB_SOURCES, LOCAL_SOURCES, SOURCES, Item, SourceAdapter, make_adapter,)from nida.data.pilot import DATASET_SHARD_FRAMES, FLOAT16_MAX_ABS, run_worker_jobfrom nida.data.quarantine import QuarantineLogfrom nida.data.registry import DATA_MODELSfrom nida.data.splits import assign_splitsfrom nida.data.timings import SegmentTimings, build_timings, write_timingsfrom nida.data.types import QuarantineRecordfrom nida.model.vocab import encode_textfrom nida.train.data import SPLITS, DataFormatError, load_latent_datasetfrom nida.utils.io import atomic_write_bytes, atomic_write_json, atomic_write_text
__all__ = ["STAGES", "ImportPlan", "ImportRequest", "Importer", "assign_group_splits"]
log = logging.getLogger(__name__)
#: Stages in run order; ``all`` runs them one after another.STAGES = ("select", "audio", "latents", "ctc", "timings", "dataset", "report")VAE_KEY = "voxcpm2_audiovae_v2"CTC_KEY = "mpoyraz_ctc_tr"#: Language written to every index record (the importer reads Turkish corpora only).LANGUAGE = "tr"#: Items between two progress lines.PROGRESS_EVERY = 1000#: Default number of audio conversion threads (decoding and resampling release the GIL).DEFAULT_AUDIO_THREADS = 4SECONDS_PER_HOUR = 3600.0
@dataclass(frozen=True)class ImportRequest: """What the caller asks for; part of the plan of a root.
Attributes: source: One of :data:`nida.data.importer.sources.SOURCES` (``alania``, ``tr_full``, ``wavdir``, ``issai_tsc``, ``mediaspeech_tr``, ``common_voice_tr``). max_hours: Stop selecting once this many hours of audio are selected. unit_offset: Index of the first work unit (parquet shard / row chunk) of this root. unit_count: Number of work units from ``unit_offset`` (``None`` = all the rest). Roots with disjoint ranges select disjoint data. revision: Pin (``None`` = resolve it once and record it): a Hub commit sha, or for ``mediaspeech_tr`` the sha256 of the ``TR.tgz`` archive (default: the one in ``import_corpora.yaml``). Refused for the local sources (``wavdir``, ``common_voice_tr``), which pin the sha1 of their manifest / validated file. """
source: str max_hours: float = 10.0 unit_offset: int = 0 unit_count: int | None = None revision: str | None = None
def __post_init__(self) -> None: if self.source not in SOURCES: raise ValueError(f"unknown source {self.source!r}; known: {SOURCES}") if not (math.isfinite(self.max_hours) and self.max_hours > 0): raise ValueError(f"max_hours must be a positive finite number, got {self.max_hours!r}") if isinstance(self.unit_offset, bool) or self.unit_offset < 0: raise ValueError(f"unit_offset must be an integer >= 0, got {self.unit_offset!r}") if self.unit_count is not None and ( isinstance(self.unit_count, bool) or self.unit_count < 1 ): raise ValueError(f"unit_count must be an integer >= 1, got {self.unit_count!r}") if self.revision is not None and self.source in LOCAL_SOURCES: raise ValueError( f"--revision is meaningless for source {self.source!r} (a local folder has no " "revision; the plan pins the sha1 of its manifest / validated file)" ) if self.revision is not None: if self.source == "mediaspeech_tr": require_sha256(self.revision) else: require_commit_sha(self.revision)
@dataclass(frozen=True)class ImportPlan: """The resolved request of a root (``plan.json``): fixes which units are processed.
A root is bound to its plan; asking for something else raises (use a new root). """
source: str revision: str | None max_hours: float unit_offset: int unit_count: int | None unit_ids: tuple[str, ...] config_digest: str content_sha1: str | None
def to_obj(self) -> dict[str, object]: return { "source": self.source, "revision": self.revision, "max_hours": self.max_hours, "unit_offset": self.unit_offset, "unit_count": self.unit_count, "unit_ids": list(self.unit_ids), "config_digest": self.config_digest, "content_sha1": self.content_sha1, }
@classmethod def from_obj(cls, obj: object, where: Path) -> ImportPlan: keys = { "source", "revision", "max_hours", "unit_offset", "unit_count", "unit_ids", "config_digest", "content_sha1", } if not isinstance(obj, dict) or set(obj) != keys or not isinstance(obj["unit_ids"], list): raise ValueError(f"{where}: not a plan.json written by the importer") return cls( source=str(obj["source"]), revision=None if obj["revision"] is None else str(obj["revision"]), max_hours=float(obj["max_hours"]), unit_offset=int(obj["unit_offset"]), unit_count=None if obj["unit_count"] is None else int(obj["unit_count"]), unit_ids=tuple(str(u) for u in obj["unit_ids"]), config_digest=str(obj["config_digest"]), content_sha1=None if obj["content_sha1"] is None else str(obj["content_sha1"]), )
def check(self, request: ImportRequest, config_digest: str, content_sha1: str | None) -> None: """Raise unless this plan is what ``request`` (and the current config/input) mean.""" wanted: dict[str, object] = { "source": request.source, "max_hours": request.max_hours, "unit_offset": request.unit_offset, "unit_count": request.unit_count, "config_digest": config_digest, "content_sha1": content_sha1, } actual = self.to_obj() if request.revision is not None: wanted["revision"] = request.revision differing = {k: (actual[k], v) for k, v in wanted.items() if actual[k] != v} if differing: raise ValueError( "this root was made for another plan (recorded, requested): " f"{differing}; use a new --root" )
@dataclass(frozen=True)class _UnitResult: """Outcome of one work unit, stored as ``select/units/<digest>.json``."""
unit_id: str truncated: bool items: tuple[Item, ...] quarantine: tuple[QuarantineRecord, ...]
def to_obj(self) -> dict[str, object]: return { "unit_id": self.unit_id, "truncated": self.truncated, "items": [item.to_obj() for item in self.items], "quarantine": [ {"item_id": q.item_id, "stage": q.stage, "reason": q.reason, "details": q.details} for q in self.quarantine ], }
@classmethod def load(cls, path: Path) -> _UnitResult: obj = json.loads(path.read_text(encoding="utf-8")) if not isinstance(obj, dict) or set(obj) != {"unit_id", "truncated", "items", "quarantine"}: raise ValueError(f"{path}: not a unit result") return cls( unit_id=str(obj["unit_id"]), truncated=bool(obj["truncated"]), items=tuple(Item.from_obj(i, f"{path}: item") for i in obj["items"]), quarantine=tuple( QuarantineRecord(q["item_id"], q["stage"], q["reason"], q["details"]) for q in obj["quarantine"] ), )
@dataclass(frozen=True)class _Seg: """A segment on its way through the stages.
``duration_ms`` / ``loudness_dbfs`` come from the audio stage; ``num_frames`` and ``frame_hop_ms`` from the latents stage (``0`` before it ran). """
item: Item duration_ms: int loudness_dbfs: float num_frames: int = 0 frame_hop_ms: float = 0.0 latent_dim: int = 0
@property def sid(self) -> str: return self.item.segment_id
@dataclass(frozen=True)class _TimelineOutcome: """A built timeline (with its mean word alignment score) or the quarantine record."""
timings: SegmentTimings | None quarantine: QuarantineRecord | None clamped_units: int = 0 mean_align_score: float = 0.0
def _digest(text: str) -> str: return hashlib.sha1(text.encode("utf-8")).hexdigest()[:16]
def _file_sha1(path: Path) -> str: return hashlib.sha1(path.read_bytes()).hexdigest()
def _write_jsonl(path: Path, rows: Sequence[Mapping[str, object]]) -> None: text = "".join(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n" for row in rows) atomic_write_text(path, text)
def _read_jsonl(path: Path) -> list[dict[str, object]]: rows: list[dict[str, object]] = [] for number, line in enumerate(path.read_text(encoding="utf-8").split("\n"), start=1): if not line: continue try: obj = json.loads(line) except json.JSONDecodeError as err: raise ValueError(f"{path}:{number}: invalid JSON ({err.msg})") from err if not isinstance(obj, dict): raise ValueError(f"{path}:{number}: expected a JSON object") rows.append(obj) return rows
def _hours(duration_ms: int) -> float: return round(duration_ms / 1000 / SECONDS_PER_HOUR, 3)
@dataclassclass Importer: """Imports one transcribed external corpus into a latent dataset (module docstring of :mod:`nida.data.importer`).
Attributes: root: Durable directory (Drive): plan, manifests, quarantine, worker results, dataset. cache: Local scratch: raw audio, 16 kHz wavs and ``.npy`` arrays (rebuilt when lost). envs_root: Where the worker virtual environments live. repo_dir: Repository root (environments are built from it). request: What to import. config_dir: ``configs/data`` (default ``repo_dir/configs/data``). sources_path: ``configs/sources.yaml`` (default ``repo_dir/configs/sources.yaml``). wavdir: ``--source-dir``: the folder of a ``wavdir`` source, or the Common Voice release folder / tarball of ``common_voice_tr``. hub: Hub client (default: ``huggingface_hub``). retry_failed: Pass ``--retry-failed`` to the workers. runner: Runs a worker command line and returns its exit code. opener: HTTP access of the ``mediaspeech_tr`` download (default: ``urllib``). uv: Path of the ``uv`` executable (default: found/installed on demand). audio_threads: Threads converting raw audio to 16 kHz wavs (operational: does not change the outputs). """
root: Path cache: Path envs_root: Path repo_dir: Path request: ImportRequest config_dir: Path | None = None sources_path: Path | None = None wavdir: Path | None = None hub: HubClient | None = None retry_failed: bool = False runner: Callable[[Sequence[str]], int] = _stream_runner opener: fetch.Opener | None = None uv: str | None = None audio_threads: int = DEFAULT_AUDIO_THREADS _ready: bool = field(default=False, init=False, repr=False) _cfg: ImportConfig | None = field(default=None, init=False, repr=False) _plan: ImportPlan | None = field(default=None, init=False, repr=False) _adapter: SourceAdapter | None = field(default=None, init=False, repr=False) _pythons: dict[str, Path] = field(default_factory=dict, init=False, repr=False)
def __post_init__(self) -> None: if isinstance(self.audio_threads, bool) or self.audio_threads < 1: raise ValueError(f"audio_threads must be an integer >= 1, got {self.audio_threads!r}")
# ------------------------------------------------------------------ setup
@property def cfg(self) -> ImportConfig: if self._cfg is None: raise RuntimeError("Importer is not prepared; call run()") return self._cfg
@property def plan(self) -> ImportPlan: if self._plan is None: raise RuntimeError("Importer is not prepared; call run()") return self._plan
@property def adapter(self) -> SourceAdapter: if self._adapter is None: raise RuntimeError("Importer is not prepared; call run()") return self._adapter
def dataset_dir(self) -> Path: """``<root>/dataset-<config digest>/``.""" return self.root / f"dataset-{self.cfg.digest}"
def _prepare(self) -> None: """Load the config, check the licence gate, load or create the plan (once per run).""" if self._ready: return config_dir = self.config_dir or self.repo_dir / "configs" / "data" sources_path = self.sources_path or self.repo_dir / "configs" / "sources.yaml" cfg = load_import_config(config_dir, self.request.source) plan_path = self.root / "plan.json" existing: ImportPlan | None = None if plan_path.is_file(): existing = ImportPlan.from_obj(json.loads(plan_path.read_text("utf-8")), plan_path) hub = self.hub if hub is None and self.request.source in HUB_SOURCES: hub = HuggingFaceHub() adapter = make_adapter( self.request.source, cfg, self.cache, hub=hub, revision=existing.revision if existing else self.request.revision, wavdir=self.wavdir, opener=self.opener, ) needed = set(adapter.source_ids) | {DATA_MODELS[k].source_id for k in (VAE_KEY, CTC_KEY)} require_approved(needed, load_sources(sources_path)) if existing is not None: local = self.request.source in LOCAL_SOURCES content = adapter.list_units().content_sha1 if local else None existing.check(self.request, cfg.digest, content) plan = existing else: listing = adapter.list_units() stop = ( None if self.request.unit_count is None else (self.request.unit_offset + self.request.unit_count) ) unit_ids = listing.unit_ids[self.request.unit_offset : stop] if not unit_ids: raise ValueError( f"no work unit in range: offset {self.request.unit_offset}, count " f"{self.request.unit_count}, {len(listing.unit_ids)} units exist" ) plan = ImportPlan( source=self.request.source, revision=listing.revision, max_hours=self.request.max_hours, unit_offset=self.request.unit_offset, unit_count=self.request.unit_count, unit_ids=unit_ids, config_digest=cfg.digest, content_sha1=listing.content_sha1, ) atomic_write_json(plan_path, plan.to_obj()) log.info( "plan: %s revision %s, %d of %d units", plan.source, plan.revision, len(unit_ids), len(listing.unit_ids), ) self._cfg, self._plan, self._adapter, self._ready = cfg, plan, adapter, True
# -------------------------------------------------------------- stage state
def _marker(self, stage: str) -> Path: return self.root / stage / "stage.json"
def _reuse(self, stage: str, input_sha1: str) -> dict[str, object] | None: """The recorded result of a finished stage (``reused: True``), else ``None``.""" marker = self._marker(stage) if not marker.is_file(): return None recorded = json.loads(marker.read_text(encoding="utf-8")) if recorded.get("input_sha1") != input_sha1: raise RuntimeError( f"{stage}: its input changed after it ran; move {marker.parent} away to recompute" ) result: dict[str, object] = dict(recorded["result"]) result["reused"] = True return result
def _finish(self, stage: str, input_sha1: str, result: dict[str, object]) -> dict[str, object]: atomic_write_json( self._marker(stage), {"stage": stage, "input_sha1": input_sha1, "result": result} ) return {**result, "reused": False}
def _require_done(self, stage: str) -> None: if not self._marker(stage).is_file(): raise RuntimeError(f"stage {stage!r} has not finished; run it first")
def _write_quarantine(self, stage: str, records: Sequence[QuarantineRecord]) -> dict[str, int]: """Replace the stage's quarantine log by ``records`` (a stage rerun rebuilds it).""" qlog = QuarantineLog(self.root / stage) qlog.path.unlink(missing_ok=True) qlog.append(records) return qlog.counts_by_reason()
def _drop(self, stage: str, item: Item, reason: str, **details: object) -> QuarantineRecord: return QuarantineRecord( item.segment_id, stage, reason, {"item_id": item.item_id, **details} )
# --------------------------------------------------------------------- run
def run(self, stage: str) -> dict[str, object]: """Run one stage (or ``all``); returns the stage result(s) as plain JSON data.
Raises: ValueError: unknown stage, or a root made for another plan/config. nida.bench.registry.SourceNotApprovedError: a source or model is not approved. """ if stage == "all": return {name: self.run(name) for name in STAGES} if stage not in STAGES: raise ValueError(f"unknown import stage {stage!r}; known: {', '.join(STAGES)}") self._prepare() log.info("=== import stage %s", stage) handler: Callable[[], dict[str, object]] = getattr(self, "_stage_" + stage) return handler()
# ------------------------------------------------------------------ select
def _stage_select(self) -> dict[str, object]: """Walk the planned units in order, stop at ``max_hours``; write the item manifest.
Each finished unit is stored (``select/units/<digest>.json``) so an interrupted run continues with the next unit. The last unit is cut at the first item that would exceed the budget (``truncated``). Duplicate segment ids across units are quarantined. """ cfg, plan = self.cfg, self.plan plan_sha = _digest(json.dumps(plan.to_obj(), sort_keys=True)) reused = self._reuse("select", plan_sha) if reused is not None: return reused units_dir = self.root / "select" / "units" budget_ms = round(plan.max_hours * 3_600_000) total_ms = 0 done: list[_UnitResult] = [] selected_in: dict[str, str] = {} # segment id -> unit that selected it stopped = False for unit_id in plan.unit_ids: path = units_dir / f"{_digest(unit_id)}.json" if path.is_file(): result = _UnitResult.load(path) if result.unit_id != unit_id: raise RuntimeError( f"{path} belongs to unit {result.unit_id!r}, not {unit_id!r}" ) else: if budget_ms - total_ms < cfg.min_duration_ms: stopped = True break result = self._select_unit(unit_id, budget_ms - total_ms, selected_in) atomic_write_json(path, result.to_obj()) log.info( "select: unit %s -> %d items, %d quarantined", unit_id, len(result.items), len(result.quarantine), ) done.append(result) for item in result.items: selected_in.setdefault(item.segment_id, result.unit_id) total_ms += sum(item.raw_duration_ms or 0 for item in result.items) if result.truncated: stopped = True break items: list[Item] = [] records: list[QuarantineRecord] = [] first_unit: dict[str, str] = {} for result in done: records.extend(result.quarantine) for item in result.items: if item.segment_id in first_unit: records.append( self._drop( "select", item, "duplicate_item", unit_id=item.unit_id, first_unit_id=first_unit[item.segment_id], ) ) continue first_unit[item.segment_id] = item.unit_id items.append(item) counts = self._write_quarantine("select", records) if not items: raise RuntimeError(f"select kept no item from {len(done)} units; quarantined: {counts}") _write_jsonl(self.root / "select" / "manifest.jsonl", [i.to_obj() for i in items]) selected_ms = sum(item.raw_duration_ms or 0 for item in items) return self._finish( "select", plan_sha, { "units_planned": len(plan.unit_ids), "units_processed": len(done), "stopped_by_max_hours": stopped, "selected": len(items), "selected_hours": _hours(selected_ms), "quarantined": counts, }, )
def _select_unit( self, unit_id: str, remaining_ms: int, selected_in: Mapping[str, str] ) -> _UnitResult: """One unit: items within ``remaining_ms``; ids in ``selected_in`` (earlier units) are quarantined as duplicates by the adapter before their audio is written.""" cfg, adapter = self.cfg, self.adapter items: list[Item] = [] records: list[QuarantineRecord] = [] used_ms = 0 truncated = False events = adapter.iter_unit(unit_id, exclude=selected_in) try: for event in events: if isinstance(event, QuarantineRecord): records.append(event) continue raw = adapter.raw_path(event) reason: str | None = None details: dict[str, object] = {} duration_ms = 0 try: duration_ms = raw_duration_ms(raw) except AudioRejected as err: reason, details = err.reason, err.details else: if duration_ms < cfg.min_duration_ms: reason, details = "too_short", {"duration_ms": duration_ms} elif duration_ms > cfg.max_duration_ms: reason, details = "too_long", {"duration_ms": duration_ms} if reason is not None: records.append(self._drop("select", event, reason, **details)) elif used_ms + duration_ms > remaining_ms: truncated = True else: items.append(_with_duration(event, duration_ms)) used_ms += duration_ms if reason is not None or truncated: if adapter.ephemeral_raw: raw.unlink(missing_ok=True) if truncated: break finally: events.close() return _UnitResult(unit_id, truncated, tuple(items), tuple(records))
def _select_items(self) -> list[Item]: self._require_done("select") return [ Item.from_obj(row, f"select/manifest.jsonl:{number}") for number, row in enumerate(_read_jsonl(self.root / "select" / "manifest.jsonl"), 1) ]
# ------------------------------------------------------------------- audio
def _wav(self, sid: str) -> Path: return self.cache / "audio16k" / f"{sid}.wav"
def _npy(self, model_key: str, sid: str) -> Path: return self.cache / "arrays" / model_key / f"{sid}.npy"
def _refetch(self, items: Sequence[Item]) -> None: """Put the raw audio of ``items`` back into the cache (one pass per unit).""" by_unit: dict[str, set[str]] = {} for item in items: by_unit.setdefault(item.unit_id, set()).add(item.segment_id) for unit_id, sids in by_unit.items(): log.info("refetching raw audio of %d items of unit %s", len(sids), unit_id) events = self.adapter.iter_unit(unit_id, only=sids) try: for _ in events: pass finally: events.close()
def _ensure_wavs(self, items: Sequence[Item]) -> dict[str, AudioRejected]: """Make sure the 16 kHz wav of every item is in the cache.
Missing wavs are converted from the raw audio, which is fetched again first if it is gone too (ephemeral sources). Converted ephemeral raw files are deleted.
Returns: ``{segment_id: reason}`` for the items that could not be given a wav. """ adapter = self.adapter todo = [i for i in items if not self._wav(i.segment_id).is_file()] if not todo: return {} if adapter.ephemeral_raw: self._refetch([i for i in todo if not adapter.raw_path(i).is_file()]) failures: dict[str, AudioRejected] = {} with ThreadPoolExecutor(max_workers=self.audio_threads) as pool: outcomes = pool.map(self._convert_one, todo) for number, (item, error) in enumerate(zip(todo, outcomes, strict=True), start=1): if error is not None: failures[item.segment_id] = error if number % PROGRESS_EVERY == 0: log.info("audio: converted %d/%d", number, len(todo)) return failures
def _convert_one(self, item: Item) -> AudioRejected | None: """Raw audio -> working wav for one item (thread-safe: touches only this item's files).""" adapter = self.adapter raw = adapter.raw_path(item) if not raw.is_file(): return AudioRejected("raw_audio_missing", path=str(raw)) error: AudioRejected | None = None try: convert_to_wav16k(raw, self._wav(item.segment_id)) except AudioRejected as err: error = err if adapter.ephemeral_raw: raw.unlink(missing_ok=True) return error
def _measure(self, item: Item) -> tuple[int, float]: """``(duration_ms, loudness_dbfs)`` of the item's wav; a bad cached wav is rebuilt once.""" wav = self._wav(item.segment_id) for attempt in (1, 2): try: facts = measure_wav16k(wav) except AudioRejected: if attempt == 2: raise wav.unlink(missing_ok=True) failed = self._ensure_wavs([item]) if item.segment_id in failed: raise failed[item.segment_id] from None else: return facts.duration_ms, facts.loudness_dbfs raise AssertionError("unreachable") # pragma: no cover
def _stage_audio(self) -> dict[str, object]: """16 kHz mono wav of every selected item, measured; unusable audio is quarantined.""" cfg = self.cfg items = self._select_items() input_sha = _file_sha1(self.root / "select" / "manifest.jsonl") reused = self._reuse("audio", input_sha) if reused is not None: return reused failures = self._ensure_wavs(items) rows: list[dict[str, object]] = [] records: list[QuarantineRecord] = [] kept_ms = 0 for number, item in enumerate(items, start=1): error = failures.get(item.segment_id) reason: str | None = None details: dict[str, object] = {} duration_ms, loudness = 0, 0.0 if error is not None: reason, details = error.reason, error.details else: try: duration_ms, loudness = self._measure(item) except AudioRejected as err: reason, details = err.reason, err.details else: if duration_ms < cfg.min_duration_ms: reason, details = "too_short", {"duration_ms": duration_ms} elif duration_ms > cfg.max_duration_ms: reason, details = "too_long", {"duration_ms": duration_ms} elif loudness < cfg.min_loudness_dbfs: reason, details = "silent", {"loudness_dbfs": round(loudness, 2)} if reason is not None: records.append(self._drop("audio", item, reason, **details)) else: rows.append( { "segment_id": item.segment_id, "duration_ms": duration_ms, "loudness_dbfs": loudness, } ) kept_ms += duration_ms if self.adapter.ephemeral_raw: self.adapter.raw_path(item).unlink(missing_ok=True) if number % PROGRESS_EVERY == 0: log.info("audio: measured %d/%d", number, len(items)) counts = self._write_quarantine("audio", records) if not rows: raise RuntimeError(f"audio kept no item of {len(items)}; quarantined: {counts}") _write_jsonl(self.root / "audio" / "manifest.jsonl", rows) return self._finish( "audio", input_sha, { "input": len(items), "kept": len(rows), "kept_hours": _hours(kept_ms), "quarantined": counts, }, )
# ------------------------------------------------------- shared stage tables
def _segs(self, upto: str) -> list[_Seg]: """Segments that survived every stage up to and including ``upto`` (``audio`` | ``latents`` | ``ctc``), in select order.""" order = ("audio", "latents", "ctc") if upto not in order: raise ValueError(f"unknown stage {upto!r}") for stage in order[: order.index(upto) + 1]: self._require_done(stage) audio = { str(r["segment_id"]): r for r in _read_jsonl(self.root / "audio" / "manifest.jsonl") } latents: dict[str, dict[str, object]] = {} if upto != "audio": latents = { str(r["segment_id"]): r for r in _read_jsonl(self.root / "latents" / "manifest.jsonl") } ctc: set[str] | None = None if upto == "ctc": ctc = {str(r["segment_id"]) for r in _read_jsonl(self.root / "ctc" / "manifest.jsonl")} segs: list[_Seg] = [] for item in self._select_items(): row = audio.get(item.segment_id) if row is None: continue frames, hop, dim = 0, 0.0, 0 if upto != "audio": facts = latents.get(item.segment_id) if facts is None: continue frames = int(str(facts["num_frames"])) hop = float(str(facts["frame_hop_ms"])) dim = int(str(facts["latent_dim"])) if ctc is not None and item.segment_id not in ctc: continue segs.append( _Seg( item, int(str(row["duration_ms"])), float(str(row["loudness_dbfs"])), frames, hop, dim, ) ) return segs
# ----------------------------------------------------------------- workers
def _python(self, key: str) -> Path: if key not in self._pythons: if self.uv is None: self.uv = bench_envs.find_uv(bench_envs.subprocess_runner) spec = envs.data_env_for_worker(DATA_MODELS[key].worker) self._pythons[key] = bench_envs.ensure_env( spec, self.envs_root, self.repo_dir, uv=self.uv ) return self._pythons[key]
def _pending(self, key: str, sids: Sequence[str]) -> set[str]: """Segments whose worker result is missing, failed (with ``retry_failed``) or whose array left the cache: these need their wav.""" path = self.root / "workers" / key / "results.jsonl" existing = load_results(path, repair=True) if path.exists() else {} pending: set[str] = set() for sid in sids: result = existing.get(sid) if result is None: pending.add(sid) elif result.output is None: if self.retry_failed: pending.add(sid) elif not Path(str(result.output.get("out_path", ""))).is_file(): pending.add(sid) return pending
def _run_model(self, key: str, segs: Sequence[_Seg]) -> dict[str, WorkResult]: """Run the data worker ``key`` over ``segs`` (resumable; no work when complete).""" model = DATA_MODELS[key] pending = self._pending(key, [s.sid for s in segs]) if pending: failed = self._ensure_wavs([s.item for s in segs if s.sid in pending]) if failed: sample = {sid: err.reason for sid, err in list(failed.items())[:3]} raise RuntimeError(f"{key}: {len(failed)} audio files cannot be rebuilt: {sample}") requests = tuple( WorkRequest(s.sid, str(self._wav(s.sid)), {"out_path": str(self._npy(key, s.sid))}) for s in segs ) return run_worker_job( self.root / "workers" / key, key, lambda: self._python(key), envs.worker_module_name(model.worker), model.ref.model_id, model.ref.revision, model.batch_size, requests, array_outputs=True, runner=self.runner, retry_failed=self.retry_failed, skip_if_complete=True, )
# ----------------------------------------------------------------- latents
def _stage_latents(self) -> dict[str, object]: """VAE latents (``vae_encode`` worker) of the segments that passed the audio stage.""" segs = self._segs("audio") input_sha = _file_sha1(self.root / "audio" / "manifest.jsonl") reused = self._reuse("latents", input_sha) if reused is not None: return reused results = self._run_model(VAE_KEY, segs) rows: list[dict[str, object]] = [] records: list[QuarantineRecord] = [] hops: set[float] = set() dims: set[int] = set() for seg in segs: result = results.get(seg.sid) if result is None: raise RuntimeError(f"{VAE_KEY}: no result for {seg.sid}") if result.output is None: records.append( self._drop("latents", seg.item, "latents_failed", error=result.error) ) continue array = np.load(str(result.output["out_path"]), allow_pickle=False) problem = _latent_problem(array) if problem is not None: records.append(self._drop("latents", seg.item, problem[0], **problem[1])) continue hop = float(str(result.output["frame_hop_ms"])) hops.add(hop) dims.add(int(array.shape[1])) rows.append( { "segment_id": seg.sid, "num_frames": int(array.shape[0]), "latent_dim": int(array.shape[1]), "frame_hop_ms": hop, } ) if len(hops) > 1 or len(dims) > 1: raise ValueError(f"latents disagree on frame hop {sorted(hops)} or dim {sorted(dims)}") counts = self._write_quarantine("latents", records) if not rows: raise RuntimeError(f"latents kept no segment of {len(segs)}; quarantined: {counts}") _write_jsonl(self.root / "latents" / "manifest.jsonl", rows) return self._finish( "latents", input_sha, { "input": len(segs), "kept": len(rows), "latent_dim": dims.pop(), "frame_hop_ms": hops.pop(), "quarantined": counts, }, )
# --------------------------------------------------------------------- ctc
def _stage_ctc(self) -> dict[str, object]: """CTC emissions (``ctc_emissions`` worker) of the segments that have latents.""" segs = self._segs("latents") input_sha = _file_sha1(self.root / "latents" / "manifest.jsonl") reused = self._reuse("ctc", input_sha) if reused is not None: return reused results = self._run_model(CTC_KEY, segs) rows: list[dict[str, object]] = [] records: list[QuarantineRecord] = [] for seg in segs: result = results.get(seg.sid) if result is None: raise RuntimeError(f"{CTC_KEY}: no result for {seg.sid}") if result.output is None: records.append(self._drop("ctc", seg.item, "ctc_failed", error=result.error)) else: rows.append({"segment_id": seg.sid}) counts = self._write_quarantine("ctc", records) if not rows: raise RuntimeError(f"ctc kept no segment of {len(segs)}; quarantined: {counts}") _write_jsonl(self.root / "ctc" / "manifest.jsonl", rows) return self._finish( "ctc", input_sha, {"input": len(segs), "kept": len(rows), "quarantined": counts} )
# ----------------------------------------------------------------- timings
def _stage_timings(self) -> dict[str, object]: """Unit timeline of every segment (CTC forced alignment of the transcript), as the pilot's ``timings`` stage does, with no event tags (``tags_json`` is ``[]``).""" segs = self._segs("ctc") input_sha = _file_sha1(self.root / "ctc" / "manifest.jsonl") reused = self._reuse("timings", input_sha) if reused is not None: return reused # The request set of the ctc stage (not just the survivors), so no result is pruned. results = self._run_model(CTC_KEY, self._segs("latents")) built: list[SegmentTimings] = [] records: list[QuarantineRecord] = [] clamped = 0 scores: list[float] = [] for number, seg in enumerate(segs, start=1): output = results[seg.sid].output if output is None: raise RuntimeError(f"{CTC_KEY}: result of {seg.sid} failed after the ctc stage") outcome = self._timeline(seg, output) if outcome.timings is not None: built.append(outcome.timings) clamped += outcome.clamped_units scores.append(outcome.mean_align_score) else: assert outcome.quarantine is not None records.append(outcome.quarantine) if number % PROGRESS_EVERY == 0: log.info("timings: %d/%d", number, len(segs)) counts = self._write_quarantine("timings", records) if not built: raise RuntimeError(f"timings built no timeline of {len(segs)}; quarantined: {counts}") write_timings(self.root / "timings" / "timings.jsonl", built) return self._finish( "timings", input_sha, { "input": len(segs), "written": len(built), "units": sum(len(t.units) for t in built), "zero_length_units": sum(t.zero_length_units for t in built), "clamped_units": clamped, "mean_align_score": round(math.fsum(scores) / len(scores), 4), "min_segment_align_score": round(min(scores), 4), "quarantined": counts, }, )
def _timeline(self, seg: _Seg, ctc: Mapping[str, object]) -> _TimelineOutcome: """Align the transcript, check the alignment, build the timeline (or say why not).""" n_tokens = len(encode_text(seg.item.text)) if n_tokens > seg.num_frames: record = self._drop( "timings", seg.item, "text_longer_than_frames", tokens=n_tokens, frames=seg.num_frames, ) return _TimelineOutcome(None, record) vocab_list = [str(t) for t in ctc["vocab"]] # type: ignore[attr-defined] vocab = {token: index for index, token in enumerate(vocab_list)} emissions = np.load(str(ctc["out_path"]), allow_pickle=False) try: aligned = align_words( seg.item.text.split(), emissions, vocab, blank_token=vocab_list[int(str(ctc["blank_id"]))], word_delimiter="|", frame_hop_ms=float(str(ctc["frame_hop_ms"])), duration_ms=seg.duration_ms, ) except ValueError as err: record = self._drop("timings", seg.item, "timings_align_error", error=str(err)) return _TimelineOutcome(None, record) if aligned.words is None: assert aligned.failure is not None reason = "timings_align_" + aligned.failure.split(":", 1)[0] record = self._drop( "timings", seg.item, reason, failure=aligned.failure, **dict(aligned.details) ) return _TimelineOutcome(None, record) scores = [w.align_score for w in aligned.words if w.align_score is not None] mean_score = math.fsum(scores) / len(scores) if scores else 0.0 problem = check_alignment(aligned.words, seg.duration_ms, self.cfg.alignment) if problem is not None: record = self._drop( "timings", seg.item, problem, mean_align_score=round(mean_score, 4), min_align_score=self.cfg.alignment.min_align_score, ) return _TimelineOutcome(None, record) built = build_timings( seg.sid, seg.item.text, json.dumps([]), aligned.words, num_frames=seg.num_frames, frame_hop_ms=seg.frame_hop_ms, ) if built.timings is None: assert built.quarantine is not None q = built.quarantine record = self._drop("timings", seg.item, q.reason, **q.details) return _TimelineOutcome(None, record) return _TimelineOutcome(built.timings, None, built.clamped_units, mean_score)
# ----------------------------------------------------------------- dataset
def _stage_dataset(self) -> dict[str, object]: """Write the latent dataset directory (format: :mod:`nida.train.data`) + timings.jsonl.""" cfg = self.cfg dataset_dir = self.dataset_dir() meta_path = dataset_dir / "meta.json" timings_path = self.root / "timings" / "timings.jsonl" self._require_done("timings") timings_sha = _file_sha1(timings_path) if meta_path.is_file(): meta = json.loads(meta_path.read_text(encoding="utf-8")) if meta.get("timings_sha1") != timings_sha: raise RuntimeError( f"{meta_path} was built from other timings; move {dataset_dir} away" ) return {"dataset": str(dataset_dir), "segments": meta["segments"], "reused": True} timelines = { t.segment_id: t for t in ( SegmentTimings.from_obj(row, f"{timings_path}:{n}") for n, row in enumerate(_read_jsonl(timings_path), 1) ) } segs = [s for s in self._segs("ctc") if s.sid in timelines] if len(segs) != len(timelines): raise RuntimeError("timings.jsonl names segments that did not survive the stages") splits = assign_group_splits({s.sid: s.item.group for s in segs}, cfg) forced = cfg.forced_split(self.plan.source) if forced is not None: # no group of this source can be pure: all rows are one split splits = {sid: forced for sid in splits} # The request set of the latents stage; recomputes arrays lost with the cache. latents = self._run_model(VAE_KEY, self._segs("audio")) index: list[dict[str, object]] = [] shard: list[np.ndarray[Any, np.dtype[np.float16]]] = [] shard_frames = 0 shard_no = 0 latent_dim: int | None = None frame_hop_ms: float | None = None
def flush() -> None: nonlocal shard, shard_frames, shard_no if not shard: return buffer = io.BytesIO() np.save(buffer, np.concatenate(shard), allow_pickle=False) atomic_write_bytes(dataset_dir / f"shard-{shard_no:05d}.npy", buffer.getvalue()) shard, shard_frames, shard_no = [], 0, shard_no + 1
for seg in sorted(segs, key=lambda s: s.sid): output = latents[seg.sid].output if output is None: raise RuntimeError(f"{VAE_KEY}: result of {seg.sid} failed after the latents stage") array = np.load(str(output["out_path"]), allow_pickle=False) if _latent_problem(array) is not None or int(array.shape[0]) != seg.num_frames: raise RuntimeError(f"{seg.sid}: cached latents differ from the latents stage") latent_dim, frame_hop_ms = seg.latent_dim, seg.frame_hop_ms index.append( { "segment_id": seg.sid, "shard": f"shard-{shard_no:05d}.npy", "offset": shard_frames, "num_frames": seg.num_frames, "text": seg.item.text, "emotion": seg.item.emotion, "intensity": None, "rate_bucket": bucket_of( rate_chars_per_s(seg.item.text, seg.duration_ms), cfg.dataset.rate_bucket_edges_chars_per_s, ), "loudness_bucket": bucket_of( seg.loudness_dbfs, cfg.dataset.loudness_bucket_edges_dbfs ), "group": seg.item.group, "split": splits[seg.sid], "language": LANGUAGE, } ) shard.append(array.astype(np.float16)) shard_frames += seg.num_frames if shard_frames >= DATASET_SHARD_FRAMES: flush() flush() _write_jsonl(dataset_dir / "index.jsonl", index) write_timings(dataset_dir / "timings.jsonl", [timelines[s.sid] for s in segs]) new_meta: dict[str, object] = { "segments": len(index), "frames": sum(int(str(i["num_frames"])) for i in index), "latent_dim": latent_dim, "frame_hop_ms": frame_hop_ms, "rate_bucket_edges_chars_per_s": list(cfg.dataset.rate_bucket_edges_chars_per_s), "loudness_bucket_edges_dbfs": list(cfg.dataset.loudness_bucket_edges_dbfs), "language": LANGUAGE, "source": self.plan.source, "source_ids": sorted({s.item.source_id for s in segs}), "plan": self.plan.to_obj(), "config_digest": cfg.digest, "seed": cfg.seed, "timings_sha1": timings_sha, "vae": [DATA_MODELS[VAE_KEY].ref.model_id, DATA_MODELS[VAE_KEY].ref.revision], "ctc": [DATA_MODELS[CTC_KEY].ref.model_id, DATA_MODELS[CTC_KEY].ref.revision], "splits": dict(sorted(Counter(splits.values()).items())), } if forced is not None: new_meta["forced_split"] = forced atomic_write_json(meta_path, new_meta) # written last: its presence marks the stage done try: self._check_with_loader(dataset_dir) except (DataFormatError, RuntimeError): meta_path.unlink(missing_ok=True) raise return { "dataset": str(dataset_dir), "segments": len(index), "frames": new_meta["frames"], "splits": new_meta["splits"], "reused": False, }
@staticmethod def _check_with_loader(dataset_dir: Path) -> None: """Every split must load with timelines and no rejection (else the importer is wrong).""" for split in SPLITS: dataset, report = load_latent_dataset(dataset_dir, split, timings=True) dataset.close() if report.num_rejected: raise RuntimeError( f"nida.train.data rejects records of the imported {split} split: " f"{report.rejection_counts}" )
# ------------------------------------------------------------------ report
def _stage_report(self) -> dict[str, object]: """``report.md`` and ``metrics.json`` of the root; returns the metrics.""" dataset_dir = self.dataset_dir() meta_path = dataset_dir / "meta.json" if not meta_path.is_file(): raise RuntimeError(f"{meta_path} is missing: run the dataset stage first") meta = json.loads(meta_path.read_text(encoding="utf-8")) index = _read_jsonl(dataset_dir / "index.jsonl") kept_ids = {str(r["segment_id"]) for r in index} segs = {s.sid: s for s in self._segs("ctc") if s.sid in kept_ids} selected = self._select_items() selected_ms = sum(i.raw_duration_ms or 0 for i in selected) quarantine = { stage: QuarantineLog(self.root / stage).counts_by_reason() for stage in ("select", "audio", "latents", "ctc", "timings") if (self.root / stage).is_dir() } splits: dict[str, dict[str, object]] = {} for split in SPLITS: members = [segs[str(r["segment_id"])] for r in index if r["split"] == split] splits[split] = { "segments": len(members), "hours": _hours(sum(s.duration_ms for s in members)), "groups": len({s.item.group for s in members}), } emotions = Counter("null" if r["emotion"] is None else str(r["emotion"]) for r in index) unmapped = Counter( str(s.item.extra.get("emotion_label")) for s in segs.values() if s.item.emotion is None and s.item.extra.get("emotion_label") is not None ) timings_result = json.loads(self._marker("timings").read_text(encoding="utf-8"))["result"] metrics: dict[str, object] = { "alignment": { key: timings_result[key] for key in ("mean_align_score", "min_segment_align_score") }, "source": self.plan.source, "source_ids": meta["source_ids"], "revision": self.plan.revision, "config_digest": self.cfg.digest, "max_hours": self.plan.max_hours, "units_planned": len(self.plan.unit_ids), "selected": {"segments": len(selected), "hours": _hours(selected_ms)}, "kept": { "segments": len(index), "hours": _hours(sum(s.duration_ms for s in segs.values())), }, "quarantine": quarantine, "emotions": dict(sorted(emotions.items())), "unmapped_emotion_labels": dict(sorted(unmapped.items())), "groups": len({s.item.group for s in segs.values()}), "splits": splits, "dataset": str(dataset_dir), } atomic_write_json(self.root / "metrics.json", metrics) atomic_write_text(self.root / "report.md", _render_report(metrics)) return metrics
def assign_group_splits(groups: Mapping[str, str], cfg: ImportConfig) -> dict[str, str]: """Group-disjoint, deterministic ``train``/``val``/``test`` split of ``{segment_id: group}``.
The split of a group is a pure function of ``(cfg.seed, group)`` (:func:`nida.data.splits.assign_splits`; ``val_fraction`` / ``test_fraction`` of the groups), independent of which other groups the root holds: the same group lands in the same split in every root, so datasets of different roots can be merged without a group crossing splits. A root with a single group is therefore wholly one split, not necessarily ``train``. """ return assign_splits(groups, cfg.split_fractions, str(cfg.seed))
def _with_duration(item: Item, duration_ms: int) -> Item: return Item( source_id=item.source_id, item_id=item.item_id, segment_id=item.segment_id, unit_id=item.unit_id, text=item.text, group=item.group, emotion=item.emotion, raw_duration_ms=duration_ms, extra=item.extra, )
def _latent_problem(array: np.ndarray[Any, Any]) -> tuple[str, dict[str, object]] | None: """A reason (and details) why latents cannot go into a float16 shard, else ``None``.""" if array.ndim != 2 or array.shape[0] < 1 or array.shape[1] < 1: return "latents_bad_shape", {"shape": list(array.shape)} if not np.all(np.isfinite(array)) or float(np.max(np.abs(array))) > FLOAT16_MAX_ABS: return "latents_not_float16", {} return None
def _render_report(m: Mapping[str, object]) -> str: selected, kept = m["selected"], m["kept"] assert isinstance(selected, dict) and isinstance(kept, dict) assert isinstance(m["splits"], dict) and isinstance(m["quarantine"], dict) lines = [ f"# data-import: {m['source']}", "", f"- source ids: {m['source_ids']}", f"- revision: `{m['revision']}`", f"- config digest: `{m['config_digest']}`", f"- max hours: {m['max_hours']}; work units planned: {m['units_planned']}", f"- selected: {selected['segments']} segments, {selected['hours']} h", f"- kept (in the dataset): {kept['segments']} segments, {kept['hours']} h", f"- groups: {m['groups']}", f"- alignment (timings): {json.dumps(m['alignment'])}", f"- dataset: `{m['dataset']}`", "", "## Splits", "", *(f"- {name}: {json.dumps(info)}" for name, info in m["splits"].items()), "", "## Emotions", "", f"- {json.dumps(m['emotions'], ensure_ascii=False)}", f"- unmapped source labels (-> null): {json.dumps(m['unmapped_emotion_labels'])}", "", "## Quarantine by stage and reason", "", *( f"- {stage}: {json.dumps(counts, ensure_ascii=False)}" for stage, counts in m["quarantine"].items() ), ] return "\n".join(lines) + "\n"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776"""Source adapters of the importer: which corpus items exist, which are selected, where theraw audio is.
An adapter splits its corpus into *work units* (a parquet shard, a chunk of manifest rows) in adeterministic order and, per unit, yields the selected :class:`Item` objects (metadata filtersand transcript normalisation applied, raw audio placed in the local cache) and a:class:`~nida.data.types.QuarantineRecord` for every row it drops, with a machine-readablereason. It does not look at audio samples; the stages do.
* :class:`AlaniaAdapter` - HF parquet shards (``alania_synth_tr``), filtered by the QC columns.* :class:`TrFullAdapter` - HF ``data.jsonl`` + wavs (``tr_full_dataset``).* :class:`WavdirAdapter` - a folder with ``manifest.jsonl`` (our own synthetic speech).
The archive and Common Voice corpora (``issai_tsc``, ``mediaspeech_tr``, ``common_voice_tr``)are in :mod:`nida.data.importer.corpora`; :func:`make_adapter` builds all six.
Item ids: ``segment_id = sha1(source_id U+001F item_id)[:16]`` (:func:`item_segment_id`);quarantine records use the segment id as ``item_id`` and keep the source's own id in``details["item_id"]``."""
from __future__ import annotations
import fnmatchimport hashlibimport jsonimport mathimport refrom collections.abc import Generator, Mapping, Setfrom dataclasses import dataclass, fieldfrom pathlib import Path, PurePosixPathfrom typing import TYPE_CHECKING, Protocolfrom urllib.parse import unquote
from nida.bench import fetchfrom nida.data.importer.config import CORPUS_SOURCES, LEGACY_SOURCES, ImportConfigfrom nida.data.importer.hub import HubClient, HubErrorfrom nida.data.importer.text import ( DETAIL_TEXT_CHARS, TextRejected, map_emotion, normalise_transcript,)from nida.data.types import QuarantineRecordfrom nida.text.turkish import nfcfrom nida.utils.io import atomic_write_bytes
if TYPE_CHECKING: import pyarrow as pa # type: ignore[import-untyped] # no stubs
__all__ = [ "ALANIA_SOURCE_ID", "HUB_SOURCES", "LOCAL_SOURCES", "STAGE", "TR_FULL_SOURCE_ID", "AlaniaAdapter", "Item", "SourceAdapter", "TrFullAdapter", "UnitListing", "WavdirAdapter", "item_segment_id", "make_adapter", "safe_relative_path",]
STAGE = "select"ALANIA_SOURCE_ID = "alania_synth_tr"TR_FULL_SOURCE_ID = "tr_full_dataset"SOURCES = (*LEGACY_SOURCES, *CORPUS_SOURCES)#: Sources read from a Hugging Face dataset repository (they need a ``HubClient``).HUB_SOURCES = ("alania", "tr_full", "issai_tsc")#: Sources read from a local folder or tarball given as ``--source-dir`` (no Hub revision;#: ``plan.json`` pins the sha1 of their manifest / validated file).LOCAL_SOURCES = ("wavdir", "common_voice_tr")
#: Parquet columns the alania adapter reads.ALANIA_COLUMNS = ( "id", "audio", "text_spoken", "duration", "voice_id", "gender", "channel_preset", "qc_cer", "qc_utmos", "license",)_CHUNK_RE = re.compile(r"chunk-(\d{5})")_DRIVE_RE = re.compile(r"[A-Za-z]:")
Scalar = str | int | float | None
def item_segment_id(source_id: str, item_id: str) -> str: """Content-addressed id of an item: ``sha1(nfc(source_id) U+001F nfc(item_id))[:16]``.
Raises: ValueError: an empty id, or one containing U+001F (the separator). """ source_id, item_id = nfc(source_id), nfc(item_id) for name, value in (("source_id", source_id), ("item_id", item_id)): if not value or "\x1f" in value: raise ValueError(f"invalid {name} {value!r}") return hashlib.sha1(f"{source_id}\x1f{item_id}".encode()).hexdigest()[:16]
def safe_relative_path(value: object) -> str | None: """``value`` if it is a plain relative ``/``-separated path inside a folder, else ``None`` (not a string, empty, absolute, drive letter, backslash, ``..`` component).""" if not isinstance(value, str) or not value or "\\" in value or "\x00" in value: return None path = PurePosixPath(value) if path.is_absolute() or _DRIVE_RE.match(value) or ".." in path.parts: return None return nfc(value)
_HUB_RESOLVE_RE = re.compile(r"^https://huggingface\.co/datasets/[^/]+/[^/]+/resolve/[^/]+/(.+)$")
def hub_url_to_path(value: object) -> object: """A Hub ``.../datasets/<owner>/<name>/resolve/<rev>/<path>`` URL -> ``<path>`` (URL-decoded); anything else is returned unchanged.
tr_full's ``data.jsonl`` names its audio by full resolve URLs of the dataset it was copied from (Codyfederer/tr-full-dataset); the same relative paths exist in the pinned repository, so only the path part is used. """ if isinstance(value, str): match = _HUB_RESOLVE_RE.match(value) if match: return unquote(match.group(1)) return value
@dataclass(frozen=True)class Item: """One selected corpus item (a line of ``select/manifest.jsonl``).
Attributes: source_id: ``configs/sources.yaml`` id of the item's source. item_id: The source's own id (alania ``id``, tr_full wav path, wavdir ``file``). segment_id: :func:`item_segment_id` of the two. unit_id: Work unit the item came from (needed to fetch its raw audio again). text: Model text (:func:`~nida.data.importer.text.normalise_transcript`). group: Split group (speaker / voice), prefixed per source in the config. emotion: Emotion id or ``None``. raw_duration_ms: Duration of the raw audio from its header; ``None`` until the select stage has measured it. extra: JSON scalars worth keeping (QC scores, raw emotion label, ...). """
source_id: str item_id: str segment_id: str unit_id: str text: str group: str emotion: str | None raw_duration_ms: int | None = None extra: Mapping[str, Scalar] = field(default_factory=dict)
def to_obj(self) -> dict[str, object]: return { "source_id": self.source_id, "item_id": self.item_id, "segment_id": self.segment_id, "unit_id": self.unit_id, "text": self.text, "group": self.group, "emotion": self.emotion, "raw_duration_ms": self.raw_duration_ms, "extra": dict(self.extra), }
@classmethod def from_obj(cls, obj: object, where: str) -> Item: """Inverse of :meth:`to_obj`.
Raises: ValueError: on a missing/extra key or a wrong type (the message names ``where``). """ keys = { "source_id", "item_id", "segment_id", "unit_id", "text", "group", "emotion", "raw_duration_ms", "extra", } if not isinstance(obj, dict) or set(obj) != keys: raise ValueError(f"{where}: an item needs exactly the keys {sorted(keys)}") for key in ("source_id", "item_id", "segment_id", "unit_id", "text", "group"): if not isinstance(obj[key], str) or not obj[key]: raise ValueError(f"{where}: {key} must be a non-empty string") emotion, duration, extra = obj["emotion"], obj["raw_duration_ms"], obj["extra"] if emotion is not None and not isinstance(emotion, str): raise ValueError(f"{where}: emotion must be a string or null") if duration is not None and (isinstance(duration, bool) or not isinstance(duration, int)): raise ValueError(f"{where}: raw_duration_ms must be an int or null") if not isinstance(extra, dict) or not all( isinstance(k, str) and (v is None or isinstance(v, str | int | float)) for k, v in extra.items() ): raise ValueError(f"{where}: extra must map strings to JSON scalars") return cls( source_id=obj["source_id"], item_id=obj["item_id"], segment_id=obj["segment_id"], unit_id=obj["unit_id"], text=obj["text"], group=obj["group"], emotion=emotion, raw_duration_ms=duration, extra=extra, )
@dataclass(frozen=True)class UnitListing: """All work units of a corpus at one pinned state.
Attributes: revision: Pinned commit sha (Hub sources) or ``None`` (wavdir). unit_ids: Every unit id in processing order. content_sha1: sha1 of the wavdir ``manifest.jsonl`` (``None`` for Hub sources). """
revision: str | None unit_ids: tuple[str, ...] content_sha1: str | None = None
class SourceAdapter(Protocol): """What the select stage needs from a corpus (see the module docstring)."""
#: ``True`` if the raw audio is a cache copy the audio stage may delete after conversion. ephemeral_raw: bool
@property def source_ids(self) -> frozenset[str]: """``sources.yaml`` ids this run reads (must all be ``approved``).""" ...
def list_units(self) -> UnitListing: """Pin the corpus state (network access for Hub sources) and list its units.""" ...
def iter_unit( self, unit_id: str, only: Set[str] | None = None, exclude: Mapping[str, str] | None = None, ) -> Generator[Item | QuarantineRecord, None, None]: """Selected items and dropped rows of one unit; raw audio is placed in the cache before an item is yielded. With ``only`` (segment ids) just those items are yielded again (to restore lost raw audio); everything else is skipped without a record.
``exclude`` maps the segment ids selected by earlier units to their unit id. A row whose segment id is in it, or was already yielded by this unit, is quarantined as ``duplicate_item`` *before* any raw audio is written, so the first item's audio is never overwritten.""" ...
def raw_path(self, item: Item) -> Path: """Where the raw audio of ``item`` is (or will be put by :meth:`iter_unit`).""" ...
def _drop(segment_id: str, item_id: str, reason: str, **details: object) -> QuarantineRecord: return QuarantineRecord(segment_id, STAGE, reason, {"item_id": item_id, **details})
def _bad_row( unit_id: str, position: int, raw: str, reason: str, **details: object) -> QuarantineRecord: """Quarantine record of a row that has no usable id: the key is derived from the unit id and the row's position in the (pinned, immutable) unit.""" key = hashlib.sha1(f"{unit_id}\x1f{position}".encode()).hexdigest()[:16] return _drop(key, f"{unit_id}#{position}", reason, row=raw[:DETAIL_TEXT_CHARS], **details)
def _first_seen( first: dict[str, str], sid: str, item_id: str, unit_id: str) -> QuarantineRecord | None: """Record ``sid`` as selected by ``unit_id``, or return the ``duplicate_item`` record if an earlier row (of this or an earlier unit) already claimed it.""" earlier = first.get(sid) if earlier is not None: return _drop(sid, item_id, "duplicate_item", unit_id=unit_id, first_unit_id=earlier) first[sid] = unit_id return None
def _finite(value: object) -> float | None: """``value`` as a finite float, else ``None`` (missing, non-numeric, NaN, inf).""" if isinstance(value, bool) or not isinstance(value, int | float): return None return float(value) if math.isfinite(value) else None
def _text_drop(segment_id: str, item_id: str, err: TextRejected) -> QuarantineRecord: return _drop(segment_id, item_id, err.reason, **err.details)
# ------------------------------------------------------------------------------ alania
class AlaniaAdapter: """``cloud0day3/alania-synthetic-speech-tr``, config ``cc-by`` only (parquet shards).
Units are the parquet files matching ``alania.parquet_glob``, sorted by name; rows are read in file order. One shard at a time is downloaded, the raw FLAC bytes of the selected rows are written to ``<cache>/raw/alania/<segment_id>.flac`` and the parquet file is deleted when the unit is finished or abandoned. """
ephemeral_raw = True
def __init__( self, cfg: ImportConfig, cache: Path, hub: HubClient, revision: str | None ) -> None: self._cfg = cfg self._cache = cache self._hub = hub self.revision = revision
@property def source_ids(self) -> frozenset[str]: return frozenset({ALANIA_SOURCE_ID})
def list_units(self) -> UnitListing: repo = self._cfg.alania.repo_id if self.revision is None: self.revision = self._hub.resolve_revision(repo) files = self._hub.list_files(repo, self.revision) units = sorted(f for f in files if fnmatch.fnmatchcase(f, self._cfg.alania.parquet_glob)) if not units: raise HubError( f"{repo}@{self.revision}: no file matches {self._cfg.alania.parquet_glob!r}; " f"first files: {sorted(files)[:5]}" ) return UnitListing(self.revision, tuple(units))
def raw_path(self, item: Item) -> Path: return self._cache / "raw" / "alania" / f"{item.segment_id}.flac"
def iter_unit( self, unit_id: str, only: Set[str] | None = None, exclude: Mapping[str, str] | None = None, ) -> Generator[Item | QuarantineRecord, None, None]: import pyarrow.parquet as pq # type: ignore[import-untyped] # no stubs
if self.revision is None: raise HubError("alania: the revision is not pinned; call list_units() first") path = self._hub.download( self._cfg.alania.repo_id, self.revision, unit_id, self._cache / "hub" / "alania" ) try: with pq.ParquetFile(path) as shard: missing = [c for c in ALANIA_COLUMNS if c not in shard.schema_arrow.names] if missing: raise ValueError(f"{unit_id}: parquet columns missing: {missing}") position = 0 first = dict(exclude or {}) for batch in shard.iter_batches( batch_size=self._cfg.alania.batch_rows, columns=list(ALANIA_COLUMNS) ): for row in _rows(batch): event = self._row(unit_id, position, row, only, first) position += 1 if event is not None: yield event finally: path.unlink(missing_ok=True)
def _row( self, unit_id: str, position: int, row: Mapping[str, object], only: Set[str] | None, first: dict[str, str], ) -> Item | QuarantineRecord | None: cfg = self._cfg alania = cfg.alania item_id = row["id"] if not isinstance(item_id, str) or not item_id.strip() or "\x1f" in item_id: return _bad_row(unit_id, position, repr(item_id), "bad_row", problem="id") sid = item_segment_id(ALANIA_SOURCE_ID, item_id) if only is not None and sid not in only: return None license_ = row["license"] if not isinstance(license_, str) or not license_.startswith(alania.license_prefix): return _drop(sid, item_id, "license", license=license_) utmos, cer = _finite(row["qc_utmos"]), _finite(row["qc_cer"]) if utmos is None or cer is None: return _drop(sid, item_id, "missing_qc", qc_utmos=utmos, qc_cer=cer) if utmos < alania.min_utmos: return _drop(sid, item_id, "low_utmos", qc_utmos=utmos) if cer > alania.max_cer: return _drop(sid, item_id, "high_cer", qc_cer=cer) seconds = _finite(row["duration"]) if seconds is None: return _drop(sid, item_id, "bad_duration", duration=repr(row["duration"])) if seconds * 1000 < cfg.min_duration_ms: return _drop(sid, item_id, "too_short", duration_s=seconds) if seconds * 1000 > cfg.max_duration_ms: return _drop(sid, item_id, "too_long", duration_s=seconds) voice = row["voice_id"] if not isinstance(voice, str | int) or isinstance(voice, bool) or not str(voice).strip(): return _drop(sid, item_id, "no_group", voice_id=repr(voice)) spoken = row["text_spoken"] try: text = normalise_transcript(spoken if isinstance(spoken, str) else "", cfg.char_map) except TextRejected as err: return _text_drop(sid, item_id, err) audio = row["audio"] data = audio.get("bytes") if isinstance(audio, dict) else None if not isinstance(data, bytes) or not data: return _drop(sid, item_id, "audio_missing") item = Item( source_id=ALANIA_SOURCE_ID, item_id=item_id, segment_id=sid, unit_id=unit_id, text=text, group=nfc(alania.group_prefix + str(voice).strip()), emotion=None, extra={ "voice_id": str(voice), "gender": _scalar(row["gender"]), "channel_preset": _scalar(row["channel_preset"]), "qc_utmos": utmos, "qc_cer": cer, }, ) duplicate = _first_seen(first, sid, item_id, unit_id) if duplicate is not None: return duplicate atomic_write_bytes(self.raw_path(item), data) return item
def _scalar(value: object) -> Scalar: """``value`` if it is a JSON scalar, else its ``str`` (QC metadata only).""" if value is None or (isinstance(value, str | int | float) and not isinstance(value, bool)): return value return str(value)
def _rows(batch: pa.RecordBatch) -> list[dict[str, object]]: rows: list[dict[str, object]] = batch.to_pylist() return rows
# ------------------------------------------------------------------------------ chunks
def _chunk_ids(num_rows: int, unit_rows: int) -> tuple[str, ...]: count = -(-num_rows // unit_rows) return tuple(f"chunk-{k:05d}" for k in range(count))
def _chunk_slice(unit_id: str, unit_rows: int) -> slice: match = _CHUNK_RE.fullmatch(unit_id) if match is None: raise ValueError(f"not a chunk unit id: {unit_id!r}") start = int(match.group(1)) * unit_rows return slice(start, start + unit_rows)
def _json_lines(path: Path) -> list[str]: """Non-empty lines of a JSONL file (split on ``\\n`` only: U+2028 stays inside strings).""" return [line for line in path.read_text(encoding="utf-8").split("\n") if line.strip()]
def _parse_object(line: str) -> dict[str, object] | None: try: obj = json.loads(line) except json.JSONDecodeError: return None return obj if isinstance(obj, dict) else None
# ------------------------------------------------------------------------------ tr_full
class TrFullAdapter: """``Taklaxbr/tr-full-dataset``: ``data.jsonl`` rows and the wavs they name.
Units are chunks of ``tr_full.unit_rows`` rows in file order. A row whose ``language`` is not ``tr_full.language`` is quarantined (``language``) before its wav is fetched; the wavs of the remaining rows of a unit are downloaded one by one (threaded) into ``<cache>/raw/tr_full/``. """
ephemeral_raw = True
def __init__( self, cfg: ImportConfig, cache: Path, hub: HubClient, revision: str | None ) -> None: self._cfg = cfg self._cache = cache self._hub = hub self.revision = revision self._lines_cache: list[str] | None = None
@property def source_ids(self) -> frozenset[str]: return frozenset({TR_FULL_SOURCE_ID})
def _data_lines(self) -> list[str]: """The non-empty lines of ``data.jsonl`` (downloaded and read once per adapter).""" if self._lines_cache is None: path = self._hub.download( self._cfg.tr_full.repo_id, self._revision(), self._cfg.tr_full.data_file, self._cache / "hub" / "tr_full", ) self._lines_cache = _json_lines(path) return self._lines_cache
def list_units(self) -> UnitListing: if self.revision is None: self.revision = self._hub.resolve_revision(self._cfg.tr_full.repo_id) lines = self._data_lines() return UnitListing(self.revision, _chunk_ids(len(lines), self._cfg.tr_full.unit_rows))
def raw_path(self, item: Item) -> Path: return self._cache / "raw" / "tr_full" / item.item_id
def iter_unit( self, unit_id: str, only: Set[str] | None = None, exclude: Mapping[str, str] | None = None, ) -> Generator[Item | QuarantineRecord, None, None]: cfg = self._cfg window = _chunk_slice(unit_id, cfg.tr_full.unit_rows) lines = self._data_lines()[window] base = window.start candidates: list[Item] = [] first = dict(exclude or {}) for offset, line in enumerate(lines): position = base + offset row = _parse_object(line) if row is None: yield _bad_row(unit_id, position, line, "bad_row", problem="not a JSON object") continue made = self._row(unit_id, position, line, row, only, first) if isinstance(made, QuarantineRecord): yield made elif made is not None: candidates.append(made) wanted = [c.item_id for c in candidates if not self.raw_path(c).is_file()] self._hub.download_many( cfg.tr_full.repo_id, self._revision(), wanted, self._cache / "raw" / "tr_full", ) for item in candidates: if self.raw_path(item).is_file(): yield item else: yield _drop(item.segment_id, item.item_id, "audio_missing")
def _revision(self) -> str: if self.revision is None: raise HubError("tr_full: the revision is not pinned; call list_units() first") return self.revision
def _row( self, unit_id: str, position: int, line: str, row: Mapping[str, object], only: Set[str] | None, first: dict[str, str], ) -> Item | QuarantineRecord | None: cfg = self._cfg rel = safe_relative_path(hub_url_to_path(row.get("audio"))) if rel is None: return _bad_row(unit_id, position, line, "bad_row", problem="audio path") sid = item_segment_id(TR_FULL_SOURCE_ID, rel) if only is not None and sid not in only: return None language = row.get("language") if not isinstance(language, str) or language.strip() != cfg.tr_full.language: return _drop(sid, rel, "language", language=language) speaker, text_raw = row.get("speaker_id"), row.get("text") if ( not isinstance(speaker, str | int) or isinstance(speaker, bool) or not str(speaker).strip() ): return _drop(sid, rel, "no_group", speaker_id=repr(speaker)) try: text = normalise_transcript(text_raw if isinstance(text_raw, str) else "", cfg.char_map) except TextRejected as err: return _text_drop(sid, rel, err) label = row.get("emotion") emotion = map_emotion(label, cfg.emotion_map) duplicate = _first_seen(first, sid, rel, unit_id) if duplicate is not None: return duplicate return Item( source_id=TR_FULL_SOURCE_ID, item_id=rel, segment_id=sid, unit_id=unit_id, text=text, group=nfc(cfg.tr_full.group_prefix + str(speaker).strip()), emotion=emotion, extra={"speaker_id": str(speaker), "emotion_label": _scalar(label)}, )
# ------------------------------------------------------------------------------ wavdir
class WavdirAdapter: """A folder with ``manifest.jsonl`` ``{file, text, group, source, emotion?}`` lines.
``file`` is relative to the folder; ``source`` is the ``sources.yaml`` id of whatever produced the audio (it must be ``approved``; :attr:`source_ids` lists every one named in the manifest). Units are chunks of ``wavdir.unit_rows`` lines. The wavs stay where they are: they are read in place and never deleted. """
ephemeral_raw = False
def __init__(self, cfg: ImportConfig, folder: Path) -> None: self._cfg = cfg self._folder = folder self._manifest = folder / "manifest.jsonl" self._lines_cache: list[str] | None = None
def _lines(self) -> list[str]: if self._lines_cache is None: if not self._manifest.is_file(): raise FileNotFoundError(f"{self._manifest} does not exist") self._lines_cache = _json_lines(self._manifest) return self._lines_cache
@property def source_ids(self) -> frozenset[str]: found: set[str] = set() for line in self._lines(): row = _parse_object(line) source = row.get("source") if row is not None else None if isinstance(source, str) and source.strip(): found.add(source.strip()) return frozenset(found)
def list_units(self) -> UnitListing: digest = hashlib.sha1(self._manifest.read_bytes()).hexdigest() return UnitListing(None, _chunk_ids(len(self._lines()), self._cfg.wavdir.unit_rows), digest)
def raw_path(self, item: Item) -> Path: return self._folder / item.item_id
def iter_unit( self, unit_id: str, only: Set[str] | None = None, exclude: Mapping[str, str] | None = None, ) -> Generator[Item | QuarantineRecord, None, None]: window = _chunk_slice(unit_id, self._cfg.wavdir.unit_rows) first = dict(exclude or {}) for offset, line in enumerate(self._lines()[window]): event = self._row(unit_id, window.start + offset, line, only, first) if event is not None: yield event
def _row( self, unit_id: str, position: int, line: str, only: Set[str] | None, first: dict[str, str], ) -> Item | QuarantineRecord | None: cfg = self._cfg row = _parse_object(line) if row is None: return _bad_row(unit_id, position, line, "bad_row", problem="not a JSON object") rel = safe_relative_path(row.get("file")) source, group, text_raw = row.get("source"), row.get("group"), row.get("text") if rel is None or not isinstance(source, str) or not source.strip() or "\x1f" in source: return _bad_row(unit_id, position, line, "bad_row", problem="file or source") source = source.strip() sid = item_segment_id(source, rel) if only is not None and sid not in only: return None if not isinstance(group, str) or not group.strip(): return _drop(sid, rel, "no_group") try: text = normalise_transcript(text_raw if isinstance(text_raw, str) else "", cfg.char_map) except TextRejected as err: return _text_drop(sid, rel, err) if not (self._folder / rel).is_file(): return _drop(sid, rel, "audio_missing") duplicate = _first_seen(first, sid, rel, unit_id) if duplicate is not None: return duplicate label = row.get("emotion") return Item( source_id=source, item_id=rel, segment_id=sid, unit_id=unit_id, text=text, group=nfc(cfg.wavdir.group_prefix + group.strip()), emotion=map_emotion(label, cfg.emotion_map), extra={"emotion_label": _scalar(label)}, )
def make_adapter( source: str, cfg: ImportConfig, cache: Path, *, hub: HubClient | None, revision: str | None, wavdir: Path | None, opener: fetch.Opener | None = None,) -> SourceAdapter: """The adapter of ``source`` (one of :data:`SOURCES`).
Args: source: Importer source name. cfg: Import config (loaded for that source). cache: Local scratch directory. hub: Hub client (``alania``, ``tr_full``, ``issai_tsc``). revision: Pin: a Hub commit sha, or the sha256 of the ``mediaspeech_tr`` archive. wavdir: ``--source-dir`` (``wavdir``: its folder; ``common_voice_tr``: a Common Voice release folder or tarball). opener: HTTP access of ``mediaspeech_tr`` (default: ``urllib``); tests inject one.
Raises: ValueError: unknown source, a Hub source without a ``hub``, a local source without ``wavdir``. """ if source in HUB_SOURCES and hub is None: raise ValueError(f"source {source!r} needs a Hub client") if source in LOCAL_SOURCES and wavdir is None: raise ValueError(f"source {source!r} needs --source-dir") if source == "alania" and hub is not None: return AlaniaAdapter(cfg, cache, hub, revision) if source == "tr_full" and hub is not None: return TrFullAdapter(cfg, cache, hub, revision) if source == "wavdir" and wavdir is not None: return WavdirAdapter(cfg, wavdir) if source in CORPUS_SOURCES: from nida.data.importer import corpora # imports this module: not at module level
if source == "issai_tsc" and hub is not None: return corpora.IssaiTscAdapter(cfg, cache, hub, revision) if source == "mediaspeech_tr": return corpora.MediaSpeechAdapter(cfg, cache, opener, revision) if source == "common_voice_tr" and wavdir is not None: return corpora.CommonVoiceAdapter(cfg, cache, wavdir) raise ValueError(f"unknown source {source!r}; known: {SOURCES}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110"""Transcript and label normalisation for imported corpora.
A transcript becomes *model text*: what :func:`nida.model.vocab.encode_text` encodes and whatthe CTC aligner is given. Rules, in order:
1. NFC (:func:`nida.data.pilot.clean_asr_text`, which also undoes ``i`` + U+0307);2. ``char_map`` replacements (typographic quotes and apostrophes);3. text that contains a tag character ``[ ] < >`` is *rejected* (``tag_chars``): the characters are reserved for the tag grammar (docs/02-tag-spec.md), and stripping them would turn an annotation such as ``[laugh]`` into the spoken word "laugh". Whitespace is collapsed to single spaces;4. digits are written out with :func:`nida.text.numbers.verbalize_digits`;5. every remaining character must be in the model vocabulary.
Case is kept (the vocabulary lower-cases with ``tr_lower`` itself). Filler sounds are NOTcanonicalised (tag-spec §4: ``eee`` -> ``ee`` ...): the transcript is used as the corpuswrites it, a known deviation for imported text."""
from __future__ import annotations
from collections.abc import Mapping
from nida.data.ears import en_lowerfrom nida.data.pilot import clean_asr_textfrom nida.model.vocab import VOCAB, encode_textfrom nida.text.numbers import verbalize_digitsfrom nida.text.turkish import tr_lower
__all__ = [ "DETAIL_TEXT_CHARS", "REASON_EMPTY", "REASON_TAG_CHARS", "TAG_CHARS", "TextRejected", "map_emotion", "normalise_transcript",]
#: Characters reserved for the tag grammar; removed from raw corpus text.TAG_CHARS = "[]<>"REASON_EMPTY = "empty_text"REASON_TAG_CHARS = "tag_chars"REASON_NUMBER = "unverbalizable_number"REASON_UNTOKENIZABLE = "untokenizable"
#: Characters of a transcript / row kept as an excerpt in a quarantine record.DETAIL_TEXT_CHARS = 120
class TextRejected(ValueError): """A transcript that cannot become model text; ``reason`` is the quarantine reason."""
def __init__(self, reason: str, details: Mapping[str, object]) -> None: super().__init__(f"{reason}: {dict(details)}") self.reason = reason self.details = dict(details)
def normalise_transcript(raw: str, char_map: Mapping[str, str]) -> str: """Model text of a raw transcript (rules in the module docstring).
Args: raw: Transcript as stored in the corpus. char_map: Single-character replacements (``configs/data/import.yaml``).
Raises: TextRejected: ``tag_chars`` (``details["chars"]`` lists them); ``empty_text``; ``unverbalizable_number`` (a digit token that :func:`verbalize_digits` cannot spell); ``untokenizable`` (``details["chars"]`` lists the characters outside the vocabulary). """ text = clean_asr_text(raw).translate({ord(k): v for k, v in char_map.items()}) tags = sorted({ch for ch in text if ch in TAG_CHARS}) if tags: raise TextRejected( REASON_TAG_CHARS, {"chars": "".join(tags), "text": text[:DETAIL_TEXT_CHARS]} ) text = " ".join(text.split()) if not text: raise TextRejected(REASON_EMPTY, {}) if any(ch.isdigit() for ch in text): spoken = verbalize_digits(text) if spoken is None: raise TextRejected(REASON_NUMBER, {"text": text[:DETAIL_TEXT_CHARS]}) text = " ".join(spoken.split()) offending = sorted({ch for ch in text if tr_lower(ch) not in VOCAB}) if offending: raise TextRejected( REASON_UNTOKENIZABLE, {"chars": "".join(offending), "text": text[:DETAIL_TEXT_CHARS]}, ) try: ids = encode_text(text) except ValueError as err: # defence in depth: something other than a character raise TextRejected(REASON_UNTOKENIZABLE, {"error": str(err)}) from err if not ids: raise TextRejected(REASON_EMPTY, {}) return text
def map_emotion(label: object, emotion_map: Mapping[str, str]) -> str | None: """Emotion id of a source label, or ``None`` when absent or not in ``emotion_map``.
Labels are English: matched after stripping and ASCII lower-casing (never ``tr_lower``, which would turn ``I`` into ``ı``). """ if not isinstance(label, str): return None return emotion_map.get(en_lower(label.strip())).gitattributes+16
LICENSEAdded+202
README.mdAdded+129
nida-v05-ema.ptAdded+3
pyproject.tomlAdded+68
requirements.txtAdded+11
src/nida/__init__.pyAdded+7
src/nida/bench/__init__.pyAdded+1
src/nida/bench/audiometrics.pyAdded+570
src/nida/bench/b1.pyAdded+622
src/nida/bench/b2.pyAdded+684
src/nida/bench/clips.pyAdded+510
src/nida/bench/envs.pyAdded+351
src/nida/bench/expresso.pyAdded+301
src/nida/bench/fetch.pyAdded+704
src/nida/bench/panel.pyAdded+817
src/nida/bench/phase0.pyAdded+358
src/nida/bench/prepare.pyAdded+450
src/nida/bench/protocol.pyAdded+325
src/nida/bench/registry.pyAdded+166
src/nida/bench/report.pyAdded+276
src/nida/bench/textmetrics.pyAdded+464
src/nida/bench/workers/__init__.pyAdded+7
src/nida/bench/workers/asr_hf.pyAdded+103
src/nida/bench/workers/asr_omni.pyAdded+42
src/nida/bench/workers/asr_qwen.pyAdded+55
src/nida/bench/workers/common.pyAdded+74
src/nida/bench/workers/quality_audiobox.pyAdded+46
src/nida/bench/workers/runner.pyAdded+340
src/nida/bench/workers/vae_voxcpm.pyAdded+146
src/nida/cli.pyAdded+929
src/nida/data/__init__.pyAdded+5
src/nida/data/acoustic.pyAdded+1002
src/nida/data/align.pyAdded+261
src/nida/data/asr_filter.pyAdded+283
src/nida/data/ears.pyAdded+1307
src/nida/data/enhance.pyAdded+593
src/nida/data/envs.pyAdded+229
src/nida/data/events.pyAdded+183
src/nida/data/fillers_ctc.pyAdded+227
src/nida/data/fusion.pyAdded+842
src/nida/data/importer/__init__.pyAdded+118
src/nida/data/importer/archives.pyAdded+296
src/nida/data/importer/audio.pyAdded+146
src/nida/data/importer/config.pyAdded+474
src/nida/data/importer/corpora.pyAdded+801
src/nida/data/importer/hub.pyAdded+150
src/nida/data/importer/pipeline.pyAdded+1326
src/nida/data/importer/sources.pyAdded+776
src/nida/data/importer/text.pyAdded+110