Files
TtsSpeaker/server/internal/tts/voice.go
T

266 lines
6.6 KiB
Go

package tts
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
// Manifest mirrors android-engine voices.example/manifest.json so a single
// file configures both the Android engine and this server.
type Manifest struct {
Version string `json:"version"`
Default string `json:"default"`
Voices []VoiceEntry `json:"voices"`
}
type VoiceEntry struct {
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 {
Name string
Locale string
Label string
SpeakerID int
Quality int
ModelPath string
LexiconPath string
TokensPath string
DataDir string
RuleFsts string
}
type Repo struct {
Version string
Default string
Packs []*VoicePack
byName map[string]*VoicePack
}
func LoadRepo(root string) (*Repo, error) {
raw, err := os.ReadFile(filepath.Join(root, "manifest.json"))
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")
}
repo := &Repo{Version: m.Version, Default: m.Default, byName: make(map[string]*VoicePack, len(m.Voices))}
for _, e := range m.Voices {
if e.Name == "" {
return nil, fmt.Errorf("voice entry without name")
}
if _, dup := repo.byName[e.Name]; dup {
return nil, fmt.Errorf("duplicate voice %q", e.Name)
}
base := root
if e.Dir != "" {
base = filepath.Join(root, e.Dir)
}
tokens := e.Tokens
if tokens == "" {
tokens = "tokens.txt"
}
rules := make([]string, 0, len(e.RuleFsts))
for _, f := range e.RuleFsts {
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, ","),
}
if e.Lexicon != "" {
pack.LexiconPath = filepath.Join(base, e.Lexicon)
}
if e.DataDir != "" {
pack.DataDir = filepath.Join(base, e.DataDir)
}
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
}
repo.Packs = append(repo.Packs, pack)
repo.byName[pack.Name] = pack
}
if _, ok := repo.byName[repo.Default]; !ok {
repo.Default = repo.Packs[0].Name
}
return repo, nil
}
func (p *VoicePack) validate() error {
required := []string{p.ModelPath, p.TokensPath}
if p.LexiconPath != "" {
required = append(required, p.LexiconPath)
}
if p.DataDir != "" {
required = append(required, p.DataDir)
}
if p.RuleFsts != "" {
required = append(required, strings.Split(p.RuleFsts, ",")...)
}
for _, path := range required {
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
}
func (r *Repo) DefaultPack() *VoicePack {
return r.byName[r.Default]
}
// Resolve accepts a voice name or a BCP-47 language tag and falls back to the
// default pack, matching VoiceRepository.resolve on the Android side.
func (r *Repo) Resolve(requested string) *VoicePack {
requested = strings.TrimSpace(requested)
if requested == "" {
return r.DefaultPack()
}
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 {
if languageOf(p.Locale) == want {
return p
}
}
}
return r.DefaultPack()
}
func languageOf(locale string) string {
tag := strings.ToLower(strings.ReplaceAll(locale, "_", "-"))
if i := strings.IndexByte(tag, '-'); i >= 0 {
tag = tag[:i]
}
return normalizeLanguage(tag)
}
func normalizeLanguage(tag string) string {
tag = strings.ToLower(strings.ReplaceAll(strings.TrimSpace(tag), "_", "-"))
if i := strings.IndexByte(tag, '-'); i >= 0 {
tag = tag[:i]
}
switch tag {
case "cmn", "zho", "zh":
return "zh"
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
}