Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions server/src/queries/person.repository.sql
Original file line number Diff line number Diff line change
Expand Up @@ -1179,6 +1179,9 @@ with
"face_search" ("faceId", "embedding")
values
($1, $2)
on conflict ("faceId") do update
set
"embedding" = "excluded"."embedding"
)
select
from
Expand Down
9 changes: 8 additions & 1 deletion server/src/repositories/person.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
type Updateable,
} from 'kysely';
import { jsonArrayFrom, jsonObjectFrom } from 'kysely/helpers/postgres';
import { sortBy } from 'lodash-es';
import { InjectKysely } from 'nestjs-kysely';
import { AssetFace, PersonUser, columns } from 'src/database.js';
import { Chunked, ChunkedArray, DummyValue, GenerateSql } from 'src/decorators.js';
Expand Down Expand Up @@ -829,7 +830,13 @@ export class PersonRepository {
}

if (embeddingsToAdd?.length) {
(query as any) = query.with('added_embeddings', (db) => db.insertInto('face_search').values(embeddingsToAdd));
const embeddingsInLockOrder = sortBy(embeddingsToAdd, (row) => row.faceId);
(query as any) = query.with('added_embeddings', (db) =>
db
.insertInto('face_search')
.values(embeddingsInLockOrder)
.onConflict((oc) => oc.column('faceId').doUpdateSet((eb) => ({ embedding: eb.ref('excluded.embedding') }))),
);
}

await query.selectFrom(dummy).execute();
Expand Down
34 changes: 34 additions & 0 deletions server/src/services/person.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1617,6 +1617,40 @@ describe(PersonService.name, () => {
expect(mocks.person.reassignFaces).not.toHaveBeenCalled();
});

it('should keep the first detection with the greatest overlap for a manual face', async () => {
const face = AssetFaceFactory.create({ sourceType: SourceType.Manual, imageWidth: 1440 });
const asset = AssetFactory.from().face(face).file({ type: AssetFileType.Preview }).exif().build();
const detection = getAsDetectedFace(face);
const [match] = detection.faces;
const box = match.boundingBox;
mocks.assetJob.getForDetectFacesJob.mockResolvedValue(getForDetectedFaces(asset));
mocks.machineLearning.detectFaces.mockResolvedValue({
...detection,
faces: [
{ ...match, boundingBox: { ...box, y2: box.y2 + 90 }, embedding: '[1, 0, 0, 0]' },
{ ...match, boundingBox: { ...box, x2: box.x2 - 31 }, embedding: '[0, 1, 0, 0]' },
{ ...match, boundingBox: { ...box, x1: box.x1 + 31 }, embedding: '[0, 0, 1, 0]' },
],
});

await sut.handleDetectFaces({ id: asset.id });

expect(mocks.person.refreshFaces).toHaveBeenCalledWith([], [], [{ faceId: face.id, embedding: '[0, 1, 0, 0]' }]);
});

it('should skip refreshing a machine learning face matched twice', async () => {
const face = AssetFaceFactory.create({ sourceType: SourceType.MachineLearning });
const asset = AssetFactory.from().face(face).file({ type: AssetFileType.Preview }).exif().build();
const detection = getAsDetectedFace(face);
const [match] = detection.faces;
mocks.assetJob.getForDetectFacesJob.mockResolvedValue(getForDetectedFaces(asset));
mocks.machineLearning.detectFaces.mockResolvedValue({ ...detection, faces: [match, match] });

await sut.handleDetectFaces({ id: asset.id });

expect(mocks.person.refreshFaces).not.toHaveBeenCalled();
});

