#!/usr/bin/env python3 """Face grouping for Cotton Albums: the reference the Rust core ports (coordinator, NEXT-GROUPING.md), and its tuning. python3 scripts/albums-grouping.py --export --truth [--export ... --truth ...] [--out grouping.json] Faces (unit vectors from the phone's whole chain) meet the truth's identities by position, as albums-score.py does. THE RULE (two stages, never single linkage, which chained 741 real faces of many people into one group): 0. CANNOT-LINK: two faces in one photo are never one person. It is a hard constraint on every join and merge, and the unlabelled quality measure (same-photo pairs inside one group must be 0). His own "not this person" splits are cannot-links too; his merges are must-links. 1. SEEDS: each face's nearest neighbour; a pair that are each other's nearest neighbour with cosine >= SEED is joined (mutual nearest neighbours above a high cut), unless that breaks a cannot-link. This gives tight groups and leaves doubtful faces alone. 2. MERGE: groups are merged, best first, while their AVERAGE pairwise cosine is >= MERGE and no cannot-link stands between them. Average, not nearest pair, so one look-alike face cannot bridge two people. 3. ATTACH: a face still alone joins the group whose centroid is nearest when that cosine is >= JOIN and no cannot-link stands (this is also the incremental step for a new face: join the best group over the cut or start its own; bounded work: one centroid comparison per group). 4. SHOW: a group is a person on the People screen at 5 or more photos. Two shown groups whose average cosine is in [ASK, MERGE) are offered as "Same person?", never merged by themselves. Measured, for a grid of SEED, MERGE and JOIN: BCubed precision (purity) and recall (completeness) over all faces; cannot-link violations (0 by construction for this rule); groups by size; the largest group; people with 5 or more photos found as one shown group, split across several, or mixed into another's. Single linkage at 0.5 is measured beside it, to show the chaining the coordinator saw on real photos. """ import argparse import json from collections import Counter, defaultdict import numpy as np def faces_of(export, truth): tr = {} for line in open(truth): t = json.loads(line) tr[t["file"]] = t out = [] for line in open(export): r = json.loads(line) t = tr.get(r.get("file")) if not t or r.get("state") not in (1, 5): continue W, H = t.get("size", (1, 1)) faces = r.get("faces") or [] used = set() for p in t.get("people") or []: x, y, s, _ = p["box"] cx, cy = (x + s / 2) / W, (y + s / 2) / H best, bd = None, 1e9 for k, f in enumerate(faces): if k in used: continue fx, fy, fw, fh = f["box"] d = abs(fx + fw / 2 - cx) + abs(fy + fh / 2 - cy) if d < bd and d < max(fw, s / W): best, bd = k, d if best is None: continue used.add(best) f = faces[best] if f.get("vector"): v = np.asarray(f["vector"], np.float32) out.append(dict(vector=v / np.linalg.norm(v), identity=p["identity"], photo=export + "|" + r["file"], quality=f.get("quality") or 0)) return out class Groups: """Union-find over faces, with each group's photo set (for cannot-link) and vector sum (for centroids).""" def __init__(self, V, photos): self.parent = list(range(len(V))) self.photos = {i: {photos[i]} for i in range(len(V))} self.sum = {i: V[i].astype(np.float64).copy() for i in range(len(V))} self.members = {i: [i] for i in range(len(V))} def find(self, a): while self.parent[a] != a: self.parent[a] = self.parent[self.parent[a]] a = self.parent[a] return a def can(self, a, b): ra, rb = self.find(a), self.find(b) return ra != rb and not (self.photos[ra] & self.photos[rb]) def join(self, a, b): ra, rb = self.find(a), self.find(b) if ra == rb: return if len(self.members[ra]) < len(self.members[rb]): ra, rb = rb, ra self.parent[rb] = ra self.photos[ra] |= self.photos.pop(rb) self.sum[ra] += self.sum.pop(rb) self.members[ra] += self.members.pop(rb) def roots(self): return list(self.members) def labels(self): return np.asarray([self.find(i) for i in range(len(self.parent))]) def two_stage(V, photos, seed, merge, join, S=None): """The rule. Average pairwise cosine between groups a and b is (sum_a . sum_b) / (|a| |b|): exact, from sums.""" S = V @ V.T if S is None else S n = len(V) photo_ids = {p: k for k, p in enumerate(dict.fromkeys(photos))} pid = np.asarray([photo_ids[p] for p in photos]) g = Groups(V, photos) # 1. Seeds: mutual nearest neighbours above SEED (a face in the same photo is never a neighbour). masked = S.copy() np.fill_diagonal(masked, -1) masked[pid[:, None] == pid[None, :]] = -1 nn = masked.argmax(1) for i in range(n): j = nn[i] if nn[j] == i and i < j and masked[i, j] >= seed and g.can(i, j): g.join(i, j) # 2. Merge groups of two or more by average cosine, best first, never across a cannot-link. roots = [r for r in g.roots() if len(g.members[r]) >= 2] if len(roots) > 1: sums = np.stack([g.sum[r] for r in roots]) sizes = np.asarray([len(g.members[r]) for r in roots], np.float64) P = np.zeros((len(roots), len(photo_ids)), bool) for k, r in enumerate(roots): P[k, [photo_ids[p] for p in g.photos[r]]] = True alive = np.ones(len(roots), bool) while True: A = (sums @ sums.T) / np.outer(sizes, sizes) conflict = (P.astype(np.int32) @ P.T.astype(np.int32)) > 0 A[conflict] = -9 A[~alive, :] = -9 A[:, ~alive] = -9 np.fill_diagonal(A, -9) a, b = np.unravel_index(np.argmax(A), A.shape) if A[a, b] < merge: break g.join(roots[a], roots[b]) sums[a] += sums[b] sizes[a] += sizes[b] P[a] |= P[b] alive[b] = False roots[a] = g.find(roots[a]) # 3. Attach faces still alone to the nearest centroid over JOIN (the incremental step). groups = [r for r in g.roots() if len(g.members[r]) >= 2] for i in range(n): if len(g.members[g.find(i)]) != 1 or not groups: continue cents = np.stack([g.sum[q] / np.linalg.norm(g.sum[q]) for q in groups]) sims = cents @ V[i] for k in np.argsort(-sims): if sims[k] < join: break if photos[i] not in g.photos[groups[k]]: g.join(groups[k], i) groups[k] = g.find(groups[k]) break return g.labels() def single_linkage(V, photos, cut, S=None): S = V @ V.T if S is None else S g = Groups(V, photos) idx = np.argwhere(np.triu(S, 1) >= cut) for a, b in idx: g.join(a, b) # no cannot-link: what the coordinator's real-photo run did return g.labels() def measure(labels, ids, photos, shown=5): n = len(labels) by_g = defaultdict(list) by_t = defaultdict(list) for i in range(n): by_g[labels[i]].append(i) by_t[ids[i]].append(i) p = r = 0.0 for i in range(n): g, t = by_g[labels[i]], by_t[ids[i]] both = sum(1 for j in g if ids[j] == ids[i]) p += both / len(g) r += both / len(t) p, r = p / n, r / n violations = 0 for m in by_g.values(): c = Counter(photos[i] for i in m) violations += sum(k * (k - 1) // 2 for k in c.values() if k > 1) sizes = sorted((len({photos[i] for i in m}) for m in by_g.values()), reverse=True) shown_groups = {g: m for g, m in by_g.items() if len({photos[i] for i in m}) >= shown} people = {t: m for t, m in by_t.items() if len({photos[i] for i in m}) >= shown} owner = defaultdict(set) mixed = 0 for g, m in shown_groups.items(): top, k = Counter(ids[i] for i in m).most_common(1)[0] owner[top].add(g) mixed += k / len(m) < 0.9 return dict( purity=round(p, 4), completeness=round(r, 4), f=round(2 * p * r / (p + r), 4) if p + r else 0, cannot_link_violations=violations, groups=len(by_g), largest_group_photos=sizes[0] if sizes else 0, groups_by_photos={"1": sum(1 for s in sizes if s == 1), "2-4": sum(1 for s in sizes if 2 <= s <= 4), "5-19": sum(1 for s in sizes if 5 <= s <= 19), "20+": sum(1 for s in sizes if s >= 20)}, shown=len(shown_groups), people_with_5_photos=len(people), people_found_whole=sum(1 for t in people if len(owner.get(t, ())) == 1), people_split=sum(1 for t in people if len(owner.get(t, ())) > 1), people_missing=sum(1 for t in people if t not in owner), shown_mixed=int(mixed)) def main(): ap = argparse.ArgumentParser() ap.add_argument("--export", action="append", required=True) ap.add_argument("--truth", action="append", required=True) ap.add_argument("--out") a = ap.parse_args() faces = [] for e, t in zip(a.export, a.truth): faces += faces_of(e, t) V = np.stack([f["vector"] for f in faces]) ids = [f["identity"] for f in faces] photos = [f["photo"] for f in faces] S = V @ V.T out = dict(faces=len(faces), people=len(set(ids)), photos=len(set(photos)), same_photo_pairs=sum(k * (k - 1) // 2 for k in Counter(photos).values())) out["single_linkage"] = {str(c): measure(single_linkage(V, photos, c, S), ids, photos) for c in (0.3, 0.4, 0.5)} grid = [] for seed in (0.45, 0.55, 0.65): for merge in (0.3, 0.35, 0.4, 0.5): for join in (0.35, 0.45, 0.55): m = measure(two_stage(V, photos, seed, merge, join, S), ids, photos) grid.append(dict(seed=seed, merge=merge, join=join, **m)) out["two_stage"] = grid ok = [x for x in grid if x["purity"] >= 0.995 and x["shown_mixed"] == 0] out["chosen"] = max(ok or grid, key=lambda x: (x["completeness"], x["people_found_whole"])) text = json.dumps(out, indent=2) print(text) if a.out: open(a.out, "w").write(text) if __name__ == "__main__": main()