Browse Source

Add auth_url and token to KnowThyNumber

Change-Id: Id767f03283550551c2225563e3b0f402981f01a3
bharath 5 months ago
parent
commit
96ec2e67c1

BIN
examples/KnowThyNumber/BE/files/grayscale.png View File


+ 182
- 0
examples/KnowThyNumber/BE/server.go View File

@@ -2,8 +2,188 @@ package main
2 2
 
3 3
 import (
4 4
 	"net/http"
5
+	"bytes"
6
+	"fmt"
7
+	"image"
8
+	"image/color"
9
+	"image/png"
10
+	"io"
11
+	"io/ioutil"
12
+	"math"
13
+	"mime/multipart"
14
+	"os"
15
+
16
+	"github.com/disintegration/imaging"
17
+	"github.com/harrydb/go/img/grayscale"
18
+	// "github.com/nfnt/resize"
5 19
 )
6 20
 
21
+// UploadFile uploads a file to the server
22
+func UploadFile(w http.ResponseWriter, r *http.Request) {
23
+	fmt.Printf("Inside upload \n")
24
+	if r.Method != http.MethodPost {
25
+		http.Redirect(w, r, "/", http.StatusSeeOther)
26
+		return
27
+	}
28
+
29
+	// Save a copy of this request for debugging.
30
+	//requestDump, err := httputil.DumpRequest(r, true)
31
+	//if err != nil {
32
+	//	fmt.Println(err)
33
+	//}
34
+
35
+	//fmt.Println(string(requestDump))
36
+
37
+	file, handle, err := r.FormFile("file")
38
+	auth_url := r.Form.Get("auth_url")
39
+	token := r.Form.Get("token")
40
+	fmt.Println(auth_url)
41
+	fmt.Println(token)
42
+	if err != nil {
43
+		fmt.Printf("upload error\n")
44
+		fmt.Println(err.Error())
45
+		fmt.Fprintf(w, "%v", err)
46
+		return
47
+	}
48
+	defer file.Close()
49
+
50
+	mimeType := handle.Header.Get("Content-Type")
51
+	switch mimeType {
52
+	// case "image/jpeg":
53
+	//	saveFile(w, file, handle)
54
+	case "image/png":
55
+		saveFile(w, file, handle, auth_url, token)
56
+	default:
57
+		jsonResponse(w, http.StatusBadRequest, "The format file is not valid.")
58
+	}
59
+}
60
+
61
+func processImage(infile multipart.File) (err error) {
62
+	imgSrc, _, err := image.Decode(infile)
63
+	if err != nil {
64
+		panic(err.Error())
65
+	}
66
+
67
+	// Create a new grayscale image
68
+	bounds := imgSrc.Bounds()
69
+	w, h := bounds.Max.X, bounds.Max.Y
70
+	grayScale := image.NewGray(image.Rectangle{image.Point{0, 0}, image.Point{w, h}})
71
+	for x := 0; x < w; x++ {
72
+		for y := 0; y < h; y++ {
73
+			imageColor := imgSrc.At(x, y)
74
+			rr, gg, bb, _ := imageColor.RGBA()
75
+			r := math.Pow(float64(rr), 2.2)
76
+			g := math.Pow(float64(gg), 2.2)
77
+			b := math.Pow(float64(bb), 2.2)
78
+			m := math.Pow(0.2125*r+0.7154*g+0.0721*b, 1/2.2)
79
+			Y := uint16(m + 0.5)
80
+			grayColor := color.Gray{uint8(Y >> 8)}
81
+			grayScale.Set(x, y, grayColor)
82
+		}
83
+	}
84
+
85
+	//Resize image
86
+	newImg := imaging.Resize(imgSrc, 28, 28, imaging.Lanczos)
87
+
88
+	// Grayscale 2
89
+	grayImg := grayscale.Convert(newImg, grayscale.ToGrayLuminance)
90
+	threshold := grayscale.Otsu(grayImg)
91
+	grayscale.Threshold(grayImg, threshold, 0, 255)
92
+
93
+	// Encode the grayscale image to the new file
94
+	newFileName := "grayscale.png"
95
+	newfile, err := os.Create("./files/" + newFileName)
96
+	if err != nil {
97
+		fmt.Printf("failed creating %s: %s", newfile, err)
98
+		return err
99
+	}
100
+	//defer newfile.Close()
101
+	//png.Encode(newfile, grayScale)
102
+	png.Encode(newfile, grayImg)
103
+
104
+	return nil
105
+}
106
+
107
+func saveFile(w http.ResponseWriter, file multipart.File, handle *multipart.FileHeader, auth_url string, token string) {
108
+	err := processImage(file)
109
+	//data, err := ioutil.ReadAll(file2)
110
+	if err != nil {
111
+		fmt.Fprintf(w, "%v", err)
112
+		fmt.Println("%v", err)
113
+		return
114
+	}
115
+
116
+	//err = ioutil.WriteFile("./files/"+handle.Filename, data, 0666)
117
+	//if err != nil {
118
+	//	fmt.Fprintf(w, "%v", err)
119
+	//	return
120
+	//}
121
+	resp := predictNumber(auth_url, token)
122
+	jsonResponse(w, http.StatusCreated, resp)
123
+}
124
+
125
+func postFile(filename string, targetUrl string, token string) (string, error) {
126
+	bodyBuf := &bytes.Buffer{}
127
+	bodyWriter := multipart.NewWriter(bodyBuf)
128
+	fmt.Println(filename)
129
+
130
+	// this step is very important
131
+	fileWriter, err := bodyWriter.CreateFormFile("file", filename)
132
+	if err != nil {
133
+		fmt.Println("error writing to buffer")
134
+		return "", err
135
+	}
136
+
137
+	// open file handle
138
+	fh, err := os.Open(filename)
139
+	if err != nil {
140
+		fmt.Println("error opening file")
141
+		return "", err
142
+	}
143
+	defer fh.Close()
144
+
145
+	//iocopy
146
+	_, err = io.Copy(fileWriter, fh)
147
+	if err != nil {
148
+		return "", err
149
+	}
150
+
151
+	contentType := bodyWriter.FormDataContentType()
152
+	bodyWriter.Close()
153
+
154
+	client := &http.Client{}
155
+	fmt.Println(bodyBuf)
156
+	r, _ := http.NewRequest("POST", targetUrl, bodyBuf)
157
+	r.Header.Add("Content-Type", contentType)
158
+	r.Header.Add("X-Auth-Token", token)
159
+	resp, err := client.Do(r)
160
+	// resp, err := http.Post(targetUrl, contentType, bodyBuf)
161
+	if err != nil {
162
+		return "", err
163
+	}
164
+	defer resp.Body.Close()
165
+	resp_body, err := ioutil.ReadAll(resp.Body)
166
+	if err != nil {
167
+		return "", err
168
+	}
169
+	fmt.Println(resp.Status)
170
+	fmt.Println(string(resp_body))
171
+	return string(resp_body), nil
172
+}
173
+
174
+func predictNumber(auth_url string, token string) string {
175
+	// target_url := "http://localhost:5000/mnist/classify"
176
+	filename := "./files/grayscale.png"
177
+	resp, _ := postFile(filename, auth_url, token)
178
+	return resp
179
+}
180
+
181
+func jsonResponse(w http.ResponseWriter, code int, message string) {
182
+	w.Header().Set("Content-Type", "application/json")
183
+	w.WriteHeader(code)
184
+	fmt.Fprint(w, message)
185
+}
186
+
7 187
 func ping(w http.ResponseWriter, r *http.Request) {
8 188
 	w.Write([]byte("pong"))
9 189
 }
