-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
180 lines (133 loc) · 5.64 KB
/
app.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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
from flask import Flask, json, Response, request, render_template
from werkzeug.utils import secure_filename
from os import path, getcwd
import time
from db import Database
from face import Face
app = Flask(__name__)
app.config['file_allowed'] = ['image/png', 'image/jpeg', 'image/jpg']
app.config['storage'] = path.join(getcwd(), 'storage')
app.db = Database()
app.face = Face(app)
def success_handle(output, status=200, mimetype='application/json'):
return Response(output, status=status, mimetype=mimetype)
def error_handle(error_message, status=500, mimetype='application/json'):
return Response(json.dumps({"error": {"message": error_message}}), status=status, mimetype=mimetype)
def get_user_by_id(user_id):
user = {}
results = app.db.select(
'SELECT users.id, users.name, users.created, faces.id, faces.user_id, faces.filename,faces.created FROM users LEFT JOIN faces ON faces.user_id = users.id WHERE users.id = ?',
[user_id])
index = 0
for row in results:
# print(row)
face = {
"id": row[3],
"user_id": row[4],
"filename": row[5],
"created": row[6],
}
if index == 0:
user = {
"id": row[0],
"name": row[1],
"created": row[2],
"faces": [],
}
if row[3]:
user["faces"].append(face)
index = index + 1
if 'id' in user:
return user
return None
def delete_user_by_id(user_id):
app.db.delete('DELETE FROM users WHERE users.id = ?', [user_id])
# also delete all faces with user id
app.db.delete('DELETE FROM faces WHERE faces.user_id = ?', [user_id])
# Route for Hompage
@app.route('/', methods=['GET'])
def page_home():
return render_template('index.html')
@app.route('/api', methods=['GET'])
def homepage():
output = json.dumps({"api": '1.0'})
return success_handle(output)
@app.route('/api/train', methods=['POST'])
def train():
output = json.dumps({"success": True})
if 'file' not in request.files:
print ("Face image is required")
return error_handle("Face image is required.")
else:
print("File request", request.files)
file = request.files['file']
if file.mimetype not in app.config['file_allowed']:
print("File extension is not allowed")
return error_handle("We are only allow upload file with *.png , *.jpg")
else:
# get name in form data
name = request.form['name']
print("Information of that face", name)
print("File is allowed and will be saved in ", app.config['storage'])
filename = secure_filename(file.filename)
trained_storage = path.join(app.config['storage'], 'trained')
file.save(path.join(trained_storage, filename))
# let start save file to our storage
# save to our sqlite database.db
created = int(time.time())
user_id = app.db.insert('INSERT INTO users(name, created) values(?,?)', [name, created])
if user_id:
print("User saved in data", name, user_id)
# user has been save with user_id and now we need save faces table as well
face_id = app.db.insert('INSERT INTO faces(user_id, filename, created) values(?,?,?)',
[user_id, filename, created])
if face_id:
print("cool face has been saved")
face_data = {"id": face_id, "filename": filename, "created": created}
return_output = json.dumps({"id": user_id, "name": name, "face": [face_data]})
return success_handle(return_output)
else:
print("An error saving face image.")
return error_handle("n error saving face image.")
else:
print("Something happend")
return error_handle("An error inserting new user")
print("Request is contain image")
return success_handle(output)
# route for user profile
@app.route('/api/users/<int:user_id>', methods=['GET', 'DELETE'])
def user_profile(user_id):
if request.method == 'GET':
user = get_user_by_id(user_id)
if user:
return success_handle(json.dumps(user), 200)
else:
return error_handle("User not found", 404)
if request.method == 'DELETE':
delete_user_by_id(user_id)
return success_handle(json.dumps({"deleted": True}))
# router for recognize a unknown face
@app.route('/api/recognize', methods=['POST'])
def recognize():
if 'file' not in request.files:
return error_handle("Image is required")
else:
file = request.files['file']
# file extension valiate
if file.mimetype not in app.config['file_allowed']:
return error_handle("File extension is not allowed")
else:
filename = secure_filename(file.filename)
unknown_storage = path.join(app.config["storage"], 'unknown')
file_path = path.join(unknown_storage, filename)
file.save(file_path)
user_id = app.face.recognize(filename)
if user_id:
user = get_user_by_id(user_id)
message = {"message": "Hey we found {0} matched with your face image".format(user["name"]),
"user": user}
return success_handle(json.dumps(message))
else:
return error_handle("Sorry we can not found any people matched with your face image, try another image")
# Run the app
app.run()