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
Feed YuNet BGR pixels and calibrate the detection threshold
Baurzhan Atynov2daaee4967ce
diff --git a/docker/server.py b/docker/server.pyindex 888c240..81e017f 100644--- a/docker/server.py+++ b/docker/server.py@@ -139,7 +139,7 @@ def detect():try:if _detector is None:engine = FaceX(embed_weights=EMBED_WEIGHTS, detect_weights=DETECT_WEIGHTS,- input_policy="rectangle", license_key=os.environ.get("LICENSE_KEY"))+ input_policy="rectangle_bgr", license_key=os.environ.get("LICENSE_KEY"))if engine.backend != "ctypes":raise RuntimeError("Missing native FaceX library")_detector = enginediff --git a/docs/research/yunet_eight_bottlenecks.md b/docs/research/yunet_eight_bottlenecks.mdnew file mode 100644index 0000000..6f12dfd--- /dev/null+++ b/docs/research/yunet_eight_bottlenecks.md@@ -0,0 +1,69 @@+# Eight bottlenecks in small face detection++The reference is the rectangular RGB YuNet path from cb672bee with score 0.58, NMS IoU 0.40 and up to 32 detections. Each experiment changes one element plus an independently calibrated score threshold. The recognition network and pixel budget stay fixed.++| Trial | Mechanism | Candidate change |+|---|---|---|+| Minimum side | A candidate disappears when either predicted side falls below the hard minimum | Lower the cutoff from 16 to 8 canvas pixels |+| Aspect ratio | Strongly elongated boxes fail the aspect filter | Widen the accepted width/height interval from [0.30, 3.0] to [0.18, 4.0] |+| Box suppression | Two nearby faces can suppress each other through IoU | Raise the suppression threshold from 0.40 to 0.55 |+| Landmark suppression | Fixed pixel distances merge nearby people regardless of face size | Scale nose and eye midpoint distances to 0.25 and 0.20 times the smaller geometric mean box side |+| Output limit | Dense scenes can exceed the 32 result slots | Admit 128 sorted boxes |+| Scale dependent confidence | A common threshold can disadvantage small boxes | Multiply score by 1.10 for candidates with a side below 32 pixels, cap at one before ranking |+| Box calibration | Correct centers may still miss IoU 0.5 because of size bias | Expand each side outwards by 4% of width or height after suppression |+| Channel order | First layer weights may respond differently to channel order | Supply BGR to the detector while retaining the original RGB image for alignment |++## Evaluation++WIDER FACE validation. Exclude the 640 evaluation images and 128 calibration images used in the rectangular input experiment. Draw 672 other images without replacement with seed 3519. The first 160 are for calibration and the remaining 512 for evaluation. This split isolates the eight-way comparison within this experiment. Images come from the same validation dataset.++For each variant select the score threshold on a 0.01 grid from 0.40 to 0.91 to maximize small matches under the baseline calibration false-positive count. Break ties using total matches and then proximity to 0.58. Select one primary variant by calibration small matches before scoring the evaluation images. Report all eight with frozen thresholds. The baseline uses 0.58 throughout.++The reference C head emits all positive-size candidates with score at least 0.30 in the experimental build. Replay uses stable descending score order followed by the native geometry filters, greedy box suppression, landmark suppression and output cap. Every thirteenth image is checked against the unmodified native detector. Boxes are mapped and clipped to original coordinates. One-to-one IoU ≥ 0.50 matching uses valid annotations. Unmatched detections include predictions on ignored annotations. A small face has geometric mean side below 16 pixels after scaling the long side of the original image to 320. These are fixed operating point counts. They are not official WIDER AP.++## Reproduction++Run from a checkout containing the reference commit, with GCC, NumPy, SciPy, Pillow, native YuNet 2023mar weights and both WIDER validation archives.++```sh+OPENBLAS_NUM_THREADS=1 python tests/bench_yunet_bottlenecks.py yunet.bin WIDER_val.zip wider_face_split.zip+```++## Results on the 512 evaluation images++There are 5173 valid faces including 4328 small faces. Thresholds were calibrated using 160 other images; the reference calibration count was 31 unmatched predictions. Changing the threshold along with each variant measures its deployable operating point.++| Trial | Score | Total matches | Small matches | Unmatched |+|---|---:|---:|---:|---:|+| Reference | 0.58 | 1306 | 686 | 94 |+| Minimum side 8 | 0.62 | 1317 | 703 | 80 |+| Wider aspect range | 0.58 | 1306 | 686 | 94 |+| NMS IoU 0.55 | 0.58 | 1306 | 686 | 95 |+| Relative landmark distances | 0.59 | 1313 | 691 | 95 |+| Result limit 128 | 0.59 | 1300 | 681 | 85 |+| Small box score bonus | 0.63 | 1295 | 685 | 93 |+| Box expansion | 0.60 | 1281 | 670 | 89 |+| Detector BGR | 0.66 | 1728 | 996 | 106 |++BGR was selected on calibration images before evaluation. At 0.66 the paired 95% image bootstrap interval was +248 to +374 small matches and −22 to +46 unmatched predictions relative to RGB. Lowering the minimum size gave +17 small matches with a paired interval of −4 to +42. The cap trial includes a threshold increase from 0.58 to 0.59 to respect the calibration budget; the comparison does not imply that a larger output buffer by itself loses detections.++On the RGB reference, an oracle that discards every incorrect candidate and optimally assigns the remainder to small annotations could match at most 1066 of 4328 at score ≥0.30, before any suppression or geometry filters. At score ≥0.58 that ceiling was 760; a minimum side of 8 gave 760 and a minimum side of 16 gave 706. This ceiling applies only to the RGB candidate boxes, channel order, score floor and IoU criterion tested.++## Independent color confirmation and release decision++The first comparison gained matches but showed 12 additional unmatched predictions. For the REST operating point we tightened the original calibration budget to 75% of baseline (at most 23 unmatched predictions on the same 160 calibration images) and selected 0.70. We then evaluated 384 further images, drawn with seed 9101 outside all the earlier splits. There were 4114 valid faces including 3411 small faces.++| Detector input and score | Total matches | Small matches | Unmatched |+|---|---:|---:|---:|+| RGB 0.58 | 1061 | 548 | 58 |+| BGR 0.58 | 1399 | 776 | 109 |+| BGR 0.66 | 1365 | 749 | 76 |+| BGR 0.70 | 1344 | 734 | 56 |++At 0.70 the gain was 186 small faces (+33.9%, recall 16.1% to 21.5%). The paired 95% image bootstrap intervals were +129 to +255 small matches, +222 to +358 total matches and −22 to +19 unmatched predictions. The observed difference of two fewer unmatched predictions is within sampling uncertainty. A separate alternating 48-image, single-core Linux CPU run of preprocessing plus native detection measured median 75.31 ms for RGB and 76.22 ms for BGR; neither embedding nor JPEG decoding was timed.++REST selects BGR 0.70 for the detector only. Input to the SDK, source coordinates, alignment and embedding use the original RGB image. Existing SDK policies retain their original thresholds and behavior. API integration was checked on landscape, portrait and square images against a direct native call with explicit channel reversal, including all embedding components.++```sh+OPENBLAS_NUM_THREADS=1 python tests/verify_yunet_color.py yunet.bin WIDER_val.zip wider_face_split.zip+```diff --git a/python/README.md b/python/README.mdindex eee5937..711d6c8 100644--- a/python/README.md+++ b/python/README.md@@ -46,18 +46,20 @@ Install the image extra for Pillow and build the shared library from this versio```pythonfx = FaceX(embed_weights="weights/edgeface_xs_fp32.bin",detect_weights="weights/yunet_fp32.bin",- input_policy="rectangle")+ input_policy="rectangle_bgr")faces = fx.detect(image)```-The detector uses up to 409600 input pixels and a default score threshold of 0.58.+Pass RGB images to the SDK. The detector receives BGR internally and uses up to+409600 input pixels with a calibrated score threshold of 0.70. The previous+RGB rectangle policy remains available as `input_policy="rectangle"` at 0.58.For a 1920 × 1080 source it resizes to 832 × 468 and centers that image on an832 × 480 canvas. Boxes and five keypoints use original image coordinates.Alignment and embedding sample the original RGB pixels. Set `score_threshold`explicitly to override the calibrated threshold. Existing SDK callers use nativeimage dimensions by default.-The Docker REST service uses the rectangle policy for `POST /detect` and returns+The Docker REST service uses the BGR rectangle policy for `POST /detect` and returnsup to 32 faces. Mount both weights at the paths above under `/app`, or set`EMBED_WEIGHTS` and `DETECT_WEIGHTS` to their paths inside the container.diff --git a/python/facex/core.py b/python/facex/core.pyindex cd7bec4..dc281a8 100644--- a/python/facex/core.py+++ b/python/facex/core.py@@ -19,6 +19,7 @@ import numpy as np# ---------------------------------------------------------------------------EMBEDDING_DIM = 512MAX_FACES_DEFAULT = 20+_POLICY_THRESHOLDS = {"native": 0.5, "rectangle": 0.58, "rectangle_bgr": 0.70}# FaceXResult struct layout:# float x1, y1, x2, y2, score (5 floats = 20 bytes)@@ -204,8 +205,8 @@ class FaceX:embed_weights: Path to embedding weights. Auto-detected if None.detect_weights: Path to detector weights. Auto-detected if None.license_key: License key for encrypted weights (None for plain).- score_threshold: Defaults to 0.58 for rectangle input and 0.5 for native input.- input_policy: Use "rectangle" for budgeted YuNet inference or "native" for original dimensions.+ score_threshold: Override the score threshold calibrated for the selected input policy.+ input_policy: Use "native", "rectangle" (RGB), or "rectangle_bgr" (YuNet 2023mar).nms_threshold: NMS IoU threshold (default 0.4).max_faces: Maximum faces to detect per image (default 20)."""@@ -226,11 +227,11 @@ class FaceX:self._handle = Noneself._cli_path = cli_pathself._max_faces = max_faces- if input_policy not in ("rectangle", "native"):+ if input_policy not in _POLICY_THRESHOLDS:raise ValueError("Unknown detector input policy")self._input_policy = input_policyif score_threshold is None:- score_threshold = 0.58 if input_policy == "rectangle" else 0.5+ score_threshold = _POLICY_THRESHOLDS[input_policy]self._score_threshold = score_thresholdself._nms_threshold = nms_threshold@@ -310,7 +311,7 @@ class FaceX:]self._lib.facex_set_nms_threshold.restype = None- if self._input_policy == "rectangle":+ if self._input_policy != "native":if not hasattr(self._lib, "facex_detect_prepared"):raise RuntimeError("Rectangle input requires a library with facex_detect_prepared")image_ptr = ctypes.POINTER(ctypes.c_uint8)@@ -369,7 +370,7 @@ class FaceX:h, w = image.shape[:2]mf = max_faces or self._max_faces- if self._input_policy == "rectangle" and self.backend != "ctypes":+ if self._input_policy != "native" and self.backend != "ctypes":raise RuntimeError("Rectangle input requires the native FaceX shared library")if self._lib and self._handle:return self._detect_ctypes(image, w, h, mf)@@ -383,9 +384,9 @@ class FaceX:def _detect_ctypes(self, image: np.ndarray, w: int, h: int, max_faces: int) -> List[dict]:results = (FaceXResult * max_faces)()ptr = image.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8))- if self._input_policy == "rectangle":+ if self._input_policy != "native":from .yunet import prepare_rectangle- canvas, rw, rh = prepare_rectangle(image)+ canvas, rw, rh = prepare_rectangle(image, bgr=self._input_policy == "rectangle_bgr")ch, cw = canvas.shape[:2]n = self._lib.facex_detect_prepared(self._handle, ptr, w, h,diff --git a/python/facex/yunet.py b/python/facex/yunet.pyindex c2e69fa..1e35e91 100644--- a/python/facex/yunet.py+++ b/python/facex/yunet.py@@ -13,11 +13,12 @@ def rectangle_shape(w, h):return rw, rh, (rw + 31) // 32 * 32, (rh + 31) // 32 * 32-def prepare_rectangle(image):+def prepare_rectangle(image, *, bgr=False):h, w = image.shape[:2]rw, rh, cw, ch = rectangle_shape(w, h)x, y = (cw - rw) // 2, (ch - rh) // 2canvas = np.zeros((ch, cw, 3), dtype=np.uint8)bicubic = getattr(Image, "Resampling", Image).BICUBIC- canvas[y:y + rh, x:x + rw] = Image.fromarray(image).resize((rw, rh), bicubic)+ pixels = np.asarray(Image.fromarray(image).resize((rw, rh), bicubic))+ canvas[y:y + rh, x:x + rw] = pixels[:, :, ::-1] if bgr else pixelsreturn canvas, rw, rhdiff --git a/tests/bench_yunet_bottlenecks.py b/tests/bench_yunet_bottlenecks.pynew file mode 100644index 0000000..da569d0--- /dev/null+++ b/tests/bench_yunet_bottlenecks.py@@ -0,0 +1,186 @@+"""Evaluate eight independent changes to the rectangular YuNet operating point."""+import argparse+import ctypes+import io+from pathlib import Path+import subprocess+import sys+import tempfile+from zipfile import ZipFile++import numpy as np+from PIL import Image+from verify_yunet import ROOT, annotations, match, native_run++sys.path.insert(0, str(ROOT / "python"))+from facex.yunet import prepare_rectangle++MODES = ("baseline", "min8", "wide_aspect", "iou55", "relative_merge",+ "limit128", "small_score", "box_expand", "bgr")+GRID = np.round(np.arange(.40, .911, .01), 2)+++def load_lib(tmp, name, raw=False):+ # Build the exact reference revision so historical results remain reproducible.+ src = subprocess.check_output(["git", "show", "cb672bee:src/detect.c"], cwd=ROOT, text=True)+ if raw:+ start = src.index(" if (bw < 16")+ end = src.index(" candidates[nf].score", start)+ src = src[:start] + " if (bw <= 0 || bh <= 0) continue;\n" + src[end:]+ start = src.index(" if (nf > 1) nf = nms_sort")+ end = src.index(" if (nf > max_faces)", start)+ src = src[:start] + src[end:]+ file = tmp / (name + ".c")+ file.write_text(src)+ so = tmp / (name + ".so")+ subprocess.run(["gcc", "-O3", "-march=native", "-I", str(ROOT / "include"),+ "-shared", "-fPIC", str(file), "-lm", "-o", str(so)], check=True)+ lib = ctypes.CDLL(str(so))+ lib.detect_init.restype = ctypes.c_void_p+ return lib+++def suppress(rows, overlaps):+ active = np.ones(len(rows), dtype=bool)+ for i in range(len(rows)):+ if active[i]:+ active[i+1:] &= ~overlaps[i, i+1:]+ return rows[active]+++def replay(raw, mode, cw, ch):+ rows = raw.copy()+ dims = rows[:, 2:4] - rows[:, :2]+ w, h = dims.T+ aspect = w / (h + 1e-6)+ lo, hi = (.18, 4.) if mode == "wide_aspect" else (.3, 3.)+ minimum = 8 if mode == "min8" else 16+ ok = ((dims.min(1) >= minimum) & (w <= cw*.95) & (h <= ch*.95) &+ (aspect >= lo) & (aspect <= hi))+ rows = rows[ok]+ if mode == "small_score":+ rows[:, 4] = np.minimum(1, rows[:, 4] * np.where(dims[ok].min(1) < 32, 1.10, 1.))+ rows = rows[np.argsort(-rows[:, 4], kind="stable")]+ a = rows[:, :4]+ area = (a[:, 2:] - a[:, :2]).prod(1)+ inter = (np.minimum(a[:, None, 2:], a[None, :, 2:]) -+ np.maximum(a[:, None, :2], a[None, :, :2])).clip(0).prod(2)+ iou = inter / np.maximum(area[:, None] + area - inter, 1e-8)+ rows = suppress(rows, iou > (.55 if mode == "iou55" else .4))+ nose = rows[:, 9:11]+ eyes = (rows[:, 5:7] + rows[:, 7:9]) / 2+ sizes = np.sqrt((rows[:, 2:4] - rows[:, :2]).prod(1))+ scale = np.minimum(sizes[:, None], sizes)+ nose_bound, eye_bound = (.25*scale, .20*scale) if mode == "relative_merge" else (25, 20)+ close = (np.linalg.norm(nose[:, None] - nose, axis=2) < nose_bound) | (+ np.linalg.norm(eyes[:, None] - eyes, axis=2) < eye_bound)+ rows = suppress(rows, close)[:128 if mode == "limit128" else 32]+ if mode == "box_expand":+ margin = (rows[:, 2:4] - rows[:, :2]) * .04+ rows[:, :2] -= margin+ rows[:, 2:4] += margin+ return rows+++def source_boxes(rows, w, h, rw, rh, cw, ch):+ boxes = rows[:, :5].copy()+ for axis, original, resized, full in ((0, w, rw, cw), (1, h, rh, ch)):+ ids = [axis, axis+2]+ boxes[:, ids] = np.clip((boxes[:, ids] - (full-resized)//2) *+ (original/resized), 0, original)+ return boxes+++def extract(weights, images, labels, names, tmp):+ libs = [load_lib(tmp, name, raw) for name, raw in (("reference", False), ("candidate", True))]+ engines = [ctypes.c_void_p(lib.detect_init(bytes(weights))) for lib in libs]+ if not all(engines):+ raise RuntimeError("Cannot open weights")+ for lib, eng, threshold in zip(libs, engines, (.58, .30)):+ lib.detect_set_score_threshold(eng, ctypes.c_float(threshold))+ records = []+ try:+ for i, name in enumerate(names):+ im = Image.open(io.BytesIO(images.read("WIDER_val/images/" + name))).convert("RGB")+ w, h = im.size+ canvas, rw, rh = prepare_rectangle(np.asarray(im))+ ch, cw = canvas.shape[:2]+ rgb, bgr = [native_run(libs[1], engines[1], x, capacity=10000)+ for x in (canvas, np.ascontiguousarray(canvas[:, :, ::-1]))]+ gt = labels[name].copy()+ small = np.sqrt(gt[:, 2:4].prod(1))*320/max(w, h) < 16+ gt[:, 2:] += gt[:, :2]+ outputs = []+ for mode in MODES:+ rows = replay(bgr if mode == "bgr" else rgb, mode, cw, ch)+ if mode == "baseline" and i % 13 == 0:+ actual = native_run(libs[0], engines[0], canvas, capacity=32)+ np.testing.assert_array_equal(actual, rows[rows[:, 4] >= .58])+ outputs.append(source_boxes(rows, w, h, rw, rh, cw, ch))+ # An oracle can select any candidate and discard all false positives.+ # Restricting GT to small boxes gives an optimistic localization ceiling.+ boxes = source_boxes(rgb, w, h, rw, rh, cw, ch)+ minimum_side = (rgb[:, 2:4] - rgb[:, :2]).min(1)+ confident = rgb[:, 4] >= .58+ masks = (rgb[:, 4] >= .30, confident, confident & (minimum_side >= 8),+ confident & (minimum_side >= 16))+ oracle = [len(match(boxes[mask], gt[small])) for mask in masks]+ records.append((gt, small, outputs, oracle))+ finally:+ for lib, eng in zip(libs, engines):+ lib.detect_free(eng)+ return records+++def measure(data, mode, thresholds):+ result = np.zeros((len(data), len(thresholds), 3), dtype=int)+ for i, (gt, small, outputs, _) in enumerate(data):+ det = outputs[mode]+ by_count = {}+ for j, t in enumerate(thresholds):+ n = int((det[:, 4] >= np.float32(t)).sum())+ if n not in by_count:+ found = match(det[:n], gt)+ by_count[n] = (len(found), n - len(found), small[found].sum())+ result[i, j] = by_count[n]+ return result+++def main():+ ap = argparse.ArgumentParser(description=__doc__)+ for arg in ("weights", "images", "labels"):+ ap.add_argument(arg, type=Path)+ args = ap.parse_args()+ with ZipFile(args.labels) as archive:+ labels = annotations(archive)+ old = np.random.default_rng(114).choice(sorted(labels), 640, replace=False)+ pool = set(labels) - set(old)+ pool -= set(np.random.default_rng(725).choice(sorted(pool), 128, replace=False))+ names = np.random.default_rng(3519).choice(sorted(pool), 672, replace=False)+ with tempfile.TemporaryDirectory() as tmp, ZipFile(args.images) as photos:+ data = extract(args.weights, photos, labels, names, Path(tmp))+ dev, test = data[:160], data[160:]+ budget = measure(dev, 0, [.58]).sum(0)[0, 1]+ locked = []+ for m, name in enumerate(MODES):+ scores = measure(dev, m, GRID).sum(0)+ feasible = np.flatnonzero(scores[:, 1] <= budget)+ i = np.flatnonzero(GRID == .58)[0] if m == 0 else max(+ feasible, key=lambda j: (scores[j, 2], scores[j, 0], -abs(GRID[j]-.58)))+ locked.append((GRID[i], scores[i, 2]))+ print("dev", name, GRID[i], scores[i].tolist(), flush=True)+ winner = int(np.argmax([entry[1] for entry in locked]))+ print("locked winner", MODES[winner], flush=True)+ print("test images, annotations, small", len(test), sum(len(x[0]) for x in test),+ sum(x[1].sum() for x in test), flush=True)+ print("small candidate ceilings", np.sum([x[3] for x in test], axis=0).tolist())+ base = measure(test, 0, [.58])[:, 0]+ bootstrap = np.random.default_rng(547).integers(len(test), size=(2000, len(test)))+ for m, name in enumerate(MODES):+ counts = measure(test, m, [locked[m][0]])[:, 0]+ ci = np.percentile((counts-base)[bootstrap].sum(1), [2.5, 97.5], axis=0)+ print("test", name, counts.sum(0).tolist(), "paired interval", ci.round(1).tolist())+++if __name__ == "__main__":+ main()diff --git a/tests/verify_rectangular_client.py b/tests/verify_rectangular_client.pyindex 07d6ef5..77d46f8 100644--- a/tests/verify_rectangular_client.py+++ b/tests/verify_rectangular_client.py@@ -20,11 +20,11 @@ def main():lib.detect_init.restype = ctypes.c_void_pdet = ctypes.c_void_p(lib.detect_init(os.fsencode(os.environ["DETECT_WEIGHTS"])))assert det- lib.detect_set_score_threshold(det, ctypes.c_float(.58))+ lib.detect_set_score_threshold(det, ctypes.c_float(.70))lib.align_face.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int,ctypes.c_void_p, ctypes.c_void_p]sdk = FaceX(embed_weights=os.environ["EMBED_WEIGHTS"], detect_weights=os.environ["DETECT_WEIGHTS"],- input_policy="rectangle")+ input_policy="rectangle_bgr")client = app.test_client()patch = Image.open(ROOT / "data/test_face.jpg").convert("RGB").resize((241, 241))try:@@ -34,7 +34,7 @@ def main():rgb = np.asarray(image)canvas, rw, rh = prepare_rectangle(rgb)ch, cw = canvas.shape[:2]- expected = native_run(lib, det, canvas)+ expected = native_run(lib, det, np.ascontiguousarray(canvas[:, :, ::-1]))faces = sdk.detect(rgb)assert len(expected) == len(faces) > 0for row, face in zip(expected, faces):diff --git a/tests/verify_yunet_color.py b/tests/verify_yunet_color.pynew file mode 100644index 0000000..b2b8577--- /dev/null+++ b/tests/verify_yunet_color.py@@ -0,0 +1,80 @@+"""Confirm the selected detector channel order on a further disjoint image subset."""+import argparse+import ctypes+import io+from pathlib import Path+import tempfile+from zipfile import ZipFile++import numpy as np+from PIL import Image++from bench_yunet_bottlenecks import GRID, annotations, load_lib, match, native_run, prepare_rectangle, source_boxes+++def collect(lib, engine, photos, labels, names):+ output = []+ for name in names:+ image = Image.open(io.BytesIO(photos.read("WIDER_val/images/" + name))).convert("RGB")+ w, h = image.size+ canvas, rw, rh = prepare_rectangle(np.asarray(image))+ ch, cw = canvas.shape[:2]+ gt = labels[name].copy()+ small = np.sqrt(gt[:, 2:].prod(1)) * 320 / max(w, h) < 16+ gt[:, 2:] += gt[:, :2]+ predictions = []+ for arr in (canvas, np.ascontiguousarray(canvas[:, :, ::-1])):+ rows = native_run(lib, engine, arr, capacity=32)+ predictions.append(source_boxes(rows, w, h, rw, rh, cw, ch))+ output.append((predictions, gt, small))+ return output+++def evaluate(data, order, t):+ records = []+ for predictions, gt, small in data:+ det = predictions[order]+ det = det[det[:, 4] >= np.float32(t)]+ good = match(det, gt)+ records.append((len(good), len(det) - len(good), small[good].sum()))+ return np.array(records)+++def main():+ ap = argparse.ArgumentParser(description=__doc__)+ for name in ("weights", "images", "labels"):+ ap.add_argument(name, type=Path)+ args = ap.parse_args()+ with ZipFile(args.labels) as archive:+ labels = annotations(archive)+ pool = set(labels)+ for seed, n in ((114, 640), (725, 128)):+ pool -= set(np.random.default_rng(seed).choice(sorted(pool), n, replace=False))+ previous = np.random.default_rng(3519).choice(sorted(pool), 672, replace=False)+ names = np.random.default_rng(9101).choice(sorted(pool-set(previous)), 384, replace=False)+ with tempfile.TemporaryDirectory() as tmp, ZipFile(args.images) as photos:+ lib = load_lib(Path(tmp), "native")+ eng = ctypes.c_void_p(lib.detect_init(bytes(args.weights)))+ if not eng:+ raise RuntimeError("Failed to open YuNet weights")+ lib.detect_set_score_threshold(eng, ctypes.c_float(.40))+ try:+ dev = collect(lib, eng, photos, labels, previous[:160])+ budget = int(.75 * evaluate(dev, 0, .58).sum(0)[1])+ candidates = [(t, evaluate(dev, 1, t).sum(0)) for t in GRID]+ threshold, values = max((p for p in candidates if p[1][1] <= budget),+ key=lambda p: (p[1][2], p[1][0]))+ print("locked conservative threshold", threshold, "dev", values, flush=True)+ data = collect(lib, eng, photos, labels, names)+ finally:+ lib.detect_free(eng)+ print("test GT and small", sum(len(r[1]) for r in data), sum(r[2].sum() for r in data))+ base = evaluate(data, 0, .58)+ bs = np.random.default_rng(478).integers(len(names), size=(2000, len(names)))+ for order, t in ((0, .58), (1, .58), (1, .66), (1, threshold)):+ counts = evaluate(data, order, t)+ print(order, t, counts.sum(0), np.percentile((counts-base)[bs].sum(1), [2.5, 97.5], axis=0))+++if __name__ == "__main__":+ main()