File size: 3,925 Bytes
e21e264
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
"""Acquire pinned BaseballCV weights and export raw, static ONNX for the GPU worker.

PyTorch/Ultralytics are build dependencies only. Inference uses ONNX Runtime.
"""
import argparse
import hashlib
import json
from pathlib import Path
import urllib.request

SOURCES = {
    "bat": ("https://data.balldatalab.com/index.php/s/jsLpPR8rXrk5Ndr/download/bat_tracking_v2.pt", "774eda0281c3485e4a8dd620280fd90c79b15783c7cd6de965a937ee46d793bb"),
    "ball": ("https://data.balldatalab.com/index.php/s/YkGBwbFtsf34ky3/download/ball_tracking_v4-YOLOv11.pt", "00faa0a129ef4b25bcc4f4610d70211efed6470d89225618cc6ffab000f507d0"),
}


def checksum(path):
    h = hashlib.sha256()
    with Path(path).open('rb') as source:
        for block in iter(lambda: source.read(1024*1024), b''):
            h.update(block)
    return h.hexdigest()


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--output', default='downloads')
    parser.add_argument('--weights', default='downloads/load_timing_models')
    parser.add_argument('--bat-checkpoint', type=Path, help='Trusted local YOLO pose checkpoint with actual shaft endpoints')
    parser.add_argument('--ball-checkpoint', type=Path, help='Trusted local YOLO detection checkpoint with baseball/ball class')
    args = parser.parse_args()
    weights = Path(args.weights)
    weights.mkdir(parents=True, exist_ok=True)
    from ultralytics import YOLO
    for name, (url, expected) in SOURCES.items():
        override = getattr(args, name+'_checkpoint')
        source = override if override is not None else weights/(name+'.pt')
        if override is not None:
            expected = checksum(source)
            url = 'trusted_local_checkpoint:'+source.name
        if override is None and not source.exists():
            temporary = source.with_suffix('.partial')
            with urllib.request.urlopen(url, timeout=60) as response, temporary.open('wb') as out:
                for block in iter(lambda: response.read(1024*1024), b''):
                    out.write(block)
            if checksum(temporary) != expected:
                temporary.unlink()
                raise ValueError(f'{name} checkpoint checksum mismatch')
            temporary.replace(source)
        if checksum(source) != expected:
            raise ValueError(f'{name} checkpoint checksum mismatch')
        model = YOLO(str(source), task='pose' if name == 'bat' else 'detect')
        shape = getattr(model.model.model[-1], 'kpt_shape', None)
        if name == 'bat' and (shape is None or shape[0] < 2 or shape[1] != 3):
            raise ValueError(f'Expected visible shaft keypoints, got {shape}')
        labels = {'bat'} if name == 'bat' else {'baseball', 'ball'}
        if sum(label in labels for label in model.names.values()) != 1:
            raise ValueError(f'Expected one unambiguous target class for {name}')
        exported = Path(model.export(format='onnx', imgsz=640, opset=17,
                                     simplify=False, dynamic=False, nms=False, device='cpu'))
        target = Path(args.output)/('tracking_'+name)
        target.mkdir(parents=True, exist_ok=True)
        (target/'model.onnx').write_bytes(exported.read_bytes())
        record = {'name': name, 'checkpoint_sha256': expected,
                  'onnx_sha256': checksum(target/'model.onnx'), 'source': url,
                  'registry_revision': None if override is not None else 'c3c26c979766b28e0c78c3fee2edc2aa3dad571e',
                  'input_size': 640, 'classes': model.names, 'keypoint_shape': shape,
                  'endpoint_order': 'extreme observed shaft landmarks; barrel identity requires hand proximity evidence',
                  'export': 'ultralytics-8.4.175; opset17; static; raw; float32'}
        (target/'model.json').write_text(json.dumps(record, indent=2)+'\n')
        print(name, record['onnx_sha256'], flush=True)


if __name__ == '__main__':
    main()