From f2455f92b6c45cb674be66528fbbd3852fea0319 Mon Sep 17 00:00:00 2001 From: zuoban <1061669148@qq.com> Date: Wed, 17 Apr 2024 14:14:19 +0800 Subject: [PATCH] initial commit --- .idea/.gitignore | 8 + .idea/fastRequestFreeCurrentProjectConfig.xml | 8 + .idea/modules.xml | 8 + .idea/tts.iml | 9 + .idea/vcs.xml | 6 + Dockerfile | 35 +++ go.mod | 36 +++ go.sum | 93 +++++++ handlers/handlers.go | 74 ++++++ main.go | 13 + routes/routes.go | 20 ++ script/build.sh | 1 + templates/index.html | 17 ++ utils/utils.go | 227 ++++++++++++++++++ 14 files changed, 555 insertions(+) create mode 100644 .idea/.gitignore create mode 100644 .idea/fastRequestFreeCurrentProjectConfig.xml create mode 100644 .idea/modules.xml create mode 100644 .idea/tts.iml create mode 100644 .idea/vcs.xml create mode 100644 Dockerfile create mode 100644 go.mod create mode 100644 go.sum create mode 100644 handlers/handlers.go create mode 100644 main.go create mode 100644 routes/routes.go create mode 100644 script/build.sh create mode 100644 templates/index.html create mode 100644 utils/utils.go diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..35410ca --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# 默认忽略的文件 +/shelf/ +/workspace.xml +# 基于编辑器的 HTTP 客户端请求 +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/fastRequestFreeCurrentProjectConfig.xml b/.idea/fastRequestFreeCurrentProjectConfig.xml new file mode 100644 index 0000000..892c707 --- /dev/null +++ b/.idea/fastRequestFreeCurrentProjectConfig.xml @@ -0,0 +1,8 @@ + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..7001211 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/tts.iml b/.idea/tts.iml new file mode 100644 index 0000000..5e764c4 --- /dev/null +++ b/.idea/tts.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..cbc02eb --- /dev/null +++ b/Dockerfile @@ -0,0 +1,35 @@ +# 使用官方 Golang 镜像作为构建环境 +FROM golang:1.22-alpine as builder +ENV CGO_ENABLED 0 +ENV GOPROXY https://goproxy.cn,direct + +# 设置工作目录 +WORKDIR /app + +# 将 go.mod 和 go.sum 文件复制到工作目录 +COPY go.mod go.sum ./ + +# 下载所有依赖项 +RUN go mod download + +# 将源代码复制到工作目录 +COPY . . + +# 构建 Go 应用程序 +RUN go build -o main . && ls + + +# 使用 scratch 作为基础镜像 +FROM alpine + +# 从 builder 阶段复制可执行文件到当前阶段 +COPY --from=builder /app/main . +COPY --from=builder /app/templates ./templates +RUN apk update --no-cache && apk add --no-cache ca-certificates +ENV TZ Asia/Shanghai + +# 暴露端口 +EXPOSE 8080 + +# 运行应用程序 +CMD ["./main"] \ No newline at end of file diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..7972028 --- /dev/null +++ b/go.mod @@ -0,0 +1,36 @@ +module tts + +go 1.22 + +require github.com/google/uuid v1.6.0 + +require ( + github.com/bytedance/sonic v1.11.4 // indirect + github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect + github.com/cloudwego/base64x v0.1.0 // indirect + github.com/cloudwego/iasm v0.1.1 // indirect + github.com/gabriel-vasile/mimetype v1.4.3 // indirect + github.com/gin-contrib/sse v0.1.0 // indirect + github.com/gin-gonic/gin v1.9.1 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.19.0 // indirect + github.com/goccy/go-json v0.10.2 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.2.7 // indirect + github.com/leodido/go-urn v1.4.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/pelletier/go-toml/v2 v2.2.1 // indirect + github.com/sirupsen/logrus v1.9.3 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.2.12 // indirect + golang.org/x/arch v0.7.0 // indirect + golang.org/x/crypto v0.22.0 // indirect + golang.org/x/net v0.24.0 // indirect + golang.org/x/sys v0.19.0 // indirect + golang.org/x/text v0.14.0 // indirect + google.golang.org/protobuf v1.33.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..49236ec --- /dev/null +++ b/go.sum @@ -0,0 +1,93 @@ +github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= +github.com/bytedance/sonic v1.10.0-rc/go.mod h1:ElCzW+ufi8qKqNW0FY314xriJhyJhuoJ3gFZdAHF7NM= +github.com/bytedance/sonic v1.11.4 h1:8+OMLSSDDm2/qJc6ld5K5Sm62NK9VHcUKk0NzBoMAM4= +github.com/bytedance/sonic v1.11.4/go.mod h1:YrWEqYtlBPS6LUA0vpuG79a1trsh4Ae41uWUWUreHhE= +github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= +github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= +github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d h1:77cEq6EriyTZ0g/qfRdp61a3Uu/AWrgIq2s0ClJV1g0= +github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d/go.mod h1:8EPpVsBuRksnlj1mLy4AWzRNQYxauNi62uWcE3to6eA= +github.com/chenzhuoyu/iasm v0.9.0/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog= +github.com/cloudwego/base64x v0.1.0 h1:Tg5q9tq1khq9Y9UwfoC6zkHK0FypN2GLDvhqFceOL8U= +github.com/cloudwego/base64x v0.1.0/go.mod h1:lM8nFiNbg74QgesNo6EAtv8N9tlRjBWExmHoNDa3PkU= +github.com/cloudwego/iasm v0.0.9/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY= +github.com/cloudwego/iasm v0.1.1 h1:Py/XoYVR3xFd2pXmvmOnoS5vHTlYT9SnGK28ES8JOIk= +github.com/cloudwego/iasm v0.1.1/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0= +github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk= +github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg= +github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.19.0 h1:ol+5Fu+cSq9JD7SoSqe04GMI92cbn0+wvQ3bZ8b/AU4= +github.com/go-playground/validator/v10 v10.19.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM= +github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= +github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM= +github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= +github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= +github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= +github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/pelletier/go-toml/v2 v2.2.1 h1:9TA9+T8+8CUCO2+WYnDLCgrYi9+omqKXyjDtosvtEhg= +github.com/pelletier/go-toml/v2 v2.2.1/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= +github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= +github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/arch v0.7.0 h1:pskyeJh/3AmoQ8CPE95vxHLqp1G1GfGNXTmcl9NEKTc= +golang.org/x/arch v0.7.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= +golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30= +golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M= +golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w= +golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o= +golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= +google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/handlers/handlers.go b/handlers/handlers.go new file mode 100644 index 0000000..ad322c1 --- /dev/null +++ b/handlers/handlers.go @@ -0,0 +1,74 @@ +package handlers + +import ( + "github.com/gin-gonic/gin" + "net/http" + "tts/utils" +) + +func GetVoiceList(c *gin.Context) { + locale := c.Query("locale") + voices, err := utils.VoiceList() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + if locale != "" { + filteredVoices := make([]interface{}, 0) + for _, voice := range voices { + if voice.(map[string]interface{})["Locale"].(string) == locale { + filteredVoices = append(filteredVoices, voice) + } + } + voices = filteredVoices + } + + c.JSON(http.StatusOK, gin.H{"voices": voices}) +} + +func SynthesizeVoice(c *gin.Context) { + text := c.Query("t") + voiceName := c.DefaultQuery("v", "zh-CN-XiaoxiaoMultilingualNeural") + rate := c.DefaultQuery("r", "0") + pitch := c.DefaultQuery("p", "0") + outputFormat := c.DefaultQuery("o", "audio-24khz-48kbitrate-mono-mp3") + + voice, err := utils.GetVoice(text, voiceName, rate, pitch, outputFormat) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.Data(http.StatusOK, "audio/mpeg", voice) +} + +func Index(c *gin.Context) { + c.HTML(http.StatusOK, "index.html", gin.H{ + "title": "TTS", + }) +} + +type SynthesizeVoiceRequest struct { + Text string `json:"t"` + VoiceName string `json:"v"` + Rate string `json:"r"` + Pitch string `json:"p"` + OutputFormat string `json:"o"` +} + +func SynthesizeVoicePost(c *gin.Context) { + var request SynthesizeVoiceRequest + if err := c.BindJSON(&request); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + voice, err := utils.GetVoice(request.Text, request.VoiceName, request.Rate, request.Pitch, request.OutputFormat) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.Data(http.StatusOK, "audio/mpeg", voice) +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..aa4f905 --- /dev/null +++ b/main.go @@ -0,0 +1,13 @@ +package main + +import ( + "tts/routes" +) + +func main() { + router := routes.SetupRouter() + err := router.Run(":8080") + if err != nil { + panic(err) + } +} diff --git a/routes/routes.go b/routes/routes.go new file mode 100644 index 0000000..0c29669 --- /dev/null +++ b/routes/routes.go @@ -0,0 +1,20 @@ +package routes + +import ( + "github.com/gin-gonic/gin" + "tts/handlers" +) + +func SetupRouter() *gin.Engine { + router := gin.Default() + + // 加载模板文件 + router.LoadHTMLGlob("templates/*") + + router.GET("/voices", handlers.GetVoiceList) + router.POST("/tts", handlers.SynthesizeVoicePost) + router.GET("/tts", handlers.SynthesizeVoice) + router.GET("/", handlers.Index) + + return router +} diff --git a/script/build.sh b/script/build.sh new file mode 100644 index 0000000..35c0f34 --- /dev/null +++ b/script/build.sh @@ -0,0 +1 @@ +docker buildx build --platform linux/amd64,linux/arm64 --tag zuoban/zb-tts .. \ No newline at end of file diff --git a/templates/index.html b/templates/index.html new file mode 100644 index 0000000..b1d5601 --- /dev/null +++ b/templates/index.html @@ -0,0 +1,17 @@ + + + + + TTS + + +

