vikramjeetthakur commited on
Commit
7735e32
·
verified ·
1 Parent(s): f680bf4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +151 -112
app.py CHANGED
@@ -1,119 +1,158 @@
1
- ####### Section 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 streamlit as st
9
- import urllib.request
10
-
11
- ####### Section 2 ###################
12
- p1 = "sarwan.jpg"
13
- p2 = "rattantata.png"
14
- p3 = "Ravinder.jpg"
15
-
16
- st.title("Face Recognition ")
17
- Images = []
18
- classnames = []
19
-
20
- #read images and train the face_recognition package
21
- img1 = cv2.imread(p1)
22
- Images.append(img1)
23
- classnames.append("Sarwan")
24
-
25
- img2 = cv2.imread(p2)
26
- Images.append(img2)
27
- classnames.append("RattanTata")
28
-
29
- img3 = cv2.imread(p3)
30
- Images.append(img3)
31
- classnames.append("RavinderKaur")
32
-
33
- directory = "facerecognition"
34
- myList = os.listdir(directory)
35
-
36
-
37
- for cls in myList:
38
- if os.path.splitext(cls)[1] in [".jpg", ".jpeg",".png"]:
39
- img_path = os.path.join(directory, cls)
40
- curImg = cv2.imread(img_path)
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
- # Try to send the request and handle errors
89
- # try:
90
- # res = urllib.request.urlopen(url)
91
- # response = requests.post(url)
92
- # st.write("Data updated successfully.")
93
- # except urllib.error.URLError as e:
94
- # st.error(f"Failed to open URL: {e}")
95
- # except requests.exceptions.RequestException as e:
96
- # st.error(f"Request failed: {e}")
97
-
98
- url = "https://fc11.glitch.me/submit?email=pm&message=faceReco&name="
99
- url = url + name
100
- st.write(url)
101
- res = urllib.request.urlopen(url)
102
- response = requests.post(url )
103
-
104
- # # using post method
105
- # url = "https://aimljul24f.glitch.me/submit?email=pm&message=faceReco&name="
106
- # url1 = "/save"
107
- # data = {'rollno': '99','name': name, 'email': '[email protected]','pwd': '**' }
108
- # response = requests.post(url +url1 , data=data)
109
- # if response.status_code == 200:
110
- # st.success("Data updated on: " + "https://aimljul24f.glitch.me/")
111
- # else:
112
- # st.warning("Data not updated")
113
- ########### end update website
114
- faceMatchedflag = 1
115
-
116
- st.image(image , use_column_width=True, output_format="PNG")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
- if(faceMatchedflag == 0) :
119
- st.warning("No faces detected in the image.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()