-
Notifications
You must be signed in to change notification settings - Fork 373
Expand file tree
/
Copy pathmoss_tts_local_v1.5_app.py
More file actions
1845 lines (1756 loc) · 74.7 KB
/
Copy pathmoss_tts_local_v1.5_app.py
File metadata and controls
1845 lines (1756 loc) · 74.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
"""Realtime Web Audio app for MOSS-TTS Local Transformer v1.5."""
from __future__ import annotations
import argparse
import json
import logging
import mimetypes
import os
import queue
import re
import sys
import threading
import time
import uuid
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Any
from urllib.parse import unquote
import orjson
import torch
import uvicorn
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, StreamingResponse
REPO_ROOT = Path(__file__).resolve().parent.parent
STREAMING_MODULE_DIR = REPO_ROOT / "moss_tts_local_v1.5"
if str(STREAMING_MODULE_DIR) not in sys.path:
sys.path.insert(0, str(STREAMING_MODULE_DIR))
from streaming import (
DEFAULT_CODEC_DIR,
DEFAULT_MODEL_DIR,
DEFAULT_OUTPUT_DIR,
StreamingRequest,
StreamingRuntime,
load_runtime,
synthesize_stream,
)
torch.backends.cuda.enable_cudnn_sdp(False)
torch.backends.cuda.enable_flash_sdp(True)
torch.backends.cuda.enable_mem_efficient_sdp(True)
torch.backends.cuda.enable_math_sdp(True)
DEFAULT_UPLOAD_DIR = Path("outputs/moss_tts_local_v1_5_uploads")
DEFAULT_MAX_NEW_TOKENS = 7500
MODE_CLONE = "Clone"
MODE_CONTINUE = "Continuation"
MODE_CONTINUE_CLONE = "Continuation + Clone"
CONTINUATION_NOTICE = (
"Continuation mode is active. Fill Reference Audio Transcript with the transcript of the reference audio."
)
ZH_TOKENS_PER_CHAR = 3.098411951313033
EN_TOKENS_PER_CHAR = 0.8673376262755219
REFERENCE_AUDIO_DIR = REPO_ROOT / "assets" / "audio"
EXAMPLE_TEXTS_JSONL_PATH = REPO_ROOT / "assets" / "text" / "moss_tts_example_texts.jsonl"
LANGUAGE_TAG_AUTO = "Auto (omit)"
LANGUAGE_TAG_CHOICES = [
LANGUAGE_TAG_AUTO,
"Chinese",
"Cantonese",
"English",
"Arabic",
"Czech",
"Danish",
"Dutch",
"Finnish",
"French",
"German",
"Greek",
"Hebrew",
"Hindi",
"Hungarian",
"Italian",
"Japanese",
"Korean",
"Macedonian",
"Malay",
"Persian (Farsi)",
"Polish",
"Portuguese",
"Romanian",
"Russian",
"Spanish",
"Swahili",
"Swedish",
"Tagalog",
"Thai",
"Turkish",
"Vietnamese",
]
def _parse_example_id(example_id: str) -> tuple[str, int] | None:
matched = re.fullmatch(r"(zh|en)/(\d+)", (example_id or "").strip())
if matched is None:
return None
return matched.group(1), int(matched.group(2))
def _resolve_reference_audio_path(language: str, index: int) -> Path | None:
stem = f"reference_{language}_{index}"
for ext in (".wav", ".mp3", ".m4a"):
audio_path = REFERENCE_AUDIO_DIR / f"{stem}{ext}"
if audio_path.exists():
return audio_path
return None
def build_example_rows() -> list[dict[str, str]]:
rows: list[dict[str, str]] = []
if not EXAMPLE_TEXTS_JSONL_PATH.exists():
return rows
with open(EXAMPLE_TEXTS_JSONL_PATH, "rb") as f:
for line in f:
if not line.strip():
continue
sample = orjson.loads(line)
parsed = _parse_example_id(str(sample.get("id", "")))
if parsed is None:
continue
language, index = parsed
audio_path = _resolve_reference_audio_path(language, index)
if audio_path is None:
continue
rows.append(
{
"role": str(sample.get("role", "")).strip(),
"audio_path": str(audio_path),
"text": str(sample.get("text", "")).strip(),
"language": "Chinese" if language == "zh" else "English",
}
)
return rows
EXAMPLE_ROWS = build_example_rows()
def _normalize_language(language_tag: str | None) -> str:
value = (language_tag or "").strip()
return "" if value == LANGUAGE_TAG_AUTO else value
def _safe_int(value: Any, *, default: int, minimum: int, maximum: int | None = None) -> int:
try:
parsed = int(float(value))
except (TypeError, ValueError):
parsed = int(default)
parsed = max(int(minimum), parsed)
if maximum is not None:
parsed = min(int(maximum), parsed)
return parsed
def _safe_float(value: Any, *, default: float, minimum: float, maximum: float | None = None) -> float:
try:
parsed = float(value)
except (TypeError, ValueError):
parsed = float(default)
parsed = max(float(minimum), parsed)
if maximum is not None:
parsed = min(float(maximum), parsed)
return parsed
def _decode_reference_path(path: str) -> str:
decoded = str(path or "")
for _ in range(2):
next_decoded = unquote(decoded)
if next_decoded == decoded:
break
decoded = next_decoded
return decoded
def _pcm16le_bytes(waveform: torch.Tensor) -> bytes:
if waveform.ndim == 1:
waveform = waveform.unsqueeze(0)
if waveform.shape[0] == 1:
waveform = waveform.repeat(2, 1)
elif waveform.shape[0] > 2:
waveform = waveform[:2]
pcm = waveform.detach().cpu().to(torch.float32).clamp(-1.0, 1.0)
pcm = (pcm * 32767.0).round().to(torch.int16)
return pcm.transpose(0, 1).contiguous().numpy().tobytes()
class RuntimeManager:
def __init__(
self,
*,
model_dir: str,
codec_dir: str,
device: str,
tts_device: str,
codec_device: str,
dtype: str,
attn_implementation: str,
codec_weight_dtype: str,
codec_compute_dtype: str,
warmup: bool,
) -> None:
self.model_dir = str(model_dir)
self.codec_dir = str(codec_dir)
self.device = device
self.tts_device = tts_device
self.codec_device = codec_device
self.dtype = dtype
self.attn_implementation = attn_implementation
self.codec_weight_dtype = codec_weight_dtype
self.codec_compute_dtype = codec_compute_dtype
self.warmup = bool(warmup)
self._lock = threading.Lock()
self._status_lock = threading.Lock()
self._runtime: StreamingRuntime | None = None
self._loader_thread: threading.Thread | None = None
self._state = "not_loaded"
self._error: str | None = None
self._load_started_at: float | None = None
self._ready_at: float | None = None
def _set_status(self, *, state: str, error: str | None = None) -> None:
with self._status_lock:
self._state = state
self._error = error
if state == "loading":
self._load_started_at = time.time()
self._ready_at = None
elif state == "ready":
self._ready_at = time.time()
def status(self) -> dict[str, Any]:
with self._status_lock:
state = self._state
error = self._error
load_started_at = self._load_started_at
ready_at = self._ready_at
elapsed = None
if load_started_at is not None:
elapsed = max(0.0, (ready_at or time.time()) - load_started_at)
return {
"state": state,
"error": error,
"load_started_at": load_started_at,
"ready_at": ready_at,
"load_elapsed_seconds": elapsed,
"model_dir": self.model_dir,
"codec_dir": self.codec_dir,
"device": self.device,
"tts_device": self.tts_device,
"codec_device": self.codec_device,
"dtype": self.dtype,
"requested_attn_implementation": self.attn_implementation,
"attn_implementation": (
self.attn_implementation
if self._runtime is None
else self._runtime.attn_implementation
),
"codec_weight_dtype": (
self.codec_weight_dtype
if self._runtime is None
else self._runtime.codec_weight_dtype
),
"codec_compute_dtype": self.codec_compute_dtype,
"n_vq": None if self._runtime is None else int(self._runtime.n_vq),
"sample_rate": None if self._runtime is None else int(self._runtime.sample_rate),
}
def preload_async(self) -> None:
with self._status_lock:
if self._runtime is not None or self._state == "loading":
return
if self._loader_thread is not None and self._loader_thread.is_alive():
return
def _load() -> None:
try:
self.get()
except Exception:
logging.exception("failed to preload MOSS-TTS Local v1.5 streaming runtime")
self._loader_thread = threading.Thread(target=_load, name="moss-tts-local-v1.5-runtime-loader", daemon=True)
self._loader_thread.start()
def get(self) -> StreamingRuntime:
with self._lock:
if self._runtime is None:
self._set_status(state="loading")
try:
self._runtime = load_runtime(
model_dir=self.model_dir,
codec_dir=self.codec_dir,
device=self.device,
tts_device=self.tts_device,
codec_device=self.codec_device,
dtype=self.dtype,
attn_implementation=self.attn_implementation,
codec_weight_dtype=self.codec_weight_dtype,
codec_compute_dtype=self.codec_compute_dtype,
warmup=self.warmup,
)
except Exception as exc:
self._set_status(state="error", error=str(exc))
raise
self._set_status(state="ready")
return self._runtime
class StreamingJob:
def __init__(self, job_id: str) -> None:
self.job_id = job_id
self.audio_queue: queue.Queue[bytes | None] = queue.Queue(maxsize=64)
self.status_lock = threading.Lock()
self.status: dict[str, Any] = {
"job_id": job_id,
"state": "queued",
"created_at": time.time(),
"started_at": None,
"first_audio_at": None,
"sample_rate": 48000,
"channels": 2,
"generated_frames": 0,
"max_new_tokens": DEFAULT_MAX_NEW_TOKENS,
"generated_audio_seconds": 0.0,
"emitted_audio_seconds": 0.0,
"lead_seconds": 0.0,
"error": None,
"closed": False,
}
self.result: dict[str, Any] | None = None
self.thread: threading.Thread | None = None
self.is_closed = False
def update(self, **kwargs: Any) -> None:
with self.status_lock:
self.status.update(kwargs)
def snapshot(self) -> dict[str, Any]:
with self.status_lock:
return dict(self.status)
class StreamingJobManager:
def __init__(self) -> None:
self._jobs: dict[str, StreamingJob] = {}
self._lock = threading.Lock()
def create(self) -> StreamingJob:
job = StreamingJob(uuid.uuid4().hex)
with self._lock:
self._jobs[job.job_id] = job
return job
def get(self, job_id: str) -> StreamingJob:
with self._lock:
job = self._jobs.get(job_id)
if job is None:
raise HTTPException(status_code=404, detail=f"stream job not found: {job_id}")
return job
def close(self, job_id: str) -> StreamingJob:
job = self.get(job_id)
with job.status_lock:
job.is_closed = True
job.status["closed"] = True
if job.status.get("state") not in {"finished", "error"}:
job.status["state"] = "closed"
try:
job.audio_queue.put_nowait(None)
except queue.Full:
pass
return job
def create_app(
*,
model_dir: str,
codec_dir: str,
output_dir: str | Path = DEFAULT_OUTPUT_DIR,
upload_dir: str | Path = DEFAULT_UPLOAD_DIR,
device: str = "cuda",
tts_device: str = "cuda:0",
codec_device: str = "cuda:0",
dtype: str = "bfloat16",
attn_implementation: str = "flash_attention_2",
codec_weight_dtype: str = "fp32",
codec_compute_dtype: str = "bf16",
warmup: bool = True,
preload: bool = True,
) -> FastAPI:
runtime_manager = RuntimeManager(
model_dir=str(model_dir),
codec_dir=str(codec_dir),
device=device,
tts_device=tts_device,
codec_device=codec_device,
dtype=dtype,
attn_implementation=attn_implementation,
codec_weight_dtype=codec_weight_dtype,
codec_compute_dtype=codec_compute_dtype,
warmup=warmup,
)
jobs = StreamingJobManager()
output_dir = Path(output_dir)
upload_dir = Path(upload_dir)
output_dir.mkdir(parents=True, exist_ok=True)
upload_dir.mkdir(parents=True, exist_ok=True)
@asynccontextmanager
async def lifespan(_: FastAPI):
if preload:
runtime_manager.get()
yield
app = FastAPI(title="MOSS-TTS Local v1.5 Realtime Streaming", lifespan=lifespan)
@app.get("/", response_class=HTMLResponse)
async def index() -> HTMLResponse:
defaults = {
"text": "欢迎关注模思智能、上海创智学院与复旦大学自然语言处理实验室。",
"max_new_tokens": DEFAULT_MAX_NEW_TOKENS,
"seed": 1234,
}
return HTMLResponse(
_html(
defaults=defaults,
examples=EXAMPLE_ROWS,
languages=LANGUAGE_TAG_CHOICES,
runtime=runtime_manager.status(),
)
)
def _put_stream_audio(job: StreamingJob, pcm_bytes: bytes) -> None:
while True:
with job.status_lock:
if job.is_closed:
return
try:
job.audio_queue.put(pcm_bytes, timeout=0.1)
return
except queue.Full:
continue
def _run_job(job: StreamingJob, request: StreamingRequest, mode_name: str, streaming_generation: bool) -> None:
try:
job.update(
state="loading_runtime",
started_at=time.time(),
max_new_tokens=int(request.max_new_frames),
mode=mode_name,
streaming_generation=streaming_generation,
)
runtime = runtime_manager.get()
job.update(state="running", sample_rate=runtime.sample_rate, channels=2, n_vq=runtime.n_vq)
for event in synthesize_stream(runtime, request, output_dir=output_dir):
with job.status_lock:
if job.is_closed:
break
if event.type == "metadata":
job.update(**event.data)
elif event.type == "progress":
job.update(**event.data)
elif event.type == "audio":
waveform = event.data["waveform"]
channels = 1 if waveform.ndim == 1 else int(min(2, waveform.shape[0]))
with job.status_lock:
if job.status.get("first_audio_at") is None:
job.status["first_audio_at"] = time.time()
if streaming_generation:
_put_stream_audio(job, _pcm16le_bytes(waveform))
job.update(
generated_frames=event.data.get("generated_frames", job.snapshot().get("generated_frames", 0)),
emitted_audio_seconds=event.data.get("emitted_audio_seconds", 0.0),
generated_audio_seconds=event.data.get("generated_audio_seconds", 0.0),
sample_rate=event.data.get("sample_rate", runtime.sample_rate),
channels=channels,
lead_seconds=event.data.get("lead_seconds", 0.0),
generation_lead_seconds=event.data.get("generation_lead_seconds", 0.0),
playback_lead_seconds=event.data.get("playback_lead_seconds"),
generation_realtime_factor=event.data.get("generation_realtime_factor", 0.0),
post_first_generation_realtime_factor=event.data.get(
"post_first_generation_realtime_factor"
),
first_audio_latency_seconds=event.data.get("first_audio_latency_seconds"),
decode_chunks_submitted=event.data.get("decode_chunks_submitted", 0),
decode_queue_depth=event.data.get("decode_queue_depth", 0),
pending_decode_frames=event.data.get("pending_decode_frames", 0),
chunk_frames=event.data.get("chunk_frames", 0),
)
elif event.type == "result":
metadata = dict(event.data["metadata"])
job.result = {
"audio_path": event.data["audio_path"],
"tokens_path": event.data["tokens_path"],
"metadata_path": event.data["metadata_path"],
"metadata": metadata,
}
job.update(
state="finished",
generated_frames=metadata.get("generated_frames", 0),
emitted_audio_seconds=metadata.get("duration_seconds", 0.0),
audio_path=event.data["audio_path"],
)
try:
job.audio_queue.put_nowait(None)
except queue.Full:
pass
except Exception as exc: # noqa: BLE001
job.update(state="error", error=str(exc))
try:
job.audio_queue.put_nowait(None)
except queue.Full:
pass
@app.post("/api/generate-stream/start")
async def generate_stream_start(
mode: str = Form("voice_clone"),
language: str = Form(""),
text: str = Form(...),
prompt_text: str = Form(""),
max_new_tokens: int = Form(DEFAULT_MAX_NEW_TOKENS),
codec_chunk_frames: int = Form(8),
seed: int = Form(1234),
tokens_control: int = Form(0),
tokens: int = Form(0),
temperature: float = Form(1.7),
top_p: float = Form(0.8),
top_k: int = Form(25),
repetition_penalty: float = Form(1.0),
streaming_generation: int = Form(1),
example_audio_path: str = Form(""),
prompt_audio: UploadFile | None = File(None),
) -> JSONResponse:
text = (text or "").strip()
if not text:
raise HTTPException(status_code=400, detail="text must not be empty")
mode = (mode or "").strip().lower()
if mode not in {"voice_clone", "continuation", "continuation_clone"}:
mode = "voice_clone"
mode_name = {
"voice_clone": MODE_CLONE,
"continuation": MODE_CONTINUE,
"continuation_clone": MODE_CONTINUE_CLONE,
}[mode]
prompt_audio_path = ""
if prompt_audio is not None and prompt_audio.filename:
suffix = Path(prompt_audio.filename).suffix or ".wav"
prompt_path = upload_dir / f"{uuid.uuid4().hex}{suffix}"
prompt_path.write_bytes(await prompt_audio.read())
prompt_audio_path = str(prompt_path)
elif example_audio_path:
candidate = Path(_decode_reference_path(example_audio_path))
if candidate.exists() and REFERENCE_AUDIO_DIR in candidate.resolve().parents:
prompt_audio_path = str(candidate)
if not prompt_audio_path:
mode_name = "Direct Generation"
if mode in {"continuation", "continuation_clone"} and prompt_audio_path:
if not text:
raise HTTPException(status_code=400, detail="continuation mode requires text")
if not (prompt_text or "").strip():
raise HTTPException(
status_code=400,
detail="continuation mode requires reference audio transcript",
)
max_new_tokens = _safe_int(
max_new_tokens,
default=DEFAULT_MAX_NEW_TOKENS,
minimum=1,
maximum=DEFAULT_MAX_NEW_TOKENS,
)
codec_chunk_frames = _safe_int(codec_chunk_frames, default=8, minimum=0, maximum=32)
streaming_generation_enabled = bool(_safe_int(streaming_generation, default=1, minimum=0, maximum=1))
request = StreamingRequest(
text=text,
mode="continuation" if not prompt_audio_path or mode in {"continuation", "continuation_clone"} else "voice_clone",
prompt_text=prompt_text or "",
prompt_audio_path=prompt_audio_path or None,
language=_normalize_language(language),
tokens_control=bool(int(tokens_control)),
tokens=_safe_int(tokens, default=0, minimum=0),
max_new_frames=max_new_tokens,
do_sample=True,
temperature=_safe_float(temperature, default=1.7, minimum=0.1, maximum=3.0),
top_p=_safe_float(top_p, default=0.8, minimum=0.1, maximum=1.0),
top_k=_safe_int(top_k, default=25, minimum=1, maximum=200),
repetition_penalty=_safe_float(repetition_penalty, default=1.0, minimum=0.8, maximum=2.0),
seed=None if int(seed) < 0 else int(seed),
codec_chunk_frames=codec_chunk_frames,
)
job = jobs.create()
thread = threading.Thread(target=_run_job, args=(job, request, mode_name, streaming_generation_enabled), daemon=True)
job.thread = thread
thread.start()
return JSONResponse(
{
"job_id": job.job_id,
"audio_url": f"/api/generate-stream/{job.job_id}/audio",
"status_url": f"/api/generate-stream/{job.job_id}/status",
"result_url": f"/api/generate-stream/{job.job_id}/result",
"sample_rate": runtime_manager.status().get("sample_rate") or 48000,
"channels": 2,
}
)
@app.get("/api/reference-audio")
async def reference_audio(path: str) -> FileResponse:
try:
reference_root = REFERENCE_AUDIO_DIR.resolve(strict=True)
candidate = Path(_decode_reference_path(path)).resolve(strict=True)
except FileNotFoundError as exc:
raise HTTPException(status_code=404, detail="reference audio not found") from exc
if candidate != reference_root and reference_root not in candidate.parents:
raise HTTPException(status_code=403, detail="reference audio path is not allowed")
if not candidate.is_file():
raise HTTPException(status_code=404, detail="reference audio not found")
media_type = mimetypes.guess_type(str(candidate))[0] or "application/octet-stream"
return FileResponse(str(candidate), media_type=media_type, filename=candidate.name)
@app.get("/api/generate-stream/{job_id}/audio")
async def generate_stream_audio(job_id: str) -> StreamingResponse:
job = jobs.get(job_id)
def iterator():
while True:
item = job.audio_queue.get()
if item is None:
break
yield item
snapshot = job.snapshot()
return StreamingResponse(
iterator(),
media_type="application/octet-stream",
headers={
"X-Audio-Codec": "pcm_s16le",
"X-Audio-Sample-Rate": str(snapshot.get("sample_rate", 48000)),
"X-Audio-Channels": str(snapshot.get("channels", 2)),
"X-Stream-Id": job_id,
},
)
@app.get("/api/generate-stream/{job_id}/status")
async def generate_stream_status(job_id: str) -> JSONResponse:
return JSONResponse(jobs.get(job_id).snapshot())
@app.get("/api/generate-stream/{job_id}/result")
async def generate_stream_result(job_id: str) -> JSONResponse:
job = jobs.get(job_id)
if job.result is None:
raise HTTPException(status_code=404, detail="result is not ready")
return JSONResponse(job.result)
@app.get("/api/generate-stream/{job_id}/result-audio")
async def generate_stream_result_audio(job_id: str) -> FileResponse:
job = jobs.get(job_id)
if job.result is None:
raise HTTPException(status_code=404, detail="result is not ready")
return FileResponse(job.result["audio_path"], media_type="audio/wav", filename="generated.wav")
@app.post("/api/generate-stream/{job_id}/close")
async def generate_stream_close(job_id: str) -> JSONResponse:
jobs.close(job_id)
return JSONResponse({"ok": True})
@app.get("/api/runtime")
async def runtime_info() -> JSONResponse:
return JSONResponse(
{
"model_dir": str(model_dir),
"codec_dir": str(codec_dir),
"output_dir": str(output_dir),
"upload_dir": str(upload_dir),
"device": device,
"tts_device": tts_device,
"codec_device": codec_device,
"dtype": dtype,
"attn_implementation": attn_implementation,
"codec_weight_dtype": codec_weight_dtype,
"codec_compute_dtype": codec_compute_dtype,
"runtime": runtime_manager.status(),
}
)
@app.get("/api/health")
async def health() -> JSONResponse:
return JSONResponse(runtime_manager.status())
return app
def _html(*, defaults: dict[str, Any], examples: list[dict[str, str]], languages: list[str], runtime: dict[str, Any]) -> str:
replacements = {
"__DEFAULT_TEXT__": json.dumps(defaults["text"], ensure_ascii=False),
"__DEFAULT_MAX_NEW_TOKENS__": str(defaults["max_new_tokens"]),
"__DEFAULT_SEED__": str(defaults["seed"]),
"__EXAMPLES_JSON__": json.dumps(examples, ensure_ascii=False),
"__LANGUAGES_JSON__": json.dumps(languages, ensure_ascii=False),
"__RUNTIME_JSON__": json.dumps(runtime, ensure_ascii=False),
}
html = INDEX_HTML
for key, value in replacements.items():
html = html.replace(key, value)
return html
INDEX_HTML = r"""
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>MOSS-TTS Local v1.5 Realtime Streaming</title>
<style>
:root {
--bg: #f6f7f8;
--panel: #ffffff;
--ink: #111418;
--muted: #4d5562;
--line: #e5e7eb;
--accent: #0f766e;
--orange: #f97316;
}
* { box-sizing: border-box; }
body {
margin: 0;
background: linear-gradient(180deg, #f7f8fa 0%, #f3f5f7 100%);
color: var(--ink);
font: 14px/1.45 ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
.page { max-width: 1840px; margin: 0 auto; padding: 22px 58px 48px; }
.app-card {
border: 1px solid var(--line);
border-radius: 16px;
background: var(--panel);
padding: 14px;
margin-bottom: 16px;
}
.app-title { font-size: 22px; font-weight: 700; margin-bottom: 6px; letter-spacing: 0.2px; }
.app-subtitle { color: var(--muted); font-size: 14px; }
.layout { display: grid; grid-template-columns: minmax(0, 3fr) minmax(360px, 2fr); gap: 16px; align-items: start; }
.stack { display: flex; flex-direction: column; gap: 16px; }
.panel {
border: 1px solid var(--line);
background: var(--panel);
border-radius: 4px;
padding: 12px;
}
label { display: block; color: var(--muted); font-size: 13px; margin-bottom: 8px; }
textarea, select, input[type="number"], input[type="text"] {
width: 100%;
border: 1px solid var(--line);
border-radius: 4px;
background: #fff;
color: var(--ink);
font: inherit;
padding: 10px 12px;
}
textarea { min-height: 190px; resize: vertical; }
.small-textarea { min-height: 76px; }
.hint { color: var(--muted); font-size: 12px; margin-top: -3px; }
.drop-zone {
border: 1px solid var(--line);
border-radius: 4px;
min-height: 158px;
display: grid;
place-items: center;
color: #6b7280;
background: #fff;
position: relative;
overflow: hidden;
}
.drop-zone input { position: absolute; inset: 0; opacity: 0; cursor: pointer; z-index: 1; }
.drop-zone.hidden { display: none; }
.drop-zone.has-reference { min-height: 0; display: block; padding: 0; overflow: visible; }
.drop-zone.has-reference input { display: none; }
.drop-zone.has-reference .drop-copy { display: none; }
.reference-preview { display: block; width: 100%; position: relative; z-index: 2; pointer-events: auto; }
audio[disabled] { opacity: 0.55; pointer-events: none; }
.drop-copy { text-align: center; pointer-events: none; }
.selected-reference { margin-top: 8px; color: var(--muted); font-size: 12px; overflow-wrap: anywhere; text-align: center; }
.reference-action-row { display: flex; justify-content: center; align-items: center; gap: 12px; margin-top: 8px; flex-wrap: wrap; }
.reference-source-row { display: flex; justify-content: center; margin-top: 0; }
.reference-source-toggle { display: inline-flex; gap: 4px; border: 1px solid var(--line); border-radius: 8px; padding: 4px; background: #fff; }
.reference-source-button { display: inline-flex; align-items: center; gap: 7px; border-radius: 6px; padding: 8px 12px; background: transparent; color: var(--muted); }
.reference-source-button.active { background: var(--accent); color: #fff; }
.reference-source-button svg { width: 18px; height: 18px; stroke: currentColor; fill: none; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
.reference-record-controls { display: flex; justify-content: center; align-items: center; gap: 10px; margin-top: 12px; flex-wrap: wrap; }
.reference-record-controls.hidden { display: none; }
.record-button { display: inline-flex; align-items: center; gap: 8px; background: var(--accent); color: #fff; }
.record-button.recording { background: #fee2e2; color: #b91c1c; }
.record-dot { width: 10px; height: 10px; border-radius: 999px; background: currentColor; }
.record-status { color: var(--muted); font-size: 12px; }
.radio-row { display: flex; gap: 8px; flex-wrap: wrap; }
.radio-pill {
display: inline-flex;
align-items: center;
gap: 8px;
border: 1px solid var(--line);
border-radius: 4px;
padding: 8px 12px;
cursor: pointer;
background: #fff;
}
.radio-pill input { accent-color: var(--orange); }
.mode-hint { margin-top: 12px; color: var(--ink); }
.accordion {
border: 1px solid var(--line);
border-radius: 4px;
background: #fff;
padding: 0;
}
.accordion summary {
cursor: pointer;
list-style: none;
padding: 12px;
color: var(--ink);
border-bottom: 1px solid var(--line);
}
.accordion summary::-webkit-details-marker { display: none; }
.accordion summary::after { content: "▾"; float: right; }
.accordion[open] summary::after { content: "▴"; }
.accordion-body { padding: 12px; display: grid; gap: 14px; }
.control-row { display: grid; grid-template-columns: 1fr 92px; gap: 12px; align-items: center; }
.control-row input[type="range"] { width: 100%; accent-color: var(--orange); }
.range-label { color: var(--muted); font-size: 13px; margin-bottom: 4px; }
.range-minmax { display: flex; justify-content: space-between; color: #9ca3af; font-size: 11px; margin-top: 2px; }
.button-row { display: grid; grid-template-columns: 1fr 150px 120px; gap: 10px; }
button {
border: none;
border-radius: 4px;
padding: 12px 14px;
font-weight: 700;
cursor: pointer;
}
.primary { background: var(--accent); color: #fff; }
.secondary { background: #e5e7eb; color: var(--ink); }
.small-button { padding: 7px 10px; font-size: 12px; font-weight: 600; }
button:disabled { opacity: 0.55; cursor: not-allowed; }
audio { width: 100%; }
.audio-panel { min-height: 118px; display: flex; flex-direction: column; gap: 8px; justify-content: center; }
.status-box {
min-height: 110px;
max-height: 260px;
overflow: auto;
white-space: pre-wrap;
border: 1px solid var(--line);
border-radius: 4px;
padding: 10px;
background: #fff;
color: var(--ink);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
}
.summary { color: var(--muted); margin-bottom: 8px; }
.meter { height: 7px; background: #e5e7eb; border-radius: 999px; overflow: hidden; margin-bottom: 8px; }
.meter > div { height: 100%; width: 0%; background: var(--orange); transition: width 0.2s ease; }
.examples-wrap { overflow: auto; max-height: 500px; border: 1px solid var(--line); border-radius: 4px; }
table { width: 100%; border-collapse: collapse; background: #fff; font-size: 13px; }
th, td { border-bottom: 1px solid #eef0f3; padding: 10px; text-align: left; vertical-align: top; }
th { position: sticky; top: 0; background: #fff; z-index: 1; font-weight: 700; }
tr { cursor: pointer; }
tr:hover td { background: #f8fafc; }
.role-cell { width: 160px; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
.download { display: none; margin-top: 8px; color: var(--accent); font-weight: 700; text-decoration: none; }
.hidden { display: none; }
@media (max-width: 1100px) {
.page { padding: 16px; }
.layout { grid-template-columns: 1fr; }
.button-row { grid-template-columns: 1fr; }
}
</style>
</head>
<body>
<div class="page">
<div class="app-card">
<div class="app-title">MOSS-TTS Local v1.5 Realtime Streaming</div>
<div class="app-subtitle">Realtime streaming decode with Direct Generation, Clone, Continuation, Continuation + Clone, and language tags</div>
</div>
<div class="layout">
<div class="stack">
<div class="panel">
<label for="text">Text</label>
<textarea id="text" placeholder="Enter text to synthesize or continue after the reference audio."></textarea>
</div>
<div class="panel">
<label>Reference Audio (Optional)</label>
<div id="reference-drop-zone" class="drop-zone">
<input id="prompt-audio" type="file" accept="audio/*,.wav,.mp3,.flac,.m4a,.ogg,.opus,.aac">
<div class="drop-copy">Drop audio here<br>or<br>click to upload</div>
<audio id="reference-audio-preview" class="reference-preview hidden" controls></audio>
</div>
<input id="example-audio-path" type="hidden" value="">
<div id="reference-record-controls" class="reference-record-controls hidden">
<button id="reference-record-button" class="record-button" type="button"><span class="record-dot"></span><span id="reference-record-button-label">Start Recording</span></button>
<span id="reference-record-status" class="record-status">Ready to record.</span>
</div>
<div class="reference-action-row">
<div class="reference-source-row">
<div class="reference-source-toggle" role="group" aria-label="Reference audio source">
<button id="reference-source-upload" class="reference-source-button active" type="button" aria-pressed="true" title="Upload">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 16V4"></path><path d="M7 9l5-5 5 5"></path><path d="M5 20h14"></path></svg>
<span>Upload</span>
</button>
<button id="reference-source-record" class="reference-source-button" type="button" aria-pressed="false" title="Record">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 14a3 3 0 0 0 3-3V6a3 3 0 0 0-6 0v5a3 3 0 0 0 3 3z"></path><path d="M19 11a7 7 0 0 1-14 0"></path><path d="M12 18v3"></path><path d="M8 21h8"></path></svg>
<span>Record</span>
</button>
</div>
</div>
<button id="clear-reference" class="secondary small-button" type="button">Clear Reference Audio</button>
</div>
<div id="selected-reference" class="selected-reference">No reference selected.</div>
</div>
<div class="panel">
<label>Mode with Reference Audio</label>
<div class="hint">If no reference audio is uploaded, Direct Generation will be used automatically.</div>
<div class="radio-row" style="margin-top: 10px;">
<label class="radio-pill"><input type="radio" name="mode" value="voice_clone" checked> Clone</label>
<label class="radio-pill"><input type="radio" name="mode" value="continuation"> Continuation</label>
<label class="radio-pill"><input type="radio" name="mode" value="continuation_clone"> Continuation + Clone</label>
</div>
</div>
<div id="mode-hint" class="mode-hint"></div>
<div id="reference-transcript-panel" class="panel hidden">
<label for="prompt-text">Reference Audio Transcript</label>
<div class="hint">Required for Continuation modes. Enter the transcript corresponding to the reference audio.</div>
<textarea id="prompt-text" class="small-textarea" placeholder="Transcript of the reference audio."></textarea>
</div>
<div class="panel">
<label for="language">Language Tag</label>
<div class="hint">Optional for v1.5. Set this when the input language is known, especially outside Chinese and English.</div>
<select id="language"></select>
<label style="margin-top: 14px;"><input id="tokens-control" type="checkbox"> Enable Duration Control (Expected Audio Tokens)</label>
<div id="tokens-wrap" class="hidden" style="margin-top: 10px;">
<label for="tokens">expected_tokens</label>
<input id="tokens" type="number" min="1" step="1" value="1">
</div>
</div>
<div id="duration-hint" class="hint">Duration control is disabled.</div>
<details class="accordion" open>
<summary>Sampling Parameters (Audio)</summary>
<div class="accordion-body">
<div class="control-row" data-pair="temperature">
<div>
<div class="range-label">temperature</div>
<input id="temperature-range" type="range" min="0.1" max="3" step="0.05" value="1.7">
<div class="range-minmax"><span>0.1</span><span>3</span></div>
</div>
<input id="temperature" type="number" min="0.1" max="3" step="0.05" value="1.7">
</div>
<div class="control-row" data-pair="top-p">
<div>
<div class="range-label">top_p</div>
<input id="top-p-range" type="range" min="0.1" max="1" step="0.01" value="0.8">
<div class="range-minmax"><span>0.1</span><span>1</span></div>
</div>
<input id="top-p" type="number" min="0.1" max="1" step="0.01" value="0.8">
</div>
<div class="control-row" data-pair="top-k">
<div>
<div class="range-label">top_k</div>
<input id="top-k-range" type="range" min="1" max="200" step="1" value="25">
<div class="range-minmax"><span>1</span><span>200</span></div>
</div>
<input id="top-k" type="number" min="1" max="200" step="1" value="25">
</div>
<div class="control-row" data-pair="repetition-penalty">
<div>
<div class="range-label">repetition_penalty</div>
<input id="repetition-penalty-range" type="range" min="0.8" max="2" step="0.05" value="1.0">
<div class="range-minmax"><span>0.8</span><span>2</span></div>
</div>
<input id="repetition-penalty" type="number" min="0.8" max="2" step="0.05" value="1.0">
</div>
<div class="control-row" data-pair="max-new-tokens">
<div>
<div class="range-label">max_new_tokens</div>
<input id="max-new-tokens-range" type="range" min="1" max="7500" step="1" value="__DEFAULT_MAX_NEW_TOKENS__">
<div class="range-minmax"><span>1</span><span>7500</span></div>
</div>
<input id="max-new-tokens" type="number" min="1" max="7500" step="1" value="__DEFAULT_MAX_NEW_TOKENS__">
</div>
<div class="control-row" data-pair="codec-chunk-frames">
<div>