import cv2
import imutils
import numpy as np
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input


def detect_mask(frame, face, maskNet):
	
	(h, w) = frame.shape[:2]
	blob = cv2.dnn.blobFromImage(frame, 1.0, (224, 224), (104.0, 177.0, 123.0))

	face.setInput(blob)
	detections = face.forward()
	faces = []
	loc = []
	prediction = []

	for i in range(0, detections.shape[2]):
		confidence = detections[0, 0, i, 2]

		if confidence > 0.5:
			
			rectangle = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
			(startX, startY, endX, endY) = rectangle.astype("int")

			(startX, startY) = (max(0, startX), max(0, startY))
			(endX, endY) = (min(w - 1, endX), min(h - 1, endY))

			face = frame[startY:endY, startX:endX]
			face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)
			face = cv2.resize(face, (224, 224))
			face = img_to_array(face)
			face = preprocess_input(face)

			faces.append(face)
			loc.append((startX, startY, endX, endY))

	if len(faces) > 0:
		faces = np.array(faces, dtype="float32")
		prediction = maskNet.predict(faces, batch_size=32)

	return (loc, prediction)

prototxtPath = r"detect_face\deploy.prototxt"
weightsPath = r"detect_face\res10_300x300_ssd_iter_140000.caffemodel"
face = cv2.dnn.readNet(prototxtPath, weightsPath)

maskNet = load_model("detect_mask.model")

cap = cv2.VideoCapture("vid.mp4")

while True:
	_, frame = cap.read()
	frame = imutils.resize(frame, width=500)

	(loc, prediction) = detect_mask(frame, face, maskNet)

	for (rectangle, pred) in zip(loc, prediction):
		(startX, startY, endX, endY) = rectangle
		(mask, withoutMask) = pred

		if mask > withoutMask:
			label = "MASK"
		else:
			label = "NO MASK"

		if label == "MASK":
			color = (155, 255, 0) 
		else:
			color = (100, 0, 255)

		label = "{}: {:.2f}%".format(label, max(mask, withoutMask) * 100)

		cv2.putText(frame, label, (startX, startY - 10),
			cv2.FONT_HERSHEY_TRIPLEX, 0.65, color, 1)
		cv2.rectangle(frame, (startX, startY), (endX, endY), color, 2)

	cv2.imshow("Mask detecttion", frame)
	key = cv2.waitKey(1) & 0xFF

	if key == ord("q"):
		break

cv2.destroyAllWindows()
cap.stop()