π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
update to use onnx runtime for clip
Abhinav20cb666e90a9
diff --git a/src/services/clipService.ts b/src/services/clipService.tsindex e7aa3865fe..7721cf8b4d 100644--- a/src/services/clipService.ts+++ b/src/services/clipService.ts@@ -1,48 +1,27 @@import * as log from 'electron-log';-import util from 'util';import { logErrorSentry } from './sentry';import { isDev } from '../utils/common';import { app } from 'electron';import path from 'path';import { existsSync } from 'fs';import fs from 'fs/promises';-const shellescape = require('any-shell-escape');-const execAsync = util.promisify(require('child_process').exec);import fetch from 'node-fetch';import { writeNodeStream } from './fs';-import { getPlatform } from '../utils/common/platform';import { CustomErrors } from '../constants/errors';--const CLIP_MODEL_PATH_PLACEHOLDER = 'CLIP_MODEL';-const GGMLCLIP_PATH_PLACEHOLDER = 'GGML_PATH';-const INPUT_PATH_PLACEHOLDER = 'INPUT';--const IMAGE_EMBEDDING_EXTRACT_CMD: string[] = [- GGMLCLIP_PATH_PLACEHOLDER,- '-mv',- CLIP_MODEL_PATH_PLACEHOLDER,- '--image',- INPUT_PATH_PLACEHOLDER,-];--const TEXT_EMBEDDING_EXTRACT_CMD: string[] = [- GGMLCLIP_PATH_PLACEHOLDER,- '-mt',- CLIP_MODEL_PATH_PLACEHOLDER,- '--text',- INPUT_PATH_PLACEHOLDER,-];+import { readFile } from 'promise-fs';+const ort = require('onnxruntime-node');+const { encode } = require('gpt-3-encoder');const TEXT_MODEL_DOWNLOAD_URL =- 'https://models.ente.io/clip-vit-base-patch32_ggml-text-model-f16.gguf';+ 'https://huggingface.co/rocca/openai-clip-js/resolve/main/clip-text-vit-32-float32-int32.onnx';const IMAGE_MODEL_DOWNLOAD_URL =- 'https://models.ente.io/clip-vit-base-patch32_ggml-vision-model-f16.gguf';+ 'https://huggingface.co/rocca/openai-clip-js/resolve/main/clip-image-vit-32-float32.onnx';-const TEXT_MODEL_NAME = 'clip-vit-base-patch32_ggml-text-model-f16.gguf';-const IMAGE_MODEL_NAME = 'clip-vit-base-patch32_ggml-vision-model-f16.gguf';+const TEXT_MODEL_NAME = 'clip-text-vit-32-float32-int32.onnx';+const IMAGE_MODEL_NAME = 'clip-image-vit-32-float32.onnx';-const IMAGE_MODEL_SIZE_IN_BYTES = 175957504; // 167.8 MB-const TEXT_MODEL_SIZE_IN_BYTES = 127853440; // 121.9 MB+const IMAGE_MODEL_SIZE_IN_BYTES = 351468764; // 335.2 MB+const TEXT_MODEL_SIZE_IN_BYTES = 254069585; // 242.3 MBconst MODEL_SAVE_FOLDER = 'models';function getModelSavePath(modelName: string) {@@ -87,7 +66,10 @@ export async function getClipImageModelPath() {} else {const localFileSize = (await fs.stat(modelSavePath)).size;if (localFileSize !== IMAGE_MODEL_SIZE_IN_BYTES) {- log.info('clip model size mismatch, downloading again');+ log.info(+ 'clip image model size mismatch, downloading again got:',+ localFileSize+ );imageModelDownloadInProgress = downloadModel(modelSavePath,IMAGE_MODEL_DOWNLOAD_URL@@ -123,7 +105,10 @@ export async function getClipTextModelPath() {} else {const localFileSize = (await fs.stat(modelSavePath)).size;if (localFileSize !== TEXT_MODEL_SIZE_IN_BYTES) {- log.info('clip model size mismatch, downloading again');+ log.info(+ 'clip text model size mismatch, downloading again',+ localFileSize+ );textModelDownloadInProgress = true;downloadModel(modelSavePath, TEXT_MODEL_DOWNLOAD_URL).catch(() => {@@ -139,42 +124,43 @@ export async function getClipTextModelPath() {return modelSavePath;}-function getGGMLClipPath() {- return isDev- ? path.join('./build', `ggmlclip-${getPlatform()}`)- : path.join(process.resourcesPath, `ggmlclip-${getPlatform()}`);+async function createOnnxSession(modelPath: string) {+ return await ort.InferenceSession.create(modelPath, {+ intraOpNumThreads: 1,+ enableCpuMemArena: false,+ });+}++let onnxImageSession: any = null;++async function getOnnxImageSession() {+ if (!onnxImageSession) {+ const clipModelPath = await getClipImageModelPath();+ onnxImageSession = createOnnxSession(clipModelPath);+ }+ return onnxImageSession;+}++let onnxTextSession: any = null;++async function getOnnxTextSession() {+ if (!onnxTextSession) {+ const clipModelPath = await getClipTextModelPath();+ onnxTextSession = createOnnxSession(clipModelPath);+ }+ return onnxTextSession;}export async function computeImageEmbedding(inputFilePath: string): Promise<Float32Array> {try {- const clipModelPath = await getClipImageModelPath();- const ggmlclipPath = getGGMLClipPath();- const cmd = IMAGE_EMBEDDING_EXTRACT_CMD.map((cmdPart) => {- if (cmdPart === GGMLCLIP_PATH_PLACEHOLDER) {- return ggmlclipPath;- } else if (cmdPart === CLIP_MODEL_PATH_PLACEHOLDER) {- return clipModelPath;- } else if (cmdPart === INPUT_PATH_PLACEHOLDER) {- return inputFilePath;- } else {- return cmdPart;- }- });-- const escapedCmd = shellescape(cmd);- log.info('running clip command', escapedCmd);- const startTime = Date.now();- const { stdout } = await execAsync(escapedCmd);- log.info('clip command execution time ', Date.now() - startTime);- // parse stdout and return embedding- // get the last line of stdout- const lines = stdout.split('\n');- const lastLine = lines[lines.length - 1];- const embedding = JSON.parse(lastLine);- const embeddingArray = new Float32Array(embedding);- return embeddingArray;+ const imageSession = await getOnnxImageSession();+ const inputDataBuffer = await readFile(inputFilePath);++ console.log('imageSession', imageSession);+ console.log('inputDataBuffer.length', inputDataBuffer.length);+ return new Float32Array();} catch (err) {logErrorSentry(err, 'Error in computeImageEmbedding');throw err;@@ -185,32 +171,14 @@ export async function computeTextEmbedding(text: string): Promise<Float32Array> {try {- const clipModelPath = await getClipTextModelPath();- const ggmlclipPath = getGGMLClipPath();- const cmd = TEXT_EMBEDDING_EXTRACT_CMD.map((cmdPart) => {- if (cmdPart === GGMLCLIP_PATH_PLACEHOLDER) {- return ggmlclipPath;- } else if (cmdPart === CLIP_MODEL_PATH_PLACEHOLDER) {- return clipModelPath;- } else if (cmdPart === INPUT_PATH_PLACEHOLDER) {- return text;- } else {- return cmdPart;- }- });-- const escapedCmd = shellescape(cmd);- log.info('running clip command', escapedCmd);- const startTime = Date.now();- const { stdout } = await execAsync(escapedCmd);- log.info('clip command execution time ', Date.now() - startTime);- // parse stdout and return embedding- // get the last line of stdout- const lines = stdout.split('\n');- const lastLine = lines[lines.length - 1];- const embedding = JSON.parse(lastLine);- const embeddingArray = new Float32Array(embedding);- return embeddingArray;+ const imageSession = await getOnnxTextSession();+ const tokenizedText = Int32Array.from(encode(text));+ const feeds = {+ input: new ort.Tensor('int32', tokenizedText, [1, 77]),+ };+ const results = await imageSession.run(feeds);+ console.log('result', results);+ return new Float32Array();} catch (err) {if (err.message === CustomErrors.MODEL_DOWNLOAD_PENDING) {log.info(CustomErrors.MODEL_DOWNLOAD_PENDING);