Repository navigation
Expand file tree
/
Copy pathpose_battle.py
More file actions
1632 lines (1460 loc) · 65.7 KB
/
Copy pathpose_battle.py
File metadata and controls
1632 lines (1460 loc) · 65.7 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
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Pose Battle - KNI / URz Open Day game.
Raspberry Pi 5 + Hailo-10H + IMX708 + monitor 1920x1080.
GStreamer/TAPPAS pipeline -> appsink -> PyGame fullscreen state-machine UI.
"""
import sys
import os
import time
import json
import math
import threading
import unicodedata
from pathlib import Path
from datetime import datetime
from collections import deque, defaultdict
import numpy as np
HAILO_APPS = Path("/home/norek/hailo_tappas/hailo-apps")
sys.path.insert(0, str(HAILO_APPS))
import gi
gi.require_version('Gst', '1.0')
from gi.repository import Gst
import hailo
from hailo_apps.python.core.common.core import (
get_pipeline_parser, get_resource_path,
handle_list_models_flag, resolve_hef_path,
)
from hailo_apps.python.core.common.defines import (
POSE_ESTIMATION_PIPELINE, POSE_ESTIMATION_POSTPROCESS_FUNCTION,
POSE_ESTIMATION_POSTPROCESS_SO_FILENAME, RESOURCES_SO_DIR_NAME,
)
from hailo_apps.python.core.gstreamer.gstreamer_app import GStreamerApp, app_callback_class
from hailo_apps.python.core.gstreamer.gstreamer_helper_pipelines import (
INFERENCE_PIPELINE, INFERENCE_PIPELINE_WRAPPER,
QUEUE, SOURCE_PIPELINE,
TRACKER_PIPELINE, USER_CALLBACK_PIPELINE,
)
import setproctitle
# ── Paths / Config ────────────────────────────────────────────────
PROJECT_DIR = Path(__file__).resolve().parent
POSES_DIR = PROJECT_DIR / "poses"
SESSIONS_DIR = PROJECT_DIR / "sessions"
LEADERBOARD_PATH = PROJECT_DIR / "leaderboard.json"
SUMMARY_CSV = PROJECT_DIR / "summary.csv"
CAM_W, CAM_H = 1280, 720
SCREEN_W, SCREEN_H = 1920, 1080
# Display layout
CAM_X, CAM_Y = 0, 0 # camera top-left
SIDE_X, SIDE_Y = CAM_W, 0 # side panel (640x720)
SIDE_W, SIDE_H = SCREEN_W - CAM_W, CAM_H # 640x720
BOTTOM_Y = CAM_H # bottom panel
BOTTOM_H = SCREEN_H - CAM_H # 360
PANEL_W = SCREEN_W // 3 # 640 per player panel
# Detection / scoring config
DET_THRESHOLD = 0.40
KP_CONF_THRESHOLD = 0.30
MIN_VISIBLE_JOINTS = 4
# ── Player count ──────────────────────────────────────────────────
# MAX_PLAYERS = liczba stref (lane'ów) — zostaw 3, ekran jest podzielony na 3.
# MIN_PLAYERS = ile osób musi być w lane'ach żeby gra wystartowała.
# 2 = tryb testowy (gra rusza już z 2 osobami, 3-cia może dołączyć w okresie
# grace; jeśli nie dołączy w T_CALIB_GRACE sekund, gra startuje bez niej).
# 3 = tryb eventowy (wszystkie 3 strefy muszą być stabilnie zajęte).
MIN_PLAYERS = 2
MAX_PLAYERS = 3
# Timings (seconds)
T_INTRO = 2.0
T_MEMORIZE = 2.5
T_POSE_WINDOW = 3.0
T_REVEAL = 2.5
T_SUMMARY = 8.0
T_STABLE_CALIB = 0.8 # how long someone has to stand still in their lane
T_CALIB_GRACE = 2.5 # extra window for a late-joining player when MIN<MAX
# Sync bonus window (ms)
SYNC_WINDOW_MS = 300
def grade_from_accuracy(accuracy):
"""Map a [0,1] accuracy value to an integer grade in 0-10, no halves.
Half-up rounding (0.85 -> 9, not 8 as Python's banker's round() would do)."""
if accuracy is None:
return 0
g = math.floor(accuracy * 10 + 0.5)
return max(0, min(10, int(g)))
def grade_color(g):
"""Color for a 0-10 grade (red -> green -> gold)."""
if g <= 3:
return (250, 80, 80) # red
if g <= 5:
return (250, 150, 60) # orange
if g <= 7:
return (250, 210, 60) # yellow
if g <= 9:
return (60, 220, 130) # green
return (255, 200, 70) # gold for 10/10
# COCO keypoint indices
NOSE, L_EYE, R_EYE, L_EAR, R_EAR = 0, 1, 2, 3, 4
L_SHOULDER, R_SHOULDER = 5, 6
L_ELBOW, R_ELBOW = 7, 8
L_WRIST, R_WRIST = 9, 10
L_HIP, R_HIP = 11, 12
L_KNEE, R_KNEE = 13, 14
L_ANKLE, R_ANKLE = 15, 16
SKELETON_PAIRS = [
(L_SHOULDER, R_SHOULDER), (L_HIP, R_HIP),
(L_SHOULDER, L_HIP), (R_SHOULDER, R_HIP),
(L_SHOULDER, L_ELBOW), (L_ELBOW, L_WRIST),
(R_SHOULDER, R_ELBOW), (R_ELBOW, R_WRIST),
(L_HIP, L_KNEE), (L_KNEE, L_ANKLE),
(R_HIP, R_KNEE), (R_KNEE, R_ANKLE),
(L_SHOULDER, NOSE), (R_SHOULDER, NOSE),
]
KEYPOINT_NAMES = {
"nose": 0, "left_eye": 1, "right_eye": 2, "left_ear": 3, "right_ear": 4,
"left_shoulder": 5, "right_shoulder": 6,
"left_elbow": 7, "right_elbow": 8,
"left_wrist": 9, "right_wrist": 10,
"left_hip": 11, "right_hip": 12,
"left_knee": 13, "right_knee": 14,
"left_ankle": 15, "right_ankle": 16,
}
# Which joints to consider when colouring a "non-target" skeleton (idle / calibration)
DEFAULT_JOINT_COLOR = (140, 200, 255)
# ── Shared state ──────────────────────────────────────────────────
class SharedState:
"""Updated from GStreamer callback, read by PyGame thread."""
def __init__(self):
self.frame_lock = threading.Lock()
self.det_lock = threading.Lock()
self.latest_frame = None # np.uint8 RGB (H,W,3)
self.latest_detections = [] # list of dicts: bbox(xyxy norm), kp ndarray(17,3) norm, track_id
self.fps = 0.0
self.detection_ts = 0.0
state = SharedState()
# ── Math: angles, scoring ─────────────────────────────────────────
def joint_angle(p_a, p_b, p_c):
"""Angle at vertex B in degrees, given three keypoints (x,y) tuples.
Returns None if any vector has zero length."""
ax, ay = p_a
bx, by = p_b
cx, cy = p_c
v1 = (ax - bx, ay - by)
v2 = (cx - bx, cy - by)
n1 = math.hypot(*v1)
n2 = math.hypot(*v2)
if n1 < 1e-6 or n2 < 1e-6:
return None
dot = (v1[0] * v2[0] + v1[1] * v2[1]) / (n1 * n2)
dot = max(-1.0, min(1.0, dot))
return math.degrees(math.acos(dot))
def score_pose(kp_xyc, target):
"""
Compute (player_score, per_joint).
kp_xyc: (17,3) array of (x_norm, y_norm, conf) - coords in [0,1] of image.
target: TargetPose
Returns:
player_score in [0,1]
per_joint: list of dicts {name, target, achieved, score, visible}
"""
per_joint = []
visible = 0
weighted_sum = 0.0
weight_total = 0.0
for j in target.joints:
i_a, i_b, i_c = j["points"]
ca = kp_xyc[i_a][2]
cb = kp_xyc[i_b][2]
cc = kp_xyc[i_c][2]
if min(ca, cb, cc) < KP_CONF_THRESHOLD:
per_joint.append({"name": j["name"], "target": j["target_angle"],
"achieved": None, "score": 0.0, "visible": False,
"weight": j["weight"]})
continue
ang = joint_angle(kp_xyc[i_a][:2], kp_xyc[i_b][:2], kp_xyc[i_c][:2])
if ang is None:
per_joint.append({"name": j["name"], "target": j["target_angle"],
"achieved": None, "score": 0.0, "visible": False,
"weight": j["weight"]})
continue
diff = abs(ang - j["target_angle"])
s = max(0.0, 1.0 - diff / target.tolerance)
per_joint.append({"name": j["name"], "target": j["target_angle"],
"achieved": ang, "score": s, "visible": True,
"weight": j["weight"]})
visible += 1
weighted_sum += s * j["weight"]
weight_total += j["weight"]
if visible < MIN_VISIBLE_JOINTS or weight_total <= 0:
return 0.0, per_joint
return weighted_sum / weight_total, per_joint
# ── Target poses ──────────────────────────────────────────────────
COCO_LR_PAIRS = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10),
(11, 12), (13, 14), (15, 16)]
class TargetPose:
def __init__(self, data):
self.name = data["name"]
self.difficulty = data.get("difficulty", "easy")
self.tolerance = float(data.get("tolerance_deg", 25.0))
self.multiplier = float(data.get("multiplier", 1.0))
# mirror: flip only the rendered reference (visual), keep scoring on
# original anatomical sides. The player sees the pose as in a mirror
# and intuitively raises the matching limb; the camera (which is not
# flipped) then reads the physically-correct anatomical side.
self.mirror_display = bool(data.get("mirror", False))
self.joints = data["joints"] # list of {name, points:[a,b,c], target_angle, weight}
# Optional: reference keypoint positions for rendering target skeleton.
# Stored as 17 [x,y] in [0,1].
ref = data.get("reference_keypoints")
if ref is not None:
arr = np.array(ref, dtype=np.float32)
if self.mirror_display:
arr = arr.copy()
arr[:, 0] = 1.0 - arr[:, 0]
for a, b in COCO_LR_PAIRS:
arr[[a, b]] = arr[[b, a]]
self.reference_kp = arr
else:
self.reference_kp = None
self.raw = data
@staticmethod
def load_all(folder):
files = sorted(folder.glob("*.json"))
poses = []
for f in files:
with open(f, "r", encoding="utf-8") as fh:
poses.append(TargetPose(json.load(fh)))
return poses
# ── Leaderboard ───────────────────────────────────────────────────
class Leaderboard:
def __init__(self, path):
self.path = path
self.entries = [] # list of {team, score, ts}
self.load()
def load(self):
if self.path.exists():
try:
self.entries = json.loads(self.path.read_text(encoding="utf-8"))
except Exception:
self.entries = []
else:
self.entries = []
def save(self):
self.path.write_text(
json.dumps(self.entries, ensure_ascii=False, indent=2),
encoding="utf-8",
)
def add(self, team, score, grade=None):
entry = {
"team": team,
"score": float(score),
"grade": int(grade) if grade is not None else None,
"ts": datetime.now().isoformat(timespec="seconds"),
}
self.entries.append(entry)
self.entries.sort(key=lambda e: e["score"], reverse=True)
self.save()
rank = next((i for i, e in enumerate(self.entries) if e is entry), 0) + 1
return rank
def top(self, n=10):
return self.entries[:n]
# ── Session logger ────────────────────────────────────────────────
def slug(s):
s = unicodedata.normalize("NFKD", s)
s = "".join(c for c in s if not unicodedata.combining(c))
out = "".join(c if c.isalnum() else "_" for c in s).strip("_")
return out or "team"
class SessionLogger:
def __init__(self, session_id, team_name):
self.session_id = session_id
self.team_name = team_name
self.path = SESSIONS_DIR / f"{session_id}_{slug(team_name)}.csv"
self._fh = open(self.path, "w", encoding="utf-8")
self._fh.write(
"session_id,team,timestamp,round_idx,pose,difficulty,multiplier,"
"player_idx,player_score,joint,target_angle,achieved_angle,joint_score,visible,weight\n"
)
def write_round(self, round_idx, pose, per_player):
"""per_player: list of {score, per_joint:[...]}"""
ts = datetime.now().isoformat(timespec="seconds")
for p_idx, p in enumerate(per_player):
for j in p["per_joint"]:
ach = "" if j["achieved"] is None else f"{j['achieved']:.2f}"
self._fh.write(
f"{self.session_id},{csv_safe(self.team_name)},{ts},{round_idx},"
f"{csv_safe(pose.name)},{pose.difficulty},{pose.multiplier:.2f},"
f"{p_idx},{p['score']:.4f},{csv_safe(j['name'])},"
f"{j['target']:.2f},{ach},"
f"{j['score']:.4f},{int(j['visible'])},{j['weight']:.2f}\n"
)
self._fh.flush()
def close(self):
try:
self._fh.close()
except Exception:
pass
def csv_safe(s):
s = str(s).replace('"', "'")
if "," in s or "\n" in s:
return '"' + s + '"'
return s
def append_summary(session_id, team, total, ranks, grade=None):
write_header = not SUMMARY_CSV.exists()
with open(SUMMARY_CSV, "a", encoding="utf-8") as fh:
if write_header:
fh.write("session_id,team,timestamp,total_score,grade,rank\n")
fh.write(
f"{session_id},{csv_safe(team)},"
f"{datetime.now().isoformat(timespec='seconds')},"
f"{total:.2f},{'' if grade is None else int(grade)},{ranks}\n"
)
# ── Hailo GStreamer pipeline ──────────────────────────────────────
class PoseBattleApp(GStreamerApp):
"""GStreamer pose pipeline whose appsink gives us the raw RGB frame.
We do NOT use the Hailo overlay -- we draw the skeleton ourselves
so we can colour joints by match-quality."""
def __init__(self, app_callback, user_data, parser=None):
if parser is None:
parser = get_pipeline_parser()
handle_list_models_flag(parser, POSE_ESTIMATION_PIPELINE)
super().__init__(parser, user_data)
if self.batch_size == 1:
self.batch_size = 2
self.hef_path = resolve_hef_path(
self.hef_path, app_name=POSE_ESTIMATION_PIPELINE, arch=self.arch
)
self.app_callback = app_callback
self.post_process_so = get_resource_path(
POSE_ESTIMATION_PIPELINE, RESOURCES_SO_DIR_NAME, self.arch,
POSE_ESTIMATION_POSTPROCESS_SO_FILENAME,
)
self.post_process_function = POSE_ESTIMATION_POSTPROCESS_FUNCTION
self.video_sink = 'appsink name=pb_sink emit-signals=true max-buffers=2 drop=true'
setproctitle.setproctitle("Pose Battle")
self.create_pipeline()
sink = self.pipeline.get_by_name("pb_sink")
if sink:
sink.connect("new-sample", self._on_new_sample)
def _on_new_sample(self, sink):
sample = sink.emit("pull-sample")
if not sample:
return Gst.FlowReturn.OK
buf = sample.get_buffer()
caps = sample.get_caps()
s = caps.get_structure(0)
w, h, fmt = s.get_value("width"), s.get_value("height"), s.get_value("format")
ok, mi = buf.map(Gst.MapFlags.READ)
if not ok:
return Gst.FlowReturn.OK
try:
ch = 4 if "RGBA" in fmt.upper() else 3
arr = np.ndarray((h, w, ch), dtype=np.uint8, buffer=mi.data).copy()
if ch == 4:
arr = arr[:, :, :3]
with state.frame_lock:
state.latest_frame = arr
finally:
buf.unmap(mi)
return Gst.FlowReturn.OK
def get_pipeline_string(self):
source = SOURCE_PIPELINE(
video_source=self.video_source, video_width=self.video_width,
video_height=self.video_height, frame_rate=self.frame_rate, sync=self.sync,
)
infer = INFERENCE_PIPELINE(
hef_path=self.hef_path, post_process_so=self.post_process_so,
post_function_name=self.post_process_function, batch_size=self.batch_size,
)
return (
f"{source} ! "
f"{INFERENCE_PIPELINE_WRAPPER(infer)} ! "
f"{TRACKER_PIPELINE(class_id=0)} ! "
f"{USER_CALLBACK_PIPELINE()} ! "
f"{QUEUE(name='sink_q')} ! "
f"videoconvert n-threads=2 qos=false ! "
f"video/x-raw,format=RGB ! "
f"{self.video_sink}"
)
# ── Pose callback (extract detections every frame) ────────────────
_fc = 0
_ft = time.time()
_fps = 0.0
_last_log = 0.0
def pose_callback(element, buffer, user_data):
global _fc, _ft, _fps, _last_log
user_data.increment()
_fc += 1
now = time.time()
if now - _ft >= 1.0:
_fps = _fc / (now - _ft)
_fc = 0
_ft = now
roi = hailo.get_roi_from_buffer(buffer)
dets = roi.get_objects_typed(hailo.HAILO_DETECTION)
out = []
for d in dets:
if d.get_confidence() < DET_THRESHOLD:
continue
lm = d.get_objects_typed(hailo.HAILO_LANDMARKS)
if not lm:
continue
bbox = d.get_bbox()
bx, by, bw, bh = bbox.xmin(), bbox.ymin(), bbox.width(), bbox.height()
pts = lm[0].get_points()
kp = np.zeros((17, 3), dtype=np.float32)
for i, p in enumerate(pts[:17]):
# Coords come back in [0,1] of bbox; convert to [0,1] of image.
kp[i, 0] = p.x() * bw + bx
kp[i, 1] = p.y() * bh + by
kp[i, 2] = p.confidence()
tid = 0
tracks = d.get_objects_typed(hailo.HAILO_UNIQUE_ID)
if tracks:
tid = tracks[0].get_id()
out.append({
"bbox": (bx, by, bx + bw, by + bh),
"kp": kp,
"track_id": tid,
"conf": d.get_confidence(),
})
with state.det_lock:
state.latest_detections = out
state.detection_ts = now
state.fps = _fps
if now - _last_log >= 10.0:
# Heartbeat so a stuck pipeline is obvious in the terminal.
print(f"[pose-battle] inference {_fps:5.1f} FPS / "
f"{len(out)} detections", flush=True)
_last_log = now
return Gst.PadProbeReturn.OK
# ── Lane assignment ───────────────────────────────────────────────
def lane_of_detection(det):
"""Return lane index 0/1/2 by mid-hip x, or -1 if no hip visible."""
kp = det["kp"]
if kp[L_HIP][2] >= KP_CONF_THRESHOLD and kp[R_HIP][2] >= KP_CONF_THRESHOLD:
x = (kp[L_HIP][0] + kp[R_HIP][0]) / 2.0
elif kp[L_HIP][2] >= KP_CONF_THRESHOLD:
x = kp[L_HIP][0]
elif kp[R_HIP][2] >= KP_CONF_THRESHOLD:
x = kp[R_HIP][0]
else:
# Fallback: bbox center
x = (det["bbox"][0] + det["bbox"][2]) / 2.0
if x < 1.0 / 3:
return 0
if x < 2.0 / 3:
return 1
return 2
def assign_lanes(detections):
"""Return list [lane0_det_or_None, lane1, lane2].
If multiple detections in a lane, pick the largest bbox.
If none, that slot is None."""
by_lane = defaultdict(list)
for d in detections:
lane = lane_of_detection(d)
if lane >= 0:
by_lane[lane].append(d)
result = [None, None, None]
for lane in range(3):
if by_lane[lane]:
# Pick largest bbox (most likely the player, ignore background people)
def area(d):
x1, y1, x2, y2 = d["bbox"]
return max(0.0, x2 - x1) * max(0.0, y2 - y1)
result[lane] = max(by_lane[lane], key=area)
return result
# ── Round result data structure ──────────────────────────────────
class RoundResult:
def __init__(self):
self.scores = [0.0, 0.0, 0.0]
self.per_joint = [[], [], []]
self.cross80_ts = [None, None, None] # ms timestamps of first 0.8 crossing
self.team_avg = 0.0
self.cohesion = 1.0
self.base_score = 0.0
self.round_score = 0.0
self.perfect_bonus = 0
self.sync_bonus = 0
self.streak_bonus = 0
self.round_total = 0.0
self.grade = 0 # 0-10 integer grade for this round
# ═══════════════════════════════════════════════════════════════════
# PyGame UI / state machine
# ═══════════════════════════════════════════════════════════════════
import pygame # noqa: E402
# Colors
BG = (8, 8, 14)
PANEL_BG = (14, 14, 22)
PANEL2_BG = (20, 20, 32)
CYAN = (0, 229, 255)
PINK = (255, 61, 113)
WHITE = (240, 240, 248)
DIM = (120, 120, 140)
DIMMER = (60, 60, 75)
GREEN = (60, 220, 130)
YELLOW = (250, 210, 60)
RED = (250, 80, 80)
GRAY = (110, 110, 120)
ACCENT = (0, 180, 220)
GOLD = (255, 200, 70)
PLAYER_COLORS = [(255, 110, 110), (110, 255, 170), (110, 180, 255)]
PLAYER_NAMES = ["Gracz 1", "Gracz 2", "Gracz 3"]
def color_for_joint_score(score, visible):
if not visible:
return GRAY
if score >= 0.80:
return GREEN
if score >= 0.50:
return YELLOW
return RED
def lerp(a, b, t):
return a + (b - a) * t
class Game:
"""The entire game state machine + rendering."""
STATE_IDLE = "idle"
STATE_TEAM_NAME = "team_name"
STATE_CALIBRATION = "calibration"
STATE_ROUND_INTRO = "round_intro"
STATE_MEMORIZE = "memorize"
STATE_POSE_WINDOW = "pose_window"
STATE_REVEAL = "reveal"
STATE_SUMMARY = "summary"
def __init__(self, screen, fonts, poses, leaderboard):
self.screen = screen
self.fonts = fonts
self.poses = list(poses)
self.lb = leaderboard
self.state = self.STATE_IDLE
self.state_t0 = time.time()
self.team_name = ""
self.round_idx = 0
self.round_results = [] # list of RoundResult
self.session_logger = None
self.session_id = None
self.session_total = 0.0
self.session_rank = None
self.session_grade = 0
self.streak = 0
# Calibration
self.calib_stable_since = [None] * MAX_PLAYERS # per-lane
self.calib_min_reached_at = None # when MIN_PLAYERS first stable
# Which lanes are "in" for this session. Set when calibration finishes.
self.active_players = [False] * MAX_PLAYERS
# Pose window state
self.pw_player_max = [0.0] * MAX_PLAYERS
self.pw_player_max_joints = [None] * MAX_PLAYERS
self.pw_cross80 = [None] * MAX_PLAYERS
# Misc
self.show_skeleton_in_idle = True
# Cache: pre-rendered camera surface and last_frame_id
self._cam_surface = None
self._cam_surface_lock = threading.Lock()
self._cam_thread = threading.Thread(target=self._cam_worker, daemon=True)
self._cam_thread_run = True
self._cam_thread.start()
# ── camera surface worker (converts numpy → pygame.Surface off the main thread)
def _cam_worker(self):
last_id = 0
while self._cam_thread_run:
with state.frame_lock:
frame = state.latest_frame
if frame is not None and id(frame) != last_id:
last_id = id(frame)
# surfarray expects (W, H, 3)
surf = pygame.surfarray.make_surface(np.transpose(frame, (1, 0, 2)))
with self._cam_surface_lock:
self._cam_surface = surf
time.sleep(0.01) # ~100Hz max
def stop(self):
self._cam_thread_run = False
# ── state transitions ─────────────────────────────────────
def set_state(self, st):
self.state = st
self.state_t0 = time.time()
def state_elapsed(self):
return time.time() - self.state_t0
def start_session(self):
self.session_id = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
self.team_name = ""
self.round_idx = 0
self.round_results = []
self.streak = 0
self.session_total = 0.0
self.session_rank = None
self.set_state(self.STATE_TEAM_NAME)
pygame.key.start_text_input()
def begin_calibration(self):
pygame.key.stop_text_input()
self.session_logger = SessionLogger(self.session_id, self.team_name)
self.calib_stable_since = [None] * MAX_PLAYERS
self.calib_min_reached_at = None
self.active_players = [False] * MAX_PLAYERS
self.set_state(self.STATE_CALIBRATION)
def begin_round(self, idx):
self.round_idx = idx
self.pw_player_max = [0.0] * MAX_PLAYERS
self.pw_player_max_joints = [None] * MAX_PLAYERS
self.pw_cross80 = [None] * MAX_PLAYERS
self.set_state(self.STATE_ROUND_INTRO)
def finish_round(self):
pose = self.poses[self.round_idx]
result = RoundResult()
result.scores = list(self.pw_player_max)
result.per_joint = list(self.pw_player_max_joints)
result.cross80_ts = list(self.pw_cross80)
# Patch missing per-joint
for i in range(3):
if result.per_joint[i] is None:
result.per_joint[i] = [
{"name": j["name"], "target": j["target_angle"], "achieved": None,
"score": 0.0, "visible": False, "weight": j["weight"]}
for j in pose.joints
]
# Team average
result.team_avg = sum(result.scores) / 3.0
# Cohesion: 1.0..1.3
spread = max(result.scores) - min(result.scores)
result.cohesion = round(1.0 + 0.3 * max(0.0, 1.0 - spread), 4)
result.base_score = result.team_avg * result.cohesion * 100.0
result.round_score = result.base_score * pose.multiplier
# Perfect bonus
if result.team_avg >= 0.95:
result.perfect_bonus = 30
# Sync bonus
ts = [t for t in result.cross80_ts if t is not None]
if len(ts) == 3 and (max(ts) - min(ts)) <= SYNC_WINDOW_MS / 1000.0:
result.sync_bonus = 15
# Streak bonus
if result.team_avg >= 0.80:
self.streak += 1
result.streak_bonus = 10 * self.streak
else:
self.streak = 0
result.round_total = (result.round_score + result.perfect_bonus
+ result.sync_bonus + result.streak_bonus)
result.grade = grade_from_accuracy(result.team_avg)
self.round_results.append(result)
per_player = [{"score": result.scores[i], "per_joint": result.per_joint[i]}
for i in range(3)]
try:
self.session_logger.write_round(self.round_idx + 1, pose, per_player)
except Exception as e:
print("[pose-battle] session logger error:", e)
self.set_state(self.STATE_REVEAL)
def finish_session(self):
self.session_total = sum(r.round_total for r in self.round_results)
# Session grade = average per-round accuracy mapped to 0..10.
if self.round_results:
avg_acc = sum(r.team_avg for r in self.round_results) / len(self.round_results)
else:
avg_acc = 0.0
self.session_grade = grade_from_accuracy(avg_acc)
self.session_rank = self.lb.add(self.team_name, self.session_total,
grade=self.session_grade)
try:
self.session_logger.close()
except Exception:
pass
append_summary(self.session_id, self.team_name, self.session_total,
self.session_rank, self.session_grade)
self.set_state(self.STATE_SUMMARY)
def abort_session(self):
if self.session_logger:
try:
self.session_logger.close()
except Exception:
pass
try:
# Remove file -- aborted session, don't pollute data.
self.session_logger.path.unlink(missing_ok=True)
except Exception:
pass
self.session_logger = None
pygame.key.stop_text_input()
self.set_state(self.STATE_IDLE)
# ── per-frame update (game logic) ─────────────────────────
def update(self):
with state.det_lock:
detections = list(state.latest_detections)
lanes = assign_lanes(detections)
self.last_lanes = lanes # for drawing
if self.state == self.STATE_CALIBRATION:
now = time.time()
for i in range(MAX_PLAYERS):
if lanes[i] is None:
self.calib_stable_since[i] = None
elif self.calib_stable_since[i] is None:
self.calib_stable_since[i] = now
stable_now = [t is not None and (now - t) >= T_STABLE_CALIB
for t in self.calib_stable_since]
n_stable = sum(stable_now)
if n_stable >= MAX_PLAYERS:
# All lanes filled - go immediately.
self.active_players = list(stable_now)
self.begin_round(0)
elif n_stable >= MIN_PLAYERS:
# Enough players - wait a brief grace window for a 3rd to join.
if self.calib_min_reached_at is None:
self.calib_min_reached_at = now
elif (now - self.calib_min_reached_at) >= T_CALIB_GRACE:
self.active_players = list(stable_now)
self.begin_round(0)
else:
self.calib_min_reached_at = None
elif self.state == self.STATE_ROUND_INTRO:
if self.state_elapsed() >= T_INTRO:
self.set_state(self.STATE_MEMORIZE)
elif self.state == self.STATE_MEMORIZE:
if self.state_elapsed() >= T_MEMORIZE:
self.set_state(self.STATE_POSE_WINDOW)
elif self.state == self.STATE_POSE_WINDOW:
pose = self.poses[self.round_idx]
now = time.time()
for i in range(3):
if lanes[i] is None:
continue
s, pj = score_pose(lanes[i]["kp"], pose)
if s > self.pw_player_max[i]:
self.pw_player_max[i] = s
self.pw_player_max_joints[i] = pj
if s >= 0.80 and self.pw_cross80[i] is None:
self.pw_cross80[i] = now
if self.state_elapsed() >= T_POSE_WINDOW:
self.finish_round()
elif self.state == self.STATE_REVEAL:
if self.state_elapsed() >= T_REVEAL:
if self.round_idx + 1 >= len(self.poses):
self.finish_session()
else:
self.begin_round(self.round_idx + 1)
elif self.state == self.STATE_SUMMARY:
if self.state_elapsed() >= T_SUMMARY:
self.set_state(self.STATE_IDLE)
# ── input handling ─────────────────────────────────────────
def handle_event(self, ev):
if ev.type == pygame.QUIT:
return "quit"
if ev.type == pygame.KEYDOWN:
if ev.key in (pygame.K_q, pygame.K_ESCAPE):
if self.state == self.STATE_IDLE:
return "quit"
else:
self.abort_session()
return None
if self.state == self.STATE_IDLE:
if ev.key == pygame.K_SPACE:
self.start_session()
if ev.key == pygame.K_e:
self._export_summary_to_clipboard()
if ev.key == pygame.K_f:
pygame.display.toggle_fullscreen()
elif self.state == self.STATE_TEAM_NAME:
if ev.key == pygame.K_RETURN and self.team_name.strip():
self.team_name = self.team_name.strip()[:24]
self.begin_calibration()
elif ev.key == pygame.K_BACKSPACE:
self.team_name = self.team_name[:-1]
if ev.type == pygame.TEXTINPUT and self.state == self.STATE_TEAM_NAME:
if len(self.team_name) < 24:
self.team_name += ev.text
return None
def _export_summary_to_clipboard(self):
# Print the summary file path; in fullscreen mode we don't actually
# have a clipboard, just log.
print(f"[pose-battle] summary CSV: {SUMMARY_CSV}")
# ── drawing ────────────────────────────────────────────────
def draw(self):
self.screen.fill(BG)
self._draw_camera_area()
# State-specific overlays
if self.state == self.STATE_IDLE:
self._draw_idle()
elif self.state == self.STATE_TEAM_NAME:
self._draw_team_name()
elif self.state == self.STATE_CALIBRATION:
self._draw_calibration()
elif self.state == self.STATE_ROUND_INTRO:
self._draw_round_intro()
elif self.state == self.STATE_MEMORIZE:
self._draw_memorize()
elif self.state == self.STATE_POSE_WINDOW:
self._draw_pose_window()
elif self.state == self.STATE_REVEAL:
self._draw_reveal()
elif self.state == self.STATE_SUMMARY:
self._draw_summary()
# Header overlay - FPS, hint
self._draw_header()
# ── camera area + skeletons ────────────────────────────────
def _draw_camera_area(self):
with self._cam_surface_lock:
cam_surf = self._cam_surface
if cam_surf is not None:
self.screen.blit(cam_surf, (CAM_X, CAM_Y))
else:
self.screen.fill((0, 0, 0), pygame.Rect(CAM_X, CAM_Y, CAM_W, CAM_H))
txt = self.fonts["body"].render("Czekam na obraz z kamery...", True, DIM)
self.screen.blit(txt, (CAM_X + 20, CAM_Y + CAM_H // 2))
# Lane dividers (vertical lines)
if self.state in (self.STATE_CALIBRATION, self.STATE_ROUND_INTRO,
self.STATE_MEMORIZE, self.STATE_POSE_WINDOW,
self.STATE_REVEAL):
for i in range(1, 3):
x = CAM_X + int(CAM_W * i / 3)
pygame.draw.line(self.screen, (60, 60, 90),
(x, CAM_Y), (x, CAM_Y + CAM_H), 1)
# Draw skeletons for everyone visible
with state.det_lock:
dets = list(state.latest_detections)
lanes = assign_lanes(dets)
target_pose = None
if self.state == self.STATE_POSE_WINDOW:
target_pose = self.poses[self.round_idx]
for lane_idx, det in enumerate(lanes):
if det is None:
continue
self._draw_skeleton(det, lane_idx, target_pose)
def _draw_skeleton(self, det, lane_idx, target_pose):
kp = det["kp"]
# Compute joint -> color mapping if we have a target pose
joint_colors = {}
if target_pose is not None:
s, per_joint = score_pose(kp, target_pose)
for j in per_joint:
# j["points"] holds the apex index; we colour the apex joint
pass
# Map by joint apex index
target_joints_by_idx = {jt["points"][1]: jt for jt in target_pose.joints}
for idx, jt in target_joints_by_idx.items():
pj = next((x for x in per_joint if x["name"] == jt["name"]), None)
if pj is None:
joint_colors[idx] = GRAY
continue
joint_colors[idx] = color_for_joint_score(pj["score"], pj["visible"])
# Default colour for non-target joints
base_color = PLAYER_COLORS[lane_idx]
def to_screen(i):
x = CAM_X + kp[i, 0] * CAM_W
y = CAM_Y + kp[i, 1] * CAM_H
return int(x), int(y)
# Limbs
for a, b in SKELETON_PAIRS:
if kp[a, 2] < KP_CONF_THRESHOLD or kp[b, 2] < KP_CONF_THRESHOLD:
continue
pa, pb = to_screen(a), to_screen(b)
# Color: if either endpoint is a target joint with a color, use that
col = base_color
if target_pose is not None:
if a in joint_colors:
col = joint_colors[a]
elif b in joint_colors:
col = joint_colors[b]
pygame.draw.line(self.screen, col, pa, pb, 4)
# Keypoints
for i in range(17):
if kp[i, 2] < KP_CONF_THRESHOLD:
continue
p = to_screen(i)
col = joint_colors.get(i, base_color)
pygame.draw.circle(self.screen, col, p, 6)
pygame.draw.circle(self.screen, WHITE, p, 6, 1)
# ── header strip ──────────────────────────────────────────
def _draw_header(self):
# Top-right FPS + small title
fps = state.fps
txt = self.fonts["small"].render(f"{fps:5.1f} FPS", True, DIM)
self.screen.blit(txt, (SCREEN_W - txt.get_width() - 10, 6))
if self.state == self.STATE_IDLE:
t = self.fonts["small"].render(
"SPACJA - start | E - eksport CSV | F - pełny ekran | ESC - wyjście",
True, DIM)
self.screen.blit(t, (10, SCREEN_H - 26))
# ── state-specific draws ──────────────────────────────────
def _draw_idle(self):
# Side panel - title + start hint
self._draw_side_panel_idle()
# Bottom panel - leaderboard
self._draw_leaderboard_panel()
def _draw_side_panel_idle(self):
pygame.draw.rect(self.screen, PANEL_BG, (SIDE_X, SIDE_Y, SIDE_W, SIDE_H))
pygame.draw.line(self.screen, DIMMER, (SIDE_X, SIDE_Y),
(SIDE_X, SIDE_Y + SIDE_H), 2)