Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Desktop ORT MVP

laurenspriem5206388637c1
diff --git a/.github/workflows/desktop-lint.yml b/.github/workflows/desktop-lint.yml
index 7b5723e55e..6082a0f0a9 100644
--- a/.github/workflows/desktop-lint.yml
+++ b/.github/workflows/desktop-lint.yml
@@ -5,6 +5,7 @@ on:
paths:
- ".github/workflows/desktop-lint.yml"
- "desktop/**"
+ - "rust/bindings/napi/**"
permissions:
contents: read
@@ -28,4 +29,17 @@ jobs:
- run: npm ci
+ # Restore-only; primed on main by warm-caches.yml.
+ - name: Restore Rust cache
+ uses: Swatinem/rust-cache@c19371144df3bb44fab255c43d04cbc2ab54d1c4 # v2.9.1
+ with:
+ workspaces: rust
+ shared-key: rust-workspace
+ save-if: false
+
+ # tsc typechecks against the generated rust-bindings/index.d.ts.
+ - name: Generate ML addon bindings
+ working-directory: rust
+ run: cargo codegen napi
+
- run: npm run lint
diff --git a/.github/workflows/photos-desktop-build.yml b/.github/workflows/photos-desktop-build.yml
index d02c1e2088..21d0de3ccc 100644
--- a/.github/workflows/photos-desktop-build.yml
+++ b/.github/workflows/photos-desktop-build.yml
@@ -109,6 +109,26 @@ jobs:
- name: Install dependencies
run: npm ci
+ - name: Setup Rust cache
+ uses: Swatinem/rust-cache@c19371144df3bb44fab255c43d04cbc2ab54d1c4 # v2.9.1
+ with:
+ workspaces: rust
+ shared-key: rust-desktop
+
+ # The packaged app is universal on macOS, and windows/linux also
+ # build arm64 targets, so the Rust ML addon needs the non-host
+ # target toolchains too (see [Note: Packaging the ML addon]).
+ - name: Add Rust cross-compilation targets
+ shell: bash
+ run: |
+ if [ "${RUNNER_OS}" = "macOS" ]; then
+ rustup target add x86_64-apple-darwin
+ elif [ "${RUNNER_OS}" = "Windows" ]; then
+ rustup target add aarch64-pc-windows-msvc
+ else
+ rustup target add aarch64-unknown-linux-gnu
+ fi
+
- name: Fetch binary dependencies and rebuild native modules
run: npm run postinstall
diff --git a/desktop/.gitignore b/desktop/.gitignore
index 7684c8e7c6..33dcd9a63e 100644
--- a/desktop/.gitignore
+++ b/desktop/.gitignore
@@ -14,3 +14,12 @@ dist/
# We download it on demand, if needed for the particular OS/arch.
build/vips*
+
+# Downloaded by scripts/ort.js for the particular OS/arch.
+build/onnxruntime/
+
+# Rust ML addons staged for packaging by scripts/ml-native.js.
+build/ml-native/
+
+# The Rust ML addon and its generated bindings, built by `cargo codegen napi`.
+rust-bindings/
diff --git a/desktop/docs/dependencies.md b/desktop/docs/dependencies.md
index 0a093615e9..7117a14b3d 100644
--- a/desktop/docs/dependencies.md
+++ b/desktop/docs/dependencies.md
@@ -74,9 +74,9 @@ On macOS, we use the `sips` CLI tool for these tasks, but that is already availa
### ML
-[onnxruntime-node](https://github.com/Microsoft/onnxruntime) is used as the ML runtime. It powers both natural language searches (using CLIP) and face detection (using YOLO).
+The ML pipeline (natural language search using CLIP, and face detection and recognition) is implemented by the Rust crate shared with the mobile apps (`rust/crates/photos`), exposed to us as a Node native addon built from source by `cargo codegen napi` (see "[Note: ML with Rust]").
-[clip-bpe-js](https://github.com/simonwarchol/clip-bpe-js) is used for tokening the user's search phrase before computing its CLIP (text) embedding.
+The addon loads [ONNX Runtime](https://onnxruntime.ai) dynamically at runtime, using Ente's pinned custom builds (CoreML-enabled on macOS) that `scripts/ort.js` downloads into the extra resources (`build`) folder. See "[Note: ONNX Runtime binaries]".
### ZIP
diff --git a/desktop/docs/dev.md b/desktop/docs/dev.md
index 5370ffe9f0..41b40cfb0b 100644
--- a/desktop/docs/dev.md
+++ b/desktop/docs/dev.md
@@ -12,7 +12,7 @@ Use `npm ci` to install dependencies using the committed lockfile. You need this
Use `npm install <package>` only when intentionally adding or updating dependencies, and review the resulting `package.json` and `package-lock.json` changes.
-The desktop app embeds the Photos web app, so local development also requires installing dependencies in `../web`:
+The desktop app embeds the Photos web app, so local development also requires installing dependencies in `../web`. The ML pipeline is implemented by the Rust crate shared with the mobile apps and built from source (see [Note: ML with Rust]), so a [Rust toolchain](https://rustup.rs) is also required.
```sh
cd ../web
@@ -45,12 +45,16 @@ During development, you might find `npm run build:quick` helpful. It is a varian
Installs skip dependency lifecycle scripts (`ignore-scripts` in `.npmrc`) so that installing cannot run arbitrary code from packages. The flip side is that our own postinstall does not run automatically either, so it must be invoked explicitly. `npm run dev` runs it automatically if it hasn't run for the currently installed dependencies; for other flows (e.g. `npm run build`) run it yourself after `npm ci`. It:
-- Runs the install scripts of the dependencies that fetch prebuilt binaries (`ffmpeg-static`, `onnxruntime-node`, `electron-winstaller`).
+- Runs the install scripts of the dependencies that fetch prebuilt binaries (`ffmpeg-static`, `electron-winstaller`).
- Runs [electron-builder](https://www.electron.build/cli)'s `install-app-deps` command to rebuild native node modules (those written in C/C++) against `electron`'s packaged `node` version.
- Downloads the `vips` binary used during development (see `scripts/vips.js`).
+- Downloads the ONNX Runtime library used by the ML pipeline (see `scripts/ort.js`).
+
+- Builds the Rust ML addon from source by running `cargo codegen napi`, which places the built addon and its generated TypeScript declarations in the gitignored `rust-bindings/` directory. Rerun this codegen (from `../rust`) after changing the Rust ML code.
+
### lint, lint:fix
Use `npm run lint` to check that your code formatting is as expected, and that there are no linter errors. Use `npm run lint:fix` to try and automatically fix the issues.
diff --git a/desktop/electron-builder.yml b/desktop/electron-builder.yml
index c41af53c35..5a9a3491ab 100644
--- a/desktop/electron-builder.yml
+++ b/desktop/electron-builder.yml
@@ -11,9 +11,6 @@ protocols:
- name: Ente
schemes: ["ente"]
win:
- files:
- - "!node_modules/onnxruntime-node/bin/napi-v6/{darwin,linux}/**/*"
- - "!node_modules/onnxruntime-node/bin/napi-v6/win32/!(${arch})/**/*"
target:
- target: nsis
arch: [x64, arm64]
@@ -26,9 +23,6 @@ win:
nsis:
deleteAppDataOnUninstall: true
linux:
- files:
- - "!node_modules/onnxruntime-node/bin/napi-v6/{darwin,win32}/**/*"
- - "!node_modules/onnxruntime-node/bin/napi-v6/linux/!(${arch})/**/*"
target:
- target: AppImage
arch: [x64, arm64]
@@ -41,12 +35,13 @@ linux:
category: Photography
icon: ./build/icon.icns
mac:
- files:
- - "!node_modules/onnxruntime-node/bin/napi-v6/{linux,win32}/**/*"
target:
target: default
arch: [universal]
category: public.app-category.photography
hardenedRuntime: true
mergeASARs: false
- x64ArchFiles: "**/node_modules/onnxruntime-node/bin/napi-v6/darwin/**"
+ # The Rust ML addon and the ONNX Runtime library are shipped as separate
+ # per-arch Mach-Os (in both slices of the universal build) instead of fat
+ # binaries; the app picks the one matching the process arch at runtime.
+ x64ArchFiles: "**/{ml-native,onnxruntime}/**"
diff --git a/desktop/package-lock.json b/desktop/package-lock.json
index 0de973f0c4..0b2b6f2eed 100644
--- a/desktop/package-lock.json
+++ b/desktop/package-lock.json
@@ -12,7 +12,6 @@
"any-shell-escape": "0.1.1",
"auto-launch": "5.0.6",
"chokidar": "4.0.3",
- "clip-bpe-js": "0.0.6",
"comlink": "4.4.2",
"compare-versions": "6.1.1",
"electron-log": "5.4.4",
@@ -22,11 +21,11 @@
"lru-cache": "11.5.1",
"next-electron-server": "1.0.0",
"node-stream-zip": "1.15.0",
- "onnxruntime-node": "1.22.0-rev",
"zod": "4.4.3"
},
"devDependencies": {
"@eslint/js": "10.0.1",
+ "@napi-rs/cli": "3.7.4",
"@types/auto-launch": "5.0.5",
"@types/node": "24.13.0",
"ajv": "8.20.0",
@@ -427,6 +426,40 @@
"node": ">=14.14"
}
},
+ "node_modules/@emnapi/core": {
+ "version": "1.11.2",
+ "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.2.tgz",
+ "integrity": "sha512-TC8MkTuZUtcTSiFeuC0ksCh9QIJ5+F21MvZ4Wn4ORfYaFJ/0dsiudv5tVkejgwZlwQ39jL9WWDe2lz8x0WglOA==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@emnapi/wasi-threads": "1.2.2",
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@emnapi/runtime": {
+ "version": "1.11.2",
+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.2.tgz",
+ "integrity": "sha512-kyOl3X0DuTiT1h2ft8r2fYO8JYtU9a9Xis/zBSiGArNaagCOWx90N1k2wxp18czFDH+OgcWGb5ZP/XMt3dcyPA==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@emnapi/wasi-threads": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.2.tgz",
+ "integrity": "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
"node_modules/@epic-web/invariant": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@epic-web/invariant/-/invariant-1.0.0.tgz",
@@ -600,138 +633,1737 @@
"node": ">=18.18.0"
}
},
- "node_modules/@humanwhocodes/module-importer": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz",
- "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==",
+ "node_modules/@humanwhocodes/module-importer": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz",
+ "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=12.22"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/nzakas"
+ }
+ },
+ "node_modules/@humanwhocodes/retry": {
+ "version": "0.4.3",
+ "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz",
+ "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=18.18"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/nzakas"
+ }
+ },
+ "node_modules/@inquirer/ansi": {
+ "version": "2.0.7",
+ "resolved": "https://registry.npmjs.org/@inquirer/ansi/-/ansi-2.0.7.tgz",
+ "integrity": "sha512-3eTuUO1vH2cZm2ZKHeQxnOqlTi9EfZDGgIe3BL3I4u+rJHocr9Fz86M4fjYABPvFnQG/gGK551HqDiIcETwU6Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ }
+ },
+ "node_modules/@inquirer/checkbox": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/@inquirer/checkbox/-/checkbox-5.2.1.tgz",
+ "integrity": "sha512-b6xmA/VlTe0ZgDQHDui+Nav470u7u49nRd8/iuhOcQPO9Ch7lGuogydhi2VOmNlZ+zXcM8IcPuNSwQcdJaF/kw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@inquirer/ansi": "^2.0.7",
+ "@inquirer/core": "^11.2.1",
+ "@inquirer/figures": "^2.0.7",
+ "@inquirer/type": "^4.0.7"
+ },
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ },
+ "peerDependencies": {
+ "@types/node": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@inquirer/confirm": {
+ "version": "6.1.1",
+ "resolved": "https://registry.npmjs.org/@inquirer/confirm/-/confirm-6.1.1.tgz",
+ "integrity": "sha512-eb8DBZcz/2qHWQda4rk2JiQk5h9QV/cVHi1yjt0f69WFZMRFn0sJTye3EAP8icut8UDMjQPsaH5KbcOogefrFQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@inquirer/core": "^11.2.1",
+ "@inquirer/type": "^4.0.7"
+ },
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ },
+ "peerDependencies": {
+ "@types/node": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@inquirer/core": {
+ "version": "11.2.1",
+ "resolved": "https://registry.npmjs.org/@inquirer/core/-/core-11.2.1.tgz",
+ "integrity": "sha512-Qd6GJT1yVyrZZCfN8W2qKF5ApmqryXRhRKCuip8h01x2w/esJQ2XIYc6f9abMIHgKQdBfFTSOdbHRLAhuM09UA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@inquirer/ansi": "^2.0.7",
+ "@inquirer/figures": "^2.0.7",
+ "@inquirer/type": "^4.0.7",
+ "cli-width": "^4.1.0",
+ "fast-wrap-ansi": "^0.2.0",
+ "mute-stream": "^3.0.0",
+ "signal-exit": "^4.1.0"
+ },
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ },
+ "peerDependencies": {
+ "@types/node": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@inquirer/core/node_modules/signal-exit": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz",
+ "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">=14"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "node_modules/@inquirer/editor": {
+ "version": "5.2.2",
+ "resolved": "https://registry.npmjs.org/@inquirer/editor/-/editor-5.2.2.tgz",
+ "integrity": "sha512-ZRVd/oD+sYsUd5zVm0NflqEzlqfYCyHNsqkHl2oWXEUHs12tCbcSFi+wVFEvD8+LGRaMUsVrE7qeo6lSG/S1Vg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@inquirer/core": "^11.2.1",
+ "@inquirer/external-editor": "^3.0.3",
+ "@inquirer/type": "^4.0.7"
+ },
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ },
+ "peerDependencies": {
+ "@types/node": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@inquirer/expand": {
+ "version": "5.1.1",
+ "resolved": "https://registry.npmjs.org/@inquirer/expand/-/expand-5.1.1.tgz",
+ "integrity": "sha512-YmQpenjbFSHAK3sOd44puHh3V1KXXr+JiNpUztoSQ4drLh2rTVzTap/YtlAVu/5xavifIlBfNEzJ/neZJ1a/1g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@inquirer/core": "^11.2.1",
+ "@inquirer/type": "^4.0.7"
+ },
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ },
+ "peerDependencies": {
+ "@types/node": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@inquirer/external-editor": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/@inquirer/external-editor/-/external-editor-3.0.3.tgz",
+ "integrity": "sha512-6thf5I8q7lZwzGLAxPaaGEREEkZ3nyePPDQ1oyobblxmEE8mqTLguScP7pDjUTAibiyb4hfXl+qjUEJ+di/aNA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "chardet": "^2.1.1",
+ "iconv-lite": "^0.7.2"
+ },
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ },
+ "peerDependencies": {
+ "@types/node": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@inquirer/external-editor/node_modules/iconv-lite": {
+ "version": "0.7.3",
+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz",
+ "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "safer-buffer": ">= 2.1.2 < 3.0.0"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/@inquirer/figures": {
+ "version": "2.0.7",
+ "resolved": "https://registry.npmjs.org/@inquirer/figures/-/figures-2.0.7.tgz",
+ "integrity": "sha512-aJ8TBPOGB6f/2qziPfElISTCEd5XOYTFckA2SGjhNmiKzfK/u4ot3v0DUzGVdUnKjN10EqnnEPck36BkyfLnJw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ }
+ },
+ "node_modules/@inquirer/input": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/@inquirer/input/-/input-5.1.2.tgz",
+ "integrity": "sha512-9K/DDBSQpOyZSkt6sOVP9Vo0TR7atX2kuILsUu0x3wVcVbe97lJwIJKMLdMw25tDYuXl/qp6erT0Xs1rfmcfZg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@inquirer/core": "^11.2.1",
+ "@inquirer/type": "^4.0.7"
+ },
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ },
+ "peerDependencies": {
+ "@types/node": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@inquirer/number": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/@inquirer/number/-/number-4.1.1.tgz",
+ "integrity": "sha512-XF4IXAbPnGPgw0wsbC/i2tPcyfdZgDpUlhsqU0SfT4IRIGWha6Xm9VRgN5yYxJq+jnyXlfXI/nQ3ulfk0iEICA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@inquirer/core": "^11.2.1",
+ "@inquirer/type": "^4.0.7"
+ },
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ },
+ "peerDependencies": {
+ "@types/node": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@inquirer/password": {
+ "version": "5.1.1",
+ "resolved": "https://registry.npmjs.org/@inquirer/password/-/password-5.1.1.tgz",
+ "integrity": "sha512-3XBfF7DAsp5qeDsvN5Rd1HmbNokVvEQoUM0QLrRcybC9nX96w3Pbmu7qUsb3IT3J3jBvs2+mTXaKHOUsgHMLzg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@inquirer/ansi": "^2.0.7",
+ "@inquirer/core": "^11.2.1",
+ "@inquirer/type": "^4.0.7"
+ },
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ },
+ "peerDependencies": {
+ "@types/node": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@inquirer/prompts": {
+ "version": "8.5.2",
+ "resolved": "https://registry.npmjs.org/@inquirer/prompts/-/prompts-8.5.2.tgz",
+ "integrity": "sha512-IYR/3C/paEVVQYQvdDlFZVjRCJVYHHON0XXMH91KO9GSxs0TdKYWlUdvfQl2EfAHDxUaN3IBffkE/BDTh5nJ6g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@inquirer/checkbox": "^5.2.1",
+ "@inquirer/confirm": "^6.1.1",
+ "@inquirer/editor": "^5.2.2",
+ "@inquirer/expand": "^5.1.1",
+ "@inquirer/input": "^5.1.2",
+ "@inquirer/number": "^4.1.1",
+ "@inquirer/password": "^5.1.1",
+ "@inquirer/rawlist": "^5.3.1",
+ "@inquirer/search": "^4.2.1",
+ "@inquirer/select": "^5.2.1"
+ },
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ },
+ "peerDependencies": {
+ "@types/node": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@inquirer/rawlist": {
+ "version": "5.3.1",
+ "resolved": "https://registry.npmjs.org/@inquirer/rawlist/-/rawlist-5.3.1.tgz",
+ "integrity": "sha512-QqdTqQddL3qPX/PPrjobpsO25NZ4dWXgTLenrR445L2ptLEYE6Z+PD5c5CNDJNx4ugRgELAIpSIJxZaO2jJ2Og==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@inquirer/core": "^11.2.1",
+ "@inquirer/type": "^4.0.7"
+ },
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ },
+ "peerDependencies": {
+ "@types/node": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@inquirer/search": {
+ "version": "4.2.1",
+ "resolved": "https://registry.npmjs.org/@inquirer/search/-/search-4.2.1.tgz",
+ "integrity": "sha512-xJj8QWKRSrfKoBIITLZK61dD3zwo0Rz11fgDImku30/Oe81zMdIdGgrLY2h6RkJ+KZ/GhNYIRMKnH/62qBTA5g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@inquirer/core": "^11.2.1",
+ "@inquirer/figures": "^2.0.7",
+ "@inquirer/type": "^4.0.7"
+ },
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ },
+ "peerDependencies": {
+ "@types/node": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@inquirer/select": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/@inquirer/select/-/select-5.2.1.tgz",
+ "integrity": "sha512-FlDndEUww8m7BfukO2nJa25vhD+H5jxxCv4oGioKqzyWz3nPHhhw4LKdYRSlXuAx7DsdWia7iyaBPKKS95Evfw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@inquirer/ansi": "^2.0.7",
+ "@inquirer/core": "^11.2.1",
+ "@inquirer/figures": "^2.0.7",
+ "@inquirer/type": "^4.0.7"
+ },
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ },
+ "peerDependencies": {
+ "@types/node": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@inquirer/type": {
+ "version": "4.0.7",
+ "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-4.0.7.tgz",
+ "integrity": "sha512-t28inv14nMQ1PhKpsJPY+kEs/c00qzeCOS2gTNRyTjG5d6qsVA2fItxW4hkvGZ5lvanGLdtCzVIx5dwdRpN1+g==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ },
+ "peerDependencies": {
+ "@types/node": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@isaacs/fs-minipass": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz",
+ "integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "minipass": "^7.0.4"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/@malept/cross-spawn-promise": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/@malept/cross-spawn-promise/-/cross-spawn-promise-2.0.0.tgz",
+ "integrity": "sha512-1DpKU0Z5ThltBwjNySMC14g0CkbyhCaz9FkhxqNsZI6uAPJXFS8cMXlBKo26FJ8ZuW6S9GCMcR9IO5k2X5/9Fg==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://github.com/sponsors/malept"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/subscription/pkg/npm-.malept-cross-spawn-promise?utm_medium=referral&utm_source=npm_fund"
+ }
+ ],
+ "license": "Apache-2.0",
+ "dependencies": {
+ "cross-spawn": "^7.0.1"
+ },
+ "engines": {
+ "node": ">= 12.13.0"
+ }
+ },
+ "node_modules/@malept/flatpak-bundler": {
+ "version": "0.4.0",
+ "resolved": "https://registry.npmjs.org/@malept/flatpak-bundler/-/flatpak-bundler-0.4.0.tgz",
+ "integrity": "sha512-9QOtNffcOF/c1seMCDnjckb3R9WHcG34tky+FHpNKKCW0wc/scYLwMtO+ptyGUfMW0/b/n4qRiALlaFHc9Oj7Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^4.1.1",
+ "fs-extra": "^9.0.0",
+ "lodash": "^4.17.15",
+ "tmp-promise": "^3.0.2"
+ },
+ "engines": {
+ "node": ">= 10.0.0"
+ }
+ },
+ "node_modules/@malept/flatpak-bundler/node_modules/fs-extra": {
+ "version": "9.1.0",
+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz",
+ "integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "at-least-node": "^1.0.0",
+ "graceful-fs": "^4.2.0",
+ "jsonfile": "^6.0.1",
+ "universalify": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/@napi-rs/cli": {
+ "version": "3.7.4",
+ "resolved": "https://registry.npmjs.org/@napi-rs/cli/-/cli-3.7.4.tgz",
+ "integrity": "sha512-idELIUceJ9zPgx/shcMt1fSSsteFG68v56RIXi4qUm7OYuJOt7CoMj2KnHVmbOqXgUHWQU1lCULrtQdZDG4F5A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@inquirer/prompts": "^8.5.2",
+ "@napi-rs/cross-toolchain": "^1.0.3",
+ "@napi-rs/wasm-tools": "^1.0.1",
+ "@octokit/rest": "^22.0.1",
+ "clipanion": "^4.0.0-rc.4",
+ "colorette": "^2.0.20",
+ "emnapi": "^1.11.1",
+ "es-toolkit": "^1.47.0",
+ "js-yaml": "^4.2.0",
+ "obug": "^2.1.2",
+ "semver": "^7.8.2",
+ "typanion": "^3.14.0"
+ },
+ "bin": {
+ "napi": "dist/cli.js",
+ "napi-raw": "cli.mjs"
+ },
+ "engines": {
+ "node": ">= 16"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ },
+ "peerDependencies": {
+ "@emnapi/runtime": "^1.7.1"
+ },
+ "peerDependenciesMeta": {
+ "@emnapi/runtime": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@napi-rs/cli/node_modules/emnapi": {
+ "version": "1.11.2",
+ "resolved": "https://registry.npmjs.org/emnapi/-/emnapi-1.11.2.tgz",
+ "integrity": "sha512-iMt/XQc69fFn2EvcU6tm14HmXKwyy0lnABugsQlqp6xFuZIUuO+ONVSg2mz+MTVF8WbC+bic65AvRXdoldALKg==",
+ "dev": true,
+ "license": "MIT",
+ "peerDependencies": {
+ "node-addon-api": ">= 6.1.0"
+ },
+ "peerDependenciesMeta": {
+ "node-addon-api": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@napi-rs/cross-toolchain": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/@napi-rs/cross-toolchain/-/cross-toolchain-1.0.3.tgz",
+ "integrity": "sha512-ENPfLe4937bsKVTDA6zdABx4pq9w0tHqRrJHyaGxgaPq03a2Bd1unD5XSKjXJjebsABJ+MjAv1A2OvCgK9yehg==",
+ "dev": true,
+ "license": "MIT",
+ "workspaces": [
+ ".",
+ "arm64/*",
+ "x64/*"
+ ],
+ "dependencies": {
+ "@napi-rs/lzma": "^1.4.5",
+ "@napi-rs/tar": "^1.1.0",
+ "debug": "^4.4.1"
+ },
+ "peerDependencies": {
+ "@napi-rs/cross-toolchain-arm64-target-aarch64": "^1.0.3",
+ "@napi-rs/cross-toolchain-arm64-target-armv7": "^1.0.3",
+ "@napi-rs/cross-toolchain-arm64-target-ppc64le": "^1.0.3",
+ "@napi-rs/cross-toolchain-arm64-target-s390x": "^1.0.3",
+ "@napi-rs/cross-toolchain-arm64-target-x86_64": "^1.0.3",
+ "@napi-rs/cross-toolchain-x64-target-aarch64": "^1.0.3",
+ "@napi-rs/cross-toolchain-x64-target-armv7": "^1.0.3",
+ "@napi-rs/cross-toolchain-x64-target-ppc64le": "^1.0.3",
+ "@napi-rs/cross-toolchain-x64-target-s390x": "^1.0.3",
+ "@napi-rs/cross-toolchain-x64-target-x86_64": "^1.0.3"
+ },
+ "peerDependenciesMeta": {
+ "@napi-rs/cross-toolchain-arm64-target-aarch64": {
+ "optional": true
+ },
+ "@napi-rs/cross-toolchain-arm64-target-armv7": {
+ "optional": true
+ },
+ "@napi-rs/cross-toolchain-arm64-target-ppc64le": {
+ "optional": true
+ },
+ "@napi-rs/cross-toolchain-arm64-target-s390x": {
+ "optional": true
+ },
+ "@napi-rs/cross-toolchain-arm64-target-x86_64": {
+ "optional": true
+ },
+ "@napi-rs/cross-toolchain-x64-target-aarch64": {
+ "optional": true
+ },
+ "@napi-rs/cross-toolchain-x64-target-armv7": {
+ "optional": true
+ },
+ "@napi-rs/cross-toolchain-x64-target-ppc64le": {
+ "optional": true
+ },
+ "@napi-rs/cross-toolchain-x64-target-s390x": {
+ "optional": true
+ },
+ "@napi-rs/cross-toolchain-x64-target-x86_64": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@napi-rs/lzma": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/lzma/-/lzma-1.5.1.tgz",
+ "integrity": "sha512-sgOZ89+y8cDbY+3WbzR8CtIhCuFRWotZ9/2PjPVDJHz6np5KFTAev0DrwiyTJTgFsCRDhfGlbmhMgyhHbWdZ6g==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^22.20 || ^24.12 || >=25"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ },
+ "optionalDependencies": {
+ "@napi-rs/lzma-android-arm-eabi": "1.5.1",
+ "@napi-rs/lzma-android-arm64": "1.5.1",
+ "@napi-rs/lzma-darwin-arm64": "1.5.1",
+ "@napi-rs/lzma-darwin-x64": "1.5.1",
+ "@napi-rs/lzma-freebsd-x64": "1.5.1",
+ "@napi-rs/lzma-linux-arm-gnueabihf": "1.5.1",
+ "@napi-rs/lzma-linux-arm64-gnu": "1.5.1",
+ "@napi-rs/lzma-linux-arm64-musl": "1.5.1",
+ "@napi-rs/lzma-linux-ppc64-gnu": "1.5.1",
+ "@napi-rs/lzma-linux-riscv64-gnu": "1.5.1",
+ "@napi-rs/lzma-linux-s390x-gnu": "1.5.1",
+ "@napi-rs/lzma-linux-x64-gnu": "1.5.1",
+ "@napi-rs/lzma-linux-x64-musl": "1.5.1",
+ "@napi-rs/lzma-wasm32-wasi": "1.5.1",
+ "@napi-rs/lzma-win32-arm64-msvc": "1.5.1",
+ "@napi-rs/lzma-win32-ia32-msvc": "1.5.1",
+ "@napi-rs/lzma-win32-x64-msvc": "1.5.1"
+ }
+ },
+ "node_modules/@napi-rs/lzma-android-arm-eabi": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/lzma-android-arm-eabi/-/lzma-android-arm-eabi-1.5.1.tgz",
+ "integrity": "sha512-sahBe4ko2Z69NPTddaX6ZgbQZu9SDoITxw1S3dWl1gAGynZG34qHHCT8UaUMFxf3h3zMhCJjEzz4basaBxiTuQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^22.20 || ^24.12 || >=25"
+ }
+ },
+ "node_modules/@napi-rs/lzma-android-arm64": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/lzma-android-arm64/-/lzma-android-arm64-1.5.1.tgz",
+ "integrity": "sha512-7tkQAJJuBHxAxiEBNFgSTpvrtGpbwZYYJUSOmGEK3OfbdbNeoT2rdBxpM/gY1s+itEVbtOSlpaRPPG19MnwOzA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^22.20 || ^24.12 || >=25"
+ }
+ },
+ "node_modules/@napi-rs/lzma-darwin-arm64": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/lzma-darwin-arm64/-/lzma-darwin-arm64-1.5.1.tgz",
+ "integrity": "sha512-XWX8gtF+GHGk3nH3Wm3QUZNcxw9QHsFVZz3MzVLhWWHhceede1J4/vD+3dj3E1iKB9G6mualaZxOoD08R3E+7g==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^22.20 || ^24.12 || >=25"
+ }
+ },
+ "node_modules/@napi-rs/lzma-darwin-x64": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/lzma-darwin-x64/-/lzma-darwin-x64-1.5.1.tgz",
+ "integrity": "sha512-CfsqUpMTI1z8enrA/b+GcHM6YDI8D0kqCiqPYEnst4rbOABQ9KZ92ybTTNnlnZ7A017WoMZKUEWc36KXDwi0xg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^22.20 || ^24.12 || >=25"
+ }
+ },
+ "node_modules/@napi-rs/lzma-freebsd-x64": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/lzma-freebsd-x64/-/lzma-freebsd-x64-1.5.1.tgz",
+ "integrity": "sha512-bTyNfg90FXIgE61U7l14aMmVOqRQ6AyP5JMT3jmCStaZI18apLNPdzZ8i7yqxZfKvRMVfPjE2brXIw27c+RRgA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": "^22.20 || ^24.12 || >=25"
+ }
+ },
+ "node_modules/@napi-rs/lzma-linux-arm-gnueabihf": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-arm-gnueabihf/-/lzma-linux-arm-gnueabihf-1.5.1.tgz",
+ "integrity": "sha512-vNE+D8nrw+eOkBsdKCsmDhowDV3pIMKXEhedvXfbgrWbrO7GlZJH+RXL+X+RYLxGwi8Ym61ZMt15sIOnNmh9Sw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^22.20 || ^24.12 || >=25"
+ }
+ },
+ "node_modules/@napi-rs/lzma-linux-arm64-gnu": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-arm64-gnu/-/lzma-linux-arm64-gnu-1.5.1.tgz",
+ "integrity": "sha512-csUem4WgoKGTprv/pOPm9UIWbb+hrfUwYXefpTHPAEGVFLl5behEFabisJ7FtihCa3yG2Efcl+yw25rlhhrIYw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^22.20 || ^24.12 || >=25"
+ }
+ },
+ "node_modules/@napi-rs/lzma-linux-arm64-musl": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-arm64-musl/-/lzma-linux-arm64-musl-1.5.1.tgz",
+ "integrity": "sha512-kB/xhlVN1eLvVmDJSKZEjp5Gg2xDYexNrB5jwpSMbOkeGS6N9AasByPBg5VqCpMYC+zZi7DM458DRhtWYhqXTQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^22.20 || ^24.12 || >=25"
+ }
+ },
+ "node_modules/@napi-rs/lzma-linux-ppc64-gnu": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-ppc64-gnu/-/lzma-linux-ppc64-gnu-1.5.1.tgz",
+ "integrity": "sha512-s28RW0W1yBWQc1nbPdF7tp14koqslY3ZWLVI8uaanX292Dc6ezd4NPVwxEoCNBVON/oD7BmUbWGtyFvmm7dQ5A==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^22.20 || ^24.12 || >=25"
+ }
+ },
+ "node_modules/@napi-rs/lzma-linux-riscv64-gnu": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-riscv64-gnu/-/lzma-linux-riscv64-gnu-1.5.1.tgz",
+ "integrity": "sha512-+lGNwYlIN14YPMTNvYtIJJqHFevDTd6Juw/1NmXbWx/iRd/LLrjhlM/yluMX6pxs6NkOGsuuEXJJrbbEUS59OQ==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^22.20 || ^24.12 || >=25"
+ }
+ },
+ "node_modules/@napi-rs/lzma-linux-s390x-gnu": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-s390x-gnu/-/lzma-linux-s390x-gnu-1.5.1.tgz",
+ "integrity": "sha512-PB44FFWWFrLeQowhcep1hPD1YcLqKlnnY60RMU74qrxTlr4YGEyzeMItJqh2uivBfv9kQScOF/B0J9+Vab/oyw==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^22.20 || ^24.12 || >=25"
+ }
+ },
+ "node_modules/@napi-rs/lzma-linux-x64-gnu": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz",
+ "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^22.20 || ^24.12 || >=25"
+ }
+ },
+ "node_modules/@napi-rs/lzma-linux-x64-musl": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-musl/-/lzma-linux-x64-musl-1.5.1.tgz",
+ "integrity": "sha512-I3nsYrWtrW9JpeCr+mkJIVDt0HY3m6qVUBs5vTtoIvJQxwqf1PBXSy5IS7T53ksQFH2kd2UX8rLxJ7B4WISpZg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^22.20 || ^24.12 || >=25"
+ }
+ },
+ "node_modules/@napi-rs/lzma-wasm32-wasi": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/lzma-wasm32-wasi/-/lzma-wasm32-wasi-1.5.1.tgz",
+ "integrity": "sha512-gy3wwPBa6+XEyA4fUzq6CClrXA1ajXjuVf5zbnHytJRgoHznj+mvpU3+co2fxXwqTCmIpn6KrzqH5bRDztBPhA==",
+ "cpu": [
+ "wasm32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@emnapi/core": "1.11.2",
+ "@emnapi/runtime": "1.11.2",
+ "@napi-rs/wasm-runtime": "^1.1.6"
+ },
+ "engines": {
+ "node": "^22.20 || ^24.12 || >=25"
+ }
+ },
+ "node_modules/@napi-rs/lzma-win32-arm64-msvc": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/lzma-win32-arm64-msvc/-/lzma-win32-arm64-msvc-1.5.1.tgz",
+ "integrity": "sha512-dK+huOsHiyH6oJjij+cnjqFCakk2HgWmpI12Xm4pLUyPphe4ebYoJBgehaNAxprmjFqBQ7nL95YPVz9BHyqmPg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^22.20 || ^24.12 || >=25"
+ }
+ },
+ "node_modules/@napi-rs/lzma-win32-ia32-msvc": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/lzma-win32-ia32-msvc/-/lzma-win32-ia32-msvc-1.5.1.tgz",
+ "integrity": "sha512-dGE8L+0EQ+GyU9ap9InqB/t/PmPG/bLj918q7OsJ29FuTdn8fK4OX3U4IQZhylHIA+/dQ/SXJk5n4yfah2XVvA==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^22.20 || ^24.12 || >=25"
+ }
+ },
+ "node_modules/@napi-rs/lzma-win32-x64-msvc": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/lzma-win32-x64-msvc/-/lzma-win32-x64-msvc-1.5.1.tgz",
+ "integrity": "sha512-EKW4t/iqdCT/xnd5t9oXLvVER/PMNAWXKqUAl3fgvUcOILeZIIht77/dVnfFcc9htA/DCBXC/6YQWdW+LusjFA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^22.20 || ^24.12 || >=25"
+ }
+ },
+ "node_modules/@napi-rs/tar": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/tar/-/tar-1.1.1.tgz",
+ "integrity": "sha512-p6q2HhUc5vwH1CNwfOcrhLoxfgn8ust8Sqlfx+sA4VzAcp1cMbvbkl99tZZlDqOjCHgQNSiTfk/yWPjl/D42qA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 10"
+ },
+ "optionalDependencies": {
+ "@napi-rs/tar-android-arm-eabi": "1.1.1",
+ "@napi-rs/tar-android-arm64": "1.1.1",
+ "@napi-rs/tar-darwin-arm64": "1.1.1",
+ "@napi-rs/tar-darwin-x64": "1.1.1",
+ "@napi-rs/tar-freebsd-x64": "1.1.1",
+ "@napi-rs/tar-linux-arm-gnueabihf": "1.1.1",
+ "@napi-rs/tar-linux-arm64-gnu": "1.1.1",
+ "@napi-rs/tar-linux-arm64-musl": "1.1.1",
+ "@napi-rs/tar-linux-ppc64-gnu": "1.1.1",
+ "@napi-rs/tar-linux-s390x-gnu": "1.1.1",
+ "@napi-rs/tar-linux-x64-gnu": "1.1.1",
+ "@napi-rs/tar-linux-x64-musl": "1.1.1",
+ "@napi-rs/tar-wasm32-wasi": "1.1.1",
+ "@napi-rs/tar-win32-arm64-msvc": "1.1.1",
+ "@napi-rs/tar-win32-ia32-msvc": "1.1.1",
+ "@napi-rs/tar-win32-x64-msvc": "1.1.1"
+ }
+ },
+ "node_modules/@napi-rs/tar-android-arm-eabi": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/tar-android-arm-eabi/-/tar-android-arm-eabi-1.1.1.tgz",
+ "integrity": "sha512-cAhnA10cSusAUbcE9HtjQY/tZ9BH/0w2sKtRcQc94TzIlnm7QSr1htJSd/PPrbWNPtrv1orXb2CkrHlVlbnlHA==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@napi-rs/tar-android-arm64": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/tar-android-arm64/-/tar-android-arm64-1.1.1.tgz",
+ "integrity": "sha512-EslUWHCDBY/g5abTPBiHLsMaML4GagV0TXLm5WL9hAjx/DDtlxz9fegMb77RJ+f7nFLOIsUxF/3QWFvgOT0sMQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@napi-rs/tar-darwin-arm64": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/tar-darwin-arm64/-/tar-darwin-arm64-1.1.1.tgz",
+ "integrity": "sha512-+A42/6ES5G9CQ35BOwzwA+WBjLID28r2jNPgc0dteD2hhClIhng0mva7D2ujUlXBNmgNOsr1LHn3stA4uTf4NQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@napi-rs/tar-darwin-x64": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/tar-darwin-x64/-/tar-darwin-x64-1.1.1.tgz",
+ "integrity": "sha512-RYtE8w1dkEvj8hSJCDV5Jw0Rz2i13fsM7u893zv5O9n/4Ad5GNsw/f4RQ7/0YGSFaenkVxqPFrjmEvUHlKzsrg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@napi-rs/tar-freebsd-x64": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/tar-freebsd-x64/-/tar-freebsd-x64-1.1.1.tgz",
+ "integrity": "sha512-rEepBvCJUwcuvUYkY83e8aot8RsR5Jcnal4PsG3tbWGKW1yAvcXhyMXf0fN6ZGpVRZFnB+FJqDyBxvsCPEXKhw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@napi-rs/tar-linux-arm-gnueabihf": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/tar-linux-arm-gnueabihf/-/tar-linux-arm-gnueabihf-1.1.1.tgz",
+ "integrity": "sha512-an1bJdfyhI5FpZYyTQ20mrqwR+a676i8GkaYc4Uy12dH/a7TJIfrK6Qa2Gm46arZvxUvx56qxoRKXbpOjUPvwA==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@napi-rs/tar-linux-arm64-gnu": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/tar-linux-arm64-gnu/-/tar-linux-arm64-gnu-1.1.1.tgz",
+ "integrity": "sha512-w++Vtx36T2yHTKws7GVnmHHcUT1ybB59xLWSh9A8bwEpJVG4dG7Qub9mFe5cpcbfrJ+XP2mKKxC3oUJSunK3iQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@napi-rs/tar-linux-arm64-musl": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/tar-linux-arm64-musl/-/tar-linux-arm64-musl-1.1.1.tgz",
+ "integrity": "sha512-Rh6UFhNtj3i4deJHOBINFIeRL0072mgbeyuK5rl1HokKnNoMKx8qKIZNEzBTTqpogMfDHWGvzyTQdnVxes5dpA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@napi-rs/tar-linux-ppc64-gnu": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/tar-linux-ppc64-gnu/-/tar-linux-ppc64-gnu-1.1.1.tgz",
+ "integrity": "sha512-Cp+AxFbv9zcyAXtnzQi0OzmgDnQgy2w9D4Ubr+iwzMtVgJcztzcEoCcCrN1k2ATdEB01LX2Vb49IaocGOZhC9Q==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@napi-rs/tar-linux-s390x-gnu": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/tar-linux-s390x-gnu/-/tar-linux-s390x-gnu-1.1.1.tgz",
+ "integrity": "sha512-ZyscC3SYKTBWyDRYjLOKAd5TyJ7q0KACRdQ8bWrb3rgrra1CCIJD66CsGTH6Dh0AVSdfLwZ8MfIIXU6+14BMjQ==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@napi-rs/tar-linux-x64-gnu": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/tar-linux-x64-gnu/-/tar-linux-x64-gnu-1.1.1.tgz",
+ "integrity": "sha512-LlIv+zg4fiOQge9LQX/ieBdRWE2fhVDjCTHxnunZkbugNmdhdelxWf1RpZb/6ZujWpNF4LPu4N/MW7ygg2oYAQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@napi-rs/tar-linux-x64-musl": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/tar-linux-x64-musl/-/tar-linux-x64-musl-1.1.1.tgz",
+ "integrity": "sha512-gZBeoKLjanOVj55qk4EMu13P2i9M0SuINmlGQkOxm1niIJofexzddHUYtqO5o/5QqtyL8lADmAcZplLILMLhHA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@napi-rs/tar-wasm32-wasi": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/tar-wasm32-wasi/-/tar-wasm32-wasi-1.1.1.tgz",
+ "integrity": "sha512-rwtQ1Mdt/ft6g6I54fJzbUeLspl4yTwj6I3UJ6mitKnrN42soJkcDrdh3Y/FGvlpqZTad2YMQ96fGJl3EtAm2Q==",
+ "cpu": [
+ "wasm32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@emnapi/core": "1.11.2",
+ "@emnapi/runtime": "1.11.2",
+ "@napi-rs/wasm-runtime": "^1.1.6"
+ },
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/@napi-rs/tar-win32-arm64-msvc": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/tar-win32-arm64-msvc/-/tar-win32-arm64-msvc-1.1.1.tgz",
+ "integrity": "sha512-30PVp1AehRpfwxmv5wI4cg0yj3WmWBsZ+1QnLGnvEELu7Eu/+dhNU0nrmhI7VfPgLwSRK2eg9DQTB3tP7Wv9bA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@napi-rs/tar-win32-ia32-msvc": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/tar-win32-ia32-msvc/-/tar-win32-ia32-msvc-1.1.1.tgz",
+ "integrity": "sha512-aI3/rmz+izUChiSeaPxcasAOxhf3FpJNuIHMXlxS/vpW+HIxUsSDR5+XV61PEG5DL4L/75iENVUxmSGM5l2yaw==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@napi-rs/tar-win32-x64-msvc": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/tar-win32-x64-msvc/-/tar-win32-x64-msvc-1.1.1.tgz",
+ "integrity": "sha512-yJsB2IsrODQVLKbm2Fg1nHiVRbEj49mSPbj4x7JPZWJI0jGVPjohE2Sif0FBbx8OxsVoUODvS0BwksZZ8jl/OA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@napi-rs/wasm-runtime": {
+ "version": "1.1.6",
+ "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.6.tgz",
+ "integrity": "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@tybys/wasm-util": "^0.10.3"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ },
+ "peerDependencies": {
+ "@emnapi/core": "^1.7.1",
+ "@emnapi/runtime": "^1.7.1"
+ }
+ },
+ "node_modules/@napi-rs/wasm-tools": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/wasm-tools/-/wasm-tools-1.0.1.tgz",
+ "integrity": "sha512-enkZYyuCdo+9jneCPE/0fjIta4wWnvVN9hBo2HuiMpRF0q3lzv1J6b/cl7i0mxZUKhBrV3aCKDBQnCOhwKbPmQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 10"
+ },
+ "optionalDependencies": {
+ "@napi-rs/wasm-tools-android-arm-eabi": "1.0.1",
+ "@napi-rs/wasm-tools-android-arm64": "1.0.1",
+ "@napi-rs/wasm-tools-darwin-arm64": "1.0.1",
+ "@napi-rs/wasm-tools-darwin-x64": "1.0.1",
+ "@napi-rs/wasm-tools-freebsd-x64": "1.0.1",
+ "@napi-rs/wasm-tools-linux-arm64-gnu": "1.0.1",
+ "@napi-rs/wasm-tools-linux-arm64-musl": "1.0.1",
+ "@napi-rs/wasm-tools-linux-x64-gnu": "1.0.1",
+ "@napi-rs/wasm-tools-linux-x64-musl": "1.0.1",
+ "@napi-rs/wasm-tools-wasm32-wasi": "1.0.1",
+ "@napi-rs/wasm-tools-win32-arm64-msvc": "1.0.1",
+ "@napi-rs/wasm-tools-win32-ia32-msvc": "1.0.1",
+ "@napi-rs/wasm-tools-win32-x64-msvc": "1.0.1"
+ }
+ },
+ "node_modules/@napi-rs/wasm-tools-android-arm-eabi": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/wasm-tools-android-arm-eabi/-/wasm-tools-android-arm-eabi-1.0.1.tgz",
+ "integrity": "sha512-lr07E/l571Gft5v4aA1dI8koJEmF1F0UigBbsqg9OWNzg80H3lDPO+auv85y3T/NHE3GirDk7x/D3sLO57vayw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@napi-rs/wasm-tools-android-arm64": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/wasm-tools-android-arm64/-/wasm-tools-android-arm64-1.0.1.tgz",
+ "integrity": "sha512-WDR7S+aRLV6LtBJAg5fmjKkTZIdrEnnQxgdsb7Cf8pYiMWBHLU+LC49OUVppQ2YSPY0+GeYm9yuZWW3kLjJ7Bg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@napi-rs/wasm-tools-darwin-arm64": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/wasm-tools-darwin-arm64/-/wasm-tools-darwin-arm64-1.0.1.tgz",
+ "integrity": "sha512-qWTI+EEkiN0oIn/N2gQo7+TVYil+AJ20jjuzD2vATS6uIjVz+Updeqmszi7zq7rdFTLp6Ea3/z4kDKIfZwmR9g==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@napi-rs/wasm-tools-darwin-x64": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/wasm-tools-darwin-x64/-/wasm-tools-darwin-x64-1.0.1.tgz",
+ "integrity": "sha512-bA6hubqtHROR5UI3tToAF/c6TDmaAgF0SWgo4rADHtQ4wdn0JeogvOk50gs2TYVhKPE2ZD2+qqt7oBKB+sxW3A==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@napi-rs/wasm-tools-freebsd-x64": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/wasm-tools-freebsd-x64/-/wasm-tools-freebsd-x64-1.0.1.tgz",
+ "integrity": "sha512-90+KLBkD9hZEjPQW1MDfwSt5J1L46EUKacpCZWyRuL6iIEO5CgWU0V/JnEgFsDOGyyYtiTvHc5bUdUTWd4I9Vg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@napi-rs/wasm-tools-linux-arm64-gnu": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/wasm-tools-linux-arm64-gnu/-/wasm-tools-linux-arm64-gnu-1.0.1.tgz",
+ "integrity": "sha512-rG0QlS65x9K/u3HrKafDf8cFKj5wV2JHGfl8abWgKew0GVPyp6vfsDweOwHbWAjcHtp2LHi6JHoW80/MTHm52Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@napi-rs/wasm-tools-linux-arm64-musl": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/wasm-tools-linux-arm64-musl/-/wasm-tools-linux-arm64-musl-1.0.1.tgz",
+ "integrity": "sha512-jAasbIvjZXCgX0TCuEFQr+4D6Lla/3AAVx2LmDuMjgG4xoIXzjKWl7c4chuaD+TI+prWT0X6LJcdzFT+ROKGHQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@napi-rs/wasm-tools-linux-x64-gnu": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/wasm-tools-linux-x64-gnu/-/wasm-tools-linux-x64-gnu-1.0.1.tgz",
+ "integrity": "sha512-Plgk5rPqqK2nocBGajkMVbGm010Z7dnUgq0wtnYRZbzWWxwWcXfZMPa8EYxrK4eE8SzpI7VlZP1tdVsdjgGwMw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@napi-rs/wasm-tools-linux-x64-musl": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/wasm-tools-linux-x64-musl/-/wasm-tools-linux-x64-musl-1.0.1.tgz",
+ "integrity": "sha512-GW7AzGuWxtQkyHknHWYFdR0CHmW6is8rG2Rf4V6GNmMpmwtXt/ItWYWtBe4zqJWycMNazpfZKSw/BpT7/MVCXQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@napi-rs/wasm-tools-wasm32-wasi": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/wasm-tools-wasm32-wasi/-/wasm-tools-wasm32-wasi-1.0.1.tgz",
+ "integrity": "sha512-/nQVSTrqSsn7YdAc2R7Ips/tnw5SPUcl3D7QrXCNGPqjbatIspnaexvaOYNyKMU6xPu+pc0BTnKVmqhlJJCPLA==",
+ "cpu": [
+ "wasm32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@napi-rs/wasm-runtime": "^1.0.3"
+ },
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/@napi-rs/wasm-tools-win32-arm64-msvc": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/wasm-tools-win32-arm64-msvc/-/wasm-tools-win32-arm64-msvc-1.0.1.tgz",
+ "integrity": "sha512-PFi7oJIBu5w7Qzh3dwFea3sHRO3pojMsaEnUIy22QvsW+UJfNQwJCryVrpoUt8m4QyZXI+saEq/0r4GwdoHYFQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@napi-rs/wasm-tools-win32-ia32-msvc": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/wasm-tools-win32-ia32-msvc/-/wasm-tools-win32-ia32-msvc-1.0.1.tgz",
+ "integrity": "sha512-gXkuYzxQsgkj05Zaq+KQTkHIN83dFAwMcTKa2aQcpYPRImFm2AQzEyLtpXmyCWzJ0F9ZYAOmbSyrNew8/us6bw==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@napi-rs/wasm-tools-win32-x64-msvc": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/wasm-tools-win32-x64-msvc/-/wasm-tools-win32-x64-msvc-1.0.1.tgz",
+ "integrity": "sha512-rEAf05nol3e3eei2sRButmgXP+6ATgm0/38MKhz9Isne82T4rPIMYsCIFj0kOisaGeVwoi2fnm7O9oWp5YVnYQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@nodelib/fs.scandir": {
+ "version": "2.1.5",
+ "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",
+ "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@nodelib/fs.stat": "2.0.5",
+ "run-parallel": "^1.1.9"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/@nodelib/fs.stat": {
+ "version": "2.0.5",
+ "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz",
+ "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/@nodelib/fs.walk": {
+ "version": "1.2.8",
+ "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz",
+ "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@nodelib/fs.scandir": "2.1.5",
+ "fastq": "^1.6.0"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/@octokit/auth-token": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-6.0.0.tgz",
+ "integrity": "sha512-P4YJBPdPSpWTQ1NU4XYdvHvXJJDxM6YwpS0FZHRgP7YFkdVxsWcpWGy/NVqlAA7PcPCnMacXlRm1y2PFZRWL/w==",
"dev": true,
- "license": "Apache-2.0",
+ "license": "MIT",
"engines": {
- "node": ">=12.22"
- },
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/nzakas"
+ "node": ">= 20"
}
},
- "node_modules/@humanwhocodes/retry": {
- "version": "0.4.3",
- "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz",
- "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==",
+ "node_modules/@octokit/core": {
+ "version": "7.0.6",
+ "resolved": "https://registry.npmjs.org/@octokit/core/-/core-7.0.6.tgz",
+ "integrity": "sha512-DhGl4xMVFGVIyMwswXeyzdL4uXD5OGILGX5N8Y+f6W7LhC1Ze2poSNrkF/fedpVDHEEZ+PHFW0vL14I+mm8K3Q==",
"dev": true,
- "license": "Apache-2.0",
- "engines": {
- "node": ">=18.18"
+ "license": "MIT",
+ "dependencies": {
+ "@octokit/auth-token": "^6.0.0",
+ "@octokit/graphql": "^9.0.3",
+ "@octokit/request": "^10.0.6",
+ "@octokit/request-error": "^7.0.2",
+ "@octokit/types": "^16.0.0",
+ "before-after-hook": "^4.0.0",
+ "universal-user-agent": "^7.0.0"
},
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/nzakas"
+ "engines": {
+ "node": ">= 20"
}
},
- "node_modules/@isaacs/fs-minipass": {
- "version": "4.0.1",
- "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz",
- "integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==",
+ "node_modules/@octokit/endpoint": {
+ "version": "11.0.3",
+ "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-11.0.3.tgz",
+ "integrity": "sha512-FWFlNxghg4HrXkD3ifYbS/IdL/mDHjh9QcsNyhQjN8dplUoZbejsdpmuqdA76nxj2xoWPs7p8uX2SNr9rYu0Ag==",
"dev": true,
- "license": "ISC",
+ "license": "MIT",
"dependencies": {
- "minipass": "^7.0.4"
+ "@octokit/types": "^16.0.0",
+ "universal-user-agent": "^7.0.2"
},
"engines": {
- "node": ">=18.0.0"
+ "node": ">= 20"
}
},
- "node_modules/@malept/cross-spawn-promise": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/@malept/cross-spawn-promise/-/cross-spawn-promise-2.0.0.tgz",
- "integrity": "sha512-1DpKU0Z5ThltBwjNySMC14g0CkbyhCaz9FkhxqNsZI6uAPJXFS8cMXlBKo26FJ8ZuW6S9GCMcR9IO5k2X5/9Fg==",
+ "node_modules/@octokit/graphql": {
+ "version": "9.0.3",
+ "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-9.0.3.tgz",
+ "integrity": "sha512-grAEuupr/C1rALFnXTv6ZQhFuL1D8G5y8CN04RgrO4FIPMrtm+mcZzFG7dcBm+nq+1ppNixu+Jd78aeJOYxlGA==",
"dev": true,
- "funding": [
- {
- "type": "individual",
- "url": "https://github.com/sponsors/malept"
- },
- {
- "type": "tidelift",
- "url": "https://tidelift.com/subscription/pkg/npm-.malept-cross-spawn-promise?utm_medium=referral&utm_source=npm_fund"
- }
- ],
- "license": "Apache-2.0",
+ "license": "MIT",
"dependencies": {
- "cross-spawn": "^7.0.1"
+ "@octokit/request": "^10.0.6",
+ "@octokit/types": "^16.0.0",
+ "universal-user-agent": "^7.0.0"
},
"engines": {
- "node": ">= 12.13.0"
+ "node": ">= 20"
}
},
- "node_modules/@malept/flatpak-bundler": {
- "version": "0.4.0",
- "resolved": "https://registry.npmjs.org/@malept/flatpak-bundler/-/flatpak-bundler-0.4.0.tgz",
- "integrity": "sha512-9QOtNffcOF/c1seMCDnjckb3R9WHcG34tky+FHpNKKCW0wc/scYLwMtO+ptyGUfMW0/b/n4qRiALlaFHc9Oj7Q==",
+ "node_modules/@octokit/openapi-types": {
+ "version": "27.0.0",
+ "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-27.0.0.tgz",
+ "integrity": "sha512-whrdktVs1h6gtR+09+QsNk2+FO+49j6ga1c55YZudfEG+oKJVvJLQi3zkOm5JjiUXAagWK2tI2kTGKJ2Ys7MGA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@octokit/plugin-paginate-rest": {
+ "version": "14.0.0",
+ "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-14.0.0.tgz",
+ "integrity": "sha512-fNVRE7ufJiAA3XUrha2omTA39M6IXIc6GIZLvlbsm8QOQCYvpq/LkMNGyFlB1d8hTDzsAXa3OKtybdMAYsV/fw==",
"dev": true,
"license": "MIT",
"dependencies": {
- "debug": "^4.1.1",
- "fs-extra": "^9.0.0",
- "lodash": "^4.17.15",
- "tmp-promise": "^3.0.2"
+ "@octokit/types": "^16.0.0"
},
"engines": {
- "node": ">= 10.0.0"
+ "node": ">= 20"
+ },
+ "peerDependencies": {
+ "@octokit/core": ">=6"
}
},
- "node_modules/@malept/flatpak-bundler/node_modules/fs-extra": {
- "version": "9.1.0",
- "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz",
- "integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==",
+ "node_modules/@octokit/plugin-request-log": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/@octokit/plugin-request-log/-/plugin-request-log-6.0.0.tgz",
+ "integrity": "sha512-UkOzeEN3W91/eBq9sPZNQ7sUBvYCqYbrrD8gTbBuGtHEuycE4/awMXcYvx6sVYo7LypPhmQwwpUe4Yyu4QZN5Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 20"
+ },
+ "peerDependencies": {
+ "@octokit/core": ">=6"
+ }
+ },
+ "node_modules/@octokit/plugin-rest-endpoint-methods": {
+ "version": "17.0.0",
+ "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-17.0.0.tgz",
+ "integrity": "sha512-B5yCyIlOJFPqUUeiD0cnBJwWJO8lkJs5d8+ze9QDP6SvfiXSz1BF+91+0MeI1d2yxgOhU/O+CvtiZ9jSkHhFAw==",
"dev": true,
"license": "MIT",
"dependencies": {
- "at-least-node": "^1.0.0",
- "graceful-fs": "^4.2.0",
- "jsonfile": "^6.0.1",
- "universalify": "^2.0.0"
+ "@octokit/types": "^16.0.0"
},
"engines": {
- "node": ">=10"
+ "node": ">= 20"
+ },
+ "peerDependencies": {
+ "@octokit/core": ">=6"
}
},
- "node_modules/@nodelib/fs.scandir": {
- "version": "2.1.5",
- "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",
- "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==",
+ "node_modules/@octokit/request": {
+ "version": "10.0.11",
+ "resolved": "https://registry.npmjs.org/@octokit/request/-/request-10.0.11.tgz",
+ "integrity": "sha512-+s7HUxjfFqOMS9VlIwDffq0MikjSAK0gSpG73W+meAvVAvX4MBrHYTK5Bj3Uot55qFT4gzUtfzE4mGWY4Br8/Q==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@nodelib/fs.stat": "2.0.5",
- "run-parallel": "^1.1.9"
+ "@octokit/endpoint": "^11.0.3",
+ "@octokit/request-error": "^7.0.2",
+ "@octokit/types": "^16.0.0",
+ "content-type": "^2.0.0",
+ "json-with-bigint": "^3.5.3",
+ "universal-user-agent": "^7.0.2"
},
"engines": {
- "node": ">= 8"
+ "node": ">= 20"
}
},
- "node_modules/@nodelib/fs.stat": {
- "version": "2.0.5",
- "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz",
- "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==",
+ "node_modules/@octokit/request-error": {
+ "version": "7.1.0",
+ "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-7.1.0.tgz",
+ "integrity": "sha512-KMQIfq5sOPpkQYajXHwnhjCC0slzCNScLHs9JafXc4RAJI+9f+jNDlBNaIMTvazOPLgb4BnlhGJOTbnN0wIjPw==",
"dev": true,
"license": "MIT",
+ "dependencies": {
+ "@octokit/types": "^16.0.0"
+ },
"engines": {
- "node": ">= 8"
+ "node": ">= 20"
}
},
- "node_modules/@nodelib/fs.walk": {
- "version": "1.2.8",
- "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz",
- "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==",
+ "node_modules/@octokit/rest": {
+ "version": "22.0.1",
+ "resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-22.0.1.tgz",
+ "integrity": "sha512-Jzbhzl3CEexhnivb1iQ0KJ7s5vvjMWcmRtq5aUsKmKDrRW6z3r84ngmiFKFvpZjpiU/9/S6ITPFRpn5s/3uQJw==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@nodelib/fs.scandir": "2.1.5",
- "fastq": "^1.6.0"
+ "@octokit/core": "^7.0.6",
+ "@octokit/plugin-paginate-rest": "^14.0.0",
+ "@octokit/plugin-request-log": "^6.0.0",
+ "@octokit/plugin-rest-endpoint-methods": "^17.0.0"
},
"engines": {
- "node": ">= 8"
+ "node": ">= 20"
+ }
+ },
+ "node_modules/@octokit/types": {
+ "version": "16.0.0",
+ "resolved": "https://registry.npmjs.org/@octokit/types/-/types-16.0.0.tgz",
+ "integrity": "sha512-sKq+9r1Mm4efXW1FCk7hFSeJo4QKreL/tTbR0rz/qx/r1Oa2VV83LTA/H/MuCOX7uCIJmQVRKBcbmWoySjAnSg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@octokit/openapi-types": "^27.0.0"
}
},
"node_modules/@sindresorhus/is": {
@@ -760,6 +2392,17 @@
"node": ">=10"
}
},
+ "node_modules/@tybys/wasm-util": {
+ "version": "0.10.3",
+ "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.3.tgz",
+ "integrity": "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
"node_modules/@types/auto-launch": {
"version": "5.0.5",
"resolved": "https://registry.npmjs.org/@types/auto-launch/-/auto-launch-5.0.5.tgz",
@@ -1165,15 +2808,6 @@
"acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
}
},
- "node_modules/adm-zip": {
- "version": "0.5.17",
- "resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.5.17.tgz",
- "integrity": "sha512-+Ut8d9LLqwEvHHJl1+PIHqoyDxFgVN847JTVM3Izi3xHDWPE4UtzzXysMZQs64DMcrJfBeS/uoEP4AD3HQHnQQ==",
- "license": "MIT",
- "engines": {
- "node": ">=12.0"
- }
- },
"node_modules/agent-base": {
"version": "7.1.4",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
@@ -1554,12 +3188,21 @@
],
"license": "MIT"
},
+ "node_modules/before-after-hook": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-4.0.0.tgz",
+ "integrity": "sha512-q6tR3RPqIB1pMiTRMFcZwuG5T8vwp+vUvEG0vuI6B+Rikh5BfPp2fQ82c925FOs+b0lcFQ8CFrL+KbilfZFhOQ==",
+ "dev": true,
+ "license": "Apache-2.0"
+ },
"node_modules/boolean": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/boolean/-/boolean-3.2.0.tgz",
"integrity": "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw==",
"deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.",
- "license": "MIT"
+ "dev": true,
+ "license": "MIT",
+ "optional": true
},
"node_modules/brace-expansion": {
"version": "5.0.6",
@@ -1736,6 +3379,13 @@
"node": ">=8"
}
},
+ "node_modules/chardet": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/chardet/-/chardet-2.2.0.tgz",
+ "integrity": "sha512-rddelWYNPRrXq6PtNEN2S3f6t9ILzvqaN5pVgi4kqt9jHQaXIial9PznB5iSPVlQSLNaaH22ItWz3EJtQ10+OA==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/chokidar": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz",
@@ -1802,11 +3452,31 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
- "node_modules/clip-bpe-js": {
- "version": "0.0.6",
- "resolved": "https://registry.npmjs.org/clip-bpe-js/-/clip-bpe-js-0.0.6.tgz",
- "integrity": "sha512-+0n0eeacgFmg9hKhHhXanKkRDhqRwzYK7dj46VYMzePxmN8zbbDgeTQZchfvARNpbBMRi7FfWRSW3lysOUDX/Q==",
- "license": "MIT"
+ "node_modules/cli-width": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-4.1.0.tgz",
+ "integrity": "sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">= 12"
+ }
+ },
+ "node_modules/clipanion": {
+ "version": "4.0.0-rc.4",
+ "resolved": "https://registry.npmjs.org/clipanion/-/clipanion-4.0.0-rc.4.tgz",
+ "integrity": "sha512-CXkMQxU6s9GklO/1f714dkKBMu1lopS1WFF0B8o4AxPykR1hpozxSiUZ5ZUeBjfPgCWqbcNOtZVFhB8Lkfp1+Q==",
+ "dev": true,
+ "license": "MIT",
+ "workspaces": [
+ "website"
+ ],
+ "dependencies": {
+ "typanion": "^3.8.0"
+ },
+ "peerDependencies": {
+ "typanion": "*"
+ }
},
"node_modules/cliui": {
"version": "8.0.1",
@@ -1856,6 +3526,13 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/colorette": {
+ "version": "2.0.20",
+ "resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.20.tgz",
+ "integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
@@ -2124,6 +3801,20 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/content-type": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz",
+ "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
"node_modules/core-util-is": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz",
@@ -2267,7 +3958,9 @@
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz",
"integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==",
+ "dev": true,
"license": "MIT",
+ "optional": true,
"dependencies": {
"es-define-property": "^1.0.0",
"es-errors": "^1.3.0",
@@ -2284,7 +3977,9 @@
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz",
"integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==",
+ "dev": true,
"license": "MIT",
+ "optional": true,
"dependencies": {
"define-data-property": "^1.0.1",
"has-property-descriptors": "^1.0.0",
@@ -2337,7 +4032,9 @@
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.1.0.tgz",
"integrity": "sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==",
- "license": "MIT"
+ "dev": true,
+ "license": "MIT",
+ "optional": true
},
"node_modules/dir-compare": {
"version": "4.2.0",
@@ -2751,6 +4448,7 @@
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
@@ -2760,6 +4458,7 @@
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
@@ -2794,11 +4493,24 @@
"node": ">= 0.4"
}
},
+ "node_modules/es-toolkit": {
+ "version": "1.49.0",
+ "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.49.0.tgz",
+ "integrity": "sha512-G5iZ6Pc/FNRY/soKZHC+TxGDD83rHUDXxzaWhGCX44vAv/tMs56WMusnm/KMNK+luUPsgA9U28cGr4RDlSzL2g==",
+ "dev": true,
+ "license": "MIT",
+ "workspaces": [
+ "docs",
+ "benchmarks"
+ ]
+ },
"node_modules/es6-error": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/es6-error/-/es6-error-4.1.1.tgz",
"integrity": "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==",
- "license": "MIT"
+ "dev": true,
+ "license": "MIT",
+ "optional": true
},
"node_modules/escalade": {
"version": "3.2.0",
@@ -2814,6 +4526,7 @@
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",
"integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=10"
@@ -3171,6 +4884,23 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/fast-string-truncated-width": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/fast-string-truncated-width/-/fast-string-truncated-width-3.0.3.tgz",
+ "integrity": "sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/fast-string-width": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/fast-string-width/-/fast-string-width-3.0.2.tgz",
+ "integrity": "sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fast-string-truncated-width": "^3.0.2"
+ }
+ },
"node_modules/fast-uri": {
"version": "3.1.4",
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.4.tgz",
@@ -3187,6 +4917,16 @@
],
"license": "BSD-3-Clause"
},
+ "node_modules/fast-wrap-ansi": {
+ "version": "0.2.2",
+ "resolved": "https://registry.npmjs.org/fast-wrap-ansi/-/fast-wrap-ansi-0.2.2.tgz",
+ "integrity": "sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fast-string-width": "^3.0.2"
+ }
+ },
"node_modules/fastq": {
"version": "1.20.1",
"resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz",
@@ -3548,7 +5288,9 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/global-agent/-/global-agent-3.0.0.tgz",
"integrity": "sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q==",
+ "dev": true,
"license": "BSD-3-Clause",
+ "optional": true,
"dependencies": {
"boolean": "^3.0.1",
"es6-error": "^4.1.1",
@@ -3565,7 +5307,9 @@
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz",
"integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==",
+ "dev": true,
"license": "MIT",
+ "optional": true,
"dependencies": {
"define-properties": "^1.2.1",
"gopd": "^1.0.1"
@@ -3581,6 +5325,7 @@
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
@@ -3635,7 +5380,9 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz",
"integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==",
+ "dev": true,
"license": "MIT",
+ "optional": true,
"dependencies": {
"es-define-property": "^1.0.0"
},
@@ -4065,7 +5812,16 @@
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz",
"integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==",
- "license": "ISC"
+ "dev": true,
+ "license": "ISC",
+ "optional": true
+ },
+ "node_modules/json-with-bigint": {
+ "version": "3.5.10",
+ "resolved": "https://registry.npmjs.org/json-with-bigint/-/json-with-bigint-3.5.10.tgz",
+ "integrity": "sha512-Vcx+JVNEBts/xfcoCS69sKrOhOk/3TVlvlT+XzUOefVKnnrbYSCKpDCm10pohsJFtsJVYnwa/cXRZ4eElzaM6w==",
+ "dev": true,
+ "license": "MIT"
},
"node_modules/json5": {
"version": "2.2.3",
@@ -4181,7 +5937,9 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/matcher/-/matcher-3.0.0.tgz",
"integrity": "sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==",
+ "dev": true,
"license": "MIT",
+ "optional": true,
"dependencies": {
"escape-string-regexp": "^4.0.0"
},
@@ -4347,6 +6105,16 @@
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
+ "node_modules/mute-stream": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-3.0.0.tgz",
+ "integrity": "sha512-dkEJPVvun4FryqBmZ5KhDo0K9iDXAwn08tMLDinNdRBNPcYEDiWYysLcc6k3mjTMlbP9KyylvRpd4wFtwrT9rw==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": "^20.17.0 || >=22.9.0"
+ }
+ },
"node_modules/natural-compare": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz",
@@ -4528,11 +6296,27 @@
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz",
"integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==",
+ "dev": true,
"license": "MIT",
+ "optional": true,
"engines": {
"node": ">= 0.4"
}
},
+ "node_modules/obug": {
+ "version": "2.1.4",
+ "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.4.tgz",
+ "integrity": "sha512-4a+OsYv9UktOJKE+l1A4OufDgdRF9PifWj+tJnHURo/P+WOxpG4GzUFL9qCalmWauao6ogiG+QvnCovwPoyAWA==",
+ "dev": true,
+ "funding": [
+ "https://github.com/sponsors/sxzz",
+ "https://opencollective.com/debug"
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
"node_modules/once": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
@@ -4543,29 +6327,6 @@
"wrappy": "1"
}
},
- "node_modules/onnxruntime-common": {
- "version": "1.22.0",
- "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.22.0.tgz",
- "integrity": "sha512-vcuaNWgtF2dGQu/EP5P8UI5rEPEYqXG2sPPe5j9lg2TY/biJF8eWklTMwlDO08iuXq48xJo0awqIpK5mPG+IxA==",
- "license": "MIT"
- },
- "node_modules/onnxruntime-node": {
- "version": "1.22.0-rev",
- "resolved": "https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.22.0-rev.tgz",
- "integrity": "sha512-9vh50/mnwauFUex0NYyyLf9pmRp8q6DVMG8K+xtoXv68SSB9bESa1bEbWLqfUncgB3XucQaOV+wfMPcqANMYhQ==",
- "hasInstallScript": true,
- "license": "MIT",
- "os": [
- "win32",
- "darwin",
- "linux"
- ],
- "dependencies": {
- "adm-zip": "^0.5.16",
- "global-agent": "^3.0.0",
- "onnxruntime-common": "1.22.0"
- }
- },
"node_modules/optionator": {
"version": "0.9.4",
"resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",
@@ -5089,7 +6850,9 @@
"version": "2.15.4",
"resolved": "https://registry.npmjs.org/roarr/-/roarr-2.15.4.tgz",
"integrity": "sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A==",
+ "dev": true,
"license": "BSD-3-Clause",
+ "optional": true,
"dependencies": {
"boolean": "^3.0.1",
"detect-node": "^2.0.4",
@@ -5198,13 +6961,17 @@
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/semver-compare/-/semver-compare-1.0.0.tgz",
"integrity": "sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow==",
- "license": "MIT"
+ "dev": true,
+ "license": "MIT",
+ "optional": true
},
"node_modules/serialize-error": {
"version": "7.0.1",
"resolved": "https://registry.npmjs.org/serialize-error/-/serialize-error-7.0.1.tgz",
"integrity": "sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw==",
+ "dev": true,
"license": "MIT",
+ "optional": true,
"dependencies": {
"type-fest": "^0.13.1"
},
@@ -5219,7 +6986,9 @@
"version": "0.13.1",
"resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.13.1.tgz",
"integrity": "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg==",
+ "dev": true,
"license": "(MIT OR CC0-1.0)",
+ "optional": true,
"engines": {
"node": ">=10"
},
@@ -5401,7 +7170,9 @@
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz",
"integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==",
- "license": "BSD-3-Clause"
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "optional": true
},
"node_modules/stat-mode": {
"version": "1.0.0",
@@ -5716,6 +7487,16 @@
"dev": true,
"license": "0BSD"
},
+ "node_modules/typanion": {
+ "version": "3.14.0",
+ "resolved": "https://registry.npmjs.org/typanion/-/typanion-3.14.0.tgz",
+ "integrity": "sha512-ZW/lVMRabETuYCd9O9ZvMhAh8GslSqaUjxmK/JLPCh6l73CvLBiuXswj/+7LdnWOgYsQ130FqLzFz5aGT4I3Ug==",
+ "dev": true,
+ "license": "MIT",
+ "workspaces": [
+ "website"
+ ]
+ },
"node_modules/type-check": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
@@ -5818,6 +7599,13 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/universal-user-agent": {
+ "version": "7.0.3",
+ "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-7.0.3.tgz",
+ "integrity": "sha512-TmnEAEAsBJVZM/AADELsK76llnwcf9vMKuPz8JflO1frO8Lchitr0fNaN9d+Ap0BjKtqWqd/J17qeDnXh8CL2A==",
+ "dev": true,
+ "license": "ISC"
+ },
"node_modules/universalify": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
diff --git a/desktop/package.json b/desktop/package.json
index 1dc9b2c5dc..d01255ee9e 100644
--- a/desktop/package.json
+++ b/desktop/package.json
@@ -26,7 +26,6 @@
"any-shell-escape": "0.1.1",
"auto-launch": "5.0.6",
"chokidar": "4.0.3",
- "clip-bpe-js": "0.0.6",
"comlink": "4.4.2",
"compare-versions": "6.1.1",
"electron-log": "5.4.4",
@@ -36,11 +35,11 @@
"lru-cache": "11.5.1",
"next-electron-server": "1.0.0",
"node-stream-zip": "1.15.0",
- "onnxruntime-node": "1.22.0-rev",
"zod": "4.4.3"
},
"devDependencies": {
"@eslint/js": "10.0.1",
+ "@napi-rs/cli": "3.7.4",
"@types/auto-launch": "5.0.5",
"@types/node": "24.13.0",
"ajv": "8.20.0",
diff --git a/desktop/scripts/ml-native.js b/desktop/scripts/ml-native.js
new file mode 100644
index 0000000000..9f00304edb
--- /dev/null
+++ b/desktop/scripts/ml-native.js
@@ -0,0 +1,129 @@
+/**
+ * [Note: Packaging the ML addon]
+ *
+ * The Rust ML addon (see [Note: ML with Rust]) is built from source by
+ * `cargo codegen napi` (which our postinstall runs) into the gitignored
+ * `rust-bindings/` directory, where the development app loads it from.
+ *
+ * When packaging, the addon(s) for the architectures being built are staged
+ * into `build/ml-native/`, which the "extraFiles" clause in
+ * `electron-builder.yml` copies into the packaged app's resources. On macOS
+ * the packaged app is universal, so both the arm64 and x64 addons must be
+ * present (and identical) in every per-arch build that gets merged; anything
+ * that is not the host architecture is cross-compiled, which requires the
+ * corresponding Rust target to be installed (`rustup target add ...`).
+ */
+
+const fsp = require("fs/promises");
+const path = require("path");
+const { execSync } = require("child_process");
+
+/** napi-cli's name for the addon built for the given platform-arch. */
+const napiTriple = (platform, arch) => {
+ switch (`${platform}-${arch}`) {
+ case "darwin-arm64":
+ return "darwin-arm64";
+ case "darwin-x64":
+ return "darwin-x64";
+ case "linux-x64":
+ return "linux-x64-gnu";
+ case "linux-arm64":
+ return "linux-arm64-gnu";
+ case "win32-x64":
+ return "win32-x64-msvc";
+ case "win32-arm64":
+ return "win32-arm64-msvc";
+ default:
+ throw new Error(`Unsupported platform-arch: ${platform}-${arch}`);
+ }
+};
+
+/** The Rust target triple for the given platform-arch. */
+const rustTriple = (platform, arch) => {
+ switch (`${platform}-${arch}`) {
+ case "darwin-arm64":
+ return "aarch64-apple-darwin";
+ case "darwin-x64":
+ return "x86_64-apple-darwin";
+ case "linux-x64":
+ return "x86_64-unknown-linux-gnu";
+ case "linux-arm64":
+ return "aarch64-unknown-linux-gnu";
+ case "win32-x64":
+ return "x86_64-pc-windows-msvc";
+ case "win32-arm64":
+ return "aarch64-pc-windows-msvc";
+ default:
+ throw new Error(`Unsupported platform-arch: ${platform}-${arch}`);
+ }
+};
+
+/**
+ * Build the addon for the given platform-arch into `rust-bindings/` if it is
+ * not already there.
+ *
+ * For the host architecture this is equivalent to (and no-ops after) the
+ * `cargo codegen napi` that postinstall runs.
+ */
+const buildAddonIfNeeded = async (appDir, platform, arch) => {
+ const addonPath = path.join(
+ appDir,
+ "rust-bindings",
+ `index.${napiTriple(platform, arch)}.node`,
+ );
+ try {
+ await fsp.access(addonPath);
+ return addonPath;
+ } catch {}
+
+ const cmd = [
+ "npm exec -- napi build",
+ "--manifest-path ../rust/bindings/napi/photos/Cargo.toml",
+ "--target-dir ../rust/target",
+ "--release --strip --platform --no-js",
+ "--dts index.d.ts",
+ "--output-dir rust-bindings",
+ `--target ${rustTriple(platform, arch)}`,
+ // Cross-compiling for the other Linux architecture needs a gcc cross
+ // toolchain; let napi-cli download its prebuilt one.
+ ...(platform == "linux" && arch != process.arch
+ ? ["--use-napi-cross"]
+ : []),
+ ].join(" ");
+ console.log(`> ${cmd}`);
+ execSync(cmd, { cwd: appDir, stdio: "inherit" });
+
+ await fsp.access(addonPath);
+ return addonPath;
+};
+
+/**
+ * Ensure the addon(s) needed when packaging for the given platform-arch are
+ * built and staged into `build/ml-native/`.
+ */
+const stageMLAddons = async (appDir, platform, arch) => {
+ // On macOS the packaged app is universal, so both architectures must be
+ // staged regardless of which arch this build pass is for.
+ const arches = platform == "darwin" ? ["arm64", "x64"] : [arch];
+
+ const stageDir = path.join(appDir, "build", "ml-native");
+ await fsp.mkdir(stageDir, { recursive: true });
+
+ const wanted = [];
+ for (const a of arches) {
+ const addonPath = await buildAddonIfNeeded(appDir, platform, a);
+ wanted.push(path.basename(addonPath));
+ await fsp.copyFile(
+ addonPath,
+ path.join(stageDir, path.basename(addonPath)),
+ );
+ }
+
+ // Remove addons staged by earlier passes for other platforms or
+ // architectures so that they don't get copied into this package.
+ for (const entry of await fsp.readdir(stageDir))
+ if (!wanted.includes(entry))
+ await fsp.rm(path.join(stageDir, entry), { recursive: true });
+};
+
+module.exports = { stageMLAddons };
diff --git a/desktop/scripts/ml_parity_host.js b/desktop/scripts/ml_parity_host.js
deleted file mode 100755
index 97397d84f2..0000000000
--- a/desktop/scripts/ml_parity_host.js
+++ /dev/null
@@ -1,455 +0,0 @@
-#!/usr/bin/env node
-
-"use strict";
-
-const crypto = require("node:crypto");
-const fs = require("node:fs/promises");
-const path = require("node:path");
-const readline = require("node:readline");
-const { BrowserWindow, MessageChannelMain } = require("electron");
-const { app, utilityProcess } = require("electron/main");
-const { wrap } = require("comlink");
-
-const MODEL_FILE_NAMES = {
- clip: "mobileclip_s2_image_opset18_rgba_opt.onnx",
- face_detection: "yolov5s_face_opset18_rgba_opt_nosplits.onnx",
- face_embedding: "mobilefacenet_opset15.onnx",
-};
-const HOST_RESPONSE_PREFIX = "__ML_PARITY_JSON__";
-
-const SCRIPT_DIR = __dirname;
-const DESKTOP_DIR = path.resolve(SCRIPT_DIR, "..");
-const REPO_ROOT = path.resolve(DESKTOP_DIR, "..");
-const COMPILED_ML_WORKER_PATH = path.join(
- REPO_ROOT,
- "desktop",
- "app",
- "main",
- "services",
- "ml-worker.js",
-);
-const COMPILED_IMAGE_SERVICE_PATH = path.join(
- REPO_ROOT,
- "desktop",
- "app",
- "main",
- "services",
- "image.js",
-);
-
-const messagePortMainEndpoint = (mp) => {
- const listeners = new WeakMap();
- return {
- postMessage: (message, transfer) => {
- mp.postMessage(message, transfer ?? []);
- },
- addEventListener: (_event, handler) => {
- const listener = (data) =>
- "handleEvent" in handler
- ? handler.handleEvent({ data })
- : handler(data);
- mp.on("message", (data) => {
- listener(data);
- });
- listeners.set(handler, listener);
- },
- removeEventListener: (_event, handler) => {
- const listener = listeners.get(handler);
- if (!listener) {
- return;
- }
- mp.off("message", listener);
- listeners.delete(handler);
- },
- start: mp.start.bind(mp),
- };
-};
-
-const toBase64FromTypedArray = (array) =>
- Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString(
- "base64",
- );
-
-const uint8ClampedArrayFromBase64 = (payload) => {
- const bytes = Buffer.from(payload, "base64");
- const array = new Uint8ClampedArray(bytes.byteLength);
- array.set(bytes);
- return array;
-};
-
-const float32ArrayFromBase64 = (payload) => {
- const bytes = Buffer.from(payload, "base64");
- if (bytes.byteLength % 4 !== 0) {
- throw new Error(
- `Float32 payload byte length ${bytes.byteLength} is not divisible by 4`,
- );
- }
- const array = new Float32Array(bytes.byteLength / 4);
- new Uint8Array(array.buffer).set(bytes);
- return array;
-};
-
-let _convertToJPEG;
-const getConvertToJPEG = () => {
- if (_convertToJPEG) {
- return _convertToJPEG;
- }
- const imageService = require(COMPILED_IMAGE_SERVICE_PATH);
- if (!imageService || typeof imageService.convertToJPEG !== "function") {
- throw new Error(
- `convertToJPEG export not found in ${COMPILED_IMAGE_SERVICE_PATH}`,
- );
- }
- _convertToJPEG = imageService.convertToJPEG;
- return _convertToJPEG;
-};
-
-const DEFAULT_DECODE_HELPER_SOURCE = `async (imageBlob) => {
- const imageBitmap = await createImageBitmap(imageBlob);
-
- const { width, height } = imageBitmap;
-
- // Use an OffscreenCanvas to get the bitmap's data.
- const offscreenCanvas = new OffscreenCanvas(width, height);
- const ctx = offscreenCanvas.getContext("2d");
- ctx.drawImage(imageBitmap, 0, 0, width, height);
- const imageData = ctx.getImageData(0, 0, width, height);
-
- return { bitmap: imageBitmap, data: imageData };
-}`;
-
-const ensureDecodeWindowScript = async (decodeWindow, decodeHelperSource) => {
- await decodeWindow.webContents.executeJavaScript(
- `
-(() => {
- const decodeHelperSource = ${JSON.stringify(decodeHelperSource)};
-
- if (
- typeof globalThis.__mlParityCreateImageBitmapAndData !== "function" ||
- globalThis.__mlParityDecodeHelperSource !== decodeHelperSource
- ) {
- const helper = eval("(" + decodeHelperSource + ")");
- if (typeof helper !== "function") {
- throw new Error("Decode helper source did not evaluate to a function");
- }
- globalThis.__mlParityCreateImageBitmapAndData = helper;
- globalThis.__mlParityDecodeHelperSource = decodeHelperSource;
- globalThis.__mlParityDecodeFile = undefined;
- }
-
- if (typeof globalThis.__mlParityDecodeFile === "function") return;
- globalThis.__mlParityDecodeFile = async (filePath, mimeType) => {
- const fs = require("node:fs/promises");
- const bytes = await fs.readFile(filePath);
- const blob = mimeType ? new Blob([bytes], { type: mimeType }) : new Blob([bytes]);
- const { bitmap, data } = await globalThis.__mlParityCreateImageBitmapAndData(blob);
- try {
- return {
- width: data.width,
- height: data.height,
- rgba_base64: Buffer.from(data.data.buffer).toString("base64"),
- };
- } finally {
- if (bitmap && typeof bitmap.close === "function") bitmap.close();
- }
- };
-})();
- `,
- true,
- );
-};
-
-const rgbaBase64FromPath = async (
- decodeWindow,
- decodeHelperSource,
- filePath,
- mimeType,
-) => {
- if (!decodeWindow || decodeWindow.isDestroyed()) {
- throw new Error("Decode window is unavailable");
- }
- if (!decodeWindow.webContents || decodeWindow.webContents.isDestroyed()) {
- throw new Error("Decode window webContents is unavailable");
- }
-
- await ensureDecodeWindowScript(decodeWindow, decodeHelperSource);
- const invocation = `globalThis.__mlParityDecodeFile(${JSON.stringify(filePath)}, ${JSON.stringify(mimeType ?? null)})`;
- return decodeWindow.webContents.executeJavaScript(invocation, true);
-};
-
-const sha256ForFile = async (filePath) => {
- const contents = await fs.readFile(filePath);
- return crypto.createHash("sha256").update(contents).digest("hex");
-};
-
-const modelMetadata = async (userDataPath) => {
- const modelsDir = path.join(userDataPath, "models");
- const result = {};
-
- await fs.mkdir(modelsDir, { recursive: true });
-
- for (const [modelName, fileName] of Object.entries(MODEL_FILE_NAMES)) {
- const filePath = path.join(modelsDir, fileName);
- try {
- await fs.access(filePath);
- const sha256 = await sha256ForFile(filePath);
- result[modelName] = `${fileName}:sha256:${sha256}`;
- } catch {
- result[modelName] = `${fileName}:missing`;
- }
- }
-
- return result;
-};
-
-const sendResponse = (payload) => {
- process.stdout.write(`${HOST_RESPONSE_PREFIX}${JSON.stringify(payload)}\n`);
-};
-
-const createWorkerState = async () => {
- await app.whenReady();
-
- try {
- await fs.access(COMPILED_ML_WORKER_PATH);
- } catch {
- throw new Error(
- "Compiled desktop ML worker not found. Run `npm --prefix desktop exec -- tsc -p desktop/tsconfig.json` first.",
- );
- }
- try {
- await fs.access(COMPILED_IMAGE_SERVICE_PATH);
- } catch {
- throw new Error(
- "Compiled desktop image service not found. Run `npm --prefix desktop exec -- tsc -p desktop/tsconfig.json` first.",
- );
- }
-
- const userDataPath =
- process.env.ML_PARITY_USER_DATA_DIR?.trim() || app.getPath("userData");
- await fs.mkdir(userDataPath, { recursive: true });
-
- const { port1, port2 } = new MessageChannelMain();
- const child = utilityProcess.fork(COMPILED_ML_WORKER_PATH);
- child.postMessage({ userDataPath }, [port1]);
-
- const decodeWindow = new BrowserWindow({
- show: false,
- webPreferences: {
- nodeIntegration: true,
- contextIsolation: false,
- sandbox: false,
- },
- });
- await decodeWindow.loadURL("about:blank");
- await ensureDecodeWindowScript(decodeWindow, DEFAULT_DECODE_HELPER_SOURCE);
-
- child.on("message", (message) => {
- if (
- message &&
- typeof message === "object" &&
- "method" in message &&
- message.method === "log"
- ) {
- return;
- }
- process.stderr.write(
- `[ml_parity_host] utility-process message: ${JSON.stringify(message)}\n`,
- );
- });
-
- child.on("exit", (code, signal) => {
- process.stderr.write(
- `[ml_parity_host] utility process exited code=${code ?? "null"} signal=${signal ?? "null"}\n`,
- );
- });
-
- const worker = wrap(messagePortMainEndpoint(port2));
-
- return {
- child,
- decodeHelperSource: DEFAULT_DECODE_HELPER_SOURCE,
- decodeWindow,
- worker,
- userDataPath,
- };
-};
-
-let workerStatePromise;
-
-const getWorkerState = () => {
- workerStatePromise ??= createWorkerState();
- return workerStatePromise;
-};
-
-const handleRequest = async (request) => {
- if (!request || typeof request !== "object") {
- throw new Error("Invalid request payload");
- }
-
- const { method, params } = request;
- const state = await getWorkerState();
-
- switch (method) {
- case "decodeImage": {
- if (!params || typeof params.file_path !== "string") {
- throw new Error("decodeImage requires params.file_path");
- }
- const mimeType =
- typeof params.mime_type === "string" && params.mime_type.trim()
- ? params.mime_type.trim()
- : undefined;
- return rgbaBase64FromPath(
- state.decodeWindow,
- state.decodeHelperSource,
- params.file_path,
- mimeType,
- );
- }
- case "setDecodeHelperSource": {
- if (
- !params ||
- typeof params.source !== "string" ||
- !params.source.trim()
- ) {
- throw new Error("setDecodeHelperSource requires params.source");
- }
- state.decodeHelperSource = params.source;
- await ensureDecodeWindowScript(
- state.decodeWindow,
- state.decodeHelperSource,
- );
- return { ok: true };
- }
- case "convertToJPEG": {
- if (!params || typeof params.input_base64 !== "string") {
- throw new Error("convertToJPEG requires params.input_base64");
- }
- const input = new Uint8Array(
- Buffer.from(params.input_base64, "base64"),
- );
- const output = await getConvertToJPEG()(input);
- return { output_base64: Buffer.from(output).toString("base64") };
- }
- case "computeCLIPImageEmbedding": {
- if (!params || typeof params.input_base64 !== "string") {
- throw new Error(
- "computeCLIPImageEmbedding requires params.input_base64",
- );
- }
- if (!Array.isArray(params.input_shape)) {
- throw new Error(
- "computeCLIPImageEmbedding requires params.input_shape",
- );
- }
- const input = uint8ClampedArrayFromBase64(params.input_base64);
- const output = await state.worker.computeCLIPImageEmbedding(
- input,
- params.input_shape,
- );
- return { output_base64: toBase64FromTypedArray(output) };
- }
- case "detectFaces": {
- if (!params || typeof params.input_base64 !== "string") {
- throw new Error("detectFaces requires params.input_base64");
- }
- if (!Array.isArray(params.input_shape)) {
- throw new Error("detectFaces requires params.input_shape");
- }
- const input = uint8ClampedArrayFromBase64(params.input_base64);
- const output = await state.worker.detectFaces(
- input,
- params.input_shape,
- );
- return { output_base64: toBase64FromTypedArray(output) };
- }
- case "computeFaceEmbeddings": {
- if (!params || typeof params.input_base64 !== "string") {
- throw new Error(
- "computeFaceEmbeddings requires params.input_base64",
- );
- }
- const input = float32ArrayFromBase64(params.input_base64);
- const output = await state.worker.computeFaceEmbeddings(input);
- return { output_base64: toBase64FromTypedArray(output) };
- }
- case "modelMetadata": {
- return modelMetadata(state.userDataPath);
- }
- case "shutdown": {
- return { ok: true };
- }
- default:
- throw new Error(`Unsupported method '${String(method)}'`);
- }
-};
-
-const shutdown = async () => {
- try {
- const state = await workerStatePromise;
- if (state.decodeWindow && !state.decodeWindow.isDestroyed()) {
- state.decodeWindow.destroy();
- }
- state.child.kill();
- } catch {
- // Ignore shutdown failures.
- }
-
- try {
- await app.quit();
- } catch {
- process.exit(0);
- }
-};
-
-const rl = readline.createInterface({
- input: process.stdin,
- crlfDelay: Infinity,
-});
-
-rl.on("line", async (line) => {
- if (!line.trim()) {
- return;
- }
-
- let request;
- try {
- request = JSON.parse(line);
- } catch (error) {
- sendResponse({
- id: null,
- ok: false,
- error: `Failed to parse request JSON: ${String(error)}`,
- });
- return;
- }
-
- const id = request.id ?? null;
-
- try {
- const result = await handleRequest(request);
- sendResponse({ id, ok: true, result });
- if (request.method === "shutdown") {
- setTimeout(() => {
- void shutdown();
- }, 0);
- }
- } catch (error) {
- sendResponse({
- id,
- ok: false,
- error: error instanceof Error ? error.message : String(error),
- });
- }
-});
-
-rl.on("close", () => {
- void shutdown();
-});
-
-process.on("SIGINT", () => {
- void shutdown();
-});
-
-process.on("SIGTERM", () => {
- void shutdown();
-});
diff --git a/desktop/scripts/ml_parity_runner.ts b/desktop/scripts/ml_parity_runner.ts
deleted file mode 100755
index d99034bc75..0000000000
--- a/desktop/scripts/ml_parity_runner.ts
+++ /dev/null
@@ -1,1015 +0,0 @@
-#!/usr/bin/env node
-
-import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
-import crypto from "node:crypto";
-import { once } from "node:events";
-import { createReadStream } from "node:fs";
-import fs from "node:fs/promises";
-import path from "node:path";
-import { performance } from "node:perf_hooks";
-import process from "node:process";
-import readline from "node:readline";
-import { fileURLToPath } from "node:url";
-
-interface ManifestItem {
- file_id: string;
- source: string;
- source_sha256?: string;
-}
-
-interface RunnerArgs {
- manifestPath: string;
- outputDir: string;
- hostScriptPath: string;
- electronBinPath: string;
- userDataPath: string;
-}
-
-interface DecodedImage {
- width: number;
- height: number;
- rgba: Uint8ClampedArray;
-}
-
-interface HostRequest {
- id: number;
- method: string;
- params?: Record<string, unknown>;
-}
-
-interface HostResponse {
- id: number | null;
- ok: boolean;
- result?: unknown;
- error?: unknown;
-}
-
-interface PendingRequest {
- resolve: (value: unknown) => void;
- reject: (reason: unknown) => void;
- timeoutHandle: ReturnType<typeof setTimeout>;
-}
-
-interface WebMLBindings {
- indexCLIP: (
- image: unknown,
- electron: unknown,
- ) => Promise<{ embedding: number[] }>;
- indexFaces: (
- file: unknown,
- image: unknown,
- electron: unknown,
- ) => Promise<{
- faces: Array<{
- detection: {
- box: { x: number; y: number; width: number; height: number };
- landmarks: Array<{ x: number; y: number }>;
- };
- score: number;
- embedding: number[];
- }>;
- }>;
- createImageBitmapAndData: (...args: unknown[]) => Promise<unknown>;
- renderableImageBlob: (blob: Blob, fileName: string) => Promise<Blob>;
-}
-
-const SCRIPT_DIR = path.dirname(fileURLToPath(import.meta.url));
-const REPO_ROOT = path.resolve(SCRIPT_DIR, "..", "..");
-const DESKTOP_ROOT = path.join(REPO_ROOT, "desktop");
-const ML_DIR = path.join(REPO_ROOT, "infra", "ml", "test");
-
-const DEFAULT_MANIFEST_PATH = path.join(
- REPO_ROOT,
- "infra",
- "ml",
- "test",
- "ground_truth",
- "manifest.json",
-);
-
-const DEFAULT_OUTPUT_DIR = path.join(
- REPO_ROOT,
- "infra",
- "ml",
- "test",
- "out",
- "parity",
- "desktop",
-);
-const DEFAULT_HOST_SCRIPT_PATH = path.join(
- REPO_ROOT,
- "desktop",
- "scripts",
- "ml_parity_host.js",
-);
-const DEFAULT_ELECTRON_BIN_PATH = path.join(
- REPO_ROOT,
- "desktop",
- "node_modules",
- ".bin",
- "electron",
-);
-const DEFAULT_USER_DATA_PATH = path.join(
- REPO_ROOT,
- "infra",
- "ml",
- "test",
- ".cache",
- "desktop-user-data",
-);
-
-const MODEL_FILE_NAMES: Record<string, string> = {
- clip: "mobileclip_s2_image_opset18_rgba_opt.onnx",
- face_detection: "yolov5s_face_opset18_rgba_opt_nosplits.onnx",
- face_embedding: "mobilefacenet_opset15.onnx",
-};
-const HOST_RESPONSE_PREFIX = "__ML_PARITY_JSON__";
-const DEFAULT_HOST_REQUEST_TIMEOUT_MS = 120_000;
-
-const parseHostRequestTimeoutMS = (value: string | undefined): number => {
- const trimmed = value?.trim();
- if (!trimmed) {
- return DEFAULT_HOST_REQUEST_TIMEOUT_MS;
- }
- const parsed = Number.parseInt(trimmed, 10);
- if (!Number.isFinite(parsed) || parsed < 1_000) {
- throw new Error(
- "ML_PARITY_HOST_REQUEST_TIMEOUT_MS must be an integer >= 1000",
- );
- }
- return parsed;
-};
-const HOST_REQUEST_TIMEOUT_MS = parseHostRequestTimeoutMS(
- process.env.ML_PARITY_HOST_REQUEST_TIMEOUT_MS,
-);
-
-const usage = () => {
- process.stderr.write(
- `Usage: desktop/scripts/ml_parity_runner.ts [flags]\n\n`,
- );
- process.stderr.write(`Flags:\n`);
- process.stderr.write(
- ` --manifest <path> Path to parity manifest (default: infra/ml/test/ground_truth/manifest.json)\n`,
- );
- process.stderr.write(
- ` --output-dir <path> Output directory for desktop parity JSONs\n`,
- );
- process.stderr.write(` --electron-bin <path> Electron binary path\n`);
- process.stderr.write(` --host-script <path> Host script path\n`);
- process.stderr.write(
- ` --user-data-dir <path> Desktop ML model cache/user-data path\n`,
- );
-};
-
-const resolveRepoPath = (inputPath: string) =>
- path.isAbsolute(inputPath) ? inputPath : path.resolve(REPO_ROOT, inputPath);
-
-const resolveMLPath = (inputPath: string) =>
- path.isAbsolute(inputPath) ? inputPath : path.resolve(ML_DIR, inputPath);
-
-const parseArgs = (argv: string[]): RunnerArgs => {
- let manifestPath = DEFAULT_MANIFEST_PATH;
- let outputDir = DEFAULT_OUTPUT_DIR;
- let hostScriptPath =
- process.env.ML_PARITY_HOST_SCRIPT?.trim() || DEFAULT_HOST_SCRIPT_PATH;
- let electronBinPath =
- process.env.ML_PARITY_ELECTRON_BIN?.trim() || DEFAULT_ELECTRON_BIN_PATH;
- let userDataPath =
- process.env.ML_PARITY_USER_DATA_DIR?.trim() || DEFAULT_USER_DATA_PATH;
-
- for (let i = 0; i < argv.length; i += 1) {
- const arg = argv[i];
- switch (arg) {
- case "--manifest": {
- const value = argv[i + 1];
- if (!value) {
- throw new Error("--manifest requires a value");
- }
- manifestPath = value;
- i += 1;
- break;
- }
- case "--output-dir": {
- const value = argv[i + 1];
- if (!value) {
- throw new Error("--output-dir requires a value");
- }
- outputDir = value;
- i += 1;
- break;
- }
- case "--electron-bin": {
- const value = argv[i + 1];
- if (!value) {
- throw new Error("--electron-bin requires a value");
- }
- electronBinPath = value;
- i += 1;
- break;
- }
- case "--host-script": {
- const value = argv[i + 1];
- if (!value) {
- throw new Error("--host-script requires a value");
- }
- hostScriptPath = value;
- i += 1;
- break;
- }
- case "--user-data-dir": {
- const value = argv[i + 1];
- if (!value) {
- throw new Error("--user-data-dir requires a value");
- }
- userDataPath = value;
- i += 1;
- break;
- }
- case "-h":
- case "--help": {
- usage();
- process.exit(0);
- }
- default:
- throw new Error(`Unknown argument '${arg}'`);
- }
- }
-
- return {
- manifestPath: resolveRepoPath(manifestPath),
- outputDir: resolveRepoPath(outputDir),
- hostScriptPath: resolveRepoPath(hostScriptPath),
- electronBinPath: resolveRepoPath(electronBinPath),
- userDataPath: resolveRepoPath(userDataPath),
- };
-};
-
-const toBase64 = (
- array: ArrayLike<number> & {
- buffer: ArrayBufferLike;
- byteOffset: number;
- byteLength: number;
- },
-) =>
- Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString(
- "base64",
- );
-
-const uint8ClampedArrayFromBase64 = (payload: string) => {
- const bytes = Buffer.from(payload, "base64");
- const array = new Uint8ClampedArray(bytes.byteLength);
- array.set(bytes);
- return array;
-};
-
-const float32ArrayFromBase64 = (payload: string) => {
- const bytes = Buffer.from(payload, "base64");
- if (bytes.byteLength % 4 !== 0) {
- throw new Error(
- `Float32 payload byte length ${bytes.byteLength} is not divisible by 4`,
- );
- }
- const array = new Float32Array(bytes.byteLength / 4);
- new Uint8Array(array.buffer).set(bytes);
- return array;
-};
-
-const stringifyUnknown = (value: unknown) => {
- if (typeof value === "string") {
- return value;
- }
- try {
- const serialized = JSON.stringify(value);
- if (typeof serialized === "string") {
- return serialized;
- }
- return String(value);
- } catch {
- return String(value);
- }
-};
-
-const normalizeHostErrorPayload = (value: unknown) => {
- if (value && typeof value === "object") {
- const maybeError = value as Record<string, unknown>;
- const messageCandidate =
- (typeof maybeError.message === "string" && maybeError.message) ||
- (typeof maybeError.error === "string" && maybeError.error);
- if (messageCandidate && messageCandidate !== "[object Object]") {
- return messageCandidate;
- }
- }
-
- const normalized = stringifyUnknown(value);
- if (normalized === "[object Object]") {
- return "Host request failed with opaque object error ([object Object]); see preceding host logs for context.";
- }
- return normalized;
-};
-
-class HostClient {
- private readonly process: ChildProcessWithoutNullStreams;
- private readonly rl: readline.Interface;
- private nextID = 1;
- private readonly pending = new Map<number, PendingRequest>();
- private readonly requestTimeoutMS: number;
- private closed = false;
-
- constructor(
- electronBinPath: string,
- hostScriptPath: string,
- userDataPath: string,
- ) {
- this.requestTimeoutMS = HOST_REQUEST_TIMEOUT_MS;
- this.process = spawn(electronBinPath, [hostScriptPath], {
- cwd: DESKTOP_ROOT,
- env: { ...process.env, ML_PARITY_USER_DATA_DIR: userDataPath },
- stdio: ["pipe", "pipe", "pipe"],
- });
-
- this.process.stderr.setEncoding("utf8");
- this.process.stderr.on("data", (chunk: string) => {
- process.stderr.write(chunk);
- });
-
- this.rl = readline.createInterface({
- input: this.process.stdout,
- crlfDelay: Infinity,
- });
-
- this.rl.on("line", (line) => {
- const trimmed = line.trim();
- if (!trimmed) {
- return;
- }
- if (!trimmed.startsWith(HOST_RESPONSE_PREFIX)) {
- process.stderr.write(
- `[ml_parity_runner] host stdout (non-protocol): ${trimmed}\n`,
- );
- return;
- }
-
- const payload = trimmed.slice(HOST_RESPONSE_PREFIX.length);
- let message: HostResponse;
- try {
- message = JSON.parse(payload) as HostResponse;
- } catch (error) {
- this.rejectAll(
- new Error(
- `Failed to parse host JSON response: ${String(error)}`,
- ),
- );
- return;
- }
-
- if (message.id === null || message.id === undefined) {
- if (!message.ok) {
- process.stderr.write(
- `[ml_parity_runner] host emitted error without request id: ${normalizeHostErrorPayload(message.error ?? "unknown error")}\n`,
- );
- }
- return;
- }
-
- const pending = this.pending.get(message.id);
- if (!pending) {
- return;
- }
- clearTimeout(pending.timeoutHandle);
- this.pending.delete(message.id);
-
- if (message.ok) {
- pending.resolve(message.result);
- } else {
- pending.reject(
- new Error(
- normalizeHostErrorPayload(
- message.error ?? "Host request failed",
- ),
- ),
- );
- }
- });
-
- this.process.on("error", (error) => {
- this.rejectAll(error);
- });
-
- this.process.on("exit", (code, signal) => {
- this.closed = true;
- this.rejectAll(
- new Error(
- `Host process exited unexpectedly (code=${String(code)}, signal=${String(signal)})`,
- ),
- );
- });
- }
-
- private rejectAll(error: unknown) {
- if (this.pending.size === 0) {
- return;
- }
- for (const pending of this.pending.values()) {
- clearTimeout(pending.timeoutHandle);
- pending.reject(error);
- }
- this.pending.clear();
- }
-
- private async writeRequest(request: HostRequest) {
- if (this.closed) {
- throw new Error("Host process is closed");
- }
- const line = `${JSON.stringify(request)}\n`;
- if (this.process.stdin.write(line)) {
- return;
- }
- await once(this.process.stdin, "drain");
- }
-
- private async request(method: string, params?: Record<string, unknown>) {
- const id = this.nextID;
- this.nextID += 1;
-
- const resultPromise = new Promise<unknown>((resolve, reject) => {
- const timeoutHandle = setTimeout(() => {
- const pending = this.pending.get(id);
- if (!pending) {
- return;
- }
- this.pending.delete(id);
- pending.reject(
- new Error(
- `Host request '${method}' timed out after ${this.requestTimeoutMS}ms`,
- ),
- );
- }, this.requestTimeoutMS);
- this.pending.set(id, { resolve, reject, timeoutHandle });
- });
-
- try {
- await this.writeRequest({ id, method, params });
- } catch (error) {
- const pending = this.pending.get(id);
- if (pending) {
- clearTimeout(pending.timeoutHandle);
- this.pending.delete(id);
- }
- throw error;
- }
- return resultPromise;
- }
-
- async decodeImage(
- filePath: string,
- mimeType?: string,
- ): Promise<DecodedImage> {
- const result = (await this.request("decodeImage", {
- file_path: filePath,
- mime_type: mimeType,
- })) as { width: number; height: number; rgba_base64: string };
-
- if (
- typeof result?.width !== "number" ||
- typeof result?.height !== "number" ||
- typeof result?.rgba_base64 !== "string"
- ) {
- throw new Error("Invalid decodeImage response payload");
- }
-
- return {
- width: result.width,
- height: result.height,
- rgba: uint8ClampedArrayFromBase64(result.rgba_base64),
- };
- }
-
- async setDecodeHelperSource(source: string) {
- await this.request("setDecodeHelperSource", { source });
- }
-
- async convertToJPEG(input: Uint8Array): Promise<Uint8Array> {
- const result = (await this.request("convertToJPEG", {
- input_base64: Buffer.from(input).toString("base64"),
- })) as { output_base64: string };
-
- if (typeof result?.output_base64 !== "string") {
- throw new Error("Invalid convertToJPEG response payload");
- }
-
- return new Uint8Array(Buffer.from(result.output_base64, "base64"));
- }
-
- async computeCLIPImageEmbedding(
- input: Uint8ClampedArray,
- inputShape: number[],
- ): Promise<Float32Array> {
- const result = (await this.request("computeCLIPImageEmbedding", {
- input_base64: toBase64(input),
- input_shape: inputShape,
- })) as { output_base64: string };
-
- if (typeof result?.output_base64 !== "string") {
- throw new Error(
- "Invalid computeCLIPImageEmbedding response payload",
- );
- }
-
- return float32ArrayFromBase64(result.output_base64);
- }
-
- async detectFaces(
- input: Uint8ClampedArray,
- inputShape: number[],
- ): Promise<Float32Array> {
- const result = (await this.request("detectFaces", {
- input_base64: toBase64(input),
- input_shape: inputShape,
- })) as { output_base64: string };
-
- if (typeof result?.output_base64 !== "string") {
- throw new Error("Invalid detectFaces response payload");
- }
-
- return float32ArrayFromBase64(result.output_base64);
- }
-
- async computeFaceEmbeddings(input: Float32Array): Promise<Float32Array> {
- const result = (await this.request("computeFaceEmbeddings", {
- input_base64: toBase64(input),
- })) as { output_base64: string };
-
- if (typeof result?.output_base64 !== "string") {
- throw new Error("Invalid computeFaceEmbeddings response payload");
- }
-
- return float32ArrayFromBase64(result.output_base64);
- }
-
- async modelMetadata(): Promise<Record<string, string>> {
- const result = (await this.request("modelMetadata")) as Record<
- string,
- string
- >;
- if (!result || typeof result !== "object") {
- throw new Error("Invalid modelMetadata response payload");
- }
- return result;
- }
-
- async shutdown() {
- if (this.closed) {
- return;
- }
-
- try {
- await this.request("shutdown");
- } catch {
- // Ignore shutdown RPC failures.
- }
-
- this.rl.close();
-
- if (!this.process.killed) {
- this.process.kill();
- }
- }
-}
-
-const gitRevision = async () => {
- const { execFile } = await import("node:child_process");
- return new Promise<string>((resolve) => {
- execFile(
- "git",
- ["rev-parse", "--short", "HEAD"],
- { cwd: REPO_ROOT },
- (error, stdout) => {
- if (error) {
- resolve("local");
- return;
- }
- const revision = stdout.trim();
- resolve(revision || "local");
- },
- );
- });
-};
-
-const sha256Hex = async (filePath: string) => {
- const hash = crypto.createHash("sha256");
-
- await new Promise<void>((resolve, reject) => {
- const stream = createReadStream(filePath);
- stream.on("data", (chunk) => hash.update(chunk));
- stream.on("error", reject);
- stream.on("end", () => resolve());
- });
-
- return hash.digest("hex");
-};
-
-const safeFileName = (fileID: string) => fileID.replaceAll("/", "__");
-const extensionFromSource = (sourcePath: string) => {
- const extension = path.extname(sourcePath).trim();
- if (!extension) {
- return ".bin";
- }
- return extension.toLowerCase();
-};
-
-const ensureModelMetadata = (metadata: Record<string, string>) => {
- const normalized = { ...metadata };
- for (const [modelName, fileName] of Object.entries(MODEL_FILE_NAMES)) {
- normalized[modelName] = normalized[modelName] || `${fileName}:unknown`;
- }
- return normalized;
-};
-
-const normalizeUnknownError = (
- error: unknown,
-): { message: string; stack?: string } => {
- if (error instanceof Error) {
- return {
- message: error.message,
- ...(typeof error.stack === "string" && error.stack.length > 0
- ? { stack: error.stack }
- : {}),
- };
- }
-
- if (typeof error === "string") {
- return { message: error };
- }
-
- if (error && typeof error === "object") {
- const maybeError = error as Record<string, unknown>;
- const messageCandidate =
- (typeof maybeError.message === "string" && maybeError.message) ||
- (typeof maybeError.error === "string" && maybeError.error) ||
- stringifyUnknown(error);
- const stackCandidate =
- typeof maybeError.stack === "string" ? maybeError.stack : undefined;
- return {
- message: messageCandidate,
- ...(stackCandidate ? { stack: stackCandidate } : {}),
- };
- }
-
- return { message: String(error) };
-};
-
-const ensureSimilarityTransformationNodeShim = async () => {
- const dependencyDir = path.join(
- REPO_ROOT,
- "web",
- "node_modules",
- "similarity-transformation",
- );
- const packageJSONPath = path.join(dependencyDir, "package.json");
-
- try {
- await fs.access(packageJSONPath);
- } catch {
- return;
- }
-
- const packageJSON = JSON.parse(
- await fs.readFile(packageJSONPath, "utf8"),
- ) as { main?: string; module?: string };
- if (typeof packageJSON.main === "string" && packageJSON.main.trim()) {
- return;
- }
-
- const moduleEntry = packageJSON.module?.trim();
- if (!moduleEntry) {
- return;
- }
-
- const modulePath = path.join(dependencyDir, moduleEntry);
- try {
- await fs.access(modulePath);
- } catch {
- return;
- }
-
- const indexJSPath = path.join(dependencyDir, "index.js");
- try {
- await fs.access(indexJSPath);
- return;
- } catch {
- // Create a local shim only for parity runner compatibility under Node CJS resolution.
- }
-
- const normalizedEntry = moduleEntry.startsWith("./")
- ? moduleEntry
- : `./${moduleEntry}`;
- await fs.writeFile(
- indexJSPath,
- `module.exports = require("${normalizedEntry}");\n`,
- );
-};
-
-const loadWebMLBindings = async (): Promise<WebMLBindings> => {
- await ensureSimilarityTransformationNodeShim();
-
- const [clipModule, decodeModule, faceModule, convertModule] =
- await Promise.all([
- import("../../web/packages/new/photos/services/ml/clip.ts"),
- import("../../web/packages/new/photos/services/ml/decode.ts"),
- import("../../web/packages/new/photos/services/ml/face.ts"),
- import("../../web/packages/gallery/services/convert.ts"),
- ]);
-
- return {
- indexCLIP: clipModule.indexCLIP as WebMLBindings["indexCLIP"],
- indexFaces: faceModule.indexFaces as WebMLBindings["indexFaces"],
- createImageBitmapAndData:
- decodeModule.createImageBitmapAndData as WebMLBindings["createImageBitmapAndData"],
- renderableImageBlob:
- convertModule.renderableImageBlob as WebMLBindings["renderableImageBlob"],
- };
-};
-
-const productionDecodeHelperSource = (
- createImageBitmapAndData: (...args: unknown[]) => Promise<unknown>,
-) => {
- const source = createImageBitmapAndData.toString();
- if (
- !source.includes("createImageBitmap") ||
- !source.includes("OffscreenCanvas")
- ) {
- throw new Error(
- "Unexpected createImageBitmapAndData source; refusing to run parity with non-production decode helper",
- );
- }
- return source;
-};
-
-const main = async () => {
- const args = parseArgs(process.argv.slice(2));
-
- await fs.access(args.manifestPath);
- await fs.access(args.hostScriptPath);
- await fs.access(args.electronBinPath);
- await fs.mkdir(args.outputDir, { recursive: true });
- await fs.mkdir(args.userDataPath, { recursive: true });
-
- const manifestPayload = JSON.parse(
- await fs.readFile(args.manifestPath, "utf8"),
- ) as { items?: ManifestItem[] };
- const items = manifestPayload.items ?? [];
- if (!items.length) {
- throw new Error(`Manifest has no items: ${args.manifestPath}`);
- }
-
- const webBindings = await loadWebMLBindings();
- const host = new HostClient(
- args.electronBinPath,
- args.hostScriptPath,
- args.userDataPath,
- );
- await host.setDecodeHelperSource(
- productionDecodeHelperSource(webBindings.createImageBitmapAndData),
- );
-
- // `renderableImageBlob` and shared logging helpers check this shim.
- (
- globalThis as {
- electron?: {
- convertToJPEG: (imageData: Uint8Array) => Promise<Uint8Array>;
- logToDisk: (message: string) => void;
- };
- }
- ).electron = {
- convertToJPEG: (imageData: Uint8Array) => host.convertToJPEG(imageData),
- logToDisk: (message: string) => {
- process.stderr.write(`${message}\n`);
- },
- };
-
- const codeRevision = await gitRevision();
-
- const electronProxy = {
- computeCLIPImageEmbedding: (
- input: Uint8ClampedArray,
- inputShape: number[],
- ) => host.computeCLIPImageEmbedding(input, inputShape),
- detectFaces: (input: Uint8ClampedArray, inputShape: number[]) =>
- host.detectFaces(input, inputShape),
- computeFaceEmbeddings: (input: Float32Array) =>
- host.computeFaceEmbeddings(input),
- };
-
- const partialResults: Array<{
- file_id: string;
- clip: { embedding: number[] };
- faces: Array<{
- box: [number, number, number, number];
- landmarks: [number, number][];
- score: number;
- embedding: number[];
- }>;
- timing_ms: Record<string, number>;
- }> = [];
- const errors: Array<{
- file_id: string;
- error: string;
- timing_ms: number;
- stack?: string;
- }> = [];
-
- try {
- for (let i = 0; i < items.length; i += 1) {
- const item = items[i]!;
- const totalStart = performance.now();
- try {
- const sourcePath = resolveMLPath(item.source);
- await fs.access(sourcePath);
-
- if (item.source_sha256) {
- const sourceHash = await sha256Hex(sourcePath);
- if (
- sourceHash.toLowerCase() !==
- item.source_sha256.toLowerCase()
- ) {
- throw new Error(
- `source hash mismatch for ${item.file_id}: expected ${item.source_sha256}, got ${sourceHash}`,
- );
- }
- }
-
- process.stdout.write(
- `Desktop parity indexing ${i + 1}/${items.length}: ${item.file_id}\n`,
- );
-
- const decodeStart = performance.now();
- const sourceBlob = new Blob([await fs.readFile(sourcePath)]);
- const renderableBlob = await webBindings.renderableImageBlob(
- sourceBlob,
- path.basename(sourcePath),
- );
-
- const renderableDir = path.join(
- args.userDataPath,
- "renderable-cache",
- );
- await fs.mkdir(renderableDir, { recursive: true });
- const renderablePath = path.join(
- renderableDir,
- `${safeFileName(item.file_id)}${extensionFromSource(sourcePath)}`,
- );
- await fs.writeFile(
- renderablePath,
- new Uint8Array(await renderableBlob.arrayBuffer()),
- );
-
- let decoded: DecodedImage;
- try {
- decoded = await host.decodeImage(
- renderablePath,
- renderableBlob.type || undefined,
- );
- } finally {
- await fs.rm(renderablePath, { force: true });
- }
- const decodeMS = performance.now() - decodeStart;
-
- const imageData = {
- width: decoded.width,
- height: decoded.height,
- data: decoded.rgba,
- };
- const image = { data: imageData };
- const fileStub = { id: i + 1 };
-
- let faceMS = 0;
- let clipMS = 0;
-
- const facePromise = (async () => {
- const startedAt = performance.now();
- const value = await webBindings.indexFaces(
- fileStub as never,
- image as never,
- electronProxy as never,
- );
- faceMS = performance.now() - startedAt;
- return value;
- })();
-
- const clipPromise = (async () => {
- const startedAt = performance.now();
- const value = await webBindings.indexCLIP(
- image as never,
- electronProxy as never,
- );
- clipMS = performance.now() - startedAt;
- return value;
- })();
-
- const [faceIndex, clipIndex] = await Promise.all([
- facePromise,
- clipPromise,
- ]);
-
- const totalMS = performance.now() - totalStart;
-
- partialResults.push({
- file_id: item.file_id,
- clip: { embedding: clipIndex.embedding },
- faces: faceIndex.faces.map((face) => ({
- box: [
- face.detection.box.x,
- face.detection.box.y,
- face.detection.box.width,
- face.detection.box.height,
- ] as [number, number, number, number],
- landmarks: face.detection.landmarks.map(
- (point) => [point.x, point.y] as [number, number],
- ),
- score: face.score,
- embedding: face.embedding,
- })),
- timing_ms: {
- decode: decodeMS,
- face_index: faceMS,
- clip_index: clipMS,
- total: totalMS,
- },
- });
- } catch (error: unknown) {
- const elapsedMS = performance.now() - totalStart;
- const normalizedError = normalizeUnknownError(error);
- process.stderr.write(
- `[ml_parity_runner] failed to index ${item.file_id}: ${normalizedError.message}\n`,
- );
- errors.push({
- file_id: item.file_id,
- error: normalizedError.message,
- timing_ms: elapsedMS,
- ...(normalizedError.stack
- ? { stack: normalizedError.stack }
- : {}),
- });
- }
- }
-
- const models = ensureModelMetadata(await host.modelMetadata());
-
- const finalResults = partialResults.map((result) => ({
- file_id: result.file_id,
- clip: result.clip,
- faces: result.faces,
- runner_metadata: {
- platform: "desktop",
- runtime: "electron-onnxruntime-node",
- models,
- code_revision: codeRevision,
- timing_ms: result.timing_ms,
- },
- }));
-
- for (const result of finalResults) {
- const targetPath = path.join(
- args.outputDir,
- `${safeFileName(result.file_id)}.json`,
- );
- await fs.writeFile(
- targetPath,
- `${JSON.stringify(result, null, 2)}\n`,
- );
- }
-
- const combinedOutputPath = path.join(args.outputDir, "results.json");
- await fs.writeFile(
- combinedOutputPath,
- `${JSON.stringify(
- {
- platform: "desktop",
- results: finalResults,
- ...(errors.length > 0 ? { errors } : {}),
- },
- null,
- 2,
- )}\n`,
- );
-
- process.stdout.write(
- `Generated ${finalResults.length} desktop parity result(s) at ${args.outputDir}\n`,
- );
- if (errors.length > 0) {
- process.stdout.write(
- `Desktop parity recorded ${errors.length} per-file error(s)\n`,
- );
- }
- process.stdout.write(`Combined output: ${combinedOutputPath}\n`);
- } finally {
- await host.shutdown();
- }
-};
-
-main().catch((error: unknown) => {
- process.stderr.write(
- `${error instanceof Error ? error.stack || error.message : String(error)}\n`,
- );
- process.exit(1);
-});
diff --git a/desktop/scripts/ort.js b/desktop/scripts/ort.js
new file mode 100644
index 0000000000..23eba1c093
--- /dev/null
+++ b/desktop/scripts/ort.js
@@ -0,0 +1,101 @@
+/**
+ * [Note: ONNX Runtime binaries]
+ *
+ * The Rust ML addon (see [Note: ML with Rust]) loads the ONNX Runtime
+ * dynamic library at runtime. We use Ente's pinned custom builds β€” CoreML
+ * enabled on macOS, WebGPU-capable elsewhere β€” published at
+ * https://github.com/laurens-pilot/ort-packaging/releases
+ *
+ * This script downloads the archive for the relevant OS/arch combination,
+ * verifies it against the release's SHA-256 sidecar, and extracts it into
+ * `build/onnxruntime/<arch>`. From there it gets used during development, and
+ * copied into the packaged app's resources by the "extraFiles" clause in
+ * `electron-builder.yml`.
+ *
+ * On macOS both architectures are downloaded since the packaged app is a
+ * universal binary. Like `vips.js`, this script runs during "npm install"
+ * (via postinstall), while `beforeBuild.js` additionally invokes it for the
+ * specific architecture being packaged (which on CI might differ from the
+ * architecture we're running on).
+ */
+
+const crypto = require("node:crypto");
+const fsp = require("node:fs/promises");
+const path = require("node:path");
+const { execFileSync } = require("node:child_process");
+
+const version = "1.27.0-r2";
+
+const releaseURL = `https://github.com/laurens-pilot/ort-packaging/releases/download/ort-${version}`;
+
+const assetName = (platform, arch) => {
+ switch (platform) {
+ case "darwin":
+ return `onnxruntime-coreml-macos-${arch}-${version}.tar.gz`;
+ case "linux":
+ return `onnxruntime-webgpu-linux-${arch}-${version}.tar.gz`;
+ case "win32":
+ return `onnxruntime-webgpu-windows-${arch}-${version}.zip`;
+ default:
+ throw new Error(`Unsupported platform: ${platform}`);
+ }
+};
+
+/**
+ * Download and extract the ONNX Runtime library for the given OS/arch into
+ * `<appDir>/build/onnxruntime/<arch>`, no-oping if it is already there.
+ */
+const downloadONNXRuntimeIfNeeded = async (platform, arch, appDir) => {
+ const asset = assetName(platform, arch);
+ const outDir = path.join(appDir, "build", "onnxruntime", arch);
+ const stampPath = path.join(outDir, ".ente-ort-stamp");
+
+ try {
+ if ((await fsp.readFile(stampPath, "utf8")) == asset) return;
+ } catch {}
+
+ console.log(`Downloading ${asset}`);
+ const download = async (name) => {
+ const res = await fetch(`${releaseURL}/${name}`);
+ if (!res.ok)
+ throw new Error(`Failed to download ${name}: HTTP ${res.status}`);
+ return Buffer.from(await res.arrayBuffer());
+ };
+
+ const [archive, sidecar] = await Promise.all([
+ download(asset),
+ download(`${asset}.sha256`),
+ ]);
+
+ const expected = sidecar.toString("utf8").trim().split(/\s+/)[0];
+ const actual = crypto.createHash("sha256").update(archive).digest("hex");
+ if (actual != expected)
+ throw new Error(
+ `SHA-256 mismatch for ${asset}: expected ${expected}, got ${actual}`,
+ );
+
+ await fsp.rm(outDir, { recursive: true, force: true });
+ await fsp.mkdir(outDir, { recursive: true });
+ const archivePath = path.join(outDir, asset);
+ await fsp.writeFile(archivePath, archive);
+ // tar is available on all the platforms we build on (bsdtar on macOS and
+ // Windows, GNU tar on Linux), and handles both .tar.gz and .zip.
+ execFileSync("tar", ["-xf", asset], { cwd: outDir });
+ await fsp.rm(archivePath);
+ await fsp.writeFile(stampPath, asset);
+};
+
+const main = async () => {
+ const arches =
+ process.platform == "darwin" ? ["arm64", "x64"] : [process.arch];
+ for (const arch of arches)
+ await downloadONNXRuntimeIfNeeded(process.platform, arch, ".");
+};
+
+module.exports = { downloadONNXRuntimeIfNeeded };
+
+if (require.main === module)
+ main().catch((e) => {
+ console.error(e);
+ process.exit(1);
+ });
diff --git a/desktop/scripts/postinstall.mjs b/desktop/scripts/postinstall.mjs
index a00445578c..0e8f9e0072 100644
--- a/desktop/scripts/postinstall.mjs
+++ b/desktop/scripts/postinstall.mjs
@@ -37,10 +37,13 @@ const run = (cmd) => {
execSync(cmd, { stdio: "inherit" });
};
-run(
- "npm rebuild --ignore-scripts=false ffmpeg-static onnxruntime-node electron-winstaller",
-);
+run("npm rebuild --ignore-scripts=false ffmpeg-static electron-winstaller");
run("npm exec -- electron-builder install-app-deps");
run("node scripts/vips.js");
+run("node scripts/ort.js");
+// Build the Rust ML addon from source (requires a Rust toolchain). See
+// [Note: ML with Rust].
+console.log("> cargo codegen napi");
+execSync("cargo codegen napi", { cwd: "../rust", stdio: "inherit" });
writeFileSync(stamp, treeHash());
diff --git a/desktop/src/main/services/ml-native.ts b/desktop/src/main/services/ml-native.ts
new file mode 100644
index 0000000000..23b016e910
--- /dev/null
+++ b/desktop/src/main/services/ml-native.ts
@@ -0,0 +1,86 @@
+/**
+ * @file Locations of the Rust ML addon and the ONNX Runtime library.
+ *
+ * This code runs in the main process; the resolved (absolute) paths are
+ * passed to the ML utility process alongside the rest of its init data.
+ *
+ * [Note: ML with Rust]
+ *
+ * The ML indexing pipeline β€” image decode, preprocessing, ONNX inference,
+ * postprocessing β€” is implemented by a Rust crate shared by all Ente clients
+ * (rust/crates/photos). The desktop app talks to it through a Node native
+ * addon (rust/bindings/napi/photos), which loads ONNX Runtime dynamically at
+ * runtime from Ente's pinned custom builds (see [Note: ONNX Runtime binaries]
+ * in scripts/ort.js).
+ *
+ * During development, `cargo codegen napi` (invoked by our postinstall)
+ * builds the addon into the gitignored `rust-bindings/` directory. When
+ * packaging, `beforeBuild.js` stages the addon for the architectures being
+ * built into `build/ml-native/`, which electron-builder copies (along with
+ * `build/onnxruntime/`) into the app's resources directory.
+ */
+
+import path from "node:path";
+import { isDev } from "../utils/electron";
+
+/**
+ * Absolute paths needed by the ML utility process to load the Rust addon.
+ */
+export interface MLNativePaths {
+ /** The Node native addon (.node) with the Rust ML bindings. */
+ addon: string;
+ /** The ONNX Runtime dynamic library that the addon should load. */
+ onnxRuntimeLibrary: string;
+}
+
+/**
+ * The platform-arch triple that `napi build` uses when naming the built
+ * addon for the current process' platform and architecture.
+ */
+const napiTriple = () => {
+ switch (`${process.platform}-${process.arch}`) {
+ case "darwin-arm64":
+ return "darwin-arm64";
+ case "darwin-x64":
+ return "darwin-x64";
+ case "linux-x64":
+ return "linux-x64-gnu";
+ case "linux-arm64":
+ return "linux-arm64-gnu";
+ case "win32-x64":
+ return "win32-x64-msvc";
+ case "win32-arm64":
+ return "win32-arm64-msvc";
+ default:
+ throw new Error(
+ `Unsupported platform-arch: ${process.platform}-${process.arch}`,
+ );
+ }
+};
+
+const onnxRuntimeLibraryName = () => {
+ switch (process.platform) {
+ case "darwin":
+ return "libonnxruntime.1.27.0.dylib";
+ case "linux":
+ return "libonnxruntime.so.1.27.0";
+ case "win32":
+ return "onnxruntime.dll";
+ default:
+ throw new Error(`Unsupported platform: ${process.platform}`);
+ }
+};
+
+export const mlNativePaths = (): MLNativePaths => {
+ const addonName = `index.${napiTriple()}.node`;
+ const addon = isDev
+ ? path.resolve("rust-bindings", addonName)
+ : path.join(process.resourcesPath, "ml-native", addonName);
+ const onnxRuntimeLibrary = path.join(
+ isDev ? path.resolve("build") : process.resourcesPath,
+ "onnxruntime",
+ process.arch,
+ onnxRuntimeLibraryName(),
+ );
+ return { addon, onnxRuntimeLibrary };
+};
diff --git a/desktop/src/main/services/ml-worker.ts b/desktop/src/main/services/ml-worker.ts
index d539048e62..9fc32fcbb0 100644
--- a/desktop/src/main/services/ml-worker.ts
+++ b/desktop/src/main/services/ml-worker.ts
@@ -1,20 +1,23 @@
/**
* @file ML related tasks. This code runs in a utility process.
*
- * The ML runtime we use for inference is [ONNX](https://onnxruntime.ai). Models
- * for various tasks are not shipped with the app but are downloaded on demand.
+ * The ML pipeline itself β€” image decode, preprocessing, ONNX inference and
+ * postprocessing β€” is implemented by the Rust crate shared with the mobile
+ * apps, and reaches us via a Node native addon (see [Note: ML with Rust]).
+ * This file downloads the models the pipeline needs, loads the addon, and
+ * forwards requests that arrive from the web layer over our MessagePort.
*/
// See [Note: Using Electron APIs in UtilityProcess] about what we can and
// cannot import.
-import Tokenizer from "clip-bpe-js";
import { expose } from "comlink";
import { net } from "electron/main";
import { existsSync } from "fs";
+import { createHash } from "node:crypto";
+import { createReadStream } from "node:fs";
import fs from "node:fs/promises";
import path from "node:path";
-import * as ort from "onnxruntime-node";
import { z } from "zod";
import log from "../log-worker";
import { messagePortMainEndpoint } from "../utils/comlink";
@@ -22,22 +25,28 @@ import { wait } from "../utils/common";
import { writeStream } from "../utils/stream";
import { fsStatMtime } from "./fs";
+// The addon is loaded at runtime from the path the main process gives us, so
+// this import is used only for its types (it resolves to the generated
+// `rust-bindings/index.d.ts`).
+import type * as MLNativeModule from "../../../rust-bindings";
+import type { MLNativePaths } from "./ml-native";
+
log.debugString("Started ML utility process");
process.on("uncaughtException", (e, origin) => log.error(origin, e));
process.parentPort.once("message", (e) => {
// Initialize ourselves with the data we got from our parent.
- parseInitData(e.data);
+ const { mlNativePaths } = parseInitData(e.data);
+ loadMLNative(mlNativePaths);
// Expose an instance of `ElectronMLWorker` on the port we got from our
// parent.
expose(
{
fsStatMtime,
- computeCLIPImageEmbedding,
+ analyzeImage,
+ releaseMLRuntime,
computeCLIPTextEmbeddingIfAvailable,
- detectFaces,
- computeFaceEmbeddings,
},
messagePortMainEndpoint(e.ports[0]!),
);
@@ -53,86 +62,199 @@ let _userDataPath: string | undefined;
/** Equivalent to app.getPath("userData") */
const userDataPath = () => _userDataPath!;
-const MLWorkerInitData = z.object({ userDataPath: z.string() });
+const MLWorkerInitData = z.object({
+ userDataPath: z.string(),
+ mlNativePaths: z.object({
+ addon: z.string(),
+ onnxRuntimeLibrary: z.string(),
+ }),
+});
const parseInitData = (data: unknown) => {
- _userDataPath = MLWorkerInitData.parse(data).userDataPath;
+ const initData = MLWorkerInitData.parse(data);
+ _userDataPath = initData.userDataPath;
+ return initData;
};
+type MLNative = typeof MLNativeModule;
+
+let _native: MLNative | undefined;
+let _nativeLoadError: string | undefined;
+
/**
- * Return a function that can be used to trigger a download of the specified
- * model, and the creating of an ONNX inference session initialized using it.
- *
- * Multiple parallel calls to the returned function are fine, it ensures that
- * the the model will be downloaded and the session created using it only once.
- * All pending calls to it meanwhile will just await on the same promise.
- *
- * And once the promise is resolved, the create ONNX inference session will be
- * cached, so subsequent calls to the returned function will just reuse the same
- * session.
+ * Load the Rust ML addon and point it at the ONNX Runtime library.
*
- * {@link makeCachedInferenceSession} can itself be called anytime, it doesn't
- * actively trigger a download until the returned function is called.
- *
- * @param modelName The name of the model to download.
- *
- * @param modelByteSize The size in bytes that we expect the model to have. If
- * the size of the downloaded model does not match the expected size, then we
- * will redownload it.
- *
- * @returns a function. calling that function returns a promise to an ONNX
- * session.
+ * A failure here (e.g. an OS version too old for the ONNX Runtime build) is
+ * not fatal to the app: we remember the error, and all subsequent ML requests
+ * fail with it, leaving the rest of the app functional.
*/
-const makeCachedInferenceSession = (
- modelName: string,
- modelByteSize: number,
-) => {
- let session: Promise<ort.InferenceSession> | undefined;
+const loadMLNative = (paths: MLNativePaths) => {
+ try {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const native = require(paths.addon) as MLNative;
+ native.initOrt(paths.onnxRuntimeLibrary);
+ _native = native;
+ log.debugString(`Loaded ML addon at ${paths.addon}`);
+ } catch (e) {
+ _nativeLoadError = e instanceof Error ? e.message : String(e);
+ log.error(`Failed to load ML addon at ${paths.addon}`, e);
+ }
+};
+
+/**
+ * Return the loaded addon, throwing if it (or the ONNX Runtime library it
+ * needs) could not be loaded on this machine.
+ */
+const mlNative = () => {
+ if (_native) return _native;
+ throw new Error(`ML is unavailable: ${_nativeLoadError ?? "not loaded"}`);
+};
+
+/**
+ * Drain the runtime events (execution provider fallbacks, self-test failures)
+ * buffered on the Rust side, writing each to our log at its severity.
+ */
+const logMLRuntimeEvents = (native: MLNative) => {
+ for (const { severity, message } of native.takeMlRuntimeEvents()) {
+ const s = `[ml-rt] ${message}`;
+ if (severity == "severe") log.error(s);
+ else if (severity == "warning") log.warn(s);
+ else log.info(s);
+ }
+};
- const download = () =>
- modelPathDownloadingIfNeeded(modelName, modelByteSize);
+/**
+ * The ML models (and the CLIP tokenizer vocabulary) used by the Rust
+ * pipeline, identified by their name in the models.ente.com bucket and pinned
+ * by their SHA-256. These are the same assets that the mobile apps use (see
+ * ml_model_assets.dart).
+ */
+const modelSpecs = {
+ faceDetection: {
+ name: "yolov5s_face_640_640_static_b1.onnx",
+ sha256: "e047647409403d52696035ecd445792173e50d7fbdcccac97b958a585db9aa3d",
+ },
+ faceEmbedding: {
+ name: "mobilefacenet_portable_static_b1.onnx",
+ sha256: "0763fc33f54e138476194da95987e133b3e976075a6b1d3e1b2caedb251b1a36",
+ },
+ clipImage: {
+ name: "mobileclip_s2_image_gelu_opset20.onnx",
+ sha256: "205a430af825e501c5138e5bb9abea942482a7a4fd4a680e98e47cf0830dce7e",
+ },
+ clipText: {
+ name: "mobileclip_s2_text_opset18_quant.onnx",
+ sha256: "d92f33dfcff83077fc2e0d3414250710efbb51795dfd89767bdbefb5fdc47322",
+ },
+ clipTextVocab: {
+ name: "bpe_simple_vocab_16e6.txt",
+ sha256: "67603cfda2e032ad77b5f8808af37789d590db664b26df8705d2bf8b3c553fc8",
+ },
+ petFaceDetection: {
+ name: "yolov5s_pet_face_fp16_V2.onnx",
+ sha256: "7876d97992eeb5f3a9f3b35eff5e0e133012928172a8b005093108d8c3ad2d1c",
+ },
+ petFaceEmbeddingDog: {
+ name: "dog_face_embedding128.onnx",
+ sha256: "fb04d781eb1f7adf6ce3432dc0c5873f16cc051b5c98c14c754afb39e2b92462",
+ },
+ petFaceEmbeddingCat: {
+ name: "cat_face_embedding128.onnx",
+ sha256: "32b10694a27f6404d2beaddbd64f07ad555f72dccb12ee60a7afe5dcf6aad6cd",
+ },
+ petBodyDetection: {
+ name: "yolov5s_object_fp16.onnx",
+ sha256: "113f0c18632eb2c4f6deebcd40eb01c676492e9b43923c2d336e1b4012fce9ef",
+ },
+ petBodyEmbeddingDog: {
+ name: "dog_body_embedding192.onnx",
+ sha256: "1d85aa20358137e30f11c2d0baa9a2248b9997928d501fe15365d1fc57522770",
+ },
+ petBodyEmbeddingCat: {
+ name: "cat_body_embedding192.onnx",
+ sha256: "62fb5891e61be69a96510d8ec56e7525a9541b0283e54574d27c86c9b4a26ddf",
+ },
+} as const;
+
+type ModelSpec = (typeof modelSpecs)[keyof typeof modelSpecs];
- const createSession = (modelPath: string) =>
- createInferenceSession(modelPath);
+/** Return the path where the given {@link modelName} is meant to be saved */
+const modelSavePath = (modelName: string) =>
+ path.join(userDataPath(), "models", modelName);
- const cachedInferenceSession = () =>
- (session ??= download().then(createSession));
+/**
+ * Cached promises to the on-disk paths of verified models, so that each model
+ * is downloaded and hash-verified at most once per process. Multiple parallel
+ * calls for the same model await the same promise.
+ */
+const _verifiedModelPaths = new Map<string, Promise<string>>();
+
+const modelPath = (spec: ModelSpec) => {
+ let promise = _verifiedModelPaths.get(spec.name);
+ if (!promise) {
+ promise = modelPathDownloadingIfNeeded(spec).catch((e: unknown) => {
+ // Allow a later call to retry the download.
+ _verifiedModelPaths.delete(spec.name);
+ throw e;
+ });
+ _verifiedModelPaths.set(spec.name, promise);
+ }
+ return promise;
+};
- return cachedInferenceSession;
+/**
+ * Forget the cached verification of the model at {@link modelPath} and delete
+ * it from disk, so that the next use downloads a fresh copy. Used when the
+ * Rust side reports the on-disk model as corrupt.
+ */
+const evictModel = async (modelPath: string) => {
+ const name = path.basename(modelPath);
+ _verifiedModelPaths.delete(name);
+ await fs.rm(modelPath, { force: true });
};
/**
- * Download the model named {@link modelName} if we don't already have it.
+ * Download the model described by {@link spec} if we don't already have it.
*
- * Also verify that the size of the model we get matches {@expectedByteSize} (if
- * not, redownload it).
+ * Also verify the SHA-256 of the on-disk model, redownloading it on mismatch.
*
* @returns the path to the model on the local machine.
*/
-const modelPathDownloadingIfNeeded = async (
- modelName: string,
- expectedByteSize: number,
-) => {
- const modelPath = modelSavePath(modelName);
+const modelPathDownloadingIfNeeded = async (spec: ModelSpec) => {
+ const savePath = modelSavePath(spec.name);
await cleanupOldModelsIfNeeded();
- if (!existsSync(modelPath)) {
- log.info("CLIP image model not found, downloading");
- await downloadModel(modelPath, modelName);
- } else {
- const size = (await fs.stat(modelPath)).size;
- if (size !== expectedByteSize) {
- log.error(
- `The size ${size} of model ${modelName} does not match the expected size, downloading again`,
+ if (!existsSync(savePath)) {
+ log.info(`ML model ${spec.name} not found, downloading`);
+ await downloadModel(savePath, spec.name);
+ }
+
+ let sha256 = await computeFileSHA256(savePath);
+ if (sha256 != spec.sha256) {
+ log.error(
+ `The SHA-256 ${sha256} of model ${spec.name} does not match the expected value, downloading again`,
+ );
+ await downloadModel(savePath, spec.name);
+ sha256 = await computeFileSHA256(savePath);
+ if (sha256 != spec.sha256)
+ throw new Error(
+ `The SHA-256 of the downloaded model ${spec.name} does not match the expected value`,
);
- await downloadModel(modelPath, modelName);
- }
}
- return modelPath;
+ return savePath;
};
+const computeFileSHA256 = (filePath: string) =>
+ new Promise<string>((resolve, reject) => {
+ const hash = createHash("sha256");
+ const stream = createReadStream(filePath);
+ stream.on("error", reject);
+ stream.on("data", (chunk) => hash.update(chunk));
+ stream.on("end", () => resolve(hash.digest("hex")));
+ });
+
/**
* Cleanup old models.
*
@@ -147,9 +269,12 @@ const cleanupOldModelsIfNeeded = async () => {
"clip-text-vit-32-uint8.onnx",
"mobileclip_s2_image.onnx",
"mobileclip_s2_image_opset18_rgba_sim.onnx",
+ "mobileclip_s2_image_opset18_rgba_opt.onnx",
"mobileclip_s2_text_int32.onnx",
"yolov5s_face_640_640_dynamic.onnx",
"yolov5s_face_opset18_rgba_opt.onnx",
+ "yolov5s_face_opset18_rgba_opt_nosplits.onnx",
+ "mobilefacenet_opset15.onnx",
];
for (const modelName of oldModelNames) {
@@ -161,10 +286,6 @@ const cleanupOldModelsIfNeeded = async () => {
}
};
-/** Return the path where the given {@link modelName} is meant to be saved */
-const modelSavePath = (modelName: string) =>
- path.join(userDataPath(), "models", modelName);
-
const downloadModel = async (saveLocation: string, name: string) => {
// `mkdir -p` the directory where we want to save the model.
const saveDir = path.dirname(saveLocation);
@@ -178,130 +299,226 @@ const downloadModel = async (saveLocation: string, name: string) => {
if (!body) throw new Error(`Received an null response for ${url}`);
// Save.
await writeStream(saveLocation, body);
- log.info(`Downloaded CLIP model ${name}`);
+ log.info(`Downloaded ML model ${name}`);
};
/**
- * Create an ONNX {@link InferenceSession} with some defaults.
+ * The subset of {@link modelSpecs} needed for the indexing related tasks that
+ * are enabled in the given request, mapped to verified on-disk paths.
+ *
+ * Models for tasks that are not requested are left as empty strings, which
+ * the Rust side treats as "not configured".
*/
-const createInferenceSession = (modelPath: string) =>
- ort.InferenceSession.create(modelPath, {
- // Restrict the number of threads to 1.
- intraOpNumThreads: 1,
- // Be more conservative with RAM usage.
- enableCpuMemArena: false,
- });
-
-const cachedCLIPImageSession = makeCachedInferenceSession(
- "mobileclip_s2_image_opset18_rgba_opt.onnx",
- 143099752 /* 143 MB */,
-);
+const indexingModelPaths = async (
+ runFaces: boolean,
+ runClip: boolean,
+ runPets: boolean,
+): Promise<MLNativeModule.ModelPaths> => {
+ const [faceDetection, faceEmbedding] = runFaces
+ ? await Promise.all([
+ modelPath(modelSpecs.faceDetection),
+ modelPath(modelSpecs.faceEmbedding),
+ ])
+ : ["", ""];
+ const clipImage = runClip ? await modelPath(modelSpecs.clipImage) : "";
+ const [
+ petFaceDetection,
+ petFaceEmbeddingDog,
+ petFaceEmbeddingCat,
+ petBodyDetection,
+ petBodyEmbeddingDog,
+ petBodyEmbeddingCat,
+ ] = runPets
+ ? await Promise.all([
+ modelPath(modelSpecs.petFaceDetection),
+ modelPath(modelSpecs.petFaceEmbeddingDog),
+ modelPath(modelSpecs.petFaceEmbeddingCat),
+ modelPath(modelSpecs.petBodyDetection),
+ modelPath(modelSpecs.petBodyEmbeddingDog),
+ modelPath(modelSpecs.petBodyEmbeddingCat),
+ ])
+ : ["", "", "", "", "", ""];
+
+ return {
+ faceDetection,
+ faceEmbedding,
+ clipImage,
+ // The CLIP text session is managed lazily by the Rust side when
+ // serving text queries; it is not part of the indexing runtime.
+ clipText: "",
+ petFaceDetection,
+ petFaceEmbeddingDog,
+ petFaceEmbeddingCat,
+ petBodyDetection,
+ petBodyEmbeddingDog,
+ petBodyEmbeddingCat,
+ };
+};
/**
- * Compute CLIP embeddings for an image.
- *
- * The embeddings are computed using ONNX runtime, with MobileCLIP as the model.
+ * The model paths key for which the Rust runtime is currently prepared, if
+ * any. Re-preparing with the same paths is skipped (the Rust side would
+ * anyway no-op, this just avoids the IPC churn).
*/
-export const computeCLIPImageEmbedding = async (
- input: Uint8ClampedArray,
- inputShape: number[],
+let _preparedRuntimeKey: string | undefined;
+
+const ensureMLRuntime = (
+ native: MLNative,
+ modelPaths: MLNativeModule.ModelPaths,
) => {
- const session = await cachedCLIPImageSession();
- const inputArray = new Uint8Array(input.buffer);
- const feeds = { input: new ort.Tensor("uint8", inputArray, inputShape) };
- const t = Date.now();
- const results = await session.run(feeds);
- log.debugString(`ONNX/CLIP image embedding took ${Date.now() - t} ms`);
- /* Need these model specific casts to type the result */
- return results.output!.data as Float32Array;
+ const key = JSON.stringify(modelPaths);
+ if (_preparedRuntimeKey == key) return;
+ native.initMlRuntime(modelPaths);
+ _preparedRuntimeKey = key;
};
-const cachedCLIPTextSession = makeCachedInferenceSession(
- "mobileclip_s2_text_opset18_quant.onnx",
- 67144712 /* 67 MB */,
-);
+/**
+ * Release the (pinned) Rust ML runtime sessions. Called by the web layer when
+ * indexing goes idle so that we don't hold on to the session memory.
+ */
+export const releaseMLRuntime = () => {
+ if (!_native) return;
+ _native.releaseMlRuntime();
+ _preparedRuntimeKey = undefined;
+ logMLRuntimeEvents(_native);
+};
-let _tokenizer: Tokenizer | undefined;
-const getTokenizer = () => (_tokenizer ??= new Tokenizer());
+/**
+ * The request the web layer sends us to analyze a single image. Mirrors (a
+ * subset of) the addon's own request, except the image source, which we
+ * convert to what the addon expects.
+ */
+export interface MLWorkerAnalyzeImageRequest {
+ fileID: number;
+ /** Path to the image on the local filesystem. */
+ path?: string | undefined;
+ /** The encoded image bytes (used when there is no local file). */
+ bytes?: Uint8Array | undefined;
+ runFaces: boolean;
+ runClip: boolean;
+ runPets: boolean;
+ generateFaceCrops: boolean;
+}
/**
- * Compute CLIP embeddings for an text snippet.
+ * Analyze a single image with the Rust ML pipeline, downloading any needed
+ * models first.
*
- * The embeddings are computed using ONNX runtime, with MobileCLIP as the model.
+ * If the Rust side reports the on-disk model as corrupt, delete and
+ * redownload it, and retry once.
*/
-export const computeCLIPTextEmbeddingIfAvailable = async (text: string) => {
- const sessionOrSkip = await Promise.race([
- cachedCLIPTextSession(),
- // Wait a bit to get the session promise to resolved the first time this
- // code runs on each app start (in these cases the model will already be
- // downloaded, so session creation should take only a 1 or 2 ticks: file
- // system stat, and ort.InferenceSession.create).
- wait(50).then(() => 1),
- ]);
-
- // Don't wait for the download to complete.
- if (typeof sessionOrSkip == "number") {
- log.info(
- "Ignoring CLIP text embedding request because model download is pending",
+export const analyzeImage = async (
+ req: MLWorkerAnalyzeImageRequest,
+): Promise<MLNativeModule.AnalyzeImageResult> => {
+ const native = mlNative();
+ try {
+ return await analyzeImageOnce(native, req);
+ } catch (e) {
+ const corruptModelPath = corruptModelPathFromError(e);
+ if (!corruptModelPath) throw e;
+ log.error(
+ `Rust ML reported a corrupt model at ${corruptModelPath}, redownloading and retrying`,
);
- return undefined;
+ await evictModel(corruptModelPath);
+ _preparedRuntimeKey = undefined;
+ return await analyzeImageOnce(native, req);
+ } finally {
+ logMLRuntimeEvents(native);
}
+};
- const session = sessionOrSkip;
- const tokenizer = getTokenizer();
- const tokenizedText = Int32Array.from(tokenizer.encodeForCLIP(text));
- const feeds = { input: new ort.Tensor("int32", tokenizedText, [1, 77]) };
+const analyzeImageOnce = async (
+ native: MLNative,
+ req: MLWorkerAnalyzeImageRequest,
+) => {
+ let source;
+ if (req.path !== undefined) {
+ source = { imagePath: req.path };
+ } else if (req.bytes) {
+ source = { imageBytes: uint8ArrayToBuffer(req.bytes) };
+ } else {
+ throw new Error("The analyze request has neither a path nor bytes");
+ }
+ const modelPaths = await indexingModelPaths(
+ req.runFaces,
+ req.runClip,
+ req.runPets,
+ );
+ ensureMLRuntime(native, modelPaths);
const t = Date.now();
- const results = await session.run(feeds);
- log.debugString(`ONNX/CLIP text embedding took ${Date.now() - t} ms`);
- return results.output!.data as Float32Array;
+ const result = await native.analyzeImage({
+ fileId: req.fileID,
+ ...source,
+ runFaces: req.runFaces,
+ runClip: req.runClip,
+ runPets: req.runPets,
+ generateFaceCrops: req.generateFaceCrops,
+ modelPaths,
+ });
+ log.debugString(`Rust ML analyzeImage took ${Date.now() - t} ms`);
+ return result;
};
-const cachedFaceDetectionSession = makeCachedInferenceSession(
- "yolov5s_face_opset18_rgba_opt_nosplits.onnx",
- 28952651 /* 29 MB */,
-);
-
/**
- * Face detection with the YOLO model and ONNX runtime.
+ * If {@link e} is the addon's tagged "CorruptModel" error, return the path of
+ * the corrupt model file it reports (but only if that path is under our
+ * models directory, as a safety check before we delete it).
*/
-export const detectFaces = async (
- input: Uint8ClampedArray,
- inputShape: number[],
-) => {
- const session = await cachedFaceDetectionSession();
- const inputArray = new Uint8Array(input.buffer);
- const feeds = { input: new ort.Tensor("uint8", inputArray, inputShape) };
- const t = Date.now();
- const results = await session.run(feeds);
- log.debugString(`ONNX/YOLO face detection took ${Date.now() - t} ms`);
- return results.output!.data;
+const corruptModelPathFromError = (e: unknown) => {
+ if (!(e instanceof Error)) return undefined;
+ if (!e.message.startsWith("CorruptModel: ")) return undefined;
+ const corruptPath = e.message.slice("CorruptModel: ".length).trim();
+ const modelsDir = path.join(userDataPath(), "models") + path.sep;
+ return corruptPath.startsWith(modelsDir) ? corruptPath : undefined;
};
-const cachedFaceEmbeddingSession = makeCachedInferenceSession(
- "mobilefacenet_opset15.onnx",
- 5286998 /* 5 MB */,
-);
+// Zero-copy view over the transferred bytes.
+const uint8ArrayToBuffer = (bytes: Uint8Array) =>
+ Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
/**
- * Face embedding with the MobileFaceNet model and ONNX runtime.
+ * Compute CLIP embeddings for a text snippet, if the model is available.
+ *
+ * The embedding is computed by the Rust pipeline (which also handles the
+ * tokenization). If the model (or the addon itself) is not available yet, we
+ * return `undefined` instead of blocking the caller on the download.
*/
-export const computeFaceEmbeddings = async (input: Float32Array) => {
- // Dimension of each face (alias)
- const mobileFaceNetFaceSize = 112;
- // Smaller alias
- const z = mobileFaceNetFaceSize;
- // Size of each face's data in the batch
- const n = Math.round(input.length / (z * z * 3));
- const inputTensor = new ort.Tensor("float32", input, [n, z, z, 3]);
-
- const session = await cachedFaceEmbeddingSession();
- const feeds = { img_inputs: inputTensor };
+export const computeCLIPTextEmbeddingIfAvailable = async (text: string) => {
+ if (!_native) return undefined;
+ const native = _native;
+
+ const pathsOrSkip = await Promise.race([
+ Promise.all([
+ modelPath(modelSpecs.clipText),
+ modelPath(modelSpecs.clipTextVocab),
+ ]),
+ // Wait a bit for the models to resolve the first time this code runs
+ // on each app start (when they're already downloaded, resolving them
+ // is quick), but don't block on a download.
+ wait(50).then(() => 1 as const),
+ ]);
+
+ if (typeof pathsOrSkip == "number") {
+ log.info(
+ "Ignoring CLIP text embedding request because model download is pending",
+ );
+ return undefined;
+ }
+
+ const [clipTextModelPath, vocabPath] = pathsOrSkip;
const t = Date.now();
- const results = await session.run(feeds);
- log.debugString(`ONNX/MFNT face embedding took ${Date.now() - t} ms`);
- /* Need these model specific casts to extract and type the result */
- return (results.embeddings as unknown as Record<string, unknown>)
- .cpuData as Float32Array;
+ try {
+ const { embedding } = await native.runClipText({
+ text,
+ modelPath: clipTextModelPath,
+ vocabPath,
+ });
+ log.debugString(
+ `Rust ML CLIP text embedding took ${Date.now() - t} ms`,
+ );
+ return Float32Array.from(embedding);
+ } finally {
+ logMLRuntimeEvents(native);
+ }
};
diff --git a/desktop/src/main/services/workers.ts b/desktop/src/main/services/workers.ts
index ce8b9a852b..514419f627 100644
--- a/desktop/src/main/services/workers.ts
+++ b/desktop/src/main/services/workers.ts
@@ -14,6 +14,7 @@ import path from "node:path";
import type { UtilityProcessType } from "../../types/ipc";
import log, { processUtilityProcessLogMessage } from "../log";
import { messagePortMainEndpoint } from "../utils/comlink";
+import { mlNativePaths } from "./ml-native";
/**
* Terminate any existing utility processes if they're running.
@@ -157,7 +158,10 @@ export const triggerCreateMLUtilityProcess = (window: BrowserWindow) => {
const child = forkWatchedUtilityProcess("ml-worker.js", "[ml-worker]");
const userDataPath = app.getPath("userData");
- child.postMessage(/* MLWorkerInitData */ { userDataPath }, [port1]);
+ child.postMessage(
+ /* MLWorkerInitData */ { userDataPath, mlNativePaths: mlNativePaths() },
+ [port1],
+ );
window.webContents.postMessage("utilityProcessPort/ml", undefined, [port2]);
diff --git a/desktop/src/main/types/onnx-runtime.d.ts b/desktop/src/main/types/onnx-runtime.d.ts
deleted file mode 100644
index 85fc00ab6f..0000000000
--- a/desktop/src/main/types/onnx-runtime.d.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-/**
- * Types for [onnxruntime-node](https://onnxruntime.ai/docs/api/js/index.html).
- *
- * Note: these are not the official types but are based on a temporary
- * [workaround](https://github.com/microsoft/onnxruntime/issues/17979).
- */
-declare module "onnxruntime-node" {
- export * from "onnxruntime-common";
-}
diff --git a/infra/ml/test/README.md b/infra/ml/test/README.md
index 6f21986278..6755e5962e 100644
--- a/infra/ml/test/README.md
+++ b/infra/ml/test/README.md
@@ -1,6 +1,6 @@
# ML Indexing Parity Test Suite
-This directory contains the ML indexing parity framework for Android, iOS, desktop, and Python ground truth.
+This directory contains the ML indexing parity framework for Android, iOS, and Python ground truth. (Desktop ships the same shared Rust pipeline that the `ente-photos` crate's `ml_indexing` integration test validates against the Python goldens, so it has no separate parity runner.)
## Layout
@@ -13,7 +13,6 @@ This directory contains the ML indexing parity framework for Android, iOS, deskt
## Prerequisites
- Python + `uv`
-- Node/npm (desktop parity)
- Flutter SDK (Android/iOS parity)
- Android emulator/device and iOS simulator/device when running mobile parity
@@ -25,7 +24,7 @@ bash infra/ml/test/run_ml_parity_tests.sh
Common flags:
-- `--platforms all|desktop|android|ios`
+- `--platforms all|android|ios`
- `--output-dir <path>`
- `--verbose` (stream full runner/comparator logs to terminal)
- `--render-detection-overlays` (generate annotated detection images under `out/parity/detections/<platform>/`; includes selected platforms plus `python` ground truth)
diff --git a/infra/ml/test/ground_truth/README.md b/infra/ml/test/ground_truth/README.md
index 9aa2ffb69b..a9bd777be3 100644
--- a/infra/ml/test/ground_truth/README.md
+++ b/infra/ml/test/ground_truth/README.md
@@ -49,6 +49,5 @@ uv run --project infra/ml python infra/ml/test/tools/generate_goldens.py \
uv run --project infra/ml python infra/ml/test/tools/compare_parity_outputs.py \
--ground-truth infra/ml/test/out/parity/python/results.json \
--platform-result android=infra/ml/test/out/parity/android/results.json \
- --platform-result ios=infra/ml/test/out/parity/ios/results.json \
- --platform-result desktop=infra/ml/test/out/parity/desktop/results.json
+ --platform-result ios=infra/ml/test/out/parity/ios/results.json
```
diff --git a/infra/ml/test/run_ml_parity_tests.sh b/infra/ml/test/run_ml_parity_tests.sh
index 22b3b3ff03..cd7dac07c7 100755
--- a/infra/ml/test/run_ml_parity_tests.sh
+++ b/infra/ml/test/run_ml_parity_tests.sh
@@ -29,7 +29,7 @@ usage() {
Usage: infra/ml/test/run_ml_parity_tests.sh [flags]
Flags:
- --platforms all|desktop|android|ios (default: all)
+ --platforms all|android|ios (default: all)
--output-dir <path> (default: infra/ml/test/out/parity)
--verbose (default: disabled)
--render-detection-overlays (default: disabled; render annotated face detection images to out/parity/detections/<platform>/)
@@ -283,9 +283,9 @@ print_kv "mobile_ml_route:" "rust"
declare -a selected_platforms=()
case "$PLATFORMS" in
all)
- selected_platforms=(desktop android ios)
+ selected_platforms=(android ios)
;;
- desktop|android|ios)
+ android|ios)
selected_platforms=("$PLATFORMS")
;;
*)
@@ -565,9 +565,6 @@ ensure_selected_mobile_devices_running() {
}
run_preflight_checks() {
- local desktop_dir="$ROOT_DIR/desktop"
- local web_dir="$ROOT_DIR/web"
- local runner_path="$desktop_dir/scripts/ml_parity_runner.ts"
local mobile_dir="$ROOT_DIR/mobile/apps/photos"
local driver_path="$mobile_dir/test_driver/ml_parity_driver.dart"
local -a preflight_errors=()
@@ -575,23 +572,6 @@ run_preflight_checks() {
for platform in "${selected_platforms[@]}"; do
case "$platform" in
- desktop)
- if [[ ! -f "$runner_path" ]]; then
- preflight_errors+=("desktop parity runner not found at $runner_path")
- fi
- if [[ ! -d "$desktop_dir/node_modules" ]]; then
- preflight_errors+=("desktop dependencies missing: $desktop_dir/node_modules")
- fi
- if [[ ! -d "$web_dir/node_modules" ]]; then
- preflight_errors+=("web dependencies missing: $web_dir/node_modules")
- fi
- if ! command -v npx >/dev/null 2>&1; then
- preflight_errors+=("npx is required for desktop parity")
- fi
- if ! command -v npm >/dev/null 2>&1; then
- preflight_errors+=("npm is required for desktop parity compilation")
- fi
- ;;
android|ios)
if ! command -v flutter >/dev/null 2>&1; then
preflight_errors+=("flutter is required for $platform parity")
@@ -799,32 +779,6 @@ for platform in "${selected_platforms[@]}"; do
mkdir -p "$platform_dir"
done
-run_desktop_runner() {
- local desktop_dir="$ROOT_DIR/desktop"
- local web_dir="$ROOT_DIR/web"
- local runner_path="$desktop_dir/scripts/ml_parity_runner.ts"
- local platform_output_dir="$OUTPUT_DIR/desktop"
-
- echo "Compiling desktop TypeScript sources"
- if ! (cd "$desktop_dir" && npm exec -- tsc); then
- echo "Desktop TypeScript compilation failed; desktop parity output not generated."
- return 1
- fi
-
- echo "Running desktop parity runner"
- if ! (
- cd "$web_dir"
- isDesktop=1 appName=photos desktopAppVersion=parity npx --yes tsx "$runner_path" \
- --manifest "$MANIFEST_PATH" \
- --output-dir "$platform_output_dir"
- ); then
- echo "Desktop parity runner failed; desktop parity output not generated."
- return 1
- fi
-
- return 0
-}
-
run_mobile_runner() {
local platform="$1"
local target="$2"
@@ -1013,9 +967,6 @@ run_ios_runner() {
run_platform_runner() {
local platform="$1"
case "$platform" in
- desktop)
- run_desktop_runner
- ;;
android)
run_android_runner
;;
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 9ae6aca003..0239092d61 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -1365,6 +1365,15 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb4a24b1aaf0fd0ce8b45161144d6f42cd91677fd5940fd431183eb023b3a2b8"
+[[package]]
+name = "convert_case"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "affbf0190ed2caf063e3def54ff444b449371d55c58e513a95ab98eca50adb49"
+dependencies = [
+ "unicode-segmentation",
+]
+
[[package]]
name = "cookie"
version = "0.18.1"
@@ -1611,6 +1620,12 @@ dependencies = [
"dtor",
]
+[[package]]
+name = "ctor"
+version = "1.0.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e2e30e509674ef0ec91e21a7735766db37d163d46151b6a361d8b83dd79116bd"
+
[[package]]
name = "ctor-proc-macro"
version = "0.0.7"
@@ -2578,6 +2593,17 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "ente_photos_napi"
+version = "0.0.0"
+dependencies = [
+ "ente-photos",
+ "napi",
+ "napi-build",
+ "napi-derive",
+ "ort",
+]
+
[[package]]
name = "ente_photos_rust"
version = "0.0.0"
@@ -2962,7 +2988,7 @@ dependencies = [
"cbindgen",
"chrono",
"clap",
- "convert_case",
+ "convert_case 0.5.0",
"derivative",
"enum-iterator",
"enum_dispatch",
@@ -5575,6 +5601,63 @@ dependencies = [
"syn 2.0.117",
]
+[[package]]
+name = "napi"
+version = "3.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "de33522036981030a75c231829566bc63414e08101a6f5ff4ac6cef19c8e0941"
+dependencies = [
+ "bitflags 2.11.0",
+ "ctor 1.0.10",
+ "futures",
+ "napi-build",
+ "napi-sys",
+ "nohash-hasher",
+ "rustc-hash",
+]
+
+[[package]]
+name = "napi-build"
+version = "2.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c9c366d2c8c60b86fa632df75f745509b52f9128f91a6bad4c796e44abb505e1"
+
+[[package]]
+name = "napi-derive"
+version = "3.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a49c513341a61a16a10af6efcce46b30d0822ba2d4fb197d24d33dfc199c78d5"
+dependencies = [
+ "convert_case 0.11.0",
+ "ctor 1.0.10",
+ "napi-derive-backend",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.117",
+]
+
+[[package]]
+name = "napi-derive-backend"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4747005fa3e2c9989ac45a723a514c5db2411238b72981a3cda4c701a9dfea17"
+dependencies = [
+ "convert_case 0.11.0",
+ "proc-macro2",
+ "quote",
+ "semver",
+ "syn 2.0.117",
+]
+
+[[package]]
+name = "napi-sys"
+version = "3.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85fbf1fa9f1babfe396d74bbbf52b3643770243e8f5b0b46715d4caf7f0dfc9a"
+dependencies = [
+ "libloading 0.9.0",
+]
+
[[package]]
name = "nasm-rs"
version = "0.3.2"
@@ -5669,6 +5752,12 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "nohash-hasher"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451"
+
[[package]]
name = "nom"
version = "7.1.3"
@@ -8932,7 +9021,7 @@ dependencies = [
"anyhow",
"brotli",
"cargo_metadata 0.19.2",
- "ctor",
+ "ctor 0.8.0",
"dom_query",
"dunce",
"glob",
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index abd9a2321f..085ee06a1d 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -6,6 +6,7 @@ members = [
"apps/ensu/src-tauri",
"bindings/frb/ente-rust",
"bindings/frb/photos",
+ "bindings/napi/photos",
"bindings/uniffi/cast",
"bindings/uniffi/ensu",
"bindings/wasm/ente-wasm",
diff --git a/rust/README.md b/rust/README.md
index f86ee94731..1fbaf4ce03 100644
--- a/rust/README.md
+++ b/rust/README.md
@@ -20,6 +20,7 @@ Other useful commands:
```sh
cargo codegen native # Regenerate bindings used by native apps
cargo codegen frb # Regenerate bindings used by Flutter apps
+cargo codegen napi # Rebuild the desktop (Electron) ML addon and its bindings
# Run integration tests against a local Museum
cargo test --features museum,ente-photos/ml-assets
diff --git a/rust/apps/codegen/src/main.rs b/rust/apps/codegen/src/main.rs
index 050c27fd94..1d12e1df2a 100644
--- a/rust/apps/codegen/src/main.rs
+++ b/rust/apps/codegen/src/main.rs
@@ -66,12 +66,18 @@ fn run() -> Result<(), DynError> {
}
generate_frb(target)
}
+ Some("napi") => {
+ if args.next().is_some() {
+ return Err(usage_error());
+ }
+ generate_napi()
+ }
_ => Err(usage_error()),
}
}
fn usage_error() -> DynError {
- "usage: cargo codegen <native [ensu|cast]|frb [shared|photos]>".into()
+ "usage: cargo codegen <native [ensu|cast]|frb [shared|photos]|napi>".into()
}
fn generate_native(target: NativeTarget) -> Result<(), DynError> {
@@ -201,6 +207,40 @@ fn generate_frb_package(package_dir: &Path) -> Result<(), DynError> {
Ok(())
}
+/// Builds the desktop Node addon and regenerates its JS type declarations
+/// into the gitignored `desktop/rust-bindings/` directory, via `@napi-rs/cli`
+/// (a devDependency of `desktop/`).
+fn generate_napi() -> Result<(), DynError> {
+ let rust_root = rust_root()?;
+ let desktop_dir = repo_root()?.join("desktop");
+ let out_dir = desktop_dir.join("rust-bindings");
+ write_generated_gitignore(&out_dir)?;
+
+ // On Windows npm is a .cmd shim, which CreateProcess doesn't resolve.
+ let npm = if cfg!(windows) { "npm.cmd" } else { "npm" };
+ run_command(
+ Command::new(npm)
+ .arg("exec")
+ .arg("--")
+ .arg("napi")
+ .arg("build")
+ .arg("--manifest-path")
+ .arg(rust_root.join("bindings/napi/photos/Cargo.toml"))
+ .arg("--target-dir")
+ .arg(target_dir()?)
+ .arg("--release")
+ .arg("--strip")
+ .arg("--platform")
+ .arg("--no-js")
+ .arg("--dts")
+ .arg("index.d.ts")
+ .arg("--output-dir")
+ .arg(&out_dir)
+ .current_dir(&desktop_dir),
+ "failed to build the desktop Node addon (run npm install in desktop/ first)".to_owned(),
+ )
+}
+
fn format_frb_bindings(target: FrbTarget) -> Result<(), DynError> {
let rust_root = rust_root()?;
let mut command = Command::new("cargo");
diff --git a/rust/bindings/frb/photos/src/api/ml_indexing_api.rs b/rust/bindings/frb/photos/src/api/ml_indexing_api.rs
index b69fa1d894..3a3d6a787d 100644
--- a/rust/bindings/frb/photos/src/api/ml_indexing_api.rs
+++ b/rust/bindings/frb/photos/src/api/ml_indexing_api.rs
@@ -153,10 +153,11 @@ pub fn release_ml_runtime() {
pub fn analyze_image_rust(req: AnalyzeImageRequest) -> Result<AnalyzeImageResult, RustMlError> {
let shared_req = shared_indexing::AnalyzeImageRequest {
file_id: req.file_id,
- image_path: req.image_path,
+ source: shared_indexing::ImageSource::Path(req.image_path),
run_faces: req.run_faces,
run_clip: req.run_clip,
run_pets: req.run_pets,
+ generate_face_crops: false,
model_paths: to_model_paths(&req.model_paths),
};
diff --git a/rust/bindings/napi/photos/Cargo.toml b/rust/bindings/napi/photos/Cargo.toml
new file mode 100644
index 0000000000..7ef5b71e8d
--- /dev/null
+++ b/rust/bindings/napi/photos/Cargo.toml
@@ -0,0 +1,17 @@
+[package]
+name = "ente_photos_napi"
+edition = "2024"
+
+[lib]
+crate-type = ["cdylib"]
+
+[dependencies]
+ente-photos.workspace = true
+napi = { version = "3", default-features = false, features = ["napi8"] }
+napi-derive = "3"
+# Only used for ort::init_from; the execution-provider feature set is
+# declared by ente-photos' per-target sections.
+ort = { workspace = true, features = ["load-dynamic"] }
+
+[build-dependencies]
+napi-build = "2"
diff --git a/rust/bindings/napi/photos/build.rs b/rust/bindings/napi/photos/build.rs
new file mode 100644
index 0000000000..0f1b01002b
--- /dev/null
+++ b/rust/bindings/napi/photos/build.rs
@@ -0,0 +1,3 @@
+fn main() {
+ napi_build::setup();
+}
diff --git a/rust/bindings/napi/photos/src/lib.rs b/rust/bindings/napi/photos/src/lib.rs
new file mode 100644
index 0000000000..d48dc45128
--- /dev/null
+++ b/rust/bindings/napi/photos/src/lib.rs
@@ -0,0 +1,400 @@
+//! Node addon exposing the shared photos ML pipeline to the desktop app's
+//! Electron utility process. A thin mirror of the FRB surface in
+//! `bindings/frb/photos/src/api/ml_indexing_api.rs`.
+
+use ente_photos::ml::{
+ error::MlError, indexing as shared_indexing, runtime::ModelPaths as SharedModelPaths,
+ types as shared_types,
+};
+use napi::bindgen_prelude::*;
+use napi_derive::napi;
+
+/// Loads the ONNX Runtime dynamic library from `dylib_path`. Must be called
+/// once, before any other ML function.
+#[napi]
+pub fn init_ort(dylib_path: String) -> Result<()> {
+ ort::init_from(&dylib_path)
+ .map_err(|error| {
+ Error::from_reason(format!(
+ "Runtime: failed to load ONNX Runtime library from '{dylib_path}': {error}"
+ ))
+ })?
+ .commit();
+ Ok(())
+}
+
+/// Configures process-wide ML execution behavior. `enable_webgpu` only has an
+/// effect on Android; it is a no-op on desktop and exists for surface parity
+/// with the mobile bindings.
+#[napi]
+pub fn set_ml_execution_config(enable_webgpu: bool) {
+ shared_indexing::set_ml_execution_config(enable_webgpu);
+}
+
+/// Pins the indexing model sessions resident for a batch of analyze calls.
+#[napi]
+pub fn init_ml_runtime(model_paths: ModelPaths) {
+ shared_indexing::init_ml_runtime(to_shared_model_paths(&model_paths));
+}
+
+/// Releases the session residency taken by [`init_ml_runtime`].
+#[napi]
+pub fn release_ml_runtime() {
+ shared_indexing::release_ml_runtime();
+}
+
+#[napi(object)]
+pub struct ModelPaths {
+ pub face_detection: String,
+ pub face_embedding: String,
+ pub clip_image: String,
+ pub clip_text: String,
+ pub pet_face_detection: String,
+ pub pet_face_embedding_dog: String,
+ pub pet_face_embedding_cat: String,
+ pub pet_body_detection: String,
+ pub pet_body_embedding_dog: String,
+ pub pet_body_embedding_cat: String,
+}
+
+#[napi(object)]
+pub struct AnalyzeImageRequest {
+ pub file_id: i64,
+ /// Filesystem path of the image. Exactly one of `image_path` and
+ /// `image_bytes` must be set.
+ pub image_path: Option<String>,
+ /// Encoded image bytes (any supported format; decoded in Rust).
+ pub image_bytes: Option<Buffer>,
+ pub run_faces: bool,
+ pub run_clip: bool,
+ pub run_pets: bool,
+ /// When set, the result carries a JPEG face crop per detected face.
+ pub generate_face_crops: bool,
+ pub model_paths: ModelPaths,
+}
+
+#[napi(object)]
+pub struct Dimensions {
+ pub width: u32,
+ pub height: u32,
+}
+
+#[napi(object)]
+pub struct FaceDetection {
+ pub score: f64,
+ /// Relative [x_min, y_min, x_max, y_max].
+ pub box_xyxy: Vec<f64>,
+ /// 5 relative [x, y] keypoints: leftEye, rightEye, nose, leftMouth,
+ /// rightMouth.
+ pub keypoints: Vec<Vec<f64>>,
+}
+
+#[napi(object)]
+pub struct FaceResult {
+ pub face_id: String,
+ pub detection: FaceDetection,
+ pub blur_value: f64,
+ pub embedding: Vec<f64>,
+}
+
+#[napi(object)]
+pub struct ClipResult {
+ pub embedding: Vec<f64>,
+}
+
+#[napi(object)]
+pub struct PetFaceResult {
+ pub pet_face_id: String,
+ pub score: f64,
+ pub box_xyxy: Vec<f64>,
+ /// 3 relative [x, y] keypoints: leftEye, rightEye, nose.
+ pub keypoints: Vec<Vec<f64>>,
+ /// 0 = dog, 1 = cat.
+ pub species: u32,
+ pub face_embedding: Vec<f64>,
+}
+
+#[napi(object)]
+pub struct PetBodyResult {
+ pub pet_body_id: String,
+ pub score: f64,
+ pub box_xyxy: Vec<f64>,
+ /// COCO class: 15 = cat, 16 = dog.
+ pub coco_class: u32,
+ pub body_embedding: Vec<f64>,
+}
+
+#[napi(object)]
+pub struct AnalyzeImageResult {
+ pub file_id: i64,
+ pub decoded_image_size: Dimensions,
+ pub faces: Option<Vec<FaceResult>>,
+ /// JPEG bytes, index-aligned with `faces`; present only when requested
+ /// via `generate_face_crops`.
+ pub face_crops: Option<Vec<Buffer>>,
+ pub clip: Option<ClipResult>,
+ pub pet_faces: Option<Vec<PetFaceResult>>,
+ pub pet_bodies: Option<Vec<PetBodyResult>>,
+ /// True when any model that contributed to this result ran on the
+ /// respective accelerated execution provider.
+ pub used_coreml: bool,
+ pub used_webgpu: bool,
+}
+
+pub struct AnalyzeImageTask {
+ req: Option<shared_indexing::AnalyzeImageRequest>,
+}
+
+impl Task for AnalyzeImageTask {
+ type Output = shared_indexing::AnalyzeImageResult;
+ type JsValue = AnalyzeImageResult;
+
+ fn compute(&mut self) -> Result<Self::Output> {
+ let req = self
+ .req
+ .take()
+ .ok_or_else(|| Error::from_reason("Runtime: analyze task computed twice"))?;
+ shared_indexing::analyze_image(req).map_err(ml_error_to_napi)
+ }
+
+ fn resolve(&mut self, _env: Env, output: Self::Output) -> Result<Self::JsValue> {
+ Ok(to_napi_analyze_image_result(output))
+ }
+}
+
+/// Analyzes one image (decode + the requested face / CLIP / pet models). The
+/// work runs off the JS event loop; callers should keep at most one analyze
+/// in flight, since the underlying model sessions serialize anyway.
+#[napi(ts_return_type = "Promise<AnalyzeImageResult>")]
+pub fn analyze_image(req: AnalyzeImageRequest) -> Result<AsyncTask<AnalyzeImageTask>> {
+ let source = match (req.image_path, req.image_bytes) {
+ (Some(path), None) => shared_indexing::ImageSource::Path(path),
+ (None, Some(bytes)) => shared_indexing::ImageSource::Bytes(bytes.to_vec()),
+ _ => {
+ return Err(Error::from_reason(
+ "InvalidRequest: exactly one of imagePath and imageBytes must be set".to_string(),
+ ));
+ }
+ };
+
+ Ok(AsyncTask::new(AnalyzeImageTask {
+ req: Some(shared_indexing::AnalyzeImageRequest {
+ file_id: req.file_id,
+ source,
+ run_faces: req.run_faces,
+ run_clip: req.run_clip,
+ run_pets: req.run_pets,
+ generate_face_crops: req.generate_face_crops,
+ model_paths: to_shared_model_paths(&req.model_paths),
+ }),
+ }))
+}
+
+#[napi(object)]
+pub struct RunClipTextRequest {
+ pub text: String,
+ pub model_path: String,
+ pub vocab_path: String,
+}
+
+#[napi(object)]
+pub struct RunClipTextResult {
+ pub embedding: Vec<f64>,
+}
+
+pub struct RunClipTextTask {
+ req: Option<shared_indexing::RunClipTextRequest>,
+}
+
+impl Task for RunClipTextTask {
+ type Output = shared_indexing::RunClipTextResult;
+ type JsValue = RunClipTextResult;
+
+ fn compute(&mut self) -> Result<Self::Output> {
+ let req = self
+ .req
+ .take()
+ .ok_or_else(|| Error::from_reason("Runtime: clip text task computed twice"))?;
+ shared_indexing::run_clip_text(req).map_err(ml_error_to_napi)
+ }
+
+ fn resolve(&mut self, _env: Env, output: Self::Output) -> Result<Self::JsValue> {
+ Ok(RunClipTextResult {
+ embedding: output
+ .embedding
+ .into_iter()
+ .map(|value| value as f64)
+ .collect(),
+ })
+ }
+}
+
+/// Computes the (L2-normalized) CLIP embedding of a text query.
+#[napi(ts_return_type = "Promise<RunClipTextResult>")]
+pub fn run_clip_text(req: RunClipTextRequest) -> AsyncTask<RunClipTextTask> {
+ AsyncTask::new(RunClipTextTask {
+ req: Some(shared_indexing::RunClipTextRequest {
+ text: req.text,
+ model_path: req.model_path,
+ vocab_path: req.vocab_path,
+ }),
+ })
+}
+
+#[napi]
+pub fn tokenize_clip_text(text: String, vocab_path: String) -> Result<Vec<i32>> {
+ shared_indexing::tokenize_clip_text(&text, &vocab_path).map_err(ml_error_to_napi)
+}
+
+/// A notable ML runtime event (execution provider fallback, golden self-test
+/// failure) buffered by the Rust runtime for app-side logging. `severity` is
+/// one of "info", "warning", or "severe".
+#[napi(object)]
+pub struct MlRuntimeEvent {
+ pub severity: String,
+ pub message: String,
+}
+
+/// Drains buffered ML runtime events. The buffer is process-wide, so drain
+/// after ML operations and log each event at its severity.
+#[napi]
+pub fn take_ml_runtime_events() -> Vec<MlRuntimeEvent> {
+ ente_photos::ml::events::take_events()
+ .into_iter()
+ .map(|event| MlRuntimeEvent {
+ severity: event.severity.as_str().to_string(),
+ message: event.message,
+ })
+ .collect()
+}
+
+/// Maps an [`MlError`] onto a JS error whose message starts with a stable
+/// `Kind:` tag. comlink only carries the message across the MessagePort, so
+/// callers match on the tag (notably `CorruptModel:`, whose detail is the
+/// model path to delete and redownload).
+fn ml_error_to_napi(error: MlError) -> Error {
+ let kind = match &error {
+ MlError::InvalidRequest(_) => "InvalidRequest",
+ MlError::Decode(_) => "Decode",
+ MlError::Preprocess(_) => "Preprocess",
+ MlError::Ort(_) => "Ort",
+ MlError::CorruptModel(_) => "CorruptModel",
+ MlError::Postprocess(_) => "Postprocess",
+ MlError::Runtime(_) => "Runtime",
+ };
+ let detail = match error {
+ MlError::InvalidRequest(message)
+ | MlError::Decode(message)
+ | MlError::Preprocess(message)
+ | MlError::Ort(message)
+ | MlError::CorruptModel(message)
+ | MlError::Postprocess(message)
+ | MlError::Runtime(message) => message,
+ };
+ Error::from_reason(format!("{kind}: {detail}"))
+}
+
+fn to_shared_model_paths(paths: &ModelPaths) -> SharedModelPaths {
+ SharedModelPaths {
+ face_detection: paths.face_detection.clone(),
+ face_embedding: paths.face_embedding.clone(),
+ clip_image: paths.clip_image.clone(),
+ clip_text: paths.clip_text.clone(),
+ pet_face_detection: paths.pet_face_detection.clone(),
+ pet_face_embedding_dog: paths.pet_face_embedding_dog.clone(),
+ pet_face_embedding_cat: paths.pet_face_embedding_cat.clone(),
+ pet_body_detection: paths.pet_body_detection.clone(),
+ pet_body_embedding_dog: paths.pet_body_embedding_dog.clone(),
+ pet_body_embedding_cat: paths.pet_body_embedding_cat.clone(),
+ }
+}
+
+fn to_napi_analyze_image_result(result: shared_indexing::AnalyzeImageResult) -> AnalyzeImageResult {
+ AnalyzeImageResult {
+ file_id: result.file_id,
+ decoded_image_size: Dimensions {
+ width: result.decoded_image_size.width,
+ height: result.decoded_image_size.height,
+ },
+ faces: result
+ .faces
+ .map(|faces| faces.into_iter().map(to_napi_face_result).collect()),
+ face_crops: result
+ .face_crops
+ .map(|crops| crops.into_iter().map(Buffer::from).collect()),
+ clip: result.clip.map(|clip| ClipResult {
+ embedding: to_f64_vec(clip.embedding),
+ }),
+ pet_faces: result
+ .pet_faces
+ .map(|faces| faces.into_iter().map(to_napi_pet_face_result).collect()),
+ pet_bodies: result
+ .pet_bodies
+ .map(|bodies| bodies.into_iter().map(to_napi_pet_body_result).collect()),
+ used_coreml: result.used_coreml,
+ used_webgpu: result.used_webgpu,
+ }
+}
+
+fn to_napi_face_result(result: shared_types::FaceResult) -> FaceResult {
+ FaceResult {
+ face_id: result.face_id,
+ detection: FaceDetection {
+ score: f64::from(result.detection.score),
+ box_xyxy: result
+ .detection
+ .box_xyxy
+ .into_iter()
+ .map(f64::from)
+ .collect(),
+ keypoints: result
+ .detection
+ .keypoints
+ .into_iter()
+ .map(|point| point.into_iter().map(f64::from).collect())
+ .collect(),
+ },
+ blur_value: f64::from(result.blur_value),
+ embedding: to_f64_vec(result.embedding),
+ }
+}
+
+fn to_napi_pet_face_result(result: shared_types::PetFaceResult) -> PetFaceResult {
+ PetFaceResult {
+ pet_face_id: result.pet_face_id,
+ score: f64::from(result.detection.score),
+ box_xyxy: result
+ .detection
+ .box_xyxy
+ .into_iter()
+ .map(f64::from)
+ .collect(),
+ keypoints: result
+ .detection
+ .keypoints
+ .into_iter()
+ .map(|point| point.into_iter().map(f64::from).collect())
+ .collect(),
+ species: u32::from(result.species),
+ face_embedding: to_f64_vec(result.face_embedding),
+ }
+}
+
+fn to_napi_pet_body_result(result: shared_types::PetBodyResult) -> PetBodyResult {
+ PetBodyResult {
+ pet_body_id: result.pet_body_id,
+ score: f64::from(result.detection.score),
+ box_xyxy: result
+ .detection
+ .box_xyxy
+ .into_iter()
+ .map(f64::from)
+ .collect(),
+ coco_class: u32::from(result.detection.coco_class),
+ body_embedding: to_f64_vec(result.body_embedding),
+ }
+}
+
+fn to_f64_vec(values: Vec<f32>) -> Vec<f64> {
+ values.into_iter().map(f64::from).collect()
+}
diff --git a/rust/crates/photos/Cargo.toml b/rust/crates/photos/Cargo.toml
index 53ec14e8e4..f2144cac69 100644
--- a/rust/crates/photos/Cargo.toml
+++ b/rust/crates/photos/Cargo.toml
@@ -50,7 +50,19 @@ ort = { workspace = true, features = [
"xnnpack",
] }
-[target.'cfg(not(any(target_os = "ios", target_os = "android")))'.dependencies]
+# macOS desktop loads the custom CoreML-enabled dylib at runtime; CoreML is
+# the preferred execution provider like on iOS.
+[target.'cfg(target_os = "macos")'.dependencies]
+ort = { workspace = true, features = [
+ "ndarray",
+ "half",
+ "coreml",
+ "api-27",
+ "load-dynamic",
+ "copy-dylibs",
+] }
+
+[target.'cfg(not(any(target_os = "ios", target_os = "android", target_os = "macos")))'.dependencies]
ort = { workspace = true, features = [
"ndarray",
"half",
diff --git a/rust/crates/photos/src/ml/indexing.rs b/rust/crates/photos/src/ml/indexing.rs
index 533ef183b3..4c6b7bffb9 100644
--- a/rust/crates/photos/src/ml/indexing.rs
+++ b/rust/crates/photos/src/ml/indexing.rs
@@ -1,7 +1,10 @@
use crate::ml::{
clip::{run_clip_image, run_clip_text_query, tokenize_clip_text as tokenize_clip_text_impl},
error::{MlError, MlResult},
- face::{run_face_alignment, run_face_detection, run_face_embedding},
+ face::{
+ run_face_alignment, run_face_detection, run_face_embedding,
+ thumbnail::{FaceBox, generate_face_thumbnails},
+ },
pet::{
run_pet_body_detection, run_pet_body_embedding, run_pet_face_alignment,
run_pet_face_detection, run_pet_face_embedding,
@@ -11,15 +14,24 @@ use crate::ml::{
types::{self, ClipResult, Dimensions, FaceResult, PetBodyResult, PetFaceResult},
webgpu,
};
-use ente_image::decode::decode_image_from_path;
+use ente_image::decode::{decode_image_from_bytes, decode_image_from_path};
+
+#[derive(Clone, Debug)]
+pub enum ImageSource {
+ Path(String),
+ Bytes(Vec<u8>),
+}
#[derive(Clone, Debug)]
pub struct AnalyzeImageRequest {
pub file_id: i64,
- pub image_path: String,
+ pub source: ImageSource,
pub run_faces: bool,
pub run_clip: bool,
pub run_pets: bool,
+ /// When set, the result carries a JPEG face crop per detected face,
+ /// generated from the same decode used for indexing.
+ pub generate_face_crops: bool,
pub model_paths: ModelPaths,
}
@@ -28,6 +40,9 @@ pub struct AnalyzeImageResult {
pub file_id: i64,
pub decoded_image_size: Dimensions,
pub faces: Option<Vec<FaceResult>>,
+ /// Index-aligned with `faces`; present only when requested via
+ /// `generate_face_crops`.
+ pub face_crops: Option<Vec<Vec<u8>>>,
pub clip: Option<ClipResult>,
pub pet_faces: Option<Vec<PetFaceResult>>,
pub pet_bodies: Option<Vec<PetBodyResult>>,
@@ -72,15 +87,19 @@ pub fn analyze_image(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageResult> {
let AnalyzeImageRequest {
file_id,
- image_path,
+ source,
run_faces,
run_clip,
run_pets,
+ generate_face_crops,
model_paths,
} = req;
runtime::with_runtime(&model_paths, |runtime| {
- let mut decoded = decode_image_from_path(&image_path)?;
+ let mut decoded = match &source {
+ ImageSource::Path(path) => decode_image_from_path(path)?,
+ ImageSource::Bytes(bytes) => decode_image_from_bytes(bytes)?,
+ };
let dims = decoded.dimensions.clone();
let detector_input = (run_faces || run_pets)
.then(|| preprocess::preprocess_yolo(&decoded))
@@ -105,6 +124,29 @@ pub fn analyze_image(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageResult> {
None
};
+ let face_crops = if generate_face_crops {
+ faces
+ .as_ref()
+ .map(|face_results| {
+ let face_boxes = face_results
+ .iter()
+ .map(|face| {
+ let [x_min, y_min, x_max, y_max] = face.detection.box_xyxy;
+ FaceBox {
+ x: x_min,
+ y: y_min,
+ width: x_max - x_min,
+ height: y_max - y_min,
+ }
+ })
+ .collect::<Vec<_>>();
+ generate_face_thumbnails(&decoded, &face_boxes)
+ })
+ .transpose()?
+ } else {
+ None
+ };
+
let clip = if run_clip {
Some(run_clip_image(runtime, &decoded)?)
} else {
@@ -154,6 +196,7 @@ pub fn analyze_image(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageResult> {
file_id,
decoded_image_size: dims,
faces,
+ face_crops,
clip,
pet_faces,
pet_bodies,
@@ -255,3 +298,71 @@ fn validate_request_model_paths(req: &AnalyzeImageRequest) -> MlResult<()> {
missing.join(", ")
)))
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn empty_model_paths() -> ModelPaths {
+ ModelPaths {
+ face_detection: String::new(),
+ face_embedding: String::new(),
+ clip_image: String::new(),
+ clip_text: String::new(),
+ pet_face_detection: String::new(),
+ pet_face_embedding_dog: String::new(),
+ pet_face_embedding_cat: String::new(),
+ pet_body_detection: String::new(),
+ pet_body_embedding_dog: String::new(),
+ pet_body_embedding_cat: String::new(),
+ }
+ }
+
+ fn png_bytes(width: u32, height: u32) -> Vec<u8> {
+ let img =
+ image::RgbImage::from_fn(width, height, |x, y| image::Rgb([x as u8, y as u8, 128]));
+ let mut bytes = std::io::Cursor::new(Vec::new());
+ image::DynamicImage::ImageRgb8(img)
+ .write_to(&mut bytes, image::ImageFormat::Png)
+ .expect("png encoding succeeds");
+ bytes.into_inner()
+ }
+
+ #[test]
+ fn analyze_image_decodes_from_bytes() {
+ let req = AnalyzeImageRequest {
+ file_id: 1,
+ source: ImageSource::Bytes(png_bytes(64, 48)),
+ run_faces: false,
+ run_clip: false,
+ run_pets: false,
+ generate_face_crops: false,
+ model_paths: empty_model_paths(),
+ };
+
+ let result = analyze_image(req).expect("analysis without models succeeds");
+ assert_eq!(result.decoded_image_size.width, 64);
+ assert_eq!(result.decoded_image_size.height, 48);
+ assert!(result.faces.is_none());
+ assert!(result.face_crops.is_none());
+ assert!(result.clip.is_none());
+ }
+
+ #[test]
+ fn analyze_image_rejects_undecodable_bytes() {
+ let req = AnalyzeImageRequest {
+ file_id: 1,
+ source: ImageSource::Bytes(vec![0u8; 16]),
+ run_faces: false,
+ run_clip: false,
+ run_pets: false,
+ generate_face_crops: false,
+ model_paths: empty_model_paths(),
+ };
+
+ match analyze_image(req) {
+ Err(MlError::Decode(_)) => {}
+ other => panic!("expected a decode error, got {other:?}"),
+ }
+ }
+}
diff --git a/rust/crates/photos/src/ml/onnx.rs b/rust/crates/photos/src/ml/onnx.rs
index e78aed48d6..d066bf1814 100644
--- a/rust/crates/photos/src/ml/onnx.rs
+++ b/rust/crates/photos/src/ml/onnx.rs
@@ -10,7 +10,7 @@ use std::{
use half::prelude::{HalfFloatSliceExt, HalfFloatVecExt};
-#[cfg(target_os = "ios")]
+#[cfg(any(target_os = "ios", target_os = "macos"))]
use ort::ep::{
CoreML,
coreml::{ComputeUnits, ModelFormat, SpecializationStrategy},
@@ -26,12 +26,12 @@ use std::num::NonZeroUsize;
use crate::ml::error::{MlError, MlResult};
use crate::ml::events;
use crate::ml::golden;
-#[cfg(any(target_os = "android", target_os = "ios"))]
+#[cfg(any(target_os = "android", target_os = "ios", target_os = "macos"))]
use crate::ml::runtime::rt_log;
#[cfg(target_os = "android")]
use crate::ml::webgpu;
-#[cfg(any(target_os = "ios", test))]
+#[cfg(any(target_os = "ios", target_os = "macos", test))]
const COREML_CACHE_SCHEMA: &str = "ort-1_27-mlprogram-all-default-v1";
const COREML_CACHE_COMPLETE_MARKER: &str = ".ente-cache-complete";
/// The name ONNX Runtime's CoreML EP gives the compiled model it stores
@@ -41,7 +41,7 @@ const COREML_CACHE_COMPILED_MODEL: &str = "compiled_model.mlmodelc";
/// The weight blob file name inside an ORT-generated `.mlpackage`
/// (`model_builder.cc` writes `@model_path/weights/weight.bin`).
const COREML_PACKAGE_WEIGHT_BLOB: &str = "weight.bin";
-#[cfg(target_os = "ios")]
+#[cfg(any(target_os = "ios", target_os = "macos"))]
const ENABLE_PERSISTENT_COREML_CACHE: bool = true;
/// An f32 model input that can be borrowed by multiple sessions.
@@ -203,14 +203,14 @@ pub(crate) fn build_session(
/// through to the next attempt. WebGPU attempts do not take this path; they
/// are validated inside the crash-canary window.
fn build_and_validate_session(model_path: &str, attempt: ProviderAttempt) -> MlResult<Session> {
- #[cfg(any(target_os = "android", target_os = "ios"))]
+ #[cfg(any(target_os = "android", target_os = "ios", target_os = "macos"))]
let execution_provider = attempt.execution_provider;
- #[cfg_attr(not(target_os = "ios"), allow(unused_mut))]
+ #[cfg_attr(not(any(target_os = "ios", target_os = "macos")), allow(unused_mut))]
let mut session = match build_session_with_providers(model_path, attempt) {
Ok(session) => session,
Err(error) => {
- #[cfg(any(target_os = "android", target_os = "ios"))]
+ #[cfg(any(target_os = "android", target_os = "ios", target_os = "macos"))]
record_provider_attempt_failure(
execution_provider,
model_path,
@@ -221,7 +221,7 @@ fn build_and_validate_session(model_path: &str, attempt: ProviderAttempt) -> MlR
}
};
- #[cfg(target_os = "ios")]
+ #[cfg(any(target_os = "ios", target_os = "macos"))]
if execution_provider == ExecutionProvider::CoreMl {
run_session_self_test(model_path, &mut session, "CoreML")?;
}
@@ -302,7 +302,7 @@ fn build_webgpu_session_with_canary(
Ok(session)
}
-#[cfg(any(target_os = "android", target_os = "ios"))]
+#[cfg(any(target_os = "android", target_os = "ios", target_os = "macos"))]
fn record_provider_attempt_failure(
provider: ExecutionProvider,
model_path: &str,
@@ -314,7 +314,7 @@ fn record_provider_attempt_failure(
}
}
-#[cfg(any(target_os = "android", target_os = "ios", test))]
+#[cfg(any(target_os = "android", target_os = "ios", target_os = "macos", test))]
fn provider_attempt_failure_message(
provider: ExecutionProvider,
model_path: &str,
@@ -336,7 +336,7 @@ fn provider_attempt_failure_message(
/// Validates a freshly built accelerated session against the model's
/// committed golden output. An error means the session must not be used; the
/// caller falls through to the next execution provider attempt.
-#[cfg(any(target_os = "android", target_os = "ios"))]
+#[cfg(any(target_os = "android", target_os = "ios", target_os = "macos"))]
fn run_session_self_test(
model_path: &str,
session: &mut Session,
@@ -521,7 +521,7 @@ fn provider_attempts(
}
}
-#[cfg(target_os = "ios")]
+#[cfg(any(target_os = "ios", target_os = "macos"))]
fn platform_default_attempts(
model_path: &str,
coreml_cache_namespace: &str,
@@ -545,7 +545,7 @@ fn platform_default_attempts(
attempts
}
-#[cfg(target_os = "ios")]
+#[cfg(any(target_os = "ios", target_os = "macos"))]
fn coreml_provider(
model_path: &str,
cache_namespace: &str,
@@ -582,7 +582,7 @@ fn coreml_provider(
/// Deletes the entire persistent cache tree while the feature is disabled, so
/// flipping `ENABLE_PERSISTENT_COREML_CACHE` off in a release actually
/// returns the disk space instead of stranding the caches forever.
-#[cfg(target_os = "ios")]
+#[cfg(any(target_os = "ios", target_os = "macos"))]
fn remove_persistent_coreml_cache(model_path: &str) {
let Some(coreml_root) = coreml_cache_root(Path::new(model_path))
.parent()
@@ -634,7 +634,7 @@ fn platform_default_attempts(
/// Accelerated execution providers are only allowed for models with a
/// committed golden self-test entry (fail closed). A miss for a production
/// model means a model update shipped without regenerating `golden_data.rs`.
-#[cfg(any(target_os = "android", target_os = "ios"))]
+#[cfg(any(target_os = "android", target_os = "ios", target_os = "macos"))]
fn golden_entry_required(model_path: &str, provider_label: &str) -> bool {
if golden::lookup(model_path).is_some() {
return true;
@@ -658,7 +658,7 @@ fn webgpu_provider() -> ExecutionProviderDispatch {
.error_on_failure()
}
-#[cfg(not(any(target_os = "ios", target_os = "android")))]
+#[cfg(not(any(target_os = "ios", target_os = "android", target_os = "macos")))]
fn platform_default_attempts(
_model_path: &str,
_coreml_cache_namespace: &str,
@@ -666,7 +666,7 @@ fn platform_default_attempts(
vec![ProviderAttempt::cpu_only()]
}
-#[cfg(target_os = "ios")]
+#[cfg(any(target_os = "ios", target_os = "macos"))]
fn prepare_coreml_cache_directory(
model_path: &str,
cache_namespace: &str,
@@ -706,7 +706,7 @@ fn prepare_coreml_cache_directory(
/// A missing completion marker means the process stopped before ONNX Runtime
/// finished constructing the session. Recreate the directory so ORT cannot
/// mistake a partial model package for a valid cache hit.
-#[cfg(any(target_os = "ios", test))]
+#[cfg(any(target_os = "ios", target_os = "macos", test))]
fn prepare_coreml_cache_entry(cache_dir: &Path) -> std::io::Result<()> {
if cache_dir.exists() && !coreml_cache_complete_marker(cache_dir).is_file() {
std::fs::remove_dir_all(cache_dir)?;
@@ -832,7 +832,7 @@ fn coreml_cache_complete_marker(cache_dir: &Path) -> PathBuf {
/// Keep generated CoreML artifacts in Library/Caches so iOS can evict them and
/// exclude them from backups. Model files are stored below Library/Application
/// Support; fall back to the process temporary directory for unusual layouts.
-#[cfg(any(target_os = "ios", test))]
+#[cfg(any(target_os = "ios", target_os = "macos", test))]
fn coreml_cache_root(model_path: &Path) -> PathBuf {
let cache_base = model_path
.ancestors()
@@ -850,7 +850,7 @@ fn coreml_cache_root(model_path: &Path) -> PathBuf {
/// Include the filename and file metadata in the directory name because ONNX
/// Runtime's internal CoreML cache key does not necessarily change when only
/// model weights change.
-#[cfg(any(target_os = "ios", test))]
+#[cfg(any(target_os = "ios", target_os = "macos", test))]
fn coreml_model_cache_key(model_path: &Path) -> std::io::Result<String> {
use std::time::UNIX_EPOCH;
@@ -873,7 +873,7 @@ fn coreml_model_cache_key(model_path: &Path) -> std::io::Result<String> {
))
}
-#[cfg(any(target_os = "ios", test))]
+#[cfg(any(target_os = "ios", target_os = "macos", test))]
fn sanitize_cache_component(value: &str) -> String {
value
.chars()
@@ -891,7 +891,7 @@ fn sanitize_cache_component(value: &str) -> String {
/// versions, returning the names of the removed directories. Without this, a
/// schema bump (ORT upgrade or CoreML policy change) would orphan the
/// previous schema's caches β€” hundreds of MB β€” forever.
-#[cfg(any(target_os = "ios", test))]
+#[cfg(any(target_os = "ios", target_os = "macos", test))]
fn prune_stale_coreml_schema_directories(
coreml_root: &Path,
current_schema: &str,
@@ -915,7 +915,7 @@ fn prune_stale_coreml_schema_directories(
/// Retain exactly one generated cache for each logical model slot. The active
/// directory is identity-specific so ONNX Runtime cannot reuse stale output.
-#[cfg(any(target_os = "ios", test))]
+#[cfg(any(target_os = "ios", target_os = "macos", test))]
fn prune_superseded_coreml_cache_directories(
model_cache_root: &Path,
current_cache_key: &str,
diff --git a/rust/crates/photos/src/ml/runtime.rs b/rust/crates/photos/src/ml/runtime.rs
index 888a370b79..4dc2eae9ea 100644
--- a/rust/crates/photos/src/ml/runtime.rs
+++ b/rust/crates/photos/src/ml/runtime.rs
@@ -555,7 +555,11 @@ pub(crate) fn release_runtime() {
}
fn should_retry_execution_provider_runtime(error: &MlError) -> bool {
- cfg!(any(target_os = "ios", target_os = "android")) && is_execution_provider_failure(error)
+ cfg!(any(
+ target_os = "ios",
+ target_os = "android",
+ target_os = "macos"
+ )) && is_execution_provider_failure(error)
}
fn is_execution_provider_failure(error: &MlError) -> bool {
diff --git a/rust/crates/photos/tests/support/ml_indexing.rs b/rust/crates/photos/tests/support/ml_indexing.rs
index f9a2d30e62..62cf6d9159 100644
--- a/rust/crates/photos/tests/support/ml_indexing.rs
+++ b/rust/crates/photos/tests/support/ml_indexing.rs
@@ -9,7 +9,8 @@ use ente_model_download::download;
use ente_photos::ml::{
error::MlError,
indexing::{
- AnalyzeImageRequest, AnalyzeImageResult, analyze_image, init_ml_runtime, release_ml_runtime,
+ AnalyzeImageRequest, AnalyzeImageResult, ImageSource, analyze_image, init_ml_runtime,
+ release_ml_runtime,
},
runtime::ModelPaths,
types::FaceResult as RustFaceResult,
@@ -275,10 +276,11 @@ impl MlIndexingTestContext {
};
let req = AnalyzeImageRequest {
file_id: (index + 1) as i64,
- image_path: image_path.to_string_lossy().into_owned(),
+ source: ImageSource::Path(image_path.to_string_lossy().into_owned()),
run_faces: true,
run_clip: true,
run_pets: false,
+ generate_face_crops: true,
model_paths: runtime.model_paths().clone(),
};
@@ -288,16 +290,25 @@ impl MlIndexingTestContext {
}
match analyze_image(req) {
- Ok(result) => match comparable_from_rust(&file_id, &result) {
- Ok(comparable) => {
- if rust_results.insert(file_id.clone(), comparable).is_some() {
- failures.push(format!("{file_id}: duplicate Rust result"));
- }
+ Ok(result) => {
+ let face_count = result.faces.as_ref().map_or(0, Vec::len);
+ let crop_count = result.face_crops.as_ref().map_or(0, Vec::len);
+ if crop_count != face_count {
+ failures.push(format!(
+ "{file_id}: face crop count {crop_count} does not match face count {face_count}"
+ ));
}
- Err(error) => {
- failures.push(format!("{file_id}: invalid Rust result: {error:#}"))
+ match comparable_from_rust(&file_id, &result) {
+ Ok(comparable) => {
+ if rust_results.insert(file_id.clone(), comparable).is_some() {
+ failures.push(format!("{file_id}: duplicate Rust result"));
+ }
+ }
+ Err(error) => {
+ failures.push(format!("{file_id}: invalid Rust result: {error:#}"))
+ }
}
- },
+ }
Err(error) => failures.push(format!("{file_id}: Rust ML indexing failed: {error}")),
}
}
diff --git a/web/packages/base/types/ipc.ts b/web/packages/base/types/ipc.ts
index dccca7e2c6..125cd68479 100644
--- a/web/packages/base/types/ipc.ts
+++ b/web/packages/base/types/ipc.ts
@@ -732,24 +732,30 @@ export interface ElectronMLWorker {
fsStatMtime: (path: string) => Promise<number>;
/**
- * Return a CLIP embedding of the given image.
+ * Analyze a single image with the Rust ML pipeline, computing the indexes
+ * (faces, CLIP) that are enabled in the request.
*
- * See: [Note: Natural language search using CLIP]
+ * The image is decoded, preprocessed, run through the ONNX models, and
+ * postprocessed entirely on the native side (by the Rust crate shared
+ * with the other Ente clients); we get back the final results.
*
- * The input is a opaque float32 array representing the image. The layout
- * and exact encoding of the input is specific to the runtime (ONNX) and the
- * ML model (a MobileCLIP variant) we use. In particular, the image
- * pre-processing happens within our model itself.
+ * See: [Note: ML with Rust]
+ */
+ analyzeImage: (
+ request: MLWorkerAnalyzeImageRequest,
+ ) => Promise<MLWorkerAnalyzeImageResult>;
+
+ /**
+ * Release the (pinned) native ML sessions.
*
- * @returns A CLIP embedding (an array of 512 floating point values).
+ * Invoked when indexing goes idle so that the utility process doesn't
+ * hold on to the model memory while there is nothing to do. Sessions are
+ * transparently recreated on the next {@link analyzeImage}.
*/
- computeCLIPImageEmbedding: (
- input: Uint8ClampedArray,
- inputShape: number[],
- ) => Promise<Float32Array>;
+ releaseMLRuntime: () => Promise<void>;
/**
- * Return a CLIP embedding of the given image if we already have the model
+ * Return a CLIP embedding of the given text if we already have the model
* downloaded and prepped. If the model is not available return `undefined`.
*
* This differs from the other sibling ML functions in that it doesn't wait
@@ -766,30 +772,102 @@ export interface ElectronMLWorker {
*
* @param text The string whose embedding we want to compute.
*
- * @returns A CLIP embedding.
+ * @returns A CLIP embedding (a normalized array of 512 floating point
+ * values).
*/
computeCLIPTextEmbeddingIfAvailable: (
text: string,
) => Promise<Float32Array | undefined>;
+}
+/**
+ * A request to index a single image via {@link ElectronMLWorker.analyzeImage}.
+ */
+export interface MLWorkerAnalyzeImageRequest {
+ /** The ID of the {@link EnteFile} being indexed. */
+ fileID: number;
/**
- * Detect faces in the given image using YOLO.
- *
- * Both the input and output are opaque binary data whose internal structure
- * is specific to our implementation and the model (YOLO) we use.
+ * Path to the image on the user's local file system. Exactly one of
+ * {@link path} and {@link bytes} should be provided.
+ */
+ path?: string | undefined;
+ /**
+ * The (encoded) contents of the image, in any supported format; the
+ * native side takes care of decoding.
+ */
+ bytes?: Uint8Array | undefined;
+ /** Compute the face related parts of the index. */
+ runFaces: boolean;
+ /** Compute the CLIP image embedding. */
+ runClip: boolean;
+ /** Run the pet recognition models (feature in development). */
+ runPets: boolean;
+ /**
+ * When set, the result will carry a JPEG face crop for each detected
+ * face.
+ */
+ generateFaceCrops: boolean;
+}
+
+/**
+ * A face detected by {@link ElectronMLWorker.analyzeImage}.
+ *
+ * All coordinates are relative (normalized to 0-1 by the dimensions of the
+ * image).
+ */
+export interface MLWorkerFaceResult {
+ /**
+ * The face ID. Same format as the faceIDs the web pipeline used to
+ * generate: `{fileID}_{xMin}_{yMin}_{xMax}_{yMax}`.
*/
- detectFaces: (
- input: Uint8ClampedArray,
- inputShape: number[],
- ) => Promise<Float32Array>;
+ faceId: string;
+ detection: {
+ score: number;
+ /** Relative [xMin, yMin, xMax, yMax]. */
+ boxXyxy: number[];
+ /**
+ * 5 relative [x, y] landmarks: leftEye, rightEye, nose, leftMouth,
+ * rightMouth.
+ */
+ keypoints: number[][];
+ };
+ blurValue: number;
+ /** The face embedding (192 floating point values). */
+ embedding: number[];
+}
+/**
+ * The result of an {@link ElectronMLWorker.analyzeImage} call.
+ *
+ * This mirrors the result produced by the Rust pipeline (only the parts of
+ * the index that were enabled in the request are present).
+ */
+export interface MLWorkerAnalyzeImageResult {
+ fileId: number;
+ /** The dimensions of the decoded image (after orientation correction). */
+ decodedImageSize: { width: number; height: number };
+ /** Present when the request had {@link runFaces} set. */
+ faces?: MLWorkerFaceResult[];
+ /**
+ * JPEG blobs of the crops of detected faces, index-aligned with
+ * {@link faces}. Present when the request had {@link generateFaceCrops}
+ * set.
+ */
+ faceCrops?: Uint8Array<ArrayBuffer>[];
+ /** Present when the request had {@link runClip} set. */
+ clip?: {
+ /** The (normalized) CLIP image embedding (512 floating point values). */
+ embedding: number[];
+ };
+ /** Pet recognition results (feature in development, ignored for now). */
+ petFaces?: unknown;
+ petBodies?: unknown;
/**
- * Return a MobileFaceNet embeddings for the given faces.
- *
- * Both the input and output are opaque binary data whose internal structure
- * is specific to our implementation and the model (MobileFaceNet) we use.
+ * True when any model that contributed to this result ran on the
+ * respective accelerated execution provider.
*/
- computeFaceEmbeddings: (input: Float32Array) => Promise<Float32Array>;
+ usedCoreml: boolean;
+ usedWebgpu: boolean;
}
/**
diff --git a/web/packages/new/photos/services/ml/blob.ts b/web/packages/new/photos/services/ml/blob.ts
index 01d884b472..f8dd92689c 100644
--- a/web/packages/new/photos/services/ml/blob.ts
+++ b/web/packages/new/photos/services/ml/blob.ts
@@ -12,8 +12,79 @@ import type { EnteFile } from "ente-media/file";
import { fileFileName } from "ente-media/file-metadata";
import { FileType } from "ente-media/file-type";
import { decodeLivePhoto } from "ente-media/live-photo";
-export { createImageBitmapAndData } from "./decode";
-export type { ImageBitmapAndData } from "./decode";
+
+/**
+ * The image that should be indexed for a given file, either as a path on the
+ * user's file system or as its (encoded, undecoded) contents.
+ *
+ * The native side decodes all the formats we care about itself, so unlike
+ * {@link fetchRenderableBlob} there is no JPEG conversion involved.
+ */
+export type IndexableImageSource =
+ | { path: string; bytes?: undefined }
+ | { path?: undefined; bytes: Uint8Array };
+
+/**
+ * Return the original image contents (or its path on disk) for the native ML
+ * pipeline to index.
+ *
+ * - For images this is the original image itself: the local file when we're
+ * called during an upload from this client, otherwise the downloaded (and
+ * decrypted) original.
+ * - For videos it is their (JPEG) thumbnail.
+ * - For live photos it is the image component of the live photo.
+ *
+ * @param file The {@link EnteFile} to index.
+ *
+ * @param puItem If we're called during the upload process, then this will be
+ * set to the {@link ProcessableUploadItem} that was uploaded so that we can
+ * directly use the on-disk file instead of needing to download the original.
+ *
+ * @param electron The {@link ElectronMLWorker} instance that we can use to
+ * IPC with the Node.js layer.
+ */
+export const fetchIndexableImageSource = async (
+ file: EnteFile,
+ puItem: ProcessableUploadItem | undefined,
+ electron: ElectronMLWorker,
+): Promise<IndexableImageSource> => {
+ if (file.metadata.fileType == FileType.video) {
+ const thumbnailData = await downloadManager.thumbnailData(file);
+ return { bytes: thumbnailData! };
+ }
+
+ if (puItem) {
+ if (puItem instanceof File) {
+ return { bytes: new Uint8Array(await puItem.arrayBuffer()) };
+ }
+ const uploadItem = await fileSystemUploadItemIfUnchanged(
+ puItem,
+ electron.fsStatMtime,
+ );
+ if (uploadItem) {
+ // The native side can directly read (and decode) local files, so
+ // pass paths as paths; only zip entries need to be read by us.
+ if (typeof uploadItem == "string") return { path: uploadItem };
+ const blob = await readNonVideoUploadItem(uploadItem, electron);
+ return { bytes: new Uint8Array(await blob.arrayBuffer()) };
+ }
+ // The file on disk has changed. Fetch it from remote instead.
+ }
+
+ const originalFileBlob = await downloadManager.fileBlob(file, {
+ background: true,
+ });
+
+ if (file.metadata.fileType == FileType.livePhoto) {
+ const { imageData } = await decodeLivePhoto(
+ fileFileName(file),
+ originalFileBlob,
+ );
+ return { bytes: imageData };
+ } else {
+ return { bytes: new Uint8Array(await originalFileBlob.arrayBuffer()) };
+ }
+};
/**
* Return a renderable blob (converting to JPEG if needed) for the given data.
diff --git a/web/packages/new/photos/services/ml/clip.ts b/web/packages/new/photos/services/ml/clip.ts
index 0d2e638ff1..0a6e2e4a29 100644
--- a/web/packages/new/photos/services/ml/clip.ts
+++ b/web/packages/new/photos/services/ml/clip.ts
@@ -1,5 +1,4 @@
import type { ElectronMLWorker } from "ente-base/types/ipc";
-import type { ImageBitmapAndData } from "./blob";
import { savedCLIPIndexes } from "./db";
import { dotProduct, norm } from "./math";
import type { CLIPMatches } from "./worker-types";
@@ -80,48 +79,6 @@ export type LocalCLIPIndex = CLIPIndex & {
fileID: number;
};
-/**
- * Compute the CLIP embedding of a given {@link image}.
- *
- * This function is the third and fourth stage of the CLIP indexing pipeline.
- * The file goes through various stages:
- *
- * 1. Download the original (if needed).
- * 2. Convert (if needed) to obtain an image bitmap.
- * 3. Preprocess the image bitmap.
- * 4. Compute embeddings of this preprocessed image using ONNX/CLIP.
- *
- * Once all of it is done, it CLIP embedding (wrapped as a {@link CLIPIndex} so
- * that it can be saved locally and also uploaded to the user's remote storage
- * for use on their other devices).
- *
- * @param image The image bitmap (and its associated data) of the image file
- * whose CLIP embedding we're computing.
- *
- * @param electron The {@link ElectronMLWorker} instance that allows us to call
- * our Node.js layer to run the ONNX inference.
- */
-export const indexCLIP = async (
- image: ImageBitmapAndData,
- electron: ElectronMLWorker,
-): Promise<CLIPIndex> => ({
- embedding: Array.from(await computeEmbedding(image.data, electron)),
-});
-
-const computeEmbedding = async (
- imageData: ImageData,
- electron: ElectronMLWorker,
-): Promise<Float32Array> => {
- // The image pre-preprocessing happens within the model itself, using ONNX
- // primitives. This is more performant and also saves us from having to
- // reinvent (say) the antialiasing wheels.
- const { height, width, data: pixelData } = imageData;
- const inputShape = [height, width, 4]; // [H, W, C]
- return normalized(
- await electron.computeCLIPImageEmbedding(pixelData, inputShape),
- );
-};
-
const normalized = (embedding: Float32Array) => {
const n = norm(embedding);
return embedding.map((v) => v / n);
diff --git a/web/packages/new/photos/services/ml/crop.ts b/web/packages/new/photos/services/ml/crop.ts
index b9b939b945..9eac4d2d11 100644
--- a/web/packages/new/photos/services/ml/crop.ts
+++ b/web/packages/new/photos/services/ml/crop.ts
@@ -35,6 +35,35 @@ export const regenerateFaceCrops = async (
}
};
+/**
+ * Locally save the face crops that the native ML pipeline generated while
+ * indexing an image.
+ *
+ * @param faceCrops JPEG blobs of the face crops, index-aligned with the faces
+ * in {@link faceIndex}.
+ *
+ * @param faceIndex The {@link FaceIndex} containing information about the
+ * faces detected in the given image.
+ *
+ * The face crops are saved in a local cache and can subsequently be retrieved
+ * from the {@link BlobCache} named "face-crops".
+ */
+export const saveFaceCropBlobs = async (
+ faceCrops: Uint8Array<ArrayBuffer>[],
+ faceIndex: FaceIndex,
+) => {
+ const cache = await blobCache("face-crops");
+
+ return Promise.all(
+ faceIndex.faces.flatMap(({ faceID }, i) => {
+ const crop = faceCrops[i];
+ return crop
+ ? [cache.put(faceID, new Blob([crop], { type: "image/jpeg" }))]
+ : [];
+ }),
+ );
+};
+
/**
* Extract and locally save the face crops (the rectangle of the original image
* that contain the detected face) for each of the faces detected in an image.
diff --git a/web/packages/new/photos/services/ml/decode.ts b/web/packages/new/photos/services/ml/decode.ts
deleted file mode 100644
index b27f304014..0000000000
--- a/web/packages/new/photos/services/ml/decode.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-/**
- * An image bitmap and its RGBA data.
- *
- * This is data structure containing data about an image in all formats that the
- * various indexing steps need.
- */
-export interface ImageBitmapAndData {
- /**
- * An {@link ImageBitmap} from the original or converted image.
- *
- * This bitmap is constructed from the original file's data if the
- * browser knows how to handle it; otherwise we first convert it to a JPEG
- * and then create the bitmap from that.
- */
- bitmap: ImageBitmap;
- /**
- * The RGBA {@link ImageData} of the {@link bitmap}, obtained by rendering
- * it to an offscreen canvas.
- */
- data: ImageData;
-}
-
-/**
- * Create an {@link ImageBitmap} from the given {@link imageBlob}, and return
- * both the image bitmap and its {@link ImageData}.
- *
- * @param maxPixels If specified, reject if the decoded image has more pixels
- * than this limit. The check happens before obtaining the image's data, which
- * would've required allocations proportional to the image size.
- */
-export const createImageBitmapAndData = async (
- imageBlob: Blob,
- maxPixels?: number,
-): Promise<ImageBitmapAndData> => {
- const imageBitmap = await createImageBitmap(imageBlob);
-
- const { width, height } = imageBitmap;
-
- if (maxPixels && width * height > maxPixels) {
- imageBitmap.close();
- throw new Error(`Image too large (${width}x${height})`);
- }
-
- // Use an OffscreenCanvas to get the bitmap's data.
- const offscreenCanvas = new OffscreenCanvas(width, height);
- const ctx = offscreenCanvas.getContext("2d")!;
- ctx.drawImage(imageBitmap, 0, 0, width, height);
- const imageData = ctx.getImageData(0, 0, width, height);
-
- return { bitmap: imageBitmap, data: imageData };
-};
diff --git a/web/packages/new/photos/services/ml/face.ts b/web/packages/new/photos/services/ml/face.ts
index e3f4c4a94b..925b7f3258 100644
--- a/web/packages/new/photos/services/ml/face.ts
+++ b/web/packages/new/photos/services/ml/face.ts
@@ -1,14 +1,4 @@
import { assertionFailed } from "ente-base/assert";
-import type { ElectronMLWorker } from "ente-base/types/ipc";
-import type { EnteFile } from "ente-media/file";
-import { Matrix } from "ml-matrix";
-import { getSimilarityTransformation } from "similarity-transformation";
-import type { ImageBitmapAndData } from "./blob";
-import {
- grayscaleIntMatrixFromNormalized2List,
- warpAffineFloat32List,
-} from "./image";
-import { clamp } from "./math";
/**
* The version of the face indexing pipeline implemented by the current client.
@@ -225,397 +215,11 @@ export const fileIDFromFaceID = (faceID: string) => {
return fileID;
};
-/**
- * Index faces in the given file.
- *
- * This function is the entry point to the face indexing pipeline. The file goes
- * through various stages:
- *
- * 1. Detect faces using ONNX/YOLO
- * 2. Align the face rectangles, compute blur.
- * 3. Compute embeddings using ONNX/MFNT for the detected face (crop).
- *
- * Once all of it is done, it returns the face rectangles and embeddings so that
- * they can be saved locally (for offline use), and also uploaded to the user's
- * remote storage so that their other devices can download them instead of
- * needing to reindex.
- *
- * @param file The {@link EnteFile} to index.
- *
- * @param image The file's contents.
- *
- * @param electron The {@link ElectronMLWorker} instance that allows us to call
- * our Node.js layer to run the ONNX inference.
- */
-export const indexFaces = async (
- file: EnteFile,
- { data: imageData }: ImageBitmapAndData,
- electron: ElectronMLWorker,
-): Promise<FaceIndex> => ({
- width: imageData.width,
- height: imageData.height,
- faces: await indexFaces_(file.id, imageData, electron),
-});
-
-const indexFaces_ = async (
- fileID: number,
- imageData: ImageData,
- electron: ElectronMLWorker,
-): Promise<Face[]> => {
- const { width, height } = imageData;
- const imageDimensions = { width, height };
-
- const yoloFaceDetections = await detectFaces(imageData, electron);
- const partialResult = yoloFaceDetections.map(
- ({ box, landmarks, score }) => {
- const faceID = makeFaceID(fileID, box, imageDimensions);
- const detection = { box, landmarks };
- return { faceID, detection, score };
- },
- );
-
- const allAlignments = partialResult.map(({ detection }) =>
- computeFaceAlignment(detection),
- );
-
- let embeddings: Float32Array[] = [];
- let blurs: number[] = [];
-
- // Process the faces in batches of 50 to:
- //
- // 1. Avoid memory pressure (as on ONNX 1.80.0, we can reproduce a crash if
- // we try to compute MFNet embeddings for a file with ~280 faces).
- //
- // 2. Reduce the time the main (Node.js) process is unresponsive (whenever
- // the main thread of the Node.js process is CPU bound, the renderer also
- // becomes unresponsive since events are routed via the main process).
- //
- const batchSize = 50;
- for (let i = 0; i < yoloFaceDetections.length; i += batchSize) {
- const alignments = allAlignments.slice(i, i + batchSize);
- const detections = partialResult
- .slice(i, i + batchSize)
- .map((f) => f.detection);
-
- const alignedFacesData = convertToMobileFaceNetInput(
- imageData,
- alignments,
- );
-
- embeddings = embeddings.concat(
- await computeEmbeddings(alignedFacesData, electron),
- );
- blurs = blurs.concat(detectBlur(alignedFacesData, detections));
- }
-
- return partialResult.map(({ faceID, detection, score }, i) => ({
- faceID,
- detection: normalizeByImageDimensions(detection, imageDimensions),
- score,
- blur: blurs[i]!,
- embedding: Array.from(embeddings[i]!),
- }));
-};
-
-/**
- * Detect faces in the given image.
- *
- * The model used is YOLOv5Face, running in an ONNX runtime.
- */
-const detectFaces = async (
- imageData: ImageData,
- electron: ElectronMLWorker,
-): Promise<YOLOFaceDetection[]> => {
- // The image pre-preprocessing happens within the model itself, using ONNX
- // primitives. This is more performant and also saves us from having to
- // reinvent (say) the antialiasing wheels.
- const {
- height: imageHeight,
- width: imageWidth,
- data: pixelData,
- } = imageData;
- const inputShape = [imageHeight, imageWidth, 4]; // [H, W, C]
-
- const scaledSize = getScaledSize(imageWidth, imageHeight);
- const yoloOutput = await electron.detectFaces(pixelData, inputShape);
- const faces = filterExtractDetectionsFromYOLOOutput(yoloOutput);
- const faceDetections = transformYOLOFaceDetections(
- faces,
- {
- x: (640 - scaledSize.width) / 2,
- y: (640 - scaledSize.height) / 2,
- width: scaledSize.width,
- height: scaledSize.height,
- },
- { x: 0, y: 0, width: imageWidth, height: imageHeight },
- );
-
- return faceDetections;
-};
-
-/**
- * Calculate image scaling done inside ONNX model run preprocessing. Needed to
- * correct the output.
- */
-const getScaledSize = (imageWidth: number, imageHeight: number) => {
- const requiredWidth = 640;
- const requiredHeight = 640;
-
- const scale = Math.min(
- requiredWidth / imageWidth,
- requiredHeight / imageHeight,
- );
- const scaledWidth = clamp(Math.round(imageWidth * scale), 0, requiredWidth);
- const scaledHeight = clamp(
- Math.round(imageHeight * scale),
- 0,
- requiredHeight,
- );
- return { width: scaledWidth, height: scaledHeight };
-};
-
-interface YOLOFaceDetection {
- box: Box;
- landmarks: Point[];
- score: number;
-}
-
-/**
- * Extract detected faces from the YOLOv5Face's output.
- *
- * Only detections that exceed a minimum score are returned.
- *
- * @param rows A Float32Array of shape [25200, 16], where each row represents a
- * face detection.
- *
- * YOLO detects a fixed number of faces, 25200, always from the input it is
- * given. Each detection is a "row" of 16 bytes, containing the bounding box,
- * score, and landmarks of the detection.
- *
- * We prune out detections with a score lower than our threshold. However, we
- * will still be left with some overlapping detections of the same face: these
- * we will deduplicate in {@link removeDuplicateDetections}.
- */
-const filterExtractDetectionsFromYOLOOutput = (
- rows: Float32Array,
-): YOLOFaceDetection[] => {
- const faces: YOLOFaceDetection[] = [];
- // Iterate over each row.
- for (let i = 0; i < rows.length; i += 16) {
- const score = rows[i + 4]!;
- if (score < 0.7) continue;
-
- const xCenter = rows[i]!;
- const yCenter = rows[i + 1]!;
- const width = rows[i + 2]!;
- const height = rows[i + 3]!;
- const x = xCenter - width / 2.0; // topLeft
- const y = yCenter - height / 2.0; // topLeft
-
- const leftEyeX = rows[i + 5]!;
- const leftEyeY = rows[i + 6]!;
- const rightEyeX = rows[i + 7]!;
- const rightEyeY = rows[i + 8]!;
- const noseX = rows[i + 9]!;
- const noseY = rows[i + 10]!;
- const leftMouthX = rows[i + 11]!;
- const leftMouthY = rows[i + 12]!;
- const rightMouthX = rows[i + 13]!;
- const rightMouthY = rows[i + 14]!;
-
- const box = { x, y, width, height };
- const landmarks = [
- { x: leftEyeX, y: leftEyeY },
- { x: rightEyeX, y: rightEyeY },
- { x: noseX, y: noseY },
- { x: leftMouthX, y: leftMouthY },
- { x: rightMouthX, y: rightMouthY },
- ];
- faces.push({ box, landmarks, score });
- }
- return faces;
-};
-
-/**
- * Transform the given {@link yoloFaceDetections} from their coordinate system in
- * which they were detected ({@link inBox}) back to the coordinate system of the
- * original image ({@link toBox}).
- */
-const transformYOLOFaceDetections = (
- yoloFaceDetections: YOLOFaceDetection[],
- inBox: Box,
- toBox: Box,
-): YOLOFaceDetection[] => {
- const scaleX = toBox.width / inBox.width;
- const scaleY = toBox.height / inBox.height;
- const translateX = toBox.x - inBox.x;
- const translateY = toBox.y - inBox.y;
-
- const correctDetections: YOLOFaceDetection[] = [];
-
- for (const detection of yoloFaceDetections) {
- const score = detection.score;
-
- const box = detection.box;
- box.x = (box.x + translateX) * scaleX;
- box.y = (box.y + translateY) * scaleY;
- box.width *= scaleX;
- box.height *= scaleY;
-
- const landmarks = detection.landmarks;
- landmarks.forEach((p) => {
- p.x = (p.x + translateX) * scaleX;
- p.y = (p.y + translateY) * scaleY;
- });
- correctDetections.push({ score, box, landmarks });
- }
-
- return correctDetections;
-};
-
-const makeFaceID = (fileID: number, box: Box, image: Dimensions) => {
- const part = (v: number) => clamp(v, 0.0, 0.999999).toFixed(5).substring(2);
- const xMin = part(box.x / image.width);
- const yMin = part(box.y / image.height);
- const xMax = part((box.x + box.width) / image.width);
- const yMax = part((box.y + box.height) / image.height);
- return [`${fileID}`, xMin, yMin, xMax, yMax].join("_");
-};
-
-interface FaceAlignment {
- /**
- * An affine transformation matrix (rotation, translation, scaling) to align
- * the face extracted from the image.
- */
- affineMatrix: number[][];
- /**
- * The bounding box of the transformed box.
- *
- * The affine transformation shifts the original detection box a new,
- * transformed, box (possibly rotated). This property is the bounding box
- * of that transformed box. It is in the coordinate system of the original,
- * full, image on which the detection occurred.
- */
- boundingBox: Box;
-}
-
-/**
- * Compute and return an {@link FaceAlignment} for the given face detection.
- *
- * @param faceDetection A geometry indicating a face detected in an image.
- */
-const computeFaceAlignment = (faceDetection: FaceDetection): FaceAlignment =>
- computeFaceAlignmentUsingSimilarityTransform(
- faceDetection,
- normalizeLandmarks(idealMobileFaceNetLandmarks, mobileFaceNetFaceSize),
- );
-
-/**
- * The ideal location of the landmarks (eye etc) that the MobileFaceNet
- * embedding model expects.
- */
-const idealMobileFaceNetLandmarks: [number, number][] = [
- [38.2946, 51.6963],
- [73.5318, 51.5014],
- [56.0252, 71.7366],
- [41.5493, 92.3655],
- [70.7299, 92.2041],
-];
-
-const normalizeLandmarks = (
- landmarks: [number, number][],
- faceSize: number,
-): [number, number][] =>
- landmarks.map(([x, y]) => [x / faceSize, y / faceSize]);
-
-const computeFaceAlignmentUsingSimilarityTransform = (
- faceDetection: FaceDetection,
- alignedLandmarks: [number, number][],
-): FaceAlignment => {
- const landmarksMat = new Matrix(
- faceDetection.landmarks
- .map((p) => [p.x, p.y])
- .slice(0, alignedLandmarks.length),
- ).transpose();
- const alignedLandmarksMat = new Matrix(alignedLandmarks).transpose();
-
- const simTransform = getSimilarityTransformation(
- landmarksMat,
- alignedLandmarksMat,
- );
-
- const RS = Matrix.mul(simTransform.rotation, simTransform.scale);
- const TR = simTransform.translation;
-
- const affineMatrix = [
- [RS.get(0, 0), RS.get(0, 1), TR.get(0, 0)],
- [RS.get(1, 0), RS.get(1, 1), TR.get(1, 0)],
- [0, 0, 1],
- ];
-
- const size = 1 / simTransform.scale;
- const meanTranslation = simTransform.toMean.sub(0.5).mul(size);
- const centerMat = simTransform.fromMean.sub(meanTranslation);
- const center = { x: centerMat.get(0, 0), y: centerMat.get(1, 0) };
-
- const boundingBox = {
- x: center.x - size / 2,
- y: center.y - size / 2,
- width: size,
- height: size,
- };
-
- return { affineMatrix, boundingBox };
-};
-
-const convertToMobileFaceNetInput = (
- imageData: ImageData,
- faceAlignments: FaceAlignment[],
-): Float32Array => {
- const faceSize = mobileFaceNetFaceSize;
- const faceData = new Float32Array(
- faceAlignments.length * faceSize * faceSize * 3,
- );
- for (let i = 0; i < faceAlignments.length; i++) {
- const { affineMatrix } = faceAlignments[i]!;
- const faceDataOffset = i * faceSize * faceSize * 3;
- warpAffineFloat32List(
- imageData,
- affineMatrix,
- faceSize,
- faceData,
- faceDataOffset,
- );
- }
- return faceData;
-};
-
interface FaceDetection {
box: Box;
landmarks: Point[];
}
-/**
- * Laplacian blur detection.
- *
- * Return an array of detected blur values, one for each face detection in
- * {@link faceDetections}. The face data is taken from the slice of
- * {@link alignedFacesData} corresponding to the face of {@link faceDetections}.
- */
-const detectBlur = (
- alignedFacesData: Float32Array,
- faceDetections: FaceDetection[],
-): number[] =>
- faceDetections.map((d, i) => {
- const faceImage = grayscaleIntMatrixFromNormalized2List(
- alignedFacesData,
- i,
- mobileFaceNetFaceSize,
- mobileFaceNetFaceSize,
- );
- return matrixVariance(applyLaplacian(faceImage, faceDirection(d)));
- });
-
type FaceDirection = "left" | "right" | "straight";
export const faceDirection = ({ landmarks }: FaceDetection): FaceDirection => {
@@ -654,178 +258,3 @@ export const faceDirection = ({ landmarks }: FaceDetection): FaceDirection => {
return "straight";
};
-
-/**
- * Return a new image by applying a Laplacian blur kernel to each pixel.
- */
-const applyLaplacian = (
- image: number[][],
- direction: FaceDirection,
-): number[][] => {
- const paddedImage = padImage(image, direction);
- const numRows = paddedImage.length - 2;
- const numCols = paddedImage[0]!.length - 2;
-
- // Create an output image initialized to 0.
- const outputImage = Array.from(
- { length: numRows },
- () => new Array(numCols).fill(0) as number[],
- );
-
- // Define the Laplacian kernel.
- const kernel = [
- [0, 1, 0],
- [1, -4, 1],
- [0, 1, 0],
- ];
-
- // Apply the kernel to each pixel
- for (let i = 0; i < numRows; i++) {
- for (let j = 0; j < numCols; j++) {
- let sum = 0;
- for (let ki = 0; ki < 3; ki++) {
- for (let kj = 0; kj < 3; kj++) {
- sum += paddedImage[i + ki]![j + kj]! * kernel[ki]![kj]!;
- }
- }
- // Adjust the output value if necessary (e.g., clipping).
- outputImage[i]![j] = sum;
- }
- }
-
- return outputImage;
-};
-
-const padImage = (image: number[][], direction: FaceDirection): number[][] => {
- const removeSideColumns = 56; /* must be even */
-
- const numRows = image.length;
- const numCols = image[0]!.length;
- const paddedNumCols = numCols + 2 - removeSideColumns;
- const paddedNumRows = numRows + 2;
-
- // Create a new matrix with extra padding.
- const paddedImage = Array.from(
- { length: paddedNumRows },
- () => new Array(paddedNumCols).fill(0) as number[],
- );
-
- if (direction == "straight") {
- // Copy original image into the center of the padded image.
- for (let i = 0; i < numRows; i++) {
- for (let j = 0; j < paddedNumCols - 2; j++) {
- paddedImage[i + 1]![j + 1] =
- image[i]![j + Math.round(removeSideColumns / 2)]!;
- }
- }
- } else if (direction == "left") {
- // If the face is facing left, we only take the right side of the face
- // image.
- for (let i = 0; i < numRows; i++) {
- for (let j = 0; j < paddedNumCols - 2; j++) {
- paddedImage[i + 1]![j + 1] = image[i]![j + removeSideColumns]!;
- }
- }
- } else {
- // If the face is facing right, we only take the left side of the face
- // image.
- for (let i = 0; i < numRows; i++) {
- for (let j = 0; j < paddedNumCols - 2; j++) {
- paddedImage[i + 1]![j + 1] = image[i]![j]!;
- }
- }
- }
-
- // Reflect padding
- // - Top and bottom rows
- for (let j = 1; j <= paddedNumCols - 2; j++) {
- // Top row
- paddedImage[0]![j] = paddedImage[2]![j]!;
- // Bottom row
- paddedImage[numRows + 1]![j] = paddedImage[numRows - 1]![j]!;
- }
- // - Left and right columns
- for (let i = 0; i < numRows + 2; i++) {
- // Left column
- paddedImage[i]![0] = paddedImage[i]![2]!;
- // Right column
- paddedImage[i]![paddedNumCols - 1] =
- paddedImage[i]![paddedNumCols - 3]!;
- }
-
- return paddedImage;
-};
-
-const matrixVariance = (matrix: number[][]): number => {
- const numRows = matrix.length;
- const numCols = matrix[0]!.length;
- const totalElements = numRows * numCols;
-
- // Calculate the mean.
- let mean = 0;
- matrix.forEach((row) => {
- row.forEach((value) => {
- mean += value;
- });
- });
- mean /= totalElements;
-
- // Calculate the variance.
- let variance = 0;
- matrix.forEach((row) => {
- row.forEach((value) => {
- const diff: number = value - mean;
- variance += diff * diff;
- });
- });
- variance /= totalElements;
-
- return variance;
-};
-
-const mobileFaceNetFaceSize = 112;
-const mobileFaceNetEmbeddingSize = 192;
-
-/**
- * Compute embeddings for the given {@link faceData}.
- *
- * The model used is MobileFaceNet, running in an ONNX runtime.
- */
-const computeEmbeddings = async (
- faceData: Float32Array,
- electron: ElectronMLWorker,
-): Promise<Float32Array[]> => {
- const outputData = await electron.computeFaceEmbeddings(faceData);
-
- const embeddingSize = mobileFaceNetEmbeddingSize;
- const embeddings = new Array<Float32Array>(
- outputData.length / embeddingSize,
- );
- for (let i = 0; i < embeddings.length; i++) {
- embeddings[i] = new Float32Array(
- outputData.slice(i * embeddingSize, (i + 1) * embeddingSize),
- );
- }
- return embeddings;
-};
-
-/**
- * Convert the coordinates to between 0-1, normalized by the image's dimensions.
- */
-const normalizeByImageDimensions = (
- faceDetection: FaceDetection,
- { width, height }: Dimensions,
-): FaceDetection => {
- const oldBox: Box = faceDetection.box;
- const box = {
- x: oldBox.x / width,
- y: oldBox.y / height,
- width: oldBox.width / width,
- height: oldBox.height / height,
- };
- const landmarks = faceDetection.landmarks.map((l) => ({
- x: l.x / width,
- y: l.y / height,
- }));
- return { box, landmarks };
-};
diff --git a/web/packages/new/photos/services/ml/image.ts b/web/packages/new/photos/services/ml/image.ts
deleted file mode 100644
index 8d91842922..0000000000
--- a/web/packages/new/photos/services/ml/image.ts
+++ /dev/null
@@ -1,238 +0,0 @@
-import { Matrix, inverse } from "ml-matrix";
-import { clamp } from "./math";
-
-const pixelRGBA = (
- imageData: Uint8ClampedArray,
- width: number,
- height: number,
- x: number,
- y: number,
-) => {
- if (x < 0 || x >= width || y < 0 || y >= height) {
- return { r: 114, g: 114, b: 114, a: 0 };
- }
- const index = (y * width + x) * 4;
- return {
- r: imageData[index]!,
- g: imageData[index + 1]!,
- b: imageData[index + 2]!,
- a: imageData[index + 3]!,
- };
-};
-
-/**
- * Returns the pixel value (RGB) at the given coordinates ({@link fx},
- * {@link fy}) using bicubic interpolation.
- */
-export const pixelRGBBicubic = (
- fx: number,
- fy: number,
- imageData: Uint8ClampedArray,
- imageWidth: number,
- imageHeight: number,
-) => {
- // Clamp to image boundaries.
- fx = clamp(fx, 0, imageWidth - 1);
- fy = clamp(fy, 0, imageHeight - 1);
-
- const x = Math.trunc(fx) - (fx >= 0.0 ? 0 : 1);
- const px = x - 1;
- const nx = x + 1;
- const ax = x + 2;
- const y = Math.trunc(fy) - (fy >= 0.0 ? 0 : 1);
- const py = y - 1;
- const ny = y + 1;
- const ay = y + 2;
- const dx = fx - x;
- const dy = fy - y;
-
- const cubic = (
- dx: number,
- ipp: number,
- icp: number,
- inp: number,
- iap: number,
- ) =>
- icp +
- 0.5 *
- (dx * (-ipp + inp) +
- dx * dx * (2 * ipp - 5 * icp + 4 * inp - iap) +
- dx * dx * dx * (-ipp + 3 * icp - 3 * inp + iap));
-
- const icc = pixelRGBA(imageData, imageWidth, imageHeight, x, y);
-
- const ipp =
- px < 0 || py < 0
- ? icc
- : pixelRGBA(imageData, imageWidth, imageHeight, px, py);
- const icp =
- px < 0 ? icc : pixelRGBA(imageData, imageWidth, imageHeight, x, py);
- const inp =
- py < 0 || nx >= imageWidth
- ? icc
- : pixelRGBA(imageData, imageWidth, imageHeight, nx, py);
- const iap =
- ax >= imageWidth || py < 0
- ? icc
- : pixelRGBA(imageData, imageWidth, imageHeight, ax, py);
-
- const ip0 = cubic(dx, ipp.r, icp.r, inp.r, iap.r);
- const ip1 = cubic(dx, ipp.g, icp.g, inp.g, iap.g);
- const ip2 = cubic(dx, ipp.b, icp.b, inp.b, iap.b);
- // const ip3 = cubic(dx, ipp.a, icp.a, inp.a, iap.a);
-
- const ipc =
- px < 0 ? icc : pixelRGBA(imageData, imageWidth, imageHeight, px, y);
- const inc =
- nx >= imageWidth
- ? icc
- : pixelRGBA(imageData, imageWidth, imageHeight, nx, y);
- const iac =
- ax >= imageWidth
- ? icc
- : pixelRGBA(imageData, imageWidth, imageHeight, ax, y);
-
- const ic0 = cubic(dx, ipc.r, icc.r, inc.r, iac.r);
- const ic1 = cubic(dx, ipc.g, icc.g, inc.g, iac.g);
- const ic2 = cubic(dx, ipc.b, icc.b, inc.b, iac.b);
- // const ic3 = cubic(dx, ipc.a, icc.a, inc.a, iac.a);
-
- const ipn =
- px < 0 || ny >= imageHeight
- ? icc
- : pixelRGBA(imageData, imageWidth, imageHeight, px, ny);
- const icn =
- ny >= imageHeight
- ? icc
- : pixelRGBA(imageData, imageWidth, imageHeight, x, ny);
- const inn =
- nx >= imageWidth || ny >= imageHeight
- ? icc
- : pixelRGBA(imageData, imageWidth, imageHeight, nx, ny);
- const ian =
- ax >= imageWidth || ny >= imageHeight
- ? icc
- : pixelRGBA(imageData, imageWidth, imageHeight, ax, ny);
-
- const in0 = cubic(dx, ipn.r, icn.r, inn.r, ian.r);
- const in1 = cubic(dx, ipn.g, icn.g, inn.g, ian.g);
- const in2 = cubic(dx, ipn.b, icn.b, inn.b, ian.b);
- // const in3 = cubic(dx, ipn.a, icn.a, inn.a, ian.a);
-
- const ipa =
- px < 0 || ay >= imageHeight
- ? icc
- : pixelRGBA(imageData, imageWidth, imageHeight, px, ay);
- const ica =
- ay >= imageHeight
- ? icc
- : pixelRGBA(imageData, imageWidth, imageHeight, x, ay);
- const ina =
- nx >= imageWidth || ay >= imageHeight
- ? icc
- : pixelRGBA(imageData, imageWidth, imageHeight, nx, ay);
- const iaa =
- ax >= imageWidth || ay >= imageHeight
- ? icc
- : pixelRGBA(imageData, imageWidth, imageHeight, ax, ay);
-
- const ia0 = cubic(dx, ipa.r, ica.r, ina.r, iaa.r);
- const ia1 = cubic(dx, ipa.g, ica.g, ina.g, iaa.g);
- const ia2 = cubic(dx, ipa.b, ica.b, ina.b, iaa.b);
- // const ia3 = cubic(dx, ipa.a, ica.a, ina.a, iaa.a);
-
- const c0 = Math.trunc(clamp(cubic(dy, ip0, ic0, in0, ia0), 0, 255));
- const c1 = Math.trunc(clamp(cubic(dy, ip1, ic1, in1, ia1), 0, 255));
- const c2 = Math.trunc(clamp(cubic(dy, ip2, ic2, in2, ia2), 0, 255));
- // const c3 = cubic(dy, ip3, ic3, in3, ia3);
-
- return { r: c0, g: c1, b: c2 };
-};
-
-/**
- * Transform {@link inputData} starting at {@link inputStartIndex}.
- *
- * @param imageData The {@link ImageData} from which these alignments originate.
- */
-export const warpAffineFloat32List = (
- imageData: ImageData,
- faceAlignmentAffineMatrix: number[][],
- faceSize: number,
- inputData: Float32Array,
- inputStartIndex: number,
-): void => {
- const { width, height, data: pixelData } = imageData;
-
- const transformationMatrix = faceAlignmentAffineMatrix.map((row) =>
- row.map((val) => (val != 1.0 ? val * faceSize : 1.0)),
- ); // 3x3
-
- const A: Matrix = new Matrix([
- [transformationMatrix[0]![0]!, transformationMatrix[0]![1]!],
- [transformationMatrix[1]![0]!, transformationMatrix[1]![1]!],
- ]);
- const Ainverse = inverse(A);
-
- const b00 = transformationMatrix[0]![2]!;
- const b10 = transformationMatrix[1]![2]!;
- const a00Prime = Ainverse.get(0, 0);
- const a01Prime = Ainverse.get(0, 1);
- const a10Prime = Ainverse.get(1, 0);
- const a11Prime = Ainverse.get(1, 1);
-
- for (let yTrans = 0; yTrans < faceSize; ++yTrans) {
- for (let xTrans = 0; xTrans < faceSize; ++xTrans) {
- // Perform inverse affine transformation.
- const xOrigin =
- a00Prime * (xTrans - b00) + a01Prime * (yTrans - b10);
- const yOrigin =
- a10Prime * (xTrans - b00) + a11Prime * (yTrans - b10);
-
- // Get the pixel RGB using bicubic interpolation.
- const { r, g, b } = pixelRGBBicubic(
- xOrigin,
- yOrigin,
- pixelData,
- width,
- height,
- );
-
- // Set the pixel in the input data.
- const index = (yTrans * faceSize + xTrans) * 3;
- inputData[inputStartIndex + index] = rgbToBipolarFloat(r);
- inputData[inputStartIndex + index + 1] = rgbToBipolarFloat(g);
- inputData[inputStartIndex + index + 2] = rgbToBipolarFloat(b);
- }
- }
-};
-
-/** Convert a RGB component 0-255 to a floating point value between -1 and 1. */
-const rgbToBipolarFloat = (pixelValue: number) => pixelValue / 127.5 - 1.0;
-
-/** Convert a floating point value between -1 and 1 to a RGB component 0-255. */
-const bipolarFloatToRGB = (pixelValue: number) =>
- clamp(Math.round((pixelValue + 1.0) * 127.5), 0, 255);
-
-export const grayscaleIntMatrixFromNormalized2List = (
- imageList: Float32Array,
- faceNumber: number,
- width: number,
- height: number,
-): number[][] => {
- const startIndex = faceNumber * width * height * 3;
- return Array.from({ length: height }, (_, y) =>
- Array.from({ length: width }, (_, x) => {
- // 0.299 βˆ™ Red + 0.587 βˆ™ Green + 0.114 βˆ™ Blue
- const pixelIndex = startIndex + 3 * (y * width + x);
- return clamp(
- Math.round(
- 0.299 * bipolarFloatToRGB(imageList[pixelIndex]!) +
- 0.587 * bipolarFloatToRGB(imageList[pixelIndex + 1]!) +
- 0.114 * bipolarFloatToRGB(imageList[pixelIndex + 2]!),
- ),
- 0,
- 255,
- );
- }),
- );
-};
diff --git a/web/packages/new/photos/services/ml/worker.ts b/web/packages/new/photos/services/ml/worker.ts
index 4012acc9f2..5b2cbdf350 100644
--- a/web/packages/new/photos/services/ml/worker.ts
+++ b/web/packages/new/photos/services/ml/worker.ts
@@ -1,27 +1,33 @@
import { expose, wrap } from "comlink";
import { clientIdentifier } from "ente-base/app";
import { assertionFailed } from "ente-base/assert";
+import { lowercaseExtension } from "ente-base/file-name";
import { isHTTP4xxError, isHTTPErrorWithStatus } from "ente-base/http";
import log from "ente-base/log";
import { logUnhandledErrorsAndRejectionsInWorker } from "ente-base/log-web";
-import type { ElectronMLWorker } from "ente-base/types/ipc";
+import type {
+ ElectronMLWorker,
+ MLWorkerAnalyzeImageRequest,
+ MLWorkerAnalyzeImageResult,
+} from "ente-base/types/ipc";
import { isNetworkDownloadError } from "ente-gallery/services/download";
import type { ProcessableUploadItem } from "ente-gallery/services/upload";
import { fileLogID, type EnteFile } from "ente-media/file";
+import { fileFileName } from "ente-media/file-metadata";
import { FileType } from "ente-media/file-type";
+import { needsJPEGConversion } from "ente-media/formats";
import { savedTrashItemFileIDs } from "ente-new/photos/services/trash";
import { wait } from "ente-utils/promise";
import { savedCollectionFiles } from "../photos-fdb";
import {
- createImageBitmapAndData,
+ fetchIndexableImageSource,
fetchRenderableBlob,
- type ImageBitmapAndData,
+ type IndexableImageSource,
} from "./blob";
import {
_clipMatches,
clearCachedCLIPIndexes,
clipIndexingVersion,
- indexCLIP,
type CLIPIndex,
} from "./clip";
import {
@@ -30,7 +36,7 @@ import {
type ClusterFacesReason,
type ClusteringProgress,
} from "./cluster";
-import { saveFaceCrops } from "./crop";
+import { saveFaceCropBlobs } from "./crop";
import {
markIndexingFailed,
readNextIndexableFileIDs,
@@ -38,7 +44,7 @@ import {
saveIndexes,
updateAssumingLocalFiles,
} from "./db";
-import { faceIndexingVersion, indexFaces, type FaceIndex } from "./face";
+import { faceIndexingVersion, type FaceIndex } from "./face";
import {
fetchMLData,
putMLData,
@@ -295,6 +301,13 @@ export class MLWorker {
this.idleTimeout = setTimeout(scheduleTick, this.idleDuration * 1000);
this.delegate?.workerDidUpdateStatus();
+ // Release the native ML sessions while we're idling so that the
+ // utility process doesn't hold on to the model memory. They get
+ // recreated transparently on the next analysis.
+ void this.electron?.releaseMLRuntime().catch((e: unknown) => {
+ log.warn("Failed to release the native ML runtime", e);
+ });
+
// Resolve any awaiting promises returned from `index`.
const onNextIdles = this.onNextIdles;
const countSinceLastIdle = this.countSinceLastIdle;
@@ -486,15 +499,6 @@ const syncWithLocalFilesAndGetFilesToIndex = async (
*/
const maxIndexableFileSize = 100 * 1000 * 1000; /* 100 MB */
-/**
- * The maximum number of pixels in an image that we will index.
- *
- * ONNX runtime's conversion of the image into a float tensor makes a single
- * allocation of 12 bytes per pixel, and Electron's allocator aborts the
- * process on single allocations of 2 GiB or more (~179 megapixels).
- */
-const maxIndexablePixels = 150 * 1000 * 1000; /* 150 MP */
-
/**
* Index file, save the persist the results locally, and put them on remote.
*
@@ -582,7 +586,7 @@ const index = async (
// There is at least one ML data type that still needs to be indexed.
- let renderableBlob: Blob;
+ let source: IndexableImageSource;
try {
// Videos are indexed using their thumbnails, so the size of the video
// file itself does not matter.
@@ -594,7 +598,7 @@ const index = async (
`File too large to index (${file.info?.fileSize} bytes)`,
);
}
- renderableBlob = await fetchRenderableBlob(
+ source = await fetchIndexableImageSource(
file,
processableUploadItem,
electron,
@@ -607,107 +611,230 @@ const index = async (
throw e;
}
- let image: ImageBitmapAndData;
+ const runFaces = !existingFaceIndex;
+ const runClip = !existingCLIPIndex;
+
+ const startTime = Date.now();
+
+ let result: MLWorkerAnalyzeImageResult;
try {
- image = await createImageBitmapAndData(
- renderableBlob,
- maxIndexablePixels,
+ result = await analyzeImageWithConversionFallback(
+ file,
+ processableUploadItem,
+ source,
+ { runFaces, runClip },
+ electron,
);
} catch (e) {
- // If we cannot get the raw image data for the file, then retrying again
- // won't help (if in the future we enhance the underlying code for
- // `indexableBlobs` to handle this failing type we can trigger a
- // reindexing attempt for failed files).
- //
// See: [Note: Transient and permanent indexing failures]
await markIndexingFailed(fileID);
throw e;
}
+ const faceIndex = existingFaceIndex ?? faceIndexFromAnalysisResult(result);
+ const clipIndex = existingCLIPIndex ?? clipIndexFromAnalysisResult(result);
+
+ log.debug(() => {
+ const ms = Date.now() - startTime;
+ const msg = [];
+ if (runFaces) msg.push(`${faceIndex.faces.length} faces`);
+ if (runClip) msg.push("clip");
+ const ep = result.usedCoreml ? " [coreml]" : "";
+ return `Indexed ${msg.join(" and ")} in ${f} (${ms} ms)${ep}`;
+ });
+
+ const remoteFaceIndex = existingRemoteFaceIndex ?? {
+ version: faceIndexingVersion,
+ client: clientIdentifier,
+ ...faceIndex,
+ };
+
+ const remoteCLIPIndex = existingRemoteCLIPIndex ?? {
+ version: clipIndexingVersion,
+ client: clientIdentifier,
+ ...clipIndex,
+ };
+
+ // Perform an "upsert" by using the existing raw data we got from the
+ // remote as the base, and inserting or overwriting only the parts we
+ // actually (re)indexed. Preserving the raw entry for a kept
+ // face/clip retains any inner keys that the current client's Zod
+ // schema doesn't know about (e.g. a `flags` bitmask set by a
+ // different client). See: [Note: Preserve unknown ML data fields].
+
+ const existingRawMLData = remoteMLData?.raw ?? {};
+ const rawMLData: RawRemoteMLData = {
+ ...existingRawMLData,
+ ...(existingFaceIndex ? {} : { face: remoteFaceIndex }),
+ ...(existingCLIPIndex ? {} : { clip: remoteCLIPIndex }),
+ };
+
+ log.debug(() => ["Uploading ML data", rawMLData]);
+
try {
- let faceIndex: FaceIndex;
- let clipIndex: CLIPIndex;
+ const lastUpdatedAt = remoteMLData?.updatedAt ?? 0;
+ await putMLData(file, rawMLData, lastUpdatedAt);
+ } catch (e) {
+ // See: [Note: Transient and permanent indexing failures]
+ if (isHTTP4xxError(e)) {
+ // 409 Conflict indicates that we tried overwriting existing
+ // mldata. Don't mark it as a failure, the file has already been
+ // processed.
+ if (!isHTTPErrorWithStatus(e, 409)) {
+ await markIndexingFailed(fileID);
+ }
+ }
+ throw e;
+ }
- const startTime = Date.now();
+ await saveIndexes({ fileID, ...faceIndex }, { fileID, ...clipIndex });
+ // This step, saving face crops, is conceptually not part of the indexing
+ // pipeline; we just do it here since the analysis has already generated
+ // the crops for us from its decode of the original.
+ if (runFaces && result.faceCrops) {
try {
- [faceIndex, clipIndex] = await Promise.all([
- existingFaceIndex ?? indexFaces(file, image, electron),
- existingCLIPIndex ?? indexCLIP(image, electron),
- ]);
+ await saveFaceCropBlobs(result.faceCrops, faceIndex);
} catch (e) {
- // See: [Note: Transient and permanent indexing failures]
- await markIndexingFailed(fileID);
- throw e;
+ // Ignore errors that happen during this since it does not
+ // impact the generated face index.
+ log.error(`Failed to save face crops for ${f}`, e);
}
+ }
+};
- log.debug(() => {
- const ms = Date.now() - startTime;
- const msg = [];
- if (!existingFaceIndex) msg.push(`${faceIndex.faces.length} faces`);
- if (!existingCLIPIndex) msg.push("clip");
- return `Indexed ${msg.join(" and ")} in ${f} (${ms} ms)`;
- });
+/**
+ * `true` if the pet recognition models should also run while indexing.
+ *
+ * Pet recognition is still under development and not yet enabled anywhere.
+ * When it ships, this gate should mirror the mobile one (mobile's
+ * `flagService.petEnabled` is derived from the remote `internalUser` flag),
+ * and the pet results in the analysis response, currently ignored, will need
+ * to be persisted.
+ */
+const petsIndexingEnabled = false;
- const remoteFaceIndex = existingRemoteFaceIndex ?? {
- version: faceIndexingVersion,
- client: clientIdentifier,
- ...faceIndex,
- };
-
- const remoteCLIPIndex = existingRemoteCLIPIndex ?? {
- version: clipIndexingVersion,
- client: clientIdentifier,
- ...clipIndex,
- };
-
- // Perform an "upsert" by using the existing raw data we got from the
- // remote as the base, and inserting or overwriting only the parts we
- // actually (re)indexed. Preserving the raw entry for a kept
- // face/clip retains any inner keys that the current client's Zod
- // schema doesn't know about (e.g. a `flags` bitmask set by a
- // different client). See: [Note: Preserve unknown ML data fields].
-
- const existingRawMLData = remoteMLData?.raw ?? {};
- const rawMLData: RawRemoteMLData = {
- ...existingRawMLData,
- ...(existingFaceIndex ? {} : { face: remoteFaceIndex }),
- ...(existingCLIPIndex ? {} : { clip: remoteCLIPIndex }),
- };
-
- log.debug(() => ["Uploading ML data", rawMLData]);
+/**
+ * Run the native ML pipeline on the given image source.
+ *
+ * The native side decodes all common formats (including HEIC, JXL and TIFF)
+ * by itself, but not some rarer ones (e.g. camera RAW). For formats which the
+ * app handles by converting to JPEG, retry the analysis with the converted
+ * JPEG if the native decode reports a failure.
+ */
+const analyzeImageWithConversionFallback = async (
+ file: EnteFile,
+ processableUploadItem: ProcessableUploadItem | undefined,
+ source: IndexableImageSource,
+ { runFaces, runClip }: { runFaces: boolean; runClip: boolean },
+ electron: ElectronMLWorker,
+): Promise<MLWorkerAnalyzeImageResult> => {
+ const request = {
+ fileID: file.id,
+ runFaces,
+ runClip,
+ runPets: petsIndexingEnabled,
+ generateFaceCrops: runFaces,
+ };
- try {
- const lastUpdatedAt = remoteMLData?.updatedAt ?? 0;
- await putMLData(file, rawMLData, lastUpdatedAt);
- } catch (e) {
- // See: [Note: Transient and permanent indexing failures]
- if (isHTTP4xxError(e)) {
- // 409 Conflict indicates that we tried overwriting existing
- // mldata. Don't mark it as a failure, the file has already been
- // processed.
- if (!isHTTPErrorWithStatus(e, 409)) {
- await markIndexingFailed(fileID);
- }
- }
- throw e;
- }
+ try {
+ return await enqueueAnalyzeImage(electron, { ...request, ...source });
+ } catch (e) {
+ const ext = lowercaseExtension(fileFileName(file));
+ if (!isMLDecodeError(e) || !ext || !needsJPEGConversion(ext)) throw e;
- await saveIndexes({ fileID, ...faceIndex }, { fileID, ...clipIndex });
-
- // This step, saving face crops, is conceptually not part of the
- // indexing pipeline; we just do it here since we have already have the
- // ImageBitmap at hand.
- if (!existingFaceIndex) {
- try {
- await saveFaceCrops(image.bitmap, faceIndex);
- } catch (e) {
- // Ignore errors that happen during this since it does not
- // impact the generated face index.
- log.error(`Failed to save face crops for ${f}`, e);
- }
- }
- } finally {
- image.bitmap.close();
+ log.info(
+ `Native decode of ${fileLogID(file)} failed, retrying with a JPEG conversion`,
+ e,
+ );
+ const blob = await fetchRenderableBlob(
+ file,
+ processableUploadItem,
+ electron,
+ );
+ const bytes = new Uint8Array(await blob.arrayBuffer());
+ return await enqueueAnalyzeImage(electron, { ...request, bytes });
}
};
+
+/** `true` if the error looks like the native side failing to decode an image. */
+const isMLDecodeError = (e: unknown) =>
+ e instanceof Error && e.message.startsWith("Decode: ");
+
+/**
+ * A promise queue serializing calls to {@link ElectronMLWorker.analyzeImage}.
+ *
+ * We process multiple files in parallel so that the fetch (and decrypt) of
+ * subsequent items can proceed while one is being analyzed, but keep only a
+ * single native inference outstanding at a time: the native model sessions
+ * serialize anyway, and queueing on our end avoids tying up worker threads in
+ * the utility process.
+ */
+let _analyzeImageQueue: Promise<unknown> = Promise.resolve();
+
+const enqueueAnalyzeImage = (
+ electron: ElectronMLWorker,
+ request: MLWorkerAnalyzeImageRequest,
+): Promise<MLWorkerAnalyzeImageResult> => {
+ const result = _analyzeImageQueue.then(() =>
+ electron.analyzeImage(request),
+ );
+ _analyzeImageQueue = result.catch(() => undefined);
+ return result;
+};
+
+/**
+ * Convert the face related parts of an analysis result into the
+ * {@link FaceIndex} shape that we persist and upload.
+ *
+ * The coordinates in the result are already relative (normalized 0-1), and
+ * the faceIDs already have the format that the (legacy) web pipeline used, so
+ * this is a mechanical reshaping.
+ */
+const faceIndexFromAnalysisResult = (
+ result: MLWorkerAnalyzeImageResult,
+): FaceIndex => {
+ const faces = result.faces;
+ if (!faces) throw new Error("Analysis result is missing the face index");
+
+ const { width, height } = result.decodedImageSize;
+
+ return {
+ width,
+ height,
+ faces: faces.map((face) => ({
+ faceID: face.faceId,
+ detection: {
+ box: {
+ x: face.detection.boxXyxy[0]!,
+ y: face.detection.boxXyxy[1]!,
+ width:
+ face.detection.boxXyxy[2]! - face.detection.boxXyxy[0]!,
+ height:
+ face.detection.boxXyxy[3]! - face.detection.boxXyxy[1]!,
+ },
+ landmarks: face.detection.keypoints.map((point) => ({
+ x: point[0]!,
+ y: point[1]!,
+ })),
+ },
+ score: face.detection.score,
+ blur: face.blurValue,
+ embedding: face.embedding,
+ })),
+ };
+};
+
+/**
+ * Extract the CLIP image embedding from an analysis result.
+ *
+ * The embedding produced by the native pipeline is already normalized.
+ */
+const clipIndexFromAnalysisResult = (
+ result: MLWorkerAnalyzeImageResult,
+): CLIPIndex => {
+ const embedding = result.clip?.embedding;
+ if (!embedding)
+ throw new Error("Analysis result is missing the CLIP embedding");
+ return { embedding };
+};