tiny-voca-arabic v2 demo: eight voices
Browse filesFiles changed (14)
- LICENSEAdded+202
- README.md+29-8
- __pycache__/app.cpython-312.pycAdded
- app.pyAdded+157
- catt_tashkeel/LICENSEAdded+202
- catt_tashkeel/__init__.pyAdded+11
- catt_tashkeel/bw2ar.pyAdded+126
- catt_tashkeel/models.pyAdded+350
- catt_tashkeel/tokenizer.pyAdded+158
- catt_tashkeel/utils.pyAdded+139
- requirements.txtAdded+4
- tiny_voca_ar/arabic_frontend.pyAdded+337
- tiny_voca_ar/numbers.pyAdded+75
- tiny_voca_ar/text.pyAdded+138
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.12345678910111213---title: Tiny Voca Arabic V2emoji: 🏆colorFrom: yellowcolorTo: graysdk: gradiosdk_version: 6.32.0python_version: '3.13'app_file: app.pypinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference12345678910111213141516171819202122232425262728293031323334---title: tiny-voca-arabic v2emoji: 🗣️colorFrom: greencolorTo: indigosdk: gradiosdk_version: 6.30.0app_file: app.pypython_version: "3.12"models:- n4ze3m/tiny-vocatags:- text-to-speech- tts- arabic- msa- tiny-voca- onnx- multi-speakershort_description: 4.5M-param eight-voice MSA Arabic TTS on CPU (ONNX)---# tiny-voca-arabic v2 demoModern Standard Arabic text-to-speech with eight voices in four speaking styles (assistant, news, story, promo;one female and one male voice each), from tiny-voca-arabic v2: a 4.5M-parameter model trained from scratch with thearchitecture and training code of [tiny-voca](https://huggingface.co/n4ze3m/tiny-voca) by Muhammed Nazeem([@n4ze3m](https://huggingface.co/n4ze3m)), Apache-2.0.Runs on the Space CPU with ONNX Runtime: numbers to words, CATT diacritization, MSA phoneme rules, then synthesis.Earlier versions: [v0](https://huggingface.co/oddadmix/tiny-voca-arabic) (one voice) and the[v1 demo](https://huggingface.co/spaces/oddadmix/tiny-voca-arabic-v1) (two voices).`catt_tashkeel/` is vendored from [CATT](https://github.com/abjadai/catt) (Apache-2.0) so the Space does not needonnxruntime-gpu; its ONNX weights download on first start. All voices are synthetic.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157"""tiny-voca-arabic v2 demo: Modern Standard Arabic text -> speech in eight voices, on the CPU with ONNX Runtime.
Text pipeline: numbers to words -> CATT diacritization -> rule-based MSA phonemes -> ONNX model.Long text is read sentence by sentence and the audio is joined.
The model files come from the model repository (MODEL_REPO). If it is private, the Space needs a secretHF_TOKEN with read access to it. MODEL_DIR=<folder with model.onnx and model.json> runs from local files instead."""import jsonimport osimport reimport time
os.environ.setdefault("CATT_THREADS", "2")
import gradio as grimport numpy as npimport onnxruntime as ort
from tiny_voca_ar.numbers import expand_numbersfrom tiny_voca_ar.text import NothingToPronounce, phonemizefrom tiny_voca_ar import arabic_frontend
MODEL_REPO = os.environ.get("MODEL_REPO", "oddadmix/tiny-voca-arabic-v2")
def _model_files(): local = os.environ.get("MODEL_DIR") if local: return os.path.join(local, "model.onnx"), os.path.join(local, "model.json") from huggingface_hub import hf_hub_download token = os.environ.get("HF_TOKEN") return tuple(hf_hub_download(MODEL_REPO, f"onnx/{name}", token=token) for name in ("model.onnx", "model.json"))
ONNX_PATH, META_PATH = _model_files()META = json.load(open(META_PATH))RATE, MAX_TOKENS = META["sample_rate"], META["max_tokens"] - 12options = ort.SessionOptions()options.intra_op_num_threads = int(os.environ.get("THREADS", "2"))SESSION = ort.InferenceSession(ONNX_PATH, options, providers=["CPUExecutionProvider"])arabic_frontend.diacritize(["مرحبا"]) # load the diacritizer (downloads its ONNX files on first start)
VOICE_NAMES = { "a000": "مساعدة · Assistant (F)", "am6": "مساعد · Assistant (M)", "nf2": "أخبار · News (F)", "nm2": "أخبار · News (M)", "sf1": "قصص · Story (F)", "sm3": "قصص · Story (M)", "pf4": "إعلان · Promo (F)", "pm2": "إعلان · Promo (M)",}VOICES = {VOICE_NAMES.get(v, v): i for i, v in enumerate(META["voices"])}SENTENCE_END = re.compile(r"(?<=[.!?؟…])\s+(?=\S)")CLAUSE_END = re.compile(r"(?<=[،,;؛:])\s+")MAX_CHARS = 3000
def _run(phones, voice, speed, pitch_shift, pitch_range): one = lambda v: np.array([v], dtype=np.float32) audio, _ = SESSION.run(None, { "tokens": np.array([phones.ids], dtype=np.int64), "stress": np.array([phones.stress], dtype=np.int64), "voice": np.array([voice], dtype=np.int64), "speed": one(speed), "pitch_shift": one(pitch_shift), "pitch_range": one(pitch_range)}) return audio[0]
def _pieces(text): """Split a sentence that is too long for one call: at commas first, then in halves between words.""" parts = [p for p in CLAUSE_END.split(text) if p.strip()] if len(parts) > 1: return parts words = text.split() if len(words) < 2: return [] half = len(words) // 2 return [" ".join(words[:half]), " ".join(words[half:])]
def speak(text, voice_name, speed=1.0, pitch_shift=0.0, pitch_range=1.0): text = (text or "").strip()[:MAX_CHARS] if not text: raise gr.Error("اكتب نصًا أولًا. Type some text first.") if text[-1] not in ".!?؟…": text += "." voice = VOICES.get(voice_name, 0) start = time.perf_counter() waves, diacritized = [], [] gap = np.zeros(int(0.12 * RATE), dtype=np.float32)
def read(piece): try: phones = phonemize(piece) except NothingToPronounce: return if len(phones) <= MAX_TOKENS: waves.extend([_run(phones, voice, speed, pitch_shift * 0.058, pitch_range), gap]) diacritized.append(" ".join(phones.diacritized)) return for part in _pieces(piece): read(part)
for sentence in SENTENCE_END.split(expand_numbers(text)): read(sentence) if not waves: raise gr.Error("لا يوجد نص عربي للقراءة. There is no Arabic text to read.") audio = np.concatenate(waves[:-1]) peak = float(np.abs(audio).max()) if peak > 0: audio = audio * (0.9 / peak) # same playback level for every voice took = time.perf_counter() - start seconds = len(audio) / RATE info = f"{seconds:.1f} s of audio in {took:.2f} s on the CPU ({seconds / took:.0f}× real time, including diacritization)" return (RATE, (audio * 32767).astype(np.int16)), "\n".join(diacritized), info
V = {code: VOICE_NAMES.get(code, code) for code in META["voices"]}FIRST = list(VOICES)[0]EXAMPLES = [ ["مرحبًا بكم، هذا نموذج صغير لتحويل النص إلى كلام باللغة العربية الفصحى.", V["a000"]], ["صباح الخير! كيف يمكنني مساعدتك اليوم؟ هل تبحث عن معلومات حول رحلتك القادمة؟", V["am6"]], ["أعلنت وزارة الصحة اليوم عن افتتاح ثلاثة مستشفيات جديدة في المحافظات الجنوبية، بتكلفة تتجاوز 500 مليون.", V["nf2"]], ["يبلغ عدد سكان المدينة 2,500,000 نسمة، ونسبة الشباب فيها 35%.", V["nm2"]], ["كان يا ما كان، في قديم الزمان، فتاة صغيرة تعيش في بيت على أطراف الغابة.", V["sf1"]], ["وفي صباح اليوم التالي، خرج الصياد إلى البحر كعادته، لكنه لم يكن يعلم ما ينتظره.", V["sm3"]], ["لا تفوّت الفرصة! خصومات تصل إلى خمسين بالمئة على جميع المنتجات، لمدة ثلاثة أيام فقط.", V["pf4"]], ["اكتشف عالمًا جديدًا من الراحة مع تطبيقنا الجديد، حمّله الآن مجانًا!", V["pm2"]],]
with gr.Blocks(title="tiny-voca-arabic v2") as demo: gr.Markdown( "# tiny-voca-arabic v2\n" "A **4.5M-parameter** Modern Standard Arabic text-to-speech model with **eight voices** in four speaking styles " "(assistant, news, story, promo; female and male each), " "trained from scratch and running here on the CPU with ONNX Runtime. Text is diacritized automatically " "(you can also add your own tashkeel), converted to phonemes with MSA rules, then spoken. " "Earlier versions: [v0](https://huggingface.co/oddadmix/tiny-voca-arabic) (one voice) · " "[v1 demo](https://huggingface.co/spaces/oddadmix/tiny-voca-arabic-v1) (two voices) · " "Based on [tiny-voca](https://huggingface.co/n4ze3m/tiny-voca) by Muhammed Nazeem (@n4ze3m): " "same architecture and training code, trained from scratch on Arabic.") with gr.Row(): with gr.Column(): text = gr.Textbox(label="النص (Text)", lines=5, rtl=True, value=EXAMPLES[0][0], max_length=MAX_CHARS) voice = gr.Radio(list(VOICES), value=FIRST, label="الصوت (Voice)") with gr.Accordion("Settings", open=False): speed = gr.Slider(0.6, 1.6, value=1.0, step=0.05, label="Speed") pitch = gr.Slider(-4, 4, value=0, step=0.5, label="Pitch shift (semitones)") prange = gr.Slider(0.0, 2.0, value=1.0, step=0.1, label="Pitch range (intonation)") button = gr.Button("تحدّث · Speak", variant="primary") with gr.Column(): audio = gr.Audio(label="Speech", type="numpy", autoplay=True) info = gr.Markdown() shown = gr.Textbox(label="Diacritized text the model read", rtl=True, lines=3, interactive=False) gr.Examples(EXAMPLES, inputs=[text, voice]) gr.Markdown("All voices are synthetic. Please tell listeners when audio they hear was generated.") button.click(speak, [text, voice, speed, pitch, prange], [audio, shown, info], api_name="speak") text.submit(speak, [text, voice, speed, pitch, prange], [audio, shown, info])
if __name__ == "__main__": demo.queue(default_concurrency_limit=2).launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.1234567891011
"""CATT: Character-based Arabic Tashkeel Transformer package."""
from .models import CATTEncoderDecoder, CATTEncoderOnlyfrom .utils import remove_non_arabic
__version__ = "1.0.2"__author__ = "Faris Alasmary"__email__ = "farisalasmary@gmail.com"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126"""functions to convert Arabic words/text into buckwalter encoding and vice versa"""
import sysimport refrom . import utils
buck2uni = { "'": u"\u0621", # hamza-on-the-line "|": u"\u0622", # madda ">": u"\u0623", # hamza-on-'alif "&": u"\u0624", # hamza-on-waaw "<": u"\u0625", # hamza-under-'alif "}": u"\u0626", # hamza-on-yaa' "A": u"\u0627", # bare 'alif "b": u"\u0628", # baa' "p": u"\u0629", # taa' marbuuTa "t": u"\u062A", # taa' "v": u"\u062B", # thaa' "j": u"\u062C", # jiim "H": u"\u062D", # Haa' "x": u"\u062E", # khaa' "d": u"\u062F", # daal "*": u"\u0630", # dhaal "r": u"\u0631", # raa' "z": u"\u0632", # zaay "s": u"\u0633", # siin "$": u"\u0634", # shiin "S": u"\u0635", # Saad "D": u"\u0636", # Daad "T": u"\u0637", # Taa' "Z": u"\u0638", # Zaa' (DHaa') "E": u"\u0639", # cayn "g": u"\u063A", # ghayn "_": u"\u0640", # taTwiil "f": u"\u0641", # faa' "q": u"\u0642", # qaaf "k": u"\u0643", # kaaf "l": u"\u0644", # laam "m": u"\u0645", # miim "n": u"\u0646", # nuun "h": u"\u0647", # haa' "w": u"\u0648", # waaw "Y": u"\u0649", # 'alif maqSuura "y": u"\u064A", # yaa' "F": u"\u064B", # fatHatayn "N": u"\u064C", # Dammatayn "K": u"\u064D", # kasratayn "a": u"\u064E", # fatHa "u": u"\u064F", # Damma "i": u"\u0650", # kasra "~": u"\u0651", # shaddah "o": u"\u0652", # sukuun "`": u"\u0670", # dagger 'alif "{": u"\u0671", # waSla}
# For a reverse transliteration (Unicode -> Buckwalter), a dictionary# which is the reverse of the above buck2uni is essential.uni2buck = {}
# Iterate through all the items in the buck2uni dict.for (key, value) in buck2uni.items(): # The value from buck2uni becomes a key in uni2buck, and vice # versa for the keys. uni2buck[value] = key
# add special charactersuni2buck[u"\ufefb"] = "lA"uni2buck[u"\ufef7"] = "l>"uni2buck[u"\ufef5"] = "l|"uni2buck[u"\ufef9"] = "l<"
# clean the arabic text from unwanted characters that may cause problem while building the language modeldef clean_text(text): text = re.sub(u"[\ufeff]", "", text, flags=re.UNICODE) # strip Unicode Character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF). For more info, check http://www.fileformat.info/info/unicode/char/feff/index.htm text = utils.remove_non_arabic(text) text = utils.strip_tashkeel(text) text = utils.strip_tatweel(text) return text
# convert a single word into buckwalter and vice versadef transliterate_word(input_word, direction='bw2ar'): output_word = '' # Loop over each character in the string, bw_word. for char in input_word: # Look up current char in the dictionary to get its # respective value. If there is no match, e.g., chars like # spaces, then just stick with the current char without any # conversion. # if type(char) == bytes: # char = char.decode('ascii') if direction == 'bw2ar': #print('in bw2ar') output_word += buck2uni.get(char, char) elif direction == 'ar2bw': #print('in ar2bw') output_word += uni2buck.get(char, char) else: sys.stderr.write('Error: invalid direction!') sys.exit() return output_word
# convert a text into buckwalter and vice versadef transliterate_text(input_text, direction='bw2ar'): output_text = '' for input_word in input_text.split(' '): output_text += transliterate_word(input_word, direction) + ' '
return output_text[:-1] # remove the last space ONLY
if __name__ == '__main__': if len(sys.argv) < 2: sys.stderr.write('Usage: INPUT TEXT | python {} DIRECTION(bw2ar|ar2bw)'.format(sys.argv[1])) exit(1) for line in sys.stdin: line = line if sys.argv[1] == 'bw2ar' else clean_text(line) output_text = transliterate_text(line, direction=str(sys.argv[1])) if output_text.strip() != '': sys.stdout.write('{}\n'.format(output_text.strip()))
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
import osimport mathimport zipfileimport numpy as npimport urllib.requestfrom tqdm import tqdmfrom pathlib import Pathimport onnxruntime as ortfrom abc import ABC, abstractmethodfrom .utils import remove_non_arabicfrom .tokenizer import TashkeelTokenizer
class BaseONNXTashkeel(ABC): """ Base class for ONNX-based Arabic text diacritization models
This abstract base class provides common functionality for Arabic text diacritization using pre-trained ONNX models. """
def __init__(self, encoder_path=None, decoder_path=None, tokenizer=None, auto_preprocess=True, model_type="ed_model"): """ Initialize ONNX Tashkeel model
Args: encoder_path (str, optional): Path to encoder ONNX file decoder_path (str, optional): Path to decoder ONNX file tokenizer (TashkeelTokenizer, optional): Tokenizer instance auto_preprocess (bool): Automatically preprocess text (remove non-Arabic) model_type (str): Type of model ("ed_model" or "eo_model") """ self.tokenizer = tokenizer or TashkeelTokenizer() self.auto_preprocess = auto_preprocess self.src_pad_idx = self.tokenizer.letters_map['<PAD>']
# Set model-specific paths encoder_path, decoder_path = self._get_model_paths( encoder_path, decoder_path, model_type )
# Load ONNX sessions self._load_onnx_sessions(encoder_path, decoder_path)
def _download_models(self, model_type): """Download and extract models if they don't exist""" package_dir = Path(__file__).parent models_dir = package_dir / "onnx_models" model_downloads = { 'ed_model': { 'url': 'https://github.com/abjadai/catt/releases/download/v2/ed_model_onnx.zip', 'extract_dir': models_dir / 'ed_model' }, 'eo_model': { 'url': 'https://github.com/abjadai/catt/releases/download/v2/eo_model_onnx.zip', 'extract_dir': models_dir / 'eo_model' } } if model_type not in model_downloads: raise ValueError(f"Unknown model type: {model_type}") config = model_downloads[model_type] extract_dir = config['extract_dir'] # Check if models already exist encoder_path = extract_dir / "encoder.onnx" decoder_path = extract_dir / "decoder.onnx" if encoder_path.exists() and decoder_path.exists(): return # Models already exist print(f"📥 Downloading {model_type} models...") # Create directories models_dir.mkdir(exist_ok=True) extract_dir.mkdir(exist_ok=True) zip_path = models_dir / f"{model_type}.zip" try: # Download with progress bar def progress_hook(block_num, block_size, total_size): if hasattr(progress_hook, 'pbar'): progress_hook.pbar.update(block_size) else: progress_hook.pbar = tqdm(total=total_size, unit='B', unit_scale=True, desc="Downloading") urllib.request.urlretrieve(config['url'], zip_path, progress_hook) if hasattr(progress_hook, 'pbar'): progress_hook.pbar.close() print(f"📦 Extracting {model_type} models...") # Extract the zip file with zipfile.ZipFile(zip_path, 'r') as zip_ref: zip_ref.extractall(extract_dir) # Remove the zip file after extraction zip_path.unlink() print(f"✅ {model_type} models downloaded and extracted successfully!") except Exception as e: print(f"❌ Failed to download {model_type} models: {e}") # Clean up partial downloads if zip_path.exists(): zip_path.unlink() raise
def _get_model_paths(self, encoder_path, decoder_path, model_type): """Get default model paths if not provided""" if encoder_path is None or decoder_path is None: package_dir = Path(__file__).parent model_dir = package_dir / "onnx_models" / model_type # Check if models exist, download if they don't encoder_file = model_dir / "encoder.onnx" decoder_file = model_dir / "decoder.onnx" if not encoder_file.exists() or not decoder_file.exists(): self._download_models(model_type) encoder_path = encoder_path or str(encoder_file) decoder_path = decoder_path or str(decoder_file) return encoder_path, decoder_path
def _load_onnx_sessions(self, encoder_path, decoder_path): """Load ONNX runtime sessions""" if not os.path.exists(encoder_path): raise FileNotFoundError(f"Encoder ONNX file not found: {encoder_path}") if not os.path.exists(decoder_path): raise FileNotFoundError(f"Decoder ONNX file not found: {decoder_path}")
so = ort.SessionOptions() so.intra_op_num_threads = int(os.environ.get("CATT_THREADS", "0")); so.inter_op_num_threads = 1 self.encoder_session = ort.InferenceSession(encoder_path, so) self.decoder_session = ort.InferenceSession(decoder_path, so) print("✅ Loaded model successfully!")
def _preprocess_text(self, text): """Preprocess text if auto_preprocess is enabled""" return remove_non_arabic(text) if self.auto_preprocess else text
def _make_pad_mask(self, q, k, q_pad_idx, k_pad_idx): """Create padding mask (numpy version)""" len_q, len_k = q.shape[1], k.shape[1] k_mask = (k != k_pad_idx).reshape(-1, 1, 1, len_k) k_mask = np.repeat(k_mask, len_q, axis=2) q_mask = (q != q_pad_idx).reshape(-1, 1, len_q, 1) q_mask = np.repeat(q_mask, len_k, axis=3) return k_mask & q_mask
def _make_no_peak_mask(self, q, k): """Create no-peak mask (numpy version)""" len_q, len_k = q.shape[1], k.shape[1] return np.tril(np.ones((len_q, len_k))).astype(bool)
def _run_encoder(self, src_np): """Run encoder using ONNX""" src_mask_np = self._make_pad_mask( src_np, src_np, self.src_pad_idx, self.src_pad_idx ).astype(bool)
encoder_inputs = {'src': src_np, 'src_mask': src_mask_np} return self.encoder_session.run(None, encoder_inputs)[0]
def _pad_seq(self, sequences, batch_first=True, padding_value=0.0, prepadding=True): """Pad sequences to same length""" lens = [seq.shape[0] for seq in sequences] max_len = max(lens)
# Create padded array if len(sequences[0].shape) == 1: padded_sequences = np.full((len(sequences), max_len), padding_value, dtype=sequences[0].dtype) else: shape = (len(sequences), max_len) + sequences[0].shape[1:] padded_sequences = np.full(shape, padding_value, dtype=sequences[0].dtype)
# Fill with actual sequence data for i, seq in enumerate(sequences): padded_sequences[i, :lens[i]] = seq
if prepadding: for i in range(len(lens)): padded_sequences[i] = np.roll(padded_sequences[i], max_len - lens[i], axis=0)
if not batch_first: padded_sequences = padded_sequences.transpose(1, 0, *range(2, padded_sequences.ndim))
return padded_sequences
def _get_batches(self, X, batch_size=16): """Generate batches from list""" num_batches = math.ceil(len(X) / batch_size) for i in range(num_batches): yield X[i*batch_size : (i+1)*batch_size]
def _prepare_batch_input(self, texts_mini): """Prepare input batch for processing""" input_ids_list = [] for text in texts_mini: input_ids, _ = self.tokenizer.encode(text, test_match=False) input_ids_list.append(input_ids)
return self._pad_seq( input_ids_list, batch_first=True, padding_value=self.tokenizer.letters_map['<PAD>'], prepadding=False )
def _apply_space_mask(self, predictions, input_ids): """Apply space masking to predictions""" space_mask = (input_ids == self.tokenizer.letters_map[' ']) predictions[space_mask] = self.tokenizer.tashkeel_map[self.tokenizer.no_tashkeel_tag] return predictions
@abstractmethod def _process_batch(self, batch_input_ids): """Process a batch of input IDs - to be implemented by subclasses""" pass
def do_tashkeel_batch(self, texts, batch_size=16, verbose=True): """ Add tashkeel to multiple Arabic texts
Args: texts (list): List of input Arabic texts batch_size (int): Batch size for processing verbose (bool): Show progress bar
Returns: list: List of texts with tashkeel """ processed_texts = [self._preprocess_text(text) for text in texts] text_with_tashkeel = [] data_iter = self._get_batches(processed_texts, batch_size)
if verbose: num_batches = math.ceil(len(processed_texts) / batch_size) data_iter = tqdm(data_iter, total=num_batches)
for texts_mini in data_iter: batch_input_ids = self._prepare_batch_input(texts_mini) predictions = self._process_batch(batch_input_ids) text_with_tashkeel_mini = self.tokenizer.decode(batch_input_ids, predictions) text_with_tashkeel.extend(text_with_tashkeel_mini)
return text_with_tashkeel
def do_tashkeel(self, text, verbose=True): """ Add tashkeel to Arabic text
Args: text (str): Input Arabic text
Returns: str: Text with tashkeel """ return self.do_tashkeel_batch([text], verbose=False)[0]
class CATTEncoderDecoder(BaseONNXTashkeel): """ ONNX-based Arabic text diacritization model using encoder-decoder architecture """
def __init__(self, encoder_path=None, decoder_path=None, tokenizer=None, auto_preprocess=True): """Initialize encoder-decoder model""" super().__init__(encoder_path, decoder_path, tokenizer, auto_preprocess, "ed_model") self.trg_pad_idx = self.tokenizer.tashkeel_map['<PAD>']
def _run_decoder(self, trg_np, enc_src_np, src_np): """Run decoder using ONNX""" src_trg_mask_np = self._make_pad_mask( trg_np, src_np, self.trg_pad_idx, self.src_pad_idx ).astype(bool)
trg_mask_np = self._make_pad_mask( trg_np, trg_np, self.trg_pad_idx, self.trg_pad_idx ).astype(bool)
no_peak_mask_np = self._make_no_peak_mask(trg_np, trg_np) trg_mask_np = trg_mask_np & no_peak_mask_np
decoder_inputs = { 'trg': trg_np, 'enc_src': enc_src_np, 'trg_mask': trg_mask_np, 'src_trg_mask': src_trg_mask_np }
return self.decoder_session.run(None, decoder_inputs)[0]
def _process_batch(self, batch_input_ids): """Process batch using encoder-decoder with autoregressive decoding""" src = batch_input_ids enc_src = self._run_encoder(src)
# Initialize target with BOS token target_ids = np.array([[self.tokenizer.tashkeel_map['<BOS>']]] * len(batch_input_ids), dtype=np.int64)
# Autoregressive decoding loop for i in range(src.shape[1] - 1): preds = self._run_decoder(target_ids, enc_src, src) next_tokens = np.argmax(preds[:, -1, :], axis=1) target_ids = np.concatenate([target_ids, np.expand_dims(next_tokens, 1)], axis=1)
# Apply space handling logic target_ids = self._apply_space_mask(target_ids, src[:, :target_ids.shape[1]])
return target_ids
class CATTEncoderOnly(BaseONNXTashkeel): """ ONNX-based Arabic text diacritization model using encoder-only architecture """
def __init__(self, encoder_path=None, decoder_path=None, tokenizer=None, auto_preprocess=True): """Initialize encoder-only model""" super().__init__(encoder_path, decoder_path, tokenizer, auto_preprocess, "eo_model")
def _run_decoder(self, enc_src_np): """Run decoder using ONNX""" decoder_inputs = {'enc_src': enc_src_np} return self.decoder_session.run(None, decoder_inputs)[0]
def _process_batch(self, batch_input_ids): """Process batch using encoder-only architecture""" # Remove BOS and EOS tokens batch_input_ids = batch_input_ids[:, 1:-1]
enc_src = self._run_encoder(batch_input_ids) preds = self._run_decoder(enc_src) predictions = np.argmax(preds, axis=-1)
# Apply space masking predictions = self._apply_space_mask(predictions, batch_input_ids)
return predictions123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
import reimport numpy as npfrom . import bw2arfrom .utils import HARAKAT_PAT
class TashkeelTokenizer:
def __init__(self): self.letters = [' ', '$', '&', "'", '*', '<', '>', 'A', 'D', 'E', 'H', 'S', 'T', 'Y', 'Z', 'b', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z', '|', '}' ] self.letters = ['<PAD>', '<BOS>', '<EOS>'] + self.letters + ['<MASK>']
self.no_tashkeel_tag = '<NT>' self.tashkeel_list = ['<NT>', '<SD>', '<SDD>', '<SF>', '<SFF>', '<SK>', '<SKK>', 'F', 'K', 'N', 'a', 'i', 'o', 'u', '~']
self.tashkeel_list = ['<PAD>', '<BOS>', '<EOS>'] + self.tashkeel_list
self.tashkeel_map = {c:i for i,c in enumerate(self.tashkeel_list)} self.letters_map = {c:i for i,c in enumerate(self.letters)} self.inverse_tags = { '~a': '<SF>', # shaddah and fatHa '~u': '<SD>', # shaddah and Damma '~i': '<SK>', # shaddah and kasra '~F': '<SFF>', # shaddah and fatHatayn '~N': '<SDD>', # shaddah and Dammatayn '~K': '<SKK>' # shaddah and kasratayn } self.tags = {v:k for k,v in self.inverse_tags.items()} self.shaddah_last = ['a~', 'u~', 'i~', 'F~', 'N~', 'K~'] self.shaddah_first = ['~a', '~u', '~i', '~F', '~N', '~K'] self.tahkeel_chars = ['F','N','K','a', 'u', 'i', '~', 'o']
def clean_text(self, text): text = re.sub(u'[%s]' % u'\u0640', '', text) # strip tatweel text = text.replace('ٱ', 'ا') return ' '.join(re.sub(u"[^\u0621-\u063A\u0640-\u0652\u0670\u0671\ufefb\ufef7\ufef5\ufef9 ]", " ", text, flags=re.UNICODE).split())
def check_match(self, text_with_tashkeel, letter_n_tashkeel_pairs): text_with_tashkeel = text_with_tashkeel.strip() # test if the reconstructed text with tashkeel is the same as the original one syn_text = self.combine_tashkeel_with_text(letter_n_tashkeel_pairs) return syn_text == text_with_tashkeel or syn_text == self.unify_shaddah_position(text_with_tashkeel)
def unify_shaddah_position(self, text_with_tashkeel): # unify the order of shaddah and the harakah to make shaddah always at the beginning for i in range(len(self.shaddah_first)): text_with_tashkeel = text_with_tashkeel.replace(self.shaddah_last[i], self.shaddah_first[i]) return text_with_tashkeel
def split_tashkeel_from_text(self, text_with_tashkeel, test_match=True): text_with_tashkeel = self.clean_text(text_with_tashkeel) text_with_tashkeel = bw2ar.transliterate_text(text_with_tashkeel, 'ar2bw') text_with_tashkeel = text_with_tashkeel.replace('`', '') # remove dagger 'alif
# unify the order of shaddah and the harakah to make shaddah always at the beginning text_with_tashkeel = self.unify_shaddah_position(text_with_tashkeel)
# remove duplicated harakat for i in range(len(self.tahkeel_chars)): text_with_tashkeel = text_with_tashkeel.replace(self.tahkeel_chars[i]*2, self.tahkeel_chars[i])
letter_n_tashkeel_pairs = [] for i in range(len(text_with_tashkeel)): # go over the whole text # check if the first character is a normal letter and the second character is a tashkeel if i < (len(text_with_tashkeel) - 1) and not text_with_tashkeel[i] in self.tashkeel_list and text_with_tashkeel[i+1] in self.tashkeel_list: # IMPORTANT: check if tashkeel is Shaddah, then there might be another Tashkeel char associated with it. If so, # replace both Shaddah and the Tashkeel chars with the appropriate tag if text_with_tashkeel[i+1] == '~': # IMPORTANT: the following if statement depends on the concept of short circuit!! # The first condition checks if there are still more chars before it access position i+2 # "text_with_tashkeel[i+2]" since it causes "index out of range" exception. Notice that # Shaddah here is put in the first position before the Harakah. if i+2 < len(text_with_tashkeel) and f'~{text_with_tashkeel[i+2]}' in self.inverse_tags: letter_n_tashkeel_pairs.append((text_with_tashkeel[i], self.inverse_tags[f'~{text_with_tashkeel[i+2]}'])) else: # if it is only Shaddah, just add it to the list letter_n_tashkeel_pairs.append((text_with_tashkeel[i], '~')) else: letter_n_tashkeel_pairs.append((text_with_tashkeel[i], text_with_tashkeel[i+1])) # if the character at position i is a normal letter and has no Tashkeel, then add # it with the tag "self.no_tashkeel_tag" # IMPORTANT: this elif block ensures also that there is no two or more consecutive tashkeel other than shaddah elif not text_with_tashkeel[i] in self.tashkeel_list: letter_n_tashkeel_pairs.append((text_with_tashkeel[i], self.no_tashkeel_tag))
if test_match: # test if the split is done correctly by ensuring that we can retrieve back the original text assert self.check_match(text_with_tashkeel, letter_n_tashkeel_pairs) return [('<BOS>', '<BOS>')] + letter_n_tashkeel_pairs + [('<EOS>', '<EOS>')]
def combine_tashkeel_with_text(self, letter_n_tashkeel_pairs): combined_with_tashkeel = [] for letter, tashkeel in letter_n_tashkeel_pairs: combined_with_tashkeel.append(letter) if tashkeel in self.tags: combined_with_tashkeel.append(self.tags[tashkeel]) elif tashkeel != self.no_tashkeel_tag: combined_with_tashkeel.append(tashkeel) text = ''.join(combined_with_tashkeel) return text
def encode(self, text_with_tashkeel, test_match=True): letter_n_tashkeel_pairs = self.split_tashkeel_from_text(text_with_tashkeel, test_match) text, tashkeel = zip(*letter_n_tashkeel_pairs) input_ids = [self.letters_map[c] for c in text] target_ids = [self.tashkeel_map[c] for c in tashkeel] return np.array(input_ids, dtype=np.int64), np.array(target_ids, dtype=np.int64)
def filter_tashkeel(self, tashkeel): tmp = [] for i, t in enumerate(tashkeel): if i != 0 and t == '<BOS>': t = self.no_tashkeel_tag elif i != (len(tashkeel) - 1) and t == '<EOS>': t = self.no_tashkeel_tag tmp.append(t) tashkeel = tmp return tashkeel
def decode(self, input_ids, target_ids): ar_texts = [] for j in range(len(input_ids)): letters = [self.letters[i] for i in input_ids[j]] tashkeel = [self.tashkeel_list[i] for i in target_ids[j]]
letters = list(filter(lambda x: x != '<BOS>' and x != '<EOS>' and x != '<PAD>', letters)) tashkeel = self.filter_tashkeel(tashkeel) tashkeel = list(filter(lambda x: x != '<BOS>' and x != '<EOS>' and x != '<PAD>', tashkeel))
# VERY IMPORTANT NOTE: zip takes min(len(letters), len(tashkeel)) and discard the reset of letters / tashkeels letter_n_tashkeel_pairs = list(zip(letters, tashkeel)) bw_text = self.combine_tashkeel_with_text(letter_n_tashkeel_pairs) ar_text = bw2ar.transliterate_text(bw_text, 'bw2ar') ar_texts.append(ar_text) return ar_texts
def get_tashkeel_with_case_ending(self, text, case_ending=True): text_split = self.split_tashkeel_from_text(text, test_match=False) text_spaces_indecies = [i for i, el in enumerate(text_split) if el == (' ', '<NT>')] new_text_split = [] for i, el in enumerate(text_split): if not case_ending and (i+1) in text_spaces_indecies: el = (el[0], '<NT>') # no case ending new_text_split.append(el) letters, tashkeel = zip(*new_text_split) return letters, tashkeel
def remove_tashkeel(self, text): text = HARAKAT_PAT.sub('', text) text = re.sub(u"[\u064E]", "", text, flags=re.UNICODE) # fattha text = re.sub(u"[\u0671]", "", text, flags=re.UNICODE) # waSla return text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139"""note: this code is used in bw2ar.py file"""
#!/usr/bin/python# -*- coding=utf-8 -*-#---# $Id: arabic.py,v 1.6 2003/04/22 17:18:22 elzubeir Exp $## ------------# Description:# ------------## Arabic codes## (C) Copyright 2003, Arabeyes, Mohammed Elzubeir# (C) Copyright 2019, Faris Abdullah Alasmary# -----------------# Revision Details: (Updated by Revision Control System)# -----------------# $Date: 2003/04/22 17:18:22 $# $Author: elzubeir $# $Revision: 1.6 $# $Source: /home/arabeyes/cvs/projects/duali/pyduali/pyduali/arabic.py,v $## This program is written under the BSD License.#---""" Constants for arabic """import reCOMMA = u'\u060C'SEMICOLON = u'\u061B'QUESTION = u'\u061F'HAMZA = u'\u0621'ALEF_MADDA = u'\u0622'ALEF_HAMZA_ABOVE = u'\u0623'WAW_HAMZA = u'\u0624'ALEF_HAMZA_BELOW = u'\u0625'YEH_HAMZA = u'\u0626'ALEF = u'\u0627'BEH = u'\u0628'TEH_MARBUTA = u'\u0629'TEH = u'\u062a'THEH = u'\u062b'JEEM = u'\u062c'HAH = u'\u062d'KHAH = u'\u062e'DAL = u'\u062f'THAL = u'\u0630'REH = u'\u0631'ZAIN = u'\u0632'SEEN = u'\u0633'SHEEN = u'\u0634'SAD = u'\u0635'DAD = u'\u0636'TAH = u'\u0637'ZAH = u'\u0638'AIN = u'\u0639'GHAIN = u'\u063a'TATWEEL = u'\u0640'FEH = u'\u0641'QAF = u'\u0642'KAF = u'\u0643'LAM = u'\u0644'MEEM = u'\u0645'NOON = u'\u0646'HEH = u'\u0647'WAW = u'\u0648'ALEF_MAKSURA = u'\u0649'YEH = u'\u064a'MADDA_ABOVE = u'\u0653'HAMZA_ABOVE = u'\u0654'HAMZA_BELOW = u'\u0655'ZERO = u'\u0660'ONE = u'\u0661'TWO = u'\u0662'THREE = u'\u0663'FOUR = u'\u0664'FIVE = u'\u0665'SIX = u'\u0666'SEVEN = u'\u0667'EIGHT = u'\u0668'NINE = u'\u0669'PERCENT = u'\u066a'DECIMAL = u'\u066b'THOUSANDS = u'\u066c'STAR = u'\u066d'MINI_ALEF = u'\u0670'ALEF_WASLA = u'\u0671'FULL_STOP = u'\u06d4'BYTE_ORDER_MARK = u'\ufeff'
# DiacriticsFATHATAN = u'\u064b'DAMMATAN = u'\u064c'KASRATAN = u'\u064d'FATHA = u'\u064e'DAMMA = u'\u064f'KASRA = u'\u0650'SHADDA = u'\u0651'SUKUN = u'\u0652'
#LigaturesLAM_ALEF = u'\ufefb'LAM_ALEF_HAMZA_ABOVE = u'\ufef7'LAM_ALEF_HAMZA_BELOW = u'\ufef9'LAM_ALEF_MADDA_ABOVE = u'\ufef5'SIMPLE_LAM_ALEF = u'\u0644\u0627'SIMPLE_LAM_ALEF_HAMZA_ABOVE = u'\u0644\u0623'SIMPLE_LAM_ALEF_HAMZA_BELOW = u'\u0644\u0625'SIMPLE_LAM_ALEF_MADDA_ABOVE = u'\u0644\u0622'
HARAKAT_PAT = re.compile(u"["+u"".join([FATHATAN, DAMMATAN, KASRATAN, FATHA, DAMMA, KASRA, SUKUN, SHADDA])+u"]")HAMZAT_PAT = re.compile(u"["+u"".join([WAW_HAMZA, YEH_HAMZA])+u"]")ALEFAT_PAT = re.compile(u"["+u"".join([ALEF_MADDA, ALEF_HAMZA_ABOVE, ALEF_HAMZA_BELOW, HAMZA_ABOVE, HAMZA_BELOW])+u"]")LAMALEFAT_PAT = re.compile(u"["+u"".join([LAM_ALEF, LAM_ALEF_HAMZA_ABOVE, LAM_ALEF_HAMZA_BELOW,LAM_ALEF_MADDA_ABOVE])+u"]")
def strip_tashkeel(text): text = HARAKAT_PAT.sub('', text) text = re.sub(u"[\u064E]", "", text, flags=re.UNICODE) # fattha text = re.sub(u"[\u0671]", "", text, flags=re.UNICODE) # waSla return text
def strip_tatweel(text): return re.sub(u'[%s]' % TATWEEL, '', text)
# remove removing Tashkeel + removing Tatweel + non Arabic charsdef remove_non_arabic(text): text = strip_tashkeel(text) text = strip_tatweel(text) return ' '.join(re.sub(u"[^\u0621-\u063A\u0641-\u064A ]", " ", text, flags=re.UNICODE).split())
1234onnxruntime>=1.20numpytqdmhuggingface_hub123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337"""MSA front end: undiacritized text -> phonemes + stress, for an Arabic tiny-voca.
text --(split at punctuation)--> phrases --CATT diacritizer--> fully vowelled phrases --rules--> phonemes
Rules (MSA, connected speech): * definite article: sun letters assimilate the l (al+shams -> aʃʃams), moon letters keep it * hamzat al-wasl: pronounced (ʔa / ʔi) only at the start of a phrase, elided inside it; a preceding long vowel is shortened (fiː + l -> fil), a preceding sukun gets a helping vowel (min + al -> mina l) * shadda -> doubled consonant; tanween -> vowel + n; long vowels from ا و ي ى and dagger alif * ta marbuta: t + case vowel inside a phrase, dropped at a pause (pausal -a) * pausal forms (before punctuation / at the end): final short vowel and -un/-in dropped, -an -> aː * emphasis: a / aː next to an emphatic (sˤ dˤ tˤ ðˤ), q, or after x ɣ r -> back ɑ / ɑː; dark l in الله * word stress by syllable weight: superheavy final > heavy penult > antepenultInside a phrase the case ending is marked optional (Phone.optional): the voice sometimes drops it, andthe aligner keeps it only when the audio has it."""from dataclasses import dataclass, fieldimport reimport unicodedata
FATHA, DAMMA, KASRA, SUKUN, SHADDA = "َ", "ُ", "ِ", "ْ", "ّ"FATHATAN, DAMMATAN, KASRATAN, DAGGER = "ً", "ٌ", "ٍ", "ٰ"MARKS = {FATHA, DAMMA, KASRA, SUKUN, SHADDA, FATHATAN, DAMMATAN, KASRATAN, DAGGER}SHORT = {FATHA: "a", DAMMA: "u", KASRA: "i"}TANWEEN = {FATHATAN: "a", DAMMATAN: "u", KASRATAN: "i"}
CONS = {"ء": "ʔ", "أ": "ʔ", "إ": "ʔ", "ؤ": "ʔ", "ئ": "ʔ", "ب": "b", "ت": "t", "ث": "θ", "ج": "dʒ", "ح": "ħ", "خ": "x", "د": "d", "ذ": "ð", "ر": "r", "ز": "z", "س": "s", "ش": "ʃ", "ص": "sˤ", "ض": "dˤ", "ط": "tˤ", "ظ": "ðˤ", "ع": "ʕ", "غ": "ɣ", "ف": "f", "ق": "q", "ك": "k", "ل": "l", "م": "m", "ن": "n", "ه": "h", "و": "w", "ي": "j", "ة": "t"}SUN = set("تثدذرزسشصضطظلن")EMPHATIC = {"sˤ", "dˤ", "tˤ", "ðˤ", "q", "lˤ"}BACKING_BEFORE = {"x", "ɣ", "r"} # back a/aː when they precede the vowelCONSONANTS = sorted(set(CONS.values()) | {"lˤ"})VOWELS = ["a", "i", "u", "aː", "iː", "uː", "ɑ", "ɑː"]LONG = {"aː", "iː", "uː", "ɑː"}VOICELESS = {"ʔ", "t", "θ", "ħ", "x", "s", "ʃ", "sˤ", "tˤ", "f", "q", "k", "h"}PAUSE_PUNCT = "،,.؟?!:;؛…"
# Words whose spelling hides a long vowel (written without the dagger alif) or is irregular.LEXICON = { "هذا": "haːðaː", "هذه": "haːðihi", "هذان": "haːðaːni", "هذين": "haːðajni", "هؤلاء": "haːʔulaːʔi", "ذلك": "ðaːlika", "ذلكم": "ðaːlikum", "تلك": "tilka", "لكن": "laːkin", "لكنه": "laːkinnahu", "لكنها": "laːkinnahaː", "لكنني": "laːkinnaniː", "لكني": "laːkinniː", "أولئك": "ʔulaːʔika", "هكذا": "haːkaðaː", "الله": "ʔallˤaːh", "والله": "wallˤaːhi", "بالله": "billaːhi", "لله": "lillaːhi", "الرحمن": "ʔarraħmaːn", "إله": "ʔilaːh", "طه": "tˤaːhaː", "داود": "daːwuːd", "عمرو": "ʕamr", "مئة": "miʔa", "مائة": "miʔa",}
@dataclassclass Phone: p: str word: int # word index in the utterance (-1 = boundary/punctuation token) stress: int = 0 optional: bool = False # case ending inside a phrase: the aligner may drop it
@dataclassclass Result: phrases: list # diacritized phrases phones: list = field(default_factory=list)
def symbols(self): return [x.p for x in self.phones]
_diacritizer = None
def diacritize(phrases, batch_size=32): global _diacritizer if _diacritizer is None: from catt_tashkeel import CATTEncoderDecoder _diacritizer = CATTEncoderDecoder() todo = [p for p in phrases if p.strip()] out = iter(_diacritizer.do_tashkeel_batch(todo, batch_size=batch_size, verbose=False)) if todo else iter([]) return [next(out) if p.strip() else "" for p in phrases]
def normalize(text): text = unicodedata.normalize("NFC", text).replace("ـ", "") # tatweel text = re.sub(r"[\"'«»“”()\[\]{}<>*_~`]", " ", text) text = re.sub(r"\s*-\s*", " ", text) return re.sub(r"\s+", " ", text).strip()
def split_phrases(text): """[(phrase, punct)] split at pause punctuation; punct is the closing mark or '' at the end.""" parts = re.split(f"([{re.escape(PAUSE_PUNCT)}]+)", normalize(text)) out = [] for i in range(0, len(parts), 2): ph = parts[i].strip(); pu = parts[i + 1][0] if i + 1 < len(parts) else "" if ph: out.append((ph, pu)) elif pu and out: out[-1] = (out[-1][0], out[-1][1] or pu) return out
def letters(word): """[(letter, set_of_marks)] with marks attached to the preceding letter.""" out = [] for ch in word: if ch in MARKS and out: out[-1][1].add(ch) elif "ء" <= ch <= "ي" or ch == "ٱ": out.append([ch, set()]) return out
def strip_marks(s): return "".join(c for c in s if c not in MARKS)
def word_phones(word, first_in_phrase, last_in_phrase): """Phones of one diacritized word -> (list of (phone, optional), starts_with_wasl).""" bare = strip_marks(word) if bare in LEXICON: seq = re.findall(r"dʒ|sˤ|dˤ|tˤ|ðˤ|lˤ|[a-zʔʕħθðʃɣχ]ː?", LEXICON[bare]) if bare.startswith("ال") and not first_in_phrase: seq = seq[2:] if last_in_phrase is False and LEXICON[bare][-1] in "aiu" and len(seq) > 1: return [(s, i == len(seq) - 1) for i, s in enumerate(seq)], bare.startswith("ال") return [(s, False) for s in seq], bare.startswith("ال") L = letters(word) if not L: return [], False out = [] wasl = False i = 0 # proclitics before a definite article: و ف ب ك ل + ال / لل pro = [] while i < len(L) - 2 and L[i][0] in "وفبك" and L[i + 1][0] == "ا" and L[i + 2][0] == "ل" and i == 0: pro.append(L[i]); i += 1; break if i == 0 and len(L) > 2 and L[0][0] == "ل" and L[1][0] == "ل" and not (L[0][1] & {SUKUN}): # لل = li + l(article) out += [("l", False), ("i", False)]; i = 1 art_l = True else: art_l = False for c, m in pro: out += [(CONS[c], False), (SHORT.get(next(iter(m & set(SHORT)), FATHA if c != "ب" else KASRA), "a"), False)] # article if not art_l and i < len(L) - 1 and L[i][0] in "اٱ" and L[i + 1][0] == "ل": nxt = L[i + 2][0] if i + 2 < len(L) else "" if not pro: wasl = True if first_in_phrase: out += [("ʔ", False), ("a", False)] i += 1 # skip the alif if nxt in SUN: i += 1 # silent l; the sun letter carries shadda if L[i][0] != "ل" and SHADDA not in L[i][1]: L[i][1].add(SHADDA) else: out.append(("l", False)); i += 1 elif art_l: i = 1 nxt = L[2][0] if len(L) > 2 else "" if nxt in SUN and nxt != "ل": i = 2 if SHADDA not in L[2][1]: L[2][1].add(SHADDA) else: out.append(("l", False)); i = 2 elif i == 0 and L[0][0] in "اٱ": # other hamzat al-wasl (verbs, ism, ibn ...) wasl = True v = SHORT.get(next(iter(L[0][1] & set(SHORT)), KASRA), "i") if first_in_phrase: out += [("ʔ", False), (v, False)] i = 1 n = len(L) while i < n: c, m = L[i] last = i == n - 1 nxt = L[i + 1] if i + 1 < n else None prev_v = out[-1][0] if out else "" if c == "ا": if prev_v in ("a", "ɑ"): out[-1] = ("aː", False) elif i == n - 1 and len(L) > 1 and L[i - 1][0] == "و": pass # silent alif after plural waw (كتبوا) elif FATHATAN in L[i - 1][1] if i else False: pass else: out.append(("aː", False)) i += 1; continue if c == "آ": out += [("ʔ", False), ("aː", False)]; i += 1; continue if c == "ى": if prev_v in ("a", "ɑ") or not prev_v: if out: out[-1] = ("aː", False) else: out.append(("aː", False)) elif prev_v == "i": out[-1] = ("iː", False) else: out.append(("aː", False)) i += 1; continue if c in "وي" and not (m & (set(SHORT) | set(TANWEEN) | {SHADDA})): longv = {"و": ("u", "uː"), "ي": ("i", "iː")}[c] if prev_v == longv[0]: out[-1] = (longv[1], False); i += 1; continue if prev_v in ("a", "ɑ") and SUKUN in m: out.append((CONS[c], False)); i += 1; continue # diphthong aw / aj if not prev_v or prev_v in VOWELS: if SUKUN not in m and not m and prev_v not in VOWELS: out.append((longv[1], False)); i += 1; continue if c == "ة": if last_in_phrase: i += 1; continue # pausal: ...a(h) cons = "t" else: cons = CONS.get(c) if cons is None: i += 1; continue out.append((cons, False)) if c in "أإ" and not (m & (set(SHORT) | set(TANWEEN) | {SUKUN})) and nxt is not None and nxt[0] not in "اوي": m = m | {KASRA if c == "إ" else FATHA} if SHADDA in m: out.append((cons, False)) if DAGGER in m: out.append(("aː", False)) tv = next(iter(m & set(TANWEEN)), None) sv = next(iter(m & set(SHORT)), None) if tv: v = TANWEEN[tv] if last_in_phrase: if v == "a" and c != "ة": out.append(("aː", False)) else: out += [(v, True), ("n", True)] elif sv: v = SHORT[sv] if last and last_in_phrase: pass # pausal: final short vowel dropped else: out.append((v, last)) i += 1 return out, wasl
def emphasis(seq): """Back a/aː near emphatics. seq: list of phone strings (one word, or the whole phrase).""" out = list(seq) for k, p in enumerate(out): if p not in ("a", "aː"): continue prev = out[k - 1] if k else ""; nxt = out[k + 1] if k + 1 < len(out) else "" nxt2 = out[k + 2] if k + 2 < len(out) else "" if prev in EMPHATIC or prev in BACKING_BEFORE or nxt in EMPHATIC or (nxt not in VOWELS and nxt2 in EMPHATIC and False): out[k] = "ɑ" if p == "a" else "ɑː" return out
def syllable_stress(phones): """Index (into phones) of the stressed vowel of one word, by MSA syllable weight.""" vidx = [k for k, p in enumerate(phones) if p in VOWELS] if not vidx: return None syl = [] # (vowel index, weight) weight: 1 light, 2 heavy, 3 superheavy for j, k in enumerate(vidx): end = vidx[j + 1] - 1 if j + 1 < len(vidx) else len(phones) # next onset consonant belongs to next syllable coda = (vidx[j + 1] - k - 2) if j + 1 < len(vidx) else (len(phones) - k - 1) coda = max(coda, 0) w = (2 if phones[k] in LONG else 1) + min(coda, 2) - (0 if phones[k] in LONG or coda else 0) w = 1 if (phones[k] not in LONG and coda == 0) else (2 if (phones[k] in LONG) + coda == 1 else 3) syl.append((k, w)) if len(syl) == 1: return syl[0][0] if syl[-1][1] == 3: return syl[-1][0] if syl[-2][1] >= 2 or len(syl) == 2: return syl[-2][0] return syl[-3][0]
def phonemize(text, diacritized=None): """text -> Result. Tokens: '^' start, '$' end, ' ' word boundary, punctuation marks, phones.""" parts = split_phrases(text) dia = diacritized if diacritized is not None else diacritize([p for p, _ in parts]) res = Result(phrases=dia) res.phones.append(Phone("^", -1)) wi = 0 for (phrase, punct), dphrase in zip(parts, dia): words = dphrase.split() pw = [] for j, w in enumerate(words): seq, wasl = word_phones(w, j == 0, j == len(words) - 1) pw.append([seq, wasl]) # elision across words: wasl after a long vowel shortens it; after a consonant add a helping vowel for j in range(1, len(pw)): if pw[j][1] and pw[j - 1][0]: prev = pw[j - 1][0] last = prev[-1][0] if last in LONG: prev[-1] = ({"aː": "a", "iː": "i", "uː": "u", "ɑː": "ɑ"}[last], False) elif last not in VOWELS: helper = "u" if strip_marks(words[j - 1]) in ("هم", "أنتم", "لكم", "عليهم", "بكم", "منهم") else \ ("a" if strip_marks(words[j - 1]) == "من" else "i") prev.append((helper, False)) elif prev[-1][1]: prev[-1] = (last, False) # the case vowel carries the liaison: no longer optional for j in range(1, len(pw)): if strip_marks(words[j]) == "الله" and pw[j - 1][0] and pw[j - 1][0][-1][0] == "i": pw[j][0] = [("l" if p == "lˤ" else p, o) for p, o in pw[j][0]] for j, (seq, _) in enumerate(pw): if not seq: continue ps = emphasis([p for p, _ in seq]) st = syllable_stress(ps) if j: res.phones.append(Phone(" ", -1)) for k, (p, (_, opt)) in enumerate(zip(ps, seq)): res.phones.append(Phone(p, wi, 1 if k == st else 0, opt)) wi += 1 res.phones.append(Phone(punct if punct else " ", -1) if punct else Phone(" ", -1)) if res.phones[-1].p == " ": res.phones.pop() res.phones.append(Phone("$", -1)) return res
def show(res): s = [] for x in res.phones: if x.word < 0: s.append({"^": "", "$": "", " ": " "}.get(x.p, f" {x.p} ")) else: s.append(("ˈ" if x.stress else "") + x.p + ("?" if x.optional else "")) return "".join(s).strip()
if __name__ == "__main__": import sys for line in sys.argv[1:] or ["نعم، يمكن أن تقدم لهم قطع صغيرة من الحلويات.", "ابدأ بخطوة صغيرة، مثل ترتيب جدولك في الأسبوع القادم."]: r = phonemize(line) print(line); print(" ", " | ".join(r.phrases)); print(" ", show(r))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475"""Read digits as Modern Standard Arabic words before diacritization.
Cardinals use the masculine nominative form without gender agreement with the counted noun, which ishow numbers are most often read aloud. Handles Western and Arabic-Indic digits, thousands separators,decimals (فاصلة), percent (في المائة) and a leading minus (سالب)."""import re
ONES = ["صفر", "واحد", "اثنان", "ثلاثة", "أربعة", "خمسة", "ستة", "سبعة", "ثمانية", "تسعة"]TEENS = ["عشرة", "أحد عشر", "اثنا عشر", "ثلاثة عشر", "أربعة عشر", "خمسة عشر", "ستة عشر", "سبعة عشر", "ثمانية عشر", "تسعة عشر"]TENS = ["", "", "عشرون", "ثلاثون", "أربعون", "خمسون", "ستون", "سبعون", "ثمانون", "تسعون"]HUNDREDS = ["", "مائة", "مئتان", "ثلاثمائة", "أربعمائة", "خمسمائة", "ستمائة", "سبعمائة", "ثمانمائة", "تسعمائة"]# (value, singular, dual, plural for 3-10)SCALES = [(10 ** 9, "مليار", "ملياران", "مليارات"), (10 ** 6, "مليون", "مليونان", "ملايين"), (1000, "ألف", "ألفان", "آلاف")]INDIC = str.maketrans("٠١٢٣٤٥٦٧٨٩۰۱۲۳۴۵۶۷۸۹", "01234567890123456789")
def _below_1000(n): parts = [] h, rest = divmod(n, 100) if h: parts.append(HUNDREDS[h]) if rest: if rest < 10: parts.append(ONES[rest]) elif rest < 20: parts.append(TEENS[rest - 10]) else: t, o = divmod(rest, 10) parts.append(f"{ONES[o]} و{TENS[t]}" if o else TENS[t]) return " و".join(parts)
def number_words(n): if n == 0: return ONES[0] if n >= 10 ** 12: return " ".join(ONES[int(d)] for d in str(n)) parts = [] for value, one, two, few in SCALES: k, n = divmod(n, value) if not k: continue if k == 1: parts.append(one) elif k == 2: parts.append(two) elif k <= 10: parts.append(f"{_below_1000(k)} {few}") else: parts.append(f"{_below_1000(k)} {one}") if n: parts.append(_below_1000(n)) return " و".join(parts)
_NUMBER = re.compile(r"(-?)(\d{1,3}(?:[,٬]\d{3})+|\d+)(?:[.٫](\d+))?(\s*[%٪])?")
def _read(m): sign, whole, frac, pct = m.groups() out = number_words(int(re.sub(r"[,٬]", "", whole))) if frac: out += " فاصلة " + (number_words(int(frac)) if not frac.startswith("0") else " ".join(ONES[int(d)] for d in frac)) if sign: out = "سالب " + out if pct: out += " في المائة" return f" {out} "
def expand_numbers(text): return re.sub(r"[ \t]+", " ", _NUMBER.sub(_read, text.translate(INDIC))).strip()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138"""Modern Standard Arabic front end: text -> phoneme tokens with a stress feature.
Same interface as the English front end it replaces (text_english.py), so the model, annotationand training code are unchanged. The pipeline is in ``arabic_frontend``:
undiacritized text -> phrases (split at punctuation) -> CATT diacritizer -> MSA rules -> phonemes
* A token is one phoneme; geminates are two identical consonant tokens.* Stress (0/1) is a parallel feature from MSA syllable weight, not a token.* Punctuation, word boundaries and the utterance edges are tokens that may last zero frames.* ``Phonemized.optional`` marks case endings inside a phrase. The aligner keeps one only when the recording has it; inference always says them (formal MSA).
Diacritizations can be served from a cache (``TINY_VOCA_DIACRITIZED`` = jsonl of {"p", "d"}) soannotation and training use exactly the vowels that were aligned."""
from dataclasses import dataclass, fieldimport hashlibimport jsonimport os
from . import arabic_frontend as af
FRONTEND_VERSION = "ar-1"FRONTENDS = ("arabic",)FRONTEND_VARIABLE = "TINY_VOCA_FRONTEND"_frontend = "arabic"
PAD, BOS, EOS, SP, UNK = "<pad>", "<bos>", "<eos>", "<sp>", "<unk>"SPECIALS = (PAD, BOS, EOS, SP, UNK)PUNCTUATION = (",", ".", "?", "!", ";", ":", "…")_PUNCT_MAP = {"،": ",", ",": ",", ".": ".", "؟": "?", "?": "?", "!": "!", "؛": ";", ";": ";", ":": ":", "…": "…"}CONSONANTS = tuple(af.CONSONANTS)VOWELS = tuple(af.VOWELS)PHONES = CONSONANTS + VOWELS# Append-only: changing the order or removing a symbol invalidates checkpoints.SYMBOLS = SPECIALS + PUNCTUATION + PHONESSYMBOL_TO_ID = {symbol: index for index, symbol in enumerate(SYMBOLS)}PHONE_SET = frozenset(PHONES)PHONE_IDS = frozenset(SYMBOL_TO_ID[p] for p in PHONES) | {SYMBOL_TO_ID[UNK]}VOICELESS = frozenset(af.VOICELESS)VOWEL_SET = frozenset(VOWELS)
class NothingToPronounce(ValueError): """The text has no Arabic word to say."""
@dataclass(frozen=True)class Phonemized: symbols: tuple ids: tuple stress: tuple unknown: tuple optional: tuple = field(default=()) diacritized: tuple = field(default=())
def __len__(self): return len(self.ids)
def frontend(): return _frontend
def set_frontend(name): if name not in FRONTENDS: raise ValueError(f"front end must be one of {FRONTENDS}, not {name!r}")
def frontend_identity(): return {"frontend_version": FRONTEND_VERSION, "phonemizer": "tiny_voca.arabic_frontend", "diacritizer": "catt-tashkeel ed_model v2", "symbols": list(SYMBOLS)}
def frontend_runtime(): return {"phonemizer": hashlib.sha256(open(af.__file__, "rb").read()).hexdigest()}
def frontend_fingerprint(): return hashlib.sha256(json.dumps(frontend_identity(), sort_keys=True, ensure_ascii=False).encode()).hexdigest()
_cache = None
def _diacritized(phrases): global _cache if _cache is None: _cache = {} path = os.environ.get("TINY_VOCA_DIACRITIZED") if path and os.path.exists(path): with open(path, encoding="utf-8") as f: for line in f: r = json.loads(line); _cache[r["p"]] = r["d"] missing = [p for p in phrases if p not in _cache] if missing: for p, d in zip(missing, af.diacritize(missing)): _cache[p] = d return [_cache[p] for p in phrases]
def phonemize(text): if not isinstance(text, str) or not text.strip(): raise ValueError("text must not be empty") parts = af.split_phrases(text) if not parts: raise NothingToPronounce("the text has nothing to pronounce") res = af.phonemize(text, _diacritized([p for p, _ in parts])) symbols, stress, optional = [], [], [] for x in res.phones: if x.p == "^": s = BOS elif x.p == "$": s = EOS elif x.p == " ": s = SP elif x.word < 0: s = _PUNCT_MAP.get(x.p, ",") else: s = x.p if s in PUNCTUATION and symbols and symbols[-1] in PUNCTUATION: continue if s in PUNCTUATION and symbols and symbols[-1] == SP: symbols.pop(); stress.pop(); optional.pop() symbols.append(s); stress.append(x.stress); optional.append(int(x.optional)) if not any(s in PHONE_SET for s in symbols): raise NothingToPronounce("the text has nothing to pronounce") return Phonemized(tuple(symbols), tuple(SYMBOL_TO_ID[s] for s in symbols), tuple(stress), (), tuple(optional), tuple(res.phrases))
def drop(ph, remove): """Copy of ``ph`` without the token positions in ``remove`` (dropped optional case endings).""" remove = set(remove) keep = [i for i in range(len(ph.symbols)) if i not in remove] pick = lambda seq: tuple(seq[i] for i in keep) if seq else seq return Phonemized(pick(ph.symbols), pick(ph.ids), pick(ph.stress), ph.unknown, pick(ph.optional), ph.diacritized)
def is_phone(token_ids): return [int(i) in PHONE_IDS for i in token_ids]LICENSEAdded+202
README.md+29-8
__pycache__/app.cpython-312.pycAdded
app.pyAdded+157
catt_tashkeel/LICENSEAdded+202
catt_tashkeel/__init__.pyAdded+11
catt_tashkeel/bw2ar.pyAdded+126
catt_tashkeel/models.pyAdded+350
catt_tashkeel/tokenizer.pyAdded+158
catt_tashkeel/utils.pyAdded+139
requirements.txtAdded+4
tiny_voca_ar/arabic_frontend.pyAdded+337
tiny_voca_ar/numbers.pyAdded+75
tiny_voca_ar/text.pyAdded+138