/
main.go
335 lines (310 loc) · 9.1 KB
/
main.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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
package main
import (
"encoding/json"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
"github.com/bwmarrin/discordgo"
"github.com/go-shiori/go-readability"
"github.com/hyacinthus/mp3join"
"golang.org/x/sync/errgroup"
"io"
"math/rand"
"regexp"
"sync"
"log"
"net/http"
"os"
"os/signal"
"strings"
"time"
)
type ExtractorResponse struct {
Title string `json:"title"`
Text string `json:"text"`
}
type OpenAIRequest struct {
Model string `json:"model"`
Input string `json:"input"`
Voice string `json:"voice"`
}
type Event int
const (
Loading Event = iota
Done
)
const commandName = "speak"
var (
s *discordgo.Session
commands = []*discordgo.ApplicationCommand{
{
Name: commandName,
Description: "Grab the contents of a webpage and return an mp3 of the text being read",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionString,
Name: "url",
Description: "URL to read",
Required: true,
},
{
Type: discordgo.ApplicationCommandOptionString,
Name: "voice",
Description: "Voice to use",
Required: false,
Choices: []*discordgo.ApplicationCommandOptionChoice{
{Name: "Alloy (default)", Value: "alloy"},
{Name: "Echo", Value: "echo"},
{Name: "Fable", Value: "fable"},
{Name: "Onyx", Value: "onyx"},
{Name: "Nova", Value: "nova"},
{Name: "Shimmer", Value: "shimmer"},
},
},
},
},
}
commandHandlers = map[string]func(s *discordgo.Session, i *discordgo.InteractionCreate){
commandName: func(s *discordgo.Session, i *discordgo.InteractionCreate) {
options := i.ApplicationCommandData().Options
optionMap := make(map[string]*discordgo.ApplicationCommandInteractionDataOption, len(options))
for _, opt := range options {
optionMap[opt.Name] = opt
}
doError := func(e error) {
fmt.Printf("error: %+v\n", e)
_, _ = s.FollowupMessageCreate(i.Interaction, true, &discordgo.WebhookParams{
Content: "Something went wrong: " + e.Error(),
})
}
if option, ok := optionMap["url"]; ok {
url := option.StringValue()
err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Requesting contents of " + url,
},
})
if err != nil {
fmt.Printf("error: %+v\n", err)
return
}
extracted, err := getContents(url)
if err != nil {
doError(err)
return
}
chunks := textChunks(extracted.Text, 4095)
c := fmt.Sprintf("Calling OpenAI TTS API to get audio for '%s' (%d chunks)", extracted.Title, len(chunks))
_, err = s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{Content: &c})
if err != nil {
fmt.Printf("error: %+v\n", err)
return
}
voice := "alloy"
if v, ok := optionMap["voice"]; ok {
voice = v.StringValue()
}
chunksProgress := make([]string, len(chunks))
for i := range chunksProgress {
chunksProgress[i] = "◻️"
}
chunksLock := sync.Mutex{}
r, err := getAudioForChunks(chunks, voice, func(chunkIndex int, event Event) {
chunksLock.Lock()
if event == Loading {
chunksProgress[chunkIndex] = "🔵"
} else if event == Done {
chunksProgress[chunkIndex] = "✅"
}
c := "Progress: " + strings.Join(chunksProgress, "")
chunksLock.Unlock()
_, err = s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{Content: &c})
if err != nil {
fmt.Printf("error: %+v\n", err)
return
}
})
if err != nil {
doError(err)
return
}
mp3Url, uerr := uploadToS3(r, extracted.Title, voice)
if uerr != nil {
doError(uerr)
return
}
finalMessage := fmt.Sprintf("Here's the audio for '%s' (%s)\n\n%s", extracted.Title, url, mp3Url)
_, err = s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{Content: &finalMessage})
if err != nil {
fmt.Printf("error: %+v\n", err)
return
}
}
},
}
)
func init() {
var err error
token := os.Getenv("DISCORD_TOKEN")
s, err = discordgo.New("Bot " + token)
if err != nil {
log.Fatalf("Invalid bot parameters: %v", err)
}
s.AddHandler(func(s *discordgo.Session, i *discordgo.InteractionCreate) {
if h, ok := commandHandlers[i.ApplicationCommandData().Name]; ok {
h(s, i)
}
})
}
func main() {
s.AddHandler(func(s *discordgo.Session, r *discordgo.Ready) {
log.Printf("Logged in as: %v#%v", s.State.User.Username, s.State.User.Discriminator)
})
err := s.Open()
if err != nil {
log.Fatalf("Cannot open the session: %v", err)
}
guildID := os.Getenv("GUILD_ID")
registeredCommands := make([]*discordgo.ApplicationCommand, len(commands))
for i, v := range commands {
cmd, err := s.ApplicationCommandCreate(s.State.User.ID, guildID, v)
if err != nil {
log.Panicf("Cannot create '%v' command: %v", v.Name, err)
}
registeredCommands[i] = cmd
}
defer s.Close()
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt)
log.Println("Press Ctrl+C to exit")
<-stop
}
func getAudioForChunks(chunks []string, voice string, callback func(int, Event)) (io.Reader, error) {
lock := sync.Mutex{}
tempFiles := make([]*os.File, len(chunks))
var g errgroup.Group
sem := make(chan struct{}, 10) // create a buffered channel as semaphore
for ii, chunk := range chunks {
ii, chunk := ii, chunk // https://golang.org/doc/faq#closures_and_goroutines
sem <- struct{}{} // block if there are already 10 goroutines running
g.Go(func() error {
defer func() { <-sem }() // read from the channel when goroutine finishes
fmt.Println("Starting chunk", ii)
callback(ii, Loading)
body := getAudioForChunk(chunk, voice)
tempFile, err := os.CreateTemp("", "speech_*.mp3")
if err != nil {
return err
}
start := time.Now()
_, err = io.Copy(tempFile, body)
if err != nil {
return err
}
_ = body.Close()
lock.Lock()
tempFiles[ii] = tempFile
lock.Unlock()
fmt.Println("Writing to temp file took", time.Since(start), "chunk", ii)
callback(ii, Done)
return nil
})
}
// wait for all goroutines to finish
if err := g.Wait(); err != nil {
return nil, err
}
// drain the semaphore channel
for len(sem) > 0 {
<-sem
}
joiner := mp3join.New()
for _, tempFile := range tempFiles {
_, err := tempFile.Seek(0, 0)
if err != nil {
return nil, err
}
err = joiner.Append(tempFile)
defer tempFile.Close()
if err != nil {
return nil, err
}
}
return joiner.Reader(), nil
}
func textChunks(input string, chunkSize int) []string {
var chunks []string
for len(input) > 0 {
chunkLen := len(input)
if chunkLen > chunkSize {
chunkLen = chunkSize
// Find the last period in the current chunk
for i := chunkLen; i >= 0; i-- {
if input[i] == '.' {
chunkLen = i + 1
break
}
}
}
chunk := input[:chunkLen]
input = input[chunkLen:]
chunks = append(chunks, chunk)
}
return chunks
}
func getAudioForChunk(text, voice string) io.ReadCloser {
client := &http.Client{}
reqBody, _ := json.Marshal(OpenAIRequest{Model: "tts-1", Input: text, Voice: voice})
req, _ := http.NewRequest("POST", "https://api.openai.com/v1/audio/speech", strings.NewReader(string(reqBody)))
req.Header.Add("Authorization", "Bearer "+os.Getenv("OPENAI_API_KEY"))
req.Header.Add("Content-Type", "application/json")
fmt.Println("Calling OpenAI TTS API with len(text) =", len(text))
start := time.Now()
resp, _ := client.Do(req)
fmt.Println("Streaming response from OpenAI after", time.Since(start))
return resp.Body
}
func getContents(url string) (ExtractorResponse, error) {
var extractorResponse ExtractorResponse
article, err := readability.FromURL(url, 30*time.Second)
if err != nil {
return extractorResponse, err
}
preview := article.TextContent
if len(preview) > 100 {
preview = preview[:100]
}
fmt.Printf("Extracted text (first 100 characters): %s\n", preview)
return ExtractorResponse{Title: article.Title, Text: article.TextContent}, nil
}
func uploadToS3(f io.Reader, title, voice string) (string, error) {
sess, err := session.NewSession(&aws.Config{Region: aws.String(os.Getenv("AWS_REGION"))})
if err != nil {
return "", err
}
uploader := s3manager.NewUploader(sess)
reg, err := regexp.Compile("[^a-zA-Z0-9]+")
if err != nil {
return "", err
}
safeTitle := reg.ReplaceAllString(title, "-")
if len(safeTitle) > 42 {
safeTitle = safeTitle[:42]
}
r := rand.Intn(9000) + 1000
fileName := fmt.Sprintf("%s-%s-%s-%04d.mp3", time.Now().Format("2006-01-02"), safeTitle, voice, r)
fmt.Println("Uploading to S3 as", fileName)
start := time.Now()
_, err = uploader.Upload(&s3manager.UploadInput{
Bucket: aws.String(os.Getenv("S3_BUCKET")),
Key: aws.String("speecher/" + fileName),
Body: f,
})
if err != nil {
return "", fmt.Errorf("failed to upload file, %v", err)
}
fmt.Println("Upload to S3 took", time.Since(start))
return fmt.Sprintf("https://%s.s3.%s.amazonaws.com/speecher/%s", os.Getenv("S3_BUCKET"), os.Getenv("AWS_REGION"), fileName), nil
}