feat: 增加在线语音 SDK 和音色管理后台,完善引擎适配
This commit is contained in:
1 parent
1856de97bc
commit
a532ba4e0f
71 files changed
+3189
-472
No files matched your search
+50
-5
@@ -34,6 +34,8 @@ Go + cgo + sherpa-onnx **2.0.1**,与 `android-engine`(`libs/sherpa-onnx-2.0.
|
||||
| `TTS_THREADS` | `2` | ONNX Runtime 线程数 |
|
||||
| `TTS_QUEUE` | `2` | 除正在合成外允许排队的请求数,超出返回 429 |
|
||||
| `TTS_MAX_TEXT` | `300` | 单次文本字符上限 |
|
||||
| `TTS_REQUIRE_AUTH` | `0` | 设为 `1` 时令牌为空会拒绝启动;生产清单已开启 |
|
||||
| `TTS_API_TOKEN` | 空 | 本地兼容模式;生产必须通过 Secret 配置 Bearer token |
|
||||
| `TTS_PRELOAD` | `1` | 启动时加载默认语音包(健康检查通过即热) |
|
||||
|
||||
## 本地运行(Windows 开发机)
|
||||
@@ -75,7 +77,7 @@ tar -czf dist/tts-server-linux-amd64.tgz -C dist tts-server lib
|
||||
|
||||
## Docker 镜像与 k3s 部署
|
||||
|
||||
服务器无法访问 Docker Hub 且未装 Go(同 `youlai-boot-ttstd` 的约束),镜像在节点上用预编译产物构建(`Dockerfile.runtime`,基础镜像 `debian:bookworm-slim`):
|
||||
服务器无法访问 Docker Hub 且未装 Go(同 `youlai-boot-ttstd` 的约束),镜像在节点上用预编译产物构建(`Dockerfile.runtime`,基础镜像 `debian:bookworm-slim`)。完整部署记录(首次上线、nginx/证书、升级回滚、运维)见 [`../docs/deploy.md`](../docs/deploy.md)。
|
||||
|
||||
```bash
|
||||
cd TtsSpeaker/server
|
||||
@@ -130,7 +132,7 @@ done < phrases.txt
|
||||
## 与设备端一致性
|
||||
|
||||
- 同一 sherpa-onnx 2.0.1、同一语音包版本(`manifest.json` 的 `version` 强制两端一致)。
|
||||
- 同一推理配置:VITS + `ruleFsts`(phone/date/number)、`maxNumSentences=1`、`silenceScale=0.2`、generation `silenceScale=0`、`numSteps=5`、`numThreads=2`。
|
||||
- 同一推理配置:VITS + `ruleFsts`(phone/date/number)、`maxNumSentences=1`、`silenceScale=0.2`、generation `silenceScale=0.2`、`numSteps=5`、`numThreads=2`。
|
||||
- 同一变调算法(`internal/tts/pitch.go` 逐行移植 `PitchShifter.java`,常数 1024/512/512/128 不变)。
|
||||
- 同一 PCM 转换规则(clamp 到 [-1,1]、乘 32767、四舍五入)。
|
||||
- 设备端若使用 int8 量化模型,需与服务器模型做 AB 试听,主观一致后才能上线。
|
||||
@@ -162,7 +164,50 @@ done < phrases.txt
|
||||
## 已知限制
|
||||
|
||||
- 仅 WAV;MP3 待后续需要时再加编码依赖。
|
||||
- 无鉴权,按内网服务使用。
|
||||
- 缓存不做淘汰,随固定文案数量增长;可定期清理 `/cache`。
|
||||
- 设置 `TTS_API_TOKEN` 后,`POST /tts` 必须带 `Authorization: Bearer <token>`;健康检查与音色清单仍可匿名读取。生产清单要求 `tts-server-auth/token` Secret,未创建时 Pod 不会启动。
|
||||
- 缓存上限 256MiB,按写入时间淘汰旧 WAV;命中通过文件流发送。Pod 重建仍会丢失 emptyDir 缓存。
|
||||
- 同时只常驻一个语音包,切换语音需重新加载模型(秒级)。
|
||||
- 请求排队上限由 `TTS_QUEUE` 控制;默认 1 路合成 + 2 路排队。
|
||||
- 请求排队上限由 `TTS_QUEUE` 控制;默认 1 路合成 + 2 路排队。
|
||||
## 本次兼容修复后的发布要求
|
||||
|
||||
- 升级前按 `android-engine/voices.example/manifest.json` 更新服务器清单:`sha256` 必填;`files` 可记录 tokens、lexicon、FST 的 SHA256。启动时校验,不修改任何模型权重。
|
||||
- 在发布前创建 `tts-server-auth` Secret,键名为 `token`,通过受控凭据渠道设置随机令牌。调用端与预生成脚本需携带 Authorization 头;不要把令牌提交到仓库。
|
||||
- 请求排队与合成共用 25 秒截止时间;取消在取得执行权、模型加载完成及原生音频回调处检查,不能抢占单次原生推理调用。
|
||||
- 缓存命中不占推理队列;排队完成后复查缓存,避免重复合成。DSP 更新已经更换缓存算法标识。
|
||||
- `GOMEMLIMIT=64MiB` 仅约束 Go 管理的内存,不包含 ONNX 原生分配;512Mi 容器上限不代表已通过峰值 300MB 的验收。
|
||||
- 普通话和方言仍需同步部署同版本包并试听,新增方言不在此次代码修复中替代模型与许可验收。
|
||||
|
||||
### 原生模型回归测试(Windows)
|
||||
|
||||
`go test ./internal/... -race` 验证不依赖原生库的逻辑。端到端测试位于 `main_test.go`,通过 `TTS_TEST_VOICES` 指定语音包;测试程序需与上述三个 sherpa DLL 放在同一目录,避免 PATH 中其他版本的 ONNX Runtime 冲突:
|
||||
|
||||
```powershell
|
||||
$env:TTS_TEST_VOICES='../models/voices'
|
||||
go test -c -o bin/tts-tests.exe .
|
||||
& ./bin/tts-tests.exe
|
||||
```
|
||||
|
||||
## 网页音色管理
|
||||
|
||||
入口 `/admin/`,由 Go 服务嵌入提供,无额外 Node 服务或前端依赖。支持音色列表、语速/音调试听、默认音色切换和 ZIP 语音包导入。
|
||||
|
||||
管理鉴权独立使用 `TTS_ADMIN_TOKEN`,必须与 `TTS_API_TOKEN` 不同;未设置时管理 API 返回 503。生产通过 `youlai/tts-server-admin` Secret 的 token 键注入。管理页面不保存浏览器令牌,刷新后需重新登录。移动端合成令牌不能调用管理 API,管理令牌也不能代替移动端令牌调用 `/tts`。
|
||||
|
||||
| 方法 | 路径 | 功能 |
|
||||
|---|---|---|
|
||||
| GET | `/admin/api/voices` | 管理音色列表 |
|
||||
| POST | `/admin/api/preview` | 管理员试听,返回 WAV |
|
||||
| POST | `/admin/api/default` | JSON `{"voice":"音色名称"}`,持久化默认音色 |
|
||||
| POST | `/admin/api/import` | body 为 ZIP 文件,Content-Type application/zip |
|
||||
|
||||
语音包 ZIP 的根目录必须是 manifest.json,与 Android 语音包格式一致,包含 version、default、voices,模型 sha256 必填;可通过 files 登记前端资源 SHA256。仅导入名称不重复的新音色,不覆盖现有模型。导入会保留已有默认音色并采用上传清单的版本;离线端的语音包需另行同步。管理页不会验证模型许可或代替人工试听验收,请上传已确认兼容 sherpa-onnx 2.0.1 的 Piper/VITS 模型。
|
||||
|
||||
上传压缩包上限 256MiB、解压后 512MiB、2048 项、32 个音色。拒绝路径越界、符号链接、缺失资源和哈希错误;校验成功后原子发布独立 pack-* 目录及清单。现有音色文件不改动;默认音色变更通过清单原子替换生效。导入过程不阻塞健康检查或已取得仓库快照的合成请求。
|
||||
|
||||
生产需挂载 /voices 可写,并仅赋予运行 UID 65534 对语音包根目录的写权限;原有模型无需更改所有权。Nginx `/admin/api/import` 单独允许大文件流式上传。
|
||||
|
||||
运维人员在服务器读取管理令牌(不要提交到源码或记录到日志):
|
||||
|
||||
```bash
|
||||
kubectl -n youlai get secret tts-server-admin -o jsonpath='{.data.token}' | base64 -d
|
||||
```
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/subtle"
|
||||
"embed"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
"tts-server/internal/tts"
|
||||
)
|
||||
|
||||
//go:embed adminweb/*
|
||||
var adminFiles embed.FS
|
||||
|
||||
func (s *server) adminRoutes(mux *http.ServeMux) {
|
||||
assets, _ := fs.Sub(adminFiles, "adminweb")
|
||||
files := http.StripPrefix("/admin/", http.FileServer(http.FS(assets)))
|
||||
mux.Handle("GET /admin/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self'; media-src 'self' blob:; object-src 'none'; frame-ancestors 'none'; base-uri 'none'")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
files.ServeHTTP(w, r)
|
||||
}))
|
||||
mux.HandleFunc("GET /admin/api/voices", s.adminAuth(s.adminList))
|
||||
mux.HandleFunc("POST /admin/api/default", s.adminAuth(s.adminDefault))
|
||||
mux.HandleFunc("POST /admin/api/import", s.adminAuth(s.adminImport))
|
||||
mux.HandleFunc("POST /admin/api/preview", s.adminAuth(func(w http.ResponseWriter, r *http.Request) {
|
||||
clone := r.Clone(r.Context())
|
||||
clone.Header.Set("Authorization", "Bearer "+s.cfg.apiToken)
|
||||
s.handleTTS(w, clone)
|
||||
}))
|
||||
}
|
||||
func (s *server) adminAuth(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
if s.cfg.adminToken == "" {
|
||||
writeError(w, 503, "管理功能尚未配置独立管理令牌")
|
||||
return
|
||||
}
|
||||
if subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), []byte("Bearer "+s.cfg.adminToken)) != 1 {
|
||||
writeError(w, 401, "管理令牌无效")
|
||||
return
|
||||
}
|
||||
next(w, r)
|
||||
}
|
||||
}
|
||||
func (s *server) adminList(w http.ResponseWriter, r *http.Request) { s.handleVoices(w, r) }
|
||||
func (s *server) adminDefault(w http.ResponseWriter, r *http.Request) {
|
||||
var input struct {
|
||||
Voice string `json:"voice"`
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 4096)
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
if err := decoder.Decode(&input); err != nil {
|
||||
writeError(w, 400, "请求无效")
|
||||
return
|
||||
}
|
||||
if err := decoder.Decode(new(any)); err != io.EOF {
|
||||
writeError(w, 400, "请求只能包含一个 JSON 对象")
|
||||
return
|
||||
}
|
||||
// Serialize persistence and pointer replacement, including concurrent imports.
|
||||
s.adminMu.Lock()
|
||||
defer s.adminMu.Unlock()
|
||||
repo, err := (&tts.VoiceStore{Root: s.cfg.voicesDir}).SetDefault(input.Voice)
|
||||
if err != nil {
|
||||
writeError(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
s.repoMu.Lock()
|
||||
s.repo = repo
|
||||
s.repoMu.Unlock()
|
||||
writeJSON(w, 200, map[string]string{"default": repo.Default, "version": repo.Version})
|
||||
}
|
||||
func (s *server) adminImport(w http.ResponseWriter, r *http.Request) {
|
||||
// One writer at a time; synthesis already holding a snapshot keeps using it.
|
||||
s.adminMu.Lock()
|
||||
defer s.adminMu.Unlock()
|
||||
_ = http.NewResponseController(w).SetReadDeadline(time.Now().Add(150 * time.Second))
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 256<<20)
|
||||
temp, err := os.CreateTemp(s.cfg.voicesDir, ".archive-*.zip")
|
||||
if err != nil {
|
||||
writeError(w, 500, "语音包目录不可写")
|
||||
return
|
||||
}
|
||||
defer os.Remove(temp.Name())
|
||||
_, err = io.Copy(temp, r.Body)
|
||||
closeErr := temp.Close()
|
||||
if err != nil || closeErr != nil {
|
||||
writeError(w, 400, "上传未完成或超过 256 MiB")
|
||||
return
|
||||
}
|
||||
repo, err := (&tts.VoiceStore{Root: s.cfg.voicesDir}).Import(temp.Name())
|
||||
if err != nil {
|
||||
writeError(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
s.repoMu.Lock()
|
||||
s.repo = repo
|
||||
s.repoMu.Unlock()
|
||||
writeJSON(w, 200, map[string]any{"voices": len(repo.Packs), "default": repo.Default, "version": repo.Version})
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
"tts-server/internal/tts"
|
||||
)
|
||||
|
||||
func TestAdminSeparateAuthentication(t *testing.T) {
|
||||
s := testServer(t)
|
||||
s.cfg.adminToken = "admin-secret"
|
||||
s.cfg.apiToken = "synthesis-secret"
|
||||
for _, token := range []string{"", "synthesis-secret"} {
|
||||
r := httptest.NewRequest("GET", "/admin/api/voices", nil)
|
||||
r.Header.Set("Authorization", "Bearer "+token)
|
||||
w := httptest.NewRecorder()
|
||||
s.routes().ServeHTTP(w, r)
|
||||
if w.Code != 401 {
|
||||
t.Fatalf("synthesis token granted admin access: %d", w.Code)
|
||||
}
|
||||
}
|
||||
r := httptest.NewRequest("GET", "/admin/api/voices", nil)
|
||||
r.Header.Set("Authorization", "Bearer admin-secret")
|
||||
w := httptest.NewRecorder()
|
||||
s.routes().ServeHTTP(w, r)
|
||||
if w.Code != 200 {
|
||||
t.Fatal(w.Code)
|
||||
}
|
||||
}
|
||||
func TestAdminDefaultAndPreview(t *testing.T) {
|
||||
s := testServer(t)
|
||||
s.cfg.adminToken = "admin-secret"
|
||||
s.cfg.apiToken = "synthesis-secret"
|
||||
r := httptest.NewRequest("POST", "/admin/api/default", bytes.NewBufferString(`{"voice":"a"}`))
|
||||
r.Header.Set("Authorization", "Bearer admin-secret")
|
||||
w := httptest.NewRecorder()
|
||||
s.routes().ServeHTTP(w, r)
|
||||
if w.Code != 200 {
|
||||
t.Fatal(w.Code, w.Body.String())
|
||||
}
|
||||
repo := s.repository()
|
||||
key := s.cache.Key(repo.Version, "a", 1, 1, "hello")
|
||||
if err := s.cache.Put(key, tts.EncodeWAV([]float32{0.1, 0.2}, 22050)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r = httptest.NewRequest("POST", "/admin/api/preview", bytes.NewBufferString(`{"text":"hello"}`))
|
||||
r.Header.Set("Authorization", "Bearer admin-secret")
|
||||
w = httptest.NewRecorder()
|
||||
s.routes().ServeHTTP(w, r)
|
||||
if w.Code != 200 || w.Header().Get("Content-Type") != "audio/wav" {
|
||||
t.Fatal(w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
type pausedUpload struct {
|
||||
started chan struct{}
|
||||
release chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (p *pausedUpload) Read(b []byte) (int, error) {
|
||||
p.once.Do(func() { close(p.started) })
|
||||
<-p.release
|
||||
return 0, io.EOF
|
||||
}
|
||||
func (p *pausedUpload) Close() error { return nil }
|
||||
func TestUploadDoesNotBlockHealth(t *testing.T) {
|
||||
s := testServer(t)
|
||||
s.cfg.adminToken = "admin-secret"
|
||||
body := &pausedUpload{started: make(chan struct{}), release: make(chan struct{})}
|
||||
r := httptest.NewRequest("POST", "/admin/api/import", body)
|
||||
r.Header.Set("Authorization", "Bearer admin-secret")
|
||||
done := make(chan struct{})
|
||||
go func() { defer close(done); s.routes().ServeHTTP(httptest.NewRecorder(), r) }()
|
||||
<-body.started
|
||||
health := make(chan int, 1)
|
||||
go func() {
|
||||
w := httptest.NewRecorder()
|
||||
s.routes().ServeHTTP(w, httptest.NewRequest("GET", "/healthz", nil))
|
||||
health <- w.Code
|
||||
}()
|
||||
select {
|
||||
case code := <-health:
|
||||
if code != http.StatusOK {
|
||||
t.Error(code)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Error("upload blocked health")
|
||||
}
|
||||
close(body.release)
|
||||
<-done
|
||||
}
|
||||
func TestAdminPageServedWithoutSecrets(t *testing.T) {
|
||||
s := testServer(t)
|
||||
w := httptest.NewRecorder()
|
||||
s.routes().ServeHTTP(w, httptest.NewRequest("GET", "/admin/", nil))
|
||||
if w.Code != 200 || w.Header().Get("Content-Security-Policy") == "" {
|
||||
t.Fatal(w.Code)
|
||||
}
|
||||
var parsed any
|
||||
if json.Unmarshal(w.Body.Bytes(), &parsed) == nil {
|
||||
t.Fatal("expected HTML")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
"use strict";
|
||||
const $=id=>document.getElementById(id);
|
||||
let token="",data=null,selected=null,audioUrl=null,busy=false;
|
||||
function notice(message,error=false){$("notice").textContent=message;$("notice").classList.toggle("error",error);}
|
||||
async function api(path,options={}){const r=await fetch("/admin/api/"+path,{...options,headers:{Authorization:"Bearer "+token,...options.headers},cache:"no-store"});if(!r.ok){let m="请求失败("+r.status+")";try{m=(await r.json()).error||m;}catch{}throw Error(m);}return r;}
|
||||
function resetAudio(){$("audio").pause();$("audio").removeAttribute("src");$("audio").hidden=true;if(audioUrl){URL.revokeObjectURL(audioUrl);audioUrl=null;}}
|
||||
function select(v){selected=v;resetAudio();$("selected-label").textContent=v.label;$("selected-meta").textContent=v.locale+" · "+v.name;render();}
|
||||
function render(){
|
||||
$("count").textContent=data.voices.length;$("version").textContent=data.version;$("default").textContent=data.voices.find(v=>v.name===data.default)?.label||data.default;$("voice-list").replaceChildren();
|
||||
for(const v of data.voices){const row=document.createElement("article");row.className="voice"+(selected?.name===v.name?" selected":"");const top=document.createElement("div");top.className="voice-top";const title=document.createElement("h3");title.textContent=v.label;top.append(title);if(v.name===data.default){const badge=document.createElement("span");badge.className="tag";badge.textContent="默认音色";top.append(badge);}row.append(top);const meta=document.createElement("p");meta.textContent=v.locale+" · "+v.name;row.append(meta);const choose=document.createElement("button");choose.className="secondary";choose.textContent="选择试听";choose.onclick=()=>select(v);row.append(choose);
|
||||
if(v.name!==data.default){const set=document.createElement("button");set.className="secondary";set.textContent="设为默认";set.onclick=async()=>{if(!confirm("将“"+v.label+"”设为默认声音?"))return;set.disabled=true;try{await api("default",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({voice:v.name})});await refresh();notice("默认声音已更新。");}catch(e){notice(e.message,true);}finally{set.disabled=false;}};row.append(" ",set);}$("voice-list").append(row);}
|
||||
}
|
||||
async function refresh(){data=await(await api("voices")).json();if(!selected||!data.voices.some(v=>v.name===selected.name))selected=data.voices.find(v=>v.name===data.default)||data.voices[0];if(selected){$("selected-label").textContent=selected.label;$("selected-meta").textContent=selected.locale+" · "+selected.name;}render();}
|
||||
$("login-form").onsubmit=async e=>{e.preventDefault();token=$("token").value.trim();try{await refresh();$("token").value="";$("login").hidden=true;$("workspace").hidden=false;$("logout").hidden=false;notice("已连接音色管理。");}catch(e){token="";notice(e.message,true);}};
|
||||
$("logout").onclick=()=>{token="";data=null;selected=null;resetAudio();$("workspace").hidden=true;$("login").hidden=false;$("logout").hidden=true;notice("已退出管理。");};
|
||||
$("refresh").onclick=async()=>{try{await refresh();notice("音色列表已刷新。");}catch(e){notice(e.message,true);}};
|
||||
for(const id of ["speed","pitch"])$(id).oninput=()=>$(id+"-label").textContent=Number($(id).value).toFixed(1);
|
||||
$("preview").onclick=async()=>{if(!selected||busy)return;busy=true;$("preview").disabled=true;resetAudio();notice("正在生成试听,请稍候…");try{const r=await api("preview",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:$("text").value,voice:selected.name,speed:Number($("speed").value),pitch:Number($("pitch").value)})});audioUrl=URL.createObjectURL(await r.blob());$("audio").src=audioUrl;$("audio").hidden=false;try{await $("audio").play();}catch{}notice("试听已生成,可使用播放器播放。");}catch(e){notice(e.message,true);}finally{busy=false;$("preview").disabled=false;}};
|
||||
$("package").onchange=()=>{const f=$("package").files[0];$("filename").textContent=f?f.name+" · "+(f.size/1024/1024).toFixed(1)+" MiB":"";$("upload").disabled=!f;};
|
||||
$("upload").onclick=async()=>{const f=$("package").files[0];if(!f)return;if(f.size>256*1024*1024){notice("压缩包不能超过 256 MiB。",true);return;}$("upload").disabled=true;notice("正在上传、校验并导入语音包,请勿关闭页面…");try{await api("import",{method:"POST",headers:{"Content-Type":"application/zip"},body:f});await refresh();$("package").value="";$("filename").textContent="";notice("新音色已导入,默认声音保持不变。");}catch(e){notice(e.message,true);}finally{$("upload").disabled=!$("package").files[0];}};
|
||||
@@ -0,0 +1,8 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>音色管理 · TTStd</title><link rel="stylesheet" href="style.css"><script src="app.js" defer></script></head><body>
|
||||
<aside><div class="brand">TTStd<small>VOICE STUDIO</small></div><div class="nav">音色管理</div><p>统一管理在线朗读使用的声音。</p><button id="logout" hidden>退出管理</button></aside>
|
||||
<main><header><p class="eyebrow">语音服务控制台</p><h1>让每一句话,都有合适的声音。</h1><p class="muted">查看语音包、试听音色,或设置默认声音。</p></header><div id="notice" role="status" aria-live="polite"></div>
|
||||
<section id="login" class="card"><h2>进入音色管理</h2><p class="muted">使用独立管理令牌。令牌仅保留在当前页面内存中。</p><form id="login-form"><label for="token">管理令牌</label><div class="login-row"><input id="token" type="password" autocomplete="off" required placeholder="请输入管理令牌"><button>连接服务</button></div></form></section>
|
||||
<div id="workspace" hidden><section class="stats"><div class="card"><span>可用音色</span><strong id="count">—</strong></div><div class="card"><span>默认声音</span><strong id="default">—</strong></div><div class="card"><span>语音包版本</span><strong id="version">—</strong></div></section>
|
||||
<div class="columns"><section class="card"><div class="section-title"><h2>音色库</h2><button id="refresh" class="secondary">刷新列表</button></div><p class="muted">选择声音,在右侧听一听。</p><div id="voice-list"></div></section>
|
||||
<div class="right"><section class="card"><p class="eyebrow">试听工作台</p><h2 id="selected-label">选择一个音色</h2><p id="selected-meta" class="muted"></p><label for="text">朗读内容</label><textarea id="text" rows="4" maxlength="300">您好,现在是上午九点整。愿您今天心情愉快。</textarea><div class="sliders"><label>语速 <output id="speed-label">0.9</output><input id="speed" type="range" min="0.5" max="2" step="0.1" value="0.9"></label><label>音调 <output id="pitch-label">1.0</output><input id="pitch" type="range" min="0.5" max="2" step="0.1" value="1"></label></div><button id="preview">生成试听</button><audio id="audio" controls hidden></audio></section>
|
||||
<section class="card"><h2>添加新音色</h2><p class="muted">上传 ZIP 语音包。根目录包含 manifest.json 及模型、词典和规则资源,仅支持当前服务兼容的 Piper / VITS 模型。</p><label class="file-box" for="package">选择 ZIP 语音包<small>压缩包不超过 256 MiB</small><input id="package" type="file" accept=".zip,application/zip"></label><p id="filename" class="muted"></p><button id="upload" class="secondary" disabled>校验并导入</button><p class="hint">音色名称不能重复。导入后保留当前默认声音。</p></section></div></div></div><footer>TTStd 语音服务 · 已连接的离线设备需另行同步语音包。</footer></main></body></html>
|
||||
@@ -0,0 +1 @@
|
||||
*{box-sizing:border-box}body{margin:0;background:#f2f5f8;color:#152536;font:16px/1.6 system-ui,-apple-system,"Microsoft YaHei",sans-serif}aside{position:fixed;inset:0 auto 0 0;width:220px;background:#112534;color:white;padding:36px 24px;display:flex;flex-direction:column}.brand{font-size:29px;font-weight:750;letter-spacing:1px}.brand small{display:block;font-size:12px;letter-spacing:3px;color:#98b1c0}.nav{margin-top:52px;padding:12px 16px;border-radius:10px;background:#234657;color:#a6efdd}aside p{color:#a6bac7;font-size:14px;margin-top:auto}main{margin-left:220px;padding:42px 44px;max-width:1660px}header{margin-bottom:30px}h1{font-size:30px;line-height:1.45;letter-spacing:-.7px;margin:8px 0}h2{font-size:20px;margin:0 0 8px}.eyebrow{font-size:13px;font-weight:700;letter-spacing:2px;color:#16846b;margin:0}.muted{color:#637587;font-size:15px;margin:8px 0 18px}.card{background:white;border:1px solid #e0e7ec;border-radius:16px;padding:26px;box-shadow:0 5px 20px #203a4d04}#login{max-width:720px;margin-top:48px}.login-row{display:flex;gap:12px}.login-row input{flex:1;min-width:0}.stats{display:grid;grid-template-columns:1fr 1.5fr 1fr;gap:18px;margin-bottom:24px}.stats span{display:block;color:#66798a;font-size:14px}.stats strong{display:block;margin-top:9px;font-size:25px;overflow-wrap:anywhere}.columns{display:grid;grid-template-columns:minmax(300px,1.1fr) minmax(320px,1fr);gap:24px}.right{display:grid;gap:24px;align-content:start}.section-title{display:flex;align-items:center;justify-content:space-between;gap:12px}.voice{border:1px solid #dde5eb;border-radius:12px;padding:20px;margin-top:14px}.voice.selected{border-color:#16846b;background:#f0fbf7;box-shadow:0 0 0 1px #16846b}.voice-top{display:flex;justify-content:space-between;gap:12px}.voice h3{font-size:18px;margin:0}.voice p{margin:6px 0;color:#607586;font-size:14px;overflow-wrap:anywhere}.voice button{margin-top:10px;font-size:14px;padding:7px 12px}.tag{font-size:12px;color:#14775f;background:#dbf5eb;padding:3px 9px;border-radius:20px;white-space:nowrap;align-self:flex-start}button{background:#137f67;border:1px solid #137f67;color:white;border-radius:9px;padding:11px 18px;font:600 15px system-ui;cursor:pointer;white-space:nowrap}button:hover{filter:brightness(.95)}button:disabled{opacity:.5;cursor:wait}.secondary{color:#186b5b;background:white;border-color:#b7cfc6}label{display:block;font-size:14px;font-weight:600;margin:14px 0 7px}input,textarea{font:16px system-ui;border:1px solid #ccd8e1;border-radius:8px;padding:12px;color:#172d3c;background:white}input:focus,textarea:focus,button:focus-visible{outline:2px solid #68bfa9;outline-offset:2px}textarea{width:100%;resize:vertical;line-height:1.7}.sliders{display:grid;grid-template-columns:1fr 1fr;gap:24px;margin-bottom:18px}.sliders input{width:100%;padding:0;accent-color:#137f67}.sliders output{float:right;color:#137f67}audio{width:100%;margin-top:18px}.file-box{border:1px dashed #a9bfc9;background:#f8fbfc;text-align:center;padding:20px;border-radius:10px;cursor:pointer}.file-box small{display:block;font-size:13px;color:#697e8b;font-weight:400}.file-box input{width:100%;margin-top:12px;font-size:13px}.hint,footer{font-size:13px;color:#697e8b}#filename{overflow-wrap:anywhere}#notice:empty{display:none}#notice{padding:13px 18px;border-radius:9px;background:#e0f5ec;color:#11694f;margin-bottom:22px}#notice.error{background:#fff0ef;color:#a62d27}footer{margin-top:30px}[hidden]{display:none!important}@media(max-width:1100px){aside{width:170px;padding:30px 18px}main{margin-left:170px;padding:32px 24px}.columns{grid-template-columns:1fr}}@media(max-width:650px){aside{position:static;width:auto;padding:18px 22px;display:block}.brand{font-size:23px}.brand small{display:inline;margin-left:12px;font-size:10px}.nav,aside p{display:none}aside button{position:absolute;right:18px;top:14px}main{margin-left:0;padding:26px 16px}h1{font-size:25px}.stats{grid-template-columns:1fr}.card{padding:20px}.columns{grid-template-columns:minmax(0,1fr)}.login-row{flex-direction:column}.stats strong{font-size:22px}}
|
||||
+17
-5
@@ -21,11 +21,23 @@ spec:
|
||||
fsGroup: 65534
|
||||
containers:
|
||||
- name: tts-server
|
||||
image: docker.io/library/tts-server:dev-1
|
||||
image: docker.io/library/tts-server:admin-20261123-1
|
||||
imagePullPolicy: IfNotPresent
|
||||
ports:
|
||||
- containerPort: 8080
|
||||
env:
|
||||
- name: TTS_ADMIN_TOKEN
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: tts-server-admin
|
||||
key: token
|
||||
- name: TTS_REQUIRE_AUTH
|
||||
value: "1"
|
||||
- name: TTS_API_TOKEN
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: tts-server-auth
|
||||
key: token
|
||||
- name: TTS_VOICES
|
||||
value: /voices
|
||||
- name: TTS_CACHE
|
||||
@@ -37,14 +49,14 @@ spec:
|
||||
- name: TTS_MAX_TEXT
|
||||
value: "300"
|
||||
- name: GOMEMLIMIT
|
||||
value: 256MiB
|
||||
value: 64MiB
|
||||
resources:
|
||||
requests:
|
||||
cpu: 200m
|
||||
memory: 256Mi
|
||||
limits:
|
||||
cpu: 1500m
|
||||
memory: 768Mi
|
||||
memory: 512Mi
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /healthz
|
||||
@@ -62,7 +74,7 @@ spec:
|
||||
volumeMounts:
|
||||
- name: voices
|
||||
mountPath: /voices
|
||||
readOnly: true
|
||||
readOnly: false
|
||||
- name: cache
|
||||
mountPath: /cache
|
||||
volumes:
|
||||
@@ -72,7 +84,7 @@ spec:
|
||||
type: Directory
|
||||
- name: cache
|
||||
emptyDir:
|
||||
sizeLimit: 1Gi
|
||||
sizeLimit: 512Mi
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
|
||||
+25
-6
@@ -1,6 +1,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
@@ -32,26 +33,44 @@ func (e *engine) preload(pack *tts.VoicePack) error {
|
||||
return err
|
||||
}
|
||||
|
||||
func (e *engine) synthesize(pack *tts.VoicePack, text string, speed, pitch float32) ([]float32, int, error) {
|
||||
func (e *engine) synthesize(ctx context.Context, pack *tts.VoicePack, text string, speed, pitch float32) ([]float32, int, error) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
model, err := e.obtain(pack)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// Same generation config as Synthesizer.java: silenceScale 0, sid, speed,
|
||||
// Same generation config as Synthesizer.java: silenceScale 0.2, sid, speed,
|
||||
// numSteps 5.
|
||||
cfg := &sherpa.GenerationConfig{SilenceScale: 0, Speed: speed, Sid: pack.SpeakerID, NumSteps: 5}
|
||||
audio := model.GenerateWithConfig(text, cfg, nil)
|
||||
cfg := &sherpa.GenerationConfig{SilenceScale: 0.2, Speed: speed, Sid: pack.SpeakerID, NumSteps: 5}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var shifted []float32
|
||||
audio := model.GenerateWithConfig(text, cfg, func(samples []float32, progress float32) bool {
|
||||
if ctx.Err() != nil {
|
||||
return false
|
||||
}
|
||||
if tts.PitchShiftNeeded(pitch) {
|
||||
shifted = append(shifted, tts.ShiftPitch(samples, pitch)...)
|
||||
}
|
||||
return ctx.Err() == nil
|
||||
})
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if audio == nil || len(audio.Samples) == 0 {
|
||||
return nil, 0, errors.New("synthesis produced no audio")
|
||||
}
|
||||
|
||||
samples := audio.Samples
|
||||
if tts.PitchShiftNeeded(pitch) {
|
||||
samples = tts.ShiftPitch(samples, pitch)
|
||||
samples = shifted
|
||||
}
|
||||
return samples, audio.SampleRate, nil
|
||||
}
|
||||
@@ -104,4 +123,4 @@ func (e *engine) release() {
|
||||
e.tts = nil
|
||||
e.loaded = ""
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,23 +7,31 @@ import (
|
||||
"math"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type Cache struct {
|
||||
dir string
|
||||
dir string
|
||||
mu sync.Mutex
|
||||
maxBytes int64
|
||||
}
|
||||
|
||||
func NewCache(dir string) (*Cache, error) {
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return nil, fmt.Errorf("create cache dir: %w", err)
|
||||
}
|
||||
return &Cache{dir: dir}, nil
|
||||
c := &Cache{dir: dir, maxBytes: 256 << 20}
|
||||
if err := c.prune(0); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// Key covers everything that changes the rendered audio, including the voice
|
||||
// pack version, so upgrades invalidate old files on their own.
|
||||
func (c *Cache) Key(version, voice string, speed, pitch float32, text string) string {
|
||||
sum := sha256.Sum256([]byte(fmt.Sprintf("%s\x00%s\x00%08x\x00%08x\x00%s",
|
||||
sum := sha256.Sum256([]byte(fmt.Sprintf("dsp-v2\x00%s\x00%s\x00%08x\x00%08x\x00%s",
|
||||
version, voice, math.Float32bits(speed), math.Float32bits(pitch), text)))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
@@ -37,11 +45,20 @@ func (c *Cache) Get(key string) ([]byte, bool) {
|
||||
}
|
||||
|
||||
func (c *Cache) Put(key string, data []byte) error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if int64(len(data)) > c.maxBytes {
|
||||
return fmt.Errorf("audio exceeds cache budget")
|
||||
}
|
||||
if err := c.prune(int64(len(data))); err != nil {
|
||||
return err
|
||||
}
|
||||
tmp, err := os.CreateTemp(c.dir, key[:8]+"-*.tmp")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
name := tmp.Name()
|
||||
defer os.Remove(name)
|
||||
if _, err := tmp.Write(data); err != nil {
|
||||
tmp.Close()
|
||||
os.Remove(name)
|
||||
@@ -52,4 +69,38 @@ func (c *Cache) Put(key string, data []byte) error {
|
||||
return err
|
||||
}
|
||||
return os.Rename(name, filepath.Join(c.dir, key+".wav"))
|
||||
}
|
||||
}
|
||||
func (c *Cache) Open(key string) (*os.File, error) {
|
||||
return os.Open(filepath.Join(c.dir, key+".wav"))
|
||||
}
|
||||
|
||||
func (c *Cache) prune(incoming int64) error {
|
||||
entries, err := os.ReadDir(c.dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var files []os.FileInfo
|
||||
var total int64
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() || filepath.Ext(entry.Name()) != ".wav" {
|
||||
continue
|
||||
}
|
||||
info, err := entry.Info()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
total += info.Size()
|
||||
files = append(files, info)
|
||||
}
|
||||
sort.Slice(files, func(i, j int) bool { return files[i].ModTime().Before(files[j].ModTime()) })
|
||||
for _, file := range files {
|
||||
if total+incoming <= c.maxBytes {
|
||||
break
|
||||
}
|
||||
if err := os.Remove(filepath.Join(c.dir, file.Name())); err != nil {
|
||||
return err
|
||||
}
|
||||
total -= file.Size()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -24,4 +24,28 @@ func TestCacheRoundTrip(t *testing.T) {
|
||||
if !ok || string(got) != "wav" {
|
||||
t.Fatalf("cache get: %q %v", got, ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCacheEvictsWithinBudget(t *testing.T) {
|
||||
c, err := NewCache(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.maxBytes = 6
|
||||
first, second := c.Key("v", "a", 1, 1, "first"), c.Key("v", "a", 1, 1, "second")
|
||||
if err := c.Put(first, []byte("1234")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := c.Put(second, []byte("5678")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok := c.Get(first); ok {
|
||||
t.Fatal("old cache retained beyond budget")
|
||||
}
|
||||
if data, ok := c.Get(second); !ok || string(data) != "5678" {
|
||||
t.Fatal("new cache missing")
|
||||
}
|
||||
if err := c.Put(first, make([]byte, 7)); err == nil {
|
||||
t.Fatal("oversized cache accepted")
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,23 @@ func ShiftPitch(samples []float32, factor float32) []float32 {
|
||||
}
|
||||
|
||||
func timeStretch(in []float32, factor float32) []float32 {
|
||||
originalLength := len(in)
|
||||
padded := make([]float32, len(in)+2*grain)
|
||||
// Reflect boundaries so even sub-window sounds retain their energy.
|
||||
for i := range padded {
|
||||
at := i - grain
|
||||
if len(in) == 1 {
|
||||
padded[i] = in[0]
|
||||
continue
|
||||
}
|
||||
period := 2 * (len(in) - 1)
|
||||
at = ((at % period) + period) % period
|
||||
if at >= len(in) {
|
||||
at = period - at
|
||||
}
|
||||
padded[i] = in[at]
|
||||
}
|
||||
in = padded
|
||||
hopA := roundInt(float32(hops) / factor)
|
||||
if hopA < 1 {
|
||||
hopA = 1
|
||||
@@ -36,6 +53,7 @@ func timeStretch(in []float32, factor float32) []float32 {
|
||||
expected = grain
|
||||
}
|
||||
out := make([]float32, expected+grain)
|
||||
weights := make([]float32, len(out))
|
||||
|
||||
inPos, outPos := 0, 0
|
||||
for inPos+grain <= len(in) {
|
||||
@@ -49,7 +67,7 @@ func timeStretch(in []float32, factor float32) []float32 {
|
||||
if to > len(in)-grain {
|
||||
to = len(in) - grain
|
||||
}
|
||||
bestCorr := -1.0
|
||||
bestCorr := 0.0
|
||||
for cand := from; cand <= to; cand += 4 {
|
||||
var corr float64
|
||||
for i := 0; i < overlap; i++ {
|
||||
@@ -63,13 +81,21 @@ func timeStretch(in []float32, factor float32) []float32 {
|
||||
}
|
||||
for i := 0; i < grain; i++ {
|
||||
out[outPos+i] += in[best+i] * window[i]
|
||||
weights[outPos+i] += window[i]
|
||||
}
|
||||
inPos += hopA
|
||||
outPos += hops
|
||||
}
|
||||
|
||||
result := make([]float32, expected)
|
||||
copy(result, out[:min(expected, len(out))])
|
||||
length := max(1, roundInt(float32(originalLength)*factor))
|
||||
offset := roundInt(float32(grain) * factor)
|
||||
result := make([]float32, length)
|
||||
for i := range result {
|
||||
at := offset + i
|
||||
if at < len(out) && weights[at] > 0.00001 {
|
||||
result[i] = out[at] / weights[at]
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
@@ -106,4 +132,4 @@ func hann(size int) []float32 {
|
||||
// roundInt matches Java Math.round(float): floor(x + 0.5).
|
||||
func roundInt(x float32) int {
|
||||
return int(math.Floor(float64(x) + 0.5))
|
||||
}
|
||||
}
|
||||
@@ -53,4 +53,56 @@ func TestShiftPitchSilence(t *testing.T) {
|
||||
t.Fatalf("sample %d: got %v, want 0", i, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPitchShortAndTail(t *testing.T) {
|
||||
for _, length := range []int{100, 511, 1023, 1025, 2601} {
|
||||
for _, factor := range []float32{0.5, 1.2, 2} {
|
||||
in := make([]float32, length)
|
||||
for i := range in {
|
||||
in[i] = 0.5
|
||||
}
|
||||
out := ShiftPitch(in, factor)
|
||||
if math.Abs(float64(len(out)-length)) > 1 {
|
||||
t.Fatalf("length %d factor %v: %d", length, factor, len(out))
|
||||
}
|
||||
var energy float64
|
||||
for _, v := range out {
|
||||
energy += float64(v * v)
|
||||
}
|
||||
if energy < float64(length)*0.01 {
|
||||
t.Fatalf("short audio lost: length=%d factor=%v energy=%v", length, factor, energy)
|
||||
}
|
||||
var tail float64
|
||||
for _, v := range out[max(0, len(out)-100):] {
|
||||
tail += float64(v * v)
|
||||
}
|
||||
if tail < 0.01 {
|
||||
t.Fatalf("tail lost: length=%d factor=%v", length, factor)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPitchChangesFrequency(t *testing.T) {
|
||||
const rate = 22050
|
||||
input := make([]float32, rate)
|
||||
for i := range input {
|
||||
input[i] = float32(0.5 * math.Sin(2*math.Pi*220*float64(i)/rate))
|
||||
}
|
||||
for _, factor := range []float32{0.5, 1.2, 2} {
|
||||
output := ShiftPitch(input, factor)
|
||||
from, to := rate/5, 4*rate/5
|
||||
crossings := 0
|
||||
for i := from + 1; i < to; i++ {
|
||||
if output[i-1] <= 0 && output[i] > 0 {
|
||||
crossings++
|
||||
}
|
||||
}
|
||||
frequency := float64(crossings) * rate / float64(to-from)
|
||||
want := 220 * float64(factor)
|
||||
if math.Abs(frequency/want-1) > 0.15 {
|
||||
t.Fatalf("pitch=%v frequency=%.1f want=%.1f", factor, frequency, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
+105
-21
@@ -1,8 +1,11 @@
|
||||
package tts
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -17,17 +20,19 @@ type Manifest struct {
|
||||
}
|
||||
|
||||
type VoiceEntry struct {
|
||||
Name string `json:"name"`
|
||||
Locale string `json:"locale"`
|
||||
Label string `json:"label"`
|
||||
SpeakerID int `json:"speakerId"`
|
||||
Quality int `json:"quality"`
|
||||
Dir string `json:"dir"`
|
||||
Model string `json:"model"`
|
||||
Lexicon string `json:"lexicon"`
|
||||
Tokens string `json:"tokens"`
|
||||
DataDir string `json:"dataDir"`
|
||||
RuleFsts []string `json:"ruleFsts"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Files map[string]string `json:"files"`
|
||||
Name string `json:"name"`
|
||||
Locale string `json:"locale"`
|
||||
Label string `json:"label"`
|
||||
SpeakerID int `json:"speakerId"`
|
||||
Quality int `json:"quality"`
|
||||
Dir string `json:"dir"`
|
||||
Model string `json:"model"`
|
||||
Lexicon string `json:"lexicon"`
|
||||
Tokens string `json:"tokens"`
|
||||
DataDir string `json:"dataDir"`
|
||||
RuleFsts []string `json:"ruleFsts"`
|
||||
}
|
||||
|
||||
type VoicePack struct {
|
||||
@@ -55,10 +60,17 @@ func LoadRepo(root string) (*Repo, error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read manifest: %w", err)
|
||||
}
|
||||
return LoadRepoManifest(root, raw)
|
||||
}
|
||||
|
||||
func LoadRepoManifest(root string, raw []byte) (*Repo, error) {
|
||||
var m Manifest
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
return nil, fmt.Errorf("parse manifest: %w", err)
|
||||
}
|
||||
if strings.TrimSpace(m.Version) == "" {
|
||||
return nil, fmt.Errorf("manifest version is required")
|
||||
}
|
||||
if len(m.Voices) == 0 {
|
||||
return nil, fmt.Errorf("manifest has no voices")
|
||||
}
|
||||
@@ -84,14 +96,14 @@ func LoadRepo(root string) (*Repo, error) {
|
||||
rules = append(rules, filepath.Join(base, f))
|
||||
}
|
||||
pack := &VoicePack{
|
||||
Name: e.Name,
|
||||
Locale: e.Locale,
|
||||
Label: e.Label,
|
||||
SpeakerID: e.SpeakerID,
|
||||
Quality: e.Quality,
|
||||
ModelPath: filepath.Join(base, e.Model),
|
||||
TokensPath: filepath.Join(base, tokens),
|
||||
RuleFsts: strings.Join(rules, ","),
|
||||
Name: e.Name,
|
||||
Locale: e.Locale,
|
||||
Label: e.Label,
|
||||
SpeakerID: e.SpeakerID,
|
||||
Quality: e.Quality,
|
||||
ModelPath: filepath.Join(base, e.Model),
|
||||
TokensPath: filepath.Join(base, tokens),
|
||||
RuleFsts: strings.Join(rules, ","),
|
||||
}
|
||||
if e.Lexicon != "" {
|
||||
pack.LexiconPath = filepath.Join(base, e.Lexicon)
|
||||
@@ -102,6 +114,31 @@ func LoadRepo(root string) (*Repo, error) {
|
||||
if pack.Label == "" {
|
||||
pack.Label = pack.Name
|
||||
}
|
||||
paths := []string{pack.ModelPath, pack.TokensPath}
|
||||
if pack.LexiconPath != "" {
|
||||
paths = append(paths, pack.LexiconPath)
|
||||
}
|
||||
if pack.DataDir != "" {
|
||||
paths = append(paths, pack.DataDir)
|
||||
}
|
||||
paths = append(paths, rules...)
|
||||
for _, path := range paths {
|
||||
if err := contained(root, path); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err := verifyHash(pack.ModelPath, e.SHA256); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for relative, hash := range e.Files {
|
||||
path := filepath.Join(base, relative)
|
||||
if err := contained(root, path); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := verifyHash(path, hash); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err := pack.validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -127,9 +164,17 @@ func (p *VoicePack) validate() error {
|
||||
required = append(required, strings.Split(p.RuleFsts, ",")...)
|
||||
}
|
||||
for _, path := range required {
|
||||
if _, err := os.Stat(path); err != nil {
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("voice %q: %w", p.Name, err)
|
||||
}
|
||||
if path == p.DataDir {
|
||||
if !info.IsDir() {
|
||||
return fmt.Errorf("voice %q: dataDir must be a directory", p.Name)
|
||||
}
|
||||
} else if !info.Mode().IsRegular() {
|
||||
return fmt.Errorf("voice %q: resource must be a regular file", p.Name)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -148,6 +193,11 @@ func (r *Repo) Resolve(requested string) *VoicePack {
|
||||
if p, ok := r.byName[requested]; ok {
|
||||
return p
|
||||
}
|
||||
for _, p := range r.Packs {
|
||||
if strings.EqualFold(strings.ReplaceAll(requested, "_", "-"), p.Locale) {
|
||||
return p
|
||||
}
|
||||
}
|
||||
want := normalizeLanguage(requested)
|
||||
if want != "" {
|
||||
for _, p := range r.Packs {
|
||||
@@ -178,4 +228,38 @@ func normalizeLanguage(tag string) string {
|
||||
default:
|
||||
return tag
|
||||
}
|
||||
}
|
||||
}
|
||||
func contained(root, path string) error {
|
||||
base, err := filepath.EvalSymlinks(root)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
target, err := filepath.EvalSymlinks(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rel, err := filepath.Rel(base, target)
|
||||
if err != nil || rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || filepath.IsAbs(rel) {
|
||||
return fmt.Errorf("voice path outside root: %s", path)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func verifyHash(path, expected string) error {
|
||||
decoded, err := hex.DecodeString(expected)
|
||||
if err != nil || len(decoded) != sha256.Size {
|
||||
return fmt.Errorf("missing/invalid SHA256: %s", path)
|
||||
}
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
hash := sha256.New()
|
||||
if _, err := io.Copy(hash, f); err != nil {
|
||||
return err
|
||||
}
|
||||
if !strings.EqualFold(hex.EncodeToString(hash.Sum(nil)), expected) {
|
||||
return fmt.Errorf("SHA256 mismatch: %s", path)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
package tts
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// VoiceStore publishes validated immutable pack directories. Old files remain
|
||||
// available for in-flight synthesis and rollback; manifests change atomically.
|
||||
type VoiceStore struct {
|
||||
Root string
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func (s *VoiceStore) manifest() (Manifest, error) {
|
||||
var m Manifest
|
||||
raw, err := os.ReadFile(filepath.Join(s.Root, "manifest.json"))
|
||||
if err != nil {
|
||||
return m, err
|
||||
}
|
||||
err = json.Unmarshal(raw, &m)
|
||||
return m, err
|
||||
}
|
||||
func (s *VoiceStore) commit(m Manifest) (*Repo, error) {
|
||||
raw, err := json.MarshalIndent(m, "", " ")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Validate against the real root before replacing the live manifest.
|
||||
repo, err := LoadRepoManifest(s.Root, raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
temp, err := os.CreateTemp(s.Root, ".manifest-*.tmp")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
name := temp.Name()
|
||||
defer os.Remove(name)
|
||||
if _, err = temp.Write(raw); err != nil {
|
||||
temp.Close()
|
||||
return nil, err
|
||||
}
|
||||
if err = temp.Sync(); err != nil {
|
||||
temp.Close()
|
||||
return nil, err
|
||||
}
|
||||
if err = temp.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = os.Rename(name, filepath.Join(s.Root, "manifest.json")); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return repo, nil
|
||||
}
|
||||
func (s *VoiceStore) SetDefault(name string) (*Repo, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
m, err := s.manifest()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
found := false
|
||||
for _, v := range m.Voices {
|
||||
if v.Name == name {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return nil, fmt.Errorf("音色不存在")
|
||||
}
|
||||
m.Default = name
|
||||
return s.commit(m)
|
||||
}
|
||||
func (s *VoiceStore) Import(archive string) (*Repo, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
m, err := s.manifest()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stage, err := os.MkdirTemp(s.Root, ".upload-")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer os.RemoveAll(stage)
|
||||
if err = extractVoices(archive, stage); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
raw, err := os.ReadFile(filepath.Join(stage, "manifest.json"))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ZIP 根目录需要 manifest.json")
|
||||
}
|
||||
if len(raw) > 1024*1024 {
|
||||
return nil, fmt.Errorf("清单过大")
|
||||
}
|
||||
var incoming Manifest
|
||||
if err = json.Unmarshal(raw, &incoming); err != nil {
|
||||
return nil, fmt.Errorf("语音包清单无效")
|
||||
}
|
||||
if len(incoming.Voices) > 32 {
|
||||
return nil, fmt.Errorf("单次最多导入 32 个音色")
|
||||
}
|
||||
if _, err = LoadRepo(stage); err != nil {
|
||||
return nil, fmt.Errorf("语音包资源或 SHA256 校验失败: %w", err)
|
||||
}
|
||||
existing := map[string]bool{}
|
||||
for _, v := range m.Voices {
|
||||
existing[v.Name] = true
|
||||
}
|
||||
folder := "pack-" + strings.TrimPrefix(filepath.Base(stage), ".upload-")
|
||||
for _, v := range incoming.Voices {
|
||||
if existing[v.Name] {
|
||||
return nil, fmt.Errorf("音色 %q 已存在,请为新音色使用不同名称", v.Name)
|
||||
}
|
||||
if filepath.IsAbs(v.Dir) || strings.Contains(v.Dir, "..") {
|
||||
return nil, fmt.Errorf("语音包目录无效")
|
||||
}
|
||||
v.Dir = filepath.Join(folder, v.Dir)
|
||||
m.Voices = append(m.Voices, v)
|
||||
}
|
||||
destination := filepath.Join(s.Root, folder)
|
||||
if err = os.Rename(stage, destination); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m.Version = incoming.Version
|
||||
repo, err := s.commit(m)
|
||||
if err != nil {
|
||||
os.RemoveAll(destination)
|
||||
return nil, err
|
||||
}
|
||||
return repo, nil
|
||||
}
|
||||
func extractVoices(archive, root string) error {
|
||||
z, err := zip.OpenReader(archive)
|
||||
if err != nil {
|
||||
return fmt.Errorf("无法读取 ZIP 语音包")
|
||||
}
|
||||
defer z.Close()
|
||||
if len(z.File) > 2048 {
|
||||
return fmt.Errorf("语音包文件数量超过 2048")
|
||||
}
|
||||
var total uint64
|
||||
for _, entry := range z.File {
|
||||
name := entry.Name
|
||||
if name == "" || strings.Contains(name, "\\") || strings.Contains(name, ":") || strings.HasPrefix(name, "/") {
|
||||
return fmt.Errorf("ZIP 路径无效")
|
||||
}
|
||||
for _, part := range strings.Split(name, "/") {
|
||||
if part == ".." {
|
||||
return fmt.Errorf("ZIP 路径越界")
|
||||
}
|
||||
}
|
||||
if entry.Mode()&os.ModeSymlink != 0 || (!entry.FileInfo().IsDir() && !entry.Mode().IsRegular()) {
|
||||
return fmt.Errorf("ZIP 仅允许普通文件和目录")
|
||||
}
|
||||
total += entry.UncompressedSize64
|
||||
if total > 512<<20 {
|
||||
return fmt.Errorf("解压后语音包超过 512 MiB")
|
||||
}
|
||||
target := filepath.Join(root, filepath.FromSlash(name))
|
||||
rel, err := filepath.Rel(root, target)
|
||||
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
|
||||
return fmt.Errorf("ZIP 路径越界")
|
||||
}
|
||||
if entry.FileInfo().IsDir() {
|
||||
if err = os.MkdirAll(target, 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err = os.MkdirAll(filepath.Dir(target), 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
src, err := entry.Open()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dst, err := os.OpenFile(target, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
|
||||
if err != nil {
|
||||
src.Close()
|
||||
return err
|
||||
}
|
||||
n, copyErr := io.Copy(dst, io.LimitReader(src, int64(entry.UncompressedSize64)+1))
|
||||
src.Close()
|
||||
closeErr := dst.Close()
|
||||
if copyErr != nil || closeErr != nil || uint64(n) != entry.UncompressedSize64 {
|
||||
return fmt.Errorf("ZIP 文件不完整")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package tts
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func testVoiceStore(t *testing.T) *VoiceStore {
|
||||
root := t.TempDir()
|
||||
writeVoiceFiles(t, root, "pack-a")
|
||||
writeVoiceFiles(t, root, "pack-b")
|
||||
writeManifest(t, root, testManifest)
|
||||
return &VoiceStore{Root: root}
|
||||
}
|
||||
func TestVoiceStoreDefaultPersists(t *testing.T) {
|
||||
store := testVoiceStore(t)
|
||||
repo, err := store.SetDefault("b")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if repo.Default != "b" {
|
||||
t.Fatal(repo.Default)
|
||||
}
|
||||
fresh, err := LoadRepo(store.Root)
|
||||
if err != nil || fresh.Default != "b" {
|
||||
t.Fatal("default not persisted", err)
|
||||
}
|
||||
if _, err = store.SetDefault("missing"); err == nil {
|
||||
t.Fatal("unknown voice accepted")
|
||||
}
|
||||
}
|
||||
func voiceZip(t *testing.T, entries map[string][]byte) string {
|
||||
t.Helper()
|
||||
name := filepath.Join(t.TempDir(), "pack.zip")
|
||||
f, err := os.Create(name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w := zip.NewWriter(f)
|
||||
for path, data := range entries {
|
||||
entry, err := w.Create(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = entry.Write(data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err = w.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = f.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return name
|
||||
}
|
||||
func TestVoiceStoreImportAndDuplicate(t *testing.T) {
|
||||
store := testVoiceStore(t)
|
||||
var incoming Manifest
|
||||
if err := json.Unmarshal([]byte(testManifest), &incoming); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
incoming.Version = "test-2"
|
||||
incoming.Default = "c"
|
||||
incoming.Voices = incoming.Voices[:1]
|
||||
incoming.Voices[0].Name = "c"
|
||||
raw, _ := json.Marshal(incoming)
|
||||
archive := voiceZip(t, map[string][]byte{"manifest.json": raw, "pack-a/model.onnx": []byte("model"), "pack-a/tokens.txt": []byte("tokens"), "pack-a/lexicon.txt": []byte("lexicon"), "pack-a/phone.fst": []byte("fst")})
|
||||
repo, err := store.Import(archive)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(repo.Packs) != 3 || repo.Default != "a" || repo.Version != "test-2" {
|
||||
t.Fatal("import changed defaults or lost voices")
|
||||
}
|
||||
if _, err = store.Import(archive); err == nil {
|
||||
t.Fatal("duplicate accepted")
|
||||
}
|
||||
}
|
||||
func TestVoiceStoreRejectsTraversalAndBadHash(t *testing.T) {
|
||||
store := testVoiceStore(t)
|
||||
archive := voiceZip(t, map[string][]byte{"../escape": []byte("bad")})
|
||||
if _, err := store.Import(archive); err == nil {
|
||||
t.Fatal("traversal accepted")
|
||||
}
|
||||
archive = voiceZip(t, map[string][]byte{"manifest.json": []byte(strings.ReplaceAll(testManifest, "9372c470", "00000000")), "pack-a/model.onnx": []byte("tampered")})
|
||||
if _, err := store.Import(archive); err == nil {
|
||||
t.Fatal("invalid package accepted")
|
||||
}
|
||||
repo, err := LoadRepo(store.Root)
|
||||
if err != nil || len(repo.Packs) != 2 {
|
||||
t.Fatal("rejected upload changed live manifest")
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
package tts
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -37,9 +39,9 @@ const testManifest = `{
|
||||
"default": "a",
|
||||
"voices": [
|
||||
{"name": "a", "locale": "zh-CN", "label": "甲", "speakerId": 0, "quality": 300,
|
||||
"dir": "pack-a", "model": "model.onnx", "lexicon": "lexicon.txt", "ruleFsts": ["phone.fst"]},
|
||||
"dir": "pack-a", "sha256": "9372c470eeadd5ecd9c3c74c2b3cb633f8e2f2fad799250a0f70d652b6b825e4", "model": "model.onnx", "lexicon": "lexicon.txt", "ruleFsts": ["phone.fst"]},
|
||||
{"name": "b", "locale": "yue-HK", "label": "乙", "speakerId": 1, "quality": 300,
|
||||
"dir": "pack-b", "model": "model.onnx", "lexicon": "lexicon.txt", "ruleFsts": ["phone.fst"]}
|
||||
"dir": "pack-b", "sha256": "9372c470eeadd5ecd9c3c74c2b3cb633f8e2f2fad799250a0f70d652b6b825e4", "model": "model.onnx", "lexicon": "lexicon.txt", "ruleFsts": ["phone.fst"]}
|
||||
]
|
||||
}`
|
||||
|
||||
@@ -91,8 +93,8 @@ func TestLoadRepoDuplicateName(t *testing.T) {
|
||||
writeManifest(t, root, `{
|
||||
"version": "t", "default": "a",
|
||||
"voices": [
|
||||
{"name": "a", "locale": "zh-CN", "dir": "pack-a", "model": "model.onnx", "lexicon": "lexicon.txt"},
|
||||
{"name": "a", "locale": "yue-HK", "dir": "pack-a", "model": "model.onnx", "lexicon": "lexicon.txt"}
|
||||
{"name": "a", "locale": "zh-CN", "dir": "pack-a", "sha256": "9372c470eeadd5ecd9c3c74c2b3cb633f8e2f2fad799250a0f70d652b6b825e4", "model": "model.onnx", "lexicon": "lexicon.txt"},
|
||||
{"name": "a", "locale": "yue-HK", "dir": "pack-a", "sha256": "9372c470eeadd5ecd9c3c74c2b3cb633f8e2f2fad799250a0f70d652b6b825e4", "model": "model.onnx", "lexicon": "lexicon.txt"}
|
||||
]
|
||||
}`)
|
||||
if _, err := LoadRepo(root); err == nil {
|
||||
@@ -105,7 +107,7 @@ func TestLoadRepoDefaultFallsBackToFirst(t *testing.T) {
|
||||
writeVoiceFiles(t, root, "pack-a")
|
||||
writeManifest(t, root, `{
|
||||
"version": "t", "default": "missing",
|
||||
"voices": [{"name": "a", "locale": "zh-CN", "dir": "pack-a", "model": "model.onnx", "lexicon": "lexicon.txt"}]
|
||||
"voices": [{"name": "a", "locale": "zh-CN", "dir": "pack-a", "sha256": "9372c470eeadd5ecd9c3c74c2b3cb633f8e2f2fad799250a0f70d652b6b825e4", "model": "model.onnx", "lexicon": "lexicon.txt"}]
|
||||
}`)
|
||||
repo, err := LoadRepo(root)
|
||||
if err != nil {
|
||||
@@ -114,4 +116,48 @@ func TestLoadRepoDefaultFallsBackToFirst(t *testing.T) {
|
||||
if repo.Default != "a" {
|
||||
t.Fatalf("default %q, want a", repo.Default)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadRepoRejectsTampering(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
writeVoiceFiles(t, root, "pack-a")
|
||||
writeVoiceFiles(t, root, "pack-b")
|
||||
writeManifest(t, root, testManifest)
|
||||
if err := os.WriteFile(filepath.Join(root, "pack-a", "model.onnx"), []byte("tampered"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := LoadRepo(root); err == nil {
|
||||
t.Fatal("tampered model accepted")
|
||||
}
|
||||
}
|
||||
func TestLoadRepoRejectsEscape(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
outside := t.TempDir()
|
||||
writeVoiceFiles(t, outside, "pack-a")
|
||||
rel, err := filepath.Rel(root, filepath.Join(outside, "pack-a"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Marshal keeps Windows backslashes valid JSON.
|
||||
raw, _ := json.Marshal(Manifest{Version: "test", Voices: []VoiceEntry{{Name: "a", Dir: rel, Model: "model.onnx", SHA256: "9372c470eeadd5ecd9c3c74c2b3cb633f8e2f2fad799250a0f70d652b6b825e4"}}})
|
||||
writeManifest(t, root, string(raw))
|
||||
if _, err := LoadRepo(root); err == nil {
|
||||
t.Fatal("escaped model accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadRepoRejectsFrontendHashMismatch(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
writeVoiceFiles(t, root, "pack-a")
|
||||
writeVoiceFiles(t, root, "pack-b")
|
||||
var manifest Manifest
|
||||
if err := json.Unmarshal([]byte(testManifest), &manifest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manifest.Voices[0].Files = map[string]string{"tokens.txt": strings.Repeat("0", 64)}
|
||||
raw, _ := json.Marshal(manifest)
|
||||
writeManifest(t, root, string(raw))
|
||||
if _, err := LoadRepo(root); err == nil {
|
||||
t.Fatal("tampered frontend accepted")
|
||||
}
|
||||
}
|
||||
+119
-45
@@ -2,14 +2,17 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/subtle"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
@@ -23,18 +26,20 @@ const (
|
||||
minRate = 0.5
|
||||
maxRate = 2.0
|
||||
bodyLimit = 64 << 10
|
||||
maxQueue = 8
|
||||
maxQueue = 2
|
||||
maxThreads = 8
|
||||
)
|
||||
|
||||
type settings struct {
|
||||
listen string
|
||||
voicesDir string
|
||||
cacheDir string
|
||||
threads int
|
||||
queue int
|
||||
maxRunes int
|
||||
preload bool
|
||||
listen string
|
||||
voicesDir string
|
||||
cacheDir string
|
||||
threads int
|
||||
queue int
|
||||
maxRunes int
|
||||
preload bool
|
||||
apiToken string
|
||||
adminToken string
|
||||
}
|
||||
|
||||
func main() {
|
||||
@@ -62,11 +67,12 @@ func main() {
|
||||
}
|
||||
|
||||
s := &server{
|
||||
cfg: cfg,
|
||||
repo: repo,
|
||||
cache: cache,
|
||||
eng: eng,
|
||||
queue: make(chan struct{}, cfg.queue+1),
|
||||
cfg: cfg,
|
||||
repo: repo,
|
||||
cache: cache,
|
||||
eng: eng,
|
||||
queue: make(chan struct{}, cfg.queue+1),
|
||||
worker: make(chan struct{}, 1),
|
||||
}
|
||||
|
||||
srv := &http.Server{
|
||||
@@ -74,7 +80,7 @@ func main() {
|
||||
Handler: s.routes(),
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
WriteTimeout: 120 * time.Second,
|
||||
WriteTimeout: 180 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
|
||||
@@ -97,15 +103,19 @@ func main() {
|
||||
}
|
||||
|
||||
type server struct {
|
||||
cfg settings
|
||||
repo *tts.Repo
|
||||
cache *tts.Cache
|
||||
eng *engine
|
||||
queue chan struct{}
|
||||
cfg settings
|
||||
adminMu sync.Mutex
|
||||
repoMu sync.RWMutex
|
||||
repo *tts.Repo
|
||||
cache *tts.Cache
|
||||
eng *engine
|
||||
queue chan struct{}
|
||||
worker chan struct{}
|
||||
}
|
||||
|
||||
func (s *server) routes() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
s.adminRoutes(mux)
|
||||
mux.HandleFunc("GET /healthz", s.handleHealth)
|
||||
mux.HandleFunc("GET /voices", s.handleVoices)
|
||||
mux.HandleFunc("POST /tts", s.handleTTS)
|
||||
@@ -113,16 +123,18 @@ func (s *server) routes() http.Handler {
|
||||
}
|
||||
|
||||
func (s *server) handleHealth(w http.ResponseWriter, r *http.Request) {
|
||||
repo := s.repository()
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"status": "ok",
|
||||
"sherpaVersion": sherpa.GetVersion(),
|
||||
"manifestVersion": s.repo.Version,
|
||||
"defaultVoice": s.repo.Default,
|
||||
"voices": len(s.repo.Packs),
|
||||
"manifestVersion": repo.Version,
|
||||
"defaultVoice": repo.Default,
|
||||
"voices": len(repo.Packs),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *server) handleVoices(w http.ResponseWriter, r *http.Request) {
|
||||
repo := s.repository()
|
||||
type voiceInfo struct {
|
||||
Name string `json:"name"`
|
||||
Locale string `json:"locale"`
|
||||
@@ -130,18 +142,26 @@ func (s *server) handleVoices(w http.ResponseWriter, r *http.Request) {
|
||||
SpeakerID int `json:"speakerId"`
|
||||
Quality int `json:"quality"`
|
||||
}
|
||||
voices := make([]voiceInfo, 0, len(s.repo.Packs))
|
||||
for _, p := range s.repo.Packs {
|
||||
voices := make([]voiceInfo, 0, len(repo.Packs))
|
||||
for _, p := range repo.Packs {
|
||||
voices = append(voices, voiceInfo{p.Name, p.Locale, p.Label, p.SpeakerID, p.Quality})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"version": s.repo.Version,
|
||||
"default": s.repo.Default,
|
||||
"version": repo.Version,
|
||||
"default": repo.Default,
|
||||
"voices": voices,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *server) handleTTS(w http.ResponseWriter, r *http.Request) {
|
||||
repo := s.repository()
|
||||
if s.cfg.apiToken != "" && subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), []byte("Bearer "+s.cfg.apiToken)) != 1 {
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second)
|
||||
defer cancel()
|
||||
|
||||
var req struct {
|
||||
Text string `json:"text"`
|
||||
Voice string `json:"voice"`
|
||||
@@ -149,11 +169,16 @@ func (s *server) handleTTS(w http.ResponseWriter, r *http.Request) {
|
||||
Pitch *float64 `json:"pitch"`
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, bodyLimit)
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
if err := decoder.Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
||||
return
|
||||
}
|
||||
|
||||
if err := decoder.Decode(new(any)); err != io.EOF {
|
||||
writeError(w, http.StatusBadRequest, "body must contain one JSON value")
|
||||
return
|
||||
}
|
||||
text := strings.TrimSpace(req.Text)
|
||||
if text == "" {
|
||||
writeError(w, http.StatusBadRequest, "text is required")
|
||||
@@ -174,15 +199,10 @@ func (s *server) handleTTS(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
fSpeed, fPitch := float32(speed), float32(pitch)
|
||||
|
||||
pack := s.repo.Resolve(req.Voice)
|
||||
key := s.cache.Key(s.repo.Version, pack.Name, fSpeed, fPitch, text)
|
||||
pack := repo.Resolve(req.Voice)
|
||||
key := s.cache.Key(repo.Version, pack.Name, fSpeed, fPitch, text)
|
||||
|
||||
if data, ok := s.cache.Get(key); ok {
|
||||
setAudioHeaders(w, pack, s.repo.Version, tts.WAVSampleRate(data))
|
||||
w.Header().Set("X-Tts-Cache", "hit")
|
||||
w.Write(data)
|
||||
log.Printf("tts hit voice=%s runes=%d speed=%.2f pitch=%.2f bytes=%d",
|
||||
pack.Name, utf8.RuneCountInString(text), speed, pitch, len(data))
|
||||
if s.serveCached(w, r, key, pack, repo.Version) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -195,9 +215,27 @@ func (s *server) handleTTS(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
select {
|
||||
case s.worker <- struct{}{}:
|
||||
defer func() { <-s.worker }()
|
||||
case <-ctx.Done():
|
||||
writeError(w, http.StatusGatewayTimeout, "queue deadline exceeded")
|
||||
return
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
// An identical request may have filled the cache while we waited.
|
||||
if s.serveCached(w, r, key, pack, repo.Version) {
|
||||
return
|
||||
}
|
||||
start := time.Now()
|
||||
samples, rate, err := s.eng.synthesize(pack, text, fSpeed, fPitch)
|
||||
samples, rate, err := s.eng.synthesize(ctx, pack, text, fSpeed, fPitch)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
writeError(w, http.StatusGatewayTimeout, "synthesis deadline exceeded")
|
||||
return
|
||||
}
|
||||
log.Printf("tts failed voice=%s: %v", pack.Name, err)
|
||||
writeError(w, http.StatusInternalServerError, "synthesis failed")
|
||||
return
|
||||
@@ -208,7 +246,7 @@ func (s *server) handleTTS(w http.ResponseWriter, r *http.Request) {
|
||||
log.Printf("cache write: %v", err)
|
||||
}
|
||||
|
||||
setAudioHeaders(w, pack, s.repo.Version, rate)
|
||||
setAudioHeaders(w, pack, repo.Version, rate)
|
||||
w.Header().Set("X-Tts-Cache", "miss")
|
||||
w.Write(data)
|
||||
|
||||
@@ -227,13 +265,21 @@ func setAudioHeaders(w http.ResponseWriter, pack *tts.VoicePack, version string,
|
||||
|
||||
func loadSettings() settings {
|
||||
cfg := settings{
|
||||
listen: env("TTS_LISTEN", ":8080"),
|
||||
voicesDir: env("TTS_VOICES", "/opt/tts/voices"),
|
||||
cacheDir: env("TTS_CACHE", "/var/cache/tts"),
|
||||
threads: envInt("TTS_THREADS", 2),
|
||||
queue: envInt("TTS_QUEUE", 2),
|
||||
maxRunes: envInt("TTS_MAX_TEXT", 300),
|
||||
preload: env("TTS_PRELOAD", "1") != "0",
|
||||
listen: env("TTS_LISTEN", ":8080"),
|
||||
voicesDir: env("TTS_VOICES", "/opt/tts/voices"),
|
||||
cacheDir: env("TTS_CACHE", "/var/cache/tts"),
|
||||
threads: envInt("TTS_THREADS", 2),
|
||||
queue: envInt("TTS_QUEUE", 2),
|
||||
maxRunes: envInt("TTS_MAX_TEXT", 300),
|
||||
preload: env("TTS_PRELOAD", "1") != "0",
|
||||
apiToken: os.Getenv("TTS_API_TOKEN"),
|
||||
adminToken: os.Getenv("TTS_ADMIN_TOKEN"),
|
||||
}
|
||||
if cfg.adminToken != "" && cfg.adminToken == cfg.apiToken {
|
||||
log.Fatal("TTS_ADMIN_TOKEN must differ from TTS_API_TOKEN")
|
||||
}
|
||||
if env("TTS_REQUIRE_AUTH", "0") == "1" && strings.TrimSpace(cfg.apiToken) == "" {
|
||||
log.Fatal("TTS_API_TOKEN is required when TTS_REQUIRE_AUTH=1")
|
||||
}
|
||||
if cfg.threads < 1 || cfg.threads > maxThreads {
|
||||
log.Fatalf("TTS_THREADS must be 1..%d", maxThreads)
|
||||
@@ -284,4 +330,32 @@ func writeJSON(w http.ResponseWriter, status int, body any) {
|
||||
|
||||
func writeError(w http.ResponseWriter, status int, msg string) {
|
||||
writeJSON(w, status, map[string]string{"error": msg})
|
||||
}
|
||||
}
|
||||
func (s *server) serveCached(w http.ResponseWriter, r *http.Request, key string, pack *tts.VoicePack, version string) bool {
|
||||
file, err := s.cache.Open(key)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer file.Close()
|
||||
header := make([]byte, 44)
|
||||
if _, err := io.ReadFull(file, header); err != nil {
|
||||
return false
|
||||
}
|
||||
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
||||
return false
|
||||
}
|
||||
info, err := file.Stat()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
setAudioHeaders(w, pack, version, tts.WAVSampleRate(header))
|
||||
w.Header().Set("X-Tts-Cache", "hit")
|
||||
http.ServeContent(w, r, key+".wav", info.ModTime(), file)
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *server) repository() *tts.Repo {
|
||||
s.repoMu.RLock()
|
||||
defer s.repoMu.RUnlock()
|
||||
return s.repo
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"tts-server/internal/tts"
|
||||
)
|
||||
|
||||
func testServer(t *testing.T) *server {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
for _, name := range []string{"model.onnx", "tokens.txt"} {
|
||||
if err := os.WriteFile(filepath.Join(root, name), []byte(name), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
hash := sha256.Sum256([]byte("model.onnx"))
|
||||
manifest, _ := json.Marshal(tts.Manifest{Version: "test", Default: "a", Voices: []tts.VoiceEntry{{Name: "a", Locale: "zh-CN", Model: "model.onnx", SHA256: hex.EncodeToString(hash[:])}}})
|
||||
if err := os.WriteFile(filepath.Join(root, "manifest.json"), manifest, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo, err := tts.LoadRepo(root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cache, err := tts.NewCache(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &server{cfg: settings{maxRunes: 300, voicesDir: root}, repo: repo, cache: cache, eng: newEngine(1), queue: make(chan struct{}, 3), worker: make(chan struct{}, 1)}
|
||||
}
|
||||
func TestRejectUnauthorizedAndTrailingJSON(t *testing.T) {
|
||||
s := testServer(t)
|
||||
s.cfg.apiToken = "test-token"
|
||||
request := httptest.NewRequest("POST", "/tts", strings.NewReader(`{"text":"hello"}`))
|
||||
response := httptest.NewRecorder()
|
||||
s.routes().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusUnauthorized {
|
||||
t.Fatal(response.Code)
|
||||
}
|
||||
request = httptest.NewRequest("POST", "/tts", strings.NewReader(`{"text":"hello"} {}`))
|
||||
request.Header.Set("Authorization", "Bearer test-token")
|
||||
response = httptest.NewRecorder()
|
||||
s.routes().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusBadRequest {
|
||||
t.Fatal(response.Code)
|
||||
}
|
||||
}
|
||||
func TestCancelledQueueReleasesSlot(t *testing.T) {
|
||||
s := testServer(t)
|
||||
s.worker <- struct{}{}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
request := httptest.NewRequest("POST", "/tts", strings.NewReader(`{"text":"hello"}`)).WithContext(ctx)
|
||||
response := httptest.NewRecorder()
|
||||
s.routes().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusGatewayTimeout {
|
||||
t.Fatal(response.Code)
|
||||
}
|
||||
if len(s.queue) != 0 {
|
||||
t.Fatal("cancelled request leaked queue slot")
|
||||
}
|
||||
}
|
||||
func TestCacheHitDoesNotWaitForInference(t *testing.T) {
|
||||
s := testServer(t)
|
||||
key := s.cache.Key("test", "a", 1, 1, "hello")
|
||||
data := tts.EncodeWAV([]float32{0.1, 0.2}, 22050)
|
||||
if err := s.cache.Put(key, data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.worker <- struct{}{}
|
||||
request := httptest.NewRequest("POST", "/tts", strings.NewReader(`{"text":"hello"}`))
|
||||
response := httptest.NewRecorder()
|
||||
s.routes().ServeHTTP(response, request)
|
||||
if response.Code != 200 || response.Header().Get("X-Tts-Cache") != "hit" || response.Body.Len() != len(data) {
|
||||
t.Fatal("cache response invalid")
|
||||
}
|
||||
}
|
||||
func TestNativeSynthesis(t *testing.T) {
|
||||
dir := os.Getenv("TTS_TEST_VOICES")
|
||||
if dir == "" {
|
||||
t.Skip("set TTS_TEST_VOICES to run native model smoke test")
|
||||
}
|
||||
repo, err := tts.LoadRepo(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
engine := newEngine(2)
|
||||
defer engine.close()
|
||||
for _, pitch := range []float32{1, 0.5, 1.2, 2} {
|
||||
samples, rate, err := engine.synthesize(context.Background(), repo.DefaultPack(), "您好。现在时间是九点整。", 0.9, pitch)
|
||||
if err != nil || len(samples) == 0 || rate != 22050 {
|
||||
t.Fatalf("pitch=%v samples=%d rate=%d err=%v", pitch, len(samples), rate, err)
|
||||
}
|
||||
var energy float64
|
||||
for _, v := range samples {
|
||||
energy += float64(v * v)
|
||||
}
|
||||
if energy < 0.01 {
|
||||
t.Fatalf("silent output pitch=%v", pitch)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,6 @@
|
||||
limit_req_zone $binary_remote_addr zone=tts_requests:1m rate=2r/s;
|
||||
limit_conn_zone $binary_remote_addr zone=tts_connections:1m;
|
||||
|
||||
# TTS 在线合成(k3s NodePort 30810)反向代理
|
||||
# 证书由 certbot 签发(自动续期):
|
||||
# certbot certonly --webroot -w /var/www/certbot -d tts.ttstd.com
|
||||
@@ -28,8 +31,23 @@ server {
|
||||
|
||||
client_max_body_size 1m;
|
||||
|
||||
# 服务本身无鉴权,对外开放前需自行加访问控制
|
||||
# Admin uploads are streamed to the service and independently authenticated.
|
||||
location = /admin/api/import {
|
||||
client_max_body_size 256m;
|
||||
proxy_pass http://127.0.0.1:30810;
|
||||
proxy_http_version 1.1;
|
||||
proxy_request_buffering off;
|
||||
proxy_read_timeout 180s;
|
||||
proxy_send_timeout 180s;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# POST /tts 使用 TTS_API_TOKEN Bearer 鉴权,部署前创建 Kubernetes Secret
|
||||
location / {
|
||||
limit_req zone=tts_requests burst=4 nodelay;
|
||||
limit_req_status 429;
|
||||
limit_conn tts_connections 4;
|
||||
proxy_pass http://127.0.0.1:30810;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
|
||||
Reference in new issue
Block a user