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('/showSignUp')
def showSignUp():
return render_template('signup.html')
@app.route('/showSignIn')
def showSignIn():
return render_template('signin.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':'Enter the required fields'})
#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')
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('/userHome')
def userHome():
if session.get('user'):
return render_template('userHome.html')
else:
return render_template('error.html',error = 'Nieautoryzowany dostep!')
@app.route('/logout')
def logout():
session.pop('user',None)
return redirect('/')
@app.route('/newSheet', methods=['POST','GET'])
def newSheet():
try:
_sheet_name = request.form['inputSheetName']
_number_items = request.form['inputItems']
_number_operators = request.form['inputOperators']
_number_chars = request.form['inputChars']
_number_trials = request.form['inputTrials']
if _sheet_name and _number_items and _number_operators and _number_chars and _number_trials:
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('nowyArkusz',(_sheet_name, _number_items,_number_operators,_number_chars, _number_trials))
data = cursor.fetchall()
if len(data) is 0:
conn.commit()
return redirect('/sheet')
#return json.dumps({'message':'Arkusz stworzono poprawnie!'})
else:
return json.dumps({'error':str(data[0])})
else:
return json.dumps({'html':'Enter the required fields'})
except Exception as e:
return json.dumps({'error':str(e)})
finally:
cursor.close()
conn.close()
#return render_template('newSheet.html')
@app.route('/sheet', methods=['POST'])
def sheet():
return render_template('sheet.html')
@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('/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")
if __name__ == "__main__":
#app.run(port=5002)
app.run(host='0.0.0.0')