diff --git a/AndroidManifest.xml b/AndroidManifest.xml index bb8e080..5c39ae9 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -1,5 +1,5 @@ + package="com.it_screen.edgevision" android:versionCode="14" android:versionName="0.3.9"> diff --git a/LICENSE_REPORT.md b/LICENSE_REPORT.md index ed0f7b2..292d8b5 100644 --- a/LICENSE_REPORT.md +++ b/LICENSE_REPORT.md @@ -52,3 +52,26 @@ chips use Dlib eye-corner landmarks. This port approximates that geometry using YuNet eye centers; age and gender accuracy must be measured separately on consenting adults. Existing stored aggregate counts are preserved across the upgrade. + + +## Controlled PoC model registry entry + +OpenCV Zoo SFace `face_recognition_sface_2021dec_int8.onnx` comes from +revision `eb9f4f2d4b79b58e5513b5d25d5f0243a8357bf4`. The upstream +[model README](https://github.com/opencv/opencv_zoo/blob/eb9f4f2d4b79b58e5513b5d25d5f0243a8357bf4/models/face_recognition_sface/README.md#license) +explicitly applies Apache-2.0 to all directory files, including these weights. +The [LFS pointer](https://raw.githubusercontent.com/opencv/opencv_zoo/eb9f4f2d4b79b58e5513b5d25d5f0243a8357bf4/models/face_recognition_sface/face_recognition_sface_2021dec_int8.onnx) +pins 9,896,933 bytes and SHA-256 +`2b0e941e6f16cc048c20aee0c8e31f569118f65d702914540f7bfdc14048d78a`. +The unchanged weights, attribution and license are tracked under `poc/assets`. +Apache-2.0 permits commercial use, modification and redistribution under its +terms. The separate PoC manifest sets `productionAllowed: false`. The default +APK excludes the weights and implementation. Commercial activation stays +blocked pending review of GDPR and other applicable requirements. + +The published license grant and the provenance review are separate. The +[OpenCV Zoo discussion for this exact INT8 export](https://github.com/opencv/opencv_zoo/issues/318) +still lacks a documented mapping to the training dataset and confirmation +of the original checkpoint authorization. The registry verifies the published +grant and exact binary for controlled internal testing. Production clearance +requires resolving provenance as well as the privacy review. diff --git a/README.md b/README.md index d16395e..0f186e8 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# EVAx10 Video analitics v0.3.8 +# EVAx10 Video analitics v0.3.9 A separate native Android experiment for consenting adult volunteers. Package `com.it_screen.edgevision`. The existing FaceAPI baseline is @@ -10,10 +10,10 @@ installable as `com.it_screen.audiencepoc`. `./build.sh` builds the ARM64, API 30+ APK with the Windows Android SDK 35 and JDK 17 via WSL. The script pins and verifies the upstream Maven AAR. Model assets load locally and are verified before ONNX Runtime session -creation. The signed test build is `build/EVAx10-Video-analitics-0.3.8.apk`. +creation. The signed test build is `build/EVAx10-Video-analitics-0.3.9.apk`. ```text -adb install --no-incremental -r EVAx10-Video-analitics-0.3.8.apk +adb install --no-incremental -r EVAx10-Video-analitics-0.3.9.apk adb shell am start -W -n com.it_screen.edgevision/.MainActivity adb logcat -s EdgeVision EdgeVisionBench ``` @@ -91,3 +91,36 @@ The RAM bar shows the share of memory in use according to Android. The label shows Android's estimate of available RAM and the app's proportional set size (PSS). Available RAM of at least 25% is green, 15–25% is amber, and below 15% or an Android low-memory signal is red. + + +### Controlled Face Re-ID PoC + +Build with `./build.sh --face-reid-poc`. Install +`build/EVAx10-Video-analitics-0.3.9-Face-ReID-PoC.apk` as the separate package +`com.it_screen.edgevision.facereidpoc`. Start requires on-device confirmation +that all adult test participants consent. Keep other people out of the camera view. +The default build excludes the SFace weights and implementation. + +The Person Tracker continues to own Tracking IDs. A new confirmed track can +reopen an unexpired Visitor Session using a normalized SFace embedding. The +PoC keeps one qualifying embedding per session in RAM, overwrites it on expiry, +and clears sessions on Stop, reset or exit to the background. The camera runs +without recording. The app has no Internet permission and the SFace runtime +does not write profiles. APK updates never transfer embeddings because they +are never persisted. Counts shown in the PoC refer to the current camera run. + +The timeout defaults to 30 minutes from the last sighting. The initial cosine +threshold is 0.55 with a margin of 0.08 to distinguish close candidates. These +are PoC settings and require field calibration. A new confirmed track waits up +to another three seconds for a usable face; short tracks that end in that window +may be missed. An ambiguous match or missing template creates a separate session +and may overestimate Unique Visitors. Poses, poor lighting and poor body-to-face +association can prevent a match. There is no liveness check. + +For a consented acceptance test, keep the camera active. Enter with the face +visible. Wait for Unique Visitors = 1, then leave for longer than Lost Track +Timeout but less than Visitor Session Timeout. Re-enter and confirm a new +Tracking ID, Unique Visitors = 1, repeated detections = 1 and open sessions = 1. +Use a separate consenting participant to check that a confidently different face +gets its own session. Test expiration with a one-minute timeout and verify the +open-session count goes to zero while the person is absent. diff --git a/REID_EVALUATION.md b/REID_EVALUATION.md index ec50e33..c08a1c9 100644 --- a/REID_EVALUATION.md +++ b/REID_EVALUATION.md @@ -1,6 +1,15 @@ # Visitor sessions and Re-ID evaluation -## Session lifecycle in 0.3.3 +## Controlled PoC in 0.3.9 + +The separate, consent-gated APK uses the exact SFace INT8 artifact described +below. It enrolls one RAM-only template per session and runs inference when +a track needs an enrollment or comparison, rather than for every video frame. +The production build uses the disabled provider. See the current +[PoC behavior and acceptance test](README.md#controlled-face-re-id-poc) and +[license review](LICENSE_REPORT.md#controlled-poc-model-registry-entry). + +## Session lifecycle in 0.3.3 (historical) A geometric tracking ID is associated with a visitor-session ID after confirmation. Closing a track releases its binding and preserves the diff --git a/build.sh b/build.sh index 1011ebd..0bc5735 100755 --- a/build.sh +++ b/build.sh @@ -4,6 +4,14 @@ cd "$(dirname "$0")" sdk=${WINDOWS_ANDROID_SDK:-/mnt/c/Users/Andrei/AppData/Local/Android/Sdk} jdk=${WINDOWS_JDK:-'/mnt/c/Program Files/Eclipse Adoptium/jdk-17.0.17.10-hotspot'} tools="$sdk/build-tools/35.0.0" +variant=standard +if [[ $# == 1 && $1 == --face-reid-poc ]]; then + variant=poc +elif [[ $# != 0 ]]; then + echo "Usage: $0 [--face-reid-poc]" >&2 + exit 2 +fi +export EVA_BUILD_VARIANT="$variant" jar=$(wslpath -w "$sdk/platforms/android-35/android.jar") mkdir -p build ort_url=https://repo.maven.apache.org/maven2/com/microsoft/onnxruntime/onnxruntime-android/1.32.0/onnxruntime-android-1.32.0.aar @@ -11,6 +19,17 @@ if [[ ! -f build/ort.aar ]]; then curl -fsSL "$ort_url" -o build/ort.aar fi python3 tools/check-production-assets.py +manifest=AndroidManifest.xml +apk=build/EVAx10-Video-analitics-0.3.9.apk +if [[ $variant == poc ]]; then + python3 tools/check-poc-assets.py + manifest=build/AndroidManifest-face-reid-poc.xml + sed -e 's/package="com.it_screen.edgevision"/package="com.it_screen.edgevision.facereidpoc"/' \ + -e 's/android:name=".MainActivity"/android:name="com.it_screen.edgevision.MainActivity"/' \ + -e 's/android:label="EVAx10 Video analitics"/android:label="EVAx10 Video analitics · Face Re-ID PoC"/' \ + AndroidManifest.xml > "$manifest" + apk=build/EVAx10-Video-analitics-0.3.9-Face-ReID-PoC.apk +fi rm -rf build/classes build/dex mkdir -p build/classes build/dex python3 - <<'PACK' @@ -20,14 +39,15 @@ with ZipFile('build/ort.aar') as aar: Path('build/ort.jar').write_bytes(aar.read('classes.jar')) PACK ort_jar=$(wslpath -w "$PWD/build/ort.jar") -"$jdk/bin/javac.exe" -encoding UTF-8 -source 8 -target 8 -classpath "$jar;$ort_jar" -d build/classes src/*.java +"$jdk/bin/javac.exe" -encoding UTF-8 -source 8 -target 8 -classpath "$jar;$ort_jar" -d build/classes src/*.java "$variant"/src/*.java classes=() for class_file in build/classes/com/it_screen/edgevision/*.class; do classes+=("$(wslpath -w "$PWD/$class_file")") done "$jdk/bin/java.exe" -cp "$(wslpath -w "$tools/lib/d8.jar")" com.android.tools.r8.D8 --min-api 26 --lib "$jar" --output "$(wslpath -w "$PWD/build/dex")" "${classes[@]}" "$ort_jar" -"$tools/aapt2.exe" link -I "$jar" --manifest AndroidManifest.xml -o build/assets.apk +"$tools/aapt2.exe" link -I "$jar" --manifest "$manifest" -o build/assets.apk python3 - <<'PY' +import os import shutil from pathlib import Path import zipfile @@ -39,13 +59,17 @@ with zipfile.ZipFile('build/unsigned.apk', 'a') as apk: if source.startswith('jni/arm64-v8a/') and source.endswith('.so'): apk.writestr(source.replace('jni/', 'lib/', 1), aar.read(source), compress_type=zipfile.ZIP_DEFLATED) - for asset in sorted(Path('assets').rglob('*')): - if asset.is_file(): - apk.write(asset, asset.as_posix(), compress_type=zipfile.ZIP_DEFLATED) + roots = [Path('assets')] + if os.environ['EVA_BUILD_VARIANT'] == 'poc': + roots.append(Path('poc/assets')) + for root in roots: + for asset in sorted(root.rglob('*')): + if asset.is_file(): + apk.write(asset, 'assets/' + asset.relative_to(root).as_posix(), compress_type=zipfile.ZIP_DEFLATED) PY "$tools/zipalign.exe" -f 4 build/unsigned.apk build/aligned.apk if [[ ! -f build/poc-debug.p12 ]]; then "$jdk/bin/keytool.exe" -genkeypair -keystore build/poc-debug.p12 -storepass android -alias edgevision -keyalg RSA -keysize 2048 -validity 3650 -dname CN=EdgeVision fi -"$jdk/bin/java.exe" -jar "$(wslpath -w "$tools/lib/apksigner.jar")" sign --ks build/poc-debug.p12 --ks-pass pass:android --out build/EVAx10-Video-analitics-0.3.8.apk build/aligned.apk -"$jdk/bin/java.exe" -jar "$(wslpath -w "$tools/lib/apksigner.jar")" verify --verbose build/EVAx10-Video-analitics-0.3.8.apk +"$jdk/bin/java.exe" -jar "$(wslpath -w "$tools/lib/apksigner.jar")" sign --ks build/poc-debug.p12 --ks-pass pass:android --out "$apk" build/aligned.apk +"$jdk/bin/java.exe" -jar "$(wslpath -w "$tools/lib/apksigner.jar")" verify --verbose "$apk" diff --git a/poc/asset-lock.json b/poc/asset-lock.json new file mode 100644 index 0000000..265ecfb --- /dev/null +++ b/poc/asset-lock.json @@ -0,0 +1,6 @@ +{ + "models/sface-int8.json": "fe647e0705c6bd89ea1b2d8266de442957b7f031200e47c9221ef5f6b23e64ec", + "models/sface-int8.onnx": "2b0e941e6f16cc048c20aee0c8e31f569118f65d702914540f7bfdc14048d78a", + "notices/SFace-Apache-2.0.txt": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30", + "notices/SFace-attribution.txt": "d481c811b5374fb46b0b2da7c9a50fd9c9d437de8b0099a9f324ea283c93d4e9" +} diff --git a/poc/assets/models/sface-int8.json b/poc/assets/models/sface-int8.json new file mode 100644 index 0000000..6875dcf --- /dev/null +++ b/poc/assets/models/sface-int8.json @@ -0,0 +1,22 @@ +{ + "id": "sface-int8", + "type": "reid", + "name": "SFace", + "version": "2021dec-int8", + "format": "ONNX", + "file": "models/sface-int8.onnx", + "size": 9896933, + "sha256": "2b0e941e6f16cc048c20aee0c8e31f569118f65d702914540f7bfdc14048d78a", + "input": {"name": "data", "width": 112, "height": 112}, + "outputs": ["fc1"], + "providers": ["CPU"], + "license": "Apache-2.0", + "licenseVerification": "verified", + "licenseNotice": "notices/SFace-Apache-2.0.txt", + "licenseEvidence": "https://github.com/opencv/opencv_zoo/blob/eb9f4f2d4b79b58e5513b5d25d5f0243a8357bf4/models/face_recognition_sface/README.md#license", + "commercialUse": true, + "modificationAllowed": true, + "redistributionAllowed": true, + "productionAllowed": false, + "controlledPocAllowed": true +} diff --git a/poc/assets/models/sface-int8.onnx b/poc/assets/models/sface-int8.onnx new file mode 100644 index 0000000..bd18a97 Binary files /dev/null and b/poc/assets/models/sface-int8.onnx differ diff --git a/poc/assets/notices/SFace-Apache-2.0.txt b/poc/assets/notices/SFace-Apache-2.0.txt new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/poc/assets/notices/SFace-Apache-2.0.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/poc/assets/notices/SFace-attribution.txt b/poc/assets/notices/SFace-attribution.txt new file mode 100644 index 0000000..a25f628 --- /dev/null +++ b/poc/assets/notices/SFace-attribution.txt @@ -0,0 +1,7 @@ +SFace 2021dec int8, OpenCV Zoo +SFace contribution: Yaoyao Zhong +ONNX conversion: Chengrui Wang +Upstream revision: eb9f4f2d4b79b58e5513b5d25d5f0243a8357bf4 +Released by OpenCV Zoo under the Apache License, Version 2.0. +The distributed ONNX weights are unchanged. +https://github.com/opencv/opencv_zoo/tree/eb9f4f2d4b79b58e5513b5d25d5f0243a8357bf4/models/face_recognition_sface diff --git a/poc/src/FaceReId.java b/poc/src/FaceReId.java new file mode 100644 index 0000000..f922f4f --- /dev/null +++ b/poc/src/FaceReId.java @@ -0,0 +1,106 @@ +package com.it_screen.edgevision; + +import android.graphics.Bitmap; +import android.graphics.Matrix; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +final class FaceReId implements ReIdProvider { + static final boolean CONTROLLED_POC = true; + private static final float AMBIGUITY_MARGIN = .08f; + private static final float[] TARGET = {38.2946f, 51.6963f, 73.5318f, 51.5014f, 56.0252f, 71.7366f, + 41.5493f, 92.3655f, 70.7299f, 92.2041f}; + private final Map templates = new HashMap<>(); + private ImageModel model; + private float threshold; + + static ReIdProvider create() { return new FaceReId(); } + + static void load(ReIdProvider provider, ModelRegistry registry, InferenceEngine engine, int threads) + throws Exception { + ModelRegistry.Entry entry = registry.list("reid").get(0); + ((FaceReId) provider).model = new ImageModel(engine.load(entry, "CPU", threads), entry) {}; + } + + static void setThreshold(ReIdProvider provider, float threshold) { + ((FaceReId) provider).threshold = threshold; + } + + static float[] embed(ReIdProvider provider, Bitmap frame, Face face) throws Exception { + if (face == null || face.landmarks == null || face.confidence < .8f || + Math.min(face.box.width() * frame.getWidth(), face.box.height() * frame.getHeight()) < 48 || + Math.hypot(face.landmarks[2] - face.landmarks[0], face.landmarks[3] - face.landmarks[1]) < 16) + return null; + Matrix transform = align(face.landmarks); + if (transform == null) return null; + float[] vector = ((FaceReId) provider).model.runNormalized(frame, transform, null).get("fc1"); + double squared = 0; + for (float value : vector) squared += (double) value * value; + if (!Double.isFinite(squared) || squared <= 0 || vector.length != 128) { + Arrays.fill(vector, 0); + return null; + } + float scale = (float) (1 / Math.sqrt(squared)); + for (int i = 0; i < vector.length; i++) vector[i] *= scale; + return vector; + } + + private static Matrix align(float[] points) { + // Least-squares similarity transform over all five YuNet landmarks. + double xMean = 0, yMean = 0, uMean = 0, vMean = 0; + for (int i = 0; i < TARGET.length; i += 2) { + xMean += points[i] / 5.0; + yMean += points[i + 1] / 5.0; + uMean += TARGET[i] / 5.0; + vMean += TARGET[i + 1] / 5.0; + } + double real = 0, imaginary = 0, energy = 0; + for (int i = 0; i < TARGET.length; i += 2) { + double x = points[i] - xMean, y = points[i + 1] - yMean; + double u = TARGET[i] - uMean, v = TARGET[i + 1] - vMean; + real += x * u + y * v; + imaginary += x * v - y * u; + energy += x * x + y * y; + } + if (!Double.isFinite(energy) || energy <= 0) return null; + float a = (float) (real / energy), b = (float) (imaginary / energy); + Matrix transform = new Matrix(); + transform.setValues(new float[]{a, -b, (float) (uMean - a * xMean + b * yMean), + b, a, (float) (vMean - b * xMean - a * yMean), 0, 0, 1}); + return transform; + } + + @Override public boolean enabled() { return true; } + @Override public boolean hasObservation(long visitorId) { return templates.containsKey(visitorId); } + + @Override public long match(float[] observation, List candidates) { + if (observation == null) return UNCERTAIN; + long bestId = 0; + float best = -2, runnerUp = -2; + boolean missing = false; + for (VisitorSessions.Candidate candidate : candidates) { + float[] reference = templates.get(candidate.id); + if (reference == null) { missing = true; continue; } + float similarity = 0; + for (int i = 0; i < reference.length; i++) similarity += observation[i] * reference[i]; + if (similarity > best) { + runnerUp = best; + best = similarity; + bestId = candidate.id; + } else runnerUp = Math.max(runnerUp, similarity); + } + if (best >= threshold && best - runnerUp >= AMBIGUITY_MARGIN) return bestId; + return missing || best >= threshold - AMBIGUITY_MARGIN ? UNCERTAIN : 0; + } + + @Override public void observed(long visitorId, float[] observation) { + if (observation != null && !templates.containsKey(visitorId)) templates.put(visitorId, observation.clone()); + } + + @Override public void expired(long visitorId) { + float[] removed = templates.remove(visitorId); + if (removed != null) Arrays.fill(removed, 0); + } +} diff --git a/src/DiagnosticsPanel.java b/src/DiagnosticsPanel.java index 996ce66..0d2aa53 100644 --- a/src/DiagnosticsPanel.java +++ b/src/DiagnosticsPanel.java @@ -30,9 +30,11 @@ final class DiagnosticsPanel { {"restored_tracks", "Restored Tracks", "", "Сколько раз программа восстановила ранее подтверждённый трек с тем же ID."}, {"closed_tracks", "Closed Tracks", "", "Треки, закрытые после истечения таймаута потери."}, {"open_visitor_sessions", "Open Visitor Sessions", "", "Сессии, у которых ещё не истёк таймаут от последнего наблюдения. Сессия может оставаться открытой после закрытия трека."}, - {"created_visitor_sessions", "Created Visitor Sessions", "", "Сколько сессий создано с запуска или сброса. Пока Re-ID отключён, это технический показатель, а не число уникальных людей."}, + {"created_visitor_sessions", "Created Visitor Sessions", "", "Сколько сессий создано с запуска или сброса. В PoC используется как оценка Unique Visitors. При отключённом Re-ID это технический показатель."}, {"visitor_session_timeout_minutes", "Visitor Session Timeout", " мин", "Сколько времени с последнего обнаружения сохраняется возможность восстановить сессию. Сам таймаут не подтверждает совпадение."}, {"reid_status", "Re-ID Provider", "", "Статус сопоставления сессий. Disabled означает, что приложение не сравнивает людей между разными треками."}, + {"repeated_detections", "Repeated Detections", "", "Сколько новых треков сопоставилось с ранее открытой сессией по SFace."}, + {"uncertain_matches", "Uncertain Matches", "", "Сколько раз совпадение оказалось неопределённым и было учтено отдельной сессией."}, {"id_switches", "ID Switches", "", "Случаи, когда одному и тому же человеку ошибочно присвоили другой ID. Для подсчёта нужна эталонная разметка. В прямом эфире — N/A."}, {"average_dwell_s", "Average Dwell Time", " с", "Среднее время от первого до последнего наблюдения подтверждённых треков в этой сессии. Учитываются текущие и закрытые треки. Ожидание закрытия после последнего кадра не прибавляется."}, {"tracking_fps", "Tracking FPS", " кадр/с", "Фактическое количество кадров в секунду, которые обработал трекер людей."}, diff --git a/src/MainActivity.java b/src/MainActivity.java index b1b29b2..b20d8bd 100644 --- a/src/MainActivity.java +++ b/src/MainActivity.java @@ -23,7 +23,9 @@ public final class MainActivity extends Activity { private final AtomicBoolean previewQueued = new AtomicBoolean(); private final AtomicLong skipped = new AtomicLong(); private final PersonTracker tracker = new PersonTracker(); - private final VisitorSessions visitorSessions = new VisitorSessions<>(ReIdProvider.disabled()); + private static final int DEFAULT_REID_THRESHOLD = 55; + private final ReIdProvider reId = FaceReId.create(); + private final VisitorSessions visitorSessions = new VisitorSessions<>(reId); private final ArrayDeque visitEvents = new ArrayDeque<>(); private final AudienceAggregator totals = new AudienceAggregator(); private final Benchmark benchmark = new Benchmark(); @@ -45,7 +47,8 @@ public final class MainActivity extends Activity { private long metricsEpoch, frameCount, lastCpu, lastCpuAt, errors; private double aiFps; private double loadMs; - private TextView status, currentVisitorValue, trackingLog; + private final Runnable expirePocSessions = this::expirePocSessions; + private TextView status, currentVisitorValue, trackingLog, uniqueValue, repeatedValue, sessionValue; private DiagnosticsPanel diagnostics; private ResourcePanel resources; private TextView cameraStatus; @@ -60,6 +63,7 @@ public final class MainActivity extends Activity { getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); + if (FaceReId.CONTROLLED_POC) getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE); preferences = getSharedPreferences("aggregates", MODE_PRIVATE); totals.visits = preferences.getInt("total", 0); readCounts("age", totals.ages); @@ -147,8 +151,15 @@ public final class MainActivity extends Activity { LinearLayout actions = new LinearLayout(this); left.addView(actions); start = button(actions, "Start", () -> { - if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) startCamera(); - else requestPermissions(new String[]{Manifest.permission.CAMERA}, 1); + if (FaceReId.CONTROLLED_POC) { + new android.app.AlertDialog.Builder(this) + .setTitle("Face Re-ID · согласие на тест") + .setMessage("Проводите тест только со взрослыми, которые согласились на локальное сопоставление лиц. " + + "Шаблоны хранятся в памяти до таймаута или остановки камеры. Убедитесь, что посторонних нет в кадре.") + .setNegativeButton("Отмена", null) + .setPositiveButton("Согласие получено", (dialog, which) -> requestCamera()) + .show(); + } else requestCamera(); }); stop = button(actions, "Stop", () -> halt("Camera stopped")); button(actions, "Reset Statistics", this::reset); @@ -196,9 +207,14 @@ public final class MainActivity extends Activity { currentVisitorNote.setTextColor(0xffaebfd1); currentVisitorNote.setPadding(0, 4, 0, 6); right.addView(currentVisitorNote); - TextView unique = text("Уникальные посетители — пока не считаются", 14); - unique.setPadding(0, 10, 0, 0); - right.addView(unique); + if (FaceReId.CONTROLLED_POC) { + uniqueValue = counter(right, "Unique Visitors · оценка PoC"); + repeatedValue = counter(right, "Повторные обнаружения"); + sessionValue = counter(right, "Активные Visitor Sessions"); + TextView note = text("За текущий запуск камеры. Неопределённое совпадение учитывается отдельно.", 13); + note.setTextColor(0xffaebfd1); + right.addView(note); + } else right.addView(text("Уникальные посетители — пока не считаются", 14)); TextView journalTitle = text("Журнал трекинга", 16); journalTitle.setPadding(0, 16, 0, 6); @@ -226,6 +242,30 @@ public final class MainActivity extends Activity { test.setEnabled(false); } + private TextView counter(LinearLayout parent, String name) { + LinearLayout row = new LinearLayout(this); + TextView label = text(name, 15); + label.setTypeface(Typeface.DEFAULT_BOLD); + row.addView(label, new LinearLayout.LayoutParams(0, -2, 1)); + TextView value = text("0", 18); + value.setTextColor(0xff9ce8c2); + row.addView(value); + parent.addView(row); + return value; + } + + private void updatePocStats(long unique, long repeats, int sessions) { + if (!FaceReId.CONTROLLED_POC) return; + updateCounter(uniqueValue, unique); + updateCounter(repeatedValue, repeats); + updateCounter(sessionValue, sessions); + } + + private void updateCounter(TextView view, long count) { + String value = Long.toString(count); + if (!value.contentEquals(view.getText())) view.setText(value); + } + private void editTrackingSettings() { LinearLayout form = column(); form.setPadding(24, 10, 24, 10); @@ -241,9 +281,14 @@ public final class MainActivity extends Activity { "Сколько минут с последнего обнаружения открыта сессия посетителя, даже если трек закрылся. Таймаут сам по себе не связывает разные треки."); trackingSettingLabel(form, "Count Once Per Track: true"); trackingSettingNote(form, "Фиксированный режим. Каждый подтверждённый трек учитывается один раз в Confirmed Tracks. Восстановление того же ID не добавляет трек в счётчик."); - trackingSettingLabel(form, "Biometric Matching: false"); - trackingSettingNote(form, "Фиксированный режим. Сопоставление людей между разными треками отключено. Подсчёт уникальных посетителей пока недоступен."); - trackingSettingNote(form, "Таймаут сессии применяется сразу. Остальные изменения вступают в силу при следующем Start."); + EditText similarity = FaceReId.CONTROLLED_POC ? trackingField(form, "Re-ID Similarity Threshold (%)", + "reid_similarity_percent", DEFAULT_REID_THRESHOLD, + "Минимальное косинусное сходство. Чем выше порог, тем сложнее связать разные треки. Это не вероятность. При близких кандидатах совпадение отмечается как неопределённое.") : null; + trackingSettingLabel(form, FaceReId.CONTROLLED_POC ? "Biometric Matching · SFace PoC" : "Biometric Matching: false"); + trackingSettingNote(form, FaceReId.CONTROLLED_POC ? + "Сопоставление выполняется локально. При Stop и истечении таймаута шаблоны удаляются из памяти." : + "Сопоставление людей между разными треками отключено."); + trackingSettingNote(form, "Таймаут сессии и порог Re-ID применяются сразу. Настройки трекинга вступают в силу при следующем Start."); ScrollView fields = new ScrollView(this); fields.addView(form); android.app.AlertDialog dialog = new android.app.AlertDialog.Builder(this) @@ -256,16 +301,19 @@ public final class MainActivity extends Activity { int lostMs = Integer.parseInt(lost.getText().toString()); int trackingFps = Integer.parseInt(fps.getText().toString()); int visitorTimeoutMinutes = Integer.parseInt(visitorTimeout.getText().toString()); - if (confirmationMs < 0 || confirmationMs > 10000 || lostMs < 1000 || + int threshold = similarity == null ? DEFAULT_REID_THRESHOLD : + Integer.parseInt(similarity.getText().toString()); + if (threshold < 1 || threshold > 100 || confirmationMs < 0 || confirmationMs > 10000 || lostMs < 1000 || lostMs > 120000 || trackingFps < 1 || trackingFps > 15 || visitorTimeoutMinutes < 1 || visitorTimeoutMinutes > 1440) throw new IllegalArgumentException(); preferences.edit().putInt("tracking_confirm_ms", confirmationMs).putInt("tracking_lost_ms", lostMs) .putInt("tracking_fps", trackingFps) - .putInt("visitor_session_timeout_minutes", visitorTimeoutMinutes).apply(); + .putInt("visitor_session_timeout_minutes", visitorTimeoutMinutes) + .putInt("reid_similarity_percent", threshold).apply(); dialog.dismiss(); } catch (IllegalArgumentException error) { - Toast.makeText(this, "Confirmation 0–10000 ms, lost 1000–120000 ms, FPS 1–15, session timeout 1–1440 min", + Toast.makeText(this, "Confirmation 0–10000 ms, lost 1000–120000 ms, FPS 1–15, session timeout 1–1440 min, Re-ID 1–100%", Toast.LENGTH_LONG).show(); } })); @@ -356,7 +404,7 @@ public final class MainActivity extends Activity { private void setRunning(boolean value) { running = value; start.setEnabled(!value); - test.setEnabled(!value); + test.setEnabled(!value && !FaceReId.CONTROLLED_POC); stop.setEnabled(value); for (Spinner control : new Spinner[]{resolution, interval, detection, classification, provider, threadCount, faceModel, ageModel}) control.setEnabled(!value); @@ -373,6 +421,11 @@ public final class MainActivity extends Activity { preferences.getInt("tracking_fps", 5)); } + private void requestCamera() { + if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) startCamera(); + else requestPermissions(new String[]{Manifest.permission.CAMERA}, 1); + } + private void startCamera() { if (running) return; Settings selection = readSettings(); @@ -385,11 +438,16 @@ public final class MainActivity extends Activity { cameraStatus.setText(input instanceof InternalCamera ? "Камера · запуск…" : "Камера · тестовое изображение"); setStatus("Loading model sessions…"); final long run = ++generation; + if (FaceReId.CONTROLLED_POC) { + updatePocStats(0, 0, 0); + ui.postDelayed(expirePocSessions, 1000); + } nextFrame = 0; skipped.set(0); inference.execute(() -> { tracker.clear(); - visitorSessions.releaseTracks(); + if (FaceReId.CONTROLLED_POC) visitorSessions.clear(); + else visitorSessions.releaseTracks(); visitEvents.clear(); ui.post(() -> { if (generation == run) trackingLog.setText("Ожидание посетителей"); }); nextFaceFrame = 0; @@ -429,6 +487,7 @@ public final class MainActivity extends Activity { new CydralDemographics.Predictor(engine.load(gender, "CPU", config.threads), gender)); ModelRegistry.Entry person = registry.list("person").get(0); personDetector = new NanoDetPerson(engine.load(person, "CPU", config.threads), person); + FaceReId.load(reId, registry, engine, config.threads); loaded = config; loadMs = ms(startAt); } catch (Exception failure) { @@ -462,8 +521,8 @@ public final class MainActivity extends Activity { List people = personDetector.detect(frame); List events = tracker.update(people, now, config.confirmMs, config.lostMs); double trackingMs = ms(inferenceAt); - int visitorTimeoutMinutes = preferences.getInt("visitor_session_timeout_minutes", - VisitorSessions.DEFAULT_TIMEOUT_MINUTES); + int visitorTimeoutMinutes = visitorTimeoutMinutes(); + FaceReId.setThreshold(reId, preferences.getInt("reid_similarity_percent", DEFAULT_REID_THRESHOLD) / 100f); visitorSessions.expire(now, visitorTimeoutMinutes * 60000L); for (PersonTracker.Event event : events) { if (event.state == PersonTracker.State.TEMPORARILY_LOST) visitorSessions.temporarilyLost(event.track.id); @@ -493,25 +552,10 @@ public final class MainActivity extends Activity { addVisitEvent("#" + event.track.id + " · " + message); } - // Returning tracks already bound to a session keep priority over new observations. - for (PersonTracker.Track track : tracker.tracks()) { - if (track.state == PersonTracker.State.ACTIVE) visitorSessions.reserveObservedTrack(track.id); - } - for (PersonTracker.Track track : tracker.tracks()) { - if (track.state != PersonTracker.State.ACTIVE) continue; - VisitorObservation sample = visitorSessions.matchingEnabled() ? new VisitorObservation(frame, track.box) : null; - VisitorSessions.Assignment assignment = visitorSessions.observe(track.id, now, sample); - if (assignment.kind == VisitorSessions.Kind.RECONNECTED) { - addVisitEvent("#" + track.id + " · Сессия V" + assignment.visitorId + " восстановлена и продлена."); - } else if (assignment.kind == VisitorSessions.Kind.CREATED) { - addVisitEvent("#" + track.id + " · Открыта сессия V" + assignment.visitorId + - (visitorSessions.matchingEnabled() ? ". Совпадение отсутствует." : ". Re-ID отключён.")); - } - } - double faceMs = -1, ageMs = -1; int faceCount = 0; List overlays = new ArrayList<>(); + Map assignments = Collections.emptyMap(); if (now >= nextFaceFrame && tracker.count(PersonTracker.State.ACTIVE) > 0) { nextFaceFrame = now + config.interval; long faceAt = System.nanoTime(); @@ -520,7 +564,7 @@ public final class MainActivity extends Activity { faceCount = faces.size(); long ageAt = System.nanoTime(); long runs = demographics.runs(); - Map assignments = associateFaces(faces); + assignments = associateFaces(faces); for (Map.Entry entry : assignments.entrySet()) { VisitorAnalytics analytics = entry.getKey().analytics; Face face = entry.getValue(); @@ -534,6 +578,39 @@ public final class MainActivity extends Activity { } if (demographics.runs() != runs) ageMs = ms(ageAt); } + // Returning tracks already bound to a session keep priority over new observations. + for (PersonTracker.Track track : tracker.tracks()) { + if (track.state == PersonTracker.State.ACTIVE) visitorSessions.reserveObservedTrack(track.id); + } + for (PersonTracker.Track track : tracker.tracks()) { + if (track.state != PersonTracker.State.ACTIVE) continue; + float[] sample = visitorSessions.needsObservation(track.id) ? + FaceReId.embed(reId, frame, assignments.get(track)) : null; + if (FaceReId.CONTROLLED_POC && sample == null && !visitorSessions.hasSession(track.id) && + now - track.confirmationStart < config.confirmMs + 3000L) continue; + VisitorSessions.Assignment assignment; + try { + assignment = visitorSessions.observe(track.id, now, sample); + } finally { + if (sample != null) Arrays.fill(sample, 0); + } + switch (assignment.kind) { + case RECONNECTED: + addVisitEvent("#" + track.id + " · Повторное обнаружение. Сессия V" + + assignment.visitorId + " продлена. Unique Visitors без изменений."); + break; + case UNCERTAIN: + addVisitEvent("#" + track.id + " · Сопоставление неопределённое. Отдельная сессия V" + + assignment.visitorId + " включена в оценку."); + break; + case CREATED: + addVisitEvent("#" + track.id + " · Открыта сессия V" + assignment.visitorId + + (FaceReId.CONTROLLED_POC ? ". Новая запись в оценке." : ". Re-ID отключён.")); + break; + default: break; + } + } + for (PersonTracker.Track track : tracker.tracks()) { if (track.state == PersonTracker.State.TEMPORARILY_LOST) continue; PersonTracker.Box box = track.box; @@ -555,6 +632,8 @@ public final class MainActivity extends Activity { } int visits = totals.visits; int[] genders = totals.genders.clone(), ages = totals.ages.clone(); + long unique = visitorSessions.totalCreated(), repeated = visitorSessions.repeatedCount(); + int openSessions = visitorSessions.openCount(); final String tracking = visitEvents.isEmpty() ? "Ожидание посетителей" : String.join("\n\n", visitEvents); final JSONObject detail; if (sampled) { @@ -570,6 +649,7 @@ public final class MainActivity extends Activity { preview.boxes = overlays; preview.invalidate(); updateStats(activeTracks, visits, genders, ages); + updatePocStats(unique, repeated, openSessions); if (detail != null) { diagnostics.update(detail); if (source instanceof InternalCamera) { @@ -634,7 +714,9 @@ public final class MainActivity extends Activity { .put("visitor_session_timeout_minutes", visitorTimeoutMinutes) .put("open_visitor_sessions", visitorSessions.openCount()) .put("created_visitor_sessions", visitorSessions.totalCreated()) - .put("reid_status", visitorSessions.matchingEnabled() ? "Enabled" : "Disabled") + .put("reid_status", visitorSessions.matchingEnabled() ? "SFace PoC" : "Disabled") + .put("repeated_detections", visitorSessions.repeatedCount()) + .put("uncertain_matches", visitorSessions.uncertainCount()) .put("age_gender_ms", ageMs < 0 ? JSONObject.NULL : round(ageMs)) .put("total_ms", round(totalMs)).put("session_load_ms", round(loadMs)).put("interval_ms", config.interval) .put("cpu_pct", cpuPercent).put("pss_mib", round(Debug.getPss() / 1024.0)).put("cpu_temperature_c", JSONObject.NULL) @@ -681,12 +763,33 @@ public final class MainActivity extends Activity { preview.invalidate(); trackingLog.setText("Журнал очищен"); updateStats(0, 0, new int[3], new int[7]); + updatePocStats(0, 0, 0); + }); + }); + } + + private int visitorTimeoutMinutes() { + return preferences.getInt("visitor_session_timeout_minutes", VisitorSessions.DEFAULT_TIMEOUT_MINUTES); + } + + private void expirePocSessions() { + long run = generation; + inference.execute(() -> { + if (generation != run) return; + visitorSessions.expire(SystemClock.elapsedRealtime(), visitorTimeoutMinutes() * 60000L); + long unique = visitorSessions.totalCreated(), repeated = visitorSessions.repeatedCount(); + int count = visitorSessions.openCount(); + ui.post(() -> { + if (generation != run || !running) return; + updatePocStats(unique, repeated, count); + ui.postDelayed(expirePocSessions, 1000); }); }); } private void halt(String message) { - generation++; + long stoppedRun = ++generation; + ui.removeCallbacks(expirePocSessions); if (source != null) { source.close(); source = null; @@ -698,10 +801,16 @@ public final class MainActivity extends Activity { cameraStatus.setText("Камера · остановлена"); setStatus(message); inference.execute(() -> { - visitorSessions.releaseTracks(); + if (FaceReId.CONTROLLED_POC) visitorSessions.closeSessions(); + else visitorSessions.releaseTracks(); + long unique = visitorSessions.totalCreated(), repeated = visitorSessions.repeatedCount(); int visits = totals.visits; int[] genders = totals.genders.clone(), ages = totals.ages.clone(); - ui.post(() -> { if (!running) updateStats(0, visits, genders, ages); }); + ui.post(() -> { + if (generation != stoppedRun) return; + updateStats(0, visits, genders, ages); + updatePocStats(unique, repeated, 0); + }); }); } @@ -717,7 +826,7 @@ public final class MainActivity extends Activity { super.onActivityResult(request, code, data); if (code != RESULT_OK || data == null || data.getData() == null) return; android.net.Uri uri = data.getData(); - if (request != 2) return; + if (request != 2 || FaceReId.CONTROLLED_POC) return; begin(readSettings(), new VideoSource() { private boolean closed; private final Runnable cleanup = () -> closed = true; diff --git a/src/ModelRegistry.java b/src/ModelRegistry.java index 7a5283a..7708299 100644 --- a/src/ModelRegistry.java +++ b/src/ModelRegistry.java @@ -22,7 +22,7 @@ final class ModelRegistry { if (!path.endsWith(".json")) continue; try (InputStream in = assets.open("models/" + path)) { Entry entry = new Entry(new JSONObject(new String(readBytes(in), java.nio.charset.StandardCharsets.UTF_8))); - if (entry.json.getString("type").equals(type) && entry.approved()) entries.add(entry); + if (entry.json.getString("type").equals(type) && entry.allowedInBuild()) entries.add(entry); } } entries.sort(java.util.Comparator.comparing(Entry::toString)); @@ -33,7 +33,7 @@ final class ModelRegistry { String path = entry.json.getString("file"); if (!path.matches("models/[A-Za-z0-9._-]+\\.onnx") || !"ONNX".equals(entry.json.getString("format"))) throw new IllegalArgumentException("Invalid ONNX asset " + path); - if (!entry.approved()) throw new SecurityException("Model is not approved for production: " + entry); + if (!entry.allowedInBuild()) throw new SecurityException("Model is not approved for this build: " + entry); try (InputStream in = assets.open(path)) { byte[] bytes = readBytes(in); verify(entry.json, bytes); @@ -62,8 +62,11 @@ final class ModelRegistry { static final class Entry { final JSONObject json; Entry(JSONObject json) { this.json = json; } - boolean approved() { - return json.optBoolean("productionAllowed") && json.optBoolean("commercialUse") && + boolean allowedInBuild() { + boolean allowed = json.optBoolean("productionAllowed") || + (FaceReId.CONTROLLED_POC && json.optBoolean("controlledPocAllowed") && + "reid".equals(json.optString("type"))); + return allowed && json.optBoolean("commercialUse") && json.optBoolean("modificationAllowed") && json.optBoolean("redistributionAllowed") && "verified".equals(json.optString("licenseVerification")); } diff --git a/src/OrtEngine.java b/src/OrtEngine.java index 7e113c7..069ae21 100644 --- a/src/OrtEngine.java +++ b/src/OrtEngine.java @@ -43,7 +43,8 @@ final class OrtEngine implements InferenceEngine { } else if ("NNAPI".equals(provider)) { options.addNnapi(EnumSet.of(ai.onnxruntime.providers.NNAPIFlags.CPU_DISABLED)); } - options.enableProfiling(new File(cache, "ort-profile-" + System.nanoTime()).getAbsolutePath()); + boolean profile = !"reid".equals(entry.json.getString("type")); + if (profile) options.enableProfiling(new File(cache, "ort-profile-" + System.nanoTime()).getAbsolutePath()); OrtSession session = environment.createSession(bytes, options); try { String inputName = entry.input().getString("name"); @@ -63,7 +64,7 @@ final class OrtEngine implements InferenceEngine { if (!session.getOutputNames().contains(expected.getString(i))) throw new IllegalArgumentException("Missing model output " + expected.getString(i)); } - Model model = new Session(session, provider); + Model model = new Session(session, provider, profile); open.add(model); return model; } catch (Exception failure) { @@ -83,12 +84,13 @@ final class OrtEngine implements InferenceEngine { private final OrtSession session; private long runs; private double inferenceMs; - private boolean profilePending = true; + private boolean profilePending; private String assignment; - Session(OrtSession session, String provider) { + Session(OrtSession session, String provider, boolean profile) { this.session = session; - assignment = provider + " (awaiting first run)"; + profilePending = profile; + assignment = profile ? provider + " (awaiting first run)" : provider; } @Override public Map run(String input, float[] data, long[] shape, Set outputs) throws Exception { diff --git a/src/ReIdProvider.java b/src/ReIdProvider.java index a9944c1..ba93820 100644 --- a/src/ReIdProvider.java +++ b/src/ReIdProvider.java @@ -2,11 +2,14 @@ package com.it_screen.edgevision; import java.util.List; -/** Optional identity service. The application currently binds only the disabled implementation. */ +/** Optional identity service for visitor sessions. */ interface ReIdProvider { - boolean enabled(); + long UNCERTAIN = -1; - /** Return a confidently matched candidate ID, or zero when there is no confident match. */ + boolean enabled(); + default boolean hasObservation(long visitorId) { return false; } + + /** Return a confidently matched candidate ID, zero for a distinct visitor, or UNCERTAIN when evidence is insufficient. */ long match(Observation observation, List candidates); void observed(long visitorId, Observation observation); void expired(long visitorId); diff --git a/src/VisitorObservation.java b/src/VisitorObservation.java deleted file mode 100644 index 45d64bd..0000000 --- a/src/VisitorObservation.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.it_screen.edgevision; - -import android.graphics.Bitmap; - -/** A borrowed camera frame and normalized body box, valid only during the provider call. */ -final class VisitorObservation { - final Bitmap frame; - final PersonTracker.Box box; - VisitorObservation(Bitmap frame, PersonTracker.Box box) { - this.frame = frame; - this.box = box; - } -} diff --git a/src/VisitorSessions.java b/src/VisitorSessions.java index 2ed96ce..cdebf3b 100644 --- a/src/VisitorSessions.java +++ b/src/VisitorSessions.java @@ -14,7 +14,7 @@ final class VisitorSessions { private final Map open = new HashMap<>(); private final Map byTrack = new HashMap<>(); private long nextId = 1; - private long totalCreated; + private long totalCreated, repeated, uncertain; VisitorSessions(ReIdProvider provider) { this.provider = provider; } @@ -27,7 +27,7 @@ final class VisitorSessions { } } - enum Kind { CREATED, RECONNECTED, CONTINUED } + enum Kind { CREATED, UNCERTAIN, RECONNECTED, CONTINUED } static final class Assignment { final long visitorId; @@ -46,6 +46,15 @@ final class VisitorSessions { boolean matchingEnabled() { return provider.enabled(); } int openCount() { return open.size(); } long totalCreated() { return totalCreated; } + long repeatedCount() { return repeated; } + long uncertainCount() { return uncertain; } + + boolean needsObservation(int trackId) { + Session session = byTrack.get(trackId); + return provider.enabled() && (session == null || !provider.hasObservation(session.id)); + } + + boolean hasSession(int trackId) { return byTrack.containsKey(trackId); } void expire(long now, long timeoutMs) { Iterator items = open.values().iterator(); @@ -63,13 +72,14 @@ final class VisitorSessions { Kind kind = Kind.CONTINUED; if (session == null) { // No timer, spatial match, or "only candidate" fallback can identify a visitor. + long match = 0; if (provider.enabled()) { List candidates = new ArrayList<>(); for (Session candidate : open.values()) { if (!candidate.visible) candidates.add(new Candidate(candidate.id, candidate.lastSeen)); } if (!candidates.isEmpty()) { - long match = provider.match(observation, Collections.unmodifiableList(candidates)); + match = provider.match(observation, Collections.unmodifiableList(candidates)); Session candidate = open.get(match); if (candidate != null && !candidate.visible) { session = candidate; @@ -77,7 +87,13 @@ final class VisitorSessions { } } } - kind = session == null ? Kind.CREATED : Kind.RECONNECTED; + if (session != null) { + kind = Kind.RECONNECTED; + repeated++; + } else if (match == ReIdProvider.UNCERTAIN) { + kind = Kind.UNCERTAIN; + uncertain++; + } else kind = Kind.CREATED; if (session == null) { session = new Session(nextId++, now); open.put(session.id, session); @@ -112,10 +128,16 @@ final class VisitorSessions { } void clear() { + closeSessions(); + totalCreated = 0; + repeated = 0; + uncertain = 0; + } + + void closeSessions() { for (Session session : open.values()) provider.expired(session.id); byTrack.clear(); open.clear(); - totalCreated = 0; } private void detach(Session session) { diff --git a/standard/src/FaceReId.java b/standard/src/FaceReId.java new file mode 100644 index 0000000..d9c6d9f --- /dev/null +++ b/standard/src/FaceReId.java @@ -0,0 +1,12 @@ +package com.it_screen.edgevision; + +import android.graphics.Bitmap; + +final class FaceReId { + static final boolean CONTROLLED_POC = false; + + static ReIdProvider create() { return ReIdProvider.disabled(); } + static void load(ReIdProvider provider, ModelRegistry registry, InferenceEngine engine, int threads) {} + static float[] embed(ReIdProvider provider, Bitmap frame, Face face) { return null; } + static void setThreshold(ReIdProvider provider, float threshold) {} +} diff --git a/tests/FaceReIdTest.java b/tests/FaceReIdTest.java new file mode 100644 index 0000000..d564ea2 --- /dev/null +++ b/tests/FaceReIdTest.java @@ -0,0 +1,49 @@ +package com.it_screen.edgevision; + +import java.util.List; + +public final class FaceReIdTest { + public static void main(String[] args) { + ReIdProvider provider = FaceReId.create(); + FaceReId.setThreshold(provider, .55f); + VisitorSessions sessions = new VisitorSessions<>(provider); + + long first = sessions.observe(1, 0, vector(1, 0)).visitorId; + sessions.trackClosed(1); + VisitorSessions.Assignment returned = sessions.observe(2, 11000, vector(.8f, .6f)); + check(returned.kind == VisitorSessions.Kind.RECONNECTED && returned.visitorId == first, + "return with a different track and moderately changed vector"); + check(sessions.totalCreated() == 1 && sessions.repeatedCount() == 1, "deduplicated counters"); + sessions.trackClosed(2); + + VisitorSessions.Assignment unknown = sessions.observe(3, 12000, null); + check(unknown.kind == VisitorSessions.Kind.UNCERTAIN && sessions.uncertainCount() == 1, + "missing observation leaves comparison uncertain"); + sessions.trackClosed(3); + + List pair = List.of(new VisitorSessions.Candidate(first, 0), + new VisitorSessions.Candidate(20, 0)); + provider.observed(20, vector(1, 0)); + check(provider.match(vector(1, 0), pair) == ReIdProvider.UNCERTAIN, "tied candidates stay uncertain"); + provider.expired(20); + check(provider.match(vector(0, 1), pair.subList(0, 1)) == 0, "distinct embedding"); + sessions.expire(72000, 60000); + check(sessions.openCount() == 0 && !provider.hasObservation(first), "timeout removes the embedding"); + + sessions.observe(4, 72000, vector(1, 0)); + sessions.closeSessions(); + check(sessions.openCount() == 0 && sessions.totalCreated() == 3, "stop closes sessions, retaining count"); + System.out.println("Face Re-ID tests passed"); + } + + private static float[] vector(float a, float b) { + float[] v = new float[128]; + v[0] = a; + v[1] = b; + return v; + } + + private static void check(boolean condition, String message) { + if (!condition) throw new AssertionError(message); + } +} diff --git a/tools/check-poc-assets.py b/tools/check-poc-assets.py new file mode 100644 index 0000000..5addb65 --- /dev/null +++ b/tools/check-poc-assets.py @@ -0,0 +1,21 @@ +"""Verify the independently reviewed inventory for the consent-gated APK.""" +import hashlib +import json +from pathlib import Path +import sys + +poc = Path(__file__).resolve().parents[1] / "poc" +assets = poc / "assets" +lock = json.loads((poc / "asset-lock.json").read_text()) +inventory = { + path.relative_to(assets).as_posix(): hashlib.sha256(path.read_bytes()).hexdigest() + for path in assets.rglob("*") if path.is_file() +} +if inventory != lock: + sys.exit("Face Re-ID PoC assets differ from the reviewed inventory") +manifest = json.loads((assets / "models/sface-int8.json").read_text()) +if (manifest["productionAllowed"] is not False or manifest["controlledPocAllowed"] is not True + or manifest["sha256"] != inventory[manifest["file"]] + or manifest["size"] != (assets / manifest["file"]).stat().st_size): + sys.exit("SFace is only admitted in the controlled PoC") +print("Face Re-ID PoC asset gate passed")