1414from threading import Thread
1515import playsound
1616import queue
17+ from datetime import datetime
1718
1819
1920FACE_DOWNSAMPLE_RATIO = 1.5
4243GAMMA = 1.5
4344threadStatusQ = queue .Queue ()
4445
46+ # Phase 2: Session tracking variables (temporary until SessionManager is ready)
47+ current_ear = 0.0
48+ session_ear_values = []
49+ session_alerts = 0
50+ session_start_time = None
51+ session_active = False
52+
53+ # Temporary Session Tracker - will be replaced by real SessionManager
54+ class TempSessionTracker :
55+ def __init__ (self ):
56+ global session_start_time , session_active
57+ session_start_time = datetime .now ()
58+ session_active = True
59+ print (f"Session started at: { session_start_time } " )
60+
61+ def add_ear_value (self , ear_value ):
62+ global session_ear_values , current_ear
63+ current_ear = ear_value
64+ timestamp = datetime .now ()
65+ session_ear_values .append ({
66+ "value" : round (ear_value , 4 ),
67+ "timestamp" : timestamp .isoformat ()
68+ })
69+
70+ def add_alert (self ):
71+ global session_alerts
72+ session_alerts += 1
73+ timestamp = datetime .now ()
74+ print (f"Alert #{ session_alerts } triggered at: { timestamp } " )
75+
76+ def end_session (self ):
77+ global session_start_time , session_active
78+ if session_active :
79+ end_time = datetime .now ()
80+ duration = (end_time - session_start_time ).total_seconds () / 60
81+ avg_ear = sum (item ["value" ] for item in session_ear_values ) / len (session_ear_values ) if session_ear_values else 0
82+
83+ print (f"\n === Session Summary ===" )
84+ print (f"Duration: { duration :.2f} minutes" )
85+ print (f"Total EAR readings: { len (session_ear_values )} " )
86+ print (f"Average EAR: { avg_ear :.4f} " )
87+ print (f"Alerts triggered: { session_alerts } " )
88+ print (f"Total blinks: { blinkCount } " )
89+
90+ session_active = False
91+
92+ # Initialize session tracker
93+ session_tracker = None
94+
4595invGamma = 1.0 / GAMMA
4696table = np .array ([((i / 255.0 ) ** invGamma ) * 255 for i in range (0 , 256 )]).astype ("uint8" )
4797
@@ -76,6 +126,7 @@ def eye_aspect_ratio(eye):
76126
77127
78128def checkEyeStatus (landmarks ):
129+ global session_tracker , current_ear
79130 mask = np .zeros (frame .shape [:2 ], dtype = np .float32 )
80131
81132 hullLeftEye = []
@@ -95,6 +146,9 @@ def checkEyeStatus(landmarks):
95146 rightEAR = eye_aspect_ratio (hullRightEye )
96147
97148 ear = (leftEAR + rightEAR ) / 2.0
149+
150+ if session_tracker :
151+ session_tracker .add_ear_value (ear )
98152
99153 eyeStatus = 1 # 1 = Open, 0 = closed
100154 if (ear < thresh ):
@@ -103,7 +157,7 @@ def checkEyeStatus(landmarks):
103157 return eyeStatus
104158
105159def checkBlinkStatus (eyeStatus ):
106- global state , blinkCount , drowsy
160+ global state , blinkCount , drowsy , session_tracker
107161 if (state >= 0 and state <= falseBlinkLimit ):
108162 if (eyeStatus ):
109163 state = 0
@@ -125,9 +179,15 @@ def checkBlinkStatus(eyeStatus):
125179 state = 0
126180 drowsy = 3
127181 blinkCount += 1
182+ # Phase 2: Track alert when drowsiness is detected
183+ if session_tracker :
184+ session_tracker .add_alert ()
128185
129186 else :
130187 drowsy = 3
188+ # Phase 2: Track alert when drowsiness persists
189+ if session_tracker :
190+ session_tracker .add_alert ()
131191
132192def getLandmarks (im ):
133193 imSmall = cv2 .resize (im , None ,
@@ -148,6 +208,44 @@ def getLandmarks(im):
148208 [points .append ((p .x , p .y )) for p in predictor (im , newRect ).parts ()]
149209 return points
150210
211+ # Phase 2: Getter functions for external access (for session_history.py)
212+ def get_current_ear ():
213+ """Get the current EAR value"""
214+ return current_ear
215+
216+ def get_current_blink_count ():
217+ """Get the current blink count"""
218+ return blinkCount
219+
220+ def get_session_data ():
221+ """Get all current session data"""
222+ return {
223+ 'ear' : current_ear ,
224+ 'blink_count' : blinkCount ,
225+ 'alerts' : session_alerts ,
226+ 'drowsy_state' : drowsy ,
227+ 'eye_state' : state ,
228+ 'session_active' : session_active
229+ }
230+
231+ def get_session_ear_values ():
232+ """Get all EAR values collected in current session"""
233+ return session_ear_values
234+
235+ def start_new_session ():
236+ """Start a new tracking session"""
237+ global session_tracker
238+ if session_tracker :
239+ session_tracker .end_session ()
240+ session_tracker = TempSessionTracker ()
241+
242+ def end_current_session ():
243+ """End the current tracking session"""
244+ global session_tracker
245+ if session_tracker :
246+ session_tracker .end_session ()
247+ session_tracker = None
248+
151249capture = cv2 .VideoCapture (0 )
152250
153251for i in range (10 ):
@@ -201,6 +299,9 @@ def getLandmarks(im):
201299falseBlinkLimit = blinkTime / spf
202300print ("drowsy limit: {}, false blink limit: {}" .format (drowsyLimit , falseBlinkLimit ))
203301
302+ # Phase 2: Start session tracking
303+ session_tracker = TempSessionTracker ()
304+
204305if __name__ == "__main__" :
205306 vid_writer = cv2 .VideoWriter ('output-low-light-2.avi' ,cv2 .VideoWriter_fourcc ('M' ,'J' ,'P' ,'G' ), 15 , (frame .shape [1 ],frame .shape [0 ]))
206307 while (1 ):
@@ -269,6 +370,10 @@ def getLandmarks(im):
269370 except Exception as e :
270371 print (e )
271372
373+ # Phase 2: End session when detection stops
374+ if session_tracker :
375+ session_tracker .end_session ()
376+
272377 capture .release ()
273378 vid_writer .release ()
274379 cv2 .destroyAllWindows ()
0 commit comments