forked from TheTipo01/restRoberto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
105 lines (83 loc) · 2.22 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
package main
import (
"crypto/sha1"
"encoding/base32"
"fmt"
"github.com/fsnotify/fsnotify"
"github.com/gorilla/mux"
"github.com/spf13/viper"
"log"
"net/http"
"os"
"os/exec"
"strings"
)
const (
audioExtension = ".mp3"
)
var (
token = make(map[string]bool)
)
func init() {
viper.SetConfigName("config")
viper.SetConfigType("yml")
viper.AddConfigPath(".")
if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
// Config file not found
fmt.Println("Config file not found")
return
}
}
// Loads tokens
for _, t := range strings.Split(viper.GetString("token"), ",") {
token[t] = true
}
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
log.Println("Reloading config file")
token = make(map[string]bool)
for _, t := range strings.Split(viper.GetString("token"), ",") {
token[t] = true
}
})
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/audio", audio).Methods("GET")
r.PathPrefix("/temp/").Handler(http.StripPrefix("/temp/", http.FileServer(http.Dir("./temp"))))
http.Handle("/", r)
http.ListenAndServe(":8087", nil)
}
func audio(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
if !token[query.Get("token")] {
w.WriteHeader(http.StatusForbidden)
return
}
uuid := genAudio(query.Get("text"))
w.WriteHeader(http.StatusAccepted)
_, _ = fmt.Fprintf(w, "/temp/"+uuid+audioExtension)
}
// Generates audio from a string. Checks if it already exist before generating it
func gen(text string, uuid string) {
_, err := os.Stat("./temp/" + uuid + audioExtension)
if err != nil {
tts := exec.Command("balcon", "-i", "-o", "-enc", "utf8", "-n", "Roberto")
tts.Stdin = strings.NewReader(text)
ttsOut, _ := tts.StdoutPipe()
_ = tts.Start()
ffmpeg := exec.Command("ffmpeg", "-i", "pipe:0", "-f", "s16le", "-ar", "48000", "-ac", "2", "-f", "mp3", "./temp/"+uuid+audioExtension)
ffmpeg.Stdin = ttsOut
_ = ffmpeg.Run()
_ = tts.Wait()
}
}
// genAudio generates a mp3 file from a string, returning it's UUID (aka SHA1 hash of the text)
func genAudio(text string) string {
h := sha1.New()
h.Write([]byte(text))
uuid := strings.ToUpper(base32.HexEncoding.EncodeToString(h.Sum(nil)))
gen(text, uuid)
return uuid
}