From 9ce1d962db1a7f0cd85c8cbcc24bf15b7a22ae78 Mon Sep 17 00:00:00 2001 From: Elizabeth Wright Date: Wed, 2 Dec 2026 15:10:57 -0800 Subject: [PATCH 1/6] add czi file dependency --- .github/scripts/check_heavy_imports.py | 2 ++ requirements.txt | 1 + 2 files changed, 3 insertions(+) diff --git a/.github/scripts/check_heavy_imports.py b/.github/scripts/check_heavy_imports.py index 6f2fb36..5fb7afb 100644 --- a/.github/scripts/check_heavy_imports.py +++ b/.github/scripts/check_heavy_imports.py @@ -20,10 +20,12 @@ "pytorch_lightning", "segmentation_models_pytorch", "streamlit", + "czifile", # project modules that need the above "src.lightning_module", "src.unet_dataset", "src.augmentation", + "src.czi_convert", ] failures = [] diff --git a/requirements.txt b/requirements.txt index 41555b3..12523ad 100644 --- a/requirements.txt +++ b/requirements.txt @@ -24,6 +24,7 @@ click==8.5.1 colorama==0.4.6 contourpy==1.4.0 cycler==0.12.1 +czifile==2026.11.26 fastremap==1.21.0 filelock==4.3.2 fill_voids==2.1.2 From 095027a56505f6a88ccc3358bc1641041ae107ce Mon Sep 17 00:00:00 2001 From: Elizabeth Wright Date: Wed, 2 Dec 2026 15:11:22 -0800 Subject: [PATCH 2/6] converter and tests --- src/czi_convert.py | 343 ++++++++++++++++++++++++++++++++++++++ tests/test_czi_convert.py | 260 +++++++++++++++++++++++++++++ 2 files changed, 603 insertions(+) create mode 100644 src/czi_convert.py create mode 100644 tests/test_czi_convert.py diff --git a/src/czi_convert.py b/src/czi_convert.py new file mode 100644 index 0000000..04612d1 --- /dev/null +++ b/src/czi_convert.py @@ -0,0 +1,343 @@ +"""Convert Zeiss .czi files into the per-channel TIFF layout RADIX reads. + + //_raw_CH()_CH.ome.tif + //_czi_metadata.xml (the CZI's full metadata, untouched) + +What is preserved +----------------- +* Pixel data and dtype (Z-stacks are max-projected unless ``z_mode="keep"``). +* Pixel size (X/Y/Z, micrometres) and the original channel name, written into each + TIFF's OME-XML. +* The complete CZI metadata XML (objective, exposure, acquisition time, ...) as a + sidecar file next to the TIFFs. The loaders only read ``*.tif*`` so it is ignored. + +Channels are matched to DAPI/FITC/TRITC with the same keyword list the rest of the app +uses (config.get_channel_aliases, so the sidebar's "Channel file names" apply), then by +emission wavelength as a fallback. A channel that can't be identified is still written +(as ``CH()``) and reported, never silently dropped or guessed. + +The only code that touches the ``czifile`` package is ``_open_czi``; everything else is +plain numpy/tifffile so it can be tested without a real .czi. +""" + +import os +import re +import xml.etree.ElementTree as ET +from contextlib import contextmanager +from dataclasses import dataclass, field +from pathlib import Path + +import numpy as np +import tifffile + +from src.config import CHANNELS, get_channel_aliases + +METADATA_SUFFIX = "_czi_metadata.xml" + +# (low, high) emission wavelength in nm used only when no name/keyword matches. +_EMISSION_RANGES_NM = {"DAPI": (400, 490), "FITC": (490, 560), "TRITC": (560, 650)} + +_SPATIAL = "YX" + + +@dataclass +class ChannelInfo: + index: int + name: str = "" + short_name: str = "" + fluor: str = "" + dye: str = "" + emission_nm: float | None = None + + @property + def labels(self) -> list[str]: + return [s for s in (self.name, self.short_name, self.fluor, self.dye) if s] + + @property + def display(self) -> str: + return self.name or self.short_name or self.fluor or self.dye or f"C{self.index + 1}" + + +@dataclass +class CziMetadata: + channels: list[ChannelInfo] + pixel_size_um: dict[str, float] # keys among "X", "Y", "Z" + xml: str + + +@dataclass +class ConversionResult: + czi: Path + outputs: list[Path] = field(default_factory=list) + channel_map: list[tuple[str, str | None]] = field(default_factory=list) # (czi name, RADIX) + warnings: list[str] = field(default_factory=list) + skipped: str | None = None # reason, when nothing was written + error: str | None = None + + +# ── Metadata ────────────────────────────────────────────────────────────────── + + +def _text(el, tag) -> str: + child = el.find(tag) + return (child.text or "").strip() if child is not None else "" + + +def parse_metadata(xml: str) -> CziMetadata: + """Pull channel descriptions and pixel sizes out of the CZI XML (best effort).""" + channels: list[ChannelInfo] = [] + sizes: dict[str, float] = {} + try: + root = ET.fromstring(xml) + except ET.ParseError: + return CziMetadata([], {}, xml) + + for i, ch in enumerate(root.findall(".//Information/Image/Dimensions/Channels/Channel")): + try: + em = float(_text(ch, "EmissionWavelength")) + except ValueError: + em = None + channels.append( + ChannelInfo( + index=i, + name=(ch.get("Name") or "").strip(), + short_name=_text(ch, "ShortName"), + fluor=_text(ch, "Fluor"), + dye=_text(ch, "DyeName"), + emission_nm=em, + ) + ) + + for d in root.findall(".//Scaling/Items/Distance"): + axis = d.get("Id") + try: + meters = float(_text(d, "Value")) + except ValueError: + continue + if axis in ("X", "Y", "Z") and meters > 0: + sizes[axis] = meters * 1e6 + return CziMetadata(channels, sizes, xml) + + +# ── Channel identification ──────────────────────────────────────────────────── + + +def _norm(s: str) -> str: + return re.sub(r"[^a-z0-9]", "", s.lower()) + + +def _matches(alias: str, label: str) -> bool: + """Whole-token match, or substring for aliases long enough not to be accidental.""" + a = _norm(alias) + if not a: + return False + tokens = [_norm(t) for t in re.split(r"[^A-Za-z0-9]+", label) if t] + if a in tokens: + return True + return len(a) >= 4 and a in _norm(label) + + +def identify_channels(infos: list[ChannelInfo], channels=CHANNELS) -> list[str | None]: + """Map each CZI channel to one of ``channels`` (or None), each used at most once. + + Pass 1: the channel name / dye / fluor against the app's keyword list. + Pass 2: emission wavelength, for whatever is still unmatched. + """ + result: list[str | None] = [None] * len(infos) + taken: set[str] = set() + + for ch in channels: + aliases = get_channel_aliases(ch) + for i, info in enumerate(infos): + if result[i] is None and ch not in taken: + if any(_matches(a, lab) for a in aliases for lab in info.labels): + result[i] = ch + taken.add(ch) + + for i, info in enumerate(infos): + if result[i] is not None or info.emission_nm is None: + continue + for ch in channels: + lo, hi = _EMISSION_RANGES_NM.get(ch, (0, 0)) + if ch not in taken and lo <= info.emission_nm < hi: + result[i] = ch + taken.add(ch) + break + return result + + +# ── Finding files / choosing output folders ─────────────────────────────────── + + +def find_czi_files(data_dir) -> list[Path]: + """Every .czi under ``data_dir`` (root or any subfolder), hidden folders skipped.""" + root = Path(data_dir) + found = [] + if not root.is_dir(): + return found + for dirpath, dirnames, filenames in os.walk(root): + dirnames[:] = sorted(d for d in dirnames if not d.startswith(".")) + found += [Path(dirpath) / f for f in sorted(filenames) if f.lower().endswith(".czi")] + return found + + +def plan_sample(czi: Path, data_dir, all_czis) -> tuple[Path, str]: + """(output folder, sample name) for ``czi``. Samples are always direct children of data_dir. + + * data/foo.czi -> data/foo/ + * data/A/x.czi (only one .czi under A) -> data/A/ (sample name "A") + * data/A/x.czi, data/A/y.czi -> data/A_x/ and data/A_y/ + """ + root = Path(data_dir) + rel = czi.relative_to(root) + if len(rel.parts) == 1: + return root / czi.stem, czi.stem + top = rel.parts[0] + siblings = [c for c in all_czis if c.relative_to(root).parts[:1] == (top,)] + if len(siblings) == 1: + return root / top, top + name = "_".join([*rel.parts[:-1], czi.stem]) + return root / name, name + + +def is_converted(out_dir: Path, name: str) -> bool: + return (out_dir / f"{name}{METADATA_SUFFIX}").is_file() + + +# ── Reading (the only czifile-dependent part) ───────────────────────────────── + + +@contextmanager +def _open_czi(path): + """Yield (metadata_xml, scenes); scenes is [(dims, load)] with ``load() -> ndarray``.""" + try: + import czifile + except ImportError as exc: + raise RuntimeError( + "Reading .czi files needs the 'czifile' package: pip install czifile" + ) from exc + + with czifile.CziFile(str(path)) as czi: + xml = czi.metadata() + scenes = czi.scenes + items = scenes.items() if hasattr(scenes, "items") else enumerate(scenes) + yield xml, [("".join(img.dims), img.asarray) for _, img in items] + + +# ── Conversion ──────────────────────────────────────────────────────────────── + + +def _safe(name: str) -> str: + return re.sub(r'[\\/:*?"<>|()\s]+', "-", name).strip("-") or "unnamed" + + +def _split_axes(arr: np.ndarray, dims: str, z_mode: str): + """Return (channels_first (C, [Z,] Y, X) array, axes str) with T/other axes validated.""" + for ax, n in zip(dims, arr.shape): + if ax not in "CZYX" and n > 1: + raise ValueError( + f"unsupported axis '{ax}' of size {n} (dims={dims}); " + "only channel, Z and XY data are supported" + ) + # drop size-1 axes we don't handle, make sure C exists + keep = [i for i, ax in enumerate(dims) if ax in "CZYX" or arr.shape[i] > 1] + arr = arr.reshape([arr.shape[i] for i in keep]) + dims = "".join(dims[i] for i in keep) + if "C" not in dims: + arr, dims = arr[np.newaxis], "C" + dims + order = [dims.index(a) for a in ("C", "Z", "Y", "X") if a in dims] + arr = np.transpose(arr, order) + dims = "".join(a for a in ("C", "Z", "Y", "X") if a in dims) + if "Z" in dims and z_mode == "max": + arr = arr.max(axis=dims.index("Z")) + dims = dims.replace("Z", "") + return arr, dims + + +def convert_czi( + czi: Path, + out_dir: Path, + name: str, + z_mode: str = "max", + overwrite: bool = False, + channels=CHANNELS, +) -> ConversionResult: + """Convert one .czi into ``out_dir`` (see module docstring). Never raises for bad data.""" + czi, out_dir = Path(czi), Path(out_dir) + res = ConversionResult(czi=czi) + if z_mode not in ("max", "keep"): + raise ValueError("z_mode must be 'max' or 'keep'") + if is_converted(out_dir, name) and not overwrite: + res.skipped = "already converted" + return res + + try: + with _open_czi(czi) as (xml, scenes): + meta = parse_metadata(xml) + if not scenes: + res.error = "no image data found" + return res + multi = len(scenes) > 1 + for s, (dims, load) in enumerate(scenes, start=1): + sc_name = f"{name}_S{s}" if multi else name + sc_dir = out_dir.parent / sc_name if multi else out_dir + if multi and is_converted(sc_dir, sc_name) and not overwrite: + res.warnings.append(f"scene {s}: already converted, skipped") + continue + _write_scene(load(), dims, meta, sc_dir, sc_name, z_mode, channels, res) + except Exception as exc: # noqa: BLE001 - report per file, keep converting the rest + res.error = f"{type(exc).__name__}: {exc}" + return res + + +def _write_scene(arr, dims, meta, out_dir, name, z_mode, channels, res): + data, axes = _split_axes(np.asarray(arr), dims, z_mode) + n_ch = data.shape[0] + infos = meta.channels if len(meta.channels) == n_ch else [ChannelInfo(i) for i in range(n_ch)] + if meta.channels and len(meta.channels) != n_ch: + res.warnings.append( + f"metadata lists {len(meta.channels)} channel(s) but the image has {n_ch}; " + "channel names could not be used" + ) + assigned = identify_channels(infos, channels) + + out_dir.mkdir(parents=True, exist_ok=True) + img_axes = axes[1:] + ome = {"axes": img_axes} + for ax in "XYZ": + if ax in meta.pixel_size_um and ax in img_axes: + ome[f"PhysicalSize{ax}"] = meta.pixel_size_um[ax] + ome[f"PhysicalSize{ax}Unit"] = "µm" + + for c in range(n_ch): + radix = assigned[c] + info = infos[c] + label = radix or _safe(info.display) + res.channel_map.append((info.display, radix)) + if radix is None: + res.warnings.append( + f"{name}: channel '{info.display}' is not DAPI/FITC/TRITC " + f"(saved as CH({label}); add its name under 'Channel file names' to map it)" + ) + path = out_dir / f"{name}_raw_CH({label})_CH{c + 1}.ome.tif" + tifffile.imwrite(path, data[c], metadata={**ome, "Channel": {"Name": info.display}}) + res.outputs.append(path) + + missing = [ch for ch in channels if ch not in assigned] + if missing: + res.warnings.append(f"{name}: no channel identified as {', '.join(missing)}") + (out_dir / f"{name}{METADATA_SUFFIX}").write_text(meta.xml, encoding="utf-8") + + +def convert_all(data_dir, z_mode="max", overwrite=False, progress=None) -> list[ConversionResult]: + """Convert every .czi under ``data_dir``. ``progress(done, total, czi)`` is optional.""" + czis = find_czi_files(data_dir) + results = [] + for i, czi in enumerate(czis): + if progress: + progress(i, len(czis), czi) + out_dir, name = plan_sample(czi, data_dir, czis) + results.append(convert_czi(czi, out_dir, name, z_mode, overwrite)) + if progress: + progress(len(czis), len(czis), None) + return results diff --git a/tests/test_czi_convert.py b/tests/test_czi_convert.py new file mode 100644 index 0000000..1ebd816 --- /dev/null +++ b/tests/test_czi_convert.py @@ -0,0 +1,260 @@ +"""Tests for src/czi_convert.py. The czifile reader is faked, so no real .czi is needed.""" + +from contextlib import contextmanager + +import numpy as np +import pytest +import tifffile + +from src import czi_convert as cc +from src.config import set_channel_aliases +from src.io_utils import load_raw_tiff_sample, match_channel_file + + +def make_xml(channels, px_um=0.5, z_um=2.0): + chans = "".join( + f'{n}' + f"{em}" + for i, (n, em) in enumerate(channels) + ) + return ( + "" + f"{chans}" + "" + f'{px_um * 1e-6}' + f'{px_um * 1e-6}' + f'{z_um * 1e-6}' + "" + ) + + +@pytest.fixture +def fake_czi(monkeypatch): + """Register what a path "contains": fake_czi(path, xml, [(dims, array), ...]).""" + store = {} + + @contextmanager + def fake_open(path): + xml, scenes = store[str(path)] + yield xml, [(dims, (lambda a=arr: a)) for dims, arr in scenes] + + monkeypatch.setattr(cc, "_open_czi", fake_open) + + def register(path, xml, scenes): + path.write_bytes(b"CZI") + store[str(path)] = (xml, scenes) + + yield register + set_channel_aliases(None) + + +THREE = [("DAPI", 460), ("EGFP", 520), ("Alexa 568", 600)] + + +def three_channel_array(h=8, w=6): + rng = np.random.default_rng(1) + return rng.integers(0, 60000, (3, h, w), dtype=np.uint16) + + +# ── channel identification ──────────────────────────────────────────────────── + + +def infos(*names, em=None): + return [ + cc.ChannelInfo(i, name=n, emission_nm=(em[i] if em else None)) for i, n in enumerate(names) + ] + + +def test_identify_by_name_and_alias(): + assert cc.identify_channels(infos("DAPI", "GFP", "rfp")) == ["DAPI", "FITC", "TRITC"] + + +def test_identify_long_alias_inside_name_but_short_alias_needs_exact_token(): + assert cc.identify_channels(infos("Calcofluor White"))[0] == "DAPI" + # "CW" must not match inside an unrelated word + assert cc.identify_channels(infos("Showcase"))[0] is None + + +def test_identify_uses_user_aliases(fake_czi): + set_channel_aliases({"DAPI": "cell_wall"}) + assert cc.identify_channels(infos("Cell_Wall stain"))[0] == "DAPI" + + +def test_identify_emission_fallback_and_each_channel_used_once(): + got = cc.identify_channels(infos("Ch1", "Ch2", "Ch3", em=[455, 525, 590])) + assert got == ["DAPI", "FITC", "TRITC"] + # two blue channels: only the first claims DAPI + assert cc.identify_channels(infos("a", "b", em=[450, 460])) == ["DAPI", None] + + +def test_identify_does_not_guess_without_evidence(): + assert cc.identify_channels(infos("Brightfield")) == [None] + + +# ── metadata ────────────────────────────────────────────────────────────────── + + +def test_parse_metadata_channels_and_pixel_size(): + m = cc.parse_metadata(make_xml(THREE, px_um=0.325, z_um=1.5)) + assert [c.name for c in m.channels] == ["DAPI", "EGFP", "Alexa 568"] + assert m.channels[1].emission_nm == 520 + assert m.pixel_size_um["X"] == pytest.approx(0.325) + assert m.pixel_size_um["Z"] == pytest.approx(1.5) + + +def test_parse_metadata_survives_garbage(): + m = cc.parse_metadata("not xml") + assert m.channels == [] and m.pixel_size_um == {} and m.xml == "not xml" + + +# ── file discovery / layout ─────────────────────────────────────────────────── + + +def test_find_and_plan(tmp_path): + (tmp_path / "root1.czi").write_bytes(b"") + (tmp_path / "UPPER.CZI").write_bytes(b"") + (tmp_path / "single").mkdir() + (tmp_path / "single" / "a.czi").write_bytes(b"") + (tmp_path / "multi").mkdir() + (tmp_path / "multi" / "x.czi").write_bytes(b"") + (tmp_path / "multi" / "y.czi").write_bytes(b"") + (tmp_path / ".hidden").mkdir() + (tmp_path / ".hidden" / "h.czi").write_bytes(b"") + (tmp_path / "notes.txt").write_text("x") + + czis = cc.find_czi_files(tmp_path) + assert {p.name for p in czis} == {"root1.czi", "UPPER.CZI", "a.czi", "x.czi", "y.czi"} + + plan = {p.name: cc.plan_sample(p, tmp_path, czis) for p in czis} + assert plan["root1.czi"] == (tmp_path / "root1", "root1") + assert plan["a.czi"] == (tmp_path / "single", "single") + assert plan["x.czi"] == (tmp_path / "multi_x", "multi_x") + assert plan["y.czi"] == (tmp_path / "multi_y", "multi_y") + + +def test_find_czi_missing_folder(tmp_path): + assert cc.find_czi_files(tmp_path / "nope") == [] + + +# ── conversion ──────────────────────────────────────────────────────────────── + + +def test_convert_writes_loader_compatible_files(tmp_path, fake_czi): + arr = three_channel_array() + fake_czi(tmp_path / "Sorghum_1.czi", make_xml(THREE), [("CYX", arr)]) + + (res,) = cc.convert_all(tmp_path) + assert res.error is None and not res.warnings + assert res.channel_map == [("DAPI", "DAPI"), ("EGFP", "FITC"), ("Alexa 568", "TRITC")] + + out = tmp_path / "Sorghum_1" + assert sorted(p.name for p in out.glob("*.ome.tif")) == [ + "Sorghum_1_raw_CH(DAPI)_CH1.ome.tif", + "Sorghum_1_raw_CH(FITC)_CH2.ome.tif", + "Sorghum_1_raw_CH(TRITC)_CH3.ome.tif", + ] + # the app's own loader finds each channel, in order, with pixel data intact + tifs = list(out.glob("*.tif*")) + assert match_channel_file(tifs, "FITC").name.startswith("Sorghum_1_raw_CH(FITC)") + stacked = load_raw_tiff_sample("Sorghum_1", tmp_path, ["TRITC", "FITC", "DAPI"]) + assert stacked.dtype == np.uint16 + np.testing.assert_array_equal(stacked[..., 2], arr[0]) # DAPI + np.testing.assert_array_equal(stacked[..., 1], arr[1]) # FITC + np.testing.assert_array_equal(stacked[..., 0], arr[2]) # TRITC + + +def test_convert_preserves_metadata(tmp_path, fake_czi): + xml = make_xml(THREE, px_um=0.325) + fake_czi(tmp_path / "s.czi", xml, [("CYX", three_channel_array())]) + cc.convert_all(tmp_path) + + with tifffile.TiffFile(tmp_path / "s" / "s_raw_CH(FITC)_CH2.ome.tif") as tf: + ome = tf.ome_metadata + assert 'PhysicalSizeX="0.325"' in ome + assert "EGFP" in ome # original channel name kept + assert (tmp_path / "s" / "s_czi_metadata.xml").read_text(encoding="utf-8") == xml + + +def test_unidentified_channel_is_kept_and_reported(tmp_path, fake_czi): + chans = [("DAPI", 460), ("Brightfield", 0), ("EGFP", 520)] + fake_czi(tmp_path / "s.czi", make_xml(chans), [("CYX", three_channel_array())]) + (res,) = cc.convert_all(tmp_path) + assert "s_raw_CH(Brightfield)_CH2.ome.tif" in [p.name for p in res.outputs] + assert any("Brightfield" in w for w in res.warnings) + assert any("TRITC" in w for w in res.warnings) # nothing identified as TRITC + + +def test_z_stack_max_projection_and_keep(tmp_path, fake_czi): + rng = np.random.default_rng(2) + arr = rng.integers(0, 5000, (3, 4, 8, 6), dtype=np.uint16) # C Z Y X + fake_czi(tmp_path / "z.czi", make_xml(THREE), [("CZYX", arr)]) + cc.convert_all(tmp_path) + f = tmp_path / "z" / "z_raw_CH(DAPI)_CH1.ome.tif" + np.testing.assert_array_equal(tifffile.imread(f), arr[0].max(axis=0)) + + cc.convert_all(tmp_path, z_mode="keep", overwrite=True) + assert tifffile.imread(f).shape == (4, 8, 6) + + +def test_single_channel_image_without_c_axis(tmp_path, fake_czi): + arr = np.ones((8, 6), dtype=np.uint8) + fake_czi(tmp_path / "one.czi", make_xml([("DAPI", 460)]), [("YX", arr)]) + (res,) = cc.convert_all(tmp_path) + assert [p.name for p in res.outputs] == ["one_raw_CH(DAPI)_CH1.ome.tif"] + assert tifffile.imread(res.outputs[0]).dtype == np.uint8 + + +def test_time_series_is_reported_not_converted(tmp_path, fake_czi): + arr = np.zeros((2, 3, 8, 6), dtype=np.uint16) + fake_czi(tmp_path / "t.czi", make_xml(THREE), [("TCYX", arr)]) + (res,) = cc.convert_all(tmp_path) + assert res.error and "'T'" in res.error and not res.outputs + + +def test_skip_already_converted_unless_overwrite(tmp_path, fake_czi): + fake_czi(tmp_path / "s.czi", make_xml(THREE), [("CYX", three_channel_array())]) + assert cc.convert_all(tmp_path)[0].outputs + again = cc.convert_all(tmp_path)[0] + assert again.skipped == "already converted" and not again.outputs + assert cc.convert_all(tmp_path, overwrite=True)[0].outputs + + +def test_multi_scene_gets_one_folder_per_scene(tmp_path, fake_czi): + a, b = three_channel_array(), three_channel_array() + fake_czi(tmp_path / "m.czi", make_xml(THREE), [("CYX", a), ("CYX", b)]) + cc.convert_all(tmp_path) + for i, arr in enumerate((a, b), start=1): + f = tmp_path / f"m_S{i}" / f"m_S{i}_raw_CH(DAPI)_CH1.ome.tif" + np.testing.assert_array_equal(tifffile.imread(f), arr[0]) + + +def test_nested_single_czi_converts_into_its_own_folder(tmp_path, fake_czi): + (tmp_path / "plantA").mkdir() + fake_czi(tmp_path / "plantA" / "scan.czi", make_xml(THREE), [("CYX", three_channel_array())]) + cc.convert_all(tmp_path) + assert (tmp_path / "plantA" / "plantA_raw_CH(DAPI)_CH1.ome.tif").is_file() + assert cc.convert_all(tmp_path)[0].skipped == "already converted" + + +def test_reader_failure_is_reported_per_file(tmp_path, fake_czi): + fake_czi(tmp_path / "ok.czi", make_xml(THREE), [("CYX", three_channel_array())]) + (tmp_path / "bad.czi").write_bytes(b"junk") # not registered -> fake reader raises KeyError + results = {r.czi.name: r for r in cc.convert_all(tmp_path)} + assert results["bad.czi"].error + assert results["ok.czi"].outputs + + +def test_missing_czifile_gives_install_hint(tmp_path, monkeypatch): + import builtins + + real_import = builtins.__import__ + + def no_czifile(name, *args, **kwargs): + if name == "czifile": + raise ImportError("no czifile") + return real_import(name, *args, **kwargs) + + monkeypatch.setattr(builtins, "__import__", no_czifile) + (tmp_path / "x.czi").write_bytes(b"") + (res,) = cc.convert_all(tmp_path) + assert res.error and "pip install czifile" in res.error From 3c0bb96d301a977e1aa4867dc9ceea9388bf5058 Mon Sep 17 00:00:00 2001 From: Elizabeth Wright Date: Wed, 2 Dec 2026 15:11:33 -0800 Subject: [PATCH 3/6] CLI for czi to tiff --- czi_to_tiff.py | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 czi_to_tiff.py diff --git a/czi_to_tiff.py b/czi_to_tiff.py new file mode 100644 index 0000000..b236f22 --- /dev/null +++ b/czi_to_tiff.py @@ -0,0 +1,57 @@ +"""Split Zeiss .czi files into per-channel TIFFs in the layout RADIX expects. + + python czi_to_tiff.py data # every .czi under data/ + python czi_to_tiff.py data --z keep --overwrite + +Same conversion as the app's "0 · Get the right files" tab (see src/czi_convert.py). +Needs: pip install czifile +""" + +import argparse +import sys +from pathlib import Path + +from src.config import load_channel_aliases_file, set_channel_aliases +from src.czi_convert import convert_all, find_czi_files + + +def main(): + p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter) + p.add_argument("data_dir", type=Path, help="Folder with .czi files (root or in subfolders)") + p.add_argument("--z", choices=["max", "keep"], default="max", help="Z-stack handling") + p.add_argument("--overwrite", action="store_true", help="Redo files already converted") + for ch in ("dapi", "fitc", "tritc"): + p.add_argument( + f"--{ch}-name", + default=None, + help=f"Extra name(s) a CZI channel may have for {ch.upper()}, comma-separated.", + ) + args = p.parse_args() + + data_dir = args.data_dir.resolve() + aliases = load_channel_aliases_file(data_dir) + for ch in ("DAPI", "FITC", "TRITC"): + cli = getattr(args, f"{ch.lower()}_name") + if cli: + aliases[ch] = [s.strip() for s in cli.split(",") if s.strip()] + aliases.get(ch, []) + set_channel_aliases(aliases) + + if not find_czi_files(data_dir): + sys.exit(f"No .czi files found under {data_dir}") + + failed = 0 + for r in convert_all(data_dir, args.z, args.overwrite): + if r.error: + failed += 1 + print(f"FAILED {r.czi.name}: {r.error}") + elif r.skipped: + print(f"skipped {r.czi.name} ({r.skipped})") + else: + print(f"ok {r.czi.name} -> {len(r.outputs)} TIFF(s) in {r.outputs[0].parent}") + for w in r.warnings: + print(f" warning: {w}") + sys.exit(1 if failed else 0) + + +if __name__ == "__main__": + main() From 350fe9a20c688b3b384e7dfe6e3bdd08414033d6 Mon Sep 17 00:00:00 2001 From: Elizabeth Wright Date: Wed, 2 Dec 2026 15:11:46 -0800 Subject: [PATCH 4/6] tab 0 --- GUI.py | 100 +++++++++++++++++++++++++++++++++++++- tests/test_gui_apptest.py | 12 +++++ 2 files changed, 110 insertions(+), 2 deletions(-) diff --git a/GUI.py b/GUI.py index b237718..17ea195 100644 --- a/GUI.py +++ b/GUI.py @@ -13,6 +13,12 @@ load_channel_aliases_file, set_channel_aliases, ) +from src.czi_convert import ( + convert_all, + find_czi_files, + is_converted, + plan_sample, +) from src.intensity_quant import ( BARRIER_TISSUES, compute_threshold_percentile_suggestions, @@ -511,11 +517,101 @@ def suggestions_panel(region, threshold_mode): # ------------------------- # TABS # ------------------------- -tab_seg, tab_tune, tab_batch = st.tabs( - ["1 · Segmentation", "2 · Threshold tuning", "3 · Batch & export"] +tab_files, tab_seg, tab_tune, tab_batch = st.tabs( + ["0 · Get the right files", "1 · Segmentation", "2 · Threshold tuning", "3 · Batch & export"] ) +# ========================= +# TAB 0: GET THE RIGHT FILES (.czi -> per-channel TIFFs) +# ========================= +with tab_files: + st.markdown("### Get the right files") + st.caption( + "RADIX reads one TIFF per channel. If your images are Zeiss `.czi` files, this " + "finds them in the image folder (at its root or inside sample folders) and splits " + "them into DAPI / FITC / TRITC TIFFs. Your `.czi` files are never modified. " + "Pixel size and the original metadata are kept." + ) + + for _msg in st.session_state.pop("czi_flash", []): + _kind, _text = _msg + getattr(st, _kind)(_text) + + _czis = find_czi_files(DATA_DIR) + if not _czis: + st.info( + f"No `.czi` files found in `{DATA_DIR}`. If your images are already TIFFs, skip to tab 1." + ) + else: + _rows = [] + for _c in _czis: + _out, _name = plan_sample(_c, DATA_DIR, _czis) + _rows.append( + { + ".czi file": str(_c.relative_to(DATA_DIR)), + "Sample folder": _out.name, + "Status": "already converted" if is_converted(_out, _name) else "to convert", + } + ) + _todo = sum(r["Status"] == "to convert" for r in _rows) + st.caption(f"{len(_czis)} `.czi` file(s) found, {_todo} still to convert.") + st.dataframe(pd.DataFrame(_rows), hide_index=True, width="stretch") + + _zc, _oc = st.columns(2) + with _zc: + _z_mode = st.radio( + "Z-stacks", + ["max", "keep"], + format_func=lambda m: ( + "Max projection (recommended)" if m == "max" else "Keep every plane (3D)" + ), + key="czi_z_mode", + help="The model works on flat 2D images, so z-stacks are flattened by default.", + ) + with _oc: + _overwrite = st.checkbox( + "Redo files that are already converted", + value=False, + key="czi_overwrite", + ) + st.caption( + "Channels are identified with the DAPI / FITC / TRITC names (including any you " + 'added under "Channel file names" in the sidebar), then by emission wavelength.' + ) + + if st.button("Convert .czi files", type="primary", disabled=not (_todo or _overwrite)): + _bar = st.progress(0.0, text="Starting...") + + def _progress(done, total, czi): + _bar.progress( + done / max(total, 1), + text=f"Converting {czi.name}..." if czi else "Done", + ) + + _results = convert_all(DATA_DIR, _z_mode, _overwrite, _progress) + _bar.empty() + + _msgs = [] + _ok = [r for r in _results if r.outputs] + if _ok: + _msgs.append( + ( + "success", + f"Converted {len(_ok)} file(s) into " + f"{sum(len(r.outputs) for r in _ok)} channel TIFF(s).", + ) + ) + for _r in _results: + if _r.error: + _msgs.append(("error", f"`{_r.czi.name}` failed: {_r.error}")) + for _w in _r.warnings: + _msgs.append(("warning", f"`{_r.czi.name}`: {_w}")) + st.session_state["czi_flash"] = _msgs + scan_image_folders.clear() + st.rerun() + + # ========================= # TAB 1: SEGMENTATION # ========================= diff --git a/tests/test_gui_apptest.py b/tests/test_gui_apptest.py index 3f124ae..07c09b8 100644 --- a/tests/test_gui_apptest.py +++ b/tests/test_gui_apptest.py @@ -20,6 +20,7 @@ def test_no_predictions_shows_guidance(monkeypatch, tmp_path): app.run() assert not app.exception assert [t.label for t in app.tabs] == [ + "0 · Get the right files", "1 · Segmentation", "2 · Threshold tuning", "3 · Batch & export", @@ -27,6 +28,17 @@ def test_no_predictions_shows_guidance(monkeypatch, tmp_path): assert any("No prediction files found" in i.value for i in app.info) +def test_files_tab_lists_czi_files(monkeypatch, tmp_path): + (tmp_path / "scan_01.czi").write_bytes(b"") + monkeypatch.chdir(APP_DIR) + app = AppTest.from_file(str(APP_DIR / "GUI.py"), default_timeout=60) + app.session_state["data_dir"] = str(tmp_path) + app.run() + assert not app.exception + assert any("1 `.czi` file(s) found" in c.value for c in app.caption) + assert [b for b in app.button if b.label == "Convert .czi files"] + + def test_loads_without_errors(at): assert not at.exception assert not at.error From 966c1e85452afbd53890b7456c77621c7539c1fd Mon Sep 17 00:00:00 2001 From: Elizabeth Wright Date: Wed, 2 Dec 2026 15:11:52 -0800 Subject: [PATCH 5/6] readme update --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index d7a5e6a..a321615 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,14 @@ alternate names are also recognized: | FITC | `FITC`, `GFP` | | TRITC | `TRITC`, `RFP` | +**Have Zeiss `.czi` files instead?** Put them in the `data` folder (directly, +or inside a subfolder) and open the **0 · Get the right files** tab, then click +*Convert .czi files*. Each one is split into DAPI / FITC / TRITC TIFFs in its +own sample folder, with pixel size kept in the TIFFs and the full CZI metadata +saved next to them as `_czi_metadata.xml`. Your `.czi` files are not +changed. Z-stacks are flattened by max projection. The same conversion is +available from a terminal: `python czi_to_tiff.py data`. + A sample is skipped if all 3 channels aren't found — the app will tell you which ones are missing. If your imaging setup produces a different channel (e.g. brightfield) instead of one of the three above, contact Stefan before From 11467b1192af45e6482dc7f967f0764c96866bc3 Mon Sep 17 00:00:00 2001 From: Elizabeth Wright Date: Thu, 3 Dec 2026 09:27:56 -0800 Subject: [PATCH 6/6] typechecking error fix --- src/czi_convert.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/czi_convert.py b/src/czi_convert.py index 04612d1..e9da1ea 100644 --- a/src/czi_convert.py +++ b/src/czi_convert.py @@ -172,7 +172,7 @@ def identify_channels(infos: list[ChannelInfo], channels=CHANNELS) -> list[str | def find_czi_files(data_dir) -> list[Path]: """Every .czi under ``data_dir`` (root or any subfolder), hidden folders skipped.""" root = Path(data_dir) - found = [] + found: list[Path] = [] if not root.is_dir(): return found for dirpath, dirnames, filenames in os.walk(root):