zilo-det 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- zilo_det/__init__.py +3 -0
- zilo_det/__main__.py +14 -0
- zilo_det/detect.py +102 -0
- zilo_det/model.json +102 -0
- zilo_det/models.py +68 -0
- zilo_det-0.1.0.dist-info/LICENSE +661 -0
- zilo_det-0.1.0.dist-info/METADATA +705 -0
- zilo_det-0.1.0.dist-info/RECORD +10 -0
- zilo_det-0.1.0.dist-info/WHEEL +5 -0
- zilo_det-0.1.0.dist-info/top_level.txt +1 -0
zilo_det/__init__.py
ADDED
zilo_det/__main__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
from .models import install_local
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def main():
|
|
6
|
+
parser = argparse.ArgumentParser(description="Install a verified local ZiLO ONNX model.")
|
|
7
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
8
|
+
commands.add_parser("install").add_argument("onnx")
|
|
9
|
+
args = parser.parse_args()
|
|
10
|
+
print(install_local(args.onnx))
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
if __name__ == "__main__":
|
|
14
|
+
main()
|
zilo_det/detect.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
from numbers import Integral, Real
|
|
3
|
+
from os import PathLike
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
import cv2
|
|
7
|
+
import numpy as np
|
|
8
|
+
import onnxruntime as ort
|
|
9
|
+
|
|
10
|
+
from . import models
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class Detections:
|
|
15
|
+
xyxy: np.ndarray
|
|
16
|
+
scores: np.ndarray
|
|
17
|
+
class_ids: np.ndarray
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def prepare(image):
|
|
21
|
+
if isinstance(image, (str, PathLike)):
|
|
22
|
+
buf = np.frombuffer(Path(image).read_bytes(), dtype=np.uint8)
|
|
23
|
+
image = cv2.imdecode(buf, cv2.IMREAD_COLOR) if buf.size else None
|
|
24
|
+
if image is None:
|
|
25
|
+
raise ValueError("Cannot decode image file")
|
|
26
|
+
if (not isinstance(image, np.ndarray) or image.dtype != np.uint8 or
|
|
27
|
+
image.ndim != 3 or image.shape[2] != 3 or not image.size):
|
|
28
|
+
raise ValueError("Expected an image path or nonempty HxWx3 uint8 BGR frame")
|
|
29
|
+
h, w = image.shape[:2]
|
|
30
|
+
gain = 640 / max(h, w)
|
|
31
|
+
rw, rh = max(1, round(w * gain)), max(1, round(h * gain))
|
|
32
|
+
left, top = (640 - rw) // 2, (640 - rh) // 2
|
|
33
|
+
canvas = np.full((640, 640, 3), 114, np.uint8)
|
|
34
|
+
canvas[top:top + rh, left:left + rw] = cv2.resize(image, (rw, rh), interpolation=cv2.INTER_LINEAR)
|
|
35
|
+
tensor = np.ascontiguousarray(canvas[:, :, ::-1].transpose(2, 0, 1)[None], dtype=np.float32)
|
|
36
|
+
tensor /= 255
|
|
37
|
+
return tensor, (gain, left, top, h, w)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _nms(boxes, scores, ids, iou, limit):
|
|
41
|
+
order = np.argsort(-scores, kind="stable")
|
|
42
|
+
area = np.maximum(0, boxes[:, 2:] - boxes[:, :2]).prod(axis=1)
|
|
43
|
+
keep = []
|
|
44
|
+
while order.size and len(keep) < limit:
|
|
45
|
+
i = order[0]
|
|
46
|
+
keep.append(i)
|
|
47
|
+
rest = order[1:]
|
|
48
|
+
overlap = (np.minimum(boxes[rest, 2:], boxes[i, 2:]) -
|
|
49
|
+
np.maximum(boxes[rest, :2], boxes[i, :2])).clip(min=0).prod(axis=1)
|
|
50
|
+
union = area[i] + area[rest] - overlap
|
|
51
|
+
order = rest[~((ids[i] == ids[rest]) & (overlap > iou * union))]
|
|
52
|
+
return np.asarray(keep, dtype=np.intp)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def postprocess(raw, geometry, conf, iou, max_det):
|
|
56
|
+
rows = raw[0].T
|
|
57
|
+
ids = np.argmax(rows[:, 4:], axis=1).astype(np.int64)
|
|
58
|
+
scores = rows[np.arange(len(rows)), 4 + ids]
|
|
59
|
+
mask = scores > conf
|
|
60
|
+
xy, wh = rows[mask, :2], rows[mask, 2:4]
|
|
61
|
+
boxes = np.concatenate((xy - wh / 2, xy + wh / 2), axis=1)
|
|
62
|
+
scores, ids = scores[mask], ids[mask]
|
|
63
|
+
keep = _nms(boxes, scores, ids, iou, max_det)
|
|
64
|
+
boxes = boxes[keep]
|
|
65
|
+
gain, left, top, h, w = geometry
|
|
66
|
+
boxes[:, 0::2] = ((boxes[:, 0::2] - left) / gain).clip(0, w)
|
|
67
|
+
boxes[:, 1::2] = ((boxes[:, 1::2] - top) / gain).clip(0, h)
|
|
68
|
+
return Detections(boxes, scores[keep], ids[keep])
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class Detector:
|
|
72
|
+
names = tuple(models.SPEC["names"])
|
|
73
|
+
|
|
74
|
+
def __init__(self, onnx_path):
|
|
75
|
+
self._open(models.verified(onnx_path))
|
|
76
|
+
|
|
77
|
+
def _open(self, verified_path):
|
|
78
|
+
options = ort.SessionOptions()
|
|
79
|
+
options.intra_op_num_threads = 2
|
|
80
|
+
self._session = ort.InferenceSession(str(verified_path), sess_options=options,
|
|
81
|
+
providers=["CPUExecutionProvider"])
|
|
82
|
+
inp, = self._session.get_inputs()
|
|
83
|
+
out, = self._session.get_outputs()
|
|
84
|
+
if (inp.shape != models.SPEC["input_shape"] or out.shape != models.SPEC["output_shape"]
|
|
85
|
+
or inp.type != "tensor(float)" or out.type != "tensor(float)"):
|
|
86
|
+
raise ValueError("Incompatible ZiLO ONNX signature")
|
|
87
|
+
self._input, self._output = inp.name, out.name
|
|
88
|
+
|
|
89
|
+
@classmethod
|
|
90
|
+
def from_pretrained(cls, alias="zilo-base-coco", *, local_files_only=False):
|
|
91
|
+
instance = cls.__new__(cls)
|
|
92
|
+
instance._open(models.resolve(alias, local_files_only=local_files_only))
|
|
93
|
+
return instance
|
|
94
|
+
|
|
95
|
+
def predict(self, image, *, conf=0.25, iou=0.7, max_det=300):
|
|
96
|
+
if not all(isinstance(x, Real) and 0 <= x <= 1 for x in (conf, iou)):
|
|
97
|
+
raise ValueError("conf and iou must be in [0, 1]")
|
|
98
|
+
if isinstance(max_det, bool) or not isinstance(max_det, Integral) or max_det < 1:
|
|
99
|
+
raise ValueError("max_det must be a positive integer")
|
|
100
|
+
x, geometry = prepare(image)
|
|
101
|
+
raw, = self._session.run([self._output], {self._input: x})
|
|
102
|
+
return postprocess(raw, geometry, conf, iou, max_det)
|
zilo_det/model.json
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
{
|
|
2
|
+
"alias": "zilo-base-coco",
|
|
3
|
+
"filename": "zilo-base-coco.onnx",
|
|
4
|
+
"source_sha256": "9c15d17603878924ac6b62754724546dea16583906d00346b9c825c6bde49977",
|
|
5
|
+
"sha256": "01d9e6491accfdd49115b71eee5918d334bc7ab5c5677f55ea9889f76ded9e1f",
|
|
6
|
+
"opset": 17,
|
|
7
|
+
"input_shape": [
|
|
8
|
+
1,
|
|
9
|
+
3,
|
|
10
|
+
640,
|
|
11
|
+
640
|
|
12
|
+
],
|
|
13
|
+
"output_shape": [
|
|
14
|
+
1,
|
|
15
|
+
84,
|
|
16
|
+
8400
|
|
17
|
+
],
|
|
18
|
+
"names": [
|
|
19
|
+
"person",
|
|
20
|
+
"bicycle",
|
|
21
|
+
"car",
|
|
22
|
+
"motorcycle",
|
|
23
|
+
"airplane",
|
|
24
|
+
"bus",
|
|
25
|
+
"train",
|
|
26
|
+
"truck",
|
|
27
|
+
"boat",
|
|
28
|
+
"traffic light",
|
|
29
|
+
"fire hydrant",
|
|
30
|
+
"stop sign",
|
|
31
|
+
"parking meter",
|
|
32
|
+
"bench",
|
|
33
|
+
"bird",
|
|
34
|
+
"cat",
|
|
35
|
+
"dog",
|
|
36
|
+
"horse",
|
|
37
|
+
"sheep",
|
|
38
|
+
"cow",
|
|
39
|
+
"elephant",
|
|
40
|
+
"bear",
|
|
41
|
+
"zebra",
|
|
42
|
+
"giraffe",
|
|
43
|
+
"backpack",
|
|
44
|
+
"umbrella",
|
|
45
|
+
"handbag",
|
|
46
|
+
"tie",
|
|
47
|
+
"suitcase",
|
|
48
|
+
"frisbee",
|
|
49
|
+
"skis",
|
|
50
|
+
"snowboard",
|
|
51
|
+
"sports ball",
|
|
52
|
+
"kite",
|
|
53
|
+
"baseball bat",
|
|
54
|
+
"baseball glove",
|
|
55
|
+
"skateboard",
|
|
56
|
+
"surfboard",
|
|
57
|
+
"tennis racket",
|
|
58
|
+
"bottle",
|
|
59
|
+
"wine glass",
|
|
60
|
+
"cup",
|
|
61
|
+
"fork",
|
|
62
|
+
"knife",
|
|
63
|
+
"spoon",
|
|
64
|
+
"bowl",
|
|
65
|
+
"banana",
|
|
66
|
+
"apple",
|
|
67
|
+
"sandwich",
|
|
68
|
+
"orange",
|
|
69
|
+
"broccoli",
|
|
70
|
+
"carrot",
|
|
71
|
+
"hot dog",
|
|
72
|
+
"pizza",
|
|
73
|
+
"donut",
|
|
74
|
+
"cake",
|
|
75
|
+
"chair",
|
|
76
|
+
"couch",
|
|
77
|
+
"potted plant",
|
|
78
|
+
"bed",
|
|
79
|
+
"dining table",
|
|
80
|
+
"toilet",
|
|
81
|
+
"tv",
|
|
82
|
+
"laptop",
|
|
83
|
+
"mouse",
|
|
84
|
+
"remote",
|
|
85
|
+
"keyboard",
|
|
86
|
+
"cell phone",
|
|
87
|
+
"microwave",
|
|
88
|
+
"oven",
|
|
89
|
+
"toaster",
|
|
90
|
+
"sink",
|
|
91
|
+
"refrigerator",
|
|
92
|
+
"book",
|
|
93
|
+
"clock",
|
|
94
|
+
"vase",
|
|
95
|
+
"scissors",
|
|
96
|
+
"teddy bear",
|
|
97
|
+
"hair drier",
|
|
98
|
+
"toothbrush"
|
|
99
|
+
],
|
|
100
|
+
"repo_id": "Rocky-129/zilo-base-coco",
|
|
101
|
+
"revision": "abbf772d71f7c591e31a0cfa66682a55ed61b22d"
|
|
102
|
+
}
|
zilo_det/models.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Content-checked model storage. Unpublished models can only be installed locally."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import re
|
|
7
|
+
import tempfile
|
|
8
|
+
from urllib.request import urlopen
|
|
9
|
+
|
|
10
|
+
SPEC = json.loads(Path(__file__).with_name("model.json").read_text(encoding="utf-8"))
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _digest(path):
|
|
14
|
+
digest = hashlib.sha256()
|
|
15
|
+
with path.open("rb") as stream:
|
|
16
|
+
for block in iter(lambda: stream.read(1 << 20), b""):
|
|
17
|
+
digest.update(block)
|
|
18
|
+
return digest.hexdigest()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def verified(path):
|
|
22
|
+
path = Path(path)
|
|
23
|
+
if _digest(path) != SPEC["sha256"]:
|
|
24
|
+
raise ValueError(f"ZiLO model SHA-256 mismatch: {path}. Reinstall the verified ONNX.")
|
|
25
|
+
return path
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _target():
|
|
29
|
+
root = Path(os.environ.get("ZILO_DET_CACHE") or Path.home() / ".cache" / "zilo-det")
|
|
30
|
+
return root / SPEC["sha256"] / SPEC["filename"]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _store(stream, target):
|
|
34
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
35
|
+
with tempfile.NamedTemporaryFile(dir=target.parent, delete=False) as out:
|
|
36
|
+
tmp = Path(out.name)
|
|
37
|
+
try:
|
|
38
|
+
with tmp.open("wb") as out:
|
|
39
|
+
for block in iter(lambda: stream.read(1 << 20), b""):
|
|
40
|
+
out.write(block)
|
|
41
|
+
verified(tmp)
|
|
42
|
+
tmp.replace(target)
|
|
43
|
+
finally:
|
|
44
|
+
tmp.unlink(missing_ok=True)
|
|
45
|
+
return target
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def install_local(path):
|
|
49
|
+
"""Verify and atomically install the model into this user's cross-project cache."""
|
|
50
|
+
with Path(path).open("rb") as stream:
|
|
51
|
+
return _store(stream, _target())
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def resolve(alias, local_files_only=False):
|
|
55
|
+
if alias != SPEC["alias"]:
|
|
56
|
+
raise KeyError(f"Unknown model: {alias}. Available: {SPEC['alias']}")
|
|
57
|
+
target = _target()
|
|
58
|
+
if target.is_file():
|
|
59
|
+
return verified(target)
|
|
60
|
+
if local_files_only or not SPEC.get("repo_id"):
|
|
61
|
+
raise FileNotFoundError(f"No cached {alias} at {target}. Seed this cache with "
|
|
62
|
+
f"'python -m zilo_det install PATH_TO_ONNX'.")
|
|
63
|
+
revision = SPEC.get("revision", "")
|
|
64
|
+
if not re.fullmatch(r"[a-f0-9]{40}", revision):
|
|
65
|
+
raise ValueError("A full immutable Hub commit is required.")
|
|
66
|
+
url = f"https://huggingface.co/{SPEC['repo_id']}/resolve/{revision}/{SPEC['filename']}"
|
|
67
|
+
with urlopen(url, timeout=60) as stream:
|
|
68
|
+
return _store(stream, target)
|