perception-sdk 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,92 @@
1
+ """The exceptions the client raises.
2
+
3
+ Every answer the API refuses becomes a `PerceptionError` carrying the HTTP status, the API's `error`
4
+ field and its `detail` sentence. The subclasses let a caller catch the cases it acts on."""
5
+
6
+ from __future__ import annotations
7
+
8
+ from typing import Any
9
+
10
+
11
+ class ConfigurationError(Exception):
12
+ """The client was not given what it needs to reach the API: a URL or a credential."""
13
+
14
+
15
+ class PerceptionError(Exception):
16
+ """The API, or the network on the way to it, did not do what was asked.
17
+
18
+ `status` is the HTTP status (0 when no response arrived), `error` is the API's `error` field
19
+ (an int status, a short code such as ``"invalid_request"``, or None), and `detail` is the API's
20
+ explanation when it gave one."""
21
+
22
+ def __init__(self, status: int, error: Any = None, detail: str | None = None) -> None:
23
+ self.status = status
24
+ self.error = error
25
+ self.detail = detail
26
+ super().__init__(status, error, detail)
27
+
28
+ def __str__(self) -> str:
29
+ head = f"HTTP {self.status}" if self.status else "no response"
30
+ if self.error is not None and self.error != self.status:
31
+ head = f"{head} {self.error}"
32
+ return f"{head}: {self.detail}" if self.detail else head
33
+
34
+ def __repr__(self) -> str:
35
+ return (
36
+ f"{type(self).__name__}(status={self.status!r}, error={self.error!r},"
37
+ f" detail={self.detail!r})"
38
+ )
39
+
40
+
41
+ class AuthenticationError(PerceptionError):
42
+ """401: the key or admin token is missing, wrong, expired or revoked."""
43
+
44
+
45
+ class PermissionDenied(PerceptionError):
46
+ """403: the credential is valid but may not touch what was named."""
47
+
48
+
49
+ class NotFoundError(PerceptionError):
50
+ """404: no such tenant, subject, source, key or other record (for this caller)."""
51
+
52
+
53
+ class ConflictError(PerceptionError):
54
+ """409: the request conflicts with the current state, such as revoking the key the request is
55
+ made with."""
56
+
57
+
58
+ class PayloadTooLarge(PerceptionError):
59
+ """413: the media is over a limit; `detail` names it."""
60
+
61
+
62
+ class ValidationError(PerceptionError):
63
+ """422: the request was malformed; `detail` says which field and why."""
64
+
65
+
66
+ class ServerError(PerceptionError):
67
+ """5xx: the API failed or a dependency it needs is not configured or not available."""
68
+
69
+
70
+ class APIConnectionError(PerceptionError):
71
+ """The request never got an HTTP answer: the connection failed or timed out."""
72
+
73
+
74
+ class UploadError(PerceptionError):
75
+ """A part of an upload could not be stored. `error` is the blob store's error code when it
76
+ gave one, such as ``"AccessDenied"`` for an expired upload URL."""
77
+
78
+
79
+ _BY_STATUS: dict[int, type[PerceptionError]] = {
80
+ 401: AuthenticationError,
81
+ 403: PermissionDenied,
82
+ 404: NotFoundError,
83
+ 409: ConflictError,
84
+ 413: PayloadTooLarge,
85
+ 422: ValidationError,
86
+ }
87
+
88
+
89
+ def error_for_status(status: int) -> type[PerceptionError]:
90
+ if status >= 500:
91
+ return ServerError
92
+ return _BY_STATUS.get(status, PerceptionError)
@@ -0,0 +1,135 @@
1
+ """The few answers worth a type: keys, the caller's identity and sources. The rest are dicts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator
6
+ from dataclasses import asdict, dataclass, field, fields
7
+ from datetime import datetime
8
+ from typing import Any
9
+
10
+
11
+ def _parse_time(value: str | None) -> datetime | None:
12
+ if value is None:
13
+ return None
14
+ # Python 3.10's fromisoformat does not read a trailing "Z".
15
+ if value.endswith("Z"):
16
+ value = value[:-1] + "+00:00"
17
+ return datetime.fromisoformat(value)
18
+
19
+
20
+ def _known(cls: type, data: dict[str, Any]) -> dict[str, Any]:
21
+ """The fields `cls` declares, so a newer API that adds a field does not break an older SDK."""
22
+ names = {f.name for f in fields(cls)}
23
+ return {k: v for k, v in data.items() if k in names}
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class ApiKey:
28
+ """A key as the API describes it. Its secret is never part of this: see `IssuedApiKey`."""
29
+
30
+ key_id: str
31
+ name: str
32
+ created_at: datetime | None
33
+ expires_at: datetime | None
34
+ last_used_at: datetime | None
35
+ revoked_at: datetime | None
36
+
37
+ @classmethod
38
+ def from_dict(cls, data: dict[str, Any]) -> ApiKey:
39
+ return cls(**_key_fields(data))
40
+
41
+ def to_dict(self) -> dict[str, Any]:
42
+ """JSON-ready: times as ISO 8601 strings."""
43
+ out = asdict(self)
44
+ for name in ("created_at", "expires_at", "last_used_at", "revoked_at"):
45
+ out[name] = out[name].isoformat() if out[name] is not None else None
46
+ return out
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class IssuedApiKey(ApiKey):
51
+ """A key just issued or rotated, with its secret. The API returns the secret once, here, and
52
+ never again; it is left out of `repr()` so it does not end up in a log by accident."""
53
+
54
+ api_key: str = field(default="", repr=False)
55
+
56
+ @classmethod
57
+ def from_dict(cls, data: dict[str, Any]) -> IssuedApiKey:
58
+ return cls(**_key_fields(data), api_key=data["api_key"])
59
+
60
+
61
+ def _key_fields(data: dict[str, Any]) -> dict[str, Any]:
62
+ return {
63
+ "key_id": data["key_id"],
64
+ "name": data.get("name") or "",
65
+ "created_at": _parse_time(data.get("created_at")),
66
+ "expires_at": _parse_time(data.get("expires_at")),
67
+ "last_used_at": _parse_time(data.get("last_used_at")),
68
+ "revoked_at": _parse_time(data.get("revoked_at")),
69
+ }
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class KeyList:
74
+ """A list of keys as the API answers it: newest first, revoked and expired ones included.
75
+
76
+ The API returns at most 200 keys. `truncated` is True when it stopped there, so there may be
77
+ older keys this list does not hold. Iterating over a `KeyList` gives its keys."""
78
+
79
+ keys: list[ApiKey]
80
+ truncated: bool
81
+
82
+ @classmethod
83
+ def from_dict(cls, data: dict[str, Any]) -> KeyList:
84
+ return cls(
85
+ keys=[ApiKey.from_dict(k) for k in data["keys"]],
86
+ truncated=bool(data.get("truncated", False)),
87
+ )
88
+
89
+ def __iter__(self) -> Iterator[ApiKey]:
90
+ return iter(self.keys)
91
+
92
+ def __len__(self) -> int:
93
+ return len(self.keys)
94
+
95
+ def to_dict(self) -> dict[str, Any]:
96
+ return {"keys": [k.to_dict() for k in self.keys], "truncated": self.truncated}
97
+
98
+
99
+ @dataclass(frozen=True)
100
+ class WhoAmI:
101
+ """The tenant and the key the client authenticated as."""
102
+
103
+ tenant_id: str
104
+ key_id: str
105
+
106
+ @classmethod
107
+ def from_dict(cls, data: dict[str, Any]) -> WhoAmI:
108
+ return cls(**_known(cls, data))
109
+
110
+ def to_dict(self) -> dict[str, Any]:
111
+ return asdict(self)
112
+
113
+
114
+ @dataclass(frozen=True)
115
+ class Source:
116
+ """One piece of media registered on a stream. `size_bytes` is None until its upload completes.
117
+ `status` is the processing state, ``"REGISTERED"`` until processing starts."""
118
+
119
+ source_id: str
120
+ stream_id: str
121
+ client_ref: str
122
+ kind: str
123
+ media_type: str
124
+ content_type: str
125
+ status: str
126
+ size_bytes: int | None = None
127
+ session_id: str | None = None
128
+ stream_offset_us: int = 0
129
+
130
+ @classmethod
131
+ def from_dict(cls, data: dict[str, Any]) -> Source:
132
+ return cls(**_known(cls, data))
133
+
134
+ def to_dict(self) -> dict[str, Any]:
135
+ return asdict(self)
File without changes
@@ -0,0 +1,248 @@
1
+ Metadata-Version: 2.5
2
+ Name: perception-sdk
3
+ Version: 0.1.0
4
+ Summary: A Python client and command line for the Perception console API
5
+ Author: Metacog Labs
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Classifier: Operating System :: OS Independent
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.10
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Programming Language :: Python :: 3.14
15
+ Classifier: Typing :: Typed
16
+ Requires-Python: >=3.10
17
+ Requires-Dist: httpx<1,>=0.27
18
+ Description-Content-Type: text/markdown
19
+
20
+ # perception-sdk
21
+
22
+ A Python client and command line for the Perception console API. The engine takes video, audio,
23
+ images and documents, works out what happened in them, and answers questions about it. The
24
+ console organises that work into projects, threads, workflows and jobs.
25
+
26
+ Python 3.10 or newer. The only dependency is `httpx`.
27
+
28
+ ## Install
29
+
30
+ ```sh
31
+ pip install perception-sdk
32
+ ```
33
+
34
+ ## Configure
35
+
36
+ The client needs the API's URL and an API key. Pass them in, or set them in the environment.
37
+ There is no default URL:
38
+
39
+ ```sh
40
+ export PERCEPTION_API_URL=https://perception-console.eastus.cloudapp.azure.com
41
+ export PERCEPTION_API_KEY=pk_...
42
+ ```
43
+
44
+ | Variable | Used by | What it is |
45
+ |---|---|---|
46
+ | `PERCEPTION_API_URL` | `Client`, `AdminClient` | The API's base URL |
47
+ | `PERCEPTION_API_KEY` | `Client` | One of your workspace's API keys (`pk_...`) |
48
+ | `PERCEPTION_ADMIN_TOKEN` | `AdminClient` | The operator's admin token. Only the engine's operator has one |
49
+
50
+ ```python
51
+ from perception_sdk import Client
52
+
53
+ with Client() as client: # reads the environment
54
+ print(client.whoami()) # WhoAmI(tenant_id='Acme', key_id='4f1c2a9be07d3e15')
55
+
56
+ client = Client("https://perception-console.eastus.cloudapp.azure.com", "pk_...")
57
+ ```
58
+
59
+ The key is sent only to the API. It never appears in `repr()`, in log lines or in exception
60
+ messages, and it is never sent to the storage that uploads go to.
61
+
62
+ ## A workspace's first key
63
+
64
+ Your workspace's first key is issued by the operator. From then on the workspace issues and
65
+ revokes its own keys, from the console (Settings, API keys) or with this package.
66
+
67
+ ## Manage API keys
68
+
69
+ ```python
70
+ with Client() as client:
71
+ new = client.keys.create("ci", expires_at="2027-06-30T00:00:00+00:00")
72
+ print(new.api_key) # the secret: shown this once, store it now
73
+
74
+ keys = client.keys.list()
75
+ for key in keys:
76
+ print(key.key_id, key.name, key.expires_at, key.last_used_at, key.revoked_at)
77
+ if keys.truncated:
78
+ print("only the newest 200 keys are listed")
79
+
80
+ replacement = client.keys.rotate(new.key_id) # revokes the old key, same name
81
+ client.keys.revoke(replacement.key_id) # answers the revoked key
82
+ client.keys.delete(new.key_id) # the same, answering nothing
83
+ ```
84
+
85
+ `keys.list()` returns a `KeyList`: its keys, newest first, revoked and expired ones included, and
86
+ `truncated`, which is True when the API stopped at its limit of 200. A key's `name` is a string,
87
+ empty when it has none. `expires_at` must be in the future and carry a time zone.
88
+
89
+ You cannot revoke the key you are calling with (`ConflictError`); revoke it with another key. You
90
+ can rotate it: the answer carries its successor, and the old key stops working at once.
91
+
92
+ Rotating without `expires_at` gives the new key no expiry, even if the old key had one. Pass
93
+ `expires_at=` to `keys.rotate()` to keep one.
94
+
95
+ ## Projects, threads, workflows and jobs
96
+
97
+ These methods return the API's JSON answer as a dict. A list answers with the list under its name
98
+ and, where the API caps it, `truncated`.
99
+
100
+ ```python
101
+ with Client() as client:
102
+ project = client.projects.create("Docks") # comes with a workflow named "Default"
103
+ p = project["project_id"]
104
+ [workflow] = client.workflows.list(p)["workflows"]
105
+
106
+ thread = client.threads.create(p, "Monday")
107
+ source = client.sources.upload(thread["subject_id"], "dock-camera.mp4")
108
+
109
+ job = client.jobs.create(
110
+ p,
111
+ workflow["workflow_id"],
112
+ workflow["latest_version"],
113
+ [source.source_id],
114
+ thread_id=thread["thread_id"],
115
+ )
116
+ print(client.jobs.status(p, job["job_id"]))
117
+
118
+ # once it has finished
119
+ print(client.jobs.output(p, job["job_id"])) # a summary and the first elements
120
+ print(client.jobs.download_url(p, job["job_id"])) # a short-lived link to the whole file
121
+ ```
122
+
123
+ | Namespace | Methods |
124
+ |---|---|
125
+ | `client.projects` | `create`, `list`, `get`, `update` |
126
+ | `client.threads` | `create`, `list`, `get`, `rename`, `delete`, `reassemble`, `cancel_rebuild`, `take_file` |
127
+ | `client.workflows` | `create`, `list`, `get`, `rename`, `save_version`, `list_versions`, `get_version`, `restore_version`, `run` |
128
+ | `client.jobs` | `create`, `list`, `get`, `status`, `retry_failure`, `output`, `download_url` |
129
+ | `client.connectors` | `create`, `list`, `get`, `update`, `delete`, `check`, `objects` |
130
+ | `client` | `catalogue`, `whoami`, `query`, `perceive_sync` |
131
+
132
+ `jobs.list()` pages newest first: pass its `next_after` back as `after=` for the next page. Pass
133
+ `request_id=` (a UUID) to `jobs.create()` or `workflows.run()` so that sending the same request
134
+ again returns the same job instead of starting another.
135
+
136
+ ## Upload media
137
+
138
+ ```python
139
+ with Client() as client:
140
+ source = client.sources.upload(
141
+ thread["subject_id"],
142
+ "dock-camera.mp4",
143
+ on_progress=lambda sent, total: print(f"{sent}/{total} bytes"),
144
+ )
145
+ print(source.source_id, source.size_bytes)
146
+ ```
147
+
148
+ `upload()` registers the file, sends it straight to the engine's storage in 5 MiB parts (reading
149
+ one part at a time, never the whole file), and completes it. A part that fails for a moment is
150
+ retried three times before `UploadError` is raised. The content type comes from the file name and
151
+ the media type from that; pass `content_type=` or `media_type=` when the guess is wrong.
152
+
153
+ Uploading is idempotent: the same file on the same stream returns the source already there. By
154
+ default the stream is named after the file and a digest of its content. Pass `stream_id=` to put
155
+ several files on one stream, with `stream_offset_us=` saying where each one starts.
156
+
157
+ In the console a thread's files are processed by a job. `sources.process()` starts processing one
158
+ source on its own, outside any job.
159
+
160
+ ## Errors
161
+
162
+ Every refusal from the API raises a `PerceptionError` with `status` (the HTTP status), `error` (the
163
+ API's error code) and `detail` (its explanation). Catch the subclass you act on:
164
+
165
+ | Exception | When |
166
+ |---|---|
167
+ | `AuthenticationError` | 401: the key is missing, wrong, expired or revoked |
168
+ | `PermissionDenied` | 403: the key may not touch what was named |
169
+ | `NotFoundError` | 404: no such project, thread, job, key or record |
170
+ | `ConflictError` | 409: the request conflicts with the current state |
171
+ | `PayloadTooLarge` | 413: the media is over a limit |
172
+ | `ValidationError` | 422: a field was wrong; `detail` says which |
173
+ | `ServerError` | 5xx |
174
+ | `APIConnectionError` | No answer: the connection failed or timed out |
175
+ | `UploadError` | A part of an upload could not be stored, or the API's upload answer was malformed |
176
+ | `PerceptionError` | Anything else, such as a success answer that is not JSON |
177
+ | `ConfigurationError` | No URL or credential was given (not a `PerceptionError`) |
178
+
179
+ ```python
180
+ from perception_sdk import Client, ConflictError, NotFoundError, PerceptionError
181
+
182
+ with Client() as client:
183
+ try:
184
+ client.keys.revoke("4f1c2a9be07d3e15")
185
+ except ConflictError:
186
+ print("that is the key you are calling with; revoke it with another")
187
+ except NotFoundError:
188
+ print("no such key")
189
+ except PerceptionError as e:
190
+ print(e.status, e.error, e.detail)
191
+ ```
192
+
193
+ Reads (`GET`) are tried up to three times (the first attempt and two retries) on a failed
194
+ connection or a 502, 503 or 504. Writes are never retried, because a write that timed out may
195
+ already have happened.
196
+
197
+ ## The operator's client
198
+
199
+ `AdminClient` uses the admin token. The admin API is not public; reach it through an SSH tunnel to
200
+ the server and pass `--url http://127.0.0.1:<port>` (or the same URL to `AdminClient`), where
201
+ `<port>` is the local end of the tunnel.
202
+
203
+ ```python
204
+ from perception_sdk import AdminClient
205
+
206
+ with AdminClient("http://127.0.0.1:<port>") as admin: # PERCEPTION_ADMIN_TOKEN
207
+ admin.tenants.create("Acme")
208
+ first = admin.keys.create("Acme", name="bootstrap")
209
+ print(first.api_key)
210
+ print(admin.keys.list("Acme").truncated)
211
+ ```
212
+
213
+ `admin.tenants` (`create`, `list`), `admin.subjects` (`create`), `admin.keys` (`list`, `create`,
214
+ `revoke`, `rotate`), `admin.dead_letters`, `admin.quarantine` and `admin.subscriptions` cover the
215
+ admin routes.
216
+
217
+ ## Command line
218
+
219
+ Installing the package also installs `perception`. It reads the same environment variables:
220
+ `PERCEPTION_API_URL` (or `--url`), `PERCEPTION_API_KEY` for a workspace's commands and
221
+ `PERCEPTION_ADMIN_TOKEN` for `admin`. Credentials are taken from the environment only, never from
222
+ a flag, so they stay out of your shell history.
223
+
224
+ ```sh
225
+ perception whoami
226
+ perception keys create --name ci --expires-at 2027-06-30T00:00:00+00:00
227
+ perception keys list --table
228
+ perception keys rotate 4f1c2a9be07d3e15
229
+ perception keys delete 4f1c2a9be07d3e15
230
+ perception jobs list pr_123 --table
231
+ perception upload th_123 dock-camera.mp4 --no-process
232
+
233
+ # with an SSH tunnel to the admin API open on <port>
234
+ perception --url http://127.0.0.1:<port> admin tenants list --table
235
+ perception --url http://127.0.0.1:<port> admin keys issue Acme --name bootstrap
236
+ ```
237
+
238
+ Answers are printed to stdout as JSON; `--table` prints a list command's answer as columns, and
239
+ says on stderr when the list was truncated or, for `jobs list`, how to ask for the next page
240
+ (`more results: pass --after <job_id>`). An issued or rotated key's secret is in that JSON,
241
+ printed this once. Errors go to stderr on one line. The exit status is 0 on success, 1 when the
242
+ API refused or could not be reached (or anything unexpected went wrong), and 2 for a usage or
243
+ configuration error such as a missing URL or key. `perception --help` and each command's
244
+ `--help` list the rest.
245
+
246
+ ## License
247
+
248
+ MIT
@@ -0,0 +1,13 @@
1
+ perception_sdk/__init__.py,sha256=nFzhw3wU7YeBXvY5H0Xi0coNUPkImhp0WnBrKrFT3Vk,916
2
+ perception_sdk/_http.py,sha256=XD4qeOXnoolqCcWNo_dRG6NIzRxqt3a-gxVh__TVHlY,10299
3
+ perception_sdk/admin.py,sha256=FFml5_cW4Rv5GdRast6YtHLl4i-c-HYB5CoZpak834A,7085
4
+ perception_sdk/cli.py,sha256=HTWtptapaPqlHEQgMX8jPb4ooDUkSJfXfYfO9swqJ9c,13042
5
+ perception_sdk/client.py,sha256=Eu-fZUe3ZmHazXMub8QVB1MEJpEQ0SstmE5_-1MSRWk,33060
6
+ perception_sdk/errors.py,sha256=8q_fX--iPVH9j5HCdNFXAlcDocrRW1zrrF6fYDSFCH4,3026
7
+ perception_sdk/models.py,sha256=Z40jeBslIvfAnUo5Zshm_U5r-PRrrbidDh41aM7gWAs,4166
8
+ perception_sdk/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ perception_sdk-0.1.0.dist-info/METADATA,sha256=OngSDIUoKIjhN9Xs22bHngv71t8UFDr_f5PbXjDHTBM,10189
10
+ perception_sdk-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
11
+ perception_sdk-0.1.0.dist-info/entry_points.txt,sha256=xkUdpv9xt3O53O793DRN1z3hLOHuTWlG_cSHVnhdmrk,55
12
+ perception_sdk-0.1.0.dist-info/licenses/LICENSE,sha256=6hivzTEAEOpfzyUe9Mc5cqUHB0gBWnSw6s5ltyRdDBI,1069
13
+ perception_sdk-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ perception = perception_sdk.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Metacog Labs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.