diff --git a/server/src/queries/person.repository.sql b/server/src/queries/person.repository.sql index 48b3d7b90ec5..bb41efe9fb71 100644 --- a/server/src/queries/person.repository.sql +++ b/server/src/queries/person.repository.sql @@ -1179,6 +1179,9 @@ with "face_search" ("faceId", "embedding") values ($1, $2) + on conflict ("faceId") do update + set + "embedding" = "excluded"."embedding" ) select from diff --git a/server/src/repositories/person.repository.ts b/server/src/repositories/person.repository.ts index 9bed48c1dac3..390e50cc03d3 100644 --- a/server/src/repositories/person.repository.ts +++ b/server/src/repositories/person.repository.ts @@ -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'; @@ -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(); diff --git a/server/src/services/person.service.spec.ts b/server/src/services/person.service.spec.ts index 8fb7ba99f3cf..d6948ce32eed 100644 --- a/server/src/services/person.service.spec.ts +++ b/server/src/services/person.service.spec.ts @@ -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, diff --git a/server/src/services/person.service.ts b/server/src/services/person.service.ts index 1b26029fa06a..72c60c2d2284 100644 --- a/server/src/services/person.service.ts +++ b/server/src/services/person.service.ts @@ -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'; @@ -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}`; @@ -485,22 +486,30 @@ export class PersonService extends BaseService { const facesToAdd: (Insertable & { id: string })[] = []; const embeddings: FaceSearchTable[] = []; - const mlFaceIds = new Set(); - - for (const face of asset.faces) { - if (face.sourceType === SourceType.MachineLearning) { - mlFaceIds.add(face.id); + const bestTaggedMatches = new Map(); + 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, @@ -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); @@ -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() }); diff --git a/server/test/medium/specs/repositories/person.repository.spec.ts b/server/test/medium/specs/repositories/person.repository.spec.ts index c400fe2b0f82..95b6a64e91ff 100644 --- a/server/test/medium/specs/repositories/person.repository.spec.ts +++ b/server/test/medium/specs/repositories/person.repository.spec.ts @@ -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();