Formatting fixes

This commit is contained in:
boltgolt 2018-12-13 20:53:18 +01:00
parent f8cfde6f72
commit f4db5ee94b
No known key found for this signature in database
GPG key ID: BECEC9937E1AAE26
9 changed files with 38 additions and 31 deletions

View file

@ -27,37 +27,37 @@ if user == "root" or user is None:
# Basic command setup # Basic command setup
parser = argparse.ArgumentParser(description="Command line interface for Howdy face authentication.", parser = argparse.ArgumentParser(description="Command line interface for Howdy face authentication.",
formatter_class=argparse.RawDescriptionHelpFormatter, formatter_class=argparse.RawDescriptionHelpFormatter,
add_help=False, add_help=False,
prog="howdy", prog="howdy",
epilog="For support please visit\nhttps://github.com/boltgolt/howdy") epilog="For support please visit\nhttps://github.com/boltgolt/howdy")
# Add an argument for the command # Add an argument for the command
parser.add_argument("command", parser.add_argument("command",
help="The command option to execute, can be one of the following: add, clear, config, disable, list, remove or test.", help="The command option to execute, can be one of the following: add, clear, config, disable, list, remove or test.",
metavar="command", metavar="command",
choices=["add", "clear", "config", "disable", "list", "remove", "test"]) choices=["add", "clear", "config", "disable", "list", "remove", "test"])
# Add an argument for the extra arguments of diable and remove # Add an argument for the extra arguments of diable and remove
parser.add_argument("argument", parser.add_argument("argument",
help="Either 0 (enable) or 1 (disable) for the disable command, or the model ID for the remove command.", help="Either 0 (enable) or 1 (disable) for the disable command, or the model ID for the remove command.",
nargs="?") nargs="?")
# Add the user flag # Add the user flag
parser.add_argument("-U", "--user", parser.add_argument("-U", "--user",
default=user, default=user,
help="Set the user account to use.") help="Set the user account to use.")
# Add the -y flag # Add the -y flag
parser.add_argument("-y", parser.add_argument("-y",
help="Skip all questions.", help="Skip all questions.",
action="store_true") action="store_true")
# Overwrite the default help message so we can use a uppercase S # Overwrite the default help message so we can use a uppercase S
parser.add_argument("-h", "--help", parser.add_argument("-h", "--help",
action="help", action="help",
default=argparse.SUPPRESS, default=argparse.SUPPRESS,
help="Show this help message and exit.") help="Show this help message and exit.")
# If we only have 1 argument we print the help text # If we only have 1 argument we print the help text
if len(sys.argv) < 2: if len(sys.argv) < 2:

View file

@ -17,4 +17,4 @@ elif "EDITOR" in os.environ:
editor = os.environ["EDITOR"] editor = os.environ["EDITOR"]
# Open the editor as a subprocess and fork it # Open the editor as a subprocess and fork it
subprocess.call([editor, os.path.dirname(os.path.realpath(__file__)) + "/../config.ini"]) subprocess.call([editor, os.path.dirname(os.path.realpath(__file__)) + "/../config.ini"])

View file

@ -16,7 +16,7 @@ config = configparser.ConfigParser()
config.read(config_path) config.read(config_path)
# Check if enough arguments have been passed # Check if enough arguments have been passed
if builtins.howdy_args.argument == None: if builtins.howdy_args.argument is None:
print("Please add a 0 (enable) or a 1 (disable) as an argument") print("Please add a 0 (enable) or a 1 (disable) as an argument")
sys.exit(1) sys.exit(1)

View file

@ -8,7 +8,7 @@ import time
import builtins import builtins
# Get the absolute path and the username # Get the absolute path and the username
path = os.path.dirname(os.path.realpath(__file__)) + "/.." path = os.path.dirname(os.path.realpath(__file__)) + "/.."
user = builtins.howdy_user user = builtins.howdy_user
# Check if the models file has been created yet # Check if the models file has been created yet

View file

@ -7,11 +7,11 @@ import json
import builtins import builtins
# Get the absolute path and the username # Get the absolute path and the username
path = os.path.dirname(os.path.realpath(__file__)) + "/.." path = os.path.dirname(os.path.realpath(__file__)) + "/.."
user = builtins.howdy_user user = builtins.howdy_user
# Check if enough arguments have been passed # Check if enough arguments have been passed
if builtins.howdy_args.argument == None: if builtins.howdy_args.argument is None:
print("Please add the ID of the model you want to remove as an argument") print("Please add the ID of the model you want to remove as an argument")
print("You can find the IDs by running:") print("You can find the IDs by running:")
print("\n\thowdy list\n") print("\n\thowdy list\n")

