Skip to content

Commit d4cccbe

Browse files
Merge pull request #3 from SentryCoderDev/SentryCoderDev-patch-FaceRecognition
Feature/FaceRecognition
2 parents 727551b + 5140ff1 commit d4cccbe

File tree

6 files changed

+288
-105
lines changed

6 files changed

+288
-105
lines changed

app.py

Lines changed: 77 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,26 @@
1+
import logging
2+
from datetime import datetime
13
from fastapi import FastAPI, WebSocket, Request
24
from fastapi.responses import HTMLResponse, StreamingResponse
35
from fastapi.templating import Jinja2Templates
6+
from fastapi.staticfiles import StaticFiles
47
import cv2
58
import pytesseract
69
import threading
710
import serial
811
import asyncio
12+
import requests
13+
import os
14+
import face_recognition
915

1016
app = FastAPI()
1117
templates = Jinja2Templates(directory="templates")
18+
app.mount("/static", StaticFiles(directory="static"), name="static")
1219

20+
# Log file settings
21+
logging.basicConfig(filename='access_log.txt', level=logging.INFO, format='%(asctime)s - %(message)s')
22+
23+
# Start cameras and serial port
1324
# All Cameras
1425
cameras = [cv2.VideoCapture(i) for i in range(3)]
1526
ser = serial.Serial('/dev/ttyUSB0', 115200) # Arduino's serial port
@@ -22,8 +33,24 @@
2233
}
2334

2435
# Pytesseract configuration
36+
# Pytesseract config
2537
pytesseract.pytesseract.tesseract_cmd = '/usr/bin/tesseract' # Path to Tesseract OCR executable
2638

39+
# Add known faces
40+
known_face_encodings = []
41+
known_face_names = []
42+
43+
def load_known_faces():
44+
known_faces_dir = "known_faces"
45+
for filename in os.listdir(known_faces_dir):
46+
image_path = os.path.join(known_faces_dir, filename)
47+
image = face_recognition.load_image_file(image_path)
48+
face_encoding = face_recognition.face_encodings(image)[0]
49+
known_face_encodings.append(face_encoding)
50+
known_face_names.append(os.path.splitext(filename)[0])
51+
52+
load_known_faces()
53+
2754
def gen_frames(cam_index):
2855
cam = cameras[cam_index]
2956
while True:
@@ -37,7 +64,7 @@ def gen_frames(cam_index):
3764
frame = buffer.tobytes()
3865
yield (b'--frame\r\n'
3966
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
40-
67+
4168
async def garage_control():
4269
while True:
4370
ret, frame = cameras[0].read()
@@ -51,6 +78,34 @@ async def garage_control():
5178
ser.write(b'OPEN_GARAGE\n')
5279
print("Garage opens for plate 'your_target_plate'")
5380
await asyncio.sleep(1)
81+
82+
async def face_recognition_task():
83+
while True:
84+
ret, frame = cameras[2].read()
85+
if ret:
86+
hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
87+
lower_yellow = (20, 100, 100)
88+
upper_yellow = (30, 255, 255)
89+
mask = cv2.inRange(hsv_frame, lower_yellow, upper_yellow)
90+
91+
if cv2.countNonZero(mask) == 0:
92+
ser.write(b'FACE_RECOGNITION\n')
93+
94+
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
95+
face_locations = face_recognition.face_locations(rgb_frame)
96+
face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
97+
98+
for face_encoding in face_encodings:
99+
matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
100+
name = "Unknown"
101+
102+
if True in matches:
103+
first_match_index = matches.index(True)
104+
name = known_face_names[first_match_index]
105+
106+
ser.write(f"IDENTIFIED:{name}\n".encode('utf-8'))
107+
108+
await asyncio.sleep(1)
54109

55110
async def read_from_arduino():
56111
global result_message
@@ -59,8 +114,23 @@ async def read_from_arduino():
59114
line = ser.readline().decode('utf-8').strip()
60115
if line.startswith("RESULT:"):
61116
result_message = line.split("RESULT:")[1]
117+
log_access("User1", result_message)
118+
send_to_nodemcu(result_message)
62119
await asyncio.sleep(0.1)
63120

121+
def log_access(user, identifier):
122+
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
123+
logging.info(f"User: {user}, Identifier: {identifier}, Time: {current_time}")
124+
125+
def send_to_nodemcu(message):
126+
try:
127+
url = "http://nodemcu-ip-address/announce"
128+
data = {"message": message}
129+
response = requests.post(url, json=data)
130+
print("NodeMCU's Answer:", response.text)
131+
except Exception as e:
132+
print(f"Sending data to NodeMCU failed: {e}")
133+
64134
@app.get("/", response_class=HTMLResponse)
65135
async def index(request: Request):
66136
return templates.TemplateResponse("index.html", {"request": request})
@@ -83,6 +153,11 @@ async def validate_password(user: str, password: str):
83153
return {"message": "Password Validated"}
84154
return {"message": "Invalid Password"}, 401
85155

156+
@app.post("/open_garage")
157+
async def open_garage():
158+
ser.write(b'OPEN_GARAGE\n')
159+
return {"message": "Garaj Açıldı"}
160+
86161
@app.get("/result")
87162
async def result():
88163
global result_message
@@ -98,10 +173,7 @@ async def websocket_endpoint(websocket: WebSocket):
98173

99174
if __name__ == "__main__":
100175
threading.Thread(target=asyncio.run, args=(garage_control(),)).start()
176+
threading.Thread(target=asyncio.run, args=(face_recognition_task(),)).start()
101177
threading.Thread(target=asyncio.run, args=(read_from_arduino(),)).start()
102178
import uvicorn
103179
uvicorn.run(app, host="0.0.0.0", port=8000)
104-
105-
106-
107-

0 commit comments

Comments
 (0)