forked from yihong0618/xiaogpt
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathutil.go
100 lines (85 loc) · 2.52 KB
/
util.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
package xiaobot
import (
"errors"
"net"
"net/url"
"os"
"regexp"
"strings"
"time"
)
//var noElapseChars = regexp.MustCompile(`([「」『』《》“”'\"()()]|(?<!-)-(?!-))`)
var regex1 = regexp.MustCompile(`[「」『』《》“”'\"()()]`)
var regex2 = regexp.MustCompile(`(^|[^-])-($|[^-])`)
// calculateTtsElapse returns the elapsed time for TTS
func calculateTtsElapse(text string) time.Duration {
speed := 4.5
// Replace the first part of the regex
result := regex1.ReplaceAllString(text, "")
// Replace the second part of the regex
result = regex2.ReplaceAllString(result, "")
v := float64(len(result)) / speed
return time.Duration(v+1) * time.Second
}
var endingPunctuations = []string{"。", "?", "!", ";", ".", "?", "!", ";"}
func splitSentences(textStream <-chan string) <-chan string {
result := make(chan string)
go func() {
cur := ""
for text := range textStream {
cur += text
for _, punc := range endingPunctuations {
if strings.HasSuffix(cur, punc) {
result <- cur
cur = ""
break
}
}
}
if cur != "" {
result <- cur
}
close(result)
}()
return result
}
func findKeyByPartialString(dictionary map[string]string, partialKey string) string {
for key, value := range dictionary {
if strings.Contains(partialKey, key) {
return value
}
}
return ""
}
func validateProxy(proxyStr string) error {
parsed, err := url.Parse(proxyStr)
if err != nil {
return err
}
if parsed.Scheme != "http" && parsed.Scheme != "https" {
return errors.New("Proxy scheme must be http or https")
}
if parsed.Hostname() == "" || parsed.Port() == "" {
return errors.New("Proxy hostname and port must be set")
}
return nil
}
func getHostname() string {
if hostname, exists := os.LookupEnv("XIAOGPT_HOSTNAME"); exists {
return hostname
}
conn, err := net.Dial("udp", "8.8.8.8:80")
if err != nil {
return ""
}
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr)
return localAddr.IP.String()
}
func Normalize(message string) string {
message = strings.TrimSpace(message)
message = strings.ReplaceAll(message, " ", "--")
message = strings.ReplaceAll(message, "\n", ",")
message = strings.ReplaceAll(message, "\"", ",")
return message
}