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.
perception_sdk/cli.py ADDED
@@ -0,0 +1,358 @@
1
+ """`perception`: the API from a shell.
2
+
3
+ Answers are printed to stdout as JSON (``--table`` prints a list as columns instead); messages go
4
+ to stderr. The exit status is 0 when the command did what was asked, 1 when the API refused or
5
+ could not be reached (or anything else went wrong), and 2 for a usage or configuration error.
6
+
7
+ The URL comes from ``--url`` or ``PERCEPTION_API_URL``. The ``admin`` commands authenticate with
8
+ ``PERCEPTION_ADMIN_TOKEN`` and the rest with ``PERCEPTION_API_KEY``. Credentials are read from the
9
+ environment only: a flag would leave them in the shell history and the process list."""
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import json
15
+ import os
16
+ import sys
17
+ from collections.abc import Callable, Sequence
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ from ._http import VERSION
22
+ from .admin import AdminClient
23
+ from .client import Client
24
+ from .errors import PerceptionError
25
+
26
+ EXIT_OK = 0
27
+ EXIT_API = 1
28
+ EXIT_USAGE = 2
29
+
30
+ KEY_COLUMNS = ("key_id", "name", "created_at", "expires_at", "last_used_at", "revoked_at")
31
+ TENANT_COLUMNS = ("tenant_id", "created_at")
32
+ JOB_COLUMNS = ("job_id", "thread_id", "workflow_id", "version", "created_at")
33
+ CREDENTIALS = ("PERCEPTION_API_KEY", "PERCEPTION_ADMIN_TOKEN")
34
+
35
+ Run = Callable[[Any, argparse.Namespace], Any]
36
+
37
+
38
+ class UsageError(Exception):
39
+ """The command cannot run as given: a missing setting or an unusable file."""
40
+
41
+
42
+ def main(argv: Sequence[str] | None = None) -> int:
43
+ parser = _parser()
44
+ try:
45
+ args = parser.parse_args(argv)
46
+ except SystemExit as exc: # --help, --version, or a usage error argparse has reported
47
+ return exc.code if isinstance(exc.code, int) else EXIT_USAGE
48
+ try:
49
+ with _connect(args) as client:
50
+ result = args.run(client, args)
51
+ _emit(result, args)
52
+ except UsageError as exc:
53
+ return _fail(str(exc), EXIT_USAGE)
54
+ except PerceptionError as exc:
55
+ return _fail(str(exc), EXIT_API)
56
+ except KeyboardInterrupt:
57
+ return 130
58
+ # a bug, or an answer the SDK did not expect: one line, no traceback
59
+ except Exception as exc: # noqa: BLE001
60
+ return _fail(_scrubbed(f"unexpected error: {type(exc).__name__}: {exc}"), EXIT_API)
61
+ return EXIT_OK
62
+
63
+
64
+ def _scrubbed(message: str) -> str:
65
+ """The message with any credential from the environment taken out, and on one line."""
66
+ for name in CREDENTIALS:
67
+ secret = os.environ.get(name)
68
+ if secret:
69
+ message = message.replace(secret, "[redacted]")
70
+ return " ".join(message.split())
71
+
72
+
73
+ def _connect(args: argparse.Namespace) -> Client | AdminClient:
74
+ url = args.url or os.environ.get("PERCEPTION_API_URL")
75
+ if not url:
76
+ raise UsageError("no API URL: pass --url or set PERCEPTION_API_URL")
77
+ if args.admin:
78
+ token = os.environ.get("PERCEPTION_ADMIN_TOKEN")
79
+ if not token:
80
+ raise UsageError("no admin token: set PERCEPTION_ADMIN_TOKEN")
81
+ return AdminClient(url, token)
82
+ key = os.environ.get("PERCEPTION_API_KEY")
83
+ if not key:
84
+ raise UsageError("no API key: set PERCEPTION_API_KEY")
85
+ return Client(url, key)
86
+
87
+
88
+ def _say(message: str) -> None:
89
+ print(f"perception: {message}", file=sys.stderr)
90
+
91
+
92
+ def _fail(message: str, code: int) -> int:
93
+ _say(message)
94
+ return code
95
+
96
+
97
+ def _emit(result: Any, args: argparse.Namespace) -> None:
98
+ if result is None: # a route that answers nothing, such as a delete
99
+ return
100
+ if getattr(args, "table", False):
101
+ print(_table(result[args.rows], args.columns))
102
+ if result.get("truncated"):
103
+ _say(f"truncated: the API returned only the first {len(result[args.rows])}")
104
+ if result.get("next_after") is not None:
105
+ _say(f"more results: pass --after {result['next_after']}")
106
+ else:
107
+ print(json.dumps(result, indent=2))
108
+
109
+
110
+ def _table(rows: list[dict[str, Any]], columns: Sequence[str]) -> str:
111
+ cells = [["-" if row.get(c) is None else str(row[c]) for c in columns] for row in rows]
112
+ widths = [max([len(c)] + [len(line[i]) for line in cells]) for i, c in enumerate(columns)]
113
+ lines = [list(columns), *cells]
114
+ return "\n".join(" ".join(v.ljust(w) for v, w in zip(line, widths)).rstrip() for line in lines)
115
+
116
+
117
+ # --- the commands ---------------------------------------------------------------------------
118
+
119
+
120
+ def _keys_list(c: Client, a: argparse.Namespace) -> Any:
121
+ return c.keys.list().to_dict()
122
+
123
+
124
+ def _keys_create(c: Client, a: argparse.Namespace) -> Any:
125
+ return c.keys.create(name=a.name, expires_at=a.expires_at).to_dict()
126
+
127
+
128
+ def _keys_revoke(c: Client, a: argparse.Namespace) -> Any:
129
+ return c.keys.revoke(a.key_id).to_dict()
130
+
131
+
132
+ def _keys_rotate(c: Client, a: argparse.Namespace) -> Any:
133
+ return c.keys.rotate(a.key_id, expires_at=a.expires_at).to_dict()
134
+
135
+
136
+ def _keys_delete(c: Client, a: argparse.Namespace) -> Any:
137
+ c.keys.delete(a.key_id)
138
+
139
+
140
+ def _jobs_list(c: Client, a: argparse.Namespace) -> Any:
141
+ return c.jobs.list(a.project, thread=a.thread, after=a.after, limit=a.limit)
142
+
143
+
144
+ def _whoami(c: Client, a: argparse.Namespace) -> Any:
145
+ return c.whoami().to_dict()
146
+
147
+
148
+ def _upload(c: Client, a: argparse.Namespace) -> Any:
149
+ path = Path(a.path)
150
+ if not path.is_file():
151
+ raise UsageError(f"no such file: {path}")
152
+ progress = _progress if sys.stderr.isatty() else None
153
+ try:
154
+ source = c.sources.upload(a.subject, path, stream_id=a.stream_id, on_progress=progress)
155
+ except (OSError, ValueError) as exc: # unreadable, empty, or of a type that cannot be told
156
+ raise UsageError(str(exc)) from exc
157
+ finally:
158
+ if progress is not None:
159
+ print(file=sys.stderr)
160
+ out = source.to_dict()
161
+ if not a.no_process:
162
+ try:
163
+ out["processing"] = c.sources.process(a.subject, source.stream_id, source.source_id)
164
+ except PerceptionError:
165
+ _say(
166
+ f"uploaded source {source.source_id} on stream {source.stream_id},"
167
+ " but processing did not start"
168
+ )
169
+ raise
170
+ return out
171
+
172
+
173
+ def _progress(sent: int, total: int) -> None:
174
+ print(f"\r{sent}/{total} bytes ({100 * sent // total}%)", end="", file=sys.stderr, flush=True)
175
+
176
+
177
+ def _tenants_list(c: AdminClient, a: argparse.Namespace) -> Any:
178
+ return c.tenants.list()
179
+
180
+
181
+ def _tenants_create(c: AdminClient, a: argparse.Namespace) -> Any:
182
+ return c.tenants.create(a.tenant)
183
+
184
+
185
+ def _subjects_create(c: AdminClient, a: argparse.Namespace) -> Any:
186
+ return c.subjects.create(a.tenant, a.subject)
187
+
188
+
189
+ def _admin_keys_list(c: AdminClient, a: argparse.Namespace) -> Any:
190
+ return c.keys.list(a.tenant).to_dict()
191
+
192
+
193
+ def _admin_keys_issue(c: AdminClient, a: argparse.Namespace) -> Any:
194
+ return c.keys.create(a.tenant, name=a.name, expires_at=a.expires_at).to_dict()
195
+
196
+
197
+ def _admin_keys_revoke(c: AdminClient, a: argparse.Namespace) -> Any:
198
+ return c.keys.revoke(a.tenant, a.key_id).to_dict()
199
+
200
+
201
+ def _admin_keys_rotate(c: AdminClient, a: argparse.Namespace) -> Any:
202
+ return c.keys.rotate(a.tenant, a.key_id, expires_at=a.expires_at).to_dict()
203
+
204
+
205
+ # --- the parser -----------------------------------------------------------------------------
206
+
207
+ _EPILOG = """\
208
+ environment:
209
+ PERCEPTION_API_URL the API's base URL (--url overrides it)
210
+ PERCEPTION_API_KEY a tenant API key, for every command but admin
211
+ PERCEPTION_ADMIN_TOKEN the operator's admin token, for the admin commands
212
+
213
+ exit status: 0 done, 1 the API refused or could not be reached, 2 usage or configuration error
214
+
215
+ The admin API is not public. Reach it over SSH: ssh -L 8080:127.0.0.1:8080 <vm>, then
216
+ --url http://127.0.0.1:8080.
217
+ """
218
+
219
+
220
+ def _parser() -> argparse.ArgumentParser:
221
+ parser = argparse.ArgumentParser(
222
+ prog="perception",
223
+ description="Manage API keys, upload media, list jobs and administer workspaces of a"
224
+ " Perception API.",
225
+ epilog=_EPILOG,
226
+ formatter_class=argparse.RawDescriptionHelpFormatter,
227
+ )
228
+ parser.add_argument("--url", help="the API's base URL (default: $PERCEPTION_API_URL)")
229
+ parser.add_argument("--version", action="version", version=f"perception {VERSION}")
230
+ commands = parser.add_subparsers(dest="command", required=True, metavar="COMMAND")
231
+
232
+ keys = _group(commands, "keys", "your tenant's API keys")
233
+ _command(
234
+ keys,
235
+ "list",
236
+ "list the keys, revoked and expired ones included",
237
+ _keys_list,
238
+ table=KEY_COLUMNS,
239
+ rows="keys",
240
+ )
241
+ create = _command(keys, "create", "issue a key and print it, this once", _keys_create)
242
+ _issue_options(create, name_required=True)
243
+ revoke = _command(keys, "revoke", "revoke a key and print it", _keys_revoke)
244
+ revoke.add_argument("key_id")
245
+ delete = _command(keys, "delete", "revoke a key, printing nothing", _keys_delete)
246
+ delete.add_argument("key_id")
247
+ rotate = _command(keys, "rotate", "revoke a key and issue its replacement", _keys_rotate)
248
+ rotate.add_argument("key_id")
249
+ rotate.add_argument("--expires-at", metavar="ISO", help="when the new key expires")
250
+
251
+ jobs = _group(commands, "jobs", "a project's jobs")
252
+ jobs_list = _command(
253
+ jobs,
254
+ "list",
255
+ "list a project's jobs, newest first",
256
+ _jobs_list,
257
+ table=JOB_COLUMNS,
258
+ rows="jobs",
259
+ )
260
+ jobs_list.add_argument("project", help="the project's id")
261
+ jobs_list.add_argument("--thread", help="only this thread's jobs")
262
+ jobs_list.add_argument("--after", metavar="JOB_ID", help="the page after this job")
263
+ jobs_list.add_argument("--limit", type=int, help="how many to list")
264
+
265
+ _command(commands, "whoami", "the tenant and key you authenticate as", _whoami)
266
+
267
+ upload = _command(commands, "upload", "upload a file and start processing it", _upload)
268
+ upload.add_argument("subject", help="the subject the media is about")
269
+ upload.add_argument("path", help="the file to upload")
270
+ upload.add_argument(
271
+ "--stream-id", help="the stream to put it on (default: from the file name and content)"
272
+ )
273
+ upload.add_argument("--no-process", action="store_true", help="upload only; do not process")
274
+
275
+ admin = _group(commands, "admin", "the operator's commands (PERCEPTION_ADMIN_TOKEN)")
276
+ tenants = _group(admin, "tenants", "tenants")
277
+ _command(
278
+ tenants,
279
+ "list",
280
+ "list the tenants",
281
+ _tenants_list,
282
+ admin=True,
283
+ table=TENANT_COLUMNS,
284
+ rows="tenants",
285
+ )
286
+ tenant_create = _command(tenants, "create", "create a tenant", _tenants_create, admin=True)
287
+ tenant_create.add_argument("tenant")
288
+
289
+ subjects = _group(admin, "subjects", "subjects")
290
+ subject_create = _command(
291
+ subjects, "create", "create a subject in a tenant", _subjects_create, admin=True
292
+ )
293
+ subject_create.add_argument("tenant")
294
+ subject_create.add_argument("subject")
295
+
296
+ tenant_keys = _group(admin, "keys", "any tenant's API keys")
297
+ listing = _command(
298
+ tenant_keys,
299
+ "list",
300
+ "list a tenant's keys",
301
+ _admin_keys_list,
302
+ admin=True,
303
+ table=KEY_COLUMNS,
304
+ rows="keys",
305
+ )
306
+ listing.add_argument("tenant")
307
+ issue = _command(
308
+ tenant_keys, "issue", "issue a key and print it, this once", _admin_keys_issue, admin=True
309
+ )
310
+ issue.add_argument("tenant")
311
+ _issue_options(issue)
312
+ admin_revoke = _command(tenant_keys, "revoke", "revoke a key", _admin_keys_revoke, admin=True)
313
+ admin_revoke.add_argument("tenant")
314
+ admin_revoke.add_argument("key_id")
315
+ admin_rotate = _command(
316
+ tenant_keys,
317
+ "rotate",
318
+ "revoke a key and issue its replacement",
319
+ _admin_keys_rotate,
320
+ admin=True,
321
+ )
322
+ admin_rotate.add_argument("tenant")
323
+ admin_rotate.add_argument("key_id")
324
+ admin_rotate.add_argument("--expires-at", metavar="ISO", help="when the new key expires")
325
+ return parser
326
+
327
+
328
+ def _group(
329
+ commands: argparse._SubParsersAction, name: str, help: str
330
+ ) -> argparse._SubParsersAction:
331
+ parser = commands.add_parser(name, help=help, description=help)
332
+ return parser.add_subparsers(dest=f"{name}_command", required=True, metavar="COMMAND")
333
+
334
+
335
+ def _command(
336
+ commands: argparse._SubParsersAction,
337
+ name: str,
338
+ help: str,
339
+ run: Run,
340
+ *,
341
+ admin: bool = False,
342
+ table: Sequence[str] | None = None,
343
+ rows: str | None = None,
344
+ ) -> argparse.ArgumentParser:
345
+ """A command. A list command names its `table` columns and the field of the answer its `rows`
346
+ are in."""
347
+ parser = commands.add_parser(name, help=help, description=help)
348
+ parser.set_defaults(run=run, admin=admin, columns=table, rows=rows)
349
+ if table is not None:
350
+ parser.add_argument("--table", action="store_true", help="print a table, not JSON")
351
+ return parser
352
+
353
+
354
+ def _issue_options(parser: argparse.ArgumentParser, *, name_required: bool = False) -> None:
355
+ parser.add_argument("--name", required=name_required, help="a name to tell the key by")
356
+ parser.add_argument(
357
+ "--expires-at", metavar="ISO", help="when it expires, such as 2027-06-30T00:00:00+00:00"
358
+ )