Spaces:
Running

notmax123 Claude Opus 5 (1M context) commited on
Commit
7daf341
·
1 Parent(s): 4b76f53

Ignore sparse nikud, and split partial nikud between front ends

Browse files

Phonikud spells a Hebrew word out of its points, so a word handed to it
without them comes back as consonant soup: שלוש -> ʃˈlʃ. The Hebrew branch
routed the whole segment through it whenever *any* mark was present, so one
shuruk dot in השלמוּת was enough to mangle a paragraph that Renikud would
have read correctly.

A word now counts as vocalized only if it carries a vowel point and more
than one mark overall — short words excepted, since לֹא is fully specified
by its one vowel. Everything else is stripped and goes to Renikud. When
both kinds are present the text is split into runs so a properly pointed
word keeps its reading while its neighbours keep Renikud.

Also ship Russian in the serverless image. RUAccent/RUPhon go in before the
serverless set so onnxruntime-gpu still wins the wheel collision, torch
comes from the CPU index (the front end runs on CPU anyway), and the ~1 GB
of weights is warmed at build time rather than on a cold worker's first job.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0138DB6F6YxWtYWy7WNaLAsU

Files changed (4) hide show
  1. app.py +86 -14
  2. docker/Dockerfile +30 -10
  3. docker/README.md +8 -6
  4. docker/requirements-russian.txt +6 -4
