File size: 10,513 Bytes
c6abe34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Analytics Coordinator - Orchestrates all analytics modules.

Runs all 7 analytics modules in the correct order and aggregates results.
"""
from typing import Dict, Any, List
import logging

from .spacing_engine import SpacingEngine
from .defensive_reaction import DefensiveReactionEngine
from .transition_effort import TransitionEffortEngine
from .decision_quality import DecisionQualityEngine
from .lineup_impact import LineupImpactEngine
from .fatigue_tracker import FatigueTracker
from .clip_generator import ClipGenerator

logger = logging.getLogger(__name__)


class AnalyticsCoordinator:
    """Coordinates execution of all advanced analytics modules."""
    
    def __init__(self):
        """Initialize all analytics modules."""
        self.spacing_engine = SpacingEngine()
        self.defensive_reaction = DefensiveReactionEngine()
        self.transition_effort = TransitionEffortEngine()
        self.decision_quality = DecisionQualityEngine()
        self.lineup_impact = LineupImpactEngine()
        self.fatigue_tracker = FatigueTracker()
        self.clip_generator = ClipGenerator()
    
    def process_all(
        self,
        video_frames: List[Any],
        player_tracks: List[Dict],
        ball_tracks: List[Dict],
        tactical_positions: List[Dict],
        player_assignment: List[Dict],
        ball_possession: List[int],
        events: List[Dict],
        shots: List[Dict],
        court_keypoints: List[Dict],
        speeds: List[Dict],
        video_path: str,
        fps: float
    ) -> Dict[str, Any]:
        """
        Run all analytics modules and aggregate results.
        
        Modules are executed in dependency order:
        1. Spacing Engine (independent)
        2. Defensive Reaction Engine (independent)
        3. Transition Effort Engine (independent)
        4. Decision Quality Engine (independent)
        5. Lineup Impact Engine (depends on spacing + defensive reactions)
        6. Fatigue Tracker (depends on defensive reactions)
        7. Clip Generator (depends on all previous modules)
        
        Args:
            video_frames: List of video frames
            player_tracks: Per-frame player tracking data
            ball_tracks: Per-frame ball tracking data
            tactical_positions: 2D court positions for players
            player_assignment: Per-frame team assignments
            ball_possession: Per-frame ball possession
            events: List of detected events
            shots: List of detected shots
            court_keypoints: Court boundary keypoints
            speeds: Per-frame player speeds
            video_path: Path to original video
            fps: Frames per second
        
        Returns:
            Aggregated analytics results from all modules
        """
        logger.info("Starting advanced analytics processing")
        
        results = {
            "modules_executed": [],
            "modules_failed": [],
        }
        
        # Module 1: Spacing Engine
        logger.info("Running Spacing Engine")
        spacing_result = self.spacing_engine.safe_process(
            video_frames=video_frames,
            player_tracks=player_tracks,
            ball_tracks=ball_tracks,
            tactical_positions=tactical_positions,
            player_assignment=player_assignment,
            ball_possession=ball_possession,
            events=events,
            shots=shots,
            court_keypoints=court_keypoints,
            speeds=speeds,
            video_path=video_path,
            fps=fps
        )
        
        if spacing_result.get("status") == "success":
            results["spacing"] = spacing_result
            results["modules_executed"].append("spacing_engine")
        else:
            results["modules_failed"].append("spacing_engine")
            logger.error(f"Spacing Engine failed: {spacing_result.get('error')}")
        
        # Module 2: Defensive Reaction Engine
        logger.info("Running Defensive Reaction Engine")
        defensive_result = self.defensive_reaction.safe_process(
            video_frames=video_frames,
            player_tracks=player_tracks,
            ball_tracks=ball_tracks,
            tactical_positions=tactical_positions,
            player_assignment=player_assignment,
            ball_possession=ball_possession,
            events=events,
            shots=shots,
            court_keypoints=court_keypoints,
            speeds=speeds,
            video_path=video_path,
            fps=fps
        )
        
        if defensive_result.get("status") == "success":
            results["defensive_reactions"] = defensive_result
            results["modules_executed"].append("defensive_reaction")
        else:
            results["modules_failed"].append("defensive_reaction")
            logger.error(f"Defensive Reaction Engine failed: {defensive_result.get('error')}")
        
        # Module 3: Transition Effort Engine
        logger.info("Running Transition Effort Engine")
        transition_result = self.transition_effort.safe_process(
            video_frames=video_frames,
            player_tracks=player_tracks,
            ball_tracks=ball_tracks,
            tactical_positions=tactical_positions,
            player_assignment=player_assignment,
            ball_possession=ball_possession,
            events=events,
            shots=shots,
            court_keypoints=court_keypoints,
            speeds=speeds,
            video_path=video_path,
            fps=fps
        )
        
        if transition_result.get("status") == "success":
            results["transition_effort"] = transition_result
            results["modules_executed"].append("transition_effort")
        else:
            results["modules_failed"].append("transition_effort")
            logger.error(f"Transition Effort Engine failed: {transition_result.get('error')}")
        
        # Module 4: Decision Quality Engine
        logger.info("Running Decision Quality Engine")
        decision_result = self.decision_quality.safe_process(
            video_frames=video_frames,
            player_tracks=player_tracks,
            ball_tracks=ball_tracks,
            tactical_positions=tactical_positions,
            player_assignment=player_assignment,
            ball_possession=ball_possession,
            events=events,
            shots=shots,
            court_keypoints=court_keypoints,
            speeds=speeds,
            video_path=video_path,
            fps=fps
        )
        
        if decision_result.get("status") == "success":
            results["decision_quality"] = decision_result
            results["modules_executed"].append("decision_quality")
        else:
            results["modules_failed"].append("decision_quality")
            logger.error(f"Decision Quality Engine failed: {decision_result.get('error')}")
        
        # Module 5: Lineup Impact Engine (depends on spacing + defensive reactions)
        logger.info("Running Lineup Impact Engine")
        lineup_result = self.lineup_impact.safe_process(
            video_frames=video_frames,
            player_tracks=player_tracks,
            ball_tracks=ball_tracks,
            tactical_positions=tactical_positions,
            player_assignment=player_assignment,
            ball_possession=ball_possession,
            events=events,
            shots=shots,
            court_keypoints=court_keypoints,
            speeds=speeds,
            video_path=video_path,
            fps=fps,
            spacing_metrics=spacing_result.get("spacing_metrics", []),
            defensive_reactions=defensive_result.get("defensive_reactions", [])
        )
        
        if lineup_result.get("status") == "success":
            results["lineup_impact"] = lineup_result
            results["modules_executed"].append("lineup_impact")
        else:
            results["modules_failed"].append("lineup_impact")
            logger.error(f"Lineup Impact Engine failed: {lineup_result.get('error')}")
        
        # Module 6: Fatigue Tracker (depends on defensive reactions)
        logger.info("Running Fatigue Tracker")
        fatigue_result = self.fatigue_tracker.safe_process(
            video_frames=video_frames,
            player_tracks=player_tracks,
            ball_tracks=ball_tracks,
            tactical_positions=tactical_positions,
            player_assignment=player_assignment,
            ball_possession=ball_possession,
            events=events,
            shots=shots,
            court_keypoints=court_keypoints,
            speeds=speeds,
            video_path=video_path,
            fps=fps,
            defensive_reactions=defensive_result.get("defensive_reactions", [])
        )
        
        if fatigue_result.get("status") == "success":
            results["fatigue"] = fatigue_result
            results["modules_executed"].append("fatigue_tracker")
        else:
            results["modules_failed"].append("fatigue_tracker")
            logger.error(f"Fatigue Tracker failed: {fatigue_result.get('error')}")
        
        # Module 7: Clip Generator (depends on all previous modules)
        logger.info("Running Clip Generator")
        clip_result = self.clip_generator.safe_process(
            video_frames=video_frames,
            player_tracks=player_tracks,
            ball_tracks=ball_tracks,
            tactical_positions=tactical_positions,
            player_assignment=player_assignment,
            ball_possession=ball_possession,
            events=events,
            shots=shots,
            court_keypoints=court_keypoints,
            speeds=speeds,
            video_path=video_path,
            fps=fps,
            spacing_metrics=spacing_result.get("spacing_metrics", []),
            defensive_reactions=defensive_result.get("defensive_reactions", []),
            transition_efforts=transition_result.get("transition_efforts", []),
            decision_analyses=decision_result.get("decision_analyses", [])
        )
        
        if clip_result.get("status") == "success":
            results["clips"] = clip_result
            results["modules_executed"].append("clip_generator")
        else:
            results["modules_failed"].append("clip_generator")
            logger.error(f"Clip Generator failed: {clip_result.get('error')}")
        
        logger.info(f"Advanced analytics complete. Executed: {len(results['modules_executed'])}, Failed: {len(results['modules_failed'])}")
        
        return results