#!/usr/bin/env python3"""Scores what Cotton Albums' pass found on a synthetic library against the library's truth. python3 scripts/albums-score.py --export <albums-export.jsonl> --truth <truth.jsonl> [--out score.json]The export is written by the Dev build (`AlbumsMeasure.export`, Documents/albums-export.jsonl); the truth by`scripts/albums-library.py`. Rows meet by the original's file name. It answers: - what was looked at, and the pictures' sizes; - look-alike: Vision's feature-print distance between shots of one moment and between neighbouring moments, and how well one threshold (with "within 3 minutes") separates them, as pair precision and recall; - blur and dark: how well sharpness and light find the blurred and dark shots (AUC, and the best cut); - screenshots and documents: what PhotoKit's subtype and Vision's utility and document outline say; - faces: how many of the drawn faces Vision found by size, and on the found ones, the identity vectors made from Vision's landmarks and the phone's crop: TAR at FAR 1e-3 and rank-1, by face size. This is the whole chain (detection, five points, alignment, model) on the phone, not the model alone."""import argparseimport base64import jsonimport sysfrom collections import defaultdictimport numpy as npdef auc(pos, neg):"""Probability a positive scores LOWER than a negative (low sharpness = blurred).""" pos, neg = np.asarray(pos), np.asarray(neg)if len(pos) == 0or len(neg) == 0:returnNone allv = np.concatenate([pos, neg]) ranks = allv.argsort().argsort() + 1 r = ranks[: len(pos)].sum()return float(1 - (r - len(pos) * (len(pos) + 1) / 2) / (len(pos) * len(neg)))def best_cut(pos, neg): vals = np.unique(np.concatenate([pos, neg])) best = (0, None)for v in np.quantile(vals, np.linspace(0, 1, 200)): tp = (np.asarray(pos) < v).sum() fp = (np.asarray(neg) < v).sum() f1 = 2 * tp / (2 * tp + fp + (len(pos) - tp)) if tp else0if f1 > best[0]: best = (f1, float(v))return dict(f1=round(best[0], 4), cut=best[1])def main(): ap = argparse.ArgumentParser() ap.add_argument("--export", required=True) ap.add_argument("--truth", required=True) ap.add_argument("--out") a = ap.parse_args() truth = {}for line in open(a.truth): t = json.loads(line) truth[t["file"]] = t rows = [json.loads(l) for l in open(a.export)] out = {} met = [(r, truth.get(r.get("file"))) for r in rows] out["rows"] = len(rows) out["met_truth"] = sum(1for _, t in met if t) looked = [(r, t) for r, t in met if r["state"] == 1and t] out["looked"] = len(looked) out["states"] = {str(k): sum(1for r in rows if r["state"] == k) for k in range(5)} sides = [r["side"] for r, _ in looked] out["picture_side"] = dict(median=int(np.median(sides)), min=min(sides), max=max(sides)) if sides elseNone# Look-alike: neighbouring camera shots in time. cams = sorted([(r, t) for r, t in looked if t["kind"] == "camera"and r.get("print")], key=lambda x: x[1]["when"]) prints = {r["file"]: np.frombuffer(base64.b64decode(r["print"]), dtype=np.float32) for r, _ in cams} same, diff = [], []for i in range(len(cams)):for j in range(i + 1, min(len(cams), i + 40)): (ri, ti), (rj, tj) = cams[i], cams[j]if abs(rj["created"] - ri["created"]) > 180:break d = float(np.linalg.norm(prints[ri["file"]] - prints[rj["file"]])) (same if ti["moment"] == tj["moment"] else diff).append(d)# Also neighbours across moments regardless of time, for a harder negative set. across = []for i in range(len(cams) - 1): (ri, ti), (rj, tj) = cams[i], cams[i + 1]if ti["moment"] != tj["moment"]: across.append(float(np.linalg.norm(prints[ri["file"]] - prints[rj["file"]]))) look = dict(print_length=int(len(next(iter(prints.values())))) if prints else0, same_moment_pairs=len(same), different_moment_pairs_within_3min=len(diff), same_median=float(np.median(same)) if same elseNone, next_moment_median=float(np.median(across)) if across elseNone)if same and across: best = Nonefor th in np.quantile(np.concatenate([same, across]), np.linspace(0.01, 0.99, 197)): tp = sum(d < th for d in same) fp = sum(d < th for d in diff) p = tp / (tp + fp) if tp + fp else0 rc = tp / len(same)if p >= 0.99and (best isNoneor rc > best["recall"]): best = dict(threshold=float(th), precision=round(p, 4), recall=round(rc, 4)) look["at_precision_99"] = best look["auc_same_vs_next_moment"] = auc(same, across) out["look_alike"] = look# Blur and dark (camera shots only; a dark shot is not also counted as blurred). blurred = [r["sharpness"] for r, t in cams if t.get("blurred") andnot t.get("dark")] sharp = [r["sharpness"] for r, t in cams ifnot t.get("blurred") andnot t.get("dark")] out["blur"] = dict(blurred=len(blurred), sharp=len(sharp), auc=auc(blurred, sharp), **best_cut(blurred, sharp)) if blurred elseNone dark = [r["light"] for r, t in cams if t.get("dark")] lit = [r["light"] for r, t in cams ifnot t.get("dark")] out["dark"] = dict(dark=len(dark), auc=auc(dark, lit), **best_cut(dark, lit)) if dark elseNone aes_b = [r["aesthetic"] for r, t in cams if (t.get("blurred") or t.get("dark")) and r.get("aesthetic") isnotNone] aes_g = [r["aesthetic"] for r, t in cams ifnot (t.get("blurred") or t.get("dark")) and r.get("aesthetic") isnotNone] out["aesthetic_auc_bad_vs_good"] = auc(aes_b, aes_g)# Screenshots, documents, WhatsApp copies. by_kind = defaultdict(list)for r, t in met:if t: by_kind[t["kind"]].append(r)def share(rs, f):return round(sum(1for r in rs if f(r)) / len(rs), 4) if rs elseNone out["screenshots"] = dict(count=len(by_kind["screenshot"]), subtype=share(by_kind["screenshot"], lambda r: r["flags"] & 1), utility=share([r for r in by_kind["screenshot"] if r["state"] == 1], lambda r: r.get("utility"))) out["documents"] = dict(count=len(by_kind["document"]), outline=share([r for r in by_kind["document"] if r["state"] == 1], lambda r: r.get("document")), utility=share([r for r in by_kind["document"] if r["state"] == 1], lambda r: r.get("utility")), camera_outline=share([r for r, _ in cams], lambda r: r.get("document")), camera_utility=share([r for r, _ in cams], lambda r: r.get("utility"))) out["whatsapp"] = dict(count=len(by_kind["whatsapp"]), long_edge_1600=share(by_kind["whatsapp"], lambda r: max(r["w"], r["h"]) == 1600), not_camera_roll=share(by_kind["whatsapp"], lambda r: r["flags"] & (1 << 12))) out["videos"] = dict(count=len(by_kind["video"]), exact_size=share(by_kind["video"], lambda r: r["exact"])) out["exact_sizes"] = share(rows, lambda r: r["exact"])# Faces: match each drawn face to a found one by centre distance, then score vectors by size. found_by_size = defaultdict(lambda: [0, 0]) vecs, labels, sizes = [], [], []for r, t in looked:if t["kind"] notin ("camera", "whatsapp"):continue W, H = t["size"] 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 bucket = 24if s < 32else32if s < 48else48if s < 64else64if s < 112else112# The size the model saw: the face in the picture the phone gave (360 px long edge). found_by_size[bucket][1] += 1 best, bd = None, 1e9for 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, dif best isNone:continue used.add(best) found_by_size[bucket][0] += 1 f = faces[best]if f.get("vector"): vecs.append(np.asarray(f["vector"], np.float32)) labels.append(p["identity"]) sizes.append(f["pixels"]) out["faces_found_by_drawn_size"] = {str(k): dict(found=v[0], drawn=v[1], recall=round(v[0] / v[1], 4) if v[1] elseNone)for k, v in sorted(found_by_size.items())}if len(vecs) > 10: V = np.stack(vecs) V /= np.linalg.norm(V, axis=1, keepdims=True) L = np.asarray(labels) S = np.asarray(sizes) sims = V @ V.T iu = np.triu_indices(len(L), 1) same_id = (L[:, None] == L[None, :])[iu] gen, imp = sims[iu][same_id], sims[iu][~same_id] th = float(np.quantile(imp, 1 - 1e-3)) if len(imp) elseNone faces = dict(vectors=len(L), identities=len(set(labels)), threshold_far_1e3=th, tar_at_far_1e3=round(float((gen > th).mean()), 4) if len(gen) elseNone)# By the size the model's crop came from (pixels across in the picture looked at).for lo, hi in ((48, 64), (64, 96), (96, 1e9)): m = (S >= lo) & (S < hi) mm = (m[:, None] & m[None, :])[iu] g = sims[iu][same_id & mm] faces[f"tar_from_{lo}px"] = dict(pairs=int(len(g)), tar=round(float((g > th).mean()), 4) if len(g) elseNone) out["face_vectors"] = faces text = json.dumps(out, indent=2) print(text)if a.out: open(a.out, "w").write(text)if __name__ == "__main__": sys.exit(main())