tarto2 commited on
Commit
d90e4a2
·
verified ·
1 Parent(s): 295539d

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -1,35 +1,37 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ SV_kp.engine filter=lfs diff=lfs merge=lfs -text
37
+ keypoint filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚀 Example Chute for Turbovision 🪂
2
+
3
+ This repository demonstrates how to deploy a **Chute** via the **Turbovision CLI**, hosted on **Hugging Face Hub**.
4
+ 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.
5
+
6
+ ## Repository Structure
7
+ The following two files **must be present** (in their current locations) for a successful deployment — their content can be modified as needed:
8
+
9
+ | File | Purpose |
10
+ |------|----------|
11
+ | `miner.py` | Defines the ML model type(s), orchestration, and all pre/postprocessing logic. |
12
+ | `config.yml` | Specifies machine configuration (e.g., GPU type, memory, environment variables). |
13
+
14
+ 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**
15
+
16
+ ## Overview
17
+
18
+ Below is a high-level diagram showing the interaction between Huggingface, Chutes and Turbovision:
19
+
20
+ ![](../images/miner.png)
21
+
22
+ ## Local Testing
23
+ After editing the `config.yml` and `miner.py` and saving it into your Huggingface Repo, you will want to test it works locally.
24
+
25
+ 1. Copy the file `scorevision/chute_tmeplate/turbovision_chute.py.j2` as a python file called `my_chute.py` and fill in the missing variables:
26
+ ```python
27
+ HF_REPO_NAME = "{{ huggingface_repository_name }}"
28
+ HF_REPO_REVISION = "{{ huggingface_repository_revision }}"
29
+ CHUTES_USERNAME = "{{ chute_username }}"
30
+ CHUTE_NAME = "{{ chute_name }}"
31
+ ```
32
+
33
+ 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)
34
+ ```bash
35
+ chutes build my_chute:chute --local --public
36
+ ```
37
+
38
+ 3. Run the name of the docker image just built (i.e. `CHUTE_NAME`) and enter it
39
+ ```bash
40
+ docker run -p 8000:8000 -e CHUTES_EXECUTION_CONTEXT=REMOTE -it <image-name> /bin/bash
41
+ ```
42
+
43
+ 4. Run the file from within the container
44
+ ```bash
45
+ chutes run my_chute:chute --dev --debug
46
+ ```
47
+
48
+ 5. In another terminal, test the local endpoints to ensure there are no bugs
49
+ ```bash
50
+ curl -X POST http://localhost:8000/health -d '{}'
51
+ curl -X POST http://localhost:8000/predict -d '{"url": "https://scoredata.me/2025_03_14/35ae7a/h1_0f2ca0.mp4","meta": {}}'
52
+ ```
53
+
54
+ ## Live Testing
55
+ 1. If you have any chute with the same name (ie from a previous deployment), ensure you delete that first (or you will get an error when trying to build).
56
+ ```bash
57
+ chutes chutes list
58
+ ```
59
+ Take note of the chute id that you wish to delete (if any)
60
+ ```bash
61
+ chutes chutes delete <chute-id>
62
+ ```
63
+
64
+ You should also delete its associated image
65
+ ```bash
66
+ chutes images list
67
+ ```
68
+ Take note of the chute image id
69
+ ```bash
70
+ chutes images delete <chute-image-id>
71
+ ```
72
+
73
+ 2. Use Turbovision's CLI to build, deploy and commit on-chain (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`)
74
+ ```bash
75
+ sv -vv push
76
+ ```
77
+
78
+ 3. 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 🔥!
79
+ ```bash
80
+ chutes warmup <chute-id>
81
+ ```
82
+
83
+ 4. Test the chute's endpoints
84
+ ```bash
85
+ curl -X POST https://<YOUR-CHUTE-SLUG>.chutes.ai/health -d '{}' -H "Authorization: Bearer $CHUTES_API_KEY"
86
+ curl -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"
87
+ ```
88
+
89
+ 5. 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)
90
+ ```bash
91
+ sv -vv run-once
92
+ ```
SV_kp.engine ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f99452eb79e064189e2758abd20a78845a5b639fc8b9c4bc650519c83e13e8db
3
+ size 368289641
__pycache__/miner.cpython-312.pyc ADDED
Binary file (12.1 kB). View file
 
__pycache__/miner.cpython-313.pyc ADDED
Binary file (22.6 kB). View file
 
__pycache__/pitch.cpython-312.pyc ADDED
Binary file (30.9 kB). View file
 
__pycache__/pitch.cpython-313.pyc ADDED
Binary file (30.8 kB). View file
 
__pycache__/player.cpython-312.pyc ADDED
Binary file (16.6 kB). View file
 
