diff --git a/.gitattributes b/.gitattributes
index a6344aac8c09253b3b630fb776ae94478aa0275b..aaecea145c890d5d51d2b37d8d1cf09f80c5d67a 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -33,3 +33,27 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
*.zip filter=lfs diff=lfs merge=lfs -text
*.zst filter=lfs diff=lfs merge=lfs -text
*tfevents* filter=lfs diff=lfs merge=lfs -text
+assets/architecture.png filter=lfs diff=lfs merge=lfs -text
+assets/banner.gif filter=lfs diff=lfs merge=lfs -text
+assets/banner.png filter=lfs diff=lfs merge=lfs -text
+assets/landscape.png filter=lfs diff=lfs merge=lfs -text
+assets/params.png filter=lfs diff=lfs merge=lfs -text
+assets/results.png filter=lfs diff=lfs merge=lfs -text
+assets/speech.gif filter=lfs diff=lfs merge=lfs -text
+gguf/aksharavp-17m-f16.gguf filter=lfs diff=lfs merge=lfs -text
+gguf/aksharavp-17m-f32.gguf filter=lfs diff=lfs merge=lfs -text
+samples/en_clone.wav filter=lfs diff=lfs merge=lfs -text
+samples/en_clone_reference.wav filter=lfs diff=lfs merge=lfs -text
+samples/en_ishaan.wav filter=lfs diff=lfs merge=lfs -text
+samples/en_meera.wav filter=lfs diff=lfs merge=lfs -text
+samples/en_sneha.wav filter=lfs diff=lfs merge=lfs -text
+samples/hi_clone.wav filter=lfs diff=lfs merge=lfs -text
+samples/hi_clone_reference.wav filter=lfs diff=lfs merge=lfs -text
+samples/hi_meera.wav filter=lfs diff=lfs merge=lfs -text
+samples/hi_nandini.wav filter=lfs diff=lfs merge=lfs -text
+samples/hi_siddharth.wav filter=lfs diff=lfs merge=lfs -text
+samples/te_clone.wav filter=lfs diff=lfs merge=lfs -text
+samples/te_clone_reference.wav filter=lfs diff=lfs merge=lfs -text
+samples/te_lakshmi.wav filter=lfs diff=lfs merge=lfs -text
+samples/te_sravani.wav filter=lfs diff=lfs merge=lfs -text
+samples/te_srinivas.wav filter=lfs diff=lfs merge=lfs -text
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..fe463e0f7888bbf8b82e42d55f5743508ddafb7e
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,408 @@
+Attribution-NonCommercial 4.0 International
+
+=======================================================================
+
+Creative Commons Corporation ("Creative Commons") is not a law firm and
+does not provide legal services or legal advice. Distribution of
+Creative Commons public licenses does not create a lawyer-client or
+other relationship. Creative Commons makes its licenses and related
+information available on an "as-is" basis. Creative Commons gives no
+warranties regarding its licenses, any material licensed under their
+terms and conditions, or any related information. Creative Commons
+disclaims all liability for damages resulting from their use to the
+fullest extent possible.
+
+Using Creative Commons Public Licenses
+
+Creative Commons public licenses provide a standard set of terms and
+conditions that creators and other rights holders may use to share
+original works of authorship and other material subject to copyright
+and certain other rights specified in the public license below. The
+following considerations are for informational purposes only, are not
+exhaustive, and do not form part of our licenses.
+
+ Considerations for licensors: Our public licenses are
+ intended for use by those authorized to give the public
+ permission to use material in ways otherwise restricted by
+ copyright and certain other rights. Our licenses are
+ irrevocable. Licensors should read and understand the terms
+ and conditions of the license they choose before applying it.
+ Licensors should also secure all rights necessary before
+ applying our licenses so that the public can reuse the
+ material as expected. Licensors should clearly mark any
+ material not subject to the license. This includes other CC-
+ licensed material, or material used under an exception or
+ limitation to copyright. More considerations for licensors:
+ wiki.creativecommons.org/Considerations_for_licensors
+
+ Considerations for the public: By using one of our public
+ licenses, a licensor grants the public permission to use the
+ licensed material under specified terms and conditions. If
+ the licensor's permission is not necessary for any reason--for
+ example, because of any applicable exception or limitation to
+ copyright--then that use is not regulated by the license. Our
+ licenses grant only permissions under copyright and certain
+ other rights that a licensor has authority to grant. Use of
+ the licensed material may still be restricted for other
+ reasons, including because others have copyright or other
+ rights in the material. A licensor may make special requests,
+ such as asking that all changes be marked or described.
+ Although not required by our licenses, you are encouraged to
+ respect those requests where reasonable. More considerations
+ for the public:
+ wiki.creativecommons.org/Considerations_for_licensees
+
+=======================================================================
+
+Creative Commons Attribution-NonCommercial 4.0 International Public
+License
+
+By exercising the Licensed Rights (defined below), You accept and agree
+to be bound by the terms and conditions of this Creative Commons
+Attribution-NonCommercial 4.0 International Public License ("Public
+License"). To the extent this Public License may be interpreted as a
+contract, You are granted the Licensed Rights in consideration of Your
+acceptance of these terms and conditions, and the Licensor grants You
+such rights in consideration of benefits the Licensor receives from
+making the Licensed Material available under these terms and
+conditions.
+
+
+Section 1 -- Definitions.
+
+ a. Adapted Material means material subject to Copyright and Similar
+ Rights that is derived from or based upon the Licensed Material
+ and in which the Licensed Material is translated, altered,
+ arranged, transformed, or otherwise modified in a manner requiring
+ permission under the Copyright and Similar Rights held by the
+ Licensor. For purposes of this Public License, where the Licensed
+ Material is a musical work, performance, or sound recording,
+ Adapted Material is always produced where the Licensed Material is
+ synched in timed relation with a moving image.
+
+ b. Adapter's License means the license You apply to Your Copyright
+ and Similar Rights in Your contributions to Adapted Material in
+ accordance with the terms and conditions of this Public License.
+
+ c. Copyright and Similar Rights means copyright and/or similar rights
+ closely related to copyright including, without limitation,
+ performance, broadcast, sound recording, and Sui Generis Database
+ Rights, without regard to how the rights are labeled or
+ categorized. For purposes of this Public License, the rights
+ specified in Section 2(b)(1)-(2) are not Copyright and Similar
+ Rights.
+ d. Effective Technological Measures means those measures that, in the
+ absence of proper authority, may not be circumvented under laws
+ fulfilling obligations under Article 11 of the WIPO Copyright
+ Treaty adopted on December 20, 1996, and/or similar international
+ agreements.
+
+ e. Exceptions and Limitations means fair use, fair dealing, and/or
+ any other exception or limitation to Copyright and Similar Rights
+ that applies to Your use of the Licensed Material.
+
+ f. Licensed Material means the artistic or literary work, database,
+ or other material to which the Licensor applied this Public
+ License.
+
+ g. Licensed Rights means the rights granted to You subject to the
+ terms and conditions of this Public License, which are limited to
+ all Copyright and Similar Rights that apply to Your use of the
+ Licensed Material and that the Licensor has authority to license.
+
+ h. Licensor means the individual(s) or entity(ies) granting rights
+ under this Public License.
+
+ i. NonCommercial means not primarily intended for or directed towards
+ commercial advantage or monetary compensation. For purposes of
+ this Public License, the exchange of the Licensed Material for
+ other material subject to Copyright and Similar Rights by digital
+ file-sharing or similar means is NonCommercial provided there is
+ no payment of monetary compensation in connection with the
+ exchange.
+
+ j. Share means to provide material to the public by any means or
+ process that requires permission under the Licensed Rights, such
+ as reproduction, public display, public performance, distribution,
+ dissemination, communication, or importation, and to make material
+ available to the public including in ways that members of the
+ public may access the material from a place and at a time
+ individually chosen by them.
+
+ k. Sui Generis Database Rights means rights other than copyright
+ resulting from Directive 96/9/EC of the European Parliament and of
+ the Council of 11 March 1996 on the legal protection of databases,
+ as amended and/or succeeded, as well as other essentially
+ equivalent rights anywhere in the world.
+
+ l. You means the individual or entity exercising the Licensed Rights
+ under this Public License. Your has a corresponding meaning.
+
+
+Section 2 -- Scope.
+
+ a. License grant.
+
+ 1. Subject to the terms and conditions of this Public License,
+ the Licensor hereby grants You a worldwide, royalty-free,
+ non-sublicensable, non-exclusive, irrevocable license to
+ exercise the Licensed Rights in the Licensed Material to:
+
+ a. reproduce and Share the Licensed Material, in whole or
+ in part, for NonCommercial purposes only; and
+
+ b. produce, reproduce, and Share Adapted Material for
+ NonCommercial purposes only.
+
+ 2. Exceptions and Limitations. For the avoidance of doubt, where
+ Exceptions and Limitations apply to Your use, this Public
+ License does not apply, and You do not need to comply with
+ its terms and conditions.
+
+ 3. Term. The term of this Public License is specified in Section
+ 6(a).
+
+ 4. Media and formats; technical modifications allowed. The
+ Licensor authorizes You to exercise the Licensed Rights in
+ all media and formats whether now known or hereafter created,
+ and to make technical modifications necessary to do so. The
+ Licensor waives and/or agrees not to assert any right or
+ authority to forbid You from making technical modifications
+ necessary to exercise the Licensed Rights, including
+ technical modifications necessary to circumvent Effective
+ Technological Measures. For purposes of this Public License,
+ simply making modifications authorized by this Section 2(a)
+ (4) never produces Adapted Material.
+
+ 5. Downstream recipients.
+
+ a. Offer from the Licensor -- Licensed Material. Every
+ recipient of the Licensed Material automatically
+ receives an offer from the Licensor to exercise the
+ Licensed Rights under the terms and conditions of this
+ Public License.
+
+ b. No downstream restrictions. You may not offer or impose
+ any additional or different terms or conditions on, or
+ apply any Effective Technological Measures to, the
+ Licensed Material if doing so restricts exercise of the
+ Licensed Rights by any recipient of the Licensed
+ Material.
+
+ 6. No endorsement. Nothing in this Public License constitutes or
+ may be construed as permission to assert or imply that You
+ are, or that Your use of the Licensed Material is, connected
+ with, or sponsored, endorsed, or granted official status by,
+ the Licensor or others designated to receive attribution as
+ provided in Section 3(a)(1)(A)(i).
+
+ b. Other rights.
+
+ 1. Moral rights, such as the right of integrity, are not
+ licensed under this Public License, nor are publicity,
+ privacy, and/or other similar personality rights; however, to
+ the extent possible, the Licensor waives and/or agrees not to
+ assert any such rights held by the Licensor to the limited
+ extent necessary to allow You to exercise the Licensed
+ Rights, but not otherwise.
+
+ 2. Patent and trademark rights are not licensed under this
+ Public License.
+
+ 3. To the extent possible, the Licensor waives any right to
+ collect royalties from You for the exercise of the Licensed
+ Rights, whether directly or through a collecting society
+ under any voluntary or waivable statutory or compulsory
+ licensing scheme. In all other cases the Licensor expressly
+ reserves any right to collect such royalties, including when
+ the Licensed Material is used other than for NonCommercial
+ purposes.
+
+
+Section 3 -- License Conditions.
+
+Your exercise of the Licensed Rights is expressly made subject to the
+following conditions.
+
+ a. Attribution.
+
+ 1. If You Share the Licensed Material (including in modified
+ form), You must:
+
+ a. retain the following if it is supplied by the Licensor
+ with the Licensed Material:
+
+ i. identification of the creator(s) of the Licensed
+ Material and any others designated to receive
+ attribution, in any reasonable manner requested by
+ the Licensor (including by pseudonym if
+ designated);
+
+ ii. a copyright notice;
+
+ iii. a notice that refers to this Public License;
+
+ iv. a notice that refers to the disclaimer of
+ warranties;
+
+ v. a URI or hyperlink to the Licensed Material to the
+ extent reasonably practicable;
+
+ b. indicate if You modified the Licensed Material and
+ retain an indication of any previous modifications; and
+
+ c. indicate the Licensed Material is licensed under this
+ Public License, and include the text of, or the URI or
+ hyperlink to, this Public License.
+
+ 2. You may satisfy the conditions in Section 3(a)(1) in any
+ reasonable manner based on the medium, means, and context in
+ which You Share the Licensed Material. For example, it may be
+ reasonable to satisfy the conditions by providing a URI or
+ hyperlink to a resource that includes the required
+ information.
+
+ 3. If requested by the Licensor, You must remove any of the
+ information required by Section 3(a)(1)(A) to the extent
+ reasonably practicable.
+
+ 4. If You Share Adapted Material You produce, the Adapter's
+ License You apply must not prevent recipients of the Adapted
+ Material from complying with this Public License.
+
+
+Section 4 -- Sui Generis Database Rights.
+
+Where the Licensed Rights include Sui Generis Database Rights that
+apply to Your use of the Licensed Material:
+
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right
+ to extract, reuse, reproduce, and Share all or a substantial
+ portion of the contents of the database for NonCommercial purposes
+ only;
+
+ b. if You include all or a substantial portion of the database
+ contents in a database in which You have Sui Generis Database
+ Rights, then the database in which You have Sui Generis Database
+ Rights (but not its individual contents) is Adapted Material; and
+
+ c. You must comply with the conditions in Section 3(a) if You Share
+ all or a substantial portion of the contents of the database.
+
+For the avoidance of doubt, this Section 4 supplements and does not
+replace Your obligations under this Public License where the Licensed
+Rights include other Copyright and Similar Rights.
+
+
+Section 5 -- Disclaimer of Warranties and Limitation of Liability.
+
+ a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
+ EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
+ AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
+ ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
+ IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
+ WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
+ PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
+ ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
+ KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
+ ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
+
+ b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
+ TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
+ NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
+ INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
+ COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
+ USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
+ ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
+ DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
+ IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
+
+ c. The disclaimer of warranties and limitation of liability provided
+ above shall be interpreted in a manner that, to the extent
+ possible, most closely approximates an absolute disclaimer and
+ waiver of all liability.
+
+
+Section 6 -- Term and Termination.
+
+ a. This Public License applies for the term of the Copyright and
+ Similar Rights licensed here. However, if You fail to comply with
+ this Public License, then Your rights under this Public License
+ terminate automatically.
+
+ b. Where Your right to use the Licensed Material has terminated under
+ Section 6(a), it reinstates:
+
+ 1. automatically as of the date the violation is cured, provided
+ it is cured within 30 days of Your discovery of the
+ violation; or
+
+ 2. upon express reinstatement by the Licensor.
+
+ For the avoidance of doubt, this Section 6(b) does not affect any
+ right the Licensor may have to seek remedies for Your violations
+ of this Public License.
+
+ c. For the avoidance of doubt, the Licensor may also offer the
+ Licensed Material under separate terms or conditions or stop
+ distributing the Licensed Material at any time; however, doing so
+ will not terminate this Public License.
+
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
+ License.
+
+
+Section 7 -- Other Terms and Conditions.
+
+ a. The Licensor shall not be bound by any additional or different
+ terms or conditions communicated by You unless expressly agreed.
+
+ b. Any arrangements, understandings, or agreements regarding the
+ Licensed Material not stated herein are separate from and
+ independent of the terms and conditions of this Public License.
+
+
+Section 8 -- Interpretation.
+
+ a. For the avoidance of doubt, this Public License does not, and
+ shall not be interpreted to, reduce, limit, restrict, or impose
+ conditions on any use of the Licensed Material that could lawfully
+ be made without permission under this Public License.
+
+ b. To the extent possible, if any provision of this Public License is
+ deemed unenforceable, it shall be automatically reformed to the
+ minimum extent necessary to make it enforceable. If the provision
+ cannot be reformed, it shall be severed from this Public License
+ without affecting the enforceability of the remaining terms and
+ conditions.
+
+ c. No term or condition of this Public License will be waived and no
+ failure to comply consented to unless expressly agreed to by the
+ Licensor.
+
+ d. Nothing in this Public License constitutes or may be interpreted
+ as a limitation upon, or waiver of, any privileges and immunities
+ that apply to the Licensor or You, including from the legal
+ processes of any jurisdiction or authority.
+
+=======================================================================
+
+Creative Commons is not a party to its public
+licenses. Notwithstanding, Creative Commons may elect to apply one of
+its public licenses to material it publishes and in those instances
+will be considered the “Licensor.” The text of the Creative Commons
+public licenses is dedicated to the public domain under the CC0 Public
+Domain Dedication. Except for the limited purpose of indicating that
+material is shared under a Creative Commons public license or as
+otherwise permitted by the Creative Commons policies published at
+creativecommons.org/policies, Creative Commons does not authorize the
+use of the trademark "Creative Commons" or any other trademark or logo
+of Creative Commons without its prior written consent including,
+without limitation, in connection with any unauthorized modifications
+to any of its public licenses or any other arrangements,
+understandings, or agreements concerning use of licensed material. For
+the avoidance of doubt, this paragraph does not form part of the
+public licenses.
+
+Creative Commons may be contacted at creativecommons.org.
+
diff --git a/LICENSE-MIT-kyutai-pocket-tts b/LICENSE-MIT-kyutai-pocket-tts
new file mode 100644
index 0000000000000000000000000000000000000000..31aa79387f27e730e33d871925e152e35e428031
--- /dev/null
+++ b/LICENSE-MIT-kyutai-pocket-tts
@@ -0,0 +1,23 @@
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
diff --git a/NOTICE b/NOTICE
new file mode 100644
index 0000000000000000000000000000000000000000..198680b3b2e78d460edcb11fab60316a56ff6a10
--- /dev/null
+++ b/NOTICE
@@ -0,0 +1,29 @@
+AksharaVP-17M — component notices
+==================================
+
+Credit line (required): "AksharaVP-17M by Sourojit Dhua (sourojitdotcom), https://huggingface.co/sourojitdotcom/AksharaVP-17M"
+
+1. AksharaVP weights (model.safetensors tensors student.*, and the GGUF copies of them)
+ Licence: CC-BY-NC-4.0 (LICENSE). Trained by Sourojit Dhua. Knowledge-distilled from Hima TTS nano
+ (Prahaladha/hima-tts-nano-hi, Prahaladha/hima-tts-nano-te) with the written permission of its authors; the flow-map
+ head was initialised from that teacher's head.
+
+2. Mimi decoder (model.safetensors tensors mimi.*, and the GGUF copies of them)
+ Kyutai, Pocket TTS, language "english_7m_2026-10" (kyutai/pocket-tts-without-voice-cloning), redistributed UNCHANGED.
+ Licence: CC-BY-4.0, https://creativecommons.org/licenses/by/4.0/ . These tensors stay under CC-BY-4.0; the
+ non-commercial terms of item 1 do not apply to them.
+
+3. clone_encoder.safetensors (optional, zero-shot cloning only) and voices.safetensors (12 built-in voice prompts)
+ From Hima TTS nano (codec encoder path and shipped voice prompts), redistributed with its authors' permission
+ under the terms of item 1.
+
+4. Code
+ aksharavp_tts/model.py, tts.py, __main__.py, gguf_load.py: Sourojit Dhua, CC-BY-NC-4.0 with the weights.
+ aksharavp_tts/flow_head.py: MLP-AdaLN flow head, derived from https://github.com/LTH14/mar (MIT, (c) 2024 Tianhong Li)
+ via Kyutai Pocket TTS (MIT, LICENSE-MIT-kyutai-pocket-tts).
+ aksharavp_tts/normalize.py, indic_languages.py: text normaliser from Hima TTS nano, used with permission.
+ Runtime dependency: pocket-tts 4.0.1 (MIT, Kyutai) for the Mimi decoder modules.
+
+5. Data
+ Text: IndicCorp v2 (ai4bharat, CC0). Clone prompts in training: LibriTTS-R (CC-BY-4.0).
+ Evaluation: FLEURS (google/fleurs, CC-BY-4.0) dev split. The clone reference clips in samples/ are FLEURS dev recordings (CC-BY-4.0).
diff --git a/README.md b/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..491b7815946b76a1e7faa2ecaa8d5c6caf21aef8
--- /dev/null
+++ b/README.md
@@ -0,0 +1,328 @@
+---
+license: cc-by-nc-4.0
+language:
+- te
+- hi
+- en
+pipeline_tag: text-to-speech
+library_name: pytorch
+tags:
+- text-to-speech
+- tts
+- telugu
+- hindi
+- indian-english
+- voice-cloning
+- zero-shot
+- tiny
+- cpu
+- on-device
+- gguf
+- knowledge-distillation
+- flow-matching
+- custom-architecture
+datasets:
+- ai4bharat/IndicCorpV2
+- google/fleurs
+metrics:
+- cer
+- wer
+model-index:
+- name: AksharaVP-17M
+ results:
+ - task:
+ type: text-to-speech
+ name: Text-to-speech intelligibility (Telugu, ASR facebook/mms-1b-all)
+ dataset:
+ type: google/fleurs
+ name: FLEURS te_in (dev, first 100 sentences)
+ split: validation
+ metrics:
+ - type: cer
+ name: CER (%)
+ value: 6.04
+ - type: wer
+ name: WER (%)
+ value: 28.94
+ - type: utmos
+ name: UTMOS22-strong
+ value: 2.64
+ - task:
+ type: text-to-speech
+ name: Text-to-speech intelligibility (Hindi, ASR facebook/mms-1b-all)
+ dataset:
+ type: google/fleurs
+ name: FLEURS hi_in (dev, first 100 sentences)
+ split: validation
+ metrics:
+ - type: cer
+ name: CER (%)
+ value: 4.57
+ - type: wer
+ name: WER (%)
+ value: 13.97
+ - type: utmos
+ name: UTMOS22-strong
+ value: 2.73
+ - task:
+ type: text-to-speech
+ name: Text-to-speech intelligibility (Indian English, ASR facebook/mms-1b-all)
+ dataset:
+ type: google/fleurs
+ name: FLEURS en_us (dev, first 100 sentences)
+ split: validation
+ metrics:
+ - type: cer
+ name: CER (%)
+ value: 4.37
+ - type: wer
+ name: WER (%)
+ value: 9.45
+ - type: utmos
+ name: UTMOS22-strong
+ value: 3.19
+---
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+# AksharaVP-17M
+
+Telugu, Hindi and Indian English speech from one 17.6M-parameter checkpoint. Built-in voices, zero-shot voice cloning, and it runs on a laptop CPU.
+
+| 17,643,026 | 6.04% · 4.57% · 4.37% | 12 + clone | 35.3 MB | 1 |
+|:---:|:---:|:---:|:---:|:---:|
+| parameters, decoder included | character error rate · te / hi / en (FLEURS dev) | built-in voices · zero-shot cloning | f16 GGUF (70.6 MB fp32) | checkpoint for all three languages |
+
+AksharaVP-17M reads **Telugu**, **Hindi** (Devanagari) and **Indian English** aloud at 24 kHz. A small transformer writes continuous audio
+latents one 80 ms frame at a time, a 4-step flow-map head samples each frame, and Kyutai's 2.6M-parameter Mimi decoder turns them into
+a waveform. One file holds everything the speaking path needs: no phonemiser, no external vocoder, no GPU.
+
+
+
+
+
+> ⚠️ **Naturalness is the weak point.** Speech is clear (low error rates below) but flatter and less expressive than large TTS systems:
+> UTMOS is 2.64 (te), 2.73 (hi) and 3.19 (en) on a 1–5 scale. See the [Comparison](#comparison) section for how that sits next to bigger models.
+
+---
+
+## Listen
+
+All clips are raw model output from the files in this repository (published sampler: guidance 1.25, temperature 0.3, 4 flow steps, seed 0) —
+nothing hand-picked after listening. Texts were written for this card (they are not FLEURS evaluation sentences).
+
+| Language | Voice | Text | Audio |
+|---|---|---|---|
+| Hindi | Meera | नमस्ते! मैं अक्षरा हूँ, और मैं हिंदी, तेलुगु और अंग्रेज़ी बोल सकती हूँ। | |
+| Hindi | Siddharth | कल सुबह दस बजे हमारी मीटिंग है, कृपया समय पर पहुँचिए। | |
+| Hindi | Nandini | बारिश के बाद हवा में मिट्टी की खुशबू कितनी अच्छी लगती है। | |
+| Telugu | Lakshmi | నమస్కారం! నేను అక్షర, తెలుగు, హిందీ మరియు ఇంగ్లీష్ మాట్లాడగలను. | |
+| Telugu | Srinivas | రేపు ఉదయం పది గంటలకు మన సమావేశం ఉంది, దయచేసి సమయానికి రండి. | |
+| Telugu | Sravani | వర్షం తర్వాత మట్టి వాసన ఎంతో హాయిగా ఉంటుంది. | |
+| Indian English | Meera | Hello! I'm a tiny text to speech model that runs on an ordinary laptop processor. | |
+| Indian English | Ishaan | Your train to Hyderabad leaves from platform four at nine fifteen. | |
+| Indian English | Sneha | Small models can still speak clearly, if they are trained with care. | |
+
+### Zero-shot voice cloning
+
+A few seconds of someone's speech in, the same voice reading new text out. The reference clips are FLEURS dev recordings (CC-BY-4.0); the
+English row clones a Hindi speaker (cross-lingual). Cloning needs the optional `clone_encoder.safetensors` (9,749,024 parameters).
+
+| Language | Reference clip | Text | AksharaVP-17M |
+|---|---|---|---|
+| Hindi | | यह आवाज़ सिर्फ़ कुछ सेकंड की रिकॉर्डिंग से बनाई गई है। | |
+| Telugu | | ఈ గొంతు కేవలం కొన్ని సెకన్ల రికార్డింగ్ నుండి తయారైంది. | |
+| Indian English | | This voice was copied from a few seconds of recorded speech. | |
+
+---
+
+## What it achieves
+
+| # | Claim | The evidence |
+|---|---|---|
+| 1 | **Three languages, one 17.6M checkpoint.** | 17,643,026 parameters: 15,025,793 for text → latents and 2,617,233 for the decoder, counted from `model.safetensors`. Telugu, Hindi and Indian English share every weight. |
+| 2 | **Smallest open TTS we found that speaks Telugu + Hindi + English from one checkpoint *and* clones voices.** | 27,392,050 parameters with the clone encoder. The next smallest we found: Pravega Pocket TTS 121.8M, DhVaani-0.5 122.8M, IndicF5 350.7M (Hub safetensors metadata, 17 Nov 2026). Smaller single-language Indic TTS exist (e.g. 8.9M-parameter per-language VITS models), but without cloning or a shared checkpoint. |
+| 3 | **Low character error rates on all three languages.** | FLEURS dev, 100 sentences each, ASR by `facebook/mms-1b-all`: CER 6.04% te, 4.57% hi, 4.37% en. |
+| 4 | **CPU only.** | See the live Space — it runs on a free 2-vCPU CPU instance. |
+| 5 | **Bit-exact GGUF.** | The f32 GGUF reproduces the safetensors output sample-for-sample (max abs difference 0.0); the f16 GGUF is 35.3 MB with the same frame counts and max sample difference 0.023. |
+
+
+
+
+
+**Stated plainly:** "smallest" here means the smallest *we found* in that specific category, by parameter count, on the date above — not a
+claim about every TTS model in existence, and not a quality ranking. The other models in that chart were **not** evaluated by us.
+
+---
+
+## How it works
+
+
+
+- **Text:** characters, not phonemes. Telugu and Devanagari share one 128-slot table (same Unicode offsets), plus ASCII — a 256-symbol vocabulary with a rank-64 factorised embedding. Numbers, dates and symbols are expanded by the bundled normaliser.
+- **Backbone:** 8 pre-LN transformer layers, width 320, grouped-query attention (5 query heads, 1 KV head), RoPE, causal. It reads `[text][voice prompt][frames so far]` and predicts the next frame's conditioning vector and an end-of-speech logit.
+- **Flow-map head:** an MLP-AdaLN (512 wide, 6 blocks, two time inputs) that jumps from noise to a 32-d latent frame in 4 steps, with classifier-free guidance on its outputs.
+- **Decoder:** Kyutai Pocket TTS's Mimi decoder (english_7m_2026-10), unchanged: 32-d latents at 12.5 Hz → 24 kHz audio.
+- **Voices:** a voice is a prompt of up to 62 latent frames (~5 s). 12 are built in; cloning encodes your clip into the same space.
+
+
+
+---
+
+## Benchmarks
+
+
+
+**FLEURS dev, first 100 sentences per language, built-in voices (cycled), published sampler, no retakes.** Brackets: 95% bootstrap intervals.
+English uses FLEURS `en_us` sentences spoken with the built-in Indian voices.
+
+| Language | CER % | WER % | UTMOS (1–5) |
+|---|---:|---:|---:|
+| Telugu | 6.04 [4.78, 7.46] | 28.94 [25.66, 32.43] | 2.64 [2.58, 2.69] |
+| Hindi | 4.57 [3.79, 5.39] | 13.97 [12.25, 15.92] | 2.73 [2.66, 2.80] |
+| Indian English | 4.37 [3.07, 5.87] | 9.45 [7.31, 11.83] | 3.19 [3.12, 3.25] |
+
+- **ASR:** `facebook/mms-1b-all` (CTC, greedy, language adapters hin/tel/eng); CER/WER after Unicode NFC and punctuation removal. Telugu WER is high for every system we measured because Telugu words are long and agglutinative — one wrong character costs a whole word.
+- **Naturalness:** UTMOS22-strong (SpeechMOS). It is an automatic predictor trained mostly on English; treat absolute values for Telugu/Hindi with care, but differences between systems on the same sentences are informative.
+- **Dev, not test.** Every choice that shaped this release (checkpoint, guidance, temperature) was made on the dev split. A held-out test split exists and has not been used for this model.
+- The demo and the Python API add an automatic retake when a take runs on or goes silent; the numbers above are **without** retakes.
+
+### CPU speed
+
+See the live Space for timings on a free CPU instance.
+
+---
+
+## Comparison
+
+Same benchmark for every row: FLEURS dev (first 100 sentences per language, same sentence ids), `facebook/mms-1b-all` CER / WER (%) and
+UTMOS22-strong, each system with its own built-in voices and default sampler, **all measured by us on the same machine with the same scripts.**
+Parameters = the speaking path (text → audio) excluding any clone-only encoder; fp32 size = parameters × 4 bytes.
+
+| System | Parameters | fp32 size | Languages | Telugu CER / WER / **UTMOS** | Hindi CER / WER / **UTMOS** | English CER / WER / **UTMOS** |
+|---|---:|---:|---|---|---|---|
+| **AksharaVP-17M (this model)** | 17,643,026 | 70.6 MB | te · hi · en, one checkpoint | 6.04 / 28.94 / **2.64** | 4.57 / 13.97 / **2.73** | 4.37 / 9.45 / **3.19** |
+| Hima TTS nano (hi + te checkpoints) | 72,160,162 | 288.6 MB | te+en / hi+en, two checkpoints | 6.54 / 31.43 / **3.51** | 4.88 / 15.06 / **3.60** | 5.29 / 11.47 / **4.04** |
+| Kyutai Pocket TTS (english) | 99,752,802 | 399.0 MB | en only | — | — | 2.35 / 6.01 / **3.99** |
+| Kyutai Pocket TTS english_7m_2026-10 | 6,862,578 | 27.5 MB | en only | — | — | 1.99 / 6.37 / **4.10** |
+| Kyutai Pocket TTS english_2m_2026-10 | 1,922,846 | 7.7 MB | en only | — | — | 3.89 / 9.70 / **3.49** |
+
+Notes: Hima TTS nano ships separate Telugu and Hindi checkpoints of 72,160,162 parameters each (English is spoken by the Hindi one; its English row uses that checkpoint). Pocket TTS rows are English-only models speaking with their own (non-Indian) built-in voices, so English accent differs from the Indian voices of the other rows. UTMOS is an English-centric predictor; compare systems within a language column, not across columns.
+
+**Paired bootstrap, AksharaVP-17M − Hima TTS nano** (same 100 sentences per language, 10,000 resamples, seed 1; negative CER/WER = fewer errors, negative UTMOS = less natural):
+
+| Language | ΔCER (points) | ΔWER (points) | ΔUTMOS |
+|---|---|---|---|
+| Telugu | -0.50 [-1.13, +0.16] (p=0.145) | -2.49 [-4.91, +0.00] (p=0.050) | -0.87 [-0.95, -0.79] |
+| Hindi | -0.31 [-0.95, +0.28] (p=0.329) | -1.07 [-2.62, +0.44] (p=0.176) | -0.87 [-0.93, -0.80] |
+| Indian English | -0.92 [-1.85, -0.09] (p=0.027) | -2.03 [-4.16, -0.15] (p=0.036) | -0.85 [-0.94, -0.76] |
+
+Read honestly: AksharaVP-17M's error rates are **as low as or lower than** Hima TTS nano's (significant only for English CER/WER; Telugu and Hindi CER
+differences are within noise), at about a quarter of the parameters — but it is **clearly less natural** (UTMOS about 0.85 lower in every language,
+significant). Kyutai's English-only Pocket TTS models beat it on English on every metric, including the 6.9M one.
+
+---
+
+## Quick start
+
+```bash
+pip install -U huggingface_hub
+hf download sourojitdotcom/AksharaVP-17M --local-dir AksharaVP-17M
+cd AksharaVP-17M
+pip install -r requirements.txt
+```
+
+```python
+from aksharavp_tts import AksharaVP
+
+tts = AksharaVP(".") # loads model.safetensors (+ clone_encoder.safetensors if present)
+audio = tts.say("నమస్కారం! మీరు ఎలా ఉన్నారు?", lang="te", voice="Lakshmi")
+tts.save(audio, "telugu.wav")
+
+audio = tts.say("कल सुबह दस बजे मिलते हैं।", lang="hi", voice="Siddharth")
+audio = tts.say("Your table is ready.", lang="en", clone="my_voice.wav") # zero-shot cloning, 3–10 s clip
+```
+
+```bash
+python -m aksharavp_tts "नमस्ते, आप कैसे हैं?" --lang hi --voice Meera -o hello.wav
+python -m aksharavp_tts --list-voices
+```
+
+Built-in voices — Hindi set: Meera, Sneha, Nandini (female), Siddharth, Ishaan, Nikhil (male); Telugu set: Lakshmi, Sravani, Bhavana (female),
+Srinivas, Karthik, Pranay (male). Any voice can speak any of the three languages. Options: `temperature` (0.3), `cfg` (guidance, 1.25), `steps` (4), `seed`.
+
+## GGUF
+
+| File | Size | Storage | Parity with `model.safetensors` |
+|---|---:|---|---|
+| `gguf/aksharavp-17m-f32.gguf` | 70.60 MB | F32, all 289 tensors | tensors identical (max abs diff 0.0); audio **bit-identical** on te/hi/en test sentences |
+| `gguf/aksharavp-17m-f16.gguf` | 35.31 MB | F16, upcast on load | tensor max abs diff 0.0072; same frame counts; waveform max abs diff ≤ 0.023 |
+
+GGUF v3 containers written with the `gguf` Python package; metadata holds the full config, parameter counts and sampler defaults.
+**llama.cpp has no runtime for this architecture** — these are portable weight files. Load them back into PyTorch with:
+
+```python
+from gguf_load import load_gguf
+tts = load_gguf("gguf/aksharavp-17m-f16.gguf")
+tts.save(tts.say("నమస్కారం", lang="te"), "out.wav")
+```
+
+## Files
+
+| File | What |
+|---|---|
+| `model.safetensors` | the 17,643,026-parameter speaking path (`student.*` + `mimi.*` decoder), fp32, 70.6 MB |
+| `clone_encoder.safetensors` | optional audio encoder for zero-shot cloning (9,749,024 params) |
+| `voices.safetensors` | 12 built-in voice prompts (62 × 32 latents each) |
+| `config.json` | architecture, parameter counts, sampler defaults, voices |
+| `aksharavp_tts/` | PyTorch inference code (`AksharaVP.say`) and the text normaliser |
+| `gguf/`, `gguf_load.py` | GGUF containers and loader |
+| `samples/` | the audio on this page |
+| `evaluation/` | measured numbers behind every table (benchmarks, comparison, GGUF parity, speed) |
+
+## Training
+
+Knowledge distillation into a small student: latent-level L2 on the teacher's hidden states plus sample-level distillation of the flow head,
+from a larger in-house teacher TTS, **Hima TTS nano** (used with its authors' written permission; the flow-map head is initialised from its head,
+and the built-in voice prompts and clone encoder come from it). Teacher speech was generated for IndicCorp v2 sentences (CC0) in Telugu, Hindi and
+English, with FLEURS dev/test sentences removed from the training text; LibriTTS-R (CC-BY-4.0) clips served as cloning prompts.
+Final stage: 100,026 steps on one Kaggle T4 GPU (about 10.8 h), initialised from an earlier distilled checkpoint of the same architecture.
+
+## Limitations and responsible use
+
+- **Naturalness** is the main gap: prosody is flatter than large models. Expect clear, slightly monotone speech.
+- **Very short inputs** (one or two words) can run on or come out oddly; the API retakes automatically, but short phrases are the least reliable.
+- **Code-mixed text** (English words inside Hindi/Telugu) works only as well as the character table allows; it was not specifically evaluated.
+- **Cloning quality** depends on a clean 3–10 s clip; it was checked to work, but speaker similarity was not benchmarked for this release.
+- **Do not clone a voice without the speaker's consent**, and label generated speech as synthetic.
+
+## Licence & attribution
+
+- **AksharaVP weights and code:** [CC-BY-NC-4.0](LICENSE) — non-commercial; credit **Sourojit Dhua (sourojitdotcom)** and link this page.
+- **Mimi decoder tensors (`mimi.*`):** Kyutai Pocket TTS, unchanged, **CC-BY-4.0**; they keep that licence.
+- Flow-head code derives from MAR (MIT) via Kyutai Pocket TTS (MIT). Full list in [NOTICE](NOTICE).
+
+```text
+AksharaVP-17M by Sourojit Dhua (sourojitdotcom) — https://huggingface.co/sourojitdotcom/AksharaVP-17M
+```
+
+```bibtex
+@misc{dhua2026aksharavp,
+ title = {AksharaVP-17M: Telugu, Hindi and Indian-English text to speech in 17.6M parameters},
+ author = {Dhua, Sourojit},
+ year = {2026},
+ url = {https://huggingface.co/sourojitdotcom/AksharaVP-17M}
+}
+```
diff --git a/aksharavp_tts/__init__.py b/aksharavp_tts/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..00078e6ad10f5556129299bf793a928edf3a520a
--- /dev/null
+++ b/aksharavp_tts/__init__.py
@@ -0,0 +1,2 @@
+from .tts import AksharaVP, SAMPLE_RATE, LANG_NAMES
+__all__ = ["AksharaVP", "SAMPLE_RATE", "LANG_NAMES"]
diff --git a/aksharavp_tts/__main__.py b/aksharavp_tts/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a4dc824504252528ea501c826fed0c0c3a85171
--- /dev/null
+++ b/aksharavp_tts/__main__.py
@@ -0,0 +1,13 @@
+import argparse
+from .tts import AksharaVP
+ap = argparse.ArgumentParser(prog="python -m aksharavp_tts", description="AksharaVP-17M text to speech (te / hi / en)")
+ap.add_argument("text"); ap.add_argument("--lang", default="hi", choices=["te", "hi", "en"]); ap.add_argument("--voice")
+ap.add_argument("--clone", help="a 3-10 s clip of clear speech to copy"); ap.add_argument("-o", "--out", default="out.wav")
+ap.add_argument("--model", default="."); ap.add_argument("--temperature", type=float); ap.add_argument("--cfg", type=float)
+ap.add_argument("--steps", type=int); ap.add_argument("--seed", type=int, default=0); ap.add_argument("--list-voices", action="store_true")
+a = ap.parse_args()
+tts = AksharaVP(a.model, load_clone_encoder=bool(a.clone))
+if a.list_voices:
+ for n, m in tts.voices.items(): print(n, m["gender"], m["set"])
+else:
+ tts.save(tts.say(a.text, lang=a.lang, voice=a.voice, clone=a.clone, temperature=a.temperature, cfg=a.cfg, steps=a.steps, seed=a.seed), a.out); print("wrote", a.out)
diff --git a/aksharavp_tts/flow_head.py b/aksharavp_tts/flow_head.py
new file mode 100644
index 0000000000000000000000000000000000000000..0765c3c593f2aea6cdec845b2c6880f49f511e83
--- /dev/null
+++ b/aksharavp_tts/flow_head.py
@@ -0,0 +1,217 @@
+from __future__ import annotations
+"""
+Taken from
+https://github.com/LTH14/mar/blob/fe470ac24afbee924668d8c5c83e9fec60af3a73/models/diffloss.py
+
+"""
+
+import math
+
+import torch
+from torch import nn
+from typing_extensions import Self
+
+
+
+def modulate(x: torch.Tensor, shift: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
+ return x * (1 + scale) + shift
+
+
+def _rms_norm(x: torch.Tensor, alpha: torch.Tensor, eps: float) -> torch.Tensor:
+ assert x.dim() >= alpha.dim()
+ x_dtype = x.dtype
+ var = eps + x.var(dim=-1, keepdim=True)
+ y = (x * (alpha.to(var) * torch.rsqrt(var))).to(x_dtype)
+ return y
+
+
+class RMSNorm(nn.Module):
+ def __init__(self, dim: int, eps: float = 1e-5):
+ super().__init__()
+ self.eps = eps
+ alpha_shape = (dim,)
+ self.alpha = nn.Parameter(torch.full(alpha_shape, 1.0, requires_grad=True))
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ return _rms_norm(x, self.alpha, self.eps)
+
+
+class LayerNorm(nn.Module):
+ """Reimplementation of LayerNorm because the default one doesn't support jvp."""
+
+ def __init__(self, channels: int, eps: float = 1e-6, elementwise_affine: bool = True):
+ super().__init__()
+ self.eps = eps
+ if elementwise_affine:
+ self.weight = nn.Parameter(torch.ones(channels))
+ self.bias = nn.Parameter(torch.zeros(channels))
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ mean = x.mean(dim=-1, keepdim=True)
+ var = x.var(dim=-1, unbiased=False, keepdim=True)
+ x = (x - mean) / torch.sqrt(var + self.eps)
+ if hasattr(self, "weight"):
+ x = x * self.weight + self.bias
+ return x
+
+
+class TimestepEmbedder(nn.Module):
+ """Embeds scalar timesteps into vector representations."""
+
+ freqs: torch.Tensor
+
+ def __init__(
+ self, hidden_size: int, frequency_embedding_size: int = 256, max_period: int = 10000
+ ):
+ super().__init__()
+ blocks = [
+ nn.Linear(frequency_embedding_size, hidden_size, bias=True),
+ nn.SiLU(),
+ nn.Linear(hidden_size, hidden_size, bias=True),
+ ]
+ blocks.append(RMSNorm(hidden_size))
+ self.mlp = nn.Sequential(*blocks)
+ self.frequency_embedding_size = frequency_embedding_size
+ half = frequency_embedding_size // 2
+ self.register_buffer(
+ "freqs", torch.exp(-math.log(max_period) * torch.arange(start=0, end=half) / half)
+ )
+
+ def forward(self, t: torch.Tensor) -> torch.Tensor:
+ args = t * self.freqs.to(t.dtype)
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
+ assert not (self.frequency_embedding_size % 2)
+ t_emb = self.mlp(embedding)
+ return t_emb
+
+
+class ResBlock(nn.Module):
+ """
+ A residual block that can optionally change the number of channels.
+ :param channels: the number of input channels.
+ """
+
+ def __init__(self, channels: int):
+ super().__init__()
+ self.channels = channels
+
+ self.in_ln = LayerNorm(channels, eps=1e-6)
+ self.mlp = nn.Sequential(
+ nn.Linear(channels, channels, bias=True),
+ nn.SiLU(),
+ nn.Linear(channels, channels, bias=True),
+ )
+
+ self.adaLN_modulation = nn.Sequential(
+ nn.SiLU(), nn.Linear(channels, 3 * channels, bias=True)
+ )
+
+ def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
+ shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(y).chunk(3, dim=-1)
+ h = modulate(self.in_ln(x), shift_mlp, scale_mlp)
+ h = self.mlp(h)
+ return x + gate_mlp * h
+
+
+class FinalLayer(nn.Module):
+ """
+ The final layer adopted from DiT.
+ """
+
+ def __init__(self, model_channels: int, out_channels: int):
+ super().__init__()
+ self.norm_final = LayerNorm(model_channels, elementwise_affine=False, eps=1e-6)
+ self.linear = nn.Linear(model_channels, out_channels, bias=True)
+ self.adaLN_modulation = nn.Sequential(
+ nn.SiLU(), nn.Linear(model_channels, 2 * model_channels, bias=True)
+ )
+
+ def forward(self, x: torch.Tensor, c: torch.Tensor) -> torch.Tensor:
+ shift, scale = self.adaLN_modulation(c).chunk(2, dim=-1)
+ x = modulate(self.norm_final(x), shift, scale)
+ x = self.linear(x)
+ return x
+
+
+class SimpleMLPAdaLN(nn.Module):
+ """Taken from https://arxiv.org/abs/2406.11838.
+
+ The MLP for Diffusion Loss.
+ :param in_channels: channels in the input Tensor.
+ :param model_channels: base channel count for the model.
+ :param out_channels: channels in the output Tensor.
+ :param cond_channels: channels in the condition.
+ :param num_res_blocks: number of residual blocks per downsample.
+ """
+
+ def __init__(
+ self,
+ in_channels: int,
+ model_channels: int,
+ out_channels: int,
+ cond_channels: int,
+ num_res_blocks: int,
+ num_time_conds: int = 1,
+ ):
+ super().__init__()
+
+ self.in_channels = in_channels
+ self.model_channels = model_channels
+ self.out_channels = out_channels
+ self.num_res_blocks = num_res_blocks
+ self.num_time_conds = num_time_conds
+
+ self.time_embed = nn.ModuleList(
+ [TimestepEmbedder(model_channels) for _ in range(num_time_conds)]
+ )
+ self.cond_embed = nn.Linear(cond_channels, model_channels)
+
+ self.input_proj = nn.Linear(in_channels, model_channels)
+
+ res_blocks = []
+ for i in range(num_res_blocks):
+ res_blocks.append(ResBlock(model_channels))
+
+ self.res_blocks = nn.ModuleList(res_blocks)
+ self.final_layer = FinalLayer(model_channels, out_channels)
+
+ @classmethod
+ def from_pydantic_config(cls, cfg: FlowLMConfig, latent_dim: int, cond_dim: int) -> Self:
+ config = cfg.flow
+
+ flow_dim = config.dim
+ flow_depth = config.depth
+ if config.type == "lsd":
+ num_time_conds = 2
+ elif config.type == "flow_matching":
+ num_time_conds = 1
+ elif config.type in ("drifting", "pointwise"):
+ num_time_conds = 0
+ else:
+ raise ValueError(f"Unknown flow type: {config.type}")
+ return cls(
+ latent_dim, flow_dim, latent_dim, cond_dim, flow_depth, num_time_conds=num_time_conds
+ )
+
+ def forward(self, c: torch.Tensor, *args: torch.Tensor) -> torch.Tensor:
+ """
+ Apply the model to an input batch.
+ :param c: conditioning from AR transformer.
+ :param args: `num_time_conds` time tensors, then an [N x C] Tensor of
+ inputs. The released models use two (start and target time); other
+ training objectives use one or none.
+ :return: an [N x C] Tensor of outputs.
+ """
+ ts, x = args[:-1], args[-1]
+ assert len(ts) == self.num_time_conds, (
+ f"Expected {self.num_time_conds} time conditions, got {len(ts)}"
+ )
+ x = self.input_proj(x)
+ y = self.cond_embed(c)
+ if self.num_time_conds:
+ y = y + sum(emb(t) for emb, t in zip(self.time_embed, ts)) / self.num_time_conds
+
+ for block in self.res_blocks:
+ x = block(x, y)
+
+ return self.final_layer(x, y)
diff --git a/aksharavp_tts/indic_languages.py b/aksharavp_tts/indic_languages.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9cdea593e45e6f343bb5c4d647d57c4c632e8bc
--- /dev/null
+++ b/aksharavp_tts/indic_languages.py
@@ -0,0 +1,1659 @@
+"""Native language tables for the text normaliser.
+
+"""
+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 ' 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}"
+
+ # ------------------------------------------------------------------
+ # Telugu grammar hooks.
+ # ------------------------------------------------------------------
+
+ # 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
+
+LANGUAGES = {cls.code: cls() for cls in (
+ Hindi, Bengali, Gujarati, Kannada, Malayalam, Marathi, Odia, Punjabi, Tamil, Telugu
+)}
diff --git a/aksharavp_tts/model.py b/aksharavp_tts/model.py
new file mode 100644
index 0000000000000000000000000000000000000000..1cc712743becb2277b11eb24acd3200c062da7a8
--- /dev/null
+++ b/aksharavp_tts/model.py
@@ -0,0 +1,205 @@
+"""AksharaVP student (Design A): Pocket-style CALM-tiny over 32-d Mimi-VAE latents at 12.5 Hz.
+Row: [text chars (shared Brahmic akshara offsets)][lang][ref frames <=62 or no-ref token][bos frame][frame_0]...[frame_n-1]
+Backbone d224 x 8, GQA 8q/2kv (head 64), FFN 224, RoPE, pre-LN. Flow head: MLP-AdaLN 192 x 4, plain flow matching (t-only,
+sinusoidal, parameter-free time features), Euler sampling. EOS head on the 64-d z. Parameter layout mirrors Kyutai english_7m
+(design_params.py formula) with vocab 256."""
+import math, torch, torch.nn as nn, torch.nn.functional as F
+
+# ---------------- tokenizer: script-agnostic Brahmic offsets + ASCII ----------------
+PAD, BOS, UNK, SPACE = 0, 1, 2, 3
+LANG = {'hi': 4, 'te': 5, 'en': 6}
+BRAHMIC = {0x0900: 'deva', 0x0C00: 'telu'}
+def encode_text(s, lang):
+ ids = [BOS, LANG[lang]]
+ for ch in s:
+ o = ord(ch)
+ if ch == ' ': ids.append(SPACE)
+ elif 0x0900 <= o <= 0x097F or 0x0C00 <= o <= 0x0C7F: ids.append(8 + (o & 0x7F)) # 8..135 shared offset
+ elif 0x21 <= o <= 0x7E: ids.append(136 + o - 0x21) # 136..229
+ elif o in (0x200C, 0x200D): continue
+ else: ids.append(UNK)
+ return ids
+VOCAB = 256
+
+def rope(n, hd, theta=10000.0):
+ inv = 1.0 / (theta ** (torch.arange(0, hd, 2).float() / hd)); f = torch.outer(torch.arange(n).float(), inv)
+ return torch.cos(f), torch.sin(f)
+def apply_rope(x, cos, sin):
+ x1, x2 = x[..., 0::2], x[..., 1::2]; c, s = cos[None, None].to(x.dtype), sin[None, None].to(x.dtype)
+ return torch.stack((x1 * c - x2 * s, x1 * s + x2 * c), -1).flatten(-2)
+
+class Attn(nn.Module):
+ def __init__(s, d, hq, hkv, hd):
+ super().__init__(); s.hq, s.hkv, s.hd = hq, hkv, hd
+ s.in_proj = nn.Linear(d, (hq + 2 * hkv) * hd, bias=False); s.out_proj = nn.Linear(hq * hd, d, bias=False)
+ def forward(s, x, cos, sin, mask=None, cache=None, pos=0):
+ B, T, _ = x.shape; q, k, v = s.in_proj(x).split([s.hq * s.hd, s.hkv * s.hd, s.hkv * s.hd], -1)
+ q = q.view(B, T, s.hq, s.hd).transpose(1, 2); k = k.view(B, T, s.hkv, s.hd).transpose(1, 2); v = v.view(B, T, s.hkv, s.hd).transpose(1, 2)
+ q, k = apply_rope(q, cos[pos:pos + T], sin[pos:pos + T]), apply_rope(k, cos[pos:pos + T], sin[pos:pos + T])
+ if cache is not None:
+ kc, vc = cache; kc[:, :, pos:pos + T] = k; vc[:, :, pos:pos + T] = v; k, v = kc[:, :, :pos + T], vc[:, :, :pos + T]
+ r = s.hq // s.hkv; k = k.repeat_interleave(r, 1); v = v.repeat_interleave(r, 1)
+ y = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, is_causal=(mask is None and cache is None))
+ return s.out_proj(y.transpose(1, 2).reshape(B, T, -1))
+
+class Block(nn.Module):
+ def __init__(s, d, hq, hkv, hd, ff):
+ super().__init__(); s.norm1, s.norm2 = nn.LayerNorm(d), nn.LayerNorm(d); s.self_attn = Attn(d, hq, hkv, hd)
+ s.linear1, s.linear2 = nn.Linear(d, ff, bias=False), nn.Linear(ff, d, bias=False)
+ def forward(s, x, cos, sin, mask=None, cache=None, pos=0):
+ x = x + s.self_attn(s.norm1(x), cos, sin, mask, cache, pos)
+ return x + s.linear2(F.gelu(s.linear1(s.norm2(x)), approximate='tanh'))
+
+def tfeat(t, dim=64):
+ half = dim // 2; f = torch.exp(-math.log(10000) * torch.arange(half, device=t.device) / half)
+ a = t[..., None].float() * 1000 * f; return torch.cat([a.cos(), a.sin()], -1)
+
+class ResBlock(nn.Module):
+ def __init__(s, w):
+ super().__init__(); s.in_ln = nn.LayerNorm(w); s.mlp = nn.Sequential(nn.Linear(w, w), nn.SiLU(), nn.Linear(w, w))
+ s.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(w, 3 * w))
+ def forward(s, x, c):
+ sh, sc, g = s.adaLN_modulation(c).chunk(3, -1)
+ return x + g * s.mlp(s.in_ln(x) * (1 + sc) + sh)
+
+class FlowNet(nn.Module):
+ def __init__(s, lat, w, depth, zc):
+ super().__init__(); s.input_proj = nn.Linear(lat, w); s.cond_embed = nn.Linear(zc, w)
+ s.res_blocks = nn.ModuleList([ResBlock(w) for _ in range(depth)])
+ s.final_norm = nn.LayerNorm(w, elementwise_affine=False)
+ s.final_adaLN = nn.Sequential(nn.SiLU(), nn.Linear(w, 2 * w)); s.final_linear = nn.Linear(w, lat)
+ def forward(s, z, t, x):
+ c = s.cond_embed(z + tfeat(t, z.shape[-1])); h = s.input_proj(x)
+ for b in s.res_blocks: h = b(h, c)
+ sh, sc = s.final_adaLN(c).chunk(2, -1)
+ return s.final_linear(s.final_norm(h) * (1 + sc) + sh)
+
+class Student(nn.Module):
+ def __init__(s, d=224, L=8, hq=8, hkv=2, hd=64, ff=224, fw=192, fdepth=4, lat=32, zc=64, rank=64, vocab=VOCAB, ref_frames=62, max_len=1024, lsd=False):
+ super().__init__(); s.d, s.lat, s.ref_frames = d, lat, ref_frames
+ s.embed = nn.Embedding(vocab, rank); s.embed_proj = nn.Linear(rank, d, bias=False) # rank-64 factorised text table
+ s.bos_before_voice = nn.Parameter(torch.zeros(1, 1, d)) # "no reference" token
+ s.speaker_proj_weight = nn.Linear(lat, d, bias=False) # reference (prompt) frames
+ s.input_linear = nn.Linear(lat, d, bias=False); s.bos_emb = nn.Parameter(torch.zeros(lat))
+ s.layers = nn.ModuleList([Block(d, hq, hkv, hd, ff) for _ in range(L)]); s.out_norm = nn.LayerNorm(d)
+ s.z_proj = nn.Linear(d, zc, bias=False); s.out_eos = nn.Linear(zc, 1); s.lsd = lsd
+ if lsd: # round 4 (Design D): Hima/Pocket-style LSD flow-map head (2 time conds), weights copied from Hima; z lives in Hima's (z+head) space
+ from .flow_head import SimpleMLPAdaLN
+ s.flow_net = SimpleMLPAdaLN(lat, fw, lat, zc, fdepth, num_time_conds=2)
+ else: s.flow_net = FlowNet(lat, fw, fdepth, zc)
+ s.register_buffer('emb_mean', torch.zeros(lat)); s.register_buffer('emb_std', torch.ones(lat))
+ cos, sin = rope(max_len, hd); s.register_buffer('cos', cos, persistent=False); s.register_buffer('sin', sin, persistent=False)
+
+ def prefix(s, text_ids, ref):
+ """text_ids [B,Tt] (PAD=0), ref [B,R,32] normalised or None-rows via ref_len=0 -> list built by caller."""
+ return s.embed_proj(s.embed(text_ids))
+
+ def forward_train(s, text, tlen, ref, rlen, frames, flen, flow_mult=4, hist_noise=0.0, return_z=False):
+ """text [B,Tt] tlen [B]; ref [B,R,32] (normalised) rlen [B] (0 = no ref); frames [B,N,32] normalised, flen [B].
+ Builds per-row sequences [text][ref or no-ref][bos][frames], right-padded; causal + key-padding mask."""
+ B, dev = text.shape[0], text.device
+ te = s.embed_proj(s.embed(text)); re_ = s.speaker_proj_weight(ref); fr = frames
+ if hist_noise > 0: fr = fr + hist_noise * torch.rand(B, 1, 1, device=dev) * torch.randn_like(fr)
+ fe = s.input_linear(torch.cat([s.bos_emb.expand(B, 1, -1).to(fr.dtype), fr], 1)) # [B,N+1,d]
+ nref = torch.where(rlen > 0, rlen, torch.ones_like(rlen))
+ P = tlen + nref; Ltot = int((P + flen + 1).max())
+ x = te.new_zeros(B, Ltot, s.d); valid = torch.zeros(B, Ltot, dtype=torch.bool, device=dev)
+ ar = torch.arange(max(Ltot, text.shape[1], ref.shape[1], frames.shape[1] + 1), device=dev)
+ # scatter pieces (vectorised via index arithmetic)
+ Tt, R, N1 = te.shape[1], re_.shape[1], fe.shape[1]
+ ti = ar[None, :Tt].expand(B, -1); tm = ti < tlen[:, None]
+ x[torch.arange(B, device=dev)[:, None].expand(-1, Tt)[tm], ti[tm]] = te[tm]
+ ri = ar[None, :R].expand(B, -1); rm = ri < rlen[:, None]
+ bidx = torch.arange(B, device=dev)[:, None]
+ x[bidx.expand(-1, R)[rm], (tlen[:, None] + ri)[rm]] = re_[rm]
+ nr = rlen == 0
+ if nr.any(): x[nr, tlen[nr]] = s.bos_before_voice[0, 0].to(x.dtype)
+ fi = ar[None, :N1].expand(B, -1); fm = fi < (flen + 1)[:, None]
+ x[bidx.expand(-1, N1)[fm], (P[:, None] + fi)[fm]] = fe[fm]
+ valid = ar[None, :Ltot] < (P + flen + 1)[:, None]
+ mask = (torch.ones(Ltot, Ltot, dtype=torch.bool, device=dev).tril()[None] & valid[:, None, :]) | torch.eye(Ltot, dtype=torch.bool, device=dev)[None]
+ mask = mask[:, None]
+ for blk in s.layers: x = blk(x, s.cos, s.sin, mask)
+ h = s.out_norm(x)
+ # outputs at positions P-1+... : position (P + j) holds input frame j-1 (bos at j=0); its output predicts frame j
+ oi = (P[:, None] + fi) # [B,N1]
+ z = s.z_proj(h[bidx.expand(-1, N1), oi.clamp(max=Ltot - 1)]) # [B,N1,zc]
+ eos_logit = s.out_eos(z).squeeze(-1) # predict stop at j==flen
+ eos_t = (fi == flen[:, None]).float(); em = fm
+ eos_loss = F.binary_cross_entropy_with_logits(eos_logit[em].float(), eos_t[em])
+ zm = fi < flen[:, None]; zt = z[:, :-1][zm[:, :-1]] if N1 > 1 else z[:, :0]
+ tgt = frames[zm[:, :-1]] # [M,32]
+ if flow_mult == 0: # round 4: head trained by sample-level KD outside (train_d.py)
+ return z.sum() * 0, eos_loss, z[:, :-1], zm[:, :-1]
+ zt = zt.repeat(flow_mult, 1); tgt = tgt.repeat(flow_mult, 1)
+ t = torch.rand(tgt.shape[0], device=dev); x0 = torch.randn_like(tgt)
+ xt = (1 - t[:, None]) * x0 + t[:, None] * tgt
+ v = s.flow_net(zt, t, xt)
+ flow_loss = F.mse_loss(v.float(), (tgt - x0).float())
+ if return_z: return flow_loss, eos_loss, z[:, :-1], zm[:, :-1] # z predicting frame j, mask j < flen
+ return flow_loss, eos_loss
+
+ def lsd_decode(s, z, x0, steps):
+ cur = x0
+ for i in range(steps):
+ a_, b_ = i / steps, (i + 1) / steps
+ cur = cur + s.flow_net(z, a_ * torch.ones_like(x0[..., :1]), b_ * torch.ones_like(x0[..., :1]), cur) * (b_ - a_)
+ return cur
+
+ @torch.no_grad()
+ def _prefix_x(s, text_ids, ref, dev):
+ parts = [s.embed_proj(s.embed(text_ids.to(dev)[None]))]
+ if ref is not None and len(ref): parts.append(s.speaker_proj_weight(((ref[:s.ref_frames].to(dev) - s.emb_mean) / s.emb_std)[None]))
+ else: parts.append(s.bos_before_voice)
+ parts.append(s.input_linear(s.bos_emb.view(1, 1, -1)))
+ return torch.cat(parts, 1)
+
+ def generate(s, text_ids, ref=None, max_frames=375, temperature=0.3, steps=4, eos_thr=0.0, cfg=1.0, solver='euler'):
+ """Single sentence. text_ids LongTensor [Tt]; ref [R,32] de-normalised latents or None. Returns [n,32] de-normalised.
+ cfg > 1: classifier-free guidance on the flow velocity; the unconditional row keeps only [BOS, lang] (the text_drop form
+ used in training) with the same voice prompt; shared noise; EOS read from the conditional row (as in Hima's sampler)."""
+ dev = s.emb_mean.device
+ xs = [s._prefix_x(text_ids, ref, dev)]
+ if cfg != 1.0: xs.append(s._prefix_x(text_ids[:2], ref, dev))
+ B = len(xs); n = max(x.shape[1] for x in xs) + max_frames + 1
+ caches = [[(torch.zeros(1, blk.self_attn.hkv, n, blk.self_attn.hd, device=dev), torch.zeros(1, blk.self_attn.hkv, n, blk.self_attn.hd, device=dev)) for blk in s.layers] for _ in xs]
+ def run(x, pos, cs):
+ T = x.shape[1]; m = None
+ if T > 1: m = torch.ones(T, pos + T, dtype=torch.bool, device=dev).tril(diagonal=pos)
+ for blk, c in zip(s.layers, cs): x = blk(x, s.cos, s.sin, m, c, pos)
+ return s.z_proj(s.out_norm(x))[:, -1]
+ zs = [run(x, 0, caches[b]) for b, x in enumerate(xs)]; ps = [x.shape[1] for x in xs]; out = []
+ for _ in range(max_frames):
+ if float(s.out_eos(zs[0])) > eos_thr: break
+ cur = temperature ** 0.5 * torch.randn(1, s.lat, device=dev)
+ def vel(x, tt):
+ t = torch.full((1,), tt, device=dev); v = s.flow_net(zs[0], t, x)
+ if B > 1: vu = s.flow_net(zs[1], t, x); v = vu + cfg * (v - vu)
+ return v
+ h = 1.0 / steps
+ if s.lsd: # Hima sampler: per-row LSD decode, CFG on the OUTPUTS with shared noise
+ xc = s.lsd_decode(zs[0], cur, steps)
+ cur = xc if B == 1 else (lambda xu: xu + cfg * (xc - xu))(s.lsd_decode(zs[1], cur, steps))
+ steps_ = 0
+ else: steps_ = steps
+ for i in range(steps_):
+ if solver == 'euler': cur = cur + h * vel(cur, i * h)
+ elif solver == 'midpoint': cur = cur + h * vel(cur + 0.5 * h * vel(cur, i * h), (i + 0.5) * h)
+ elif solver == 'heun':
+ k1 = vel(cur, i * h); xe = cur + h * k1
+ cur = cur + 0.5 * h * (k1 + vel(xe, (i + 1) * h)) if i < steps - 1 else xe # last step Euler (t=1 not trained)
+ else: raise ValueError(solver)
+ out.append(cur)
+ for b in range(B): zs[b] = run(s.input_linear(cur[:, None]), ps[b], caches[b]); ps[b] += 1
+ if not out: return torch.zeros(0, s.lat)
+ return (torch.cat(out, 0) * s.emb_std + s.emb_mean).cpu()
+
+CONFIGS = {'A': {}, 'Cp': dict(d=320, L=8, hq=5, hkv=1, hd=64, ff=640, fw=256, fdepth=5),
+ 'DA': dict(zc=576, fw=512, fdepth=6, lsd=True), 'DCp': dict(d=320, L=8, hq=5, hkv=1, hd=64, ff=640, zc=576, fw=512, fdepth=6, lsd=True)} # Cp = plain (non-looped) ~9.76M capacity probe
+def n_params(m): return sum(p.numel() for p in m.parameters()) + sum(b.numel() for n, b in m.named_buffers() if n in ('emb_mean', 'emb_std'))
+if __name__ == '__main__':
+ m = Student(); print('student params (incl. emb_mean/std buffers):', n_params(m))
+ B = 3; text = torch.randint(8, 200, (B, 40)); tlen = torch.tensor([40, 30, 12]); ref = torch.randn(B, 62, 32); rlen = torch.tensor([62, 0, 20])
+ fr = torch.randn(B, 50, 32); flen = torch.tensor([50, 33, 7])
+ fl, el = m.forward_train(text, tlen, ref, rlen, fr, flen); print('losses', float(fl), float(el))
+ print(m.generate(torch.tensor(encode_text('नमस्ते', 'hi')), max_frames=5).shape)
diff --git a/aksharavp_tts/normalize.py b/aksharavp_tts/normalize.py
new file mode 100644
index 0000000000000000000000000000000000000000..be21feebb0f346758e7fe36060530374f4335fa2
--- /dev/null
+++ b/aksharavp_tts/normalize.py
@@ -0,0 +1,2154 @@
+"""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 structured inputs raise NormalizationError before any cleanup.
+"""
+# -*- coding: utf-8 -*-
+import re
+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", "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=11)
+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):
+ 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):
+ # 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.") 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 re.search(r"<\s*(?:/?[A-Za-z_]|[!?])|[{}]|\$\{", t):
+ raise NormalizationError("markup_or_placeholder", "Resolve templates and send plain text, not markup/SSML.")
+ if any((unicodedata.category(c) == "Cc" and c not in "\n\r\t") or unicodedata.category(c) == "Co" for c in t):
+ raise NormalizationError("control_character", "Unsupported control character in text.")
+ # 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,}", "", t)
+ if re.search(r"[0-9]{31,}", t):
+ raise NormalizationError("number_too_long", "Numeric spans are limited to 30 digits.")
+ if 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.")
+ for m in re.finditer(r"(? 30:
+ raise NormalizationError("number_too_long", "Numeric spans are limited to 30 digits.")
+ if not _valid_grouping(m[0].rstrip(",")):
+ raise NormalizationError("invalid_grouping", "Invalid number grouping; send ungrouped digits or standard grouping.")
+ for m in re.finditer(r"(? 59 or int(m[3]) > 59:
+ raise NormalizationError("invalid_duration", "Duration minutes and seconds must be below 60.")
+ 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"(? 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",
+}
+
+# CRM names and acronyms with at least three ASCII letters use initial capitals,
+# even when they occur alone: RAVI -> Ravi, UPI -> Upi, IMPS -> Imps.
+# This intentionally includes known acronyms. One- and two-letter tokens retain
+# their casing. Whole-token boundaries avoid altering mixed-case words or IDs.
+# This is a text policy; improvement in generated audio still needs listening.
+_CAPS_WORD = re.compile(r"(?hello|namaste|theek(?:[ \t]+hai)?|thik|acha|achha|accha|sorry|ji|maaf|"
+ r"हेलो|नमस्ते|ठीक(?:[ \t]*-[ \t]*|[ \t]+)है|ठीक|अच्छा|सॉरी|जी|माफ|माफ़|माफ़|क्षमा)"
+ r"(?=$|[\s,\-–—.!?:;।॥,、…])(?:[ \t]*[,\-–—.!?:;।॥,、…])+[ \t]*", re.IGNORECASE)
+
+
+def opening_policy(text, policy):
+ """Change punctuation only after a listed opening greeting; never global commas."""
+ if policy not in {"preserve", "none", "comma", "hyphen", "drop"}:
+ raise ValueError("unsupported opening policy")
+ if policy == "preserve":
+ return text
+ def replace(m):
+ if policy == "drop":
+ return ""
+ word = re.sub(r"[ \t]*-[ \t]*", " ", m["word"])
+ return word + {"none": " ", "comma": ", ", "hyphen": "- "}[policy]
+ return _OPENING.sub(replace, text, count=1).strip()
+
+
+def _title_case_caps_words(text):
+ """Title-case standalone ALL-CAPS words of three or more letters."""
+ if not isinstance(text, str):
+ return text
+ return _CAPS_WORD.sub(lambda m: m.group(0).capitalize(), text)
+
+
+def _remove_speech_commas_and_hyphens(text):
+ """Remove pause punctuation AFTER structured values have become spoken words.
+
+ Spaces keep adjacent words separate. Unicode dash punctuation includes ASCII
+ hyphens, en/em dashes and nonbreaking hyphens. Do not strip numeric signs or
+ grouping before the locale engine interprets amounts, dates and identifiers.
+ """
+ commas = ",،、,︐︑﹐﹑、"
+ text = "".join(" " if c in commas or c == "\u00ad" or
+ unicodedata.category(c) == "Pd" else c for c in text)
+ return re.sub(r"\s+", " ", text).strip()
+
+
+# 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):
+ 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)(? 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 ((? 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"(? 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"(?]+|www\.[^\s<>]+"
+ # bare domains: example.com, 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)
+ for m in re.finditer(r"(? 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"(? "five hundred to seven hundred rupees"
+ L = self.lang
+ pat = re.compile(
+ rf"(? 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"(? "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_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"|(?= 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"(?= 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"(?{operand})\s*)?(?P<=|>=|≤|≥|<|>)\s*(?P{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"(? "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"(? 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"(? "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"(? चौदह सौ बाईस)
+ 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, spans = {}, []
+ for matcher in (self._m_email, self._m_url):
+ 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
+ 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)
+ matches = self._gather(text)
+ # 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, greeting_policy="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; no language is guessed from shared scripts.
+ """
+ code = resolve_language(language)
+ # Validate options before the cache, so invalid lists cannot raise TypeError.
+ validate_text(text, date_order=date_order, two_digit_year_base=two_digit_year_base, language=code)
+ engine = _engine(code, date_order, two_digit_year_base)
+ text = _title_case_caps_words(text)
+ # Explicit alternatives retain punctuation for isolated staging comparisons.
+ # The default additionally removes commas and hyphens throughout final speech.
+ text = (_HELLO_COMMA.sub(r"\1- ", text) if greeting_policy == "legacy"
+ else opening_policy(text, greeting_policy))
+ spoken = engine.normalize(text)
+ return _remove_speech_commas_and_hyphens(spoken) if greeting_policy == "none" else spoken
+
+
+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/aksharavp_tts/tts.py b/aksharavp_tts/tts.py
new file mode 100644
index 0000000000000000000000000000000000000000..afb5aa63f5d625514d6c69ce15847649b4c4180e
--- /dev/null
+++ b/aksharavp_tts/tts.py
@@ -0,0 +1,163 @@
+"""AksharaVP-17M: Telugu, Hindi and Indian-English text to speech in 17,643,026 parameters.
+
+ from aksharavp_tts import AksharaVP
+ tts = AksharaVP(".") # folder with model.safetensors, config.json, voices.safetensors
+ audio = tts.say("నమస్కారం, మీరు ఎలా ఉన్నారు?", lang="te", voice="Lakshmi")
+ audio = tts.say("नमस्ते, आप कैसे हैं?", lang="hi", clone="my_voice.wav") # needs clone_encoder.safetensors
+ tts.save(audio, "out.wav")
+"""
+import json, os, re
+import numpy as np, torch
+from safetensors.torch import load_file
+from .model import Student, encode_text
+from .normalize import normalize
+
+SAMPLE_RATE = 24000
+LANG_NAMES = {'te': 'Telugu', 'hi': 'Hindi', 'en': 'Indian English'}
+
+
+def _sentences(text, limit=220):
+ parts = [p.strip() for p in re.split(r"(?<=[.!?।॥])\s+", text.strip()) if p.strip()]
+ out = []
+ for p in parts:
+ if out and len(out[-1]) + len(p) + 1 <= limit: out[-1] += " " + p
+ else: out.append(p)
+ return out
+
+
+def _frame_limit(norm_text):
+ letters = sum(ch.isalnum() or 0x0900 <= ord(ch) <= 0x0D7F for ch in norm_text)
+ return int(np.ceil((2.0 * 0.092 * letters + 1.0) * 12.5))
+
+
+def _longest_silence(audio, sr=SAMPLE_RATE):
+ audio = np.asarray(audio, np.float32).reshape(-1); w = sr // 10; n = len(audio) // w
+ if n == 0: return 0.0
+ db = 20 * np.log10(np.sqrt((audio[: n * w].reshape(n, w) ** 2).mean(1)) + 1e-9); loud = np.where(db > -55)[0]
+ if len(loud) == 0: return n / 10
+ run = best = 0
+ for v in db[loud[0]:]:
+ run = run + 1 if v <= -55 else 0; best = max(best, run)
+ return best / 10
+
+
+def _build_mimi(cfg_dict):
+ from pocket_tts.models.mimi import build_mimi
+ from pocket_tts.utils.config import MimiConfig
+ from pocket_tts.modules.stateful_module import StatefulModule
+ m = build_mimi(MimiConfig(**cfg_dict))
+ for name, mod in m.named_modules():
+ if isinstance(mod, StatefulModule): mod._module_absolute_name = name
+ return m
+
+
+HIMA_CODEC = {"dtype": "float32", "sample_rate": 24000, "inner_dim": 32, "outer_dim": 512, "channels": 1, "frame_rate": 12.5,
+ "seanet": {"dimension": 512, "channels": 1, "n_filters": 64, "n_residual_layers": 1, "ratios": [6, 5, 4], "kernel_size": 7,
+ "residual_kernel_size": 3, "last_kernel_size": 3, "dilation_base": 2, "pad_mode": "constant", "compress": 2},
+ "transformer": {"d_model": 512, "input_dimension": 512, "output_dimensions": [512], "num_heads": 8, "num_layers": 2,
+ "layer_scale": 0.01, "context": 250, "dim_feedforward": 2048},
+ "quantizer": {"dimension": 32, "output_dimension": 512}}
+
+
+class AksharaVP:
+ def __init__(self, folder=".", device="cpu", state_dict=None, load_clone_encoder=True):
+ self.folder, self.device = folder, torch.device(device)
+ self.config = json.load(open(os.path.join(folder, "config.json")))
+ sc = {k: v for k, v in self.config["student"].items() if k in ("d", "L", "hq", "hkv", "hd", "ff", "fw", "fdepth", "lat", "zc", "rank", "vocab", "ref_frames", "max_len", "lsd")}
+ sd = state_dict if state_dict is not None else load_file(os.path.join(folder, "model.safetensors"))
+ self.student = Student(**sc)
+ self.student.load_state_dict({k[8:]: v for k, v in sd.items() if k.startswith("student.")}, strict=True)
+ self.student.to(self.device).eval()
+ self.mimi = _build_mimi(self.config["decoder_mimi"])
+ dec = {k[5:]: v for k, v in sd.items() if k.startswith("mimi.")}
+ missing, unexpected = self.mimi.load_state_dict(dec, strict=False)
+ assert not unexpected and all(k.startswith(("encoder.", "encoder_transformer.", "downsample.")) for k in missing), (missing, unexpected)
+
+
+ for a in ("encoder", "encoder_transformer", "downsample"): # decoder path only; cloning loads clone_encoder.safetensors
+ if hasattr(self.mimi, a): delattr(self.mimi, a)
+ self.mimi.to(self.device).eval()
+ v = load_file(os.path.join(folder, "voices.safetensors"))
+ self._voices = {k: t.float() for k, t in v.items()}
+ self.voices = {m["name"]: m for m in self.config["voices"]}
+ self._enc = None
+ self._enc_path = os.path.join(folder, "clone_encoder.safetensors")
+ self.can_clone = os.path.exists(self._enc_path)
+ if load_clone_encoder and self.can_clone: self._load_encoder()
+ s = self.config["sampler"]; self.defaults = dict(cfg=s["cfg"], temperature=s["temperature"], steps=s["steps"])
+
+ def _load_encoder(self):
+ if self._enc is None:
+ m = _build_mimi(HIMA_CODEC)
+ e = {k[8:]: v for k, v in load_file(self._enc_path).items()}
+ missing, unexpected = m.load_state_dict(e, strict=False)
+ assert not unexpected and all(k.startswith(("decoder.", "decoder_transformer.", "upsample.", "quantizer.")) for k in missing)
+ self._enc = m.to(self.device).eval()
+ return self._enc
+
+ @torch.no_grad()
+ def voice_from_clip(self, path_or_array, sr=None):
+ """Reference latents (<= 62 frames, about 5 s) from a short clip of clear speech."""
+ from scipy.signal import resample_poly
+ if isinstance(path_or_array, str):
+ import soundfile as sf
+ x, sr = sf.read(path_or_array, dtype="float32", always_2d=True); x = x.mean(1)
+ else:
+ x = np.asarray(path_or_array, np.float32)
+ if x.ndim > 1: x = x.mean(1)
+ if sr != SAMPLE_RATE:
+ from math import gcd
+ g = gcd(int(sr), SAMPLE_RATE); x = resample_poly(x, SAMPLE_RATE // g, int(sr) // g).astype(np.float32)
+ if len(x) < SAMPLE_RATE * 2: raise ValueError("the reference clip is shorter than 2 seconds")
+ x = x[: SAMPLE_RATE * 10]; x = x[: len(x) // 1920 * 1920]
+ enc = self._load_encoder()
+ return enc.encode_to_latent(torch.from_numpy(x)[None, None].to(self.device)).float()[0][: self.student.ref_frames].cpu()
+
+ def _ref(self, voice, clone):
+ if clone is not None:
+ return clone if isinstance(clone, torch.Tensor) else self.voice_from_clip(clone)
+ if voice is None: return None
+ if voice not in self._voices: raise ValueError(f"unknown voice {voice!r}; built-in voices: {list(self.voices)}")
+ return self._voices[voice]
+
+ @torch.no_grad()
+ def decode(self, frames):
+ from pocket_tts.modules.stateful_module import init_states
+ if len(frames) == 0: return np.zeros(0, np.float32)
+ return self.mimi.decode_from_latent(frames.float()[None].to(self.device), init_states(self.mimi, batch_size=1, sequence_length=10000)).reshape(-1).cpu().numpy()
+
+ @torch.no_grad()
+ def say(self, text, lang="hi", voice=None, clone=None, temperature=None, cfg=None, steps=None, seed=0, pause=0.15, retries=2):
+ """Speech for `text` as float32 at 24 kHz. lang: te | hi | en. voice: a built-in name; clone: a .wav path (or latents) to copy.
+ Defaults (published): cfg 1.25, temperature 0.3, 4 flow steps. Long text is split at sentence ends."""
+ if lang not in LANG_NAMES: raise ValueError("lang must be one of te, hi, en")
+ if voice is None and clone is None: voice = self.config["default_voice"][lang]
+ ref = self._ref(voice, clone)
+ kw = dict(temperature=self.defaults["temperature"] if temperature is None else temperature,
+ cfg=self.defaults["cfg"] if cfg is None else cfg, steps=self.defaults["steps"] if steps is None else steps)
+ if seed is not None: torch.manual_seed(seed)
+ loc = "te" if lang == "te" else "hi" # the training-time normaliser locale (English rows used the Hindi locale)
+ gap = np.zeros(int(pause * SAMPLE_RATE), np.float32); out = []; self.last_retries = 0
+ for part in _sentences(text):
+ norm = normalize(part, language=loc)
+ ids = torch.tensor(encode_text(norm, lang))
+ limit = min(375, _frame_limit(norm)); best = None
+ for attempt in range(retries + 1):
+ fr = self.student.generate(ids, ref, max_frames=limit if retries else 375, **kw) # frames are drawn one by one, so a cap never changes a take that ends in time
+ wav = self.decode(fr); sil = _longest_silence(wav)
+ bad = bool(retries) and (len(fr) >= limit or sil >= 3.0)
+ if best is None or not bad or (best[3] and sil < best[2]): best = (fr, wav, sil, bad)
+ if not bad: break
+ self.last_retries += 1
+ if len(best[0]): out += [best[1], gap]
+ audio = np.concatenate(out[:-1]) if out else np.zeros(0, np.float32)
+ peak = float(np.abs(audio).max()) if len(audio) else 0.0
+ return audio * (0.97 / peak) if peak > 0.97 else audio
+
+ @staticmethod
+ def save(audio, path):
+ import soundfile as sf
+ sf.write(path, audio, SAMPLE_RATE)
+
+ def n_params(self):
+ return sum(p.numel() for p in self.student.parameters()) + self.student.emb_mean.numel() + self.student.emb_std.numel() + sum(p.numel() for p in self.mimi.parameters())
diff --git a/assets/architecture.png b/assets/architecture.png
new file mode 100644
index 0000000000000000000000000000000000000000..62db15023d270cfac938f8473a9ab28b346fd83b
--- /dev/null
+++ b/assets/architecture.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:037087228a0c9d14db88433e824423a71fd61dd61d4f7fba3a99011c26b99033
+size 334682
diff --git a/assets/architecture.svg b/assets/architecture.svg
new file mode 100644
index 0000000000000000000000000000000000000000..c3a8f90400874a2922f1a4f648df94208eeef8e4
--- /dev/null
+++ b/assets/architecture.svg
@@ -0,0 +1,21 @@
+
+
+
+
+
+
+How AksharaVP-17M speaks
+Autoregressive over continuous 32-d audio latents (12.5 frames/s). Every number is counted from the released weights.
+Text Telugu · Devanagari · Latin 256-symbol shared akshara table
+Voice prompt up to 62 latent frames (~5 s) 12 built-in voices or a clip
+Clone encoder (optional) 9,749,024 params only for zero-shot cloning
+Transformer backbone 8 layers · d320 · GQA 5q/1kv 5,496,417 params incl. embeddings + EOS
+Flow-map head MLP-AdaLN 512×6 · 2 time inputs 9,529,376 params · 4 steps/frame
+Latent frame 32-d · 80 ms fed back in (autoregressive)
+Mimi decoder Kyutai Pocket TTS 7M 2,617,233 params
+24 kHz audio mono waveform
+
+
+
+Speaking path: 15,025,793 (backbone + head + embeddings) + 2,617,233 (decoder) = 17,643,026 parameters
+EOS is predicted from the backbone state; classifier-free guidance 1.25, temperature 0.3.
\ No newline at end of file
diff --git a/assets/banner.gif b/assets/banner.gif
new file mode 100644
index 0000000000000000000000000000000000000000..ca1a0d1cafecce6d2754fbd251f6d0a772dd9be2
--- /dev/null
+++ b/assets/banner.gif
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:77d10a46bad7b70792e3026f43c3750c8f8841e06e0382dd060d10c71ed7feb3
+size 459043
diff --git a/assets/banner.png b/assets/banner.png
new file mode 100644
index 0000000000000000000000000000000000000000..e15f682afde37ca22872d1c4316538813ea481fa
--- /dev/null
+++ b/assets/banner.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:f93835e619ab21a9bdcb2fd727ab4b584a88350299c89913127e5e4892113801
+size 455818
diff --git a/assets/banner.svg b/assets/banner.svg
new file mode 100644
index 0000000000000000000000000000000000000000..3136720ac8d9e32108582cbeb1a9cb4a812eeb5d
--- /dev/null
+++ b/assets/banner.svg
@@ -0,0 +1,20 @@
+
+
+
+
+
+
+TEXT · TO · SPEECH
+AksharaVP-17M
+Telugu · Hindi · Indian English — one checkpoint,
+built-in voices and zero-shot voice cloning.
+
+17,643,026 params
+70.6 MB fp32
+CPU · GGUF
+FLEURS dev character error rate: te 6.04% · hi 4.57% · en 4.37%
+24 kHz audio · 12.5 latent frames per second · 4 flow steps per frame
+
+
+
+నమస్కారం TELUGU नमस्ते HINDI Hello INDIAN ENGLISH
\ No newline at end of file
diff --git a/assets/landscape.png b/assets/landscape.png
new file mode 100644
index 0000000000000000000000000000000000000000..6f11132a262c7fbb8764c9b7f3234e58fb7f6e3b
--- /dev/null
+++ b/assets/landscape.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:c01ca8155410d2949c2013a2ab4d71ba2c4d270466ca008011b06520ce8e4a52
+size 217425
diff --git a/assets/landscape.svg b/assets/landscape.svg
new file mode 100644
index 0000000000000000000000000000000000000000..1e6d102003d370f620089300a5cb8a318b17cdce
--- /dev/null
+++ b/assets/landscape.svg
@@ -0,0 +1,7 @@
+
+
+
+
+Open TTS that speak Telugu + Hindi + English from one checkpoint and clone voices
+Parameter counts from each repository's safetensors metadata on the Hugging Face Hub (checked 17 Nov 2026). Sizes only — not a quality ranking.
+AksharaVP-17M + clone encoder this release 27.4M Pravega Pocket TTS dheeyantra/pravega-pocket-tts 121.8M DhVaani-0.5 ARTPARK-IISc/DhVaani-0.5 122.8M IndicF5 ai4bharat/IndicF5 350.7M AksharaVP is shown with its optional clone encoder (27,392,050); without cloning, the speaking path is 17,643,026.
\ No newline at end of file
diff --git a/assets/params.png b/assets/params.png
new file mode 100644
index 0000000000000000000000000000000000000000..44ac2eda1bbfb636ace884e41a98d86ae535942c
--- /dev/null
+++ b/assets/params.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:9365a2118b6559baa4f3e932c5ce6ff2158eb0053e562129670a10605b08fdc5
+size 125577
diff --git a/assets/params.svg b/assets/params.svg
new file mode 100644
index 0000000000000000000000000000000000000000..2ff2fcb04b63d2badf813ff16c6c447d63bd2ccd
--- /dev/null
+++ b/assets/params.svg
@@ -0,0 +1,7 @@
+
+
+
+
+Where the 17,643,026 parameters go
+One checkpoint for all three languages. The optional clone encoder (9,749,024) is not part of this count.
+Flow-map head 9,529,376 · 54.0% Transformer layers 5,253,120 · 29.8% Embeddings, projections, EOS 243,297 · 1.4% Mimi decoder (Kyutai) 2,617,233 · 14.8%
\ No newline at end of file
diff --git a/assets/results.png b/assets/results.png
new file mode 100644
index 0000000000000000000000000000000000000000..0d82c2560d4c9608da248b068c07e4061eb2fd4d
--- /dev/null
+++ b/assets/results.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:7992265fc9a5d83c3c15803d8133e3d1bc46118f67f0fbbf77e3ce428c03cab6
+size 205979
diff --git a/assets/results.svg b/assets/results.svg
new file mode 100644
index 0000000000000000000000000000000000000000..30482faf780a10e576577f171b264dd9e602bd5b
--- /dev/null
+++ b/assets/results.svg
@@ -0,0 +1,7 @@
+
+
+
+
+Measured on FLEURS dev (100 sentences per language)
+Built-in voices, published sampler. White line = 95% bootstrap interval. ASR: facebook/mms-1b-all (CTC); naturalness: UTMOS22-strong.
+Character error rate lower is better Telugu 6.04% Hindi 4.57% Indian English 4.37% Word error rate lower is better Telugu 28.94% Hindi 13.97% Indian English 9.45% UTMOS (naturalness) higher is better · scale 1–5 Telugu 2.64 Hindi 2.73 Indian English 3.19
\ No newline at end of file
diff --git a/assets/speech.gif b/assets/speech.gif
new file mode 100644
index 0000000000000000000000000000000000000000..f55a60d843927c7b2525cb80a1fc2a0b39df24cb
--- /dev/null
+++ b/assets/speech.gif
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:da86f0694983d40a8bac581a1200070df9a03db28a96013e9ae03899f4c3dbf5
+size 275050
diff --git a/assets/speech.svg b/assets/speech.svg
new file mode 100644
index 0000000000000000000000000000000000000000..a3be30a189e70a492d7d6f962623f3a3642be8d8
--- /dev/null
+++ b/assets/speech.svg
@@ -0,0 +1,6 @@
+
+
+
+
+Real AksharaVP-17M output, one checkpoint, three languages
+Waveform envelopes of the released samples (published sampler, seed 0). Listen to them in the Samples section. TELUGU · voice Lakshmi · 5.0 s of audio నమస్కారం! నేను అక్షర, తెలుగు, హిందీ మరియు ఇంగ్లీష్ మాట్లాడగలను. HINDI · voice Meera · 4.9 s of audio नमस्ते! मैं अक्षरा हूँ, और मैं हिंदी, तेलुगु और अंग्रेज़ी बोल सकती हूँ। INDIAN ENGLISH · voice Meera · 4.7 s of audio Hello! I'm a tiny text to speech model that runs on an ordinary laptop processor.
\ No newline at end of file
diff --git a/clone_encoder.safetensors b/clone_encoder.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..f7348a4cf8828d07d5577fce02932d0c7bc62046
--- /dev/null
+++ b/clone_encoder.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:cfc6635ddf519cee20838d2fa8f46928e98e2be2298f7eef2bb49845db7412eb
+size 39001336
diff --git a/config.json b/config.json
new file mode 100644
index 0000000000000000000000000000000000000000..29f64aca59ca927a9ca4909e058247eb69079979
--- /dev/null
+++ b/config.json
@@ -0,0 +1,195 @@
+{
+ "name": "AksharaVP-17M",
+ "architecture": "aksharavp-calm-lsd",
+ "languages": [
+ "te",
+ "hi",
+ "en"
+ ],
+ "params": {
+ "total": 17643026,
+ "student": 15025793,
+ "decoder": 2617233,
+ "clone_encoder_optional": 9749024,
+ "total_with_clone_encoder": 27392050
+ },
+ "student": {
+ "d": 320,
+ "L": 8,
+ "hq": 5,
+ "hkv": 1,
+ "hd": 64,
+ "ff": 640,
+ "zc": 576,
+ "fw": 512,
+ "fdepth": 6,
+ "lsd": true,
+ "lat": 32,
+ "rank": 64,
+ "vocab": 256,
+ "ref_frames": 62,
+ "max_len": 1024
+ },
+ "sampler": {
+ "cfg": 1.25,
+ "temperature": 0.3,
+ "steps": 4,
+ "max_frames": 375,
+ "frame_rate_hz": 12.5,
+ "sample_rate": 24000
+ },
+ "decoder_mimi": {
+ "dtype": "float32",
+ "sample_rate": 24000,
+ "inner_dim": 32,
+ "outer_dim": 128,
+ "channels": 1,
+ "frame_rate": 12.5,
+ "seanet": {
+ "dimension": 512,
+ "channels": 1,
+ "n_filters": 64,
+ "n_residual_layers": 1,
+ "ratios": [
+ 6,
+ 5,
+ 4
+ ],
+ "kernel_size": 7,
+ "residual_kernel_size": 3,
+ "last_kernel_size": 3,
+ "dilation_base": 2,
+ "pad_mode": "constant",
+ "compress": 2
+ },
+ "transformer": {
+ "d_model": 512,
+ "num_heads": 8,
+ "num_layers": 2,
+ "layer_scale": 0.01,
+ "context": 250,
+ "dim_feedforward": 2048,
+ "input_dimension": 512,
+ "output_dimensions": [
+ 512
+ ]
+ },
+ "quantizer": {
+ "dimension": 32,
+ "output_dimension": 128
+ },
+ "decoder_seanet": {
+ "dimension": 128,
+ "channels": 1,
+ "n_filters": 32,
+ "n_residual_layers": 1,
+ "ratios": [
+ 6,
+ 5,
+ 4
+ ],
+ "kernel_size": 3,
+ "residual_kernel_size": 3,
+ "last_kernel_size": 3,
+ "dilation_base": 2,
+ "pad_mode": "constant",
+ "compress": 2
+ },
+ "decoder_transformer": {
+ "d_model": 128,
+ "num_heads": 4,
+ "num_layers": 12,
+ "layer_scale": 0.01,
+ "context": 50,
+ "dim_feedforward": 384,
+ "input_dimension": 128,
+ "output_dimensions": [
+ 128
+ ]
+ }
+ },
+ "voices": [
+ {
+ "name": "Meera",
+ "gender": "female",
+ "set": "hi",
+ "frames": 58
+ },
+ {
+ "name": "Sneha",
+ "gender": "female",
+ "set": "hi",
+ "frames": 62
+ },
+ {
+ "name": "Nandini",
+ "gender": "female",
+ "set": "hi",
+ "frames": 62
+ },
+ {
+ "name": "Siddharth",
+ "gender": "male",
+ "set": "hi",
+ "frames": 62
+ },
+ {
+ "name": "Ishaan",
+ "gender": "male",
+ "set": "hi",
+ "frames": 62
+ },
+ {
+ "name": "Nikhil",
+ "gender": "male",
+ "set": "hi",
+ "frames": 61
+ },
+ {
+ "name": "Lakshmi",
+ "gender": "female",
+ "set": "te",
+ "frames": 62
+ },
+ {
+ "name": "Sravani",
+ "gender": "female",
+ "set": "te",
+ "frames": 62
+ },
+ {
+ "name": "Bhavana",
+ "gender": "female",
+ "set": "te",
+ "frames": 56
+ },
+ {
+ "name": "Srinivas",
+ "gender": "male",
+ "set": "te",
+ "frames": 60
+ },
+ {
+ "name": "Karthik",
+ "gender": "male",
+ "set": "te",
+ "frames": 51
+ },
+ {
+ "name": "Pranay",
+ "gender": "male",
+ "set": "te",
+ "frames": 62
+ }
+ ],
+ "default_voice": {
+ "hi": "Meera",
+ "en": "Meera",
+ "te": "Lakshmi"
+ },
+ "checkpoint": {
+ "source": "round-4 DCp last_model.pt",
+ "step": 100026,
+ "sha256": "2cd4456730fa2ec0ac546315df102b5e95f0b44968621040262318db1cafeb78"
+ }
+}
\ No newline at end of file
diff --git a/evaluation/comparison.json b/evaluation/comparison.json
new file mode 100644
index 0000000000000000000000000000000000000000..d5663b592133d30eed6c61445b5b89429686233f
--- /dev/null
+++ b/evaluation/comparison.json
@@ -0,0 +1,167 @@
+{
+ "models": [
+ {
+ "name": "AksharaVP-17M (this model)",
+ "ours": true,
+ "params": 17643026,
+ "langs": "te \u00b7 hi \u00b7 en, one checkpoint",
+ "results": {
+ "te": {
+ "CER": 6.0372,
+ "WER": 28.937,
+ "UTMOS": 2.6385,
+ "n": 100
+ },
+ "hi": {
+ "CER": 4.5652,
+ "WER": 13.9677,
+ "UTMOS": 2.733,
+ "n": 100
+ },
+ "en": {
+ "CER": 4.3683,
+ "WER": 9.4492,
+ "UTMOS": 3.1852,
+ "n": 100
+ }
+ },
+ "source": "baseline/r4_DCp_last_model_cfg1.25_n100_dev.json",
+ "fp32_MB": 70.572104
+ },
+ {
+ "name": "Hima TTS nano (hi + te checkpoints)",
+ "params": 72160162,
+ "langs": "te+en / hi+en, two checkpoints",
+ "results": {
+ "te": {
+ "CER": 6.5378,
+ "WER": 31.4304,
+ "UTMOS": 3.5107,
+ "n": 100
+ },
+ "hi": {
+ "CER": 4.8804,
+ "WER": 15.0589,
+ "UTMOS": 3.5989,
+ "n": 100
+ },
+ "en": {
+ "CER": 5.2879,
+ "WER": 11.4704,
+ "UTMOS": 4.0355,
+ "n": 100
+ }
+ },
+ "source": "baseline/hima_dev100_dev.json, enprobe_hima_dev_dev.json",
+ "fp32_MB": 288.640648
+ },
+ {
+ "name": "Kyutai Pocket TTS (english)",
+ "params": 99752802,
+ "langs": "en only",
+ "results": {
+ "en": {
+ "CER": 2.3513,
+ "WER": 6.0131,
+ "UTMOS": 3.9945,
+ "n": 100
+ }
+ },
+ "source": "baseline/enprobe_pocket_english_dev_dev.json",
+ "fp32_MB": 399.011208
+ },
+ {
+ "name": "Kyutai Pocket TTS english_7m_2026-10",
+ "params": 6862578,
+ "langs": "en only",
+ "results": {
+ "en": {
+ "CER": 1.9856,
+ "WER": 6.3669,
+ "UTMOS": 4.1018,
+ "n": 100
+ }
+ },
+ "source": "baseline/enprobe_pocket_english_7m_2026-10_dev_dev.json",
+ "fp32_MB": 27.450312
+ },
+ {
+ "name": "Kyutai Pocket TTS english_2m_2026-10",
+ "params": 1922846,
+ "langs": "en only",
+ "results": {
+ "en": {
+ "CER": 3.8876,
+ "WER": 9.7019,
+ "UTMOS": 3.4948,
+ "n": 100
+ }
+ },
+ "source": "baseline/enprobe_pocket_english_2m_2026-10_dev_dev.json",
+ "fp32_MB": 7.691384
+ }
+ ],
+ "bootstrap_vs_hima": {
+ "te": {
+ "dCER": [
+ -0.49580305181323964,
+ -1.1323514594333068,
+ 0.16311895580706173,
+ 0.1446
+ ],
+ "dWER": [
+ -2.49111498160341,
+ -4.90516677567037,
+ 0.0,
+ 0.0502
+ ],
+ "dUTMOS": [
+ -0.8718396995882988,
+ -0.9468453193902967,
+ -0.7948288431167604,
+ 0.0
+ ]
+ },
+ "hi": {
+ "dCER": [
+ -0.3148669116968514,
+ -0.9455831255690215,
+ 0.28077730267494283,
+ 0.329
+ ],
+ "dWER": [
+ -1.0746316412427643,
+ -2.6176208315815686,
+ 0.4444543297746145,
+ 0.1762
+ ],
+ "dUTMOS": [
+ -0.8663386421171426,
+ -0.9320238929688931,
+ -0.7976584428250787,
+ 0.0
+ ]
+ },
+ "en": {
+ "dCER": [
+ -0.9211334904211661,
+ -1.8535581172881552,
+ -0.09390450194621545,
+ 0.0272
+ ],
+ "dWER": [
+ -2.029627198937715,
+ -4.158710283657445,
+ -0.14944727561296156,
+ 0.0364
+ ],
+ "dUTMOS": [
+ -0.850278826076746,
+ -0.9350222995281222,
+ -0.7625989204049114,
+ 0.0
+ ]
+ }
+ },
+ "notes": "Notes: Hima TTS nano ships separate Telugu and Hindi checkpoints of 72,160,162 parameters each (English is spoken by the Hindi one; its English row uses that checkpoint). Pocket TTS rows are English-only models speaking with their own (non-Indian) built-in voices, so English accent differs from the Indian voices of the other rows. UTMOS is an English-centric predictor; compare systems within a language column, not across columns."
+}
\ No newline at end of file
diff --git a/evaluation/gguf_parity.json b/evaluation/gguf_parity.json
new file mode 100644
index 0000000000000000000000000000000000000000..a1ff3299843642d40fbe52ee8fab4b80d60151c2
--- /dev/null
+++ b/evaluation/gguf_parity.json
@@ -0,0 +1,48 @@
+{
+ "f32": {
+ "tensor_max_abs_diff": 0.0,
+ "audio": {
+ "hi": {
+ "samples_gguf": 72960,
+ "samples_ref": 72960,
+ "identical": true,
+ "max_abs_audio": 0.0
+ },
+ "te": {
+ "samples_gguf": 76800,
+ "samples_ref": 76800,
+ "identical": true,
+ "max_abs_audio": 0.0
+ },
+ "en": {
+ "samples_gguf": 74880,
+ "samples_ref": 74880,
+ "identical": true,
+ "max_abs_audio": 0.0
+ }
+ }
+ },
+ "f16": {
+ "tensor_max_abs_diff": 0.00717926025390625,
+ "audio": {
+ "hi": {
+ "samples_gguf": 72960,
+ "samples_ref": 72960,
+ "identical": false,
+ "max_abs_audio": 0.013351529836654663
+ },
+ "te": {
+ "samples_gguf": 76800,
+ "samples_ref": 76800,
+ "identical": false,
+ "max_abs_audio": 0.014216159470379353
+ },
+ "en": {
+ "samples_gguf": 74880,
+ "samples_ref": 74880,
+ "identical": false,
+ "max_abs_audio": 0.022888675332069397
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/evaluation/gguf_sizes.json b/evaluation/gguf_sizes.json
new file mode 100644
index 0000000000000000000000000000000000000000..bd450db9cc40300a7f126ee0f1a37fe8a1c6fa0f
--- /dev/null
+++ b/evaluation/gguf_sizes.json
@@ -0,0 +1,16 @@
+{
+ "aksharavp-17m-f32.gguf": {
+ "bytes": 70600512,
+ "MB": 70.6,
+ "sha256": "95dc46c5f5b4b0d58c3d91b49ce683691e2bcb3bda3acdf446bb8df94f8881cf",
+ "tensors": 289,
+ "values": 17643026
+ },
+ "aksharavp-17m-f16.gguf": {
+ "bytes": 35313984,
+ "MB": 35.31,
+ "sha256": "a3d61b7059cbd0be400b3f18692996456794469e24f3dba3e1bb6e56ef5150af",
+ "tensors": 289,
+ "values": 17643026
+ }
+}
\ No newline at end of file
diff --git a/evaluation/numbers.json b/evaluation/numbers.json
new file mode 100644
index 0000000000000000000000000000000000000000..4af4d03a9be476f71226dec89619e8328e855a9a
--- /dev/null
+++ b/evaluation/numbers.json
@@ -0,0 +1,111 @@
+{
+ "params": {
+ "total": 17643026,
+ "student": 15025793,
+ "decoder": 2617233,
+ "clone_encoder_optional": 9749024,
+ "total_with_clone_encoder": 27392050
+ },
+ "ours": {
+ "te": {
+ "CER": {
+ "value": 6.0372,
+ "ci95": [
+ 4.7796,
+ 7.4551
+ ],
+ "n": 100
+ },
+ "WER": {
+ "value": 28.937,
+ "ci95": [
+ 25.6568,
+ 32.4314
+ ],
+ "n": 100
+ },
+ "UTMOS": {
+ "value": 2.6385,
+ "ci95": [
+ 2.5804,
+ 2.6947
+ ],
+ "n": 100
+ }
+ },
+ "hi": {
+ "CER": {
+ "value": 4.5652,
+ "ci95": [
+ 3.7913,
+ 5.3939
+ ],
+ "n": 100
+ },
+ "WER": {
+ "value": 13.9677,
+ "ci95": [
+ 12.2499,
+ 15.9243
+ ],
+ "n": 100
+ },
+ "UTMOS": {
+ "value": 2.733,
+ "ci95": [
+ 2.6629,
+ 2.8027
+ ],
+ "n": 100
+ }
+ },
+ "en": {
+ "CER": {
+ "value": 4.3683,
+ "ci95": [
+ 3.0681,
+ 5.8725
+ ],
+ "n": 100
+ },
+ "WER": {
+ "value": 9.4492,
+ "ci95": [
+ 7.3144,
+ 11.8277
+ ],
+ "n": 100
+ },
+ "UTMOS": {
+ "value": 3.1852,
+ "ci95": [
+ 3.1198,
+ 3.2517
+ ],
+ "n": 100
+ }
+ }
+ },
+ "landscape": [
+ {
+ "name": "AksharaVP-17M + clone encoder",
+ "params": 27392050,
+ "source": "this release"
+ },
+ {
+ "name": "Pravega Pocket TTS",
+ "params": 121790146,
+ "source": "dheeyantra/pravega-pocket-tts"
+ },
+ {
+ "name": "DhVaani-0.5",
+ "params": 122798800,
+ "source": "ARTPARK-IISc/DhVaani-0.5"
+ },
+ {
+ "name": "IndicF5",
+ "params": 350681834,
+ "source": "ai4bharat/IndicF5"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/evaluation/parity_vs_dev_eval_pipeline.json b/evaluation/parity_vs_dev_eval_pipeline.json
new file mode 100644
index 0000000000000000000000000000000000000000..f6aa009b94387818bae4297974c972f204ed66fc
--- /dev/null
+++ b/evaluation/parity_vs_dev_eval_pipeline.json
@@ -0,0 +1,32 @@
+{
+ "hi-dev-000": {
+ "len_pkg": 176640,
+ "len_eval": 176640,
+ "max_abs": 3.0517112463712692e-05
+ },
+ "hi-dev-001": {
+ "len_pkg": 109440,
+ "len_eval": 109440,
+ "max_abs": 3.0516181141138077e-05
+ },
+ "te-dev-000": {
+ "len_pkg": 264960,
+ "len_eval": 264960,
+ "max_abs": 3.051667590625584e-05
+ },
+ "te-dev-001": {
+ "len_pkg": 301440,
+ "len_eval": 301440,
+ "max_abs": 3.051722887903452e-05
+ },
+ "en-dev-000": {
+ "len_pkg": 241920,
+ "len_eval": 241920,
+ "max_abs": 3.0517112463712692e-05
+ },
+ "en-dev-001": {
+ "len_pkg": 136320,
+ "len_eval": 136320,
+ "max_abs": 3.0516646802425385e-05
+ }
+}
\ No newline at end of file
diff --git a/gguf/aksharavp-17m-f16.gguf b/gguf/aksharavp-17m-f16.gguf
new file mode 100644
index 0000000000000000000000000000000000000000..2bd7a031a9616952b7cbb61d3471ad64483f5441
--- /dev/null
+++ b/gguf/aksharavp-17m-f16.gguf
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:a3d61b7059cbd0be400b3f18692996456794469e24f3dba3e1bb6e56ef5150af
+size 35313984
diff --git a/gguf/aksharavp-17m-f32.gguf b/gguf/aksharavp-17m-f32.gguf
new file mode 100644
index 0000000000000000000000000000000000000000..6e3de9c4b0914f8f7372e57251324ebe60007b78
--- /dev/null
+++ b/gguf/aksharavp-17m-f32.gguf
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:95dc46c5f5b4b0d58c3d91b49ce683691e2bcb3bda3acdf446bb8df94f8881cf
+size 70600512
diff --git a/gguf_load.py b/gguf_load.py
new file mode 100644
index 0000000000000000000000000000000000000000..0008471cbc9041230ad307e751965a1e092aee4d
--- /dev/null
+++ b/gguf_load.py
@@ -0,0 +1,47 @@
+"""Load an AksharaVP-17M GGUF weight container back into PyTorch.
+
+The GGUF file is a portable weight container (GGUF v3, written with the `gguf` package): every tensor of model.safetensors
+plus the config and sampler settings as metadata. llama.cpp has no runtime for this TTS architecture; run it with
+the PyTorch code in aksharavp_tts/.
+
+ from gguf_load import load_gguf
+ tts = load_gguf("gguf/aksharavp-17m-f32.gguf") # -> aksharavp_tts.AksharaVP
+ tts.save(tts.say("नमस्ते", lang="hi"), "hi.wav")
+"""
+import json, os, sys, tempfile
+import numpy as np, torch
+from gguf import GGUFReader
+
+
+def read_gguf(path):
+ r = GGUFReader(path)
+ meta = {}
+ for f in r.fields.values():
+ if f.name.startswith("aksharavp.") or f.name.startswith("general."):
+ try: meta[f.name] = f.contents()
+ except Exception: pass
+ sd = {}
+ for t in r.tensors:
+ a = np.array(t.data)
+ shape = [int(x) for x in reversed(t.shape.tolist())] # GGUF stores dims innermost-first
+ sd[t.name] = torch.from_numpy(a.reshape(shape).astype(np.float32).copy())
+ return sd, meta
+
+
+def load_gguf(path, folder=None, device="cpu", load_clone_encoder=True):
+ """folder: the model folder holding voices.safetensors (and clone_encoder.safetensors); defaults to the GGUF's parent's parent."""
+ here = os.path.dirname(os.path.abspath(__file__)); sys.path.insert(0, here)
+ from aksharavp_tts import AksharaVP
+ sd, meta = read_gguf(path)
+ folder = folder or here
+ cfg = json.loads(meta["aksharavp.config_json"])
+ d = tempfile.mkdtemp(); json.dump(cfg, open(os.path.join(d, "config.json"), "w"))
+ for f in ("voices.safetensors", "clone_encoder.safetensors"):
+ if os.path.exists(os.path.join(folder, f)): os.symlink(os.path.join(folder, f), os.path.join(d, f))
+ return AksharaVP(d, device=device, state_dict=sd, load_clone_encoder=load_clone_encoder)
+
+
+if __name__ == "__main__":
+ sd, meta = read_gguf(sys.argv[1])
+ print({k: v for k, v in meta.items() if k != "aksharavp.config_json"})
+ print(len(sd), "tensors,", sum(v.numel() for v in sd.values()), "values")
diff --git a/model.safetensors b/model.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..5793883757adedc22d6c66c131cc925f796623c7
--- /dev/null
+++ b/model.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:e61b2723119755585beb571dda7351285f13ec6c4bc57792c652916a560f8015
+size 70606632
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..ba2c5b17813604655e28c5b21fc7658e1d5174bd
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,7 @@
+torch>=2.5
+numpy
+safetensors
+soundfile
+scipy
+pocket-tts==4.0.1
+gguf>=0.10 # only for gguf_load.py
diff --git a/samples/en_clone.wav b/samples/en_clone.wav
new file mode 100644
index 0000000000000000000000000000000000000000..c5541b03a2f973533c704861e6da9871047a0aef
--- /dev/null
+++ b/samples/en_clone.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:b0fb3439c46abbab99dd0e11b74a4d0ba957beb1f4b61550902be273e1c7d3cd
+size 184364
diff --git a/samples/en_clone_reference.wav b/samples/en_clone_reference.wav
new file mode 100644
index 0000000000000000000000000000000000000000..cd4cef80dd08a96fe999750a0c933661e989a344
--- /dev/null
+++ b/samples/en_clone_reference.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:da7464f62f1a1e2fd7ab0df5d6d120c4140cddbed482805346f1a85ae88cbbf8
+size 276524
diff --git a/samples/en_ishaan.wav b/samples/en_ishaan.wav
new file mode 100644
index 0000000000000000000000000000000000000000..97fb8ac200bdea7f850d38bf977c32b7979c30da
--- /dev/null
+++ b/samples/en_ishaan.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:ed3ae8c122427ee706651c325112813cd23d61d3231e298ade3c63b05ceafaf8
+size 188204
diff --git a/samples/en_meera.wav b/samples/en_meera.wav
new file mode 100644
index 0000000000000000000000000000000000000000..b38f0330ecea894fa1ad7af463bb8ac29a60e9c0
--- /dev/null
+++ b/samples/en_meera.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:d238b75d64cf72b07f7bb4918ebef7a12f6bc54761c53ad12e48ae4fd96a3a46
+size 226604
diff --git a/samples/en_sneha.wav b/samples/en_sneha.wav
new file mode 100644
index 0000000000000000000000000000000000000000..0f460757554fb7bf774c486aa812379e311eb830
--- /dev/null
+++ b/samples/en_sneha.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:fa730adad822c87f1a36bb1f8db7812083c580b249d8a123bc32ef4052b88acc
+size 195884
diff --git a/samples/hi_clone.wav b/samples/hi_clone.wav
new file mode 100644
index 0000000000000000000000000000000000000000..967f334818480eb74e94d12d41073310b4f0ec06
--- /dev/null
+++ b/samples/hi_clone.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:743f07c7fa3eee64c3a57b13fd6f4168c94b6c2dda6525cd2c0b6985c645fbb2
+size 176684
diff --git a/samples/hi_clone_reference.wav b/samples/hi_clone_reference.wav
new file mode 100644
index 0000000000000000000000000000000000000000..3700528785307eacb5cd8abea7f5c135f3df2ab3
--- /dev/null
+++ b/samples/hi_clone_reference.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:4727dda551ea07dc7fccbf8ee384497b94e90bcddc33aecb8fa87bcbe5c6b941
+size 282284
diff --git a/samples/hi_meera.wav b/samples/hi_meera.wav
new file mode 100644
index 0000000000000000000000000000000000000000..9891958851c8b8c02ba102945abc1f3a8b3fc0e6
--- /dev/null
+++ b/samples/hi_meera.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:e7e15d8146c3354dd5d684d0e3c3780d617299e05fd2b70e2f7277ab2679f355
+size 234284
diff --git a/samples/hi_nandini.wav b/samples/hi_nandini.wav
new file mode 100644
index 0000000000000000000000000000000000000000..7bced135b243570d770bec777680dcdf396848de
--- /dev/null
+++ b/samples/hi_nandini.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:bcee823434a00e06d98bd50e995a8ef532ec48a533d8c13e58d569bd7a535237
+size 215084
diff --git a/samples/hi_siddharth.wav b/samples/hi_siddharth.wav
new file mode 100644
index 0000000000000000000000000000000000000000..5028a308936ca34e3ed691cebbca21bc2f744e13
--- /dev/null
+++ b/samples/hi_siddharth.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:a24a6406fe06e37afb1c39cba1f558c15697772abb56c2cdb93d9aa6ad57333c
+size 184364
diff --git a/samples/samples.json b/samples/samples.json
new file mode 100644
index 0000000000000000000000000000000000000000..716709fe2d4afd2b89d93f39e39ee7fedd1f9d3e
--- /dev/null
+++ b/samples/samples.json
@@ -0,0 +1,107 @@
+[
+ {
+ "file": "samples/hi_meera.wav",
+ "lang": "hi",
+ "voice": "Meera",
+ "text": "नमस्ते! मैं अक्षरा हूँ, और मैं हिंदी, तेलुगु और अंग्रेज़ी बोल सकती हूँ।",
+ "seconds": 4.88,
+ "gen_s": 1.89,
+ "retries": 0
+ },
+ {
+ "file": "samples/hi_siddharth.wav",
+ "lang": "hi",
+ "voice": "Siddharth",
+ "text": "कल सुबह दस बजे हमारी मीटिंग है, कृपया समय पर पहुँचिए।",
+ "seconds": 3.84,
+ "gen_s": 1.47,
+ "retries": 0
+ },
+ {
+ "file": "samples/hi_nandini.wav",
+ "lang": "hi",
+ "voice": "Nandini",
+ "text": "बारिश के बाद हवा में मिट्टी की खुशबू कितनी अच्छी लगती है।",
+ "seconds": 4.48,
+ "gen_s": 1.76,
+ "retries": 0
+ },
+ {
+ "file": "samples/te_lakshmi.wav",
+ "lang": "te",
+ "voice": "Lakshmi",
+ "text": "నమస్కారం! నేను అక్షర, తెలుగు, హిందీ మరియు ఇంగ్లీష్ మాట్లాడగలను.",
+ "seconds": 4.96,
+ "gen_s": 1.96,
+ "retries": 0
+ },
+ {
+ "file": "samples/te_srinivas.wav",
+ "lang": "te",
+ "voice": "Srinivas",
+ "text": "రేపు ఉదయం పది గంటలకు మన సమావేశం ఉంది, దయచేసి సమయానికి రండి.",
+ "seconds": 4.0,
+ "gen_s": 1.54,
+ "retries": 0
+ },
+ {
+ "file": "samples/te_sravani.wav",
+ "lang": "te",
+ "voice": "Sravani",
+ "text": "వర్షం తర్వాత మట్టి వాసన ఎంతో హాయిగా ఉంటుంది.",
+ "seconds": 3.76,
+ "gen_s": 1.49,
+ "retries": 0
+ },
+ {
+ "file": "samples/en_meera.wav",
+ "lang": "en",
+ "voice": "Meera",
+ "text": "Hello! I'm a tiny text to speech model that runs on an ordinary laptop processor.",
+ "seconds": 4.72,
+ "gen_s": 1.8,
+ "retries": 0
+ },
+ {
+ "file": "samples/en_ishaan.wav",
+ "lang": "en",
+ "voice": "Ishaan",
+ "text": "Your train to Hyderabad leaves from platform four at nine fifteen.",
+ "seconds": 3.92,
+ "gen_s": 1.49,
+ "retries": 0
+ },
+ {
+ "file": "samples/en_sneha.wav",
+ "lang": "en",
+ "voice": "Sneha",
+ "text": "Small models can still speak clearly, if they are trained with care.",
+ "seconds": 4.08,
+ "gen_s": 1.48,
+ "retries": 0
+ },
+ {
+ "file": "samples/hi_clone.wav",
+ "lang": "hi",
+ "clone_reference": "samples/hi_clone_reference.wav",
+ "text": "यह आवाज़ सिर्फ़ कुछ सेकंड की रिकॉर्डिंग से बनाई गई है।",
+ "seconds": 3.68,
+ "retries": 0
+ },
+ {
+ "file": "samples/te_clone.wav",
+ "lang": "te",
+ "clone_reference": "samples/te_clone_reference.wav",
+ "text": "ఈ గొంతు కేవలం కొన్ని సెకన్ల రికార్డింగ్ నుండి తయారైంది.",
+ "seconds": 3.52,
+ "retries": 0
+ },
+ {
+ "file": "samples/en_clone.wav",
+ "lang": "en",
+ "clone_reference": "samples/en_clone_reference.wav",
+ "text": "This voice was copied from a few seconds of recorded speech.",
+ "seconds": 3.84,
+ "retries": 0
+ }
+]
\ No newline at end of file
diff --git a/samples/te_clone.wav b/samples/te_clone.wav
new file mode 100644
index 0000000000000000000000000000000000000000..e854f3ba52309f23ad6566970363636820f18905
--- /dev/null
+++ b/samples/te_clone.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:464b7b4273233283450bf970b639c3dca5f6ef4282daa75b8aa1fb7f1bc465f4
+size 169004
diff --git a/samples/te_clone_reference.wav b/samples/te_clone_reference.wav
new file mode 100644
index 0000000000000000000000000000000000000000..0d85261b34605d33b11a3470b9414c5e2604ae29
--- /dev/null
+++ b/samples/te_clone_reference.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:d26664788f03a34e39c3512515fc218dd2783046fe022b0f1c350774b3665de0
+size 297644
diff --git a/samples/te_lakshmi.wav b/samples/te_lakshmi.wav
new file mode 100644
index 0000000000000000000000000000000000000000..fe65baeaa1cb58f8537483c70382d73275a877aa
--- /dev/null
+++ b/samples/te_lakshmi.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:ba6310816312aad9bbd0c85ba207e8af8816c35b02ee3bffbde255ade5de6ae9
+size 238124
diff --git a/samples/te_sravani.wav b/samples/te_sravani.wav
new file mode 100644
index 0000000000000000000000000000000000000000..553b0750791d292146de998ae0ac5e5d91d9245c
--- /dev/null
+++ b/samples/te_sravani.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:bf152a80c5f880ab28e07c304aa3a80e44ba6238eb0632142262afe1a77bdc9b
+size 180524
diff --git a/samples/te_srinivas.wav b/samples/te_srinivas.wav
new file mode 100644
index 0000000000000000000000000000000000000000..78c1ad01f1859648174878a8076b1bb4530c88b9
--- /dev/null
+++ b/samples/te_srinivas.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:2916ab4ccdd0834a709c954c042790fa1499d027b5f732d54013726e4a30c6d1
+size 192044
diff --git a/voices.safetensors b/voices.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..b8a6ef451458a62434fd73855bdf4a62c167341e
--- /dev/null
+++ b/voices.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:ad90808a3feb7c259268504da6119b3d41dafc4edf08e6338190052244a783b5
+size 93048