WU/Python/app.py
2018-11-28 01:39:20 +01:00

597 lines
17 KiB
Python

from flask import Flask, render_template, request, json, session, redirect
#from flask.ext.mysql import MySQL
from flaskext.mysql import MySQL
from pony.orm import *
import face_recognition
import cv2
import logging as log
import datetime as dt
from time import sleep
import types
#from werkzeug import generate_password_hash, check_password_hash
app = Flask(__name__)
app.secret_key = '523tvb6h3nio6r21cc4r1qx'
mysql = MySQL()
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'root'
#app.config['MYSQL_DATABASE_USER'] = 'Micik'
app.config['MYSQL_DATABASE_PASSWORD'] = 'localhost'
app.config['MYSQL_DATABASE_DB'] = 'wu'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
faces_list = []
testing_face = 0
#wu = Database()
#class Users(wu.Entity):
# login = PrimaryKey(str)
# haslo = Optional(str)
# face = Optional(str)
#wu.bind("mysql", host = "localhost", user = "root", passwd = "localhost", db = "wu")
#wu.generate_mapping(create_tables = True)
@app.route("/")
def main():
return render_template('index.html', info="Witaj!")
@app.route("/indexENG")
def indexENG():
return render_template('indexENG.html', info="Hello!")
@app.route('/showSignUp')
def showSignUp():
return render_template('signup.html')
@app.route('/showSignUpENG')
def showSignUpENG():
return render_template('signupENG.html')
@app.route('/showSignIn')
def showSignIn():
return render_template('signin.html')
@app.route('/showSignInENG')
def showSignInENG():
return render_template('signinENG.html')
@app.route('/signUp',methods=['POST','GET'])
def signUp():
try:
_login = request.form['inputLogin']
_password = request.form['inputPassword']
# validate the received values
if _login and _password:
# All Good, let's call MySQL
conn = mysql.connect()
cursor = conn.cursor()
#_hashed_password = generate_password_hash(_password)
#cursor.callproc('rejestracja4',(_name,_email,_hashed_password))
#cursor.callproc('rejestracja4',(_name,_email,_password))
#cursor.callproc('dodajUzytkownika', (_email, _password, _type, _organization, _name, _surname))
args = (_login, _password)
cursor.execute("INSERT into Users(login, password) values(%s, %s)", args)
data = cursor.fetchall()
if len(data) is 0:
conn.commit()
#return redirect("index.html")
#return redirect("/")
return render_template("index.html", info="Pomyślnie zarejestrowano!")
#return json.dumps({'message':'User created successfully !'})
else:
return render_template("error.html", error="Użytkownik już istnieje!")
#return json.dumps({'error':str(data[0])})
else:
return json.dumps({'html':'<span>Enter the required fields</span>'})
#except Exception as e:
# return json.dumps({'error':str(e)})
finally:
cursor.close()
conn.close()
@app.route('/signUpENG',methods=['POST','GET'])
def signUpENG():
try:
_login = request.form['inputLogin']
_password = request.form['inputPassword']
# validate the received values
if _login and _password:
# All Good, let's call MySQL
conn = mysql.connect()
cursor = conn.cursor()
#_hashed_password = generate_password_hash(_password)
#cursor.callproc('rejestracja4',(_name,_email,_hashed_password))
#cursor.callproc('rejestracja4',(_name,_email,_password))
#cursor.callproc('dodajUzytkownika', (_email, _password, _type, _organization, _name, _surname))
args = (_login, _password)
cursor.execute("INSERT into Users(login, password) values(%s, %s)", args)
data = cursor.fetchall()
if len(data) is 0:
conn.commit()
#return redirect("index.html")
#return redirect("/")
return render_template("indexENG.html", info="Successfully registered!")
#return json.dumps({'message':'User created successfully !'})
else:
return render_template("errorENG.html", error="The user already exists!")
#return json.dumps({'error':str(data[0])})
else:
return json.dumps({'html':'<span>Enter the required fields</span>'})
#except Exception as e:
# return json.dumps({'error':str(e)})
finally:
cursor.close()
conn.close()
@app.route('/validateLogin',methods=['POST'])
def validateLogin():
try:
_username = request.form['inputLogin']
_password = request.form['inputPassword']
con = mysql.connect()
cursor = con.cursor()
#cursor.callproc('logowanie',(_username,))
args = (_username, _password)
query = "SELECT * from Users where login = %s and password = %s"
cursor.execute(query, args)
data = cursor.fetchall()
if len(data) > 0:
#if check_password_hash(str(data[0][3]),_password):
#if str(data[0][3]) == _password:
if str(data[0][1]) == _password:
session['user'] = data[0][0]
#return redirect('/userHome', user=session['user'])
return render_template('userHome.html', user=session['user'])
else:
return render_template('error.html',error = 'Zly email lub haslo!')
else:
return render_template('error.html',error = 'Zly email lub haslo!')
except Exception as e:
return render_template('error.html',error = str(e))
finally:
cursor.close()
con.close()
@app.route('/validateLoginENG',methods=['POST'])
def validateLoginENG():
try:
_username = request.form['inputLogin']
_password = request.form['inputPassword']
con = mysql.connect()
cursor = con.cursor()
#cursor.callproc('logowanie',(_username,))
args = (_username, _password)
query = "SELECT * from Users where login = %s and password = %s"
cursor.execute(query, args)
data = cursor.fetchall()
if len(data) > 0:
#if check_password_hash(str(data[0][3]),_password):
#if str(data[0][3]) == _password:
if str(data[0][1]) == _password:
session['user'] = data[0][0]
#return redirect('/userHomeENG', user=session['user'])
return render_template('userHomeENG.html', user=session['user'])
else:
return render_template('errorENG.html',error = 'Wrong email or password!')
else:
return render_template('errorENG.html',error = 'Wrong email or password!')
except Exception as e:
return render_template('errorENG.html', error = str(e))
finally:
cursor.close()
con.close()
@app.route('/userHome')
def userHome():
if session.get('user'):
return render_template('userHome.html', user=session['user'])
else:
return render_template('error.html',error = 'Nieautoryzowany dostep!')
@app.route('/userHomeENG')
def userHomeENG():
if session.get('user'):
return render_template('userHomeENG.html', user=session['user'])
else:
return render_template('errorENG.html',error = 'Unauthorized access!')
@app.route('/logout')
def logout():
session.pop('user',None)
return redirect('/')
@app.route('/logoutENG')
def logoutENG():
session.pop('user',None)
return redirect('/indexENG')
@app.route('/signUpWithFace')
def signUpWithFace():
cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
log.basicConfig(filename='webcam.log',level=log.INFO)
video_capture = cv2.VideoCapture(0)
anterior = 0
faces = None
#testing_face = 0
#faces_list = []
i = 0
while True:
if not video_capture.isOpened():
print('Unable to load camera.')
sleep(5)
pass
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30)
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
if anterior != len(faces):
anterior = len(faces)
log.info("faces: "+str(len(faces))+" at "+str(dt.datetime.now()))
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Display the resulting frame
cv2.imshow('Video', frame)
#break
#face_list.append()
#print (type(faces))
#print (len(faces))
#print (type(faces[0]))
#print (type(faces[0][0]))
#if testing_face == faces:
# break
#if type(faces) == "numpy.ndarray" or type(faces) == "ndarray":
#if not isinstance(faces, types.TupleType):
if type(faces) is not tuple:
i += 1
face = 0
for f in faces[0]:
face += f
faces_list.append(face)
if i == 5:
break
# faces_list.append(faces)
# i += 1
# if i == 5:
# break
'''
face = 0
i += 1
for id in faces[0]:
face += id
if i == 5:
break
if 825 == face:
video_capture.release()
cv2.destroyAllWindows()
return render_template('index.html')
print (face)
'''
#return render_template("index.html")
#print (faces)
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
print (faces_list)
return render_template('index.html', info="Zapisano twarz")
'''
face = 0
for id in faces[0]:
face += id
print (id)
#if face
print (face)
'''
#return render_template('error.html', error="Nie wykryto twarzy!")
@app.route('/signUpWithFaceENG')
def signUpWithFaceENG():
cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
log.basicConfig(filename='webcam.log',level=log.INFO)
video_capture = cv2.VideoCapture(0)
anterior = 0
faces = None
#testing_face = 0
#faces_list = []
i = 0
while True:
if not video_capture.isOpened():
print('Unable to load camera.')
sleep(5)
pass
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30)
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
if anterior != len(faces):
anterior = len(faces)
log.info("faces: "+str(len(faces))+" at "+str(dt.datetime.now()))
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Display the resulting frame
cv2.imshow('Video', frame)
#break
#face_list.append()
#print (type(faces))
#print (len(faces))
#print (type(faces[0]))
#print (type(faces[0][0]))
#if testing_face == faces:
# break
#if type(faces) == "numpy.ndarray" or type(faces) == "ndarray":
#if not isinstance(faces, types.TupleType):
if type(faces) is not tuple:
i += 1
face = 0
for f in faces[0]:
face += f
faces_list.append(face)
if i == 5:
break
# faces_list.append(faces)
# i += 1
# if i == 5:
# break
'''
face = 0
i += 1
for id in faces[0]:
face += id
if i == 5:
break
if 825 == face:
video_capture.release()
cv2.destroyAllWindows()
return render_template('index.html')
print (face)
'''
#return render_template("index.html")
#print (faces)
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
print (faces_list)
return render_template('indexENG.html', info="A face has been saved")
'''
face = 0
for id in faces[0]:
face += id
print (id)
#if face
print (face)
'''
#return render_template('error.html', error="Nie wykryto twarzy!")
@app.route('/signInWithFace')
def signInWithFace():
cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
log.basicConfig(filename='webcam.log',level=log.INFO)
video_capture = cv2.VideoCapture(0)
anterior = 0
faces = None
testing_face = 825
#faces_list = []
i = 0
while True:
if not video_capture.isOpened():
print('Unable to load camera.')
sleep(5)
pass
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30)
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
if anterior != len(faces):
anterior = len(faces)
log.info("faces: "+str(len(faces))+" at "+str(dt.datetime.now()))
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Display the resulting frame
cv2.imshow('Video', frame)
#print (faces_list)
if type(faces) is not tuple:
face = 0
i += 1
for f in faces[0]:
face += f
if face in faces_list:
break
# print (faces)
# if faces in faces_list:
# break
elif i == 20:
return render_template("error.html", error="Brak dostępu!")
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
#print (faces_list)
return render_template('userHome.html', info="Zapisano twarz", user=session.get('user'))
@app.route('/signInWithFaceENG')
def signInWithFaceENG():
cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
log.basicConfig(filename='webcam.log',level=log.INFO)
video_capture = cv2.VideoCapture(0)
anterior = 0
faces = None
testing_face = 825
#faces_list = []
i = 0
while True:
if not video_capture.isOpened():
print('Unable to load camera.')
sleep(5)
pass
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30)
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
if anterior != len(faces):
anterior = len(faces)
log.info("faces: "+str(len(faces))+" at "+str(dt.datetime.now()))
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Display the resulting frame
cv2.imshow('Video', frame)
#print (faces_list)
if type(faces) is not tuple:
face = 0
i += 1
for f in faces[0]:
face += f
if face in faces_list:
break
# print (faces)
# if faces in faces_list:
# break
elif i == 20:
return render_template("errorENG.html", error="Lack of access!")
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
#print (faces_list)
return render_template('userHomeENG.html', info="A face has been saved", user=session.get('user'))
if __name__ == "__main__":
#app.run(port=5002)
app.run(host='0.0.0.0')