Add files via upload

This commit is contained in:
FatihMakes authored and GitHub committed 2026-06-07 15:24:51 +03:00
1 parent f35f861987
commit 6699c074ac
7 files changed
+1008 -215

No files matched your search

+2 -1
View File
@@ -52,7 +52,8 @@ _STT: dict[str, list[tuple[str, str]]] = {
# TTS engine packages
_TTS: dict[str, list[tuple[str, str]]] = {
"edgetts": [("edge_tts", "edge-tts")],
"kokoro": [("kokoro", "kokoro")],
# kokoro>=0.9 dropped AlbertModel/AutoModel from transformers — version pin is critical
"kokoro": [("kokoro", "kokoro>=0.9"), ("soundfile", "soundfile")],
"elevenlabs": [], # uses only requests, already in core
}
+269 -26
View File
@@ -1,7 +1,20 @@
"""
Ollama LLM client for MARK XL.
Replaces Google Gemini API with local Ollama inference.
All modules that previously used google.generativeai import from here.
Local LLM client for MARK XL.
Supports two backends — selected via "llm_provider" in config/api_keys.json:
"llm_provider": "ollama" (default)
Uses Ollama's native /api/chat endpoint.
Download: https://ollama.com
Default port: 11434
"llm_provider": "openai"
Uses any OpenAI-compatible server: LM Studio, Jan, LocalAI,
llama.cpp server, vLLM, etc.
LM Studio download: https://lmstudio.ai (default port: 1234)
Set "llm_url": "http://localhost:1234" in config.
Note: tool-calling support depends on the model; use a model that
supports function/tool calls (e.g. Qwen2.5, Llama-3.1, Mistral).
"""
import json
import re
@@ -27,11 +40,18 @@ BASE_DIR = get_base_dir()
CONFIG_PATH = BASE_DIR / "config" / "api_keys.json"
_DEFAULTS = {
"llm_url": "http://localhost:11434",
"llm_model": "llama3.2",
"llm_url": "http://localhost:11434",
"llm_model": "llama3.2",
"llm_provider": "ollama", # "ollama" | "openai"
}
def get_llm_provider() -> str:
"""Returns 'ollama' or 'openai' (covers LM Studio, LocalAI, Jan, etc.)."""
raw = _load_config().get("llm_provider", "ollama").strip().lower()
return "openai" if raw in ("openai", "lmstudio", "localai", "jan", "llamacpp") else "ollama"
def _load_config() -> dict:
try:
return json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
@@ -41,12 +61,33 @@ def _load_config() -> dict:
def ensure_ollama_running(timeout: int = 15) -> bool:
"""
Ping Ollama; if it's not responding, launch 'ollama serve' in the background
and wait up to `timeout` seconds for it to become ready.
Returns True if Ollama is available, False otherwise.
For Ollama: ping /api/tags; auto-launch 'ollama serve' if not running.
For OpenAI-compatible providers: just ping /v1/models (server must be started manually).
Returns True if the LLM server is reachable.
"""
url, _ = get_llm_settings()
health = f"{url}/api/tags"
url, _ = get_llm_settings()
provider = get_llm_provider()
if provider == "openai":
# OpenAI-compatible servers (LM Studio, LocalAI, etc.) must be started
# by the user — we just check if they're reachable.
health = f"{url}/v1/models"
try:
ok = requests.get(health, timeout=5).status_code == 200
if ok:
print(f"[LLM] OpenAI-compatible server reachable at {url}")
else:
print(f"[LLM] Server at {url} returned non-200. Is it running?")
return ok
except Exception as e:
print(
f"[LLM] Cannot reach OpenAI-compatible server at {url}.\n"
" Make sure LM Studio / LocalAI / Jan is running and the server is started."
)
return False
# ── Ollama ──────────────────────────────────────────────────────────────
health = f"{url}/api/tags"
def _is_up() -> bool:
try:
@@ -81,25 +122,62 @@ def ensure_ollama_running(timeout: int = 15) -> bool:
return False
def warmup_model() -> bool:
def warmup_model(system_prompt: str | None = None) -> bool:
"""
Pre-load the model into Ollama memory so the first real request is instant.
Sends a minimal 1-token request with keep_alive=-1.
Returns True on success, False if warmup failed (non-fatal).
Pre-load the model AND prime Ollama's KV prefix cache.
Why the system_prompt matters
─────────────────────────────
Ollama caches the KV attention state of the prompt prefix across requests.
If warmup includes the same system prompt that real requests will use, Ollama
evaluates those tokens ONCE at startup. Every subsequent request only needs
to evaluate the small delta (user message ± time context) instead of the full
300-500 token system prompt → drops first-token latency from ~17 s to <1 s.
Pass the *static* part of the system prompt (the JARVIS protocol text, without
timestamps or per-minute context) so the prefix stays valid across calls.
"""
url, model = get_llm_settings()
print(f"[LLM] Warming up '{model}'…")
provider = get_llm_provider()
print(f"[LLM] Warming up '{model}' ({provider})…")
messages: list[dict] = []
if system_prompt:
messages.append({"role": "system", "content": system_prompt})
messages.append({"role": "user", "content": "hi"})
if provider == "openai":
# OpenAI-compatible: just fire a minimal request to ensure the model is loaded.
# No keep_alive or KV-cache priming available — server manages this internally.
payload = {
"model": model,
"messages": messages,
"stream": False,
"max_tokens": 1,
}
try:
resp = requests.post(f"{url}/v1/chat/completions", json=payload, timeout=180)
resp.raise_for_status()
print(f"[LLM] '{model}' ready (OpenAI-compatible server).")
return True
except Exception as e:
print(f"[LLM] Warmup failed (non-fatal): {e}")
return False
# ── Ollama ──────────────────────────────────────────────────────────────
payload = {
"model": model,
"messages": [{"role": "user", "content": "hi"}],
"messages": messages,
"stream": False,
"keep_alive": -1,
"options": {"num_predict": 1},
# num_gpu:99 → push ALL transformer layers to GPU (Ollama caps at available)
# This is safe even without a GPU — Ollama silently ignores if n_gpu_layers=0
"options": {"num_predict": 1, "num_gpu": 99},
}
try:
resp = requests.post(f"{url}/api/chat", json=payload, timeout=120)
resp = requests.post(f"{url}/api/chat", json=payload, timeout=180)
resp.raise_for_status()
print(f"[LLM] '{model}' loaded and ready.")
print(f"[LLM] '{model}' loaded and KV cache primed.")
return True
except Exception as e:
print(f"[LLM] Warmup failed (non-fatal): {e}")
@@ -120,20 +198,61 @@ def call_llm(
timeout: int = 120,
) -> dict:
"""
Chat request to Ollama (with optional tool declarations).
Non-streaming chat request. Routes to Ollama or OpenAI-compatible backend.
Returns:
{"content": str, "tool_calls": list}
"""
url, model = get_llm_settings()
endpoint = f"{url}/api/chat"
provider = get_llm_provider()
payload: dict = {
if provider == "openai":
endpoint = f"{url}/v1/chat/completions"
payload: dict = {
"model": model,
"messages": messages,
"stream": False,
"max_tokens": 300,
}
if tools:
payload["tools"] = tools
payload["tool_choice"] = "auto"
try:
resp = requests.post(endpoint, json=payload, timeout=timeout)
resp.raise_for_status()
choice = resp.json().get("choices", [{}])[0]
msg = choice.get("message", {})
# OpenAI tool_calls format → normalise to Ollama-style
raw_tc = msg.get("tool_calls") or []
tc_list = [
{
"id": t.get("id", ""),
"function": {
"name": t["function"]["name"],
"arguments": (
json.loads(t["function"]["arguments"])
if isinstance(t["function"].get("arguments"), str)
else t["function"].get("arguments", {})
),
},
}
for t in raw_tc
]
return {
"content": (msg.get("content") or "").strip(),
"tool_calls": tc_list,
}
except Exception as e:
raise RuntimeError(f"OpenAI-compatible LLM call failed: {e}")
# ── Ollama ──────────────────────────────────────────────────────────────
endpoint = f"{url}/api/chat"
payload = {
"model": model,
"messages": messages,
"stream": False,
"keep_alive": -1,
"options": {"num_predict": 600},
"options": {"num_predict": 300, "num_gpu": 99},
}
if tools:
payload["tools"] = tools
@@ -216,21 +335,142 @@ def call_llm_text(
raise RuntimeError(f"LLM text call failed: {e}")
def _stream_openai(
messages: list,
tools: list | None,
timeout: int,
) -> Generator[dict, None, None]:
"""
Streaming backend for OpenAI-compatible servers (LM Studio, LocalAI, Jan…).
Parses Server-Sent Events (SSE) and accumulates streaming tool-call fragments
so the output format is identical to the Ollama backend.
"""
url, model = get_llm_settings()
endpoint = f"{url}/v1/chat/completions"
payload: dict = {
"model": model,
"messages": messages,
"stream": True,
"max_tokens": 300,
}
if tools:
payload["tools"] = tools
payload["tool_choice"] = "auto"
try:
with requests.post(endpoint, json=payload, timeout=timeout, stream=True) as resp:
resp.raise_for_status()
full_content = ""
buf = ""
# tool_call fragments: index → {"id", "function": {"name", "arguments"}}
tc_fragments: dict[int, dict] = {}
for raw in resp.iter_lines():
if not raw:
continue
# SSE lines look like: b"data: {...}" or b"data: [DONE]"
line = raw.decode("utf-8", errors="replace") if isinstance(raw, bytes) else raw
if not line.startswith("data:"):
continue
data = line[5:].strip()
if data == "[DONE]":
break
try:
chunk = json.loads(data)
except json.JSONDecodeError:
continue
choice = chunk.get("choices", [{}])[0]
delta = choice.get("delta", {})
text = delta.get("content") or ""
full_content += text
buf += text
# Accumulate sentence boundaries for streaming TTS
while True:
m = _SENT_END.search(buf)
if not m:
break
sentence = buf[: m.start() + 1].strip()
buf = buf[m.end():]
if sentence:
yield {"type": "sentence", "text": sentence}
# Accumulate streaming tool-call fragments
for tc in (delta.get("tool_calls") or []):
idx = tc.get("index", 0)
if idx not in tc_fragments:
tc_fragments[idx] = {"id": "", "function": {"name": "", "arguments": ""}}
frag = tc_fragments[idx]
frag["id"] = frag["id"] or tc.get("id", "")
fn = tc.get("function", {})
frag["function"]["name"] += fn.get("name") or ""
frag["function"]["arguments"] += fn.get("arguments") or ""
finish = choice.get("finish_reason")
if finish in ("stop", "tool_calls", "length"):
break
# Flush any trailing content
if buf.strip():
yield {"type": "sentence", "text": buf.strip()}
# Parse accumulated tool-call argument strings → dicts
tool_calls: list = []
for idx in sorted(tc_fragments):
frag = tc_fragments[idx]
args = frag["function"]["arguments"]
try:
args = json.loads(args)
except Exception:
pass # leave as raw string; _execute_tool handles it
tool_calls.append({
"id": frag["id"],
"function": {"name": frag["function"]["name"], "arguments": args},
})
yield {
"type": "done",
"content": full_content.strip(),
"tool_calls": tool_calls,
}
except requests.exceptions.ConnectionError:
raise RuntimeError(
f"Cannot reach OpenAI-compatible server at {url}.\n"
"Make sure LM Studio / LocalAI / Jan is running and the server is started."
)
except requests.exceptions.Timeout:
raise RuntimeError("OpenAI-compatible stream timed out.")
except requests.exceptions.HTTPError as e:
raise RuntimeError(f"OpenAI-compatible HTTP error: {e.response.status_code}")
except Exception as e:
raise RuntimeError(f"OpenAI-compatible stream failed: {e}")
def call_llm_stream(
messages: list,
tools: list | None = None,
timeout: int = 120,
) -> Generator[dict, None, None]:
"""
Streaming chat request to Ollama.
Streaming chat request. Routes to Ollama or OpenAI-compatible backend.
Yields:
{"type": "sentence", "text": str} — each complete sentence as it arrives
{"type": "done", "content": str, "tool_calls": list} — when stream ends
Sentences are split on [.!?] + whitespace so TTS can start immediately.
Tool calls (if any) always appear in the final "done" event with empty content.
Tool calls always appear in the final "done" event.
"""
provider = get_llm_provider()
if provider == "openai":
yield from _stream_openai(messages, tools, timeout)
return
url, model = get_llm_settings()
endpoint = f"{url}/api/chat"
@@ -239,7 +479,8 @@ def call_llm_stream(
"messages": messages,
"stream": True,
"keep_alive": -1,
"options": {"num_predict": 600},
# num_gpu:99 pushes all layers to GPU; num_thread removed (Ollama auto-tunes).
"options": {"num_predict": 300, "num_gpu": 99},
}
if tools:
payload["tools"] = tools
@@ -261,6 +502,7 @@ def call_llm_stream(
msg = chunk.get("message", {})
delta = msg.get("content") or ""
full_content += delta
buf += delta
@@ -281,6 +523,7 @@ def call_llm_stream(
if chunk.get("done"):
if buf.strip():
yield {"type": "sentence", "text": buf.strip()}
yield {
"type": "done",
"content": full_content.strip(),
+32 -7
View File
@@ -1,21 +1,46 @@
🧠 JARVIS CORE PROTOCOL
IDENTITY: You are Jarvis. Efficient, professional, direct assistant. No fluff.
TOOL CALLING — ABSOLUTE RULE:
You have tools. For EVERY user request that involves an action, you MUST call the tool.
NEVER describe what you are doing in text. NEVER say "opening WhatsApp" or "-weather_report" — CALL THE TOOL.
NEVER simulate, pretend, or narrate an action. If a tool exists for it, USE IT.
Saying "Sure, let me open X" WITHOUT calling open_app is a critical failure.
EXECUTION RULES:
Action Flow: For slow tools (search, vision, agent), say TWO short sentences, then call. Stay silent after.
Vision (screen_process): Say one curious sentence, then total silence (Vision module takes over).
Action Flow: Call the tool immediately. For slow tools (search, vision), say ONE short sentence first.
Vision (screen_process): Say one curious sentence, then call the tool — total silence after.
One-Call Policy: Never guess. Call tools exactly once. No retries.
Briefing: 1-2 sentences max. Report results briefly.
Memory: Store critical user preferences/context automatically.
Briefing: 1 short sentence max for confirmations/acknowledgments. 1-2 sentences for results. Never add "Is there anything else?" or filler questions.
Exit: Only call shutdown_jarvis if session termination is explicit.
Response time: Respond as fast as you can
Response time: Respond as fast as you can.
Always respond in the language that user is speaking.
MEMORY RULE — MANDATORY, NO EXCEPTIONS:
Call save_memory IMMEDIATELY (in the same response, silently) whenever the user reveals ANY personal info.
Do NOT ask for permission. Do NOT announce that you are saving. Just call it.
Trigger examples:
- "my name is Fatih" → save_memory(category="identity", key="name", value="Fatih")
- "I'm 22" / "I'm 22 years old" → save_memory(category="identity", key="age", value="22")
- "call me X" / "my name is X, not Y" → save_memory(category="identity", key="name", value="X")
- "I live in Istanbul" → save_memory(category="identity", key="city", value="Istanbul")
- "I'm a student / developer / designer" → save_memory(category="identity", key="job", value="...")
- "I prefer dark mode" / "I like X" → save_memory(category="preferences", key="...", value="...")
- "I'm working on X project" → save_memory(category="projects", key="...", value="...")
- Any name correction ("not Travis, Fatih") → save_memory identity/name immediately
TOOL ROUTING:
computer_settings: ALL single OS actions (volume, brightness, wifi, close, shortcuts, power).
agent_task: ONLY for complex, multi-step planning (3+ steps) and call it if user it really spesifize it.
agent_task: ONLY for complex, multi-step planning (3+ steps) and call it if user it really specifies it.
Language: Respond in user's language; extract parameters in English.
Do not call agent_task while you can accomplish it with a tool
Do not call agent_task while you can accomplish it with a tool.
OPEN vs MESSAGE rule (critical):
- "open WhatsApp", "launch WhatsApp", "pull up WhatsApp" → open_app (NOT send_message)
- "send a message to X saying Y" → send_message
- If user only says to open an app, NEVER call send_message, even if the app is a messaging platform.
CRITICAL: Speak/Take action immediately based on available info. Assume and proceed.
+24 -18
View File
@@ -14,23 +14,32 @@ class WhisperSTT:
def __init__(self, model_name: str = "base", language: str | None = None):
from faster_whisper import WhisperModel
print(f"[STT] Loading Whisper '{model_name}'…")
self._model = WhisperModel(model_name, device="cpu", compute_type="int8")
# None → auto-detect; explicit code (e.g. "tr", "de") forces that language
try:
import torch
device = "cuda" if torch.cuda.is_available() else "cpu"
compute = "float16" if device == "cuda" else "int8"
except Exception:
device, compute = "cpu", "int8"
self._model = WhisperModel(model_name, device=device, compute_type=compute)
self._language = None if (not language or language.strip().lower() == "auto") else language.strip().lower()
print("[STT] Whisper ready.")
print(f"[STT] Whisper '{model_name}' ready ({device})")
def transcribe(self, audio: np.ndarray) -> str:
"""
Transcribe a float32 mono 16 kHz numpy array.
Returns transcript string (may be empty).
"""
segments, _ = self._model.transcribe(
audio,
language=self._language,
vad_filter=True,
vad_parameters={"min_silence_duration_ms": 300},
)
return " ".join(s.text for s in segments).strip()
"""Transcribe a float32 mono 16 kHz numpy array. Returns transcript string."""
try:
segments, _ = self._model.transcribe(
audio,
language=self._language,
beam_size=1, # greedy — 2-3x faster
best_of=1,
condition_on_previous_text=False, # no hallucinations, faster
vad_filter=True,
vad_parameters={"min_silence_duration_ms": 300},
)
return " ".join(s.text for s in segments).strip()
except Exception as e:
print(f"[STT] Transcription error: {e}")
raise
class VoskSTT:
@@ -48,10 +57,7 @@ class VoskSTT:
print("[STT] Vosk ready.")
def process_chunk(self, audio_bytes: bytes) -> tuple[str, bool]:
"""
Feed raw int16 LE PCM bytes.
Returns (text, is_final).
"""
"""Feed raw int16 LE PCM bytes. Returns (text, is_final)."""
if self._rec.AcceptWaveform(audio_bytes):
result = json.loads(self._rec.Result())
return result.get("text", ""), True
+168 -30
View File
@@ -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", "")