#!/usr/bin/python3 """Record a Howdy face model from many frames, for howdy-settings. Howdy's own "add" keeps one frame. This records for a few seconds while the user turns their head and keeps the most different views, so the model covers more angles. Usage, as root: enroll.py USER LABEL With --score USER it checks the face like Howdy does at login and prints the match score (distance to the nearest view times ten, lower is closer); the exit code is 0 when the score is under the certainty limit, as in compare.py. """ import configparser import json import pathlib import sys import time import numpy as np HOWDY_DIRS = ["/usr/lib64/howdy", "/usr/lib/howdy"] SECONDS = 8 MIN_VIEWS = 5 def pick_diverse(views, count=8, spread=0.05): """Start from the most typical view, then add the view farthest from the chosen ones until there are `count` or the rest are closer than `spread`.""" views = np.array(views) distances = np.linalg.norm(views[:, None] - views[None, :], axis=2) chosen = [int(distances.sum(axis=1).argmin())] while len(chosen) < count: nearest = distances[:, chosen].min(axis=1) best = int(nearest.argmax()) if nearest[best] < spread: break chosen.append(best) return [views[i].tolist() for i in chosen] def score_of(known, view): return float(np.linalg.norm(np.array(known) - np.array(view), axis=1).min() * 10) def views(config, seconds): """Encodings of frames that show exactly one face, for `seconds`.""" import dlib # noqa: E402 dlib before OpenCV, as Howdy does import cv2 import paths_factory from recorders.video_capture import VideoCapture from rotation import rotate_frame detector = dlib.get_frontal_face_detector() pose = dlib.shape_predictor(paths_factory.shape_predictor_5_face_landmarks_path()) encoder = dlib.face_recognition_model_v1( paths_factory.dlib_face_recognition_resnet_model_v1_path()) dark_threshold = config.getfloat("video", "dark_threshold", fallback=60) rotate = config.getint("video", "rotate", fallback=0) clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)) capture = VideoCapture(config) frames, start = 0, time.monotonic() while time.monotonic() - start < seconds: frames += 1 frame, gsframe = capture.read_frame() gsframe = clahe.apply(gsframe) hist = cv2.calcHist([gsframe], [0], None, [8], [0, 256]) if hist.sum() == 0 or hist[0][0] / hist.sum() * 100 > dark_threshold: continue frame = rotate_frame(frame, rotate, frames) gsframe = rotate_frame(gsframe, rotate, frames) faces = detector(gsframe, 1) if len(faces) == 1: landmarks = pose(frame, faces[0]) yield list(encoder.compute_face_descriptor(frame, landmarks, 1)) capture.release() def load_config(): sys.path[:0] = HOWDY_DIRS import paths_factory config = configparser.ConfigParser() config.read(paths_factory.config_file_path()) return config, paths_factory def score(user): config, paths_factory = load_config() model_file = pathlib.Path(paths_factory.user_model_path(user)) if not model_file.exists(): sys.exit(10) known = [view for model in json.loads(model_file.read_text()) for view in model["data"]] limit = config.getfloat("video", "certainty", fallback=3.5) # After the first match, which unlocks at login, a few more frames show the margin best, extra = None, 5 for view in views(config, config.getfloat("video", "timeout", fallback=4)): best = min(best, score_of(known, view)) if best is not None else score_of(known, view) if best < limit: extra -= 1 if extra < 0: break if best is None: sys.exit(11) print(f"{best:.2f} {limit:.2f}") sys.exit(0 if best < limit else 11) def main(user, label): config, paths_factory = load_config() found = list(views(config, SECONDS)) if len(found) < MIN_VIEWS: sys.exit("No face seen long enough, look at the camera and try again") model_file = pathlib.Path(paths_factory.user_model_path(user)) models = json.loads(model_file.read_text()) if model_file.exists() else [] models.append({ "time": int(time.time()), "label": label, "id": models[-1]["id"] + 1 if models else 0, "data": pick_diverse(found), }) model_file.write_text(json.dumps(models)) if __name__ == "__main__": if sys.argv[1] == "--score": score(sys.argv[2]) else: main(*sys.argv[1:3])