-
Notifications
You must be signed in to change notification settings - Fork 0
/
bertVits2.go
221 lines (205 loc) · 5.51 KB
/
bertVits2.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
package main
import (
"NothinBot/EasyBot"
"NothinBot/TimeLayout"
"bufio"
"encoding/json"
"errors"
"os"
"regexp"
"strings"
"time"
"github.com/moxcomic/ihttp"
log "github.com/sirupsen/logrus"
)
type bertVitsPost struct {
Command string `json:"command"`
Text string `json:"text"`
Speaker string `json:"speaker"`
Lang string `json:"language"`
SDP float32 `json:"sdp_ratio,omitempty"`
NS float32 `json:"noise_scale,omitempty"`
NSW float32 `json:"noise_scale_w,omitempty"`
LS float32 `json:"length_scale,omitempty"`
}
type bertVitsResp struct {
Code int `json:"code"`
Output string `json:"output"` // 音频base64, 直接发
Error string `json:"error"`
}
func (p *bertVitsPost) post() (*bertVitsResp, error) {
postData, _ := json.Marshal(p)
log.Debug("[BertVITS2] post: ", string(postData))
resp, err := ihttp.New().WithUrl("http://127.0.0.1:9876").
WithHeader("Content-Type", "application/json").
WithBody(postData).
Post().ToString()
if err != nil {
log.Error("[BertVITS2] ihttp error: ", err)
return nil, errors.New("BertVITS2后端未运行")
}
log.Debug("[BertVITS2] resp: ", resp)
r := &bertVitsResp{}
json.Unmarshal([]byte(resp), r)
return r, nil
}
func bertVits2TTS(ctx *EasyBot.CQMessage, text, speaker, lang string) (outputB64 string, err error) {
if text == "" {
return "", errors.New("empty text")
}
if speaker == "" {
speaker = "suijiSUI"
}
if lang == "" {
lang = "ZH"
}
p := &bertVitsPost{
Text: text,
Speaker: speaker,
Lang: lang,
SDP: 0.4,
}
resp, err := p.post()
var state string
switch {
case err != nil:
state = "后端未运行"
case resp.Error != "":
state = "Failed: " + resp.Error
err = errors.New(state)
case resp.Code != 0:
state = "Code 0 failed"
err = errors.New(state)
case resp.Output == "":
state = "Empty output"
err = errors.New(state)
default:
state = "Success"
}
p.recordHist(ctx.GroupID, ctx.UserID, ctx.GetCardOrNickname(), state)
if resp != nil {
return resp.Output, err
}
return "", err
}
// 记录历史
func (p *bertVitsPost) recordHist(groupId, userId int, userName, state string) {
nowTime := time.Now().Format(TimeLayout.L24)
text := strings.Replace(p.Text, "\n", "\\n", -1)
content := ConvertToCSV(nowTime, groupId, userId, userName, state, p.Speaker, p.Lang, text)
if err := appendToFile(
"tts_history.csv", content,
); err != nil {
log.Error("[BertVITS2] 历史写入失败")
bot.Log2SU.Error("[BertVITS2] 历史记录写入失败\n", content)
}
}
// 追加文本
func appendToFile(filePath, content string) error {
file, err := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
return err
}
defer file.Close()
writer := bufio.NewWriter(file)
_, err = writer.WriteString(content)
if err != nil {
return err
}
err = writer.Flush()
if err != nil {
return err
}
return nil
}
var (
langMap = map[string]string{
"中文": "ZH",
"汉语": "ZH",
"ZH": "ZH",
"日文": "JP",
"日语": "JP",
"JP": "JP",
}
)
func checkBertVITS2(ctx *EasyBot.CQMessage) {
//后端控制
matches := ctx.RegFindAllStringSubmatch(regexp.MustCompile(`^(unload|refresh|exit|卸载|清理|退出).*(模型|model)$`))
if len(matches) > 0 && ctx.IsPrivateSU() {
p := &bertVitsPost{}
switch matches[0][1] {
case "unload", "refresh", "卸载", "清理":
p.Command = "/unload"
case "exit", "退出":
p.Command = "/exit"
}
_, err := p.post()
if err == nil {
ctx.SendMsg("已执行")
} else {
ctx.SendMsg(err)
}
return
}
matches = ctx.RegFindAllStringSubmatch(regexp.MustCompile(`(?s)让?岁己(用(中文|汉语|ZH|日文|日语|JP))?(说|复述)\s*(.*)`))
if len(matches) > 0 {
// isInWhite := func() (is bool) {
// var v *viper.Viper
// for i := 0; i < len(v.GetStringSlice("bertVits.whiteList.group")); i++ { //群聊白名单
// if ctx.GroupID == v.GetInt(fmt.Sprint("bertVits.whiteList.group.", i)) {
// return true
// }
// }
// for i := 0; i < len(v.GetStringSlice("bertVits.whiteList.private")); i++ { //私聊白名单
// if ctx.UserID == v.GetInt(fmt.Sprint("bertVits.whiteList.private.", i)) {
// return true
// }
// }
// return false
// }()
// if !ctx.IsSU() && !isInWhite {
// ctx.SendMsg("[BertVITS2] Permission Denied")
// return
// }
lang := "ZH"
if l, ok := langMap[matches[0][2]]; ok {
lang = l
}
text := trimOuterQuotes(unescape.Replace(matches[0][4]))
replyMsg, err := ctx.GetReplyedMsg()
if replyMsg != nil && err == nil { //复述回复时无视内容
text = trimOuterQuotes(replyMsg.RawMessage)
}
sendVitsMsg(ctx, text, lang)
}
}
// 发送vits消息
func sendVitsMsg(ctx *EasyBot.CQMessage, text, lang string) error {
log.Debug("[BertVITS2] Vits text: ", text)
if len(strings.TrimSpace(text)) == 0 {
return ctx.SendMsgReply("[BertVITS2] 文本输入不可为空!")
}
outputB64, err := bertVits2TTS(ctx, text, "", lang)
if err != nil {
log.Error("[BertVITS2] 发生错误: ", err)
return ctx.SendMsgReply("[BertVITS2] 发生错误:", err.Error())
}
return ctx.SendMsg(bot.Utils.Format.VocalBase64(outputB64, true))
}
// 去除最外层一对互相匹配的引号
func trimOuterQuotes(s string) string {
runes := []rune(s)
if len(runes) < 2 {
return s
}
left := runes[0]
right := runes[(len(runes) - 1)]
if (left == '\'' && right == '\'') ||
(left == '`' && right == '`') ||
(left == '"' && right == '"') ||
(left == '“' && right == '”') ||
(left == '”' && right == '“') {
runes = runes[1 : len(runes)-1]
}
return string(runes)
}