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, 'matplotlib.use', 'mpl.use', (['"""Agg"""'], {}), True, 'import matplotlib as mpl\n'), (58, 'dlib.get_frontal_face_detector', 'dlib.get_frontal_face_detector', ([], {}), False, 'import dlib\n'), (59, 'dlib.shape_predictor', 'dlib.shape_predictor', (['"""face_recognition_data/shape_predictor_68_face_landmarks.dat"""'], {}), False, 'import dlib\n'), (60, 'imutils.face_utils.FaceAligner', 'FaceAligner', (['predictor'], {'desiredFaceWidth': '(96)'}), False, 'from imutils.face_utils import FaceAligner\n'), (136, 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), False, 'import cv2\n'), (140, 'numpy.zeros', 'np.zeros', (['(1, 128)'], {}), True, 'import numpy as np\n'), (167, 'matplotlib.pyplot.legend', 'plt.legend', ([], {'bbox_to_anchor': '(1, 1)'}), True, 'import matplotlib.pyplot as plt\n'), (168, 'matplotlib.rcParams.update', 'rcParams.update', (["{'figure.autolayout': True}"], {}), False, 'from matplotlib import rcParams\n'), (169, 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), True, 'import matplotlib.pyplot as plt\n'), (170, 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""./recognition/static/recognition/img/training_visualisation.png"""'], {}), True, 'import matplotlib.pyplot as plt\n'), (171, 'matplotlib.pyplot.close', 'plt.close', ([], {}), True, 'import matplotlib.pyplot as plt\n'), (176, 'datetime.date.today', 'datetime.date.today', ([], {}), False, 'import datetime\n'), (177, 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), False, 'import datetime\n'), (208, 'datetime.date.today', 'datetime.date.today', ([], {}), False, 'import datetime\n'), (209, 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), False, 'import datetime\n'), (265, 'math.ceil', 'math.ceil', (['m'], {}), False, 'import math\n'), (272, 'pandas.plotting.register_matplotlib_converters', 'register_matplotlib_converters', ([], {}), False, 'from pandas.plotting import register_matplotlib_converters\n'), (320, 'django_pandas.io.read_frame', 'read_frame', (['qs'], {}), False, 'from django_pandas.io import read_frame\n'), (328, 'seaborn.barplot', 'sns.barplot', ([], {'data': 'df', 'x': '"""date"""', 'y': '"""hours"""'}), True, 'import seaborn as sns\n'), (329, 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '"""vertical"""'}), True, 'import matplotlib.pyplot as plt\n'), (330, 'matplotlib.rcParams.update', 'rcParams.update', (["{'figure.autolayout': True}"], {}), False, 'from matplotlib import rcParams\n'), (331, 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), True, 'import matplotlib.pyplot as plt\n'), (343, 'pandas.plotting.register_matplotlib_converters', 'register_matplotlib_converters', ([], {}), False, 'from pandas.plotting import register_matplotlib_converters\n'), (388, 'django_pandas.io.read_frame', 'read_frame', (['qs'], {}), False, 'from django_pandas.io import read_frame\n'), (394, 'seaborn.barplot', 'sns.barplot', ([], {'data': 'df', 'x': '"""username"""', 'y': '"""hours"""'}), True, 'import seaborn as sns\n'), (395, 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '"""vertical"""'}), True, 'import matplotlib.pyplot as plt\n'), (396, 'matplotlib.rcParams.update', 'rcParams.update', (["{'figure.autolayout': True}"], {}), False, 'from matplotlib import rcParams\n'), (397, 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), True, 'import matplotlib.pyplot as plt\n'), (398, 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""./recognition/static/recognition/img/attendance_graphs/hours_vs_employee/1.png"""'], {}), True, 'import matplotlib.pyplot as plt\n'), (399, 'matplotlib.pyplot.close', 'plt.close', ([], {}), True, 'import matplotlib.pyplot as plt\n'), (404, 'django.contrib.auth.models.User.objects.all', 'User.objects.all', ([], {}), False, 'from django.contrib.auth.models import User\n'), (411, 'datetime.date.today', 'datetime.date.today', ([], {}), False, 'import datetime\n'), (420, 'datetime.date.today', 'datetime.date.today', ([], {}), False, 'import datetime\n'), (460, 'pandas.DataFrame', 'pd.DataFrame', ([], {}), True, 'import pandas as pd\n'), (465, 'seaborn.lineplot', 'sns.lineplot', ([], {'data': 'df', 'x': '"""date"""', 'y': '"""Number of employees"""'}), True, 'import seaborn as sns\n'), (466, 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""./recognition/static/recognition/img/attendance_graphs/this_week/1.png"""'], {}), True, 'import matplotlib.pyplot as plt\n'), (467, 'matplotlib.pyplot.close', 'plt.close', ([], {}), True, 'import matplotlib.pyplot as plt\n'), (476, 'datetime.date.today', 'datetime.date.today', ([], {}), False, 'import datetime\n'), (516, 'pandas.DataFrame', 'pd.DataFrame', ([], {}), True, 'import pandas as pd\n'), (523, 'seaborn.lineplot', 'sns.lineplot', ([], {'data': 'df', 'x': '"""date"""', 'y': '"""emp_count"""'}), True, 'import seaborn as sns\n'), (524, 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""./recognition/static/recognition/img/attendance_graphs/last_week/1.png"""'], {}), True, 'import matplotlib.pyplot as plt\n'), (525, 'matplotlib.pyplot.close', 'plt.close', ([], {}), True, 'import matplotlib.pyplot as plt\n'), (537, 'django.shortcuts.render', 'render', (['request', '"""recognition/home.html"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (579, 'dlib.get_frontal_face_detector', 'dlib.get_frontal_face_detector', ([], {}), False, 'import dlib\n'), (581, 'dlib.shape_predictor', 'dlib.shape_predictor', (['"""face_recognition_data/shape_predictor_68_face_landmarks.dat"""'], {}), False, 'import dlib\n'), (589, 'imutils.face_utils.FaceAligner', 'FaceAligner', (['predictor'], {'desiredFaceWidth': '(96)'}), False, 'from imutils.face_utils import FaceAligner\n'), (590, 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), False, 'from sklearn.preprocessing import LabelEncoder\n'), (591, 'numpy.load', 'np.load', (['"""face_recognition_data/classes.npy"""'], {}), True, 'import numpy as np\n'), (594, 'numpy.zeros', 'np.zeros', (['(1, 128)'], {}), True, 'import numpy as np\n'), (679, 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), False, 'import cv2\n'), (681, 'django.shortcuts.redirect', 'redirect', (['"""home"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (689, 'dlib.get_frontal_face_detector', 'dlib.get_frontal_face_detector', ([], {}), False, 'import dlib\n'), (691, 'dlib.shape_predictor', 'dlib.shape_predictor', (['"""face_recognition_data/shape_predictor_68_face_landmarks.dat"""'], {}), False, 'import dlib\n'), (699, 'imutils.face_utils.FaceAligner', 'FaceAligner', (['predictor'], {'desiredFaceWidth': '(96)'}), False, 'from imutils.face_utils import FaceAligner\n'), (700, 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), False, 'from sklearn.preprocessing import LabelEncoder\n'), (701, 'numpy.load', 'np.load', (['"""face_recognition_data/classes.npy"""'], {}), True, 'import numpy as np\n'), (704, 'numpy.zeros', 'np.zeros', (['(1, 128)'], {}), True, 'import numpy as np\n'), (789, 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), False, 'import cv2\n'), (791, 'django.shortcuts.redirect', 'redirect', (['"""home"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (806, 'os.listdir', 'os.listdir', (['training_dir'], {}), False, 'import os\n'), (818, 'os.listdir', 'os.listdir', (['training_dir'], {}), False, 'import os\n'), (840, 'numpy.array', 'np.array', (['y'], {}), True, 'import numpy as np\n'), (841, 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), False, 'from sklearn.preprocessing import LabelEncoder\n'), (844, 'numpy.array', 'np.array', (['X'], {}), True, 'import numpy as np\n'), (846, 'numpy.save', 'np.save', (['"""face_recognition_data/classes.npy"""', 'encoder.classes_'], {}), True, 'import numpy as np\n'), (847, 'sklearn.svm.SVC', 'SVC', ([], {'kernel': '"""linear"""', 'probability': '(True)'}), False, 'from sklearn.svm import SVC\n'), (856, 'django.contrib.messages.success', 'messages.success', (['request', 'f"""Training Complete."""'], {}), False, 'from django.contrib import messages\n'), (858, 'django.shortcuts.render', 'render', (['request', '"""recognition/train.html"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (863, 'django.shortcuts.render', 'render', (['request', '"""recognition/not_authorised.html"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (873, 'django.shortcuts.render', 'render', (['request', '"""recognition/view_attendance_home.html"""', "{'total_num_of_emp': total_num_of_emp, 'emp_present_today': emp_present_today}"], {}), False, 'from django.shortcuts import render, redirect\n'), (78, 'imutils.resize', 'imutils.resize', (['frame'], {'width': '(800)'}), False, 'import imutils\n'), (81, 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2GRAY'], {}), False, 'import cv2\n'), (125, 'cv2.imshow', 'cv2.imshow', (['"""Add Images"""', 'frame'], {}), False, 'import cv2\n'), (128, 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), False, 'import cv2\n'), (142, 'face_recognition.face_locations', 'face_recognition.face_locations', (['face_aligned'], {}), False, 'import face_recognition\n'), (143, 'face_recognition.face_encodings', 'face_recognition.face_encodings', (['face_aligned'], {'known_face_locations': 'x_face_locations'}), False, 'import face_recognition\n'), (165, 'matplotlib.pyplot.scatter', 'plt.scatter', (['X_embedded[idx, 0]', 'X_embedded[idx, 1]'], {'label': 't'}), True, 'import matplotlib.pyplot as plt\n'), (179, 'django.contrib.auth.models.User.objects.get', 'User.objects.get', ([], {'username': 'person'}), False, 'from django.contrib.auth.models import User\n'), (211, 'django.contrib.auth.models.User.objects.get', 'User.objects.get', ([], {'username': 'person'}), False, 'from django.contrib.auth.models import User\n'), (333, 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""./recognition/static/recognition/img/attendance_graphs/hours_vs_date/1.png"""'], {}), True, 'import matplotlib.pyplot as plt\n'), (334, 'matplotlib.pyplot.close', 'plt.close', ([], {}), True, 'import matplotlib.pyplot as plt\n'), (336, 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""./recognition/static/recognition/img/attendance_graphs/employee_login/1.png"""'], {}), True, 'import matplotlib.pyplot as plt\n'), (337, 'matplotlib.pyplot.close', 'plt.close', ([], {}), True, 'import matplotlib.pyplot as plt\n'), (421, 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(7)'}), False, 'import datetime\n'), (423, 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(7)'}), False, 'import datetime\n'), (477, 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(7)'}), False, 'import datetime\n'), (479, 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(7)'}), False, 'import datetime\n'), (543, 'django.shortcuts.render', 'render', (['request', '"""recognition/admin_dashboard.html"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (547, 'django.shortcuts.render', 'render', (['request', '"""recognition/employee_dashboard.html"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (552, 'django.shortcuts.redirect', 'redirect', (['"""not-authorised"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (570, 'django.shortcuts.render', 'render', (['request', '"""recognition/add_photos.html"""', "{'form': form}"], {}), False, 'from django.shortcuts import render, redirect\n'), (588, 'pickle.load', 'pickle.load', (['f'], {}), False, 'import pickle\n'), (614, 'imutils.resize', 'imutils.resize', (['frame'], {'width': '(800)'}), False, 'import imutils\n'), (616, 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2GRAY'], {}), False, 'import cv2\n'), (666, 'cv2.imshow', 'cv2.imshow', (['"""Mark Attendance - In - Press q to exit"""', 'frame'], {}), False, 'import cv2\n'), (698, 'pickle.load', 'pickle.load', (['f'], {}), False, 'import pickle\n'), (724, 'imutils.resize', 'imutils.resize', (['frame'], {'width': '(800)'}), False, 'import imutils\n'), (726, 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2GRAY'], {}), False, 'import cv2\n'), (776, 'cv2.imshow', 'cv2.imshow', (['"""Mark Attendance- Out - Press q to exit"""', 'frame'], {}), False, 'import cv2\n'), (799, 'django.shortcuts.redirect', 'redirect', (['"""not-authorised"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (807, 'os.path.join', 'os.path.join', (['training_dir', 'person_name'], {}), False, 'import os\n'), (810, 'face_recognition.face_recognition_cli.image_files_in_folder', 'image_files_in_folder', (['curr_directory'], {}), False, 'from face_recognition.face_recognition_cli import image_files_in_folder\n'), (820, 'os.path.join', 'os.path.join', (['training_dir', 'person_name'], {}), False, 'import os\n'), (823, 'face_recognition.face_recognition_cli.image_files_in_folder', 'image_files_in_folder', (['curr_directory'], {}), False, 'from face_recognition.face_recognition_cli import image_files_in_folder\n'), (851, 'pickle.dump', 'pickle.dump', (['svc', 'f'], {}), False, 'import pickle\n'), (879, 'django.shortcuts.redirect', 'redirect', (['"""not-authorised"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (912, 'django.shortcuts.render', 'render', (['request', '"""recognition/view_attendance_date.html"""', "{'form': form, 'qs': qs}"], {}), False, 'from django.shortcuts import render, redirect\n'), (918, 'django.shortcuts.redirect', 'redirect', (['"""not-authorised"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (968, 'django.shortcuts.render', 'render', (['request', '"""recognition/view_attendance_employee.html"""', "{'form': form, 'qs': qs}"], {}), False, 'from django.shortcuts import render, redirect\n'), (976, 'django.shortcuts.redirect', 'redirect', (['"""not-authorised"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (1008, 'django.shortcuts.render', 'render', (['request', '"""recognition/view_my_attendance_employee_login.html"""', "{'form': form, 'qs': qs}"], {}), False, 'from django.shortcuts import render, redirect\n'), (43, 'django.contrib.auth.models.User.objects.filter', 'User.objects.filter', ([], {'username': 'username'}), False, 'from django.contrib.auth.models import User\n'), (64, 'imutils.video.VideoStream', 'VideoStream', ([], {'src': '(0)'}), False, 'from imutils.video import VideoStream\n'), (94, 'imutils.face_utils.rect_to_bb', 'face_utils.rect_to_bb', (['face'], {}), False, 'from imutils import face_utils\n'), (112, 'imutils.resize', 'imutils.resize', (['face_aligned'], {'width': '(400)'}), False, 'import imutils\n'), (118, 'cv2.rectangle', 'cv2.rectangle', (['frame', '(x, y)', '(x + w, y + h)', '(0, 255, 0)', '(1)'], {}), False, 'import cv2\n'), (121, 'cv2.waitKey', 'cv2.waitKey', (['(50)'], {}), False, 'import cv2\n'), (152, 'numpy.amax', 'np.amax', (['prob[0]'], {}), True, 'import numpy as np\n'), (161, 'sklearn.manifold.TSNE', 'TSNE', ([], {'n_components': '(2)'}), False, 'from sklearn.manifold import TSNE\n'), (181, 'users.models.Present.objects.get', 'Present.objects.get', ([], {'user': 'user', 'date': 'today'}), False, 'from users.models import Present, Time\n'), (197, 'users.models.Time', 'Time', ([], {'user': 'user', 'date': 'today', 'time': 'time', 'out': '(False)'}), False, 'from users.models import Present, Time\n'), (213, 'users.models.Time', 'Time', ([], {'user': 'user', 'date': 'today', 'time': 'time', 'out': '(True)'}), False, 'from users.models import Present, Time\n'), (412, 'users.models.Present.objects.filter', 'Present.objects.filter', ([], {'date': 'today'}), False, 'from users.models import Present, Time\n'), (424, 'users.models.Present.objects.filter', 'Present.objects.filter', ([], {'date__gte': 'monday_of_this_week'}), False, 'from users.models import Present, Time\n'), (480, 'users.models.Present.objects.filter', 'Present.objects.filter', ([], {'date__gte': 'monday_of_last_week'}), False, 'from users.models import Present, Time\n'), (559, 'django.contrib.messages.success', 'messages.success', (['request', 'f"""Dataset Created"""'], {}), False, 'from django.contrib import messages\n'), (560, 'django.shortcuts.redirect', 'redirect', (['"""add-photos"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (562, 'django.contrib.messages.warning', 'messages.warning', (['request', 'f"""No such username found. Please register employee first."""'], {}), False, 'from django.contrib import messages\n'), (563, 'django.shortcuts.redirect', 'redirect', (['"""dashboard"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (606, 'imutils.video.VideoStream', 'VideoStream', ([], {'src': '(0)'}), False, 'from imutils.video import VideoStream\n'), (625, 'imutils.face_utils.rect_to_bb', 'face_utils.rect_to_bb', (['face'], {}), False, 'from imutils import face_utils\n'), (628, 'cv2.rectangle', 'cv2.rectangle', (['frame', '(x, y)', '(x + w, y + h)', '(0, 255, 0)', '(1)'], {}), False, 'import cv2\n'), (671, 'cv2.waitKey', 'cv2.waitKey', (['(50)'], {}), False, 'import cv2\n'), (716, 'imutils.video.VideoStream', 'VideoStream', ([], {'src': '(0)'}), False, 'from imutils.video import VideoStream\n'), (735, 'imutils.face_utils.rect_to_bb', 'face_utils.rect_to_bb', (['face'], {}), False, 'from imutils import face_utils\n'), (738, 'cv2.rectangle', 'cv2.rectangle', (['frame', '(x, y)', '(x + w, y + h)', '(0, 255, 0)', '(1)'], {}), False, 'import cv2\n'), (781, 'cv2.waitKey', 'cv2.waitKey', (['(50)'], {}), False, 'import cv2\n'), (808, 'os.path.isdir', 'os.path.isdir', (['curr_directory'], {}), False, 'import os\n'), (821, 'os.path.isdir', 'os.path.isdir', (['curr_directory'], {}), False, 'import os\n'), (825, 'cv2.imread', 'cv2.imread', (['imagefile'], {}), False, 'import cv2\n'), (890, 'users.models.Time.objects.filter', 'Time.objects.filter', ([], {'date': 'date'}), False, 'from users.models import Present, Time\n'), (891, 'users.models.Present.objects.filter', 'Present.objects.filter', ([], {'date': 'date'}), False, 'from users.models import Present, Time\n'), (984, 'users.models.Time.objects.filter', 'Time.objects.filter', ([], {'user': 'u'}), False, 'from users.models import Present, Time\n'), (985, 'users.models.Present.objects.filter', 'Present.objects.filter', ([], {'user': 'u'}), False, 'from users.models import Present, Time\n'), (187, 'users.models.Present', 'Present', ([], {'user': 'user', 'date': 'today', 'present': '(True)'}), False, 'from users.models import Present, Time\n'), (190, 'users.models.Present', 'Present', ([], {'user': 'user', 'date': 'today', 'present': '(False)'}), False, 'from users.models import Present, Time\n'), (438, 'users.models.Present.objects.filter', 'Present.objects.filter', ([], {'date': 'date'}), False, 'from users.models import Present, Time\n'), (444, 'datetime.timedelta', 'datetime.timedelta', ([], {'days': 'cnt'}), False, 'import datetime\n'), (493, 'users.models.Present.objects.filter', 'Present.objects.filter', ([], {'date': 'date'}), False, 'from users.models import Present, Time\n'), (499, 'datetime.timedelta', 'datetime.timedelta', ([], {'days': 'cnt'}), False, 'import datetime\n'), (896, 'django.shortcuts.render', 'render', (['request', '"""recognition/view_attendance_date.html"""', "{'form': form, 'qs': qs}"], {}), False, 'from django.shortcuts import render, redirect\n'), (898, 'django.contrib.messages.warning', 'messages.warning', (['request', 'f"""No records for selected date."""'], {}), False, 'from django.contrib import messages\n'), (899, 'django.shortcuts.redirect', 'redirect', (['"""view-attendance-date"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (929, 'django.contrib.auth.models.User.objects.get', 'User.objects.get', ([], {'username': 'username'}), False, 'from django.contrib.auth.models import User\n'), (931, 'users.models.Time.objects.filter', 'Time.objects.filter', ([], {'user': 'u'}), False, 'from users.models import Present, Time\n'), (932, 'users.models.Present.objects.filter', 'Present.objects.filter', ([], {'user': 'u'}), False, 'from users.models import Present, Time\n'), (960, 'django.contrib.messages.warning', 'messages.warning', (['request', 'f"""No such username found."""'], {}), False, 'from django.contrib import messages\n'), (961, 'django.shortcuts.redirect', 'redirect', (['"""view-attendance-employee"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (989, 'django.contrib.messages.warning', 'messages.warning', (['request', 'f"""Invalid date selection."""'], {}), False, 'from django.contrib import messages\n'), (990, 'django.shortcuts.redirect', 'redirect', (['"""view-my-attendance-employee-login"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (648, 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), False, 'import datetime\n'), (758, 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), False, 'import datetime\n'), (835, 'os.remove', 'os.remove', (['imagefile'], {}), False, 'import os\n'), (937, 'django.contrib.messages.warning', 'messages.warning', (['request', 'f"""Invalid date selection."""'], {}), False, 'from django.contrib import messages\n'), (938, 'django.shortcuts.redirect', 'redirect', (['"""view-attendance-employee"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (999, 'django.shortcuts.render', 'render', (['request', '"""recognition/view_my_attendance_employee_login.html"""', "{'form': form, 'qs': qs}"], {}), False, 'from django.shortcuts import render, redirect\n'), (1002, 'django.contrib.messages.warning', 'messages.warning', (['request', 'f"""No records for selected duration."""'], {}), False, 'from django.contrib import messages\n'), (1003, 'django.shortcuts.redirect', 'redirect', (['"""view-my-attendance-employee-login"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (637, 'numpy.ravel', 'np.ravel', (['[pred]'], {}), True, 'import numpy as np\n'), (747, 'numpy.ravel', 'np.ravel', (['[pred]'], {}), True, 'import numpy as np\n'), (947, 'django.shortcuts.render', 'render', (['request', '"""recognition/view_attendance_employee.html"""', "{'form': form, 'qs': qs}"], {}), False, 'from django.shortcuts import render, redirect\n'), (950, 'django.contrib.messages.warning', 'messages.warning', (['request', 'f"""No records for selected duration."""'], {}), False, 'from django.contrib import messages\n'), (951, 'django.shortcuts.redirect', 'redirect', (['"""view-attendance-employee"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (827, 'face_recognition.face_encodings', 'face_recognition.face_encodings', (['image'], {}), False, 'import face_recognition\n')]