-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
160 lines (121 loc) · 4.33 KB
/
main.py
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
from flask import Flask, render_template, request, redirect, url_for, session, flash
import torch
import os
import mysql.connector
import base64
from io import BytesIO
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import cv2
import pickle
import json
import torch.nn as nn
import torch.nn.functional as F
import warnings
warnings.filterwarnings("ignore")
app = Flask(__name__)
app.config[
"SECRET_KEY"
] = "1b11e3688e45e9f809a8e11f5fc3fdfe1041a8a808da7f0a1192fc3b778055281ef5d073c3a36ddfe193"
dataBase = mysql.connector.connect(
host="localhost", user="root", passwd="_______", database="userdata"
)
cursorObject = dataBase.cursor()
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.conv2_drop = nn.Dropout2d()
self.fc1 = nn.Linear(320, 50)
self.fc2 = nn.Linear(50, 10)
def forward(self, x):
x = F.relu(F.max_pool2d(self.conv1(x), 2))
x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
x = x.view(-1, 320)
x = F.relu(self.fc1(x))
x = F.dropout(x, training=self.training)
x = self.fc2(x)
return F.softmax(x)
@app.route("/createuser", methods=["POST"])
def createUser():
if request.method == "POST":
username = request.form.get("uname")
pwd = request.form.get("pwd")
cpwd = request.form.get("cpwd")
if cpwd == pwd:
val = (username, pwd)
cursorObject.execute(
"INSERT INTO users (name, passwd) VALUES (%s, %s)", val
)
dataBase.commit()
if databaseConnection(username, pwd):
flash("Account successfully created!")
return render_template("login.html", signup=False)
else:
return render_template("login.html", signup=True, messages=True)
def databaseConnection(username, password):
# cursorObject.execute("CREATE DATABASE IF EXISTS userdata")
# cursorObject.execute("SHOW DATABASES")
# cursorObject.execute("CREATE TABLE users (name VARCHAR(255), passwd VARCHAR(255))")
cursorObject.execute("SELECT * from users")
datalist = cursorObject.fetchall()
print(datalist)
# print((username, password))
if (username, password) in datalist:
return True
else:
False
cnn_model = Net()
label = 0
accuracy = 0
def pred(image):
global label, accuracy
resized_image = cv2.resize(image, (28, 28), interpolation=cv2.INTER_LINEAR) / 255.0
# resized_image = resized_image.astype("float64")
data = torch.from_numpy(resized_image)
data = data.type("torch.FloatTensor")
data = data.unsqueeze(0)
with open("model.pkl", "rb") as f:
cnn_model = pickle.load(f)
with torch.no_grad():
output = cnn_model(data)
pred = np.round_(np.array(output), decimals=3) * 100
label = int(np.argmax(pred))
accuracy = int(pred[0][label])
print((label, accuracy))
return (label, accuracy)
@app.route("/", methods=["POST", "GET"])
def home():
return render_template("login.html")
@app.route("/loginuser", methods=["POST", "GET"])
def login():
if request.method == "POST":
username = request.form.get("uname")
pwd = request.form.get("pwd")
if databaseConnection(username, pwd):
return redirect(url_for("classifierPage"))
else:
return render_template("login.html", signup=True)
if request.method == "GET":
print("GET")
return render_template("login.html", signup=False)
@app.route("/NoClassifier")
def classifierPage(model_pred=(True, None, None)):
return render_template("classifier.html")
@app.route("/getImage", methods=["POST", "GET"])
def getImage():
global label, accuracy
if request.method == "POST":
imagebase64 = request.form["imagebase64"]
encoded_img = imagebase64.split(",")[1]
image_data = bytes(encoded_img, encoding="ascii")
img_conv = Image.open(BytesIO(base64.b64decode(image_data))).convert("L")
img_conv.save("image.png")
image = np.asarray(img_conv)
return json.dumps({"predictions": pred(image)})
else:
return json.dumps({"predictions": (label, accuracy)})
if __name__ == "__main__":
app.run(debug=True)