Full face stack that runs entirely in the browser. Detection, 576-point 3D mesh, recognition, anti-spoof, smile — all WebAssembly, zero server. Apache 2.0.
C avx-512avx2biometricsc99computer-visioncpu-inferencedeep-learningedge-aiembedded-aiface-embeddingface-recognitionface-verificationlow-latencyonnx-runtimeproduction-readysimdzero-dependencies
Identify people across multiple enrollment photos
Baurzhan Atynoveca012127d81
diff --git a/python/README.md b/python/README.mdindex 025161d..e9f2793 100644--- a/python/README.md+++ b/python/README.md@@ -222,3 +222,26 @@ can require rescoring the entire gallery. Both implementations now use the samerow-wise summation order for final scores and break equal scores by enrollmentorder. At a floating-point decision boundary a score can differ in the lastbits from older releases.++### Identify a person across multiple enrollment photos++Use IdentityGallery when a person has multiple reference photos. Supply the+same nonnegative integer ID for all rows belonging to that person. The score+for each person is the maximum cosine across their views. The margin is the+difference between the two best people. A tied best score or a zero query+returns -1. A single registered person requires a zero margin to match.++```python+from facex import IdentityGallery++gallery = IdentityGallery(enrollment_embeddings, person_ids)+ids = gallery.identify(query_embeddings, min_score=0.85, min_margin=0.05)+```++The thresholds above are examples. Calibrate them with separate queries+representative of the deployment. The gallery keeps the original float32+enrollment snapshot for exact fallback and stores up to eight representative+views per person for screening. Rebuild after enrollment changes.+To inspect how often screening suffices, call+`ids, resolved = gallery.screen(query_embeddings, min_score=0.85, min_margin=0.05)`.+A false mask entry requires exact lookup even though its placeholder ID is -1.diff --git a/python/facex/__init__.py b/python/facex/__init__.pyindex 61d9e48..f21998d 100644--- a/python/facex/__init__.py+++ b/python/facex/__init__.py@@ -11,6 +11,7 @@ Usage:from facex.core import FaceX, similarityfrom facex.gallery import CompactGallery, Gallery, enrollment_template+from facex.identity import IdentityGallery__version__ = "0.1.0"-__all__ = ["FaceX", "CompactGallery", "Gallery", "enrollment_template", "similarity"]+__all__ = ["FaceX", "IdentityGallery", "CompactGallery", "Gallery", "enrollment_template", "similarity"]diff --git a/python/facex/identity.py b/python/facex/identity.pynew file mode 100644index 0000000..c97b386--- /dev/null+++ b/python/facex/identity.py@@ -0,0 +1,131 @@+"""Threshold identification with multiple enrollment rows per identity."""+import operator++import numpy as np++from .gallery import CompactGallery, _unit_rows+++# Round the angular inputs outwards before evaluating the cap bound. Padding+# only the final score loses accuracy near a zero or pi angle.+_PAD = 1e-12+++def _caps(rows, limit, rng):+ sample_ids = rng.choice(len(rows), min(len(rows), max(128, limit)), replace=False)+ sample = _unit_rows(rows[sample_ids])+ chosen = [0]+ nearest = sample @ sample[0]+ while len(chosen) < min(limit, len(sample)):+ nxt = nearest.argmin()+ if nearest[nxt] >= 1 - _PAD:+ break+ chosen.append(nxt)+ nearest = np.maximum(nearest, sample @ sample[nxt])+ axes = sample[chosen].copy()+ labels = (sample @ axes.T).argmax(axis=1)+ for i in range(len(axes)):+ members = sample[labels == i]+ axes[i] = members[(members @ members.mean(axis=0)).argmax()]+ cosines = np.ones(len(axes))+ for start in range(0, len(rows), 256):+ dots = _unit_rows(rows[start:start+256]) @ axes.T+ labels = dots.argmax(axis=1)+ np.minimum.at(cosines, labels, dots[np.arange(len(dots)), labels])+ return axes, np.clip(cosines - _PAD, -1, 1)+++class IdentityGallery:+ """Fixed gallery of nonnegative int64 identity IDs with one or more views each.++ The identity score is the maximum cosine across its enrollment rows.+ The runner-up is always a different identity. A tied best score abstains.+ """++ def __init__(self, embeddings, identity_ids, *, max_caps=8):+ rows = np.asarray(embeddings)+ labels = np.asarray(identity_ids)+ cap_count = operator.index(max_caps)+ if rows.ndim != 2 or not len(rows):+ raise ValueError("Expected a nonempty enrollment matrix")+ if labels.shape != (len(rows),) or labels.dtype.kind not in "iu":+ raise ValueError("Expected one integer identity ID per enrollment row")+ if labels.min() < 0 or int(labels.max()) > np.iinfo(np.int64).max:+ raise ValueError("Identity IDs must fit in nonnegative int64")+ if cap_count < 1:+ raise ValueError("max_caps must be positive")++ order = np.argsort(labels, kind="stable")+ self._ids, counts = np.unique(labels, return_counts=True)+ self._ids = self._ids.astype(np.int64)+ self._galleries = []+ axes, cosines, starts = [], [], []+ offset = 0+ cap_offset = 0+ rng = np.random.default_rng(2026)+ for count in counts:+ group = rows[order[offset:offset+count]]+ self._galleries.append(CompactGallery(group))+ directions, limits = _caps(group, cap_count, rng)+ starts.append(cap_offset)+ axes.append(directions)+ cosines.append(limits)+ offset += count+ cap_offset += len(limits)+ self._starts = np.array(starts)+ self._axes = np.concatenate(axes)+ self._cos = np.concatenate(cosines)+ self._sin = np.sqrt((1 - self._cos) * (1 + self._cos))++ def screen(self, queries, *, min_score, min_margin):+ """Return (IDs, resolved mask). Resolved -1 is a rejection.++ Unresolved rows also carry -1 and require exact lookup. identify()+ performs that lookup automatically.+ """+ if not -1 <= min_score <= 1 or not 0 <= min_margin <= 2:+ raise ValueError("Invalid cosine score or margin threshold")+ unit = _unit_rows(queries)+ ids = np.full(len(unit), -1, dtype=np.int64)+ resolved = np.ones(len(unit), dtype=bool)+ for i, q in enumerate(unit):+ if not q.any() or (len(self._ids) == 1 and min_margin > 0):+ continue+ dots = self._axes @ q+ low = np.maximum.reduceat(dots - _PAD, self._starts)+ d = np.clip(dots + _PAD, -1, 1)+ upper = np.where(d >= self._cos, 1.,+ d * self._cos + np.sqrt((1 - d) * (1 + d)) * self._sin)+ high = np.maximum.reduceat(upper + _PAD, self._starts)+ if high.max() < min_score:+ continue+ winner = low.argmax()+ high[winner] = -np.inf+ gap = low[winner] - high.max()+ if low[winner] >= min_score and gap > 0 and gap >= min_margin:+ ids[i] = self._ids[winner]+ else:+ resolved[i] = False+ return ids, resolved++ def identify(self, queries, *, min_score, min_margin):+ """Return exact threshold decisions, with -1 for rejection."""+ queries = np.asarray(queries)+ ids, resolved = self.screen(queries, min_score=min_score, min_margin=min_margin)+ remaining = np.flatnonzero(~resolved)+ if not len(remaining):+ return ids+ pending = queries[remaining]+ best = np.full(len(pending), -np.inf)+ second = best.copy()+ winner = np.empty(len(pending), dtype=np.int64)+ for identity, gallery in zip(self._ids, self._galleries):+ _, scores = gallery.search(pending, 1)+ score = scores[:, 0]+ improved = score > best+ second = np.where(improved, best, np.maximum(second, score))+ best = np.maximum(best, score)+ winner[improved] = identity+ accepted = (best >= min_score) & (best > second) & (best - second >= min_margin)+ ids[remaining[accepted]] = winner[accepted]+ return idsdiff --git a/tests/test_identity_gallery.py b/tests/test_identity_gallery.pynew file mode 100644index 0000000..3a23632--- /dev/null+++ b/tests/test_identity_gallery.py@@ -0,0 +1,89 @@+import unittest++import numpy as np++from facex import IdentityGallery+++def oracle(rows, labels, queries, threshold, margin):+ rows = rows.astype('d')+ rows /= np.linalg.norm(rows, axis=1)[:, None]+ ids = np.unique(labels)+ results = []+ for q in queries.astype('d'):+ norm = np.linalg.norm(q[None], axis=1)[0]+ if not norm or (len(ids) == 1 and margin > 0):+ results.append(-1)+ continue+ cosine = np.clip(np.sum(rows * (q / norm), axis=1), -1, 1)+ scores = np.array([cosine[labels == i].max() for i in ids])+ order = np.argsort(-scores, kind='stable')+ gap = scores[order[0]] - scores[order[1]] if len(ids) > 1 else np.inf+ results.append(ids[order[0]] if scores[order[0]] >= threshold+ and gap > 0 and gap >= margin else -1)+ return results+++class IdentityGalleryTest(unittest.TestCase):+ def test_same_identity_ties_and_exact_thresholds(self):+ rows = np.eye(4, 512, dtype='f')+ labels = np.array([41, 7, 41, 99])+ rows[2] = rows[0]+ index = IdentityGallery(rows, labels)+ query = rows[[0]]+ np.testing.assert_array_equal(index.identify(query, min_score=1, min_margin=1), [41])+ np.testing.assert_array_equal(index.identify(query, min_score=1,+ min_margin=np.nextafter(1., 2.)), [-1])+ rows[3] = rows[0]+ tied = IdentityGallery(rows, labels)+ np.testing.assert_array_equal(tied.identify(query, min_score=1, min_margin=0), [-1])+ np.testing.assert_array_equal(index.identify(query, min_score=1, min_margin=1), [41])++ def test_mixed_queries(self):+ rng = np.random.default_rng(28)+ data = rng.normal(size=(150, 512)).astype('f')+ data[0] *= 1e-35+ data[-1] *= 1e30+ labels = np.tile([8, 13, 99], 50)+ queries = np.vstack((data[::9], np.zeros((1,512), 'f'),+ rng.normal(size=(29,512)).astype('f')))[:, ::-1]+ rows = data[:, ::-1]+ for caps in (1, 8):+ gallery = IdentityGallery(rows, labels, max_caps=caps)+ for threshold, margin in ((-1, 0), (.75, .05), (1, 0), (.1, .02)):+ kw = dict(min_score=threshold, min_margin=margin)+ expected = np.array(oracle(rows, labels, queries, threshold, margin))+ got = gallery.identify(queries, **kw)+ ids, resolved = gallery.screen(queries, **kw)+ np.testing.assert_array_equal(expected[resolved], ids[resolved])+ np.testing.assert_array_equal(expected, got)++ def test_unresolved_can_accept_or_reject(self):+ first, second, other = np.eye(3, 512, dtype="f")+ rows = np.stack((first, second, other))+ gallery = IdentityGallery(rows, [10, 10, 20], max_caps=1)+ # One cap contains two orthogonal views. Its witness misses one of them.+ kw = dict(min_score=.9, min_margin=.05)+ _, flags = gallery.screen(rows[:2], **kw)+ self.assertEqual(int(flags.sum()), 1)+ np.testing.assert_array_equal(gallery.identify(rows[:2], **kw), [10, 10])+ midpoint = ((first + second) / np.sqrt(2))[None]+ _, flags = gallery.screen(midpoint, **kw)+ self.assertFalse(flags[0])+ np.testing.assert_array_equal(gallery.identify(midpoint, **kw), [-1])++ def test_single_identity_and_empty_batch(self):+ row = np.eye(1, 512, dtype='f')+ gallery = IdentityGallery(row, [200])+ for threshold, margin, answer in ((1, 0, 200), (1, .01, -1)):+ kw = dict(min_score=threshold, min_margin=margin)+ np.testing.assert_array_equal(gallery.identify(row, **kw), [answer])+ np.testing.assert_array_equal(gallery.identify(row * 0, **kw), [-1])+ self.assertEqual(gallery.identify(row[:0], **kw).shape, (0,))+ for bad in ([-1], [2.5], [], [2**63]):+ with self.assertRaises(ValueError):+ IdentityGallery(row, bad)+++if __name__ == '__main__':+ unittest.main()