diff --git a/CHANGES.md b/CHANGES.md index f0d5d81fd44..4c1604c4c99 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,10 @@ # Change Log +## 1.137 + +- Updated Sandcastle Gallery creation process to leverage MIT licensed Huggingface model to vectorize each sandcastle for Embedding search +- Switched Sandcastle application to use an embedding based search instead of existing pagefind implementation + ## 1.136 - 2025-12-01 ### @cesium/engine diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 7de84032cb0..a184f03043e 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -106,6 +106,7 @@ See [CONTRIBUTING.md](CONTRIBUTING.md) for details on how to contribute to Cesiu - [Mark Schlosser](https://github.com/markschlosseratbentley) - [Adam Larkeryd](https://github.com/alarkbentley) - [Don McCurdy](https://github.com/donmccurdy) + - [Tom DiCarlo](https://github.com/tomdicarlo) - [Flightradar24 AB](https://www.flightradar24.com) - [Aleksei Kalmykov](https://github.com/kalmykov) - [BIT Systems](http://www.caci.com/bit-systems) diff --git a/LICENSE.md b/LICENSE.md index 1631b3c9d97..56112890375 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1039,6 +1039,212 @@ http://www.jshint.com/ > > THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. JSHint was forked from the 2010-12-16 edition of JSLint. +### transformers.js + +https://github.com/huggingface/transformers.js?tab=Apache-2.0-1-ov-file + +> Apache License +> Version 2.0, January 2004 +> http://www.apache.org/licenses/ +> +> TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION +> +> 1. Definitions. +> +> "License" shall mean the terms and conditions for use, reproduction, +> and distribution as defined by Sections 1 through 9 of this document. +> +> "Licensor" shall mean the copyright owner or entity authorized by +> the copyright owner that is granting the License. +> +> "Legal Entity" shall mean the union of the acting entity and all +> other entities that control, are controlled by, or are under common +> control with that entity. For the purposes of this definition, +> "control" means (i) the power, direct or indirect, to cause the +> direction or management of such entity, whether by contract or +> otherwise, or (ii) ownership of fifty percent (50%) or more of the +> outstanding shares, or (iii) beneficial ownership of such entity. +> +> "You" (or "Your") shall mean an individual or Legal Entity +> exercising permissions granted by this License. +> +> "Source" form shall mean the preferred form for making modifications, +> including but not limited to software source code, documentation +> source, and configuration files. +> +> "Object" form shall mean any form resulting from mechanical +> transformation or translation of a Source form, including but +> not limited to compiled object code, generated documentation, +> and conversions to other media types. +> +> "Work" shall mean the work of authorship, whether in Source or +> Object form, made available under the License, as indicated by a +> copyright notice that is included in or attached to the work +> (an example is provided in the Appendix below). +> +> "Derivative Works" shall mean any work, whether in Source or Object +> form, that is based on (or derived from) the Work and for which the +> editorial revisions, annotations, elaborations, or other modifications +> represent, as a whole, an original work of authorship. For the purposes +> of this License, Derivative Works shall not include works that remain +> separable from, or merely link (or bind by name) to the interfaces of, +> the Work and Derivative Works thereof. +> +> "Contribution" shall mean any work of authorship, including +> the original version of the Work and any modifications or additions +> to that Work or Derivative Works thereof, that is intentionally +> submitted to Licensor for inclusion in the Work by the copyright owner +> or by an individual or Legal Entity authorized to submit on behalf of +> the copyright owner. For the purposes of this definition, "submitted" +> means any form of electronic, verbal, or written communication sent +> to the Licensor or its representatives, including but not limited to +> communication on electronic mailing lists, source code control systems, +> and issue tracking systems that are managed by, or on behalf of, the +> Licensor for the purpose of discussing and improving the Work, but +> excluding communication that is conspicuously marked or otherwise +> designated in writing by the copyright owner as "Not a Contribution." +> +> "Contributor" shall mean Licensor and any individual or Legal Entity +> on behalf of whom a Contribution has been received by Licensor and +> subsequently incorporated within the Work. +> +> 2. Grant of Copyright License. Subject to the terms and conditions of +> this License, each Contributor hereby grants to You a perpetual, +> worldwide, non-exclusive, no-charge, royalty-free, irrevocable +> copyright license to reproduce, prepare Derivative Works of, +> publicly display, publicly perform, sublicense, and distribute the +> Work and such Derivative Works in Source or Object form. +> +> 3. Grant of Patent License. Subject to the terms and conditions of +> this License, each Contributor hereby grants to You a perpetual, +> worldwide, non-exclusive, no-charge, royalty-free, irrevocable +> (except as stated in this section) patent license to make, have made, +> use, offer to sell, sell, import, and otherwise transfer the Work, +> where such license applies only to those patent claims licensable +> by such Contributor that are necessarily infringed by their +> Contribution(s) alone or by combination of their Contribution(s) +> with the Work to which such Contribution(s) was submitted. If You +> institute patent litigation against any entity (including a +> cross-claim or counterclaim in a lawsuit) alleging that the Work +> or a Contribution incorporated within the Work constitutes direct +> or contributory patent infringement, then any patent licenses +> granted to You under this License for that Work shall terminate +> as of the date such litigation is filed. +> +> 4. Redistribution. You may reproduce and distribute copies of the +> Work or Derivative Works thereof in any medium, with or without +> modifications, and in Source or Object form, provided that You +> meet the following conditions: +> +> (a) You must give any other recipients of the Work or +> Derivative Works a copy of this License; and +> +> (b) You must cause any modified files to carry prominent notices +> stating that You changed the files; and +> +> (c) You must retain, in the Source form of any Derivative Works +> that You distribute, all copyright, patent, trademark, and +> attribution notices from the Source form of the Work, +> excluding those notices that do not pertain to any part of +> the Derivative Works; and +> +> (d) If the Work includes a "NOTICE" text file as part of its +> distribution, then any Derivative Works that You distribute must +> include a readable copy of the attribution notices contained +> within such NOTICE file, excluding those notices that do not +> pertain to any part of the Derivative Works, in at least one +> of the following places: within a NOTICE text file distributed +> as part of the Derivative Works; within the Source form or +> documentation, if provided along with the Derivative Works; or, +> within a display generated by the Derivative Works, if and +> wherever such third-party notices normally appear. The contents +> of the NOTICE file are for informational purposes only and +> do not modify the License. You may add Your own attribution +> notices within Derivative Works that You distribute, alongside +> or as an addendum to the NOTICE text from the Work, provided +> that such additional attribution notices cannot be construed +> as modifying the License. +> +> You may add Your own copyright statement to Your modifications and +> may provide additional or different license terms and conditions +> for use, reproduction, or distribution of Your modifications, or +> for any such Derivative Works as a whole, provided Your use, +> reproduction, and distribution of the Work otherwise complies with +> the conditions stated in this License. +> +> 5. Submission of Contributions. Unless You explicitly state otherwise, +> any Contribution intentionally submitted for inclusion in the Work +> by You to the Licensor shall be under the terms and conditions of +> this License, without any additional terms or conditions. +> Notwithstanding the above, nothing herein shall supersede or modify +> the terms of any separate license agreement you may have executed +> with Licensor regarding such Contributions. +> +> 6. Trademarks. This License does not grant permission to use the trade +> names, trademarks, service marks, or product names of the Licensor, +> except as required for reasonable and customary use in describing the +> origin of the Work and reproducing the content of the NOTICE file. +> +> 7. Disclaimer of Warranty. Unless required by applicable law or +> agreed to in writing, Licensor provides the Work (and each +> Contributor provides its Contributions) on an "AS IS" BASIS, +> WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +> implied, including, without limitation, any warranties or conditions +> of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A +> PARTICULAR PURPOSE. You are solely responsible for determining the +> appropriateness of using or redistributing the Work and assume any +> risks associated with Your exercise of permissions under this License. +> +> 8. Limitation of Liability. In no event and under no legal theory, +> whether in tort (including negligence), contract, or otherwise, +> unless required by applicable law (such as deliberate and grossly +> negligent acts) or agreed to in writing, shall any Contributor be +> liable to You for damages, including any direct, indirect, special, +> incidental, or consequential damages of any character arising as a +> result of this License or out of the use or inability to use the +> Work (including but not limited to damages for loss of goodwill, +> work stoppage, computer failure or malfunction, or any and all +> other commercial damages or losses), even if such Contributor +> has been advised of the possibility of such damages. +> +> 9. Accepting Warranty or Additional Liability. While redistributing +> the Work or Derivative Works thereof, You may choose to offer, +> and charge a fee for, acceptance of support, warranty, indemnity, +> or other liability obligations and/or rights consistent with this +> License. However, in accepting such obligations, You may act only +> on Your own behalf and on Your sole responsibility, not on behalf +> of any other Contributor, and only if You agree to indemnify, +> defend, and hold each Contributor harmless for any liability +> incurred by, or claims asserted against, such Contributor by reason +> of your accepting any such warranty or additional liability. +> +> END OF TERMS AND CONDITIONS +> +> APPENDIX: How to apply the Apache License to your work. +> +> To apply the Apache License to your work, attach the following +> boilerplate notice, with the fields enclosed by brackets "[]" +> replaced with your own identifying information. (Don't include +> the brackets!) The text should be enclosed in the appropriate +> comment syntax for the file format. We also recommend that a +> file or class name and description of purpose be included on the +> same "printed page" as the copyright notice for easier +> identification within third-party archives. +> +> Copyright [yyyy] [name of copyright owner] +> +> Licensed under the Apache License, Version 2.0 (the "License"); +> you may not use this file except in compliance with the License. +> You may obtain a copy of the License at +> +> http://www.apache.org/licenses/LICENSE-2.0 +> +> Unless required by applicable law or agreed to in writing, software +> distributed under the License is distributed on an "AS IS" BASIS, +> WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +> See the License for the specific language governing permissions and +> limitations under the License. + ### Public domain data from Natural Earth Free vector and raster map data @ naturalearthdata.com diff --git a/packages/sandcastle/package.json b/packages/sandcastle/package.json index 241fbca4496..7b62bdf7271 100644 --- a/packages/sandcastle/package.json +++ b/packages/sandcastle/package.json @@ -11,6 +11,7 @@ }, "dependencies": { "@ariakit/react": "^0.4.17", + "@huggingface/transformers": "^3.3.1", "@monaco-editor/react": "^4.7.0", "@stratakit/bricks": "^0.3.4", "@stratakit/foundations": "^0.2.4", diff --git a/packages/sandcastle/scripts/buildGallery.js b/packages/sandcastle/scripts/buildGallery.js index 16d5e0cca41..17a73859757 100644 --- a/packages/sandcastle/scripts/buildGallery.js +++ b/packages/sandcastle/scripts/buildGallery.js @@ -9,6 +9,7 @@ import { rimraf } from "rimraf"; import { parse } from "yaml"; import { globby } from "globby"; import * as pagefind from "pagefind"; +import { AutoModel, AutoTokenizer } from "@huggingface/transformers"; import createGalleryRecord from "./createGalleryRecord.js"; @@ -20,6 +21,63 @@ const defaultThumbnailPath = "images/placeholder-thumbnail.jpg"; const requiredMetadataKeys = ["title", "description"]; const galleryItemConfig = /sandcastle\.(yml|yaml)/; +// Embedding configuration +const MODEL_ID = "avsolatorio/GIST-small-Embedding-v0"; + +/** + * Initialize the embedding model (singleton pattern) + */ +let embeddingModel = null; +let embeddingTokenizer = null; + +async function initEmbeddingModel() { + if (embeddingModel && embeddingTokenizer) { + return { model: embeddingModel, tokenizer: embeddingTokenizer }; + } + + console.log("Loading embedding model..."); + console.log("This may take a while on first run as the model is downloaded."); + + embeddingTokenizer = await AutoTokenizer.from_pretrained(MODEL_ID); + embeddingModel = await AutoModel.from_pretrained(MODEL_ID, { + dtype: "fp32", + }); + + return { model: embeddingModel, tokenizer: embeddingTokenizer }; +} + +function itemToText(title, description, labels) { + const text = `Title: ${title} +Description: ${description} +Labels: ${labels.join(", ")}`; + + return text; +} + +/** + * Generate embeddings for a batch of items + */ +async function generateEmbeddings(items) { + const { model, tokenizer } = await initEmbeddingModel(); + + console.log(`\nGenerating embeddings for ${items.length} gallery items...`); + + const texts = items.map((item) => + itemToText(item.title, item.description, item.labels), + ); + + const embeddings = []; + + const inputs = await tokenizer(texts, { padding: true, truncation: true }); + const { sentence_embedding } = await model(inputs); + + const batchEmbeddings = sentence_embedding.tolist(); + embeddings.push(...batchEmbeddings); + + console.log(`Generated ${embeddings.length} embeddings`); + return embeddings; +} + async function createPagefindIndex() { try { const { index } = await pagefind.createIndex({ @@ -89,6 +147,7 @@ export async function buildGalleryList(options = {}) { * @property {number} lineCount * @property {string} description * @property {string[]} labels + * @property {number[]} [embedding] - Vector embedding for semantic search */ /** @@ -117,6 +176,7 @@ export async function buildGalleryList(options = {}) { return condition; }; + const galleryFiles = await globby( galleryFilesPattern.map((pattern) => // globby can only work with paths using '/' but node on windows uses '\' @@ -274,6 +334,21 @@ export async function buildGalleryList(options = {}) { // regardless of if titles match the directory names output.entries.sort((a, b) => a.title.localeCompare(b.title)); + // Generate embeddings for all entries + try { + const embeddings = await generateEmbeddings(output.entries); + // Add embeddings to each entry + output.entries.forEach((entry, index) => { + entry.embedding = embeddings[index]; + }); + console.log( + `\n✓ Successfully added embeddings to ${output.entries.length} gallery items`, + ); + } catch (error) { + console.error("Failed to generate embeddings:", error); + console.log("Continuing without embeddings..."); + } + const outputDirectory = join(rootDirectory, publicDirectory, "gallery"); await rimraf(outputDirectory); await mkdir(outputDirectory, { recursive: true }); diff --git a/packages/sandcastle/src/Gallery/EmbeddingSearch.ts b/packages/sandcastle/src/Gallery/EmbeddingSearch.ts new file mode 100644 index 00000000000..1e52fe89e7e --- /dev/null +++ b/packages/sandcastle/src/Gallery/EmbeddingSearch.ts @@ -0,0 +1,219 @@ +import { AutoModel, AutoTokenizer } from '@huggingface/transformers'; + +export interface VectorSearchResult { + rank: number; + id: string; + legacy_id: string; + title: string; + description: string; + labels: string[]; + distance: number; + score: number; + url: string; +} + +interface GalleryListItem { + url: string; + id: string; + title: string; + thumbnail: string; + lineCount: number; + description: string; + labels: string[]; + embedding?: number[]; +} + +interface GalleryList { + entries: GalleryListItem[]; + legacyIds: Record; +} + +class EmbeddingSearch { + private galleryList: GalleryList | null = null; + private tokenizer: any = null; + private model: any = null; + private modelId: string = 'avsolatorio/GIST-small-Embedding-v0'; + private loadingPromise: Promise | null = null; + + /** + * Load the gallery list with embeddings + */ + private async loadGalleryList(): Promise { + if (this.galleryList) return; + + try { + const response = await fetch('/gallery/list.json'); + if (!response.ok) { + throw new Error(`Failed to load gallery list: ${response.statusText}`); + } + this.galleryList = await response.json(); + + // Verify that embeddings are present + const itemsWithEmbeddings = this.galleryList!.entries.filter(item => item.embedding); + if (itemsWithEmbeddings.length === 0) { + throw new Error('No embeddings found in gallery list. Run the build script to generate them.'); + } + + console.log(`Loaded ${itemsWithEmbeddings.length} gallery items with embeddings`); + } catch (error) { + console.error('Failed to load gallery list:', error); + throw error; + } + } + + /** + * Initialize the embedding model + */ + private async loadModel(): Promise { + if (this.model && this.tokenizer) return; + + try { + console.log(`Loading embedding model: ${this.modelId} (this may take a moment on first load)...`); + this.tokenizer = await AutoTokenizer.from_pretrained(this.modelId); + this.model = await AutoModel.from_pretrained(this.modelId); + console.log(`Embedding model loaded successfully: ${this.modelId}`); + } catch (error) { + console.error('Failed to load embedding model:', error); + throw error; + } + } + + /** + * Initialize both the gallery list and the model + */ + async initialize(): Promise { + // If already fully initialized, return immediately + if (this.galleryList && this.model && this.tokenizer) { + return; + } + + // If currently loading, wait for that to finish + if (this.loadingPromise) { + return this.loadingPromise; + } + + // Start loading + this.loadingPromise = (async () => { + await Promise.all([ + this.loadGalleryList(), + this.loadModel(), + ]); + // Clear the promise after successful initialization + this.loadingPromise = null; + })(); + + return this.loadingPromise; + } + + /** + * Calculate cosine similarity between two vectors + */ + private cosineSimilarity(vecA: number[], vecB: number[]): number { + if (vecA.length !== vecB.length) { + throw new Error('Vectors must have the same length'); + } + + let dotProduct = 0; + let normA = 0; + let normB = 0; + + for (let i = 0; i < vecA.length; i++) { + dotProduct += vecA[i] * vecB[i]; + normA += vecA[i] * vecA[i]; + normB += vecB[i] * vecB[i]; + } + + return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB)); + } + + /** + * Perform a vector similarity search + * @param query - The search query text + * @param limit - Maximum number of results to return + * @returns Array of search results ranked by relevance + */ + async search(query: string, limit: number = 10): Promise { + if (!query || query.trim().length === 0) { + return []; + } + + try { + if (!this.galleryList || !this.model || !this.tokenizer) { + await this.initialize(); + } + + if (!this.galleryList || !this.model || !this.tokenizer) { + throw new Error('Vector search not properly initialized'); + } + + const inputs = await this.tokenizer([query.trim()], { padding: true, truncation: true }); + + const { sentence_embedding } = await this.model(inputs); + const queryEmbedding = sentence_embedding.tolist()[0]; + + const itemsWithEmbeddings = this.galleryList.entries.filter(item => item.embedding); + const results = itemsWithEmbeddings.map((item) => { + const score = this.cosineSimilarity(queryEmbedding, item.embedding!); + return { + ...item, + score, + distance: 1 - score, // Convert similarity to distance + }; + }); + + results.sort((a, b) => b.score - a.score); + const topResults = results.slice(0, limit); + + // Format results to match expected interface + const formattedResults = topResults.map((result, index) => ({ + rank: index + 1, + id: result.id, + legacy_id: result.id, // Use id as legacy_id for compatibility + title: result.title, + description: result.description, + labels: result.labels, + distance: result.distance, + score: result.score, + url: result.url, + })); + + return formattedResults; + } catch (error) { + console.error('[EmbeddingSearch] Search failed:', error); + // Return empty results on error so the app can continue + return []; + } + } + + /** + * Check if the search service is ready + */ + isReady(): boolean { + return this.galleryList !== null && this.model !== null && this.tokenizer !== null; + } +} + +const embeddingSearch = new EmbeddingSearch(); + +// Pre-load the model and gallery list at application startup +// This happens in the background so the UI can load while the model downloads +if (typeof window !== 'undefined') { + // Start loading immediately when the module is imported + embeddingSearch.initialize().then(() => { + console.log('[EmbeddingSearch] Model and embeddings pre-loaded and ready for search!'); + }).catch((error) => { + console.error('[EmbeddingSearch] Failed to pre-load model:', error); + }); +} + +/** + * Performs vector search using the local embedding model + * @param query - The search query string + * @param limit - Maximum number of results to return (default: 10) + * @returns Promise resolving to array of search results + */ +export async function vectorSearch(query: string, limit: number = 10): Promise { + return embeddingSearch.search(query, limit); +} + +export { embeddingSearch }; diff --git a/packages/sandcastle/src/Gallery/GalleryItemSearchInput.tsx b/packages/sandcastle/src/Gallery/GalleryItemSearchInput.tsx index befb4e6e972..64939c5325f 100644 --- a/packages/sandcastle/src/Gallery/GalleryItemSearchInput.tsx +++ b/packages/sandcastle/src/Gallery/GalleryItemSearchInput.tsx @@ -8,35 +8,30 @@ export function GalleryItemSearchInput() { const store = useGalleryItemContext(); const inputRef = useRef(null); const { setSearchTerm, items } = store ?? {}; - const [hasValue, setHasValue] = useState(false); + const [inputValue, setInputValue] = useState(""); const clearSearch = useCallback(() => { - const input = inputRef.current; - if (input) { - input.value = ""; - setHasValue(false); - input.focus(); - } - + setInputValue(""); + if (setSearchTerm) { setSearchTerm(null); } + + // Focus input after clearing + setTimeout(() => inputRef.current?.focus(), 0); }, [setSearchTerm]); const updateSearch = useCallback( (e: { target: { value: string | null } }) => { - let term = e.target.value; - setHasValue(!!term && term !== ""); + let term = e.target.value || ""; + + // Update local state immediately for responsive input + setInputValue(term); + + // Update search term in store if (setSearchTerm) { - if (term) { - term = term.trim(); - } - - if (!term || term === "") { - term = null; - } - - setSearchTerm(term); + const trimmed = term.trim(); + setSearchTerm(trimmed || null); } }, [setSearchTerm], @@ -50,12 +45,13 @@ export function GalleryItemSearchInput() {