Spaces:
Build error
Build error
Update app.py
#1
by
vikramjeetthakur
- opened
app.py
CHANGED
|
@@ -1,119 +1,158 @@
|
|
| 1 |
-
|
| 2 |
from PIL import Image
|
| 3 |
import numpy as np
|
| 4 |
import cv2
|
| 5 |
-
import requests
|
| 6 |
import face_recognition
|
| 7 |
import os
|
| 8 |
-
import
|
| 9 |
-
import
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
directory
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
Images.append(curImg)
|
| 42 |
-
classnames.append(os.path.splitext(cls)[0])
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
# Load images for face recognition
|
| 46 |
-
encodeListknown = [face_recognition.face_encodings(img)[0] for img in Images]
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
####### Section 3 ###################
|
| 50 |
-
# Take picture using the camera
|
| 51 |
-
img_file_buffer = st.camera_input("Take Your picture")
|
| 52 |
-
|
| 53 |
-
# recognise the face in the uploaded image
|
| 54 |
-
if img_file_buffer is not None:
|
| 55 |
-
test_image = Image.open(img_file_buffer)
|
| 56 |
-
image = np.asarray(test_image)
|
| 57 |
-
image = image.copy()
|
| 58 |
-
|
| 59 |
-
imgS = cv2.resize(image, (0, 0), None, 0.25, 0.25)
|
| 60 |
-
imgS = cv2.cvtColor(imgS, cv2.COLOR_BGR2RGB)
|
| 61 |
-
facesCurFrame = face_recognition.face_locations(imgS)
|
| 62 |
-
encodesCurFrame = face_recognition.face_encodings(imgS, facesCurFrame)
|
| 63 |
-
faceMatchedflag = 0
|
| 64 |
-
# run looop to find match in encodeListknown list
|
| 65 |
-
for encodeFace, faceLoc in zip(encodesCurFrame, facesCurFrame):
|
| 66 |
-
# Assuming that encodeListknown is defined and populated in your code
|
| 67 |
-
matches = face_recognition.compare_faces(encodeListknown, encodeFace)
|
| 68 |
-
faceDis = face_recognition.face_distance(encodeListknown, encodeFace)
|
| 69 |
-
matchIndex = np.argmin(faceDis)
|
| 70 |
-
|
| 71 |
-
if matches[matchIndex]:
|
| 72 |
-
name = classnames[matchIndex].upper()
|
| 73 |
-
#st.write (name)
|
| 74 |
-
# show the name on image to user
|
| 75 |
-
y1, x2, y2, x1 = faceLoc
|
| 76 |
-
y1, x2, y2, x1 = y1 * 4, x2 * 4, y2 * 4, x1 * 4
|
| 77 |
-
cv2.rectangle(image , (x1, y1), (x2, y2), (0, 255, 0), 2)
|
| 78 |
-
cv2.rectangle(image , (x1, y2 - 35), (x2, y2), (0, 255, 0), cv2.FILLED)
|
| 79 |
-
cv2.putText(image , name, (x1 + 6, y2 - 6), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)
|
| 80 |
-
|
| 81 |
-
########## update website
|
| 82 |
-
# using Get Method
|
| 83 |
-
# Construct the URL
|
| 84 |
-
url = "https://fc11.glitch.me/submit?email=pm&message=faceReco&name="
|
| 85 |
-
url = url + name
|
| 86 |
-
st.write("Constructed URL:", url)
|
| 87 |
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
#
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
-
|
| 119 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
from PIL import Image
|
| 3 |
import numpy as np
|
| 4 |
import cv2
|
|
|
|
| 5 |
import face_recognition
|
| 6 |
import os
|
| 7 |
+
from typing import List, Tuple
|
| 8 |
+
import requests
|
| 9 |
+
from urllib.parse import quote
|
| 10 |
+
import logging
|
| 11 |
+
|
| 12 |
+
# Set up logging
|
| 13 |
+
logging.basicConfig(level=logging.INFO)
|
| 14 |
+
logger = logging.getLogger(__name__)
|
| 15 |
+
|
| 16 |
+
class FaceRecognitionApp:
|
| 17 |
+
def __init__(self, image_directory: str = "facerecognition"):
|
| 18 |
+
"""Initialize the face recognition application."""
|
| 19 |
+
self.image_directory = image_directory
|
| 20 |
+
self.images: List[np.ndarray] = []
|
| 21 |
+
self.classnames: List[str] = []
|
| 22 |
+
self.encode_list_known = None
|
| 23 |
+
|
| 24 |
+
# Initialize Streamlit page
|
| 25 |
+
st.set_page_config(page_title="Face Recognition System", page_icon="👤")
|
| 26 |
+
st.title("Face Recognition System")
|
| 27 |
+
|
| 28 |
+
# Load and encode known faces
|
| 29 |
+
self._load_known_faces()
|
| 30 |
+
|
| 31 |
+
def _load_known_faces(self) -> None:
|
| 32 |
+
"""Load and encode all known faces from the directory and predefined images."""
|
| 33 |
+
try:
|
| 34 |
+
# Load predefined images
|
| 35 |
+
predefined_images = {
|
| 36 |
+
"sarwan.jpg": "Sarwan",
|
| 37 |
+
"rattantata.png": "RattanTata",
|
| 38 |
+
"Ravinder.jpg": "RavinderKaur"
|
| 39 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
+
for img_path, name in predefined_images.items():
|
| 42 |
+
if os.path.exists(img_path):
|
| 43 |
+
img = cv2.imread(img_path)
|
| 44 |
+
if img is not None:
|
| 45 |
+
self.images.append(img)
|
| 46 |
+
self.classnames.append(name)
|
| 47 |
+
else:
|
| 48 |
+
logger.warning(f"Failed to load image: {img_path}")
|
| 49 |
+
|
| 50 |
+
# Load images from directory
|
| 51 |
+
if os.path.exists(self.image_directory):
|
| 52 |
+
for filename in os.listdir(self.image_directory):
|
| 53 |
+
if filename.lower().endswith(('.jpg', '.jpeg', '.png')):
|
| 54 |
+
img_path = os.path.join(self.image_directory, filename)
|
| 55 |
+
img = cv2.imread(img_path)
|
| 56 |
+
if img is not None:
|
| 57 |
+
self.images.append(img)
|
| 58 |
+
self.classnames.append(os.path.splitext(filename)[0])
|
| 59 |
+
else:
|
| 60 |
+
logger.warning(f"Failed to load image: {img_path}")
|
| 61 |
+
|
| 62 |
+
# Encode faces
|
| 63 |
+
if self.images:
|
| 64 |
+
self.encode_list_known = []
|
| 65 |
+
for img in self.images:
|
| 66 |
+
rgb_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
| 67 |
+
encodings = face_recognition.face_encodings(rgb_img)
|
| 68 |
+
if encodings:
|
| 69 |
+
self.encode_list_known.append(encodings[0])
|
| 70 |
+
else:
|
| 71 |
+
logger.warning("No face detected in one of the reference images")
|
| 72 |
+
|
| 73 |
+
logger.info(f"Loaded {len(self.images)} images for face recognition")
|
| 74 |
+
|
| 75 |
+
except Exception as e:
|
| 76 |
+
logger.error(f"Error loading known faces: {str(e)}")
|
| 77 |
+
st.error("Error loading reference images. Please check the image files.")
|
| 78 |
+
|
| 79 |
+
def _process_face(self, image: np.ndarray, scale: float = 0.25) -> Tuple[np.ndarray, bool]:
|
| 80 |
+
"""Process image and detect faces."""
|
| 81 |
+
img_small = cv2.resize(image, (0, 0), None, scale, scale)
|
| 82 |
+
img_rgb = cv2.cvtColor(img_small, cv2.COLOR_BGR2RGB)
|
| 83 |
+
|
| 84 |
+
face_locations = face_recognition.face_locations(img_rgb)
|
| 85 |
+
face_encodings = face_recognition.face_encodings(img_rgb, face_locations)
|
| 86 |
+
|
| 87 |
+
face_matched = False
|
| 88 |
+
|
| 89 |
+
for encoding, (top, right, bottom, left) in zip(face_encodings, face_locations):
|
| 90 |
+
if self.encode_list_known:
|
| 91 |
+
matches = face_recognition.compare_faces(self.encode_list_known, encoding)
|
| 92 |
+
face_distances = face_recognition.face_distance(self.encode_list_known, encoding)
|
| 93 |
+
|
| 94 |
+
if any(matches):
|
| 95 |
+
best_match_idx = np.argmin(face_distances)
|
| 96 |
+
if matches[best_match_idx]:
|
| 97 |
+
name = self.classnames[best_match_idx].upper()
|
| 98 |
+
face_matched = True
|
| 99 |
+
|
| 100 |
+
# Scale back the coordinates
|
| 101 |
+
top, right, bottom, left = [coord * int(1/scale) for coord in (top, right, bottom, left)]
|
| 102 |
+
|
| 103 |
+
# Draw rectangle and name
|
| 104 |
+
cv2.rectangle(image, (left, top), (right, bottom), (0, 255, 0), 2)
|
| 105 |
+
cv2.rectangle(image, (left, bottom - 35), (right, bottom), (0, 255, 0), cv2.FILLED)
|
| 106 |
+
cv2.putText(image, name, (left + 6, bottom - 6),
|
| 107 |
+
cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)
|
| 108 |
+
|
| 109 |
+
# Update external service
|
| 110 |
+
self._update_external_service(name)
|
| 111 |
+
|
| 112 |
+
return image, face_matched
|
| 113 |
+
|
| 114 |
+
def _update_external_service(self, name: str) -> None:
|
| 115 |
+
"""Update external service with recognition results."""
|
| 116 |
+
try:
|
| 117 |
+
base_url = "https://fc11.glitch.me/submit"
|
| 118 |
+
params = {
|
| 119 |
+
"email": "pm",
|
| 120 |
+
"message": "faceReco",
|
| 121 |
+
"name": quote(name)
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
response = requests.get(base_url, params=params, timeout=5)
|
| 125 |
+
response.raise_for_status()
|
| 126 |
+
|
| 127 |
+
st.success(f"Successfully updated recognition for {name}")
|
| 128 |
+
logger.info(f"External service updated for {name}")
|
| 129 |
|
| 130 |
+
except requests.exceptions.RequestException as e:
|
| 131 |
+
logger.error(f"Failed to update external service: {str(e)}")
|
| 132 |
+
st.warning("Failed to update external service, but recognition completed successfully")
|
| 133 |
+
|
| 134 |
+
def run(self) -> None:
|
| 135 |
+
"""Run the face recognition application."""
|
| 136 |
+
if not self.encode_list_known:
|
| 137 |
+
st.error("No reference faces loaded. Please check the image directory.")
|
| 138 |
+
return
|
| 139 |
+
|
| 140 |
+
img_file_buffer = st.camera_input("Take Your Picture")
|
| 141 |
+
|
| 142 |
+
if img_file_buffer is not None:
|
| 143 |
+
try:
|
| 144 |
+
image = np.array(Image.open(img_file_buffer))
|
| 145 |
+
processed_image, face_matched = self._process_face(image.copy())
|
| 146 |
+
|
| 147 |
+
st.image(processed_image, use_column_width=True, channels="BGR")
|
| 148 |
+
|
| 149 |
+
if not face_matched:
|
| 150 |
+
st.warning("No matching faces found in the image.")
|
| 151 |
+
|
| 152 |
+
except Exception as e:
|
| 153 |
+
logger.error(f"Error processing image: {str(e)}")
|
| 154 |
+
st.error("Error processing the image. Please try again.")
|
| 155 |
+
|
| 156 |
+
if __name__ == "__main__":
|
| 157 |
+
app = FaceRecognitionApp()
|
| 158 |
+
app.run()
|