-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
3884 lines (3390 loc) · 136 KB
/
Copy pathserver.py
File metadata and controls
3884 lines (3390 loc) · 136 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
"""
server.py — Kokoro TTS 本地 API 服务器
启动后在 127.0.0.1:5000 暴露 TTS 接口,
接收英文文本,返回高质量 WAV 音频流。
用法:
python server.py
或双击 start.bat
"""
import asyncio
import html as html_module
import io
import json
import math
import os
import re
import sys
import threading
import time
import warnings
from dataclasses import dataclass
from pathlib import Path
from typing import Literal, Optional
from urllib import error as urllib_error
from urllib import request as urllib_request
# Suppress harmless PyTorch / HuggingFace warnings
warnings.filterwarnings("ignore", message="dropout option adds dropout")
warnings.filterwarnings("ignore", message=".*weight_norm.*deprecated.*")
os.environ["HF_HUB_DISABLE_SYMLINKS_WARNING"] = "1"
import numpy as np
import soundfile as sf
try:
import torch
except ImportError:
torch = None
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse, Response, StreamingResponse
from pydantic import BaseModel, ConfigDict, Field, field_validator
from audio_encoding import (
AudioEncodingError,
WebMOpusEncoder,
encode_ogg_opus,
validate_ffmpeg,
)
from document_formula import (
canonicalize_latex_interchange,
FormulaConversionError,
GeneratedFormulaFragment,
NativeToLatexResult,
PandocUnavailableError,
generate_formula_fragment,
native_formula_to_latex,
pandoc_health,
)
from tts_catalog import (
AVAILABLE_VOICES,
CATALOG as TTS_CATALOG,
DEFAULT_SPEED as CATALOG_DEFAULT_SPEED,
DEFAULT_VOICE,
SPEEDS,
VOICE_GROUPS,
VOICE_LANG_CODES,
)
# ════════════════════════════════════════════════════════════════
# 配置区(按需修改)
# ════════════════════════════════════════════════════════════════
HOST = os.environ.get("KOKORO_HOST", "127.0.0.1")
PORT = int(os.environ.get("KOKORO_PORT", "5000"))
VOICE = os.environ.get("KOKORO_VOICE", DEFAULT_VOICE)
DEFAULT_SPEED = float(os.environ.get("KOKORO_SPEED", str(CATALOG_DEFAULT_SPEED)))
# 推理设备:auto(自动检测)、cuda、cpu
DEVICE = os.environ.get("KOKORO_DEVICE", "auto")
SAMPLE_RATE = 24000
SEGMENT_SILENCE_MS = int(os.environ.get("KOKORO_SEGMENT_SILENCE_MS", "0"))
FADE_MS = int(os.environ.get("KOKORO_FADE_MS", "0"))
WARMUP_ENABLED = os.environ.get("KOKORO_WARMUP", "1") != "0"
SUPPORTED_AUDIO_FORMATS = {"wav", "ogg"}
STREAM_CHUNK_BYTES = 16384
OLLAMA_BASE_URL = os.environ.get("OLLAMA_BASE_URL", "http://127.0.0.1:11434").rstrip("/")
OLLAMA_TRANSLATE_MODEL = os.environ.get("OLLAMA_TRANSLATE_MODEL", "translategemma:4b")
OLLAMA_FORMULA_MODEL = os.environ.get("OLLAMA_FORMULA_MODEL", "translategemma:4b")
OLLAMA_READ_MODEL = os.environ.get("OLLAMA_READ_MODEL", "translategemma:4b")
OLLAMA_TRANSLATE_TIMEOUT = float(os.environ.get("OLLAMA_TRANSLATE_TIMEOUT", "90"))
OLLAMA_KEEP_ALIVE_PIN_VALUE = os.environ.get("OLLAMA_KEEP_ALIVE_PIN_VALUE", "-1m")
MATH_GLOSSARY_FILE = Path(__file__).resolve().parent / "config" / "math_glossary.json"
PINNED_OLLAMA_MODELS: set[str] = set()
_GLOSSARY_SYMBOL_ALIASES = {
"double_arrow": "right_double_arrow",
"tilde": "tilde_accent",
}
_GLOSSARY_CANDIDATE_ALIASES = {
("right_arrow", "mapping"): "function_type",
("right_arrow", "derives"): "informal_derivation",
("right_arrow", "data_construction"): "informal_derivation",
("right_arrow", "points_to"): "literal",
("mapsto", "mapping"): "element_mapping",
("equals", "defined_as"): "definition_by_context",
("tuple", "tuple"): "ordered_tuple",
("sqrt", "sqrt"): "square_root",
}
@dataclass(frozen=True)
class OllamaSource:
id: str
name: str
base_url: str
remote: bool = False
@dataclass(frozen=True)
class OllamaModelRef:
value: str
model: str
source: OllamaSource
@dataclass(frozen=True)
class OllamaSourceState:
source: OllamaSource
reachable: bool
available_models: list[str]
eligible_models: list[str]
running_models: list[str]
models: list[dict]
error_code: Optional[str] = None
def _local_ollama_source() -> OllamaSource:
return OllamaSource("local", "Local Ollama", OLLAMA_BASE_URL, False)
def _load_ollama_sources_from_env(raw: Optional[str] = None) -> dict[str, OllamaSource]:
sources = {"local": _local_ollama_source()}
raw_value = os.environ.get("KOKORO_OLLAMA_SOURCES", "") if raw is None else raw
if not raw_value:
return sources
try:
items = json.loads(raw_value)
except json.JSONDecodeError:
return sources
if not isinstance(items, list):
return sources
for item in items:
if not isinstance(item, dict):
continue
source_id = str(item.get("id") or "").strip()
name = str(item.get("name") or source_id).strip()
base_url = str(item.get("base_url") or "").strip().rstrip("/")
if not source_id or source_id == "local" or not base_url:
continue
if any(ch.isspace() for ch in source_id):
continue
sources[source_id] = OllamaSource(source_id, name or source_id, base_url, True)
return sources
OLLAMA_SOURCES = _load_ollama_sources_from_env()
def _model_value_for_source(source: OllamaSource, model: str) -> str:
return model if source.id == "local" else f"remote:{source.id}:{model}"
def _clean_ollama_model_name(value: Optional[str]) -> str:
selected = (value or "").strip()
if selected.startswith("remote:"):
parts = selected.split(":", 2)
if len(parts) == 3:
return parts[2].strip()
return selected
def _resolve_ollama_model_ref(value: Optional[str]) -> OllamaModelRef:
selected = (value or OLLAMA_TRANSLATE_MODEL).strip() or OLLAMA_TRANSLATE_MODEL
if selected.startswith("remote:"):
parts = selected.split(":", 2)
if len(parts) != 3 or not parts[1] or not parts[2]:
raise RuntimeError("Invalid remote Ollama model reference")
source = OLLAMA_SOURCES.get(parts[1])
if source is None:
raise RuntimeError("Remote Ollama source is not configured")
return OllamaModelRef(
_model_value_for_source(source, parts[2]),
parts[2],
source,
)
source = OLLAMA_SOURCES["local"]
return OllamaModelRef(selected, selected, source)
def _call_ollama_source_json(source: OllamaSource, path: str):
if source.id == "local":
return _call_ollama_json(path)
return _call_ollama_json(path, base_url=source.base_url)
def _ollama_model_items(payload) -> list[dict]:
if not isinstance(payload, dict):
return []
return [item for item in payload.get("models", []) if isinstance(item, dict)]
def _ollama_model_usable_for_translation(item: dict) -> bool:
raw_capabilities = item.get("capabilities")
capabilities = {
str(capability).strip().lower()
for capability in raw_capabilities
if str(capability).strip()
} if isinstance(raw_capabilities, (list, tuple, set)) else set()
if capabilities & {"completion", "generate", "generation", "chat"}:
return True
if capabilities & {"embedding", "embeddings", "rerank", "reranking"}:
return False
name = str(item.get("name") or item.get("model") or "").strip().lower()
tokens = {token for token in re.split(r"[-_.:/]+", name) if token}
if tokens & {"embed", "embedding", "embeddings", "rerank", "reranker", "reranking"}:
return False
return not name.startswith(("bge-", "bge_", "all-minilm", "nomic-embed"))
def _inspect_ollama_source(source: OllamaSource) -> OllamaSourceState:
try:
tag_payload = _call_ollama_source_json(source, "/api/tags")
except Exception:
return OllamaSourceState(
source=source,
reachable=False,
available_models=[],
eligible_models=[],
running_models=[],
models=[],
error_code="unreachable",
)
error_code = None
try:
running_payload = _call_ollama_source_json(source, "/api/ps")
running_models = _ollama_model_names(running_payload)
except Exception:
running_models = []
error_code = "running_state_unavailable"
available_models: list[str] = []
eligible_models: list[str] = []
model_states: list[dict] = []
running_set = set(running_models)
for item in _ollama_model_items(tag_payload):
name = item.get("name") or item.get("model")
if not isinstance(name, str) or not name or name in available_models:
continue
usable = _ollama_model_usable_for_translation(item)
value = _model_value_for_source(source, name)
available_models.append(name)
if usable:
eligible_models.append(name)
model_states.append(
{
"value": value,
"name": name,
"running": name in running_set,
"pinned": value in PINNED_OLLAMA_MODELS,
"usable_for_translation": usable,
}
)
return OllamaSourceState(
source=source,
reachable=True,
available_models=available_models,
eligible_models=eligible_models,
running_models=running_models,
models=model_states,
error_code=error_code,
)
def _collect_ollama_source_states() -> dict[str, OllamaSourceState]:
return {
source.id: _inspect_ollama_source(source)
for source in OLLAMA_SOURCES.values()
}
def _collect_ollama_model_options(
states: Optional[dict[str, OllamaSourceState]] = None,
) -> list[dict[str, str]]:
options: list[dict[str, str]] = []
source_states = states or _collect_ollama_source_states()
for source in OLLAMA_SOURCES.values():
state = source_states.get(source.id)
if state is None or not state.reachable:
continue
for model in state.eligible_models:
value = _model_value_for_source(source, model)
options.append(
{
"value": value,
"label": f"{source.name} / {model}",
"source": source.id,
"source_name": source.name,
"model": model,
}
)
return options
if VOICE not in AVAILABLE_VOICES:
raise ValueError(f"Unsupported KOKORO_VOICE: {VOICE}")
if not math.isfinite(DEFAULT_SPEED) or not 0.5 <= DEFAULT_SPEED <= 2.0:
raise ValueError("KOKORO_SPEED must be a finite number between 0.5 and 2.0")
if SEGMENT_SILENCE_MS < 0 or FADE_MS < 0:
raise ValueError("Audio timing values cannot be negative")
if OLLAMA_TRANSLATE_TIMEOUT <= 0:
raise ValueError("OLLAMA_TRANSLATE_TIMEOUT must be positive")
def _load_math_glossary() -> dict:
try:
with MATH_GLOSSARY_FILE.open("r", encoding="utf-8") as f:
data = json.load(f)
except FileNotFoundError:
return {"version": 0, "symbols": []}
if not isinstance(data, dict):
raise ValueError("math_glossary.json must contain an object")
symbols = data.get("symbols", [])
if not isinstance(symbols, list):
raise ValueError("math_glossary.json symbols must be a list")
for item in symbols:
if not isinstance(item, dict) or not isinstance(item.get("id"), str):
raise ValueError("Each math glossary symbol must have an id")
return data
MATH_GLOSSARY = _load_math_glossary()
def _glossary_symbol(symbol_id: str) -> dict:
for item in MATH_GLOSSARY.get("symbols", []):
if item.get("id") == symbol_id:
return item
alias = _GLOSSARY_SYMBOL_ALIASES.get(symbol_id)
if alias:
for item in MATH_GLOSSARY.get("symbols", []):
if item.get("id") == alias:
return item
return {}
def _glossary_candidate(symbol_id: str, candidate_id: str | None = None, lang: str = "zh") -> str:
symbol = _glossary_symbol(symbol_id)
if not symbol:
return ""
selected_id = candidate_id or symbol.get("default_candidate") or symbol.get("semantic_default")
for candidate in symbol.get("candidates", []):
if candidate.get("id") == selected_id:
return str(candidate.get(lang) or "")
alias = _GLOSSARY_CANDIDATE_ALIASES.get((symbol.get("id", symbol_id), selected_id or ""))
if alias:
for candidate in symbol.get("candidates", []):
if candidate.get("id") == alias:
return str(candidate.get(lang) or "")
if not candidate_id:
read_aloud = symbol.get("read_aloud") or {}
default_key = "default_zh" if lang == "zh" else "default_en"
if read_aloud.get(default_key):
return str(read_aloud[default_key])
direct = symbol.get("direct", {})
return str(direct.get(lang) or "")
def _glossary_direct(symbol_id: str, lang: str = "zh") -> str:
symbol = _glossary_symbol(symbol_id)
direct = symbol.get("direct", {}) if symbol else {}
return str(direct.get(lang) or "")
def _math_glossary_prompt(lang: str = "zh", max_symbols: int = 40) -> str:
lines = [
"Math glossary. Choose the reading that best fits the formula and nearby context; use the direct reading when semantics are unclear.",
]
for item in MATH_GLOSSARY.get("symbols", [])[:max_symbols]:
forms = ", ".join(item.get("forms", [])[:4])
direct = (item.get("direct") or {}).get(lang, "")
read_aloud = item.get("read_aloud") or {}
default_key = "default_zh" if lang == "zh" else "default_en"
default = read_aloud.get(default_key) or _glossary_candidate(item.get("id", ""), None, lang)
candidate_parts = []
for candidate in item.get("candidates", [])[:8]:
reading = candidate.get(lang)
if reading:
candidate_parts.append(f"{candidate.get('id')}={reading}")
candidates = "; ".join(candidate_parts)
category = item.get("category", "")
label = f"{category}; " if category else ""
lines.append(f"- {forms}: {label}direct={direct}; default={default}; candidates={candidates}")
return "\n".join(lines)
# ════════════════════════════════════════════════════════════════
# 全局变量
# ════════════════════════════════════════════════════════════════
pipeline = None
british_pipeline = None
inference_lock = asyncio.Lock()
_tts_model_load_lock = threading.Lock()
actual_device = None
def resolve_device(device_cfg: str) -> str:
"""解析设备配置。"""
if device_cfg == "auto":
return "cuda" if torch and torch.cuda.is_available() else "cpu"
return device_cfg
def _tts_model_is_loaded() -> bool:
return pipeline is not None and british_pipeline is not None
def _load_tts_model() -> None:
"""Load and warm the local Kokoro pipelines without publishing partial state."""
global pipeline, british_pipeline, actual_device
if torch is None:
raise RuntimeError("PyTorch is required to start the TTS model")
selected_device = resolve_device(DEVICE)
print()
print("=" * 60)
print("[LOADING] Kokoro TTS model...")
print(f" Device: {selected_device}")
if selected_device == "cuda":
gpu_name = torch.cuda.get_device_name(0)
gpu_mem = torch.cuda.get_device_properties(0).total_memory / (1024 ** 3)
print(f" GPU: {gpu_name} ({gpu_mem:.1f} GB)")
print(f" Default voice: {VOICE}")
print("=" * 60)
print()
t0 = time.time()
try:
from kokoro import KPipeline
loaded_pipeline = KPipeline(
lang_code="a",
repo_id="hexgrad/Kokoro-82M",
device=selected_device,
)
loaded_british_pipeline = KPipeline(
lang_code="b",
repo_id="hexgrad/Kokoro-82M",
model=loaded_pipeline.model,
device=selected_device,
)
if WARMUP_ENABLED:
print("[WARMUP] Running initial inference...")
warmup_started = time.time()
warmup_pipeline = (
loaded_british_pipeline
if VOICE_LANG_CODES[VOICE] == "b"
else loaded_pipeline
)
_run_pipeline_inference(warmup_pipeline, "Hello.", VOICE, DEFAULT_SPEED)
print(f"[WARMUP] Done in {time.time() - warmup_started:.2f}s")
except ImportError:
print("[ERROR] Cannot import kokoro. Please install: pip install kokoro>=0.9.4")
raise
except Exception as error:
print(f"[ERROR] Model loading failed: {error}")
raise
actual_device = selected_device
pipeline = loaded_pipeline
british_pipeline = loaded_british_pipeline
print()
print("=" * 60)
print(f"[OK] Model loaded in {time.time() - t0:.1f}s")
print("=" * 60)
print()
def _ensure_tts_model_loaded() -> None:
if _tts_model_is_loaded():
return
with _tts_model_load_lock:
if _tts_model_is_loaded():
return
_load_tts_model()
# ════════════════════════════════════════════════════════════════
# 应用生命周期
# ════════════════════════════════════════════════════════════════
def _start_watchdog():
tray_pid_str = os.environ.get("KOKORO_TRAY_PID")
if not tray_pid_str:
return
try:
tray_pid = int(tray_pid_str)
except ValueError:
return
def watchdog_loop():
import ctypes
kernel32 = ctypes.windll.kernel32
PROCESS_QUERY_INFORMATION = 0x0400
while True:
time.sleep(5)
h_process = kernel32.OpenProcess(PROCESS_QUERY_INFORMATION, False, tray_pid)
if not h_process:
print(f"\\n[WATCHDOG] Parent tray process {tray_pid} is dead. Exiting server.")
os._exit(0)
else:
kernel32.CloseHandle(h_process)
t = threading.Thread(target=watchdog_loop, daemon=True)
t.start()
print(f"[WATCHDOG] Monitoring parent process PID: {tray_pid}")
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Prepare the API; load the local TTS model only when TTS is requested."""
global pipeline, british_pipeline, actual_device
_start_watchdog()
validate_ffmpeg()
print()
print("=" * 60)
print(f"[READY] API server: http://{HOST}:{PORT}")
print("[TTS] Kokoro model will load on the first TTS request")
print(f"[TEST] Page: http://{HOST}:{PORT}/")
print(f"[HEALTH] Check: http://{HOST}:{PORT}/health")
print("=" * 60)
print()
try:
yield
finally:
loaded_device = actual_device
if _tts_model_is_loaded():
print("[STOP] Releasing model resources...")
with _tts_model_load_lock:
pipeline = None
british_pipeline = None
actual_device = None
if loaded_device == "cuda" and torch:
torch.cuda.empty_cache()
# ════════════════════════════════════════════════════════════════
# FastAPI 应用
# ════════════════════════════════════════════════════════════════
app = FastAPI(
title="Kokoro TTS 本地服务",
description="本地运行的高质量英文 TTS 服务(Kokoro 82M)",
version="1.7.20",
lifespan=lifespan,
)
# CORS — 允许来自浏览器任意页面的请求
app.add_middleware(
CORSMiddleware,
allow_origins=[
f"http://{HOST}:{PORT}",
f"http://localhost:{PORT}",
],
allow_credentials=False,
allow_methods=["GET", "POST"],
allow_headers=["Content-Type"],
)
# ════════════════════════════════════════════════════════════════
# 数据模型
# ════════════════════════════════════════════════════════════════
class TTSRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
text: str = Field(max_length=10000)
voice: Optional[str] = None
speed: Optional[float] = Field(default=DEFAULT_SPEED, ge=0.5, le=2.0)
@field_validator("voice")
@classmethod
def validate_voice(cls, value):
if value is not None and value not in AVAILABLE_VOICES:
raise ValueError(f"不支持的声音:{value}")
return value
# ════════════════════════════════════════════════════════════════
# 推理逻辑
# ════════════════════════════════════════════════════════════════
class TranslateRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
text: str = Field(max_length=12000)
context: Optional[str] = Field(default=None, max_length=12000)
model: Optional[str] = Field(default=None, max_length=120)
target_language: Optional[str] = Field(default="Simplified Chinese", max_length=80)
@field_validator("model")
@classmethod
def validate_model(cls, value):
if value is None:
return value
model = value.strip()
if not model:
raise ValueError("model cannot be blank")
if any(ch.isspace() for ch in model):
raise ValueError("model cannot contain whitespace")
return model
@field_validator("target_language")
@classmethod
def validate_target_language(cls, value):
if value is None:
return "Simplified Chinese"
target_language = value.strip()
if not target_language:
raise ValueError("target_language cannot be blank")
return target_language
class TranslateResponse(BaseModel):
text: str
translated_text: str
model: str
target_language: str
elapsed: float
class OllamaModelKeepAliveRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
model: str = Field(max_length=120)
keep_alive: str | int | float = Field(default=OLLAMA_KEEP_ALIVE_PIN_VALUE)
@field_validator("model")
@classmethod
def validate_model(cls, value):
model = value.strip()
if not model:
raise ValueError("model cannot be blank")
if any(ch.isspace() for ch in model):
raise ValueError("model cannot contain whitespace")
return model
@field_validator("keep_alive")
@classmethod
def validate_keep_alive(cls, value):
if isinstance(value, bool):
raise ValueError("keep_alive cannot be boolean")
if isinstance(value, (int, float)):
if not math.isfinite(value):
raise ValueError("keep_alive must be finite")
return value
cleaned = str(value).strip()
if not cleaned:
raise ValueError("keep_alive cannot be blank")
if re.fullmatch(r"-?\d+", cleaned):
return int(cleaned)
if re.fullmatch(r"-?\d+\.\d+", cleaned):
return float(cleaned)
if not re.fullmatch(r"-?\d+(?:\.\d+)?(?:ms|s|m|h)", cleaned):
raise ValueError("keep_alive must be a duration like -1, 30m, 8h, or 0")
return cleaned
class OllamaModelUnloadRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
model: str = Field(max_length=120)
@field_validator("model")
@classmethod
def validate_model(cls, value):
model = value.strip()
if not model:
raise ValueError("model cannot be blank")
if any(ch.isspace() for ch in model):
raise ValueError("model cannot contain whitespace")
return model
class OllamaModelKeepAliveResponse(BaseModel):
status: str
model: str
keep_alive: str | int | float
model_running: bool
model_pinned: bool
elapsed: float
done_reason: Optional[str] = None
class ReadPrepareRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
text: str = Field(max_length=12000)
context: Optional[str] = Field(default=None, max_length=12000)
model: Optional[str] = Field(default=None, max_length=120)
@field_validator("model")
@classmethod
def validate_model(cls, value):
if value is None:
return value
model = value.strip()
if not model:
raise ValueError("model cannot be blank")
if any(ch.isspace() for ch in model):
raise ValueError("model cannot contain whitespace")
return model
class ReadPrepareResponse(BaseModel):
text: str
prepared_text: str
model: str
elapsed: float
class FormulaVerbalizeRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
formulas: list[str] = Field(min_length=1, max_length=20)
context: Optional[str] = Field(default=None, max_length=12000)
model: Optional[str] = Field(default=None, max_length=120)
@field_validator("formulas")
@classmethod
def validate_formulas(cls, value):
cleaned = []
for formula in value:
if not isinstance(formula, str):
raise ValueError("formula must be text")
formula = formula.strip()
if not formula:
raise ValueError("formula cannot be blank")
if len(formula) > 1000:
raise ValueError("formula is too long")
cleaned.append(formula)
return cleaned
@field_validator("model")
@classmethod
def validate_model(cls, value):
if value is None:
return value
model = value.strip()
if not model:
raise ValueError("model cannot be blank")
if any(ch.isspace() for ch in model):
raise ValueError("model cannot contain whitespace")
return model
class FormulaVerbalizeResponse(BaseModel):
verbalizations: list[str]
model: str
elapsed: float
class LatexFormulaHealthResponse(BaseModel):
available: bool
version: Optional[str] = None
interchange_format: str = "latex"
native_format: str = "docx-omml"
class LatexFormulaFragmentRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
text: str = Field(min_length=1, max_length=50000)
class LatexFormulaFragmentResponse(BaseModel):
canonical_latex: str
docx_base64: str
local_path: str
filename: str
formula_count: int
inline_formula_count: int
display_formula_count: int
native_formula_count: int
native_display_formula_count: int
warnings: list[str] = Field(default_factory=list)
generator: str
generator_version: str
expires_in_seconds: int
class NativeFormulaToLatexRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
source_format: Literal["docx-base64", "docx-local-path", "flat-opc"]
content: str = Field(min_length=1, max_length=12000000)
class NativeFormulaToLatexResponse(BaseModel):
latex: str
formula_count: int
inline_formula_count: int
display_formula_count: int
warnings: list[str] = Field(default_factory=list)
generator: str
generator_version: str
class PdfSelectionToLatexRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
text: str = Field(min_length=1, max_length=50000)
html: str = Field(default="", max_length=2000000)
model: str = Field(min_length=1, max_length=120)
@field_validator("model")
@classmethod
def validate_model(cls, value):
model = value.strip()
if not model:
raise ValueError("model cannot be blank")
if any(ch.isspace() for ch in model):
raise ValueError("model cannot contain whitespace")
return model
class PdfSelectionToLatexResponse(BaseModel):
latex: str
formula_count: int
inline_formula_count: int
display_formula_count: int
warnings: list[str] = Field(default_factory=list)
model: str
recognizer: str = "ollama-pdf-selection"
elapsed: float
class OllamaModelOption(BaseModel):
value: str
label: str
source: str
source_name: str
model: str
class OllamaSourceModelStatus(BaseModel):
value: str
name: str
running: bool
pinned: bool
usable_for_translation: bool
class OllamaSourceStatus(BaseModel):
id: str
name: str
kind: str
configured: bool
reachable: bool
error_code: Optional[str] = None
models: list[OllamaSourceModelStatus] = Field(default_factory=list)
class TranslateHealthResponse(BaseModel):
status: str
ollama_reachable: bool
model: str
model_available: bool
model_running: bool
model_pinned: bool = False
available_models: list[str]
running_models: list[str]
source: str = "local"
source_name: str = "Local Ollama"
available_model_options: list[OllamaModelOption] = Field(default_factory=list)
sources: list[OllamaSourceStatus] = Field(default_factory=list)
error: Optional[str] = None
def _apply_fade(audio: np.ndarray, sample_rate: int, fade_ms: int) -> np.ndarray:
"""Apply a short fade at both ends without mutating the input."""
result = np.asarray(audio, dtype=np.float32).reshape(-1).copy()
fade_samples = min(len(result) // 2, int(sample_rate * fade_ms / 1000))
if fade_samples <= 0:
return result
result[:fade_samples] *= np.linspace(0.0, 1.0, fade_samples, dtype=np.float32)
result[-fade_samples:] *= np.linspace(1.0, 0.0, fade_samples, dtype=np.float32)
return result
def _combine_audio_segments(
audio_segments,
sample_rate: int = SAMPLE_RATE,
silence_ms: int = SEGMENT_SILENCE_MS,
fade_ms: int = FADE_MS,
) -> np.ndarray:
"""Join model segments with silence and smooth the final boundaries."""
normalized = [
np.asarray(segment, dtype=np.float32).reshape(-1)
for segment in audio_segments
if segment is not None and np.asarray(segment).size > 0
]
if not normalized:
raise RuntimeError("模型未生成任何音频")
silence_samples = max(0, int(sample_rate * silence_ms / 1000))
if len(normalized) > 1 and silence_samples:
silence = np.zeros(silence_samples, dtype=np.float32)
parts = []
for index, segment in enumerate(normalized):
parts.append(segment)
if index < len(normalized) - 1:
parts.append(silence)
full_audio = np.concatenate(parts)
else:
full_audio = np.concatenate(normalized)
return _apply_fade(full_audio, sample_rate, fade_ms)
def _run_pipeline_inference(selected_pipeline, text: str, voice: str, speed: float):
if selected_pipeline is None:
raise RuntimeError("模型尚未就绪")
# 使用 pipeline 生成音频
# KPipeline 会自动处理长文本分块
audio_segments = []
for _, _, audio in selected_pipeline(text, voice=voice, speed=speed):
if audio is not None:
audio_segments.append(audio.numpy() if hasattr(audio, 'numpy') else audio)
return _combine_audio_segments(audio_segments), SAMPLE_RATE
def _run_inference(text: str, voice: str, speed: float):
"""同步执行 Kokoro TTS 推理(在线程池中运行)。"""
return _run_pipeline_inference(
_select_pipeline_for_voice(voice),
text,
voice,
speed,
)
def _select_pipeline_for_voice(voice: str):
return british_pipeline if VOICE_LANG_CODES[voice] == "b" else pipeline
def _select_audio_format(format_query: Optional[str], accept: Optional[str]) -> str:
if format_query is not None:
normalized = format_query.lower()
if normalized not in SUPPORTED_AUDIO_FORMATS:
raise HTTPException(status_code=406, detail="不支持的音频格式")
return normalized
normalized_accept = (accept or "*/*").lower()
if "audio/ogg" in normalized_accept:
return "ogg"
if (
"audio/wav" in normalized_accept
or "audio/*" in normalized_accept
or "*/*" in normalized_accept
):
return "wav"
raise HTTPException(status_code=406, detail="不支持的音频格式")
def _audio_response(wav: np.ndarray, sample_rate: int, audio_format: str) -> Response:
if audio_format == "ogg":
content = encode_ogg_opus(wav, sample_rate)
return Response(
content=content,
media_type="audio/ogg",
headers={"Content-Disposition": 'inline; filename="speech.ogg"'},
)