Code cleanup

This commit is contained in:
Joel Collins 2020-10-14 14:56:29 +00:00
parent 2bfb988460
commit 994e83dbeb
46 changed files with 261 additions and 318 deletions

View file

@ -1,8 +1,5 @@
# -*- coding: utf-8 -*-
import datetime
import logging
import os
import shutil
import threading
import time
from abc import ABCMeta, abstractmethod
@ -21,6 +18,7 @@ class BaseCamera(metaclass=ABCMeta):
self.lock = StrictLock(name="Camera", timeout=None)
self.frames_iterator = None
self.frame = None
self.last_access = 0
self.event = ClientEvent()
@ -34,13 +32,11 @@ class BaseCamera(metaclass=ABCMeta):
@abstractmethod
def configuration(self):
"""The current camera configuration."""
pass
@property
@abstractmethod
def state(self):
"""The current read-only camera state."""
pass
@property
def settings(self):
@ -132,7 +128,6 @@ class BaseCamera(metaclass=ABCMeta):
@abstractmethod
def frames(self):
"""Create generator that returns frames from the camera."""
pass
# WORKER THREAD

View file

@ -1,8 +1,5 @@
# -*- coding: utf-8 -*-
"""
"""
from __future__ import division
import io
@ -11,18 +8,13 @@ import time
from datetime import datetime
# Type hinting
from typing import Tuple
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from PIL import Image, ImageDraw
from openflexure_microscope.camera.base import BaseCamera
from openflexure_microscope.captures import CaptureObject
"""
PIL spams the logger with debug-level information. This is a pain when debugging api.app.
We override the logging settings in api.app by setting a level for PIL here.
"""
# PIL spams the logger with debug-level information. This is a pain when debugging api.app.
# We override the logging settings in api.app by setting a level for PIL here.
pil_logger = logging.getLogger("PIL")
pil_logger.setLevel(logging.INFO)
@ -79,7 +71,6 @@ class MissingCamera(BaseCamera):
def initialisation(self):
"""Run any initialisation code when the frame iterator starts."""
pass
def close(self):
"""Close the Raspberry Pi PiCameraStreamer."""
@ -134,7 +125,7 @@ class MissingCamera(BaseCamera):
"Cannot update camera config while recording is active."
)
def set_zoom(self, zoom_value: float = 1.0) -> None:
def set_zoom(self, *_) -> None:
"""
Change the camera zoom, handling re-centering and scaling.
"""
@ -142,7 +133,7 @@ class MissingCamera(BaseCamera):
# LAUNCH ACTIONS
def start_preview(self, fullscreen=True, window=None):
def start_preview(self, *_):
"""Start the on board GPU camera preview."""
logging.warning("GPU preview not implemented in mock camera")
@ -150,7 +141,7 @@ class MissingCamera(BaseCamera):
"""Stop the on board GPU camera preview."""
logging.warning("GPU preview not implemented in mock camera")
def start_recording(self, output, fmt: str = "h264", quality: int = 15):
def start_recording(self, *_):
"""Start recording.
Start a new video recording, writing to a output object.
@ -173,14 +164,7 @@ class MissingCamera(BaseCamera):
with self.lock:
logging.warning("Recording not implemented in mock camera")
def capture(
self,
output,
fmt: str = "jpeg",
use_video_port: bool = False,
resize: Tuple[int, int] = None,
bayer: bool = True,
):
def capture(self, output, *_):
"""
Capture a still image to a StreamObject.
@ -189,10 +173,6 @@ class MissingCamera(BaseCamera):
Args:
output: String or file-like object to write capture data to
use_video_port (bool): Capture from the video port used for streaming. Lower resolution, faster.
fmt (str): Format of the capture.
resize ((int, int)): Resize the captured image.
bayer (bool): Store raw bayer data in capture
"""
with self.lock:

View file

@ -30,7 +30,6 @@ from __future__ import division
import io
import logging
import os
import time
# Type hinting
@ -43,13 +42,8 @@ import picamerax
import picamerax.array
from openflexure_microscope.camera.base import BaseCamera
from openflexure_microscope.captures import CaptureObject
from openflexure_microscope.paths import settings_file_path
from openflexure_microscope.utilities import (
json_to_ndarray,
ndarray_to_json,
serialise_array_b64,
)
from openflexure_microscope.utilities import json_to_ndarray, ndarray_to_json
# Richard's fix gain
from .set_picamera_gain import set_analog_gain, set_digital_gain
@ -117,6 +111,7 @@ class PiCameraStreamer(BaseCamera):
) #: str: Path of .npy lens shading table file
# Start the stream worker on init
self.stream = None
self.start_worker()
@property
@ -131,7 +126,6 @@ class PiCameraStreamer(BaseCamera):
def initialisation(self):
"""Run any initialisation code when the frame iterator starts."""
pass
def close(self):
"""Close the Raspberry Pi PiCameraStreamer."""
@ -466,7 +460,7 @@ class PiCameraStreamer(BaseCamera):
# Reduce the resolution for video streaming
try:
self.camera._check_recording_stopped()
self.camera._check_recording_stopped() # pylint: disable=W0212
except picamerax.exc.PiCameraRuntimeError:
logging.info(
"Error while changing resolution: Recording already running."

View file

@ -39,7 +39,7 @@ def read_exif_from_file(filename):
head = data[2:6]
HEAD_LENGTH = 4
exif = None
while 1:
while len(head) == HEAD_LENGTH:
length = struct.unpack(">H", head[2:4])[0]
if head[:2] == b"\xff\xe1":

View file

@ -2,8 +2,8 @@ import copy
import numbers
import struct
from ._common import *
from ._exif import *
from ._common import split_into_segments
from ._exif import ExifIFD, ImageIFD, TAGS, TYPES
TIFF_HEADER_LENGTH = 8
@ -243,11 +243,11 @@ def _value_to_bytes(raw_value, value_type, offset):
elif value_type == TYPES.Ascii:
try:
new_value = raw_value.encode("latin1") + b"\x00"
except:
except: # pylint: disable=W0702
try:
new_value = raw_value + b"\x00"
except TypeError:
raise ValueError("Got invalid type to convert.")
except TypeError as e:
raise ValueError("Got invalid type to convert.") from e
length = len(new_value)
if length > 4:
value_str = struct.pack(">I", offset)
@ -262,7 +262,7 @@ def _value_to_bytes(raw_value, value_type, offset):
elif isinstance(raw_value[0], tuple):
length = len(raw_value)
new_value = b""
for n, val in enumerate(raw_value):
for _, val in enumerate(raw_value):
num, den = val
new_value += struct.pack(">L", num) + struct.pack(">L", den)
value_str = struct.pack(">I", offset)
@ -275,7 +275,7 @@ def _value_to_bytes(raw_value, value_type, offset):
elif isinstance(raw_value[0], tuple):
length = len(raw_value)
new_value = b""
for n, val in enumerate(raw_value):
for _, val in enumerate(raw_value):
num, den = val
new_value += struct.pack(">l", num) + struct.pack(">l", den)
value_str = struct.pack(">I", offset)
@ -286,13 +286,13 @@ def _value_to_bytes(raw_value, value_type, offset):
value_str = struct.pack(">I", offset)
try:
four_bytes_over = b"" + raw_value
except TypeError:
raise ValueError("Got invalid type to convert.")
except TypeError as e:
raise ValueError("Got invalid type to convert.") from e
else:
try:
value_str = raw_value + b"\x00" * (4 - length)
except TypeError:
raise ValueError("Got invalid type to convert.")
except TypeError as e:
raise ValueError("Got invalid type to convert.") from e
elif value_type == TYPES.SByte: # Signed Byte
length = len(raw_value)
if length <= 4:
@ -333,7 +333,7 @@ def _dict_to_bytes(ifd_dict, ifd, ifd_offset):
entries = b""
values = b""
for n, key in enumerate(sorted(ifd_dict)):
for _, key in enumerate(sorted(ifd_dict)):
if (ifd == "0th") and (key in (ImageIFD.ExifTag, ImageIFD.GPSTag)):
continue
elif (ifd == "Exif") and (key == ExifIFD.InteroperabilityTag):
@ -358,11 +358,11 @@ def _dict_to_bytes(ifd_dict, ifd, ifd_offset):
length_str, value_str, four_bytes_over = _value_to_bytes(
raw_value, value_type, offset
)
except ValueError:
except ValueError as e:
raise ValueError(
'"dump" got wrong type of exif value.\n'
+ "{0} in {1} IFD. Got as {2}.".format(key, ifd, type(ifd_dict[key]))
)
) from e
entries += key_str + type_str + length_str + value_str
values += four_bytes_over

View file

@ -3,7 +3,7 @@ import struct
import sys
from . import _webp
from ._common import *
from ._common import merge_segments, split_into_segments
from ._exceptions import InvalidImageDataError

View file

@ -2,9 +2,9 @@ import struct
import sys
from . import _webp
from ._common import *
from ._common import get_exif_seg, read_exif_from_file, split_into_segments
from ._exceptions import InvalidImageDataError
from ._exif import *
from ._exif import ExifIFD, ImageIFD, TAGS, TYPES
LITTLE_ENDIAN = b"\x49\x49"
@ -109,6 +109,8 @@ class _ExifReader(object):
else:
raise InvalidImageDataError("Given file is neither JPEG nor TIFF.")
self.endian_mark = None
def get_ifd_dict(self, pointer, ifd_name, read_unknown=False):
ifd_dict = {}
tag_count = struct.unpack(

View file

@ -1,7 +1,7 @@
import io
from . import _webp
from ._common import *
from ._common import get_exif_seg, split_into_segments
def remove(src, new_file=None):
@ -42,7 +42,7 @@ def remove(src, new_file=None):
new_data = src_data
except Exception as e:
print(e)
raise ValueError("Error occurred.")
raise ValueError("Error occurred.") from e
if isinstance(new_file, io.BytesIO):
new_file.write(new_data)

View file

@ -1,6 +1,6 @@
import io
from ._common import *
from ._common import get_exif_seg, merge_segments, split_into_segments
def transplant(exif_src, image, new_file=None):

View file

@ -204,8 +204,6 @@ def get_exif(data):
CHUNK_FOURCC_LENGTH = 4
LENGTH_BYTES_LENGTH = 4
chunks = []
exif = b""
while pointer < file_size:
fourcc = data[pointer : pointer + CHUNK_FOURCC_LENGTH]
pointer += CHUNK_FOURCC_LENGTH

View file

@ -46,8 +46,8 @@ class UserComment:
cls._JIS_PREFIX: cls._JIS,
cls._UNICODE_PREFIX: cls._UNICODE,
}[prefix]
except KeyError:
raise ValueError("unable to determine appropriate encoding")
except KeyError as e:
raise ValueError("unable to determine appropriate encoding") from e
return body.decode(encoding, errors="replace")
@classmethod

View file

@ -4,7 +4,7 @@ import logging
import time
import picamerax
from picamerax import exc, mmal, mmalobj
from picamerax import exc, mmal
from picamerax.mmalobj import to_rational
MMAL_PARAMETER_ANALOG_GAIN = mmal.MMAL_PARAMETER_GROUP_CAMERA + 0x59
@ -21,7 +21,7 @@ def set_gain(camera, gain, value):
if gain not in [MMAL_PARAMETER_ANALOG_GAIN, MMAL_PARAMETER_DIGITAL_GAIN]:
raise ValueError("The gain parameter was not valid")
ret = mmal.mmal_port_parameter_set_rational(
camera._camera.control._port, gain, to_rational(value)
camera._camera.control._port, gain, to_rational(value) # pylint: disable=W0212
)
if ret == 4:
raise exc.PiCameraMMALError(