Skip to content

armgit / ente

Public Imported from GitHub
0

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

add model download logic

Abhinavad67236529b4
diff --git a/src/services/clipService.ts b/src/services/clipService.ts
index 45be96fe80..66d09459c3 100644
--- a/src/services/clipService.ts
+++ b/src/services/clipService.ts
@@ -1,12 +1,20 @@
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';
const CLIP_MODEL_PATH_PLACEHOLDER = 'CLIP_MODEL';
const GGMLCLIP_PATH_PLACEHOLDER = 'GGML_PATH';
const INPUT_PATH_PLACEHOLDER = 'INPUT';
+const MODEL_SIZE_IN_BYTES = 303606311; // 289.54 MB
const IMAGE_EMBEDDING_EXTRACT_CMD: string[] = [
GGMLCLIP_PATH_PLACEHOLDER,
@@ -24,8 +32,49 @@ const TEXT_EMBEDDING_EXTRACT_CMD: string[] = [
INPUT_PATH_PLACEHOLDER,
];
-function getClipModelPath() {
- return './models/openai_clip-vit-base-patch32.ggmlv0.f16.bin';
+const GGML_CLIP_MODEL_DOWNLOAD_URL =
+ 'https://models.ente.io/openai_clip-vit-base-patch32.ggmlv0.f16.bin';
+const MODEL_NAME = 'openai_clip-vit-base-patch32.ggmlv0.f16.bin';
+const MODEL_SAVE_FOLDER = 'models';
+
+function getModelSavePath() {
+ let userDataDir: string;
+ if (isDev) {
+ userDataDir = '.';
+ } else {
+ userDataDir = app.getPath('userData');
+ }
+ return path.join(userDataDir, MODEL_SAVE_FOLDER, MODEL_NAME);
+}
+
+async function downloadModel(saveLocation: string) {
+ // confirm that the save location exists
+ const saveDir = path.dirname(saveLocation);
+ if (!existsSync(saveDir)) {
+ log.info('creating model save dir');
+ await fs.mkdir(saveDir, { recursive: true });
+ }
+ log.info('downloading clip model');
+ const resp = await fetch(GGML_CLIP_MODEL_DOWNLOAD_URL);
+ await writeNodeStream(saveLocation, resp.body, true);
+ log.info('clip model downloaded');
+}
+
+export async function getClipModelPath() {
+ const modelSavePath = getModelSavePath();
+ log.info('clip model save path', modelSavePath);
+ if (!existsSync(modelSavePath)) {
+ await downloadModel(modelSavePath);
+ } else {
+ const localFileSize = (await fs.stat(modelSavePath)).size;
+ if (localFileSize !== MODEL_SIZE_IN_BYTES) {
+ log.info('clip model size mismatch, downloading again');
+ await downloadModel(modelSavePath);
+ } else {
+ log.info('clip model already downloaded');
+ }
+ }
+ return modelSavePath;
}
function getGGMLClipPath() {
diff --git a/src/services/fs.ts b/src/services/fs.ts
index b380428c4c..a2ac7914a4 100644
--- a/src/services/fs.ts
+++ b/src/services/fs.ts
@@ -6,6 +6,8 @@ import StreamZip from 'node-stream-zip';
import { Readable } from 'stream';
import { logError } from './logging';
import { existsSync } from 'fs';
+import { log } from 'console';
+import { convertBytesToHumanReadable } from '../utils/logging';
// https://stackoverflow.com/a/63111390
export const getDirFilePaths = async (dirPath: string) => {
@@ -226,18 +228,26 @@ export const convertBrowserStreamToNode = (
return rs;
};
-export async function writeStream(
+export async function writeNodeStream(
filePath: string,
- fileStream: ReadableStream<Uint8Array>
+ fileStream: NodeJS.ReadableStream,
+ enableLogging = false
) {
const writeable = fs.createWriteStream(filePath);
- const readable = convertBrowserStreamToNode(fileStream);
- readable.on('error', (error) => {
+ fileStream.on('error', (error) => {
writeable.destroy(error); // Close the writable stream with an error
});
- readable.pipe(writeable);
+ fileStream.pipe(writeable);
+
+ let downloaded = 0;
+ if (enableLogging) {
+ fileStream.on('data', (chunk) => {
+ downloaded += chunk.length;
+ log(`Received ${convertBytesToHumanReadable(downloaded)} of data.`);
+ });
+ }
await new Promise((resolve, reject) => {
writeable.on('finish', resolve);
@@ -250,6 +260,14 @@ export async function writeStream(
});
}
+export async function writeStream(
+ filePath: string,
+ fileStream: ReadableStream<Uint8Array>
+) {
+ const readable = convertBrowserStreamToNode(fileStream);
+ await writeNodeStream(filePath, readable);
+}
+
export async function readTextFile(filePath: string) {
if (!existsSync(filePath)) {
throw new Error('File does not exist');
diff --git a/src/utils/logging.ts b/src/utils/logging.ts
index 664dea1d50..5924224eba 100644
--- a/src/utils/logging.ts
+++ b/src/utils/logging.ts
@@ -23,3 +23,16 @@ export function makeID(length: number) {
}
return result;
}
+
+export function convertBytesToHumanReadable(
+ bytes: number,
+ precision = 2
+): string {
+ if (bytes === 0 || isNaN(bytes)) {
+ return '0 MB';
+ }
+
+ const i = Math.floor(Math.log(bytes) / Math.log(1024));
+ const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
+ return (bytes / Math.pow(1024, i)).toFixed(precision) + ' ' + sizes[i];
+}
diff --git a/src/utils/processStats.ts b/src/utils/processStats.ts
index 00b3a71d1e..8bb61c262e 100644
--- a/src/utils/processStats.ts
+++ b/src/utils/processStats.ts
@@ -1,5 +1,6 @@
import ElectronLog from 'electron-log';
import { webFrame } from 'electron/renderer';
+import { convertBytesToHumanReadable } from './logging';
const LOGGING_INTERVAL_IN_MICROSECONDS = 30 * 1000; // 30 seconds
@@ -292,13 +293,3 @@ const getNormalizedWebFrameResourceUsage = () => {
},
};
};
-
-function convertBytesToHumanReadable(bytes: number, precision = 2): string {
- if (bytes === 0 || isNaN(bytes)) {
- return '0 MB';
- }
-
- const i = Math.floor(Math.log(bytes) / Math.log(1024));
- const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
- return (bytes / Math.pow(1024, i)).toFixed(precision) + ' ' + sizes[i];
-}