Skip to content

armgit / ente

Public Imported from GitHub
0

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

wip checkpoint

Manav Rathi63138a539a3d
diff --git a/web/packages/new/photos/services/ml/cgroups.ts b/web/packages/new/photos/services/ml/cgroups.ts
index 50002431c0..982fd655e1 100644
--- a/web/packages/new/photos/services/ml/cgroups.ts
+++ b/web/packages/new/photos/services/ml/cgroups.ts
@@ -1,8 +1,11 @@
import { masterKeyFromSession } from "@/base/session-store";
+import { fileIDFromFaceID, wipClusterEnable } from ".";
+import type { EnteFile } from "../../types/file";
+import { getLocalFiles } from "../files";
import { setCGroups } from "../search";
import { pullCGroups } from "../user-entity";
import type { FaceCluster } from "./cluster";
-import { clusterGroups } from "./db";
+import { getClusterGroups, getFaceIndexes } from "./db";
/**
* A cgroup ("cluster group") is a group of clusters (possibly containing just a
@@ -24,8 +27,8 @@ import { clusterGroups } from "./db";
* cluster, or they may hide an named {@link CGroup}. In both cases, we promote
* the cluster to a CGroup if needed so that their request to hide gets synced.
*
+ * The user can see both the cgroups and clusters in the UI, but only the
* cgroups are synced with remote.
- *
*/
export interface CGroup {
/**
@@ -91,55 +94,111 @@ export type AnnotatedCGroup = CGroup & {
};
/**
- * Syncronize the user's cluster groups with remote, running local clustering if
- * needed.
- *
- * A cgroup (cluster group) consists of clusters, each of which itself is a set
- * of faces.
- *
- * cgroup << cluster << face
- *
- * CGroups are synced with remote, while clusters are a local only (though the
- * clusters that are part of a cgroup do get synced with remote).
- *
- * Clusters are generated locally using {@link clusterFaces} function. These
- * generated clusters are then mapped to cgroups based on various user actions:
- *
- * - The user can provide a name for a cluster ("name a person"). This
- * upgrades a cluster into a cgroup, and it then gets synced via remote to
- * the user's other clients.
- *
- * - They can attach more clusters to a cgroup ("merge clusters").
- *
- * - They can remove a cluster from a cgroup ("break clusters").
- *
- * - They can hide a cluster. This creates an unnamed cgroup so that the
- * user's other clients know not to show it.
+ * Fetch existing cgroups for the user from remote and save them to DB.
*/
export const syncCGroups = async () => {
- // 1. Fetch existing cgroups for the user from remote.
- // 2. Save them to DB.
- // 3. Prune stale faceIDs from the clusters in the DB.
- // 4. Rerun clustering using the cgroups and clusters in DB.
- // 5. Save the generated clusters to DB.
- //
- // The user can see both the cgroups and clusters in the UI, but only the
- // cgroups are synced.
+ if (!process.env.NEXT_PUBLIC_ENTE_WIP_CL) return;
+ if (!(await wipClusterEnable())) return;
const masterKey = await masterKeyFromSession();
await pullCGroups(masterKey);
+};
- /*
- * After clustering, we also do some routine cleanup. Faces belonging to files
- * that have been deleted (including those in Trash) should be pruned off.
- *
- * We should not make strict assumptions about the clusters we get from remote.
- * In particular, the same face ID can be in different clusters. In such cases
- * we should assign it arbitrarily assign it to the last cluster we find it in.
- * Such leeway is intentionally provided to allow clients some slack in how they
- * implement the sync without needing to make an blocking API request for every
- * user interaction.
- */
+/**
+ * Construct in-memory "people" from the cgroups present locally.
+ *
+ * This function is meant to run after files, cgroups and faces have been synced
+ * with remote. It then uses all the information in the local DBs to construct
+ * an in-memory list of {@link Person}s on which the UI will operate.
+ */
+export const updatePeople = async () => {
+ if (!process.env.NEXT_PUBLIC_ENTE_WIP_CL) return;
+ if (!(await wipClusterEnable())) return;
+
+ // Ignore faces belonging to deleted (incl Trash) and hidden files.
+ //
+ // More generally, we should not make strict assumptions about the clusters
+ // we get from remote. In particular, the same face ID can be in different
+ // clusters. In such cases we should assign it arbitrarily assign it to the
+ // last cluster we find it in. Such leeway is intentionally provided to
+ // allow clients some slack in how they implement the sync without needing
+ // to make an blocking API request for every user interaction.
+
+ const files = await getLocalFiles("normal");
+ const fileByID = new Map(files.map((f) => [f.id, f]));
+
+ const faceIndexes = await getFaceIndexes();
+ const personFaceByID = new Map<
+ string,
+ { faceID: string; file: EnteFile; score: number }
+ >();
+ for (const { faces } of faceIndexes) {
+ for (const { faceID, score } of faces) {
+ const fileID = fileIDFromFaceID(faceID);
+ if (!fileID) continue;
+ const file = fileByID.get(fileID);
+ if (!file) continue;
+ personFaceByID.set(faceID, { faceID, file, score });
+ }
+ }
+
+ // Convert cgroups to people.
+ const cgroups = await getClusterGroups();
+ const people = cgroups
+ .map((cgroup) => {
+ // Hidden cgroups are clusters specifically marked so as to not be shown
+ // in the UI.
+ if (cgroup.isHidden) return undefined;
+
+ // Unnamed groups are also not shown.
+ const name = cgroup.name;
+ if (!name) return undefined;
+
+ // Person faces from all the clusters assigned to this cgroup, sorted by
+ // their score.
+ const faces = cgroup.assigned
+ .map(({ faces }) =>
+ faces
+ .map((id) => personFaceByID.get(id))
+ .filter((f) => !!f),
+ )
+ .flat()
+ .sort((a, b) => b.score - a.score);
+
+ // Ignore this cgroup if we don't have eligible faces left in it.
+ const highestScoringFace = faces[0];
+ if (!highestScoringFace) return undefined;
+
+ // IDs of the files containing this face.
+ const fileIDs = [...new Set(faces.map((f) => f.file.id))];
+
+ // Avatar face ID, or the highest scoring face.
+ const avatarFaceID = cgroup.avatarFaceID;
+ let avatarFile: EnteFile | undefined;
+ if (avatarFaceID) {
+ const avatarFileID = fileIDFromFaceID(avatarFaceID);
+ if (avatarFileID) {
+ avatarFile = fileByID.get(avatarFileID);
+ }
+ }
+
+ let displayFaceID: string;
+ let displayFaceFile: EnteFile;
+ if (avatarFaceID && avatarFile) {
+ displayFaceID = avatarFaceID;
+ displayFaceFile = avatarFile;
+ } else {
+ displayFaceID = highestScoringFace.faceID;
+ displayFaceFile = highestScoringFace.file;
+ }
+
+ const id = cgroup.id;
+
+ return { id, name, fileIDs, displayFaceID, displayFaceFile };
+ })
+ .filter((c) => !!c);
+
+ // Read all the latest cluster groups, locally present files, local faces
// Re-read the cgroups across which we should search from the local ML DB.
//
@@ -147,5 +206,5 @@ export const syncCGroups = async () => {
// another handle to the DB to be opened (from the search worker's context).
// Making the DB call here avoids that (not that we noticed any issues, but
// preemptively trying not to poke IndexedDB too much lest it be flaky).
- await setCGroups(await clusterGroups());
+ await setCGroups();
};
diff --git a/web/packages/new/photos/services/ml/clip.ts b/web/packages/new/photos/services/ml/clip.ts
index bcea2dca7a..84a33c7964 100644
--- a/web/packages/new/photos/services/ml/clip.ts
+++ b/web/packages/new/photos/services/ml/clip.ts
@@ -1,6 +1,6 @@
import type { ElectronMLWorker } from "@/base/types/ipc";
import type { ImageBitmapAndData } from "./blob";
-import { clipIndexes } from "./db";
+import { getCLIPIndexes } from "./db";
import { pixelRGBBilinear } from "./image";
import { dotProduct, norm } from "./math";
import type { CLIPMatches } from "./worker-types";
@@ -208,7 +208,7 @@ let _cachedCLIPIndexes:
* produces potentially new CLIP indexes).
*/
const cachedOrReadCLIPIndexes = async () =>
- (_cachedCLIPIndexes ??= (await clipIndexes()).map(
+ (_cachedCLIPIndexes ??= (await getCLIPIndexes()).map(
({ fileID, embedding }) => ({
fileID,
embedding: new Float32Array(embedding),
diff --git a/web/packages/new/photos/services/ml/db.ts b/web/packages/new/photos/services/ml/db.ts
index 833bcffbd3..20ecb4436d 100644
--- a/web/packages/new/photos/services/ml/db.ts
+++ b/web/packages/new/photos/services/ml/db.ts
@@ -212,7 +212,7 @@ const newFileStatus = (fileID: number): FileStatus => ({
/**
* Return the {@link FaceIndex}, if any, for {@link fileID}.
*/
-export const faceIndex = async (fileID: number) => {
+export const getFaceIndex = async (fileID: number) => {
const db = await mlDB();
return db.get("face-index", fileID);
};
@@ -220,7 +220,7 @@ export const faceIndex = async (fileID: number) => {
/**
* Return all face indexes present locally.
*/
-export const faceIndexes = async () => {
+export const getFaceIndexes = async () => {
const db = await mlDB();
return await db.getAll("face-index");
};
@@ -228,7 +228,7 @@ export const faceIndexes = async () => {
/**
* Return all CLIP indexes present locally.
*/
-export const clipIndexes = async () => {
+export const getCLIPIndexes = async () => {
const db = await mlDB();
return await db.getAll("clip-index");
};
@@ -329,7 +329,7 @@ export const updateAssumingLocalFiles = async (
* fall within the purview of the indexer will be indexable + indexed (if we are
* ignoring the "failed" ones).
*/
-export const indexableAndIndexedCounts = async () => {
+export const getIndexableAndIndexedCounts = async () => {
const db = await mlDB();
const tx = db.transaction("file-status", "readonly");
const indexableCount = await tx.store
@@ -353,7 +353,7 @@ export const indexableAndIndexedCounts = async () => {
* than {@link count} items present, the files with the higher file IDs (which
* can be taken as a approximate for their creation order) are preferred.
*/
-export const indexableFileIDs = async (count: number) => {
+export const getIndexableFileIDs = async (count: number) => {
const db = await mlDB();
const tx = db.transaction("file-status", "readonly");
let cursor = await tx.store
@@ -392,7 +392,7 @@ export const markIndexingFailed = async (fileID: number) => {
/**
* Return all face clusters present locally.
*/
-export const faceClusters = async () => {
+export const getFaceClusters = async () => {
const db = await mlDB();
return db.getAll("face-cluster");
};
@@ -400,7 +400,7 @@ export const faceClusters = async () => {
/**
* Return all cluster group entries (aka "cgroups") present locally.
*/
-export const clusterGroups = async () => {
+export const getClusterGroups = async () => {
const db = await mlDB();
return db.getAll("cluster-group");
};
@@ -411,6 +411,7 @@ export const clusterGroups = async () => {
* This function deletes all entries from the face cluster object store, and
* then inserts the given {@link clusters} into it.
*/
+// TODO-Cluster
export const setFaceClusters = async (clusters: FaceCluster[]) => {
const db = await mlDB();
const tx = db.transaction("face-cluster", "readwrite");
diff --git a/web/packages/new/photos/services/ml/index.ts b/web/packages/new/photos/services/ml/index.ts
index 9ad329dafe..7427394a3d 100644
--- a/web/packages/new/photos/services/ml/index.ts
+++ b/web/packages/new/photos/services/ml/index.ts
@@ -18,7 +18,7 @@ import { proxy, transfer } from "comlink";
import { isInternalUser } from "../feature-flags";
import { getRemoteFlag, updateRemoteFlag } from "../remote-store";
import type { UploadItem } from "../upload/types";
-import { syncCGroups } from "./cgroups";
+import { syncCGroups, updatePeople } from "./cgroups";
import {
type ClusterFace,
type ClusteringOpts,
@@ -27,7 +27,7 @@ import {
type OnClusteringProgress,
} from "./cluster";
import { regenerateFaceCrops } from "./crop";
-import { clearMLDB, faceIndex, indexableAndIndexedCounts } from "./db";
+import { clearMLDB, getFaceIndex, getIndexableAndIndexedCounts } from "./db";
import { MLWorker } from "./worker";
import type { CLIPMatches } from "./worker-types";
@@ -296,23 +296,18 @@ export const mlStatusSync = async () => {
*
* If ML is enabled, it pulls any missing embeddings from remote and starts
* indexing to backfill any missing values. It also syncs cgroups and updates
- * the search service to use the latest values.
+ * the search service to use the latest values. Finally, it uses the latest
+ * files, faces and cgroups to update the people shown in the UI.
*
* This will only have an effect if {@link mlStatusSync} has been called at
* least once prior to calling this in the sync sequence.
*/
export const mlSync = async () => {
- if (_state.isMLEnabled) {
- await Promise.all([
- // On-device ML, if supported.
- isMLSupported && worker().then((w) => w.sync()),
- // "People".
- process.env.NEXT_PUBLIC_ENTE_WIP_CL &&
- wipClusterEnable().then((enable) =>
- enable ? syncCGroups() : undefined,
- ),
- ]);
- }
+ if (!isMLSupported) return;
+ if (!_state.isMLEnabled) return;
+ await Promise.all([worker().then((w) => w.sync()), syncCGroups()]).then(
+ () => updatePeople(),
+ );
};
/**
@@ -548,7 +543,8 @@ const setMLStatusSnapshot = (snapshot: MLStatus) => {
const getMLStatus = async (): Promise<MLStatus> => {
if (!_state.isMLEnabled) return { phase: "disabled" };
- const { indexedCount, indexableCount } = await indexableAndIndexedCounts();
+ const { indexedCount, indexableCount } =
+ await getIndexableAndIndexedCounts();
// During live uploads, the indexable count remains zero even as the indexer
// is processing the newly uploaded items. This is because these "live
@@ -617,12 +613,18 @@ const workerDidProcessFileOrIdle = throttled(updateMLStatusSnapshot, 2000);
* transmission and storage.
*/
export interface Person {
- /** Unique ID (nanoid) of the underlying {@link CGroup}. */
+ /**
+ * Nanoid of the underlying {@link CGroup}.
+ */
id: string;
- /** The name of the person. */
+ /**
+ * The name of the person.
+ */
name: string;
- /** The files in which this face occurs. */
- files: number[];
+ /**
+ * IDs of the (unique) files in which this face occurs.
+ */
+ fileIDs: number[];
/**
* The face that should be used as the "cover" face to represent this
* {@link Person} in the UI.
@@ -722,7 +724,7 @@ export const clipMatches = (
export const unidentifiedFaceIDs = async (
enteFile: EnteFile,
): Promise<string[]> => {
- const index = await faceIndex(enteFile.id);
+ const index = await getFaceIndex(enteFile.id);
return index?.faces.map((f) => f.faceID) ?? [];
};
@@ -730,7 +732,8 @@ export const unidentifiedFaceIDs = async (
* Extract the fileID of the {@link EnteFile} to which the face belongs from its
* faceID.
*/
-const fileIDFromFaceID = (faceID: string) => {
+// TODO-Cluster
+export const fileIDFromFaceID = (faceID: string) => {
const fileID = parseInt(faceID.split("_")[0] ?? "");
if (isNaN(fileID)) {
assertionFailed(`Ignoring attempt to parse invalid faceID ${faceID}`);
@@ -766,7 +769,7 @@ export const faceCrop = async (faceID: string, enteFile: EnteFile) => {
* the file (updating the "face-crops" {@link BlobCache}).
*/
const regenerateFaceCropsIfNeeded = async (enteFile: EnteFile) => {
- const index = await faceIndex(enteFile.id);
+ const index = await getFaceIndex(enteFile.id);
if (!index) return;
const cache = await blobCache("face-crops");
diff --git a/web/packages/new/photos/services/ml/worker.ts b/web/packages/new/photos/services/ml/worker.ts
index e81714316a..ba097e9054 100644
--- a/web/packages/new/photos/services/ml/worker.ts
+++ b/web/packages/new/photos/services/ml/worker.ts
@@ -32,8 +32,8 @@ import {
} from "./cluster";
import { saveFaceCrops } from "./crop";
import {
- faceIndexes,
- indexableFileIDs,
+ getFaceIndexes,
+ getIndexableFileIDs,
markIndexingFailed,
saveIndexes,
updateAssumingLocalFiles,
@@ -283,7 +283,7 @@ export class MLWorker {
// TODO-Cluster
async clusterFaces(opts: ClusteringOpts, onProgress: OnClusteringProgress) {
return clusterFaces(
- await faceIndexes(),
+ await getFaceIndexes(),
await getAllLocalFiles(),
opts,
onProgress,
@@ -395,7 +395,7 @@ const syncWithLocalFilesAndGetFilesToIndex = async (
localTrashFileIDs,
);
- const fileIDsToIndex = await indexableFileIDs(count);
+ const fileIDsToIndex = await getIndexableFileIDs(count);
return new Map(
fileIDsToIndex.map((id) => [id, ensure(localFileByID.get(id))]),
);