slouchbuddy 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- slouchbuddy/__init__.py +3 -0
- slouchbuddy/alert_tracker.py +46 -0
- slouchbuddy/app.py +227 -0
- slouchbuddy/buddy.py +164 -0
- slouchbuddy/buddy_brain.py +139 -0
- slouchbuddy/calibration.py +27 -0
- slouchbuddy/cli.py +87 -0
- slouchbuddy/config.py +63 -0
- slouchbuddy/dashboard.py +292 -0
- slouchbuddy/dashboard_art.py +39 -0
- slouchbuddy/dashboard_data.py +121 -0
- slouchbuddy/dashboard_theme.py +220 -0
- slouchbuddy/ipc.py +63 -0
- slouchbuddy/koala.py +187 -0
- slouchbuddy/launch_agent.py +122 -0
- slouchbuddy/launcher.py +33 -0
- slouchbuddy/menubar.py +155 -0
- slouchbuddy/notifications.py +99 -0
- slouchbuddy/pose_detection.py +96 -0
- slouchbuddy/posture_analyzer.py +126 -0
- slouchbuddy/session_logger.py +37 -0
- slouchbuddy/session_summary.py +80 -0
- slouchbuddy/ui_overlay.py +161 -0
- slouchbuddy/wake_reminder.py +26 -0
- slouchbuddy-0.1.0.dist-info/METADATA +185 -0
- slouchbuddy-0.1.0.dist-info/RECORD +30 -0
- slouchbuddy-0.1.0.dist-info/WHEEL +5 -0
- slouchbuddy-0.1.0.dist-info/entry_points.txt +2 -0
- slouchbuddy-0.1.0.dist-info/licenses/LICENSE +21 -0
- slouchbuddy-0.1.0.dist-info/top_level.txt +1 -0
slouchbuddy/__init__.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import time
|
|
2
|
+
|
|
3
|
+
from slouchbuddy import config
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class BadPostureTracker:
|
|
7
|
+
"""Tracks how long posture has been continuously bad and decides when to alert.
|
|
8
|
+
|
|
9
|
+
Pure logic with an injectable clock, so it can be unit-tested without a camera.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
def __init__(self, threshold_seconds=None, cooldown_seconds=None, clock=time.time):
|
|
13
|
+
self.threshold_seconds = (
|
|
14
|
+
config.BAD_POSTURE_THRESHOLD_SECONDS if threshold_seconds is None else threshold_seconds
|
|
15
|
+
)
|
|
16
|
+
self.cooldown_seconds = (
|
|
17
|
+
config.ALERT_COOLDOWN_SECONDS if cooldown_seconds is None else cooldown_seconds
|
|
18
|
+
)
|
|
19
|
+
self._clock = clock
|
|
20
|
+
self._bad_since = None
|
|
21
|
+
self._last_alert = None
|
|
22
|
+
|
|
23
|
+
def update(self, is_bad):
|
|
24
|
+
"""Record the latest frame. Returns (bad_duration_seconds, should_alert)."""
|
|
25
|
+
now = self._clock()
|
|
26
|
+
|
|
27
|
+
if not is_bad:
|
|
28
|
+
self._bad_since = None
|
|
29
|
+
return 0, False
|
|
30
|
+
|
|
31
|
+
if self._bad_since is None:
|
|
32
|
+
self._bad_since = now
|
|
33
|
+
duration = now - self._bad_since
|
|
34
|
+
|
|
35
|
+
if duration < self.threshold_seconds:
|
|
36
|
+
return duration, False
|
|
37
|
+
|
|
38
|
+
cooled_down = (
|
|
39
|
+
self._last_alert is None or now - self._last_alert >= self.cooldown_seconds
|
|
40
|
+
)
|
|
41
|
+
if cooled_down:
|
|
42
|
+
self._last_alert = now
|
|
43
|
+
return duration, cooled_down
|
|
44
|
+
|
|
45
|
+
def reset(self):
|
|
46
|
+
self._bad_since = None
|
slouchbuddy/app.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
"""Slouchbuddy: real-time webcam loop (one iteration per video frame).
|
|
2
|
+
|
|
3
|
+
slouchbuddy run # foreground: live window, Q quits
|
|
4
|
+
python -m slouchbuddy.app --background # hidden; controlled by the menu bar app
|
|
5
|
+
"""
|
|
6
|
+
import argparse
|
|
7
|
+
import os
|
|
8
|
+
import time
|
|
9
|
+
|
|
10
|
+
import cv2
|
|
11
|
+
import mediapipe as mp
|
|
12
|
+
|
|
13
|
+
from slouchbuddy import config
|
|
14
|
+
from slouchbuddy import ipc
|
|
15
|
+
from slouchbuddy import ui_overlay as ui
|
|
16
|
+
from slouchbuddy.alert_tracker import BadPostureTracker
|
|
17
|
+
from slouchbuddy.calibration import load_calibration, save_calibration
|
|
18
|
+
from slouchbuddy.notifications import alert_bad_posture
|
|
19
|
+
from slouchbuddy.pose_detection import PostureDetector
|
|
20
|
+
from slouchbuddy.posture_analyzer import analyze_posture
|
|
21
|
+
from slouchbuddy.session_logger import SessionLogger
|
|
22
|
+
|
|
23
|
+
mp_pose = mp.solutions.pose
|
|
24
|
+
mp_drawing = mp.solutions.drawing_utils
|
|
25
|
+
LANDMARK_SPEC = mp_drawing.DrawingSpec(color=(255, 255, 255), thickness=1, circle_radius=2)
|
|
26
|
+
CONNECTION_SPEC = mp_drawing.DrawingSpec(color=(160, 160, 160), thickness=1)
|
|
27
|
+
|
|
28
|
+
SHORTCUTS = [("C", "Calibrate"), ("B", "Break taken"), ("Q", "Quit")]
|
|
29
|
+
WINDOW_NAME = "Slouchbuddy"
|
|
30
|
+
CAMERA_RETRY_SECONDS = 3
|
|
31
|
+
HIDDEN_FRAME_DELAY = 0.05 # ~15 fps is plenty when nobody is looking at the window
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def open_camera():
|
|
35
|
+
# Set CAMERA_INDEX=1 (etc.) to pick a different camera, e.g. to avoid an iPhone.
|
|
36
|
+
return cv2.VideoCapture(int(os.environ.get("CAMERA_INDEX", 0)))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def main(background=False):
|
|
40
|
+
posture_detector = PostureDetector()
|
|
41
|
+
baseline_metrics = load_calibration() # None until the user calibrates
|
|
42
|
+
session_logger = SessionLogger()
|
|
43
|
+
tracker = BadPostureTracker()
|
|
44
|
+
last_break_time = time.time()
|
|
45
|
+
|
|
46
|
+
pose = mp_pose.Pose(
|
|
47
|
+
static_image_mode=False,
|
|
48
|
+
model_complexity=1,
|
|
49
|
+
enable_segmentation=False,
|
|
50
|
+
min_detection_confidence=0.5,
|
|
51
|
+
min_tracking_confidence=0.5,
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
cap = None
|
|
55
|
+
window_visible = not background
|
|
56
|
+
paused = False
|
|
57
|
+
calibrate_requested = False
|
|
58
|
+
last_status_write = 0
|
|
59
|
+
|
|
60
|
+
def publish(state, score=None, reasons=None, force=False):
|
|
61
|
+
nonlocal last_status_write
|
|
62
|
+
now = time.time()
|
|
63
|
+
if background and (force or now - last_status_write >= 1):
|
|
64
|
+
last_status_write = now
|
|
65
|
+
ipc.write_status(
|
|
66
|
+
{
|
|
67
|
+
"state": state,
|
|
68
|
+
"score": score,
|
|
69
|
+
"reasons": reasons,
|
|
70
|
+
"calibrated": baseline_metrics is not None,
|
|
71
|
+
"window_visible": window_visible,
|
|
72
|
+
"break_overdue": now - last_break_time >= config.BREAK_REMINDER_SECONDS,
|
|
73
|
+
}
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
def hide_window():
|
|
77
|
+
nonlocal window_visible
|
|
78
|
+
window_visible = False
|
|
79
|
+
cv2.destroyAllWindows()
|
|
80
|
+
cv2.waitKey(1) # let macOS actually close it
|
|
81
|
+
|
|
82
|
+
try:
|
|
83
|
+
while True:
|
|
84
|
+
quit_requested = False
|
|
85
|
+
if background:
|
|
86
|
+
for command in ipc.pop_commands():
|
|
87
|
+
if command == "quit":
|
|
88
|
+
quit_requested = True
|
|
89
|
+
elif command == "show":
|
|
90
|
+
window_visible = True
|
|
91
|
+
elif command == "hide":
|
|
92
|
+
hide_window()
|
|
93
|
+
elif command == "toggle":
|
|
94
|
+
if window_visible:
|
|
95
|
+
hide_window()
|
|
96
|
+
else:
|
|
97
|
+
window_visible = True
|
|
98
|
+
elif command == "calibrate":
|
|
99
|
+
calibrate_requested = True
|
|
100
|
+
elif command == "break":
|
|
101
|
+
last_break_time = time.time()
|
|
102
|
+
elif command == "pause":
|
|
103
|
+
paused = True
|
|
104
|
+
elif command == "resume":
|
|
105
|
+
paused = False
|
|
106
|
+
if quit_requested:
|
|
107
|
+
break
|
|
108
|
+
|
|
109
|
+
if paused:
|
|
110
|
+
# Release the camera entirely so the green light goes off.
|
|
111
|
+
if cap is not None:
|
|
112
|
+
cap.release()
|
|
113
|
+
cap = None
|
|
114
|
+
tracker.reset()
|
|
115
|
+
if window_visible:
|
|
116
|
+
hide_window()
|
|
117
|
+
publish("paused", force=True)
|
|
118
|
+
time.sleep(0.3)
|
|
119
|
+
continue
|
|
120
|
+
|
|
121
|
+
if cap is None:
|
|
122
|
+
cap = open_camera()
|
|
123
|
+
|
|
124
|
+
success, frame = cap.read()
|
|
125
|
+
if not success:
|
|
126
|
+
if not background:
|
|
127
|
+
print("Could not read from camera (check permissions / CAMERA_INDEX).")
|
|
128
|
+
break
|
|
129
|
+
cap.release()
|
|
130
|
+
cap = None
|
|
131
|
+
publish("camera_error", force=True)
|
|
132
|
+
time.sleep(CAMERA_RETRY_SECONDS)
|
|
133
|
+
continue
|
|
134
|
+
|
|
135
|
+
frame = cv2.flip(frame, 1) # mirror view
|
|
136
|
+
|
|
137
|
+
# OpenCV frames are BGR; MediaPipe expects RGB.
|
|
138
|
+
results = pose.process(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
|
|
139
|
+
|
|
140
|
+
current_metrics = None
|
|
141
|
+
if results.pose_landmarks:
|
|
142
|
+
posture_detector.update_landmarks(results.pose_landmarks)
|
|
143
|
+
current_metrics = posture_detector.get_current_metrics(mp_pose)
|
|
144
|
+
if window_visible:
|
|
145
|
+
mp_drawing.draw_landmarks(
|
|
146
|
+
frame,
|
|
147
|
+
results.pose_landmarks,
|
|
148
|
+
mp_pose.POSE_CONNECTIONS,
|
|
149
|
+
landmark_drawing_spec=LANDMARK_SPEC,
|
|
150
|
+
connection_drawing_spec=CONNECTION_SPEC,
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
if calibrate_requested and current_metrics:
|
|
154
|
+
baseline_metrics = current_metrics
|
|
155
|
+
save_calibration(baseline_metrics)
|
|
156
|
+
calibrate_requested = False
|
|
157
|
+
print("Calibration saved")
|
|
158
|
+
|
|
159
|
+
time_since_break = time.time() - last_break_time
|
|
160
|
+
minutes, seconds = divmod(int(time_since_break), 60)
|
|
161
|
+
break_overdue = time_since_break >= config.BREAK_REMINDER_SECONDS
|
|
162
|
+
|
|
163
|
+
if baseline_metrics is None:
|
|
164
|
+
publish("uncalibrated")
|
|
165
|
+
if window_visible:
|
|
166
|
+
ui.draw_calibration_prompt(frame)
|
|
167
|
+
elif current_metrics is None:
|
|
168
|
+
tracker.reset()
|
|
169
|
+
publish("no_pose")
|
|
170
|
+
if window_visible:
|
|
171
|
+
ui.draw_status_card(frame, None, None, pose_detected=False)
|
|
172
|
+
else:
|
|
173
|
+
analysis = analyze_posture(current_metrics, baseline_metrics)
|
|
174
|
+
|
|
175
|
+
reasons_text = None
|
|
176
|
+
if analysis.is_bad_posture:
|
|
177
|
+
reasons_text = (
|
|
178
|
+
analysis.status.removeprefix("BAD POSTURE: ").replace(" + ", ", ").title()
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
bad_duration, should_alert = tracker.update(analysis.is_bad_posture)
|
|
182
|
+
publish("bad" if analysis.is_bad_posture else "good", analysis.posture_score, reasons_text)
|
|
183
|
+
|
|
184
|
+
if window_visible:
|
|
185
|
+
ui.draw_status_card(frame, analysis.posture_score, reasons_text, pose_detected=True)
|
|
186
|
+
if bad_duration >= tracker.threshold_seconds:
|
|
187
|
+
ui.draw_alert_toast(frame)
|
|
188
|
+
if should_alert and not background:
|
|
189
|
+
# In the background the koala front end shows the message AND plays the chime
|
|
190
|
+
# together, so they stay in sync.
|
|
191
|
+
alert_bad_posture(analysis.status, analysis.posture_score)
|
|
192
|
+
|
|
193
|
+
session_logger.log(analysis.posture_score, analysis.status, bad_duration)
|
|
194
|
+
|
|
195
|
+
if not window_visible:
|
|
196
|
+
time.sleep(HIDDEN_FRAME_DELAY)
|
|
197
|
+
continue
|
|
198
|
+
|
|
199
|
+
ui.draw_break_timer(frame, break_overdue, minutes, seconds)
|
|
200
|
+
cv2.imshow(WINDOW_NAME, ui.compose_canvas(frame, SHORTCUTS))
|
|
201
|
+
key = cv2.waitKey(1) & 0xFF
|
|
202
|
+
|
|
203
|
+
closed = cv2.getWindowProperty(WINDOW_NAME, cv2.WND_PROP_VISIBLE) < 1
|
|
204
|
+
if key == ord("c") and current_metrics:
|
|
205
|
+
baseline_metrics = current_metrics
|
|
206
|
+
save_calibration(baseline_metrics)
|
|
207
|
+
print("Calibration saved:", baseline_metrics)
|
|
208
|
+
elif key == ord("b"):
|
|
209
|
+
last_break_time = time.time()
|
|
210
|
+
print("Break taken, timer reset")
|
|
211
|
+
elif key == ord("q") or closed:
|
|
212
|
+
if background:
|
|
213
|
+
hide_window() # keep monitoring; the menu bar can bring the window back
|
|
214
|
+
else:
|
|
215
|
+
break
|
|
216
|
+
finally:
|
|
217
|
+
if cap is not None:
|
|
218
|
+
cap.release()
|
|
219
|
+
pose.close()
|
|
220
|
+
session_logger.close()
|
|
221
|
+
cv2.destroyAllWindows()
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
if __name__ == "__main__":
|
|
225
|
+
parser = argparse.ArgumentParser(description="Slouchbuddy")
|
|
226
|
+
parser.add_argument("--background", action="store_true", help="run hidden, controlled via the menu bar app")
|
|
227
|
+
main(background=parser.parse_args().background)
|
slouchbuddy/buddy.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""The desk buddy: a koala that sits in the top-right corner of your screen and reacts to
|
|
2
|
+
your posture.
|
|
3
|
+
|
|
4
|
+
slouchbuddy buddy
|
|
5
|
+
|
|
6
|
+
Drag it anywhere; right-click for the menu. Needs the background monitor, which it
|
|
7
|
+
starts itself unless one is already running (e.g. from the macOS menu bar app).
|
|
8
|
+
"""
|
|
9
|
+
import argparse
|
|
10
|
+
import time
|
|
11
|
+
import tkinter as tk
|
|
12
|
+
import webbrowser
|
|
13
|
+
|
|
14
|
+
from PIL import Image, ImageTk
|
|
15
|
+
|
|
16
|
+
from slouchbuddy import buddy_brain as brain_mod
|
|
17
|
+
from slouchbuddy import ipc, koala, launcher
|
|
18
|
+
from slouchbuddy.buddy_brain import BuddyBrain
|
|
19
|
+
from slouchbuddy.notifications import play_alert_sound
|
|
20
|
+
|
|
21
|
+
KOALA_SIZE = 170
|
|
22
|
+
WIDTH = 230
|
|
23
|
+
KOALA_HEIGHT = KOALA_SIZE + 16 # card height with just the koala
|
|
24
|
+
BUBBLE_HEIGHT = 84
|
|
25
|
+
CARD = (253, 246, 236) # warm off-white card behind the koala
|
|
26
|
+
CARD_HEX = "#fdf6ec"
|
|
27
|
+
POLL_MS = 500
|
|
28
|
+
FRAME_MS = 110 # ~9 fps is smooth enough and keeps CPU use low
|
|
29
|
+
MESSAGE_SECONDS = 9
|
|
30
|
+
TOP_MARGIN = 34 # clear the macOS menu bar
|
|
31
|
+
RIGHT_MARGIN = 16
|
|
32
|
+
INK = "#353b44"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def window_position(screen_w, width=WIDTH):
|
|
36
|
+
"""Top-right corner of the screen."""
|
|
37
|
+
return screen_w - width - RIGHT_MARGIN, TOP_MARGIN
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class BuddyWindow:
|
|
41
|
+
def __init__(self, own_monitor):
|
|
42
|
+
self.root = tk.Tk()
|
|
43
|
+
self.root.title("Slouchbuddy")
|
|
44
|
+
self.root.overrideredirect(True)
|
|
45
|
+
self.root.attributes("-topmost", True)
|
|
46
|
+
|
|
47
|
+
x, y = window_position(self.root.winfo_screenwidth())
|
|
48
|
+
self.height = KOALA_HEIGHT
|
|
49
|
+
self.root.geometry(f"{WIDTH}x{self.height}+{x}+{y}")
|
|
50
|
+
self.root.config(bg=CARD_HEX)
|
|
51
|
+
|
|
52
|
+
# A solid card (no transparency tricks) so it renders the same on every OS.
|
|
53
|
+
self.canvas = tk.Canvas(self.root, width=WIDTH, height=BUBBLE_HEIGHT + KOALA_HEIGHT,
|
|
54
|
+
bg=CARD_HEX, highlightthickness=2, highlightbackground=INK)
|
|
55
|
+
self.canvas.pack(fill="both", expand=True)
|
|
56
|
+
|
|
57
|
+
self.brain = BuddyBrain()
|
|
58
|
+
self.mood = brain_mod.SLEEPING
|
|
59
|
+
self.message = None
|
|
60
|
+
self.message_until = 0
|
|
61
|
+
self.status = None
|
|
62
|
+
self.monitor = launcher.spawn_monitor() if own_monitor and ipc.read_status() is None else None
|
|
63
|
+
self.dashboard = None
|
|
64
|
+
self._photo = None
|
|
65
|
+
self._drag = (0, 0)
|
|
66
|
+
|
|
67
|
+
self.canvas.bind("<ButtonPress-1>", self._start_drag)
|
|
68
|
+
self.canvas.bind("<B1-Motion>", self._drag_move)
|
|
69
|
+
for right_click in ("<Button-2>", "<Button-3>", "<Control-Button-1>"):
|
|
70
|
+
self.canvas.bind(right_click, self._show_menu)
|
|
71
|
+
|
|
72
|
+
self.menu = tk.Menu(self.root, tearoff=0)
|
|
73
|
+
self.menu.add_command(label="Calibrate (sit upright first)", command=lambda: ipc.send_command("calibrate"))
|
|
74
|
+
self.menu.add_command(label="I took a break", command=lambda: ipc.send_command("break"))
|
|
75
|
+
self.pause_index = self.menu.index("end") + 1
|
|
76
|
+
self.menu.add_command(label="Pause monitoring", command=self._toggle_pause)
|
|
77
|
+
self.menu.add_command(label="Show / hide camera view", command=lambda: ipc.send_command("toggle"))
|
|
78
|
+
self.menu.add_separator()
|
|
79
|
+
self.menu.add_command(label="Open dashboard", command=self._open_dashboard)
|
|
80
|
+
self.menu.add_separator()
|
|
81
|
+
self.menu.add_command(label="Quit buddy", command=self.quit)
|
|
82
|
+
|
|
83
|
+
self.root.protocol("WM_DELETE_WINDOW", self.quit)
|
|
84
|
+
self._poll()
|
|
85
|
+
self._animate()
|
|
86
|
+
|
|
87
|
+
# --- window plumbing -------------------------------------------------
|
|
88
|
+
def _start_drag(self, event):
|
|
89
|
+
self._drag = (event.x_root - self.root.winfo_x(), event.y_root - self.root.winfo_y())
|
|
90
|
+
|
|
91
|
+
def _drag_move(self, event):
|
|
92
|
+
self.root.geometry(f"+{event.x_root - self._drag[0]}+{event.y_root - self._drag[1]}")
|
|
93
|
+
|
|
94
|
+
def _show_menu(self, event):
|
|
95
|
+
paused = bool(self.status and self.status.get("state") == "paused")
|
|
96
|
+
self.menu.entryconfig(self.pause_index, label="Resume monitoring" if paused else "Pause monitoring")
|
|
97
|
+
self.menu.tk_popup(event.x_root, event.y_root)
|
|
98
|
+
|
|
99
|
+
def _toggle_pause(self):
|
|
100
|
+
paused = bool(self.status and self.status.get("state") == "paused")
|
|
101
|
+
ipc.send_command("resume" if paused else "pause")
|
|
102
|
+
|
|
103
|
+
def _open_dashboard(self):
|
|
104
|
+
if self.dashboard is None or self.dashboard.poll() is not None:
|
|
105
|
+
self.dashboard = launcher.spawn_dashboard()
|
|
106
|
+
webbrowser.open(f"http://localhost:{launcher.DASHBOARD_PORT}")
|
|
107
|
+
|
|
108
|
+
def quit(self):
|
|
109
|
+
if self.monitor is not None and self.monitor.poll() is None:
|
|
110
|
+
ipc.send_command("quit")
|
|
111
|
+
try:
|
|
112
|
+
self.monitor.wait(timeout=3)
|
|
113
|
+
except Exception:
|
|
114
|
+
self.monitor.terminate()
|
|
115
|
+
if self.dashboard is not None and self.dashboard.poll() is None:
|
|
116
|
+
self.dashboard.terminate()
|
|
117
|
+
self.root.destroy()
|
|
118
|
+
|
|
119
|
+
# --- behaviour -------------------------------------------------------
|
|
120
|
+
def _poll(self):
|
|
121
|
+
self.status = ipc.read_status()
|
|
122
|
+
view = self.brain.update(self.status)
|
|
123
|
+
self.mood = view.mood
|
|
124
|
+
if view.message:
|
|
125
|
+
self.message = view.message
|
|
126
|
+
self.message_until = time.time() + MESSAGE_SECONDS
|
|
127
|
+
if view.alert:
|
|
128
|
+
play_alert_sound() # the bubble and the chime appear together
|
|
129
|
+
self.root.after(POLL_MS, self._poll)
|
|
130
|
+
|
|
131
|
+
def _animate(self):
|
|
132
|
+
self._draw(time.time())
|
|
133
|
+
self.root.after(FRAME_MS, self._animate)
|
|
134
|
+
|
|
135
|
+
# --- drawing ---------------------------------------------------------
|
|
136
|
+
def _draw(self, t):
|
|
137
|
+
img = koala.render(self.mood, t=t, size=KOALA_SIZE, supersample=2)
|
|
138
|
+
card = Image.new("RGB", img.size, CARD)
|
|
139
|
+
card.paste(img, mask=img.getchannel("A"))
|
|
140
|
+
self._photo = ImageTk.PhotoImage(card) # keep a reference or Tk garbage-collects it
|
|
141
|
+
|
|
142
|
+
showing = bool(self.message and time.time() < self.message_until)
|
|
143
|
+
wanted = KOALA_HEIGHT + (BUBBLE_HEIGHT if showing else 0)
|
|
144
|
+
if wanted != self.height: # grow/shrink the card downward so the koala stays put
|
|
145
|
+
self.height = wanted
|
|
146
|
+
self.root.geometry(f"{WIDTH}x{wanted}")
|
|
147
|
+
|
|
148
|
+
c = self.canvas
|
|
149
|
+
c.delete("all")
|
|
150
|
+
c.create_image(WIDTH // 2, 8, image=self._photo, anchor="n")
|
|
151
|
+
if showing:
|
|
152
|
+
c.create_text(WIDTH // 2, KOALA_HEIGHT + BUBBLE_HEIGHT // 2 - 4, text=self.message,
|
|
153
|
+
width=WIDTH - 36, fill=INK, font=("Helvetica", 12), justify="center")
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def main(argv=None):
|
|
157
|
+
parser = argparse.ArgumentParser(description="Slouchbuddy desk buddy")
|
|
158
|
+
parser.add_argument("--no-monitor", action="store_true", help="don't start the background monitor")
|
|
159
|
+
args = parser.parse_args(argv)
|
|
160
|
+
BuddyWindow(own_monitor=not args.no_monitor).root.mainloop()
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
if __name__ == "__main__":
|
|
164
|
+
main()
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""The buddy's personality: turns monitor status into a mood and the occasional comment.
|
|
2
|
+
|
|
3
|
+
Pure logic with an injectable clock (no GUI), so it is unit-tested without a display.
|
|
4
|
+
"""
|
|
5
|
+
import time
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Optional
|
|
8
|
+
|
|
9
|
+
# Moods the character can draw.
|
|
10
|
+
HAPPY, SLOUCHING, WORRIED, CURIOUS, SLEEPING, COFFEE = (
|
|
11
|
+
"happy", "slouching", "worried", "curious", "sleeping", "coffee",
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
# One hint per detected issue (checked in this order), matched against the reasons text.
|
|
15
|
+
ISSUE_HINTS = [
|
|
16
|
+
("level with shoulders", "Whoa, head up! Your head is down at shoulder level."),
|
|
17
|
+
("shoulders", "Shoulders are uneven. Level them out."),
|
|
18
|
+
("head forward", "Chin back, you're craning toward the screen."),
|
|
19
|
+
("screen distance", "A bit close to the screen. Lean back."),
|
|
20
|
+
("head tilt", "Your head is tilting. Straighten up."),
|
|
21
|
+
]
|
|
22
|
+
GENERIC_SLOUCH = "Posture check! Sit up tall."
|
|
23
|
+
|
|
24
|
+
MIN_BAD_SECONDS_BEFORE_COMMENT = 5
|
|
25
|
+
MIN_BAD_SECONDS_FOR_PRAISE = 10
|
|
26
|
+
SECONDS_BETWEEN_COMMENTS = 20
|
|
27
|
+
SLOUCH_REPEAT_SECONDS = 120 # re-nag at most this often while the slouch continues
|
|
28
|
+
GOOD_STREAK_MILESTONES_MIN = (15, 30, 60, 120)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class BuddyView:
|
|
33
|
+
mood: str
|
|
34
|
+
message: Optional[str] = None # a new comment to show now, else None
|
|
35
|
+
alert: bool = False # True when the comment is a real nudge (slouch, break): play the chime too
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class BuddyBrain:
|
|
39
|
+
def __init__(self, clock=time.time):
|
|
40
|
+
self._clock = clock
|
|
41
|
+
self._bad_since = None
|
|
42
|
+
self._good_since = None
|
|
43
|
+
self._last_comment = -1e9
|
|
44
|
+
self._last_slouch_comment = -1e9
|
|
45
|
+
self._milestones_said = set()
|
|
46
|
+
self._break_said = False
|
|
47
|
+
self._camera_said = False
|
|
48
|
+
self._uncalibrated_said = False
|
|
49
|
+
|
|
50
|
+
def _say(self, text, now, force=False):
|
|
51
|
+
if not force and now - self._last_comment < SECONDS_BETWEEN_COMMENTS:
|
|
52
|
+
return None
|
|
53
|
+
self._last_comment = now
|
|
54
|
+
return text
|
|
55
|
+
|
|
56
|
+
def update(self, status):
|
|
57
|
+
now = self._clock()
|
|
58
|
+
|
|
59
|
+
if status is None:
|
|
60
|
+
return BuddyView(SLEEPING)
|
|
61
|
+
|
|
62
|
+
state = status.get("state")
|
|
63
|
+
overdue = bool(status.get("break_overdue"))
|
|
64
|
+
|
|
65
|
+
if state == "paused":
|
|
66
|
+
self._reset_streaks()
|
|
67
|
+
return BuddyView(SLEEPING)
|
|
68
|
+
|
|
69
|
+
if state == "camera_error":
|
|
70
|
+
self._reset_streaks()
|
|
71
|
+
msg = None
|
|
72
|
+
if not self._camera_said:
|
|
73
|
+
self._camera_said = True
|
|
74
|
+
msg = self._say("I can't see you. Check the camera permission?", now, force=True)
|
|
75
|
+
return BuddyView(WORRIED, msg)
|
|
76
|
+
self._camera_said = False
|
|
77
|
+
|
|
78
|
+
if state == "uncalibrated":
|
|
79
|
+
msg = None
|
|
80
|
+
if not self._uncalibrated_said:
|
|
81
|
+
self._uncalibrated_said = True
|
|
82
|
+
msg = self._say("Sit up nice and tall, then choose Calibrate from my menu.", now, force=True)
|
|
83
|
+
return BuddyView(CURIOUS, msg)
|
|
84
|
+
|
|
85
|
+
if state == "no_pose":
|
|
86
|
+
self._reset_streaks()
|
|
87
|
+
return BuddyView(COFFEE if overdue else CURIOUS)
|
|
88
|
+
|
|
89
|
+
if overdue and not self._break_said:
|
|
90
|
+
self._break_said = True
|
|
91
|
+
msg = self._say("Time for a break! Stand up and stretch.", now, force=True)
|
|
92
|
+
return BuddyView(COFFEE, msg, alert=bool(msg))
|
|
93
|
+
if not overdue:
|
|
94
|
+
self._break_said = False
|
|
95
|
+
|
|
96
|
+
if state == "bad":
|
|
97
|
+
self._good_since = None
|
|
98
|
+
self._milestones_said.clear()
|
|
99
|
+
if self._bad_since is None:
|
|
100
|
+
self._bad_since = now
|
|
101
|
+
bad_for = now - self._bad_since
|
|
102
|
+
|
|
103
|
+
msg = None
|
|
104
|
+
if (
|
|
105
|
+
bad_for >= MIN_BAD_SECONDS_BEFORE_COMMENT
|
|
106
|
+
and now - self._last_slouch_comment >= SLOUCH_REPEAT_SECONDS
|
|
107
|
+
):
|
|
108
|
+
msg = self._say(self._slouch_message(status.get("reasons")), now)
|
|
109
|
+
if msg:
|
|
110
|
+
self._last_slouch_comment = now
|
|
111
|
+
return BuddyView(WORRIED if bad_for >= 30 else SLOUCHING, msg, alert=bool(msg))
|
|
112
|
+
|
|
113
|
+
# state == "good"
|
|
114
|
+
msg = None
|
|
115
|
+
if self._bad_since is not None:
|
|
116
|
+
if now - self._bad_since >= MIN_BAD_SECONDS_FOR_PRAISE:
|
|
117
|
+
msg = self._say("Nice, much better!", now, force=True)
|
|
118
|
+
self._bad_since = None
|
|
119
|
+
if self._good_since is None:
|
|
120
|
+
self._good_since = now
|
|
121
|
+
good_minutes = (now - self._good_since) / 60
|
|
122
|
+
for milestone in GOOD_STREAK_MILESTONES_MIN:
|
|
123
|
+
if good_minutes >= milestone and milestone not in self._milestones_said:
|
|
124
|
+
self._milestones_said.add(milestone)
|
|
125
|
+
msg = self._say(f"{milestone} minutes of great posture. Keep it up!", now) or msg
|
|
126
|
+
return BuddyView(COFFEE if overdue else HAPPY, msg)
|
|
127
|
+
|
|
128
|
+
def _reset_streaks(self):
|
|
129
|
+
self._bad_since = None
|
|
130
|
+
self._good_since = None
|
|
131
|
+
self._milestones_said.clear()
|
|
132
|
+
|
|
133
|
+
@staticmethod
|
|
134
|
+
def _slouch_message(reasons):
|
|
135
|
+
text = (reasons or "").lower()
|
|
136
|
+
for key, hint in ISSUE_HINTS:
|
|
137
|
+
if key in text:
|
|
138
|
+
return hint
|
|
139
|
+
return GENERIC_SLOUCH
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
|
|
4
|
+
from slouchbuddy import config
|
|
5
|
+
from slouchbuddy.config import CALIBRATION_FILE
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _resolve_path(path):
|
|
9
|
+
if os.path.isabs(path):
|
|
10
|
+
return path
|
|
11
|
+
return os.path.join(config.DATA_ROOT, path)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def save_calibration(metrics, path=CALIBRATION_FILE):
|
|
15
|
+
resolved = _resolve_path(path)
|
|
16
|
+
os.makedirs(os.path.dirname(resolved), exist_ok=True)
|
|
17
|
+
with open(resolved, "w") as f:
|
|
18
|
+
json.dump(metrics, f, indent=2)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def load_calibration(path=CALIBRATION_FILE):
|
|
22
|
+
resolved = _resolve_path(path)
|
|
23
|
+
if not os.path.exists(resolved):
|
|
24
|
+
return None
|
|
25
|
+
|
|
26
|
+
with open(resolved) as f:
|
|
27
|
+
return json.load(f)
|