File size: 10,325 Bytes
5a26b95 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 | """Unit tests for logic that needs no neural network."""
import json, os, sqlite3
from datetime import datetime
import numpy as np
import pytest
from core import (ARC, CHIP_DST, DAILY, MODELS, UNKNOWN, Attendance, Config, Database, Gallery, Match, Tracker, daily_rows, export, hash_password,
hours, imwrite, iou, mask_url, monthly_rows, pose, similarity, verify_password)
unit = lambda v: np.asarray(v, np.float32) / np.linalg.norm(v)
D = lambda *a: datetime(2026, 1, *a)
class F:
def __init__(self, box, emb=None, score=0.9): self.box, self.emb, self.reasons, self.score, self.chip = np.array(box, float), emb, [], score, (b"jpg", "{}")
@pytest.fixture
def cfg(tmp_path): return Config(str(tmp_path / "s.json"))
@pytest.fixture
def db(tmp_path):
d = Database(str(tmp_path / "t.db")); yield d; d.close()
def test_config_and_security(cfg):
assert cfg.get("profile.threshold") == MODELS["facenet_vggface2"]["threshold"] # per-model values, defaults from MODELS
cfg.set("profile.threshold", 0.7); cfg.set("model", "arcface_mbf"); cfg.save()
c = Config(cfg.path); assert c.get("profile.threshold") == MODELS["arcface_mbf"]["threshold"] and c.get("camera.transport") == "tcp"
c.set("model", "facenet_vggface2"); assert c.get("profile.threshold") == 0.7
with open(cfg.path, "w") as f: json.dump({"model": "models/vggface2.onnx", "runtime": "tflite"}, f) # old or hand-edited file
c = Config(cfg.path); assert (c.get("model"), c.get("runtime")) == ("facenet_vggface2", "onnx")
h = hash_password("secret123"); assert verify_password("secret123", h) and not verify_password("x", h) and not verify_password("x", "junk")
assert mask_url("rtsp://admin:pa55@10.0.0.5/s") == "rtsp://admin:***@10.0.0.5/s" and mask_url("rtsp://h/s") == "rtsp://h/s"
def test_gallery(cfg):
rng = np.random.default_rng(0); a, b = unit(rng.normal(size=512)), unit(rng.normal(size=512))
noisy = lambda v: unit(v + 0.025 * rng.normal(size=512))
g = Gallery(cfg); assert not g.match([a])[0].known
g.set(np.array([1] * 5 + [2] * 3), np.stack([noisy(a) for _ in range(5)] + [noisy(b) for _ in range(3)]),
{1: {"name": "Alice", "emp_code": "E1"}, 2: {"name": "Bob", "emp_code": "E2"}})
m = g.match([noisy(a), unit(rng.normal(size=512))])
assert g.persons == 2 and g.samples == 8 and m[0].name == "Alice" and m[0].sim > 0.6 and not m[1].known
g.set(np.array([1, 2]), np.stack([a, a]), {1: {"name": "A", "emp_code": ""}, 2: {"name": "B", "emp_code": ""}})
assert not g.match([a])[0].known # equal scores -> margin rule rejects
def test_tracker():
t, alice = Tracker(votes=3, window=5), Match(7, "Alice", "E7", 0.8, 0.3)
for i in range(3): tr = t.update([F([10 + i, 10, 110 + i, 110])], [alice])
assert tr[0].identity == 7 and tr[0].state == "known" and len(t.tracks) == 1
t, unk = Tracker(votes=2, window=3), Match(None, "Unknown", "", 0.3, 0.2)
assert t.update([F([0, 0, 50, 50])], [None])[0].state == "low_quality"
t.update([F([0, 0, 50, 50])], [unk]); assert t.update([F([1, 0, 51, 50])], [unk])[0].identity == UNKNOWN
for _ in range(12): t.update([], [])
assert t.tracks == [] and iou([0, 0, 10, 10], [5, 0, 15, 10]) == pytest.approx(1 / 3)
def test_tracker_splits_on_person_swap():
t, ea, eb = Tracker(votes=2, gate=0.65), unit(np.r_[1.0, np.zeros(511)]), unit(np.r_[0, 1.0, np.zeros(510)])
for _ in range(2): first = t.update([F([0, 0, 100, 100], ea)], [Match(1, "A", "", 0.9, 0.1)])[0]
tr = t.update([F([0, 0, 100, 100], eb)], [Match(2, "B", "", 0.9, 0.1)])[0]
assert first.identity == 1 and tr is not first and tr.identity is None
def test_similarity_and_imwrite(tmp_path):
t = similarity(ARC, ARC * 2 + 5); assert np.allclose(t, [[2, 0, 5], [0, 2, 5]]) # pure scale + shift is recovered exactly
ang = np.radians(20); r = np.array([[np.cos(ang), -np.sin(ang)], [np.sin(ang), np.cos(ang)]]); src = ARC @ r.T * 1.7 + [300, 80]
assert np.allclose(np.c_[src, np.ones(5)] @ similarity(src, ARC).T, ARC, atol=1e-6) # rotated face -> template
t = similarity(src, CHIP_DST); assert np.allclose(np.c_[src, np.ones(5)] @ t.T, CHIP_DST, atol=1e-6) # chip: same alignment at 2x
assert np.allclose(np.c_[CHIP_DST, np.ones(5)] @ similarity(CHIP_DST, ARC).T, ARC) # and back to the 112 ArcFace crop
p = str(tmp_path / "ünïcode_顔.jpg"); assert imwrite(p, np.zeros((8, 8, 3), np.uint8)) and os.path.getsize(p)
def test_pose():
lm = np.array([[30, 40], [70, 40], [50, 60], [35, 80], [65, 80]], float)
assert np.allclose(pose(lm), (0, 0.5)); lm[2, 0] = 75; assert pose(lm)[0] > 0.5
def test_attendance_rules(db, cfg, tmp_path):
e, att = db.add_employee(emp_code="E1", name="Alice", department="IT"), Attendance(db, cfg, str(tmp_path))
both, entry, exit_ = ({"id": db.x("INSERT INTO cameras(name,url,role) VALUES(?,?,?)", (r, "u", r)), "name": r, "role": r} for r in ("both", "entry", "exit"))
ev = att.process(e, "Alice", "E1", both, 0.8, np.full((160, 160, 3), 99, np.uint8), D(5, 8, 55))
assert ev["event_type"] == "check_in" and ev["status"] == "Present" and os.path.exists(ev["snapshot_path"])
assert att.process(e, "A", "E1", both, 0.8, now=D(5, 8, 55, 30)) is None # cooldown
assert att.process(e, "A", "E1", both, 0.8, now=D(5, 8, 58))["event_type"] == "seen" # inside check-out gap
assert att.process(e, "A", "E1", both, 0.8, now=D(5, 17, 30))["event_type"] == "check_out"
r = db.one("SELECT * FROM attendance WHERE employee_id=?", (e,))
assert hours(r["check_in"], r["check_out"]) == pytest.approx(8 + 35 / 60) and len(db.logs("2026-01-05", "2026-01-05")) == 3
assert att.process(e, "A", "E1", entry, 0.7, now=D(6, 9, 20))["status"] == "Late"
assert att.process(e, "A", "E1", entry, 0.7, now=D(6, 12))["event_type"] == "seen"
assert att.process(e, "A", "E1", exit_, 0.7, now=D(6, 18))["event_type"] == "check_out"
att.process(e, "A", "E1", exit_, 0.7, now=D(7, 8)); assert att.process(e, "A", "E1", entry, 0.7, now=D(7, 8, 1))["event_type"] == "check_in"
assert att.unknown(both, 0.3, now=D(5, 10)) and not att.unknown(both, 0.3, now=D(5, 10, 0, 10)) and att.unknown(both, 0.3, now=D(5, 10, 1))
def test_db_and_reports(db, tmp_path):
a, b = db.add_employee(emp_code="E1", name="Alice", department="IT"), db.add_employee(emp_code="E2", name="Bob", department="HR")
db.add_faces(a, "m1", [F([0, 0, 1, 1], np.ones(512))] * 3, "camera"); db.add_faces(b, "m1", [F([0, 0, 1, 1], np.zeros(512))], "image")
assert db.load_gallery("m1")[1].shape == (4, 512) and db.load_gallery("m2")[1].shape[0] == 0 and len(db.unembedded("m2")) == 4
db.add_embeddings("m2", [(r["id"], np.ones(128)) for r in db.unembedded("m2")]); assert db.load_gallery("m2")[1].shape == (4, 128)
assert not db.unembedded("m2") and db.employees()[0]["face_count"] == 3
db.update("employees", b, active=False); assert set(db.load_gallery("m1")[0]) == {a}; db.update("employees", b, active=True)
db.x("INSERT INTO attendance(employee_id,date,check_in,check_out,manual) VALUES(?,?,?,?,1)", (a, "2026-01-05", "2026-01-05 09:00:00", "2026-01-05 17:00:00"))
rows, ids = daily_rows(db, "2026-01-05", "2026-01-05", absent=True)
assert {r[2]: r[7] for r in rows} == {"Alice": "Present", "Bob": "Absent"} and len(ids) == 1
assert daily_rows(db, "2026-01-05", "2026-01-05", status="Absent", absent=True)[0][0][2] == "Bob"
m = {r[1]: r for r in monthly_rows(db, 2026, 1)}; assert m["Alice"][3] == 1 and m["Alice"][6] == 8.0 and m["Alice"][7] == "09:00"
assert (m["Alice"][5], m["Bob"][5]) == (21, 22) # absent days: January 2026 has 22 working days
for ext in ("csv", "xlsx"): export(str(tmp_path / ("r." + ext)), DAILY, rows); assert os.path.getsize(tmp_path / ("r." + ext))
assert db.stats("2026-01-05") == {"total": 2, "present": 1, "out": 1, "late": 0} and db.get("employees", b)["name"] == "Bob"
db.mark(b, "2026-01-05", check_in="2026-01-05 09:30:00", status="Late"); db.mark(b, "2026-01-05", note="n"); r = db.attendance("2026-01-05", "2026-01-05", b)
assert len(r) == 1 and (r[0]["status"], r[0]["note"], r[0]["check_in"][11:]) == ("Late", "n", "09:30:00") and db.stats("2026-01-05")["late"] == 1
db.mark(b, "2026-01-06", status="Absent", manual=1, note="sick"); db.mark(a, "2026-01-06", status="Leave", check_in="2026-01-06 09:00:00")
assert [r[2] for r in daily_rows(db, "2026-01-06", "2026-01-06", status="Absent", absent=True)[0]] == ["Bob"] # marked Absent: listed once
assert {r[1]: r[5] for r in monthly_rows(db, 2026, 1)} == {"Alice": 20, "Bob": 21} # Leave is no absence, a record marked Absent is one
assert db.stats("2026-01-06") == {"total": 2, "present": 0, "out": 0, "late": 0} # KPIs count by status, like the Attendance page
db.delete("employees", a); assert not db.all("SELECT * FROM faces WHERE employee_id=?", (a,)) and not db.get("employees", a)
assert len(db.all("SELECT * FROM embeddings")) == 2 # cascade: faces and their embeddings of every model are gone
db.delete("faces", b, "employee_id"); assert db.load_gallery("m1")[1].shape[0] == 0 and not db.all("SELECT * FROM embeddings") and db.get("employees", b)
def test_migrates_one_model_database(tmp_path):
p = str(tmp_path / "old.db"); c = sqlite3.connect(p)
c.executescript("CREATE TABLE employees(id INTEGER PRIMARY KEY, emp_code TEXT UNIQUE NOT NULL, name TEXT NOT NULL, department TEXT DEFAULT '',"
" designation TEXT DEFAULT '', email TEXT DEFAULT '', phone TEXT DEFAULT '', photo_path TEXT DEFAULT '', active INTEGER DEFAULT 1,"
" created_at TEXT); CREATE TABLE face_embeddings(id INTEGER PRIMARY KEY, employee_id INTEGER NOT NULL, embedding BLOB NOT NULL,"
" quality REAL, source TEXT, created_at TEXT); INSERT INTO employees(id, emp_code, name) VALUES(1, 'E1', 'Alice');")
c.execute("INSERT INTO face_embeddings(employee_id, embedding, quality, source) VALUES(1, ?, 0.8, 'camera')", (np.ones(512, np.float32).tobytes(),))
c.commit(); c.close()
db = Database(p); labels, mat, _ = db.load_gallery("facenet_vggface2")
assert list(labels) == [1] and mat.shape == (1, 512) and not db.one("SELECT 1 FROM sqlite_master WHERE name='face_embeddings'"); db.close()
|