mxp1404 commited on
Commit
a541e77
·
verified ·
1 Parent(s): 10c7e2a

Upload chatbot/tts.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. chatbot/tts.py +36 -0
chatbot/tts.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Text-to-speech via Kokoro ONNX (82M parameter model, runs on CPU)."""
2
+
3
+ import io
4
+ import numpy as np
5
+
6
+ _kokoro_instance = None
7
+
8
+
9
+ def _get_kokoro():
10
+ global _kokoro_instance
11
+ if _kokoro_instance is not None:
12
+ return _kokoro_instance
13
+
14
+ from huggingface_hub import hf_hub_download
15
+ from kokoro_onnx import Kokoro
16
+
17
+ model_path = hf_hub_download(
18
+ repo_id="fastrtc/kokoro-onnx", filename="kokoro-v1.0.onnx"
19
+ )
20
+ voices_path = hf_hub_download(
21
+ repo_id="fastrtc/kokoro-onnx", filename="voices-v1.0.bin"
22
+ )
23
+ _kokoro_instance = Kokoro(model_path, voices_path)
24
+ return _kokoro_instance
25
+
26
+
27
+ def synthesize(text: str, voice: str = "af_sarah", speed: float = 1.0) -> bytes:
28
+ """Convert text to WAV audio bytes."""
29
+ kokoro = _get_kokoro()
30
+ samples, sample_rate = kokoro.create(text, voice=voice, speed=speed, lang="en-us")
31
+
32
+ buf = io.BytesIO()
33
+ import soundfile as sf
34
+ sf.write(buf, samples, sample_rate, format="WAV")
35
+ buf.seek(0)
36
+ return buf.read()