Maya TTS: streaming Indic + English text-to-speech (inference engine)
Python
Maya3 1.0: streaming multilingual Indic TTS inference engine
Bharath Kumar79142d835fc7
diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..be71c25--- /dev/null+++ b/.gitignore@@ -0,0 +1,8 @@+__pycache__/+*.pyc+*.egg-info/+.venv/+serve/scratch/+*.wav+clone_out/+smoke_out/diff --git a/CHANGELOG.md b/CHANGELOG.mdnew file mode 100644index 0000000..b2cfbbe--- /dev/null+++ b/CHANGELOG.md@@ -0,0 +1,12 @@+# Changelog++## 1.0 (2026-10-25)++First public release.++- Maya3 weights on Hugging Face: [maya-research/maya2-native](https://huggingface.co/maya-research/maya2-native) (bf16 safetensors).+- 12 languages: as bn en gu hi kn ml mr or pa ta te.+- 20 named voices, plus zero-shot and cross-lingual voice cloning.+- Streaming engine: continuous batching, CUDA graphs, cached voice prefixes, built-in duration and loop guards.+- Python API (`generate`, `stream`, `astream`), an OpenAI-compatible HTTP server and a multi-context WebSocket server.+- Bundled text normaliser for numbers, currency, dates, times, URLs and e-mail addresses in every language.diff --git a/CITATION.cff b/CITATION.cffnew file mode 100644index 0000000..f53dbc6--- /dev/null+++ b/CITATION.cff@@ -0,0 +1,16 @@+cff-version: 1.2.0+message: "If you use Maya3, please cite it as below."+title: "Maya3: Streaming Multilingual Text-to-Speech for Indic Languages"+authors:+ - name: "Maya Research"+version: "1.0"+date-released: "2026-10-25"+license: Apache-2.0+repository-code: "https://github.com/MayaResearch/maya2-native"+url: "https://huggingface.co/maya-research/maya2-native"+keywords:+ - text-to-speech+ - indic+ - multilingual+ - voice-cloning+ - streamingdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdnew file mode 100644index 0000000..ab59440--- /dev/null+++ b/CONTRIBUTING.md@@ -0,0 +1,12 @@+# Contributing++Thanks for helping improve Maya3.++- **Bugs and feature requests:** open a GitHub issue. Include the language, the voice or cloning mode, the exact text, the seed, the GPU, and the `maya3` commit. A short audio clip helps.+- **Pull requests:** keep them small and focused, and describe what changed and how you tested it.+ - Run the CPU tests before sending: `./run_tests.sh`.+ - Changes to the engine's hot path (`maya3/engine.py`, `serve/fast_*.py`) should come with before/after numbers from `maya3/bench/bench_engine.py` on a GPU.+- **Text normaliser:** `maya3/text/tn/` is a verbatim vendored copy, pinned by sha256 in `test_text.py`. Put fixes in `maya3/text/rules.py` or `maya3/text/lexicon.py`, with a test case.+- **Style:** Python 3.10+, standard library first, no new heavy dependencies without discussion.+- **Security / misuse reports:** do not open a public issue. See [SECURITY.md](SECURITY.md).+- By contributing you agree that your contribution is licensed under the repository's license.diff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..d0381d6--- /dev/null+++ b/LICENSE@@ -0,0 +1,176 @@+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 CONDITIONSdiff --git a/README.md b/README.mdnew file mode 100644index 0000000..e14a098--- /dev/null+++ b/README.md@@ -0,0 +1,240 @@+# Maya3 TTS++Streaming multilingual text-to-speech for **11 Indic languages and English**, with 20 built-in voices and+zero-shot voice cloning. This repository is the **inference engine**: a continuous-batching CUDA-graph engine, a+Python API, an OpenAI-compatible HTTP server and a WebSocket streaming server. The weights are on Hugging Face at+**[maya-research/maya2-native](https://huggingface.co/maya-research/maya2-native)**.++**[Samples](https://huggingface.co/maya-research/maya2-native#samples) · [Model card](https://huggingface.co/maya-research/maya2-native) · [Engine docs](docs/ENGINE.md) · [Text normaliser](maya3/text/README.md)**++> The Python package and model are called **Maya3**; `maya2-native` is the repository name.++- **Languages:** as bn en gu hi kn ml mr or pa ta te.+- **Streaming:** about 14 ms to first audio at B=1 on an H100. One H100 NVL serves **224 concurrent streams** at **323 s of audio per second**, with steady-state TTFA p99 **242 ms** and 0 playback stalls.+- **Voices:** 20 named voices (`voice="Ahana"`), or clone a voice from 3-10 s of audio.+- **Text normaliser (bundled):** numbers, currency, dates, URLs and ALL-CAPS names are spoken correctly in every language.++## Install++You need Python 3.10-3.12, Linux and an NVIDIA GPU with a CUDA 12.8 driver (8 GB or more of GPU memory).++```bash+git clone https://github.com/MayaResearch/maya2-native maya3 && cd maya3+python -m venv .venv && . .venv/bin/activate+pip install -e ".[server]" --extra-index-url https://download.pytorch.org/whl/cu128+```++The pinned runtime is torch 2.8.0 (cu128, triton 3.4.0), transformers 5.6.2 and speechbrain 1.1.2. Weights, the+Mimi codec and the ECAPA speaker encoder are downloaded from Hugging Face on first use. Set `HF_HUB_OFFLINE=1` to+use only the local cache.++## Quickstart++### Python++```python+from maya3 import Maya3TTS+import soundfile as sf++tts = Maya3TTS.from_pretrained("maya-research/maya2-native", max_seats=16)++wav = tts.generate("नमस्ते, आपका ऑर्डर कल पहुँच जाएगा।", lang="hi", voice="Ahana")+sf.write("out.wav", wav, 24000) # float32, 24 kHz mono++for pcm in tts.stream("Your OTP is 482913.", lang="en", voice="Siddhant", normalize=True):+ ... # int16 PCM chunks, as they are generated+```++`generate`, `stream` and `astream` are thread-safe and asyncio-safe. Concurrent calls are batched on the GPU.++### Command line++```bash+python examples/synthesize.py "నమస్కారం, మీరు ఎలా ఉన్నారు?" --lang te --voice Sreekar -o out.wav+python examples/synthesize.py --list-voices+```++### HTTP server (OpenAI-compatible) and WebSocket streaming++```bash+python -m maya3.server --ckpt maya-research/maya2-native --host 0.0.0.0 --port 8080 --max-seats 64+```++```bash+curl -sN localhost:8080/v1/audio/speech -H 'content-type: application/json' \+ -d '{"input":"Your order has shipped.","language":"en","voice":"Ahana","response_format":"wav"}' > out.wav+```++```python+from openai import OpenAI # any OpenAI-compatible client+client = OpenAI(base_url="http://localhost:8080/v1", api_key="unused")+with client.audio.speech.with_streaming_response.create(+ model="maya3", voice="Ahana", input="Hello from Maya3.", response_format="pcm") as r: # s16le, 24 kHz+ for chunk in r.iter_bytes():+ ...+```++- `POST /v1/audio/speech` streams `wav`, `pcm`, `mp3` or `opus`; `flac` is sent once the audio is complete.+- `WS /v1/tts/stream` carries several concurrent contexts per socket, with cancel and binary frames. See `examples/ws_stream.py` and the protocol in the docstring of `maya3/server.py`.+- `GET/POST/DELETE /v1/voices` manages cloned voices, and `GET /health` reports status.+- Text is normalised by default. Turn this off with `"normalize": false` per request, or `--no-normalise` for the whole server.+- `maya3.client` has a small Python client for HTTP and WebSocket.++## Voices++| voice | gender | age | languages (>= 1 h trained) | description |+|---|---|---|---|---|+| Ahana | female | young | bn en gu hi kn ml mr or pa ta te | Young female voice, bright, youthful |+| Vaidehi | female | adult | bn en gu hi kn ml mr or pa ta te | Adult female voice, calm, gentle |+| Malini | female | mature | bn en gu hi kn ml mr or pa ta te | Mature female voice, steady narrator |+| Charvi | female | young | bn en gu hi kn ml mr or pa ta te | Young female voice, energetic, upbeat |+| Jahnavi | female | adult | bn en gu hi kn ml mr or ta te | Adult female voice, warm, friendly |+| Anirban | male | adult | bn en gu hi kn ml mr or pa ta te | Adult male voice, steady narrator |+| Nakul | male | young | bn en gu hi kn ml mr or pa ta te | Young male voice, bright, youthful |+| Vasant | male | mature | bn en gu hi kn ml mr or ta te | Mature male voice, steady narrator |+| Siddhant | male | adult | bn en gu hi kn ml mr or pa ta te | Adult male voice, clear, professional |+| Satvik | male | young | bn en gu hi kn ml mr or pa ta te | Young male voice, warm, friendly |+| Abhay | male | adult | en hi | Adult male voice, natural conversational style; trained on English, Hindi |+| Nivedita | female | adult | en hi | Adult female voice, natural conversational style; trained on English, Hindi |+| Ishwari | female | adult | hi | Adult female voice, natural conversational style; trained on Hindi |+| Ritvik | male | adult | hi | Adult male voice, natural conversational style; trained on Hindi |+| Vrinda | female | young | hi | Young female voice, natural conversational style; trained on Hindi |+| Sreekar | male | adult | en hi te | Adult male voice, natural conversational style; trained on English, Hindi, Telugu |+| Kayal | female | adult | en ta | Adult female voice, natural conversational style; trained on English, Tamil |+| Shaunak | male | young | en hi | Young male voice, natural conversational style; trained on English, Hindi |+| Akshat | male | adult | en hi | Adult male voice, natural conversational style; trained on English, Hindi |+| Tanushree | female | adult | en hi | Adult female voice, natural conversational style; trained on English, Hindi |++- Every voice can speak all 12 languages. Languages outside its trained list are spoken cross-lingually.+- Names are case-insensitive. `tts.voices` (a property) and `GET /v1/voices` list them.+- The voices are synthetic personas and must not be presented as real people.++**Named-voice prompt format.** A named voice is selected by its name in the prompt: the engine renders+`<|lang:xx|>{Name}: <text><|audio|>`. Send only your text with `voice="Name"` (Python) or `"voice": "Name"` (HTTP/WS).+Do not type `{Name}: ` yourself, and do not combine a named voice with a reference clip. Each voice's conditioning+mode is in `voices/voices.json`:+- `named` uses the trained name prompt;+- `spk` uses a stored speaker embedding.++## Voice cloning++```python+# 3-10 s of clean speech + its exact transcript and language. Only clone voices you have consent to use.+tts.register_voice("my_voice", ref_audio="ref.wav", ref_text="<exact transcript of ref.wav>", lang="hi")+wav = tts.generate("வணக்கம், எப்படி இருக்கிறீர்கள்?", lang="ta", voice="my_voice") # cross-lingual++# one-off (cached for the session):+wav = tts.generate("Hello!", lang="en", ref_audio="ref.wav", ref_text="...", ref_lang="hi")+```++There are three conditioning modes for a reference:+- `icl_spk` (default): the reference audio as an in-context prompt, plus its ECAPA embedding;+- `icl`: the reference audio only;+- `spk`: the ECAPA embedding only, so no transcript is needed.++The reference language can differ from the target language. Over HTTP, `POST /v1/voices` registers a clone (see+`examples/clone_voice.py`). Zero-shot clones are recognisably close to the reference but not identical.++## Languages++| code | language | CER % (Qwen3-ASR, release bench) |+|---|---|---:|+| `as` | Assamese | 6.59 |+| `bn` | Bengali | 2.83 |+| `en` | English | 1.74 |+| `gu` | Gujarati | 3.76 |+| `hi` | Hindi | 2.05 |+| `kn` | Kannada | 2.72 |+| `ml` | Malayalam | 4.20 |+| `mr` | Marathi | 2.09 |+| `or` | Odia | 4.33 |+| `pa` | Punjabi | 3.32 |+| `ta` | Tamil | 4.55 |+| `te` | Telugu | 2.64 |++Overall CER on the 6,000-clip release bench is 3.40 % (Qwen3-ASR). Real failures, where two ASRs agree, are+0.15 %. The model card describes the method in full.++## Streaming performance++The whole release bench (6000 texts, 20.3 h of audio) was served by `maya3.server` with its+defaults, as 224 concurrent WebSocket streams on **one H100 NVL**:++| metric | value |+|---|---|+| throughput | 323 audio-s/s |+| TTFA, steady state, p50 / p90 / p99 | 111 / 134 / 242 ms |+| TTFA, whole run incl. ramp and drain, p50 / p99 | 115 / 774 ms |+| playback stalls / errors | 0 / 0 |+| B=1 (single stream, H100) | TTFA about 14 ms, RTF about 0.13 |++GPU memory, with a bf16 backbone, an fp16 depth decoder and 2048 KV tokens per seat (add about 0.5 GB of CUDA context):++| `max_seats` | steady | peak |+|---:|---:|---:|+| 1 | 7.7 GB | 9.2 GB |+| 8 | 9.7 GB | 10.9 GB |+| 16 | 11.7 GB | 12.8 GB |+| 32 | 15.8 GB | 16.5 GB |++An RTX 4090 (24 GB) serves 48 streams at `capacity=2048` (TTFA p99 66 ms), or 96 at `capacity=1024`. Engine knobs,+design notes and the conversion tools are in [docs/ENGINE.md](docs/ENGINE.md). The text normaliser is described in+[maya3/text/README.md](maya3/text/README.md).++## Limitations++- **Assamese is the weakest language**, with the highest CER and the least stable voice identity. No voice has much Assamese training audio.+- **Very short prompts (1-2 words)** can drift in voice identity. Prefer a slightly longer phrase for short agent turns.+- **Code-mixed and mixed-script text** has the highest error rates, and English words inside Indic sentences vary by voice.+- **URLs, symbols and long digit strings** need the normaliser (on by default in the server, `normalize=True` in Python).+- **Clone similarity** is recognisably close but not identical. Noisy or very short references reduce it.+- **Inline emotion tags** (`[laughs]`, `[whispers]`, ...) are best effort.+- **Sampling.** Output is sampled. The same seed is reproducible only when the request runs alone.++## Responsible use++Do not use Maya3 to impersonate real people, to clone a voice without the speaker's consent, for fraud, or to defeat+voice authentication. Tell listeners when speech is synthetic. To report misuse or a security problem, see+[SECURITY.md](SECURITY.md) (contact: TBD).++## Repository layout++| path | content |+|---|---|+| `maya3/` | public API (`api.py`), streaming engine (`engine.py`), HTTP/WS server (`server.py`), client, guards, text normaliser, tools, tests |+| `serve/` | CUDA-graph components: fused backbone step, fp16 depth decoder, one-frame Mimi decoder, KV cache |+| `tts/` | model definition and the training-time prompt packer the engine reproduces |+| `scripts/` | prompt and stop-control helpers shared with the model code |+| `configs/` | model config and the duration prior read by the engine |+| `examples/` | command-line synthesis, OpenAI client, WebSocket streaming, voice cloning |+| `docs/ENGINE.md` | engine internals, knobs, memory and latency measurements, checkpoint conversion |++## Tests++The CPU tests need no GPU and no weights:++```bash+pip install -e ".[dev]" --extra-index-url https://download.pytorch.org/whl/cu128+./run_tests.sh # = CUDA_VISIBLE_DEVICES= python -m pytest -q maya3/tests/test_text.py maya3/tests/test_guards.py maya3/tests/test_server.py+```++The GPU checks (`maya3/tests/test_backbone_*.py`, `test_depth_fused.py`, `test_rope_kernel.py`, `test_sampling.py`)+are scripts that take a checkpoint path. See their docstrings.++## License++Apache-2.0. See `LICENSE`. The model weights have their own license on the Hugging Face model card. Maya3 builds on+Qwen3, Mimi (Kyutai) and SpeechBrain ECAPA-TDNN; see their licences.++## Citation++```bibtex+@misc{maya3tts,+ title = {Maya3: Streaming Multilingual Text-to-Speech for Indic Languages},+ author = {Maya Research},+ year = {2026},+ howpublished = {\url{https://huggingface.co/maya-research/maya2-native}}+}+```++GitHub's "Cite this repository" button reads `CITATION.cff`. Changes are listed in [CHANGELOG.md](CHANGELOG.md).diff --git a/SECURITY.md b/SECURITY.mdnew file mode 100644index 0000000..e2dfa59--- /dev/null+++ b/SECURITY.md@@ -0,0 +1,17 @@+# Security and misuse reports++Please do not report security problems or misuse in a public issue.++- **Security vulnerabilities in the engine or server** (for example a request or an uploaded reference clip that crashes the server or exhausts its resources): use GitHub's private vulnerability reporting (**Security → Report a vulnerability** on this repository), or e-mail TBD.+- **Misuse of the model** (impersonation, cloning without consent, fraud): e-mail TBD with as much detail as you can share.++## Supported versions++| version | supported |+|---|---|+| 1.0 | yes |++## Deployment notes++- `maya3.server` has no authentication. Put it behind your own gateway before exposing it outside a trusted network.+- `POST /v1/voices` accepts reference audio from the caller. Restrict it if untrusted users can reach the server, and only register voices you have consent to use.diff --git a/configs/s3_fresh_v1.yaml b/configs/s3_fresh_v1.yamlnew file mode 100644index 0000000..9a07055--- /dev/null+++ b/configs/s3_fresh_v1.yaml@@ -0,0 +1,14 @@+# Maya3 model-architecture config read by maya3.engine.Engine (and the conversion tools) when a checkpoint is loaded.+# Only the `model` block is used at inference time. `backbone` is always overridden by the caller's backbone dir+# (a release dir's backbone/ with the Qwen3 config.json + tokenizer); the other keys must match the checkpoint+# and are cross-checked against its tensors on load.+model:+ backbone: backbone+ attn: sdpa+ speaker_anchor:+ enabled: true+ input_dim: 192+ hidden: 512+ dropout: 0.2+ depth_grouped: true+ depth_ckpt_from: 9diff --git a/configs/text_frames_prior.json b/configs/text_frames_prior.jsonnew file mode 100644index 0000000..24f8d8e--- /dev/null+++ b/configs/text_frames_prior.json@@ -0,0 +1,122 @@+{+ "as": {+ "n": 780,+ "fpc_p50": 0.7549,+ "fpc_p90": 0.98,+ "fpc_p97": 1.1965,+ "affine_a": -1.36,+ "affine_b": 0.7786,+ "resid_p95": 32.6,+ "resid_p99": 91.6+ },+ "bn": {+ "n": 9752,+ "fpc_p50": 0.8222,+ "fpc_p90": 1.069,+ "fpc_p97": 1.25,+ "affine_a": 3.16,+ "affine_b": 0.7887,+ "resid_p95": 34.4,+ "resid_p99": 76.2+ },+ "en": {+ "n": 23630,+ "fpc_p50": 0.733,+ "fpc_p90": 1.0136,+ "fpc_p97": 1.2,+ "affine_a": 0.6,+ "affine_b": 0.7416,+ "resid_p95": 36.8,+ "resid_p99": 75.0+ },+ "gu": {+ "n": 10256,+ "fpc_p50": 0.8868,+ "fpc_p90": 1.1745,+ "fpc_p97": 1.3787,+ "affine_a": 1.74,+ "affine_b": 0.8834,+ "resid_p95": 38.7,+ "resid_p99": 83.1+ },+ "hi": {+ "n": 20114,+ "fpc_p50": 0.807,+ "fpc_p90": 1.0814,+ "fpc_p97": 1.2941,+ "affine_a": 5.65,+ "affine_b": 0.7644,+ "resid_p95": 39.8,+ "resid_p99": 79.8+ },+ "kn": {+ "n": 11445,+ "fpc_p50": 0.7803,+ "fpc_p90": 1.0471,+ "fpc_p97": 1.2529,+ "affine_a": 1.91,+ "affine_b": 0.7675,+ "resid_p95": 34.0,+ "resid_p99": 69.5+ },+ "ml": {+ "n": 10486,+ "fpc_p50": 0.6809,+ "fpc_p90": 0.9195,+ "fpc_p97": 1.0949,+ "affine_a": 1.25,+ "affine_b": 0.6788,+ "resid_p95": 49.7,+ "resid_p99": 105.6+ },+ "mr": {+ "n": 16138,+ "fpc_p50": 0.8319,+ "fpc_p90": 1.0769,+ "fpc_p97": 1.2545,+ "affine_a": 1.12,+ "affine_b": 0.8235,+ "resid_p95": 30.4,+ "resid_p99": 60.1+ },+ "or": {+ "n": 2441,+ "fpc_p50": 0.7955,+ "fpc_p90": 1.0357,+ "fpc_p97": 1.2443,+ "affine_a": 1.06,+ "affine_b": 0.7936,+ "resid_p95": 34.4,+ "resid_p99": 68.4+ },+ "pa": {+ "n": 9201,+ "fpc_p50": 0.8169,+ "fpc_p90": 1.1279,+ "fpc_p97": 1.3571,+ "affine_a": 1.86,+ "affine_b": 0.8079,+ "resid_p95": 35.8,+ "resid_p99": 73.5+ },+ "ta": {+ "n": 13289,+ "fpc_p50": 0.6545,+ "fpc_p90": 0.8936,+ "fpc_p97": 1.0802,+ "affine_a": 2.24,+ "affine_b": 0.6425,+ "resid_p95": 32.6,+ "resid_p99": 70.8+ },+ "te": {+ "n": 12761,+ "fpc_p50": 0.8023,+ "fpc_p90": 1.0577,+ "fpc_p97": 1.2731,+ "affine_a": 1.2,+ "affine_b": 0.7927,+ "resid_p95": 43.6,+ "resid_p99": 89.6+ }+}\ No newline at end of filediff --git a/docs/ENGINE.md b/docs/ENGINE.mdnew file mode 100644index 0000000..19e3d8b--- /dev/null+++ b/docs/ENGINE.md@@ -0,0 +1,230 @@+# Maya3 engine internals++Maya3 is a Qwen3-1.7B backbone plus a 555M depth decoder.+- It predicts 32 Mimi codebooks at 12.5 Hz, one 80 ms frame per step, and the audio is 24 kHz mono.+- It conditions on an ECAPA-192 speaker embedding.+- It speaks 12 languages: `as bn en gu hi kn ml mr or pa ta te`.++This package is the inference stack:+- a continuous-batching engine where every hot step is a CUDA graph;+- a voice registry that caches each voice's prompt prefix;+- guards inside the engine, on by default;+- a Python API, an OpenAI-compatible HTTP endpoint and a streaming WebSocket.++## Install++You need Python 3.10-3.12 and an NVIDIA GPU with a CUDA 12.8 driver. torch 2.8.0+cu128 comes from the PyTorch index.++```bash+git clone https://github.com/MayaResearch/maya2-native maya3 && cd maya3+python -m venv .venv && . .venv/bin/activate+pip install -e ".[server]" --extra-index-url https://download.pytorch.org/whl/cu128+# extras: [server] = aiohttp (HTTP/WS server + client); [dev] = server deps + pytest, pytest-asyncio, pytest-aiohttp+```++CPU-only checks need no GPU (see `run_tests.sh` at the repo root):++```bash+CUDA_VISIBLE_DEVICES= python -m pytest -q maya3/tests/test_text.py maya3/tests/test_guards.py maya3/tests/test_server.py+```++Pinned runtime versions:++| package | version |+|---|---|+| torch | 2.8.0, with triton 3.4.0 |+| torchaudio | 2.8.0 |+| transformers | 5.6.2 |+| speechbrain | 1.1.2 |++numpy, scipy, soundfile, huggingface_hub, safetensors and pyyaml are also required.++The install provides the packages `maya3`, `tts` (model code), `serve` (CUDA-graph components) and `scripts` (prompt and stop controls), plus `configs/`. An editable install (`-e`) is recommended. A plain `pip install .` also works, because the two `configs/` files the engine reads are packaged, but then Triton caches its kernels inside the installed `serve/` package unless `TRITON_CACHE_DIR` is set.++## Quick start (Python)++```python+from maya3 import Maya3TTS+import soundfile as sf++tts = Maya3TTS.from_pretrained("maya-research/maya2-native", max_seats=16) # HF repo id or a local release dir++wav = tts.generate("नमस्ते, आज मौसम बहुत अच्छा है।", lang="hi") # float32, 24 kHz mono+sf.write("out.wav", wav, 24000)++wav = tts.generate("Your order has shipped.", lang="en", voice="Ahana") # a named voice from voices/voices.json++tts.register_voice("asha", ref_audio="asha.wav", ref_text="<exact transcript of asha.wav>", lang="hi")+wav = tts.generate("Your order has shipped.", lang="en", voice="asha") # cross-lingual clone, cached prefix++for pcm in tts.stream("Long text ...", lang="te", voice="asha"): # int16 chunks as they are generated+ ...++wav = tts.generate("Pay ₹1,250 by 5 pm.", lang="en", normalize=True) # bundled normaliser: digits, currency, URLs+```++**Release directory.** `from_pretrained(dir)` resolves the directory with `maya3.hub.resolve`. Mimi and ECAPA are taken from the Hugging Face cache, or downloaded on first use. The directory holds:+- `model.safetensors`, or the shards plus `model.safetensors.index.json`;+- `maya3_config.json`;+- `backbone/`: the Qwen3 config and tokenizer only;+- `voices/voices.json`.++```python+from maya3.hub import resolve+resolve("/path/to/release/maya3")+# {"ckpt": ".../maya3", "backbone_dir": ".../maya3/backbone", "mimi_dir": "<kyutai/mimi snapshot>",+# "ecapa_dir": "<speechbrain/spkrec-ecapa-voxceleb snapshot>", "voices_json": ... or None}+```++- `HF_HUB_OFFLINE=1` never touches the network.+- `MAYA3_MIMI_DIR` and `MAYA3_ECAPA_DIR` (or `resolve(..., mimi=, ecapa=)`) point at local copies.+- The explicit form still works: `Maya3TTS.from_pretrained("model.pt", backbone_dir=..., mimi_dir=..., ecapa_dir=...)`.++**Calls and voices.**+- `generate`, `stream` and `astream` are thread- and asyncio-safe. Concurrent calls are batched on the GPU.+- `ref_audio=`, `ref_text=` and `ref_lang=` on a call clone a voice once and cache it for the session. A registered voice is better.+- The reference clip should be 3-10 s long, with its exact transcript and language. Its language may differ from the target's, which gives cross-lingual cloning.++**Conditioning modes.**+- `icl_spk` (default with a reference): reference audio plus ECAPA;+- `icl`;+- `spk` (ECAPA only; no transcript needed);+- `plain` (no reference);+- `named` (a trained voice selected by `voice="Name"`, with no reference audio).++**Text.**+- Inline tags such as `[laughs]`, `[sighs]` and `[whispers]` are passed through.+- Long text is split at sentence boundaries into pieces of about 20 s. The pieces are streamed back-to-back with 150 ms gaps.++**Sampling per call.** The options are `seed`, `temperature`, `top_k`, `top_p` and `repetition_penalty`. With the same seed, text and voice, the audio is the same when the request runs alone.++### Converting a checkpoint into a release directory++```bash+python -m maya3.tools.convert_to_safetensors <model.pt> <out_dir> --backbone-src <backbone dir with config.json + tokenizer>+CUDA_VISIBLE_DEVICES= python -m maya3.tools.verify_conversion <model.pt> <out_dir> # bit-identical check, CPU+```++- Dtypes are kept exactly as stored.+- The output is sharded at 5 GB.+- Tied tensors (`lm_head` and `embed_tokens`) are stored once and recorded as aliases.+- `maya3_config.json` records the resolved model config: speaker anchor, `depth_grouped` and the format version.+- `tts.model.load_s3.load_model_for_eval` loads the directory directly.++The backbone's own `model.safetensors` (7 GB) is never needed. When the backbone directory holds no weight files, the architecture is built from `config.json` and every weight comes from the Maya3 checkpoint. The result is bit-identical (`maya3/tests/test_backbone_from_config.py`). `MAYA3_BACKBONE_FROM_CONFIG=1` forces this path.++## Server++```bash+python -m maya3.server --ckpt /path/to/release/maya3 --port 8080 --max-seats 64+# or explicitly: --ckpt model.pt --backbone-dir BB --mimi-dir MIMI --ecapa-dir ECAPA [--voices clones.json]+curl -sN localhost:8080/v1/audio/speech -H 'content-type: application/json' \+ -d '{"input":"Hello there.","language":"en","voice":"plain","response_format":"wav"}' > out.wav+```++```python+from openai import OpenAI+client = OpenAI(base_url="http://localhost:8080/v1", api_key="unused")+with client.audio.speech.with_streaming_response.create(model="maya3", voice="plain", input="Hello there.",+ response_format="pcm") as r: # s16le, 24 kHz mono+ for chunk in r.iter_bytes():+ ...+```++- `POST /v1/audio/speech` is OpenAI-compatible.+ - It streams wav, pcm, mp3 or opus. flac is sent once the audio is complete.+ - Text is normalised by default. Turn this off with `"normalize": false` on a request, or `--no-normalise` for the whole server.+- `WS /v1/tts/stream` streams with multiple contexts per socket and supports cancel.+- `GET/POST/DELETE /v1/voices` manages voices, and `GET /health` reports status.+- `--voices` takes a JSON file of reference-clip voices (`voice_id`, `ref_audio`, `ref_text`, `lang`, `mode`). Named voices come from the release's `voices/voices.json`.+- **Per-voice mode.** Each entry of `voices/voices.json` has a `mode`:+ - `named`: the trained `{Name}: text` prompt.+ - `spk`: the voice's stored ECAPA centroid, given by `ecapa` (an .npy path relative to the file).+ - `icl_spk`: the centroid plus a curated reference clip. `ref_clips` holds `[{codes: <.npy (32,F) Mimi codes>, text, lang}]`.+ - Callers use `voice="Name"` in every mode; the mode only changes how the voice is conditioned.+- `maya3.client` has a Python client for HTTP and WebSocket.+- The full wire contract is in the docstring of `maya3/server.py`.++## Hardware and memory++Measured with bf16 backbone, fp16 depth, KV capacity 2048 tokens per seat, warmed and serving requests. Values are from the torch allocator; add about 0.5 GB of CUDA context.++| max_seats | static weights | KV | steady GPU memory | peak during load |+|---:|---:|---:|---:|---:|+| 1 | 5.6 GB | 0.47 GB | 7.7 GB | 9.2 GB |+| 8 | 5.6 GB | 2.1 GB | 9.7 GB | 10.9 GB |+| 16 | 5.6 GB | 4.0 GB | 11.7 GB | 12.8 GB |+| 32 | 5.6 GB | 7.8 GB | 15.8 GB | 16.5 GB |++| GPU | measured streams at the SLA (TTFA p99 <= 300 ms, 0 playback stalls) | B=1 TTFA / RTF |+|---|---|---|+| H100 80 GB | 224 (capacity 1536) | 14 ms / 0.137 |+| RTX 4090 24 GB | 48 at capacity 2048 (TTFA p99 66 ms); 96 at capacity 1024 (TTFA p99 104 ms, 188 audio-s/s) | 15 ms / 0.154 |+| 16 GB card | about 16 at capacity 2048 (estimate from the memory table) | - |+| 12 GB card | 1-4 (estimate) | - |++- Everything runs in plain bf16; no quantisation is needed.+- KV is 112 KiB per token per seat, so `capacity=1024` halves the KV memory.+- The fp32 reference depth decoder (2.2 GB) is freed once the fp16 fast copy is built.++## Knobs (`EngineConfig`, passed as keyword arguments to `from_pretrained`)++| knob | default | meaning |+|---|---|---|+| `max_seats` | 16 | concurrent generations batched on the GPU. The CUDA graphs and KV are sized for it, so memory follows the table above. |+| `capacity` | 2048 | backbone KV tokens per seat (prompt plus generated frames, at 12.5 frames/s) |+| `depth_dtype` | `fp16` | depth decoder precision: `fp16`, `bf16` or `fp32`. fp16 is the closest to fp32 greedy. |+| `cb0_temp`, `cb0_top_k`, `cb0_top_p`, `cb0_rep`, `cb0_rep_win` | engine defaults | cb0 sampler: temperature, top-k, top-p, presence penalty and its window |+| `temp`, `top_k` | 0.7, 64 | depth sampler |+| `chunk_s`, `gap_s` | 20 s, 0.15 s | long-text piece length and the silence between pieces |+| `hard_cap` | 1500 | absolute frame ceiling per piece (120 s) |+| `busy_frac`, `busy_admit` | 0.75, 4 | admission smoothing under load. `--busy-frac 0.6` gave 0 stalls in a 30-min soak at 224 seats. |+| `guards` | on | `GuardConfig`: the duration cap and loop guard below |+| `seed` | fixed | engine RNG seed; per-request `seed=` overrides it |++## Engine design (`maya3/engine.py`)++Each tick produces one frame for every active seat:+1. **Admission.**+ - A new request's voice prefix (reference text plus codes) is constant per voice, so its backbone KV is computed once and copied into the request's slot.+ - Only the target text is prefilled. This happens *inside* the same graphed backbone step as the decode rows, so the first frame comes out in the admission tick.+2. **Generation.** The cb0 sampler and controlled stop run on the GPU. Then come the depth decoder (31 levels, one CUDA graph, fp16) and the Mimi one-frame decoder (one CUDA graph).+3. **Readout.** One device-to-host copy and one sync per tick. Guards and delivery then run on the host.++The prompt geometry comes from the training packer (`tts.data.packing_v2`). It was checked token for token against the reference eval harness.++Prompt builders are pluggable (`maya3/prompt.py`). Named speakers use `NamedSpeakerBuilder`, which renders `<|lang:xx|>{Name}: text<|audio|>`.++## Guards (on by default, zero latency, no configuration): `maya3/guards.py`++- **Duration cap.** Generation stops at 2.2 × the expected duration + 1.2 s. The expected duration comes from a digit-, pause- and language-aware prior.+- **Loop guard.** It watches for a cb0 stall or a periodic loop.+ - On a hit it applies an EOS boost of +4 on the AEOS logit, so the model ends the phrase itself.+ - If the loop persists 24 frames after the boost, a backstop stop follows.+ - It is tag-aware: it is suspended around inline `[tags]`.++## Measured (one H100 NVL, bf16 backbone, fp16 depth, guards on)++These engine measurements were taken on a pre-release checkpoint with the same architecture; speed does not depend on the weights. The release-1.0 numbers are in the README.++- **B=1:** TTFA 14 ms for plain voice and 15 ms for a cloned voice. This covers the prompt build, prefill, first frame, Mimi decode and the host copy. RTF is 0.137, about 7x faster than real time.+- **One frame:** 10.5 ms at B=1 (backbone 2.0, cb0 sampler 0.35, depth 6.5, Mimi 1.8), 23.7 ms at B=100 and 30 ms at B=160.+- **Server (WebSocket, closed loop, 0 playback stalls):**++ | lanes | frames | TTFA p99 | RTF p99 | throughput |+ |---:|---|---:|---:|---:|+ | 224 | base64 | 137 ms | 0.85 | 329 audio-s/s |+ | 256 | binary | 150 ms | 0.92 | 348 audio-s/s |++- **Server, 224 lanes, binary frames, by voice type:**+ - plain: TTFA p99 166 ms, 0 stalls, 342.6 audio-s/s;+ - cloned voice: TTFA p99 185 ms, 0 stalls, 317.0 audio-s/s.+ - Seats at SLA (TTFA p99 ≤ 300 ms, 0 stalls): **224 per H100**.+- **Quality:** ASR CER and clone similarity match the reference eval engine within seed noise.++## Benchmarks (`maya3/bench/`)++| script | what it does |+|---|---|+| `bench_engine.py` | latency and closed-loop throughput of the engine |+| `load_ws.py` | WebSocket load generator: client-side TTFA, stalls and RTF through the server |diff --git a/examples/clone_voice.py b/examples/clone_voice.pynew file mode 100755index 0000000..9027d71--- /dev/null+++ b/examples/clone_voice.py@@ -0,0 +1,48 @@+#!/usr/bin/env python3+"""Zero-shot voice cloning, in Python and over HTTP.++Only clone voices you own or have the speaker's documented consent to use.++ python examples/clone_voice.py --model <repo or dir> --ref ref.wav --ref-text "<exact transcript>" --ref-lang hi+ python examples/clone_voice.py --server http://127.0.0.1:8080 --ref ref.wav --ref-text "..." --ref-lang hi+"""+import argparse+import os+import sys++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++TEXTS = [("hi", "नमस्ते, यह मेरी आवाज़ की एक प्रति है।"), ("en", "Hello, this is a cloned voice."),+ ("ta", "வணக்கம், இது ஒரு குளோன் செய்யப்பட்ட குரல்.")]+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--model", default=os.environ.get("MAYA3_MODEL"))+ ap.add_argument("--server", default=None, help="use a running maya3.server instead of loading the model")+ ap.add_argument("--ref", required=True)+ ap.add_argument("--ref-text", required=True)+ ap.add_argument("--ref-lang", required=True)+ ap.add_argument("--mode", default="icl_spk", choices=["icl_spk", "icl", "spk"])+ ap.add_argument("--out-dir", default="clone_out")+ a = ap.parse_args()+ os.makedirs(a.out_dir, exist_ok=True)+ if a.server:+ from maya3.client import Maya3Client+ c = Maya3Client(a.server)+ c.register_voice("my_voice", a.ref, ref_text=a.ref_text, lang=a.ref_lang, mode=a.mode, replace=True)+ for lang, text in TEXTS:+ c.speech(text, f"{a.out_dir}/{lang}.wav", language=lang, voice="my_voice")+ c.remove_voice("my_voice")+ else:+ import soundfile as sf+ from maya3 import Maya3TTS+ tts = Maya3TTS.from_pretrained(a.model, max_seats=4)+ tts.register_voice("my_voice", ref_audio=a.ref, ref_text=a.ref_text, lang=a.ref_lang, mode=a.mode)+ for lang, text in TEXTS:+ sf.write(f"{a.out_dir}/{lang}.wav", tts.generate(text, lang=lang, voice="my_voice"), 24000)+ print(f"wrote {len(TEXTS)} clips to {a.out_dir}/")+++if __name__ == "__main__":+ main()diff --git a/examples/openai_client.py b/examples/openai_client.pynew file mode 100755index 0000000..6c66cf2--- /dev/null+++ b/examples/openai_client.py@@ -0,0 +1,18 @@+#!/usr/bin/env python3+"""Use the OpenAI Python SDK against a running maya3.server (pip install openai).++ python examples/openai_client.py --base-url http://127.0.0.1:8080/v1+"""+import argparse++from openai import OpenAI++ap = argparse.ArgumentParser()+ap.add_argument("--base-url", default="http://127.0.0.1:8080/v1")+a = ap.parse_args()+client = OpenAI(base_url=a.base_url, api_key="unused")+with client.audio.speech.with_streaming_response.create(+ model="maya3", voice="Kayal", input="வணக்கம்! உங்கள் பதிவு உறுதிசெய்யப்பட்டது.",+ response_format="wav", extra_body={"language": "ta"}) as r:+ r.stream_to_file("openai_ta.wav")+print("wrote openai_ta.wav")diff --git a/examples/synthesize.py b/examples/synthesize.pynew file mode 100755index 0000000..7e36d4e--- /dev/null+++ b/examples/synthesize.py@@ -0,0 +1,51 @@+#!/usr/bin/env python3+"""Command-line synthesis with Maya3.++ python examples/synthesize.py "नमस्ते, आप कैसे हैं?" --lang hi --voice Ahana -o out.wav+ python examples/synthesize.py "Hello!" --lang en --ref ref.wav --ref-text "<exact transcript>" --ref-lang hi -o clone.wav+ python examples/synthesize.py --list-voices++--model is a Hugging Face repo id or a local release directory (default: $MAYA3_MODEL).+"""+import argparse+import os+import sys+import time++import soundfile as sf++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+from maya3 import Maya3TTS # noqa: E402+++def main():+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("text", nargs="?")+ ap.add_argument("--model", default=os.environ.get("MAYA3_MODEL"), help="HF repo id or local release dir")+ ap.add_argument("--lang", default="en", help="as bn en gu hi kn ml mr or pa ta te")+ ap.add_argument("--voice", default=None, help="named voice (see --list-voices) or 'plain'")+ ap.add_argument("--ref", default=None, help="reference wav for zero-shot cloning (3-10 s)")+ ap.add_argument("--ref-text", default=None, help="exact transcript of --ref")+ ap.add_argument("--ref-lang", default=None, help="language of --ref (default: --lang)")+ ap.add_argument("--no-normalize", action="store_true", help="skip the bundled text normaliser")+ ap.add_argument("--seed", type=int, default=None)+ ap.add_argument("-o", "--out", default="out.wav")+ ap.add_argument("--list-voices", action="store_true")+ a = ap.parse_args()+ if not a.model:+ ap.error("--model (or $MAYA3_MODEL) is required")+ tts = Maya3TTS.from_pretrained(a.model, max_seats=1)+ if a.list_voices:+ print("\n".join(sorted(tts.voices)))+ return+ if not a.text:+ ap.error("text is required")+ t = time.time()+ wav = tts.generate(a.text, lang=a.lang, voice=a.voice, ref_audio=a.ref, ref_text=a.ref_text,+ ref_lang=a.ref_lang or a.lang if a.ref else None, normalize=not a.no_normalize, seed=a.seed)+ sf.write(a.out, wav, 24000)+ print(f"wrote {a.out}: {len(wav) / 24000:.2f} s of audio in {time.time() - t:.2f} s")+++if __name__ == "__main__":+ main()diff --git a/examples/ws_stream.py b/examples/ws_stream.pynew file mode 100755index 0000000..33cb4b6--- /dev/null+++ b/examples/ws_stream.py@@ -0,0 +1,39 @@+#!/usr/bin/env python3+"""Stream from the WebSocket endpoint and report time to first audio. Two contexts run concurrently on one socket.++ python -m maya3.server --ckpt <repo or dir> --port 8080 &+ python examples/ws_stream.py --url ws://127.0.0.1:8080/v1/tts/stream+"""+import argparse+import asyncio+import os+import sys+import time+import wave++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+from maya3.client import Maya3Stream # noqa: E402+++async def speak(s, text, lang, voice, out):+ t0, first, buf = time.perf_counter(), None, bytearray()+ async for pcm in s.speak(text, language=lang, voice=voice):+ first = first or time.perf_counter()+ buf += pcm+ with wave.open(out, "wb") as w:+ w.setnchannels(1); w.setsampwidth(2); w.setframerate(24000); w.writeframes(bytes(buf))+ print(f"{out}: TTFA {1e3 * (first - t0):.0f} ms, {len(buf) / 48000:.2f} s audio")+++async def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--url", default="ws://127.0.0.1:8080/v1/tts/stream")+ a = ap.parse_args()+ async with Maya3Stream(a.url, binary=True) as s:+ await asyncio.gather(+ speak(s, "आपका ऑर्डर आज शाम तक पहुँच जाएगा।", "hi", "Ahana", "ws_hi.wav"),+ speak(s, "Your appointment is confirmed for 10:30 AM tomorrow.", "en", "Siddhant", "ws_en.wav"))+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/maya3/__init__.py b/maya3/__init__.pynew file mode 100644index 0000000..c24ee99--- /dev/null+++ b/maya3/__init__.py@@ -0,0 +1,15 @@+"""Maya3 inference: fast streaming engine, voice registry with cached prefix KV, engine-internal guards, public API."""+__all__ = ["Maya3TTS", "Engine", "EngineConfig", "Voice"]+++def __getattr__(name):+ if name == "Maya3TTS":+ from maya3.api import Maya3TTS+ return Maya3TTS+ if name in ("Engine", "EngineConfig"):+ from maya3 import engine+ return getattr(engine, name)+ if name == "Voice":+ from maya3.prompt import Voice+ return Voice+ raise AttributeError(name)diff --git a/maya3/api.py b/maya3/api.pynew file mode 100644index 0000000..0f98070--- /dev/null+++ b/maya3/api.py@@ -0,0 +1,259 @@+"""Public Python API.++ from maya3 import Maya3TTS+ tts = Maya3TTS.from_pretrained("path/to/model.pt", backbone_dir=..., mimi_dir=..., ecapa_dir=...)+ wav = tts.generate("नमस्ते, आप कैसे हैं?", lang="hi") # plain voice+ tts.register_voice("asha", ref_audio="asha.wav", ref_text="...", lang="hi") # clone once, reuse+ wav = tts.generate("Hello there.", lang="en", voice="asha") # cached prefix KV + ECAPA+ wav = tts.generate("Hello there.", lang="en", ref_audio="x.wav", ref_text="...") # one-off clone+ for pcm in tts.stream("Long text ...", lang="te", voice="asha"): ... # int16 chunks, 24 kHz+ async for pcm in tts.astream(...): ... # asyncio++Audio is 24 kHz mono. generate() returns float32 in [-1, 1]; stream()/astream() yield int16 numpy chunks.+Concurrency: any number of threads / coroutines may call generate/stream at once; the engine batches them.+"""+from __future__ import annotations++import asyncio+import hashlib+import os+import queue+import threading+from pathlib import Path++import numpy as np+import torch++from maya3.engine import SR, Engine, EngineConfig+from maya3.prompt import Voice, norm_mode+++class GenerationError(RuntimeError):+ def __init__(self, code, msg):+ super().__init__(f"{code}: {msg}")+ self.code = code+++def load_audio(x, sr=None):+ """path | (array, sr) | array (assumed 24 kHz) -> float32 mono 24 kHz."""+ if isinstance(x, (str, os.PathLike)):+ import soundfile as sf+ w, sr = sf.read(str(x), dtype="float32")+ elif isinstance(x, tuple):+ w, sr = x+ else:+ w = x+ w = np.asarray(w, np.float32)+ if w.ndim > 1:+ w = w.mean(1) if w.shape[1] < w.shape[0] else w.mean(0)+ sr = sr or SR+ if sr != SR:+ from math import gcd+ from scipy.signal import resample_poly+ g = gcd(int(sr), SR)+ w = resample_poly(w, SR // g, int(sr) // g).astype(np.float32)+ return w+++class Ecapa:+ """ECAPA-TDNN speaker embedding, corpus recipe (speechbrain spkrec-ecapa-voxceleb; 16 kHz fbank-80, sentence norm)."""++ def __init__(self, ecapa_dir, device="cuda"):+ from speechbrain.lobes.features import Fbank+ from speechbrain.processing.features import InputNormalization+ from speechbrain.lobes.models.ECAPA_TDNN import ECAPA_TDNN+ self.fbank = Fbank(n_mels=80).eval().to(device)+ self.norm = InputNormalization(norm_type="sentence", std_norm=False).eval().to(device)+ emb = ECAPA_TDNN(input_size=80, channels=[1024, 1024, 1024, 1024, 3072], kernel_sizes=[5, 3, 3, 3, 1],+ dilations=[1, 2, 3, 4, 1], attention_channels=128, lin_neurons=192).eval()+ emb.load_state_dict(torch.load(Path(ecapa_dir) / "embedding_model.ckpt", map_location="cpu", weights_only=True), strict=True)+ self.emb = emb.to(device)+ self.device = device++ @torch.inference_mode()+ def __call__(self, w24):+ from scipy.signal import resample_poly+ if w24 is None or len(w24) < 2400:+ raise ValueError("reference audio is too short (need >= 0.1 s; 3-10 s recommended)")+ w16 = torch.from_numpy(resample_poly(np.asarray(w24, np.float32), 2, 3).astype(np.float32)).to(self.device)[None]+ L = torch.ones(1, device=self.device)+ e = self.emb(self.norm(self.fbank(w16), L), L).reshape(-1)+ return torch.nn.functional.normalize(e, dim=0).cpu().numpy()+++class Maya3TTS:+ def __init__(self, engine: Engine, ecapa_dir=None):+ self.engine = engine+ self.ecapa_dir = ecapa_dir+ self._ecapa = None+ self._oneoff = {}+ engine.start()++ @classmethod+ def from_pretrained(cls, ckpt, backbone_dir=None, mimi_dir=None, ecapa_dir=None, device="cuda", voices=True, **config):+ """from_pretrained("<release dir>") -- a Maya3 release directory (model.safetensors + backbone/ + voices/), resolved by+ maya3.hub.resolve (Mimi / ECAPA from the Hugging Face cache); or explicit (ckpt, backbone_dir, mimi_dir, ecapa_dir).+ voices: register the release's named voices (voices/voices.json). config: EngineConfig fields."""+ named = None+ if backbone_dir is None:+ from maya3 import hub+ r = hub.resolve(ckpt)+ ckpt, backbone_dir = r["ckpt"], r["backbone_dir"]+ mimi_dir, ecapa_dir = mimi_dir or r["mimi_dir"], ecapa_dir or r.get("ecapa_dir")+ named = r.get("voices_json")+ cfg = EngineConfig(**config)+ tts = cls(Engine(ckpt, backbone_dir, mimi_dir, cfg, device=device), ecapa_dir=ecapa_dir)+ if voices and named and os.path.exists(named):+ tts.load_named_voices(named)+ return tts++ def load_named_voices(self, voices_json, **kw):+ """Register the named (trained) voices listed in voices.json; see maya3.prompt.load_named_voices."""+ from maya3.prompt import load_named_voices+ ids = load_named_voices(self.engine.registry, voices_json, **kw)+ for vid in ids:+ v = self.engine.registry.get(vid)+ self.engine.call(lambda v=v: self.engine.prepare_voice(v))+ return ids++ # ------------------------------------------------------------------ voices+ @property+ def voices(self):+ return self.engine.registry.ids()++ def _embed(self, w):+ if self._ecapa is None:+ if self.ecapa_dir is None:+ raise ValueError("ecapa_dir is required for reference-audio voices")+ self._ecapa = Ecapa(self.ecapa_dir, self.engine.device)+ return self._ecapa(w)++ def make_voice(self, voice_id, ref_audio=None, ref_text=None, lang=None, mode="icl_spk", ref_codes=None, ecapa=None,+ builder=None, meta=None):+ """Build a Voice from a reference clip (audio + its transcript + its language) or precomputed codes/ECAPA."""+ mode = norm_mode(mode)+ clips = []+ if ref_audio is not None or ref_codes is not None:+ if ref_codes is None:+ w = load_audio(ref_audio)+ if len(w) > 30 * SR:+ raise ValueError("reference audio longer than 30 s; 3-10 s works best")++ def enc():+ x = torch.as_tensor(w, device=self.engine.device)[None, None]+ return self.engine.mimi.encode(x, num_quantizers=32).audio_codes[0].cpu().numpy().astype(np.int64)+ ref_codes = self.engine.call(enc)+ if ecapa is None and mode in ("spk", "icl_spk"):+ ecapa = self.engine.call(lambda: self._embed(w))+ if mode in ("icl", "icl_spk"):+ if not ref_text or not lang:+ raise ValueError("ref_text and lang (the reference clip's transcript and language) are required for cloning")+ clips = [{"text": ref_text, "codes": np.asarray(ref_codes, np.int64), "lang": lang}]+ v = Voice(voice_id, mode, clips=clips, ecapa=ecapa, builder=builder, meta=meta or {})+ self.engine.call(lambda: self.engine.prepare_voice(v))+ return v++ def register_voice(self, voice_id, ref_audio=None, ref_text=None, lang=None, mode="icl_spk", **kw):+ """Register (or replace) a named voice; its prefix KV and speaker memory are computed now and reused."""+ v = self.make_voice(voice_id, ref_audio, ref_text, lang, mode, **kw)+ self.engine.registry.add(v)+ return voice_id++ def remove_voice(self, voice_id):+ return self.engine.registry.remove(voice_id) is not None++ def _voice(self, voice, ref_audio, ref_text, ref_lang, mode):+ if ref_audio is None:+ return self.engine.registry.get(voice or "plain")+ if voice is not None and voice != "plain":+ raise ValueError("pass either voice=<registered/named voice> or ref_audio=, not both (a named voice with a reference "+ "clip was never trained)")+ h = hashlib.sha1()+ if isinstance(ref_audio, (str, os.PathLike)):+ st = os.stat(ref_audio)+ h.update(f"{os.path.abspath(ref_audio)}|{st.st_size}|{st.st_mtime_ns}".encode())+ else:+ h.update(np.asarray(load_audio(ref_audio)).tobytes())+ h.update(f"|{ref_text}|{ref_lang}|{mode}".encode())+ key = h.hexdigest()+ if key not in self._oneoff:+ if len(self._oneoff) > 64:+ self._oneoff.pop(next(iter(self._oneoff)))+ self._oneoff[key] = self.make_voice(f"oneoff-{key[:12]}", ref_audio, ref_text, ref_lang, mode)+ return self._oneoff[key]++ # ------------------------------------------------------------------ synthesis+ SAMPLING_KEYS = ("seed", "temperature", "top_k", "top_p", "repetition_penalty")++ def _prep_text(self, text, lang, normalize):+ if not normalize:+ return text+ from maya3.text import normalise_text # the bundled normaliser (digits, currency, URLs, ...)+ if isinstance(text, (list, tuple)):+ return [normalise_text(t, lang) for t in text]+ return normalise_text(text, lang)++ def stream(self, text, lang="en", voice=None, ref_audio=None, ref_text=None, ref_lang=None, mode="icl_spk",+ max_frames=None, timeout=300, normalize=False, info=None, seed=None, temperature=None, top_k=None,+ top_p=None, repetition_penalty=None):+ """Yield int16 PCM chunks (24 kHz) as they are generated.+ seed/temperature/top_k/top_p/repetition_penalty: per-request sampler settings (None = engine defaults).+ normalize: run the bundled text normaliser first (digits, currency, dates, URLs, ALL-CAPS names).+ info: optional dict that receives the end payload (reason, frames, ttfa_s, stops, ...)."""+ v = self._voice(voice, ref_audio, ref_text, ref_lang or lang, mode)+ sampling = {"seed": seed, "temperature": temperature, "top_k": top_k, "top_p": top_p,+ "repetition_penalty": repetition_penalty}+ q = queue.Queue()+ req = self.engine.submit(self._prep_text(text, lang, normalize), lang, v, on_event=lambda k, p: q.put((k, p)),+ max_frames=max_frames, sampling=sampling)+ try:+ while True:+ kind, payload = q.get(timeout=timeout)+ if kind == "audio":+ yield payload+ elif kind == "end":+ if info is not None:+ info.update(payload)+ self.last_info = payload+ return+ else:+ raise GenerationError(payload.get("code"), payload.get("error"))+ finally:+ req.cancel()++ def generate(self, text, lang="en", voice=None, ref_audio=None, ref_text=None, ref_lang=None, mode="icl_spk",+ max_frames=None, return_info=False, **kw):+ """Synthesise text -> float32 waveform (24 kHz). kw: normalize, seed, temperature, top_k, top_p, repetition_penalty."""+ info = {}+ chunks = list(self.stream(text, lang, voice, ref_audio, ref_text, ref_lang, mode, max_frames, info=info, **kw))+ wav = (np.concatenate(chunks).astype(np.float32) / 32767.0) if chunks else np.zeros(0, np.float32)+ return (wav, info) if return_info else wav++ async def astream(self, text, lang="en", voice=None, ref_audio=None, ref_text=None, ref_lang=None, mode="icl_spk",+ max_frames=None, info=None, normalize=False, **sampling):+ """asyncio variant of stream(); `info` (a dict) receives the end payload."""+ loop = asyncio.get_running_loop()+ q = asyncio.Queue()+ if ref_audio is not None:+ v = await asyncio.to_thread(self._voice, voice, ref_audio, ref_text, ref_lang or lang, mode)+ else:+ v = self.engine.registry.get(voice or "plain")+ req = self.engine.submit(self._prep_text(text, lang, normalize), lang, v,+ on_event=lambda k, p: loop.call_soon_threadsafe(q.put_nowait, (k, p)),+ max_frames=max_frames, sampling=sampling)+ try:+ while True:+ kind, payload = await q.get()+ if kind == "audio":+ yield payload+ elif kind == "end":+ if info is not None:+ info.update(payload)+ return+ else:+ raise GenerationError(payload.get("code"), payload.get("error"))+ finally:+ req.cancel()++ def close(self):+ self.engine.close()diff --git a/maya3/assets/duration_prior.json b/maya3/assets/duration_prior.jsonnew file mode 100644index 0000000..91eac3e--- /dev/null+++ b/maya3/assets/duration_prior.json@@ -0,0 +1,181 @@+{+ "form": "dur_s = c0 + c1*indic_letters + c2*latin_letters + c3*pauses + c4*digits",+ "langs": {+ "as": {+ "coef": [+ 0.0,+ 0.07962,+ 0.17764,+ 0.53121,+ 0.62254+ ],+ "n": 598,+ "ratio_p50": 0.937,+ "ratio_p99": 1.388,+ "ratio_p999": 1.487,+ "ratio_max": 1.501+ },+ "bn": {+ "coef": [+ 0.71369,+ 0.06604,+ 0.04537,+ 0.49869,+ 0.23288+ ],+ "n": 804,+ "ratio_p50": 0.974,+ "ratio_p99": 1.445,+ "ratio_p999": 1.66,+ "ratio_max": 1.689+ },+ "en": {+ "coef": [+ 2.87006,+ 0.01,+ 0.04601,+ 0.40336,+ 0.06541+ ],+ "n": 463,+ "ratio_p50": 0.959,+ "ratio_p99": 1.626,+ "ratio_p999": 1.861,+ "ratio_max": 1.971+ },+ "gu": {+ "coef": [+ 0.54378,+ 0.07044,+ 0.01,+ 0.50786,+ 0.24873+ ],+ "n": 534,+ "ratio_p50": 0.966,+ "ratio_p99": 1.511,+ "ratio_p999": 1.906,+ "ratio_max": 2.082+ },+ "hi": {+ "coef": [+ 2.44169,+ 0.05329,+ 0.02187,+ 0.43341,+ 0.37052+ ],+ "n": 506,+ "ratio_p50": 0.961,+ "ratio_p99": 1.622,+ "ratio_p999": 1.816,+ "ratio_max": 1.872+ },+ "kn": {+ "coef": [+ 1.71201,+ 0.06651,+ 0.01,+ 0.45228,+ 0.5053+ ],+ "n": 691,+ "ratio_p50": 0.968,+ "ratio_p99": 1.543,+ "ratio_p999": 1.72,+ "ratio_max": 1.798+ },+ "ml": {+ "coef": [+ 0.92428,+ 0.05706,+ 0.11842,+ 0.52651,+ 0.41106+ ],+ "n": 867,+ "ratio_p50": 0.98,+ "ratio_p99": 1.509,+ "ratio_p999": 1.957,+ "ratio_max": 2.227+ },+ "mr": {+ "coef": [+ 1.44052,+ 0.0719,+ 0.03206,+ 0.30526,+ 0.28705+ ],+ "n": 423,+ "ratio_p50": 0.962,+ "ratio_p99": 1.379,+ "ratio_p999": 1.585,+ "ratio_max": 1.667+ },+ "or": {+ "coef": [+ 0.0,+ 0.08134,+ 0.12578,+ 0.43209,+ 0.23588+ ],+ "n": 940,+ "ratio_p50": 0.947,+ "ratio_p99": 1.414,+ "ratio_p999": 2.078,+ "ratio_max": 2.493+ },+ "pa": {+ "coef": [+ 0.57673,+ 0.07431,+ 0.01,+ 0.39355,+ 0.37283+ ],+ "n": 529,+ "ratio_p50": 0.962,+ "ratio_p99": 1.536,+ "ratio_p999": 1.821,+ "ratio_max": 1.823+ },+ "ta": {+ "coef": [+ 2.05273,+ 0.05244,+ 0.01,+ 0.47524,+ 0.45486+ ],+ "n": 843,+ "ratio_p50": 0.96,+ "ratio_p99": 1.452,+ "ratio_p999": 1.574,+ "ratio_max": 1.592+ },+ "te": {+ "coef": [+ 0.45026,+ 0.07269,+ 0.0576,+ 0.46093,+ 0.39692+ ],+ "n": 703,+ "ratio_p50": 0.969,+ "ratio_p99": 1.487,+ "ratio_p999": 1.832,+ "ratio_max": 2.149+ }+ },+ "ratio_all": {+ "0.5": 0.963,+ "0.9": 1.203,+ "0.99": 1.505,+ "0.995": 1.628,+ "0.999": 1.828,+ "max": 2.493+ }+}\ No newline at end of filediff --git a/maya3/bench/__init__.py b/maya3/bench/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/maya3/bench/bench_engine.py b/maya3/bench/bench_engine.pynew file mode 100644index 0000000..3b358f5--- /dev/null+++ b/maya3/bench/bench_engine.py@@ -0,0 +1,117 @@+"""maya3.Engine latency/throughput bench (same protocol as baseline_fastbatch.py, through the public submit() path).++ B=1 : one request at a time; TTFA = submit -> first PCM chunk delivered to the callback (prompt build, prefix-KV copy,+ inline prefill, first frame, Mimi, D2H all included); RTF = wall / audio.+ N>1 : closed loop, N requests in flight; a finished request immediately submits the next; reps*N requests total.+ TTFA = submit -> first chunk (queue wait included). Tick p50/p99 from the engine.+Usage: bench_engine.py <model.pt> <out.json> [--seats 1,8,32,64,100] [--depth fp16] [--no-guards]+"""+import argparse, json, os, sys, threading, time+import numpy as np, torch+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))+from maya3.engine import Engine, EngineConfig, SR+from maya3.bench import common as C++ap = argparse.ArgumentParser()+ap.add_argument("ckpt"); ap.add_argument("out")+ap.add_argument("--seats", default="1,8,32,64,100"); ap.add_argument("--depth", default="fp16")+ap.add_argument("--no-guards", action="store_true"); ap.add_argument("--b1-n", type=int, default=40)+ap.add_argument("--reps", type=int, default=3); ap.add_argument("--capacity", type=int, default=2304)+ap.add_argument("--max-inline-rows", type=int, default=384); ap.add_argument("--max-admit", type=int, default=8)+ap.add_argument("--label", default="maya3"); ap.add_argument("--cb0-rep", type=float, default=None); ap.add_argument("--ramp-s", type=float, default=2.0)+A = ap.parse_args()+q = lambda x, p: round(float(np.quantile(x, p)), 4) if len(x) else None+rows = C.rows()+pack = C.load_pack()+res = {"ckpt": A.ckpt, "label": A.label, "depth": A.depth, "guards": not A.no_guards, "gpu": torch.cuda.get_device_name(), "runs": {}}+E = None+for N in [int(x) for x in A.seats.split(",")]:+ cfg = EngineConfig(max_seats=N, capacity=A.capacity, depth_dtype=A.depth, max_inline_rows=A.max_inline_rows,+ max_admit_per_tick=A.max_admit, free_reference_depth=False,+ **({} if A.cb0_rep is None else {"cb0_rep": A.cb0_rep})) # rebuilt per N below+ cfg.guards.enabled = not A.no_guards+ if E is None:+ E = Engine(A.ckpt, C.BACKBONE, C.MIMI, cfg)+ model, mimi, registry = E.model, E.mimi, E.registry+ else: # rebuild the fast components only (same weights)+ E.cfg = cfg; E.backbone = E.depth = E.codec = None; torch.cuda.empty_cache(); E._build_fast()+ vmap = C.register_pack_voices(E, pack, rows)+ t0 = time.time(); E.warmup(); warm = time.time() - t0+ for v in set(vmap.values()):+ E.prepare_voice(E.registry.get(v))+ E.start()+ reqs = [(r["pieces"][0], r["lang"], vmap[r["id"]], r["mode"]) for r in rows]+ lock = threading.Lock()+ rec = {"warmup_s": round(warm, 1)}+ # extra warm-up through the live loop+ ev = threading.Event(); E.submit(reqs[0][0], reqs[0][1], reqs[0][2], on_event=lambda k, p: ev.set() if k != "audio" else None); ev.wait(60)+ torch.cuda.reset_peak_memory_stats(); E.tick_ms.clear()+ if N == 1:+ ttfa, rtf, audio = {"plain": [], "icl_spk": []}, {"plain": [], "icl_spk": []}, 0.0+ tw = time.time()+ for i, (text, lang, vid, mode) in enumerate(reqs[:A.b1_n]):+ done = threading.Event(); info = {}+ t_sub = time.perf_counter()+ first = []+ def cb(k, p, first=first, info=info, done=done):+ if k == "audio":+ if not first: first.append(time.perf_counter())+ else:+ info.update(p if isinstance(p, dict) else {}); info["kind"] = k; done.set()+ E.submit(text, lang, vid, on_event=cb, split=False)+ done.wait(120)+ if info.get("kind") != "end" or not first: continue+ ttfa[mode].append(first[0] - t_sub); rtf[mode].append(info["wall_s"] / max(info["audio_s"], 1e-3)); audio += info["audio_s"]+ wall = time.time() - tw+ rec.update({"n_req": A.b1_n, "audio_s_per_s": round(audio / wall, 2)})+ for m in ttfa:+ rec[m] = {"n": len(ttfa[m]), "ttfa_ms_p50": round(q(ttfa[m], .5) * 1e3, 1), "ttfa_ms_p90": round(q(ttfa[m], .9) * 1e3, 1),+ "ttfa_ms_p99": round(q(ttfa[m], .99) * 1e3, 1), "rtf_p50": q(rtf[m], .5), "rtf_p90": q(rtf[m], .9)}+ else:+ total = A.reps * N+ state = {"sent": 0, "done": 0, "audio": 0.0}+ tt, rt, reasons, steady = [], [], {}, []+ alldone = threading.Event()+ def send():+ with lock:+ if state["sent"] >= total: return+ i = state["sent"]; state["sent"] += 1+ text, lang, vid, mode = reqs[i % len(reqs)]+ t_sub = time.perf_counter(); first = []+ def cb(k, p):+ if k == "audio":+ if not first: first.append(time.perf_counter())+ return+ with lock:+ state["done"] += 1+ if k == "end":+ tt.append(first[0] - t_sub if first else None); rt.append(p["wall_s"] / max(p["audio_s"], 1e-3))+ if t_sub - tw0[0] > A.ramp_s + 1.0 and first: steady.append((first[0] - t_sub, rt[-1]))+ state["audio"] += p["audio_s"]; reasons[p["reason"]] = reasons.get(p["reason"], 0) + 1+ else:+ reasons[p.get("code")] = reasons.get(p.get("code"), 0) + 1+ fin = state["done"] >= total+ if fin: alldone.set()+ else: send()+ E.submit(text, lang, vid, on_event=cb, split=False)+ tw = time.time(); tw0 = [time.perf_counter()]+ for i in range(N): threading.Timer(A.ramp_s * i / N, send).start()+ alldone.wait(3600)+ wall = time.time() - tw+ tt = [x for x in tt if x is not None]+ tk = sorted(E.tick_ms)+ rec.update({"n_req": total, "wall_s": round(wall, 1), "audio_s": round(state["audio"], 1),+ "audio_s_per_s": round(state["audio"] / wall, 2), "ttfa_ms_p50": round(q(tt, .5) * 1e3, 1),+ "ttfa_ms_p99": round(q(tt, .99) * 1e3, 1), "rtf_p50": q(rt, .5), "rtf_p99": q(rt, .99), "reasons": reasons, "ramp_s": A.ramp_s,+ "steady": {"n": len(steady), "ttfa_ms_p50": round(q([a for a, _ in steady], .5) * 1e3, 1) if steady else None,+ "ttfa_ms_p99": round(q([a for a, _ in steady], .99) * 1e3, 1) if steady else None,+ "rtf_p99": q([b for _, b in steady], .99) if steady else None},+ "tick_ms_p50": round(tk[len(tk) // 2], 2), "tick_ms_p99": round(tk[int(len(tk) * .99)], 2)})+ rec["peak_alloc_gb"] = round(torch.cuda.max_memory_allocated() / 1e9, 2)+ rec["phase_ms_last"] = E.phase_ms+ rec["stats"] = dict(E.stats)+ E.close(); E._thread = None; E._stop = False+ res["runs"][f"N{N}"] = rec+ print(f"N={N}", json.dumps(rec), flush=True)+ json.dump(res, open(A.out, "w"), indent=1)+print("BENCH_DONE")diff --git a/maya3/bench/common.py b/maya3/bench/common.pynew file mode 100644index 0000000..51fcdb0--- /dev/null+++ b/maya3/bench/common.py@@ -0,0 +1,39 @@+"""Shared bench helpers: default asset paths (env-overridable), row loading, pack voices."""+import json, os+import numpy as np+H = os.path.expanduser("~")+ASSETS = os.environ.get("M3_ASSETS", "assets") # bench/test assets dir (backbone/, pack/, ...)+HF = os.environ.get("HF_HOME", f"{H}/.cache/huggingface")+BACKBONE = os.environ.get("M3_BACKBONE", f"{ASSETS}/backbone")+MIMI = f"{HF}/hub/models--kyutai--mimi/snapshots/89091b3e466eb6a9d11e537bf26b144f194978f7"+ECAPA = f"{HF}/hub/models--speechbrain--spkrec-ecapa-voxceleb/snapshots/0f99f2d0ebe89ac095bcc5903c4dd8f72b367286"+ROWS = os.environ.get("INFER_ROWS", "rows.jsonl")+++def load_pack(pack_dir=f"{ASSETS}/pack", codes_dir=f"{ASSETS}/speaker_pack_v1"):+ refs = json.load(open(f"{pack_dir}/refs.json"))+ ec = np.load(f"{pack_dir}/ecapa.npz")+ return {r["pack_uid"]: dict(r, codes=np.load(f"{codes_dir}/{r['code_file']}").astype(np.int64),+ ecapa=ec[r["pack_uid"]].astype(np.float32), text=r["text_train"]) for r in refs}+++def rows(path=ROWS):+ return [json.loads(l) for l in open(path) if l.strip()]+++def register_pack_voices(engine, pack, rows_):+ """One registry voice per (ref_uid, mode) used by the rows; returns row -> voice id."""+ from maya3.prompt import Voice+ out = {}+ for r in rows_:+ if r.get("voice"): # named (trained) voice selected by name+ out[r["id"]] = r["voice"]; continue+ if not r.get("ref_uid") or r["mode"] == "plain":+ out[r["id"]] = "plain"; continue+ vid = f"{r['ref_uid']}|{r['mode']}"+ if vid not in engine.registry:+ p = pack[r["ref_uid"]]+ engine.registry.add(Voice(vid, r["mode"], clips=[{"text": p["text"], "codes": p["codes"], "lang": p["lang_final"]}],+ ecapa=p["ecapa"]))+ out[r["id"]] = vid+ return outdiff --git a/maya3/bench/load_ws.py b/maya3/bench/load_ws.pynew file mode 100644index 0000000..8cba6a0--- /dev/null+++ b/maya3/bench/load_ws.py@@ -0,0 +1,285 @@+"""Closed-loop WebSocket load client for maya3/server.py.++ python -m maya3.bench.load_ws --url ws://127.0.0.1:8080/v1/tts/stream --texts sets/infer300.jsonl \\+ --lanes 32 --duration 180 --ramp-s 5 --out /tmp/load_32.json++Each lane holds one WebSocket and keeps exactly one utterance in flight (send speak -> wait for end/error -> next).+Texts come from a jsonl (field `pieces[0]`, else `text`; language from `lang`), shuffled with --seed.+Per request: TTFA (speak sent -> first audio received), playback stalls (playback starts when the first audio+arrives (+ --prebuffer-ms); a chunk arriving more than 100 ms after the playback buffer ran dry is a stall),+RTF = (end received - sent) / audio seconds, audio_s, server-reported ttfa/reason.+Requests are started only inside the --duration window; in-flight ones are drained and counted.+audio_s_per_s counts audio received inside the window. Output: JSON summary (p50/p90/p99) to stdout / --out.+"""+from __future__ import annotations++import argparse+import asyncio+import base64+import collections+import json+import random+import struct+import sys+import time+from pathlib import Path++SR = 24000+STALL_S = 0.100+++def pct(values):+ v = sorted(x for x in values if x is not None)+ if not v:+ return {"n": 0, "p50": None, "p90": None, "p99": None, "max": None, "mean": None}++ def at(p):+ i = (len(v) - 1) * p+ lo = int(i)+ hi = min(lo + 1, len(v) - 1)+ return v[lo] + (v[hi] - v[lo]) * (i - lo)+ return {"n": len(v), "p50": round(at(.5), 4), "p90": round(at(.9), 4), "p99": round(at(.99), 4),+ "max": round(v[-1], 4), "mean": round(sum(v) / len(v), 4)}+++class Playback:+ """Real-time playback simulation of one utterance."""++ def __init__(self, sent, prebuffer_s=0.0):+ self.sent, self.prebuffer = sent, prebuffer_s+ self.first = None+ self.dry = None # time the playback buffer runs dry+ self.audio_s = 0.0+ self.stalls = 0+ self.stall_s = 0.0+ self.max_gap_s = 0.0+ self.arrivals = [] # (t_rel_to_run_start, audio_s) for the audio-in-window metric++ def add(self, t, nbytes):+ dur = nbytes / (2 * SR)+ if self.first is None:+ self.first = t+ self.dry = t + self.prebuffer+ gap = t - self.dry+ if gap > 0:+ self.max_gap_s = max(self.max_gap_s, gap)+ if gap > STALL_S:+ self.stalls += 1+ self.stall_s += gap+ self.dry = max(t, self.dry) + dur+ self.audio_s += dur+ return dur+++def load_texts(path, langs=None, field="pieces"):+ rows = []+ for line in Path(path).read_text().splitlines():+ if not line.strip():+ continue+ r = json.loads(line)+ lang = r.get("lang")+ if langs and lang not in langs:+ continue+ t = r.get(field)+ if isinstance(t, list):+ t = t[0] if t else None+ t = t or r.get("text")+ if isinstance(t, str) and t.strip():+ rows.append({"id": r.get("id"), "lang": lang, "text": t.strip()})+ if not rows:+ raise SystemExit(f"no usable rows in {path} (langs={langs})")+ return rows+++def parse_binary(data):+ (n,) = struct.unpack_from("<I", data)+ return data[4:4 + n].decode(), len(data) - 4 - n+++async def one_request(ws, row, args, lane, seq, run_start):+ import aiohttp+ cid = f"l{lane}-{seq}"+ msg = {"type": "speak", "context_id": cid, "text": row["text"], "language": row["lang"], "binary": args.binary}+ if args.voice:+ msg["voice"] = args.voice+ if args.max_frames:+ msg["max_frames"] = args.max_frames+ sent = time.perf_counter()+ pb = Playback(sent, args.prebuffer_ms / 1000)+ rec = {"lane": lane, "seq": seq, "id": row["id"], "lang": row["lang"], "chars": len(row["text"]),+ "sent_s": round(sent - run_start, 4), "status": "error", "code": None}+ try:+ await ws.send_json(msg)+ async with asyncio.timeout(args.timeout):+ while True:+ m = await ws.receive()+ t = time.perf_counter()+ if m.type == aiohttp.WSMsgType.BINARY:+ c, n = parse_binary(m.data)+ if c != cid:+ raise RuntimeError(f"audio for unexpected context {c}")+ pb.arrivals.append((t - run_start, pb.add(t, n)))+ continue+ if m.type != aiohttp.WSMsgType.TEXT:+ raise ConnectionError(f"socket closed ({m.type.name})")+ f = json.loads(m.data)+ if f.get("context_id") not in (cid, None):+ raise RuntimeError(f"frame for unexpected context {f.get('context_id')}")+ kind = f.get("type")+ if kind == "audio":+ n = len(base64.b64decode(f["audio"]))+ pb.arrivals.append((t - run_start, pb.add(t, n)))+ elif kind == "end":+ rec.update(status="ok" if pb.audio_s > 0 else "error", code=None if pb.audio_s > 0 else "no_audio",+ reason=f.get("reason"), server_ttfa_ms=f.get("ttfa_ms"), frames=f.get("frames"))+ break+ elif kind == "error":+ rec.update(code=f.get("code"), error=f.get("error"))+ break+ elif kind == "pong":+ continue+ except TimeoutError:+ rec.update(code="client_timeout")+ try:+ await ws.send_json({"type": "cancel", "context_id": cid})+ except Exception:+ pass+ except (ConnectionError, RuntimeError) as exc:+ rec.update(code="connection", error=str(exc))+ end = time.perf_counter()+ rec.update(ttfa_ms=round((pb.first - sent) * 1000, 2) if pb.first else None,+ e2e_ms=round((end - sent) * 1000, 2), audio_s=round(pb.audio_s, 4),+ rtf=round((end - sent) / pb.audio_s, 4) if pb.audio_s else None,+ stalls=pb.stalls, stall_ms=round(pb.stall_s * 1000, 2), max_gap_ms=round(pb.max_gap_s * 1000, 2))+ return rec, pb.arrivals+++async def lane_loop(session, lane, args, rows, run_start, stop_at, out, arrivals):+ if args.ramp_s > 0 and args.lanes > 1:+ await asyncio.sleep(args.ramp_s * lane / args.lanes)+ rng = random.Random(args.seed * 1000 + lane)+ order = list(range(len(rows)))+ rng.shuffle(order)+ seq = 0+ ws = None+ while time.perf_counter() < stop_at:+ if ws is None or ws.closed:+ try:+ ws = await session.ws_connect(args.url, max_msg_size=64 * 1024 * 1024, heartbeat=None)+ meta = await ws.receive_json(timeout=30)+ if meta.get("type") != "metadata" or meta.get("sample_rate") != SR:+ raise RuntimeError(f"bad metadata {meta}")+ except Exception as exc:+ out.append({"lane": lane, "seq": seq, "status": "error", "code": "connect", "error": str(exc),+ "sent_s": round(time.perf_counter() - run_start, 4)})+ ws = None+ await asyncio.sleep(1.0)+ continue+ row = rows[order[seq % len(order)]]+ rec, arr = await one_request(ws, row, args, lane, seq, run_start)+ out.append(rec)+ arrivals.extend(arr)+ seq += 1+ if rec["status"] != "ok":+ if rec["code"] in ("connection", "client_timeout"):+ await ws.close()+ ws = None+ await asyncio.sleep(args.error_backoff_ms / 1000)+ if ws is not None:+ await ws.close()+++async def run(args):+ import aiohttp+ rows = load_texts(args.texts, set(args.langs.split(",")) if args.langs else None)+ http = args.url.replace("ws://", "http://").replace("wss://", "https://").split("/v1/")[0]+ timeout = aiohttp.ClientTimeout(total=None, sock_connect=30)+ async with aiohttp.ClientSession(timeout=timeout, connector=aiohttp.TCPConnector(limit=0)) as session:+ async def health():+ try:+ async with session.get(http + "/health", timeout=aiohttp.ClientTimeout(total=10)) as r:+ return await r.json()+ except Exception as exc:+ return {"error": str(exc)}+ h0 = await health()+ out, arrivals = [], []+ run_start = time.perf_counter()+ stop_at = run_start + args.duration+ await asyncio.gather(*(lane_loop(session, i, args, rows, run_start, stop_at, out, arrivals)+ for i in range(args.lanes)))+ elapsed = time.perf_counter() - run_start+ h1 = await health()+ window = min(args.duration, elapsed)+ ok = [r for r in out if r["status"] == "ok"]+ errors = collections.Counter(r["code"] for r in out if r["status"] != "ok")+ audio_win = sum(a for t, a in arrivals if t <= window)+ summary = {+ "config": {k: (str(v) if isinstance(v, Path) else v) for k, v in vars(args).items()},+ "duration_s": round(window, 3), "elapsed_with_drain_s": round(elapsed, 3),+ "requests": len(out), "completed": len(ok), "errors": dict(errors),+ "error_pct": round(100 * (len(out) - len(ok)) / max(1, len(out)), 3),+ "req_per_s": round(len(ok) / window, 4) if window else None,+ "audio_s_per_s": round(audio_win / window, 4) if window else None,+ "audio_s_per_s_with_drain": round(sum(r.get("audio_s") or 0 for r in out) / elapsed, 4) if elapsed else None,+ "ttfa_ms": pct(r["ttfa_ms"] for r in ok),+ "server_ttfa_ms": pct(r.get("server_ttfa_ms") for r in ok),+ "rtf": pct(r["rtf"] for r in ok),+ "e2e_ms": pct(r["e2e_ms"] for r in ok),+ "audio_s": pct(r["audio_s"] for r in ok),+ "stalls": sum(r.get("stalls", 0) for r in out),+ "stalled_request_pct": round(100 * sum(r.get("stalls", 0) > 0 for r in ok) / max(1, len(ok)), 3),+ "stall_ms_per_audio_min": round(60 * sum(r.get("stall_ms", 0) for r in ok) / max(1e-9, sum(r["audio_s"] for r in ok)), 3)+ if ok else None,+ "max_gap_ms": pct(r.get("max_gap_ms") for r in ok),+ "reasons": dict(collections.Counter(r.get("reason") for r in ok)),+ "by_lang": {lang: {"n": len(rs), "ttfa_ms_p90": pct(r["ttfa_ms"] for r in rs)["p90"],+ "rtf_p90": pct(r["rtf"] for r in rs)["p90"], "stalls": sum(r["stalls"] for r in rs)}+ for lang, rs in sorted(_group(ok, "lang").items())},+ "health_before": h0, "health_after": h1,+ }+ if args.per_request:+ summary["per_request"] = out+ return summary+++def _group(rows, key):+ g = collections.defaultdict(list)+ for r in rows:+ g[r.get(key)].append(r)+ return g+++def build_parser():+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])+ ap.add_argument("--url", default="ws://127.0.0.1:8080/v1/tts/stream")+ ap.add_argument("--texts", required=True, type=Path, help="jsonl with pieces[0] (or text) and lang")+ ap.add_argument("--lanes", type=int, default=8)+ ap.add_argument("--duration", type=float, default=60.0, help="seconds during which new requests are started")+ ap.add_argument("--ramp-s", type=float, default=0.0, help="stagger lane starts over this many seconds")+ ap.add_argument("--langs", default=None, help="comma list filter, e.g. hi,en,te")+ ap.add_argument("--voice", default=None)+ ap.add_argument("--max-frames", type=int, default=None)+ ap.add_argument("--binary", action="store_true", help="binary audio frames instead of base64 JSON")+ ap.add_argument("--prebuffer-ms", type=float, default=0.0, help="client playback prebuffer before starting playback")+ ap.add_argument("--timeout", type=float, default=180.0, help="per-request timeout (s)")+ ap.add_argument("--error-backoff-ms", type=float, default=100.0)+ ap.add_argument("--seed", type=int, default=0)+ ap.add_argument("--per-request", action="store_true", help="include every request record in the JSON")+ ap.add_argument("--out", type=Path, default=None)+ return ap+++def main(argv=None):+ args = build_parser().parse_args(argv)+ summary = asyncio.run(run(args))+ text = json.dumps(summary, indent=2, ensure_ascii=False)+ if args.out:+ args.out.parent.mkdir(parents=True, exist_ok=True)+ args.out.write_text(text)+ brief = {k: summary[k] for k in ("requests", "completed", "errors", "audio_s_per_s", "stalls", "stalled_request_pct")}+ brief.update(ttfa_ms=summary["ttfa_ms"], rtf=summary["rtf"])+ print(json.dumps(brief, indent=1) if args.out else text, file=sys.stdout)+++if __name__ == "__main__":+ main()diff --git a/maya3/client.py b/maya3/client.pynew file mode 100644index 0000000..653e08a--- /dev/null+++ b/maya3/client.py@@ -0,0 +1,267 @@+"""Small clients for the Maya3 server (maya3/server.py). Audio is 24 kHz mono; WS audio is always s16le PCM, HTTP+returns wav / pcm / mp3 / opus (Ogg) / flac. Extra keyword arguments are sent as request fields: seed, temperature,+top_k, top_p, repetition_penalty, normalize (default true on the server).++Sync (standard library only):+ from maya3.client import Maya3Client+ c = Maya3Client("http://127.0.0.1:8080")+ c.speech("नमस्ते, आप कैसे हैं?", "out.wav", language="hi") # streamed to the file+ c.speech("Hello there.", "out.mp3", language="en", seed=7) # format from the suffix (.ogg/.opus -> opus)+ for pcm in c.iter_speech("Hello there.", language="en"): ... # raw PCM bytes as they arrive+ c.register_voice("asha", "asha.wav", ref_text="...", lang="hi"); c.voices(); c.remove_voice("asha")++Async (aiohttp):+ from maya3.client import Maya3Stream, aspeech+ async with Maya3Stream("ws://127.0.0.1:8080/v1/tts/stream") as s:+ async for pcm in s.speak("Hello there.", language="en", voice="plain"): ...+ # several s.speak(...) iterators may run concurrently on one socket; s.last_end[context_id] has the end info+ await aspeech("Hello", "out.wav", base_url="http://127.0.0.1:8080", language="en")+"""+from __future__ import annotations++import asyncio+import base64+import json+import struct+import urllib.error+import urllib.request+import uuid+from pathlib import Path++SR = 24000+++class Maya3Error(RuntimeError):+ def __init__(self, code, message, status=None):+ super().__init__(f"{code}: {message}" + (f" (HTTP {status})" if status else ""))+ self.code, self.message, self.status = code, message, status+++def _speech_body(text, language, voice, response_format, max_frames, extra):+ body = {"model": "maya3", "input": text, "voice": voice, "response_format": response_format}+ if language:+ body["language"] = language+ if max_frames:+ body["max_frames"] = max_frames+ body.update(extra)+ return body+++SUFFIX_FORMATS = {"wav": "wav", "pcm": "pcm", "raw": "pcm", "mp3": "mp3", "opus": "opus", "ogg": "opus", "flac": "flac"}+++def _format_for(out, response_format):+ if response_format:+ return response_format+ if not out:+ return "wav"+ return SUFFIX_FORMATS.get(Path(out).suffix.lstrip(".").lower(), "wav")+++def _http_error(status, raw):+ try:+ err = json.loads(raw)["error"]+ return Maya3Error(err.get("code"), err.get("message"), status)+ except Exception:+ return Maya3Error("http_error", raw[:300].decode("utf-8", "replace") if isinstance(raw, bytes) else str(raw), status)+++# ---------------------------------------------------------------------------------------------------- sync+class Maya3Client:+ def __init__(self, base_url="http://127.0.0.1:8080", timeout=300):+ self.base = base_url.rstrip("/")+ self.timeout = timeout++ def _open(self, method, path, body=None, headers=None):+ data = json.dumps(body).encode() if isinstance(body, dict) else body+ hdrs = {"Content-Type": "application/json"} if isinstance(body, dict) else {}+ hdrs.update(headers or {})+ req = urllib.request.Request(self.base + path, data=data, method=method, headers=hdrs)+ try:+ return urllib.request.urlopen(req, timeout=self.timeout)+ except urllib.error.HTTPError as e:+ raise _http_error(e.code, e.read()) from None++ def _json(self, method, path, body=None):+ with self._open(method, path, body) as r:+ return json.loads(r.read())++ def iter_speech(self, text, language=None, voice="plain", response_format="pcm", max_frames=None,+ chunk_bytes=3840, **extra):+ """Yield the response body (pcm: raw s16le) in chunks as it streams."""+ r = self._open("POST", "/v1/audio/speech", _speech_body(text, language, voice, response_format, max_frames, extra))+ with r:+ while True:+ b = r.read1(chunk_bytes) if hasattr(r, "read1") else r.read(chunk_bytes)+ if not b:+ return+ yield b++ def speech(self, text, out=None, language=None, voice="plain", response_format=None, max_frames=None, **extra):+ """Synthesize to `out` (path; format from its suffix: .wav/.pcm/.mp3/.opus/.ogg/.flac, else wav) or return the+ bytes when out is None."""+ fmt = _format_for(out, response_format)+ chunks = self.iter_speech(text, language, voice, fmt, max_frames, chunk_bytes=65536, **extra)+ if out is None:+ return b"".join(chunks)+ with open(out, "wb") as f:+ for b in chunks:+ f.write(b)+ return out++ def health(self):+ try:+ return self._json("GET", "/health")+ except Maya3Error as e:+ if e.status == 503:+ return {"ready": False, "error": e.message}+ raise++ def voices(self):+ return self._json("GET", "/v1/voices")["voices"]++ def register_voice(self, voice_id, ref_audio, ref_text=None, lang=None, mode="icl_spk", replace=False):+ """ref_audio: path or wav/flac bytes."""+ data = ref_audio if isinstance(ref_audio, (bytes, bytearray)) else Path(ref_audio).read_bytes()+ return self._json("POST", "/v1/voices", {"voice_id": voice_id, "ref_audio_b64": base64.b64encode(data).decode(),+ "ref_text": ref_text, "lang": lang, "mode": mode, "replace": replace})++ def remove_voice(self, voice_id):+ return self._json("DELETE", f"/v1/voices/{voice_id}")+++# ---------------------------------------------------------------------------------------------------- async+async def aspeech(text, out=None, base_url="http://127.0.0.1:8080", language=None, voice="plain", response_format=None,+ max_frames=None, session=None, **extra):+ """Async HTTP synthesis to a file (streamed) or to bytes."""+ import aiohttp+ fmt = _format_for(out, response_format)+ own = session is None+ session = session or aiohttp.ClientSession()+ try:+ async with session.post(base_url.rstrip("/") + "/v1/audio/speech",+ json=_speech_body(text, language, voice, fmt, max_frames, extra)) as r:+ if r.status != 200:+ raise _http_error(r.status, await r.read())+ if out is None:+ return await r.read()+ with open(out, "wb") as f:+ async for b in r.content.iter_any():+ f.write(b)+ return out+ finally:+ if own:+ await session.close()+++def parse_binary_frame(data):+ """WS binary audio frame -> (context_id, pcm bytes)."""+ (n,) = struct.unpack_from("<I", data)+ return data[4:4 + n].decode(), data[4 + n:]+++class Maya3Stream:+ """WebSocket client; demultiplexes concurrent contexts on one socket."""++ def __init__(self, url="ws://127.0.0.1:8080/v1/tts/stream", binary=False, session=None):+ self.url, self.binary = url, binary+ self._session, self._own = session, session is None+ self.ws = None+ self.metadata = None+ self.last_end = {}+ self._queues = {}+ self._reader = None++ async def __aenter__(self):+ return await self.connect()++ async def __aexit__(self, *exc):+ await self.close()++ async def connect(self):+ import aiohttp+ if self._session is None:+ self._session = aiohttp.ClientSession()+ self.ws = await self._session.ws_connect(self.url, max_msg_size=16 * 1024 * 1024)+ self.metadata = await self.ws.receive_json()+ self._reader = asyncio.create_task(self._read())+ return self++ async def _read(self):+ import aiohttp+ try:+ async for msg in self.ws:+ if msg.type == aiohttp.WSMsgType.BINARY:+ cid, pcm = parse_binary_frame(msg.data)+ item = ("audio", pcm)+ elif msg.type == aiohttp.WSMsgType.TEXT:+ m = json.loads(msg.data)+ cid = m.get("context_id")+ if m.get("type") == "audio":+ item = ("audio", base64.b64decode(m["audio"]))+ else:+ item = (m.get("type"), m)+ else:+ break+ q = self._queues.get(cid)+ if q is not None:+ q.put_nowait(item)+ elif cid is None and item[0] == "error": # socket-level error: fail every waiting context+ for q in self._queues.values():+ q.put_nowait(item)+ finally:+ for q in self._queues.values():+ q.put_nowait(("closed", None))++ async def speak(self, text, language=None, voice=None, context_id=None, max_frames=None, **extra):+ """Async iterator of PCM bytes for one utterance; breaking out early cancels it on the server.+ extra: seed, temperature, top_k, top_p, repetition_penalty, normalize."""+ cid = context_id or uuid.uuid4().hex[:12]+ q = self._queues[cid] = asyncio.Queue()+ msg = {"type": "speak", "context_id": cid, "text": text, "binary": self.binary}+ msg.update({k: v for k, v in extra.items() if v is not None})+ if language:+ msg["language"] = language+ if voice:+ msg["voice"] = voice+ if max_frames:+ msg["max_frames"] = max_frames+ done = False+ try:+ await self.ws.send_json(msg)+ while True:+ kind, payload = await q.get()+ if kind == "audio":+ yield payload+ elif kind == "end":+ done = True+ self.last_end[cid] = payload+ return+ elif kind == "error":+ done = True+ raise Maya3Error(payload.get("code"), payload.get("error"))+ elif kind == "closed":+ done = True+ raise Maya3Error("closed", "connection closed before the end of the utterance")+ finally:+ if not done and not self.ws.closed:+ try:+ await self.ws.send_json({"type": "cancel", "context_id": cid})+ except Exception:+ pass+ self._queues.pop(cid, None)++ async def close(self):+ if self.ws is not None:+ await self.ws.close()+ if self._reader is not None:+ await asyncio.gather(self._reader, return_exceptions=True)+ if self._own and self._session is not None:+ await self._session.close()+++async def stream_ws(text, url="ws://127.0.0.1:8080/v1/tts/stream", language=None, voice=None, max_frames=None, **extra):+ """One-shot WS streaming iterator of PCM bytes."""+ async with Maya3Stream(url) as s:+ async for pcm in s.speak(text, language, voice, max_frames=max_frames, **extra):+ yield pcmdiff --git a/maya3/engine.py b/maya3/engine.pynew file mode 100644index 0000000..ccb12af--- /dev/null+++ b/maya3/engine.py@@ -0,0 +1,694 @@+"""Maya3 streaming engine: one GPU-owner thread, continuous batching over seats, everything hot CUDA-graphed.++Per tick (one 80 ms Mimi frame for every active seat):+ 1. admit : new requests get a slot; the voice's cached prefix KV (reference span, constant per voice) is copied into+ the slot and only the target text is prefilled -- INSIDE the same graphed backbone step as the decode+ rows (inline prefill, serve/fast_backbone.StaticBackbone.step_mixed). Plain requests (no prefix) are+ prefilled entirely inline. So a new request's first frame is produced in its admission tick.+ 2. cb0 : controlled stop (tau 0.35 / hazard 0.6 / argmax AEOS, min frames) + cb0 sampling on the GPU, with the+ per-seat AEOS bias of the EOS-boost loop guard.+ 3. depth : 31 levels in one CUDA graph (serve/fast_depth.FastDepth), fp16 by default (closer to fp32 greedy than bf16).+ 4. mimi : one-frame static-state Mimi decode graph (serve/fast_codec.StaticMimi) -> int16 PCM on the GPU.+ 5. ONE device->host copy (stop codes, cb0, PCM) and ONE sync; then guards + delivery on the host.++Differences from the offline reference decoder used for the quality evals (FastBatch): prefix-KV reuse + inline+prefill instead of a full eager HF prefill per request, vectorised loop guard, one sync per tick, PCM as int16.+"""+from __future__ import annotations++import collections+import dataclasses+import gc+import itertools+import os+import sys+import threading+import time+from pathlib import Path+from typing import Callable, Optional++import numpy as np+import torch++ROOT = Path(__file__).resolve().parents[1]+for p in (ROOT, ROOT / "scripts"):+ if str(p) not in sys.path:+ sys.path.insert(0, str(p))+os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")++from maya3 import guards as G # noqa: E402+from maya3.prompt import DEFAULT_BUILDER, MODES, Voice, VoiceRegistry # noqa: E402++SR = 24000+FRAME = 1920+BUCKETS = (1, 2, 4, 8, 16, 24, 32, 48, 64, 80, 96, 112, 128, 160, 192, 224, 256)+ROW_BUCKETS = (1, 2, 4, 8, 16, 24, 32, 48, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 448, 512)+REASONS = {1: "aeos", 2: "aeos_argmax", 3: "aeos_tau", 4: "aeos_hazard"}+++class EngineConfig:+ max_seats: int = 16+ capacity: int = 2048 # backbone KV tokens per seat (prompt + generated frames)+ depth_dtype: str = "fp16" # fp16 | bf16 | fp32+ temp: float = 0.7 # depth sampler+ top_k: int = 64+ # cb0 sampler defaults = best setting of a sampler sweep (presence penalty 0.8 over the last 12 frames ++ # temperature 0.9; best stability objective, raw-text no-stop rate 0.79 -> 0.07 %)+ cb0_temp: float = 0.9+ cb0_top_k: int = 64+ cb0_top_p: float = 1.0+ cb0_rep: float = 0.8 # presence penalty: logit -= rep for every code seen in the last cb0_rep_win frames+ cb0_rep_win: int = 12+ hard_cap: int = 1500 # frames (120 s): absolute per-chunk ceiling+ max_inline_rows: int = 384 # prefill rows folded into one tick (protects running seats' tick time)+ max_admit_per_tick: int = 8+ busy_frac: float = 0.75 # above this seat occupancy, admit at most busy_admit per tick (smooths tick time)+ busy_admit: int = 4+ seed: int = 20261024+ guards: G.GuardConfig = dataclasses.field(default_factory=G.GuardConfig)+ gap_s: float = 0.15 # silence between the text pieces of one request+ chunk_s: float = 20.0 # long text is split into pieces of about this many seconds+ use_graphs: bool = True+ fuse_proj: bool = False # backbone: one GEMM for q|k|v and one for gate|up per layer+ fuse_rope: bool = True # backbone: fused q/k RMSNorm + RoPE + KV-cache write (Triton; implies fuse_proj)+ fused_norm: bool = False # backbone: F.rms_norm instead of the HF RMSNorm module+ fused_depth: bool = True # depth: Triton add+LayerNorm and one-kernel top-k sampler+ compile_depth: bool = False # Inductor-fuse the depth frame body before capture (measured: no gain; off)+ free_reference_depth: bool = True # drop the fp32 reference depth stack once FastDepth holds its own copy (-2.2 GB)+ verify_prefix: bool = False # debug: assert the cached prefix embedding equals the recomputed one+++class Request:+ """One synthesis request. on_event(kind, payload) is called from the engine thread:+ ('audio', np.int16 [n]) PCM 24 kHz mono, one or more frames+ ('end', dict) reason, frames, audio_s, ttfa_s, pieces, stops+ ('error', dict) code, error+ It must be cheap and non-blocking (put into a queue)."""+ _ids = itertools.count()++ def __init__(self, pieces, lang, voice: Voice, on_event, max_frames=None, rid=None, sampling=None):+ self.id = rid or f"r{next(self._ids)}"+ self.sampling = dict(sampling or {})+ self.pieces = list(pieces)+ self.lang = lang+ self.voice = voice+ self.on_event = on_event+ self.max_frames = max_frames+ self.cancelled = False+ self.t_submit = time.perf_counter()+ self.t_first = None+ self.k = 0 # current piece+ self.frames = 0+ self.stops = []+ self.done = False++ def cancel(self):+ self.cancelled = True+++def _check_sampling(sp):+ if not sp:+ return {}+ allowed = {"seed", "temperature", "top_k", "top_p", "repetition_penalty"}+ bad = set(sp) - allowed+ if bad:+ raise ValueError(f"unknown sampling keys {sorted(bad)}; allowed {sorted(allowed)}")+ out = {k: v for k, v in sp.items() if v is not None}+ if "temperature" in out and not 0.05 <= float(out["temperature"]) <= 2.0:+ raise ValueError("temperature must be in [0.05, 2.0]")+ if "top_k" in out and not 1 <= int(out["top_k"]) <= 2049:+ raise ValueError("top_k must be in [1, 2049]")+ if "top_p" in out and not 0.0 < float(out["top_p"]) <= 1.0:+ raise ValueError("top_p must be in (0, 1]")+ if "repetition_penalty" in out and not 0.0 <= float(out["repetition_penalty"]) <= 5.0:+ raise ValueError("repetition_penalty must be in [0, 5]")+ if "seed" in out:+ out["seed"] = int(out["seed"])+ return out+++class _Seat:+ __slots__ = ("req", "slot", "frames", "cap", "loose_cap", "minimum", "suspend", "boost_at", "n_boost", "hist", "new")++ def __init__(self, req, slot, cap, loose_cap, minimum, suspend, hist):+ self.req, self.slot, self.cap, self.loose_cap, self.minimum, self.suspend = req, slot, cap, loose_cap, minimum, suspend+ self.frames = 0+ self.boost_at = None+ self.n_boost = 0+ self.hist = np.full(hist, -1, np.int64)+ self.new = True+++class Engine:+ def __init__(self, ckpt, backbone_dir, mimi_dir, config: EngineConfig = None, device="cuda", registry=None,+ builder=DEFAULT_BUILDER, model_config=None, log=print):+ from transformers import MimiModel+ from tts.data.packing_v2 import PackerV2+ from tts.model.load_s3 import load_model_for_eval+ from scripts import s2_serve_controls as S+ self.S = S+ self.cfg = cfg = config or EngineConfig()+ self.device = device+ self.log = log+ torch.backends.cuda.enable_cudnn_sdp(False)+ torch.backends.cuda.matmul.allow_tf32 = False+ t0 = time.perf_counter()+ mcfg = {"model": {"backbone": str(backbone_dir), "attn": "sdpa"}, "data": {"max_tokens": 8192}}+ self.model, self.provenance = load_model_for_eval(str(ckpt), device=device, dtype=torch.bfloat16, cfg=mcfg,+ config=str(model_config or ROOT / "configs/s3_fresh_v1.yaml"),+ amortize_frac=1.0, require_anchor=True, verbose=False)+ self.model.depth.float()+ self.packer = PackerV2(self.model.backbone.tokenizer, self.model.backbone.token_ids, max_tokens=8192)+ self.prior = S.load_prior(str(ROOT / "configs/text_frames_prior.json"))+ self.dur = G.DurationPrior()+ self.mimi = MimiModel.from_pretrained(str(mimi_dir)).to(device).eval()+ self.load_s = time.perf_counter() - t0+ self.registry = registry or VoiceRegistry()+ self.builder = builder+ self._build_fast()+ self._pending = collections.deque()+ self._calls = collections.deque() # callables run on the engine thread between ticks (voice prep, encodes)+ self._cv = threading.Condition()+ self._stop = False+ self._thread = None+ self.stats = {"ticks": 0, "admitted": 0, "completed": 0, "prefix_hits": 0, "prefix_misses": 0, "fallback_prefill": 0}+ self.tick_ms = collections.deque(maxlen=20000)+ self.phase_ms = {}+ self.failed = None++ # ------------------------------------------------------------------ fast components+ def _build_fast(self):+ from serve.fast_backbone import StaticBackbone+ from serve.fast_depth import FastDepth+ from serve.fast_codec import StaticMimi+ cfg, dev = self.cfg, self.device+ n = cfg.max_seats+ buckets = tuple(b for b in BUCKETS if b < n) + (next(b for b in BUCKETS if b >= n),)+ rows = tuple(b for b in ROW_BUCKETS if b <= buckets[-1] + cfg.max_inline_rows)+ rows = rows + tuple(b for b in ROW_BUCKETS if b > rows[-1])[:1]+ self.buckets, self.row_buckets, self.max_rows = buckets, rows, rows[-1]+ ctx = tuple(c for c in (256, 512, 768, 1024, 1536, 2048, 3072) if c < cfg.capacity) + (cfg.capacity,)+ dt = {"bf16": torch.bfloat16, "fp16": torch.float16, "fp32": torch.float32}[cfg.depth_dtype]+ self.backbone = StaticBackbone(self.model.backbone, n, capacity=cfg.capacity, batch_buckets=rows, ctx_buckets=ctx,+ attention="triton", use_graphs=cfg.use_graphs,+ fuse_proj=cfg.fuse_proj, fused_norm=cfg.fused_norm, fuse_rope=cfg.fuse_rope)+ if cfg.compile_depth:+ import torch._dynamo as _dyn+ _dyn.config.cache_size_limit = max(64, _dyn.config.cache_size_limit)+ self.depth = FastDepth(self.model, n, dtype=dt, batch_buckets=buckets, seed=cfg.seed + 1, temp=cfg.temp, top_k=cfg.top_k,+ compile=cfg.compile_depth, fused=cfg.fused_depth)+ self.codec = StaticMimi(self.mimi, n, batch_buckets=buckets)+ if cfg.free_reference_depth and getattr(self.model.depth, "groups", None) is not None:+ d = self.model.depth # only spk_proj_* / null_mem are used after this (speaker memory); FastDepth has its own copy+ for name in ("groups", "cross", "heads", "code_lo", "code_up", "in_proj", "level_emb", "norm"):+ if hasattr(d, name):+ setattr(d, name, None)+ torch.cuda.empty_cache()+ m = n + 1+ D = self.model.backbone.d_model+ self.h = torch.zeros(m, D, device=dev, dtype=torch.bfloat16)+ self.feedback = torch.zeros_like(self.h)+ self.frames_t = torch.zeros(m, device=dev, dtype=torch.long)+ self.min_t = torch.zeros(m, device=dev, dtype=torch.long)+ self.hazard_t = torch.zeros(m, device=dev, dtype=torch.float32)+ self.aeos_bias = torch.zeros(m, device=dev, dtype=torch.float32)+ # per-slot sampler settings and RNG stream (per-request seed => reproducible output at a fixed batch composition)+ self.temp_t = torch.full((m,), cfg.cb0_temp, device=dev, dtype=torch.float32)+ self.topk_t = torch.full((m,), cfg.cb0_top_k, device=dev, dtype=torch.long)+ self.topp_t = torch.full((m,), cfg.cb0_top_p, device=dev, dtype=torch.float32)+ self.rep_t = torch.full((m,), cfg.cb0_rep, device=dev, dtype=torch.float32)+ self.seed_t = torch.zeros(m, device=dev, dtype=torch.int32)+ self.ctr_t = torch.zeros(m, device=dev, dtype=torch.int32)+ self.hist_t = torch.full((m, max(1, cfg.cb0_rep_win)), -1, device=dev, dtype=torch.long)+ import random as _random+ self._seed_rng = _random.Random(cfg.seed)+ self.generator = torch.Generator(device=dev).manual_seed(cfg.seed)+ self.free = list(range(n))[::-1]+ self.active = []+ self._any_rep = False # some active request overrides the presence penalty (host-side flag, no sync)+ self._any_top_p = cfg.cb0_top_p < 1.0+ # one pinned host buffer per tick: [B, 2 + FRAME/4] int64 view = stop code, cb0, PCM int16 packed+ self._host = torch.empty(n, 2 + FRAME // 4, dtype=torch.int64).pin_memory()+ self._evt = torch.cuda.Event()+ self.warm = False++ def warmup(self):+ t0 = time.perf_counter()+ self.backbone.warmup()+ self.depth.warmup()+ self.codec.warmup()+ torch.cuda.synchronize()+ # exercise the admission paths once (prefix KV build, inline prefill, cb0 kernels)+ v = self.registry.get("plain")+ for _ in range(2):+ done = threading.Event()+ r = Request(["Hello, this is a warmup."], "en", v, lambda k, p, d=done: d.set() if k != "audio" else None, max_frames=3)+ self._pending.append(r)+ while self._pending or self.active:+ self._tick()+ gc.collect()+ gc.freeze() # long-lived objects (model, graphs) leave the GC's scan set: no multi-ms pauses+ g0, g1, g2 = gc.get_threshold()+ gc.set_threshold(max(g0, 50000), g1, g2)+ self.warm = True+ self.warmup_s = time.perf_counter() - t0+ return self.warmup_s++ # ------------------------------------------------------------------ voices+ @torch.inference_mode()+ def prepare_voice(self, voice: Voice):+ """Pack the voice's prefix, compute speaker memory and the prefix backbone KV (once per voice)."""+ with voice.lock:+ if voice.mem is not None:+ return voice+ use_icl, use_mem = MODES[voice.mode]+ builder = voice.builder or self.builder+ voice.prefix = builder.prefix(self.packer, voice)+ voice.spk_refs = (np.asarray(voice.ecapa, np.float32).reshape(1, 192) if voice.ecapa is not None+ else np.zeros((1, 192), np.float32))+ refs_t = torch.as_tensor(voice.spk_refs, device=self.device)[None]+ voice.mem = self.model.depth.spk_memory(refs_t, "ecapa", null_mask=torch.tensor([not use_mem], device=self.device))+ voice.rmask = torch.ones(1, 1, dtype=torch.bool, device=self.device)+ voice.ts = int(voice.prefix["tokens"].shape[0]) if voice.prefix is not None else 0+ if voice.ts:+ # embed a dummy request to get the prefix embeddings exactly as the full prompt composes them+ ex = builder.example(self.packer, voice, "a", voice.ref_lang or "en")+ prompt, n = self.S.prompt_from_example(ex, self.model, self.device, torch.bfloat16, 32)+ emb = prompt[:, :voice.ts].to(torch.bfloat16)+ h, cache = self.model.backbone(emb, use_cache=True)+ voice.kv = [(l.keys[:, :, :voice.ts].clone(), l.values[:, :, :voice.ts].clone()) for l in cache.layers]+ voice.emb = emb.clone()+ del cache+ return voice++ # ------------------------------------------------------------------ public (thread-safe)+ def split(self, text, lang):+ return self.S.split_text(text, lang, self.prior, self.cfg.chunk_s) if self.cfg.chunk_s > 0 else [text]++ def submit(self, text, lang, voice="plain", on_event=None, max_frames=None, rid=None, split=True, sampling=None):+ """sampling: optional {seed, temperature, top_k, top_p, repetition_penalty} for codebook 0 (the depth decoder keeps the+ engine's temperature/top-k but draws from the request's seeded stream). Same seed + same text + same voice => same audio+ when the request runs alone (batched bf16 numerics may differ slightly with batch composition)."""+ sampling = _check_sampling(sampling)+ if isinstance(voice, str):+ voice = self.registry.get(voice)+ if not isinstance(text, (list, tuple)):+ if not isinstance(text, str) or not text.strip():+ raise ValueError("text must be a non-empty string")+ text = self.split(text.strip(), lang) if split else [text.strip()]+ req = Request(text, lang, voice, on_event or (lambda k, p: None), max_frames=max_frames, rid=rid, sampling=sampling)+ with self._cv:+ if self.failed:+ raise RuntimeError(f"engine failed: {self.failed}")+ self._pending.append(req)+ self._cv.notify()+ return req++ def call(self, fn, timeout=120):+ """Run fn() on the engine thread (between ticks) and return its result; direct call if the loop is not running."""+ if self._thread is None or threading.current_thread() is self._thread:+ with torch.inference_mode():+ return fn()+ box = {}+ ev = threading.Event()+ with self._cv:+ self._calls.append((fn, box, ev))+ self._cv.notify()+ if not ev.wait(timeout):+ raise TimeoutError("engine call timed out")+ if "error" in box:+ raise box["error"]+ return box["result"]++ def _run_calls(self):+ while self._calls:+ with self._cv:+ fn, box, ev = self._calls.popleft()+ try:+ box["result"] = fn()+ except Exception as exc:+ box["error"] = exc+ ev.set()++ def start(self):+ if self._thread is None:+ if not self.warm:+ self.warmup()+ self._thread = threading.Thread(target=self._loop, name="maya3-engine", daemon=True)+ self._thread.start()+ return self++ def close(self):+ with self._cv:+ self._stop = True+ self._cv.notify()+ if self._thread is not None:+ self._thread.join(timeout=10)++ def health(self):+ recent = list(self.tick_ms)[-2000:]+ rs = sorted(recent)+ return {"ready": self.warm and self.failed is None, "failed": self.failed, "active": len(self.active),+ "pending": len(self._pending), "max_seats": self.cfg.max_seats, **self.stats,+ "tick_ms_p50": rs[len(rs) // 2] if rs else None, "tick_ms_p99": rs[int(len(rs) * .99)] if rs else None,+ "phase_ms": self.phase_ms, **self._mem()}++ def _mem(self):+ try:+ return {"mem_alloc_gb": round(torch.cuda.memory_allocated() / 1e9, 2), "mem_reserved_gb": round(torch.cuda.memory_reserved() / 1e9, 2)}+ except Exception:+ return {}++ # ------------------------------------------------------------------ loop+ def _loop(self):+ try:+ with torch.inference_mode():+ while True:+ with self._cv:+ while not self._stop and not self._pending and not self.active and not self._calls:+ self._cv.wait(0.5)+ if self._stop:+ break+ self._run_calls()+ self._tick()+ except BaseException as exc: # pragma: no cover+ import traceback+ traceback.print_exc()+ self.failed = f"{type(exc).__name__}: {exc}"+ finally:+ with self._cv:+ jobs = list(self._pending) + [s.req for s in self.active]+ self._pending.clear()+ for r in jobs:+ self._emit(r, "error", {"code": "unavailable", "error": self.failed or "engine stopped"})+ self.active = []++ def _emit(self, req, kind, payload):+ try:+ req.on_event(kind, payload)+ except Exception: # a broken consumer must not kill the engine+ req.cancelled = True++ # ------------------------------------------------------------------ admission+ def _plan(self, req):+ """Build the prompt for req's current piece. Returns (prompt_emb [1,T,D] bf16, ts, cap, loose_cap, minimum, suspend)."""+ S, cfg = self.S, self.cfg+ voice = req.voice+ if voice.mem is None:+ self.prepare_voice(voice)+ text = req.pieces[req.k]+ builder = voice.builder or self.builder+ ex = builder.example(self.packer, voice, text, req.lang)+ prompt, n = S.prompt_from_example(ex, self.model, self.device, torch.bfloat16, 32)+ prompt = prompt.to(torch.bfloat16)+ ef, er = S.expected_frames(self.prior, req.lang, len(text))+ loose = min(cfg.hard_cap, int(2.0 * (ef + er) + 40))+ cap = loose+ g = cfg.guards+ if g.enabled:+ cap = min(cap, max(int(ef * 0.5) + 8, self.dur.cap_frames(text, req.lang, g.dur_k, g.dur_margin_s)))+ if req.max_frames: # total over all pieces of the request+ cap = min(cap, max(1, int(req.max_frames) - req.frames))+ minimum = max(4, int(0.5 * ef))+ if g.enabled and g.loop and g.aware_v2:+ suspend = G.suspend_windows_v2(text, req.lang, self.dur)+ else:+ suspend = G.tag_windows(text, req.lang, self.dur, g.tag_hold_s) if (g.enabled and g.loop and g.tag_aware and "[" in text) else ()+ return prompt, int(n), cap, loose, minimum, suspend++ def _bind(self, req, cap, loose, minimum, suspend):+ slot = self.free.pop()+ v = req.voice+ self.depth.set_speaker(slot, v.mem, v.rmask)+ self.codec.reset(slot)+ self.frames_t[slot] = 0+ self.min_t[slot] = minimum+ self.hazard_t[slot] = 0+ self.aeos_bias[slot] = 0+ sp, cfg = req.sampling, self.cfg+ if "seed" in sp and sp["seed"] is not None: # each piece of a multi-piece request gets its own derived stream+ seed = (int(sp["seed"]) * 1000003 + req.k * 7919) % (2 ** 31 - 1)+ else:+ seed = self._seed_rng.randrange(1, 2 ** 31 - 1)+ self.seed_t[slot] = seed+ self.ctr_t[slot] = 0+ self.depth.row_seed[slot] = (seed * 69069 + 1) % (2 ** 31 - 1)+ self.depth.row_ctr[slot] = 0+ self.temp_t[slot] = float(sp.get("temperature") or cfg.cb0_temp)+ self.topk_t[slot] = int(sp.get("top_k") or cfg.cb0_top_k)+ self.topp_t[slot] = float(sp.get("top_p") or cfg.cb0_top_p)+ self.rep_t[slot] = float(sp["repetition_penalty"] if sp.get("repetition_penalty") is not None else cfg.cb0_rep)+ self.hist_t[slot] = -1+ if float(sp.get("top_p") or 1.0) < 1.0:+ self._any_top_p = True+ if sp.get("repetition_penalty"):+ self._any_rep = True+ return _Seat(req, slot, cap, loose, minimum, suspend, self.cfg.guards.hist)++ def _admit(self):+ """Pop pending requests into seats. Returns (new seats, inline prefills [(slot, x)])."""+ new, prefills, rows = [], [], len(self.active)+ cap_admit = self.cfg.max_admit_per_tick+ if len(self.active) > self.cfg.busy_frac * self.cfg.max_seats:+ cap_admit = min(cap_admit, self.cfg.busy_admit)+ while self._pending and self.free and len(new) < cap_admit:+ with self._cv:+ req = self._pending[0]+ if req.cancelled:+ self._pending.popleft()+ self._emit(req, "error", {"code": "cancelled", "error": "cancelled"})+ continue+ try:+ prompt, n, cap, loose, minimum, suspend = self._plan(req)+ except Exception as exc:+ with self._cv:+ self._pending.popleft()+ self._emit(req, "error", {"code": "invalid_request", "error": f"{type(exc).__name__}: {exc}"})+ continue+ if n + cap + 2 > self.cfg.capacity:+ cap = self.cfg.capacity - n - 2+ if cap < 8:+ with self._cv:+ self._pending.popleft()+ self._emit(req, "error", {"code": "invalid_request",+ "error": f"prompt of {n} tokens leaves no room in KV capacity {self.cfg.capacity}"})+ continue+ v = req.voice+ ts = v.ts+ tokens = n - ts+ inline = 0 < tokens and rows + tokens <= self.max_rows+ if not inline and new:+ break # row budget for this tick is used; admit next tick+ with self._cv:+ self._pending.popleft()+ seat = self._bind(req, cap, loose, minimum, suspend)+ if self.cfg.verify_prefix and ts:+ assert torch.equal(prompt[:, :ts], v.emb), "cached prefix embedding differs from the recomputed prompt"+ if inline:+ if ts:+ self.backbone.load_prefix(seat.slot, v.kv, ts)+ self.stats["prefix_hits"] += 1+ else:+ self.backbone.lengths[seat.slot] = 0+ self.backbone.lengths_cpu[seat.slot] = 0+ prefills.append((seat.slot, prompt[0, ts:]))+ rows += tokens+ else: # prompt longer than one tick's row budget: eager HF prefill (from the cached prefix if any)+ from serve.cache import cache_from_owned_tensors+ if ts:+ h, cache = self.model.backbone(prompt[:, ts:], past_key_values=cache_from_owned_tensors(v.kv), use_cache=True)+ else:+ h, cache = self.model.backbone(prompt, use_cache=True)+ self.backbone.load_slot(seat.slot, cache, n)+ self.h[seat.slot] = h[0, -1]+ del cache+ self.stats["fallback_prefill"] += 1+ seat.new = "eager" # already has its hidden state; it decodes this tick without a backbone row+ new.append(seat)+ self.stats["admitted"] += 1+ return new, prefills++ # ------------------------------------------------------------------ one tick+ @torch.inference_mode()+ def _tick(self):+ t0 = time.perf_counter()+ cfg = self.cfg+ # cancelled seats leave before any work+ keep = []+ for s in self.active:+ if s.req.cancelled:+ self._release(s)+ self._emit(s.req, "error", {"code": "cancelled", "error": "cancelled"})+ else:+ keep.append(s)+ self.active = keep+ if self._pending and any(r.cancelled for r in self._pending):+ with self._cv:+ gone = [r for r in self._pending if r.cancelled]+ self._pending = collections.deque(r for r in self._pending if not r.cancelled)+ for r in gone:+ self._emit(r, "error", {"code": "cancelled", "error": "cancelled"})+ new, prefills = self._admit()+ t1 = time.perf_counter()+ dec = [s.slot for s in self.active]+ if dec or prefills:+ idx = torch.tensor(dec, device=self.device, dtype=torch.long) if dec else None+ if prefills:+ h, last = self.backbone.step_mixed(dec, self.feedback[idx] if dec else None, prefills)+ for (slot, _), hid in zip(prefills, last):+ self.h[slot] = hid+ else:+ h = self.backbone.step(dec, self.feedback[idx])+ if dec:+ self.h[idx] = h+ self.active = self.active + new+ if not self.active:+ return+ t2 = time.perf_counter()+ seats = self.active+ slots = [s.slot for s in seats]+ B = len(slots)+ idx = torch.tensor(slots, device=self.device, dtype=torch.long)+ h = self.h[idx]+ code, cb0 = self._cb0(h, idx)+ codes, fb = self.depth(slots, h, cb0)+ self.feedback[idx] = fb.to(self.feedback.dtype)+ pcm = self.codec.decode(slots, codes)+ pcm16 = (pcm.clamp(-1, 1) * 32767).round().to(torch.int16)+ packed = torch.cat([code[:, None], cb0[:, None], pcm16.view(torch.int64).view(B, FRAME // 4)], 1)+ host = self._host[:B]+ host.copy_(packed, non_blocking=True)+ self._evt.record()+ self._evt.synchronize()+ t3 = time.perf_counter()+ hv = host.numpy()+ stop_l = hv[:, 0].tolist()+ cb0_l = hv[:, 1]+ pcm_np = hv[:, 2:].view(np.int16)+ now = time.perf_counter()+ finished = []+ g = cfg.guards+ check = []+ for i, s in enumerate(seats):+ req = s.req+ s.new = False+ if stop_l[i]:+ finished.append((s, REASONS[stop_l[i]]))+ continue+ s.frames += 1+ req.frames += 1+ if req.t_first is None:+ req.t_first = now+ self._emit(req, "audio", pcm_np[i].copy())+ s.hist[:-1] = s.hist[1:]+ s.hist[-1] = cb0_l[i]+ if s.frames >= s.cap:+ if s.req.max_frames and s.req.frames >= s.req.max_frames:+ reason = "max_frames" # the caller's limit, not a model failure+ elif g.enabled and s.cap < s.loose_cap:+ reason = "cap_guard"+ else:+ reason = "cap"+ finished.append((s, reason))+ elif g.enabled and g.loop and s.frames >= g.start and s.frames % g.every == 0 and \+ not any(a <= s.frames <= b for a, b in s.suspend):+ check.append(i)+ if check:+ W = np.stack([seats[i].hist for i in check])+ n = np.array([seats[i].frames for i in check])+ hits = G.loop_detect_batch(W, n, g)+ fin_ids = {id(f[0]) for f in finished}+ for i, hit in zip(check, hits):+ s = seats[i]+ if id(s) in fin_ids:+ continue+ if hit is not None and g.mode == "boost":+ if s.boost_at is None:+ s.boost_at = s.frames+ s.n_boost += 1+ self.aeos_bias[s.slot] = g.boost+ if s.frames - s.boost_at >= g.backstop:+ finished.append((s, "loop_backstop"))+ elif hit is not None:+ finished.append((s, "loop_" + hit.split(":")[0]))+ elif s.boost_at is not None:+ self.aeos_bias[s.slot] = 0.0+ s.boost_at = None+ if finished:+ gone = set()+ for s, reason in finished:+ gone.add(id(s))+ self._release(s)+ self._finish_piece(s, reason)+ self.active = [s for s in self.active if id(s) not in gone]+ t4 = time.perf_counter()+ self.stats["ticks"] += 1+ self.tick_ms.append((t4 - t0) * 1e3)+ self.phase_ms = {"admit": round((t1 - t0) * 1e3, 2), "backbone": round((t2 - t1) * 1e3, 2),+ "frame": round((t3 - t2) * 1e3, 2), "host": round((t4 - t3) * 1e3, 2), "batch": B,+ "prefill_rows": sum(int(x.shape[0]) for _, x in prefills)}++ def _release(self, s):+ self.backbone.free(s.slot)+ self.aeos_bias[s.slot] = 0+ self.free.append(s.slot)++ def _finish_piece(self, s, reason):+ req = s.req+ req.stops.append({"reason": reason, "frames": s.frames, "cap": s.cap, "n_boost": s.n_boost})+ req.k += 1+ if req.k < len(req.pieces) and not req.cancelled and not (req.max_frames and req.frames >= req.max_frames):+ self._emit(req, "audio", np.zeros(int(self.cfg.gap_s * SR), np.int16))+ with self._cv:+ self._pending.appendleft(req) # next piece goes first: the stream continues without queueing+ return+ req.done = True+ self.stats["completed"] += 1+ self._emit(req, "end", {"reason": req.stops[-1]["reason"], "frames": req.frames, "audio_s": req.frames * FRAME / SR,+ "ttfa_s": (req.t_first - req.t_submit) if req.t_first else None,+ "wall_s": time.perf_counter() - req.t_submit, "pieces": len(req.pieces), "stops": req.stops})++ def _cb0(self, h, idx):+ """Controlled stop + cb0 sampling (same rule as the reference decoder and ServeSession.speak(stop='controlled')) for all seats, with+ per-seat temperature / top-k / top-p / presence penalty and a per-request Philox stream."""+ from tts.tokens import AEOS_CLASS+ from serve.fast_depth_kernels import row_exponential+ logits = self.model.backbone.cb0_logits(h).float() / self.temp_t[idx, None]+ logits[:, AEOS_CLASS] += self.aeos_bias[idx]+ rep = self.rep_t[idx]+ if self.cfg.cb0_rep_win > 0 and bool((self.cfg.cb0_rep > 0) or self._any_rep):+ hist = self.hist_t[idx]+ pen = torch.zeros_like(logits)+ pen.scatter_add_(1, hist.clamp_min(0), (hist >= 0).float())+ pen[:, AEOS_CLASS] = 0+ logits = logits - rep[:, None] * (pen > 0).float()+ srt = logits.sort(-1, descending=True).values+ kth = srt.gather(1, (self.topk_t[idx] - 1).clamp(0, logits.shape[1] - 1)[:, None])+ logits = logits.masked_fill(logits < kth, -float("inf"))+ if self._any_top_p:+ sp_, si = logits.softmax(-1).sort(-1, descending=True)+ drop = (sp_.cumsum(-1) - sp_) > self.topp_t[idx, None]+ logits = logits.masked_fill(torch.zeros_like(drop).scatter(1, si, drop), -float("inf"))+ probs = logits.softmax(-1)+ pa = probs[:, AEOS_CLASS]+ arg = probs.argmax(-1)+ frames = self.frames_t[idx]+ can = frames >= self.min_t[idx]+ hz = self.hazard_t[idx]+ hz = torch.where(can, 1 - (1 - hz) * (1 - pa), hz)+ code = torch.zeros_like(arg)+ code = torch.where(can & (hz >= .6), torch.full_like(code, 4), code)+ code = torch.where(can & (pa >= .35), torch.full_like(code, 3), code)+ code = torch.where(can & (arg == AEOS_CLASS), torch.full_like(code, 2), code)+ q = probs.clone()+ q[:, AEOS_CLASS] = 0+ q = q / q.sum(-1, keepdim=True).clamp_min(1e-12)+ E = row_exponential(q.shape[0], q.shape[1], self.seed_t[idx], self.ctr_t[idx], level=0)+ cb0 = (q / E).argmax(-1).clamp_max(AEOS_CLASS - 1)+ self.ctr_t[idx] += 1+ if self.cfg.cb0_rep_win > 0:+ self.hist_t[idx] = torch.cat([self.hist_t[idx, 1:], cb0[:, None]], 1)+ self.hazard_t[idx] = hz+ self.frames_t[idx] = frames + 1+ return code, cb0diff --git a/maya3/guards.py b/maya3/guards.pynew file mode 100644index 0000000..86a4e1e--- /dev/null+++ b/maya3/guards.py@@ -0,0 +1,146 @@+"""Engine-internal guards (zero latency, no user configuration, on by default).++Port of the guards used by the offline reference decoder (DurationPrior, loop_detect, and the FastBatch guard logic), with the+loop detector vectorised over seats (same decision per seat as guards.loop_detect; maya3/tests/test_guards.py).++ 1. duration cap : stop at 2.2 x expected + 1.2 s (digit/pause/language-aware prior), floor 0.5 x old-prior + 8 frames+ 2. loop guard : every 2 frames from frame 32, on the cb0 tail (last 96 frames): a 32-frame stall or a periodic+ pattern (c[t] == c[t-p] on >= 70 % of the last 64 frames, p = 2..16) ->+ EOS boost (+4 on the AEOS logit; the model ends the phrase itself), removed when the loop clears;+ a loop that persists 24 frames after the boost is stopped (loop_backstop).+ Tag-aware: suspended for [-0.5 s, +3 s] around each inline [tag]'s estimated time.+"""+from __future__ import annotations++import dataclasses+import json+import os+import re++import numpy as np++HERE = os.path.dirname(os.path.abspath(__file__))+PRIOR_PATH = os.environ.get("MAYA3_DUR_PRIOR", os.path.join(HERE, "assets", "duration_prior.json"))+PAUSE = re.compile(r"[,;:.!?।॥…\-]")+TAG = re.compile(r"\[[a-z ]+\]")+FRAME_S = 0.08+++def text_feats(t):+ letters = sum(1 for ch in t if ch.isalpha() or (0x900 <= ord(ch) <= 0xDFF))+ latin = sum(1 for ch in t if ch.isascii() and ch.isalpha())+ return np.array([1.0, letters - latin, latin, len(PAUSE.findall(t)), sum(ch.isdigit() for ch in t)])+++class DurationPrior:+ def __init__(self, path=PRIOR_PATH):+ d = json.load(open(path))+ self.coef = {l: np.array(v["coef"]) for l, v in d["langs"].items()}+ self.default = np.mean(list(self.coef.values()), 0)++ def expected_s(self, text, lang):+ return float(max(0.35, text_feats(text) @ self.coef.get(lang, self.default)))++ def cap_frames(self, text, lang, k=2.2, margin_s=1.2):+ return int((k * self.expected_s(text, lang) + margin_s) / FRAME_S)+++class GuardConfig:+ enabled: bool = True+ dur_k: float = 2.2+ dur_margin_s: float = 1.2+ loop: bool = True+ stall: int = 32+ period_win: int = 64+ period_thr: float = 0.7+ pmin: int = 2+ pmax: int = 16+ start: int = 32 # first frame the loop rule is evaluated+ every: int = 2+ mode: str = "boost" # boost | stop+ boost: float = 4.0+ backstop: int = 24+ tag_aware: bool = True+ tag_hold_s: float = 3.0+ hist: int = 96 # cb0 tail kept per seat+ # loop guard v2b windows (suspend_windows_v2): ON by default. Measured against the v1 windows on an eval subset with text+ # normalisation: real_fail_cq 1.16 -> 0.96 %, no-stop 0 -> 0, emotion CER 7.5 -> 5.6 %. MAYA3_GUARD_V2=0 restores v1 tag windows+ aware_v2: bool = os.environ.get("MAYA3_GUARD_V2", "1") == "1"+++def tag_windows(text, lang, prior, hold_s=3.0):+ out = []+ for m in TAG.finditer(text):+ t = prior.expected_s(text[:m.start()], lang) if m.start() > 0 else 0.0+ out.append((max(0, int((t - 0.5) / FRAME_S)), int((t + hold_s) / FRAME_S)))+ return tuple(out)+++def loop_detect_batch(W, n, cfg: GuardConfig):+ """W: [S, hist] int array, row i = the last `hist` cb0 codes of seat i, right-aligned (newest last; -1 = empty);+ n: [S] frames generated so far. Returns list of None | 'stall' | 'period:<p>' (guards.loop_detect semantics with+ min_frames=12 on the last 96 codes)."""+ S = W.shape[0]+ out = [None] * S+ if S == 0:+ return out+ st = cfg.stall+ tail = W[:, -st:]+ stall = (n >= max(12, st)) & (tail == tail[:, :1]).all(1)+ pw = cfg.period_win+ win = W[:, -pw:]+ can_p = n >= max(12, st, pw)+ hit_p = np.full(S, 0, np.int64)+ if can_p.any():+ for p in range(cfg.pmin, cfg.pmax + 1):+ frac = (win[:, p:] == win[:, :-p]).mean(1)+ new = (hit_p == 0) & can_p & (frac >= cfg.period_thr)+ hit_p[new] = p+ for i in range(S):+ if n[i] < max(12, st):+ continue+ if stall[i]:+ out[i] = "stall"+ elif hit_p[i]:+ out[i] = f"period:{int(hit_p[i])}"+ return out+++# ---- loop guard v2 (derived from the remaining eval failures; identical in the reference decoder's guards) ----------+# The v1 tag windows ([-0.5 s, +3 s] around the prior-estimated tag time) miss most backstop cuts: style tags colour all the+# speech after them (whispered / sad / excited speech trips the period rule seconds later), the real tag time drifts from the+# prior (cuts happen at 1.0-2.1 x the piece's expected frames), and fillers / dialogue speaker switches are legitimate pauses.+# v2 windows (no loop action inside; the duration cap still applies):+# style tag [0.8 t - 0.5 s, 1.5 t + 4.0 s] (style_hold_s=None: to the end of the piece; rejected, see below)+# event tag [0.8 t - 0.5 s, 1.5 t + 4.0 s]+# filler [0.8 t - 0.5 s, 1.5 t + 2.5 s] hmm / umm / uh / ಹ್ಮ್ / उम्म / ഉം ...+# speaker [0.8 t - 0.5 s, 1.5 t + 2.0 s] "Name: " after a sentence end (dialogue speaker switch)+STYLE_TAGS = {"whispers", "whispering", "sad", "excited", "curious", "shouting", "angry", "frustrated", "sarcastic", "crying",+ "nervous", "scared", "happy", "panicked", "amazed", "worried", "calm", "serious", "surprised", "cheerful", "tired",+ "fearful", "disgusted", "confused", "sleepy", "annoyed", "softly", "loudly"}+FILLER_RE = re.compile(r"(?<!\w)(?:hmm+|hm+|umm+|um|uh+|uhh|erm|ह्म्म?|हम्म|उम्म?|ಹ್ಮ್|ಉಮ್|ஹ்ம்|ம்ம்|உம்|উমম?|হুম|ଉମ୍|ହମ୍|ਹਮ|ਉਮ|"+ r"હમ્મ|ઉમ|ఉమ్|హ్మ్|ഉം|ഹ്മ്)(?!\w)", re.I)+SPEAKER_RE = re.compile(r"(?:(?<=[.!?।॥])\s+|\n)([^\s:,.!?।]{1,24}):\s")+TAG_RE_V2 = re.compile(r"\[([a-z _]+)\]")+++def suspend_windows_v2(text, lang, prior, tag_hold_s=4.0, filler_hold_s=2.5, switch_hold_s=2.0, end_frames=10 ** 6,+ style_hold_s=4.0):+ """Frame windows where the v2 loop guard takes no action (see the block comment above). Default (v2b): style tags+ get a bounded window like event tags; style_hold_s=None suspends to the end of the piece (the first v2 variant,+ measured worse: it turned backstop cuts into duration-cap overruns on emotion rows)."""+ ev = []+ for m in TAG_RE_V2.finditer(text):+ ev.append((m.start(), style_hold_s if m.group(1).strip() in STYLE_TAGS else tag_hold_s))+ for m in FILLER_RE.finditer(text):+ ev.append((m.start(), filler_hold_s))+ for m in SPEAKER_RE.finditer(text):+ ev.append((m.start(1), switch_hold_s))+ out = []+ for pos, hold in sorted(ev):+ t = prior.expected_s(text[:pos], lang) if pos > 0 else 0.0+ a = max(0, int((0.8 * t - 0.5) / FRAME_S))+ b = end_frames if hold is None else int((1.5 * t + hold) / FRAME_S)+ out.append((a, b))+ return tuple(out)diff --git a/maya3/hub.py b/maya3/hub.pynew file mode 100644index 0000000..884f809--- /dev/null+++ b/maya3/hub.py@@ -0,0 +1,155 @@+"""Resolve a Maya3 release (a local dir or a Hugging Face repo id) into the paths the engine needs.++ from maya3.hub import resolve+ paths = resolve("/path/to/release/maya3") # or "org/maya3" (Hugging Face repo id)+ # -> {"ckpt": ..., "backbone_dir": ..., "mimi_dir": ..., "ecapa_dir": ...}+ tts = Maya3TTS.from_pretrained("/path/to/release/maya3", max_seats=16) # calls resolve() itself++Release layout (what maya3/tools/convert_to_safetensors.py writes):+ model.safetensors | model-0000k-of-0000N.safetensors + model.safetensors.index.json+ maya3_config.json resolved model config + format version (+ codec / speaker-encoder repo ids)+ backbone/ Qwen3 config.json + tokenizer files (no weights; the architecture is built from config)+ voices/voices.json named voices (optional)++Mimi (kyutai/mimi) and ECAPA (speechbrain/spkrec-ecapa-voxceleb) come from `huggingface_hub.snapshot_download`,+OFFLINE FIRST: a copy already in the local HF cache is used without any network call (also when the cache has the+snapshot but no `refs/main`, e.g. a copied cache). The network is only used when nothing usable is cached and+HF_HUB_OFFLINE is not set. A local directory may be passed instead of a repo id (`mimi=`, `ecapa=`, or the+MAYA3_MIMI_DIR / MAYA3_ECAPA_DIR environment variables).+"""+from __future__ import annotations++import json+import os+from pathlib import Path++MIMI_REPO = "kyutai/mimi"+ECAPA_REPO = "speechbrain/spkrec-ecapa-voxceleb"+RELEASE_CONFIG = "maya3_config.json"+WEIGHT_FILES = ("model.safetensors.index.json", "model.safetensors", "model.pt")+# files each component needs (also the snapshot_download allow-lists)+MIMI_FILES = ("config.json", "model.safetensors")+MIMI_PATTERNS = ["config.json", "model.safetensors", "preprocessor_config.json"]+ECAPA_FILES = ("embedding_model.ckpt",)+ECAPA_PATTERNS = ["embedding_model.ckpt", "hyperparams.yaml"]+RELEASE_PATTERNS = ["*.safetensors", "*.safetensors.index.json", RELEASE_CONFIG, "backbone/*", "voices/*", "README.md"]+++def _offline():+ return os.environ.get("HF_HUB_OFFLINE", "").strip().lower() in ("1", "true", "yes", "on")+++def _has(d, files):+ return d is not None and all((Path(d) / f).is_file() for f in files)+++def _cached_snapshot(repo_id, files, cache_dir=None, revision=None):+ """A cached snapshot dir of `repo_id` holding `files`, found without any network call, or None."""+ from huggingface_hub import snapshot_download+ try:+ d = snapshot_download(repo_id, revision=revision, cache_dir=cache_dir, local_files_only=True)+ if _has(d, files):+ return d+ except Exception: # not cached / no refs for the revision: fall back to scanning the snapshots+ pass+ if revision is not None and len(revision) != 40:+ return None+ from huggingface_hub import constants+ root = Path(cache_dir or constants.HF_HUB_CACHE) / ("models--" + repo_id.replace("/", "--")) / "snapshots"+ if not root.is_dir():+ return None+ snaps = [p for p in root.iterdir() if p.is_dir() and _has(p, files) and (revision is None or p.name == revision)]+ if not snaps:+ return None+ return str(max(snaps, key=lambda p: p.stat().st_mtime))+++def snapshot(repo_or_dir, files, patterns, cache_dir=None, revision=None, local_files_only=None):+ """Local dir for a repo id (or an existing local dir): offline first, then the network unless offline."""+ p = Path(os.path.expanduser(str(repo_or_dir)))+ if p.is_dir():+ if not _has(p, files):+ raise FileNotFoundError(f"{p} lacks {[f for f in files if not (p / f).is_file()]}")+ return str(p.resolve())+ d = _cached_snapshot(str(repo_or_dir), files, cache_dir, revision)+ if d is not None:+ return d+ if local_files_only or (local_files_only is None and _offline()):+ raise FileNotFoundError(f"{repo_or_dir} is not in the local Hugging Face cache "+ f"({cache_dir or 'default HF cache'}) and downloads are disabled (HF_HUB_OFFLINE)")+ from huggingface_hub import snapshot_download+ d = snapshot_download(str(repo_or_dir), revision=revision, cache_dir=cache_dir, allow_patterns=list(patterns))+ if not _has(d, files):+ raise FileNotFoundError(f"{repo_or_dir}@{revision or 'main'} lacks {list(files)}")+ return d+++def release_config(model_dir):+ """maya3_config.json of a release dir as a dict ({} if absent, e.g. a bare model.pt dir)."""+ p = Path(model_dir) / RELEASE_CONFIG+ return json.loads(p.read_text()) if p.is_file() else {}+++def resolve(model_dir_or_repo, *, mimi=None, ecapa=None, cache_dir=None, revision=None, local_files_only=None,+ include_model_config=False) -> dict:+ """-> dict(ckpt=..., backbone_dir=..., mimi_dir=..., ecapa_dir=..., voices_json=...), absolute local paths.++ voices_json is <dir>/voices/voices.json when it lists at least one named voice, else None. It is not a+ Maya3TTS.from_pretrained argument: splat only the first four keys, or call from_pretrained("<release dir>").++ model_dir_or_repo a local release dir (see the module docstring) or a Hugging Face repo id+ mimi / ecapa repo id or local dir overriding maya3_config.json / MAYA3_MIMI_DIR / MAYA3_ECAPA_DIR /+ the defaults kyutai/mimi and speechbrain/spkrec-ecapa-voxceleb+ cache_dir HF cache dir (default: HF_HUB_CACHE / HF_HOME)+ revision revision of model_dir_or_repo when it is a repo id (Mimi / ECAPA use their cached / main)+ local_files_only True: never touch the network; None (default): offline first, network only if nothing is+ cached and HF_HUB_OFFLINE is unset; False: same as None+ include_model_config also return model_config=<dir>/maya3_config.json (an Engine kwarg, not an EngineConfig+ field: do not splat it into Maya3TTS.from_pretrained)+ """+ p = Path(os.path.expanduser(str(model_dir_or_repo)))+ if p.is_dir():+ model_dir = p.resolve()+ elif p.is_file() and p.suffix == ".pt": # a bare flat checkpoint: backbone etc. must be passed separately+ raise ValueError(f"{p} is a bare checkpoint; pass ckpt/backbone_dir/mimi_dir/ecapa_dir explicitly")+ else:+ model_dir = Path(snapshot(str(model_dir_or_repo), (RELEASE_CONFIG,), RELEASE_PATTERNS, cache_dir, revision,+ local_files_only))+ weights = [f for f in WEIGHT_FILES if (model_dir / f).is_file()]+ if not weights:+ raise FileNotFoundError(f"{model_dir}: no {' / '.join(WEIGHT_FILES)}")+ if weights[0] == "model.safetensors.index.json":+ idx = json.loads((model_dir / weights[0]).read_text())+ missing = sorted({f for f in idx["weight_map"].values() if not (model_dir / f).is_file()})+ if missing:+ raise FileNotFoundError(f"{model_dir}: shards missing: {missing}")+ backbone = model_dir / "backbone"+ if not (backbone / "config.json").is_file() or not (backbone / "tokenizer.json").is_file():+ raise FileNotFoundError(f"{backbone}: needs config.json and tokenizer.json")+ cfg = release_config(model_dir)+ mimi = mimi or os.environ.get("MAYA3_MIMI_DIR") or (cfg.get("audio") or {}).get("codec") or MIMI_REPO+ ecapa = ecapa or os.environ.get("MAYA3_ECAPA_DIR") or (cfg.get("speaker_encoder") or {}).get("repo") or ECAPA_REPO+ out = {+ "ckpt": str(model_dir if weights[0] != "model.pt" else model_dir / "model.pt"),+ "backbone_dir": str(backbone),+ "mimi_dir": snapshot(mimi, MIMI_FILES, MIMI_PATTERNS, cache_dir, None, local_files_only),+ "ecapa_dir": snapshot(ecapa, ECAPA_FILES, ECAPA_PATTERNS, cache_dir, None, local_files_only),+ }+ out["voices_json"] = voices_file(model_dir) # None when the release ships no named voices+ if include_model_config and (model_dir / RELEASE_CONFIG).is_file():+ out["model_config"] = str(model_dir / RELEASE_CONFIG)+ return out+++def voices_file(model_dir):+ """<release>/voices/voices.json if it lists any voice, else None (the stub ships empty)."""+ p = Path(model_dir) / "voices" / "voices.json"+ if not p.is_file():+ return None+ d = json.loads(p.read_text())+ return str(p) if (d.get("voices") if isinstance(d, dict) else d) else None+++if __name__ == "__main__":+ import sys+ print(json.dumps(resolve(sys.argv[1]), indent=1))diff --git a/maya3/prompt.py b/maya3/prompt.pynew file mode 100644index 0000000..2ab6d5e--- /dev/null+++ b/maya3/prompt.py@@ -0,0 +1,217 @@+"""Voices and prompt building for the Maya3 engine.++A *voice* is everything about a request that does not depend on the target text: the conditioning mode, the packed+reference prefix (reference text + its 32-codebook Mimi codes), the ECAPA-192 speaker embedding and the depth speaker+memory computed from it. Because the prompt layout tags the first reference span with the REFERENCE language+(not the target language), the packed prefix -- and therefore its backbone KV -- is a constant of the voice and is+computed once and cached (see engine.py).++Prompt geometry is the training packer's (tts.data.packing_v2.PackerV2._span + collate_v2, via+scripts/s2_serve_controls); this module only decides WHICH spans to pack, exactly as the training-time example builder+does (layout "v5"; checked token for token against it):++ plain : <|lang:B|> target <|audio|> (speaker memory nulled)+ spk : same tokens, ECAPA anchor + depth speaker memory+ icl : <|lang:A|> ref <|audio|> codes AEOS [<|lang:B|> if A != B] target <|audio|> (speaker memory nulled)+ icl_spk : icl + ECAPA (the full zero-shot clone; the default for a reference clip)++Prompt builders are pluggable: a Voice carries a `builder` (default V5Builder). Named speakers+("{Name}: text"-style prefixes, format not frozen) become registry entries with their own builder and a cached+prefix; the engine needs no new path (see NamedSpeakerBuilder).+"""+from __future__ import annotations++import dataclasses+import threading+from typing import Callable, Optional++import numpy as np+import torch++MODES = {"plain": (False, False), "spk": (False, True), "icl": (True, False), "icl_spk": (True, True),+ "named": (False, False)} # (use_icl, use_mem); named = a trained voice selected by its name in the text, memory nulled+MODE_ALIASES = {"joint_null": "plain", "spk_only": "spk", "icl_only": "icl", "clone": "icl_spk"}+++def norm_mode(m):+ m = MODE_ALIASES.get(m, m)+ if m not in MODES:+ raise ValueError(f"unknown conditioning mode {m!r}; choose one of {sorted(MODES)}")+ return m+++class Voice:+ """A registered voice. `clips`: list of {text, codes (32,F) int, lang}; `ecapa`: (192,) L2-normalised or None."""+ id: str+ mode: str = "plain"+ clips: list = dataclasses.field(default_factory=list)+ ecapa: Optional[np.ndarray] = None+ builder: Optional["PromptBuilder"] = None+ meta: dict = dataclasses.field(default_factory=dict)+ # ---- cached, filled lazily by the engine (never by users)+ prefix: Optional[dict] = None # packed prefix arrays {tokens, kind, codes, loss_mask}+ spk_refs: Optional[np.ndarray] = None # (1,192) float32+ mem: Optional[torch.Tensor] = None # (1,1,D) depth speaker memory+ rmask: Optional[torch.Tensor] = None # (1,1) bool+ kv: Optional[list] = None # [(k, v)] per layer, [1, KV, ts, Dh] (backbone prefix KV)+ emb: Optional[torch.Tensor] = None # [1, ts, D] prefix input embeddings (for the exactness check)+ ts: int = 0 # prefix length in tokens (0 = nothing to cache)+ lock: threading.Lock = dataclasses.field(default_factory=threading.Lock, repr=False)++ def __post_init__(self):+ self.mode = norm_mode(self.mode)+ use_icl, use_mem = MODES[self.mode]+ if use_icl and not self.clips:+ raise ValueError(f"voice {self.id}: mode {self.mode} needs at least one reference clip")+ if use_mem and self.ecapa is None:+ raise ValueError(f"voice {self.id}: mode {self.mode} needs an ECAPA embedding")+ if self.ecapa is not None:+ e = np.asarray(self.ecapa, np.float32).reshape(-1, 192)+ if e.shape[0] != 1:+ raise ValueError("the fast depth path supports exactly one ECAPA reference embedding per voice")+ self.ecapa = e[0]++ @property+ def ref_lang(self):+ return self.clips[0]["lang"] if self.clips else None+++class PromptBuilder:+ """Interface: prefix(packer, voice) -> packed prefix dict or None (constant per voice; cached);+ target(packer, voice, text, lang) -> example dict for s2_serve_controls.prompt_from_example."""++ def prefix(self, packer, voice):+ raise NotImplementedError++ def example(self, packer, voice, text, lang):+ raise NotImplementedError+++class V5Builder(PromptBuilder):+ """The training layout (layout='v5' in the training-time example builder)."""++ def prefix(self, packer, voice):+ use_icl, _ = MODES[voice.mode]+ if not use_icl:+ return None+ spans = []+ for i, cl in enumerate(voice.clips):+ cut = {"text_final": cl["text"], "lang_final": cl["lang"], "codes": np.asarray(cl["codes"], np.int64), "row": 0}+ spans.append(packer._span(cut, first=(i == 0), cont=False))+ return {key: np.concatenate([sp[j] for sp in spans]) for j, key in enumerate(("tokens", "kind", "codes", "loss_mask"))}++ def example(self, packer, voice, text, lang):+ from scripts import s2_serve_controls as S+ from tts.tokens import N_Q+ _, use_mem = MODES[voice.mode]+ prefix = voice.prefix+ xling = prefix is not None and any(cl["lang"] != lang for cl in voice.clips)+ ex = S.make_example(packer, prefix, text, lang, voice.spk_refs, not use_mem)+ if xling: # the target's first span gets its own language tag when the references are in another language+ cut = {"text_final": text, "lang_final": lang, "codes": np.zeros((N_Q, 1), np.int64), "row": 0}+ t, k, c, m = packer._span(cut, first=True, cont=False)+ ts = ex["target_start"]+ for key, arr in (("tokens", t), ("kind", k), ("codes", c), ("loss_mask", m)):+ ex[key] = np.concatenate([prefix[key], arr])+ assert ex["target_start"] == ts+ ex["xling"] = xling+ return ex+++class NamedSpeakerBuilder(V5Builder):+ """Named speakers: the voice is selected by its name in the text conditioning,+ <|lang:xx|>{template.format(name=Name, text=text)}<|audio|>+ with no reference audio and a nulled speaker memory (like plain). The template follows the trainer's+ named-speaker prompt spec; it was checked token for token against the+ trainer's packer. Nothing is cached per voice (the language tag precedes the name), the whole prompt is short."""++ def __init__(self, template="{{{name}}}: {text}"):+ self.template = template++ def render(self, voice, text):+ return self.template.format(name=voice.meta.get("name", voice.id), text=text.strip())++ def prefix(self, packer, voice):+ return None++ def example(self, packer, voice, text, lang):+ return super().example(packer, voice, self.render(voice, text), lang)+++def load_named_voices(registry, voices_json, template=None, replace=True):+ """Register the trained named voices of voices.json (list, or {"voices": [...]}); each entry needs a name+ ("name"/"id"/"display_name"); every other field is kept in Voice.meta (gender, age, style, langs, provenance...).+ Returns the registered ids. Lookup is case-insensitive (VoiceRegistry.get)."""+ import json+ d = json.load(open(voices_json))+ items = d.get("voices", d) if isinstance(d, dict) else d+ tmpl = template or (d.get("template") if isinstance(d, dict) else None)+ builder = NamedSpeakerBuilder(tmpl) if tmpl else NamedSpeakerBuilder()+ import os+ import numpy as np+ base = os.path.dirname(os.path.abspath(voices_json))+ ids = []+ for it in items:+ name = it.get("name") or it.get("display_name") or it.get("id")+ if not name:+ raise ValueError(f"voice entry without a name: {it}")+ meta = {k: v for k, v in it.items() if k not in ("ecapa", "centroid", "ref_clips")}+ meta["name"] = name+ mode = norm_mode(it.get("mode", "named"))+ if mode == "named":+ v = Voice(str(name), "named", builder=builder, meta=meta)+ else:+ # per-voice fallback: the voice's stored ECAPA centroid (spk) and/or curated reference clip(s) (icl / icl_spk)+ ecapa = np.load(os.path.join(base, it["ecapa"])).astype(np.float32).reshape(-1) if it.get("ecapa") else None+ clips = []+ if MODES[mode][0]:+ for c in (it.get("ref_clips") or [])[: int(it.get("max_ref_clips", 1))]:+ clips.append({"text": c["text"], "lang": c["lang"],+ "codes": np.load(os.path.join(base, c["codes"])).astype(np.int64)})+ v = Voice(str(name), mode, clips=clips, ecapa=ecapa, meta=meta)+ registry.add(v, replace=replace)+ ids.append(str(name))+ return ids+++DEFAULT_BUILDER = V5Builder()+++class VoiceRegistry:+ """Thread-safe id -> Voice map. `plain` is always present (no reference, speaker memory nulled)."""++ def __init__(self):+ self._v = {"plain": Voice("plain", "plain")}+ self._lock = threading.Lock()++ def add(self, voice: Voice, replace=True):+ with self._lock:+ if not replace and voice.id in self._v:+ raise KeyError(f"voice {voice.id} exists")+ self._v[voice.id] = voice+ return voice++ def get(self, vid) -> Voice:+ with self._lock:+ if vid in self._v:+ return self._v[vid]+ low = str(vid).lower() # case-insensitive fallback (named voices: "asha" == "Asha")+ hits = [v for k, v in self._v.items() if k.lower() == low]+ if len(hits) == 1:+ return hits[0]+ raise KeyError(f"unknown voice {vid!r}")++ def remove(self, vid):+ with self._lock:+ if vid == "plain":+ raise KeyError("cannot remove the plain voice")+ return self._v.pop(vid, None)++ def ids(self):+ with self._lock:+ return list(self._v)++ def __contains__(self, vid):+ with self._lock:+ return vid in self._vdiff --git a/maya3/server.py b/maya3/server.pynew file mode 100644index 0000000..fa47106--- /dev/null+++ b/maya3/server.py@@ -0,0 +1,1288 @@+"""Maya3 TTS server: OpenAI-compatible HTTP speech endpoint + low-latency WebSocket streaming (aiohttp).++Run+---+ python -m maya3.server --ckpt model.pt --backbone-dir BB --mimi-dir MIMI --ecapa-dir ECAPA \\+ --host 127.0.0.1 --port 8080 --max-seats 64 --max-pending 64 --queue-deadline-ms 2000 [--voices voices.json] \\+ [--no-normalise]++The port opens immediately; `GET /health` answers 503 while the model loads and warms up and 200 once it is ready.+`--voices` is a JSON list (or {"voices": [...]}) of {"voice_id", "ref_audio" (path, relative to the json file),+"ref_text", "lang", "mode", "meta"} that is registered before the server reports ready.+The model's audio is 24 kHz, mono; PCM is signed 16-bit little-endian.++Text normalisation+------------------+Every request's text goes through the bundled normaliser (maya3.text.normalise_text: numbers, currency, dates,+times, OTPs / phone numbers, URLs / e-mails -> words in the request language; ALL-CAPS names title-cased; inline+[tags] such as [laughs] untouched) unless the server runs with --no-normalise or the request sets "normalize": false+(HTTP and WS). Only the user's text is normalised; a named voice's "{Name}: " prefix is added by the engine.++Sampling (HTTP and WS, all optional; absent = engine defaults)+--------------------------------------------------------------+ seed (int, 0..2^63-1) temperature (0.1..1.5) top_k (int, 1..2048) top_p (0 < p <= 1) repetition_penalty (0..5)+Only the keys given are passed to the engine (Engine.submit(..., sampling={...})); invalid values -> 400 / WS+invalid_request naming the field. Same seed + text + voice gives the same audio when the request runs alone.++HTTP (OpenAI-compatible)+------------------------+ POST /v1/audio/speech {"model": "maya3", "input": "नमस्ते", "voice": "plain", "response_format": "wav",+ "language": "hi", "speed": 1.0, "stream_format": "audio", "normalize": true, "seed": 7}+ curl -sN localhost:8080/v1/audio/speech -H 'content-type: application/json' \\+ -d '{"input":"Hello there.","language":"en","response_format":"pcm"}' | ffplay -f s16le -ar 24000 -ch_layout mono -++ * response_format (Content-Type):+ wav (audio/wav) default; streamed, RIFF header with sizes 0xFFFFFFFF, then s16le PCM+ pcm (audio/pcm) streamed raw s16le, 24 kHz mono+ mp3 (audio/mpeg) streamed CBR MPEG-2 layer III, 24 kHz mono, ~80 kbit/s (libsndfile/LAME); bare+ frames, no Xing/Info header; decoders add ~50 ms of encoder delay/padding+ opus (audio/ogg; codecs=opus) streamed Ogg/Opus at 24 kHz (libsndfile/libopus); the Ogg headers are sent at+ once, audio in ~1 s Ogg pages+ flac (audio/flac) lossless, sent when the audio is complete (Content-Length set)+ aac -> 400 (no AAC encoder is bundled). mp3/opus need libsndfile >= 1.1 (the soundfile >= 0.12 wheels); when it+ is missing they are refused with 400. GET /health lists the usable formats under server.formats.+ * stream_format: "audio" (default, chunked body) or "sse" (OpenAI events `speech.audio.delta` carrying base64+ bytes of the chosen format, then `speech.audio.done`; wav/pcm/mp3/opus, not flac).+ * language / lang: as bn en gu hi kn ml mr or pa ta te; when absent it is guessed from the script of the input+ (Devanagari -> hi, Bengali script -> bn, Latin -> en, ...). Reported in the X-Maya3-Language header.+ * voice: a registered voice id ("plain" by default); named voices match case-insensitively ("asha" -> "Asha").+ OpenAI voice names (alloy, nova, ...) map to "plain" unless a voice with that id is registered.+ speed must be 1.0. Extension: max_frames (80 ms frames, 1..1500).+ * normalize: true (default) / false; sampling fields as above.+ * Response headers: X-Sample-Rate, X-Channels, X-Encoding (pcm_s16le | mp3 | opus | flac), X-Maya3-Language,+ X-Maya3-Voice (the resolved id), X-Maya3-Normalized (1/0), X-Request-Id.+ * Errors are JSON {"error": {"message", "type", "code", "param"}}: 400 invalid input, 503 overloaded / not ready+ (with Retry-After), sent before any audio. A failure after audio started aborts the connection (the chunked body+ has no terminating chunk), so a truncated utterance never looks like a successful one.++WebSocket+---------+ WS /v1/tts/stream+ server -> {"type": "metadata", "sample_rate": 24000, "encoding": "pcm_s16le", "channels": 1, "max_contexts": 8,+ "languages": [...]}+ client -> {"type": "speak", "context_id": "c1", "text": "...", "language": "hi", "voice": "plain",+ "max_frames": 400, "binary": false, "normalize": true, "seed": 7, "temperature": 0.8, ...}+ (voice, language, normalize and the sampling fields behave as on HTTP)+ server -> {"type": "audio", "context_id": "c1", "audio": "<base64 s16le>"} (repeated)+ or, with "binary": true, binary frames: uint32-LE len(context_id utf-8) | context_id | PCM s16le+ server -> {"type": "end", "context_id": "c1", "reason": "aeos", "frames": 52, "audio_s": 4.16, "ttfa_ms": 61.0}+ client -> {"type": "cancel", "context_id": "c1"} -> the context ends with {"type": "end", "reason": "cancelled"}+ client -> {"type": "ping"} -> {"type": "pong"}+ errors -> {"type": "error", "context_id": "c1" | null, "code": "...", "error": "..."}+ Every speak gets exactly one terminal message (end or error) and no audio after it. Several contexts may run on+ one socket at once (up to max_contexts; more -> error "too_many_contexts"). Error codes: invalid_request,+ overloaded (queue full or queue deadline passed; sent before any audio), slow_consumer (the client fell more than+ --ws-max-lag-s of audio behind; the request is cancelled), unavailable, too_many_contexts, internal.+ Closing the socket cancels its requests. Audio on the WebSocket is always PCM s16le 24 kHz mono (no+ response_format); use HTTP for wav/mp3/opus/flac.++Voices+------+ GET /v1/voices {"voices": [{"id", "mode", "ref_lang"}]}+ mode: plain | spk | icl | icl_spk | named; named voices also carry "meta" (the registry's+ Voice.meta: name / display name, gender, age, style, langs, ...); a name-template voice+ whose own mode is not "named" (e.g. icl_spk) reports that as "base_mode"+ POST /v1/voices JSON {"voice_id", "ref_audio_b64" (wav/flac bytes, base64), "ref_text", "lang",+ "mode": "icl_spk", "replace": false}+ or multipart/form-data with the same fields and the clip as file field "ref_audio"+ -> 201 {"id", "mode", "ref_lang", "register_s"}; 409 if it exists and replace is false+ DELETE /v1/voices/{id}++Health / misc+-------------+ GET /health engine.health() + {"server": {...}}; 503 until ready+ GET /v1/models OpenAI-style model list++Admission control: a request that would make more than --max-pending requests wait for their first audio, or that+waits longer than --queue-deadline-ms before its first audio, is refused (HTTP 503 / WS "overloaded") and cancelled+in the engine. A client disconnect cancels its engine request.+"""+from __future__ import annotations++import argparse+import asyncio+import base64+import binascii+import collections+import io+import json+import logging+import math+import threading+import re+import struct+import time+import uuid+from pathlib import Path++from aiohttp import WSMsgType, web++SR = 24000+FRAME = 1920+LANGS = ("as", "bn", "en", "gu", "hi", "kn", "ml", "mr", "or", "pa", "ta", "te")+MAX_TEXT_CHARS = 4000+MAX_FRAMES = 1500+MODES = ("plain", "spk", "icl", "icl_spk")+MODE_ALIASES = {"joint_null": "plain", "spk_only": "spk", "icl_only": "icl", "clone": "icl_spk"}+OPENAI_VOICES = {"alloy", "ash", "ballad", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer", "verse",+ "marin", "cedar"}+FORMATS = {"wav": "audio/wav", "pcm": "audio/pcm", "mp3": "audio/mpeg", "opus": "audio/ogg; codecs=opus",+ "flac": "audio/flac"}+STREAMED_FORMATS = ("wav", "pcm", "mp3", "opus") # flac is encoded once the utterance is complete+SF_CODECS = {"mp3": ("MP3", "MPEG_LAYER_III"), "opus": ("OGG", "OPUS")} # libsndfile >= 1.1 (soundfile >= 0.12 wheels)+UNSUPPORTED_FORMATS = {"aac": "no AAC encoder is bundled"}+MP3_LEVEL = 0.5 # libsndfile compression level; CBR ~80 kbit/s at 24 kHz mono+NORMALISE_INLINE_CHARS = 256 # longer inputs are normalised on a worker thread+SEED_MAX = 2 ** 63 - 1+VOICE_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.\-]{0,63}$")+# Unicode blocks -> language, used only when the caller gives no language.+SCRIPTS = ((0x0900, 0x097F, "hi"), (0x0980, 0x09FF, "bn"), (0x0A00, 0x0A7F, "pa"), (0x0A80, 0x0AFF, "gu"),+ (0x0B00, 0x0B7F, "or"), (0x0B80, 0x0BFF, "ta"), (0x0C00, 0x0C7F, "te"), (0x0C80, 0x0CFF, "kn"),+ (0x0D00, 0x0D7F, "ml"))++log = logging.getLogger("maya3.server")+++# ---------------------------------------------------------------------------------------------------- helpers+class ApiError(Exception):+ def __init__(self, status, code, message, param=None, retry_after=None):+ super().__init__(message)+ self.status, self.code, self.message, self.param, self.retry_after = status, code, message, param, retry_after++ def response(self):+ kind = "invalid_request_error" if self.status < 500 else "server_error"+ headers = {"Retry-After": str(self.retry_after)} if self.retry_after else None+ return web.json_response({"error": {"message": self.message, "type": kind, "code": self.code,+ "param": self.param}}, status=self.status, headers=headers)+++def bad(message, param=None, code="invalid_request"):+ return ApiError(400, code, message, param)+++def detect_lang(text):+ counts = collections.Counter()+ for ch in text:+ o = ord(ch)+ if o < 0x80:+ if ch.isalpha():+ counts["en"] += 1+ continue+ for lo, hi, lang in SCRIPTS:+ if lo <= o <= hi:+ counts[lang] += 1+ break+ return counts.most_common(1)[0][0] if counts else "en"+++def wav_header(data_bytes=0xFFFFFFFF, sr=SR, channels=1, bits=16):+ """RIFF/WAVE header; the default 0xFFFFFFFF sizes mark a stream of unknown length."""+ riff = 0xFFFFFFFF if data_bytes == 0xFFFFFFFF else 36 + data_bytes+ return struct.pack("<4sI4s4sIHHIIHH4sI", b"RIFF", riff, b"WAVE", b"fmt ", 16, 1, channels, sr,+ sr * channels * bits // 8, channels * bits // 8, bits, b"data", data_bytes)+++def ws_binary_frame(context_id, pcm):+ cid = context_id.encode()+ return struct.pack("<I", len(cid)) + cid + pcm+++def parse_lang(body, text):+ lang = body.get("language", body.get("lang"))+ if lang is None or lang == "auto":+ return detect_lang(text)+ if not isinstance(lang, str) or lang.lower() not in LANGS:+ raise bad(f"unsupported language {lang!r}; supported: {', '.join(LANGS)}", "language")+ return lang.lower()+++def parse_text(text, field):+ if not isinstance(text, str) or not text.strip():+ raise bad(f"{field} must be a non-empty string", field)+ if len(text) > MAX_TEXT_CHARS:+ raise bad(f"{field} is {len(text)} characters; the limit is {MAX_TEXT_CHARS}", field)+ return text.strip()+++def parse_max_frames(v):+ if v is None:+ return None+ if isinstance(v, bool) or not isinstance(v, int) or not 1 <= v <= MAX_FRAMES:+ raise bad(f"max_frames must be an integer in 1..{MAX_FRAMES} (80 ms frames)", "max_frames")+ return v+++def _is_int(v):+ return isinstance(v, int) and not isinstance(v, bool)+++def _is_num(v):+ return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)+++def parse_sampling(body):+ """Per-request sampling overrides -> dict of the keys that were given (None when none were)."""+ out = {}+ v = body.get("seed")+ if v is not None:+ if not _is_int(v) or not 0 <= v <= SEED_MAX:+ raise bad("seed must be an integer in 0..2^63-1", "seed")+ out["seed"] = int(v)+ v = body.get("temperature")+ if v is not None:+ if not _is_num(v) or not 0.1 <= v <= 1.5:+ raise bad("temperature must be a number in 0.1..1.5", "temperature")+ out["temperature"] = float(v)+ v = body.get("top_k")+ if v is not None:+ if not _is_int(v) or not 1 <= v <= 2048:+ raise bad("top_k must be an integer in 1..2048", "top_k")+ out["top_k"] = int(v)+ v = body.get("top_p")+ if v is not None:+ if not _is_num(v) or not 0 < v <= 1:+ raise bad("top_p must be a number with 0 < top_p <= 1", "top_p")+ out["top_p"] = float(v)+ v = body.get("repetition_penalty")+ if v is not None:+ if not _is_num(v) or not 0 <= v <= 5:+ raise bad("repetition_penalty must be a number in 0..5", "repetition_penalty")+ out["repetition_penalty"] = float(v)+ return out or None+++def parse_normalize(body):+ key = "normalize" if "normalize" in body else "normalise"+ v = body.get(key, True)+ if v is None:+ return True+ if not isinstance(v, bool):+ raise bad(f"{key} must be true or false", key)+ return v+++def is_named(voice):+ """Named speakers (selected by a "{Name}: text" template): mode 'named' or a NamedSpeakerBuilder builder."""+ return getattr(voice, "mode", None) == "named" or type(getattr(voice, "builder", None)).__name__ == "NamedSpeakerBuilder"+++def _jsonable(x):+ try:+ return json.loads(json.dumps(x, default=str))+ except (TypeError, ValueError):+ return {}+++def voice_info(vid, v):+ ref_lang = getattr(v, "ref_lang", None)+ if ref_lang is None:+ clips = getattr(v, "clips", None) or []+ ref_lang = clips[0].get("lang") if clips and isinstance(clips[0], dict) else None+ mode = getattr(v, "mode", None)+ out = {"id": vid, "mode": mode, "ref_lang": ref_lang}+ if is_named(v):+ out["mode"] = "named"+ if mode != "named":+ out["base_mode"] = mode # conditioning under the name template (plain/spk/icl/icl_spk)+ out["meta"] = _jsonable(dict(getattr(v, "meta", None) or {}))+ return out+++def _normaliser():+ from maya3.text import normalise_text+ return normalise_text+++# ---------------------------------------------------------------------------------------------------- jobs+class Overloaded(Exception):+ pass+++class _Bridge:+ """Engine thread -> event loop: events are queued and ONE call_soon_threadsafe wakes the loop per batch (not one per+ 80 ms frame per request, which costs a self-pipe write + wakeup each and adds host jitter at 100+ seats)."""++ def __init__(self, loop):+ self.loop, self.q, self.scheduled = loop, collections.deque(), False++ def post(self, job, kind, payload): # engine thread+ self.q.append((job, kind, payload))+ if not self.scheduled:+ self.scheduled = True+ self.loop.call_soon_threadsafe(self.flush)++ def flush(self): # event loop+ self.scheduled = False+ q = self.q+ while q:+ job, kind, payload = q.popleft()+ job._put(kind, payload)+++_BRIDGES = {}+++def _bridge(loop):+ b = _BRIDGES.get(id(loop))+ if b is None or b.loop is not loop:+ b = _BRIDGES[id(loop)] = _Bridge(loop)+ return b+++class Job:+ """One engine request seen from the event loop. Engine events arrive through a coalescing _Bridge."""++ def __init__(self, srv, rid, loop, max_lag_s, on_overflow=None):+ self.srv, self.rid, self.loop = srv, rid, loop+ self.items = collections.deque()+ self.ev = asyncio.Event()+ self.req = None+ self.lag = 0 # samples received from the engine but not yet consumed+ self.max_lag = int(max_lag_s * SR) if max_lag_s else None+ self.on_overflow = on_overflow+ self.overflowed = False+ self.closed = False+ self.t_submit = time.perf_counter()+ self.t_first = None+ self.bridge = _bridge(loop)++ def on_event(self, kind, payload): # engine thread+ try:+ self.bridge.post(self, kind, payload)+ except RuntimeError: # loop closed: the request is orphaned+ if self.req is not None:+ self.req.cancel()++ def _put(self, kind, payload):+ if self.closed:+ return+ self.srv._waiting.discard(self)+ if kind == "audio":+ if self.t_first is None:+ self.t_first = time.perf_counter()+ self.lag += len(payload)+ if self.max_lag is not None and self.lag > self.max_lag and not self.overflowed:+ self.overflowed = True+ if self.req is not None:+ self.req.cancel()+ if self.on_overflow is not None:+ self.on_overflow()+ self.items.append((kind, payload))+ self.ev.set()++ def interrupt(self):+ self.items.append(("interrupt", None))+ self.ev.set()++ async def get(self, timeout=None):+ while not self.items:+ self.ev.clear()+ if timeout is None:+ await self.ev.wait()+ else:+ await asyncio.wait_for(self.ev.wait(), timeout)+ kind, payload = self.items.popleft()+ if kind == "audio":+ self.lag -= len(payload)+ return kind, payload++ def take_audio(self, first, max_samples):+ """Coalesce `first` with audio already queued (no waiting) up to max_samples."""+ parts, n = [first.tobytes()], len(first)+ while n < max_samples and self.items and self.items[0][0] == "audio":+ _, p = self.items.popleft()+ self.lag -= len(p)+ parts.append(p.tobytes())+ n += len(p)+ return b"".join(parts), n++ def close(self):+ if not self.closed:+ self.closed = True+ if self.req is not None:+ self.req.cancel()+ self.srv._waiting.discard(self)+ self.srv._jobs.discard(self)+++# ---------------------------------------------------------------------------------------------------- server+class Maya3Server:+ def __init__(self, tts=None, *, max_pending=64, queue_deadline_ms=2000, ws_max_contexts=8, ws_max_lag_s=20.0,+ http_max_lag_s=120.0, ws_send_queue=64, ws_send_timeout_s=15.0, coalesce_ms=480, loader=None,+ owns_tts=False, normalise=True):+ self.tts = tts+ self.normalise = normalise # bundled text normaliser (maya3.text); per request: "normalize": false+ self.loader = loader+ self.owns_tts = owns_tts or loader is not None+ self.load_error = None+ self.max_pending = max_pending+ self.deadline = queue_deadline_ms / 1000.0+ self.ws_max_contexts = ws_max_contexts+ self.ws_max_lag_s = ws_max_lag_s+ self.http_max_lag_s = http_max_lag_s+ self.ws_send_queue = ws_send_queue+ self.ws_send_timeout_s = ws_send_timeout_s+ self.coalesce = max(FRAME, int(coalesce_ms * SR / 1000))+ self._waiting = set() # jobs without their first event yet (admission control)+ self._jobs = set()+ self._voice_lock = None+ self.sockets = 0+ self.stats = collections.Counter()++ # ------------------------------------------------------------------ app+ def app(self):+ app = web.Application(client_max_size=24 * 1024 * 1024)+ app["maya3"] = self+ app.on_startup.append(self._startup)+ app.on_cleanup.append(self._cleanup)+ r = app.router+ r.add_get("/health", self.health)+ r.add_get("/v1/models", self.models)+ r.add_post("/v1/audio/speech", self.speech)+ r.add_get("/v1/tts/stream", self.ws)+ r.add_get("/v1/voices", self.list_voices)+ r.add_post("/v1/voices", self.add_voice)+ r.add_delete("/v1/voices/{voice_id}", self.delete_voice)+ return app++ async def _startup(self, app):+ self._voice_lock = asyncio.Lock()+ if self.normalise:+ try: # import + warm the tables off the loop (first call ~10 ms)+ await asyncio.to_thread(_normaliser().__call__, "1", "en")+ except Exception as exc:+ log.error("text normaliser unavailable (%s: %s); serving without normalisation", type(exc).__name__, exc)+ self.normalise = False+ if self.tts is None and self.loader is not None:+ self._load_task = asyncio.create_task(self._load())++ async def _load(self):+ t0 = time.perf_counter()+ try:+ self.tts = await asyncio.to_thread(self.loader)+ log.info("model ready in %.1f s", time.perf_counter() - t0)+ except Exception as exc: # surfaced by /health+ log.exception("model load failed")+ self.load_error = f"{type(exc).__name__}: {exc}"++ async def _cleanup(self, app):+ for job in list(self._jobs):+ job.close()+ if self.owns_tts and self.tts is not None:+ await asyncio.to_thread(self.tts.close)++ @property+ def engine(self):+ return self.tts.engine++ def ready(self):+ if self.tts is None:+ raise ApiError(503, "unavailable", self.load_error or "model is loading", retry_after=5)+ failed = getattr(self.engine, "failed", None)+ if failed:+ raise ApiError(503, "unavailable", f"engine failed: {failed}")++ def resolve_voice(self, voice):+ if voice is None or voice == "":+ return "plain"+ if not isinstance(voice, str):+ raise bad("voice must be a string (a registered voice id)", "voice")+ reg = self.engine.registry+ if voice in reg:+ return voice+ low = voice.lower()+ for vid in reg.ids(): # named voices match case-insensitively ("asha" -> "Asha")+ if vid.lower() == low:+ try:+ if is_named(reg.get(vid)):+ return vid+ except KeyError:+ pass+ if low in OPENAI_VOICES:+ return "plain"+ raise bad(f"unknown voice {voice!r}; registered voices: {', '.join(reg.ids())}", "voice")++ # ------------------------------------------------------------------ admission+ async def prepare_text(self, text, lang, normalize=True):+ """Apply the bundled normaliser (unless disabled globally or for this request). Only the user's text is+ normalised: a named voice's "{Name}: " prefix is added by the engine."""+ if not (self.normalise and normalize):+ return text+ fn = _normaliser()+ out = fn(text, lang) if len(text) <= NORMALISE_INLINE_CHARS else await asyncio.to_thread(fn, text, lang)+ self.stats["normalised"] += 1+ return out if out.strip() else text++ def submit(self, text, lang, voice, max_frames, rid, max_lag_s, on_overflow=None, sampling=None):+ """Admit and submit a request. Raises ApiError (overloaded / unavailable / invalid)."""+ if len(self._waiting) >= self.max_pending:+ self.stats["rejected_pending"] += 1+ raise ApiError(503, "overloaded", f"server overloaded: {len(self._waiting)} requests already waiting "+ f"for audio (max_pending={self.max_pending}); retry later", retry_after=1)+ job = Job(self, rid, asyncio.get_running_loop(), max_lag_s, on_overflow)+ try:+ kw = {"sampling": sampling} if sampling else {}+ job.req = self.engine.submit(text, lang, voice, on_event=job.on_event, max_frames=max_frames, rid=rid, **kw)+ except KeyError as exc:+ raise bad(str(exc).strip("'\""), "voice")+ except ValueError as exc:+ raise bad(str(exc))+ except RuntimeError as exc:+ raise ApiError(503, "unavailable", str(exc))+ self._waiting.add(job)+ self._jobs.add(job)+ self.stats["submitted"] += 1+ return job++ async def first_event(self, job, gone=None):+ """Wait for the job's first event within the queue deadline; on expiry cancel it and raise Overloaded."""+ limit = job.t_submit + self.deadline+ while True:+ remaining = limit - time.perf_counter()+ if remaining <= 0:+ job.close()+ self.stats["rejected_deadline"] += 1+ raise Overloaded(f"no audio within the queue deadline of {self.deadline * 1000:.0f} ms; retry later")+ try:+ return await job.get(timeout=min(remaining, 0.2))+ except asyncio.TimeoutError:+ if gone is not None and gone():+ raise ConnectionResetError("client went away")++ # ------------------------------------------------------------------ HTTP+ async def health(self, request):+ srv = {"waiting": len(self._waiting), "jobs": len(self._jobs), "ws_sockets": self.sockets,+ "max_pending": self.max_pending, "queue_deadline_ms": self.deadline * 1000, "normalise": self.normalise,+ "formats": [f for f in FORMATS if codec_support().get(f) is None], **self.stats}+ if self.tts is None:+ return web.json_response({"ready": False, "loading": self.load_error is None, "failed": self.load_error,+ "server": srv}, status=503)+ try:+ state = dict(self.engine.health())+ except Exception as exc:+ state = {"ready": False, "failed": f"health: {type(exc).__name__}: {exc}"}+ state["server"] = srv+ return web.json_response(state, status=200 if state.get("ready") else 503)++ async def models(self, request):+ return web.json_response({"object": "list", "data": [{"id": "maya3", "object": "model", "owned_by": "maya"}]})++ async def _json(self, request):+ try:+ body = await request.json()+ except Exception:+ raise bad("request body must be a JSON object")+ if not isinstance(body, dict):+ raise bad("request body must be a JSON object")+ return body++ async def speech(self, request):+ try:+ return await self._speech(request)+ except ApiError as exc:+ return exc.response()++ async def _speech(self, request):+ self.ready()+ body = await self._json(request)+ text = parse_text(body.get("input"), "input")+ lang = parse_lang(body, text)+ fmt = body.get("response_format", "wav") or "wav"+ usable = [f for f in FORMATS if codec_support().get(f) is None]+ if not isinstance(fmt, str) or fmt.lower() not in FORMATS:+ why = UNSUPPORTED_FORMATS.get(fmt.lower()) if isinstance(fmt, str) else None+ hint = f" is not supported ({why})" if why else ""+ raise bad(f"response_format {fmt!r}{hint}; use one of: {', '.join(usable)}", "response_format")+ fmt = fmt.lower()+ if codec_support().get(fmt):+ raise bad(f"response_format {fmt!r} is not available on this server ({codec_support()[fmt]}); use one of: "+ f"{', '.join(usable)}", "response_format")+ speed = body.get("speed", 1.0)+ if isinstance(speed, bool) or not isinstance(speed, (int, float)) or float(speed) != 1.0:+ raise bad("speed must be 1.0 (speed control is not supported)", "speed")+ sfmt = body.get("stream_format", "audio") or "audio"+ if sfmt not in ("audio", "sse"):+ raise bad("stream_format must be 'audio' or 'sse'", "stream_format")+ if sfmt == "sse" and fmt not in STREAMED_FORMATS:+ raise bad(f"stream_format 'sse' supports response_format {', '.join(STREAMED_FORMATS)}", "stream_format")+ voice = self.resolve_voice(body.get("voice"))+ max_frames = parse_max_frames(body.get("max_frames"))+ sampling = parse_sampling(body)+ normalize = parse_normalize(body)+ rid = f"h-{uuid.uuid4().hex[:16]}"+ n_chars = len(text)+ text = await self.prepare_text(text, lang, normalize)+ enc = StreamEncoder(fmt) if fmt in STREAMED_FORMATS else None++ def abort():+ if request.transport is not None:+ request.transport.abort()+ job = self.submit(text, lang, voice, max_frames, rid, self.http_max_lag_s, on_overflow=abort, sampling=sampling)+ gone = lambda: request.transport is None or request.transport.is_closing()+ resp = None+ try:+ try:+ kind, payload = await self.first_event(job, gone)+ except Overloaded as exc:+ raise ApiError(503, "overloaded", str(exc), retry_after=1)+ if kind == "error":+ code = payload.get("code")+ status = 400 if code == "invalid_request" else 503+ raise ApiError(status, code or "unavailable", payload.get("error") or "generation failed")+ headers = {"Content-Type": FORMATS[fmt], "X-Sample-Rate": str(SR), "X-Channels": "1",+ "X-Encoding": "pcm_s16le" if fmt in ("wav", "pcm") else fmt, "X-Maya3-Language": lang,+ "X-Maya3-Voice": voice, "X-Maya3-Normalized": "1" if (self.normalise and normalize) else "0",+ "X-Request-Id": rid, "Cache-Control": "no-store"}+ if fmt == "flac":+ pcm = bytearray()+ while kind == "audio":+ pcm += payload.tobytes()+ kind, payload = await job.get()+ if kind != "end":+ raise ApiError(503, payload.get("code") or "unavailable", payload.get("error") or "generation failed")+ data = await asyncio.to_thread(_encode_flac, bytes(pcm))+ self._log_end(rid, "http", lang, voice, n_chars, job, payload)+ return web.Response(body=data, headers=headers)+ sse = sfmt == "sse"+ if sse:+ headers["Content-Type"] = "text/event-stream"++ async def encode(fn, *a):+ return await asyncio.to_thread(fn, *a) if enc.heavy else fn(*a)+ try:+ head = await encode(enc.start)+ except Exception as exc:+ log.exception("%s: %s encoder failed to start", rid, fmt)+ raise ApiError(503, "unavailable", f"{fmt} encoder failed: {type(exc).__name__}: {exc}")+ resp = web.StreamResponse(headers=headers)+ resp.enable_chunked_encoding()+ await resp.prepare(request)++ async def out(data):+ if not data:+ return+ if sse:+ data = b"data: " + json.dumps({"type": "speech.audio.delta",+ "audio": base64.b64encode(data).decode()}).encode() + b"\n\n"+ await resp.write(data)+ await out(head)+ while True:+ if kind == "audio":+ data, _ = job.take_audio(payload, self.coalesce)+ await out(await encode(enc.feed, data))+ elif kind == "end":+ await out(await encode(enc.finish))+ if sse:+ await resp.write(b"data: " + json.dumps({"type": "speech.audio.done", "usage": {+ "audio_s": payload.get("audio_s"), "frames": payload.get("frames"),+ "reason": payload.get("reason")}}).encode() + b"\n\n")+ await resp.write_eof()+ self._log_end(rid, "http", lang, voice, n_chars, job, payload)+ return resp+ elif kind == "error":+ # Never turn a failed utterance into a well-formed end of stream.+ log.warning("%s: error after audio started: %s", rid, payload)+ self.stats["aborted_midstream"] += 1+ abort()+ return resp+ kind, payload = await job.get()+ except asyncio.CancelledError:+ self.stats["client_gone"] += 1+ raise+ except ConnectionResetError: # client went away (or was dropped as a slow consumer)+ self.stats["client_gone"] += 1+ return resp if resp is not None else web.Response(status=499)+ except ApiError:+ if resp is not None: # headers already sent: abort instead of a JSON body+ abort()+ return resp+ raise+ finally:+ if job.overflowed:+ self.stats["slow_consumer"] += 1+ job.close()+ if enc is not None:+ enc.close()++ def _log_end(self, rid, via, lang, voice, chars, job, info):+ self.stats["completed"] += 1+ ttfa = (job.t_first - job.t_submit) * 1000 if job.t_first else None+ log.info("%s %s lang=%s voice=%s chars=%d ttfa_ms=%s audio_s=%.2f reason=%s", rid, via, lang, voice, chars,+ f"{ttfa:.0f}" if ttfa is not None else "-", info.get("audio_s") or 0.0, info.get("reason"))++ # ------------------------------------------------------------------ voices+ async def list_voices(self, request):+ try:+ self.ready()+ except ApiError as exc:+ return exc.response()+ reg = self.engine.registry+ out = []+ for vid in reg.ids():+ try:+ v = reg.get(vid)+ except KeyError:+ continue+ out.append(voice_info(vid, v))+ return web.json_response({"voices": out})++ async def add_voice(self, request):+ try:+ self.ready()+ fields, audio = await self._voice_fields(request)+ vid = fields.get("voice_id") or fields.get("id")+ if not isinstance(vid, str) or not VOICE_ID_RE.match(vid):+ raise bad("voice_id must be 1-64 characters of letters, digits, '_', '.', '-' (starting with a "+ "letter or digit)", "voice_id")+ if vid == "plain":+ raise bad("'plain' is built in and cannot be replaced", "voice_id")+ replace = fields.get("replace") in (True, "true", "1", 1)+ if vid in self.engine.registry and not replace:+ raise ApiError(409, "voice_exists", f"voice {vid!r} already exists; pass replace=true to overwrite",+ "voice_id")+ mode = fields.get("mode") or "icl_spk"+ mode = MODE_ALIASES.get(mode, mode)+ if mode not in MODES:+ raise bad(f"unknown mode {mode!r}; choose one of {', '.join(MODES)}", "mode")+ lang = fields.get("lang") or fields.get("language")+ if lang is not None and lang not in LANGS:+ raise bad(f"unsupported lang {lang!r}; supported: {', '.join(LANGS)}", "lang")+ ref_text = fields.get("ref_text")+ if mode in ("icl", "icl_spk") and (not isinstance(ref_text, str) or not ref_text.strip() or not lang):+ raise bad(f"mode {mode} needs ref_text (the transcript of the clip) and lang (the clip's language)",+ "ref_text")+ if mode != "plain" and audio is None:+ raise bad(f"mode {mode} needs reference audio (ref_audio_b64 or a multipart file 'ref_audio')",+ "ref_audio_b64")+ ref = await asyncio.to_thread(_decode_audio, audio) if audio is not None else None+ t0 = time.perf_counter()+ async with self._voice_lock:+ try:+ await asyncio.to_thread(self.tts.register_voice, vid, ref_audio=ref,+ ref_text=ref_text.strip() if isinstance(ref_text, str) else None,+ lang=lang, mode=mode)+ except (ValueError, KeyError) as exc:+ raise bad(f"could not register voice: {exc}")+ self.stats["voices_registered"] += 1+ info = voice_info(vid, self.engine.registry.get(vid))+ info["ref_lang"] = info["ref_lang"] or (lang if mode in ("icl", "icl_spk") else None)+ return web.json_response({**info, "register_s": round(time.perf_counter() - t0, 3)}, status=201)+ except ApiError as exc:+ return exc.response()++ async def _voice_fields(self, request):+ if request.content_type.startswith("multipart/"):+ fields, audio = {}, None+ reader = await request.multipart()+ async for part in reader:+ if part.name == "ref_audio":+ audio = bytes(await part.read())+ elif part.name:+ fields[part.name] = await part.text()+ return fields, audio+ body = await self._json(request)+ audio = None+ b64 = body.get("ref_audio_b64")+ if b64 is not None:+ if not isinstance(b64, str):+ raise bad("ref_audio_b64 must be a base64 string of a wav/flac file", "ref_audio_b64")+ try:+ audio = base64.b64decode(b64, validate=True)+ except (binascii.Error, ValueError):+ raise bad("ref_audio_b64 is not valid base64", "ref_audio_b64")+ return body, audio++ async def delete_voice(self, request):+ try:+ self.ready()+ vid = request.match_info["voice_id"]+ if vid == "plain":+ raise bad("the plain voice cannot be removed", "voice_id")+ if vid not in self.engine.registry:+ raise ApiError(404, "voice_not_found", f"unknown voice {vid!r}", "voice_id")+ async with self._voice_lock:+ await asyncio.to_thread(self.tts.remove_voice, vid)+ return web.json_response({"id": vid, "deleted": True})+ except ApiError as exc:+ return exc.response()++ # ------------------------------------------------------------------ WebSocket+ async def ws(self, request):+ ws = web.WebSocketResponse(heartbeat=30, max_msg_size=64 * 1024)+ await ws.prepare(request)+ sock = _Socket(self, ws, request)+ self.sockets += 1+ sock.sender = asyncio.create_task(sock.send_loop())+ sock.put({"type": "metadata", "sample_rate": SR, "encoding": "pcm_s16le", "channels": 1,+ "max_contexts": self.ws_max_contexts, "languages": list(LANGS)})+ try:+ async for msg in ws:+ if msg.type == WSMsgType.TEXT:+ sock.handle(msg.data)+ elif msg.type == WSMsgType.BINARY:+ sock.error(None, "invalid_request", "send JSON text messages (speak / cancel / ping)")+ elif msg.type == WSMsgType.ERROR:+ break+ finally:+ self.sockets -= 1+ await sock.shutdown()+ return ws+++class _Context:+ __slots__ = ("cid", "job", "task", "binary", "stop", "samples")++ def __init__(self, cid, binary):+ self.cid, self.binary = cid, binary+ self.job = self.task = self.stop = None+ self.samples = 0+++class _Socket:+ """One WS connection: a reader (the handler), one pump task per context, one sender with a bounded queue."""++ def __init__(self, srv, ws, request):+ self.srv, self.ws, self.request = srv, ws, request+ self.contexts = {}+ self.out = collections.deque() # (cid or None, kind, data)+ self.wake = asyncio.Event()+ self.room = asyncio.Event()+ self.room.set()+ self.closed = False+ self.sender = None++ # -- sending+ def put(self, msg, cid=None, audio=False):+ self.out.append((cid, audio, msg))+ self.wake.set()++ async def put_audio(self, ctx, msg):+ while len(self.out) >= self.srv.ws_send_queue and not self.closed and ctx.stop is None:+ self.room.clear()+ await self.room.wait()+ if self.closed or ctx.stop is not None:+ return False+ self.put(msg, ctx.cid, True)+ return True++ def error(self, cid, code, message):+ self.put({"type": "error", "context_id": cid, "code": code, "error": message})++ async def send_loop(self):+ ws = self.ws+ try:+ while True:+ while not self.out:+ self.wake.clear()+ await self.wake.wait()+ _, _, msg = self.out.popleft()+ if len(self.out) < self.srv.ws_send_queue:+ self.room.set()+ if ws.closed:+ continue+ coro = ws.send_bytes(msg) if isinstance(msg, bytes) else ws.send_str(json.dumps(msg))+ try:+ await asyncio.wait_for(coro, self.srv.ws_send_timeout_s)+ except asyncio.TimeoutError:+ log.warning("ws send blocked > %.0f s; dropping the connection", self.srv.ws_send_timeout_s)+ self.abort()+ return+ except (ConnectionResetError, RuntimeError):+ self.abort()+ return+ except asyncio.CancelledError:+ pass++ def abort(self):+ self.closed = True+ self.room.set()+ for ctx in self.contexts.values():+ self._stop(ctx, "disconnected")+ if self.request.transport is not None:+ self.request.transport.abort()++ # -- receiving+ def handle(self, data):+ cid = None+ try:+ try:+ msg = json.loads(data)+ except ValueError:+ raise bad("message is not valid JSON")+ if not isinstance(msg, dict):+ raise bad("message must be a JSON object")+ cid = msg.get("context_id")+ if cid is not None and (not isinstance(cid, str) or not 1 <= len(cid) <= 128):+ cid = None+ raise bad("context_id must be a string of 1-128 characters", "context_id")+ kind = msg.get("type")+ if kind == "ping":+ self.put({"type": "pong", **({"context_id": cid} if cid else {})})+ elif kind == "cancel":+ ctx = self.contexts.get(cid)+ if ctx is not None: # unknown / finished contexts: idempotent no-op+ self._stop(ctx, "cancelled")+ elif kind == "speak":+ self._speak(cid, msg)+ else:+ raise bad("unknown message type; use speak, cancel or ping", "type")+ except ApiError as exc:+ self.error(cid, exc.code, exc.message)++ def _speak(self, cid, msg):+ srv = self.srv+ if cid is None:+ raise bad("speak needs a context_id", "context_id")+ if cid in self.contexts:+ raise bad(f"context {cid!r} is still active; use a new context_id", "context_id")+ if len(self.contexts) >= srv.ws_max_contexts:+ raise ApiError(429, "too_many_contexts",+ f"at most {srv.ws_max_contexts} concurrent contexts per connection")+ srv.ready()+ text = parse_text(msg.get("text"), "text")+ lang = parse_lang(msg, text)+ voice = srv.resolve_voice(msg.get("voice"))+ max_frames = parse_max_frames(msg.get("max_frames"))+ binary = msg.get("binary", False)+ if not isinstance(binary, bool):+ raise bad("binary must be true or false", "binary")+ sampling = parse_sampling(msg)+ normalize = parse_normalize(msg)+ ctx = _Context(cid, binary)+ chars = len(text)+ deferred = None+ if srv.normalise and normalize and len(text) > NORMALISE_INLINE_CHARS:+ deferred = (text, sampling, max_frames) # normalised on a worker thread, then submitted by _pump+ else:+ if srv.normalise and normalize:+ text = _normaliser()(text, lang) or text+ srv.stats["normalised"] += 1+ self._submit(ctx, text, lang, voice, max_frames, sampling)+ self.contexts[cid] = ctx+ ctx.task = asyncio.create_task(self._pump(ctx, lang, voice, chars, deferred))++ def _submit(self, ctx, text, lang, voice, max_frames, sampling):+ ctx.job = self.srv.submit(text, lang, voice, max_frames, f"w-{uuid.uuid4().hex[:12]}", self.srv.ws_max_lag_s,+ on_overflow=lambda: self._stop(ctx, "slow_consumer"), sampling=sampling)++ def _stop(self, ctx, reason):+ if ctx.stop is None:+ ctx.stop = reason+ if ctx.job is not None:+ ctx.job.close()+ ctx.job.interrupt()+ # drop audio of this context that has not been sent yet+ if any(c == ctx.cid and a for c, a, _ in self.out):+ self.out = collections.deque(x for x in self.out if not (x[0] == ctx.cid and x[1]))+ self.room.set()++ async def _pump(self, ctx, lang, voice, chars, deferred=None):+ srv, cid = self.srv, ctx.cid+ job = None+ try:+ if deferred is not None:+ text, sampling, max_frames = deferred+ text = await srv.prepare_text(text, lang)+ if ctx.stop is not None:+ if ctx.stop == "cancelled":+ self.put({"type": "end", "context_id": cid, "reason": "cancelled", "frames": 0, "audio_s": 0.0,+ "ttfa_ms": None})+ srv.stats["cancelled"] += 1+ return+ try:+ self._submit(ctx, text, lang, voice, max_frames, sampling)+ except ApiError as exc:+ self.error(cid, exc.code, exc.message)+ return+ job = ctx.job+ try:+ kind, payload = await srv.first_event(job)+ except Overloaded as exc:+ self.error(cid, "overloaded", str(exc))+ return+ while ctx.stop is None:+ if kind == "audio":+ pcm, n = job.take_audio(payload, srv.coalesce)+ msg = ws_binary_frame(cid, pcm) if ctx.binary else \+ {"type": "audio", "context_id": cid, "audio": base64.b64encode(pcm).decode()}+ if await self.put_audio(ctx, msg):+ ctx.samples += n+ elif kind == "end":+ self.put({"type": "end", "context_id": cid, "reason": payload.get("reason"),+ "frames": payload.get("frames"), "audio_s": payload.get("audio_s"),+ "ttfa_ms": self._ttfa(job, payload)})+ srv._log_end(job.rid, "ws", lang, voice, chars, job, payload)+ return+ elif kind == "error":+ code = payload.get("code") or "internal"+ self.error(cid, code, payload.get("error") or code)+ return+ kind, payload = await job.get()+ if ctx.stop == "cancelled":+ self.put({"type": "end", "context_id": cid, "reason": "cancelled", "frames": ctx.samples // FRAME,+ "audio_s": round(ctx.samples / SR, 3), "ttfa_ms": self._ttfa(job, {})})+ srv.stats["cancelled"] += 1+ elif ctx.stop == "slow_consumer":+ srv.stats["slow_consumer"] += 1+ self.error(cid, "slow_consumer", f"client fell more than {srv.ws_max_lag_s:.0f} s of audio behind; "+ "request cancelled")+ except asyncio.CancelledError:+ pass+ except Exception as exc: # pragma: no cover - defensive+ log.exception("ws context %s failed", cid)+ self.error(cid, "internal", f"{type(exc).__name__}: {exc}")+ finally:+ if job is not None:+ job.close()+ if self.contexts.get(cid) is ctx:+ del self.contexts[cid]++ @staticmethod+ def _ttfa(job, info):+ if info.get("ttfa_s") is not None:+ return round(info["ttfa_s"] * 1000, 1)+ return round((job.t_first - job.t_submit) * 1000, 1) if job.t_first else None++ async def shutdown(self):+ self.closed = True+ self.room.set()+ ctxs = list(self.contexts.values())+ for ctx in ctxs:+ self._stop(ctx, "disconnected")+ ctx.task.cancel()+ await asyncio.gather(*(c.task for c in ctxs), return_exceptions=True)+ if self.sender is not None:+ self.sender.cancel()+ await asyncio.gather(self.sender, return_exceptions=True)+++# ---------------------------------------------------------------------------------------------------- audio io+_CODECS = None+++def codec_support():+ """{format: None (ok) | reason} for the formats encoded by libsndfile (checked once)."""+ global _CODECS+ if _CODECS is None:+ out = {}+ try:+ import soundfile as sf+ formats = sf.available_formats()+ for fmt, (major, sub) in SF_CODECS.items():+ ok = major in formats and sub in sf.available_subtypes(major)+ out[fmt] = None if ok else f"this libsndfile ({sf.__libsndfile_version__}) cannot write {major}/{sub}"+ out["flac"] = None if "FLAC" in formats else "this libsndfile cannot write FLAC"+ except Exception as exc: # soundfile missing / broken+ out = {f: f"soundfile unavailable ({type(exc).__name__}: {exc})" for f in ("mp3", "opus", "flac")}+ _CODECS = out+ return _CODECS+++class _AppendSink(io.RawIOBase):+ """Write-only file object for libsndfile that hands out bytes as soon as they are appended. libsndfile seeks back+ at close to patch headers it already wrote (the MP3 LAME/Info frame); bytes already handed out cannot change, so+ such rewrites are dropped. For MP3 the blank Info placeholder (the first write) is withheld entirely: a stream of+ plain CBR frames is valid MP3, while a never-filled Info frame misleads decoders about the length."""++ def __init__(self, skip_blank_first=False):+ self.buf = bytearray() # bytes not yet taken+ self.base = 0 # stream offset of buf[0]+ self.pos = 0+ self.skip = skip_blank_first+ self.n_writes = 0++ def writable(self):+ return True++ def seekable(self):+ return True++ def readable(self):+ return False++ def write(self, b):+ b = bytes(b)+ n = len(b)+ self.n_writes += 1+ end = self.base + len(self.buf)+ if self.n_writes == 1 and self.skip and self.pos == 0 and n > 4 and b[0] == 0xFF and (b[1] & 0xE0) == 0xE0 \+ and not any(b[4:]):+ self.base = n # withheld placeholder frame+ elif self.pos >= end:+ if self.pos > end: # never happens for append-only encoders; keep the stream well-formed anyway+ self.buf.extend(b"\0" * (self.pos - end))+ self.buf.extend(b)+ elif self.pos + n > end: # partial overlap with handed-out bytes: keep only the new tail+ self.buf.extend(b[end - self.pos:])+ self.pos += n+ return n++ def seek(self, offset, whence=0):+ end = self.base + len(self.buf)+ self.pos = offset if whence == 0 else (self.pos + offset if whence == 1 else end + offset)+ return self.pos++ def tell(self):+ return self.pos++ def take(self):+ out = bytes(self.buf)+ self.base += len(self.buf)+ self.buf.clear()+ return out+++class StreamEncoder:+ """Incremental encoder for one HTTP response: start() -> header bytes, feed(pcm s16le) -> bytes, finish() -> tail.+ wav/pcm are pass-through (cheap, called on the event loop); mp3/opus run libsndfile (call feed/finish off-loop;+ `heavy` is True)."""++ def __init__(self, fmt):+ self.fmt = fmt+ self.heavy = fmt in SF_CODECS+ self.sf = self.sink = None+ self.lock = threading.Lock()+ self.closed = False++ def start(self):+ if self.fmt == "wav":+ return wav_header()+ if not self.heavy:+ return b""+ import soundfile as sf+ major, sub = SF_CODECS[self.fmt]+ self.sink = _AppendSink(skip_blank_first=self.fmt == "mp3")+ kw = {"bitrate_mode": "CONSTANT", "compression_level": MP3_LEVEL} if self.fmt == "mp3" else {}+ self.sf = sf.SoundFile(self.sink, "w", samplerate=SR, channels=1, format=major, subtype=sub, **kw)+ return self.sink.take()++ def feed(self, pcm):+ if not self.heavy:+ return pcm+ import numpy as np+ with self.lock:+ if self.closed:+ return b""+ self.sf.write(np.frombuffer(pcm, np.int16))+ return self.sink.take()++ def finish(self):+ if not self.heavy:+ return b""+ with self.lock:+ if self.closed:+ return b""+ self.closed = True+ self.sf.close()+ return self.sink.take()++ def close(self):+ if self.heavy and self.sf is not None:+ with self.lock:+ if not self.closed:+ self.closed = True+ try:+ self.sf.close()+ except Exception:+ pass+++def _encode_flac(pcm):+ import numpy as np+ import soundfile as sf+ buf = io.BytesIO()+ sf.write(buf, np.frombuffer(pcm, np.int16), SR, format="FLAC", subtype="PCM_16")+ return buf.getvalue()+++def _decode_audio(data):+ """wav/flac/ogg bytes -> (float32 mono array, sample rate); Maya3TTS resamples to 24 kHz."""+ import numpy as np+ import soundfile as sf+ try:+ w, sr = sf.read(io.BytesIO(data), dtype="float32", always_2d=True)+ except Exception as exc:+ raise bad(f"could not decode reference audio ({exc}); send a wav or flac file", "ref_audio_b64")+ w = w.mean(1).astype(np.float32)+ dur = len(w) / sr if sr else 0+ if dur < 0.5:+ raise bad(f"reference audio is {dur:.2f} s; need at least 0.5 s (3-10 s works best)", "ref_audio_b64")+ if dur > 30:+ raise bad(f"reference audio is {dur:.1f} s; the limit is 30 s (3-10 s works best)", "ref_audio_b64")+ return (w, int(sr))+++# ---------------------------------------------------------------------------------------------------- CLI+def load_voices_file(tts, path):+ path = Path(path)+ spec = json.loads(path.read_text())+ items = spec["voices"] if isinstance(spec, dict) else spec+ for it in items:+ ref = it.get("ref_audio")+ if ref is not None and not Path(ref).is_absolute():+ ref = str(path.parent / ref)+ kw = {"meta": it["meta"]} if isinstance(it.get("meta"), dict) else {}+ tts.register_voice(it["voice_id"], ref_audio=ref, ref_text=it.get("ref_text"), lang=it.get("lang"),+ mode=it.get("mode", "icl_spk"), **kw)+ log.info("registered voice %s (%s)", it["voice_id"], it.get("mode", "icl_spk"))+++def main(argv=None):+ ap = argparse.ArgumentParser(description="Maya3 TTS server (OpenAI-compatible HTTP + WebSocket streaming)")+ ap.add_argument("--ckpt", required=True, help="model checkpoint, or a Maya3 release directory (then --backbone-dir "+ "and --mimi-dir may be omitted)")+ ap.add_argument("--backbone-dir", default=None)+ ap.add_argument("--mimi-dir", default=None)+ ap.add_argument("--ecapa-dir", default=None, help="needed to register reference-audio voices")+ ap.add_argument("--host", default="127.0.0.1")+ ap.add_argument("--port", type=int, default=8080)+ ap.add_argument("--device", default="cuda")+ ap.add_argument("--max-seats", type=int, default=64, help="concurrent generations batched on the GPU")+ ap.add_argument("--capacity", type=int, default=None, help="EngineConfig.capacity (KV tokens per seat)")+ ap.add_argument("--depth-dtype", choices=["fp16", "bf16", "fp32"], default=None)+ ap.add_argument("--max-pending", type=int, default=None,+ help="max requests waiting for their first audio (default: max-seats)")+ ap.add_argument("--queue-deadline-ms", type=float, default=2000)+ ap.add_argument("--voices", default=None, help="voices.json to register at startup")+ ap.add_argument("--ws-max-contexts", type=int, default=8, help="concurrent contexts per WebSocket")+ ap.add_argument("--ws-max-lag-s", type=float, default=20.0,+ help="cancel a WS request when this much generated audio is waiting to be sent")+ ap.add_argument("--http-max-lag-s", type=float, default=120.0)+ ap.add_argument("--busy-frac", type=float, default=None, help="EngineConfig.busy_frac (admission smoothing under load)")+ ap.add_argument("--busy-admit", type=int, default=None, help="EngineConfig.busy_admit (prefills per tick when busy)")+ ap.add_argument("--no-normalise", "--no-normalize", dest="no_normalise", action="store_true",+ help="turn the bundled text normaliser off for every request (default: on; per request: "+ "\"normalize\": false)")+ ap.add_argument("--log-level", default="INFO")+ args = ap.parse_args(argv)+ if args.max_seats < 1 or args.queue_deadline_ms <= 0 or (args.max_pending is not None and args.max_pending < 1):+ ap.error("max-seats and max-pending must be >= 1 and queue-deadline-ms > 0")+ logging.basicConfig(level=args.log_level, format="%(asctime)s %(levelname)s %(name)s: %(message)s")++ def loader():+ from maya3.api import Maya3TTS+ cfg = {"max_seats": args.max_seats}+ if args.capacity:+ cfg["capacity"] = args.capacity+ if args.depth_dtype:+ cfg["depth_dtype"] = args.depth_dtype+ if args.busy_frac is not None:+ cfg["busy_frac"] = args.busy_frac+ if args.busy_admit is not None:+ cfg["busy_admit"] = args.busy_admit+ tts = Maya3TTS.from_pretrained(args.ckpt, args.backbone_dir, args.mimi_dir, ecapa_dir=args.ecapa_dir,+ device=args.device, **cfg)+ if args.voices:+ load_voices_file(tts, args.voices)+ return tts++ srv = Maya3Server(loader=loader, max_pending=args.max_pending or args.max_seats,+ queue_deadline_ms=args.queue_deadline_ms, ws_max_contexts=args.ws_max_contexts,+ ws_max_lag_s=args.ws_max_lag_s, http_max_lag_s=args.http_max_lag_s,+ normalise=not args.no_normalise)+ web.run_app(srv.app(), host=args.host, port=args.port, access_log=None, handler_cancellation=True,+ print=lambda *a: log.info("listening on http://%s:%d", args.host, args.port))+++if __name__ == "__main__":+ main()diff --git a/maya3/tests/__init__.py b/maya3/tests/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/maya3/tests/data_backstop_cuts.json b/maya3/tests/data_backstop_cuts.jsonnew file mode 100644index 0000000..37de1d5--- /dev/null+++ b/maya3/tests/data_backstop_cuts.json@@ -0,0 +1,420 @@+[+{+"id": "as-0007__icl__chunks",+"lang": "as",+"text": "পেমেণ্ট সম্পৰ্কীয় কোনো অভিযোগ থাকিলে আমাৰ লেণ্ডলাইন নম্বৰ শূন্য, তিন, ছয়, এক, দুই, তিন, চার, পাঁচ, ছয়, সাত, আট ত অফিচৰ সময়ত কল কৰক।",+"cut": 212,+"kind": "none",+"v1": false,+"v2": false,+"asr_words": 13,+"text_words": 24+},+{+"id": "emo_bn-0065_whispers__plain__tagged",+"lang": "bn",+"text": "[whispers] আরে শোন, আমি তোকে দুইশো পঞ্চাশ টাকা ইউপিআই করে দিয়েছি। তুই একবার গুগল পে চেক করে নে তো।",+"cut": 150,+"kind": "tag",+"v1": false,+"v2": true,+"asr_words": 10,+"text_words": 18+},+{+"id": "emo_bn-0162_curious__plain__tagged",+"lang": "bn",+"text": "আমি কি আপনার রেজিস্টার্ড মোবাইল নম্বর নয়, আট, সাত. [curious] ছয়, পাঁচ, চার, তিন, দুই, এক, শূন্য-এ একটি OTP পাঠাব?",+"cut": 192,+"kind": "tag",+"v1": false,+"v2": true,+"asr_words": 10,+"text_words": 19+},+{+"id": "emo_en-0065_sighs__plain__tagged",+"lang": "en",+"text": "Umm, before you drop off, Rahul, would you be interested in upgrading to the Platinum card? [sighs] The annual fee is just nine hundred ninety nine rupees, and you get free lounge access.",+"cut": 160,+"kind": "tag",+"v1": false,+"v2": true,+"asr_words": 15,+"text_words": 32+},+{+"id": "emo_en-0162_curious__plain__tagged",+"lang": "en",+"text": "Welcome to HDFC Bank. Press one for credit card queries, press two [curious] for savings accounts, or press three to speak with our customer care executive.",+"cut": 140,+"kind": "tag",+"v1": false,+"v2": true,+"asr_words": 10,+"text_words": 25+},+{+"id": "emo_gu-0065_sighs__plain__tagged",+"lang": "gu",+"text": "અચ્છા, તમે લાઈન પર જ રહેજો, હું તમારી વિગતો ચેક [sighs] કરું છું. આમાં બે થી ત્રણ મિનિટ લાગી શકે છે.",+"cut": 144,+"kind": "tag",+"v1": false,+"v2": true,+"asr_words": 10,+"text_words": 20+},+{+"id": "emo_gu-0161_sad__plain__tagged",+"lang": "gu",+"text": "[sad] ખાતાની જાણકારી માટે એક દબાવો, ક્રેડિટ કાર્ડ માટે બે દબાવો, અથવા ગ્રાહક સેવા અધિકારી સાથે વાત કરવા માટે નવ દબાવો.",+"cut": 144,+"kind": "tag",+"v1": false,+"v2": true,+"asr_words": 12,+"text_words": 20+},+{+"id": "emo_gu-0162_curious__icl_spk__tagged",+"lang": "gu",+"text": "હું તમારો OTP નવ, આઠ, સાત, છ, પાંચ, ચાર, ત્રણ. [curious] બે, એક, શૂન્ય પર મોકલી રહ્યો છું, શું આ સાચું છે?",+"cut": 142,+"kind": "tag",+"v1": false,+"v2": true,+"asr_words": 10,+"text_words": 21+},+{+"id": "emo_hi-0064_sighs__plain__tagged",+"lang": "hi",+"text": "हाँ तो, आपका जो पेमेंट फेल हुआ था ना. [sighs] बारह मई को, उसका रिफंड प्रोसेस हो गया है।",+"cut": 138,+"kind": "tag",+"v1": false,+"v2": true,+"asr_words": 12,+"text_words": 18+},+{+"id": "emo_hi-0161_sad__plain__tagged",+"lang": "hi",+"text": "[sad] अपने बैंक खाते की शेष राशि जानने के लिए एक दबाएं, क्रेडिट कार्ड सेवाओं के लिए दो दबाएं, और हमारे ग्राहक सेवा अधिकारी से बात करने के लिए नौ दबाएं।",+"cut": 168,+"kind": "tag",+"v1": false,+"v2": true,+"asr_words": 18,+"text_words": 30+},+{+"id": "emo_kn-0063_sighs__plain__tagged",+"lang": "kn",+"text": "ಸರಿ, ದಯವಿಟ್ಟು ಲೈನ್ನಲ್ಲಿರಿ, ನಾನು ನಿಮ್ಮ ಕರೆಯನ್ನು ಒಂದು, ಎಂಟು, ಸೊನ್ನೆ. [sighs] ಸೊನ್ನೆ, ಒಂಬತ್ತು, ಎಂಟು, ಏಳು, ಆರು, ಐದು, ನಾಲ್ಕು, ಮೂರಕ್ಕೆ ವರ್ಗಾಯಿಸುತ್ತೇನೆ.",+"cut": 200,+"kind": "tag",+"v1": false,+"v2": true,+"asr_words": 9,+"text_words": 18+},+{+"id": "emo_kn-0066_whispers__plain__tagged",+"lang": "kn",+"text": "[whispers] ಆ, ನಿಮ್ಮ ಉಳಿತಾಯ ಖಾತೆಯಲ್ಲಿ ಈಗ ಹನ್ನೆರಡು ಸಾವಿರದ ನಾನೂರ ಐವತ್ತು ರೂಪಾಯಿ ಐವತ್ತು ಪೈಸೆ ಬ್ಯಾಲೆನ್ಸ್ ಇದೆ. ಬೇರೆ ಏನಾದರೂ ಸಹಾಯ ಬೇಕೇ?",+"cut": 208,+"kind": "tag",+"v1": false,+"v2": true,+"asr_words": 14,+"text_words": 18+},+{+"id": "emo_ml-0061_laughs__plain__tagged",+"lang": "ml",+"text": "[laughs] നമസ്കാരം, എച്ച്ഡിഎഫ്സി ബാങ്കിൽ നിന്ന് ഞാൻ അഞ്ജലി. ഉം, നിങ്ങളുടെ അക്കൗണ്ട് നമ്പർ നാല്, അഞ്ച്, മൂന്ന്, രണ്ടിൽ തുടങ്ങുന്നതാണോ?",+"cut": 108,+"kind": "tag",+"v1": false,+"v2": true,+"asr_words": 1,+"text_words": 15+},+{+"id": "emo_ml-0161_sad__plain__tagged",+"lang": "ml",+"text": "[sad] ഞാൻ OTP ഒമ്പത്, എട്ട്, ഏഴ്, ആറ്, അഞ്ച്, നാല്, മൂന്ന്, രണ്ട്, ഒന്ന്, പൂജ്യം എന്ന നമ്പറിലേക്ക് അയക്കുകയാണ്, ഇത് ശരിയാണോ?",+"cut": 240,+"kind": "tag",+"v1": false,+"v2": true,+"asr_words": 9,+"text_words": 17+},+{+"id": "emo_mr-0067_whispers__plain__tagged",+"lang": "mr",+"text": "[whispers] अरे ऐक ना, काल रात्रीच्या जेवणाचे एक हजार दोनशे पन्नास रुपये झाले होते. उम्म, तू मला गुगल पे करतोस का? माझा नंबर तर आहेच ना तुझ्याकडे?",+"cut": 122,+"kind": "tag",+"v1": false,+"v2": true,+"asr_words": 3,+"text_words": 26+},+{+"id": "emo_mr-0068_excited__icl_spk__tagged",+"lang": "mr",+"text": "तुमची नवीन चेकबुक पंचेचाळीस, शिवाजी नगर, पुणे, चार, एक, एक, शून्य, शून्य. [excited] पाच या पत्त्यावर सात दिवसांत पाठवली जाईल. हा पत्ता बरोबर आहे ना?",+"cut": 162,+"kind": "tag",+"v1": false,+"v2": true,+"asr_words": 11,+"text_words": 24+},+{+"id": "emo_mr-0068_excited__plain__tagged",+"lang": "mr",+"text": "तुमची नवीन चेकबुक पंचेचाळीस, शिवाजी नगर, पुणे, चार, एक, एक, शून्य, शून्य. [excited] पाच या पत्त्यावर सात दिवसांत पाठवली जाईल. हा पत्ता बरोबर आहे ना?",+"cut": 198,+"kind": "tag",+"v1": false,+"v2": true,+"asr_words": 11,+"text_words": 24+},+{+"id": "emo_mr-0161_sad__plain__tagged",+"lang": "mr",+"text": "[sad] मराठीसाठी एक दाबा, हिंदीसाठी दोन दाबा, आणि इंग्रजीसाठी तीन दाबा.",+"cut": 82,+"kind": "tag",+"v1": false,+"v2": true,+"asr_words": 1,+"text_words": 10+},+{+"id": "emo_mr-0163_curious__plain__tagged",+"lang": "mr",+"text": "तुमचे क्रेडिट कार्ड ज्याचे शेवटचे चार अंक चार, पाच. [curious] तीन, दोन आहेत, ते हरवल्याची नोंद करण्यासाठी कृपया एक दाबा.",+"cut": 136,+"kind": "tag",+"v1": false,+"v2": true,+"asr_words": 9,+"text_words": 19+},+{+"id": "emo_or-0067_excited__icl_spk__tagged",+"lang": "or",+"text": "ମୁଁ ବୁଝିପାରୁଛି, ଏହା ବହୁତ ବିରକ୍ତିକର। ଉମ୍, ଆପଣଙ୍କ EMI ବାବଦକୁ [excited] ବାର ହଜାର ଚାରି ଶହ ପଚାଶ ଟଙ୍କାର ପେମେଣ୍ଟ ବାକି ଅଛି।",+"cut": 226,+"kind": "tag",+"v1": false,+"v2": true,+"asr_words": 11,+"text_words": 18+},+{+"id": "emo_or-0161_sad__plain__tagged",+"lang": "or",+"text": "[sad] ସଞ୍ଚୟ ଖାତା ପାଇଁ ଏକ ଦବାନ୍ତୁ, ଚଳିତ ଖାତା ପାଇଁ ଦୁଇ ଦବାନ୍ତୁ ଏବଂ ଋଣ ବିଷୟରେ ଜାଣିବା ପାଇଁ ତିନି ଦବାନ୍ତୁ।",+"cut": 200,+"kind": "tag",+"v1": false,+"v2": true,+"asr_words": 10,+"text_words": 17+},+{+"id": "emo_ta-0068_whispers__plain__tagged",+"lang": "ta",+"text": "[whispers] உங்கள் உதவிக்கு மிக்க நன்றி. உங்கள் கணக்கில் மீதமுள்ள தொகை பன்னிரண்டாயிரத்து நானூற்று ஐம்பது ரூபாய். வேறு ஏதேனும் உதவி தேவையா?",+"cut": 102,+"kind": "tag",+"v1": false,+"v2": true,+"asr_words": 4,+"text_words": 16+},+{+"id": "emo_ta-0163_excited__plain__tagged",+"lang": "ta",+"text": "எச்சரிக்கை! உங்கள் வங்கி கணக்கிலிருந்து பதினைந்தாயிரத்து ஐந்நூறு ரூபாய் எடுக்கப்பட்டுள்ளது. [excited] நீங்கள் இதை செய்யவில்லை என்றால், உடனடியாக எங்களை தொடர்பு கொள்ளவும்.",+"cut": 184,+"kind": "tag",+"v1": false,+"v2": true,+"asr_words": 8,+"text_words": 16+},+{+"id": "emo_ta-0164_sad__plain__tagged",+"lang": "ta",+"text": "[sad] உங்களின் பன்னிரண்டு இலக்க ஆதார் எண் அல்லது PAN எண்ணை உள்ளிடவும்.",+"cut": 78,+"kind": "tag",+"v1": false,+"v2": true,+"asr_words": 1,+"text_words": 9+},+{+"id": "emo_te-0065_whispers__plain__tagged",+"lang": "te",+"text": "[whispers] సరే సార్, మీ రిజిస్టర్డ్ మొబైల్ నంబర్ తొమ్మిది, ఎనిమిది, ఏడు, ఆరు, ఐదు, ఒకటి, రెండు, మూడు, నాలుగు, ఐదుకి ఒక ఓటీపీ పంపాను, అది చెప్పగలరా?",+"cut": 250,+"kind": "tag",+"v1": false,+"v2": true,+"asr_words": 13,+"text_words": 21+},+{+"id": "emo_te-0161_sad__plain__tagged",+"lang": "te",+"text": "[sad] నేను మీ OTP ని తొమ్మిది, ఎనిమిది, ఏడు, ఆరు, ఐదు, నాలుగు, మూడు, రెండు, ఒకటి, సున్నాకి పంపుతున్నాను, ఇది సరైనదేనా?",+"cut": 294,+"kind": "tag",+"v1": false,+"v2": true,+"asr_words": 13,+"text_words": 17+},+{+"id": "hal_ml_list_2__plain__raw",+"lang": "ml",+"text": "ശരി, ഞാൻ, ഇതൊന്ന്, ചെക്ക്, ചെയ്യട്ടെ, ആഹ്, ഒരു, മിനിറ്റ്.",+"cut": 124,+"kind": "none",+"v1": false,+"v2": false,+"asr_words": 4,+"text_words": 8+},+{+"id": "kn-0039__icl_spk__raw",+"lang": "kn",+"text": "ನಿಮ್ಮ ಕ್ರೆಡಿಟ್ ಕಾರ್ಡ್ ಬಿಲ್ ಹದಿನೈದು ಸಾವಿರದ ಆರುನೂರ ಎಪ್ಪತ್ತು ರೂಪಾಯಿ ಬಾಕಿ ಇದೆ, and the due date is ಇಪ್ಪತ್ತೈದನೇ ಅಕ್ಟೋಬರ್ ಎರಡು ಸಾವಿರದ ಇಪ್ಪತ್ತಮೂರು, ನೀವು ಲೇಟ್ ಪೇಮೆಂಟ್ ಚಾರ್ಜ್ ಐನೂರು ರೂಪಾಯಿ ಕಟ್ಟಬೇಕಾಗುತ್ತದೆ.",+"cut": 282,+"kind": "none",+"v1": false,+"v2": false,+"asr_words": 19,+"text_words": 28+},+{+"id": "kn-0063__icl_spk__raw",+"lang": "kn",+"text": "ಸರಿ, ದಯವಿಟ್ಟು ಲೈನ್ನಲ್ಲಿರಿ, ನಾನು ನಿಮ್ಮ ಕರೆಯನ್ನು ಒಂದು, ಎಂಟು, ಸೊನ್ನೆ, ಸೊನ್ನೆ, ಒಂಬತ್ತು, ಎಂಟು, ಏಳು, ಆರು, ಐದು, ನಾಲ್ಕು, ಮೂರಕ್ಕೆ ವರ್ಗಾಯಿಸುತ್ತೇನೆ.",+"cut": 236,+"kind": "none",+"v1": false,+"v2": false,+"asr_words": 19,+"text_words": 18+},+{+"id": "kn-0147__icl_spk__raw",+"lang": "kn",+"text": "ಈ ಸಾಲದ ಪ್ರಕ್ರಿಯೆಗೆ ಐದು ಸಾವಿರದ ಒಂಬೈನೂರು ರೂಪಾಯಿ ಪರಿಶೀಲನಾ ಶುಲ್ಕವನ್ನು ವಿಧಿಸಲಾಗುತ್ತದೆ. ಹೆಚ್ಚಿನ ವಿವರಗಳಿಗಾಗಿ ನೀವು ನಮ್ಮ ಶಾಖೆಯ ವ್ಯವಸ್ಥಾಪಕ ಶ್ರೀ ರಮೇಶ್ ರಾವ್ ಅವರನ್ನು ಸಂಪರ್ಕಿಸಬಹುದು. ಅವರ ಕಚೇರಿ ವಿಳಾಸ, ಎರಡನೇ ಮಹಡಿ, ಕಮರ್ಷಿಯಲ್ ಕಾಂಪ್ಲೆಕ್ಸ್, ಮಲ್ಲೇಶ್ವರಂ ಎಂಟನೇ ಕ್ರಾಸ್, ಬೆಂಗಳೂರು ಐದು ಲಕ್ಷದ ಅರವತ್ತು ಸಾವಿರದ ಮೂರು.",+"cut": 364,+"kind": "none",+"v1": false,+"v2": false,+"asr_words": 217,+"text_words": 37+},+{+"id": "xl_bn-0062_en__spk__chunks",+"lang": "bn",+"text": "আমি বুঝতে পারছি আপনার সমস্যাটা, উম, আপনার পাঁচ হাজার চারশো টাকা কেটে নিয়েছে কিন্তু পেমেন্টটা ফেল হয়েছে, তাই তো?",+"cut": 110,+"kind": "filler",+"v1": false,+"v2": true,+"asr_words": 5,+"text_words": 19+},+{+"id": "ctl_kn_plain_kn-0061",+"lang": "kn",+"text": "ನಮಸ್ಕಾರ, ನಾನು ರಮೇಶ್. ಹ್ಮ್, ನಿಮ್ಮ ಕ್ರೆಡಿಟ್ ಕಾರ್ಡ್ ನಂಬರ್ ನಾಲ್ಕು, ಒಂದು, ಒಂದು, ಒಂದು, ಎರಡು, ಮೂರು, ನಾಲ್ಕು, ಐದು, ಆರು, ಏಳು, ಎಂಟು, ಒಂಬತ್ತು, ಸೊನ್ನೆ, ಸೊನ್ನೆ, ಸೊನ್ನೆ, ಸೊನ್ನೆ ಅನ್ನು ದೃಢೀಕರಿಸಬಹುದೇ?",+"cut": 114,+"kind": "filler",+"v1": false,+"v2": true,+"asr_words": 3,+"text_words": 26+},+{+"id": "nm_Hrishi_kn_plain_kn-0061",+"lang": "kn",+"text": "ನಮಸ್ಕಾರ, ನಾನು ರಮೇಶ್. ಹ್ಮ್, ನಿಮ್ಮ ಕ್ರೆಡಿಟ್ ಕಾರ್ಡ್ ನಂಬರ್ ನಾಲ್ಕು, ಒಂದು, ಒಂದು, ಒಂದು, ಎರಡು, ಮೂರು, ನಾಲ್ಕು, ಐದು, ಆರು, ಏಳು, ಎಂಟು, ಒಂಬತ್ತು, ಸೊನ್ನೆ, ಸೊನ್ನೆ, ಸೊನ್ನೆ, ಸೊನ್ನೆ ಅನ್ನು ದೃಢೀಕರಿಸಬಹುದೇ?",+"cut": 108,+"kind": "filler",+"v1": false,+"v2": true,+"asr_words": 3,+"text_words": 26+},+{+"id": "nm_Poorvi_hi_dialogue_d0",+"lang": "hi",+"text": "रोहन: क्या आप आज मीटिंग में आ रहे हैं? प्रिया: हाँ, मैं दस बजे तक पहुँच जाऊँगी।",+"cut": 112,+"kind": "speaker",+"v1": false,+"v2": true,+"asr_words": 9,+"text_words": 17+},+{+"id": "nm_Satvik_bn_plain_bn-0061",+"lang": "bn",+"text": "নমস্কার, স্টেট ব্যাঙ্ক অফ ইন্ডিয়া থেকে আমি রাহুল বলছি। আচ্ছা, আপনার অ্যাকাউন্ট নম্বর কি নয়, আট, সাত, ছয়, পাঁচ, চার, তিন, দুই, এক, শূন্য দিয়ে শেষ হচ্ছে?",+"cut": 150,+"kind": "none",+"v1": false,+"v2": false,+"asr_words": 10,+"text_words": 27+},+{+"id": "nm_Siddhant_en_dialogue_d0",+"lang": "en",+"text": "Rohan: are you coming to the meeting today? Priya: yes, I will be there by ten.",+"cut": 122,+"kind": "speaker",+"v1": false,+"v2": true,+"asr_words": 9,+"text_words": 16+},+{+"id": "nm_Vaidehi_hi_dialogue_d0",+"lang": "hi",+"text": "रोहन: क्या आप आज मीटिंग में आ रहे हैं? प्रिया: हाँ, मैं दस बजे तक पहुँच जाऊँगी।",+"cut": 112,+"kind": "speaker",+"v1": false,+"v2": true,+"asr_words": 9,+"text_words": 17+},+{+"id": "nm_Vasant_kn_plain_kn-0061",+"lang": "kn",+"text": "ನಮಸ್ಕಾರ, ನಾನು ರಮೇಶ್. ಹ್ಮ್, ನಿಮ್ಮ ಕ್ರೆಡಿಟ್ ಕಾರ್ಡ್ ನಂಬರ್ ನಾಲ್ಕು, ಒಂದು, ಒಂದು, ಒಂದು, ಎರಡು, ಮೂರು, ನಾಲ್ಕು, ಐದು, ಆರು, ಏಳು, ಎಂಟು, ಒಂಬತ್ತು, ಸೊನ್ನೆ, ಸೊನ್ನೆ, ಸೊನ್ನೆ, ಸೊನ್ನೆ ಅನ್ನು ದೃಢೀಕರಿಸಬಹುದೇ?",+"cut": 156,+"kind": "filler",+"v1": false,+"v2": false,+"asr_words": 8,+"text_words": 26+}+]\ No newline at end of filediff --git a/maya3/tests/fakes.py b/maya3/tests/fakes.pynew file mode 100644index 0000000..de83dc1--- /dev/null+++ b/maya3/tests/fakes.py@@ -0,0 +1,218 @@+"""CPU-only stand-ins for maya3.engine.Engine / maya3.api.Maya3TTS with the same event contract.++FakeEngine runs one thread that "ticks" every `frame_s` seconds: it admits pending requests into at most `max_seats`+seats and emits one 80 ms frame (1920 int16 samples) per active seat per tick, then ('end', {...}). Frame k of a+request is filled with the value k + 1 so tests can check order and completeness of the PCM.+Text directives (for tests): "#frames=N" fixes the frame count, "#error=K" emits ('error', internal) after K frames.+"""+from __future__ import annotations++import collections+import re+import threading+import time+from types import SimpleNamespace++import numpy as np++FRAME = 1920+SR = 24000+++class FakeVoice:+ def __init__(self, vid, mode="plain", ref_lang=None, meta=None, builder=None):+ self.id, self.mode, self.ref_lang = vid, mode, ref_lang+ self.meta, self.builder = dict(meta or {}), builder+++class NamedSpeakerBuilder:+ """Stand-in for maya3.prompt.NamedSpeakerBuilder (the server recognises named voices by mode 'named' or by this+ builder class name)."""++ def __init__(self, template="{{{name}}}: {text}"):+ self.template = template+++def named_voice(name, mode="named", **meta):+ return FakeVoice(name, mode, None, meta={"name": name, **meta}, builder=NamedSpeakerBuilder())+++class FakeRegistry:+ def __init__(self):+ self._v = {"plain": FakeVoice("plain")}+ self._lock = threading.Lock()++ def add(self, v, replace=True):+ with self._lock:+ if not replace and v.id in self._v:+ raise KeyError(f"voice {v.id} exists")+ self._v[v.id] = v+ return v++ def get(self, vid):+ with self._lock:+ if vid not in self._v:+ raise KeyError(f"unknown voice {vid!r}")+ return self._v[vid]++ def remove(self, vid):+ with self._lock:+ if vid == "plain":+ raise KeyError("cannot remove the plain voice")+ return self._v.pop(vid, None)++ def ids(self):+ with self._lock:+ return list(self._v)++ def __contains__(self, vid):+ with self._lock:+ return vid in self._v+++class FakeRequest:+ def __init__(self, rid, text, lang, voice, on_event, frames, error_at, sampling=None):+ self.id, self.text, self.lang, self.voice, self.on_event = rid, text, lang, voice, on_event+ self.sampling = sampling # the sampling= kwarg as received (None when not passed)+ self.n_frames, self.error_at = frames, error_at+ self.cancelled = False+ self.frames = 0+ self.t_submit = time.perf_counter()+ self.t_first = None+ self.events = [] # kinds emitted, for assertions+ self.done = threading.Event()++ def cancel(self):+ self.cancelled = True+++class FakeEngine:+ def __init__(self, max_seats=4, frame_s=0.005, frames_per_char=0.5, min_frames=3):+ self.cfg = SimpleNamespace(max_seats=max_seats)+ self.frame_s, self.frames_per_char, self.min_frames = frame_s, frames_per_char, min_frames+ self.registry = FakeRegistry()+ self.device = "cpu"+ self.failed = None+ self.requests = []+ self._pending = collections.deque()+ self._active = []+ self._cv = threading.Condition()+ self._stop = False+ self._n = 0+ self._thread = threading.Thread(target=self._loop, name="fake-engine", daemon=True)+ self._thread.start()++ def submit(self, text, lang, voice="plain", on_event=None, max_frames=None, rid=None, split=True, sampling=None):+ if isinstance(voice, str):+ voice = self.registry.get(voice)+ if not isinstance(text, str) or not text.strip():+ raise ValueError("text must be a non-empty string")+ if self.failed:+ raise RuntimeError(f"engine failed: {self.failed}")+ if sampling is not None: # same contract as Engine._check_sampling+ bad = set(sampling) - {"seed", "temperature", "top_k", "top_p", "repetition_penalty"}+ if bad:+ raise ValueError(f"unknown sampling keys {sorted(bad)}")+ m = re.search(r"#frames=(\d+)", text)+ n = int(m.group(1)) if m else max(self.min_frames, int(len(text) * self.frames_per_char))+ if max_frames:+ n = min(n, int(max_frames))+ m = re.search(r"#error=(\d+)", text)+ self._n += 1+ req = FakeRequest(rid or f"r{self._n}", text, lang, voice, on_event or (lambda k, p: None), n,+ int(m.group(1)) if m else None, None if sampling is None else dict(sampling))+ with self._cv:+ self.requests.append(req)+ self._pending.append(req)+ self._cv.notify()+ return req++ def _emit(self, req, kind, payload):+ req.events.append(kind)+ try:+ req.on_event(kind, payload)+ except Exception:+ req.cancelled = True+ if kind != "audio":+ req.done.set()++ def _loop(self):+ while True:+ with self._cv:+ while not self._stop and not self._pending and not self._active:+ self._cv.wait(0.5)+ if self._stop:+ break+ # cancelled requests leave first (pending ones too, like the real engine's admission)+ for r in [r for r in self._pending if r.cancelled]:+ self._pending.remove(r)+ self._emit(r, "error", {"code": "cancelled", "error": "cancelled"})+ while self._pending and len(self._active) < self.cfg.max_seats:+ self._active.append(self._pending.popleft())+ keep = []+ for r in self._active:+ if r.cancelled:+ self._emit(r, "error", {"code": "cancelled", "error": "cancelled"})+ continue+ if r.error_at is not None and r.frames >= r.error_at:+ self._emit(r, "error", {"code": "internal", "error": "synthetic failure"})+ continue+ if r.t_first is None:+ r.t_first = time.perf_counter()+ r.frames += 1+ self._emit(r, "audio", np.full(FRAME, r.frames, np.int16))+ if r.frames >= r.n_frames:+ self._emit(r, "end", {"reason": "aeos", "frames": r.frames, "audio_s": r.frames * FRAME / SR,+ "ttfa_s": r.t_first - r.t_submit, "wall_s": time.perf_counter() - r.t_submit,+ "pieces": 1, "stops": [{"reason": "aeos", "frames": r.frames}]})+ else:+ keep.append(r)+ self._active = keep+ time.sleep(self.frame_s)+ for r in list(self._pending) + self._active:+ self._emit(r, "error", {"code": "unavailable", "error": "engine stopped"})++ def health(self):+ return {"ready": self.failed is None, "failed": self.failed, "active": len(self._active),+ "pending": len(self._pending), "max_seats": self.cfg.max_seats}++ def close(self):+ with self._cv:+ self._stop = True+ self._cv.notify()+ self._thread.join(timeout=5)+++class FakeTTS:+ """Maya3TTS surface used by the server: engine, voices, register_voice, remove_voice, close."""++ def __init__(self, engine=None, register_s=0.0, **engine_kw):+ self.engine = engine or FakeEngine(**engine_kw)+ self.register_s = register_s+ self.registered = []++ @property+ def voices(self):+ return self.engine.registry.ids()++ def register_voice(self, voice_id, ref_audio=None, ref_text=None, lang=None, mode="icl_spk", **kw):+ if mode in ("icl", "icl_spk") and (not ref_text or not lang):+ raise ValueError("ref_text and lang are required for cloning")+ if mode != "plain" and ref_audio is None:+ raise ValueError("reference audio required")+ if ref_audio is not None:+ w, sr = ref_audio+ assert isinstance(w, np.ndarray) and w.dtype == np.float32 and w.ndim == 1+ time.sleep(self.register_s)+ self.registered.append({"voice_id": voice_id, "mode": mode, "lang": lang, "ref_text": ref_text,+ "ref_sr": ref_audio[1] if ref_audio is not None else None,+ "ref_len": len(ref_audio[0]) if ref_audio is not None else 0})+ self.engine.registry.add(FakeVoice(voice_id, mode, lang if mode in ("icl", "icl_spk") else None,+ meta=kw.get("meta")))+ return voice_id++ def remove_voice(self, voice_id):+ return self.engine.registry.remove(voice_id) is not None++ def close(self):+ self.engine.close()diff --git a/maya3/tests/test_backbone_from_config.py b/maya3/tests/test_backbone_from_config.pynew file mode 100644index 0000000..90f237f--- /dev/null+++ b/maya3/tests/test_backbone_from_config.py@@ -0,0 +1,22 @@+"""GPU: engine loaded with the backbone built from config (no backbone safetensors read) == normal load: identical+state dict, identical RoPE buffers and identical prompt hidden states. Usage: test_backbone_from_config.py <model.pt>"""+import os, sys, time, torch+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))+from maya3.engine import Engine, EngineConfig+from maya3.bench import common as C+def load(flag):+ os.environ["MAYA3_BACKBONE_FROM_CONFIG"] = flag+ t = time.time(); E = Engine(sys.argv[1], C.BACKBONE, C.MIMI, EngineConfig(max_seats=2, capacity=512)); return E, time.time() - t+A, ta = load("0"); B, tb = load("1")+sa, sb = A.model.state_dict(), B.model.state_dict()+diff = [k for k in sa if not torch.equal(sa[k], sb[k])]+ra = [b for n, b in A.model.backbone.lm.named_buffers()]; rb = [b for n, b in B.model.backbone.lm.named_buffers()]+print("load_s normal / from_config:", round(ta, 1), round(tb, 1), "| state diffs:", len(diff), diff[:3], "| buffers equal:", all(torch.equal(x, y) for x, y in zip(ra, rb)))+with torch.inference_mode():+ v = A.registry.get("plain"); A.prepare_voice(v)+ ex = A.builder.example(A.packer, v, "Hello there, how are you?", "en")+ p, _ = A.S.prompt_from_example(ex, A.model, "cuda", torch.bfloat16, 32)+ ha, _ = A.model.backbone(p.to(torch.bfloat16)); hb, _ = B.model.backbone(p.to(torch.bfloat16))+ print("hidden equal:", torch.equal(ha, hb))+ assert not diff and torch.equal(ha, hb)+print("FROM_CONFIG_OK")diff --git a/maya3/tests/test_backbone_fused.py b/maya3/tests/test_backbone_fused.pynew file mode 100644index 0000000..0dcaabc--- /dev/null+++ b/maya3/tests/test_backbone_fused.py@@ -0,0 +1,47 @@+"""GPU: StaticBackbone fused paths (fuse_proj, fuse_rope) vs the reference unfused path on identical inputs.+Usage: test_backbone_fused.py <model.pt>"""+import os, sys, torch+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))+from maya3.engine import Engine, EngineConfig+from maya3.bench import common as C+from serve.fast_backbone import StaticBackbone+E = Engine(sys.argv[1], C.BACKBONE, C.MIMI, EngineConfig(max_seats=8, capacity=1024))+bb = E.model.backbone+torch.manual_seed(0)+with torch.inference_mode():+ mk = lambda **kw: StaticBackbone(bb, 8, capacity=1024, batch_buckets=(1, 2, 4, 8, 64, 384), ctx_buckets=(512, 1024), attention="triton", **kw)+ ref, fp, fr, solo = mk(), mk(fuse_proj=True), mk(fuse_rope=True), mk()+ slots = [0, 3, 5]+ pre = torch.randn(1, 200, bb.d_model, device="cuda", dtype=torch.bfloat16) * 0.05+ for S in (ref, fp, fr, solo):+ for s in slots:+ S.load_prefix(s, [(torch.zeros(1, S.kv_heads, 0, S.head_dim, device="cuda", dtype=torch.bfloat16),) * 2 for _ in S.layers], 0)+ outs = {n: [] for n in ("ref", "proj", "rope", "solo")}+ # inline prefill of 200 rows for slot 0 + 3 + 5 (different lengths), then 20 decode steps+ for n, S in (("ref", ref), ("proj", fp), ("rope", fr)):+ _, last = S.step_mixed([], None, [(0, pre[0]), (3, pre[0, :120]), (5, pre[0, :37])])+ outs[n].append(torch.stack(last))+ torch.manual_seed(1)+ for t in range(20):+ x = torch.randn(3, bb.d_model, device="cuda", dtype=torch.bfloat16) * 0.05+ outs[n].append(S.step(slots, x))+ # noise floor: the SAME unfused path, but every slot prefilled and decoded alone (different batch composition)+ last = [solo.step_mixed([], None, [(sl, t)])[1][0] for sl, t in ((0, pre[0]), (3, pre[0, :120]), (5, pre[0, :37]))]+ outs["solo"].append(torch.stack(last)); torch.manual_seed(1)+ for t in range(20):+ x = torch.randn(3, bb.d_model, device="cuda", dtype=torch.bfloat16) * 0.05+ outs["solo"].append(torch.cat([solo.step([sl], x[j:j + 1]) for j, sl in enumerate(slots)]))+ floor = None+ for n in ("solo", "proj", "rope"):+ worst = 0+ if n == "solo":+ print("solo per-step rel:", [round(((a.float() - b.float()).norm() / a.float().norm()).item(), 4) for a, b in zip(outs["ref"], outs[n])])+ print("solo per-row rel step0:", [round(((a.float() - b.float()).norm() / a.float().norm()).item(), 4) for a, b in zip(outs["ref"][0], outs[n][0])])+ for a, b in zip(outs["ref"], outs[n]):+ cos = torch.nn.functional.cosine_similarity(a.float(), b.float(), -1).min().item()+ rel = ((a.float() - b.float()).norm() / a.float().norm()).item()+ worst = max(worst, rel)+ print(f"{n}: worst rel L2 {worst:.2e}, last min cosine {cos:.6f}")+ if n == "solo": floor = worst+ else: assert worst <= max(2 * floor, 1e-3), (n, worst, floor)+print("BACKBONE_FUSED_OK")diff --git a/maya3/tests/test_depth_fused.py b/maya3/tests/test_depth_fused.pynew file mode 100644index 0000000..0599838--- /dev/null+++ b/maya3/tests/test_depth_fused.py@@ -0,0 +1,40 @@+"""GPU: FastDepth fused body vs reference body (greedy code agreement vs the fp16 noise floor = fp16 vs fp32 reference),+and the fused top-k sampler's distribution vs the exact top-k softmax. Usage: test_depth_fused.py <model.pt>"""+import os, sys, torch+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))+from maya3.engine import Engine, EngineConfig+from maya3.bench import common as C+from serve.fast_depth import FastDepth+from serve.fast_depth_kernels import topk_sample+E = Engine(sys.argv[1], C.BACKBONE, C.MIMI, EngineConfig(max_seats=4, capacity=1024, free_reference_depth=False))+torch.manual_seed(0)+with torch.inference_mode():+ # sampler distribution: 200k draws from one fixed logit row+ lg = torch.randn(1, 2048, device="cuda") * 3+ seed = torch.zeros(1, device="cuda", dtype=torch.int32)+ draws = []+ for i in range(4000):+ draws.append(topk_sample(lg.expand(50, -1).contiguous(), seed, 3, 0.7, 64)); seed += 1+ d = torch.cat(draws)+ emp = torch.bincount(d, minlength=2048).float() / d.numel()+ l = lg[0] / 0.7; kth = l.topk(64).values[-1]; p = torch.where(l >= kth, l, torch.tensor(-float("inf"), device="cuda")).softmax(-1)+ tv = 0.5 * (emp - p).abs().sum().item()+ print(f"sampler total-variation vs exact top-k softmax: {tv:.4f} (200k draws; sampling noise ~0.01)")+ assert tv < 0.03 and emp[p == 0].sum() == 0+ # greedy agreement on real hidden states from a prefill of real prompts+ v = E.registry.get("plain"); E.prepare_voice(v)+ ex = E.builder.example(E.packer, v, "नमस्ते, आज मौसम बहुत अच्छा है और हम बाहर घूमने जा रहे हैं।", "hi")+ prompt, n = E.S.prompt_from_example(ex, E.model, "cuda", torch.bfloat16, 32)+ hs, _ = E.model.backbone(prompt.to(torch.bfloat16)); h = hs[0, -16:].contiguous() # 16 real-ish states+ B = h.shape[0]; slots = list(range(B))+ mk = lambda dt, fused: FastDepth(E.model, B, dtype=dt, batch_buckets=(B,), greedy=True, fused=fused)+ ref32, ref16, fus16 = mk(torch.float32, False), mk(torch.float16, False), mk(torch.float16, True)+ for D_ in (ref32, ref16, fus16):+ for s_ in slots: D_.set_speaker(s_, v.mem, v.rmask)+ cb0 = E.model.backbone.cb0_logits(h).float()[:, :2048].argmax(-1)+ out = {k: D_._fn(torch.tensor(slots, device="cuda"), h.to(D_.dtype), cb0)[0] for k, D_ in+ (("fp32", ref32), ("fp16", ref16), ("fused", fus16))}+ agree = lambda a, b: (out[a] == out[b]).float().mean().item()+ print(f"greedy code agreement: fp16 vs fp32 {agree('fp16','fp32'):.3f} | fused vs fp32 {agree('fused','fp32'):.3f} | fused vs fp16 {agree('fused','fp16'):.3f}")+ assert agree("fused", "fp32") >= agree("fp16", "fp32") - 0.05+print("DEPTH_FUSED_OK")diff --git a/maya3/tests/test_guards.py b/maya3/tests/test_guards.pynew file mode 100644index 0000000..1d5e7be--- /dev/null+++ b/maya3/tests/test_guards.py@@ -0,0 +1,109 @@+"""CPU: vectorised loop guard == a scalar reference loop_detect (_ref_loop_detect below) on random / periodic / stalled cb0 streams."""+import os, sys+import numpy as np+import pytest+ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+sys.path.insert(0, ROOT)+from maya3 import guards as G+++def _ref_loop_detect(c0, min_frames=12, stall=32, period_win=64, period_thr=0.7, pmin=2, pmax=16):+ n = len(c0)+ if n < max(min_frames, stall):+ return None+ tail = np.asarray(c0[-stall:])+ if (tail == tail[0]).all():+ return "stall"+ if n >= period_win:+ w = np.asarray(c0[-period_win:])+ for p in range(pmin, pmax + 1):+ if (w[p:] == w[:-p]).mean() >= period_thr:+ return f"period:{p}"+ return None+++def test_loop_detect_batch_matches_reference():+ rng = np.random.default_rng(0)+ cfg = G.GuardConfig()+ Ws, ns, refs = [], [], []+ for t in range(3000):+ n = int(rng.integers(30, 200)); kind = t % 3+ if kind == 0:+ c = rng.integers(0, 50, n)+ elif kind == 1:+ p = int(rng.integers(2, 17)); base = rng.integers(0, 30, p)+ c = np.array([base[i % p] for i in range(n)]); c[rng.random(n) < rng.random() * 0.5] = rng.integers(0, 30)+ else:+ c = rng.integers(0, 3, n); c[-int(rng.integers(20, 40)):] = 7+ refs.append(_ref_loop_detect(c[-96:]))+ W = np.full(96, -1); tail = c[-96:]; W[-len(tail):] = tail+ Ws.append(W); ns.append(n)+ got = G.loop_detect_batch(np.stack(Ws), np.array(ns), cfg)+ assert got == refs+++def test_duration_prior_and_tags():+ dp = G.DurationPrior()+ assert dp.cap_frames("Hello there, how are you?", "en") > 20+ w = G.tag_windows("Hello [laughs] there", "en", dp)+ assert len(w) == 1 and w[0][0] <= w[0][1]+++if __name__ == "__main__":+ test_loop_detect_batch_matches_reference(); test_duration_prior_and_tags(); print("test_guards OK")+++# ---- loop guard v2 windows: fixtures = the actual loop_backstop cuts of an earlier checkpoint on normalised eval text+def _cuts():+ import json+ return json.load(open(os.path.join(os.path.dirname(__file__), "data_backstop_cuts.json")))+++def test_v2_windows_cover_tag_filler_speaker_cuts():+ P = G.DurationPrior()+ cuts = _cuts()+ cov = lambda c, **kw: any(a <= c["cut"] - 24 <= b for a, b in G.suspend_windows_v2(c["text"], c["lang"], P, **kw))+ for c in cuts: # v1 tag windows covered none of the real cuts (loop onset = cut - 24-frame backstop)+ assert not any(a <= c["cut"] - 24 <= b for a, b in G.tag_windows(c["text"], c["lang"], P)), c["id"]+ tag = [c for c in cuts if c["kind"] == "tag"]+ sp = [c for c in cuts if c["kind"] == "speaker"]+ fill = [c for c in cuts if c["kind"] == "filler"]+ assert len(tag) == 25 and all(cov(c, style_hold_s=None) for c in tag) # first v2 (style tags to end): all+ assert sum(cov(c) for c in tag) >= 12 # v2b default: bounded style windows+ assert all(cov(c) for c in sp) and len(sp) == 3+ assert sum(cov(c) for c in fill) >= 3+++def test_v2_keeps_guard_on_unmarked_text():+ P = G.DurationPrior()+ for c in _cuts():+ if c["kind"] == "none": # incl. kn-0147, a real loop (ASR heard 217 words for a 37-word text): must stay guarded+ assert G.suspend_windows_v2(c["text"], c["lang"], P) == (), c["id"]+++def test_v2_window_shapes():+ P = G.DurationPrior()+ w = G.suspend_windows_v2("[whispers] arre sun, maine tujhe paise bhej diye hain", "hi", P)+ assert w[0][0] == 0 and w[0][1] == int(4.0 / G.FRAME_S) # style tag at t=0: bounded window (v2b default)+ w = G.suspend_windows_v2("[whispers] arre sun, maine tujhe paise bhej diye hain", "hi", P, style_hold_s=None)+ assert w[0][1] >= 10 ** 6 # first v2: to the end of the piece+ w = G.suspend_windows_v2("I checked it, [laughs] and it is fine now.", "en", P)+ assert len(w) == 1 and w[0][1] < 10 ** 6+ w = G.suspend_windows_v2("ನಮಸ್ಕಾರ, ನಾನು ರಮೇಶ್. ಹ್ಮ್, ನಿಮ್ಮ ಕಾರ್ಡ್ ನಂಬರ್", "kn", P)+ assert len(w) == 1 # filler+ w = G.suspend_windows_v2("Rohan: are you coming? Priya: yes, I am.", "en", P)+ assert len(w) == 1 # speaker switch (the leading name is not a switch)+ assert G.GuardConfig().aware_v2 is (os.environ.get("MAYA3_GUARD_V2", "1") == "1") # default ON (v2b, validated 19:12Z)+++def test_v2_identical_to_eval_guards():+ ev = os.environ.get("MAYA3_REF_GUARDS", "")+ if not ev or not os.path.exists(ev):+ pytest.skip("eval guards not present")+ import importlib.util+ spec = importlib.util.spec_from_file_location("_eval_guards_v2", ev)+ E = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(E)+ Pm, Pe = G.DurationPrior(), E.DurationPrior()+ for c in _cuts():+ assert G.suspend_windows_v2(c["text"], c["lang"], Pm) == E.suspend_windows_v2(c["text"], c["lang"], Pe), c["id"]diff --git a/maya3/tests/test_rope_kernel.py b/maya3/tests/test_rope_kernel.pynew file mode 100644index 0000000..3a067dd--- /dev/null+++ b/maya3/tests/test_rope_kernel.py@@ -0,0 +1,27 @@+"""GPU unit test: _qk_norm_rope_cache vs HF Qwen3 q_norm/k_norm + rotate_half RoPE (one layer)."""+import os, sys, torch+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))+from serve.fast_backbone import _qk_norm_rope_cache, _rotate_half+torch.manual_seed(0)+B, H, KV, D, CAP = 5, 16, 8, 128, 512+dt = torch.bfloat16+qkv = (torch.randn(B, (H + 2 * KV) * D, device="cuda") * 2).to(dt)+wq = (1 + 0.1 * torch.randn(D, device="cuda")).to(dt); wk = (1 + 0.1 * torch.randn(D, device="cuda")).to(dt)+pos = torch.tensor([0, 7, 100, 300, 511], device="cuda"); slots = torch.tensor([0, 1, 2, 3, 4], device="cuda")+inv = 1.0 / (1e6 ** (torch.arange(0, D, 2, device="cuda").float() / D))+fr = torch.arange(CAP, device="cuda").float()[:, None] * inv[None]+emb = torch.cat([fr, fr], -1); cos, sin = emb.cos().to(dt).contiguous(), emb.sin().to(dt).contiguous()+def rms(x, w, eps=1e-6):+ xf = x.float(); return w * (xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + eps)).to(dt)+q_, k_, v_ = qkv.split([H * D, KV * D, KV * D], -1)+c, s = cos[pos][:, None], sin[pos][:, None]+q = rms(q_.view(B, H, D), wq); k = rms(k_.view(B, KV, D), wk)+qr = q * c + _rotate_half(q) * s; kr = k * c + _rotate_half(k) * s+K = torch.zeros(6, KV, CAP, D, device="cuda", dtype=dt); V = torch.zeros_like(K); qo = torch.empty(B, H, D, device="cuda", dtype=dt)+_qk_norm_rope_cache[(B, H + KV)](qkv, qo, K, V, slots, pos, cos, sin, wq, wk, 1e-6, qkv.stride(0), qo.stride(0), qo.stride(1),+ K.stride(0), K.stride(1), K.stride(2), cos.stride(0), H=H, KVH=KV, D=D)+kk = K[slots, :, pos]; vv = V[slots, :, pos]+rel = lambda a, b: ((a.float() - b.float()).norm() / b.float().norm()).item()+print("q rel", rel(qo, qr), "k rel", rel(kk, kr), "v exact", torch.equal(vv, v_.view(B, KV, D)))+assert rel(qo, qr) < 1e-2 and rel(kk, kr) < 1e-2 and torch.equal(vv, v_.view(B, KV, D))+print("ROPE_KERNEL_OK")diff --git a/maya3/tests/test_sampling.py b/maya3/tests/test_sampling.pynew file mode 100644index 0000000..d39eed5--- /dev/null+++ b/maya3/tests/test_sampling.py@@ -0,0 +1,31 @@+"""GPU: per-request sampling. Same seed alone -> identical audio; different seed -> different audio; temperature / top_k /+top_p / repetition_penalty accepted and effective; invalid values rejected. Usage: test_sampling.py <model.pt>"""+import os, sys+import numpy as np+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))+from maya3 import Maya3TTS+from maya3.bench import common as C++tts = Maya3TTS.from_pretrained(sys.argv[1], C.BACKBONE, C.MIMI, ecapa_dir=C.ECAPA, max_seats=4)+T = "The quick brown fox jumps over the lazy dog, and then it runs away."+a = tts.generate(T, "en", seed=123)+b = tts.generate(T, "en", seed=123)+c = tts.generate(T, "en", seed=124)+print("same seed identical:", len(a) == len(b) and np.array_equal(a, b), "| other seed differs:", not (len(a) == len(c) and np.array_equal(a, c)))+assert len(a) == len(b) and np.array_equal(a, b)+assert not (len(a) == len(c) and np.array_equal(a, c))+for kw in ({"temperature": 0.5}, {"top_k": 8}, {"top_p": 0.8}, {"repetition_penalty": 0.0}, {"temperature": 1.2, "seed": 7}):+ w, info = tts.generate(T, "en", return_info=True, **kw)+ print(kw, round(len(w) / 24000, 2), "s", info["stops"][-1]["reason"])+ assert len(w) > 24000+g1 = tts.generate(T, "en", seed=5, top_k=1) # top_k=1 on cb0: deterministic cb0 path+g2 = tts.generate(T, "en", seed=6, top_k=1)+print("top_k=1 different seeds same length:", len(g1) == len(g2))+for bad in ({"temperature": 0}, {"top_k": 0}, {"top_p": 1.5}, {"foo": 1}):+ try:+ tts.generate("x", "en", **bad) if "foo" not in bad else tts.engine.submit("x", "en", sampling=bad)+ raise SystemExit(f"accepted invalid {bad}")+ except (ValueError, TypeError):+ pass+print("SAMPLING_OK")+tts.close()diff --git a/maya3/tests/test_server.py b/maya3/tests/test_server.pynew file mode 100644index 0000000..6498dbc--- /dev/null+++ b/maya3/tests/test_server.py@@ -0,0 +1,875 @@+"""Server/client/bench tests against FakeEngine (CPU only, ephemeral ports).++ python -m pytest maya3/tests/test_server.py -q+"""+from __future__ import annotations++import asyncio+import base64+import io+import json+import struct+import time++import aiohttp+import numpy as np+import pytest+import soundfile as sf++from maya3 import server as S+from maya3.client import Maya3Client, Maya3Error, Maya3Stream, aspeech, parse_binary_frame+from maya3.tests.fakes import FRAME, FakeTTS, FakeVoice, named_voice++pytestmark = pytest.mark.asyncio+++def frames_of(pcm: bytes):+ a = np.frombuffer(pcm, np.int16)+ assert len(a) % FRAME == 0+ return [int(x) for x in a.reshape(-1, FRAME)[:, 0]]+++def wav_bytes(seconds=1.0, sr=16000):+ buf = io.BytesIO()+ t = np.arange(int(seconds * sr)) / sr+ sf.write(buf, (0.3 * np.sin(2 * np.pi * 220 * t)).astype(np.float32), sr, format="WAV", subtype="PCM_16")+ return buf.getvalue()+++async def wait_until(pred, timeout=3.0):+ t0 = time.perf_counter()+ while time.perf_counter() - t0 < timeout:+ if pred():+ return True+ await asyncio.sleep(0.01)+ return pred()+++def make(aiohttp_client):+ made = []++ async def _make(engine=None, **server_kw):+ # FakeEngine reads "#frames=N" directives from the text, which the normaliser would spell out: tests opt in.+ server_kw.setdefault("normalise", False)+ tts = FakeTTS(**(engine or {}))+ srv = S.Maya3Server(tts, **server_kw)+ client = await aiohttp_client(srv.app())+ made.append(tts)+ return client, srv, tts+ yield _make+ for tts in made:+ tts.close()+++async def speech(client, **body):+ body.setdefault("input", "hello world")+ return await client.post("/v1/audio/speech", json=body)+++# ------------------------------------------------------------------------------------------- health / misc+async def test_health_ready_and_loading(make, aiohttp_client):+ client, srv, tts = await make()+ r = await client.get("/health")+ assert r.status == 200+ h = await r.json()+ assert h["ready"] and h["max_seats"] == 4 and "server" in h+ loading = await aiohttp_client(S.Maya3Server(None).app())+ r = await loading.get("/health")+ assert r.status == 503 and (await r.json())["ready"] is False+ r = await speech(loading)+ assert r.status == 503 and (await r.json())["error"]["code"] == "unavailable"+ r = await client.get("/v1/models")+ assert (await r.json())["data"][0]["id"] == "maya3"+++async def test_background_loader(aiohttp_client):+ tts = FakeTTS()+ srv = S.Maya3Server(loader=lambda: (time.sleep(0.2), tts)[1])+ client = await aiohttp_client(srv.app())+ assert (await client.get("/health")).status == 503+ assert await wait_until(lambda: srv.tts is not None)+ assert (await client.get("/health")).status == 200+++# ------------------------------------------------------------------------------------------- OpenAI endpoint+async def test_speech_pcm_streams(make):+ client, srv, tts = await make(engine={"frame_s": 0.02})+ t0 = time.perf_counter()+ r = await speech(client, input="stream me #frames=30", response_format="pcm", language="en")+ assert r.status == 200+ assert r.headers["Content-Type"] == "audio/pcm" and r.headers["X-Sample-Rate"] == "24000"+ assert r.headers["X-Maya3-Language"] == "en" and r.headers["Transfer-Encoding"] == "chunked"+ first = await r.content.readexactly(2 * FRAME)+ t_first = time.perf_counter() - t0+ rest = await r.read()+ t_all = time.perf_counter() - t0+ assert frames_of(first + rest) == list(range(1, 31))+ assert t_first < t_all / 2, (t_first, t_all) # audio arrives while generating, not at the end+ req = tts.engine.requests[-1]+ assert req.lang == "en" and req.voice.id == "plain" and req.id == r.headers["X-Request-Id"]+++async def test_speech_wav_streaming_header(make):+ client, srv, tts = await make()+ r = await speech(client, input="wav #frames=7", response_format="wav", language="hi")+ assert r.status == 200 and r.headers["Content-Type"] == "audio/wav"+ body = await r.read()+ riff, size, wave, fmt, _, pcmfmt, ch, sr, _, _, bits, data, dsize = struct.unpack("<4sI4s4sIHHIIHH4sI", body[:44])+ assert (riff, wave, fmt, data) == (b"RIFF", b"WAVE", b"fmt ", b"data")+ assert size == dsize == 0xFFFFFFFF and (pcmfmt, ch, sr, bits) == (1, 1, 24000, 16)+ assert frames_of(body[44:]) == list(range(1, 8))+++async def test_speech_default_format_is_wav_and_flac(make):+ client, srv, tts = await make()+ r = await speech(client, input="x #frames=4")+ assert r.status == 200 and r.headers["Content-Type"] == "audio/wav"+ r = await speech(client, input="x #frames=5", response_format="flac")+ assert r.status == 200 and r.headers["Content-Type"] == "audio/flac"+ w, sr = sf.read(io.BytesIO(await r.read()), dtype="int16")+ assert sr == 24000 and len(w) == 5 * FRAME and int(w[-1]) == 5+++async def test_speech_sse(make):+ client, srv, tts = await make()+ r = await speech(client, input="x #frames=6", response_format="pcm", stream_format="sse")+ assert r.status == 200 and r.headers["Content-Type"].startswith("text/event-stream")+ events = [json.loads(l[6:]) for l in (await r.text()).splitlines() if l.startswith("data: ")]+ assert events[-1]["type"] == "speech.audio.done" and events[-1]["usage"]["frames"] == 6+ pcm = b"".join(base64.b64decode(e["audio"]) for e in events if e["type"] == "speech.audio.delta")+ assert frames_of(pcm) == list(range(1, 7))+++async def test_openai_voice_alias_and_language_detection(make):+ client, srv, tts = await make()+ r = await speech(client, input="नमस्ते दुनिया", voice="alloy", response_format="pcm", model="tts-1")+ assert r.status == 200 and r.headers["X-Maya3-Voice"] == "plain" and r.headers["X-Maya3-Language"] == "hi"+ await r.read()+ assert tts.engine.requests[-1].lang == "hi"+ r = await speech(client, input="வணக்கம்", response_format="pcm")+ assert r.headers["X-Maya3-Language"] == "ta"+ await r.read()++[email protected]("body,param,frag", [+ ({"input": ""}, "input", "non-empty"),+ ({"input": " "}, "input", "non-empty"),+ ({"input": 5}, "input", "non-empty"),+ ({"input": "x" * 4001}, "input", "4000"),+ ({"input": "hi", "language": "fr"}, "language", "unsupported language"),+ ({"input": "hi", "voice": "nobody"}, "voice", "unknown voice"),+ ({"input": "hi", "response_format": "aac"}, "response_format", "not supported"),+ ({"input": "hi", "response_format": "ogg"}, "response_format", "wav, pcm, mp3, opus, flac"),+ ({"input": "hi", "response_format": 3}, "response_format", "use one of"),+ ({"input": "hi", "speed": 1.5}, "speed", "1.0"),+ ({"input": "hi", "max_frames": 0}, "max_frames", "max_frames"),+ ({"input": "hi", "stream_format": "sse", "response_format": "flac"}, "stream_format", "sse"),+])+async def test_speech_validation(make, body, param, frag):+ client, srv, tts = await make()+ r = await client.post("/v1/audio/speech", json=body)+ assert r.status == 400+ err = (await r.json())["error"]+ assert err["param"] == param and frag in err["message"] and err["type"] == "invalid_request_error"+ assert not tts.engine.requests+++async def test_speech_bad_json(make):+ client, srv, tts = await make()+ r = await client.post("/v1/audio/speech", data=b"{nope", headers={"Content-Type": "application/json"})+ assert r.status == 400 and "JSON" in (await r.json())["error"]["message"]+ r = await client.post("/v1/audio/speech", json=[1, 2])+ assert r.status == 400+++async def test_speech_speed_one_accepted(make):+ client, srv, tts = await make()+ r = await speech(client, input="x #frames=3", speed=1, response_format="pcm")+ assert r.status == 200 and len(await r.read()) == 3 * FRAME * 2+++async def test_midstream_error_aborts_body(make):+ client, srv, tts = await make()+ r = await speech(client, input="boom #frames=50 #error=3", response_format="pcm")+ assert r.status == 200+ with pytest.raises(aiohttp.ClientPayloadError):+ await r.read()+++# ------------------------------------------------------------------------------------------- admission+async def test_overload_max_pending_503(make):+ client, srv, tts = await make(engine={"max_seats": 1, "frame_s": 0.02}, max_pending=1, queue_deadline_ms=5000)+ r1 = await speech(client, input="long #frames=500", response_format="pcm")+ assert r1.status == 200 # holds the only seat+ t2 = asyncio.create_task(speech(client, input="second", response_format="pcm"))+ assert await wait_until(lambda: len(srv._waiting) == 1)+ r3 = await speech(client, input="third", response_format="pcm")+ assert r3.status == 503 and r3.headers.get("Retry-After") == "1"+ assert (await r3.json())["error"]["code"] == "overloaded"+ assert len(tts.engine.requests) == 2 # the rejected one never reached the engine+ r1.close()+ r2 = await t2+ assert r2.status == 200+ await r2.read()+++async def test_overload_queue_deadline_503_and_cancel(make):+ client, srv, tts = await make(engine={"max_seats": 1, "frame_s": 0.02}, max_pending=8, queue_deadline_ms=200)+ r1 = await speech(client, input="long #frames=500", response_format="pcm")+ assert r1.status == 200+ t0 = time.perf_counter()+ r2 = await speech(client, input="waits", response_format="wav")+ waited = time.perf_counter() - t0+ assert r2.status == 503 and (await r2.json())["error"]["code"] == "overloaded"+ assert 0.15 < waited < 1.5+ assert await wait_until(lambda: tts.engine.requests[1].cancelled)+ assert srv.stats["rejected_deadline"] == 1 and not srv._waiting+ r1.close()+++async def test_http_disconnect_cancels_engine_request(make):+ client, srv, tts = await make(engine={"frame_s": 0.01})+ r = await speech(client, input="forever #frames=100000", response_format="pcm")+ await r.content.readexactly(2 * FRAME)+ req = tts.engine.requests[-1]+ r.close()+ assert await wait_until(lambda: req.cancelled and req.done.is_set())+ assert await wait_until(lambda: not srv._jobs)+++async def test_http_disconnect_while_queued_cancels(make):+ client, srv, tts = await make(engine={"max_seats": 1, "frame_s": 0.02}, queue_deadline_ms=10000)+ r1 = await speech(client, input="long #frames=500", response_format="pcm")+ task = asyncio.create_task(speech(client, input="queued", response_format="pcm"))+ assert await wait_until(lambda: len(tts.engine.requests) == 2)+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)+ assert await wait_until(lambda: tts.engine.requests[1].cancelled)+ r1.close()+++async def test_engine_failure_is_503(make):+ client, srv, tts = await make()+ tts.engine.failed = "boom"+ r = await speech(client)+ assert r.status == 503+ assert (await client.get("/health")).status == 503+++# ------------------------------------------------------------------------------------------- WebSocket+async def ws_open(client):+ ws = await client.ws_connect("/v1/tts/stream")+ meta = await ws.receive_json()+ assert meta == {"type": "metadata", "sample_rate": 24000, "encoding": "pcm_s16le", "channels": 1,+ "max_contexts": meta["max_contexts"], "languages": list(S.LANGS)}+ return ws+++async def ws_collect(ws, until, timeout=10):+ """Read until `until(contexts)` is true; returns {cid: {"pcm": bytes, "msgs": [...]}}."""+ ctx = {}+ async with asyncio.timeout(timeout):+ while not until(ctx):+ m = await ws.receive()+ if m.type == aiohttp.WSMsgType.BINARY:+ cid, pcm = parse_binary_frame(m.data)+ c = ctx.setdefault(cid, {"pcm": b"", "msgs": []})+ c["pcm"] += pcm+ c["msgs"].append({"type": "audio", "binary": True})+ continue+ assert m.type == aiohttp.WSMsgType.TEXT, m+ f = json.loads(m.data)+ c = ctx.setdefault(f.get("context_id"), {"pcm": b"", "msgs": []})+ if f["type"] == "audio":+ c["pcm"] += base64.b64decode(f["audio"])+ c["msgs"].append(f)+ return ctx+++def terminal(c):+ return bool(c["msgs"]) and c["msgs"][-1]["type"] in ("end", "error")+++async def test_ws_multi_context(make):+ client, srv, tts = await make(engine={"frame_s": 0.005})+ ws = await ws_open(client)+ await ws.send_json({"type": "speak", "context_id": "a", "text": "one #frames=20", "language": "en"})+ await ws.send_json({"type": "speak", "context_id": "b", "text": "दो #frames=11", "language": "hi", "binary": True})+ await ws.send_json({"type": "speak", "context_id": "c", "text": "three #frames=5", "lang": "te", "max_frames": 3})+ ctx = await ws_collect(ws, lambda c: all(k in c and terminal(c[k]) for k in "abc"))+ for cid, n in (("a", 20), ("b", 11), ("c", 3)):+ end = ctx[cid]["msgs"][-1]+ assert end["type"] == "end" and end["reason"] == "aeos" and end["frames"] == n+ assert end["ttfa_ms"] is not None and abs(end["audio_s"] - n * 0.08) < 1e-6+ assert frames_of(ctx[cid]["pcm"]) == list(range(1, n + 1))+ assert all(m["type"] == "audio" for m in ctx[cid]["msgs"][:-1])+ assert all(m.get("binary") for m in ctx["b"]["msgs"][:-1])+ langs = {r.text.split()[0]: r.lang for r in tts.engine.requests}+ assert langs == {"one": "en", "दो": "hi", "three": "te"}+ # a finished context id may be reused+ await ws.send_json({"type": "speak", "context_id": "a", "text": "again #frames=2"})+ ctx = await ws_collect(ws, lambda c: "a" in c and terminal(c["a"]))+ assert ctx["a"]["msgs"][-1]["frames"] == 2+ await ws.close()+++async def test_ws_cancel(make):+ client, srv, tts = await make(engine={"frame_s": 0.01})+ ws = await ws_open(client)+ await ws.send_json({"type": "speak", "context_id": "long", "text": "x #frames=100000"})+ await ws.send_json({"type": "speak", "context_id": "short", "text": "y #frames=30"})+ await ws_collect(ws, lambda c: "long" in c and c["long"]["pcm"])+ await ws.send_json({"type": "cancel", "context_id": "long"})+ await ws.send_json({"type": "cancel", "context_id": "never-existed"}) # ignored+ ctx = await ws_collect(ws, lambda c: all(k in c and terminal(c[k]) for k in ("long", "short")))+ end = ctx["long"]["msgs"][-1]+ assert end["type"] == "end" and end["reason"] == "cancelled"+ assert ctx["short"]["msgs"][-1]["reason"] == "aeos" and len(frames_of(ctx["short"]["pcm"])) <= 30+ long_req = next(r for r in tts.engine.requests if "100000" in r.text)+ assert await wait_until(lambda: long_req.cancelled and long_req.done.is_set())+ # nothing for 'long' after its end+ await ws.send_json({"type": "ping"})+ ctx = await ws_collect(ws, lambda c: None in c and any(m["type"] == "pong" for m in c[None]["msgs"]))+ assert "long" not in ctx+ assert srv.stats["cancelled"] == 1+ await ws.close()+++async def test_ws_errors(make):+ client, srv, tts = await make(ws_max_contexts=2, engine={"frame_s": 0.02})+ ws = await ws_open(client)++ async def err(msg, cid=None):+ await (ws.send_str(msg) if isinstance(msg, str) else ws.send_json(msg))+ ctx = await ws_collect(ws, lambda c: cid in c and terminal(c[cid]))+ e = ctx[cid]["msgs"][-1]+ assert e["type"] == "error", e+ return e+ assert (await err("not json"))["code"] == "invalid_request"+ assert "context_id" in (await err({"type": "speak", "text": "hi"}))["error"]+ assert "non-empty" in (await err({"type": "speak", "context_id": "e1", "text": ""}, "e1"))["error"]+ assert "4000" in (await err({"type": "speak", "context_id": "e2", "text": "x" * 4001}, "e2"))["error"]+ assert "language" in (await err({"type": "speak", "context_id": "e3", "text": "hi", "language": "xx"}, "e3"))["error"]+ assert "unknown voice" in (await err({"type": "speak", "context_id": "e4", "text": "hi", "voice": "zz"}, "e4"))["error"]+ assert "unknown message type" in (await err({"type": "nope", "context_id": "e5"}, "e5"))["error"]+ await ws.send_bytes(b"\x00\x01")+ ctx = await ws_collect(ws, lambda c: None in c and terminal(c[None]))+ assert ctx[None]["msgs"][-1]["code"] == "invalid_request"+ assert not tts.engine.requests+ # duplicate active context and the per-socket context limit+ await ws.send_json({"type": "speak", "context_id": "k1", "text": "a #frames=1000"})+ await ws.send_json({"type": "speak", "context_id": "k1", "text": "b"})+ ctx = await ws_collect(ws, lambda c: "k1" in c and any(m["type"] == "error" for m in c["k1"]["msgs"]))+ assert "still active" in [m for m in ctx["k1"]["msgs"] if m["type"] == "error"][0]["error"]+ await ws.send_json({"type": "speak", "context_id": "k2", "text": "a #frames=1000"})+ e = await err({"type": "speak", "context_id": "k3", "text": "c"}, "k3")+ assert e["code"] == "too_many_contexts"+ await ws.close()+++async def test_ws_overloaded(make):+ client, srv, tts = await make(engine={"max_seats": 1, "frame_s": 0.02}, queue_deadline_ms=150)+ ws = await ws_open(client)+ await ws.send_json({"type": "speak", "context_id": "hog", "text": "x #frames=100000"})+ await ws_collect(ws, lambda c: "hog" in c and c["hog"]["pcm"])+ await ws.send_json({"type": "speak", "context_id": "late", "text": "y"})+ ctx = await ws_collect(ws, lambda c: "late" in c and terminal(c["late"]))+ assert ctx["late"]["msgs"] == [ctx["late"]["msgs"][-1]] and ctx["late"]["msgs"][-1]["code"] == "overloaded"+ assert await wait_until(lambda: tts.engine.requests[1].cancelled)+ # max_pending path+ srv.max_pending = 0+ await ws.send_json({"type": "speak", "context_id": "late2", "text": "y"})+ ctx = await ws_collect(ws, lambda c: "late2" in c and terminal(c["late2"]))+ assert ctx["late2"]["msgs"][-1]["code"] == "overloaded" and len(tts.engine.requests) == 2+ await ws.close()+++async def test_ws_disconnect_cancels(make):+ client, srv, tts = await make(engine={"frame_s": 0.01})+ ws = await ws_open(client)+ await ws.send_json({"type": "speak", "context_id": "a", "text": "x #frames=100000"})+ await ws.send_json({"type": "speak", "context_id": "b", "text": "y #frames=100000"})+ await ws_collect(ws, lambda c: all(k in c and c[k]["pcm"] for k in "ab"))+ await ws.close()+ assert await wait_until(lambda: all(r.cancelled and r.done.is_set() for r in tts.engine.requests))+ assert await wait_until(lambda: not srv._jobs and srv.sockets == 0)+++async def test_ws_slow_consumer_cancelled(make):+ # Engine much faster than the client reads: with binary frames the socket buffers fill, the bounded send queue+ # fills, generated audio piles up past ws_max_lag_s and the request is cancelled.+ client, srv, tts = await make(engine={"frame_s": 0.0005}, ws_max_lag_s=2.0, ws_send_queue=4, coalesce_ms=80)+ ws = await client.ws_connect("/v1/tts/stream", max_msg_size=0)+ await ws.receive_json()+ await ws.send_json({"type": "speak", "context_id": "s", "text": "x #frames=200000", "binary": True})+ assert await wait_until(lambda: tts.engine.requests and tts.engine.requests[0].cancelled, timeout=20)+ ctx = await ws_collect(ws, lambda c: "s" in c and terminal(c["s"]), timeout=30)+ assert ctx["s"]["msgs"][-1]["code"] == "slow_consumer"+ assert srv.stats["slow_consumer"] == 1+ await ws.close()+++# ------------------------------------------------------------------------------------------- voices+async def test_voice_registration_json(make):+ client, srv, tts = await make()+ body = {"voice_id": "asha", "ref_audio_b64": base64.b64encode(wav_bytes(1.5, 16000)).decode(),+ "ref_text": "a reference", "lang": "hi", "mode": "icl_spk"}+ r = await client.post("/v1/voices", json=body)+ assert r.status == 201, await r.text()+ out = await r.json()+ assert out["id"] == "asha" and out["mode"] == "icl_spk" and out["ref_lang"] == "hi"+ reg = tts.registered[-1]+ assert reg["ref_sr"] == 16000 and reg["ref_len"] == 24000 and reg["ref_text"] == "a reference"+ voices = {v["id"]: v for v in (await (await client.get("/v1/voices")).json())["voices"]}+ assert set(voices) == {"plain", "asha"}+ # use it+ r = await speech(client, input="x #frames=3", voice="asha", response_format="pcm")+ assert r.status == 200 and r.headers["X-Maya3-Voice"] == "asha"+ await r.read()+ assert tts.engine.requests[-1].voice.id == "asha"+ ws = await ws_open(client)+ await ws.send_json({"type": "speak", "context_id": "v", "text": "y #frames=2", "voice": "asha"})+ ctx = await ws_collect(ws, lambda c: "v" in c and terminal(c["v"]))+ assert ctx["v"]["msgs"][-1]["type"] == "end" and tts.engine.requests[-1].voice.id == "asha"+ await ws.close()+ # exists -> 409 unless replace+ assert (await client.post("/v1/voices", json=body)).status == 409+ assert (await client.post("/v1/voices", json={**body, "replace": True})).status == 201+ # an OpenAI name can be registered and then wins over the alias+ assert (await client.post("/v1/voices", json={**body, "voice_id": "alloy"})).status == 201+ r = await speech(client, input="z #frames=2", voice="alloy", response_format="pcm")+ assert r.headers["X-Maya3-Voice"] == "alloy"+ await r.read()+ # delete+ assert (await client.delete("/v1/voices/asha")).status == 200+ assert (await client.delete("/v1/voices/asha")).status == 404+ assert (await client.delete("/v1/voices/plain")).status == 400+ r = await speech(client, input="x", voice="asha")+ assert r.status == 400 and "unknown voice" in (await r.json())["error"]["message"]+++async def test_voice_registration_multipart(make):+ client, srv, tts = await make()+ form = aiohttp.FormData()+ form.add_field("voice_id", "ravi")+ form.add_field("ref_text", "namaskara")+ form.add_field("lang", "kn")+ form.add_field("ref_audio", wav_bytes(2.0, 24000), filename="ravi.wav", content_type="audio/wav")+ r = await client.post("/v1/voices", data=form)+ assert r.status == 201, await r.text()+ assert tts.registered[-1]["lang"] == "kn" and tts.registered[-1]["ref_len"] == 48000++[email protected]("patch,frag", [+ ({"voice_id": "bad id!"}, "voice_id"),+ ({"voice_id": "plain"}, "built in"),+ ({"ref_text": None}, "ref_text"),+ ({"lang": "xx"}, "unsupported lang"),+ ({"mode": "weird"}, "unknown mode"),+ ({"ref_audio_b64": "@@@"}, "base64"),+ ({"ref_audio_b64": base64.b64encode(b"not audio").decode()}, "decode"),+ ({"ref_audio_b64": base64.b64encode(wav_bytes(0.2)).decode()}, "at least"),+ ({"ref_audio_b64": base64.b64encode(wav_bytes(31.0, 8000)).decode()}, "30 s"),+ ({"ref_audio_b64": None}, "reference audio"),+])+async def test_voice_registration_errors(make, patch, frag):+ client, srv, tts = await make()+ body = {"voice_id": "v1", "ref_audio_b64": base64.b64encode(wav_bytes()).decode(), "ref_text": "t", "lang": "en"}+ body.update(patch)+ r = await client.post("/v1/voices", json=body)+ assert r.status == 400, await r.text()+ assert frag in (await r.json())["error"]["message"]+ assert not tts.registered+++async def test_register_does_not_block_streaming(make):+ client, srv, tts = await make(engine={"frame_s": 0.005})+ tts.register_s = 0.5+ body = {"voice_id": "slow", "ref_audio_b64": base64.b64encode(wav_bytes()).decode(), "ref_text": "t", "lang": "en"}+ reg = asyncio.create_task(client.post("/v1/voices", json=body))+ await asyncio.sleep(0.05)+ t0 = time.perf_counter()+ r = await speech(client, input="x #frames=5", response_format="pcm")+ await r.read()+ assert time.perf_counter() - t0 < 0.4+ assert (await reg).status == 201+++# ------------------------------------------------------------------------------------------- client + bench+async def test_clients(make, tmp_path):+ client, srv, tts = await make()+ base = str(client.make_url("")).rstrip("/")+ ws_url = base.replace("http://", "ws://") + "/v1/tts/stream"+ # async HTTP+ await aspeech("x #frames=4", tmp_path / "a.wav", base_url=base, language="en")+ raw = (tmp_path / "a.wav").read_bytes()+ assert raw[:4] == b"RIFF" and frames_of(raw[44:]) == [1, 2, 3, 4]+ # async WS, two concurrent contexts, base64 and binary+ for binary in (False, True):+ async with Maya3Stream(ws_url, binary=binary) as s:+ async def one(text):+ return b"".join([p async for p in s.speak(text, language="en")])+ a, b = await asyncio.gather(one("a #frames=6"), one("b #frames=9"))+ assert frames_of(a) == list(range(1, 7)) and frames_of(b) == list(range(1, 10))+ assert len(s.last_end) == 2+ with pytest.raises(Maya3Error) as ei:+ async for _ in s.speak("x", language="fr"):+ pass+ assert ei.value.code == "invalid_request"+ # breaking early cancels on the server+ async for _ in s.speak("long #frames=100000"):+ break+ req = tts.engine.requests[-1]+ assert await wait_until(lambda: req.cancelled)+ # sync client (urllib) in a thread+ c = Maya3Client(base)++ def sync_part():+ pcm = c.speech("x #frames=3", response_format="pcm", language="en")+ assert frames_of(pcm) == [1, 2, 3]+ c.speech("y #frames=2", str(tmp_path / "b.flac"))+ chunks = list(c.iter_speech("z #frames=5"))+ assert frames_of(b"".join(chunks)) == [1, 2, 3, 4, 5]+ c.register_voice("cv", wav_bytes(), ref_text="t", lang="en")+ assert "cv" in [v["id"] for v in c.voices()]+ c.remove_voice("cv")+ try:+ c.speech("x", language="fr")+ except Maya3Error as e:+ assert e.status == 400 and e.code == "invalid_request"+ else:+ raise AssertionError("expected 400")+ return c.health()+ h = await asyncio.to_thread(sync_part)+ assert h["ready"]+ # formats from the file suffix, sampling / normalize as extra fields (HTTP and WS)+ await aspeech("x #frames=5", tmp_path / "c.ogg", base_url=base, seed=3)+ assert tts.engine.requests[-1].sampling == {"seed": 3}+ assert abs(sf.info(str(tmp_path / "c.ogg")).duration - 0.4) < 0.01+ await asyncio.to_thread(c.speech, "x #frames=5", str(tmp_path / "c.mp3"), top_k=5, normalize=False)+ assert tts.engine.requests[-1].sampling == {"top_k": 5}+ assert (tmp_path / "c.mp3").read_bytes()[:1] == b"\xff"+ async with Maya3Stream(ws_url) as s:+ pcm = b"".join([p async for p in s.speak("w #frames=3", temperature=0.5, normalize=False)])+ assert frames_of(pcm) == [1, 2, 3] and tts.engine.requests[-1].sampling == {"temperature": 0.5}+ w, sr = sf.read(str(tmp_path / "b.flac"), dtype="int16")+ assert sr == 24000 and len(w) == 2 * FRAME+++async def test_load_ws_bench_smoke(make, tmp_path):+ from maya3.bench import load_ws+ client, srv, tts = await make(engine={"frame_s": 0.01, "max_seats": 8})+ texts = tmp_path / "t.jsonl"+ texts.write_text("\n".join(json.dumps({"id": f"r{i}", "lang": l, "pieces": [f"text {i} #frames={5 + i}"]})+ for i, l in enumerate(["en", "hi", "te", "en"])) + "\n")+ url = str(client.make_url("/v1/tts/stream")).replace("http://", "ws://")+ for binary in ([], ["--binary"]):+ args = load_ws.build_parser().parse_args(["--url", url, "--texts", str(texts), "--lanes", "3",+ "--duration", "1.0", "--per-request"] + binary)+ s = await load_ws.run(args)+ assert s["completed"] >= 6 and s["errors"] == {}, s["errors"]+ assert s["ttfa_ms"]["p50"] is not None and s["rtf"]["p90"] is not None and s["audio_s_per_s"] > 0+ assert s["stalls"] == 0 # the fake engine runs ~8x faster than real time+ assert set(s["by_lang"]) <= {"en", "hi", "te"} and s["health_before"]["ready"]+ assert all(r["frames"] == round(r["audio_s"] / 0.08) for r in s["per_request"] if r["status"] == "ok")+++async def test_playback_stall_accounting():+ from maya3.bench.load_ws import Playback+ pb = Playback(sent=0.0)+ b80 = 2 * FRAME+ pb.add(0.10, b80) # playback 0.10..0.18+ pb.add(0.15, b80) # buffered, 0.18..0.26+ pb.add(0.30, b80) # dry at 0.26: gap 40 ms, no stall+ assert pb.stalls == 0+ pb.add(0.60, b80) # dry at 0.38: gap 220 ms -> stall+ assert pb.stalls == 1 and abs(pb.stall_s - 0.22) < 1e-9 and abs(pb.audio_s - 0.32) < 1e-9+ pre = Playback(sent=0.0, prebuffer_s=0.3)+ pre.add(0.1, b80)+ pre.add(0.5, b80) # playback starts 0.4, dry at 0.48 -> 20 ms gap+ assert pre.stalls == 0+++async def test_wav_header_and_lang_detection():+ h = S.wav_header(100)+ assert len(h) == 44 and struct.unpack_from("<I", h, 4)[0] == 136 and struct.unpack_from("<I", h, 40)[0] == 100+ assert S.detect_lang("ನಮಸ್ಕಾರ") == "kn" and S.detect_lang("123 ...") == "en"+ assert S.detect_lang("সুপ্ৰভাত") == "bn" and S.detect_lang("ਸਤ ਸ੍ਰੀ") == "pa" and S.detect_lang("હેલો") == "gu"+++# ------------------------------------------------------------------------------------------- output formats+def decoded_s(data):+ w, sr = sf.read(io.BytesIO(data), dtype="int16")+ assert sr == 24000+ return len(w) / sr++[email protected]("fmt,ctype,tol", [("mp3", "audio/mpeg", 0.1), ("opus", "audio/ogg; codecs=opus", 0.01)])+async def test_speech_mp3_opus_streamed(make, fmt, ctype, tol):+ assert S.codec_support()[fmt] is None, S.codec_support()+ client, srv, tts = await make(engine={"frame_s": 0.02})+ t0 = time.perf_counter()+ r = await speech(client, input="x #frames=40", response_format=fmt) # 3.2 s+ assert r.status == 200 and r.headers["Content-Type"] == ctype and r.headers["Transfer-Encoding"] == "chunked"+ assert r.headers["X-Encoding"] == fmt+ chunks, t_chunks = [], []+ async for b in r.content.iter_any():+ chunks.append(b)+ t_chunks.append(time.perf_counter() - t0)+ t_all = time.perf_counter() - t0+ data = b"".join(chunks)+ assert abs(decoded_s(data) - 40 * 0.08) <= tol, decoded_s(data)+ # encoded audio leaves while the utterance is still being generated (fake engine: 40 frames x 20 ms = 0.8 s)+ n_early = sum(1 for t in t_chunks if t < t_all * 0.75)+ assert n_early >= 2, (t_chunks, t_all)+ if fmt == "mp3":+ assert data[:2] == b"\xff\xf3" or data[:2] == b"\xff\xf2" # bare MPEG-2 layer III frames+ else:+ assert data[:4] == b"OggS" and b"OpusHead" in data[:64]++[email protected]("frames", [1, 6, 75])[email protected]("fmt", ["mp3", "opus", "flac", "wav"])+async def test_formats_duration(make, fmt, frames):+ client, srv, tts = await make(engine={"frame_s": 0.001})+ r = await speech(client, input=f"x #frames={frames}", response_format=fmt)+ assert r.status == 200+ data = await r.read()+ want = frames * 0.08+ if fmt == "wav": # streamed header has unknown sizes; check the PCM payload+ assert len(data) - 44 == frames * FRAME * 2+ else:+ assert abs(decoded_s(data) - want) <= (0.1 if fmt == "mp3" else 0.001), (fmt, decoded_s(data), want)+++async def test_sse_mp3(make):+ client, srv, tts = await make()+ r = await speech(client, input="x #frames=20", response_format="mp3", stream_format="sse")+ assert r.status == 200+ events = [json.loads(l[6:]) for l in (await r.text()).splitlines() if l.startswith("data: ")]+ assert events[-1]["type"] == "speech.audio.done"+ data = b"".join(base64.b64decode(e["audio"]) for e in events if e["type"] == "speech.audio.delta")+ assert abs(decoded_s(data) - 1.6) <= 0.1+++async def test_unavailable_codec_is_400(make, monkeypatch):+ client, srv, tts = await make()+ monkeypatch.setattr(S, "_CODECS", {"mp3": "no MP3 here", "opus": None, "flac": None})+ r = await speech(client, input="x", response_format="mp3")+ assert r.status == 400 and "no MP3 here" in (await r.json())["error"]["message"]+ assert not tts.engine.requests+++async def test_mp3_midstream_error_aborts(make):+ client, srv, tts = await make()+ r = await speech(client, input="boom #frames=50 #error=12", response_format="mp3")+ assert r.status == 200+ with pytest.raises(aiohttp.ClientPayloadError):+ await r.read()+++async def test_mp3_client_disconnect_cancels(make):+ client, srv, tts = await make(engine={"frame_s": 0.01})+ r = await speech(client, input="forever #frames=100000", response_format="opus")+ await r.content.readany()+ req = tts.engine.requests[-1]+ r.close()+ assert await wait_until(lambda: req.cancelled and req.done.is_set())+ assert await wait_until(lambda: not srv._jobs)+++# ------------------------------------------------------------------------------------------- sampling+SAMPLING = {"seed": 1234, "temperature": 0.7, "top_k": 50, "top_p": 0.9}+++async def test_sampling_pass_through_http(make):+ client, srv, tts = await make()+ r = await speech(client, input="x #frames=2", response_format="pcm", **SAMPLING)+ assert r.status == 200+ await r.read()+ assert tts.engine.requests[-1].sampling == SAMPLING+ r = await speech(client, input="x #frames=2", response_format="pcm", seed=0, temperature=1)+ await r.read()+ got = tts.engine.requests[-1].sampling+ assert got == {"seed": 0, "temperature": 1.0} and isinstance(got["temperature"], float)+ r = await speech(client, input="x #frames=2", response_format="pcm", top_p=None) # null = absent+ await r.read()+ assert tts.engine.requests[-1].sampling is None # nothing given -> no sampling kwarg+++async def test_sampling_pass_through_ws(make):+ client, srv, tts = await make()+ ws = await ws_open(client)+ await ws.send_json({"type": "speak", "context_id": "s", "text": "y #frames=2", **SAMPLING})+ await ws.send_json({"type": "speak", "context_id": "t", "text": "z #frames=2", "top_k": 1})+ ctx = await ws_collect(ws, lambda c: all(k in c and terminal(c[k]) for k in "st"))+ assert ctx["s"]["msgs"][-1]["type"] == "end"+ by_text = {r.text.split()[0]: r.sampling for r in tts.engine.requests}+ assert by_text == {"y": SAMPLING, "z": {"top_k": 1}}+ await ws.send_json({"type": "speak", "context_id": "bad", "text": "z", "temperature": 3})+ ctx = await ws_collect(ws, lambda c: "bad" in c and terminal(c["bad"]))+ e = ctx["bad"]["msgs"][-1]+ assert e["type"] == "error" and e["code"] == "invalid_request" and "temperature" in e["error"]+ assert len(tts.engine.requests) == 2+ await ws.close()++[email protected]("patch,param", [+ ({"seed": -1}, "seed"), ({"seed": "7"}, "seed"), ({"seed": True}, "seed"), ({"seed": 1.5}, "seed"),+ ({"seed": 2 ** 63}, "seed"),+ ({"temperature": 0.05}, "temperature"), ({"temperature": 1.6}, "temperature"), ({"temperature": "hot"}, "temperature"),+ ({"temperature": False}, "temperature"),+ ({"top_k": 0}, "top_k"), ({"top_k": 2049}, "top_k"), ({"top_k": 5.0}, "top_k"),+ ({"top_p": 0}, "top_p"), ({"top_p": 1.01}, "top_p"), ({"top_p": -0.5}, "top_p"),+ ({"repetition_penalty": 6}, "repetition_penalty"),+ ({"normalize": "no"}, "normalize"),+])+async def test_sampling_validation(make, patch, param):+ client, srv, tts = await make()+ r = await speech(client, **patch)+ assert r.status == 400+ err = (await r.json())["error"]+ assert err["param"] == param and param in err["message"]+ assert not tts.engine.requests+++async def test_sampling_nan_rejected(make):+ client, srv, tts = await make()+ r = await client.post("/v1/audio/speech", data=b'{"input": "hi", "top_p": NaN}',+ headers={"Content-Type": "application/json"})+ assert r.status == 400 and (await r.json())["error"]["param"] == "top_p"+++async def test_sampling_bounds_accepted(make):+ client, srv, tts = await make()+ for sp in ({"temperature": 0.1, "top_k": 1, "top_p": 1}, {"temperature": 1.5, "top_k": 2048, "top_p": 1e-6},+ {"seed": 2 ** 63 - 1}):+ r = await speech(client, input="x #frames=1", response_format="pcm", **sp)+ assert r.status == 200, await r.text()+ await r.read()+ assert tts.engine.requests[-1].sampling == {k: (float(v) if k in ("temperature", "top_p") else v)+ for k, v in sp.items()}+++# ------------------------------------------------------------------------------------------- normaliser+async def test_normaliser_default_on_http(make):+ assert S.Maya3Server(None).normalise is True # on by default+ client, srv, tts = await make(normalise=True)+ r = await speech(client, input="I have 25 apples [laughs]", language="en", response_format="pcm")+ assert r.status == 200 and r.headers["X-Maya3-Normalized"] == "1"+ await r.read()+ assert tts.engine.requests[-1].text == "I have twenty five apples [laughs]"+ r = await speech(client, input="Your OTP is 482913.", language="en", response_format="pcm")+ await r.read()+ assert tts.engine.requests[-1].text == "Your OTP is four, eight, two, nine, one, three."+ r = await speech(client, input="मेरे पास 25 रुपये हैं", response_format="pcm") # language detected from raw+ assert r.headers["X-Maya3-Language"] == "hi"+ await r.read()+ assert tts.engine.requests[-1].text == "मेरे पास पच्चीस रुपये हैं"+ r = await speech(client, input="నా దగ్గర 25 రూపాయలు ఉన్నాయి", language="te", response_format="pcm")+ await r.read()+ assert tts.engine.requests[-1].text == "నా దగ్గర ఇరవై ఐదు రూపాయలు ఉన్నాయి"+ r = await speech(client, input="Visit https://www.example.com/abc today", language="en", response_format="pcm")+ await r.read()+ assert tts.engine.requests[-1].text == "Visit W W W dot example dot com slash abc today"+ # per request off+ r = await speech(client, input="I have 25 apples", language="en", response_format="pcm", normalize=False)+ assert r.headers["X-Maya3-Normalized"] == "0"+ await r.read()+ assert tts.engine.requests[-1].text == "I have 25 apples"+ assert srv.stats["normalised"] == 5+ h = await (await client.get("/health")).json()+ assert h["server"]["normalise"] is True and {"wav", "pcm", "mp3", "opus", "flac"} <= set(h["server"]["formats"])+++async def test_normaliser_long_input_off_loop(make):+ client, srv, tts = await make(normalise=True)+ text = "Pay 25 rupees now. " * 30 # > NORMALISE_INLINE_CHARS: normalised on a worker thread+ r = await speech(client, input=text, language="en", response_format="pcm", max_frames=3)+ assert r.status == 200+ await r.read()+ assert tts.engine.requests[-1].text == ("Pay twenty five rupees now. " * 30).strip()+++async def test_normaliser_globally_off(make):+ client, srv, tts = await make(normalise=False)+ r = await speech(client, input="I have 25 apples", language="en", response_format="pcm", normalize=True)+ assert r.headers["X-Maya3-Normalized"] == "0"+ await r.read()+ assert tts.engine.requests[-1].text == "I have 25 apples"+++async def test_normaliser_ws(make):+ client, srv, tts = await make(normalise=True)+ ws = await ws_open(client)+ long = "Pay 25 rupees now. " * 30+ await ws.send_json({"type": "speak", "context_id": "a", "text": "I have 3 cats [laughs]", "language": "en"})+ await ws.send_json({"type": "speak", "context_id": "b", "text": "I have 3 cats", "normalize": False})+ await ws.send_json({"type": "speak", "context_id": "c", "text": long, "language": "en", "max_frames": 2})+ ctx = await ws_collect(ws, lambda c: all(k in c and terminal(c[k]) for k in "abc"))+ assert all(ctx[k]["msgs"][-1]["type"] == "end" for k in "abc")+ texts = sorted(r.text for r in tts.engine.requests)+ assert texts == sorted(["I have three cats [laughs]", "I have 3 cats", ("Pay twenty five rupees now. " * 30).strip()])+ # cancelling a long context while it is being normalised still ends it exactly once+ await ws.send_json({"type": "speak", "context_id": "d", "text": long, "language": "en"})+ await ws.send_json({"type": "cancel", "context_id": "d"})+ ctx = await ws_collect(ws, lambda c: "d" in c and terminal(c["d"]))+ assert ctx["d"]["msgs"][-1]["type"] == "end" and ctx["d"]["msgs"][-1]["reason"] == "cancelled"+ await ws.send_json({"type": "ping"})+ ctx = await ws_collect(ws, lambda c: None in c and any(m["type"] == "pong" for m in c[None]["msgs"]))+ assert "d" not in ctx+ await ws.close()+ assert await wait_until(lambda: not srv._jobs)+++async def test_named_voice_text_is_normalised_without_prefix(make):+ client, srv, tts = await make(normalise=True)+ tts.engine.registry.add(named_voice("Asha", gender="female"))+ r = await speech(client, input="I have 25 apples", voice="asha", language="en", response_format="pcm")+ assert r.status == 200 and r.headers["X-Maya3-Voice"] == "Asha"+ await r.read()+ req = tts.engine.requests[-1]+ assert req.voice.id == "Asha" and req.text == "I have twenty five apples" # the engine adds "{Asha}: "+++# ------------------------------------------------------------------------------------------- voices (named)+async def test_voices_list_named(make):+ client, srv, tts = await make()+ meta = {"display_name": "Asha", "gender": "female", "age": "adult", "style": "warm", "langs": ["hi", "en"]}+ reg = tts.engine.registry+ reg.add(named_voice("Asha", **meta))+ reg.add(named_voice("Nova", gender="female")) # shadows the OpenAI alias "nova"+ reg.add(named_voice("Ravi", mode="icl_spk")) # name template over a cloned reference+ reg.add(FakeVoice("bob", "icl_spk", "en")) # a clone: case-sensitive id+ voices = {v["id"]: v for v in (await (await client.get("/v1/voices")).json())["voices"]}+ assert voices["plain"] == {"id": "plain", "mode": "plain", "ref_lang": None}+ assert voices["bob"] == {"id": "bob", "mode": "icl_spk", "ref_lang": "en"}+ assert voices["Asha"] == {"id": "Asha", "mode": "named", "ref_lang": None, "meta": {"name": "Asha", **meta}}+ assert voices["Ravi"]["mode"] == "named" and voices["Ravi"]["base_mode"] == "icl_spk"+ for asked, want in (("asha", "Asha"), ("ASHA", "Asha"), ("Asha", "Asha"), ("nova", "Nova"), ("alloy", "plain")):+ r = await speech(client, input="x #frames=1", voice=asked, response_format="pcm")+ assert r.status == 200 and r.headers["X-Maya3-Voice"] == want, (asked, await r.text())+ await r.read()+ assert tts.engine.requests[-1].voice.id == want+ r = await speech(client, input="x", voice="BOB")+ assert r.status == 400 and "unknown voice" in (await r.json())["error"]["message"]+ ws = await ws_open(client)+ await ws.send_json({"type": "speak", "context_id": "n", "text": "y #frames=1", "voice": "aSHA"})+ ctx = await ws_collect(ws, lambda c: "n" in c and terminal(c["n"]))+ assert ctx["n"]["msgs"][-1]["type"] == "end" and tts.engine.requests[-1].voice.id == "Asha"+ await ws.close()+++async def test_voices_file_meta(tmp_path):+ tts = FakeTTS()+ wav = tmp_path / "a.wav"+ wav.write_bytes(wav_bytes(1.0))+ spec = tmp_path / "voices.json"+ spec.write_text(json.dumps({"voices": [{"voice_id": "asha", "ref_audio": "a.wav", "ref_text": "t", "lang": "hi",+ "mode": "plain", "meta": {"gender": "female"}}]}))+ tts.register_voice = lambda vid, **kw: tts.registered.append((vid, kw))+ S.load_voices_file(tts, spec)+ vid, kw = tts.registered[0]+ assert vid == "asha" and kw["meta"] == {"gender": "female"} and kw["ref_audio"] == str(wav)+ tts.close()diff --git a/maya3/tests/test_text.py b/maya3/tests/test_text.pynew file mode 100644index 0000000..c1edb0f--- /dev/null+++ b/maya3/tests/test_text.py@@ -0,0 +1,303 @@+"""Bundled text normaliser (maya3.text): CPU only, standard library only.++ python -m pytest maya3/tests/test_text.py -q+"""+from __future__ import annotations++import os+import re+import subprocess+import sys++import pytest++import maya3.text as T+from maya3.text import normalise_text++ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++[email protected]("text,lang,want", [+ ("I have 25 apples", "en", "I have twenty five apples"),+ ("मेरे पास 25 रुपये हैं", "hi", "मेरे पास पच्चीस रुपये हैं"),+ ("నా దగ్గర 25 రూపాయలు ఉన్నాయి", "te", "నా దగ్గర ఇరవై ఐదు రూపాయలు ఉన్నాయి"),+ ("Your OTP is 482913.", "en", "Your OTP is four, eight, two, nine, one, three."),+ ("आपका ओटीपी 4821 है", "hi", "आपका ओटीपी चार, आठ, दो, एक है"),+ ("Visit https://www.example.com/abc today", "en", "Visit W W W dot example dot com slash abc today"),+ ("Email [email protected]", "en", "Email A dot B at gmail dot com"),+ ("Ha [laughs] I have 3 cats", "en", "Ha [laughs] I have three cats"),+ ("मेरे पास 25 रुपये हैं [laughs] और 3 किताबें", "hi", "मेरे पास पच्चीस रुपये हैं [laughs] और तीन किताबें"),+ (" spaced [sighs] out 12% ", "ta", "spaced [sighs] out பன்னிரண்டு சதவீதம்"),+ ("২৫ টাকা", "bn", "পঁচিশ টাকা"),+])+def test_normalise(text, lang, want):+ assert normalise_text(text, lang) == want+++def test_caps_fold_and_acronyms():+ assert normalise_text("RAHUL KUMAR paid", "en") == "Rahul Kumar paid"+ assert normalise_text("HDFC NEFT KYC done", "en") == "HDFC NEFT KYC done" # vowel-poor: stay acronyms+ assert T._caps_fold("ASHA OTP NASA KYC") == "Asha OTP Nasa KYC" # 4 letters + 2 vowels -> a name+++def test_tags_are_protected():+ out = normalise_text("[laughs] 2 [sighs] [whispers] 3 [laughs]", "en")+ assert out == "[laughs] two [sighs] [whispers] three [laughs]"+ assert normalise_text("[laughs]", "en") == "[laughs]"+++def test_fallback_returns_text_unchanged(monkeypatch):+ def boom(s, lang):+ raise RuntimeError("tn failure")+ monkeypatch.setattr(T, "_TN", boom)+ assert normalise_text("I have 25 apples [laughs] 3", "en") == "I have 25 apples [laughs] 3"+ monkeypatch.setattr(T, "_TN", None)+ assert normalise_text("x 1", "fr") == "x 1" # unsupported language: unchanged+++def test_all_languages_run():+ for lang in ("as", "bn", "en", "gu", "hi", "kn", "ml", "mr", "or", "pa", "ta", "te"):+ out = normalise_text("Pay ₹1,250 on 12/03/2024 at 10:30, call 9820451120 [laughs]", lang)+ assert out and not any(ch.isdigit() for ch in out) and out.endswith("[laughs]"), (lang, out)+++def test_vendored_copy_is_verbatim():+ import hashlib+ want = { # sha256 of the vendored upstream tn files (upstream commit fe5e6ec)+ "assamese_numbers.py": "0f590e4132c5ee539d4fffdf098c58ae1b72ba28c9b939f78ffb78374c043d48",+ "identifier_rules.py": "c3021145c5020b85d8597f4e47415e0341c1baafa0fbc0a80318a8b27f523682",+ "indic_languages.py": "af9195e44e739bf72b2522a253d69edd0d6fc5ff1dbb7f1b5040f548cabcd800", # one comment line reworded for the public release+ "normalize.py": "b232015a7c02b8ab9b28f5e21571a0cd6c4ad7ee35ab9381bd5ee56a59169b8b",+ "script_guard.py": "5b7405de2997932ff8785da20fbd3c89e5316ce3854638194dec3f4988e019fb",+ "text_pipeline.py": "259b2ac510406bdef6a5f9bc14ebc2d3c28173729bdb6dff71e25ea31b44680a",+ "tts_chunker.py": "6ad313fa5bff97512d07db5164664802c9c9f887dd835e8ad5bc8d814657ff58",+ }+ d = os.path.join(os.path.dirname(T.__file__), "tn")+ got = {f: hashlib.sha256(open(os.path.join(d, f), "rb").read()).hexdigest() for f in want}+ assert got == want+++def test_imports_with_stdlib_only():+ code = ("import sys; import maya3.text as t; assert t.normalise_text('25', 'hi') == 'पच्चीस'; "+ "print(sorted({m.split('.')[0] for m in sys.modules} & {'numpy', 'torch', 'scipy', 'aiohttp'}))")+ out = subprocess.run([sys.executable, "-c", code], cwd=ROOT, capture_output=True, text=True, check=True)+ assert out.stdout.strip() == "[]"+++GUARDS = os.environ.get("MAYA3_REF_GUARDS", "") # optional: reference wrapper for the parity test++[email protected](not os.path.exists(GUARDS), reason="reference eval wrapper not available")+def test_parity_with_eval_wrapper():+ """Same output as the wrapper the release evals used, on the source repo's audit cases in every language."""+ import importlib.util+ import json+ spec = importlib.util.spec_from_file_location("_eval_guards", GUARDS)+ g = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(g)+ base = os.environ.get("MAYA3_REF_NORM_CASES", "")+ cases = [c["input"] for c in json.load(open(base))["cases"]] if os.path.exists(base) else []+ cases += ["Your OTP is 482913 [laughs]", "Visit https://www.example.com/abc", "RAHUL KUMAR paid ₹1,250"]+ for text in cases:+ for lang in ("en", "hi", "te", "ta", "bn", "kn"):+ t = text + " [laughs] " + text.upper()+ assert normalise_text(t, lang, rules=False) == g.normalise_text(t, lang), (lang, t)+++# ---------------------------------------------------------------------------------------------------------------+# Residual-failure rules (maya3.text.rules), cases taken from eval rows that still failed with normalisation on.[email protected]("text,lang,want", [+ # R1 two-digit-year dates (strict normaliser raised ambiguous_year and read "one five minus zero eight ...")+ ("कृपया लक्षात घ्या की तुमची मुदत ठेव 15-08-25 ला परिपक्व होत आहे", "mr", "कृपया लक्षात घ्या की तुमची मुदत ठेव पंधरा ऑगस्ट दोन हजार पंचवीस ला परिपक्व होत आहे"),+ ("শেষ তারিখ 15-08-25 নির্ধারণ", "bn", "শেষ তারিখ পনেরো আগস্ট দুই হাজার পঁচিশ নির্ধারণ"),+ ("ট্রানজ্যাকশন 9/9/99 তারিখে", "bn", "ট্রানজ্যাকশন নয় সেপ্টেম্বর উনিশশো নিরানব্বই তারিখে"),+ ("12-05-24 ତାରିଖରେ", "or", "ବାର ମଇ ଦୁଇ ହଜାର ଚବିଶି ତାରିଖରେ"),+ ("starting from 05/11/24.", "en", "starting from five November two thousand twenty four."),+ ("കാലാവധി 15-08-25 ന്", "ml", "കാലാവധി പതിനഞ്ച് ഓഗസ്റ്റ് രണ്ടായിരത്തി ഇരുപത്തിയഞ്ചിന്"),+ # R2 card expiry MM/YY next to an expiry / date word or a CVV+ ("ಕಾರ್ಡ್ನ ಅಂತಿಮ ದಿನಾಂಕ 11/26 ಮತ್ತು CVV 456 ನಮೂದಿಸಿ.", "kn", "ಕಾರ್ಡ್ನ ಅಂತಿಮ ದಿನಾಂಕ ನವೆಂಬರ್ ಎರಡು ಸಾವಿರದ ಇಪ್ಪತ್ತಾರು ಮತ್ತು CVV ನಾಲ್ಕು, ಐದು, ಆರು ನಮೂದಿಸಿ."),+ ("కార్డు గడువు తేదీ 08/25 మరియు CVV 456", "te", "కార్డు గడువు తేదీ ఆగస్టు రెండు వేల ఇరవై ఐదు మరియు CVV నాలుగు, ఐదు, ఆరు"),+ ("एक्सपायरी डेट 12/25 टाका.", "mr", "एक्सपायरी डेट डिसेंबर दोन हजार पंचवीस टाका."),+ # R3 financial-year ranges+ ("ਵਿੱਤੀ ਸਾਲ 2023-24 ਲਈ", "pa", "ਵਿੱਤੀ ਸਾਲ ਦੋ ਹਜ਼ਾਰ ਤੇਈ ਚੌਵੀ ਲਈ"),+ ("वित्त वर्ष 2023-24", "hi", "वित्त वर्ष दो हजार तेईस चौबीस"),+ # R4 space-separated card / phone digit groups+ ("तुमच्या 4111 2233 4455 6677 या कार्डवरून", "mr", "तुमच्या चार, एक, एक, एक, दोन, दोन, तीन, तीन, चार, चार, पाच, पाच, सहा, सहा, सात, सात या कार्डवरून"),+ ("ಒಟಿಪಿಯನ್ನು 98765 43210 ಗೆ ಕಳುಹಿಸುತ್ತಿದ್ದೇನೆ", "kn", "ಒಟಿಪಿಯನ್ನು ಒಂಬತ್ತು, ಎಂಟು, ಏಳು, ಆರು, ಐದು, ನಾಲ್ಕು, ಮೂರು, ಎರಡು, ಒಂದು, ಸೊನ್ನೆಗೆ ಕಳುಹಿಸುತ್ತಿದ್ದೇನೆ"),+ ("call 98765 43210", "en", "call nine, eight, seven, six, five, four, three, two, one, zero"),+ # R5 PIN keyword+ ("कृपया अपना यूपीआई पिन 4532 दर्ज करें", "hi", "कृपया अपना यूपीआई पिन चार, पाँच, तीन, दो दर्ज करें"),+ # R6 six-digit PIN codes+ ("சென்னை 600018 என்ற முகவரியில்", "ta", "சென்னை ஆறு, பூஜ்ஜியம், பூஜ்ஜியம், பூஜ்ஜியம், ஒன்று, எட்டு என்ற முகவரியில்"),+ ("Bengaluru 560038.", "en", "Bengaluru five, six, zero, zero, three, eight."),+ ("नागपूर 440010 येथे", "mr", "नागपूर चार, चार, शून्य, शून्य, एक, शून्य येथे"),+ ("যোৰহাট 785001 ত", "as", "যোৰহাট সাত, আঠ, পাঁচ, শূন্য, শূন্য, এক ত"),+ ("ಪುಣೆಯ 411001 ಅಂಚೆ ಕಚೇರಿಯಲ್ಲಿ", "kn", "ಪುಣೆಯ ನಾಲ್ಕು, ಒಂದು, ಒಂದು, ಸೊನ್ನೆ, ಸೊನ್ನೆ, ಒಂದು ಅಂಚೆ ಕಚೇರಿಯಲ್ಲಿ"),+ # R7 version strings+ ("ऐप को v4.5.2 पर अपडेट करें", "hi", "ऐप को वी चार दशमलव पाँच दशमलव दो पर अपडेट करें"),+ # R8 Tamil Month D, YYYY keeps the year as a year+ ("கடந்த ஆகஸ்ட் 15, 2025 அன்று", "ta", "கடந்த ஆகஸ்ட் பதினைந்தாம் தேதி இரண்டாயிரத்து இருபத்தைந்து அன்று"),+ # R9 rupees + paise in every language+ ("₹1,25,000.50 has been credited", "en", "one lakh twenty five thousand rupees fifty paise has been credited"),+ ("পরিমাণ হল ₹95.41, যা", "bn", "পরিমাণ হল পঁচানব্বই টাকা একচল্লিশ পয়সা, যা"),+ ("મોત્તા (₹5,400.50) નેગેટિવ", "gu", "મોત્તા, પાંચ હજાર ચારસો રૂપિયા પચાસ પૈસા, નેગેટિવ"),+ ("ಮೊತ್ತ ₹4,500.50 ಮರುಪಾವತಿ", "kn", "ಮೊತ್ತ ನಾಲ್ಕು ಸಾವಿರದ ಐನೂರು ರೂಪಾಯಿ ಐವತ್ತು ಪೈಸೆ ಮರುಪಾವತಿ"),+ ("ബിൽ ₹95.41 ആണ്", "ml", "ബിൽ തൊണ്ണൂറ്റിയഞ്ച് രൂപ നാൽപ്പത്തിയൊന്ന് പൈസ ആണ്"),+ ("बिल ₹95.41 आहे", "mr", "बिल पंच्याण्णव रुपये एक्केचाळीस पैसे आहे"),+ ("ਬਿੱਲ ₹95.41 ਹੈ", "pa", "ਬਿੱਲ ਪਚਾਨਵੇਂ ਰੁਪਏ ਇਕਤਾਲੀ ਪੈਸੇ ਹੈ"),+ ("தொகை ₹15,430.50 ஆகும்", "ta", "தொகை பதினைந்தாயிரத்து நானூற்று முப்பது ரூபாய் ஐம்பது பைசா ஆகும்"),+])+def test_residual_rules(text, lang, want):+ assert normalise_text(text, lang) == want++[email protected]("text,lang", [+ ("Your OTP is 482913.", "en"), # 6-digit OTP stays digit by digit (already was)+ ("मेरे पास 25 रुपये हैं", "hi"),+])+def test_residual_rules_keep_existing(text, lang):+ from maya3.text.tn import normalize as tn_normalize+ assert normalise_text(text, lang) == tn_normalize(T._caps_fold(text), lang).strip()++[email protected]("text,lang,want", [+ ("घर नंबर 8-2-45, सेक्टर 17", "hi", None), # door number: not a date (unchanged from the plain normaliser)+ ("100000 रुपये", "hi", "एक लाख रुपये"), # amount: not a PIN code+ ("₹100000 का", "hi", "एक लाख रुपये का"),+ ("customer id CUST-567890", "en", None), # ID suffix: left to the normaliser's code reader+ ("राशि 150000 ÷ 12 है", "hi", None), # arithmetic: not a PIN code+ ("दिनांक 05/11 को", "hi", None), # DD/MM without year: unchanged+ ("www.airindia.in/v2.1 देखें", "mr", None), # inside a URL: rules do not apply+])+def test_residual_rules_negative(text, lang, want):+ from maya3.text.tn import normalize as tn_normalize+ plain = re.sub(r"\s+", " ", tn_normalize(T._caps_fold(text), lang)).strip()+ got = normalise_text(text, lang)+ if want is None:+ assert got == plain.replace(" dash ", " " + T._rules.DASH.get(lang, "dash") + " ")+ else:+ assert got == want+ assert "February" not in got and "फ़रवरी" not in got and "फरवरी" not in got+++def test_tag_keeps_comma(monkeypatch):+ # P1 is off by default (no measured gain); when switched on it keeps the comma before an inline [tag]+ assert normalise_text("नौ, आठ, सात, [curious] छह, पाँच", "hi") == "नौ, आठ, सात. [curious] छह, पाँच"+ monkeypatch.setattr(T._rules, "TAG_COMMA", True)+ assert normalise_text("नौ, आठ, सात, [curious] छह, पाँच", "hi") == "नौ, आठ, सात, [curious] छह, पाँच"+ assert normalise_text("आपका पेमेंट फेल हुआ था ना, [sighs] बारह मई को", "hi") == "आपका पेमेंट फेल हुआ था ना, [sighs] बारह मई को"+ assert normalise_text("ठीक है. [laughs] चलो", "hi") == "ठीक है. [laughs] चलो"+++def test_uri_dash_native():+ assert normalise_text("[email protected] ਤੇ ਭੇਜੋ", "pa") == "ਕੇ ਵਾਈ ਸੀ ਅੰਡਰਸਕੋਰ update ਐਟ ਦ ਰੇਟ safebank ਡੈਸ਼ india ਡਾਟ com ਤੇ ਭੇਜੋ" # P3 spells kyc+ assert "dash" in normalise_text("mail [email protected]", "en")+++def test_rules_all_languages():+ for lang in ("as", "bn", "en", "gu", "hi", "kn", "ml", "mr", "or", "pa", "ta", "te"):+ out = normalise_text("15-08-25, 4111 2233 4455 6677, 560038, ₹95.41, v4.5.2, 2023-24, expiry 08/27", lang)+ assert out and not any(ch.isdigit() for ch in out), (lang, out)+ assert "minus" not in out and "/" not in out, (lang, out)+++# ---------------------------------------------------------------------------------------------------------------+# normaliser fixes from a multi-language benchmark (maya3.text.lexicon L1-L3, maya3.text.rules P3)[email protected]("text,want", [+ ("4 8 9 30 45 71", "চাৰি আঠ ন ত্ৰিশ পঞ্চল্লিশ একসত্তৰ"),+ ("₹1,250.50", "এক হাজাৰ দুশ পঞ্চাশ টকা পঞ্চাশ পইচা"),+ ("2,50,00,000", "দুই কোটি পঞ্চাশ লাখ"),+ ("1st 4th 9th", "প্ৰথম চতুৰ্থ নৱম"),+ ("3.14", "তিনি দশমিক এক চাৰি"),+ ("12/03/2024", "বাৰ মাৰ্চ দুই হাজাৰ চৌবিশ"),+ ("পুৱা 10:30 বজাত বিনিময়", "পুৱা দহ বাজি ত্ৰিশ মিনিটত বিনিময়"),+ ("ৰাতি 8:00 বজাৰ ভিতৰত", "ৰাতি আঠ বজাৰ ভিতৰত"),+ ("12:30 PM ত", "দুপৰীয়া বাৰ বাজি ত্ৰিশ মিনিটত"),+ ("₹50 ৰ এটা কেচবেক", "পঞ্চাশ টকাৰ এটা কেচবেক"),+ ("2.5% লৈকে", "দুই দশমিক পাঁচ শতাংশলৈকে"),+ ("45°C", "পঞ্চল্লিশ ডিগ্ৰী চেলছিয়াছ"),+ ("3/4", "তিনি চতুৰ্থাংশ"),+ ("আমি আজি 2023 টা অভিযোগৰ", "আমি আজি দুই হাজাৰ তেইশ টা অভিযোগৰ"), # টা is a classifier, not o'clock+ ("[email protected] লৈ", "support এট দ্য ৰেট এইচ ডি এফ সি bank ডট com লৈ"),+ ("ID TRN987654", "ID টি, আৰ, এন, ন, আঠ, সাত, ছয়, পাঁচ, চাৰি"),+])+def test_assamese_lexicon(text, want):+ assert normalise_text(text, "as") == want+++def test_assamese_no_bengali_forms():+ from maya3.text import lexicon+ T._lexicon.install(True)+ assert all("র" not in w for w in lexicon.AS_ONES) and len(lexicon.AS_ONES) == 100+ s = ("Pay ₹1,23,456.75 on 12/03/2024 at 5:00 PM, 1st, 3rd, 33%, 1/2, x², 5 > 3, [email protected], #45, A&B, "+ "38°C, RS 42, 9:15 AM, 14:30, 1990 চনত, 99, 31, 38 [laughs]")+ out = normalise_text(s, "as")+ assert "র" not in out and not any(ch.isdigit() for ch in out), out # no Bengali ra (র), no digits+ for bn_word in ("চার", "আট", "তিন ", "নয়", "সকাল", "দুপুর", "সন্ধ্যা", "অ্যাট", "এর ", "টা বেজে"):+ assert bn_word not in out, (bn_word, out)+++def test_lexicon_off_restores_vendored_tables():+ from maya3.text.tn import normalize as tn_normalize+ s = "12:30 PM ত ₹50 ৰ 45, 71 [email protected] e-receipt.hdfcbank.com 40 km/h"+ for lang in ("as", "bn", "hi", "kn"):+ on = normalise_text(s, lang)+ off = normalise_text(s, lang, rules=False)+ assert off == re.sub(r"\s+", " ", tn_normalize(T._caps_fold(s), lang)).strip()+ assert on != off+ assert normalise_text(s, lang) == on # toggling back on gives the same output+ assert "ত্রিশ" in normalise_text("30", "as", rules=False) # vendored data untouched+ assert normalise_text("30", "bn") == "ত্রিশ" # Bengali keeps its own ra++[email protected]("text,lang,want", [+ ("40 km/h বেগে", "bn", "চল্লিশ কে এম প্রতি ঘণ্টা বেগে"),+ ("850 km/h আৰু", "as", "আঠশ পঞ্চাশ কে এম প্ৰতি ঘণ্টা আৰু"),+ ("45 km/h च्या", "mr", "पंचेचाळीस के एम प्रति तासच्या"),+ ("120 km/h ની", "gu", "એકસો વીસ કે એમ પ્રતિ કલાકની"),+ ("100 MB/s ಗಿಂತ", "kn", "ನೂರು ಎಂ ಬಿ ಪರ್ ಸೆಕೆಂಡ್ ಗಿಂತ"),+ ("30 km/h வேகத்தில்", "ta", "முப்பது கே எம் பெர் ஹவர் வேகத்தில்"),+ ("speed 40 km/h", "en", "speed forty kilometers per hour"),+ ("100 MB/s", "en", "one hundred M B per second"),+])+def test_per_units(text, lang, want):+ assert normalise_text(text, lang) == want++[email protected]("text,lang,want", [+ # sub-domain hosts were spelled from the last label only+ ("तुमची पावती e-receipt.hdfcbank.com वर", "mr", "तुमची पावती ई डॅश receipt डॉट एच डी एफ सी bank डॉट com वर"),+ ("netbanking.nationalbank.in ਤੋਂ", "pa", "netbanking ਡਾਟ nationalbank ਡਾਟ in ਤੋਂ"),+ # a bare domain at the end of a sentence was not spelled at all+ ("Book on irctc.co.in.", "en", "Book on I R C T C dot co dot in."),+ # UPI IDs: the local part was left raw+ ("pay rahul.deshmukh@okaxis now", "en", "pay rahul dot deshmukh at okaxis now"),+ # P3 acronym labels+ ("[email protected] ত", "as", "report ডেশ্ব fraud এট দ্য ৰেট এছ বি আই ডট co ডট in ত"),+ ("www.onlinesbi.sbi देखें", "hi", "डब्ल्यू डब्ल्यू डब्ल्यू डॉट online एस बी आई डॉट एस बी आई देखें"),+ ("kyc.axisbank.com", "en", "K Y C dot axisbank dot com"),+ ("[email protected]", "en", "support at paytm dot com"), # not an acronym: unchanged+])+def test_uri_hosts_and_acronyms(text, lang, want):+ assert normalise_text(text, lang) == want+++def test_uri_acronym_only_inside_uris():+ assert normalise_text("sbi and kyc", "en") == "sbi and kyc"+ assert normalise_text("Contact the public office", "en") == "Contact the public office"++[email protected]("text,lang,want", [+ # R10 percent range with two signs ("...percentminus four percent")+ ("3.5%-4% सुत", "as", "তিনি দশমিক পাঁচৰ পৰা চাৰি শতাংশ सुत"),+ ("rate 3.5%-4%", "en", "rate three point five to four percent"),+ # R11 price per unit ("/" dropped, "kg" left raw)+ ("₹500/kg ਲੱਗੇਗਾ", "pa", "ਪੰਜ ਸੌ ਰੁਪਏ ਪ੍ਰਤੀ ਕੇ ਜੀ ਲੱਗੇਗਾ"),+ ("₹500/kg ଅତିରିକ୍ତ", "or", "ପାଞ୍ଚ ଶହ ଟଙ୍କା ପ୍ରତି କେ ଜି ଅତିରିକ୍ତ"),+ ("₹500/kg extra", "en", "five hundred rupees per kg extra"),+ # R12 p.a.+ ("8.5% p.a. सुद", "mr", "आठ पूर्णांक पाच टक्के पी ए सुद"),+ ("7% p.a. interest", "en", "seven percent per annum interest"),+])+def test_symbol_rules(text, lang, want):+ assert normalise_text(text, lang) == wantdiff --git a/maya3/text/README.md b/maya3/text/README.mdnew file mode 100644index 0000000..43756d5--- /dev/null+++ b/maya3/text/README.md@@ -0,0 +1,56 @@+# maya3.text: the bundled text normaliser++`normalise_text(text, lang)` turns numbers, currency, dates, times, OTPs and phone numbers, URLs and e-mails into+spoken words in the request language (as bn en gu hi kn ml mr or pa ta te). It title-cases ALL-CAPS names and leaves+inline `[tags]` alone. The server applies it to every request by default. `--no-normalise` turns it off for the+whole server, and the request field `"normalize": false` turns it off for one request.+`Maya3TTS.generate/stream(..., normalize=True)` applies it in Python.++**Provenance.** `tn/` is vendored byte for byte from Maya Research's text normaliser (upstream commit `fe5e6ec`); the release benchmark used the same copy. `tests/test_text.py::test_vendored_copy_is_verbatim` pins the sha256 of each file (one comment line in `indic_languages.py` was reworded for the public release). The only addition is `tn/__init__.py`. The wrapper in `__init__.py` adds caps folding, tag protection and a per-piece fallback: on error it returns the piece unchanged.++**Dependencies.** Standard library only. The package has no data files.++**Not supported.** The opt-in identifier modes `FR3_TN_URL_SPELL=1` and `FR3_TN_LONG_DIGITS=1` read+`identifier_words.json`. That file is not in the fe5e6ec snapshot. With either variable set, the normaliser raises on any text+that contains a URL, e-mail address or long digit run. The wrapper then passes that piece (the text between+`[tags]`) through unnormalised. Both are off by default, as they were in the evals. When the normaliser+falls back internally (an invalid date, for example), it prints one `[obs] {"event": "normalization_fallback", ...}`+line to stdout. That line never contains the caller's text.++**Targeted rules (`rules.py`).** `normalise_text(text, lang)` applies a small set of pre/post rules around+the vendored copy (which stays byte-identical). They come from a review of the remaining failures in the release evaluations. Each one fixes an input shape that the strict normaliser rejected (it then read+the span character by character) or read in an unexpected way:++| rule | input | before | after |+|---|---|---|---|+| R1 date_2y | `15-08-25`, `9/9/99` | "one five minus zero eight minus two five" | "fifteen August two thousand twenty five" (00-50 -> 20xx) |+| R2 expiry | `11/26` beside an expiry/validity/date word or a CVV | "eleven by twenty six" | "November two thousand twenty six" |+| R3 fy_range | `2023-24` | "two, zero, two, three, two, four" | "two thousand twenty three twenty four" |+| R4 digit_groups | `4111 2233 4455 6677`, `98765 43210` | four cardinals | digit by digit |+| R5 pin_keyword | `पिन 4532` | "four thousand five hundred thirty two" | digit by digit |+| R6 pincode | bare 6-digit number, no currency/unit/ID prefix/maths next to it | "five lakh sixty thousand thirty eight" | digit by digit |+| R7 version | `v4.5.2` | "four.five.two" | "four point five point two" |+| R8 ta_date_year | Tamil `ஆகஸ்ட் 15, 2025` | year read digit by digit | year read as a year |+| R9 paise | `₹95.41` in bn en gu kn ml mr pa ta | "ninety five point four one rupees" | "ninety five rupees forty one paise" |+| P1 tag_comma | `सात, [curious] छह` | "सात. [curious]" | the comma is kept (off by default: no measured gain) |+| P2 uri_dash | `-` inside an e-mail or URL, Indic languages | English "dash" | the word in the request language |++Rules never apply inside e-mail addresses or URLs. `normalise_text(..., rules=False)` reproduces the eval-time+behaviour exactly (`test_parity_with_eval_wrapper`). That mode is for testing only, because R9 patches the+module-level language tables while rules are on. The before/after diff over all 13,468 eval texts (517 changed) was+reviewed by hand.++**Benchmark review fixes.** More corrections, again around the+untouched vendored copy and only with `rules=True`:++| fix | where | before | after |+|---|---|---|---|+| L1 as_lexicon | `lexicon.py` | Assamese reused Bengali tables: ত্রিশ (Bengali র), প্রথম/চতুর্থ, অ্যাট দ্য রেট, letters আর/এস, সকাল/দুপুর/রাত, "{h}টা", "দহ বাজি ত্রিশ মিনিট বজাত", "পঞ্চাশ টকা ৰ" | ত্ৰিশ, প্ৰথম/চতুৰ্থ, এট দ্য ৰেট, আৰ/এছ, পুৱা/দুপৰীয়া/ৰাতি, "{h} বজা", "দহ বাজি ত্ৰিশ মিনিটত", "পঞ্চাশ টকাৰ"; 45 পঞ্চল্লিশ, 71 একসত্তৰ |+| L2 per_unit | `lexicon.py` | `40 km/h` -> "কে এম per এইচ" | "কে এম প্রতি ঘণ্টা" (language's per word + hour/second) |+| L3 uri_hosts | `lexicon.py` | `e-receipt.hdfcbank.com` -> "e-receipt.hdfcbank ডট com"; sentence-final `irctc.co.in.` and UPI IDs `a.b@okaxis` left raw | whole host / ID spelled |+| P3 uri_acronym | `rules.py` | `sbi.co.in`, `hdfcbank.com` -> "sbi", "hdfcbank" (Latin) | letters in the request language: "এছ বি আই", "এইচ ডি এফ সি bank" |+| R10 pct_range | `rules.py` | `3.5%-4%` -> "...percentminus four percent" | "three point five to four percent" |+| R11 per_price | `rules.py` | `₹500/kg` -> "five hundred rupees kg" | "... per K G" (per word of the language) |+| R12 per_annum | `rules.py` | `p.a.` left raw | "P A" in the request language (en: "per annum") |++`lexicon.install(False)` restores every patched table, so `rules=False` is still the eval-time behaviour.diff --git a/maya3/text/__init__.py b/maya3/text/__init__.pynew file mode 100644index 0000000..60507a1--- /dev/null+++ b/maya3/text/__init__.py@@ -0,0 +1,82 @@+"""Text normalisation for Maya3 (numbers, currency, dates, OTPs, URLs, ... -> spoken words, per language).++ from maya3.text import normalise_text+ normalise_text("Your OTP is 482913 [laughs]", "en") # 'Your OTP is four, eight, two, nine, one, three [laughs]'++Same behaviour as the normalise_text wrapper the release evals used:+ * inline [tags] (e.g. [laughs], [sighs]) are protected: the text between them is normalised piece by piece;+ * ALL-CAPS Latin words that look like names (>= 5 letters with >= 2 vowels, or 4 letters with >= 2 vowels) are+ title-cased first, so the normaliser and the model read them as words; short / vowel-poor tokens (OTP, NEFT,+ HDFC, KYC) stay acronyms;+ * each piece goes through the bundled normaliser maya3.text.tn (pure Python, standard library only);+ * if the normaliser raises on a piece, that piece is kept unchanged (the eval wrapper's second fallback, a+ separate benchmark pipeline, is not part of the release);+ * whitespace is collapsed and the result stripped;+ * `rules=True` (default) adds the targeted pre/post rules of maya3.text.rules (two-digit-year dates, card expiry,+ FY ranges, spaced card/phone digits, PIN codes, version strings, rupees+paise in every language, the comma+ before an inline [tag]). `rules=False` is the exact behaviour of the release evals before these rules were added.+`lang` is a Maya3 language code (as bn en gu hi kn ml mr or pa ta te); for an unknown code the normaliser raises,+so the text comes back with only the caps fold and whitespace collapse applied.+"""+from __future__ import annotations++import logging+import re++from maya3.text import lexicon as _lexicon+from maya3.text import rules as _rules++__all__ = ["normalise_text", "normalize_text", "SOURCE"]++SOURCE = "Maya Research text normaliser, upstream commit fe5e6ec"++_TAG = re.compile(r"(\[[a-z ]+\])")+_CAPS = re.compile(r"\b[A-Z]{4,}\b")+_VOWELS = set("AEIOU")+_TN = None++log = logging.getLogger("maya3.text")+++def _caps_fold(t):+ def f(m):+ w = m.group(0)+ if len(w) >= 5 and sum(ch in _VOWELS for ch in w) >= 2 or (len(w) == 4 and sum(ch in _VOWELS for ch in w) >= 2):+ return w.title()+ return w+ return _CAPS.sub(f, t)+++def _load_tn():+ global _TN+ if _TN is None:+ from maya3.text.tn.normalize import normalize+ _TN = normalize+ return _TN+++def normalise_text(text: str, lang: str, rules: bool = True) -> str:+ tn = _load_tn()+ _rules.install(rules)+ _lexicon.install(rules)+ out = []+ segs = _TAG.split(text)+ for i, seg in enumerate(segs):+ if not seg or _TAG.fullmatch(seg):+ out.append(seg)+ continue+ s = _caps_fold(seg)+ try:+ s2 = tn(_rules.pre(s, lang) if rules else s, lang)+ if rules:+ s2 = _rules.post(s2, seg, lang, before_tag=any(_TAG.fullmatch(x) for x in segs[i + 1:i + 2]))+ except Exception as exc: # never fail a request on normalisation: keep this piece as written+ log.debug("normaliser fallback (%s: %s)", type(exc).__name__, exc)+ s2 = s+ lead = seg[:len(seg) - len(seg.lstrip())]+ trail = seg[len(seg.rstrip()):]+ out.append(lead + s2.strip() + trail)+ return re.sub(r"\s+", " ", "".join(out)).strip()+++normalize_text = normalise_textdiff --git a/maya3/text/lexicon.py b/maya3/text/lexicon.pynew file mode 100644index 0000000..ed88b3f--- /dev/null+++ b/maya3/text/lexicon.py@@ -0,0 +1,170 @@+"""Language-table corrections applied around the vendored normaliser (maya3.text.tn), found by a multi-language+normaliser benchmark.++The vendored copy stays byte-identical. `install(True)` (called by maya3.text.normalise_text with rules on) patches+the module-level language tables / one Normalizer method; `install(False)` restores the originals exactly, so+`normalise_text(..., rules=False)` keeps the eval-time behaviour.++ L1 as_lexicon Assamese inherited Bengali grammar tables: Bengali र (U+09B0) instead of Assamese ৰ (U+09F0) in the+ number words (ত্রিশ -> ত্ৰিশ), Bengali ordinals / symbol words / letter names / clock words+ (চতুর্থ, অ্যাট দ্য রেট, আর, সকাল, দুপুর, রাত, "{h}টা", "এর বর্গ" ...). Replaced with Assamese forms;+ Assamese clock markers (বজাত / বজাৰ / বজালৈ) and period words (পুৱা, আবেলি, বিয়লি, ৰাতি ...)+ are recognised, and postpositions glue to the number noun (পঞ্চাশ টকা ৰ -> পঞ্চাশ টকাৰ).+ L2 per_unit "km/h", "MB/s": the per word was the English "per" in bn as gu kn ml mr pa ta, and the+ denominator was a spelled letter ("কে এম per এইচ"); now the language's per word + hour / second.+ L3 uri_hosts bare domains with sub-domains (e-receipt.hdfcbank.com, netbanking.nationalbank.in) were only+ matched from the last label, so "e-receipt.hdfcbank" stayed raw; a bare domain that ends a sentence+ ("irctc.co.in.") was not matched at all; the local part of a UPI ID (rahul.deshmukh@okaxis) stayed+ raw. All three are now spelled like other URLs.+"""+from __future__ import annotations++import re+import types++__all__ = ["install", "AS_ONES"]++_R, _RR = "র", "ৰ" # Bengali ra, Assamese ra+++def _as_script(s):+ return s.replace(_R, _RR) if isinstance(s, str) else s+++# Assamese 0-99: AI4Bharat indic-numtowords data (tn/assamese_numbers.py) with the Bengali ra fixed to ৰ+# (ঊনত্রিশ..আঠত্রিশ -> ঊনত্ৰিশ..আঠত্ৰিশ) and two malformed entries corrected: 45 পঁঞ্চল্লিশ -> পঞ্চল্লিশ,+# 71 এসত্তৰ -> একসত্তৰ.+def _as_ones():+ from maya3.text.tn.assamese_numbers import ONES+ ones = [_as_script(w) for w in ONES]+ ones[45] = "পঞ্চল্লিশ"+ ones[71] = "একসত্তৰ"+ return ones+++AS_ONES = None # filled on first install++_AS_SYM = {+ "at": "এট দ্য ৰেট", "underscore": "আণ্ডাৰস্ক'ৰ", "slash": "শ্লেচ", "hash": "হেচ", "amp": "এণ্ড",+ "squared": "বৰ্গ", "sqrt": "বৰ্গমূল", "lt": "তকৈ কম", "gt": "তকৈ বেছি",+ "half": "আধা", "quarter": "এক চতুৰ্থাংশ", "three_quarters": "তিনি চতুৰ্থাংশ",+ "degree": "ডিগ্ৰী", "celsius": "ডিগ্ৰী চেলছিয়াছ", "fahrenheit": "ডিগ্ৰী ফাৰেনহাইট",+ "second": "ছেকেণ্ড", "cent": "চেণ্ট", "per": "প্ৰতি",+}+_AS_PERIOD_DETECT = {+ "পুৱা": "morning", "পুৱাৰ": "morning", "পুৱাতে": "morning", "ৰাতিপুৱা": "morning",+ "দুপৰীয়া": "afternoon", "দুপৰীয়াৰ": "afternoon", "দুপৰীয়াত": "afternoon",+ "আবেলি": "evening", "আবেলিৰ": "evening", "আবেলিতে": "evening", "বিয়লি": "evening", "বিয়লিৰ": "evening",+ "সন্ধিয়া": "evening", "সন্ধিয়াৰ": "evening", "সন্ধিয়াতে": "evening",+ "ৰাতি": "night", "ৰাতিৰ": "night", "ৰাতিতে": "night",+}+_AS_ATTACH = {"টকা", "পইচা", "ডলাৰ", "শতাংশ", "মিনিট", "ঘণ্টা", "ছেকেণ্ড", "বজা", "ডিগ্ৰী", "কিলোমিটাৰ"}+_AS_PP = ("ৰ", "ত", "লৈ", "তকৈ", "ৰে", "তে", "লৈকে", "ৰপৰা")+++def _as_attach(self, rep, tok):+ """Assamese case endings glue to the noun without sandhi: টকা+ৰ -> টকাৰ, মিনিট+ত -> মিনিটত."""+ t = tok.lstrip("-")+ last = rep.rsplit(" ", 1)[-1]+ if last not in _AS_ATTACH or t not in _AS_PP:+ return None+ return rep + t+++_PER = {"bn": "প্রতি", "gu": "પ્રતિ", "mr": "प्रति", "pa": "ਪ੍ਰਤੀ",+ "ta": "பெர்", "kn": "ಪರ್", "ml": "പെർ"} # hi or te already have one; as: _AS_SYM+_PER_UNITS = { # denominators of X/h, X/s (H, S are not units on their own, so only "km/h"-style reads change)+ "en": {"H": "hour", "S": "second"},+ "hi": {"H": "घंटा", "S": "सेकंड"}, "mr": {"H": "तास", "S": "सेकंद"},+ "bn": {"H": "ঘণ্টা", "S": "সেকেন্ড"}, "as": {"H": "ঘণ্টা", "S": "ছেকেণ্ড"},+ "gu": {"H": "કલાક", "S": "સેકન્ડ"}, "pa": {"H": "ਘੰਟਾ", "S": "ਸਕਿੰਟ"}, "or": {"H": "ଘଣ୍ଟା", "S": "ସେକେଣ୍ଡ"},+ "ta": {"H": "ஹவர்", "S": "செகண்ட்"}, "te": {"S": "సెకండ్"}, # te already has H+ "kn": {"H": "ಅವರ್", "S": "ಸೆಕೆಂಡ್"}, "ml": {"H": "അവർ", "S": "സെക്കൻഡ്"},+}++_saved = [] # (restore callable) in apply order+_installed = False+++def _set_attr(obj, name, value):+ had = name in vars(obj)+ old = vars(obj).get(name)+ setattr(obj, name, value)+ _saved.append(lambda: setattr(obj, name, old) if had else delattr(obj, name))+++def _set_key(d, key, value):+ had = key in d+ old = d.get(key)+ d[key] = value+ _saved.append(lambda: d.__setitem__(key, old) if had else d.pop(key, None))+++def _patch_url(N):+ orig = N._m_url++ def _m_url(self, text):+ # as the vendored _m_url, but a bare host may have sub-domain labels (e-receipt.hdfcbank.com) and may end a+ # sentence ("... irctc.co.in." was left unspelled: the vendored lookahead rejected any following ".")+ pat = (r"https?://[^\s<>]+|www\.[^\s<>]+"+ r"|\b[A-Za-z][\w\-]*(?:\.[A-Za-z0-9][\w\-]*)*\.(?:com|org|net|ai|io|co|dev|app|edu|gov|in)"+ r"(?:\.(?:in|uk|us))?(?:[/?#][^\s<>]*)?(?![\w]|\.\w)")+ for m in re.finditer(pat, text):+ token = m.group(0).rstrip(".,!?;)")+ body = re.sub(r"^https?://", "", token)+ yield m.start(), m.start() + len(token), self._spell_uri_part(body)+ # UPI IDs with a dotted local part (rahul.deshmukh@okaxis) were left raw (the "." unspoken); spell the ID+ for m in re.finditer(r"(?<![\w.@])[A-Za-z][\w\-]*\.[\w.\-]*@[A-Za-z][A-Za-z0-9]{1,15}(?![\w@]|\.\w)", text):+ yield m.start(), m.end(), self._spell_uri_part(m.group(0))++ N._m_url = _m_url+ _saved.append(lambda: setattr(N, "_m_url", orig))+++def install(on: bool = True):+ global _installed, AS_ONES+ if on == _installed:+ return+ import sys+ import maya3.text.tn.normalize # noqa: F401+ mod = sys.modules["maya3.text.tn.normalize"]+ if on:+ L = mod.language_table("as")+ AS_ONES = AS_ONES or _as_ones()+ _set_attr(L, "ONES", AS_ONES)+ _set_attr(L, "ORDINAL_EXCEPTIONS", {1: "প্ৰথম", 2: "দ্বিতীয়", 3: "তৃতীয়", 4: "চতুৰ্থ", 5: "পঞ্চম",+ 6: "ষষ্ঠ", 7: "সপ্তম", 8: "অষ্টম", 9: "নৱম", 10: "দশম"})+ _set_attr(L, "LETTERS", {**{k: _as_script(v) for k, v in L.LETTERS.items()}, "S": "এছ", "Y": "ৱাই"})+ for k, v in list(L.SYM.items()):+ if _as_script(v) != v:+ _set_key(L.SYM, k, _as_script(v))+ for k, v in _AS_SYM.items():+ _set_key(L.SYM, k, v)+ _set_attr(L, "PERIODS", {"morning": "পুৱা", "afternoon": "দুপৰীয়া", "evening": "সন্ধিয়া", "night": "ৰাতি"})+ _set_attr(L, "PERIOD_DETECT", {**L.PERIOD_DETECT, **_AS_PERIOD_DETECT})+ _set_attr(L, "TIME_ON_HOUR", "{h} বজা")+ # Bengali "টা" is a counting classifier in Assamese (2023 টা অভিযোগ), not an o'clock marker+ _set_attr(L, "TIME_MARKERS", ["বাজে", "বজাত", "বজাৰ", "বজালৈ", "বজাতকৈ", "বজা"])+ _set_attr(L, "MARKER_SUFFIXES", {"বজাত": "ত", "বজাৰ": "ৰ", "বজালৈ": "লৈ", "বজাতকৈ": "তকৈ"})+ _set_attr(L, "POWER", "{base}ৰ ঘাত {exp}")+ _set_attr(L, "DECADE_SHORT", "{tens}ৰ দশক")+ _set_attr(L, "DECADE_FULL", "{tens}ৰ দশক")+ _set_attr(L, "ABBREV_UNITS", {"MINS": "মিনিট", "MIN": "মিনিট", "HRS": "ঘণ্টা", "HR": "ঘণ্টা",+ "SECS": "ছেকেণ্ড", "SEC": "ছেকেণ্ড", "KMS": "কিলোমিটাৰ"})+ _set_attr(L, "attach_postposition", types.MethodType(_as_attach, L))+ for code, word in _PER.items():+ sym = mod.language_table(code).SYM+ if "per" not in sym:+ _set_key(sym, "per", word)+ for code, words in _PER_UNITS.items():+ T = mod.language_table(code)+ uw = dict(T.UNIT_WORDS)+ for k, w in words.items():+ uw.setdefault(k, w)+ _set_attr(T, "UNIT_WORDS", uw)+ _patch_url(mod.Normalizer)+ else:+ while _saved:+ _saved.pop()()+ mod._engine.cache_clear() # regexes are built from the tables+ _installed = ondiff --git a/maya3/text/rules.py b/maya3/text/rules.pynew file mode 100644index 0000000..51bf7ba--- /dev/null+++ b/maya3/text/rules.py@@ -0,0 +1,273 @@+"""Targeted pre/post rules around the vendored normaliser (maya3.text.tn), derived from the eval rows that still+failed with text normalisation on.++The vendored copy stays byte-identical. Each rule rewrites one input shape that the strict normaliser either rejects+(it then falls back to reading the span character by character: "15-08-25" -> "one five minus zero eight minus two+five") or reads in a way listeners do not expect (a PIN code as "five lakh sixty thousand thirty eight"):++ R1 date_2y DD-MM-YY, DD/MM/YY, DD.MM.YY -> four-digit year (pivot: 00-50 -> 20xx, 51-99 -> 19xx),+ then the normaliser's own date reading+ R2 expiry MM/YY or MM/YYYY next to an expiry / validity / date word or a CVV -> "<month> <year>"+ R3 fy_range 2023-24 (second part = next year) -> "<year> <two-digit number>"+ R4 digit_groups 4111 2233 4455 6677, 98765 43210, 1800 123 4567 (>= 10 digits in space-separated groups)+ -> one digit run, which the normaliser reads digit by digit+ R5 pin_keyword PIN / पिन / ... followed by 4-6 digits -> digit by digit+ R6 pincode a bare 6-digit number (no currency or unit next to it, no grouping commas) -> digit by digit+ R7 version v4.5.2 -> "v four point five point two" (language's decimal word)+ R8 ta_date_year Tamil "ஆகஸ்ட் 15, 2025" -> "15 ஆகஸ்ட் 2025" (the normaliser keeps the year)+ R10 pct_range 3.5%-4% -> 3.5-4% (the normaliser's own percent range)+ R11 per_price ₹500/kg -> "<amount> <per word> K G"+ R12 per_annum 8.5% p.a. -> "P A" (en: "per annum")+ R9 paise rupee amounts with two decimals read "<n> rupees <m> paise" in every language (the tables of+ bn en gu kn ml mr pa ta had no paise word, so they read "point five zero rupees")+ post:+ P1 tag_comma a piece that ends in "," before an inline [tag] keeps its comma (the normaliser turns a trailing+ comma into a full stop, and the model then ends the sentence at the tag)+ P2 uri_dash "-" inside an e-mail / URL is spoken in the request language, not as the English word "dash"+ P3 uri_acronym lowercase acronym labels in an e-mail / URL (sbi, kyc, hdfc in hdfcbank, sbi in onlinesbi) are+ spelled letter by letter in the request language; other labels keep their English spelling+Language-table corrections (Assamese lexicon, "per" units, sub-domain hosts) live in maya3.text.lexicon.+"""+from __future__ import annotations++import re++__all__ = ["pre", "post", "install", "RULES"]++RULES = ("date_2y", "expiry", "fy_range", "digit_groups", "pin_keyword", "pincode", "version", "ta_date_year",+ "paise", "pct_range", "per_price", "per_annum", "tag_comma", "uri_dash", "uri_acronym")++PAISE = {"en": "paise", "bn": "পয়সা", "gu": "પૈસા", "kn": "ಪೈಸೆ", "ml": "പൈസ", "mr": "पैसे", "pa": "ਪੈਸੇ",+ "ta": "பைசா"} # hi as or te already have one+DASH = {"hi": "डैश", "mr": "डॅश", "bn": "ড্যাশ", "as": "ডেশ্ব", "gu": "ડૅશ", "pa": "ਡੈਸ਼", "or": "ଡ୍ୟାସ୍",+ "ta": "டாஷ்", "te": "డాష్", "kn": "ಡ್ಯಾಶ್", "ml": "ഡാഷ്"}++# expiry / validity / date words (any language; matched case-insensitively in the 40 characters before the span)+_EXPIRY_WORDS = [+ "expiry", "expires", "expire", "exp", "valid", "validity", "thru", "expiration",+ "एक्सपायरी", "समाप्ति", "वैधता", "मुदत", "समाप्ती",+ "মেয়াদ", "মেয়াদ", "এক্সপায়ারি", "এক্সপায়ারি", "এক্সপায়াৰী", "ম্যাদ",+ "એક્સપાયરી", "સમાપ્તિ", "માન્યતા", "ਮਿਆਦ", "ਐਕਸਪਾਇਰੀ",+ "காலாவதி", "எக்ஸ்பைரி", "గడువు", "ఎక్స్పైరీ", "ఎక్స్పైరీ",+ "ಮುಕ್ತಾಯ", "ಅಂತಿಮ ದಿನಾಂಕ", "ಎಕ್ಸ್ಪೈರಿ", "കാലാവധി", "എക്സ്പയറി", "ମିଆଦ", "ଏକ୍ସପାୟାରୀ", "ସମାପ୍ତି",+]+_DATE_WORDS = ["date", "तारीख", "तिथि", "दिनांक", "डेट", "তারিখ", "তাৰিখ", "તારીખ", "ડેટ", "ਤਾਰੀਖ਼", "ਤਾਰੀਖ", "ਡੇਟ",+ "தேதி", "டேட்", "తేదీ", "డేట్", "ದಿನಾಂಕ", "ಡೇಟ್", "തീയതി", "ഡേറ്റ്", "ତାରିଖ", "ଡେଟ୍"]+_alt = lambda ws: "|".join(sorted(map(re.escape, ws), key=len, reverse=True))+_EXPIRY_RE = re.compile(_alt(_EXPIRY_WORDS), re.I)+_DATE_RE = re.compile(_alt(_DATE_WORDS), re.I)+_PIN_WORDS = ["pin", "पिन", "पिनकोड", "ಪಿನ್", "పిన్", "பின்", "പിൻ", "পিন", "ପିନ", "ਪਿੰਨ", "ਪਿਨ", "પિન"]+_PIN_RE = re.compile(r"(?<![\w])(?:" + "|".join(map(re.escape, _PIN_WORDS)) + r")(?:[\s-]*(?:code|कोड|কোড|કોડ|ਕੋਡ|କୋଡ|ಕೋಡ್|కోడ్|கோட்|കോഡ്))?"+ r"(?:\s*(?:no\.?|number|नंबर|नम्बर))?\s*[:\-]?\s*(\d{4,6})(?![\d,]|\.\d)", re.I)+# words right after a number that make it an amount / quantity (R6 must not read those digit by digit)+_AMOUNT_AFTER = re.compile(+ r"\s*(?:rupees?|rs\.?|inr|dollars?|usd|paise|lakh|crore|thousand|people|users|customers|km|kg|kms|"+ r"रुपये|रुपए|रुपया|रु\.?|लाख|करोड़|हज़ार|हजार|लोग|লাখ|টাকা|টকা|কোটি|રૂપિયા|લાખ|ਰੁਪਏ|ਲੱਖ|ரூபாய்|ரூ\.?|லட்சம்|"+ r"రూపాయలు|రూ\.?|లక్షల|ರೂಪಾಯಿ|ರೂ\.?|ಲಕ್ಷ|രൂപ|ലക്ഷം|ଟଙ୍କା|ଲକ୍ଷ|ਕਰੋੜ|कोटी)(?![\w])", re.I)+_CURRENCY_BEFORE = re.compile(r"(?:₹|\$|€|£|\brs\.?|\binr|रु\.?|ரூ\.?|రూ\.?|ರೂ\.?)\s*$", re.I)+_NUMBER_WORD_BEFORE = re.compile(+ r"(?:\bno\.?|\bnumber|\bplot|\bflat|\bhouse|\bdoor|\bh\.\s?no\.?|नंबर|नम्बर|क्रमांक|नं\.?|নং|নম্বর|নম্বৰ|ਨੰਬਰ|નંબર|ନମ୍ବର|"+ r"எண்|నంబర్|ಸಂಖ್ಯೆ|ನಂಬರ್|നമ്പർ)\s*[:\-]?\s*$", re.I)+_TA_MONTHS = ["ஜனவரி", "பிப்ரவரி", "மார்ச்", "ஏப்ரல்", "மே", "ஜூன்", "ஜூலை", "ஆகஸ்ட்", "செப்டம்பர்", "அக்டோபர்",+ "நவம்பர்", "டிசம்பர்"]+_URI_RE = re.compile(r"https?://\S+|www\.\S+|\b[\w.%+\-]+@[\w.\-]+\.[A-Za-z]{2,}|\b[A-Za-z][\w.\-]*@[A-Za-z][A-Za-z0-9]{1,15}\b|\b[A-Za-z][\w\-]*(?:\.[A-Za-z0-9][\w\-]*)*\.(?:com|org|net|ai|io|co|dev|app|edu|gov|in)(?:\.(?:in|uk|us))?(?:[/?#][^\s<>]*)?")++# P3: lowercase acronym labels inside e-mail / URL hosts and paths are spelled letter by letter (sbi.co.in ->+# "S B I dot co dot in", hdfcbank.com -> "H D F C bank dot com"); other labels keep their English spelling.+_URI_ACRONYMS = {"sbi", "hdfc", "icici", "kyc", "irctc", "pnb", "rbi", "idbi", "npci", "uidai", "epfo", "mf", "lic",+ "upi", "gst", "sms", "atm", "emi", "bob", "boi", "uco", "iob", "nsdl", "cdsl", "pnr", "otp", "ifsc"}+_URI_ACR_PREFIX = ("icici", "irctc", "uidai", "hdfc", "idbi", "npci", "epfo", "sbi", "pnb", "kyc", "rbi")+_URI_ACR_SUFFIX = ("sbi", "mf")++_SPELL_UNITS = {"kg", "km", "gm", "g", "ml", "ltr", "l"} # R11: read letter by letter (as the normaliser reads "15 kg")++_installed = False+++def install(on: bool = True):+ """R9: add the paise word to the language tables that lack it (bn en gu kn ml mr pa ta), so the normaliser's own+ main+sub-unit path reads ₹95.41 as "<n> rupees <m> paise" (with its native scale words and case suffixes).+ The tables are module-level; install(False) removes the added words again (used only by rules=False, the+ eval-parity mode; do not mix rules=False with concurrent rules=True calls)."""+ global _installed+ if on == _installed:+ return+ from maya3.text.tn.normalize import language_table+ for code, word in PAISE.items():+ sym = language_table(code).SYM+ if on:+ sym.setdefault("paisa", word)+ elif sym.get("paisa") == word:+ del sym["paisa"]+ _installed = on+++def _table(lang):+ from maya3.text.tn.normalize import language_table+ return language_table(lang)+++def _tn_id_context(L, before):+ """True when the normaliser itself will read the next number digit by digit (an ID keyword such as PIN / OTP /+ number in the three tokens before it); the rule then leaves the span alone so the normaliser's postposition+ sandhi ("...ಒಂದರಲ್ಲಿ") is kept."""+ from maya3.text.tn import normalize as _N # the function; its module holds the keyword sets+ import sys+ mod = sys.modules["maya3.text.tn.normalize"]+ kws = mod._ID_KEYWORDS_EN | mod._OTP_INPUT_WORDS | {w.lower() for w in L.ID_KEYWORDS}+ toks = re.findall(r"[\w#\u0900-\u0DFF']+", before.replace("\u200c", "").lower())[-3:]+ return any(t in kws for t in toks)+++def _digits(L, s):+ return ", ".join(L.digit(int(c)) for c in s)+++def _year4(yy):+ y = int(yy)+ return 2000 + y if y <= 50 else 1900 + y+++def _decimal_word(L):+ w = L.decimal(1, "2")+ a, b = L.cardinal(1), L.digit(2)+ return w[len(a):len(w) - len(b)].strip() if w.startswith(a) and w.endswith(b) else "point"+++def pre(text: str, lang: str) -> str:+ """Apply R1-R8 outside e-mail / URL spans (those are identifiers, spelled by the normaliser)."""+ try:+ L = _table(lang)+ except Exception:+ return text+ out, pos = [], 0+ for m in _URI_RE.finditer(text):+ out.append(_pre(text[pos:m.start()], lang, L)); out.append(m.group(0)); pos = m.end()+ out.append(_pre(text[pos:], lang, L))+ return "".join(out)+++def _pre(text, lang, L):+ t = text++ # R10 percent ranges written with the sign twice: 3.5%-4% (the normaliser read "...percentminus four percent")+ t = re.sub(r"(?<![\d.])(\d+(?:\.\d+)?)\s?%\s?[-–]\s?(\d+(?:\.\d+)?)\s?%", r"\1-\2%", t)++ # R11 price per unit: ₹500/kg (the "/" was dropped and "kg" left in Latin letters)+ def r11(m):+ unit, per = m.group(2), L.SYM.get("per") or "per"+ if lang != "en" and unit.lower() in _SPELL_UNITS:+ unit = " ".join(L.letter(c) for c in unit.upper())+ return f"{m.group(1)} {per} {unit}"+ t = re.sub(r"((?:[₹$€£]|\b(?:Rs\.?|INR)\s?)\s?\d[\d,]*(?:\.\d+)?)\s?/\s?(kg|km|gm|g|ml|ltr|l|day|month|night|year|person)\b", r11, t,+ flags=re.I)++ # R12 "p.a." (per annum) after a rate was left as the raw token "p.a."+ t = re.sub(r"(?<![\w.])[pP]\.\s?[aA]\.?(?![\w])", lambda m: "per annum" if lang == "en" else f"{L.letter('P')} {L.letter('A')}", t)++ # R7 version strings+ def r7(m):+ parts = m.group(1).split(".")+ dw = _decimal_word(L)+ return f"{L.letter('v')} " + f" {dw} ".join(L.cardinal(int(p)) for p in parts)+ t = re.sub(r"(?<![\w.])[vV](\d+(?:\.\d+){1,3})(?![\w]|\.\d)", r7, t)++ # R4 space-separated digit groups (card / phone numbers): join into one run (>= 10 digits in total)+ def r4(m):+ groups = m.group(0).split()+ return "".join(groups) if sum(len(g) for g in groups) >= 10 else m.group(0)+ t = re.sub(r"(?<![\d,.])(?:\d{4,5}(?: \d{3,5}){1,3}|\d{2,4} \d{3,4} \d{4})(?![\d,]|\.\d)", r4, t)++ # R1 dates with a two-digit year+ def r1(m):+ d, sep, mo, yy = m.group(1), m.group(2), m.group(3), m.group(4)+ if not (1 <= int(d) <= 31 and 1 <= int(mo) <= 12):+ return m.group(0)+ if sep == "-" and len(d) == 1 and len(mo) == 1: # 8-2-45: a door number, not a date+ return m.group(0)+ if _NUMBER_WORD_BEFORE.search(t[max(0, m.start() - 16):m.start()]): # "House No. 12-5-24", "ঘৰ নং ..."+ return m.group(0)+ return f"{d}{sep}{mo}{sep}{_year4(yy)}"+ t = re.sub(r"(?<![\d/.\-])(\d{1,2})([/.\-])(\d{1,2})\2(\d{2})(?![\d/\-]|\.\d)", r1, t)++ # R2 card expiry / month-year next to an expiry, date or CVV word+ def r2(m):+ mo, y = int(m.group(1)), m.group(2)+ before = t[max(0, m.start() - 40):m.start()]+ after = t[m.end():m.end() + 40]+ strong = _EXPIRY_RE.search(before) or re.search(r"\bcvv\b", before + " " + after, re.I)+ weak = _DATE_RE.search(before) and (len(y) == 4 or int(y) > 12) # second part > 12: not DD/MM, so MM/YY+ if not (strong or weak):+ return m.group(0)+ year = int(y) if len(y) == 4 else 2000 + int(y)+ return f"{L.month(mo)} {L.year(year)}"+ t = re.sub(r"(?<![\d/.\-])(0?[1-9]|1[0-2])/(\d{2}|20\d{2})(?![\d/]|\.\d)", r2, t)++ # R3 financial-year ranges 2023-24+ def r3(m):+ y, yy = int(m.group(1)), int(m.group(2))+ if (y + 1) % 100 != yy:+ return m.group(0)+ return f"{L.year(y)} {L.cardinal(yy)}"+ t = re.sub(r"(?<![\d\-])((?:19|20)\d{2})[-–](\d{2})(?![\d\-])", r3, t)++ # R5 PIN keyword + digits+ def r5(m):+ if _tn_id_context(L, t[max(0, m.start(1) - 60):m.start(1)]):+ return m.group(0)+ return m.group(0)[:m.start(1) - m.start(0)] + _digits(L, m.group(1))+ t = _PIN_RE.sub(r5, t)++ # R6 bare six-digit numbers (Indian PIN codes): digit by digit unless an amount / quantity+ def r6(m):+ before = t[max(0, m.start() - 8):m.start()]+ if (_CURRENCY_BEFORE.search(before) or _AMOUNT_AFTER.match(t, m.end())+ or re.search(r"[A-Za-z0-9]\s?-\s?$|[#÷×*/+=<>]\s*$", before) # ID suffix (CUST-567890), #ref, maths+ or re.match(r"\s*[÷×*/+=<>^]", t[m.end():])+ or _tn_id_context(L, re.split(r"[.!?;।॥\n]", t[max(0, m.start() - 60):m.start()])[-1])):+ return m.group(0)+ return _digits(L, m.group(0))+ t = re.sub(r"(?<![\d,.₹$#\w])[1-9]\d{5}(?![\d,]|\.\d|\s*%)", r6, t)++ # R8 Tamil "Month D, YYYY" -> "D Month YYYY"+ if lang == "ta":+ months = "|".join(_TA_MONTHS)+ t = re.sub(rf"(?<!\w)({months})\s+(\d{{1,2}}),?\s+(\d{{4}})(?!\d)", r"\2 \1 \3", t)+ return t+++TAG_COMMA = False # P1 off: no measured gain (6 vs 6 backstop cuts on the 14 affected emotion rows x2 seeds)+++def post(out: str, seg: str, lang: str, before_tag: bool) -> str:+ # P1 keep a trailing comma that precedes an inline [tag] (disabled, see TAG_COMMA)+ if TAG_COMMA and before_tag and seg.rstrip().endswith(",") and out.rstrip().endswith("."):+ out = out.rstrip()[:-1] + ","+ # P2 spoken hyphen inside e-mail / URL in the request language+ uris = [m.group(0) for m in _URI_RE.finditer(seg)]+ if lang in DASH and uris:+ out = re.sub(r"(?<=\s)dash(?=\s)", DASH[lang], out)+ # P3 acronym labels inside e-mail / URL+ labels = {w for u in uris for w in re.findall(r"[a-z]+", re.sub(r"^https?://", "", u))+ if w in _URI_ACRONYMS or w.startswith(_URI_ACR_PREFIX) or w.endswith(_URI_ACR_SUFFIX)}+ if labels:+ try:+ L = _table(lang)+ except Exception:+ return out+ spell = lambda w: " ".join(L.letter(c.upper()) for c in w)++ def p3(m):+ w = m.group(0)+ if w in _URI_ACRONYMS:+ return spell(w)+ for a in _URI_ACR_PREFIX:+ if w.startswith(a) and len(w) - len(a) >= 3:+ return spell(a) + " " + w[len(a):]+ for a in _URI_ACR_SUFFIX:+ if w.endswith(a) and len(w) - len(a) >= 4:+ return w[:-len(a)] + " " + spell(a)+ return w+ out = re.sub(r"(?<![\w.@/])(?:" + "|".join(sorted(map(re.escape, labels), key=len, reverse=True)) + r")(?![\w]|[.@/\-]\w)",+ p3, out)+ return outdiff --git a/maya3/text/tn/__init__.py b/maya3/text/tn/__init__.pynew file mode 100644index 0000000..59563a9--- /dev/null+++ b/maya3/text/tn/__init__.py@@ -0,0 +1,6 @@+"""Vendored text normaliser (upstream commit fe5e6ec).++The modules in this directory are byte-identical copies of the source (see maya3/text/README.md); only this+__init__.py was added so they import as a package. Use maya3.text.normalise_text rather than this package directly.+"""+from .normalize import NormalizationError, normalize, resolve_language # noqa: F401diff --git a/maya3/text/tn/assamese_numbers.py b/maya3/text/tn/assamese_numbers.pynew file mode 100644index 0000000..01da17e--- /dev/null+++ b/maya3/text/tn/assamese_numbers.py@@ -0,0 +1,6 @@+"""Assamese number data from AI4Bharat/indic-numtowords (MIT).+Source: https://github.com/AI4Bharat/indic-numtowords/blob/master/indic_numtowords/asm/data/nums.py+License: assamese_numbers.LICENSE. Data only; the upstream parser is not used.+"""+ONES = ['শূন্য', 'এক', 'দুই', 'তিনি', 'চাৰি', 'পাঁচ', 'ছয়', 'সাত', 'আঠ', 'ন', 'দহ', 'এঘাৰ', 'বাৰ', 'তেৰ', 'চৈধ্য', 'পোন্ধৰ', 'ষোল্ল', 'সোতৰ', 'ওঠৰ', 'ঊনৈশ', 'বিশ', 'একৈশ', 'বাইশ', 'তেইশ', 'চৌবিশ', 'পঁচিশ', 'ছাব্বিশ', 'সাতাইশ', 'আঠাইশ', 'ঊনত্রিশ', 'ত্রিশ', 'একত্রিশ', 'বত্রিশ', 'তেত্রিশ', 'চৌত্রিশ', 'পঁয়ত্রিশ', 'ছয়ত্রিশ', 'সাতত্রিশ', 'আঠত্রিশ', 'ঊনচল্লিশ', 'চল্লিশ', 'একচল্লিশ', 'বিয়াল্লিশ', 'তিয়াল্লিশ', 'চৌচল্লিশ', 'পঁঞ্চল্লিশ', 'ছয়চল্লিশ', 'সাতচল্লিশ', 'আঠচল্লিশ', 'ঊনপঞ্চাশ', 'পঞ্চাশ', 'একাৱন', 'বাৱন', 'তেপন', 'চৌৱন', 'পঁচপন', 'ছাপন', 'সাতাৱন', 'আঠাৱন', 'ঊনষাঠি', 'ষাঠি', 'একষষ্ঠি', 'বাষষ্ঠি', 'তেষষ্ঠি', 'চৌষষ্ঠি', 'পঁয়ষষ্ঠি', 'ছয়ষষ্ঠি', 'সাতষষ্ঠি', 'আঠষষ্ঠি', 'ঊনসত্তৰ', 'সত্তৰ', 'এসত্তৰ', 'বাসত্তৰ', 'তেসত্তৰ', 'চৌসত্তৰ', 'পঁয়সত্তৰ', 'ছয়সত্তৰ', 'সাতসত্তৰ', 'আঠসত্তৰ', 'ঊনাশী', 'আশী', 'একাশী', 'বিৰাশী', 'তিৰাশী', 'চৌৰাশী', 'পঁচাশী', 'ছিয়াশী', 'সাতাশী', 'আঠাশী', 'ঊননব্বৈ', 'নব্বৈ', 'একানব্বৈ', 'বিৰানব্বৈ', 'তিৰানব্বৈ', 'চৌৰানব্বৈ', 'পঁচানব্বৈ', 'ছিয়ানব্বৈ', 'সাতানব্বৈ', 'আঠানব্বৈ', 'নিৰানব্বৈ']+HUNDREDS = ['', 'এশ', 'দুশ', 'তিনিশ', 'চাৰিশ', 'পাঁচশ', 'ছয়শ', 'সাতশ', 'আঠশ', 'নশ']diff --git a/maya3/text/tn/identifier_rules.py b/maya3/text/tn/identifier_rules.pynew file mode 100644index 0000000..943a2c7--- /dev/null+++ b/maya3/text/tn/identifier_rules.py@@ -0,0 +1,85 @@+"""Opt-in identifier rendering; no model calls or prose transliteration.++Uppercase dictionary components prescribe character spelling. In particular,+AXIS is spelled as an identifier rather than guessed as the word 'access'.+Ordinary words stay words; existing locale letter/symbol tables supply sounds.+"""+import json+import re+from functools import lru_cache+from pathlib import Path+++@lru_cache(maxsize=1)+def vocabulary():+ return json.loads(Path(__file__).with_name("identifier_words.json").read_text(encoding="utf-8"))+++def spell_uri(part, lang, spell_digits):+ data = vocabulary()++ def word(token, expand=True):+ if expand and token.lower() in data["brands"]:+ return " ".join(word(p, False) for p in data["brands"][token.lower()])+ if (len(token) == 1 or token.isupper() or token.upper() in data["acronyms"]+ or token.upper() in lang.ABBREV_UNITS):+ return " ".join(lang.letter(c) for c in token)+ pieces = re.findall(r"[A-Z]+(?=[A-Z][a-z]|$)|[A-Z]?[a-z]+|[A-Z]+", token)+ if len(pieces) > 1:+ return " ".join(word(p, False) for p in pieces)+ return token++ symbols = {"@": "at", ".": "dot", "_": "underscore", "-": "minus",+ "/": "slash", "+": "plus", "=": "equals", "&": "amp",+ "#": "hash", "%": "percent"}+ out = []+ # Retain non-ASCII runs intact, including Indic combining marks.+ for token in re.findall(r"[A-Za-z]+|[0-9]+|[@._/\-+?=&#%:~]|[^A-Za-z0-9@._/\-+?=&#%:~]+", part):+ if token.isascii() and token.isalpha():+ out.append(word(token))+ elif token.isdecimal():+ out.append(spell_digits(token, comma=False))+ elif token in symbols:+ out.append(lang.SYM[symbols[token]])+ else:+ out.append({"?": "question mark", ":": "colon", "~": "tilde"}.get(token, token))+ return " ".join(p for p in out if p.strip())+++def group_digits(digits, lang, sizes=None):+ """Spaces inside groups, comma pause between groups; every digit survives."""+ if sizes is None:+ if len(digits) == 16:+ sizes = [4] * 4+ elif len(digits) == 10:+ sizes = [3, 3, 4]+ else:+ sizes = [4] * (len(digits) // 4) + [len(digits) % 4]+ out, start = [], 0+ for size in sizes:+ if size:+ out.append(" ".join(lang.digit(int(c)) for c in digits[start:start + size]))+ start += size+ assert start == len(digits)+ return ", ".join(out)+++# These shapes identify card/telephone numbers even without English keywords.+# Dates and currency retain higher matcher priority in the normalizer.+LONG_RUN = re.compile(+ r"(?<![A-Za-z0-9.,])(?:\+\d{1,3}[ -]+|91[ -]+)?"+ r"(?:\d{4}(?:[ -]\d{4}){3}|\d{5}[ -]\d{5}|\d{3}[ -]\d{3}[ -]\d{4}|\d{4}[ -]\d{7}|\d{8,})"+ r"(?![A-Za-z0-9]|[.,]\d)"+)+++def long_runs(text, lang):+ for match in LONG_RUN.finditer(text):+ token = match.group().lstrip("+")+ groups = re.split(r"[ -]", token)+ digits = "".join(groups)+ sizes = [len(g) for g in groups] if len(groups) > 1 else None+ spoken = group_digits(digits, lang, sizes)+ if match.group().startswith("+"):+ spoken = lang.SYM["plus"] + " " + spoken+ yield match.start(), match.end(), spokendiff --git a/maya3/text/tn/indic_languages.py b/maya3/text/tn/indic_languages.pynew file mode 100644index 0000000..c7d80d7--- /dev/null+++ b/maya3/text/tn/indic_languages.py@@ -0,0 +1,1702 @@+"""Native language tables recovered from MayaTeam/enterprise.++Source: 7384e91b02848ed791060c2eb368d52c9b92203c:gpu-origin/normalize_all.py+Only LangBase subclasses were extracted; the legacy parser was NOT copied.+The review branch also repairs singular units and Hindi irregular ordinals, and+adds explicit Hindi/Telugu month-spelling aliases for calendar validation.+These are inherited candidate lexicons, not independently native-speaker approved.+See docs/NORMALIZATION_REVIEW.md for provenance, limitations and release gates.+"""+if __package__:+ from .normalize import LangBase+else:+ from normalize import LangBase+++class Hindi(LangBase):+ code = "hi"+ name = "Hindi"+ native_digits = "०१२३४५६७८९"+ SINGULAR_NOUNS = {"घंटे": "घंटा", "रुपये": "रुपया", "पैसे": "पैसा"}++ ONES = [+ "शून्य", "एक", "दो", "तीन", "चार", "पाँच", "छह", "सात", "आठ", "नौ",+ "दस", "ग्यारह", "बारह", "तेरह", "चौदह", "पंद्रह", "सोलह", "सत्रह", "अठारह", "उन्नीस",+ "बीस", "इक्कीस", "बाईस", "तेईस", "चौबीस", "पच्चीस", "छब्बीस", "सत्ताईस", "अट्ठाईस", "उनतीस",+ "तीस", "इकतीस", "बत्तीस", "तैंतीस", "चौंतीस", "पैंतीस", "छत्तीस", "सैंतीस", "अड़तीस", "उनतालीस",+ "चालीस", "इकतालीस", "बयालीस", "तैंतालीस", "चौवालीस", "पैंतालीस", "छियालीस", "सैंतालीस", "अड़तालीस", "उनचास",+ "पचास", "इक्यावन", "बावन", "तिरपन", "चौवन", "पचपन", "छप्पन", "सत्तावन", "अट्ठावन", "उनसठ",+ "साठ", "इकसठ", "बासठ", "तिरसठ", "चौंसठ", "पैंसठ", "छियासठ", "सड़सठ", "अड़सठ", "उनहत्तर",+ "सत्तर", "इकहत्तर", "बहत्तर", "तिहत्तर", "चौहत्तर", "पचहत्तर", "छिहत्तर", "सतहत्तर", "अठहत्तर", "उन्यासी",+ "अस्सी", "इक्यासी", "बयासी", "तिरासी", "चौरासी", "पचासी", "छियासी", "सत्तासी", "अठासी", "नवासी",+ "नब्बे", "इक्यानवे", "बानवे", "तिरानवे", "चौरानवे", "पंचानवे", "छियानवे", "सत्तानवे", "अट्ठानवे", "निन्यानवे",+ ]+ HUNDRED = "सौ"+ THOUSAND = "हज़ार"+ LAKH = "लाख"+ CRORE = "करोड़"++ LETTERS = {+ "A": "ए", "B": "बी", "C": "सी", "D": "डी", "E": "ई", "F": "एफ़",+ "G": "जी", "H": "एच", "I": "आई", "J": "जे", "K": "के", "L": "एल",+ "M": "एम", "N": "एन", "O": "ओ", "P": "पी", "Q": "क्यू", "R": "आर",+ "S": "एस", "T": "टी", "U": "यू", "V": "वी", "W": "डब्ल्यू",+ "X": "एक्स", "Y": "वाई", "Z": "ज़ेड",+ }++ MONTHS = ["जनवरी", "फ़रवरी", "मार्च", "अप्रैल", "मई", "जून",+ "जुलाई", "अगस्त", "सितंबर", "अक्टूबर", "नवंबर", "दिसंबर"]+ MONTH_ALIASES = {"फरवरी": 2, "सितम्बर": 9, "नवम्बर": 11, "दिसम्बर": 12}++ SYM = {+ "rupee": "रुपये", "dollar": "डॉलर", "euro": "यूरो", "pound": "पाउंड",+ "cent": "सेंट", "paisa": "पैसे",+ "percent": "प्रतिशत",+ "point": "दशमलव",+ "minus": "माइनस", "plus": "प्लस", "equals": "बराबर",+ "times": "गुणा", "divide": "भाग",+ "squared": "का वर्ग", "sqrt": "वर्गमूल",+ "lt": "से कम", "gt": "से ज़्यादा",+ "plus_minus": "धन-ऋण",+ "at": "एट द रेट", "underscore": "अंडरस्कोर", "dot": "डॉट",+ "slash": "स्लैश", "hash": "हैश", "amp": "और",+ "half": "आधा", "quarter": "चौथाई", "three_quarters": "तीन चौथाई",+ "degree": "डिग्री", "celsius": "डिग्री सेल्सियस", "fahrenheit": "डिग्री फ़ारेनहाइट",+ "minute": "मिनट", "second": "सेकंड", "per": "प्रति",+ }++ TIME_ON_HOUR = "{h} बजे"+ TIME_HM = "{h} बजकर {m} मिनट"+ RANGE = "{a} से {b}"+ RANGE_TO = "{a} से {b} तक"+ RATIO = "{a} अनुपात {b}"+ POWER = "{base} की घात {exp}"+ FRACTION = "{num} बटा {den}"+ DECADE_SHORT = "{tens} के"+ DECADE_FULL = "{tens} का दशक"++ PERIODS = {"morning": "सुबह", "afternoon": "दोपहर", "evening": "शाम", "night": "रात"}++ TIME_MARKERS = ["बजे", "बजकर"]+ PERIOD_DETECT = {"सुबह": "morning", "दोपहर": "afternoon", "शाम": "evening",+ "रात": "night", "सवेरे": "morning"}+ YEAR_WORDS = ["साल", "वर्ष", "सन्", "सन"]+ ID_KEYWORDS = ["नंबर", "नम्बर", "खाता", "खाते", "कोड", "ऑर्डर", "फ़ोन", "फोन", "मोबाइल"]+ LABEL_WORDS = ["अनुच्छेद", "धारा", "कमरा", "कक्षा", "वार्ड", "अध्याय", "भाग"]+ ID_AFTER_WORDS = ["खत्म", "डायल", "कॉल", "संपर्क"]+ NUMBER_WORD = "नंबर"+ ABBREV_UNITS = {"MINS": "मिनट", "HRS": "घंटे", "SECS": "सेकंड",+ "KMS": "किलोमीटर"}+ MINUTE_WORDS = ["मिनट"]+ SCALE_WORDS = {"करोड़": "crore", "लाख": "lakh", "हज़ार": "thousand", "हजार": "thousand",+ "अरब": "arab"}+ CURRENCY_WORDS = {"रुपये": "rupee", "रुपए": "rupee", "रुपया": "rupee"}++ ORDINAL_EXCEPTIONS = {1: "पहला", 2: "दूसरा", 3: "तीसरा", 4: "चौथा", 6: "छठा"}+ ORDINAL_SUFFIX = "वाँ"+ ORDINAL_INPUT_SUFFIXES = ["वीं", "वाँ", "वां", "वें", "वे"]++ def _ordinal_compose(self, n, src_suffix):+ # 12वीं -> बारहवीं : cardinal + preserved suffix+ if src_suffix:+ if n in self.ORDINAL_EXCEPTIONS:+ # Irregular stems retain gender/case: 1वीं -> पहली, not एकवीं.+ ending = {"वीं": "ी", "वें": "े", "वे": "े"}.get(src_suffix, "ा")+ return self.ORDINAL_EXCEPTIONS[n][:-1] + ending+ return f"{self.cardinal(n)}{src_suffix}"+ if n in self.ORDINAL_EXCEPTIONS:+ return self.ORDINAL_EXCEPTIONS[n]+ return f"{self.cardinal(n)}{self.ORDINAL_SUFFIX}"+++class Bengali(LangBase):+ code = "bn"+ name = "Bengali"+ native_digits = "০১২৩৪৫৬৭৮৯"++ ONES = [+ "শূন্য", "এক", "দুই", "তিন", "চার", "পাঁচ", "ছয়", "সাত", "আট", "নয়",+ "দশ", "এগারো", "বারো", "তেরো", "চৌদ্দ", "পনেরো", "ষোলো", "সতেরো", "আঠারো", "উনিশ",+ "বিশ", "একুশ", "বাইশ", "তেইশ", "চব্বিশ", "পঁচিশ", "ছাব্বিশ", "সাতাশ", "আঠাশ", "ঊনত্রিশ",+ "ত্রিশ", "একত্রিশ", "বত্রিশ", "তেত্রিশ", "চৌত্রিশ", "পঁয়ত্রিশ", "ছত্রিশ", "সাঁইত্রিশ", "আটত্রিশ", "ঊনচল্লিশ",+ "চল্লিশ", "একচল্লিশ", "বিয়াল্লিশ", "তেতাল্লিশ", "চুয়াল্লিশ", "পঁয়তাল্লিশ", "ছেচল্লিশ", "সাতচল্লিশ", "আটচল্লিশ", "ঊনপঞ্চাশ",+ "পঞ্চাশ", "একান্ন", "বায়ান্ন", "তিপ্পান্ন", "চুয়ান্ন", "পঞ্চান্ন", "ছাপ্পান্ন", "সাতান্ন", "আটান্ন", "ঊনষাট",+ "ষাট", "একষট্টি", "বাষট্টি", "তেষট্টি", "চৌষট্টি", "পঁয়ষট্টি", "ছেষট্টি", "সাতষট্টি", "আটষট্টি", "ঊনসত্তর",+ "সত্তর", "একাত্তর", "বাহাত্তর", "তিয়াত্তর", "চুয়াত্তর", "পঁচাত্তর", "ছিয়াত্তর", "সাতাত্তর", "আটাত্তর", "ঊনআশি",+ "আশি", "একাশি", "বিরাশি", "তিরাশি", "চুরাশি", "পঁচাশি", "ছিয়াশি", "সাতাশি", "আটাশি", "ঊননব্বই",+ "নব্বই", "একানব্বই", "বিরানব্বই", "তিরানব্বই", "চুরানব্বই", "পঁচানব্বই", "ছিয়ানব্বই", "সাতানব্বই", "আটানব্বই", "নিরানব্বই",+ ]+ HUNDRED = "শো"+ THOUSAND = "হাজার"+ LAKH = "লাখ"+ CRORE = "কোটি"++ LETTERS = {+ "A": "এ", "B": "বি", "C": "সি", "D": "ডি", "E": "ই", "F": "এফ",+ "G": "জি", "H": "এইচ", "I": "আই", "J": "জে", "K": "কে", "L": "এল",+ "M": "এম", "N": "এন", "O": "ও", "P": "পি", "Q": "কিউ", "R": "আর",+ "S": "এস", "T": "টি", "U": "ইউ", "V": "ভি", "W": "ডব্লিউ",+ "X": "এক্স", "Y": "ওয়াই", "Z": "জেড",+ }++ MONTHS = ["জানুয়ারি", "ফেব্রুয়ারি", "মার্চ", "এপ্রিল", "মে", "জুন",+ "জুলাই", "আগস্ট", "সেপ্টেম্বর", "অক্টোবর", "নভেম্বর", "ডিসেম্বর"]++ SYM = {+ "rupee": "টাকা", "dollar": "ডলার", "euro": "ইউরো", "pound": "পাউন্ড",+ "cent": "সেন্ট",+ "percent": "শতাংশ",+ "point": "দশমিক",+ "minus": "মাইনাস", "plus": "প্লাস", "equals": "সমান",+ "times": "গুণ", "divide": "ভাগ",+ "squared": "এর বর্গ", "sqrt": "বর্গমূল",+ "lt": "এর চেয়ে কম", "gt": "এর চেয়ে বেশি",+ "plus_minus": "প্লাস-মাইনাস",+ "at": "অ্যাট দ্য রেট", "underscore": "আন্ডারস্কোর", "dot": "ডট",+ "slash": "স্ল্যাশ", "hash": "হ্যাশ", "amp": "অ্যান্ড",+ "half": "অর্ধেক", "quarter": "এক চতুর্থাংশ", "three_quarters": "তিন চতুর্থাংশ",+ "degree": "ডিগ্রি", "celsius": "ডিগ্রি সেলসিয়াস", "fahrenheit": "ডিগ্রি ফারেনহাইট",+ "minute": "মিনিট", "second": "সেকেন্ড",+ }++ TIME_ON_HOUR = "{h}টা"+ TIME_HM = "{h}টা বেজে {m} মিনিট"+ RANGE = "{a} থেকে {b}"+ RANGE_TO = "{a} থেকে {b} পর্যন্ত"+ RATIO = "{a} অনুপাত {b}"+ POWER = "{base} এর ঘাত {exp}"+ FRACTION = "{num} বাই {den}"+ DECADE_SHORT = "{tens} এর দশক"+ DECADE_FULL = "{tens} এর দশক"++ PERIODS = {"morning": "সকাল", "afternoon": "দুপুর",+ "evening": "সন্ধ্যা", "night": "রাত"}++ TIME_MARKERS = ["টা", "টায়", "টার", "বেজে", "বাজে", "বাজবে"]+ PERIOD_DETECT = {"সকাল": "morning", "সকালে": "morning",+ "ভোর": "morning", "ভোরে": "morning",+ "দুপুর": "afternoon", "দুপুরে": "afternoon",+ "বিকেল": "evening", "বিকেলে": "evening", "বিকাল": "evening",+ "সন্ধ্যা": "evening", "সন্ধ্যায়": "evening",+ "রাত": "night", "রাতে": "night"}+ YEAR_WORDS = ["সাল", "সালে", "সালের", "সন", "বছর", "বছরে"]+ ID_KEYWORDS = ["নম্বর", "নাম্বার", "অ্যাকাউন্ট", "একাউন্ট", "কোড", "অর্ডার", "ফোন", "মোবাইল", "ওটিপি", "পিন", "আইডি", "পাসওয়ার্ড", "ট্রেন", "এক্সপ্রেস", "পিএনআর", "কার্ড", "রেফারেন্স", "ট্রানজেকশন", "টিকিট", "অ্যাকাউন্টের", "নম্বরে", "আইডিতে", "ইউজার", "ইনস্টলমেন্ট", "কিস্তি", "ডিজিট", "অঙ্ক", "লেনদেন"]+ ID_AFTER_WORDS = ["ডায়াল", "কল", "যোগাযোগ"]+ NUMBER_WORD = "নম্বর"+ ABBREV_UNITS = {"MINS":"মিনিট", "MIN":"মিনিট", "HRS":"ঘণ্টা", "HR":"ঘণ্টা", "SECS":"সেকেন্ড", "SEC":"সেকেন্ড", "KMS":"কিলোমিটার"}+ LABEL_WORDS = ["অনুচ্ছেদ", "ধারা", "রুম", "ঘর", "কক্ষ", "ওয়ার্ড",+ "অধ্যায়", "গেট", "কাউন্টার"]+ MINUTE_WORDS = ["মিনিট"]+ SCALE_WORDS = {"কোটি": "crore", "লাখ": "lakh", "লক্ষ": "lakh",+ "হাজার": "thousand"}+ CURRENCY_WORDS = {"টাকা": "rupee", "টাকার": "rupee", "টাকায়": "rupee",+ "রুপি": "rupee"}++ ORDINAL_EXCEPTIONS = {1: "প্রথম", 2: "দ্বিতীয়", 3: "তৃতীয়", 4: "চতুর্থ",+ 5: "পঞ্চম", 6: "ষষ্ঠ", 7: "সপ্তম", 8: "অষ্টম",+ 9: "নবম", 10: "দশম"}+ ORDINAL_SUFFIX = "তম"+ ORDINAL_INPUT_SUFFIXES = ["তম", "লা", "রা", "ঠা", "ই", "শে"]++ # Bengali date-of-month ordinals for ১লা / ২রা / ৩রা / ৪ঠা+ _DATE_ORDINALS = {1: "পহেলা", 2: "দোসরা", 3: "তেসরা", 4: "চৌঠা"}++ # ------------------------------------------------------------------+ # Hundreds fuse: এক+শো -> একশো, চার+শো -> চারশো (written solid).+ # ------------------------------------------------------------------+ def hundreds(self, h, rest):+ out = f"{self.ONES[h]}{self.HUNDRED}"+ if rest:+ out += f" {self.two_digit(rest)}"+ return out++ def year(self, y):+ """1947 -> উনিশশো সাতচল্লিশ (fused শো); 2026 -> দুই হাজার ছাব্বিশ."""+ if 1100 <= y <= 1999:+ hi, lo = divmod(y, 100)+ out = f"{self.two_digit(hi)}{self.HUNDRED}"+ if lo:+ out += f" {self.two_digit(lo)}"+ return out+ return self.cardinal(y)++ def _ordinal_compose(self, n, src_suffix):+ # Date-style ordinals: ১লা -> পহেলা, ২রা -> দোসরা, ৪ঠা -> চৌঠা,+ # ৫ই -> পাঁচই, ১৯শে -> উনিশে. General: ১২তম -> বারোতম.+ if src_suffix in ("লা", "রা", "ঠা") and n in self._DATE_ORDINALS:+ return self._DATE_ORDINALS[n]+ if src_suffix == "ই":+ return f"{self.cardinal(n)}ই"+ if src_suffix == "শে":+ return f"{self.cardinal(n)}ে"+ if src_suffix == "তম":+ return f"{self.cardinal(n)}তম"+ if n in self.ORDINAL_EXCEPTIONS:+ return self.ORDINAL_EXCEPTIONS[n]+ return f"{self.cardinal(n)}{self.ORDINAL_SUFFIX}"++ # postpositions attach to noun-words with Bengali sandhi+ # (টাকা+এর->টাকার, শতাংশ+এ->শতাংশে, টা+মধ্যে->টার মধ্যে)+ _ATTACH_NOUNS = {"টাকা", "পয়সা", "ডলার", "শতাংশ", "কিলোমিটার",+ "কিলোগ্রাম", "মিটার", "লিটার", "গ্রাম", "ডিগ্রি",+ "মিনিট", "সেকেন্ড", "টা", "টো"}++ def attach_postposition(self, rep, tok):+ t = tok.lstrip("-")+ last = rep.rsplit(" ", 1)[-1]+ if last not in self._ATTACH_NOUNS:+ return None+ if t == last:+ return rep # duplicate marker+ if t in ("এ", "তে", "য়"): # locative+ if last.endswith(("া","ো","ে")):+ return rep + "য়" # টাকায়, এগারোটায়+ return rep + "ে" # শতাংশে, মিনিটে+ if t in ("এর", "র"): # genitive+ if last.endswith(("া","ো","ে")):+ return rep + "র" # টাকার, টার+ return rep + "ের" # মিনিটের+ if t in ("মধ্যে", "নাগাদ", "থেকে", "পর্যন্ত", "দিয়ে"):+ g = rep + ("র" if last.endswith(("া","ো","ে")) else "ের")+ return g + " " + t # এগারোটার মধ্যে+ return None+++class Gujarati(LangBase):+ code = "gu"+ name = "Gujarati"+ native_digits = "૦૧૨૩૪૫૬૭૮૯"++ ONES = [+ "શૂન્ય", "એક", "બે", "ત્રણ", "ચાર", "પાંચ", "છ", "સાત", "આઠ", "નવ",+ "દસ", "અગિયાર", "બાર", "તેર", "ચૌદ", "પંદર", "સોળ", "સત્તર", "અઢાર", "ઓગણીસ",+ "વીસ", "એકવીસ", "બાવીસ", "ત્રેવીસ", "ચોવીસ", "પચ્ચીસ", "છવ્વીસ", "સત્તાવીસ", "અઠ્ઠાવીસ", "ઓગણત્રીસ",+ "ત્રીસ", "એકત્રીસ", "બત્રીસ", "તેત્રીસ", "ચોત્રીસ", "પાંત્રીસ", "છત્રીસ", "સાડત્રીસ", "આડત્રીસ", "ઓગણચાળીસ",+ "ચાળીસ", "એકતાળીસ", "બેતાળીસ", "તેંતાળીસ", "ચુંમાળીસ", "પિસ્તાળીસ", "છેંતાળીસ", "સુડતાળીસ", "અડતાળીસ", "ઓગણપચાસ",+ "પચાસ", "એકાવન", "બાવન", "ત્રેપન", "ચોપન", "પંચાવન", "છપ્પન", "સત્તાવન", "અઠ્ઠાવન", "ઓગણસાઠ",+ "સાઠ", "એકસઠ", "બાસઠ", "ત્રેસઠ", "ચોસઠ", "પાંસઠ", "છાસઠ", "સડસઠ", "અડસઠ", "અગણોસિત્તેર",+ "સિત્તેર", "એકોતેર", "બોતેર", "તોંતેર", "ચુંમોતેર", "પંચોતેર", "છોતેર", "સિત્તોતેર", "અઠ્ઠોતેર", "ઓગણએંસી",+ "એંસી", "એક્યાસી", "બ્યાસી", "ત્યાસી", "ચોરાસી", "પંચાસી", "છયાસી", "સત્યાસી", "અઠયાસી", "નેવ્યાસી",+ "નેવું", "એકાણું", "બાણું", "ત્રાણું", "ચોરાણું", "પંચાણું", "છન્નું", "સત્તાણું", "અઠ્ઠાણું", "નવ્વાણું",+ ]+ HUNDRED = "સો"+ THOUSAND = "હજાર"+ LAKH = "લાખ"+ CRORE = "કરોડ"++ # Gujarati hundreds are fused compounds (200 = બસો, not "બે સો").+ HUNDREDS_FUSED = {+ 1: "એકસો", 2: "બસો", 3: "ત્રણસો", 4: "ચારસો", 5: "પાંચસો",+ 6: "છસો", 7: "સાતસો", 8: "આઠસો", 9: "નવસો",+ }++ LETTERS = {+ "A": "એ", "B": "બી", "C": "સી", "D": "ડી", "E": "ઈ", "F": "એફ",+ "G": "જી", "H": "એચ", "I": "આઈ", "J": "જે", "K": "કે", "L": "એલ",+ "M": "એમ", "N": "એન", "O": "ઓ", "P": "પી", "Q": "ક્યુ", "R": "આર",+ "S": "એસ", "T": "ટી", "U": "યુ", "V": "વી", "W": "ડબલ્યુ",+ "X": "એક્સ", "Y": "વાય", "Z": "ઝેડ",+ }++ MONTHS = ["જાન્યુઆરી", "ફેબ્રુઆરી", "માર્ચ", "એપ્રિલ", "મે", "જૂન",+ "જુલાઈ", "ઓગસ્ટ", "સપ્ટેમ્બર", "ઓક્ટોબર", "નવેમ્બર", "ડિસેમ્બર"]++ SYM = {+ "rupee": "રૂપિયા", "dollar": "ડોલર", "euro": "યુરો", "pound": "પાઉન્ડ",+ "cent": "સેન્ટ",+ "percent": "ટકા",+ "point": "દશાંશ",+ "minus": "માઇનસ", "plus": "પ્લસ", "equals": "બરાબર",+ "times": "ગુણ્યા", "divide": "ભાગ્યા",+ "squared": "નો વર્ગ", "sqrt": "વર્ગમૂળ",+ "lt": "થી ઓછું", "gt": "થી વધારે",+ "plus_minus": "વત્તા-ઓછા",+ "at": "એટ ધ રેટ", "underscore": "અન્ડરસ્કોર", "dot": "ડોટ",+ "slash": "સ્લેશ", "hash": "હેશ", "amp": "અને",+ "half": "અડધો", "quarter": "પા", "three_quarters": "પોણો",+ "degree": "ડિગ્રી", "celsius": "ડિગ્રી સેલ્સિયસ", "fahrenheit": "ડિગ્રી ફેરનહીટ",+ "minute": "મિનિટ", "second": "સેકન્ડ",+ }++ TIME_ON_HOUR = "{h} વાગ્યે"+ TIME_HM = "{h} વાગીને {m} મિનિટ"+ RANGE = "{a} થી {b}"+ RANGE_TO = "{a} થી {b} સુધી"+ RATIO = "{a} ગુણોત્તર {b}"+ POWER = "{base} ની ઘાત {exp}"+ FRACTION = "{num} બટા {den}"+ DECADE_SHORT = "{tens} ના"+ DECADE_FULL = "{tens} નો દાયકો"++ PERIODS = {"morning": "સવારે", "afternoon": "બપોરે",+ "evening": "સાંજે", "night": "રાત્રે"}++ TIME_MARKERS = ["વાગ્યે", "વાગે", "વાગ્યા", "વાગ્યું", "વાગીને", "કલાકે"]+ PERIOD_DETECT = {"સવારે": "morning", "સવાર": "morning", "સવારના": "morning",+ "બપોરે": "afternoon", "બપોર": "afternoon", "બપોરના": "afternoon",+ "સાંજે": "evening", "સાંજ": "evening", "સાંજના": "evening",+ "રાત્રે": "night", "રાતે": "night", "રાત": "night", "રાતના": "night"}+ YEAR_WORDS = ["વર્ષ", "વર્ષે", "સાલ", "સન", "સને"]+ ID_KEYWORDS = ["નંબર", "નમ્બર", "ખાતા", "ખાતું", "ખાતાં", "કોડ", "ઓર્ડર", "ફોન", "મોબાઇલ", "મોબાઈલ", "એકાઉન્ટ", "એકાઉન્ટમાં", "એકાઉન્ટનો", "પિન", "આઈડી", "પાસવર્ડ", "ટ્રેન", "એક્સપ્રેસ", "પીએનઆર", "કાર્ડ", "રેફરન્સ", "ટ્રાન્ઝેક્શન", "ટિકિટ", "ઓટીપી", "નંબરમાં", "યુઝર", "હપ્તો", "અંક", "ડિજિટ"]+ ID_AFTER_WORDS = ["ડાયલ", "કૉલ", "સંપર્ક"]+ NUMBER_WORD = "નંબર"+ ABBREV_UNITS = {"MINS":"મિનિટ", "MIN":"મિનિટ", "HRS":"કલાક", "HR":"કલાક", "SECS":"સેકન્ડ", "SEC":"સેકન્ડ", "KMS":"કિલોમીટર"}+ LABEL_WORDS = ["અનુચ્છેદ", "કલમ", "ઓરડો", "રૂમ", "વોર્ડ", "ધોરણ",+ "પ્રકરણ", "ભાગ", "વર્ગ"]+ MINUTE_WORDS = ["મિનિટ", "મિનીટ"]+ SCALE_WORDS = {"કરોડ": "crore", "લાખ": "lakh", "હજાર": "thousand",+ "અબજ": "arab"}+ CURRENCY_WORDS = {"રૂપિયા": "rupee", "રૂપિયો": "rupee", "રૂપિયે": "rupee",+ "રૂ": "rupee"}++ ORDINAL_EXCEPTIONS = {1: "પહેલો", 2: "બીજો", 3: "ત્રીજો", 4: "ચોથો", 6: "છઠ્ઠો"}+ # Stems for gender/case agreement with a source suffix (1લી -> પહેલી).+ ORDINAL_STEMS = {1: "પહેલ", 2: "બીજ", 3: "ત્રીજ", 4: "ચોથ", 6: "છઠ્ઠ"}+ ORDINAL_SUFFIX = "મો"+ ORDINAL_INPUT_SUFFIXES = ["મી", "મો", "મું", "મા", "મે",+ "લી", "લો", "લું", "લા",+ "જી", "જો", "જું", "જા",+ "થી", "થો", "થું", "થા"]++ # ------------------------------------------------------------------+ # Gujarati-specific composition+ # ------------------------------------------------------------------++ def hundreds(self, h, rest):+ """Fused hundreds: 250 -> 'બસો પચાસ', 147 -> 'એકસો સુડતાળીસ'."""+ out = self.HUNDREDS_FUSED[h]+ if rest:+ out += f" {self.two_digit(rest)}"+ return out++ def year(self, y):+ """1100-1999: fused hundred style — 1947 -> 'ઓગણીસો સુડતાળીસ',+ 1857 -> 'અઢારસો સત્તાવન'. A trailing સ merges with સો+ (ઓગણીસ + સો -> ઓગણીસો). Everything else: full cardinal."""+ if 1100 <= y <= 1999:+ hi, lo = divmod(y, 100)+ w = self.two_digit(hi)+ w = w[:-1] + self.HUNDRED if w.endswith("સ") else w + self.HUNDRED+ if lo:+ return f"{w} {self.two_digit(lo)}"+ return w+ return self.cardinal(y)++ def _ordinal_compose(self, n, src_suffix):+ # 1-4, 6 have suppletive stems: 1લી -> પહેલી, 2જી -> બીજી, 4થા -> ચોથા.+ if n in self.ORDINAL_STEMS:+ if src_suffix and len(src_suffix) > 1:+ return self.ORDINAL_STEMS[n] + src_suffix[1:]+ return self.ORDINAL_EXCEPTIONS[n]+ # Regular: cardinal + મ-suffix (12મી -> બારમી, 5મો -> પાંચમો).+ if src_suffix and src_suffix.startswith("મ"):+ return f"{self.cardinal(n)}{src_suffix}"+ return f"{self.cardinal(n)}{self.ORDINAL_SUFFIX}"++ # Gujarati postpositions agglutinate directly onto the preceding word+ # (રૂપિયા + માં -> રૂપિયામાં). Oblique of the plural currency word before+ # a genitive: રૂપિયા stays (already the citation form here).+ _PP = {"માં", "માંથી", "નું", "નો", "ની", "ના", "ને", "થી", "સુધી",+ "પર", "પરથી", "વડે", "કરતાં", "જેટલા", "જેટલું"}++ # attach postpositions only to noun-words we insert (currency/unit/+ # percent), never to a bare cardinal (Terminal બે + પર stays "બે પર")+ _ATTACH_NOUNS = {"રૂપિયા", "પૈસા", "ડોલર", "ટકા", "ટકાવારી",+ "કિલોમીટર", "કિલોગ્રામ", "મીટર", "લિટર", "ગ્રામ",+ "ડિગ્રી", "કલાક", "મિનિટ", "સેકન્ડ"}++ def attach_postposition(self, rep, tok):+ t = tok.lstrip("-")+ last = rep.rsplit(" ", 1)[-1]+ if t == last and last in self._ATTACH_NOUNS:+ return rep+ if t in self._PP and last in self._ATTACH_NOUNS:+ return rep + t+ return None+++class Kannada(LangBase):+ code = "kn"+ name = "Kannada"+ native_digits = "೦೧೨೩೪೫೬೭೮೯"++ ONES = [+ "ಸೊನ್ನೆ", "ಒಂದು", "ಎರಡು", "ಮೂರು", "ನಾಲ್ಕು", "ಐದು", "ಆರು", "ಏಳು", "ಎಂಟು", "ಒಂಬತ್ತು",+ "ಹತ್ತು", "ಹನ್ನೊಂದು", "ಹನ್ನೆರಡು", "ಹದಿಮೂರು", "ಹದಿನಾಲ್ಕು", "ಹದಿನೈದು", "ಹದಿನಾರು", "ಹದಿನೇಳು", "ಹದಿನೆಂಟು", "ಹತ್ತೊಂಬತ್ತು",+ "ಇಪ್ಪತ್ತು", "ಇಪ್ಪತ್ತೊಂದು", "ಇಪ್ಪತ್ತೆರಡು", "ಇಪ್ಪತ್ತಮೂರು", "ಇಪ್ಪತ್ತನಾಲ್ಕು", "ಇಪ್ಪತ್ತೈದು", "ಇಪ್ಪತ್ತಾರು", "ಇಪ್ಪತ್ತೇಳು", "ಇಪ್ಪತ್ತೆಂಟು", "ಇಪ್ಪತ್ತೊಂಬತ್ತು",+ "ಮೂವತ್ತು", "ಮೂವತ್ತೊಂದು", "ಮೂವತ್ತೆರಡು", "ಮೂವತ್ತಮೂರು", "ಮೂವತ್ತನಾಲ್ಕು", "ಮೂವತ್ತೈದು", "ಮೂವತ್ತಾರು", "ಮೂವತ್ತೇಳು", "ಮೂವತ್ತೆಂಟು", "ಮೂವತ್ತೊಂಬತ್ತು",+ "ನಲವತ್ತು", "ನಲವತ್ತೊಂದು", "ನಲವತ್ತೆರಡು", "ನಲವತ್ತಮೂರು", "ನಲವತ್ತನಾಲ್ಕು", "ನಲವತ್ತೈದು", "ನಲವತ್ತಾರು", "ನಲವತ್ತೇಳು", "ನಲವತ್ತೆಂಟು", "ನಲವತ್ತೊಂಬತ್ತು",+ "ಐವತ್ತು", "ಐವತ್ತೊಂದು", "ಐವತ್ತೆರಡು", "ಐವತ್ತಮೂರು", "ಐವತ್ತನಾಲ್ಕು", "ಐವತ್ತೈದು", "ಐವತ್ತಾರು", "ಐವತ್ತೇಳು", "ಐವತ್ತೆಂಟು", "ಐವತ್ತೊಂಬತ್ತು",+ "ಅರವತ್ತು", "ಅರವತ್ತೊಂದು", "ಅರವತ್ತೆರಡು", "ಅರವತ್ತಮೂರು", "ಅರವತ್ತನಾಲ್ಕು", "ಅರವತ್ತೈದು", "ಅರವತ್ತಾರು", "ಅರವತ್ತೇಳು", "ಅರವತ್ತೆಂಟು", "ಅರವತ್ತೊಂಬತ್ತು",+ "ಎಪ್ಪತ್ತು", "ಎಪ್ಪತ್ತೊಂದು", "ಎಪ್ಪತ್ತೆರಡು", "ಎಪ್ಪತ್ತಮೂರು", "ಎಪ್ಪತ್ತನಾಲ್ಕು", "ಎಪ್ಪತ್ತೈದು", "ಎಪ್ಪತ್ತಾರು", "ಎಪ್ಪತ್ತೇಳು", "ಎಪ್ಪತ್ತೆಂಟು", "ಎಪ್ಪತ್ತೊಂಬತ್ತು",+ "ಎಂಬತ್ತು", "ಎಂಬತ್ತೊಂದು", "ಎಂಬತ್ತೆರಡು", "ಎಂಬತ್ತಮೂರು", "ಎಂಬತ್ತನಾಲ್ಕು", "ಎಂಬತ್ತೈದು", "ಎಂಬತ್ತಾರು", "ಎಂಬತ್ತೇಳು", "ಎಂಬತ್ತೆಂಟು", "ಎಂಬತ್ತೊಂಬತ್ತು",+ "ತೊಂಬತ್ತು", "ತೊಂಬತ್ತೊಂದು", "ತೊಂಬತ್ತೆರಡು", "ತೊಂಬತ್ತಮೂರು", "ತೊಂಬತ್ತನಾಲ್ಕು", "ತೊಂಬತ್ತೈದು", "ತೊಂಬತ್ತಾರು", "ತೊಂಬತ್ತೇಳು", "ತೊಂಬತ್ತೆಂಟು", "ತೊಂಬತ್ತೊಂಬತ್ತು",+ ]+ HUNDRED = "ನೂರು"+ THOUSAND = "ಸಾವಿರ"+ LAKH = "ಲಕ್ಷ"+ CRORE = "ಕೋಟಿ"++ # Fused hundreds (standalone) and their combining (oblique) forms used+ # when a 0-99 remainder follows: 147 -> ನೂರ ನಲವತ್ತೇಳು.+ HUNDREDS = ["", "ನೂರು", "ಇನ್ನೂರು", "ಮುನ್ನೂರು", "ನಾನೂರು", "ಐನೂರು",+ "ಆರುನೂರು", "ಏಳುನೂರು", "ಎಂಟುನೂರು", "ಒಂಬೈನೂರು"]+ HUNDREDS_COMB = ["", "ನೂರ", "ಇನ್ನೂರ", "ಮುನ್ನೂರ", "ನಾನೂರ", "ಐನೂರ",+ "ಆರುನೂರ", "ಏಳುನೂರ", "ಎಂಟುನೂರ", "ಒಂಬೈನೂರ"]+ THOUSAND_COMB = "ಸಾವಿರದ"+ LAKH_COMB = "ಲಕ್ಷದ"++ LETTERS = {+ "A": "ಎ", "B": "ಬಿ", "C": "ಸಿ", "D": "ಡಿ", "E": "ಇ", "F": "ಎಫ್",+ "G": "ಜಿ", "H": "ಎಚ್", "I": "ಐ", "J": "ಜೆ", "K": "ಕೆ", "L": "ಎಲ್",+ "M": "ಎಂ", "N": "ಎನ್", "O": "ಒ", "P": "ಪಿ", "Q": "ಕ್ಯೂ", "R": "ಆರ್",+ "S": "ಎಸ್", "T": "ಟಿ", "U": "ಯು", "V": "ವಿ", "W": "ಡಬ್ಲ್ಯೂ",+ "X": "ಎಕ್ಸ್", "Y": "ವೈ", "Z": "ಝಡ್",+ }++ MONTHS = ["ಜನವರಿ", "ಫೆಬ್ರವರಿ", "ಮಾರ್ಚ್", "ಏಪ್ರಿಲ್", "ಮೇ", "ಜೂನ್",+ "ಜುಲೈ", "ಆಗಸ್ಟ್", "ಸೆಪ್ಟೆಂಬರ್", "ಅಕ್ಟೋಬರ್", "ನವೆಂಬರ್", "ಡಿಸೆಂಬರ್"]++ SYM = {+ "rupee": "ರೂಪಾಯಿ", "dollar": "ಡಾಲರ್", "euro": "ಯೂರೋ", "pound": "ಪೌಂಡ್",+ "cent": "ಸೆಂಟ್",+ "percent": "ಪ್ರತಿಶತ",+ "point": "ದಶಮಾಂಶ",+ "minus": "ಮೈನಸ್", "plus": "ಪ್ಲಸ್", "equals": "ಸಮ",+ "times": "ಗುಣಿಸು", "divide": "ಭಾಗಿಸು",+ "squared": "ವರ್ಗ", "sqrt": "ವರ್ಗಮೂಲ",+ "lt": "ಗಿಂತ ಕಡಿಮೆ", "gt": "ಗಿಂತ ಹೆಚ್ಚು",+ "plus_minus": "ಪ್ಲಸ್ ಮೈನಸ್",+ "at": "ಅಟ್ ದಿ ರೇಟ್", "underscore": "ಅಂಡರ್ಸ್ಕೋರ್", "dot": "ಡಾಟ್",+ "slash": "ಸ್ಲ್ಯಾಶ್", "hash": "ಹ್ಯಾಶ್", "amp": "ಮತ್ತು",+ "half": "ಅರ್ಧ", "quarter": "ಕಾಲು", "three_quarters": "ಮುಕ್ಕಾಲು",+ "degree": "ಡಿಗ್ರಿ", "celsius": "ಡಿಗ್ರಿ ಸೆಲ್ಸಿಯಸ್", "fahrenheit": "ಡಿಗ್ರಿ ಫ್ಯಾರನ್ಹೀಟ್",+ "minute": "ನಿಮಿಷ", "second": "ಸೆಕೆಂಡ್",+ }++ TIME_ON_HOUR = "{h} ಗಂಟೆ"+ TIME_HM = "{h} ಗಂಟೆ {m} ನಿಮಿಷ"+ RANGE = "{a} ರಿಂದ {b}"+ RANGE_TO = "{a} ರಿಂದ {b} ವರೆಗೆ"+ RATIO = "{a} ಅನುಪಾತ {b}"+ POWER = "{base} ಘಾತ {exp}"+ FRACTION = "{num} ಬೈ {den}"+ DECADE_SHORT = "{tens}ರ" # decade() passes the ು-stripped stem+ DECADE_FULL = "{tens}ರ ದಶಕ"++ PERIODS = {"morning": "ಬೆಳಿಗ್ಗೆ", "afternoon": "ಮಧ್ಯಾಹ್ನ",+ "evening": "ಸಂಜೆ", "night": "ರಾತ್ರಿ"}++ TIME_MARKERS = ["ಗಂಟೆಗೆ", "ಗಂಟೆಯ", "ಗಂಟೆ"]+ MARKER_SUFFIXES = {"ಗಂಟೆಗೆ": "ಗೆ"}+ PERIOD_DETECT = {"ಬೆಳಿಗ್ಗೆ": "morning", "ಬೆಳಗ್ಗೆ": "morning",+ "ಮುಂಜಾನೆ": "morning", "ಮಧ್ಯಾಹ್ನ": "afternoon",+ "ಸಂಜೆ": "evening", "ರಾತ್ರಿ": "night"}+ YEAR_WORDS = ["ವರ್ಷ", "ಇಸವಿ", "ಸಾಲಿನ", "ಸಾಲು", "ಸನ್"]+ ID_KEYWORDS = ["ನಂಬರ್", "ಸಂಖ್ಯೆ", "ಖಾತೆ", "ಕೋಡ್", "ಆರ್ಡರ್", "ಫೋನ್", "ಮೊಬೈಲ್", "ಐಡಿ", "ಪಿನ್", "ಪಾಸ್ವರ್ಡ್", "ರೈಲು", "ಎಕ್ಸ್ಪ್ರೆಸ್", "ಪಿಎನ್ಆರ್", "ಕಾರ್ಡ್", "ರೆಫರೆನ್ಸ್", "ಟ್ರಾನ್ಸಾಕ್ಷನ್", "ಟಿಕೆಟ್", "ಓಟಿಪಿ", "ಅಕೌಂಟ್", "ಅಂಕಿ", "ಬಳಕೆದಾರ", "ಕಂತು", "ವಹಿವಾಟು"]+ ID_AFTER_WORDS = ["ಡಯಲ್", "ಕರೆ", "ಸಂಪರ್ಕ"]+ NUMBER_WORD = "ನಂಬರ್"+ ABBREV_UNITS = {"MINS":"ನಿಮಿಷ", "MIN":"ನಿಮಿಷ", "HRS":"ಗಂಟೆ", "HR":"ಗಂಟೆ", "SECS":"ಸೆಕೆಂಡ್", "SEC":"ಸೆಕೆಂಡ್", "KMS":"ಕಿಲೋಮೀಟರ್"}+ LABEL_WORDS = ["ವಿಧಿ", "ಕಲಂ", "ಕೊಠಡಿ", "ವಾರ್ಡ್", "ಅಧ್ಯಾಯ", "ಭಾಗ", "ತರಗತಿ"]+ MINUTE_WORDS = ["ನಿಮಿಷ"]+ SCALE_WORDS = {"ಕೋಟಿ": "crore", "ಲಕ್ಷ": "lakh", "ಲಕ್ಷದ": "lakh",+ "ಸಾವಿರ": "thousand", "ಸಾವಿರದ": "thousand"}+ CURRENCY_WORDS = {"ರೂಪಾಯಿ": "rupee", "ರುಪಾಯಿ": "rupee", "ರೂ.": "rupee",+ "ರೂ": "rupee"}++ ORDINAL_EXCEPTIONS = {1: "ಮೊದಲನೇ"}+ ORDINAL_SUFFIX = "ನೇ"+ ORDINAL_INPUT_SUFFIXES = ["ನೆಯ", "ನೇ", "ನೆ"]++ # ==================================================================+ # Dravidian composition — fused hundreds/thousands with sandhi.+ # ==================================================================++ def hundreds(self, h, rest):+ if rest:+ return f"{self.HUNDREDS_COMB[h]} {self.two_digit(rest)}"+ return self.HUNDREDS[h]++ def under_thousand(self, n):+ if n < 100:+ return self.two_digit(n)+ return self.hundreds(n // 100, n % 100)++ def cardinal(self, n):+ if n < 0:+ return f"{self.SYM['minus']} {self.cardinal(-n)}"+ if n < 1000:+ return self.under_thousand(n)+ parts = []+ crore, n = divmod(n, 10**7)+ lakh, n = divmod(n, 10**5)+ thousand, n = divmod(n, 1000)+ if crore:+ # ಕೋಟಿ stays plain even when a remainder follows.+ parts.append(f"{self.cardinal(crore)} {self.CRORE}")+ if lakh:+ word = self.LAKH_COMB if (thousand or n) else self.LAKH+ parts.append(f"{self.two_digit(lakh)} {word}")+ if thousand:+ word = self.THOUSAND_COMB if n else self.THOUSAND+ if thousand == 1 and not (crore or lakh):+ # 1000 -> ಸಾವಿರ; 1947 -> ಸಾವಿರದ ಒಂಬೈನೂರ ನಲವತ್ತೇಳು (no ಒಂದು)+ parts.append(word)+ else:+ parts.append(f"{self.under_thousand(thousand)} {word}")+ if n:+ parts.append(self.under_thousand(n))+ return " ".join(parts)++ def year(self, y):+ """Kannada reads years as full cardinals (news/TTS style):+ 1947 -> ಸಾವಿರದ ಒಂಬೈನೂರ ನಲವತ್ತೇಳು, 2026 -> ಎರಡು ಸಾವಿರದ ಇಪ್ಪತ್ತಾರು."""+ return self.cardinal(y)++ def decade(self, tens, full):+ # Genitive stem: final ು drops before -ರ (ತೊಂಬತ್ತು -> ತೊಂಬತ್ತರ).+ w = self.two_digit(tens)+ stem = w[:-1] if w.endswith("ು") else w+ tpl = self.DECADE_FULL if full else self.DECADE_SHORT+ return tpl.format(tens=stem)++ def _ordinal_compose(self, n, src_suffix):+ # ಎರಡು -> ಎರಡನೇ : final ು of the cardinal drops before ನೇ.+ base = self.cardinal(n)+ if base.endswith("ು"):+ base = base[:-1]+ suffix = src_suffix if src_suffix in self.ORDINAL_INPUT_SUFFIXES else self.ORDINAL_SUFFIX+ return f"{base}{suffix}"++ # Kannada case markers attach with oblique on ು-final words:+ # ಐದು+ಇಂದ->ಐದರಿಂದ, ಮೂರು+ಗೆ->ಮೂರಕ್ಕೆ, ಒಂಬತ್ತು+ನಲ್ಲಿ->ಒಂಬತ್ತರಲ್ಲಿ;+ # consonant/ೆ-final just attach (ನಿಮಿಷ+ಕ್ಕೆ->ನಿಮಿಷಕ್ಕೆ, ಸೊನ್ನೆ+ಗೆ->ಸೊನ್ನೆಗೆ)+ _PP = {"ಗೆ", "ಕ್ಕೆ", "ಇಂದ", "ದಿಂದ", "ರಿಂದ", "ನಲ್ಲಿ", "ಅಲ್ಲಿ",+ "ರಲ್ಲಿ", "ವರೆಗೆ", "ಗಾಗಿ", "ಕ್ಕಾಗಿ"}++ def attach_postposition(self, rep, tok):+ t = tok.lstrip("-")+ last = rep.rsplit(" ", 1)[-1]+ if not last or not ("\u0c80" <= last[-1] <= "\u0cff"):+ return None+ if t == last:+ return rep+ if t not in self._PP:+ return None+ base = rep[:len(rep)-len(last)]+ dative = t in ("ಗೆ", "ಕ್ಕೆ")+ ablative = t in ("ಇಂದ", "ದಿಂದ", "ರಿಂದ")+ locative = t in ("ನಲ್ಲಿ", "ಅಲ್ಲಿ", "ರಲ್ಲಿ")+ if last.endswith("\u0cc1"): # ು-final -> drop, oblique -ರ/-ಕ್ಕೆ+ stem = last[:-1]+ suf = "ಕ್ಕೆ" if dative else "ರಿಂದ" if ablative else "ರಲ್ಲಿ" if locative else t+ return base + stem + suf+ if last.endswith(("\u0cc6", "\u0cbf", "\u0cc0")): # ೆ/ಿ/ೀ-final+ suf = "ಗೆ" if dative else "ಯಿಂದ" if ablative else "ಯಲ್ಲಿ" if locative else t+ return base + last + suf+ # consonant/inherent-a-final -> -ಕ್ಕೆ/-ದಿಂದ/-ದಲ್ಲಿ+ suf = "ಕ್ಕೆ" if dative else "ದಿಂದ" if ablative else "ದಲ್ಲಿ" if locative else t+ return base + last + suf+++class Malayalam(LangBase):+ code = "ml"+ name = "Malayalam"+ native_digits = "൦൧൨൩൪൫൬൭൮൯"+ COUNT_ONE = "ഒരു"++ ONES = [+ "പൂജ്യം", "ഒന്ന്", "രണ്ട്", "മൂന്ന്", "നാല്", "അഞ്ച്", "ആറ്", "ഏഴ്", "എട്ട്", "ഒമ്പത്",+ "പത്ത്", "പതിനൊന്ന്", "പന്ത്രണ്ട്", "പതിമൂന്ന്", "പതിനാല്", "പതിനഞ്ച്", "പതിനാറ്",+ "പതിനേഴ്", "പതിനെട്ട്", "പത്തൊമ്പത്",+ "ഇരുപത്", "ഇരുപത്തിയൊന്ന്", "ഇരുപത്തിരണ്ട്", "ഇരുപത്തിമൂന്ന്", "ഇരുപത്തിനാല്",+ "ഇരുപത്തിയഞ്ച്", "ഇരുപത്തിയാറ്", "ഇരുപത്തിയേഴ്", "ഇരുപത്തിയെട്ട്", "ഇരുപത്തിയൊമ്പത്",+ "മുപ്പത്", "മുപ്പത്തിയൊന്ന്", "മുപ്പത്തിരണ്ട്", "മുപ്പത്തിമൂന്ന്", "മുപ്പത്തിനാല്",+ "മുപ്പത്തിയഞ്ച്", "മുപ്പത്തിയാറ്", "മുപ്പത്തിയേഴ്", "മുപ്പത്തിയെട്ട്", "മുപ്പത്തിയൊമ്പത്",+ "നാൽപ്പത്", "നാൽപ്പത്തിയൊന്ന്", "നാൽപ്പത്തിരണ്ട്", "നാൽപ്പത്തിമൂന്ന്", "നാൽപ്പത്തിനാല്",+ "നാൽപ്പത്തിയഞ്ച്", "നാൽപ്പത്തിയാറ്", "നാൽപ്പത്തിയേഴ്", "നാൽപ്പത്തിയെട്ട്", "നാൽപ്പത്തിയൊമ്പത്",+ "അമ്പത്", "അമ്പത്തിയൊന്ന്", "അമ്പത്തിരണ്ട്", "അമ്പത്തിമൂന്ന്", "അമ്പത്തിനാല്",+ "അമ്പത്തിയഞ്ച്", "അമ്പത്തിയാറ്", "അമ്പത്തിയേഴ്", "അമ്പത്തിയെട്ട്", "അമ്പത്തിയൊമ്പത്",+ "അറുപത്", "അറുപത്തിയൊന്ന്", "അറുപത്തിരണ്ട്", "അറുപത്തിമൂന്ന്", "അറുപത്തിനാല്",+ "അറുപത്തിയഞ്ച്", "അറുപത്തിയാറ്", "അറുപത്തിയേഴ്", "അറുപത്തിയെട്ട്", "അറുപത്തിയൊമ്പത്",+ "എഴുപത്", "എഴുപത്തിയൊന്ന്", "എഴുപത്തിരണ്ട്", "എഴുപത്തിമൂന്ന്", "എഴുപത്തിനാല്",+ "എഴുപത്തിയഞ്ച്", "എഴുപത്തിയാറ്", "എഴുപത്തിയേഴ്", "എഴുപത്തിയെട്ട്", "എഴുപത്തിയൊമ്പത്",+ "എൺപത്", "എൺപത്തിയൊന്ന്", "എൺപത്തിരണ്ട്", "എൺപത്തിമൂന്ന്", "എൺപത്തിനാല്",+ "എൺപത്തിയഞ്ച്", "എൺപത്തിയാറ്", "എൺപത്തിയേഴ്", "എൺപത്തിയെട്ട്", "എൺപത്തിയൊമ്പത്",+ "തൊണ്ണൂറ്", "തൊണ്ണൂറ്റിയൊന്ന്", "തൊണ്ണൂറ്റിരണ്ട്", "തൊണ്ണൂറ്റിമൂന്ന്", "തൊണ്ണൂറ്റിനാല്",+ "തൊണ്ണൂറ്റിയഞ്ച്", "തൊണ്ണൂറ്റിയാറ്", "തൊണ്ണൂറ്റിയേഴ്", "തൊണ്ണൂറ്റിയെട്ട്", "തൊണ്ണൂറ്റിയൊമ്പത്",+ ]+ HUNDRED = "നൂറ്" # not used in composition (Dravidian override below)+ THOUSAND = "ആയിരം"+ LAKH = "ലക്ഷം"+ CRORE = "കോടി"++ # Fused hundreds: standalone and combining (before a remainder).+ _H_STAND = {1: "നൂറ്", 2: "ഇരുനൂറ്", 3: "മുന്നൂറ്", 4: "നാനൂറ്", 5: "അഞ്ഞൂറ്",+ 6: "അറുനൂറ്", 7: "എഴുനൂറ്", 8: "എണ്ണൂറ്", 9: "തൊള്ളായിരം"}+ _H_COMB = {1: "നൂറ്റി", 2: "ഇരുനൂറ്റി", 3: "മുന്നൂറ്റി", 4: "നാനൂറ്റി", 5: "അഞ്ഞൂറ്റി",+ 6: "അറുനൂറ്റി", 7: "എഴുനൂറ്റി", 8: "എണ്ണൂറ്റി", 9: "തൊള്ളായിരത്തി"}++ # Fused thousands for multipliers 1..10; others via sandhi (see _thousand).+ _TH_STAND = {1: "ആയിരം", 2: "രണ്ടായിരം", 3: "മൂവായിരം", 4: "നാലായിരം",+ 5: "അയ്യായിരം", 6: "ആറായിരം", 7: "ഏഴായിരം", 8: "എണ്ണായിരം",+ 9: "ഒമ്പതിനായിരം", 10: "പതിനായിരം"}++ _ONE_MULT = "ഒരു" # multiplier word for 1 lakh / 1 crore++ LETTERS = {+ "A": "എ", "B": "ബി", "C": "സി", "D": "ഡി", "E": "ഇ", "F": "എഫ്",+ "G": "ജി", "H": "എച്ച്", "I": "ഐ", "J": "ജെ", "K": "കെ", "L": "എൽ",+ "M": "എം", "N": "എൻ", "O": "ഒ", "P": "പി", "Q": "ക്യു", "R": "ആർ",+ "S": "എസ്", "T": "ടി", "U": "യു", "V": "വി", "W": "ഡബ്ല്യു",+ "X": "എക്സ്", "Y": "വൈ", "Z": "ഇസഡ്",+ }++ MONTHS = ["ജനുവരി", "ഫെബ്രുവരി", "മാർച്ച്", "ഏപ്രിൽ", "മേയ്", "ജൂൺ",+ "ജൂലൈ", "ഓഗസ്റ്റ്", "സെപ്റ്റംബർ", "ഒക്ടോബർ", "നവംബർ", "ഡിസംബർ"]++ SYM = {+ "rupee": "രൂപ", "dollar": "ഡോളർ", "euro": "യൂറോ", "pound": "പൗണ്ട്",+ "cent": "സെന്റ്",+ "percent": "ശതമാനം",+ "point": "ദശാംശം",+ "minus": "മൈനസ്", "plus": "പ്ലസ്", "equals": "സമം",+ "times": "ഗുണം", "divide": "ഹരണം",+ "squared": "വർഗം", "sqrt": "വർഗമൂലം",+ "lt": "നെക്കാൾ കുറവ്", "gt": "നെക്കാൾ കൂടുതൽ",+ "plus_minus": "പ്ലസ്-മൈനസ്",+ "at": "അറ്റ് ദ റേറ്റ്", "underscore": "അണ്ടർസ്കോർ", "dot": "ഡോട്ട്",+ "slash": "സ്ലാഷ്", "hash": "ഹാഷ്", "amp": "ആൻഡ്",+ "half": "അര", "quarter": "കാൽ", "three_quarters": "മുക്കാൽ",+ "degree": "ഡിഗ്രി", "celsius": "ഡിഗ്രി സെൽഷ്യസ്", "fahrenheit": "ഡിഗ്രി ഫാരൻഹീറ്റ്",+ "minute": "മിനിറ്റ്", "second": "സെക്കൻഡ്",+ }++ TIME_ON_HOUR = "{h} മണി"+ TIME_HM = "{h} മണി {m} മിനിറ്റ്"+ RANGE = "{a} മുതൽ {b}"+ RANGE_TO = "{a} മുതൽ {b} വരെ"+ RATIO = "{a} അനുപാതം {b}"+ POWER = "{base} ഘാതം {exp}"+ FRACTION = "{num} ബൈ {den}"+ DECADE_SHORT = "{tens}കൾ"+ DECADE_FULL = "{tens}കളുടെ ദശകം"++ PERIODS = {"morning": "രാവിലെ", "afternoon": "ഉച്ചയ്ക്ക്",+ "evening": "വൈകുന്നേരം", "night": "രാത്രി"}++ TIME_MARKERS = ["മണി", "മണിക്ക്", "മണിയോടെ"]+ MARKER_SUFFIXES = {"മണിക്ക്": "ന്", "മണിയോടെ": "ഓടെ"}+ PERIOD_DETECT = {"രാവിലെ": "morning", "കാലത്ത്": "morning",+ "ഉച്ചയ്ക്ക്": "afternoon", "ഉച്ചക്ക്": "afternoon",+ "ഉച്ച": "afternoon", "ഉച്ചകഴിഞ്ഞ്": "afternoon",+ "വൈകുന്നേരം": "evening", "വൈകിട്ട്": "evening",+ "സന്ധ്യക്ക്": "evening", "രാത്രി": "night"}+ YEAR_WORDS = ["വർഷം", "വർഷത്തിൽ", "വർഷത്തെ", "കൊല്ലം", "ആണ്ട്"]+ ID_KEYWORDS = ["നമ്പർ", "നമ്പര്", "നമ്പറിൽ", "അക്കൗണ്ട്", "കോഡ്", "ഓർഡർ", "ഫോൺ", "മൊബൈൽ", "ഒടിപി", "പിൻ", "ഐഡി", "പാസ്വേഡ്", "ട്രെയിൻ", "എക്സ്പ്രസ്", "പിഎൻആർ", "കാർഡ്", "റഫറൻസ്", "ട്രാൻസാക്ഷൻ", "ടിക്കറ്റ്", "അക്കൗണ്ടിൽ", "നമ്പറിലേക്ക്", "യൂസർ", "തവണ", "അക്കം", "ഇടപാട്"]+ NUMBER_WORD = "നമ്പർ"+ ABBREV_UNITS = {"MINS":"മിനിറ്റ്", "MIN":"മിനിറ്റ്", "HRS":"മണിക്കൂർ", "HR":"മണിക്കൂർ", "SECS":"സെക്കൻഡ്", "SEC":"സെക്കൻഡ്", "KMS":"കിലോമീറ്റർ"}+ LABEL_WORDS = ["അനുച്ഛേദം", "വകുപ്പ്", "മുറി", "റൂം", "വാർഡ്", "ക്ലാസ്",+ "അധ്യായം", "ഭാഗം", "ഗേറ്റ്", "കൗണ്ടർ"]+ MINUTE_WORDS = ["മിനിറ്റ്", "മിനുട്ട്"]+ SCALE_WORDS = {"കോടി": "crore", "കോടിയുടെ": "crore",+ "ലക്ഷം": "lakh", "ലക്ഷത്തി": "lakh", "ലക്ഷത്തിന്റെ": "lakh",+ "ആയിരം": "thousand", "ആയിരത്തി": "thousand"}+ CURRENCY_WORDS = {"രൂപ": "rupee", "രൂപാ": "rupee", "രൂപയുടെ": "rupee",+ "രൂപയ്ക്ക്": "rupee"}++ ORDINAL_EXCEPTIONS = {}+ ORDINAL_SUFFIX = "ാം" # ഒന്ന് -> ഒന്നാം, പത്ത് -> പത്താം+ ORDINAL_INPUT_SUFFIXES = ["ാം", "ാമത്തെ", "ാമത്"]++ _VIRAMA = "്" # ്+ _ANUSVARA = "ം" # ം++ # ------------------------------------------------------------------+ # Dravidian composition overrides (fused hundreds/thousands + sandhi)+ # ------------------------------------------------------------------++ def hundreds(self, h, rest):+ if rest:+ return f"{self._H_COMB[h]} {self.two_digit(rest)}"+ return self._H_STAND[h]++ def _thousand(self, m, combining):+ """Fused '<m> thousand' word for m in 1..99."""+ if m in self._TH_STAND:+ word = self._TH_STAND[m]+ else:+ base = self.ONES[m]+ if base.endswith("ത" + self._VIRAMA):+ # ends in ...ത് (round tens, -ഒമ്പത്): ഇരുപത് -> ഇരുപതിനായിരം+ word = base[:-1] + "ിനായിരം"+ elif base.endswith(self._VIRAMA):+ # virama + ആ -> ാ : അമ്പത്തിനാല് -> അമ്പത്തിനാലായിരം,+ # തൊണ്ണൂറ് -> തൊണ്ണൂറായിരം+ word = base[:-1] + "ായിരം"+ else:+ word = base + " " + self.THOUSAND+ if combining:+ # ം -> ത്തി : ആയിരം -> ആയിരത്തി+ return word[:-1] + "ത്തി"+ return word++ def cardinal(self, n):+ if n < 0:+ return f"{self.SYM['minus']} {self.cardinal(-n)}"+ if n < 100:+ return self.ONES[n]+ if n < 1000:+ return self.hundreds(n // 100, n % 100)+ parts = []+ crore, n = divmod(n, 10**7)+ lakh, n = divmod(n, 10**5)+ thousand, n = divmod(n, 1000)+ if crore:+ mult = self._ONE_MULT if crore == 1 else self.cardinal(crore)+ parts.append(f"{mult} {self.CRORE}")+ if lakh:+ word = self.LAKH[:-1] + "ത്തി" if (thousand or n) else self.LAKH+ mult = self._ONE_MULT if lakh == 1 else self.two_digit(lakh)+ parts.append(f"{mult} {word}")+ if thousand:+ parts.append(self._thousand(thousand, combining=bool(n)))+ if n:+ parts.append(self.under_thousand(n))+ return " ".join(parts)++ def year(self, y):+ """Malayalam reads years as full cardinals (news/TTS convention):+ 1947 -> ആയിരത്തി തൊള്ളായിരത്തി നാൽപ്പത്തിയേഴ്."""+ return self.cardinal(y)++ def decade(self, tens, full):+ # തൊണ്ണൂറ് + കൾ -> തൊണ്ണൂറുകൾ (final virama -> ു before കൾ)+ stem = self.two_digit(tens)+ if stem.endswith(self._VIRAMA):+ stem = stem[:-1] + "ു"+ tpl = self.DECADE_FULL if full else self.DECADE_SHORT+ return tpl.format(tens=stem)++ def _ordinal_compose(self, n, src_suffix):+ # രണ്ട് -> രണ്ടാം : strip final virama/anusvara, then attach suffix.+ stem = self.cardinal(n)+ if stem.endswith(self._VIRAMA) or stem.endswith(self._ANUSVARA):+ stem = stem[:-1]+ suffix = src_suffix if src_suffix in self.ORDINAL_INPUT_SUFFIXES else self.ORDINAL_SUFFIX+ return f"{stem}{suffix}"++ # Malayalam case markers (often hyphen-attached in source) attach with+ # sandhi: രൂപ+ന്റെ->രൂപയുടെ, ആറ്+ൽ->ആറിൽ, രൂപ+ൽ->രൂപയിൽ+ def attach_postposition(self, rep, tok):+ t = tok.lstrip("-")+ last = rep.rsplit(" ", 1)[-1]+ if not last or not ("ഀ" <= last[-1] <= "ൿ"):+ return None+ base = rep[:len(rep)-len(last)]+ virama = last.endswith("്")+ anusvara = last.endswith("ം")+ ivow = last[-1] in ("ി", "ീ")+ if t in ("ന്റെ", "ുടെ", "യുടെ"):+ if virama: return base + last[:-1] + "ിന്റെ"+ if anusvara: return base + last[:-1] + "ത്തിന്റെ"+ return base + last + "യുടെ"+ if t in ("ൽ", "ിൽ", "ലെ", "ിലെ"):+ end = "ിലെ" if t in ("ലെ", "ിലെ") else "ിൽ"+ if virama: return base + last[:-1] + end+ if anusvara: return base + last[:-1] + "ത്ത" + end+ return base + last + "യ" + end+ if t in ("ലേക്ക്", "ിലേക്ക്"):+ if virama: return base + last[:-1] + "ിലേക്ക്"+ if anusvara: return base + last[:-1] + "ത്തിലേക്ക്"+ return base + last + "യിലേക്ക്"+ if t in ("ന്", "ിന്", "ക്ക്", "ിനാണ്"):+ tail = "ിനാണ്" if t == "ിനാണ്" else "ിന്"+ if virama: return base + last[:-1] + tail+ if anusvara: return base + last[:-1] + "ത്ത" + tail+ if ivow: return base + last + "ക്ക്"+ return base + last + "യ്ക്ക്"+ return None+++class Marathi(LangBase):+ code = "mr"+ name = "Marathi"+ native_digits = "०१२३४५६७८९"+ SINGULAR_NOUNS = {"रुपये": "रुपया", "मिनिटे": "मिनिट"}++ ONES = [+ "शून्य", "एक", "दोन", "तीन", "चार", "पाच", "सहा", "सात", "आठ", "नऊ",+ "दहा", "अकरा", "बारा", "तेरा", "चौदा", "पंधरा", "सोळा", "सतरा", "अठरा", "एकोणीस",+ "वीस", "एकवीस", "बावीस", "तेवीस", "चोवीस", "पंचवीस", "सव्वीस", "सत्तावीस", "अठ्ठावीस", "एकोणतीस",+ "तीस", "एकतीस", "बत्तीस", "तेहतीस", "चौतीस", "पस्तीस", "छत्तीस", "सदतीस", "अडतीस", "एकोणचाळीस",+ "चाळीस", "एक्केचाळीस", "बेचाळीस", "त्रेचाळीस", "चव्वेचाळीस", "पंचेचाळीस", "सेहेचाळीस", "सत्तेचाळीस", "अठ्ठेचाळीस", "एकोणपन्नास",+ "पन्नास", "एक्कावन्न", "बावन्न", "त्रेपन्न", "चोपन्न", "पंचावन्न", "छप्पन्न", "सत्तावन्न", "अठ्ठावन्न", "एकोणसाठ",+ "साठ", "एकसष्ट", "बासष्ट", "त्रेसष्ट", "चौसष्ट", "पासष्ट", "सहासष्ट", "सदुसष्ट", "अडुसष्ट", "एकोणसत्तर",+ "सत्तर", "एक्काहत्तर", "बाहत्तर", "त्र्याहत्तर", "चौऱ्याहत्तर", "पंच्याहत्तर", "शहात्तर", "सत्त्याहत्तर", "अठ्ठ्याहत्तर", "एकोणऐंशी",+ "ऐंशी", "एक्क्याऐंशी", "ब्याऐंशी", "त्र्याऐंशी", "चौऱ्याऐंशी", "पंच्याऐंशी", "शहाऐंशी", "सत्त्याऐंशी", "अठ्ठ्याऐंशी", "एकोणनव्वद",+ "नव्वद", "एक्क्याण्णव", "ब्याण्णव", "त्र्याण्णव", "चौऱ्याण्णव", "पंच्याण्णव", "शहाण्णव", "सत्त्याण्णव", "अठ्ठ्याण्णव", "नव्व्याण्णव",+ ]+ HUNDRED = "शे"+ THOUSAND = "हजार"+ LAKH = "लाख"+ CRORE = "कोटी"++ LETTERS = {+ "A": "ए", "B": "बी", "C": "सी", "D": "डी", "E": "ई", "F": "एफ",+ "G": "जी", "H": "एच", "I": "आय", "J": "जे", "K": "के", "L": "एल",+ "M": "एम", "N": "एन", "O": "ओ", "P": "पी", "Q": "क्यू", "R": "आर",+ "S": "एस", "T": "टी", "U": "यू", "V": "व्ही", "W": "डब्ल्यू",+ "X": "एक्स", "Y": "वाय", "Z": "झेड",+ }++ MONTHS = ["जानेवारी", "फेब्रुवारी", "मार्च", "एप्रिल", "मे", "जून",+ "जुलै", "ऑगस्ट", "सप्टेंबर", "ऑक्टोबर", "नोव्हेंबर", "डिसेंबर"]++ SYM = {+ "rupee": "रुपये", "dollar": "डॉलर", "euro": "युरो", "pound": "पाउंड",+ "cent": "सेंट",+ "percent": "टक्के",+ "point": "पूर्णांक",+ "minus": "उणे", "plus": "अधिक", "equals": "बरोबर",+ "times": "गुणिले", "divide": "भागिले",+ "squared": "चा वर्ग", "sqrt": "वर्गमूळ",+ "lt": "पेक्षा कमी", "gt": "पेक्षा जास्त",+ "plus_minus": "अधिक-उणे",+ "at": "ॲट द रेट", "underscore": "अंडरस्कोर", "dot": "डॉट",+ "slash": "स्लॅश", "hash": "हॅश", "amp": "आणि",+ "half": "अर्धा", "quarter": "पाव", "three_quarters": "पाऊण",+ "degree": "अंश", "celsius": "अंश सेल्सिअस", "fahrenheit": "अंश फॅरनहाइट",+ "minute": "मिनिटे", "second": "सेकंद",+ }++ TIME_ON_HOUR = "{h} वाजता"+ TIME_HM = "{h} वाजून {m} मिनिटे"+ RANGE = "{a} ते {b}"+ RANGE_TO = "{a} ते {b} पर्यंत"+ RATIO = "{a} गुणोत्तर {b}"+ POWER = "{base} चा घात {exp}"+ FRACTION = "{num} बटा {den}"+ DECADE_SHORT = "{tens} च्या"+ DECADE_FULL = "{tens} चे दशक"++ PERIODS = {"morning": "सकाळी", "afternoon": "दुपारी",+ "evening": "संध्याकाळी", "night": "रात्री"}++ TIME_MARKERS = ["वाजता", "वाजून", "वाजले", "वाजल्या", "वाजेपर्यंत"]+ PERIOD_DETECT = {"सकाळी": "morning", "सकाळ": "morning", "सकाळचे": "morning",+ "पहाटे": "morning",+ "दुपारी": "afternoon", "दुपार": "afternoon", "दुपारचे": "afternoon",+ "संध्याकाळी": "evening", "संध्याकाळ": "evening",+ "सायंकाळी": "evening",+ "रात्री": "night", "रात्र": "night", "रात्रीचे": "night"}+ YEAR_WORDS = ["साल", "साली", "सालच्या", "सन", "वर्ष", "वर्षी", "इसवी"]+ ID_KEYWORDS = ["नंबर", "क्रमांक", "खाते", "खात्याचा", "खात्यावर", "कोड", "ऑर्डर", "फोन", "मोबाईल", "मोबाइल", "अकाउंट", "अकाउंटसाठी", "अकाउंटमधून", "खात्यातून", "खात्यात", "खात्याची", "पिन", "आयडी", "पासवर्ड", "ट्रेन", "एक्सप्रेस", "पीएनआर", "कार्ड", "रेफरन्स", "ट्रांझॅक्शन", "तिकीट", "ओटीपी", "गाडी", "युजर", "यूजर", "हप्ता", "हप्त्याचा", "अंक", "व्यवहार", "ट्रान्झॅक्शन", "क्र", "क्रं", "चेक", "धनादेश"]+ ID_AFTER_WORDS = ["डायल", "कॉल", "संपर्क"]+ NUMBER_WORD = "क्रमांक"+ ABBREV_UNITS = {"MINS":"मिनिटे", "MIN":"मिनिट", "HRS":"तास", "HR":"तास", "SECS":"सेकंद", "SEC":"सेकंद", "KMS":"किलोमीटर"}+ LABEL_WORDS = ["कलम", "अनुच्छेद", "खोली", "वर्ग", "इयत्ता", "वॉर्ड",+ "अध्याय", "भाग", "प्रकरण", "गट"]+ MINUTE_WORDS = ["मिनिटे", "मिनिटं", "मिनिट", "मिनिटांनी"]+ SCALE_WORDS = {"कोटी": "crore", "लाख": "lakh", "हजार": "thousand",+ "अब्ज": "arab"}+ CURRENCY_WORDS = {"रुपये": "rupee", "रुपया": "rupee", "रुपयांचा": "rupee",+ "रुपयांची": "rupee", "रु": "rupee"}++ ORDINAL_EXCEPTIONS = {1: "पहिला", 2: "दुसरा", 3: "तिसरा", 4: "चौथा"}+ ORDINAL_SUFFIX = "वा"+ ORDINAL_INPUT_SUFFIXES = ["वा", "वी", "वे", "व्या", "वं"]++ # ------------------------------------------------------------------+ # Hundreds fuse: एक+शे -> एकशे, दोन+शे -> दोनशे (written solid).+ # Exactly 100 with no remainder is शंभर.+ # ------------------------------------------------------------------+ def hundreds(self, h, rest):+ if h == 1 and rest == 0:+ return "शंभर"+ out = f"{self.ONES[h]}{self.HUNDRED}"+ if rest:+ out += f" {self.two_digit(rest)}"+ return out++ def year(self, y):+ """1947 -> एकोणीसशे सत्तेचाळीस (fused शे); 2026 -> दोन हजार सव्वीस."""+ if 1100 <= y <= 1999:+ hi, lo = divmod(y, 100)+ out = f"{self.two_digit(hi)}{self.HUNDRED}"+ if lo:+ out += f" {self.two_digit(lo)}"+ return out+ return self.cardinal(y)++ def _ordinal_compose(self, n, src_suffix):+ # 12वा -> बारावा, 12वी -> बारावी : cardinal + preserved suffix+ if src_suffix:+ return f"{self.cardinal(n)}{src_suffix}"+ if n in self.ORDINAL_EXCEPTIONS:+ return self.ORDINAL_EXCEPTIONS[n]+ return f"{self.cardinal(n)}{self.ORDINAL_SUFFIX}"++ # Marathi: -ए ending noun-words take oblique plural -यां before a case+ # marker (रुपये+चा->रुपयांचा, मिनिटे+ला->मिनिटांना)+ _ATTACH_NOUNS = {"रुपये", "पैसे", "डॉलर", "टक्के", "मिनिटे", "तास",+ "किलोमीटर", "किलो", "मीटर", "लिटर", "ग्रॅम", "अंश"}+ _CASE = {"चा":"चा","ची":"ची","चे":"चे","चं":"चं","च्या":"च्या",+ "ला":"ना","ना":"ना","नी":"नी","त":"त","तून":"तून","हून":"हून",+ "पर्यंत":"पर्यंत","मध्ये":"मध्ये","साठी":"साठी"}++ def attach_postposition(self, rep, tok):+ t = tok.lstrip("-").lstrip("ांं")+ last = rep.rsplit(" ", 1)[-1]+ if last not in self._ATTACH_NOUNS or t not in self._CASE:+ return None+ base = rep[:len(rep)-len(last)]+ obl = last[:-1] + "ां" if last.endswith("े") else last+ return base + obl + self._CASE[t]+++class Odia(LangBase):+ code = "or"+ name = "Odia"+ native_digits = "୦୧୨୩୪୫୬୭୮୯"++ ONES = [+ "ଶୂନ୍ୟ", "ଏକ", "ଦୁଇ", "ତିନି", "ଚାରି", "ପାଞ୍ଚ", "ଛଅ", "ସାତ", "ଆଠ", "ନଅ",+ "ଦଶ", "ଏଗାର", "ବାର", "ତେର", "ଚଉଦ", "ପନ୍ଦର", "ଷୋହଳ", "ସତର", "ଅଠର", "ଉଣେଇଶି",+ "କୋଡ଼ିଏ", "ଏକୋଇଶି", "ବାଇଶି", "ତେଇଶି", "ଚବିଶି", "ପଚିଶି", "ଛବିଶି", "ସତାଇଶି", "ଅଠେଇଶି", "ଅଣତିରିଶି",+ "ତିରିଶି", "ଏକତିରିଶି", "ବତିଶି", "ତେତିଶି", "ଚଉତିରିଶି", "ପଞ୍ଚତିରିଶି", "ଛତିଶି", "ସଇଁତିରିଶି", "ଅଠତିରିଶି", "ଅଣଚାଳିଶି",+ "ଚାଳିଶି", "ଏକଚାଳିଶି", "ବୟାଳିଶି", "ତେୟାଳିଶି", "ଚଉରାଳିଶି", "ପଞ୍ଚଚାଳିଶି", "ଛୟାଳିଶି", "ସତଚାଳିଶି", "ଅଠଚାଳିଶି", "ଅଣଚାଶ",+ "ପଚାଶ", "ଏକାବନ", "ବାଉନ", "ତେପନ", "ଚଉବନ", "ପଞ୍ଚାବନ", "ଛପନ", "ସତାବନ", "ଅଠାବନ", "ଅଣଷଠି",+ "ଷାଠିଏ", "ଏକଷଠି", "ବାଷଠି", "ତେଷଠି", "ଚଉଷଠି", "ପଞ୍ଚଷଠି", "ଛଅଷଠି", "ସତଷଠି", "ଅଠଷଠି", "ଅଣସ୍ତରି",+ "ସତୁରି", "ଏକସ୍ତରି", "ବାସ୍ତରି", "ତେସ୍ତରି", "ଚଉସ୍ତରି", "ପଞ୍ଚସ୍ତରି", "ଛଅସ୍ତରି", "ସତସ୍ତରି", "ଅଠସ୍ତରି", "ଅଣାଅଶୀ",+ "ଅଶୀ", "ଏକାଅଶୀ", "ବୟାଅଶୀ", "ତେୟାଅଶୀ", "ଚଉରାଅଶୀ", "ପଞ୍ଚାଅଶୀ", "ଛୟାଅଶୀ", "ସତାଅଶୀ", "ଅଠାଅଶୀ", "ଅଣାନବେ",+ "ନବେ", "ଏକାନବେ", "ବୟାନବେ", "ତେୟାନବେ", "ଚଉରାନବେ", "ପଞ୍ଚାନବେ", "ଛୟାନବେ", "ସତାନବେ", "ଅଠାନବେ", "ଅନେଶତ",+ ]+ HUNDRED = "ଶହ"+ THOUSAND = "ହଜାର"+ LAKH = "ଲକ୍ଷ"+ CRORE = "କୋଟି"++ LETTERS = {+ "A": "ଏ", "B": "ବି", "C": "ସି", "D": "ଡି", "E": "ଇ", "F": "ଏଫ୍",+ "G": "ଜି", "H": "ଏଚ୍", "I": "ଆଇ", "J": "ଜେ", "K": "କେ", "L": "ଏଲ୍",+ "M": "ଏମ୍", "N": "ଏନ୍", "O": "ଓ", "P": "ପି", "Q": "କ୍ୟୁ", "R": "ଆର୍",+ "S": "ଏସ୍", "T": "ଟି", "U": "ୟୁ", "V": "ଭି", "W": "ଡବ୍ଲ୍ୟୁ",+ "X": "ଏକ୍ସ", "Y": "ୱାଇ", "Z": "ଜେଡ୍",+ }++ MONTHS = ["ଜାନୁଆରୀ", "ଫେବୃଆରୀ", "ମାର୍ଚ୍ଚ", "ଅପ୍ରେଲ", "ମଇ", "ଜୁନ",+ "ଜୁଲାଇ", "ଅଗଷ୍ଟ", "ସେପ୍ଟେମ୍ବର", "ଅକ୍ଟୋବର", "ନଭେମ୍ବର", "ଡିସେମ୍ବର"]++ SYM = {+ "rupee": "ଟଙ୍କା", "dollar": "ଡଲାର", "euro": "ୟୁରୋ", "pound": "ପାଉଣ୍ଡ",+ "cent": "ସେଣ୍ଟ",+ "percent": "ପ୍ରତିଶତ",+ "point": "ଦଶମିକ",+ "minus": "ମାଇନସ୍", "plus": "ପ୍ଲସ୍", "equals": "ସମାନ",+ "times": "ଗୁଣ", "divide": "ଭାଗ",+ "squared": "ର ବର୍ଗ", "sqrt": "ବର୍ଗମୂଳ",+ "lt": "ଠାରୁ କମ୍", "gt": "ଠାରୁ ଅଧିକ",+ "plus_minus": "ପ୍ଲସ୍-ମାଇନସ୍",+ "at": "ଆଟ୍ ଦି ରେଟ୍", "underscore": "ଅଣ୍ଡରସ୍କୋର", "dot": "ଡଟ୍",+ "slash": "ସ୍ଲାସ୍", "hash": "ହ୍ୟାସ୍", "amp": "ଆଣ୍ଡ",+ "half": "ଅଧା", "quarter": "ଏକ ଚତୁର୍ଥାଂଶ", "three_quarters": "ତିନି ଚତୁର୍ଥାଂଶ",+ "degree": "ଡିଗ୍ରୀ", "celsius": "ଡିଗ୍ରୀ ସେଲସିୟସ୍", "fahrenheit": "ଡିଗ୍ରୀ ଫାରେନହାଇଟ୍",+ "minute": "ମିନିଟ୍",+ "paisa": "ପଇସା", "per": "ପ୍ରତି", "second": "ସେକେଣ୍ଡ",+ }++ TIME_ON_HOUR = "{h}ଟା"+ TIME_HM = "{h}ଟା {m} ମିନିଟ୍"+ RANGE = "{a} ରୁ {b}"+ RANGE_TO = "{a} ରୁ {b} ପର୍ଯ୍ୟନ୍ତ"+ RATIO = "{a} ଅନୁପାତ {b}"+ POWER = "{base} ର ଘାତ {exp}"+ FRACTION = "{num} ବଟା {den}"+ DECADE_SHORT = "{tens} ଦଶକ"+ DECADE_FULL = "{tens} ଦଶକ"++ PERIODS = {"morning": "ସକାଳ", "afternoon": "ଦିନ",+ "evening": "ସନ୍ଧ୍ୟା", "night": "ରାତି"}++ TIME_MARKERS = ["ଟା", "ଟାରେ", "ଟାରୁ", "ବେଳେ", "ବଜେ"]+ PERIOD_DETECT = {"ସକାଳ": "morning", "ସକାଳେ": "morning", "ସକାଳୁ": "morning",+ "ଭୋର": "morning", "ଭୋରରୁ": "morning",+ "ଦିନ": "afternoon", "ଅପରାହ୍ନ": "afternoon",+ "ମଧ୍ୟାହ୍ନ": "afternoon", "ଦ୍ୱିପହର": "afternoon",+ "ସନ୍ଧ୍ୟା": "evening", "ସନ୍ଧ୍ୟାରେ": "evening",+ "ରାତି": "night", "ରାତିରେ": "night", "ରାତ୍ରି": "night"}+ YEAR_WORDS = ["ମସିହା", "ମସିହାରେ", "ସାଲ", "ସନ", "ବର୍ଷ", "ବର୍ଷରେ"]+ ID_KEYWORDS = ["ନମ୍ବର", "ନମ୍ବର୍", "ଖାତା", "ଆକାଉଣ୍ଟ", "କୋଡ୍", "ଅର୍ଡର", "ଫୋନ୍", "ଫୋନ", "ମୋବାଇଲ୍", "ମୋବାଇଲ", "ଓଟିପି", "ପିନ୍", "ଆଇଡି", "ପାସୱାର୍ଡ", "ଏକ୍ସପ୍ରେସ", "ପିଏନ୍ଆର୍", "କାର୍ଡ", "ରେଫରେନ୍ସ", "ଟିକେଟ", "ଆକାଉଣ୍ଟରୁ", "ଟ୍ରେନ୍", "ୟୁଜର", "କିସ୍ତି", "ଅଙ୍କ", "ଲାଣଦେଣ"]+ ID_AFTER_WORDS = ["ଡାଏଲ", "କଲ", "ଯୋଗାଯୋଗ"]+ NUMBER_WORD = "ନମ୍ବର"+ ABBREV_UNITS = {"MINS":"ମିନିଟ୍", "MIN":"ମିନିଟ୍", "HRS":"ଘଣ୍ଟା", "HR":"ଘଣ୍ଟା", "SECS":"ସେକେଣ୍ଡ", "SEC":"ସେକେଣ୍ଡ", "KMS":"କିଲୋମିଟର"}+ LABEL_WORDS = ["ଅନୁଚ୍ଛେଦ", "ଧାରା", "ରୁମ୍", "କୋଠରି", "ୱାର୍ଡ",+ "ଅଧ୍ୟାୟ", "ଭାଗ", "ଗେଟ୍", "କାଉଣ୍ଟର", "ଶ୍ରେଣୀ"]+ MINUTE_WORDS = ["ମିନିଟ୍", "ମିନିଟ"]+ SCALE_WORDS = {"କୋଟି": "crore", "ଲକ୍ଷ": "lakh", "ଲାଖ": "lakh",+ "ହଜାର": "thousand"}+ CURRENCY_WORDS = {"ଟଙ୍କା": "rupee", "ଟଙ୍କାର": "rupee", "ଟଙ୍କାରେ": "rupee",+ "ଟଂକା": "rupee", "ରୁପି": "rupee"}++ ORDINAL_EXCEPTIONS = {1: "ପ୍ରଥମ", 2: "ଦ୍ୱିତୀୟ", 3: "ତୃତୀୟ", 4: "ଚତୁର୍ଥ",+ 5: "ପଞ୍ଚମ", 6: "ଷଷ୍ଠ", 7: "ସପ୍ତମ", 8: "ଅଷ୍ଟମ",+ 9: "ନବମ", 10: "ଦଶମ"}+ ORDINAL_SUFFIX = "ତମ"+ ORDINAL_INPUT_SUFFIXES = ["ତମ"]++ # Odia postpositions agglutinate onto noun-words (ଟଙ୍କା + ରୁ -> ଟଙ୍କାରୁ)+ _ATTACH_NOUNS = {"ଟଙ୍କା", "ପଇସା", "ଡଲାର", "ପ୍ରତିଶତ", "କିଲୋମିଟର",+ "କିଲୋଗ୍ରାମ", "ମିଟର", "ଲିଟର", "ଗ୍ରାମ", "ଡିଗ୍ରୀ",+ "ମିନିଟ୍", "ଘଣ୍ଟା", "ସେକେଣ୍ଡ"}+ _PP = {"ରେ", "ରୁ", "କୁ", "ର", "ଠାରୁ", "ପର୍ଯ୍ୟନ୍ତ", "ମଧ୍ୟରେ",+ "ପାଇଁ", "ଅପେକ୍ଷା", "ଭିତରେ"}++ def attach_postposition(self, rep, tok):+ t = tok.lstrip("-")+ last = rep.rsplit(" ", 1)[-1]+ if t == last and last in self._ATTACH_NOUNS:+ return rep+ if t in self._PP and last in self._ATTACH_NOUNS:+ return rep + t+ return None+++class Punjabi(LangBase):+ code = "pa"+ name = "Punjabi"+ native_digits = "੦੧੨੩੪੫੬੭੮੯"+ SINGULAR_NOUNS = {"ਘੰਟੇ": "ਘੰਟਾ"}++ ONES = [+ "ਸਿਫ਼ਰ", "ਇੱਕ", "ਦੋ", "ਤਿੰਨ", "ਚਾਰ", "ਪੰਜ", "ਛੇ", "ਸੱਤ", "ਅੱਠ", "ਨੌਂ",+ "ਦਸ", "ਗਿਆਰਾਂ", "ਬਾਰਾਂ", "ਤੇਰਾਂ", "ਚੌਦਾਂ", "ਪੰਦਰਾਂ", "ਸੋਲਾਂ", "ਸਤਾਰਾਂ", "ਅਠਾਰਾਂ", "ਉੱਨੀ",+ "ਵੀਹ", "ਇੱਕੀ", "ਬਾਈ", "ਤੇਈ", "ਚੌਵੀ", "ਪੱਚੀ", "ਛੱਬੀ", "ਸਤਾਈ", "ਅਠਾਈ", "ਉਣੱਤੀ",+ "ਤੀਹ", "ਇਕੱਤੀ", "ਬੱਤੀ", "ਤੇਤੀ", "ਚੌਂਤੀ", "ਪੈਂਤੀ", "ਛੱਤੀ", "ਸੈਂਤੀ", "ਅਠੱਤੀ", "ਉਣਤਾਲੀ",+ "ਚਾਲੀ", "ਇਕਤਾਲੀ", "ਬਿਆਲੀ", "ਤਰਤਾਲੀ", "ਚੁਤਾਲੀ", "ਪੰਤਾਲੀ", "ਛਿਆਲੀ", "ਸੰਤਾਲੀ", "ਅਠਤਾਲੀ", "ਉਣੰਜਾ",+ "ਪੰਜਾਹ", "ਇਕਵੰਜਾ", "ਬਵੰਜਾ", "ਤਰਵੰਜਾ", "ਚੁਰੰਜਾ", "ਪਚਵੰਜਾ", "ਛਪੰਜਾ", "ਸਤਵੰਜਾ", "ਅਠਵੰਜਾ", "ਉਣਾਹਠ",+ "ਸੱਠ", "ਇਕਾਹਠ", "ਬਾਹਠ", "ਤ੍ਰੇਹਠ", "ਚੌਂਹਠ", "ਪੈਂਹਠ", "ਛਿਆਹਠ", "ਸਤਾਹਠ", "ਅਠਾਹਠ", "ਉਣੱਤਰ",+ "ਸੱਤਰ", "ਇਕਹੱਤਰ", "ਬਹੱਤਰ", "ਤਿਹੱਤਰ", "ਚੁਹੱਤਰ", "ਪੰਝੱਤਰ", "ਛਿਹੱਤਰ", "ਸਤੱਤਰ", "ਅਠੱਤਰ", "ਉਣਾਸੀ",+ "ਅੱਸੀ", "ਇਕਾਸੀ", "ਬਿਆਸੀ", "ਤਰਾਸੀ", "ਚੁਰਾਸੀ", "ਪਚਾਸੀ", "ਛਿਆਸੀ", "ਸਤਾਸੀ", "ਅਠਾਸੀ", "ਉਣਾਨਵੇਂ",+ "ਨੱਬੇ", "ਇਕਾਨਵੇਂ", "ਬਾਨਵੇਂ", "ਤਰਾਨਵੇਂ", "ਚੁਰਾਨਵੇਂ", "ਪਚਾਨਵੇਂ", "ਛਿਆਨਵੇਂ", "ਸਤਾਨਵੇਂ", "ਅਠਾਨਵੇਂ", "ਨੜਿੰਨਵੇਂ",+ ]+ HUNDRED = "ਸੌ"+ THOUSAND = "ਹਜ਼ਾਰ"+ LAKH = "ਲੱਖ"+ CRORE = "ਕਰੋੜ"++ LETTERS = {+ "A": "ਏ", "B": "ਬੀ", "C": "ਸੀ", "D": "ਡੀ", "E": "ਈ", "F": "ਐੱਫ",+ "G": "ਜੀ", "H": "ਐੱਚ", "I": "ਆਈ", "J": "ਜੇ", "K": "ਕੇ", "L": "ਐੱਲ",+ "M": "ਐੱਮ", "N": "ਐੱਨ", "O": "ਓ", "P": "ਪੀ", "Q": "ਕਿਊ", "R": "ਆਰ",+ "S": "ਐੱਸ", "T": "ਟੀ", "U": "ਯੂ", "V": "ਵੀ", "W": "ਡਬਲਿਊ",+ "X": "ਐਕਸ", "Y": "ਵਾਈ", "Z": "ਜ਼ੈੱਡ",+ }++ MONTHS = ["ਜਨਵਰੀ", "ਫ਼ਰਵਰੀ", "ਮਾਰਚ", "ਅਪ੍ਰੈਲ", "ਮਈ", "ਜੂਨ",+ "ਜੁਲਾਈ", "ਅਗਸਤ", "ਸਤੰਬਰ", "ਅਕਤੂਬਰ", "ਨਵੰਬਰ", "ਦਸੰਬਰ"]++ SYM = {+ "rupee": "ਰੁਪਏ", "dollar": "ਡਾਲਰ", "euro": "ਯੂਰੋ", "pound": "ਪੌਂਡ",+ "cent": "ਸੈਂਟ",+ "percent": "ਫ਼ੀਸਦੀ",+ "point": "ਦਸ਼ਮਲਵ",+ "minus": "ਮਾਈਨਸ", "plus": "ਪਲੱਸ", "equals": "ਬਰਾਬਰ",+ "times": "ਗੁਣਾ", "divide": "ਭਾਗ",+ "squared": "ਦਾ ਵਰਗ", "sqrt": "ਵਰਗਮੂਲ",+ "lt": "ਤੋਂ ਘੱਟ", "gt": "ਤੋਂ ਵੱਧ",+ "plus_minus": "ਧਨ-ਰਿਣ",+ "at": "ਐਟ ਦ ਰੇਟ", "underscore": "ਅੰਡਰਸਕੋਰ", "dot": "ਡਾਟ",+ "slash": "ਸਲੈਸ਼", "hash": "ਹੈਸ਼", "amp": "ਅਤੇ",+ "half": "ਅੱਧਾ", "quarter": "ਚੌਥਾਈ", "three_quarters": "ਤਿੰਨ ਚੌਥਾਈ",+ "degree": "ਡਿਗਰੀ", "celsius": "ਡਿਗਰੀ ਸੈਲਸੀਅਸ", "fahrenheit": "ਡਿਗਰੀ ਫਾਰਨਹਾਈਟ",+ "minute": "ਮਿੰਟ", "second": "ਸਕਿੰਟ",+ }++ TIME_ON_HOUR = "{h} ਵਜੇ"+ TIME_HM = "{h} ਵੱਜ ਕੇ {m} ਮਿੰਟ"+ RANGE = "{a} ਤੋਂ {b}"+ RANGE_TO = "{a} ਤੋਂ {b} ਤੱਕ"+ RATIO = "{a} ਅਨੁਪਾਤ {b}"+ POWER = "{base} ਦੀ ਘਾਤ {exp}"+ FRACTION = "{num} ਬਟਾ {den}"+ DECADE_SHORT = "{tens} ਦੇ"+ DECADE_FULL = "{tens} ਦਾ ਦਹਾਕਾ"++ PERIODS = {"morning": "ਸਵੇਰੇ", "afternoon": "ਦੁਪਹਿਰ", "evening": "ਸ਼ਾਮ", "night": "ਰਾਤ"}++ TIME_MARKERS = ["ਵਜੇ", "ਵੱਜ ਕੇ", "ਵਜਕੇ", "ਵੱਜੇ"]+ PERIOD_DETECT = {"ਸਵੇਰੇ": "morning", "ਸਵੇਰ": "morning", "ਤੜਕੇ": "morning",+ "ਦੁਪਹਿਰ": "afternoon", "ਸ਼ਾਮ": "evening", "ਸ਼ਾਮੀਂ": "evening",+ "ਰਾਤ": "night", "ਰਾਤੀਂ": "night"}+ YEAR_WORDS = ["ਸਾਲ", "ਵਰ੍ਹਾ", "ਵਰ੍ਹੇ", "ਸੰਨ"]+ ID_KEYWORDS = ["ਨੰਬਰ", "ਖਾਤਾ", "ਖਾਤੇ", "ਕੋਡ", "ਆਰਡਰ", "ਫ਼ੋਨ", "ਫੋਨ", "ਮੋਬਾਈਲ", "ਮੋਬਾਇਲ", "ਅਕਾਊਂਟ", "ਅਕਾਊਂਟਵਿੱਚ", "ਪਿੰਨ", "ਆਈਡੀ", "ਪਾਸਵਰਡ", "ਟ੍ਰੇਨ", "ਐਕਸਪ੍ਰੈਸ", "ਪੀਐਨਆਰ", "ਕਾਰਡ", "ਰੈਫਰੈਂਸ", "ਟਿਕਟ", "ਓਟੀਪੀ", "ਯੂਜ਼ਰ", "ਕਿਸ਼ਤ", "ਅੰਕ", "ਲੈਣ-ਦੇਣ"]+ ID_AFTER_WORDS = ["ਡਾਇਲ", "ਕਾਲ", "ਸੰਪਰਕ"]+ NUMBER_WORD = "ਨੰਬਰ"+ ABBREV_UNITS = {"MINS":"ਮਿੰਟ", "MIN":"ਮਿੰਟ", "HRS":"ਘੰਟੇ", "HR":"ਘੰਟਾ", "SECS":"ਸਕਿੰਟ", "SEC":"ਸਕਿੰਟ", "KMS":"ਕਿਲੋਮੀਟਰ"}+ LABEL_WORDS = ["ਧਾਰਾ", "ਅਨੁਛੇਦ", "ਕਮਰਾ", "ਕਲਾਸ", "ਵਾਰਡ", "ਅਧਿਆਇ", "ਭਾਗ", "ਜਮਾਤ"]+ MINUTE_WORDS = ["ਮਿੰਟ"]+ SCALE_WORDS = {"ਕਰੋੜ": "crore", "ਲੱਖ": "lakh", "ਹਜ਼ਾਰ": "thousand", "ਹਜਾਰ": "thousand",+ "ਅਰਬ": "arab"}+ CURRENCY_WORDS = {"ਰੁਪਏ": "rupee", "ਰੁਪਿਆ": "rupee", "ਰੁਪਈਏ": "rupee", "ਰੁਪਿਏ": "rupee"}++ ORDINAL_EXCEPTIONS = {1: "ਪਹਿਲਾ", 2: "ਦੂਜਾ", 3: "ਤੀਜਾ", 4: "ਚੌਥਾ", 6: "ਛੇਵਾਂ"}+ ORDINAL_SUFFIX = "ਵਾਂ"+ ORDINAL_INPUT_SUFFIXES = ["ਵੀਂ", "ਵਾਂ", "ਵੇਂ", "ਵਾ"]++ def _ordinal_compose(self, n, src_suffix):+ # 12ਵੀਂ -> ਬਾਰਾਂਵੀਂ : cardinal + preserved suffix+ if src_suffix:+ return f"{self.cardinal(n)}{src_suffix}"+ if n in self.ORDINAL_EXCEPTIONS:+ return self.ORDINAL_EXCEPTIONS[n]+ return f"{self.cardinal(n)}{self.ORDINAL_SUFFIX}"+++class Tamil(LangBase):+ code = "ta"+ name = "Tamil"+ native_digits = "௦௧௨௩௪௫௬௭௮௯"+ COUNT_ONE = "ஒரு"++ ONES = [+ "பூஜ்ஜியம்", "ஒன்று", "இரண்டு", "மூன்று", "நான்கு",+ "ஐந்து", "ஆறு", "ஏழு", "எட்டு", "ஒன்பது",+ "பத்து", "பதினொன்று", "பன்னிரண்டு", "பதின்மூன்று", "பதினான்கு",+ "பதினைந்து", "பதினாறு", "பதினேழு", "பதினெட்டு", "பத்தொன்பது",+ "இருபது", "இருபத்தொன்று", "இருபத்திரண்டு", "இருபத்துமூன்று", "இருபத்துநான்கு",+ "இருபத்தைந்து", "இருபத்தாறு", "இருபத்தேழு", "இருபத்தெட்டு", "இருபத்தொன்பது",+ "முப்பது", "முப்பத்தொன்று", "முப்பத்திரண்டு", "முப்பத்துமூன்று", "முப்பத்துநான்கு",+ "முப்பத்தைந்து", "முப்பத்தாறு", "முப்பத்தேழு", "முப்பத்தெட்டு", "முப்பத்தொன்பது",+ "நாற்பது", "நாற்பத்தொன்று", "நாற்பத்திரண்டு", "நாற்பத்துமூன்று", "நாற்பத்துநான்கு",+ "நாற்பத்தைந்து", "நாற்பத்தாறு", "நாற்பத்தேழு", "நாற்பத்தெட்டு", "நாற்பத்தொன்பது",+ "ஐம்பது", "ஐம்பத்தொன்று", "ஐம்பத்திரண்டு", "ஐம்பத்துமூன்று", "ஐம்பத்துநான்கு",+ "ஐம்பத்தைந்து", "ஐம்பத்தாறு", "ஐம்பத்தேழு", "ஐம்பத்தெட்டு", "ஐம்பத்தொன்பது",+ "அறுபது", "அறுபத்தொன்று", "அறுபத்திரண்டு", "அறுபத்துமூன்று", "அறுபத்துநான்கு",+ "அறுபத்தைந்து", "அறுபத்தாறு", "அறுபத்தேழு", "அறுபத்தெட்டு", "அறுபத்தொன்பது",+ "எழுபது", "எழுபத்தொன்று", "எழுபத்திரண்டு", "எழுபத்துமூன்று", "எழுபத்துநான்கு",+ "எழுபத்தைந்து", "எழுபத்தாறு", "எழுபத்தேழு", "எழுபத்தெட்டு", "எழுபத்தொன்பது",+ "எண்பது", "எண்பத்தொன்று", "எண்பத்திரண்டு", "எண்பத்துமூன்று", "எண்பத்துநான்கு",+ "எண்பத்தைந்து", "எண்பத்தாறு", "எண்பத்தேழு", "எண்பத்தெட்டு", "எண்பத்தொன்பது",+ "தொண்ணூறு", "தொண்ணூற்றொன்று", "தொண்ணூற்றிரண்டு", "தொண்ணூற்றுமூன்று", "தொண்ணூற்றுநான்கு",+ "தொண்ணூற்றைந்து", "தொண்ணூற்றாறு", "தொண்ணூற்றேழு", "தொண்ணூற்றெட்டு", "தொண்ணூற்றொன்பது",+ ]+ HUNDRED = "நூறு"+ THOUSAND = "ஆயிரம்"+ LAKH = "லட்சம்"+ CRORE = "கோடி"++ # Fused hundreds (index 1..9) and their combining forms before a remainder.+ HUNDREDS = ["", "நூறு", "இருநூறு", "முந்நூறு", "நானூறு", "ஐந்நூறு",+ "அறுநூறு", "எழுநூறு", "எண்ணூறு", "தொள்ளாயிரம்"]+ HUNDREDS_COMB = ["", "நூற்று", "இருநூற்று", "முந்நூற்று", "நானூற்று", "ஐந்நூற்று",+ "அறுநூற்று", "எழுநூற்று", "எண்ணூற்று", "தொள்ளாயிரத்து"]++ LETTERS = {+ "A": "ஏ", "B": "பி", "C": "சி", "D": "டி", "E": "இ", "F": "எஃப்",+ "G": "ஜி", "H": "எச்", "I": "ஐ", "J": "ஜே", "K": "கே", "L": "எல்",+ "M": "எம்", "N": "என்", "O": "ஓ", "P": "பி", "Q": "கியூ", "R": "ஆர்",+ "S": "எஸ்", "T": "டி", "U": "யூ", "V": "வி", "W": "டபிள்யூ",+ "X": "எக்ஸ்", "Y": "ஒய்", "Z": "இசட்",+ }++ MONTHS = ["ஜனவரி", "பிப்ரவரி", "மார்ச்", "ஏப்ரல்", "மே", "ஜூன்",+ "ஜூலை", "ஆகஸ்ட்", "செப்டம்பர்", "அக்டோபர்", "நவம்பர்", "டிசம்பர்"]++ SYM = {+ "rupee": "ரூபாய்", "dollar": "டாலர்", "euro": "யூரோ", "pound": "பவுண்ட்",+ "cent": "சென்ட்",+ "percent": "சதவீதம்",+ "point": "புள்ளி",+ "minus": "மைனஸ்", "plus": "பிளஸ்", "equals": "சமம்",+ "times": "பெருக்கல்", "divide": "வகுத்தல்",+ "squared": "இன் வர்க்கம்", "sqrt": "வர்க்கமூலம்",+ "lt": "விடக் குறைவு", "gt": "விட அதிகம்",+ "plus_minus": "பிளஸ் மைனஸ்",+ "at": "அட் தி ரேட்", "underscore": "அண்டர்ஸ்கோர்", "dot": "டாட்",+ "slash": "ஸ்லாஷ்", "hash": "ஹேஷ்", "amp": "மற்றும்",+ "half": "அரை", "quarter": "கால்", "three_quarters": "முக்கால்",+ "degree": "டிகிரி", "celsius": "டிகிரி செல்சியஸ்",+ "fahrenheit": "டிகிரி ஃபாரன்ஹீட்",+ "minute": "நிமிடம்", "second": "வினாடி",+ }++ TIME_ON_HOUR = "{h} மணி"+ TIME_HM = "{h} மணி {m} நிமிடம்"+ RANGE = "{a} முதல் {b}"+ RANGE_TO = "{a} முதல் {b} வரை"+ RATIO = "{a} விகிதம் {b}"+ POWER = "{base} இன் அடுக்கு {exp}"+ FRACTION = "{num} வகுத்தல் {den}"+ DECADE_SHORT = "{tens}கள்"+ DECADE_FULL = "{tens}களின் தசாப்தம்"++ PERIODS = {"morning": "காலை", "afternoon": "மதியம்",+ "evening": "மாலை", "night": "இரவு"}++ TIME_MARKERS = ["மணிக்கு", "மணி"]+ MARKER_SUFFIXES = {"மணிக்கு": "க்கு"}+ PERIOD_DETECT = {"காலை": "morning", "அதிகாலை": "morning",+ "மதியம்": "afternoon", "நண்பகல்": "afternoon",+ "பிற்பகல்": "afternoon",+ "மாலை": "evening", "இரவு": "night"}+ YEAR_WORDS = ["ஆண்டு", "ஆண்டில்", "வருடம்", "வருடத்தில்", "வருஷம்"]+ ID_KEYWORDS = ["எண்", "நம்பர்", "கணக்கு", "தொலைபேசி", "போன்", "மொபைல்", "ஆர்டர்", "ஓடிபி", "பின்", "ஐடி", "கடவுச்சொல்", "ரயில்", "எக்ஸ்பிரஸ்", "பிஎன்ஆர்", "கார்டு", "குறியீடு", "டிக்கெட்", "கணக்கில்", "யூசர்", "தவணை", "இலக்கம்", "பரிவர்த்தனை"]+ ID_AFTER_WORDS = ["டயல்", "அழை", "தொடர்பு"]+ NUMBER_WORD = "எண்"+ ABBREV_UNITS = {"MINS":"நிமிடம்", "MIN":"நிமிடம்", "HRS":"மணி", "HR":"மணி", "SECS":"விநாடி", "SEC":"விநாடி", "KMS":"கிலோமீட்டர்"}+ LABEL_WORDS = ["பிரிவு", "சரத்து", "அறை", "வார்டு", "அத்தியாயம்",+ "வகுப்பு", "பாகம்", "கவுண்டர்", "கேட்"]+ MINUTE_WORDS = ["நிமிடம்", "நிமிடங்கள்", "நிமிஷம்"]+ SCALE_WORDS = {"கோடி": "crore", "கோடியே": "crore",+ "லட்சம்": "lakh", "லட்சத்து": "lakh", "இலட்சம்": "lakh",+ "ஆயிரம்": "thousand", "ஆயிரத்து": "thousand"}+ CURRENCY_WORDS = {"ரூபாய்": "rupee", "ரூ": "rupee", "ருபாய்": "rupee"}++ ORDINAL_EXCEPTIONS = {1: "முதலாவது"}+ ORDINAL_SUFFIX = "ஆவது"+ ORDINAL_INPUT_SUFFIXES = ["ஆவது", "வது", "ஆம்", "ம்"]++ # Consonants that double onto a preceding combining form (வல்லினம்).+ _DOUBLE = {"க": "க்", "ச": "ச்", "த": "த்", "ப": "ப்"}++ # ------------------------------------------------------------------+ # Dravidian composition: fused hundreds/thousands + sandhi joins.+ # ------------------------------------------------------------------+ def _sandhi_join(self, parts):+ """Join number parts; after a combining form ending -த்து/-ற்று a+ following க/ச/த/ப doubles onto it (ஆயிரத்துத் தொள்ளாயிரம்)."""+ out = [p for p in parts if p]+ for i in range(len(out) - 1):+ if out[i].endswith(("த்து", "ற்று")) and out[i + 1][0] in self._DOUBLE:+ out[i] += self._DOUBLE[out[i + 1][0]]+ return " ".join(out)++ def hundreds(self, h, rest):+ if rest:+ return self._sandhi_join([self.HUNDREDS_COMB[h], self.two_digit(rest)])+ return self.HUNDREDS[h]++ def under_thousand(self, n):+ if n < 100:+ return self.two_digit(n)+ return self.hundreds(n // 100, n % 100)++ def _thousands_word(self, t, combining):+ """1 -> ஆயிரம்/ஆயிரத்து; else fuse multiplier: final -ு drops before+ ஆ- (நான்கு+ஆயிரம் -> நான்காயிரம், ஐம்பத்துநான்கு -> ஐம்பத்துநான்காயிரம்)."""+ base = "ஆயிரத்து" if combining else "ஆயிரம்"+ if t == 1:+ return base+ return self.ONES[t][:-1] + "ா" + base[1:]++ def cardinal(self, n):+ if n < 0:+ return f"{self.SYM['minus']} {self.cardinal(-n)}"+ if n == 0:+ return self.ONES[0]+ crore, rest = divmod(n, 10 ** 7)+ lakh, rest = divmod(rest, 10 ** 5)+ thousand, low = divmod(rest, 1000)+ parts = []+ if crore:+ mult = "ஒரு" if crore == 1 else self.cardinal(crore)+ parts.append(f"{mult} " + ("கோடியே" if (lakh or thousand or low) else "கோடி"))+ if lakh:+ mult = "ஒரு" if lakh == 1 else self.two_digit(lakh)+ parts.append(f"{mult} " + ("லட்சத்து" if (thousand or low) else "லட்சம்"))+ if thousand:+ parts.append(self._thousands_word(thousand, bool(low)))+ if low:+ parts.append(self.under_thousand(low))+ return self._sandhi_join(parts)++ def year(self, y):+ """Tamil reads years as full cardinals:+ 1947 -> ஆயிரத்துத் தொள்ளாயிரத்து நாற்பத்தேழு,+ 2026 -> இரண்டாயிரத்து இருபத்தாறு."""+ return self.cardinal(y)++ def _ordinal_compose(self, n, src_suffix):+ # 12ஆவது/12வது -> பன்னிரண்டாவது; 12ஆம்/12ம் -> பன்னிரண்டாம்.+ suffix = "ஆம்" if src_suffix in ("ஆம்", "ம்") else "ஆவது"+ if n == 1:+ return "முதலாம்" if suffix == "ஆம்" else "முதலாவது"+ base = self.cardinal(n)+ if base[-1] in ("ு", "்"):+ # drop final -u / virama and merge the suffix vowel: -ாவது / -ாம்+ return base[:-1] + "ா" + suffix[1:]+ if base[-1] in ("ி", "ீ", "ை"):+ # glide insertion: கோடி -> கோடியாவது+ return base + "யா" + suffix[1:]+ return base + suffix++ # Tamil case markers attach with sandhi to noun-words+ _ATTACH_NOUNS = {"ரூபாய்", "டாலர்", "சதவீதம்", "மணி", "நிமிடம்",+ "விநாடி", "கிலோமீட்டர்", "கிலோ", "மீட்டர்", "லிட்டர்",+ "கிராம்", "டிகிரி", "மைல்"}++ def attach_postposition(self, rep, tok):+ t = tok.lstrip("-")+ last = rep.rsplit(" ", 1)[-1]+ base = rep[:len(rep)-len(last)]+ num_obl = {"ஒன்று":"ஒன்ற","இரண்டு":"இரண்ட","மூன்று":"மூன்ற",+ "நான்கு":"நான்க","ஐந்து":"ஐந்த","ஆறு":"ஆற","ஏழு":"ஏழ",+ "எட்டு":"எட்ட","ஒன்பது":"ஒன்பத","பத்து":"பத்த","பூஜ்ஜியம்":"பூஜ்ஜியத்த"}+ if last in num_obl: # number + case (hyphen markers)+ if t in ("இல்","ல்"): return base+num_obl[last]+"ில்"+ if t in ("க்கு","கு"): return base+num_obl[last]+"ிற்கு"+ if t in ("இலிருந்து","ல்இருந்து"): return base+num_obl[last]+"ிலிருந்து"+ return None+ if last not in self._ATTACH_NOUNS:+ return None+ if t in ("க்கு", "கு"):+ if last == "நிமிடம்":+ return base + "நிமிடத்திற்கு"+ if last == "சதவீதம்":+ return base + "சதவீதத்திற்கு"+ return base + last + "க்கு"+ if t in ("இல்", "ல்", "இலிருந்து", "ல்இருந்து"):+ if last.endswith("ம்"):+ return base + last[:-2] + "த்தில்"+ return base + last + "இல்"+ return None+++class Telugu(LangBase):+ code = "te"+ name = "Telugu"+ native_digits = "౦౧౨౩౪౫౬౭౮౯"++ ONES = [+ "సున్నా", "ఒకటి", "రెండు", "మూడు", "నాలుగు", "ఐదు", "ఆరు", "ఏడు", "ఎనిమిది", "తొమ్మిది",+ "పది", "పదకొండు", "పన్నెండు", "పదమూడు", "పద్నాలుగు", "పదిహేను", "పదహారు", "పదిహేడు", "పద్దెనిమిది", "పందొమ్మిది",+ "ఇరవై", "ఇరవై ఒకటి", "ఇరవై రెండు", "ఇరవై మూడు", "ఇరవై నాలుగు", "ఇరవై ఐదు", "ఇరవై ఆరు", "ఇరవై ఏడు", "ఇరవై ఎనిమిది", "ఇరవై తొమ్మిది",+ "ముప్పై", "ముప్పై ఒకటి", "ముప్పై రెండు", "ముప్పై మూడు", "ముప్పై నాలుగు", "ముప్పై ఐదు", "ముప్పై ఆరు", "ముప్పై ఏడు", "ముప్పై ఎనిమిది", "ముప్పై తొమ్మిది",+ "నలభై", "నలభై ఒకటి", "నలభై రెండు", "నలభై మూడు", "నలభై నాలుగు", "నలభై ఐదు", "నలభై ఆరు", "నలభై ఏడు", "నలభై ఎనిమిది", "నలభై తొమ్మిది",+ "యాభై", "యాభై ఒకటి", "యాభై రెండు", "యాభై మూడు", "యాభై నాలుగు", "యాభై ఐదు", "యాభై ఆరు", "యాభై ఏడు", "యాభై ఎనిమిది", "యాభై తొమ్మిది",+ "అరవై", "అరవై ఒకటి", "అరవై రెండు", "అరవై మూడు", "అరవై నాలుగు", "అరవై ఐదు", "అరవై ఆరు", "అరవై ఏడు", "అరవై ఎనిమిది", "అరవై తొమ్మిది",+ "డెబ్బై", "డెబ్బై ఒకటి", "డెబ్బై రెండు", "డెబ్బై మూడు", "డెబ్బై నాలుగు", "డెబ్బై ఐదు", "డెబ్బై ఆరు", "డెబ్బై ఏడు", "డెబ్బై ఎనిమిది", "డెబ్బై తొమ్మిది",+ "ఎనభై", "ఎనభై ఒకటి", "ఎనభై రెండు", "ఎనభై మూడు", "ఎనభై నాలుగు", "ఎనభై ఐదు", "ఎనభై ఆరు", "ఎనభై ఏడు", "ఎనభై ఎనిమిది", "ఎనభై తొమ్మిది",+ "తొంభై", "తొంభై ఒకటి", "తొంభై రెండు", "తొంభై మూడు", "తొంభై నాలుగు", "తొంభై ఐదు", "తొంభై ఆరు", "తొంభై ఏడు", "తొంభై ఎనిమిది", "తొంభై తొమ్మిది",+ ]+ # Indo-Aryan style fields kept for interface completeness; the fused+ # forms below (వంద/నూట/వందలు/వందల etc.) are what cardinal() actually uses.+ HUNDRED = "వంద"+ THOUSAND = "వెయ్యి"+ LAKH = "లక్ష"+ CRORE = "కోటి"++ LETTERS = {+ "A": "ఏ", "B": "బీ", "C": "సీ", "D": "డీ", "E": "ఈ", "F": "ఎఫ్",+ "G": "జీ", "H": "హెచ్", "I": "ఐ", "J": "జే", "K": "కే", "L": "ఎల్",+ "M": "ఎం", "N": "ఎన్", "O": "ఓ", "P": "పీ", "Q": "క్యూ", "R": "ఆర్",+ "S": "ఎస్", "T": "టీ", "U": "యూ", "V": "వీ", "W": "డబ్ల్యూ",+ "X": "ఎక్స్", "Y": "వై", "Z": "జెడ్",+ }++ MONTHS = ["జనవరి", "ఫిబ్రవరి", "మార్చి", "ఏప్రిల్", "మే", "జూన్",+ "జూలై", "ఆగస్టు", "సెప్టెంబర్", "అక్టోబర్", "నవంబర్", "డిసెంబర్"]+ MONTH_ALIASES = {"సెప్టెంబరు": 9, "అక్టోబరు": 10, "నవంబరు": 11, "డిసెంబరు": 12}++ SYM = {+ "rupee": "రూపాయలు", "dollar": "డాలర్లు", "euro": "యూరోలు",+ "pound": "పౌండ్లు", "cent": "సెంట్లు",+ "percent": "శాతం", "paisa": "పైసలు",+ "point": "పాయింట్",+ "minus": "మైనస్", "plus": "ప్లస్", "equals": "సమానం",+ "times": "ఇంటూ", "divide": "భాగించగా",+ "squared": "వర్గం", "sqrt": "వర్గమూలం",+ "lt": "కంటే తక్కువ", "gt": "కంటే ఎక్కువ",+ "plus_minus": "ప్లస్ మైనస్",+ "at": "ఎట్ ద రేట్", "underscore": "అండర్ స్కోర్", "dot": "డాట్",+ "slash": "స్లాష్", "hash": "హ్యాష్", "amp": "మరియు",+ "half": "అర", "quarter": "పావు", "three_quarters": "ముప్పావు",+ "degree": "డిగ్రీలు", "celsius": "డిగ్రీల సెల్సియస్", "fahrenheit": "డిగ్రీల ఫారెన్హీట్",+ "minute": "నిమిషాలు", "per": "పర్", "second": "సెకన్లు",+ }++ TIME_ON_HOUR = "{h} గంటలు"+ TIME_HM = "{h} గంటల {m} నిమిషాలు"+ RANGE = "{a} నుంచి {b}"+ RANGE_TO = "{a} నుంచి {b} వరకు"+ RATIO = "{a} నిష్పత్తి {b}"+ POWER = "{base} పవర్ {exp}"+ FRACTION = "{num} బై {den}"+ DECADE_SHORT = "{tens}ల"+ DECADE_FULL = "{tens}ల దశకం"++ PERIODS = {"morning": "ఉదయం", "afternoon": "మధ్యాహ్నం",+ "evening": "సాయంత్రం", "night": "రాత్రి"}++ TIME_MARKERS = ["గంటలకు", "గంటలకి", "గంటకు", "గంటకి", "గంటల", "గంటలు", "గం"]+ MARKER_SUFFIXES = {"గంటలకు": "కు", "గంటలకి": "కి", "గంటకు": "కు",+ "గంటకి": "కి", "నిమిషాలకు": "కు", "నిమిషానికి": "కి"}+ PERIOD_DETECT = {"ఉదయం": "morning", "పొద్దున": "morning", "పొద్దున్న": "morning",+ "తెల్లవారుజామున": "morning", "మధ్యాహ్నం": "afternoon",+ "సాయంత్రం": "evening", "రాత్రి": "night"}+ YEAR_WORDS = ["సంవత్సరం", "సంవత్సరంలో", "ఏడాది", "సం"]+ ID_KEYWORDS = ["నంబర్", "నంబరు", "నెంబర్", "నెంబరు", "ఖాతా", "ఫోన్", "మొబైల్", "కోడ్", "ఆర్డర్", "ఎక్స్ప్రెస్", "express", "అకౌంట్", "టికెట్", "రిజిస్ట్రేషన్", "యూజర్", "వాయిదా", "అంకె", "లావాదేవీ", "పిన్"]+ ID_AFTER_WORDS = ["ఎండ్", "ముగిసే", "ముగుస్తుంది", "చివర", "చివరి", "అంకెలతో", "డయల్", "పిన్", "పిన్కోడ్", "pin", "pincode", "కాల్", "సంప్రదించండి"]+ LABEL_WORDS = ["గది", "వార్డు", "అధికరణ", "అధ్యాయం", "తరగతి", "భాగం", "సెక్షన్",+ "ప్లాట్ఫారమ్", "ప్లాట్ఫారమ్", "సీటు", "సీట్", "కోచ్", "గేట్",+ "రూమ్", "హాల్", "టెర్మినల్", "కౌంటర్"]+ MINUTE_WORDS = ["నిమిషాలకు", "నిమిషానికి", "నిమిషాలు", "నిమిషాల", "నిమిషం"]+ SCALE_WORDS = {"కోటి": "crore", "కోటీ": "crore", "కోట్లు": "crore", "కోట్ల": "crore",+ "లక్ష": "lakh", "లక్షా": "lakh", "లక్షలు": "lakh", "లక్షల": "lakh",+ "వెయ్యి": "thousand", "వేలు": "thousand", "వేల": "thousand"}+ CURRENCY_WORDS = {"రూపాయలు": "rupee", "రూపాయల": "rupee", "రూపాయి": "rupee",+ "రూపాయ": "rupee", "రూ": "rupee"}++ ORDINAL_EXCEPTIONS = {1: "మొదటి"}+ ORDINAL_SUFFIX = "వ"+ ORDINAL_INPUT_SUFFIXES = ["వ", "వది", "ో"]++ # ==================================================================+ # Dravidian composition — fused/sandhi forms (overrides base).+ # ==================================================================++ def hundreds(self, h, rest):+ """100 వంద / నూట; 200+ వందలు / combining వందల."""+ if h == 1:+ if rest:+ return f"నూట {self.ONES[rest]}"+ return "వంద"+ if rest:+ return f"{self.ONES[h]} వందల {self.ONES[rest]}"+ return f"{self.ONES[h]} వందలు"++ def under_thousand(self, n):+ if n < 100:+ return self.ONES[n]+ return self.hundreds(n // 100, n % 100)++ def _thousands(self, t, has_rest):+ """t in 1..99. 1000 వెయ్యి (same before a remainder); 2+ వేలు/వేల."""+ if t == 1:+ return "వెయ్యి"+ return f"{self.ONES[t]} {'వేల' if has_rest else 'వేలు'}"++ def _lakhs(self, l, has_rest):+ """l in 1..99. లక్ష / sandhi లక్షా; 2+ లక్షలు/లక్షల."""+ if l == 1:+ return "లక్షా" if has_rest else "లక్ష"+ return f"{self.ONES[l]} {'లక్షల' if has_rest else 'లక్షలు'}"++ def _crores(self, c, has_rest):+ """కోటి / sandhi కోటీ; 2+ కోట్లు/కోట్ల."""+ if c == 1:+ return "కోటీ" if has_rest else "కోటి"+ return f"{self.cardinal(c)} {'కోట్ల' if has_rest else 'కోట్లు'}"++ def cardinal(self, n):+ if n < 0:+ return f"{self.SYM['minus']} {self.cardinal(-n)}"+ if n < 100:+ return self.ONES[n]+ if n < 1000:+ return self.under_thousand(n)+ crore, rest = divmod(n, 10**7)+ lakh, rest = divmod(rest, 10**5)+ thousand, sub = divmod(rest, 1000)+ parts = []+ if crore:+ parts.append(self._crores(crore, bool(lakh or thousand or sub)))+ if lakh:+ parts.append(self._lakhs(lakh, bool(thousand or sub)))+ if thousand:+ parts.append(self._thousands(thousand, bool(sub)))+ if sub:+ parts.append(self.under_thousand(sub))+ return " ".join(parts)++ def year(self, y):+ """Spoken Telugu reads 1100-1999 hundred-style — 1947 పందొమ్మిది+ వందల నలభై ఏడు (the "వెయ్యి తొమ్మిది వందల…" full cardinal sounds+ stiff; flagged by native review). 2000+ stays full cardinal:+ 2026 రెండు వేల ఇరవై ఆరు."""+ if 1100 <= y <= 1999:+ hi, lo = divmod(y, 100)+ if lo:+ return f"{self.ONES[hi]} వందల {self.ONES[lo]}"+ return f"{self.ONES[hi]} వందలు"+ return self.cardinal(y)++ def _ordinal_compose(self, n, src_suffix):+ # Formal -వ ordinal with the regular Telugu stem change:+ # రెండు -> రెండవ, ఎనిమిది -> ఎనిమిదవ, ఇరవై -> ఇరవయ్యవ, వంద -> వందవ.+ if n in self.ORDINAL_EXCEPTIONS and not src_suffix:+ return self.ORDINAL_EXCEPTIONS[n]+ word = self.cardinal(n)+ if word.endswith("ు") or word.endswith("ి"): # ు / ి matra+ stem = word[:-1]+ elif word.endswith("ై"): # ై matra+ stem = word[:-1] + "య్య"+ else:+ stem = word+ return f"{stem}{self.ORDINAL_SUFFIX}"++ # ------------------------------------------------------------------+ # Inherited Telugu grammar hooks. Upstream cited an external review, not+ # independently verified human/native-speaker approval.+ # ------------------------------------------------------------------++ # metric units read as full words, not letter names+ UNIT_WORDS = {+ "KM": "కిలోమీటర్లు", "KG": "కిలోలు", "GM": "గ్రాములు",+ "MG": "మిల్లీగ్రాములు", "MCG": "మైక్రోగ్రాములు",+ "ML": "మిల్లీలీటర్లు", "CM": "సెంటీమీటర్లు", "MM": "మిల్లీమీటర్లు",+ "H": "అవర్", "HR": "అవర్",+ }++ NUMBER_WORD = "నంబర్"+ ABBREV_UNITS = {"MINS": "నిమిషాలు", "MIN": "నిమిషాలు",+ "HRS": "గంటలు", "HR": "గంట",+ "SECS": "సెకన్లు", "SEC": "సెకన్లు", "KMS": "కిలోమీటర్లు"}++ # singular noun forms used after "1" (ఒక రూపాయి, ఒక గంట)+ _NOUN_SINGULAR = {"రూపాయలు": "రూపాయి", "డాలర్లు": "డాలర్",+ "గంటలు": "గంట", "నిమిషాలు": "నిమిషం", "పైసలు": "పైసా", "సెకన్లు": "సెకను"}++ def _oblique_last(self, words):+ """Oblique stem for the final word before an appended noun:+ వందలు/వేలు/లక్షలు/కోట్లు -> వందల/వేల/లక్షల/కోట్ల ; ఒకటి -> ఒక."""+ last = words.rsplit(" ", 1)[-1]+ if last.endswith("లు"):+ return words[:-1] # strip ు : వందలు -> వందల+ return words++ def decimal(self, int_part, frac_digits):+ frac = " ".join(self.digit(int(d)) for d in frac_digits)+ return f"{self._oblique_last(self.cardinal(int_part))} " \+ f"{self.SYM['point']} {frac}"++ def join_amount(self, words, noun):+ if words == "ఒకటి":+ return f"ఒక {self._NOUN_SINGULAR.get(noun, noun)}"+ return f"{self._oblique_last(words)} {noun}"++ def time_phrase(self, h, m, period_key=None):+ h12 = h % 12 or 12+ hw = "ఒక" if h12 == 1 else self.two_digit(h12)+ hnoun = "గంట" if h12 == 1 else ("గంటలు" if m == 0 else "గంటల")+ if h12 == 1 and m != 0:+ hnoun = "గంట"+ if m == 0:+ core = f"{hw} {hnoun}"+ elif m == 1:+ core = f"{hw} {hnoun} ఒక నిమిషం"+ else:+ core = f"{hw} {hnoun} {self.two_digit(m)} నిమిషాలు"+ if period_key:+ return f"{self.PERIODS[period_key]} {core}"+ return core++ # postpositions appearing as a separate token right after a rendered+ # span get attached with correct sandhi ("గంటలు కి" -> "గంటలకు")+ _PP_SPACED = {"వరకు", "దాకా", "లోపు", "నుండి", "నుంచి",+ "పాటు", "క్రితం", "తర్వాత", "ముందు", "చొప్పున", "కంటే", "దగ్గర", "లోపల"}+ _PP_GLUE = {"కి", "కు", "ని", "న", "నే", "కే", "లో", "తో",+ "లోని", "లోకి", "లోనే", "కల్లా"}+ # గా keeps the nominative: రూపాయలు + గా -> రూపాయలుగా+ _PP_NOMINATIVE = {"గా", "గానే"}+ # common counted nouns: a plural-final cardinal right before these takes+ # the oblique stem (మూడు లక్షలు రూపాయలు -> మూడు లక్షల రూపాయలు)+ _COUNT_NOUNS = {"రూపాయలు", "మంది", "కిలోలు", "కిలోమీటర్లు", "గంటలు",+ "నిమిషాలు", "రోజులు", "సంవత్సరాలు", "ఏళ్లు", "సార్లు",+ "మార్కులు", "ఓట్లు", "సీట్లు", "పరుగులు", "వికెట్లు",+ "లీటర్లు", "గ్రాములు", "టన్నులు", "ఎకరాలు", "శాతం",+ "కోట్లు", "లక్షలు", "వడ్డీ", "జీతం", "ఖర్చు",+ "ధర", "ఆదాయం", "లాభం", "నష్టం", "పెట్టుబడి", "రుణం",+ "జరిమానా", "బడ్జెట్", "మోతాదు", "మాత్ర", "మాత్రలు", "టాబ్లెట్", "కోట్ల", "లక్షల",+ "దూరం", "బరువు", "వేగం", "మైళ్లు", "మైళ్ళు", "అడుగులు", "సెకన్లు",+ "పేజీలు", "సమయం", "సమయానికి"}++ def scale_noun(self, canon, numstr):+ one = numstr.replace(",", "") == "1"+ return {"crore": "కోటి" if one else "కోట్లు",+ "lakh": "లక్ష" if one else "లక్షలు",+ "thousand": "వెయ్యి" if one else "వేలు"}.get(canon, canon)++ _PP_ROMAN = {"ki": "కి", "ku": "కు", "ni": "ని", "lo": "లో",+ "ga": "గా", "ke": "కే", "varaku": "వరకు", "nunchi": "నుంచి",+ "nundi": "నుండి", "daggara": "దగ్గర"}++ def attach_postposition(self, rep, tok):+ tok = self._PP_ROMAN.get(tok.lower(), tok)+ last = rep.rsplit(" ", 1)[-1]+ if rep == "ఒకటి" and tok[:1].isascii() and tok[:1].isalpha():+ return "ఒక " + tok # 1 litre -> ఒక litre+ if not last or not ("ఀ" <= last[-1] <= "౿"):+ return None # last word not Telugu (Latin unit etc.)+ if last in self.LETTERS.values():+ return None # bare letter names take no glued case+ if tok == last:+ return rep # duplicate word (వరకు వరకు) — consume+ plural = last.endswith("లు")+ if tok in self._PP_NOMINATIVE:+ return rep + tok # రూపాయలు గా -> రూపాయలుగా+ base_tok = tok.replace("\u200c", "")+ for end in ("ను", "ని", "కు", "కి", "లో", "గా", "తో", "పై"):+ if base_tok.endswith(end) and base_tok[:-len(end)] in self._COUNT_NOUNS:+ base_tok = base_tok[:-len(end)]+ break+ if plural and base_tok in self._COUNT_NOUNS:+ return rep[:-1] + " " + tok+ if rep == "ఒకటి" and tok in self._COUNT_NOUNS:+ return "ఒక " + self._NOUN_SINGULAR.get(tok, tok)+ if tok in self._PP_SPACED:+ return (rep[:-1] if plural else rep) + " " + tok+ if tok not in self._PP_GLUE:+ return None+ if last == "శాతం" and tok in ("కి", "కు"):+ return rep[:-1] + "ానికి" # శాతం కి -> శాతానికి+ if plural:+ if tok in ("కి", "కు"):+ return rep[:-1] + tok # keep the source marker: గంటలు కి -> గంటలకి+ if tok == "ని":+ return rep[:-1] + "ను" # రూపాయలు ని -> రూపాయలను+ return rep[:-1] + tok # గంటలు లో -> గంటలలో+ if tok in ("కి", "కు"):+ return rep + tok # keep the source marker: ఐదు కి -> ఐదుకి+ return rep + tok+++class Assamese(Bengali):+ """Assamese lexicon; Bengali grammar/entries remain the documented fallback.++ Number forms: AI4Bharat data; Gregorian months: Unicode CLDR as.xml.+ No new inference dependency and no translation of customer prose.+ """+ code = "as"+ name = "Assamese"+ if __package__:+ from .assamese_numbers import ONES, HUNDREDS+ else:+ from assamese_numbers import ONES, HUNDREDS+ HUNDRED = "শ"+ THOUSAND = "হাজাৰ"+ MONTHS = ['জানুৱাৰী', 'ফেব্ৰুৱাৰী', 'মাৰ্চ', 'এপ্ৰিল', 'মে’', 'জুন', 'জুলাই', 'আগষ্ট', 'ছেপ্তেম্বৰ', 'অক্টোবৰ', 'নৱেম্বৰ', 'ডিচেম্বৰ']+ SYM = {**Bengali.SYM, "rupee": "টকা", "paisa": "পইচা", "dollar": "ডলাৰ",+ "euro": "ইউৰো", "pound": "পাউণ্ড"}+ CURRENCY_WORDS = {**Bengali.CURRENCY_WORDS, "টকা": "rupee", "টকাৰ": "rupee",+ "টকাত": "rupee", "ৰুপী": "rupee"}+ SCALE_WORDS = {**Bengali.SCALE_WORDS, "হাজাৰ": "thousand"}+ ID_KEYWORDS = Bengali.ID_KEYWORDS + ["নম্বৰ", "একাউণ্ট", "কাৰ্ড", "নম্বৰত", "অংক"]+ NUMBER_WORD = "নম্বৰ"+ YEAR_WORDS = Bengali.YEAR_WORDS + ["চন", "চনত", "বছৰ", "বছৰত"]+ TIME_HM = "{h} বাজি {m} মিনিট"+ RANGE = "{a}ৰ পৰা {b}"+ RANGE_TO = "{a}ৰ পৰা {b}লৈ"+ FRACTION = "{num} বাই {den}"+ SINGULAR_NOUNS = {}++ def hundreds(self, h, rest):+ return self.HUNDREDS[h] + (" " + self.two_digit(rest) if rest else "")++ def year(self, y):+ return self.cardinal(y)++LANGUAGES = {cls.code: cls() for cls in (+ Hindi, Bengali, Assamese, Gujarati, Kannada, Malayalam, Marathi, Odia, Punjabi, Tamil, Telugu+)}diff --git a/maya3/text/tn/normalize.py b/maya3/text/tn/normalize.pynew file mode 100644index 0000000..99cff23--- /dev/null+++ b/maya3/text/tn/normalize.py@@ -0,0 +1,2195 @@+"""Dependency-free, reviewable TTS normalization.++Indian English and ten Indic language tables share one corrected parser.+The selected locale controls numbers, currency, dates, units and identifiers;+it does not translate prose or choose/change the model conditioning tag.+Hindi speech output folds nukta and ends standalone है with a danda outside+explicit question sentences (ending in ?).+These are intentional pronunciation/pause workarounds, not spelling corrections.+Invalid/ambiguous tokens fall back to digit and separator words.+FR3_TN_STRICT=1 retains the strict audit contract.+See docs/NORMALIZATION_REVIEW.md for the contract and remaining listening gates.+"""+# -*- coding: utf-8 -*-+# The former generator/indic_norm package is absent from this repository.+# This tracked file is the source of truth; protect edits with tests/test_normalize.py.+import re+import os+import json+import sys+import argparse+from datetime import date+import unicodedata+from functools import lru_cache++# Keep CLI execution and the imported table module on the same LangBase class.+if __name__ == "__main__":+ sys.modules.setdefault("normalize", sys.modules[__name__])+++LANGUAGE_NAMES = {"en-IN": "Indian English", "hi": "Hindi", "te": "Telugu",+ "ta": "Tamil", "bn": "Bengali", "as": "Assamese", "gu": "Gujarati", "kn": "Kannada",+ "ml": "Malayalam", "mr": "Marathi", "or": "Odia", "pa": "Punjabi"}+_LANGUAGE_ALIASES = {alias.lower(): code for code, name in LANGUAGE_NAMES.items()+ for alias in (code, name, code if code == "en-IN" else code + "-IN")}+_LANGUAGE_ALIASES.update({"en": "en-IN", "english": "en-IN", "en-us": "en-IN",+ "en-gb": "en-IN", "indian-english": "en-IN", "oriya": "or", "od": "or"})++# Input aliases, not translations of arbitrary prose. Keep identifiers digitwise+# even when callers write OTP in native script (including Indian English mode).+_OTP_INPUT_WORDS = {"ओटीपी", "ఓటీపీ", "ఓటిపి", "ஓடிபி", "ஓடீபி", "ওটিপি",+ "ઓટીપી", "ಒಟಿಪಿ", "ಓಟಿಪಿ", "ഒടിപി", "ഓടിപി", "ଓଟିପି", "ਓਟੀਪੀ"}+_PAISA_INPUT_WORDS = {"paise", "paisa", "पैसा", "पैसे", "పైసా", "పైసలు", "பைசா",+ "পয়সা", "પૈસા", "ಪೈಸೆ", "പൈസ", "ପଇସା", "ਪੈਸਾ", "ਪੈਸੇ"}+++def resolve_language(language):+ if not isinstance(language, str) or language.lower() not in _LANGUAGE_ALIASES:+ raise NormalizationError("unsupported_normalization_language", "Choose one of the documented normalization languages.")+ return _LANGUAGE_ALIASES[language.lower()]+++@lru_cache(maxsize=12)+def language_table(language):+ code = resolve_language(language)+ if code == "en-IN":+ return LANG+ if __package__:+ from .indic_languages import LANGUAGES+ else:+ from indic_languages import LANGUAGES+ return LANGUAGES[code]+++class NormalizationError(ValueError):+ """A safe-to-return error code. Never includes the caller's financial text."""+ def __init__(self, code, message, span=None, source=None):+ self.span, self.source = span, source+ self.code = code+ super().__init__(message)+++_TAMIL_MONTHS = ["ஜனவரி", "பிப்ரவரி", "மார்ச்", "ஏப்ரல்", "மே", "ஜூன்",+ "ஜூலை", "ஆகஸ்ட்", "செப்டம்பர்", "அக்டோபர்", "நவம்பர்", "டிசம்பர்"]+# Calendar days only. Native-speaker/audio review is required before rollout.+_TAMIL_ORDINALS = ["", "முதலாம்", "இரண்டாம்", "மூன்றாம்", "நான்காம்", "ஐந்தாம்",+ "ஆறாம்", "ஏழாம்", "எட்டாம்", "ஒன்பதாம்", "பத்தாம்", "பதினொன்றாம்",+ "பன்னிரண்டாம்", "பதின்மூன்றாம்", "பதினான்காம்", "பதினைந்தாம்", "பதினாறாம்",+ "பதினேழாம்", "பதினெட்டாம்", "பத்தொன்பதாம்", "இருபதாம்", "இருபத்தொன்றாம்",+ "இருபத்திரண்டாம்", "இருபத்துமூன்றாம்", "இருபத்துநான்காம்", "இருபத்தைந்தாம்",+ "இருபத்தாறாம்", "இருபத்தேழாம்", "இருபத்தெட்டாம்", "இருபத்தொன்பதாம்",+ "முப்பதாம்", "முப்பத்தொன்றாம்"]+++def _ascii_digits(text):+ # str.isdigit also accepts superscripts. Only Unicode DECIMAL digits belong+ # here; keep math superscripts for the math matcher.+ return "".join(str(unicodedata.decimal(c)) if c.isdecimal() else c for c in text)+++# Hindi speech compatibility, not a general Unicode diacritic remover. Apply to+# FINAL output because number/date/letter/URL expansions can introduce nukta.+# Keep every other script, accent, vowel sign and nasal mark untouched.+_HINDI_NUKTA_FOLD = str.maketrans({+ "\u093c": None,+ "\u0929": "\u0928", "\u0931": "\u0930", "\u0934": "\u0933",+ "\u0958": "\u0915", "\u0959": "\u0916", "\u095a": "\u0917",+ "\u095b": "\u091c", "\u095c": "\u0921", "\u095d": "\u0922",+ "\u095e": "\u092b", "\u095f": "\u092f",+})+++def _calendar_check(day, month, year=2000, span=None):+ # A missing year can include Feb 29; never invent a year in the output.+ try:+ date(year, month, day)+ except ValueError:+ raise NormalizationError("invalid_date", "Invalid calendar date; correct the input.", span=span) from None+++def _sentence_before(text, start):+ return re.split(r"[.!?;।॥\n]", text[max(0, start - 100):start])[-1]+++def _sentence_after(text, end):+ return re.split(r"[.!?;।॥\n]", text[end:end + 100])[0]+++def _valid_grouping(number):+ integer = number.lstrip("+-−").split(".")[0]+ return "," not in integer or bool(re.fullmatch(+ r"[0-9]{1,3}(?:,[0-9]{3})+|[0-9]{1,2}(?:,[0-9]{2})*,[0-9]{3}", integer))+++def _month_lookup(locale):+ return {**_ENGLISH_MONTHS, **{name.lower(): i + 1 for i, name in enumerate(locale.MONTHS)},+ **{name.lower(): i for name, i in locale.MONTH_ALIASES.items()}}+++def validate_text(text, *, date_order="DMY", two_digit_year_base=None, language="en-IN"):+ """Validate before destructive cleanup. Dates default to explicit DMY policy.++ Two-digit years require a caller-supplied century (1900 or 2000). Short dates+ in date context must be spelled out; ordinary fractions remain fractions.+ Plain text only: SSML/templates are rejected, not stripped and spoken.+ """+ if not isinstance(text, str):+ raise NormalizationError("invalid_text", "text must be a string.")+ if len(text) > 20000:+ raise NormalizationError("text_too_long", "text exceeds the 20000 character limit.")+ if date_order not in ("DMY", "MDY"):+ raise NormalizationError("invalid_date_order", "date_order must be DMY or MDY.")+ if two_digit_year_base is not None and (type(two_digit_year_base) is not int or two_digit_year_base not in (1900, 2000)):+ raise NormalizationError("invalid_century", "two_digit_year_base must be 1900 or 2000.")+ locale = language_table(language)+ t = _ascii_digits(text)+ if (bad := re.search(r"<\s*(?:/?[A-Za-z_]|[!?])|[{}]|\$\{", t)):+ raise NormalizationError("markup_or_placeholder", "Resolve templates and send plain text, not markup/SSML.", span=bad.span())+ for i, c in enumerate(t):+ if (unicodedata.category(c) == "Cc" and c not in "\n\r\t") or unicodedata.category(c) == "Co":+ raise NormalizationError("control_character", "Unsupported control character in text.", span=(i, i + 1))+ # URI numeric components are identifiers, not dates, amounts or clocks.+ t = re.sub(r"https?://\S+|www\.\S+|\b[\w.%+\-]+@[\w.\-]+\.[A-Za-z]{2,}", lambda m: " " * len(m[0]), t)+ if (bad := re.search(r"[0-9]{31,}", t)):+ raise NormalizationError("number_too_long", "Numeric spans are limited to 30 digits.", span=bad.span())+ if (bad := re.search(r"\d{4}-\d{2}-\d{2}T\d", t, re.I)):+ raise NormalizationError("unsupported_timestamp", "Spell out the date, time and timezone separately.", span=bad.span())+ for m in re.finditer(r"(?<![\w.])[+-]?[0-9][0-9,]*(?:\.[0-9]+)?", t):+ if len(re.sub(r"\D", "", m[0])) > 30:+ raise NormalizationError("number_too_long", "Numeric spans are limited to 30 digits.", span=m.span())+ if not _valid_grouping(m[0].rstrip(",")):+ raise NormalizationError("invalid_grouping", "Invalid number grouping; send ungrouped digits or standard grouping.", span=m.span())+ for m in re.finditer(r"(?<![\w\d])([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?!\d)", t):+ _calendar_check(int(m[3]), int(m[2]), int(m[1]), span=m.span())+ for m in re.finditer(r"(?<![\w\d-])([0-9]{1,2})([/.-])([0-9]{1,2})\2([0-9]{2,4})(?!\d)", t):+ y = int(m[4])+ if len(m[4]) != 4:+ if len(m[4]) != 2 or two_digit_year_base is None:+ raise NormalizationError("ambiguous_year", "Use a four-digit year or explicitly configure the century.", span=m.span())+ y += two_digit_year_base+ a, b = int(m[1]), int(m[3])+ _calendar_check(a if date_order == "DMY" else b, b if date_order == "DMY" else a, y, span=m.span())+ months = {**{name: i + 1 for i, name in enumerate(_TAMIL_MONTHS)}, **_month_lookup(locale)}+ month_re = "|".join(sorted(map(re.escape, months), key=len, reverse=True))+ ordinal_re = "|".join(sorted(map(re.escape, set(locale.ORDINAL_INPUT_SUFFIXES) | {"st", "nd", "rd", "th", "ஆம்", "ம்"}), key=len, reverse=True))+ for pattern, reverse in [+ (rf"(?<!\w)([0-9]{{1,2}})(?:-?(?:{ordinal_re}))?[ -]+({month_re})(?!\w)(?:[ ,\-]+([0-9]{{4}}))?", False),+ (rf"(?<!\w)({month_re})[ -]+([0-9]{{1,2}})(?:-?(?:{ordinal_re}))?(?!\d)(?:,?\s+([0-9]{{4}}))?", True),+ ]:+ for m in re.finditer(pattern, t, re.I):+ day, month = (m[2], m[1]) if reverse else (m[1], m[2])+ _calendar_check(int(day), months[month.lower()], int(m[3]) if m[3] else 2000, span=m.span())+ tamil_month_re = "|".join(_TAMIL_MONTHS)+ for m in re.finditer(rf"({tamil_month_re})\s+(\d{{1,2}})(?:-?(?:ஆம்|ம்))?(?:\s*தேதி)?(?:\s+(\d{{4}}))?", t):+ _calendar_check(int(m[2]), months[m[1]], int(m[3]) if m[3] else 2000, span=m.span())+ if (bad := re.search(r"\b(?:on|by|before|after|date|due)\s+[0-9]{1,2}/[0-9]{1,2}(?![/\d])", t, re.I)):+ raise NormalizationError("ambiguous_short_date", "Spell out the month and year for a short date.", span=bad.span())+ if (bad := re.search(r"தேதி\s+[0-9]{1,2}\.\s*[0-9]{4}", t)):+ raise NormalizationError("conflicting_date", "Conflicting date components; confirm the intended date.", span=bad.span())+ rupee_words = [word for word, key in locale.CURRENCY_WORDS.items() if key == "rupee"]+ rupee_aliases = "|".join(sorted(map(re.escape, rupee_words + ["INR", "Rs"]), key=len, reverse=True))+ rupee_prefix = rf"(?:₹|(?<!\w)(?:{rupee_aliases})\.?)"+ minor_units = "|".join(sorted(map(re.escape, _PAISA_INPUT_WORDS), key=len, reverse=True))+ if (bad := re.search(rf"{rupee_prefix}\s*[+-]?[0-9][0-9,.]*\s*(?:{minor_units})(?=$|[\s.,!?;।॥-])", t, re.I)):+ raise NormalizationError("conflicting_currency_unit", "Rupee prefix conflicts with a paise suffix; confirm the unit.", span=bad.span())+ if (bad := re.search(rf"(?:{rupee_prefix}|[$€£]|\b(?:USD|EUR|GBP))\s*[+-]?[0-9][0-9,.]*\s*%", t, re.I)):+ raise NormalizationError("conflicting_currency_unit", "A value cannot have both a currency prefix and percent suffix.", span=bad.span())+ for m in re.finditer(r"(?<![\w:])([0-9]{1,3}):([0-9]{2}):([0-9]{2})(?![\d:])", t):+ if int(m[2]) > 59 or int(m[3]) > 59:+ raise NormalizationError("invalid_duration", "Duration minutes and seconds must be below 60.", span=m.span())+ no_durations = re.sub(r"[0-9]+:[0-9]{2}:[0-9]{2}", lambda m: " " * len(m[0]), t)+ for m in re.finditer(r"(?<![\w:])([0-9]{1,2})(?:[:.]([0-9]{2}))?\s*(a\.?m\.?|p\.?m\.?)(?!\w)|(?<![\w:])([0-9]{1,2}):([0-9]{2})(?![\d:])", no_durations, re.I):+ if m[1]:+ valid = 1 <= int(m[1]) <= 12 and int(m[2] or 0) < 60+ else:+ # Explicit ratio context is not a clock.+ if re.search(r"\b(?:ratio|odds|proportion)\b", _sentence_before(t, m.start()), re.I):+ continue+ valid = int(m[4]) < 24 and int(m[5]) < 60+ if not valid:+ raise NormalizationError("invalid_time", "Invalid clock time; use 00:00-23:59 or 1-12 with am/pm.", span=m.span())++class LangBase:+ # ---- identity -------------------------------------------------------+ code = "" # ISO 639-1: hi bn ta te mr gu kn ml pa or+ name = ""+ native_digits = "" # the 10 native digit glyphs "०१२३४५६७८९" etc.++ # ---- numbers --------------------------------------------------------+ ONES = [] # words for 0..99 (100 entries, native script)+ HUNDRED = "" # word used in "X hundred" composition (Indo-Aryan)+ THOUSAND = ""+ LAKH = ""+ CRORE = ""++ # ---- letters (English letter names written in native script) --------+ LETTERS = {} # {"A": "...", ..., "Z": "..."}++ # ---- calendar -------------------------------------------------------+ MONTHS = [] # 12 native month names (Jan..Dec, Gregorian)+ MONTH_ALIASES = {} # accepted alternate input spelling -> month 1..12++ # ---- symbols / unit words -------------------------------------------+ # Values are native-script spoken words. Keys are fixed; the engine+ # relies on every key existing.+ SYM = {+ "rupee": "", "dollar": "", "euro": "", "pound": "", "cent": "",+ "percent": "", # % symbol+ "point": "", # decimal point word (Hindi: दशमलव)+ "minus": "", "plus": "", "equals": "", "times": "", "divide": "",+ "squared": "", # ² (Hindi: का वर्ग — appended after operand)+ "sqrt": "", # √ (spoken before operand)+ "lt": "", "gt": "", # < >+ "plus_minus": "", # ±+ "at": "", # @ (Hindi: एट द रेट)+ "underscore": "",+ "dot": "", # . in emails/URLs+ "slash": "", # / in URLs+ "hash": "", # #+ "amp": "", # &+ "half": "", "quarter": "", "three_quarters": "",+ "degree": "", "celsius": "", "fahrenheit": "",+ "minute": "", # time minutes word+ }++ # ---- templates (use {placeholders}) ----------------------------------+ TIME_ON_HOUR = "" # "{h} बजे"+ TIME_HM = "" # "{h} बजकर {m} मिनट"+ RANGE = "" # "{a} से {b}" (10–20)+ RANGE_TO = "" # "{a} से {b} तक" (time ranges)+ RATIO = "" # "{a} अनुपात {b}"+ POWER = "" # "{base} की घात {exp}"+ FRACTION = "" # "{num} बटा {den}" (2/7)+ DECADE_SHORT = "" # "{tens} के" (90s)+ DECADE_FULL = "" # "{tens} का दशक" (1980s)++ # Period words emitted before the time (order: period first, then time).+ PERIODS = {"morning": "", "afternoon": "", "evening": "", "night": ""}++ # ---- source-text detection vocab (native words the engine must+ # recognise in the INPUT). Include all common variants/spellings.+ TIME_MARKERS = [] # e.g. ["बजे", "बजकर"]+ # markers that carry a case suffix which must be re-attached to the+ # rendered time ("10 గంటలకు" -> "పది గంటలకు", not "పది గంటలు")+ MARKER_SUFFIXES = {} # e.g. {"గంటలకు": "కు"}+ PERIOD_DETECT = {} # native word -> "morning"/"afternoon"/"evening"/"night"+ YEAR_WORDS = [] # e.g. ["साल", "वर्ष", "सन्"]+ ID_KEYWORDS = [] # native keywords marking identifiers: नंबर, खाता ...+ ID_AFTER_WORDS = [] # words AFTER a digit-run marking it as an+ # identifier ("7104 తో ఎండ్ అయ్యే number")+ LABEL_WORDS = [] # native label words read as cardinal: कमरा, अनुच्छेद ...+ MINUTE_WORDS = [] # native "minute" words in input, e.g. ["मिनट"]+ SCALE_WORDS = {} # native scale word in input -> "crore"/"lakh"/"thousand"+ CURRENCY_WORDS = {} # native currency words in input -> canonical key+ # e.g. {"रुपये": "rupee", "रु": "rupee"}++ # ---- ordinals ---------------------------------------------------------+ ORDINAL_EXCEPTIONS = {} # n -> word (Hindi: {1: "पहला", 2: "दूसरा", ...})+ ORDINAL_SUFFIX = "" # default suffix appended to cardinal (Hindi: वाँ)+ # Suffixes seen in input that should be preserved on output when possible+ ORDINAL_INPUT_SUFFIXES = [] # e.g. ["वीं", "वाँ", "वें", "वां"]++ # ======================================================================+ # Composition methods — Indo-Aryan defaults; Dravidian modules override.+ # ======================================================================++ def digit(self, d: int) -> str:+ return self.ONES[d]++ def two_digit(self, n: int) -> str:+ return self.ONES[n]++ def hundreds(self, h: int, rest: int) -> str:+ """h in 1..9, rest 0..99 -> 'X sau [rest]'."""+ out = f"{self.ONES[h]} {self.HUNDRED}"+ if rest:+ out += f" {self.two_digit(rest)}"+ return out++ def under_thousand(self, n: int) -> str:+ if n < 100:+ return self.two_digit(n)+ return self.hundreds(n // 100, n % 100)++ def cardinal(self, n: int) -> str:+ """Indian-system cardinal. Override in Dravidian modules."""+ if n < 0:+ return f"{self.SYM['minus']} {self.cardinal(-n)}"+ if n < 1000:+ return self.under_thousand(n)+ parts = []+ crore, n = divmod(n, 10**7)+ lakh, n = divmod(n, 10**5)+ thousand, n = divmod(n, 1000)+ if crore:+ parts.append(f"{self.cardinal(crore)} {self.CRORE}")+ if lakh:+ parts.append(f"{self.two_digit(lakh)} {self.LAKH}")+ if thousand:+ parts.append(f"{self.two_digit(thousand)} {self.THOUSAND}")+ if n:+ parts.append(self.under_thousand(n))+ return " ".join(parts)++ def year(self, y: int) -> str:+ """Year-style reading. Indo-Aryan: 1947 -> 'unnis sau saintalis'.+ Dravidian modules usually override to full cardinal."""+ if 1100 <= y <= 1999:+ hi, lo = divmod(y, 100)+ out = f"{self.two_digit(hi)} {self.HUNDRED}"+ if lo:+ out += f" {self.two_digit(lo)}"+ return out+ return self.cardinal(y)++ def letter(self, c: str) -> str:+ return self.LETTERS.get(c.upper(), c)++ def month(self, i: int) -> str:+ """i is 1..12"""+ return self.MONTHS[i - 1]++ def time_phrase(self, h: int, m: int, period_key=None) -> str:+ # _resolve_time may deliberately hand back a 24-hour hour (languages+ # that transcribe am/pm keep "14:30" as "fourteen thirty"); only fold+ # into 12-hour when it has not already been decided upstream.+ if self.AMPM_WORDS and h > 12:+ h12 = h+ else:+ h12 = h % 12+ if h12 == 0:+ h12 = 12+ if m == 0:+ core = self.TIME_ON_HOUR.format(h=self.two_digit(h12))+ else:+ core = self.TIME_HM.format(h=self.two_digit(h12), m=self.two_digit(m))+ if period_key:+ return f"{self.PERIODS[period_key]} {core}"+ return core++ def ordinal(self, n: int, src_suffix: str = "") -> str:+ if n in self.ORDINAL_EXCEPTIONS and not src_suffix:+ return self.ORDINAL_EXCEPTIONS[n]+ return self._ordinal_compose(n, src_suffix)++ def _ordinal_compose(self, n: int, src_suffix: str) -> str:+ """Default: cardinal + suffix. Languages with stem changes override."""+ base = self.ORDINAL_EXCEPTIONS.get(n)+ if base and not src_suffix:+ return base+ suffix = src_suffix if src_suffix in self.ORDINAL_INPUT_SUFFIXES else self.ORDINAL_SUFFIX+ return f"{self.cardinal(n)}{suffix}"++ def decimal(self, int_part: int, frac_digits: str) -> str:+ frac = " ".join(self.digit(int(d)) for d in frac_digits)+ return f"{self.cardinal(int_part)} {self.SYM['point']} {frac}"++ def decade(self, tens: int, full: bool) -> str:+ """tens: e.g. 90 for '90s', 80 for '1980s'."""+ tpl = self.DECADE_FULL if full else self.DECADE_SHORT+ return tpl.format(tens=self.two_digit(tens))++ # ------------------------------------------------------------------+ # Grammar hooks — no-ops by default; languages with case/sandhi+ # morphology (Telugu, ...) override these.+ # ------------------------------------------------------------------++ # unit initialisms that read as full native words instead of letters+ # (e.g. Telugu KM -> కిలోమీటర్లు)+ UNIT_WORDS = {}++ # written abbreviations that are not speakable words — expanded to native+ # words wherever they appear (mins -> నిమిషాలు). Keys uppercased.+ ABBREV_UNITS = {}++ # spoken word for the "No." / "no." abbreviation before digits+ NUMBER_WORD = ""++ # When non-empty the language transcribes the am/pm token literally and the+ # engine stops INFERRING a period from the hour. Indo-Aryan languages say+ # the period naturally ("shaam paanch baje"), so they leave this empty;+ # English must not have "in the evening" inserted into text that only said+ # "pm". Keys are lowercase, dots stripped.+ AMPM_WORDS = {}+ COUNT_ONE = None+ SINGULAR_NOUNS = {}++ def join_amount(self, words: str, noun: str) -> str:+ """Join number words with a following noun we insert (currency,+ scale, unit). Languages may apply oblique/singular morphology."""+ if words == self.ONES[1]:+ return f"{self.COUNT_ONE or words} {self.SINGULAR_NOUNS.get(noun, noun)}"+ return f"{words} {noun}"++ def scale_noun(self, canon: str, numstr: str) -> str:+ """Scale word used in '₹3 crore'-type phrases; languages may+ pluralize when the number is not 1."""+ return {"crore": self.CRORE, "lakh": self.LAKH,+ "thousand": self.THOUSAND}.get(canon, canon)++ def attach_postposition(self, rep: str, tok: str):+ """Called when a native token `tok` immediately follows a rendered+ span `rep`. Return the merged string (consuming the token), or None+ to leave both untouched."""+ return None++++# ----------------------------------------------------------------------------+# Static tables+# ----------------------------------------------------------------------------++# All Indic decimal digit blocks -> ASCII+_INDIC_DIGIT_BLOCKS = [+ 0x0966, # Devanagari+ 0x09E6, # Bengali+ 0x0A66, # Gurmukhi+ 0x0AE6, # Gujarati+ 0x0B66, # Odia+ 0x0BE6, # Tamil+ 0x0C66, # Telugu+ 0x0CE6, # Kannada+ 0x0D66, # Malayalam+]+_DIGIT_TRANS = {}+for _base in _INDIC_DIGIT_BLOCKS:+ for _i in range(10):+ _DIGIT_TRANS[_base + _i] = ord("0") + _i++# Emoji / decorative ranges to strip entirely+_EMOJI_RE = re.compile(+ "["+ "\U0001F300-\U0001FAFF" # symbols & pictographs, emoticons, transport...+ "\U00002700-\U000027BF" # dingbats+ "\U00002600-\U000026FF" # misc symbols+ "\U0001F1E6-\U0001F1FF" # flags+ "\U0000FE00-\U0000FE0F" # variation selectors+ "\U0001F000-\U0001F0FF"+ "\U00002B00-\U00002BFF" # arrows/stars (⭐)+ "\U00002300-\U000023FF" # misc technical (⌛ ⏳ ⏬)+ "\U00002190-\U000021FF" # arrows (→)+ "\U000025A0-\U000025FF" # geometric (● ▶)+ "\U00002022" # bullet •+ "\U00002605\U00002606" # ★ ☆+ "\U00002122\U000000A9\U000000AE" # ™ © ®+ # NOTE: ZWNJ/ZWJ (200C/200D) are deliberately NOT stripped — they are+ # meaningful orthography in Telugu/Malayalam (ఆన్లైన్). Only the truly+ # invisible ZWSP/BOM are removed, without inserting a space.+ "`~|\\\\{}\\[\\]«»‹›„‚•·¤§†‡"+ "]+"+)+_ZW_STRIP = {0x200B: None, 0x200E: None, 0x200F: None, 0xFEFF: None}++_ENGLISH_MONTHS = {+ "jan": 1, "january": 1, "feb": 2, "february": 2, "mar": 3, "march": 3,+ "apr": 4, "april": 4, "may": 5, "jun": 6, "june": 6, "jul": 7, "july": 7,+ "aug": 8, "august": 8, "sep": 9, "sept": 9, "september": 9,+ "oct": 10, "october": 10, "nov": 11, "november": 11,+ "dec": 12, "december": 12,+}++# Established acronyms that stay in Latin script (never spelled out unless+# they are part of an alphanumeric identifier).+_ACRONYM_WHITELIST = {+ "UPI", "EMI", "API", "MRI", "GST", "SEBI", "MCX", "IGI", "HDFC", "ISRO",+ "IMD", "SBI", "RBI", "ICICI", "IRCTC", "ATM", "SIM", "OTP", "PIN", "CEO",+ "CFO", "CTO", "IPL", "BCCI", "DNA", "RNA", "WHO", "NASA", "PDF", "GPS",+ "LED", "LCD", "USB", "WIFI", "AI", "IT", "TV", "FM", "AC", "EV", "CBI",+ "NIA", "ED", "GDP", "CPI", "FII", "DII", "IPO", "NSE", "BSE", "KYC",+ "NEFT", "RTGS", "IMPS", "IFSC", "CVV", "PAN", "UID", "NRI", "MLA", "MP",+ "PM", "CM", "DM", "SP", "IAS", "IPS", "NEET", "JEE", "UPSC", "CBSE",+ "ICSE", "BA", "MA", "MBA", "MBBS", "AIIMS", "ISKCON", "DLF", "TCS",+ "LTIMINDTREE", "ONGC", "NTPC", "BHEL", "SAIL", "GAIL", "LIC",+ "RAM", "ROM", "CPU", "GPU", "SSD", "HDD", "GPA", "SUV", "SLA", "GDP",+ "UIDAI", "FASTAG", "GSTIN", "OK", "US", "UK", "UAE", "USA", "EU", "UN",+ "PSU", "FIR", "RTI", "PIL", "GPRS", "HD", "UHD", "CCTV", "AQI", "UV",+}++# Units read letter-by-letter (initialisms). Keys uppercased for lookup.+_UNIT_INITIALISMS = {+ "GB", "MB", "KB", "TB", "PB", "MAH", "MPH", "KMPH", "MHZ", "GHZ", "KHZ",+ "HZ", "KWH", "RPM", "HP", "BHP", "CC", "DPI", "PPI", "FPS", "MBPS",+ "GBPS", "KBPS", "PSI", "BPM", "V", "KV", "W", "KW", "MW", "MA", "AH",+ "WH", "DB", "PPM", "ML", "MG", "KG", "KM", "CM", "MM", "GM", "MCG", "IU",+}++# English "big number" scale words that stay in Latin (5 million -> पाँच million)+_EN_SCALES = {"million", "billion", "trillion", "mn", "bn", "millions",+ "billions"}++_ID_KEYWORDS_EN = {+ "phone", "mobile", "card", "account", "otp", "pin", "code", "order",+ "ref", "reference", "train", "flight", "ticket", "tracking", "license",+ "licence", "booking", "pnr", "upi", "imei", "registration", "number",+ "no", "ending", "khasra", "plot", "docket", "complaint", "case", "loan",+ "policy", "invoice", "receipt", "transaction", "txn", "utr", "id",+ "extension", "helpline", "hotline", "whatsapp", "aadhaar", "aadhar",+ "passport", "cvv", "gstin",+}++_LABEL_WORDS_EN = {+ "hall", "window", "counter", "room", "ward", "terminal", "zone", "gate",+ "section", "tower", "platform", "floor", "seat", "berth", "coach",+ "season", "episode", "chapter", "class", "grade", "level", "article",+ "position", "page", "question", "step", "stage", "round", "phase",+ "wing", "block", "lane", "screen", "stand", "row", "table", "lesson",+ "unit", "part", "volume", "rank", "standard", "semester", "waitlist",+}++_STREET_WORDS = {+ "मार्ग", "रोड", "नगर", "सड़क", "गली", "चौक",+ "road", "street", "lane", "avenue", "marg", "nagar", "chowk", "colony",+}++_CURRENCY_SYMBOLS = {"₹": "rupee", "$": "dollar", "€": "euro", "£": "pound",+ "Rs.": "rupee", "Rs": "rupee"}++_MATH_WORDS_EN = {"squared", "cubed", "plus", "minus", "times", "equals",+ "power", "root", "over", "by", "divided", "into"}+++def _fmt(template, **kw):+ out = template+ for k, v in kw.items():+ out = out.replace("{" + k + "}", str(v))+ return out+++class Normalizer:+ def __init__(self, lang, *, date_order="DMY", two_digit_year_base=None):+ self.lang = lang+ self.date_order = date_order+ self.two_digit_year_base = two_digit_year_base+ self._build_regexes()++ # ------------------------------------------------------------------+ # Regex construction (depends on language vocab)+ # ------------------------------------------------------------------+ def _build_regexes(self):+ L = self.lang++ def alt(words):+ return "|".join(re.escape(w) for w in+ sorted(set(words), key=len, reverse=True)) or r"(?!x)x"++ self._period_re = alt(list(L.PERIOD_DETECT.keys()))+ self._marker_re = alt(L.TIME_MARKERS)+ self._month_lookup = _month_lookup(L)+ self._month_re = alt(self._month_lookup)+ self._scale_re = alt(list(L.SCALE_WORDS.keys()) ++ ["crore", "crores", "Crore", "Crores", "Cr", "cr",+ "lakh", "lakhs", "Lakh", "Lakhs", "thousand"] ++ sorted(_EN_SCALES))+ self._ord_suffix_re = alt(list(L.ORDINAL_INPUT_SUFFIXES) ++ ["st", "nd", "rd", "th"])+ native_currency = [word for word, key in L.CURRENCY_WORDS.items()+ if not word.isascii() and key in {"rupee", "dollar", "euro", "pound"}]+ self._currency_re = r"₹|\$|€|£|Rs\.?|INR|USD|EUR|GBP"+ if native_currency:+ self._currency_re += "|(?:" + alt(native_currency) + r")\.?"+ self._id_keywords = _ID_KEYWORDS_EN | _OTP_INPUT_WORDS | {w.lower() for w in L.ID_KEYWORDS}+ self._label_words = _LABEL_WORDS_EN | {w.lower() for w in L.LABEL_WORDS}+ self._minute_re = alt(L.MINUTE_WORDS + ["minute", "minutes", "min"])+ # ratio detection keywords: english words + the language's own ratio+ # word extracted from its RATIO template ("{a} अनुपात {b}" -> अनुपात),+ # so "விகிதம் 9:15" reads as a ratio, not a time+ tpl_words = re.sub(r"\{[ab]\}", " ", L.RATIO or "").split()+ self._ratio_kws = {"ratio", "odds", "proportion", "अनुपात"} | \+ {w.lower() for w in tpl_words}++ # ------------------------------------------------------------------+ # Small helpers+ # ------------------------------------------------------------------+ def _month_index(self, token):+ return self._month_lookup.get(token.strip().lower())++ def _digits_spelled(self, digits, comma=True):+ if os.environ.get("FR3_TN_LONG_DIGITS", "0") == "1" and len(digits) >= 8:+ if __package__:+ from .identifier_rules import group_digits+ else:+ from identifier_rules import group_digits+ return group_digits(digits, self.lang)+ words = [self.lang.digit(int(d)) for d in digits]+ return ", ".join(words) if comma else " ".join(words)++ def _letters_spelled(self, letters, comma=False):+ words = [self.lang.letter(c) for c in letters]+ return ", ".join(words) if comma else " ".join(words)++ def _spell_alnum(self, token, comma):+ """Spell a code segment: letters by sound, digits one by one."""+ parts = []+ for ch in token:+ if ch.isdigit():+ parts.append(self.lang.digit(int(ch)))+ elif ch.isalpha() and ch.isascii():+ parts.append(self.lang.letter(ch))+ # other chars (hyphens) become separators, dropped+ return (", " if comma else " ").join(parts)++ def _spell_model_segment(self, seg):+ """WH-1000XM5 style segment: letter runs by sound, digit runs as+ cardinal when a clean round block, else digit-by-digit; spaces."""+ out = []+ for run in re.findall(r"[A-Za-z]+|\d+", seg):+ if run.isdigit():+ n = int(run)+ if len(run) == 1 or (n % 100 == 0 and n >= 100):+ out.append(self.lang.cardinal(n))+ else:+ out.append(self._digits_spelled(run, comma=False))+ else:+ out.append(self._letters_spelled(run))+ return " ".join(out)++ def _number_words(self, numstr):+ """Plain number string (commas allowed) -> cardinal / decimal words."""+ if numstr.startswith(("-", "+")):+ sign = self.lang.SYM["minus" if numstr[0] == "-" else "plus"]+ return f"{sign} {self._number_words(numstr[1:])}"+ numstr = numstr.replace(",", "")+ if "." in numstr:+ ip, fp = numstr.split(".", 1)+ return self.lang.decimal(int(ip or 0), fp)+ return self.lang.cardinal(int(numstr))++ def _keyword_before(self, text, start, keywords, window=3):+ before = _sentence_before(text, start).replace("\u200c", "")+ toks = re.findall(r"[\w#ऀ-']+", before.lower())+ for tok in toks[-window:]:+ tok = tok.strip("#'")+ if tok in keywords:+ return True+ return False++ def _period_for_hour24(self, h):+ if 4 <= h < 12:+ return "morning"+ if 12 <= h < 16:+ return "afternoon"+ if 16 <= h < 20:+ return "evening"+ return "night"++ def _time_words(self, h, m, period_key):+ if self.lang.code != "en" and (h == 0 or h > 12):+ # Keep the written 24-hour hour. The inherited language time methods+ # otherwise fold zero into twelve or fourteen into two.+ template = self.lang.TIME_HM if m else self.lang.TIME_ON_HOUR+ return template.format(h=self.lang.cardinal(h), m=self.lang.cardinal(m))+ return self.lang.time_phrase(h, m, period_key)++ # ------------------------------------------------------------------+ # Pre-clean+ # ------------------------------------------------------------------+ def _preclean(self, text):+ text = _ascii_digits(text)+ text = text.replace("−", "-")+ text = text.translate(_ZW_STRIP)+ # double quotation marks (incl. CSV-style "" and """ runs) carry no+ # sound — a voice model cannot speak them.+ text = re.sub(r'["“”„]+', "", text)+ # single quotes wrapping phrases ('Premium Home Decor') go too.+ # Kept: apostrophes inside words (D'Souza, John's) and quoted single+ # letters ('Y' -> letter name, handled by its own matcher).+ text = re.sub(r"(?<=[\s(।,—–-])['‘’](?![A-Za-z]['‘’])(?=\S)", "", text)+ text = re.sub(r"^['‘’](?![A-Za-z]['‘’])(?=\S)", "", text)+ text = re.sub(r"(?<=\S)(?<!['‘’][A-Za-z])['‘’](?=[\s,।.!?;:)]|$)", "", text)+ text = re.sub(r"#{2,}", " ", text) # markdown header/### junk+ # ellipses (… / ... / ..) are a spoken pause -> read as a comma+ text = re.sub(r"\s*(?:…|‥|\.{2,})\s*", ", ", text)+ # parentheses are silent; the aside becomes a comma pause+ text = re.sub(r"\s*[()]\s*", ", ", text)+ # //comment// markers are markup junk ((?<!:) keeps https:// intact)+ text = re.sub(r"(?<!:)/{2,}", " ", text)+ # "No." / "no." before digits is the number abbreviation, not "no"+ if self.lang.NUMBER_WORD:+ text = re.sub(r"\b[Nn][Oo]s?\.\s*(?=\d)",+ self.lang.NUMBER_WORD + " ", text)+ # written-only unit abbreviations -> native words (mins -> నిమిషాలు);+ # guards keep code segments like MIN-22 intact+ for ab, word in self.lang.ABBREV_UNITS.items():+ # consume the abbreviation's own full stop when the sentence+ # continues ("Dr. Rao" -> "doctor Rao"), but keep it when the+ # abbreviation ends the sentence ("... approx." -> "approximately.")+ text = re.sub(rf"(?<![\w-]){ab}(?:\.(?=\s+\S))?(?![\w-])", word, text,+ flags=re.IGNORECASE)+ text = re.sub(r"^[,\s]+", "", text)+ # Comparison operators are meaningful even without a left numeric operand.+ text = _EMOJI_RE.sub(" ", text)+ # en/em dash between numbers -> canonical range dash; others deleted+ text = re.sub(r"(?<=[\d])\s*[–—]\s*(?=[\d])", "–", text)+ # time-range dash: "11 AM – 3 PM" (dash not directly digit-adjacent)+ text = re.sub(r"\s+[–—]\s+(?=\d)", " – ", text)+ text = re.sub(r"[—]", " ", text)+ text = re.sub(r"(?<![\d\s])[–](?![\d\s])", " ", text)+ text = re.sub(r"[ \t]{2,}", " ", text)+ return text++ # ------------------------------------------------------------------+ # Matchers — each returns list of (start, end, replacement)+ # Priority = order in self._matchers (earlier wins).+ # ------------------------------------------------------------------+ def _gather(self, text):+ matches = [] # (priority, start, end, replacement)+ matchers = [+ self._m_email,+ self._m_url,+ self._m_handle,+ self._m_comparison,+ self._m_time_range,+ self._m_duration,+ self._m_time_verbalized,+ self._m_time,+ self._m_tamil_date,+ self._m_date,+ self._m_currency_range,+ self._m_currency,+ self._m_bare_rupee_suffix,+ self._m_long_digit_runs,+ self._m_amount_context,+ self._m_percent_range,+ self._m_percent,+ self._m_negative,+ self._m_designation,+ self._m_vehicle_plate,+ self._m_ordinal,+ self._m_code,+ self._m_id_digits,+ self._m_chem,+ self._m_math,+ self._m_num_range,+ self._m_dimensions,+ self._m_roman,+ self._m_unit_initialism,+ self._m_kmb_suffix,+ self._m_fraction,+ self._m_ratio,+ self._m_label,+ self._m_acronym_model,+ self._m_num_hyphen_word,+ self._m_decade,+ self._m_year,+ self._m_quoted_letter,+ self._m_short_mixed_token,+ self._m_decimal,+ self._m_int,+ ]+ for prio, fn in enumerate(matchers):+ for (s, e, rep) in fn(text):+ matches.append((prio, s, e, rep))+ return matches++ # --- email / url / handle -----------------------------------------+ def _spell_uri_part(self, part):+ """Word chunks stay; digits spelled; symbols to words."""+ if os.environ.get("FR3_TN_URL_SPELL", "0") == "1":+ if __package__:+ from .identifier_rules import spell_uri+ else:+ from identifier_rules import spell_uri+ return spell_uri(part, self.lang, self._digits_spelled)+ S = self.lang.SYM+ out = []+ for run in re.findall(r"[^\W\d_]+|\d+|[^\w\s]|_", part):+ if run.isdigit():+ out.append(self._digits_spelled(run, comma=False))+ elif run == ".":+ out.append(S["dot"])+ elif run == "_":+ out.append(S["underscore"])+ elif run == "@":+ out.append(S["at"])+ elif run == "/":+ out.append(S["slash"])+ elif run == "-":+ out.append("dash")+ elif run == "+":+ out.append(S["plus"])+ elif run in {"?", "=", "&", "#", "%", ":", "~"}:+ out.append({"?": "question mark", "=": "equals", "&": "ampersand",+ "#": "hash", "%": "percent", ":": "colon", "~": "tilde"}[run])+ elif run.lower() == "www":+ out.append(self._letters_spelled("WWW"))+ elif len(run) == 1 or run.upper() in self.lang.ABBREV_UNITS:+ # Do not expand /Dr/ to /doctor/ on a second normalization pass.+ out.append(self._letters_spelled(run.upper()))+ else:+ out.append(run)+ return " ".join(w for w in out if w)++ def _m_email(self, text):+ for m in re.finditer(r"\b[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}\b", text):+ yield m.start(), m.end(), self._spell_uri_part(m.group(0))++ def _m_url(self, text):+ pat = (r"https?://[^\s<>]+|www\.[^\s<>]+"+ # bare domains: maya.ai, irctc.co.in/booking+ r"|\b[A-Za-z][\w\-]*\.(?:com|org|net|ai|io|co|dev|app|edu|gov|in)"+ r"(?:\.(?:in|uk|us))?(?:[/?#][^\s<>]*)?(?![\w.])")+ for m in re.finditer(pat, text):+ token = m.group(0).rstrip(".,!?;)")+ body = re.sub(r"^https?://", "", token)+ yield m.start(), m.start() + len(token), self._spell_uri_part(body)++ def _m_handle(self, text):+ # trailing \w so a sentence-final period after the handle is not+ # swallowed and spoken as "dot" ("@test_user." -> handle + full stop)+ pat = r"(?<![\w.])@([A-Za-z](?:[\w.\-]*\w)?)" if os.environ.get("FR3_TN_URL_SPELL", "0") == "1" else r"(?<![\w.])@([A-Za-z](?:[\w.]*\w)?)"+ for m in re.finditer(pat, text):+ yield m.start(), m.end(), \+ f"{self.lang.SYM['at']} {self._spell_uri_part(m.group(1))}"++ # --- time -----------------------------------------------------------+ def _parse_time_match(self, m, text):+ """Shared logic. Returns (h12, mm, period_key)."""+ pass++ def _time_pattern(self):+ P = self._period_re+ MK = self._marker_re+ # (?<!\w) / (?!\w) around native-word alternations: "ગુજરાત" ends+ # with રાત (night) — without boundaries the period word matches+ # inside other words+ return re.compile(+ rf"(?:(?<!\w)({P})\s+)?" # leading period word+ rf"(\d{{1,2}})" # hour+ # a real time needs :mm, AM/PM or a time marker right after the+ # hour — otherwise bare numbers spuriously swallow period words+ rf"(?=:\d{{2}}"+ rf"|\.\d{{2}}\s*(?:AM|PM|am|pm|a\.m\.|p\.m\.)(?![A-Za-z])" # 6.45 pm — dot form+ rf"|\s*(?:AM|PM|am|pm|a\.m\.|p\.m\.)(?![A-Za-z])|\s*(?:{MK})(?!\w))"+ rf"(?:[.:](\d{{2}}))?" # :mm or .mm (gated by the lookahead)+ rf"(?:\s*(AM|PM|am|pm|a\.m\.|p\.m\.))?" # am/pm+ rf"(?:\s*({MK})(?!\w))?" # बजे / मणि ...+ rf"(?:\s+({P})(?!\w))?", re.I # trailing period word+ )++ def _resolve_time(self, lead_p, h, mm, ampm, marker, trail_p):+ L = self.lang+ h = int(h)+ m = int(mm) if mm is not None else 0+ period = None+ src_period = lead_p or trail_p+ if src_period:+ period = L.PERIOD_DETECT.get(src_period)+ if L.code != "en" and not ampm and not src_period:+ return h, m, None+ infer = not L.AMPM_WORDS # languages that speak am/pm keep the token instead+ if ampm:+ a = ampm.lower().replace(".", "")+ h24 = h % 12 + (12 if a == "pm" else 0)+ if infer:+ period = period or self._period_for_hour24(h24)+ elif h > 12 or h == 0:+ # 24-hour clock+ if infer:+ period = period or self._period_for_hour24(h)+ if L.AMPM_WORDS and not ampm and (h > 12 or h == 0):+ return h, m, period # "14:30" -> "fourteen thirty", not "two thirty"+ h12 = h % 12+ if h12 == 0:+ h12 = 12+ return h12, m, period++ def _m_duration(self, text):+ # H:MM:SS is a duration, not a 12-hour clock. Zero hours must not become 12.+ L = self.lang+ sec_word = L.SYM.get("second", "seconds")+ for m in re.finditer(r"\b(\d{1,3}):(\d{2}):(\d{2})\b", text):+ h, mm, ss = int(m.group(1)), int(m.group(2)), int(m.group(3))+ if mm > 59 or ss > 59:+ continue+ hours = L.ABBREV_UNITS.get("HRS", "hours")+ minutes = L.SYM["minute"]+ parts = [L.join_amount(L.cardinal(n), unit if n != 1 or L.code != 'en' else unit.rstrip('s'))+ for n, unit in ((h, hours), (mm, minutes), (ss, sec_word)) if n]+ yield m.start(), m.end(), " ".join(parts) or L.join_amount(L.cardinal(0), sec_word)++ def _m_time_verbalized(self, text):+ # "9 बजकर 15 मिनट" — already half-verbalized with digits: rebuild the+ # canonical phrase instead of reading the pieces separately+ L = self.lang+ MIN = self._minute_re+ pat = re.compile(+ rf"\b(\d{{1,2}})\s*(?:{self._marker_re})\s+(\d{{1,2}})\s*({MIN})(?!\w)")+ for m in pat.finditer(text):+ h, mm = int(m.group(1)), int(m.group(2))+ if h > 23 or mm > 59:+ continue+ rep = self._time_words(h, mm, None)+ sfx = L.MARKER_SUFFIXES.get(m.group(3) or "")+ if sfx:+ rep = L.attach_postposition(rep, sfx) or rep+ yield m.start(), m.end(), rep++ def _m_time(self, text):+ pat = self._time_pattern()+ for m in pat.finditer(text):+ lead_p, h, mm, ampm, marker, trail_p = m.groups()+ if h is None:+ continue+ # must look like a time: needs marker, am/pm, period word, or a+ # valid HH:MM+ hh = int(h)+ is_hhmm = mm is not None and int(mm) <= 59 and hh < 24+ if not (ampm or marker or ((lead_p or trail_p) and (is_hhmm or mm is None))):+ if not (is_hhmm and mm is not None and hh > 12):+ # bare h:mm with hh<=12: still a time if mm is 2-digit <=59+ if not (is_hhmm and not self._keyword_before(+ text, m.start(), self._ratio_kws, window=4)):+ continue+ if mm is None and not (ampm or marker):+ continue # bare number is not a time+ if mm is not None and int(mm) > 59:+ continue+ if hh > 23:+ continue+ h12, mnt, period = self._resolve_time(lead_p, h, mm, ampm, marker, trail_p)+ src_period = lead_p or trail_p+ if src_period:+ rep = f"{src_period} {self.lang.time_phrase(h12, mnt, None)}"+ else:+ rep = self._time_words(h12, mnt, period)+ if ampm and self.lang.AMPM_WORDS:+ w = self.lang.AMPM_WORDS.get(ampm.lower().replace(".", ""))+ if w:+ # a bare hour with am/pm reads "eight p m", never+ # "eight o'clock p m" -- o'clock was not in the input+ if mnt == 0:+ rep = self.lang.two_digit(h12)+ rep = f"{rep} {w}"+ sfx = self.lang.MARKER_SUFFIXES.get(marker or "")+ if sfx:+ rep = self.lang.attach_postposition(rep, sfx) or rep+ yield m.start(), m.end(), rep++ def _m_time_range(self, text):+ # 11 AM – 3 PM / 9:00 – 17:00 / 11 AM to 3 PM stays "to"+ pat = self._time_pattern()+ rng = re.compile(+ rf"({pat.pattern})\s*[–\-]\s*({pat.pattern})", pat.flags)+ for m in rng.finditer(text):+ g = m.groups()+ left, right = g[0], g[7]+ gl, gr = g[1:7], g[8:14]+ if gl[1] is None or gr[1] is None:+ continue+ # each side must independently look like a time+ if not ((gl[3] or gl[4] or gl[2]) and (gr[3] or gr[4] or gr[2])):+ continue+ h1, m1, p1 = self._resolve_time(*gl)+ h2, m2, p2 = self._resolve_time(*gr)+ a = self._time_words(h1, m1, p1)+ b = self._time_words(h2, m2, p2)+ if self.lang.AMPM_WORDS:+ if gl[3]:+ a = (self.lang.two_digit(h1) if m1 == 0 else a) + " " + self.lang.AMPM_WORDS[gl[3].lower().replace('.', '')]+ if gr[3]:+ b = (self.lang.two_digit(h2) if m2 == 0 else b) + " " + self.lang.AMPM_WORDS[gr[3].lower().replace('.', '')]+ rep = _fmt(self.lang.RANGE_TO, a=a, b=b)+ tail = self.lang.RANGE_TO.split("{b}")[-1].strip()+ if tail and re.match(rf"\s*{re.escape(tail)}(?!\w)",+ text[m.end():]):+ rep = rep[: -len(tail)].rstrip() # source already says it+ yield m.start(), m.end(), rep++ # --- dates -----------------------------------------------------------+ def _m_tamil_date(self, text):+ if self.lang.code not in ("en", "ta"):+ return+ months = "|".join(_TAMIL_MONTHS)+ # Only calendar-day suffixes. Do not pretend all Tamil number morphology+ # can be repaired by concatenating an English cardinal with a suffix.+ pat = rf"(?<!\w)({months})\s+(\d{{1,2}})(?:-?(?:ஆம்|ம்))?(?![\dA-Za-z])(?:\s*தேதி)?"+ for m in re.finditer(pat, text):+ d = int(m[2])+ if 1 <= d <= 31:+ yield m.start(), m.end(), f"{m[1]} {_TAMIL_ORDINALS[d]} தேதி"+ for m in re.finditer(r"(?<!\w)(\d+)-?(?:ஆம்|ம்)(?![\w\u0B80-\u0BFF])", text):+ d = int(m[1])+ if not 1 <= d <= 31:+ if self.lang.code == "en":+ raise NormalizationError("unsupported_tamil_ordinal", "Select Tamil normalization for ordinals outside calendar days 1-31.", span=m.span(), source=text)+ yield m.start(), m.end(), self.lang.ordinal(d, "ஆம்")+ else:+ yield m.start(), m.end(), _TAMIL_ORDINALS[d]++ def _date_words(self, day, month, year=None, ordinal=False, month_first=False):+ L = self.lang+ if L.code == "ta":+ out = f"{L.month(month)} {_TAMIL_ORDINALS[day]} தேதி"+ else:+ suffix = ordinal if isinstance(ordinal, str) and ordinal in L.ORDINAL_INPUT_SUFFIXES else ""+ day_words = L.ordinal(day, suffix) if ordinal else L.cardinal(day)+ out = f"{L.month(month)} {day_words}" if month_first and L.code != "en" else f"{day_words} {L.month(month)}"+ return f"{out} {L.year(year)}" if year is not None else out++ def _m_date(self, text):+ L = self.lang+ for m in re.finditer(rf"\b(\d{{1,2}})[-–](\d{{1,2}})\s+({self._month_re})(?!\w)(?:\s+(\d{{4}}))?", text, re.I):+ mo = self._month_index(m[3])+ for day in (m[1], m[2]):+ _calendar_check(int(day), mo, int(m[4]) if m[4] else 2000)+ days = _fmt(L.RANGE, a=L.cardinal(int(m[1])), b=L.cardinal(int(m[2])))+ out = f"{days} {L.month(mo)}"+ if m[4]:+ out += f" {L.year(int(m[4]))}"+ yield m.start(), m.end(), out+ for m in re.finditer(r"(?<![\w-])(\d{4})-(\d{1,2})-(\d{1,2})(?![\d-])", text):+ yield m.start(), m.end(), self._date_words(int(m[3]), int(m[2]), int(m[1]))+ # DD/MM/YYYY or DD-MM-YYYY or DD.MM.YYYY+ for m in re.finditer(r"\b(\d{1,2})([/.\-])(\d{1,2})\2(\d{2,4})\b(?![/A-Za-z-])", text):+ d, mo, y = int(m.group(1)), int(m.group(3)), int(m.group(4))+ if self.date_order == "MDY":+ d, mo = mo, d+ if not (1 <= d <= 31 and 1 <= mo <= 12):+ continue+ if len(m.group(4)) == 2:+ y += self.two_digit_year_base+ yield m.start(), m.end(), self._date_words(d, mo, y)+ # DD-Mon-YYYY / DD Mon YYYY / DD Mon, with native or English months+ # (?!\w) after the month: without it "25 ಮೇಲೆ" would parse as+ # "25 May" because ಮೇಲೆ starts with ಮೇ (May)+ pat = re.compile(+ rf"\b(\d{{1,2}})(?:-?({self._ord_suffix_re}))?[\-\s]({self._month_re})(?!\w)"+ rf"(?:[\-\s,]+(\d{{4}}))?", re.IGNORECASE)+ for m in pat.finditer(text):+ d = int(m.group(1))+ mo = self._month_index(m.group(3))+ if mo is None or not (1 <= d <= 31):+ continue+ out = self._date_words(d, mo, int(m[4]) if m[4] else None, m[2])+ yield m.start(), m.end(), out+ # Month DD, YYYY (English order)+ pat2 = re.compile(+ rf"\b({self._month_re})\s+(\d{{1,2}})(?:-?({self._ord_suffix_re}))?(?:,?\s+(\d{{4}}))?(?!\d)",+ re.IGNORECASE)+ for m in pat2.finditer(text):+ mo = self._month_index(m.group(1))+ d = int(m.group(2))+ if mo is None or not (1 <= d <= 31):+ continue+ out = self._date_words(d, mo, int(m[4]) if m[4] else None, m[3], month_first=True)+ yield m.start(), m.end(), out++ # --- currency ---------------------------------------------------------+ _CURRENCY_CODE_KEYS = {"₹": "rupee", "$": "dollar", "€": "euro",+ "£": "pound", "RS": "rupee", "INR": "rupee",+ "USD": "dollar", "EUR": "euro", "GBP": "pound"}++ def _cur_key(self, symtok):+ t = symtok.strip().rstrip(".").strip().upper()+ return self._CURRENCY_CODE_KEYS.get(t) or self.lang.CURRENCY_WORDS.get(t) or self.lang.CURRENCY_WORDS.get(t + ".") or "rupee"++ def _m_currency_range(self, text):+ # ₹500-700 -> "five hundred to seven hundred rupees"+ L = self.lang+ pat = re.compile(+ rf"(?<!\w)([+-]?)({self._currency_re})"+ rf"\s*([+-]?\d+(?:,\d{{2,3}})*(?:\.\d+)?)\s*[–\-]\s*([+-]?\d+(?:,\d{{2,3}})*(?:\.\d+)?)(?!\d|[.,]\d)", re.I)+ for m in pat.finditer(text):+ if m[1] and m[3].startswith(("-", "+")):+ raise NormalizationError("conflicting_sign", "Currency amount has two signs; confirm the value.", span=m.span(), source=text)+ a, b = self._number_words(m[1] + m[3]), self._number_words(m[4])+ cw = L.SYM[self._cur_key(m[2])]+ rng = _fmt(L.RANGE, a=a, b=L.join_amount(b, cw))+ yield m.start(), m.end(), rng++ def _m_bare_rupee_suffix(self, text):+ L = self.lang+ for m in re.finditer(r"(?<![\w₹.])(\d+(?:,\d{2,3})*(?:\.\d+)?)\s?/-", text):+ num = m.group(1).replace(",", "")+ words = self._number_words(num)+ yield m.start(), m.end(), L.join_amount(words, L.SYM["rupee"])++ def _m_currency(self, text):+ L = self.lang+ S = L.SYM+ pat = re.compile(+ rf"(?<!\d)([+-]?)\s*(₹|\$|€|£|(?<!\w)(?:{self._currency_re}))"+ rf"\s*([+-]?)(\d+(?:,\d{{2,3}})*(?:\.\d+)?)"+ rf"(?:\s*({self._scale_re})(?:((?:ां|ं)?(?:चा|ची|चे|च्या|त|ना|हून|पर्यंत|मध्ये))|(?![ऀ-ःऺ-ॏঀ-ঃা-্ਁ-ਃਾ-੍ઁ-ઃા-્ଁ-ଃା-୍ஂா-்ఀ-ఄా-ౌಁ-ಃಾ-ೌഀ-ഃാ-ൌ]))(?![A-Za-z0-9]))?(?:\s?/-)?", re.I)+ for m in pat.finditer(text):+ if m[1] and m[3]:+ raise NormalizationError("conflicting_sign", "Currency amount has two signs; confirm the value.", span=m.span(), source=text)+ key = self._cur_key(m[2])+ num = m[4].replace(",", "")+ scale = m[5]+ cur_word = S[key]+ # money with exactly 2 decimals and no scale word -> main + sub+ # unit ($84.20 -> 84 dollar 20 cent; ₹95.41 -> 95 rupees 41 paise)+ if "." in num and not scale and len(num.split(".", 1)[1]) == 2:+ ip, fp = num.split(".", 1)+ main = L.cardinal(int(ip or 0))+ if key == "rupee" and L.SYM.get("paisa"):+ sub_word = L.SYM["paisa"]+ else:+ sub_word = S["cent"] if key != "rupee" else None+ if fp.strip("0") == "":+ out = L.join_amount(main, cur_word)+ elif sub_word:+ out = (f"{L.join_amount(main, cur_word)} "+ f"{L.join_amount(L.cardinal(int(fp)), sub_word)}")+ else:+ out = L.join_amount(L.decimal(int(ip or 0), fp), cur_word)+ else:+ words = self._number_words(num)+ if scale:+ sl = scale.lower()+ canon = L.SCALE_WORDS.get(scale)+ if canon is None and sl in _EN_SCALES:+ scale_word = scale # 1.5 million -> ... million dollar+ else:+ if canon is None:+ canon = ("crore" if sl in ("cr",) or "crore" in sl+ else "lakh" if "lakh" in sl+ else "thousand")+ scale_word = L.scale_noun(canon, num)+ out = L.join_amount(L.join_amount(words, scale_word),+ cur_word)+ case = m[6]+ if case:+ out = L.attach_postposition(out, case) or out+ else:+ out = L.join_amount(words, cur_word)+ sign = m[1] or m[3]+ if sign:+ out = f"{S['minus'] if sign == '-' else S['plus']} {out}"+ # Keep whitespace outside the matched amount.+ space = m[0][:1].isspace() or (m.start() > 0 and text[m.start() - 1].isalnum())+ yield m.start(), m.end(), (" " if space else "") + out++ def _m_amount_context(self, text):+ # Explicit currency suffix/amount label wins over broad identifier hints.+ units = (r"rupees?|rs\.?|inr|dollars?|usd|euros?|pounds?|paise|paisa|cents?|"+ r"ரூபாய்|பைசா|रुपये|रुपया|रुपए|రూ\.?|రూపాయలు|രൂപ")+ units += "|" + "|".join(map(re.escape, self.lang.CURRENCY_WORDS))+ for m in re.finditer(rf"(?<![\w.])([+-]?\d[\d,]*(?:\.\d+)?)(?=\s*(?:{units})(?![A-Za-z]))", text, re.I):+ yield m.start(), m.end(), self._number_words(m[1])+ labels = {"balance", "amount", "payable", "outstanding", "payment", "price", "fee", "pay", "emi", "தவணை"}+ for m in re.finditer(r"(?<![\w.,+/-])\d+(?:,\d{2,3})*(?!\w|[.,/-]\d)", text):+ before = _sentence_before(text, m.start()).lower()+ toks = re.findall(r"\w+", before)[-3:]+ if any(t in labels for t in toks) and not any(t in {"number", "id", "code", "otp", "pin"} for t in toks):+ yield m.start(), m.end(), self._number_words(m[0])++ # --- percent ------------------------------------------------------------+ def _m_percent_range(self, text):+ # 40-70% / 40–70% -> "40 to 70 percent"+ L = self.lang+ for m in re.finditer(r"\b(\d+(?:\.\d+)?)\s*[–\-]\s*(\d+(?:\.\d+)?)\s*%",+ text):+ a = self._number_words(m.group(1))+ b = self._number_words(m.group(2))+ yield m.start(), m.end(), \+ f"{_fmt(L.RANGE, a=a, b=b)} {L.SYM['percent']}"++ def _m_percent(self, text):+ L = self.lang+ for m in re.finditer(r"(-?)(\d+(?:,\d{2,3})*(?:\.\d+)?)\s*%", text):+ words = self._number_words(m.group(2))+ if m.group(1):+ words = f"{L.SYM['minus']} {words}"+ yield m.start(), m.end(), f"{words} {L.SYM['percent']}"++ # --- designations (Sony WH-1000XM5, Kepler-186f, Soyuz T-11) -----------+ def _m_designation(self, text):+ # TitleCase brand fused: Kepler-186f, Salyut-7+ for m in re.finditer(r"\b([A-Z][a-z]{2,})-([A-Za-z0-9]+)\b", text):+ seg = m.group(2)+ if not re.search(r"\d", seg):+ continue+ if self._month_index(seg) or self._month_index(m.group(1)):+ continue+ yield m.start(), m.end(), \+ f"{m.group(1)} {self._spell_model_segment(seg)}"+ # Brand word + short designation: Sony WH-1000XM5, Soyuz T-11+ pat = re.compile(+ r"\b([A-Z][a-z]{2,})\s+([A-Z]{1,4}-[A-Za-z0-9]+)\b")+ for m in pat.finditer(text):+ brand = m.group(1)+ if brand.lower() in self._id_keywords or brand.lower() in self._label_words:+ continue+ seg = m.group(2)+ if not re.search(r"\d", seg):+ continue+ yield (m.start(2), m.end(2), self._spell_model_segment(seg))++ # --- alphanumeric codes -------------------------------------------------+ def _m_code(self, text):+ # hyphenated tokens containing at least one letter and one digit+ pat = re.compile(r"#?\b(?=[A-Za-z0-9/-]*\d)(?=[A-Za-z0-9/-]*[A-Za-z])"+ r"[A-Za-z0-9]+(?:[-/][A-Za-z0-9]+)+(?![A-Za-z0-9])")+ for m in pat.finditer(text):+ tok = m.group(0).lstrip("#")+ # date like 12-Aug-2025 -> handled by date matcher (higher prio)+ parts = re.split(r"[-/]", tok)+ if (any(self._month_index(p) for p in parts)+ and all(p.isdigit() for p in parts+ if not self._month_index(p))):+ continue # date-like 12-Aug-2025; MAY-17Y7 is still a code+ # a lowercase word segment means this is prose, not a code+ # (900-point, 80-watt) -> handled by num-hyphen-word matcher+ if any(re.fullmatch(r"[a-z][a-z]+|[A-Z][a-z]{2,}", p) for p in parts):+ continue # prose word segment (900-point, 7-East)+ if (len(parts) == 2 and parts[0].isdigit() and parts[1].isalpha()+ and len(parts[1]) >= 3):+ continue # 30-DAY, 24-HOUR -> number + word+ # 15-GB -> unit matcher+ if (len(parts) == 2 and parts[0].isdigit()+ and parts[1].upper() in _UNIT_INITIALISMS):+ continue+ # Hall 3-A / Window 5-B -> label matcher (but CR-2A stays a code)+ if (re.fullmatch(r"\d{1,3}-?[A-Za-z]", tok)+ and self._keyword_before(text, m.start(),+ self._label_words, window=2)):+ continue+ if sum(c.isalnum() for c in tok) <= 2:+ continue+ yield m.start(), m.end(), self._spell_alnum(tok, comma=True)+ # solid mixed tokens (length>=5, >=2 digits): MH12AB8821, 77K2L9+ pat2 = re.compile(r"\b(?=(?:[A-Za-z]*\d){2})(?=[A-Za-z0-9]*[A-Za-z])"+ r"[A-Za-z0-9]{5,}\b")+ for m in pat2.finditer(text):+ tok = m.group(0)+ if re.fullmatch(r"\d+s", tok):+ continue # 1980s -> decade matcher+ if re.fullmatch(r"\d+[x×]\d+", tok):+ continue # 1920x1080 -> dimensions matcher+ m2 = re.fullmatch(r"\d+([A-Za-z]{1,4})", tok)+ if m2 and m2.group(1).upper() in _UNIT_INITIALISMS:+ continue # 250ml -> unit matcher+ if re.fullmatch(r"(?:[A-Z][a-z]?\d*)+", tok) and self._chem_ok(tok):+ continue # chemistry wins+ yield m.start(), m.end(), self._spell_alnum(tok, comma=True)++ def _m_vehicle_plate(self, text):+ # spaced Indian plates: AP 09 CL 4421 / TS 09 EA 1234+ L = self.lang+ pat = re.compile(r"\b([A-Z]{2})[ -](\d{1,2})[ -]([A-Z]{1,3})[ -](\d{3,4})\b")+ for m in pat.finditer(text):+ out = []+ for grp in m.groups():+ for ch in grp:+ out.append(L.digit(int(ch)) if ch.isdigit() else L.letter(ch))+ yield m.start(), m.end(), ", ".join(out)++ # --- identifier digit runs ----------------------------------------------+ def _m_long_digit_runs(self, text):+ if os.environ.get("FR3_TN_LONG_DIGITS", "0") != "1":+ return+ if __package__:+ from .identifier_rules import long_runs+ else:+ from identifier_rules import long_runs+ reserved = [(s, e) for matcher in (self._m_percent_range, self._m_percent, self._m_negative)+ for s, e, _ in matcher(text)]+ for s, e, spoken in long_runs(text, self.lang):+ if not any(s < end and e > start for start, end in reserved):+ yield s, e, spoken++ def _m_id_digits(self, text):+ L = self.lang+ # hyphen/space separated digit groups, or long runs, or # prefixed+ pat = re.compile(r"(\+?)(?:#?\b\d+(?:[-\s]\d+)+\b|#\s?\d{3,}\b"+ r"|(?<![\d.])(?<!\d,)\d{7,}(?![.,]?\d))")+ for m in pat.finditer(text):+ has_plus = m.group(1) == "+"+ tok = m.group(0).lstrip("+# ")+ groups = re.split(r"[-\s]", tok)+ digits = "".join(groups)+ is_id = False+ if has_plus and len(digits) >= 8:+ is_id = True # +91 ... country-code phone+ elif m.group(0).startswith("#"):+ is_id = True+ elif len(digits) >= 7 and " " not in tok:+ is_id = True+ elif any(len(g) >= 4 for g in groups) and len(groups) >= 2 and "-" in tok:+ is_id = True+ elif len(groups) >= 3 and "-" in tok:+ is_id = True+ elif self._keyword_before(text, m.start(), self._id_keywords):+ is_id = True+ else:+ a_toks = re.findall(r"[\w#ऀ-']+",+ _sentence_after(text, m.end()).lower())[:4]+ if any(t in self._id_keywords for t in a_toks):+ is_id = True+ if not is_id:+ continue+ # ranges like 10-20 without keyword: ascending small pairs -> skip+ a_toks2 = re.findall(r"[\w#ऀ-']+",+ _sentence_after(text, m.end()).lower())[:4]+ if ("-" in tok and len(groups) == 2+ and all(len(g) <= 3 for g in groups)+ and int(groups[0]) < int(groups[1])+ and not self._keyword_before(text, m.start(), self._id_keywords)+ and not any(t in self._id_keywords for t in a_toks2)):+ continue+ rep = self._digits_spelled(digits, comma=True)+ if has_plus:+ rep = f"{L.SYM['plus']} {rep}"+ yield m.start(), m.end(), rep+ # keyword-driven short runs: OTP 4471, code 22377, train 207,+ # "ending in 7104"+ for m in re.finditer(r"(?<![\d.])(?<!\d,)\d{3,6}(?![.,]?\d)(?!s\b)", text):+ # "139 dial करें" — dial/डायल shortly after marks a hotline number+ after_toks = re.findall(r"[\w#ऀ-']+",+ _sentence_after(text, m.end()).lower())[:6]+ id_after = {"dial", "डायल"} | set(self.lang.ID_AFTER_WORDS)+ if any(t in id_after for t in after_toks):+ yield m.start(), m.end(), \+ self._digits_spelled(m.group(0), comma=True)+ continue+ # an identifier keyword within ~4 tokens AFTER also marks it+ # ("4321 हा OTP", "998877 वापरा password") — but not label/year+ if (any(t in self._id_keywords for t in after_toks[:4])+ and not self._keyword_before(text, m.start(), self._label_words, window=2)+ and not self._keyword_before(text, m.start(),+ {w.lower() for w in L.YEAR_WORDS} | {"year"}, window=2)):+ yield m.start(), m.end(), \+ self._digits_spelled(m.group(0), comma=True)+ continue+ if self._keyword_before(text, m.start(), self._id_keywords):+ # label words override (Room 314 stays cardinal)+ if self._keyword_before(text, m.start(), self._label_words, window=2):+ continue+ # year words override (साल 2026)+ if self._keyword_before(text, m.start(),+ {w.lower() for w in L.YEAR_WORDS} | {"year"},+ window=2):+ continue+ yield m.start(), m.end(), \+ self._digits_spelled(m.group(0), comma=True)++ # --- chemistry ------------------------------------------------------------+ _ELEMENTS = {+ "H", "He", "Li", "Be", "B", "C", "N", "O", "F", "Ne", "Na", "Mg",+ "Al", "Si", "P", "S", "Cl", "Ar", "K", "Ca", "Fe", "Cu", "Zn", "Ag",+ "Au", "Hg", "Pb", "I", "Mn", "Cr", "Ni", "Sn", "Br", "Mg",+ }+ _CHEM_WHITELIST = {"HCl", "NaCl", "KCl", "NaOH", "KOH", "HBr", "HF",+ "CO", "NO", "NH3", "CH4", "H2O", "CO2", "SO2", "O2",+ "N2", "H2", "H2SO4", "HNO3", "CaCO3", "C6H12O6",+ "NaHCO3", "MgSO4", "ZnO", "FeO"}++ def _chem_ok(self, tok):+ if tok in self._CHEM_WHITELIST:+ return True+ pieces = re.findall(r"[A-Z][a-z]?|\d+", tok)+ letters = [p for p in pieces if not p.isdigit()]+ digits = [p for p in pieces if p.isdigit()]+ if not letters or any(p not in self._ELEMENTS for p in letters):+ return False+ return bool(digits) and len(letters) >= 2 or (bool(digits) and tok in self._CHEM_WHITELIST)++ def _m_chem(self, text):+ L = self.lang+ for m in re.finditer(r"\b(?:[A-Z][a-z]?\d*){1,8}\b", text):+ tok = m.group(0)+ if len(tok) < 2 or tok.upper() in _ACRONYM_WHITELIST:+ continue+ if not self._chem_ok(tok):+ continue+ out = []+ for piece in re.findall(r"[A-Z][a-z]?|\d+", tok):+ if piece.isdigit():+ out.append(L.cardinal(int(piece)))+ else:+ out.append(self._letters_spelled(piece.upper()))+ yield m.start(), m.end(), " ".join(out)++ # --- math -------------------------------------------------------------+ def _m_comparison(self, text):+ # Indic comparative phrases are postpositions: '<500' -> '500 से कम',+ # not 'से कम 500'. Treat the numeric bound as one semantic span.+ L = self.lang+ number = r"[+-]?\d+(?:,\d{2,3})*(?:\.\d+)?"+ operand = rf"(?:₹\s*)?{number}(?:\s*%)?"+ pattern = rf"(?<![\w.])(?:(?P<left>{operand})\s*)?(?P<op><=|>=|≤|≥|<|>)\s*(?P<right>{operand})"+ def words(token):+ s = token.strip()+ if s.startswith("₹"):+ return L.join_amount(self._number_words(s[1:].strip()), L.SYM["rupee"])+ if s.endswith("%"):+ return f"{self._number_words(s[:-1].strip())} {L.SYM['percent']}"+ return self._number_words(s)+ ors = {"hi": "या", "te": "లేదా", "ta": "அல்லது", "bn": "বা", "gu": "અથવા",+ "kn": "ಅಥವಾ", "ml": "അല്ലെങ്കിൽ", "mr": "किंवा", "or": "କିମ୍ବା", "pa": "ਜਾਂ"}+ for m in re.finditer(pattern, text):+ op = m['op']+ comparison = L.SYM["lt" if op.startswith("<") or op == "≤" else "gt"]+ if len(op) > 1 or op in ("≤", "≥"):+ comparison += " or equal to" if L.code == "en" else f" {ors[L.code]} {L.SYM['equals']}"+ left = words(m['left']) + " " if m['left'] else ""+ right = words(m['right'])+ yield m.start(), m.end(), left + (f"{comparison} {right}" if L.code == "en" else f"{right} {comparison}")++ def _m_math(self, text):+ L = self.lang+ S = L.SYM+ # power: 10^23 / x^2+ for m in re.finditer(r"(\d+(?:\.\d+)?|[A-Za-z])\s*\^\s*(\d+|[A-Za-z])", text):+ base, exp = m.group(1), m.group(2)+ bw = self._number_words(base) if base[0].isdigit() else L.letter(base)+ ew = self._number_words(exp) if exp[0].isdigit() else L.letter(exp)+ yield m.start(), m.end(), _fmt(L.POWER, base=bw, exp=ew)+ # squared ²+ for m in re.finditer(r"(\d+(?:\.\d+)?|[A-Za-z])²", text):+ v = m.group(1)+ vw = self._number_words(v) if v[0].isdigit() else L.letter(v)+ yield m.start(), m.end(), f"{vw} {S['squared']}"+ # √+ for m in re.finditer(r"√\s*(\d+(?:\.\d+)?)", text):+ yield m.start(), m.end(), f"{S['sqrt']} {self._number_words(m.group(1))}"+ # operator chains: x + 5 = 12, E = mc^2, 17 × 3 = 51 — rendered only+ # when a strong math operator (= × ÷ ^ √) is present, so hyphen+ # ranges/ids and prose like "e-mail" never match+ eq = re.compile(+ r"(?<![\w.])((?:[A-Za-z]{1,2}|\d+(?:\.\d+)?)"+ r"(?:\s*[=+\-−×*÷/^]\s*(?:[A-Za-z]{1,2}|\d+(?:\.\d+)?))+)")+ for m in eq.finditer(text):+ span = m.group(1)+ if not re.search(r"[=×÷^√]", span):+ continue+ yield m.start(1), m.end(1), self._render_math_expr(span)+ # single letters adjacent to verbal math words: "a squared plus b"+ for m in re.finditer(r"\b([A-Za-z])\b(?=\s+(?:squared|cubed|plus|minus|"+ r"times|equals|to the power)\b)", text):+ yield m.start(), m.end(), L.letter(m.group(1))+ # Operators are expanded in-place in _final_sweep. This also handles+ # thresholds without a left operand and preserves x < y word order.++ def _render_math_expr(self, span):+ L = self.lang+ S = L.SYM+ opmap = {"=": S["equals"], "+": S["plus"], "-": S["minus"],+ "−": S["minus"], "×": S["times"], "*": S["times"],+ "÷": S["divide"], "/": S["divide"]}+ toks = re.findall(r"\d+(?:\.\d+)?|[A-Za-z]+|[=+\-−×*÷/^]", span)+ out = []+ i = 0+ while i < len(toks):+ tok = toks[i]+ if tok == "^":+ # base already emitted; render exponent via the power template+ exp = toks[i + 1] if i + 1 < len(toks) else ""+ ew = (self._number_words(exp) if exp[:1].isdigit()+ else self._letters_spelled(exp.upper()))+ base = out.pop() if out else ""+ out.append(_fmt(L.POWER, base=base, exp=ew))+ i += 2+ continue+ if tok in opmap:+ out.append(opmap[tok])+ elif tok[0].isdigit():+ out.append(self._number_words(tok))+ else:+ out.append(self._letters_spelled(tok.upper()))+ i += 1+ return " ".join(out)++ # --- ranges -----------------------------------------------------------+ def _m_num_range(self, text):+ L = self.lang+ for m in re.finditer(r"(\d+(?:\.\d+)?)\s*[–]\s*(\d+(?:\.\d+)?)", text):+ a = self._number_words(m.group(1))+ b = self._number_words(m.group(2))+ yield m.start(), m.end(), _fmt(L.RANGE, a=a, b=b)+ # hyphen range: only ascending small pairs, no id keyword+ for m in re.finditer(r"\b(\d{1,3})-(\d{1,3})\b", text):+ if self._keyword_before(text, m.start(), self._id_keywords):+ continue+ a, b = int(m.group(1)), int(m.group(2))+ if a == b:+ # 50-50 -> "fifty fifty"+ yield m.start(), m.end(), f"{L.cardinal(a)} {L.cardinal(b)}"+ continue+ if a > b:+ if re.match(r"\s+(?:days?|months?|years?|hours?|minutes?)\b", text[m.end():], re.I):+ yield m.start(), m.end(), _fmt(L.RANGE, a=L.cardinal(a), b=L.cardinal(b))+ continue+ # score-style pair: "3-2 से जीते" -> "तीन दो"+ yield m.start(), m.end(), f"{L.cardinal(a)} {L.cardinal(b)}"+ continue+ yield m.start(), m.end(), \+ _fmt(L.RANGE, a=L.cardinal(a), b=L.cardinal(b))++ # --- dimensions / "x" as times: 24x7, 1920x1080, 6 x 4 -------------------+ def _m_dimensions(self, text):+ L = self.lang+ for m in re.finditer(+ r"\b(\d+(?:\.\d+)?)\s*[x×]\s*(\d+(?:\.\d+)?)\b", text):+ if m.group(1) == "0":+ continue # hex literals like 0x1F+ yield m.start(), m.end(), \+ f"{self._number_words(m.group(1))} {L.SYM['times']} " \+ f"{self._number_words(m.group(2))}"+ # lone x between something and a number (higher-priority matcher may+ # have consumed the left operand: "₹4,583.33 x 24")+ for m in re.finditer(r"(?<=\s)[x×](?=\s\d)", text):+ yield m.start(), m.end(), L.SYM["times"]++ # --- Roman numerals after label words: Class XII, World War II ----------+ _ROMAN_VALS = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}++ def _roman_value(self, s):+ total = 0+ for i, ch in enumerate(s):+ v = self._ROMAN_VALS[ch]+ if i + 1 < len(s) and self._ROMAN_VALS[s[i + 1]] > v:+ total -= v+ else:+ total += v+ return total++ def _m_roman(self, text):+ L = self.lang+ # {2,7}: single letters stay letters (Counter 2-C reads "C", not 100)+ pat = re.compile(+ r"\b(?=[IVXLCDM]{2,7}\b)M{0,3}(?:CM|CD|D?C{0,3})"+ r"(?:XC|XL|L?X{0,3})(?:IX|IV|V?I{0,3})\b")+ ctx = self._label_words | {"war", "vol", "part", "act", "book",+ "youdh", "युद्ध", "अध्याय", "कक्षा",+ "भाग", "खंड"}+ for m in pat.finditer(text):+ tok = m.group(0)+ if not tok:+ continue+ # only with a label-ish word right before — avoids XL sizes,+ # initials, and words like "MIX"+ if not self._keyword_before(text, m.start(), ctx, window=2):+ continue+ yield m.start(), m.end(), L.cardinal(self._roman_value(tok))++ # --- K/M/B suffixes glued to numbers: 3.4K, 1.2M -------------------------+ def _m_kmb_suffix(self, text):+ L = self.lang+ for m in re.finditer(r"(?<![\d.A-Za-z])(\d+(?:\.\d+)?)([KMB])\b", text):+ yield m.start(), m.end(), \+ f"{self._number_words(m.group(1))} {L.letter(m.group(2))}"++ # --- ordinals -----------------------------------------------------------+ def _m_ordinal(self, text):+ L = self.lang+ pat = re.compile(rf"\b(\d+)-?({self._ord_suffix_re})(?![A-Za-z0-9])", re.I)+ for m in pat.finditer(text):+ n = int(m.group(1))+ suf = m.group(2).lower()+ if suf in ("st", "nd", "rd", "th"):+ yield m.start(), m.end(), L.ordinal(n)+ else:+ yield m.start(), m.end(), L.ordinal(n, suf)++ # --- fractions -----------------------------------------------------------+ def _m_fraction(self, text):+ L = self.lang+ S = L.SYM+ pat = re.compile(r"\b(\d{1,4}(?:\.\d+)?)/(\d{1,4}(?:\.\d+)?)\b")+ for m in pat.finditer(text):+ a, b = m.group(1), m.group(2)+ if (a, b) == ("1", "2"):+ rep = S["half"]+ elif (a, b) == ("1", "4"):+ rep = S["quarter"]+ elif (a, b) == ("3", "4"):+ rep = S["three_quarters"]+ else:+ rep = _fmt(L.FRACTION, num=self._number_words(a),+ den=self._number_words(b))+ yield m.start(), m.end(), rep++ # --- ratios -----------------------------------------------------------+ def _m_ratio(self, text):+ L = self.lang+ for m in re.finditer(r"\b(\d{1,3}):(\d{1,2})\b", text):+ mm = m.group(2)+ # 2-digit right side <=59 looks like a time -> time matcher takes it+ if len(mm) == 2 and int(mm) <= 59 and not self._keyword_before(+ text, m.start(), self._ratio_kws, window=4):+ continue+ after = text[m.end():m.end() + 20].strip()+ if any(after.startswith(w) for w in self._ratio_kws if not+ w.isascii()):+ # source already says the ratio word ("1:3 నిష్పత్తిలో")+ yield m.start(), m.end(), \+ f"{L.cardinal(int(m.group(1)))} {L.cardinal(int(mm))}"+ continue+ yield m.start(), m.end(), \+ _fmt(L.RATIO, a=L.cardinal(int(m.group(1))),+ b=L.cardinal(int(mm)))++ # --- labels (Room 314, Hall 3-A, Seat 23A, coach B4) --------------------+ def _m_label(self, text):+ L = self.lang+ lbl = "|".join(re.escape(w) for w in sorted(self._label_words, key=len,+ reverse=True))+ pat = re.compile(+ rf"\b({lbl})\s+(?:(\d+)(?![\d.]|,\d)(?!-[A-Za-z]{{2,}})(?:[-\s]?([A-Za-z])\b)?|([A-Za-z])\b(?:[-\s]?(\d+))?)",+ re.IGNORECASE)+ for m in pat.finditer(text):+ word = m.group(1)+ out = [word]+ if m.group(2):+ out.append(L.cardinal(int(m.group(2))))+ if m.group(3):+ out.append(L.letter(m.group(3)))+ elif m.group(4):+ if len(m.group(4)) == 1:+ out.append(L.letter(m.group(4)))+ else:+ out.append(m.group(4))+ if m.group(5):+ out.append(L.cardinal(int(m.group(5))))+ yield m.start(), m.end(), " ".join(out)++ # --- ALLCAPS model prefix + number: "XPS 15" ----------------------------+ def _m_acronym_model(self, text):+ L = self.lang+ for m in re.finditer(r"\b([A-Z]{2,4})\s+(\d{1,3})(?![\d.])", text):+ tok = m.group(1)+ if tok in _ACRONYM_WHITELIST or tok.upper() in _UNIT_INITIALISMS:+ continue+ if tok.lower() in self._id_keywords or tok.lower() in self._label_words:+ continue+ yield m.start(), m.end(), \+ f"{self._letters_spelled(tok)} {L.cardinal(int(m.group(2)))}"++ # --- unit initialisms after numbers: 1.5 GB, 5,000 mAh ------------------+ def _m_unit_initialism(self, text):+ L = self.lang+ units = "|".join(sorted(_UNIT_INITIALISMS, key=len, reverse=True))+ pat = re.compile(+ rf"(?<![\w.])(-?)\b(\d+(?:,\d{{2,3}})*(?:\.\d+)?)[\s\-]?({units})"+ rf"(?:\s?/\s?([A-Za-z]{{1,4}}))?\b",+ re.IGNORECASE)+ for m in pat.finditer(text):+ unit = m.group(3)+ if unit.upper() not in _UNIT_INITIALISMS:+ continue+ # single-letter units (V, W) only when written in caps —+ # a lowercase "5 v" is too ambiguous+ if len(unit) == 1 and not unit.isupper():+ continue+ num = self._number_words(m.group(2))+ if m.group(1):+ num = f"{L.SYM['minus']} {num}"+ uk = re.sub(r"[^A-Za-z]", "", unit).upper()+ word = L.UNIT_WORDS.get(uk) or self._letters_spelled(uk)+ rep = L.join_amount(num, word)+ if m.group(4):+ u2 = m.group(4).upper()+ w2 = L.UNIT_WORDS.get(u2) or self._letters_spelled(u2)+ rep += f" {L.SYM.get('per', 'per')} {w2}"+ yield m.start(), m.end(), rep++ # --- number-hyphen-word: 80-watt, 900-point ------------------------------+ def _m_num_hyphen_word(self, text):+ for m in re.finditer(r"\b(\d+(?:,\d{2,3})*(?:\.\d+)?)-([A-Za-zऀ-ൿ]{2,})\b",+ text):+ word = m.group(2)+ if self._month_index(word):+ continue # 12-Aug+ if word.upper() in _UNIT_INITIALISMS:+ continue # unit matcher handles+ num = self._number_words(m.group(1))+ yield m.start(), m.end(), f"{num} {word}"++ # --- decades ------------------------------------------------------------+ def _m_decade(self, text):+ L = self.lang+ for m in re.finditer(r"\b(19|20)(\d)0s\b", text):+ if m.group(1) == "19":+ # 1980s -> "eighty's decade" (spec)+ yield m.start(), m.end(), L.decade(int(m.group(2)) * 10, full=True)+ else:+ # 2020s -> full year words + decade template+ y = int(m.group(0)[:4])+ yield m.start(), m.end(), _fmt(L.DECADE_FULL, tens=L.year(y))+ for m in re.finditer(r"(?<![\w])'?(\d)0s\b", text):+ yield m.start(), m.end(), L.decade(int(m.group(1)) * 10, full=False)++ # --- years ---------------------------------------------------------------+ def _m_year(self, text):+ L = self.lang+ year_words = {w.lower() for w in L.YEAR_WORDS} | \+ {"year", "in", "since", "by", "from", "साल", "वर्ष"}+ for m in re.finditer(r"\b(1[5-9]\d{2}|20\d{2})\b", text):+ y = int(m.group(0))+ ctx = self._keyword_before(text, m.start(), year_words, window=2)+ # attached native locative suffix right after: 1947में / 1947-ல்+ after = text[m.end():m.end() + 20]+ # danda ।/॥ are inside the Devanagari block — they are sentence+ # punctuation, not a locative suffix+ suffixed = bool(re.match(r"^-?(?![।॥])[ऀ-]", after))+ # following token is/starts with a year word: "1947 সালে",+ # "1983 साली", "१९४७ ମସିହାରେ", or Hindi locatives+ next_tok = after.strip().split()[0] if after.strip() else ""+ follower = next_tok in ("में", "से", "तक", "માં", "मध्ये",+ "ਵਿੱਚ", "ਤੋਂ") or any(+ next_tok.startswith(w) for w in L.YEAR_WORDS if w)+ if ctx or suffixed or follower:+ yield m.start(), m.end(), L.year(y)++ # --- quoted single letters: reply 'Y' -----------------------------------+ def _m_quoted_letter(self, text):+ for m in re.finditer(r"['\"‘“]([A-Za-z])['\"’”]", text):+ yield m.start(), m.end(), self.lang.letter(m.group(1))++ # --- short mixed tokens: 5G, A4, B12, Y2K, S24, A380 ---------------------+ def _m_short_mixed_token(self, text):+ L = self.lang+ pat = re.compile(r"(?<![\d.])\b(?=[A-Za-z0-9]{2,5}\b)"+ r"(?=[A-Za-z0-9]*\d)(?=[A-Za-z0-9]*[A-Za-z])"+ r"[A-Za-z0-9]+\b")+ for m in pat.finditer(text):+ tok = m.group(0)+ if re.fullmatch(r"\d+(?:st|nd|rd|th|s)", tok):+ continue # ordinals / decades+ out = []+ for run in re.findall(r"[A-Za-z]+|\d+", tok):+ if run.isdigit():+ out.append(L.cardinal(int(run)))+ else:+ out.append(self._letters_spelled(run.upper()))+ yield m.start(), m.end(), " ".join(out)++ # --- decimals -------------------------------------------------------------+ def _m_decimal(self, text):+ # trailing (?!\.?\d) instead of (?![\d.]) so a sentence-final full+ # stop after the decimal ("...830.93.") doesn't block the match+ for m in re.finditer(+ r"(?<![\d.])(\d{1,3}(?:,\d{2,3})+|\d+)\.(\d+)(?!\.?\d)", text):+ yield m.start(), m.end(), \+ self.lang.decimal(int(m.group(1).replace(",", "")), m.group(2))++ # --- negative numbers -------------------------------------------------------+ def _m_negative(self, text):+ L = self.lang+ for m in re.finditer(r"(?<![\w.,-])-(\d+(?:\.\d+)?)", text):+ yield m.start(), m.end(), \+ f"{L.SYM['minus']} {self._number_words(m.group(1))}"++ # --- plain integers ----------------------------------------------------------+ def _m_int(self, text):+ L = self.lang+ for m in re.finditer(r"\b\d{1,3}(?:,\d{2,3})+\b|\b\d+\b", text):+ digits = m.group(0).replace(",", "")+ # street numbers read year-style (1422 गांधी मार्ग -> चौदह सौ बाईस)+ after = text[m.end():m.end() + 30].strip().lower()+ first_words = after.split()[:2]+ if (len(digits) == 4 and digits[0] != "0"+ and any(w.strip(".,") in _STREET_WORDS for w in first_words)):+ yield m.start(), m.end(), L.year(int(digits))+ continue+ if digits.startswith("0") and len(digits) > 1:+ yield m.start(), m.end(), self._digits_spelled(digits, comma=True)+ continue+ yield m.start(), m.end(), L.cardinal(int(digits))++ # ------------------------------------------------------------------+ # Final sweep: leftover meaningful symbols -> words; decorative junk out+ # ------------------------------------------------------------------+ def _final_sweep(self, text):+ S = self.lang.SYM+ text = re.sub(r"<=|≤", " less than or equal to ", text)+ text = re.sub(r">=|≥", " greater than or equal to ", text)+ text = re.sub(r"°\s*C\b", f" {S['celsius']} ", text)+ text = re.sub(r"°\s*F\b", f" {S['fahrenheit']} ", text)+ text = text.replace("°", f" {S['degree']} ")+ rep = {"%": S["percent"], "@": S["at"], "&": S["amp"],+ "=": S["equals"], "+": S["plus"], "×": S["times"],+ "÷": S["divide"], "±": S["plus_minus"], "√": S["sqrt"],+ "_": S["underscore"], "#": S["hash"]}+ for sym, word in rep.items():+ text = text.replace(sym, f" {word} ")+ text = text.replace("<", f" {S['lt']} ").replace(">", f" {S['gt']} ")+ text = re.sub(r"[\^*]", " ", text)+ # slashes not consumed by URL/fraction/date/code matchers are junk+ text = re.sub(r"\s*/\s*", " ", text)+ # clause colons read as a pause ("అడ్రస్: Door" -> "అడ్రస్, Door")+ text = re.sub(r"\s*:\s*", ", ", text)+ text = re.sub(r"[₹$€£](?!\s?\d)", " ", text) # bare currency signs+ text = re.sub(r"[–—]", " ", text)+ return text++ # ------------------------------------------------------------------+ # Fallback: absolutely no digits may remain+ # ------------------------------------------------------------------+ def _digit_fallback(self, text):+ def repl(m):+ d = m.group(0)+ if len(d) >= 7 or d.startswith("0"):+ return self._digits_spelled(d, comma=True)+ return self.lang.cardinal(int(d))+ return re.sub(r"\d+", repl, text)++ # ------------------------------------------------------------------+ def normalize(self, text):+ validate_text(text, date_order=self.date_order, two_digit_year_base=self.two_digit_year_base, language=self.lang.code)+ # URLs/emails are opaque identifiers. Protect them before prose cleanup+ # can expand Dr/No inside a path or turn // and parentheses into pauses.+ raw = _ascii_digits(text)+ protected, originals, spans = {}, {}, []+ identifiers = (self._m_email, self._m_url)+ if os.environ.get("FR3_TN_URL_SPELL", "0") == "1":+ identifiers += (self._m_handle,)+ for matcher in identifiers:+ for s, e, spoken in matcher(raw):+ if not any(s < b and e > a for a, b, _ in spans):+ key = chr(0xF0000 + len(protected))+ protected[key] = spoken+ originals[key] = raw[s:e]+ spans.append((s, e, key))+ for s, e, key in sorted(spans, reverse=True):+ raw = raw[:s] + key + raw[e:]+ text = raw+ text = self._preclean(text)+ try:+ matches = self._gather(text)+ except NormalizationError as exc:+ if exc.span is not None:+ start, end = exc.span+ pieces = [text[:start], text[start:end], text[end:]]+ # Parser coordinates refer to precleaned text containing opaque+ # URI placeholders. Restore their source text before retrying.+ for key, original in originals.items():+ pieces = [piece.replace(key, original) for piece in pieces]+ exc.source = "".join(pieces)+ exc.span = (len(pieces[0]), len(pieces[0]) + len(pieces[1]))+ raise+ # priority asc, then leftmost, then longest+ matches.sort(key=lambda t: (t[0], t[1], -(t[2] - t[1])))+ taken = []+ accepted = []+ for prio, s, e, rep in matches:+ if any(not (e <= ts or s >= te) for ts, te in taken):+ continue+ taken.append((s, e))+ accepted.append((s, e, rep))+ accepted.sort(key=lambda t: t[0])+ out = []+ pos = 0+ for s, e, rep in accepted:+ out.append(text[pos:s])+ pos = e+ # native postposition right after the span (spaced OR attached:+ # "గంటలు కి" / "6:30కి") -> language attaches it with sandhi+ while True:+ nxt = re.match(r"[ \t]*-?([^\s\d,।.!?;:()\-—–]{1,14})",+ text[pos:])+ if not nxt:+ break+ if text[pos + nxt.end(): pos + nxt.end() + 1] == ".":+ break # abbreviation like కి.మీ — not a postposition+ merged = self.lang.attach_postposition(rep, nxt.group(1))+ if merged is None:+ break+ rep = merged+ pos += nxt.end()+ out.append(rep)+ out.append(text[pos:])+ result = "".join(out)+ result = self._final_sweep(result)+ result = self._digit_fallback(result)+ for key, spoken in protected.items():+ result = result.replace(key, spoken)+ # A foreign cardinal must never be glued into an Indic suffix (fiveన).+ result = re.sub(r"(?<=[A-Za-z])(?=[\u0900-\u0DFF])", " ", result)+ # tidy whitespace / punctuation spacing+ result = re.sub(r"\s+([,।.!?;])", r"\1", result)+ result = re.sub(r",\s*([।.!?;,])", r"\1", result)+ result = re.sub(r",(?=\S)", ", ", result) # space after every comma+ result = re.sub(r"\s{2,}", " ", result)+ result = re.sub(r"\s+’", "’", result)+ result = re.sub(r"[,\s]+$", ".", result) if result.rstrip().endswith(",") else result+ if self.lang.code == "hi":+ result = result.translate(_HINDI_NUKTA_FOLD)+ return result.strip()+++++# ---------------------------------------------------------------------------+# English table (the only language table)+# ---------------------------------------------------------------------------++_ONES_0_19 = ["zero", "one", "two", "three", "four", "five", "six", "seven",+ "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen",+ "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]+_TENS = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy",+ "eighty", "ninety"]+++def _two_digit(n):+ """0..99 -> 'zero' .. 'ninety nine'. No hyphen: the model reads words."""+ if n < 20:+ return _ONES_0_19[n]+ t, o = divmod(n, 10)+ return _TENS[t] if not o else f"{_TENS[t]} {_ONES_0_19[o]}"+++_ORDINAL_IRREGULAR = {1: "first", 2: "second", 3: "third", 5: "fifth", 8: "eighth",+ 9: "ninth", 12: "twelfth"}+++def _ordinal(n):+ if n in _ORDINAL_IRREGULAR:+ return _ORDINAL_IRREGULAR[n]+ w = _two_digit(n) if n < 100 else None+ if w is None:+ return None+ # twenty-first, thirty-second ... take the irregular form on the last digit+ tail = n % 10+ if n >= 20 and tail in _ORDINAL_IRREGULAR:+ return f"{_TENS[n // 10]} {_ORDINAL_IRREGULAR[tail]}"+ if w.endswith("y"): # twenty -> twentieth+ return w[:-1] + "ieth"+ return w + "th"+++class English(LangBase):+ code = "en"+ name = "English"+ native_digits = "0123456789" # English uses ASCII digits++ ONES = [_two_digit(i) for i in range(100)]+ HUNDRED = "hundred"+ THOUSAND = "thousand"+ LAKH = "lakh"+ CRORE = "crore"++ # Letter names are already English, so each maps to itself.+ LETTERS = {chr(65 + i): chr(65 + i) for i in range(26)}++ MONTHS = ["January", "February", "March", "April", "May", "June", "July",+ "August", "September", "October", "November", "December"]++ SYM = {+ "rupee": "rupees", "dollar": "dollars", "euro": "euros",+ "pound": "pounds", "cent": "cents",+ "percent": "percent",+ "point": "point",+ "minus": "minus", "plus": "plus", "equals": "equals",+ "times": "times", "divide": "divided by",+ "squared": "squared", "sqrt": "square root of",+ "lt": "less than", "gt": "greater than",+ "plus_minus": "plus or minus",+ "at": "at", "underscore": "underscore", "dot": "dot",+ "slash": "slash", "hash": "hash", "amp": "and",+ "half": "half", "quarter": "quarter", "three_quarters": "three quarters",+ "degree": "degrees", "celsius": "celsius", "fahrenheit": "fahrenheit",+ "minute": "minutes",+ }++ TIME_ON_HOUR = "{h} o'clock"+ TIME_HM = "{h} {m}" # "ten thirty" — how a clock is read aloud+ RANGE = "{a} to {b}"+ RANGE_TO = "{a} to {b}"+ RATIO = "{a} to {b}"+ POWER = "{base} to the power {exp}"+ FRACTION = "{num} over {den}"+ DECADE_SHORT = "{tens}s"+ DECADE_FULL = "{tens}s"++ PERIODS = {"morning": "in the morning", "afternoon": "in the afternoon",+ "evening": "in the evening", "night": "at night"}++ # ---- vocabulary the engine must recognise in the INPUT ----------------+ TIME_MARKERS = ["o'clock", "oclock"]+ MARKER_SUFFIXES = {}+ PERIOD_DETECT = {"morning": "morning", "afternoon": "afternoon",+ "evening": "evening", "night": "night",+ "am": "morning", "a.m.": "morning",+ "pm": "afternoon", "p.m.": "afternoon"}+ YEAR_WORDS = ["year", "years"]+ # Deliberately NOT "order"/"invoice"/"ticket" on their own: "your order is 250+ # rupees" is a price, and listing them made it read "two, five, zero". They only+ # mark an identifier in the explicit "order number ..." form, which "number" catches.+ # One normalizer serves every language, so an identifier must be recognised+ # whatever script the sentence around it is written in. Without the native+ # words, "ऑर्डर नंबर 47291" reads as a cardinal instead of digit-by-digit.+ ID_KEYWORDS = ["number", "pin", "otp", "pnr", "imei", "ifsc", "account", "नंबर", "नम्बर",+ "खाता", "खाते", "कोड", "ऑर्डर", "फ़ोन", "फोन", "मोबाइल", "నంబర్", "నంబరు", "నెంబర్",+ "నెంబరు", "ఖాతా", "ఫోన్", "మొబైల్", "కోడ్", "ఆర్డర్", "ఎక్స్ప్రెస్", "express",+ "అకౌంట్", "టికెట్", "రిజిస్ట్రేషన్", "యూజర్", "వాయిదా", "అంకె", "లావాదేవీ", "పిన్",+ "எண்", "நம்பர்", "கணக்கு", "தொலைபேசி", "போன்", "மொபைல்", "ஆர்டர்", "ஓடிபி", "பின்",+ "ஐடி", "கடவுச்சொல்", "ரயில்", "எக்ஸ்பிரஸ்", "பிஎன்ஆர்", "கார்டு", "குறியீடு",+ "டிக்கெட்", "கணக்கில்", "யூசர்", "தவணை", "இலக்கம்", "பரிவர்த்தனை", "ನಂಬರ್", "ಸಂಖ್ಯೆ",+ "ಖಾತೆ", "ಕೋಡ್", "ಆರ್ಡರ್", "ಫೋನ್", "ಮೊಬೈಲ್", "ಐಡಿ", "ಪಿನ್", "ಪಾಸ್ವರ್ಡ್", "ರೈಲು",+ "ಎಕ್ಸ್ಪ್ರೆಸ್", "ಪಿಎನ್ಆರ್", "ಕಾರ್ಡ್", "ರೆಫರೆನ್ಸ್", "ಟ್ರಾನ್ಸಾಕ್ಷನ್", "ಟಿಕೆಟ್", "ಓಟಿಪಿ",+ "ಅಕೌಂಟ್", "ಅಂಕಿ", "ಬಳಕೆದಾರ", "ಕಂತು", "ವಹಿವಾಟು", "നമ്പർ", "നമ്പര്", "നമ്പറിൽ",+ "അക്കൗണ്ട്", "കോഡ്", "ഓർഡർ", "ഫോൺ", "മൊബൈൽ", "ഒടിപി", "പിൻ", "ഐഡി", "പാസ്വേഡ്",+ "ട്രെയിൻ", "എക്സ്പ്രസ്", "പിഎൻആർ", "കാർഡ്", "റഫറൻസ്", "ട്രാൻസാക്ഷൻ", "ടിക്കറ്റ്",+ "അക്കൗണ്ടിൽ", "നമ്പറിലേക്ക്", "യൂസർ", "തവണ", "അക്കം", "ഇടപാട്", "क्रमांक", "खात्याचा",+ "खात्यावर", "मोबाईल", "अकाउंट", "अकाउंटसाठी", "अकाउंटमधून", "खात्यातून", "खात्यात",+ "खात्याची", "पिन", "आयडी", "पासवर्ड", "ट्रेन", "एक्सप्रेस", "पीएनआर", "कार्ड",+ "रेफरन्स", "ट्रांझॅक्शन", "तिकीट", "ओटीपी", "गाडी", "युजर", "यूजर", "हप्ता",+ "हप्त्याचा", "अंक", "व्यवहार", "ट्रान्झॅक्शन", "क्र", "क्रं", "चेक", "धनादेश", "নম্বর",+ "নাম্বার", "অ্যাকাউন্ট", "একাউন্ট", "কোড", "অর্ডার", "ফোন", "মোবাইল", "ওটিপি", "পিন",+ "আইডি", "পাসওয়ার্ড", "ট্রেন", "এক্সপ্রেস", "পিএনআর", "কার্ড", "রেফারেন্স",+ "ট্রানজেকশন", "টিকিট", "অ্যাকাউন্টের", "নম্বরে", "আইডিতে", "ইউজার", "ইনস্টলমেন্ট",+ "কিস্তি", "ডিজিট", "অঙ্ক", "লেনদেন", "નંબર", "નમ્બર", "ખાતા", "ખાતું", "ખાતાં", "કોડ",+ "ઓર્ડર", "ફોન", "મોબાઇલ", "મોબાઈલ", "એકાઉન્ટ", "એકાઉન્ટમાં", "એકાઉન્ટનો", "પિન",+ "આઈડી", "પાસવર્ડ", "ટ્રેન", "એક્સપ્રેસ", "પીએનઆર", "કાર્ડ", "રેફરન્સ", "ટ્રાન્ઝેક્શન",+ "ટિકિટ", "ઓટીપી", "નંબરમાં", "યુઝર", "હપ્તો", "અંક", "ડિજિટ", "ਨੰਬਰ", "ਖਾਤਾ", "ਖਾਤੇ",+ "ਕੋਡ", "ਆਰਡਰ", "ਫ਼ੋਨ", "ਫੋਨ", "ਮੋਬਾਈਲ", "ਮੋਬਾਇਲ", "ਅਕਾਊਂਟ", "ਅਕਾਊਂਟਵਿੱਚ", "ਪਿੰਨ",+ "ਆਈਡੀ", "ਪਾਸਵਰਡ", "ਟ੍ਰੇਨ", "ਐਕਸਪ੍ਰੈਸ", "ਪੀਐਨਆਰ", "ਕਾਰਡ", "ਰੈਫਰੈਂਸ", "ਟਿਕਟ", "ਓਟੀਪੀ",+ "ਯੂਜ਼ਰ", "ਕਿਸ਼ਤ", "ਅੰਕ", "ਲੈਣ-ਦੇਣ", "ନମ୍ବର", "ନମ୍ବର୍", "ଖାତା", "ଆକାଉଣ୍ଟ", "କୋଡ୍",+ "ଅର୍ଡର", "ଫୋନ୍", "ଫୋନ", "ମୋବାଇଲ୍", "ମୋବାଇଲ", "ଓଟିପି", "ପିନ୍", "ଆଇଡି", "ପାସୱାର୍ଡ",+ "ଏକ୍ସପ୍ରେସ", "ପିଏନ୍ଆର୍", "କାର୍ଡ", "ରେଫରେନ୍ସ", "ଟିକେଟ", "ଆକାଉଣ୍ଟରୁ", "ଟ୍ରେନ୍", "ୟୁଜର",+ "କିସ୍ତି", "ଅଙ୍କ", "ଲାଣଦେଣ"]+ ID_AFTER_WORDS = ["number", "code", "खत्म", "डायल", "कॉल", "संपर्क", "ఎండ్", "ముగిసే",+ "ముగుస్తుంది", "చివర", "చివరి", "అంకెలతో", "డయల్", "పిన్", "పిన్కోడ్", "pin",+ "pincode", "కాల్", "సంప్రదించండి", "டயல்", "அழை", "தொடர்பு", "ಡಯಲ್", "ಕರೆ", "ಸಂಪರ್ಕ",+ "ডায়াল", "কল", "যোগাযোগ", "ડાયલ", "કૉલ", "સંપર્ક", "ਡਾਇਲ", "ਕਾਲ", "ਸੰਪਰਕ", "ଡାଏଲ",+ "କଲ", "ଯୋଗାଯୋଗ"]+ LABEL_WORDS = ["room", "flat", "floor", "gate", "platform", "seat",+ "section", "chapter", "page", "block", "phase"]+ MINUTE_WORDS = ["minute", "minutes", "min", "mins"]+ SCALE_WORDS = {"crore": "crore", "crores": "crore", "cr": "crore",+ "lakh": "lakh", "lakhs": "lakh", "lac": "lakh",+ "thousand": "thousand", "thousands": "thousand", "k": "thousand"}+ CURRENCY_WORDS = {"rupee": "rupee", "rupees": "rupee", "rs": "rupee",+ "inr": "rupee", "dollar": "dollar", "dollars": "dollar",+ "usd": "dollar", "euro": "euro", "euros": "euro",+ "pound": "pound", "pounds": "pound",+ "paisa": "cent", "paise": "cent",+ "cent": "cent", "cents": "cent"}++ # Unit initialisms spoken as full words instead of letters. The engine+ # falls back to letter-spelling ("K G") when a key is absent, which is+ # right for GB/MB but wrong for the metric units customers actually say.+ UNIT_WORDS = {+ "KG": "kilograms", "KM": "kilometers", "CM": "centimeters",+ "MM": "millimeters", "GM": "grams", "MG": "milligrams",+ "ML": "millilitres", "MCG": "micrograms",+ "KMPH": "kilometers per hour", "MPH": "miles per hour",+ "KWH": "kilowatt hours", "RPM": "R P M",+ }++ # Written-only abbreviations expanded wherever they appear. Case-insensitive,+ # guarded by word boundaries, so "Drew" and "MIN-22" are untouched.+ ABBREV_UNITS = {+ "MINS": "minutes", "MIN": "minutes", "HRS": "hours", "SECS": "seconds",+ "DR": "doctor", "MR": "mister", "MRS": "missus", "MS": "miss",+ "PROF": "professor", "LTD": "limited", "PVT": "private",+ "A/C": "account", "APPROX": "approximately", "ETA": "E T A",+ }++ # "No. 12" -> "number twelve"+ NUMBER_WORD = "number"++ # English transcribes the am/pm that was written; it never invents a period.+ # "6.45 pm" -> "six forty five p m", NOT "six forty five in the evening".+ AMPM_WORDS = {"am": "a m", "pm": "p m"}++ ORDINAL_EXCEPTIONS = {n: _ordinal(n) for n in range(1, 100) if _ordinal(n)}+ ORDINAL_SUFFIX = "th"+ ORDINAL_INPUT_SUFFIXES = ["st", "nd", "rd", "th"]+++ def time_phrase(self, h, m, period_key=None):+ """English puts the period AFTER the clock time — "five in the evening", not+ the base class's Indo-Aryan "in the evening five" (शाम पाँच बजे)."""+ if h == 0:+ core = "zero " + ("hundred" if m == 0 else self.two_digit(m))+ else:+ core = super().time_phrase(h, m, None)+ return f"{core} {self.PERIODS[period_key]}" if period_key else core++ def _ordinal_compose(self, n, src_suffix=""):+ if n < 100:+ return "zeroth" if n == 0 else _ordinal(n)+ for scale, word in ((10**7, self.CRORE), (10**5, self.LAKH),+ (1000, self.THOUSAND), (100, self.HUNDRED)):+ if n >= scale:+ count, rest = divmod(n, scale)+ head = f"{self.cardinal(count)} {word}"+ return f"{head} {self.ordinal(rest)}" if rest else head + "th"+++LANG = English()+_NORMALIZER = Normalizer(LANG)+++@lru_cache(maxsize=66)+def _engine(language, date_order, two_digit_year_base):+ return Normalizer(language_table(language), date_order=date_order, two_digit_year_base=two_digit_year_base)+++def normalize(text, language="en-IN", *, date_order="DMY", two_digit_year_base=None):+ """Locale-specific numbers and symbols; prose is preserved, never translated.++ Omitted language retains Indian English for compatibility. Use an explicit+ language/locale for Indic speech. language="auto" selects majority-script+ inference with a guard against introducing foreign-script expansions.+ """+ auto = isinstance(language, str) and language == "auto"+ original = text+ if auto:+ if __package__:+ from .script_guard import detect_language, guard_output+ else:+ from script_guard import detect_language, guard_output+ language = detect_language(text) if isinstance(text, str) else "en-IN"+ code = resolve_language(language)+ # Validate before accessing the cache, including unhashable option values.+ warning = None+ while True:+ try:+ validate_text(text, date_order=date_order, two_digit_year_base=two_digit_year_base, language=code)+ result = _engine(code, date_order, two_digit_year_base).normalize(text)+ break+ except NormalizationError as exc:+ # Request type/options are not text tokens and cannot be rendered.+ if os.environ.get("FR3_TN_STRICT", "0") == "1" or exc.span is None:+ raise+ warning = warning or exc.code+ source = exc.source if exc.source is not None else text+ start, end = exc.span+ token = source[start:end]+ locale = language_table(code)+ symbols = {"/": "slash", ".": "dot", "-": "minus", "+": "plus",+ "@": "at", "_": "underscore", "₹": "rupee", "$": "dollar",+ "%": "percent"}+ words = []+ for char in token:+ if char.isdecimal():+ words.append(" " + locale.ONES[unicodedata.decimal(char)] + " ")+ elif char in symbols:+ words.append(" " + locale.SYM[symbols[char]] + " ")+ elif char in ",:;<>{}" or unicodedata.category(char) in ("Cc", "Co"):+ words.append(" ")+ else:+ words.append(char)+ replacement = "".join(words)+ if replacement == token:+ raise # no progress: do not loop on a new, unhandled error+ text = source[:start] + " " + replacement + " " + source[end:]+ if warning:+ # One privacy-safe observation per normalization call, never caller text.+ try:+ import obs+ obs.event("normalization_fallback", level="warn", code=warning)+ except ImportError:+ print("[obs] " + json.dumps({"event": "normalization_fallback", "level": "warn", "code": warning}), flush=True)+ return guard_output(original, result, language_table(code)) if auto else result+++if __name__ == "__main__":+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("text", nargs="?", help="Plain text; otherwise read stdin.")+ parser.add_argument("--date-order", choices=("DMY", "MDY"), default="DMY")+ parser.add_argument("--language", default="en-IN", help="Language code/name, including hi, te and en-IN.")+ parser.add_argument("--two-digit-year-base", type=int, choices=(1900, 2000))+ args = parser.parse_args()+ try:+ print(normalize(args.text if args.text is not None else sys.stdin.read(), language=args.language,+ date_order=args.date_order, two_digit_year_base=args.two_digit_year_base))+ except NormalizationError as exc:+ print(f"{exc.code}: {exc}", file=sys.stderr)+ sys.exit(2)diff --git a/maya3/text/tn/script_guard.py b/maya3/text/tn/script_guard.pynew file mode 100644index 0000000..5c160e7--- /dev/null+++ b/maya3/text/tn/script_guard.py@@ -0,0 +1,53 @@+"""Deterministic, CPU-only locale inference and output script containment.++Count letters/marks, not shared danda punctuation or decimal digits. Devanagari+cannot distinguish Hindi/Marathi: auto uses Hindi; explicit Marathi is preferred.+"""+import unicodedata+from collections import Counter++BLOCKS = ((0x0900, 0x097F, 'hi'), (0x0980, 0x09FF, 'bn'),+ (0x0A00, 0x0A7F, 'pa'), (0x0A80, 0x0AFF, 'gu'),+ (0x0B00, 0x0B7F, 'or'), (0x0B80, 0x0BFF, 'ta'),+ (0x0C00, 0x0C7F, 'te'), (0x0C80, 0x0CFF, 'kn'),+ (0x0D00, 0x0D7F, 'ml'))+++def script_counts(text):+ counts = Counter()+ for c in text:+ if unicodedata.category(c)[0] not in 'LM':+ continue+ if unicodedata.name(c, '').startswith('LATIN'):+ counts['en-IN'] += 1+ continue+ for low, high, code in BLOCKS:+ if low <= ord(c) <= high:+ counts[code] += 1+ break+ return counts+++def detect_language(text):+ counts = script_counts(text)+ code = max(counts, key=counts.get) if counts else 'en-IN'+ if code == 'bn' and any(c in text for c in 'ৰৱ'):+ return 'as'+ return code+++def guard_output(original, result, locale):+ allowed = set(script_counts(original))+ # A numeric/symbol-only input supplies no script; use the default locale.+ if not allowed or set(script_counts(result)) <= allowed:+ return result+ # Fail conservatively: preserve prose and read the original digits in the+ # chosen input script; never return a generated foreign-script expansion.+ if __package__:+ from .normalize import language_table+ else:+ from normalize import language_table+ locale = language_table(detect_language(original))+ result = ''.join(' ' + locale.digit(unicodedata.decimal(c)) + ' '+ if c.isdecimal() else c for c in original)+ return ' '.join(result.split()) if set(script_counts(result)) <= allowed else originaldiff --git a/maya3/text/tn/text_pipeline.py b/maya3/text/tn/text_pipeline.pynew file mode 100644index 0000000..5fa6602--- /dev/null+++ b/maya3/text/tn/text_pipeline.py@@ -0,0 +1,124 @@+"""CPU-only request preparation shared by HTTP and WebSocket serving.++No model imports, logging of caller text, or silent raw-text fallback.+"""+if __package__:+ from .normalize import LANGUAGE_NAMES, NormalizationError, validate_text, resolve_language+ from .script_guard import detect_language+else:+ from normalize import LANGUAGE_NAMES, NormalizationError, validate_text, resolve_language+ from script_guard import detect_language++NORMALIZATION_LANGUAGES = tuple(LANGUAGE_NAMES)+++class PipelineError(Exception):+ def __init__(self, code, message, status=422):+ self.code, self.status = code, status+ super().__init__(message)++ def payload(self):+ return {"error": str(self), "code": self.code}+++def prepare_text(text, *, normalizer, splitter, post_process, normalize_enabled=True,+ chunk_enabled=True, date_order="DMY", two_digit_year_base=None, max_chunk_chars=None,+ normalization_language="en-IN"):+ try:+ if not normalize_enabled:+ validate_text(text, date_order=date_order, two_digit_year_base=two_digit_year_base, language=detect_language(text) if normalization_language is None and isinstance(text, str) else normalization_language)+ if not isinstance(text, str):+ raise NormalizationError("invalid_text", "text must be a string.")+ t = text.strip()+ if not t:+ return []+ if normalize_enabled:+ if normalizer is None:+ raise PipelineError("normalizer_unavailable", "Text normalizer unavailable.", 503)+ t = normalizer(t, language="auto" if normalization_language is None else normalization_language, date_order=date_order, two_digit_year_base=two_digit_year_base)+ if not isinstance(t, str) or not any(c.isalnum() for c in t):+ raise PipelineError("empty_normalized_text", "No speakable text remains.")+ if chunk_enabled:+ if splitter is None or post_process is None:+ raise PipelineError("chunker_unavailable", "Text chunker unavailable.", 503)+ t = post_process(t)+ parts = splitter(t)+ if not parts or any(not isinstance(p, str) or not p.strip() for p in parts):+ raise PipelineError("invalid_chunks", "Text chunker returned invalid chunks.", 503)+ # Current chunker changes whitespace only. Detect dropped/reordered text+ # before audio starts; do not send a too-long whole-text fallback.+ if " ".join(" ".join(parts).split()) != " ".join(t.split()):+ raise PipelineError("chunk_content_mismatch", "Text chunker changed content.", 503)+ if max_chunk_chars and any(len(p) > max_chunk_chars for p in parts):+ raise PipelineError("unsplittable_text", "A text token exceeds the safe chunk size; shorten it.")+ return parts+ return [t]+ except NormalizationError as exc:+ raise PipelineError(exc.code, str(exc)) from None+ except PipelineError:+ raise+ except Exception:+ raise PipelineError("text_pipeline_failed", "Text preparation failed; no audio was generated.", 503) from None+++def resolve_conditioning(settings, supported):+ """Never invent an untrained language tag. Legacy omission remains Hindi.++ `language`/`lang` requests a model tag unless `conditioning_language` is+ explicitly supplied. The latter is for a checkpoint trained with a tag that+ differs from the text language, and requires deployment-owner confirmation.+ """+ value = settings.get("conditioning_language") or settings.get("language") or settings.get("lang") or "Hindi"+ aliases = {"en": "English", "en-in": "English", "en-us": "English",+ "hi": "Hindi", "hi-in": "Hindi", "indian english": "English", "indian-english": "English"}+ if not isinstance(value, str):+ raise PipelineError("invalid_language", "language must be a string.")+ by_name = {x.lower(): x for x in supported}+ value = aliases.get(value.lower(), by_name.get(value.lower(), value))+ if value not in supported:+ raise PipelineError("unsupported_conditioning_language",+ "No supported model tag for this language. Confirm the checkpoint conditioning_language.")+ return value+++def resolve_normalization(settings):+ """Normalization locale and model conditioning are deliberately separate.++ Explicit normalization_language wins, then language/lang; omission preserves+ Indian English. Never guess Hindi versus Marathi from Devanagari text.+ """+ value = next((settings[key] for key in ("normalization_language", "language", "lang")+ if key in settings), "en-IN")+ try:+ return resolve_language(value)+ except NormalizationError as exc:+ raise PipelineError(exc.code, str(exc)) from None+++def merge_settings(current, incoming, sticky):+ """Snapshot per queued utterance; newer aliases replace older aliases."""+ result = dict(current)+ # A language change must not inherit a previous explicit override.+ if "language" in incoming or "lang" in incoming:+ for key in ("conditioning_language", "normalization_language"):+ if key not in incoming:+ result.pop(key, None)+ for a, b in (("voice_id", "voice"), ("language", "lang")):+ if a in incoming or b in incoming:+ result.pop(a, None)+ result.pop(b, None)+ result.update({k: incoming[k] for k in sticky if k in incoming})+ return result+++_REQUEST_LANGUAGE_KEYS = frozenset(("language", "lang", "normalization_language", "conditioning_language"))+++def retain_session_settings(current, incoming, sticky):+ """Text-frame locales belong to their context, not the next customer turn.++ start/config frames still use merge_settings directly and establish explicit+ session defaults. Other sticky options retain the existing protocol behavior.+ """+ return merge_settings(current, {k: v for k, v in incoming.items()+ if k not in _REQUEST_LANGUAGE_KEYS}, sticky)diff --git a/maya3/text/tn/tts_chunker.py b/maya3/text/tn/tts_chunker.pynew file mode 100644index 0000000..c107120--- /dev/null+++ b/maya3/text/tn/tts_chunker.py@@ -0,0 +1,208 @@+"""Prosody-aware, Indic-aware, emotion-tag-safe chunker for TTS.++Python port of the TypeScript chunker (studio gateway, itself a port of+indic_chunker.py on branch local-chunker-normguard) that passes the I1-I6+invariant harness. Replaces the earlier sentence-only chunker, which had two+defects:+ * it split on any '.', '!' or '?', tearing "8.4", "example.com", "₹2,500"+ and quoted '"आओगे?"' apart;+ * it split ONLY on sentence punctuation, so a long comma-joined sentence+ became one oversized chunk that silently overran max_model_len and+ truncated mid-speech.++Splits normalized text preferring, in priority order:+ 1. sentence boundaries ( . ! ? … । ॥ — ONLY token-final, i.e. followed by+ whitespace, so decimals / URLs / currency / quoted '?' stay intact )+ 2. clause boundaries ( ; : , — – and pan-Indic connector words )+ 3. word boundaries ( never splits a word / Devanagari cluster )++Emotion tags ([laughs], [clears throat], …) are atomic and glued to the word+they condition, so a boundary can never strand a tag into the wrong clip.++BUDGET: MAX chars is sized in SPEAKING SECONDS, but the real ceiling is the+engine's context window: a chunk costs ~50 audio tokens/sec plus ~1.0 (Hindi)+to ~1.5 (Telugu) prompt tokens/char. At max_model_len=1024 a chunk must stay+under ~13 s / ~180 chars; 25 s / 347 chars needs max_model_len=2048. Set+CHUNK_MAX_CHARS to match the deployed window.+"""+import os+import re++_DASH_ELLIPSIS = dict.fromkeys(map(ord, "―‒⸺⸻"), " ") # bar/figure/2-3em dash -> space+ # (em/en dash and … kept: clause cues)+def post_process(s):+ if not s:+ return s+ s = s.translate(_DASH_ELLIPSIS)+ s = re.sub(r"\.{2,}", "…", s) # ASCII ".." / "..." -> ellipsis (a sentence cue)+ s = re.sub(r"\s+([,.;:!?।])", r"\1", s) # drop space before punctuation+ s = re.sub(r"\s{2,}", " ", s) # collapse runs of spaces+ return s.strip()+++SPC = 0.060 # measured speaking rate, s/char: 40 clips,+ # 10 languages x 2 voices, mean 0.058+ # (ta/ml ~0.051, or ~0.062 -- 1.54x spread).+ # 0.072 was a guess and over-split by ~20%.+MAX = int(os.environ.get("CHUNK_MAX_CHARS", str(round(20 / SPC)))) # 333 -> ~20.0 s (fits max_model_len=2048)+MIN = int(os.environ.get("CHUNK_MIN_CHARS", "60")) # ~4.3 s: merge runts+HARD = MAX # absolute ceiling (except a lone long token)+CHUNK_GAP_S = 0.15 # silence inserted between concatenated chunks+SECS_PER_CHAR = SPC # back-compat alias+CHUNK_MAX_SEC = MAX * SPC # back-compat alias++TAG_G = re.compile(r"\[[a-z][a-z ]*\]") # bracketed lowercase = TTS tag+SENT_END = re.compile(r"(?:[.!?।॥…]|\.{3})+[\"'”’»)\]]*$")+CLAUSE_END = re.compile(r"[,;:—–][\"'”’»)\]]*$")+_WS = re.compile(r"\s+")+STRIP = "\"'“”‘’«»()[],.;:!?।॥…-–—"+STRIP_LEAD = "\"'“”‘’«»("++CONNECTORS = {+ "and", "but", "because", "while", "so", "then",+ "और", "एवं", "तथा", "लेकिन", "पर", "मगर", "क्योंकि", "जबकि", "फिर", "आणि", "पण", "कारण",+ "এবং", "আর", "কিন্তু", "কারণ", "তারপর", "ଏବଂ", "କିନ୍ତୁ",+ "અને", "પણ", "કારણ", "ਅਤੇ", "ਪਰ", "ਕਿਉਂਕਿ",+ "మరియు", "కానీ", "ఎందుకంటే", "ಮತ್ತು", "ಆದರೆ", "ಏಕೆಂದರೆ",+ "மற்றும்", "ஆனால்", "ஏனெனில்", "പക്ഷേ", "എന്നാൽ", "കാരണം",+}+++def _strip(s, chars):+ return s.strip(chars)+++def _groups(para):+ """Whitespace tokens -> atomic groups, with emotion tags glued to their word."""+ prot = TAG_G.sub(lambda m: m.group(0).replace(" ", "\x00"), para)+ toks = [t.replace("\x00", " ") for t in prot.split() if t]+ out, glue_right = [], False+ for t in toks:+ bare = _strip(TAG_G.sub("", t).strip(), STRIP)+ is_tag = bare == "" # token is only tag(+punctuation)+ if glue_right:+ out[-1] = out[-1] + " " + t+ glue_right = is_tag # consecutive tags keep gluing+ continue+ if is_tag and out and not SENT_END.search(out[-1]):+ out[-1] = out[-1] + " " + t # mid/end tag -> preceding word+ elif is_tag:+ out.append(t) # sentence-leading tag -> next word+ glue_right = True+ else:+ out.append(t)+ return out+++def _strength(group, nxt):+ """Boundary strength AFTER this group: 3 sentence, 2 clause, 1 word."""+ if SENT_END.search(group):+ return 3+ if CLAUSE_END.search(group):+ return 2+ if nxt is not None:+ parts = nxt.split()+ first = _strip(parts[0], STRIP_LEAD) if parts else ""+ if first in CONNECTORS:+ return 2 # break BEFORE a connector word+ return 1+++def _runs(gs, min_strength):+ """Join groups into runs, breaking where boundary strength >= min_strength."""+ out, buf = [], []+ for i, g in enumerate(gs):+ buf.append(g)+ nxt = gs[i + 1] if i + 1 < len(gs) else None+ if nxt is not None and _strength(g, nxt) >= min_strength:+ out.append(" ".join(buf))+ buf = []+ if buf:+ out.append(" ".join(buf))+ return out+++def _split_words(clause):+ out, buf = [], ""+ for g in _groups(clause):+ cand = (buf + " " + g) if buf else g+ if len(cand) <= HARD or not buf:+ buf = cand+ else:+ out.append(buf)+ buf = g+ if buf:+ out.append(buf)+ return out+++def _split_long(sent):+ out, buf = [], ""+ for clause in _runs(_groups(sent), 2):+ if len(clause) > MAX:+ if buf:+ out.append(buf)+ buf = ""+ out.extend(_split_words(clause))+ continue+ cand = (buf + " " + clause) if buf else clause+ if len(cand) <= MAX:+ buf = cand+ else:+ out.append(buf)+ buf = clause+ if buf:+ out.append(buf)+ return out+++def _chunk_groups(gs):+ out, buf = [], ""+ for sent in _runs(gs, 3):+ if len(sent) > MAX:+ if buf:+ out.append(buf)+ buf = ""+ out.extend(_split_long(sent))+ continue+ cand = (buf + " " + sent) if buf else sent+ if len(cand) <= MAX:+ buf = cand+ else:+ out.append(buf)+ buf = sent+ if buf:+ out.append(buf)+ return out+++def _merge_runts(pieces):+ if not pieces:+ return []+ merged = []+ for p in pieces:+ if merged and len(p) < MIN and len(merged[-1] + " " + p) <= HARD:+ merged[-1] = merged[-1] + " " + p+ else:+ merged.append(p)+ if len(merged) >= 2 and len(merged[0]) < MIN and len(merged[0] + " " + merged[1]) <= HARD:+ merged[1] = merged[0] + " " + merged[1]+ merged.pop(0)+ return [_WS.sub(" ", m).strip() for m in merged]+++def split_for_tts(text, max_sec=None, spc=SPC, hard_sec=None):+ """Split normalized text into prosody-friendly, tag-safe TTS chunks.++ max_sec/spc/hard_sec are accepted for call-site compatibility with the old+ chunker; sizing is governed by MAX/MIN/HARD (chars) above.+ """+ if not text or not text.strip():+ return []+ pieces = []+ for para in text.split("\n"):+ p = para.strip()+ if not p:+ continue+ pieces.extend(_chunk_groups(_groups(p)))+ return _merge_runts(pieces) or [text.strip()]diff --git a/maya3/tools/__init__.py b/maya3/tools/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/maya3/tools/convert_to_safetensors.py b/maya3/tools/convert_to_safetensors.pynew file mode 100644index 0000000..28c9fc6--- /dev/null+++ b/maya3/tools/convert_to_safetensors.py@@ -0,0 +1,281 @@+"""Convert a flat Maya3 checkpoint (`model.pt`, keys `model.<name>`) into the safetensors release format.++ python -m maya3.tools.convert_to_safetensors <model.pt> <out_dir> [--backbone-src DIR] [--model-config YAML]++Writes into <out_dir>:+ model.safetensors (one file when the stored bytes are <= --max-shard-gb, default 5)+ model-0000k-of-0000N.safetensors (otherwise) + model.safetensors.index.json+ maya3_config.json the resolved model config `tts.model.load_s3.load_model_for_eval` needs+ (speaker anchor, depth_grouped, ...), the format version and provenance+ backbone/ with --backbone-src: config.json + tokenizer files only (never weights)++Guarantees:+ * every tensor keeps its stored dtype and values exactly (no casts; non-contiguous tensors are made contiguous);+ * tensors that share storage (tied weights: lm_head <-> embed_tokens) and tensors that are exact copies of each+ other (same dtype/shape, bit-identical) are stored ONCE; the other names are recorded as aliases in the+ safetensors metadata (`maya3_aliases`) and in maya3_config.json, and the loader restores them;+ * keys are stored without the training-namespace `model.` prefix (the loader adds it back).++Check the result with `python -m maya3.tools.verify_conversion <model.pt> <out_dir>`.+CPU only; needs about 2x the checkpoint size in RAM and the checkpoint size in free disk.+"""+from __future__ import annotations++import argparse+import collections+import datetime+import json+import os+import shutil+import sys+from pathlib import Path++import torch++ROOT = Path(__file__).resolve().parents[2]+if str(ROOT) not in sys.path:+ sys.path.insert(0, str(ROOT))++from tts.model import load_s3 as L # noqa: E402++FORMAT = "maya3-safetensors"+FORMAT_VERSION = 1+ENGINE_DEFAULT_CONFIG = ROOT / "configs" / "s3_fresh_v1.yaml" # what maya3.engine.Engine passes as model_config+LANGS = ["as", "bn", "en", "gu", "hi", "kn", "ml", "mr", "or", "pa", "ta", "te"]+# small backbone metadata the architecture (AutoConfig) and tokenizer (AutoTokenizer) need; never weights+BACKBONE_FILES = ("config.json", "generation_config.json", "tokenizer.json", "tokenizer_config.json",+ "special_tokens_map.json", "added_tokens.json", "vocab.json", "merges.txt", "chat_template.jinja")+WEIGHT_SUFFIXES = (".safetensors", ".bin", ".pt", ".pth", ".ckpt", ".gguf")+++def _gb(n):+ return n / 1e9+++def _free_bytes(path):+ p = Path(path)+ while not p.exists():+ p = p.parent+ return shutil.disk_usage(p).free+++def bits_equal(a, b):+ """Bitwise equality (torch.equal treats -0.0 == 0.0 and NaN != NaN; aliasing must be exact)."""+ if a.dtype != b.dtype or a.shape != b.shape:+ return False+ return torch.equal(a.contiguous().reshape(-1).view(torch.uint8), b.contiguous().reshape(-1).view(torch.uint8))+++def _alias_preference(name):+ # keep the input embedding as the stored copy of a tied pair (the HF convention); otherwise the first name+ return ("lm_head" in name, name)+++def plan_storage(sd, dedupe_equal=True):+ """-> (stored {name: tensor}, aliases {alias: stored name}).++ Shared storage: identical views -> alias; any other overlap -> an independent contiguous copy (values exact).+ Bit-identical independent tensors (same dtype, shape, bytes) -> alias as well (lossless dedupe)."""+ by_storage = collections.defaultdict(list)+ for k, v in sd.items():+ by_storage[(v.device.type, v.untyped_storage().data_ptr())].append(k)+ stored, aliases = {}, {}+ for names in by_storage.values():+ names = sorted(names, key=_alias_preference)+ views = {}+ for k in names:+ v = sd[k]+ sig = (v.dtype, tuple(v.shape), tuple(v.stride()), v.storage_offset())+ if sig in views:+ aliases[k] = views[sig]+ else:+ views[sig] = k+ stored[k] = v+ if len(views) > 1: # partially-overlapping views of one storage: unshare them+ for k in views.values():+ stored[k] = stored[k].contiguous().clone()+ # exact-copy dedupe among independent tensors+ groups = collections.defaultdict(list)+ for k, v in stored.items():+ groups[(v.dtype, tuple(v.shape))].append(k)+ for names in (groups.values() if dedupe_equal else ()):+ if len(names) < 2:+ continue+ names = sorted(names, key=_alias_preference)+ keep = []+ for k in names:+ hit = next((c for c in keep if bits_equal(stored[c], stored[k])), None)+ if hit is None:+ keep.append(k)+ else:+ aliases[k] = hit+ for k in names:+ if k in aliases:+ stored.pop(k)+ # an alias must point at a stored name (chains cannot form: targets are always stored names)+ assert all(t in stored for t in aliases.values())+ stored = {k: (v if v.is_contiguous() else v.contiguous()) for k, v in stored.items()}+ return stored, aliases+++def shard(stored, max_bytes):+ """Greedy, in name order -> [[names], ...]."""+ shards, cur, size = [], [], 0+ for k in sorted(stored):+ n = stored[k].numel() * stored[k].element_size()+ if cur and size + n > max_bytes:+ shards.append(cur)+ cur, size = [], 0+ cur.append(k)+ size += n+ if cur:+ shards.append(cur)+ return shards+++def resolve_release_model_cfg(ckpt, shapes, model_config=None):+ """The inference-relevant model block, reconciled against the checkpoint's own tensors (as load_s3 does)."""+ if model_config is not None:+ mc, src = L.resolve_model_cfg(ckpt, config=str(model_config))+ else:+ mc, src = L.resolve_model_cfg(ckpt)+ if src == "none":+ mc, src = L.resolve_model_cfg(ckpt, config=str(ENGINE_DEFAULT_CONFIG))+ anchor = L._reconcile_anchor(mc.get("speaker_anchor"), L.anchor_cfg_from_shapes(shapes))+ dcf = mc.get("depth_ckpt_from")+ out = {+ "backbone": "backbone", # relative to the release dir+ "attn": "sdpa",+ "speaker_anchor": anchor,+ "depth_grouped": bool(mc.get("depth_grouped", False)),+ "depth_ckpt_from": int(dcf) if dcf is not None else None,+ }+ # the engine loads with configs/s3_fresh_v1.yaml as an explicit override: make sure it builds the same model+ eng, _ = L.resolve_model_cfg(ckpt, config=str(ENGINE_DEFAULT_CONFIG))+ eng_anchor = L._reconcile_anchor(eng.get("speaker_anchor"), L.anchor_cfg_from_shapes(shapes))+ agrees = eng_anchor == anchor and bool(eng.get("depth_grouped", False)) == out["depth_grouped"]+ return out, src, agrees+++def copy_backbone(src, dst):+ src, dst = Path(src), Path(dst)+ dst.mkdir(parents=True, exist_ok=True)+ copied = []+ for name in BACKBONE_FILES:+ p = src / name+ if p.is_file():+ shutil.copy2(p, dst / name)+ copied.append(name)+ if "config.json" not in copied or "tokenizer.json" not in copied:+ raise FileNotFoundError(f"{src} lacks config.json / tokenizer.json")+ bad = [p.name for p in dst.iterdir() if p.name.endswith(WEIGHT_SUFFIXES)]+ if bad:+ raise RuntimeError(f"weight files in {dst}: {bad} (the backbone dir must hold none)")+ return copied+++def main(argv=None):+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])+ ap.add_argument("ckpt", help="flat model.pt (keys model.<name>) or a dir containing one")+ ap.add_argument("out_dir")+ ap.add_argument("--backbone-src", help="backbone dir to take config.json + tokenizer files from (no weights copied)")+ ap.add_argument("--model-config", help="the run's resolved config yaml (default: found next to the checkpoint, "+ "else configs/s3_fresh_v1.yaml)")+ ap.add_argument("--max-shard-gb", type=float, default=5.0)+ ap.add_argument("--min-free-gb", type=float, default=60.0, help="refuse to write when the target fs has less free")+ ap.add_argument("--source-name", help="label recorded in maya3_config.json (default: <run>/<step>)")+ ap.add_argument("--no-dedupe", action="store_true", help="store equal-valued (untied) tensors separately")+ A = ap.parse_args(argv)++ flat = L._flat_path(os.path.abspath(A.ckpt))+ if flat is None:+ sys.exit(f"{A.ckpt}: not a flat model.pt export")+ free = _free_bytes(A.out_dir)+ need = os.path.getsize(flat)+ if free < A.min_free_gb * 1e9 or free < need * 1.05:+ sys.exit(f"refusing to write: {_gb(free):.1f} GB free at {A.out_dir}, need >= {A.min_free_gb:.0f} GB "+ f"and >= {_gb(need) * 1.05:.1f} GB")++ print(f"loading {flat} ({_gb(need):.2f} GB, mmap)", flush=True)+ sd = torch.load(flat, map_location="cpu", weights_only=True, mmap=True)+ bad = [k for k in sd if not k.startswith(L.MODEL_PREFIX)]+ if bad:+ sys.exit(f"non-model keys in {flat}: {bad[:4]}")+ sd = {k[len(L.MODEL_PREFIX):]: v for k, v in sd.items()}+ shapes = {k: v.shape for k, v in sd.items()}+ model_cfg, cfg_src, engine_agrees = resolve_release_model_cfg(flat, shapes, A.model_config)+ print(f"model config from {cfg_src}: {json.dumps(model_cfg)} (engine default config agrees: {engine_agrees})")+ if not engine_agrees:+ print("WARNING: configs/s3_fresh_v1.yaml (maya3.engine's model_config default) would build a different "+ "model; pass model_config=<release>/maya3_config.json to the Engine", file=sys.stderr)++ stored, aliases = plan_storage(sd, dedupe_equal=not A.no_dedupe)+ stored_bytes = sum(v.numel() * v.element_size() for v in stored.values())+ print(f"{len(sd)} tensors -> {len(stored)} stored + {len(aliases)} aliases {aliases}; "+ f"{_gb(stored_bytes):.2f} GB", flush=True)++ out = Path(A.out_dir)+ out.mkdir(parents=True, exist_ok=True)+ for p in list(out.glob("model*.safetensors")) + list(out.glob("model.safetensors.index.json")):+ p.unlink() # stale shards of a previous conversion+ from safetensors.torch import save_file+ groups = shard(stored, int(A.max_shard_gb * 1e9))+ meta = {"format": "pt", L.ALIASES_KEY: json.dumps(aliases, sort_keys=True),+ "maya3_format": FORMAT, "maya3_format_version": str(FORMAT_VERSION)}+ weight_map = {}+ names = ([L.SAFETENSORS_NAME] if len(groups) == 1 else+ [f"model-{i + 1:05d}-of-{len(groups):05d}.safetensors" for i in range(len(groups))])+ for fname, keys in zip(names, groups):+ tmp = out / (fname + ".tmp")+ save_file({k: stored[k] for k in keys}, str(tmp), metadata=meta)+ os.chmod(tmp, 0o644)+ os.replace(tmp, out / fname)+ weight_map.update({k: fname for k in keys})+ print(f" wrote {fname}: {len(keys)} tensors, {_gb(os.path.getsize(out / fname)):.2f} GB", flush=True)+ if len(groups) > 1:+ index = {"metadata": {"total_size": stored_bytes, L.ALIASES_KEY: aliases,+ "maya3_format": FORMAT, "maya3_format_version": FORMAT_VERSION},+ "weight_map": dict(sorted(weight_map.items()))}+ (out / L.SAFETENSORS_INDEX).write_text(json.dumps(index, indent=1) + "\n")++ prov = {}+ pj = Path(flat).parent / "provenance.json"+ if pj.is_file():+ prov = json.loads(pj.read_text())+ step_dir = Path(flat).parent+ dtypes = collections.Counter(str(v.dtype).replace("torch.", "") for v in sd.values())+ cfg = {+ "format": FORMAT,+ "format_version": FORMAT_VERSION,+ "model_type": "maya3",+ "model": model_cfg,+ "key_prefix": L.MODEL_PREFIX, # stripped in the files; load_s3 adds it back+ "aliases": aliases,+ "tensors": {"count": len(sd), "stored": len(stored), "dtypes": dict(dtypes),+ "stored_bytes": stored_bytes,+ "n_params_unique": int(sum(v.numel() for v in stored.values()))},+ "architecture": {"backbone": "Qwen3-1.7B (Qwen3ForCausalLM, built from backbone/config.json)",+ "depth_decoder": "DepthV2, 31 levels", "speaker_anchor": "ECAPA-192 -> MLP"},+ "audio": {"sample_rate": 24000, "frame_rate_hz": 12.5, "n_codebooks": 32, "codebook_size": 2048,+ "codec": "kyutai/mimi"},+ "speaker_encoder": {"repo": "speechbrain/spkrec-ecapa-voxceleb", "dim": 192},+ "languages": LANGS,+ "source": {"name": A.source_name or f"{step_dir.parent.parent.name}/{step_dir.name}",+ "update": prov.get("source_update", L.checkpoint_update(flat)),+ "format": prov.get("format"), "sha256_total": prov.get("total_hash"),+ "hash_alg": prov.get("hash_alg"), "n_params": prov.get("n_params")},+ "converted_utc": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),+ "converter": {"torch": torch.__version__,+ "safetensors": __import__("safetensors").__version__},+ }+ (out / L.RELEASE_CONFIG).write_text(json.dumps(cfg, indent=1) + "\n")+ print(f" wrote {L.RELEASE_CONFIG}")+ if A.backbone_src:+ copied = copy_backbone(A.backbone_src, out / "backbone")+ print(f" backbone/: {copied}")+ print("CONVERTED " + json.dumps({"out_dir": str(out), "files": names, "stored_gb": round(_gb(stored_bytes), 3),+ "aliases": aliases}))+++if __name__ == "__main__":+ main()diff --git a/maya3/tools/make_release_voices.py b/maya3/tools/make_release_voices.pynew file mode 100644index 0000000..3e6d43a--- /dev/null+++ b/maya3/tools/make_release_voices.py@@ -0,0 +1,35 @@+"""Write the PUBLIC voices/ dir of a release: voices.json (name, prefix, gender, age band, style, trained languages, hours,+per-voice mode) + the ECAPA centroids / reference-clip codes the chosen modes need. Drops provider ids, source speaker ids,+pack names, catalogue uids and paths.+Usage: make_release_voices.py <internal voices.json> <out voices dir> [--mode named|spk|icl_spk] [--fallback-dir DIR]+ [--mode-per-voice Name=mode,...]"""+import argparse, json, os, shutil+ap = argparse.ArgumentParser()+ap.add_argument("src"); ap.add_argument("out")+ap.add_argument("--mode", default="named"); ap.add_argument("--fallback-dir", default=None)+ap.add_argument("--mode-per-voice", default="")+A = ap.parse_args()+per = dict(x.split("=") for x in A.mode_per_voice.split(",") if x)+d = json.load(open(A.src)); os.makedirs(A.out, exist_ok=True)+fb = {}+if A.fallback_dir:+ fb = {v["name"]: v for v in json.load(open(os.path.join(A.fallback_dir, "voices_icl_spk.json")))["voices"]}+pub = []+for v in d["voices"]:+ n = v["name"]; mode = per.get(n, A.mode)+ e = {"name": n, "prompt_prefix": v.get("prompt_prefix", "{" + n + "}: "), "mode": mode, "gender": v.get("gender"),+ "age_band": v.get("age_band"), "style": v.get("style"), "langs": v.get("langs_ge1h") or v.get("langs"), "hours": v.get("hours")}+ if mode in ("spk", "icl_spk", "icl"):+ f = fb[n]+ shutil.copy(os.path.join(A.fallback_dir, f["ecapa"]), os.path.join(A.out, f["ecapa"])); e["ecapa"] = f["ecapa"]+ if mode != "spk":+ e["ref_clips"] = []+ for c in f["ref_clips"][:1]:+ shutil.copy(os.path.join(A.fallback_dir, c["codes"]), os.path.join(A.out, c["codes"]))+ e["ref_clips"].append({"codes": c["codes"], "text": c["text"], "lang": c["lang"], "seconds": c.get("seconds")})+ pub.append(e)+json.dump({"schema": "maya3_voices_v1", "prompt_format": "{Name}: <text>",+ "note": "Select with voice=<name> (case-insensitive). mode: named = trained name prompt; spk = stored speaker embedding; "+ "icl_spk = embedding + reference clip. Never combine a named voice with your own reference audio.",+ "voices": pub}, open(os.path.join(A.out, "voices.json"), "w"), indent=1, ensure_ascii=False)+print(f"wrote {len(pub)} voices ({sorted(set(x['mode'] for x in pub))}) -> {A.out}")diff --git a/maya3/tools/to_bf16.py b/maya3/tools/to_bf16.pynew file mode 100644index 0000000..b8dfe31--- /dev/null+++ b/maya3/tools/to_bf16.py@@ -0,0 +1,16 @@+"""Cast a flat Maya3 model.pt to bf16 (half the size). Lossless for inference: load_model_for_eval(dtype=bf16) casts every+tensor to bf16 anyway (the engine then upcasts the depth stack from those bf16 values), so the engine sees bit-identical+weights. Usage: to_bf16.py <model.pt> <out model.pt>"""+import sys, torch+src, out = sys.argv[1], sys.argv[2]+sd = torch.load(src, map_location="cpu", weights_only=False, mmap=True)+payload = sd.get("model", sd) if isinstance(sd, dict) else sd+n, memo = 0, {}+for k, v in list(payload.items()):+ if torch.is_tensor(v) and v.is_floating_point() and v.dtype != torch.bfloat16:+ key = (v.untyped_storage().data_ptr(), v.storage_offset(), tuple(v.shape))+ if key not in memo: # tied tensors (lm_head = embed_tokens) stay shared+ memo[key] = v.to(torch.bfloat16); n += 1+ payload[k] = memo[key]+torch.save(sd, out)+print(f"cast {n} tensors -> {out}")diff --git a/maya3/tools/verify_bf16.py b/maya3/tools/verify_bf16.pynew file mode 100644index 0000000..24f2413--- /dev/null+++ b/maya3/tools/verify_bf16.py@@ -0,0 +1,15 @@+"""Check that the bf16 copy loads to bit-identical engine weights: load_model_for_eval(dtype=bf16) on both files (CPU).+Usage: verify_bf16.py <fp32 model.pt> <bf16 model.pt> <backbone_dir>"""+import os, sys, torch+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))+from tts.model.load_s3 import load_model_for_eval+ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+cfg = {"model": {"backbone": sys.argv[3], "attn": "sdpa"}, "data": {"max_tokens": 8192}}+def load(p):+ m, _ = load_model_for_eval(p, device=None, dtype=torch.bfloat16, cfg=cfg, config=f"{ROOT}/configs/s3_fresh_v1.yaml",+ amortize_frac=1.0, require_anchor=True, verbose=False)+ return m.state_dict()+a, b = load(sys.argv[1]), load(sys.argv[2])+bad = [k for k in a if not torch.equal(a[k], b[k])]+print(f"{len(a)} tensors, {len(bad)} differ", bad[:3]); assert not bad+print("BF16_LOSSLESS_OK")diff --git a/maya3/tools/verify_conversion.py b/maya3/tools/verify_conversion.pynew file mode 100644index 0000000..230a859--- /dev/null+++ b/maya3/tools/verify_conversion.py@@ -0,0 +1,117 @@+"""Verify a safetensors release export against its source `model.pt`, on CPU.++ CUDA_VISIBLE_DEVICES= python -m maya3.tools.verify_conversion <model.pt> <out_dir> [--backbone-dir DIR]++Checks, in order (any failure exits non-zero):+ 1. raw tensors: the export (aliases restored) has exactly the source's names, and every tensor has the same+ dtype, shape and bytes (bitwise; also torch.equal);+ 2. both load through `tts.model.load_s3.load_model_for_eval` (the source with its run config / the engine's+ default config, the export with its own maya3_config.json) into the same model: same anchor config,+ depth_grouped, tensor count and parameter count;+ 3. every state-dict tensor of the two loaded models is bit-identical (`torch.equal` + bitwise).+The backbone is built from <out_dir>/backbone (config + tokenizer only) for both loads unless --backbone-dir is given.+"""+from __future__ import annotations++import argparse+import gc+import json+import os+import sys+import time+from pathlib import Path++os.environ.setdefault("CUDA_VISIBLE_DEVICES", "")+import torch # noqa: E402++ROOT = Path(__file__).resolve().parents[2]+if str(ROOT) not in sys.path:+ sys.path.insert(0, str(ROOT))++from tts.model import load_s3 as L # noqa: E402+from maya3.tools.convert_to_safetensors import ENGINE_DEFAULT_CONFIG, bits_equal # noqa: E402+++def compare(a, b, what):+ """-> list of mismatch strings."""+ errs = []+ if set(a) != set(b):+ errs.append(f"{what}: key sets differ: only in source {sorted(set(a) - set(b))[:8]}, "+ f"only in export {sorted(set(b) - set(a))[:8]}")+ for k in sorted(set(a) & set(b)):+ x, y = a[k], b[k]+ if x.dtype != y.dtype or x.shape != y.shape:+ errs.append(f"{what}: {k}: {x.dtype}{tuple(x.shape)} vs {y.dtype}{tuple(y.shape)}")+ elif not torch.equal(x, y) and not (torch.isnan(x).any() and bits_equal(x, y)):+ errs.append(f"{what}: {k}: values differ")+ elif not bits_equal(x, y):+ errs.append(f"{what}: {k}: bit patterns differ (e.g. signed zeros)")+ return errs+++def main(argv=None):+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])+ ap.add_argument("ckpt")+ ap.add_argument("out_dir")+ ap.add_argument("--backbone-dir", help="default: <out_dir>/backbone")+ ap.add_argument("--model-config", help="config for the SOURCE load (default: the run config next to it, "+ "else configs/s3_fresh_v1.yaml)")+ ap.add_argument("--skip-models", action="store_true", help="only the raw tensor comparison (step 1)")+ A = ap.parse_args(argv)+ t0 = time.time()+ flat = L._flat_path(os.path.abspath(A.ckpt))+ out = os.path.abspath(A.out_dir)+ bb = os.path.abspath(A.backbone_dir or os.path.join(out, "backbone"))+ errs = []++ # 1. raw tensors+ src = torch.load(flat, map_location="cpu", weights_only=True, mmap=True)+ st = L._safetensors_files(out)+ if st is None:+ sys.exit(f"{out}: no model.safetensors[.index.json]")+ exp = L._load_safetensors(st)+ errs += compare(src, exp, "raw")+ print(f"[1] raw: {len(src)} source tensors vs {len(exp)} export tensors ({len(st[1])} file(s), "+ f"aliases {st[2]}): {'OK' if not errs else 'FAIL'} ({time.time() - t0:.0f}s)", flush=True)+ del src, exp+ gc.collect()+ if A.skip_models or errs:+ return finish(errs)++ # 2./3. through load_model_for_eval+ cfg = {"model": {"backbone": bb, "attn": "sdpa"}}+ mc = A.model_config+ if mc is None and L.find_run_config(flat) is None:+ mc = str(ENGINE_DEFAULT_CONFIG)+ m1, p1 = L.load_model_for_eval(flat, cfg=cfg, config=mc, require_anchor=None)+ sd1 = {k: v.detach().clone() for k, v in m1.state_dict().items()}+ del m1+ gc.collect()+ m2, p2 = L.load_model_for_eval(out, cfg=cfg, require_anchor=None)+ sd2 = m2.state_dict()+ for key in ("anchor", "anchor_cfg", "depth_grouped", "depth_ckpt_from", "n_tensors", "n_params", "update"):+ if p1.get(key) != p2.get(key):+ errs.append(f"provenance {key}: source {p1.get(key)!r} vs export {p2.get(key)!r}")+ e = compare(sd1, sd2, "state_dict")+ errs += e+ print(f"[2] provenance: source format={p1['format']} cfg={p1['config_source']} | export format={p2['format']} "+ f"cfg={p2['config_source']}", flush=True)+ print(f"[3] state_dict: {len(sd1)} vs {len(sd2)} tensors, "+ f"dtypes {sorted({str(v.dtype) for v in sd2.values()})}: {'OK' if not e else 'FAIL'} "+ f"({time.time() - t0:.0f}s)", flush=True)+ return finish(errs, {"n_state_dict": len(sd1), "n_params": p2["n_params"], "anchor_cfg": p2["anchor_cfg"],+ "depth_grouped": p2["depth_grouped"]})+++def finish(errs, extra=None):+ if errs:+ for e in errs[:50]:+ print("MISMATCH " + e)+ print(f"VERIFY FAIL ({len(errs)} mismatches)")+ sys.exit(1)+ print("VERIFY OK " + json.dumps(extra or {}, sort_keys=True))+ return 0+++if __name__ == "__main__":+ main()diff --git a/pyproject.toml b/pyproject.tomlnew file mode 100644index 0000000..264b42f--- /dev/null+++ b/pyproject.toml@@ -0,0 +1,46 @@+[build-system]+requires = ["setuptools>=69", "wheel"]+build-backend = "setuptools.build_meta"++[project]+name = "maya3"+version = "0.1.0"+description = "Maya3 TTS: streaming multilingual (12 Indic languages + English) text-to-speech with zero-shot voice cloning"+readme = "README.md"+requires-python = ">=3.10"+license = "Apache-2.0"+# Pins are the versions the engine was built and measured with (torch 2.8.0+cu128, transformers 5.6.2).+# torch / torchaudio cu128 wheels come from https://download.pytorch.org/whl/cu128 (see README.md "Install").+dependencies = [+ "torch==2.8.0", # brings triton 3.4.0 (the fused backbone / depth kernels)+ "torchaudio==2.8.0", # speechbrain needs it; must match torch+ "transformers==5.6.2", # Qwen3 backbone, MimiModel, DynamicCache layout used by serve/cache.py+ "tokenizers>=0.22,<0.23",+ "numpy>=2.0",+ "scipy>=1.13",+ "soundfile>=0.12",+ "speechbrain==1.1.2", # ECAPA-TDNN speaker embedding (spkrec-ecapa-voxceleb)+ "huggingface_hub>=1.0",+ "safetensors>=0.6",+ "pyyaml>=6.0",+]++[project.optional-dependencies]+# HTTP (OpenAI-compatible) + WebSocket server and the client (maya3.server, maya3.client)+server = ["aiohttp>=3.10"]+# CPU test suite (maya3/tests): server tests run against a fake engine+dev = ["aiohttp>=3.10", "pytest>=8", "pytest-asyncio>=0.23", "pytest-aiohttp>=1.0"]++[tool.setuptools]+include-package-data = false++[tool.setuptools.packages.find]+where = ["."]+# serve/ and scripts/ have no __init__.py (namespace packages); configs/ is shipped as data at the project root+# because maya3/engine.py reads <root>/configs/s3_fresh_v1.yaml and <root>/configs/text_frames_prior.json.+include = ["maya3", "maya3.*", "tts", "tts.*", "serve", "scripts", "configs"]+namespaces = true++[tool.setuptools.package-data]+maya3 = ["assets/*.json"]+configs = ["s3_fresh_v1.yaml", "text_frames_prior.json"]diff --git a/run_tests.sh b/run_tests.shnew file mode 100755index 0000000..a83c274--- /dev/null+++ b/run_tests.sh@@ -0,0 +1,6 @@+#!/usr/bin/env bash+# CPU test suite: no GPU, no weights, no network. Needs the [dev] extras.+set -euo pipefail+cd "$(dirname "$0")"+CUDA_VISIBLE_DEVICES= exec "${PYTHON:-python}" -m pytest -q -p no:cacheprovider \+ maya3/tests/test_text.py maya3/tests/test_guards.py maya3/tests/test_server.py "$@"diff --git a/scripts/s2_serve_controls.py b/scripts/s2_serve_controls.pynew file mode 100644index 0000000..2206e19--- /dev/null+++ b/scripts/s2_serve_controls.py@@ -0,0 +1,677 @@+"""Serving controls: the decode-side fixes for stop behaviour, long-form drift and output level.++Everything here is decode-side; the checkpoint is untouched. Three controls, each switchable so+ablations can be run with and without each one:++ --stop {sampled,controlled}+ sampled = the trained behaviour: <aeos> is one class in the multinomial cb0 draw (a+ well-fit model spreads the stop hazard over trailing-silence frames, so a+ non-aeos draw keeps talking = babble tails).+ controlled = <aeos> is masked out of the sampled draw; the stop fires when, after a+ text-conditioned minimum length, argmax == <aeos>, or p(<aeos>) >= --tau, or the+ cumulative stop hazard 1 - prod(1 - p_t) >= --hazard. The cap is the same+ per-language text -> frames prior at its p99 residual instead of a flat 1500.+ --chunk-s S+ chunked generation with RE-PROMPTING (against long-rollout drift): the text is split at sentence terminals into pieces+ of about S seconds (prior-estimated). Chunk 1 uses the requested arm. Chunk k > 1 is generated+ in a FRESH backbone context whose in-context reference is the previous chunk's text plus the+ last --ref-tail-frames of its generated codes (the same speaker memory throughout). Drift+ accumulated over long rollouts resets at each chunk boundary. 0 disables.+ --level {none,peaknorm,limiter}+ post-decode level control (against loudness ramps): peaknorm = the corpus's own consumer rule (attenuate so the+ peak sits at --ceiling-db, never boost); limiter = look-ahead peak limiter at --ceiling-db+ (5 ms look-ahead, 80 ms release) so a loudness ramp cannot flat-top.++Rails are computed on the RAW decode (so the ramp is visible) and on the processed output: clip rate+(|x| >= 0.999), flat-top runs (>= 3 consecutive pinned samples), pinned fraction, RMS dBFS, per-second+RMS slope (dB/s) and end-minus-start (last 3 s vs first 3 s), HF (> 6 kHz) energy fraction, silent+(>= 3 s of 1-s windows under RMS 0.005), frames / cap / aeos, duration vs the prior's expectation.++Targets: by default a LONG text per row is built by concatenating the target texts of other eval-set+rows of the same language until --long-chars characters (the corpus targets are ~10 s; drift and+loudness ramps need 25-40 s to show). --targets orig uses each row's own text instead.++ python scripts/s2_serve_controls.py --config <eval_config.yaml> --set <eval_set.pt> \+ --ckpt <run>/ckpt/<step> --out-dir <out_dir> --langs hi,te --per-lang 2 \+ --views spk_only,icl_spk --configs baseline,controlled [--device cuda:0] [--q-serve 16]++The checkpoint is loaded by the SHARED strict loader tts/model/load_s3.py, so an+S3 checkpoint builds and loads its speaker anchor and an S2 checkpoint does not — a disagreement+raises instead of silently serving a different model. --model-config <yaml> names the run config+that built the checkpoint (default: auto-discovered next to it, else --config);+--require-anchor {yes,no} asserts the arm before anything is built. The loaded model is echoed as+`CKPT_LOADED {...}` and stored in <out-dir>/run.json under "ckpt_provenance".++Configs (--configs): baseline = sampled stop, no chunking, no level control (the plain trained decode);+controlled = controlled stop + chunk-s (re-prompt on the ORIGINAL reference) + limiter; stop_only /+chunk_only / level_only ablations.++Further controls (added after listening tests reported "static / double voice from the start, worse by+the end, pure static once the transcript is done"):+ --greedy-from L depth levels >= L are taken by argmax instead of sampled (the fine codebooks+ sampled at temperature decode as broadband hiss on EVERY frame, and that hiss is+ fed back into the model's context). Configs greedy9 / greedy17 isolate it.+ --deep-temp T levels >= 9 sampled at temperature T (levels 1-8 keep --temp).+ --reprompt {orig,own} chunk k > 1 re-prompts on the row's ORIGINAL reference block (orig, default:+ clean human audio; for spk_only a fresh embedding-only context) or on the+ model's own previous chunk (own, the original behaviour, which carries the drift+ forward — te icl went 0.5% -> 8.4% HF by the last chunk in a short test).+ --static-stop H every --static-check frames after the minimum length, decode the last 3 s and+ stop when the HF fraction of the last 2 s exceeds H twice in a row (the+ "transcript is over, only static remains" state), or when it is silent+ (RMS < -45 dBFS). 0 disables.+ config "full" = controlled stop + chunking (orig) + limiter + greedy-from 9 + static-stop 0.05.+"""++import argparse+import collections+import json+import os+import re+import sys+import time+import wave++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+import numpy as np+import torch+import yaml++KIND_TEXT, KIND_AUDIO = 0, 1+SEED0 = 20260901+SR = 24000+FPS = 12.5+# per-language text -> frames prior (frames = a + b * chars), fitted on 40 shards of the+# training corpus (the --prior file, configs/text_frames_prior.json by default). resid_p99 = 99th percentile of the+# residual, used as the cap margin. Fallback when the JSON is not present.+PRIOR_DEFAULT = {"a": 2.0, "b": 0.72, "resid_p99": 90.0}+TERMINALS = "।.!?;।॥"+++def load_prior(path):+ prior = {}+ if path and os.path.exists(path):+ for lang, d in json.load(open(path)).items():+ prior[lang] = {"a": float(d["affine_a"]), "b": float(d["affine_b"]),+ "resid_p99": float(d["resid_p99"])}+ return prior+++def expected_frames(prior, lang, nchar):+ p = prior.get(lang, PRIOR_DEFAULT)+ return p["a"] + p["b"] * nchar, p["resid_p99"]+++# ----------------------------------------------------------------------------- text+def split_text(text, lang, prior, chunk_s):+ """Split at sentence terminals into pieces of about chunk_s seconds (prior-estimated).+ Falls back to commas, then whitespace, for run-on text."""+ if chunk_s <= 0:+ return [text]+ target = chunk_s * FPS+ # sentence pieces keep their terminal punctuation+ pieces = [p.strip() for p in re.split(f"(?<=[{re.escape(TERMINALS)}])\\s+", text) if p.strip()]+ out, cur = [], ""+ for p in pieces:+ cand = (cur + " " + p).strip() if cur else p+ if cur and expected_frames(prior, lang, len(cand))[0] > target:+ out.append(cur)+ cur = p+ else:+ cur = cand+ if cur:+ out.append(cur)+ # a single piece longer than the budget: split at commas / whitespace+ final = []+ for piece in out:+ if expected_frames(prior, lang, len(piece))[0] <= target * 1.3:+ final.append(piece)+ continue+ words = re.split(r"(?<=[,،])\s+|\s+", piece)+ cur = ""+ for w in words:+ cand = (cur + " " + w).strip() if cur else w+ if cur and expected_frames(prior, lang, len(cand))[0] > target:+ final.append(cur)+ cur = w+ else:+ cur = cand+ if cur:+ final.append(cur)+ return final+++def row_text(ex, tok, ctl_ids):+ """Target-span text of an eval-set view, decoded from its text tokens without control tokens."""+ t, k = np.asarray(ex["tokens"]), np.asarray(ex["kind"])+ ts = int(ex.get("target_start", 0))+ ids = [int(x) for x in t[ts:][k[ts:] == KIND_TEXT] if int(x) not in ctl_ids]+ return tok.decode(ids).strip()+++# ----------------------------------------------------------------------------- prompts+def make_example(packer, prefix, text, lang, spk_refs, spk_null):+ """Pack a prompt: an optional reference prefix (tokens/kind/codes/loss_mask arrays, already+ packed) followed by the target span for `text` (one dummy audio frame; the prompt is truncated+ at it)."""+ from tts.tokens import N_Q++ cut = {"text_final": text, "lang_final": lang, "codes": np.zeros((N_Q, 1), np.int64), "row": 0}+ first = prefix is None+ t, k, c, m = packer._span(cut, first=first, cont=False)+ if prefix is not None:+ t = np.concatenate([prefix["tokens"], t])+ k = np.concatenate([prefix["kind"], k])+ c = np.concatenate([prefix["codes"], c])+ m = np.concatenate([prefix["loss_mask"], m])+ ts = int(prefix["tokens"].shape[0])+ else:+ ts = 0+ return {"tokens": t, "kind": k, "codes": c, "loss_mask": m, "spk_refs": spk_refs,+ "spk_null": spk_null, "mode": "serve", "n_cuts": 1, "target_rows": [0],+ "ref_rows": [], "target_start": ts, "lang": lang}+++def ref_prefix_from_view(ex):+ """The packed reference block of an icl view (everything before target_start)."""+ ts = int(ex.get("target_start", 0))+ if ts == 0:+ return None+ return {key: np.asarray(ex[key])[:ts] for key in ("tokens", "kind", "codes", "loss_mask")}+++def ref_prefix_from_generated(packer, text, lang, codes_qF, q_serve, tail_frames):+ """Re-prompting reference: the previous chunk's text + the tail of its generated codes,+ packed as a first (lang-tagged) reference span. Levels >= q_serve are zero; the prompt is+ composed with q_use = q_serve so they are never read."""+ from tts.tokens import N_Q++ codes = codes_qF[:, -tail_frames:] if tail_frames > 0 else codes_qF+ full = np.zeros((N_Q, codes.shape[1]), np.int64)+ full[: codes.shape[0]] = codes.cpu().numpy() if torch.is_tensor(codes) else codes+ cut = {"text_final": text, "lang_final": lang, "codes": full, "row": 0}+ t, k, c, m = packer._span(cut, first=True, cont=False)+ return {"tokens": t, "kind": k, "codes": c, "loss_mask": m}+++def prompt_from_example(ex, model, dev, dt, q_serve):+ """Collate one example with q_use = q_serve, cut at the target's first audio position and+ compose the backbone inputs. Returns (prompt_emb, n_prompt_tokens).++ The prompt goes through collate_v2 (PackerV2._span -> collate_v2), so the S3 per-span+ geometry is built by the SAME code as in training and is only sliced here — never+ hand-made. The speaker vector the anchor reads is collate_v2's `spk_refs`/`spk_ref_mask`+ /`spk_null` block, i.e. the same mean-pooled ECAPA-192 input as in training+ (tts/model/anchors.py:52-65)."""+ from tts.data.packing_v2 import collate_v2+ from tts.model.load_s3 import truncate_prompt_batch++ b = collate_v2([ex], q_choices=(q_serve,), q_rng=np.random.default_rng(0))+ kind = b["kind"][0]+ ts = int(ex.get("target_start", 0))+ a = (kind == KIND_AUDIO).nonzero().flatten()+ a = a[a >= ts]+ assert a.numel(), "prompt has no target audio position"+ a0 = int(a[0])+ # slice the span tables with the columns. The target span's <|audio|>+ # sentinel is at a0-1 (the last prompt position, whose hidden state generates frame 0)+ # and MUST survive the cut, or the anchor never reaches the generating position.+ pb = truncate_prompt_batch(b, a0,+ require_target_span=model.speaker_anchor is not None)+ pb = {k: (v.to(dev, dtype=dt) if torch.is_tensor(v) and v.is_floating_point()+ else (v.to(dev) if torch.is_tensor(v) else v)) for k, v in pb.items()}+ return model.compose_inputs(pb), a0+++# ----------------------------------------------------------------------------- depth sampling[email protected]_mode()+def depth_generate(depth, h_frame, cb0, spk_mem, q_serve, temp, top_k, cfg_scale, ref_mask,+ greedy_from=None, deep_temp=None, deep_from=9):+ """DepthV2.generate with per-level control: levels >= greedy_from by argmax; levels >= deep_from+ at deep_temp (else temp). Same prefix construction and CFG as the model's own generate."""+ from tts.model.depth_v2 import GROUP_OF_LEVEL+ from tts.tokens import AEOS_CLASS++ if torch.any(cb0 >= AEOS_CLASS) or torch.any(cb0 < 0):+ raise ValueError("aeos/invalid cb0 must be handled by the caller")+ B = h_frame.shape[0]+ null_mem = None+ if cfg_scale > 0:+ null_mem = depth.null_mem.to(spk_mem.dtype).expand(B, spk_mem.shape[1], -1)+ outs = [cb0]+ for level in range(1, q_serve):+ codes_prev = torch.stack(outs, 1)+ x = depth._prefix(h_frame, codes_prev, level)+ h = depth._run(x, GROUP_OF_LEVEL[level], spk_mem, ref_mask)+ logits = depth.heads[level - 1](h).float()+ if cfg_scale > 0:+ hn = depth._run(x, GROUP_OF_LEVEL[level], null_mem)+ ln = depth.heads[level - 1](hn).float()+ logits = ln + cfg_scale * (logits - ln)+ if greedy_from is not None and level >= greedy_from:+ outs.append(logits.argmax(-1))+ continue+ t = deep_temp if (deep_temp is not None and level >= deep_from) else temp+ logits = logits / t+ if top_k:+ kth = logits.topk(top_k, -1).values[:, -1:]+ logits = logits.masked_fill(logits < kth, -float("inf"))+ outs.append(torch.multinomial(logits.softmax(-1), 1).squeeze(-1))+ return torch.stack(outs, -1)+++def hf_of(w, sr=SR):+ if w.size < 256:+ return 0.0+ sp = np.abs(np.fft.rfft(w)) ** 2+ f = np.fft.rfftfreq(len(w), 1 / sr)+ return float(sp[f >= 6000].sum() / (sp.sum() + 1e-12))+++# ----------------------------------------------------------------------------- session+class ServeSession:+ """Backbone KV session + DepthV2 frame decoding with speaker memory, plus the stop policy."""++ def __init__(self, model, spk_mem, ref_mask, q_serve=16, temp=0.7, top_k=64, cfg_scale=0.0,+ device="cuda:0", greedy_from=None, deep_temp=None, mimi=None, static_stop=0.0,+ static_check=25):+ self.m, self.dev = model, device+ self.mem, self.rmask = spk_mem, ref_mask+ self.q, self.temp, self.top_k, self.cfg = q_serve, temp, top_k, cfg_scale+ self.greedy_from, self.deep_temp = greedy_from, deep_temp+ self.mimi, self.static_stop, self.static_check = mimi, static_stop, static_check+ self.past = None++ def _static_state(self, out):+ """Decode the last 3 s of generated codes; return (hf of the last 2 s, rms dBFS)."""+ codes = torch.stack(out[-38:], -1)[None].to(self.dev).long()+ w = self.mimi.decode(codes)[0][0, 0].float().cpu().numpy()+ w = w[-2 * SR:]+ rms = 20 * np.log10(np.sqrt((w ** 2).mean()) + 1e-9) if w.size else -99.0+ return hf_of(w), float(rms)++ def _step(self, emb):+ h, self.past = self.m.backbone(emb, past_key_values=self.past, use_cache=True)+ return h[:, -1]++ def _cb0_probs(self, h):+ logits = self.m.backbone.cb0_logits(h).float() / self.temp+ if self.top_k:+ kth = logits.topk(self.top_k, -1).values[:, -1:]+ logits = logits.masked_fill(logits < kth, -float("inf"))+ return logits.softmax(-1)[0]++ @torch.inference_mode()+ def speak(self, prompt_emb, cap, stop="sampled", min_frames=0, tau=0.35, hazard=0.6):+ from tts.tokens import AEOS_CLASS++ h = self._step(prompt_emb.to(self.dev))+ out, p_trace, H = [], [], 0.0+ reason = "cap"+ static_hits = 0+ for t in range(cap):+ if (self.static_stop > 0 and self.mimi is not None and t >= max(min_frames, 38)+ and t % self.static_check == 0):+ hf, rms = self._static_state(out)+ if rms < -45.0:+ reason = "silence"+ break+ static_hits = static_hits + 1 if hf >= self.static_stop else 0+ if static_hits >= 2:+ reason = "static"+ break+ p = self._cb0_probs(h)+ p_aeos = float(p[AEOS_CLASS])+ p_trace.append(p_aeos)+ if stop == "sampled":+ cb0 = int(torch.multinomial(p, 1))+ if cb0 == AEOS_CLASS:+ reason = "aeos"+ break+ else:+ if t >= min_frames:+ H = 1.0 - (1.0 - H) * (1.0 - p_aeos)+ if int(p.argmax()) == AEOS_CLASS:+ reason = "aeos_argmax"+ break+ if p_aeos >= tau:+ reason = "aeos_tau"+ break+ if H >= hazard:+ reason = "aeos_hazard"+ break+ q = p.clone()+ q[AEOS_CLASS] = 0.0+ q = q / q.sum()+ cb0 = int(torch.multinomial(q, 1))+ frame = depth_generate(+ self.m.depth, h.float(), torch.tensor([cb0], device=self.dev), self.mem, self.q,+ self.temp, self.top_k, self.cfg, self.rmask, greedy_from=self.greedy_from,+ deep_temp=self.deep_temp)[0]+ out.append(frame)+ fb = self.m.audio_in.frames(frame[None, :], frame.shape[0])+ h = self._step(fb[None].to(prompt_emb.dtype))+ if reason.startswith("aeos"):+ self._step(self.m.audio_in.aeos(1)[None].to(prompt_emb.dtype))+ codes = (torch.stack(out, -1) if out+ else torch.zeros(self.q, 0, dtype=torch.long, device=self.dev))+ return codes, reason, p_trace+++# ----------------------------------------------------------------------------- level + rails+def peak_norm(x, ceiling_db=-1.0):+ ceil = 10 ** (ceiling_db / 20)+ peak = float(np.abs(x).max()) if x.size else 0.0+ g = min(1.0, ceil / peak) if peak > 0 else 1.0+ return (x * g).astype(np.float32), g+++def limiter(x, ceiling_db=-1.0, lookahead_s=0.005, release_s=0.08, sr=SR):+ """Look-ahead peak limiter: gain drops instantly (within the look-ahead window) to keep the+ windowed peak at the ceiling and recovers with an exponential release."""+ from scipy.ndimage import maximum_filter1d++ if x.size == 0:+ return x.astype(np.float32), 1.0+ ceil = 10 ** (ceiling_db / 20)+ L = max(1, int(lookahead_s * sr))+ env = maximum_filter1d(np.abs(x), size=2 * L + 1, mode="nearest")+ g = np.minimum(1.0, ceil / np.maximum(env, 1e-9))+ rel = float(np.exp(-1.0 / (release_s * sr)))+ out_g = np.empty_like(g)+ cur = 1.0+ for n in range(len(g)):+ gn = g[n]+ cur = gn if gn < cur else gn + (cur - gn) * rel+ out_g[n] = cur+ y = np.clip(x * out_g, -1.0, 1.0).astype(np.float32)+ return y, float(out_g.min())+++def rails(w, sr=SR):+ a = np.abs(w)+ n = len(w)+ pinned = a >= 0.999+ runs = 0+ if n:+ d = np.diff(np.concatenate([[0], pinned.astype(np.int8), [0]]))+ starts, ends = np.where(d == 1)[0], np.where(d == -1)[0]+ runs = int(((ends - starts) >= 3).sum())+ sec = w[: (n // sr) * sr].reshape(-1, sr) if n >= sr else np.zeros((0, sr))+ rms_s = 20 * np.log10(np.sqrt((sec ** 2).mean(1)) + 1e-9) if len(sec) else np.array([])+ slope = float(np.polyfit(np.arange(len(rms_s)), rms_s, 1)[0]) if len(rms_s) >= 4 else None+ end_start = (float(rms_s[-3:].mean() - rms_s[:3].mean()) if len(rms_s) >= 6 else None)+ if n:+ sp = np.abs(np.fft.rfft(w)) ** 2+ f = np.fft.rfftfreq(n, 1 / sr)+ hf = float(sp[f >= 6000].sum() / (sp.sum() + 1e-12))+ else:+ hf = None+ thirds = None+ if len(sec) >= 3:+ hfs = [hf_of(x) for x in sec]+ t3 = len(hfs) // 3+ thirds = [round(float(np.mean(hfs[:t3])), 4), round(float(np.mean(hfs[t3:2 * t3])), 4),+ round(float(np.mean(hfs[2 * t3:])), 4)]+ silent_run = 0+ best = 0+ for r in rms_s:+ silent_run = silent_run + 1 if r < 20 * np.log10(0.005) else 0+ best = max(best, silent_run)+ return {+ "dur_s": round(n / sr, 2),+ "peak_dbfs": round(float(20 * np.log10(a.max() + 1e-9)), 2) if n else None,+ "rms_dbfs": round(float(20 * np.log10(np.sqrt((w ** 2).mean()) + 1e-9)), 2) if n else None,+ "clip_frac": round(float(pinned.mean()), 5) if n else None,+ "flat_top_runs": runs,+ "rms_slope_db_s": None if slope is None else round(slope, 3),+ "rms_end_minus_start_db": None if end_start is None else round(end_start, 2),+ "hf_frac_gt6k": None if hf is None else round(hf, 4),+ "hf_thirds": thirds,+ "silent_ge3s": bool(best >= 3),+ }+++def save_wav(p, w):+ with wave.open(p, "wb") as fh:+ fh.setnchannels(1)+ fh.setsampwidth(2)+ fh.setframerate(SR)+ fh.writeframes((np.clip(w, -1, 1) * 32767).astype("<i2").tobytes())+++CONFIGS = {+ # stop / chunk / level are the base controls; greedy_from / deep_temp / reprompt / static_stop the further ones+ "baseline": {"stop": "sampled", "chunk": False, "level": "none"},+ "controlled": {"stop": "controlled", "chunk": True, "level": "limiter", "reprompt": "orig"},+ "stop_only": {"stop": "controlled", "chunk": False, "level": "none"},+ "chunk_only": {"stop": "sampled", "chunk": True, "level": "none", "reprompt": "orig"},+ "chunk_own": {"stop": "sampled", "chunk": True, "level": "none", "reprompt": "own"},+ "level_only": {"stop": "sampled", "chunk": False, "level": "limiter"},+ "greedy17": {"stop": "sampled", "chunk": False, "level": "none", "greedy_from": 17},+ "greedy9": {"stop": "sampled", "chunk": False, "level": "none", "greedy_from": 9},+ "deep05": {"stop": "sampled", "chunk": False, "level": "none", "deep_temp": 0.5},+ "full": {"stop": "controlled", "chunk": True, "level": "limiter", "reprompt": "orig",+ "greedy_from": 9, "static_stop": 0.05},+}+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--config", required=True)+ ap.add_argument("--set", dest="set_path", required=True)+ ap.add_argument("--ckpt", required=True)+ ap.add_argument("--out-dir", required=True)+ ap.add_argument("--langs", default="hi,te")+ ap.add_argument("--per-lang", type=int, default=2)+ ap.add_argument("--views", default="spk_only,icl_spk")+ ap.add_argument("--configs", default="baseline,controlled")+ ap.add_argument("--targets", choices=["long", "orig"], default="long")+ ap.add_argument("--long-chars", type=int, default=450)+ ap.add_argument("--temp", type=float, default=0.7)+ ap.add_argument("--top-k", type=int, default=64)+ ap.add_argument("--q-serve", type=int, default=16)+ ap.add_argument("--cfg", type=float, default=0.0)+ ap.add_argument("--hard-cap", type=int, default=1500)+ ap.add_argument("--tau", type=float, default=0.35)+ ap.add_argument("--hazard", type=float, default=0.6)+ ap.add_argument("--min-frac", type=float, default=0.5,+ help="minimum length as a fraction of the prior's expected frames")+ ap.add_argument("--chunk-s", type=float, default=16.0)+ ap.add_argument("--ref-tail-frames", type=int, default=150)+ ap.add_argument("--level", default=None, help="override the config's level control")+ ap.add_argument("--ceiling-db", type=float, default=-1.0)+ ap.add_argument("--prior", default=os.path.join(os.path.dirname(__file__), "..", "configs",+ "text_frames_prior.json"))+ ap.add_argument("--greedy-from", type=int, default=None, help="override: levels >= L by argmax")+ ap.add_argument("--deep-temp", type=float, default=None, help="override: levels >= 9 at this temp")+ ap.add_argument("--reprompt", choices=["orig", "own"], default=None, help="override chunk re-prompt source")+ ap.add_argument("--static-stop", type=float, default=None, help="override: HF fraction that stops (0 off)")+ ap.add_argument("--static-check", type=int, default=25)+ ap.add_argument("--device", default="cuda:0")+ ap.add_argument("--threads", type=int, default=8)+ ap.add_argument("--seed", type=int, default=SEED0)+ # the run config that BUILT the checkpoint (speaker anchor etc). Default =+ # auto-discovered next to the checkpoint, else --config. --require-anchor asserts the arm.+ ap.add_argument("--model-config", default=None)+ ap.add_argument("--require-anchor", choices=["yes", "no"], default=None)+ A = ap.parse_args()++ torch.set_num_threads(A.threads)+ cfg = yaml.safe_load(open(A.config))+ dev = A.device+ dt = torch.bfloat16 if dev.startswith("cuda") else torch.float32+ os.makedirs(A.out_dir + "/wav", exist_ok=True)+ prior = load_prior(A.prior)+ if not prior:+ print(f"WARNING: no prior at {A.prior}; using the default {PRIOR_DEFAULT}", flush=True)+ views = A.views.split(",")+ configs = A.configs.split(",")+ langs = A.langs.split(",")++ from transformers import AutoTokenizer++ from tts.data.packing_v2 import PackerV2+ from tts.model.load_s3 import load_model_for_eval+ from tts.tokens import extend_tokenizer++ tok = AutoTokenizer.from_pretrained(cfg["model"]["backbone"])+ tok, ids = extend_tokenizer(tok)+ ctl_ids = set(int(v) for v in ids.values())+ packer = PackerV2(tok, ids, max_tokens=int(cfg["data"].get("max_tokens", 8192)))+ if dev.startswith("cuda"):+ torch.backends.cuda.enable_cudnn_sdp(False)+ t0 = time.time()+ # shared STRICT loader (tts/model/load_s3.py). A loader that always built an anchor-free+ # model and never asked for the checkpoint's extra tensors would silently serve a different+ # model from an anchored checkpoint.+ model, prov = load_model_for_eval(+ A.ckpt, device=dev, dtype=dt, cfg=cfg, config=A.model_config,+ amortize_frac=1.0, # unused here (generation never calls forward())+ require_anchor=None if A.require_anchor is None+ else A.require_anchor == "yes")+ model.depth.float()+ print(f"model loaded in {time.time() - t0:.0f}s on {dev} "+ f"(anchor={prov['anchor']}, update={prov['update']})", flush=True)++ from transformers import MimiModel++ mimi = MimiModel.from_pretrained("kyutai/mimi").to(dev).eval()+ data = torch.load(A.set_path, weights_only=False)+ by_lang = collections.defaultdict(list)+ for i, row in enumerate(data["rows"]):+ by_lang[row["lang"]].append((i, row))+ picked = []+ for lang in langs:+ rows = by_lang.get(lang, [])+ picked += [(lang, i, r) for i, r in rows[: A.per_lang]]+ # long targets: concatenate OTHER rows' target texts of the same language+ texts = {lang: [row_text(r["views"]["spk_only"], tok, ctl_ids) for _, r in by_lang[lang]]+ for lang in langs}++ recs = []+ for lang, i, row in picked:+ own = row_text(row["views"]["spk_only"], tok, ctl_ids)+ if A.targets == "long":+ pool = [t for t in texts[lang] if t != own] or [own]+ text, k = own, 0+ while len(text) < A.long_chars:+ text = text + " " + pool[k % len(pool)]+ k += 1+ else:+ text = own+ exp_frames, _resid = expected_frames(prior, lang, len(text))+ for view in views:+ ex0 = row["views"][view]+ spk_refs = np.asarray(ex0["spk_refs"], np.float32)+ spk_null = bool(ex0.get("spk_null", True))+ refs_t = torch.as_tensor(spk_refs, dtype=torch.float32, device=dev)[None]+ null_t = torch.tensor([spk_null], device=dev)+ mem = model.depth.spk_memory(refs_t, "ecapa", null_mask=null_t)+ rmask = torch.ones(1, refs_t.shape[1], dtype=torch.bool, device=dev)+ icl_prefix = ref_prefix_from_view(ex0) if view.startswith("icl") else None+ for cname in configs:+ c = dict(CONFIGS[cname])+ if A.level is not None:+ c["level"] = A.level+ greedy_from = A.greedy_from if A.greedy_from is not None else c.get("greedy_from")+ deep_temp = A.deep_temp if A.deep_temp is not None else c.get("deep_temp")+ reprompt = A.reprompt or c.get("reprompt", "orig")+ static_stop = A.static_stop if A.static_stop is not None else c.get("static_stop", 0.0)+ chunks = split_text(text, lang, prior, A.chunk_s if c["chunk"] else 0)+ torch.manual_seed(A.seed + 7919 * i + 101 * views.index(view))+ gen_codes, reasons, frames_per_chunk, caps = [], [], [], []+ prev_text, prev_codes = None, None+ tg = time.time()+ for ci, ctext in enumerate(chunks):+ if ci == 0 or reprompt == "orig":+ prefix = icl_prefix+ else:+ prefix = ref_prefix_from_generated(packer, prev_text, lang, prev_codes,+ A.q_serve, A.ref_tail_frames)+ ex = make_example(packer, prefix, ctext, lang, spk_refs, spk_null)+ emb, _ = prompt_from_example(ex, model, dev, dt, A.q_serve)+ ef, er = expected_frames(prior, lang, len(ctext))+ if c["stop"] == "controlled":+ cap = min(A.hard_cap, int(ef + er + 10))+ min_frames = max(4, int(A.min_frac * ef))+ else:+ cap = A.hard_cap+ min_frames = 0+ sess = ServeSession(model, mem, rmask, q_serve=A.q_serve, temp=A.temp,+ top_k=A.top_k, cfg_scale=A.cfg if not spk_null else 0.0,+ device=dev, greedy_from=greedy_from, deep_temp=deep_temp,+ mimi=mimi, static_stop=static_stop,+ static_check=A.static_check)+ codes, reason, _ = sess.speak(emb.to(dt), cap, stop=c["stop"],+ min_frames=min_frames, tau=A.tau,+ hazard=A.hazard)+ gen_codes.append(codes)+ reasons.append(reason)+ frames_per_chunk.append(int(codes.shape[-1]))+ caps.append(cap)+ prev_text, prev_codes = ctext, codes+ print(f" [{lang} r{i} {view} {cname}] chunk {ci + 1}/{len(chunks)} "+ f"{codes.shape[-1]}f cap {cap} stop={reason} "+ f"({time.time() - tg:.0f}s)", flush=True)+ codes = torch.cat(gen_codes, -1) if gen_codes else None+ recs.append({"lang": lang, "row": i, "view": view, "config": cname, "text": text,+ "nchar": len(text), "exp_frames": round(exp_frames, 1),+ "chunks": len(chunks), "frames": frames_per_chunk, "caps": caps,+ "stops": reasons, "gen_frames": int(codes.shape[-1]),+ "level": c["level"], "greedy_from": greedy_from,+ "deep_temp": deep_temp, "reprompt": reprompt if c["chunk"] else None,+ "static_stop": static_stop, "codes": codes.cpu()})+ del model+ if dev.startswith("cuda"):+ torch.cuda.empty_cache()+ summary = collections.defaultdict(list)+ with torch.inference_mode(), open(A.out_dir + "/rails.jsonl", "w") as fh:+ for n, rec in enumerate(recs):+ codes = rec.pop("codes")+ if codes.shape[-1] == 0:+ w = np.zeros(0, np.float32)+ else:+ w = mimi.decode(codes[None].to(dev).long())[0][0, 0].float().cpu().numpy()+ raw = rails(w)+ if rec["level"] == "peaknorm":+ y, g = peak_norm(w, A.ceiling_db)+ elif rec["level"] == "limiter":+ y, g = limiter(w, A.ceiling_db)+ else:+ y, g = np.clip(w, -1, 1).astype(np.float32), 1.0+ proc = rails(y)+ base = f"{A.out_dir}/wav/{n:03d}_{rec['lang']}_r{rec['row']}_{rec['view']}_{rec['config']}"+ save_wav(base + "_raw.wav", w)+ if rec["level"] != "none":+ save_wav(base + "_proc.wav", y)+ rec.update({"raw": raw, "proc": proc, "min_gain": round(float(g), 3),+ "dur_ratio_vs_prior": round(rec["gen_frames"] / max(1.0, rec["exp_frames"]), 3)})+ fh.write(json.dumps(rec, ensure_ascii=False) + "\n")+ key = (rec["view"], rec["config"])+ summary[key].append(rec)+ print(f"{n:03d} {rec['lang']} r{rec['row']} {rec['view']:8s} {rec['config']:10s} "+ f"{rec['gen_frames']:4d}f/{rec['exp_frames']:.0f} exp, chunks {rec['chunks']}, "+ f"stops {','.join(rec['stops'])} | RAW peak {raw['peak_dbfs']} rms {raw['rms_dbfs']} "+ f"clip {raw['clip_frac']} runs {raw['flat_top_runs']} slope {raw['rms_slope_db_s']} "+ f"hf {raw['hf_frac_gt6k']} | PROC peak {proc['peak_dbfs']} clip {proc['clip_frac']} "+ f"runs {proc['flat_top_runs']}", flush=True)+ print("\n=== SUMMARY (means over rows; RAW decode unless marked proc) ===")+ print(f"{'view':9s}{'config':11s}{'n':>3s}{'frames':>8s}{'dur/exp':>8s}{'peak':>7s}{'rms':>7s}"+ f"{'clip%':>7s}{'runs':>6s}{'slope':>7s}{'end-st':>7s}{'hf%':>6s}{'procclip%':>10s}{'procruns':>9s}")+ for (view, cname), rs in summary.items():+ def mean(key, sub="raw", rs=rs):+ vals = [r[sub][key] for r in rs if r[sub][key] is not None]+ return sum(vals) / len(vals) if vals else float("nan")+ print(f"{view:9s}{cname:11s}{len(rs):3d}{sum(r['gen_frames'] for r in rs) / len(rs):8.0f}"+ f"{sum(r['dur_ratio_vs_prior'] for r in rs) / len(rs):8.2f}{mean('peak_dbfs'):7.2f}"+ f"{mean('rms_dbfs'):7.2f}{100 * mean('clip_frac'):7.3f}{mean('flat_top_runs'):6.0f}"+ f"{mean('rms_slope_db_s'):7.3f}{mean('rms_end_minus_start_db'):7.2f}"+ f"{100 * mean('hf_frac_gt6k'):6.2f}{100 * mean('clip_frac', 'proc'):10.3f}"+ f"{mean('flat_top_runs', 'proc'):9.0f}")+ json.dump({"args": vars(A), "n": len(recs), "ckpt_provenance": prov},+ open(A.out_dir + "/run.json", "w"), indent=1)+++if __name__ == "__main__":+ main()diff --git a/serve/cache.py b/serve/cache.pynew file mode 100644index 0000000..382c626--- /dev/null+++ b/serve/cache.py@@ -0,0 +1,62 @@+"""Reference ragged-cache batching; positions remain local to each seat."""+import torch+from transformers import DynamicCache+from transformers.cache_utils import DynamicLayer+++def cache_from_owned_tensors(layers):+ """Install freshly owned tensors without concatenating them to empty caches.++ DynamicCache(ddp_cache_data=...) calls update(), which copies every tensor+ once more. These inputs are already owned by this cache, so initialization+ can install them directly using the pinned DynamicLayer representation.+ """+ cache=DynamicCache()+ for keys,values in layers:+ layer=DynamicLayer()+ layer.keys,layer.values=keys,values+ layer.dtype,layer.device=keys.dtype,keys.device+ layer.is_initialized=True+ cache.layers.append(layer)+ return cache+++def pack_caches(caches, new_tokens, device):+ lengths=[c.layers[0].keys.shape[-2] if c is not None else 0 for c in caches]+ maximum=max(lengths)+ if maximum==0:+ return None,None,lengths+ exemplar=next(c for c in caches if c is not None)+ layers=[]+ for li in range(len(exemplar.layers)):+ kv=[]+ for name in ('keys','values'):+ sample=getattr(exemplar.layers[li],name)+ stacked=sample.new_zeros(len(caches),sample.shape[1],maximum,sample.shape[-1])+ for i,(c,length) in enumerate(zip(caches,lengths)):+ if length:+ stacked[i:i+1,:,-length:]=getattr(c.layers[li],name)+ kv.append(stacked)+ layers.append(tuple(kv))+ mask=torch.arange(maximum+new_tokens,device=device)[None]>=torch.tensor(+ [maximum-l for l in lengths],device=device)[:,None]+ return cache_from_owned_tensors(layers),mask,lengths+++def split_cache(cache,lengths,keep=None,*,copy=True):+ """Split cache rows, optionally borrowing immutable views for experiments.++ The default gives independent mutable storage. copy=False permits only+ DynamicLayer append/crop operations, which replace tensors rather than+ writing existing storage. A borrowed row retains the whole packed batch+ until all views die; measure memory before using it in a serving path.+ """+ def take(tensor,i,length):+ view=tensor[i:i+1,:,-length:]+ return view.clone(memory_format=torch.contiguous_format) if copy else view+ result=[]+ for i,length in enumerate(lengths):+ length=min(length,keep) if keep is not None else length+ result.append(cache_from_owned_tensors([+ (take(l.keys,i,length),take(l.values,i,length)) for l in cache.layers]))+ return resultdiff --git a/serve/fast_backbone.py b/serve/fast_backbone.pynew file mode 100644index 0000000..93600d7--- /dev/null+++ b/serve/fast_backbone.py@@ -0,0 +1,362 @@+"""Static-KV, CUDA-graph single-token decode for the Qwen3 backbone with per-seat positions.++KV lives in [max_slots+1, kv_heads, capacity, head_dim] tensors per layer (last row is a+dummy slot used to pad a batch up to its bucket; its length stays 0). One CUDA graph per+(batch bucket, context bucket); all graphs share one memory pool. HF module weights are+used in place (no copies).+"""+from __future__ import annotations++import os+from pathlib import Path++ROOT=Path(__file__).resolve().parents[1]+os.environ.setdefault('TRITON_CACHE_DIR',str(ROOT/'serve/scratch/triton'))+import torch+import torch.nn.functional as F++try:+ import triton+ import triton.language as tl+except Exception: # pragma: no cover+ triton=None+++def _rotate_half(x):+ half=x.shape[-1]//2+ return torch.cat((-x[...,half:],x[...,:half]),-1)+++if triton is not None:+ @triton.jit+ def _decode_attn(Q,K,V,Out,Slots,Pos,scale,+ sq_b,sq_h,sk_s,sk_h,sk_t,so_b,so_h,+ G:tl.constexpr,D:tl.constexpr,BLOCK:tl.constexpr,NBLOCKS:tl.constexpr):+ """One program per (row, q head). Reads the static cache in place for keys 0..pos."""+ row=tl.program_id(0);head=tl.program_id(1)+ slot=tl.load(Slots+row);pos=tl.load(Pos+row)+ d=tl.arange(0,D)+ q=tl.load(Q+row*sq_b+head*sq_h+d).to(tl.float32)+ kbase=K+slot*sk_s+(head//G)*sk_h+ vbase=V+slot*sk_s+(head//G)*sk_h+ m=tl.full((),-float('inf'),tl.float32)+ den=tl.zeros((),tl.float32)+ acc=tl.zeros((D,),tl.float32)+ for blk in range(0,NBLOCKS):+ t=blk*BLOCK+tl.arange(0,BLOCK)+ valid=t<=pos+ k=tl.load(kbase+t[:,None]*sk_t+d[None,:],mask=valid[:,None],other=0.).to(tl.float32)+ s=tl.sum(k*q[None,:],1)*scale+ s=tl.where(valid,s,-float('inf'))+ bm=tl.maximum(m,tl.max(s,0))+ w=tl.exp(s-bm)+ v=tl.load(vbase+t[:,None]*sk_t+d[None,:],mask=valid[:,None],other=0.).to(tl.float32)+ r=tl.exp(m-bm)+ acc=acc*r+tl.sum(w[:,None]*v,0)+ den=den*r+tl.sum(w,0)+ m=bm+ tl.store(Out+row*so_b+head*so_h+d,(acc/den).to(Out.dtype.element_ty))+++ @triton.jit+ def _qk_norm_rope_cache(QKV,Qout,K,V,Slots,Pos,COS,SIN,WQ,WK,eps,+ s_qkv,s_qo_b,s_qo_h,sk_s,sk_h,sk_t,s_cos,+ H:tl.constexpr,KVH:tl.constexpr,D:tl.constexpr):+ """Fused Qwen3 q_norm/k_norm (RMSNorm) + RoPE + K/V cache write for one (row, head). Program j < H: query head;+ j >= H: key head j-H (also copies its value head into the cache)."""+ row=tl.program_id(0);j=tl.program_id(1)+ half=tl.arange(0,D//2)+ pos=tl.load(Pos+row)+ c1=tl.load(COS+pos*s_cos+half).to(tl.float32);c2=tl.load(COS+pos*s_cos+D//2+half).to(tl.float32)+ n1s=tl.load(SIN+pos*s_cos+half).to(tl.float32);n2s=tl.load(SIN+pos*s_cos+D//2+half).to(tl.float32)+ if j<H:+ base=QKV+row*s_qkv+j*D;w1=tl.load(WQ+half).to(tl.float32);w2=tl.load(WQ+D//2+half).to(tl.float32)+ else:+ base=QKV+row*s_qkv+(H+j-H)*D;w1=tl.load(WK+half).to(tl.float32);w2=tl.load(WK+D//2+half).to(tl.float32)+ x1=tl.load(base+half).to(tl.float32);x2=tl.load(base+D//2+half).to(tl.float32)+ inv=1.0/tl.sqrt((tl.sum(x1*x1,0)+tl.sum(x2*x2,0))/D+eps)+ # HF: weight * (x*inv).to(bf16), in bf16+ y1=(x1*inv).to(tl.bfloat16).to(tl.float32)*w1;y2=(x2*inv).to(tl.bfloat16).to(tl.float32)*w2+ y1=y1.to(tl.bfloat16).to(tl.float32);y2=y2.to(tl.bfloat16).to(tl.float32)+ o1=y1*c1-y2*n1s;o2=y2*c2+y1*n2s+ if j<H:+ ob=Qout+row*s_qo_b+j*s_qo_h+ tl.store(ob+half,o1.to(Qout.dtype.element_ty));tl.store(ob+D//2+half,o2.to(Qout.dtype.element_ty))+ else:+ kh=j-H;slot=tl.load(Slots+row)+ kb=K+slot*sk_s+kh*sk_h+pos*sk_t+ tl.store(kb+half,o1.to(K.dtype.element_ty));tl.store(kb+D//2+half,o2.to(K.dtype.element_ty))+ vb=QKV+row*s_qkv+(H+KVH+kh)*D+ vv1=tl.load(vb+half);vv2=tl.load(vb+D//2+half)+ vcb=V+slot*sk_s+kh*sk_h+pos*sk_t+ tl.store(vcb+half,vv1);tl.store(vcb+D//2+half,vv2)+++ @triton.jit+ def _add_rms(Hin,A,Hout,Y,W,eps,s_h,s_a,s_ho,s_y,N:tl.constexpr):+ """h' = h + a (bf16 rounding, as torch) ; y = W * (h' * rsqrt(mean(h'^2) + eps)).to(bf16) (HF Qwen3RMSNorm)."""+ row=tl.program_id(0);c=tl.arange(0,N)+ hs=(tl.load(Hin+row*s_h+c).to(tl.float32)+tl.load(A+row*s_a+c).to(tl.float32)).to(tl.bfloat16)+ tl.store(Hout+row*s_ho+c,hs)+ x=hs.to(tl.float32)+ inv=1.0/tl.sqrt(tl.sum(x*x,0)/N+eps)+ y=(x*inv).to(tl.bfloat16).to(tl.float32)*tl.load(W+c).to(tl.float32)+ tl.store(Y+row*s_y+c,y.to(tl.bfloat16))+++class _Graph:+ __slots__=('graph','slots','slots_cpu','x','real','real_cpu','out','last','offset','offset_cpu','offset_dirty','evt')+++class StaticBackbone:+ def __init__(self,backbone,max_slots,capacity=1536,+ batch_buckets=(1,2,4,8,16,24,32,48,64,80,96),ctx_buckets=(512,768,1024,1536),+ attention='gather',fused_norm=False,use_graphs=True,fuse_proj=False,fuse_rope=False):+ """attention: 'gather' (index_select + matmul; the simple path) or 'triton' (in-place kernel)."""+ if attention not in ('gather','triton'):raise ValueError('attention must be gather or triton')+ if attention=='triton' and triton is None:raise RuntimeError('triton is not importable')+ with torch.inference_mode():+ self.backbone=backbone;self.lm=backbone.lm.model;cfg=backbone.lm.config+ self.layers=list(self.lm.layers);self.norm=self.lm.norm+ p=next(self.lm.parameters());self.dtype=p.dtype;self.device=p.device+ self.heads=cfg.num_attention_heads;self.kv_heads=cfg.num_key_value_heads+ self.head_dim=getattr(cfg,'head_dim',cfg.hidden_size//cfg.num_attention_heads)+ self.groups=self.heads//self.kv_heads;self.hidden=cfg.hidden_size+ self.scaling=self.head_dim**-0.5;self.eps=cfg.rms_norm_eps+ self.max_slots=max_slots;self.capacity=capacity;self.dummy=max_slots+ self.attention=attention;self.fused_norm=fused_norm;self.use_graphs=use_graphs+ # fuse_proj: one GEMM for q|k|v and one for gate|up per layer; the HF modules' weights become views of the+ # concatenated tensors (no extra memory; the HF path still works)+ self.fuse_proj=fuse_proj or fuse_rope;self.fuse_rope=fuse_rope and attention=='triton';self.wqkv=[];self.wgu=[]+ if self.fuse_proj:+ for layer in self.layers:+ a=layer.self_attn;m=layer.mlp+ if a.q_proj.bias is not None or getattr(m.gate_proj,'bias',None) is not None:raise ValueError('fuse_proj expects bias-free projections')+ w=torch.cat([a.q_proj.weight,a.k_proj.weight,a.v_proj.weight]).contiguous()+ nq,nk=a.q_proj.weight.shape[0],a.k_proj.weight.shape[0]+ a.q_proj.weight.data=w[:nq];a.k_proj.weight.data=w[nq:nq+nk];a.v_proj.weight.data=w[nq+nk:]+ self.wqkv.append(w)+ g=torch.cat([m.gate_proj.weight,m.up_proj.weight]).contiguous();ng=m.gate_proj.weight.shape[0]+ m.gate_proj.weight.data=g[:ng];m.up_proj.weight.data=g[ng:]+ self.wgu.append(g)+ # Row buckets may exceed max_slots: inline prefill adds several rows for one slot.+ self.batch_buckets=tuple(sorted(set(batch_buckets)))+ if self.batch_buckets[-1]<max_slots:self.batch_buckets+=(max_slots,)+ self.ctx_buckets=tuple(sorted({min(c,capacity) for c in ctx_buckets}|{capacity}))+ shape=(max_slots+1,self.kv_heads,capacity,self.head_dim)+ self.k=[torch.zeros(shape,dtype=self.dtype,device=self.device) for _ in self.layers]+ self.v=[torch.zeros(shape,dtype=self.dtype,device=self.device) for _ in self.layers]+ self.lengths=torch.zeros(max_slots+1,dtype=torch.long,device=self.device)+ self.lengths_cpu=[0]*(max_slots+1)+ positions=torch.arange(capacity,device=self.device)[None]+ cos,sin=self.lm.rotary_emb(torch.zeros(1,1,self.hidden,dtype=self.dtype,device=self.device),positions)+ self.cos=cos[0].contiguous();self.sin=sin[0].contiguous() # [capacity, head_dim], model dtype (as HF)+ self.graphs={};self.pool=None++ # ---------------------------------------------------------------- slots+ @torch.inference_mode()+ def load_slot(self,slot,hf_cache,length):+ if not 0<=slot<self.max_slots:raise IndexError(slot)+ if length>self.capacity:raise ValueError(f'length {length} exceeds capacity {self.capacity}')+ for i in range(len(self.layers)):+ layer=hf_cache.layers[i]+ self.k[i][slot,:,:length].copy_(layer.keys[0,:,:length])+ self.v[i][slot,:,:length].copy_(layer.values[0,:,:length])+ self.lengths[slot]=length;self.lengths_cpu[slot]=length++ @torch.inference_mode()+ def free(self,slot):+ self.lengths[slot]=0;self.lengths_cpu[slot]=0++ # ---------------------------------------------------------------- math+ def _rms(self,module,x):+ if self.fused_norm:return F.rms_norm(x,(x.shape[-1],),module.weight,self.eps)+ return module(x)++ def _forward(self,slots,x,real,ctx,offset=None):+ B=x.shape[0];H=self.heads;KV=self.kv_heads;D=self.head_dim;G=self.groups+ pos=self.lengths[slots] # [B]+ if offset is not None:pos=pos+offset # inline prefill: several consecutive rows of one slot+ cos=self.cos[pos][:,None];sin=self.sin[pos][:,None] # [B,1,D]+ if self.attention=='gather':+ bias=torch.zeros(B,ctx,dtype=torch.float32,device=x.device).masked_fill_(+ torch.arange(ctx,device=x.device)[None]>pos[:,None],float('-inf')).view(B,1,1,ctx)+ h=x;pend=None+ for i,layer in enumerate(self.layers):+ attn=layer.self_attn+ if self.fuse_rope and pend is not None:+ h,y=self._add_norm(h,pend,layer.input_layernorm.weight);pend=None+ else:+ y=self._rms(layer.input_layernorm,h)+ kc=self.k[i];vc=self.v[i]+ if self.fuse_rope:+ qkv=F.linear(y,self.wqkv[i]).contiguous()+ q=torch.empty(B,H,D,dtype=qkv.dtype,device=qkv.device)+ _qk_norm_rope_cache[(B,H+KV)](qkv,q,kc,vc,slots,pos,self.cos,self.sin,attn.q_norm.weight,attn.k_norm.weight,+ self.eps,qkv.stride(0),q.stride(0),q.stride(1),kc.stride(0),kc.stride(1),kc.stride(2),self.cos.stride(0),+ H=H,KVH=KV,D=D)+ o=torch.empty_like(q)+ self._launch(q,kc,vc,o,slots,pos,ctx)+ h,y2=self._add_norm(h,attn.o_proj(o.view(B,H*D)),layer.post_attention_layernorm.weight)+ gu=F.linear(y2,self.wgu[i]);g_,u_=gu.chunk(2,-1)+ pend=layer.mlp.down_proj(F.silu(g_)*u_)+ continue+ if self.fuse_proj:+ qkv=F.linear(y,self.wqkv[i]);q_,k_,v_=qkv.split([H*D,KV*D,KV*D],-1)+ q=self._rms(attn.q_norm,q_.view(B,H,D));k=self._rms(attn.k_norm,k_.view(B,KV,D));v=v_.view(B,KV,D)+ else:+ q=self._rms(attn.q_norm,attn.q_proj(y).view(B,H,D))+ k=self._rms(attn.k_norm,attn.k_proj(y).view(B,KV,D))+ v=attn.v_proj(y).view(B,KV,D)+ q=q*cos+_rotate_half(q)*sin+ k=k*cos+_rotate_half(k)*sin+ kc=self.k[i];vc=self.v[i]+ kc[slots,:,pos]=k;vc[slots,:,pos]=v+ if self.attention=='gather':+ K=kc[:,:,:ctx].index_select(0,slots);V=vc[:,:,:ctx].index_select(0,slots) # [B,KV,ctx,D]+ scores=torch.matmul(q.view(B,KV,G,D),K.transpose(-1,-2)).float()*self.scaling+bias+ o=torch.matmul(scores.softmax(-1).to(q.dtype),V).reshape(B,H*D)+ else:+ q=q.contiguous();o=torch.empty_like(q)+ self._launch(q,kc,vc,o,slots,pos,ctx)+ o=o.view(B,H*D)+ h=h+attn.o_proj(o)+ if self.fuse_proj:+ gu=F.linear(self._rms(layer.post_attention_layernorm,h),self.wgu[i]);g_,u_=gu.chunk(2,-1)+ h=h+layer.mlp.down_proj(F.silu(g_)*u_)+ else:+ h=h+layer.mlp(self._rms(layer.post_attention_layernorm,h))+ if pend is not None:+ h,out=self._add_norm(h,pend,self.norm.weight)+ else:+ out=self._rms(self.norm,h)+ self.lengths.index_add_(0,slots,real)+ return out++ def _add_norm(self,h,a,w):+ if h.dtype!=torch.bfloat16:raise ValueError('fused add+norm kernel is bf16-only')+ a=a.contiguous();ho=torch.empty_like(h);y=torch.empty_like(h)+ _add_rms[(h.shape[0],)](h,a,ho,y,w,self.eps,h.stride(0),a.stride(0),ho.stride(0),y.stride(0),N=h.shape[-1])+ return ho,y++ def _launch(self,q,kc,vc,o,slots,pos,ctx):+ block=256+ _decode_attn[(q.shape[0],self.heads)](q,kc,vc,o,slots,pos,self.scaling,+ q.stride(0),q.stride(1),kc.stride(0),kc.stride(1),kc.stride(2),o.stride(0),o.stride(1),+ G=self.groups,D=self.head_dim,BLOCK=block,NBLOCKS=(ctx+block-1)//block)+ return o++ # ---------------------------------------------------------------- graphs+ def _bucket(self,values,need,what):+ for b in values:+ if b>=need:return b+ raise ValueError(f'{what} {need} exceeds largest bucket {values[-1]}')++ @torch.inference_mode()+ def _capture(self,bb,cb):+ g=_Graph()+ g.slots=torch.full((bb,),self.dummy,dtype=torch.long,device=self.device)+ g.real=torch.zeros(bb,dtype=torch.long,device=self.device)+ g.offset=torch.zeros(bb,dtype=torch.long,device=self.device)+ g.offset_cpu=torch.zeros(bb,dtype=torch.long).pin_memory();g.offset_dirty=False+ g.x=torch.zeros(bb,self.hidden,dtype=self.dtype,device=self.device)+ g.slots_cpu=torch.full((bb,),self.dummy,dtype=torch.long).pin_memory()+ g.real_cpu=torch.zeros(bb,dtype=torch.long).pin_memory()+ g.last=None;g.graph=None;g.evt=None+ if self.use_graphs:+ stream=torch.cuda.Stream()+ stream.wait_stream(torch.cuda.current_stream())+ with torch.cuda.stream(stream):+ for _ in range(2):self._forward(g.slots,g.x,g.real,cb,g.offset) # all-dummy rows: touches only the dummy slot+ torch.cuda.current_stream().wait_stream(stream)+ if self.pool is None:self.pool=torch.cuda.graph_pool_handle()+ g.graph=torch.cuda.CUDAGraph()+ with torch.cuda.graph(g.graph,pool=self.pool):+ g.out=self._forward(g.slots,g.x,g.real,cb,g.offset)+ self.graphs[bb,cb]=g+ return g++ @torch.inference_mode()+ def warmup(self,batch_buckets=None,ctx_buckets=None):+ # Largest first so later (smaller) captures reuse the shared pool's blocks.+ for bb in sorted(batch_buckets or self.batch_buckets,reverse=True):+ for cb in sorted(ctx_buckets or self.ctx_buckets,reverse=True):+ cb=min(cb,self.capacity)+ if (bb,cb) not in self.graphs:self._capture(bb,cb)+ torch.cuda.synchronize()++ @torch.inference_mode()+ def step(self,slots,x):+ B=len(slots)+ if B==0:return x.new_zeros(0,self.hidden)+ if len(set(slots))!=B:raise ValueError('duplicate slots in one step')+ need=0+ for s in slots:+ if not 0<=s<self.max_slots:raise IndexError(s)+ need=max(need,self.lengths_cpu[s]+1)+ if need>self.capacity:raise ValueError(f'context {need} exceeds capacity {self.capacity}')+ bb=self._bucket(self.batch_buckets,B,'batch');cb=self._bucket(self.ctx_buckets,need,'context')+ g=self.graphs.get((bb,cb)) or self._capture(bb,cb)+ key=tuple(slots)+ if g.offset_dirty:g.offset.zero_();g.offset_dirty=False;g.last=None+ if g.last!=key:+ if g.evt is not None:g.evt.synchronize() # pinned staging may still feed an earlier async copy+ g.slots_cpu[:B]=torch.tensor(slots,dtype=torch.long);g.slots_cpu[B:]=self.dummy+ g.real_cpu[:B]=1;g.real_cpu[B:]=0+ g.slots.copy_(g.slots_cpu,non_blocking=True);g.real.copy_(g.real_cpu,non_blocking=True)+ g.evt=torch.cuda.Event();g.evt.record()+ g.last=key+ g.x[:B].copy_(x)+ if g.graph is not None:+ g.graph.replay();out=g.out[:B].clone()+ else:+ out=self._forward(g.slots,g.x,g.real,cb,g.offset)[:B]+ for s in slots:self.lengths_cpu[s]+=1+ return out++ @torch.inference_mode()+ def load_prefix(self,slot,kv,length):+ """Install a stored reference-prefix KV (list of per-layer (k,v) [1,KV,length,D]) into a slot."""+ if not 0<=slot<self.max_slots:raise IndexError(slot)+ for i,(k,v) in enumerate(kv):+ self.k[i][slot,:,:length].copy_(k[0]);self.v[i][slot,:,:length].copy_(v[0])+ self.lengths[slot]=length;self.lengths_cpu[slot]=length++ @torch.inference_mode()+ def step_mixed(self,slots,x,prefills):+ """One graphed step for decoding seats plus inline prefills.++ prefills: list of (slot, x_tokens [T,hidden]); the slot must already hold its prefix.+ Each prefill contributes T rows of the same slot at consecutive positions: every layer+ writes all rows' K/V before attention, and row i only reads keys <= its own position,+ so this is an exact causal prefill. Returns (decode hidden [B,hidden], [last hidden per prefill]).+ """+ B=len(slots);rows=B+sum(t.shape[0] for _,t in prefills)+ if rows==0:return x.new_zeros(0,self.hidden),[]+ if len(set(slots)|{s for s,_ in prefills})!=B+len(prefills):raise ValueError('duplicate slots in one step')+ need=max([self.lengths_cpu[s]+1 for s in slots]+[self.lengths_cpu[s]+t.shape[0] for s,t in prefills])+ if need>self.capacity:raise ValueError(f'context {need} exceeds capacity {self.capacity}')+ bb=self._bucket(self.batch_buckets,rows,'batch');cb=self._bucket(self.ctx_buckets,need,'context')+ g=self.graphs.get((bb,cb)) or self._capture(bb,cb)+ if g.evt is not None:g.evt.synchronize()+ index=list(slots);offsets=[0]*B+ for s,t in prefills:index+=[s]*t.shape[0];offsets+=range(t.shape[0])+ g.slots_cpu[:rows]=torch.tensor(index,dtype=torch.long);g.slots_cpu[rows:]=self.dummy+ g.offset_cpu[:rows]=torch.tensor(offsets,dtype=torch.long);g.offset_cpu[rows:]=0+ g.real_cpu[:rows]=1;g.real_cpu[rows:]=0+ g.slots.copy_(g.slots_cpu,non_blocking=True);g.real.copy_(g.real_cpu,non_blocking=True)+ g.offset.copy_(g.offset_cpu,non_blocking=True);g.last=None;g.offset_dirty=bool(prefills)+ g.evt=torch.cuda.Event();g.evt.record()+ if B:g.x[:B].copy_(x)+ at=B+ for _,t in prefills:g.x[at:at+t.shape[0]].copy_(t);at+=t.shape[0]+ if g.graph is not None:g.graph.replay();out=g.out+ else:out=self._forward(g.slots,g.x,g.real,cb,g.offset)+ decoded=out[:B].clone();last=[];at=B+ for s,t in prefills:+ at+=t.shape[0];last.append(out[at-1].clone());self.lengths_cpu[s]+=t.shape[0]+ for s in slots:self.lengths_cpu[s]+=1+ return decoded,last++ def memory_bytes(self):+ return sum(t.numel()*t.element_size() for t in self.k+self.v)diff --git a/serve/fast_codec.py b/serve/fast_codec.pynew file mode 100644index 0000000..35d4f99--- /dev/null+++ b/serve/fast_codec.py@@ -0,0 +1,277 @@+"""Slot-based, static-state, CUDA-graphed one-frame Mimi decoder.++Arithmetic mirrors serve/codec.py::StreamingMimi (the verified reference): causal+convolution history, transposed-convolution overlap tails (bias removed from the+stored tail), and sliding-window attention with absolute RoPE positions. The+difference is where state lives: every stateful layer owns ONE static tensor with+a row per slot (row ``max_slots`` is a dummy used to pad a batch to its bucket),+and the decoder transformer runs against static per-slot KV ring buffers, so one+decode is a single CUDA-graph replay with no per-seat Python work.++No upstream module or parameter is modified; HF sub-modules are called for their+weights. Global side effect: warmup() sets torch.backends.cudnn.benchmark=False so+convolution algorithm choice is settled before capture. Matmul/cuDNN TF32 flags+are read at capture time and baked into the graphs.++Sliding-window semantics (HF create_sliding_window_causal_mask, reproduced by+StreamingMimi keeping sliding_window-1 cached tokens plus the new ones): a query+at absolute position p sees keys with p - sliding_window < key_pos <= p.+"""+import torch+import torch.nn.functional as F+from transformers.models.mimi.modeling_mimi import (MimiConv1d, MimiConvTranspose1d, MimiResnetBlock,+ apply_rotary_pos_emb, repeat_kv)++NEVER = -(1 << 40) # key_pos of an empty ring entry; always outside every window+++class _Bucket:+ __slots__ = ('graph', 'slots', 'codes', 'out', 'pinned', 'events', 'turn')+++class StaticMimi:+ def __init__(self, mimi, max_slots, batch_buckets=(1, 2, 4, 8, 16, 24, 32, 48, 64, 80, 96), ring=256):+ cfg = mimi.config+ if not cfg.use_causal_conv or cfg.pad_mode != 'constant' or cfg.trim_right_ratio != 1:+ raise ValueError('Static decoder requires causal constant padding and trim_right_ratio=1')+ if mimi.upsample is None:+ raise ValueError('Static decoder expects the Mimi upsample layer')+ self.m = mimi+ self.max_slots = int(max_slots)+ self.dummy = self.max_slots+ self.batch_buckets = tuple(sorted(set(int(b) for b in batch_buckets)))+ self.window = int(cfg.sliding_window)+ self.frame_tokens = int(mimi.upsample.conv.stride[0])+ self.ring = int(ring)+ if self.ring < self.window + self.frame_tokens:+ raise ValueError('ring must hold sliding_window + frame_tokens entries')+ parameter = next(mimi.parameters())+ self.device, self.dtype = parameter.device, parameter.dtype+ self.codebooks = int(cfg.num_quantizers)+ with torch.inference_mode():+ # Convolution history / overlap tails: one flat row per slot, one view per stateful layer.+ self._spec = {}+ self._plan(mimi.upsample, 'upsample')+ for i, layer in enumerate(mimi.decoder.layers):+ self._plan(layer, f'decoder.{i}')+ total = sum(c * p for c, p in self._spec.values())+ rows = self.max_slots + 1+ self.conv_flat = torch.zeros(rows, total, device=self.device, dtype=self.dtype)+ self.state, offset = {}, 0+ for key, (channels, pad) in self._spec.items():+ self.state[key] = self.conv_flat[:, offset:offset + channels * pad].view(rows, channels, pad)+ offset += channels * pad+ layers = mimi.decoder_transformer.layers+ attn = layers[0].self_attn+ self.kv_heads, self.head_dim, self.kv_groups = attn.num_key_value_heads, attn.head_dim, attn.num_key_value_groups+ # [layer, k/v, slot, heads, ring, head_dim]; keys are stored post-RoPE.+ self.kv = torch.zeros(len(layers), 2, rows, self.kv_heads, self.ring, self.head_dim,+ device=self.device, dtype=self.dtype)+ self.key_pos = torch.full((rows, self.ring), NEVER, device=self.device, dtype=torch.long)+ self.tokens = torch.zeros(rows, device=self.device, dtype=torch.long)+ self._steps = torch.arange(self.frame_tokens, device=self.device)+ rotary = attn.rotary_emb+ self._inv_freq = rotary.inv_freq.detach().float().clone()+ self._rope_scale = float(rotary.attention_scaling)+ self._pool = None+ self._buckets = {}+ self.samples_per_frame = None++ # ---- state layout -------------------------------------------------------------------------+ def _plan(self, module, key):+ if isinstance(module, MimiConv1d):+ if module.conv.stride != (1,):+ raise ValueError('Only stride-one decoder convolutions are supported')+ padding = (module.conv.kernel_size[0] - 1) * module.conv.dilation[0]+ if padding:+ self._spec[key] = (module.conv.in_channels, padding)+ elif isinstance(module, MimiConvTranspose1d):+ if module.padding_left != 0 or module.conv.dilation != (1,):+ raise ValueError('Unsupported transpose-convolution geometry')+ if module.padding_right:+ self._spec[key] = (module.conv.out_channels, module.padding_right)+ elif isinstance(module, MimiResnetBlock):+ self._plan(module.shortcut, key + '.shortcut')+ for i, child in enumerate(module.block):+ self._plan(child, key + f'.block.{i}')++ def state_bytes_per_slot(self):+ return {'conv': self.conv_flat[0].numel() * self.conv_flat.element_size(),+ 'attention_kv': self.kv[:, :, 0].numel() * self.kv.element_size(),+ 'attention_index': self.key_pos[0].numel() * 8 + 8}++ # ---- graph body ---------------------------------------------------------------------------+ def _layer(self, module, x, slots, key):+ if isinstance(module, MimiConv1d):+ if key in self.state:+ state = self.state[key]+ joined = torch.cat((state.index_select(0, slots), x), dim=-1)+ state.index_copy_(0, slots, joined[..., -state.shape[-1]:])+ x = joined+ return module.conv(x)+ if isinstance(module, MimiConvTranspose1d):+ y = module.conv(x)+ produced = x.shape[-1] * module.conv.stride[0]+ if key in self.state:+ state = self.state[key]+ overlap = state.shape[-1]+ if overlap > produced:+ raise ValueError('Chunk too short for transpose-convolution overlap')+ previous = state.index_select(0, slots)+ tail = y[..., produced:]+ if module.conv.bias is not None:+ tail = tail - module.conv.bias[None, :, None]+ state.index_copy_(0, slots, tail)+ y[..., :overlap] += previous # disjoint from the tail because overlap <= produced+ return y[..., :produced]+ if isinstance(module, MimiResnetBlock):+ shortcut = self._layer(module.shortcut, x, slots, key + '.shortcut')+ for i, child in enumerate(module.block):+ x = self._layer(child, x, slots, key + f'.block.{i}')+ return shortcut + x+ return module(x)++ @staticmethod+ def _rvq(rvq, codes):+ total = None+ for i in range(codes.shape[1]):+ e = F.embedding(codes[:, i], rvq.layers[i].codebook.embed).permute(0, 2, 1)+ total = e if total is None else total + e+ return rvq.output_proj(total) if rvq.output_proj is not None else total++ def _quantizer(self, codes):+ # Same arithmetic as MimiSplitResidualVectorQuantizer.decode, without its in-graph torch.tensor(0.0).+ q = self.m.quantizer+ n = q.num_semantic_quantizers+ out = self._rvq(q.semantic_residual_vector_quantizer, codes[:, :n])+ if codes.shape[1] > n:+ out = out + self._rvq(q.acoustic_residual_vector_quantizer, codes[:, n:])+ return out++ def _transformer(self, h, slots):+ batch, count, _ = h.shape+ start = self.tokens.index_select(0, slots)+ positions = start[:, None] + self._steps[None] # [B,T] absolute+ ring_index = positions % self.ring+ rows = slots[:, None]+ self.key_pos.index_put_((rows, ring_index), positions)+ key_pos = self.key_pos.index_select(0, slots)[:, None, :] # [B,1,R]+ query_pos = positions[:, :, None] # [B,T,1]+ mask = ((key_pos <= query_pos) & (key_pos > query_pos - self.window))[:, None] # [B,1,T,R]+ freqs = positions[:, :, None].float() * self._inv_freq[None, None, :]+ emb = torch.cat((freqs, freqs), dim=-1)+ cos = (emb.cos() * self._rope_scale).to(h.dtype)+ sin = (emb.sin() * self._rope_scale).to(h.dtype)+ for li, layer in enumerate(self.m.decoder_transformer.layers):+ attn = layer.self_attn+ x = layer.input_layernorm(h)+ q = attn.q_proj(x).view(batch, count, attn.num_heads, self.head_dim).transpose(1, 2)+ k = attn.k_proj(x).view(batch, count, self.kv_heads, self.head_dim).transpose(1, 2)+ v = attn.v_proj(x).view(batch, count, self.kv_heads, self.head_dim).transpose(1, 2)+ q, k = apply_rotary_pos_emb(q, k, cos, sin)+ keys, values = self.kv[li, 0], self.kv[li, 1]+ # Advanced indices on dims 0 and 2 put the indexed dims first: value layout [B,T,heads,dim].+ keys[rows, :, ring_index] = k.transpose(1, 2)+ values[rows, :, ring_index] = v.transpose(1, 2)+ k_all = repeat_kv(keys.index_select(0, slots), self.kv_groups)+ v_all = repeat_kv(values.index_select(0, slots), self.kv_groups)+ a = F.scaled_dot_product_attention(q, k_all, v_all, attn_mask=mask)+ a = attn.o_proj(a.transpose(1, 2).reshape(batch, count, -1))+ h = h + layer.self_attn_layer_scale(a)+ h = h + layer.mlp_layer_scale(layer.mlp(layer.post_attention_layernorm(h)))+ self.tokens.index_copy_(0, slots, start + count)+ self.tokens[self.dummy].zero_()+ return h++ def _forward(self, slots, codes):+ x = self._quantizer(codes)+ x = self._layer(self.m.upsample, x, slots, 'upsample')+ x = self._transformer(x.transpose(1, 2), slots).transpose(1, 2)+ for i, layer in enumerate(self.m.decoder.layers):+ x = self._layer(layer, x, slots, f'decoder.{i}')+ return x++ # ---- capture ------------------------------------------------------------------------------+ def _capture(self, size):+ bucket = _Bucket()+ bucket.slots = torch.full((size,), self.dummy, device=self.device, dtype=torch.long)+ bucket.codes = torch.zeros(size, self.codebooks, 1, device=self.device, dtype=torch.long)+ bucket.pinned = [torch.full((size,), self.dummy, dtype=torch.long).pin_memory() for _ in range(8)]+ bucket.events = [None] * len(bucket.pinned)+ bucket.turn = 0+ # Warmup and capture touch only the dummy slot, so live seats are never disturbed.+ side = torch.cuda.Stream(device=self.device)+ side.wait_stream(torch.cuda.current_stream(self.device))+ with torch.cuda.stream(side):+ for _ in range(3):+ self._forward(bucket.slots, bucket.codes)+ torch.cuda.current_stream(self.device).wait_stream(side)+ torch.cuda.synchronize(self.device)+ if self._pool is None:+ self._pool = torch.cuda.graph_pool_handle()+ bucket.graph = torch.cuda.CUDAGraph()+ with torch.cuda.graph(bucket.graph, pool=self._pool):+ bucket.out = self._forward(bucket.slots, bucket.codes)+ if self.samples_per_frame is None:+ self.samples_per_frame = bucket.out.shape[-1]+ self._reset_row(self.dummy)+ self._buckets[size] = bucket+ return bucket++ @torch.inference_mode()+ def warmup(self, batch_buckets=None):+ torch.backends.cudnn.benchmark = False+ sizes = self.batch_buckets if batch_buckets is None else tuple(sorted(set(int(b) for b in batch_buckets)))+ for size in sorted(sizes, reverse=True): # largest first so the shared pool is sized once+ if size not in self._buckets:+ self._capture(size)+ self.batch_buckets = tuple(sorted(set(self.batch_buckets) | set(sizes)))++ # ---- public -------------------------------------------------------------------------------+ def _reset_row(self, row):+ self.conv_flat[row].zero_()+ self.key_pos[row].fill_(NEVER)+ self.tokens[row].zero_()++ @torch.inference_mode()+ def reset(self, slot, zero_kv=False):+ """Three fill kernels, no host sync. KV rows are unreachable once key_pos is NEVER+ (masked weights are exactly zero); zero_kv=True additionally clears them."""+ if not 0 <= slot < self.max_slots:+ raise IndexError(f'slot {slot} outside [0,{self.max_slots})')+ self._reset_row(slot)+ if zero_kv:+ self.kv[:, :, slot].zero_()++ @torch.inference_mode()+ def decode(self, slots, codes):+ """slots: distinct ints in [0,max_slots) (or a CUDA long tensor of them); codes: [B,K] long CUDA,+ one frame per seat. Returns an owned float32 [B, samples_per_frame] tensor."""+ count = len(slots)+ if codes.shape[0] != count or codes.dim() != 2 or codes.shape[1] != self.codebooks:+ raise ValueError(f'codes must be [{count},{self.codebooks}], got {tuple(codes.shape)}')+ size = next((b for b in self.batch_buckets if b >= count), None)+ if size is None:+ raise ValueError(f'batch {count} exceeds largest bucket {self.batch_buckets[-1]}')+ bucket = self._buckets.get(size) or self._capture(size)+ if torch.is_tensor(slots):+ bucket.slots[:count].copy_(slots)+ bucket.slots[count:].fill_(self.dummy)+ else:+ if len(set(slots)) != count or min(slots) < 0 or max(slots) >= self.max_slots:+ raise ValueError('slots must be distinct and inside [0,max_slots)')+ # Rotate pinned staging rows so an async H2D copy is never overwritten before it runs.+ turn = bucket.turn+ bucket.turn = (turn + 1) % len(bucket.pinned)+ if bucket.events[turn] is not None:+ bucket.events[turn].synchronize()+ staging = bucket.pinned[turn]+ staging[:count] = torch.tensor(slots, dtype=torch.long)+ staging[count:] = self.dummy+ bucket.slots.copy_(staging, non_blocking=True)+ event = torch.cuda.Event()+ event.record()+ bucket.events[turn] = event+ bucket.codes[:count, :, 0].copy_(codes)+ bucket.graph.replay()+ return bucket.out[:count, 0].float().clone() if bucket.out.dtype != torch.float32 else bucket.out[:count, 0].clone()diff --git a/serve/fast_depth.py b/serve/fast_depth.pynew file mode 100644index 0000000..05ace5b--- /dev/null+++ b/serve/fast_depth.py@@ -0,0 +1,257 @@+"""Whole-frame depth decoder in one CUDA graph per batch bucket (bf16 by default).++One replay = 31 depth levels + in-graph sampling + the backbone feedback+embedding. Differences from WholeDepthGraph/IncrementalDepth, all of them the+same real-valued function (kernel order differs, so not bit-exact):++* a private lower-precision deep copy of `model.depth` (the original is untouched);+* speaker cross-attention hoisted to a per-slot constant table (single unmasked+ reference => softmax is exactly one => output is o(v), independent of the query),+ gathered inside the graph from a static `slots_idx`, so admission needs no recapture;+* ONE engine-wide CUDA generator registered on every graph and one batched+ `exponential_` per level (no per-seat Philox state copies);+* prefix embeddings computed once per position (position k depends on slot k alone)+ from a fused `code_up(code_lo)+level_emb` table, written into a static buffer;+* preallocated within-group KV (one strided write per layer instead of two cats);+* `is_causal=True` instead of a rebuilt boolean mask; no `_assert_async`;+* last trunk layer evaluates only the final position (its other outputs are never+ read: later levels of a shared group reuse this layer's K/V, which come from its input).+"""+import copy+import math++import torch+import torch.nn.functional as F++from tts.model.depth_v2 import GROUP_OF_LEVEL, LAYERS, D, H++HEAD = D // H+N_LEVELS = 32+++class FastDepth:+ def __init__(self, model, max_slots, dtype=torch.bfloat16, temp=0.7, top_k=64,+ batch_buckets=(1, 2, 4, 8, 16, 24, 32, 48, 64, 80, 96), seed=1234, greedy=False, compile=False, fused=False):+ if model.depth.n_q != N_LEVELS:+ raise ValueError('FastDepth expects the 32-codebook depth stack')+ self.max_slots = int(max_slots)+ self.dtype = dtype+ self.temp = float(temp)+ self.top_k = int(top_k)+ self.greedy = bool(greedy) # debug: argmax of the same fp32 probabilities+ self.batch_buckets = tuple(sorted(set(int(b) for b in batch_buckets)))+ with torch.inference_mode():+ d = copy.deepcopy(model.depth).to(dtype).eval().requires_grad_(False)+ self.depth = d+ self.device = d.in_proj.weight.device+ self.n_codes = d.n_codes+ # position k+1 of the prefix = code_up(code_lo[cb_k + k*n_codes]) + level_emb[k+1]+ table = d.code_up(d.code_lo.weight).view(N_LEVELS - 1, self.n_codes, D)+ self.embed = (table + d.level_emb.weight[1:N_LEVELS, None]).contiguous()+ self.level0 = d.level_emb.weight[0].clone()+ self.audio_in = model.audio_in # shared, read-only (engine dtype, bf16 in serving)+ self.feedback_offsets = torch.arange(N_LEVELS, device=self.device) * model.audio_in.n_codes+ self.feedback_scale = math.sqrt(N_LEVELS)+ # row max_slots is the padding slot (zeros)+ self.cross_const = torch.zeros(self.max_slots + 1, LAYERS, D, device=self.device, dtype=dtype)+ self.generator = torch.Generator(device=self.device).manual_seed(int(seed))+ self.pool = None+ self.graphs = {}+ # optional: Inductor-fused frame body (fixed shape per bucket), still replayed as one CUDA graph+ # fused=True: Triton add+LayerNorm and one-kernel top-k sampling (serve/fast_depth_kernels.py); RNG = Philox keyed by+ # a device seed the graph increments each replay (same distribution, different random stream than torch's)+ self.fused = bool(fused)+ self.seed_t = torch.full((1,), int(seed) % (2 ** 31 - 1), device=self.device, dtype=torch.int32)+ # per-slot sampling streams (fused path): seed of the slot's request and its frame counter (incremented in-graph)+ self.row_seed = torch.zeros(self.max_slots + 1, device=self.device, dtype=torch.int32)+ self.row_ctr = torch.zeros(self.max_slots + 1, device=self.device, dtype=torch.int32)+ self.per_row = True+ body = self._compute_fused if self.fused else self._compute+ self._fn = torch.compile(body, dynamic=False) if compile else body++ @torch.inference_mode()+ def set_speaker(self, slot, mem, ref_mask):+ if mem.ndim != 3 or mem.shape[0] != 1 or mem.shape[1] != 1 or tuple(ref_mask.shape) != (1, 1):+ raise ValueError(f'FastDepth serves exactly one reference per slot; got mem {tuple(mem.shape)}')+ if not 0 <= slot < self.max_slots:+ raise IndexError(f'slot {slot} outside 0..{self.max_slots - 1}')+ mem = mem.to(self.device, self.dtype)+ keep = ref_mask.to(self.device)[:, :, None]+ for layer, block in enumerate(self.depth.cross):+ _, v = block.kv(mem).chunk(2, -1)+ self.cross_const[slot, layer].copy_(block.o(v * keep)[0, 0])++ def _compute(self, slots_idx, h, cb0):+ d = self.depth+ B = h.shape[0]+ cross = self.cross_const[slots_idx] # [B, LAYERS, D]+ cross = [cross[:, layer, None] for layer in range(LAYERS)]+ prefix = torch.empty(B, N_LEVELS, D, device=h.device, dtype=self.dtype)+ prefix[:, 0] = d.in_proj(h) + self.level0+ prefix[:, 1] = F.embedding(cb0, self.embed[0])+ # [layer][B, position, k|v, head, dim]: one strided write per layer and level+ kv = [torch.empty(B, N_LEVELS, 2, H, HEAD, device=h.device, dtype=self.dtype) for _ in range(LAYERS)]+ codes = [cb0]+ previous = None+ for level in range(1, N_LEVELS):+ group = GROUP_OF_LEVEL[level]+ n = level + 1+ incremental = group == previous+ reused_later = level + 1 < N_LEVELS and GROUP_OF_LEVEL[level + 1] == group+ x = prefix[:, level:n] if incremental else prefix[:, :n]+ for layer, block in enumerate(d.groups[group]):+ T = x.shape[1]+ qkv = block.qkv(block.n1(x)).view(B, T, 3, H, HEAD)+ q = qkv[:, :, 0].transpose(1, 2)+ if incremental:+ kv[layer][:, level:n].copy_(qkv[:, :, 1:])+ k = kv[layer][:, :n, 0].transpose(1, 2)+ v = kv[layer][:, :n, 1].transpose(1, 2)+ a = F.scaled_dot_product_attention(q, k, v)+ else:+ if reused_later:+ kv[layer][:, :n].copy_(qkv[:, :, 1:])+ k = qkv[:, :, 1].transpose(1, 2)+ v = qkv[:, :, 2].transpose(1, 2)+ if layer == LAYERS - 1:+ # only the final position is read after the last layer; it sees every key+ a = F.scaled_dot_product_attention(q[:, :, -1:], k, v)+ x = x[:, -1:]+ else:+ a = F.scaled_dot_product_attention(q, k, v, is_causal=True)+ x = x + block.o(a.transpose(1, 2).reshape(B, x.shape[1], D))+ x = x + block.f2(F.gelu(block.f1(block.n2(x))))+ x = x + cross[layer]+ logits = d.heads[level - 1](d.norm(x[:, -1])).float() / self.temp+ kth = logits.topk(self.top_k, -1).values[:, -1:]+ probs = logits.masked_fill(logits < kth, -float('inf')).softmax(-1)+ if self.greedy:+ code = probs.argmax(-1)+ else:+ race = torch.empty_like(probs).exponential_(1, generator=self.generator)+ code = (probs / race).argmax(-1)+ codes.append(code)+ if n < N_LEVELS:+ prefix[:, n] = F.embedding(code, self.embed[level])+ previous = group+ codes = torch.stack(codes, -1)+ # == model.audio_in.frames(codes, 32) without its host-synchronizing range check+ e = self.audio_in.table(codes + self.feedback_offsets)+ feedback = self.audio_in.norm(e.sum(1) / self.feedback_scale)+ return codes, feedback++ def _compute_fused(self, slots_idx, h, cb0):+ from serve.fast_depth_kernels import add_ln, topk_sample+ d = self.depth+ B = h.shape[0]+ cross = self.cross_const[slots_idx] # [B, LAYERS, D]+ cross = [cross[:, layer, None] for layer in range(LAYERS)]+ prefix = torch.empty(B, N_LEVELS, D, device=h.device, dtype=self.dtype)+ prefix[:, 0] = d.in_proj(h) + self.level0+ prefix[:, 1] = F.embedding(cb0, self.embed[0])+ kv = [torch.empty(B, N_LEVELS, 2, H, HEAD, device=h.device, dtype=self.dtype) for _ in range(LAYERS)]+ codes = [cb0]+ previous = None+ row_seed = self.row_seed[slots_idx]+ row_ctr = self.row_ctr[slots_idx]+ for level in range(1, N_LEVELS):+ group = GROUP_OF_LEVEL[level]+ n = level + 1+ incremental = group == previous+ reused_later = level + 1 < N_LEVELS and GROUP_OF_LEVEL[level + 1] == group+ x = prefix[:, level:n] if incremental else prefix[:, :n]+ blocks = d.groups[group]+ y = blocks[0].n1(x)+ for layer, block in enumerate(blocks):+ T = x.shape[1]+ qkv = block.qkv(y).view(B, T, 3, H, HEAD)+ q = qkv[:, :, 0].transpose(1, 2)+ if incremental:+ kv[layer][:, level:n].copy_(qkv[:, :, 1:])+ k = kv[layer][:, :n, 0].transpose(1, 2)+ v = kv[layer][:, :n, 1].transpose(1, 2)+ a = F.scaled_dot_product_attention(q, k, v)+ else:+ if reused_later:+ kv[layer][:, :n].copy_(qkv[:, :, 1:])+ k = qkv[:, :, 1].transpose(1, 2)+ v = qkv[:, :, 2].transpose(1, 2)+ if layer == LAYERS - 1:+ a = F.scaled_dot_product_attention(q[:, :, -1:], k, v)+ x = x[:, -1:]+ else:+ a = F.scaled_dot_product_attention(q, k, v, is_causal=True)+ T = x.shape[1]+ x, y2 = add_ln(x, block.o(a.transpose(1, 2).reshape(B, T, D)), block.n2)+ f = block.f2(F.gelu(block.f1(y2)))+ nxt = blocks[layer + 1].n1 if layer + 1 < LAYERS else d.norm+ x, y = add_ln(x, f, nxt, cross[layer])+ # y = d.norm(x) of the final position (x is [B,1,D] after the last layer)+ if self.per_row:+ code = topk_sample(d.heads[level - 1](y[:, -1]), row_seed, level, self.temp, self.top_k, self.greedy, ctr_t=row_ctr)+ else:+ code = topk_sample(d.heads[level - 1](y[:, -1]), self.seed_t, level, self.temp, self.top_k, self.greedy)+ codes.append(code)+ if n < N_LEVELS:+ prefix[:, n] = F.embedding(code, self.embed[level])+ previous = group+ self.seed_t.add_(1)+ self.row_ctr.index_add_(0, slots_idx, torch.ones_like(row_ctr))+ codes = torch.stack(codes, -1)+ e = self.audio_in.table(codes + self.feedback_offsets)+ feedback = self.audio_in.norm(e.sum(1) / self.feedback_scale)+ return codes, feedback++ @torch.inference_mode()+ def _capture(self, bucket):+ if bucket in self.graphs:+ return self.graphs[bucket]+ s = {'slots_idx': torch.full((bucket,), self.max_slots, device=self.device, dtype=torch.long),+ 'h': torch.zeros(bucket, self.depth.in_proj.in_features, device=self.device, dtype=self.dtype),+ 'cb0': torch.zeros(bucket, device=self.device, dtype=torch.long),+ 'last_slots': None}+ stream = torch.cuda.Stream()+ stream.wait_stream(torch.cuda.current_stream())+ with torch.cuda.stream(stream):+ for _ in range(3):+ self._fn(s['slots_idx'], s['h'], s['cb0'])+ torch.cuda.current_stream().wait_stream(stream)+ if self.pool is None:+ self.pool = torch.cuda.graph_pool_handle()+ graph = torch.cuda.CUDAGraph()+ graph.register_generator_state(self.generator)+ with torch.cuda.graph(graph, pool=self.pool, stream=stream):+ s['codes'], s['feedback'] = self._fn(s['slots_idx'], s['h'], s['cb0'])+ s['graph'] = graph+ self.graphs[bucket] = s+ return s++ def warmup(self, batch_buckets=None):+ # largest first so smaller captures reuse the shared pool's blocks+ for bucket in sorted(set(batch_buckets or self.batch_buckets), reverse=True):+ self._capture(int(bucket))++ def bucket_for(self, batch):+ for bucket in self.batch_buckets:+ if bucket >= batch:+ return bucket+ raise ValueError(f'batch {batch} exceeds the largest bucket {self.batch_buckets[-1]}')++ @torch.inference_mode()+ def __call__(self, slots, h, cb0):+ B = len(slots)+ if h.shape[0] != B or cb0.shape[0] != B:+ raise ValueError('slots, h and cb0 must have the same batch size')+ s = self._capture(self.bucket_for(B))+ key = tuple(slots)+ if key != s['last_slots']:+ if any(not 0 <= slot < self.max_slots for slot in key):+ raise IndexError(f'slot outside 0..{self.max_slots - 1}')+ # pageable source: staged before copy_ returns, so a later call cannot race it+ padded = list(key) + [self.max_slots] * (s['slots_idx'].shape[0] - B)+ s['slots_idx'].copy_(torch.tensor(padded, dtype=torch.long))+ s['last_slots'] = key+ s['h'][:B].copy_(h)+ s['cb0'][:B].copy_(cb0)+ s['graph'].replay()+ return s['codes'][:B].clone(), s['feedback'][:B].clone()diff --git a/serve/fast_depth_kernels.py b/serve/fast_depth_kernels.pynew file mode 100644index 0000000..8bcbb09--- /dev/null+++ b/serve/fast_depth_kernels.py@@ -0,0 +1,98 @@+"""Triton kernels for FastDepth's fused frame body (fused=True).++_add_ln x' = x + a [+ c[b]] with the same rounding order as torch (each add rounded to the depth dtype), stored;+ y = LayerNorm(x') (fp32 statistics, affine), stored. Replaces 2-3 elementwise kernels + a LayerNorm.+_topk_sample per row: logits/temp -> top-k mask -> exponential-race sample (== argmax(p/E), E ~ Exp(1)), i.e. the same+ distribution as the torch path (topk + masked_fill + softmax + exponential_ + div + argmax), one kernel.+ RNG = Philox (tl.rand) keyed by a device-side seed that the captured graph increments every replay.+"""+import torch+import triton+import triton.language as tl+++def _add_ln(X, A, C, XO, Y, W, Bb, eps, T,+ sxb, sxt, sab, sat, scb, sob, sot, syb, syt,+ N: tl.constexpr, HAS_C: tl.constexpr):+ row = tl.program_id(0)+ b = row // T+ t = row % T+ c = tl.arange(0, N)+ dt = XO.dtype.element_ty+ x = (tl.load(X + b * sxb + t * sxt + c).to(tl.float32) + tl.load(A + b * sab + t * sat + c).to(tl.float32)).to(dt)+ if HAS_C:+ x = (x.to(tl.float32) + tl.load(C + b * scb + c).to(tl.float32)).to(dt)+ tl.store(XO + b * sob + t * sot + c, x)+ xf = x.to(tl.float32)+ mean = tl.sum(xf, 0) / N+ d = xf - mean+ var = tl.sum(d * d, 0) / N+ y = d / tl.sqrt(var + eps) * tl.load(W + c).to(tl.float32) + tl.load(Bb + c).to(tl.float32)+ tl.store(Y + b * syb + t * syt + c, y.to(Y.dtype.element_ty))+++def add_ln(x, a, ln, c=None):+ """x, a: [B, T, D] (any strides, last dim contiguous); c: [B, 1, D] or None; ln: nn.LayerNorm(D).+ Returns (x + a [+ c], LayerNorm(...)) as new contiguous tensors."""+ B, T, D = x.shape+ xo = torch.empty(B, T, D, device=x.device, dtype=x.dtype)+ y = torch.empty_like(xo)+ cc = c if c is not None else x+ _add_ln[(B * T,)](x, a, cc, xo, y, ln.weight, ln.bias, ln.eps, T,+ x.stride(0), x.stride(1), a.stride(0), a.stride(1), cc.stride(0), xo.stride(0), xo.stride(1),+ y.stride(0), y.stride(1), N=D, HAS_C=c is not None)+ return xo, y+++def _topk_sample(L, Out, Seed, Ctr, level, inv_temp, s_l, V: tl.constexpr, K: tl.constexpr, GREEDY: tl.constexpr,+ PER_ROW: tl.constexpr):+ row = tl.program_id(0)+ c = tl.arange(0, V)+ x = tl.load(L + row * s_l + c).to(tl.float32) * inv_temp+ xs = tl.sort(x, descending=True)+ kth = tl.sum(tl.where(c == K - 1, xs, 0.0), 0)+ xm = tl.where(x >= kth, x, -float("inf"))+ if GREEDY:+ score = xm+ else:+ if PER_ROW: # per-request stream: seed of this row's request, counter = frames generated by it+ seed = tl.load(Seed + row)+ ctr = tl.load(Ctr + row)+ u = tl.rand(seed, (ctr * 32 + level) * V + c)+ else:+ seed = tl.load(Seed)+ u = tl.rand(seed, (row * 64 + level) * V + c)+ u = tl.maximum(u, 1e-12)+ score = xm - tl.log(-tl.log(u))+ tl.store(Out + row, tl.argmax(score, 0).to(tl.int64))+++def topk_sample(logits, seed_t, level, temp, top_k, greedy=False, ctr_t=None):+ """seed_t [1] (engine-wide stream) or, with ctr_t, per-row seeds [B] and counters [B] (reproducible per request)."""+ B, V = logits.shape+ out = torch.empty(B, device=logits.device, dtype=torch.long)+ per_row = ctr_t is not None+ _topk_sample[(B,)](logits, out, seed_t, ctr_t if per_row else seed_t, level, 1.0 / temp, logits.stride(0), V=V, K=top_k,+ GREEDY=greedy, PER_ROW=per_row)+ return out+++def _row_exponential(Out, Seed, Ctr, level, s_o, V: tl.constexpr, BLOCK: tl.constexpr):+ """Out[row, :V] = Exp(1) noise from the row's own Philox stream (seed, counter): per-request reproducible sampling."""+ row = tl.program_id(0)+ seed = tl.load(Seed + row)+ ctr = tl.load(Ctr + row)+ for start in range(0, V, BLOCK):+ c = start + tl.arange(0, BLOCK)+ u = tl.rand(seed, (ctr * 32 + level) * 4096 + c)+ u = tl.maximum(u, 1e-12)+ tl.store(Out + row * s_o + c, -tl.log(u), mask=c < V)+++def row_exponential(B, V, seeds, ctrs, level=0):+ out = torch.empty(B, V, device=seeds.device, dtype=torch.float32)+ _row_exponential[(B,)](out, seeds, ctrs, level, out.stride(0), V=V, BLOCK=1024)+ return outdiff --git a/tts/__init__.py b/tts/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/tts/data/__init__.py b/tts/data/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/tts/data/packing_v2.py b/tts/data/packing_v2.pynew file mode 100644index 0000000..34bf02e--- /dev/null+++ b/tts/data/packing_v2.py@@ -0,0 +1,343 @@+"""S2 packing — conditioning contract.++One packed row = ONE same-speaker group only (the S1 mode-A fix: unrelated+cuts NEVER share a row, so no attention reset machinery is needed). Four+modes decide the two conditioning channels independently:++ icl_spk (30%): ref utterances in context + ECAPA depth memory+ icl_only ( 5%): ref utterances in context + null memory+ spk_only (55%): no refs in context + ECAPA depth memory+ joint_null (10%): no refs in context + null memory (CFG negative;+ matched dropout — same target units as the conditioned arms)++Layout (lang tag once, on the first span; no <|spk|> slots, no emo slot):+ [ref: <|lang|> text <|audio|> frames AEOS] x R (icl modes; cont forced off)+ [target: (<|cont|>) (<|lang|> if first span) text <|audio|> frames AEOS] x N++Ref frames carry loss (real same-speaker audio; they also feed the ledger).+Throughput comes from token-budget BATCHING of short single-group rows+(TokenBudgetBatcher), not from co-packing strangers.++Span geometry (additive, never changes an existing tensor): collate_v2 also emits+the SPAN GEOMETRY the S3 model needs — where each span's <|audio|> sentinel+sits (the speaker anchor is added there, no new token/position/kind) and which+audio frames are TARGET vs in-context REFERENCE (history corruption touches+target frames only). See `_add_span_geometry`.+"""+import numpy as np+import torch++from ..tokens import AEOS_CLASS, CONTRACT, N_Q++KIND_TEXT, KIND_AUDIO, KIND_AEOS = 0, 1, 3+MODES2 = ("icl_spk", "icl_only", "spk_only", "joint_null")+D_SPK = 192+R_MAX = 3+++class BadUnit(Exception):+ """An ENUMERATED data reject: the only exception+ class a loader worker may skip. Everything else is a defect and fails loud."""++ def __init__(self, reason):+ super().__init__(reason)+ self.reason = reason+++class PackerV2:+ def __init__(self, tokenizer, token_ids, max_tokens=8192, rng=None):+ self.tok = tokenizer+ self.ids = token_ids+ self.max_tokens = max_tokens+ self.rng = rng if rng is not None else np.random.default_rng(0)++ def _span(self, cut, first, cont):+ """Numpy span builder: the original per-token python lists+ ([[-1]*32] per text token, codes.tolist()) dominated the GIL-bound+ loader path. Output is byte-identical to the list version (verified+ by an identity test against it)."""+ head = []+ untrained = 0+ if cont:+ head.append(self.ids[CONTRACT.cont]); untrained += 1+ if first:+ head.append(self.ids[f"<|lang:{cut['lang_final']}|>"])+ untrained += 1+ text = cut["text_final"]+ if not isinstance(text, str) or not text.strip():+ raise BadUnit("empty_text") # explicit bad-text condition+ try:+ head += self.tok(text, add_special_tokens=False)["input_ids"]+ except UnicodeError as e: # the ONLY tokenizer reject+ raise BadUnit("unicode") from e # treated as bad data; any+ # other failure propagates+ head.append(self.ids[CONTRACT.audio])+ n_text = len(head)+ codes = cut["codes"] # (n_q, F) reader-validated+ F_ = codes.shape[1]+ L = n_text + F_ + 1+ t = np.zeros(L, np.int64); t[:n_text] = head+ k = np.zeros(L, np.int8)+ k[n_text:n_text + F_] = KIND_AUDIO; k[-1] = KIND_AEOS+ c = np.full((L, N_Q), -1, np.int64)+ c[n_text:n_text + F_] = codes.T+ c[-1, 0] = AEOS_CLASS+ m = np.ones(L, bool); m[:untrained] = False+ return t, k, c, m++ def build(self, unit, refs, mode):+ """unit: target cut dicts (a chain or a single cut); refs: dict from+ ShardSourceV2.refs_for or None; mode: one of MODES2. Returns example+ dict or None (nothing packed)."""+ use_icl = mode in ("icl_spk", "icl_only")+ use_mem = mode in ("icl_spk", "spk_only") and refs is not None+ # one language per packed row: the single lang+ # tag must name every span in the row+ lang = unit[0]["lang_final"]+ assert all(c["lang_final"] == lang for c in unit), "mixed-lang unit"+ # speaker identity: a packed row is ONE (video, speaker)+ # group by construction (`ShardSourceV2._units` iterates groups), so a+ # unit that is language-homogeneous must be speaker-homogeneous too.+ # Assert it rather than trust it: history corruption picks swap donors+ # by this identity, and a mixed-speaker row would make the donor rule+ # silently wrong. None (a hand-built unit with no identity) is legal+ # and collates to speaker_id = -1 — see collate_v2.+ speaker_key = unit[0].get("speaker_key")+ assert all(c.get("speaker_key") == speaker_key for c in unit), \+ "mixed-speaker unit"+ if use_icl:+ assert all(rc["lang_final"] == lang for rc in refs["cuts"]), \+ "ref language differs from target language"+ spans, ref_rows, total = [], [], 0+ if use_icl:+ for i, rc in enumerate(refs["cuts"]):+ s = self._span(rc, first=(i == 0), cont=False)+ if total + len(s[0]) > self.max_tokens:+ break+ spans.append(s); total += len(s[0])+ ref_rows.append(refs["rows"][i])+ target_start = total # first token of the target spans+ packed_rows, packed = [], 0+ for j, cut in enumerate(unit):+ # <|cont|> only when the actual predecessor is IN the row:+ # unit cuts after the first carry their predecessor by construction+ s = self._span(cut, first=(total == 0),+ cont=(j > 0 and cut.get("cont", False)))+ if total + len(s[0]) > self.max_tokens:+ break # whole-span preflight+ spans.append(s); total += len(s[0])+ packed_rows.append(cut["row"]); packed += 1+ if packed == 0:+ return None+ # examples carry NUMPY (not torch): they cross a multiprocessing+ # queue as plain pickled bytes — torch tensors would ship one shared-+ # memory file descriptor EACH and exhaust the fd limit+ if use_mem:+ embs = np.asarray(refs["embs"], dtype=np.float32)+ else:+ embs = np.zeros((1, D_SPK), np.float32)+ return {+ "tokens": np.concatenate([s[0] for s in spans]),+ "kind": np.concatenate([s[1] for s in spans]),+ "codes": np.concatenate([s[2] for s in spans]),+ "loss_mask": np.concatenate([s[3] for s in spans]),+ "spk_refs": embs,+ "spk_null": not use_mem,+ "mode": mode, "n_cuts": packed,+ "target_rows": packed_rows,+ "ref_rows": ref_rows if use_icl else [],+ "target_start": target_start, # evals score the target span only;+ # training may exclude refs from+ # the depth loss+ "lang": lang, # trained-language telemetry+ # identity carried to collate_v2 -> batch["speaker_id"], the+ # donor constraint of tts/model/corrupt.py span_swap. None when the+ # source did not supply one.+ "speaker_key": speaker_key,+ # stable per-row ids of the TARGET cuts that actually fit, for the+ # paired-arm order digest+ "sample_keys": [c.get("sample_key") for c in unit[:packed]],+ }+++def collate_v2(examples, q_choices=(8, 16, 24, 32), q_rng=None, pad_id=0):+ """Variable-B batch of one-group rows. q_rng MUST be the rank-shared+ lockstep generator (FSDP reduce-scatter shape contract — S1 lesson).+ Text-replay examples (no spk keys) collate as null-memory rows."""+ q_rng = q_rng if q_rng is not None else np.random.default_rng(0)+ B = len(examples)+ T = max(e["tokens"].shape[0] for e in examples)+ out = {+ "tokens": torch.full((B, T), pad_id, dtype=torch.long),+ "kind": torch.full((B, T), KIND_TEXT, dtype=torch.int8),+ "codes": torch.full((B, T, N_Q), -1, dtype=torch.long),+ "loss_mask": torch.zeros(B, T, dtype=torch.bool),+ "attention_mask": torch.zeros(B, T, dtype=torch.long),+ "spk_refs": torch.zeros(B, R_MAX, D_SPK),+ "spk_ref_mask": torch.zeros(B, R_MAX, dtype=torch.bool),+ "spk_null": torch.ones(B, dtype=torch.bool),+ "q_use": torch.tensor(int(q_rng.choice(q_choices))),+ "modes": [e.get("mode", "text") for e in examples],+ "langs": [e.get("lang", "text") for e in examples],+ # per-ROW speaker identity as a dense+ # BATCH-LOCAL id, -1 = unknown (text-replay rows, and any example whose+ # source did not carry a `speaker_key`). Only equality within the batch+ # matters — tts/model/corrupt.py uses it to keep a span_swap donor off+ # the row's OWN speaker, and a same-speaker donor leaves the history+ # acoustics intact, i.e. does not break the acoustic-copy shortcut at all.+ # -1 never matches -1 there: unknown is not "same speaker".+ "speaker_id": _speaker_ids(examples),+ # first TARGET position per row (0 for non-ICL rows and text rows)+ "target_start": torch.tensor([int(e.get("target_start", 0))+ for e in examples], dtype=torch.long),+ "credited_s": torch.tensor([float(e.get("credited_s", 0.0))+ for e in examples]),+ }+ for b, e in enumerate(examples):+ L = e["tokens"].shape[0]+ # examples may carry numpy (audio path, mp-queue-friendly) or torch+ # (text replay) — as_tensor handles both without copying torch inputs+ out["tokens"][b, :L] = torch.as_tensor(e["tokens"])+ out["kind"][b, :L] = torch.as_tensor(e["kind"])+ out["codes"][b, :L] = torch.as_tensor(e["codes"])+ out["loss_mask"][b, :L] = torch.as_tensor(e["loss_mask"])+ out["attention_mask"][b, :L] = 1+ r = e.get("spk_refs")+ if r is not None and not bool(e.get("spk_null", True)):+ R = r.shape[0]+ out["spk_refs"][b, :R] = torch.as_tensor(r)+ out["spk_ref_mask"][b, :R] = True # zero-pad + mask: padding+ out["spk_null"][b] = False # never absorbs attention+ _add_span_geometry(out) # additive span geometry+ return out+++def _speaker_ids(examples):+ """(B,) long tensor of batch-local speaker ids; -1 where unknown.++ Ids are assigned in first-appearance order, so the tensor is a pure+ function of the example list (no RNG, no global state) and two ranks that+ see the same rows produce the same ids."""+ seen, ids = {}, []+ for e in examples:+ key = e.get("speaker_key")+ ids.append(-1 if key is None else seen.setdefault(key, len(seen)))+ return torch.tensor(ids, dtype=torch.long)+++def _add_span_geometry(out):+ """Add per-span <|audio|> sentinel positions + per-position+ target/reference/row/span ids to an already-collated batch.++ WHY derived here instead of emitted by PackerV2.build: only the batch knows+ the padded (B, T) geometry, and text-replay examples never pass through+ build() — deriving from `kind` is ONE code path for every example source and+ leaves every pre-existing tensor byte-identical (proved by+ tests/test_anchor_corrupt.py::test_collate_byte_identical_to_baseline).++ Layout invariant relied on (`PackerV2._span` above): a span is+ [ ...text..., <|audio|>, F audio frames, AEOS ], so a MAXIMAL run of+ KIND_AUDIO positions is exactly one span's frames, and the position right+ before the run holds that span's <|audio|> sentinel. A frame is a TARGET+ frame iff its column >= the row's `target_start` — the same rule the model+ already uses to keep refs out of the depth loss (tts_model_v2.py:62-68).++ Added keys (S = number of audio spans in the batch, may be 0):+ span_batch_row (S,) long batch row b of the span+ span_start (S,) long column of the span's FIRST audio frame+ span_len (S,) long number of audio frames in the span+ span_sentinel (S,) long column of the span's <|audio|> token+ span_is_target (S,) bool False = in-context reference span+ frame_span_id (B,T) long global span id at audio frames, -1 elsewhere+ frame_batch_row (B,T) long b at audio frames, -1 elsewhere+ frame_target_mask(B,T) bool audio frame of a TARGET span+ frame_ref_mask (B,T) bool audio frame of a REFERENCE span+ """+ if "target_start" not in out:+ raise ValueError("span geometry needs `target_start` (the first TARGET "+ "column of every row); collate_v2 always sets it, a "+ "hand-built batch must too")+ aud = out["kind"] == KIND_AUDIO+ B, T = aud.shape+ dev = aud.device # every derived tensor stays on the+ # batch's device: serving builds its+ # prompt batches straight on the GPU+ prv = torch.zeros_like(aud); prv[:, 1:] = aud[:, :-1]+ nxt = torch.zeros_like(aud); nxt[:, :-1] = aud[:, 1:]+ starts, ends = aud & ~prv, aud & ~nxt+ rows_s, pos_s = starts.nonzero(as_tuple=True) # row-major -> pairs 1:1+ rows_e, pos_e = ends.nonzero(as_tuple=True) # with the run ends+ # the 1:1 pairing is what makes span_len correct for the SECOND and later+ # span of a row; assert it instead of trusting it silently (multi-span+ # rows are where a mispairing would go unnoticed)+ if not torch.equal(rows_s, rows_e):+ raise ValueError("audio run starts and ends do not pair up row-wise — "+ "packer layout violated")+ if pos_s.numel() and int(pos_s.min()) == 0:+ raise ValueError("an audio run starts at column 0 — no <|audio|> "+ "sentinel precedes it; packer layout violated")+ pos = torch.arange(T, device=dev)[None, :]+ is_tgt = pos >= out["target_start"].to(dev)[:, None] # (B, T)+ # global span id at every audio position: count span starts up to here+ sid = (starts.reshape(-1).long().cumsum(0).view(B, T) - 1)+ rid = torch.arange(B, device=dev)[:, None].expand(B, T)+ out["span_batch_row"] = rows_s+ out["span_start"] = pos_s+ out["span_len"] = pos_e - pos_s + 1+ out["span_sentinel"] = pos_s - 1+ out["span_is_target"] = is_tgt[rows_s, pos_s]+ out["frame_span_id"] = torch.where(aud, sid, torch.full_like(sid, -1))+ out["frame_batch_row"] = torch.where(aud, rid, torch.full_like(rid, -1))+ out["frame_target_mask"] = aud & is_tgt+ out["frame_ref_mask"] = aud & ~is_tgt+ return out+++class TokenBudgetBatcher:+ """Pool -> length-sort -> token-budget batches that cover EVERY pooled row+ -> shuffled emission. Padded size B*max_len stays under pack_tokens, B+ under max_rows.++ Replaces the reservoir that re-sorted after every refill and emitted only+ down to n//2 rows: on an infinite source that kept the ~n/2 shortest rows+ back until an even shorter row displaced them (credited-but-untrained+ sink) and emitted every cycle long->short.+ Here every pooled row is emitted before the next pool is read; batch+ order inside a pool is shuffled so consecutive updates are not+ length/mode-correlated. Within-batch padding is unchanged (batches are+ contiguous length ranges of a sorted pool)."""++ def __init__(self, gen, pack_tokens=13000, max_rows=48, reservoir=64,+ stats=None, rng=None):+ self.gen = gen+ self.budget = pack_tokens+ self.max_rows = max_rows+ self.n = reservoir+ self.stats = stats if stats is not None else {}+ self.rng = rng if rng is not None else np.random.default_rng(0)++ def _batches(self, pool):+ pool.sort(key=lambda e: e["tokens"].shape[0], reverse=True)+ out, i = [], 0+ while i < len(pool):+ top = pool[i]["tokens"].shape[0]+ take = max(1, min(self.max_rows, len(pool) - i,+ self.budget // max(1, top)))+ out.append(pool[i:i + take])+ i += take+ self.rng.shuffle(out) # in-place list shuffle+ self.stats["pools"] = self.stats.get("pools", 0) + 1+ self.stats["rows"] = self.stats.get("rows", 0) + len(pool)+ return out++ def __iter__(self):+ pool = []+ for ex in self.gen:+ pool.append(ex)+ if len(pool) >= self.n:+ for b in self._batches(pool):+ yield b+ pool = []+ if pool: # finite source (tests): drain+ for b in self._batches(pool):+ yield bdiff --git a/tts/model/__init__.py b/tts/model/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/tts/model/anchors.py b/tts/model/anchors.pynew file mode 100644index 0000000..1714977--- /dev/null+++ b/tts/model/anchors.py@@ -0,0 +1,119 @@+"""The backbone-side SPEAKER ANCHOR.++WHY: in S2 the speaker reaches the DEPTH stack only, so the backbone predicts+cb0 with no idea who is speaking — measured, spk_only cb0 NLL equals joint_null+exactly. This module injects one speaker vector into the+BACKBONE at a position that already exists: the span's `<|audio|>` sentinel.+No new token, no new position, no KIND_SPK — the frozen+50-token contract and the packed geometry are untouched.++WHY the final layer is zero-initialised: S3 warm-starts from a trained S2+checkpoint. A zero output layer makes the step-0+forward bit-identical to S2's, so the warm restart cannot damage the model+before the anchor has learned anything.++WHY a learned null INPUT (not a zero input): rows with no usable speaker+embedding (joint_null / icl_only / text replay) and rows whose anchor is+dropped must still traverse the same MLP, so the null case is a point the+network can place anywhere in input space instead of a hard-coded origin —+the same trick DepthV2 uses for its speaker memory (depth_v2.py:103).+"""+import torch+from torch import nn++D_SPK_ECAPA = 192 # ECAPA embedding width carried by collate_v2+++class SpeakerAnchor(nn.Module):+ """2-layer MLP: mean-pooled ECAPA-192 -> d_model, ZERO-INIT output layer.++ `d_model` is first because it has no sensible default (the natural spelling+ `SpeakerAnchor(input_dim=192, d_model, ...)` is not valid Python);+ every caller passes keywords, so the names are what matter.++ dropout_p is the PER-ROW anchor dropout probability (20% by default,+ independent of the depth memory's dropout) — it is deliberately NOT an+ nn.Dropout inside the MLP: dropping the whole anchor for a row is what+ teaches the backbone to work without one, and it must stay independent of+ DepthV2's null_mask so the two conditioning channels can be ablated apart.+ """++ def __init__(self, d_model, input_dim=D_SPK_ECAPA, hidden=512,+ dropout_p=0.20):+ super().__init__()+ self.input_dim, self.dropout_p = int(input_dim), float(dropout_p)+ self.fc1 = nn.Linear(input_dim, hidden)+ self.fc2 = nn.Linear(hidden, d_model)+ self.null_vec = nn.Parameter(torch.zeros(input_dim))+ nn.init.normal_(self.null_vec, std=0.02)+ nn.init.zeros_(self.fc2.weight) # zero-init OUTPUT layer:+ nn.init.zeros_(self.fc2.bias) # step-0 forward == S2's++ def pool(self, refs, ref_mask=None):+ """Mean-pool a row's reference embeddings -> (B, input_dim), in fp32.++ The batch carries ONE `spk_refs` block per ROW, not per span+ (packing_v2.py:120-128 stores `refs["embs"]` on the example; collate_v2+ pads it to (B, R_MAX, 192) with `spk_ref_mask`), so every span of a row+ receives the SAME anchor vector. Padding rows are excluded by the mask+ instead of being averaged in as zeros.++ The POOLING ARITHMETIC stays fp32 (a masked mean of up to 3 vectors is+ cheap and bf16 would round the divisor); `forward` casts the result to+ the LINEAR's parameter dtype before fc1 — see the dtype note there.+ """+ refs = refs[..., :self.input_dim].float()+ if ref_mask is None:+ return refs.mean(1)+ m = ref_mask[..., None].to(refs.dtype)+ return (refs * m).sum(1) / m.sum(1).clamp(min=1.0)++ def forward(self, refs, ref_mask=None, null_mask=None, gen=None):+ """refs (B, R, >=input_dim); ref_mask (B, R) bool True = real ref;+ null_mask (B,) bool True = row has no speaker embedding. Returns+ (B, d_model), zero at init.++ `gen` is the optional torch.Generator for the row-dropout draw, and it+ is not a convenience: without it the draw comes out+ of the GLOBAL torch stream, and because it happens inside+ compose_inputs — i.e. BEFORE TTSModelV2.forward's depth-frame randperm+ — an arm with an anchor selects different frames from an arm without+ one on the very same batch. The driver passes a tagged per-rank,+ per-update generator (scripts/s3_train.py:tagged_generator, TAG_ANCHOR)+ so the two streams are independent and the causal arms stay paired.+ Must live on the same device as the draw; `u` is moved to the pooled+ device afterwards so a CPU generator still works in tests."""+ pooled = self.pool(refs, ref_mask)+ B = pooled.shape[0]+ use_null = torch.zeros(B, dtype=torch.bool, device=pooled.device)+ if null_mask is not None:+ use_null |= null_mask.to(pooled.device)+ if ref_mask is not None:+ use_null |= ref_mask.sum(1) == 0 # nothing to pool+ if self.training and self.dropout_p > 0:+ # per-ROW dropout; ranks may drop different rows (that is fine —+ # the parameter SET touched per step is what FSDP2 needs to match,+ # and sym_term() below guarantees it)+ u = torch.rand(B, generator=gen,+ device=gen.device if gen is not None else pooled.device)+ use_null |= (u.to(pooled.device) < self.dropout_p)+ x = torch.where(use_null[:, None], self.null_vec.to(pooled.dtype)[None, :],+ pooled)+ # DTYPE: under FSDP2 mixed precision the+ # root-owned parameters are all-gathered as bf16 while `spk_refs` stays+ # fp32, so an fp32 `x` into a bf16 fc1 aborts the very first forward+ # with "mat1 and mat2 must have the same dtype". Take the dtype FROM the+ # weight (not from a config flag) so the module is correct in fp32 CPU+ # tests, in bf16 training and in fp16 alike.+ x = x.to(self.fc1.weight.dtype)+ return self.fc2(nn.functional.gelu(self.fc1(x)))++ def sym_term(self):+ """FSDP2 gradient symmetry (the same anchor+ DepthV2.forward:191-197 carries): a parameter whose use is+ data-dependent must be pulled into the graph on EVERY step of EVERY+ rank or the reduce-scatter sets diverge. `null_vec` is used only when+ some row is null/dropped, and NO anchor parameter is used at all on a+ batch with no audio spans (text replay) — so the caller adds this+ exactly-zero scalar to its output unconditionally."""+ return 0.0 * sum(p.sum() for p in self.parameters())diff --git a/tts/model/audio_io.py b/tts/model/audio_io.pynew file mode 100644index 0000000..8b890e8--- /dev/null+++ b/tts/model/audio_io.py@@ -0,0 +1,38 @@+"""Backbone-side audio input embeddings — SEPARATE from the depth decoder's table.++Why separate: the depth table lives at depth d_model+and inside the depth FSDP group; reusing it for backbone inputs both breaks width+and reaches a sharded parameter without its all-gather hook. This module is owned+by the TTSModel root, at backbone width, with one extra learned row for the+position AFTER an audio span ends (the <aeos> input — class 2048 exists only as a+cb0 TARGET; as an INPUT it is this dedicated vector, never an embedding lookup).+"""+import math+import torch+import torch.nn as nn++from ..tokens import N_Q, N_CODES, AEOS_CLASS+++class AudioInputEmbed(nn.Module):+ def __init__(self, d_backbone, n_q=N_Q, n_codes=N_CODES):+ super().__init__()+ self.n_q, self.n_codes = n_q, n_codes+ self.table = nn.Embedding(n_q * n_codes, d_backbone)+ self.aeos_in = nn.Parameter(torch.zeros(d_backbone))+ self.norm = nn.RMSNorm(d_backbone)+ nn.init.normal_(self.table.weight, std=0.02)+ nn.init.normal_(self.aeos_in, std=0.02)++ def frames(self, codes, q_use):+ """codes (N, n_q) in [0, n_codes); use first q_use levels (level-dropout+ Q is sampled BEFORE the backbone sees the frame)."""+ if torch.any((codes[:, :q_use] < 0) | (codes[:, :q_use] >= self.n_codes)):+ raise ValueError("audio code outside [0, n_codes) reached the input "+ "table — reader validation failed upstream")+ lvl = torch.arange(q_use, device=codes.device)+ e = self.table(codes[:, :q_use] + lvl * self.n_codes)+ return self.norm(e.sum(1) / math.sqrt(q_use))++ def aeos(self, n):+ return self.norm(self.aeos_in)[None, :].expand(n, -1)diff --git a/tts/model/backbone.py b/tts/model/backbone.pynew file mode 100644index 0000000..ba14fc7--- /dev/null+++ b/tts/model/backbone.py@@ -0,0 +1,98 @@+"""Backbone wrapper: a HF causal LM consumed as a 12.5 Hz sequence model.++Candidate backbones load through the same wrapper so comparing them is a+config switch, not a code fork:+ qwen: Qwen/Qwen3-4B-Base (Apache-2.0, full attention)++The wrapper owns three things the raw LM doesn't have:+- vocab extension for the token contract (resize + mean-init of new rows);+- an input-composition layer: text positions use the LM's embedding table,+ audio positions use the depth decoder's summed-code feedback vector, the+ speaker slot uses the conditioning projector's output — all merged into one+ (B, T, d) inputs_embeds tensor (audio never enters the text vocab);+- the cb0 head: n_codes+1 classes (class 2048 = <aeos>), separate from lm_head.+"""+import torch+import torch.nn as nn+from transformers import AutoModelForCausalLM, AutoTokenizer++from ..tokens import CONTRACT, N_CODES, AEOS_CLASS, extend_tokenizer++BACKBONES = {+ "qwen": "Qwen/Qwen3-4B-Base",+ "llama": "meta-llama/Llama-3.2-3B",+}+++def _from_config(path):+ import glob, os+ if os.environ.get("MAYA3_BACKBONE_FROM_CONFIG") == "1":+ return True+ return os.path.isdir(path) and not glob.glob(os.path.join(path, "*.safetensors")) and not glob.glob(os.path.join(path, "*.bin"))+++def _lm_from_config(path, dtype, attn):+ from transformers import AutoConfig+ cfg = AutoConfig.from_pretrained(path)+ with torch.device("meta"):+ lm = AutoModelForCausalLM.from_config(cfg, dtype=dtype, attn_implementation=attn)+ lm = lm.to_empty(device="cpu")+ for m in lm.modules(): # non-persistent buffers (RoPE inv_freq) were never materialised: recompute them+ if hasattr(m, "inv_freq") and hasattr(m, "rope_type"):+ if getattr(m, "rope_init_fn", None) is not None:+ fn = m.rope_init_fn+ elif m.rope_type == "default":+ fn = m.compute_default_rope_parameters+ else:+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS+ fn = ROPE_INIT_FUNCTIONS[m.rope_type]+ inv, scale = fn(m.config, torch.device("cpu"))+ m.inv_freq = inv+ if hasattr(m, "original_inv_freq"):+ m.original_inv_freq = inv+ if hasattr(m, "attention_scaling"):+ m.attention_scaling = scale+ lm.tie_weights()+ return lm+++class Backbone(nn.Module):+ def __init__(self, name="qwen", dtype=torch.float32, attn="flash_attention_2"):+ # fp32 parameters by default: FSDP2's MixedPrecisionPolicy casts to bf16+ # for compute but the SHARDED source params are what AdamW updates — load+ # them bf16 and there are no fp32 masters.+ super().__init__()+ path = BACKBONES.get(name, name)+ if _from_config(path):+ # inference: every backbone weight comes from the Maya3 checkpoint loaded strictly afterwards, so build the+ # architecture without reading (or even needing) the multi-GB backbone safetensors+ self.lm = _lm_from_config(path, dtype, attn)+ else:+ self.lm = AutoModelForCausalLM.from_pretrained(path, dtype=dtype,+ attn_implementation=attn)+ self.tokenizer = AutoTokenizer.from_pretrained(path)+ self.tokenizer, self.token_ids = extend_tokenizer(self.tokenizer)+ old = self.lm.get_input_embeddings().weight.shape[0]+ if len(self.tokenizer) > old:+ self.lm.resize_token_embeddings(len(self.tokenizer))+ with torch.no_grad():+ emb = self.lm.get_input_embeddings().weight+ emb[old:] = emb[:old].mean(0, keepdim=True) + 0.02 * torch.randn_like(emb[old:])+ self.d_model = self.lm.config.hidden_size+ # cb0 + <aeos>: the only audio-side output the backbone owns+ self.cb0_head = nn.Linear(self.d_model, N_CODES + 1, bias=False)++ def embed_text(self, ids):+ return self.lm.get_input_embeddings()(ids)++ def forward(self, inputs_embeds, attention_mask=None, past_key_values=None,+ use_cache=False):+ out = self.lm.model(inputs_embeds=inputs_embeds, attention_mask=attention_mask,+ past_key_values=past_key_values, use_cache=use_cache)+ return out.last_hidden_state, getattr(out, "past_key_values", None)++ def text_logits(self, hidden):+ return self.lm.lm_head(hidden)++ def cb0_logits(self, hidden):+ return self.cb0_head(hidden)diff --git a/tts/model/chunked_ce.py b/tts/model/chunked_ce.pynew file mode 100644index 0000000..d6d033c--- /dev/null+++ b/tts/model/chunked_ce.py@@ -0,0 +1,88 @@+"""Chunked, recompute-on-backward cross-entropy for the LM head.++THE PROBLEM. The text+replay arm (10% of updates, `data.text_rows` x `data.max_tokens`) sends every+text position through the backbone's 194,548-way LM head at once:+tts/model/tts_model_v2.py materialises `out["text_logits"]` and+tts/train/losses.py then calls `F.cross_entropy(logits.float(), ...)` on it. At+~16,384 positions that is bf16 logits 5.9 GiB + the `.float()` copy 11.9 GiB ++cross_entropy's internal log-softmax 11.9 GiB ~= 30 GiB of transient, of which+the ~11.9 GiB log-softmax is RETAINED until backward. This is very probably+the training memory peak, and therefore the cheapest way to buy 1/4 depth+coverage, larger packs, and selective backbone checkpointing.++THE FIX. Process the positions in row chunks: for each chunk compute its logits,+take the fp32 CE SUM, add it to a running fp32 total, and wrap the chunk in+non-reentrant `torch.utils.checkpoint` so nothing but the (chunk, d) hidden+slice — which is a VIEW of a tensor that was already alive — survives the+forward. Transient falls to 30 GiB / ceil(n/chunk) and the retained log-softmax+to zero; the cost is one extra LM-head matmul per chunk during backward, the+same trade tts/train/loop.py:183-187 already makes for the 28 backbone layers.++WHY THE MATHS IS THE SAME. `reduction="sum"` is additive over rows, and CE is+computed per row: sum_i f(x_i) == sum_chunks sum_{i in chunk} f(x_i) in exact+arithmetic, and in fp32 the two differ only in SUMMATION ORDER (measured below+1e-7 relative in tests/test_chunked_ce.py). Every cast is the one the unchunked+path makes, in the same place: `head(h)` in the module dtype, `.float()`, then+`F.cross_entropy(..., reduction="sum")`. `weight` and `ignore_index` are+forwarded untouched, so a weighted head (the AEOS-weighted cb0 CE,+tts/train/losses.py:97-107) decomposes identically — with `reduction="sum"`+PyTorch returns sum_i w[t_i] * loss_i and applies no weight normalisation, which+is exactly what makes the split legal.++WHY NOT A `nn.Module`. It holds no state. Keeping it a function means the+state_dict, and hence the S2 checkpoint contract, is untouched, and the caller+stays inside `TTSModelV2.forward` so the sharded LM head+is only ever entered through `Module.__call__` while the root module's forward+is live — the FSDP2 rule the audio_io lesson is named after.+"""+import torch+import torch.nn.functional as F+import torch.utils.checkpoint as ckpt+++def chunked_ce_sum(head, hidden, targets, chunk, *, weight=None,+ ignore_index=-100):+ """CE SUM over `hidden` in `chunk`-row pieces. -> () fp32 tensor.++ head callable (rows, d) -> (rows, vocab); the module call whose+ parameters must still receive gradients (e.g.+ `Backbone.text_logits`).+ hidden (N, d) hidden states, model dtype.+ targets (N,) long class indices.+ chunk rows per piece; must be > 0 (0 means "off" and is the+ caller's decision, not this function's).+ weight per-class weights, forwarded to F.cross_entropy unchanged.+ ignore_index forwarded unchanged (default -100, F.cross_entropy's).++ An empty `hidden` returns a 0.0 that is still connected to `head`'s+ parameters ONLY if the caller made it so; it does not fabricate a graph.+ Callers that need gradient symmetry on an empty batch must use their own+ zero term (the pattern in DepthV2.forward), because this function must not+ invent a collective the other ranks do not issue.+ """+ if int(chunk) <= 0:+ raise ValueError(f"chunk must be > 0, got {chunk} (0 = off is the "+ f"caller's branch, not this function's)")+ chunk = int(chunk)+ n = int(hidden.shape[0])+ if targets.shape[0] != n:+ raise ValueError(f"hidden has {n} rows, targets {targets.shape[0]}")++ def _ce(h_chunk, t_chunk):+ return F.cross_entropy(head(h_chunk).float(), t_chunk, weight=weight,+ ignore_index=ignore_index, reduction="sum")++ total = torch.zeros((), dtype=torch.float32, device=hidden.device)+ for i in range(0, n, chunk):+ h_c, t_c = hidden[i:i + chunk], targets[i:i + chunk]+ if torch.is_grad_enabled():+ # preserve_rng_state=False: the chunk is a matmul + CE, with no RNG+ # of any kind, and the default True does a device RNG snapshot per+ # chunk — a host-device sync we would pay ~8x per text update.+ part = ckpt.checkpoint(_ce, h_c, t_c, use_reentrant=False,+ preserve_rng_state=False)+ else:+ part = _ce(h_c, t_c) # eval/no_grad: checkpointing saves nothing+ total = total + part+ return totaldiff --git a/tts/model/corrupt.py b/tts/model/corrupt.pynew file mode 100644index 0000000..eeafd85--- /dev/null+++ b/tts/model/corrupt.py@@ -0,0 +1,422 @@+"""HISTORY CORRUPTION of the backbone's audio input.++WHY: S2 was trained with complete temporal+teacher forcing, so the backbone always saw ground-truth history and learned to+COPY the acoustic condition of that history (level, hiss) into the next frame.+At serving its own imperfect output is the history and the condition snowballs+— the measured drift lives in the COARSE codes, i.e. in what the backbone+reads, not in the deep codebooks. The fix is to corrupt what the backbone reads+as history for TARGET frames while every LABEL stays the clean truth, so the+model must predict the clean next frame from a history it cannot trust.++What is NEVER touched (the correctness contract, tested in+tests/test_anchor_corrupt.py):+ * in-context REFERENCE frames — they are the voice prompt; corrupting them+ would teach the model to ignore the reference;+ * `batch["codes"]` itself — cb0 targets, AEOS targets, depth targets AND the+ depth teacher-forced prefix all read the ORIGINAL tensor+ (tts_model_v2.py forward), so this module returns a CLONE;+ * levels >= q_use (BOTH kinds; the first+ version copied all 32 codebooks on a swap, which `audio_in` happened not to+ read), and levels < first_level for level_noise.++Two corruption kinds, mixed by weight:+ span_swap (.625) a contiguous 1-4 s window of the target span's history is+ replaced by a same-length window of a DONOR span in the+ same batch: same language, same q_use, and — when+ `require_other_speaker` is set — a DIFFERENT SPEAKER.+ Realistic-but-wrong acoustics.++DONOR SPEAKER. The first version required only a+different BATCH ROW and called that "a different speaker group". It is not: a+batch is up to 96 rows drawn from ONE shard, so several rows are routinely the+same (video, speaker) group. A same-speaker donor swaps temporal CONTENT while+leaving the history ACOUSTICS (level, hiss, timbre) exactly as they were — i.e.+it does not break the acoustic-copy shortcut described above, which is the whole+point of the treatment. With `require_other_speaker: true` the donor must have+a KNOWN, DIFFERENT `batch["speaker_id"]`; a row with no eligible donor falls+back to level_noise for that window (it is never left uncorrupted, and never+swapped from its own speaker). Two counts quantify the gap: the realised+same-speaker swap frames, and the frames the unconstrained row-only rule would have taken+from the same speaker in expectation (`swap_same_spk_expected_frames`) — the+measurement of how weak an unconstrained arm's treatment really was.+ level_noise(.375) the same kind of window keeps levels < first_level (8) and+ randomises levels in [first_level, q_use). Coarse structure+ survives, the fine condition does not.++Ramp: the caller passes the current max frame fraction (0 -> 0.30 over 10k+updates). Per span we draw ONE window length W and the NUMBER+of windows k so that E[corrupted target frames] == frac * target frames; the+realised counts come back in `stats` for telemetry.++DEVICE / STALLS. The first version read four GPU+tensors back with `.tolist()`, drew every decision as a python scalar in a loop+over spans and windows, and copied the noise block CPU->GPU inside the step —+several synchronisations plus a host round-trip per update. This version builds+the corrupted tensor ENTIRELY ON THE CODES' DEVICE with fixed-shape vectorised+ops: no `.tolist()`, no `.item()`, no python loop over the batch, no H2D of+generated values, and no data-dependent shape (which would itself sync, because+allocating a masked_select output needs the count on the host). "Corrupt on the+CPU before H2D" was rejected: the loop hands the model a batch that is already+on the GPU (tts/train/loop.py:200), so a CPU build would mean a full D2H+H2D of+`codes` every step.++Consequences of that decision, both REQUIRED of the caller:+ * `gen` must be a torch.Generator ON `batch["codes"].device` (a CUDA+ generator for GPU training: `torch.Generator(device="cuda")`); a CPU+ generator with GPU codes raises here instead of silently syncing.+ * every count in `stats` is a 0-dim int64 tensor on that device, plus a+ stacked 1-D `stats["counts"]` in `stats["count_keys"]` order. Accumulate+ the TENSORS across updates and divide ONCE at logging time+ (Sigma corrupted_frames / Sigma target_frames) — reading them per step with+ float() re-introduces the stall, and AVERAGING per-batch `realised_frac`+ over updates is the wrong estimator (it weights a 2-frame batch like a+ 2000-frame one and counts text-only batches as 0).++Window PLACEMENT is a random-phase tiling: the k windows of a span sit on the+grid `phase + i*W` for k distinct slots i, phase ~ U[0, L - floor(L/W)*W].+That makes windows non-overlapping BY CONSTRUCTION (the first version drew+uniform starts and retried up to 4 times, so overlaps still happened and the+realised fraction sagged), which is what makes E[corrupted] = frac * L exact.+"""+import math+from dataclasses import dataclass++import torch++from ..tokens import FRAME_HZ, N_CODES, N_Q++#: `stats["counts"]` layout — a 1-D int64 tensor the caller can accumulate on+#: device without a sync. FRAME counts are the ones telemetry must divide.+#: New keys are APPENDED, never inserted: scripts/s3_train.py all-reduces this+#: vector by index and its logged names are a run-to-run contract.+COUNT_KEYS = ("target_frames", "corrupted_frames", "swap_frames",+ "noise_frames", "noise_noop_frames", "windows", "swap_draws",+ "noise_draws", "donor_fallbacks",+ # ---- donor speaker constraint, all FRAME-weighted ----+ # swap draws that found NO eligible donor and became level_noise+ # (the window-weighted form of `donor_fallbacks`); these frames+ # are also inside `noise_frames`.+ "swap_fallback_frames",+ # frames REALLY swapped from a donor with the same KNOWN speaker.+ # Identically 0 when require_other_speaker is on — the invariant+ # the fix exists for. Unconstrained, this is exactly how much of+ # the treatment was a no-op.+ "swap_same_spk_frames",+ # frames the UNCONSTRAINED (different-row-only) rule would have+ # taken from the same speaker, in EXPECTATION (donors are drawn+ # uniformly over the eligible set, so this is n_same/n_eligible+ # per window x its length, rounded once per batch). Informational+ # counterfactual; equals swap_same_spk_frames in expectation when+ # the constraint is off.+ "swap_same_spk_expected_frames",+ # frames swapped while NO speaker constraint was in force (knob+ # off, or a batch with no speaker_id at all — old callers)+ "swap_unconstrained_frames")+++@dataclass(frozen=True)+class CorruptConfig:+ """Parsed `history_corruption` config block. `from_dict(None)` and a block with+ `enabled: false` both return None = feature OFF = S2 behaviour."""+ swap_w: float = 0.625+ noise_w: float = 0.375+ dur_lo: float = 1.0 # seconds+ dur_hi: float = 4.0+ first_level: int = 8+ #: span_swap donors must be a DIFFERENT, KNOWN speaker. Default False+ #: = the original behaviour (different batch row only), bit-for-bit.+ require_other_speaker: bool = False++ @classmethod+ def from_dict(cls, d):+ if not d or not d.get("enabled", False):+ return None+ sw = d.get("span_swap") or {}+ nz = d.get("level_noise") or {}+ dur = list(sw.get("duration_s", (1.0, 4.0)))+ c = cls(swap_w=float(sw.get("weight", 0.625)),+ noise_w=float(nz.get("weight", 0.375)),+ dur_lo=float(dur[0]), dur_hi=float(dur[1]),+ first_level=int(nz.get("first_level", 8)),+ require_other_speaker=bool(+ d.get("require_other_speaker", False)))+ if c.swap_w < 0 or c.noise_w < 0 or c.swap_w + c.noise_w <= 0:+ raise ValueError(f"history_corruption weights must be >=0 and sum "+ f">0, got {c.swap_w}/{c.noise_w}")+ if not 0 < c.dur_lo <= c.dur_hi:+ raise ValueError(f"span_swap.duration_s must be 0 < lo <= hi, got {dur}")+ if not 1 <= c.first_level < N_Q:+ raise ValueError(f"level_noise.first_level must be in [1,{N_Q}), "+ f"got {c.first_level}")+ return c++ @property+ def p_swap(self):+ return self.swap_w / (self.swap_w + self.noise_w)+++def _span_geometry(batch, dev):+ """The four (S,) span tensors collate_v2._add_span_geometry emits+ (packing_v2.py), moved to `dev` only if the caller left them elsewhere."""+ need = ("span_batch_row", "span_start", "span_len", "span_is_target")+ if any(k not in batch for k in need):+ raise ValueError("history corruption needs collate_v2's span geometry "+ f"{need} (see packing_v2._add_span_geometry)")+ return tuple(batch[k].to(dev) for k in need)+++def _lang_ids(batch, dev):+ """Per-ROW language id. `batch["langs"]` is a python list of strings (it is+ not a tensor, so tts/train/loop.py:200 leaves it on the host); one small+ B-element H2D per step is the whole cost, and it buys a device-side+ same-language donor test."""+ langs = batch.get("langs")+ if langs is None:+ raise ValueError("history corruption needs batch['langs'] (per-row "+ "language from collate_v2, packing_v2.py:158)")+ seen = {}+ ids = [seen.setdefault(lg, len(seen)) for lg in langs]+ return torch.tensor(ids, dtype=torch.long, device=dev)+++def _speaker_ids(batch, cfg, dev):+ """Per-ROW speaker id, or None when the batch carries no identity.++ `collate_v2` always emits `speaker_id` (packing_v2._speaker_ids); a batch+ that does not have it is an OLD caller (a fixture from before the constraint, a hand-built+ serving batch). Those keep the historical unconstrained donor rule, which+ is why the key is optional — but a config that ASKED for the constraint and+ then silently ran the weak treatment for 300k updates is exactly the defect+ the constraint exists to remove, so that combination is fatal (no silent+ fallbacks)."""+ spk = batch.get("speaker_id")+ if spk is None:+ if cfg.require_other_speaker:+ raise ValueError(+ "history_corruption.require_other_speaker is set but the batch "+ "has no `speaker_id` — collate_v2 emits it from each example's "+ "`speaker_key` (tts/data/packing_v2.py); a hand-built batch "+ "must supply a (B,) long tensor, -1 where the speaker is "+ "unknown")+ return None+ return torch.as_tensor(spk, device=dev).reshape(-1).long()+++def _zero_stats(frac, dev):+ z = torch.zeros(len(COUNT_KEYS), dtype=torch.long, device=dev)+ return _pack_stats(frac, z, dev)+++def _pack_stats(frac, counts, dev):+ st = {"requested_frac": float(frac), "counts": counts,+ "count_keys": COUNT_KEYS}+ st.update({k: counts[i] for i, k in enumerate(COUNT_KEYS)})+ # per-BATCH only; telemetry must use Sigma corrupted / Sigma target instead+ # (module docstring)+ st["realised_frac"] = (counts[1].double()+ / counts[0].clamp(min=1).double())+ return st+++def corrupt_history(batch, cfg, frac, gen=None, trace=False):+ """Return (codes_for_the_backbone_input, stats).++ `codes_for_the_backbone_input` is `batch["codes"]` ITSELF when nothing can+ be corrupted (no clone, no cost) and a clone otherwise — the caller must+ treat it as read-only and keep using `batch["codes"]` for every label.++ frac: current max frame fraction from the ramp (0..0.30). cfg: CorruptConfig+ or None (OFF). gen: torch.Generator on `batch["codes"].device` (see the+ module docstring). trace=True materialises a per-window record for+ fixed-seed tests — it is the ONLY path that syncs, and it is test-only.+ """+ codes = batch["codes"]+ dev = codes.device+ if cfg is None or float(frac) <= 0.0:+ return codes, _zero_stats(frac, dev)+ if gen is not None and gen.device.type != dev.type:+ raise ValueError(+ f"corrupt_history: generator is on {gen.device} but codes are on "+ f"{dev}; pass a per-rank torch.Generator(device='{dev.type}') — "+ "every draw is a device tensor op")++ rows, starts, lens, is_tgt = _span_geometry(batch, dev)+ S = int(rows.shape[0]) # tensor SHAPES never sync+ B, T = int(codes.shape[0]), int(codes.shape[1])+ if S == 0: # text-replay-only batch+ return codes, _zero_stats(frac, dev)+ lang = _lang_ids(batch, dev)[rows] # (S,) language of each span+ spk_row = _speaker_ids(batch, cfg, dev) # (B,) or None+ spk = None if spk_row is None else spk_row[rows] # (S,)+ # python bool fixed by the CONFIG (a missing speaker_id already raised+ # above), so every rank takes the same branch — no data-dependent control+ # flow in the step.+ constrained = bool(cfg.require_other_speaker)+ # q_use stays a TENSOR: turning it into a python int here would sync, and+ # it is only ever needed as a level mask.+ q_use = torch.as_tensor(batch["q_use"], device=dev).reshape(())+ lvl = torch.arange(N_Q, device=dev)+ in_q = lvl < q_use # (N_Q,)+ noise_lvl = in_q[cfg.first_level:] # (N_Q-first_level,)+ lens_f = lens.to(torch.float32)++ # ---- per-span draws: window length W, window count k ------------------+ u = torch.rand(S, generator=gen, device=dev)+ W = torch.round((cfg.dur_lo + (cfg.dur_hi - cfg.dur_lo) * u) * FRAME_HZ)+ W = W.long().clamp(min=1)+ W = torch.minimum(W, lens.clamp(min=1)) # window fits the span+ n_slots = torch.div(lens, W, rounding_mode="floor").clamp(min=1)+ want = frac * lens_f / W.to(torch.float32) # E[k] for E[kW]=fL+ k = want.floor()+ k = k + (torch.rand(S, generator=gen, device=dev) < (want - k)).to(k.dtype)+ k = torch.minimum(k.long(), n_slots)+ k = torch.where(is_tgt, k, torch.zeros_like(k)) # refs are never touched++ # ---- which slots of the random-phase tiling are used ------------------+ # NS bounds floor(L/W) for every span: L <= T and W >= min(W_min, L).+ w_min = max(1, math.floor(cfg.dur_lo * FRAME_HZ))+ NS = max(1, T // w_min)+ slot = torch.arange(NS, device=dev)+ slot_ok = slot[None, :] < n_slots[:, None] # (S, NS)+ key = torch.rand(S, NS, generator=gen, device=dev)+ key = torch.where(slot_ok, key, torch.full_like(key, 2.0))+ rank = torch.argsort(torch.argsort(key, dim=1, stable=True), dim=1)+ chosen = (rank < k[:, None]) & slot_ok+ phase = (torch.rand(S, generator=gen, device=dev)+ * (lens - n_slots * W + 1).to(torch.float32)).long()+ start = starts[:, None] + phase[:, None] + slot[None, :] * W[:, None]++ # ---- kind per window + donor choice -----------------------------------+ want_swap = torch.rand(S, NS, generator=gen, device=dev) < cfg.p_swap+ # donor eligibility is a per-SPAN property (W is per span): a donor must be+ # a different row (= different speaker group), the same language, and at+ # least as long as the window. Same q_use holds by construction — collate_v2+ # draws ONE q per BATCH (packing_v2.py:162).+ elig_row = ((lang[:, None] == lang[None, :])+ & (rows[:, None] != rows[None, :])+ & (lens[None, :] >= W[:, None])) # (S_win, S_donor)+ if spk is None:+ same_spk = None+ else:+ known = spk >= 0+ # -1 is UNKNOWN, not "the unknown speaker": two unknown rows are never+ # certified as the same person, and (under the constraint) never as+ # different people either — an unknown row is simply not a donor.+ same_spk = (spk[:, None] == spk[None, :]) & known[:, None] & known[None, :]+ elig = elig_row+ if constrained:+ elig = elig_row & known[:, None] & known[None, :] & ~same_spk+ n_elig = elig.sum(1)+ has_donor = n_elig > 0+ is_swap = chosen & want_swap & has_donor[:, None]+ fallback = chosen & want_swap & ~has_donor[:, None] # -> becomes noise+ is_noise = chosen & ~is_swap+ # pick the p-th eligible donor without materialising the eligible list:+ # cumsum jumps by 1 exactly at eligible columns, so the first column whose+ # cumsum reaches p+1 IS that donor.+ pick = (torch.rand(S, NS, generator=gen, device=dev)+ * n_elig[:, None].to(torch.float32)).long()+ pick = torch.minimum(pick, (n_elig - 1).clamp(min=0)[:, None])+ donor = torch.searchsorted(elig.long().cumsum(1).contiguous(),+ (pick + 1).contiguous()).clamp(max=S - 1)+ d_room = (lens[donor] - W[:, None] + 1).clamp(min=1).to(torch.float32)+ d_off = (torch.rand(S, NS, generator=gen, device=dev) * d_room).long()+ d_off = torch.minimum(d_off, (lens[donor] - W[:, None]).clamp(min=0))++ # ---- expand windows to frames (fixed shape, invalid entries parked) ----+ Wm = max(1, min(math.ceil(cfg.dur_hi * FRAME_HZ), T))+ off = torch.arange(Wm, device=dev)+ inwin = off[None, None, :] < W[:, None, None] # (S, NS, Wm)+ dst_row = rows[:, None, None].expand(S, NS, Wm)+ dst_col = start[:, :, None] + off+ src_row = rows[donor][:, :, None].expand(S, NS, Wm)+ src_col = (starts[donor] + d_off)[:, :, None] + off+ # column T is a SCRATCH column: every masked-off entry is written there and+ # the helper planes are sliced back to T before use. This is what keeps the+ # shapes static — a boolean select would need its size on the host.+ swap_at = torch.where(inwin & is_swap[:, :, None], dst_col, T)+ noise_at = torch.where(inwin & is_noise[:, :, None], dst_col, T)++ m_swap = torch.zeros(B, T + 1, dtype=torch.bool, device=dev)+ m_swap[dst_row, swap_at] = True+ gr = torch.arange(B, device=dev)[:, None].expand(B, T + 1).clone()+ gc = torch.arange(T + 1, device=dev)[None, :].expand(B, T + 1).clone()+ gr[dst_row, swap_at] = src_row # identity elsewhere+ gc[dst_row, swap_at] = src_col+ m_noise = torch.zeros(B, T + 1, dtype=torch.bool, device=dev)+ m_noise[dst_row, noise_at] = True++ m_swap, m_noise = m_swap[:, :T], m_noise[:, :T]+ gathered = codes[gr[:, :T], gc[:, :T].clamp(max=T - 1)]+ out = torch.where(m_swap[:, :, None] & in_q, gathered, codes)+ seg = out[..., cfg.first_level:]+ noise = torch.randint(0, N_CODES, seg.shape, generator=gen,+ dtype=codes.dtype, device=dev)+ out[..., cfg.first_level:] = torch.where(+ m_noise[:, :, None] & noise_lvl, noise, seg)++ # ---- frame-weighted telemetry (device tensors; see the docstring) ------+ wf = W[:, None]+ swap_frames = (is_swap * wf).sum()+ noise_frames_raw = (is_noise * wf).sum()+ live = noise_lvl.any().long() # 0 iff q_use <= first_level: the+ noise_frames = noise_frames_raw * live # window would write nothing+ # ---- donor-speaker bookkeeping (device only, no RNG: the OFF path is+ # bit-identical to the unconstrained module because nothing here is drawn) ------+ zero = swap_frames * 0+ if same_spk is None:+ swap_same = swap_same_exp = zero+ else:+ # REALISED: the donor actually used, per window+ swap_same = ((is_swap & torch.gather(same_spk, 1, donor)) * wf).sum()+ # COUNTERFACTUAL for the unconstrained rule: donors are uniform over the eligible+ # set, so E[same-speaker frames] = W * n_same_eligible / n_eligible.+ # Computed from `elig_row` (the UNCONSTRAINED matrix) so it is the same+ # number whether or not the constraint is on. Rounded once per batch to+ # keep `counts` a single int64 vector the caller can accumulate.+ n_row = elig_row.sum(1)+ p_same = ((elig_row & same_spk).sum(1).double()+ / n_row.clamp(min=1).double())+ swap_same_exp = (((is_swap * wf).double() * p_same[:, None]).sum()+ .round().long())+ counts = torch.stack([+ (lens * is_tgt).sum(), # target_frames+ swap_frames + noise_frames, # corrupted_frames+ swap_frames, # swap_frames+ noise_frames, # noise_frames+ noise_frames_raw * (1 - live), # noise_noop_frames+ chosen.sum(), # windows+ is_swap.sum(), # swap_draws+ is_noise.sum(), # noise_draws+ fallback.sum(), # donor_fallbacks+ (fallback * wf).sum(), # swap_fallback_frames+ swap_same, # swap_same_spk_frames+ swap_same_exp, # swap_same_spk_expected_frames+ zero if constrained else swap_frames, # swap_unconstrained_frames+ ]).long()+ stats = _pack_stats(frac, counts, dev)+ if trace:+ stats["trace"] = _trace(chosen, is_swap, rows, start, W, donor,+ starts[donor] + d_off)+ return out, stats+++def _trace(chosen, is_swap, rows, start, W, donor, d_start):+ """Per-window records for the fixed-seed determinism test. TEST ONLY: this+ is the one path that copies decisions back to the host."""+ ch = chosen.tolist()+ sw = is_swap.tolist()+ rw, st, wl = rows.tolist(), start.tolist(), W.tolist()+ dn, ds = donor.tolist(), d_start.tolist()+ recs = []+ for j, row in enumerate(ch):+ for i, on in enumerate(row):+ if not on:+ continue+ swap = sw[j][i]+ recs.append({"span": j, "row": rw[j], "start": st[j][i],+ "frames": wl[j], "kind": "swap" if swap else "noise",+ "donor_span": dn[j][i] if swap else None,+ "donor_start": ds[j][i] if swap else None})+ return recsdiff --git a/tts/model/depth_v2.py b/tts/model/depth_v2.pynew file mode 100644index 0000000..bfba007--- /dev/null+++ b/tts/model/depth_v2.py@@ -0,0 +1,618 @@+"""Depth transformer (DepthV2): predicts codebook levels 1..31 of each frame.++Geometry: 4 layers x 1024 x 16 heads, FFN 3072 (GELU). Eleven weight GROUPS:+levels 1-8 each get a PRIVATE trunk; levels 9-16, 17-24, 25-31 share three+band trunks. Speaker conditioning enters HERE ONLY: each reference embedding+(CAM++-1024 or ECAPA-192, mutually exclusive per example) is projected by a+source-specific Linear to one 1024-d K/V memory token; every layer carries a+cross-attention over that memory, SHARED across groups (the reconcile budget:+~560M all-in including the speaker path). Per-level code embeddings are+rank-128 factorized; 31 independent 1024->2048 heads.++Level indexing follows depth.py: level 0 (cb0) is the backbone's; this module+generates levels 1..31 (or 1..q-1 under level-dropout).++Null conditioning (matched joint dropout, 10%): spk_mem is replaced by a+learned null token — the SAME code path, so CFG at inference is just a second+forward with the null memory.++GROUPED teacher-forced forward (OPT-IN): a prefix position is+embedded from its SLOT alone (see _prefix) and the trunk self-attention is+causal, so within one weight group a single pass over the group's longest+prefix already contains, at position L, the state the level-L pass would+produce at its last position. Levels 9-16 / 17-24 / 25-31 share groups+8/9/10, so those three bands collapse to one pass each: 118 positions per+frame instead of 527 at q=32.++The maths is equivalent but the KERNEL ORDER is not, so the grouped logits+are NOT bit-for-bit the loop's: measured max |dlogit| 1.9e-06 in fp32,+i.e. equality only within GROUPED_FP32_ATOL. It is therefore OPT-IN —+`grouped` defaults to False, so the default forward is S2's per-level loop+kernel for kernel, and the control configuration and the zero-init+warm-start equivalence check are bitwise S2. Enable it per configuration+(config key `model.depth_grouped` -> DepthV2(..., grouped=True)) only after+that configuration has passed a short bf16 tolerance test (2 GPUs,+q16/q24/q32, GROUPED_BF16_SMOKE_ATOL).+"""+import functools+import math++import torch+import torch.nn as nn++from ..tokens import N_Q, N_CODES++GROUP_OF_LEVEL = [None] + [i for i in range(8)] + [8] * 8 + [9] * 8 + [10] * 7+N_GROUPS = 11+D, H, FFN, LAYERS = 1024, 16, 3072, 4+RANK = 128+# Selective activation checkpointing: checkpoint levels >= this during+# training (levels 1-8 have short prefixes and run direct; see _forward_loop).+# NOT an environment variable any more: the value is a per-RUN recipe+# knob, so it belongs in the closed config schema as `model.depth_ckpt_from`+# and in the dumped <run_dir>/config.yaml, not in whatever the launcher+# happened to export. scripts/s3_train.py REFUSES to start if the old+# `S2_CKPT_FROM` is still exported (a silent env override of a config key+# is exactly what this refusal prevents).+CKPT_FROM = 9 # loop-path default = S2, bitwise+GROUPED_CKPT_FROM = 1 # grouped-path default: see default_ckpt_from()++# Tolerances of record for the grouped path. The grouped and the+# loop path compute the same function in a DIFFERENT KERNEL ORDER, so they+# agree to floating point, never bitwise: measured max |dlogit| 1.88e-06 in+# fp32 at q32 against a logit scale of 2.65.+# The tests assert allclose(atol=GROUPED_FP32_ATOL) — ~5x headroom over that+# measurement — and torch.equal ONLY against the default (loop) path.+GROUPED_FP32_ATOL = 1e-5+# Pre-registered gate for turning grouped=True on for a training config: in+# TRAINING bf16 on 2 GPUs, grouped vs loop at q16/q24/q32 within+# atol=rtol=GROUPED_BF16_SMOKE_ATOL and a depth-loss delta below+# GROUPED_BF16_LOSS_DELTA. Provisional — to be tightened from a measurement+# before a full-scale run.+GROUPED_BF16_SMOKE_ATOL = 2e-2+GROUPED_BF16_LOSS_DELTA = 1e-3+++def _check_ckpt_from(v):+ """Validate an explicit `ckpt_from` (1..31). 1 = checkpoint every level."""+ v = int(v)+ if not 1 <= v <= N_Q - 1:+ raise ValueError(f"ckpt_from={v}: must be 1..{N_Q - 1} (1 = every "+ f"level checkpointed, {N_Q - 1} = only the last)")+ return v+++def default_ckpt_from(grouped: bool) -> int:+ """Effective selective-checkpoint threshold when the config names none.++ LOOP path -> CKPT_FROM (9), which is S2 bit-for-bit: levels 1-8 run direct+ and 9-31 recompute.++ GROUPED path -> 1, i.e. every group pass is checkpointed. WHY the default+ differs: the grouped schedule keeps the eight private levels 1-8 as+ 44 of its 118 positions, and at threshold 9 those are the ONLY positions+ whose activations are stored — so grouped saves trunk FLOPs but almost no+ activation memory (~6.9 vs the loop's ~7.4 GiB at 1/16 coverage, estimated).+ Checkpointing every pass drops that to ~3.0 GiB for +9% depth FLOPs, which+ is the memory training needs to afford 1/8 and 1/4 depth coverage. An+ explicit `model.depth_ckpt_from` overrides this in either mode.+ """+ return GROUPED_CKPT_FROM if grouped else CKPT_FROM+++def sample_codes(logits, temp=1.0, top_k=0):+ """Draw one code per row from `logits` (N, n_codes) -> (N,) long.++ WHY it exists: serving samples the depth+ stack at temp 0.7 with top-k 64 (generate() below), while S2's roll-in+ sampled the FULL softmax at temp 1 — so the corrupted inputs roll-in fed+ the model were drawn from a distribution it never meets at serve time.+ One helper now spells the rule for the roll-in path.++ The defaults are S2 bit-for-bit: `p / 1.0` is the identity in IEEE-754+ and `top_k=0` skips the mask, leaving exactly+ torch.multinomial(logits.detach().float().softmax(-1), 1).squeeze(-1).+ """+ p = logits.detach().float()+ if temp != 1.0:+ p = p / temp+ if top_k:+ kth = p.topk(min(int(top_k), p.shape[-1]), -1).values[:, -1:]+ p = p.masked_fill(p < kth, -float("inf"))+ return torch.multinomial(p.softmax(-1), 1).squeeze(-1)+++def group_schedule(q):+ """Passes for levels 1..q-1 as ((group, (levels...)), ...), ascending.++ Levels 1-8 own groups 0-7, so each is its own pass (prefix lengths 2..9).+ Levels 9-16, 17-24 and 25-31 share groups 8, 9 and 10, so each band is ONE+ pass over its deepest prefix (lengths 17 / 25 / 32, clipped by q_eff).+ Cached: the schedule depends only on q, and q takes 3 values in training.+ """+ buckets = {}+ for level in range(1, q):+ buckets.setdefault(GROUP_OF_LEVEL[level], []).append(level)+ for g, lv in buckets.items():+ if lv != list(range(lv[0], lv[-1] + 1)):+ raise ValueError(+ f"GROUP_OF_LEVEL group {g} is not one contiguous run of "+ f"levels ({lv}) — the shared pass would be wrong")+ return tuple((g, tuple(lv)) for g, lv in buckets.items())+++class _SelfBlock(nn.Module):+ """One private-trunk layer: causal self-attn + GELU FFN (pre-norm)."""++ def __init__(self):+ super().__init__()+ self.n1, self.n2 = nn.LayerNorm(D), nn.LayerNorm(D)+ self.qkv = nn.Linear(D, 3 * D, bias=False)+ self.o = nn.Linear(D, D, bias=False)+ self.f1, self.f2 = nn.Linear(D, FFN, bias=False), nn.Linear(FFN, D, bias=False)++ def forward(self, x, mask):+ B, T, _ = x.shape+ q, k, v = self.qkv(self.n1(x)).chunk(3, -1)++ def sh(t):+ return t.view(B, T, H, D // H).transpose(1, 2)+ a = nn.functional.scaled_dot_product_attention(sh(q), sh(k), sh(v),+ attn_mask=mask)+ x = x + self.o(a.transpose(1, 2).reshape(B, T, D))+ return x + self.f2(nn.functional.gelu(self.f1(self.n2(x))))+++class _CrossBlock(nn.Module):+ """Speaker cross-attention, shared across groups at one layer index.+ kmask (B, S) bool, True = real reference token (padding excluded:+ repeat-padding would double a ref's attention mass)."""++ def __init__(self):+ super().__init__()+ self.n = nn.LayerNorm(D)+ self.q = nn.Linear(D, D, bias=False)+ self.kv = nn.Linear(D, 2 * D, bias=False)+ self.o = nn.Linear(D, D, bias=False)++ def forward(self, x, mem, kmask=None):+ B, T, _ = x.shape+ S = mem.shape[1]+ q = self.q(self.n(x)).view(B, T, H, D // H).transpose(1, 2)+ k, v = self.kv(mem).chunk(2, -1)+ k = k.view(B, S, H, D // H).transpose(1, 2)+ v = v.view(B, S, H, D // H).transpose(1, 2)+ am = kmask[:, None, None, :] if kmask is not None else None+ a = nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=am)+ return x + self.o(a.transpose(1, 2).reshape(B, T, D))+++class DepthV2(nn.Module):+ def __init__(self, d_backbone=2048, n_q=N_Q, n_codes=N_CODES,+ grouped: bool = False, ckpt_from: int | None = None):+ """grouped: the DEFAULT path taken by forward() when its per-call+ `grouped` kwarg is None. False = S2's per-level loop, kernel for+ kernel (the strict S2 equivalence check needs a bitwise S2 default);+ True = the grouped passes, which agree only to+ GROUPED_FP32_ATOL. Wired from config key `model.depth_grouped`+ (default false) by TTSModelV2. Deliberately a PLAIN attribute, not a+ buffer: the state_dict — and hence the S2 checkpoint contract — is+ unchanged, and the flag is a property of the RUN, not of the weights.++ ckpt_from: selective activation-checkpointing threshold, 1..31 (levels+ >= it recompute during training). None = default_ckpt_from(grouped) —+ 9 on the loop path (S2 bitwise), 1 on the grouped path (the memory+ lever). Wired from config key `model.depth_ckpt_from`; also a+ plain attribute, and also a property of the RUN, not of the weights.+ """+ super().__init__()+ self.grouped = bool(grouped)+ # Selective-checkpoint threshold, per RUN (config `model.depth_ckpt_from`).+ # None = the mode's default: see default_ckpt_from(). Like+ # `grouped` this is a plain attribute — it must not enter state_dict.+ self.ckpt_from = default_ckpt_from(self.grouped) if ckpt_from is None \+ else _check_ckpt_from(ckpt_from)+ self.n_q, self.n_codes = n_q, n_codes+ self.in_proj = nn.Linear(d_backbone, D, bias=False)+ # factorized per-level code embeddings: (codes -> rank) private per+ # level, (rank -> D) shared+ self.code_lo = nn.Embedding((n_q - 1) * n_codes, RANK)+ self.code_up = nn.Linear(RANK, D, bias=False)+ self.level_emb = nn.Embedding(n_q, D)+ # 11 private trunks x 4 layers; cross-attn shared across groups per layer+ self.groups = nn.ModuleList(+ nn.ModuleList(_SelfBlock() for _ in range(LAYERS))+ for _ in range(N_GROUPS))+ self.cross = nn.ModuleList(_CrossBlock() for _ in range(LAYERS))+ self.norm = nn.LayerNorm(D)+ self.heads = nn.ModuleList(+ nn.Linear(D, n_codes, bias=False) for _ in range(n_q - 1))+ # speaker memory: source-specific projections + learned null token+ self.spk_proj_campp = nn.Linear(1024, D, bias=False)+ self.spk_proj_ecapa = nn.Linear(192, D, bias=False)+ self.null_mem = nn.Parameter(torch.zeros(1, 1, D))+ nn.init.normal_(self.null_mem, std=0.02)+ nn.init.normal_(self.code_lo.weight, std=0.02)+ nn.init.normal_(self.level_emb.weight, std=0.02)++ def spk_memory(self, refs, source, null_mask=None):+ """refs: (B, R, dim) L2-normalized reference embeddings (dim 1024 for+ 'campp', 192 for 'ecapa'); source: str or (B,) list of str;+ null_mask: (B,) bool — replace that row's memory with the null token+ (matched joint dropout / CFG negative). Returns (B, R, D)."""+ B, R, _ = refs.shape+ if isinstance(source, str):+ proj = self.spk_proj_campp if source == "campp" else self.spk_proj_ecapa+ mem = proj(refs)+ else:+ mem = torch.zeros(B, R, D, dtype=refs.dtype, device=refs.device)+ for i, s in enumerate(source):+ proj = self.spk_proj_campp if s == "campp" else self.spk_proj_ecapa+ mem[i] = proj(refs[i, :, : proj.in_features])+ if null_mask is not None and null_mask.any():+ mem[null_mask] = self.null_mem.to(mem.dtype).expand(-1, R, -1)+ return mem++ def _prefix(self, h_frame, codes_prev, level):+ """Embedded prefix for predicting `level`: [proj(h)+lvl0] ++ [emb(cb_k, slot k) + lvl_{k+1} for k=0..level-1] -> (B, level+1, D).+ codes_prev columns are cb0..cb30 — cb0 IS in the within-frame+ factorization; generate() builds the identical+ prefix from the sampled cb0 + its own sampled deeper codes."""+ parts = [self.in_proj(h_frame)[:, None] + self.level_emb.weight[:1]]+ ks = torch.arange(level, device=h_frame.device)+ flat = codes_prev[:, :level] + ks * self.n_codes+ e = self.code_up(self.code_lo(flat)) + self.level_emb(ks + 1)[None]+ parts.append(e)+ return torch.cat(parts, 1)++ def _trunk(self, x, group, mem, kmask=None):+ """One group's 4 causal self-attn layers interleaved with the 4 SHARED+ speaker cross-attn layers, over the whole prefix; all positions, unnormed."""+ T = x.shape[1]+ mask = torch.ones(T, T, dtype=torch.bool, device=x.device).tril()[None, None]+ for li in range(LAYERS):+ x = self.groups[group][li](x, mask)+ x = self.cross[li](x, mem, kmask)+ return x++ def _run(self, x, group, mem, kmask=None):+ """Last position only — the per-level path and generate() use this."""+ return self.norm(self._trunk(x, group, mem, kmask)[:, -1])++ def _run_at(self, x, group, mem, kmask=None, take=(-1,)):+ """Same trunk, read out at several positions -> (B, len(take), D).++ WHY this is exact: _prefix embeds position k from slot k+ alone — never from the level being predicted — and the self-attention+ is causal, so position L of a length-(L'+1) prefix (L <= L') sees the+ same tokens under the same weights as the level-L pass sees at ITS+ last position. Every layer after that (cross-attn over the speaker+ memory, FFN, LayerNorm) is position-wise. `take` is a plain tuple so+ torch.utils.checkpoint passes it through untouched.+ """+ return self.norm(self._trunk(x, group, mem, kmask)[:, list(take)])++ def _forward_loop(self, h_frames, inputs, spk_mem, ref_mask, q,+ rollin_mask=None, rollin_temp=1.0, rollin_top_k=0):+ """S2's per-level path: 31 passes over prefixes 2..32 = 527 positions.++ Kept (a) as the reference implementation the grouped path is tested+ against and (b) as the ONLY path for roll-in rows: such a row's+ level-L input is SAMPLED from this same forward's level-(L-1) logits,+ so its prefix does not exist until the previous level has run and the+ band passes cannot be shared. `inputs` is mutated in place for roll-in+ rows — every caller hands over a clone.+ """+ out = []+ for level in range(1, q):+ x = self._prefix(h_frames, inputs, level)+ if (self.training and torch.is_grad_enabled()+ and level >= self.ckpt_from):+ # selective activation checkpointing:+ # the un-checkpointed 31-level loop held ~25GB and OOM'd the+ # first launch; levels 1-8 (short prefixes) stay direct —+ # 35/80 GB peak leaves the headroom — and levels 9-31+ # recompute, cutting the recompute tax on the cheap levels+ h = torch.utils.checkpoint.checkpoint(+ self._run, x, GROUP_OF_LEVEL[level], spk_mem, ref_mask,+ use_reentrant=False)+ else:+ h = self._run(x, GROUP_OF_LEVEL[level], spk_mem, ref_mask)+ logits = self.heads[level - 1](h)+ out.append(logits)+ if rollin_mask is not None and level < q - 1:+ # roll-in replaces cb1.. only; column 0 is substituted once,+ # before the loop, from rollin_cb0 if the caller sampled it+ with torch.no_grad():+ samp = sample_codes(logits, rollin_temp, rollin_top_k)+ inputs[rollin_mask, level] = samp[rollin_mask]+ return out++ def _forward_grouped(self, h_frames, inputs, spk_mem, ref_mask, q):+ """One causal pass per weight GROUP instead of one per level.++ COST MODEL — positions processed per frame, summed over passes:+ loop sum_{L=1..q-1} (L+1) = 527 (q32) 299 (q24) 135 (q16)+ grouped (2+..+9) + 17 + 25 + 32 = 118 (q32) 85 (q24) 60 (q16)+ i.e. 22.4% of the trunk work at q32 for identical outputs. The saving+ is trunk-only: the 31 head matmuls and the prefix embeddings are+ unchanged, and the grouped path builds ONE prefix per group instead of+ one per level (11 instead of 31 at q32).+ """+ out = [None] * (q - 1)+ for g, lv in group_schedule(q):+ x = self._prefix(h_frames, inputs, lv[-1])+ if (self.training and torch.is_grad_enabled()+ and lv[-1] >= self.ckpt_from):+ # SAME threshold convention, applied per PASS: a pass is+ # checkpointed iff any level it serves would have been (its+ # deepest level lv[-1] is the test). At the LOOP default+ # ckpt_from=9 that is exactly the three shared bands, which+ # are also the memory-heavy passes (prefixes 17/25/32 held+ # for 4 self- + 4 cross-attn layers); the eight private+ # levels 1-8 stay direct, as in S2 — which is why the GROUPED+ # default is ckpt_from=1: with 9, those 44 of 118+ # positions are the entire activation bill and the grouped+ # path saves trunk FLOPs but almost no memory.+ hs = torch.utils.checkpoint.checkpoint(+ self._run_at, x, g, spk_mem, ref_mask, lv,+ use_reentrant=False)+ else:+ hs = self._run_at(x, g, spk_mem, ref_mask, lv)+ for j, level in enumerate(lv):+ out[level - 1] = self.heads[level - 1](hs[:, j])+ return out++ def _forward_split(self, h_frames, inputs, spk_mem, ref_mask, q,+ rollin_mask, rollin_temp, rollin_top_k, sample=True):+ """Mixed batch: roll-in rows take the sequential loop, the rest take+ the group passes; the two results are re-merged row-wise.++ `sample=False` (set by forward() when the caller supplied+ `rollin_codes`) means the roll-in inputs are already in `inputs` and+ must NOT be re-drawn. The rows still take the sequential loop, so the+ split/merge machinery is exercised exactly as in a real training step —+ only the draw is gone.++ COST MODEL with a roll-in row fraction r at q32:+ r*527 + (1-r)*118 positions, vs 527 for the pure loop. The training+ recipe ramps roll-in to 0.30 of the depth frames, so the+ steady state is ~0.30*527 + 0.70*118 = 241 positions = 46% of S2.+ The extra cost of splitting is one more prefix build and two+ index_copy per level; both are O(N*D), negligible against a trunk+ pass. Row order is preserved by index_copy on sorted index vectors.+ """+ ridx = rollin_mask.nonzero(as_tuple=True)[0]+ nidx = (~rollin_mask).nonzero(as_tuple=True)[0]+ r_out = self._forward_loop(+ h_frames[ridx], inputs[ridx], spk_mem[ridx],+ None if ref_mask is None else ref_mask[ridx], q,+ rollin_mask.new_ones(ridx.numel()) if sample else None,+ rollin_temp, rollin_top_k)+ if nidx.numel() == 0:+ return r_out # ridx == arange(N): order kept+ n_out = self._forward_grouped(+ h_frames[nidx], inputs[nidx], spk_mem[nidx],+ None if ref_mask is None else ref_mask[nidx], q)+ n_rows = h_frames.shape[0]+ return [a.new_zeros(n_rows, a.shape[-1])+ .index_copy(0, nidx, a).index_copy(0, ridx, b)+ for a, b in zip(n_out, r_out)]++ def forward(self, h_frames, targets, refs=None, null_mask=None, q_eff=None,+ rollin_mask=None, source="ecapa", spk_mem=None, ref_mask=None,+ grouped=None, rollin_temp=1.0, rollin_top_k=0, rollin_cb0=None,+ rollin_codes=None):+ """Training (teacher-forced). h_frames (N, d_backbone); targets+ (N, n_q) ground-truth codes incl. level 0; refs (N, R, dim) reference+ embeddings projected HERE (inside Module.__call__, so FSDP2's+ all-gather hook covers the speaker projections); null_mask (N,) bool.+ rollin_mask (N,) bool: those frames read STOP-GRADIENT sampled codes+ (from this forward's own logits) instead of teacher codes at levels+ >=2 — scheduled sampling for the depth stack (roll-in).+ q_eff: level-dropout Q. Returns list of logits per level 1..q_eff-1+ (each (N, n_codes)) — same contract as depth.py. Loss targets are+ ALWAYS the true codes; roll-in only corrupts inputs.++ S3 kwargs (all default to S2 behaviour bit-for-bit):+ grouped: None (default) = use the module attribute `self.grouped`,+ set from the constructor kwarg / config key `model.depth_grouped`+ and FALSE unless that configuration opted in. True runs one causal+ pass per weight group instead of one per level: equivalent+ maths, different KERNEL ORDER, hence equal to the loop only within+ GROUPED_FP32_ATOL (1.9e-06 measured in fp32) — which is why it is+ opt-in and why the equivalence check runs the default.+ The per-call kwarg overrides the attribute and exists so the tests+ (and a bf16 tolerance test) can drive both paths on one module. See _run_at+ for WHY it is exact in exact arithmetic and+ _forward_grouped/_forward_split for the cost model.+ rollin_temp / rollin_top_k: sampling rule for the roll-in inputs+ Serving uses 0.7 / 64; S2 roll-in used 1.0 / 0,+ which is the default here so nothing moves until a caller asks.+ rollin_cb0 (N,) long or None: for rows in rollin_mask, the level-1+ INPUT (prefix slot 0, and hence every deeper prefix of that row —+ exactly what generate() does with its own sampled cb0) uses this+ code instead of the true cb0. The caller (tts_model_v2) samples it+ from the backbone's cb0 logits for the selected frames. TARGETS+ NEVER CHANGE: the loss still scores against the true codes. Codes+ must be valid cb0 classes; AEOS/invalid must be resolved by the+ caller, same contract as generate().+ rollin_codes (N, n_q) long or None: TEACHER-FORCED roll-in. When+ given, the roll-in rows read columns 1..q-2 of this tensor as their+ level inputs and NOTHING is sampled inside this forward; column 0 is+ untouched (it stays governed by rollin_cb0 / the true cb0) and+ columns >= q-1 are never read as inputs at all. Default None = the+ sampled roll-in, bitwise: the only added work is one Python `is not None` test.++ WHY IT EXISTS (found in a bf16 test run). The loop path draws its roll-in+ samples over the FULL batch and _forward_split draws them over the+ roll-in SUB-batch, so the two consume different RNG and, in bf16,+ different reduction tilings flip near-tie argmaxes: the sampled codes+ diverge and the paths stop computing the same function. Measured on a+ checkpoint at update 84000: `noroll` is EXACT at every q while the roll-in case reaches+ max |dlogit| ~10-19 purely from that divergence. Injecting the loop's+ own draws makes both paths see identical inputs at every level, which+ is the only way the grouped/split machinery can be gated on the+ roll-in path at all. TARGETS ARE NEVER TOUCHED — the loss still+ scores against the true codes.+ """+ if grouped is None:+ grouped = self.grouped # config default; see __init__+ q = q_eff or self.n_q+ if spk_mem is None:+ spk_mem = self.spk_memory(refs, source, null_mask)+ if ref_mask is not None and null_mask is not None:+ # null rows attend over all R copies of the null token+ ref_mask = ref_mask | null_mask[:, None]+ inputs = targets # columns cb0..cb31; :31 consumed+ roll = rollin_mask is not None and bool(rollin_mask.any())+ if roll:+ inputs = inputs.clone()+ if rollin_cb0 is not None:+ if rollin_cb0.shape != (h_frames.shape[0],):+ raise ValueError(+ f"rollin_cb0 must be ({h_frames.shape[0]},), got "+ f"{tuple(rollin_cb0.shape)}")+ sub = rollin_cb0[rollin_mask]+ if bool(((sub < 0) | (sub >= self.n_codes)).any()):+ raise ValueError(+ "rollin_cb0 carries aeos/invalid cb0 classes; the "+ "caller must resolve them (as generate() requires)")+ inputs[rollin_mask, 0] = sub.to(inputs.dtype)+ force = rollin_codes is not None+ if force:+ if not roll:+ raise ValueError(+ "rollin_codes needs a rollin_mask with at least one row: "+ "there is nothing to force otherwise")+ if rollin_codes.shape != (h_frames.shape[0], self.n_q):+ raise ValueError(+ f"rollin_codes must be ({h_frames.shape[0]}, {self.n_q}), "+ f"got {tuple(rollin_codes.shape)}")+ hi = max(1, q - 1) # columns 1..q-2 are what sampling writes+ sub = rollin_codes[rollin_mask, 1:hi]+ if sub.numel() and bool(((sub < 0) | (sub >= self.n_codes)).any()):+ raise ValueError(+ "rollin_codes carries aeos/invalid classes; the caller "+ "must resolve them (as rollin_cb0 requires)")+ inputs[rollin_mask, 1:hi] = sub.to(inputs.dtype)+ if not grouped:+ out = self._forward_loop(h_frames, inputs, spk_mem, ref_mask, q,+ rollin_mask if (roll and not force) else None,+ rollin_temp, rollin_top_k)+ elif roll:+ out = self._forward_split(h_frames, inputs, spk_mem, ref_mask, q,+ rollin_mask, rollin_temp, rollin_top_k,+ sample=not force)+ else:+ out = self._forward_grouped(h_frames, inputs, spk_mem, ref_mask, q)+ # gradient-symmetry anchor: params whose use varies with the batch+ # (null token on null rows; the dormant CAM++ projection; the ECAPA+ # projection when every row is null) must produce grads on EVERY rank+ # every audio step, or FSDP2's reduce-scatter set diverges (S1 lesson)+ anchor = 0.0 * (self.null_mem.sum() + self.spk_proj_campp.weight.sum()+ + self.spk_proj_ecapa.weight.sum())+ out[0] = out[0] + anchor.to(out[0].dtype)+ return out++ @torch.inference_mode()+ def generate(self, h_frame, cb0, spk_mem, q_serve=None, temp=0.7,+ top_k=64, cfg_scale=0.0, null_mem=None, ref_mask=None):+ """Serve one frame. cfg_scale>0 applies depth-logit CFG:+ logits = null + scale*(cond - null) (depth only, not+ cb0). null_mem defaults to the learned null token. The prefix uses+ the SAMPLED cb0 + this frame's own sampled deeper codes — identical+ construction to teacher forcing."""+ from ..tokens import AEOS_CLASS+ if torch.any(cb0 >= AEOS_CLASS) or torch.any(cb0 < 0):+ raise ValueError("aeos/invalid cb0 must be handled by the caller")+ q = q_serve or self.n_q+ B = h_frame.shape[0]+ if cfg_scale > 0 and null_mem is None:+ null_mem = self.null_mem.to(spk_mem.dtype).expand(B, spk_mem.shape[1], -1)+ outs = [cb0]+ for level in range(1, q):+ codes_prev = torch.stack(outs, 1) # cb0..cb_{l-1}+ x = self._prefix(h_frame, codes_prev, level)+ h = self._run(x, GROUP_OF_LEVEL[level], spk_mem, ref_mask)+ logits = self.heads[level - 1](h).float()+ if cfg_scale > 0:+ hn = self._run(x, GROUP_OF_LEVEL[level], null_mem)+ ln = self.heads[level - 1](hn).float()+ logits = ln + cfg_scale * (logits - ln)+ logits = logits / temp+ if top_k:+ kth = logits.topk(top_k, -1).values[:, -1:]+ logits = logits.masked_fill(logits < kth, -float("inf"))+ outs.append(torch.multinomial(logits.softmax(-1), 1).squeeze(-1))+ return torch.stack(outs, -1) # (B, q)+++if __name__ == "__main__":+ m = DepthV2()+ n = sum(p.numel() for p in m.parameters())+ parts = {+ "group_trunks": sum(p.numel() for p in m.groups.parameters()),+ "cross": sum(p.numel() for p in m.cross.parameters()),+ "heads": sum(p.numel() for p in m.heads.parameters()),+ "code_emb": m.code_lo.weight.numel() + m.code_up.weight.numel(),+ "spk_path": (m.spk_proj_campp.weight.numel()+ + m.spk_proj_ecapa.weight.numel() + m.null_mem.numel()),+ }+ print({k: f"{v/1e6:.1f}M" for k, v in parts.items()}, f"TOTAL {n/1e6:.1f}M")+ B = 3+ h = torch.randn(B, 2048)+ tgt = torch.randint(0, 2048, (B, 32))+ refs = torch.nn.functional.normalize(torch.randn(B, 3, 1024), dim=-1)+ outs = m(h, tgt, refs=refs, source="campp",+ null_mask=torch.tensor([False, True, False]), q_eff=16)+ assert len(outs) == 15 and outs[0].shape == (B, 2048)+ er = torch.nn.functional.normalize(torch.randn(B, 3, 192), dim=-1)+ outs = m(h, tgt, refs=er, null_mask=torch.zeros(B, dtype=torch.bool),+ q_eff=16, rollin_mask=torch.tensor([True, False, True]),+ ref_mask=torch.tensor([[1, 1, 0], [1, 1, 1], [1, 0, 0]]).bool())+ assert len(outs) == 15+ (sum(o.float().pow(2).mean() for o in outs)).backward()+ for nm in ("null_mem", "spk_proj_campp.weight", "spk_proj_ecapa.weight"):+ g = dict(m.named_parameters())[nm].grad+ assert g is not None, f"symmetry anchor failed for {nm}"+ # acceptance: cb0 must steer level-1; cb_k steers level k+1 but never+ # levels <= k (within-frame causality)+ with torch.no_grad():+ nm = torch.zeros(B, dtype=torch.bool)+ o1 = m(h, tgt, refs=er, null_mask=nm, q_eff=8)+ t2 = tgt.clone(); t2[:, 0] = (t2[:, 0] + 7) % 2048+ o2 = m(h, t2, refs=er, null_mask=nm, q_eff=8)+ assert not torch.allclose(o1[0], o2[0]), "cb0 does not reach level 1"+ t3 = tgt.clone(); t3[:, 2] = (t3[:, 2] + 7) % 2048+ o3 = m(h, t3, refs=er, null_mask=nm, q_eff=8)+ assert torch.allclose(o1[0], o3[0]) and torch.allclose(o1[1], o3[1]), \+ "cb2 leaked into levels <= 2"+ assert not torch.allclose(o1[2], o3[2]), "cb2 does not reach level 3"+ # the grouped path reproduces the per-level loop to+ # GROUPED_FP32_ATOL (NOT bitwise — kernel order differs), and the DEFAULT+ # path is the loop itself, bit for bit+ assert m.grouped is False, "grouped must default to OFF"+ with torch.no_grad():+ nm = torch.zeros(B, dtype=torch.bool)+ for qq in (16, 24, 32):+ og = m(h, tgt, refs=er, null_mask=nm, q_eff=qq, grouped=True)+ ol = m(h, tgt, refs=er, null_mask=nm, q_eff=qq, grouped=False)+ dflt = m(h, tgt, refs=er, null_mask=nm, q_eff=qq)+ assert all(torch.allclose(a, b, atol=GROUPED_FP32_ATOL)+ for a, b in zip(og, ol)), f"grouped != loop at q={qq}"+ assert all(torch.equal(a, b) for a, b in zip(dflt, ol)), \+ f"the default forward is not the S2 loop at q={qq}"+ # teacher-forced vs generation prefix identity for a fixed code sequence+ cp = tgt[:1, :5]+ x_tf = m._prefix(h[:1], cp, 5)+ x_gen = m._prefix(h[:1], torch.stack([cp[:, j] for j in range(5)], 1), 5)+ assert torch.equal(x_tf, x_gen), "teacher/gen prefix construction differs"+ g = m.generate(torch.randn(1, 2048), torch.tensor([7]),+ m.spk_memory(torch.nn.functional.normalize(+ torch.randn(1, 2, 192), dim=-1), "ecapa"),+ q_serve=16, cfg_scale=2.0)+ assert g.shape == (1, 16)+ print("depth_v2 self-test OK")diff --git a/tts/model/load_s3.py b/tts/model/load_s3.pynew file mode 100644index 0000000..f6f8d82--- /dev/null+++ b/tts/model/load_s3.py@@ -0,0 +1,488 @@+"""The ONE checkpoint loader every eval/serving script uses.++WHY this module exists: a loader that builds an anchor-free `TTSModelV2`, asks DCP for exactly+the tensors that model happens to have, and throws the rest away will, pointed at an S3+checkpoint, load a *different model* — the speaker anchor is silently dropped — while printing+nothing. Every comparison made through such a path is invalid, and nothing in the output+says so. This module makes the two failure modes impossible:++ * the checkpoint carries `speaker_anchor.*` tensors and the constructed model has no+ anchor -> RuntimeError, never a quiet anchor-free eval;+ * the constructed model has an anchor and the checkpoint has none -> RuntimeError;+ * any other missing/unexpected/mis-shaped model tensor -> RuntimeError.++It also keeps working for an S2 baseline checkpoint (no anchor keys, S2 config), because S2+and S3 checkpoints MUST evaluate through the same code path or the comparison is between two+loaders as much as between two checkpoints.++Accepted checkpoint sources:+ <run>/ckpt/<7-digit>/ DCP training checkpoint (`__k_0.distcp` + `extra.pt`),+ tts/train/loop.py:54 `save_ckpt`+ <dir>/model.pt or a .pt file flat model-only export from+ scripts/s3_warmstart_extract.py (keys `model.<name>`,+ `provenance.json` beside it)+ <dir>/model.safetensors release export from maya3/tools/convert_to_safetensors.py:+ <dir>/model.safetensors.index.json one file or index-sharded, keys WITHOUT the `model.`+ prefix, tied tensors stored once (aliases in the metadata),+ `maya3_config.json` beside it (the resolved model config,+ used when no explicit `config=` is given)++Model kwargs (which anchor, which backbone) are resolved in this order, and the answer is+reported in the provenance dict so a log line always says what was built:+ 1. `config=` an explicit --model-config path (the operator overrides everything);+ 2. `<run>/config.yaml` the run's own resolved config, if the trainer wrote one next to the+ checkpoint (not every trainer writes one; the lookup is here+ so it works whenever one is present);+ 3. `cfg=` the eval config the script already loads (--config).+`model.backbone`/`model.attn` are ALWAYS taken from the caller's eval config when it has them:+an eval machine usually points the backbone at a local path in its own eval config, so a run+config's absolute training path would not exist there. Everything else (the anchor block) comes+from the resolution above, and is cross-checked against the checkpoint's own tensor shapes.++Training-only knobs are forced OFF for evaluation: `history_corruption` (it rewrites the+backbone's input history — a serving prompt must never be corrupted) and `depth_grad_scale`+(a gradient-only knob; its forward is the identity, tts_model_v2.py:208-211).++`model.depth_grouped` is NOT such a knob and is reconstructed from the run's config. It selects+DepthV2's grouped teacher-forced forward, which is a+CONSTRUCTOR decision (depth_v2.py:158) and only agrees with the per-level loop to+GROUPED_FP32_ATOL — so scoring a checkpoint trained with `depth_grouped: true` through the loop+measures a slightly different function than the one that was trained. It matters ONLY for+TEACHER-FORCED evaluation — the depth NLL / cb0 NLL numbers, e.g. clean-history+scoring, which goes through `TTSModelV2.forward` — because `DepthV2.generate()` has no grouped+path at all (it is autoregressive over levels by construction, depth_v2.py `generate`), so a+free-running/serving run is bit-identical either way. The flag is reported in the provenance+dict and therefore in the `CKPT_LOADED` line, which is the line to check+before reading any number.+"""+import json+import os++import torch++MODEL_PREFIX = "model."+ANCHOR_PREFIX = "speaker_anchor."+# nearest-first search for the run's resolved config, relative to the checkpoint dir:+# <ckpt>/, <ckpt>/../ (= <run>/ckpt/), <ckpt>/../../ (= <run>/, the documented home)+RUN_CONFIG_NAMES = ("config.yaml", "config.resolved.yaml")+RUN_CONFIG_DEPTH = 3+# 1-D per-span tables and (B, T) per-frame maps added by packing_v2._add_span_geometry+SPAN_KEYS = ("span_batch_row", "span_start", "span_len", "span_sentinel",+ "span_is_target")+FRAME_KEYS = ("frame_span_id", "frame_batch_row", "frame_target_mask",+ "frame_ref_mask")+++# --------------------------------------------------------------------- checkpoint inspection+def _dcp_dir(path):+ """True if `path` is a directory holding DCP shards (`*.distcp`)."""+ return os.path.isdir(path) and any(f.endswith(".distcp")+ for f in os.listdir(path))+++def _flat_path(path):+ """The flat model-only export at `path`, or None."""+ if os.path.isfile(path) and path.endswith(".pt"):+ return path+ cand = os.path.join(path, "model.pt")+ return cand if os.path.isfile(cand) else None+++# ------------------------------------------------------------------ safetensors release format+SAFETENSORS_NAME = "model.safetensors"+SAFETENSORS_INDEX = "model.safetensors.index.json"+RELEASE_CONFIG = "maya3_config.json"+ALIASES_KEY = "maya3_aliases" # metadata entry: json {alias name: stored name} for tied tensors+++def _safetensors_files(path):+ """(release dir, [shard files], aliases) for a safetensors release export at `path`, or None.+ `path` is the release dir, its `model.safetensors`, or its `model.safetensors.index.json`."""+ d = path if os.path.isdir(path) else os.path.dirname(path)+ if os.path.isfile(path) and not path.endswith((".safetensors", ".safetensors.index.json")):+ return None+ index = os.path.join(d, SAFETENSORS_INDEX)+ single = os.path.join(d, SAFETENSORS_NAME)+ if os.path.isfile(index):+ with open(index) as fh:+ idx = json.load(fh)+ files = sorted(set(idx["weight_map"].values()))+ meta = idx.get("metadata") or {}+ aliases = meta.get(ALIASES_KEY) or {}+ if isinstance(aliases, str):+ aliases = json.loads(aliases)+ return d, [os.path.join(d, f) for f in files], dict(aliases)+ if os.path.isfile(single):+ from safetensors import safe_open+ with safe_open(single, framework="pt") as fh:+ meta = fh.metadata() or {}+ return d, [single], dict(json.loads(meta.get(ALIASES_KEY, "{}")))+ return None+++def _load_safetensors(st):+ """Flat `model.<name>` state dict from a safetensors release export (CPU; dtypes as stored).+ Aliased (tied) names point at the SAME tensor object as their stored name, as torch.load+ would give for a tied flat export."""+ from safetensors.torch import load_file+ _, files, aliases = st+ sd = {}+ for f in files:+ part = load_file(f, device="cpu")+ dup = set(part) & set(sd)+ if dup:+ raise RuntimeError(f"tensor(s) stored in more than one shard: {sorted(dup)[:4]}")+ sd.update(part)+ for alias, target in aliases.items():+ if alias in sd:+ raise RuntimeError(f"aliased tensor {alias} is also stored")+ if target not in sd:+ raise RuntimeError(f"alias {alias} -> {target}: target not in the export")+ sd[alias] = sd[target]+ return {MODEL_PREFIX + k: v for k, v in sd.items()}+++def _release_config_path(path):+ """`maya3_config.json` of a safetensors release export at `path`, or None."""+ if not os.path.exists(path) or _dcp_dir(path) or _flat_path(path) is not None:+ return None # DCP / flat .pt keep their own resolution+ st = _safetensors_files(path)+ if st is None:+ return None+ p = os.path.join(st[0], RELEASE_CONFIG)+ return p if os.path.isfile(p) else None+++def _inspect(path):+ """(kind, shapes, payload). `payload` is the loaded flat state dict for a `.pt` export+ (loaded ONCE — the file is ~9 GiB) and None for DCP, whose tensor bytes are not touched+ until the model exists."""+ if _dcp_dir(path):+ from torch.distributed.checkpoint import FileSystemReader+ from torch.distributed.checkpoint.metadata import TensorStorageMetadata+ md = FileSystemReader(path).read_metadata().state_dict_metadata+ shapes = {}+ for k, m in md.items():+ if not k.startswith(MODEL_PREFIX):+ continue # optim.* etc: not our business+ if not isinstance(m, TensorStorageMetadata):+ raise TypeError(f"non-tensor entry under model.* in {path}: "+ f"{k} ({type(m).__name__})")+ shapes[k[len(MODEL_PREFIX):]] = torch.Size(m.size)+ if not shapes:+ raise ValueError(f"no {MODEL_PREFIX}* tensors in DCP checkpoint {path}")+ return "dcp", shapes, None+ flat = _flat_path(path)+ if flat is None:+ st = _safetensors_files(path)+ if st is not None:+ sd = _load_safetensors(st)+ return "safetensors", {k[len(MODEL_PREFIX):]: v.shape for k, v in sd.items()}, sd+ raise FileNotFoundError(+ f"{path} is neither a DCP checkpoint dir (*.distcp), a flat "+ f"model export (*.pt / <dir>/model.pt) nor a safetensors release export "+ f"(<dir>/{SAFETENSORS_NAME} or <dir>/{SAFETENSORS_INDEX})")+ sd = torch.load(flat, map_location="cpu", weights_only=True)+ bad = [k for k in sd if not k.startswith(MODEL_PREFIX)]+ if bad:+ raise RuntimeError(+ f"{flat} holds non-model keys ({bad[:4]}) — a flat warm-start export "+ f"carries `model.*` tensors only (scripts/s3_warmstart_extract.py)")+ return "flat", {k[len(MODEL_PREFIX):]: v.shape for k, v in sd.items()}, sd+++def checkpoint_shapes(path):+ """(kind, {tensor name without `model.` -> torch.Size}) for a checkpoint.++ DCP reads METADATA only (no tensor bytes), so the anchor decision can be made before the+ 2.90B-parameter model is constructed (measured on an S2 checkpoint: 727 tensors,+ 2,899,683,328 params, namespaces backbone/depth/audio_in only)."""+ kind, shapes, _ = _inspect(path)+ return kind, shapes+++def checkpoint_update(path):+ """Update number of the checkpoint, or None. DCP: the 7-digit directory name, which+ loop.py:55 writes and commits LATEST for last, so it is authoritative (s3_warmstart_extract+ .read_update cross-checks it against extra.pt at bank time). Flat: provenance.json's+ source_update."""+ base = os.path.basename(os.path.normpath(path))+ if len(base) == 7 and base.isdigit():+ return int(base)+ flat = _flat_path(path) if not _dcp_dir(path) else None+ if flat is None and not _dcp_dir(path):+ rc = _release_config_path(path)+ if rc is not None:+ with open(rc) as fh:+ return (json.load(fh).get("source") or {}).get("update")+ if flat is not None:+ prov = os.path.join(os.path.dirname(os.path.abspath(flat)),+ "provenance.json")+ if os.path.isfile(prov):+ with open(prov) as fh:+ return json.load(fh).get("source_update")+ return None+++def anchor_cfg_from_shapes(shapes):+ """Derive the SpeakerAnchor constructor kwargs from the checkpoint's own tensors, or None.++ The tensors define the module exactly — `fc1.weight` is (hidden, input_dim) — so a+ checkpoint can always be loaded correctly even where no config survived. `dropout` is+ training-only (anchors.py:80 guards on self.training) and irrelevant under .eval().+ """+ w = shapes.get(ANCHOR_PREFIX + "fc1.weight")+ if w is None:+ return None+ if len(w) != 2:+ raise RuntimeError(f"{ANCHOR_PREFIX}fc1.weight has shape {tuple(w)}, expected 2-D")+ return {"enabled": True, "hidden": int(w[0]), "input_dim": int(w[1])}+++# ------------------------------------------------------------------------- config resolution+def find_run_config(ckpt_dir):+ """The run's resolved config next to a checkpoint, or None (nearest first)."""+ d = os.path.abspath(ckpt_dir if os.path.isdir(ckpt_dir)+ else os.path.dirname(ckpt_dir))+ for _ in range(RUN_CONFIG_DEPTH):+ for name in RUN_CONFIG_NAMES:+ p = os.path.join(d, name)+ if os.path.isfile(p):+ return p+ parent = os.path.dirname(d)+ if parent == d:+ break+ d = parent+ return None+++def _load_yaml(path):+ import yaml+ with open(path) as fh:+ return yaml.safe_load(fh)+++def resolve_model_cfg(ckpt_dir, cfg=None, config=None):+ """-> (model_cfg dict, source string). See the module docstring for the precedence."""+ if config is not None:+ mc = config if isinstance(config, dict) else _load_yaml(config)+ src = "override" if isinstance(config, dict) else f"override:{config}"+ return dict(mc.get("model", mc)), src+ rel = _release_config_path(ckpt_dir)+ if rel is not None:+ # a safetensors release export carries its own resolved config; a relative+ # `backbone` is relative to the release dir (`backbone/` in the HF repo layout)+ with open(rel) as fh:+ mc = dict(json.load(fh).get("model", {}))+ bb = mc.get("backbone")+ if bb and not os.path.isabs(bb):+ mc["backbone"] = os.path.join(os.path.dirname(rel), bb)+ return mc, f"release:{rel}"+ run = find_run_config(ckpt_dir)+ if run is not None:+ return dict((_load_yaml(run) or {}).get("model", {})), f"run:{run}"+ if cfg is not None:+ return dict(cfg.get("model", cfg)), "eval-config"+ return {}, "none"+++def _reconcile_anchor(cfg_anchor, ckpt_anchor, require_anchor=None):+ """Decide the anchor kwargs, or raise. This is the whole point of the module.++ cfg_anchor = the `model.speaker_anchor` block of the resolved config (None if absent).+ ckpt_anchor = derived from the checkpoint's tensors (None if it has no anchor).+ """+ cfg_on = bool((cfg_anchor or {}).get("enabled", False))+ ckpt_on = ckpt_anchor is not None+ if cfg_anchor is not None and cfg_on != ckpt_on:+ raise RuntimeError(+ f"speaker anchor mismatch: the resolved config says enabled={cfg_on} but the "+ f"checkpoint {'HAS' if ckpt_on else 'has NO'} {ANCHOR_PREFIX}* tensors. "+ f"Evaluating either way would compare a different model than the one that was "+ f"trained. Pass the run's own config with --model-config.")+ if require_anchor is not None and bool(require_anchor) != ckpt_on:+ raise RuntimeError(+ f"--require-anchor={require_anchor} but the checkpoint "+ f"{'HAS' if ckpt_on else 'has NO'} {ANCHOR_PREFIX}* tensors")+ if not ckpt_on:+ return None+ out = dict(ckpt_anchor) # geometry from the tensors (authoritative)+ if cfg_anchor:+ for k in ("input_dim", "hidden"):+ if k in cfg_anchor and int(cfg_anchor[k]) != int(out[k]):+ raise RuntimeError(+ f"speaker_anchor.{k}: config says {cfg_anchor[k]}, the checkpoint's "+ f"tensors say {out[k]}")+ out["dropout"] = float(cfg_anchor.get("dropout", 0.20))+ return out+++# ----------------------------------------------------------------------------- construction+def build_eval_model(model_cfg, anchor_cfg, amortize_frac, depth_grouped=False):+ """Construct the eval-mode TTSModelV2. Kept as a module-level function so CPU tests can+ substitute a stand-in: the real backbone needs the Qwen weights and DepthV2 is 555M+ parameters, neither of which fits a <60 s CPU test.++ `depth_grouped` is the RUN's flag (config key `model.depth_grouped`), not an eval choice:+ DepthV2 takes it in the constructor precisely so no forward can flip it (depth_v2.py:158).+ """+ from .tts_model_v2 import TTSModelV2+ return TTSModelV2(backbone=model_cfg["backbone"],+ attn=model_cfg.get("attn", "sdpa"),+ amortize_frac=amortize_frac,+ speaker_anchor=anchor_cfg,+ history_corruption=None, # training-only (see docstring)+ depth_grad_scale=1.0, # gradient-only knob+ depth_grouped=depth_grouped)+++def _strict_diff(model, ckpt_shapes, source):+ """Every model tensor must be in the checkpoint, every checkpoint tensor in the model, at+ the same shape. S2's loader asked for the model's keys only, so extra checkpoint tensors+ (the S3 anchor) vanished without a word."""+ have = {k: v.shape for k, v in model.state_dict().items()}+ missing = sorted(set(have) - set(ckpt_shapes))+ unexpected = sorted(set(ckpt_shapes) - set(have))+ bad = sorted(k for k in set(have) & set(ckpt_shapes)+ if tuple(have[k]) != tuple(ckpt_shapes[k]))+ if missing or unexpected or bad:+ raise RuntimeError(+ f"checkpoint {source} does not match the constructed model:\n"+ f" missing from the checkpoint ({len(missing)}): {missing[:8]}\n"+ f" not in the model ({len(unexpected)}): {unexpected[:8]}\n"+ f" shape mismatch ({len(bad)}): "+ f"{[(k, tuple(ckpt_shapes[k]), tuple(have[k])) for k in bad[:4]]}")+++def load_model_for_eval(ckpt_dir, device=None, dtype=None, *, cfg=None,+ config=None, amortize_frac=1.0, require_anchor=None,+ verbose=True):+ """Load a checkpoint STRICTLY into an eval-mode TTSModelV2. -> (model, provenance).++ ckpt_dir DCP checkpoint dir, a flat model.pt, or a dir containing one, or a+ safetensors release dir (model.safetensors[.index.json] + maya3_config.json).+ device/dtype applied after loading (None = leave on CPU / as constructed).+ cfg the eval config dict the script already loaded (--config).+ config explicit override: a path to the run's resolved config, or a dict.+ amortize_frac 1.0 = score every frame (the eval setting); irrelevant for generation.+ require_anchor True/False asserts the arm's expectation before anything is built.++ provenance: {source, format, update, config_source, backbone, anchor, anchor_cfg,+ depth_grouped, depth_ckpt_from, n_tensors, n_params, amortize_frac}++ `depth_grouped` is taken from the resolved config's `model.depth_grouped` (the same+ precedence as the anchor block: --model-config > <run>/config.yaml > --config) and+ reported so a teacher-forced number can be attributed to the path that produced it —+ see the module docstring for why generation is unaffected.+ """+ src = os.path.abspath(ckpt_dir)+ kind, shapes, payload = _inspect(src)+ model_cfg, cfg_source = resolve_model_cfg(src, cfg=cfg, config=config)+ # eval machines point model.backbone at a local copy, so the CALLER's config wins for+ # the two path-like keys and the run config only supplies the feature blocks+ eval_model = (cfg or {}).get("model", {}) if cfg else {}+ for k in ("backbone", "attn"):+ if k in eval_model:+ model_cfg[k] = eval_model[k]+ if "backbone" not in model_cfg:+ raise RuntimeError(f"no model.backbone in the resolved config ({cfg_source}) — "+ f"pass --config or --model-config")+ anchor_cfg = _reconcile_anchor(model_cfg.get("speaker_anchor"),+ anchor_cfg_from_shapes(shapes),+ require_anchor=require_anchor)+ # the run's depth path, not an eval choice: a run trained with+ # model.depth_grouped=true would be scored through the LOOP without this line+ depth_grouped = bool(model_cfg.get("depth_grouped", False))+ # `model.depth_ckpt_from` is reported but NOT applied: activation+ # checkpointing only exists in training (`self.training and+ # torch.is_grad_enabled()`, depth_v2.py:311/347), so it cannot change an+ # eval number. It is in the provenance so a scored checkpoint records the+ # memory recipe it was trained under.+ depth_ckpt_from = model_cfg.get("depth_ckpt_from")+ model = build_eval_model(model_cfg, anchor_cfg, amortize_frac, depth_grouped)+ _strict_diff(model, shapes, src)++ if kind == "dcp":+ import torch.distributed.checkpoint as dcp+ from torch.distributed.checkpoint import FileSystemReader+ # the model's OWN tensors are the load targets (S2's proven no-dist read path: the+ # 24 rank shards are reassembled by the reader), so nothing is left uninitialised+ sd = {MODEL_PREFIX + k: v for k, v in model.state_dict().items()}+ dcp.load(sd, storage_reader=FileSystemReader(src))+ payload = sd+ flat = {k[len(MODEL_PREFIX):]: v for k, v in payload.items()}+ model.load_state_dict(flat, strict=True) # belt and braces after _strict_diff++ model.eval()+ if device is not None or dtype is not None:+ model.to(**({"device": device} if device is not None else {}),+ **({"dtype": dtype} if dtype is not None else {}))+ prov = {"source": src, "format": kind, "update": checkpoint_update(src),+ "config_source": cfg_source, "backbone": model_cfg["backbone"],+ "anchor": anchor_cfg is not None, "anchor_cfg": anchor_cfg,+ "depth_grouped": depth_grouped,+ "depth_ckpt_from": (int(depth_ckpt_from)+ if depth_ckpt_from is not None else None),+ "n_tensors": len(shapes),+ "n_params": int(sum(p.numel() for p in model.parameters())),+ "amortize_frac": amortize_frac}+ if verbose:+ print("CKPT_LOADED " + json.dumps(prov, sort_keys=True), flush=True)+ return model, prov+++# ------------------------------------------------------------------- serving prompt geometry+def truncate_prompt_batch(b, cut, require_target_span=False):+ """Cut a collated batch at column `cut` and SLICE THE SPAN GEOMETRY WITH IT.++ WHY: the serving/eval prompt is one collate_v2 batch cut at the+ target's first audio column. The old inline loop kept every tensor whose dim-1 was T and+ passed everything else through untouched — which left the 1-D `span_*` tables describing+ the FULL example: spans that were cut away still appeared, and `span_start`/`span_len`+ still counted frames that are no longer in the prompt. `compose_inputs` would then add the+ speaker anchor at sentinel columns outside the prompt (index_put out of range, or silently+ the wrong column once padding shifts).++ Spans are kept iff their `<|audio|>` SENTINEL survives the cut, not their frames: the+ target span's sentinel sits at `cut - 1` (it is the last prompt position, the one whose+ hidden state generates frame 0) while all of its frames are cut away. Dropping it would+ serve the target span with no anchor at all — exactly the training/serving mismatch the+ anchor exists to remove. `span_len` is clipped to the frames that remain.++ A batch with no geometry (a collate from before span geometry was added) passes through unchanged.+ """+ T = int(b["kind"].shape[1])+ cut = int(cut)+ if not 0 < cut <= T:+ raise ValueError(f"cut {cut} outside (0, {T}]")+ pb = {}+ for k, v in b.items():+ if k in SPAN_KEYS:+ continue+ if torch.is_tensor(v) and v.dim() >= 2 and v.shape[1] == T:+ pb[k] = v[:, :cut].clone()+ else:+ pb[k] = v+ if "span_sentinel" not in b:+ return pb+ sent = b["span_sentinel"]+ idx = ((sent >= 0) & (sent < cut)).nonzero().flatten()+ start = b["span_start"][idx].clamp(max=cut)+ end = (b["span_start"][idx] + b["span_len"][idx]).clamp(max=cut)+ pb["span_batch_row"] = b["span_batch_row"][idx].clone()+ pb["span_sentinel"] = sent[idx].clone()+ pb["span_start"] = start+ pb["span_len"] = (end - start).clamp(min=0)+ pb["span_is_target"] = b["span_is_target"][idx].clone()+ if "frame_span_id" in pb:+ # a surviving frame can only belong to a surviving span (sentinel < start <= frame),+ # so the remap is total; -1 stays -1+ remap = torch.full((int(sent.numel()),), -1, dtype=torch.long)+ remap[idx] = torch.arange(idx.numel(), dtype=torch.long)+ f = pb["frame_span_id"]+ pb["frame_span_id"] = torch.where(f >= 0, remap[f.clamp(min=0)], f)+ if require_target_span and not bool(pb["span_is_target"].any()):+ raise RuntimeError(+ "the truncated prompt keeps no TARGET span sentinel — the speaker anchor would "+ "never reach the position that generates frame 0 (packing/target_start bug)")+ return pbdiff --git a/tts/model/tts_model_v2.py b/tts/model/tts_model_v2.pynew file mode 100644index 0000000..b3074ae--- /dev/null+++ b/tts/model/tts_model_v2.py@@ -0,0 +1,329 @@+"""S2 assembly: backbone + DepthV2 (speaker memory lives in the depth stack).++Differences from v1 (tts_model.py):+- no SpeakerConditioner, no KIND_SPK slots (packer v2 never emits them — a+ slot reaching compose is a data bug and raises);+- no EmotionHead (emotion arm deferred; <|emo|> stays reserved in the vocab);+- depth is DepthV2: speaker refs enter as cross-attention K/V memory INSIDE+ depth.forward (never via a bare method call — FSDP2 all-gather hooks only+ wrap Module.__call__, the audio_io lesson);+- scheduled roll-in: batch["rollin_p"] converts that fraction of the depth+ frames to stop-gradient sampled prefixes (exposure to own errors).++S3 additions — ALL DEFAULT OFF and+bit-identical to S2 when off:+- `speaker_anchor`: zero-init MLP added to every span's <|audio|> sentinel+ embedding, so the BACKBONE finally knows who is speaking;+- `history_corruption`: TARGET-only corruption of the codes that feed the+ backbone as history, labels untouched (against copying the+ history's acoustic condition);+- `depth_grad_scale`: scales the acoustic gradient flowing from depth into the+ backbone (forward is an identity for any g);+- `rollin_include_cb0`: roll-in frames read a sampled cb0 from the backbone's+ own logits, matching serving;+- `chunked_lm_head`: the 194,548-way text CE is computed in row chunks under+ activation checkpointing instead of materialising ~30 GiB of logits.++Batch contract (packing_v2.collate_v2): tokens, kind (0=text 1=audio 3=aeos),+codes, loss_mask, attention_mask, spk_refs (B, R, 192), spk_null (B,), q_use,+optional rollin_p / sel_generator / anchor_generator / arm_id; S3 span geometry+span_batch_row / span_start / span_len / span_sentinel / span_is_target /+frame_* masks.++RNG: depth-frame SELECTION and anchor DROPOUT are two+independent stochastic streams. `forward(sel_generator=..., anchor_generator=+...)` (or the same keys on the batch, which the eval scripts use) supplies a+tagged torch.Generator for each; scripts/s3_train.py:tagged_generator() derives+them from (run.seed, tag, rank, update). With them supplied, an arm that has an+anchor and an arm that does not select the SAME frames of the same batch at the+same update, because neither draw walks the global torch stream. With them+absent both fall back to the global stream and the anchor's dropout draw shifts+selection — the S2 behaviour, kept only so old call sites still run.+"""+import inspect++import torch+from torch import nn++from ..tokens import AEOS_CLASS+from .anchors import D_SPK_ECAPA, SpeakerAnchor+from .audio_io import AudioInputEmbed+from .backbone import Backbone+from .chunked_ce import chunked_ce_sum+from .corrupt import CorruptConfig, corrupt_history+from .depth_v2 import DepthV2++KIND_TEXT, KIND_AUDIO, KIND_SPK, KIND_AEOS = 0, 1, 2, 3+++class TTSModelV2(nn.Module):+ def __init__(self, backbone="qwen", attn="sdpa", amortize_frac=0.125,+ speaker_anchor=None, history_corruption=None,+ depth_grad_scale=1.0, depth_grouped=False,+ chunked_lm_head=0, depth_ckpt_from=None):+ """speaker_anchor / history_corruption are the config dicts of+ configs/s3_path_a.yaml (None or {"enabled": false} = OFF):+ speaker_anchor: {enabled, input_dim, dropout, hidden}+ history_corruption: {enabled, span_swap: {weight, duration_s:[lo,hi]},+ level_noise: {weight, first_level}}++ depth_grouped selects DepthV2's grouped teacher-forced forward.+ It is a CONSTRUCTOR decision, never a per-call one: the flag has to+ be identical on every rank for the whole run, and `forward` must not be+ able to flip an FSDP2 collective pattern per batch. Default False =+ the level-by-level loop = bitwise S2.++ chunked_lm_head (config key `model.chunked_lm_head`, rows per chunk)+ is a MEMORY knob with no numeric intent: 0 = off = the unchunked path, which+ materialises the whole (positions, 194,548) logits tensor, bitwise+ unchanged. Any positive value computes the same fp32 CE sum in chunks+ under checkpointing (tts/model/chunked_ce.py). Like+ depth_grouped it is a CONSTRUCTOR decision so no batch can flip the+ checkpoint/collective pattern per rank.++ depth_ckpt_from is DepthV2's selective activation-checkpointing+ threshold (config `model.depth_ckpt_from`, 1..31). None = the mode+ default: 9 on the loop path (S2 bitwise), 1 when depth_grouped is on,+ where checkpointing every group pass is the activation-memory+ lever. A constructor decision for the same FSDP2 reason.+ """+ super().__init__()+ self.backbone = Backbone(backbone, attn=attn)+ d = self.backbone.d_model+ self.depth = DepthV2(d_backbone=d, grouped=depth_grouped,+ ckpt_from=depth_ckpt_from)+ self.audio_in = AudioInputEmbed(d) # root-owned: FSDP-safe+ self._configure(d, amortize_frac, speaker_anchor, history_corruption,+ depth_grad_scale, chunked_lm_head)++ def _configure(self, d_model, amortize_frac=0.125, speaker_anchor=None,+ history_corruption=None, depth_grad_scale=1.0,+ chunked_lm_head=0):+ """Config-only half of __init__. Split out so tests can drive the REAL+ compose_inputs/forward with stand-in backbone/depth submodules — the+ real ones need the Qwen weights and 555M depth params, which no CPU+ test can afford."""+ self.amortize_frac = amortize_frac+ self.depth_grad_scale = float(depth_grad_scale)+ # plain attributes, never buffers: properties of the RUN, not of the+ # weights, so the state_dict / checkpoint contract is unchanged+ self.chunked_lm_head = int(chunked_lm_head or 0)+ if self.chunked_lm_head < 0:+ raise ValueError(f"model.chunked_lm_head must be >= 0 (0 = off), "+ f"got {chunked_lm_head}")+ self.speaker_anchor = None+ if speaker_anchor and speaker_anchor.get("enabled", False):+ self.speaker_anchor = SpeakerAnchor(+ d_model=d_model,+ input_dim=int(speaker_anchor.get("input_dim", D_SPK_ECAPA)),+ hidden=int(speaker_anchor.get("hidden", 512)),+ dropout_p=float(speaker_anchor.get("dropout", 0.20)))+ self.corrupt_cfg = CorruptConfig.from_dict(history_corruption)+ # rollin_cb0/rollin_temp/rollin_top_k are passed to DepthV2.forward+ # only if its signature has them, so an older depth module degrades+ # to the plain roll-in instead of raising.+ self._depth_kwargs = frozenset(+ inspect.signature(self.depth.forward).parameters)++ def compose_inputs(self, batch, codes=None, anchor_gen=None):+ """`codes` overrides batch["codes"] on the INPUT path only (S3 history+ corruption); every LABEL keeps reading batch["codes"]. Default None =+ exactly the S2 path. `anchor_gen` is the tagged generator for the+ anchor's row dropout (falls back to batch["anchor_generator"])."""+ if bool((batch["kind"] == KIND_SPK).any()):+ raise ValueError("KIND_SPK reached the v2 model — v1 packer output?")+ tok_emb = self.backbone.embed_text(batch["tokens"])+ q_use = int(batch["q_use"])+ codes = batch["codes"] if codes is None else codes+ audio = batch["kind"] == KIND_AUDIO+ if audio.any():+ fb = self.audio_in.frames(codes[audio], q_use)+ tok_emb = tok_emb.masked_scatter(audio[..., None], fb.to(tok_emb.dtype))+ aeos = batch["kind"] == KIND_AEOS+ if aeos.any():+ tok_emb = tok_emb.masked_scatter(+ aeos[..., None], self.audio_in.aeos(int(aeos.sum())).to(tok_emb.dtype))+ if self.speaker_anchor is not None:+ tok_emb = self._add_speaker_anchor(batch, tok_emb, anchor_gen)+ return tok_emb++ def _add_speaker_anchor(self, batch, tok_emb, gen=None):+ """Add the row's speaker vector at EVERY span's <|audio|>+ sentinel (packing_v2 span geometry). One vector per ROW — the batch+ carries one spk_refs block per row, not per span."""+ for k in ("span_batch_row", "span_sentinel"):+ if k not in batch:+ raise ValueError(f"speaker_anchor needs collate_v2's {k} "+ "(see packing_v2._add_span_geometry)")+ a = self.speaker_anchor(batch["spk_refs"],+ ref_mask=batch.get("spk_ref_mask"),+ null_mask=batch.get("spk_null"),+ gen=(gen if gen is not None+ else batch.get("anchor_generator")))+ rows, cols = batch["span_batch_row"], batch["span_sentinel"]+ if rows.numel():+ tok_emb = tok_emb.index_put((rows, cols), a[rows].to(tok_emb.dtype),+ accumulate=True)+ # gradient symmetry: exactly-zero term so the+ # anchor params are in the graph even on a batch with no spans / all+ # rows null — added unconditionally, never inside the `if`.+ return tok_emb + self.speaker_anchor.sym_term().to(tok_emb.dtype)++ def _rollin_cb0(self, h_sel, true_cb0, rmask, temp, top_k):+ """Roll-in cb0: roll-in frames feed DEPTH a cb0 SAMPLED from+ the backbone's own logits for that frame instead of the true one, so+ the depth stack sees the cb0 distribution it meets at serving (S2+ roll-in never sampled cb0). Stop-gradient throughout; frames+ outside the roll-in mask keep the TRUE cb0, so the returned (N,) tensor+ is safe whether depth substitutes everywhere or only on masked rows.++ SUPPORT == SERVING'S. scripts/+ s2_serve_controls.py:283-289 divides the FULL (N_CODES+1)-way logits by+ the temperature and takes top-k over ALL classes INCLUDING AEOS; only+ then, when it decides to continue, does it zero AEOS out of that+ distribution and renormalise (s2_serve_controls.py:330-333). Dropping+ AEOS BEFORE the top-k (the first version of this method) admits the+ 65th-ranked class whenever AEOS is inside the top 64, so training would+ sample from a support serving never uses. Masking the AEOS LOGIT to+ -inf after the top-k is exactly serving's "q[AEOS]=0; q/=q.sum()".++ `h_sel` must be the RAW backbone hidden state, not an fp32 copy: under+ FSDP2 mixed precision `cb0_head` is bf16, and serving likewise+ feeds `cb0_logits` the model-dtype hidden state (s2_serve_controls.py:+ 283) while passing `h.float()` to depth (:335)."""+ neg_inf = -float("inf")+ with torch.no_grad():+ lg = self.backbone.cb0_logits(h_sel.detach()).float()+ if temp != 1.0:+ lg = lg / max(float(temp), 1e-6)+ k = int(top_k)+ if k:+ kth = lg.topk(min(k, lg.shape[-1]), -1).values[:, -1:]+ sup = lg.masked_fill(lg < kth, neg_inf) # fresh tensor+ else:+ sup = lg.clone() # never alias `lg`+ sup[:, AEOS_CLASS] = neg_inf+ if k == 1:+ # top_k == 1 with AEOS as the argmax leaves an all -inf row+ # (NaN in softmax). Serving cannot reach it — the controlled+ # stop breaks on `p.argmax() == AEOS_CLASS` first+ # (s2_serve_controls.py:321) — but training has no stop, so fall+ # back to the un-top-k'd, AEOS-free support. k >= 2 keeps at+ # least two classes, so at most one of them can be AEOS.+ lg[:, AEOS_CLASS] = neg_inf+ sup = torch.where(torch.isfinite(sup).any(-1, keepdim=True),+ sup, lg)+ samp = torch.multinomial(sup.softmax(-1), 1).squeeze(-1)+ return torch.where(rmask, samp, true_cb0)++ def forward(self, batch, corrupt_frac=0.0, corrupt_gen=None,+ rollin_temp=1.0, rollin_top_k=0, rollin_include_cb0=False,+ sel_generator=None, anchor_generator=None):+ """corrupt_frac: current history-corruption ramp value (0..0.30), only+ meaningful when the model was built with history_corruption enabled;+ corrupt_gen: the loop's seeded torch.Generator. rollin_* configure the+ within-frame roll-in sampling. sel_generator /+ anchor_generator are the tagged per-update streams for depth-frame+ selection and anchor dropout (module docstring); each+ falls back to the same-named batch key and then to the global torch+ stream. S2 call sites — model(batch) — are unaffected: every S3 knob+ defaults to the S2 behaviour."""+ codes_in = batch["codes"]+ if self.corrupt_cfg is not None and float(corrupt_frac) > 0.0:+ codes_in, cstats = corrupt_history(batch, self.corrupt_cfg,+ float(corrupt_frac), corrupt_gen)+ else:+ cstats = None+ x = self.compose_inputs(batch, codes=codes_in,+ anchor_gen=anchor_generator)+ hidden, _ = self.backbone(x, attention_mask=batch.get("attention_mask"))+ out = {"hidden": hidden}+ if cstats is not None:+ out["corrupt_stats"] = cstats # telemetry for the loop+ nk = batch["kind"][:, 1:]+ lm = batch["loss_mask"][:, 1:]+ h = hidden[:, :-1]+ pred_text = (nk == KIND_TEXT) & lm+ pred_cb0 = ((nk == KIND_AUDIO) | (nk == KIND_AEOS)) & lm+ pred_depth = (nk == KIND_AUDIO) & lm+ if not batch.get("depth_on_refs", True) and "target_start" in batch:+ # exclude in-context REFERENCE frames from the depth loss: the+ # row's speaker memory holds those utterances' own embeddings,+ # so predicting them is a self-conditioning shortcut.+ # cb0 loss on refs is unaffected.+ pos = torch.arange(1, nk.shape[1] + 1, device=nk.device)[None, :]+ pred_depth = pred_depth & (pos >= batch["target_start"][:, None])+ # the 194,548-way text head is skipped when this arm's text loss+ # weight is 0 (audio arms) — the flag is a rank-lockstep Python bool+ # set by the loop from the arm; the tied matrix still trains as the+ # input embedding on those arms+ if pred_text.any() and batch.get("compute_text_logits", True):+ ht = h[pred_text]+ tt = batch["tokens"][:, 1:][pred_text]+ if self.chunked_lm_head:+ # ~30 GiB of transient 194,548-way logits on the replay+ # arm, ~11.9 GiB of it retained until backward. The chunked+ # form computes the SAME fp32 CE sum tts/train/losses.py:93-96+ # would (sum of per-chunk sums) and hands it over ready-made;+ # `text_targets` still travels, so the denominator, telemetry+ # and every other consumer are unchanged.+ out["text_loss_sum"] = chunked_ce_sum(+ self.backbone.text_logits, ht, tt, self.chunked_lm_head)+ else:+ # key insertion order kept as it was, so `out` is identical+ out["text_logits"] = self.backbone.text_logits(ht)+ out["text_targets"] = tt+ if pred_cb0.any():+ out["cb0_logits"] = self.backbone.cb0_logits(h[pred_cb0])+ out["cb0_targets"] = batch["codes"][:, 1:, 0][pred_cb0]+ if pred_depth.any():+ q_use = int(batch["q_use"])+ tgt = batch["codes"][:, 1:][pred_depth] # (N, n_q) ORIGINAL+ row_of = torch.nonzero(pred_depth)[:, 0] # frame -> batch row+ n = tgt.shape[0]+ k = max(1, int(n * self.amortize_frac))+ gen = (sel_generator if sel_generator is not None+ else batch.get("sel_generator"))+ sel = torch.randperm(n, device=tgt.device, generator=gen)[:k]+ rows = row_of[sel]+ p = float(batch.get("rollin_p", 0.0))+ rmask = (torch.rand(k, device=tgt.device) < p) if p > 0 else None+ # the REALIZED roll-in count, not the+ # expected p*k the telemetry used to record. A device scalar that+ # is never read here — s3_train sums it ON DEVICE and reads it once+ # per log window — so this costs one reduction and no sync, and it+ # is the count the depth FLOP model must be charged for (rolled+ # rows take _forward_split's sequential path).+ out["rollin_count"] = (+ rmask.sum() if rmask is not None+ else torch.zeros((), dtype=torch.long, device=tgt.device))+ # RAW backbone dtype for the cb0 head (bf16 under FSDP2 mixed+ # precision: an fp32 hidden state into+ # the root-owned bf16 cb0_head aborts the forward), fp32 for depth.+ # Serving splits the same way: cb0_logits(h) vs depth h.float()+ # (s2_serve_controls.py:283 / :335).+ h_raw = h[pred_depth][sel]+ kw = {}+ if rollin_include_cb0 and rmask is not None \+ and "rollin_cb0" in self._depth_kwargs:+ kw["rollin_cb0"] = self._rollin_cb0(+ h_raw, tgt[sel][:, 0], rmask, rollin_temp, rollin_top_k)+ h_sel = h_raw.float()+ for name, val in (("rollin_temp", rollin_temp),+ ("rollin_top_k", rollin_top_k)):+ if name in self._depth_kwargs:+ kw[name] = val+ g = self.depth_grad_scale+ if g != 1.0:+ # depth_grad_scale: forward is an exact identity for any g; the+ # gradient reaching the BACKBONE through depth is scaled by g,+ # depth's own parameter gradients are untouched.+ h_sel = h_sel.detach() + g * (h_sel - h_sel.detach())+ out["depth_logits"] = self.depth(+ h_sel, tgt[sel],+ refs=batch["spk_refs"][rows],+ null_mask=batch["spk_null"][rows],+ ref_mask=batch["spk_ref_mask"][rows],+ q_eff=q_use, rollin_mask=rmask, **kw)+ out["depth_targets"] = tgt[sel][:, 1:q_use]+ return outdiff --git a/tts/tokens.py b/tts/tokens.pynew file mode 100644index 0000000..ea95ff4--- /dev/null+++ b/tts/tokens.py@@ -0,0 +1,87 @@+"""Token contract v0 for the custom-TTS campaign (see custom-tts-plan.md §5).++The backbone keeps its text tokenizer untouched; we append ~50 control tokens to the+text vocab and keep audio OUTSIDE the text vocab entirely (audio enters as embeddings+summed from the depth codebooks, never as text-vocab ids).++Sequence layout of one utterance (sentence-interleave format):+ <|lang:xx|> text ... <|emo|> emo_label <|audio|> a a a ... <aeos-as-cb0-class>+The emotion slot sits AFTER the text and BEFORE the audio so the model predicts it+causally from text (and forced values steer the audio that follows). Pace tags are+plain-text tags inside the text span; punctuation is the prosody interface.++<aeos> is NOT a token in this table: it is class N_CODES (2048) on the cb0 head only,+weighted 3x in the loss. Keeping it out of the text vocab means the backbone can never+emit it as text.+"""+from dataclasses import dataclass, field++# ---- audio codec constants (Kyutai Mimi, 32-codebook lane) -------------------------+FRAME_HZ = 12.5+N_Q = 32 # codebooks trained; serve-time early-exit at 16/24 allowed+N_CODES = 2048 # per-codebook vocabulary+AEOS_CLASS = N_CODES # cb0 head has N_CODES+1 classes; class 2048 = <aeos>+AEOS_LOSS_WEIGHT = 3.0++LANGS = ["as", "bn", "en", "gu", "hi", "kn", "ml", "mr", "or", "pa", "ta", "te"]++CTL_SLOTS = 32 # reserved, unassigned control ids for future use+++@dataclass(frozen=True)+class TokenContract:+ """Names of every added text-vocab token, in the exact order they are appended.++ The order is FROZEN once a checkpoint exists: appending is allowed, reordering+ and deleting are not. `added_tokens()` is the single source of truth consumed by+ the tokenizer extension, the embedding-resize code and the golden contract test.+ """+ spk: str = "<|spk|>" # precedes the speaker-embedding soft slot+ audio: str = "<|audio|>" # text->audio switch+ emo: str = "<|emo|>" # emotion slot opener (label follows as text)+ instruct_open: str = "<|instruct|>" # instruction-mode span (Mode-B controls)+ instruct_close: str = "<|/instruct|>"+ cont: str = "<|cont|>" # non-initial continuation span (from+ # tag_continuation; never a mere packing+ # boundary)+ langs: tuple = tuple(f"<|lang:{l}|>" for l in LANGS)+ ctl: tuple = tuple(f"<|ctl:{i:02d}|>" for i in range(CTL_SLOTS))++ def added_tokens(self) -> list:+ return [self.spk, self.audio, self.emo,+ self.instruct_open, self.instruct_close, self.cont,+ *self.langs, *self.ctl]++ # next-token loss-mask policy: these are conditioning+ # inputs, never prediction targets; <|emo|> and <|audio|> stay unmasked+ # (learned causal sentinels), as does an inferred emotion label.+ def masked_as_targets(self) -> list:+ return [self.spk, self.instruct_open, self.instruct_close, self.cont,+ *self.langs, *self.ctl]+++CONTRACT = TokenContract()+++def extend_tokenizer(tokenizer):+ """Append the contract tokens; return (tokenizer, name->id dict).++ Idempotent: HF add_tokens skips names already present, and ids are re-read from+ the tokenizer, so calling this on an already-extended checkpoint is a no-op.+ """+ tokenizer.add_tokens(CONTRACT.added_tokens(), special_tokens=True)+ ids = {t: tokenizer.convert_tokens_to_ids(t) for t in CONTRACT.added_tokens()}+ missing = [t for t, i in ids.items() if i is None or i < 0]+ if missing:+ raise ValueError(f"tokenizer failed to register: {missing}")+ return tokenizer, ids+++def golden_contract(tokenizer) -> dict:+ """Serializable snapshot for the golden tensor-contract test."""+ _, ids = extend_tokenizer(tokenizer)+ return {+ "frame_hz": FRAME_HZ, "n_q": N_Q, "n_codes": N_CODES,+ "aeos_class": AEOS_CLASS, "aeos_loss_weight": AEOS_LOSS_WEIGHT,+ "added": ids, "vocab_size": len(tokenizer),+ }