View file

@ -45,6 +45,7 @@ Press ctrl+C in this terminal to quit
Click on the image to enable or disable slow mode Click on the image to enable or disable slow mode
""") """)
def mouse(event, x, y, flags, param): def mouse(event, x, y, flags, param):
"""Handle mouse events""" """Handle mouse events"""
global slow_mode global slow_mode
@ -53,10 +54,12 @@ def mouse(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN: if event == cv2.EVENT_LBUTTONDOWN:
slow_mode = not slow_mode slow_mode = not slow_mode
def print_text(line_number, text): def print_text(line_number, text):
"""Print the status text by line number""" """Print the status text by line number"""
cv2.putText(overlay, text, (10, height - 10 - (10 * line_number)), cv2.FONT_HERSHEY_SIMPLEX, .3, (0, 255, 0), 0, cv2.LINE_AA) cv2.putText(overlay, text, (10, height - 10 - (10 * line_number)), cv2.FONT_HERSHEY_SIMPLEX, .3, (0, 255, 0), 0, cv2.LINE_AA)
# Open the window and attach a a mouse listener # Open the window and attach a a mouse listener
cv2.namedWindow("Howdy Test") cv2.namedWindow("Howdy Test")
cv2.setMouseCallback("Howdy Test", mouse) cv2.setMouseCallback("Howdy Test", mouse)
@ -90,7 +93,6 @@ try:
sec = int(time.time()) sec = int(time.time())
sec_frames = 0 sec_frames = 0
# Grab a single frame of video # Grab a single frame of video
ret, frame = (video_capture.read()) ret, frame = (video_capture.read())
# Make a frame to put overlays in # Make a frame to put overlays in

View file

@ -18,11 +18,13 @@ import configparser
config = configparser.ConfigParser() config = configparser.ConfigParser()
config.read(os.path.dirname(os.path.abspath(__file__)) + "/config.ini") config.read(os.path.dirname(os.path.abspath(__file__)) + "/config.ini")
def stop(status): def stop(status):
"""Stop the execution and close video stream""" """Stop the execution and close video stream"""
video_capture.release() video_capture.release()
sys.exit(status) sys.exit(status)
# Make sure we were given an username to tast against # Make sure we were given an username to tast against
try: try:
if not isinstance(sys.argv[1], str): if not isinstance(sys.argv[1], str):
@ -182,7 +184,7 @@ while True:
print("Certainty of winning frame: %.3f" % (match * 10, )) print("Certainty of winning frame: %.3f" % (match * 10, ))
# Catch older 3-encoding models # Catch older 3-encoding models
if not match_index in models: if match_index not in models:
match_index = 0 match_index = 0
print("Winning model: %d (\"%s\")" % (match_index, models[match_index]["label"])) print("Winning model: %d (\"%s\")" % (match_index, models[match_index]["label"]))

View file

@ -7,7 +7,6 @@ import re
from subprocess import Popen, PIPE from subprocess import Popen, PIPE
from cv2 import CAP_PROP_FRAME_WIDTH from cv2 import CAP_PROP_FRAME_WIDTH
from cv2 import CAP_PROP_FRAME_HEIGHT from cv2 import CAP_PROP_FRAME_HEIGHT
from cv2 import CAP_PROP_FOURCC
try: try:
import ffmpeg import ffmpeg
@ -16,6 +15,7 @@ except ImportError:
print(" pip3 install ffmpeg-python\n") print(" pip3 install ffmpeg-python\n")
sys.exit(12) sys.exit(12)
class ffmpeg_reader: class ffmpeg_reader:
""" This class was created to look as similar to the openCV features used in Howdy as possible for overall code cleanliness. """ """ This class was created to look as similar to the openCV features used in Howdy as possible for overall code cleanliness. """
@ -54,16 +54,16 @@ class ffmpeg_reader:
return_code = process.poll() return_code = process.poll()
# Worst case scenario, err will equal en empty byte string, b'', so probe will get set to [] here. # Worst case scenario, err will equal en empty byte string, b'', so probe will get set to [] here.
regex = re.compile('\s\d{3,4}x\d{3,4}') regex = re.compile(r"\s\d{3,4}x\d{3,4}")
probe = regex.findall(str(err.decode("utf-8"))) probe = regex.findall(str(err.decode("utf-8")))
if not return_code == 1 or len(probe) < 1: if not return_code == 1 or len(probe) < 1:
# Could not determine the resolution from ffmpeg call. Reverting to ffmpeg.probe() # Could not determine the resolution from ffmpeg call. Reverting to ffmpeg.probe()
probe = ffmpeg.probe(self.device_path) probe = ffmpeg.probe(self.device_path)
height = probe['streams'][0]['height'] height = probe["streams"][0]["height"]
width = probe['streams'][0]['width'] width = probe["streams"][0]["width"]
else: else:
(height, width) = [x.strip() for x in probe[0].split('x')] (height, width) = [x.strip() for x in probe[0].split("x")]
# Set height and width from probe if they haven't been set already # Set height and width from probe if they haven't been set already
if height.isdigit() and self.get(CAP_PROP_FRAME_HEIGHT) == 0: if height.isdigit() and self.get(CAP_PROP_FRAME_HEIGHT) == 0:
@ -71,7 +71,6 @@ class ffmpeg_reader:
if width.isdigit() and self.get(CAP_PROP_FRAME_WIDTH) == 0: if width.isdigit() and self.get(CAP_PROP_FRAME_WIDTH) == 0:
self.set(CAP_PROP_FRAME_WIDTH, int(width)) self.set(CAP_PROP_FRAME_WIDTH, int(width))
def record(self, numframes): def record(self, numframes):
""" Record a video, saving it to self.video array for processing later """ """ Record a video, saving it to self.video array for processing later """
@ -86,7 +85,7 @@ class ffmpeg_reader:
stream, ret = ( stream, ret = (
ffmpeg ffmpeg
.input(self.device_path, format=self.device_format) .input(self.device_path, format=self.device_format)
.output('pipe:', format='rawvideo', pix_fmt='rgb24', vframes=numframes) .output("pipe:", format="rawvideo", pix_fmt="rgb24", vframes=numframes)
.run(capture_stdout=True, quiet=True) .run(capture_stdout=True, quiet=True)
) )
self.video = ( self.video = (
@ -95,7 +94,6 @@ class ffmpeg_reader:
.reshape([-1, self.width, self.height, 3]) .reshape([-1, self.width, self.height, 3])
) )
def read(self): def read(self):
""" Read a sigle frame from the self.video array. Will record a video if array is empty. """ """ Read a sigle frame from the self.video array. Will record a video if array is empty. """

View file

@ -12,6 +12,7 @@ import ConfigParser
config = ConfigParser.ConfigParser() config = ConfigParser.ConfigParser()
config.read(os.path.dirname(os.path.abspath(__file__)) + "/config.ini") config.read(os.path.dirname(os.path.abspath(__file__)) + "/config.ini")
def doAuth(pamh): def doAuth(pamh):
"""Starts authentication in a seperate process""" """Starts authentication in a seperate process"""
@ -56,18 +57,22 @@ def doAuth(pamh):
pamh.conversation(pamh.Message(pamh.PAM_ERROR_MSG, "Unknown error: " + str(status))) pamh.conversation(pamh.Message(pamh.PAM_ERROR_MSG, "Unknown error: " + str(status)))
return pamh.PAM_SYSTEM_ERR return pamh.PAM_SYSTEM_ERR
def pam_sm_authenticate(pamh, flags, args): def pam_sm_authenticate(pamh, flags, args):
"""Called by PAM when the user wants to authenticate, in sudo for example""" """Called by PAM when the user wants to authenticate, in sudo for example"""
return doAuth(pamh) return doAuth(pamh)
def pam_sm_open_session(pamh, flags, args): def pam_sm_open_session(pamh, flags, args):
"""Called when starting a session, such as su""" """Called when starting a session, such as su"""
return doAuth(pamh) return doAuth(pamh)
def pam_sm_close_session(pamh, flags, argv): def pam_sm_close_session(pamh, flags, argv):
"""We don't need to clean anyting up at the end of a session, so returns true""" """We don't need to clean anyting up at the end of a session, so returns true"""
return pamh.PAM_SUCCESS return pamh.PAM_SUCCESS
def pam_sm_setcred(pamh, flags, argv): def pam_sm_setcred(pamh, flags, argv):
"""We don't need set any credentials, so returns true""" """We don't need set any credentials, so returns true"""
return pamh.PAM_SUCCESS return pamh.PAM_SUCCESS