from django.shortcuts import render,redirect
from .forms import usernameForm,DateForm,UsernameAndDateForm, DateForm_2
from django.contrib import messages
from django.contrib.auth.models import User
import cv2
import dlib
import imutils
from imutils import face_utils
from imutils.video import VideoStream
from imutils.face_utils import rect_to_bb
from imutils.face_utils import FaceAligner
import time
from attendance_system_facial_recognition.settings import BASE_DIR
import os
import face_recognition
from face_recognition.face_recognition_cli import image_files_in_folder
import pickle
from sklearn.preprocessing import LabelEncoder
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
import numpy as np
from django.contrib.auth.decorators import login_required
import matplotlib as mpl
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
import datetime
from django_pandas.io import read_frame
from users.models import Present, Time
import seaborn as sns
import pandas as pd
from django.db.models import Count
#import mpld3
import matplotlib.pyplot as plt
from pandas.plotting import register_matplotlib_converters
from matplotlib import rcParams
import math

mpl.use('Agg')


#utility functions:
def username_present(username):
	if User.objects.filter(username=username).exists():
		return True
	
	return False

def create_dataset(username):
	id = username
	if(os.path.exists('face_recognition_data/training_dataset/{}/'.format(id))==False):
		os.makedirs('face_recognition_data/training_dataset/{}/'.format(id))
	directory='face_recognition_data/training_dataset/{}/'.format(id)

	# Detect face
	#Loading the HOG face detector and the shape predictpr for allignment

	print("[INFO] Loading the facial detector")
	detector = dlib.get_frontal_face_detector()
	predictor = dlib.shape_predictor('face_recognition_data/shape_predictor_68_face_landmarks.dat')   #Add path to the shape predictor ######CHANGE TO RELATIVE PATH LATER
	fa = FaceAligner(predictor , desiredFaceWidth = 96)
	#capture images from the webcam and process and detect the face
	# Initialize the video stream
	print("[INFO] Initializing Video stream")
	vs = VideoStream(src=0).start()
	#time.sleep(2.0) ####CHECK######

	# Our identifier
	# We will put the id here and we will store the id with a face, so that later we can identify whose face it is
	
	# Our dataset naming counter
	sampleNum = 0
	# Capturing the faces one by one and detect the faces and showing it on the window
	while(True):
		# Capturing the image
		#vs.read each frame
		frame = vs.read()
		#Resize each image
		frame = imutils.resize(frame ,width = 800)
		#the returned img is a colored image but for the classifier to work we need a greyscale image
		#to convert
		gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
		#To store the faces
		#This will detect all the images in the current frame, and it will return the coordinates of the faces
		#Takes in image and some other parameter for accurate result
		faces = detector(gray_frame,0)
		#In above 'faces' variable there can be multiple faces so we have to get each and every face and draw a rectangle around it.
		
		
			


		for face in faces:
			print("inside for loop")
			(x,y,w,h) = face_utils.rect_to_bb(face)

			face_aligned = fa.align(frame,gray_frame,face)
			# Whenever the program captures the face, we will write that is a folder
			# Before capturing the face, we need to tell the script whose face it is
			# For that we will need an identifier, here we call it id
			# So now we captured a face, we need to write it in a file
			sampleNum = sampleNum+1
			# Saving the image dataset, but only the face part, cropping the rest
			
			if face is None:
				print("face is none")
				continue


			

			cv2.imwrite(directory+'/'+str(sampleNum)+'.jpg'	, face_aligned)
			face_aligned = imutils.resize(face_aligned ,width = 400)
			#cv2.imshow("Image Captured",face_aligned)
			# @params the initial point of the rectangle will be x,y and
			# @params end point will be x+width and y+height
			# @params along with color of the rectangle
			# @params thickness of the rectangle
			cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),1)
			# Before continuing to the next loop, I want to give it a little pause
			# waitKey of 100 millisecond
			cv2.waitKey(50)

		#Showing the image in another window
		#Creates a window with window name "Face" and with the image img
		cv2.imshow("Add Images",frame)
		#Before closing it we need to give a wait command, otherwise the open cv wont work
		# @params with the millisecond of delay 1
		cv2.waitKey(1)
		#To get out of the loop
		if(sampleNum>300):
			break
	
	#Stoping the videostream
	vs.stop()
	# destroying all the windows
	cv2.destroyAllWindows()


def predict(face_aligned,svc,threshold=0.7):
	face_encodings=np.zeros((1,128))
	try:
		x_face_locations=face_recognition.face_locations(face_aligned)
		faces_encodings=face_recognition.face_encodings(face_aligned,known_face_locations=x_face_locations)
		if(len(faces_encodings)==0):
			return ([-1],[0])

	except:

		return ([-1],[0])

	prob=svc.predict_proba(faces_encodings)
	result=np.where(prob[0]==np.amax(prob[0]))
	if(prob[0][result[0]]<=threshold):
		return ([-1],prob[0][result[0]])

	return (result[0],prob[0][result[0]])


def vizualize_Data(embedded, targets,):
	
	X_embedded = TSNE(n_components=2).fit_transform(embedded)

	for i, t in enumerate(set(targets)):
		idx = targets == t
		plt.scatter(X_embedded[idx, 0], X_embedded[idx, 1], label=t)

	plt.legend(bbox_to_anchor=(1, 1));
	rcParams.update({'figure.autolayout': True})
	plt.tight_layout()	
	plt.savefig('./recognition/static/recognition/img/training_visualisation.png')
	plt.close()



def update_attendance_in_db_in(present):
	today=datetime.date.today()
	time=datetime.datetime.now()
	for person in present:
		user=User.objects.get(username=person)
		try:
		   qs=Present.objects.get(user=user,date=today)
		except :
			qs= None
		
		if qs is None:
			if present[person]==True:
						a=Present(user=user,date=today,present=True)
						a.save()
			else:
				a=Present(user=user,date=today,present=False)
				a.save()
		else:
			if present[person]==True:
				qs.present=True
				qs.save(update_fields=['present'])
		if present[person]==True:
			a=Time(user=user,date=today,time=time, out=False)
			a.save()


			
		




def update_attendance_in_db_out(present):
	today=datetime.date.today()
	time=datetime.datetime.now()
	for person in present:
		user=User.objects.get(username=person)
		if present[person]==True:
			a=Time(user=user,date=today,time=time, out=True)
			a.save()
		




def check_validity_times(times_all):

	if(len(times_all)>0):
		sign=times_all.first().out
	else:
		sign=True
	times_in=times_all.filter(out=False)
	times_out=times_all.filter(out=True)
	if(len(times_in)!=len(times_out)):
		sign=True
	break_hourss=0
	if(sign==True):
			check=False
			break_hourss=0
			return (check,break_hourss)
	prev=True
	prev_time=times_all.first().time

	for obj in times_all:
		curr=obj.out
		if(curr==prev):
			check=False
			break_hourss=0
			return (check,break_hourss)
		if(curr==False):
			curr_time=obj.time
			to=curr_time
			ti=prev_time
			break_time=((to-ti).total_seconds())/3600
			break_hourss+=break_time


		else:
			prev_time=obj.time

		prev=curr

	return (True,break_hourss)


def convert_hours_to_hours_mins(hours):
	
	h=int(hours)
	hours-=h
	m=hours*60
	m=math.ceil(m)
	return str(str(h)+ " hrs " + str(m) + "  mins")

		

#used
def hours_vs_date_given_employee(present_qs,time_qs,admin=True):
	register_matplotlib_converters()
	df_hours=[]
	df_break_hours=[]
	qs=present_qs

	for obj in qs:
		date=obj.date
		times_in=time_qs.filter(date=date).filter(out=False).order_by('time')
		times_out=time_qs.filter(date=date).filter(out=True).order_by('time')
		times_all=time_qs.filter(date=date).order_by('time')
		obj.time_in=None
		obj.time_out=None
		obj.hours=0
		obj.break_hours=0
		if (len(times_in)>0):			
			obj.time_in=times_in.first().time
			
		if (len(times_out)>0):
			obj.time_out=times_out.last().time

		if(obj.time_in is not None and obj.time_out is not None):
			ti=obj.time_in
			to=obj.time_out
			hours=((to-ti).total_seconds())/3600
			obj.hours=hours
		

		else:
			obj.hours=0

		(check,break_hourss)= check_validity_times(times_all)
		if check:
			obj.break_hours=break_hourss


		else:
			obj.break_hours=0


		
		df_hours.append(obj.hours)
		df_break_hours.append(obj.break_hours)
		obj.hours=convert_hours_to_hours_mins(obj.hours)
		obj.break_hours=convert_hours_to_hours_mins(obj.break_hours)
			
	
	
	
	df = read_frame(qs)	
	
	
	df["hours"]=df_hours
	df["break_hours"]=df_break_hours

	print(df)
	
	sns.barplot(data=df,x='date',y='hours')
	plt.xticks(rotation='vertical')
	rcParams.update({'figure.autolayout': True})
	plt.tight_layout()
	if(admin):
		plt.savefig('./recognition/static/recognition/img/attendance_graphs/hours_vs_date/1.png')
		plt.close()
	else:
		plt.savefig('./recognition/static/recognition/img/attendance_graphs/employee_login/1.png')
		plt.close()
	return qs
	

#used
def hours_vs_employee_given_date(present_qs,time_qs):
	register_matplotlib_converters()
	df_hours=[]
	df_break_hours=[]
	df_username=[]
	qs=present_qs

	for obj in qs:
		user=obj.user
		times_in=time_qs.filter(user=user).filter(out=False)
		times_out=time_qs.filter(user=user).filter(out=True)
		times_all=time_qs.filter(user=user)
		obj.time_in=None
		obj.time_out=None
		obj.hours=0
		obj.hours=0
		if (len(times_in)>0):			
			obj.time_in=times_in.first().time
		if (len(times_out)>0):
			obj.time_out=times_out.last().time
		if(obj.time_in is not None and obj.time_out is not None):
			ti=obj.time_in
			to=obj.time_out
			hours=((to-ti).total_seconds())/3600
			obj.hours=hours
		else:
			obj.hours=0
		(check,break_hourss)= check_validity_times(times_all)
		if check:
			obj.break_hours=break_hourss


		else:
			obj.break_hours=0

		
		df_hours.append(obj.hours)
		df_username.append(user.username)
		df_break_hours.append(obj.break_hours)
		obj.hours=convert_hours_to_hours_mins(obj.hours)
		obj.break_hours=convert_hours_to_hours_mins(obj.break_hours)

	



	df = read_frame(qs)	
	df['hours']=df_hours
	df['username']=df_username
	df["break_hours"]=df_break_hours


	sns.barplot(data=df,x='username',y='hours')
	plt.xticks(rotation='vertical')
	rcParams.update({'figure.autolayout': True})
	plt.tight_layout()
	plt.savefig('./recognition/static/recognition/img/attendance_graphs/hours_vs_employee/1.png')
	plt.close()
	return qs


def total_number_employees():
	qs=User.objects.all()
	return (len(qs) -1)
	# -1 to account for admin 



def employees_present_today():
	today=datetime.date.today()
	qs=Present.objects.filter(date=today).filter(present=True)
	return len(qs)




#used	
def this_week_emp_count_vs_date():
	today=datetime.date.today()
	some_day_last_week=today-datetime.timedelta(days=7)
	monday_of_last_week=some_day_last_week-  datetime.timedelta(days=(some_day_last_week.isocalendar()[2] - 1))
	monday_of_this_week = monday_of_last_week + datetime.timedelta(days=7)
	qs=Present.objects.filter(date__gte=monday_of_this_week).filter(date__lte=today)
	str_dates=[]
	emp_count=[]
	str_dates_all=[]
	emp_cnt_all=[]
	cnt=0
	
	



	for obj in qs:
		date=obj.date
		str_dates.append(str(date))
		qs=Present.objects.filter(date=date).filter(present=True)
		emp_count.append(len(qs))


	while(cnt<5):

		date=str(monday_of_this_week+datetime.timedelta(days=cnt))
		cnt+=1
		str_dates_all.append(date)
		if(str_dates.count(date))>0:
			idx=str_dates.index(date)

			emp_cnt_all.append(emp_count[idx])
		else:
			emp_cnt_all.append(0)

	
	
	



	df=pd.DataFrame()
	df["date"]=str_dates_all
	df["Number of employees"]=emp_cnt_all
	
	
	sns.lineplot(data=df,x='date',y='Number of employees')
	plt.savefig('./recognition/static/recognition/img/attendance_graphs/this_week/1.png')
	plt.close()






#used
def last_week_emp_count_vs_date():
	today=datetime.date.today()
	some_day_last_week=today-datetime.timedelta(days=7)
	monday_of_last_week=some_day_last_week-  datetime.timedelta(days=(some_day_last_week.isocalendar()[2] - 1))
	monday_of_this_week = monday_of_last_week + datetime.timedelta(days=7)
	qs=Present.objects.filter(date__gte=monday_of_last_week).filter(date__lt=monday_of_this_week)
	str_dates=[]
	emp_count=[]


	str_dates_all=[]
	emp_cnt_all=[]
	cnt=0
	

	for obj in qs:
		date=obj.date
		str_dates.append(str(date))
		qs=Present.objects.filter(date=date).filter(present=True)
		emp_count.append(len(qs))


	while(cnt<5):

		date=str(monday_of_last_week+datetime.timedelta(days=cnt))
		cnt+=1
		str_dates_all.append(date)
		if(str_dates.count(date))>0:
			idx=str_dates.index(date)

			emp_cnt_all.append(emp_count[idx])
			
		else:
			emp_cnt_all.append(0)

	
	
	



	df=pd.DataFrame()
	df["date"]=str_dates_all
	df["emp_count"]=emp_cnt_all
	

	
	
	sns.lineplot(data=df,x='date',y='emp_count')
	plt.savefig('./recognition/static/recognition/img/attendance_graphs/last_week/1.png')
	plt.close()


		





# Create your views here.
def home(request):

	return render(request, 'recognition/home.html')

@login_required
def dashboard(request):
	if(request.user.username=='admin'):
		print("admin")
		return render(request, 'recognition/admin_dashboard.html')
	else:
		print("not admin")

		return render(request,'recognition/employee_dashboard.html')

@login_required
def add_photos(request):
	if request.user.username!='admin':
		return redirect('not-authorised')
	if request.method=='POST':
		form=usernameForm(request.POST)
		data = request.POST.copy()
		username=data.get('username')
		if username_present(username):
			create_dataset(username)
			messages.success(request, f'Dataset Created')
			return redirect('add-photos')
		else:
			messages.warning(request, f'No such username found. Please register employee first.')
			return redirect('dashboard')


	else:
		

			form=usernameForm()
			return render(request,'recognition/add_photos.html', {'form' : form})



