forked from kamushadenes/elevenlabs-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chunker.go
87 lines (75 loc) · 1.85 KB
/
chunker.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
package elevenlabs
import (
"bufio"
"fmt"
"io"
"strings"
)
type textChunk struct {
Text string `json:"text"`
TryTriggerGeneration bool `json:"try_trigger_generation"`
}
type streamingInputResponse struct {
Audio string `json:"audio"`
}
// readText reads from an io.Reader and sends the text over a channel.
func readText(r io.Reader, text chan<- string) {
scanner := bufio.NewScanner(r)
scanner.Split(bufio.ScanWords)
for scanner.Scan() {
word := scanner.Text()
text <- fmt.Sprintf("%s ", word)
}
close(text)
}
// textChunker reads chunks from a slice of strings and writes them to the provided io.Writer
func textChunker(chunks chan<- string, text <-chan string) {
splitters := []string{".", ",", "?", "!", ";", ":", "—", "-", "(", ")", "[", "]", "}", " "}
buffer := ""
for text := range text {
if endsWithAny(buffer, splitters) {
if endsWith(buffer, " ") {
chunks <- buffer
} else {
chunks <- buffer + " "
}
buffer = text
} else if startsWithAny(text, splitters) {
output := buffer + string(text[0])
if endsWith(output, " ") {
chunks <- output
} else {
chunks <- output + " "
}
buffer = text[1:]
} else {
buffer += text
}
}
if buffer != "" {
chunks <- buffer
}
close(chunks)
}
// endsWithAny checks if the given string ends with any of the specified substrings.
func endsWithAny(s string, subs []string) bool {
for _, sub := range subs {
if endsWith(s, sub) {
return true
}
}
return false
}
// startsWithAny checks if the given string starts with any of the specified substrings.
func startsWithAny(s string, subs []string) bool {
for _, sub := range subs {
if strings.HasPrefix(s, sub) {
return true
}
}
return false
}
// endsWith checks if the given string ends with the specified substring.
func endsWith(s, sub string) bool {
return strings.HasSuffix(s, sub)
}