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,183 @@
1
+ """Notebook resource."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any, cast
6
+
7
+ from cloudsprite._exceptions import validate_id
8
+ from cloudsprite._resultset import ResultSet
9
+ from cloudsprite.resources._base import Resource
10
+
11
+ if TYPE_CHECKING:
12
+ from cloudsprite.resources.datasets import Dataset
13
+ from cloudsprite.resources.traces import TraceRef
14
+
15
+
16
+ class Notebook(Resource):
17
+ """A notebook that groups datasets, traces, equations, and notes."""
18
+
19
+ @property
20
+ def datasets(self) -> ResultSet[Dataset]:
21
+ """Datasets linked to this notebook.
22
+
23
+ Sourced from ``GET /api/notebooks/{id}/bootstrap``, which embeds the
24
+ linked datasets. There is no ``/api/notebooks/{id}/datasets`` route and
25
+ ``GET /api/datasets/`` does not accept a ``notebook_id`` filter, so this
26
+ cannot be a lazily-paginated collection — the association is only
27
+ exposed inline. Returns a :class:`~cloudsprite._resultset.ResultSet` so
28
+ it still supports ``first()`` / ``count()`` / ``to_dataframe()``.
29
+ """
30
+ from cloudsprite.resources.datasets import Dataset
31
+
32
+ payload = self._client.get(f"/api/notebooks/{self.id}/bootstrap")
33
+ raw = payload.get("datasets", []) if isinstance(payload, dict) else []
34
+ items = [Dataset(self._client, data=d) for d in raw if isinstance(d, dict)]
35
+ return ResultSet(items)
36
+
37
+ @property
38
+ def traces(self) -> ResultSet[TraceRef]:
39
+ """Fan-out: all traces across all datasets referenced by this notebook."""
40
+ all_traces: list[TraceRef] = []
41
+ for ds in self.datasets:
42
+ for trace in ds.traces:
43
+ all_traces.append(trace)
44
+ return ResultSet(all_traces)
45
+
46
+ # --- Write operations ---
47
+
48
+ def set_preferred_figure(self, figure_id: str) -> Notebook:
49
+ """Select an attached valid figure as this notebook's view (notebook:update)."""
50
+ figure_id = validate_id(figure_id, "figure_id")
51
+ data = self._client.put(f"/api/notebooks/{self.id}/preferred-figure", json={"figure_id": figure_id})
52
+ if isinstance(data, dict):
53
+ self._data.update(data)
54
+ return self
55
+
56
+ def clear_preferred_figure(self) -> Notebook:
57
+ """Clear the preferred figure to restore the normal graph (notebook:update)."""
58
+ data = self._client.delete(f"/api/notebooks/{self.id}/preferred-figure")
59
+ if isinstance(data, dict):
60
+ self._data.update(data)
61
+ return self
62
+
63
+ def update(self, **kwargs: Any) -> None:
64
+ """Update notebook fields (title, description)."""
65
+ data = self._client.patch(f"/api/notebooks/{self.id}", json=kwargs)
66
+ if isinstance(data, dict):
67
+ self._data.update(data)
68
+
69
+ def trash(self) -> None:
70
+ """Move notebook to trash (soft delete). Can be restored later.
71
+
72
+ Server: ``DELETE /api/notebooks/{id}`` (soft-delete). There is no
73
+ ``POST /trash`` route for notebooks — that path was an SDK bug.
74
+ """
75
+ self._client.delete(f"/api/notebooks/{self.id}")
76
+
77
+ def restore(self) -> None:
78
+ """Restore notebook from trash.
79
+
80
+ Server: ``POST /api/notebooks/{id}/restore``.
81
+ """
82
+ self._client.post(f"/api/notebooks/{self.id}/restore")
83
+
84
+ def delete(self) -> None:
85
+ """Permanently delete a trashed notebook.
86
+
87
+ Server: ``DELETE /api/notebooks/{id}/permanent-delete``.
88
+ """
89
+ self._client.delete(f"/api/notebooks/{self.id}/permanent-delete")
90
+
91
+ # --- Traces ---
92
+
93
+ def add_traces(self, *datasets: Any) -> list[dict[str, Any]]:
94
+ """Add dataset traces to this notebook.
95
+
96
+ Accepts Dataset objects or dataset ID strings. All traces from
97
+ those datasets become part of this notebook's analysis.
98
+
99
+ Args:
100
+ *datasets: Dataset objects or dataset UUID strings.
101
+
102
+ Returns:
103
+ List of created NotebookTrace metadata dicts.
104
+
105
+ Example:
106
+ >>> nb.add_traces(ds1, ds2)
107
+ >>> nb.add_traces("9a20c280-0017-4c55-b449-97ab8d860a40")
108
+ """
109
+ from cloudsprite._exceptions import validate_id
110
+
111
+ results: list[dict[str, Any]] = []
112
+ for ds in datasets:
113
+ ds_id = ds.id if hasattr(ds, "id") else str(ds)
114
+ validate_id(ds_id, "dataset_id")
115
+ data = self._client.post(
116
+ f"/api/notebooks/{self.id}/traces/",
117
+ json={"dataset_id": ds_id},
118
+ )
119
+ results.append(cast(dict[str, Any], data))
120
+ return results
121
+
122
+ # --- Equations ---
123
+
124
+ def add_equation(self, name: str, expression: str, **kwargs: Any) -> dict[str, Any]:
125
+ """Add an equation to this notebook.
126
+
127
+ Args:
128
+ name: Display name for the equation
129
+ expression: Math expression (e.g. "S21_25C - S21_85C")
130
+ **kwargs: Additional fields (x_unit, y_unit, etc.)
131
+ """
132
+ return cast(
133
+ dict[str, Any],
134
+ self._client.post(
135
+ f"/api/notebooks/{self.id}/equations/",
136
+ json={"name": name, "expression": expression, **kwargs},
137
+ ),
138
+ )
139
+
140
+ # --- Measurements ---
141
+
142
+ def add_measurement(self, name: str, **kwargs: Any) -> dict[str, Any]:
143
+ """Add a measurement annotation to this notebook.
144
+
145
+ Args:
146
+ name: Measurement name (e.g. "Max Insertion Loss")
147
+ **kwargs: Additional fields (trace_id, operation, frequency, etc.)
148
+ """
149
+ return cast(
150
+ dict[str, Any],
151
+ self._client.post(
152
+ f"/api/notebooks/{self.id}/measurements/",
153
+ json={"name": name, **kwargs},
154
+ ),
155
+ )
156
+
157
+ # --- Notes ---
158
+
159
+ def add_note(self, content: str) -> dict[str, Any]:
160
+ """Add a note to this notebook."""
161
+ return cast(
162
+ dict[str, Any],
163
+ self._client.post(
164
+ f"/api/notebooks/{self.id}/notes/",
165
+ json={"content": content},
166
+ ),
167
+ )
168
+
169
+ # --- Export ---
170
+
171
+ def export(self, format: str = "pdf") -> dict[str, Any]:
172
+ """Export this notebook."""
173
+ return cast(
174
+ dict[str, Any],
175
+ self._client.post(
176
+ f"/api/notebooks/{self.id}/export",
177
+ json={"format": format},
178
+ ),
179
+ )
180
+
181
+ def snapshot(self) -> dict[str, Any]:
182
+ """Save a point-in-time snapshot of this notebook."""
183
+ return cast(dict[str, Any], self._client.post(f"/api/notebooks/{self.id}/snapshot", json={}))
@@ -0,0 +1,99 @@
1
+ """Orb resource — Raspberry Pi instrument controllers.
2
+
3
+ Orbs are physical devices that bridge lab instruments to the cloud platform.
4
+ Each orb connects to one or more instruments via VISA and communicates with
5
+ the backend via WebSocket.
6
+
7
+ Example:
8
+ >>> orb = cs.orbs["lab-orb-1"]
9
+ >>> print(orb.status) # "online"
10
+ >>> orb.reload_instruments()
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from typing import TYPE_CHECKING, Any, cast
16
+
17
+ from cloudsprite.resources._base import Resource, ResourceCollection
18
+
19
+ if TYPE_CHECKING:
20
+ from cloudsprite.resources.instruments import Instrument
21
+
22
+
23
+ class Orb(Resource):
24
+ """A Raspberry Pi orb device that controls instruments.
25
+
26
+ Attributes:
27
+ id: Unique identifier (UUID).
28
+ name: Display name.
29
+ serial_number: Hardware serial number.
30
+ status: Online status ('online', 'offline', 'unknown').
31
+ last_heartbeat: ISO timestamp of last heartbeat, or None.
32
+ connected_instruments: List of instrument connection info dicts.
33
+ """
34
+
35
+ @property
36
+ def serial_number(self) -> str:
37
+ """Hardware serial number."""
38
+ return str(self._data.get("serial_number", ""))
39
+
40
+ @property
41
+ def status(self) -> str:
42
+ """Online status: 'online', 'offline', or 'unknown'."""
43
+ return str(self._data.get("status", "unknown"))
44
+
45
+ @property
46
+ def last_heartbeat(self) -> str | None:
47
+ """ISO timestamp of the last heartbeat, or None if never seen."""
48
+ value = self._data.get("last_heartbeat")
49
+ return None if value is None else str(value)
50
+
51
+ @property
52
+ def connected_instruments(self) -> list[dict[str, Any]]:
53
+ """List of instrument connection status dicts."""
54
+ raw = self._data.get("connected_instruments", [])
55
+ return cast(list[dict[str, Any]], raw if isinstance(raw, list) else [])
56
+
57
+ @property
58
+ def instruments(self) -> ResourceCollection[Instrument]:
59
+ """Instruments associated with this orb.
60
+
61
+ Returns a ResourceCollection supporting bracket notation and iteration.
62
+
63
+ Example:
64
+ >>> for inst in orb.instruments:
65
+ ... print(inst.name, inst.status)
66
+ """
67
+ from cloudsprite.resources.instruments import Instrument
68
+
69
+ return ResourceCollection(
70
+ self._client,
71
+ f"/api/orbs/{self.id}/instruments/",
72
+ Instrument,
73
+ name_field="name",
74
+ )
75
+
76
+ def reload_instruments(self, timeout: float = 15.0) -> dict[str, Any]:
77
+ """Ask this orb to reload its instrument list from the backend.
78
+
79
+ Use after adding or removing instrument associations in the web UI.
80
+ The orb re-fetches its instrument list without requiring a restart.
81
+
82
+ Args:
83
+ timeout: Maximum seconds to wait for acknowledgment (default: 15).
84
+
85
+ Returns:
86
+ dict with keys:
87
+ - success (bool): Whether reload completed.
88
+ - instrument_count (int): Number of instruments now managed.
89
+
90
+ Example:
91
+ >>> result = orb.reload_instruments()
92
+ >>> print(f"Orb now manages {result['instrument_count']} instruments")
93
+ """
94
+ from cloudsprite._ws import reload_instruments
95
+
96
+ return reload_instruments(self._client, timeout=timeout)
97
+
98
+ def __repr__(self) -> str:
99
+ return f"Orb('{self.name}', serial='{self.serial_number}')"
@@ -0,0 +1,77 @@
1
+ """Parameter resources — keys, values, and templates."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, cast
6
+
7
+ from cloudsprite.resources._base import Resource
8
+
9
+
10
+ class Parameter:
11
+ """A parameter value on a dataset (not client-bound; no Resource base)."""
12
+
13
+ def __init__(self, data: dict[str, Any]):
14
+ self._data = data
15
+
16
+ @property
17
+ def id(self) -> str:
18
+ """Stable UUID of this parameter value, if present."""
19
+ return str(self._data.get("id", ""))
20
+
21
+ @property
22
+ def key(self) -> str:
23
+ """Parameter key title (human-readable name)."""
24
+ return str(self._data.get("parameter_key_title", self._data.get("key", "")))
25
+
26
+ @property
27
+ def value(self) -> str:
28
+ """Parameter value as a string."""
29
+ return str(self._data.get("value", ""))
30
+
31
+ def __repr__(self) -> str:
32
+ return f"Parameter('{self.key}={self.value}')"
33
+
34
+
35
+ class ParameterKey(Resource):
36
+ """A parameter key definition (reusable across datasets)."""
37
+
38
+ @property
39
+ def unit(self) -> str:
40
+ """Unit string for values of this key, or empty if unitless."""
41
+ return str(self._data.get("unit", ""))
42
+
43
+ def update(self, **kwargs: Any) -> None:
44
+ """Update parameter key fields."""
45
+ data = self._client.patch(f"/api/parameters/{self.id}", json=kwargs)
46
+ if isinstance(data, dict):
47
+ self._data.update(data)
48
+
49
+ def delete(self) -> None:
50
+ """Delete this parameter key.
51
+
52
+ Server: ``DELETE /api/parameters/{id}``.
53
+ """
54
+ self._client.delete(f"/api/parameters/{self.id}")
55
+
56
+
57
+ class ParameterTemplate(Resource):
58
+ """A parameter template (predefined set of keys for a workflow)."""
59
+
60
+ @property
61
+ def keys(self) -> list[dict[str, Any]]:
62
+ """Key definitions included in this template."""
63
+ raw = self._data.get("keys", [])
64
+ return cast(list[dict[str, Any]], raw if isinstance(raw, list) else [])
65
+
66
+ def update(self, **kwargs: Any) -> None:
67
+ """Update template fields."""
68
+ data = self._client.patch(f"/api/parameter-templates/{self.id}", json=kwargs)
69
+ if isinstance(data, dict):
70
+ self._data.update(data)
71
+
72
+ def delete(self) -> None:
73
+ """Delete this template.
74
+
75
+ Server: ``DELETE /api/parameter-templates/{id}``.
76
+ """
77
+ self._client.delete(f"/api/parameter-templates/{self.id}")
@@ -0,0 +1,182 @@
1
+ """Project resource — top-level organizer for datasets and notebooks.
2
+
3
+ Projects group related datasets and notebooks. They belong to a team
4
+ and have a unique slug within that team.
5
+
6
+ Example:
7
+ >>> project = cs.projects.create(title="Cable Qual Batch 7", prefix="CQ")
8
+ >>> ds = project.create_dataset("Sweep 25C")
9
+ >>> ds.upload("sweep.s2p")
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import TYPE_CHECKING, Any, cast
15
+
16
+ from cloudsprite._exceptions import validate_id
17
+ from cloudsprite.resources._base import Resource, ResourceCollection
18
+
19
+ if TYPE_CHECKING:
20
+ from cloudsprite.resources.cloudscripts import CloudScriptCollection
21
+ from cloudsprite.resources.datasets import Dataset
22
+ from cloudsprite.resources.notebooks import Notebook
23
+ from cloudsprite.resources.reports import ReportCollection
24
+ from cloudsprite.resources.workflows import Workflow
25
+
26
+
27
+ class Project(Resource):
28
+ """A project containing datasets and notebooks.
29
+
30
+ Attributes:
31
+ id: Unique identifier (UUID).
32
+ name: Display title.
33
+ slug: URL-safe identifier (unique within team).
34
+ """
35
+
36
+ # Injected by ResourceCollection.create() when the caller omits it.
37
+ # Load-bearing: ProjectCreateSchema declares visibility as required, so
38
+ # create(title=...) would be a 422 without this.
39
+ _CREATE_DEFAULTS = {"visibility": "team"}
40
+
41
+ @property
42
+ def slug(self) -> str:
43
+ """URL-safe project identifier within its team."""
44
+ return str(self._data.get("slug", ""))
45
+
46
+ @property
47
+ def datasets(self) -> ResourceCollection[Dataset]:
48
+ """Datasets belonging to this project."""
49
+ from cloudsprite.resources.datasets import Dataset
50
+
51
+ return ResourceCollection(
52
+ self._client,
53
+ f"/api/datasets/?project_id={self.id}&include_parameters=true",
54
+ Dataset,
55
+ name_field="title", # DatasetSchema uses title, not name
56
+ )
57
+
58
+ @property
59
+ def notebooks(self) -> ResourceCollection[Notebook]:
60
+ """Notebooks belonging to this project."""
61
+ from cloudsprite.resources.notebooks import Notebook
62
+
63
+ return ResourceCollection(
64
+ self._client,
65
+ f"/api/notebooks/?project_id={self.id}",
66
+ Notebook,
67
+ name_field="title", # NotebookSchema uses title
68
+ )
69
+
70
+ @property
71
+ def reports(self) -> ReportCollection:
72
+ """Reports belonging to this project."""
73
+ from cloudsprite.resources.reports import Report, ReportCollection
74
+
75
+ return ReportCollection(
76
+ self._client,
77
+ f"/api/reports/?project_id={self.id}",
78
+ Report,
79
+ name_field="title",
80
+ )
81
+
82
+ @property
83
+ def cloudscripts(self) -> CloudScriptCollection:
84
+ """CloudScripts belonging to this project (beta)."""
85
+ from cloudsprite.resources.cloudscripts import CloudScript, CloudScriptCollection
86
+
87
+ return CloudScriptCollection(
88
+ self._client,
89
+ f"/api/scripts/?project_id={self.id}",
90
+ CloudScript,
91
+ name_field="name",
92
+ )
93
+
94
+ # Legacy name kept as a true alias (same object).
95
+ sprites = cloudscripts
96
+
97
+ @property
98
+ def workflows(self) -> ResourceCollection[Workflow]:
99
+ """Workflows belonging to this project (beta)."""
100
+ from cloudsprite.resources.workflows import Workflow
101
+
102
+ return ResourceCollection(
103
+ self._client,
104
+ f"/api/workflows/?project_id={self.id}",
105
+ Workflow,
106
+ name_field="name",
107
+ )
108
+
109
+ def add_tag(self, tag_id: str) -> dict[str, Any]:
110
+ """Attach an existing tag to this project.
111
+
112
+ ``POST /api/tags/projects/{project_id}/add/{tag_id}``. Takes a tag id,
113
+ not a name — symmetric with :meth:`remove_tag` and with
114
+ :meth:`Dataset.add_tag`.
115
+
116
+ Args:
117
+ tag_id: UUID of an existing tag.
118
+ """
119
+ validate_id(tag_id, "tag_id")
120
+ return cast(
121
+ dict[str, Any],
122
+ self._client.post(f"/api/tags/projects/{self.id}/add/{tag_id}"),
123
+ )
124
+
125
+ def remove_tag(self, tag_id: str) -> None:
126
+ """Detach a tag from this project.
127
+
128
+ ``DELETE /api/tags/projects/{project_id}/remove/{tag_id}``.
129
+
130
+ Args:
131
+ tag_id: UUID of the tag to detach.
132
+ """
133
+ validate_id(tag_id, "tag_id")
134
+ self._client.delete(f"/api/tags/projects/{self.id}/remove/{tag_id}")
135
+
136
+ def create_dataset(self, title: str, **kwargs: Any) -> Dataset:
137
+ """Create a dataset in this project.
138
+
139
+ Args:
140
+ title: Dataset display name.
141
+ **kwargs: Additional fields (description, etc.)
142
+ """
143
+ from cloudsprite.resources.datasets import Dataset, apply_sdk_dataset_source
144
+
145
+ payload = apply_sdk_dataset_source({"title": title, "project_id": self.id, **kwargs})
146
+ data = self._client.post("/api/datasets/", json=payload)
147
+ return Dataset(self._client, data=data)
148
+
149
+ def create_notebook(self, title: str, **kwargs: Any) -> Notebook:
150
+ """Create a notebook in this project."""
151
+ from cloudsprite.resources.notebooks import Notebook
152
+
153
+ data = self._client.post("/api/notebooks/", json={"title": title, "project_id": self.id, **kwargs})
154
+ return Notebook(self._client, data=data)
155
+
156
+ def update(self, **kwargs: Any) -> None:
157
+ """Update project fields (title, description, etc.)."""
158
+ data = self._client.patch(f"/api/projects/{self.id}", json=kwargs)
159
+ if isinstance(data, dict):
160
+ self._data.update(data)
161
+
162
+ def trash(self) -> None:
163
+ """Move project to trash (soft delete). Cascades to datasets.
164
+
165
+ Server: ``POST /api/projects/{id}/trash`` (not DELETE — base DELETE is
166
+ a hard delete with S3 cleanup, a different operation).
167
+ """
168
+ self._client.post(f"/api/projects/{self.id}/trash")
169
+
170
+ def restore(self) -> None:
171
+ """Restore project from trash, including cascade-trashed datasets.
172
+
173
+ Server: ``POST /api/projects/{id}/restore``.
174
+ """
175
+ self._client.post(f"/api/projects/{self.id}/restore")
176
+
177
+ def delete(self) -> None:
178
+ """Permanently delete a trashed project.
179
+
180
+ Server: ``DELETE /api/projects/{id}/permanent-delete``.
181
+ """
182
+ self._client.delete(f"/api/projects/{self.id}/permanent-delete")
@@ -0,0 +1,125 @@
1
+ """Related datasets — ranked, with the reasons they were chosen.
2
+
3
+ Parity with ``GET /api/datasets/{id}/related/``. Every item carries at
4
+ least one reason (signal, one sentence, strength, evidence). Only datasets the
5
+ caller can read are returned; evidence the caller cannot read is ``redacted``
6
+ with no id or label. The API exposes no feedback endpoint yet, so the SDK has no
7
+ feedback call.
8
+
9
+ Example::
10
+
11
+ for item in ds.related(limit=5):
12
+ print(item.dataset.title, round(item.score, 2), item.reasons[0].text)
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from dataclasses import dataclass
18
+ from typing import Any, Iterator
19
+
20
+ RELATED_SIGNALS = ("lineage", "capture_context", "dut_setup", "co_membership", "parameters", "content", "tag")
21
+ RELATED_SCOPES = ("project", "team", "organization")
22
+ MAX_RELATED_LIMIT = 50
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class RelatedEvidence:
27
+ """What backs a reason. ``id`` and ``label`` are None when ``redacted``."""
28
+
29
+ kind: str
30
+ redacted: bool
31
+ id: str | None = None
32
+ label: str | None = None
33
+ project_id: str | None = None
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class RelatedReason:
38
+ """Why a dataset is related."""
39
+
40
+ signal: str
41
+ text: str
42
+ strength: float # 0..1
43
+ evidence: tuple[RelatedEvidence, ...] = ()
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class RelatedDataset:
48
+ """A related dataset reference (use ``cs.datasets``/``project.datasets`` with ``id`` to open it)."""
49
+
50
+ id: str
51
+ title: str
52
+ project_id: str
53
+ slug: str | None = None
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class RelatedItem:
58
+ """One ranked related dataset."""
59
+
60
+ dataset: RelatedDataset
61
+ score: float # 0..1
62
+ reasons: tuple[RelatedReason, ...] # largest contribution first, never empty
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class RelatedDatasets:
67
+ """Ranked related datasets for one dataset."""
68
+
69
+ dataset_id: str
70
+ scope: str
71
+ signals: tuple[str, ...]
72
+ computed_at: str # when the cached candidate list was built (up to 10 minutes old)
73
+ items: tuple[RelatedItem, ...]
74
+
75
+ def __iter__(self) -> Iterator[RelatedItem]:
76
+ return iter(self.items)
77
+
78
+ def __len__(self) -> int:
79
+ return len(self.items)
80
+
81
+ @classmethod
82
+ def from_api(cls, data: dict[str, Any]) -> RelatedDatasets:
83
+ """Build from the ``getRelatedDatasets`` response body."""
84
+ items = []
85
+ for raw in data.get("items") or []:
86
+ ds = raw.get("dataset") or {}
87
+ reasons = tuple(
88
+ RelatedReason(
89
+ signal=str(r.get("signal", "")),
90
+ text=str(r.get("text", "")),
91
+ strength=float(r.get("strength") or 0.0),
92
+ evidence=tuple(
93
+ RelatedEvidence(
94
+ kind=str(e.get("kind", "")),
95
+ redacted=bool(e.get("redacted", False)),
96
+ id=e.get("id"),
97
+ label=e.get("label"),
98
+ project_id=e.get("project_id"),
99
+ )
100
+ for e in (r.get("evidence") or [])
101
+ if isinstance(e, dict)
102
+ ),
103
+ )
104
+ for r in (raw.get("reasons") or [])
105
+ if isinstance(r, dict)
106
+ )
107
+ items.append(
108
+ RelatedItem(
109
+ dataset=RelatedDataset(
110
+ id=str(ds.get("id", "")),
111
+ title=str(ds.get("title", "")),
112
+ project_id=str(ds.get("project_id", "")),
113
+ slug=ds.get("slug"),
114
+ ),
115
+ score=float(raw.get("score") or 0.0),
116
+ reasons=reasons,
117
+ )
118
+ )
119
+ return cls(
120
+ dataset_id=str(data.get("dataset_id", "")),
121
+ scope=str(data.get("scope", "")),
122
+ signals=tuple(data.get("signals") or ()),
123
+ computed_at=str(data.get("computed_at", "")),
124
+ items=tuple(items),
125
+ )