def mark_your_attendance(request):
	
	

	
	detector = dlib.get_frontal_face_detector()
	
	predictor = dlib.shape_predictor('face_recognition_data/shape_predictor_68_face_landmarks.dat')   #Add path to the shape predictor ######CHANGE TO RELATIVE PATH LATER
	svc_save_path="face_recognition_data/svc.sav"	


		
			
	with open(svc_save_path, 'rb') as f:
			svc = pickle.load(f)
	fa = FaceAligner(predictor , desiredFaceWidth = 96)
	encoder=LabelEncoder()
	encoder.classes_ = np.load('face_recognition_data/classes.npy')


	faces_encodings = np.zeros((1,128))
	no_of_faces = len(svc.predict_proba(faces_encodings)[0])
	count = dict()
	present = dict()
	log_time = dict()
	start = dict()
	for i in range(no_of_faces):
		count[encoder.inverse_transform([i])[0]] = 0
		present[encoder.inverse_transform([i])[0]] = False

	

	vs = VideoStream(src=0).start()
	
	sampleNum = 0
	
	while(True):
		
		frame = vs.read()
		
		frame = imutils.resize(frame ,width = 800)
		
		gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
		
		faces = detector(gray_frame,0)
		
		


		for face in faces:
			print("INFO : inside for loop")
			(x,y,w,h) = face_utils.rect_to_bb(face)

			face_aligned = fa.align(frame,gray_frame,face)
			cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),1)
					
			
			(pred,prob)=predict(face_aligned,svc)
			

			
			if(pred!=[-1]):
				
				person_name=encoder.inverse_transform(np.ravel([pred]))[0]
				pred=person_name
				if count[pred] == 0:
					start[pred] = time.time()
					count[pred] = count.get(pred,0) + 1

				if count[pred] == 4 and (time.time()-start[pred]) > 1.2:
					 count[pred] = 0
				else:
				#if count[pred] == 4 and (time.time()-start) <= 1.5:
					present[pred] = True
					log_time[pred] = datetime.datetime.now()
					count[pred] = count.get(pred,0) + 1
					print(pred, present[pred], count[pred])
				cv2.putText(frame, str(person_name)+ str(prob), (x+6,y+h-6), cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,255,0),1)

			else:
				person_name="unknown"
				cv2.putText(frame, str(person_name), (x+6,y+h-6), cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,255,0),1)

			
			
			#cv2.putText()
			# Before continuing to the next loop, I want to give it a little pause
			# waitKey of 100 millisecond
			#cv2.waitKey(50)

		#Showing the image in another window
		#Creates a window with window name "Face" and with the image img
		cv2.imshow("Mark Attendance - In - Press q to exit",frame)
		#Before closing it we need to give a wait command, otherwise the open cv wont work
		# @params with the millisecond of delay 1
		#cv2.waitKey(1)
		#To get out of the loop
		key=cv2.waitKey(50) & 0xFF
		if(key==ord("q")):
			break
	
	#Stoping the videostream
	vs.stop()

	# destroying all the windows
	cv2.destroyAllWindows()
	update_attendance_in_db_in(present)
	return redirect('home')



def mark_your_attendance_out(request):
	

	
	detector = dlib.get_frontal_face_detector()
	
	predictor = dlib.shape_predictor('face_recognition_data/shape_predictor_68_face_landmarks.dat')   #Add path to the shape predictor ######CHANGE TO RELATIVE PATH LATER
	svc_save_path="face_recognition_data/svc.sav"	


		
			
	with open(svc_save_path, 'rb') as f:
			svc = pickle.load(f)
	fa = FaceAligner(predictor , desiredFaceWidth = 96)
	encoder=LabelEncoder()
	encoder.classes_ = np.load('face_recognition_data/classes.npy')


	faces_encodings = np.zeros((1,128))
	no_of_faces = len(svc.predict_proba(faces_encodings)[0])
	count = dict()
	present = dict()
	log_time = dict()
	start = dict()
	for i in range(no_of_faces):
		count[encoder.inverse_transform([i])[0]] = 0
		present[encoder.inverse_transform([i])[0]] = False

	

	vs = VideoStream(src=0).start()
	
	sampleNum = 0
	
	while(True):
		
		frame = vs.read()
		
		frame = imutils.resize(frame ,width = 800)
		
		gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
		
		faces = detector(gray_frame,0)
		
		


		for face in faces:
			print("INFO : inside for loop")
			(x,y,w,h) = face_utils.rect_to_bb(face)

			face_aligned = fa.align(frame,gray_frame,face)
			cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),1)
					
			
			(pred,prob)=predict(face_aligned,svc)
			

			
			if(pred!=[-1]):
				
				person_name=encoder.inverse_transform(np.ravel([pred]))[0]
				pred=person_name
				if count[pred] == 0:
					start[pred] = time.time()
					count[pred] = count.get(pred,0) + 1

				if count[pred] == 4 and (time.time()-start[pred]) > 1.5:
					 count[pred] = 0
				else:
				#if count[pred] == 4 and (time.time()-start) <= 1.5:
					present[pred] = True
					log_time[pred] = datetime.datetime.now()
					count[pred] = count.get(pred,0) + 1
					print(pred, present[pred], count[pred])
				cv2.putText(frame, str(person_name)+ str(prob), (x+6,y+h-6), cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,255,0),1)

			else:
				person_name="unknown"
				cv2.putText(frame, str(person_name), (x+6,y+h-6), cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,255,0),1)

			
			
			#cv2.putText()
			# Before continuing to the next loop, I want to give it a little pause
			# waitKey of 100 millisecond
			#cv2.waitKey(50)

		#Showing the image in another window
		#Creates a window with window name "Face" and with the image img
		cv2.imshow("Mark Attendance- Out - Press q to exit",frame)
		#Before closing it we need to give a wait command, otherwise the open cv wont work
		# @params with the millisecond of delay 1
		#cv2.waitKey(1)
		#To get out of the loop
		key=cv2.waitKey(50) & 0xFF
		if(key==ord("q")):
			break
	
	#Stoping the videostream
	vs.stop()

	# destroying all the windows
	cv2.destroyAllWindows()
	update_attendance_in_db_out(present)
	return redirect('home')




@login_required
def train(request):
	if request.user.username!='admin':
		return redirect('not-authorised')

	training_dir='face_recognition_data/training_dataset'
	
	
	
	count=0
	for person_name in os.listdir(training_dir):
		curr_directory=os.path.join(training_dir,person_name)
		if not os.path.isdir(curr_directory):
			continue
		for imagefile in image_files_in_folder(curr_directory):
			count+=1

	X=[]
	y=[]
	i=0


	for person_name in os.listdir(training_dir):
		print(str(person_name))
		curr_directory=os.path.join(training_dir,person_name)
		if not os.path.isdir(curr_directory):
			continue
		for imagefile in image_files_in_folder(curr_directory):
			print(str(imagefile))
			image=cv2.imread(imagefile)
			try:
				X.append((face_recognition.face_encodings(image)[0]).tolist())
				

				
				y.append(person_name)
				i+=1
			except:
				print("removed")
				os.remove(imagefile)

			


	targets=np.array(y)
	encoder = LabelEncoder()
	encoder.fit(y)
	y=encoder.transform(y)
	X1=np.array(X)
	print("shape: "+ str(X1.shape))
	np.save('face_recognition_data/classes.npy', encoder.classes_)
	svc = SVC(kernel='linear',probability=True)
	svc.fit(X1,y)
	svc_save_path="face_recognition_data/svc.sav"
	with open(svc_save_path, 'wb') as f:
		pickle.dump(svc,f)

	
	vizualize_Data(X1,targets)
	
	messages.success(request, f'Training Complete.')

	return render(request,"recognition/train.html")


@login_required
def not_authorised(request):
	return render(request,'recognition/not_authorised.html')



@login_required
def view_attendance_home(request):
	total_num_of_emp=total_number_employees()
	emp_present_today=employees_present_today()
	this_week_emp_count_vs_date()
	last_week_emp_count_vs_date()
	return render(request,"recognition/view_attendance_home.html", {'total_num_of_emp' : total_num_of_emp, 'emp_present_today': emp_present_today})


