Prevent duplicate visitor sessions from overlapping tracks and isolated matches

This commit is contained in:
EVA x10 Development 2026-11-26 14:11:26 +01:00
parent 37e37e5be1
commit f80f447302
7 changed files with 156 additions and 29 deletions

View File

@ -1,5 +1,5 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.it_screen.edgevision" android:versionCode="26" android:versionName="0.3.21">
package="com.it_screen.edgevision" android:versionCode="27" android:versionName="0.3.22">
<uses-sdk android:minSdkVersion="30" android:targetSdkVersion="34"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera.any" android:required="true"/>

View File

@ -1,4 +1,4 @@
# EVAx10 Video analitics v0.3.21
# EVAx10 Video analitics v0.3.22
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.21.apk`.
creation. The signed test build is `build/EVAx10-Video-analitics-0.3.22.apk`.
```text
adb install --no-incremental -r EVAx10-Video-analitics-0.3.21.apk
adb install --no-incremental -r EVAx10-Video-analitics-0.3.22.apk
adb shell am start -W -n com.it_screen.edgevision/.MainActivity
adb logcat -s EdgeVision EdgeVisionBench
```
@ -96,7 +96,7 @@ 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.21-Face-ReID-PoC.apk` as the separate package
`build/EVAx10-Video-analitics-0.3.22-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.
@ -111,9 +111,11 @@ 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 five seconds for a usable face or a stronger match across multiple frames; short tracks that end in that window
may be missed. An ambiguous match or missing face leaves the track unresolved. The estimate
are PoC settings and require field calibration. A new session requires three usable observations at least 400 ms apart.
When a geometrically overlapping track already owns a visible visitor session,
that session is eligible for face comparison and keeps its original track.
An overlapping candidate blocks a new visitor decision until the tracks can
be distinguished. Short tracks can remain uncounted. An ambiguous match or missing face leaves the track unresolved. The estimate
may undercount visitors whose faces never become usable. Poses, poor lighting and poor body-to-face
association can prevent a match. There is no liveness check.

View File

@ -20,14 +20,14 @@ if [[ ! -f build/ort.aar ]]; then
fi
python3 tools/check-production-assets.py
manifest=AndroidManifest.xml
apk=build/EVAx10-Video-analitics-0.3.21.apk
apk=build/EVAx10-Video-analitics-0.3.22.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"/' \
AndroidManifest.xml > "$manifest"
apk=build/EVAx10-Video-analitics-0.3.21-Face-ReID-PoC.apk
apk=build/EVAx10-Video-analitics-0.3.22-Face-ReID-PoC.apk
fi
rm -rf build/classes build/dex
mkdir -p build/classes build/dex

View File

@ -698,7 +698,8 @@ public final class MainActivity extends Activity {
now - track.activeSince < 5000L;
VisitorSessions.Assignment assignment;
try {
assignment = visitorSessions.observe(track.id, now, sample, awaitMoreEvidence);
assignment = visitorSessions.observe(track.id, now, sample, awaitMoreEvidence,
activeId -> overlapsActiveTrack(track, activeId));
} finally {
if (sample != null) Arrays.fill(sample, 0);
}
@ -720,6 +721,10 @@ public final class MainActivity extends Activity {
addVisitEvent("#" + track.id + " · Повторное обнаружение. Сессия V" +
assignment.visitorId + " продлена. Unique Visitors без изменений.");
break;
case DUPLICATE_TRACK:
addVisitEvent("#" + track.id + " · Совпадение с активной сессией V" +
assignment.visitorId + ". Дополнительный трек не увеличил Unique Visitors.");
break;
case UNCERTAIN:
addVisitEvent("#" + track.id + " · Сопоставление неопределённое. Unique Visitors без изменений.");
break;
@ -786,6 +791,20 @@ public final class MainActivity extends Activity {
});
}
private boolean overlapsActiveTrack(PersonTracker.Track track, int activeId) {
PersonTracker.Box a = track.observed;
for (PersonTracker.Track other : tracker.tracks()) {
if (other.id != activeId || other.state != PersonTracker.State.ACTIVE) continue;
PersonTracker.Box b = other.observed;
if (a.iou(b) >= .30f) return true;
// A truncated body box can have low IoU even when it surrounds the same head.
float headA = a.top + .18f * a.height(), headB = b.top + .18f * b.height();
return Math.abs(a.x() - b.x()) <= .25f * Math.min(a.width(), b.width()) &&
Math.abs(headA - headB) <= .18f * Math.min(a.height(), b.height());
}
return false;
}
private Rect faceSearchRegion(Bitmap frame) {
if (tracker.count(PersonTracker.State.ACTIVE) != 1) return null;
for (PersonTracker.Track track : tracker.tracks()) {

View File

@ -9,6 +9,7 @@ import java.util.Set;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.function.IntPredicate;
/** Owns visitor sessions independently of the lifetime of the camera's geometric tracks. */
final class VisitorSessions<Observation> {
@ -16,6 +17,11 @@ final class VisitorSessions<Observation> {
private final ReIdProvider<Observation> provider;
private final Map<Long, Session> open = new HashMap<>();
private final Map<Integer, Session> byTrack = new HashMap<>();
private static final int REQUIRED_DISTINCT_FRAMES = 3;
private static final long MIN_FRAME_SPACING_MS = 400;
private static final long MAX_EVIDENCE_GAP_MS = 8000;
private final Map<Integer, NewVisitorEvidence> newVisitorEvidence = new HashMap<>();
private final Set<Integer> reportedDuplicates = new HashSet<>();
private final Set<Integer> unresolved = new HashSet<>();
private final int[] ageCounts = new int[AudienceAggregator.AGES.length];
private String observationDetails = "";
@ -36,7 +42,13 @@ final class VisitorSessions<Observation> {
}
}
enum Kind { CREATED, UNCERTAIN, DEFERRED, RECONNECTED, CONTINUED }
enum Kind { CREATED, UNCERTAIN, DEFERRED, RECONNECTED, DUPLICATE_TRACK, CONTINUED }
private static final class NewVisitorEvidence {
int frames;
long lastSample;
Set<Long> candidates = Collections.emptySet();
}
static final class Assignment {
final long visitorId;
@ -76,10 +88,15 @@ final class VisitorSessions<Observation> {
}
Assignment observe(int trackId, long now, Observation observation) {
return observe(trackId, now, observation, false);
return observe(trackId, now, observation, false, ignored -> false);
}
Assignment observe(int trackId, long now, Observation observation, boolean awaitMoreEvidence) {
return observe(trackId, now, observation, awaitMoreEvidence, ignored -> false);
}
Assignment observe(int trackId, long now, Observation observation, boolean awaitMoreEvidence,
IntPredicate overlapsActiveTrack) {
observationDetails = "";
Session session = byTrack.get(trackId);
Kind kind = Kind.CONTINUED;
@ -88,21 +105,42 @@ final class VisitorSessions<Observation> {
long match = 0;
if (provider.enabled()) {
List<Candidate> candidates = new ArrayList<>();
boolean overlapping = false;
for (Session candidate : open.values()) {
if (!candidate.visible) candidates.add(new Candidate(candidate.id, candidate.lastSeen));
boolean duplicateCandidate = candidate.visible && candidate.track != null &&
overlapsActiveTrack.test(candidate.track);
overlapping |= duplicateCandidate;
if (!candidate.visible || duplicateCandidate)
candidates.add(new Candidate(candidate.id, candidate.lastSeen));
}
observationDetails = "eligible=" + candidates.size() + " open=" + open.size()
+ " waiting=" + awaitMoreEvidence;
if (awaitMoreEvidence && observation == null) return new Assignment(0, Kind.DEFERRED);
if (observation == null) match = ReIdProvider.UNCERTAIN;
else if (!candidates.isEmpty()) {
+ " active_overlap=" + overlapping + " waiting=" + awaitMoreEvidence;
if (observation == null) {
if (awaitMoreEvidence) return new Assignment(0, Kind.DEFERRED);
match = ReIdProvider.UNCERTAIN;
} else {
if (!candidates.isEmpty()) {
match = provider.match(observation, Collections.unmodifiableList(candidates));
observationDetails += " " + provider.matchDetails();
}
Session candidate = open.get(match);
if (candidate != null && !candidate.visible) {
if (candidate != null && candidate.visible) {
newVisitorEvidence.remove(trackId);
unresolved.remove(trackId);
// A coincident track does not take over the session from its visible owner.
return new Assignment(candidate.id, reportedDuplicates.add(trackId) ?
Kind.DUPLICATE_TRACK : Kind.DEFERRED);
}
if (candidate != null) {
session = candidate;
detach(session);
} else if (awaitMoreEvidence) return new Assignment(0, Kind.DEFERRED);
} else if (match == ReIdProvider.UNCERTAIN || overlapping) {
newVisitorEvidence.remove(trackId);
if (awaitMoreEvidence) return new Assignment(0, Kind.DEFERRED);
match = ReIdProvider.UNCERTAIN;
} else if (!confirmedNewVisitor(trackId, now, candidates)) {
return new Assignment(0, Kind.DEFERRED);
}
}
}
if (session != null) {
@ -114,6 +152,8 @@ final class VisitorSessions<Observation> {
return new Assignment(0, Kind.UNCERTAIN);
} else kind = Kind.CREATED;
unresolved.remove(trackId);
newVisitorEvidence.remove(trackId);
reportedDuplicates.remove(trackId);
if (session == null) {
session = new Session(nextId++, now);
open.put(session.id, session);
@ -129,6 +169,22 @@ final class VisitorSessions<Observation> {
return new Assignment(session.id, kind);
}
private boolean confirmedNewVisitor(int trackId, long now, List<Candidate> candidates) {
Set<Long> candidateIds = new HashSet<>();
for (Candidate candidate : candidates) candidateIds.add(candidate.id);
NewVisitorEvidence evidence = newVisitorEvidence.computeIfAbsent(trackId, ignored -> new NewVisitorEvidence());
if (!candidateIds.equals(evidence.candidates) || now - evidence.lastSample > MAX_EVIDENCE_GAP_MS) {
evidence.frames = 0;
evidence.candidates = candidateIds;
}
if (evidence.frames == 0 || now - evidence.lastSample >= MIN_FRAME_SPACING_MS) {
evidence.frames++;
evidence.lastSample = now;
}
observationDetails += " distinct_frames=" + evidence.frames + "/" + REQUIRED_DISTINCT_FRAMES;
return evidence.frames >= REQUIRED_DISTINCT_FRAMES;
}
void updateAge(int trackId, Integer age) {
Session session = byTrack.get(trackId);
int unknown = AudienceAggregator.ageGroup(null);
@ -153,12 +209,16 @@ final class VisitorSessions<Observation> {
void trackClosed(int trackId) {
unresolved.remove(trackId);
newVisitorEvidence.remove(trackId);
reportedDuplicates.remove(trackId);
Session session = byTrack.get(trackId);
if (session != null) detach(session);
}
void releaseTracks() {
unresolved.clear();
newVisitorEvidence.clear();
reportedDuplicates.clear();
for (Session session : open.values()) detach(session);
}
@ -172,6 +232,8 @@ final class VisitorSessions<Observation> {
void closeSessions() {
unresolved.clear();
newVisitorEvidence.clear();
reportedDuplicates.clear();
for (Session session : open.values()) provider.expired(session.id);
byTrack.clear();
open.clear();

View File

@ -8,11 +8,20 @@ public final class FaceReIdTest {
FaceReId.setThreshold(provider, .55f);
VisitorSessions<float[]> sessions = new VisitorSessions<>(provider);
long first = sessions.observe(1, 0, vector(1, 0)).visitorId;
sessions.observe(1, 0, vector(1, 0));
sessions.observe(1, 400, vector(1, 0));
long first = sessions.observe(1, 800, vector(1, 0)).visitorId;
sessions.observe(1, 1000, vector(.8f, .6f));
check(sessions.ageCounts()[AudienceAggregator.ageGroup(null)] == 1,
"new session starts without an age estimate");
sessions.updateAge(1, 34);
check(sessions.observe(9, 1200, vector(1, 0), false, id -> id == 1).kind ==
VisitorSessions.Kind.DUPLICATE_TRACK && sessions.totalCreated() == 1,
"overlapping simultaneous track compares against the visible session");
check(sessions.observe(9, 1600, vector(1, 0), false, id -> id == 1).kind ==
VisitorSessions.Kind.DEFERRED && sessions.repeatedCount() == 0,
"overlapping duplicate neither steals the session nor counts a return");
sessions.trackClosed(9);
sessions.trackClosed(1);
check(sessions.observe(2, 120000, vector(0, -1), true).kind == VisitorSessions.Kind.DEFERRED &&
sessions.totalCreated() == 1, "first low-quality comparison does not create a duplicate");
@ -48,11 +57,43 @@ public final class FaceReIdTest {
check(sessions.ageCounts()[AudienceAggregator.ageGroup(34)] == 1,
"expired sessions still count in this run's age breakdown");
sessions.observe(4, 183000, vector(1, 0));
sessions.observe(4, 183400, vector(1, 0));
sessions.observe(4, 183800, vector(1, 0));
sessions.closeSessions();
check(sessions.openCount() == 0 && sessions.totalCreated() == 2, "stop closes sessions, retaining count");
testDistinctEvidence();
System.out.println("Face Re-ID tests passed");
}
private static void testDistinctEvidence() {
ReIdProvider<float[]> provider = FaceReId.create();
FaceReId.setThreshold(provider, .55f);
VisitorSessions<float[]> sessions = new VisitorSessions<>(provider);
sessions.observe(1, 0, vector(1, 0));
sessions.observe(1, 400, vector(1, 0));
sessions.observe(1, 800, vector(1, 0));
sessions.trackClosed(1);
sessions.observe(2, 3000, vector(.543f, .840f));
sessions.observe(2, 4000, vector(.488f, .873f));
check(sessions.observe(2, 5000, vector(.422f, .907f)).kind == VisitorSessions.Kind.DEFERRED &&
sessions.totalCreated() == 1, "two inconclusive frames plus one low match do not create a visitor");
sessions.observe(2, 5400, vector(.50f, .866f));
sessions.observe(2, 6000, vector(0, -1));
sessions.observe(2, 6100, vector(0, -1));
check(sessions.observe(2, 6400, vector(0, -1)).kind == VisitorSessions.Kind.DEFERRED,
"an uncertain frame discards previous distinct evidence and close frames do not count twice");
check(sessions.observe(2, 6800, vector(0, -1)).kind == VisitorSessions.Kind.CREATED &&
sessions.totalCreated() == 2, "three spaced distinct frames confirm a different visitor");
check(sessions.observe(3, 7000, vector(1, 0), false, id -> false).kind ==
VisitorSessions.Kind.RECONNECTED, "unoccupied session retains priority for a genuine return");
sessions.observe(4, 7400, vector(-1, 0), false, id -> false);
sessions.observe(4, 7800, vector(-1, 0), false, id -> false);
check(sessions.observe(4, 8200, vector(-1, 0), false, id -> false).kind ==
VisitorSessions.Kind.CREATED, "a spatially separate visitor can be counted alongside visible sessions");
}
private static float[] vector(float a, float b) {
float[] v = new float[128];
v[0] = a;

View File

@ -7,8 +7,9 @@ public final class VisitorSessionsTest {
public static void main(String[] args) {
VisitorSessions<String> sessions = new VisitorSessions<>(new TestProvider());
long first = sessions.observe(1, 0, "A").visitorId;
sessions.observe(1, 1000, "A");
sessions.observe(1, 0, "A");
sessions.observe(1, 500, "A");
long first = sessions.observe(1, 1000, "A").visitorId;
sessions.temporarilyLost(1);
sessions.trackClosed(1);
sessions.expire(TIMEOUT - 1, TIMEOUT);
@ -18,13 +19,15 @@ public final class VisitorSessionsTest {
sessions.totalCreated() == 1, "return binds new track without counting again");
check(sessions.observe(3, TIMEOUT + 10, "A").visitorId != first,
"two visible tracks cannot claim the same session");
sessions.expire(TIMEOUT + 100, TIMEOUT);
sessions.observe(3, TIMEOUT + 410, "B");
sessions.observe(3, TIMEOUT + 810, "B");
sessions.expire(TIMEOUT + 900, TIMEOUT);
check(sessions.openCount() == 2, "return extended expiry");
sessions.releaseTracks();
check(sessions.observe(4, TIMEOUT + 200, "oldest").visitorId == first, "release preserves sessions");
sessions.expire(TIMEOUT * 2 + 200, TIMEOUT);
check(sessions.observe(4, TIMEOUT + 1000, "oldest").visitorId == first, "release preserves sessions");
sessions.expire(TIMEOUT * 2 + 1000, TIMEOUT);
check(sessions.openCount() == 0, "expiry is inclusive and based on last sighting");
check(sessions.observe(5, TIMEOUT * 2 + 200, "A").visitorId != first, "expired identity not reused");
check(sessions.observe(5, TIMEOUT * 2 + 1000, "A").visitorId != first, "expired identity not reused");
sessions.clear();
check(sessions.openCount() == 0 && sessions.totalCreated() == 0, "reset clears state");