From 7bc4c514a63baf3c38746562311952f0dbe69378 Mon Sep 17 00:00:00 2001 From: Julian Stirling Date: Tue, 2 Dec 2025 16:26:15 +0000 Subject: [PATCH] Autofix import order --- change_log_helper.py | 3 +- check_version_sync.py | 2 +- .../picamera2/cam_test_utils/__init__.py | 2 +- .../picamera2/test_acquisition.py | 2 +- .../picamera2/test_calibration.py | 2 +- .../picamera2/test_exposure_time_drift.py | 11 +++---- .../picamera2/test_tuning.py | 1 - integration-tests/testfile.py | 4 +-- picamera_tests.py | 8 ++--- pull_webapp.py | 7 ++-- .../background_detect.py | 6 ++-- src/openflexure_microscope_server/logging.py | 4 +-- .../scan_directories.py | 15 ++++----- .../scan_planners.py | 2 +- .../server/__init__.py | 14 ++++---- .../server/legacy_api.py | 6 ++-- .../server/serve_static_files.py | 2 +- .../stitching.py | 10 +++--- .../things/autofocus.py | 12 +++---- .../things/camera/__init__.py | 23 ++++++------- .../things/camera/opencv.py | 4 +-- .../things/camera/picamera.py | 17 +++++----- .../camera/picamera_recalibrate_utils.py | 9 +++--- .../camera/picamera_tuning_file_utils.py | 9 +++--- .../things/camera/simulation.py | 13 ++++---- .../things/camera_stage_mapping.py | 12 +++---- .../things/smart_scan.py | 30 ++++++++--------- .../things/stage/__init__.py | 5 +-- .../things/stage/dummy.py | 6 ++-- .../things/stage/sangaboard.py | 12 ++++--- .../things/stage_measure.py | 6 ++-- .../things/system.py | 12 +++---- src/openflexure_microscope_server/ui.py | 2 +- .../utilities.py | 32 +++++++++---------- tests/mock_things/mock_camera.py | 3 +- tests/test_autofocus.py | 2 +- tests/test_background_detectors.py | 14 ++++---- tests/test_camera.py | 2 +- tests/test_camera_buffer.py | 3 +- tests/test_cameras.py | 2 +- tests/test_config_utilities.py | 5 +-- tests/test_dummy_server.py | 8 ++--- tests/test_legacy_api.py | 2 +- tests/test_logging.py | 6 ++-- tests/test_picamera_tuning_files.py | 3 +- tests/test_sangaboard.py | 4 +-- tests/test_scan_data.py | 4 +-- tests/test_scan_directories.py | 20 ++++++------ tests/test_scan_planners.py | 4 ++- tests/test_serve_static_files.py | 2 +- tests/test_server_config.py | 2 +- tests/test_smart_scan.py | 22 ++++++------- tests/test_stack.py | 25 ++++++++------- tests/test_stage.py | 8 ++--- tests/test_stage_measure.py | 6 ++-- tests/test_stitching.py | 10 +++--- tests/test_version_strings.py | 8 ++--- tests/utilities/__init__.py | 2 +- tests/utilities/scan_test_helpers.py | 8 ++--- 59 files changed, 244 insertions(+), 236 deletions(-) diff --git a/change_log_helper.py b/change_log_helper.py index 5caaac6a..6d921b7d 100755 --- a/change_log_helper.py +++ b/change_log_helper.py @@ -2,11 +2,10 @@ """Create a list of the MRs into v3 (unless specified) since the last release.""" -import sys import argparse +import sys import gitlab - from gitlab.exceptions import GitlabGetError PROJECT_ID = 9238334 diff --git a/check_version_sync.py b/check_version_sync.py index 40a4628e..15ff5f51 100755 --- a/check_version_sync.py +++ b/check_version_sync.py @@ -2,8 +2,8 @@ """Check that the npm version string matches the Python version string exactly.""" import json -import tomllib import os +import tomllib with open("pyproject.toml", "rb") as toml_f: pyproject_data = tomllib.load(toml_f) diff --git a/hardware-specific-tests/picamera2/cam_test_utils/__init__.py b/hardware-specific-tests/picamera2/cam_test_utils/__init__.py index 32019040..145510f1 100644 --- a/hardware-specific-tests/picamera2/cam_test_utils/__init__.py +++ b/hardware-specific-tests/picamera2/cam_test_utils/__init__.py @@ -1,8 +1,8 @@ """Utilities to help with testing the camera.""" -from typing import Optional import tempfile from contextlib import contextmanager +from typing import Optional from fastapi.testclient import TestClient diff --git a/hardware-specific-tests/picamera2/test_acquisition.py b/hardware-specific-tests/picamera2/test_acquisition.py index 7c8bd8cf..1d8ba1a9 100644 --- a/hardware-specific-tests/picamera2/test_acquisition.py +++ b/hardware-specific-tests/picamera2/test_acquisition.py @@ -1,7 +1,7 @@ """Test data collection from the Raspberry Picamera.""" -from PIL import Image import numpy as np +from PIL import Image def test_jpeg_and_array(picamera_client): diff --git a/hardware-specific-tests/picamera2/test_calibration.py b/hardware-specific-tests/picamera2/test_calibration.py index eb0d127b..22d55cae 100644 --- a/hardware-specific-tests/picamera2/test_calibration.py +++ b/hardware-specific-tests/picamera2/test_calibration.py @@ -1,7 +1,7 @@ """Test data collection from the Raspberry Picamera.""" -from copy import deepcopy import tempfile +from copy import deepcopy from .cam_test_utils import camera_test_client diff --git a/hardware-specific-tests/picamera2/test_exposure_time_drift.py b/hardware-specific-tests/picamera2/test_exposure_time_drift.py index 792aa861..1b2f4eff 100644 --- a/hardware-specific-tests/picamera2/test_exposure_time_drift.py +++ b/hardware-specific-tests/picamera2/test_exposure_time_drift.py @@ -4,13 +4,12 @@ This can get very tedious. Recommend running pytest with -s option to monitor progress. """ -from typing import Any -import logging -import time -import tempfile -import os import json - +import logging +import os +import tempfile +import time +from typing import Any from .cam_test_utils import camera_test_client diff --git a/hardware-specific-tests/picamera2/test_tuning.py b/hardware-specific-tests/picamera2/test_tuning.py index 6d58d8e6..4e6c25a3 100644 --- a/hardware-specific-tests/picamera2/test_tuning.py +++ b/hardware-specific-tests/picamera2/test_tuning.py @@ -10,7 +10,6 @@ from openflexure_microscope_server.things.camera import ( picamera_tuning_file_utils as tf_utils, ) - MODEL = Picamera2.global_camera_info()[0]["Model"] diff --git a/integration-tests/testfile.py b/integration-tests/testfile.py index f9e43361..a9b37264 100755 --- a/integration-tests/testfile.py +++ b/integration-tests/testfile.py @@ -7,11 +7,11 @@ For now, this file should be run directly rather than through a test framework. They are designed to run on CI and should work on Linux or WSL for local debugging. """ -from typing import Optional -import subprocess import os import shutil +import subprocess from time import sleep, time +from typing import Optional from PIL import Image diff --git a/picamera_tests.py b/picamera_tests.py index 892491eb..29097b60 100755 --- a/picamera_tests.py +++ b/picamera_tests.py @@ -1,12 +1,12 @@ #! /usr/bin/env python3 """Run the Piamera tests and archive the results in the git repository.""" -import subprocess -import shutil -import os -import posixpath import argparse import json +import os +import posixpath +import shutil +import subprocess import sys import zipfile diff --git a/pull_webapp.py b/pull_webapp.py index 4c8db77a..52425f06 100755 --- a/pull_webapp.py +++ b/pull_webapp.py @@ -10,15 +10,14 @@ If the static directory already exists and contains data, it will be removed bef extraction. """ -import zipfile +import argparse import io -import sys import os import shutil -import argparse +import sys +import zipfile import gitlab - from gitlab.exceptions import GitlabGetError THIS_DIR = os.path.dirname(os.path.abspath(__file__)) diff --git a/src/openflexure_microscope_server/background_detect.py b/src/openflexure_microscope_server/background_detect.py index 9bd056dc..f42bba95 100644 --- a/src/openflexure_microscope_server/background_detect.py +++ b/src/openflexure_microscope_server/background_detect.py @@ -5,11 +5,13 @@ for analysis. Information from these images is used to detect whether an image f current camera field of view contains sample. """ -from typing import Optional, Any +from typing import Any, Optional + import cv2 import numpy as np -from pydantic import BaseModel, Field, ConfigDict +from pydantic import BaseModel, ConfigDict, Field from pydantic.errors import PydanticUserError + from labthings_fastapi.thing_description import type_to_dataschema diff --git a/src/openflexure_microscope_server/logging.py b/src/openflexure_microscope_server/logging.py index ff4f8de7..5007c8f8 100644 --- a/src/openflexure_microscope_server/logging.py +++ b/src/openflexure_microscope_server/logging.py @@ -12,11 +12,11 @@ output to STDOUT/STDERR are captured by ``systemd``. These can be viewed by usin """ import logging -from logging.handlers import RotatingFileHandler import os +from logging.handlers import RotatingFileHandler -from fastapi.responses import PlainTextResponse from fastapi import HTTPException +from fastapi.responses import PlainTextResponse LOGGER = logging.getLogger(__name__) OFM_LOG_FILE = None diff --git a/src/openflexure_microscope_server/scan_directories.py b/src/openflexure_microscope_server/scan_directories.py index a8850afb..8c0c4a5f 100644 --- a/src/openflexure_microscope_server/scan_directories.py +++ b/src/openflexure_microscope_server/scan_directories.py @@ -1,25 +1,24 @@ """Functionality to manage file system operations for scan directories.""" -from typing import Optional, Any, Mapping +import json +import logging import os import re import shutil -import zipfile import threading -import json +import zipfile from datetime import datetime, timedelta -import logging +from typing import Any, Mapping, Optional from pydantic import ( BaseModel, - field_validator, - field_serializer, ConfigDict, ValidationError, + field_serializer, + field_validator, ) -from openflexure_microscope_server.utilities import requires_lock -from openflexure_microscope_server.utilities import make_name_safe +from openflexure_microscope_server.utilities import make_name_safe, requires_lock LOGGER = logging.getLogger(__name__) diff --git a/src/openflexure_microscope_server/scan_planners.py b/src/openflexure_microscope_server/scan_planners.py index 3a215183..454c0660 100644 --- a/src/openflexure_microscope_server/scan_planners.py +++ b/src/openflexure_microscope_server/scan_planners.py @@ -9,9 +9,9 @@ subclassing the ScanPlanner # would be to import Union and use a string. from __future__ import annotations -from typing import TypeAlias, Optional, Any import logging from copy import copy +from typing import Any, Optional, TypeAlias import numpy as np diff --git a/src/openflexure_microscope_server/server/__init__.py b/src/openflexure_microscope_server/server/__init__.py index 93a675d8..ea343596 100644 --- a/src/openflexure_microscope_server/server/__init__.py +++ b/src/openflexure_microscope_server/server/__init__.py @@ -2,20 +2,22 @@ from __future__ import annotations -from typing import Optional, Callable, Any -from functools import wraps -from copy import copy import logging from argparse import Namespace +from copy import copy +from functools import wraps +from typing import Any, Callable, Optional -import labthings_fastapi as lt import uvicorn from uvicorn.main import Server +import labthings_fastapi as lt + from openflexure_microscope_server.utilities import load_patched_config -from .serve_static_files import add_static_files -from .legacy_api import add_v2_endpoints + from ..logging import configure_logging, retrieve_log, retrieve_log_from_file +from .legacy_api import add_v2_endpoints +from .serve_static_files import add_static_files LOGGER = logging.getLogger(__name__) diff --git a/src/openflexure_microscope_server/server/legacy_api.py b/src/openflexure_microscope_server/server/legacy_api.py index 5e939116..ff41c2bc 100644 --- a/src/openflexure_microscope_server/server/legacy_api.py +++ b/src/openflexure_microscope_server/server/legacy_api.py @@ -1,9 +1,11 @@ """Provide endpoints that mimic the v2 API for OpenFlexure Connect discoverability.""" -import labthings_fastapi as lt -from fastapi import Response from socket import gethostname +from fastapi import Response + +import labthings_fastapi as lt + FAKE_ROUTES = [ "/api/v2/", "/api/v2/streams/snapshot", diff --git a/src/openflexure_microscope_server/server/serve_static_files.py b/src/openflexure_microscope_server/server/serve_static_files.py index 542aa383..11510781 100644 --- a/src/openflexure_microscope_server/server/serve_static_files.py +++ b/src/openflexure_microscope_server/server/serve_static_files.py @@ -3,9 +3,9 @@ import os from typing import Optional +from fastapi import FastAPI from fastapi.responses import FileResponse, RedirectResponse from fastapi.staticfiles import StaticFiles -from fastapi import FastAPI THIS_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_PATH = os.path.normpath(os.path.join(THIS_DIR, "..", "static")) diff --git a/src/openflexure_microscope_server/stitching.py b/src/openflexure_microscope_server/stitching.py index ba0f4b6f..b1a88863 100644 --- a/src/openflexure_microscope_server/stitching.py +++ b/src/openflexure_microscope_server/stitching.py @@ -6,13 +6,13 @@ CPU intensity of stitching causing scanning problems due to the Python Global Interpreter Lock (GIL). May be possible to shift to multiprocessing in the future. """ -from typing import Optional, Any -import threading -import subprocess -import signal import os -from io import TextIOWrapper import shlex +import signal +import subprocess +import threading +from io import TextIOWrapper +from typing import Any, Optional import labthings_fastapi as lt diff --git a/src/openflexure_microscope_server/things/autofocus.py b/src/openflexure_microscope_server/things/autofocus.py index c80b5308..44098957 100644 --- a/src/openflexure_microscope_server/things/autofocus.py +++ b/src/openflexure_microscope_server/things/autofocus.py @@ -7,22 +7,22 @@ of images (a 'z-stack'). See repository root for licensing information. """ -from contextlib import contextmanager import logging -import time -from typing import Annotated, Mapping, Optional, Sequence, Literal import os +import time +from contextlib import contextmanager from dataclasses import dataclass +from typing import Annotated, Literal, Mapping, Optional, Sequence -from fastapi import Depends import numpy as np -from pydantic import BaseModel, field_validator, computed_field, model_validator +from fastapi import Depends +from pydantic import BaseModel, computed_field, field_validator, model_validator import labthings_fastapi as lt from labthings_fastapi.types.numpy import NDArray -from .camera import RawCameraDependency as RawCamera from .camera import CameraDependency as CameraClient +from .camera import RawCameraDependency as RawCamera from .stage import StageDependency as Stage LOGGER = logging.getLogger(__name__) diff --git a/src/openflexure_microscope_server/things/camera/__init__.py b/src/openflexure_microscope_server/things/camera/__init__.py index 1bb3bcef..9cda7723 100644 --- a/src/openflexure_microscope_server/things/camera/__init__.py +++ b/src/openflexure_microscope_server/things/camera/__init__.py @@ -7,31 +7,32 @@ See repository root for licensing information. """ from __future__ import annotations -from typing import Literal, Optional, Tuple, Any, Mapping -from types import TracebackType -import json + import io -import time +import json import logging -from datetime import datetime -import tempfile import os +import tempfile +import time +from datetime import datetime +from types import TracebackType +from typing import Any, Literal, Mapping, Optional, Tuple import numpy as np -from pydantic import RootModel -from PIL import Image import piexif +from PIL import Image +from pydantic import RootModel import labthings_fastapi as lt from labthings_fastapi.types.numpy import NDArray -from openflexure_microscope_server.ui import ActionButton, PropertyControl from openflexure_microscope_server.background_detect import ( - ColourChannelDetectLUV, - ChannelDeviationLUV, BackgroundDetectAlgorithm, BackgroundDetectorStatus, + ChannelDeviationLUV, + ColourChannelDetectLUV, ) +from openflexure_microscope_server.ui import ActionButton, PropertyControl LOGGER = logging.getLogger(__name__) diff --git a/src/openflexure_microscope_server/things/camera/opencv.py b/src/openflexure_microscope_server/things/camera/opencv.py index a19645d8..644b4cfa 100644 --- a/src/openflexure_microscope_server/things/camera/opencv.py +++ b/src/openflexure_microscope_server/things/camera/opencv.py @@ -9,9 +9,9 @@ See repository root for licensing information. from __future__ import annotations import logging -from typing import Literal, Optional -from types import TracebackType from threading import Thread +from types import TracebackType +from typing import Literal, Optional import cv2 from PIL import Image diff --git a/src/openflexure_microscope_server/things/camera/picamera.py b/src/openflexure_microscope_server/things/camera/picamera.py index 7c664dbc..86b5241a 100644 --- a/src/openflexure_microscope_server/things/camera/picamera.py +++ b/src/openflexure_microscope_server/things/camera/picamera.py @@ -15,39 +15,40 @@ https://datasheets.raspberrypi.com/camera/raspberry-pi-camera-guide.pdf """ from __future__ import annotations -from typing import Annotated, Iterator, Literal, Mapping, Optional, Any -from types import TracebackType + +import copy import json import logging import os -import copy import tempfile import time from contextlib import contextmanager from threading import RLock +from types import TracebackType +from typing import Annotated, Any, Iterator, Literal, Mapping, Optional -from pydantic import BaseModel, BeforeValidator import numpy as np -from PIL import Image from picamera2 import Picamera2 from picamera2.encoders import MJPEGEncoder from picamera2.outputs import Output +from PIL import Image +from pydantic import BaseModel, BeforeValidator import labthings_fastapi as lt from labthings_fastapi.exceptions import NotConnectedToServerError +from openflexure_microscope_server.background_detect import ChannelBlankError from openflexure_microscope_server.ui import ( ActionButton, PropertyControl, action_button_for, property_control_for, ) -from openflexure_microscope_server.background_detect import ChannelBlankError + +from . import ArrayModel, BaseCamera from . import picamera_recalibrate_utils as recalibrate_utils from . import picamera_tuning_file_utils as tf_utils -from . import BaseCamera, ArrayModel - LOGGER = logging.getLogger(__name__) SUPPORTED_CAMS_SENSOR_INFO = { diff --git a/src/openflexure_microscope_server/things/camera/picamera_recalibrate_utils.py b/src/openflexure_microscope_server/things/camera/picamera_recalibrate_utils.py index fdd0fab6..b5b3c5ff 100644 --- a/src/openflexure_microscope_server/things/camera/picamera_recalibrate_utils.py +++ b/src/openflexure_microscope_server/things/camera/picamera_recalibrate_utils.py @@ -41,16 +41,17 @@ reliable. The three steps above can be accomplished by: # ruff: noqa: N806 N803 from __future__ import annotations + import gc import logging import time from typing import List, Tuple -from pydantic import BaseModel -import numpy as np -from scipy.ndimage import zoom -from picamera2 import Picamera2 +import numpy as np import picamera2 +from picamera2 import Picamera2 +from pydantic import BaseModel +from scipy.ndimage import zoom LOGGER = logging.getLogger(__name__) diff --git a/src/openflexure_microscope_server/things/camera/picamera_tuning_file_utils.py b/src/openflexure_microscope_server/things/camera/picamera_tuning_file_utils.py index 2a327289..50965f77 100644 --- a/src/openflexure_microscope_server/things/camera/picamera_tuning_file_utils.py +++ b/src/openflexure_microscope_server/things/camera/picamera_tuning_file_utils.py @@ -3,14 +3,13 @@ The functions that edit the tuning files return a new dictionary that is updated. """ -from typing import Any, Optional -from copy import deepcopy -import os import json +import os +from copy import deepcopy +from typing import Any, Optional -from pydantic import BaseModel import numpy as np - +from pydantic import BaseModel THIS_DIR = os.path.dirname(os.path.abspath(__file__)) diff --git a/src/openflexure_microscope_server/things/camera/simulation.py b/src/openflexure_microscope_server/things/camera/simulation.py index 1129df17..f0b80d0a 100644 --- a/src/openflexure_microscope_server/things/camera/simulation.py +++ b/src/openflexure_microscope_server/things/camera/simulation.py @@ -7,12 +7,13 @@ See repository root for licensing information. """ from __future__ import annotations -import logging -from typing import Literal, Optional, Mapping -from types import TracebackType -from threading import Thread -import time + import io +import logging +import time +from threading import Thread +from types import TracebackType +from typing import Literal, Mapping, Optional import numpy as np from PIL import Image, ImageFilter @@ -26,8 +27,8 @@ from openflexure_microscope_server.ui import ( property_control_for, ) -from . import BaseCamera, ArrayModel from ..stage import BaseStage +from . import ArrayModel, BaseCamera LOGGER = logging.getLogger(__name__) diff --git a/src/openflexure_microscope_server/things/camera_stage_mapping.py b/src/openflexure_microscope_server/things/camera_stage_mapping.py index 409aa800..88a3393d 100644 --- a/src/openflexure_microscope_server/things/camera_stage_mapping.py +++ b/src/openflexure_microscope_server/things/camera_stage_mapping.py @@ -15,23 +15,23 @@ from typing import ( Any, Dict, List, + Mapping, NamedTuple, Optional, Tuple, - Mapping, ) -from fastapi import HTTPException import numpy as np +from fastapi import HTTPException + +import labthings_fastapi as lt from camera_stage_mapping.camera_stage_calibration_1d import ( calibrate_backlash_1d, image_to_stage_displacement_from_1d, ) -from camera_stage_mapping.exceptions import MappingError - -import labthings_fastapi as lt -from labthings_fastapi.types.numpy import DenumpifyingDict from camera_stage_mapping.camera_stage_tracker import Tracker +from camera_stage_mapping.exceptions import MappingError +from labthings_fastapi.types.numpy import DenumpifyingDict from .camera import CameraDependency as CameraClient from .stage import StageDependency as Stage diff --git a/src/openflexure_microscope_server/things/smart_scan.py b/src/openflexure_microscope_server/things/smart_scan.py index 0d35cc2f..eefa6b65 100644 --- a/src/openflexure_microscope_server/things/smart_scan.py +++ b/src/openflexure_microscope_server/things/smart_scan.py @@ -7,37 +7,35 @@ It also controls external processes for live stitching composite images, and the creation of the final stitched images. """ -from typing import ( - Optional, - Self, - TypeVar, - ParamSpec, - Callable, - Concatenate, - Mapping, - Any, -) -import threading import os +import threading import time from datetime import datetime from subprocess import SubprocessError +from typing import ( + Any, + Callable, + Concatenate, + Mapping, + Optional, + ParamSpec, + Self, + TypeVar, +) +import numpy as np from fastapi import HTTPException from fastapi.responses import FileResponse -import numpy as np from pydantic import BaseModel import labthings_fastapi as lt -from openflexure_microscope_server import scan_directories -from openflexure_microscope_server import scan_planners -from openflexure_microscope_server import stitching +from openflexure_microscope_server import scan_directories, scan_planners, stitching # Things from .autofocus import AutofocusThing, StackParams -from .camera_stage_mapping import CameraStageMapper from .camera import CameraDependency as CameraClient +from .camera_stage_mapping import CameraStageMapper from .stage import StageDependency as StageDep T = TypeVar("T") diff --git a/src/openflexure_microscope_server/things/stage/__init__.py b/src/openflexure_microscope_server/things/stage/__init__.py index 3643fc5d..0e92c2c6 100644 --- a/src/openflexure_microscope_server/things/stage/__init__.py +++ b/src/openflexure_microscope_server/things/stage/__init__.py @@ -10,8 +10,9 @@ As the object will be used as a context manager create the hardware connection i """ from __future__ import annotations -from collections.abc import Sequence, Mapping -from typing import Literal, Never, Any + +from collections.abc import Mapping, Sequence +from typing import Any, Literal, Never import labthings_fastapi as lt diff --git a/src/openflexure_microscope_server/things/stage/dummy.py b/src/openflexure_microscope_server/things/stage/dummy.py index 6758b37a..a2572908 100644 --- a/src/openflexure_microscope_server/things/stage/dummy.py +++ b/src/openflexure_microscope_server/things/stage/dummy.py @@ -2,10 +2,10 @@ from __future__ import annotations -from typing import Optional, Any -from types import TracebackType -from collections.abc import Mapping import time +from collections.abc import Mapping +from types import TracebackType +from typing import Any, Optional import labthings_fastapi as lt diff --git a/src/openflexure_microscope_server/things/stage/sangaboard.py b/src/openflexure_microscope_server/things/stage/sangaboard.py index e5cc99b5..7432480b 100644 --- a/src/openflexure_microscope_server/things/stage/sangaboard.py +++ b/src/openflexure_microscope_server/things/stage/sangaboard.py @@ -1,18 +1,20 @@ """Provide a LabThings-FastAPI interface to the Sangaboard motor controller.""" from __future__ import annotations + import logging import threading import time -from copy import copy -from typing import Iterator, Literal, Optional, Any -from types import TracebackType -from contextlib import contextmanager from collections.abc import Mapping +from contextlib import contextmanager +from copy import copy +from types import TracebackType +from typing import Any, Iterator, Literal, Optional import semver -import sangaboard + import labthings_fastapi as lt +import sangaboard from . import BaseStage diff --git a/src/openflexure_microscope_server/things/stage_measure.py b/src/openflexure_microscope_server/things/stage_measure.py index 6b1837be..c4dd9613 100644 --- a/src/openflexure_microscope_server/things/stage_measure.py +++ b/src/openflexure_microscope_server/things/stage_measure.py @@ -13,20 +13,20 @@ is tracked and an error is raised if it exceeds a minimum amount. Currently this is 10% of the expected motion is the measured axis. """ -from typing import Literal, Any, Optional, overload import time from dataclasses import dataclass from threading import Lock +from typing import Any, Literal, Optional, overload import numpy as np -from camera_stage_mapping import fft_image_tracking import labthings_fastapi as lt +from camera_stage_mapping import fft_image_tracking # Things from .autofocus import AutofocusThing -from .camera_stage_mapping import CameraStageMapper from .camera import CameraDependency as CamDep +from .camera_stage_mapping import CameraStageMapper from .stage import StageDependency as StageDep CSMDep = lt.deps.direct_thing_client_dependency( diff --git a/src/openflexure_microscope_server/things/system.py b/src/openflexure_microscope_server/things/system.py index ba70f065..d8a785e6 100644 --- a/src/openflexure_microscope_server/things/system.py +++ b/src/openflexure_microscope_server/things/system.py @@ -4,14 +4,14 @@ A module to control the underlying microscope system and to expose information a the microscope, server, and thing states to the web API. """ -from collections.abc import Mapping -import socket -from typing import Optional, Any -from uuid import UUID, uuid4 -import subprocess import os -from signal import SIGTERM +import socket +import subprocess import time +from collections.abc import Mapping +from signal import SIGTERM +from typing import Any, Optional +from uuid import UUID, uuid4 from pydantic import BaseModel diff --git a/src/openflexure_microscope_server/ui.py b/src/openflexure_microscope_server/ui.py index 7a595dd9..9de8396c 100644 --- a/src/openflexure_microscope_server/ui.py +++ b/src/openflexure_microscope_server/ui.py @@ -1,6 +1,6 @@ """Functionality for communicating the required user interface for a thing.""" -from typing import Callable, Any +from typing import Any, Callable from pydantic import BaseModel diff --git a/src/openflexure_microscope_server/utilities.py b/src/openflexure_microscope_server/utilities.py index 77c2ab06..9c88e170 100644 --- a/src/openflexure_microscope_server/utilities.py +++ b/src/openflexure_microscope_server/utilities.py @@ -1,26 +1,26 @@ """Utility functions and classes.""" -from typing import ( - TypeVar, - Callable, - ParamSpec, - Optional, - Any, - Concatenate, - Self, - overload, - TypeAlias, - Literal, -) +import json +import logging import os import re import sys -from threading import Thread -import logging -from importlib.metadata import version import tomllib from functools import wraps -import json +from importlib.metadata import version +from threading import Thread +from typing import ( + Any, + Callable, + Concatenate, + Literal, + Optional, + ParamSpec, + Self, + TypeAlias, + TypeVar, + overload, +) from pydantic import BaseModel diff --git a/tests/mock_things/mock_camera.py b/tests/mock_things/mock_camera.py index a817a47d..2b67ed78 100644 --- a/tests/mock_things/mock_camera.py +++ b/tests/mock_things/mock_camera.py @@ -7,11 +7,12 @@ The mocks do not subclass Things. Instead, they return predefined answers to functions. """ +from unittest.mock import Mock, PropertyMock + from openflexure_microscope_server.background_detect import ( BackgroundDetectorStatus, ColourChannelDetectSettings, ) -from unittest.mock import Mock, PropertyMock class MockCameraThing(Mock): diff --git a/tests/test_autofocus.py b/tests/test_autofocus.py index b68dfb1a..4c02146c 100644 --- a/tests/test_autofocus.py +++ b/tests/test_autofocus.py @@ -3,8 +3,8 @@ This doesn't check the behaviour of the JPEG shaprness monitor. """ -import pytest import numpy as np +import pytest from openflexure_microscope_server.things.autofocus import ( AutofocusThing, diff --git a/tests/test_background_detectors.py b/tests/test_background_detectors.py index 37df95ae..764daee0 100644 --- a/tests/test_background_detectors.py +++ b/tests/test_background_detectors.py @@ -5,19 +5,19 @@ This tests both the base class an individual algorithms. import re +import numpy as np import pytest from pydantic import BaseModel -import numpy as np from openflexure_microscope_server.background_detect import ( - MissingBackgroundDataError, BackgroundDetectAlgorithm, - ChannelDistributions, - ColourChannelDetectSettings, - ColourChannelDetectLUV, - _chunked_stds, - ChannelDeviationLUV, ChannelBlankError, + ChannelDeviationLUV, + ChannelDistributions, + ColourChannelDetectLUV, + ColourChannelDetectSettings, + MissingBackgroundDataError, + _chunked_stds, ) RNG = np.random.default_rng() diff --git a/tests/test_camera.py b/tests/test_camera.py index 66091593..c6009f71 100644 --- a/tests/test_camera.py +++ b/tests/test_camera.py @@ -3,9 +3,9 @@ import tempfile from contextlib import contextmanager +import numpy as np import pytest from fastapi.testclient import TestClient -import numpy as np from PIL import Image import labthings_fastapi as lt diff --git a/tests/test_camera_buffer.py b/tests/test_camera_buffer.py index 5530478c..3fb0635f 100644 --- a/tests/test_camera_buffer.py +++ b/tests/test_camera_buffer.py @@ -3,9 +3,8 @@ from random import randint import numpy as np -from PIL import Image import pytest - +from PIL import Image from openflexure_microscope_server.things.camera import ( CameraMemoryBuffer, diff --git a/tests/test_cameras.py b/tests/test_cameras.py index fc10370b..aa28e762 100644 --- a/tests/test_cameras.py +++ b/tests/test_cameras.py @@ -7,8 +7,8 @@ on camera functionality using the simulation camera are in "test_camera". import pytest from openflexure_microscope_server.things.camera import BaseCamera -from openflexure_microscope_server.things.camera.simulation import SimulatedCamera from openflexure_microscope_server.things.camera.opencv import OpenCVCamera +from openflexure_microscope_server.things.camera.simulation import SimulatedCamera @pytest.fixture diff --git a/tests/test_config_utilities.py b/tests/test_config_utilities.py index dd1b212f..1d0aa408 100644 --- a/tests/test_config_utilities.py +++ b/tests/test_config_utilities.py @@ -1,10 +1,11 @@ """Test the configuration handling functions in utilities.""" -import pytest -import os import json +import os from json import JSONDecodeError +import pytest + from openflexure_microscope_server import utilities diff --git a/tests/test_dummy_server.py b/tests/test_dummy_server.py index 3a871f36..08715d7a 100644 --- a/tests/test_dummy_server.py +++ b/tests/test_dummy_server.py @@ -12,18 +12,18 @@ import json import os import tempfile -from fastapi.testclient import TestClient -from PIL import Image import numpy as np import piexif import pytest +from fastapi.testclient import TestClient +from PIL import Image import labthings_fastapi as lt -from openflexure_microscope_server.things.camera.simulation import SimulatedCamera -from openflexure_microscope_server.things.stage.dummy import DummyStage from openflexure_microscope_server.things.autofocus import AutofocusThing +from openflexure_microscope_server.things.camera.simulation import SimulatedCamera from openflexure_microscope_server.things.camera_stage_mapping import CameraStageMapper +from openflexure_microscope_server.things.stage.dummy import DummyStage @pytest.fixture diff --git a/tests/test_legacy_api.py b/tests/test_legacy_api.py index e8a63a4b..2f7f105d 100644 --- a/tests/test_legacy_api.py +++ b/tests/test_legacy_api.py @@ -1,7 +1,7 @@ """Test server booting and shut down.""" -from socket import gethostname import asyncio +from socket import gethostname # Import as ofm server to attempt to minimise confusion with server as a var in other # functions and also FastAPI `Server`. diff --git a/tests/test_logging.py b/tests/test_logging.py index 85d59888..d9509f8e 100644 --- a/tests/test_logging.py +++ b/tests/test_logging.py @@ -1,12 +1,12 @@ """Test the server's logging configuration and handling.""" +import logging import os import tempfile -import logging -from fastapi.responses import PlainTextResponse -from fastapi import HTTPException import pytest +from fastapi import HTTPException +from fastapi.responses import PlainTextResponse from openflexure_microscope_server import logging as ofm_logging diff --git a/tests/test_picamera_tuning_files.py b/tests/test_picamera_tuning_files.py index c48b2380..4938d8a3 100644 --- a/tests/test_picamera_tuning_files.py +++ b/tests/test_picamera_tuning_files.py @@ -2,9 +2,8 @@ from copy import deepcopy -import pytest import numpy as np - +import pytest from openflexure_microscope_server.things.camera import ( picamera_tuning_file_utils as tf_utils, diff --git a/tests/test_sangaboard.py b/tests/test_sangaboard.py index a75b19a7..bd9ec103 100644 --- a/tests/test_sangaboard.py +++ b/tests/test_sangaboard.py @@ -5,9 +5,9 @@ import logging import pytest from openflexure_microscope_server.things.stage.sangaboard import ( - SangaboardThing, - REQUIRED_VERSION, RECOMMENDED_VERSION, + REQUIRED_VERSION, + SangaboardThing, ) diff --git a/tests/test_scan_data.py b/tests/test_scan_data.py index a1ea4f1c..b14ba061 100644 --- a/tests/test_scan_data.py +++ b/tests/test_scan_data.py @@ -1,8 +1,8 @@ """Test the functionality in the scan_directories module.""" -from datetime import datetime, timedelta -from copy import copy import json +from copy import copy +from datetime import datetime, timedelta from math import floor from openflexure_microscope_server.scan_directories import ScanData diff --git a/tests/test_scan_directories.py b/tests/test_scan_directories.py index 7ee8962d..13336b11 100644 --- a/tests/test_scan_directories.py +++ b/tests/test_scan_directories.py @@ -1,24 +1,24 @@ """Test the functionality in the scan_directories module.""" -import tempfile -import os -import math -import shutil -import logging -import random -import time import json +import logging +import math +import os +import random +import shutil +import tempfile +import time from collections import namedtuple import pytest from openflexure_microscope_server.scan_directories import ( - ScanDirectoryManager, + SCAN_DATA_FILENAME, + NotEnoughFreeSpaceError, ScanDirectory, + ScanDirectoryManager, ScanInfo, get_files_in_zip, - NotEnoughFreeSpaceError, - SCAN_DATA_FILENAME, ) from .test_scan_data import _fake_scan_data diff --git a/tests/test_scan_planners.py b/tests/test_scan_planners.py index 4d87a0d6..bbaf061a 100644 --- a/tests/test_scan_planners.py +++ b/tests/test_scan_planners.py @@ -4,10 +4,12 @@ As well as low level function by function tests, this test suite also provides t that simulate scanning a sample, checking that the expected path is followed. """ -import pytest from copy import copy +import pytest + from openflexure_microscope_server import scan_planners + from .utilities import scan_test_helpers diff --git a/tests/test_serve_static_files.py b/tests/test_serve_static_files.py index 8d381456..4af8b09d 100644 --- a/tests/test_serve_static_files.py +++ b/tests/test_serve_static_files.py @@ -1,9 +1,9 @@ """Test the code that mounts static files to the server, without creating a server.""" +import asyncio import os import shutil import tempfile -import asyncio import pytest from starlette.responses import FileResponse, RedirectResponse diff --git a/tests/test_server_config.py b/tests/test_server_config.py index 3074d707..d3a267cb 100644 --- a/tests/test_server_config.py +++ b/tests/test_server_config.py @@ -1,7 +1,7 @@ """Test server booting and shut down.""" -import os import json +import os from copy import deepcopy import pytest diff --git a/tests/test_smart_scan.py b/tests/test_smart_scan.py index 617caab1..bbea1391 100644 --- a/tests/test_smart_scan.py +++ b/tests/test_smart_scan.py @@ -13,31 +13,31 @@ For these tests to reliably represent real behaviour the mock Things will need t be tested for matching signatures with dynamically generated clients. """ -from typing import Callable, Optional -import tempfile +import logging import os import shutil -import logging +import tempfile from datetime import datetime +from typing import Callable, Optional -from fastapi import HTTPException import pytest +from fastapi import HTTPException from labthings_fastapi.exceptions import InvocationCancelledError -from openflexure_microscope_server.things.smart_scan import ( - SmartScanThing, - ScanNotRunningError, -) from openflexure_microscope_server.scan_directories import ( - ScanData, NotEnoughFreeSpaceError, + ScanData, +) +from openflexure_microscope_server.things.smart_scan import ( + ScanNotRunningError, + SmartScanThing, ) -from .mock_things.mock_csm import MockCSMThing from .mock_things.mock_autofocus import MockAutoFocusThing -from .mock_things.mock_stage import MockStageThing from .mock_things.mock_camera import MockCameraThing +from .mock_things.mock_csm import MockCSMThing +from .mock_things.mock_stage import MockStageThing # A global logger to pass in as an Invocation Logger LOGGER = logging.getLogger("mock-invocation_logger") diff --git a/tests/test_stack.py b/tests/test_stack.py index 57e493db..3f92aedc 100644 --- a/tests/test_stack.py +++ b/tests/test_stack.py @@ -1,31 +1,32 @@ """Tests for the smart and fast stacking.""" -from typing import Optional +import logging import tempfile from random import randint -import logging +from typing import Optional -import pytest import numpy as np -from hypothesis import given, strategies as st +import pytest from fastapi.testclient import TestClient +from hypothesis import given +from hypothesis import strategies as st import labthings_fastapi as lt +from openflexure_microscope_server.scan_directories import IMAGE_REGEX from openflexure_microscope_server.things.autofocus import ( - AutofocusThing, - StackParams, - CaptureInfo, - MIN_TEST_IMAGE_COUNT, + EXTRA_STACK_CAPTURES, MAX_TEST_IMAGE_COUNT, + MIN_TEST_IMAGE_COUNT, + AutofocusThing, + CaptureInfo, + NotAPeakError, + StackParams, + _count_turning_points, _get_capture_by_id, _get_capture_index_by_id, - EXTRA_STACK_CAPTURES, - NotAPeakError, _get_peak_turning_point, - _count_turning_points, ) -from openflexure_microscope_server.scan_directories import IMAGE_REGEX LOGGER = logging.getLogger("mock-invocation_logger") RANDOM_GENERATOR = np.random.default_rng() diff --git a/tests/test_stage.py b/tests/test_stage.py index 1beebf9b..b735ab4c 100644 --- a/tests/test_stage.py +++ b/tests/test_stage.py @@ -1,12 +1,13 @@ """Test the stage without creating a full HTTP server and socket connection.""" -import tempfile import itertools +import tempfile -from fastapi.testclient import TestClient import pytest +from fastapi.testclient import TestClient from httpx import HTTPStatusError -from hypothesis import given, settings, HealthCheck, strategies as st +from hypothesis import HealthCheck, given, settings +from hypothesis import strategies as st import labthings_fastapi as lt from labthings_fastapi.exceptions import NotConnectedToServerError @@ -17,7 +18,6 @@ from openflexure_microscope_server.things.stage import ( ) from openflexure_microscope_server.things.stage.dummy import DummyStage - from .mock_things.mock_cancel import MockCancel # Keep the size and number of moves fairly small or the tests can take forever diff --git a/tests/test_stage_measure.py b/tests/test_stage_measure.py index 5e0462d3..f2a8205b 100644 --- a/tests/test_stage_measure.py +++ b/tests/test_stage_measure.py @@ -1,13 +1,13 @@ """File contains unit tests for stage_measure.""" -from copy import copy -import logging import dataclasses +import logging import tempfile +from copy import copy -from fastapi.testclient import TestClient import numpy as np import pytest +from fastapi.testclient import TestClient import labthings_fastapi as lt diff --git a/tests/test_stitching.py b/tests/test_stitching.py index 95ebd355..55d8df67 100644 --- a/tests/test_stitching.py +++ b/tests/test_stitching.py @@ -6,20 +6,20 @@ generated, and the subprocess calling works as expected. import logging import os -from copy import copy -import uuid import threading import time +import uuid +from copy import copy import pytest import labthings_fastapi as lt from openflexure_microscope_server.stitching import ( - BaseStitcher, - PreviewStitcher, - FinalStitcher, STITCHING_RESOLUTION, + BaseStitcher, + FinalStitcher, + PreviewStitcher, StitcherValidationError, ) diff --git a/tests/test_version_strings.py b/tests/test_version_strings.py index 773f18ad..542a6474 100644 --- a/tests/test_version_strings.py +++ b/tests/test_version_strings.py @@ -1,16 +1,16 @@ """Tests that version strings can be produced reliably.""" -import subprocess +import logging import os import re -import tempfile import shutil +import subprocess +import tempfile import warnings -import logging +import pytest from hypothesis import strategies as st from hypothesis.errors import NonInteractiveExampleWarning -import pytest from openflexure_microscope_server import utilities diff --git a/tests/utilities/__init__.py b/tests/utilities/__init__.py index a261de29..e584d480 100644 --- a/tests/utilities/__init__.py +++ b/tests/utilities/__init__.py @@ -4,8 +4,8 @@ At the top level are some basic testing functions. More specific testing utiliti provided by modules inside the package. """ -from typing import Protocol, Iterable from collections.abc import Hashable +from typing import Iterable, Protocol class SizedIterableHashable(Iterable[Hashable], Protocol): diff --git a/tests/utilities/scan_test_helpers.py b/tests/utilities/scan_test_helpers.py index bf22876a..ce9ffbb0 100755 --- a/tests/utilities/scan_test_helpers.py +++ b/tests/utilities/scan_test_helpers.py @@ -11,11 +11,11 @@ import os import pickle import numpy as np -from scipy import interpolate from matplotlib import pyplot as plt -from matplotlib.path import Path as MatPath -from matplotlib.patches import PathPatch from matplotlib.figure import Figure +from matplotlib.patches import PathPatch +from matplotlib.path import Path as MatPath +from scipy import interpolate from openflexure_microscope_server import scan_planners @@ -145,8 +145,8 @@ def example_smart_spiral( def profile_example_smart_spiral(): """Profile running an example scan and print the cumulative profile stats.""" - import pstats import cProfile + import pstats profiler = cProfile.Profile() profiler.runcall(example_smart_spiral)