app.py CHANGED
@@ -230,6 +230,13 @@ _INLINE_LANG_PAIR = re.compile(r"<(en|en-us|he|es|de|ge|it|ru)>(.*?)(?:</\1>|<\1
230
  _LANG_LIST_BLOCK_RE = re.compile(r"<lang_list\b[^>]*>.*?</lang_list>", re.DOTALL | re.IGNORECASE)
231
  _LANG_TAG_RE = re.compile(r"</?[^>]+>")
232
  _HEBREW_NIKUD_RE = re.compile(r"[\u0591-\u05BD\u05BF\u05C1-\u05C2\u05C4-\u05C5\u05C7]")
 
 
 
 
 
 
 
233
  _HEBREW_CHAR_RE = re.compile(r"[\u0590-\u05ff]")
234
  _CYRILLIC_CHAR_RE = re.compile(r"[\u0400-\u04ff]")
235
  _EMAIL_RE = re.compile(r"[A-Za-z0-9._%+\-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
@@ -355,6 +362,54 @@ def has_hebrew_nikud(text: str) -> bool:
355
  return _HEBREW_NIKUD_RE.search(text) is not None
356
 
357
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
358
  def _canonical_lang(lang: str) -> str:
359
  return LANG_CODE_ALIASES.get(lang.lower(), lang.lower())
360
 
@@ -739,6 +794,34 @@ class TextProcessor:
739
  return self.renikud.phonemize(content)
740
  return self.renikud.phonemize(content, speaker=speaker, target_speaker=speaker)
741
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
742
  def _phonemize_segment(self, content: str, lang: str, speaker: int = 0) -> str:
743
  content = _strip_synthesis_tags(content).strip()
744
  if not content:
@@ -750,20 +833,9 @@ class TextProcessor:
750
  return content
751
  if self.renikud is None:
752
  raise ValueError("Hebrew text requires Renikud weights (renikud.onnx).")
753
- # Explicit niqqud is a pronunciation instruction. Preserve it and
754
- # let Phonikud deterministically convert it to IPA (with stress),
755
- # rather than discarding it before G2P.
756
- if has_hebrew_nikud(content):
757
- return strip_silent_separator_tokens(
758
- phonikud_phonemize(
759
- content,
760
- preserve_punctuation=True,
761
- preserve_stress=True,
762
- use_expander=False,
763
- predict_stress=True,
764
- )
765
- )
766
- return strip_silent_separator_tokens(self._renikud_phonemize(content, speaker))
767
  if lang == "ru" or _CYRILLIC_CHAR_RE.search(content):
768
  return strip_silent_separator_tokens(self._russian(content))
769
  return strip_silent_separator_tokens(self._espeak(content, lang))
 
230
  _LANG_LIST_BLOCK_RE = re.compile(r"<lang_list\b[^>]*>.*?</lang_list>", re.DOTALL | re.IGNORECASE)
231
  _LANG_TAG_RE = re.compile(r"</?[^>]+>")
232
  _HEBREW_NIKUD_RE = re.compile(r"[\u0591-\u05BD\u05BF\u05C1-\u05C2\u05C4-\u05C5\u05C7]")
233
+ # The subset that actually spells a vowel. Dagesh, shin/sin dots, meteg and the
234
+ # cantillation marks are not vowels, so a word wearing only those is unvocalized
235
+ # no matter how many it has.
236
+ _HEBREW_VOWEL_RE = re.compile(r"[\u05B0-\u05BB\u05C7]")
237
+ _HEBREW_LETTER_RE = re.compile(r"[\u05D0-\u05EA]")
238
+ _NIKUD_SHORT_WORD_LETTERS = 3
239
+ _WHITESPACE_SPLIT_RE = re.compile(r"(\s+)")
240
  _HEBREW_CHAR_RE = re.compile(r"[\u0590-\u05ff]")
241
  _CYRILLIC_CHAR_RE = re.compile(r"[\u0400-\u04ff]")
242
  _EMAIL_RE = re.compile(r"[A-Za-z0-9._%+\-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
 
362
  return _HEBREW_NIKUD_RE.search(text) is not None
363
 
364
 
365
+ def _word_keeps_nikud(word: str) -> bool:
366
+ """Whether a word's points are a pronunciation instruction or noise.
367
+
368
+ Phonikud reads a word letter-by-letter from its points, so a word it is
369
+ handed without them comes out as consonant soup (שלוש -> ``ʃˈlʃ``). One
370
+ stray mark anywhere therefore used to drag a whole unvocalized paragraph
371
+ through it — a single shuruk dot in השלמוּת is enough, and that dot is
372
+ typography, not vocalization.
373
+
374
+ A word is treated as vocalized only when it carries a vowel point, and only
375
+ when it carries more than one mark overall. Short words are the exception:
376
+ לֹא or זֶה is fully specified by its single vowel.
377
+ """
378
+ marks = _HEBREW_NIKUD_RE.findall(word)
379
+ if not marks or not _HEBREW_VOWEL_RE.search(word):
380
+ return False
381
+ if len(marks) > 1:
382
+ return True
383
+ return len(_HEBREW_LETTER_RE.findall(word)) <= _NIKUD_SHORT_WORD_LETTERS
384
+
385
+
386
+ def filter_partial_nikud(text: str) -> str:
387
+ """Drop points from words that are not actually vocalized."""
388
+ if not has_hebrew_nikud(text):
389
+ return text
390
+ return "".join(
391
+ tok if _word_keeps_nikud(tok) else strip_hebrew_nikud(tok)
392
+ for tok in _WHITESPACE_SPLIT_RE.split(text)
393
+ )
394
+
395
+
396
+ def hebrew_nikud_runs(text: str) -> list[tuple[bool, str]]:
397
+ """Split into maximal runs of vocalized / unvocalized words.
398
+
399
+ Partial nikud marks the words the writer wanted pronounced a particular
400
+ way; the rest of the sentence still belongs to Renikud. Each run goes to
401
+ the front end that can read it, in the original order.
402
+ """
403
+ runs: list[list[Any]] = []
404
+ for tok in text.split():
405
+ vocalized = has_hebrew_nikud(tok)
406
+ if runs and runs[-1][0] == vocalized:
407
+ runs[-1][1].append(tok)
408
+ else:
409
+ runs.append([vocalized, [tok]])
410
+ return [(vocalized, " ".join(toks)) for vocalized, toks in runs]
411
+
412
+
413
  def _canonical_lang(lang: str) -> str:
414
  return LANG_CODE_ALIASES.get(lang.lower(), lang.lower())
415
 
 
794
  return self.renikud.phonemize(content)
795
  return self.renikud.phonemize(content, speaker=speaker, target_speaker=speaker)
796
 
797
+ @staticmethod
798
+ def _phonikud_phonemize(content: str) -> str:
799
+ return phonikud_phonemize(
800
+ content,
801
+ preserve_punctuation=True,
802
+ preserve_stress=True,
803
+ use_expander=False,
804
+ predict_stress=True,
805
+ )
806
+
807
+ def _hebrew_phonemize(self, content: str, speaker: int) -> str:
808
+ """Route each part of the text to the front end that can read it.
809
+
810
+ Explicit niqqud is a pronunciation instruction, so Phonikud converts it
811
+ deterministically to IPA. Everything else — including words whose points
812
+ were too sparse to mean anything (see ``filter_partial_nikud``) — goes to
813
+ Renikud, which predicts the vocalization itself.
814
+ """
815
+ content = filter_partial_nikud(content)
816
+ if not has_hebrew_nikud(content):
817
+ return self._renikud_phonemize(content, speaker)
818
+ parts = [
819
+ self._phonikud_phonemize(run) if vocalized
820
+ else self._renikud_phonemize(run, speaker)
821
+ for vocalized, run in hebrew_nikud_runs(content)
822
+ ]
823
+ return " ".join(p for p in (p.strip() for p in parts) if p)
824
+
825
  def _phonemize_segment(self, content: str, lang: str, speaker: int = 0) -> str:
826
  content = _strip_synthesis_tags(content).strip()
827
  if not content:
 
833
  return content
834
  if self.renikud is None:
835
  raise ValueError("Hebrew text requires Renikud weights (renikud.onnx).")
836
+ return strip_silent_separator_tokens(
837
+ self._hebrew_phonemize(content, speaker)
838
+ )
 
 
 
 
 
 
 
 
 
 
 
839
  if lang == "ru" or _CYRILLIC_CHAR_RE.search(content):
840
  return strip_silent_separator_tokens(self._russian(content))
841
  return strip_silent_separator_tokens(self._espeak(content, lang))
docker/Dockerfile CHANGED
@@ -1,11 +1,14 @@
1
- # Slim BlueTTS 2.5 ONNX + NVIDIA GPU for RunPod Serverless (no torch/gradio).
2
  # Build from repo root:
3
  # docker buildx build --platform linux/amd64 -f docker/Dockerfile \
4
- # -t maxme123/blue-v2:serverless-v5 --push .
5
  #
6
- # Russian is not in this image: RUAccent/RUPhon need torch + transformers, which
7
- # would undo the no-torch invariant asserted below. Build with
8
- # --build-arg WITH_RUSSIAN=1 to include them (image grows by ~2.5 GB).
 
 
 
9
 
10
  ARG CUDA_IMAGE=nvidia/cuda:12.6.3-cudnn-runtime-ubuntu24.04
11
  FROM ${CUDA_IMAGE}
@@ -44,20 +47,27 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
44
 
45
  WORKDIR /app
46
 
47
- ARG WITH_RUSSIAN=0
48
 
49
  COPY docker/requirements-serverless.txt /app/docker/requirements-serverless.txt
50
  COPY docker/requirements-russian.txt /app/docker/requirements-russian.txt
 
 
 
 
 
51
  RUN pip install --upgrade pip setuptools wheel \
 
 
 
 
52
  && pip install -r /app/docker/requirements-serverless.txt \
53
  && python -c "import onnxruntime as ort, sys; \
54
  p = ort.get_available_providers(); \
55
  print('ORT', ort.__version__, p); \
56
- sys.exit('CUDAExecutionProvider missing — the CPU onnxruntime wheel clobbered the GPU one; check install order in requirements-serverless.txt') \
57
  if 'CUDAExecutionProvider' not in p else None" \
58
- && if [ "$WITH_RUSSIAN" = "1" ]; then \
59
- pip install -r /app/docker/requirements-russian.txt; \
60
- else \
61
  python -c "import torch" 2>/dev/null && echo 'ERROR: torch should not be installed' && exit 1 || echo 'OK: no torch'; \
62
  fi
63
 
@@ -92,5 +102,15 @@ open('/app/onnx_slim/.repo_id','w').write(BLUE_REPO+chr(10)+ONNX_BUNDLE_STAMP+ch
92
  open('/app/voices/.repo_id','w').write(BLUE_REPO+chr(10)+ONNX_BUNDLE_STAMP+chr(10)); \
93
  print('markers written')"
94
 
 
 
 
 
 
 
 
 
 
 
95
  # No HEALTHCHECK — RunPod serverless uses the runpod SDK job loop, not HTTP probes.
96
  CMD ["/app/docker/entrypoint.sh"]
 
1
+ # BlueTTS 2.5 ONNX + NVIDIA GPU for RunPod Serverless (no gradio).
2
  # Build from repo root:
3
  # docker buildx build --platform linux/amd64 -f docker/Dockerfile \
4
+ # -t maxme123/blue-v2:serverless-v6 --push .
5
  #
6
+ # Russian is included: RUAccent + RUPhon and their ~1 GB of weights are baked in
7
+ # below so a cold worker does not download them on its first Russian job. They
8
+ # need torch, which is installed from the CPU wheel index — the front end runs on
9
+ # CPU by design (BLUE_RU_G2P_DEVICE), and the CUDA torch build would add ~2 GB of
10
+ # libraries that duplicate what the base image and onnxruntime-gpu already carry.
11
+ # Build with --build-arg WITH_RUSSIAN=0 for a torch-free image without Russian.
12
 
13
  ARG CUDA_IMAGE=nvidia/cuda:12.6.3-cudnn-runtime-ubuntu24.04
14
  FROM ${CUDA_IMAGE}
 
47
 
48
  WORKDIR /app
49
 
50
+ ARG WITH_RUSSIAN=1
51
 
52
  COPY docker/requirements-serverless.txt /app/docker/requirements-serverless.txt
53
  COPY docker/requirements-russian.txt /app/docker/requirements-russian.txt
54
+ # Order matters, and not for readability: ruphon depends on the CPU `onnxruntime`,
55
+ # which unpacks over the same directory as `onnxruntime-gpu`. Whichever pip writes
56
+ # last wins, so the Russian deps go in first and the serverless set — which pins
57
+ # onnxruntime-gpu — goes in last. The assert below is what turns a future flip
58
+ # into a failed build instead of a silently CPU-bound image.
59
  RUN pip install --upgrade pip setuptools wheel \
60
+ && if [ "$WITH_RUSSIAN" = "1" ]; then \
61
+ pip install --index-url https://download.pytorch.org/whl/cpu torch \
62
+ && pip install -r /app/docker/requirements-russian.txt; \
63
+ fi \
64
  && pip install -r /app/docker/requirements-serverless.txt \
65
  && python -c "import onnxruntime as ort, sys; \
66
  p = ort.get_available_providers(); \
67
  print('ORT', ort.__version__, p); \
68
+ sys.exit('CUDAExecutionProvider missing — the CPU onnxruntime wheel clobbered the GPU one; check install order above') \
69
  if 'CUDAExecutionProvider' not in p else None" \
70
+ && if [ "$WITH_RUSSIAN" != "1" ]; then \
 
 
71
  python -c "import torch" 2>/dev/null && echo 'ERROR: torch should not be installed' && exit 1 || echo 'OK: no torch'; \
72
  fi
73
 
 
102
  open('/app/voices/.repo_id','w').write(BLUE_REPO+chr(10)+ONNX_BUNDLE_STAMP+chr(10)); \
103
  print('markers written')"
104
 
105
+ # Bake the Russian weights in. RUAccent's dictionary + omograph model and RUPhon's
106
+ # graph are ~1 GB fetched on first use, which would otherwise land on the first
107
+ # Russian job of every cold worker. Phonemizing one sentence is what triggers the
108
+ # download, and it doubles as a build-time check that the front end actually loads
109
+ # (the transformers/tokenizer patch in g2p/russian_g2p.py is version-sensitive).
110
+ RUN if [ "$WITH_RUSSIAN" = "1" ]; then \
111
+ python -c "from g2p.russian_g2p import phonemize_russian; \
112
+ print('ru warm:', phonemize_russian('Взгляну́в на Санкт-Петербург, я всё понял.'))"; \
113
+ fi
114
+
115
  # No HEALTHCHECK — RunPod serverless uses the runpod SDK job loop, not HTTP probes.
116
  CMD ["/app/docker/entrypoint.sh"]
docker/README.md CHANGED
@@ -53,9 +53,11 @@ rights before exposing it publicly.
53
  `lang` accepts `en`, `he`, `ru`, `es`, `de`, `it`. Anything else returns an
54
  error listing the supported set rather than mispronouncing the text.
55
 
56
- **Russian needs a build flag.** RUAccent + RUPhon pull torch and transformers,
57
- which the default serverless image deliberately excludes; build with
58
- `--build-arg WITH_RUSSIAN=1` (image grows ~2.5 GB) to enable it.
 
 
59
 
60
  Successful `output` includes:
61
  - `audio_base64` — **OGG/Opus by default** (`format: "wav"` to keep WAV)
@@ -82,14 +84,14 @@ docker buildx build \
82
  --push .
83
  ```
84
 
85
- With Russian:
86
 
87
  ```bash
88
  docker buildx build \
89
  --platform linux/amd64 \
90
- --build-arg WITH_RUSSIAN=1 \
91
  -f docker/Dockerfile \
92
- -t maxme123/blue-v2:russian \
93
  --push .
94
  ```
95
 
 
53
  `lang` accepts `en`, `he`, `ru`, `es`, `de`, `it`. Anything else returns an
54
  error listing the supported set rather than mispronouncing the text.
55
 
56
+ Russian is included by default. RUAccent + RUPhon need torch and transformers,
57
+ installed from the CPU wheel index (the front end runs on CPU by design), and
58
+ their ~1 GB of weights is baked into the image so no cold worker downloads them
59
+ mid-job. That costs ~2 GB of image; `--build-arg WITH_RUSSIAN=0` builds the
60
+ torch-free image without Russian.
61
 
62
  Successful `output` includes:
63
  - `audio_base64` — **OGG/Opus by default** (`format: "wav"` to keep WAV)
 
84
  --push .
85
  ```
86
 
87
+ Without Russian (no torch, ~2 GB smaller):
88
 
89
  ```bash
90
  docker buildx build \
91
  --platform linux/amd64 \
92
+ --build-arg WITH_RUSSIAN=0 \
93
  -f docker/Dockerfile \
94
+ -t maxme123/blue-v2:no-russian \
95
  --push .
96
  ```
97
 
docker/requirements-russian.txt CHANGED
@@ -1,7 +1,9 @@
1
- # Optional Russian front end (RUAccent stress + RUPhon phonemization).
2
- # Only installed when the image is built with --build-arg WITH_RUSSIAN=1: these
3
- # pull torch + transformers (~2.5 GB), which the default serverless image
4
- # deliberately excludes.
 
 
5
  #
6
  # The transformers pin is RUAccent/RUPhon's own. Note that RUPhon's bundled
7
  # tokenizer mis-sizes token_type_ids on transformers >= ~4.4x; g2p/russian_g2p.py
 
1
+ # Russian front end (RUAccent stress + RUPhon phonemization). Installed unless
2
+ # the image is built with --build-arg WITH_RUSSIAN=0.
3
+ #
4
+ # `torch` is listed for anyone installing this file directly, but the Dockerfile
5
+ # installs it first from the CPU wheel index: the front end runs on CPU
6
+ # (BLUE_RU_G2P_DEVICE defaults to CPU) and the default CUDA build would add ~2 GB.
7
  #
8
  # The transformers pin is RUAccent/RUPhon's own. Note that RUPhon's bundled
9
  # tokenizer mis-sizes token_type_ids on transformers >= ~4.4x; g2p/russian_g2p.py