支持接口

+ + + \ No newline at end of file diff --git a/utils/utils.go b/utils/utils.go new file mode 100644 index 0000000..05852e4 --- /dev/null +++ b/utils/utils.go @@ -0,0 +1,227 @@ +package utils + +import ( + "bytes" + "crypto/hmac" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "github.com/google/uuid" + "github.com/sirupsen/logrus" + "io" + "net/http" + "net/url" + "strings" + "time" +) + +var ( + log = logrus.New() + client = &http.Client{} + voiceListCache []interface{} + cacheDuration = 1 * time.Hour // 缓存持续时间 +) + +func init() { + ticker := time.NewTicker(cacheDuration) + go func() { + for range ticker.C { + voiceListCache = nil + } + }() +} + +const ( + endpointURL = "https://dev.microsofttranslator.com/apps/endpoint?api-version=1.0" + voicesListURL = "https://eastus.api.speech.microsoft.com/cognitiveservices/voices/list" + userAgent = "okhttp/4.5.0" + clientVersion = "4.0.530a 5fe1dc6c" + userId = "0f04d16a175c411e" + homeGeographicRegion = "zh-Hans-CN" + clientTraceId = "aab069b9-70a7-4844-a734-96cd78d94be9" + voiceDecodeKey = "oik6PdDdMnOXemTbwvMn9de/h9lFnfBaCWbGMMZqqoSaQaqUOqjVGm5NqsmjcBI1x+sS9ugjB55HEJWRiFXYFw==" + defaultVoiceName = "zh-CN-XiaoxiaoMultilingualNeural" + defaultRate = "0" + defaultPitch = "0" + defaultOutputFormat = "audio-24khz-48kbitrate-mono-mp3" +) + +var ( + errEndpoint = errors.New("failed to get endpoint") +) + +// GetEndpoint 获取语音合成服务的端点信息 +func GetEndpoint() (map[string]interface{}, error) { + signature := Sign(endpointURL) + headers := map[string]string{ + "Accept-Language": "zh-Hans", + "X-ClientVersion": clientVersion, + "X-UserId": userId, + "X-HomeGeographicRegion": homeGeographicRegion, + "X-ClientTraceId": clientTraceId, + "X-MT-Signature": signature, + "User-Agent": userAgent, + "Content-Type": "application/json; charset=utf-8", + "Content-Length": "0", + "Accept-Encoding": "gzip", + } + req, err := http.NewRequest("POST", endpointURL, nil) + if err != nil { + return nil, err + } + + for k, v := range headers { + req.Header.Set(k, v) + } + + resp, err := client.Do(req) + if err != nil { + log.Error("failed to do request: ", err) + return nil, err + } + defer resp.Body.Close() + + var result map[string]interface{} + err = json.NewDecoder(resp.Body).Decode(&result) + if err != nil { + return nil, err + } + + return result, nil +} + +// Sign 生成签名 +func Sign(urlStr string) string { + u := strings.Split(urlStr, "://")[1] + encodedUrl := url.QueryEscape(u) + uuidStr := strings.ReplaceAll(uuid.New().String(), "-", "") + formattedDate := strings.ToLower(time.Now().UTC().Format("Mon, 02 Jan 2006 15:04:05")) + "gmt" + bytesToSign := fmt.Sprintf("MSTranslatorAndroidApp%s%s%s", encodedUrl, formattedDate, uuidStr) + bytesToSign = strings.ToLower(bytesToSign) + decode, _ := base64.StdEncoding.DecodeString(voiceDecodeKey) + hash := hmac.New(sha256.New, decode) + hash.Write([]byte(bytesToSign)) + secretKey := hash.Sum(nil) + signBase64 := base64.StdEncoding.EncodeToString(secretKey) + return fmt.Sprintf("MSTranslatorAndroidApp::%s::%s::%s", signBase64, formattedDate, uuidStr) +} + +// GetVoice 获取语音合成结果 +// GetVoice 获取语音合成结果 +func GetVoice(text, voiceName, rate, pitch, outputFormat string) ([]byte, error) { + if voiceName == "" { + voiceName = defaultVoiceName + } + if rate == "" { + rate = defaultRate + } + if pitch == "" { + pitch = defaultPitch + } + if outputFormat == "" { + outputFormat = defaultOutputFormat + } + + endpoint, err := GetEndpoint() + if err != nil { + return nil, err + } + + u := fmt.Sprintf("https://%s.tts.speech.microsoft.com/cognitiveservices/v1", endpoint["r"]) + headers := map[string]string{ + "Authorization": endpoint["t"].(string), + "Content-Type": "application/ssml+xml", + "X-Microsoft-OutputFormat": outputFormat, + } + + ssml := GetSsml(text, voiceName, rate, pitch) + + req, err := http.NewRequest("POST", u, bytes.NewBufferString(ssml)) + if err != nil { + return nil, err + } + + for k, v := range headers { + req.Header.Set(k, v) + } + + resp, err := client.Do(req) + if err != nil { + log.Error("failed to do request: ", err) + return nil, err + } + defer resp.Body.Close() + + return io.ReadAll(resp.Body) +} + +// GetSsml 生成 SSML 格式的文本 +func GetSsml(text, voiceName, rate, pitch string) string { + return fmt.Sprintf(` + + + + %s + + + + `, voiceName, rate, pitch, text) +} + +// VoiceList 获取可用的语音列表 +func VoiceList() ([]interface{}, error) { + // 如果缓存中有值,直接返回缓存的结果 + if voiceListCache != nil { + return voiceListCache, nil + } + + headers := map[string]string{ + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.26", + "X-Ms-Useragent": "SpeechStudio/2021.05.001", + "Content-Type": "application/json", + "Origin": "https://azure.microsoft.com", + "Referer": "https://azure.microsoft.com", + } + + req, err := http.NewRequest("GET", voicesListURL, nil) + if err != nil { + return nil, err + } + + for k, v := range headers { + req.Header.Set(k, v) + } + + resp, err := client.Do(req) + if err != nil { + log.Error("failed to do request: ", err) + return nil, err + } + defer resp.Body.Close() + + var result []interface{} + err = json.NewDecoder(resp.Body).Decode(&result) + if err != nil { + return nil, err + } + + // 将结果存储到缓存中 + voiceListCache = result + + return result, nil +} + +func ByteCountIEC(b int64) string { + const unit = 1024 + if b < unit { + return fmt.Sprintf("%d B", b) + } + div, exp := int64(unit), 0 + for n := b / unit; n >= unit; n /= unit { + div *= unit + exp++ + } + return fmt.Sprintf("%.1f %ciB", float64(b)/float64(div), "KMGTPE"[exp]) +}