config.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Image:
2
+ from_base: parachutes/python:3.12
3
+ run_command:
4
+ - pip install --upgrade setuptools wheel
5
+ - pip install "ultralytics==8.3.222" "opencv-python-headless" "numpy" "pydantic"
6
+ - pip install "tensorflow" "torch==2.7.1" "torchvision==0.22.1" "torch-tensorrt==2.7"
7
+ set_workdir: /app
8
+
9
+ NodeSelector:
10
+ gpu_count: 1
11
+ min_vram_gb_per_gpu: 16
12
+ exclude:
13
+ - "5090"
14
+ - b200
15
+ - h200
16
+ - mi300x
17
+
18
+ Chute:
19
+ timeout_seconds: 900
20
+ concurrency: 4
21
+ max_instances: 5
22
+ scaling_threshold: 0.5
hrnetv2_w48.yaml ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MODEL:
2
+ IMAGE_SIZE: [960, 540]
3
+ NUM_JOINTS: 58
4
+ PRETRAIN: ''
5
+ EXTRA:
6
+ FINAL_CONV_KERNEL: 1
7
+ STAGE1:
8
+ NUM_MODULES: 1
9
+ NUM_BRANCHES: 1
10
+ BLOCK: BOTTLENECK
11
+ NUM_BLOCKS: [4]
12
+ NUM_CHANNELS: [64]
13
+ FUSE_METHOD: SUM
14
+ STAGE2:
15
+ NUM_MODULES: 1
16
+ NUM_BRANCHES: 2
17
+ BLOCK: BASIC
18
+ NUM_BLOCKS: [4, 4]
19
+ NUM_CHANNELS: [48, 96]
20
+ FUSE_METHOD: SUM
21
+ STAGE3:
22
+ NUM_MODULES: 4
23
+ NUM_BRANCHES: 3
24
+ BLOCK: BASIC
25
+ NUM_BLOCKS: [4, 4, 4]
26
+ NUM_CHANNELS: [48, 96, 192]
27
+ FUSE_METHOD: SUM
28
+ STAGE4:
29
+ NUM_MODULES: 3
30
+ NUM_BRANCHES: 4
31
+ BLOCK: BASIC
32
+ NUM_BLOCKS: [4, 4, 4, 4]
33
+ NUM_CHANNELS: [48, 96, 192, 384]
34
+ FUSE_METHOD: SUM
35
+
keypoint ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7ea78fa76aaf94976a8eca428d6e3c59697a93430cba1a4603e20284b61f5113
3
+ size 264964645
miner.py ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ from typing import List, Tuple, Dict
3
+ import sys
4
+ import os
5
+
6
+ from numpy import ndarray
7
+ import numpy as np
8
+ from pydantic import BaseModel
9
+ import cv2
10
+
11
+ sys.path.append(os.path.dirname(os.path.abspath(__file__)))
12
+
13
+ os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
14
+ os.environ["OMP_NUM_THREADS"] = "16"
15
+ os.environ["TF_NUM_INTRAOP_THREADS"] = "16"
16
+ os.environ["TF_NUM_INTEROP_THREADS"] = "2"
17
+ os.environ["CUDA_LAUNCH_BLOCKING"] = "0"
18
+ os.environ["ORT_LOGGING_LEVEL"] = "3"
19
+ os.environ["TF_ENABLE_ONEDNN_OPTS"] = "0"
20
+
21
+ import logging
22
+ import tensorflow as tf
23
+ from tensorflow.keras import mixed_precision
24
+ import torch._dynamo
25
+ import torch
26
+ # import torch_tensorrt
27
+ import gc
28
+ from ultralytics import YOLO
29
+ from pitch import process_batch_input, get_cls_net
30
+ import yaml
31
+
32
+ logging.getLogger("tensorflow").setLevel(logging.ERROR)
33
+ tf.config.threading.set_intra_op_parallelism_threads(16)
34
+ tf.config.threading.set_inter_op_parallelism_threads(2)
35
+ tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
36
+ tf.get_logger().setLevel("ERROR")
37
+ tf.autograph.set_verbosity(0)
38
+ mixed_precision.set_global_policy("mixed_float16")
39
+ tf.config.optimizer.set_jit(True)
40
+ torch._dynamo.config.suppress_errors = True
41
+
42
+
43
+ class BoundingBox(BaseModel):
44
+ x1: int
45
+ y1: int
46
+ x2: int
47
+ y2: int
48
+ cls_id: int
49
+ conf: float
50
+
51
+
52
+ class TVFrameResult(BaseModel):
53
+ frame_id: int
54
+ boxes: List[BoundingBox]
55
+ keypoints: List[Tuple[int, int]]
56
+
57
+
58
+ class Miner:
59
+ QUASI_TOTAL_IOA: float = 0.90
60
+ SMALL_CONTAINED_IOA: float = 0.85
61
+ SMALL_RATIO_MAX: float = 0.50
62
+ SINGLE_PLAYER_HUE_PIVOT: float = 90.0
63
+
64
+ def __init__(self, path_hf_repo: Path) -> None:
65
+ print(path_hf_repo / "objdetect.pt")
66
+ self.bbox_model = YOLO(path_hf_repo / "objdetect.pt")
67
+ print(" BBox Model (objdetect.pt) Loaded")
68
+ device = "cuda" if torch.cuda.is_available() else "cpu"
69
+ # model_kp_path = path_hf_repo / "SV_kp.engine"
70
+ # model_kp = torch_tensorrt.load(model_kp_path)
71
+
72
+ model_kp_path = path_hf_repo / 'keypoint'
73
+ config_kp_path = path_hf_repo / 'hrnetv2_w48.yaml'
74
+ cfg_kp = yaml.safe_load(open(config_kp_path, 'r'))
75
+
76
+ loaded_state_kp = torch.load(model_kp_path, map_location=device)
77
+ model = get_cls_net(cfg_kp)
78
+ model.load_state_dict(loaded_state_kp)
79
+ model.to(device)
80
+ model.eval()
81
+
82
+ # @torch.inference_mode()
83
+ # def run_inference(model, input_tensor: torch.Tensor):
84
+ # input_tensor = input_tensor.to(device).to(memory_format=torch.channels_last)
85
+ # output = model.module().forward(input_tensor)
86
+ # return output
87
+
88
+ # run_inference(model_kp, torch.randn(8, 3, 540, 960, device=device, dtype=torch.float32))
89
+ self.keypoints_model = model
90
+ self.kp_threshold = 0.1
91
+ self.pitch_batch_size = 8
92
+ print("✅ Keypoints Model Loaded")
93
+
94
+ def __repr__(self) -> str:
95
+ return (
96
+ f"BBox Model: {type(self.bbox_model).__name__}\n"
97
+ f"Keypoints Model: {type(self.keypoints_model).__name__}"
98
+ )
99
+
100
+ @staticmethod
101
+ def _clip_box_to_image(x1: int, y1: int, x2: int, y2: int, w: int, h: int) -> Tuple[int, int, int, int]:
102
+ x1 = max(0, min(int(x1), w - 1))
103
+ y1 = max(0, min(int(y1), h - 1))
104
+ x2 = max(0, min(int(x2), w - 1))
105
+ y2 = max(0, min(int(y2), h - 1))
106
+ if x2 <= x1:
107
+ x2 = min(w - 1, x1 + 1)
108
+ if y2 <= y1:
109
+ y2 = min(h - 1, y1 + 1)
110
+ return x1, y1, x2, y2
111
+
112
+ @staticmethod
113
+ def _area(bb: BoundingBox) -> int:
114
+ return max(0, bb.x2 - bb.x1) * max(0, bb.y2 - bb.y1)
115
+
116
+ @staticmethod
117
+ def _intersect_area(a: BoundingBox, b: BoundingBox) -> int:
118
+ ix1 = max(a.x1, b.x1)
119
+ iy1 = max(a.y1, b.y1)
120
+ ix2 = min(a.x2, b.x2)
121
+ iy2 = min(a.y2, b.y2)
122
+ if ix2 <= ix1 or iy2 <= iy1:
123
+ return 0
124
+ return (ix2 - ix1) * (iy2 - iy1)
125
+
126
+ @staticmethod
127
+ def _center(bb: BoundingBox) -> Tuple[float, float]:
128
+ return (0.5 * (bb.x1 + bb.x2), 0.5 * (bb.y1 + bb.y2))
129
+
130
+ @staticmethod
131
+ def _mean_hs(img_bgr: np.ndarray) -> Tuple[float, float]:
132
+ hsv = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2HSV)
133
+ return float(np.mean(hsv[:, :, 0])), float(np.mean(hsv[:, :, 1]))
134
+
135
+ def _hs_feature_from_roi(self, img_bgr: np.ndarray, box: BoundingBox) -> np.ndarray:
136
+ H, W = img_bgr.shape[:2]
137
+ x1, y1, x2, y2 = self._clip_box_to_image(box.x1, box.y1, box.x2, box.y2, W, H)
138
+ roi = img_bgr[y1:y2, x1:x2]
139
+ if roi.size == 0:
140
+ return np.array([0.0, 0.0], dtype=np.float32)
141
+ hsv = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
142
+ lower_green = np.array([35, 60, 60], dtype=np.uint8)
143
+ upper_green = np.array([85, 255, 255], dtype=np.uint8)
144
+ green_mask = cv2.inRange(hsv, lower_green, upper_green)
145
+ non_green_mask = cv2.bitwise_not(green_mask)
146
+ num_non_green = int(np.count_nonzero(non_green_mask))
147
+ total = hsv.shape[0] * hsv.shape[1]
148
+ if num_non_green > max(50, total // 20):
149
+ h_vals = hsv[:, :, 0][non_green_mask > 0]
150
+ s_vals = hsv[:, :, 1][non_green_mask > 0]
151
+ h_mean = float(np.mean(h_vals)) if h_vals.size else 0.0
152
+ s_mean = float(np.mean(s_vals)) if s_vals.size else 0.0
153
+ else:
154
+ h_mean, s_mean = self._mean_hs(roi)
155
+ return np.array([h_mean, s_mean], dtype=np.float32)
156
+
157
+ def _ioa(self, a: BoundingBox, b: BoundingBox) -> float:
158
+ inter = self._intersect_area(a, b)
159
+ aa = self._area(a)
160
+ if aa <= 0:
161
+ return 0.0
162
+ return inter / aa
163
+
164
+ def suppress_quasi_total_containment(self, boxes: List[BoundingBox]) -> List[BoundingBox]:
165
+ if len(boxes) <= 1:
166
+ return boxes
167
+ keep = [True] * len(boxes)
168
+ for i in range(len(boxes)):
169
+ if not keep[i]:
170
+ continue
171
+ for j in range(len(boxes)):
172
+ if i == j or not keep[j]:
173
+ continue
174
+ ioa_i_in_j = self._ioa(boxes[i], boxes[j])
175
+ if ioa_i_in_j >= self.QUASI_TOTAL_IOA:
176
+ keep[i] = False
177
+ break
178
+ return [bb for bb, k in zip(boxes, keep) if k]
179
+
180
+ def suppress_small_contained(self, boxes: List[BoundingBox]) -> List[BoundingBox]:
181
+ if len(boxes) <= 1:
182
+ return boxes
183
+ keep = [True] * len(boxes)
184
+ areas = [self._area(bb) for bb in boxes]
185
+ for i in range(len(boxes)):
186
+ if not keep[i]:
187
+ continue
188
+ for j in range(len(boxes)):
189
+ if i == j or not keep[j]:
190
+ continue
191
+ ai, aj = areas[i], areas[j]
192
+ if ai == 0 or aj == 0:
193
+ continue
194
+ if ai <= aj:
195
+ ratio = ai / aj
196
+ if ratio <= self.SMALL_RATIO_MAX:
197
+ ioa_i_in_j = self._ioa(boxes[i], boxes[j])
198
+ if ioa_i_in_j >= self.SMALL_CONTAINED_IOA:
199
+ keep[i] = False
200
+ break
201
+ else:
202
+ ratio = aj / ai
203
+ if ratio <= self.SMALL_RATIO_MAX:
204
+ ioa_j_in_i = self._ioa(boxes[j], boxes[i])
205
+ if ioa_j_in_i >= self.SMALL_CONTAINED_IOA:
206
+ keep[j] = False
207
+ return [bb for bb, k in zip(boxes, keep) if k]
208
+
209
+ def _assign_players_two_clusters(self, features: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
210
+ criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20, 1.0)
211
+ _, labels, centers = cv2.kmeans(
212
+ np.float32(features),
213
+ K=2,
214
+ bestLabels=None,
215
+ criteria=criteria,
216
+ attempts=5,
217
+ flags=cv2.KMEANS_PP_CENTERS,
218
+ )
219
+ return labels.reshape(-1), centers
220
+
221
+ def _reclass_extra_goalkeepers(self, img_bgr: np.ndarray, boxes: List[BoundingBox], cluster_centers: np.ndarray | None) -> None:
222
+ gk_idxs = [i for i, bb in enumerate(boxes) if int(bb.cls_id) == 1]
223
+ if len(gk_idxs) <= 1:
224
+ return
225
+ gk_idxs_sorted = sorted(gk_idxs, key=lambda i: boxes[i].conf, reverse=True)
226
+ keep_gk_idx = gk_idxs_sorted[0]
227
+ to_reclass = gk_idxs_sorted[1:]
228
+ for gki in to_reclass:
229
+ hs_gk = self._hs_feature_from_roi(img_bgr, boxes[gki])
230
+ if cluster_centers is not None:
231
+ d0 = float(np.linalg.norm(hs_gk - cluster_centers[0]))
232
+ d1 = float(np.linalg.norm(hs_gk - cluster_centers[1]))
233
+ assign_cls = 6 if d0 <= d1 else 7
234
+ else:
235
+ assign_cls = 6 if float(hs_gk[0]) < self.SINGLE_PLAYER_HUE_PIVOT else 7
236
+ boxes[gki].cls_id = int(assign_cls)
237
+
238
+ def predict_batch(self, batch_images: List[ndarray], offset: int, n_keypoints: int) -> List[TVFrameResult]:
239
+ bboxes: Dict[int, List[BoundingBox]] = {}
240
+ bbox_model_results = self.bbox_model.predict(batch_images)
241
+ if bbox_model_results is not None:
242
+ for frame_idx_in_batch, detection in enumerate(bbox_model_results):
243
+ if not hasattr(detection, "boxes") or detection.boxes is None:
244
+ continue
245
+ boxes: List[BoundingBox] = []
246
+ for box in detection.boxes.data:
247
+ x1, y1, x2, y2, conf, cls_id = box.tolist()
248
+ # if cls_id == 3:
249
+ # cls_id = 2
250
+ # elif cls_id == 2:
251
+ # cls_id = 3
252
+ boxes.append(
253
+ BoundingBox(
254
+ x1=int(x1),
255
+ y1=int(y1),
256
+ x2=int(x2),
257
+ y2=int(y2),
258
+ cls_id=int(cls_id),
259
+ conf=float(conf),
260
+ )
261
+ )
262
+ footballs = [bb for bb in boxes if int(bb.cls_id) == 0]
263
+ if len(footballs) > 1:
264
+ best_ball = max(footballs, key=lambda b: b.conf)
265
+ boxes = [bb for bb in boxes if int(bb.cls_id) != 0]
266
+ boxes.append(best_ball)
267
+ boxes = self.suppress_quasi_total_containment(boxes)
268
+ boxes = self.suppress_small_contained(boxes)
269
+ img_bgr = batch_images[frame_idx_in_batch]
270
+ player_indices: List[int] = []
271
+ player_feats: List[np.ndarray] = []
272
+ for i, bb in enumerate(boxes):
273
+ if int(bb.cls_id) == 2:
274
+ hs = self._hs_feature_from_roi(img_bgr, bb)
275
+ player_indices.append(i)
276
+ player_feats.append(hs)
277
+ cluster_centers = None
278
+ n_players = len(player_feats)
279
+ if n_players >= 2:
280
+ feats = np.vstack(player_feats)
281
+ labels, centers = self._assign_players_two_clusters(feats)
282
+ order = np.argsort(centers[:, 0])
283
+ centers = centers[order]
284
+ remap = {old_idx: new_idx for new_idx, old_idx in enumerate(order)}
285
+ labels = np.vectorize(remap.get)(labels)
286
+ cluster_centers = centers
287
+ for idx_in_list, lbl in zip(player_indices, labels):
288
+ boxes[idx_in_list].cls_id = 6 if int(lbl) == 0 else 7
289
+ elif n_players == 1:
290
+ hue, _ = player_feats[0]
291
+ boxes[player_indices[0]].cls_id = 6 if float(hue) < self.SINGLE_PLAYER_HUE_PIVOT else 7
292
+ self._reclass_extra_goalkeepers(img_bgr, boxes, cluster_centers)
293
+ bboxes[offset + frame_idx_in_batch] = boxes
294
+
295
+ pitch_batch_size = min(self.pitch_batch_size, len(batch_images))
296
+ keypoints: Dict[int, List[Tuple[int, int]]] = {}
297
+ while True:
298
+ # try:
299
+ gc.collect()
300
+ if torch.cuda.is_available():
301
+ tf.keras.backend.clear_session()
302
+ torch.cuda.empty_cache()
303
+ torch.cuda.synchronize()
304
+ device_str = "cuda" if torch.cuda.is_available() else "cpu"
305
+ keypoints_result = process_batch_input(
306
+ batch_images,
307
+ self.keypoints_model,
308
+ self.kp_threshold,
309
+ device_str,
310
+ batch_size=pitch_batch_size,
311
+ )
312
+ if keypoints_result is not None and len(keypoints_result) > 0:
313
+ for frame_number_in_batch, kp_dict in enumerate(keypoints_result):
314
+ if frame_number_in_batch >= len(batch_images):
315
+ break
316
+ frame_keypoints: List[Tuple[int, int]] = []
317
+ try:
318
+ height, width = batch_images[frame_number_in_batch].shape[:2]
319
+ if kp_dict is not None and isinstance(kp_dict, dict):
320
+ for idx in range(32):
321
+ x, y = 0, 0
322
+ kp_idx = idx + 1
323
+ if kp_idx in kp_dict:
324
+ try:
325
+ kp_data = kp_dict[kp_idx]
326
+ if isinstance(kp_data, dict) and "x" in kp_data and "y" in kp_data:
327
+ x = int(kp_data["x"] * width)
328
+ y = int(kp_data["y"] * height)
329
+ except (KeyError, TypeError, ValueError):
330
+ pass
331
+ frame_keypoints.append((x, y))
332
+ except (IndexError, ValueError, AttributeError):
333
+ frame_keypoints = [(0, 0)] * 32
334
+ if len(frame_keypoints) < n_keypoints:
335
+ frame_keypoints.extend([(0, 0)] * (n_keypoints - len(frame_keypoints)))
336
+ else:
337
+ frame_keypoints = frame_keypoints[:n_keypoints]
338
+ keypoints[offset + frame_number_in_batch] = frame_keypoints
339
+ print("✅ Keypoints predicted")
340
+ break
341
+ # except RuntimeError as e:
342
+ # print(self.pitch_batch_size)
343
+ # print(e)
344
+ # if "out of memory" in str(e):
345
+ # if self.pitch_batch_size == 1:
346
+ # break
347
+ # self.pitch_batch_size = self.pitch_batch_size // 2 if self.pitch_batch_size > 1 else 1
348
+ # pitch_batch_size = min(self.pitch_batch_size, len(batch_images))
349
+ # else:
350
+ # break
351
+ # except Exception as e:
352
+ # print(f"❌ Error during keypoints prediction: {e}")
353
+ # break
354
+
355
+ results: List[TVFrameResult] = []
356
+ for frame_number in range(offset, offset + len(batch_images)):
357
+ frame_boxes = bboxes.get(frame_number, [])
358
+ frame_keypoints = keypoints.get(frame_number, [(0, 0) for _ in range(n_keypoints)])
359
+ result = TVFrameResult(
360
+ frame_id=frame_number,
361
+ boxes=frame_boxes,
362
+ keypoints=frame_keypoints,
363
+ )
364
+ results.append(result)
365
+
366
+ gc.collect()
367
+ if torch.cuda.is_available():
368
+ tf.keras.backend.clear_session()
369
+ torch.cuda.empty_cache()
370
+ torch.cuda.synchronize()
371
+
372
+ return results
objdetect.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8bbacfcb38e38b1b8816788e9e6e845160533719a0b87b693d58b932380d0d28
3
+ size 152961687
object-detection.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:05112479be8cb59494e9ae23a57af43becd5aa1f448b0e5ed33fcb6b4c2bbbc3
3
+ size 273322667
pitch.py ADDED
@@ -0,0 +1,687 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+ from __future__ import division
3
+ from __future__ import print_function
4
+
5
+ import os
6
+ import sys
7
+ import time
8
+ from typing import List, Optional, Tuple
9
+
10
+ import cv2
11
+ import numpy as np
12
+ import torch
13
+ import torch.nn as nn
14
+ import torch.nn.functional as F
15
+ import torchvision.transforms as T
16
+ import torchvision.transforms.functional as f
17
+ from pydantic import BaseModel
18
+
19
+ import logging
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ class BoundingBox(BaseModel):
24
+ x1: int
25
+ y1: int
26
+ x2: int
27
+ y2: int
28
+ cls_id: int
29
+ conf: float
30
+
31
+
32
+ class TVFrameResult(BaseModel):
33
+ frame_id: int
34
+ boxes: list[BoundingBox]
35
+ keypoints: list[tuple[int, int]]
36
+
37
+ BatchNorm2d = nn.BatchNorm2d
38
+ BN_MOMENTUM = 0.1
39
+
40
+ def conv3x3(in_planes, out_planes, stride=1):
41
+ """3x3 convolution with padding"""
42
+ return nn.Conv2d(in_planes, out_planes, kernel_size=3,
43
+ stride=stride, padding=1, bias=False)
44
+
45
+
46
+ class BasicBlock(nn.Module):
47
+ expansion = 1
48
+
49
+ def __init__(self, inplanes, planes, stride=1, downsample=None):
50
+ super(BasicBlock, self).__init__()
51
+ self.conv1 = conv3x3(inplanes, planes, stride)
52
+ self.bn1 = BatchNorm2d(planes, momentum=BN_MOMENTUM)
53
+ self.relu = nn.ReLU(inplace=True)
54
+ self.conv2 = conv3x3(planes, planes)
55
+ self.bn2 = BatchNorm2d(planes, momentum=BN_MOMENTUM)
56
+ self.downsample = downsample
57
+ self.stride = stride
58
+
59
+ def forward(self, x):
60
+ residual = x
61
+
62
+ out = self.conv1(x)
63
+ out = self.bn1(out)
64
+ out = self.relu(out)
65
+
66
+ out = self.conv2(out)
67
+ out = self.bn2(out)
68
+
69
+ if self.downsample is not None:
70
+ residual = self.downsample(x)
71
+
72
+ out += residual
73
+ out = self.relu(out)
74
+
75
+ return out
76
+
77
+
78
+ class Bottleneck(nn.Module):
79
+ expansion = 4
80
+
81
+ def __init__(self, inplanes, planes, stride=1, downsample=None):
82
+ super(Bottleneck, self).__init__()
83
+ self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
84
+ self.bn1 = BatchNorm2d(planes, momentum=BN_MOMENTUM)
85
+ self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
86
+ padding=1, bias=False)
87
+ self.bn2 = BatchNorm2d(planes, momentum=BN_MOMENTUM)
88
+ self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1,
89
+ bias=False)
90
+ self.bn3 = BatchNorm2d(planes * self.expansion,
91
+ momentum=BN_MOMENTUM)
92
+ self.relu = nn.ReLU(inplace=True)
93
+ self.downsample = downsample
94
+ self.stride = stride
95
+
96
+ def forward(self, x):
97
+ residual = x
98
+
99
+ out = self.conv1(x)
100
+ out = self.bn1(out)
101
+ out = self.relu(out)
102
+
103
+ out = self.conv2(out)
104
+ out = self.bn2(out)
105
+ out = self.relu(out)
106
+
107
+ out = self.conv3(out)
108
+ out = self.bn3(out)
109
+
110
+ if self.downsample is not None:
111
+ residual = self.downsample(x)
112
+
113
+ out += residual
114
+ out = self.relu(out)
115
+
116
+ return out
117
+
118
+
119
+ class HighResolutionModule(nn.Module):
120
+ def __init__(self, num_branches, blocks, num_blocks, num_inchannels,
121
+ num_channels, fuse_method, multi_scale_output=True):
122
+ super(HighResolutionModule, self).__init__()
123
+ self._check_branches(
124
+ num_branches, blocks, num_blocks, num_inchannels, num_channels)
125
+
126
+ self.num_inchannels = num_inchannels
127
+ self.fuse_method = fuse_method
128
+ self.num_branches = num_branches
129
+
130
+ self.multi_scale_output = multi_scale_output
131
+
132
+ self.branches = self._make_branches(
133
+ num_branches, blocks, num_blocks, num_channels)
134
+ self.fuse_layers = self._make_fuse_layers()
135
+ self.relu = nn.ReLU(inplace=True)
136
+
137
+ def _check_branches(self, num_branches, blocks, num_blocks,
138
+ num_inchannels, num_channels):
139
+ if num_branches != len(num_blocks):
140
+ error_msg = 'NUM_BRANCHES({}) <> NUM_BLOCKS({})'.format(
141
+ num_branches, len(num_blocks))
142
+ logger.error(error_msg)
143
+ raise ValueError(error_msg)
144
+
145
+ if num_branches != len(num_channels):
146
+ error_msg = 'NUM_BRANCHES({}) <> NUM_CHANNELS({})'.format(
147
+ num_branches, len(num_channels))
148
+ logger.error(error_msg)
149
+ raise ValueError(error_msg)
150
+
151
+ if num_branches != len(num_inchannels):
152
+ error_msg = 'NUM_BRANCHES({}) <> NUM_INCHANNELS({})'.format(
153
+ num_branches, len(num_inchannels))
154
+ logger.error(error_msg)
155
+ raise ValueError(error_msg)
156
+
157
+ def _make_one_branch(self, branch_index, block, num_blocks, num_channels,
158
+ stride=1):
159
+ downsample = None
160
+ if stride != 1 or \
161
+ self.num_inchannels[branch_index] != num_channels[branch_index] * block.expansion:
162
+ downsample = nn.Sequential(
163
+ nn.Conv2d(self.num_inchannels[branch_index],
164
+ num_channels[branch_index] * block.expansion,
165
+ kernel_size=1, stride=stride, bias=False),
166
+ BatchNorm2d(num_channels[branch_index] * block.expansion,
167
+ momentum=BN_MOMENTUM),
168
+ )
169
+
170
+ layers = []
171
+ layers.append(block(self.num_inchannels[branch_index],
172
+ num_channels[branch_index], stride, downsample))
173
+ self.num_inchannels[branch_index] = \
174
+ num_channels[branch_index] * block.expansion
175
+ for i in range(1, num_blocks[branch_index]):
176
+ layers.append(block(self.num_inchannels[branch_index],
177
+ num_channels[branch_index]))
178
+
179
+ return nn.Sequential(*layers)
180
+
181
+ def _make_branches(self, num_branches, block, num_blocks, num_channels):
182
+ branches = []
183
+
184
+ for i in range(num_branches):
185
+ branches.append(
186
+ self._make_one_branch(i, block, num_blocks, num_channels))
187
+
188
+ return nn.ModuleList(branches)
189
+
190
+ def _make_fuse_layers(self):
191
+ if self.num_branches == 1:
192
+ return None
193
+
194
+ num_branches = self.num_branches
195
+ num_inchannels = self.num_inchannels
196
+ fuse_layers = []
197
+ for i in range(num_branches if self.multi_scale_output else 1):
198
+ fuse_layer = []
199
+ for j in range(num_branches):
200
+ if j > i:
201
+ fuse_layer.append(nn.Sequential(
202
+ nn.Conv2d(num_inchannels[j],
203
+ num_inchannels[i],
204
+ 1,
205
+ 1,
206
+ 0,
207
+ bias=False),
208
+ BatchNorm2d(num_inchannels[i], momentum=BN_MOMENTUM)))
209
+ # nn.Upsample(scale_factor=2**(j-i), mode='nearest')))
210
+ elif j == i:
211
+ fuse_layer.append(None)
212
+ else:
213
+ conv3x3s = []
214
+ for k in range(i - j):
215
+ if k == i - j - 1:
216
+ num_outchannels_conv3x3 = num_inchannels[i]
217
+ conv3x3s.append(nn.Sequential(
218
+ nn.Conv2d(num_inchannels[j],
219
+ num_outchannels_conv3x3,
220
+ 3, 2, 1, bias=False),
221
+ BatchNorm2d(num_outchannels_conv3x3, momentum=BN_MOMENTUM)))
222
+ else:
223
+ num_outchannels_conv3x3 = num_inchannels[j]
224
+ conv3x3s.append(nn.Sequential(
225
+ nn.Conv2d(num_inchannels[j],
226
+ num_outchannels_conv3x3,
227
+ 3, 2, 1, bias=False),
228
+ BatchNorm2d(num_outchannels_conv3x3,
229
+ momentum=BN_MOMENTUM),
230
+ nn.ReLU(inplace=True)))
231
+ fuse_layer.append(nn.Sequential(*conv3x3s))
232
+ fuse_layers.append(nn.ModuleList(fuse_layer))
233
+
234
+ return nn.ModuleList(fuse_layers)
235
+
236
+ def get_num_inchannels(self):
237
+ return self.num_inchannels
238
+
239
+ def forward(self, x):
240
+ if self.num_branches == 1:
241
+ return [self.branches[0](x[0])]
242
+
243
+ for i in range(self.num_branches):
244
+ x[i] = self.branches[i](x[i])
245
+
246
+ x_fuse = []
247
+ for i in range(len(self.fuse_layers)):
248
+ y = x[0] if i == 0 else self.fuse_layers[i][0](x[0])
249
+ for j in range(1, self.num_branches):
250
+ if i == j:
251
+ y = y + x[j]
252
+ elif j > i:
253
+ y = y + F.interpolate(
254
+ self.fuse_layers[i][j](x[j]),
255
+ size=[x[i].shape[2], x[i].shape[3]],
256
+ mode='bilinear')
257
+ else:
258
+ y = y + self.fuse_layers[i][j](x[j])
259
+ x_fuse.append(self.relu(y))
260
+
261
+ return x_fuse
262
+
263
+
264
+ blocks_dict = {
265
+ 'BASIC': BasicBlock,
266
+ 'BOTTLENECK': Bottleneck
267
+ }
268
+
269
+
270
+ class HighResolutionNet(nn.Module):
271
+
272
+ def __init__(self, config, **kwargs):
273
+ self.inplanes = 64
274
+ extra = config['MODEL']['EXTRA']
275
+ super(HighResolutionNet, self).__init__()
276
+
277
+ # stem net
278
+ self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=3, stride=2, padding=1,
279
+ bias=False)
280
+ self.bn1 = BatchNorm2d(self.inplanes, momentum=BN_MOMENTUM)
281
+ self.conv2 = nn.Conv2d(self.inplanes, self.inplanes, kernel_size=3, stride=2, padding=1,
282
+ bias=False)
283
+ self.bn2 = BatchNorm2d(self.inplanes, momentum=BN_MOMENTUM)
284
+ self.relu = nn.ReLU(inplace=True)
285
+ self.sf = nn.Softmax(dim=1)
286
+ self.layer1 = self._make_layer(Bottleneck, 64, 64, 4)
287
+
288
+ self.stage2_cfg = extra['STAGE2']
289
+ num_channels = self.stage2_cfg['NUM_CHANNELS']
290
+ block = blocks_dict[self.stage2_cfg['BLOCK']]
291
+ num_channels = [
292
+ num_channels[i] * block.expansion for i in range(len(num_channels))]
293
+ self.transition1 = self._make_transition_layer(
294
+ [256], num_channels)
295
+ self.stage2, pre_stage_channels = self._make_stage(
296
+ self.stage2_cfg, num_channels)
297
+
298
+ self.stage3_cfg = extra['STAGE3']
299
+ num_channels = self.stage3_cfg['NUM_CHANNELS']
300
+ block = blocks_dict[self.stage3_cfg['BLOCK']]
301
+ num_channels = [
302
+ num_channels[i] * block.expansion for i in range(len(num_channels))]
303
+ self.transition2 = self._make_transition_layer(
304
+ pre_stage_channels, num_channels)
305
+ self.stage3, pre_stage_channels = self._make_stage(
306
+ self.stage3_cfg, num_channels)
307
+
308
+ self.stage4_cfg = extra['STAGE4']
309
+ num_channels = self.stage4_cfg['NUM_CHANNELS']
310
+ block = blocks_dict[self.stage4_cfg['BLOCK']]
311
+ num_channels = [
312
+ num_channels[i] * block.expansion for i in range(len(num_channels))]
313
+ self.transition3 = self._make_transition_layer(
314
+ pre_stage_channels, num_channels)
315
+ self.stage4, pre_stage_channels = self._make_stage(
316
+ self.stage4_cfg, num_channels, multi_scale_output=True)
317
+
318
+ self.upsample = nn.Upsample(scale_factor=2, mode='nearest')
319
+ final_inp_channels = sum(pre_stage_channels) + self.inplanes
320
+
321
+ self.head = nn.Sequential(nn.Sequential(
322
+ nn.Conv2d(
323
+ in_channels=final_inp_channels,
324
+ out_channels=final_inp_channels,
325
+ kernel_size=1),
326
+ BatchNorm2d(final_inp_channels, momentum=BN_MOMENTUM),
327
+ nn.ReLU(inplace=True),
328
+ nn.Conv2d(
329
+ in_channels=final_inp_channels,
330
+ out_channels=config['MODEL']['NUM_JOINTS'],
331
+ kernel_size=extra['FINAL_CONV_KERNEL']),
332
+ nn.Softmax(dim=1)))
333
+
334
+
335
+
336
+ def _make_head(self, x, x_skip):
337
+ x = self.upsample(x)
338
+ x = torch.cat([x, x_skip], dim=1)
339
+ x = self.head(x)
340
+
341
+ return x
342
+
343
+ def _make_transition_layer(
344
+ self, num_channels_pre_layer, num_channels_cur_layer):
345
+ num_branches_cur = len(num_channels_cur_layer)
346
+ num_branches_pre = len(num_channels_pre_layer)
347
+
348
+ transition_layers = []
349
+ for i in range(num_branches_cur):
350
+ if i < num_branches_pre:
351
+ if num_channels_cur_layer[i] != num_channels_pre_layer[i]:
352
+ transition_layers.append(nn.Sequential(
353
+ nn.Conv2d(num_channels_pre_layer[i],
354
+ num_channels_cur_layer[i],
355
+ 3,
356
+ 1,
357
+ 1,
358
+ bias=False),
359
+ BatchNorm2d(
360
+ num_channels_cur_layer[i], momentum=BN_MOMENTUM),
361
+ nn.ReLU(inplace=True)))
362
+ else:
363
+ transition_layers.append(None)
364
+ else:
365
+ conv3x3s = []
366
+ for j in range(i + 1 - num_branches_pre):
367
+ inchannels = num_channels_pre_layer[-1]
368
+ outchannels = num_channels_cur_layer[i] \
369
+ if j == i - num_branches_pre else inchannels
370
+ conv3x3s.append(nn.Sequential(
371
+ nn.Conv2d(
372
+ inchannels, outchannels, 3, 2, 1, bias=False),
373
+ BatchNorm2d(outchannels, momentum=BN_MOMENTUM),
374
+ nn.ReLU(inplace=True)))
375
+ transition_layers.append(nn.Sequential(*conv3x3s))
376
+
377
+ return nn.ModuleList(transition_layers)
378
+
379
+ def _make_layer(self, block, inplanes, planes, blocks, stride=1):
380
+ downsample = None
381
+ if stride != 1 or inplanes != planes * block.expansion:
382
+ downsample = nn.Sequential(
383
+ nn.Conv2d(inplanes, planes * block.expansion,
384
+ kernel_size=1, stride=stride, bias=False),
385
+ BatchNorm2d(planes * block.expansion, momentum=BN_MOMENTUM),
386
+ )
387
+
388
+ layers = []
389
+ layers.append(block(inplanes, planes, stride, downsample))
390
+ inplanes = planes * block.expansion
391
+ for i in range(1, blocks):
392
+ layers.append(block(inplanes, planes))
393
+
394
+ return nn.Sequential(*layers)
395
+
396
+ def _make_stage(self, layer_config, num_inchannels,
397
+ multi_scale_output=True):
398
+ num_modules = layer_config['NUM_MODULES']
399
+ num_branches = layer_config['NUM_BRANCHES']
400
+ num_blocks = layer_config['NUM_BLOCKS']
401
+ num_channels = layer_config['NUM_CHANNELS']
402
+ block = blocks_dict[layer_config['BLOCK']]
403
+ fuse_method = layer_config['FUSE_METHOD']
404
+
405
+ modules = []
406
+ for i in range(num_modules):
407
+ # multi_scale_output is only used last module
408
+ if not multi_scale_output and i == num_modules - 1:
409
+ reset_multi_scale_output = False
410
+ else:
411
+ reset_multi_scale_output = True
412
+ modules.append(
413
+ HighResolutionModule(num_branches,
414
+ block,
415
+ num_blocks,
416
+ num_inchannels,
417
+ num_channels,
418
+ fuse_method,
419
+ reset_multi_scale_output)
420
+ )
421
+ num_inchannels = modules[-1].get_num_inchannels()
422
+
423
+ return nn.Sequential(*modules), num_inchannels
424
+
425
+ def forward(self, x):
426
+ # h, w = x.size(2), x.size(3)
427
+ x = self.conv1(x)
428
+ x_skip = x.clone()
429
+ x = self.bn1(x)
430
+ x = self.relu(x)
431
+ x = self.conv2(x)
432
+ x = self.bn2(x)
433
+ x = self.relu(x)
434
+ x = self.layer1(x)
435
+
436
+ x_list = []
437
+ for i in range(self.stage2_cfg['NUM_BRANCHES']):
438
+ if self.transition1[i] is not None:
439
+ x_list.append(self.transition1[i](x))
440
+ else:
441
+ x_list.append(x)
442
+ y_list = self.stage2(x_list)
443
+
444
+ x_list = []
445
+ for i in range(self.stage3_cfg['NUM_BRANCHES']):
446
+ if self.transition2[i] is not None:
447
+ x_list.append(self.transition2[i](y_list[-1]))
448
+ else:
449
+ x_list.append(y_list[i])
450
+ y_list = self.stage3(x_list)
451
+
452
+ x_list = []
453
+ for i in range(self.stage4_cfg['NUM_BRANCHES']):
454
+ if self.transition3[i] is not None:
455
+ x_list.append(self.transition3[i](y_list[-1]))
456
+ else:
457
+ x_list.append(y_list[i])
458
+ x = self.stage4(x_list)
459
+
460
+ # Head Part
461
+ height, width = x[0].size(2), x[0].size(3)
462
+ x1 = F.interpolate(x[1], size=(height, width), mode='bilinear', align_corners=False)
463
+ x2 = F.interpolate(x[2], size=(height, width), mode='bilinear', align_corners=False)
464
+ x3 = F.interpolate(x[3], size=(height, width), mode='bilinear', align_corners=False)
465
+ x = torch.cat([x[0], x1, x2, x3], 1)
466
+ x = self._make_head(x, x_skip)
467
+
468
+ return x
469
+
470
+ def init_weights(self, pretrained=''):
471
+ for m in self.modules():
472
+ if isinstance(m, nn.Conv2d):
473
+ nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
474
+ #nn.init.normal_(m.weight, std=0.001)
475
+ #nn.init.constant_(m.bias, 0)
476
+ elif isinstance(m, nn.BatchNorm2d):
477
+ nn.init.constant_(m.weight, 1)
478
+ nn.init.constant_(m.bias, 0)
479
+ if pretrained != '':
480
+ if os.path.isfile(pretrained):
481
+ pretrained_dict = torch.load(pretrained)
482
+ model_dict = self.state_dict()
483
+ pretrained_dict = {k: v for k, v in pretrained_dict.items()
484
+ if k in model_dict.keys()}
485
+ model_dict.update(pretrained_dict)
486
+ self.load_state_dict(model_dict)
487
+ else:
488
+ sys.exit(f'Weights {pretrained} not found.')
489
+
490
+
491
+ def get_cls_net(config, pretrained='', **kwargs):
492
+ """Create keypoint detection model with softmax activation"""
493
+ model = HighResolutionNet(config, **kwargs)
494
+ model.init_weights(pretrained)
495
+ return model
496
+
497
+
498
+ def get_cls_net_l(config, pretrained='', **kwargs):
499
+ """Create line detection model with sigmoid activation"""
500
+ model = HighResolutionNet(config, **kwargs)
501
+ model.init_weights(pretrained)
502
+
503
+ # After loading weights, replace just the activation function
504
+ # The saved model expects the nested Sequential structure
505
+ inner_seq = model.head[0]
506
+ # Replace softmax (index 4) with sigmoid
507
+ model.head[0][4] = nn.Sigmoid()
508
+
509
+ return model
510
+
511
+ # Simplified utility functions - removed complex Gaussian generation functions
512
+ # These were mainly used for training data generation, not inference
513
+
514
+
515
+
516
+ # generate_gaussian_array_vectorized_dist_l function removed - not used in current implementation
517
+ @torch.inference_mode()
518
+ def run_inference(model, input_tensor: torch.Tensor, device):
519
+ input_tensor = input_tensor.to(device).to(memory_format=torch.channels_last)
520
+ output = model.module().forward(input_tensor)
521
+ return output
522
+
523
+ def preprocess_batch_fast(frames):
524
+ """Ultra-fast batch preprocessing using optimized tensor operations"""
525
+ target_size = (540, 960) # H, W format for model input
526
+ batch = []
527
+ for i, frame in enumerate(frames):
528
+ frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
529
+ img = cv2.resize(frame_rgb, (target_size[1], target_size[0]))
530
+ img = img.astype(np.float32) / 255.0
531
+ img = np.transpose(img, (2, 0, 1)) # HWC -> CHW
532
+ batch.append(img)
533
+ batch = torch.from_numpy(np.stack(batch)).float()
534
+
535
+ return batch
536
+
537
+ def extract_keypoints_from_heatmap(heatmap: torch.Tensor, scale: int = 2, max_keypoints: int = 1):
538
+ """Optimized keypoint extraction from heatmaps"""
539
+ batch_size, n_channels, height, width = heatmap.shape
540
+
541
+ # Find local maxima using max pooling (keep on GPU)
542
+ kernel = 3
543
+ pad = 1
544
+ max_pooled = F.max_pool2d(heatmap, kernel, stride=1, padding=pad)
545
+ local_maxima = (max_pooled == heatmap)
546
+ heatmap = heatmap * local_maxima
547
+
548
+ # Get top keypoints (keep on GPU longer)
549
+ scores, indices = torch.topk(heatmap.view(batch_size, n_channels, -1), max_keypoints, sorted=False)
550
+ y_coords = torch.div(indices, width, rounding_mode="floor")
551
+ x_coords = indices % width
552
+
553
+ # Optimized tensor operations
554
+ x_coords = x_coords * scale
555
+ y_coords = y_coords * scale
556
+
557
+ # Create result tensor directly on GPU
558
+ results = torch.stack([x_coords.float(), y_coords.float(), scores], dim=-1)
559
+
560
+ return results
561
+
562
+
563
+ def extract_keypoints_from_heatmap_fast(heatmap: torch.Tensor, scale: int = 2, max_keypoints: int = 1):
564
+ """Ultra-fast keypoint extraction optimized for speed"""
565
+ batch_size, n_channels, height, width = heatmap.shape
566
+
567
+ # Simplified local maxima detection (faster but slightly less accurate)
568
+ max_pooled = F.max_pool2d(heatmap, 3, stride=1, padding=1)
569
+ local_maxima = (max_pooled == heatmap)
570
+
571
+ # Apply mask and get top keypoints in one go
572
+ masked_heatmap = heatmap * local_maxima
573
+ flat_heatmap = masked_heatmap.view(batch_size, n_channels, -1)
574
+ scores, indices = torch.topk(flat_heatmap, max_keypoints, dim=-1, sorted=False)
575
+
576
+ # Vectorized coordinate calculation
577
+ y_coords = torch.div(indices, width, rounding_mode="floor") * scale
578
+ x_coords = (indices % width) * scale
579
+
580
+ # Stack results efficiently
581
+ results = torch.stack([x_coords.float(), y_coords.float(), scores], dim=-1)
582
+ return results
583
+
584
+
585
+ def process_keypoints_vectorized(kp_coords, kp_threshold, w, h, batch_size):
586
+ """Ultra-fast vectorized keypoint processing"""
587
+ batch_results = []
588
+
589
+ # Convert to numpy once for faster CPU operations
590
+ kp_np = kp_coords.cpu().numpy()
591
+
592
+ for batch_idx in range(batch_size):
593
+ kp_dict = {}
594
+ # Vectorized threshold check
595
+ valid_kps = kp_np[batch_idx, :, 0, 2] > kp_threshold
596
+ valid_indices = np.where(valid_kps)[0]
597
+
598
+ for ch_idx in valid_indices:
599
+ x = float(kp_np[batch_idx, ch_idx, 0, 0]) / w
600
+ y = float(kp_np[batch_idx, ch_idx, 0, 1]) / h
601
+ p = float(kp_np[batch_idx, ch_idx, 0, 2])
602
+ kp_dict[ch_idx + 1] = {'x': x, 'y': y, 'p': p}
603
+
604
+ batch_results.append(kp_dict)
605
+
606
+ return batch_results
607
+
608
+ def inference_batch(frames, model, kp_threshold, device, batch_size=8):
609
+ """Optimized batch inference for multiple frames"""
610
+ results = []
611
+ num_frames = len(frames)
612
+
613
+ # Get the device from the model itself
614
+ model_device = next(model.parameters()).device
615
+
616
+ # Process all frames in optimally-sized batches
617
+ for i in range(0, num_frames, batch_size):
618
+ current_batch_size = min(batch_size, num_frames - i)
619
+ batch_frames = frames[i:i + current_batch_size]
620
+
621
+ # Fast preprocessing - create on CPU first
622
+ batch = preprocess_batch_fast(batch_frames)
623
+ b, c, h, w = batch.size()
624
+
625
+ # Move batch to model device
626
+ batch = batch.to(model_device)
627
+
628
+ with torch.no_grad():
629
+ heatmaps = model(batch)
630
+
631
+ # Ultra-fast keypoint extraction
632
+ kp_coords = extract_keypoints_from_heatmap_fast(heatmaps[:,:-1,:,:], scale=2, max_keypoints=1)
633
+
634
+ # Vectorized batch processing - no loops
635
+ batch_results = process_keypoints_vectorized(kp_coords, kp_threshold, 960, 540, current_batch_size)
636
+ results.extend(batch_results)
637
+
638
+ # Minimal cleanup
639
+ del heatmaps, kp_coords, batch
640
+
641
+ return results
642
+
643
+ # Keypoint mapping from detection indices to standard football pitch keypoint IDs
644
+ map_keypoints = {
645
+ 1: 1, 2: 14, 3: 25, 4: 2, 5: 10, 6: 18, 7: 26, 8: 3, 9: 7, 10: 23,
646
+ 11: 27, 20: 4, 21: 8, 22: 24, 23: 28, 24: 5, 25: 13, 26: 21, 27: 29,
647
+ 28: 6, 29: 17, 30: 30, 31: 11, 32: 15, 33: 19, 34: 12, 35: 16, 36: 20,
648
+ 45: 9, 50: 31, 52: 32, 57: 22
649
+ }
650
+
651
+ def get_mapped_keypoints(kp_points):
652
+ """Apply keypoint mapping to detection results"""
653
+ mapped_points = {}
654
+ for key, value in kp_points.items():
655
+ if key in map_keypoints:
656
+ mapped_key = map_keypoints[key]
657
+ mapped_points[mapped_key] = value
658
+ # else:
659
+ # Keep unmapped keypoints with original key
660
+ # mapped_points[key] = value
661
+ return mapped_points
662
+
663
+ def process_batch_input(frames, model, kp_threshold, device, batch_size=8):
664
+ """Process multiple input images in batch"""
665
+ # Batch inference
666
+ kp_results = inference_batch(frames, model, kp_threshold, device, batch_size)
667
+ kp_results = [get_mapped_keypoints(kp) for kp in kp_results]
668
+ # Draw results and save
669
+ # for i, (frame, kp_points, input_path) in enumerate(zip(frames, kp_results, valid_paths)):
670
+ # height, width = frame.shape[:2]
671
+
672
+ # # Apply mapping to get standard keypoint IDs
673
+ # mapped_kp_points = get_mapped_keypoints(kp_points)
674
+
675
+ # for key, value in mapped_kp_points.items():
676
+ # x = int(value['x'] * width)
677
+ # y = int(value['y'] * height)
678
+ # cv2.circle(frame, (x, y), 5, (0, 255, 0), -1) # Green circles
679
+ # cv2.putText(frame, str(key), (x+10, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
680
+
681
+ # # Save result
682
+ # output_path = input_path.replace('.png', '_result.png').replace('.jpg', '_result.jpg')
683
+ # cv2.imwrite(output_path, frame)
684
+
685
+ # print(f"Batch processing complete. Processed {len(frames)} images.")
686
+
687
+ return kp_results
player.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ce9fc31f61e6f156f786077abb8eef36b0836bda1ef07d1d0ba82d43ae0ecd0b
3
+ size 22540152
player.py ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ from sklearn.cluster import KMeans
4
+ import warnings
5
+ import time
6
+
7
+ import torch
8
+ from torchvision.ops import batched_nms
9
+ from numpy import ndarray
10
+ # Suppress ALL runtime and sklearn warnings
11
+ warnings.filterwarnings('ignore', category=RuntimeWarning)
12
+ warnings.filterwarnings('ignore', category=FutureWarning)
13
+ warnings.filterwarnings('ignore', category=UserWarning)
14
+
15
+ # Suppress sklearn warnings specifically
16
+ import logging
17
+ logging.getLogger('sklearn').setLevel(logging.ERROR)
18
+
19
+ def get_grass_color(img):
20
+ # Convert image to HSV color space
21
+ hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
22
+
23
+ # Define range of green color in HSV
24
+ lower_green = np.array([30, 40, 40])
25
+ upper_green = np.array([80, 255, 255])
26
+
27
+ # Threshold the HSV image to get only green colors
28
+ mask = cv2.inRange(hsv, lower_green, upper_green)
29
+
30
+ # Calculate the mean value of the pixels that are not masked
31
+ masked_img = cv2.bitwise_and(img, img, mask=mask)
32
+ grass_color = cv2.mean(img, mask=mask)
33
+ return grass_color[:3]
34
+
35
+ def get_players_boxes(frame, result):
36
+ players_imgs = []
37
+ players_boxes = []
38
+ for (box, score, cls) in result:
39
+ label = int(cls)
40
+ if label == 0:
41
+ x1, y1, x2, y2 = box.astype(int)
42
+ player_img = frame[y1: y2, x1: x2]
43
+ players_imgs.append(player_img)
44
+ players_boxes.append([box, score, cls])
45
+ return players_imgs, players_boxes
46
+
47
+ def get_kits_colors(players, grass_hsv=None, frame=None):
48
+ kits_colors = []
49
+ if grass_hsv is None:
50
+ grass_color = get_grass_color(frame)
51
+ grass_hsv = cv2.cvtColor(np.uint8([[list(grass_color)]]), cv2.COLOR_BGR2HSV)
52
+
53
+ for player_img in players:
54
+ # Skip empty or invalid images
55
+ if player_img is None or player_img.size == 0 or len(player_img.shape) != 3:
56
+ continue
57
+
58
+ # Convert image to HSV color space
59
+ hsv = cv2.cvtColor(player_img, cv2.COLOR_BGR2HSV)
60
+
61
+ # Define range of green color in HSV
62
+ lower_green = np.array([grass_hsv[0, 0, 0] - 10, 40, 40])
63
+ upper_green = np.array([grass_hsv[0, 0, 0] + 10, 255, 255])
64
+
65
+ # Threshold the HSV image to get only green colors
66
+ mask = cv2.inRange(hsv, lower_green, upper_green)
67
+
68
+ # Bitwise-AND mask and original image
69
+ mask = cv2.bitwise_not(mask)
70
+ upper_mask = np.zeros(player_img.shape[:2], np.uint8)
71
+ upper_mask[0:player_img.shape[0]//2, 0:player_img.shape[1]] = 255
72
+ mask = cv2.bitwise_and(mask, upper_mask)
73
+
74
+ kit_color = np.array(cv2.mean(player_img, mask=mask)[:3])
75
+
76
+ kits_colors.append(kit_color)
77
+ return kits_colors
78
+
79
+ def get_kits_classifier(kits_colors):
80
+ if len(kits_colors) == 0:
81
+ return None
82
+ if len(kits_colors) == 1:
83
+ # Only one kit color, create a dummy classifier
84
+ return None
85
+ kits_kmeans = KMeans(n_clusters=2)
86
+ kits_kmeans.fit(kits_colors)
87
+ return kits_kmeans
88
+
89
+ def classify_kits(kits_classifer, kits_colors):
90
+ if kits_classifer is None or len(kits_colors) == 0:
91
+ return np.array([0]) # Default to team 0
92
+ team = kits_classifer.predict(kits_colors)
93
+ return team
94
+
95
+ def get_left_team_label(players_boxes, kits_colors, kits_clf):
96
+ left_team_label = 0
97
+ team_0 = []
98
+ team_1 = []
99
+
100
+ for i in range(len(players_boxes)):
101
+ x1, y1, x2, y2 = players_boxes[i][0].astype(int)
102
+ team = classify_kits(kits_clf, [kits_colors[i]]).item()
103
+ if team == 0:
104
+ team_0.append(np.array([x1]))
105
+ else:
106
+ team_1.append(np.array([x1]))
107
+
108
+ team_0 = np.array(team_0)
109
+ team_1 = np.array(team_1)
110
+
111
+ # Safely calculate averages with fallback for empty arrays
112
+ avg_team_0 = np.average(team_0) if len(team_0) > 0 else 0
113
+ avg_team_1 = np.average(team_1) if len(team_1) > 0 else 0
114
+
115
+ if avg_team_0 - avg_team_1 > 0:
116
+ left_team_label = 1
117
+
118
+ return left_team_label
119
+
120
+ def check_box_boundaries(boxes, img_height, img_width):
121
+ """
122
+ Check if bounding boxes are within image boundaries and clip them if necessary.
123
+
124
+ Args:
125
+ boxes: numpy array of shape (N, 4) with [x1, y1, x2, y2] format
126
+ img_height: height of the image
127
+ img_width: width of the image
128
+
129
+ Returns:
130
+ valid_boxes: numpy array of valid boxes within boundaries
131
+ valid_indices: indices of valid boxes
132
+ """
133
+ x1, y1, x2, y2 = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
134
+
135
+ # Check if boxes are within boundaries
136
+ valid_mask = (x1 >= 0) & (y1 >= 0) & (x2 < img_width) & (y2 < img_height) & (x1 < x2) & (y1 < y2)
137
+
138
+ if not np.any(valid_mask):
139
+ return np.array([]), np.array([])
140
+
141
+ valid_boxes = boxes[valid_mask]
142
+ valid_indices = np.where(valid_mask)[0]
143
+
144
+ # Clip boxes to image boundaries
145
+ valid_boxes[:, 0] = np.clip(valid_boxes[:, 0], 0, img_width - 1) # x1
146
+ valid_boxes[:, 1] = np.clip(valid_boxes[:, 1], 0, img_height - 1) # y1
147
+ valid_boxes[:, 2] = np.clip(valid_boxes[:, 2], 0, img_width - 1) # x2
148
+ valid_boxes[:, 3] = np.clip(valid_boxes[:, 3], 0, img_height - 1) # y2
149
+
150
+ return valid_boxes, valid_indices
151
+
152
+ def process_team_identification_batch(frames, results, kits_clf, left_team_label, grass_hsv):
153
+ """
154
+ Process team identification and label formatting for batch results.
155
+
156
+ Args:
157
+ frames: list of frames
158
+ results: list of detection results for each frame
159
+ kits_clf: trained kit classifier
160
+ left_team_label: label for left team
161
+ grass_hsv: grass color in HSV format
162
+
163
+ Returns:
164
+ processed_results: list of processed results with team identification
165
+ """
166
+ processed_results = []
167
+
168
+ for frame_idx, frame in enumerate(frames):
169
+ frame_results = []
170
+ frame_detections = results[frame_idx]
171
+
172
+ if not frame_detections:
173
+ processed_results.append([])
174
+ continue
175
+
176
+ # Extract player boxes and images
177
+ players_imgs = []
178
+ players_boxes = []
179
+ player_indices = []
180
+
181
+ for idx, (box, score, cls) in enumerate(frame_detections):
182
+ label = int(cls)
183
+ if label == 0: # Player detection
184
+ x1, y1, x2, y2 = box.astype(int)
185
+
186
+ # Check boundaries
187
+ if (x1 >= 0 and y1 >= 0 and x2 < frame.shape[1] and y2 < frame.shape[0] and x1 < x2 and y1 < y2):
188
+ player_img = frame[y1:y2, x1:x2]
189
+ if player_img.size > 0: # Ensure valid image
190
+ players_imgs.append(player_img)
191
+ players_boxes.append([box, score, cls])
192
+ player_indices.append(idx)
193
+
194
+ # Initialize player team mapping
195
+ player_team_map = {}
196
+
197
+ # Process team identification if we have players
198
+ if players_imgs and kits_clf is not None:
199
+ kits_colors = get_kits_colors(players_imgs, grass_hsv)
200
+ teams = classify_kits(kits_clf, kits_colors)
201
+
202
+ # Create mapping from player index to team
203
+ for i, team in enumerate(teams):
204
+ player_team_map[player_indices[i]] = team.item()
205
+
206
+ id = 0
207
+ # Process all detections with team identification
208
+ for idx, (box, score, cls) in enumerate(frame_detections):
209
+ label = int(cls)
210
+ x1, y1, x2, y2 = box.astype(int)
211
+
212
+ # Check boundaries
213
+ valid_boxes, valid_indices = check_box_boundaries(
214
+ np.array([[x1, y1, x2, y2]]), frame.shape[0], frame.shape[1]
215
+ )
216
+
217
+ if len(valid_boxes) == 0:
218
+ continue
219
+
220
+ x1, y1, x2, y2 = valid_boxes[0].astype(int)
221
+
222
+ # Apply team identification logic
223
+ if label == 0: # Player
224
+ if players_imgs and kits_clf is not None and idx in player_team_map:
225
+ team = player_team_map[idx]
226
+ if team == left_team_label:
227
+ final_label = 6 # Player-L (Left team)
228
+ else:
229
+ final_label = 7 # Player-R (Right team)
230
+ else:
231
+ final_label = 6 # Default player label
232
+
233
+ elif label == 1: # Goalkeeper
234
+ final_label = 1 # GK
235
+
236
+ elif label == 2: # Ball
237
+ final_label = 0 # Ball
238
+
239
+ elif label == 3 or label == 4: # Referee or other
240
+ final_label = 3 # Referee
241
+
242
+ else:
243
+ continue
244
+ # final_label = int(label) # Keep original label, ensure it's int
245
+
246
+ frame_results.append({
247
+ "id": int(id),
248
+ "bbox": [int(x1), int(y1), int(x2), int(y2)],
249
+ "class_id": int(final_label),
250
+ "conf": float(score)
251
+ })
252
+ id = id + 1
253
+
254
+ processed_results.append(frame_results)
255
+
256
+ return processed_results
257
+
258
+ def convert_numpy_types(obj):
259
+ """Convert numpy types to native Python types for JSON serialization."""
260
+ if isinstance(obj, np.integer):
261
+ return int(obj)
262
+ elif isinstance(obj, np.floating):
263
+ return float(obj)
264
+ elif isinstance(obj, np.ndarray):
265
+ return obj.tolist()
266
+ elif isinstance(obj, dict):
267
+ return {key: convert_numpy_types(value) for key, value in obj.items()}
268
+ elif isinstance(obj, list):
269
+ return [convert_numpy_types(item) for item in obj]
270
+ else:
271
+ return obj
272
+
273
+ def pre_process_img(frames, scale):
274
+ imgs = np.stack([cv2.resize(frame, (int(scale), int(scale))) for frame in frames])
275
+ imgs = imgs.transpose(0, 3, 1, 2)
276
+ imgs = imgs.astype(np.float32) / 255.0 # Normalize
277
+ return imgs
278
+
279
+ def post_process_output(outputs, x_scale, y_scale, conf_thresh=0.6, nms_thresh=0.75):
280
+ B, C, N = outputs.shape
281
+ outputs = torch.from_numpy(outputs)
282
+ outputs = outputs.permute(0, 2, 1)
283
+ boxes = outputs[..., :4]
284
+ class_scores = 1 / (1 + torch.exp(-outputs[..., 4:]))
285
+ conf, class_id = class_scores.max(dim=2)
286
+
287
+ mask = conf > conf_thresh
288
+
289
+ for i in range(class_id.shape[0]): # loop over batch
290
+ # Find detections that are balls
291
+ ball_idx = np.where(class_id[i] == 2)[0]
292
+ if ball_idx.size > 0:
293
+ # Pick the one with the highest confidence
294
+ top = ball_idx[np.argmax(conf[i, ball_idx])]
295
+ if conf[i, top] > 0.55: # apply confidence threshold
296
+ mask[i, top] = True
297
+
298
+ # ball_mask = (class_id == 2) & (conf > 0.51)
299
+ # mask = mask | ball_mask
300
+
301
+ batch_idx, pred_idx = mask.nonzero(as_tuple=True)
302
+
303
+ if len(batch_idx) == 0:
304
+ return [[] for _ in range(B)]
305
+
306
+ boxes = boxes[batch_idx, pred_idx]
307
+ conf = conf[batch_idx, pred_idx]
308
+ class_id = class_id[batch_idx, pred_idx]
309
+
310
+ x, y, w, h = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
311
+ x1 = (x - w / 2) * x_scale
312
+ y1 = (y - h / 2) * y_scale
313
+ x2 = (x + w / 2) * x_scale
314
+ y2 = (y + h / 2) * y_scale
315
+ boxes_xyxy = torch.stack([x1, y1, x2, y2], dim=1)
316
+
317
+ max_coord = 1e4
318
+ offset = batch_idx.to(boxes_xyxy) * max_coord
319
+ boxes_for_nms = boxes_xyxy + offset[:, None]
320
+
321
+ keep = batched_nms(boxes_for_nms, conf, batch_idx, nms_thresh)
322
+
323
+ boxes_final = boxes_xyxy[keep]
324
+ conf_final = conf[keep]
325
+ class_final = class_id[keep]
326
+ batch_final = batch_idx[keep]
327
+
328
+ results = [[] for _ in range(B)]
329
+ for b in range(B):
330
+ mask_b = batch_final == b
331
+ if mask_b.sum() == 0:
332
+ continue
333
+ results[b] = list(zip(boxes_final[mask_b].numpy(),
334
+ conf_final[mask_b].numpy(),
335
+ class_final[mask_b].numpy()))
336
+ return results
337
+
338
+ def player_detection_result(frames: list[ndarray], batch_size, model, kits_clf=None, left_team_label=None, grass_hsv=None):
339
+ start_time = time.time()
340
+ # input_layer = model.input(0)
341
+ # output_layer = model.output(0)
342
+ height, width = frames[0].shape[:2]
343
+ scale = 640.0
344
+ x_scale = width / scale
345
+ y_scale = height / scale
346
+
347
+ # infer_queue = AsyncInferQueue(model, len(frames))
348
+
349
+ infer_time = time.time()
350
+ kits_clf = kits_clf
351
+ left_team_label = left_team_label
352
+ grass_hsv = grass_hsv
353
+ results = []
354
+ for i in range(0, len(frames), batch_size):
355
+ if i + batch_size > len(frames):
356
+ batch_size = len(frames) - i
357
+ batch_frames = frames[i:i + batch_size]
358
+ imgs = pre_process_img(batch_frames, scale)
359
+
360
+ input_name = model.get_inputs()[0].name
361
+ outputs = model.run(None, {input_name: imgs})[0]
362
+ raw_results = post_process_output(np.array(outputs), x_scale, y_scale)
363
+
364
+ if kits_clf is None or left_team_label is None or grass_hsv is None:
365
+ # Use first frame to initialize team classification
366
+ first_frame = batch_frames[0]
367
+ first_frame_results = raw_results[0] if raw_results else []
368
+
369
+ if first_frame_results:
370
+ players_imgs, players_boxes = get_players_boxes(first_frame, first_frame_results)
371
+ if players_imgs:
372
+ grass_color = get_grass_color(first_frame)
373
+ grass_hsv = cv2.cvtColor(np.uint8([[list(grass_color)]]), cv2.COLOR_BGR2HSV)
374
+ kits_colors = get_kits_colors(players_imgs, grass_hsv)
375
+ if kits_colors: # Only proceed if we have valid kit colors
376
+ kits_clf = get_kits_classifier(kits_colors)
377
+ if kits_clf is not None:
378
+ left_team_label = int(get_left_team_label(players_boxes, kits_colors, kits_clf))
379
+
380
+ # Process team identification and boundary checking
381
+ processed_results = process_team_identification_batch(
382
+ batch_frames, raw_results, kits_clf, left_team_label, grass_hsv
383
+ )
384
+
385
+ processed_results = convert_numpy_types(processed_results)
386
+ results.extend(processed_results)
387
+
388
+ # Return the same format as before for compatibility
389
+ return results, kits_clf, left_team_label, grass_hsv