-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
254 lines (211 loc) · 6.02 KB
/
main.go
File metadata and controls
254 lines (211 loc) · 6.02 KB
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
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/go-redis/redis"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
const (
endpoint = "https://westcentralus.api.cognitive.microsoft.com/vision/v1.0/analyze?visualFeatures=categories,description,tags&details=Celebrities&language=en"
fvendpoint = "https://westcentralus.api.cognitive.microsoft.com/face/v1.0"
persongid = "banned_users"
)
var key = os.Getenv("VISION_KEY")
var fvkey = os.Getenv("FACE_VISION_KEY")
func main() {
client := redis.NewClient(&redis.Options{
Addr: "redis:6379",
Password: "",
DB: 0,
})
_, err := client.Ping().Result()
if err != nil {
log.Fatal("Couldn't connect to Redis. Please make sure that Redis is running.")
}
r := mux.NewRouter()
r.HandleFunc("/", apiHealthHandler)
r.HandleFunc("/hide", redisHandler(client, hideHandler)).Methods("POST")
r.HandleFunc("/newuser", newUser)
r.HandleFunc("/adduserphoto", newUserPhoto)
r.HandleFunc("/traingroups", trainGroups)
r.HandleFunc("/listusers", listUsers)
loggedRouter := handlers.LoggingHandler(os.Stdout, r)
log.Fatal(http.ListenAndServe(":2048", loggedRouter))
}
func ensure_groups_created() {
// TODO
}
func apiHealthHandler(w http.ResponseWriter, r *http.Request) {
healthResponse := &HealthResponse{
Status: "OK!",
Timestamp: time.Now().Unix(),
}
jsonResp, err := json.Marshal(healthResponse)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
fmt.Fprintf(w, string(jsonResp))
}
func redisHandler(c *redis.Client,
f func(c *redis.Client, w http.ResponseWriter, r *http.Request)) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) { f(c, w, r) }
}
func hideHandler(client *redis.Client, w http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
var req Request
err = json.Unmarshal(b, &req)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
response := &Response{
Images: make([]ImageResponse, len(req.Urls)),
}
for index, url := range req.Urls {
var cvResponse CVResponse
var fetchNew = true
if req.UseCache {
fmt.Println("Using cache")
val, err := client.Get(url).Result()
if err == nil {
fetchNew = false
marshalErr := json.Unmarshal([]byte(val), &cvResponse)
if marshalErr != nil {
http.Error(w, marshalErr.Error(), 500)
return
}
}
}
if fetchNew {
fmt.Println("Fetching new")
cvResponse, err = getDescriptionFromCognitiveServices(url)
if err != nil {
http.Error(w, err.Error(), 429)
return
}
responseJson, err := json.Marshal(cvResponse)
if err == nil {
client.Set(url, responseJson, 0).Err()
}
}
imageResponse := ImageResponse{
Url: url,
Hide: shouldBlockImage(req.Tags, cvResponse),
SubstituteImage: url,
Tags: cvResponse.Tags,
}
response.Images[index] = imageResponse
}
responseJson, err := json.Marshal(response)
if err != nil {
http.Error(w, err.Error(), 500)
}
w.Header().Set("content-type", "application/json")
w.Write(responseJson)
}
func getDescriptionFromCognitiveServices(url string) (cvr CVResponse, err error) {
var msReq = &CVRequest{
url,
}
postData, err := json.Marshal(msReq)
if err != nil {
return
}
req, err := http.NewRequest("POST", endpoint, bytes.NewReader(postData))
req.Header.Set("Ocp-Apim-Subscription-Key", key)
req.Header.Set("Content-Type", "application/json")
resp, err := makeAPICallWithBackoff(req)
if err != nil {
return
}
defer resp.Body.Close()
json.NewDecoder(resp.Body).Decode(&cvr)
return
}
// TODO: add face rec to this
func shouldBlockImage(blockTags []string, cvResponse CVResponse) bool {
// If image is too small then the width or height is set to 0 but shouldn't be hidden
if cvResponse.Metadata.Width == 0 || cvResponse.Metadata.Height == 0 || len(blockTags) == 0 {
return false
}
imageTags := cvResponse.Description.Tags
for _, detail := range cvResponse.Categories {
for _, celeb := range detail.Detail.Celebrities {
imageTags = append(imageTags, strings.Split(celeb.Name, " ")...)
}
}
set := make(map[string]bool)
for _, imageTag := range imageTags {
set[strings.ToLower(imageTag)] = true
set[strings.ToLower(imageTag)+"s"] = true
set[strings.ToLower(imageTag)+"es"] = true
}
for _, blockTag := range blockTags {
_, tagInImage := set[strings.ToLower(blockTag)]
if tagInImage {
return true
}
}
// NOTE: Where to put this?
// TODO: detect faces, get first 10 faceids, and then
//faces := detectFaces(photoUrl)
//for face := range *faces {
// face.FaceId
//}
// TODO: then call
//getFaceVerification(photoUrl)
return false
}
func newUser(w http.ResponseWriter, r *http.Request) {
//username := r.URL.Query().Get("username")
//userinfo := r.URL.Query().Get("userinfo")
//person := createPerson(username, userinfo)
// TODO: something with person ID?
// TODO: respond with updated list of users-> redirect to listUsers?
}
func newUserPhoto(w http.ResponseWriter, r *http.Request) {
//personId := r.URL.Query().Get("personId")
//photoUrl := r.URL.Query().Get("url")
//newFace := addPersonFace(personId, photoUrl)
// TODO: store persistedFaceId somewhere -> list of faces that can occur in a photo-> max 10 cos demo
}
func trainGroups(w http.ResponseWriter, r *http.Request) {
// TODO: loop over all keys and retrain group for each
//trainPersonGroup()
// TODO: some spinner or something to mark busy? idk
}
func listUsers(w http.ResponseWriter, r *http.Request) {
// each user needs to have its personId
}
func makeAPICallWithBackoff(req *http.Request) (resp *http.Response, err error) {
client := &http.Client{}
var backoffTimeout = 0.5
resp, err = client.Do(req)
for {
if err == nil {
return
}
time.Sleep(time.Duration(backoffTimeout) * time.Second)
resp, err = client.Do(req)
backoffTimeout *= 2
if backoffTimeout == 8 {
err = errors.New("API Timeout")
return
}
}
}