An 8M-parameter English text-to-speech model distilled from Kokoro-82M. 9 MB, runs 18x real time on one CPU thread.
Phonemes without eSpeak: Paradee's own G2P is the default
Claude1cf8fc6bfb9b
diff --git a/README.md b/README.mdindex aa207da..bc2d53e 100644--- a/README.md+++ b/README.md@@ -55,11 +55,11 @@ audio, words = tts.with_timestamps("Paradee is a small voice that runs anywhere.# words: [("Paradee", 0.25, 0.84), ("is", 0.84, 0.96), ("a", 0.96, 1.06), ...]: (text, start, end) in seconds```-The voice sets the language, and each sentence is spoken in one language. Text is turned into-phonemes the way Kokoro does it, which is what the training data used: English with-[misaki](https://github.com/hexgrad/misaki), Kokoro's own grapheme-to-phoneme library (its British-dictionary for the British voices), and Hindi, French and Spanish with eSpeak NG through misaki.-The first English run also downloads misaki's dictionary data. `Paradee(version="1.2")` loads the+The voice sets the language, and each sentence is spoken in one language. English is turned into+phonemes with [misaki](https://github.com/hexgrad/misaki), Kokoro's own grapheme-to-phoneme library+(its British dictionary for the British voices). The first English run also downloads misaki's+dictionary data. Hindi, French and Spanish, and the English words misaki has no entry for, go+through Paradee's own small G2P model, described in [Phonemes without eSpeak](#phonemes-without-espeak). `Paradee(version="1.2")` loads theprevious release with the four English voices, and `Paradee(version="1.1")` and`Paradee(version="1.0")` load the earlier ones, which have `af_heart` only.@@ -201,6 +201,30 @@ conversion Whisper mishears about 31% of words, and with it about 2%. It is foronly. For Hindi, French and Spanish the model learned eSpeak's own output, with the few symbolrenames in misaki's `EspeakG2P`.+## Phonemes without eSpeak++Kokoro, and the data Paradee was trained on, get the phonemes for Hindi, French and Spanish from+[eSpeak NG](https://github.com/espeak-ng/espeak-ng), and misaki also hands it the English words it+has no entry for, mostly names. eSpeak NG is GPL-3.0, so an app that bundles it has to be GPL too.+Since 1.3.1 the package doesn't use it. [`paradee/g2p.py`](paradee/g2p.py) gives the same+phonemes from three small parts in `paradee/data/`, all Apache 2.0:++- a 0.76M-parameter model (0.9 MB int8 ONNX) that reads one word, plus the last letter of the word+ before it and the first letter of the word after it, and writes the word's phonemes. The+ neighbouring letters are enough for French liaison ("les amis"), the Spanish b, d and g that+ soften after a vowel, and the stress eSpeak puts at the end of a phrase.+- word lists: the words the model gets wrong, and the 3,000 most common words of each language.+- a table of number pieces per language, which numbers are put together from.++The model and lists were learned from eSpeak's output on 400k Wikipedia sentences per language.+On held-out sentences from other articles they differ from eSpeak in 0.80% (Hindi), 0.95% (French)+and 0.59% (Spanish) of phoneme characters, mostly a moved stress mark. For the English words misaki+sends on, they differ in 1.6% (American) and 1.7% (British). On 200 sentences per voice, Whisper's+word error rate on Paradee is within 0.3 points of the eSpeak phonemes for every voice.++`Paradee(g2p="espeak")` (or `--g2p espeak`) uses eSpeak NG as before. It needs+`pip install "paradee[espeak]"`.+## LicenseApache 2.0, the same as Kokoro. The sentences in `training/data/` come from WikiText-103 and are@@ -211,7 +235,8 @@ under CC BY-SA 3.0.Paradee is distilled from [Kokoro-82M](https://huggingface.co/hexgrad/Kokoro-82M) by hexgrad,which builds on [StyleTTS 2](https://github.com/yl4579/StyleTTS2) and[iSTFTNet](https://arxiv.org/abs/2203.02395). Phonemes come from-[misaki](https://github.com/hexgrad/misaki).+[misaki](https://github.com/hexgrad/misaki), and Paradee's own G2P was learned from+[eSpeak NG](https://github.com/espeak-ng/espeak-ng)'s output.## Citationdiff --git a/paradee/__init__.py b/paradee/__init__.pyindex 1a25db2..6288893 100644--- a/paradee/__init__.py+++ b/paradee/__init__.py@@ -3,4 +3,4 @@ Hindi, French and Spanish."""from .tts import Paradee, SAMPLE_RATE, VOICES, LANGUAGES__all__ = ["Paradee", "SAMPLE_RATE", "VOICES", "LANGUAGES"]-__version__ = "1.3.0"+__version__ = "1.3.1"diff --git a/paradee/__main__.py b/paradee/__main__.pyindex 98451b9..c0edfa8 100644--- a/paradee/__main__.py+++ b/paradee/__main__.py@@ -12,9 +12,10 @@ def main():ap.add_argument("--voice", default="af_heart", help="English: af_heart, bf_isabella, am_puck, bm_fable. Hindi: hf_alpha, hm_omega. French: ff_siwis. Spanish: em_alex. (1.2: the English four; 1.0 and 1.1: af_heart only)")ap.add_argument("--fp32", action="store_true", help="use the fp32 model instead of int8")ap.add_argument("--model-version", default="1.3", choices=["1.3", "1.2", "1.1", "1.0"])+ ap.add_argument("--g2p", default="paradee", choices=["paradee", "espeak"], help="phonemes from Paradee's own G2P (default) or from eSpeak NG (needs paradee[espeak])")a = ap.parse_args()text = a.text if a.text is not None else sys.stdin.read()- audio = Paradee(version=a.model_version, quantized=not a.fp32)(text, speed=a.speed, voice=a.voice)+ audio = Paradee(version=a.model_version, quantized=not a.fp32, g2p=a.g2p)(text, speed=a.speed, voice=a.voice)pcm = (np.clip(audio, -1, 1) * 32767).astype("<i2")with wave.open(a.out, "wb") as w:w.setnchannels(1); w.setsampwidth(2); w.setframerate(SAMPLE_RATE); w.writeframes(pcm.tobytes())diff --git a/paradee/data/g2p.json.gz b/paradee/data/g2p.json.gznew file mode 100644index 0000000..48b9048Binary files /dev/null and b/paradee/data/g2p.json.gz differdiff --git a/paradee/data/g2p.onnx b/paradee/data/g2p.onnxnew file mode 100644index 0000000..cad3e00Binary files /dev/null and b/paradee/data/g2p.onnx differdiff --git a/paradee/g2p.py b/paradee/g2p.pynew file mode 100644index 0000000..0f2a884--- /dev/null+++ b/paradee/g2p.py@@ -0,0 +1,297 @@+"""Paradee's own grapheme-to-phoneme model: text -> the phonemes Paradee was trained on, without eSpeak.++Paradee learned Hindi, French and Spanish from eSpeak NG's phonemes, and English from misaki, which hands+the words it has no entry for (names, mostly) to eSpeak. eSpeak is GPL-3.0, so it can't ship inside a+closed-source app. This module gives the same phonemes from three small Apache-2.0 parts, all in data/:++- a 0.76M-parameter model (g2p.onnx, 0.9 MB int8) that reads one word, plus the last letter of the word+ before it and the first letter of the word after it, and writes the word's phonemes with stress marks.+ The neighbouring letters are enough for French liaison ("les amis" -> lez), the Spanish b, d and g that+ soften after a vowel, and the stress eSpeak puts at the end of a phrase.+- word lists (g2p.json.gz): the words the model gets wrong, and the 3,000 most common words of each language+ so they skip the model.+- a table of number pieces per language (0 to 99, the hundreds, thousand, lakh, million...) that numbers+ are put together from.++The model and lists were learned from eSpeak's output on 400k Wikipedia sentences per language. On held-out+sentences they differ from eSpeak in 0.80% (Hindi), 0.95% (French) and 0.59% (Spanish) of phoneme+characters, mostly a moved stress mark.+"""+import gzip, json, os, re, unicodedata+import numpy as np+import onnxruntime as ort++_DATA = os.path.join(os.path.dirname(__file__), "data")+_PERCENT = {"hi": "प्रतिशत", "fr": "pour cent", "es": "por ciento"}+_DEVANAGARI_DIGITS = str.maketrans("०१२३४५६७८९", "0123456789")+_MAX_WORD = 60 # letters the model reads of one word+++def _is_edge(c):+ """Punctuation, symbols, spaces and zero-width characters, which are trimmed off the ends of a word."""+ return unicodedata.category(c)[0] in "PSZ" or c in ""+++def _strip(w):+ i, j = 0, len(w)+ while i < j and _is_edge(w[i]):+ i += 1+ while j > i and _is_edge(w[j - 1]):+ j -= 1+ return w[i:j]+++def _words(text):+ """Each whitespace-separated piece of `text` as (word, punctuation before it?, punctuation after it?).+ A piece with no letters or digits is (None, True, True)."""+ out = []+ for raw in text.split():+ core = _strip(raw)+ if not core or not any(c.isalnum() for c in core):+ out.append((None, True, True))+ continue+ i = raw.find(core)+ out.append((core, i > 0, i + len(core) < len(raw)))+ return out+++def _contexts(words):+ """(before, after) for each word: the last letter of the word before and the first letter of the word+ after, lowercased, or "#" when punctuation or the end of the sentence is in between."""+ res = []+ for i, (w, lead, trail) in enumerate(words):+ if w is None:+ res.append(None)+ continue+ if i == 0 or lead or words[i - 1][0] is None or words[i - 1][2]:+ before = "#"+ else:+ before = words[i - 1][0][-1].lower()+ if i == len(words) - 1 or trail or words[i + 1][0] is None or words[i + 1][1]:+ after = "#"+ else:+ after = words[i + 1][0][0].lower()+ res.append((before, after))+ return res+++# Numbers, put together from pieces the way eSpeak reads them.+def _unstress(s):+ return s.replace("ˈ", "").replace("ˌ", "")+++def _hi(n, t):+ if n < 100:+ return [t[str(n)]]+ out = []+ for div, name in [(10**7, "crore"), (10**5, "lakh"), (1000, "thousand")]:+ if n >= div:+ out += _hi(n // div, t) + [t[name]]+ n %= div+ if n >= 100:+ out.append(t[str(n // 100 * 100)])+ n %= 100+ if n:+ out.append(t[str(n)])+ return out+++def _fr(n, t, top=True):+ out = []+ for div, one, many in [(10**9, "milliard", "milliards"), (10**6, "million", "millions")]:+ if n >= div:+ q = n // div+ out += (["œ̃"] if q == 1 else _fr(q, t, False)) + [t[one if q == 1 else many]]+ n %= div+ if n >= 1000:+ q = n // 1000+ out += ([] if q == 1 else _fr(q, t, False)) + [t["thousand"]]+ n %= 1000+ if n >= 100:+ out.append(t[str(n // 100 * 100)])+ n %= 100+ if n or not out:+ out.append(t[str(n)])+ if top: # French stresses only the last word of a number+ out = [_unstress(x) for x in out[:-1]] + out[-1:]+ return out+++def _es(n, t):+ out = []+ if n >= 10**6:+ q = n // 10**6+ out += [t["millón"]] if q == 1 else _es(q, t) + [t["millones"]]+ n %= 10**6+ if n >= 1000:+ q = n // 1000+ if q == 1:+ out.append(t["thousand"])+ else:+ p = _es(q, t)+ if q % 10 == 1 and q % 100 != 11 and p[-1].endswith("o"): # veintiuno mil -> veintiún mil+ p[-1] = p[-1][:-1]+ out += p + [t["thousand"]]+ n %= 1000+ if n >= 100:+ h = n // 100 * 100+ n %= 100+ out.append(t["100+"] if h == 100 and n else t[str(h)])+ if n or not out:+ out.append(t[str(n)])+ return out+++_NUMBERS = {"hi": _hi, "fr": _fr, "es": _es}+_SOFT = {"b": "β", "d": "ð", "ɡ": "ɣ"}+++def _soften(p, before):+ """Spanish b, d and g are said β, ð and ɣ after a vowel and most consonants, also across words, as eSpeak+ writes them. `before` is the sound or letter before, "#" after a pause."""+ i = 0+ while i < len(p) and p[i] in "ˈˌ":+ i += 1+ c = p[i:i + 1]+ if c in _SOFT and before not in "#nmɲŋ" and not (c == "d" and before == "l"):+ p = p[:i] + _SOFT[c] + p[i + 1:]+ return p+++class G2P:+ """Phonemes for Paradee without eSpeak. One instance serves every language.++ g2p("Bonjour à tous.", "fr") -> "bɔ̃ʒˈuʁ a tˈus." languages: "hi", "fr", "es"+ g2p.english_fallback(british) -> a fallback for misaki's English G2P, in place of misaki's EspeakFallback+ """++ def __init__(self, threads=1):+ with gzip.open(os.path.join(_DATA, "g2p.json.gz"), "rt", encoding="utf-8") as f:+ data = json.load(f)+ self.ins, self.outs = data["vocab"]["in"], data["vocab"]["out"]+ self.index = {c: i for i, c in enumerate(self.ins)}+ self.numbers = data["numbers"]+ self.lexicon = {lang: (d["w"], {tuple(k.split("\t")): v for k, v in d["c"].items()})+ for lang, d in data["lexicon"].items()}+ so = ort.SessionOptions()+ so.intra_op_num_threads = threads+ so.inter_op_num_threads = 1+ self.session = ort.InferenceSession(os.path.join(_DATA, "g2p.onnx"), so, providers=["CPUExecutionProvider"])++ def model(self, items):+ """Phonemes for each (language, letter before, word, letter after), from the model alone."""+ if not items:+ return []+ ix, unk = self.index, self.index["<unk>"]+ rows = [[ix[f"<{lang}>"], ix.get(a, unk), ix["<s1>"]] + [ix.get(c, unk) for c in w.lower()[:_MAX_WORD]]+ + [ix["<s2>"], ix.get(b, unk)] for lang, a, w, b in items]+ T = max(map(len, rows))+ chars = np.zeros((len(rows), T), dtype=np.int64)+ pad = np.ones((len(rows), T), dtype=bool)+ for i, r in enumerate(rows):+ chars[i, :len(r)] = r+ pad[i, :len(r)] = False+ best = self.session.run(None, {"chars": chars, "pad": pad})[0]+ res = []+ for r, row in zip(best, rows): # CTC: merge repeats, drop blanks (0); each letter has 3 output steps+ out, prev = [], 0+ for k in r[:3 * len(row)]:+ if k != prev and k != 0:+ out.append(self.outs[k])+ prev = k+ res.append("".join(out))+ return res++ def words(self, lang, items):+ """Phonemes for each (word, letter before, letter after): the word list first, then the model."""+ words, in_context = self.lexicon.get(lang, ({}, {}))+ out = [in_context.get((w, a, b)) or words.get(w) for w, a, b in items]+ todo = [i for i, p in enumerate(out) if p is None]+ for i, p in zip(todo, self.model([(lang, items[i][1], items[i][0], items[i][2]) for i in todo])):+ out[i] = p+ return out++ def number(self, n, lang, before="#"):+ parts = _NUMBERS[lang](n, self.numbers[lang])+ if lang == "es":+ soft = []+ for k, p in enumerate(parts):+ soft.append(_soften(p, before if k == 0 else soft[-1][-1]))+ parts = soft+ return " ".join(parts)++ def __call__(self, text, lang):+ """One sentence of Hindi ("hi"), French ("fr") or Spanish ("es") -> phonemes, one space between words,+ punctuation kept, like misaki's EspeakG2P."""+ text = text.translate(_DEVANAGARI_DIGITS).replace("«", "“").replace("»", "”")+ text = re.sub("[]", "", text)+ text = re.sub(r"([।॥])(?=\S)", r"\1 ", text)+ if lang == "fr": # 12 000 is one number+ text = re.sub(r"(?<=\d)[ ](?=\d{3}\b)", "", text)+ text = re.sub(r"(\d)\s?%", lambda m: m.group(1) + " " + _PERCENT[lang], text)+ words = _words(text)+ jobs, plan = [], []+ for raw, (core, _, _), ctx in zip(text.split(), words, _contexts(words)):+ if core is None:+ plan.append((raw, None, ""))+ continue+ i = raw.find(core)+ parts = []+ for piece in re.findall(r"\d+|[^\d]+", core):+ if piece.isdigit():+ parts.append(("number", piece))+ else:+ piece = piece.strip("-.,/:")+ if any(c.isalnum() for c in piece):+ parts.append(("word", piece))+ ids = []+ for kind, piece in parts:+ first, last = piece == parts[0][1], piece == parts[-1][1]+ if kind == "number":+ if len(piece) < 10:+ ids.append(("text", self.number(int(piece), lang, ctx[0] if first else "#")))+ else: # a long string of digits is read digit by digit+ ids.append(("text", " ".join(self.number(int(d), lang) for d in piece)))+ else:+ jobs.append((piece, ctx[0] if first else "#", ctx[1] if last else "#"))+ ids.append(("job", len(jobs) - 1))+ plan.append((raw[:i], ids, raw[i + len(core):]))+ res = self.words(lang, jobs)+ out = []+ for lead, ids, trail in plan:+ if ids is None:+ out.append(lead)+ else:+ out.append(lead + " ".join(x if kind == "text" else res[x] for kind, x in ids) + trail)+ return " ".join(out).replace("-", "")++ def english_fallback(self, british):+ """For misaki's en.G2P(fallback=...): phonemes for the English words misaki has no entry for."""+ return _EnglishFallback(self, british)+++class _EnglishFallback:+ def __init__(self, g2p, british):+ from misaki import en+ self.g2p, self.lang = g2p, "en-gb" if british else "en-us"+ self.plain = en.G2P(trf=False, british=british, fallback=None, unk="") # reads digits on its own++ def __call__(self, token):+ """Like eSpeak, keeps the punctuation around the word ("St." -> "sənt.")."""+ words = self.g2p.lexicon[self.lang][0]+ out = []+ for piece in token.text.split():+ core = _strip(piece)+ if not core or not any(c.isalnum() for c in core):+ continue+ i = piece.find(core)+ said = []+ for part in re.findall(r"\d+|\D+", core): # digits ("22:", "Se8") are read by misaki itself+ if part.isdigit():+ said.append(self.plain(part)[0])+ else:+ part = part.strip("-.,/:'")+ if any(c.isalnum() for c in part):+ said.append(words.get(part) or self.g2p.model([(self.lang, "#", part, "#")])[0])+ out.append(piece[:i] + " ".join(said) + piece[i + len(core):])+ return " ".join(out), 2diff --git a/paradee/tts.py b/paradee/tts.pyindex 3d5fa8d..204ae0a 100644--- a/paradee/tts.py+++ b/paradee/tts.py@@ -1,5 +1,5 @@-"""Text -> phonemes (Kokoro's own G2P: misaki for English, eSpeak through misaki for the other languages) ->-token ids -> one ONNX graph -> 24 kHz audio."""+"""Text -> phonemes (misaki for English, Paradee's own G2P for Hindi, French and Spanish and for the English words+misaki has no entry for) -> token ids -> one ONNX graph -> 24 kHz audio."""import json, re, unicodedatafrom dataclasses import dataclassimport numpy as np@@ -16,6 +16,7 @@ VOICES = {# A voice's first letter is its language, as in Kokoro: a = American English, b = British English, h = Hindi,# f = French, e = Spanish. The values are the eSpeak languages Kokoro uses for the languages misaki doesn't cover.LANGUAGES = {"a": "en-us", "b": "en-gb", "h": "hi", "f": "fr-fr", "e": "es"}+G2PS = ("paradee", "espeak")SAMPLE_RATE = 24000MAX_PHONEMES = 510 # the text side has 512 positions, two of which are the pad tokens at each end# Inside every released graph (1.0, 1.1, 1.2): each token's length in frames of 600 samples, rounded. The frames@@ -177,11 +178,17 @@ class Paradee:quantized: use the 8.5 MB int8 file (default) instead of the 35 MB fp32 one. They sound the same.model_path / config_path: local files instead of downloading from the Hugging Face Hub.threads: CPU threads for onnxruntime. One thread already runs about 60x faster than real time.+ g2p: "paradee" (default) turns text into phonemes with Paradee's own small G2P model (paradee/g2p.py), which+ gives eSpeak NG's phonemes without eSpeak. "espeak" uses eSpeak NG itself, as Kokoro does; it is GPL-3.0 and+ needs `pip install paradee[espeak]`."""- def __init__(self, version="1.3", quantized=True, model_path=None, config_path=None, threads=1):+ def __init__(self, version="1.3", quantized=True, model_path=None, config_path=None, threads=1, g2p="paradee"):if version not in REPOS:raise ValueError(f"unknown version {version!r}; choose one of {', '.join(REPOS)}")+ if g2p not in G2PS:+ raise ValueError(f"unknown g2p {g2p!r}; choose one of {', '.join(G2PS)}")+ self.g2p_name = g2prepo, revision = REPOS[version], f"v{version}"self.version, self.voices = version, VOICES[version]name = "onnx/paradee_int8.onnx" if quantized else "onnx/paradee.onnx"@@ -194,22 +201,40 @@ class Paradee:with open(model_path, "rb") as f:model = _with_output(f.read(), DURATIONS)self.session = ort.InferenceSession(model, so, providers=["CPUExecutionProvider"])- self._g2p = {}+ self._g2p, self._own = {}, Nonedef g2p(self, voice="af_heart"):- """The same G2P setup as kokoro.KPipeline, which made the training data, for the voice's language (its- first letter): misaki's American or British English for a and b, eSpeak through misaki for h (Hindi),- f (French) and e (Spanish). Each is loaded the first time it is needed."""+ """The G2P for the voice's language (its first letter): misaki's American or British English for a and b,+ and phonemes in eSpeak's style for h (Hindi), f (French) and e (Spanish). With g2p="espeak" this is the+ same setup as kokoro.KPipeline, which made the training data; with g2p="paradee" Paradee's own model+ stands in for eSpeak, both for the three languages and for the English words misaki has no entry for.+ Each is loaded the first time it is needed. Like misaki's, it returns (phonemes, tokens), and tokens is+ None for h, f and e."""lang = voice[0]if lang not in LANGUAGES:raise ValueError(f"no language for voice {voice!r}")if lang not in self._g2p:- from misaki import en, espeak- if lang in "ab":- british = lang == "b"- self._g2p[lang] = en.G2P(trf=False, british=british, fallback=espeak.EspeakFallback(british=british), unk="")+ if self.g2p_name == "paradee":+ from .g2p import G2P+ self._own = self._own or G2P()+ own = self._own+ if lang in "ab":+ from misaki import en+ british = lang == "b"+ self._g2p[lang] = en.G2P(trf=False, british=british, fallback=own.english_fallback(british), unk="")+ else:+ code = {"h": "hi", "f": "fr", "e": "es"}[lang]+ self._g2p[lang] = lambda text: (own(text, code), None)else:- self._g2p[lang] = espeak.EspeakG2P(language=LANGUAGES[lang])+ try:+ from misaki import en, espeak+ except ImportError as e:+ raise ImportError('g2p="espeak" needs eSpeak NG: pip install "paradee[espeak]"') from e+ if lang in "ab":+ british = lang == "b"+ self._g2p[lang] = en.G2P(trf=False, british=british, fallback=espeak.EspeakFallback(british=british), unk="")+ else:+ self._g2p[lang] = espeak.EspeakG2P(language=LANGUAGES[lang])return self._g2p[lang]def phonemize(self, text, voice="af_heart"):diff --git a/pyproject.toml b/pyproject.tomlindex ac4939d..551ab12 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -1,6 +1,6 @@[project]name = "paradee"-version = "1.3.0"+version = "1.3.1"description = "An 8M-parameter text-to-speech model distilled from Kokoro-82M, in English, Hindi, French and Spanish"readme = "README.md"license = "Apache-2.0"@@ -14,10 +14,12 @@ dependencies = ["misaki>=0.9.4","spacy>=3.7","num2words",- "phonemizer-fork",- "espeakng-loader",]+[project.optional-dependencies]+# eSpeak NG (GPL-3.0), only for Paradee(g2p="espeak"). The default G2P doesn't need it.+espeak = ["phonemizer-fork", "espeakng-loader"]+[project.scripts]paradee = "paradee.__main__:main"