From 06ef6b8bd56c3ab903760c505a654ce4c2a768f9 Mon Sep 17 00:00:00 2001 From: Jakub Kaczmarzyk Date: Wed, 10 Jul 2024 23:44:43 -0400 Subject: [PATCH] only use specified backend (or tifffile) to read mpp (#227) Previously, even if tiffslide was the chosen backend, openslide would still be used first to get mpp. This could cause panics if a slide could not be read by openslide. This panic could confuse users because they asked to use tiffslide. This commit changes the mpp reading function to use the chosen backend or tifffile if that backend fails. --- wsinfer/wsi.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/wsinfer/wsi.py b/wsinfer/wsi.py index 61a7e35..21a5474 100644 --- a/wsinfer/wsi.py +++ b/wsinfer/wsi.py @@ -192,6 +192,8 @@ def _get_mpp_tiffslide( slide_path: str | Path, ) -> tuple[float, float]: """Read MPP using TiffSlide.""" + logger.debug("Attempting to read MPP using TiffSlide") + if not HAS_TIFFSLIDE: logger.critical( "Cannot read MPP with TiffSlide because TiffSlide is not available" @@ -223,6 +225,7 @@ def _get_mpp_tiffslide( # https://github.com/bayer-science-for-a-better-life/tiffslide/blob/8bea5a4c8e1429071ade6d4c40169ce153786d19/tiffslide/tiffslide.py#L712-L745 def _get_mpp_tifffile(slide_path: str | Path) -> tuple[float, float]: """Read MPP using Tifffile.""" + logger.debug("Attempting to read MPP using tifffile") with tifffile.TiffFile(slide_path) as tif: series0 = tif.series[0] page0 = series0[0] @@ -267,20 +270,23 @@ def get_avg_mpp(slide_path: Path | str) -> float: mppx: float mppy: float - if HAS_OPENSLIDE: + if _BACKEND == "openslide": try: mppx, mppy = _get_mpp_openslide(slide_path) return (mppx + mppy) / 2 except CannotReadSpacing: - # At this point, we want to continue to other implementations. pass - if HAS_TIFFSLIDE: + if _BACKEND == "tiffslide": try: mppx, mppy = _get_mpp_tiffslide(slide_path) return (mppx + mppy) / 2 except CannotReadSpacing: - # Our last hope to read the mpp is tifffile. pass + + logger.debug(f"Failed to read MPP using {_BACKEND}.") + logger.debug("Trying to read MPP with tifffile as last resort.") + + # If tiffslide/openslide don't work, try tifffile. try: mppx, mppy = _get_mpp_tifffile(slide_path) return (mppx + mppy) / 2