viewrium 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.
- viewrium/__init__.py +94 -0
- viewrium/_client.py +320 -0
- viewrium/_errors.py +57 -0
- viewrium/_object.py +45 -0
- viewrium/resources/__init__.py +22 -0
- viewrium/resources/api_key.py +66 -0
- viewrium/resources/model.py +476 -0
- viewrium/resources/tag.py +28 -0
- viewrium/resources/usage.py +50 -0
- viewrium-0.1.0.dist-info/METADATA +164 -0
- viewrium-0.1.0.dist-info/RECORD +12 -0
- viewrium-0.1.0.dist-info/WHEEL +4 -0
viewrium/__init__.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Official Python SDK for the Viewrium API.
|
|
2
|
+
|
|
3
|
+
Quickstart::
|
|
4
|
+
|
|
5
|
+
import viewrium
|
|
6
|
+
|
|
7
|
+
viewrium.api_key = "sk_live_..."
|
|
8
|
+
|
|
9
|
+
model = viewrium.Model.create(
|
|
10
|
+
custom_id="sku-1",
|
|
11
|
+
images=["https://example.com/img1.jpg"],
|
|
12
|
+
height=90,
|
|
13
|
+
tags=["chair"],
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
Async variant::
|
|
17
|
+
|
|
18
|
+
import asyncio
|
|
19
|
+
import viewrium
|
|
20
|
+
|
|
21
|
+
viewrium.api_key = "sk_live_..."
|
|
22
|
+
|
|
23
|
+
async def main():
|
|
24
|
+
return await viewrium.AsyncModel.create(
|
|
25
|
+
custom_id="sku-1",
|
|
26
|
+
images=["https://example.com/img1.jpg"],
|
|
27
|
+
height=90,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
asyncio.run(main())
|
|
31
|
+
|
|
32
|
+
Configuration (all optional; env vars are used when module vars are unset):
|
|
33
|
+
|
|
34
|
+
- ``viewrium.api_key`` env ``VIEWRIUM_API_KEY`` (required at call time)
|
|
35
|
+
- ``viewrium.api_base`` env ``VIEWRIUM_API_BASE`` default ``https://api.viewrium.com``
|
|
36
|
+
- ``viewrium.timeout`` request timeout in seconds (default 60)
|
|
37
|
+
- ``viewrium.max_retries`` retries on 429 / 5xx (default 3, respects Retry-After)
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
from __future__ import annotations
|
|
41
|
+
|
|
42
|
+
__version__ = "0.1.0"
|
|
43
|
+
|
|
44
|
+
# Module-level configuration. Read on each request; env vars used as fallbacks.
|
|
45
|
+
api_key: str | None = None
|
|
46
|
+
api_base: str | None = None
|
|
47
|
+
timeout: float | None = None
|
|
48
|
+
max_retries: int | None = None
|
|
49
|
+
|
|
50
|
+
from ._client import aclose, close # noqa: E402
|
|
51
|
+
from ._errors import ( # noqa: E402
|
|
52
|
+
APIError,
|
|
53
|
+
AuthError,
|
|
54
|
+
NotFoundError,
|
|
55
|
+
RateLimitError,
|
|
56
|
+
ValidationError,
|
|
57
|
+
ViewriumError,
|
|
58
|
+
)
|
|
59
|
+
from ._object import ViewriumObject # noqa: E402
|
|
60
|
+
from .resources import ( # noqa: E402
|
|
61
|
+
ApiKey,
|
|
62
|
+
AsyncApiKey,
|
|
63
|
+
AsyncModel,
|
|
64
|
+
AsyncTag,
|
|
65
|
+
AsyncUsage,
|
|
66
|
+
Model,
|
|
67
|
+
Tag,
|
|
68
|
+
Usage,
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
__all__ = [
|
|
72
|
+
"__version__",
|
|
73
|
+
"api_key",
|
|
74
|
+
"api_base",
|
|
75
|
+
"timeout",
|
|
76
|
+
"max_retries",
|
|
77
|
+
"Model",
|
|
78
|
+
"AsyncModel",
|
|
79
|
+
"ApiKey",
|
|
80
|
+
"AsyncApiKey",
|
|
81
|
+
"Usage",
|
|
82
|
+
"AsyncUsage",
|
|
83
|
+
"Tag",
|
|
84
|
+
"AsyncTag",
|
|
85
|
+
"ViewriumObject",
|
|
86
|
+
"ViewriumError",
|
|
87
|
+
"AuthError",
|
|
88
|
+
"RateLimitError",
|
|
89
|
+
"ValidationError",
|
|
90
|
+
"NotFoundError",
|
|
91
|
+
"APIError",
|
|
92
|
+
"close",
|
|
93
|
+
"aclose",
|
|
94
|
+
]
|
viewrium/_client.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
"""HTTP transport for the Viewrium SDK.
|
|
2
|
+
|
|
3
|
+
Exposes `request_sync` and `request_async` that both:
|
|
4
|
+
|
|
5
|
+
- Read `api_key` + `api_base` + `timeout` + `max_retries` from module config
|
|
6
|
+
(`viewrium.api_key`) falling back to env vars (`VIEWRIUM_API_KEY`,
|
|
7
|
+
`VIEWRIUM_API_BASE`).
|
|
8
|
+
- Retry on 429 and 5xx up to `max_retries`, honoring `Retry-After`.
|
|
9
|
+
- Map non-2xx responses to typed `ViewriumError` subclasses.
|
|
10
|
+
- Return parsed JSON as a `ViewriumObject`.
|
|
11
|
+
|
|
12
|
+
Sync and async are kept as separate, lazy `httpx.Client` / `httpx.AsyncClient`
|
|
13
|
+
singletons. The async singleton is invalidated if the running event loop
|
|
14
|
+
changes (so `asyncio.run()` twice in the same process stays healthy).
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import asyncio
|
|
20
|
+
import os
|
|
21
|
+
import random
|
|
22
|
+
import time
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
import httpx
|
|
26
|
+
|
|
27
|
+
from ._errors import (
|
|
28
|
+
APIError,
|
|
29
|
+
AuthError,
|
|
30
|
+
NotFoundError,
|
|
31
|
+
RateLimitError,
|
|
32
|
+
ValidationError,
|
|
33
|
+
ViewriumError,
|
|
34
|
+
)
|
|
35
|
+
from ._object import ViewriumObject
|
|
36
|
+
|
|
37
|
+
DEFAULT_API_BASE = "https://api.viewrium.com"
|
|
38
|
+
DEFAULT_TIMEOUT = 60.0
|
|
39
|
+
DEFAULT_MAX_RETRIES = 3
|
|
40
|
+
_RETRYABLE_STATUSES = {429, 500, 502, 503, 504}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
# ---------------------------------------------------------------------------
|
|
44
|
+
# Config resolution: module var > env var > default
|
|
45
|
+
# ---------------------------------------------------------------------------
|
|
46
|
+
def _resolve_api_key() -> str:
|
|
47
|
+
import viewrium
|
|
48
|
+
|
|
49
|
+
key = getattr(viewrium, "api_key", None) or os.environ.get("VIEWRIUM_API_KEY")
|
|
50
|
+
if not key:
|
|
51
|
+
raise AuthError(
|
|
52
|
+
"No API key configured. Set `viewrium.api_key = 'sk_live_...'` "
|
|
53
|
+
"or export VIEWRIUM_API_KEY."
|
|
54
|
+
)
|
|
55
|
+
return key
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _resolve_api_base() -> str:
|
|
59
|
+
import viewrium
|
|
60
|
+
|
|
61
|
+
base = (
|
|
62
|
+
getattr(viewrium, "api_base", None)
|
|
63
|
+
or os.environ.get("VIEWRIUM_API_BASE")
|
|
64
|
+
or DEFAULT_API_BASE
|
|
65
|
+
)
|
|
66
|
+
return base.rstrip("/")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _resolve_timeout() -> float:
|
|
70
|
+
import viewrium
|
|
71
|
+
|
|
72
|
+
return float(getattr(viewrium, "timeout", DEFAULT_TIMEOUT) or DEFAULT_TIMEOUT)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _resolve_max_retries() -> int:
|
|
76
|
+
import viewrium
|
|
77
|
+
|
|
78
|
+
value = getattr(viewrium, "max_retries", DEFAULT_MAX_RETRIES)
|
|
79
|
+
return DEFAULT_MAX_RETRIES if value is None else int(value)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _build_headers(extra: dict[str, str] | None = None) -> dict[str, str]:
|
|
83
|
+
from . import __version__
|
|
84
|
+
|
|
85
|
+
headers = {
|
|
86
|
+
"Authorization": f"Bearer {_resolve_api_key()}",
|
|
87
|
+
"User-Agent": f"viewrium-python/{__version__}",
|
|
88
|
+
"Accept": "application/json",
|
|
89
|
+
}
|
|
90
|
+
if extra:
|
|
91
|
+
headers.update(extra)
|
|
92
|
+
return headers
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _full_url(path: str) -> str:
|
|
96
|
+
if path.startswith("http://") or path.startswith("https://"):
|
|
97
|
+
return path
|
|
98
|
+
return f"{_resolve_api_base()}{path if path.startswith('/') else '/' + path}"
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
# ---------------------------------------------------------------------------
|
|
102
|
+
# Response -> ViewriumObject / error mapping
|
|
103
|
+
# ---------------------------------------------------------------------------
|
|
104
|
+
def _extract_detail(response: httpx.Response) -> str:
|
|
105
|
+
try:
|
|
106
|
+
body = response.json()
|
|
107
|
+
except Exception:
|
|
108
|
+
return response.text or f"HTTP {response.status_code}"
|
|
109
|
+
if isinstance(body, dict):
|
|
110
|
+
detail = body.get("detail") or body.get("error") or body.get("message")
|
|
111
|
+
if detail:
|
|
112
|
+
return str(detail)
|
|
113
|
+
return str(body)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _parse_retry_after(response: httpx.Response) -> float | None:
|
|
117
|
+
raw = response.headers.get("Retry-After")
|
|
118
|
+
if not raw:
|
|
119
|
+
return None
|
|
120
|
+
try:
|
|
121
|
+
return float(raw)
|
|
122
|
+
except ValueError:
|
|
123
|
+
return None
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _raise_for_status(response: httpx.Response) -> None:
|
|
127
|
+
status = response.status_code
|
|
128
|
+
if 200 <= status < 300:
|
|
129
|
+
return
|
|
130
|
+
detail = _extract_detail(response)
|
|
131
|
+
body = None
|
|
132
|
+
try:
|
|
133
|
+
body = response.json()
|
|
134
|
+
except Exception:
|
|
135
|
+
pass
|
|
136
|
+
if status == 401:
|
|
137
|
+
raise AuthError(detail, status_code=status, response_body=body)
|
|
138
|
+
if status == 404:
|
|
139
|
+
raise NotFoundError(detail, status_code=status, response_body=body)
|
|
140
|
+
if status in (400, 409, 422):
|
|
141
|
+
raise ValidationError(detail, status_code=status, response_body=body)
|
|
142
|
+
if status == 429:
|
|
143
|
+
raise RateLimitError(
|
|
144
|
+
detail,
|
|
145
|
+
status_code=status,
|
|
146
|
+
response_body=body,
|
|
147
|
+
retry_after=_parse_retry_after(response),
|
|
148
|
+
)
|
|
149
|
+
raise APIError(detail, status_code=status, response_body=body)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _parse_success(response: httpx.Response) -> ViewriumObject | Any:
|
|
153
|
+
if response.status_code == 204 or not response.content:
|
|
154
|
+
return ViewriumObject()
|
|
155
|
+
try:
|
|
156
|
+
payload = response.json()
|
|
157
|
+
except Exception as e:
|
|
158
|
+
raise APIError(
|
|
159
|
+
f"Failed to parse JSON response: {e}",
|
|
160
|
+
status_code=response.status_code,
|
|
161
|
+
response_body=response.text,
|
|
162
|
+
) from e
|
|
163
|
+
return ViewriumObject.construct(payload)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _backoff_wait(response: httpx.Response | None, attempt: int) -> float:
|
|
167
|
+
if response is not None:
|
|
168
|
+
hinted = _parse_retry_after(response)
|
|
169
|
+
if hinted is not None:
|
|
170
|
+
return hinted
|
|
171
|
+
base = min(2 ** attempt, 30)
|
|
172
|
+
return base + random.uniform(0, 0.25)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
# ---------------------------------------------------------------------------
|
|
176
|
+
# Lazy clients
|
|
177
|
+
# ---------------------------------------------------------------------------
|
|
178
|
+
_sync_client: httpx.Client | None = None
|
|
179
|
+
_async_state: dict[str, Any] = {"client": None, "loop": None}
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _get_sync_client() -> httpx.Client:
|
|
183
|
+
global _sync_client
|
|
184
|
+
if _sync_client is None:
|
|
185
|
+
_sync_client = httpx.Client(timeout=_resolve_timeout())
|
|
186
|
+
return _sync_client
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _get_async_client() -> httpx.AsyncClient:
|
|
190
|
+
try:
|
|
191
|
+
loop = asyncio.get_running_loop()
|
|
192
|
+
except RuntimeError:
|
|
193
|
+
loop = None
|
|
194
|
+
cached = _async_state["client"]
|
|
195
|
+
cached_loop = _async_state["loop"]
|
|
196
|
+
if cached is None or (loop is not None and cached_loop is not loop):
|
|
197
|
+
_async_state["client"] = httpx.AsyncClient(timeout=_resolve_timeout())
|
|
198
|
+
_async_state["loop"] = loop
|
|
199
|
+
return _async_state["client"]
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def close() -> None:
|
|
203
|
+
"""Close the sync client. Safe to call repeatedly.
|
|
204
|
+
|
|
205
|
+
The async client is left to GC; explicit close in an async context is
|
|
206
|
+
available via `aclose()`.
|
|
207
|
+
"""
|
|
208
|
+
global _sync_client
|
|
209
|
+
if _sync_client is not None:
|
|
210
|
+
try:
|
|
211
|
+
_sync_client.close()
|
|
212
|
+
except Exception:
|
|
213
|
+
pass
|
|
214
|
+
_sync_client = None
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
async def aclose() -> None:
|
|
218
|
+
"""Close the async client. Safe to call repeatedly."""
|
|
219
|
+
client = _async_state.get("client")
|
|
220
|
+
if client is not None:
|
|
221
|
+
try:
|
|
222
|
+
await client.aclose()
|
|
223
|
+
except Exception:
|
|
224
|
+
pass
|
|
225
|
+
_async_state["client"] = None
|
|
226
|
+
_async_state["loop"] = None
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
# ---------------------------------------------------------------------------
|
|
230
|
+
# Request entry points
|
|
231
|
+
# ---------------------------------------------------------------------------
|
|
232
|
+
def request_sync(
|
|
233
|
+
method: str,
|
|
234
|
+
path: str,
|
|
235
|
+
*,
|
|
236
|
+
json: Any = None,
|
|
237
|
+
params: dict[str, Any] | None = None,
|
|
238
|
+
data: dict[str, Any] | None = None,
|
|
239
|
+
files: Any = None,
|
|
240
|
+
timeout: float | None = None,
|
|
241
|
+
) -> ViewriumObject | Any:
|
|
242
|
+
url = _full_url(path)
|
|
243
|
+
max_retries = _resolve_max_retries()
|
|
244
|
+
attempt = 0
|
|
245
|
+
last_response: httpx.Response | None = None
|
|
246
|
+
while True:
|
|
247
|
+
try:
|
|
248
|
+
last_response = _get_sync_client().request(
|
|
249
|
+
method.upper(),
|
|
250
|
+
url,
|
|
251
|
+
headers=_build_headers(),
|
|
252
|
+
params=params,
|
|
253
|
+
json=json,
|
|
254
|
+
data=data,
|
|
255
|
+
files=files,
|
|
256
|
+
timeout=timeout if timeout is not None else _resolve_timeout(),
|
|
257
|
+
)
|
|
258
|
+
except httpx.HTTPError as e:
|
|
259
|
+
if attempt >= max_retries:
|
|
260
|
+
raise
|
|
261
|
+
time.sleep(_backoff_wait(None, attempt))
|
|
262
|
+
attempt += 1
|
|
263
|
+
continue
|
|
264
|
+
if last_response.status_code in _RETRYABLE_STATUSES and attempt < max_retries:
|
|
265
|
+
time.sleep(_backoff_wait(last_response, attempt))
|
|
266
|
+
attempt += 1
|
|
267
|
+
continue
|
|
268
|
+
break
|
|
269
|
+
_raise_for_status(last_response)
|
|
270
|
+
return _parse_success(last_response)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
async def request_async(
|
|
274
|
+
method: str,
|
|
275
|
+
path: str,
|
|
276
|
+
*,
|
|
277
|
+
json: Any = None,
|
|
278
|
+
params: dict[str, Any] | None = None,
|
|
279
|
+
data: dict[str, Any] | None = None,
|
|
280
|
+
files: Any = None,
|
|
281
|
+
timeout: float | None = None,
|
|
282
|
+
) -> ViewriumObject | Any:
|
|
283
|
+
url = _full_url(path)
|
|
284
|
+
max_retries = _resolve_max_retries()
|
|
285
|
+
attempt = 0
|
|
286
|
+
last_response: httpx.Response | None = None
|
|
287
|
+
while True:
|
|
288
|
+
try:
|
|
289
|
+
last_response = await _get_async_client().request(
|
|
290
|
+
method.upper(),
|
|
291
|
+
url,
|
|
292
|
+
headers=_build_headers(),
|
|
293
|
+
params=params,
|
|
294
|
+
json=json,
|
|
295
|
+
data=data,
|
|
296
|
+
files=files,
|
|
297
|
+
timeout=timeout if timeout is not None else _resolve_timeout(),
|
|
298
|
+
)
|
|
299
|
+
except httpx.HTTPError:
|
|
300
|
+
if attempt >= max_retries:
|
|
301
|
+
raise
|
|
302
|
+
await asyncio.sleep(_backoff_wait(None, attempt))
|
|
303
|
+
attempt += 1
|
|
304
|
+
continue
|
|
305
|
+
if last_response.status_code in _RETRYABLE_STATUSES and attempt < max_retries:
|
|
306
|
+
await asyncio.sleep(_backoff_wait(last_response, attempt))
|
|
307
|
+
attempt += 1
|
|
308
|
+
continue
|
|
309
|
+
break
|
|
310
|
+
_raise_for_status(last_response)
|
|
311
|
+
return _parse_success(last_response)
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
__all__ = [
|
|
315
|
+
"request_sync",
|
|
316
|
+
"request_async",
|
|
317
|
+
"close",
|
|
318
|
+
"aclose",
|
|
319
|
+
"ViewriumError",
|
|
320
|
+
]
|
viewrium/_errors.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Typed error hierarchy for the Viewrium SDK.
|
|
2
|
+
|
|
3
|
+
All API-originated failures inherit from `ViewriumError`. Network-level
|
|
4
|
+
failures (connection reset, DNS) bubble up as `httpx` exceptions unchanged.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ViewriumError(Exception):
|
|
11
|
+
"""Base class for all Viewrium SDK errors raised from API responses."""
|
|
12
|
+
|
|
13
|
+
def __init__(
|
|
14
|
+
self,
|
|
15
|
+
message: str,
|
|
16
|
+
*,
|
|
17
|
+
status_code: int | None = None,
|
|
18
|
+
response_body: object = None,
|
|
19
|
+
) -> None:
|
|
20
|
+
super().__init__(message)
|
|
21
|
+
self.message = message
|
|
22
|
+
self.status_code = status_code
|
|
23
|
+
self.response_body = response_body
|
|
24
|
+
|
|
25
|
+
def __repr__(self) -> str:
|
|
26
|
+
return f"{type(self).__name__}(status_code={self.status_code!r}, message={self.message!r})"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class AuthError(ViewriumError):
|
|
30
|
+
"""Raised on 401 or missing API key."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class NotFoundError(ViewriumError):
|
|
34
|
+
"""Raised on 404."""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class ValidationError(ViewriumError):
|
|
38
|
+
"""Raised on 400/409/422 (bad request / conflict / schema validation)."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class RateLimitError(ViewriumError):
|
|
42
|
+
"""Raised on 429. `retry_after` is the server-suggested wait in seconds (or None)."""
|
|
43
|
+
|
|
44
|
+
def __init__(
|
|
45
|
+
self,
|
|
46
|
+
message: str,
|
|
47
|
+
*,
|
|
48
|
+
status_code: int | None = 429,
|
|
49
|
+
response_body: object = None,
|
|
50
|
+
retry_after: float | None = None,
|
|
51
|
+
) -> None:
|
|
52
|
+
super().__init__(message, status_code=status_code, response_body=response_body)
|
|
53
|
+
self.retry_after = retry_after
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class APIError(ViewriumError):
|
|
57
|
+
"""Raised on 5xx or any non-categorised status."""
|
viewrium/_object.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Response container with dict + attribute access.
|
|
2
|
+
|
|
3
|
+
Matches the Stripe-style ergonomics: `model.id` or `model["id"]` both work.
|
|
4
|
+
Nested dicts and lists are recursively converted on construction so chained
|
|
5
|
+
access (`result.data[0].id`) is natural.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ViewriumObject(dict):
|
|
14
|
+
"""A dict subclass that also exposes keys as attributes.
|
|
15
|
+
|
|
16
|
+
Constructed via `ViewriumObject.construct(payload)` to recursively
|
|
17
|
+
convert nested dicts and lists.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
def __getattr__(self, name: str) -> Any:
|
|
21
|
+
try:
|
|
22
|
+
return self[name]
|
|
23
|
+
except KeyError:
|
|
24
|
+
raise AttributeError(name)
|
|
25
|
+
|
|
26
|
+
def __setattr__(self, name: str, value: Any) -> None:
|
|
27
|
+
self[name] = value
|
|
28
|
+
|
|
29
|
+
def __delattr__(self, name: str) -> None:
|
|
30
|
+
try:
|
|
31
|
+
del self[name]
|
|
32
|
+
except KeyError:
|
|
33
|
+
raise AttributeError(name)
|
|
34
|
+
|
|
35
|
+
def __repr__(self) -> str:
|
|
36
|
+
return f"ViewriumObject({dict.__repr__(self)})"
|
|
37
|
+
|
|
38
|
+
@classmethod
|
|
39
|
+
def construct(cls, payload: Any) -> Any:
|
|
40
|
+
"""Recursively convert dicts to ViewriumObjects, lists element-wise."""
|
|
41
|
+
if isinstance(payload, dict):
|
|
42
|
+
return cls({k: cls.construct(v) for k, v in payload.items()})
|
|
43
|
+
if isinstance(payload, list):
|
|
44
|
+
return [cls.construct(v) for v in payload]
|
|
45
|
+
return payload
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Resource classes for the Viewrium API.
|
|
2
|
+
|
|
3
|
+
Each resource ships a sync class (`Model`, `ApiKey`, `Usage`, `Tag`) and an
|
|
4
|
+
async twin (`AsyncModel`, `AsyncApiKey`, `AsyncUsage`, `AsyncTag`). Both
|
|
5
|
+
share module-level config (`viewrium.api_key`, `viewrium.api_base`).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from .api_key import ApiKey, AsyncApiKey
|
|
9
|
+
from .model import AsyncModel, Model
|
|
10
|
+
from .tag import AsyncTag, Tag
|
|
11
|
+
from .usage import AsyncUsage, Usage
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"Model",
|
|
15
|
+
"AsyncModel",
|
|
16
|
+
"ApiKey",
|
|
17
|
+
"AsyncApiKey",
|
|
18
|
+
"Usage",
|
|
19
|
+
"AsyncUsage",
|
|
20
|
+
"Tag",
|
|
21
|
+
"AsyncTag",
|
|
22
|
+
]
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""API key resource - sync + async.
|
|
2
|
+
|
|
3
|
+
Creates secret (``sk_``) or publishable (``pk_``) keys. The plaintext key is
|
|
4
|
+
returned ONCE from ``create()``; persist it securely on your side. Only the
|
|
5
|
+
hash is stored server-side. Revoke via ``delete(key_id)``. pk keys inherit
|
|
6
|
+
origin restrictions from the project's ``allowed_domains``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Literal
|
|
12
|
+
|
|
13
|
+
from .._client import request_async, request_sync
|
|
14
|
+
from .._object import ViewriumObject
|
|
15
|
+
|
|
16
|
+
_BASE = "/v1/api_keys"
|
|
17
|
+
|
|
18
|
+
ApiKeyType = Literal["secret", "publishable"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class ApiKey:
|
|
22
|
+
"""API key management. Sync."""
|
|
23
|
+
|
|
24
|
+
@classmethod
|
|
25
|
+
def create(
|
|
26
|
+
cls,
|
|
27
|
+
*,
|
|
28
|
+
name: str | None = None,
|
|
29
|
+
key_type: ApiKeyType = "secret",
|
|
30
|
+
) -> ViewriumObject:
|
|
31
|
+
body: dict = {"key_type": key_type}
|
|
32
|
+
if name is not None:
|
|
33
|
+
body["name"] = name
|
|
34
|
+
return request_sync("POST", _BASE, json=body)
|
|
35
|
+
|
|
36
|
+
@classmethod
|
|
37
|
+
def list(cls) -> ViewriumObject:
|
|
38
|
+
return request_sync("GET", _BASE)
|
|
39
|
+
|
|
40
|
+
@classmethod
|
|
41
|
+
def delete(cls, key_id: str) -> ViewriumObject:
|
|
42
|
+
return request_sync("DELETE", f"{_BASE}/{key_id}")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class AsyncApiKey:
|
|
46
|
+
"""API key management. Async."""
|
|
47
|
+
|
|
48
|
+
@classmethod
|
|
49
|
+
async def create(
|
|
50
|
+
cls,
|
|
51
|
+
*,
|
|
52
|
+
name: str | None = None,
|
|
53
|
+
key_type: ApiKeyType = "secret",
|
|
54
|
+
) -> ViewriumObject:
|
|
55
|
+
body: dict = {"key_type": key_type}
|
|
56
|
+
if name is not None:
|
|
57
|
+
body["name"] = name
|
|
58
|
+
return await request_async("POST", _BASE, json=body)
|
|
59
|
+
|
|
60
|
+
@classmethod
|
|
61
|
+
async def list(cls) -> ViewriumObject:
|
|
62
|
+
return await request_async("GET", _BASE)
|
|
63
|
+
|
|
64
|
+
@classmethod
|
|
65
|
+
async def delete(cls, key_id: str) -> ViewriumObject:
|
|
66
|
+
return await request_async("DELETE", f"{_BASE}/{key_id}")
|
|
@@ -0,0 +1,476 @@
|
|
|
1
|
+
"""Model resource (scans) - sync + async.
|
|
2
|
+
|
|
3
|
+
Mirrors the 8 `/v1/models*` endpoints:
|
|
4
|
+
|
|
5
|
+
- `create` (JSON body, image URLs or source URL)
|
|
6
|
+
- `create_from_images` (multipart, local image files)
|
|
7
|
+
- `create_from_video` (multipart, local video file)
|
|
8
|
+
- `retrieve`, `list`, `modify`, `delete`
|
|
9
|
+
- `list_events` (usage records for this model)
|
|
10
|
+
|
|
11
|
+
`height` is passed through to the backend, which normalizes to cm based on
|
|
12
|
+
`size_unit` ("cm" | "in"). Tags validated server-side; client applies no cap.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any, Iterable, Union
|
|
20
|
+
|
|
21
|
+
from .._client import request_async, request_sync
|
|
22
|
+
from .._object import ViewriumObject
|
|
23
|
+
|
|
24
|
+
ImagePath = Union[str, Path]
|
|
25
|
+
VideoPath = Union[str, Path]
|
|
26
|
+
|
|
27
|
+
_BASE = "/v1/models"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _strip_none(payload: dict[str, Any]) -> dict[str, Any]:
|
|
31
|
+
return {k: v for k, v in payload.items() if v is not None}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _build_create_body(
|
|
35
|
+
*,
|
|
36
|
+
custom_id: str | None,
|
|
37
|
+
title: str | None,
|
|
38
|
+
description: str | None,
|
|
39
|
+
images: list[str] | None,
|
|
40
|
+
source_url: str | None,
|
|
41
|
+
height: float | None,
|
|
42
|
+
size_unit: str | None,
|
|
43
|
+
tags: list[str] | None,
|
|
44
|
+
price: float | None,
|
|
45
|
+
currency: str | None,
|
|
46
|
+
metadata: dict[str, Any] | None,
|
|
47
|
+
display_enabled: bool | None,
|
|
48
|
+
) -> dict[str, Any]:
|
|
49
|
+
if bool(images) == bool(source_url):
|
|
50
|
+
raise ValueError(
|
|
51
|
+
"Provide exactly one of `images` (URL list) or `source_url` to Model.create()."
|
|
52
|
+
)
|
|
53
|
+
return _strip_none({
|
|
54
|
+
"custom_id": custom_id,
|
|
55
|
+
"title": title,
|
|
56
|
+
"description": description,
|
|
57
|
+
"image_urls": images,
|
|
58
|
+
"source_url": source_url,
|
|
59
|
+
"height": height,
|
|
60
|
+
"size_unit": size_unit,
|
|
61
|
+
"tags": tags,
|
|
62
|
+
"price": price,
|
|
63
|
+
"currency": currency,
|
|
64
|
+
"metadata": metadata,
|
|
65
|
+
"display_enabled": display_enabled,
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _list_params(
|
|
70
|
+
*,
|
|
71
|
+
tag: str | None,
|
|
72
|
+
tags: list[str] | str | None,
|
|
73
|
+
custom_id: str | None,
|
|
74
|
+
status: str | None,
|
|
75
|
+
limit: int | None,
|
|
76
|
+
offset: int | None,
|
|
77
|
+
) -> dict[str, Any]:
|
|
78
|
+
params: dict[str, Any] = {}
|
|
79
|
+
if tag is not None:
|
|
80
|
+
params["tag"] = tag
|
|
81
|
+
if tags is not None:
|
|
82
|
+
params["tags"] = tags if isinstance(tags, str) else ",".join(tags)
|
|
83
|
+
if custom_id is not None:
|
|
84
|
+
params["custom_id"] = custom_id
|
|
85
|
+
if status is not None:
|
|
86
|
+
params["status"] = status
|
|
87
|
+
if limit is not None:
|
|
88
|
+
params["limit"] = limit
|
|
89
|
+
if offset is not None:
|
|
90
|
+
params["offset"] = offset
|
|
91
|
+
return params
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _modify_body(
|
|
95
|
+
*,
|
|
96
|
+
custom_id: str | None,
|
|
97
|
+
title: str | None,
|
|
98
|
+
description: str | None,
|
|
99
|
+
price: float | None,
|
|
100
|
+
currency: str | None,
|
|
101
|
+
height: float | None,
|
|
102
|
+
size_unit: str | None,
|
|
103
|
+
tags: list[str] | None,
|
|
104
|
+
metadata: dict[str, Any] | None,
|
|
105
|
+
display_enabled: bool | None,
|
|
106
|
+
) -> dict[str, Any]:
|
|
107
|
+
return _strip_none({
|
|
108
|
+
"custom_id": custom_id,
|
|
109
|
+
"title": title,
|
|
110
|
+
"description": description,
|
|
111
|
+
"price": price,
|
|
112
|
+
"currency": currency,
|
|
113
|
+
"height": height,
|
|
114
|
+
"size_unit": size_unit,
|
|
115
|
+
"tags": tags,
|
|
116
|
+
"metadata": metadata,
|
|
117
|
+
"display_enabled": display_enabled,
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _multipart_common(
|
|
122
|
+
*,
|
|
123
|
+
title: str | None,
|
|
124
|
+
custom_id: str | None,
|
|
125
|
+
description: str | None,
|
|
126
|
+
height: float | None,
|
|
127
|
+
size_unit: str | None,
|
|
128
|
+
tags: list[str] | None,
|
|
129
|
+
display_enabled: bool | None,
|
|
130
|
+
) -> dict[str, Any]:
|
|
131
|
+
data: dict[str, Any] = {}
|
|
132
|
+
if title is not None:
|
|
133
|
+
data["title"] = title
|
|
134
|
+
if custom_id is not None:
|
|
135
|
+
data["custom_id"] = custom_id
|
|
136
|
+
if description is not None:
|
|
137
|
+
data["description"] = description
|
|
138
|
+
if height is not None:
|
|
139
|
+
data["height"] = str(height)
|
|
140
|
+
if size_unit is not None:
|
|
141
|
+
data["size_unit"] = size_unit
|
|
142
|
+
if tags is not None:
|
|
143
|
+
data["tags"] = json.dumps(tags)
|
|
144
|
+
if display_enabled is not None:
|
|
145
|
+
data["display_enabled"] = "true" if display_enabled else "false"
|
|
146
|
+
return data
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _open_image_handles(images: Iterable[ImagePath]) -> tuple[list, list]:
|
|
150
|
+
"""Open files for a multipart `images` list. Returns (files_spec, handles)."""
|
|
151
|
+
files: list = []
|
|
152
|
+
handles: list = []
|
|
153
|
+
for img in images:
|
|
154
|
+
path = Path(img)
|
|
155
|
+
fp = path.open("rb")
|
|
156
|
+
handles.append(fp)
|
|
157
|
+
files.append(("images", (path.name, fp, None)))
|
|
158
|
+
return files, handles
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _open_video_handle(video: VideoPath) -> tuple[list, list]:
|
|
162
|
+
path = Path(video)
|
|
163
|
+
fp = path.open("rb")
|
|
164
|
+
return [("video", (path.name, fp, None))], [fp]
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _close_all(handles: list) -> None:
|
|
168
|
+
for fp in handles:
|
|
169
|
+
try:
|
|
170
|
+
fp.close()
|
|
171
|
+
except Exception:
|
|
172
|
+
pass
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
# ---------------------------------------------------------------------------
|
|
176
|
+
# Sync
|
|
177
|
+
# ---------------------------------------------------------------------------
|
|
178
|
+
class Model:
|
|
179
|
+
"""3D models (backed by the `scans` table). Sync API."""
|
|
180
|
+
|
|
181
|
+
@classmethod
|
|
182
|
+
def create(
|
|
183
|
+
cls,
|
|
184
|
+
*,
|
|
185
|
+
custom_id: str | None = None,
|
|
186
|
+
title: str | None = None,
|
|
187
|
+
description: str | None = None,
|
|
188
|
+
images: list[str] | None = None,
|
|
189
|
+
source_url: str | None = None,
|
|
190
|
+
height: float | None = None,
|
|
191
|
+
size_unit: str | None = None,
|
|
192
|
+
tags: list[str] | None = None,
|
|
193
|
+
price: float | None = None,
|
|
194
|
+
currency: str | None = None,
|
|
195
|
+
metadata: dict[str, Any] | None = None,
|
|
196
|
+
display_enabled: bool | None = None,
|
|
197
|
+
) -> ViewriumObject:
|
|
198
|
+
body = _build_create_body(
|
|
199
|
+
custom_id=custom_id, title=title, description=description,
|
|
200
|
+
images=images, source_url=source_url,
|
|
201
|
+
height=height, size_unit=size_unit, tags=tags,
|
|
202
|
+
price=price, currency=currency, metadata=metadata,
|
|
203
|
+
display_enabled=display_enabled,
|
|
204
|
+
)
|
|
205
|
+
return request_sync("POST", _BASE, json=body)
|
|
206
|
+
|
|
207
|
+
@classmethod
|
|
208
|
+
def create_from_images(
|
|
209
|
+
cls,
|
|
210
|
+
images: Iterable[ImagePath],
|
|
211
|
+
*,
|
|
212
|
+
title: str | None = None,
|
|
213
|
+
custom_id: str | None = None,
|
|
214
|
+
description: str | None = None,
|
|
215
|
+
height: float | None = None,
|
|
216
|
+
size_unit: str | None = None,
|
|
217
|
+
tags: list[str] | None = None,
|
|
218
|
+
display_enabled: bool | None = None,
|
|
219
|
+
) -> ViewriumObject:
|
|
220
|
+
files, handles = _open_image_handles(images)
|
|
221
|
+
try:
|
|
222
|
+
data = _multipart_common(
|
|
223
|
+
title=title, custom_id=custom_id, description=description,
|
|
224
|
+
height=height, size_unit=size_unit, tags=tags,
|
|
225
|
+
display_enabled=display_enabled,
|
|
226
|
+
)
|
|
227
|
+
return request_sync(
|
|
228
|
+
"POST", f"{_BASE}/from-images", data=data, files=files,
|
|
229
|
+
)
|
|
230
|
+
finally:
|
|
231
|
+
_close_all(handles)
|
|
232
|
+
|
|
233
|
+
@classmethod
|
|
234
|
+
def create_from_video(
|
|
235
|
+
cls,
|
|
236
|
+
video: VideoPath,
|
|
237
|
+
*,
|
|
238
|
+
title: str | None = None,
|
|
239
|
+
custom_id: str | None = None,
|
|
240
|
+
description: str | None = None,
|
|
241
|
+
height: float | None = None,
|
|
242
|
+
size_unit: str | None = None,
|
|
243
|
+
tags: list[str] | None = None,
|
|
244
|
+
display_enabled: bool | None = None,
|
|
245
|
+
) -> ViewriumObject:
|
|
246
|
+
files, handles = _open_video_handle(video)
|
|
247
|
+
try:
|
|
248
|
+
data = _multipart_common(
|
|
249
|
+
title=title, custom_id=custom_id, description=description,
|
|
250
|
+
height=height, size_unit=size_unit, tags=tags,
|
|
251
|
+
display_enabled=display_enabled,
|
|
252
|
+
)
|
|
253
|
+
return request_sync(
|
|
254
|
+
"POST", f"{_BASE}/from-video", data=data, files=files,
|
|
255
|
+
)
|
|
256
|
+
finally:
|
|
257
|
+
_close_all(handles)
|
|
258
|
+
|
|
259
|
+
@classmethod
|
|
260
|
+
def retrieve(cls, model_id: str) -> ViewriumObject:
|
|
261
|
+
return request_sync("GET", f"{_BASE}/{model_id}")
|
|
262
|
+
|
|
263
|
+
@classmethod
|
|
264
|
+
def list(
|
|
265
|
+
cls,
|
|
266
|
+
*,
|
|
267
|
+
tag: str | None = None,
|
|
268
|
+
tags: list[str] | str | None = None,
|
|
269
|
+
custom_id: str | None = None,
|
|
270
|
+
status: str | None = None,
|
|
271
|
+
limit: int | None = None,
|
|
272
|
+
offset: int | None = None,
|
|
273
|
+
) -> ViewriumObject:
|
|
274
|
+
return request_sync(
|
|
275
|
+
"GET", _BASE,
|
|
276
|
+
params=_list_params(
|
|
277
|
+
tag=tag, tags=tags, custom_id=custom_id,
|
|
278
|
+
status=status, limit=limit, offset=offset,
|
|
279
|
+
),
|
|
280
|
+
)
|
|
281
|
+
|
|
282
|
+
@classmethod
|
|
283
|
+
def modify(
|
|
284
|
+
cls,
|
|
285
|
+
model_id: str,
|
|
286
|
+
*,
|
|
287
|
+
custom_id: str | None = None,
|
|
288
|
+
title: str | None = None,
|
|
289
|
+
description: str | None = None,
|
|
290
|
+
price: float | None = None,
|
|
291
|
+
currency: str | None = None,
|
|
292
|
+
height: float | None = None,
|
|
293
|
+
size_unit: str | None = None,
|
|
294
|
+
tags: list[str] | None = None,
|
|
295
|
+
metadata: dict[str, Any] | None = None,
|
|
296
|
+
display_enabled: bool | None = None,
|
|
297
|
+
) -> ViewriumObject:
|
|
298
|
+
body = _modify_body(
|
|
299
|
+
custom_id=custom_id, title=title, description=description,
|
|
300
|
+
price=price, currency=currency,
|
|
301
|
+
height=height, size_unit=size_unit,
|
|
302
|
+
tags=tags, metadata=metadata, display_enabled=display_enabled,
|
|
303
|
+
)
|
|
304
|
+
return request_sync("PATCH", f"{_BASE}/{model_id}", json=body)
|
|
305
|
+
|
|
306
|
+
@classmethod
|
|
307
|
+
def delete(cls, model_id: str) -> ViewriumObject:
|
|
308
|
+
return request_sync("DELETE", f"{_BASE}/{model_id}")
|
|
309
|
+
|
|
310
|
+
@classmethod
|
|
311
|
+
def list_events(
|
|
312
|
+
cls,
|
|
313
|
+
model_id: str,
|
|
314
|
+
*,
|
|
315
|
+
limit: int | None = None,
|
|
316
|
+
offset: int | None = None,
|
|
317
|
+
) -> ViewriumObject:
|
|
318
|
+
params: dict[str, Any] = {}
|
|
319
|
+
if limit is not None:
|
|
320
|
+
params["limit"] = limit
|
|
321
|
+
if offset is not None:
|
|
322
|
+
params["offset"] = offset
|
|
323
|
+
return request_sync("GET", f"{_BASE}/{model_id}/events", params=params)
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
# ---------------------------------------------------------------------------
|
|
327
|
+
# Async
|
|
328
|
+
# ---------------------------------------------------------------------------
|
|
329
|
+
class AsyncModel:
|
|
330
|
+
"""3D models (backed by the `scans` table). Async API."""
|
|
331
|
+
|
|
332
|
+
@classmethod
|
|
333
|
+
async def create(
|
|
334
|
+
cls,
|
|
335
|
+
*,
|
|
336
|
+
custom_id: str | None = None,
|
|
337
|
+
title: str | None = None,
|
|
338
|
+
description: str | None = None,
|
|
339
|
+
images: list[str] | None = None,
|
|
340
|
+
source_url: str | None = None,
|
|
341
|
+
height: float | None = None,
|
|
342
|
+
size_unit: str | None = None,
|
|
343
|
+
tags: list[str] | None = None,
|
|
344
|
+
price: float | None = None,
|
|
345
|
+
currency: str | None = None,
|
|
346
|
+
metadata: dict[str, Any] | None = None,
|
|
347
|
+
display_enabled: bool | None = None,
|
|
348
|
+
) -> ViewriumObject:
|
|
349
|
+
body = _build_create_body(
|
|
350
|
+
custom_id=custom_id, title=title, description=description,
|
|
351
|
+
images=images, source_url=source_url,
|
|
352
|
+
height=height, size_unit=size_unit, tags=tags,
|
|
353
|
+
price=price, currency=currency, metadata=metadata,
|
|
354
|
+
display_enabled=display_enabled,
|
|
355
|
+
)
|
|
356
|
+
return await request_async("POST", _BASE, json=body)
|
|
357
|
+
|
|
358
|
+
@classmethod
|
|
359
|
+
async def create_from_images(
|
|
360
|
+
cls,
|
|
361
|
+
images: Iterable[ImagePath],
|
|
362
|
+
*,
|
|
363
|
+
title: str | None = None,
|
|
364
|
+
custom_id: str | None = None,
|
|
365
|
+
description: str | None = None,
|
|
366
|
+
height: float | None = None,
|
|
367
|
+
size_unit: str | None = None,
|
|
368
|
+
tags: list[str] | None = None,
|
|
369
|
+
display_enabled: bool | None = None,
|
|
370
|
+
) -> ViewriumObject:
|
|
371
|
+
files, handles = _open_image_handles(images)
|
|
372
|
+
try:
|
|
373
|
+
data = _multipart_common(
|
|
374
|
+
title=title, custom_id=custom_id, description=description,
|
|
375
|
+
height=height, size_unit=size_unit, tags=tags,
|
|
376
|
+
display_enabled=display_enabled,
|
|
377
|
+
)
|
|
378
|
+
return await request_async(
|
|
379
|
+
"POST", f"{_BASE}/from-images", data=data, files=files,
|
|
380
|
+
)
|
|
381
|
+
finally:
|
|
382
|
+
_close_all(handles)
|
|
383
|
+
|
|
384
|
+
@classmethod
|
|
385
|
+
async def create_from_video(
|
|
386
|
+
cls,
|
|
387
|
+
video: VideoPath,
|
|
388
|
+
*,
|
|
389
|
+
title: str | None = None,
|
|
390
|
+
custom_id: str | None = None,
|
|
391
|
+
description: str | None = None,
|
|
392
|
+
height: float | None = None,
|
|
393
|
+
size_unit: str | None = None,
|
|
394
|
+
tags: list[str] | None = None,
|
|
395
|
+
display_enabled: bool | None = None,
|
|
396
|
+
) -> ViewriumObject:
|
|
397
|
+
files, handles = _open_video_handle(video)
|
|
398
|
+
try:
|
|
399
|
+
data = _multipart_common(
|
|
400
|
+
title=title, custom_id=custom_id, description=description,
|
|
401
|
+
height=height, size_unit=size_unit, tags=tags,
|
|
402
|
+
display_enabled=display_enabled,
|
|
403
|
+
)
|
|
404
|
+
return await request_async(
|
|
405
|
+
"POST", f"{_BASE}/from-video", data=data, files=files,
|
|
406
|
+
)
|
|
407
|
+
finally:
|
|
408
|
+
_close_all(handles)
|
|
409
|
+
|
|
410
|
+
@classmethod
|
|
411
|
+
async def retrieve(cls, model_id: str) -> ViewriumObject:
|
|
412
|
+
return await request_async("GET", f"{_BASE}/{model_id}")
|
|
413
|
+
|
|
414
|
+
@classmethod
|
|
415
|
+
async def list(
|
|
416
|
+
cls,
|
|
417
|
+
*,
|
|
418
|
+
tag: str | None = None,
|
|
419
|
+
tags: list[str] | str | None = None,
|
|
420
|
+
custom_id: str | None = None,
|
|
421
|
+
status: str | None = None,
|
|
422
|
+
limit: int | None = None,
|
|
423
|
+
offset: int | None = None,
|
|
424
|
+
) -> ViewriumObject:
|
|
425
|
+
return await request_async(
|
|
426
|
+
"GET", _BASE,
|
|
427
|
+
params=_list_params(
|
|
428
|
+
tag=tag, tags=tags, custom_id=custom_id,
|
|
429
|
+
status=status, limit=limit, offset=offset,
|
|
430
|
+
),
|
|
431
|
+
)
|
|
432
|
+
|
|
433
|
+
@classmethod
|
|
434
|
+
async def modify(
|
|
435
|
+
cls,
|
|
436
|
+
model_id: str,
|
|
437
|
+
*,
|
|
438
|
+
custom_id: str | None = None,
|
|
439
|
+
title: str | None = None,
|
|
440
|
+
description: str | None = None,
|
|
441
|
+
price: float | None = None,
|
|
442
|
+
currency: str | None = None,
|
|
443
|
+
height: float | None = None,
|
|
444
|
+
size_unit: str | None = None,
|
|
445
|
+
tags: list[str] | None = None,
|
|
446
|
+
metadata: dict[str, Any] | None = None,
|
|
447
|
+
display_enabled: bool | None = None,
|
|
448
|
+
) -> ViewriumObject:
|
|
449
|
+
body = _modify_body(
|
|
450
|
+
custom_id=custom_id, title=title, description=description,
|
|
451
|
+
price=price, currency=currency,
|
|
452
|
+
height=height, size_unit=size_unit,
|
|
453
|
+
tags=tags, metadata=metadata, display_enabled=display_enabled,
|
|
454
|
+
)
|
|
455
|
+
return await request_async("PATCH", f"{_BASE}/{model_id}", json=body)
|
|
456
|
+
|
|
457
|
+
@classmethod
|
|
458
|
+
async def delete(cls, model_id: str) -> ViewriumObject:
|
|
459
|
+
return await request_async("DELETE", f"{_BASE}/{model_id}")
|
|
460
|
+
|
|
461
|
+
@classmethod
|
|
462
|
+
async def list_events(
|
|
463
|
+
cls,
|
|
464
|
+
model_id: str,
|
|
465
|
+
*,
|
|
466
|
+
limit: int | None = None,
|
|
467
|
+
offset: int | None = None,
|
|
468
|
+
) -> ViewriumObject:
|
|
469
|
+
params: dict[str, Any] = {}
|
|
470
|
+
if limit is not None:
|
|
471
|
+
params["limit"] = limit
|
|
472
|
+
if offset is not None:
|
|
473
|
+
params["offset"] = offset
|
|
474
|
+
return await request_async(
|
|
475
|
+
"GET", f"{_BASE}/{model_id}/events", params=params,
|
|
476
|
+
)
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Tag resource - sync + async.
|
|
2
|
+
|
|
3
|
+
Lists unique tags across the caller's organization with per-tag model counts.
|
|
4
|
+
Tags are created implicitly when assigned to a model; no POST /v1/tags.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from .._client import request_async, request_sync
|
|
10
|
+
from .._object import ViewriumObject
|
|
11
|
+
|
|
12
|
+
_BASE = "/v1/tags"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Tag:
|
|
16
|
+
"""Tag autocomplete listing. Sync."""
|
|
17
|
+
|
|
18
|
+
@classmethod
|
|
19
|
+
def list(cls) -> ViewriumObject:
|
|
20
|
+
return request_sync("GET", _BASE)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class AsyncTag:
|
|
24
|
+
"""Tag autocomplete listing. Async."""
|
|
25
|
+
|
|
26
|
+
@classmethod
|
|
27
|
+
async def list(cls) -> ViewriumObject:
|
|
28
|
+
return await request_async("GET", _BASE)
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Usage resource - sync + async.
|
|
2
|
+
|
|
3
|
+
Returns aggregated event counts for the caller's organization. Accepts
|
|
4
|
+
ISO 8601 `since` / `until` bounds. Internal service events (rodin, gemini,
|
|
5
|
+
scrape, convert, store) are never exposed here.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from .._client import request_async, request_sync
|
|
13
|
+
from .._object import ViewriumObject
|
|
14
|
+
|
|
15
|
+
_BASE = "/v1/usage"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _params(since: str | None, until: str | None) -> dict[str, Any]:
|
|
19
|
+
params: dict[str, Any] = {}
|
|
20
|
+
if since is not None:
|
|
21
|
+
params["since"] = since
|
|
22
|
+
if until is not None:
|
|
23
|
+
params["until"] = until
|
|
24
|
+
return params
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Usage:
|
|
28
|
+
"""Aggregated usage records. Sync."""
|
|
29
|
+
|
|
30
|
+
@classmethod
|
|
31
|
+
def retrieve(
|
|
32
|
+
cls,
|
|
33
|
+
*,
|
|
34
|
+
since: str | None = None,
|
|
35
|
+
until: str | None = None,
|
|
36
|
+
) -> ViewriumObject:
|
|
37
|
+
return request_sync("GET", _BASE, params=_params(since, until))
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class AsyncUsage:
|
|
41
|
+
"""Aggregated usage records. Async."""
|
|
42
|
+
|
|
43
|
+
@classmethod
|
|
44
|
+
async def retrieve(
|
|
45
|
+
cls,
|
|
46
|
+
*,
|
|
47
|
+
since: str | None = None,
|
|
48
|
+
until: str | None = None,
|
|
49
|
+
) -> ViewriumObject:
|
|
50
|
+
return await request_async("GET", _BASE, params=_params(since, until))
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: viewrium
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official Python SDK for the Viewrium API. Create and manage 3D models, api keys, and usage records.
|
|
5
|
+
Project-URL: Homepage, https://viewrium.com
|
|
6
|
+
Project-URL: Repository, https://github.com/davidzagyvaig/viewrium
|
|
7
|
+
Project-URL: Documentation, https://docs.viewrium.com
|
|
8
|
+
Author-email: Viewrium <hello@viewrium.com>
|
|
9
|
+
License: Apache-2.0
|
|
10
|
+
Keywords: 3d,api,ar,model-viewer,sdk,viewrium
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Requires-Dist: httpx>=0.27
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# viewrium
|
|
24
|
+
|
|
25
|
+
Official Python SDK for the [Viewrium](https://viewrium.com) API. Create and manage 3D models, API keys, and usage records.
|
|
26
|
+
|
|
27
|
+
## Install
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pip install viewrium
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Python 3.10+.
|
|
34
|
+
|
|
35
|
+
## Configure
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
import viewrium
|
|
39
|
+
viewrium.api_key = "sk_live_..."
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Or via environment variable:
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
export VIEWRIUM_API_KEY=sk_live_...
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Both are supported; the module variable wins if both are set.
|
|
49
|
+
|
|
50
|
+
Other config (all optional):
|
|
51
|
+
|
|
52
|
+
| Variable | Env | Default |
|
|
53
|
+
|---|---|---|
|
|
54
|
+
| `viewrium.api_base` | `VIEWRIUM_API_BASE` | `https://api.viewrium.com` |
|
|
55
|
+
| `viewrium.timeout` | - | `60` seconds |
|
|
56
|
+
| `viewrium.max_retries` | - | `3` (retries 429 / 5xx, respects `Retry-After`) |
|
|
57
|
+
|
|
58
|
+
## Quickstart (sync)
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
import viewrium
|
|
62
|
+
|
|
63
|
+
viewrium.api_key = "sk_live_..."
|
|
64
|
+
|
|
65
|
+
model = viewrium.Model.create(
|
|
66
|
+
custom_id="sku-1",
|
|
67
|
+
images=["https://example.com/img1.jpg", "https://example.com/img2.jpg"],
|
|
68
|
+
height=90,
|
|
69
|
+
tags=["chair", "summer-2026"],
|
|
70
|
+
)
|
|
71
|
+
print(model.id, model.status)
|
|
72
|
+
|
|
73
|
+
models = viewrium.Model.list(tag="chair", limit=20)
|
|
74
|
+
for m in models.data:
|
|
75
|
+
print(m.custom_id, m.status)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Quickstart (async)
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
import asyncio
|
|
82
|
+
import viewrium
|
|
83
|
+
|
|
84
|
+
viewrium.api_key = "sk_live_..."
|
|
85
|
+
|
|
86
|
+
async def main():
|
|
87
|
+
model = await viewrium.AsyncModel.create(
|
|
88
|
+
custom_id="sku-1",
|
|
89
|
+
images=["https://example.com/img1.jpg"],
|
|
90
|
+
height=35,
|
|
91
|
+
size_unit="in", # converted to cm server-side
|
|
92
|
+
)
|
|
93
|
+
events = await viewrium.AsyncModel.list_events(model.id)
|
|
94
|
+
return model, events
|
|
95
|
+
|
|
96
|
+
asyncio.run(main())
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## Resources
|
|
100
|
+
|
|
101
|
+
Each resource has a sync class and an `Async`-prefixed async twin.
|
|
102
|
+
|
|
103
|
+
| Sync | Async | Methods |
|
|
104
|
+
|---|---|---|
|
|
105
|
+
| `Model` | `AsyncModel` | `create`, `create_from_images`, `create_from_video`, `retrieve`, `list`, `modify`, `delete`, `list_events` |
|
|
106
|
+
| `ApiKey` | `AsyncApiKey` | `create`, `list`, `delete` |
|
|
107
|
+
| `Usage` | `AsyncUsage` | `retrieve` |
|
|
108
|
+
| `Tag` | `AsyncTag` | `list` |
|
|
109
|
+
|
|
110
|
+
## Uploading files
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
model = viewrium.Model.create_from_images(
|
|
114
|
+
["./chair-front.jpg", "./chair-side.jpg", "./chair-back.jpg"],
|
|
115
|
+
custom_id="sku-1",
|
|
116
|
+
height=90,
|
|
117
|
+
tags=["chair"],
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
model = viewrium.Model.create_from_video(
|
|
121
|
+
"./chair-walkaround.mp4",
|
|
122
|
+
custom_id="sku-2",
|
|
123
|
+
height=92,
|
|
124
|
+
)
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
Paths are strings or `pathlib.Path`. Files are opened + closed by the SDK.
|
|
128
|
+
|
|
129
|
+
## Sizing
|
|
130
|
+
|
|
131
|
+
Pass `height` + optional `size_unit` (`"cm"` or `"in"`, default `"cm"`). The server normalizes to cm before storing. Explicit `height` wins over scraped values; if neither is present, the model renders unscaled.
|
|
132
|
+
|
|
133
|
+
## Errors
|
|
134
|
+
|
|
135
|
+
```python
|
|
136
|
+
from viewrium import (
|
|
137
|
+
ViewriumError, # base class
|
|
138
|
+
AuthError, # 401 / missing key
|
|
139
|
+
NotFoundError, # 404
|
|
140
|
+
ValidationError, # 400 / 409 / 422
|
|
141
|
+
RateLimitError, # 429 (has .retry_after)
|
|
142
|
+
APIError, # 5xx / other
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
try:
|
|
146
|
+
viewrium.Model.retrieve("not-a-real-id")
|
|
147
|
+
except NotFoundError:
|
|
148
|
+
...
|
|
149
|
+
except RateLimitError as e:
|
|
150
|
+
print("back off for", e.retry_after, "seconds")
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
## Cleanup
|
|
154
|
+
|
|
155
|
+
The SDK lazily opens HTTP clients and tears them down on process exit. If you need to close eagerly:
|
|
156
|
+
|
|
157
|
+
```python
|
|
158
|
+
viewrium.close() # sync client
|
|
159
|
+
await viewrium.aclose() # async client
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
## License
|
|
163
|
+
|
|
164
|
+
Apache 2.0.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
viewrium/__init__.py,sha256=dR7QLrUUJ9Qanhp2RZQV-vl3ejaxn_JjD35F1pGCxnY,2022
|
|
2
|
+
viewrium/_client.py,sha256=6RfE7EhR0DWwnOGpvgE7nEMOHXKYRK1mVNbUZWp1EtI,9495
|
|
3
|
+
viewrium/_errors.py,sha256=TqunZc_I9J-mQ68-Hya-ob11AlJWKTd8LX51mj4ec6c,1587
|
|
4
|
+
viewrium/_object.py,sha256=2s2_oDhyWR98iZx9xF1KX2_H4Bi9gw-gYyyR61x1_wk,1366
|
|
5
|
+
viewrium/resources/__init__.py,sha256=6XxLTZeKRemrH1XptPSfNlZW-O7hfGsmgm7IEvzSg4E,549
|
|
6
|
+
viewrium/resources/api_key.py,sha256=Mg5APwPR9IKS36SRyfNPZat7nf-7gpY_doGNlD5Or0o,1785
|
|
7
|
+
viewrium/resources/model.py,sha256=7zLkagpUURynLONDH_OmMGaQlBVm-tkpLuXFnuBgeCk,14773
|
|
8
|
+
viewrium/resources/tag.py,sha256=3VqGE8YIOFQhSZY3ZqU2TgRfXA4iGVPsGQRPgxCMEks,654
|
|
9
|
+
viewrium/resources/usage.py,sha256=xdiJ0-qUBXAEXdvjWpvCIAn1fJXJf__aNllX4gsW-98,1222
|
|
10
|
+
viewrium-0.1.0.dist-info/METADATA,sha256=PQIt2yu4NBI_4fOuetL2FIed4NEFCFTR9jl-ukH_azE,4167
|
|
11
|
+
viewrium-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
12
|
+
viewrium-0.1.0.dist-info/RECORD,,
|