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})
[((38, 0, 38, 14), 'matplotlib.use', 'mpl.use', ({(38, 8, 38, 13): '"""Agg"""'}, {}), "('Agg')", True, 'import matplotlib as mpl\n'), ((58, 12, 58, 44), 'dlib.get_frontal_face_detector', 'dlib.get_frontal_face_detector', ({}, {}), '()', False, 'import dlib\n'), ((59, 13, 59, 96), 'dlib.shape_predictor', 'dlib.shape_predictor', ({(59, 34, 59, 95): '"""face_recognition_data/shape_predictor_68_face_landmarks.dat"""'}, {}), "(\n    'face_recognition_data/shape_predictor_68_face_landmarks.dat')", False, 'import dlib\n'), ((60, 6, 60, 52), 'imutils.face_utils.FaceAligner', 'FaceAligner', (), '', False, 'from imutils.face_utils import FaceAligner\n'), ((136, 1, 136, 24), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ({}, {}), '()', False, 'import cv2\n'), ((140, 16, 140, 33), 'numpy.zeros', 'np.zeros', ({(140, 25, 140, 32): '(1, 128)'}, {}), '((1, 128))', True, 'import numpy as np\n'), ((167, 1, 167, 34), 'matplotlib.pyplot.legend', 'plt.legend', (), '', True, 'import matplotlib.pyplot as plt\n'), ((168, 1, 168, 45), 'matplotlib.rcParams.update', 'rcParams.update', ({(168, 17, 168, 44): "{'figure.autolayout': True}"}, {}), "({'figure.autolayout': True})", False, 'from matplotlib import rcParams\n'), ((169, 1, 169, 19), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ({}, {}), '()', True, 'import matplotlib.pyplot as plt\n'), ((170, 1, 170, 79), 'matplotlib.pyplot.savefig', 'plt.savefig', ({(170, 13, 170, 78): '"""./recognition/static/recognition/img/training_visualisation.png"""'}, {}), "('./recognition/static/recognition/img/training_visualisation.png')", True, 'import matplotlib.pyplot as plt\n'), ((171, 1, 171, 12), 'matplotlib.pyplot.close', 'plt.close', ({}, {}), '()', True, 'import matplotlib.pyplot as plt\n'), ((176, 7, 176, 28), 'datetime.date.today', 'datetime.date.today', ({}, {}), '()', False, 'import datetime\n'), ((177, 6, 177, 29), 'datetime.datetime.now', 'datetime.datetime.now', ({}, {}), '()', False, 'import datetime\n'), ((208, 7, 208, 28), 'datetime.date.today', 'datetime.date.today', ({}, {}), '()', False, 'import datetime\n'), ((209, 6, 209, 29), 'datetime.datetime.now', 'datetime.datetime.now', ({}, {}), '()', False, 'import datetime\n'), ((265, 3, 265, 15), 'math.ceil', 'math.ceil', ({(265, 13, 265, 14): 'm'}, {}), '(m)', False, 'import math\n'), ((272, 1, 272, 33), 'pandas.plotting.register_matplotlib_converters', 'register_matplotlib_converters', ({}, {}), '()', False, 'from pandas.plotting import register_matplotlib_converters\n'), ((320, 6, 320, 20), 'django_pandas.io.read_frame', 'read_frame', ({(320, 17, 320, 19): 'qs'}, {}), '(qs)', False, 'from django_pandas.io import read_frame\n'), ((328, 1, 328, 40), 'seaborn.barplot', 'sns.barplot', (), '', True, 'import seaborn as sns\n'), ((329, 1, 329, 32), 'matplotlib.pyplot.xticks', 'plt.xticks', (), '', True, 'import matplotlib.pyplot as plt\n'), ((330, 1, 330, 45), 'matplotlib.rcParams.update', 'rcParams.update', ({(330, 17, 330, 44): "{'figure.autolayout': True}"}, {}), "({'figure.autolayout': True})", False, 'from matplotlib import rcParams\n'), ((331, 1, 331, 19), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ({}, {}), '()', True, 'import matplotlib.pyplot as plt\n'), ((343, 1, 343, 33), 'pandas.plotting.register_matplotlib_converters', 'register_matplotlib_converters', ({}, {}), '()', False, 'from pandas.plotting import register_matplotlib_converters\n'), ((388, 6, 388, 20), 'django_pandas.io.read_frame', 'read_frame', ({(388, 17, 388, 19): 'qs'}, {}), '(qs)', False, 'from django_pandas.io import read_frame\n'), ((394, 1, 394, 44), 'seaborn.barplot', 'sns.barplot', (), '', True, 'import seaborn as sns\n'), ((395, 1, 395, 32), 'matplotlib.pyplot.xticks', 'plt.xticks', (), '', True, 'import matplotlib.pyplot as plt\n'), ((396, 1, 396, 45), 'matplotlib.rcParams.update', 'rcParams.update', ({(396, 17, 396, 44): "{'figure.autolayout': True}"}, {}), "({'figure.autolayout': True})", False, 'from matplotlib import rcParams\n'), ((397, 1, 397, 19), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ({}, {}), '()', True, 'import matplotlib.pyplot as plt\n'), ((398, 1, 398, 94), 'matplotlib.pyplot.savefig', 'plt.savefig', ({(398, 13, 398, 93): '"""./recognition/static/recognition/img/attendance_graphs/hours_vs_employee/1.png"""'}, {}), "(\n    './recognition/static/recognition/img/attendance_graphs/hours_vs_employee/1.png'\n    )", True, 'import matplotlib.pyplot as plt\n'), ((399, 1, 399, 12), 'matplotlib.pyplot.close', 'plt.close', ({}, {}), '()', True, 'import matplotlib.pyplot as plt\n'), ((404, 4, 404, 22), 'django.contrib.auth.models.User.objects.all', 'User.objects.all', ({}, {}), '()', False, 'from django.contrib.auth.models import User\n'), ((411, 7, 411, 28), 'datetime.date.today', 'datetime.date.today', ({}, {}), '()', False, 'import datetime\n'), ((420, 7, 420, 28), 'datetime.date.today', 'datetime.date.today', ({}, {}), '()', False, 'import datetime\n'), ((460, 4, 460, 18), 'pandas.DataFrame', 'pd.DataFrame', ({}, {}), '()', True, 'import pandas as pd\n'), ((465, 1, 465, 55), 'seaborn.lineplot', 'sns.lineplot', (), '', True, 'import seaborn as sns\n'), ((466, 1, 466, 86), 'matplotlib.pyplot.savefig', 'plt.savefig', ({(466, 13, 466, 85): '"""./recognition/static/recognition/img/attendance_graphs/this_week/1.png"""'}, {}), "(\n    './recognition/static/recognition/img/attendance_graphs/this_week/1.png')", True, 'import matplotlib.pyplot as plt\n'), ((467, 1, 467, 12), 'matplotlib.pyplot.close', 'plt.close', ({}, {}), '()', True, 'import matplotlib.pyplot as plt\n'), ((476, 7, 476, 28), 'datetime.date.today', 'datetime.date.today', ({}, {}), '()', False, 'import datetime\n'), ((516, 4, 516, 18), 'pandas.DataFrame', 'pd.DataFrame', ({}, {}), '()', True, 'import pandas as pd\n'), ((523, 1, 523, 45), 'seaborn.lineplot', 'sns.lineplot', (), '', True, 'import seaborn as sns\n'), ((524, 1, 524, 86), 'matplotlib.pyplot.savefig', 'plt.savefig', ({(524, 13, 524, 85): '"""./recognition/static/recognition/img/attendance_graphs/last_week/1.png"""'}, {}), "(\n    './recognition/static/recognition/img/attendance_graphs/last_week/1.png')", True, 'import matplotlib.pyplot as plt\n'), ((525, 1, 525, 12), 'matplotlib.pyplot.close', 'plt.close', ({}, {}), '()', True, 'import matplotlib.pyplot as plt\n'), ((537, 8, 537, 48), 'django.shortcuts.render', 'render', ({(537, 15, 537, 22): 'request', (537, 24, 537, 47): '"""recognition/home.html"""'}, {}), "(request, 'recognition/home.html')", False, 'from django.shortcuts import render, redirect\n'), ((579, 12, 579, 44), 'dlib.get_frontal_face_detector', 'dlib.get_frontal_face_detector', ({}, {}), '()', False, 'import dlib\n'), ((581, 13, 581, 96), 'dlib.shape_predictor', 'dlib.shape_predictor', ({(581, 34, 581, 95): '"""face_recognition_data/shape_predictor_68_face_landmarks.dat"""'}, {}), "(\n    'face_recognition_data/shape_predictor_68_face_landmarks.dat')", False, 'import dlib\n'), ((589, 6, 589, 52), 'imutils.face_utils.FaceAligner', 'FaceAligner', (), '', False, 'from imutils.face_utils import FaceAligner\n'), ((590, 9, 590, 23), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ({}, {}), '()', False, 'from sklearn.preprocessing import LabelEncoder\n'), ((591, 20, 591, 64), 'numpy.load', 'np.load', ({(591, 28, 591, 63): '"""face_recognition_data/classes.npy"""'}, {}), "('face_recognition_data/classes.npy')", True, 'import numpy as np\n'), ((594, 19, 594, 36), 'numpy.zeros', 'np.zeros', ({(594, 28, 594, 35): '(1, 128)'}, {}), '((1, 128))', True, 'import numpy as np\n'), ((679, 1, 679, 24), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ({}, {}), '()', False, 'import cv2\n'), ((681, 8, 681, 24), 'django.shortcuts.redirect', 'redirect', ({(681, 17, 681, 23): '"""home"""'}, {}), "('home')", False, 'from django.shortcuts import render, redirect\n'), ((689, 12, 689, 44), 'dlib.get_frontal_face_detector', 'dlib.get_frontal_face_detector', ({}, {}), '()', False, 'import dlib\n'), ((691, 13, 691, 96), 'dlib.shape_predictor', 'dlib.shape_predictor', ({(691, 34, 691, 95): '"""face_recognition_data/shape_predictor_68_face_landmarks.dat"""'}, {}), "(\n    'face_recognition_data/shape_predictor_68_face_landmarks.dat')", False, 'import dlib\n'), ((699, 6, 699, 52), 'imutils.face_utils.FaceAligner', 'FaceAligner', (), '', False, 'from imutils.face_utils import FaceAligner\n'), ((700, 9, 700, 23), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ({}, {}), '()', False, 'from sklearn.preprocessing import LabelEncoder\n'), ((701, 20, 701, 64), 'numpy.load', 'np.load', ({(701, 28, 701, 63): '"""face_recognition_data/classes.npy"""'}, {}), "('face_recognition_data/classes.npy')", True, 'import numpy as np\n'), ((704, 19, 704, 36), 'numpy.zeros', 'np.zeros', ({(704, 28, 704, 35): '(1, 128)'}, {}), '((1, 128))', True, 'import numpy as np\n'), ((789, 1, 789, 24), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ({}, {}), '()', False, 'import cv2\n'), ((791, 8, 791, 24), 'django.shortcuts.redirect', 'redirect', ({(791, 17, 791, 23): '"""home"""'}, {}), "('home')", False, 'from django.shortcuts import render, redirect\n'), ((806, 20, 806, 44), 'os.listdir', 'os.listdir', ({(806, 31, 806, 43): 'training_dir'}, {}), '(training_dir)', False, 'import os\n'), ((818, 20, 818, 44), 'os.listdir', 'os.listdir', ({(818, 31, 818, 43): 'training_dir'}, {}), '(training_dir)', False, 'import os\n'), ((840, 9, 840, 20), 'numpy.array', 'np.array', ({(840, 18, 840, 19): 'y'}, {}), '(y)', True, 'import numpy as np\n'), ((841, 11, 841, 25), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ({}, {}), '()', False, 'from sklearn.preprocessing import LabelEncoder\n'), ((844, 4, 844, 15), 'numpy.array', 'np.array', ({(844, 13, 844, 14): 'X'}, {}), '(X)', True, 'import numpy as np\n'), ((846, 1, 846, 63), 'numpy.save', 'np.save', ({(846, 9, 846, 44): '"""face_recognition_data/classes.npy"""', (846, 46, 846, 62): 'encoder.classes_'}, {}), "('face_recognition_data/classes.npy', encoder.classes_)", True, 'import numpy as np\n'), ((847, 7, 847, 44), 'sklearn.svm.SVC', 'SVC', (), '', False, 'from sklearn.svm import SVC\n'), ((856, 1, 856, 49), 'django.contrib.messages.success', 'messages.success', ({(856, 18, 856, 25): 'request', (856, 27, 856, 48): 'f"""Training Complete."""'}, {}), "(request, f'Training Complete.')", False, 'from django.contrib import messages\n'), ((858, 8, 858, 48), 'django.shortcuts.render', 'render', ({(858, 15, 858, 22): 'request', (858, 23, 858, 47): '"""recognition/train.html"""'}, {}), "(request, 'recognition/train.html')", False, 'from django.shortcuts import render, redirect\n'), ((863, 8, 863, 57), 'django.shortcuts.render', 'render', ({(863, 15, 863, 22): 'request', (863, 23, 863, 56): '"""recognition/not_authorised.html"""'}, {}), "(request, 'recognition/not_authorised.html')", False, 'from django.shortcuts import render, redirect\n'), ((873, 8, 873, 144), 'django.shortcuts.render', 'render', ({(873, 15, 873, 22): 'request', (873, 23, 873, 62): '"""recognition/view_attendance_home.html"""', (873, 64, 873, 143): "{'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})", False, 'from django.shortcuts import render, redirect\n'), ((78, 10, 78, 44), 'imutils.resize', 'imutils.resize', (), '', False, 'import imutils\n'), ((81, 15, 81, 54), 'cv2.cvtColor', 'cv2.cvtColor', ({(81, 28, 81, 33): 'frame', (81, 35, 81, 53): 'cv2.COLOR_BGR2GRAY'}, {}), '(frame, cv2.COLOR_BGR2GRAY)', False, 'import cv2\n'), ((125, 2, 125, 32), 'cv2.imshow', 'cv2.imshow', ({(125, 13, 125, 25): '"""Add Images"""', (125, 26, 125, 31): 'frame'}, {}), "('Add Images', frame)", False, 'import cv2\n'), ((128, 2, 128, 16), 'cv2.waitKey', 'cv2.waitKey', ({(128, 14, 128, 15): '(1)'}, {}), '(1)', False, 'import cv2\n'), ((142, 19, 142, 64), 'face_recognition.face_locations', 'face_recognition.face_locations', ({(142, 51, 142, 63): 'face_aligned'}, {}), '(face_aligned)', False, 'import face_recognition\n'), ((143, 18, 143, 101), 'face_recognition.face_encodings', 'face_recognition.face_encodings', (), '', False, 'import face_recognition\n'), ((165, 2, 165, 62), 'matplotlib.pyplot.scatter', 'plt.scatter', (), '', True, 'import matplotlib.pyplot as plt\n'), ((179, 7, 179, 40), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', (), '', False, 'from django.contrib.auth.models import User\n'), ((211, 7, 211, 40), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', (), '', False, 'from django.contrib.auth.models import User\n'), ((333, 2, 333, 91), 'matplotlib.pyplot.savefig', 'plt.savefig', ({(333, 14, 333, 90): '"""./recognition/static/recognition/img/attendance_graphs/hours_vs_date/1.png"""'}, {}), "(\n    './recognition/static/recognition/img/attendance_graphs/hours_vs_date/1.png'\n    )", True, 'import matplotlib.pyplot as plt\n'), ((334, 2, 334, 13), 'matplotlib.pyplot.close', 'plt.close', ({}, {}), '()', True, 'import matplotlib.pyplot as plt\n'), ((336, 2, 336, 92), 'matplotlib.pyplot.savefig', 'plt.savefig', ({(336, 14, 336, 91): '"""./recognition/static/recognition/img/attendance_graphs/employee_login/1.png"""'}, {}), "(\n    './recognition/static/recognition/img/attendance_graphs/employee_login/1.png'\n    )", True, 'import matplotlib.pyplot as plt\n'), ((337, 2, 337, 13), 'matplotlib.pyplot.close', 'plt.close', ({}, {}), '()', True, 'import matplotlib.pyplot as plt\n'), ((421, 26, 421, 52), 'datetime.timedelta', 'datetime.timedelta', (), '', False, 'import datetime\n'), ((423, 45, 423, 71), 'datetime.timedelta', 'datetime.timedelta', (), '', False, 'import datetime\n'), ((477, 26, 477, 52), 'datetime.timedelta', 'datetime.timedelta', (), '', False, 'import datetime\n'), ((479, 45, 479, 71), 'datetime.timedelta', 'datetime.timedelta', (), '', False, 'import datetime\n'), ((543, 9, 543, 60), 'django.shortcuts.render', 'render', ({(543, 16, 543, 23): 'request', (543, 25, 543, 59): '"""recognition/admin_dashboard.html"""'}, {}), "(request, 'recognition/admin_dashboard.html')", False, 'from django.shortcuts import render, redirect\n'), ((547, 9, 547, 62), 'django.shortcuts.render', 'render', ({(547, 16, 547, 23): 'request', (547, 24, 547, 61): '"""recognition/employee_dashboard.html"""'}, {}), "(request, 'recognition/employee_dashboard.html')", False, 'from django.shortcuts import render, redirect\n'), ((552, 9, 552, 35), 'django.shortcuts.redirect', 'redirect', ({(552, 18, 552, 34): '"""not-authorised"""'}, {}), "('not-authorised')", False, 'from django.shortcuts import render, redirect\n'), ((570, 10, 570, 72), 'django.shortcuts.render', 'render', ({(570, 17, 570, 24): 'request', (570, 25, 570, 54): '"""recognition/add_photos.html"""', (570, 56, 570, 71): "{'form': form}"}, {}), "(request, 'recognition/add_photos.html', {'form': form})", False, 'from django.shortcuts import render, redirect\n'), ((588, 9, 588, 23), 'pickle.load', 'pickle.load', ({(588, 21, 588, 22): 'f'}, {}), '(f)', False, 'import pickle\n'), ((614, 10, 614, 44), 'imutils.resize', 'imutils.resize', (), '', False, 'import imutils\n'), ((616, 15, 616, 54), 'cv2.cvtColor', 'cv2.cvtColor', ({(616, 28, 616, 33): 'frame', (616, 35, 616, 53): 'cv2.COLOR_BGR2GRAY'}, {}), '(frame, cv2.COLOR_BGR2GRAY)', False, 'import cv2\n'), ((666, 2, 666, 60), 'cv2.imshow', 'cv2.imshow', ({(666, 13, 666, 53): '"""Mark Attendance - In - Press q to exit"""', (666, 54, 666, 59): 'frame'}, {}), "('Mark Attendance - In - Press q to exit', frame)", False, 'import cv2\n'), ((698, 9, 698, 23), 'pickle.load', 'pickle.load', ({(698, 21, 698, 22): 'f'}, {}), '(f)', False, 'import pickle\n'), ((724, 10, 724, 44), 'imutils.resize', 'imutils.resize', (), '', False, 'import imutils\n'), ((726, 15, 726, 54), 'cv2.cvtColor', 'cv2.cvtColor', ({(726, 28, 726, 33): 'frame', (726, 35, 726, 53): 'cv2.COLOR_BGR2GRAY'}, {}), '(frame, cv2.COLOR_BGR2GRAY)', False, 'import cv2\n'), ((776, 2, 776, 60), 'cv2.imshow', 'cv2.imshow', ({(776, 13, 776, 53): '"""Mark Attendance- Out - Press q to exit"""', (776, 54, 776, 59): 'frame'}, {}), "('Mark Attendance- Out - Press q to exit', frame)", False, 'import cv2\n'), ((799, 9, 799, 35), 'django.shortcuts.redirect', 'redirect', ({(799, 18, 799, 34): '"""not-authorised"""'}, {}), "('not-authorised')", False, 'from django.shortcuts import render, redirect\n'), ((807, 17, 807, 55), 'os.path.join', 'os.path.join', ({(807, 30, 807, 42): 'training_dir', (807, 43, 807, 54): 'person_name'}, {}), '(training_dir, person_name)', False, 'import os\n'), ((810, 19, 810, 56), 'face_recognition.face_recognition_cli.image_files_in_folder', 'image_files_in_folder', ({(810, 41, 810, 55): 'curr_directory'}, {}), '(curr_directory)', False, 'from face_recognition.face_recognition_cli import image_files_in_folder\n'), ((820, 17, 820, 55), 'os.path.join', 'os.path.join', ({(820, 30, 820, 42): 'training_dir', (820, 43, 820, 54): 'person_name'}, {}), '(training_dir, person_name)', False, 'import os\n'), ((823, 19, 823, 56), 'face_recognition.face_recognition_cli.image_files_in_folder', 'image_files_in_folder', ({(823, 41, 823, 55): 'curr_directory'}, {}), '(curr_directory)', False, 'from face_recognition.face_recognition_cli import image_files_in_folder\n'), ((851, 2, 851, 20), 'pickle.dump', 'pickle.dump', ({(851, 14, 851, 17): 'svc', (851, 18, 851, 19): 'f'}, {}), '(svc, f)', False, 'import pickle\n'), ((879, 9, 879, 35), 'django.shortcuts.redirect', 'redirect', ({(879, 18, 879, 34): '"""not-authorised"""'}, {}), "('not-authorised')", False, 'from django.shortcuts import render, redirect\n'), ((912, 10, 912, 93), 'django.shortcuts.render', 'render', ({(912, 17, 912, 24): 'request', (912, 25, 912, 64): '"""recognition/view_attendance_date.html"""', (912, 66, 912, 92): "{'form': form, 'qs': qs}"}, {}), "(request, 'recognition/view_attendance_date.html', {'form': form,\n    'qs': qs})", False, 'from django.shortcuts import render, redirect\n'), ((918, 9, 918, 35), 'django.shortcuts.redirect', 'redirect', ({(918, 18, 918, 34): '"""not-authorised"""'}, {}), "('not-authorised')", False, 'from django.shortcuts import render, redirect\n'), ((968, 10, 968, 96), 'django.shortcuts.render', 'render', ({(968, 17, 968, 24): 'request', (968, 25, 968, 68): '"""recognition/view_attendance_employee.html"""', (968, 70, 968, 95): "{'form': form, 'qs': qs}"}, {}), "(request, 'recognition/view_attendance_employee.html', {'form': form,\n    'qs': qs})", False, 'from django.shortcuts import render, redirect\n'), ((976, 9, 976, 35), 'django.shortcuts.redirect', 'redirect', ({(976, 18, 976, 34): '"""not-authorised"""'}, {}), "('not-authorised')", False, 'from django.shortcuts import render, redirect\n'), ((1008, 10, 1008, 105), 'django.shortcuts.render', 'render', ({(1008, 17, 1008, 24): 'request', (1008, 25, 1008, 77): '"""recognition/view_my_attendance_employee_login.html"""', (1008, 79, 1008, 104): "{'form': form, 'qs': qs}"}, {}), "(request, 'recognition/view_my_attendance_employee_login.html', {\n    'form': form, 'qs': qs})", False, 'from django.shortcuts import render, redirect\n'), ((43, 4, 43, 42), 'django.contrib.auth.models.User.objects.filter', 'User.objects.filter', (), '', False, 'from django.contrib.auth.models import User\n'), ((64, 6, 64, 24), 'imutils.video.VideoStream', 'VideoStream', (), '', False, 'from imutils.video import VideoStream\n'), ((94, 15, 94, 42), 'imutils.face_utils.rect_to_bb', 'face_utils.rect_to_bb', ({(94, 37, 94, 41): 'face'}, {}), '(face)', False, 'from imutils import face_utils\n'), ((112, 18, 112, 59), 'imutils.resize', 'imutils.resize', (), '', False, 'import imutils\n'), ((118, 3, 118, 51), 'cv2.rectangle', 'cv2.rectangle', ({(118, 17, 118, 22): 'frame', (118, 23, 118, 28): '(x, y)', (118, 29, 118, 38): '(x + w, y + h)', (118, 39, 118, 48): '(0, 255, 0)', (118, 49, 118, 50): '(1)'}, {}), '(frame, (x, y), (x + w, y + h), (0, 255, 0), 1)', False, 'import cv2\n'), ((121, 3, 121, 18), 'cv2.waitKey', 'cv2.waitKey', ({(121, 15, 121, 17): '(50)'}, {}), '(50)', False, 'import cv2\n'), ((152, 26, 152, 42), 'numpy.amax', 'np.amax', ({(152, 34, 152, 41): 'prob[0]'}, {}), '(prob[0])', True, 'import numpy as np\n'), ((161, 14, 161, 34), 'sklearn.manifold.TSNE', 'TSNE', (), '', False, 'from sklearn.manifold import TSNE\n'), ((181, 8, 181, 49), 'users.models.Present.objects.get', 'Present.objects.get', (), '', False, 'from users.models import Present, Time\n'), ((197, 5, 197, 52), 'users.models.Time', 'Time', (), '', False, 'from users.models import Present, Time\n'), ((213, 5, 213, 51), 'users.models.Time', 'Time', (), '', False, 'from users.models import Present, Time\n'), ((412, 4, 412, 38), 'users.models.Present.objects.filter', 'Present.objects.filter', (), '', False, 'from users.models import Present, Time\n'), ((424, 4, 424, 57), 'users.models.Present.objects.filter', 'Present.objects.filter', (), '', False, 'from users.models import Present, Time\n'), ((480, 4, 480, 57), 'users.models.Present.objects.filter', 'Present.objects.filter', (), '', False, 'from users.models import Present, Time\n'), ((559, 3, 559, 48), 'django.contrib.messages.success', 'messages.success', ({(559, 20, 559, 27): 'request', (559, 29, 559, 47): 'f"""Dataset Created"""'}, {}), "(request, f'Dataset Created')", False, 'from django.contrib import messages\n'), ((560, 10, 560, 32), 'django.shortcuts.redirect', 'redirect', ({(560, 19, 560, 31): '"""add-photos"""'}, {}), "('add-photos')", False, 'from django.shortcuts import render, redirect\n'), ((562, 3, 562, 88), 'django.contrib.messages.warning', 'messages.warning', ({(562, 20, 562, 27): 'request', (562, 29, 562, 87): 'f"""No such username found. Please register employee first."""'}, {}), "(request,\n    f'No such username found. Please register employee first.')", False, 'from django.contrib import messages\n'), ((563, 10, 563, 31), 'django.shortcuts.redirect', 'redirect', ({(563, 19, 563, 30): '"""dashboard"""'}, {}), "('dashboard')", False, 'from django.shortcuts import render, redirect\n'), ((606, 6, 606, 24), 'imutils.video.VideoStream', 'VideoStream', (), '', False, 'from imutils.video import VideoStream\n'), ((625, 15, 625, 42), 'imutils.face_utils.rect_to_bb', 'face_utils.rect_to_bb', ({(625, 37, 625, 41): 'face'}, {}), '(face)', False, 'from imutils import face_utils\n'), ((628, 3, 628, 51), 'cv2.rectangle', 'cv2.rectangle', ({(628, 17, 628, 22): 'frame', (628, 23, 628, 28): '(x, y)', (628, 29, 628, 38): '(x + w, y + h)', (628, 39, 628, 48): '(0, 255, 0)', (628, 49, 628, 50): '(1)'}, {}), '(frame, (x, y), (x + w, y + h), (0, 255, 0), 1)', False, 'import cv2\n'), ((671, 6, 671, 21), 'cv2.waitKey', 'cv2.waitKey', ({(671, 18, 671, 20): '(50)'}, {}), '(50)', False, 'import cv2\n'), ((716, 6, 716, 24), 'imutils.video.VideoStream', 'VideoStream', (), '', False, 'from imutils.video import VideoStream\n'), ((735, 15, 735, 42), 'imutils.face_utils.rect_to_bb', 'face_utils.rect_to_bb', ({(735, 37, 735, 41): 'face'}, {}), '(face)', False, 'from imutils import face_utils\n'), ((738, 3, 738, 51), 'cv2.rectangle', 'cv2.rectangle', ({(738, 17, 738, 22): 'frame', (738, 23, 738, 28): '(x, y)', (738, 29, 738, 38): '(x + w, y + h)', (738, 39, 738, 48): '(0, 255, 0)', (738, 49, 738, 50): '(1)'}, {}), '(frame, (x, y), (x + w, y + h), (0, 255, 0), 1)', False, 'import cv2\n'), ((781, 6, 781, 21), 'cv2.waitKey', 'cv2.waitKey', ({(781, 18, 781, 20): '(50)'}, {}), '(50)', False, 'import cv2\n'), ((808, 9, 808, 38), 'os.path.isdir', 'os.path.isdir', ({(808, 23, 808, 37): 'curr_directory'}, {}), '(curr_directory)', False, 'import os\n'), ((821, 9, 821, 38), 'os.path.isdir', 'os.path.isdir', ({(821, 23, 821, 37): 'curr_directory'}, {}), '(curr_directory)', False, 'import os\n'), ((825, 9, 825, 30), 'cv2.imread', 'cv2.imread', ({(825, 20, 825, 29): 'imagefile'}, {}), '(imagefile)', False, 'import cv2\n'), ((890, 11, 890, 41), 'users.models.Time.objects.filter', 'Time.objects.filter', (), '', False, 'from users.models import Present, Time\n'), ((891, 14, 891, 47), 'users.models.Present.objects.filter', 'Present.objects.filter', (), '', False, 'from users.models import Present, Time\n'), ((984, 11, 984, 38), 'users.models.Time.objects.filter', 'Time.objects.filter', (), '', False, 'from users.models import Present, Time\n'), ((985, 14, 985, 44), 'users.models.Present.objects.filter', 'Present.objects.filter', (), '', False, 'from users.models import Present, Time\n'), ((187, 8, 187, 50), 'users.models.Present', 'Present', (), '', False, 'from users.models import Present, Time\n'), ((190, 6, 190, 49), 'users.models.Present', 'Present', (), '', False, 'from users.models import Present, Time\n'), ((438, 5, 438, 38), 'users.models.Present.objects.filter', 'Present.objects.filter', (), '', False, 'from users.models import Present, Time\n'), ((444, 31, 444, 59), 'datetime.timedelta', 'datetime.timedelta', (), '', False, 'import datetime\n'), ((493, 5, 493, 38), 'users.models.Present.objects.filter', 'Present.objects.filter', (), '', False, 'from users.models import Present, Time\n'), ((499, 31, 499, 59), 'datetime.timedelta', 'datetime.timedelta', (), '', False, 'import datetime\n'), ((896, 11, 896, 94), 'django.shortcuts.render', 'render', ({(896, 18, 896, 25): 'request', (896, 26, 896, 65): '"""recognition/view_attendance_date.html"""', (896, 67, 896, 93): "{'form': form, 'qs': qs}"}, {}), "(request, 'recognition/view_attendance_date.html', {'form': form,\n    'qs': qs})", False, 'from django.shortcuts import render, redirect\n'), ((898, 4, 898, 63), 'django.contrib.messages.warning', 'messages.warning', ({(898, 21, 898, 28): 'request', (898, 30, 898, 62): 'f"""No records for selected date."""'}, {}), "(request, f'No records for selected date.')", False, 'from django.contrib import messages\n'), ((899, 11, 899, 43), 'django.shortcuts.redirect', 'redirect', ({(899, 20, 899, 42): '"""view-attendance-date"""'}, {}), "('view-attendance-date')", False, 'from django.shortcuts import render, redirect\n'), ((929, 6, 929, 41), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', (), '', False, 'from django.contrib.auth.models import User\n'), ((931, 12, 931, 39), 'users.models.Time.objects.filter', 'Time.objects.filter', (), '', False, 'from users.models import Present, Time\n'), ((932, 15, 932, 45), 'users.models.Present.objects.filter', 'Present.objects.filter', (), '', False, 'from users.models import Present, Time\n'), ((960, 4, 960, 57), 'django.contrib.messages.warning', 'messages.warning', ({(960, 21, 960, 28): 'request', (960, 30, 960, 56): 'f"""No such username found."""'}, {}), "(request, f'No such username found.')", False, 'from django.contrib import messages\n'), ((961, 11, 961, 47), 'django.shortcuts.redirect', 'redirect', ({(961, 20, 961, 46): '"""view-attendance-employee"""'}, {}), "('view-attendance-employee')", False, 'from django.shortcuts import render, redirect\n'), ((989, 5, 989, 58), 'django.contrib.messages.warning', 'messages.warning', ({(989, 22, 989, 29): 'request', (989, 31, 989, 57): 'f"""Invalid date selection."""'}, {}), "(request, f'Invalid date selection.')", False, 'from django.contrib import messages\n'), ((990, 12, 990, 57), 'django.shortcuts.redirect', 'redirect', ({(990, 21, 990, 56): '"""view-my-attendance-employee-login"""'}, {}), "('view-my-attendance-employee-login')", False, 'from django.shortcuts import render, redirect\n'), ((648, 22, 648, 45), 'datetime.datetime.now', 'datetime.datetime.now', ({}, {}), '()', False, 'import datetime\n'), ((758, 22, 758, 45), 'datetime.datetime.now', 'datetime.datetime.now', ({}, {}), '()', False, 'import datetime\n'), ((835, 4, 835, 24), 'os.remove', 'os.remove', ({(835, 14, 835, 23): 'imagefile'}, {}), '(imagefile)', False, 'import os\n'), ((937, 5, 937, 58), 'django.contrib.messages.warning', 'messages.warning', ({(937, 22, 937, 29): 'request', (937, 31, 937, 57): 'f"""Invalid date selection."""'}, {}), "(request, f'Invalid date selection.')", False, 'from django.contrib import messages\n'), ((938, 12, 938, 48), 'django.shortcuts.redirect', 'redirect', ({(938, 21, 938, 47): '"""view-attendance-employee"""'}, {}), "('view-attendance-employee')", False, 'from django.shortcuts import render, redirect\n'), ((999, 13, 999, 108), 'django.shortcuts.render', 'render', ({(999, 20, 999, 27): 'request', (999, 28, 999, 80): '"""recognition/view_my_attendance_employee_login.html"""', (999, 82, 999, 107): "{'form': form, 'qs': qs}"}, {}), "(request, 'recognition/view_my_attendance_employee_login.html', {\n    'form': form, 'qs': qs})", False, 'from django.shortcuts import render, redirect\n'), ((1002, 6, 1002, 69), 'django.contrib.messages.warning', 'messages.warning', ({(1002, 23, 1002, 30): 'request', (1002, 32, 1002, 68): 'f"""No records for selected duration."""'}, {}), "(request, f'No records for selected duration.')", False, 'from django.contrib import messages\n'), ((1003, 13, 1003, 58), 'django.shortcuts.redirect', 'redirect', ({(1003, 22, 1003, 57): '"""view-my-attendance-employee-login"""'}, {}), "('view-my-attendance-employee-login')", False, 'from django.shortcuts import render, redirect\n'), ((637, 42, 637, 58), 'numpy.ravel', 'np.ravel', ({(637, 51, 637, 57): '[pred]'}, {}), '([pred])', True, 'import numpy as np\n'), ((747, 42, 747, 58), 'numpy.ravel', 'np.ravel', ({(747, 51, 747, 57): '[pred]'}, {}), '([pred])', True, 'import numpy as np\n'), ((947, 13, 947, 99), 'django.shortcuts.render', 'render', ({(947, 20, 947, 27): 'request', (947, 28, 947, 71): '"""recognition/view_attendance_employee.html"""', (947, 73, 947, 98): "{'form': form, 'qs': qs}"}, {}), "(request, 'recognition/view_attendance_employee.html', {'form': form,\n    'qs': qs})", False, 'from django.shortcuts import render, redirect\n'), ((950, 6, 950, 69), 'django.contrib.messages.warning', 'messages.warning', ({(950, 23, 950, 30): 'request', (950, 32, 950, 68): 'f"""No records for selected duration."""'}, {}), "(request, f'No records for selected duration.')", False, 'from django.contrib import messages\n'), ((951, 13, 951, 49), 'django.shortcuts.redirect', 'redirect', ({(951, 22, 951, 48): '"""view-attendance-employee"""'}, {}), "('view-attendance-employee')", False, 'from django.shortcuts import render, redirect\n'), ((827, 14, 827, 52), 'face_recognition.face_encodings', 'face_recognition.face_encodings', ({(827, 46, 827, 51): 'image'}, {}), '(image)', False, 'import face_recognition\n')]