-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
62 lines (55 loc) · 1.4 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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os/exec"
"strings"
)
var (
server = &http.Server{Addr: ":8080"}
)
type Img struct {
Path string `json:"path"`
}
type NsfwResult struct {
Score string
}
func main() {
http.HandleFunc("/", imgHandler)
log.Fatal(server.ListenAndServe())
}
func imgHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Use post", 405)
return
}
img := Img{}
err := json.NewDecoder(r.Body).Decode(&img)
if err != nil {
fmt.Fprintf(w, fmt.Sprintf("Error decoding body: %v", fmt.Sprint(err)))
}
cmd := exec.Command("python", "/workspace/classify_nsfw.py", "--model_def", "/workspace/nsfw_model/deploy.prototxt", "--pretrained_model", "/workspace/nsfw_model/resnet_50_1by2_nsfw.caffemodel", fmt.Sprint(img.Path))
output, err := cmd.CombinedOutput()
if err != nil {
fmt.Fprintf(w, fmt.Sprintf("error in Output():", fmt.Sprint(err)))
}
score := strings.Trim(after(string(output), "NSFW_SCORE="), " ")
result := &NsfwResult{Score: strings.TrimSuffix(score, "\n")}
json, _ := json.Marshal(result)
w.Header().Set("Content-Type", "application/json")
w.Write(json)
}
func after(value string, a string) string {
// Get substring after a string.
pos := strings.LastIndex(value, a)
if pos == -1 {
return ""
}
adjustedPos := pos + len(a)
if adjustedPos >= len(value) {
return ""
}
return value[adjustedPos:len(value)]
}