Decouple visitor sessions from tracking and add disabled Re-ID provider
This commit is contained in:
parent
59ee0842b9
commit
192f41a63b
|
|
@ -1,5 +1,5 @@
|
|||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="com.it_screen.edgevision" android:versionCode="7" android:versionName="0.3.2">
|
||||
package="com.it_screen.edgevision" android:versionCode="8" android:versionName="0.3.3">
|
||||
<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"/>
|
||||
|
|
|
|||
14
README.md
14
README.md
|
|
@ -1,4 +1,4 @@
|
|||
# EVAx10 Video analitics v0.3.2
|
||||
# EVAx10 Video analitics v0.3.3
|
||||
|
||||
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.2.apk`.
|
||||
creation. The signed test build is `build/EVAx10-Video-analitics-0.3.3.apk`.
|
||||
|
||||
```text
|
||||
adb install --no-incremental -r EVAx10-Video-analitics-0.3.2.apk
|
||||
adb install --no-incremental -r EVAx10-Video-analitics-0.3.3.apk
|
||||
adb shell am start -W -n com.it_screen.edgevision/.MainActivity
|
||||
adb logcat -s EdgeVision EdgeVisionBench
|
||||
```
|
||||
|
|
@ -55,7 +55,7 @@ The right panel starts with Current visitors, an estimate of people visible now.
|
|||
**Журнал трекинга** shows time-stamped confirmation, temporary loss,
|
||||
restoration, and closure by track ID. A restoration lists the time since
|
||||
first and last observation. **More** opens a scrollable diagnostics
|
||||
dialog with live values and definitions. A restored ID does not increment **Total visits**.
|
||||
dialog with live values and definitions. A restored ID does not increment **Confirmed Tracks**.
|
||||
Confirmed Tracks includes the existing persisted confirmed-track total until **Reset Statistics** is used. It is not a unique-visitor history. Reset while someone is in the frame starts a new tracking session.
|
||||
|
||||
Position, shape and motion determine association. A return close to the
|
||||
|
|
@ -70,3 +70,9 @@ bench results and limits.
|
|||
## Delivered device build
|
||||
|
||||
The previous bench APK is preserved as `build/EdgeVision-0.1.apk`.
|
||||
|
||||
**Visitor Session Timeout** is a separate setting (30 minutes by default).
|
||||
Closing the body track leaves its visitor session eligible until that
|
||||
timeout. The on-device Re-ID provider is disabled. See the
|
||||
[session and Re-ID report](REID_EVALUATION.md) for the lifecycle,
|
||||
benchmarks, licensing, and limits.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,80 @@
|
|||
# Visitor sessions and Re-ID evaluation
|
||||
|
||||
## Session lifecycle in 0.3.3
|
||||
|
||||
A geometric tracking ID is associated with a visitor-session ID after
|
||||
confirmation. Closing a track releases its binding and preserves the
|
||||
session until the configured timeout. Every observed frame from the bound
|
||||
track refreshes the session's monotonic last-seen timestamp. The default
|
||||
timeout is 30 minutes, configurable from 1 to 1440 minutes in **Tracking
|
||||
settings → Visitor Session Timeout (minutes)**.
|
||||
|
||||
Before processing detections, the session manager expires sessions whose
|
||||
last sighting meets the limit. While capture is idle, expiration is
|
||||
evaluated when processing resumes. Stop/Start on the same screen releases
|
||||
track bindings and retains open sessions. Reset Statistics or recreating
|
||||
the activity clears these in-memory sessions. There is no persistent
|
||||
visitor-session database or historical unique-person count.
|
||||
|
||||
A pluggable ReIdProvider may choose a confidently matched, open, unoccupied
|
||||
session and attach the new track. The session manager verifies the match
|
||||
against its own current state. Simultaneously visible tracks cannot claim
|
||||
one session. A successful reconnect refreshes last seen and leaves the
|
||||
created-session count unchanged. An unmatched track creates a new session.
|
||||
The test provider operates on synthetic data. The application supplies only
|
||||
the disabled provider, which neither receives nor stores observations.
|
||||
There is no timer-based or one-candidate identity fallback.
|
||||
|
||||
**More** reports simulator-independent technical diagnostics: open and created
|
||||
sessions, timeout, and Re-ID status. Those numbers do not represent unique
|
||||
visitors. A 30-minute session window and a unique-person count over a day
|
||||
are different requirements. Daily or custom-range deduplication requires
|
||||
an approved stable identifier over that reporting horizon and a separate
|
||||
retention decision.
|
||||
|
||||
## Candidate comparison
|
||||
|
||||
| | Person Re-ID | Face Re-ID |
|
||||
| --- | --- | --- |
|
||||
| Candidate | Intel Open Model Zoo person-reidentification-retail-0286, FP32 IR converted to ONNX for the lab | OpenCV Zoo SFace 2021dec INT8 ONNX |
|
||||
| Input / output | Whole body, 256×128 → 256 floats | Aligned face, 112×112 → 128 floats |
|
||||
| Published evidence | Intel reports Market-1501 rank-1 94.8%, mAP 83.7%. This is closed-set retrieval. [Model card](https://github.com/openvinotoolkit/open_model_zoo/blob/master/models/intel/person-reidentification-retail-0286/README.md) | OpenCV reports LFW 99.60% and CPLFW 91.05% for the full-size SFace reference model. These are pair-verification results. The INT8 candidate was not checked against those labels here. [OpenCV tutorial](https://docs.opencv.org/4.x/d0/dd4/tutorial_dnn_face.html) |
|
||||
| Expected field limitations | Similar clothing or uniforms can cause false merges. Changing clothes, heavy occlusion, or a partial body crop can cause false splits. A visible face is unnecessary. | Requires a visible, adequately lit face at a suitable pose. A mask, head turn, or distance may leave no usable observation. |
|
||||
| Licensing review | The named IR artifacts and their SHA-384 checksums appear in a [manifest](https://github.com/openvinotoolkit/open_model_zoo/blob/master/models/intel/person-reidentification-retail-0286/model.yml) that points to Apache-2.0. Review source checkpoint, training-data evidence, and conversion parity before admitting the derived weights in production. Torchreid OSNet checkpoints are a separate source. Their [maintainer limits pretrained weights to research](https://github.com/KaiyangZhou/deep-person-reid/issues/520). | The pinned model directory explicitly covers its files with [Apache-2.0](https://github.com/opencv/opencv_zoo/blob/eb9f4f2d4b79b58e5513b5d25d5f0243a8357bf4/models/face_recognition_sface/README.md#license). The question about provenance for the exact INT8 release remains [open](https://github.com/opencv/opencv_zoo/issues/318). No candidate approval or production packaging change in this release. |
|
||||
| Privacy | An appearance descriptor that links a person's visits can be personal data. If the method identifies people using physical or behavioural characteristics, biometric rules can apply even when facial features are omitted. | Facial templates used to identify returning people require a biometric assessment. Local processing and a short TTL reduce exposure but do not remove that obligation. [EDPB video guidelines](https://www.edpb.europa.eu/system/files/documents/files/file1/edpb_guidelines_201903_video_devices_en_0.pdf) |
|
||||
|
||||
The published accuracy figures are on different data and protocols. They do
|
||||
not establish which method is more accurate on this camera. Before approval,
|
||||
use the same labelled returns and impostor arrivals in both arms. Report
|
||||
false merges, false splits, no-match coverage, and errors by elapsed time,
|
||||
lighting, pose, clothing similarity, and occlusion. Use only participants
|
||||
who have agreed to the test. Evaluate retention, access, deletion, and legal
|
||||
basis before any field deployment.
|
||||
|
||||
## RK3566 measurements
|
||||
|
||||
Separate temporary Android app, ONNX Runtime 1.32.0 ARM64, CPU, two intra-op
|
||||
threads, 10 warm-up passes and 50 timed passes per run, two runs alternating
|
||||
the candidates. Inputs were deterministic synthetic tensors. Timings cover
|
||||
creating the input tensor, model execution and reading the output buffer.
|
||||
They exclude camera, alignment, search and production contention. No
|
||||
images, identities or templates from people were used. The bench APK was
|
||||
removed from the tablet afterwards.
|
||||
|
||||
| Model | Run 1 p50 / p95 | Run 2 p50 / p95 |
|
||||
| --- | ---: | ---: |
|
||||
| Intel person-reidentification-retail-0286 FP32 | 204.2 / 213.9 ms | 203.6 / 267.0 ms |
|
||||
| SFace INT8 | 101.3 / 108.2 ms | 100.9 / 102.4 ms |
|
||||
|
||||
The earlier body-tracking benchmark had median 118.5 ms for detector plus
|
||||
tracker at a 5 FPS target. Adding either model synchronously to every frame
|
||||
would exceed a 200 ms frame budget at those median latencies. Benchmark a
|
||||
candidate at new-track/reattachment time with a bounded work queue before
|
||||
committing to an architecture and runtime budget.
|
||||
|
||||
Lab ONNX SHA-256: person
|
||||
`a4a96924dfd42b84d4e326a6b8d5ce87ce53acc508a52c73cb51584e56eb9853`,
|
||||
SFace `2b0e941e6f16cc048c20aee0c8e31f569118f65d702914540f7bfdc14048d78a`.
|
||||
The Intel FP32 IR SHA-384 values matched the upstream manifest. The converted
|
||||
graph was validated by successful execution, not numerical IR parity.
|
||||
No bench model weights or code are in the production APK.
|
||||
4
build.sh
4
build.sh
|
|
@ -47,5 +47,5 @@ PY
|
|||
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.2.apk build/aligned.apk
|
||||
"$jdk/bin/java.exe" -jar "$(wslpath -w "$tools/lib/apksigner.jar")" verify --verbose build/EVAx10-Video-analitics-0.3.2.apk
|
||||
"$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.3.apk build/aligned.apk
|
||||
"$jdk/bin/java.exe" -jar "$(wslpath -w "$tools/lib/apksigner.jar")" verify --verbose build/EVAx10-Video-analitics-0.3.3.apk
|
||||
|
|
|
|||
|
|
@ -29,6 +29,10 @@ final class DiagnosticsPanel {
|
|||
{"created_tracks", "Created Tracks", "", "Все созданные за сессию треки, включая те, которые ещё не подтвердились."},
|
||||
{"restored_tracks", "Restored Tracks", "", "Сколько раз программа восстановила ранее подтверждённый трек с тем же ID."},
|
||||
{"closed_tracks", "Closed Tracks", "", "Треки, закрытые после истечения таймаута потери."},
|
||||
{"open_visitor_sessions", "Open Visitor Sessions", "", "Сессии, у которых ещё не истёк таймаут от последнего наблюдения. Сессия может оставаться открытой после закрытия трека."},
|
||||
{"created_visitor_sessions", "Created Visitor Sessions", "", "Сколько сессий создано с запуска или сброса. Пока Re-ID отключён, это технический показатель, а не число уникальных людей."},
|
||||
{"visitor_session_timeout_minutes", "Visitor Session Timeout", " мин", "Сколько времени с последнего обнаружения сохраняется возможность восстановить сессию. Сам таймаут не подтверждает совпадение."},
|
||||
{"reid_status", "Re-ID Provider", "", "Статус сопоставления сессий. Disabled означает, что приложение не сравнивает людей между разными треками."},
|
||||
{"id_switches", "ID Switches", "", "Случаи, когда одному и тому же человеку ошибочно присвоили другой ID. Для подсчёта нужна эталонная разметка. В прямом эфире — N/A."},
|
||||
{"average_dwell_s", "Average Dwell Time", " с", "Среднее время от первого до последнего наблюдения подтверждённых треков в этой сессии. Учитываются текущие и закрытые треки. Ожидание закрытия после последнего кадра не прибавляется."},
|
||||
{"tracking_fps", "Tracking FPS", " кадр/с", "Фактическое количество кадров в секунду, которые обработал трекер людей."},
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ 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<VisitorObservation> visitorSessions = new VisitorSessions<>(ReIdProvider.disabled());
|
||||
private final ArrayDeque<String> visitEvents = new ArrayDeque<>();
|
||||
private final AudienceAggregator totals = new AudienceAggregator();
|
||||
private final Benchmark benchmark = new Benchmark();
|
||||
|
|
@ -211,6 +212,8 @@ public final class MainActivity extends Activity {
|
|||
EditText confirmation = trackingField(form, "Confirmation Time (ms)", "tracking_confirm_ms", 1000);
|
||||
EditText lost = trackingField(form, "Lost Track Timeout (ms)", "tracking_lost_ms", 10000);
|
||||
EditText fps = trackingField(form, "Target Tracking FPS", "tracking_fps", 5);
|
||||
EditText visitorTimeout = trackingField(form, "Visitor Session Timeout (minutes)",
|
||||
"visitor_session_timeout_minutes", VisitorSessions.DEFAULT_TIMEOUT_MINUTES);
|
||||
form.addView(text("Count Once Per Track: true\nBiometric Matching: false", 14));
|
||||
android.app.AlertDialog dialog = new android.app.AlertDialog.Builder(this)
|
||||
.setTitle("Tracking settings").setView(form)
|
||||
|
|
@ -221,14 +224,17 @@ public final class MainActivity extends Activity {
|
|||
int confirmationMs = Integer.parseInt(confirmation.getText().toString());
|
||||
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 ||
|
||||
lostMs > 120000 || trackingFps < 1 || trackingFps > 15)
|
||||
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).apply();
|
||||
.putInt("tracking_fps", trackingFps)
|
||||
.putInt("visitor_session_timeout_minutes", visitorTimeoutMinutes).apply();
|
||||
dialog.dismiss();
|
||||
} catch (IllegalArgumentException error) {
|
||||
Toast.makeText(this, "Confirmation 0–10000 ms, lost 1000–120000 ms, FPS 1–15",
|
||||
Toast.makeText(this, "Confirmation 0–10000 ms, lost 1000–120000 ms, FPS 1–15, session timeout 1–1440 min",
|
||||
Toast.LENGTH_LONG).show();
|
||||
}
|
||||
}));
|
||||
|
|
@ -315,7 +321,8 @@ public final class MainActivity extends Activity {
|
|||
(String) provider.getSelectedItem(), Integer.parseInt(threadCount.getSelectedItem().toString()),
|
||||
faceModels.get(faceModel.getSelectedItemPosition()), demographicModels.get(ageModel.getSelectedItemPosition()),
|
||||
preferences.getInt("tracking_confirm_ms", 1000), preferences.getInt("tracking_lost_ms", 10000),
|
||||
preferences.getInt("tracking_fps", 5));
|
||||
preferences.getInt("tracking_fps", 5), preferences.getInt("visitor_session_timeout_minutes",
|
||||
VisitorSessions.DEFAULT_TIMEOUT_MINUTES) * 60000L);
|
||||
}
|
||||
|
||||
private void startCamera() {
|
||||
|
|
@ -333,7 +340,7 @@ public final class MainActivity extends Activity {
|
|||
skipped.set(0);
|
||||
inference.execute(() -> {
|
||||
tracker.clear();
|
||||
|
||||
visitorSessions.releaseTracks();
|
||||
visitEvents.clear();
|
||||
ui.post(() -> { if (generation == run) trackingLog.setText("Ожидание посетителей"); });
|
||||
nextFaceFrame = 0;
|
||||
|
|
@ -406,6 +413,11 @@ public final class MainActivity extends Activity {
|
|||
List<PersonTracker.Detection> people = personDetector.detect(frame);
|
||||
List<PersonTracker.Event> events = tracker.update(people, now, config.confirmMs, config.lostMs);
|
||||
double trackingMs = ms(inferenceAt);
|
||||
visitorSessions.expire(now, config.visitorTimeoutMs);
|
||||
for (PersonTracker.Event event : events) {
|
||||
if (event.state == PersonTracker.State.TEMPORARILY_LOST) visitorSessions.temporarilyLost(event.track.id);
|
||||
if (event.state == PersonTracker.State.CLOSED) visitorSessions.trackClosed(event.track.id);
|
||||
}
|
||||
boolean changed = false;
|
||||
for (PersonTracker.Event event : events) {
|
||||
String message;
|
||||
|
|
@ -430,6 +442,22 @@ 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<DrawBox> overlays = new ArrayList<>();
|
||||
|
|
@ -544,6 +572,10 @@ public final class MainActivity extends Activity {
|
|||
.put("average_dwell_s", tracker.averageDwellSeconds())
|
||||
.put("tracking_target_fps", config.trackingFps).put("confirmation_ms", config.confirmMs)
|
||||
.put("lost_timeout_ms", config.lostMs)
|
||||
.put("visitor_session_timeout_minutes", config.visitorTimeoutMs / 60000L)
|
||||
.put("open_visitor_sessions", visitorSessions.openCount())
|
||||
.put("created_visitor_sessions", visitorSessions.totalCreated())
|
||||
.put("reid_status", visitorSessions.matchingEnabled() ? "Enabled" : "Disabled")
|
||||
.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)
|
||||
|
|
@ -582,7 +614,7 @@ public final class MainActivity extends Activity {
|
|||
private void reset() {
|
||||
inference.execute(() -> {
|
||||
tracker.clear();
|
||||
|
||||
visitorSessions.clear();
|
||||
visitEvents.clear();
|
||||
totals.reset();
|
||||
persist();
|
||||
|
|
@ -607,7 +639,7 @@ public final class MainActivity extends Activity {
|
|||
setRunning(false);
|
||||
setStatus(message);
|
||||
inference.execute(() -> {
|
||||
|
||||
visitorSessions.releaseTracks();
|
||||
int visits = totals.visits;
|
||||
int[] genders = totals.genders.clone(), ages = totals.ages.clone();
|
||||
ui.post(() -> { if (!running) updateStats(0, visits, genders, ages); });
|
||||
|
|
@ -669,10 +701,11 @@ public final class MainActivity extends Activity {
|
|||
final String resolution, provider;
|
||||
final int interval, threads;
|
||||
final int confirmMs, lostMs, trackingFps;
|
||||
final long visitorTimeoutMs;
|
||||
final float detection, classification;
|
||||
final ModelRegistry.Entry face, age;
|
||||
Settings(String resolution, int interval, float detection, float classification, String provider,
|
||||
int threads, ModelRegistry.Entry face, ModelRegistry.Entry age, int confirmMs, int lostMs, int trackingFps) {
|
||||
int threads, ModelRegistry.Entry face, ModelRegistry.Entry age, int confirmMs, int lostMs, int trackingFps, long visitorTimeoutMs) {
|
||||
this.resolution = resolution;
|
||||
this.interval = interval;
|
||||
this.detection = detection;
|
||||
|
|
@ -684,6 +717,7 @@ public final class MainActivity extends Activity {
|
|||
this.confirmMs = confirmMs;
|
||||
this.lostMs = lostMs;
|
||||
this.trackingFps = trackingFps;
|
||||
this.visitorTimeoutMs = visitorTimeoutMs;
|
||||
}
|
||||
boolean sameModels(Settings other) {
|
||||
return other.face == face && other.age == age && other.provider.equals(provider) && other.threads == threads;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,22 @@
|
|||
package com.it_screen.edgevision;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** Optional identity service. The application currently binds only the disabled implementation. */
|
||||
interface ReIdProvider<Observation> {
|
||||
boolean enabled();
|
||||
|
||||
/** Return a confidently matched candidate ID, or zero when there is no confident match. */
|
||||
long match(Observation observation, List<VisitorSessions.Candidate> candidates);
|
||||
void observed(long visitorId, Observation observation);
|
||||
void expired(long visitorId);
|
||||
|
||||
static <T> ReIdProvider<T> disabled() {
|
||||
return new ReIdProvider<T>() {
|
||||
@Override public boolean enabled() { return false; }
|
||||
@Override public long match(T observation, List<VisitorSessions.Candidate> candidates) { return 0; }
|
||||
@Override public void observed(long visitorId, T observation) { }
|
||||
@Override public void expired(long visitorId) { }
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,126 @@
|
|||
package com.it_screen.edgevision;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** Owns visitor sessions independently of the lifetime of the camera's geometric tracks. */
|
||||
final class VisitorSessions<Observation> {
|
||||
static final int DEFAULT_TIMEOUT_MINUTES = 30;
|
||||
private final ReIdProvider<Observation> provider;
|
||||
private final Map<Long, Session> open = new HashMap<>();
|
||||
private final Map<Integer, Session> byTrack = new HashMap<>();
|
||||
private long nextId = 1;
|
||||
private long totalCreated;
|
||||
|
||||
VisitorSessions(ReIdProvider<Observation> provider) { this.provider = provider; }
|
||||
|
||||
static final class Candidate {
|
||||
final long id;
|
||||
final long lastSeenMs;
|
||||
Candidate(long id, long lastSeenMs) {
|
||||
this.id = id;
|
||||
this.lastSeenMs = lastSeenMs;
|
||||
}
|
||||
}
|
||||
|
||||
enum Kind { CREATED, RECONNECTED, CONTINUED }
|
||||
|
||||
static final class Assignment {
|
||||
final long visitorId;
|
||||
final Kind kind;
|
||||
Assignment(long visitorId, Kind kind) { this.visitorId = visitorId; this.kind = kind; }
|
||||
}
|
||||
|
||||
private static final class Session {
|
||||
final long id;
|
||||
long lastSeen;
|
||||
Integer track;
|
||||
boolean visible;
|
||||
Session(long id, long now) { this.id = id; lastSeen = now; }
|
||||
}
|
||||
|
||||
boolean matchingEnabled() { return provider.enabled(); }
|
||||
int openCount() { return open.size(); }
|
||||
long totalCreated() { return totalCreated; }
|
||||
|
||||
void expire(long now, long timeoutMs) {
|
||||
Iterator<Session> items = open.values().iterator();
|
||||
while (items.hasNext()) {
|
||||
Session session = items.next();
|
||||
if (now - session.lastSeen < timeoutMs) continue;
|
||||
detach(session);
|
||||
items.remove();
|
||||
provider.expired(session.id);
|
||||
}
|
||||
}
|
||||
|
||||
Assignment observe(int trackId, long now, Observation observation) {
|
||||
Session session = byTrack.get(trackId);
|
||||
Kind kind = Kind.CONTINUED;
|
||||
if (session == null) {
|
||||
// No timer, spatial match, or "only candidate" fallback can identify a visitor.
|
||||
if (provider.enabled()) {
|
||||
List<Candidate> 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));
|
||||
Session candidate = open.get(match);
|
||||
if (candidate != null && !candidate.visible) {
|
||||
session = candidate;
|
||||
detach(session);
|
||||
}
|
||||
}
|
||||
}
|
||||
kind = session == null ? Kind.CREATED : Kind.RECONNECTED;
|
||||
if (session == null) {
|
||||
session = new Session(nextId++, now);
|
||||
open.put(session.id, session);
|
||||
totalCreated++;
|
||||
}
|
||||
session.track = trackId;
|
||||
byTrack.put(trackId, session);
|
||||
}
|
||||
session.visible = true;
|
||||
session.lastSeen = now;
|
||||
if (provider.enabled()) provider.observed(session.id, observation);
|
||||
return new Assignment(session.id, kind);
|
||||
}
|
||||
|
||||
void reserveObservedTrack(int trackId) {
|
||||
Session session = byTrack.get(trackId);
|
||||
if (session != null) session.visible = true;
|
||||
}
|
||||
|
||||
void temporarilyLost(int trackId) {
|
||||
Session session = byTrack.get(trackId);
|
||||
if (session != null) session.visible = false;
|
||||
}
|
||||
|
||||
void trackClosed(int trackId) {
|
||||
Session session = byTrack.get(trackId);
|
||||
if (session != null) detach(session);
|
||||
}
|
||||
|
||||
void releaseTracks() {
|
||||
for (Session session : open.values()) detach(session);
|
||||
}
|
||||
|
||||
void clear() {
|
||||
for (Session session : open.values()) provider.expired(session.id);
|
||||
byTrack.clear();
|
||||
open.clear();
|
||||
totalCreated = 0;
|
||||
}
|
||||
|
||||
private void detach(Session session) {
|
||||
if (session.track != null) byTrack.remove(session.track);
|
||||
session.track = null;
|
||||
session.visible = false;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,57 @@
|
|||
package com.it_screen.edgevision;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public final class VisitorSessionsTest {
|
||||
private static final long TIMEOUT = 30 * 60 * 1000L;
|
||||
|
||||
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.temporarilyLost(1);
|
||||
sessions.trackClosed(1);
|
||||
sessions.expire(TIMEOUT - 1, TIMEOUT);
|
||||
check(sessions.openCount() == 1, "session survives track closure");
|
||||
VisitorSessions.Assignment returned = sessions.observe(2, TIMEOUT - 1, "A");
|
||||
check(returned.visitorId == first && returned.kind == VisitorSessions.Kind.RECONNECTED &&
|
||||
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);
|
||||
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.openCount() == 0, "expiry is inclusive and based on last sighting");
|
||||
check(sessions.observe(5, TIMEOUT * 2 + 200, "A").visitorId != first, "expired identity not reused");
|
||||
sessions.clear();
|
||||
check(sessions.openCount() == 0 && sessions.totalCreated() == 0, "reset clears state");
|
||||
|
||||
VisitorSessions<String> disabled = new VisitorSessions<>(ReIdProvider.disabled());
|
||||
long original = disabled.observe(1, 0, null).visitorId;
|
||||
disabled.temporarilyLost(1);
|
||||
disabled.reserveObservedTrack(1);
|
||||
check(disabled.observe(1, 16000, null).visitorId == original &&
|
||||
disabled.totalCreated() == 1, "same visible track stays bound without Re-ID");
|
||||
disabled.trackClosed(1);
|
||||
disabled.expire(17000, TIMEOUT);
|
||||
check(disabled.observe(2, 17000, null).visitorId != original &&
|
||||
disabled.openCount() == 2, "timeout alone never links different tracks");
|
||||
System.out.println("Visitor session lifecycle tests passed");
|
||||
}
|
||||
|
||||
private static void check(boolean ok, String reason) {
|
||||
if (!ok) throw new AssertionError(reason);
|
||||
}
|
||||
|
||||
private static final class TestProvider implements ReIdProvider<String> {
|
||||
@Override public boolean enabled() { return true; }
|
||||
@Override public long match(String observation, List<VisitorSessions.Candidate> candidates) {
|
||||
// A deterministic test double. No visual or biometric data are used.
|
||||
return candidates.stream().mapToLong(c -> c.id).min().orElse(0);
|
||||
}
|
||||
@Override public void observed(long visitorId, String observation) { }
|
||||
@Override public void expired(long visitorId) { }
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue