-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
771 lines (654 loc) · 32.1 KB
/
main.py
File metadata and controls
771 lines (654 loc) · 32.1 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
"""Sadball - Football shooting analyzer."""
import os
import sys
import cv2
import numpy as np
import threading
from collections import deque
from datetime import datetime
from dotenv import load_dotenv
from ultralytics import YOLO
from capture.camera import CameraCapture
from tracking.pose_tracker import PoseTracker
from tracking.ball_tracker import BallTracker
from tracking.person_detector import PersonDetector
from logic.shot_detector import ShotDetector
from logic.shot_logger import ShotLogger
from logic.temporal_buffers import PoseTrackingBuffer
from logic.contact_finder import ContactFrameFinder
from logic.kicking_analyzer import KickingPatternAnalyzer
from logic.pose_landmarks import get_foot_anchor
from analysis.form_analyzer import FormAnalyzer
from analysis.phase_segmenter import ShotPhaseSegmenter
from analysis.temporal_analyzer import TemporalFormAnalyzer
from feedback.llm_client import AITechniqueCoach
from logic.notes_manager import ShotNotesManager
class ShootingSession:
"""Training session with shot detection, detailed analysis, and feedback."""
def __init__(
self,
player_level: str = "intermediate",
detailed_logs: bool = False,
ai_feedback: bool = False,
ai_provider: str = "auto",
no_ui: bool = False,
model_path: str = "./models/best.pt",
camera_id: int = 0
):
self.player_level = player_level
self.detailed_logs = detailed_logs
self.ai_feedback_enabled = ai_feedback
self.ai_provider = ai_provider
self.no_ui = no_ui
if not os.path.exists(model_path):
print(f"\nError: YOLO model file not found at '{model_path}'")
print("\nTo get a model file, you can either:")
print(" 1. Train your own model on a football/soccer ball dataset")
print(" (see README.md for instructions)")
print(" 2. Place a pre-trained YOLO .pt file at the path above")
print("\nSet YOLO_MODEL_PATH in your .env file to your model path")
sys.exit(1)
self.camera = CameraCapture(fps=60, camera_id=camera_id, buffer_duration_seconds=5.0)
self.pose_tracker = PoseTracker(model_path="./task_files/pose_landmarker_full.task")
self.yolo = YOLO(model_path)
print(f"YOLO model loaded from {model_path}")
self.ball_tracker = BallTracker(shared_model=self.yolo, imgsz=832, confidence=0.45, fps=60.0)
self.person_detector = PersonDetector(shared_model=self.yolo, imgsz=832)
self.shot_detector = ShotDetector(detailed_logs=detailed_logs)
self.form_analyzer = FormAnalyzer()
self.shot_logger = ShotLogger()
self.contact_finder = ContactFrameFinder()
self.phase_segmenter = ShotPhaseSegmenter(fps=60.0)
self.temporal_analyzer = TemporalFormAnalyzer()
self.ai_coach = None
if ai_feedback:
provider_arg = None if ai_provider == "auto" else ai_provider
self.ai_coach = AITechniqueCoach(provider=provider_arg, enabled=True)
if self.ai_coach.is_available():
print(f"AI Coach enabled ({self.ai_coach.provider_instance.name}: {self.ai_coach.model})")
else:
print("AI Coach unavailable - using rule-based feedback")
self.is_active = False
self.yolo_results = None
self.frame_count = 0
self.current_frame = None
self.pose_history = deque(maxlen=60)
self.timestamp_history = deque(maxlen=60)
self.frame_buffer = deque(maxlen=90) # ~1.5s at 60fps, stores (frame, timestamp)
self.pose_buffer = PoseTrackingBuffer(max_frames=60)
self.notes_manager = ShotNotesManager()
def process_frame(self):
"""Process one frame. Returns the frame with overlay or None on error."""
result = self.camera.get_frame()
if result is None:
return None
frame, timestamp = result
self.frame_count += 1
self.current_frame = frame.copy() # Store clean frame for screenshot
# model.track() needs every frame for best association quality
self.yolo_results = self.yolo.track(
frame,
conf=0.25,
persist=True,
verbose=False,
imgsz=832,
tracker="./config/bytetrack_football.yaml",
device='cuda'
)
pose_data = self.pose_tracker.process_frame(frame, timestamp=timestamp)
person = self.person_detector.detect_person(frame, yolo_results=self.yolo_results)
ball_pos = self.ball_tracker.detect_ball(
frame, timestamp,
yolo_results=self.yolo_results,
pose_data=pose_data
)
ball_velocity = self.ball_tracker.get_velocity()
ball_acceleration = self.ball_tracker.get_acceleration()
ball_direction = self.ball_tracker.get_direction()
ball_tracking_quality = self.ball_tracker.get_tracking_quality()
ball_active_score = self.ball_tracker.get_active_ball_score()
self.pose_history.append(pose_data)
self.timestamp_history.append(timestamp)
self.frame_buffer.append((frame.copy(), timestamp))
self.pose_buffer.add(pose_data, timestamp)
shot_detected, shot_event = self.shot_detector.update(
timestamp, ball_pos, ball_velocity, pose_data,
ball_acceleration=ball_acceleration,
ball_direction=ball_direction,
ball_tracking_quality=ball_tracking_quality,
ball_active_score=ball_active_score,
ball_tracking_id=self.ball_tracker.get_tracking_id(),
ball_target_switched=self.ball_tracker.target_switched()
)
if person is None:
shot_detected = False
elif shot_detected and shot_event:
# Dynamic shot window: scale by ball velocity
ball_speed = shot_event.ball_velocity
if ball_speed > 2000:
window_duration = 0.8 # Fast shot - short window
elif ball_speed > 1000:
window_duration = 1.2 # Medium shot
else:
window_duration = 1.8 # Slow shot - longer tracking needed
self.ball_tracker.activate_shot_window(timestamp, duration=window_duration)
self._on_shot_detected(shot_event, pose_data, ball_velocity, ball_direction)
if not self.no_ui:
self._draw_overlay(frame, pose_data, ball_pos, person, shot_detected)
return frame
def _on_shot_detected(self, event, pose_data, ball_velocity, ball_direction):
"""Handle shot detection with detailed analysis."""
shot_number = self.shot_logger.shot_count + 1
print(f"\n{'='*50}")
print(f"SHOT #{shot_number} DETECTED!")
print(f"{'='*50}")
print(f"Foot: {event.foot_used}")
print(f"Velocity: {event.ball_velocity:.0f} px/s")
if event.direction is not None:
print(f"Direction: {event.direction:.0f} deg")
print(f"\n--- Detection ---")
print(f"Display Score: {event.shot_score:.2f}")
print(f"Ball Acceleration: {event.ball_acceleration:.0f} px/s\u00b2")
print(f"Foot Speed: {event.foot_speed:.0f} px/s")
if event.decision_reason:
print(f"Decision: {event.decision_reason}")
# Find exact contact frame
contact_result = None
foot_buffer = (self.shot_detector.left_foot_buffer
if event.foot_used == 'left'
else self.shot_detector.right_foot_buffer)
contact_result = self.contact_finder.find_contact_frame(
frame_buffer=list(self.frame_buffer),
pose_history=list(self.pose_history),
timestamp_history=list(self.timestamp_history),
ball_buffer=self.shot_detector.ball_buffer,
foot_buffer=foot_buffer,
detection_timestamp=event.timestamp,
kicking_foot=event.foot_used
)
if contact_result:
print(f"\n--- Contact Frame ---")
print(f"Contact confidence: {contact_result.confidence:.2f}")
print(f"Ball-foot distance at contact: {contact_result.ball_foot_distance:.0f}px")
print(f"Foot speed at contact: {contact_result.foot_speed_at_contact:.0f} px/s")
print(f"Frames before detection: {contact_result.post_contact_frames}")
# Use contact pose for analysis if available, otherwise fallback
analysis_pose = contact_result.contact_pose if contact_result and contact_result.contact_pose else pose_data
analysis_ball_pos = contact_result.ball_position_at_contact if contact_result else event.ball_position
analysis_velocity = self._select_analysis_ball_velocity(
event=event,
live_ball_velocity=ball_velocity,
contact_result=contact_result,
)
print(f"Analysis velocity: {analysis_velocity:.1f} px/s")
# Phase segmentation and temporal analysis
temporal_analysis = None
phases = None
pose_list = list(self.pose_history)
ts_list = list(self.timestamp_history)
if contact_result and len(pose_list) >= 5:
# Find contact index within pose_history
contact_idx_in_poses = len(pose_list) - 1 - contact_result.post_contact_frames
contact_idx_in_poses = max(0, min(contact_idx_in_poses, len(pose_list) - 1))
phases = self.phase_segmenter.segment_shot(
pose_sequence=pose_list,
timestamps=ts_list,
contact_frame_idx=contact_idx_in_poses,
kicking_foot=event.foot_used
)
temporal_analysis = self.temporal_analyzer.analyze_shot(
phases=phases,
contact_pose=analysis_pose,
kicking_foot=event.foot_used,
ball_position=analysis_ball_pos,
ball_velocity_pxs=analysis_velocity
)
if temporal_analysis:
print(f"\n--- Temporal Analysis ---")
print(f"Temporal score: {temporal_analysis.overall_temporal_score:.0f}/100")
print(f"Total duration: {temporal_analysis.total_duration_ms:.0f}ms")
print(f"Phase sequence valid: {temporal_analysis.phase_sequence_valid}")
if temporal_analysis.backswing:
print(f"Backswing: {temporal_analysis.backswing.backswing_duration_ms:.0f}ms, "
f"knee ROM: {temporal_analysis.backswing.knee_range_of_motion:.0f}deg")
if temporal_analysis.follow_through:
print(f"Follow-through: {temporal_analysis.follow_through.follow_through_duration_ms:.0f}ms, "
f"smoothness: {temporal_analysis.follow_through.deceleration_smoothness:.0%}")
analysis = None
ai_feedback = None
if analysis_pose:
analysis = self.form_analyzer.analyze_touch_form(
analysis_pose,
analysis_ball_pos,
event.foot_used,
ball_velocity_pxs=analysis_velocity,
ball_direction=ball_direction,
detailed=True
)
self.shot_logger.print_detailed_correction(analysis)
# Save screenshot before AI feedback so the image file exists on disk
screenshot_frame = (contact_result.contact_frame
if contact_result and contact_result.contact_frame is not None
else self.current_frame)
log_entry = None
if screenshot_frame is not None:
log_entry = self.shot_logger.log_shot(
screenshot_frame,
event,
analysis,
ai_feedback=None,
contact_result=contact_result,
temporal_analysis=temporal_analysis
)
# Update TCN temporal window with the canonical shot ID from ShotLogger
# so it matches feedback_labels.json for label joining
if log_entry and self.shot_detector.tcn_recorder is not None:
self.shot_detector.tcn_recorder.update_last_shot_id(log_entry["id"])
if analysis and self.ai_feedback_enabled and self.ai_coach and self.ai_coach.is_available():
detailed_data = analysis.get('detailed', analysis)
# Add temporal analysis to AI feedback prompt data
if temporal_analysis:
detailed_data = dict(detailed_data)
detailed_data['temporal_analysis'] = self.temporal_analyzer.to_dict(temporal_analysis)
screenshot_path = log_entry.get("screenshot_path") if log_entry else None
shot_contact_info = log_entry.get("contact_frame") if log_entry else None
# Run AI feedback in a background thread to avoid blocking frame processing
def _generate_ai_feedback(data, level, s_num, s_logger, coach, img_path, c_info):
try:
fb = coach.generate_detailed_feedback(
data, player_level=level, shot_number=s_num,
image_path=img_path, contact_info=c_info,
)
s_logger.print_ai_feedback(fb)
s_logger.update_last_shot_ai_feedback(fb)
except Exception as e:
print(f"AI feedback error (background): {e}")
threading.Thread(
target=_generate_ai_feedback,
args=(detailed_data, self.player_level, shot_number,
self.shot_logger, self.ai_coach, screenshot_path,
shot_contact_info),
daemon=True
).start()
print(f"{'='*50}\n")
def _select_analysis_ball_velocity(self, event, live_ball_velocity, contact_result) -> float:
"""
Build a robust velocity estimate for post-shot analysis.
We avoid single-frame collapse by combining multiple velocity signals
and preferring the strongest plausible value around contact.
"""
candidates = []
if live_ball_velocity is not None:
candidates.append(float(live_ball_velocity))
if event and getattr(event, "ball_velocity", None) is not None:
candidates.append(float(event.ball_velocity))
if contact_result and getattr(contact_result, "ball_speed_at_contact", None) is not None:
candidates.append(float(contact_result.ball_speed_at_contact))
peak_window_speed = self.shot_detector.ball_buffer.get_peak_speed(8)
candidates.append(float(peak_window_speed))
valid = [v for v in candidates if np.isfinite(v) and v > 0.0]
if not valid:
return 0.0
# Use a robust high estimate: average of top-2 values to reduce
# under-scoring from transient dips without over-trusting a single spike.
ranked = sorted(valid)
top_two = ranked[-2:] if len(ranked) >= 2 else ranked
return float(sum(top_two) / len(top_two))
def _draw_overlay(self, frame, pose_data, ball_pos, person, shot_detected):
"""Draw visualization with physics-based scoring debug info."""
h, w = frame.shape[:2]
if pose_data:
frame = self.pose_tracker.draw_pose(frame, pose_data)
if ball_pos:
cv2.circle(frame, ball_pos, 12, (0, 255, 0), -1)
cv2.circle(frame, ball_pos, 16, (0, 255, 0), 2)
# Draw ball trajectory (recent path from per-track history)
trajectory = self.ball_tracker.get_track_trajectory(n=30)
if len(trajectory) >= 2:
for i in range(1, len(trajectory)):
alpha = i / len(trajectory) # 0=oldest, 1=newest
color = (
0,
int(100 + 155 * alpha),
int(200 * (1 - alpha))
)
thickness = max(1, int(3 * alpha))
cv2.line(frame, trajectory[i - 1], trajectory[i], color, thickness)
# Get kicking phase info for foot highlighting
debug_info = self.shot_detector.get_debug_info()
kicking_phase = debug_info.get('kicking_phase', 'idle')
kicking_foot = debug_info.get('kicking_foot')
# Phase-based foot color
phase_colors = {
'idle': (150, 150, 150),
'approach': (255, 200, 0),
'backswing': (0, 165, 255),
'forward_swing': (0, 100, 255),
'contact': (0, 255, 0),
'follow_through': (255, 100, 100)
}
kick_foot_color = phase_colors.get(kicking_phase, (150, 150, 150))
if pose_data and 'joints' in pose_data:
joints = pose_data['joints']
# Highlight kicking foot with phase color
if kicking_foot and kicking_phase != 'idle':
anchor = get_foot_anchor(joints, kicking_foot)
if anchor:
foot_pt = (int(anchor[0]), int(anchor[1]))
cv2.circle(frame, foot_pt, 10, kick_foot_color, -1)
cv2.circle(frame, foot_pt, 14, kick_foot_color, 2)
# Draw foot-to-ball line
if ball_pos:
min_dist = float('inf')
closest_foot = None
for side in ['left', 'right']:
foot = get_foot_anchor(joints, side)
if foot:
dist = np.sqrt((ball_pos[0] - foot[0])**2 + (ball_pos[1] - foot[1])**2)
if dist < min_dist:
min_dist = dist
closest_foot = (int(foot[0]), int(foot[1]))
if closest_foot:
color = (0, 255, 0) if min_dist < 120 else (0, 165, 255) if min_dist < 200 else (0, 0, 255)
cv2.line(frame, closest_foot, ball_pos, color, 2)
# Draw foot swing arc trajectory
if kicking_foot and kicking_phase not in ('idle',):
arc = self.pose_buffer.get_swing_arc(kicking_foot, n_frames=10)
if len(arc) >= 2:
for i in range(1, len(arc)):
pt1 = (int(arc[i-1][0]), int(arc[i-1][1]))
pt2 = (int(arc[i][0]), int(arc[i][1]))
alpha = i / len(arc)
line_color = (
int(kick_foot_color[0] * alpha),
int(kick_foot_color[1] * alpha),
int(kick_foot_color[2] * alpha)
)
cv2.line(frame, pt1, pt2, line_color, 2)
state = self.shot_detector.get_state()
distance = self.shot_detector.get_distance()
state_colors = {
'IDLE': (150, 150, 150),
'TRACKING': (255, 200, 0),
'ACTIVE': (0, 200, 255),
'CONFIRMING': (255, 165, 0),
'COOLDOWN': (0, 255, 0),
}
color = state_colors.get(state, (255, 255, 255))
cv2.putText(frame, f"State: {state}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, color, 2)
if distance is not None:
cv2.putText(frame, f"Distance: {distance:.0f}px", (10, 60),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)
shot_count = len(self.shot_logger.get_session_shots())
cv2.putText(frame, f"Shots: {shot_count}", (10, 90),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)
shot_score = self.shot_detector.get_score()
threshold = debug_info.get('threshold', 0.4)
# Show kicking phase
if kicking_phase != 'idle':
phase_label = kicking_phase.replace('_', ' ').title()
cv2.putText(frame, f"Kick: {phase_label}", (10, 195),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, kick_foot_color, 2)
bar_x = w - 40
bar_y_top = 60
bar_height = 150
bar_width = 25
cv2.rectangle(frame, (bar_x, bar_y_top), (bar_x + bar_width, bar_y_top + bar_height),
(50, 50, 50), -1)
threshold_y = int(bar_y_top + bar_height * (1 - threshold))
cv2.line(frame, (bar_x - 5, threshold_y), (bar_x + bar_width + 5, threshold_y),
(0, 255, 255), 2)
score_height = int(bar_height * min(shot_score, 1.0))
score_y = bar_y_top + bar_height - score_height
if shot_score >= threshold:
bar_color = (0, 255, 0)
elif shot_score >= threshold * 0.7:
bar_color = (0, 255, 255)
else:
bar_color = (100, 100, 100)
cv2.rectangle(frame, (bar_x, score_y), (bar_x + bar_width, bar_y_top + bar_height),
bar_color, -1)
cv2.putText(frame, f"{shot_score:.2f}", (bar_x - 10, bar_y_top - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
cv2.putText(frame, "Score", (bar_x - 5, bar_y_top + bar_height + 15),
cv2.FONT_HERSHEY_SIMPLEX, 0.4, (200, 200, 200), 1)
features = self.shot_detector.get_features()
if features and shot_score > 0.15:
breakdown = features.feature_breakdown
if breakdown:
dominant = max(breakdown.items(), key=lambda x: x[1])
dominant_name, dominant_value = dominant
name_abbrev = {
'distance': 'Dist',
'foot_speed': 'Foot',
'ball_accel': 'Accel',
'alignment': 'Align',
'temporal': 'Time',
'causality': 'Cause',
'impulse': 'Impls',
'speed_increase': 'Speed',
'kicking': 'Kick',
'kicking_pattern': 'Pose',
}
short_name = name_abbrev.get(dominant_name, dominant_name[:5])
cv2.putText(frame, f"Top: {short_name}", (w - 80, bar_y_top + bar_height + 35),
cv2.FONT_HERSHEY_SIMPLEX, 0.4, (200, 200, 200), 1)
if self.ball_tracker.is_tracking():
quality = self.ball_tracker.get_tracking_quality()
quality_color = (0, 255, 0) if quality > 0.7 else (0, 255, 255) if quality > 0.4 else (0, 0, 255)
cv2.putText(frame, f"Track: {quality:.0%}", (10, 120),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, quality_color, 2)
active_score = self.ball_tracker.get_active_ball_score()
active_color = (0, 255, 0) if active_score > 0.7 else (0, 255, 255) if active_score > 0.4 else (0, 0, 255)
cv2.putText(frame, f"Active: {active_score:.0%}", (10, 145),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, active_color, 2)
ball_debug = self.ball_tracker.get_debug_info()
decision = ball_debug.get("last_decision", "")
if decision:
cv2.putText(frame, f"Ball: {decision}", (10, 170),
cv2.FONT_HERSHEY_SIMPLEX, 0.4, (200, 200, 200), 1)
cooldown = debug_info.get('cooldown', 0)
if cooldown > 0:
cv2.putText(frame, f"Cooldown: {cooldown:.1f}s", (10, 195),
cv2.FONT_HERSHEY_SIMPLEX, 0.4, (150, 150, 150), 1)
if self.ai_feedback_enabled:
ai_status = "AI: ON" if (self.ai_coach and self.ai_coach.is_available()) else "AI: OFF"
cv2.putText(frame, ai_status, (w - 80, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 2)
if shot_detected:
cv2.putText(frame, "SHOT!", (w//2 - 60, 50),
cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0, 255, 0), 3)
tier = self.shot_detector.get_tier_fired()
if tier:
cv2.putText(frame, tier, (w//2 + 80, 50),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 255), 2)
def _get_session_info(self):
"""Gather stats for sidebar display."""
debug = self.shot_detector.get_debug_info()
return {
'shot_count': len(self.shot_logger.get_session_shots()),
'state': debug.get('state', 'IDLE'),
'score': debug.get('score', 0.0),
'kick_phase': debug.get('kicking_phase', 'idle'),
'kick_score': debug.get('kicking_score', 0.0),
'tracking_quality': self.ball_tracker.get_tracking_quality(),
'active_score': self.ball_tracker.get_active_ball_score(),
'frame_count': self.frame_count,
'session_id': self.shot_logger.session_id,
}
def _take_manual_screenshot(self):
"""Save current frame as a manual screenshot."""
if self.current_frame is None:
return
timestamp_str = datetime.now().strftime("%Y%m%d_%H%M%S_%f")[:-3]
filename = f"manual_{self.shot_logger.session_id}_{timestamp_str}.jpg"
path = os.path.join("shots", "screenshots", filename)
os.makedirs(os.path.dirname(path), exist_ok=True)
cv2.imwrite(path, self.current_frame)
print(f"Manual screenshot saved: {path}")
def _reset_session(self):
"""Reset all session state for a fresh start."""
# Ball tracker
self.ball_tracker.reset()
# Shot detector buffers and state
self.shot_detector.ball_buffer.clear()
self.shot_detector.left_foot_buffer.clear()
self.shot_detector.right_foot_buffer.clear()
self.shot_detector._reset_tier_state()
self.shot_detector.last_shot_time = -999.0
self.shot_detector.frame_count = 0
self.shot_detector.missing_frames = 0
self.shot_detector._last_features = None
self.shot_detector._display_score = 0.0
self.shot_detector._debug_log.clear()
self.shot_detector.last_tracker_switch_time = -999.0
self.shot_detector._tracking_quality_low = False
# Kicking analyzer (fresh instance)
self.shot_detector.kicking_analyzer = KickingPatternAnalyzer(fps=self.shot_detector.fps)
# Scorer state
self.shot_detector.scorer.score_history.clear()
self.shot_detector.scorer.features_history.clear()
self.shot_detector.scorer.frames_above_threshold = 0
self.shot_detector.scorer.frames_below_threshold = 0
self.shot_detector.scorer.peak_score_in_window = 0.0
self.shot_detector.scorer.last_shot_frame = -100
self.shot_detector.scorer.frame_count = 0
# Shot logger session counters
self.shot_logger.shot_count = 0
self.shot_logger.session_id = datetime.now().strftime("%Y%m%d_%H%M%S")
self.shot_logger._session_analyses.clear()
# Session-level buffers
self.frame_count = 0
self.pose_history.clear()
self.timestamp_history.clear()
self.frame_buffer.clear()
self.pose_buffer = PoseTrackingBuffer(max_frames=60)
# Stateless components (re-instantiate for clean state)
self.contact_finder = ContactFrameFinder()
self.phase_segmenter = ShotPhaseSegmenter(fps=60.0)
self.temporal_analyzer = TemporalFormAnalyzer()
print("Session reset")
def run_terminal(self):
"""Terminal-only mode loop (no PySide6 required)."""
if not self.camera.start():
print("Failed to start camera")
return
self.is_active = True
print(f"Session started - Level: {self.player_level}")
print("Press Ctrl+C to quit")
consecutive_errors = 0
try:
while self.is_active:
frame = self.process_frame()
if frame is None:
consecutive_errors += 1
if consecutive_errors > 10:
print(f"Too many consecutive frame errors, stopping")
break
continue
consecutive_errors = 0
if self.frame_count % 60 == 0:
debug = self.shot_detector.get_debug_info()
shots = len(self.shot_logger.get_session_shots())
print(f"[Frame {self.frame_count}] Shots: {shots} | "
f"State: {debug.get('state', '?')} | "
f"Score: {debug.get('score', 0):.2f}")
cv2.waitKey(1)
except KeyboardInterrupt:
print("\nSession interrupted by user")
finally:
self._cleanup()
def _cleanup(self):
"""Clean up resources and print summary."""
self.camera.stop()
self.shot_logger.print_session_summary()
if self.ai_feedback_enabled and self.ai_coach and self.ai_coach.is_available():
analyses = self.shot_logger.get_session_detailed_analyses()
if analyses:
summary = self.ai_coach.generate_session_summary(
analyses,
player_level=self.player_level
)
if summary.get('ai_enabled'):
print("\n" + "=" * 60)
print("AI SESSION SUMMARY")
print("=" * 60)
print(summary.get('session_summary', ''))
print("=" * 60)
if self.detailed_logs:
self.shot_detector.save_final_logs()
else:
# Always save TCN temporal windows even without --detailed-logs
if (self.shot_detector.tcn_recorder is not None
and self.shot_detector.tcn_recorder.n_recorded > 0):
self.shot_detector.tcn_recorder.update_labels()
self.shot_detector.tcn_recorder.save()
self.ball_tracker.save_debug_log()
print("Debug logs saved to: shots/ball_tracker_debug.json")
print("Session ended")
def main():
import argparse
load_dotenv()
parser = argparse.ArgumentParser(description="Sadball - Football Shooting Analyzer")
parser.add_argument("--level", default="intermediate",
choices=["beginner", "intermediate", "advanced"],
help="Player skill level for feedback calibration")
parser.add_argument("--detailed-logs",default=False, action="store_true",
help="Enable detailed logging for shot detection algorithm analysis")
parser.add_argument("--ai-feedback",default=False, action="store_true",
help="Enable AI-powered technique feedback (requires API key)")
parser.add_argument("--no-ui",default=False, action="store_true",
help="Run in terminal-only mode without UI window (logging only)")
args = parser.parse_args()
ai_provider = os.getenv("AI_PROVIDER", "auto").strip().lower()
if ai_provider not in {"openai", "gemini", "anthropic", "auto"}:
print(f"Warning: Invalid AI_PROVIDER '{ai_provider}', falling back to 'auto'")
ai_provider = "auto"
model_path = os.getenv("YOLO_MODEL_PATH", "./models/best.pt").strip()
camera_id_raw = os.getenv("CAMERA_ID", "0").strip()
try:
camera_id = int(camera_id_raw)
except ValueError:
print(f"Warning: Invalid CAMERA_ID '{camera_id_raw}', falling back to 0")
camera_id = 0
print("\n" + "=" * 60)
print("SADBALL - Football Shooting Analyzer")
print("=" * 60)
print(f"Player level: {args.level}")
print(f"AI feedback: {'Enabled' if args.ai_feedback else 'Disabled'}")
if args.ai_feedback:
print(f"AI provider: {ai_provider}")
print(f"Detailed logs: {'Enabled' if args.detailed_logs else 'Disabled'}")
print(f"UI mode: {'Terminal only' if args.no_ui else 'Full UI'}")
print(f"Model: {model_path}")
print(f"Camera: {camera_id}")
print("=" * 60 + "\n")
session = ShootingSession(
player_level=args.level,
detailed_logs=args.detailed_logs,
ai_feedback=args.ai_feedback,
ai_provider=ai_provider,
no_ui=args.no_ui,
model_path=model_path,
camera_id=camera_id
)
if args.no_ui:
session.run_terminal()
else:
from PySide6.QtWidgets import QApplication
from ui.main_window import MainWindow, create_classic_palette
# Install exception hook so PySide6 doesn't swallow tracebacks
_original_excepthook = sys.excepthook
def _excepthook(exc_type, exc_value, exc_tb):
import traceback
traceback.print_exception(exc_type, exc_value, exc_tb)
_original_excepthook(exc_type, exc_value, exc_tb)
sys.excepthook = _excepthook
app = QApplication(sys.argv)
app.setStyle("Fusion")
app.setPalette(create_classic_palette())
window = MainWindow(session)
window.show()
sys.exit(app.exec())
if __name__ == "__main__":
main()