visionai-sdk-python 2.0.0__py3-none-any.whl → 2.1.1__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.
@@ -38,7 +38,7 @@ class _BaseClient:
38
38
  vlm_url: Base URL for the VLM inference service.
39
39
  allowed_issuers: Optional list of allowed JWT issuers. If provided, tokens
40
40
  whose ``iss`` claim is not in this list will be rejected. If omitted,
41
- issuer validation is skipped.
41
+ the issuers are derived from ``auth_url``.
42
42
  verify_ssl: Whether to verify TLS certificates.
43
43
  timeout: Default request timeout in seconds.
44
44
  max_connections: Maximum number of concurrent connections in the pool.
@@ -1,49 +1,36 @@
1
- # Maps known VisionAI server base URLs to their trusted JWT issuers.
2
- # Keys are normalized (no trailing slash).
3
- # Values are exact issuer strings as they appear in the JWT `iss` claim.
1
+ # Resolves the trusted JWT issuers for a VisionAI server base URL.
4
2
  #
5
- # Long-term: replace this static table with dynamic discovery from the server's
3
+ # Every deployment hosts its own Keycloak behind the site's public base URL, so
4
+ # the realm issuer is derived from `auth_url` rather than kept in a table. Only
5
+ # sites that additionally accept tokens from an external IdP need an entry here.
6
+ #
7
+ # Long-term: replace this with dynamic discovery from the server's
6
8
  # trusted-issuers endpoint (e.g. GET {auth_url}/api/v1/auth/trusted-issuers).
7
9
 
8
10
  _KEYCLOAK_REALM_PATH = "/keycloak/realms/linker-platform"
9
11
 
