Skip to content

armgit / ente

Public Imported from GitHub
0

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

Cleanup

Manav Rathice045fb6800e
diff --git a/web/packages/new/photos/services/ml/crop.ts b/web/packages/new/photos/services/ml/crop.ts
index d08ed77f13..12a83904e8 100644
--- a/web/packages/new/photos/services/ml/crop.ts
+++ b/web/packages/new/photos/services/ml/crop.ts
@@ -1,6 +1,6 @@
import { blobCache } from "@/next/blob-cache";
import { ensure } from "@/utils/ensure";
-import { type Box, type FaceAlignment, type FaceIndex } from "./face";
+import { type Box, type FaceIndex } from "./face";
import { clamp } from "./image";
/**
@@ -21,106 +21,13 @@ export const saveFaceCrops = async (
) => {
const cache = await blobCache("face-crops");
- const faces = faceIndex.faceEmbedding.faces;
- const blobs = await generateFaceThumbnailsUsingCanvas(
- imageBitmap,
- faces.map(({ detection }) => detection.box),
- );
- for (let i = 0; i < faces.length; i++) {
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
- await cache.put(faces[i]!.faceID, blobs[i]!);
- }
- /*
return Promise.all(
faceIndex.faceEmbedding.faces.map(({ faceID, detection }) =>
- // extractFaceCrop2(imageBitmap, detection.box).then((b) =>
- // extractFaceCrop(
- // imageBitmap,
- // computeFaceAlignment(
- // restoreToImageDimensions(detection, imageBitmap),
- // ),
- // ).then((b) => cache.put(faceID, b)),
-
- ),
- );
- */
-};
-
-const generateFaceThumbnailsUsingCanvas = async (
- imageBitmap: ImageBitmap,
- faceBoxes: Box[],
-) => {
- const img = imageBitmap;
-
- const futureFaceThumbnails: Promise<Blob>[] = [];
- for (const faceBox of faceBoxes) {
- // Note that the faceBox values are relative to the image size, so we need to convert them to absolute values first
- const xMinAbs = faceBox.x * img.width;
- const yMinAbs = faceBox.y * img.height;
- const widthAbs = faceBox.width * img.width;
- const heightAbs = faceBox.height * img.height;
-
- // Calculate the crop values by adding some padding around the face and making sure it's centered
- const regularPadding = 0.4;
- const minimumPadding = 0.1;
- const xCrop = xMinAbs - widthAbs * regularPadding;
- const xOvershoot = Math.abs(Math.min(0, xCrop)) / widthAbs;
- const widthCrop =
- widthAbs * (1 + 2 * regularPadding) -
- 2 *
- Math.min(xOvershoot, regularPadding - minimumPadding) *
- widthAbs;
- const yCrop = yMinAbs - heightAbs * regularPadding;
- const yOvershoot = Math.abs(Math.min(0, yCrop)) / heightAbs;
- const heightCrop =
- heightAbs * (1 + 2 * regularPadding) -
- 2 *
- Math.min(yOvershoot, regularPadding - minimumPadding) *
- heightAbs;
-
- // Prevent the face from going out of image bounds
- const xCropSafe = clamp(xCrop, 0, img.width);
- const yCropSafe = clamp(yCrop, 0, img.height);
- const widthCropSafe = clamp(widthCrop, 0, img.width - xCropSafe);
- const heightCropSafe = clamp(heightCrop, 0, img.height - yCropSafe);
-
- futureFaceThumbnails.push(
- _cropAndEncodeCanvas(
- img,
- xCropSafe,
- yCropSafe,
- widthCropSafe,
- heightCropSafe,
+ extractFaceCrop(imageBitmap, detection.box).then((b) =>
+ cache.put(faceID, b),
),
- );
- }
- return Promise.all(futureFaceThumbnails);
-};
-
-const _cropAndEncodeCanvas = async (
- imageBitmap: ImageBitmap,
- x: number,
- y: number,
- width: number,
- height: number,
-) => {
- const offscreen = new OffscreenCanvas(width, height);
- const offscreenCtx = ensure(offscreen.getContext("2d"));
- offscreenCtx.imageSmoothingQuality = "high";
-
- offscreenCtx.drawImage(
- imageBitmap,
- x,
- y,
- width,
- height,
- 0,
- 0,
- width,
- height,
+ ),
);
-
- return offscreen.convertToBlob({ type: "image/jpeg", quality: 0.8 });
};
/**
@@ -133,11 +40,11 @@ const _cropAndEncodeCanvas = async (
*
* @returns a JPEG blob.
*/
-export const extractFaceCrop2 = (imageBitmap: ImageBitmap, faceBox: Box) => {
+export const extractFaceCrop = (imageBitmap: ImageBitmap, faceBox: Box) => {
const { width: imageWidth, height: imageHeight } = imageBitmap;
- // The faceBox is relative to the image size, and we need to convert
- // them to absolute values first.
+ // The faceBox coordinates are normalized 0-1 relative to the image size,
+ // and we need to convert them back to absolute values first.
const faceX = faceBox.x * imageWidth;
const faceY = faceBox.y * imageHeight;
const faceWidth = faceBox.width * imageWidth;
@@ -173,114 +80,3 @@ export const extractFaceCrop2 = (imageBitmap: ImageBitmap, faceBox: Box) => {
return canvas.convertToBlob({ type: "image/jpeg", quality: 0.8 });
};
-
-// export const saveFaceCrop = async (
-// imageBitmap: ImageBitmap,
-// faceID: string,
-// alignment: FaceAlignment,
-// ) => {
-// const faceCrop = extractFaceCrop(imageBitmap, alignment);
-// const blob = await imageBitmapToBlob(faceCrop);
-// faceCrop.close();
-
-// const cache = await blobCache("face-crops");
-// await cache.put(faceID, blob);
-
-// return blob;
-// };
-
-// const imageBitmapToBlob = (imageBitmap: ImageBitmap) => {
-// const canvas = new OffscreenCanvas(imageBitmap.width, imageBitmap.height);
-// ensure(canvas.getContext("2d")).drawImage(imageBitmap, 0, 0);
-// return canvas.convertToBlob({ type: "image/jpeg", quality: 0.8 });
-// };
-
-const unnormalizeBox = (imageBitmap: ImageBitmap, alignment: FaceAlignment) => {
- const { width: imageWidth, height: imageHeight } = imageBitmap;
-
- const obb = alignment.boundingBox;
- // The faceBox is relative to the image size, and we need to convert
- // them to absolute values first.
- const faceX = obb.x * imageWidth;
- const faceY = obb.y * imageHeight;
- const faceWidth = obb.width * imageWidth;
- const faceHeight = obb.height * imageHeight;
-
- const bb = { x: faceX, y: faceY, width: faceWidth, height: faceHeight };
- return bb;
-};
-
-const extractFaceCrop = (
- imageBitmap: ImageBitmap,
- alignment: FaceAlignment,
-) => {
- // TODO-ML: This algorithm is different from what is used by the mobile app.
- // Also, it needs to be something that can work fully using the embedding we
- // receive from remote - the `alignment.boundingBox` will not be available
- // to us in such cases.
- const paddedBox = roundBox(enlargeBox(alignment.boundingBox, 1.5));
- const outputSize = { width: paddedBox.width, height: paddedBox.height };
-
- const maxDimension = 256;
- const scale = Math.min(
- maxDimension / paddedBox.width,
- maxDimension / paddedBox.height,
- );
-
- if (scale < 1) {
- outputSize.width = Math.round(scale * paddedBox.width);
- outputSize.height = Math.round(scale * paddedBox.height);
- }
-
- const offscreen = new OffscreenCanvas(outputSize.width, outputSize.height);
- const offscreenCtx = ensure(offscreen.getContext("2d"));
- offscreenCtx.imageSmoothingQuality = "high";
-
- offscreenCtx.translate(outputSize.width / 2, outputSize.height / 2);
-
- const outputBox = {
- x: -outputSize.width / 2,
- y: -outputSize.height / 2,
- width: outputSize.width,
- height: outputSize.height,
- };
-
- const enlargedBox = enlargeBox(paddedBox, 1.5);
- const enlargedOutputBox = enlargeBox(outputBox, 1.5);
-
- offscreenCtx.drawImage(
- imageBitmap,
- enlargedBox.x,
- enlargedBox.y,
- enlargedBox.width,
- enlargedBox.height,
- enlargedOutputBox.x,
- enlargedOutputBox.y,
- enlargedOutputBox.width,
- enlargedOutputBox.height,
- );
-
- return offscreen.convertToBlob({ type: "image/jpeg", quality: 0.8 });
-};
-
-/** Round all the components of the box. */
-const roundBox = (box: Box): Box => ({
- x: Math.round(box.x),
- y: Math.round(box.y),
- width: Math.round(box.width),
- height: Math.round(box.height),
-});
-
-/** Increase the size of the given {@link box} by {@link factor}. */
-const enlargeBox = (box: Box, factor: number): Box => {
- const center = { x: box.x + box.width / 2, y: box.y + box.height / 2 };
- const newWidth = factor * box.width;
- const newHeight = factor * box.height;
-
- return {
- x: center.x - newWidth / 2,
- y: center.y - newHeight / 2,
- width: newWidth,
- height: newHeight,
- };
-};
diff --git a/web/packages/new/photos/services/ml/face.ts b/web/packages/new/photos/services/ml/face.ts
index aaef3b922b..a55ecb3187 100644
--- a/web/packages/new/photos/services/ml/face.ts
+++ b/web/packages/new/photos/services/ml/face.ts
@@ -423,7 +423,7 @@ const convertToYOLOInputFloat32ChannelsFirst = (imageBitmap: ImageBitmap) => {
return { yoloInput, yoloSize };
};
-export interface YOLOFaceDetection {
+interface YOLOFaceDetection {
box: Box;
landmarks: Point[];
score: number;
@@ -607,7 +607,7 @@ const makeFaceID = (fileID: number, box: Box, image: Dimensions) => {
return [`${fileID}`, xMin, yMin, xMax, yMax].join("_");
};
-export interface FaceAlignment {
+interface FaceAlignment {
/**
* An affine transformation matrix (rotation, translation, scaling) to align
* the face extracted from the image.
@@ -629,10 +629,7 @@ export interface FaceAlignment {
*
* @param faceDetection A geometry indicating a face detected in an image.
*/
-// TODO-ML: Unexport?
-export const computeFaceAlignment = (
- faceDetection: FaceDetection,
-): FaceAlignment =>
+const computeFaceAlignment = (faceDetection: FaceDetection): FaceAlignment =>
computeFaceAlignmentUsingSimilarityTransform(
faceDetection,
normalizeLandmarks(idealMobileFaceNetLandmarks, mobileFaceNetFaceSize),
@@ -956,26 +953,3 @@ const normalizeByImageDimensions = (
}));
return { box, landmarks };
};
-
-/**
- * Scale normalized coordinates from 0-1 back to the image's dimensions.
- *
- * Inverse of {@link normalizeByImageDimensions}.
- */
-export const restoreToImageDimensions = (
- faceDetection: FaceDetection,
- { width, height }: Dimensions,
-): FaceDetection => {
- const oldBox: Box = faceDetection.box;
- const box = {
- x: oldBox.x * width,
- y: oldBox.y * height,
- width: oldBox.width * width,
- height: oldBox.height * height,
- };
- const landmarks = faceDetection.landmarks.map((l) => ({
- x: l.x * width,
- y: l.y * height,
- }));
- return { box, landmarks };
-};