cloudsprite 0.11.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.
Files changed (70) hide show
  1. cloudsprite/__init__.py +451 -0
  2. cloudsprite/_antenna.py +83 -0
  3. cloudsprite/_auth.py +295 -0
  4. cloudsprite/_client.py +502 -0
  5. cloudsprite/_config.py +203 -0
  6. cloudsprite/_consent.py +104 -0
  7. cloudsprite/_context.py +945 -0
  8. cloudsprite/_exceptions.py +136 -0
  9. cloudsprite/_figure_models.py +158 -0
  10. cloudsprite/_figure_validation.py +168 -0
  11. cloudsprite/_filter_foster.py +165 -0
  12. cloudsprite/_filter_synthesis.py +400 -0
  13. cloudsprite/_filtering.py +134 -0
  14. cloudsprite/_impedance_matching.py +262 -0
  15. cloudsprite/_interpolation.py +47 -0
  16. cloudsprite/_lineage.py +775 -0
  17. cloudsprite/_link_budget.py +99 -0
  18. cloudsprite/_logging.py +53 -0
  19. cloudsprite/_mixed_mode.py +49 -0
  20. cloudsprite/_monte_carlo.py +193 -0
  21. cloudsprite/_noise_figure.py +44 -0
  22. cloudsprite/_pagination.py +130 -0
  23. cloudsprite/_parsers.py +75 -0
  24. cloudsprite/_publish.py +162 -0
  25. cloudsprite/_redact.py +179 -0
  26. cloudsprite/_response.py +63 -0
  27. cloudsprite/_resultset.py +65 -0
  28. cloudsprite/_rf_network.py +111 -0
  29. cloudsprite/_run_config.py +46 -0
  30. cloudsprite/_script_runner.py +217 -0
  31. cloudsprite/_script_workspace.py +271 -0
  32. cloudsprite/_sparameter_metrics.py +75 -0
  33. cloudsprite/_tdr.py +283 -0
  34. cloudsprite/_trace.py +112 -0
  35. cloudsprite/_version.py +23 -0
  36. cloudsprite/_visualizer.py +380 -0
  37. cloudsprite/_visualizer_cli.py +412 -0
  38. cloudsprite/_visualizer_preview.py +864 -0
  39. cloudsprite/_work_context.py +116 -0
  40. cloudsprite/_ws.py +577 -0
  41. cloudsprite/cli.py +300 -0
  42. cloudsprite/py.typed +0 -0
  43. cloudsprite/resources/__init__.py +1 -0
  44. cloudsprite/resources/_base.py +293 -0
  45. cloudsprite/resources/_models.py +50 -0
  46. cloudsprite/resources/cloudscripts.py +173 -0
  47. cloudsprite/resources/datasets.py +431 -0
  48. cloudsprite/resources/figures.py +282 -0
  49. cloudsprite/resources/instruments.py +295 -0
  50. cloudsprite/resources/notebooks.py +183 -0
  51. cloudsprite/resources/orbs.py +99 -0
  52. cloudsprite/resources/parameters.py +77 -0
  53. cloudsprite/resources/projects.py +182 -0
  54. cloudsprite/resources/related.py +125 -0
  55. cloudsprite/resources/reports.py +992 -0
  56. cloudsprite/resources/search.py +245 -0
  57. cloudsprite/resources/shares.py +229 -0
  58. cloudsprite/resources/sprites.py +15 -0
  59. cloudsprite/resources/tags.py +107 -0
  60. cloudsprite/resources/teams.py +86 -0
  61. cloudsprite/resources/traces.py +147 -0
  62. cloudsprite/resources/usage.py +152 -0
  63. cloudsprite/resources/visualizer_templates.py +466 -0
  64. cloudsprite/resources/workflows.py +59 -0
  65. cloudsprite-0.11.0.dist-info/METADATA +358 -0
  66. cloudsprite-0.11.0.dist-info/RECORD +70 -0
  67. cloudsprite-0.11.0.dist-info/WHEEL +5 -0
  68. cloudsprite-0.11.0.dist-info/entry_points.txt +3 -0
  69. cloudsprite-0.11.0.dist-info/licenses/LICENSE +21 -0
  70. cloudsprite-0.11.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,173 @@
