argus-puppet 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.
@@ -0,0 +1,16 @@
1
+ """argus-puppet — Body pose for the Argus suite: whole-body keypoints, pose embeddings, diversity and coverage metrics, and ControlNet pose conditioning (:8220)"""
2
+
3
+ from __future__ import annotations
4
+
5
+ try:
6
+ # Written by hatch-vcs at build time (see pyproject [tool.hatch.build.hooks.vcs]).
7
+ from argus_puppet._version import __version__
8
+ except ImportError: # running from a source checkout that hasn't been built
9
+ from importlib.metadata import PackageNotFoundError, version
10
+
11
+ try:
12
+ __version__ = version("argus-puppet")
13
+ except PackageNotFoundError:
14
+ __version__ = "0.0.0+unknown"
15
+
16
+ __all__ = ["__version__"]
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '0.1.0'
22
+ __version_tuple__ = version_tuple = (0, 1, 0)
23
+
24
+ __commit_id__ = commit_id = None
argus_puppet/age.py ADDED
@@ -0,0 +1,150 @@
1
+ """The suite's age fail-safe for real-person input: argus-curator's MiVOLO estimates over HTTP.
2
+
3
+ The pose library may be built from real photos, and the suite keeps any frame where a face or a body reads under 18
4
+ out of it (background people included). The estimate comes from curator's ``POST /faces?body=true`` (InsightFace
5
+ faces plus a body pass, MiVOLO ages for both), the same service argus-darkroom's age check calls.
6
+
7
+ * :class:`AgeEstimator` is the protocol: :meth:`~AgeEstimator.min_age` gives the lowest estimate over every face and
8
+ body in one image, ``None`` when there is nobody to estimate, and raises :class:`AgeUnavailable` when the check
9
+ cannot vouch for the image (service down, an error answer, a face or body without an estimate, a body pass that
10
+ did not run). Callers **fail closed**: an image that raised, or read ``None``, is excluded.
11
+ * :class:`HttpAgeEstimator` posts the image bytes to the URL in the settings (``ARGUS_PUPPET_AGE_URL``, never a URL a
12
+ caller supplied), through :func:`argus_cortex.net.fetch` with that one host allowed, a per-read timeout and an
13
+ overall deadline, and no redirects for the POST. Nothing is written.
14
+
15
+ An estimate is a tool's reading of an image, never a stated age. Nothing is sent anywhere unless a caller asks for
16
+ the check and a URL is configured.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import math
23
+ from typing import Protocol
24
+ from urllib.parse import urlsplit
25
+
26
+ import structlog
27
+
28
+ log = structlog.get_logger(__name__)
29
+
30
+ __all__ = ["ADULT_AGE", "AgeEstimator", "AgeUnavailable", "HttpAgeEstimator", "min_age_from_payload"]
31
+
32
+ # Any face or body read under this keeps the frame out.
33
+ ADULT_AGE = 18.0
34
+ # Per-read timeout and whole-call deadline of one check (curator queues for its GPU lease).
35
+ TIMEOUT_S = 30.0
36
+ DEADLINE_S = 60.0
37
+ # Curator's answer is a short JSON document; anything larger is not one.
38
+ MAX_REPLY_BYTES = 1024 * 1024
39
+ _PEOPLE_CHECK_FAILED = frozenset({"detection_failed", "body_ages_failed"})
40
+
41
+
42
+ class AgeUnavailable(RuntimeError):
43
+ """The age check cannot vouch for this image (callers exclude it)."""
44
+
45
+
46
+ class AgeEstimator(Protocol):
47
+ def min_age(self, data: bytes) -> float | None:
48
+ """The lowest age estimate over every face and body in the image, in years; ``None`` when there is no face
49
+ or body to estimate. Raises :class:`AgeUnavailable`."""
50
+ ...
51
+
52
+
53
+ def _years(value: object) -> float | None:
54
+ """An estimate, or ``None``. A bool, NaN, infinity or a negative number is no estimate (NaN < 18 is False, so
55
+ accepting one would let the rule silently not fire)."""
56
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
57
+ return None
58
+ try:
59
+ years = float(value)
60
+ except OverflowError:
61
+ return None
62
+ return years if math.isfinite(years) and years >= 0 else None
63
+
64
+
65
+ def min_age_from_payload(payload: object) -> float | None:
66
+ """The lowest estimate in curator's ``POST /faces?body=true`` answer; ``None`` when it found nobody.
67
+
68
+ Raises :class:`AgeUnavailable` for anything that cannot vouch for the image: no ``faces`` list, a source other
69
+ than MiVOLO, a body pass that did not report ``people_check: ok`` (without it an empty ``people`` list is not
70
+ "nobody found"), a face without an estimate, or a body not matched to a face without one. A body matched to a
71
+ face (an int index into ``faces``) may lack its own estimate (the face's counts); when it has one, it counts too.
72
+ A body without one whose ``face_index`` is not a valid index fails closed."""
73
+ if not isinstance(payload, dict) or not isinstance(payload.get("faces"), list):
74
+ raise AgeUnavailable("the age check returned no faces list")
75
+ if payload.get("source", "mivolo") != "mivolo":
76
+ raise AgeUnavailable(f"the age check's source was {payload.get('source')!r}, not mivolo")
77
+ check = payload.get("people_check")
78
+ if check in _PEOPLE_CHECK_FAILED:
79
+ raise AgeUnavailable(f"the body check failed ({check}): {payload.get('people_error') or ''}".rstrip(": "))
80
+ if check != "ok":
81
+ raise AgeUnavailable(f"the body check did not run (people_check {check!r})")
82
+ people = payload.get("people")
83
+ if not isinstance(people, list):
84
+ raise AgeUnavailable("the age check returned no people list")
85
+ ages: list[float] = []
86
+ for face in payload["faces"]:
87
+ years = _years(face.get("age_estimate_years")) if isinstance(face, dict) else None
88
+ if years is None:
89
+ raise AgeUnavailable("the age check returned a face without an estimate")
90
+ ages.append(years)
91
+ for person in people:
92
+ if not isinstance(person, dict):
93
+ raise AgeUnavailable("the age check returned a malformed person")
94
+ years = _years(person.get("age_estimate_years"))
95
+ if years is None:
96
+ index = person.get("face_index")
97
+ if index is None:
98
+ raise AgeUnavailable("the age check returned a person without an estimate")
99
+ # bool is an int: True would pass for face 1. Out of range would vouch with another face's age.
100
+ if isinstance(index, bool) or not isinstance(index, int) or not 0 <= index < len(payload["faces"]):
101
+ raise AgeUnavailable(f"the age check matched a person to face {index!r}, which it did not return")
102
+ continue # matched to a face, whose estimate is already counted
103
+ ages.append(years)
104
+ return min(ages) if ages else None
105
+
106
+
107
+ class HttpAgeEstimator:
108
+ """MiVOLO estimates from argus-curator's ``POST /faces?body=true`` at *base_url* (from settings only)."""
109
+
110
+ def __init__(self, base_url: str, *, timeout: float = TIMEOUT_S, deadline: float = DEADLINE_S) -> None:
111
+ parts = urlsplit(base_url.strip())
112
+ if parts.scheme not in ("http", "https") or not parts.hostname:
113
+ raise ValueError(f"ARGUS_PUPPET_AGE_URL must be an http(s) URL, not {base_url!r}")
114
+ self.url = base_url.strip().rstrip("/") + "/faces?body=true"
115
+ # The configured service is usually on loopback or the LAN: allow exactly its host (still resolved and
116
+ # pinned by argus_cortex.net); every other host stays under the public-address rule.
117
+ port = parts.port or (443 if parts.scheme == "https" else 80)
118
+ host = f"[{parts.hostname}]" if ":" in parts.hostname else parts.hostname
119
+ self._allow = (f"{host}:{port}",)
120
+ self.timeout = timeout
121
+ self.deadline = deadline
122
+
123
+ def min_age(self, data: bytes) -> float | None:
124
+ try:
125
+ from argus_cortex.net import FetchFailed, UrlRefused, fetch
126
+ except ImportError as exc: # pragma: no cover - httpx comes with the cli and server extras
127
+ raise AgeUnavailable(f"the age check needs httpx (argus-cortex[remote]): {exc}") from exc
128
+ try:
129
+ reply = fetch(
130
+ self.url,
131
+ method="POST",
132
+ content=data,
133
+ headers={"Content-Type": "application/octet-stream"},
134
+ allow_hosts=self._allow,
135
+ timeout=self.timeout,
136
+ deadline=self.deadline,
137
+ max_bytes=MAX_REPLY_BYTES,
138
+ max_redirects=0,
139
+ ).raise_for_status()
140
+ except FetchFailed as exc:
141
+ raise AgeUnavailable(f"the age check answered HTTP {exc.status}") from exc
142
+ except (UrlRefused, OSError) as exc:
143
+ raise AgeUnavailable(f"the age check could not be reached: {exc}") from exc
144
+ if 300 <= reply.status < 400:
145
+ raise AgeUnavailable(f"the age check answered a redirect (HTTP {reply.status}); it is not followed")
146
+ try:
147
+ payload = json.loads(reply.body)
148
+ except ValueError as exc:
149
+ raise AgeUnavailable("the age check's answer is not JSON") from exc
150
+ return min_age_from_payload(payload)