@login_required
def view_attendance_date(request):
	if request.user.username!='admin':
		return redirect('not-authorised')
	qs=None
	time_qs=None
	present_qs=None


	if request.method=='POST':
		form=DateForm(request.POST)
		if form.is_valid():
			date=form.cleaned_data.get('date')
			print("date:"+ str(date))
			time_qs=Time.objects.filter(date=date)
			present_qs=Present.objects.filter(date=date)
			if(len(time_qs)>0 or len(present_qs)>0):
				qs=hours_vs_employee_given_date(present_qs,time_qs)


				return render(request,'recognition/view_attendance_date.html', {'form' : form,'qs' : qs })
			else:
				messages.warning(request, f'No records for selected date.')
				return redirect('view-attendance-date')


			
			
			
		


	else:
		

			form=DateForm()
			return render(request,'recognition/view_attendance_date.html', {'form' : form, 'qs' : qs})


@login_required
def view_attendance_employee(request):
	if request.user.username!='admin':
		return redirect('not-authorised')
	time_qs=None
	present_qs=None
	qs=None

	if request.method=='POST':
		form=UsernameAndDateForm(request.POST)
		if form.is_valid():
			username=form.cleaned_data.get('username')
			if username_present(username):
				
				u=User.objects.get(username=username)
				
				time_qs=Time.objects.filter(user=u)
				present_qs=Present.objects.filter(user=u)
				date_from=form.cleaned_data.get('date_from')
				date_to=form.cleaned_data.get('date_to')
				
				if date_to < date_from:
					messages.warning(request, f'Invalid date selection.')
					return redirect('view-attendance-employee')
				else:
					

					time_qs=time_qs.filter(date__gte=date_from).filter(date__lte=date_to).order_by('-date')
					present_qs=present_qs.filter(date__gte=date_from).filter(date__lte=date_to).order_by('-date')
					
					if (len(time_qs)>0 or len(present_qs)>0):
						qs=hours_vs_date_given_employee(present_qs,time_qs,admin=True)
						return render(request,'recognition/view_attendance_employee.html', {'form' : form, 'qs' :qs})
					else:
						#print("inside qs is None")
						messages.warning(request, f'No records for selected duration.')
						return redirect('view-attendance-employee')



			
			
				
			else:
				print("invalid username")
				messages.warning(request, f'No such username found.')
				return redirect('view-attendance-employee')


	else:
		

			form=UsernameAndDateForm()
			return render(request,'recognition/view_attendance_employee.html', {'form' : form, 'qs' :qs})




@login_required
def view_my_attendance_employee_login(request):
	if request.user.username=='admin':
		return redirect('not-authorised')
	qs=None
	time_qs=None
	present_qs=None
	if request.method=='POST':
		form=DateForm_2(request.POST)
		if form.is_valid():
			u=request.user
			time_qs=Time.objects.filter(user=u)
			present_qs=Present.objects.filter(user=u)
			date_from=form.cleaned_data.get('date_from')
			date_to=form.cleaned_data.get('date_to')
			if date_to < date_from:
					messages.warning(request, f'Invalid date selection.')
					return redirect('view-my-attendance-employee-login')
			else:
					

					time_qs=time_qs.filter(date__gte=date_from).filter(date__lte=date_to).order_by('-date')
					present_qs=present_qs.filter(date__gte=date_from).filter(date__lte=date_to).order_by('-date')
				
					if (len(time_qs)>0 or len(present_qs)>0):
						qs=hours_vs_date_given_employee(present_qs,time_qs,admin=False)
						return render(request,'recognition/view_my_attendance_employee_login.html', {'form' : form, 'qs' :qs})
					else:
						
						messages.warning(request, f'No records for selected duration.')
						return redirect('view-my-attendance-employee-login')
	else:
		

			form=DateForm_2()
			return render(request,'recognition/view_my_attendance_employee_login.html', {'form' : form, 'qs' :qs})
