scorevision: push artifact
Browse files12345678910111213141516171819202122232 unmodified lines262728293031323334352 unmodified lines3839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509from pathlib import Pathfrom typing import List, Tuple, Dict, Optionalimport sys, ossys.path.append(os.path.dirname(os.path.abspath(__file__)))import onnxruntime as ortimport numpy as npimport cv2from torchvision.ops import batched_nmsimport torchfrom ultralytics import YOLOfrom numpy import ndarrayfrom pydantic import BaseModelfrom team_cluster import TeamClassifierfrom utils import (BoundingBox,Constants,suppress_small_contained_boxes,classify_teams_batch,)class TVFrameResult(BaseModel):frame_id: int2 unmodified linesclass Miner:"""Football video analysis system for object detection and team classification."""# Use constants from utilsSMALL_CONTAINED_IOA = Constants.SMALL_CONTAINED_IOASMALL_RATIO_MAX = Constants.SMALL_RATIO_MAXSINGLE_PLAYER_HUE_PIVOT = Constants.SINGLE_PLAYER_HUE_PIVOT2 unmodified linesCORNER_CONFIDENCE = Constants.CORNER_CONFIDENCEGOALKEEPER_POSITION_MARGIN = Constants.GOALKEEPER_POSITION_MARGINMIN_SAMPLES_FOR_FIT = 16 # Minimum player crops needed before fitting TeamClassifierMAX_SAMPLES_FOR_FIT = 500 # Maximum samples to avoid overfittingdef __init__(self, path_hf_repo: Path) -> None:providers = ['CUDAExecutionProvider','CPUExecutionProvider']model_path = path_hf_repo / "detection.onnx"session = ort.InferenceSession(model_path, providers=providers)input_name = session.get_inputs()[0].nameheight = width = 640dummy = np.zeros((1, 3, height, width), dtype=np.float32)session.run(None, {input_name: dummy})model = sessionself.bbox_model = modelprint("BBox Model Loaded")self.keypoints_model = YOLO(path_hf_repo / "keypoint.pt")print("Keypoints Model (keypoint.pt) Loaded")# Initialize team classifier with OSNet modelteam_model_path = path_hf_repo / "osnet_model.pth.tar-100"device = 'cuda'self.team_classifier = TeamClassifier(device=device,batch_size=32,model_name=str(team_model_path))print("Team Classifier Loaded")# Team classification stateself.team_classifier_fitted = Falseself.player_crops_for_fit = [] # Collect samples across framesdef __repr__(self) -> str:return (f"BBox Model: {type(self.bbox_model).__name__}\n"f"Keypoints Model: {type(self.keypoints_model).__name__}")def _handle_multiple_goalkeepers(self, boxes: List[BoundingBox]) -> List[BoundingBox]:"""Handle goalkeeper detection issues:1. Fix misplaced goalkeepers (standing in middle of field)2. Limit to maximum 2 goalkeepers (one from each team)Returns:Filtered list of boxes with corrected goalkeepers"""# Step 1: Fix misplaced goalkeepers first# Convert goalkeepers in middle of field to regular playersboxes = self._fix_misplaced_goalkeepers(boxes)# Step 2: Handle multiple goalkeepers (after fixing misplaced ones)gk_idxs = [i for i, bb in enumerate(boxes) if int(bb.cls_id) == 1]if len(gk_idxs) <= 2:return boxes# Sort goalkeepers by confidence (highest first)gk_idxs_sorted = sorted(gk_idxs, key=lambda i: boxes[i].conf, reverse=True)keep_gk_idxs = set(gk_idxs_sorted[:2]) # Keep top 2 goalkeepers# Create new list keeping only top 2 goalkeepersfiltered_boxes = []for i, box in enumerate(boxes):if int(box.cls_id) == 1:# Only keep the top 2 goalkeepers by confidenceif i in keep_gk_idxs:filtered_boxes.append(box)# Skip extra goalkeeperselse:# Keep all non-goalkeeper boxesfiltered_boxes.append(box)return filtered_boxesdef _fix_misplaced_goalkeepers(self, boxes: List[BoundingBox]) -> List[BoundingBox]:""""""gk_idxs = [i for i, bb in enumerate(boxes) if int(bb.cls_id) == 1]player_idxs = [i for i, bb in enumerate(boxes) if int(bb.cls_id) == 2]if len(gk_idxs) == 0 or len(player_idxs) < 2:return boxesupdated_boxes = boxes.copy()for gk_idx in gk_idxs:if boxes[gk_idx].conf < 0.3:updated_boxes[gk_idx].cls_id = 2return updated_boxesdef _pre_process_img(self, frames: List[np.ndarray], scale: float = 640.0) -> np.ndarray:"""Preprocess images for ONNX inference.Args:frames: List of BGR framesscale: Target scale for resizingReturns:Preprocessed numpy array ready for ONNX inference"""imgs = np.stack([cv2.resize(frame, (int(scale), int(scale))) for frame in frames])imgs = imgs.transpose(0, 3, 1, 2) # BHWC to BCHWimgs = imgs.astype(np.float32) / 255.0 # Normalize to [0, 1]return imgsdef _post_process_output(self, outputs: np.ndarray, x_scale: float, y_scale: float,conf_thresh: float = 0.6, nms_thresh: float = 0.55) -> List[List[Tuple]]:"""Post-process ONNX model outputs to get detections.Args:outputs: Raw ONNX model outputsx_scale: X-axis scaling factory_scale: Y-axis scaling factorconf_thresh: Confidence thresholdnms_thresh: NMS thresholdReturns:List of detections for each frame: [(box, conf, class_id), ...]"""B, C, N = outputs.shapeoutputs = torch.from_numpy(outputs)outputs = outputs.permute(0, 2, 1) # B,C,N -> B,N,Cboxes = outputs[..., :4]class_scores = 1 / (1 + torch.exp(-outputs[..., 4:])) # Sigmoid activationconf, class_id = class_scores.max(dim=2)mask = conf > conf_thresh# Special handling for balls - keep best one even with lower confidencefor i in range(class_id.shape[0]): # loop over batch# Find detections that are ballsball_mask = class_id[i] == 0ball_idx = ball_mask.nonzero(as_tuple=True)[0]if ball_idx.numel() > 0:# Pick the one with the highest confidencebest_ball_idx = ball_idx[conf[i, ball_idx].argmax()]if conf[i, best_ball_idx] >= 0.55: # apply confidence thresholdmask[i, best_ball_idx] = Truebatch_idx, pred_idx = mask.nonzero(as_tuple=True)if len(batch_idx) == 0:return [[] for _ in range(B)]boxes = boxes[batch_idx, pred_idx]conf = conf[batch_idx, pred_idx]class_id = class_id[batch_idx, pred_idx]# Convert from center format to xyxy formatx, y, w, h = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]x1 = (x - w / 2) * x_scaley1 = (y - h / 2) * y_scalex2 = (x + w / 2) * x_scaley2 = (y + h / 2) * y_scaleboxes_xyxy = torch.stack([x1, y1, x2, y2], dim=1)# Apply batched NMSmax_coord = 1e4offset = batch_idx.to(boxes_xyxy) * max_coordboxes_for_nms = boxes_xyxy + offset[:, None]keep = batched_nms(boxes_for_nms, conf, batch_idx, nms_thresh)boxes_final = boxes_xyxy[keep]conf_final = conf[keep]class_final = class_id[keep]batch_final = batch_idx[keep]# Group results by batchresults = [[] for _ in range(B)]for b in range(B):mask_b = batch_final == bif mask_b.sum() == 0:continueresults[b] = list(zip(boxes_final[mask_b].numpy(),conf_final[mask_b].numpy(),class_final[mask_b].numpy()))return resultsdef _ioa(self, a: BoundingBox, b: BoundingBox) -> float:inter = self._intersect_area(a, b)aa = self._area(a)if aa <= 0:return 0.0return inter / aadef suppress_small_contained(self, boxes: List[BoundingBox]) -> List[BoundingBox]:if len(boxes) <= 1:return boxeskeep = [True] * len(boxes)areas = [self._area(bb) for bb in boxes]for i in range(len(boxes)):if not keep[i]:continuefor j in range(len(boxes)):if i == j or not keep[j]:continueai, aj = areas[i], areas[j]if ai == 0 or aj == 0:continueif ai <= aj:ratio = ai / ajif ratio <= self.SMALL_RATIO_MAX:ioa_i_in_j = self._ioa(boxes[i], boxes[j])if ioa_i_in_j >= self.SMALL_CONTAINED_IOA:keep[i] = Falsebreakelse:ratio = aj / aiif ratio <= self.SMALL_RATIO_MAX:ioa_j_in_i = self._ioa(boxes[j], boxes[i])if ioa_j_in_i >= self.SMALL_CONTAINED_IOA:keep[j] = Falsereturn [bb for bb, k in zip(boxes, keep) if k]def _detect_objects_batch(self, batch_images: List[ndarray], offset: int) -> Dict[int, List[BoundingBox]]:"""Phase 1: Object detection for all frames in batch.Returns detected objects with players still having class_id=2 (before team classification).Args:batch_images: List of images to processoffset: Frame offset for numberingReturns:Dictionary mapping frame_id to list of detected boxes"""bboxes: Dict[int, List[BoundingBox]] = {}if len(batch_images) == 0:return bboxesprint(f"Processing batch of {len(batch_images)} images")# Get original image dimensions for scalingheight, width = batch_images[0].shape[:2]scale = 640.0x_scale = width / scaley_scale = height / scale# Memory optimization: Process smaller batches if neededmax_batch_size = 32 # Reduce batch size further to prevent memory issuesif len(batch_images) > max_batch_size:print(f"Large batch detected ({len(batch_images)} images), splitting into smaller batches of {max_batch_size}")# Process in smaller chunksall_bboxes = {}for chunk_start in range(0, len(batch_images), max_batch_size):chunk_end = min(chunk_start + max_batch_size, len(batch_images))chunk_images = batch_images[chunk_start:chunk_end]chunk_offset = offset + chunk_startprint(f"Processing chunk {chunk_start//max_batch_size + 1}: images {chunk_start}-{chunk_end-1}")chunk_bboxes = self._detect_objects_batch(chunk_images, chunk_offset)all_bboxes.update(chunk_bboxes)return all_bboxes# Preprocess images for ONNX inferenceimgs = self._pre_process_img(batch_images, scale)actual_batch_size = len(batch_images)# Handle batch size mismatch - pad if neededmodel_batch_size = self.bbox_model.get_inputs()[0].shape[0]print(f"Model input shape: {self.bbox_model.get_inputs()[0].shape}, batch_size: {model_batch_size}")if model_batch_size is not None:try:# Handle dynamic batch size (None, -1, 'None')if str(model_batch_size) in ['None', '-1'] or model_batch_size == -1:model_batch_size = Noneelse:model_batch_size = int(model_batch_size)except (ValueError, TypeError):model_batch_size = Noneprint(f"Processed model_batch_size: {model_batch_size}, actual_batch_size: {actual_batch_size}")if model_batch_size and actual_batch_size < model_batch_size:padding_size = model_batch_size - actual_batch_sizedummy_img = np.zeros((1, 3, int(scale), int(scale)), dtype=np.float32)padding = np.repeat(dummy_img, padding_size, axis=0)imgs = np.vstack([imgs, padding])# ONNX inference with error handlingtry:input_name = self.bbox_model.get_inputs()[0].nameimport timestart_time = time.time()outputs = self.bbox_model.run(None, {input_name: imgs})[0]inference_time = time.time() - start_timeprint(f"Inference time: {inference_time:.3f}s for {actual_batch_size} images")# Remove padded results if we added paddingif model_batch_size and isinstance(model_batch_size, int) and actual_batch_size < model_batch_size:outputs = outputs[:actual_batch_size]# Post-process outputs to get detectionsraw_results = self._post_process_output(np.array(outputs), x_scale, y_scale)except Exception as e:print(f"Error during ONNX inference: {e}")return bboxesif not raw_results:return bboxes# Convert raw results to BoundingBox objects and apply processingfor frame_idx_in_batch, frame_detections in enumerate(raw_results):if not frame_detections:continue# Convert to BoundingBox objectsboxes: List[BoundingBox] = []for box, conf, cls_id in frame_detections:x1, y1, x2, y2 = boxif int(cls_id) < 4:boxes.append(BoundingBox(x1=int(x1),y1=int(y1),x2=int(x2),y2=int(y2),cls_id=int(cls_id),conf=float(conf),))# Handle footballs - keep only the best onefootballs = [bb for bb in boxes if int(bb.cls_id) == 0]if len(footballs) > 1:best_ball = max(footballs, key=lambda b: b.conf)boxes = [bb for bb in boxes if int(bb.cls_id) != 0]boxes.append(best_ball)# Remove overlapping small boxesboxes = suppress_small_contained_boxes(boxes, self.SMALL_CONTAINED_IOA, self.SMALL_RATIO_MAX)# Handle goalkeeper detection issues:# 1. Fix misplaced goalkeepers (convert to players if standing in middle)# 2. Allow up to 2 goalkeepers maximum (one from each team)# Goalkeepers remain class_id = 1 (no team assignment)boxes = self._handle_multiple_goalkeepers(boxes)# Store results (players still have class_id=2, will be classified in phase 2)frame_id = offset + frame_idx_in_batchbboxes[frame_id] = boxesreturn bboxesdef predict_batch(self,batch_images: List[ndarray],offset: int,n_keypoints: int,task_type: Optional[str] = None,) -> List[TVFrameResult]:process_objects = task_type is None or task_type == "object"process_keypoints = task_type is None or task_type == "keypoint"# Phase 1: Object Detection for all framesbboxes: Dict[int, List[BoundingBox]] = {}if process_objects:bboxes = self._detect_objects_batch(batch_images, offset)import timetime_start = time.time()# Phase 2: Team Classification for all detected playersif process_objects and bboxes:bboxes, self.team_classifier_fitted, self.player_crops_for_fit = classify_teams_batch(self.team_classifier,self.team_classifier_fitted,self.player_crops_for_fit,batch_images,bboxes,offset,self.MIN_SAMPLES_FOR_FIT,self.MAX_SAMPLES_FOR_FIT,self.SINGLE_PLAYER_HUE_PIVOT)self.team_classifier_fitted = Falseself.player_crops_for_fit = []print(f"Time Team Classification: {time.time() - time_start} s")# Phase 3: Keypoint Detectionkeypoints: Dict[int, List[Tuple[int, int]]] = {}if process_keypoints:keypoints = self._detect_keypoints_batch(batch_images, offset, n_keypoints)# Phase 4: Combine resultsresults: List[TVFrameResult] = []for frame_number in range(offset, offset + len(batch_images)):results.append(TVFrameResult(frame_id=frame_number,boxes=bboxes.get(frame_number, []),keypoints=keypoints.get(frame_number,[(0, 0) for _ in range(n_keypoints)],),))return resultsdef _detect_keypoints_batch(self, batch_images: List[ndarray],offset: int, n_keypoints: int) -> Dict[int, List[Tuple[int, int]]]:"""Phase 3: Keypoint detection for all frames in batch.Args:batch_images: List of images to processoffset: Frame offset for numberingn_keypoints: Number of keypoints expectedReturns:Dictionary mapping frame_id to list of keypoint coordinates"""keypoints: Dict[int, List[Tuple[int, int]]] = {}keypoints_model_results = self.keypoints_model.predict(batch_images)if keypoints_model_results is None:return keypointsfor frame_idx_in_batch, detection in enumerate(keypoints_model_results):if not hasattr(detection, "keypoints") or detection.keypoints is None:continue# Extract keypoints with confidenceframe_keypoints_with_conf: List[Tuple[int, int, float]] = []for i, part_points in enumerate(detection.keypoints.data):for k_id, (x, y, _) in enumerate(part_points):confidence = float(detection.keypoints.conf[i][k_id])frame_keypoints_with_conf.append((int(x), int(y), confidence))# Pad or truncate to expected number of keypointsif len(frame_keypoints_with_conf) < n_keypoints:frame_keypoints_with_conf.extend([(0, 0, 0.0)] * (n_keypoints - len(frame_keypoints_with_conf)))else:frame_keypoints_with_conf = frame_keypoints_with_conf[:n_keypoints]# Filter keypoints based on confidence thresholdsfiltered_keypoints: List[Tuple[int, int]] = []for idx, (x, y, confidence) in enumerate(frame_keypoints_with_conf):if idx in self.CORNER_INDICES:# Corner keypoints have lower confidence thresholdif confidence < 0.3:filtered_keypoints.append((0, 0))else:filtered_keypoints.append((int(x), int(y)))else:# Regular keypointsif confidence < 0.5:filtered_keypoints.append((0, 0))else:filtered_keypoints.append((int(x), int(y)))frame_id = offset + frame_idx_in_batchkeypoints[frame_id] = filtered_keypointsreturn keypoints123456789101112131415161718192021222324252627282930313233342 unmodified lines3738394041422 unmodified lines45464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429from pathlib import Pathfrom typing import List, Tuple, Dictimport sysimport osfrom numpy import ndarrayfrom pydantic import BaseModelsys.path.append(os.path.dirname(os.path.abspath(__file__)))from ultralytics import YOLOfrom team_cluster import TeamClassifierfrom utils import (BoundingBox,Constants,)import timeimport torchimport gcfrom pitch import process_batch_input, get_cls_netimport yamlclass BoundingBox(BaseModel):x1: inty1: intx2: inty2: intcls_id: intconf: floatclass TVFrameResult(BaseModel):frame_id: int2 unmodified linesclass Miner:SMALL_CONTAINED_IOA = Constants.SMALL_CONTAINED_IOASMALL_RATIO_MAX = Constants.SMALL_RATIO_MAXSINGLE_PLAYER_HUE_PIVOT = Constants.SINGLE_PLAYER_HUE_PIVOT2 unmodified linesCORNER_CONFIDENCE = Constants.CORNER_CONFIDENCEGOALKEEPER_POSITION_MARGIN = Constants.GOALKEEPER_POSITION_MARGINMIN_SAMPLES_FOR_FIT = 16 # Minimum player crops needed before fitting TeamClassifierMAX_SAMPLES_FOR_FIT = 600 # Maximum samples to avoid overfittingdef __init__(self, path_hf_repo: Path) -> None:try:device = "cuda" if torch.cuda.is_available() else "cpu"model_path = path_hf_repo / "football_object_detection.onnx"self.bbox_model = YOLO(model_path)print("BBox Model Loaded")team_model_path = path_hf_repo / "osnet_model.pth.tar-100"self.team_classifier = TeamClassifier(device=device,batch_size=32,model_name=str(team_model_path))print("Team Classifier Loaded")# Team classification stateself.team_classifier_fitted = Falseself.player_crops_for_fit = []model_kp_path = path_hf_repo / 'keypoint'config_kp_path = path_hf_repo / 'hrnetv2_w48.yaml'cfg_kp = yaml.safe_load(open(config_kp_path, 'r'))loaded_state_kp = torch.load(model_kp_path, map_location=device)model = get_cls_net(cfg_kp)model.load_state_dict(loaded_state_kp)model.to(device)model.eval()self.keypoints_model = modelself.kp_threshold = 0.1self.pitch_batch_size = 4self.health = "healthy"print("✅ Keypoints Model Loaded")except Exception as e:self.health = "❌ Miner initialization failed: " + str(e)print(self.health)def __repr__(self) -> str:if self.health == 'healthy':return (f"health: {self.health}\n"f"BBox Model: {type(self.bbox_model).__name__}\n"f"Keypoints Model: {type(self.keypoints_model).__name__}")else:return self.healthdef _calculate_iou(self, box1: Tuple[float, float, float, float],box2: Tuple[float, float, float, float]) -> float:"""Calculate Intersection over Union (IoU) between two bounding boxes.Args:box1: (x1, y1, x2, y2)box2: (x1, y1, x2, y2)Returns:IoU score (0-1)"""x1_1, y1_1, x2_1, y2_1 = box1x1_2, y1_2, x2_2, y2_2 = box2# Calculate intersection areax_left = max(x1_1, x1_2)y_top = max(y1_1, y1_2)x_right = min(x2_1, x2_2)y_bottom = min(y2_1, y2_2)if x_right < x_left or y_bottom < y_top:return 0.0intersection_area = (x_right - x_left) * (y_bottom - y_top)# Calculate union areabox1_area = (x2_1 - x1_1) * (y2_1 - y1_1)box2_area = (x2_2 - x1_2) * (y2_2 - y1_2)union_area = box1_area + box2_area - intersection_areaif union_area == 0:return 0.0return intersection_area / union_areadef _detect_objects_batch(self, decoded_images: List[ndarray]) -> Dict[int, List[BoundingBox]]:batch_size = 16detection_results = []n_frames = len(decoded_images)for frame_number in range(0, n_frames, batch_size):batch_images = decoded_images[frame_number: frame_number + batch_size]detections = self.bbox_model(batch_images, verbose=False, save=False)detection_results.extend(detections)return detection_resultsdef _team_classify(self, detection_results, decoded_images, offset):self.team_classifier_fitted = Falsestart = time.time()# Collect player crops from first batch for fittingfit_sample_size = 600player_crops_for_fit = []for frame_id in range(len(detection_results)):detection_box = detection_results[frame_id].boxes.dataif len(detection_box) < 4:continue# Collect player boxes for team classification fitting (first batch only)if len(player_crops_for_fit) < fit_sample_size:frame_image = decoded_images[frame_id]for box in detection_box:x1, y1, x2, y2, conf, cls_id = box.tolist()if conf < 0.5:continuemapped_cls_id = str(int(cls_id))# Only collect player crops (cls_id = 2)if mapped_cls_id == '2':crop = frame_image[int(y1):int(y2), int(x1):int(x2)]if crop.size > 0:player_crops_for_fit.append(crop)# Fit team classifier after collecting samplesif self.team_classifier and not self.team_classifier_fitted and len(player_crops_for_fit) >= fit_sample_size:print(f"Fitting TeamClassifier with {len(player_crops_for_fit)} player crops")self.team_classifier.fit(player_crops_for_fit)self.team_classifier_fitted = Truebreakif not self.team_classifier_fitted and len(player_crops_for_fit) >= 16:print(f"Fallback: Fitting TeamClassifier with {len(player_crops_for_fit)} player crops")self.team_classifier.fit(player_crops_for_fit)self.team_classifier_fitted = Trueend = time.time()print(f"Fitting Kmeans time: {end - start}")# Second pass: predict teams with configurable frame skipping optimizationstart = time.time()# Get configuration for frame skippingprediction_interval = 1 # Default: predict every 2 framesiou_threshold = 0.3print(f"Team classification - prediction_interval: {prediction_interval}, iou_threshold: {iou_threshold}")# Storage for predicted frame results: {frame_id: {box_idx: (bbox, team_id)}}predicted_frame_data = {}# Step 1: Predict for frames at prediction_interval onlyframes_to_predict = []for frame_id in range(len(detection_results)):if frame_id % prediction_interval == 0:frames_to_predict.append(frame_id)print(f"Predicting teams for {len(frames_to_predict)}/{len(detection_results)} frames "f"(saving {100 - (len(frames_to_predict) * 100 // len(detection_results))}% compute)")for frame_id in frames_to_predict:detection_box = detection_results[frame_id].boxes.dataframe_image = decoded_images[frame_id]# Collect player crops for this frameframe_player_crops = []frame_player_indices = []frame_player_boxes = []for idx, box in enumerate(detection_box):x1, y1, x2, y2, conf, cls_id = box.tolist()if cls_id == 2 and conf < 0.6:continuemapped_cls_id = str(int(cls_id))# Collect player crops for predictionif self.team_classifier and self.team_classifier_fitted and mapped_cls_id == '2':crop = frame_image[int(y1):int(y2), int(x1):int(x2)]if crop.size > 0:frame_player_crops.append(crop)frame_player_indices.append(idx)frame_player_boxes.append((x1, y1, x2, y2))# Predict teams for all players in this frameif len(frame_player_crops) > 0:team_ids = self.team_classifier.predict(frame_player_crops)predicted_frame_data[frame_id] = {}for idx, bbox, team_id in zip(frame_player_indices, frame_player_boxes, team_ids):# Map team_id (0,1) to cls_id (6,7)team_cls_id = str(6 + int(team_id))predicted_frame_data[frame_id][idx] = (bbox, team_cls_id)# Step 2: Process all frames (interpolate skipped frames)fallback_count = 0interpolated_count = 0bboxes: dict[int, list[BoundingBox]] = {}for frame_id in range(len(detection_results)):detection_box = detection_results[frame_id].boxes.dataframe_image = decoded_images[frame_id]boxes = []team_predictions = {}if frame_id % prediction_interval == 0:# Predicted frame: use pre-computed predictionsif frame_id in predicted_frame_data:for idx, (bbox, team_cls_id) in predicted_frame_data[frame_id].items():team_predictions[idx] = team_cls_idelse:# Skipped frame: interpolate from neighboring predicted frames# Find nearest predicted framesprev_predicted_frame = (frame_id // prediction_interval) * prediction_intervalnext_predicted_frame = prev_predicted_frame + prediction_interval# Collect current frame player boxesfor idx, box in enumerate(detection_box):x1, y1, x2, y2, conf, cls_id = box.tolist()if cls_id == 2 and conf < 0.6:continuemapped_cls_id = str(int(cls_id))if self.team_classifier and self.team_classifier_fitted and mapped_cls_id == '2':target_box = (x1, y1, x2, y2)# Try to match with previous predicted framebest_team_id = Nonebest_iou = 0.0if prev_predicted_frame in predicted_frame_data:team_id, iou = self._find_best_match(target_box,predicted_frame_data[prev_predicted_frame],iou_threshold)if team_id is not None:best_team_id = team_idbest_iou = iou# Try to match with next predicted frame if available and no good match yetif best_team_id is None and next_predicted_frame < len(detection_results):if next_predicted_frame in predicted_frame_data:team_id, iou = self._find_best_match(target_box,predicted_frame_data[next_predicted_frame],iou_threshold)if team_id is not None and iou > best_iou:best_team_id = team_idbest_iou = iou# Track interpolation successif best_team_id is not None:interpolated_count += 1else:# Fallback: if no match found, predict individuallycrop = frame_image[int(y1):int(y2), int(x1):int(x2)]if crop.size > 0:team_id = self.team_classifier.predict([crop])[0]best_team_id = str(6 + int(team_id))fallback_count += 1if best_team_id is not None:team_predictions[idx] = best_team_id# Parse boxes with team classificationfor idx, box in enumerate(detection_box):x1, y1, x2, y2, conf, cls_id = box.tolist()if cls_id == 2 and conf < 0.6:continue# Check overlap with staff boxoverlap_staff = Falsefor idy, boxy in enumerate(detection_box):s_x1, s_y1, s_x2, s_y2, s_conf, s_cls_id = boxy.tolist()if cls_id == 2 and s_cls_id == 4:staff_iou = self._calculate_iou(box[:4], boxy[:4])if staff_iou >= 0.8:overlap_staff = Truebreakif overlap_staff:continuemapped_cls_id = str(int(cls_id))# Override cls_id for players with team predictionif idx in team_predictions:mapped_cls_id = team_predictions[idx]if mapped_cls_id != '4':if int(mapped_cls_id) == 3 and conf < 0.5:continueboxes.append(BoundingBox(x1=int(x1),y1=int(y1),x2=int(x2),y2=int(y2),cls_id=int(mapped_cls_id),conf=float(conf),))# Handle footballs - keep only the best onefootballs = [bb for bb in boxes if int(bb.cls_id) == 0]if len(footballs) > 1:best_ball = max(footballs, key=lambda b: b.conf)boxes = [bb for bb in boxes if int(bb.cls_id) != 0]boxes.append(best_ball)bboxes[offset + frame_id] = boxesreturn bboxesdef predict_batch(self, batch_images: List[ndarray], offset: int, n_keypoints: int) -> List[TVFrameResult]:start = time.time()detection_results = self._detect_objects_batch(batch_images)end = time.time()print(f"Detection time: {end - start}")start = time.time()bboxes = self._team_classify(detection_results, batch_images, offset)end = time.time()print(f"Team classify time: {end - start}")pitch_batch_size = min(self.pitch_batch_size, len(batch_images))keypoints: Dict[int, List[Tuple[int, int]]] = {}start = time.time()while True:gc.collect()if torch.cuda.is_available():torch.cuda.empty_cache()torch.cuda.synchronize()device_str = "cuda"keypoints_result = process_batch_input(batch_images,self.keypoints_model,self.kp_threshold,device_str,batch_size=pitch_batch_size,)if keypoints_result is not None and len(keypoints_result) > 0:for frame_number_in_batch, kp_dict in enumerate(keypoints_result):if frame_number_in_batch >= len(batch_images):breakframe_keypoints: List[Tuple[int, int]] = []try:height, width = batch_images[frame_number_in_batch].shape[:2]if kp_dict is not None and isinstance(kp_dict, dict):for idx in range(32):x, y = 0, 0kp_idx = idx + 1if kp_idx in kp_dict:try:kp_data = kp_dict[kp_idx]if isinstance(kp_data, dict) and "x" in kp_data and "y" in kp_data:x = int(kp_data["x"] * width)y = int(kp_data["y"] * height)except (KeyError, TypeError, ValueError):passframe_keypoints.append((x, y))except (IndexError, ValueError, AttributeError):frame_keypoints = [(0, 0)] * 32if len(frame_keypoints) < n_keypoints:frame_keypoints.extend([(0, 0)] * (n_keypoints - len(frame_keypoints)))else:frame_keypoints = frame_keypoints[:n_keypoints]keypoints[offset + frame_number_in_batch] = frame_keypointsbreakend = time.time()print(f"Keypoint time: {end - start}")results: List[TVFrameResult] = []for frame_number in range(offset, offset + len(batch_images)):frame_boxes = bboxes.get(frame_number, [])frame_keypoints = keypoints.get(frame_number, [(0, 0) for _ in range(n_keypoints)])result = TVFrameResult(frame_id=frame_number,boxes=frame_boxes,keypoints=frame_keypoints,)results.append(result)gc.collect()if torch.cuda.is_available():torch.cuda.empty_cache()torch.cuda.synchronize()return results
miner.py+359-439