Went on a PEP-8 rampage

This commit is contained in:
Joel Collins 2019-01-31 17:20:46 +00:00
parent f99ad30fb6
commit 0948c9308a
36 changed files with 186 additions and 218 deletions

View file

@ -1,9 +1,7 @@
# -*- coding: utf-8 -*-
import time
import io
import os
import threading
from PIL import Image
import datetime
import yaml
import logging
@ -35,6 +33,18 @@ def generate_basename():
return datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
def generate_numbered_basename(obj_list: list) -> str:
initial_basename = generate_basename()
basename = initial_basename
# Handle clashing
iterator = 1
while basename in [obj.basename for obj in obj_list]:
basename = initial_basename + "_{}".format(iterator)
iterator += 1
return basename
class CameraEvent(object):
"""
A frame-signaller object used by any instances or subclasses of BaseCamera.
@ -79,18 +89,6 @@ class CameraEvent(object):
self.events[get_ident()][0].clear()
def generate_basename(obj_list: list) -> str:
initial_basename = generate_basename()
basename = initial_basename
# Handle clashing
iterator = 1
while basename in [obj.basename for obj in obj_list]:
basename = initial_basename + "_{}".format(iterator)
iterator += 1
return basename
class BaseCamera(object):
"""
Base implementation of StreamingCamera.
@ -155,7 +153,7 @@ class BaseCamera(object):
# START AND STOP WORKER THREAD
def start_worker(self, timeout: int=5) -> bool:
def start_worker(self, timeout: int = 5) -> bool:
"""Start the background camera thread if it isn't running yet."""
timeout_time = time.time() + timeout
@ -176,7 +174,7 @@ class BaseCamera(object):
time.sleep(0)
return True
def stop_worker(self, timeout: int=5) -> bool:
def stop_worker(self, timeout: int = 5) -> bool:
"""Flag worker thread for stop. Waits for thread close or timeout."""
logging.debug("Stopping worker thread")
timeout_time = time.time() + timeout
@ -217,13 +215,13 @@ class BaseCamera(object):
"""Return the latest recorded video."""
return last_entry(self.videos)
def image_from_id(self, id):
def image_from_id(self, image_id):
"""Return an image StreamObject with a matching ID."""
return entry_by_id(id, self.images)
return entry_by_id(image_id, self.images)
def video_from_id(self, id):
def video_from_id(self, video_id):
"""Return a video StreamObject with a matching ID."""
return entry_by_id(id, self.videos)
return entry_by_id(video_id, self.videos)
# MANAGE CAPTURE DATABASE
@ -277,25 +275,24 @@ class BaseCamera(object):
def new_image(
self,
write_to_file: bool=False,
temporary: bool=True,
filename: str=None,
fmt: str='jpeg',
shunt_others: bool=True):
write_to_file: bool = False,
temporary: bool = True,
filename: str = None,
fmt: str = 'jpeg'):
"""
Create a new image capture object. Adds to the image list, and shunt all others.
Args:
write_to_file (bool): Should the StreamObject write to a file, or an in-memory byte stream.
keep_on_disk (bool): Should the data be deleted after session ends. Creating the capture with a content manager sets this to true.
temporary (bool): Should the data be deleted after session ends. Creating the capture with a content manager sets this to true.
filename (str): Name of the stored file. Defaults to timestamp.
fmt (str): Format of the capture.
"""
# Generate file name
if not filename:
filename = generate_basename(self.images)
filename = generate_numbered_basename(self.images)
logging.debug(filename)
# Create capture object
@ -317,11 +314,10 @@ class BaseCamera(object):
def new_video(
self,
write_to_file: bool=True,
temporary: bool=False,
filename: str=None,
fmt: str='h264',
shunt_others: bool=True):
write_to_file: bool = True,
temporary: bool = False,
filename: str = None,
fmt: str = 'h264'):
"""
Create a new video capture object. Adds to the image list, and shunt all others.
@ -335,7 +331,7 @@ class BaseCamera(object):
# Generate file name
if not filename:
filename = generate_basename(self.videos)
filename = generate_numbered_basename(self.videos)
logging.debug(filename)
# Create capture object

View file

@ -15,6 +15,7 @@ thumbnail_size = (60, 60)
BASE_CAPTURE_PATH = os.path.join(os.path.expanduser('~'), 'micrographs')
TEMP_CAPTURE_PATH = os.path.join(BASE_CAPTURE_PATH, 'tmp')
def clear_tmp():
global TEMP_CAPTURE_PATH
@ -24,6 +25,7 @@ def clear_tmp():
os.remove(f)
logging.debug("Removed {}".format(f))
def capture_from_dict(capture_dict):
capture = CaptureObject(create_metadata_file=False) # Create a placeholder capture
@ -48,14 +50,15 @@ class CaptureObject(object):
Note: Captures cannot be stored in a lower-level directory than BASE_CAPTURE_PATH.
"""
def __init__(
self,
write_to_file: bool=False,
temporary: bool=False,
filename: str='',
folder: str='',
fmt: str='',
create_metadata_file: bool=True) -> None:
write_to_file: bool = False,
temporary: bool = False,
filename: str = '',
folder: str = '',
fmt: str = '',
create_metadata_file: bool = True) -> None:
"""Create a new StreamObject, to manage capture data."""
# Store a nice ID
@ -102,7 +105,9 @@ class CaptureObject(object):
def __enter__(self):
"""Create StreamObject in context, to auto-clean disk data."""
logging.debug("Entering context for {}. Stored files will be cleaned up automatically regardless of location.".format(self.id))
logging.debug(
"Entering context for {}. Stored files will be cleaned up automatically regardless of location.".format(
self.id))
self.temporary = True # Flag file to be removed on close.
self.context_manager = True # Used in metadata
@ -129,7 +134,7 @@ class CaptureObject(object):
else:
logging.debug("Target for {} set to 'file'".format(self.id))
self.stream = self.file
# Save initial metadata file
if create_metadata_file:
self.save_metadata()
@ -170,7 +175,8 @@ class CaptureObject(object):
def split_file_path(self, filepath):
"""Takes a full file path, and splits it into separated class properties."""
self.filefolder, self.filename = os.path.split(filepath) # Split the full file path into a folder and a filename
self.filefolder, self.filename = os.path.split(
filepath) # Split the full file path into a folder and a filename
self.basename = os.path.splitext(self.filename)[0] # Split the filename out from it's file extension
self.metadataname = "{}.yaml".format(self.basename)
@ -234,18 +240,10 @@ class CaptureObject(object):
@property
def metadata(self) -> dict:
# Create basic metadata dictionary
d = {
'id': self.id,
'filename': self.filename,
'path': self.file,
'time': self.timestring,
'format': self.format,
'tags': self.tags
}
d = {'id': self.id, 'filename': self.filename, 'path': self.file, 'time': self.timestring,
'format': self.format, 'tags': self.tags, 'custom': self._metadata}
# Add custom metadata to dictionary
d['custom'] = self._metadata
return d
@property
@ -261,14 +259,10 @@ class CaptureObject(object):
"""Return dictionary of StreamObject properties."""
# Create basic state dictionary
d = {
'locked': self.locked,
'temporary': self.temporary,
}
d = {'locked': self.locked, 'temporary': self.temporary, 'metadata': self.metadata,
'metadata_path': self.metadata_file}
# Add metadata to state
d['metadata'] = self.metadata
d['metadata_path'] = self.metadata_file
# Check bytestream
if self.stream_exists:
@ -404,4 +398,5 @@ class CaptureObject(object):
if self.temporary:
self.delete()
atexit.register(clear_tmp)
atexit.register(clear_tmp)