Commit c9972d67 authored by Sankalana G.L.A's avatar Sankalana G.L.A

code

parents
/.dist
/__pycache__
\ No newline at end of file
import mysql.connector
con = mysql.connector.connect(
host="127.0.0.1",
user="phpmyadmin",
password="root",
database="auth"
)
from cgitb import text
from cryptography.fernet import Fernet
#key = Fernet.generate_key()
#key = "CAwtEeCpDv7aVJ69Vx01flE-henTDRkenL_mE5WJyVg="
def encrypt(key,data):
key = key.encode()
fernet = Fernet(key)
#print(key)
enc = fernet.encrypt(data)
return(enc)
def decrypt(key,data):
key = key.encode()
fernet = Fernet(key)
#print(key)
#token = f.encrypt(data)
dec = fernet.decrypt(data)
return(dec)
# print(encrypt(key,b"hello"))
#test = b'gAAAAABjQDv8NOqIhnVGFvKJFB-mNnNLdzc5DJxHb6ThM4RM6c_2qZC1FKtFItAdAe64kOvIxbYMOgRRW02jx1Y55yyWCH7I8g=='
#print(decrypt(key,bytes.fromhex(test)).decode())
\ No newline at end of file
from config import con
import cryptoModule
import os
from hashlib import sha256
import base64
import fingerprintModule as FPM
import time
key = "CAwtEeCpDv7aVJ69Vx01flE-henTDRkenL_mE5WJyVg="
def checkUser(uid):
isAvailable = False
cursor = con.cursor() #mysql method
cursor.execute(f"SELECT * FROM users WHERE uid = {uid}")
result = cursor.fetchall() #getall result
if(len(result) > 0):
isAvailable = True
return(isAvailable)
def insertUser(uid, fname, lname,dob, address, gender, birthLocation):
if(checkUser(uid) == False):
try:
cursor = con.cursor()
sql = f"INSERT INTO users (id, uid, firstname, lastname, address, gender, birth_location,date_of_birth) VALUES (0, {uid}, '{fname}', '{lname}','{address}','{gender}','{birthLocation}','{dob}')"
cursor.execute(sql)
con.commit()
# print("1 record inserted, ID:", cursor.lastrowid)
return True
except:
return False
else:
return False
def getId(uid):
try:
cursor = con.cursor()
cursor.execute(f"SELECT * FROM users WHERE uid = {uid}")
result = cursor.fetchall()
if(len(result) > 0):
return result[0][0]
else:
return False
except:
return False
def uploadToDB(uid, imgData):
if(checkUser(uid)):
try:
cursor = con.cursor()
id = getId(uid)
if(id != False):
sql = f'INSERT INTO face_data (id, u_id, image_data) VALUES (0, {id}, "{imgData}")'
cursor.execute(sql)
con.commit()
# print("1 record inserted, ID:", cursor.lastrowid)
return True
except:
return False
else:
return False
# def convert2Base64(uid):
# isDone = False
# files = os.listdir('resources/')
# for img in files:
# with open(f"resources/{img}", "rb") as img_file:
# imgBase64 = base64.b64encode(img_file.read())
# # print(imgBase64.decode())
# isDone = uploadToDB(uid,str(imgBase64.decode()))
# if(isDone == False):
# print('Error')
# break
# img_file.close()
# print('Done')
def insertFingerPrint(uid, fingerprintId):
try:
cursor = con.cursor()
sql = f'INSERT INTO fingerprint_data (id, u_id, fingerprint) VALUES (0, {uid}, "{fingerprintId}")'
cursor.execute(sql)
con.commit()
# print("1 record inserted, ID:", cursor.lastrowid)
#return True
print("\n[!] Fingerprint Saved!")
time.sleep(1)
print("\n[!] User Registration Completed!")
except:
#return False
print("\nFaild to save the Fingerprnt!")
def readFingerPrint(uid):
try:
cursor = con.cursor()
cursor.execute(f"SELECT * FROM fingerprint_data WHERE u_id = {uid}")
result = cursor.fetchall()
if(len(result) > 0):
return result[0][2]
else:
return False
except:
return False
def fingerReg_handler(uid):
SEQ_NO = len(next(os.walk('resources/'))[1])
hashVal = sha256(str(SEQ_NO).encode('utf-8')).hexdigest()
#print(hashVal)
ret = FPM.fingerprintRegister(SEQ_NO)
if("RET_ID" in ret):
#print(f"{uid}, {hashVal}")
insertFingerPrint(uid,str(hashVal))
def convert2Base64(uid,path):
isDone = False
files = os.listdir(f'resources/{path}')
for img in files:
# print(img)
with open(f"resources/{path}/{img}", "rb") as img_file: #open image by image in binary format
imgBase64 = base64.b64encode(img_file.read()) #opened image convert to base64
# print(imgBase64.decode())
#imageData = imgBase64.decode()
encImgData = cryptoModule.encrypt(key,imgBase64)
isDone = uploadToDB(uid,str(encImgData.hex())) #get correct version of image
if(isDone == False):
# print('Error')
return False
break
img_file.close() #closed the open image file
print("\nFace data saved!\n")
time.sleep(5)
fingerReg_handler(getId(uid))
# return True
#print(insertFingerPrint(7,"1"))
#print(readFingerPrint(1))
# print(getId(45))
# print(insterUser(45,"gggg","ccc"))
#print(checkUser(8520))
# print(convert2Base64(45))
# print(uploadToDB(20,'yyy'))
#print(insertUser(111,"cc","rr","1999-09-26","na","Male","Na"))
#fingerReg_handler(7)
#print(convert2Base64(149990727,"149990727-asd-sad"))
\ No newline at end of file
import serial
import time
comPort = "/dev/ttyACM0" #/dev/ttyACM0
regID = 1
def fingerprintRegister(uuid):
print("\nFinger Print Registration\n")
with serial.Serial(comPort, 9600, timeout=1) as ser:
time.sleep(5)
ser.write(b'a')
while(True):
line = ser.readline()
#if(line):{print(line.decode().strip())}
line = line.decode().strip()
if(":" in line):
line = line.split(":")
#print(line)
if(line[0] in ["FINGER_ID"]):
#print(f"Finger ID : {line[1]}")
ser.close()
return (f"RET_ID:{line[1]}")
#break;
else:
if(line in ["FINGER_ID_REQ"]):
print("[+] Please Place The Finger On The Sensor!")
#return "PLACE_FIN"
time.sleep(3)
#print(str(uid).encode())
ser.write(bytes(str(uuid),'utf-8'))
#time.sleep(2)
elif(line in ["RM_FINGER"]):
print("[!] Remove The Finger")
#return "RM_FIN"
elif(line in ["PLC_S_FINGER_AGAIN"]):
print("[+] Place The Same Finger Again")
#return "PLACE_FIN_AGN"
elif(line in ["IMG_TAKE_SUCCESS"]):
print("[!] Fingerprint Saved")
#return "FIN_SVD"
elif(line in ["COM_ERROR","UNK_ERROR","IMG_ERROR"]):
print("[-] Error Occured. Try Restarting The System :( ")
#return "FIN_ERR"
def fingerprintRead():
with serial.Serial(comPort, 9600, timeout=1) as ser:
time.sleep(3)
ser.write(b'b')
time.sleep(1)
buffer = ['','']
print("\nReady To Read......")
while(True):
line = ser.readline()
line = line.decode().strip()
#if(line):{print(line)}
if(":" in line):
line = line.split(":")
#print(line)
if(line[0] in ["FOUND_ID"]):
#print(f"Finger ID : {line[1]}")
buffer[0] = line[1]
if(line[0] in ["CONFIDENCE_LV"]):
#print(f"Confidence Level : {line[1]}")
buffer[1] = line[1]
return(f"FIN_FOUND:{buffer[0]}:{buffer[1]}")
else:
if(line in ["FINGER_READ_MODE"]):
#print("Ready to read.")
return("READ_READY")
elif(line in ["NO_MATCH"]):
#print("No matching record found!")
return("NO_REC")
"""
if __name__ == '__main__':
while(1):
out = fingerprintRegister(regID)
if("RET_ID" in out):
print(f"out {out}")
else:
print(out)
"""
# if __name__ == '__main__':
# while(1):
# print(fingerprintRead())
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
fuser -k /dev/ttyACM0
import numpy as np #image manipulation
import cv2 #open cv
import time
import dbOps
import os #get the folder path
from multiprocessing import Process
import serial
from random import randint
comPort = "/dev/ttyACM0"
cap = cv2.VideoCapture(0)
cap.set(3,640) #width
cap.set(4,320) #height
sampleCount = 5
imageThreshold = 30 #only face
uidSize = 9
def checkDir(uid,fname,lname):
path = f"resources/{uid}-{fname}-{lname}"
return(os.path.isdir(path))
def fingerprintSensor_ok():
try:
ser = serial.Serial(port=comPort)
ser.close()
return True
except:
return False
def destroyCam():
cap.release()#release the camera
cv2.destroyAllWindows()
def generateID(n):
idStart = 10**(n-1)
idEnd = (10**n)-1
return randint(idStart, idEnd)
def face_detect(uid):
samples = 0
while(True):
path = "" #declare
if(checkDir(uid,fname,lname) == False): #check directery
os.makedirs(f"resources/{uid}-{fname}-{lname}")
path = f"resources/{uid}-{fname}-{lname}" #assign the path
ret, frame = cap.read() #read frame by frame
face_cascade = cv2.CascadeClassifier('haar_face.xml') #open haar cascade algoritham
gray_frm = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) # image enhance bgr to gray
faces = face_cascade.detectMultiScale(gray_frm,1.3,3) #detect the faces from gray frame
for x, y, width, height in faces:
cv2.rectangle(frame, (x, y), (x + width, y + height), color=(255, 0, 0), thickness=2) #detected face rectangle
if(samples < sampleCount):
areaOfInterest = gray_frm[y-imageThreshold : y+height+imageThreshold, x-imageThreshold : x+width+imageThreshold] #increase capture area
try:
cv2.imwrite(f"{path}/{samples+1}.jpeg",areaOfInterest) #save
print(f"Sample Count : {samples+1}") #print
samples += 1
except:
pass
else:
break;
cv2.putText(frame,f'{samples}/{sampleCount}',(10,50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2) #print count
cv2.imshow('cam feed',frame) #display the camera feed frame by frame
if cv2.waitKey(1) & 0xFF == ord('q'): #quit
#cv2.destroyAllWindows()
break #brak the loop
# def cleanUp():
# files = os.listdir('resources/')
# for file in files:
# try:
# os.remove(f"resources/{file}")
# except:
# print("clean up failed")
# cleanUp()
if __name__ == '__main__':
while(not(fingerprintSensor_ok())):
print("Fingerprint Sensor Offline")
time.sleep(5)
else:
if(fingerprintSensor_ok()):print("[!] Fingerprint Sensor Online\n")
newIdPrompt = str(input('Do you want to generate a new ID? Y/N : '))
if(newIdPrompt in ['y','Y']):
uid = str(generateID(uidSize))
while(dbOps.checkUser(uid)):
uid = str(generateID(uidSize))
else:
print(f"New ID : {uid}")
else:
uid = str(input("Enter User ID : "))
fname = str(input("Enter First Name : "))
lname = str(input("Enter Last Name : "))
dob = str(input("Enter Date of Birth (Y-M-D) : "))
address = str(input("Enter Address : "))
gender = str(input("Enter gender : "))
birthLocation = str(input("Enter Birth Location : "))
path = f"{uid}-{fname}-{lname}"
if(dbOps.checkUser(uid)):
print('Uid Already Available')
choice = str(input('Do you want to continue? Y/N : '))
if(choice in ['y','Y']):
time.sleep(2) #wait for 2 seconds
#face_detect(uid)
faceCap_process = Process(target=face_detect, args=(uid,))
faceCap_process.start()
faceCap_process.join()
destroyCam()
time.sleep(2)
#dbOps.convert2Base64(uid,path)#uid - db / path - folder name
dataStore_process = Process(target=dbOps.convert2Base64, args=(uid,path))
dataStore_process.start()
dataStore_process.join()
else:
pass #end
else:
if(dbOps.insertUser(uid,fname,lname,dob,address,gender,birthLocation)):
print('User Added')#print user added
time.sleep(2) #time delay
# face_detect(uid)
# dbOps.convert2Base64(uid,path)
faceCap_process = Process(target=face_detect, args=(uid,))
faceCap_process.start()
faceCap_process.join()
destroyCam()
time.sleep(2)
#dbOps.convert2Base64(uid,path)#uid - db / path - folder name
dataStore_process = Process(target=dbOps.convert2Base64, args=(uid,path))
dataStore_process.start()
dataStore_process.join()
else:
print('Error')
#cap.release()#release the camera
#cv2.destroyAllWindows()#close the window
# cleanUp()
# print(chechDir(uid))
destroyCam()
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment