- android-engine:TextToSpeechService 引擎,含设置页、语音包导入(SHA-256 校验)与预热 - server:Go CPU 合成服务与部署文件 - test-client:端到端验证客户端 - 模型与语音包不入库,见 models/README.md
287 lines
7.0 KiB
Go
287 lines
7.0 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"strconv"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
"unicode/utf8"
|
|
|
|
sherpa "github.com/k2-fsa/sherpa-onnx-go/v2/sherpa_onnx"
|
|
|
|
"tts-server/internal/tts"
|
|
)
|
|
|
|
const (
|
|
minRate = 0.5
|
|
maxRate = 2.0
|
|
bodyLimit = 64 << 10
|
|
maxQueue = 8
|
|
maxThreads = 8
|
|
)
|
|
|
|
type settings struct {
|
|
listen string
|
|
voicesDir string
|
|
cacheDir string
|
|
threads int
|
|
queue int
|
|
maxRunes int
|
|
preload bool
|
|
}
|
|
|
|
func main() {
|
|
log.SetFlags(log.LstdFlags | log.Lmicroseconds)
|
|
cfg := loadSettings()
|
|
|
|
repo, err := tts.LoadRepo(cfg.voicesDir)
|
|
if err != nil {
|
|
log.Fatalf("voices: %v", err)
|
|
}
|
|
log.Printf("manifest %q: %d voice(s), default %q", repo.Version, len(repo.Packs), repo.Default)
|
|
|
|
cache, err := tts.NewCache(cfg.cacheDir)
|
|
if err != nil {
|
|
log.Fatalf("cache: %v", err)
|
|
}
|
|
|
|
eng := newEngine(cfg.threads)
|
|
if cfg.preload {
|
|
start := time.Now()
|
|
if err := eng.preload(repo.DefaultPack()); err != nil {
|
|
log.Fatalf("preload %q: %v", repo.Default, err)
|
|
}
|
|
log.Printf("preloaded %q in %s", repo.Default, time.Since(start).Round(time.Millisecond))
|
|
}
|
|
|
|
s := &server{
|
|
cfg: cfg,
|
|
repo: repo,
|
|
cache: cache,
|
|
eng: eng,
|
|
queue: make(chan struct{}, cfg.queue+1),
|
|
}
|
|
|
|
srv := &http.Server{
|
|
Addr: cfg.listen,
|
|
Handler: s.routes(),
|
|
ReadHeaderTimeout: 5 * time.Second,
|
|
ReadTimeout: 15 * time.Second,
|
|
WriteTimeout: 120 * time.Second,
|
|
IdleTimeout: 60 * time.Second,
|
|
}
|
|
|
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
|
defer stop()
|
|
|
|
go func() {
|
|
log.Printf("listening on %s", cfg.listen)
|
|
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
log.Fatalf("http: %v", err)
|
|
}
|
|
}()
|
|
|
|
<-ctx.Done()
|
|
stopCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
|
defer cancel()
|
|
_ = srv.Shutdown(stopCtx)
|
|
eng.close()
|
|
log.Printf("stopped")
|
|
}
|
|
|
|
type server struct {
|
|
cfg settings
|
|
repo *tts.Repo
|
|
cache *tts.Cache
|
|
eng *engine
|
|
queue chan struct{}
|
|
}
|
|
|
|
func (s *server) routes() http.Handler {
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("GET /healthz", s.handleHealth)
|
|
mux.HandleFunc("GET /voices", s.handleVoices)
|
|
mux.HandleFunc("POST /tts", s.handleTTS)
|
|
return mux
|
|
}
|
|
|
|
func (s *server) handleHealth(w http.ResponseWriter, r *http.Request) {
|
|
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),
|
|
})
|
|
}
|
|
|
|
func (s *server) handleVoices(w http.ResponseWriter, r *http.Request) {
|
|
type voiceInfo struct {
|
|
Name string `json:"name"`
|
|
Locale string `json:"locale"`
|
|
Label string `json:"label"`
|
|
SpeakerID int `json:"speakerId"`
|
|
Quality int `json:"quality"`
|
|
}
|
|
voices := make([]voiceInfo, 0, len(s.repo.Packs))
|
|
for _, p := range s.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,
|
|
"voices": voices,
|
|
})
|
|
}
|
|
|
|
func (s *server) handleTTS(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
Text string `json:"text"`
|
|
Voice string `json:"voice"`
|
|
Speed *float64 `json:"speed"`
|
|
Pitch *float64 `json:"pitch"`
|
|
}
|
|
r.Body = http.MaxBytesReader(w, r.Body, bodyLimit)
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
|
return
|
|
}
|
|
|
|
text := strings.TrimSpace(req.Text)
|
|
if text == "" {
|
|
writeError(w, http.StatusBadRequest, "text is required")
|
|
return
|
|
}
|
|
if n := utf8.RuneCountInString(text); n > s.cfg.maxRunes {
|
|
writeError(w, http.StatusBadRequest, "text exceeds "+strconv.Itoa(s.cfg.maxRunes)+" characters")
|
|
return
|
|
}
|
|
|
|
speed := 1.0
|
|
if req.Speed != nil {
|
|
speed = clamp(*req.Speed)
|
|
}
|
|
pitch := 1.0
|
|
if req.Pitch != nil {
|
|
pitch = clamp(*req.Pitch)
|
|
}
|
|
fSpeed, fPitch := float32(speed), float32(pitch)
|
|
|
|
pack := s.repo.Resolve(req.Voice)
|
|
key := s.cache.Key(s.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))
|
|
return
|
|
}
|
|
|
|
select {
|
|
case s.queue <- struct{}{}:
|
|
defer func() { <-s.queue }()
|
|
default:
|
|
w.Header().Set("Retry-After", "1")
|
|
writeError(w, http.StatusTooManyRequests, "busy, retry later")
|
|
return
|
|
}
|
|
|
|
start := time.Now()
|
|
samples, rate, err := s.eng.synthesize(pack, text, fSpeed, fPitch)
|
|
if err != nil {
|
|
log.Printf("tts failed voice=%s: %v", pack.Name, err)
|
|
writeError(w, http.StatusInternalServerError, "synthesis failed")
|
|
return
|
|
}
|
|
elapsed := time.Since(start)
|
|
data := tts.EncodeWAV(samples, rate)
|
|
if err := s.cache.Put(key, data); err != nil {
|
|
log.Printf("cache write: %v", err)
|
|
}
|
|
|
|
setAudioHeaders(w, pack, s.repo.Version, rate)
|
|
w.Header().Set("X-Tts-Cache", "miss")
|
|
w.Write(data)
|
|
|
|
audioSeconds := float64(len(samples)) / float64(rate)
|
|
log.Printf("tts miss voice=%s runes=%d speed=%.2f pitch=%.2f audio=%.2fs synth=%s rtf=%.2f",
|
|
pack.Name, utf8.RuneCountInString(text), speed, pitch, audioSeconds,
|
|
elapsed.Round(time.Millisecond), elapsed.Seconds()/audioSeconds)
|
|
}
|
|
|
|
func setAudioHeaders(w http.ResponseWriter, pack *tts.VoicePack, version string, sampleRate int) {
|
|
w.Header().Set("Content-Type", "audio/wav")
|
|
w.Header().Set("X-Tts-Voice", pack.Name)
|
|
w.Header().Set("X-Tts-Voice-Version", version)
|
|
w.Header().Set("X-Tts-Sample-Rate", strconv.Itoa(sampleRate))
|
|
}
|
|
|
|
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",
|
|
}
|
|
if cfg.threads < 1 || cfg.threads > maxThreads {
|
|
log.Fatalf("TTS_THREADS must be 1..%d", maxThreads)
|
|
}
|
|
if cfg.queue < 0 || cfg.queue > maxQueue {
|
|
log.Fatalf("TTS_QUEUE must be 0..%d", maxQueue)
|
|
}
|
|
if cfg.maxRunes < 1 || cfg.maxRunes > 2000 {
|
|
log.Fatalf("TTS_MAX_TEXT must be 1..2000")
|
|
}
|
|
return cfg
|
|
}
|
|
|
|
func env(key, def string) string {
|
|
if v := os.Getenv(key); v != "" {
|
|
return v
|
|
}
|
|
return def
|
|
}
|
|
|
|
func envInt(key string, def int) int {
|
|
v := os.Getenv(key)
|
|
if v == "" {
|
|
return def
|
|
}
|
|
n, err := strconv.Atoi(v)
|
|
if err != nil {
|
|
log.Fatalf("%s must be an integer: %v", key, err)
|
|
}
|
|
return n
|
|
}
|
|
|
|
func clamp(v float64) float64 {
|
|
if v < minRate {
|
|
return minRate
|
|
}
|
|
if v > maxRate {
|
|
return maxRate
|
|
}
|
|
return v
|
|
}
|
|
|
|
func writeJSON(w http.ResponseWriter, status int, body any) {
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(body)
|
|
}
|
|
|
|
func writeError(w http.ResponseWriter, status int, msg string) {
|
|
writeJSON(w, status, map[string]string{"error": msg})
|
|
} |