tarsius 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.
tarsius/__init__.py ADDED
@@ -0,0 +1,41 @@
1
+ """Local, training-free state detection for a region of a camera image."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ from .backends.edges import EdgeBackend
6
+ from .backends.ncnn import NcnnBackend
7
+ from .classifier import Classifier, Result, Status
8
+ from .errors import (
9
+ BackendError,
10
+ BackendMismatchError,
11
+ FeaturesError,
12
+ ImageError,
13
+ TarsiusError,
14
+ )
15
+ from .features import FeatureBackend, Features, Reference, extract_features
16
+ from .image import load_image
17
+ from .roi import FULL_FRAME, Roi
18
+ from .vote import majority
19
+
20
+ __version__ = version("tarsius")
21
+
22
+ __all__ = [
23
+ "FULL_FRAME",
24
+ "BackendError",
25
+ "BackendMismatchError",
26
+ "Classifier",
27
+ "EdgeBackend",
28
+ "FeatureBackend",
29
+ "Features",
30
+ "FeaturesError",
31
+ "ImageError",
32
+ "NcnnBackend",
33
+ "Reference",
34
+ "Result",
35
+ "Roi",
36
+ "Status",
37
+ "TarsiusError",
38
+ "extract_features",
39
+ "load_image",
40
+ "majority",
41
+ ]
@@ -0,0 +1 @@
1
+ """Feature backends."""
@@ -0,0 +1,49 @@
1
+ """Edge map backend: numpy only, needs a tight region."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+ from PIL import Image, ImageFilter
7
+
8
+ from ..features import Vector, unit
9
+
10
+ SIZE = (128, 96)
11
+ # Pixels the region may move between frames, e.g. after a camera bump.
12
+ SHIFT = 2
13
+
14
+
15
+ class EdgeBackend:
16
+ """
17
+ Gradient magnitude compared by normalized cross-correlation.
18
+
19
+ Baseline without extra dependencies. Anything moved inside the region
20
+ changes the edges, so the region must be tight, and it must keep some
21
+ static structure (door, wall edges) for the empty state: a featureless
22
+ region has nothing to compare.
23
+ """
24
+
25
+ id = "edges/1"
26
+ default_margin = 0.02
27
+
28
+ def extract(self, image: Image.Image) -> tuple[Vector, Vector]:
29
+ """Return the centre crop and every shifted window of the edge map."""
30
+ gray = image.convert("L").resize(SIZE, Image.Resampling.BILINEAR)
31
+ pixels = np.asarray(gray.filter(ImageFilter.GaussianBlur(1)), np.float32)
32
+ grad_x = np.zeros_like(pixels)
33
+ grad_y = np.zeros_like(pixels)
34
+ grad_x[:, 1:-1] = pixels[:, 2:] - pixels[:, :-2]
35
+ grad_y[1:-1, :] = pixels[2:, :] - pixels[:-2, :]
36
+ edges = np.hypot(grad_x, grad_y)
37
+ height, width = edges.shape
38
+ inner = (slice(SHIFT, height - SHIFT), slice(SHIFT, width - SHIFT))
39
+ windows = [
40
+ unit(
41
+ edges[
42
+ SHIFT + dy : height - SHIFT + dy,
43
+ SHIFT + dx : width - SHIFT + dx,
44
+ ]
45
+ )
46
+ for dy in range(-SHIFT, SHIFT + 1)
47
+ for dx in range(-SHIFT, SHIFT + 1)
48
+ ]
49
+ return unit(edges[inner]), np.stack(windows)
@@ -0,0 +1,76 @@
1
+ """SqueezeNet embedding backend on ncnn."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib.resources import as_file, files
6
+
7
+ import numpy as np
8
+ from PIL import Image
9
+
10
+ from ..errors import BackendError
11
+ from ..features import Vector
12
+
13
+ _INPUT = 227
14
+ _MEAN = [104.0, 117.0, 123.0]
15
+ # Last feature map before the ImageNet classifier, 512 channels.
16
+ _BLOB = "fire9/concat_drop9"
17
+
18
+
19
+ class NcnnBackend:
20
+ """
21
+ ImageNet SqueezeNet 1.1 features, averaged over the feature map.
22
+
23
+ No training: the network only describes the region, the classifier
24
+ compares those descriptions. Robust to clutter and lighting, so a rough
25
+ region is enough.
26
+ """
27
+
28
+ # Bump with any change to the model, ncnn options or preprocessing.
29
+ id = "squeezenet11/1"
30
+ default_margin = 0.02
31
+
32
+ def __init__(self, *, threads: int = 1) -> None:
33
+ """Load the bundled model; raises ImportError without the ``ncnn`` extra."""
34
+ try:
35
+ import ncnn # noqa: PLC0415
36
+ except ImportError as err: # pragma: no cover - depends on the environment
37
+ raise ImportError("NcnnBackend needs `pip install tarsius[ncnn]`") from err
38
+ self._ncnn = ncnn
39
+ self._net = ncnn.Net()
40
+ opt = self._net.opt
41
+ opt.num_threads = threads
42
+ # fp16 arithmetic differs between CPUs; keep features comparable when
43
+ # references move to other hardware, e.g. restored from a backup.
44
+ opt.use_fp16_arithmetic = False
45
+ opt.use_vulkan_compute = False
46
+ models = files("tarsius") / "models"
47
+ param = models / "squeezenet_v1.1.param"
48
+ model = models / "squeezenet_v1.1.bin"
49
+ if not (param.is_file() and model.is_file()):
50
+ raise BackendError("bundled SqueezeNet model is missing")
51
+ with as_file(param) as param_path, as_file(model) as model_path:
52
+ if self._net.load_param(str(param_path)) or self._net.load_model(
53
+ str(model_path)
54
+ ):
55
+ raise BackendError("ncnn could not load the SqueezeNet model")
56
+
57
+ def extract(self, image: Image.Image) -> tuple[Vector, Vector]:
58
+ """Return the unit-norm embedding as both reference and query."""
59
+ ncnn = self._ncnn
60
+ # PIL antialiases when shrinking, ncnn's own resize does not.
61
+ resized = image.convert("RGB").resize(
62
+ (_INPUT, _INPUT), Image.Resampling.BILINEAR
63
+ )
64
+ bgr = np.ascontiguousarray(np.asarray(resized)[..., ::-1])
65
+ mat = ncnn.Mat.from_pixels(bgr, ncnn.Mat.PixelType.PIXEL_BGR, _INPUT, _INPUT)
66
+ mat.substract_mean_normalize(_MEAN, [])
67
+ extractor = self._net.create_extractor()
68
+ extractor.input("data", mat)
69
+ ret, out = extractor.extract(_BLOB)
70
+ if ret: # pragma: no cover - ncnn reports no recoverable cause
71
+ raise BackendError(f"ncnn extraction failed with {ret}")
72
+ maps = np.array(out, dtype=np.float32)
73
+ embedding = maps.reshape(maps.shape[0], -1).mean(axis=1)
74
+ norm = float(np.linalg.norm(embedding))
75
+ vector = embedding / norm if norm > 0 else embedding
76
+ return vector, vector[None]
tarsius/classifier.py ADDED
@@ -0,0 +1,179 @@
1
+ """Nearest-reference classifier with explicit "unsure" and "not ready" results."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+ from collections.abc import Mapping
7
+ from dataclasses import dataclass, field
8
+ from enum import StrEnum
9
+ from typing import NamedTuple
10
+
11
+ import numpy as np
12
+ import numpy.typing as npt
13
+
14
+ from .errors import BackendMismatchError
15
+ from .features import FeatureBackend, Features, Reference, Vector
16
+
17
+
18
+ class Status(StrEnum):
19
+ """Why a result has or lacks a state."""
20
+
21
+ CONFIDENT = "confident"
22
+ # The best state does not beat the runner-up by the margin: ask the user.
23
+ UNSURE = "unsure"
24
+ # Fewer than two states have references: nothing to compare yet.
25
+ NOT_READY = "not_ready"
26
+
27
+
28
+ @dataclass(frozen=True, slots=True)
29
+ class Result:
30
+ """Outcome of one classification."""
31
+
32
+ status: Status
33
+ # Set only when confident.
34
+ state: str | None = None
35
+ # Best state even when unsure, e.g. to ask "is this <candidate>?".
36
+ candidate: str | None = None
37
+ margin: float = 0.0
38
+ # Diagnostics only; the scale depends on the backend.
39
+ scores: Mapping[str, float] = field(default_factory=dict)
40
+ # Most similar reference key per state.
41
+ nearest: Mapping[str, str] = field(default_factory=dict)
42
+
43
+
44
+ class _Index(NamedTuple):
45
+ keys: tuple[str, ...]
46
+ labels: npt.NDArray[np.str_]
47
+ matrix: Vector
48
+
49
+
50
+ class Classifier:
51
+ """
52
+ k-nearest references per state, compared by similarity.
53
+
54
+ A state wins only when its mean top-k similarity beats every other state
55
+ by ``margin``. ``k`` shrinks to the smallest state's reference count, so
56
+ adding references to one state never makes it lose. Safe to share between
57
+ threads: changes swap in a new snapshot that lookups read once.
58
+ """
59
+
60
+ def __init__(self, backend_id: str, *, margin: float, k: int = 3) -> None:
61
+ """Create an empty classifier for features of ``backend_id``."""
62
+ if k < 1:
63
+ raise ValueError("k must be at least 1")
64
+ if margin <= 0:
65
+ raise ValueError("margin must be positive, a tie is never confident")
66
+ self.backend_id = backend_id
67
+ self.margin = margin
68
+ self.k = k
69
+ self._lock = threading.Lock()
70
+ self._refs: dict[str, tuple[str, Vector]] = {}
71
+ self._index: _Index | None = None
72
+
73
+ @classmethod
74
+ def for_backend(cls, backend: FeatureBackend, *, k: int = 3) -> Classifier:
75
+ """Create a classifier with the backend's id and default margin."""
76
+ return cls(backend.id, margin=backend.default_margin, k=k)
77
+
78
+ def add(self, key: str, features: Features | Reference, *, state: str) -> None:
79
+ """
80
+ Add or replace the reference ``key``.
81
+
82
+ Raises ValueError for a region without any structure, e.g. a blank
83
+ frame from an offline camera, since it would match nothing.
84
+ """
85
+ self._check(features.backend_id)
86
+ vector = features.vector
87
+ if not np.linalg.norm(vector) > 0:
88
+ raise ValueError("reference has no structure to compare")
89
+ with self._lock:
90
+ index = self._index
91
+ if index is not None and index.matrix.shape[1] != vector.shape[0]:
92
+ raise BackendMismatchError(
93
+ f"vector length {vector.shape[0]}, expected {index.matrix.shape[1]}"
94
+ )
95
+ self._refs[key] = (state, vector)
96
+ self._index = self._build()
97
+
98
+ def remove(self, key: str) -> None:
99
+ """Drop the reference ``key`` if present."""
100
+ with self._lock:
101
+ if self._refs.pop(key, None) is not None:
102
+ self._index = self._build()
103
+
104
+ def clear(self) -> None:
105
+ """Drop all references."""
106
+ with self._lock:
107
+ self._refs.clear()
108
+ self._index = None
109
+
110
+ def references(self) -> dict[str, str]:
111
+ """Return the state of every reference key."""
112
+ index = self._index
113
+ if index is None:
114
+ return {}
115
+ return dict(zip(index.keys, index.labels.tolist(), strict=True))
116
+
117
+ def counts(self) -> dict[str, int]:
118
+ """Return the number of references per state."""
119
+ index = self._index
120
+ if index is None:
121
+ return {}
122
+ states, counts = np.unique(index.labels, return_counts=True)
123
+ return dict(zip(states.tolist(), counts.tolist(), strict=True))
124
+
125
+ @property
126
+ def ready(self) -> bool:
127
+ """Return True once at least two states have references."""
128
+ return len(self.counts()) >= 2
129
+
130
+ def __len__(self) -> int:
131
+ """Return the number of references."""
132
+ index = self._index
133
+ return 0 if index is None else len(index.keys)
134
+
135
+ def classify(self, features: Features) -> Result:
136
+ """Classify ``features`` against the references."""
137
+ self._check(features.backend_id)
138
+ index = self._index
139
+ if index is None:
140
+ return Result(Status.NOT_READY)
141
+ states, counts = np.unique(index.labels, return_counts=True)
142
+ if len(states) < 2:
143
+ return Result(Status.NOT_READY)
144
+ similarity = (features.query @ index.matrix.T).max(axis=0)
145
+ k = min(self.k, int(counts.min()))
146
+ scores: dict[str, float] = {}
147
+ nearest: dict[str, str] = {}
148
+ for state in states.tolist():
149
+ members = np.flatnonzero(index.labels == state)
150
+ ranked = members[np.argsort(similarity[members])[::-1]]
151
+ scores[state] = float(similarity[ranked[:k]].mean())
152
+ nearest[state] = index.keys[ranked[0]]
153
+ best, runner_up = sorted(scores, key=scores.__getitem__, reverse=True)[:2]
154
+ margin = scores[best] - scores[runner_up]
155
+ confident = margin >= self.margin
156
+ return Result(
157
+ Status.CONFIDENT if confident else Status.UNSURE,
158
+ best if confident else None,
159
+ best,
160
+ margin,
161
+ scores,
162
+ nearest,
163
+ )
164
+
165
+ def _check(self, backend_id: str) -> None:
166
+ if backend_id != self.backend_id:
167
+ raise BackendMismatchError(
168
+ f"features from {backend_id}, expected {self.backend_id}"
169
+ )
170
+
171
+ def _build(self) -> _Index | None:
172
+ if not self._refs:
173
+ return None
174
+ keys = tuple(self._refs)
175
+ return _Index(
176
+ keys,
177
+ np.array([self._refs[key][0] for key in keys]),
178
+ np.stack([self._refs[key][1] for key in keys]),
179
+ )
tarsius/errors.py ADDED
@@ -0,0 +1,23 @@
1
+ """Exceptions raised by tarsius."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class TarsiusError(Exception):
7
+ """Base class for all tarsius errors."""
8
+
9
+
10
+ class ImageError(TarsiusError):
11
+ """The image could not be decoded, e.g. a camera returned an error page."""
12
+
13
+
14
+ class BackendError(TarsiusError):
15
+ """A feature backend could not load its model or process an image."""
16
+
17
+
18
+ class BackendMismatchError(TarsiusError, ValueError):
19
+ """Features come from another backend than the classifier expects."""
20
+
21
+
22
+ class FeaturesError(TarsiusError):
23
+ """Stored features are corrupt or written by an incompatible version."""
tarsius/features.py ADDED
@@ -0,0 +1,101 @@
1
+ """Feature vectors and the backend protocol."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import zipfile
6
+ from dataclasses import dataclass
7
+ from io import BytesIO
8
+ from typing import Protocol
9
+
10
+ import numpy as np
11
+ import numpy.typing as npt
12
+ from PIL import Image
13
+
14
+ from .errors import FeaturesError
15
+ from .roi import FULL_FRAME, Roi
16
+
17
+ type Vector = npt.NDArray[np.float32]
18
+
19
+ # Bump when the stored layout changes; older data then fails to load.
20
+ _FORMAT = 1
21
+
22
+
23
+ class FeatureBackend(Protocol):
24
+ """Turns an image region into vectors that compare by dot product."""
25
+
26
+ # Changes whenever extracted features change, so stored ones get rebuilt.
27
+ id: str
28
+ # Similarity gap between the two best states below which a result is unsure.
29
+ default_margin: float
30
+
31
+ def extract(self, image: Image.Image) -> tuple[Vector, Vector]:
32
+ """
33
+ Return ``(vector, query)`` for ``image``.
34
+
35
+ ``vector`` is the unit-norm reference form. ``query`` holds one or more
36
+ unit-norm rows; the similarity of a query to a reference is the best
37
+ row, which lets a backend tolerate small camera shifts.
38
+ """
39
+ ...
40
+
41
+
42
+ # Arrays do not compare with ==, so identity equality.
43
+ @dataclass(frozen=True, slots=True, eq=False)
44
+ class Reference:
45
+ """The part of a confirmed frame a classifier keeps."""
46
+
47
+ backend_id: str
48
+ vector: Vector
49
+
50
+ def to_bytes(self) -> bytes:
51
+ """Serialize for a cache next to the original image."""
52
+ buffer = BytesIO()
53
+ np.savez(
54
+ buffer,
55
+ format=np.array(_FORMAT),
56
+ backend_id=np.array(self.backend_id),
57
+ vector=self.vector,
58
+ )
59
+ return buffer.getvalue()
60
+
61
+ @classmethod
62
+ def from_bytes(cls, data: bytes) -> Reference:
63
+ """Load data written by :meth:`to_bytes`; raise FeaturesError if unusable."""
64
+ try:
65
+ with np.load(BytesIO(data), allow_pickle=False) as npz:
66
+ if int(npz["format"]) != _FORMAT:
67
+ raise FeaturesError(f"unsupported format {int(npz['format'])}")
68
+ return cls(str(npz["backend_id"]), npz["vector"].astype(np.float32))
69
+ except FeaturesError:
70
+ raise
71
+ except (EOFError, OSError, KeyError, ValueError, zipfile.BadZipFile) as err:
72
+ raise FeaturesError(f"unreadable features: {err}") from err
73
+
74
+
75
+ @dataclass(frozen=True, slots=True, eq=False)
76
+ class Features:
77
+ """Features of one image region."""
78
+
79
+ backend_id: str
80
+ vector: Vector
81
+ query: Vector
82
+
83
+ def reference(self) -> Reference:
84
+ """Return what a classifier keeps when this frame is confirmed."""
85
+ return Reference(self.backend_id, self.vector)
86
+
87
+
88
+ def extract_features(
89
+ backend: FeatureBackend, image: Image.Image, roi: Roi = FULL_FRAME
90
+ ) -> Features:
91
+ """Crop ``image`` to ``roi`` and extract its features."""
92
+ vector, query = backend.extract(roi.crop(image))
93
+ return Features(backend.id, vector, query)
94
+
95
+
96
+ def unit(array: npt.NDArray[np.floating]) -> Vector:
97
+ """Return ``array`` flattened, zero-mean and scaled to unit length."""
98
+ flat = array.astype(np.float32).ravel()
99
+ flat = flat - flat.mean()
100
+ norm = float(np.linalg.norm(flat))
101
+ return flat / norm if norm > 0 else flat
tarsius/image.py ADDED
@@ -0,0 +1,33 @@
1
+ """Image decoding."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from io import BytesIO
6
+
7
+ from PIL import Image, UnidentifiedImageError
8
+
9
+ from .errors import ImageError
10
+
11
+
12
+ def load_image(data: bytes, *, draft_side: int = 1024) -> Image.Image:
13
+ """
14
+ Decode an encoded image to RGB.
15
+
16
+ JPEGs are decoded at the smallest scale whose longer side is still at
17
+ least ``draft_side``, since full 4K decoding costs more than the feature
18
+ extraction itself. Other formats are decoded at full size.
19
+ """
20
+ if draft_side < 1:
21
+ raise ValueError("draft_side must be positive")
22
+ try:
23
+ image = Image.open(BytesIO(data))
24
+ width, height = image.size
25
+ scale = draft_side / max(width, height)
26
+ if scale < 1:
27
+ # draft keeps both sides at or above the request.
28
+ image.draft(
29
+ "RGB", (max(1, int(width * scale)), max(1, int(height * scale)))
30
+ )
31
+ return image.convert("RGB")
32
+ except (UnidentifiedImageError, OSError) as err:
33
+ raise ImageError(f"cannot decode image: {err}") from err
@@ -0,0 +1,20 @@
1
+ BSD LICENSE.
2
+
3
+ Redistribution and use in source and binary forms, with or without modification, are permitted
4
+ provided that the following conditions are met:
5
+
6
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions
7
+ and the following disclaimer.
8
+
9
+ 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
10
+ and the following disclaimer in the documentation and/or other materials provided with the
11
+ distribution.
12
+
13
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
14
+ IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
15
+ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
16
+ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
17
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
18
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
19
+ IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
20
+ THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Binary file
@@ -0,0 +1,50 @@
1
+ 7767517
2
+ 48 56
3
+ Input data 0 1 data -23330=5,3,227,227,1,3 0=227 1=227 2=3
4
+ Convolution conv1 1 1 data conv1_relu_conv1 -23330=5,3,113,113,1,64 0=64 1=3 3=2 5=1 6=1728 9=1
5
+ Pooling pool1 1 1 conv1_relu_conv1 pool1 -23330=5,3,56,56,1,64 1=3 2=2
6
+ Convolution fire2/squeeze1x1 1 1 pool1 fire2/squeeze1x1_fire2/relu_squeeze1x1 -23330=5,3,56,56,1,16 0=16 1=1 5=1 6=1024 9=1
7
+ Split splitncnn_0 1 2 fire2/squeeze1x1_fire2/relu_squeeze1x1 fire2/squeeze1x1_fire2/relu_squeeze1x1_splitncnn_0 fire2/squeeze1x1_fire2/relu_squeeze1x1_splitncnn_1 -23330=10,3,56,56,1,16,3,56,56,1,16
8
+ Convolution fire2/expand1x1 1 1 fire2/squeeze1x1_fire2/relu_squeeze1x1_splitncnn_1 fire2/expand1x1_fire2/relu_expand1x1 -23330=5,3,56,56,1,64 0=64 1=1 5=1 6=1024 9=1
9
+ Convolution fire2/expand3x3 1 1 fire2/squeeze1x1_fire2/relu_squeeze1x1_splitncnn_0 fire2/expand3x3_fire2/relu_expand3x3 -23330=5,3,56,56,1,64 0=64 1=3 4=1 5=1 6=9216 9=1
10
+ Concat fire2/concat 2 1 fire2/expand1x1_fire2/relu_expand1x1 fire2/expand3x3_fire2/relu_expand3x3 fire2/concat -23330=5,3,56,56,1,128
11
+ Convolution fire3/squeeze1x1 1 1 fire2/concat fire3/squeeze1x1_fire3/relu_squeeze1x1 -23330=5,3,56,56,1,16 0=16 1=1 5=1 6=2048 9=1
12
+ Split splitncnn_1 1 2 fire3/squeeze1x1_fire3/relu_squeeze1x1 fire3/squeeze1x1_fire3/relu_squeeze1x1_splitncnn_0 fire3/squeeze1x1_fire3/relu_squeeze1x1_splitncnn_1 -23330=10,3,56,56,1,16,3,56,56,1,16
13
+ Convolution fire3/expand1x1 1 1 fire3/squeeze1x1_fire3/relu_squeeze1x1_splitncnn_1 fire3/expand1x1_fire3/relu_expand1x1 -23330=5,3,56,56,1,64 0=64 1=1 5=1 6=1024 9=1
14
+ Convolution fire3/expand3x3 1 1 fire3/squeeze1x1_fire3/relu_squeeze1x1_splitncnn_0 fire3/expand3x3_fire3/relu_expand3x3 -23330=5,3,56,56,1,64 0=64 1=3 4=1 5=1 6=9216 9=1
15
+ Concat fire3/concat 2 1 fire3/expand1x1_fire3/relu_expand1x1 fire3/expand3x3_fire3/relu_expand3x3 fire3/concat -23330=5,3,56,56,1,128
16
+ Pooling pool3 1 1 fire3/concat pool3 -23330=5,3,28,28,1,128 1=3 2=2
17
+ Convolution fire4/squeeze1x1 1 1 pool3 fire4/squeeze1x1_fire4/relu_squeeze1x1 -23330=5,3,28,28,1,32 0=32 1=1 5=1 6=4096 9=1
18
+ Split splitncnn_2 1 2 fire4/squeeze1x1_fire4/relu_squeeze1x1 fire4/squeeze1x1_fire4/relu_squeeze1x1_splitncnn_0 fire4/squeeze1x1_fire4/relu_squeeze1x1_splitncnn_1 -23330=10,3,28,28,1,32,3,28,28,1,32
19
+ Convolution fire4/expand1x1 1 1 fire4/squeeze1x1_fire4/relu_squeeze1x1_splitncnn_1 fire4/expand1x1_fire4/relu_expand1x1 -23330=5,3,28,28,1,128 0=128 1=1 5=1 6=4096 9=1
20
+ Convolution fire4/expand3x3 1 1 fire4/squeeze1x1_fire4/relu_squeeze1x1_splitncnn_0 fire4/expand3x3_fire4/relu_expand3x3 -23330=5,3,28,28,1,128 0=128 1=3 4=1 5=1 6=36864 9=1
21
+ Concat fire4/concat 2 1 fire4/expand1x1_fire4/relu_expand1x1 fire4/expand3x3_fire4/relu_expand3x3 fire4/concat -23330=5,3,28,28,1,256
22
+ Convolution fire5/squeeze1x1 1 1 fire4/concat fire5/squeeze1x1_fire5/relu_squeeze1x1 -23330=5,3,28,28,1,32 0=32 1=1 5=1 6=8192 9=1
23
+ Split splitncnn_3 1 2 fire5/squeeze1x1_fire5/relu_squeeze1x1 fire5/squeeze1x1_fire5/relu_squeeze1x1_splitncnn_0 fire5/squeeze1x1_fire5/relu_squeeze1x1_splitncnn_1 -23330=10,3,28,28,1,32,3,28,28,1,32
24
+ Convolution fire5/expand1x1 1 1 fire5/squeeze1x1_fire5/relu_squeeze1x1_splitncnn_1 fire5/expand1x1_fire5/relu_expand1x1 -23330=5,3,28,28,1,128 0=128 1=1 5=1 6=4096 9=1
25
+ Convolution fire5/expand3x3 1 1 fire5/squeeze1x1_fire5/relu_squeeze1x1_splitncnn_0 fire5/expand3x3_fire5/relu_expand3x3 -23330=5,3,28,28,1,128 0=128 1=3 4=1 5=1 6=36864 9=1
26
+ Concat fire5/concat 2 1 fire5/expand1x1_fire5/relu_expand1x1 fire5/expand3x3_fire5/relu_expand3x3 fire5/concat -23330=5,3,28,28,1,256
27
+ Pooling pool5 1 1 fire5/concat pool5 -23330=5,3,14,14,1,256 1=3 2=2
28
+ Convolution fire6/squeeze1x1 1 1 pool5 fire6/squeeze1x1_fire6/relu_squeeze1x1 -23330=5,3,14,14,1,48 0=48 1=1 5=1 6=12288 9=1
29
+ Split splitncnn_4 1 2 fire6/squeeze1x1_fire6/relu_squeeze1x1 fire6/squeeze1x1_fire6/relu_squeeze1x1_splitncnn_0 fire6/squeeze1x1_fire6/relu_squeeze1x1_splitncnn_1 -23330=10,3,14,14,1,48,3,14,14,1,48
30
+ Convolution fire6/expand1x1 1 1 fire6/squeeze1x1_fire6/relu_squeeze1x1_splitncnn_1 fire6/expand1x1_fire6/relu_expand1x1 -23330=5,3,14,14,1,192 0=192 1=1 5=1 6=9216 9=1
31
+ Convolution fire6/expand3x3 1 1 fire6/squeeze1x1_fire6/relu_squeeze1x1_splitncnn_0 fire6/expand3x3_fire6/relu_expand3x3 -23330=5,3,14,14,1,192 0=192 1=3 4=1 5=1 6=82944 9=1
32
+ Concat fire6/concat 2 1 fire6/expand1x1_fire6/relu_expand1x1 fire6/expand3x3_fire6/relu_expand3x3 fire6/concat -23330=5,3,14,14,1,384
33
+ Convolution fire7/squeeze1x1 1 1 fire6/concat fire7/squeeze1x1_fire7/relu_squeeze1x1 -23330=5,3,14,14,1,48 0=48 1=1 5=1 6=18432 9=1
34
+ Split splitncnn_5 1 2 fire7/squeeze1x1_fire7/relu_squeeze1x1 fire7/squeeze1x1_fire7/relu_squeeze1x1_splitncnn_0 fire7/squeeze1x1_fire7/relu_squeeze1x1_splitncnn_1 -23330=10,3,14,14,1,48,3,14,14,1,48
35
+ Convolution fire7/expand1x1 1 1 fire7/squeeze1x1_fire7/relu_squeeze1x1_splitncnn_1 fire7/expand1x1_fire7/relu_expand1x1 -23330=5,3,14,14,1,192 0=192 1=1 5=1 6=9216 9=1
36
+ Convolution fire7/expand3x3 1 1 fire7/squeeze1x1_fire7/relu_squeeze1x1_splitncnn_0 fire7/expand3x3_fire7/relu_expand3x3 -23330=5,3,14,14,1,192 0=192 1=3 4=1 5=1 6=82944 9=1
37
+ Concat fire7/concat 2 1 fire7/expand1x1_fire7/relu_expand1x1 fire7/expand3x3_fire7/relu_expand3x3 fire7/concat -23330=5,3,14,14,1,384
38
+ Convolution fire8/squeeze1x1 1 1 fire7/concat fire8/squeeze1x1_fire8/relu_squeeze1x1 -23330=5,3,14,14,1,64 0=64 1=1 5=1 6=24576 9=1
39
+ Split splitncnn_6 1 2 fire8/squeeze1x1_fire8/relu_squeeze1x1 fire8/squeeze1x1_fire8/relu_squeeze1x1_splitncnn_0 fire8/squeeze1x1_fire8/relu_squeeze1x1_splitncnn_1 -23330=10,3,14,14,1,64,3,14,14,1,64
40
+ Convolution fire8/expand1x1 1 1 fire8/squeeze1x1_fire8/relu_squeeze1x1_splitncnn_1 fire8/expand1x1_fire8/relu_expand1x1 -23330=5,3,14,14,1,256 0=256 1=1 5=1 6=16384 9=1
41
+ Convolution fire8/expand3x3 1 1 fire8/squeeze1x1_fire8/relu_squeeze1x1_splitncnn_0 fire8/expand3x3_fire8/relu_expand3x3 -23330=5,3,14,14,1,256 0=256 1=3 4=1 5=1 6=147456 9=1
42
+ Concat fire8/concat 2 1 fire8/expand1x1_fire8/relu_expand1x1 fire8/expand3x3_fire8/relu_expand3x3 fire8/concat -23330=5,3,14,14,1,512
43
+ Convolution fire9/squeeze1x1 1 1 fire8/concat fire9/squeeze1x1_fire9/relu_squeeze1x1 -23330=5,3,14,14,1,64 0=64 1=1 5=1 6=32768 9=1
44
+ Split splitncnn_7 1 2 fire9/squeeze1x1_fire9/relu_squeeze1x1 fire9/squeeze1x1_fire9/relu_squeeze1x1_splitncnn_0 fire9/squeeze1x1_fire9/relu_squeeze1x1_splitncnn_1 -23330=10,3,14,14,1,64,3,14,14,1,64
45
+ Convolution fire9/expand1x1 1 1 fire9/squeeze1x1_fire9/relu_squeeze1x1_splitncnn_1 fire9/expand1x1_fire9/relu_expand1x1 -23330=5,3,14,14,1,256 0=256 1=1 5=1 6=16384 9=1
46
+ Convolution fire9/expand3x3 1 1 fire9/squeeze1x1_fire9/relu_squeeze1x1_splitncnn_0 fire9/expand3x3_fire9/relu_expand3x3 -23330=5,3,14,14,1,256 0=256 1=3 4=1 5=1 6=147456 9=1
47
+ Concat fire9/concat 2 1 fire9/expand1x1_fire9/relu_expand1x1 fire9/expand3x3_fire9/relu_expand3x3 fire9/concat_drop9 -23330=5,3,14,14,1,512
48
+ Convolution conv10 1 1 fire9/concat_drop9 conv10_relu_conv10 -23330=5,3,14,14,1,1000 0=1000 1=1 5=1 6=512000 9=1
49
+ Pooling pool10 1 1 conv10_relu_conv10 pool10 -23330=5,1,1000,1,1,1 0=1 4=1
50
+ Softmax prob 1 1 pool10 prob -23330=5,1,1000,1,1,1
tarsius/py.typed ADDED
File without changes
tarsius/roi.py ADDED
@@ -0,0 +1,59 @@
1
+ """Region of interest inside a camera image."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterable
6
+ from dataclasses import astuple, dataclass
7
+
8
+ from PIL import Image
9
+
10
+
11
+ @dataclass(frozen=True, slots=True)
12
+ class Roi:
13
+ """Rectangle as fractions of the image size, so it survives resolution changes."""
14
+
15
+ left: float = 0.0
16
+ top: float = 0.0
17
+ right: float = 1.0
18
+ bottom: float = 1.0
19
+
20
+ def __post_init__(self) -> None:
21
+ """Reject empty or out-of-frame rectangles."""
22
+ if not (0.0 <= self.left < self.right <= 1.0):
23
+ raise ValueError(f"invalid horizontal range {self.left}..{self.right}")
24
+ if not (0.0 <= self.top < self.bottom <= 1.0):
25
+ raise ValueError(f"invalid vertical range {self.top}..{self.bottom}")
26
+
27
+ @classmethod
28
+ def from_cells(
29
+ cls, cells: Iterable[tuple[int, int]], *, columns: int, rows: int
30
+ ) -> Roi:
31
+ """Return the bounding box of grid cells given as ``(column, row)``."""
32
+ picked = list(cells)
33
+ if not picked:
34
+ raise ValueError("no cells selected")
35
+ for column, row in picked:
36
+ if not (0 <= column < columns and 0 <= row < rows):
37
+ raise ValueError(f"cell {column},{row} outside a {columns}x{rows} grid")
38
+ return cls(
39
+ min(column for column, _ in picked) / columns,
40
+ min(row for _, row in picked) / rows,
41
+ (max(column for column, _ in picked) + 1) / columns,
42
+ (max(row for _, row in picked) + 1) / rows,
43
+ )
44
+
45
+ def as_tuple(self) -> tuple[float, float, float, float]:
46
+ """Return ``(left, top, right, bottom)``, e.g. for config storage."""
47
+ return astuple(self)
48
+
49
+ def crop(self, image: Image.Image) -> Image.Image:
50
+ """Return the region of ``image``, at least one pixel in each direction."""
51
+ width, height = image.size
52
+ left = min(round(self.left * width), width - 1)
53
+ top = min(round(self.top * height), height - 1)
54
+ right = max(round(self.right * width), left + 1)
55
+ bottom = max(round(self.bottom * height), top + 1)
56
+ return image.crop((left, top, right, bottom))
57
+
58
+
59
+ FULL_FRAME = Roi()
tarsius/vote.py ADDED
@@ -0,0 +1,27 @@
1
+ """Combine several frames into one decision."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import Counter
6
+ from collections.abc import Sequence
7
+
8
+ from .classifier import Result
9
+
10
+
11
+ def majority(results: Sequence[Result], *, min_share: float = 0.5) -> str | None:
12
+ """
13
+ Return the state picked by more than ``min_share`` of all frames.
14
+
15
+ Unsure and not-ready frames count against every state, so a burst of
16
+ unsure frames keeps the decision open instead of letting one confident
17
+ frame win. ``min_share`` of at least 0.5 makes the winner unique.
18
+ """
19
+ if not 0.5 <= min_share < 1:
20
+ raise ValueError("min_share must be in [0.5, 1)")
21
+ if not results:
22
+ return None
23
+ votes = Counter(result.state for result in results if result.state is not None)
24
+ if not votes:
25
+ return None
26
+ state, count = votes.most_common(1)[0]
27
+ return state if count / len(results) > min_share else None
@@ -0,0 +1,106 @@
1
+ Metadata-Version: 2.5
2
+ Name: tarsius
3
+ Version: 0.1.0
4
+ Summary: Local, training-free state detection for a region of a camera image
5
+ Project-URL: Repository, https://github.com/RaHehl/tarsius
6
+ Project-URL: Bug Tracker, https://github.com/RaHehl/tarsius/issues
7
+ Project-URL: Changelog, https://github.com/RaHehl/tarsius/releases
8
+ Author: Raphael Hehl
9
+ License-Expression: Apache-2.0 AND BSD-2-Clause
10
+ License-File: LICENSE
11
+ License-File: NOTICE
12
+ License-File: src/tarsius/models/LICENSE.squeezenet
13
+ Keywords: camera,computer-vision,home-assistant,ncnn,presence
14
+ Classifier: Development Status :: 2 - Pre-Alpha
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Topic :: Scientific/Engineering :: Image Recognition
20
+ Classifier: Topic :: Software Development :: Libraries
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.14
23
+ Requires-Dist: numpy>=2.0
24
+ Requires-Dist: pillow>=11.0
25
+ Provides-Extra: ncnn
26
+ Requires-Dist: ncnn>=1.0.20260526; extra == 'ncnn'
27
+ Description-Content-Type: text/markdown
28
+
29
+ # tarsius
30
+
31
+ <p align="center">
32
+ <a href="https://github.com/RaHehl/tarsius/actions/workflows/ci.yml?query=branch%3Amain"><img src="https://github.com/RaHehl/tarsius/actions/workflows/ci.yml/badge.svg?branch=main" alt="CI"></a>
33
+ <a href="https://codecov.io/gh/RaHehl/tarsius"><img src="https://codecov.io/gh/RaHehl/tarsius/graph/badge.svg" alt="Coverage"></a>
34
+ <a href="https://pypi.org/project/tarsius/"><img src="https://img.shields.io/pypi/v/tarsius" alt="PyPI"></a>
35
+ <a href="https://pypi.org/project/tarsius/"><img src="https://img.shields.io/pypi/pyversions/tarsius" alt="Python"></a>
36
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-Apache--2.0-blue" alt="License"></a>
37
+ </p>
38
+ <p align="center">
39
+ <a href="https://github.com/astral-sh/uv"><img src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/uv/main/assets/badge/v0.json" alt="uv"></a>
40
+ <a href="https://github.com/astral-sh/ruff"><img src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json" alt="Ruff"></a>
41
+ <a href="https://github.com/j178/prek"><img src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/j178/prek/master/docs/assets/badge-v0.json" alt="prek"></a>
42
+ </p>
43
+
44
+ Local, training-free state detection for a region of a camera image: is the car in the garage, is the mailbox flag up, is the gate open.
45
+
46
+ You confirm a few frames per state, tarsius compares new frames against them and answers with a state or "unsure". Nothing leaves the machine and nothing gets trained.
47
+
48
+ ```python
49
+ from tarsius import Classifier, NcnnBackend, Roi, extract_features, load_image
50
+
51
+ backend = NcnnBackend()
52
+ spot = Roi(0.10, 0.10, 0.60, 0.50)
53
+ classifier = Classifier.for_backend(backend)
54
+ car = extract_features(backend, load_image(car_jpeg), spot)
55
+ empty = extract_features(backend, load_image(empty_jpeg), spot)
56
+ classifier.add("ref-1", car, state="occupied")
57
+ classifier.add("ref-2", empty, state="free")
58
+
59
+ result = classifier.classify(extract_features(backend, load_image(new_jpeg), spot))
60
+ result.status # Status.CONFIDENT, Status.UNSURE or Status.NOT_READY
61
+ result.state # "occupied" or "free" when confident
62
+ result.candidate # best guess, also when unsure
63
+ ```
64
+
65
+ Store `features.reference().to_bytes()` next to each confirmed frame and restore it with `Reference.from_bytes()`. On `FeaturesError`, extract again from the stored frame.
66
+
67
+ ## Backends
68
+
69
+ - `NcnnBackend`: SqueezeNet 1.1 ImageNet features on [ncnn](https://github.com/Tencent/ncnn), install with `tarsius[ncnn]`. Tolerates clutter and lighting changes, a rough region is enough.
70
+ - `EdgeBackend`: numpy only, a baseline. Needs a tight region that still shows some static structure when the object is gone.
71
+
72
+ `NcnnBackend` is the intended default. It stays an optional extra until ncnn ships a release that no longer requires `opencv-python`, which has no musllinux wheels. Without that, tarsius cannot install on Alpine (musl) systems such as Home Assistant OS, whose Core container is Alpine based. ncnn master already made opencv optional ([Tencent/ncnn@0ca5a4b](https://github.com/Tencent/ncnn/commit/0ca5a4b6d)), so the next ncnn release should unblock it.
73
+
74
+ ## Results so far
75
+
76
+ One household, two garage cameras, 24 days of recorded history, day and IR night.
77
+ References come from older frames, the test is the newest week.
78
+ The table is the harder camera: a dark car and clutter that gets moved around in front of it (459 frames, 164 in the test week).
79
+ The other camera scores 100 % with both backends.
80
+
81
+ | Backend | Region | 2 confirmed segments per state | 5 per state |
82
+ |---|---|---|---|
83
+ | ncnn | tight | 0 % wrong, 0 % unsure | 0 % wrong, 0 % unsure |
84
+ | ncnn | wide, with clutter | 0 % wrong, 0 % unsure | 0 % wrong, 0 % unsure |
85
+ | edges | tight | 1.8 % wrong, 3.5 % unsure | 0 % wrong, 1.8 % unsure |
86
+ | edges | wide, with clutter | 27 % wrong, 7.6 % unsure | 20 % wrong, 8.5 % unsure |
87
+
88
+ About 20 ms per 4 MP frame including JPEG decoding, for either backend, on an x86 desktop with one thread.
89
+ A small sample, not a guarantee. `scripts/history_split.py` runs the same evaluation on your own recordings.
90
+
91
+ ## Development
92
+
93
+ ```sh
94
+ scripts/build_model.sh # once, builds the ncnn model into src/tarsius/models
95
+ uv sync --extra ncnn
96
+ uv run pytest
97
+ uvx prek run --all-files
98
+ ```
99
+
100
+ The ncnn model is not stored in git. `scripts/build_model.sh` converts the original SqueezeNet 1.1 release with the ncnn tools. Inputs and outputs are checked against pinned sha256 sums, so CI and a local run produce the same files. It needs x86_64 Linux with `curl`, `unzip`, `libgomp1` and `libprotobuf32t64` (Ubuntu 24.04).
101
+
102
+ Releases: every PR gets a label, Release Drafter collects them into a draft, publishing the GitHub release builds and uploads to PyPI.
103
+
104
+ ## License
105
+
106
+ Apache-2.0. The bundled SqueezeNet model is BSD-2-Clause, see NOTICE.
@@ -0,0 +1,20 @@
1
+ tarsius/__init__.py,sha256=FGS7mfLH-C9Q04uAye2lSUOBrmWfqvPE9rmdC8OO4rI,915
2
+ tarsius/classifier.py,sha256=d9mDZ_SOLuXkZcHCIad3z_tFyYGZO9qrHWalzz2-mOo,6409
3
+ tarsius/errors.py,sha256=1VLJa1zl7wgLjuyXbrq1LG0zF2EtR_GsqTckCVl9M90,618
4
+ tarsius/features.py,sha256=SDC3RSXaC-QS-fl7JfwNQUxqYpkisq5VKOdeetNCtJc,3224
5
+ tarsius/image.py,sha256=hPj6GLT6LJc775vVHqDCGebVf25tjX8SI3achhZTQ30,1072
6
+ tarsius/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ tarsius/roi.py,sha256=v6ZX7_Byvu9Eb0YhgcpqX_VJmYnGCxH1ZR6-G4nN41o,2187
8
+ tarsius/vote.py,sha256=MrjKVlvBUz8IqDdd6k43B7dU9wvYJbqWRirFOYruofk,934
9
+ tarsius/backends/__init__.py,sha256=UrpCqWYPwhcD422uFmq11Bxw-X1uX5x1pIn8HOJi6kc,24
10
+ tarsius/backends/edges.py,sha256=bHHd1ZEa_kcJ-r1nf0aoqANDXSy0JB1kkEJNhE8xVvk,1698
11
+ tarsius/backends/ncnn.py,sha256=4zOTl8yTBklatbM1zB2bvb3FGw666zDr8DmLGbq9tNc,3112
12
+ tarsius/models/LICENSE.squeezenet,sha256=kA4XbjG3IKi7Py2xznNfSaLCjtzO4LsfvtKzUMMYtdA,1250
13
+ tarsius/models/squeezenet_v1.1.bin,sha256=upJbC7ya6uo0uqKlgFaZDakrpAYlAgm84DgvXGbicls,2478984
14
+ tarsius/models/squeezenet_v1.1.param,sha256=ylWFUgqxKBpE-ifrBumFGj3-iCsheXjWza3d1YNWR3w,8336
15
+ tarsius-0.1.0.dist-info/METADATA,sha256=lFq1K8erf28uZBh-ydnJCIJ86vj13M5kAyilUq5T0ac,5997
16
+ tarsius-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
17
+ tarsius-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
18
+ tarsius-0.1.0.dist-info/licenses/NOTICE,sha256=lxrGjKZXPCPfUiINzVR3cWK-1ibZnulgoMRCLSRk0S0,332
19
+ tarsius-0.1.0.dist-info/licenses/src/tarsius/models/LICENSE.squeezenet,sha256=kA4XbjG3IKi7Py2xznNfSaLCjtzO4LsfvtKzUMMYtdA,1250
20
+ tarsius-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,8 @@
1
+ tarsius
2
+ Copyright 2026 Raphael Hehl
3
+
4
+ This product bundles the SqueezeNet v1.1 model
5
+ (https://github.com/forresti/SqueezeNet), converted to ncnn with fp16
6
+ weights. BSD-2-Clause, see tarsius/models/LICENSE.squeezenet.
7
+ SqueezeNet by Forrest N. Iandola, Song Han, Matthew W. Moskewicz,
8
+ Khalid Ashraf, William J. Dally and Kurt Keutzer.
@@ -0,0 +1,20 @@
1
+ BSD LICENSE.
2
+
3
+ Redistribution and use in source and binary forms, with or without modification, are permitted
4
+ provided that the following conditions are met:
5
+
6
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions
7
+ and the following disclaimer.
8
+
9
+ 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
10
+ and the following disclaimer in the documentation and/or other materials provided with the
11
+ distribution.
12
+
13
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
14
+ IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
15
+ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
16
+ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
17
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
18
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
19
+ IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
20
+ THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.