Cotton code
226 lines · 9.0 KB · PythonRaw
#!/usr/bin/env python3"""People on a synthetic library: how well face grouping and "Is this X?" suggestions work on real vectors.    python3 scripts/albums-people-score.py --export <albums-export.jsonl> --truth <truth.jsonl>        [--contacts <contacts.json>] [--out people.json]The export's face vectors come from the phone's whole chain (Vision's face and five points, the crop, the face model;or the Mac harness running the same code). Faces meet the truth's drawn people by position (as albums-score.py does).Grouping is the prototype's leader clustering (assets/design/albums/proto, `people`): faces in order of capturequality, each joins the nearest group whose running centroid is at least JOIN in cosine, else starts its own; thengroups whose centroids are at least MERGE apart are merged once. A person is shown when their group has at least`--shown` faces. Measured over a range of JOIN values:  - BCubed precision and recall over the faces (precision: of the faces grouped with a face, the share that are    really that person; recall: of a person's faces, the share in the face's own group);  - groups shown, against people with that many faces, and how pure the shown groups are;  - people split across shown groups, and shown groups that mix people.Suggestions ("Is this Asha?", DECISIONS §6): a contact picture's vector is compared with every shown group's centroid;the nearest is suggested when its cosine distance is at most SUGGEST_MAX_DISTANCE and the second nearest is at leastSUGGEST_MARGIN further (the core's rules/media/people.rs, both constants), scored for the core's own constants and forconstants tuned to this model."""import argparseimport jsonfrom collections import Counter, defaultdictimport numpy as npdef labelled(export, truth):    """Face vectors with the identity of the drawn person each one is."""    tr = {}    for line in open(truth):        t = json.loads(line)        tr[t["file"]] = t    vecs, labels, quality, where = [], [], [], []    for line in open(export):        r = json.loads(line)        t = tr.get(r.get("file"))        if not t or r.get("state") != 1:            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)                vecs.append(v / np.linalg.norm(v))                labels.append(p["identity"])                quality.append(f.get("quality") or 0)                where.append(r["file"])    return np.stack(vecs), np.asarray(labels), np.asarray(quality), wheredef leader(V, quality, join, merge):    order = np.argsort(-quality)    cents, counts, label = [], [], np.full(len(V), -1)    for i in order:        if cents:            C = np.stack(cents)            sims = C @ V[i]            j = int(np.argmax(sims))            if sims[j] >= join:                counts[j] += 1                cents[j] = cents[j] + (V[i] - cents[j]) / counts[j]                label[i] = j                continue        cents.append(V[i].copy())        counts.append(1)        label[i] = len(cents) - 1    # One merge pass: groups whose centroids are close enough become one (largest first).    if merge is not None and len(cents) > 1:        C = np.stack([c / np.linalg.norm(c) for c in cents])        parent = list(range(len(cents)))        def find(a):            while parent[a] != a:                parent[a] = parent[parent[a]]                a = parent[a]            return a        S = C @ C.T        iu = np.argwhere(np.triu(S, 1) >= merge)        for a, b in iu:            ra, rb = find(a), find(b)            if ra != rb:                parent[rb] = ra        label = np.asarray([find(l) for l in label])    return labeldef bcubed(pred, truth):    p = r = 0.0    by_pred = defaultdict(list)    by_true = defaultdict(list)    for i, (a, b) in enumerate(zip(pred, truth)):        by_pred[a].append(i)        by_true[b].append(i)    for i, (a, b) in enumerate(zip(pred, truth)):        same_pred = by_pred[a]        same_true = by_true[b]        both = sum(1 for j in same_pred if truth[j] == b)        p += both / len(same_pred)        r += both / len(same_true)    n = len(pred)    p, r = p / n, r / n    return p, r, 2 * p * r / (p + r) if p + r else 0def shown_stats(pred, truth, shown):    groups = defaultdict(list)    for i, g in enumerate(pred):        groups[g].append(i)    big = {g: m for g, m in groups.items() if len(m) >= shown}    people = Counter(truth)    real = {k for k, n in people.items() if n >= shown}    purity = []    mixed = 0    owner = defaultdict(set)    for g, m in big.items():        c = Counter(truth[i] for i in m)        top, n = c.most_common(1)[0]        purity.append(n / len(m))        if n / len(m) < 0.9:            mixed += 1        owner[top].add(g)    split = sum(1 for k in real if len(owner.get(k, ())) > 1)    found = sum(1 for k in real if k in owner)    covered = sum(len(m) for m in big.values()) / len(pred)    return dict(shown_groups=len(big), people_with_enough_faces=len(real), people_found=found, people_split=split,                mixed_groups=mixed, purity_mean=round(float(np.mean(purity)), 4) if purity else None,                faces_in_shown_groups=round(covered, 4))def suggestions(V, pred, truth, shown, contacts, max_distance, margin):    groups = defaultdict(list)    for i, g in enumerate(pred):        groups[g].append(i)    big = [(g, m) for g, m in groups.items() if len(m) >= shown]    if not big:        return None    C = np.stack([V[m].mean(0) / np.linalg.norm(V[m].mean(0)) for _, m in big])    owner = [Counter(truth[i] for i in m).most_common(1)[0][0] for _, m in big]    right = wrong = silent = 0    for identity, vector in contacts.items():        v = np.asarray(vector, np.float32)        v /= np.linalg.norm(v)        d = 1 - C @ v        order = np.argsort(d)        first = order[0]        second = d[order[1]] if len(order) > 1 else 9        has_group = identity in owner        if d[first] <= max_distance and second - d[first] >= margin:            if owner[first] == identity:                right += 1            else:                wrong += 1        else:            silent += 1 if has_group else 0    asked = right + wrong    present = sum(1 for k in contacts if k in owner)    return dict(contacts=len(contacts), contacts_with_a_group=present, suggested=asked, right=right, wrong=wrong,                precision=round(right / asked, 4) if asked else None,                recall=round(right / present, 4) if present else None)def main():    ap = argparse.ArgumentParser()    ap.add_argument("--export", required=True)    ap.add_argument("--truth", required=True)    ap.add_argument("--contacts")    ap.add_argument("--shown", type=int, default=3)    ap.add_argument("--out")    a = ap.parse_args()    V, L, Q, _ = labelled(a.export, a.truth)    out = dict(faces=len(L), people=len(set(L)))    S = V @ V.T    iu = np.triu_indices(len(L), 1)    same = (L[:, None] == L[None, :])[iu]    out["cosine_same_person_median"] = round(float(np.median(S[iu][same])), 4)    out["cosine_different_median"] = round(float(np.median(S[iu][~same])), 4)    out["cosine_different_p999"] = round(float(np.quantile(S[iu][~same], 0.999)), 4)    runs = []    for join in (0.25, 0.3, 0.35, 0.4, 0.45, 0.5):        for merge in (None, join + 0.1):            pred = leader(V, Q, join, merge)            p, r, f = bcubed(pred, L)            runs.append(dict(join=join, merge=merge, bcubed_precision=round(p, 4), bcubed_recall=round(r, 4),                             bcubed_f=round(f, 4), groups=int(len(set(pred))), **shown_stats(pred, L, a.shown)))    out["grouping"] = runs    best = max(runs, key=lambda x: (x["bcubed_precision"] >= 0.99, x["bcubed_f"]))    out["chosen"] = best    if a.contacts:        contacts = json.load(open(a.contacts))        pred = leader(V, Q, best["join"], best["merge"])        out["suggestions_core_constants"] = suggestions(V, pred, L, a.shown, contacts, 0.45, 0.05)        tuned = []        for md in (0.5, 0.55, 0.6, 0.65, 0.7):            for mg in (0.03, 0.05, 0.08, 0.1):                s = suggestions(V, pred, L, a.shown, contacts, md, mg)                tuned.append(dict(max_distance=md, margin=mg, **s))        out["suggestions_tuned"] = [t for t in tuned if t["precision"] is not None]    text = json.dumps(out, indent=2)    print(text)    if a.out:        open(a.out, "w").write(text)if __name__ == "__main__":    main()