-
Notifications
You must be signed in to change notification settings - Fork 508
Expand file tree
/
Copy pathapp.py
More file actions
2904 lines (2673 loc) · 108 KB
/
Copy pathapp.py
File metadata and controls
2904 lines (2673 loc) · 108 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
from __future__ import annotations
import argparse
import base64
import io
import json
import logging
import os
import queue
import tempfile
import threading
import time
import urllib.parse
import uuid
import wave
from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable, Iterator, Optional, Sequence, TypeVar
import numpy as np
import torch
import uvicorn
from fastapi import FastAPI, File, Form, Request, UploadFile
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, StreamingResponse
from moss_tts_nano_runtime import (
DEFAULT_AUDIO_TOKENIZER_PATH,
DEFAULT_CHECKPOINT_PATH,
DEFAULT_OUTPUT_DIR,
NanoTTSService,
)
from text_normalization_pipeline import (
TextNormalizationSnapshot as SharedTextNormalizationSnapshot,
WeTextProcessingManager as SharedWeTextProcessingManager,
prepare_tts_request_texts as shared_prepare_tts_request_texts,
)
APP_DIR = Path(__file__).resolve().parent
DEMO_METADATA_PATH = APP_DIR / "assets" / "demo.jsonl"
PROMPT_UPLOAD_DIR = APP_DIR / ".app_prompt_uploads"
@dataclass(frozen=True)
class DemoEntry:
demo_id: str
name: str
prompt_audio_path: Path
prompt_audio_relative_path: str
text: str
def _load_demo_entries() -> list[DemoEntry]:
if not DEMO_METADATA_PATH.is_file():
logging.warning("demo metadata file not found: %s", DEMO_METADATA_PATH)
return []
demo_entries: list[DemoEntry] = []
for line_index, raw_line in enumerate(DEMO_METADATA_PATH.read_text(encoding="utf-8").splitlines(), start=1):
line = raw_line.strip()
if not line:
continue
try:
payload = json.loads(line)
except Exception:
logging.warning("failed to parse demo metadata line=%s path=%s", line_index, DEMO_METADATA_PATH, exc_info=True)
continue
prompt_audio_relative_path = str(payload.get("role", "")).strip()
text = str(payload.get("text", "")).strip()
if not prompt_audio_relative_path or not text:
logging.warning("skip invalid demo metadata line=%s role/text missing", line_index)
continue
prompt_audio_path = (APP_DIR / prompt_audio_relative_path).resolve()
if not prompt_audio_path.is_file():
logging.warning(
"skip demo metadata line=%s prompt speech missing: %s",
line_index,
prompt_audio_path,
)
continue
try:
prompt_audio_relative_path = str(prompt_audio_path.relative_to(APP_DIR))
except ValueError:
logging.warning(
"skip demo metadata line=%s prompt speech escaped app dir: %s",
line_index,
prompt_audio_path,
)
continue
demo_index = len(demo_entries) + 1
name = str(payload.get("name", "")).strip() or f"Demo {demo_index}: {prompt_audio_path.stem}"
demo_entries.append(
DemoEntry(
demo_id=f"demo-{demo_index}",
name=name,
prompt_audio_path=prompt_audio_path,
prompt_audio_relative_path=prompt_audio_relative_path,
text=text,
)
)
return demo_entries
def _resolve_vscode_root_path(vscode_proxy_uri: Optional[str], server_port: int) -> Optional[str]:
if not vscode_proxy_uri:
return None
raw = vscode_proxy_uri.strip()
if not raw or raw == "/":
return None
port_str = str(server_port)
replacements = (
"{{port}}",
"{port}",
"%7B%7Bport%7D%7D",
"%7b%7bport%7d%7d",
"%7Bport%7D",
"%7bport%7d",
)
resolved = raw
for token in replacements:
resolved = resolved.replace(token, port_str)
parsed = urllib.parse.urlsplit(resolved)
if parsed.scheme and parsed.netloc:
path = parsed.path or "/"
else:
path = resolved
if not path.startswith("/"):
path = "/" + path
normalized = path.rstrip("/")
return normalized or None
@dataclass(frozen=True)
class WarmupSnapshot:
state: str
progress: float
message: str
error: str | None = None
@property
def ready(self) -> bool:
return self.state == "ready"
@property
def failed(self) -> bool:
return self.state == "failed"
class WarmupManager:
def __init__(self, runtime: NanoTTSService, text_normalizer_manager: "WeTextProcessingManager | None" = None) -> None:
self.runtime = runtime
self.text_normalizer_manager = text_normalizer_manager
self._lock = threading.Lock()
self._thread: threading.Thread | None = None
self._started = False
self._state = "pending"
self._progress = 0.0
self._message = "Waiting for startup warmup."
self._error: str | None = None
def start(self) -> None:
with self._lock:
if self._started:
return
self._started = True
self._thread = threading.Thread(target=self._run, name="nano-tts-warmup", daemon=True)
self._thread.start()
def snapshot(self) -> WarmupSnapshot:
with self._lock:
return WarmupSnapshot(
state=self._state,
progress=self._progress,
message=self._message,
error=self._error,
)
def ensure_ready(self) -> WarmupSnapshot:
with self._lock:
if not self._started:
self._started = True
self._thread = threading.Thread(target=self._run, name="nano-tts-warmup", daemon=True)
self._thread.start()
thread = self._thread
if thread is not None and thread.is_alive():
thread.join()
return self.snapshot()
def _set_state(
self,
*,
state: str | None = None,
progress: float | None = None,
message: str | None = None,
error: str | None = None,
) -> None:
with self._lock:
if state is not None:
self._state = state
if progress is not None:
self._progress = max(0.0, min(1.0, float(progress)))
if message is not None:
self._message = message
self._error = error
def _run(self) -> None:
try:
self._set_state(state="running", progress=0.1, message="Loading Nano-TTS model.", error=None)
self.runtime.get_model()
self._set_state(state="running", progress=0.6, message="Running startup warmup synthesis.", error=None)
result = self.runtime.warmup()
_maybe_delete_file(result["audio_path"])
if self.text_normalizer_manager is not None:
self._set_state(
state="running",
progress=0.85,
message="Loading WeTextProcessing text normalization.",
error=None,
)
normalization_snapshot = self.text_normalizer_manager.ensure_ready()
if normalization_snapshot.failed:
raise RuntimeError(normalization_snapshot.error or normalization_snapshot.message)
self._set_state(
state="ready",
progress=1.0,
message=(
f"Warmup complete. device={self.runtime.device} "
f"elapsed={result['elapsed_seconds']:.2f}s"
+ (" | WeTextProcessing ready." if self.text_normalizer_manager is not None else "")
),
error=None,
)
except Exception as exc:
logging.exception("Nano-TTS warmup failed")
self._set_state(state="failed", progress=1.0, message="Warmup failed.", error=str(exc))
T = TypeVar("T")
class RequestRuntimeManager:
def __init__(self, default_runtime: NanoTTSService) -> None:
self.default_runtime = default_runtime
self.default_cpu_threads = max(1, int(os.cpu_count() or 1))
self._lock = threading.Lock()
self._cpu_execution_lock = threading.Lock()
self._cpu_runtime: NanoTTSService | None = None
@staticmethod
def normalize_requested_execution_device(requested: str | None) -> str:
normalized = str(requested or "default").strip().lower()
if normalized not in {"default", "cpu"}:
return "default"
return normalized
def is_dedicated_cpu_request(self, requested: str | None) -> bool:
normalized = self.normalize_requested_execution_device(requested)
return normalized == "cpu" and self.default_runtime.device.type != "cpu"
def is_cpu_runtime_loaded(self) -> bool:
with self._lock:
return self._cpu_runtime is not None
def _build_cpu_runtime_locked(self) -> NanoTTSService:
if self._cpu_runtime is not None:
return self._cpu_runtime
self._cpu_runtime = NanoTTSService(
checkpoint_path=self.default_runtime.checkpoint_path,
audio_tokenizer_path=self.default_runtime.audio_tokenizer_path,
device="cpu",
dtype="float32",
attn_implementation=self.default_runtime.attn_implementation or "auto",
output_dir=self.default_runtime.output_dir,
voice_presets=self.default_runtime.voice_presets,
)
return self._cpu_runtime
def resolve_runtime(self, requested: str | None) -> tuple[NanoTTSService, str]:
normalized = self.normalize_requested_execution_device(requested)
if normalized != "cpu":
return self.default_runtime, str(self.default_runtime.device.type)
if self.default_runtime.device.type == "cpu":
return self.default_runtime, "cpu"
with self._lock:
return self._build_cpu_runtime_locked(), "cpu"
def _resolve_cpu_threads(self, cpu_threads: int | None) -> int:
if cpu_threads is None:
return self.default_cpu_threads
try:
normalized_threads = int(cpu_threads)
except Exception:
return self.default_cpu_threads
if normalized_threads <= 0:
return self.default_cpu_threads
return max(1, normalized_threads)
def call_with_runtime(
self,
*,
requested_execution_device: str | None,
cpu_threads: int | None,
callback: Callable[[NanoTTSService], T],
) -> tuple[T, str, int | None]:
runtime, execution_device = self.resolve_runtime(requested_execution_device)
if runtime.device.type != "cpu":
return callback(runtime), execution_device, None
resolved_cpu_threads = self._resolve_cpu_threads(cpu_threads)
with self._cpu_execution_lock:
previous_threads = torch.get_num_threads()
threads_changed = previous_threads != resolved_cpu_threads
if threads_changed:
torch.set_num_threads(resolved_cpu_threads)
try:
return callback(runtime), execution_device, resolved_cpu_threads
finally:
if threads_changed:
torch.set_num_threads(previous_threads)
def iter_with_runtime(
self,
*,
requested_execution_device: str | None,
cpu_threads: int | None,
factory: Callable[[NanoTTSService], Iterator[T]],
) -> Iterator[tuple[T, str, int | None]]:
runtime, execution_device = self.resolve_runtime(requested_execution_device)
if runtime.device.type != "cpu":
for item in factory(runtime):
yield item, execution_device, None
return
resolved_cpu_threads = self._resolve_cpu_threads(cpu_threads)
with self._cpu_execution_lock:
previous_threads = torch.get_num_threads()
threads_changed = previous_threads != resolved_cpu_threads
if threads_changed:
torch.set_num_threads(resolved_cpu_threads)
try:
for item in factory(runtime):
yield item, execution_device, resolved_cpu_threads
finally:
if threads_changed:
torch.set_num_threads(previous_threads)
@dataclass
class StreamingJob:
stream_id: str
audio_queue: "queue.Queue[bytes | None]" = field(default_factory=lambda: queue.Queue(maxsize=64))
created_at: float = field(default_factory=time.monotonic)
started_at: float | None = None
first_audio_at: float | None = None
completed_at: float | None = None
state: str = "starting"
run_status: str = "Starting realtime synthesis..."
error: str | None = None
prompt_audio_path: str | None = None
sample_rate: int = 48000
channels: int = 2
emitted_audio_seconds: float = 0.0
lead_seconds: float = 0.0
current_chunk_index: int | None = None
text_chunks: list[str] = field(default_factory=list)
chunk_index_base: int | None = None
audio_chunk_ranges: list[tuple[float, float, int]] = field(default_factory=list)
is_closed: bool = False
final_result: dict[str, object] | None = None
lock: threading.Lock = field(default_factory=threading.Lock)
def _resolve_playback_chunk_index_locked(self) -> int | None:
if not self.audio_chunk_ranges:
return self.current_chunk_index
playback_audio_seconds = max(0.0, float(self.emitted_audio_seconds) - float(self.lead_seconds))
for start_seconds, end_seconds, chunk_index in self.audio_chunk_ranges:
if playback_audio_seconds <= end_seconds + 1e-6:
return chunk_index
return self.audio_chunk_ranges[-1][2]
def snapshot(self) -> dict[str, object]:
with self.lock:
return {
"stream_id": self.stream_id,
"state": self.state,
"run_status": self.run_status,
"error": self.error,
"prompt_audio_path": self.prompt_audio_path,
"sample_rate": self.sample_rate,
"channels": self.channels,
"emitted_audio_seconds": self.emitted_audio_seconds,
"lead_seconds": self.lead_seconds,
"current_chunk_index": self.current_chunk_index,
"playback_chunk_index": self._resolve_playback_chunk_index_locked(),
"text_chunks": list(self.text_chunks),
"first_audio_latency_seconds": (
None
if self.started_at is None or self.first_audio_at is None
else max(0.0, self.first_audio_at - self.started_at)
),
"completed_at": self.completed_at,
"ready": self.state == "done",
"failed": self.state == "failed",
"closed": self.is_closed,
}
class StreamingJobManager:
def __init__(self) -> None:
self._lock = threading.Lock()
self._jobs: dict[str, StreamingJob] = {}
def create(self) -> StreamingJob:
stream_id = f"stream-{int(time.time() * 1000)}-{uuid.uuid4().hex[:8]}"
job = StreamingJob(stream_id=stream_id)
with self._lock:
self._jobs[stream_id] = job
return job
def get(self, stream_id: str) -> StreamingJob | None:
with self._lock:
return self._jobs.get(stream_id)
def close(self, stream_id: str) -> StreamingJob | None:
with self._lock:
job = self._jobs.get(stream_id)
if job is None:
return None
with job.lock:
job.is_closed = True
job.state = "closed" if job.state not in {"done", "failed"} else job.state
try:
job.audio_queue.put_nowait(None)
except queue.Full:
pass
return job
def delete(self, stream_id: str) -> StreamingJob | None:
with self._lock:
return self._jobs.pop(stream_id, None)
def _warmup_status_text(snapshot: WarmupSnapshot) -> str:
progress_pct = int(round(snapshot.progress * 100.0))
if snapshot.failed:
return f"Warmup failed: {snapshot.error or snapshot.message}"
if snapshot.ready:
return snapshot.message
return f"Warmup in progress ({progress_pct}%): {snapshot.message}"
def _format_run_status(result: dict[str, object]) -> str:
waveform_numpy = np.asarray(result["waveform_numpy"])
sample_count = int(waveform_numpy.shape[0]) if waveform_numpy.ndim >= 1 else 0
sample_rate = int(result["sample_rate"])
audio_seconds = sample_count / sample_rate if sample_rate > 0 else 0.0
global_attn = str(result.get("effective_global_attn_implementation", "unknown"))
local_attn = str(result.get("effective_local_attn_implementation", global_attn))
attn_summary = global_attn if global_attn == local_attn else f"{global_attn}/{local_attn}"
tts_batch_size = result.get("voice_clone_chunk_batch_size")
codec_batch_size = result.get("voice_clone_codec_batch_size")
batch_summary = ""
if tts_batch_size is not None or codec_batch_size is not None:
batch_summary = f" | tts_batch={int(tts_batch_size or 1)} | codec_batch={int(codec_batch_size or 1)}"
execution_summary = ""
execution_device = result.get("execution_device")
cpu_threads = result.get("cpu_threads")
if execution_device:
execution_summary = f" | exec={execution_device}"
if cpu_threads is not None:
execution_summary += f" | cpu_threads={int(cpu_threads)}"
prompt_audio_display_path = str(result.get("prompt_audio_display_path") or "").strip()
prompt_audio_path = str(result.get("prompt_audio_path") or "").strip()
speaker_summary = f"voice={result['voice']}"
if prompt_audio_display_path:
if prompt_audio_display_path.lower().startswith("uploaded:"):
speaker_summary = f"prompt={prompt_audio_display_path.split(':', 1)[1].strip()}"
else:
speaker_summary = f"prompt={Path(prompt_audio_display_path).stem}"
elif prompt_audio_path:
speaker_summary = f"prompt={Path(prompt_audio_path).stem}"
return (
f"Done | mode={result['mode']} | {speaker_summary} | "
f"attn={attn_summary}{batch_summary}{execution_summary} | audio={audio_seconds:.2f}s | elapsed={float(result['elapsed_seconds']):.2f}s"
)
def _format_stream_status(snapshot: dict[str, object]) -> str:
if bool(snapshot.get("failed")):
return f"Stream failed: {snapshot.get('error') or snapshot.get('run_status') or 'Unknown error'}"
if bool(snapshot.get("ready")):
return str(snapshot.get("run_status") or "Stream complete.")
if bool(snapshot.get("closed")):
return "Stream closed."
return str(snapshot.get("run_status") or "Streaming...")
def _normalize_stream_chunk_index(
raw_chunk_index: object,
*,
chunk_count: int,
current_base: int | None,
) -> tuple[int | None, int | None]:
try:
numeric_chunk_index = int(raw_chunk_index)
except Exception:
return None, current_base
if chunk_count <= 0:
return max(0, numeric_chunk_index), current_base
normalized_base = current_base
if normalized_base is None:
if numeric_chunk_index == 0:
normalized_base = 0
elif numeric_chunk_index == chunk_count:
normalized_base = 1
elif numeric_chunk_index == 1:
normalized_base = 1
else:
normalized_base = 0
normalized_chunk_index = numeric_chunk_index - normalized_base
if 0 <= normalized_chunk_index < chunk_count:
return normalized_chunk_index, normalized_base
if 0 <= numeric_chunk_index < chunk_count:
return numeric_chunk_index, 0
if 1 <= numeric_chunk_index <= chunk_count:
return numeric_chunk_index - 1, 1
return None, normalized_base
def _audio_to_wav_bytes(audio_array, sample_rate: int) -> bytes:
audio_np = np.asarray(audio_array, dtype=np.float32)
if audio_np.ndim == 1:
audio_np = audio_np[:, None]
elif audio_np.ndim == 2 and audio_np.shape[0] <= 8 and audio_np.shape[0] < audio_np.shape[1]:
audio_np = audio_np.T
elif audio_np.ndim != 2:
raise ValueError(f"Unsupported audio array shape: {audio_np.shape}")
audio_np = np.clip(audio_np, -1.0, 1.0)
audio_int16 = (audio_np * 32767.0).astype(np.int16)
buffer = io.BytesIO()
with wave.open(buffer, "wb") as wav_file:
wav_file.setnchannels(int(audio_int16.shape[1]))
wav_file.setsampwidth(2)
wav_file.setframerate(sample_rate)
wav_file.writeframes(audio_int16.tobytes())
buffer.seek(0)
return buffer.read()
def _audio_to_pcm16le_bytes(audio_array) -> bytes:
audio_np = np.asarray(audio_array, dtype=np.float32)
if audio_np.ndim == 1:
audio_np = audio_np[:, None]
elif audio_np.ndim == 2 and audio_np.shape[0] <= 8 and audio_np.shape[0] < audio_np.shape[1]:
audio_np = audio_np.T
elif audio_np.ndim != 2:
raise ValueError(f"Unsupported audio array shape: {audio_np.shape}")
audio_np = np.clip(audio_np, -1.0, 1.0)
audio_int16 = (audio_np * 32767.0).astype(np.int16)
return audio_int16.tobytes()
def _read_audio_file_base64(path_value: str | None) -> str:
path_text = str(path_value or "").strip()
if not path_text:
return ""
path = Path(path_text)
if not path.is_file():
return ""
try:
return base64.b64encode(path.read_bytes()).decode("ascii")
except Exception:
logging.warning("failed to read audio file for base64 response: %s", path, exc_info=True)
return ""
def _maybe_delete_file(path_value: str | None) -> None:
if not path_value:
return
try:
Path(path_value).unlink(missing_ok=True)
except Exception:
logging.warning("failed to remove temporary file: %s", path_value, exc_info=True)
def _coerce_bool(value: str | None, default: bool) -> bool:
if value is None:
return default
normalized = str(value).strip().lower()
if normalized in {"1", "true", "yes", "y", "on"}:
return True
if normalized in {"0", "false", "no", "n", "off"}:
return False
return default
def _sanitize_uploaded_prompt_filename(filename: str | None) -> str:
base_name = Path(str(filename or "")).name.strip()
if not base_name:
return "prompt_speech.wav"
return base_name
def _format_uploaded_prompt_display_name(filename: str | None) -> str:
return f"Uploaded: {_sanitize_uploaded_prompt_filename(filename)}"
async def _persist_uploaded_prompt_audio(upload: UploadFile | None) -> tuple[str | None, str | None]:
if upload is None:
return None, None
original_filename = _sanitize_uploaded_prompt_filename(upload.filename)
suffix = Path(original_filename).suffix
if not suffix or len(suffix) > 16:
suffix = ".wav"
PROMPT_UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
temp_path: str | None = None
bytes_written = 0
try:
with tempfile.NamedTemporaryFile(
mode="wb",
delete=False,
prefix="prompt-speech-",
suffix=suffix,
dir=str(PROMPT_UPLOAD_DIR),
) as handle:
temp_path = handle.name
while True:
chunk = await upload.read(1024 * 1024)
if not chunk:
break
handle.write(chunk)
bytes_written += len(chunk)
finally:
await upload.close()
if not temp_path or bytes_written <= 0:
_maybe_delete_file(temp_path)
raise ValueError("Uploaded prompt speech is empty.")
return temp_path, _format_uploaded_prompt_display_name(original_filename)
def _render_index_html(
*,
request: Request,
runtime: NanoTTSService,
demo_entries: list[DemoEntry],
warmup_status: str,
text_normalization_status: str,
) -> str:
base_path = request.scope.get("root_path", "").rstrip("/")
template = """
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>MOSS-TTS-Nano Demo</title>
<style>
:root {
color-scheme: light;
--bg: #eef1f7;
--bg-soft: #f7f8fc;
--panel: #ffffff;
--text: #1f2534;
--muted: #647089;
--line: #dbe2f0;
--line-strong: #cfd8ea;
--chip: #dfe5ff;
--chip-text: #4f63d8;
--accent: #6a6ef6;
--accent-strong: #565cea;
--accent-soft: rgba(106, 110, 246, 0.12);
--danger: #ba1f46;
--shadow: 0 14px 32px rgba(34, 47, 78, 0.06);
}
* {
box-sizing: border-box;
}
body {
margin: 0;
min-height: 100vh;
background:
radial-gradient(1100px 380px at 12% -10%, #ffffff 0%, transparent 70%),
linear-gradient(180deg, var(--bg-soft) 0%, var(--bg) 54%);
color: var(--text);
font-family: "Plus Jakarta Sans", "Noto Sans SC", "Segoe UI", sans-serif;
}
.page {
max-width: 1460px;
margin: 0 auto;
padding: 24px 26px 30px;
}
.hero {
margin-bottom: 12px;
}
.hero h1 {
margin: 0 0 10px;
font-size: 38px;
letter-spacing: -0.03em;
}
.hero .lead {
margin: 0 0 8px;
color: var(--muted);
font-size: 19px;
line-height: 1.55;
max-width: 980px;
}
.hero-points {
margin: 0 0 8px 20px;
padding: 0;
color: #33415f;
line-height: 1.6;
}
.hero-points strong {
color: #121826;
}
.build-note {
margin: 0;
color: #4f5d7c;
}
.top-tabs {
display: flex;
align-items: center;
gap: 22px;
margin-top: 14px;
border-bottom: 1px solid var(--line);
}
.top-tab {
border: 0;
background: transparent;
color: #4e5f89;
font-size: 15px;
font-weight: 500;
padding: 10px 0;
position: relative;
cursor: default;
}
.top-tab.active {
color: var(--accent-strong);
font-weight: 700;
}
.top-tab.active::after {
content: "";
position: absolute;
left: 0;
right: 0;
bottom: -1px;
height: 2px;
background: var(--accent-strong);
}
.top-tab:disabled {
opacity: 1;
}
.grid {
display: grid;
grid-template-columns: minmax(0, 1.08fr) minmax(320px, 0.92fr);
gap: 14px;
margin-top: 14px;
}
.panel {
background: var(--panel);
border: 1px solid var(--line);
border-radius: 12px;
padding: 12px;
box-shadow: var(--shadow);
}
.field {
margin-bottom: 11px;
}
.field > label[for],
.field > .field-tag {
display: inline-flex;
align-items: center;
gap: 6px;
margin-bottom: 7px;
font-size: 14px;
line-height: 1;
font-weight: 700;
color: var(--chip-text);
background: var(--chip);
border-radius: 6px;
padding: 5px 8px;
}
.field > label[for]::before,
.field > .field-tag::before {
content: "♫";
font-size: 11px;
opacity: 0.75;
}
.field > label:not([for]):not(.field-tag) {
display: inline-flex;
align-items: center;
gap: 8px;
margin-top: 2px;
color: #273554;
font-size: 14px;
font-weight: 500;
}
.field input,
.field textarea,
.field select {
width: 100%;
border: 1px solid var(--line);
border-radius: 8px;
padding: 10px 12px;
font-size: 14px;
color: var(--text);
background: #fff;
transition: border-color 140ms ease, box-shadow 140ms ease;
}
.field input:focus,
.field textarea:focus,
.field select:focus {
outline: 0;
border-color: #aeb9f7;
box-shadow: 0 0 0 3px rgba(106, 110, 246, 0.15);
}
.field textarea {
min-height: 108px;
resize: vertical;
}
#normalized-text-output {
min-height: 114px;
background: #fbfcff;
}
input[type="file"] {
border-style: dashed;
border-color: var(--line-strong);
padding: 54px 12px;
background: linear-gradient(180deg, #ffffff 0%, #f5f8ff 100%);
color: #4d5d83;
}
input[type="file"]::file-selector-button {
border: 0;
border-radius: 999px;
padding: 8px 12px;
margin-right: 10px;
background: #edf1ff;
color: var(--chip-text);
font-weight: 700;
cursor: pointer;
}
.prompt-audio-box {
border: 1px solid var(--line);
border-radius: 8px;
background: linear-gradient(180deg, #ffffff 0%, #f7f9ff 100%);
padding: 10px;
}
#prompt-audio-preview {
margin-top: 0;
}
#prompt-audio-upload[hidden],
#prompt-audio-preview[hidden] {
display: none;
}
.prompt-audio-actions {
display: flex;
gap: 8px;
margin-top: 8px;
flex-wrap: wrap;
}
.prompt-audio-actions button {
min-height: 34px;
font-size: 13px;
padding: 8px 12px;
}
.row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
details {
border: 1px solid var(--line);
border-radius: 10px;
padding: 10px 12px;
margin: 12px 0;
background: #f9fafe;
}
summary {
cursor: pointer;
font-weight: 600;
color: #2f3f65;
}
.buttons {
display: grid;
grid-template-columns: minmax(0, 1fr) auto auto;
gap: 10px;
margin-top: 12px;
}
button:not(.top-tab) {
border: 0;
border-radius: 8px;
padding: 10px 14px;
font-size: 14px;
font-weight: 700;
cursor: pointer;
background: linear-gradient(90deg, #6469f6 0%, #636ef8 50%, #5f61f0 100%);
color: #fff;
transition: transform 140ms ease, box-shadow 140ms ease, opacity 140ms ease;
}
button:not(.top-tab):hover {
transform: translateY(-1px);
box-shadow: 0 8px 16px rgba(97, 101, 242, 0.24);
}
#generate-btn {
width: 100%;
min-height: 42px;
}
button.secondary {
background: #edf1fb;
color: #44527a;
border: 1px solid var(--line-strong);
}
button:not(.top-tab):disabled {
opacity: 0.6;
cursor: wait;
transform: none;
box-shadow: none;
}
.status {
white-space: pre-wrap;
line-height: 1.5;
font-size: 14px;
color: var(--muted);
min-height: 52px;
border: 1px solid var(--line);
border-radius: 8px;
background: #fcfdff;
padding: 10px 12px;
}
.status.error {
color: var(--danger);
border-color: rgba(186, 31, 70, 0.28);
background: rgba(186, 31, 70, 0.06);
}
.meta {
font-size: 13px;
color: var(--muted);
margin-top: 7px;
line-height: 1.5;
}
.playback-script {
min-height: 108px;
display: flex;
flex-wrap: wrap;
align-content: flex-start;
gap: 10px;
padding: 12px;
border: 1px solid var(--line);
border-radius: 8px;
background: linear-gradient(180deg, #ffffff 0%, #f6f8fe 100%);
overflow: auto;
}
.playback-script.empty {
display: block;
color: var(--muted);
}
.playback-segment {
display: inline-flex;
align-items: center;
padding: 8px 11px;
border-radius: 10px;
border: 1px solid var(--line);
background: #ffffff;
color: #4a5c82;
line-height: 1.6;
transition: background-color 160ms ease, color 160ms ease, border-color 160ms ease, box-shadow 160ms ease, transform 160ms ease;
}
.playback-segment.played {
border-color: rgba(106, 110, 246, 0.24);
background: var(--accent-soft);
color: #424db6;
}
.playback-segment.active {
border-color: var(--accent-strong);
background: var(--accent);
color: #ffffff;
box-shadow: 0 8px 18px rgba(106, 110, 246, 0.32);
transform: translateY(-1px);
}
audio {
width: 100%;