-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
215 lines (182 loc) · 5.74 KB
/
api.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
package main
import (
"encoding/json"
"fmt"
//"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"strings"
"sync"
"time"
"regexp"
"github.com/dgrijalva/jwt-go"
)
type Result struct {
Output string `json:"output,omitempty"`
Error string `json:"error,omitempty"`
}
type Job struct {
ID string `json:"id"`
Phrase string `json:"phrase"`
Output string `json:"output,omitempty"`
CreatedAt time.Time `json:"created_at"`
FinishedAt time.Time `json:"finished_at,omitempty"`
Status string `json:"status,omitempty"`
}
type JobManager struct {
sync.RWMutex
Jobs map[string]*Job
}
func NewJobManager() *JobManager {
return &JobManager{
Jobs: make(map[string]*Job),
}
}
func (jm *JobManager) AddJob(phrase string) *Job {
jm.Lock()
defer jm.Unlock()
jobID := generateJobID()
job := &Job{
ID: jobID,
Phrase: phrase,
CreatedAt: time.Now(),
Status: "in_progress",
}
jm.Jobs[jobID] = job
return job
}
func (jm *JobManager) GetJob(jobID string) (*Job, error) {
jm.RLock()
defer jm.RUnlock()
job, ok := jm.Jobs[jobID]
if !ok {
return nil, fmt.Errorf("job %s not found", jobID)
}
return job, nil
}
func generateJobID() string {
return fmt.Sprintf("%d", time.Now().UnixNano())
}
func main() {
jobManager := NewJobManager()
http.HandleFunc("/job", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodPost:
var reqBody struct {
Phrase string `json:"phrase"`
}
if err := json.NewDecoder(r.Body).Decode(&reqBody); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
// Verify JWT token
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
tokenString := strings.Replace(authHeader, "Bearer ", "", 1)
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(os.Getenv("JWT_SECRET")), nil
})
if err != nil || !token.Valid {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
// Create job
job := jobManager.AddJob(reqBody.Phrase)
go func() {
//cmd := exec.Command("espeak", "-v", "en-us", "-s", "130", "-p", "50", "-g", "10", job.Phrase)
cmd := exec.Command("./main", "-m", "./WizardLM-7B-uncensored.ggml.q4_0.bin", "-p", job.Phrase, "-n", "512", "-s", "42", "-t", "3")
out, err := cmd.CombinedOutput()
inicio := job.Phrase
fin := "\\[end of text\\]"
// Construir el patrón de expresión regular
patron := fmt.Sprintf("%s(.*?)%s", inicio, fin)
re := regexp.MustCompile(patron)
// Buscar el contenido entre las dos frases
match := re.FindStringSubmatch(string(out))
if len(match) > 1 {
contenido := match[1]
//fmt.Println(string(out))
job.FinishedAt = time.Now()
if err != nil {
job.Status = "failed"
job.Output = contenido
log.Printf("error while processing job '%s': %v", job.ID, err)
} else {
job.Status = "completed"
job.Output = contenido
log.Printf("job '%s' completed successfully", job.ID)
}
} else {
fmt.Println("No se encontró contenido entre las frases")
}
}()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"job_id": job.ID})
case http.MethodGet:
jobID := r.URL.Query().Get("job_id")
if jobID == "" {
http.Error(w, "missing job_id", http.StatusBadRequest)
return
}
// Verify JWT token
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
tokenString := strings.Replace(authHeader, "Bearer ", "", 1)
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(os.Getenv("JWT_SECRET")), nil
})
if err != nil || !token.Valid {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
job, err := jobManager.GetJob(jobID)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(job)
default:
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
}
})
http.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"exp": time.Now().Add(time.Hour).Unix(),
})
tokenString, err := token.SignedString([]byte(os.Getenv("JWT_SECRET")))
if err != nil {
http.Error(w, "internal server error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"token": tokenString})
})
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
log.Printf("server listening on port %s", port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}
// curl http://localhost:8080/token
// curl -X POST -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2ODQzNTMyMDR9.DD63YjCdt2upWJkMCZR2OcbPJEwnHDuhDaxEg-v5IPk" -H "Content-Type: application/json" -d '{"phrase": "Hello, world!"}' http://localhost:8080/job
// curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2ODQzNTMyMDR9.DD63YjCdt2upWJkMCZR2OcbPJEwnHDuhDaxEg-v5IPk" http://localhost:8080/job?job_id=1684349700082163228