pnnbao-ump Claude Opus 4.8 (1M context) commited on
Commit
335be2c
·
1 Parent(s): c0d71f4

fix(chunking): v3 chunks by normalized-TEXT length like v2-gpu (not phoneme); bump v3.0.7

Browse files

The v3 Turbo path chunked at the PHONEME level (chunk_phonemes), but phonemes run
~1.2-1.4x longer than text, so at the same max_chars it split far more than the
v2-gpu path (which chunks normalized TEXT via normalize_to_chunks) → choppy,
extra mid-turn pauses in conversation.

- Add normalize_to_chunks_v3: chunk by normalized-text length identical to v2-gpu,
while preserving inline emotion cues ([cười]/<|emotion_k|>) that plain
normalize would otherwise strip; phonemize each chunk afterwards. With no cues
it delegates to normalize_to_chunks → byte-identical to v2-gpu.
- v3 Turbo infer/infer_stream, gradio v3 standard + conversation paths now use it.
- Remove now-unused chunk_phonemes helper.

Result: v2-gpu and v3-turbo now chunk consistently (e.g. 8 vs previously 10).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

apps/gradio_main.py CHANGED
@@ -21,7 +21,7 @@ import threading
21
  import yaml
22
  import uuid
23
  from vieneu_utils.core_utils import join_audio_chunks, env_bool, get_silence_duration_v2
24
- from vieneu_utils.phonemize_text import phonemize_to_chunks, normalize_to_chunks, chunk_phonemes
25
  # PuncNormalizer = sea_g2p.Normalizer luôn bật punc_norm=True.
26
  from vieneu_utils.phonemize_text import PuncNormalizer as Normalizer
27
  import gc
