"""Jata-Talk-Mini: type plain Arabic (no tashkeel), get speech. Runs on CPU. Command line: python speak.py "هلا والله، وش أخبارك؟" --voice Female --output hello.wav From Python: from speak import Voca voca = Voca() voca.save("هلا والله", "hello.wav", voice="Male") audio = voca.speak("هلا والله") # float32 numpy array, 24 kHz Voices: Male, Female. """ import argparse import json import os from pathlib import Path import re import sys import time import wave import numpy as np import onnxruntime as ort HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) from jata_talk_mini import arabic # noqa: E402 from jata_talk_mini.text import frontend_fingerprint, phonemize # noqa: E402 ONES = "صفر|واحد|اثنين|ثلاثة|أربعة|خمسة|ستة|سبعة|ثمانية|تسعة".split("|") TEENS = "عشرة|إحدعش|اثنعش|ثلاثطعش|أربعطعش|خمسطعش|ستطعش|سبعطعش|ثمنطعش|تسعطعش".split("|") TENS = "عشرين|ثلاثين|أربعين|خمسين|ستين|سبعين|ثمانين|تسعين".split("|") HUNDREDS = "مية|ميتين|ثلاثمية|أربعمية|خمسمية|ستمية|سبعمية|ثمانمية|تسعمية".split("|") THOUSANDS = "ألف|ألفين|ثلاثة آلاف|أربعة آلاف|خمسة آلاف|ستة آلاف|سبعة آلاف|ثمانية آلاف|تسعة آلاف|عشرة آلاف".split("|") HOURS = "وحدة|ثنتين|ثلاث|أربع|خمس|ست|سبع|ثمان|تسع|عشر|إحدعش|اثنعش".split("|") NUMBER = re.compile(r"\d+(?:[.,٫]\d+)?") CLOCK = re.compile(r"\b(\d{1,2}):(\d{2})\b") SENTENCE_END = re.compile(r"(?<=[.!?؟…])\s+") CLAUSE_END = re.compile(r"(?<=[,;:،؛])\s+") MAX_TOKENS = 500 def number_words(n): """Whole number -> Saudi spoken words (خمسمية وخمسة وعشرين).""" if n < 10: return ONES[n] if n < 20: return TEENS[n - 10] if n < 100: return TENS[n // 10 - 2] if n % 10 == 0 else f"{ONES[n % 10]} و{TENS[n // 10 - 2]}" if n < 1000: head = HUNDREDS[n // 100 - 1] return head if n % 100 == 0 else f"{head} و{number_words(n % 100)}" if n < 1_000_000: thousands = n // 1000 head = THOUSANDS[thousands - 1] if thousands <= 10 else f"{number_words(thousands)} ألف" return head if n % 1000 == 0 else f"{head} و{number_words(n % 1000)}" millions = n // 1_000_000 head = "مليون" if millions == 1 else "مليونين" if millions == 2 else f"{number_words(millions)} مليون" return head if n % 1_000_000 == 0 else f"{head} و{number_words(n % 1_000_000)}" def spell_numbers(text): """Digits -> words. Long digit runs (phone numbers, codes) are read one digit at a time.""" text = text.translate(str.maketrans("٠١٢٣٤٥٦٧٨٩۰۱۲۳۴۵۶۷۸۹", "01234567890123456789")) def clock(match): hour, minute = int(match.group(1)), int(match.group(2)) if hour > 23 or minute > 59: return match.group() if minute == 45: hour, tail = hour + 1, " إلا ربع" else: tail = {0: "", 15: " وربع", 30: " ونص", 20: " وثلث"}.get(minute, f" و{number_words(minute)} دقيقة") return f" {HOURS[(hour - 1) % 12]}{tail} " def say(match): whole, fraction = (re.split(r"[.,٫]", match.group()) + [""])[:2] if len(whole) > 9 or (len(whole) > 1 and whole.startswith("0")): spoken = " ".join(ONES[int(d)] for d in whole) else: spoken = number_words(int(whole)) if fraction: spoken += " فاصلة " + (number_words(int(fraction)) if not fraction.startswith("0") else " ".join(ONES[int(d)] for d in fraction)) return f" {spoken} " return NUMBER.sub(say, CLOCK.sub(clock, text)) def clean(text): """Keep what the model can read: Arabic letters, spaces and punctuation.""" text = spell_numbers(text).replace("%", " بالمية ") kept = "".join(c if (arabic.WORD.match(c) or c in " .,!?;:،؛؟…\n") else " " for c in text) return " ".join(kept.split()) class Voca: def __init__(self, model=HERE / "models" / "jata-talk-mini.onnx", threads=min(4, os.cpu_count() or 1)): options = ort.SessionOptions() options.intra_op_num_threads = threads options.inter_op_num_threads = 1 options.log_severity_level = 3 # optional inputs have defaults; no need to warn about them self.session = ort.InferenceSession(str(model), options, providers=["CPUExecutionProvider"]) settings = json.loads(self.session.get_modelmeta().custom_metadata_map["jata_talk_mini"]) self.meta, self.vowel_meta = settings["tts"], settings["vowels"] if self.meta["frontend_fingerprint"] != frontend_fingerprint(): raise RuntimeError("the model does not match the text code in jata_talk_mini") self.voices = self.meta["voices"] self.sample_rate = self.meta["sample_rate"] def add_vowels(self, text): """Plain text -> text with the tashkeel the model reads.""" text = arabic.normalize_punctuation(clean(text)) text = "".join(c for c in text if not 0x064B <= ord(c) <= 0x0652 and c != "ٰ") if not text.strip(): return text ids = np.array([[self.vowel_meta["char_ids"].get(c, self.vowel_meta["unknown"]) for c in text]], dtype=np.int64) best = self.session.run(["vowel_logits"], {"chars": ids})[0][0].argmax(-1) labels = self.vowel_meta["labels"] return "".join(c + (labels[b] if arabic.WORD.match(c) else "") for c, b in zip(text, best)) def _pieces(self, text): """Phonemes of each sentence, short enough for one call; long ones are cut at commas, then between words.""" for sentence in SENTENCE_END.split(clean(text)): if any(c.isalpha() for c in sentence): yield from self._fit(sentence) def _fit(self, piece): phones = phonemize(self.add_vowels(piece)) if len(phones.ids) <= MAX_TOKENS: yield phones return parts = CLAUSE_END.split(piece) if len(parts) == 1: words = piece.split(" ") half = (len(words) + 1) // 2 parts = [" ".join(words[:half]), " ".join(words[half:])] for part in parts: yield from self._fit(part) def speak(self, text, voice="Male", speed=1.0): """Plain Arabic text -> float32 audio at ``self.sample_rate``.""" if voice not in self.voices: raise ValueError(f"voice must be one of {self.voices}") audio = [] for phones in self._pieces(text): out = self.session.run(["audio"], { "tokens": np.array([phones.ids], dtype=np.int64), "stress": np.array([phones.stress], dtype=np.int64), "voice": np.array([self.voices.index(voice)], dtype=np.int64), "speed": np.array([speed], dtype=np.float32), "pitch_shift": np.zeros(1, dtype=np.float32), "pitch_range": np.ones(1, dtype=np.float32)}) audio.append(out[0][0]) if not audio: raise ValueError("no Arabic text to read") audio.append(np.zeros(int(0.25 * self.sample_rate), dtype=np.float32)) # so no player cuts the end audio = np.concatenate(audio) peak = float(np.abs(audio).max()) return audio * (0.99 / peak) if peak > 0.99 else audio def save(self, text, path, voice="Male", speed=1.0): audio = self.speak(text, voice, speed) with wave.open(str(path), "wb") as f: f.setnchannels(1) f.setsampwidth(2) f.setframerate(self.sample_rate) f.writeframes((audio * 32767).astype(" ").strip() except EOFError: break if not line: break number += 1 voca.save(line, f"{number}.wav", args.voice, args.speed) print(f"saved {number}.wav {voca.add_vowels(line) if args.show_vowels else ''}") if __name__ == "__main__": main()