ome-tiled 0.1.0__tar.gz

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.
@@ -0,0 +1,122 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ env/
12
+ build/
13
+ develop-eggs/
14
+ dist/
15
+ downloads/
16
+ eggs/
17
+ .eggs/
18
+ lib/
19
+ lib64/
20
+ parts/
21
+ sdist/
22
+ var/
23
+ wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+
28
+ # PyInstaller
29
+ # Usually these files are written by a python script from a template
30
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
31
+ *.manifest
32
+ *.spec
33
+
34
+ # Installer logs
35
+ pip-log.txt
36
+ pip-delete-this-directory.txt
37
+
38
+ # Unit test / coverage reports
39
+ htmlcov/
40
+ .tox/
41
+ .coverage
42
+ .coverage.*
43
+ .cache
44
+ nosetests.xml
45
+ coverage.xml
46
+ *.cover
47
+ .hypothesis/
48
+ .pytest_cache/
49
+ .ruff_cache/
50
+ .nox/
51
+
52
+ # Translations
53
+ *.mo
54
+ *.pot
55
+
56
+ # Django stuff:
57
+ *.log
58
+ local_settings.py
59
+
60
+ # Flask stuff:
61
+ instance/
62
+ .webassets-cache
63
+
64
+ # Scrapy stuff:
65
+ .scrapy
66
+
67
+ # Sphinx documentation
68
+ docs/_build/
69
+
70
+ # PyBuilder
71
+ target/
72
+
73
+ # Jupyter Notebook
74
+ .ipynb_checkpoints
75
+
76
+ # Dask worker cache
77
+ dask-worker-space/
78
+
79
+ # pyenv
80
+ .python-version
81
+
82
+ # celery beat schedule file
83
+ celerybeat-schedule
84
+
85
+ # SageMath parsed files
86
+ *.sage.py
87
+
88
+ # dotenv
89
+ .env
90
+
91
+ # virtualenv
92
+ .venv
93
+ venv/
94
+ ENV/
95
+
96
+ # Spyder project settings
97
+ .spyderproject
98
+ .spyproject
99
+
100
+ # Rope project settings
101
+ .ropeproject
102
+
103
+ # mkdocs documentation
104
+ /site
105
+
106
+ # mypy
107
+ .mypy_cache/
108
+
109
+ # IDE settings
110
+ .vscode/
111
+ .idea/
112
+
113
+ # local test configs
114
+ test_configs/*
115
+
116
+ # MkDocs build output
117
+ site/
118
+
119
+ # claude
120
+ .claude/settings.local.json
121
+ .claude/plans
122
+ CLAUDE.local.md
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2024 - 2026, Leibniz Institute of Photonic Technology
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,194 @@
1
+ Metadata-Version: 2.5
2
+ Name: ome-tiled
3
+ Version: 0.1.0
4
+ Summary: A tiled adapter that serves OME-Zarr images with their axis names.
5
+ Project-URL: bugs, https://github.com/redsun-acquisition/ome-tiled/issues
6
+ Project-URL: changelog, https://github.com/redsun-acquisition/ome-tiled/blob/main/CHANGELOG.md
7
+ Project-URL: homepage, https://github.com/redsun-acquisition/ome-tiled
8
+ Author-email: Jacopo Abramo <jacopo.abramo@gmail.com>
9
+ Maintainer-email: Jacopo Abramo <jacopo.abramo@gmail.com>
10
+ License: Apache-2.0
11
+ License-File: LICENSE
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: Implementation :: CPython
21
+ Classifier: Topic :: Scientific/Engineering
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: <3.14,>=3.11
24
+ Requires-Dist: tiled[server]>=0.2.18
25
+ Requires-Dist: yaozarrs>=0.3.2
26
+ Requires-Dist: zarr>=3.1.6
27
+ Description-Content-Type: text/markdown
28
+
29
+ [![PyPI](https://img.shields.io/pypi/v/ome-tiled.svg?color=green)](https://pypi.org/project/ome-tiled)
30
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/ome-tiled)](https://pypi.org/project/ome-tiled)
31
+ [![codecov](https://codecov.io/gh/redsun-acquisition/ome-tiled/graph/badge.svg)](https://codecov.io/gh/redsun-acquisition/ome-tiled)
32
+ [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
33
+ [![Checked with mypy](https://www.mypy-lang.org/static/mypy_badge.svg)](https://mypy-lang.org/)
34
+ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
35
+
36
+ # ome-tiled
37
+
38
+ An adapter for [`tiled`](https://github.com/bluesky/tiled) that serves OME-Zarr
39
+ images as arrays with their axis names, which `tiled`'s own Zarr adapter
40
+ leaves out.
41
+
42
+ ## Install
43
+
44
+ With `uv` (recommended):
45
+
46
+ ```console
47
+ uv add ome-tiled
48
+ ```
49
+
50
+ With `pip`:
51
+
52
+ ```console
53
+ pip install ome-tiled
54
+ ```
55
+
56
+ Install it on the server, and also wherever `tiled register` runs: registering
57
+ opens each store through the adapter on the registering side.
58
+
59
+ ## Usage
60
+
61
+ Serve a directory, letting `ome-tiled` find the OME-Zarr stores in it:
62
+
63
+ ```console
64
+ tiled serve directory data/ \
65
+ --adapter application/x-ome-zarr=ome_tiled:OmeZarrAdapter \
66
+ --mimetype-hook ome_tiled:detect
67
+ ```
68
+
69
+ Each image then reads as one array whose `dims` are its axis names:
70
+
71
+ ```python
72
+ from tiled.client import from_uri
73
+
74
+ client = from_uri("http://localhost:8000", api_key="...")
75
+ client["stack"].structure().dims # ('t', 'z', 'y', 'x')
76
+ ```
77
+
78
+ The hook recognizes a store by its metadata, whatever it is called. Stores
79
+ named `*.ome.zarr` can be routed by name instead, with
80
+ `--ext .ome.zarr=application/x-ome-zarr` in place of `--mimetype-hook`.
81
+
82
+ ### From a configuration file
83
+
84
+ Register the adapter in the server's configuration:
85
+
86
+ ```yaml
87
+ # config.yml
88
+ trees:
89
+ - tree: catalog
90
+ path: /
91
+ args:
92
+ uri: ./catalog.db
93
+ init_if_not_exists: true
94
+ readable_storage:
95
+ - data/
96
+ adapters_by_mimetype:
97
+ application/x-ome-zarr: ome_tiled:OmeZarrAdapter
98
+ ```
99
+
100
+ Then start the server and register the directory:
101
+
102
+ ```console
103
+ tiled serve config config.yml --api-key secret
104
+ tiled register http://localhost:8000 data/ --api-key secret \
105
+ --adapter application/x-ome-zarr=ome_tiled:OmeZarrAdapter \
106
+ --mimetype-hook ome_tiled:detect
107
+ ```
108
+
109
+ ### From Python
110
+
111
+ ```python
112
+ from tiled.catalog import from_uri
113
+
114
+ catalog = from_uri(
115
+ "catalog.db",
116
+ readable_storage=["data/"],
117
+ init_if_not_exists=True,
118
+ adapters_by_mimetype={"application/x-ome-zarr": "ome_tiled:OmeZarrAdapter"},
119
+ )
120
+ ```
121
+
122
+ `tiled.server.simple.SimpleTiledServer` takes no adapters, so add the adapter to
123
+ its catalog after starting the server and before registering anything:
124
+
125
+ ```python
126
+ from tiled.server.simple import SimpleTiledServer
127
+
128
+ from ome_tiled import OME_ZARR_MIMETYPE, OmeZarrAdapter
129
+
130
+ server = SimpleTiledServer(readable_storage=["data/"])
131
+ server.catalog.context.adapters_by_mimetype.maps[0][OME_ZARR_MIMETYPE] = OmeZarrAdapter
132
+ ```
133
+
134
+ ### Registering by hand
135
+
136
+ `tiled` answers a registered node's structure and metadata from its database,
137
+ so a registration made with `client.new` has to store the adapter's own, or the
138
+ node reads without its axis names:
139
+
140
+ ```python
141
+ from tiled.structures.core import StructureFamily
142
+ from tiled.structures.data_source import Asset, DataSource, Management
143
+
144
+ from ome_tiled import OME_ZARR_MIMETYPE, OmeZarrAdapter
145
+
146
+ uri = "file:///data/stack.ome.zarr"
147
+ adapter = OmeZarrAdapter.from_uris(uri)
148
+ client.new(
149
+ key="stack",
150
+ structure_family=StructureFamily.array,
151
+ data_sources=[
152
+ DataSource(
153
+ management=Management.external,
154
+ mimetype=OME_ZARR_MIMETYPE,
155
+ structure_family=StructureFamily.array,
156
+ structure=adapter.structure(),
157
+ assets=[Asset(data_uri=uri, is_directory=True, parameter="data_uri")],
158
+ )
159
+ ],
160
+ metadata=dict(adapter.metadata()),
161
+ specs=[],
162
+ )
163
+ ```
164
+
165
+ The URI may name the image group or its full-resolution array; both read the
166
+ same way.
167
+
168
+ ## What it reads
169
+
170
+ - NGFF 0.4 and 0.5 images and label images, validated with
171
+ [`yaozarrs`](https://github.com/imaging-formats/yaozarrs). The axes, with their
172
+ types and units, are under `axes` in the node's metadata.
173
+ - A Zarr group holding several such images, each presented as its own array.
174
+ - The full-resolution level only. Pyramids read at level `0`.
175
+
176
+ Anything else is served as `tiled`'s Zarr adapter serves it, with a log line
177
+ saying why: other NGFF layouts such as `bioformats2raw` series, plates, wells
178
+ and label groups, and any group whose NGFF metadata fails validation.
179
+ Validation is strict, so a file that breaks the NGFF specification, for example
180
+ a dataset without `coordinateTransformations`, reads as plain Zarr rather than
181
+ as an image.
182
+
183
+ Axes of a custom kind, such as a scan pattern, keep their names too. NGFF
184
+ orders axes as time, then channel or custom, then space, so a file that puts a
185
+ custom axis after the spatial ones fails validation and reads as plain Zarr.
186
+
187
+ ## More
188
+
189
+ The `tiled` documentation explains adapters, mimetypes and detection hooks in
190
+ more detail: [Serve Files with Custom Formats](https://blueskyproject.io/tiled/user-guide/read-custom-formats.html).
191
+
192
+ ## License
193
+
194
+ Apache License 2.0. See [`LICENSE`](LICENSE).
@@ -0,0 +1,166 @@
1
+ [![PyPI](https://img.shields.io/pypi/v/ome-tiled.svg?color=green)](https://pypi.org/project/ome-tiled)
2
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/ome-tiled)](https://pypi.org/project/ome-tiled)
3
+ [![codecov](https://codecov.io/gh/redsun-acquisition/ome-tiled/graph/badge.svg)](https://codecov.io/gh/redsun-acquisition/ome-tiled)
4
+ [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
5
+ [![Checked with mypy](https://www.mypy-lang.org/static/mypy_badge.svg)](https://mypy-lang.org/)
6
+ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
7
+
8
+ # ome-tiled
9
+
10
+ An adapter for [`tiled`](https://github.com/bluesky/tiled) that serves OME-Zarr
11
+ images as arrays with their axis names, which `tiled`'s own Zarr adapter
12
+ leaves out.
13
+
14
+ ## Install
15
+
16
+ With `uv` (recommended):
17
+
18
+ ```console
19
+ uv add ome-tiled
20
+ ```
21
+
22
+ With `pip`:
23
+
24
+ ```console
25
+ pip install ome-tiled
26
+ ```
27
+
28
+ Install it on the server, and also wherever `tiled register` runs: registering
29
+ opens each store through the adapter on the registering side.
30
+
31
+ ## Usage
32
+
33
+ Serve a directory, letting `ome-tiled` find the OME-Zarr stores in it:
34
+
35
+ ```console
36
+ tiled serve directory data/ \
37
+ --adapter application/x-ome-zarr=ome_tiled:OmeZarrAdapter \
38
+ --mimetype-hook ome_tiled:detect
39
+ ```
40
+
41
+ Each image then reads as one array whose `dims` are its axis names:
42
+
43
+ ```python
44
+ from tiled.client import from_uri
45
+
46
+ client = from_uri("http://localhost:8000", api_key="...")
47
+ client["stack"].structure().dims # ('t', 'z', 'y', 'x')
48
+ ```
49
+
50
+ The hook recognizes a store by its metadata, whatever it is called. Stores
51
+ named `*.ome.zarr` can be routed by name instead, with
52
+ `--ext .ome.zarr=application/x-ome-zarr` in place of `--mimetype-hook`.
53
+
54
+ ### From a configuration file
55
+
56
+ Register the adapter in the server's configuration:
57
+
58
+ ```yaml
59
+ # config.yml
60
+ trees:
61
+ - tree: catalog
62
+ path: /
63
+ args:
64
+ uri: ./catalog.db
65
+ init_if_not_exists: true
66
+ readable_storage:
67
+ - data/
68
+ adapters_by_mimetype:
69
+ application/x-ome-zarr: ome_tiled:OmeZarrAdapter
70
+ ```
71
+
72
+ Then start the server and register the directory:
73
+
74
+ ```console
75
+ tiled serve config config.yml --api-key secret
76
+ tiled register http://localhost:8000 data/ --api-key secret \
77
+ --adapter application/x-ome-zarr=ome_tiled:OmeZarrAdapter \
78
+ --mimetype-hook ome_tiled:detect
79
+ ```
80
+
81
+ ### From Python
82
+
83
+ ```python
84
+ from tiled.catalog import from_uri
85
+
86
+ catalog = from_uri(
87
+ "catalog.db",
88
+ readable_storage=["data/"],
89
+ init_if_not_exists=True,
90
+ adapters_by_mimetype={"application/x-ome-zarr": "ome_tiled:OmeZarrAdapter"},
91
+ )
92
+ ```
93
+
94
+ `tiled.server.simple.SimpleTiledServer` takes no adapters, so add the adapter to
95
+ its catalog after starting the server and before registering anything:
96
+
97
+ ```python
98
+ from tiled.server.simple import SimpleTiledServer
99
+
100
+ from ome_tiled import OME_ZARR_MIMETYPE, OmeZarrAdapter
101
+
102
+ server = SimpleTiledServer(readable_storage=["data/"])
103
+ server.catalog.context.adapters_by_mimetype.maps[0][OME_ZARR_MIMETYPE] = OmeZarrAdapter
104
+ ```
105
+
106
+ ### Registering by hand
107
+
108
+ `tiled` answers a registered node's structure and metadata from its database,
109
+ so a registration made with `client.new` has to store the adapter's own, or the
110
+ node reads without its axis names:
111
+
112
+ ```python
113
+ from tiled.structures.core import StructureFamily
114
+ from tiled.structures.data_source import Asset, DataSource, Management
115
+
116
+ from ome_tiled import OME_ZARR_MIMETYPE, OmeZarrAdapter
117
+
118
+ uri = "file:///data/stack.ome.zarr"
119
+ adapter = OmeZarrAdapter.from_uris(uri)
120
+ client.new(
121
+ key="stack",
122
+ structure_family=StructureFamily.array,
123
+ data_sources=[
124
+ DataSource(
125
+ management=Management.external,
126
+ mimetype=OME_ZARR_MIMETYPE,
127
+ structure_family=StructureFamily.array,
128
+ structure=adapter.structure(),
129
+ assets=[Asset(data_uri=uri, is_directory=True, parameter="data_uri")],
130
+ )
131
+ ],
132
+ metadata=dict(adapter.metadata()),
133
+ specs=[],
134
+ )
135
+ ```
136
+
137
+ The URI may name the image group or its full-resolution array; both read the
138
+ same way.
139
+
140
+ ## What it reads
141
+
142
+ - NGFF 0.4 and 0.5 images and label images, validated with
143
+ [`yaozarrs`](https://github.com/imaging-formats/yaozarrs). The axes, with their
144
+ types and units, are under `axes` in the node's metadata.
145
+ - A Zarr group holding several such images, each presented as its own array.
146
+ - The full-resolution level only. Pyramids read at level `0`.
147
+
148
+ Anything else is served as `tiled`'s Zarr adapter serves it, with a log line
149
+ saying why: other NGFF layouts such as `bioformats2raw` series, plates, wells
150
+ and label groups, and any group whose NGFF metadata fails validation.
151
+ Validation is strict, so a file that breaks the NGFF specification, for example
152
+ a dataset without `coordinateTransformations`, reads as plain Zarr rather than
153
+ as an image.
154
+
155
+ Axes of a custom kind, such as a scan pattern, keep their names too. NGFF
156
+ orders axes as time, then channel or custom, then space, so a file that puts a
157
+ custom axis after the spatial ones fails validation and reads as plain Zarr.
158
+
159
+ ## More
160
+
161
+ The `tiled` documentation explains adapters, mimetypes and detection hooks in
162
+ more detail: [Serve Files with Custom Formats](https://blueskyproject.io/tiled/user-guide/read-custom-formats.html).
163
+
164
+ ## License
165
+
166
+ Apache License 2.0. See [`LICENSE`](LICENSE).
@@ -0,0 +1,144 @@
1
+ [build-system]
2
+ requires = ["hatchling", "hatch-vcs"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "ome-tiled"
7
+ dynamic = ["version"]
8
+ description = "A tiled adapter that serves OME-Zarr images with their axis names."
9
+ readme = "README.md"
10
+ authors = [{ name = "Jacopo Abramo", email = "jacopo.abramo@gmail.com" }]
11
+ maintainers = [{ name = "Jacopo Abramo", email = "jacopo.abramo@gmail.com" }]
12
+ classifiers = [
13
+ "Development Status :: 3 - Alpha",
14
+ "Intended Audience :: Developers",
15
+ "Intended Audience :: Science/Research",
16
+ "Topic :: Scientific/Engineering",
17
+ "Programming Language :: Python :: Implementation :: CPython",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ # no 3.14 until tiled installs there: https://github.com/bluesky/tiled/issues/1144
23
+ "Typing :: Typed",
24
+ "License :: OSI Approved :: Apache Software License",
25
+ ]
26
+ license = { text = "Apache-2.0" }
27
+ requires-python = ">=3.11,<3.14"
28
+ dependencies = [
29
+ "tiled[server]>=0.2.18",
30
+ "yaozarrs>=0.3.2",
31
+ "zarr>=3.1.6",
32
+ ]
33
+
34
+ [project.urls]
35
+ bugs = "https://github.com/redsun-acquisition/ome-tiled/issues"
36
+ changelog = "https://github.com/redsun-acquisition/ome-tiled/blob/main/CHANGELOG.md"
37
+ homepage = "https://github.com/redsun-acquisition/ome-tiled"
38
+
39
+ [tool.hatch.version]
40
+ source = "vcs"
41
+
42
+ [tool.hatch.build.targets.wheel]
43
+ packages = ["src/ome_tiled"]
44
+
45
+ [tool.hatch.build.targets.sdist]
46
+ include = ["src/ome_tiled/**"]
47
+
48
+ [tool.mypy]
49
+ files = "."
50
+ disable_error_code = [
51
+ "import-untyped",
52
+ "no-untyped-call"
53
+ ]
54
+ pretty = true
55
+ strict = true
56
+ warn_unreachable = true
57
+ warn_no_return = true
58
+
59
+ [tool.coverage.run]
60
+ source = ["ome_tiled"]
61
+
62
+ # CI combines data from Linux, macOS and Windows runners, each checking out
63
+ # the repository under a different absolute path
64
+ [tool.coverage.paths]
65
+ source = ["src/", "*/src/"]
66
+
67
+ [tool.ruff]
68
+ fix = true
69
+
70
+ [tool.ruff.format]
71
+ docstring-code-format = true
72
+
73
+ [tool.ruff.lint]
74
+ extend-select = [
75
+ "D", # enable docstring checks
76
+ "I", # enable imports checks
77
+ "TC", # enable type check imports
78
+ "FA102", # force __future__ imports
79
+ ]
80
+ ignore = ["D100","D104"] # https://docs.astral.sh/ruff/rules/undocumented-public-package/
81
+
82
+ [tool.ruff.lint.per-file-ignores]
83
+ "tests/*.py" = [
84
+ # ignore missing docstrings in tests
85
+ "D101",
86
+ "D102",
87
+ "D103",
88
+ # ignore type check imports in tests
89
+ "TC",
90
+ ]
91
+
92
+ [tool.ruff.lint.pydocstyle]
93
+ convention = "numpy"
94
+
95
+ [tool.tox]
96
+ requires = ["tox>=4.28", "tox-uv-bare>=1.36"]
97
+ env_list = ["lint", "mypy", "tests"]
98
+
99
+ [tool.tox.env_run_base]
100
+ runner = "uv-venv-lock-runner"
101
+ dependency_groups = ["dev"]
102
+
103
+ [tool.tox.env.lint]
104
+ commands = [
105
+ ["ruff", "check", "--fix", "."],
106
+ ["ruff", "format", "."],
107
+ ]
108
+
109
+ [tool.tox.env.mypy]
110
+ commands = [["mypy"]]
111
+
112
+ [tool.tox.env.tests]
113
+ commands = [["pytest", "-q", { replace = "posargs", extend = true }]]
114
+
115
+ # https://coverage.readthedocs.io/en/latest/config.html
116
+ [tool.coverage.report]
117
+ exclude_lines = [
118
+ "@abstractmethod",
119
+ "if TYPE_CHECKING:",
120
+ "@overload",
121
+ "class .*Protocol",
122
+ "except ImportError",
123
+ "except PackageNotFoundError",
124
+ "raise NotImplementedError()",
125
+ ]
126
+
127
+ [tool.pytest.ini_options]
128
+ minversion = "6.0"
129
+ testpaths = [
130
+ "tests",
131
+ ]
132
+ addopts = "-p no:warnings"
133
+
134
+ [dependency-groups]
135
+ dev = [
136
+ "acquire-zarr>=0.10.0",
137
+ "mypy>=2.3.1",
138
+ "ome-writers[acquire-zarr,zarr-python]>=0.3.2",
139
+ "prek>=0.5.3",
140
+ "pytest>=9.1.1",
141
+ "pytest-cov>=7.1.0",
142
+ "ruff>=0.16.8",
143
+ "tox-uv-bare>=1.36.0",
144
+ ]
@@ -0,0 +1,4 @@
1
+ from ome_tiled._adapter import OmeZarrAdapter
2
+ from ome_tiled._ngff import OME_ZARR_MIMETYPE, detect
3
+
4
+ __all__ = ["OME_ZARR_MIMETYPE", "OmeZarrAdapter", "detect"]
@@ -0,0 +1,104 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from typing import TYPE_CHECKING, Any
5
+
6
+ import zarr
7
+ from tiled.adapters.zarr import ZarrArrayAdapter, ZarrGroupAdapter
8
+ from tiled.structures.array import ArrayStructure
9
+ from tiled.utils import path_from_uri
10
+ from zarr.errors import GroupNotFoundError
11
+
12
+ from ome_tiled._ngff import NgffImage, NgffSkipped, classify
13
+
14
+ if TYPE_CHECKING:
15
+ from pathlib import Path
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ # tiled ships no type information, so its classes are Any to mypy
21
+ class OmeZarrAdapter(ZarrGroupAdapter): # type: ignore[misc]
22
+ """Serve OME-Zarr images as arrays with their axis names.
23
+
24
+ Register it under ``OME_ZARR_MIMETYPE``. An image registered by its group
25
+ or by its full-resolution array reads as one array whose ``dims`` are the
26
+ axes' names, with the axes in the metadata under ``axes``. A group holding
27
+ images presents each as such an array. Any other group, including NGFF
28
+ layouts this package does not read and metadata that fails validation, is
29
+ served as ``tiled``'s Zarr adapter serves it.
30
+ """
31
+
32
+ def __getitem__(self, key: str) -> Any:
33
+ value = self._zarr_group[key]
34
+ if isinstance(value, zarr.Group):
35
+ return open_group(value)
36
+ return super().__getitem__(key)
37
+
38
+ @classmethod
39
+ def from_uris(cls, data_uri: str, **kwargs: Any) -> Any:
40
+ """Open the group or array at *data_uri*."""
41
+ return open_path(path_from_uri(data_uri), **kwargs)
42
+
43
+ @classmethod
44
+ def from_catalog(cls, data_source: Any, node: Any, /, **kwargs: Any) -> Any:
45
+ """Open a registered asset, keeping the structure stored with it."""
46
+ return open_path(
47
+ path_from_uri(data_source.assets[0].data_uri),
48
+ structure=data_source.structure,
49
+ metadata=node.metadata_,
50
+ specs=node.specs,
51
+ **kwargs,
52
+ )
53
+
54
+
55
+ def open_path(
56
+ path: Path, *, structure: ArrayStructure | None = None, **kwargs: Any
57
+ ) -> Any:
58
+ """Return the adapter for the group or array at *path*."""
59
+ node = zarr.open(path, mode="r")
60
+ if isinstance(node, zarr.Group):
61
+ return open_group(node, structure=structure, **kwargs)
62
+ try:
63
+ parent = zarr.open_group(path.parent, mode="r")
64
+ except GroupNotFoundError:
65
+ image = None
66
+ else:
67
+ image = classify(parent.attrs.asdict())
68
+ if isinstance(image, NgffImage):
69
+ return open_image(node, image, structure=structure, **kwargs)
70
+ return ZarrArrayAdapter(
71
+ node, structure or ArrayStructure.from_array(node), **kwargs
72
+ )
73
+
74
+
75
+ def open_group(
76
+ group: zarr.Group, *, structure: ArrayStructure | None = None, **kwargs: Any
77
+ ) -> Any:
78
+ """Return an image's array adapter for an image group, a group adapter otherwise."""
79
+ image = classify(group.attrs.asdict())
80
+ if isinstance(image, NgffImage):
81
+ array = group.get(image.path)
82
+ if isinstance(array, zarr.Array):
83
+ return open_image(array, image, structure=structure, **kwargs)
84
+ image = NgffSkipped(f"dataset {image.path!r} is not an array")
85
+ if isinstance(image, NgffSkipped):
86
+ logger.info("Serving %s as plain Zarr: %s", group.store_path, image.reason)
87
+ return OmeZarrAdapter(group, **kwargs)
88
+
89
+
90
+ def open_image(
91
+ array: zarr.Array[Any],
92
+ image: NgffImage,
93
+ *,
94
+ structure: ArrayStructure | None = None,
95
+ metadata: dict[str, Any] | None = None,
96
+ **kwargs: Any,
97
+ ) -> Any:
98
+ """Return an array adapter carrying the image's axis names and axes."""
99
+ return ZarrArrayAdapter(
100
+ array,
101
+ structure or ArrayStructure.from_array(array, dims=image.dims),
102
+ metadata={**(metadata or {}), "axes": [dict(axis) for axis in image.axes]},
103
+ **kwargs,
104
+ )
@@ -0,0 +1,98 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import TYPE_CHECKING, Any, Final
5
+
6
+ import yaozarrs
7
+ import zarr
8
+ from pydantic import ValidationError
9
+ from yaozarrs import v04, v05
10
+ from zarr.errors import ContainsArrayError, GroupNotFoundError
11
+
12
+ if TYPE_CHECKING:
13
+ from collections.abc import Mapping
14
+ from pathlib import Path
15
+
16
+ OME_ZARR_MIMETYPE: Final = "application/x-ome-zarr"
17
+ """Mimetype under which a catalog routes OME-Zarr data to ``OmeZarrAdapter``."""
18
+
19
+ IMAGES: Final = (v04.Image, v04.LabelImage, v05.Image, v05.LabelImage)
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class NgffImage:
24
+ """An OME-Zarr image, reduced to what serving it as one array needs.
25
+
26
+ Attributes
27
+ ----------
28
+ dims : tuple[str, ...]
29
+ Axis names, in array order.
30
+ axes : tuple[Mapping[str, Any], ...]
31
+ Each axis as the metadata writes it: ``name``, ``type`` and ``unit``
32
+ when present.
33
+ path : str
34
+ Path of the full-resolution array, relative to the image group.
35
+ """
36
+
37
+ dims: tuple[str, ...]
38
+ axes: tuple[Mapping[str, Any], ...]
39
+ path: str
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class NgffSkipped:
44
+ """An OME-Zarr group this package does not serve, and why."""
45
+
46
+ reason: str
47
+
48
+
49
+ def classify(attributes: Mapping[str, Any]) -> NgffImage | NgffSkipped | None:
50
+ """Classify a Zarr group by its attributes.
51
+
52
+ Returns
53
+ -------
54
+ NgffImage | NgffSkipped | None
55
+ ``NgffImage`` for an NGFF 0.4 or 0.5 image or label image,
56
+ ``NgffSkipped`` for any other NGFF layout and for NGFF metadata that
57
+ fails validation, and ``None`` for a group that is not NGFF.
58
+ """
59
+ try:
60
+ node = yaozarrs.validate_ome_object(dict(attributes))
61
+ except ValidationError as error:
62
+ # the errors do not tell a plain group from a broken image, so the keys
63
+ # decide whether the group claimed to be NGFF at all
64
+ if "ome" in attributes or "multiscales" in attributes:
65
+ return NgffSkipped(f"NGFF metadata failed validation: {error}")
66
+ return None
67
+ if isinstance(node, v05.OMEAttributes):
68
+ node = node.ome
69
+ if not isinstance(node, IMAGES):
70
+ return NgffSkipped(type(node).__name__)
71
+ multiscale = node.multiscales[0]
72
+ axes = tuple(axis.model_dump(exclude_none=True) for axis in multiscale.axes)
73
+ return NgffImage(
74
+ dims=tuple(axis["name"] for axis in axes),
75
+ axes=axes,
76
+ path=multiscale.datasets[0].path,
77
+ )
78
+
79
+
80
+ def detect(path: Path, mimetype: str | None) -> str | None:
81
+ """Return ``OME_ZARR_MIMETYPE`` for an OME-Zarr store, *mimetype* for anything else.
82
+
83
+ A directory is an OME-Zarr store when its root group carries NGFF metadata,
84
+ or when a group directly under a plain root is an NGFF image. Pass it to
85
+ ``tiled`` as ``mimetype_detection_hook``.
86
+ """
87
+ if not path.is_dir():
88
+ return mimetype
89
+ try:
90
+ root = zarr.open_group(path, mode="r")
91
+ except (GroupNotFoundError, ContainsArrayError):
92
+ return mimetype
93
+ if classify(root.attrs.asdict()) is not None:
94
+ return OME_ZARR_MIMETYPE
95
+ for _, child in root.groups():
96
+ if isinstance(classify(child.attrs.asdict()), NgffImage):
97
+ return OME_ZARR_MIMETYPE
98
+ return mimetype
File without changes