embedgl 0.0.1__tar.gz

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-0.0.1/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,9 @@
1
+ include src/build_support.py
2
+ include package.json package-lock.json tsconfig.json vite.config.ts
3
+ include src/embedgl/THIRD_PARTY_LICENSES.txt
4
+ recursive-include src/embedgl/static *.js *.css
5
+ recursive-include frontend *.ts *.tsx *.css
6
+ recursive-include scripts *.py *.mjs
7
+ recursive-include tests *.py
8
+ recursive-include examples *.ipynb
9
+ global-exclude __pycache__ *.py[cod]
embedgl-0.0.1/PKG-INFO ADDED
@@ -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,189 @@
1
+ # Embedgl
2
+
3
+ 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.
4
+
5
+ ![EmebedGL Demo Image](examples/sample.png)
6
+
7
+ ## Install
8
+
9
+ Install into the same environment as your notebook kernel:
10
+
11
+ ```sh
12
+ pip install embedgl
13
+ ```
14
+
15
+ For a local checkout, run `pip install -e .` from the repository root. Python 3.12 or newer is required.
16
+
17
+ 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.
18
+
19
+ ## Try It
20
+
21
+ Run in a notebook cell:
22
+
23
+ ```python
24
+ from embedgl.demo import make_demo
25
+
26
+ viewer = make_demo()
27
+ viewer
28
+ ```
29
+
30
+ 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.
31
+
32
+ ## Your DataFrame
33
+
34
+ Provide precomputed coordinate columns. **The viewer does not compute projections or clusters.**
35
+
36
+ ```python
37
+ from embedgl import EmbeddingViewer
38
+
39
+ viewer = EmbeddingViewer(
40
+ frame,
41
+ id_column="hash_id",
42
+ coordinates_2d=("umap_x", "umap_y"),
43
+ coordinates_3d=("umap3_x", "umap3_y", "umap3_z"),
44
+ cluster_column="cluster",
45
+ thumbnail_column="thumbnail",
46
+ image_column="image",
47
+ searchable_columns=("file_name", "ocr_text"),
48
+ filterable_columns=("file_name", "cluster", "amount", "reviewed"),
49
+ metadata_columns=("file_name", "source_path", "amount"),
50
+ height=700,
51
+ )
52
+ viewer
53
+ ```
54
+
55
+ 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.
56
+
57
+ - 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.
58
+ - Coordinates must be finite numeric values with no nulls. The renderer normalizes their scale locally without modifying the frame.
59
+ - 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.
60
+ - 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.
61
+ - Filter columns support strings/categories, numeric values, booleans, dates, and datetimes. Flatten struct fields before configuring them. List/embedding columns are not filterable.
62
+ - 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.
63
+ - 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.
64
+
65
+ ## Search and Filters From Python
66
+
67
+ ```python
68
+ viewer.set_search("coffee")
69
+ viewer.set_filters(
70
+ [
71
+ {"column": "amount", "op": "gte", "value": 10},
72
+ {"column": "amount", "op": "lte", "value": 75},
73
+ {"column": "reviewed", "op": "eq", "value": True},
74
+ ]
75
+ )
76
+
77
+ viewer.set_search("")
78
+ viewer.set_filters([])
79
+ ```
80
+
81
+ Supported filter operations:
82
+
83
+ | Operation | Value | Columns |
84
+ | --- | --- | --- |
85
+ | `contains` | String | String/category |
86
+ | `eq` | Scalar | Any configured filter column |
87
+ | `in` | List of scalars, at most 1,000 | Any configured filter column |
88
+ | `gte`, `lte` | Inclusive bound | Numeric/date/datetime |
89
+ | `is_null`, `not_null` | No value | Any configured filter column |
90
+
91
+ 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.
92
+
93
+ 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.
94
+
95
+ ## Selection
96
+
97
+ ```python
98
+ viewer.selected_ids
99
+ selected_frame = viewer.selected_df
100
+
101
+ viewer.set_selection(["some-stable-id"])
102
+ viewer.set_selection(["another-id"], mode="add")
103
+ viewer.set_selection(["some-stable-id"], mode="remove")
104
+ viewer.clear_selection()
105
+ ```
106
+
107
+ 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.
108
+
109
+ 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:
110
+
111
+ ```python
112
+ def selection_changed(change):
113
+ print(viewer.selected_count)
114
+
115
+
116
+ viewer.observe(selection_changed, names=["selection_revision"])
117
+ ```
118
+
119
+ 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.
120
+
121
+ ## Frontend Development
122
+
123
+ Run these commands from the repository root with Node.js 22 and npm:
124
+
125
+ ```sh
126
+ npm ci
127
+ npm run build
128
+ uv sync
129
+ ```
130
+
131
+ 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:
132
+
133
+ ```sh
134
+ npm run watch
135
+ ```
136
+
137
+ 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.
138
+
139
+ ## Release Checks
140
+
141
+ 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.
142
+
143
+ From a clean checkout, build and validate with:
144
+
145
+ ```sh
146
+ npm ci
147
+ npm run build
148
+ uv sync --group dev
149
+ uv run python -m unittest discover -s tests -v
150
+ uv run python -m build
151
+ uv run python scripts/check_dist.py
152
+ uv run python -m twine check --strict dist/*
153
+ ```
154
+
155
+ 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.
156
+
157
+ 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.
158
+
159
+ ### Publish From GitHub
160
+
161
+ 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.
162
+
163
+ One-time setup (repository `M-Anwar/embedgl`):
164
+
165
+ 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.
166
+ 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.
167
+ 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`.
168
+ 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.
169
+
170
+ For each release:
171
+
172
+ 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.
173
+ 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.
174
+ 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.
175
+ 4. Follow **Actions > Release checks**. Approve the `pypi` deployment if required, then verify the new version on [PyPI](https://pypi.org/project/embedgl/).
176
+
177
+ 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.
178
+
179
+ 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.
180
+
181
+ ## Data Flow and Limitations
182
+
183
+ 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.
184
+
185
+ 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.
186
+
187
+ 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.
188
+
189
+ 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.