-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathui_app.py
More file actions
762 lines (675 loc) · 27.5 KB
/
ui_app.py
File metadata and controls
762 lines (675 loc) · 27.5 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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
import os
import threading
import random
from time import time
import plyer
os.environ["OPENCV_VIDEOIO_MSMF_ENABLE_HW_TRANSFORMS"] = "0"
import sys
import cv2
import numpy as np
import mediapipe as mp
from PySide6.QtCore import QThread, Signal, Qt, QObject, QCoreApplication
from PySide6.QtGui import QImage, QPixmap, QFont, QFontDatabase
from PySide6.QtWidgets import (
QApplication,
QMainWindow,
QLabel,
QPushButton,
QVBoxLayout,
QHBoxLayout,
QWidget,
QListWidget,
QFrame,
QSpinBox,
QDialog,
QCheckBox,
QRadioButton,
QButtonGroup,
QScrollArea,
)
from helpers import extract_pose_data, analyze_posture
from workout_system.main import main as workout_main
from workout_system.session import run_interactive_stretch_session_qt
from user_preferences import (
is_first_run,
mark_first_run_complete,
get_timer_duration,
get_selected_goals,
HABIT_GOALS,
)
TIMER_DURATION = 30
# OpenCV to Qt ****************************************************************
def bgr_to_qimage(frame_bgr):
h, w, ch = frame_bgr.shape
rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)
return QImage(rgb.data, w, h, ch * w, QImage.Format_RGB888).copy()
# Calibration Worker (NO cv2.imshow) ******************************************
class CalibrationWorker(QThread):
frame_ready = Signal(QImage)
status = Signal(str)
done = Signal(list) # base_data list (length 99)
error = Signal(str)
def __init__(self, camera_backend, fps=30, seconds=5, camera_index=0):
super().__init__()
self.camera_backend = camera_backend
self.fps = fps
self.seconds = seconds
self.camera_index = camera_index
self._running = False
def stop(self):
self._running = False
def run(self):
cap = cv2.VideoCapture(self.camera_index, self.camera_backend)
cap.set(cv2.CAP_PROP_FPS, self.fps)
if not cap.isOpened():
self.error.emit("Calibration: could not open camera.")
return
mp_pose = mp.solutions.pose
pose = mp_pose.Pose()
frames_needed = max(1, int(self.seconds * self.fps))
collected = []
self._running = True
self.status.emit(f"Calibrating… sit upright ({self.seconds}s)")
frames_seen = 0
while self._running and frames_seen < frames_needed:
ret, frame = cap.read()
if not ret:
self.error.emit("Calibration: could not read frame.")
break
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
results = pose.process(frame_rgb)
# We only collect if landmarks exist
if results.pose_landmarks:
landmarks = extract_pose_data(results)
# landmarks.tolist() should be length 99
collected.append(landmarks.tolist())
# show preview inside Qt
self.frame_ready.emit(bgr_to_qimage(frame))
frames_seen += 1
# small throttle; rely on your fps cap too
self.msleep(int(1000 / max(1, self.fps)))
cap.release()
try:
pose.close()
except Exception:
pass
if not collected:
self.error.emit(
"Calibration failed: no pose detected. Try better lighting / full body in frame."
)
return
# Average across collected frames
base_data = np.mean(np.array(collected, dtype=float), axis=0).tolist()
self.status.emit("Calibration complete.")
self.done.emit(base_data)
# Posture Worker (NO cv2.imshow) *************************************************
class PostureWorker(QThread):
frame_ready = Signal(QImage)
issues_ready = Signal(list)
status = Signal(str)
error = Signal(str)
def __init__(self, base_data, camera_backend, main_window, fps=30, camera_index=0):
super().__init__()
self.base_data = base_data
self.camera_backend = camera_backend
self.fps = fps
self.camera_index = camera_index
self._running = False
# Use the shared notifier from main_window
self.notifier = main_window.notifier
def stop(self):
self._running = False
def run(self):
if self.base_data is None:
self.error.emit("Run: please calibrate first.")
return
cap = cv2.VideoCapture(self.camera_index, self.camera_backend)
cap.set(cv2.CAP_PROP_FPS, self.fps)
if not cap.isOpened():
self.error.emit("Run: could not open camera.")
return
mp_pose = mp.solutions.pose
mp_drawing = mp.solutions.drawing_utils
pose = mp_pose.Pose()
self._running = True
self.status.emit("Running posture monitor…")
while self._running:
ret, frame = cap.read()
if not ret:
self.error.emit("Run: could not read frame.")
break
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
results = pose.process(frame_rgb)
issues = []
if results.pose_landmarks:
mp_drawing.draw_landmarks(
frame, results.pose_landmarks, mp_pose.POSE_CONNECTIONS
)
landmarks = extract_pose_data(results)
issues = analyze_posture(self.base_data, landmarks.tolist())
# Keep your on-frame red text overlay
if issues:
y_offset = 30
for issue in issues:
cv2.putText(
frame,
f"{issue['type']}: {issue['severity']:.3f}",
(10, y_offset),
cv2.FONT_HERSHEY_SIMPLEX,
0.6,
(0, 0, 255),
2,
)
y_offset += 25
# Start/continue the timer when issues are detected
# Only if not currently working out
if not self.notifier.workingOut:
self.notifier.decrement_posture_timer()
else:
# Reset timer when no issues
if not self.notifier.workingOut:
self.notifier.reset_timer()
self.frame_ready.emit(bgr_to_qimage(frame))
self.issues_ready.emit(issues)
self.msleep(int(1000 / max(1, self.fps)))
cap.release()
try:
pose.close()
except Exception:
pass
self.status.emit("Stopped.")
# Workout Worker (runs in same window) *****************************
class WorkoutWorker(QThread):
frame_ready = Signal(QImage)
status = Signal(str)
finished = Signal()
error = Signal(str)
def __init__(
self, goal, session_time_seconds, camera_backend, fps=30, camera_index=0
):
super().__init__()
self.goal = goal
self.session_time_seconds = session_time_seconds
self.camera_backend = camera_backend
self.fps = fps
self.camera_index = camera_index
self._stop_requested = False
def request_stop(self):
self._stop_requested = True
def run(self):
def frame_callback(frame_bgr):
"""Callback to send frames to Qt"""
self.frame_ready.emit(bgr_to_qimage(frame_bgr))
# Small delay to respect FPS
self.msleep(int(1000 / max(1, self.fps)))
def should_stop_callback():
"""Callback to check if workout should stop"""
return self._stop_requested
try:
self.status.emit(f"Starting {self.goal} workout")
completed = run_interactive_stretch_session_qt(
self.goal,
self.session_time_seconds,
frame_callback,
should_stop_callback,
)
if completed:
self.status.emit("Workout complete! Great job!")
else:
self.status.emit("Workout stopped.")
self.finished.emit()
except Exception as e:
self.error.emit(f"Workout error: {str(e)}")
self.finished.emit()
class OnboardingDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
from user_preferences import load_preferences
prefs = load_preferences()
is_setup = not prefs.get("first_run", True)
if is_setup:
self.setWindowTitle("Preferences Settings")
else:
self.setWindowTitle("Welcome to Posture Monitor")
self.setGeometry(100, 100, 600, 700)
self.setModal(True)
self.selected_habits = []
self.selected_strictness = "medium"
layout = QVBoxLayout()
if is_setup:
title_text = "Adjust Your Preferences"
else:
title_text = "Let's Set Up Your Posture Monitor"
title = QLabel(title_text)
title_font = QFont()
title_font.setPointSize(16)
title_font.setBold(True)
title.setFont(title_font)
layout.addWidget(title)
habits_label = QLabel("What would you like to improve? (Select all that apply)")
habits_label_font = QFont()
habits_label_font.setPointSize(12)
habits_label_font.setBold(True)
habits_label.setFont(habits_label_font)
layout.addWidget(habits_label)
self.habit_checkboxes = {}
for habit in HABIT_GOALS.keys():
checkbox = QCheckBox(habit)
self.habit_checkboxes[habit] = checkbox
if habit in prefs.get("selected_habits", []):
checkbox.setChecked(True)
layout.addWidget(checkbox)
layout.addSpacing(20)
strictness_label = QLabel("How strict should monitoring be?")
strictness_label_font = QFont()
strictness_label_font.setPointSize(12)
strictness_label_font.setBold(True)
strictness_label.setFont(strictness_label_font)
layout.addWidget(strictness_label)
self.strictness_group = QButtonGroup()
self.strictness_radios = {}
strictness_options = [
("Strict (10s timer)", "strict"),
("Medium (30s timer) - Recommended", "medium"),
("Relaxed (60s timer)", "relaxed"),
]
current_strictness = prefs.get("strictness_level", "medium")
for label, value in strictness_options:
radio = QRadioButton(label)
if value == current_strictness:
radio.setChecked(True)
self.strictness_radios[value] = radio
self.strictness_group.addButton(radio)
layout.addWidget(radio)
layout.addSpacing(20)
button_layout = QHBoxLayout()
button_layout.addStretch()
start_btn = QPushButton("Start Monitoring")
start_btn.clicked.connect(self.on_start_clicked)
button_layout.addWidget(start_btn)
layout.addLayout(button_layout)
self.setLayout(layout)
self.setStyleSheet(
"""
QDialog { background: #FEECD0; }
QLabel { color: #1f2937; }
QCheckBox { color: #1f2937; }
QRadioButton { color: #1f2937; }
QPushButton { background: #1f2937; color: white; padding: 10px; border-radius: 8px; }
QPushButton:hover { background: #374151; }
"""
)
def on_start_clicked(self):
"""Save preferences and close dialog"""
self.selected_habits = [
habit
for habit, checkbox in self.habit_checkboxes.items()
if checkbox.isChecked()
]
if not self.selected_habits:
self.selected_habits = ["Back Pain"]
for value, radio in self.strictness_radios.items():
if radio.isChecked():
self.selected_strictness = value
break
mark_first_run_complete(self.selected_habits, self.selected_strictness)
self.accept()
# ---------- Main Window ----------
class MainWindow(QMainWindow):
def __init__(self, camera_backend, font_family):
super().__init__()
self.setWindowTitle("Posture Monitor")
self.resize(1200, 700)
self.camera_backend = camera_backend
self.base_data = None
self.font_family = font_family
self.calib_worker = None
self.posture_worker = None
self.workout_worker = None
# Create a shared notifier instance for all posture workers
self.notifier = Notification(self)
# Show onboarding if first run
if is_first_run():
self.show_onboarding()
# Video preview
self.video = QLabel("Click CALIBRATE to begin")
self.video.setAlignment(Qt.AlignCenter)
self.video.setMinimumSize(860, 560)
self.video.setObjectName("VideoPanel")
# Issues list
self.issues_list = QListWidget()
self.issues_list.setObjectName("IssuesList")
# Dynamic title for right panel
self.right_title = QLabel("Posture Issues")
self.right_title.setStyleSheet("font-size: 16px; font-weight: 600;")
# Status line
self.status_label = QLabel(
"Sit upright with a neutral spine, shoulders relaxed, facing the camera with your head and shoulders in view"
)
self.status_label.setObjectName("StatusLabel")
# Controls
self.calibrate_btn = QPushButton("Calibrate")
self.start_btn = QPushButton("Start")
self.stop_btn = QPushButton("Stop")
self.settings_btn = QPushButton("⚙ Settings")
self.start_btn.setEnabled(False)
self.stop_btn.setEnabled(False)
self.seconds_spin = QSpinBox()
self.seconds_spin.setRange(2, 15)
self.seconds_spin.setValue(5)
self.seconds_spin.setSuffix("s")
# Right panel
right_layout = QVBoxLayout()
right_layout.addWidget(self.right_title)
right_layout.addWidget(self.issues_list)
right_frame = QFrame()
right_frame.setObjectName("RightPanel")
right_frame.setLayout(right_layout)
# Top layout
top = QHBoxLayout()
top.addWidget(self.video, stretch=3)
top.addWidget(right_frame, stretch=1)
# Controls layout
controls = QHBoxLayout()
controls.addWidget(self.calibrate_btn)
label = QLabel("Calibration:")
label.setStyleSheet("color: #3e5374;")
controls.addWidget(label)
controls.addWidget(self.seconds_spin)
controls.addSpacing(12)
controls.addWidget(self.start_btn)
controls.addWidget(self.stop_btn)
controls.addSpacing(12)
controls.addWidget(self.settings_btn)
controls.addStretch()
root = QVBoxLayout()
root.addLayout(top)
root.addWidget(self.status_label)
root.addLayout(controls)
central = QWidget()
central.setLayout(root)
self.setCentralWidget(central)
# Styling
self.setStyleSheet(
f"""
* {{ font-family: "{self.font_family}"; }}
QMainWindow {{ background: #FEECD0; color: #506b95; font-family: "{self.font_family}"; font-size: 14px;}}
#VideoPanel {{ background: #CCD4B1; border-radius: 18px; font-size: 24px;}}
#RightPanel {{ background: #DCA278; border-radius: 18px; padding: 14px; margin-left: 16px; }}
#IssuesList {{ background: #0b1224; border: 1px solid #22304a; border-radius: 12px; padding: 8px; }}
#StatusLabel {{ padding: 12px 8px; color: #3e5374; font-size: 16px;}}
QPushButton {{ background: #3e5374; border: 1px solid #334155; padding: 10px 14px; border-radius: 12px; font-family: "{self.font_family}"; font-size: 16px;}}
QPushButton:hover {{ background: #506b95; font-family: "{self.font_family}"; }}
QPushButton:disabled {{ opacity: 0.5; font-family: "{self.font_family}"; }}
QSpinBox {{ background: #3e5374; border: 1px solid #22304a; border-radius: 6px; padding: 10px; }}
"""
)
# Wiring
self.calibrate_btn.clicked.connect(self.start_calibration)
self.start_btn.clicked.connect(self.start_posture)
self.stop_btn.clicked.connect(self.stop_current)
self.settings_btn.clicked.connect(self.show_settings)
def show_settings(self):
"""Show settings dialog to change preferences"""
dialog = OnboardingDialog(self)
dialog.exec()
def show_onboarding(self):
"""Show onboarding dialog for new users"""
dialog = OnboardingDialog(self)
dialog.exec()
# ----- UI slots -----
def on_frame(self, qimg):
pix = QPixmap.fromImage(qimg)
self.video.setPixmap(
pix.scaled(self.video.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)
)
def on_issues(self, issues):
self.issues_list.clear()
if not issues:
self.issues_list.addItem("No issues detected·")
return
for issue in issues:
item_str = f"{issue['severity']:.3f}"
item_str = item_str.split(".")
item_str = item_str[0] + "·" + item_str[1]
self.issues_list.addItem(f"{issue['type']} | severity: {item_str}")
def set_status(self, msg):
self.status_label.setText(msg)
def on_error(self, msg):
self.set_status(msg)
# ----- Calibration -----
def start_calibration(self):
# Stop posture run if active
self.stop_current()
# Avoid double-start
if self.calib_worker is not None:
return
self.calibrate_btn.setEnabled(False)
self.start_btn.setEnabled(False)
self.stop_btn.setEnabled(False)
self.issues_list.clear()
seconds = int(self.seconds_spin.value())
self.calib_worker = CalibrationWorker(
camera_backend=self.camera_backend, fps=30, seconds=seconds, camera_index=0
)
self.calib_worker.frame_ready.connect(self.on_frame)
self.calib_worker.status.connect(self.set_status)
self.calib_worker.error.connect(self.on_calib_error)
self.calib_worker.done.connect(self.on_calib_done)
self.calib_worker.start()
def on_calib_done(self, base_data):
self.base_data = base_data
self.calib_worker = None
self.set_status("Calibration complete· Press Start·")
self.calibrate_btn.setEnabled(True)
self.start_btn.setEnabled(True)
self.stop_btn.setEnabled(False)
def on_calib_error(self, msg):
self.calib_worker = None
self.set_status(msg)
self.calibrate_btn.setEnabled(True)
self.start_btn.setEnabled(self.base_data is not None)
self.stop_btn.setEnabled(False)
# ----- Posture run -----
def start_posture(self):
if self.base_data is None:
self.set_status("Please calibrate first.")
return
if self.posture_worker is not None:
return
self.right_title.setText("Posture Issues")
self.calibrate_btn.setEnabled(False)
self.start_btn.setEnabled(False)
self.stop_btn.setEnabled(True)
self.posture_worker = PostureWorker(
base_data=self.base_data,
camera_backend=self.camera_backend,
main_window=self,
fps=30,
camera_index=0,
)
self.posture_worker.frame_ready.connect(self.on_frame)
self.posture_worker.issues_ready.connect(self.on_issues)
self.posture_worker.status.connect(self.set_status)
self.posture_worker.error.connect(self.on_run_error)
self.posture_worker.finished.connect(self.on_run_finished)
self.posture_worker.start()
def stop_posture(self):
if self.posture_worker:
self.posture_worker.stop()
self.posture_worker.wait()
self.posture_worker = None
self.calibrate_btn.setEnabled(True)
self.start_btn.setEnabled(self.base_data is not None)
self.stop_btn.setEnabled(False)
def start_workout(self, goal):
"""Start a workout in the same window"""
print(f"[WORKOUT] start_workout called with goal: {goal}")
if self.workout_worker is not None:
print("[WORKOUT] Workout already running, ignoring request")
return
# Mark as working out and reset timer BEFORE stopping posture monitoring
# This prevents the timer from restarting
if hasattr(self, "notifier") and self.notifier:
self.notifier.workingOut = True
self.notifier.reset_timer()
# Stop posture monitoring
self.stop_posture()
# Update UI for workout mode
self.right_title.setText("Workout in Progress")
self.issues_list.clear()
self.issues_list.addItem("Performing workout...")
self.calibrate_btn.setEnabled(False)
self.start_btn.setEnabled(False)
self.stop_btn.setEnabled(True)
self.workout_worker = WorkoutWorker(
goal=goal,
session_time_seconds=60, # 1 minute workout
camera_backend=self.camera_backend,
fps=30,
camera_index=0,
)
self.workout_worker.frame_ready.connect(self.on_frame)
self.workout_worker.status.connect(self.set_status)
self.workout_worker.error.connect(self.on_workout_error)
self.workout_worker.finished.connect(self.on_workout_finished)
print("[WORKOUT] Starting workout worker...")
self.workout_worker.start()
def trigger_workout_from_notification(self):
"""Slot to trigger workout from notification thread"""
print("[WORKOUT] Triggering workout from notification...")
self.start_workout("Posture")
def stop_workout(self):
if self.workout_worker:
self.workout_worker.request_stop()
self.workout_worker.wait()
self.workout_worker = None
self.calibrate_btn.setEnabled(True)
self.start_btn.setEnabled(self.base_data is not None)
self.stop_btn.setEnabled(False)
def stop_current(self):
if self.posture_worker:
self.stop_posture()
elif self.workout_worker:
self.stop_workout()
def on_workout_error(self, msg):
self.set_status(msg)
self.stop_workout()
def on_workout_finished(self):
self.workout_worker = None
# Automatically resume posture monitoring
self.start_posture()
# Reset the shared notifier's working out flag so timer can work again
if self.notifier:
self.notifier.workingOut = False
self.notifier.reset_timer()
def on_run_error(self, msg):
self.set_status(msg)
self.stop_posture()
def on_run_finished(self):
self.posture_worker = None
self.calibrate_btn.setEnabled(True)
self.start_btn.setEnabled(self.base_data is not None)
self.stop_btn.setEnabled(False)
def closeEvent(self, event):
# stop threads on exit
if self.calib_worker:
self.calib_worker.stop()
self.calib_worker.wait()
self.calib_worker = None
if self.posture_worker:
self.posture_worker.stop()
self.posture_worker.wait()
self.posture_worker = None
if self.workout_worker:
self.workout_worker.request_stop()
self.workout_worker.wait()
self.workout_worker = None
event.accept()
class Notification(QObject):
start_workout_signal = Signal(str) # Signal to trigger workout
def __init__(self, main_window):
super().__init__()
self.posture_timer = {"start_time": None, "notification_sent": False}
self.main_window = main_window
self.workingOut = False
# Connect the signal to the main window's slot
self.start_workout_signal.connect(main_window.start_workout)
def decrement_posture_timer(self):
"""
Manages a configurable timer for bad posture notifications.
- Starts timer when issues are detected
- Resets timer when all issues are removed
- Sends notification when timer reaches configured duration
"""
# Don't notify if working out to prevent multiple notifications
if self.workingOut:
return
timer_duration = get_timer_duration()
# If timer hasn't started yet, start it
if self.posture_timer["start_time"] is None:
self.posture_timer["start_time"] = time()
self.posture_timer["notification_sent"] = False
print(f"[TIMER] Bad posture detected, timer started ({timer_duration}s)")
else:
# Check if configured time has elapsed
elapsed_time = time() - self.posture_timer["start_time"]
print(f"[TIMER] Elapsed time: {elapsed_time:.1f}s / {timer_duration}s")
if (
elapsed_time >= timer_duration
and not self.posture_timer["notification_sent"]
):
print(f"[TIMER] {timer_duration}s reached! Triggering workout...")
# Set workingOut immediately to prevent timer from restarting or resetting
self.workingOut = True
# Send notification in a separate thread to avoid blocking the camera
notification_thread = threading.Thread(
target=self.send_notification, daemon=True
)
notification_thread.start()
self.posture_timer["notification_sent"] = True
def reset_timer(self):
"""Reset the timer when good posture is detected."""
self.posture_timer["start_time"] = None
self.posture_timer["notification_sent"] = False
def send_notification(self):
"""Send notification in a separate thread to avoid blocking the main camera loop."""
print("[WORKOUT] Sending notification and starting workout...")
plyer.notification.notify(
title="Bad Posture Alert!",
message="You have been maintaining bad posture for too long. Please correct it. Shrimp",
)
# workingOut is already set to True in decrement_posture_timer()
# Get a random goal from the user's selected goals
goals = get_selected_goals()
selected_goal = random.choice(goals)
# Small delay to ensure notifications are processed
import time as time_module
time_module.sleep(0.1)
# Emit signal to trigger workout (safe across threads)
print(f"[WORKOUT] Emitting start_workout signal with goal: {selected_goal}...")
self.start_workout_signal.emit(selected_goal)
if __name__ == "__main__":
# Choose backend like your original main.py comments:
# Windows: cv2.CAP_DSHOW
# Mac: cv2.CAP_AVFOUNDATION
camera_backend = cv2.CAP_DSHOW
app = QApplication(sys.argv)
# FONTS --------------------------------------------------------------------------
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
font_path = os.path.join(
BASE_DIR, "assets", "fonts", "ethereal", "EtherealDemo-SemiBold.otf"
)
font_id = QFontDatabase.addApplicationFont(font_path)
if font_id == -1:
print("Failed to load font")
family = "Arial" # Fallback font
else:
families = QFontDatabase.applicationFontFamilies(font_id)
print("Loaded font families:", families)
family = families[0] # THIS is the real name Qt uses
app.setFont(QFont(family, 10))
# --------------------------------------------------------------------------------
win = MainWindow(camera_backend=camera_backend, font_family=family)
win.show()
sys.exit(app.exec())