@@ -15,3 +195,5 @@ func main() {
15 195
 		panic(err)
16 196
 	}
17 197
 }
198
+
199
+

+ 7
- 2
examples/KnowThyNumber/FE/JsCode.js View File

@@ -73,7 +73,7 @@ function uploadArea() {
73 73
 function getDstImage(data) {
74 74
     console.log("Entering into getDstImage")
75 75
     var fname = "./img/"
76
-    switch(data["classification"]) {
76
+    switch(data["data"]) {
77 77
         case 1:
78 78
             return fname+"1.jpg"
79 79
         case 2:
@@ -98,13 +98,18 @@ function getDstImage(data) {
98 98
 }
99 99
 
100 100
 function uploadArea2() {
101
-    var canvas = document.getElementById("myCanvas")
101
+    var canvas = document.getElementById("myCanvas");
102
+
102 103
     canvas.toBlob(
103 104
         function (blob) {
104 105
             // Do something with the blob object,
105 106
             // e.g. creating a multipart form for file uploads:
106 107
             var formData = new FormData();
108
+            var auth_url = document.getElementById("auth_url").value;
109
+            var token = document.getElementById("token").value;
107 110
             formData.append('file', blob, "predict.png");
111
+            formData.append("auth_url", auth_url);
112
+            formData.append("token", token);
108 113
             $.ajax({
109 114
                 url: 'http://localhost:9000/upload/',
110 115
                 type: 'POST',

+ 2
- 0
examples/KnowThyNumber/FE/index.html View File

@@ -49,6 +49,8 @@
49 49
     <!-- button id="clear-area">Clear Area</button -->
50 50
     <!-- button id="upload-area" onclick="javascript:doUpload();return false;">Predict</button -->
51 51
     <!-- td -->
52
+        Auth URL: <input class="form-control" type="text" id="auth_url" name="auth_url"></input>
53
+        Token: <input class="form-control" type="text" id="token" name="token"></input>
52 54
     <br /><br />
53 55
     Color : <select id="selColor" class="form-control">
54 56
         <option value="black">black</option>

Loading…
Cancel
Save