-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
413 lines (309 loc) · 15.8 KB
/
main.py
File metadata and controls
413 lines (309 loc) · 15.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
#!/usr/bin/env python3
import tkinter as tk
from tkinter import ttk, messagebox
import cv2
import threading
import time
from deepface import DeepFace
import pandas as pd
from datetime import datetime, date
import os
import csv
from collections import Counter
try:
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib
matplotlib.use('TkAgg')
MATPLOTLIB_AVAILABLE = True
except ImportError:
MATPLOTLIB_AVAILABLE = False
class EmotionTrackerMain:
def __init__(self):
self.root = tk.Tk()
self.root.title("Emotion Tracker")
self.root.geometry("800x600")
self.is_recording = False
self.camera = None
self.frame_count = 0
self.processing_thread = None
self.data_dir = "data"
self.session_emotions = []
self._ensure_data_directory()
self.setup_ui()
def setup_ui(self):
self.notebook = ttk.Notebook(self.root)
self.notebook.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
self.setup_control_tab()
self.setup_monitor_tab()
self.setup_analytics_tab()
def _ensure_data_directory(self):
if not os.path.exists(self.data_dir):
os.makedirs(self.data_dir)
def setup_control_tab(self):
self.control_frame = ttk.Frame(self.notebook)
self.notebook.add(self.control_frame, text="Control")
title_label = ttk.Label(self.control_frame, text="Emotion Tracker Control", font=("Arial", 16, "bold"))
title_label.pack(pady=20)
self.status_frame = ttk.Frame(self.control_frame)
self.status_frame.pack(pady=20)
self.status_label = ttk.Label(self.status_frame, text="Status: Stopped", font=("Arial", 12))
self.status_label.pack()
self.frames_label = ttk.Label(self.status_frame, text="Frames Processed: 0", font=("Arial", 10))
self.frames_label.pack(pady=5)
button_frame = ttk.Frame(self.control_frame)
button_frame.pack(pady=30)
self.start_button = tk.Button(button_frame, text="START", command=self.start_recording,
bg="green", fg="white", font=("Arial", 12, "bold"),
padx=20, pady=10, relief="raised", bd=2)
self.start_button.pack(side=tk.LEFT, padx=10)
self.stop_button = tk.Button(button_frame, text="STOP", command=self.stop_recording,
bg="red", fg="white", font=("Arial", 12, "bold"),
padx=20, pady=10, relief="raised", bd=2)
self.stop_button.pack(side=tk.LEFT, padx=10)
self.stop_button.config(state=tk.DISABLED)
def setup_monitor_tab(self):
self.monitor_frame = ttk.Frame(self.notebook)
self.notebook.add(self.monitor_frame, text="Monitor")
main_frame = ttk.Frame(self.monitor_frame)
main_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
emotion_frame = ttk.Frame(main_frame)
emotion_frame.pack(fill=tk.X, pady=20)
self.emotion_label = ttk.Label(emotion_frame, text="None", font=("Arial", 48, "bold"))
self.emotion_label.pack()
self.confidence_label = ttk.Label(emotion_frame, text="Confidence: 0%", font=("Arial", 14))
self.confidence_label.pack(pady=10)
self.confidence_bar = ttk.Progressbar(emotion_frame, length=300, mode='determinate')
self.confidence_bar.pack(pady=10)
session_frame = ttk.LabelFrame(main_frame, text="Session Statistics", padding=10)
session_frame.pack(fill=tk.X, pady=20)
self.session_duration_label = ttk.Label(session_frame, text="Duration: 00:00:00", font=("Arial", 12))
self.session_duration_label.pack(anchor=tk.W)
self.total_detections_label = ttk.Label(session_frame, text="Total Detections: 0", font=("Arial", 12))
self.total_detections_label.pack(anchor=tk.W)
def setup_analytics_tab(self):
self.analytics_frame = ttk.Frame(self.notebook)
self.notebook.add(self.analytics_frame, text="Analytics")
main_frame = ttk.Frame(self.analytics_frame)
main_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
control_frame = ttk.Frame(main_frame)
control_frame.pack(fill=tk.X, pady=10)
ttk.Label(control_frame, text="Select Date:", font=("Arial", 12)).pack(side=tk.LEFT, padx=5)
self.date_var = tk.StringVar()
self.date_combo = ttk.Combobox(control_frame, textvariable=self.date_var, state="readonly", width=15)
self.date_combo.pack(side=tk.LEFT, padx=5)
self.date_combo.bind("<<ComboboxSelected>>", self.on_date_selected)
refresh_button = ttk.Button(control_frame, text="Refresh", command=self.load_analytics_data)
refresh_button.pack(side=tk.LEFT, padx=10)
stats_frame = ttk.LabelFrame(main_frame, text="Statistics", padding=10)
stats_frame.pack(fill=tk.X, pady=10)
self.stats_text = tk.Text(stats_frame, height=4, font=("Arial", 10))
self.stats_text.pack(fill=tk.X)
charts_frame = ttk.Frame(main_frame)
charts_frame.pack(fill=tk.BOTH, expand=True, pady=10)
left_chart_frame = ttk.LabelFrame(charts_frame, text="Emotion Distribution", padding=5)
left_chart_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(0, 5))
right_chart_frame = ttk.LabelFrame(charts_frame, text="Session Emotions", padding=5)
right_chart_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=(5, 0))
self.setup_pie_chart(left_chart_frame)
self.setup_session_chart(right_chart_frame)
self.load_analytics_data()
def start_recording(self):
try:
self.camera = cv2.VideoCapture(0)
if not self.camera.isOpened():
messagebox.showerror("Error", "Cannot access camera!")
return
self.camera.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
self.camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
self.is_recording = True
self.frame_count = 0
self.status_label.config(text="Status: Recording")
self.start_button.config(state=tk.DISABLED)
self.stop_button.config(state=tk.NORMAL)
self.processing_thread = threading.Thread(target=self.process_frames, daemon=True)
self.processing_thread.start()
except Exception as e:
messagebox.showerror("Error", f"Failed to start: {e}")
def stop_recording(self):
self.is_recording = False
if self.camera:
self.camera.release()
self.camera = None
if self.processing_thread:
self.processing_thread.join(timeout=2)
self.status_label.config(text="Status: Stopped")
self.start_button.config(state=tk.NORMAL)
self.stop_button.config(state=tk.DISABLED)
def process_frames(self):
frame_skip = 0
while self.is_recording:
try:
ret, frame = self.camera.read()
if not ret:
time.sleep(0.1)
continue
frame_skip += 1
if frame_skip % 3 == 0:
frame = cv2.resize(frame, (640, 480))
try:
result = DeepFace.analyze(frame, actions=['emotion'], enforce_detection=False, silent=True)
if isinstance(result, list):
result = result[0]
emotions = result.get('emotion', {})
if emotions:
dominant_emotion = max(emotions, key=emotions.get)
confidence = emotions[dominant_emotion] / 100.0
self.frame_count += 1
self.session_emotions.append(dominant_emotion)
self.save_emotion_data(dominant_emotion, confidence)
self.root.after(0, self.update_ui, dominant_emotion, confidence)
except Exception as e:
pass
time.sleep(0.1)
except Exception as e:
time.sleep(0.1)
def update_ui(self, emotion, confidence):
self.frames_label.config(text=f"Frames Processed: {self.frame_count}")
self.emotion_label.config(text=emotion.title())
self.confidence_label.config(text=f"Confidence: {confidence:.1%}")
self.confidence_bar['value'] = confidence * 100
self.total_detections_label.config(text=f"Total Detections: {self.frame_count}")
self.update_session_chart()
def save_emotion_data(self, emotion, confidence):
filename = os.path.join(self.data_dir, f"emotions_{date.today().strftime('%Y-%m-%d')}.csv")
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
try:
file_exists = os.path.exists(filename)
with open(filename, 'a', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile)
if not file_exists:
writer.writerow(["timestamp", "emotion", "confidence"])
writer.writerow([timestamp, emotion, confidence])
except Exception:
pass
def load_analytics_data(self):
available_dates = self.get_available_dates()
if available_dates:
date_strings = [d.strftime('%Y-%m-%d') for d in available_dates]
self.date_combo['values'] = date_strings
self.date_combo.set(date_strings[0])
self.selected_date = available_dates[0]
else:
self.date_combo['values'] = [date.today().strftime('%Y-%m-%d')]
self.date_combo.set(date.today().strftime('%Y-%m-%d'))
self.selected_date = date.today()
self.update_analytics()
def on_date_selected(self, event):
selected_date_str = self.date_var.get()
self.selected_date = datetime.strptime(selected_date_str, '%Y-%m-%d').date()
self.update_analytics()
def get_available_dates(self):
dates = []
try:
for filename in os.listdir(self.data_dir):
if filename.startswith('emotions_') and filename.endswith('.csv'):
date_str = filename.replace('emotions_', '').replace('.csv', '')
try:
parsed_date = datetime.strptime(date_str, '%Y-%m-%d').date()
dates.append(parsed_date)
except ValueError:
continue
except Exception:
pass
return sorted(dates, reverse=True)
def update_analytics(self):
stats = self.get_emotion_statistics()
self.update_stats_display(stats)
self.update_pie_chart(stats)
def get_emotion_statistics(self):
filename = os.path.join(self.data_dir, f"emotions_{self.selected_date.strftime('%Y-%m-%d')}.csv")
try:
if os.path.exists(filename):
df = pd.read_csv(filename)
emotion_counts = df['emotion'].value_counts().to_dict()
dominant_emotion = df['emotion'].mode().iloc[0] if not df['emotion'].mode().empty else 'None'
avg_confidence = df['confidence'].mean()
return {
'total_records': len(df),
'dominant_emotion': dominant_emotion,
'avg_confidence': avg_confidence,
'emotion_counts': emotion_counts
}
except Exception:
pass
return {
'total_records': 0,
'dominant_emotion': 'None',
'avg_confidence': 0.0,
'emotion_counts': {}
}
def update_stats_display(self, stats):
self.stats_text.delete(1.0, tk.END)
stats_text = f"""Total Records: {stats['total_records']}
Dominant Emotion: {stats['dominant_emotion']}
Average Confidence: {stats['avg_confidence']:.2%}
Date: {self.selected_date.strftime('%Y-%m-%d')}"""
self.stats_text.insert(1.0, stats_text)
def setup_pie_chart(self, parent):
if MATPLOTLIB_AVAILABLE:
self.pie_fig, self.pie_ax = plt.subplots(figsize=(4, 3))
self.pie_canvas = FigureCanvasTkAgg(self.pie_fig, parent)
self.pie_canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
else:
self.pie_text = tk.Text(parent, height=10, font=("Arial", 10))
self.pie_text.pack(fill=tk.BOTH, expand=True)
def setup_session_chart(self, parent):
self.session_text = tk.Text(parent, height=10, font=("Arial", 10))
self.session_text.pack(fill=tk.BOTH, expand=True)
def update_pie_chart(self, stats):
if MATPLOTLIB_AVAILABLE:
self.pie_ax.clear()
if not stats['emotion_counts']:
self.pie_ax.text(0.5, 0.5, 'No data available', ha='center', va='center', transform=self.pie_ax.transAxes)
self.pie_canvas.draw()
return
emotions = list(stats['emotion_counts'].keys())
counts = list(stats['emotion_counts'].values())
colors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99', '#ff99cc', '#c2c2f0', '#ffb3e6']
wedges, texts, autotexts = self.pie_ax.pie(counts, labels=emotions, autopct='%1.1f%%',
colors=colors[:len(emotions)], startangle=90)
self.pie_ax.set_title('Emotion Distribution')
self.pie_canvas.draw()
else:
self.pie_text.delete(1.0, tk.END)
if not stats['emotion_counts']:
self.pie_text.insert(1.0, "No data available")
return
total = stats['total_records']
text = "Emotion Distribution:\n\n"
for emotion, count in stats['emotion_counts'].items():
percentage = (count / total) * 100
text += f"{emotion.title()}: {count} ({percentage:.1f}%)\n"
self.pie_text.insert(1.0, text)
def update_session_chart(self):
self.session_text.delete(1.0, tk.END)
if not self.session_emotions:
self.session_text.insert(1.0, "No session data yet")
return
emotion_counts = Counter(self.session_emotions)
total = len(self.session_emotions)
text = "Current Session:\n\n"
for emotion, count in emotion_counts.most_common():
percentage = (count / total) * 100
text += f"{emotion.title()}: {count} ({percentage:.1f}%)\n"
self.session_text.insert(1.0, text)
def run(self):
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
self.root.mainloop()
def on_closing(self):
if self.is_recording:
self.stop_recording()
self.root.quit()
self.root.destroy()
def main():
print("Starting Emotion Tracker...")
app = EmotionTrackerMain()
app.run()
if __name__ == "__main__":
main()