Face unlock: say why a camera can't be used, list the cameras, pick one
CI / test (push) Canceled after 21m7s

"no camera at PATH" now says why (not there or a broken link, permission
denied, not a V4L2 device, a metadata node rather than the picture node,
OpenCV couldn't start it or it gives no picture: another app using it) and
lists the cameras found (VIDIOC_QUERYCAP on /dev/v4l/by-id/* and /dev/video*).
New commands: `chandra-face cameras`, `chandra-face set-camera PATH` (root,
edits device in face.conf after checking it is a capture node). The Face
unlock window shows the cameras found with a Use button (one password), then
opens again. just install prints NOT READY with the reason when the
configured camera can't be used.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hhiJfJNAYqWzQiuKMf
This commit is contained in:
Claude committed 2026-11-26 04:47:06 +00:00
1 parent ff6f733810
commit 516180196f
7 files changed
+251 -9

No files matched your search

+128 -8
View File
@@ -16,6 +16,8 @@
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 cameras the cameras here, and why one can't be used (anyone)
chandra-face set-camera PATH use the camera at PATH (root; edits face.conf)
chandra-face apply [--user U] add and remove faces in one go, from JSON on stdin:
{"add": [{"label", "vectors"}], "remove": [ids]} (root)
@@ -32,6 +34,9 @@ be fooled by a good photo, more easily with an RGB webcam than an IR camera; see
"""
import configparser
import fcntl
import glob
import struct
import hashlib
import json
import math
@@ -403,14 +408,88 @@ class ImageCamera:
pass
VIDIOC_QUERYCAP = 0x80685600
V4L2_CAP_VIDEO_CAPTURE = 0x1
V4L2_CAP_VIDEO_CAPTURE_MPLANE = 0x1000
V4L2_CAP_DEVICE_CAPS = 0x80000000
def query_camera(path):
"""(name, "") when `path` is a V4L2 node that captures pictures, else (name or "", why not)."""
try:
fd = os.open(path, os.O_RDWR | os.O_NONBLOCK)
except OSError as e:
why = e.strerror or str(e)
if e.errno in (13, 1): # EACCES, EPERM
why += " (you need access to it: be logged in at this seat, or in the video group)"
return "", why
try:
buf = bytearray(104)
try:
fcntl.ioctl(fd, VIDIOC_QUERYCAP, buf)
except OSError as e:
return "", "not a V4L2 camera (%s)" % (e.strerror or e)
name = bytes(buf[16:48]).split(b"\0")[0].decode("utf-8", "replace")
caps, dev_caps = struct.unpack_from("<II", buf, 84)
c = dev_caps if caps & V4L2_CAP_DEVICE_CAPS else caps
if not c & (V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_VIDEO_CAPTURE_MPLANE):
return name, "not a picture node (metadata; its -video-index0 sibling is the camera)"
return name, ""
finally:
os.close(fd)
def list_cameras():
"""[(path, name, why not or "")]: the /dev/v4l/by-id links, then /dev/video* nodes no link
points at."""
out, seen = [], set()
for p in sorted(glob.glob("/dev/v4l/by-id/*")):
seen.add(os.path.realpath(p))
out.append((p,) + query_camera(p))
for p in sorted(glob.glob("/dev/video*"), key=lambda s: (len(s), s)):
if os.path.realpath(p) not in seen:
out.append((p,) + query_camera(p))
return out
def cameras_text(cams):
ok = ["%s (%s)" % (n or "camera", p) for p, n, why in cams if not why]
if not ok:
return "no camera that takes pictures is connected"
return "cameras here: " + "; ".join(ok)
def camera_problem(device):
"""Why the configured camera can't be used, or "" (only checks the node, not streaming)."""
if device.startswith("images:"):
return ""
path = "/dev/video" + device if device.isdigit() else device
if not os.path.exists(path):
why = "broken link" if os.path.islink(path) else "not there"
return ("no camera at %s (%s: unplugged, or its name differs); %s. Pick one in Settings > "
"Session > Add or remove faces, or run chandra-face set-camera PATH"
% (path, why, cameras_text(list_cameras())))
name, why = query_camera(path)
if why:
return "camera %s: %s; %s" % (path, why, cameras_text(list_cameras()))
return ""
class V4L2Camera:
def __init__(self, device):
problem = camera_problem(device)
if problem:
raise Fail(problem, 2)
import cv2
self.cv2 = cv2
dev = int(device) if device.isdigit() else device
self.cap = cv2.VideoCapture(dev, cv2.CAP_V4L2)
if not self.cap.isOpened():
raise Fail("camera %s not available" % device, 2)
raise Fail("OpenCV couldn't start camera %s (is another app using it?)" % device, 2)
ok, _ = self.cap.read()
if not ok:
self.cap.release()
raise Fail("camera %s gives no picture (is another app using it?)" % device, 2)
def read(self):
ok, frame = self.cap.read()
@@ -423,8 +502,6 @@ class V4L2Camera:
def open_camera(cfg, loop=False):
if cfg.device.startswith("images:"):
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)
@@ -674,7 +751,13 @@ def cmd_camera(cfg, user, label, out, cfg_path, no_elevate):
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)
try:
cam = open_camera(cfg, loop=True)
except Fail as e:
# Say why, and which cameras there are: the window offers them.
out.error(str(e))
cmd_cameras(out)
return e.code
snaps = {} # id -> embedding
next_id = 1
last = None
@@ -901,9 +984,8 @@ def cmd_status(cfg, user, out):
if not os.path.exists(os.path.join(cfg.models, m)):
problem = "face models missing: run chandra-face fetch-models"
break
if not problem and not cfg.device.startswith("images:") and not cfg.device.isdigit() \
and not os.path.exists(cfg.device):
problem = "no camera at %s" % cfg.device
if not problem:
problem = camera_problem(cfg.device)
out.emit("backend", backend)
out.emit("device", cfg.device)
if problem:
@@ -917,6 +999,38 @@ def cmd_status(cfg, user, out):
return 0
def cmd_cameras(out):
"""Lines `camera PATH<TAB>NAME<TAB>WHY` (WHY empty: it takes pictures)."""
for p, n, why in list_cameras():
out.emit("camera", "%s\t%s\t%s" % (p, n, why))
return 0
def cmd_set_camera(cfg, path, out):
"""Point face.conf's `device` at `path` (root), after checking it is a camera."""
if not path.startswith("/dev/") or not os.path.exists(path):
raise Fail("no camera at %s" % path)
name, why = query_camera(path)
if why:
raise Fail("%s: %s" % (path, why))
conf = cfg.path
text = open(conf).read() if os.path.exists(conf) else "[face]\n"
lines = text.split("\n")
at = next((i for i, l in enumerate(lines) if re.match(r"^\s*device\s*=", l)), None)
if at is None:
sec = next((i for i, l in enumerate(lines) if l.strip() == "[face]"), None)
if sec is None:
lines += ["[face]"]
sec = len(lines) - 1
lines.insert(sec + 1, "device = " + path)
else:
lines[at] = "device = " + path
os.makedirs(os.path.dirname(conf) or ".", exist_ok=True)
write_atomic(conf, "\n".join(lines), 0o644)
out.emit("done", "Camera: %s" % (name or path))
return 0
def cmd_fetch_models(cfg, out):
import urllib.request
@@ -943,7 +1057,7 @@ def cmd_fetch_models(cfg, out):
# ---------------------------------------------------------------- main
ROOT_CMDS = ("enroll", "remove", "clear", "test", "compare", "fetch-models", "apply")
ROOT_CMDS = ("enroll", "remove", "clear", "test", "compare", "fetch-models", "apply", "set-camera")
def elevate(argv, user):
@@ -1016,6 +1130,12 @@ def main(argv):
return cmd_apply(cfg, user, out)
if cmd == "camera":
return cmd_camera(cfg, user, label, out, cfg_path, no_elevate)
if cmd == "cameras":
return cmd_cameras(out)
if cmd == "set-camera":
if not params:
raise Fail("set-camera PATH (see chandra-face cameras)")
return cmd_set_camera(cfg, params[0], out)
if cmd == "remove":
if not params:
raise Fail("remove ID")
+5
View File
@@ -167,5 +167,10 @@ if "--no-models" not in sys.argv:
subprocess.check_call([py, "-I", helper, "--no-elevate", "fetch-models"])
if "--pam" in sys.argv:
subprocess.check_call([py, "-I", helper, "--no-elevate", "pam", "enable"])
# Say now when it can't work yet (no camera at the configured path, say), and what is there.
st = subprocess.run([py, "-I", helper, "--no-elevate", "status", "--machine"], capture_output=True, text=True)
for line in st.stdout.splitlines():
if line.startswith("problem "):
print("face unlock: NOT READY: " + line[len("problem "):], file=sys.stderr)
print("face unlock: add a face in Settings > Session > Face unlock (after logging in to the new "
"session), or now with `chandra-face enroll`, then `chandra-face pam enable`")
+20 -1
View File
@@ -237,7 +237,8 @@ class FaceTests(unittest.TestCase):
self.assertEqual(rc, 0)
self.assertTrue(any(l.startswith("problem ") for l in out), out)
self.env.camera([], device="/dev/no-such-camera")
self.assertIn("problem no camera at /dev/no-such-camera", self.env.run("status")[1])
out = self.env.run("status")[1]
self.assertTrue(any(l.startswith("problem no camera at /dev/no-such-camera (not there") for l in out), out)
class Session:
@@ -354,6 +355,24 @@ class CameraWindowTests(unittest.TestCase):
self.assertEqual(s.finish(), 0)
self.assertEqual(len(self.vectors()[0]["vectors"]), 2)
def test_a_missing_camera_says_why_and_lists_the_cameras(self):
self.env.camera([], device="/dev/v4l/by-id/usb-No-Such-Camera-video-index0", backend="fake")
s = Session(self.env)
words, _ = s.next("error")
text = " ".join(words[1:])
self.assertTrue(text.startswith("no camera at /dev/v4l/by-id/usb-No-Such-Camera-video-index0 (not there"), text)
self.assertIn("chandra-face set-camera PATH", text)
self.assertEqual(s.finish(), 2)
rc, out = self.env.run("status")
self.assertTrue(any(l.startswith("problem no camera at /dev/v4l/by-id/usb-No-Such") for l in out), out)
def test_set_camera_refuses_what_is_not_a_camera(self):
for bad in ("/dev/null", "/dev/v4l/by-id/nothing", "/etc/passwd"):
rc, out = self.env.run("set-camera", bad)
self.assertNotEqual(rc, 0, bad)
self.assertTrue(out[-1].startswith("error"), out)
self.assertNotIn("/dev/null", slurp(self.env.conf))
def test_apply_refuses_bad_data(self):
for bad in (b"[]", b"{\"add\": [{\"vectors\": [[1, 2]]}]}",
b"{\"add\": [{\"vectors\": [[1e999, 0, 0, 0]]}]}", b"{\"remove\": [7]}", b"nonsense"):