Download AttendanceSystem(window)/core.py from mchuca/AttendanceSystem: direct link, hf CLI and curl.
- Browser
- Download file 42.2 kB
-
https://huggingface.co/mchuca/AttendanceSystem/resolve/main/AttendanceSystem(window)/core.py
- Command line
-
hf download 'hf://mchuca/AttendanceSystem/AttendanceSystem(window)/core.py'
-
curl -L -o core.py 'https://huggingface.co/mchuca/AttendanceSystem/resolve/main/AttendanceSystem(window)/core.py'
42.2 kB
| """Attendance core (no Qt): config, storage, RTSP capture, face engine (MTCNN + selectable recognition models, each as ONNX or | |
| PyTorch), matching, tracking, rules, reports.""" | |
| import calendar, copy, csv, hashlib, hmac, json, logging, os, re, sqlite3, threading, time, urllib.request, zipfile | |
| from collections import Counter, defaultdict, deque | |
| from dataclasses import dataclass | |
| from datetime import date, datetime, timedelta | |
| import cv2 | |
| import numpy as np | |
| import torch | |
| log = logging.getLogger("ams") | |
| BASE = os.path.dirname(os.path.abspath(__file__)) | |
| TS = "%Y-%m-%d %H:%M:%S" | |
| now = lambda: datetime.now().strftime(TS) | |
| WINDOWS = os.name == "nt" | |
| def imwrite(path, img): # cv2.imwrite fails on Windows for non-ASCII paths; imencode + tofile works everywhere | |
| ok, buf = cv2.imencode(os.path.splitext(path)[1] or ".jpg", img) | |
| if ok: buf.tofile(path) | |
| return ok | |
| # ------------------------------------------------------------------ models | |
| _IF = "https://github.com/deepinsight/insightface/releases/download/v0.7/" | |
| _FN = "https://github.com/timesler/facenet-pytorch/releases/download/v2.2.9/" | |
| RUNTIMES = {"onnx": "ONNX Runtime", "pt": "PyTorch (.pt)"} # every model in both formats: original + converted, same embeddings | |
| _FACENET = dict(arch="Inception-ResNet-v1 · 160×160 · 512-d", style="facenet", src="export", mb=90, license="MIT (facenet-pytorch)", speed=3, | |
| threshold=0.60, gate=0.65, min_same=0.62) | |
| _ARCFACE = dict(style="arcface", pt="convert", license="InsightFace: non-commercial research use only", threshold=0.42, gate=0.50, min_same=0.45) | |
| MODELS = { # recognition models. threshold / gate / min_same: cosine defaults calibrated per model | |
| "facenet_vggface2": dict(_FACENET, name="FaceNet · VGGFace2", accuracy=4, pt=_FN + "20180402-114759-vggface2.pt", | |
| pt_sha="281cebca8662831adb987a874bdcb36e73f5b1c6dc5ee5878f305e985625d99b", | |
| about="Balanced default, robust to pose and lighting. Original PyTorch weights (~110 MB); ONNX is converted from them."), | |
| "facenet_casia": dict(_FACENET, name="FaceNet · CASIA-WebFace", accuracy=3, pt=_FN + "20180408-102900-casia-webface.pt", | |
| pt_sha="7a67afdbbc995fce5e10128675e318799a70698c2f433ba75dd7eb9a2f096e7d", | |
| about="Same network trained on the smaller CASIA-WebFace set. Original PyTorch weights; ONNX is converted from them."), | |
| "arcface_r50": dict(_ARCFACE, name="ArcFace · ResNet-50", arch="InsightFace buffalo_l · 112×112 · 512-d", src=_IF + "buffalo_l.zip#w600k_r50.onnx", | |
| sha="4c06341c33c2ca1f86781dab0e829f88ad5b64be9fba56e56bc9ebdefc619e43", mb=166, accuracy=5, speed=1, | |
| about="Most accurate, but the slowest on CPU (about 4x MobileFaceNet). Download ~290 MB."), | |
| "arcface_mbf": dict(_ARCFACE, name="ArcFace · MobileFaceNet", arch="InsightFace buffalo_s · 112×112 · 512-d", src=_IF + "buffalo_s.zip#w600k_mbf.onnx", | |
| sha="9cc6e4a75f0e2bf0b1aed94578f144d15175f357bdc05e815e5c4a02b319eb4f", mb=13, accuracy=4, speed=5, | |
| about="Fastest and smallest on CPU, still very accurate. Best choice for several cameras. Download ~120 MB."), | |
| "sface": dict(name="SFace · OpenCV Zoo", arch="MobileFaceNet-style · 112×112 · 128-d", style="sface", pt="convert", batch1=True, | |
| src="https://github.com/opencv/opencv_zoo/raw/main/models/face_recognition_sface/face_recognition_sface_2021dec.onnx", | |
| sha="0ba9fbfa01b5270c96627c4ef784da859931e02f04419c829e83484087c34e79", mb=37, license="Apache-2.0 (commercial use OK)", | |
| accuracy=3, speed=4, threshold=0.55, gate=0.62, min_same=0.58, about="Light model with a permissive license. Download ~37 MB.")} | |
| ARC = np.array([[38.2946, 51.6963], [73.5318, 51.5014], [56.0252, 71.7366], [41.5493, 92.3655], [70.7299, 92.2041]]) # ArcFace 112 landmarks | |
| CHIP, CHIP_DST = 512, (ARC + 72) * 2 # stored face chips: ArcFace alignment at 2x with a border, so any model can re-embed them later | |
| model_path = lambda key, runtime="onnx": os.path.join(BASE, "models", "%s.%s" % (key, runtime)) | |
| def ensure_model(key, report=lambda msg: None, runtime="onnx"): | |
| """Path of a model file (runtime onnx / pt). On first use: download the original and check its SHA-256, or convert it from the | |
| other format (FaceNet .pt -> ONNX, ONNX -> TorchScript .pt).""" | |
| path, m = model_path(key, runtime), MODELS[key] | |
| if os.path.exists(path): return path | |
| os.makedirs(os.path.dirname(path), exist_ok=True); tmp = path + ".part" | |
| src, sha = (m["src"], m.get("sha")) if runtime == "onnx" else (m["pt"], m.get("pt_sha")) | |
| if src in ("export", "convert"): | |
| import convert | |
| other = ensure_model(key, report, "pt" if runtime == "onnx" else "onnx"); report("Converting %s to %s..." % (m["name"], RUNTIMES[runtime])) | |
| convert.facenet_to_onnx(other, tmp) if src == "export" else convert.onnx_to_torchscript(other, tmp, m.get("batch1", False)) | |
| else: | |
| url, _, member = src.partition("#") | |
| with urllib.request.urlopen(url, timeout=60) as r, open(tmp, "wb") as f: | |
| total, done = int(r.headers.get("Content-Length") or 0), 0 | |
| for block in iter(lambda: r.read(1 << 20), b""): | |
| f.write(block); done += len(block); report("Downloading %s %d%%" % (m["name"], done * 100 // total) if total else "Downloading...") | |
| if member: # model inside a zip pack | |
| with zipfile.ZipFile(tmp) as z: data = z.read(next(n for n in z.namelist() if n.endswith(member))) | |
| with open(tmp, "wb") as f: f.write(data) | |
| with open(tmp, "rb") as f: digest = hashlib.sha256(f.read()).hexdigest() | |
| if digest != sha: os.remove(tmp); raise RuntimeError("Download of %s is corrupt (checksum mismatch) - try again." % m["name"]) | |
| os.replace(tmp, path); return path | |
| def similarity(src, dst): | |
| """Least-squares similarity transform (rotation, scale, shift) mapping points src -> dst, as a 2x3 matrix. Deterministic.""" | |
| s, d = np.asarray(src, np.float64), np.asarray(dst, np.float64); z, o = np.zeros(len(s)), np.ones(len(s)) | |
| a = np.empty((2 * len(s), 4)); a[0::2] = np.c_[s[:, 0], -s[:, 1], o, z]; a[1::2] = np.c_[s[:, 1], s[:, 0], z, o] | |
| p, q, tx, ty = np.linalg.lstsq(a, d.reshape(-1), rcond=None)[0] | |
| return np.array([[p, -q, tx], [q, p, ty]]) | |
| # ------------------------------------------------------------------ config | |
| DEFAULTS = { | |
| "torch_threads": 0, "model": "facenet_vggface2", "runtime": "onnx", "profiles": {}, # profiles: per-model overrides | |
| "detection": {"min_face_size": 40, "thresholds": [0.6, 0.7, 0.7], "min_confidence": 0.95, "max_side": 960, "margin": 20, "align": True}, | |
| "quality": {"min_face_px": 60, "min_blur": 40.0, "max_yaw": 0.45, "pitch": [0.2, 0.8], "brightness": [40, 225]}, | |
| "recognition": {"margin": 0.04, "top_k": 3}, | |
| "tracking": {"iou": 0.3, "max_missed": 10, "window": 7, "votes": 3}, | |
| "attendance": {"cooldown_sec": 60, "checkout_gap_min": 5, "work_start": "09:00", "late_grace_min": 15, | |
| "save_snapshots": True, "save_unknown": True, "unknown_cooldown_sec": 30}, | |
| "camera": {"transport": "tcp", "reconnect_sec": 3.0, "timeout_ms": 10000, "process_fps": 5.0, "display_fps": 25.0}, | |
| "enrollment": {"samples": 15, "max_sim": 0.95, "interval_sec": 0.25}, | |
| "admin": {"require_login": True, "username": "admin", "password_hash": ""}, | |
| "paths": {"data": "data", "logs": "logs"}} | |
| def merge(a, b): | |
| return {**a, **{k: merge(a[k], v) if isinstance(v, dict) and isinstance(a.get(k), dict) else v for k, v in b.items()}} | |
| class Config: | |
| def __init__(self, path): | |
| self.path, self.lock = path, threading.RLock() | |
| self.d = merge(copy.deepcopy(DEFAULTS), json.load(open(path, encoding="utf-8")) if os.path.exists(path) else {}) | |
| for k, known in (("model", MODELS), ("runtime", RUNTIMES)): # e.g. "model" in a settings file of the one-model version | |
| if self.d[k] not in known: self.d[k] = DEFAULTS[k] | |
| self.save() | |
| def save(self): | |
| with self.lock: | |
| os.makedirs(os.path.dirname(os.path.abspath(self.path)), exist_ok=True) | |
| with open(self.path + ".tmp", "w", encoding="utf-8") as f: json.dump(self.d, f, indent=2) | |
| os.replace(self.path + ".tmp", self.path) | |
| def get(self, key): # dotted key; every key exists because DEFAULTS are merged in. "profile.x" = x of the active model | |
| if key.startswith("profile."): m = self.d["model"]; return self.d["profiles"].get(m, {}).get(key[8:], MODELS[m][key[8:]]) | |
| node = self.d | |
| for k in key.split("."): node = node[k] | |
| return node | |
| def set(self, key, value): | |
| if key.startswith("profile."): key = "profiles.%s.%s" % (self.d["model"], key[8:]) | |
| with self.lock: | |
| *ks, last = key.split("."); node = self.d | |
| for k in ks: node = node.setdefault(k, {}) | |
| node[last] = value | |
| def dir(self, key): # absolute or project-relative folder, created on demand | |
| p = os.path.join(BASE, self.get("paths." + key)); os.makedirs(p, exist_ok=True); return p | |
| # ---------------------------------------------------------------- security | |
| def hash_password(pw, salt=None, n=200000): | |
| salt = salt or os.urandom(16).hex() | |
| return "pbkdf2$%d$%s$%s" % (n, salt, hashlib.pbkdf2_hmac("sha256", pw.encode(), bytes.fromhex(salt), n).hex()) | |
| def verify_password(pw, stored): | |
| try: _, n, salt, _h = stored.split("$"); return hmac.compare_digest(hash_password(pw, salt, int(n)), stored) | |
| except ValueError: return False | |
| mask_url = lambda u: re.sub(r"^(\w+://[^:/@]+):[^@]*@", r"\1:***@", u or "") | |
| # ---------------------------------------------------------------- database | |
| SCHEMA = """ | |
| CREATE TABLE IF NOT EXISTS 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 IF NOT EXISTS faces(id INTEGER PRIMARY KEY, employee_id INTEGER NOT NULL REFERENCES employees(id) ON DELETE CASCADE, | |
| chip BLOB, meta TEXT, quality REAL, source TEXT, created_at TEXT); | |
| CREATE TABLE IF NOT EXISTS embeddings(face_id INTEGER NOT NULL REFERENCES faces(id) ON DELETE CASCADE, model TEXT NOT NULL, | |
| vec BLOB NOT NULL, PRIMARY KEY(face_id, model)); | |
| CREATE TABLE IF NOT EXISTS cameras(id INTEGER PRIMARY KEY, name TEXT NOT NULL, url TEXT NOT NULL, role TEXT DEFAULT 'both', | |
| enabled INTEGER DEFAULT 1); | |
| CREATE TABLE IF NOT EXISTS attendance(id INTEGER PRIMARY KEY, employee_id INTEGER NOT NULL REFERENCES employees(id) | |
| ON DELETE CASCADE, date TEXT NOT NULL, check_in TEXT, check_out TEXT, status TEXT DEFAULT 'Present', | |
| check_in_camera INTEGER, check_out_camera INTEGER, manual INTEGER DEFAULT 0, note TEXT DEFAULT '', UNIQUE(employee_id, date)); | |
| CREATE TABLE IF NOT EXISTS logs(id INTEGER PRIMARY KEY, employee_id INTEGER REFERENCES employees(id) ON DELETE CASCADE, | |
| timestamp TEXT NOT NULL, camera_id INTEGER, event_type TEXT, similarity REAL, snapshot_path TEXT DEFAULT ''); | |
| CREATE INDEX IF NOT EXISTS i_face ON faces(employee_id); | |
| CREATE INDEX IF NOT EXISTS i_att ON attendance(date); | |
| CREATE INDEX IF NOT EXISTS i_log ON logs(timestamp);""" | |
| class Database: | |
| def __init__(self, path): | |
| self.lock = threading.RLock() | |
| self.c = sqlite3.connect(path, check_same_thread=False, timeout=30) | |
| self.c.row_factory = sqlite3.Row | |
| self.c.execute("PRAGMA journal_mode=WAL"); self.c.execute("PRAGMA foreign_keys=ON"); self.c.executescript(SCHEMA) | |
| if self.one("SELECT 1 FROM sqlite_master WHERE name='face_embeddings'"): # database of the one-model version: keep its faces | |
| self.c.executescript("BEGIN; INSERT INTO faces(id, employee_id, quality, source, created_at) SELECT id, employee_id, quality, source," | |
| " created_at FROM face_embeddings; INSERT INTO embeddings SELECT id, 'facenet_vggface2', embedding FROM face_embeddings;" | |
| " DROP TABLE face_embeddings; COMMIT;") # all or nothing | |
| def x(self, sql, p=(), many=False): | |
| with self.lock: | |
| cur = (self.c.executemany if many else self.c.execute)(sql, p); self.c.commit(); return cur.lastrowid | |
| def all(self, sql, p=()): | |
| with self.lock: return [dict(r) for r in self.c.execute(sql, p)] | |
| def one(self, sql, p=()): | |
| r = self.all(sql, p); return r[0] if r else None | |
| def close(self): | |
| with self.lock: self.c.close() | |
| # generic rows (f = column values); table and column names always come from the code, never from user input | |
| def get(self, table, rid): return self.one("SELECT * FROM %s WHERE id=?" % table, (rid,)) | |
| def update(self, table, rid, **f): self.x("UPDATE %s SET %s WHERE id=?" % (table, ",".join(k + "=?" for k in f)), (*f.values(), rid)) | |
| def delete(self, table, rid, col="id"): self.x("DELETE FROM %s WHERE %s=?" % (table, col), (rid,)) | |
| def add_employee(self, **f): return self.insert("employees", created_at=now(), **f) | |
| def insert(self, table, conflict="", **f): | |
| return self.x("INSERT INTO %s(%s) VALUES(%s) %s" % (table, ",".join(f), ",".join("?" * len(f)), conflict), tuple(f.values())) | |
| def mark(self, eid, day, **f): # set fields of the one attendance row of an employee and day | |
| self.insert("attendance", "ON CONFLICT(employee_id,date) DO UPDATE SET " + ",".join("%s=excluded.%s" % (k, k) for k in f), | |
| employee_id=eid, date=day, **f) | |
| def employees(self, search="", active=False): | |
| s = "%%%s%%" % search | |
| return self.all("SELECT e.*,(SELECT COUNT(*) FROM faces WHERE employee_id=e.id) face_count FROM employees e" | |
| " WHERE (name LIKE ? OR emp_code LIKE ? OR department LIKE ?) AND active>=? ORDER BY name COLLATE NOCASE", | |
| (s, s, s, int(active))) | |
| def departments(self): | |
| return [r["department"] for r in self.all("SELECT DISTINCT department FROM employees WHERE department<>'' ORDER BY 1")] | |
| def cameras(self, enabled=False): return self.all("SELECT * FROM cameras WHERE enabled>=? ORDER BY id", (int(enabled),)) | |
| def add_faces(self, eid, model, faces, source): # enrolled faces (with chips) and their embeddings for the active model | |
| for f in faces: | |
| fid = self.insert("faces", employee_id=eid, chip=f.chip[0], meta=f.chip[1], quality=f.score, source=source, created_at=now()) | |
| self.insert("embeddings", face_id=fid, model=model, vec=np.asarray(f.emb, np.float32).tobytes()) | |
| def unembedded(self, model): # stored faces without an embedding for this model (after switching models) | |
| return self.all("SELECT id, chip, meta FROM faces f WHERE chip IS NOT NULL AND NOT EXISTS" | |
| " (SELECT 1 FROM embeddings WHERE face_id=f.id AND model=?)", (model,)) | |
| def add_embeddings(self, model, items): # items: [(face id, embedding)] | |
| self.x("INSERT OR REPLACE INTO embeddings(face_id,model,vec) VALUES(?,?,?)", [(i, model, np.asarray(e, np.float32).tobytes()) for i, e in items], True) | |
| def load_gallery(self, model): | |
| rows = self.all("SELECT f.employee_id, m.vec FROM embeddings m JOIN faces f ON f.id=m.face_id JOIN employees e ON e.id=f.employee_id" | |
| " WHERE e.active=1 AND m.model=?", (model,)) | |
| mat = np.stack([np.frombuffer(r["vec"], np.float32) for r in rows]) if rows else np.zeros((0, 1), np.float32) | |
| return np.array([r["employee_id"] for r in rows], np.int64), mat, {e["id"]: e for e in self.employees(active=True)} | |
| def attendance(self, d1, d2, eid=None, dept="", status=""): | |
| return self.all("SELECT a.*, e.emp_code, e.name, e.department FROM attendance a JOIN employees e ON e.id=a.employee_id" | |
| " WHERE date BETWEEN ? AND ? AND (?=0 OR employee_id=?) AND (?='' OR department=?) AND (?='' OR status=?)" | |
| " ORDER BY date DESC, check_in", (d1, d2, eid or 0, eid or 0, dept, dept, status, status)) | |
| def logs(self, d1, d2, eid=None): | |
| return self.all("SELECT l.*, e.emp_code, e.name, c.name camera FROM logs l LEFT JOIN employees e ON e.id=l.employee_id" | |
| " LEFT JOIN cameras c ON c.id=l.camera_id WHERE timestamp BETWEEN ? AND ? AND (?=0 OR employee_id=?)" | |
| " ORDER BY timestamp DESC LIMIT 2000", (d1, d2 + " 23:59:59", eid or 0, eid or 0)) # range: uses index i_log | |
| def stats(self, day): # live KPI counts in one query | |
| return self.one("SELECT (SELECT COUNT(*) FROM employees WHERE active=1) total, COUNT(CASE WHEN status IN ('Present','Late') THEN 1 END)" | |
| " present, COUNT(check_out) out, COUNT(CASE WHEN status='Late' THEN 1 END) late FROM attendance WHERE date=?", (day,)) | |
| # ------------------------------------------------------------------ camera | |
| _ENV = threading.Lock() | |
| is_net = lambda s: isinstance(s, str) and s.split("://")[0].lower() in ("rtsp", "rtsps", "http", "https", "rtmp") | |
| def open_capture(src, transport="tcp", timeout=10000): | |
| src = int(src) if str(src).strip().isdigit() else str(src).strip() | |
| if not is_net(src): cap = cv2.VideoCapture(src, cv2.CAP_DSHOW) if WINDOWS and isinstance(src, int) else cv2.VideoCapture(src) # DirectShow opens webcams fast | |
| else: | |
| with _ENV: # FFmpeg reads its options from the environment at open time | |
| os.environ["OPENCV_FFMPEG_CAPTURE_OPTIONS"] = "rtsp_transport;" + transport | |
| cap = cv2.VideoCapture(src, cv2.CAP_FFMPEG, [cv2.CAP_PROP_OPEN_TIMEOUT_MSEC, timeout, cv2.CAP_PROP_READ_TIMEOUT_MSEC, timeout]) | |
| cap.set(cv2.CAP_PROP_BUFFERSIZE, 1) | |
| return cap | |
| def probe(src, transport="tcp"): | |
| cap = open_capture(src, transport, 8000) | |
| ok, f = cap.read() if cap.isOpened() else (False, None) | |
| msg = "OK - %dx%d @ %.1f fps" % (f.shape[1], f.shape[0], cap.get(cv2.CAP_PROP_FPS)) if ok else "No video from this source" | |
| cap.release() | |
| return ok, msg, f if ok else None | |
| class CameraStream: | |
| """Reads in its own thread from creation on, keeps only the newest frame (no lag), reconnects. Video files loop at their fps.""" | |
| def __init__(self, src, name="", transport="tcp", reconnect=3.0, timeout=10000): | |
| self.src, self.name, self.transport, self.reconnect, self.timeout = src, name or str(src), transport, reconnect, timeout | |
| self.status, self.fps, self.frame, self.fid, self.ts = "stopped", 0.0, None, 0, 0.0 | |
| self.lock, self.halt = threading.Lock(), threading.Event() | |
| self.thread = threading.Thread(target=self._run, daemon=True); self.thread.start() | |
| def stop(self): self.halt.set(); self.thread.join(3); self.status = "stopped" | |
| def alive(self): return self.status == "online" and time.time() - self.ts < 5 | |
| def read(self): | |
| with self.lock: return self.frame, self.fid, self.ts | |
| def _run(self): | |
| is_file = not is_net(self.src) and not str(self.src).strip().isdigit() | |
| while not self.halt.is_set(): | |
| self.status = "connecting" if self.status == "stopped" else "reconnecting" | |
| log.info("Opening camera '%s' (%s)", self.name, mask_url(str(self.src))) | |
| cap = open_capture(self.src, self.transport, self.timeout) | |
| period = 1 / (cap.get(cv2.CAP_PROP_FPS) or 25) if is_file else 0 | |
| fails, n, t0 = 0, 0, time.time() | |
| while cap.isOpened() and fails < 5 and not self.halt.is_set(): | |
| t = time.time(); ok, frame = cap.read() | |
| if not ok: | |
| fails += 1 | |
| cap.set(cv2.CAP_PROP_POS_FRAMES, 0) if is_file else time.sleep(0.05) | |
| continue | |
| self.status, fails, n = "online", 0, n + 1 | |
| with self.lock: self.frame, self.fid, self.ts = frame, self.fid + 1, time.time() | |
| if time.time() - t0 >= 2: self.fps, n, t0 = n / (time.time() - t0), 0, time.time() | |
| if period: time.sleep(max(0, period - (time.time() - t))) | |
| cap.release() | |
| if not self.halt.is_set(): | |
| log.warning("Camera '%s' offline, retry in %.0fs", self.name, self.reconnect) | |
| self.status = "reconnecting"; self.halt.wait(self.reconnect) | |
| self.status = "stopped" | |
| class CameraManager: | |
| """One shared stream per camera (live view and enrollment read the same one).""" | |
| def __init__(self, cfg): self.cfg, self.streams, self.refs, self.lock = cfg, {}, {}, threading.Lock() | |
| def acquire(self, cam): | |
| with self.lock: | |
| if cam["id"] not in self.streams: | |
| c = self.cfg.get("camera") | |
| self.streams[cam["id"]] = CameraStream(cam["url"], cam["name"], c["transport"], c["reconnect_sec"], c["timeout_ms"]) | |
| self.refs[cam["id"]] = self.refs.get(cam["id"], 0) + 1 | |
| return self.streams[cam["id"]] | |
| def release(self, cid): | |
| with self.lock: | |
| self.refs[cid] = self.refs.get(cid, 1) - 1 | |
| s = self.streams.pop(cid, None) if self.refs[cid] <= 0 else None | |
| if s: self.refs.pop(cid) | |
| if s: s.stop() | |
| def stop_all(self): | |
| for cid in list(self.streams): self.refs[cid] = 1; self.release(cid) | |
| # ------------------------------------------------------------- face engine | |
| class Face: | |
| box: np.ndarray # x1,y1,x2,y2 in frame pixels | |
| lm: np.ndarray # 5 landmarks: eyes, nose, mouth corners | |
| crop: np.ndarray # level 160x160 RGB view (quality checks, snapshots, photos) | |
| ok: bool # passed quality checks | |
| score: float # quality score 0..1 | |
| reasons: list | |
| emb: np.ndarray = None # filled by FaceEngine.analyze | |
| chip: tuple = None # (jpeg, meta json) for storing; analyze(chips=True) | |
| area = property(lambda s: (s.box[2] - s.box[0]) * (s.box[3] - s.box[1])) | |
| def bgr(self): return cv2.cvtColor(self.crop, cv2.COLOR_RGB2BGR) | |
| def pose(lm): | |
| """yaw = nose offset / eye distance (0 = frontal); pitch = nose between eye and mouth line (0.5 = frontal).""" | |
| le, re, nose, ml, mr = np.asarray(lm, float) | |
| eye, mouth = (le + re) / 2, (ml + mr) / 2 | |
| return (nose[0] - eye[0]) / max(np.linalg.norm(re - le), 1e-6), (nose[1] - eye[1]) / max(mouth[1] - eye[1], 1e-6) | |
| def quality(crop, box, lm, q): | |
| gray = cv2.cvtColor(crop, cv2.COLOR_RGB2GRAY) | |
| size, blur, light = min(box[2] - box[0], box[3] - box[1]), cv2.Laplacian(gray, cv2.CV_64F).var(), gray.mean() | |
| yaw, pitch = pose(lm) | |
| reasons = [r for r, bad in (("too small", size < q["min_face_px"]), ("blurry", blur < q["min_blur"]), | |
| ("too dark", light < q["brightness"][0]), ("too bright", light > q["brightness"][1]), | |
| ("turned sideways", abs(yaw) > q["max_yaw"]), ("looking up/down", not q["pitch"][0] <= pitch <= q["pitch"][1])) if bad] | |
| score = 0.4 * min(blur / 300, 1) + 0.4 * max(0, 1 - abs(yaw) / 0.6) * max(0, 1 - abs(pitch - 0.5) / 0.4) + 0.2 * min(size / 160, 1) | |
| return not reasons, float(score), reasons | |
| class FaceEngine: | |
| """MTCNN detection (PyTorch) + the selected recognition model (ONNX Runtime or PyTorch). CPU only.""" | |
| def __init__(self, cfg, key=None, report=lambda msg: None, reuse=None, runtime=None): | |
| # CPU threads: "auto" = half the logical cores. All cores oversubscribe (PyTorch measured ~18x slower on a busy 6-core CPU) | |
| threads = int(cfg.get("torch_threads") or 0) or max(1, (os.cpu_count() or 2) // 2) | |
| self.cfg, self.key, self.runtime = cfg, key or cfg.get("model"), runtime or cfg.get("runtime") | |
| self.m, path = MODELS[self.key], ensure_model(self.key, report, self.runtime) | |
| if reuse: self.lock, self.mtcnn = reuse.lock, reuse.mtcnn # switching models: keep the detector | |
| else: | |
| from facenet_pytorch import MTCNN | |
| torch.set_num_threads(threads) | |
| self.lock, self.mtcnn = threading.Lock(), MTCNN(device=torch.device("cpu")) # only detect() is used; it applies the settings | |
| report("Loading %s (%s)..." % (self.m["name"], RUNTIMES[self.runtime])); self.one_by_one = self.m.get("batch1", False) # SFace: one face per run | |
| if self.runtime == "pt": | |
| import convert | |
| self.net = convert.facenet_net(path) if self.m["style"] == "facenet" else torch.jit.load(path, map_location="cpu").eval() | |
| else: | |
| import onnxruntime as ort | |
| opts = ort.SessionOptions(); opts.intra_op_num_threads = threads; self.net = None | |
| opts.add_session_config_entry("session.intra_op.allow_spinning", "0") # no busy-waiting threads: leaves the CPU to MTCNN | |
| self.sess = ort.InferenceSession(path, opts, providers=["CPUExecutionProvider"]); self.inp = self.sess.get_inputs()[0].name | |
| self.detect(np.zeros((240, 320, 3), np.uint8)) | |
| for _ in range(3): self.embed([self.model_input(np.zeros((200, 200, 3), np.uint8), (50, 50, 150, 150), ARC + 44)]) # warm-up (TorchScript: 2 runs) | |
| log.info("Face engine ready (CPU): %s via %s", self.m["name"], RUNTIMES[self.runtime]) | |
| def _run(self, x): # NCHW float32 -> embeddings | |
| if self.net is None: return self.sess.run(None, {self.inp: x})[0] # ONNX Runtime sessions are thread-safe | |
| with torch.no_grad(): return self.net(torch.from_numpy(x)).numpy() | |
| def detect(self, bgr): # -> [(box, 5 landmarks)]; on a downscaled copy for speed, mapped back to full size | |
| d = self.cfg.get("detection"); h, w = bgr.shape[:2]; s = min(1.0, d["max_side"] / max(h, w)) | |
| small = cv2.resize(bgr, (int(w * s), int(h * s)), interpolation=cv2.INTER_AREA) if s < 1 else bgr | |
| with self.lock: # one detection at a time (no_grad inside); settings changes apply at once | |
| self.mtcnn.min_face_size, self.mtcnn.thresholds = d["min_face_size"], d["thresholds"] | |
| boxes, probs, pts = self.mtcnn.detect(cv2.cvtColor(small, cv2.COLOR_BGR2RGB), landmarks=True) | |
| return [] if boxes is None else [(np.asarray(b, np.float64) / s, np.asarray(l, np.float64) / s) # MTCNN may return object arrays | |
| for b, p, l in zip(boxes, probs, pts) if p >= d["min_confidence"]] | |
| def align(self, img, box, lm): | |
| """FaceNet crop: box + facenet margin, rotated so the eyes are level, -> 160x160.""" | |
| d = self.cfg.get("detection"); k = (1 + d["margin"] / (160 - d["margin"])) / 2 | |
| x1, y1, x2, y2 = box; cx, cy, hw, hh = (x1 + x2) / 2, (y1 + y2) / 2, (x2 - x1) * k, (y2 - y1) * k | |
| ang = np.degrees(np.arctan2(lm[1][1] - lm[0][1], lm[1][0] - lm[0][0])) if d["align"] else 0 | |
| rot = np.vstack([cv2.getRotationMatrix2D((float(cx), float(cy)), float(ang), 1.0), [0, 0, 1]]) | |
| sx, sy = 80 / hw, 80 / hh | |
| return cv2.warpAffine(img, np.array([[sx, 0, (hw - cx) * sx], [0, sy, (hh - cy) * sy]]) @ rot, (160, 160), | |
| borderMode=cv2.BORDER_REPLICATE) | |
| def model_input(self, img, box, lm, view=None): # RGB crop the recognition model expects (view: the FaceNet crop, if made already) | |
| if self.m["style"] == "facenet": return view if view is not None else cv2.cvtColor(self.align(img, box, lm), cv2.COLOR_BGR2RGB) | |
| return cv2.cvtColor(cv2.warpAffine(img, similarity(lm, ARC), (112, 112)), cv2.COLOR_BGR2RGB) # ArcFace 5-point alignment | |
| def embed(self, crops): | |
| if not crops: return np.zeros((0, 1), np.float32) | |
| x, st = np.stack(crops).astype(np.float32), self.m["style"] | |
| if st != "sface": x = (x - 127.5) / (128.0 if st == "facenet" else 127.5) # SFace takes raw 0..255 RGB | |
| x = np.ascontiguousarray(x.transpose(0, 3, 1, 2)) # NHWC -> NCHW | |
| e = np.concatenate([self._run(x[i:i + 1]) for i in range(len(x))]) if self.one_by_one else self._run(x) | |
| return e / np.linalg.norm(e, axis=1, keepdims=True) | |
| def chip(self, img, box, lm): | |
| """Store form of a face: ArcFace-aligned 512x512 JPEG + landmarks/box in chip pixels (meta), re-embeddable by any model.""" | |
| t = similarity(lm, CHIP_DST); c = np.hypot(t[0, 0], t[1, 0]) | |
| pts = np.c_[np.vstack([lm, [(box[0] + box[2]) / 2, (box[1] + box[3]) / 2]]), np.ones(6)] @ t.T # landmarks + box centre | |
| (cx, cy), hw, hh = pts[5], (box[2] - box[0]) * c / 2, (box[3] - box[1]) * c / 2 | |
| jpg = cv2.imencode(".jpg", cv2.warpAffine(img, t, (CHIP, CHIP), borderMode=cv2.BORDER_REPLICATE), [cv2.IMWRITE_JPEG_QUALITY, 95])[1] | |
| return jpg.tobytes(), json.dumps({"lm": np.round(pts[:5], 2).tolist(), "box": [round(v, 2) for v in (cx - hw, cy - hh, cx + hw, cy + hh)]}) | |
| def embed_chips(self, rows): # [(face id, embedding)] for stored faces (db.unembedded rows) | |
| crops = [] | |
| for r in rows: | |
| m = json.loads(r["meta"]); crops.append(self.model_input(cv2.imdecode(np.frombuffer(r["chip"], np.uint8), cv2.IMREAD_COLOR), m["box"], np.array(m["lm"]))) | |
| return list(zip([r["id"] for r in rows], self.embed(crops))) | |
| def analyze(self, bgr, embed_all=False, chips=False): | |
| q, faces = self.cfg.get("quality"), [] | |
| for box, lm in self.detect(bgr): | |
| crop = cv2.cvtColor(self.align(bgr, box, lm), cv2.COLOR_BGR2RGB) # converts 160x160 instead of the whole frame | |
| faces.append(Face(box, lm, crop, *quality(crop, box, lm, q))) | |
| if chips: faces[-1].chip = self.chip(bgr, box, lm) | |
| todo = [f for f in faces if f.ok or embed_all] | |
| for f, e in zip(todo, self.embed([self.model_input(bgr, f.box, f.lm, f.crop) for f in todo])): f.emb = e | |
| return faces | |
| def embed_image(self, bgr): # largest face of a photo, any quality | |
| faces = self.analyze(bgr, embed_all=True, chips=True) | |
| return max(faces, key=lambda f: f.area) if faces else None | |
| def load_engine(cfg, db, key=None, report=lambda msg: None, reuse=None, runtime=None): | |
| """Engine for a model + runtime, with every stored face embedded for the model (faces enrolled under other models: from their chips).""" | |
| eng, key = FaceEngine(cfg, key, report, reuse, runtime), key or cfg.get("model") | |
| rows = db.unembedded(key) | |
| for i in range(0, len(rows), 32): | |
| report("Preparing stored faces for %s %d/%d" % (MODELS[key]["name"], i, len(rows))); db.add_embeddings(key, eng.embed_chips(rows[i:i + 32])) | |
| return eng | |
| # ---------------------------------------------------------------- matching | |
| class Match: | |
| id: int; name: str; code: str; sim: float; second: float # id None = unknown | |
| known = property(lambda s: s.id is not None) | |
| class Gallery: | |
| """All embeddings of active employees. Person score = mean of their top-k sample cosine similarities.""" | |
| def __init__(self, cfg): self.cfg, self.lock = cfg, threading.Lock(); self.set(np.zeros(0, np.int64), np.zeros((0, 512)), {}) | |
| def load(self, db): self.set(*db.load_gallery(self.cfg.get("model"))) | |
| persons = property(lambda s: len(s.ids)) | |
| samples = property(lambda s: len(s.mat)) | |
| def set(self, labels, mat, people): | |
| mat = np.asarray(mat, np.float32); mat = mat / (np.linalg.norm(mat, axis=1, keepdims=True) + 1e-10) | |
| ids = np.unique(labels); rows = [np.flatnonzero(labels == i) for i in ids] | |
| idx = -np.ones((len(ids), max(map(len, rows), default=0)), np.int64) # sample rows per person, -1 padded | |
| for i, r in enumerate(rows): idx[i, :len(r)] = r | |
| with self.lock: self.mat, self.ids, self.idx, self.people = mat, ids, idx, people | |
| def match(self, embs): | |
| with self.lock: mat, ids, idx, people = self.mat, self.ids, self.idx, self.people | |
| if not len(ids): return [Match(None, "Unknown", "", 0.0, 0.0) for _ in embs] | |
| if not len(embs): return [] | |
| r, thr, own, out = self.cfg.get("recognition"), self.cfg.get("profile.threshold"), idx >= 0, []; k = min(r["top_k"], idx.shape[1]) | |
| top = np.sort(np.where(own, (np.stack(embs) @ mat.T)[:, np.maximum(idx, 0)], -np.inf), axis=2)[:, :, -k:] # faces x persons x k | |
| score = np.where(top > -np.inf, top, 0).sum(2) / np.minimum(own.sum(1), k) | |
| for row in score: | |
| o = np.argsort(-row); best, second = float(row[o[0]]), float(row[o[1]]) if len(o) > 1 else 0.0 | |
| p = people.get(int(ids[o[0]])) if best >= thr and best - second >= r["margin"] else None | |
| out.append(Match(int(ids[o[0]]), p["name"], p["emp_code"], best, second) if p else Match(None, "Unknown", "", best, second)) | |
| return out | |
| # ---------------------------------------------------------------- tracking | |
| UNKNOWN = -1 | |
| def iou(a, b): | |
| i = max(0, min(a[2], b[2]) - max(a[0], b[0])) * max(0, min(a[3], b[3]) - max(a[1], b[1])) | |
| u = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - i | |
| return i / u if u > 0 else 0.0 | |
| class Track: | |
| def __init__(self, face, window): | |
| self.box, self.face, self.emb, self.missed, self.votes = face.box, face, None, 0, deque(maxlen=window) | |
| self.identity, self.sim, self.marked, self.lowq = None, 0.0, False, False # identity: employee id / UNKNOWN / None | |
| def observe(self, face, match, need): | |
| self.box, self.face, self.missed, self.lowq = face.box, face, 0, match is None | |
| if face.emb is not None: self.emb = face.emb | |
| if match is None: return | |
| self.votes.append((match.id if match.known else UNKNOWN, match.sim)) | |
| win, n = Counter(v for v, _ in self.votes).most_common(1)[0] | |
| if n >= need: | |
| if win != self.identity: self.marked = False | |
| self.identity, self.sim = win, float(np.mean([s for v, s in self.votes if v == win])) | |
| def state(self): | |
| if self.identity is None: return "low_quality" if self.lowq and not self.votes else "pending" | |
| return "unknown" if self.identity == UNKNOWN else "known" | |
| class Tracker: | |
| """IoU tracking + identity voting. The appearance gate stops a new person in the same spot inheriting a track.""" | |
| def __init__(self, iou_t=0.3, max_missed=10, window=7, votes=3, gate=0.65): | |
| self.iou_t, self.max_missed, self.window, self.need, self.gate, self.tracks = iou_t, max_missed, window, votes, gate, [] | |
| def update(self, faces, matches): # matches[i] None = face too poor to recognize | |
| pairs = [] | |
| for ti, t in enumerate(self.tracks): | |
| for fi, f in enumerate(faces): | |
| o = iou(t.box, f.box) | |
| if o >= self.iou_t and (f.emb is None or t.emb is None or float(f.emb @ t.emb) >= self.gate): pairs.append((o, ti, fi)) | |
| used_t, used_f = set(), set() | |
| for _, ti, fi in sorted(pairs, reverse=True): | |
| if ti not in used_t and fi not in used_f: | |
| used_t.add(ti); used_f.add(fi); self.tracks[ti].observe(faces[fi], matches[fi], self.need) | |
| for ti, t in enumerate(self.tracks): t.missed += ti not in used_t | |
| for fi, f in enumerate(faces): | |
| if fi not in used_f: t = Track(f, self.window); t.observe(f, matches[fi], self.need); self.tracks.append(t) | |
| self.tracks = [t for t in self.tracks if t.missed <= self.max_missed] | |
| return [t for t in self.tracks if t.missed == 0] | |
| # -------------------------------------------------------------- attendance | |
| hours = lambda a, b: max(0.0, (datetime.strptime(b, TS) - datetime.strptime(a, TS)).total_seconds() / 3600) if a and b else 0.0 | |
| class Attendance: | |
| """Roles - entry: first sighting = check-in | exit: every sighting = check-out (last wins) | | |
| both: first = check-in, sightings >= checkout_gap_min later = check-out.""" | |
| def __init__(self, db, cfg, data_dir): self.db, self.cfg, self.dir, self.last, self.lock = db, cfg, data_dir, {}, threading.Lock() | |
| def _cool(self, key, sec, t): | |
| with self.lock: | |
| if t - self.last.get(key, -1e18) < sec: return False | |
| self.last[key] = t; return True | |
| def late(self, t): | |
| h, m = map(int, self.cfg.get("attendance.work_start").split(":")) | |
| limit = t.replace(hour=h, minute=m, second=0, microsecond=0) + timedelta(minutes=self.cfg.get("attendance.late_grace_min")) | |
| return "Late" if t > limit else "Present" | |
| def process(self, eid, name, code, cam, sim, img=None, now=None): | |
| now, a = now or datetime.now(), self.cfg.get("attendance") | |
| if not self._cool((eid, cam["id"]), a["cooldown_sec"], now.timestamp()): return None | |
| day, ts = now.strftime("%Y-%m-%d"), now.strftime(TS) | |
| rec = self.db.one("SELECT * FROM attendance WHERE employee_id=? AND date=?", (eid, day)) | |
| kind, status = "seen", rec["status"] if rec else "Present" | |
| if cam["role"] != "exit" and not (rec and rec["check_in"]): | |
| kind, status = "check_in", self.late(now); self.db.mark(eid, day, check_in=ts, status=status, check_in_camera=cam["id"]) | |
| elif cam["role"] == "exit" or (cam["role"] == "both" and now - datetime.strptime(rec["check_in"], TS) >= timedelta(minutes=a["checkout_gap_min"])): | |
| kind = "check_out"; self.db.mark(eid, day, check_out=ts, check_out_camera=cam["id"]) | |
| return self._log(eid, name, code, kind, cam, sim, status, img if kind != "seen" and a["save_snapshots"] else None, now) | |
| def unknown(self, cam, sim, img=None, now=None): | |
| now, a = now or datetime.now(), self.cfg.get("attendance") | |
| if a["save_unknown"] and self._cool(("?", cam["id"]), a["unknown_cooldown_sec"], now.timestamp()): | |
| return self._log(None, "Unknown", "", "unknown", cam, sim, "", img, now) | |
| def _log(self, eid, name, code, kind, cam, sim, status, img, now): | |
| ev = dict(employee_id=eid, timestamp=now.strftime(TS), event_type=kind, similarity=round(float(sim), 4), snapshot_path="") | |
| if img is not None: | |
| d = os.path.join(self.dir, "unknown" if eid is None else "snapshots", now.strftime("%Y-%m-%d")); os.makedirs(d, exist_ok=True) | |
| ev["snapshot_path"] = os.path.join(d, "%s_%s_%s.jpg" % (now.strftime("%H%M%S_%f"), eid or "x", kind)); imwrite(ev["snapshot_path"], img) | |
| self.db.insert("logs", camera_id=cam["id"], **ev) | |
| log.info("%s: %s (%s) cam=%s sim=%.3f", kind, name, code, cam["name"], sim) | |
| return dict(ev, name=name, emp_code=code, camera_name=cam["name"], status=status) | |
| # ----------------------------------------------------------------- reports | |
| DAILY = ["Date", "Emp Code", "Name", "Department", "Check In", "Check Out", "Hours", "Status", "Manual", "Note"] | |
| MONTHLY = ["Emp Code", "Name", "Department", "Present Days", "Late Days", "Absent Days", "Total Hours", "Avg Check In"] | |
| def daily_rows(db, d1, d2, eid=None, dept="", status="", absent=False): | |
| """-> (rows, attendance ids). Employees without a record are added as Absent for a single day.""" | |
| recs = db.attendance(d1, d2, eid, dept, status) | |
| rows = [[r["date"], r["emp_code"], r["name"], r["department"], (r["check_in"] or "")[11:], (r["check_out"] or "")[11:], | |
| round(hours(r["check_in"], r["check_out"]), 2), r["status"], "Yes" if r["manual"] else "", r["note"]] for r in recs] | |
| if absent and d1 == d2 and status in ("", "Absent"): | |
| seen = {r["employee_id"] for r in (db.attendance(d1, d1) if status else recs)} # everybody with any record that day | |
| rows += [[d1, e["emp_code"], e["name"], e["department"], "", "", 0, "Absent", "", ""] for e in db.employees(active=True) | |
| if e["id"] not in seen and (not eid or e["id"] == eid) and (not dept or e["department"] == dept)] | |
| return rows, [r["id"] for r in recs] | |
| def monthly_rows(db, y, m, dept=""): | |
| last, by = calendar.monthrange(y, m)[1], defaultdict(list) | |
| for r in db.attendance("%d-%02d-01" % (y, m), "%d-%02d-%02d" % (y, m, last), dept=dept): by[r["employee_id"]].append(r) | |
| work = {d.isoformat() for d in (date(y, m, i) for i in range(1, last + 1)) if d <= date.today() and d.weekday() < 5} # Sat/Sun off | |
| rows = [] | |
| for e in db.employees(active=True): | |
| if dept and e["department"] != dept: continue | |
| rs = by[e["id"]]; pres = sum(r["status"] in ("Present", "Late") for r in rs) | |
| ins = [int(r["check_in"][11:13]) * 60 + int(r["check_in"][14:16]) for r in rs if r["check_in"]] | |
| rows.append([e["emp_code"], e["name"], e["department"], pres, sum(r["status"] == "Late" for r in rs), | |
| len(work - {r["date"] for r in rs if r["status"] != "Absent"}), # working days so far with no record, or marked Absent | |
| round(sum(hours(r["check_in"], r["check_out"]) for r in rs), 2), "%02d:%02d" % divmod(sum(ins) // len(ins), 60) if ins else ""]) | |
| return rows | |
| def export(path, headers, rows): | |
| if path.lower().endswith(".xlsx"): | |
| from openpyxl import Workbook | |
| wb = Workbook(); ws = wb.active; ws.append(list(headers)); ws.freeze_panes = "A2" | |
| for r in rows: ws.append(list(r)) | |
| wb.save(path) | |
| else: | |
| with open(path, "w", newline="", encoding="utf-8-sig") as f: w = csv.writer(f); w.writerow(headers); w.writerows(rows) | |
| # -------------------------------------------------------------- enrollment | |
| class Collector: | |
| """Keeps good, varied samples of ONE person.""" | |
| def __init__(self, target, max_sim=0.95, min_same=0.62): self.target, self.max_sim, self.min_same = target, max_sim, min_same; self.reset() | |
| def reset(self): self.embs, self.faces, self.best, self.best_score = [], [], None, -1.0 | |
| done = property(lambda s: len(s.embs) >= s.target) | |
| def offer(self, f): | |
| if f.emb is None or not f.ok: return False, ", ".join(f.reasons) or "low quality" | |
| if self.embs: | |
| E = np.stack(self.embs); mean = E.mean(0) | |
| if f.emb @ mean / np.linalg.norm(mean) < self.min_same: return False, "different person? only the enrolling person may be in view" | |
| if (E @ f.emb).max() > self.max_sim: return False, "move your head slightly" | |
| self.embs.append(f.emb); self.faces.append(f) | |
| if f.score > self.best_score: self.best, self.best_score = f.bgr(), f.score | |
| return True, "captured" | |