@@ -878,11 +878,9 @@ def synthesize_speech(text: str, voice_choice: str, custom_audio, custom_text: s
878
  try:
879
  from vieneu_utils.phonemize_text import phonemize_text_with_emotions
880
 
881
- # Chia chunk SAU normalize: phonemize CẢ văn bản trước (normalize +
882
- # G2P + giữ inline cues) rồi chia thường (gộp câu, mỗi chunk kết
883
- # thúc bằng . ! ?).
884
- v3_phonemes = phonemize_text_with_emotions(raw_text)
885
- v3_chunks = chunk_phonemes(v3_phonemes, max_chars=max_chars_chunk)
886
  v3_bs = max(1, int(max_batch_size_run)) if use_batch else 1
887
  v3_engine_dev = getattr(getattr(tts, "engine", None), "device", None)
888
  v3_can_batch = (
@@ -901,9 +899,9 @@ def synthesize_speech(text: str, voice_choice: str, custom_audio, custom_text: s
901
  return
902
  group = v3_chunks[i:i + v3_bs]
903
  yield None, f"⚡ v3 Turbo: lô {i // v3_bs + 1} ({len(group)} đoạn, batch size {v3_bs})..."
904
- # group là các chuỗi phoneme đã sẵn sàng (đã normalize+G2P).
905
- reqs = [{"phonemes": ph, "ref_codes": ref_codes,
906
- "voice_token_id": v3_voice_token_id} for ph in group]
907
  v3_wavs.extend(tts._v3_batch_engine.generate_batch(
908
  reqs, temperature=temperature, max_new_frames=300))
909
  wav = join_audio_chunks(v3_wavs, sr=sr_v3, silence_p=0.15)
@@ -1309,7 +1307,7 @@ def _synthesize_conversation_v3(lines, mapping, temperature, max_chars_chunk, si
1309
  global tts
1310
  from collections import defaultdict
1311
  from vieneu_utils.core_utils import join_audio_chunks
1312
- from vieneu_utils.phonemize_text import phonemize_text_with_emotions, chunk_phonemes
1313
  # NOTE: KHÔNG import vieneu.v3_turbo_serve ở đây — module đó import torch ở cấp
1314
  # module, nên trên bản cài CPU/macOS không-torch (ONNX) sẽ lỗi "No module named
1315
  # 'torch'". Chỉ import bên trong nhánh CUDA bên dưới (nơi thực sự cần batch engine).
@@ -1372,10 +1370,10 @@ def _synthesize_conversation_v3(lines, mapping, temperature, max_chars_chunk, si
1372
  if key not in voice_cache:
1373
  voice_cache[key] = _voice_for(line['speaker'])
1374
  ref_codes, vtok = voice_cache[key]
1375
- # Chia chunk SAU normalize: phonemize cả lượt thoại trước rồi chia thường.
1376
- line_phonemes = phonemize_text_with_emotions(line['text'])
1377
- for ph in chunk_phonemes(line_phonemes, max_chars=max_chars_chunk):
1378
- reqs.append({"phonemes": ph,
1379
  "ref_codes": ref_codes, "voice_token_id": vtok})
1380
  req_line.append(li)
1381
 
 
21
  import yaml
22
  import uuid
23
  from vieneu_utils.core_utils import join_audio_chunks, env_bool, get_silence_duration_v2
24
+ from vieneu_utils.phonemize_text import phonemize_to_chunks, normalize_to_chunks, normalize_to_chunks_v3
25
  # PuncNormalizer = sea_g2p.Normalizer luôn bật punc_norm=True.
26
  from vieneu_utils.phonemize_text import PuncNormalizer as Normalizer
27
  import gc
 
878
  try:
879
  from vieneu_utils.phonemize_text import phonemize_text_with_emotions
880
 
881
+ # Chia chunk theo TEXT đã normalize (giống v2-gpu, không vụn), giữ
882
+ # inline cues; phonemize TỪNG chunk khi dựng request.
883
+ v3_chunks = normalize_to_chunks_v3(raw_text, max_chars=max_chars_chunk)
 
 
884
  v3_bs = max(1, int(max_batch_size_run)) if use_batch else 1
885
  v3_engine_dev = getattr(getattr(tts, "engine", None), "device", None)
886
  v3_can_batch = (
 
899
  return
900
  group = v3_chunks[i:i + v3_bs]
901
  yield None, f"⚡ v3 Turbo: lô {i // v3_bs + 1} ({len(group)} đoạn, batch size {v3_bs})..."
902
+ # group là các TEXT chunk -> phonemize từng cái (giữ inline cues).
903
+ reqs = [{"phonemes": phonemize_text_with_emotions(c), "ref_codes": ref_codes,
904
+ "voice_token_id": v3_voice_token_id} for c in group]
905
  v3_wavs.extend(tts._v3_batch_engine.generate_batch(
906
  reqs, temperature=temperature, max_new_frames=300))
907
  wav = join_audio_chunks(v3_wavs, sr=sr_v3, silence_p=0.15)
 
1307
  global tts
1308
  from collections import defaultdict
1309
  from vieneu_utils.core_utils import join_audio_chunks
1310
+ from vieneu_utils.phonemize_text import phonemize_text_with_emotions, normalize_to_chunks_v3
1311
  # NOTE: KHÔNG import vieneu.v3_turbo_serve ở đây — module đó import torch ở cấp
1312
  # module, nên trên bản cài CPU/macOS không-torch (ONNX) sẽ lỗi "No module named
1313
  # 'torch'". Chỉ import bên trong nhánh CUDA bên dưới (nơi thực sự cần batch engine).
 
1370
  if key not in voice_cache:
1371
  voice_cache[key] = _voice_for(line['speaker'])
1372
  ref_codes, vtok = voice_cache[key]
1373
+ # Chia chunk theo TEXT đã normalize (giống v2-gpu), giữ inline cues, rồi
1374
+ # phonemize từng chunk.
1375
+ for chunk in normalize_to_chunks_v3(line['text'], max_chars=max_chars_chunk):
1376
+ reqs.append({"phonemes": phonemize_text_with_emotions(chunk),
1377
  "ref_codes": ref_codes, "voice_token_id": vtok})
1378
  req_line.append(li)
1379
 
pyproject.toml CHANGED
@@ -33,7 +33,7 @@ explicit = true
33
 
34
  [project]
35
  name = "vieneu"
36
- version = "3.0.6"
37
  description = "Advanced on-device Vietnamese TTS with instant voice cloning"
38
  readme = "README_PYPI.md"
39
  license = { file = "LICENSE" }
 
33
 
34
  [project]
35
  name = "vieneu"
36
+ version = "3.0.7"
37
  description = "Advanced on-device Vietnamese TTS with instant voice cloning"
38
  readme = "README_PYPI.md"
39
  license = { file = "LICENSE" }
src/vieneu/v3turbo.py CHANGED
@@ -13,7 +13,7 @@ from typing import Any, Generator, List, Optional, Union
13
  import numpy as np
14
 
15
  from .base import BaseVieneuTTS
16
- from vieneu_utils.phonemize_text import phonemize_text_with_emotions, chunk_phonemes
17
  from vieneu_utils.core_utils import join_audio_chunks
18
 
19
  logger = logging.getLogger("Vieneu.V3Turbo")
@@ -186,16 +186,15 @@ class V3TurboVieNeuTTS(BaseVieneuTTS):
186
  ) -> np.ndarray:
187
  ref_codes, voice_token_id = self._resolve_v3_ref(voice, ref_audio, ref_codes)
188
 
189
- # Chia chunk SAU normalize: phonemize CẢ văn bản trước (normalize + G2P +
190
- # giữ inline cues), rồi cắt ở tầng PHONEME bằng cách chia thường (gộp câu
191
- # tham lam) — mỗi chunk luôn kết thúc bằng dấu câu (. ! ?).
192
- phonemes_full = phonemize_text_with_emotions(text) # SEAPipeline + inline cues
193
- chunks = chunk_phonemes(phonemes_full, max_chars=max_chars)
194
  if not chunks:
195
  return np.array([], dtype=np.float32)
196
 
197
  all_wavs: List[np.ndarray] = []
198
- for ph in chunks:
 
199
  wav = self.engine.infer(
200
  text="", phonemes=ph, ref_codes=ref_codes,
201
  emotion=emotion, voice_token_id=voice_token_id,
@@ -224,10 +223,10 @@ class V3TurboVieNeuTTS(BaseVieneuTTS):
224
  **kwargs: Any,
225
  ) -> Generator[np.ndarray, None, None]:
226
  ref_codes, voice_token_id = self._resolve_v3_ref(voice, ref_audio, ref_codes)
227
- # Chia chunk SAU normalize: phonemize cả văn bản rồi chia thường (gộp câu).
228
- phonemes_full = phonemize_text_with_emotions(text)
229
- chunks = chunk_phonemes(phonemes_full, max_chars=max_chars)
230
- for ph in chunks:
231
  wav = self.engine.infer(
232
  text="", phonemes=ph, ref_codes=ref_codes,
233
  emotion=emotion, voice_token_id=voice_token_id,
 
13
  import numpy as np
14
 
15
  from .base import BaseVieneuTTS
16
+ from vieneu_utils.phonemize_text import phonemize_text_with_emotions, normalize_to_chunks_v3
17
  from vieneu_utils.core_utils import join_audio_chunks
18
 
19
  logger = logging.getLogger("Vieneu.V3Turbo")
 
186
  ) -> np.ndarray:
187
  ref_codes, voice_token_id = self._resolve_v3_ref(voice, ref_audio, ref_codes)
188
 
189
+ # Chia chunk theo TEXT đã normalize (giống v2-gpu, không vụn như cắt ở
190
+ # tầng phoneme), giữ inline cues, rồi phonemize TỪNG chunk.
191
+ chunks = normalize_to_chunks_v3(text, max_chars=max_chars)
 
 
192
  if not chunks:
193
  return np.array([], dtype=np.float32)
194
 
195
  all_wavs: List[np.ndarray] = []
196
+ for chunk in chunks:
197
+ ph = phonemize_text_with_emotions(chunk)
198
  wav = self.engine.infer(
199
  text="", phonemes=ph, ref_codes=ref_codes,
200
  emotion=emotion, voice_token_id=voice_token_id,
 
223
  **kwargs: Any,
224
  ) -> Generator[np.ndarray, None, None]:
225
  ref_codes, voice_token_id = self._resolve_v3_ref(voice, ref_audio, ref_codes)
226
+ # Chia chunk theo TEXT đã normalize (giống v2-gpu), giữ inline cues.
227
+ chunks = normalize_to_chunks_v3(text, max_chars=max_chars)
228
+ for chunk in chunks:
229
+ ph = phonemize_text_with_emotions(chunk)
230
  wav = self.engine.infer(
231
  text="", phonemes=ph, ref_codes=ref_codes,
232
  emotion=emotion, voice_token_id=voice_token_id,
src/vieneu_utils/phonemize_text.py CHANGED
@@ -248,23 +248,38 @@ def normalize_to_chunks(
248
  ]
249
 
250
 
251
- def chunk_phonemes(phonemes: str, max_chars: int = 256) -> list[str]:
252
- """Chia chuỗi phoneme (đã normalize + G2P, giữ inline cues) thành các chunk
253
- <= ``max_chars`` bằng CÁCH CHIA THƯỜNG (gộp câu tham lam, không vụn từng câu
254
- như ``split_into_chunks_v2``). Mỗi chunk được chốt dấu câu kết thúc hợp lệ
255
- (``.`` ``!`` ``?``) — kể cả khi một câu quá dài bị cắt theo cụm/từ.
256
-
257
- Dùng cho các đường phoneme-level (v3 Turbo, inline emotion) để chunk vừa
258
- không phình quá giới hạn vừa luôn kết thúc bằng dấu câu.
 
 
 
259
  """
260
  from vieneu_utils.core_utils import split_text_into_chunks
261
 
262
- if not phonemes:
263
  return []
264
- return [
265
- punc_norm(c)
266
- for c in split_text_into_chunks(phonemes, max_chars=max_chars)
267
- ]
 
 
 
 
 
 
 
 
 
 
 
 
268
 
269
 
270
  def phonemize_to_chunks(
 
248
  ]
249
 
250
 
251
+ def normalize_to_chunks_v3(text: str, max_chars: int = 256) -> list[str]:
252
+ """Chia chunk cho đường v3 GIỐNG HỆT v2-gpu: cắt theo độ dài TEXT ĐÃ normalize.
253
+
254
+ Đường v3 trước đây cắt ở tầng PHONEME (``chunk_phonemes``), mà phoneme dài hơn
255
+ text ~1.2-1.4x nên cùng ``max_chars`` lại cắt vụn hơn v2-gpu. Hàm này cắt theo
256
+ text-length như ``normalize_to_chunks`` (v2-gpu) để số chunk khớp nhau, ĐỒNG
257
+ THỜI giữ inline emotion cue (``[cười]``/``<|emotion_k|>`` -> ``<|emotion_k|>``)
258
+ mà ``normalize_to_chunks`` thường sẽ nuốt mất (dấu ``[...]`` bị xoá khi normalize).
259
+
260
+ Trả về list TEXT chunk (mỗi chunk có thể chứa ``<|emotion_k|>``); caller
261
+ phonemize từng chunk bằng :func:`phonemize_text_with_emotions`.
262
  """
263
  from vieneu_utils.core_utils import split_text_into_chunks
264
 
265
+ if not text:
266
  return []
267
+ # Không có emotion cue -> dùng thẳng đường v2-gpu (kết quả giống hệt).
268
+ if "[" not in text and "<|emotion_" not in text:
269
+ return normalize_to_chunks(text, max_chars=max_chars)
270
+
271
+ # Có cue: normalize từng đoạn text giữa các cue, chèn lại token cảm xúc, rồi
272
+ # cắt theo text-length (token <|emotion_k|> được splitter giữ nguyên là 1 từ).
273
+ normalizer = _get_normalizer()
274
+ rebuilt = []
275
+ for i, part in enumerate(_EMOTION_SPLIT_RE.split(text)):
276
+ if i % 2 == 1: # emotion tag
277
+ tok = _emotion_tag_token(part)
278
+ rebuilt.append(tok if tok is not None else part)
279
+ elif part.strip(): # đoạn text: normalize, giữ dấu (không ép câu)
280
+ rebuilt.append(normalizer.normalize(part, punc_norm=False))
281
+ normalized = " ".join(p for p in rebuilt if p)
282
+ return [punc_norm(c) for c in split_text_into_chunks(normalized, max_chars=max_chars)]
283
 
284
 
285
  def phonemize_to_chunks(
uv.lock CHANGED
@@ -5463,7 +5463,7 @@ wheels = [
5463
 
5464
  [[package]]
5465
  name = "vieneu"
5466
- version = "3.0.6"
5467
  source = { editable = "." }
5468
  dependencies = [
5469
  { name = "gradio" },
 
5463
 
5464
  [[package]]
5465
  name = "vieneu"
5466
+ version = "3.0.7"
5467
  source = { editable = "." }
5468
  dependencies = [
5469
  { name = "gradio" },