Face unlock window: live camera preview, Snap, thumbnails, one password on Apply
CI / test (push) Failing after 12m30s
CI / test (push) Failing after 12m30s
Settings > Session "Add or remove faces…" (and "Remove…" on a face) opens a compositor-drawn Face unlock window instead of running root steps one by one: - chandra-face camera runs as the user (no password): it streams a small live picture with the face box and a cropped thumbnail per snap; the snaps' embeddings stay in that process, nothing is written to disk. - Click a snap to drop it; mark saved faces Remove/Keep. - Apply saves the snaps as one face and removes the marked ones in one root `chandra-face apply` (JSON on stdin, validated) through run0/pkexec: one password prompt. - New raster host function image-pixels (host-wasm, wasmhost, native) for the window's pictures. Tests: camera session and apply in face/test_face.py; the window end to end against a fake tool in compositor/host/face_test.mbt. Docs explain why the change itself still needs root. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DPL5hhiJfJNAYqWzQiuKMf
This commit is contained in:
74 files changed
+2617
-89
No files matched your search
+283
-14
@@ -12,6 +12,12 @@
|
||||
chandra-face pam [status|enable|disable] [SERVICE...] put pam_chandra_face.so into
|
||||
/etc/pam.d/SERVICE (root; default polkit-1 sudo)
|
||||
chandra-face fetch-models download the face models (root)
|
||||
chandra-face camera [--label L] the "Add a face" window's camera, run as you: streams
|
||||
a small live picture with the face box, keeps snaps
|
||||
(their embeddings) in memory, and on "apply" saves
|
||||
the snaps and removals in one root step (one password)
|
||||
chandra-face apply [--user U] add and remove faces in one go, from JSON on stdin:
|
||||
{"add": [{"label", "vectors"}], "remove": [ids]} (root)
|
||||
|
||||
Root commands started by another user re-run themselves through run0 or pkexec, so polkit asks
|
||||
for an administrator's password first (in Chandra's own dialog).
|
||||
@@ -35,6 +41,8 @@ import re
|
||||
import shutil
|
||||
import stat
|
||||
import sys
|
||||
import select
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
@@ -253,6 +261,10 @@ class OpenCVRecognizer:
|
||||
import numpy as np
|
||||
|
||||
self.cv2, self.np = cv2, np
|
||||
try:
|
||||
cv2.utils.logging.setLogLevel(cv2.utils.logging.LOG_LEVEL_ERROR)
|
||||
except AttributeError:
|
||||
pass
|
||||
if not hasattr(cv2, "FaceDetectorYN"):
|
||||
raise Fail("OpenCV %s is too old (4.5.4+ needed)" % cv2.__version__, 2)
|
||||
det = os.path.join(cfg.models, "face_detection_yunet_2023mar.onnx")
|
||||
@@ -362,13 +374,16 @@ def read_pnm(path):
|
||||
class ImageCamera:
|
||||
"""`images:DIR`: the image files in DIR, in name order, as camera frames (for tests)."""
|
||||
|
||||
def __init__(self, spec, cfg):
|
||||
def __init__(self, spec, cfg, loop=False):
|
||||
d = spec[len("images:"):]
|
||||
self.files = sorted(os.path.join(d, f) for f in os.listdir(d) if not f.startswith("."))
|
||||
self.i = 0
|
||||
self.cfg = cfg
|
||||
self.loop = loop
|
||||
|
||||
def read(self):
|
||||
if self.loop and self.files:
|
||||
self.i %= len(self.files)
|
||||
if self.i >= len(self.files):
|
||||
return None
|
||||
f = self.files[self.i]
|
||||
@@ -405,9 +420,9 @@ class V4L2Camera:
|
||||
self.cap.release()
|
||||
|
||||
|
||||
def open_camera(cfg):
|
||||
def open_camera(cfg, loop=False):
|
||||
if cfg.device.startswith("images:"):
|
||||
return ImageCamera(cfg.device, cfg)
|
||||
return ImageCamera(cfg.device, cfg, loop)
|
||||
if not cfg.device.isdigit() and not os.path.exists(cfg.device):
|
||||
raise Fail("no camera at %s" % cfg.device, 2)
|
||||
return V4L2Camera(cfg.device)
|
||||
@@ -521,7 +536,7 @@ def cmd_enroll(cfg, user, label, out):
|
||||
raise Fail("couldn't see a face clearly: look at the camera in good light and try again")
|
||||
faces = load_faces(cfg, user)
|
||||
nid = max([f["id"] for f in faces] + [0]) + 1
|
||||
label = (label or "Face %d" % nid).replace("\t", " ").replace("\n", " ")[:60]
|
||||
label = clean_label(label, nid)
|
||||
faces.append({"id": nid, "label": label, "created": time.strftime("%Y-%m-%d"),
|
||||
"vectors": [[round(x, 6) for x in v] for v in vecs]})
|
||||
save_faces(cfg, user, faces)
|
||||
@@ -529,6 +544,260 @@ def cmd_enroll(cfg, user, label, out):
|
||||
return 0
|
||||
|
||||
|
||||
def clean_label(label, nid):
|
||||
return (label or "Face %d" % nid).replace("\t", " ").replace("\n", " ").strip()[:60] or "Face %d" % nid
|
||||
|
||||
|
||||
MAX_APPLY = 1 << 20
|
||||
|
||||
|
||||
def cmd_apply(cfg, user, out, data=None):
|
||||
"""Add and remove faces in one step (what the "Add a face" window's Apply runs as root).
|
||||
|
||||
The embeddings come from the user's own camera process: anyone who can type the admin
|
||||
password could enroll any face anyway, so the password is the check, as for enroll."""
|
||||
check_user(user)
|
||||
if data is None:
|
||||
data = sys.stdin.buffer.read(MAX_APPLY + 1)
|
||||
if len(data) > MAX_APPLY:
|
||||
raise Fail("too much data")
|
||||
try:
|
||||
req = json.loads(data.decode("utf-8") or "{}")
|
||||
except ValueError:
|
||||
raise Fail("bad request")
|
||||
if not isinstance(req, dict):
|
||||
raise Fail("bad request")
|
||||
adds = req.get("add") or []
|
||||
removes = [str(r) for r in (req.get("remove") or [])]
|
||||
if not isinstance(adds, list) or len(adds) > 8:
|
||||
raise Fail("bad request")
|
||||
faces = load_faces(cfg, user)
|
||||
dims = {len(v) for f in faces for v in f.get("vectors", [])}
|
||||
new = []
|
||||
for a in adds:
|
||||
vecs = a.get("vectors") if isinstance(a, dict) else None
|
||||
if not isinstance(vecs, list) or not 1 <= len(vecs) <= 32:
|
||||
raise Fail("bad face data")
|
||||
for v in vecs:
|
||||
if not isinstance(v, list) or not 4 <= len(v) <= 1024 or \
|
||||
not all(isinstance(x, (int, float)) and math.isfinite(x) for x in v):
|
||||
raise Fail("bad face data")
|
||||
dims.add(len(v))
|
||||
if len(dims) > 1:
|
||||
raise Fail("face data from another recognizer")
|
||||
label = a.get("label") if isinstance(a.get("label"), str) else ""
|
||||
new.append((label, vecs))
|
||||
known = {str(f["id"]) for f in faces}
|
||||
missing = [r for r in removes if r not in known]
|
||||
if missing:
|
||||
raise Fail("no face %s for %s" % (", ".join(missing), user))
|
||||
nid = max([f["id"] for f in faces] + [0]) # ids aren't reused
|
||||
faces = [f for f in faces if str(f["id"]) not in removes]
|
||||
for label, vecs in new:
|
||||
nid += 1
|
||||
faces.append({"id": nid, "label": clean_label(label, nid), "created": time.strftime("%Y-%m-%d"),
|
||||
"vectors": [[round(float(x), 6) for x in v] for v in vecs]})
|
||||
save_faces(cfg, user, faces)
|
||||
parts = []
|
||||
if new:
|
||||
parts.append("added %s" % ", ".join(f["label"] for f in faces[-len(new):]))
|
||||
if removes:
|
||||
parts.append("removed %d face%s" % (len(removes), "" if len(removes) == 1 else "s"))
|
||||
msg = " and ".join(parts) or "nothing to change"
|
||||
out.emit("done", msg[:1].upper() + msg[1:])
|
||||
return 0
|
||||
|
||||
|
||||
PREVIEW_W = 320
|
||||
THUMB = 96
|
||||
|
||||
|
||||
def resize_rows(rows, w, h):
|
||||
"""Nearest-pixel resize of rows of gray values (the fake camera's frames)."""
|
||||
sh, sw = len(rows), len(rows[0])
|
||||
return [[rows[y * sh // h][x * sw // w] for x in range(w)] for y in range(h)]
|
||||
|
||||
|
||||
def rgb_bytes(frame, rec, box=None, size=None):
|
||||
"""`frame` (or its `box` = (x, y, w, h)) as RGB bytes at `size` = (w, h)."""
|
||||
if isinstance(frame, list):
|
||||
if box:
|
||||
x, y, w, h = box
|
||||
frame = [r[x:x + w] for r in frame[y:y + h]]
|
||||
g = resize_rows(frame, *size)
|
||||
return bytes(v for r in g for v in r for _ in range(3))
|
||||
cv2 = rec.cv2 if hasattr(rec, "cv2") else __import__("cv2")
|
||||
if box:
|
||||
x, y, w, h = box
|
||||
frame = frame[y:y + h, x:x + w]
|
||||
if frame.ndim == 2:
|
||||
frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR)
|
||||
frame = cv2.resize(frame, size, interpolation=cv2.INTER_AREA)
|
||||
return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB).tobytes()
|
||||
|
||||
|
||||
def frame_size(frame):
|
||||
if isinstance(frame, list):
|
||||
return len(frame[0]), len(frame)
|
||||
return frame.shape[1], frame.shape[0]
|
||||
|
||||
|
||||
def send_blob(header, data):
|
||||
"""A binary message: `header LEN` on a line, then LEN bytes."""
|
||||
sys.stdout.flush()
|
||||
sys.stdout.buffer.write(("%s %d\n" % (header, len(data))).encode())
|
||||
sys.stdout.buffer.write(data)
|
||||
sys.stdout.buffer.flush()
|
||||
|
||||
|
||||
def elevated(args):
|
||||
"""argv running chandra-face `args` as root through run0 or pkexec (polkit asks first)."""
|
||||
me = os.path.realpath(sys.argv[0])
|
||||
run0 = shutil.which("run0")
|
||||
if run0 and os.path.isdir("/run/systemd/system"):
|
||||
return [run0, "--background=", "--", sys.executable, "-I", me] + args
|
||||
pk = shutil.which("pkexec")
|
||||
if pk:
|
||||
return [pk, sys.executable, "-I", me] + args
|
||||
raise Fail("needs root, and neither run0 nor pkexec is installed")
|
||||
|
||||
|
||||
def cmd_camera(cfg, user, label, out, cfg_path, no_elevate):
|
||||
"""The "Add a face" window's camera, run as the session user (no root, no password).
|
||||
|
||||
Out ("--machine" lines): `frame W H BX BY BW BH LEN` + LEN bytes of RGB (the live picture,
|
||||
about 12 a second; the box is -1s without one face), `snap ID W H LEN` + RGB (a kept snap,
|
||||
cropped to the face), `info` / `error` / `done` lines, `applied CODE` at the end of an apply.
|
||||
In (stdin lines): `snap`, `drop ID`, `apply REMOVE-IDS` (comma-separated, may be empty), `quit`.
|
||||
The pictures stay in this process's memory: nothing is written to disk; only the embeddings
|
||||
of the snaps kept go to the root `apply`, through a pipe."""
|
||||
check_user(user)
|
||||
rec = make_recognizer(cfg)
|
||||
cam = open_camera(cfg, loop=True)
|
||||
snaps = {} # id -> embedding
|
||||
next_id = 1
|
||||
last = None
|
||||
last_sent = 0.0
|
||||
pending = b""
|
||||
out.info("Look at the camera and press Snap")
|
||||
try:
|
||||
while True:
|
||||
frame = cam.read()
|
||||
if frame is None:
|
||||
out.error("The camera gave no picture")
|
||||
return 2
|
||||
if isinstance(cam, ImageCamera):
|
||||
time.sleep(max(cfg.frame_delay, 0.03))
|
||||
last = frame
|
||||
now = time.monotonic()
|
||||
if now - last_sent >= 0.08:
|
||||
last_sent = now
|
||||
w, h = frame_size(frame)
|
||||
pw = min(PREVIEW_W, w)
|
||||
ph = max(1, h * pw // w)
|
||||
dets = rec.detect(frame) if rec.brightness(frame) >= cfg.dark else []
|
||||
bx = (-1, -1, -1, -1)
|
||||
if len(dets) == 1:
|
||||
d = dets[0]
|
||||
bx = (d.x * pw // w, d.y * ph // h, d.w * pw // w, d.h * ph // h)
|
||||
send_blob("frame %d %d %d %d %d %d" % ((pw, ph) + bx), rgb_bytes(frame, rec, size=(pw, ph)))
|
||||
r, _, _ = select.select([0], [], [], 0)
|
||||
if not r:
|
||||
continue
|
||||
got = os.read(0, 4096)
|
||||
if not got:
|
||||
return 0
|
||||
pending += got
|
||||
while b"\n" in pending:
|
||||
line, pending = pending.split(b"\n", 1)
|
||||
words = line.decode("utf-8", "replace").strip().split(" ", 1)
|
||||
cmd, arg = words[0], (words[1] if len(words) > 1 else "")
|
||||
if cmd == "quit":
|
||||
return 0
|
||||
if cmd == "drop":
|
||||
snaps.pop(arg, None)
|
||||
elif cmd == "snap":
|
||||
v, why, box = snap_face(cfg, rec, last)
|
||||
if v is None:
|
||||
out.error(why)
|
||||
continue
|
||||
sid = str(next_id)
|
||||
next_id += 1
|
||||
snaps[sid] = v
|
||||
send_blob("snap %s %d %d" % (sid, THUMB, THUMB), rgb_bytes(last, rec, box, (THUMB, THUMB)))
|
||||
elif cmd == "apply":
|
||||
cam.close()
|
||||
cam = None
|
||||
removes = [r for r in arg.split(",") if r.strip()]
|
||||
req = {"add": [{"label": label or "", "vectors": list(snaps.values())}] if snaps else [],
|
||||
"remove": removes}
|
||||
code = run_apply(cfg, user, out, req, cfg_path, no_elevate)
|
||||
out.emit("applied", str(code))
|
||||
return code
|
||||
finally:
|
||||
if cam is not None:
|
||||
cam.close()
|
||||
|
||||
|
||||
def snap_face(cfg, rec, frame):
|
||||
"""(embedding, "", square face box) for the one face in `frame`, or (None, why, None)."""
|
||||
if frame is None:
|
||||
return None, "No picture yet", None
|
||||
if rec.brightness(frame) < cfg.dark:
|
||||
return None, "The picture is too dark", None
|
||||
dets = rec.detect(frame)
|
||||
if not dets:
|
||||
return None, "No face in view", None
|
||||
if len(dets) > 1:
|
||||
return None, "More than one face in view", None
|
||||
d = dets[0]
|
||||
if d.w < cfg.min_face and d.h < cfg.min_face and cfg.backend != "fake":
|
||||
return None, "Come closer to the camera", None
|
||||
if cfg.require_ir and not rec.gray(frame):
|
||||
return None, "Needs an infrared camera (require_ir)", None
|
||||
v = [round(x, 6) for x in rec.embed(frame, d)]
|
||||
w, h = frame_size(frame)
|
||||
side = min(int(max(d.w, d.h) * 1.4), w, h)
|
||||
x = min(max(0, d.x + d.w // 2 - side // 2), w - side)
|
||||
y = min(max(0, d.y + d.h // 2 - side // 2), h - side)
|
||||
return v, "", (x, y, side, side)
|
||||
|
||||
|
||||
def run_apply(cfg, user, out, req, cfg_path, no_elevate):
|
||||
"""Run `apply` as root with `req` on its stdin, passing on what it says."""
|
||||
data = json.dumps(req).encode()
|
||||
if os.geteuid() == 0 or no_elevate:
|
||||
try:
|
||||
return cmd_apply(cfg, user, out, data)
|
||||
except Fail as e:
|
||||
out.error(str(e))
|
||||
return e.code
|
||||
args = ["apply", "--machine", "--user", user]
|
||||
if cfg_path != DEFAULT_CONFIG:
|
||||
args += ["--config", cfg_path]
|
||||
out.info("Waiting for the password…")
|
||||
p = subprocess.Popen(elevated(args), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL)
|
||||
try:
|
||||
p.stdin.write(data)
|
||||
p.stdin.close()
|
||||
except BrokenPipeError:
|
||||
pass
|
||||
said = False
|
||||
for raw in p.stdout:
|
||||
line = raw.decode("utf-8", "replace").rstrip("\n")
|
||||
kind = line.split(" ", 1)[0]
|
||||
if kind in ("info", "error", "done"):
|
||||
said = said or kind != "info"
|
||||
sys.stdout.write(line + "\n")
|
||||
sys.stdout.flush()
|
||||
code = p.wait()
|
||||
if not said:
|
||||
out.error("Nothing changed")
|
||||
return code or 1
|
||||
return code
|
||||
|
||||
|
||||
def cmd_remove(cfg, user, ident, out):
|
||||
check_user(user)
|
||||
faces = load_faces(cfg, user)
|
||||
@@ -670,22 +939,16 @@ def cmd_fetch_models(cfg, out):
|
||||
# ---------------------------------------------------------------- main
|
||||
|
||||
|
||||
ROOT_CMDS = ("enroll", "remove", "clear", "test", "compare", "fetch-models")
|
||||
ROOT_CMDS = ("enroll", "remove", "clear", "test", "compare", "fetch-models", "apply")
|
||||
|
||||
|
||||
def elevate(argv, user):
|
||||
"""Run this command again as root through run0 (systemd) or pkexec: polkit asks first."""
|
||||
me = os.path.realpath(sys.argv[0])
|
||||
args = [me] + argv
|
||||
args = list(argv)
|
||||
if "--user" not in argv:
|
||||
args += ["--user", user]
|
||||
run0 = shutil.which("run0")
|
||||
if run0 and os.path.isdir("/run/systemd/system"):
|
||||
os.execv(run0, [run0, "--background=", "--"] + [sys.executable, "-I"] + args)
|
||||
pk = shutil.which("pkexec")
|
||||
if pk:
|
||||
os.execv(pk, [pk, sys.executable, "-I"] + args)
|
||||
raise Fail("needs root, and neither run0 nor pkexec is installed")
|
||||
cmd = elevated(args)
|
||||
os.execv(cmd[0], cmd)
|
||||
|
||||
|
||||
def main(argv):
|
||||
@@ -745,6 +1008,10 @@ def main(argv):
|
||||
return cmd_compare(cfg, user, out, verbose=True)
|
||||
if cmd == "enroll":
|
||||
return cmd_enroll(cfg, user, label, out)
|
||||
if cmd == "apply":
|
||||
return cmd_apply(cfg, user, out)
|
||||
if cmd == "camera":
|
||||
return cmd_camera(cfg, user, label, out, cfg_path, no_elevate)
|
||||
if cmd == "remove":
|
||||
if not params:
|
||||
raise Fail("remove ID")
|
||||
@@ -768,6 +1035,8 @@ def main(argv):
|
||||
return e.code
|
||||
except KeyboardInterrupt:
|
||||
return 1
|
||||
except BrokenPipeError:
|
||||
return 0 # the window that read us went away
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in new issue
Block a user