diegosouzacdv commited on
Commit
845ded6
·
verified ·
1 Parent(s): 1537ead

Add optional LFM3-Audio-2B engine (off unless LFM3_ENABLED=1)

Browse files
Files changed (5) hide show
  1. README.md +36 -11
  2. app.py +277 -278
  3. lfm3_engine.py +204 -0
  4. pieces.py +51 -0
  5. requirements.txt +14 -10
README.md CHANGED
@@ -1,11 +1,36 @@
1
- ---
2
- title: Kokoro TTS
3
- emoji: 🗣️
4
- colorFrom: indigo
5
- colorTo: purple
6
- sdk: gradio
7
- sdk_version: 6.6.0
8
- app_file: app.py
9
- pinned: false
10
- python_version: "3.10"
11
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Kokoro TTS
3
+ emoji: 🗣️
4
+ colorFrom: indigo
5
+ colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: 6.6.0
8
+ app_file: app.py
9
+ pinned: false
10
+ python_version: "3.11"
11
+ ---
12
+
13
+ # Kokoro TTS (and optional LFM3 for comparison)
14
+
15
+ Kokoro-82M answers on `/` (Gradio) and `POST /tts/stream` (raw PCM16 mono, streamed).
16
+
17
+ ## Optional second engine: LFM3-Audio-2B
18
+
19
+ Off by default. To compare it with Kokoro in the same Space, set the Space variable
20
+ `LFM3_ENABLED=1`. It adds routes with the same contract under `/lfm3/tts`:
21
+
22
+ - `POST /lfm3/tts/stream`: `{"text", "voice": "female" | "male" | "af_heart"-style, "sample_rate": 16000 | 24000}`;
23
+ `speed` is ignored (LFM3 has no speed control).
24
+ - `POST /lfm3/tts/bench`: seconds spent synthesizing vs seconds of audio, per piece.
25
+ The first call loads the model, so read the second.
26
+ - `GET /lfm3/tts/health`.
27
+
28
+ The ~8 GB model (float32 on CPU) loads on the first LFM3 request, not at start-up, so Kokoro
29
+ is unaffected until then. LFM3 and Kokoro share the 2 vCPUs: benchmark them one at a time.
30
+ `TTS_API_KEY`, when set, protects both engines' POST routes.
31
+
32
+ To make the tutor use LFM3, point `KOKORO_HF_SPACE_URL` at `https://<space>.hf.space/lfm3`
33
+ (the client appends `/tts/stream`). Compare both with
34
+ `python -m scripts.compare_tts_spaces --space kokoro=https://<space>.hf.space --space lfm3=https://<space>.hf.space/lfm3`.
35
+
36
+ License of the model: LFM Open License v1.0 (commercial use only below US$10M annual revenue).
app.py CHANGED
@@ -1,278 +1,277 @@
1
- """Kokoro-82M TTS Space: Gradio UI + a streaming HTTP endpoint.
2
-
3
- - Gradio UI and its API (/generate_tts) are unchanged, so existing clients
4
- (gradio_client.predict) keep working.
5
- - POST /tts/stream returns raw PCM16 mono audio WHILE it is being generated:
6
- the text is cut into pieces (the first sentence at its first clause, so the
7
- first audio is short), each piece is synthesized and sent as soon as it is
8
- ready. No Gradio queue, no WAV file to download, resampled to 16 kHz here.
9
-
10
- Engine (KOKORO_ENGINE): "onnx" (default) runs the same Kokoro-82M v1.0
11
- weights through ONNX Runtime (kokoro-onnx), with phonemes from Kokoro's own
12
- G2P (misaki) so pronunciation is unchanged; "torch" is the original
13
- PyTorch KPipeline. If ONNX can't start, it falls back to torch.
14
-
15
- The Space runs on 2 shared vCPUs: one synthesis at a time (a lock per piece,
16
- so concurrent requests interleave piece by piece instead of waiting for a
17
- whole reply).
18
- """
19
- import os
20
- import re
21
- import threading
22
- import time
23
- import urllib.request
24
-
25
- import gradio as gr
26
- import numpy as np
27
- import torch
28
- import uvicorn
29
- from fastapi import FastAPI, HTTPException, Request
30
- from fastapi.responses import JSONResponse, StreamingResponse
31
- from kokoro import KPipeline
32
- from scipy.signal import resample_poly
33
-
34
- def _cpu_quota() -> int:
35
- """CPUs this container may really use. os.cpu_count() reports the host
36
- (16 on HF cpu-basic, which gives 2 vCPUs): that many threads would fight
37
- over 2 cores. Reads the cgroup quota; KOKORO_THREADS overrides."""
38
- env = os.getenv("KOKORO_THREADS", "").strip()
39
- if env.isdigit() and int(env) > 0:
40
- return int(env)
41
- try:
42
- quota, period = open("/sys/fs/cgroup/cpu.max").read().split()[:2]
43
- if quota != "max":
44
- return max(1, int(int(quota) / int(period)))
45
- except (OSError, ValueError):
46
- pass
47
- try:
48
- q = int(open("/sys/fs/cgroup/cpu/cpu.cfs_quota_us").read())
49
- p = int(open("/sys/fs/cgroup/cpu/cpu.cfs_period_us").read())
50
- if q > 0:
51
- return max(1, q // p)
52
- except (OSError, ValueError):
53
- pass
54
- try:
55
- return max(1, len(os.sched_getaffinity(0)))
56
- except AttributeError:
57
- return max(1, os.cpu_count() or 1)
58
-
59
-
60
- THREADS = _cpu_quota()
61
- torch.set_num_threads(THREADS)
62
-
63
- # Optional shared secret (Space secret TTS_API_KEY): when set, /tts/stream
64
- # requires the X-API-Key header. The Gradio UI stays public as before.
65
- API_KEY = os.getenv("TTS_API_KEY", "").strip()
66
- MAX_CHARS = 600
67
- FIRST_PIECE_MAX = 60 # first sentence longer than this is cut at its first clause
68
- SAMPLE_RATE = 24000 # Kokoro output
69
-
70
- _LANGS = {"a": ("af_", "am_"), "b": ("bf_", "bm_"), "p": ("pf_", "pm_")}
71
- _pipelines: dict = {}
72
- _pipelines_lock = threading.Lock()
73
- _synth_lock = threading.Lock()
74
-
75
- # ---------------------------------------------------------------- engine
76
-
77
- ONNX_RELEASE = "https://github.com/thewh1teagle/kokoro-onnx/releases/download/model-files-v1.0"
78
- ONNX_FILES = ("kokoro-v1.0.onnx", "voices-v1.0.bin")
79
- MODEL_DIR = os.getenv("KOKORO_MODEL_DIR", os.path.join(os.path.dirname(os.path.abspath(__file__)), "models"))
80
- ENGINE = os.getenv("KOKORO_ENGINE", "onnx").strip().lower()
81
- _onnx = None # kokoro_onnx.Kokoro when the ONNX engine is active
82
-
83
-
84
- def _start_onnx():
85
- import onnxruntime as ort
86
- from kokoro_onnx import Kokoro
87
-
88
- os.makedirs(MODEL_DIR, exist_ok=True)
89
- for name in ONNX_FILES:
90
- path = os.path.join(MODEL_DIR, name)
91
- if not os.path.exists(path) or os.path.getsize(path) == 0:
92
- t0 = time.perf_counter()
93
- urllib.request.urlretrieve(f"{ONNX_RELEASE}/{name}", path + ".part")
94
- os.replace(path + ".part", path)
95
- print(f"[TTS] downloaded {name} in {time.perf_counter() - t0:.1f}s")
96
- opts = ort.SessionOptions()
97
- opts.intra_op_num_threads = THREADS
98
- opts.inter_op_num_threads = 1
99
- opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
100
- session = ort.InferenceSession(
101
- os.path.join(MODEL_DIR, ONNX_FILES[0]), sess_options=opts, providers=["CPUExecutionProvider"]
102
- )
103
- return Kokoro.from_session(session, os.path.join(MODEL_DIR, ONNX_FILES[1]))
104
-
105
-
106
- if ENGINE == "onnx":
107
- try:
108
- _onnx = _start_onnx()
109
- print(f"[TTS] engine: onnx ({THREADS} threads)")
110
- except Exception as e:
111
- print(f"[TTS] onnx failed ({e}); falling back to torch")
112
- ENGINE = "torch"
113
- if ENGINE != "onnx":
114
- print(f"[TTS] engine: torch ({THREADS} threads)")
115
-
116
-
117
- def get_pipeline_for_voice(voice_id: str) -> KPipeline:
118
- """American English is loaded at start-up; British / Portuguese on first
119
- use. With ONNX the pipeline is G2P only (model=False)."""
120
- lang = next((code for code, prefixes in _LANGS.items() if voice_id.startswith(prefixes)), "a")
121
- with _pipelines_lock:
122
- if lang not in _pipelines:
123
- _pipelines[lang] = KPipeline(lang_code=lang, repo_id="hexgrad/Kokoro-82M", model=_onnx is None)
124
- return _pipelines[lang]
125
-
126
-
127
- get_pipeline_for_voice("af_heart")
128
-
129
-
130
- def _synth(text: str, voice_id: str, speed: float) -> np.ndarray:
131
- """Float32 mono audio at 24 kHz for one piece of text."""
132
- pipeline = get_pipeline_for_voice(voice_id)
133
- segments = []
134
- with _synth_lock:
135
- if _onnx is not None:
136
- for result in pipeline(text, voice=voice_id, split_pattern=None):
137
- if result.phonemes:
138
- audio, _sr = _onnx.create(result.phonemes, voice=voice_id, speed=speed, is_phonemes=True)
139
- segments.append(np.asarray(audio, dtype=np.float32))
140
- else:
141
- for _gs, _ps, audio in pipeline(text, voice=voice_id, speed=speed, split_pattern=None):
142
- seg = np.asarray(audio, dtype=np.float32)
143
- if seg.ndim > 1:
144
- seg = seg.mean(axis=-1)
145
- if seg.size:
146
- segments.append(seg)
147
- return np.concatenate(segments) if segments else np.zeros(0, dtype=np.float32)
148
-
149
-
150
- _SENTENCE = re.compile(r"(?<=[.!?…])\s+")
151
- _CLAUSE = re.compile(r"(?<=[,;:])\s+")
152
-
153
-
154
- def split_for_streaming(text: str) -> list:
155
- """Sentences, with the first one cut at its first clause when long, so
156
- the first audio arrives after synthesizing only a few words."""
157
- sentences = [s.strip() for s in _SENTENCE.split(text) if s.strip()]
158
- if not sentences:
159
- return []
160
- first = sentences[0]
161
- if len(first) > FIRST_PIECE_MAX:
162
- parts = _CLAUSE.split(first, maxsplit=1)
163
- if len(parts) == 2 and len(parts[0]) >= 12 and len(parts[1]) >= 12:
164
- return [parts[0], parts[1]] + sentences[1:]
165
- return sentences
166
-
167
-
168
- def _to_pcm16(audio: np.ndarray, rate: int) -> bytes:
169
- if rate == 16000:
170
- audio = resample_poly(audio, 2, 3) # 24 kHz -> 16 kHz
171
- return (np.clip(audio, -1.0, 1.0) * 32767).astype(np.int16).tobytes()
172
-
173
-
174
- # ---------------------------------------------------------------- Gradio UI
175
-
176
-
177
- def generate_tts(text: str, voice_id: str, speed: float):
178
- try:
179
- text = (text or "").strip()[:MAX_CHARS]
180
- if not text:
181
- return None
182
- audio = np.concatenate([_synth(p, voice_id, speed) for p in split_for_streaming(text)])
183
- return (SAMPLE_RATE, audio) if audio.size else None
184
- except Exception as e:
185
- print(f"[TTS] Erro: {e}")
186
- return None
187
-
188
-
189
- VOICES = [
190
- "af_heart", "af_alloy", "af_aoede", "af_bella", "af_jessica",
191
- "af_kore", "af_nicole", "af_nova", "af_river", "af_sarah", "af_sky",
192
- "am_adam", "am_echo", "am_eric", "am_fenrir", "am_liam",
193
- "am_michael", "am_onyx", "am_orion", "am_puck",
194
- "bf_alice", "bf_emma", "bf_isabella",
195
- "bm_george", "bm_lewis",
196
- "pf_dora", "pm_alex", "pm_santa",
197
- ]
198
-
199
- demo = gr.Interface(
200
- fn=generate_tts,
201
- inputs=[
202
- gr.Textbox(label="Texto", lines=3, placeholder="Digite o texto aqui..."),
203
- gr.Dropdown(choices=VOICES, value="af_heart", label="Voz"),
204
- gr.Slider(minimum=0.5, maximum=2.0, value=1.0, step=0.1, label="Velocidade"),
205
- ],
206
- outputs=gr.Audio(label="Audio Gerado"),
207
- title="Kokoro-82M TTS",
208
- description="Ingles Americano / Britanico e Portugues Brasileiro.",
209
- )
210
-
211
- # ---------------------------------------------------------------- HTTP API
212
-
213
- app = FastAPI()
214
-
215
-
216
- @app.get("/tts/health")
217
- def tts_health():
218
- return {"ok": True, "engine": ENGINE, "threads": THREADS, "voices": len(VOICES), "loaded": sorted(_pipelines)}
219
-
220
-
221
- @app.post("/tts/stream")
222
- async def tts_stream(request: Request):
223
- """Body: {"text", "voice"="af_heart", "speed"=1.0, "sample_rate"=16000}.
224
- Response: raw PCM16 mono little-endian, streamed piece by piece."""
225
- if API_KEY and request.headers.get("x-api-key") != API_KEY:
226
- raise HTTPException(status_code=401, detail="invalid api key")
227
- try:
228
- body = await request.json()
229
- except Exception:
230
- raise HTTPException(status_code=400, detail="json body required")
231
- text = str(body.get("text") or "").strip()[:MAX_CHARS]
232
- voice = str(body.get("voice") or "af_heart")
233
- if voice not in VOICES:
234
- raise HTTPException(status_code=400, detail="unknown voice")
235
- try:
236
- speed = min(2.0, max(0.5, float(body.get("speed") or 1.0)))
237
- rate = int(body.get("sample_rate") or 16000)
238
- except (TypeError, ValueError):
239
- raise HTTPException(status_code=400, detail="invalid speed or sample_rate")
240
- if rate not in (16000, 24000):
241
- raise HTTPException(status_code=400, detail="sample_rate must be 16000 or 24000")
242
- if not text:
243
- return JSONResponse({"detail": "empty text"}, status_code=400)
244
-
245
- pieces = split_for_streaming(text)
246
-
247
- def generate():
248
- t0 = time.perf_counter()
249
- for i, piece in enumerate(pieces):
250
- pcm = _to_pcm16(_synth(piece, voice, speed), rate)
251
- if i == 0:
252
- print(f"[TTS stream] first piece in {time.perf_counter() - t0:.2f}s ({len(piece)} chars)")
253
- yield pcm
254
-
255
- return StreamingResponse(
256
- generate(), # sync generator: Starlette runs it in a worker thread
257
- media_type="application/octet-stream",
258
- headers={"X-Sample-Rate": str(rate), "X-Pieces": str(len(pieces)), "Cache-Control": "no-store"},
259
- )
260
-
261
-
262
- app = gr.mount_gradio_app(app, demo, path="/")
263
-
264
-
265
- def _warmup():
266
- try:
267
- _synth("Hello there.", "af_heart", 1.0)
268
- print("[TTS] warm-up done")
269
- except Exception as e:
270
- print(f"[TTS] warm-up failed: {e}")
271
-
272
-
273
- threading.Thread(target=_warmup, daemon=True).start()
274
-
275
- if __name__ == "__main__":
276
- # HF Spaces (Gradio SDK) expose GRADIO_SERVER_PORT (7860); 7861 is taken
277
- # by the platform there, so PORT is not used.
278
- uvicorn.run(app, host="0.0.0.0", port=int(os.getenv("GRADIO_SERVER_PORT", "7860")))
 
1
+ """Kokoro-82M TTS Space: Gradio UI + a streaming HTTP endpoint.
2
+
3
+ - Gradio UI and its API (/generate_tts) are unchanged, so existing clients
4
+ (gradio_client.predict) keep working.
5
+ - POST /tts/stream returns raw PCM16 mono audio WHILE it is being generated:
6
+ the text is cut into pieces (the first sentence at its first clause, so the
7
+ first audio is short), each piece is synthesized and sent as soon as it is
8
+ ready. No Gradio queue, no WAV file to download, resampled to 16 kHz here.
9
+
10
+ Engine (KOKORO_ENGINE): "onnx" (default) runs the same Kokoro-82M v1.0
11
+ weights through ONNX Runtime (kokoro-onnx), with phonemes from Kokoro's own
12
+ G2P (misaki) so pronunciation is unchanged; "torch" is the original
13
+ PyTorch KPipeline. If ONNX can't start, it falls back to torch.
14
+
15
+ The Space runs on 2 shared vCPUs: one synthesis at a time (a lock per piece,
16
+ so concurrent requests interleave piece by piece instead of waiting for a
17
+ whole reply).
18
+ """
19
+ import os
20
+ import threading
21
+ import time
22
+ import urllib.request
23
+
24
+ import gradio as gr
25
+ import numpy as np
26
+ import torch
27
+ import uvicorn
28
+ from fastapi import FastAPI, HTTPException, Request
29
+ from fastapi.responses import JSONResponse, StreamingResponse
30
+ from kokoro import KPipeline
31
+ from scipy.signal import resample_poly
32
+
33
+ import lfm3_engine
34
+ from pieces import split_for_streaming
35
+
36
+ def _cpu_quota() -> int:
37
+ """CPUs this container may really use. os.cpu_count() reports the host
38
+ (16 on HF cpu-basic, which gives 2 vCPUs): that many threads would fight
39
+ over 2 cores. Reads the cgroup quota; KOKORO_THREADS overrides."""
40
+ env = os.getenv("KOKORO_THREADS", "").strip()
41
+ if env.isdigit() and int(env) > 0:
42
+ return int(env)
43
+ try:
44
+ quota, period = open("/sys/fs/cgroup/cpu.max").read().split()[:2]
45
+ if quota != "max":
46
+ return max(1, int(int(quota) / int(period)))
47
+ except (OSError, ValueError):
48
+ pass
49
+ try:
50
+ q = int(open("/sys/fs/cgroup/cpu/cpu.cfs_quota_us").read())
51
+ p = int(open("/sys/fs/cgroup/cpu/cpu.cfs_period_us").read())
52
+ if q > 0:
53
+ return max(1, q // p)
54
+ except (OSError, ValueError):
55
+ pass
56
+ try:
57
+ return max(1, len(os.sched_getaffinity(0)))
58
+ except AttributeError:
59
+ return max(1, os.cpu_count() or 1)
60
+
61
+
62
+ THREADS = _cpu_quota()
63
+ torch.set_num_threads(THREADS)
64
+
65
+ # Optional shared secret (Space secret TTS_API_KEY): when set, /tts/stream
66
+ # requires the X-API-Key header. The Gradio UI stays public as before.
67
+ API_KEY = os.getenv("TTS_API_KEY", "").strip()
68
+ MAX_CHARS = 600
69
+ SAMPLE_RATE = 24000 # Kokoro output
70
+
71
+ _LANGS = {"a": ("af_", "am_"), "b": ("bf_", "bm_"), "p": ("pf_", "pm_")}
72
+ _pipelines: dict = {}
73
+ _pipelines_lock = threading.Lock()
74
+ _synth_lock = threading.Lock()
75
+
76
+ # ---------------------------------------------------------------- engine
77
+
78
+ ONNX_RELEASE = "https://github.com/thewh1teagle/kokoro-onnx/releases/download/model-files-v1.0"
79
+ ONNX_FILES = ("kokoro-v1.0.onnx", "voices-v1.0.bin")
80
+ MODEL_DIR = os.getenv("KOKORO_MODEL_DIR", os.path.join(os.path.dirname(os.path.abspath(__file__)), "models"))
81
+ ENGINE = os.getenv("KOKORO_ENGINE", "onnx").strip().lower()
82
+ _onnx = None # kokoro_onnx.Kokoro when the ONNX engine is active
83
+
84
+
85
+ def _start_onnx():
86
+ import onnxruntime as ort
87
+ from kokoro_onnx import Kokoro
88
+
89
+ os.makedirs(MODEL_DIR, exist_ok=True)
90
+ for name in ONNX_FILES:
91
+ path = os.path.join(MODEL_DIR, name)
92
+ if not os.path.exists(path) or os.path.getsize(path) == 0:
93
+ t0 = time.perf_counter()
94
+ urllib.request.urlretrieve(f"{ONNX_RELEASE}/{name}", path + ".part")
95
+ os.replace(path + ".part", path)
96
+ print(f"[TTS] downloaded {name} in {time.perf_counter() - t0:.1f}s")
97
+ opts = ort.SessionOptions()
98
+ opts.intra_op_num_threads = THREADS
99
+ opts.inter_op_num_threads = 1
100
+ opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
101
+ session = ort.InferenceSession(
102
+ os.path.join(MODEL_DIR, ONNX_FILES[0]), sess_options=opts, providers=["CPUExecutionProvider"]
103
+ )
104
+ return Kokoro.from_session(session, os.path.join(MODEL_DIR, ONNX_FILES[1]))
105
+
106
+
107
+ if ENGINE == "onnx":
108
+ try:
109
+ _onnx = _start_onnx()
110
+ print(f"[TTS] engine: onnx ({THREADS} threads)")
111
+ except Exception as e:
112
+ print(f"[TTS] onnx failed ({e}); falling back to torch")
113
+ ENGINE = "torch"
114
+ if ENGINE != "onnx":
115
+ print(f"[TTS] engine: torch ({THREADS} threads)")
116
+
117
+
118
+ def get_pipeline_for_voice(voice_id: str) -> KPipeline:
119
+ """American English is loaded at start-up; British / Portuguese on first
120
+ use. With ONNX the pipeline is G2P only (model=False)."""
121
+ lang = next((code for code, prefixes in _LANGS.items() if voice_id.startswith(prefixes)), "a")
122
+ with _pipelines_lock:
123
+ if lang not in _pipelines:
124
+ _pipelines[lang] = KPipeline(lang_code=lang, repo_id="hexgrad/Kokoro-82M", model=_onnx is None)
125
+ return _pipelines[lang]
126
+
127
+
128
+ get_pipeline_for_voice("af_heart")
129
+
130
+
131
+ def _synth(text: str, voice_id: str, speed: float) -> np.ndarray:
132
+ """Float32 mono audio at 24 kHz for one piece of text."""
133
+ pipeline = get_pipeline_for_voice(voice_id)
134
+ segments = []
135
+ with _synth_lock:
136
+ if _onnx is not None:
137
+ for result in pipeline(text, voice=voice_id, split_pattern=None):
138
+ if result.phonemes:
139
+ audio, _sr = _onnx.create(result.phonemes, voice=voice_id, speed=speed, is_phonemes=True)
140
+ segments.append(np.asarray(audio, dtype=np.float32))
141
+ else:
142
+ for _gs, _ps, audio in pipeline(text, voice=voice_id, speed=speed, split_pattern=None):
143
+ seg = np.asarray(audio, dtype=np.float32)
144
+ if seg.ndim > 1:
145
+ seg = seg.mean(axis=-1)
146
+ if seg.size:
147
+ segments.append(seg)
148
+ return np.concatenate(segments) if segments else np.zeros(0, dtype=np.float32)
149
+
150
+
151
+ def _to_pcm16(audio: np.ndarray, rate: int) -> bytes:
152
+ if rate == 16000:
153
+ audio = resample_poly(audio, 2, 3) # 24 kHz -> 16 kHz
154
+ return (np.clip(audio, -1.0, 1.0) * 32767).astype(np.int16).tobytes()
155
+
156
+
157
+ # ---------------------------------------------------------------- Gradio UI
158
+
159
+
160
+ def generate_tts(text: str, voice_id: str, speed: float):
161
+ try:
162
+ text = (text or "").strip()[:MAX_CHARS]
163
+ if not text:
164
+ return None
165
+ audio = np.concatenate([_synth(p, voice_id, speed) for p in split_for_streaming(text)])
166
+ return (SAMPLE_RATE, audio) if audio.size else None
167
+ except Exception as e:
168
+ print(f"[TTS] Erro: {e}")
169
+ return None
170
+
171
+
172
+ VOICES = [
173
+ "af_heart", "af_alloy", "af_aoede", "af_bella", "af_jessica",
174
+ "af_kore", "af_nicole", "af_nova", "af_river", "af_sarah", "af_sky",
175
+ "am_adam", "am_echo", "am_eric", "am_fenrir", "am_liam",
176
+ "am_michael", "am_onyx", "am_orion", "am_puck",
177
+ "bf_alice", "bf_emma", "bf_isabella",
178
+ "bm_george", "bm_lewis",
179
+ "pf_dora", "pm_alex", "pm_santa",
180
+ ]
181
+
182
+ demo = gr.Interface(
183
+ fn=generate_tts,
184
+ inputs=[
185
+ gr.Textbox(label="Texto", lines=3, placeholder="Digite o texto aqui..."),
186
+ gr.Dropdown(choices=VOICES, value="af_heart", label="Voz"),
187
+ gr.Slider(minimum=0.5, maximum=2.0, value=1.0, step=0.1, label="Velocidade"),
188
+ ],
189
+ outputs=gr.Audio(label="Audio Gerado"),
190
+ title="Kokoro-82M TTS",
191
+ description="Ingles Americano / Britanico e Portugues Brasileiro.",
192
+ )
193
+
194
+ # ---------------------------------------------------------------- HTTP API
195
+
196
+ app = FastAPI()
197
+
198
+
199
+ @app.get("/tts/health")
200
+ def tts_health():
201
+ return {"ok": True, "engine": ENGINE, "threads": THREADS, "voices": len(VOICES), "loaded": sorted(_pipelines)}
202
+
203
+
204
+ @app.post("/tts/stream")
205
+ async def tts_stream(request: Request):
206
+ """Body: {"text", "voice"="af_heart", "speed"=1.0, "sample_rate"=16000}.
207
+ Response: raw PCM16 mono little-endian, streamed piece by piece."""
208
+ if API_KEY and request.headers.get("x-api-key") != API_KEY:
209
+ raise HTTPException(status_code=401, detail="invalid api key")
210
+ try:
211
+ body = await request.json()
212
+ except Exception:
213
+ raise HTTPException(status_code=400, detail="json body required")
214
+ text = str(body.get("text") or "").strip()[:MAX_CHARS]
215
+ voice = str(body.get("voice") or "af_heart")
216
+ if voice not in VOICES:
217
+ raise HTTPException(status_code=400, detail="unknown voice")
218
+ try:
219
+ speed = min(2.0, max(0.5, float(body.get("speed") or 1.0)))
220
+ rate = int(body.get("sample_rate") or 16000)
221
+ except (TypeError, ValueError):
222
+ raise HTTPException(status_code=400, detail="invalid speed or sample_rate")
223
+ if rate not in (16000, 24000):
224
+ raise HTTPException(status_code=400, detail="sample_rate must be 16000 or 24000")
225
+ if not text:
226
+ return JSONResponse({"detail": "empty text"}, status_code=400)
227
+
228
+ pieces = split_for_streaming(text)
229
+
230
+ def generate():
231
+ t0 = time.perf_counter()
232
+ for i, piece in enumerate(pieces):
233
+ pcm = _to_pcm16(_synth(piece, voice, speed), rate)
234
+ if i == 0:
235
+ print(f"[TTS stream] first piece in {time.perf_counter() - t0:.2f}s ({len(piece)} chars)")
236
+ yield pcm
237
+
238
+ return StreamingResponse(
239
+ generate(), # sync generator: Starlette runs it in a worker thread
240
+ media_type="application/octet-stream",
241
+ headers={"X-Sample-Rate": str(rate), "X-Pieces": str(len(pieces)), "Cache-Control": "no-store"},
242
+ )
243
+
244
+
245
+ # Optional second engine (LFM3-Audio-2B) for A/B tests: routes under /lfm3/tts,
246
+ # model loaded on first use. Off unless the Space variable LFM3_ENABLED=1.
247
+ if lfm3_engine.enabled():
248
+ def _check_key(request: Request) -> None:
249
+ if API_KEY and request.headers.get("x-api-key") != API_KEY:
250
+ raise HTTPException(status_code=401, detail="invalid api key")
251
+
252
+ app.include_router(lfm3_engine.build_router(
253
+ engine=lfm3_engine.Lfm3Engine(THREADS),
254
+ check_key=_check_key,
255
+ split=split_for_streaming,
256
+ to_pcm16=_to_pcm16,
257
+ max_chars=MAX_CHARS,
258
+ ))
259
+ print("[TTS] LFM3 routes enabled at /lfm3/tts (model loads on first request)")
260
+
261
+ app = gr.mount_gradio_app(app, demo, path="/")
262
+
263
+
264
+ def _warmup():
265
+ try:
266
+ _synth("Hello there.", "af_heart", 1.0)
267
+ print("[TTS] warm-up done")
268
+ except Exception as e:
269
+ print(f"[TTS] warm-up failed: {e}")
270
+
271
+
272
+ threading.Thread(target=_warmup, daemon=True).start()
273
+
274
+ if __name__ == "__main__":
275
+ # HF Spaces (Gradio SDK) expose GRADIO_SERVER_PORT (7860); 7861 is taken
276
+ # by the platform there, so PORT is not used.
277
+ uvicorn.run(app, host="0.0.0.0", port=int(os.getenv("GRADIO_SERVER_PORT", "7860")))
 
lfm3_engine.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LFM3-Audio-2B as an optional second engine of the Kokoro Space (for A/B tests).
2
+
3
+ Off unless the Space variable LFM3_ENABLED=1. When on, the routes below sit
4
+ beside the Kokoro ones with the same contract (a client only changes the path):
5
+
6
+ POST /lfm3/tts/stream {"text", "voice", "sample_rate"} -> raw PCM16 mono
7
+ POST /lfm3/tts/bench {"text", "voice"} -> seconds per piece
8
+ GET /lfm3/tts/health
9
+
10
+ The model (about 8 GB in float32 on CPU) loads on the first request, not at
11
+ start-up, so Kokoro boots and answers exactly as before; transformers is not
12
+ imported until then. One LFM3 synthesis at a time. "speed" is ignored (LFM3 has
13
+ no speed control; X-Speed-Ignored says so). Voices: "female", "male" or a
14
+ Kokoro id such as "af_heart" (see pieces.parse_voice).
15
+
16
+ LiquidAI/LFM3-Audio-2B is under the LFM Open License v1.0: commercial use only
17
+ below US$10M annual revenue.
18
+ """
19
+ import asyncio
20
+ import os
21
+ import threading
22
+ import time
23
+ from typing import Callable
24
+
25
+ import numpy as np
26
+ from fastapi import APIRouter, HTTPException, Request
27
+ from fastapi.responses import JSONResponse, StreamingResponse
28
+
29
+ from pieces import parse_voice, system_prompt
30
+
31
+ MODEL_ID = os.getenv("LFM3_MODEL_ID", "LiquidAI/LFM3-Audio-2B")
32
+ MAX_NEW_TOKENS = int(os.getenv("LFM3_MAX_NEW_TOKENS", "256")) # audio frames per piece
33
+ SAMPLE_RATE = 24000 # LFM3 codec output
34
+
35
+
36
+ def enabled() -> bool:
37
+ return os.getenv("LFM3_ENABLED", "").strip().lower() in ("1", "true", "yes")
38
+
39
+
40
+ class Lfm3Engine:
41
+ """Lazy, thread-safe LFM3 text-to-speech."""
42
+
43
+ def __init__(self, threads: int) -> None:
44
+ self.threads = threads
45
+ self.device = "cpu"
46
+ self.dtype = "float32"
47
+ self._model = None
48
+ self._processor = None
49
+ self._codec = None
50
+ self._load_lock = threading.Lock()
51
+ self._synth_lock = threading.Lock()
52
+
53
+ @property
54
+ def loaded(self) -> bool:
55
+ return self._model is not None
56
+
57
+ def _load(self) -> None:
58
+ with self._load_lock:
59
+ if self._model is not None:
60
+ return
61
+ import torch
62
+ from transformers import AutoModelForMultimodalLM, AutoProcessor
63
+
64
+ started = time.perf_counter()
65
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
66
+ dtype = torch.bfloat16 if self.device == "cuda" else torch.float32
67
+ self.dtype = str(dtype).replace("torch.", "")
68
+ model = AutoModelForMultimodalLM.from_pretrained(
69
+ MODEL_ID, dtype=dtype, device_map=self.device, trust_remote_code=True
70
+ ).eval()
71
+ processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True)
72
+ self._codec = processor.audio_tokenizer.to(device=self.device).eval()
73
+ self._processor = processor
74
+ self._model = model # set last: `loaded` means everything is ready
75
+ print(f"[LFM3] loaded {MODEL_ID} on {self.device} ({self.dtype}) in {time.perf_counter() - started:.1f}s")
76
+
77
+ def synth(self, text: str, language: str, gender: str) -> np.ndarray:
78
+ """Float32 mono audio at 24 kHz for one piece of text."""
79
+ import torch
80
+
81
+ self._load()
82
+ conversation = [
83
+ {"role": "system", "content": system_prompt(language, gender)},
84
+ {"role": "user", "content": text},
85
+ {"role": "assistant", "content": "<|audio_start|>"},
86
+ ]
87
+ with self._synth_lock, torch.no_grad():
88
+ inputs = self._processor.apply_chat_template(
89
+ conversation,
90
+ continue_final_message=True,
91
+ tokenize=True,
92
+ return_dict=True,
93
+ return_tensors="pt",
94
+ ).to(self.device)
95
+ outputs = self._model.generate(
96
+ **inputs,
97
+ max_new_tokens=MAX_NEW_TOKENS,
98
+ audio_temperature=1.0,
99
+ audio_top_k=128,
100
+ audio_repetition_penalty=1.1,
101
+ audio_repetition_window=4096,
102
+ return_dict_in_generate=True,
103
+ )
104
+ waveform = self._codec.decode(
105
+ outputs.audio_codes[:1, :, : outputs.audio_lengths[0]]
106
+ ).audio_values[0]
107
+ return waveform.float().cpu().numpy().reshape(-1)
108
+
109
+
110
+ def build_router(
111
+ *,
112
+ engine: Lfm3Engine,
113
+ check_key: Callable[[Request], None],
114
+ split: Callable[[str], list],
115
+ to_pcm16: Callable[[np.ndarray, int], bytes],
116
+ max_chars: int,
117
+ ) -> APIRouter:
118
+ """Routes that share the Kokoro Space's API-key check, text splitting and
119
+ PCM conversion."""
120
+ router = APIRouter(prefix="/lfm3/tts")
121
+
122
+ async def read_body(request: Request) -> dict:
123
+ try:
124
+ body = await request.json()
125
+ except Exception:
126
+ raise HTTPException(status_code=400, detail="json body required")
127
+ if not isinstance(body, dict):
128
+ raise HTTPException(status_code=400, detail="json object required")
129
+ return body
130
+
131
+ def voice_or_400(body: dict):
132
+ parsed = parse_voice(str(body.get("voice") or "female"))
133
+ if parsed is None:
134
+ raise HTTPException(
135
+ status_code=400, detail="unknown voice: use female, male or an a?_/b?_ Kokoro id"
136
+ )
137
+ return parsed
138
+
139
+ @router.get("/health")
140
+ def health():
141
+ return {"ok": True, "engine": "lfm3", "model": MODEL_ID, "loaded": engine.loaded,
142
+ "device": engine.device, "dtype": engine.dtype, "threads": engine.threads}
143
+
144
+ @router.post("/stream")
145
+ async def stream(request: Request):
146
+ check_key(request)
147
+ body = await read_body(request)
148
+ text = str(body.get("text") or "").strip()[:max_chars]
149
+ language, gender = voice_or_400(body)
150
+ try:
151
+ rate = int(body.get("sample_rate") or 16000)
152
+ except (TypeError, ValueError):
153
+ raise HTTPException(status_code=400, detail="invalid sample_rate")
154
+ if rate not in (16000, 24000):
155
+ raise HTTPException(status_code=400, detail="sample_rate must be 16000 or 24000")
156
+ if not text:
157
+ return JSONResponse({"detail": "empty text"}, status_code=400)
158
+
159
+ pieces = split(text)
160
+
161
+ def generate():
162
+ started = time.perf_counter()
163
+ for i, piece in enumerate(pieces):
164
+ pcm = to_pcm16(engine.synth(piece, language, gender), rate)
165
+ if i == 0:
166
+ print(f"[LFM3 stream] first piece in {time.perf_counter() - started:.2f}s ({len(piece)} chars)")
167
+ yield pcm
168
+
169
+ return StreamingResponse(
170
+ generate(), # sync generator: Starlette runs it in a worker thread
171
+ media_type="application/octet-stream",
172
+ headers={"X-Sample-Rate": str(rate), "X-Pieces": str(len(pieces)),
173
+ "X-Speed-Ignored": "1", "Cache-Control": "no-store"},
174
+ )
175
+
176
+ @router.post("/bench")
177
+ async def bench(request: Request):
178
+ """Seconds spent synthesizing against seconds of audio, per piece
179
+ (rtf below 1 is faster than real time). The first call also loads the
180
+ model, so run it twice and read the second."""
181
+ check_key(request)
182
+ body = await read_body(request)
183
+ text = str(body.get("text") or "").strip()[:max_chars]
184
+ language, gender = voice_or_400(body)
185
+ if not text:
186
+ return JSONResponse({"detail": "empty text"}, status_code=400)
187
+
188
+ def run():
189
+ rows = []
190
+ for piece in split(text):
191
+ started = time.perf_counter()
192
+ audio = engine.synth(piece, language, gender)
193
+ took = time.perf_counter() - started
194
+ seconds = audio.size / SAMPLE_RATE
195
+ rows.append({"chars": len(piece), "synth_seconds": round(took, 3),
196
+ "audio_seconds": round(seconds, 3),
197
+ "rtf": round(took / seconds, 3) if seconds else None})
198
+ return rows
199
+
200
+ rows = await asyncio.to_thread(run)
201
+ return {"device": engine.device, "threads": engine.threads, "pieces": rows,
202
+ "first_piece_seconds": rows[0]["synth_seconds"] if rows else None}
203
+
204
+ return router
pieces.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pure helpers of the LFM3 Space (no model, no network): text pieces and voices.
2
+
3
+ Kept apart from app.py so they can be unit-tested without torch or transformers.
4
+ """
5
+ import re
6
+
7
+ FIRST_PIECE_MAX = 60 # first sentence longer than this is cut at its first clause
8
+
9
+ _SENTENCE = re.compile(r"(?<=[.!?…])\s+")
10
+ _CLAUSE = re.compile(r"(?<=[,;:])\s+")
11
+
12
+ # The Kokoro voice ids the app already sends (af_heart, bm_george, ...) are
13
+ # accepted, so the same client can be pointed at either Space. LFM3 has no
14
+ # named voices: only a language/locale and a female or male voice.
15
+ _KOKORO_LANG = {"a": "American English", "b": "British English"}
16
+ _GENDER = {"f": "female", "m": "male"}
17
+ _KOKORO_VOICE = re.compile(r"^([ab])([fm])_[a-z]+$")
18
+
19
+
20
+ def split_for_streaming(text: str) -> list:
21
+ """Sentences, with the first one cut at its first clause when long, so
22
+ the first audio arrives after synthesizing only a few words."""
23
+ sentences = [s.strip() for s in _SENTENCE.split(text) if s.strip()]
24
+ if not sentences:
25
+ return []
26
+ first = sentences[0]
27
+ if len(first) > FIRST_PIECE_MAX:
28
+ parts = _CLAUSE.split(first, maxsplit=1)
29
+ if len(parts) == 2 and len(parts[0]) >= 12 and len(parts[1]) >= 12:
30
+ return [parts[0], parts[1]] + sentences[1:]
31
+ return sentences
32
+
33
+
34
+ def parse_voice(voice: str):
35
+ """(language, gender) for a voice id, or None when it is not supported.
36
+
37
+ "female" / "male" mean American English; "af_heart"-style ids map the
38
+ first letter to American (a) or British (b) English and the second to the
39
+ gender. Portuguese Kokoro voices (pf_, pm_) are not mapped on purpose:
40
+ this Space is for comparing English."""
41
+ voice = (voice or "").strip().lower()
42
+ if voice in ("female", "male"):
43
+ return "American English", voice
44
+ match = _KOKORO_VOICE.match(voice)
45
+ if match:
46
+ return _KOKORO_LANG[match.group(1)], _GENDER[match.group(2)]
47
+ return None
48
+
49
+
50
+ def system_prompt(language: str, gender: str) -> str:
51
+ return f"Perform TTS in {language} using a {gender} voice."
requirements.txt CHANGED
@@ -1,10 +1,14 @@
1
- kokoro>=0.9.4
2
- kokoro-onnx>=0.4.9
3
- onnxruntime>=1.20
4
- soundfile>=0.12.1
5
- numpy>=1.24.0
6
- gradio>=4.0.0
7
- torch
8
- scipy
9
- fastapi
10
- uvicorn
 
 
 
 
 
1
+ kokoro>=0.9.4
2
+ kokoro-onnx>=0.4.9
3
+ onnxruntime>=1.20
4
+ soundfile>=0.12.1
5
+ numpy>=1.24.0
6
+ gradio>=4.0.0
7
+ torch
8
+ scipy
9
+ fastapi
10
+ uvicorn
11
+ # Optional LFM3-Audio-2B engine (LFM3_ENABLED=1). transformers 5 needs Python 3.11+.
12
+ transformers>=5.20.2
13
+ accelerate
14
+ librosa