|
| 1 | +""" |
| 2 | +Example: Platform-aware CZI loading for napari-czitools plugin. |
| 3 | +
|
| 4 | +This module shows how to handle Linux threading issues when czitools |
| 5 | +is used as part of a Napari plugin. |
| 6 | +""" |
| 7 | + |
| 8 | +import platform |
| 9 | +from pathlib import Path |
| 10 | +from typing import Optional, Tuple |
| 11 | +import pandas as pd |
| 12 | +import numpy as np |
| 13 | +from czitools.read_tools import read_tools |
| 14 | +from czitools.utils.planetable import get_planetable |
| 15 | +from czitools.metadata_tools.czi_metadata import CziMetadata |
| 16 | + |
| 17 | + |
| 18 | +class NapariCziLoader: |
| 19 | + """ |
| 20 | + Platform-aware CZI loader for Napari plugins. |
| 21 | +
|
| 22 | + Handles threading issues on Linux automatically. |
| 23 | + """ |
| 24 | + |
| 25 | + def __init__(self, enable_planetable_on_linux: bool = False): |
| 26 | + """ |
| 27 | + Initialize loader. |
| 28 | +
|
| 29 | + Args: |
| 30 | + enable_planetable_on_linux: If True, attempt planetable extraction |
| 31 | + on Linux (may crash). If False, skip planetable on Linux. |
| 32 | + """ |
| 33 | + self.enable_planetable_on_linux = enable_planetable_on_linux |
| 34 | + self.is_linux = platform.system() == "Linux" |
| 35 | + |
| 36 | + def load_czi( |
| 37 | + self, filepath: Path, extract_planetable: bool = True |
| 38 | + ) -> Tuple[np.ndarray, CziMetadata, Optional[pd.DataFrame]]: |
| 39 | + """ |
| 40 | + Load CZI file with platform-aware handling. |
| 41 | +
|
| 42 | + Args: |
| 43 | + filepath: Path to CZI file |
| 44 | + extract_planetable: Whether to attempt planetable extraction |
| 45 | +
|
| 46 | + Returns: |
| 47 | + Tuple of (array, metadata, planetable_df) |
| 48 | + planetable_df may be None on Linux or if extraction fails |
| 49 | + """ |
| 50 | + print(f"Loading CZI: {filepath}") |
| 51 | + |
| 52 | + # Always load image data (thread-safe) |
| 53 | + array, metadata = read_tools.read_6darray(filepath, use_dask=True, use_xarray=True, chunk_zyx=True) |
| 54 | + print(f"✅ Image loaded: {array.shape}") |
| 55 | + |
| 56 | + # Handle planetable based on platform |
| 57 | + planetable_df = None |
| 58 | + |
| 59 | + if extract_planetable: |
| 60 | + if self.is_linux and not self.enable_planetable_on_linux: |
| 61 | + # Skip on Linux by default |
| 62 | + print("ℹ️ Planetable extraction disabled on Linux (threading safety)") |
| 63 | + print(" To enable: set enable_planetable_on_linux=True") |
| 64 | + print(" Warning: May cause crashes with Napari on Linux") |
| 65 | + else: |
| 66 | + # Try extraction |
| 67 | + planetable_df = self._extract_planetable_safe(filepath) |
| 68 | + |
| 69 | + return array, metadata, planetable_df |
| 70 | + |
| 71 | + def _extract_planetable_safe(self, filepath: Path) -> Optional[pd.DataFrame]: |
| 72 | + """ |
| 73 | + Safely attempt planetable extraction with error handling. |
| 74 | +
|
| 75 | + Args: |
| 76 | + filepath: Path to CZI file |
| 77 | +
|
| 78 | + Returns: |
| 79 | + DataFrame or None if extraction fails |
| 80 | + """ |
| 81 | + if self.is_linux: |
| 82 | + print("⚠️ WARNING: Attempting planetable extraction on Linux") |
| 83 | + print(" This may cause Napari to crash due to threading conflicts") |
| 84 | + print(" If crashes occur, set CZITOOLS_DISABLE_AICSPYLIBCZI=1") |
| 85 | + |
| 86 | + try: |
| 87 | + df, _ = get_planetable(filepath, norm_time=True) |
| 88 | + print(f"✅ Planetable extracted: {len(df)} rows") |
| 89 | + return df |
| 90 | + |
| 91 | + except RuntimeError as e: |
| 92 | + if "CZITOOLS_DISABLE_AICSPYLIBCZI" in str(e): |
| 93 | + print("ℹ️ Planetable disabled (safe mode active)") |
| 94 | + else: |
| 95 | + print(f"❌ Planetable extraction failed: {e}") |
| 96 | + return None |
| 97 | + |
| 98 | + except Exception as e: |
| 99 | + print(f"❌ Planetable extraction error: {e}") |
| 100 | + if self.is_linux: |
| 101 | + print(" This may be a threading conflict on Linux") |
| 102 | + print(" Restart Napari with: export CZITOOLS_DISABLE_AICSPYLIBCZI=1") |
| 103 | + return None |
| 104 | + |
| 105 | + |
| 106 | +# Example usage in a napari plugin widget |
| 107 | +def example_napari_plugin_widget(): |
| 108 | + """ |
| 109 | + Example of how to use NapariCziLoader in a napari plugin. |
| 110 | + """ |
| 111 | + from magicgui import magic_factory |
| 112 | + from napari.types import LayerDataTuple |
| 113 | + |
| 114 | + @magic_factory( |
| 115 | + call_button="Load CZI", |
| 116 | + filepath={"mode": "r", "filter": "*.czi"}, |
| 117 | + enable_planetable={"label": "Extract Planetable (may crash on Linux)"}, |
| 118 | + ) |
| 119 | + def load_czi_widget(filepath: Path, enable_planetable: bool = False) -> LayerDataTuple: |
| 120 | + """ |
| 121 | + Napari widget to load CZI files. |
| 122 | +
|
| 123 | + Args: |
| 124 | + filepath: CZI file to load |
| 125 | + enable_planetable: Extract planetable (risky on Linux) |
| 126 | +
|
| 127 | + Returns: |
| 128 | + Layer data tuple for Napari |
| 129 | + """ |
| 130 | + # Create loader with platform awareness |
| 131 | + loader = NapariCziLoader(enable_planetable_on_linux=enable_planetable) |
| 132 | + |
| 133 | + # Load CZI |
| 134 | + array, metadata, planetable_df = loader.load_czi(filepath, extract_planetable=enable_planetable) |
| 135 | + |
| 136 | + # Prepare metadata for Napari |
| 137 | + layer_metadata = { |
| 138 | + "czi_metadata": metadata.info, |
| 139 | + "planetable": planetable_df.to_dict() if planetable_df is not None else None, |
| 140 | + } |
| 141 | + |
| 142 | + # Show planetable summary if available |
| 143 | + if planetable_df is not None: |
| 144 | + print(f"\n📊 Planetable Summary:") |
| 145 | + print(f" Total planes: {len(planetable_df)}") |
| 146 | + if "Time[s]" in planetable_df.columns: |
| 147 | + print(f" Time range: {planetable_df['Time[s]'].min():.2f} - {planetable_df['Time[s]'].max():.2f} s") |
| 148 | + |
| 149 | + # Return layer data tuple |
| 150 | + return (array, {"name": filepath.name, "metadata": layer_metadata}, "image") |
| 151 | + |
| 152 | + return load_czi_widget |
| 153 | + |
| 154 | + |
| 155 | +# Example: Manual usage |
| 156 | +if __name__ == "__main__": |
| 157 | + from pathlib import Path |
| 158 | + |
| 159 | + # Create loader |
| 160 | + loader = NapariCziLoader(enable_planetable_on_linux=False) # Safe default for Linux |
| 161 | + |
| 162 | + # Load CZI |
| 163 | + filepath = Path("data/CellDivision_T3_Z5_CH2_X240_Y170.czi") |
| 164 | + array, metadata, planetable_df = loader.load_czi(filepath) |
| 165 | + |
| 166 | + print(f"\n✅ Loaded successfully:") |
| 167 | + print(f" Shape: {array.shape}") |
| 168 | + print(f" Planetable: {'Available' if planetable_df is not None else 'Not extracted'}") |
| 169 | + |
| 170 | + # If running in Napari, could display now: |
| 171 | + # import napari |
| 172 | + # viewer = napari.current_viewer() |
| 173 | + # viewer.add_image(array, name=filepath.name) |
0 commit comments