Add files via upload
This commit is contained in:
1 parent
f35f861987
commit
6699c074ac
7 files changed
+1008
-215
No files matched your search
+168
-30
@@ -8,6 +8,8 @@ ElevenLabs – cloud API (API key required, best quality)
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import queue as _queue
|
||||
import threading
|
||||
from typing import Callable, Optional
|
||||
|
||||
@@ -15,6 +17,15 @@ import numpy as np
|
||||
import sounddevice as sd
|
||||
|
||||
|
||||
|
||||
# USE_TF=0 stops transformers from importing TensorFlow (saves 4-8 s startup).
|
||||
# Do NOT set USE_TORCH or USE_JAX explicitly — forcing those values breaks
|
||||
# transformers' lazy-loader on certain versions, causing AutoModel and other
|
||||
# classes to vanish from the public namespace. Auto-detection is reliable.
|
||||
os.environ.setdefault("USE_TF", "0")
|
||||
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Audio playback helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -41,17 +52,12 @@ def _to_numpy(samples) -> np.ndarray:
|
||||
def _compress_silence(
|
||||
arr: np.ndarray,
|
||||
sample_rate: int = 24_000,
|
||||
max_silence_ms: int = 300, # cap long pauses to this many ms
|
||||
threshold: float = 0.0015, # RMS below this = silence (very conservative)
|
||||
max_silence_ms: int = 500, # cap punctuation pauses — keeps natural rhythm
|
||||
threshold: float = 0.003, # RMS below this = silence; lower = less clipping
|
||||
) -> np.ndarray:
|
||||
"""
|
||||
Shorten excessively long silent segments in Kokoro audio.
|
||||
|
||||
Kokoro can produce 1-2 s pauses after punctuation. This caps them
|
||||
to max_silence_ms while leaving natural short pauses intact.
|
||||
|
||||
threshold is intentionally low (0.0015) so soft consonants like
|
||||
's', 'f', 'h' are never misidentified as silence.
|
||||
Shorten Kokoro's very long punctuation pauses (1-2 s → ≤500 ms).
|
||||
Conservative settings preserve natural prosody; only trims extreme pauses.
|
||||
"""
|
||||
max_samp = int(max_silence_ms * sample_rate / 1000)
|
||||
frame_len = 240 # ~10 ms at 24 kHz
|
||||
@@ -121,6 +127,74 @@ class EdgeTTSEngine:
|
||||
return bytes(buf)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Kokoro import helper — auto-upgrades on version-mismatch errors
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# Errors that indicate the installed kokoro uses old transformers classes
|
||||
# (AlbertModel, AutoModel) that are no longer exported at the top level.
|
||||
_KOKORO_COMPAT_ERRORS = ("AlbertModel", "AutoModel", "cannot import name")
|
||||
|
||||
|
||||
def _import_kokoro_pipeline():
|
||||
"""Import KPipeline, auto-upgrading kokoro if a version mismatch is found.
|
||||
|
||||
Old kokoro (<0.9) imports AlbertModel / AutoModel from transformers.
|
||||
Newer transformers versions no longer export these at the top level,
|
||||
causing an ImportError. kokoro>=0.9 removed these dependencies.
|
||||
|
||||
When the error is detected we:
|
||||
1. Upgrade kokoro to >=0.9 via pip (silent, background)
|
||||
2. Flush stale kokoro entries from sys.modules
|
||||
3. Re-import — this time it should succeed
|
||||
"""
|
||||
import sys
|
||||
|
||||
def _try_import():
|
||||
from kokoro import KPipeline # noqa: PLC0415
|
||||
return KPipeline
|
||||
|
||||
try:
|
||||
return _try_import()
|
||||
except Exception as first_err:
|
||||
err_msg = str(first_err)
|
||||
if not any(marker in err_msg for marker in _KOKORO_COMPAT_ERRORS):
|
||||
# Unrelated error (kokoro not installed, etc.)
|
||||
raise RuntimeError(
|
||||
f"Kokoro import failed: {first_err}\n"
|
||||
"Run: pip install kokoro>=0.9 soundfile"
|
||||
) from first_err
|
||||
|
||||
# ── Version mismatch: upgrade kokoro silently and retry ──────────
|
||||
print("[TTS] Kokoro/transformers version mismatch detected — upgrading kokoro…")
|
||||
import subprocess
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "pip", "install", "kokoro>=0.9",
|
||||
"--upgrade", "--quiet", "--disable-pip-version-check"],
|
||||
capture_output=True,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
stderr = result.stderr.decode(errors="replace").strip()
|
||||
raise RuntimeError(
|
||||
f"Kokoro auto-upgrade failed: {stderr[:200]}\n"
|
||||
"Run manually: pip install kokoro>=0.9 soundfile"
|
||||
) from first_err
|
||||
|
||||
# Flush any stale kokoro submodules from the import cache
|
||||
stale = [k for k in sys.modules if k == "kokoro" or k.startswith("kokoro.")]
|
||||
for key in stale:
|
||||
del sys.modules[key]
|
||||
|
||||
print("[TTS] Kokoro upgraded — retrying import…")
|
||||
try:
|
||||
return _try_import()
|
||||
except Exception as retry_err:
|
||||
raise RuntimeError(
|
||||
f"Kokoro still broken after upgrade: {retry_err}\n"
|
||||
"Run manually: pip install --upgrade kokoro transformers"
|
||||
) from retry_err
|
||||
|
||||
|
||||
# Kokoro voice prefix → KPipeline lang_code mapping
|
||||
_KOKORO_LANG_CODES = {
|
||||
"a": "a", # American English (af_*, am_*)
|
||||
@@ -140,19 +214,22 @@ _KOKORO_LANG_CODES = {
|
||||
class KokoroTTSEngine:
|
||||
"""Fully offline Kokoro neural TTS.
|
||||
|
||||
Model (~330 MB) is downloaded from HuggingFace on first use.
|
||||
Subsequent runs load from local cache instantly.
|
||||
Model (~330 MB) is downloaded from HuggingFace on first use,
|
||||
then cached locally — subsequent starts load from disk.
|
||||
|
||||
Warmup strategy: _init() runs synchronously in the background
|
||||
_do_tts() thread (not the UI thread). After the pipeline loads,
|
||||
a dummy inference compiles the PyTorch JIT graph immediately so
|
||||
the first real speak() call has zero compilation overhead.
|
||||
"""
|
||||
|
||||
def __init__(self, voice: str = "af_heart", speed: float = 1.2):
|
||||
def __init__(self, voice: str = "af_heart", speed: float = 1.0):
|
||||
self.voice = voice
|
||||
self.speed = speed # 1.0 = normal, 1.2 = 20% faster (recommended)
|
||||
self.speed = speed
|
||||
self._pipeline = None
|
||||
self._lock = threading.Lock()
|
||||
# Eager init: download/load model now so it's ready before first speak()
|
||||
self._init()
|
||||
self._init() # blocking, but called from background thread
|
||||
|
||||
# Detect lang_code from voice prefix (e.g. "af_heart" → "a")
|
||||
@property
|
||||
def _lang_code(self) -> str:
|
||||
prefix = self.voice[0].lower() if self.voice else "a"
|
||||
@@ -161,27 +238,88 @@ class KokoroTTSEngine:
|
||||
def _init(self) -> None:
|
||||
if self._pipeline is not None:
|
||||
return
|
||||
|
||||
lang = self._lang_code
|
||||
|
||||
# Prefer GPU — Kokoro on CUDA is ~10x faster than CPU.
|
||||
try:
|
||||
from kokoro import KPipeline
|
||||
lang = self._lang_code
|
||||
print(f"[TTS] Loading Kokoro pipeline (lang='{lang}', voice='{self.voice}')…")
|
||||
print("[TTS] Kokoro model will be downloaded (~330 MB) if not cached.")
|
||||
import torch
|
||||
device = "cuda" if torch.cuda.is_available() else "cpu"
|
||||
if device == "cpu":
|
||||
import os as _os
|
||||
n_threads = max(1, min(4, (_os.cpu_count() or 4) // 2))
|
||||
try:
|
||||
torch.set_num_threads(n_threads)
|
||||
torch.set_num_interop_threads(2)
|
||||
except RuntimeError:
|
||||
pass
|
||||
print(
|
||||
f"[TTS] Kokoro on CPU — for faster speech install CUDA PyTorch:\n"
|
||||
" pip install torch --index-url https://download.pytorch.org/whl/cu118"
|
||||
)
|
||||
except Exception:
|
||||
device = "cpu"
|
||||
|
||||
print(f"[TTS] Kokoro — loading (lang='{lang}', device='{device}')…")
|
||||
|
||||
KPipeline = _import_kokoro_pipeline()
|
||||
|
||||
try:
|
||||
self._pipeline = KPipeline(lang_code=lang, device=device)
|
||||
except TypeError:
|
||||
# Older Kokoro build — no device parameter
|
||||
self._pipeline = KPipeline(lang_code=lang)
|
||||
print("[TTS] Kokoro pipeline ready.")
|
||||
|
||||
print("[TTS] Kokoro compiling (first-time only)…")
|
||||
# Warmup: compiles PyTorch JIT graph so first real speak() call is instant.
|
||||
try:
|
||||
for _ in self._pipeline("hello", voice=self.voice, speed=self.speed):
|
||||
pass
|
||||
print("[TTS] Kokoro ready.")
|
||||
except Exception as e:
|
||||
print(f"[TTS] Kokoro init error: {e}")
|
||||
raise
|
||||
print(f"[TTS] Kokoro warmup warning: {e}")
|
||||
|
||||
def speak(self, text: str) -> None:
|
||||
with self._lock:
|
||||
if self._pipeline is None:
|
||||
self._init()
|
||||
for _, _, audio in self._pipeline(text, voice=self.voice, speed=self.speed):
|
||||
if audio is not None:
|
||||
arr = _to_numpy(audio)
|
||||
arr = _compress_silence(arr) # shorten long punctuation pauses
|
||||
if arr.size > 0:
|
||||
_play_np(arr, 24000)
|
||||
|
||||
# ── Concurrent synthesise + playback ────────────────────────────────
|
||||
# Kokoro generates audio chunks lazily. Without threading, we:
|
||||
# synthesise chunk N → play N → synthesise N+1 → play N+1 …
|
||||
# With a producer/consumer pair, chunk N+1 synthesises WHILE chunk N
|
||||
# plays, cutting perceived latency by the playback duration of all but
|
||||
# the last chunk (typically 1-3 s on multi-sentence responses).
|
||||
audio_q: "_queue.Queue[np.ndarray | None]" = _queue.Queue(maxsize=4)
|
||||
synth_error: list[Exception] = []
|
||||
|
||||
def _synth():
|
||||
try:
|
||||
for _, _, audio in self._pipeline(text, voice=self.voice, speed=self.speed):
|
||||
if audio is not None:
|
||||
arr = _to_numpy(audio)
|
||||
arr = _compress_silence(arr)
|
||||
if arr.size > 0:
|
||||
audio_q.put(arr) # blocks if player is slow (backpressure)
|
||||
except Exception as exc:
|
||||
synth_error.append(exc)
|
||||
finally:
|
||||
audio_q.put(None) # sentinel → player exits
|
||||
|
||||
synth_thread = threading.Thread(target=_synth, daemon=True)
|
||||
synth_thread.start()
|
||||
|
||||
# Player runs in this thread so sd.wait() doesn't block the synth thread.
|
||||
while True:
|
||||
arr = audio_q.get()
|
||||
if arr is None:
|
||||
break
|
||||
_play_np(arr, 24000)
|
||||
|
||||
synth_thread.join()
|
||||
|
||||
if synth_error:
|
||||
raise synth_error[0]
|
||||
|
||||
|
||||
class ElevenLabsTTSEngine:
|
||||
@@ -264,7 +402,7 @@ def create_tts_player(config: dict) -> TTSPlayer:
|
||||
engine_name = config.get("tts_engine", "edgetts").lower()
|
||||
if engine_name == "kokoro":
|
||||
voice = config.get("tts_voice", "af_heart")
|
||||
speed = float(config.get("tts_speed", 1.2))
|
||||
speed = float(config.get("tts_speed", 1.0))
|
||||
engine = KokoroTTSEngine(voice=voice, speed=speed)
|
||||
elif engine_name == "elevenlabs":
|
||||
api_key = config.get("elevenlabs_api_key", "")
|
||||
|
||||
Reference in new issue
Block a user