π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Desktop runner for ML indexing tests
laurenspriem9dcff3b13323
diff --git a/desktop/scripts/ml_parity_host.js b/desktop/scripts/ml_parity_host.jsnew file mode 100755index 0000000000..631b1a0833--- /dev/null+++ b/desktop/scripts/ml_parity_host.js@@ -0,0 +1,433 @@+#!/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 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(`${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 `yarn --cwd desktop tsc` first.",+ );+ }+ try {+ await fs.access(COMPILED_IMAGE_SERVICE_PATH);+ } catch {+ throw new Error(+ "Compiled desktop image service not found. Run `yarn --cwd desktop tsc` 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.tsnew file mode 100755index 0000000000..534620030f--- /dev/null+++ b/desktop/scripts/ml_parity_runner.ts@@ -0,0 +1,690 @@+#!/usr/bin/env node++import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";+import crypto from "node:crypto";+import { createReadStream } from "node:fs";+import fs from "node:fs/promises";+import { once } from "node:events";+import path from "node:path";+import process from "node:process";+import { performance } from "node:perf_hooks";+import readline from "node:readline";+import { fileURLToPath } from "node:url";++import { indexCLIP } from "../../web/packages/new/photos/services/ml/clip.ts";+import { createImageBitmapAndData } from "../../web/packages/new/photos/services/ml/decode.ts";+import { indexFaces } from "../../web/packages/new/photos/services/ml/face.ts";++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?: string;+}++interface PendingRequest {+ resolve: (value: unknown) => void;+ reject: (reason: unknown) => void;+}++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");++const DEFAULT_MANIFEST_PATH = path.join(+ REPO_ROOT,+ "infra",+ "ml",+ "ground_truth",+ "manifest.json",+);++const DEFAULT_OUTPUT_DIR = path.join(REPO_ROOT, "infra", "ml", "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", ".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 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/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;+};++class HostClient {+ private readonly process: ChildProcessWithoutNullStreams;+ private readonly rl: readline.Interface;+ private nextID = 1;+ private readonly pending = new Map<number, PendingRequest>();+ private closed = false;++ constructor(+ electronBinPath: string,+ hostScriptPath: string,+ userDataPath: string,+ ) {+ 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) => {+ if (!line.trim()) {+ return;+ }+ let message: HostResponse;+ try {+ message = JSON.parse(line) 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: ${message.error ?? "unknown error"}\n`,+ );+ }+ return;+ }++ const pending = this.pending.get(message.id);+ if (!pending) {+ return;+ }+ this.pending.delete(message.id);++ if (message.ok) {+ pending.resolve(message.result);+ } else {+ pending.reject(new Error(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()) {+ 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) => {+ this.pending.set(id, { resolve, reject });+ });++ await this.writeRequest({ id, method, params });+ 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 productionDecodeHelperSource = () => {+ 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 host = new HostClient(args.electronBinPath, args.hostScriptPath, args.userDataPath);+ await host.setDecodeHelperSource(productionDecodeHelperSource());++ // `renderableImageBlob` checks these static build-time flags in shared web code.+ (globalThis as { electron?: { convertToJPEG: (imageData: Uint8Array) => Promise<Uint8Array> } }).electron =+ {+ convertToJPEG: (imageData: Uint8Array) => host.convertToJPEG(imageData),+ };++ const { renderableImageBlob } = await import(+ "../../web/packages/gallery/services/convert.ts"+ );++ 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>;+ }> = [];++ try {+ for (let i = 0; i < items.length; i += 1) {+ const item = items[i]!;+ 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 totalStart = performance.now();++ const decodeStart = performance.now();+ const sourceBlob = new Blob([await fs.readFile(sourcePath)]);+ const renderableBlob = await 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 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 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,+ },+ });+ }++ 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,+ },+ null,+ 2,+ )}\n`,+ );++ process.stdout.write(+ `Generated ${finalResults.length} desktop parity result(s) at ${args.outputDir}\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/infra/ml/ml-indexing-parity-test-plan.md b/infra/ml/ml-indexing-parity-test-plan.mdindex 6c5d779a13..7feb25de9e 100644--- a/infra/ml/ml-indexing-parity-test-plan.md+++ b/infra/ml/ml-indexing-parity-test-plan.md@@ -87,7 +87,7 @@ This section is for implementation agents to keep a running log so handoffs stay- [x] W1: Define shared output schema (`file_id`, clip vector, detections, face embeddings, metadata)- [x] W2: Implement Python ground truth pipeline (`clip.py`, `face_detection.py`, `face_alignment.py`, `face_embedding.py`, `pipeline.py`)- [x] W3: Add/define corpus manifest and storage layout under `infra/ml/ground_truth`-- [ ] W4: Implement desktop parity runner+- [x] W4: Implement desktop parity runner- [ ] W5: Implement Android parity runner- [ ] W6: Implement iOS parity runner- [x] W7: Implement comparator and report generator@@ -102,6 +102,8 @@ This section is for implementation agents to keep a running log so handoffs stay| 2026-02-16 | Codex (GPT-5) | Switched bootstrap corpus source to the canonical fixtures dataset (`ente-io/test-fixtures/ml/indexing/v1`), expanded manifest entries, and updated bootstrap generator to load remote fixture URLs with local cache and SHA-256 verification. | `infra/ml/ground_truth/manifest.json`, `infra/ml/tools/generate_goldens.py`, `infra/ml/ground_truth/README.md`, `infra/ml/ml-indexing-parity-test-plan.md`, `infra/ml/.gitignore` | `uv run --project infra/ml --no-sync python infra/ml/tools/generate_goldens.py --manifest infra/ml/ground_truth/manifest.json --output-dir infra/ml/ground_truth/goldens`; `uv run --project infra/ml --no-sync --with pytest pytest infra/ml/tests/test_schema.py infra/ml/tests/test_comparator.py`; `infra/ml/tools/run_suite.sh --suite smoke --platforms all --output-dir infra/ml/out/parity` | Keep using bootstrap outputs for parity harness bring-up until ONNX-backed Python pipeline modules land (W2). || 2026-02-16 | Codex (GPT-5) | Switched parity artifact policy to runtime-only outputs: removed checked-in per-file/result JSON artifacts and documented gitignored fixture-data + platform output directories generated by `run_suite.sh`. | `infra/ml/ground_truth/goldens/*.json`, `infra/ml/.gitignore`, `infra/ml/ml-indexing-parity-test-plan.md`, `infra/ml/tools/run_suite.sh`, `infra/ml/tools/generate_goldens.py`, `infra/ml/ground_truth/manifest.json` | `git status --short`; `ls infra/ml/ground_truth/goldens`; `infra/ml/tools/run_suite.sh --suite smoke --platforms all --output-dir infra/ml/out/parity` | Implement W4/W5/W6 runners to emit runtime output JSONs into `infra/ml/out/parity/<platform>/`. || 2026-02-16 | Codex (GPT-5) | Implemented W2 real ONNX-backed Python ground-truth pipeline with trusted library primitives: Pillow (+HEIF plugin) decode/orientation, OpenCV resize/warp/NMS, ONNX Runtime inference for CLIP + YOLOv5Face + MobileFaceNet, and integrated `generate_goldens.py` to emit schema outputs from live inference. | `infra/ml/ground_truth/_runtime.py`, `infra/ml/ground_truth/clip.py`, `infra/ml/ground_truth/face_detection.py`, `infra/ml/ground_truth/face_alignment.py`, `infra/ml/ground_truth/face_embedding.py`, `infra/ml/ground_truth/pipeline.py`, `infra/ml/tools/generate_goldens.py`, `infra/ml/tools/run_suite.sh`, `infra/ml/ground_truth/README.md`, `infra/ml/pyproject.toml`, `infra/ml/uv.lock`, `infra/ml/ml-indexing-parity-test-plan.md` | `uv run --project infra/ml --no-sync --with pillow-heif python infra/ml/tools/generate_goldens.py --manifest infra/ml/ground_truth/manifest.json --output-dir infra/ml/out/parity/python`; `uv run --project infra/ml --no-sync --with pytest pytest infra/ml/tests/test_schema.py infra/ml/tests/test_comparator.py`; `infra/ml/tools/run_suite.sh --suite smoke --platforms all --allow-empty-comparison --output-dir infra/ml/out/parity` | Implement W4 desktop parity runner next, then wire W5/W6 mobile runners into `run_suite.sh`. |+| 2026-02-16 | Codex (GPT-5) | Implemented W4 desktop parity runner using production desktop ML runtime paths: added Electron host that drives the compiled `ml-worker` utility process for ONNX inference/model downloads, added desktop parity runner that invokes web `indexFaces`/`indexCLIP` logic and emits shared-schema outputs, and wired `run_suite.sh` to compile desktop sources and run desktop parity generation when dependencies are present. | `desktop/scripts/ml_parity_host.js`, `desktop/scripts/ml_parity_runner.ts`, `infra/ml/tools/run_suite.sh`, `infra/ml/ml-indexing-parity-test-plan.md` | `bash -n infra/ml/tools/run_suite.sh`; `node --check desktop/scripts/ml_parity_host.js`; `node --experimental-strip-types --check desktop/scripts/ml_parity_runner.ts`; `uv run --project infra/ml --no-sync --with pytest pytest infra/ml/tests/test_schema.py infra/ml/tests/test_comparator.py`; `infra/ml/tools/run_suite.sh --suite smoke --platforms desktop --allow-empty-comparison --output-dir /tmp/ml_parity_desktop_smoke` | Implement W5/W6 mobile parity runners and then mark W8 complete once all platform runners are fully orchestrated by `run_suite.sh`. |+| 2026-02-16 | Codex (GPT-5) | Hardened desktop decode parity to use the exact production decode helper source: extracted `createImageBitmapAndData` into shared web ML module, reused by production via `blob.ts`, and injected that exact function source into the parity host renderer decode path. | `web/packages/new/photos/services/ml/decode.ts`, `web/packages/new/photos/services/ml/blob.ts`, `desktop/scripts/ml_parity_host.js`, `desktop/scripts/ml_parity_runner.ts`, `infra/ml/tools/run_suite.sh`, `infra/ml/ml-indexing-parity-test-plan.md` | `node --check desktop/scripts/ml_parity_host.js`; `node --experimental-strip-types --check desktop/scripts/ml_parity_runner.ts`; `node --experimental-strip-types --check web/packages/new/photos/services/ml/decode.ts`; `bash -n infra/ml/tools/run_suite.sh`; `uv run --project infra/ml --no-sync --with pytest pytest infra/ml/tests/test_schema.py infra/ml/tests/test_comparator.py`; `infra/ml/tools/run_suite.sh --suite smoke --platforms desktop --allow-empty-comparison --output-dir /tmp/ml_parity_desktop_smoke` | Run full desktop parity locally once `desktop/node_modules` + `web/node_modules` are installed, then proceed with W5/W6. |### Decisions and Rationale Log| Date | Decision | Rationale | Impacted Files |@@ -111,11 +113,13 @@ This section is for implementation agents to keep a running log so handoffs stay| 2026-02-16 | Point default parity corpus to `ente-io/test-fixtures/ml/indexing/v1` and verify each fixture by SHA-256 during bootstrap generation. | Aligns suite inputs with the dedicated maintained fixture set while preserving deterministic generation and reducing local corpus drift risk. | `infra/ml/ground_truth/manifest.json`, `infra/ml/tools/generate_goldens.py`, `infra/ml/ground_truth/README.md` || 2026-02-16 | Keep all parity outputs ephemeral (gitignored), generated fresh on each suite run. | Avoids stale checked-in artifacts and ensures every comparison is based on current runner outputs over the same fixture set. | `infra/ml/.gitignore`, `infra/ml/ground_truth/goldens/`, `infra/ml/tools/run_suite.sh` || 2026-02-16 | Implement Python ground truth using trusted library primitives (Pillow/OpenCV/ORT), avoiding handwritten interpolation and NMS logic. | Keeps the reference pipeline easier to audit and maintain while still mirroring the mobile `analyzeImageStatic` flow and model behavior. | `infra/ml/ground_truth/_runtime.py`, `infra/ml/ground_truth/clip.py`, `infra/ml/ground_truth/face_detection.py`, `infra/ml/ground_truth/face_alignment.py`, `infra/ml/ground_truth/face_embedding.py`, `infra/ml/ground_truth/pipeline.py` |+| 2026-02-16 | Desktop runner orchestration is dependency-aware and non-fatal by default when desktop/web node installs are absent. | Preserves one-command suite usability in Python-only environments while still auto-running real desktop parity when prerequisites exist; strict mode can still fail on missing outputs. | `infra/ml/tools/run_suite.sh`, `desktop/scripts/ml_parity_runner.ts`, `desktop/scripts/ml_parity_host.js` |+| 2026-02-16 | Desktop parity decode must use the same conversion+bitmap decode path as production (`renderableImageBlob` then `createImageBitmapAndData` semantics), sourced from one shared implementation. | Decode differences can hide regressions in orientation/format handling; parity coverage is only trustworthy if decode semantics match production and stay coupled as code evolves. | `web/packages/new/photos/services/ml/decode.ts`, `web/packages/new/photos/services/ml/blob.ts`, `desktop/scripts/ml_parity_host.js`, `desktop/scripts/ml_parity_runner.ts`, `infra/ml/tools/run_suite.sh` |### Open Questions / Blockers| Date | Owner | Blocker | Unblocked By ||---|---|---|---|-| 2026-02-13 | Codex (GPT-5) | Platform runners are not yet implemented (`desktop/scripts/ml_parity_runner.ts`, mobile integration parity tests), so `run_suite.sh` currently consumes platform outputs only when available. | Implement W4/W5/W6 runner outputs in shared schema and invoke them directly from `run_suite.sh`. |+| 2026-02-16 | Codex (GPT-5) | Mobile platform runners are still missing (`mobile/apps/photos/integration_test/ml_parity_android_test.dart`, `mobile/apps/photos/integration_test/ml_parity_ios_test.dart`), so parity compare can still run with desktop/python only. | Implement W5/W6 and wire both runners into `run_suite.sh` with shared-schema outputs. |### Handoff Checklist- [x] Added brief implementation note to `Implementation Log`diff --git a/infra/ml/tools/run_suite.sh b/infra/ml/tools/run_suite.shindex 5a9a9cd3df..ca684dc0bf 100755--- a/infra/ml/tools/run_suite.sh+++ b/infra/ml/tools/run_suite.sh@@ -166,6 +166,95 @@ for platform in "${selected_platforms[@]}"; domkdir -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"++ if [[ ! -f "$runner_path" ]]; then+ echo "Desktop parity runner not found at $runner_path; skipping desktop run."+ return 2+ fi++ if [[ ! -d "$desktop_dir/node_modules" ]]; then+ echo "Desktop dependencies are missing ($desktop_dir/node_modules); skipping desktop run."+ return 2+ fi++ if [[ ! -d "$web_dir/node_modules" ]]; then+ echo "Web dependencies are missing ($web_dir/node_modules); skipping desktop run."+ return 2+ fi++ if ! command -v npx >/dev/null 2>&1; then+ echo "npx is required to run the desktop parity runner; skipping desktop run."+ return 2+ fi++ echo "Compiling desktop TypeScript sources"+ if ! yarn --cwd "$desktop_dir" 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_platform_runner() {+ local platform="$1"+ case "$platform" in+ desktop)+ run_desktop_runner+ ;;+ android)+ echo "Android parity runner is not implemented yet; skipping android run."+ return 2+ ;;+ ios)+ echo "iOS parity runner is not implemented yet; skipping ios run."+ return 2+ ;;+ *)+ echo "Unknown platform: $platform" >&2+ return 1+ ;;+ esac+}++for platform in "${selected_platforms[@]}"; do+ set +e+ run_platform_runner "$platform"+ platform_run_exit=$?+ set -e++ case "$platform_run_exit" in+ 0)+ echo "Platform runner completed for $platform."+ ;;+ 1)+ echo "Platform runner failed for $platform."+ ;;+ 2)+ echo "Platform runner unavailable for $platform."+ ;;+ *)+ echo "Platform runner returned unexpected exit code $platform_run_exit for $platform."+ ;;+ esac+done+declare -a compare_args=()missing_platform_count=0@@ -173,7 +262,7 @@ for platform in "${selected_platforms[@]}"; doplatform_output="$OUTPUT_DIR/$platform/results.json"if [[ -f "$platform_output" ]]; thencompare_args+=(--platform-result "$platform=$platform_output")- echo "Using existing $platform output: $platform_output"+ echo "Using $platform output: $platform_output"elseecho "Platform output unavailable for $platform at $platform_output"missing_platform_count=$((missing_platform_count + 1))diff --git a/web/packages/new/photos/services/ml/blob.ts b/web/packages/new/photos/services/ml/blob.tsindex 5676008456..01d884b472 100644--- a/web/packages/new/photos/services/ml/blob.ts+++ b/web/packages/new/photos/services/ml/blob.ts@@ -12,48 +12,8 @@ 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";--/**- * 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}.- */-export const createImageBitmapAndData = async (- imageBlob: Blob,-): Promise<ImageBitmapAndData> => {- 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 };-};+export { createImageBitmapAndData } from "./decode";+export type { ImageBitmapAndData } from "./decode";/*** Return a renderable blob (converting to JPEG if needed) for the given data.diff --git a/web/packages/new/photos/services/ml/decode.ts b/web/packages/new/photos/services/ml/decode.tsnew file mode 100644index 0000000000..66844b01dc--- /dev/null+++ b/web/packages/new/photos/services/ml/decode.ts@@ -0,0 +1,41 @@+/**+ * 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}.+ */+export const createImageBitmapAndData = async (+ imageBlob: Blob,+): Promise<ImageBitmapAndData> => {+ 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 };+};