1
+ """CloudScript and cloudscript-version resources (beta).
2
+
3
+ Engineer-facing automation: list/create CloudScripts, upload versions, archive, run.
4
+ A CloudScript is an ordinary Python file that runs in CloudSprite; the REST paths
5
+ stay ``/api/scripts/``. Not part of the frozen 1.0 contract.
6
+ ``cloudsprite.resources.sprites`` is the legacy module alias.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from pathlib import Path
12
+ from typing import Any
13
+ from urllib.parse import parse_qs, urlparse
14
+
15
+ from cloudsprite._exceptions import ValidationError
16
+ from cloudsprite.resources._base import Resource, ResourceCollection
17
+
18
+
19
+ def _project_id_from_collection_path(path: str) -> str:
20
+ query = urlparse(path).query or (path.split("?", 1)[1] if "?" in path else "")
21
+ values = parse_qs(query).get("project_id") or []
22
+ if not values or not values[0]:
23
+ raise ValidationError("CloudScript collection is missing project_id")
24
+ return values[0]
25
+
26
+
27
+ def _cloudscript_from_upload(client: Any, payload: Any) -> CloudScript:
28
+ if not isinstance(payload, dict):
29
+ raise ValidationError("Unexpected CloudScript upload response")
30
+ data = payload.get("script") if "script" in payload else payload
31
+ if not isinstance(data, dict):
32
+ raise ValidationError("Unexpected script upload response")
33
+ return CloudScript(client, data)
34
+
35
+
36
+ def _version_from_upload(client: Any, payload: Any) -> CloudScriptVersion:
37
+ if not isinstance(payload, dict):
38
+ raise ValidationError("Unexpected script upload response")
39
+ data = payload.get("version")
40
+ if not isinstance(data, dict):
41
+ raise ValidationError("Unexpected script upload response")
42
+ return CloudScriptVersion(client, data)
43
+
44
+
45
+ class CloudScriptVersion(Resource):
46
+ """An immutable version of a stored CloudScript (beta)."""
47
+
48
+ @property
49
+ def version(self) -> int:
50
+ """Monotonic version number (1-based)."""
51
+ raw = self._data.get("version", 0)
52
+ return int(raw) if raw is not None else 0
53
+
54
+ @property
55
+ def content_hash(self) -> str:
56
+ """Content hash of the stored file."""
57
+ return str(self._data.get("content_hash", ""))
58
+
59
+ def content_url(self) -> str:
60
+ """Presigned GET URL for this version's source.
61
+
62
+ Server: ``GET /api/script-versions/{id}/content/``.
63
+ """
64
+ payload = self._client.get(f"/api/script-versions/{self.id}/content/")
65
+ if not isinstance(payload, dict) or not payload.get("url"):
66
+ raise ValidationError("CloudScript version content URL missing from response")
67
+ return str(payload["url"])
68
+
69
+
70
+ class CloudScript(Resource):
71
+ """A project-scoped CloudScript — a Python file CloudSprite can run (beta).
72
+
73
+ Example::
74
+
75
+ script = project.cloudscripts.create("sweep.py", description="nightly sweep")
76
+ script.upload_version("sweep.py", message="fix timeout")
77
+ run = script.run()
78
+ """
79
+
80
+ @property
81
+ def project_id(self) -> str:
82
+ """Owning project UUID."""
83
+ return str(self._data.get("project_id", ""))
84
+
85
+ @property
86
+ def is_archived(self) -> bool:
87
+ """True when the CloudScript has been soft-archived."""
88
+ return bool(self._data.get("archived", False))
89
+
90
+ @property
91
+ def versions(self) -> list[CloudScriptVersion]:
92
+ """Versions on this CloudScript (fetched from detail).
93
+
94
+ Server: ``GET /api/scripts/{id}/``.
95
+ """
96
+ payload = self._client.get(f"/api/scripts/{self.id}/")
97
+ raw = payload.get("versions", []) if isinstance(payload, dict) else []
98
+ return [CloudScriptVersion(self._client, item) for item in raw if isinstance(item, dict)]
99
+
100
+ def upload_version(self, file_path: str, *, message: str = "") -> CloudScriptVersion:
101
+ """Upload a new version from a local file (multipart).
102
+
103
+ Server: ``POST /api/scripts/{id}/versions/``.
104
+ """
105
+ path = Path(file_path)
106
+ payload = self._client.post_file(
107
+ f"/api/scripts/{self.id}/versions/",
108
+ path.name,
109
+ path.read_bytes(),
110
+ extra_fields={"message": message},
111
+ )
112
+ version = _version_from_upload(self._client, payload)
113
+ if isinstance(payload, dict) and isinstance(payload.get("script"), dict):
114
+ self._data.update(payload["script"])
115
+ return version
116
+
117
+ def archive(self) -> None:
118
+ """Soft-archive this CloudScript.
119
+
120
+ Server: ``DELETE /api/scripts/{id}/``.
121
+ """
122
+ self._client.delete(f"/api/scripts/{self.id}/")
123
+ self._data["archived"] = True
124
+
125
+ def run(
126
+ self,
127
+ *,
128
+ version_id: str | None = None,
129
+ config: dict[str, Any] | None = None,
130
+ input_dataset_ids: list[str] | None = None,
131
+ ) -> dict[str, Any]:
132
+ """Queue a server-side run (HTTP 202).
133
+
134
+ Server: ``POST /api/scripts/{id}/run/``.
135
+ """
136
+ body: dict[str, Any] = {
137
+ "config": config or {},
138
+ "input_dataset_ids": input_dataset_ids or [],
139
+ }
140
+ if version_id is not None:
141
+ body["version_id"] = version_id
142
+ payload = self._client.post(f"/api/scripts/{self.id}/run/", json=body)
143
+ return payload if isinstance(payload, dict) else {}
144
+
145
+
146
+ class CloudScriptCollection(ResourceCollection[CloudScript]):
147
+ """Project-scoped CloudScripts. ``create`` is multipart, not JSON."""
148
+
149
+ def create(self, **kwargs: Any) -> CloudScript:
150
+ """Create a CloudScript + version 1 from a local file.
151
+
152
+ Required kwarg: ``file_path``. Optional: ``name``, ``description``,
153
+ ``message``. Server: ``POST /api/scripts/`` (multipart).
154
+ """
155
+ file_path = kwargs.get("file_path")
156
+ if not isinstance(file_path, str) or not file_path:
157
+ raise ValidationError("cloudscripts.create() requires file_path='...'")
158
+ path = Path(file_path)
159
+ project_id = _project_id_from_collection_path(self._path)
160
+ name = kwargs.get("name")
161
+ payload = self._client.post_file(
162
+ "/api/scripts/",
163
+ path.name,
164
+ path.read_bytes(),
165
+ extra_fields={
166
+ "project_id": project_id,
167
+ "name": name if isinstance(name, str) and name else path.stem,
168
+ "description": str(kwargs.get("description") or ""),
169
+ "message": str(kwargs.get("message") or ""),
170
+ },
171
+ )
172
+ self._items = None
173
+ return _cloudscript_from_upload(self._client, payload)
@@ -0,0 +1,431 @@
1
+ """Dataset resource — the primary data container in CloudSprite.
2
+
3
+ Datasets hold datafiles (traces, screenshots, raw files), parameter values,
4
+ tags, and notes. They belong to a project and can be referenced by notebooks.
5
+
6
+ Example:
7
+ >>> ds = project.create_dataset("Sweep 25C", description="Room temp VNA sweep")
8
+ >>> ds.upload("sweep.s2p")
9
+ >>> ds.set_param("Temperature", "25")
10
+ >>> ds.add_tag(cs.tags.create("PASS").id)
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from typing import TYPE_CHECKING, Any, cast
16
+
17
+ from cloudsprite._exceptions import ValidationError, validate_id
18
+ from cloudsprite._resultset import ResultSet
19
+ from cloudsprite.resources._base import Resource, ResourceCollection
20
+ from cloudsprite.resources.related import MAX_RELATED_LIMIT, RELATED_SCOPES, RELATED_SIGNALS, RelatedDatasets
21
+ from cloudsprite.resources.usage import DatasetUsage
22
+
23
+ if TYPE_CHECKING:
24
+ from cloudsprite.resources.tags import Tag
25
+ from cloudsprite.resources.traces import TraceRef
26
+
27
+
28
+ def apply_sdk_dataset_source(payload: dict[str, Any]) -> dict[str, Any]:
29
+ """Stamp source_type/source_metadata on SDK-created datasets.
30
+
31
+ Backend accepts source_type in {upload, sdk, api} and stores arbitrary JSON
32
+ in source_metadata. Every SDK create path should call this so datasets are
33
+ distinguishable from generic API-key creates (which default to source_type=api).
34
+ """
35
+ from cloudsprite._version import sdk_version as _resolve_sdk_version
36
+
37
+ sdk_version = _resolve_sdk_version()
38
+
39
+ out = dict(payload)
40
+ out["source_type"] = "sdk"
41
+ meta = dict(out.get("source_metadata") or {})
42
+ meta["sdk_version"] = sdk_version
43
+ out["source_metadata"] = meta
44
+ return out
45
+
46
+
47
+ class Dataset(Resource):
48
+ """A dataset containing traces, parameters, tags, and notes.
49
+
50
+ Attributes:
51
+ id: Unique identifier (UUID).
52
+ name: Display title.
53
+ slug: URL-safe identifier (unique within project).
54
+ description: Optional description text.
55
+ params: Parameter key-value pairs as a dict.
56
+ """
57
+
58
+ # Deliberately no _CREATE_DEFAULTS. DatasetCreateSchema accepts only title,
59
+ # description, project_id, parameters and source_type, so visibility was
60
+ # dead payload: Ninja drops the unknown field and the model already defaults
61
+ # it to "team". It also disagreed with Project.create_dataset(), which posts
62
+ # to the same endpoint without it.
63
+
64
+ @property
65
+ def slug(self) -> str:
66
+ """URL-safe identifier, unique within the parent project."""
67
+ return str(self._data.get("slug", ""))
68
+
69
+ @property
70
+ def description(self) -> str:
71
+ """Free-text description, or empty string if unset."""
72
+ return str(self._data.get("description", ""))
73
+
74
+ @property
75
+ def params(self) -> dict[str, Any]:
76
+ """Parameter values as a {key: value} dict."""
77
+ raw = self._data.get("parameters", [])
78
+ if isinstance(raw, list):
79
+ result: dict[str, Any] = {}
80
+ for p in raw:
81
+ if not isinstance(p, dict):
82
+ continue
83
+ key = p.get("parameter_key_title") or p.get("key")
84
+ if key is not None:
85
+ result[str(key)] = p.get("value")
86
+ return result
87
+ return raw if isinstance(raw, dict) else {}
88
+
89
+ @property
90
+ def traces(self) -> ResourceCollection[TraceRef]:
91
+ """Access traces (datafiles) in this dataset.
92
+
93
+ Returns a ResourceCollection supporting bracket notation and iteration.
94
+
95
+ Example:
96
+ >>> ds.traces["S21"] # exact match
97
+ >>> ds.traces["S*"] # glob
98
+ >>> for t in ds.traces: ... # iterate all
99
+ """
100
+ from cloudsprite.resources.traces import TraceRef
101
+
102
+ return ResourceCollection(
103
+ self._client,
104
+ f"/api/datasets/{self.id}/datafiles/",
105
+ TraceRef,
106
+ name_field="name", # DataFileSchema.name
107
+ )
108
+
109
+ # --- Write operations ---
110
+
111
+ def set_preferred_figure(self, figure_id: str) -> Dataset:
112
+ """Select an attached valid figure as this dataset's view (dataset:update)."""
113
+ figure_id = validate_id(figure_id, "figure_id")
114
+ data = self._client.put(f"/api/datasets/{self.id}/preferred-figure", json={"figure_id": figure_id})
115
+ if isinstance(data, dict):
116
+ self._data.update(data)
117
+ return self
118
+
119
+ def clear_preferred_figure(self) -> Dataset:
120
+ """Clear the preferred figure to restore the normal graph (dataset:update)."""
121
+ data = self._client.delete(f"/api/datasets/{self.id}/preferred-figure")
122
+ if isinstance(data, dict):
123
+ self._data.update(data)
124
+ return self
125
+
126
+ def update(self, **kwargs: Any) -> None:
127
+ """Update dataset fields.
128
+
129
+ Args:
130
+ **kwargs: Fields to update (title, description).
131
+
132
+ Example:
133
+ >>> ds.update(title="Sweep 25C — Final", description="Corrected data")
134
+ """
135
+ data = self._client.patch(f"/api/datasets/{self.id}", json=kwargs)
136
+ if isinstance(data, dict):
137
+ self._data.update(data)
138
+
139
+ def trash(self) -> None:
140
+ """Move dataset to trash (soft delete). Can be restored later.
141
+
142
+ Server: ``DELETE /api/datasets/{id}`` (soft-delete; not POST /trash).
143
+ """
144
+ self._client.delete(f"/api/datasets/{self.id}")
145
+
146
+ def restore(self) -> None:
147
+ """Restore dataset from trash.
148
+
149
+ Server: ``POST /api/datasets/{id}/restore``.
150
+ """
151
+ self._client.post(f"/api/datasets/{self.id}/restore")
152
+
153
+ def delete(self) -> None:
154
+ """Permanently delete dataset. This cannot be undone.
155
+
156
+ Server: ``DELETE /api/datasets/{id}/permanent-delete``.
157
+ """
158
+ self._client.delete(f"/api/datasets/{self.id}/permanent-delete")
159
+
160
+ # --- File upload ---
161
+
162
+ def upload(self, file_path: str) -> dict[str, Any]:
163
+ """Upload a file from disk to this dataset.
164
+
165
+ Accepts any file type — CSV, S2P, S1P, PNG, etc. The backend
166
+ auto-detects the file type and creates appropriate traces.
167
+
168
+ Args:
169
+ file_path: Path to the file on disk.
170
+
171
+ Returns:
172
+ DataFile metadata dict from the backend.
173
+
174
+ Example:
175
+ >>> ds.upload("data/sweep_25c.s2p")
176
+ >>> ds.upload("screenshots/scope_capture.png")
177
+ """
178
+ return cast(
179
+ dict[str, Any],
180
+ self._client.upload_file(
181
+ f"/api/datasets/{self.id}/datafiles/",
182
+ file_path=file_path,
183
+ ),
184
+ )
185
+
186
+ def upload_bytes(self, data: bytes, filename: str) -> dict[str, Any]:
187
+ """Upload file content from memory.
188
+
189
+ Args:
190
+ data: Raw file bytes.
191
+ filename: Name for the uploaded file (used for type detection).
192
+
193
+ Returns:
194
+ DataFile metadata dict from the backend.
195
+
196
+ Example:
197
+ >>> csv_data = b"freq,s21\\n1e9,-0.5\\n2e9,-0.8"
198
+ >>> ds.upload_bytes(csv_data, "measurement.csv")
199
+ """
200
+ if not filename:
201
+ raise ValidationError("filename must not be empty")
202
+ return cast(
203
+ dict[str, Any],
204
+ self._client.post_file(
205
+ f"/api/datasets/{self.id}/datafiles/",
206
+ file_name=filename,
207
+ file_data=data,
208
+ ),
209
+ )
210
+
211
+ def upload_large(self, file_path: str, chunk_size: int = 50 * 1024 * 1024) -> dict[str, Any]:
212
+ """Upload a large file using chunked multipart upload.
213
+
214
+ For files >50MB that exceed single-request upload limits.
215
+ Automatically falls back to regular upload for small files.
216
+
217
+ Args:
218
+ file_path: Path to the file on disk.
219
+ chunk_size: Size of each chunk in bytes (default: 50MB).
220
+
221
+ Returns:
222
+ DataFile metadata dict from the backend.
223
+
224
+ Example:
225
+ >>> ds.upload_large("large_capture.csv") # 200MB file
226
+ """
227
+ return cast(
228
+ dict[str, Any],
229
+ self._client.upload_multipart(
230
+ f"/api/datasets/{self.id}/datafiles/",
231
+ file_path=file_path,
232
+ chunk_size=chunk_size,
233
+ ),
234
+ )
235
+
236
+ def upload_screenshot(self, file_path: str) -> dict[str, Any]:
237
+ """Upload an image as the dataset's screenshot/thumbnail.
238
+
239
+ Args:
240
+ file_path: Path to PNG or JPEG image file.
241
+
242
+ Returns:
243
+ ImageFile metadata dict from the backend.
244
+ """
245
+ return cast(
246
+ dict[str, Any],
247
+ self._client.upload_file(
248
+ f"/api/datasets/{self.id}/datafiles/imagefile/",
249
+ file_path=file_path,
250
+ ),
251
+ )
252
+
253
+ # --- Parameters ---
254
+
255
+ def set_param(self, key: str, value: str) -> dict[str, Any]:
256
+ """Set a parameter value on this dataset.
257
+
258
+ Creates the parameter key in the system if it doesn't exist yet.
259
+ If the parameter already has a value, this creates an additional one
260
+ (use delete_param to remove existing values first).
261
+
262
+ Args:
263
+ key: Parameter key name (e.g. "Temperature", "DUT", "Operator").
264
+ value: Parameter value as a string.
265
+
266
+ Returns:
267
+ Created ParameterValue metadata.
268
+
269
+ Example:
270
+ >>> ds.set_param("Temperature", "25")
271
+ >>> ds.set_param("Cable Length", "1.5m")
272
+ """
273
+ if not key:
274
+ raise ValidationError("Parameter key must not be empty")
275
+ return cast(
276
+ dict[str, Any],
277
+ self._client.post(
278
+ f"/api/datasets/{self.id}/parameters/",
279
+ json={"parameter_key_title": key, "value": value},
280
+ ),
281
+ )
282
+
283
+ def delete_param(self, param_value_id: str) -> None:
284
+ """Delete a parameter value by its ID.
285
+
286
+ Args:
287
+ param_value_id: UUID of the parameter value to remove.
288
+ """
289
+ validate_id(param_value_id, "param_value_id")
290
+ self._client.delete(f"/api/datasets/{self.id}/parameters/{param_value_id}/")
291
+
292
+ # --- Tags ---
293
+
294
+ @property
295
+ def tags(self) -> ResultSet[Tag]:
296
+ """Tags already attached to this dataset, from the dataset payload.
297
+
298
+ No extra request: the dataset payload carries its tags. Reflects the
299
+ state when this object was fetched; re-fetch the dataset to see later
300
+ :meth:`add_tag` / :meth:`remove_tag` changes. Look tags up by name with
301
+ ``cs.tags``.
302
+
303
+ Example:
304
+ >>> [t.name for t in ds.tags]
305
+ """
306
+ from cloudsprite.resources.tags import Tag
307
+
308
+ raw = self._data.get("tags") or [] # the API sends null for an untagged dataset
309
+ items = [Tag(self._client, data=t) for t in raw if isinstance(t, dict) and t.get("id")]
310
+ return ResultSet(items)
311
+
312
+ def add_tag(self, tag_id: str) -> dict[str, Any]:
313
+ """Attach an existing tag to this dataset.
314
+
315
+ Takes a **tag id**, not a name: the server route is
316
+ ``POST /api/tags/datasets/{dataset_id}/add/{tag_id}``, which associates
317
+ an existing tag. This is symmetric with :meth:`remove_tag`.
318
+
319
+ The previous signature took a name and claimed to create the tag if
320
+ absent, but posted to ``/api/datasets/{id}/tags/`` — a route that does
321
+ not exist, so it always failed. Creating-on-demand would need a separate
322
+ lookup plus ``POST /api/tags/``, which would make a typo silently mint a
323
+ junk tag; that is left to the caller.
324
+
325
+ Args:
326
+ tag_id: UUID of an existing tag.
327
+
328
+ Returns:
329
+ Association metadata dict.
330
+
331
+ Example:
332
+ >>> ds.add_tag(tag.id)
333
+ """
334
+ validate_id(tag_id, "tag_id")
335
+ return cast(
336
+ dict[str, Any],
337
+ self._client.post(f"/api/tags/datasets/{self.id}/add/{tag_id}"),
338
+ )
339
+
340
+ def remove_tag(self, tag_id: str) -> None:
341
+ """Remove a tag from this dataset.
342
+
343
+ Args:
344
+ tag_id: UUID of the tag to remove.
345
+ """
346
+ validate_id(tag_id, "tag_id")
347
+ # Tag association lives on the tags router, not under /datasets/:
348
+ # DELETE /api/tags/datasets/{dataset_id}/remove/{tag_id}. The old path
349
+ # (/api/datasets/{id}/tags/{tag_id}) does not exist and 404s.
350
+ self._client.delete(f"/api/tags/datasets/{self.id}/remove/{tag_id}")
351
+
352
+ # --- Usage and related datasets ---
353
+
354
+ def usage(self, *, depth: int = 1) -> DatasetUsage:
355
+ """What uses this dataset, what was derived from it and what it was derived from.
356
+
357
+ ``depth`` (1-3) is the number of lineage hops for ``derived`` / ``derived_from``. Objects you cannot
358
+ read are counted in each group's ``hidden_count`` and never named. ``viewers`` is filled only when you
359
+ have ``dataset:update`` or are a team admin (see ``viewers_visible``).
360
+
361
+ Server: ``GET /api/datasets/{id}/usage/``.
362
+
363
+ Example:
364
+ >>> usage = ds.usage()
365
+ >>> usage.counts["reports"], [n.name for n in usage.notebooks]
366
+ """
367
+ if isinstance(depth, bool) or not isinstance(depth, int) or not 1 <= depth <= 3:
368
+ raise ValidationError("depth must be an integer from 1 to 3")
369
+ data = self._client.get(f"/api/datasets/{self.id}/usage/", params={"depth": depth})
370
+ if not isinstance(data, dict):
371
+ raise ValidationError("Unexpected dataset usage response")
372
+ return DatasetUsage.from_api(data)
373
+
374
+ def related(
375
+ self,
376
+ *,
377
+ limit: int = 10,
378
+ signals: list[str] | tuple[str, ...] | None = None,
379
+ scope: str = "project",
380
+ ) -> RelatedDatasets:
381
+ """Datasets related to this one, ranked, each with the reasons it was chosen.
382
+
383
+ ``limit`` is 1-50. ``signals`` narrows the evidence used (``lineage``, ``capture_context``,
384
+ ``dut_setup``, ``co_membership``, ``parameters``, ``content``, ``tag``); default all. ``scope`` is where
385
+ candidates may come from: ``"project"`` (default), ``"team"`` or ``"organization"``. Only datasets you can
386
+ read are returned.
387
+
388
+ Server: ``GET /api/datasets/{id}/related/``.
389
+
390
+ Example:
391
+ >>> for item in ds.related(limit=5, scope="team"):
392
+ ... print(item.dataset.title, item.reasons[0].text)
393
+ """
394
+ if isinstance(limit, bool) or not isinstance(limit, int) or not 1 <= limit <= MAX_RELATED_LIMIT:
395
+ raise ValidationError(f"limit must be an integer from 1 to {MAX_RELATED_LIMIT}")
396
+ if scope not in RELATED_SCOPES:
397
+ raise ValidationError(f"scope must be one of {', '.join(RELATED_SCOPES)}")
398
+ params: dict[str, Any] = {"limit": limit, "scope": scope}
399
+ if signals:
400
+ unknown = [s for s in signals if s not in RELATED_SIGNALS]
401
+ if unknown:
402
+ raise ValidationError(f"Unknown signal(s): {', '.join(unknown)}. Valid: {', '.join(RELATED_SIGNALS)}")
403
+ params["signals"] = list(signals)
404
+ data = self._client.get(f"/api/datasets/{self.id}/related/", params=params)
405
+ if not isinstance(data, dict):
406
+ raise ValidationError("Unexpected related datasets response")
407
+ return RelatedDatasets.from_api(data)
408
+
409
+ # --- Notes ---
410
+
411
+ def add_note(self, content: str) -> dict[str, Any]:
412
+ """Add a text note to this dataset.
413
+
414
+ Args:
415
+ content: Note text content (supports markdown).
416
+
417
+ Returns:
418
+ Note metadata dict.
419
+
420
+ Example:
421
+ >>> ds.add_note("Anomaly detected at 2.4 GHz — possible connector issue")
422
+ """
423
+ if not content:
424
+ raise ValidationError("Note content must not be empty")
425
+ return cast(
426
+ dict[str, Any],
427
+ self._client.post(
428
+ f"/api/datasets/{self.id}/notes/",
429
+ json={"content": content},
430
+ ),
431
+ )