1
+ import logging
2
+ from datetime import datetime
1
3
from fastapi import FastAPI , WebSocket , Request
2
4
from fastapi .responses import HTMLResponse , StreamingResponse
3
5
from fastapi .templating import Jinja2Templates
6
+ from fastapi .staticfiles import StaticFiles
4
7
import cv2
5
8
import pytesseract
6
9
import threading
7
10
import serial
8
11
import asyncio
12
+ import requests
13
+ import os
14
+ import face_recognition
9
15
10
16
app = FastAPI ()
11
17
templates = Jinja2Templates (directory = "templates" )
18
+ app .mount ("/static" , StaticFiles (directory = "static" ), name = "static" )
12
19
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
13
24
# All Cameras
14
25
cameras = [cv2 .VideoCapture (i ) for i in range (3 )]
15
26
ser = serial .Serial ('/dev/ttyUSB0' , 115200 ) # Arduino's serial port
22
33
}
23
34
24
35
# Pytesseract configuration
36
+ # Pytesseract config
25
37
pytesseract .pytesseract .tesseract_cmd = '/usr/bin/tesseract' # Path to Tesseract OCR executable
26
38
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
+
27
54
def gen_frames (cam_index ):
28
55
cam = cameras [cam_index ]
29
56
while True :
@@ -37,7 +64,7 @@ def gen_frames(cam_index):
37
64
frame = buffer .tobytes ()
38
65
yield (b'--frame\r \n '
39
66
b'Content-Type: image/jpeg\r \n \r \n ' + frame + b'\r \n ' )
40
-
67
+
41
68
async def garage_control ():
42
69
while True :
43
70
ret , frame = cameras [0 ].read ()
@@ -51,6 +78,34 @@ async def garage_control():
51
78
ser .write (b'OPEN_GARAGE\n ' )
52
79
print ("Garage opens for plate 'your_target_plate'" )
53
80
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 )
54
109
55
110
async def read_from_arduino ():
56
111
global result_message
@@ -59,8 +114,23 @@ async def read_from_arduino():
59
114
line = ser .readline ().decode ('utf-8' ).strip ()
60
115
if line .startswith ("RESULT:" ):
61
116
result_message = line .split ("RESULT:" )[1 ]
117
+ log_access ("User1" , result_message )
118
+ send_to_nodemcu (result_message )
62
119
await asyncio .sleep (0.1 )
63
120
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
+
64
134
@app .get ("/" , response_class = HTMLResponse )
65
135
async def index (request : Request ):
66
136
return templates .TemplateResponse ("index.html" , {"request" : request })
@@ -83,6 +153,11 @@ async def validate_password(user: str, password: str):
83
153
return {"message" : "Password Validated" }
84
154
return {"message" : "Invalid Password" }, 401
85
155
156
+ @app .post ("/open_garage" )
157
+ async def open_garage ():
158
+ ser .write (b'OPEN_GARAGE\n ' )
159
+ return {"message" : "Garaj Açıldı" }
160
+
86
161
@app .get ("/result" )
87
162
async def result ():
88
163
global result_message
@@ -98,10 +173,7 @@ async def websocket_endpoint(websocket: WebSocket):
98
173
99
174
if __name__ == "__main__" :
100
175
threading .Thread (target = asyncio .run , args = (garage_control (),)).start ()
176
+ threading .Thread (target = asyncio .run , args = (face_recognition_task (),)).start ()
101
177
threading .Thread (target = asyncio .run , args = (read_from_arduino (),)).start ()
102
178
import uvicorn
103
179
uvicorn .run (app , host = "0.0.0.0" , port = 8000 )
104
-
105
-
106
-
107
-
0 commit comments