[((1205, 1219), 'matplotlib.use', 'mpl.use', (['"""Agg"""'], {}), "('Agg')\n", (1212, 1219), True, 'import matplotlib as mpl\n'), ((1771, 1803), 'dlib.get_frontal_face_detector', 'dlib.get_frontal_face_detector', ([], {}), '()\n', (1801, 1803), False, 'import dlib\n'), ((1817, 1905), 'dlib.shape_predictor', 'dlib.shape_predictor', (['"""face_recognition_data/shape_predictor_68_face_landmarks.dat"""'], {}), "(\n    'face_recognition_data/shape_predictor_68_face_landmarks.dat')\n", (1837, 1905), False, 'import dlib\n'), ((1978, 2021), 'imutils.face_utils.FaceAligner', 'FaceAligner', (['predictor'], {'desiredFaceWidth': '(96)'}), '(predictor, desiredFaceWidth=96)\n', (1989, 2021), False, 'from imutils.face_utils import FaceAligner\n'), ((4719, 4742), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (4740, 4742), False, 'import cv2\n'), ((4806, 4824), 'numpy.zeros', 'np.zeros', (['(1, 128)'], {}), '((1, 128))\n', (4814, 4824), True, 'import numpy as np\n'), ((5505, 5538), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'bbox_to_anchor': '(1, 1)'}), '(bbox_to_anchor=(1, 1))\n', (5515, 5538), True, 'import matplotlib.pyplot as plt\n'), ((5541, 5585), 'matplotlib.rcParams.update', 'rcParams.update', (["{'figure.autolayout': True}"], {}), "({'figure.autolayout': True})\n", (5556, 5585), False, 'from matplotlib import rcParams\n'), ((5587, 5605), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (5603, 5605), True, 'import matplotlib.pyplot as plt\n'), ((5608, 5686), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""./recognition/static/recognition/img/training_visualisation.png"""'], {}), "('./recognition/static/recognition/img/training_visualisation.png')\n", (5619, 5686), True, 'import matplotlib.pyplot as plt\n'), ((5688, 5699), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (5697, 5699), True, 'import matplotlib.pyplot as plt\n'), ((5751, 5772), 'datetime.date.today', 'datetime.date.today', ([], {}), '()\n', (5770, 5772), False, 'import datetime\n'), ((5779, 5802), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (5800, 5802), False, 'import datetime\n'), ((6386, 6407), 'datetime.date.today', 'datetime.date.today', ([], {}), '()\n', (6405, 6407), False, 'import datetime\n'), ((6414, 6437), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (6435, 6437), False, 'import datetime\n'), ((7401, 7413), 'math.ceil', 'math.ceil', (['m'], {}), '(m)\n', (7410, 7413), False, 'import math\n'), ((7540, 7572), 'pandas.plotting.register_matplotlib_converters', 'register_matplotlib_converters', ([], {}), '()\n', (7570, 7572), False, 'from pandas.plotting import register_matplotlib_converters\n'), ((8577, 8591), 'django_pandas.io.read_frame', 'read_frame', (['qs'], {}), '(qs)\n', (8587, 8591), False, 'from django_pandas.io import read_frame\n'), ((8668, 8709), 'seaborn.barplot', 'sns.barplot', ([], {'data': 'df', 'x': '"""date"""', 'y': '"""hours"""'}), "(data=df, x='date', y='hours')\n", (8679, 8709), True, 'import seaborn as sns\n'), ((8709, 8740), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '"""vertical"""'}), "(rotation='vertical')\n", (8719, 8740), True, 'import matplotlib.pyplot as plt\n'), ((8742, 8786), 'matplotlib.rcParams.update', 'rcParams.update', (["{'figure.autolayout': True}"], {}), "({'figure.autolayout': True})\n", (8757, 8786), False, 'from matplotlib import rcParams\n'), ((8788, 8806), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (8804, 8806), True, 'import matplotlib.pyplot as plt\n'), ((9114, 9146), 'pandas.plotting.register_matplotlib_converters', 'register_matplotlib_converters', ([], {}), '()\n', (9144, 9146), False, 'from pandas.plotting import register_matplotlib_converters\n'), ((10131, 10145), 'django_pandas.io.read_frame', 'read_frame', (['qs'], {}), '(qs)\n', (10141, 10145), False, 'from django_pandas.io import read_frame\n'), ((10234, 10279), 'seaborn.barplot', 'sns.barplot', ([], {'data': 'df', 'x': '"""username"""', 'y': '"""hours"""'}), "(data=df, x='username', y='hours')\n", (10245, 10279), True, 'import seaborn as sns\n'), ((10279, 10310), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '"""vertical"""'}), "(rotation='vertical')\n", (10289, 10310), True, 'import matplotlib.pyplot as plt\n'), ((10312, 10356), 'matplotlib.rcParams.update', 'rcParams.update', (["{'figure.autolayout': True}"], {}), "({'figure.autolayout': True})\n", (10327, 10356), False, 'from matplotlib import rcParams\n'), ((10358, 10376), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (10374, 10376), True, 'import matplotlib.pyplot as plt\n'), ((10378, 10481), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""./recognition/static/recognition/img/attendance_graphs/hours_vs_employee/1.png"""'], {}), "(\n    './recognition/static/recognition/img/attendance_graphs/hours_vs_employee/1.png'\n    )\n", (10389, 10481), True, 'import matplotlib.pyplot as plt\n'), ((10473, 10484), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (10482, 10484), True, 'import matplotlib.pyplot as plt\n'), ((10532, 10550), 'django.contrib.auth.models.User.objects.all', 'User.objects.all', ([], {}), '()\n', (10548, 10550), False, 'from django.contrib.auth.models import User\n'), ((10641, 10662), 'datetime.date.today', 'datetime.date.today', ([], {}), '()\n', (10660, 10662), False, 'import datetime\n'), ((10792, 10813), 'datetime.date.today', 'datetime.date.today', ([], {}), '()\n', (10811, 10813), False, 'import datetime\n'), ((11619, 11633), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (11631, 11633), True, 'import pandas as pd\n'), ((11704, 11760), 'seaborn.lineplot', 'sns.lineplot', ([], {'data': 'df', 'x': '"""date"""', 'y': '"""Number of employees"""'}), "(data=df, x='date', y='Number of employees')\n", (11716, 11760), True, 'import seaborn as sns\n'), ((11760, 11850), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""./recognition/static/recognition/img/attendance_graphs/this_week/1.png"""'], {}), "(\n    './recognition/static/recognition/img/attendance_graphs/this_week/1.png')\n", (11771, 11850), True, 'import matplotlib.pyplot as plt\n'), ((11847, 11858), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (11856, 11858), True, 'import matplotlib.pyplot as plt\n'), ((11913, 11934), 'datetime.date.today', 'datetime.date.today', ([], {}), '()\n', (11932, 11934), False, 'import datetime\n'), ((12755, 12769), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (12767, 12769), True, 'import pandas as pd\n'), ((12833, 12879), 'seaborn.lineplot', 'sns.lineplot', ([], {'data': 'df', 'x': '"""date"""', 'y': '"""emp_count"""'}), "(data=df, x='date', y='emp_count')\n", (12845, 12879), True, 'import seaborn as sns\n'), ((12879, 12969), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""./recognition/static/recognition/img/attendance_graphs/last_week/1.png"""'], {}), "(\n    './recognition/static/recognition/img/attendance_graphs/last_week/1.png')\n", (12890, 12969), True, 'import matplotlib.pyplot as plt\n'), ((12966, 12977), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (12975, 12977), True, 'import matplotlib.pyplot as plt\n'), ((13042, 13082), 'django.shortcuts.render', 'render', (['request', '"""recognition/home.html"""'], {}), "(request, 'recognition/home.html')\n", (13048, 13082), False, 'from django.shortcuts import render, redirect\n'), ((14006, 14038), 'dlib.get_frontal_face_detector', 'dlib.get_frontal_face_detector', ([], {}), '()\n', (14036, 14038), False, 'import dlib\n'), ((14054, 14142), 'dlib.shape_predictor', 'dlib.shape_predictor', (['"""face_recognition_data/shape_predictor_68_face_landmarks.dat"""'], {}), "(\n    'face_recognition_data/shape_predictor_68_face_landmarks.dat')\n", (14074, 14142), False, 'import dlib\n'), ((14334, 14377), 'imutils.face_utils.FaceAligner', 'FaceAligner', (['predictor'], {'desiredFaceWidth': '(96)'}), '(predictor, desiredFaceWidth=96)\n', (14345, 14377), False, 'from imutils.face_utils import FaceAligner\n'), ((14390, 14404), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (14402, 14404), False, 'from sklearn.preprocessing import LabelEncoder\n'), ((14425, 14469), 'numpy.load', 'np.load', (['"""face_recognition_data/classes.npy"""'], {}), "('face_recognition_data/classes.npy')\n", (14432, 14469), True, 'import numpy as np\n'), ((14491, 14509), 'numpy.zeros', 'np.zeros', (['(1, 128)'], {}), '((1, 128))\n', (14499, 14509), True, 'import numpy as np\n'), ((16648, 16671), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (16669, 16671), False, 'import cv2\n'), ((16717, 16733), 'django.shortcuts.redirect', 'redirect', (['"""home"""'], {}), "('home')\n", (16725, 16733), False, 'from django.shortcuts import render, redirect\n'), ((16793, 16825), 'dlib.get_frontal_face_detector', 'dlib.get_frontal_face_detector', ([], {}), '()\n', (16823, 16825), False, 'import dlib\n'), ((16841, 16929), 'dlib.shape_predictor', 'dlib.shape_predictor', (['"""face_recognition_data/shape_predictor_68_face_landmarks.dat"""'], {}), "(\n    'face_recognition_data/shape_predictor_68_face_landmarks.dat')\n", (16861, 16929), False, 'import dlib\n'), ((17121, 17164), 'imutils.face_utils.FaceAligner', 'FaceAligner', (['predictor'], {'desiredFaceWidth': '(96)'}), '(predictor, desiredFaceWidth=96)\n', (17132, 17164), False, 'from imutils.face_utils import FaceAligner\n'), ((17177, 17191), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (17189, 17191), False, 'from sklearn.preprocessing import LabelEncoder\n'), ((17212, 17256), 'numpy.load', 'np.load', (['"""face_recognition_data/classes.npy"""'], {}), "('face_recognition_data/classes.npy')\n", (17219, 17256), True, 'import numpy as np\n'), ((17278, 17296), 'numpy.zeros', 'np.zeros', (['(1, 128)'], {}), '((1, 128))\n', (17286, 17296), True, 'import numpy as np\n'), ((19435, 19458), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (19456, 19458), False, 'import cv2\n'), ((19505, 19521), 'django.shortcuts.redirect', 'redirect', (['"""home"""'], {}), "('home')\n", (19513, 19521), False, 'from django.shortcuts import render, redirect\n'), ((19725, 19749), 'os.listdir', 'os.listdir', (['training_dir'], {}), '(training_dir)\n', (19735, 19749), False, 'import os\n'), ((19969, 19993), 'os.listdir', 'os.listdir', (['training_dir'], {}), '(training_dir)\n', (19979, 19993), False, 'import os\n'), ((20437, 20448), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (20445, 20448), True, 'import numpy as np\n'), ((20460, 20474), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (20472, 20474), False, 'from sklearn.preprocessing import LabelEncoder\n'), ((20519, 20530), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (20527, 20530), True, 'import numpy as np\n'), ((20565, 20627), 'numpy.save', 'np.save', (['"""face_recognition_data/classes.npy"""', 'encoder.classes_'], {}), "('face_recognition_data/classes.npy', encoder.classes_)\n", (20572, 20627), True, 'import numpy as np\n'), ((20635, 20673), 'sklearn.svm.SVC', 'SVC', ([], {'kernel': '"""linear"""', 'probability': '(True)'}), "(kernel='linear', probability=True)\n", (20638, 20673), False, 'from sklearn.svm import SVC\n'), ((20828, 20876), 'django.contrib.messages.success', 'messages.success', (['request', 'f"""Training Complete."""'], {}), "(request, f'Training Complete.')\n", (20844, 20876), False, 'from django.contrib import messages\n'), ((20886, 20927), 'django.shortcuts.render', 'render', (['request', '"""recognition/train.html"""'], {}), "(request, 'recognition/train.html')\n", (20892, 20927), False, 'from django.shortcuts import render, redirect\n'), ((20982, 21032), 'django.shortcuts.render', 'render', (['request', '"""recognition/not_authorised.html"""'], {}), "(request, 'recognition/not_authorised.html')\n", (20988, 21032), False, 'from django.shortcuts import render, redirect\n'), ((21244, 21389), 'django.shortcuts.render', 'render', (['request', '"""recognition/view_attendance_home.html"""', "{'total_num_of_emp': total_num_of_emp, 'emp_present_today': emp_present_today}"], {}), "(request, 'recognition/view_attendance_home.html', {\n    'total_num_of_emp': total_num_of_emp, 'emp_present_today':\n    emp_present_today})\n", (21250, 21389), False, 'from django.shortcuts import render, redirect\n'), ((2604, 2636), 'imutils.resize', 'imutils.resize', (['frame'], {'width': '(800)'}), '(frame, width=800)\n', (2618, 2636), False, 'import imutils\n'), ((2764, 2803), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2GRAY'], {}), '(frame, cv2.COLOR_BGR2GRAY)\n', (2776, 2803), False, 'import cv2\n'), ((4416, 4447), 'cv2.imshow', 'cv2.imshow', (['"""Add Images"""', 'frame'], {}), "('Add Images', frame)\n", (4426, 4447), False, 'import cv2\n'), ((4578, 4592), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (4589, 4592), False, 'import cv2\n'), ((4849, 4894), 'face_recognition.face_locations', 'face_recognition.face_locations', (['face_aligned'], {}), '(face_aligned)\n', (4880, 4894), False, 'import face_recognition\n'), ((4913, 5002), 'face_recognition.face_encodings', 'face_recognition.face_encodings', (['face_aligned'], {'known_face_locations': 'x_face_locations'}), '(face_aligned, known_face_locations=\n    x_face_locations)\n', (4944, 5002), False, 'import face_recognition\n'), ((5442, 5502), 'matplotlib.pyplot.scatter', 'plt.scatter', (['X_embedded[idx, 0]', 'X_embedded[idx, 1]'], {'label': 't'}), '(X_embedded[idx, 0], X_embedded[idx, 1], label=t)\n', (5453, 5502), True, 'import matplotlib.pyplot as plt\n'), ((5834, 5867), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', ([], {'username': 'person'}), '(username=person)\n', (5850, 5867), False, 'from django.contrib.auth.models import User\n'), ((6469, 6502), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', ([], {'username': 'person'}), '(username=person)\n', (6485, 6502), False, 'from django.contrib.auth.models import User\n'), ((8821, 8920), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""./recognition/static/recognition/img/attendance_graphs/hours_vs_date/1.png"""'], {}), "(\n    './recognition/static/recognition/img/attendance_graphs/hours_vs_date/1.png'\n    )\n", (8832, 8920), True, 'import matplotlib.pyplot as plt\n'), ((8913, 8924), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (8922, 8924), True, 'import matplotlib.pyplot as plt\n'), ((8934, 9034), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""./recognition/static/recognition/img/attendance_graphs/employee_login/1.png"""'], {}), "(\n    './recognition/static/recognition/img/attendance_graphs/employee_login/1.png'\n    )\n", (8945, 9034), True, 'import matplotlib.pyplot as plt\n'), ((9027, 9038), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (9036, 9038), True, 'import matplotlib.pyplot as plt\n'), ((10840, 10866), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(7)'}), '(days=7)\n', (10858, 10866), False, 'import datetime\n'), ((11021, 11047), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(7)'}), '(days=7)\n', (11039, 11047), False, 'import datetime\n'), ((11961, 11987), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(7)'}), '(days=7)\n', (11979, 11987), False, 'import datetime\n'), ((12142, 12168), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(7)'}), '(days=7)\n', (12160, 12168), False, 'import datetime\n'), ((13187, 13238), 'django.shortcuts.render', 'render', (['request', '"""recognition/admin_dashboard.html"""'], {}), "(request, 'recognition/admin_dashboard.html')\n", (13193, 13238), False, 'from django.shortcuts import render, redirect\n'), ((13277, 13331), 'django.shortcuts.render', 'render', (['request', '"""recognition/employee_dashboard.html"""'], {}), "(request, 'recognition/employee_dashboard.html')\n", (13283, 13331), False, 'from django.shortcuts import render, redirect\n'), ((13418, 13444), 'django.shortcuts.redirect', 'redirect', (['"""not-authorised"""'], {}), "('not-authorised')\n", (13426, 13444), False, 'from django.shortcuts import render, redirect\n'), ((13886, 13948), 'django.shortcuts.render', 'render', (['request', '"""recognition/add_photos.html"""', "{'form': form}"], {}), "(request, 'recognition/add_photos.html', {'form': form})\n", (13892, 13948), False, 'from django.shortcuts import render, redirect\n'), ((14313, 14327), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (14324, 14327), False, 'import pickle\n'), ((14872, 14904), 'imutils.resize', 'imutils.resize', (['frame'], {'width': '(800)'}), '(frame, width=800)\n', (14886, 14904), False, 'import imutils\n'), ((14925, 14964), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2GRAY'], {}), '(frame, cv2.COLOR_BGR2GRAY)\n', (14937, 14964), False, 'import cv2\n'), ((16286, 16345), 'cv2.imshow', 'cv2.imshow', (['"""Mark Attendance - In - Press q to exit"""', 'frame'], {}), "('Mark Attendance - In - Press q to exit', frame)\n", (16296, 16345), False, 'import cv2\n'), ((17100, 17114), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (17111, 17114), False, 'import pickle\n'), ((17659, 17691), 'imutils.resize', 'imutils.resize', (['frame'], {'width': '(800)'}), '(frame, width=800)\n', (17673, 17691), False, 'import imutils\n'), ((17712, 17751), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2GRAY'], {}), '(frame, cv2.COLOR_BGR2GRAY)\n', (17724, 17751), False, 'import cv2\n'), ((19073, 19132), 'cv2.imshow', 'cv2.imshow', (['"""Mark Attendance- Out - Press q to exit"""', 'frame'], {}), "('Mark Attendance- Out - Press q to exit', frame)\n", (19083, 19132), False, 'import cv2\n'), ((19607, 19633), 'django.shortcuts.redirect', 'redirect', (['"""not-authorised"""'], {}), "('not-authorised')\n", (19615, 19633), False, 'from django.shortcuts import render, redirect\n'), ((19768, 19807), 'os.path.join', 'os.path.join', (['training_dir', 'person_name'], {}), '(training_dir, person_name)\n', (19780, 19807), False, 'import os\n'), ((19878, 19915), 'face_recognition.face_recognition_cli.image_files_in_folder', 'image_files_in_folder', (['curr_directory'], {}), '(curr_directory)\n', (19899, 19915), False, 'from face_recognition.face_recognition_cli import image_files_in_folder\n'), ((20038, 20077), 'os.path.join', 'os.path.join', (['training_dir', 'person_name'], {}), '(training_dir, person_name)\n', (20050, 20077), False, 'import os\n'), ((20148, 20185), 'face_recognition.face_recognition_cli.image_files_in_folder', 'image_files_in_folder', (['curr_directory'], {}), '(curr_directory)\n', (20169, 20185), False, 'from face_recognition.face_recognition_cli import image_files_in_folder\n'), ((20775, 20794), 'pickle.dump', 'pickle.dump', (['svc', 'f'], {}), '(svc, f)\n', (20786, 20794), False, 'import pickle\n'), ((21479, 21505), 'django.shortcuts.redirect', 'redirect', (['"""not-authorised"""'], {}), "('not-authorised')\n", (21487, 21505), False, 'from django.shortcuts import render, redirect\n'), ((22158, 22244), 'django.shortcuts.render', 'render', (['request', '"""recognition/view_attendance_date.html"""', "{'form': form, 'qs': qs}"], {}), "(request, 'recognition/view_attendance_date.html', {'form': form,\n    'qs': qs})\n", (22164, 22244), False, 'from django.shortcuts import render, redirect\n'), ((22344, 22370), 'django.shortcuts.redirect', 'redirect', (['"""not-authorised"""'], {}), "('not-authorised')\n", (22352, 22370), False, 'from django.shortcuts import render, redirect\n'), ((23766, 23856), 'django.shortcuts.render', 'render', (['request', '"""recognition/view_attendance_employee.html"""', "{'form': form, 'qs': qs}"], {}), "(request, 'recognition/view_attendance_employee.html', {'form': form,\n    'qs': qs})\n", (23772, 23856), False, 'from django.shortcuts import render, redirect\n'), ((23966, 23992), 'django.shortcuts.redirect', 'redirect', (['"""not-authorised"""'], {}), "('not-authorised')\n", (23974, 23992), False, 'from django.shortcuts import render, redirect\n'), ((25081, 25181), 'django.shortcuts.render', 'render', (['request', '"""recognition/view_my_attendance_employee_login.html"""', "{'form': form, 'qs': qs}"], {}), "(request, 'recognition/view_my_attendance_employee_login.html', {\n    'form': form, 'qs': qs})\n", (25087, 25181), False, 'from django.shortcuts import render, redirect\n'), ((1278, 1316), 'django.contrib.auth.models.User.objects.filter', 'User.objects.filter', ([], {'username': 'username'}), '(username=username)\n', (1297, 1316), False, 'from django.contrib.auth.models import User\n'), ((2170, 2188), 'imutils.video.VideoStream', 'VideoStream', ([], {'src': '(0)'}), '(src=0)\n', (2181, 2188), False, 'from imutils.video import VideoStream\n'), ((3230, 3257), 'imutils.face_utils.rect_to_bb', 'face_utils.rect_to_bb', (['face'], {}), '(face)\n', (3251, 3257), False, 'from imutils import face_utils\n'), ((3839, 3878), 'imutils.resize', 'imutils.resize', (['face_aligned'], {'width': '(400)'}), '(face_aligned, width=400)\n', (3853, 3878), False, 'import imutils\n'), ((4133, 4193), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(x, y)', '(x + w, y + h)', '(0, 255, 0)', '(1)'], {}), '(frame, (x, y), (x + w, y + h), (0, 255, 0), 1)\n', (4146, 4193), False, 'import cv2\n'), ((4291, 4306), 'cv2.waitKey', 'cv2.waitKey', (['(50)'], {}), '(50)\n', (4302, 4306), False, 'import cv2\n'), ((5148, 5164), 'numpy.amax', 'np.amax', (['prob[0]'], {}), '(prob[0])\n', (5155, 5164), True, 'import numpy as np\n'), ((5335, 5355), 'sklearn.manifold.TSNE', 'TSNE', ([], {'n_components': '(2)'}), '(n_components=2)\n', (5339, 5355), False, 'from sklearn.manifold import TSNE\n'), ((5883, 5925), 'users.models.Present.objects.get', 'Present.objects.get', ([], {'user': 'user', 'date': 'today'}), '(user=user, date=today)\n', (5902, 5925), False, 'from users.models import Present, Time\n'), ((6264, 6313), 'users.models.Time', 'Time', ([], {'user': 'user', 'date': 'today', 'time': 'time', 'out': '(False)'}), '(user=user, date=today, time=time, out=False)\n', (6268, 6313), False, 'from users.models import Present, Time\n'), ((6536, 6584), 'users.models.Time', 'Time', ([], {'user': 'user', 'date': 'today', 'time': 'time', 'out': '(True)'}), '(user=user, date=today, time=time, out=True)\n', (6540, 6584), False, 'from users.models import Present, Time\n'), ((10667, 10701), 'users.models.Present.objects.filter', 'Present.objects.filter', ([], {'date': 'today'}), '(date=today)\n', (10689, 10701), False, 'from users.models import Present, Time\n'), ((11052, 11105), 'users.models.Present.objects.filter', 'Present.objects.filter', ([], {'date__gte': 'monday_of_this_week'}), '(date__gte=monday_of_this_week)\n', (11074, 11105), False, 'from users.models import Present, Time\n'), ((12173, 12226), 'users.models.Present.objects.filter', 'Present.objects.filter', ([], {'date__gte': 'monday_of_last_week'}), '(date__gte=monday_of_last_week)\n', (12195, 12226), False, 'from users.models import Present, Time\n'), ((13632, 13677), 'django.contrib.messages.success', 'messages.success', (['request', 'f"""Dataset Created"""'], {}), "(request, f'Dataset Created')\n", (13648, 13677), False, 'from django.contrib import messages\n'), ((13688, 13710), 'django.shortcuts.redirect', 'redirect', (['"""add-photos"""'], {}), "('add-photos')\n", (13696, 13710), False, 'from django.shortcuts import render, redirect\n'), ((13722, 13811), 'django.contrib.messages.warning', 'messages.warning', (['request', 'f"""No such username found. Please register employee first."""'], {}), "(request,\n    f'No such username found. Please register employee first.')\n", (13738, 13811), False, 'from django.contrib import messages\n'), ((13818, 13839), 'django.shortcuts.redirect', 'redirect', (['"""dashboard"""'], {}), "('dashboard')\n", (13826, 13839), False, 'from django.shortcuts import render, redirect\n'), ((14776, 14794), 'imutils.video.VideoStream', 'VideoStream', ([], {'src': '(0)'}), '(src=0)\n', (14787, 14794), False, 'from imutils.video import VideoStream\n'), ((15080, 15107), 'imutils.face_utils.rect_to_bb', 'face_utils.rect_to_bb', (['face'], {}), '(face)\n', (15101, 15107), False, 'from imutils import face_utils\n'), ((15162, 15222), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(x, y)', '(x + w, y + h)', '(0, 255, 0)', '(1)'], {}), '(frame, (x, y), (x + w, y + h), (0, 255, 0), 1)\n', (15175, 15222), False, 'import cv2\n'), ((16524, 16539), 'cv2.waitKey', 'cv2.waitKey', (['(50)'], {}), '(50)\n', (16535, 16539), False, 'import cv2\n'), ((17563, 17581), 'imutils.video.VideoStream', 'VideoStream', ([], {'src': '(0)'}), '(src=0)\n', (17574, 17581), False, 'from imutils.video import VideoStream\n'), ((17867, 17894), 'imutils.face_utils.rect_to_bb', 'face_utils.rect_to_bb', (['face'], {}), '(face)\n', (17888, 17894), False, 'from imutils import face_utils\n'), ((17949, 18009), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(x, y)', '(x + w, y + h)', '(0, 255, 0)', '(1)'], {}), '(frame, (x, y), (x + w, y + h), (0, 255, 0), 1)\n', (17962, 18009), False, 'import cv2\n'), ((19311, 19326), 'cv2.waitKey', 'cv2.waitKey', (['(50)'], {}), '(50)\n', (19322, 19326), False, 'import cv2\n'), ((19816, 19845), 'os.path.isdir', 'os.path.isdir', (['curr_directory'], {}), '(curr_directory)\n', (19829, 19845), False, 'import os\n'), ((20086, 20115), 'os.path.isdir', 'os.path.isdir', (['curr_directory'], {}), '(curr_directory)\n', (20099, 20115), False, 'import os\n'), ((20221, 20242), 'cv2.imread', 'cv2.imread', (['imagefile'], {}), '(imagefile)\n', (20231, 20242), False, 'import cv2\n'), ((21706, 21736), 'users.models.Time.objects.filter', 'Time.objects.filter', ([], {'date': 'date'}), '(date=date)\n', (21725, 21736), False, 'from users.models import Present, Time\n'), ((21751, 21784), 'users.models.Present.objects.filter', 'Present.objects.filter', ([], {'date': 'date'}), '(date=date)\n', (21773, 21784), False, 'from users.models import Present, Time\n'), ((24144, 24171), 'users.models.Time.objects.filter', 'Time.objects.filter', ([], {'user': 'u'}), '(user=u)\n', (24163, 24171), False, 'from users.models import Present, Time\n'), ((24186, 24216), 'users.models.Present.objects.filter', 'Present.objects.filter', ([], {'user': 'u'}), '(user=u)\n', (24208, 24216), False, 'from users.models import Present, Time\n'), ((6005, 6049), 'users.models.Present', 'Present', ([], {'user': 'user', 'date': 'today', 'present': '(True)'}), '(user=user, date=today, present=True)\n', (6012, 6049), False, 'from users.models import Present, Time\n'), ((6078, 6123), 'users.models.Present', 'Present', ([], {'user': 'user', 'date': 'today', 'present': '(False)'}), '(user=user, date=today, present=False)\n', (6085, 6123), False, 'from users.models import Present, Time\n'), ((11273, 11306), 'users.models.Present.objects.filter', 'Present.objects.filter', ([], {'date': 'date'}), '(date=date)\n', (11295, 11306), False, 'from users.models import Present, Time\n'), ((11405, 11433), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': 'cnt'}), '(days=cnt)\n', (11423, 11433), False, 'import datetime\n'), ((12405, 12438), 'users.models.Present.objects.filter', 'Present.objects.filter', ([], {'date': 'date'}), '(date=date)\n', (12427, 12438), False, 'from users.models import Present, Time\n'), ((12537, 12565), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': 'cnt'}), '(days=cnt)\n', (12555, 12565), False, 'import datetime\n'), ((21898, 21984), 'django.shortcuts.render', 'render', (['request', '"""recognition/view_attendance_date.html"""', "{'form': form, 'qs': qs}"], {}), "(request, 'recognition/view_attendance_date.html', {'form': form,\n    'qs': qs})\n", (21904, 21984), False, 'from django.shortcuts import render, redirect\n'), ((21995, 22054), 'django.contrib.messages.warning', 'messages.warning', (['request', 'f"""No records for selected date."""'], {}), "(request, f'No records for selected date.')\n", (22011, 22054), False, 'from django.contrib import messages\n'), ((22066, 22098), 'django.shortcuts.redirect', 'redirect', (['"""view-attendance-date"""'], {}), "('view-attendance-date')\n", (22074, 22098), False, 'from django.shortcuts import render, redirect\n'), ((22594, 22629), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', ([], {'username': 'username'}), '(username=username)\n', (22610, 22629), False, 'from django.contrib.auth.models import User\n'), ((22647, 22674), 'users.models.Time.objects.filter', 'Time.objects.filter', ([], {'user': 'u'}), '(user=u)\n', (22666, 22674), False, 'from users.models import Present, Time\n'), ((22690, 22720), 'users.models.Present.objects.filter', 'Present.objects.filter', ([], {'user': 'u'}), '(user=u)\n', (22712, 22720), False, 'from users.models import Present, Time\n'), ((23611, 23664), 'django.contrib.messages.warning', 'messages.warning', (['request', 'f"""No such username found."""'], {}), "(request, f'No such username found.')\n", (23627, 23664), False, 'from django.contrib import messages\n'), ((23676, 23712), 'django.shortcuts.redirect', 'redirect', (['"""view-attendance-employee"""'], {}), "('view-attendance-employee')\n", (23684, 23712), False, 'from django.shortcuts import render, redirect\n'), ((24341, 24394), 'django.contrib.messages.warning', 'messages.warning', (['request', 'f"""Invalid date selection."""'], {}), "(request, f'Invalid date selection.')\n", (24357, 24394), False, 'from django.contrib import messages\n'), ((24407, 24452), 'django.shortcuts.redirect', 'redirect', (['"""view-my-attendance-employee-login"""'], {}), "('view-my-attendance-employee-login')\n", (24415, 24452), False, 'from django.shortcuts import render, redirect\n'), ((15423, 15434), 'time.time', 'time.time', ([], {}), '()\n', (15432, 15434), False, 'import time\n'), ((15675, 15698), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (15696, 15698), False, 'import datetime\n'), ((18210, 18221), 'time.time', 'time.time', ([], {}), '()\n', (18219, 18221), False, 'import time\n'), ((18462, 18485), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (18483, 18485), False, 'import datetime\n'), ((20400, 20420), 'os.remove', 'os.remove', (['imagefile'], {}), '(imagefile)\n', (20409, 20420), False, 'import os\n'), ((22853, 22906), 'django.contrib.messages.warning', 'messages.warning', (['request', 'f"""Invalid date selection."""'], {}), "(request, f'Invalid date selection.')\n", (22869, 22906), False, 'from django.contrib import messages\n'), ((22919, 22955), 'django.shortcuts.redirect', 'redirect', (['"""view-attendance-employee"""'], {}), "('view-attendance-employee')\n", (22927, 22955), False, 'from django.shortcuts import render, redirect\n'), ((24796, 24896), 'django.shortcuts.render', 'render', (['request', '"""recognition/view_my_attendance_employee_login.html"""', "{'form': form, 'qs': qs}"], {}), "(request, 'recognition/view_my_attendance_employee_login.html', {\n    'form': form, 'qs': qs})\n", (24802, 24896), False, 'from django.shortcuts import render, redirect\n'), ((24916, 24979), 'django.contrib.messages.warning', 'messages.warning', (['request', 'f"""No records for selected duration."""'], {}), "(request, f'No records for selected duration.')\n", (24932, 24979), False, 'from django.contrib import messages\n'), ((24993, 25038), 'django.shortcuts.redirect', 'redirect', (['"""view-my-attendance-employee-login"""'], {}), "('view-my-attendance-employee-login')\n", (25001, 25038), False, 'from django.shortcuts import render, redirect\n'), ((15337, 15353), 'numpy.ravel', 'np.ravel', (['[pred]'], {}), '([pred])\n', (15345, 15353), True, 'import numpy as np\n'), ((18124, 18140), 'numpy.ravel', 'np.ravel', (['[pred]'], {}), '([pred])\n', (18132, 18140), True, 'import numpy as np\n'), ((23300, 23390), 'django.shortcuts.render', 'render', (['request', '"""recognition/view_attendance_employee.html"""', "{'form': form, 'qs': qs}"], {}), "(request, 'recognition/view_attendance_employee.html', {'form': form,\n    'qs': qs})\n", (23306, 23390), False, 'from django.shortcuts import render, redirect\n'), ((23438, 23501), 'django.contrib.messages.warning', 'messages.warning', (['request', 'f"""No records for selected duration."""'], {}), "(request, f'No records for selected duration.')\n", (23454, 23501), False, 'from django.contrib import messages\n'), ((23515, 23551), 'django.shortcuts.redirect', 'redirect', (['"""view-attendance-employee"""'], {}), "('view-attendance-employee')\n", (23523, 23551), False, 'from django.shortcuts import render, redirect\n'), ((15506, 15517), 'time.time', 'time.time', ([], {}), '()\n', (15515, 15517), False, 'import time\n'), ((18293, 18304), 'time.time', 'time.time', ([], {}), '()\n', (18302, 18304), False, 'import time\n'), ((20265, 20303), 'face_recognition.face_encodings', 'face_recognition.face_encodings', (['image'], {}), '(image)\n', (20296, 20303), False, 'import face_recognition\n')]