napari-virtual-reader 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- napari_virtual_reader/__init__.py +6 -0
- napari_virtual_reader/_metadata.py +174 -0
- napari_virtual_reader/_reader.py +389 -0
- napari_virtual_reader/_widget.py +219 -0
- napari_virtual_reader/napari.yaml +37 -0
- napari_virtual_reader-0.0.1.dist-info/METADATA +174 -0
- napari_virtual_reader-0.0.1.dist-info/RECORD +10 -0
- napari_virtual_reader-0.0.1.dist-info/WHEEL +4 -0
- napari_virtual_reader-0.0.1.dist-info/entry_points.txt +2 -0
- napari_virtual_reader-0.0.1.dist-info/licenses/LICENSE +27 -0
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""Read-only inspector for virtual Zarr structure and selected-layer metadata."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from qtpy.QtCore import Qt
|
|
8
|
+
from qtpy.QtWidgets import (
|
|
9
|
+
QHBoxLayout,
|
|
10
|
+
QLabel,
|
|
11
|
+
QLineEdit,
|
|
12
|
+
QSplitter,
|
|
13
|
+
QStyle,
|
|
14
|
+
QTabWidget,
|
|
15
|
+
QTextEdit,
|
|
16
|
+
QToolButton,
|
|
17
|
+
QTreeWidget,
|
|
18
|
+
QTreeWidgetItem,
|
|
19
|
+
QVBoxLayout,
|
|
20
|
+
QWidget,
|
|
21
|
+
)
|
|
22
|
+
from superqt.utils import ensure_main_thread
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def ensure_metadata_panel(viewer: Any) -> "MetadataPanel":
|
|
26
|
+
"""Share one right-hand inspector between the opener and reader workflows."""
|
|
27
|
+
panels = viewer.window._qt_window.findChildren(MetadataPanel)
|
|
28
|
+
if panels:
|
|
29
|
+
panels[0].dock.show()
|
|
30
|
+
return panels[0]
|
|
31
|
+
panel = MetadataPanel()
|
|
32
|
+
panel.viewer = viewer
|
|
33
|
+
panel.dock = viewer.window.add_dock_widget(panel, name="Virtual Zarr metadata", area="right")
|
|
34
|
+
viewer.layers.selection.events.active.connect(panel._active_layer_changed)
|
|
35
|
+
panel._active_layer_changed()
|
|
36
|
+
return panel
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@ensure_main_thread
|
|
40
|
+
def prepare_metadata_inspectors() -> None:
|
|
41
|
+
"""Attach reader-only loads to live viewers, even when called by a worker."""
|
|
42
|
+
from napari import Viewer
|
|
43
|
+
|
|
44
|
+
for viewer in tuple(Viewer._instances):
|
|
45
|
+
ensure_metadata_panel(viewer)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class MetadataPanel(QWidget):
|
|
49
|
+
"""Browse source hierarchy and attributes without accessing array values."""
|
|
50
|
+
|
|
51
|
+
def __init__(self) -> None:
|
|
52
|
+
super().__init__()
|
|
53
|
+
self.setMinimumWidth(280)
|
|
54
|
+
layout = QVBoxLayout(self)
|
|
55
|
+
self.source = QLabel()
|
|
56
|
+
self.source.setWordWrap(True)
|
|
57
|
+
self.source.setTextFormat(Qt.PlainText)
|
|
58
|
+
layout.addWidget(self.source)
|
|
59
|
+
row = QHBoxLayout()
|
|
60
|
+
self.search = QLineEdit()
|
|
61
|
+
self.search.setPlaceholderText("Filter metadata")
|
|
62
|
+
self.search.setClearButtonEnabled(True)
|
|
63
|
+
row.addWidget(self.search)
|
|
64
|
+
self.tabs = QTabWidget()
|
|
65
|
+
self.structure = QTreeWidget()
|
|
66
|
+
self.structure.setHeaderLabels(["Zarr path", "Layout"])
|
|
67
|
+
self.metadata = QTreeWidget()
|
|
68
|
+
self.metadata.setHeaderLabels(["Property", "Value"])
|
|
69
|
+
self.trees = (self.structure, self.metadata)
|
|
70
|
+
for tooltip, icon, method in (
|
|
71
|
+
("Expand all", QStyle.SP_ArrowDown, "expandAll"),
|
|
72
|
+
("Collapse all", QStyle.SP_ArrowUp, "collapseAll"),
|
|
73
|
+
):
|
|
74
|
+
button = QToolButton()
|
|
75
|
+
button.setIcon(self.style().standardIcon(icon))
|
|
76
|
+
button.setToolTip(tooltip)
|
|
77
|
+
button.setAccessibleName(tooltip)
|
|
78
|
+
button.clicked.connect(lambda checked=False, method=method: getattr(self.tabs.currentWidget(), method)())
|
|
79
|
+
row.addWidget(button)
|
|
80
|
+
layout.addLayout(row)
|
|
81
|
+
self.tabs.addTab(self.structure, "Zarr structure")
|
|
82
|
+
self.tabs.addTab(self.metadata, "Metadata")
|
|
83
|
+
self.detail = QTextEdit()
|
|
84
|
+
self.detail.setReadOnly(True)
|
|
85
|
+
self.detail.setMinimumHeight(100)
|
|
86
|
+
splitter = QSplitter(Qt.Vertical)
|
|
87
|
+
splitter.addWidget(self.tabs)
|
|
88
|
+
splitter.addWidget(self.detail)
|
|
89
|
+
splitter.setStretchFactor(0, 3)
|
|
90
|
+
splitter.setStretchFactor(1, 1)
|
|
91
|
+
layout.addWidget(splitter)
|
|
92
|
+
for tree in self.trees:
|
|
93
|
+
tree.setAlternatingRowColors(True)
|
|
94
|
+
tree.setUniformRowHeights(True)
|
|
95
|
+
tree.setColumnWidth(0, 170)
|
|
96
|
+
tree.currentItemChanged.connect(self._selected)
|
|
97
|
+
self.search.textChanged.connect(self._filter)
|
|
98
|
+
self.tabs.currentChanged.connect(lambda: self.detail.clear())
|
|
99
|
+
|
|
100
|
+
def _property(self, parent: Any, name: str, value: Any) -> None:
|
|
101
|
+
"""Represent structured attributes as expandable keys and indexed lists."""
|
|
102
|
+
if isinstance(value, dict):
|
|
103
|
+
summary = f"{len(value)} properties"
|
|
104
|
+
children = value.items()
|
|
105
|
+
elif isinstance(value, (list, tuple)):
|
|
106
|
+
summary = f"{len(value)} items"
|
|
107
|
+
children = enumerate(value)
|
|
108
|
+
else:
|
|
109
|
+
summary = str(value)
|
|
110
|
+
children = ()
|
|
111
|
+
item = QTreeWidgetItem(parent, [str(name), summary[:200]])
|
|
112
|
+
item.setData(0, Qt.UserRole, value)
|
|
113
|
+
for key, child in children:
|
|
114
|
+
self._property(item, str(key), child)
|
|
115
|
+
|
|
116
|
+
def _active_layer_changed(self, event=None) -> None:
|
|
117
|
+
"""Follow image selection independently of the optional opener widget."""
|
|
118
|
+
self.set_layer(self.viewer.layers.selection.active)
|
|
119
|
+
|
|
120
|
+
def _node(self, parent: Any, name: str, node: dict) -> None:
|
|
121
|
+
"""Show array shape/dtype and make chunk grids/codecs inspectable."""
|
|
122
|
+
metadata = node.get("metadata", {})
|
|
123
|
+
layout = "group"
|
|
124
|
+
if node["kind"] == "array":
|
|
125
|
+
shape = " x ".join(str(size) for size in metadata["shape"])
|
|
126
|
+
layout = f"{shape} | {metadata.get('data_type', metadata.get('dtype', ''))}"
|
|
127
|
+
item = QTreeWidgetItem(parent, [name, layout])
|
|
128
|
+
properties = metadata if node["kind"] == "array" else node["attributes"]
|
|
129
|
+
item.setData(0, Qt.UserRole, properties)
|
|
130
|
+
self._property(item, "Array metadata" if metadata else "Attributes", properties)
|
|
131
|
+
for child in node.get("children", []):
|
|
132
|
+
self._node(item, child["name"], child)
|
|
133
|
+
|
|
134
|
+
def set_layer(self, layer: Any) -> None:
|
|
135
|
+
"""Display one selected layer, clearing stale metadata for other layers."""
|
|
136
|
+
for tree in self.trees:
|
|
137
|
+
tree.clear()
|
|
138
|
+
self.detail.clear()
|
|
139
|
+
self.source.clear()
|
|
140
|
+
metadata = getattr(layer, "metadata", {})
|
|
141
|
+
if not isinstance(metadata, dict) or "zarr_structure" not in metadata:
|
|
142
|
+
return
|
|
143
|
+
source = metadata.get("source", "")
|
|
144
|
+
self.source.setText(Path(source).name)
|
|
145
|
+
self.source.setToolTip(source)
|
|
146
|
+
self._node(self.structure, "/", metadata["zarr_structure"])
|
|
147
|
+
for key, value in metadata.items():
|
|
148
|
+
if key != "zarr_structure":
|
|
149
|
+
self._property(self.metadata, key, value)
|
|
150
|
+
self.structure.expandToDepth(1)
|
|
151
|
+
self.metadata.expandToDepth(0)
|
|
152
|
+
self._filter(self.search.text())
|
|
153
|
+
|
|
154
|
+
def _selected(self, item: Any, previous: Any) -> None:
|
|
155
|
+
"""Expose complete, selectable values without widening the tree columns."""
|
|
156
|
+
self.detail.setPlainText(
|
|
157
|
+
json.dumps(item.data(0, Qt.UserRole), indent=2, ensure_ascii=True, default=str) if item else ""
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
def _filter(self, text: str) -> None:
|
|
161
|
+
"""Retain matching rows and their ancestors in both inspector views."""
|
|
162
|
+
text = text.casefold()
|
|
163
|
+
|
|
164
|
+
def visit(item: QTreeWidgetItem) -> bool:
|
|
165
|
+
child_matches = [visit(item.child(index)) for index in range(item.childCount())]
|
|
166
|
+
matches = not text or text in f"{item.text(0)} {item.text(1)}".casefold() or any(child_matches)
|
|
167
|
+
item.setHidden(not matches)
|
|
168
|
+
if text and any(child_matches):
|
|
169
|
+
item.setExpanded(True)
|
|
170
|
+
return matches
|
|
171
|
+
|
|
172
|
+
for tree in self.trees:
|
|
173
|
+
for index in range(tree.topLevelItemCount()):
|
|
174
|
+
visit(tree.topLevelItem(index))
|
|
@@ -0,0 +1,389 @@
|
|
|
1
|
+
"""Read reference-backed OME images without converting or copying their pixels."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import sys
|
|
5
|
+
from collections.abc import Iterator
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from tempfile import TemporaryDirectory
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
import dask.array as da
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
IMAGE_SUFFIXES = (
|
|
14
|
+
".czi",
|
|
15
|
+
".tif",
|
|
16
|
+
".tiff",
|
|
17
|
+
".svs",
|
|
18
|
+
".ndpi",
|
|
19
|
+
".nd2",
|
|
20
|
+
".lif",
|
|
21
|
+
".ims",
|
|
22
|
+
".vsi",
|
|
23
|
+
".qptiff",
|
|
24
|
+
".dcm",
|
|
25
|
+
".dicom",
|
|
26
|
+
".nii",
|
|
27
|
+
".nii.gz",
|
|
28
|
+
".nrrd",
|
|
29
|
+
".nhdr",
|
|
30
|
+
".mrc",
|
|
31
|
+
".map",
|
|
32
|
+
".vzip",
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class _ChunkedArray:
|
|
37
|
+
"""Adapt regular and rectilinear Zarr grids to Dask's array protocol."""
|
|
38
|
+
|
|
39
|
+
def __init__(self, array: Any) -> None:
|
|
40
|
+
self._array = array
|
|
41
|
+
self.shape = array.shape
|
|
42
|
+
self.dtype = array.dtype
|
|
43
|
+
self.ndim = array.ndim
|
|
44
|
+
self.chunks = getattr(array, "read_chunk_sizes", None)
|
|
45
|
+
if self.chunks is None:
|
|
46
|
+
self.chunks = array.chunks
|
|
47
|
+
|
|
48
|
+
def __getitem__(self, selection: Any) -> np.ndarray:
|
|
49
|
+
"""Read only the slice requested by a Dask task."""
|
|
50
|
+
return self._array[selection]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _image_groups(group: Any, name: str = "") -> Iterator[tuple[str, Any, dict]]:
|
|
54
|
+
"""Find OME 0.4/0.5 image groups, including scenes and plate fields."""
|
|
55
|
+
attributes = dict(group.attrs)
|
|
56
|
+
ome = attributes.get("ome", attributes)
|
|
57
|
+
if ome.get("multiscales"):
|
|
58
|
+
yield name, group, ome
|
|
59
|
+
return
|
|
60
|
+
children = sorted(
|
|
61
|
+
group.groups(),
|
|
62
|
+
key=lambda item: (
|
|
63
|
+
not item[0].isdecimal(),
|
|
64
|
+
int(item[0]) if item[0].isdecimal() else item[0],
|
|
65
|
+
),
|
|
66
|
+
)
|
|
67
|
+
for child_name, child in children:
|
|
68
|
+
if child_name not in {"refkv_source", "tiles", "labels"}:
|
|
69
|
+
yield from _image_groups(child, f"{name}/{child_name}".strip("/"))
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _lazy_array(array: Any) -> da.Array:
|
|
73
|
+
"""Build a graph without probing pixels or using Zarr's regular-only chunks."""
|
|
74
|
+
adapted = _ChunkedArray(array)
|
|
75
|
+
return da.from_array(
|
|
76
|
+
adapted,
|
|
77
|
+
chunks=adapted.chunks,
|
|
78
|
+
meta=np.empty((0,) * array.ndim, dtype=array.dtype),
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _contrast_limits(dtype: np.dtype, channel: dict) -> tuple[float, float]:
|
|
83
|
+
"""Use embedded windows or dtype bounds instead of scanning a lazy volume."""
|
|
84
|
+
fallback = (0.0, 1.0)
|
|
85
|
+
if np.issubdtype(dtype, np.integer):
|
|
86
|
+
limits = np.iinfo(dtype)
|
|
87
|
+
fallback = (float(limits.min), float(limits.max))
|
|
88
|
+
window = channel.get("window", {})
|
|
89
|
+
low, high = window.get("start"), window.get("end")
|
|
90
|
+
if low is not None and high is not None:
|
|
91
|
+
if np.isfinite(low) and np.isfinite(high) and low < high:
|
|
92
|
+
return float(low), float(high)
|
|
93
|
+
return fallback
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _stack_czi_scenes(
|
|
97
|
+
layers: list[tuple[Any, dict, str]], source: Path
|
|
98
|
+
) -> list[tuple[Any, dict, str]]:
|
|
99
|
+
"""Stack compatible CZI series per channel while retaining scene provenance."""
|
|
100
|
+
channels = {}
|
|
101
|
+
for layer in layers:
|
|
102
|
+
metadata = layer[1]["metadata"]
|
|
103
|
+
key = (metadata["multiscale_index"], metadata["channel"])
|
|
104
|
+
channels.setdefault(key, []).append(layer)
|
|
105
|
+
result = []
|
|
106
|
+
for scenes in channels.values():
|
|
107
|
+
first = scenes[0][1]
|
|
108
|
+
levels = [
|
|
109
|
+
data if kwargs["multiscale"] else [data] for data, kwargs, _ in scenes
|
|
110
|
+
]
|
|
111
|
+
compatible = all(
|
|
112
|
+
kwargs["axis_labels"] == first["axis_labels"]
|
|
113
|
+
and np.allclose(kwargs["scale"], first["scale"])
|
|
114
|
+
and len(scene_levels) == len(levels[0])
|
|
115
|
+
and all(
|
|
116
|
+
level.shape == reference.shape and level.dtype == reference.dtype
|
|
117
|
+
for level, reference in zip(scene_levels, levels[0])
|
|
118
|
+
)
|
|
119
|
+
for scene_levels, (_, kwargs, _) in zip(levels, scenes)
|
|
120
|
+
)
|
|
121
|
+
if (
|
|
122
|
+
len(scenes) < 2
|
|
123
|
+
or "s" in (axis.lower() for axis in first["axis_labels"])
|
|
124
|
+
or not compatible
|
|
125
|
+
):
|
|
126
|
+
result.extend(scenes)
|
|
127
|
+
continue
|
|
128
|
+
stacked = [da.stack(level, axis=0) for level in zip(*levels)]
|
|
129
|
+
metadata = {
|
|
130
|
+
**first["metadata"],
|
|
131
|
+
"scenes": [
|
|
132
|
+
{
|
|
133
|
+
**kwargs["metadata"],
|
|
134
|
+
"scale": kwargs["scale"],
|
|
135
|
+
"translate": kwargs["translate"],
|
|
136
|
+
}
|
|
137
|
+
for _, kwargs, _ in scenes
|
|
138
|
+
],
|
|
139
|
+
}
|
|
140
|
+
kwargs = {
|
|
141
|
+
**first,
|
|
142
|
+
"name": f"{source.stem} | {metadata['channel_label']}",
|
|
143
|
+
"axis_labels": ("S",) + first["axis_labels"],
|
|
144
|
+
"scale": (1.0,) + first["scale"],
|
|
145
|
+
"translate": (0.0,)
|
|
146
|
+
+ tuple(
|
|
147
|
+
origin
|
|
148
|
+
if all(scene[1]["translate"][index] == origin for scene in scenes)
|
|
149
|
+
else 0.0
|
|
150
|
+
for index, origin in enumerate(first["translate"])
|
|
151
|
+
),
|
|
152
|
+
"metadata": metadata,
|
|
153
|
+
}
|
|
154
|
+
result.append((stacked if first["multiscale"] else stacked[0], kwargs, "image"))
|
|
155
|
+
return result
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _zarr_structure(group: Any) -> dict:
|
|
159
|
+
"""Snapshot groups, array layout and attributes without fetching pixels."""
|
|
160
|
+
children = []
|
|
161
|
+
for name, node in sorted(
|
|
162
|
+
group.members(),
|
|
163
|
+
key=lambda item: (
|
|
164
|
+
not item[0].isdecimal(),
|
|
165
|
+
int(item[0]) if item[0].isdecimal() else item[0],
|
|
166
|
+
),
|
|
167
|
+
):
|
|
168
|
+
if hasattr(node, "shape"):
|
|
169
|
+
children.append(
|
|
170
|
+
{"name": name, "kind": "array", "metadata": node.metadata.to_dict()}
|
|
171
|
+
)
|
|
172
|
+
else:
|
|
173
|
+
children.append({"name": name, **_zarr_structure(node)})
|
|
174
|
+
return {"kind": "group", "attributes": dict(group.attrs), "children": children}
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _layers(root: Any, source: Path) -> list[tuple[Any, dict, str]]:
|
|
178
|
+
"""Translate OME axes, stored pyramids, transforms and channels to layers."""
|
|
179
|
+
from napari.utils.colormaps import Colormap
|
|
180
|
+
|
|
181
|
+
layers = []
|
|
182
|
+
for group_name, group, ome in _image_groups(root):
|
|
183
|
+
for series_index, multiscale in enumerate(ome["multiscales"]):
|
|
184
|
+
axes = tuple(
|
|
185
|
+
(axis if isinstance(axis, str) else axis["name"]).lower()
|
|
186
|
+
for axis in multiscale["axes"]
|
|
187
|
+
)
|
|
188
|
+
if len(set(axes)) != len(axes) or not {"y", "x"}.issubset(axes):
|
|
189
|
+
raise ValueError(f"Unsupported image axes in {group_name}: {axes}")
|
|
190
|
+
datasets = multiscale["datasets"]
|
|
191
|
+
arrays = [group[dataset["path"]] for dataset in datasets]
|
|
192
|
+
if not arrays or any(array.ndim != len(axes) for array in arrays):
|
|
193
|
+
raise ValueError(f"Invalid OME image dimensions in {group_name}")
|
|
194
|
+
channel_axis = axes.index("c") if "c" in axes else None
|
|
195
|
+
channel_count = (
|
|
196
|
+
arrays[0].shape[channel_axis] if channel_axis is not None else 1
|
|
197
|
+
)
|
|
198
|
+
if channel_axis is not None and any(
|
|
199
|
+
array.shape[channel_axis] != channel_count for array in arrays
|
|
200
|
+
):
|
|
201
|
+
raise ValueError(f"Channel counts differ across levels in {group_name}")
|
|
202
|
+
remaining_axes = tuple(axis for axis in axes if axis != "c")
|
|
203
|
+
display_axes = tuple(
|
|
204
|
+
axis for axis in remaining_axes if axis not in {"y", "x"}
|
|
205
|
+
) + ("y", "x")
|
|
206
|
+
permutation = tuple(remaining_axes.index(axis) for axis in display_axes)
|
|
207
|
+
scale = np.ones(len(axes))
|
|
208
|
+
translate = np.zeros(len(axes))
|
|
209
|
+
transforms = datasets[0].get(
|
|
210
|
+
"coordinateTransformations", []
|
|
211
|
+
) + multiscale.get("coordinateTransformations", [])
|
|
212
|
+
for transform in transforms:
|
|
213
|
+
if transform["type"] == "scale":
|
|
214
|
+
factor = np.asarray(transform["scale"])
|
|
215
|
+
scale *= factor
|
|
216
|
+
translate *= factor
|
|
217
|
+
elif transform["type"] == "translation":
|
|
218
|
+
translate += np.asarray(transform["translation"])
|
|
219
|
+
else:
|
|
220
|
+
raise ValueError(f"Unsupported OME transform: {transform['type']}")
|
|
221
|
+
lazy_levels = [_lazy_array(array) for array in arrays]
|
|
222
|
+
channels = ome.get("omero", {}).get("channels", [])
|
|
223
|
+
for channel_index in range(channel_count):
|
|
224
|
+
selection = tuple(
|
|
225
|
+
channel_index if axis == "c" else slice(None) for axis in axes
|
|
226
|
+
)
|
|
227
|
+
levels = [
|
|
228
|
+
level[selection].transpose(permutation) for level in lazy_levels
|
|
229
|
+
]
|
|
230
|
+
channel = (
|
|
231
|
+
channels[channel_index] if channel_index < len(channels) else {}
|
|
232
|
+
)
|
|
233
|
+
colormap = "gray"
|
|
234
|
+
color = channel.get("color", "")
|
|
235
|
+
if isinstance(color, str) and len(color) == 6:
|
|
236
|
+
try:
|
|
237
|
+
rgb = [
|
|
238
|
+
int(color[start : start + 2], 16) / 255
|
|
239
|
+
for start in (0, 2, 4)
|
|
240
|
+
]
|
|
241
|
+
colormap = Colormap([[0, 0, 0], rgb], name=f"refkv_{color}")
|
|
242
|
+
except ValueError:
|
|
243
|
+
pass
|
|
244
|
+
series_name = multiscale.get("name") or group_name or source.stem
|
|
245
|
+
if series_index:
|
|
246
|
+
series_name = f"{series_name}/{series_index}"
|
|
247
|
+
label = channel.get("label", f"Channel {channel_index}")
|
|
248
|
+
kwargs = {
|
|
249
|
+
"name": f"{source.stem} | {series_name} | {label}",
|
|
250
|
+
"axis_labels": display_axes,
|
|
251
|
+
"scale": tuple(scale[axes.index(axis)] for axis in display_axes),
|
|
252
|
+
"translate": tuple(
|
|
253
|
+
translate[axes.index(axis)] for axis in display_axes
|
|
254
|
+
),
|
|
255
|
+
"contrast_limits": _contrast_limits(arrays[0].dtype, channel),
|
|
256
|
+
"colormap": colormap,
|
|
257
|
+
"blending": "additive",
|
|
258
|
+
"multiscale": len(levels) > 1,
|
|
259
|
+
"rgb": False,
|
|
260
|
+
"metadata": {
|
|
261
|
+
"source": str(source),
|
|
262
|
+
"series": group_name,
|
|
263
|
+
"multiscale_index": series_index,
|
|
264
|
+
"channel": channel_index,
|
|
265
|
+
"channel_label": label,
|
|
266
|
+
"ome": ome,
|
|
267
|
+
},
|
|
268
|
+
}
|
|
269
|
+
layers.append(
|
|
270
|
+
(levels if len(levels) > 1 else levels[0], kwargs, "image")
|
|
271
|
+
)
|
|
272
|
+
if not layers:
|
|
273
|
+
raise ValueError("refkv found no supported OME image series in this file.")
|
|
274
|
+
if root.attrs.get("refkv_zarrified", {}).get("profile") == "czi":
|
|
275
|
+
layers = _stack_czi_scenes(layers, source)
|
|
276
|
+
structure = _zarr_structure(root)
|
|
277
|
+
for _, kwargs, _ in layers:
|
|
278
|
+
kwargs["metadata"]["zarr_structure"] = structure
|
|
279
|
+
return layers
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def read_images(path: str | list[str]) -> list[tuple[Any, dict, str]]:
|
|
283
|
+
"""Open local images or VZIP archives as lazy virtual OME-Zarr layers.
|
|
284
|
+
|
|
285
|
+
Args:
|
|
286
|
+
path: One local source path or a list of source paths.
|
|
287
|
+
|
|
288
|
+
Returns:
|
|
289
|
+
napari layer-data tuples containing lazy arrays and display metadata.
|
|
290
|
+
|
|
291
|
+
Raises:
|
|
292
|
+
FileNotFoundError: A source is not an existing file.
|
|
293
|
+
ValueError: Image axes, transforms or OME metadata are unsupported.
|
|
294
|
+
|
|
295
|
+
Notes:
|
|
296
|
+
Raw images are virtualized in memory. No archive or converted pixels
|
|
297
|
+
are written. Sources must remain available while layers are being used.
|
|
298
|
+
"""
|
|
299
|
+
import refkv.zarr
|
|
300
|
+
import zarr
|
|
301
|
+
from refkv.zarrify import zarrify
|
|
302
|
+
|
|
303
|
+
paths = path if isinstance(path, list) else [path]
|
|
304
|
+
layers = []
|
|
305
|
+
for item in paths:
|
|
306
|
+
source = Path(item).expanduser().resolve()
|
|
307
|
+
if not source.is_file():
|
|
308
|
+
raise FileNotFoundError(f"Image file does not exist: {source}")
|
|
309
|
+
store = (
|
|
310
|
+
refkv.zarr.open(str(source))
|
|
311
|
+
if source.suffix.lower() == ".vzip"
|
|
312
|
+
else refkv.zarr.store(zarrify(str(source)))
|
|
313
|
+
)
|
|
314
|
+
root = zarr.open_group(store, mode="r")
|
|
315
|
+
layers.extend(_layers(root, source))
|
|
316
|
+
return layers
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def read_and_save_image(
|
|
320
|
+
path: str, archive_path: str, *, overwrite: bool = False
|
|
321
|
+
) -> list[tuple[Any, dict, str]]:
|
|
322
|
+
"""Prepare lazy layers and atomically save their reference archive, not pixels.
|
|
323
|
+
|
|
324
|
+
Args:
|
|
325
|
+
path: Local image source; existing VZIP archives are not accepted.
|
|
326
|
+
archive_path: Destination ending in .vzip, separate from the source.
|
|
327
|
+
overwrite: Allow atomic replacement of an existing destination.
|
|
328
|
+
|
|
329
|
+
Returns:
|
|
330
|
+
napari layer-data tuples retaining references to the original source.
|
|
331
|
+
|
|
332
|
+
Raises:
|
|
333
|
+
FileNotFoundError: The source or destination directory does not exist.
|
|
334
|
+
FileExistsError: The destination exists and overwrite is disabled.
|
|
335
|
+
ValueError: The source, destination or OME image metadata is unsupported.
|
|
336
|
+
OSError: Staging or atomically publishing the archive fails.
|
|
337
|
+
"""
|
|
338
|
+
import refkv.zarr
|
|
339
|
+
import zarr
|
|
340
|
+
from refkv.zarrify import zarrify
|
|
341
|
+
|
|
342
|
+
source = Path(path).expanduser().resolve()
|
|
343
|
+
destination = Path(archive_path).expanduser().resolve()
|
|
344
|
+
if not source.is_file():
|
|
345
|
+
raise FileNotFoundError(f"Image file does not exist: {source}")
|
|
346
|
+
if source.suffix.lower() == ".vzip":
|
|
347
|
+
raise ValueError("The selected input is already a VZIP archive.")
|
|
348
|
+
if destination == source or destination.suffix.lower() != ".vzip":
|
|
349
|
+
raise ValueError("Choose a separate .vzip archive destination.")
|
|
350
|
+
if not destination.parent.is_dir():
|
|
351
|
+
raise FileNotFoundError(
|
|
352
|
+
f"Archive directory does not exist: {destination.parent}"
|
|
353
|
+
)
|
|
354
|
+
if destination.exists() and not overwrite:
|
|
355
|
+
raise FileExistsError(f"Archive already exists: {destination}")
|
|
356
|
+
reference = zarrify(str(source))
|
|
357
|
+
root = zarr.open_group(refkv.zarr.store(reference), mode="r")
|
|
358
|
+
layers = _layers(root, source)
|
|
359
|
+
with TemporaryDirectory(prefix=".refkv-", dir=destination.parent) as temporary:
|
|
360
|
+
staged = Path(temporary) / destination.name
|
|
361
|
+
reference.save(staged)
|
|
362
|
+
if overwrite:
|
|
363
|
+
os.replace(staged, destination)
|
|
364
|
+
else:
|
|
365
|
+
os.link(staged, destination)
|
|
366
|
+
for _, kwargs, _ in layers:
|
|
367
|
+
kwargs["metadata"]["vzip"] = str(destination)
|
|
368
|
+
return layers
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def napari_get_reader(path: str | list[str]):
|
|
372
|
+
"""Offer the reader for supported image extensions without opening the file.
|
|
373
|
+
|
|
374
|
+
Args:
|
|
375
|
+
path: A local source path or list of paths supplied by napari.
|
|
376
|
+
|
|
377
|
+
Returns:
|
|
378
|
+
The reader callable when every suffix is supported, otherwise None.
|
|
379
|
+
A matching suffix does not guarantee that the image can be decoded.
|
|
380
|
+
"""
|
|
381
|
+
paths = path if isinstance(path, list) else [path]
|
|
382
|
+
if paths and all(str(item).lower().endswith(IMAGE_SUFFIXES) for item in paths):
|
|
383
|
+
qt_widgets = sys.modules.get("qtpy.QtWidgets")
|
|
384
|
+
if qt_widgets is not None and qt_widgets.QApplication.instance() is not None:
|
|
385
|
+
from ._metadata import prepare_metadata_inspectors
|
|
386
|
+
|
|
387
|
+
prepare_metadata_inspectors()
|
|
388
|
+
return read_images
|
|
389
|
+
return None
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
"""Small, asynchronous file opener; napari owns all display controls."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
import napari
|
|
7
|
+
from napari.qt.threading import create_worker
|
|
8
|
+
from qtpy.QtCore import Qt, Slot
|
|
9
|
+
from qtpy.QtWidgets import (
|
|
10
|
+
QCheckBox,
|
|
11
|
+
QFileDialog,
|
|
12
|
+
QHBoxLayout,
|
|
13
|
+
QLabel,
|
|
14
|
+
QLineEdit,
|
|
15
|
+
QMessageBox,
|
|
16
|
+
QProgressBar,
|
|
17
|
+
QPushButton,
|
|
18
|
+
QStyle,
|
|
19
|
+
QToolButton,
|
|
20
|
+
QVBoxLayout,
|
|
21
|
+
QWidget,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
from ._metadata import ensure_metadata_panel
|
|
25
|
+
from ._reader import IMAGE_SUFFIXES, read_and_save_image, read_images
|
|
26
|
+
|
|
27
|
+
logger = logging.getLogger(__name__)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class VirtualReaderWidget(QWidget):
|
|
31
|
+
"""Open images through refkv, preparing layers away from the Qt main thread."""
|
|
32
|
+
|
|
33
|
+
def __init__(self, viewer: napari.Viewer) -> None:
|
|
34
|
+
super().__init__()
|
|
35
|
+
self.viewer = viewer
|
|
36
|
+
self._worker = None
|
|
37
|
+
self._closed = False
|
|
38
|
+
self._archive_path = None
|
|
39
|
+
self.metadata_panel = ensure_metadata_panel(viewer)
|
|
40
|
+
self._metadata_dock = self.metadata_panel.dock
|
|
41
|
+
self.setMinimumWidth(260)
|
|
42
|
+
self.setAcceptDrops(True)
|
|
43
|
+
layout = QVBoxLayout(self)
|
|
44
|
+
row = QHBoxLayout()
|
|
45
|
+
self.filename = QLineEdit()
|
|
46
|
+
self.filename.setPlaceholderText("Image file or VZIP archive")
|
|
47
|
+
self.filename.setAcceptDrops(False)
|
|
48
|
+
self.filename.textChanged.connect(self._update_open)
|
|
49
|
+
self.filename.returnPressed.connect(self._open)
|
|
50
|
+
self.browse = QToolButton()
|
|
51
|
+
self.browse.setIcon(self.style().standardIcon(QStyle.SP_DirOpenIcon))
|
|
52
|
+
self.browse.setToolTip("Choose image file or VZIP archive")
|
|
53
|
+
self.browse.setAccessibleName("Choose image file")
|
|
54
|
+
self.browse.clicked.connect(self._choose_file)
|
|
55
|
+
row.addWidget(self.filename)
|
|
56
|
+
row.addWidget(self.browse)
|
|
57
|
+
layout.addLayout(row)
|
|
58
|
+
self.save_archive = QCheckBox("Save VZIP archive")
|
|
59
|
+
self.save_archive.setToolTip("Save references without copying image pixels")
|
|
60
|
+
layout.addWidget(self.save_archive)
|
|
61
|
+
self.open_button = QPushButton("Open")
|
|
62
|
+
self.open_button.setIcon(self.style().standardIcon(QStyle.SP_DialogOpenButton))
|
|
63
|
+
self.open_button.clicked.connect(self._open)
|
|
64
|
+
layout.addWidget(self.open_button)
|
|
65
|
+
self.progress = QProgressBar()
|
|
66
|
+
self.progress.setRange(0, 0)
|
|
67
|
+
self.progress.setTextVisible(False)
|
|
68
|
+
self.progress.hide()
|
|
69
|
+
layout.addWidget(self.progress)
|
|
70
|
+
self.status = QLabel("")
|
|
71
|
+
self.status.setWordWrap(True)
|
|
72
|
+
self.status.setTextFormat(Qt.PlainText)
|
|
73
|
+
layout.addWidget(self.status)
|
|
74
|
+
layout.addStretch()
|
|
75
|
+
self._update_open()
|
|
76
|
+
|
|
77
|
+
def _update_open(self) -> None:
|
|
78
|
+
"""Enable opening only when there is an input and no active worker."""
|
|
79
|
+
self.filename.setToolTip(self.filename.text())
|
|
80
|
+
self.open_button.setEnabled(bool(self.filename.text().strip()) and self._worker is None)
|
|
81
|
+
self.save_archive.setEnabled(
|
|
82
|
+
self._worker is None and Path(self.filename.text().strip()).suffix.lower() != ".vzip"
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
def _choose_file(self) -> None:
|
|
86
|
+
"""Select an input without generating files or changing source images."""
|
|
87
|
+
patterns = " ".join(f"*{suffix}" for suffix in IMAGE_SUFFIXES)
|
|
88
|
+
path, _ = QFileDialog.getOpenFileName(
|
|
89
|
+
self,
|
|
90
|
+
"Open as virtual OME-Zarr",
|
|
91
|
+
self.filename.text(),
|
|
92
|
+
f"Images and archives ({patterns});;All files (*)",
|
|
93
|
+
)
|
|
94
|
+
if path:
|
|
95
|
+
self.filename.setText(path)
|
|
96
|
+
|
|
97
|
+
def _open(self) -> None:
|
|
98
|
+
"""Snapshot the source and build metadata and lazy layer graphs off-thread."""
|
|
99
|
+
path = self.filename.text().strip()
|
|
100
|
+
if not path or self._worker is not None:
|
|
101
|
+
return
|
|
102
|
+
self._archive_path = None
|
|
103
|
+
operation = read_images
|
|
104
|
+
arguments = (path,)
|
|
105
|
+
options = {}
|
|
106
|
+
if self.save_archive.isChecked() and Path(path).suffix.lower() != ".vzip":
|
|
107
|
+
destination, _ = QFileDialog.getSaveFileName(
|
|
108
|
+
self,
|
|
109
|
+
"Save VZIP archive",
|
|
110
|
+
str(Path(path).with_suffix(".vzip")),
|
|
111
|
+
"VZIP archives (*.vzip)",
|
|
112
|
+
options=QFileDialog.DontConfirmOverwrite,
|
|
113
|
+
)
|
|
114
|
+
if not destination:
|
|
115
|
+
return
|
|
116
|
+
output = Path(destination).expanduser().resolve()
|
|
117
|
+
if not output.suffix:
|
|
118
|
+
output = output.with_suffix(".vzip")
|
|
119
|
+
if output == Path(path).expanduser().resolve() or output.suffix.lower() != ".vzip":
|
|
120
|
+
self._failed(ValueError("Choose a separate .vzip archive destination."))
|
|
121
|
+
return
|
|
122
|
+
overwrite = output.exists()
|
|
123
|
+
if (
|
|
124
|
+
overwrite
|
|
125
|
+
and QMessageBox.question(
|
|
126
|
+
self,
|
|
127
|
+
"Replace VZIP archive?",
|
|
128
|
+
f"Replace {output.name}?",
|
|
129
|
+
QMessageBox.Yes | QMessageBox.No,
|
|
130
|
+
QMessageBox.No,
|
|
131
|
+
)
|
|
132
|
+
!= QMessageBox.Yes
|
|
133
|
+
):
|
|
134
|
+
return
|
|
135
|
+
self._archive_path = output
|
|
136
|
+
operation = read_and_save_image
|
|
137
|
+
arguments = (path, str(output))
|
|
138
|
+
options = {"overwrite": overwrite}
|
|
139
|
+
self._closed = False
|
|
140
|
+
self.status.setText(f"Opening {Path(path).name}...")
|
|
141
|
+
self._worker = create_worker(
|
|
142
|
+
operation,
|
|
143
|
+
*arguments,
|
|
144
|
+
_start_thread=False,
|
|
145
|
+
_ignore_errors=True,
|
|
146
|
+
**options,
|
|
147
|
+
)
|
|
148
|
+
self._worker.returned.connect(self._loaded)
|
|
149
|
+
self._worker.errored.connect(self._failed)
|
|
150
|
+
self._worker.finished.connect(self._finished)
|
|
151
|
+
self.filename.setEnabled(False)
|
|
152
|
+
self.browse.setEnabled(False)
|
|
153
|
+
self._update_open()
|
|
154
|
+
self.progress.show()
|
|
155
|
+
self._worker.start()
|
|
156
|
+
|
|
157
|
+
@Slot(object)
|
|
158
|
+
def _loaded(self, layers: list) -> None:
|
|
159
|
+
"""Add layers on the owning viewer's Qt thread, not in the worker."""
|
|
160
|
+
if self._closed:
|
|
161
|
+
return
|
|
162
|
+
added = []
|
|
163
|
+
try:
|
|
164
|
+
for data, kwargs, _ in layers:
|
|
165
|
+
added.append(self.viewer.add_image(data, **kwargs))
|
|
166
|
+
except Exception as error:
|
|
167
|
+
for layer in added:
|
|
168
|
+
self.viewer.layers.remove(layer)
|
|
169
|
+
self._failed(error)
|
|
170
|
+
return
|
|
171
|
+
message = f"Opened {len(added)} image layer(s)"
|
|
172
|
+
if self._archive_path is not None:
|
|
173
|
+
message += f"; saved {self._archive_path.name}"
|
|
174
|
+
self.status.setText(message)
|
|
175
|
+
self.status.setToolTip(str(self._archive_path) if self._archive_path else "")
|
|
176
|
+
|
|
177
|
+
@Slot(object)
|
|
178
|
+
def _failed(self, error: Exception) -> None:
|
|
179
|
+
"""Report external file/codec errors without silently switching readers."""
|
|
180
|
+
from napari.utils.notifications import show_error
|
|
181
|
+
|
|
182
|
+
logger.error(
|
|
183
|
+
"Virtual image opening failed: %s",
|
|
184
|
+
error,
|
|
185
|
+
exc_info=(type(error), error, error.__traceback__),
|
|
186
|
+
)
|
|
187
|
+
if not self._closed:
|
|
188
|
+
self.status.setText(str(error))
|
|
189
|
+
show_error(str(error))
|
|
190
|
+
|
|
191
|
+
def _finished(self) -> None:
|
|
192
|
+
"""Restore controls after either successful preparation or failure."""
|
|
193
|
+
self._worker = None
|
|
194
|
+
self.progress.hide()
|
|
195
|
+
self.filename.setEnabled(True)
|
|
196
|
+
self.browse.setEnabled(True)
|
|
197
|
+
self._update_open()
|
|
198
|
+
|
|
199
|
+
def dragEnterEvent(self, event) -> None:
|
|
200
|
+
"""Accept a single local file when no load is in progress."""
|
|
201
|
+
urls = event.mimeData().urls()
|
|
202
|
+
if self._worker is None and len(urls) == 1 and urls[0].isLocalFile():
|
|
203
|
+
event.acceptProposedAction()
|
|
204
|
+
else:
|
|
205
|
+
event.ignore()
|
|
206
|
+
|
|
207
|
+
def dropEvent(self, event) -> None:
|
|
208
|
+
"""Select a dropped input; opening remains an explicit action."""
|
|
209
|
+
urls = event.mimeData().urls()
|
|
210
|
+
if self._worker is None and len(urls) == 1 and urls[0].isLocalFile():
|
|
211
|
+
self.filename.setText(urls[0].toLocalFile())
|
|
212
|
+
event.acceptProposedAction()
|
|
213
|
+
else:
|
|
214
|
+
event.ignore()
|
|
215
|
+
|
|
216
|
+
def closeEvent(self, event) -> None:
|
|
217
|
+
"""Discard worker results if the dock is closed during preparation."""
|
|
218
|
+
self._closed = True
|
|
219
|
+
super().closeEvent(event)
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
name: napari-virtual-reader
|
|
2
|
+
display_name: napari-virtual-reader
|
|
3
|
+
schema_version: 0.2.1
|
|
4
|
+
contributions:
|
|
5
|
+
commands:
|
|
6
|
+
- id: napari-virtual-reader.get_reader
|
|
7
|
+
python_name: napari_virtual_reader._reader:napari_get_reader
|
|
8
|
+
title: Open as virtual OME-Zarr
|
|
9
|
+
- id: napari-virtual-reader.widget
|
|
10
|
+
python_name: napari_virtual_reader._widget:VirtualReaderWidget
|
|
11
|
+
title: Open virtual OME-Zarr
|
|
12
|
+
readers:
|
|
13
|
+
- command: napari-virtual-reader.get_reader
|
|
14
|
+
accepts_directories: false
|
|
15
|
+
filename_patterns:
|
|
16
|
+
- '*.[cC][zZ][iI]'
|
|
17
|
+
- '*.[tT][iI][fF]'
|
|
18
|
+
- '*.[tT][iI][fF][fF]'
|
|
19
|
+
- '*.[sS][vV][sS]'
|
|
20
|
+
- '*.[nN][dD][pP][iI]'
|
|
21
|
+
- '*.[nN][dD]2'
|
|
22
|
+
- '*.[lL][iI][fF]'
|
|
23
|
+
- '*.[iI][mM][sS]'
|
|
24
|
+
- '*.[vV][sS][iI]'
|
|
25
|
+
- '*.[qQ][pP][tT][iI][fF][fF]'
|
|
26
|
+
- '*.[dD][cC][mM]'
|
|
27
|
+
- '*.[dD][iI][cC][oO][mM]'
|
|
28
|
+
- '*.[nN][iI][iI]'
|
|
29
|
+
- '*.[nN][iI][iI].[gG][zZ]'
|
|
30
|
+
- '*.[nN][rR][rR][dD]'
|
|
31
|
+
- '*.[nN][hH][dD][rR]'
|
|
32
|
+
- '*.[mM][rR][cC]'
|
|
33
|
+
- '*.[mM][aA][pP]'
|
|
34
|
+
- '*.[vV][zZ][iI][pP]'
|
|
35
|
+
widgets:
|
|
36
|
+
- command: napari-virtual-reader.widget
|
|
37
|
+
display_name: Open Data as virtual OME-ZARR
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: napari-virtual-reader
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Experimental napari plugin for lazy virtual OME-Zarr images via refkv
|
|
5
|
+
Project-URL: Homepage, https://github.com/sebi06/napari-virtual-reader
|
|
6
|
+
Project-URL: Bug Tracker, https://github.com/sebi06/napari-virtual-reader/issues
|
|
7
|
+
Project-URL: Documentation, https://github.com/sebi06/napari-virtual-reader#readme
|
|
8
|
+
Project-URL: Source Code, https://github.com/sebi06/napari-virtual-reader
|
|
9
|
+
Author-email: Sebastian Rhode <sebrhode@gmail.com>
|
|
10
|
+
License-Expression: BSD-3-Clause
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: napari,ome-zarr,plugin,virtual
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Framework :: napari
|
|
15
|
+
Classifier: Intended Audience :: Science/Research
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering :: Image Processing
|
|
22
|
+
Requires-Python: >=3.12
|
|
23
|
+
Requires-Dist: dask[array]>=2024.1
|
|
24
|
+
Requires-Dist: napari>=0.10.0
|
|
25
|
+
Requires-Dist: numpy>=2
|
|
26
|
+
Requires-Dist: qtpy>=2.4
|
|
27
|
+
Requires-Dist: refkv[images,zarr]>=0.2.0
|
|
28
|
+
Requires-Dist: superqt>=0.7
|
|
29
|
+
Requires-Dist: zarr>=3.4
|
|
30
|
+
Provides-Extra: testing
|
|
31
|
+
Requires-Dist: pytest-qt>=4.4; extra == 'testing'
|
|
32
|
+
Requires-Dist: pytest>=8; extra == 'testing'
|
|
33
|
+
Requires-Dist: ruff>=0.9; extra == 'testing'
|
|
34
|
+
Requires-Dist: tifffile; extra == 'testing'
|
|
35
|
+
Description-Content-Type: text/markdown
|
|
36
|
+
|
|
37
|
+
# napari-virtual-reader
|
|
38
|
+
|
|
39
|
+
**Experimental software - Alpha status.** APIs and behavior may change without
|
|
40
|
+
notice. Validate results independently before relying on them for analysis.
|
|
41
|
+
|
|
42
|
+
Open image files as lazy, reference-backed OME-Zarr in napari. No pixel
|
|
43
|
+
conversion, copied image data, or intermediate archive is required.
|
|
44
|
+
|
|
45
|
+
The plugin uses refkv directly. It does not depend on czitools, pylibCZIrw,
|
|
46
|
+
or the napari-czitools plugin.
|
|
47
|
+
|
|
48
|
+
## Install
|
|
49
|
+
|
|
50
|
+
Python 3.12 or newer is required. Install into the environment running napari:
|
|
51
|
+
|
|
52
|
+
```powershell
|
|
53
|
+
python -m pip install napari-virtual-reader
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
A working Qt backend is required. For a fresh environment:
|
|
57
|
+
|
|
58
|
+
```powershell
|
|
59
|
+
python -m pip install "napari[pyqt6]" napari-virtual-reader
|
|
60
|
+
napari
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Restart napari after installation. The package registers an npe2 reader and
|
|
64
|
+
widget through its `napari.manifest` entry point; no manual registration is
|
|
65
|
+
required. Check **Plugins > Plugin Manager** for **napari-virtual-reader**.
|
|
66
|
+
|
|
67
|
+
## Open an image
|
|
68
|
+
|
|
69
|
+
In napari, choose **Plugins > napari-virtual-reader > Open Data as virtual OME-ZARR**,
|
|
70
|
+
select the input, and click **Open**. Preparation runs in a background worker; napari
|
|
71
|
+
provides its normal layer, contrast, time, and Z controls.
|
|
72
|
+
|
|
73
|
+
You can also use **File > Open** or drop a file on the napari canvas and choose
|
|
74
|
+
the napari-virtual-reader reader. Drop a file on the plugin dock to select it without
|
|
75
|
+
opening it yet.
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
import napari
|
|
79
|
+
|
|
80
|
+
viewer = napari.Viewer()
|
|
81
|
+
viewer.open("image.czi", plugin="napari-virtual-reader")
|
|
82
|
+
napari.run()
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Raw images are virtualized in memory through `refkv.zarrify.zarrify`. Existing
|
|
86
|
+
`.vzip` archives are opened directly. Original image files must remain available
|
|
87
|
+
and unchanged for as long as their layers are used. Nothing is written beside
|
|
88
|
+
the source by default.
|
|
89
|
+
|
|
90
|
+
### Save a VZIP Archive
|
|
91
|
+
|
|
92
|
+
In **Plugins > napari-virtual-reader > Open Data as virtual OME-ZARR**, select an image and enable
|
|
93
|
+
**Save VZIP archive** before clicking **Open**. Choose the destination in the
|
|
94
|
+
save dialog; the suggested filename is a sibling `.vzip`. Saving runs in the
|
|
95
|
+
background, and the resulting image still opens lazily with the metadata panel.
|
|
96
|
+
The status shows the saved filename, with its full path available on hover.
|
|
97
|
+
|
|
98
|
+
Saving stores references to the original image, not converted pixel data.
|
|
99
|
+
The archive covers the complete source, including all scenes and pyramid levels.
|
|
100
|
+
Existing destinations require explicit replacement confirmation; failed writes
|
|
101
|
+
leave the old archive intact. Cancelling the save dialog cancels the open action.
|
|
102
|
+
The save option is disabled for inputs that are already VZIP archives.
|
|
103
|
+
File/Open and canvas drops remain in-memory operations without automatic saving.
|
|
104
|
+
|
|
105
|
+
## Metadata Inspector
|
|
106
|
+
|
|
107
|
+
The **Virtual Zarr metadata** dock opens on the right when using the refkv reader
|
|
108
|
+
through File/Open or drag-and-drop, without opening the plugin widget first.
|
|
109
|
+
It also appears with **Plugins > napari-virtual-reader > Open Data as virtual OME-ZARR**.
|
|
110
|
+
Both workflows share one inspector that follows the selected image layer.
|
|
111
|
+
|
|
112
|
+
- **Zarr structure** shows expandable groups and arrays, including original
|
|
113
|
+
shapes, dtypes, attributes, chunk grids and codec configuration.
|
|
114
|
+
- **Metadata** shows the selected layer's OME metadata, source and channel
|
|
115
|
+
information, plus original scene transforms for stacked CZI images.
|
|
116
|
+
- A filter finds matching properties; selecting a row shows its complete,
|
|
117
|
+
selectable value below the tree.
|
|
118
|
+
|
|
119
|
+
The inspector uses a metadata-only snapshot collected in the background. It
|
|
120
|
+
does not scan pixel data or reconstruct the source hierarchy from displayed
|
|
121
|
+
layer shapes. Selecting an unrelated layer clears the inspector.
|
|
122
|
+
|
|
123
|
+
## Scope
|
|
124
|
+
|
|
125
|
+
- CZI, TIFF/OME-TIFF, and other refkv-supported files that expose OME image series.
|
|
126
|
+
Reader registration includes common microscopy and volumetric image extensions;
|
|
127
|
+
actual support is determined by refkv's parser and the file's metadata/codecs.
|
|
128
|
+
- One layer per channel. Compatible CZI scenes are stacked lazily along a leading
|
|
129
|
+
**S** axis, in numeric series order; for example, 28 equally sized 2D scenes
|
|
130
|
+
become one `(28, Y, X)` layer per channel. This also applies to CZI-derived
|
|
131
|
+
VZIP archives. Other formats retain separate series layers.
|
|
132
|
+
- CZI stacking requires matching axes, shapes, dtypes, physical scales and
|
|
133
|
+
pyramid levels. Incompatible scenes remain separate without cropping or
|
|
134
|
+
resampling. Scene-dependent stage origins are replaced by local coordinates
|
|
135
|
+
on the stacked layer; original origins and metadata remain available in
|
|
136
|
+
the layer's `metadata["scenes"]` list.
|
|
137
|
+
- Stored multiscale pyramids, OME axis ordering, physical scale/origin, channel
|
|
138
|
+
names, colors, and display windows.
|
|
139
|
+
- Regular and rectilinear chunk grids, without scanning complete lazy arrays
|
|
140
|
+
for contrast limits. Files without display windows use dtype bounds (0-1 for
|
|
141
|
+
floating point); adjust contrast in napari as needed.
|
|
142
|
+
- OME-Zarr 0.4 and 0.5 image metadata, including nested image hierarchies.
|
|
143
|
+
|
|
144
|
+
This is deliberately not a replacement for every refkv dataset interface:
|
|
145
|
+
non-image tables, audio, arbitrary tensors, remote inputs, and stores without
|
|
146
|
+
OME image metadata are outside this first version. There are no custom dimension
|
|
147
|
+
sliders or CZI-specific options.
|
|
148
|
+
|
|
149
|
+
## Development
|
|
150
|
+
|
|
151
|
+
```powershell
|
|
152
|
+
git clone https://github.com/sebi06/napari-virtual-reader.git
|
|
153
|
+
cd napari-virtual-reader
|
|
154
|
+
python -m pip install -e ".[testing]"
|
|
155
|
+
python -m pytest
|
|
156
|
+
python -m ruff check .
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
Install a Qt backend as above if the development environment does not already
|
|
160
|
+
provide one. Development installs register the same napari plugin as PyPI installs.
|
|
161
|
+
|
|
162
|
+
## Releases
|
|
163
|
+
|
|
164
|
+
GitHub Actions tests pull requests and pushes to `main`. Publishing runs only
|
|
165
|
+
after the test matrix passes on a release tag such as `v0.0.1`.
|
|
166
|
+
|
|
167
|
+
Set `project.version` in `pyproject.toml` to the intended release version before
|
|
168
|
+
tagging; tags do not change the package version. PyPI requires a new
|
|
169
|
+
version for every upload. Manual workflow runs test and build without publishing.
|
|
170
|
+
|
|
171
|
+
See the [changelog](CHANGELOG.md) for the change history and the
|
|
172
|
+
[release notes](_release_notes/v0.0.1.md) for v0.0.1 features, validation, and
|
|
173
|
+
limitations. Publication status is recorded in those files and updated after
|
|
174
|
+
GitHub Actions and PyPI publication are verified.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
napari_virtual_reader/__init__.py,sha256=_0_Dcvq0V5impBLm3PBFhDhWH2YP8pB8HsBLktwjM6Q,188
|
|
2
|
+
napari_virtual_reader/_metadata.py,sha256=7RdGaNQ65zuPK5GLY2NCf5el5n4kNhFM1p1Gbn89-rY,6989
|
|
3
|
+
napari_virtual_reader/_reader.py,sha256=J0m0wcrmyS6S59kek_6TfqXPHmkj6azXl8WlcYa1e6o,15089
|
|
4
|
+
napari_virtual_reader/_widget.py,sha256=-o5lIbAayp0l-a6yA-S8iQfL7aNYtOetFo17VH-LSRc,8233
|
|
5
|
+
napari_virtual_reader/napari.yaml,sha256=H4j_cnjqGRDZOqYNiLd4krhX7GBwvxPw7DVFAqBgObU,1184
|
|
6
|
+
napari_virtual_reader-0.0.1.dist-info/METADATA,sha256=wYDtF7QkHyUAPlZiDqnToV9rI-6IFae-Aze_AEF3mco,7764
|
|
7
|
+
napari_virtual_reader-0.0.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
8
|
+
napari_virtual_reader-0.0.1.dist-info/entry_points.txt,sha256=8ly-lq6RaAuvzF5N5HemnjenOZMWNijIIBu03WJUVVo,76
|
|
9
|
+
napari_virtual_reader-0.0.1.dist-info/licenses/LICENSE,sha256=d2WL4S8IQbOsD5ht27yN2klI-GQ_BDQhVTlIAR8jgvM,1493
|
|
10
|
+
napari_virtual_reader-0.0.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
Copyright (c) 2026, Sebastian Rhode
|
|
2
|
+
All rights reserved.
|
|
3
|
+
|
|
4
|
+
Redistribution and use in source and binary forms, with or without
|
|
5
|
+
modification, are permitted provided that the following conditions are met:
|
|
6
|
+
|
|
7
|
+
* Redistributions of source code must retain the above copyright notice, this
|
|
8
|
+
list of conditions and the following disclaimer.
|
|
9
|
+
|
|
10
|
+
* Redistributions in binary form must reproduce the above copyright notice,
|
|
11
|
+
this list of conditions and the following disclaimer in the documentation
|
|
12
|
+
and/or other materials provided with the distribution.
|
|
13
|
+
|
|
14
|
+
* Neither the name of napari-virtual-reader nor the names of its
|
|
15
|
+
contributors may be used to endorse or promote products derived from
|
|
16
|
+
this software without specific prior written permission.
|
|
17
|
+
|
|
18
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
19
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
20
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
21
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
22
|
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
23
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
24
|
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
25
|
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
26
|
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
27
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|