10
- # On-premise deployments backed by Keycloak (realm: linker-platform).
11
- # Issuer = base_url + _KEYCLOAK_REALM_PATH for all entries.
12
- _KEYCLOAK_BASE_URLS: list[str] = [
13
- "https://offline.visionai.linkervision.com",
14
- "https://lighthouse.visionai.linkervision.ai",
15
- "https://lighthouse-production.visionai.linkervision.ai",
16
- ]
17
-
18
- # Cloud deployments backed by Auth0 (one tenant per environment).
19
- _AUTH0_URL_TO_ISSUERS: dict[str, list[str]] = {
12
+ # Sites whose tokens may still come from an external IdP, in addition to their
13
+ # own Keycloak realm. Production has not cut over yet; listing both issuers lets
14
+ # an installed SDK keep working across the migration without an upgrade.
15
+ #
16
+ # Drop the entry once production is confirmed migrated — a retired Auth0 tenant
17
+ # name can be re-registered by someone else, so it should not stay trusted
18
+ # indefinitely.
19
+ _EXTERNAL_IDP_ISSUERS: dict[str, list[str]] = {
20
20
  "https://visionai.linkervision.com": [
21
21
  "https://data-engine-prod.us.auth0.com",
22
22
  ],
23
- "https://staging.visionai.linkervision.com": [
24
- "https://data-engine-staging.jp.auth0.com",
25
- ],
26
- "https://dev2.visionai.linkervision.com": [
27
- "https://data-engine-dev2.jp.auth0.com",
28
- ],
29
- "https://dev.visionai.linkervision.com": [
30
- "https://dev-045acunea5v1mm3l.us.auth0.com",
31
- ],
32
- }
33
-
34
- _AUTH_URL_TO_ISSUERS: dict[str, list[str]] = {
35
- **{url: [f"{url}{_KEYCLOAK_REALM_PATH}"] for url in _KEYCLOAK_BASE_URLS},
36
- **_AUTH0_URL_TO_ISSUERS,
37
23
  }
38
24
 
39
25
 
40
26
  def resolve_allowed_issuers(auth_url: str) -> list[str]:
41
27
  """Return the trusted issuers for the given auth_url.
42
28
 
43
- If the URL is in the known table, return its configured issuers.
44
- Otherwise, assume a Keycloak deployment and derive the issuer from auth_url.
29
+ Always includes the site's own Keycloak realm issuer, plus any external IdP
30
+ issuer the site still accepts.
45
31
  """
46
32
  normalized = auth_url.rstrip("/")
47
- if known := _AUTH_URL_TO_ISSUERS.get(normalized):
48
- return known
49
- return [f"{normalized}{_KEYCLOAK_REALM_PATH}"]
33
+ return [
34
+ f"{normalized}{_KEYCLOAK_REALM_PATH}",
35
+ *_EXTERNAL_IDP_ISSUERS.get(normalized, []),
36
+ ]
@@ -2,12 +2,24 @@
2
2
 
3
3
  from .async_resource import AsyncVLMResource
4
4
  from .models import NIMRequestModel, ResponseErrorModel, ResponseNormalModel
5
+ from .preprocess import (
6
+ DEFAULT_RESIZE_SPEC,
7
+ Interpolation,
8
+ ResizeMode,
9
+ ResizePlan,
10
+ compute_resize,
11
+ )
5
12
  from .resource import VLMResource
6
13
 
7
14
  __all__ = [
15
+ "DEFAULT_RESIZE_SPEC",
8
16
  "AsyncVLMResource",
9
- "VLMResource",
17
+ "Interpolation",
10
18
  "NIMRequestModel",
11
- "ResponseNormalModel",
19
+ "ResizeMode",
20
+ "ResizePlan",
12
21
  "ResponseErrorModel",
22
+ "ResponseNormalModel",
23
+ "VLMResource",
24
+ "compute_resize",
13
25
  ]
@@ -0,0 +1,186 @@
1
+ """Image-resize planning helpers for VLM inference.
2
+
3
+ This module only computes target dimensions (pure math, no image
4
+ dependencies). The mode (``name``), ``factor``, and ``interpolation`` come
5
+ from the model server's resize spec; ``pixels`` comes from the UI resize
6
+ option. The actual resize is done by the caller with whatever imaging
7
+ library its pipeline already uses, applying ``plan.interpolation``:
8
+
9
+ plan = compute_resize(
10
+ width=w, height=h, name="smart_resize", factor=32, pixels=768,
11
+ interpolation="bicubic",
12
+ )
13
+
14
+ # PIL client
15
+ PIL_INTERPOLATION = {
16
+ "bicubic": Image.Resampling.BICUBIC,
17
+ "lanczos": Image.Resampling.LANCZOS,
18
+ }
19
+ out = img.resize((plan.width, plan.height), PIL_INTERPOLATION[plan.interpolation])
20
+
21
+ # OpenCV client
22
+ CV2_INTERPOLATION = {
23
+ "bicubic": cv2.INTER_CUBIC,
24
+ "lanczos": cv2.INTER_LANCZOS4,
25
+ }
26
+ out = cv2.resize(
27
+ arr, (plan.width, plan.height), interpolation=CV2_INTERPOLATION[plan.interpolation]
28
+ )
29
+ """
30
+
31
+ import math
32
+ from collections.abc import Mapping
33
+ from types import MappingProxyType
34
+ from typing import Any, Literal, NamedTuple, get_args
35
+
36
+ _MAX_ASPECT_RATIO = 200
37
+
38
+ ResizeMode = Literal["smart_resize", "square_resize"]
39
+ Interpolation = Literal["bicubic", "lanczos"]
40
+
41
+ # Fallback resize spec for when the model server does not provide one.
42
+ # Read-only; splat it into compute_resize alongside the UI pixels value:
43
+ # compute_resize(width=w, height=h, pixels=768, **DEFAULT_RESIZE_SPEC)
44
+ DEFAULT_RESIZE_SPEC: Mapping[str, Any] = MappingProxyType(
45
+ {"name": "smart_resize", "factor": 32, "interpolation": "bicubic"}
46
+ )
47
+
48
+
49
+ class ResizePlan(NamedTuple):
50
+ """Target dimensions and interpolation method for a client-side resize."""
51
+
52
+ width: int
53
+ height: int
54
+ interpolation: Interpolation
55
+
56
+
57
+ def _smart_resize(
58
+ height: int,
59
+ width: int,
60
+ factor: int,
61
+ min_pixels: int,
62
+ max_pixels: int,
63
+ ) -> tuple[int, int]:
64
+ """Compute target (height, width) — note height-first, unlike ResizePlan.
65
+
66
+ 1. Both dimensions are divisible by ``factor``.
67
+ 2. The total number of pixels is within [``min_pixels``, ``max_pixels``].
68
+ 3. The aspect ratio is maintained as closely as possible.
69
+
70
+ Raises ValueError when the aspect ratio exceeds 200 or the constraints
71
+ cannot all be satisfied. Argument validation is compute_resize's job.
72
+ """
73
+ if max(height, width) / min(height, width) > _MAX_ASPECT_RATIO:
74
+ raise ValueError(
75
+ "absolute aspect ratio must be smaller than "
76
+ f"{_MAX_ASPECT_RATIO}, got {max(height, width) / min(height, width)}"
77
+ )
78
+ h_bar = max(factor, round(height / factor) * factor)
79
+ w_bar = max(factor, round(width / factor) * factor)
80
+ if h_bar * w_bar > max_pixels:
81
+ beta = math.sqrt((height * width) / max_pixels)
82
+ h_bar = max(factor, math.floor(height / beta / factor) * factor)
83
+ w_bar = max(factor, math.floor(width / beta / factor) * factor)
84
+ elif h_bar * w_bar < min_pixels:
85
+ beta = math.sqrt(min_pixels / (height * width))
86
+ h_bar = math.ceil(height * beta / factor) * factor
87
+ w_bar = math.ceil(width * beta / factor) * factor
88
+ if not min_pixels <= h_bar * w_bar <= max_pixels:
89
+ raise ValueError(
90
+ f"cannot satisfy min_pixels={min_pixels}, max_pixels={max_pixels} for a "
91
+ f"{width}x{height} image with factor={factor}"
92
+ )
93
+ return h_bar, w_bar
94
+
95
+
96
+ def compute_resize(
97
+ *,
98
+ width: int,
99
+ height: int,
100
+ name: ResizeMode,
101
+ pixels: int,
102
+ interpolation: Interpolation,
103
+ factor: int | None = None,
104
+ min_pixels: int | None = None,
105
+ ) -> ResizePlan:
106
+ """Plan a VLM-input resize from the model server's resize spec.
107
+
108
+ All arguments are keyword-only — a transposed width/height cannot happen
109
+ silently. ``name``, ``factor``, and ``interpolation`` mirror the model
110
+ server's resize spec fields; ``pixels`` is the UI resize option value.
111
+
112
+ - ``name="smart_resize"`` — dimensions divisible by ``factor``, total
113
+ pixel count within [``min_pixels``, ``pixels * pixels``], aspect ratio
114
+ kept. ``factor`` is required (the model's patch size, e.g. 32 or 48);
115
+ ``min_pixels`` defaults to ``4 * factor * factor``.
116
+ - ``name="square_resize"`` — exact ``pixels`` x ``pixels``; aspect ratio
117
+ not preserved. ``factor`` has no meaning and is ignored, so a whole
118
+ server resize spec can be forwarded as-is.
119
+
120
+ Args:
121
+ width: Source image width in pixels.
122
+ height: Source image height in pixels.
123
+ name: Resize mode from the model server: "smart_resize" or
124
+ "square_resize".
125
+ pixels: UI pixel option — one number, but its meaning depends on
126
+ ``name``:
127
+
128
+ - ``"smart_resize"``: an area budget, not a side length. The
129
+ output area is capped at ``pixels * pixels`` while keeping the
130
+ source aspect ratio, so neither output side is generally equal
131
+ to ``pixels`` — e.g. ``pixels=768`` on a 1920x1080 frame gives
132
+ 1024x576 (= 589,824 px, the same area as 768x768).
133
+ - ``"square_resize"``: the exact side length. The output is
134
+ always ``pixels`` x ``pixels`` — e.g. ``pixels=384`` gives
135
+ 384x384 regardless of the source shape.
136
+ interpolation: Interpolation the caller should resize with,
137
+ from the model server: "bicubic" or "lanczos". Passed through
138
+ into the returned plan.
139
+ factor: Smart resize only: round dimensions to multiples of this.
140
+ min_pixels: Smart resize only: lower bound on output pixel count.
141
+
142
+ Returns:
143
+ ResizePlan(width, height, interpolation) — note width-first,
144
+ matching the (width, height) order PIL and OpenCV resize calls expect.
145
+
146
+ Raises:
147
+ ValueError: If height/width are not positive, ``pixels`` or ``factor``
148
+ is not a positive integer, ``name`` or ``interpolation`` is not a
149
+ supported value, ``factor`` is missing (smart), ``min_pixels`` is
150
+ given for square resize or exceeds the pixel budget, or the
151
+ constraints cannot be satisfied (extreme aspect ratio).
152
+ """
153
+ if height <= 0 or width <= 0:
154
+ raise ValueError(f"height and width must be positive, got {width}x{height}")
155
+ if name not in get_args(ResizeMode):
156
+ raise ValueError(f"name must be one of {get_args(ResizeMode)}, got {name!r}")
157
+ if interpolation not in get_args(Interpolation):
158
+ raise ValueError(
159
+ f"interpolation must be one of {get_args(Interpolation)}, "
160
+ f"got {interpolation!r}"
161
+ )
162
+ if isinstance(pixels, bool) or not isinstance(pixels, int) or pixels <= 0:
163
+ raise ValueError(f"pixels must be a positive integer, got {pixels!r}")
164
+
165
+ if name == "smart_resize":
166
+ if factor is None:
167
+ raise ValueError("smart_resize requires factor")
168
+ if isinstance(factor, bool) or not isinstance(factor, int) or factor <= 0:
169
+ raise ValueError(f"factor must be a positive integer, got {factor!r}")
170
+ max_pixels = pixels * pixels
171
+ if min_pixels is None:
172
+ min_pixels = 4 * factor * factor
173
+ if min_pixels <= 0 or min_pixels > max_pixels:
174
+ raise ValueError(
175
+ f"min_pixels must be in (0, pixels * pixels], got "
176
+ f"min_pixels={min_pixels}, pixels={pixels}"
177
+ )
178
+ h_bar, w_bar = _smart_resize(height, width, factor, min_pixels, max_pixels)
179
+ else:
180
+ # factor is part of the server resize spec, so a caller forwarding the
181
+ # whole spec may pass it; it has no meaning here, so ignore it.
182
+ if min_pixels is not None:
183
+ raise ValueError("min_pixels only applies to smart_resize")
184
+ w_bar = h_bar = pixels
185
+
186
+ return ResizePlan(width=w_bar, height=h_bar, interpolation=interpolation)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: visionai-sdk-python
3
- Version: 2.0.0
3
+ Version: 2.1.1
4
4
  Summary: VisionAI SDK for Python
5
5
  Author-email: Tony Yang <tonyyang@linkervision.com>
6
6
  Requires-Python: >=3.11
@@ -27,6 +27,7 @@ Python client library for VisionAI authentication and Vision Language Model (VLM
27
27
  - **Auto Token Management**: Automatic token refresh before expiration
28
28
  - **JWT Validation**: Built-in token signature and expiration verification
29
29
  - **VLM Inference**: Submit and poll vision-language model tasks
30
+ - **Resize Planning**: Compute VLM input dimensions (smart / square resize) without any image dependency — the caller does the actual resize
30
31
  - **Async Support**: Full async/await support with `AsyncClient`
31
32
  - **Type Safe**: Full type hints with Pydantic validation
32
33
  - **Service Source Attribution**: Auto-attach a service-source header to every outbound `requests`/`httpx`/`aiohttp` call with a single startup call
@@ -187,6 +188,43 @@ elif result.status in ("failed", "timeout"):
187
188
  - `failed`: Error, check `error`
188
189
  - `timeout`: Request timeout
189
190
 
191
+ ### Resize Planning
192
+
193
+ Compute the target dimensions for a VLM input image. Pure math, no image
194
+ dependencies — resize with whatever library your service already uses,
195
+ applying `plan.interpolation`. `name`, `factor`, and `interpolation` come
196
+ from the model server's resize spec; `pixels` is the UI resize option:
197
+
198
+ ```python
199
+ from visionai_sdk_python.vlm import compute_resize
200
+
201
+ plan = compute_resize(
202
+ width=1920, height=1080, name="smart_resize", factor=32, pixels=768,
203
+ interpolation="bicubic",
204
+ )
205
+ # ResizePlan(width=1024, height=576, interpolation='bicubic')
206
+ # smart_resize: dimensions divisible by factor, area capped at pixels * pixels
207
+
208
+ compute_resize(width=w, height=h, name="square_resize", pixels=384, interpolation="lanczos")
209
+ # square_resize: exact pixels x pixels; factor is ignored, so a whole resize
210
+ # spec can be forwarded as-is
211
+
212
+ # No resize spec from the model server? Fall back to the default
213
+ # (smart_resize, factor 32, bicubic):
214
+ from visionai_sdk_python.vlm import DEFAULT_RESIZE_SPEC
215
+ plan = compute_resize(width=w, height=h, pixels=768, **DEFAULT_RESIZE_SPEC)
216
+
217
+ # Apply with your own imaging library (PIL shown; see module docstring for cv2)
218
+ interpolation = {"bicubic": Image.Resampling.BICUBIC,
219
+ "lanczos": Image.Resampling.LANCZOS}[plan.interpolation]
220
+ img = img.resize((plan.width, plan.height), interpolation)
221
+ ```
222
+
223
+ Invalid input (non-positive dimensions, a non-integer or non-positive
224
+ `pixels`/`factor`, unknown `name` or `interpolation`, missing `factor` for
225
+ smart resize, `min_pixels` on a square resize or over the pixel budget, an
226
+ unsatisfiable budget) raises `ValueError`.
227
+
190
228
  ## Token Validation
191
229
 
192
230
  ```python
@@ -212,6 +250,25 @@ client = Client(
212
250
  )
213
251
  ```
214
252
 
253
+ ### Token issuers
254
+
255
+ `allowed_issuers` is optional. When you leave it out, the SDK derives the
256
+ trusted issuers from `auth_url` and accepts a token whose `iss` claim either:
257
+
258
+ - equals `{auth_url}/keycloak/realms/linker-platform`, the realm every
259
+ deployment hosts behind its own base URL; or
260
+ - equals an external issuer the site is known to still accept — today only
261
+ production, which takes its Auth0 tenant alongside Keycloak while it migrates.
262
+
263
+ That means `auth_url` has to be the site's **public base URL** — the same host
264
+ that appears in the token's `iss` claim. Pointing it at an in-cluster or proxied
265
+ address (for example a backend service URL) derives issuers that no token will
266
+ ever carry, and verification fails with `jwt.InvalidIssuerError`. Pass
267
+ `allowed_issuers` explicitly if you need to talk to a site through such an
268
+ address.
269
+
270
+ Passing `allowed_issuers` yourself replaces both rules with an exact-match list.
271
+
215
272
  ## Error Handling
216
273
 
217
274
  ```python
@@ -1,11 +1,11 @@
1
1
  visionai_sdk_python/__init__.py,sha256=y2RFANz0iHxxrATkwIv9cDRkuICybgfMpTbjVX79lRw,569
2
- visionai_sdk_python/_base.py,sha256=6MoFyrOr4I3TkoXkBuZIlnih0xHB4QNuOWGug0vh2Ho,8117
2
+ visionai_sdk_python/_base.py,sha256=VC4EGUqUzTkrN63ByKL_kPOckXjRfFNXWVXByGZhVfM,8130
3
3
  visionai_sdk_python/_jwt_verifier.py,sha256=h4CAK1iiDAJ-oKnXrLbCJw5rWcsVe94QNY12ne1Wzto,8442
4
4
  visionai_sdk_python/_request_attribution.py,sha256=zQk_bSLsu1RTp1Fe3MGUUX8YRzq3iqfBTmhhjM7BuRU,1907
5
5
  visionai_sdk_python/_source_header.py,sha256=DWiR-TGclET4UrqmAEO7bYPtf9XuLSE4FGQjZIgVWiY,5133
6
6
  visionai_sdk_python/async_client.py,sha256=u133WD2wqaUSNz-Rq3DgHDBQuPmArHgJtoiIpke5O-M,3876
7
7
  visionai_sdk_python/client.py,sha256=7hvlq0evaPLolm1hDXS44EaaZR7OUIkEpOrUCbGaz2Y,3736
8
- visionai_sdk_python/constants.py,sha256=hDLdISOkrrEifLumVy0gPLO2NmUDxdfe2UIueizpbh8,1868
8
+ visionai_sdk_python/constants.py,sha256=KWhoxZdlwqXwhUJDqERStq2mrms-MA8aRDqBwbIvNO0,1471
9
9
  visionai_sdk_python/endpoints.py,sha256=CC-AoxXzg39sMAhqx1CTS3gRWKx_H7VOqBANRLVotoU,183
10
10
  visionai_sdk_python/exceptions.py,sha256=r4bxvsQGNTVa7-ISX1JAC7VRJ-6qs3n30l3j3qxai-Y,1047
11
11
  visionai_sdk_python/instrumentation.py,sha256=tTTL5Op0fZULpmoOKW8dw8-2ReOQUEpMvHrf-R5C_yg,24512
@@ -15,12 +15,13 @@ visionai_sdk_python/auth/_mixin.py,sha256=qxn9wQxOtigcvbFGSmjv7Fu7-HCsIJVs1oqf-w
15
15
  visionai_sdk_python/auth/async_resource.py,sha256=Yz9l0MtoihNREZwx0rkImCGn_sRkx2WdPkRCZ1YKi38,4457
16
16
  visionai_sdk_python/auth/models.py,sha256=Ke0eWJwU4d1M4W5WS9EbWTQRrvnYyxccrMg3XbgbDdA,435
17
17
  visionai_sdk_python/auth/resource.py,sha256=F4d1cZ88GZrXUrgHD_sduSEJzZiO9ZPVX7m1wTeaSp0,4368
18
- visionai_sdk_python/vlm/__init__.py,sha256=f0G0zigVm5mn05fWvmvV6fR7UIbil2aSXhHRYwpgIVs,341
18
+ visionai_sdk_python/vlm/__init__.py,sha256=EDd7ZG4k7inn8qqkyIhO3xI_4MPMWJT5Npsient-tTc,571
19
19
  visionai_sdk_python/vlm/_mixin.py,sha256=TkqezNpW8QEe9pujsvx1APcylYQYr_PvHruEz4Le3JQ,1718
20
20
  visionai_sdk_python/vlm/async_resource.py,sha256=pOuHpzsbw6NawGQHROcLzs_ezKg78DI1RZHA5W1ko_s,3695
21
21
  visionai_sdk_python/vlm/models.py,sha256=yDFjo4LfAxqXYBnl6ZW7YUJQoKKRkQWtqBJi2ruI6Jw,984
22
+ visionai_sdk_python/vlm/preprocess.py,sha256=ZpJJa13h8_YKwh_P7Pn8WIXV0x-r2xJi-ETgCFsGw-Y,7892
22
23
  visionai_sdk_python/vlm/resource.py,sha256=VaNybrunD_8eNDbAAJwaxkUrbR4amGATM4CGvQsX7Qk,3608
23
- visionai_sdk_python-2.0.0.dist-info/METADATA,sha256=jBJEmXCRk132qsKCSg0HmY9pFU8A2tgiflJZuNiE7fU,25936
24
- visionai_sdk_python-2.0.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
25
- visionai_sdk_python-2.0.0.dist-info/top_level.txt,sha256=79a5MCSLLv6Mbfun-8RS-G6O927hahBwDqJjeuWLdvM,20
26
- visionai_sdk_python-2.0.0.dist-info/RECORD,,
24
+ visionai_sdk_python-2.1.1.dist-info/METADATA,sha256=Y2oQtkae1coZFW8Ltl9NVikIKIImK01nJPh6R5bRvdc,28624
25
+ visionai_sdk_python-2.1.1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
26
+ visionai_sdk_python-2.1.1.dist-info/top_level.txt,sha256=79a5MCSLLv6Mbfun-8RS-G6O927hahBwDqJjeuWLdvM,20
27
+ visionai_sdk_python-2.1.1.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (83.0.0)
2
+ Generator: setuptools (84.0.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5