it('should match metadata face stored at a different resolution', async () => {
const face = AssetFaceFactory.create({
sourceType: SourceType.Exif,
Expand Down
44 changes: 28 additions & 16 deletions server/src/services/person.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { Insertable } from 'kysely';
import { isUndefined, omitBy } from 'lodash-es';
import { isUndefined, omitBy, partition } from 'lodash-es';
import { Chunked, OnJob } from 'src/decorators.js';
import { BulkIdErrorReason, BulkIdResponseDto } from 'src/dtos/asset-ids.response.dto.js';
import { AuthDto } from 'src/dtos/auth.dto.js';
Expand Down Expand Up @@ -59,6 +59,7 @@ import { mimeTypes } from 'src/utils/mime-types.js';
import { batched, findOrFail, hasSomeDefined, isFacialRecognitionEnabled } from 'src/utils/misc.js';
import { Point, transformPoints } from 'src/utils/transform.js';

const FACE_OVERLAP_EPSILON = 1e-9;
const personKey = ({ ownerId, personGroupId }: PersonId) => `${ownerId}/${personGroupId}`;
const shareKey = ({ personId, sharedWithId }: { personId: string; sharedWithId: string }) =>
`${personId}/${sharedWithId}`;
Expand Down Expand Up @@ -485,22 +486,30 @@ export class PersonService extends BaseService {

const facesToAdd: (Insertable<AssetFaceTable> & { id: string })[] = [];
const embeddings: FaceSearchTable[] = [];
const mlFaceIds = new Set<string>();

for (const face of asset.faces) {
if (face.sourceType === SourceType.MachineLearning) {
mlFaceIds.add(face.id);
const bestTaggedMatches = new Map<string, { embedding: string; overlap: number }>();
const [mlFaces, taggedFaces] = partition(asset.faces, (face) => face.sourceType === SourceType.MachineLearning);
const unmatchedMlFaceIds = new Set(mlFaces.map((face) => face.id));
const facesByPriority = [...taggedFaces, ...mlFaces];

const findMatch = (box: BoundingBox) => {
for (const face of facesByPriority) {
const overlap = this.iou(face, box, imageWidth, imageHeight);
if (overlap > 0.5) {
return { face, overlap };
}
}
}
};

for (const { boundingBox, embedding } of faces) {
const matches = asset.faces.filter((face) => this.iou(face, boundingBox, imageWidth, imageHeight) > 0.5);
// prefer metadata faces over machine learning duplicates
const match = matches.find((face) => face.sourceType !== SourceType.MachineLearning) ?? matches[0];

if (match && !mlFaceIds.delete(match.id)) {
embeddings.push({ faceId: match.id, embedding });
} else if (!match) {
const match = findMatch(boundingBox);
if (match?.face.sourceType === SourceType.MachineLearning) {
unmatchedMlFaceIds.delete(match.face.id);
} else if (match) {
const previous = bestTaggedMatches.get(match.face.id);
if (!previous || match.overlap > previous.overlap + FACE_OVERLAP_EPSILON) {
bestTaggedMatches.set(match.face.id, { embedding, overlap: match.overlap });
}
} else {
const faceId = this.cryptoRepository.randomUUID();
facesToAdd.push({
id: faceId,
Expand All @@ -515,7 +524,10 @@ export class PersonService extends BaseService {
embeddings.push({ faceId, embedding });
}
}
const faceIdsToRemove = [...mlFaceIds];
for (const [faceId, { embedding }] of bestTaggedMatches) {
embeddings.push({ faceId, embedding });
}
const faceIdsToRemove = [...unmatchedMlFaceIds];

if (facesToAdd.length > 0 || faceIdsToRemove.length > 0 || embeddings.length > 0) {
await this.personRepository.refreshFaces(facesToAdd, faceIdsToRemove, embeddings);
Expand All @@ -530,7 +542,7 @@ export class PersonService extends BaseService {
const jobs = facesToAdd.map((face) => ({ name: JobName.FacialRecognition, data: { id: face.id } }) as const);
await this.jobRepository.queueAll([{ name: JobName.FacialRecognitionQueueAll, data: { force: false } }, ...jobs]);
} else if (embeddings.length > 0) {
this.logger.log(`Added ${embeddings.length} face embeddings for asset ${id}`);
this.logger.log(`Refreshed ${embeddings.length} face embeddings for asset ${id}`);
}

await this.assetRepository.upsertJobStatus({ assetId: asset.id, facesRecognizedAt: new Date() });
Expand Down
22 changes: 22 additions & 0 deletions server/test/medium/specs/repositories/person.repository.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,28 @@ beforeAll(async () => {
});

describe(PersonRepository.name, () => {
describe('refreshFaces', () => {
it('should replace an existing face embedding on refresh', async () => {
const { ctx, sut } = setup();
const { user } = await ctx.newUser();
const { asset } = await ctx.newAsset({ ownerId: user.id });
const { assetFace } = await ctx.newAssetFace({ assetId: asset.id });
const zeros = Array.from({ length: 510 }, () => 0);
const original = JSON.stringify([1, 0, ...zeros]);
const replacement = JSON.stringify([0, 1, ...zeros]);

await sut.refreshFaces([], [], [{ faceId: assetFace.id, embedding: original }]);
await sut.refreshFaces([], [], [{ faceId: assetFace.id, embedding: replacement }]);

const { embedding } = await ctx.database
.selectFrom('face_search')
.select('embedding')
.where('faceId', '=', assetFace.id)
.executeTakeFirstOrThrow();
expect(embedding).toBe(replacement);
});
});

describe('createAll', () => {
it('should create people in the groups they were given', async () => {
const { ctx, sut } = setup();
Expand Down
Loading