Add auth_url and token to KnowThyNumber

Change-Id: Id767f03283550551c2225563e3b0f402981f01a3
This commit is contained in:
bharath 2018-11-16 09:51:45 +05:30
parent 657be965a5
commit 96ec2e67c1
4 changed files with 191 additions and 2 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 126 B

View File

@ -2,8 +2,188 @@ package main
import ( import (
"net/http" "net/http"
"bytes"
"fmt"
"image"
"image/color"
"image/png"
"io"
"io/ioutil"
"math"
"mime/multipart"
"os"
"github.com/disintegration/imaging"
"github.com/harrydb/go/img/grayscale"
// "github.com/nfnt/resize"
) )
// UploadFile uploads a file to the server
func UploadFile(w http.ResponseWriter, r *http.Request) {
fmt.Printf("Inside upload \n")
if r.Method != http.MethodPost {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
// Save a copy of this request for debugging.
//requestDump, err := httputil.DumpRequest(r, true)
//if err != nil {
// fmt.Println(err)
//}
//fmt.Println(string(requestDump))
file, handle, err := r.FormFile("file")
auth_url := r.Form.Get("auth_url")
token := r.Form.Get("token")
fmt.Println(auth_url)
fmt.Println(token)
if err != nil {
fmt.Printf("upload error\n")
fmt.Println(err.Error())
fmt.Fprintf(w, "%v", err)
return
}
defer file.Close()
mimeType := handle.Header.Get("Content-Type")
switch mimeType {
// case "image/jpeg":
// saveFile(w, file, handle)
case "image/png":
saveFile(w, file, handle, auth_url, token)
default:
jsonResponse(w, http.StatusBadRequest, "The format file is not valid.")
}
}
func processImage(infile multipart.File) (err error) {
imgSrc, _, err := image.Decode(infile)
if err != nil {
panic(err.Error())
}
// Create a new grayscale image
bounds := imgSrc.Bounds()
w, h := bounds.Max.X, bounds.Max.Y
grayScale := image.NewGray(image.Rectangle{image.Point{0, 0}, image.Point{w, h}})
for x := 0; x < w; x++ {
for y := 0; y < h; y++ {
imageColor := imgSrc.At(x, y)
rr, gg, bb, _ := imageColor.RGBA()
r := math.Pow(float64(rr), 2.2)
g := math.Pow(float64(gg), 2.2)
b := math.Pow(float64(bb), 2.2)
m := math.Pow(0.2125*r+0.7154*g+0.0721*b, 1/2.2)
Y := uint16(m + 0.5)
grayColor := color.Gray{uint8(Y >> 8)}
grayScale.Set(x, y, grayColor)
}
}
//Resize image
newImg := imaging.Resize(imgSrc, 28, 28, imaging.Lanczos)
// Grayscale 2
grayImg := grayscale.Convert(newImg, grayscale.ToGrayLuminance)
threshold := grayscale.Otsu(grayImg)
grayscale.Threshold(grayImg, threshold, 0, 255)
// Encode the grayscale image to the new file
newFileName := "grayscale.png"
newfile, err := os.Create("./files/" + newFileName)
if err != nil {
fmt.Printf("failed creating %s: %s", newfile, err)
return err
}
//defer newfile.Close()
//png.Encode(newfile, grayScale)
png.Encode(newfile, grayImg)
return nil
}
func saveFile(w http.ResponseWriter, file multipart.File, handle *multipart.FileHeader, auth_url string, token string) {
err := processImage(file)
//data, err := ioutil.ReadAll(file2)
if err != nil {
fmt.Fprintf(w, "%v", err)
fmt.Println("%v", err)
return
}
//err = ioutil.WriteFile("./files/"+handle.Filename, data, 0666)
//if err != nil {
// fmt.Fprintf(w, "%v", err)
// return
//}
resp := predictNumber(auth_url, token)
jsonResponse(w, http.StatusCreated, resp)
}
func postFile(filename string, targetUrl string, token string) (string, error) {
bodyBuf := &bytes.Buffer{}
bodyWriter := multipart.NewWriter(bodyBuf)
fmt.Println(filename)
// this step is very important
fileWriter, err := bodyWriter.CreateFormFile("file", filename)
if err != nil {
fmt.Println("error writing to buffer")
return "", err
}
// open file handle
fh, err := os.Open(filename)
if err != nil {
fmt.Println("error opening file")
return "", err
}
defer fh.Close()
//iocopy
_, err = io.Copy(fileWriter, fh)
if err != nil {
return "", err
}
contentType := bodyWriter.FormDataContentType()
bodyWriter.Close()
client := &http.Client{}
fmt.Println(bodyBuf)
r, _ := http.NewRequest("POST", targetUrl, bodyBuf)
r.Header.Add("Content-Type", contentType)
r.Header.Add("X-Auth-Token", token)
resp, err := client.Do(r)
// resp, err := http.Post(targetUrl, contentType, bodyBuf)
if err != nil {
return "", err
}
defer resp.Body.Close()
resp_body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
fmt.Println(resp.Status)
fmt.Println(string(resp_body))
return string(resp_body), nil
}
func predictNumber(auth_url string, token string) string {
// target_url := "http://localhost:5000/mnist/classify"
filename := "./files/grayscale.png"
resp, _ := postFile(filename, auth_url, token)
return resp
}
func jsonResponse(w http.ResponseWriter, code int, message string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
fmt.Fprint(w, message)
}
func ping(w http.ResponseWriter, r *http.Request) { func ping(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("pong")) w.Write([]byte("pong"))
} }
@ -15,3 +195,5 @@ func main() {
panic(err) panic(err)
} }
} }

View File

@ -73,7 +73,7 @@ function uploadArea() {
function getDstImage(data) { function getDstImage(data) {
console.log("Entering into getDstImage") console.log("Entering into getDstImage")
var fname = "./img/" var fname = "./img/"
switch(data["classification"]) { switch(data["data"]) {
case 1: case 1:
return fname+"1.jpg" return fname+"1.jpg"
case 2: case 2:
@ -98,13 +98,18 @@ function getDstImage(data) {
} }
function uploadArea2() { function uploadArea2() {
var canvas = document.getElementById("myCanvas") var canvas = document.getElementById("myCanvas");
canvas.toBlob( canvas.toBlob(
function (blob) { function (blob) {
// Do something with the blob object, // Do something with the blob object,
// e.g. creating a multipart form for file uploads: // e.g. creating a multipart form for file uploads:
var formData = new FormData(); var formData = new FormData();
var auth_url = document.getElementById("auth_url").value;
var token = document.getElementById("token").value;
formData.append('file', blob, "predict.png"); formData.append('file', blob, "predict.png");
formData.append("auth_url", auth_url);
formData.append("token", token);
$.ajax({ $.ajax({
url: 'http://localhost:9000/upload/', url: 'http://localhost:9000/upload/',
type: 'POST', type: 'POST',

View File

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