diff --git a/apps/api/src/faces/rank.test.ts b/apps/api/src/faces/rank.test.ts new file mode 100644 index 0000000..bfcfcae --- /dev/null +++ b/apps/api/src/faces/rank.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from "vitest"; +import { claimsToKeep, faceAndNumberScore, numberAndKitScore, numberOnlyScore } from "./rank.js"; + +describe("suggestion rank", () => { + it("puts face+number above number+kit, and that above number alone", () => { + const both = faceAndNumberScore(0.7, 0.95); + const kit = numberAndKitScore(0.95, 1); + const only = numberOnlyScore(0.95); + expect(both).toBeGreaterThan(kit); + expect(kit).toBeGreaterThan(only); + expect(both).toBeLessThanOrEqual(0.99); + expect(kit).toBeLessThanOrEqual(0.82); + }); + + it("keeps one face cluster when two different faces were both named as the same #9", () => { + const a = [1, 0, 0]; + const b = [0, 1, 0]; + const same = [0.99, 0.01, 0]; + const keep = claimsToKeep( + [ + { id: "strong", personId: "alvarez", score: 0.91, centroid: a }, + { id: "also-him", personId: "alvarez", score: 0.88, centroid: same }, + { id: "other-face", personId: "alvarez", score: 0.7, centroid: b }, + ], + 0.9, + ); + expect([...keep].sort()).toEqual(["also-him", "strong"]); + }); +}); diff --git a/apps/api/src/faces/rank.ts b/apps/api/src/faces/rank.ts new file mode 100644 index 0000000..3f65711 --- /dev/null +++ b/apps/api/src/faces/rank.ts @@ -0,0 +1,58 @@ +import { cosine } from "./math.js"; + +/** + * How sure a name is, highest first. The best guess wins; a weaker one never outranks a stronger one. + * + * 1. Face and shirt agree (same player) — strongest. + * 2. Face alone, when the shirt was not read. + * 3. Clear shirt plus kit colour matching a teammate we already trust (face+number, or a confirmation). + * 4. Clear shirt, only one player in the game wears it, kit not yet known — quieter, and only one face cluster. + */ + +/** Face and the number on the kit are the same person. */ +export function faceAndNumberScore(face: number, jersey: number): number { + return Math.round(Math.min(0.99, face + 0.15 * jersey) * 1000) / 1000; +} + +/** Shirt number, and the kit colour matches the team we already know from a trusted player. */ +export function numberAndKitScore(jersey: number, kitSure: number): number { + return Math.round(Math.min(0.82, jersey * 0.85 * kitSure) * 1000) / 1000; +} + +/** Shirt number alone (one wearer, kit not known yet). Stays under a real face match. */ +export function numberOnlyScore(jersey: number): number { + return Math.round(Math.min(0.72, jersey * 0.72) * 1000) / 1000; +} + +export interface Claim { + id: string; + personId: string; + score: number; + centroid: number[]; +} + +/** + * One person, several face groups. Groups that look like the same face all keep the name. + * Groups that do not look like each other: only the cluster with the best score keeps it, + * so two different faces are not both "Manuel Alvarez #9". + */ +export function claimsToKeep(claims: Claim[], sameFace: number): Set { + const keep = new Set(); + const byPerson = new Map(); + for (const c of claims) { + const list = byPerson.get(c.personId) ?? []; + list.push(c); + byPerson.set(c.personId, list); + } + for (const set of byPerson.values()) { + const ordered = [...set].sort((a, b) => b.score - a.score); + const clusters: Claim[][] = []; + for (const c of ordered) { + const hit = clusters.find((cluster) => cluster.some((o) => o.centroid.length > 0 && c.centroid.length > 0 && cosine(o.centroid, c.centroid) >= sameFace)); + if (hit) hit.push(c); + else clusters.push([c]); + } + for (const c of clusters[0] ?? []) keep.add(c.id); + } + return keep; +} diff --git a/apps/api/src/faces/service.ts b/apps/api/src/faces/service.ts index 81817be..b5e5465 100644 --- a/apps/api/src/faces/service.ts +++ b/apps/api/src/faces/service.ts @@ -24,6 +24,7 @@ import { numberContext, numbersIn, peopleOnRoster, rosterOf, type NumberContext import { samePlayer } from "../sports/identity.js"; import { eventSport, normSport } from "./sport.js"; import { addToMean, cosine, inFocus, mergeMeans, MIN_SHARPNESS, OPEN_MARGIN, THRESHOLDS, openFloor } from "./math.js"; +import { claimsToKeep, faceAndNumberScore, numberAndKitScore, numberOnlyScore } from "./rank.js"; import type { FaceEngine } from "./process.js"; import { FaceFollower } from "./track.js"; import { randomUUID } from "node:crypto"; @@ -613,9 +614,9 @@ export class FaceService { allowNumber && (!ok || faceAgrees === false || (ok && firstNumber == null)); if (faceAgrees && first && read) { - // Face and shirt agree on the same player: surer than either alone. + // Rank 1: face and shirt are the same player. suggestedPersonId = first.p.id; - suggestionScore = Math.round(Math.min(0.99, first.s + 0.15 * read.score) * 1000) / 1000; + suggestionScore = faceAndNumberScore(first.s, read.score); } else if (preferNumber && read) { // The number decides among faces that look near, then the squad who wears it (kit colour if both teams). const close = ranked.filter((r) => r.s >= (bounded ? match * 0.8 : floor)); @@ -628,7 +629,7 @@ export class FaceService { } if (near.length === 1) { suggestedPersonId = near[0]!.p.id; - suggestionScore = Math.round(Math.max(near[0]!.s, read.score * 0.9) * 1000) / 1000; + suggestionScore = Math.max(near[0]!.s, numberOnlyScore(read.score)); } else { const byNumber = ctx ? await this.suggestByNumber(g.id, ctx, read) : null; if (byNumber) ({ personId: suggestedPersonId, score: suggestionScore } = byNumber); @@ -657,9 +658,32 @@ export class FaceService { await db.faceGroup.update({ where: { id: g.id }, data: { suggestedPersonId, suggestionScore } }); } } + await this.dropWeakerDuplicateClaims(eventId); if (ctx && !ctx.national && ctx.teamIds.length) await this.nameLineupPhotos(eventId, ctx, notThem, off); } + /** + * Two face groups suggested as the same player, but the faces do not match: keep the stronger guess + * (face+number beats number-only). The other group is left unnamed so it is not a second "Manuel Alvarez". + */ + private async dropWeakerDuplicateClaims(eventId: string): Promise { + const { db } = this.deps; + const rows = await db.faceGroup.findMany({ + where: { eventId, personId: null, suggestedPersonId: { not: null } }, + select: { id: true, suggestedPersonId: true, suggestionScore: true, centroid: true, model: true }, + }); + if (rows.length < 2) return; + const model = rows[0]!.model; + const keep = claimsToKeep( + rows.map((g) => ({ id: g.id, personId: g.suggestedPersonId!, score: g.suggestionScore ?? 0, centroid: g.centroid })), + this.thresholds(model).group, + ); + for (const g of rows) { + if (keep.has(g.id)) continue; + await db.faceGroup.update({ where: { id: g.id }, data: { suggestedPersonId: null, suggestionScore: null } }); + } + } + /** * A team lined up for the photograph: each clear shirt number belongs to one player of that squad. * Those faces are suggested from the number. A group that already spans other photographs keeps a @@ -824,12 +848,22 @@ export class FaceService { const people = teamOf.size ? await db.person.findMany({ where: { organizationId: event.organizationId, sportsPlayerId: { in: [...teamOf.keys()] } }, select: { id: true, sportsPlayerId: true } }) : []; - if (people.length === 1) return { personId: people[0]!.id, score: Math.round(read.score * 0.9 * 1000) / 1000 }; + const team = await this.teamByKit(groupId, eventId); + const onKit = (sportsPlayerId: string | null) => { + if (!team || !sportsPlayerId) return team ? false : true; + return teamOf.get(sportsPlayerId) === team.teamId; + }; + if (people.length === 1) { + const one = people[0]!; + // Kit of a player we already trust (face+number) says the other team: this number is not him. + if (team && one.sportsPlayerId && !onKit(one.sportsPlayerId)) return null; + const score = team && one.sportsPlayerId && onKit(one.sportsPlayerId) ? numberAndKitScore(read.score, team.sure) : numberOnlyScore(read.score); + return { personId: one.id, score }; + } if (people.length === 2) { - // One in each team: the kit colour of this group against each team's (from players already confirmed here). - const team = await this.teamByKit(groupId, eventId); - const pick = team ? people.find((p) => p.sportsPlayerId && teamOf.get(p.sportsPlayerId) === team.teamId) : undefined; - if (pick && team) return { personId: pick.id, score: Math.round(read.score * 0.85 * team.sure * 1000) / 1000 }; + // One in each team: only the kit colour (learnt from a trusted teammate) may pick. + const pick = team ? people.find((p) => onKit(p.sportsPlayerId)) : undefined; + if (pick && team) return { personId: pick.id, score: numberAndKitScore(read.score, team.sure) }; } if (players.length) return null; // two players with that number and no clear kit, or not people yet: no guess } @@ -843,7 +877,7 @@ export class FaceService { const nums = await numbersIn(db, ctx, candidates.map((p) => p.id)); const wearing = candidates.filter((p) => nums.get(p.id) === read.number); if (wearing.length !== 1) return null; - return { personId: wearing[0]!.id, score: Math.round(read.score * 0.9 * 1000) / 1000 }; + return { personId: wearing[0]!.id, score: numberOnlyScore(read.score) }; } /** Which of these people play for the team (by their squad entry). */ diff --git a/apps/api/test/faces.test.ts b/apps/api/test/faces.test.ts index 8eb13b3..9b93578 100644 --- a/apps/api/test/faces.test.ts +++ b/apps/api/test/faces.test.ts @@ -397,7 +397,8 @@ describe("faces", () => { expect(groups[0]!.number).toMatchObject({ value: "10", votes: 2 }); // Benfica's 10 isn't playing; the suggestion waits for someone to confirm it. expect(groups[0]!.suggestion).toMatchObject({ name: "Rui Costa" }); - expect(groups[0]!.suggestion!.score).toBeCloseTo(0.855, 3); + // Number alone, kit not known yet: quieter than face+number (that tops out at 0.99). + expect(groups[0]!.suggestion!.score).toBeCloseTo(0.684, 2); expect(groups[0]!.person).toBeNull(); expect((await ctx.db.photo.findMany({ select: { players: true } })).every((p) => p.players.length === 0)).toBe(true); }); diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 98106b2..1afa658 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -219,13 +219,13 @@ group. Face and number are used together: -- **Face sure, number agrees:** the face's suggestion, surer (score + 0.15 × the reading, at most 0.99). +- **Face and number agree:** the strongest guess (face score + 0.15 × the reading, at most 0.99). - **Face sure, no number read:** the face's suggestion. Faces come from confirmed groups and from the official headshots (Liga, UEFA, FPA licence photos) that squads bring as reference photos, so even a first match has faces to go by. -- **Clear number, face not that wearer (or no sure face):** the number wins — near faces who wear it, else the squad - player with that number (one reading is enough; a sure face that disagrees is only kept if the number finds nobody). -- **Face not sure (weak, or two people too close):** among the people the face is near to, the one whose number was - read; else the squad player who wears that number in either team of the event (0.9 × the mean reading). +- **Clear number, no face to compare (or the face is someone else):** the squad player who wears it, but only if the + kit colour matches a teammate already trusted (face+number or a confirmation). The other team's kit never takes the name. + Without a known kit yet, one wearer is still suggested, quieter (under a real face match). +- Two face groups that do not look like the same person never both keep that name: the stronger guess wins. - **Both teams have that number:** the kit colour decides. Each face keeps the median colour of the middle of its chest; each team's colour is the median of its players already confirmed in the event, or suggested with face and shirt agreeing (score 0.85 and up), goalkeepers left out. The same colour also decides between two people the