π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Cleanup
Manav Rathi6ad27a2d42d6
diff --git a/desktop/src/main/services/ml-worker.ts b/desktop/src/main/services/ml-worker.tsindex e028dd01d5..379a1b1f4a 100644--- a/desktop/src/main/services/ml-worker.ts+++ b/desktop/src/main/services/ml-worker.ts@@ -15,7 +15,7 @@ import { existsSync } from "fs";import fs from "node:fs/promises";import path from "node:path";import * as ort from "onnxruntime-node";-import { messagePortMainEndpoint } from "../utils/comlink-endpoint";+import { messagePortMainEndpoint } from "../utils/comlink";import { ensure, wait } from "../utils/common";import { writeStream } from "../utils/stream";@@ -54,14 +54,12 @@ const log = {const mainProcess = (method: string, param: unknown) =>process.parentPort.postMessage({ method, p: param });-log.debugString(- `Started ML worker process with args ${process.argv.join(" ")}`,-);+log.debugString(`Started ML worker process`);process.parentPort.once("message", (e) => {+ // Initialize ourselves with the data we got from our parent.parseInitData(e.data);-- const port = ensure(e.ports[0]);+ // Expose anexpose({computeCLIPImageEmbedding,@@ -69,14 +67,8 @@ process.parentPort.once("message", (e) => {detectFaces,computeFaceEmbeddings,},- messagePortMainEndpoint(port),+ messagePortMainEndpoint(ensure(e.ports[0])),);- // port.on("message", (request) => {- // void handleMessageFromRenderer(request.data).then((response) =>- // port.postMessage(response),- // );- // });- // port.start();});/**diff --git a/desktop/src/main/services/ml.ts b/desktop/src/main/services/ml.tsindex 66c699b5d2..05642fc95f 100644--- a/desktop/src/main/services/ml.ts+++ b/desktop/src/main/services/ml.ts@@ -63,6 +63,9 @@ import log from "../log";* worker can directly talk to each other!** Node.js utility process <-> Renderer web worker+ *+ * The RPC protocol is handled using comlink on both ends. The port itself needs+ * to be relayed using `postMessage`.*/export const createMLWorker = (window: BrowserWindow) => {const { port1, port2 } = new MessageChannelMain();diff --git a/desktop/src/main/utils/comlink-endpoint.ts b/desktop/src/main/utils/comlink.tssimilarity index 99%rename from desktop/src/main/utils/comlink-endpoint.tsrename to desktop/src/main/utils/comlink.tsindex 4572837306..d2006e795b 100644--- a/desktop/src/main/utils/comlink-endpoint.ts+++ b/desktop/src/main/utils/comlink.ts@@ -10,7 +10,7 @@ import type { MessagePortMain } from "electron";** It has been modified (somewhat hackily) to be useful with an Electron* MessagePortMain instead of a Node.js worker_thread. Only things that we- * currently need have been made to work as you can see by the abuntant type+ * currently need have been made to work as you can see by the abundant type* casts. Caveat emptor.*/export const messagePortMainEndpoint = (mp: MessagePortMain): Endpoint => {diff --git a/web/packages/base/types/ipc.ts b/web/packages/base/types/ipc.tsindex 4aca8b865d..748490ed58 100644--- a/web/packages/base/types/ipc.ts+++ b/web/packages/base/types/ipc.ts@@ -335,12 +335,15 @@ export interface Electron {// - ML/**- * Create a new ML session.+ * Create a new ML worker.** This creates a new Node.js utility process, and sets things up so that we* can communicate directly with that utility process using a* {@link MessagePort} that gets posted using "createMLWorker/port".*+ * At the other end of that port will be an object that conforms to the+ * {@link ElectronMLWorker} interface.+ ** For more details about the IPC flow, see: [Note: ML IPC].** Note: For simplicity of implementation, we assume that there is at most@@ -535,6 +538,65 @@ export interface Electron {clearPendingUploads: () => Promise<void>;}+/**+ * The shape of the object exposed by the Node.js ML worker process on the+ * message port that the web layer obtains by doing {@link createMLWorker}.+ */+export interface ElectronMLWorker {+ /**+ * Return a CLIP embedding of the given image.+ *+ * See: [Note: Natural language search using CLIP]+ *+ * The input is a opaque float32 array representing the image. The layout+ * and exact encoding of the input is specific to our implementation and the+ * ML model (CLIP) we use.+ *+ * @returns A CLIP embedding (an array of 512 floating point values).+ */+ computeCLIPImageEmbedding: (input: Float32Array) => Promise<Float32Array>;++ /**+ * Return a CLIP embedding of the given image 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+ * for the model download to finish. It does trigger a model download, but+ * then immediately returns `undefined`. At some future point, when the+ * model downloaded finishes, calls to this function will start returning+ * the result we seek.+ *+ * The reason for doing it in this asymmetric way is because CLIP text+ * embeddings are used as part of deducing user initiated search results,+ * and we don't want to block that interaction on a large network request.+ *+ * See: [Note: Natural language search using CLIP]+ *+ * @param text The string whose embedding we want to compute.+ *+ * @returns A CLIP embedding.+ */+ computeCLIPTextEmbeddingIfAvailable: (+ text: string,+ ) => Promise<Float32Array | undefined>;++ /**+ * 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.+ */+ detectFaces: (input: Float32Array) => Promise<Float32Array>;++ /**+ * 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.+ */+ computeFaceEmbeddings: (input: Float32Array) => Promise<Float32Array>;+}+/*** Errors that have special semantics on the web side.*diff --git a/web/packages/new/photos/services/ml/clip.ts b/web/packages/new/photos/services/ml/clip.tsindex eecf7e2209..f6230f2466 100644--- a/web/packages/new/photos/services/ml/clip.ts+++ b/web/packages/new/photos/services/ml/clip.ts@@ -1,9 +1,8 @@-import type { Electron } from "@/base/types/ipc";+import type { Electron, ElectronMLWorker } from "@/base/types/ipc";import type { ImageBitmapAndData } from "./blob";import { clipIndexes } from "./db";import { pixelRGBBicubic } from "./image";import { dotProduct, norm } from "./math";-import type { MLWorkerElectron } from "./worker-types";/*** The version of the CLIP indexing pipeline implemented by the current client.@@ -98,19 +97,19 @@ export type LocalCLIPIndex = CLIPIndex & {* be set to the {@link UploadItem} that was uploaded. This way, we can directly* use the on-disk file instead of needing to download the original from remote.*- * @param electron The {@link MLWorkerElectron} instance that allows us to call+ * @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: MLWorkerElectron,+ electron: ElectronMLWorker,): Promise<CLIPIndex> => ({embedding: await computeEmbedding(image.data, electron),});const computeEmbedding = async (imageData: ImageData,- electron: MLWorkerElectron,+ electron: ElectronMLWorker,): Promise<number[]> => {const clipInput = convertToCLIPInput(imageData);return normalized(await electron.computeCLIPImageEmbedding(clipInput));diff --git a/web/packages/new/photos/services/ml/face.ts b/web/packages/new/photos/services/ml/face.tsindex 910970d3b9..7ecbf06002 100644--- a/web/packages/new/photos/services/ml/face.ts+++ b/web/packages/new/photos/services/ml/face.ts@@ -7,6 +7,7 @@///* eslint-disable @typescript-eslint/no-non-null-assertion */+import type { ElectronMLWorker } from "@/base/types/ipc";import type { EnteFile } from "@/new/photos/types/file";import { Matrix } from "ml-matrix";import { getSimilarityTransformation } from "similarity-transformation";@@ -24,7 +25,6 @@ import {warpAffineFloat32List,} from "./image";import { clamp } from "./math";-import type { MLWorkerElectron } from "./worker-types";/*** The version of the face indexing pipeline implemented by the current client.@@ -236,13 +236,13 @@ export interface Box {** @param image The file's contents.*- * @param electron The {@link MLWorkerElectron} instance that allows us to call+ * @param electron The {@link ElectronMLWorker} instance that allows us to call* our Node.js layer to run the ONNX inference.*/export const indexFaces = async (enteFile: EnteFile,{ data: imageData }: ImageBitmapAndData,- electron: MLWorkerElectron,+ electron: ElectronMLWorker,): Promise<FaceIndex> => ({width: imageData.width,height: imageData.height,@@ -252,7 +252,7 @@ export const indexFaces = async (const indexFaces_ = async (fileID: number,imageData: ImageData,- electron: MLWorkerElectron,+ electron: ElectronMLWorker,): Promise<Face[]> => {const { width, height } = imageData;const imageDimensions = { width, height };@@ -316,7 +316,7 @@ const indexFaces_ = async (*/const detectFaces = async (imageData: ImageData,- electron: MLWorkerElectron,+ electron: ElectronMLWorker,): Promise<YOLOFaceDetection[]> => {const rect = ({ width, height }: Dimensions) => ({x: 0,@@ -878,7 +878,7 @@ const mobileFaceNetEmbeddingSize = 192;*/const computeEmbeddings = async (faceData: Float32Array,- electron: MLWorkerElectron,+ electron: ElectronMLWorker,): Promise<Float32Array[]> => {const outputData = await electron.computeFaceEmbeddings(faceData);diff --git a/web/packages/new/photos/services/ml/worker-rpc.ts b/web/packages/new/photos/services/ml/worker-rpc.tsdeleted file mode 100644index 782c0a3bd3..0000000000--- a/web/packages/new/photos/services/ml/worker-rpc.ts+++ /dev/null@@ -1,131 +0,0 @@-import { z } from "zod";--/**- * The port used to communicate with the Node.js ML worker process- *- * See: [Note: ML IPC]- * */-let _port: MessagePort | undefined;--/**- * Use the given {@link MessagePort} to communicate with the Node.js ML worker- * process.- */-export const startUsingMessagePort = (port: MessagePort) => {- _port = port;- port.start();-};--/**- * Return a CLIP embedding of the given image.- *- * See: [Note: Natural language search using CLIP]- *- * The input is a opaque float32 array representing the image. The layout- * and exact encoding of the input is specific to our implementation and the- * ML model (CLIP) we use.- *- * @returns A CLIP embedding (an array of 512 floating point values).- */-export const computeCLIPImageEmbedding = (- input: Float32Array,-): Promise<Float32Array> =>- ensureFloat32Array(electronMLWorker("computeCLIPImageEmbedding", input));--/**- * Return a CLIP embedding of the given image 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- * for the model download to finish. It does trigger a model download, but- * then immediately returns `undefined`. At some future point, when the- * model downloaded finishes, calls to this function will start returning- * the result we seek.- *- * The reason for doing it in this asymmetric way is because CLIP text- * embeddings are used as part of deducing user initiated search results,- * and we don't want to block that interaction on a large network request.- *- * See: [Note: Natural language search using CLIP]- *- * @param text The string whose embedding we want to compute.- *- * @returns A CLIP embedding.- */-export const computeCLIPTextEmbeddingIfAvailable = async (- text: string,-): Promise<Float32Array | undefined> =>- ensureOptionalFloat32Array(- electronMLWorker("computeCLIPTextEmbeddingIfAvailable", text),- );--/**- * 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.- */-export const detectFaces = (input: Float32Array): Promise<Float32Array> =>- ensureFloat32Array(electronMLWorker("detectFaces", input));--/**- * 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.- */-export const computeFaceEmbeddings = (- input: Float32Array,-): Promise<Float32Array> =>- ensureFloat32Array(electronMLWorker("computeFaceEmbeddings", input));--const ensureFloat32Array = async (- pu: Promise<unknown>,-): Promise<Float32Array> => {- const u = await pu;- if (u instanceof Float32Array) return u;- throw new Error(`Expected a Float32Array but instead got ${typeof u}`);-};--const ensureOptionalFloat32Array = async (- pu: Promise<unknown>,-): Promise<Float32Array | undefined> => {- const u = await pu;- if (u === undefined) return u;- if (u instanceof Float32Array) return u;- throw new Error(`Expected a Float32Array but instead got ${typeof u}`);-};--/**- * Make a call to the ML worker running in the Node.js layer using our- * hand-rolled RPC protocol. See: [Note: Node.js ML worker RPC protocol].- */-const electronMLWorker = async (method: string, p: string | Float32Array) => {- const port = _port;- if (!port) {- throw new Error(- "No MessagePort to communicate with Electron ML worker",- );- }-- // Generate a unique nonce to identify this RPC interaction.- const id = Math.random();- return new Promise((resolve, reject) => {- const handleMessage = (event: MessageEvent) => {- const response = RPCResponse.parse(event.data);- if (response.id != id) return;- port.removeEventListener("message", handleMessage);- const error = response.error;- if (error) reject(new Error(error));- else resolve(response.result);- };- port.addEventListener("message", handleMessage);- port.postMessage({ id, method, p });- });-};--const RPCResponse = z.object({- id: z.number(),- result: z.any().optional(),- error: z.string().optional(),-});diff --git a/web/packages/new/photos/services/ml/worker-types.ts b/web/packages/new/photos/services/ml/worker-types.tsindex 1eb43933a3..a83a215ea4 100644--- a/web/packages/new/photos/services/ml/worker-types.ts+++ b/web/packages/new/photos/services/ml/worker-types.ts@@ -1,22 +1,8 @@/**- * @file Type for the objects shared (as a Comlink proxy) by the main thread and- * the ML worker.+ * @file Types for the objects shared (as a Comlink proxy) by the main thread+ * and the ML worker.*/-/**- * A subset of {@link Electron} provided to the {@link MLWorker}.- *- * `globalThis.electron` does not exist in the execution context of web workers.- * So instead, we manually provide a proxy object of type- * {@link MLWorkerElectron} that exposes a subset of the functions from- * {@link Electron} that are needed by the code running in the ML web worker.- */-export interface MLWorkerElectron {- detectFaces: (input: Float32Array) => Promise<Float32Array>;- computeFaceEmbeddings: (input: Float32Array) => Promise<Float32Array>;- computeCLIPImageEmbedding: (input: Float32Array) => Promise<Float32Array>;-}-/*** Callbacks invoked by the worker at various points in the indexing pipeline to* notify the main thread of events it might be interested in.@@ -25,7 +11,7 @@ export interface MLWorkerDelegate {/*** Called whenever a file is processed during indexing.*- * It is called both when the indexing was successful or failed.+ * It is called both when the indexing was successful or it failed.*/workerDidProcessFile: () => void;}diff --git a/web/packages/new/photos/services/ml/worker.ts b/web/packages/new/photos/services/ml/worker.tsindex d27f3021f4..e137531f6d 100644--- a/web/packages/new/photos/services/ml/worker.ts+++ b/web/packages/new/photos/services/ml/worker.ts@@ -3,6 +3,7 @@ import { isHTTP4xxError } from "@/base/http";import { getKVN } from "@/base/kv";import { ensureAuthToken } from "@/base/local-user";import log from "@/base/log";+import type { ElectronMLWorker } from "@/base/types/ipc";import type { EnteFile } from "@/new/photos/types/file";import { fileLogID } from "@/new/photos/utils/file";import { ensure } from "@/utils/ensure";@@ -32,8 +33,7 @@ import {type RemoteDerivedData,} from "./embedding";import { faceIndexingVersion, indexFaces, type FaceIndex } from "./face";-import { startUsingMessagePort } from "./worker-rpc";-import type { MLWorkerDelegate, MLWorkerElectron } from "./worker-types";+import type { MLWorkerDelegate } from "./worker-types";const idleDurationStart = 5; /* 5 seconds */const idleDurationMax = 16 * 60; /* 16 minutes */@@ -47,11 +47,6 @@ interface IndexableItem {remoteDerivedData: RemoteDerivedData | undefined;}-globalThis.onmessage = (event: MessageEvent) => {- if (event.data == "createMLWorker/port")- startUsingMessagePort(ensure(event.ports[0]));-};-/*** Run operations related to machine learning (e.g. indexing) in a Web Worker.*@@ -75,7 +70,7 @@ globalThis.onmessage = (event: MessageEvent) => {* - "idle": in between state transitions.*/export class MLWorker {- private electron: MLWorkerElectron | undefined;+ private electron: ElectronMLWorker | undefined;private delegate: MLWorkerDelegate | undefined;private state: "idle" | "indexing" = "idle";private liveQ: IndexableItem[] = [];@@ -88,20 +83,16 @@ export class MLWorker {* This is conceptually the constructor, however it is easier to have this* as a separate function to avoid complicating the comlink types further.*- * @param electron The {@link MLWorkerElectron} that allows the worker to- * use the functionality provided by our Node.js layer when running in the- * context of our desktop app.+ * @param port A {@link MessagePort} that allows us to communicate with an+ * Electron utility process running in the Node.js layer of our desktop app,+ * exposing an object that conforms to the {@link ElectronMLWorker}+ * interface.** @param delegate The {@link MLWorkerDelegate} the worker can use to inform* the main thread of interesting events.*/async init(port: MessagePort, delegate: MLWorkerDelegate) {- // this.electron = electron;- this.electron = wrap<MLWorkerElectron>(port); /* mlWorkerElectron = {- detectFaces: electron.detectFaces,- computeFaceEmbeddings: electron.computeFaceEmbeddings,- computeCLIPImageEmbedding: electron.computeCLIPImageEmbedding,- };*/+ this.electron = wrap<ElectronMLWorker>(port);this.delegate = delegate;// Initialize the downloadManager running in the web worker with the// user's token. It'll be used to download files to index if needed.@@ -267,7 +258,7 @@ expose(MLWorker);*/const indexNextBatch = async (items: IndexableItem[],- electron: MLWorkerElectron,+ electron: ElectronMLWorker,delegate: MLWorkerDelegate | undefined,) => {// Don't try to index if we wouldn't be able to upload them anyway. The@@ -385,7 +376,7 @@ const syncWithLocalFilesAndGetFilesToIndex = async (*/const index = async ({ enteFile, uploadItem, remoteDerivedData }: IndexableItem,- electron: MLWorkerElectron,+ electron: ElectronMLWorker,) => {const f = fileLogID(enteFile);const fileID = enteFile.id;