Face unlock: say why a camera can't be used, list the cameras, pick one
CI / test (push) Canceled after 21m7s
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:
7 files changed
+251
-9
No files matched your search
+128
-8
@@ -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")
|
||||
|
||||
Reference in new issue
Block a user