Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -296,219 +296,228 @@
|
|
| 296 |
# uvicorn.run(final_app, host="0.0.0.0", port=7860)
|
| 297 |
import os
|
| 298 |
import re
|
|
|
|
| 299 |
import time
|
| 300 |
import asyncio
|
| 301 |
import uvloop
|
|
|
|
|
|
|
|
|
|
| 302 |
import numpy as np
|
| 303 |
import gradio as gr
|
| 304 |
-
import torch
|
| 305 |
-
from functools import lru_cache
|
| 306 |
-
from huggingface_hub import hf_hub_download
|
| 307 |
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
| 308 |
import uvicorn
|
| 309 |
-
from concurrent.futures import ThreadPoolExecutor
|
| 310 |
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
|
|
|
| 314 |
|
| 315 |
-
# -----------------------
|
| 316 |
-
# HF
|
| 317 |
-
# -----------------------
|
| 318 |
-
# CPU Basic
|
|
|
|
| 319 |
|
| 320 |
-
|
| 321 |
-
# Kokoro official pipeline
|
| 322 |
-
# -----------------------
|
| 323 |
-
from kokoro import KPipeline
|
| 324 |
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
# -----------------------
|
|
|
|
|
|
|
| 328 |
VOICE_CHOICES = {
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 339 |
}
|
| 340 |
|
| 341 |
-
|
|
|
|
| 342 |
|
| 343 |
-
|
| 344 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 345 |
|
| 346 |
-
#
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 350 |
|
| 351 |
-
|
| 352 |
-
|
|
|
|
|
|
|
|
|
|
| 353 |
|
| 354 |
-
|
| 355 |
-
|
|
|
|
| 356 |
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
# -----------------------
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
|
|
|
|
|
|
|
|
|
| 373 |
if not text:
|
| 374 |
return text
|
| 375 |
|
| 376 |
-
#
|
| 377 |
text = text.replace("Kokoro", "[Kokoro](/kΛOkΙΙΉO/)")
|
| 378 |
|
| 379 |
-
#
|
| 380 |
-
text =
|
| 381 |
-
|
| 382 |
-
# Turn v1.0 into "version 1.0"
|
| 383 |
-
text = _VER.sub(lambda m: "version " + m.group(2), text)
|
| 384 |
|
| 385 |
-
#
|
| 386 |
-
|
| 387 |
-
for _ in range(3):
|
| 388 |
-
text2 = _CAMEL.sub(r"\1 \2", text)
|
| 389 |
-
if text2 == text:
|
| 390 |
-
break
|
| 391 |
-
text = text2
|
| 392 |
|
| 393 |
-
#
|
| 394 |
-
|
|
|
|
|
|
|
|
|
|
| 395 |
|
| 396 |
return text
|
| 397 |
|
| 398 |
-
# -----------------------
|
| 399 |
-
#
|
| 400 |
-
# -
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
return audio
|
| 404 |
-
mask = np.abs(audio) > threshold
|
| 405 |
-
if not np.any(mask):
|
| 406 |
-
return audio
|
| 407 |
-
start = int(np.argmax(mask))
|
| 408 |
-
end = int(len(mask) - np.argmax(mask[::-1]))
|
| 409 |
-
# Keep a little context so words do not get clipped
|
| 410 |
-
pad = 120
|
| 411 |
-
return audio[max(0, start - pad): min(len(audio), end + pad)]
|
| 412 |
-
|
| 413 |
-
SAMPLE_RATE = 24000
|
| 414 |
-
INTER_CHUNK_SIL_MS = 40 # reduces βteleportβ effect between chunks
|
| 415 |
-
|
| 416 |
-
def wav_chunk_from_text(text: str, voice_name: str, speed: float):
|
| 417 |
-
text = normalize_for_tts(text).strip()
|
| 418 |
-
if not text:
|
| 419 |
-
return None
|
| 420 |
-
|
| 421 |
-
voice_tensor = get_voice_tensor(voice_name)
|
| 422 |
|
| 423 |
-
|
| 424 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 425 |
text,
|
| 426 |
voice=voice_tensor,
|
| 427 |
speed=float(speed),
|
| 428 |
-
split_pattern=r"$^"
|
| 429 |
)
|
| 430 |
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
pad = np.zeros(int(SAMPLE_RATE * (INTER_CHUNK_SIL_MS / 1000.0)), dtype=np.float32)
|
| 447 |
-
audio = np.concatenate([audio, pad], axis=0)
|
| 448 |
-
|
| 449 |
-
pcm = (np.clip(audio, -1.0, 1.0) * 32767).astype(np.int16)
|
| 450 |
-
return SAMPLE_RATE, pcm
|
| 451 |
-
|
| 452 |
-
# -----------------------
|
| 453 |
-
# Your tuned splitter, kept
|
| 454 |
-
# -----------------------
|
| 455 |
-
def tuned_splitter(text):
|
| 456 |
-
chunks = re.split(r'([.,!?;:\n]+)', text)
|
| 457 |
-
buffer = ""
|
| 458 |
-
chunk_count = 0
|
| 459 |
-
for part in chunks:
|
| 460 |
-
buffer += part
|
| 461 |
-
if chunk_count == 0:
|
| 462 |
-
threshold = 50
|
| 463 |
-
elif chunk_count == 1:
|
| 464 |
-
threshold = 100
|
| 465 |
-
elif chunk_count == 2:
|
| 466 |
-
threshold = 150
|
| 467 |
-
else:
|
| 468 |
-
threshold = 250
|
| 469 |
-
if re.search(r'[.,!?;:\n]$', buffer) and len(buffer) >= threshold:
|
| 470 |
-
if buffer.strip():
|
| 471 |
-
yield buffer
|
| 472 |
-
chunk_count += 1
|
| 473 |
-
buffer = ""
|
| 474 |
-
if buffer.strip():
|
| 475 |
-
yield buffer.strip()
|
| 476 |
-
|
| 477 |
-
# -----------------------
|
| 478 |
-
# Streaming generator (Gradio UI)
|
| 479 |
-
# -----------------------
|
| 480 |
-
def stream_generator(text, voice_name, speed):
|
| 481 |
-
get_voice_tensor(voice_name)
|
| 482 |
-
for i, chunk in enumerate(tuned_splitter(text)):
|
| 483 |
t0 = time.time()
|
| 484 |
-
|
| 485 |
-
|
| 486 |
dur = time.time() - t0
|
| 487 |
-
print(f"β‘
|
| 488 |
-
yield
|
| 489 |
-
|
| 490 |
-
# -----------------------
|
| 491 |
-
# Gradio UI
|
| 492 |
-
# -----------------------
|
| 493 |
-
with gr.Blocks(title="Kokoro TTS", ssr_mode=False) as app:
|
| 494 |
-
gr.Markdown("## β‘ Kokoro-82M (Official Pipeline, Streamed)")
|
| 495 |
-
with gr.Row():
|
| 496 |
-
with gr.Column():
|
| 497 |
-
text_in = gr.Textbox(
|
| 498 |
-
label="Input Text",
|
| 499 |
-
lines=3,
|
| 500 |
-
value="The system is live. Use the UI or connect to /ws/audio."
|
| 501 |
-
)
|
| 502 |
-
voice_in = gr.Dropdown(list(VOICE_CHOICES.keys()), value='πΊπΈ πΊ Bella', label="Voice")
|
| 503 |
-
speed_in = gr.Slider(0.5, 2.0, value=1.0, label="Speed")
|
| 504 |
-
btn = gr.Button("Generate", variant="primary")
|
| 505 |
-
with gr.Column():
|
| 506 |
-
audio_out = gr.Audio(streaming=True, autoplay=True, label="Audio Stream")
|
| 507 |
-
btn.click(stream_generator, inputs=[text_in, voice_in, speed_in], outputs=[audio_out])
|
| 508 |
|
| 509 |
-
# -----------------------
|
| 510 |
-
#
|
| 511 |
-
# -----------------------
|
| 512 |
api = FastAPI()
|
| 513 |
|
| 514 |
INFERENCE_EXECUTOR = ThreadPoolExecutor(max_workers=1)
|
|
@@ -519,24 +528,25 @@ async def audio_engine_loop():
|
|
| 519 |
loop = asyncio.get_running_loop()
|
| 520 |
|
| 521 |
while True:
|
| 522 |
-
|
|
|
|
| 523 |
try:
|
| 524 |
if ws.client_state.value > 1:
|
| 525 |
continue
|
| 526 |
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
|
| 533 |
-
|
| 534 |
-
continue
|
| 535 |
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
|
|
|
|
| 540 |
|
| 541 |
except Exception as e:
|
| 542 |
print(f"API Engine Error: {e}")
|
|
@@ -549,7 +559,7 @@ async def startup():
|
|
| 549 |
async def websocket_endpoint(ws: WebSocket):
|
| 550 |
await ws.accept()
|
| 551 |
|
| 552 |
-
|
| 553 |
speed = 1.0
|
| 554 |
|
| 555 |
print(f"β
Client connected: {ws.client}")
|
|
@@ -576,23 +586,52 @@ async def websocket_endpoint(ws: WebSocket):
|
|
| 576 |
break
|
| 577 |
|
| 578 |
if "config" in data:
|
| 579 |
-
voice_name = data.get("voice",
|
|
|
|
| 580 |
speed = float(data.get("speed", speed))
|
| 581 |
-
get_voice_tensor(
|
| 582 |
|
| 583 |
if "text" in data:
|
| 584 |
-
|
| 585 |
-
|
|
|
|
|
|
|
| 586 |
if chunk.strip():
|
| 587 |
-
await INFERENCE_QUEUE.put((
|
|
|
|
|
|
|
|
|
|
| 588 |
|
| 589 |
except Exception as e:
|
| 590 |
print(f"π₯ Critical WS Error: {e}")
|
| 591 |
finally:
|
| 592 |
heartbeat_task.cancel()
|
| 593 |
|
| 594 |
-
#
|
| 595 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 596 |
|
| 597 |
if __name__ == "__main__":
|
| 598 |
-
uvicorn.run(final_app, host="0.0.0.0", port=7860)
|
|
|
|
| 296 |
# uvicorn.run(final_app, host="0.0.0.0", port=7860)
|
| 297 |
import os
|
| 298 |
import re
|
| 299 |
+
import json
|
| 300 |
import time
|
| 301 |
import asyncio
|
| 302 |
import uvloop
|
| 303 |
+
from functools import lru_cache
|
| 304 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 305 |
+
|
| 306 |
import numpy as np
|
| 307 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
| 308 |
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
| 309 |
import uvicorn
|
|
|
|
| 310 |
|
| 311 |
+
import torch
|
| 312 |
+
import soundfile as sf
|
| 313 |
+
from huggingface_hub import hf_hub_download
|
| 314 |
+
from kokoro import KPipeline
|
| 315 |
|
| 316 |
+
# -----------------------------
|
| 317 |
+
# HF SPACE REALITY SETTINGS
|
| 318 |
+
# -----------------------------
|
| 319 |
+
# Free CPU Basic is small, so keep concurrency controlled.
|
| 320 |
+
torch.set_num_threads(max(1, int(os.environ.get("TORCH_NUM_THREADS", "2"))))
|
| 321 |
|
| 322 |
+
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
|
|
|
|
|
|
|
|
|
|
| 323 |
|
| 324 |
+
print("π BOOTING KOKORO (OFFICIAL PIPELINE)")
|
| 325 |
+
|
| 326 |
+
# -----------------------------
|
| 327 |
+
# VOICES
|
| 328 |
+
# -----------------------------
|
| 329 |
VOICE_CHOICES = {
|
| 330 |
+
"πΊπΈ πΊ Heart": "af_heart",
|
| 331 |
+
"πΊπΈ πΊ Bella": "af_bella",
|
| 332 |
+
"πΊπΈ πΊ Nicole": "af_nicole",
|
| 333 |
+
"πΊπΈ πΊ Aoede": "af_aoede",
|
| 334 |
+
"πΊπΈ πΊ Kore": "af_kore",
|
| 335 |
+
"πΊπΈ πΊ Sarah": "af_sarah",
|
| 336 |
+
"πΊπΈ πΊ Nova": "af_nova",
|
| 337 |
+
"πΊπΈ πΊ Sky": "af_sky",
|
| 338 |
+
"πΊπΈ πΊ Alloy": "af_alloy",
|
| 339 |
+
"πΊπΈ πΊ Jessica": "af_jessica",
|
| 340 |
+
"πΊπΈ πΊ River": "af_river",
|
| 341 |
+
"πΊπΈ πΉ Michael": "am_michael",
|
| 342 |
+
"πΊπΈ πΉ Fenrir": "am_fenrir",
|
| 343 |
+
"πΊπΈ πΉ Puck": "am_puck",
|
| 344 |
+
"πΊπΈ πΉ Echo": "am_echo",
|
| 345 |
+
"πΊπΈ πΉ Eric": "am_eric",
|
| 346 |
+
"πΊπΈ πΉ Liam": "am_liam",
|
| 347 |
+
"πΊπΈ πΉ Onyx": "am_onyx",
|
| 348 |
+
"πΊπΈ πΉ Santa": "am_santa",
|
| 349 |
+
"πΊπΈ πΉ Adam": "am_adam",
|
| 350 |
+
"π¬π§ πΊ Emma": "bf_emma",
|
| 351 |
+
"π¬π§ πΊ Isabella": "bf_isabella",
|
| 352 |
+
"π¬π§ πΊ Alice": "bf_alice",
|
| 353 |
+
"π¬π§ πΊ Lily": "bf_lily",
|
| 354 |
+
"π¬π§ πΉ George": "bm_george",
|
| 355 |
+
"π¬π§ πΉ Fable": "bm_fable",
|
| 356 |
+
"π¬π§ πΉ Lewis": "bm_lewis",
|
| 357 |
+
"π¬π§ πΉ Daniel": "bm_daniel",
|
| 358 |
}
|
| 359 |
|
| 360 |
+
# Kokoro official repo for weights + voices
|
| 361 |
+
KOKORO_REPO = "hexgrad/Kokoro-82M"
|
| 362 |
|
| 363 |
+
# -----------------------------
|
| 364 |
+
# PIPELINES
|
| 365 |
+
# lang_code must match voice family. :contentReference[oaicite:7]{index=7}
|
| 366 |
+
# -----------------------------
|
| 367 |
+
PIPELINES = {
|
| 368 |
+
"a": KPipeline(lang_code="a"), # American English
|
| 369 |
+
"b": KPipeline(lang_code="b"), # British English
|
| 370 |
+
}
|
| 371 |
|
| 372 |
+
# -----------------------------
|
| 373 |
+
# OPTIONAL: preload spacy model if present
|
| 374 |
+
# prevents runtime download surprises
|
| 375 |
+
# -----------------------------
|
| 376 |
+
try:
|
| 377 |
+
import spacy
|
| 378 |
+
spacy.load("en_core_web_sm")
|
| 379 |
+
except Exception:
|
| 380 |
+
pass
|
| 381 |
+
|
| 382 |
+
# -----------------------------
|
| 383 |
+
# VOICE CACHE (torch tensors)
|
| 384 |
+
# -----------------------------
|
| 385 |
+
VOICE_TENSOR_CACHE = {}
|
| 386 |
|
| 387 |
+
def voice_to_lang_code(voice_code: str) -> str:
|
| 388 |
+
# af_ / am_ => 'a', bf_ / bm_ => 'b'
|
| 389 |
+
if voice_code.startswith("b"):
|
| 390 |
+
return "b"
|
| 391 |
+
return "a"
|
| 392 |
|
| 393 |
+
def get_voice_tensor(voice_code: str):
|
| 394 |
+
if voice_code in VOICE_TENSOR_CACHE:
|
| 395 |
+
return VOICE_TENSOR_CACHE[voice_code]
|
| 396 |
|
| 397 |
+
path = hf_hub_download(
|
| 398 |
+
repo_id=KOKORO_REPO,
|
| 399 |
+
filename=f"voices/{voice_code}.pt",
|
| 400 |
+
)
|
| 401 |
+
# weights_only True is recommended by torch warning text in your logs
|
| 402 |
+
vt = torch.load(path, map_location="cpu", weights_only=True)
|
| 403 |
+
VOICE_TENSOR_CACHE[voice_code] = vt
|
| 404 |
+
return vt
|
| 405 |
+
|
| 406 |
+
# -----------------------------
|
| 407 |
+
# TEXT NORMALIZATION
|
| 408 |
+
# Stops βskippingβ for many brand names by avoiding OOD token collapse.
|
| 409 |
+
# Also makes acronyms pronounceable.
|
| 410 |
+
# -----------------------------
|
| 411 |
+
_ACRONYM_RE = re.compile(r"\b([A-Z]{2,})\b")
|
| 412 |
+
_CAMEL_RE = re.compile(r"([a-z])([A-Z])")
|
| 413 |
+
_DIGIT_WORD_RE = re.compile(r"\b(\d+)([A-Za-z]+)\b")
|
| 414 |
+
|
| 415 |
+
def normalize_text_for_kokoro(text: str) -> str:
|
| 416 |
if not text:
|
| 417 |
return text
|
| 418 |
|
| 419 |
+
# Keep your special Kokoro pronunciation trick
|
| 420 |
text = text.replace("Kokoro", "[Kokoro](/kΛOkΙΙΉO/)")
|
| 421 |
|
| 422 |
+
# Split CamelCase: OpenAI -> Open AI
|
| 423 |
+
text = _CAMEL_RE.sub(r"\1 \2", text)
|
|
|
|
|
|
|
|
|
|
| 424 |
|
| 425 |
+
# Handle 2FA -> "2 F A" (first split digits+letters)
|
| 426 |
+
text = _DIGIT_WORD_RE.sub(r"\1 \2", text)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 427 |
|
| 428 |
+
# Acronyms: API -> "A P I"
|
| 429 |
+
def _spell(m):
|
| 430 |
+
s = m.group(1)
|
| 431 |
+
return " ".join(list(s))
|
| 432 |
+
text = _ACRONYM_RE.sub(_spell, text)
|
| 433 |
|
| 434 |
return text
|
| 435 |
|
| 436 |
+
# -----------------------------
|
| 437 |
+
# CHUNKING
|
| 438 |
+
# Fewer micro-chunks reduces stalls under load.
|
| 439 |
+
# -----------------------------
|
| 440 |
+
_SENT_SPLIT = re.compile(r"(?<=[.!?])\s+|\n+")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 441 |
|
| 442 |
+
def chunk_text(text: str, min_chars: int = 240, max_chars: int = 520):
|
| 443 |
+
text = text.strip()
|
| 444 |
+
if not text:
|
| 445 |
+
return
|
| 446 |
+
|
| 447 |
+
parts = _SENT_SPLIT.split(text)
|
| 448 |
+
buf = ""
|
| 449 |
+
for p in parts:
|
| 450 |
+
if not p:
|
| 451 |
+
continue
|
| 452 |
+
if len(buf) + len(p) + 1 <= max_chars:
|
| 453 |
+
buf = (buf + " " + p).strip()
|
| 454 |
+
if len(buf) < min_chars:
|
| 455 |
+
continue
|
| 456 |
+
yield buf
|
| 457 |
+
buf = ""
|
| 458 |
+
else:
|
| 459 |
+
if buf:
|
| 460 |
+
yield buf
|
| 461 |
+
buf = p.strip()
|
| 462 |
+
if len(buf) >= min_chars:
|
| 463 |
+
yield buf
|
| 464 |
+
buf = ""
|
| 465 |
+
|
| 466 |
+
if buf:
|
| 467 |
+
yield buf
|
| 468 |
+
|
| 469 |
+
# -----------------------------
|
| 470 |
+
# AUDIO UTILS
|
| 471 |
+
# Avoid trimming per-chunk to prevent audible βmissingβ regions.
|
| 472 |
+
# Do optional gentle trim only on final concatenated output if needed.
|
| 473 |
+
# -----------------------------
|
| 474 |
+
def float_to_int16(audio_f32: np.ndarray) -> np.ndarray:
|
| 475 |
+
audio_f32 = np.clip(audio_f32, -1.0, 1.0)
|
| 476 |
+
return (audio_f32 * 32767.0).astype(np.int16)
|
| 477 |
+
|
| 478 |
+
# -----------------------------
|
| 479 |
+
# CORE SYNTH
|
| 480 |
+
# Uses official generator API. :contentReference[oaicite:8]{index=8}
|
| 481 |
+
# -----------------------------
|
| 482 |
+
def kokoro_generate_stream(text: str, voice_code: str, speed: float):
|
| 483 |
+
lang_code = voice_to_lang_code(voice_code)
|
| 484 |
+
pipeline = PIPELINES[lang_code]
|
| 485 |
+
voice_tensor = get_voice_tensor(voice_code)
|
| 486 |
+
|
| 487 |
+
# We already chunk ourselves, so keep split_pattern simple.
|
| 488 |
+
# If you pass a strong splitter here, you will double-split and create micro audio pieces.
|
| 489 |
+
generator = pipeline(
|
| 490 |
text,
|
| 491 |
voice=voice_tensor,
|
| 492 |
speed=float(speed),
|
| 493 |
+
split_pattern=r"$^", # split nothing
|
| 494 |
)
|
| 495 |
|
| 496 |
+
for _, _, audio in generator:
|
| 497 |
+
# audio is float array at 24kHz
|
| 498 |
+
yield audio
|
| 499 |
+
|
| 500 |
+
# -----------------------------
|
| 501 |
+
# GRADIO STREAM
|
| 502 |
+
# -----------------------------
|
| 503 |
+
def gradio_stream_generator(text, voice_name, speed):
|
| 504 |
+
voice_code = VOICE_CHOICES.get(voice_name, voice_name)
|
| 505 |
+
text = normalize_text_for_kokoro(text)
|
| 506 |
+
|
| 507 |
+
# warm voice cache
|
| 508 |
+
get_voice_tensor(voice_code)
|
| 509 |
+
|
| 510 |
+
for i, chunk in enumerate(chunk_text(text)):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 511 |
t0 = time.time()
|
| 512 |
+
# generator yields 1 item because split_pattern disables splitting
|
| 513 |
+
for audio_f32 in kokoro_generate_stream(chunk, voice_code, speed):
|
| 514 |
dur = time.time() - t0
|
| 515 |
+
print(f"β‘ UI chunk {i}: {len(chunk)} chars in {dur:.2f}s")
|
| 516 |
+
yield 24000, float_to_int16(audio_f32)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 517 |
|
| 518 |
+
# -----------------------------
|
| 519 |
+
# FASTAPI WS
|
| 520 |
+
# -----------------------------
|
| 521 |
api = FastAPI()
|
| 522 |
|
| 523 |
INFERENCE_EXECUTOR = ThreadPoolExecutor(max_workers=1)
|
|
|
|
| 528 |
loop = asyncio.get_running_loop()
|
| 529 |
|
| 530 |
while True:
|
| 531 |
+
ws, voice_code, speed, chunk = await INFERENCE_QUEUE.get()
|
| 532 |
+
|
| 533 |
try:
|
| 534 |
if ws.client_state.value > 1:
|
| 535 |
continue
|
| 536 |
|
| 537 |
+
def _run():
|
| 538 |
+
out = []
|
| 539 |
+
for audio_f32 in kokoro_generate_stream(chunk, voice_code, speed):
|
| 540 |
+
out.append(float_to_int16(audio_f32).tobytes())
|
| 541 |
+
return out
|
| 542 |
|
| 543 |
+
frames = await loop.run_in_executor(INFERENCE_EXECUTOR, _run)
|
|
|
|
| 544 |
|
| 545 |
+
for frame in frames:
|
| 546 |
+
try:
|
| 547 |
+
await ws.send_bytes(frame)
|
| 548 |
+
except Exception:
|
| 549 |
+
break
|
| 550 |
|
| 551 |
except Exception as e:
|
| 552 |
print(f"API Engine Error: {e}")
|
|
|
|
| 559 |
async def websocket_endpoint(ws: WebSocket):
|
| 560 |
await ws.accept()
|
| 561 |
|
| 562 |
+
voice_code = "af_bella"
|
| 563 |
speed = 1.0
|
| 564 |
|
| 565 |
print(f"β
Client connected: {ws.client}")
|
|
|
|
| 586 |
break
|
| 587 |
|
| 588 |
if "config" in data:
|
| 589 |
+
voice_name = data.get("voice", "πΊπΈ πΊ Bella")
|
| 590 |
+
voice_code = VOICE_CHOICES.get(voice_name, voice_name)
|
| 591 |
speed = float(data.get("speed", speed))
|
| 592 |
+
get_voice_tensor(voice_code)
|
| 593 |
|
| 594 |
if "text" in data:
|
| 595 |
+
raw = data["text"]
|
| 596 |
+
text = normalize_text_for_kokoro(raw)
|
| 597 |
+
# Bigger chunks reduces stalls under load
|
| 598 |
+
for chunk in chunk_text(text):
|
| 599 |
if chunk.strip():
|
| 600 |
+
await INFERENCE_QUEUE.put((ws, voice_code, speed, chunk))
|
| 601 |
+
|
| 602 |
+
if "flush" in data:
|
| 603 |
+
pass
|
| 604 |
|
| 605 |
except Exception as e:
|
| 606 |
print(f"π₯ Critical WS Error: {e}")
|
| 607 |
finally:
|
| 608 |
heartbeat_task.cancel()
|
| 609 |
|
| 610 |
+
# -----------------------------
|
| 611 |
+
# GRADIO UI
|
| 612 |
+
# -----------------------------
|
| 613 |
+
with gr.Blocks(title="Kokoro TTS") as app:
|
| 614 |
+
gr.Markdown("## β‘ Kokoro-82M (Official Pipeline, HF CPU-friendly)")
|
| 615 |
+
with gr.Row():
|
| 616 |
+
with gr.Column():
|
| 617 |
+
text_in = gr.Textbox(
|
| 618 |
+
label="Input Text",
|
| 619 |
+
lines=3,
|
| 620 |
+
value="The system is live. Use the UI or connect to /ws/audio.",
|
| 621 |
+
)
|
| 622 |
+
voice_in = gr.Dropdown(
|
| 623 |
+
list(VOICE_CHOICES.keys()),
|
| 624 |
+
value="πΊπΈ πΊ Bella",
|
| 625 |
+
label="Voice",
|
| 626 |
+
)
|
| 627 |
+
speed_in = gr.Slider(0.5, 2.0, value=1.0, label="Speed")
|
| 628 |
+
btn = gr.Button("Generate", variant="primary")
|
| 629 |
+
with gr.Column():
|
| 630 |
+
audio_out = gr.Audio(streaming=True, autoplay=True, label="Audio Stream")
|
| 631 |
+
|
| 632 |
+
btn.click(gradio_stream_generator, inputs=[text_in, voice_in, speed_in], outputs=[audio_out])
|
| 633 |
+
|
| 634 |
+
final_app = gr.mount_gradio_app(api, app, path="/")
|
| 635 |
|
| 636 |
if __name__ == "__main__":
|
| 637 |
+
uvicorn.run(final_app, host="0.0.0.0", port=7860)
|