embedgl 0.0.1__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.
embedgl/widget.py ADDED
@@ -0,0 +1,378 @@
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ import json
5
+ import uuid
6
+ from collections.abc import Sequence
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ import anywidget
11
+ import numpy as np
12
+ import polars as pl
13
+ import traitlets
14
+ from PIL import Image
15
+
16
+ from .query import evaluate, field_kind, scalar
17
+
18
+
19
+ class EmbeddingViewer(anywidget.AnyWidget):
20
+ """Explore projected rows without transferring the source DataFrame to the browser."""
21
+
22
+ _esm = Path(__file__).parent / "static" / "widget.js"
23
+ _css = Path(__file__).parent / "static" / "widget.css"
24
+ dataset = traitlets.Dict().tag(sync=True)
25
+ query = traitlets.Dict().tag(sync=True)
26
+ selected_count = traitlets.Int(0).tag(sync=True)
27
+ selection_revision = traitlets.Int(0).tag(sync=True)
28
+ height = traitlets.Int(640, min=320, max=2000).tag(sync=True)
29
+
30
+ def __init__(
31
+ self,
32
+ frame: pl.DataFrame,
33
+ *,
34
+ id_column: str,
35
+ coordinates_2d: Sequence[str] | None = None,
36
+ coordinates_3d: Sequence[str] | None = None,
37
+ cluster_column: str | None = None,
38
+ thumbnail_column: str | None = "thumbnail",
39
+ image_column: str | None = None,
40
+ searchable_columns: Sequence[str] = (),
41
+ filterable_columns: Sequence[str] = (),
42
+ metadata_columns: Sequence[str] = (),
43
+ height: int = 640,
44
+ ) -> None:
45
+ self.id_column = id_column
46
+ self.coordinate_columns = {
47
+ mode: tuple(columns)
48
+ for mode, columns in (("2d", coordinates_2d), ("3d", coordinates_3d))
49
+ if columns is not None
50
+ }
51
+ self.cluster_column = cluster_column
52
+ self.thumbnail_column = thumbnail_column
53
+ self.image_column = image_column
54
+ self.searchable_columns = list(searchable_columns)
55
+ self.filterable_columns = list(filterable_columns)
56
+ self.metadata_columns = list(dict.fromkeys([*metadata_columns, id_column]))
57
+ self._selected = np.empty(0, dtype="<u4")
58
+ self._query_revision = 0
59
+ self._text = ""
60
+ self._filters: list[dict[str, Any]] = []
61
+ self._geometry: dict[str, np.ndarray] = {}
62
+ self._row_column = f"__viewer_{uuid.uuid4().hex}"
63
+ super().__init__(height=height)
64
+ self.replace_data(frame)
65
+ self.on_msg(self._message)
66
+
67
+ @property
68
+ def selected_ids(self) -> list[str | int]:
69
+ return self._frame[self._selected.tolist(), :].get_column(self.id_column).to_list()
70
+
71
+ @property
72
+ def selected_df(self) -> pl.DataFrame:
73
+ return self._frame[self._selected.tolist(), :]
74
+
75
+ def replace_data(self, frame: pl.DataFrame) -> None:
76
+ if not isinstance(frame, pl.DataFrame):
77
+ raise TypeError("frame must be an eager Polars DataFrame")
78
+ if frame.height >= 2**32:
79
+ raise ValueError("Row count must fit uint32")
80
+ if not self.coordinate_columns:
81
+ raise ValueError("Provide coordinates_2d and/or coordinates_3d")
82
+ required = {
83
+ self.id_column,
84
+ *self.searchable_columns,
85
+ *self.filterable_columns,
86
+ *self.metadata_columns,
87
+ }
88
+ required.update(column for columns in self.coordinate_columns.values() for column in columns)
89
+ required.update(column for column in (self.cluster_column, self.image_column) if column)
90
+ if self.thumbnail_column and self.thumbnail_column in frame.columns:
91
+ required.add(self.thumbnail_column)
92
+ missing = required.difference(frame.columns)
93
+ if missing:
94
+ raise ValueError(f"Missing columns: {sorted(missing)}")
95
+ ids = frame.get_column(self.id_column)
96
+ if not (ids.dtype == pl.String or ids.dtype.is_integer()) or ids.null_count() or ids.n_unique() != frame.height:
97
+ raise ValueError("IDs must be unique non-null strings or integers")
98
+ geometry: dict[str, np.ndarray] = {}
99
+ bounds: dict[str, Any] = {}
100
+ for mode, columns in self.coordinate_columns.items():
101
+ if len(columns) != (2 if mode == "2d" else 3):
102
+ raise ValueError(f"{mode} requires {'two' if mode == '2d' else 'three'} coordinate columns")
103
+ if any(not frame.schema[column].is_numeric() for column in columns):
104
+ raise ValueError("Coordinates must be numeric")
105
+ positions = frame.select(columns).to_numpy().astype("<f4")
106
+ if not np.isfinite(positions).all():
107
+ raise ValueError("Coordinates must be finite and non-null")
108
+ if mode == "2d":
109
+ positions = np.column_stack((positions, np.zeros(frame.height, dtype="<f4")))
110
+ geometry[mode] = np.ascontiguousarray(positions, dtype="<f4")
111
+ bounds[mode] = {
112
+ "min": positions.min(axis=0).tolist() if frame.height else [0, 0, 0],
113
+ "max": positions.max(axis=0).tolist() if frame.height else [0, 0, 0],
114
+ }
115
+ fields = [{"name": column, "kind": field_kind(frame.schema[column])} for column in self.filterable_columns]
116
+ for column in self.searchable_columns:
117
+ if field_kind(frame.schema[column]) != "string":
118
+ raise ValueError(f"Search column must be a string: {column}")
119
+ for column in (self.thumbnail_column, self.image_column):
120
+ if column and column in frame.columns and frame.schema[column] != pl.Binary:
121
+ raise ValueError(f"Image column must have Binary dtype: {column}")
122
+ for column in self.metadata_columns:
123
+ if frame.schema[column] == pl.Binary or frame.schema[column].is_nested():
124
+ raise ValueError(f"Metadata must be scalar: {column}")
125
+ legend: list[dict[str, Any]] = []
126
+ unique: list[str] = []
127
+ if self.cluster_column:
128
+ field_kind(frame.schema[self.cluster_column])
129
+ labels = frame.get_column(self.cluster_column).cast(pl.String).fill_null("(null)")
130
+ codes, unique = labels.to_numpy(), labels.unique(maintain_order=True).to_list()
131
+ mapping = {label: index for index, label in enumerate(unique)}
132
+ cluster_codes = np.fromiter((mapping[label] for label in codes), dtype="<u4", count=frame.height)
133
+ legend = [{"code": index, "label": label} for index, label in enumerate(unique[:200])]
134
+ else:
135
+ cluster_codes = np.zeros(frame.height, dtype="<u4")
136
+ self._frame = frame.clone()
137
+ self._indexed = self._frame.with_row_index(self._row_column)
138
+ self._geometry = geometry
139
+ self._clusters = cluster_codes
140
+ self._matches = np.arange(frame.height, dtype="<u4")
141
+ self._selected = np.empty(0, dtype="<u4")
142
+ self._query_revision += 1
143
+ self._text, self._filters = "", []
144
+ with self.hold_sync():
145
+ self.selected_count = 0
146
+ self.selection_revision += 1
147
+ self.query = {"text": "", "filters": [], "revision": self._query_revision, "count": frame.height}
148
+ self.dataset = {
149
+ "revision": uuid.uuid4().hex,
150
+ "count": frame.height,
151
+ "modes": list(geometry),
152
+ "bounds": bounds,
153
+ "fields": fields,
154
+ "searchable": self.searchable_columns,
155
+ "metadata": self.metadata_columns,
156
+ "clusters": legend,
157
+ "cluster_count": len(unique) if self.cluster_column else 0,
158
+ "has_images": bool(self.thumbnail_column and self.thumbnail_column in frame.columns),
159
+ }
160
+
161
+ def set_search(self, text: str) -> None:
162
+ self._set_query(text, self._filters)
163
+
164
+ def set_filters(self, filters: Sequence[dict[str, Any]]) -> None:
165
+ self._set_query(self._text, list(filters))
166
+
167
+ def _set_query(self, text: str, filters: list[dict[str, Any]]) -> None:
168
+ if not isinstance(text, str) or not isinstance(filters, list):
169
+ raise ValueError("Query requires string text and a filter list")
170
+ encoded = json.dumps(filters, allow_nan=False)
171
+ if len(encoded) > 65536:
172
+ raise ValueError("Filters exceed the 64 KiB limit")
173
+ filters = json.loads(encoded)
174
+ indices = (
175
+ evaluate(
176
+ self._indexed,
177
+ self._row_column,
178
+ text,
179
+ filters,
180
+ self.searchable_columns,
181
+ self.filterable_columns,
182
+ )
183
+ .to_numpy()
184
+ .astype("<u4", copy=False)
185
+ )
186
+ if text == self.query.get("text") and filters == self.query.get("filters"):
187
+ return
188
+ self._matches = indices
189
+ self._selected = np.empty(0, dtype="<u4")
190
+ self._query_revision += 1
191
+ self._text, self._filters = text, filters
192
+ with self.hold_sync():
193
+ self.selected_count = 0
194
+ self.selection_revision += 1
195
+ self.query = {"text": text, "filters": filters, "revision": self._query_revision, "count": len(indices)}
196
+
197
+ def set_selection(self, ids: Sequence[str | int], mode: str = "replace") -> None:
198
+ values = list(ids)
199
+ rows = self._indexed.filter(pl.col(self.id_column).is_in(values)).get_column(self._row_column).to_numpy()
200
+ if len(rows) != len(set(values)):
201
+ raise ValueError("Selection contains unknown IDs")
202
+ self._select(rows, mode)
203
+
204
+ def clear_selection(self) -> None:
205
+ self._select(np.empty(0, dtype="<u4"), "replace")
206
+
207
+ def _select(self, rows: np.ndarray, mode: str) -> None:
208
+ if mode not in {"replace", "add", "remove"}:
209
+ raise ValueError("Selection mode must be replace, add or remove")
210
+ if len(rows) and (rows.min() < 0 or rows.max() >= self._frame.height):
211
+ raise ValueError("Selection row out of bounds")
212
+ if mode == "add":
213
+ selected = np.union1d(self._selected, rows)
214
+ elif mode == "remove":
215
+ selected = np.setdiff1d(self._selected, rows)
216
+ else:
217
+ selected = np.unique(rows)
218
+ self._selected = np.asarray(selected, dtype="<u4")
219
+ with self.hold_sync():
220
+ self.selected_count = len(self._selected)
221
+ self.selection_revision += 1
222
+
223
+ def _reply(self, request: dict[str, Any], payload: dict[str, Any], buffers: list[bytes] | None = None) -> None:
224
+ self.send(
225
+ {
226
+ "version": 1,
227
+ "request_id": request.get("request_id"),
228
+ "dataset_revision": self.dataset["revision"],
229
+ "query_revision": self.query["revision"],
230
+ **payload,
231
+ },
232
+ buffers=buffers or [],
233
+ )
234
+
235
+ def _message(self, widget: anywidget.AnyWidget, content: dict[str, Any], buffers: list[memoryview]) -> None:
236
+ del widget
237
+ if not isinstance(content, dict):
238
+ return
239
+ try:
240
+ if content.get("version") != 1:
241
+ raise ValueError("Unsupported protocol version")
242
+ if content.get("dataset_revision") != self.dataset["revision"]:
243
+ raise ValueError("Dataset changed; reload this view")
244
+ operation = content.get("op")
245
+ if (
246
+ operation in {"select", "select_all", "query", "page", "matches", "facets"}
247
+ and content.get("query_revision") != self.query["revision"]
248
+ ):
249
+ raise ValueError("Query changed; retry with the current query")
250
+ if operation == "geometry":
251
+ mode = str(content.get("mode"))
252
+ positions = self._geometry[mode]
253
+ start = max(0, int(content.get("start", 0)))
254
+ end = min(start + 65536, self._frame.height)
255
+ if start > self._frame.height:
256
+ raise ValueError("Invalid geometry offset")
257
+ self._reply(
258
+ content,
259
+ {"op": "geometry", "mode": mode, "start": start, "end": end},
260
+ [
261
+ positions[start:end].tobytes(),
262
+ self._clusters[start:end].tobytes(),
263
+ ],
264
+ )
265
+ elif operation in {"matches", "selection"}:
266
+ indices = self._matches if operation == "matches" else self._selected
267
+ start = max(0, int(content.get("start", 0)))
268
+ end = min(start + 262144, len(indices))
269
+ self._reply(
270
+ content,
271
+ {
272
+ "op": operation,
273
+ "start": start,
274
+ "end": end,
275
+ "total": len(indices),
276
+ "selection_revision": self.selection_revision,
277
+ },
278
+ [indices[start:end].tobytes()],
279
+ )
280
+ elif operation == "query":
281
+ self._set_query(content.get("text", ""), content.get("filters", []))
282
+ self._reply(content, {"op": "query", "query": self.query})
283
+ elif operation == "page":
284
+ scope = content.get("scope", "all")
285
+ if scope not in {"all", "selected"}:
286
+ raise ValueError("Page scope must be all or selected")
287
+ if scope == "selected" and content.get("selection_revision") != self.selection_revision:
288
+ raise ValueError("Selection changed; retry with the current selection")
289
+ offset = max(0, int(content.get("offset", 0)))
290
+ limit = min(100, max(1, int(content.get("limit", 30))))
291
+ indices = self._selected if scope == "selected" else self._matches
292
+ offset = min(offset, max(0, (len(indices) - 1) // limit * limit))
293
+ rows = indices[offset : offset + limit]
294
+ records = self._frame[rows.tolist(), :].select(self.metadata_columns).to_dicts()
295
+ self._reply(
296
+ content,
297
+ {
298
+ "op": "page",
299
+ "offset": offset,
300
+ "scope": scope,
301
+ "selection_revision": self.selection_revision,
302
+ "rows": [
303
+ {
304
+ "index": int(index),
305
+ "values": {
306
+ key: scalar(value[:2000] if isinstance(value, str) else value)
307
+ for key, value in record.items()
308
+ },
309
+ }
310
+ for index, record in zip(rows, records, strict=True)
311
+ ],
312
+ },
313
+ )
314
+ elif operation == "detail":
315
+ index = int(content["index"])
316
+ if index < 0 or index >= self._frame.height:
317
+ raise ValueError("Detail index out of bounds")
318
+ record = self._frame.select(self.metadata_columns).row(index, named=True)
319
+ self._reply(
320
+ content,
321
+ {
322
+ "op": "detail",
323
+ "index": index,
324
+ "values": {
325
+ key: scalar(value[:100000] if isinstance(value, str) else value)
326
+ for key, value in record.items()
327
+ },
328
+ },
329
+ )
330
+ elif operation == "facets":
331
+ column = content.get("column")
332
+ if column not in self.filterable_columns:
333
+ raise ValueError("Column is not filterable")
334
+ offset = max(0, int(content.get("offset", 0)))
335
+ values = self._frame.get_column(column).drop_nulls().unique().sort()
336
+ self._reply(
337
+ content,
338
+ {
339
+ "op": "facets",
340
+ "column": column,
341
+ "total": len(values),
342
+ "values": [
343
+ scalar(value[:2000] if isinstance(value, str) else value)
344
+ for value in values.slice(offset, 100)
345
+ ],
346
+ },
347
+ )
348
+ elif operation == "select_all":
349
+ self._select(self._matches, "replace")
350
+ self._reply(content, {"op": "selected"})
351
+ elif operation == "select":
352
+ if len(buffers) != 1 or len(buffers[0]) > self._frame.height * 4 or len(buffers[0]) % 4:
353
+ raise ValueError("Expected a bounded uint32 selection buffer")
354
+ self._select(np.frombuffer(buffers[0], dtype="<u4"), content.get("mode", "replace"))
355
+ self._reply(content, {"op": "selected"})
356
+ elif operation == "image":
357
+ index = int(content["index"])
358
+ if index < 0 or index >= self._frame.height:
359
+ raise ValueError("Image index out of bounds")
360
+ column = self.image_column if content.get("full") and self.image_column else self.thumbnail_column
361
+ if not column or column not in self._frame.columns:
362
+ self._reply(content, {"op": "image", "index": index, "mime": None})
363
+ return
364
+ image_bytes = self._frame.get_column(column)[index]
365
+ if not image_bytes:
366
+ self._reply(content, {"op": "image", "index": index, "mime": None})
367
+ return
368
+ if len(image_bytes) > 20 * 1024 * 1024:
369
+ raise ValueError("Image exceeds 20 MiB limit")
370
+ with Image.open(io.BytesIO(image_bytes)) as image:
371
+ mime = Image.MIME.get(image.format or "")
372
+ if mime not in {"image/jpeg", "image/png", "image/webp", "image/gif"}:
373
+ raise ValueError("Unsupported image format")
374
+ self._reply(content, {"op": "image", "index": index, "mime": mime}, [image_bytes])
375
+ else:
376
+ raise ValueError(f"Unknown operation: {operation}")
377
+ except Exception as error:
378
+ self._reply(content, {"op": "error", "error": str(error)})
@@ -0,0 +1,212 @@
1
+ Metadata-Version: 2.4
2
+ Name: embedgl
3
+ Version: 0.0.1
4
+ Summary: JupyterLab widget for visualizing embeddings
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Repository, https://github.com/M-Anwar/embedgl
7
+ Project-URL: Issues, https://github.com/M-Anwar/embedgl/issues
8
+ Classifier: Framework :: Jupyter
9
+ Classifier: Framework :: Jupyter :: JupyterLab
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Topic :: Scientific/Engineering :: Visualization
14
+ Requires-Python: >=3.12
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: Pillow>=10.1
18
+ Requires-Dist: numpy
19
+ Requires-Dist: polars<3,>=2.1
20
+ Requires-Dist: anywidget>=0.9.18
21
+ Requires-Dist: traitlets>=5.9
22
+ Dynamic: license-file
23
+
24
+ # Embedgl
25
+
26
+ A React/Three.js anywidget for exploring precomputed 2D and 3D projections in JupyterLab or another anywidget-compatible notebook. An eager Polars DataFrame owns the data in Python. Column search and filters determine which points render; image bytes and metadata are requested on demand.
27
+
28
+ ![EmebedGL Demo Image](examples/sample.png)
29
+
30
+ ## Install
31
+
32
+ Install into the same environment as your notebook kernel:
33
+
34
+ ```sh
35
+ pip install embedgl
36
+ ```
37
+
38
+ For a local checkout, run `pip install -e .` from the repository root. Python 3.12 or newer is required.
39
+
40
+ The built JavaScript/CSS assets are included under `embedgl/static` in the installed package. Normal notebook use needs neither Node.js nor a frontend server. No separate custom JupyterLab extension is required; the notebook must support ipywidgets/anywidget and WebGL. In JupyterLab, install `jupyterlab_widgets` in the JupyterLab server environment if it is separate from the kernel environment.
41
+
42
+ ## Try It
43
+
44
+ Run in a notebook cell:
45
+
46
+ ```python
47
+ from embedgl.demo import make_demo
48
+
49
+ viewer = make_demo()
50
+ viewer
51
+ ```
52
+
53
+ The demo generates a small Polars DataFrame and synthetic receipt thumbnails locally. It does not load source receipt images or any ML models. Open [examples/usage.ipynb](examples/usage.ipynb) in JupyterLab or VS Code after installing the package, select the environment where `embedgl` is installed, and run the cells in order.
54
+
55
+ ## Your DataFrame
56
+
57
+ Provide precomputed coordinate columns. **The viewer does not compute projections or clusters.**
58
+
59
+ ```python
60
+ from embedgl import EmbeddingViewer
61
+
62
+ viewer = EmbeddingViewer(
63
+ frame,
64
+ id_column="hash_id",
65
+ coordinates_2d=("umap_x", "umap_y"),
66
+ coordinates_3d=("umap3_x", "umap3_y", "umap3_z"),
67
+ cluster_column="cluster",
68
+ thumbnail_column="thumbnail",
69
+ image_column="image",
70
+ searchable_columns=("file_name", "ocr_text"),
71
+ filterable_columns=("file_name", "cluster", "amount", "reviewed"),
72
+ metadata_columns=("file_name", "source_path", "amount"),
73
+ height=700,
74
+ )
75
+ viewer
76
+ ```
77
+
78
+ Pass only columns that exist in your frame. At least one coordinate set is required; omit `coordinates_3d`, `cluster_column`, `image_column`, or other optional mappings when unavailable.
79
+
80
+ - IDs must be unique, non-null strings or integers. Original ID types, including 64-bit integers, stay in Python; browser messages use dense uint32 row indices.
81
+ - Coordinates must be finite numeric values with no nulls. The renderer normalizes their scale locally without modifying the frame.
82
+ - Images must be Polars `Binary` columns containing JPEG, PNG, WebP, or GIF bytes. An absent default `thumbnail` column is allowed; pass `thumbnail_column=None` for a point-only view. Filesystem paths and remote URLs are not automatically opened.
83
+ - Search columns must be string-like. Search is case-insensitive literal substring matching across those columns (OR), combined with filters (AND). Empty search matches all rows.
84
+ - Filter columns support strings/categories, numeric values, booleans, dates, and datetimes. Flatten struct fields before configuring them. List/embedding columns are not filterable.
85
+ - Metadata is an explicit scalar-column whitelist. The ID column is always included. The first two configured metadata columns label result rows. Page text is capped at 2,000 characters per value; requested detail text is capped at 100,000. Binary/nested metadata is rejected. Large integers are represented as strings in metadata responses.
86
+ - The DataFrame is treated as an immutable snapshot. Use `replace_data(new_frame)` to load a replacement with the same configured columns. This clears queries, selections, and browser caches.
87
+
88
+ ## Search and Filters From Python
89
+
90
+ ```python
91
+ viewer.set_search("coffee")
92
+ viewer.set_filters(
93
+ [
94
+ {"column": "amount", "op": "gte", "value": 10},
95
+ {"column": "amount", "op": "lte", "value": 75},
96
+ {"column": "reviewed", "op": "eq", "value": True},
97
+ ]
98
+ )
99
+
100
+ viewer.set_search("")
101
+ viewer.set_filters([])
102
+ ```
103
+
104
+ Supported filter operations:
105
+
106
+ | Operation | Value | Columns |
107
+ | --- | --- | --- |
108
+ | `contains` | String | String/category |
109
+ | `eq` | Scalar | Any configured filter column |
110
+ | `in` | List of scalars, at most 1,000 | Any configured filter column |
111
+ | `gte`, `lte` | Inclusive bound | Numeric/date/datetime |
112
+ | `is_null`, `not_null` | No value | Any configured filter column |
113
+
114
+ Pass dates/datetimes as ISO strings, with timezone presence matching the column dtype. Boolean values must be actual booleans, not strings. Decimal/integer bounds can be strings to preserve precision. Ordinary comparisons do not match nulls. Filters are limited to 32 predicates and 64 KiB of JSON. Text search is limited to 4,096 characters. The UI offers the first 100 distinct string values as suggestions; custom values remain accepted. The `in` control accepts a JSON array.
115
+
116
+ Accepted search/filter changes immediately clear selection and hide unmatched points. They do not resend coordinates or automatically move the camera. Use **Fit matching points** to frame the remaining points explicitly. Results retain source-row order and are paginated 30 at a time.
117
+
118
+ ## Selection
119
+
120
+ ```python
121
+ viewer.selected_ids
122
+ selected_frame = viewer.selected_df
123
+
124
+ viewer.set_selection(["some-stable-id"])
125
+ viewer.set_selection(["another-id"], mode="add")
126
+ viewer.set_selection(["some-stable-id"], mode="remove")
127
+ viewer.clear_selection()
128
+ ```
129
+
130
+ Use the pan/orbit, rectangle-selection, and circular-selection toolbar modes. For circular selection, press at the desired center, drag outward to set the radius, and release to select. The center stays fixed at the initial press position. Clicking a point in pan/orbit or rectangle mode selects the nearest point; result checkboxes and image details also change selection. Hold Shift to add and Alt to remove during canvas selection. **Select all results** includes every matching row, not just the displayed page. In both 2D and 3D, area selection uses projected screen positions. In 3D, rectangles and circles include all matched points inside their screen-space boundary and camera clip volume, including points behind others.
131
+
132
+ Programmatic selection can include currently filtered-out rows, which stay selected in Python but are not rendered. A subsequent accepted query change clears the complete selection. `selected_df` preserves source-row order. For change notifications, standard widget observation is available:
133
+
134
+ ```python
135
+ def selection_changed(change):
136
+ print(viewer.selected_count)
137
+
138
+
139
+ viewer.observe(selection_changed, names=["selection_revision"])
140
+ ```
141
+
142
+ Cluster labels only assign colors (an eight-color palette, repeated for larger cluster counts). Hover shows up to 12 nearest overlapping screen-space points, not all members of the semantic cluster. Click a preview to inspect its image and whitelisted metadata.
143
+
144
+ ## Frontend Development
145
+
146
+ Run these commands from the repository root with Node.js 22 and npm:
147
+
148
+ ```sh
149
+ npm ci
150
+ npm run build
151
+ uv sync
152
+ ```
153
+
154
+ The build typechecks the frontend, bundles React, Three.js, icons, and the inline worker into `src/embedgl/static/widget.js` and `src/embedgl/static/widget.css`, and generates `src/embedgl/THIRD_PARTY_LICENSES.txt`. Commit these generated files so installing a checkout or source distribution does not require Node.js. For continuous compilation:
155
+
156
+ ```sh
157
+ npm run watch
158
+ ```
159
+
160
+ For notebook hot reload, set `ANYWIDGET_HMR=1` before importing the widget. Otherwise create a new widget after rebuilding, or restart the kernel if the old module is cached. Run the full build again before releasing; watch mode does not typecheck or regenerate license notices.
161
+
162
+ ## Release Checks
163
+
164
+ The Python package lives under `src/embedgl`; frontend sources and examples are not importable Python packages. The version is maintained explicitly in `pyproject.toml`, not derived from Git tags. Update it for each release; PyPI does not allow replacing an uploaded version.
165
+
166
+ From a clean checkout, build and validate with:
167
+
168
+ ```sh
169
+ npm ci
170
+ npm run build
171
+ uv sync --group dev
172
+ uv run python -m unittest discover -s tests -v
173
+ uv run python -m build
174
+ uv run python scripts/check_dist.py
175
+ uv run python -m twine check --strict dist/*
176
+ ```
177
+
178
+ Start with an empty `dist` directory so old releases are not mixed with the new one. The build rejects missing or empty JS, CSS, or third-party notices. The archive check verifies that the wheel and source distribution contain the same compiled assets. Python builds use the prebuilt assets and never download frontend dependencies.
179
+
180
+ The release-check workflow runs on Linux and Windows, builds the wheel from the source distribution, and runs tests against that wheel outside the checkout. Before uploading, also render `embedgl.demo.make_demo()` in a real JupyterLab notebook and check 2D/3D views, picking, image previews, and selection. Automated Python checks do not verify browser rendering or performance.
181
+
182
+ ### Publish From GitHub
183
+
184
+ Publishing a non-prerelease GitHub release runs the release-check workflow against the tagged commit. Both Linux and Windows must pass before a separate job uploads the validated Linux-built wheel and source distribution to PyPI. Pushes, pull requests, manual workflow runs, tag pushes alone, draft releases, and releases marked as prereleases do not publish to PyPI. Authentication uses PyPI Trusted Publishing (OIDC); no PyPI API token or GitHub secret is needed.
185
+
186
+ One-time setup (repository `M-Anwar/embedgl`):
187
+
188
+ 1. In GitHub, open **Settings > Environments > New environment** and create `pypi`. Under its deployment branch/tag rules, select **Selected branches and tags** and add a **tag** rule matching `v*`. Optionally add required reviewers if your repository plan supports them; each upload will then wait for approval.
189
+ 2. Log in to PyPI with two-factor authentication enabled. For an existing `embedgl` project you own, open **Manage > Publishing > Add a new publisher**. For a first upload, use [PyPI's pending publisher form](https://pypi.org/manage/account/publishing/) and set the project name to `embedgl`. A pending publisher does not reserve a name; if someone else owns it, you need ownership or a different package name.
190
+ 3. Choose GitHub and enter these exact values: owner `M-Anwar`, repository `embedgl`, workflow filename `release-check.yml` (not its path or display name), and environment `pypi`.
191
+ 4. Commit and push the workflow and release changes. Keep the workflow on the default branch and on any branch you plan to release. Ensure GitHub Actions is enabled for the repository.
192
+
193
+ For each release:
194
+
195
+ 1. Set a new, unused `[project].version` in `pyproject.toml`, rebuild and commit frontend assets if they changed, and push the release-ready commit to your chosen branch. Run the release checks and notebook smoke test above.
196
+ 2. In GitHub, open **Releases > Draft a new release**. Under **Choose a tag**, enter `v` followed by the exact project version, such as `v1.0` for version `1.0`. Create the new tag on publish and select your release branch in **Target**. When selecting an existing tag, its commit is used regardless of the current branch tip.
197
+ 3. Add a title and release notes, leave **Set as a pre-release** unchecked, and click **Publish release**. The workflow rejects tags that do not exactly match the version in the tagged commit; it does not change the version automatically.
198
+ 4. Follow **Actions > Release checks**. Approve the `pypi` deployment if required, then verify the new version on [PyPI](https://pypi.org/project/embedgl/).
199
+
200
+ PyPI does not allow overwriting a published version or reusing deleted distribution filenames. For a corrected release, increment the version and create a new tag/release; do not move an old release tag. A failed run before uploading can be rerun after fixing external setup, but an upload that already succeeded must not be repeated. The workflow deliberately does not ignore existing files.
201
+
202
+ Manual publishing remains available with `uv run python -m twine upload dist/*` after local validation. Authenticate through your usual secure PyPI workflow; never commit credentials.
203
+
204
+ ## Data Flow and Limitations
205
+
206
+ The ready view requests coordinates in paced chunks of up to 65,536 points. Geometry is float32 positions plus uint32 cluster codes; row order is implicit. Each requested dimension mode is cached per browser model. All large buffers use custom messages, not synced traits or saved notebook state. Filtering sends only uint32 match indices; selection uses the same compact representation. Images are fetched at most four at a time and held in a 32 MiB browser LRU cache; a single image is limited to 20 MiB.
207
+
208
+ Three.js renders a buffer-based point cloud. A per-view Web Worker projects matched points and builds a KDBush index after camera motion settles. Hover and rectangle picking are briefly suspended while that index rebuilds. Multiple displays of the same widget share query/selection/data state but have independent cameras. Close/dispose outputs to release their GPU/worker resources.
209
+
210
+ Operation requires a live, responsive notebook kernel. Saved output is not an offline data export. Long-running notebook computations delay query/image responses; a 30-second timeout exposes a reconnect action. Search/filter evaluation runs synchronously in the kernel in this first version. Browser geometry, per-view GPU buffers, worker indexing, and match masks consume additional memory beyond the Polars frame.
211
+
212
+ The design targets 100,000–1 million points, but capacity and frame rate depend on hardware and data. Python smoke tests and distribution-content checks are included. Live notebook behavior and million-point performance require separate browser testing and benchmarks.
@@ -0,0 +1,12 @@
1
+ embedgl/THIRD_PARTY_LICENSES.txt,sha256=-zpp5haVlkqGqeiT1WSgQuDLiEoPxA6wCY3afEzuNAc,6707
2
+ embedgl/__init__.py,sha256=DFw-Z0_Yud7DzAJV2Y_ppuqforDVS_FgVIIRggRehFo,121
3
+ embedgl/demo.py,sha256=F5eGy5qGXCnctB9VoEK-pJ-AykE4o_NpZBZYfXmdh7c,3238
4
+ embedgl/query.py,sha256=7qjx1kV7nMdBeP_zZcLOs9yjD4iMhiPYFOfdyMmtheE,4677
5
+ embedgl/widget.py,sha256=sqtaE8b5zGiko6kZA3ZPOdx5kMMQPd2vurfprqmRkXU,18107
6
+ embedgl/static/widget.css,sha256=AT5haOcOiBl9jE357CS4y_OswRyGA6Wgu0KXd7-ds4g,9669
7
+ embedgl/static/widget.js,sha256=4YIpQ-w-0hgGDnxPW2qORMtBr09PkW10l1Qk4OZB5fI,1182244
8
+ embedgl-0.0.1.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
9
+ embedgl-0.0.1.dist-info/METADATA,sha256=i-FciNNRv6xXXuvmyzb3Zyn-rJXRoYdn3Wyp05UUK9w,14452
10
+ embedgl-0.0.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
11
+ embedgl-0.0.1.dist-info/top_level.txt,sha256=zB1vAMM41ijFFT4CsImL8_oPculWfdODfi3hmnlU8rE,8
12
+ embedgl-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+