High-Quality Voice Cloning TTS for 600+ Languages
Python
Add opt-in text normalization (numbers, dates, currency) via generate(normalize_text=True) (#227)
Chao Cao52aa4045205f
diff --git a/README.md b/README.mdindex e28416d..6b59aa3 100644--- a/README.md+++ b/README.md@@ -192,7 +192,14 @@ audio = model.generate(text="Hello again!", voice_clone_prompt=prompt)>> - Use a 3–10 seconds reference audio clip. Longer audio slows down inference and may degrade cloning quality.> - For standard pronunciation, use a reference audio in the **same language** as the target speech. In cross-lingual voice cloning (i.e., the reference audio and target speech are in different languages), the generated speech will carry an accent from the reference audio's language.-> - For better results with Arabic numerals, normalize them to words first (e.g., "123" → "one hundred twenty-three") with text normalization tools (e.g., [WeTextProcessing](https://github.com/wenet-e2e/WeTextProcessing)).+> - For better results with Arabic numerals, normalize them to words first (e.g., "123" → "one hundred twenty-three"). You can pass `normalize_text=True` to `generate()` to do this automatically (opt-in; install the extra with `pip install "omnivoice[tn]"`, which pulls in [WeTextProcessing](https://github.com/wenet-e2e/WeTextProcessing)):+>+> ```python+> # "I have 2345 apples." is read correctly instead of digit-by-digit.+> audio = model.generate(text="I have 2345 apples.", normalize_text=True)+> ```+>+> Chinese and English use WeTextProcessing; other languages fall back to `num2words` for integers. Inline control syntax (`[laughter]`, `[B EY1 S]`, pinyin tone markers) is preserved. On macOS (Apple Silicon), `pynini` has no wheel — install it via `conda install -c conda-forge pynini` first.>> For more tips, see [docs/tips.md](docs/tips.md).diff --git a/omnivoice/models/omnivoice.py b/omnivoice/models/omnivoice.pyindex a9e0cbd..96effb1 100644--- a/omnivoice/models/omnivoice.py+++ b/omnivoice/models/omnivoice.py@@ -69,7 +69,11 @@ from omnivoice.utils.audio import ()from omnivoice.utils.duration import RuleDurationEstimatorfrom omnivoice.utils.lang_map import LANG_IDS, LANG_NAMES-from omnivoice.utils.text import add_punctuation, chunk_text_punctuation+from omnivoice.utils.text import (+ add_punctuation,+ chunk_text_punctuation,+ normalize_text as _normalize_text,+)from omnivoice.utils.voice_design import (_INSTRUCT_ALL_VALID,_INSTRUCT_EN_TO_ZH,@@ -596,6 +600,7 @@ class OmniVoice(PreTrainedModel):duration: Union[float, list[Optional[float]], None] = None,speed: Union[float, list[Optional[float]], None] = None,generation_config: Optional[OmniVoiceGenerationConfig] = None,+ normalize_text: bool = False,**kwargs,) -> list[np.ndarray]:"""Generate speech audio given text in various modes.@@ -628,6 +633,15 @@ class OmniVoice(PreTrainedModel):speed: Speaking speed factor. ``> 1.0`` for faster, ``< 1.0`` forslower. If a list, one value per item. ``None`` (default) usesthe model's default estimation.+ normalize_text: If ``True``, run text normalization on the target+ text before synthesis (numbers, dates, currency, etc. are+ converted to their spoken form, e.g. ``"2345"`` ->+ ``"twenty three forty five"``). Default ``False`` (paper+ reproducibility is unaffected). Chinese/English require the+ optional ``omnivoice[tn]`` dependency (WeTextProcessing); other+ languages use ``num2words`` for bare integers when installed.+ Inline control syntax (``[laughter]``, ``[B EY1 S]``, pinyin+ tone markers) is preserved. See :func:`omnivoice.utils.text.normalize_text`.generation_config: Explicit config object. If provided, takesprecedence over ``**kwargs``.**kwargs: Generation config or its fields:@@ -678,6 +692,7 @@ class OmniVoice(PreTrainedModel):preprocess_prompt=gen_config.preprocess_prompt,speed=speed,duration=duration,+ normalize_text=normalize_text,)short_idx, long_idx = full_task.get_indices(@@ -1025,6 +1040,7 @@ class OmniVoice(PreTrainedModel):preprocess_prompt: bool = True,speed: Union[float, list[Optional[float]], None] = None,duration: Union[float, list[Optional[float]], None] = None,+ normalize_text: bool = False,) -> GenerationTask:if isinstance(text, str):text_list = [text]@@ -1037,6 +1053,14 @@ class OmniVoice(PreTrainedModel):language_list = self._ensure_list(language, batch_size)language_list = [_resolve_language(lang) for lang in language_list]++ # Optional text normalization (opt-in). Applied to the target text only+ # (not ref_text, which must stay aligned with the reference audio),+ # before duration estimation so the estimate matches the spoken form.+ if normalize_text:+ text_list = [+ _normalize_text(t, lang) for t, lang in zip(text_list, language_list)+ ]instruct_list = self._ensure_list(instruct, batch_size)for i, s in enumerate(instruct_list):if s is None:diff --git a/omnivoice/utils/text.py b/omnivoice/utils/text.pyindex 0ea9c90..5bb2c7a 100644--- a/omnivoice/utils/text.py+++ b/omnivoice/utils/text.py@@ -21,9 +21,15 @@ Provides:- ``chunk_text_punctuation()``: Splits long text into model-friendly chunks atsentence boundaries, with abbreviation-aware punctuation splitting.- ``add_punctuation()``: Appends missing end punctuation (Chinese or English).+- ``normalize_text()``: Optional text normalization (numbers, dates, currency,+ etc.) into their spoken form, while preserving inline control syntax."""-from typing import List, Optional+import logging+import re+from typing import Callable, List, Optional++logger = logging.getLogger(__name__)SPLIT_PUNCTUATION = set(".,;:!?。,;:!?")@@ -217,3 +223,207 @@ def add_punctuation(text: str):text += "。" if is_chinese else "."return text+++# ---------------------------------------------------------------------------+# Optional text normalization (opt-in via ``generate(normalize_text=True)``)+# ---------------------------------------------------------------------------+#+# Arabic numerals, dates, currency, etc. are converted into their spoken form+# so the model reads them correctly (e.g. "2345" -> "twenty three forty five",+# "199" -> the Chinese reading). Chinese/English go through WeTextProcessing;+# any other language falls back to ``num2words`` for bare integers when+# available.+#+# The OmniVoice inline control syntax must survive normalization:+# * bracketed non-verbal tags, e.g. ``[laughter]``, ``[sigh]``;+# * bracketed CMU pronunciation overrides, e.g. ``[B EY1 S]`` -- the stress+# digit would otherwise be read as a number;+# * Chinese pinyin tone markers (uppercase pinyin + tone digit) -- likewise.+# Protected spans are held out and re-inserted verbatim around normalization.++# Any ``[...]`` span covers both non-verbal tags and CMU pronunciation.+_BRACKET_TAG_RE = re.compile(r"\[[^\[\]]*\]")+# Uppercase pinyin followed by a tone digit 1-5 (Chinese pronunciation control).+_PINYIN_TONE_RE = re.compile(r"[A-Z]+[1-5]")+_CJK_RE = re.compile(r"[\u4e00-\u9fff]")++_TN_INSTALL_MSG = (+ "Text normalization (normalize_text=True) requires WeTextProcessing, which "+ "is not installed.\n"+ " pip install WeTextProcessing # or: pip install 'omnivoice[tn]'\n"+ "WeTextProcessing depends on pynini, which has no prebuilt wheel for macOS "+ "arm64 (Apple Silicon). On macOS, install pynini from conda-forge first:\n"+ " conda install -c conda-forge pynini\n"+ "then: pip install WeTextProcessing"+)++# Normalizer construction builds FSTs and is comparatively slow, so instances+# are cached per language for the lifetime of the process.+_ZH_NORMALIZER = None+_EN_NORMALIZER = None+++def _get_zh_normalizer():+ global _ZH_NORMALIZER+ if _ZH_NORMALIZER is None:+ try:+ from tn.chinese.normalizer import Normalizer+ except ImportError as e: # pragma: no cover - depends on optional extra+ raise ImportError(_TN_INSTALL_MSG) from e+ # Conservative flags: normalize numbers/symbols only. Keep interjections+ # and erhua (they are spoken), keep the user's original characters, and+ # do not delete or rewrite anything beyond numeric/symbolic tokens.+ _ZH_NORMALIZER = Normalizer(+ remove_interjections=False,+ remove_erhua=False,+ traditional_to_simple=False,+ remove_puncts=False,+ full_to_half=False,+ )+ return _ZH_NORMALIZER+++def _get_en_normalizer():+ global _EN_NORMALIZER+ if _EN_NORMALIZER is None:+ try:+ from tn.english.normalizer import Normalizer+ except ImportError as e: # pragma: no cover - depends on optional extra+ raise ImportError(_TN_INSTALL_MSG) from e+ _EN_NORMALIZER = Normalizer()+ return _EN_NORMALIZER+++def _resolve_lang_code(language: Optional[str], text: str) -> str:+ """Map a language name/code to ``"zh"``/``"en"``/other code.++ When ``language`` is ``None`` (or unrecognized), fall back to detecting+ Chinese vs. English by the presence of CJK characters.+ """+ if language is not None:+ code = language.strip().lower()+ if code and code != "none":+ if code in ("zh", "en"):+ return code+ try:+ from omnivoice.utils.lang_map import LANG_IDS, LANG_NAME_TO_ID++ if code in LANG_IDS:+ return code+ if code in LANG_NAME_TO_ID:+ return LANG_NAME_TO_ID[code]+ except Exception: # pragma: no cover - lang_map should be importable+ pass+ return code # assume it is already a language id, e.g. "ja", "de"+ return "zh" if _CJK_RE.search(text) else "en"+++def _num2words_segment(text: str, lang: str) -> str:+ """Best-effort integer-to-words fallback for non zh/en languages."""+ try:+ from num2words import num2words+ except ImportError:+ return text # fallback is best-effort; silently skip when unavailable++ def _repl(match):+ try:+ return num2words(int(match.group()), lang=lang)+ except Exception:+ return match.group() # unsupported language / value: leave as-is++ return re.sub(r"\d+", _repl, text)+++def _normalize_segment(fn: Callable[[str], str], segment: str) -> str:+ """Normalize one non-protected segment, never raising on bad input.++ Leading/trailing whitespace is preserved explicitly because the underlying+ normalizers strip it, which would otherwise glue words to an adjacent+ protected span (e.g. ``the [B EY1 S] guitar`` -> ``the[B EY1 S]guitar``).+ """+ if not segment.strip():+ return segment+ lead = segment[: len(segment) - len(segment.lstrip())]+ trail = segment[len(segment.rstrip()) :]+ try:+ core = fn(segment.strip())+ except Exception as e: # pragma: no cover - defensive+ logger.warning(+ "Text normalization failed on a segment (%s); keeping it unchanged.",+ type(e).__name__,+ )+ return segment+ return lead + core + trail+++def _apply_with_protection(+ text: str, fn: Callable[[str], str], protect_pinyin: bool+) -> str:+ """Run ``fn`` on ``text`` while holding out protected control spans."""+ spans = [m.span() for m in _BRACKET_TAG_RE.finditer(text)]+ if protect_pinyin:+ spans += [m.span() for m in _PINYIN_TONE_RE.finditer(text)]+ if not spans:+ return _normalize_segment(fn, text)++ # Merge overlapping/adjacent protected spans, then normalize the gaps.+ spans.sort()+ merged: List[List[int]] = []+ for start, end in spans:+ if merged and start <= merged[-1][1]:+ merged[-1][1] = max(merged[-1][1], end)+ else:+ merged.append([start, end])++ out: List[str] = []+ last = 0+ for start, end in merged:+ if start > last:+ out.append(_normalize_segment(fn, text[last:start]))+ out.append(text[start:end]) # protected span, verbatim+ last = end+ if last < len(text):+ out.append(_normalize_segment(fn, text[last:]))+ return "".join(out)+++def normalize_text(text: str, language: Optional[str] = None) -> str:+ """Normalize numbers, dates, currency, etc. into their spoken form.++ Chinese is routed to WeTextProcessing's ``ZhNormalizer`` and English to its+ ``EnNormalizer`` (configured to only rewrite numeric/symbolic tokens). Any+ other language falls back to ``num2words`` for bare integers when it is+ installed, otherwise the text is returned unchanged.++ Inline OmniVoice control syntax is preserved: bracketed non-verbal tags+ (``[laughter]``) and CMU pronunciation overrides (``[B EY1 S]``) are passed+ through untouched, and Chinese pinyin tone markers (uppercase pinyin ++ tone digit) are protected so the tone digit is not read as a number.++ Args:+ text: Input text.+ language: Language code (``"en"``/``"zh"``) or full name (``"English"``).+ ``None`` auto-detects Chinese vs. English by script.++ Returns:+ The normalized text.++ Raises:+ ImportError: For Chinese/English when the optional ``omnivoice[tn]``+ dependency (WeTextProcessing) is not installed.+ """+ if not text or not text.strip():+ return text++ code = _resolve_lang_code(language, text)+ if code == "zh":+ normalizer = _get_zh_normalizer()+ return _apply_with_protection(text, normalizer.normalize, protect_pinyin=True)+ if code == "en":+ normalizer = _get_en_normalizer()+ return _apply_with_protection(text, normalizer.normalize, protect_pinyin=False)+ # Other languages: best-effort integer conversion via num2words.+ return _apply_with_protection(+ text, lambda s: _num2words_segment(s, code), protect_pinyin=False+ )diff --git a/pyproject.toml b/pyproject.tomlindex 535cf97..36ac0ad 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -45,6 +45,11 @@ dependencies = [[project.optional-dependencies]+tn = [+ "WeTextProcessing", # zh/en text normalization (numbers, dates, currency)+ "num2words", # integer-to-words fallback for other languages+]+eval = ["jiwer==3.1.0", # WER"s3prl", # Speech representation (HuBERT etc.)