Upload folder using huggingface_hub
Browse filesFiles changed (19)
- .gitattributes+3
- README.mdAdded+132
- SV_kp.engineAdded+3
- __pycache__/miner.cpython-310.pycAdded
- config.ymlAdded+25
- detection.ptAdded+3
- football_keypoints_detection.ptAdded+3
- football_object_detection.onnxAdded+3
- football_object_detection.ptAdded+3
- hrnetv2_w48.yamlAdded+35
- keypointAdded+3
- keypoint.ptAdded+3
- miner.pyAdded+429
- objdetect.ptAdded+3
- osnet_ain.pycAdded
- osnet_model.pth.tar-100Added+3
- pitch.pyAdded+669
- team_cluster.pycAdded
- utils.pycAdded
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines33343536373832 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textSV_kp.engine filter=lfs diff=lfs merge=lfs -textosnet_model.pth.tar-100 filter=lfs diff=lfs merge=lfs -textkeypoint filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132🚀 Example Chute for Turbovision 🪂
This repository demonstrates how to deploy a Chute via the Turbovision CLI, hosted on Hugging Face Hub. It serves as a minimal example showcasing the required structure and workflow for integrating machine learning models, preprocessing, and orchestration into a reproducible Chute environment.
## Repository Structure
The following two files must be present (in their current locations) for a successful deployment — their content can be modified as needed:
| File | Purpose ||------|---------|| `miner.py` | Defines the ML model type(s), orchestration, and all pre/postprocessing logic. || `config.yml` | Specifies machine configuration (e.g., GPU type, memory, environment variables). |
Other files — e.g., model weights, utility scripts, or dependencies — are optional and can be included as needed for your model.
> **Note**: Any required assets must be defined or contained within this repo, which is fully open-source, since all network-related operations (downloading challenge data, weights, etc.) are disabled inside the Chute.
## Overview
Below is a high-level diagram showing the interaction between Huggingface, Chutes and Turbovision:
```┌─────────────┐ ┌──────────┐ ┌──────────────┐│ HuggingFace │ ───> │ Chutes │ ───> │ Turbovision ││ Hub │ │ .ai │ │ Validator │└─────────────┘ └──────────┘ └──────────────┘```
## Local Testing
After editing the `config.yml` and `miner.py` and saving it into your Huggingface Repo, you will want to test it works locally.
1. **Copy the template file** `scorevision/chute_template/turbovision_chute.py.j2` as a python file called `my_chute.py` and fill in the missing variables:
```pythonHF_REPO_NAME = "{{ huggingface_repository_name }}"HF_REPO_REVISION = "{{ huggingface_repository_revision }}"CHUTES_USERNAME = "{{ chute_username }}"CHUTE_NAME = "{{ chute_name }}"```
2. **Run the following command to build the chute locally** (Caution: there are known issues with the docker location when running this on a mac):
```bashchutes build my_chute:chute --local --public```
3. **Run the name of the docker image just built** (i.e. `CHUTE_NAME`) and enter it:
```bashdocker run -p 8000:8000 -e CHUTES_EXECUTION_CONTEXT=REMOTE -it <image-name> /bin/bash```
4. **Run the file from within the container**:
```bashchutes run my_chute:chute --dev --debug```
5. **In another terminal, test the local endpoints** to ensure there are no bugs:
```bash# Health checkcurl -X POST http://localhost:8000/health -d '{}'
# Prediction testcurl -X POST http://localhost:8000/predict -d '{"url": "https://scoredata.me/2025_03_14/35ae7a/h1_0f2ca0.mp4","meta": {}}'```
## Live Testing
If you have any chute with the same name (i.e. from a previous deployment), ensure you delete that first (or you will get an error when trying to build).
1. **List existing chutes**:
```bashchutes chutes list```
Take note of the chute id that you wish to delete (if any):
```bashchutes chutes delete <chute-id>```
2. **You should also delete its associated image**:
```bashchutes images list```
Take note of the chute image id:
```bashchutes images delete <chute-image-id>```
3. **Use Turbovision's CLI to build, deploy and commit on-chain**:
```bashsv -vv push```
> **Note**: You can skip the on-chain commit using `--no-commit`. You can also specify a past huggingface revision to point to using `--revision` and/or the local files you want to upload to your huggingface repo using `--model-path`.
4. **When completed, warm up the chute** (if its cold 🧊):
You can confirm its status using `chutes chutes list` or `chutes chutes get <chute-id>` if you already know its id.
> **Note**: Warming up can sometimes take a while but if the chute runs without errors (should be if you've tested locally first) and there are sufficient nodes (i.e. machines) available matching the `config.yml` you specified, the chute should become hot 🔥!
```bashchutes warmup <chute-id>```
5. **Test the chute's endpoints**:
```bash# Health checkcurl -X POST https://<YOUR-CHUTE-SLUG>.chutes.ai/health -d '{}' -H "Authorization: Bearer $CHUTES_API_KEY"
# Predictioncurl -X POST https://<YOUR-CHUTE-SLUG>.chutes.ai/predict -d '{"url": "https://scoredata.me/2025_03_14/35ae7a/h1_0f2ca0.mp4","meta": {}}' -H "Authorization: Bearer $CHUTES_API_KEY"```
6. **Test what your chute would get on a validator**:
This also applies any validation/integrity checks which may fail if you did not use the Turbovision CLI above to deploy the chute:
```bashsv -vv run-once```123version https://git-lfs.github.com/spec/v1oid sha256:f99452eb79e064189e2758abd20a78845a5b639fc8b9c4bc650519c83e13e8dbsize 36828964112345678910111213141516171819202122232425Image: from_base: parachutes/python:3.12 run_command: - pip install --upgrade setuptools wheel - pip install "torch==2.7.1" "torchvision==0.22.1" - pip install "ultralytics==8.3.222" "opencv-python-headless" "numpy" "pydantic" - pip install scikit-learn - pip install onnxruntime-gpu set_workdir: /app
NodeSelector: gpu_count: 1 min_vram_gb_per_gpu: 16 exclude: - "5090" - b200 - h200 - mi300x
Chute: timeout_seconds: 900 concurrency: 4 max_instances: 5 scaling_threshold: 0.5 shutdown_after_seconds: 3600123version https://git-lfs.github.com/spec/v1oid sha256:2ad3e89b658d2626c34174f6799d240ffd37cfe45752c0ce6ef73b05935042e0size 52014742123version https://git-lfs.github.com/spec/v1oid sha256:6dd10dba85895c92760cdb5a99c5cfca899c68f361a66c5448f38a187280ee1fsize 6849672123version https://git-lfs.github.com/spec/v1oid sha256:7b51470cb703f5a9a789df38674b67d4bbe7f8f31846d69dbc97ce484f790cf9size 10245169123version https://git-lfs.github.com/spec/v1oid sha256:8bbacfcb38e38b1b8816788e9e6e845160533719a0b87b693d58b932380d0d28size 1529616871234567891011121314151617181920212223242526272829303132333435MODEL:
IMAGE_SIZE: [960, 540]
NUM_JOINTS: 58
PRETRAIN: ''
EXTRA:
FINAL_CONV_KERNEL: 1
STAGE1:
NUM_MODULES: 1
NUM_BRANCHES: 1
BLOCK: BOTTLENECK
NUM_BLOCKS: [4]
NUM_CHANNELS: [64]
FUSE_METHOD: SUM
STAGE2:
NUM_MODULES: 1
NUM_BRANCHES: 2
BLOCK: BASIC
NUM_BLOCKS: [4, 4]
NUM_CHANNELS: [48, 96]
FUSE_METHOD: SUM
STAGE3:
NUM_MODULES: 4
NUM_BRANCHES: 3
BLOCK: BASIC
NUM_BLOCKS: [4, 4, 4]
NUM_CHANNELS: [48, 96, 192]
FUSE_METHOD: SUM
STAGE4:
NUM_MODULES: 3
NUM_BRANCHES: 4
BLOCK: BASIC
NUM_BLOCKS: [4, 4, 4, 4]
NUM_CHANNELS: [48, 96, 192, 384]
FUSE_METHOD: SUM
123version https://git-lfs.github.com/spec/v1oid sha256:7ea78fa76aaf94976a8eca428d6e3c59697a93430cba1a4603e20284b61f5113size 264964645123version https://git-lfs.github.com/spec/v1oid sha256:6dd10dba85895c92760cdb5a99c5cfca899c68f361a66c5448f38a187280ee1fsize 6849672123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429from pathlib import Pathfrom typing import List, Tuple, Dictimport sysimport os
from 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 yaml
class BoundingBox(BaseModel): x1: int y1: int x2: int y2: int cls_id: int conf: float
class TVFrameResult(BaseModel): frame_id: int boxes: List[BoundingBox] keypoints: List[Tuple[int, int]]
class Miner: SMALL_CONTAINED_IOA = Constants.SMALL_CONTAINED_IOA SMALL_RATIO_MAX = Constants.SMALL_RATIO_MAX SINGLE_PLAYER_HUE_PIVOT = Constants.SINGLE_PLAYER_HUE_PIVOT CORNER_INDICES = Constants.CORNER_INDICES KEYPOINTS_CONFIDENCE = Constants.KEYPOINTS_CONFIDENCE CORNER_CONFIDENCE = Constants.CORNER_CONFIDENCE GOALKEEPER_POSITION_MARGIN = Constants.GOALKEEPER_POSITION_MARGIN MIN_SAMPLES_FOR_FIT = 16 # Minimum player crops needed before fitting TeamClassifier MAX_SAMPLES_FOR_FIT = 600 # Maximum samples to avoid overfitting
def __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 state self.team_classifier_fitted = False self.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 = model self.kp_threshold = 0.1 self.pitch_batch_size = 4 self.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.health
def _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 = box1 x1_2, y1_2, x2_2, y2_2 = box2
# Calculate intersection area x_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.0
intersection_area = (x_right - x_left) * (y_bottom - y_top)
# Calculate union area box1_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_area
if union_area == 0: return 0.0
return intersection_area / union_area
def _detect_objects_batch(self, decoded_images: List[ndarray]) -> Dict[int, List[BoundingBox]]: batch_size = 16 detection_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_results
def _team_classify(self, detection_results, decoded_images, offset): self.team_classifier_fitted = False start = time.time() # Collect player crops from first batch for fitting fit_sample_size = 600 player_crops_for_fit = []
for frame_id in range(len(detection_results)): detection_box = detection_results[frame_id].boxes.data if 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: continue mapped_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 samples if 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 = True break if 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 = True end = time.time() print(f"Fitting Kmeans time: {end - start}")
# Second pass: predict teams with configurable frame skipping optimization start = time.time()
# Get configuration for frame skipping prediction_interval = 1 # Default: predict every 2 frames iou_threshold = 0.3
print(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 only frames_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.data frame_image = decoded_images[frame_id]
# Collect player crops for this frame frame_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: continue mapped_cls_id = str(int(cls_id))
# Collect player crops for prediction if 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 frame if 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 = 0 interpolated_count = 0 bboxes: dict[int, list[BoundingBox]] = {} for frame_id in range(len(detection_results)): detection_box = detection_results[frame_id].boxes.data frame_image = decoded_images[frame_id] boxes = []
team_predictions = {}
if frame_id % prediction_interval == 0: # Predicted frame: use pre-computed predictions if frame_id in predicted_frame_data: for idx, (bbox, team_cls_id) in predicted_frame_data[frame_id].items(): team_predictions[idx] = team_cls_id else: # Skipped frame: interpolate from neighboring predicted frames # Find nearest predicted frames prev_predicted_frame = (frame_id // prediction_interval) * prediction_interval next_predicted_frame = prev_predicted_frame + prediction_interval
# Collect current 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: continue mapped_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 frame best_team_id = None best_iou = 0.0
if 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_id best_iou = iou
# Try to match with next predicted frame if available and no good match yet if 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_id best_iou = iou
# Track interpolation success if best_team_id is not None: interpolated_count += 1 else: # Fallback: if no match found, predict individually crop = 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 += 1
if best_team_id is not None: team_predictions[idx] = best_team_id
# Parse boxes with team classification for 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 box overlap_staff = False for 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 = True break if overlap_staff: continue
mapped_cls_id = str(int(cls_id))
# Override cls_id for players with team prediction if 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: continue boxes.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 one footballs = [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] = boxes return bboxes
def 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): break frame_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, 0 kp_idx = idx + 1 if 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): pass frame_keypoints.append((x, y)) except (IndexError, ValueError, AttributeError): frame_keypoints = [(0, 0)] * 32 if 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_keypoints break end = 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 results123version https://git-lfs.github.com/spec/v1oid sha256:8bbacfcb38e38b1b8816788e9e6e845160533719a0b87b693d58b932380d0d28size 152961687123version https://git-lfs.github.com/spec/v1oid sha256:64873ef0e8abf28df31facd113f27634e2d085a2dcf8d19123409b1d0e2566c8size 36189526123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669from __future__ import absolute_importfrom __future__ import divisionfrom __future__ import print_function
import osimport sysimport timefrom typing import List, Optional, Tuple
import cv2import numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as Fimport torchvision.transforms as Timport torchvision.transforms.functional as ffrom pydantic import BaseModel
import logginglogger = logging.getLogger(__name__)
class BoundingBox(BaseModel): x1: int y1: int x2: int y2: int cls_id: int conf: float
class TVFrameResult(BaseModel): frame_id: int boxes: list[BoundingBox] keypoints: list[tuple[int, int]]
BatchNorm2d = nn.BatchNorm2dBN_MOMENTUM = 0.1
def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
class BasicBlock(nn.Module): expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = BatchNorm2d(planes, momentum=BN_MOMENTUM) self.relu = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes) self.bn2 = BatchNorm2d(planes, momentum=BN_MOMENTUM) self.downsample = downsample self.stride = stride
def forward(self, x): residual = x
out = self.conv1(x) out = self.bn1(out) out = self.relu(out)
out = self.conv2(out) out = self.bn2(out)
if self.downsample is not None: residual = self.downsample(x)
out += residual out = self.relu(out)
return out
class Bottleneck(nn.Module): expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = BatchNorm2d(planes, momentum=BN_MOMENTUM) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn2 = BatchNorm2d(planes, momentum=BN_MOMENTUM) self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1, bias=False) self.bn3 = BatchNorm2d(planes * self.expansion, momentum=BN_MOMENTUM) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride
def forward(self, x): residual = x
out = self.conv1(x) out = self.bn1(out) out = self.relu(out)
out = self.conv2(out) out = self.bn2(out) out = self.relu(out)
out = self.conv3(out) out = self.bn3(out)
if self.downsample is not None: residual = self.downsample(x)
out += residual out = self.relu(out)
return out
class HighResolutionModule(nn.Module): def __init__(self, num_branches, blocks, num_blocks, num_inchannels, num_channels, fuse_method, multi_scale_output=True): super(HighResolutionModule, self).__init__() self._check_branches( num_branches, blocks, num_blocks, num_inchannels, num_channels)
self.num_inchannels = num_inchannels self.fuse_method = fuse_method self.num_branches = num_branches
self.multi_scale_output = multi_scale_output
self.branches = self._make_branches( num_branches, blocks, num_blocks, num_channels) self.fuse_layers = self._make_fuse_layers() self.relu = nn.ReLU(inplace=True)
def _check_branches(self, num_branches, blocks, num_blocks, num_inchannels, num_channels): if num_branches != len(num_blocks): error_msg = 'NUM_BRANCHES({}) <> NUM_BLOCKS({})'.format( num_branches, len(num_blocks)) logger.error(error_msg) raise ValueError(error_msg)
if num_branches != len(num_channels): error_msg = 'NUM_BRANCHES({}) <> NUM_CHANNELS({})'.format( num_branches, len(num_channels)) logger.error(error_msg) raise ValueError(error_msg)
if num_branches != len(num_inchannels): error_msg = 'NUM_BRANCHES({}) <> NUM_INCHANNELS({})'.format( num_branches, len(num_inchannels)) logger.error(error_msg) raise ValueError(error_msg)
def _make_one_branch(self, branch_index, block, num_blocks, num_channels, stride=1): downsample = None if stride != 1 or \ self.num_inchannels[branch_index] != num_channels[branch_index] * block.expansion: downsample = nn.Sequential( nn.Conv2d(self.num_inchannels[branch_index], num_channels[branch_index] * block.expansion, kernel_size=1, stride=stride, bias=False), BatchNorm2d(num_channels[branch_index] * block.expansion, momentum=BN_MOMENTUM), )
layers = [] layers.append(block(self.num_inchannels[branch_index], num_channels[branch_index], stride, downsample)) self.num_inchannels[branch_index] = \ num_channels[branch_index] * block.expansion for i in range(1, num_blocks[branch_index]): layers.append(block(self.num_inchannels[branch_index], num_channels[branch_index]))
return nn.Sequential(*layers)
def _make_branches(self, num_branches, block, num_blocks, num_channels): branches = []
for i in range(num_branches): branches.append( self._make_one_branch(i, block, num_blocks, num_channels))
return nn.ModuleList(branches)
def _make_fuse_layers(self): if self.num_branches == 1: return None
num_branches = self.num_branches num_inchannels = self.num_inchannels fuse_layers = [] for i in range(num_branches if self.multi_scale_output else 1): fuse_layer = [] for j in range(num_branches): if j > i: fuse_layer.append(nn.Sequential( nn.Conv2d(num_inchannels[j], num_inchannels[i], 1, 1, 0, bias=False), BatchNorm2d(num_inchannels[i], momentum=BN_MOMENTUM))) # nn.Upsample(scale_factor=2**(j-i), mode='nearest'))) elif j == i: fuse_layer.append(None) else: conv3x3s = [] for k in range(i - j): if k == i - j - 1: num_outchannels_conv3x3 = num_inchannels[i] conv3x3s.append(nn.Sequential( nn.Conv2d(num_inchannels[j], num_outchannels_conv3x3, 3, 2, 1, bias=False), BatchNorm2d(num_outchannels_conv3x3, momentum=BN_MOMENTUM))) else: num_outchannels_conv3x3 = num_inchannels[j] conv3x3s.append(nn.Sequential( nn.Conv2d(num_inchannels[j], num_outchannels_conv3x3, 3, 2, 1, bias=False), BatchNorm2d(num_outchannels_conv3x3, momentum=BN_MOMENTUM), nn.ReLU(inplace=True))) fuse_layer.append(nn.Sequential(*conv3x3s)) fuse_layers.append(nn.ModuleList(fuse_layer))
return nn.ModuleList(fuse_layers)
def get_num_inchannels(self): return self.num_inchannels
def forward(self, x): if self.num_branches == 1: return [self.branches[0](x[0])]
for i in range(self.num_branches): x[i] = self.branches[i](x[i])
x_fuse = [] for i in range(len(self.fuse_layers)): y = x[0] if i == 0 else self.fuse_layers[i][0](x[0]) for j in range(1, self.num_branches): if i == j: y = y + x[j] elif j > i: y = y + F.interpolate( self.fuse_layers[i][j](x[j]), size=[x[i].shape[2], x[i].shape[3]], mode='bilinear') else: y = y + self.fuse_layers[i][j](x[j]) x_fuse.append(self.relu(y))
return x_fuse
blocks_dict = { 'BASIC': BasicBlock, 'BOTTLENECK': Bottleneck}
class HighResolutionNet(nn.Module):
def __init__(self, config, **kwargs): self.inplanes = 64 extra = config['MODEL']['EXTRA'] super(HighResolutionNet, self).__init__()
# stem net self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=3, stride=2, padding=1, bias=False) self.bn1 = BatchNorm2d(self.inplanes, momentum=BN_MOMENTUM) self.conv2 = nn.Conv2d(self.inplanes, self.inplanes, kernel_size=3, stride=2, padding=1, bias=False) self.bn2 = BatchNorm2d(self.inplanes, momentum=BN_MOMENTUM) self.relu = nn.ReLU(inplace=True) self.sf = nn.Softmax(dim=1) self.layer1 = self._make_layer(Bottleneck, 64, 64, 4)
self.stage2_cfg = extra['STAGE2'] num_channels = self.stage2_cfg['NUM_CHANNELS'] block = blocks_dict[self.stage2_cfg['BLOCK']] num_channels = [ num_channels[i] * block.expansion for i in range(len(num_channels))] self.transition1 = self._make_transition_layer( [256], num_channels) self.stage2, pre_stage_channels = self._make_stage( self.stage2_cfg, num_channels)
self.stage3_cfg = extra['STAGE3'] num_channels = self.stage3_cfg['NUM_CHANNELS'] block = blocks_dict[self.stage3_cfg['BLOCK']] num_channels = [ num_channels[i] * block.expansion for i in range(len(num_channels))] self.transition2 = self._make_transition_layer( pre_stage_channels, num_channels) self.stage3, pre_stage_channels = self._make_stage( self.stage3_cfg, num_channels)
self.stage4_cfg = extra['STAGE4'] num_channels = self.stage4_cfg['NUM_CHANNELS'] block = blocks_dict[self.stage4_cfg['BLOCK']] num_channels = [ num_channels[i] * block.expansion for i in range(len(num_channels))] self.transition3 = self._make_transition_layer( pre_stage_channels, num_channels) self.stage4, pre_stage_channels = self._make_stage( self.stage4_cfg, num_channels, multi_scale_output=True)
self.upsample = nn.Upsample(scale_factor=2, mode='nearest') final_inp_channels = sum(pre_stage_channels) + self.inplanes
self.head = nn.Sequential(nn.Sequential( nn.Conv2d( in_channels=final_inp_channels, out_channels=final_inp_channels, kernel_size=1), BatchNorm2d(final_inp_channels, momentum=BN_MOMENTUM), nn.ReLU(inplace=True), nn.Conv2d( in_channels=final_inp_channels, out_channels=config['MODEL']['NUM_JOINTS'], kernel_size=extra['FINAL_CONV_KERNEL']), nn.Softmax(dim=1)))
def _make_head(self, x, x_skip): x = self.upsample(x) x = torch.cat([x, x_skip], dim=1) x = self.head(x)
return x
def _make_transition_layer( self, num_channels_pre_layer, num_channels_cur_layer): num_branches_cur = len(num_channels_cur_layer) num_branches_pre = len(num_channels_pre_layer)
transition_layers = [] for i in range(num_branches_cur): if i < num_branches_pre: if num_channels_cur_layer[i] != num_channels_pre_layer[i]: transition_layers.append(nn.Sequential( nn.Conv2d(num_channels_pre_layer[i], num_channels_cur_layer[i], 3, 1, 1, bias=False), BatchNorm2d( num_channels_cur_layer[i], momentum=BN_MOMENTUM), nn.ReLU(inplace=True))) else: transition_layers.append(None) else: conv3x3s = [] for j in range(i + 1 - num_branches_pre): inchannels = num_channels_pre_layer[-1] outchannels = num_channels_cur_layer[i] \ if j == i - num_branches_pre else inchannels conv3x3s.append(nn.Sequential( nn.Conv2d( inchannels, outchannels, 3, 2, 1, bias=False), BatchNorm2d(outchannels, momentum=BN_MOMENTUM), nn.ReLU(inplace=True))) transition_layers.append(nn.Sequential(*conv3x3s))
return nn.ModuleList(transition_layers)
def _make_layer(self, block, inplanes, planes, blocks, stride=1): downsample = None if stride != 1 or inplanes != planes * block.expansion: downsample = nn.Sequential( nn.Conv2d(inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False), BatchNorm2d(planes * block.expansion, momentum=BN_MOMENTUM), )
layers = [] layers.append(block(inplanes, planes, stride, downsample)) inplanes = planes * block.expansion for i in range(1, blocks): layers.append(block(inplanes, planes))
return nn.Sequential(*layers)
def _make_stage(self, layer_config, num_inchannels, multi_scale_output=True): num_modules = layer_config['NUM_MODULES'] num_branches = layer_config['NUM_BRANCHES'] num_blocks = layer_config['NUM_BLOCKS'] num_channels = layer_config['NUM_CHANNELS'] block = blocks_dict[layer_config['BLOCK']] fuse_method = layer_config['FUSE_METHOD']
modules = [] for i in range(num_modules): # multi_scale_output is only used last module if not multi_scale_output and i == num_modules - 1: reset_multi_scale_output = False else: reset_multi_scale_output = True modules.append( HighResolutionModule(num_branches, block, num_blocks, num_inchannels, num_channels, fuse_method, reset_multi_scale_output) ) num_inchannels = modules[-1].get_num_inchannels()
return nn.Sequential(*modules), num_inchannels
def forward(self, x): # h, w = x.size(2), x.size(3) x = self.conv1(x) x_skip = x.clone() x = self.bn1(x) x = self.relu(x) x = self.conv2(x) x = self.bn2(x) x = self.relu(x) x = self.layer1(x)
x_list = [] for i in range(self.stage2_cfg['NUM_BRANCHES']): if self.transition1[i] is not None: x_list.append(self.transition1[i](x)) else: x_list.append(x) y_list = self.stage2(x_list)
x_list = [] for i in range(self.stage3_cfg['NUM_BRANCHES']): if self.transition2[i] is not None: x_list.append(self.transition2[i](y_list[-1])) else: x_list.append(y_list[i]) y_list = self.stage3(x_list)
x_list = [] for i in range(self.stage4_cfg['NUM_BRANCHES']): if self.transition3[i] is not None: x_list.append(self.transition3[i](y_list[-1])) else: x_list.append(y_list[i]) x = self.stage4(x_list)
# Head Part height, width = x[0].size(2), x[0].size(3) x1 = F.interpolate(x[1], size=(height, width), mode='bilinear', align_corners=False) x2 = F.interpolate(x[2], size=(height, width), mode='bilinear', align_corners=False) x3 = F.interpolate(x[3], size=(height, width), mode='bilinear', align_corners=False) x = torch.cat([x[0], x1, x2, x3], 1) x = self._make_head(x, x_skip)
return x
def init_weights(self, pretrained=''): for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') #nn.init.normal_(m.weight, std=0.001) #nn.init.constant_(m.bias, 0) elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) if pretrained != '': if os.path.isfile(pretrained): pretrained_dict = torch.load(pretrained) model_dict = self.state_dict() pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict.keys()} model_dict.update(pretrained_dict) self.load_state_dict(model_dict) else: sys.exit(f'Weights {pretrained} not found.')
def get_cls_net(config, pretrained='', **kwargs): """Create keypoint detection model with softmax activation""" model = HighResolutionNet(config, **kwargs) model.init_weights(pretrained) return model
def get_cls_net_l(config, pretrained='', **kwargs): """Create line detection model with sigmoid activation""" model = HighResolutionNet(config, **kwargs) model.init_weights(pretrained) # After loading weights, replace just the activation function # The saved model expects the nested Sequential structure inner_seq = model.head[0] # Replace softmax (index 4) with sigmoid model.head[0][4] = nn.Sigmoid() return model
# Simplified utility functions - removed complex Gaussian generation functions# These were mainly used for training data generation, not inference
# generate_gaussian_array_vectorized_dist_l function removed - not used in current implementation@torch.inference_mode()def run_inference(model, input_tensor: torch.Tensor, device): input_tensor = input_tensor.to(device).to(memory_format=torch.channels_last) output = model.module().forward(input_tensor) return output
def preprocess_batch_fast(frames): """Ultra-fast batch preprocessing using optimized tensor operations""" target_size = (540, 960) # H, W format for model input batch = [] for i, frame in enumerate(frames): frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) img = cv2.resize(frame_rgb, (target_size[1], target_size[0])) img = img.astype(np.float32) / 255.0 img = np.transpose(img, (2, 0, 1)) # HWC -> CHW batch.append(img) batch = torch.from_numpy(np.stack(batch)).float()
return batch
def extract_keypoints_from_heatmap(heatmap: torch.Tensor, scale: int = 2, max_keypoints: int = 1): """Optimized keypoint extraction from heatmaps""" batch_size, n_channels, height, width = heatmap.shape # Find local maxima using max pooling (keep on GPU) kernel = 3 pad = 1 max_pooled = F.max_pool2d(heatmap, kernel, stride=1, padding=pad) local_maxima = (max_pooled == heatmap) heatmap = heatmap * local_maxima # Get top keypoints (keep on GPU longer) scores, indices = torch.topk(heatmap.view(batch_size, n_channels, -1), max_keypoints, sorted=False) y_coords = torch.div(indices, width, rounding_mode="floor") x_coords = indices % width # Optimized tensor operations x_coords = x_coords * scale y_coords = y_coords * scale # Create result tensor directly on GPU results = torch.stack([x_coords.float(), y_coords.float(), scores], dim=-1) return results
def extract_keypoints_from_heatmap_fast(heatmap: torch.Tensor, scale: int = 2, max_keypoints: int = 1): """Ultra-fast keypoint extraction optimized for speed""" batch_size, n_channels, height, width = heatmap.shape # Simplified local maxima detection (faster but slightly less accurate) max_pooled = F.max_pool2d(heatmap, 3, stride=1, padding=1) local_maxima = (max_pooled == heatmap) # Apply mask and get top keypoints in one go masked_heatmap = heatmap * local_maxima flat_heatmap = masked_heatmap.view(batch_size, n_channels, -1) scores, indices = torch.topk(flat_heatmap, max_keypoints, dim=-1, sorted=False) # Vectorized coordinate calculation y_coords = torch.div(indices, width, rounding_mode="floor") * scale x_coords = (indices % width) * scale # Stack results efficiently results = torch.stack([x_coords.float(), y_coords.float(), scores], dim=-1) return results
def process_keypoints_vectorized(kp_coords, kp_threshold, w, h, batch_size): """Ultra-fast vectorized keypoint processing""" batch_results = [] # Convert to numpy once for faster CPU operations kp_np = kp_coords.cpu().numpy() for batch_idx in range(batch_size): kp_dict = {} # Vectorized threshold check valid_kps = kp_np[batch_idx, :, 0, 2] > kp_threshold valid_indices = np.where(valid_kps)[0] for ch_idx in valid_indices: x = float(kp_np[batch_idx, ch_idx, 0, 0]) / w y = float(kp_np[batch_idx, ch_idx, 0, 1]) / h p = float(kp_np[batch_idx, ch_idx, 0, 2]) kp_dict[ch_idx + 1] = {'x': x, 'y': y, 'p': p} batch_results.append(kp_dict) return batch_results
def inference_batch(frames, model, kp_threshold, device, batch_size=8): """Optimized batch inference for multiple frames""" results = [] num_frames = len(frames) # Get the device from the model itself model_device = next(model.parameters()).device # Process all frames in optimally-sized batches for i in range(0, num_frames, batch_size): current_batch_size = min(batch_size, num_frames - i) batch_frames = frames[i:i + current_batch_size] # Fast preprocessing - create on CPU first batch = preprocess_batch_fast(batch_frames) b, c, h, w = batch.size() # Move batch to model device batch = batch.to(model_device)
with torch.no_grad(): heatmaps = model(batch)
# Ultra-fast keypoint extraction kp_coords = extract_keypoints_from_heatmap_fast(heatmaps[:,:-1,:,:], scale=2, max_keypoints=1) # Vectorized batch processing - no loops batch_results = process_keypoints_vectorized(kp_coords, kp_threshold, 960, 540, current_batch_size) results.extend(batch_results) # Minimal cleanup del heatmaps, kp_coords, batch return results
# Keypoint mapping from detection indices to standard football pitch keypoint IDsmap_keypoints = { 1: 1, 2: 14, 3: 25, 4: 2, 5: 10, 6: 18, 7: 26, 8: 3, 9: 7, 10: 23, 11: 27, 20: 4, 21: 8, 22: 24, 23: 28, 24: 5, 25: 13, 26: 21, 27: 29, 28: 6, 29: 17, 30: 30, 31: 11, 32: 15, 33: 19, 34: 12, 35: 16, 36: 20, 45: 9, 50: 31, 52: 32, 57: 22}
def get_mapped_keypoints(kp_points): """Apply keypoint mapping to detection results""" mapped_points = {} for key, value in kp_points.items(): if key in map_keypoints: mapped_key = map_keypoints[key] mapped_points[mapped_key] = value # else: # Keep unmapped keypoints with original key # mapped_points[key] = value return mapped_points
def process_batch_input(frames, model, kp_threshold, device, batch_size=16): """Process multiple input images in batch""" # Batch inference kp_results = inference_batch(frames, model, kp_threshold, device, batch_size) kp_results = [get_mapped_keypoints(kp) for kp in kp_results]
return kp_results.gitattributes+3
README.mdAdded+132
SV_kp.engineAdded+3
__pycache__/miner.cpython-310.pycAdded
config.ymlAdded+25
detection.ptAdded+3
football_keypoints_detection.ptAdded+3
football_object_detection.onnxAdded+3
football_object_detection.ptAdded+3
hrnetv2_w48.yamlAdded+35
keypointAdded+3
keypoint.ptAdded+3
miner.pyAdded+429
objdetect.ptAdded+3
osnet_ain.pycAdded
osnet_model.pth.tar-100Added+3
pitch.pyAdded+669
team_cluster.pycAdded
utils.pycAdded