0
0
Fork 0
mirror of https://github.com/boltgolt/howdy.git synced 2024-09-19 09:51:19 +02:00

refactor: add path factory to not recreate paths

This commit is contained in:
Sayafdine Said 2023-06-25 11:57:13 +02:00
parent 87017faf86
commit c12dce0956
No known key found for this signature in database
GPG key ID: 7567D43648C6E2F4
12 changed files with 76 additions and 34 deletions

View file

@ -9,6 +9,7 @@ import configparser
import builtins import builtins
import numpy as np import numpy as np
import paths import paths
import paths_factory
from recorders.video_capture import VideoCapture from recorders.video_capture import VideoCapture
from i18n import _ from i18n import _
@ -28,7 +29,7 @@ except ImportError as err:
import cv2 import cv2
# Test if at lest 1 of the data files is there and abort if it's not # Test if at lest 1 of the data files is there and abort if it's not
if not os.path.isfile(paths.dlib_data_dir / "shape_predictor_5_face_landmarks.dat"): if not os.path.isfile(paths_factory.shape_predictor_5_face_landmarks_path()):
print(_("Data files have not been downloaded, please run the following commands:")) print(_("Data files have not been downloaded, please run the following commands:"))
print("\n\tcd " + paths.dlib_data_dir) print("\n\tcd " + paths.dlib_data_dir)
print("\tsudo ./install.sh\n") print("\tsudo ./install.sh\n")
@ -36,20 +37,20 @@ if not os.path.isfile(paths.dlib_data_dir / "shape_predictor_5_face_landmarks.da
# Read config from disk # Read config from disk
config = configparser.ConfigParser() config = configparser.ConfigParser()
config.read(paths.config_dir / "config.ini") config.read(paths_factory.config_file_path())
use_cnn = config.getboolean("core", "use_cnn", fallback=False) use_cnn = config.getboolean("core", "use_cnn", fallback=False)
if use_cnn: if use_cnn:
face_detector = dlib.cnn_face_detection_model_v1(paths.dlib_data_dir / "mmod_human_face_detector.dat") face_detector = dlib.cnn_face_detection_model_v1(str(paths_factory.mmod_human_face_detector_path()))
else: else:
face_detector = dlib.get_frontal_face_detector() face_detector = dlib.get_frontal_face_detector()
pose_predictor = dlib.shape_predictor(paths.dlib_data_dir / "shape_predictor_5_face_landmarks.dat") pose_predictor = dlib.shape_predictor(str(paths_factory.shape_predictor_5_face_landmarks_path()))
face_encoder = dlib.face_recognition_model_v1(paths.dlib_data_dir / "dlib_face_recognition_resnet_model_v1.dat") face_encoder = dlib.face_recognition_model_v1(str(paths_factory.dlib_face_recognition_resnet_model_v1_path()))
user = builtins.howdy_user user = builtins.howdy_user
# The permanent file to store the encoded model in # The permanent file to store the encoded model in
enc_file = paths.user_models_dir / f"{user}.dat" enc_file = paths_factory.user_model_path(user)
# Known encodings # Known encodings
encodings = [] encodings = []

View file

@ -5,6 +5,7 @@ import os
import sys import sys
import builtins import builtins
import paths import paths
import paths_factory
from i18n import _ from i18n import _
@ -17,7 +18,7 @@ if not os.path.exists(paths.user_models_dir):
sys.exit(1) sys.exit(1)
# Check if the user has a models file to delete # Check if the user has a models file to delete
if not os.path.isfile(paths.user_models_dir / f"{user}.dat"): if not os.path.isfile(paths_factory.user_model_path(user)):
print(_("{} has no models or they have been cleared already").format(user)) print(_("{} has no models or they have been cleared already").format(user))
sys.exit(1) sys.exit(1)
@ -33,5 +34,5 @@ if not builtins.howdy_args.y:
sys.exit(1) sys.exit(1)
# Delete otherwise # Delete otherwise
os.remove(paths.user_models_dir / f"{user}.dat") os.remove(paths_factory.user_model_path(user))
print(_("\nModels cleared")) print(_("\nModels cleared"))

View file

@ -4,6 +4,7 @@
import os import os
import subprocess import subprocess
import paths import paths
import paths_factory
from i18n import _ from i18n import _
@ -20,4 +21,4 @@ elif os.path.isfile("/etc/alternatives/editor"):
editor = "/etc/alternatives/editor" editor = "/etc/alternatives/editor"
# Open the editor as a subprocess and fork it # Open the editor as a subprocess and fork it
subprocess.call([editor, paths.config_dir / "config.ini"]) subprocess.call([editor, paths_factory.config_file_path()])

View file

@ -7,11 +7,12 @@ import builtins
import fileinput import fileinput
import configparser import configparser
import paths import paths
import paths_factory
from i18n import _ from i18n import _
# Get the absolute filepath # Get the absolute filepath
config_path = paths.config_dir.parent / "config.ini" config_path = paths_factory.config_file_path()
# Read config from disk # Read config from disk
config = configparser.ConfigParser() config = configparser.ConfigParser()

View file

@ -7,6 +7,7 @@ import json
import time import time
import builtins import builtins
import paths import paths
import paths_factory
from i18n import _ from i18n import _
@ -19,7 +20,7 @@ if not os.path.exists(paths.user_models_dir):
sys.exit(1) sys.exit(1)
# Path to the models file # Path to the models file
enc_file = paths.user_models_dir / f"{user}.dat" enc_file = paths_factory.user_model_path(user)
# Try to load the models file and abort if the user does not have it yet # Try to load the models file and abort if the user does not have it yet
try: try:

View file

@ -6,6 +6,7 @@ import os
import json import json
import builtins import builtins
import paths import paths
import paths_factory
from i18n import _ from i18n import _
@ -27,7 +28,7 @@ if not os.path.exists(paths.user_models_dir):
sys.exit(1) sys.exit(1)
# Path to the models file # Path to the models file
enc_file = paths.user_models_dir / f"{user}.dat" enc_file = paths_factory.user_model_path(user)
# Try to load the models file and abort if the user does not have it yet # Try to load the models file and abort if the user does not have it yet
try: try:

View file

@ -6,11 +6,12 @@ import os
import builtins import builtins
import fileinput import fileinput
import paths import paths
import paths_factory
from i18n import _ from i18n import _
# Get the absolute filepath # Get the absolute filepath
config_path = paths.config_dir / "/config.ini" config_path = paths_factory.config_file_path()
# Check if enough arguments have been passed # Check if enough arguments have been passed
if len(builtins.howdy_args.arguments) < 2: if len(builtins.howdy_args.arguments) < 2:

View file

@ -6,13 +6,14 @@ import configparser
import datetime import datetime
import snapshot import snapshot
import paths import paths
import paths_factory
from recorders.video_capture import VideoCapture from recorders.video_capture import VideoCapture
from i18n import _ from i18n import _
# Read the config # Read the config
config = configparser.ConfigParser() config = configparser.ConfigParser()
config.read(paths.config_dir / "config.ini") config.read(paths_factory.config_file_path())
# Start video capture # Start video capture
video_capture = VideoCapture(config) video_capture = VideoCapture(config)

View file

@ -11,16 +11,14 @@ import dlib
import cv2 import cv2
import numpy as np import numpy as np
import paths import paths
import paths_factory
from i18n import _ from i18n import _
from recorders.video_capture import VideoCapture from recorders.video_capture import VideoCapture
# The absolute path to the config directory
path = "/etc/howdy"
# Read config from disk # Read config from disk
config = configparser.ConfigParser() config = configparser.ConfigParser()
config.read(paths.config_dir / "config.ini") config.read(paths_factory.config_file_path())
if config.get("video", "recording_plugin", fallback="opencv") != "opencv": if config.get("video", "recording_plugin", fallback="opencv") != "opencv":
print(_("Howdy has been configured to use a recorder which doesn't support the test command yet, aborting")) print(_("Howdy has been configured to use a recorder which doesn't support the test command yet, aborting"))
@ -60,20 +58,20 @@ use_cnn = config.getboolean('core', 'use_cnn', fallback=False)
if use_cnn: if use_cnn:
face_detector = dlib.cnn_face_detection_model_v1( face_detector = dlib.cnn_face_detection_model_v1(
paths.dlib_data_dir / "mmod_human_face_detector.dat" paths_factory.mmod_human_face_detector_path()
) )
else: else:
face_detector = dlib.get_frontal_face_detector() face_detector = dlib.get_frontal_face_detector()
pose_predictor = dlib.shape_predictor(paths.dlib_data_dir / "shape_predictor_5_face_landmarks.dat") pose_predictor = dlib.shape_predictor(paths_factory.shape_predictor_5_face_landmarks_path())
face_encoder = dlib.face_recognition_model_v1(paths.dlib_data_dir / "dlib_face_recognition_resnet_model_v1.dat") face_encoder = dlib.face_recognition_model_v1(paths_factory.dlib_face_recognition_resnet_model_v1_path())
encodings = [] encodings = []
models = None models = None
try: try:
user = builtins.howdy_user user = builtins.howdy_user
models = json.load(open(paths.user_models_dir / f"{user}.dat")) models = json.load(open(paths_factory.user_model_path(user)))
for model in models: for model in models:
encodings += model["data"] encodings += model["data"]

View file

@ -24,6 +24,7 @@ import snapshot
import numpy as np import numpy as np
import _thread as thread import _thread as thread
import paths import paths
import paths_factory
# Allow imports from the local howdy folder # Allow imports from the local howdy folder
sys.path.append('/lib/security/howdy') sys.path.append('/lib/security/howdy')
@ -49,7 +50,7 @@ def init_detector(lock):
global face_detector, pose_predictor, face_encoder global face_detector, pose_predictor, face_encoder
# Test if at lest 1 of the data files is there and abort if it's not # Test if at lest 1 of the data files is there and abort if it's not
if not os.path.isfile(paths.dlib_data_dir / "shape_predictor_5_face_landmarks.dat"): if not os.path.isfile(str(paths_factory.shape_predictor_5_face_landmarks_path())):
print(_("Data files have not been downloaded, please run the following commands:")) print(_("Data files have not been downloaded, please run the following commands:"))
print("\n\tcd " + paths.dlib_data_dir) print("\n\tcd " + paths.dlib_data_dir)
print("\tsudo ./install.sh\n") print("\tsudo ./install.sh\n")
@ -58,13 +59,13 @@ def init_detector(lock):
# Use the CNN detector if enabled # Use the CNN detector if enabled
if use_cnn: if use_cnn:
face_detector = dlib.cnn_face_detection_model_v1(paths.dlib_data_dir / "mmod_human_face_detector.dat") face_detector = dlib.cnn_face_detection_model_v1(str(paths_factory.mmod_human_face_detector_path()))
else: else:
face_detector = dlib.get_frontal_face_detector() face_detector = dlib.get_frontal_face_detector()
# Start the others regardless # Start the others regardless
pose_predictor = dlib.shape_predictor(paths.dlib_data_dir / "shape_predictor_5_face_landmarks.dat") pose_predictor = dlib.shape_predictor(str(paths_factory.shape_predictor_5_face_landmarks_path()))
face_encoder = dlib.face_recognition_model_v1(paths.dlib_data_dir / "dlib_face_recognition_resnet_model_v1.dat") face_encoder = dlib.face_recognition_model_v1(str(paths_factory.dlib_face_recognition_resnet_model_v1_path()))
# Note the time it took to initialize detectors # Note the time it took to initialize detectors
timings["ll"] = time.time() - timings["ll"] timings["ll"] = time.time() - timings["ll"]
@ -127,7 +128,7 @@ face_encoder = None
# Try to load the face model from the models folder # Try to load the face model from the models folder
try: try:
models = json.load(open(paths.user_models_dir / f"{user}.dat")) models = json.load(open(paths_factory.user_model_path(user)))
for model in models: for model in models:
encodings += model["data"] encodings += model["data"]
@ -140,7 +141,7 @@ if len(models) < 1:
# Read config from disk # Read config from disk
config = configparser.ConfigParser() config = configparser.ConfigParser()
config.read(paths.config_dir / "config.ini") config.read(paths_factory.config_file_path())
# Get all config values needed # Get all config values needed
use_cnn = config.getboolean("core", "use_cnn", fallback=False) use_cnn = config.getboolean("core", "use_cnn", fallback=False)

View file

@ -0,0 +1,36 @@
from pathlib import PurePath
import paths
models = [
"shape_predictor_5_face_landmarks.dat",
"mmod_human_face_detector.dat",
"dlib_face_recognition_resnet_model_v1.dat",
]
def shape_predictor_5_face_landmarks_path() -> PurePath:
return paths.dlib_data_dir / models[0]
def mmod_human_face_detector_path() -> PurePath:
return paths.dlib_data_dir / models[1]
def dlib_face_recognition_resnet_model_v1_path() -> PurePath:
return paths.dlib_data_dir / models[2]
def user_model_path(user: str) -> PurePath:
return paths.user_models_dir / f"{user}.dat"
def config_file_path() -> PurePath:
return paths.config_dir / "config.ini"
def snapshots_dir_path() -> PurePath:
return paths.log_path / "snapshots"
def snapshot_path(snapshot: str) -> PurePath:
return snapshots_dir_path() / snapshot

View file

@ -5,6 +5,7 @@ import cv2
import os import os
import datetime import datetime
import numpy as np import numpy as np
import paths_factory
def generate(frames, text_lines): def generate(frames, text_lines):
@ -50,15 +51,13 @@ def generate(frames, text_lines):
line_number += 1 line_number += 1
# Made sure a snapshot folder exist # Made sure a snapshot folder exist
if not os.path.exists(paths.log_path): if not os.path.exists(paths_factory.snapshots_dir_path()):
os.makedirs(paths.log_path) os.makedirs(paths_factory.snapshots_dir_path())
if not os.path.exists(paths.log_path / "snapshots"):
os.makedirs(paths.log_path / "snapshots")
# Generate a filename based on the current time # Generate a filename based on the current time
filename = datetime.datetime.utcnow().strftime("%Y%m%dT%H%M%S.jpg") filename = datetime.datetime.utcnow().strftime("%Y%m%dT%H%M%S.jpg")
# Write the image to that file # Write the image to that file
cv2.imwrite(paths.log_path / "snapshots" / filename, snap) cv2.imwrite(paths_factory.snapshot_path(filename), snap)
# Return the saved file location # Return the saved file location
return paths.log_path / "/snapshots/" / filename return paths_factory.snapshot_path(filename)