-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcli.py
More file actions
281 lines (234 loc) · 8.23 KB
/
cli.py
File metadata and controls
281 lines (234 loc) · 8.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
"""
Command-line interface for geozarr-toolkit.
Usage:
geozarr validate <path> [--conventions ...]
geozarr info <path> [--json]
"""
from __future__ import annotations
import argparse
import json
from pathlib import Path
from typing import TYPE_CHECKING
import structlog
if TYPE_CHECKING:
from collections.abc import Sequence
log = structlog.get_logger()
def create_parser() -> argparse.ArgumentParser:
"""Create the argument parser."""
parser = argparse.ArgumentParser(
prog="geozarr",
description="GeoZarr convention utilities",
)
parser.add_argument(
"--version",
action="version",
version=f"%(prog)s {_get_version()}",
)
subparsers = parser.add_subparsers(dest="command", help="Available commands")
# validate command
validate_parser = subparsers.add_parser(
"validate",
help="Validate a Zarr store against GeoZarr conventions",
)
validate_parser.add_argument(
"input_path",
help="Path to Zarr store",
)
validate_parser.add_argument(
"--conventions",
nargs="+",
choices=["spatial", "proj", "multiscales", "geoemb"],
help="Conventions to validate (auto-detected if not specified)",
)
validate_parser.add_argument(
"--verbose",
"-v",
action="store_true",
help="Show detailed output",
)
validate_parser.set_defaults(func=validate_command)
# info command
info_parser = subparsers.add_parser(
"info",
help="Display information about a Zarr store",
)
info_parser.add_argument(
"input_path",
help="Path to Zarr store",
)
info_parser.add_argument(
"--json",
action="store_true",
dest="output_json",
help="Output as JSON",
)
info_parser.add_argument(
"--verbose",
"-v",
action="store_true",
help="Show detailed output",
)
info_parser.set_defaults(func=info_command)
return parser
def _get_version() -> str:
"""Get the package version."""
try:
from geozarr_toolkit._version import version
return version
except ImportError:
return "unknown"
def validate_command(args: argparse.Namespace) -> int:
"""Run the validate command."""
import zarr
from geozarr_toolkit.helpers import detect_conventions, validate_group
input_path = Path(args.input_path)
if not input_path.exists():
log.error("Input path does not exist", path=str(input_path))
print(f"Error: Path does not exist: {input_path}")
return 1
try:
group = zarr.open_group(str(input_path), mode="r")
except Exception as e:
log.error("Failed to open Zarr store", path=str(input_path), error=str(e))
print(f"Error: Failed to open Zarr store: {e}")
return 1
# Determine conventions to validate
conventions = args.conventions
if conventions is None:
conventions = detect_conventions(dict(group.attrs))
if args.verbose:
print(f"Auto-detected conventions: {', '.join(conventions) or 'none'}")
if not conventions:
print("No conventions detected in store")
return 0
# Validate
results = validate_group(group, conventions)
# Report results
has_errors = False
for conv, errors in results.items():
if errors:
has_errors = True
print(f"[FAIL] {conv}:")
for error in errors:
print(f" - {error}")
elif args.verbose:
print(f"[OK] {conv}")
if not has_errors:
print(f"Validation passed for: {', '.join(conventions)}")
return 0
else:
return 1
def info_command(args: argparse.Namespace) -> int:
"""Run the info command."""
import zarr
from geozarr_toolkit.helpers import detect_conventions
input_path = Path(args.input_path)
if not input_path.exists():
log.error("Input path does not exist", path=str(input_path))
print(f"Error: Path does not exist: {input_path}")
return 1
try:
group = zarr.open_group(str(input_path), mode="r")
except Exception as e:
log.error("Failed to open Zarr store", path=str(input_path), error=str(e))
print(f"Error: Failed to open Zarr store: {e}")
return 1
attrs = dict(group.attrs)
conventions = detect_conventions(attrs)
if args.output_json:
info = {
"path": str(input_path.absolute()),
"conventions": conventions,
"attributes": attrs,
}
if args.verbose:
# Add member info
members: dict[str, dict[str, str | list[int]]] = {}
for name, item in group.items():
if isinstance(item, zarr.Group):
members[name] = {"type": "group"}
else:
members[name] = {
"type": "array",
"shape": [int(s) for s in item.shape],
"dtype": str(item.dtype),
}
info["members"] = members
print(json.dumps(info, indent=2, default=str))
else:
print(f"Path: {input_path.absolute()}")
print(f"Conventions: {', '.join(conventions) or 'none detected'}")
print()
# Show convention-specific info
if "spatial" in conventions:
dims = attrs.get("spatial:dimensions", [])
transform = attrs.get("spatial:transform")
bbox = attrs.get("spatial:bbox")
print("Spatial:")
print(f" Dimensions: {dims}")
if transform:
print(f" Transform: {transform}")
if bbox:
print(f" BBox: {bbox}")
print()
if "proj" in conventions:
code = attrs.get("proj:code")
print("Projection:")
if code:
print(f" Code: {code}")
elif attrs.get("proj:wkt2"):
print(" WKT2: (present)")
elif attrs.get("proj:projjson"):
print(" PROJJSON: (present)")
print()
if "multiscales" in conventions:
ms = attrs.get("multiscales", {})
layout = ms.get("layout", [])
print("Multiscales:")
print(f" Levels: {len(layout)}")
for level in layout:
asset = level.get("asset", "?")
derived = level.get("derived_from", "")
if derived:
print(f" - {asset} (from {derived})")
else:
print(f" - {asset}")
print()
if "geoemb" in conventions:
print("Geoembeddings:")
print(f" Type: {attrs.get('geoemb:type')}")
print(f" Dimensions: {attrs.get('geoemb:dimensions')}")
print(f" Model: {attrs.get('geoemb:model')}")
source_data = attrs.get("geoemb:source_data", [])
print(f" Source data: {len(source_data)} reference(s)")
print(f" Data type: {attrs.get('geoemb:data_type')}")
if attrs.get("geoemb:gsd"):
print(f" GSD: {attrs['geoemb:gsd']}m")
if attrs.get("geoemb:spatial_layout"):
print(f" Spatial layout: {attrs['geoemb:spatial_layout']}")
if attrs.get("geoemb:chip_layout"):
cl = attrs["geoemb:chip_layout"]
print(f" Chip layout: {cl.get('layout_type')} {cl.get('chip_size')}")
if attrs.get("geoemb:quantization"):
q = attrs["geoemb:quantization"]
print(f" Quantization: {q.get('method')} (from {q.get('original_dtype')})")
print()
if args.verbose:
print("Members:")
for name, item in group.items():
if isinstance(item, zarr.Group):
print(f" {name}/ (group)")
else:
print(f" {name}: {item.shape} {item.dtype}")
return 0
def main(argv: Sequence[str] | None = None) -> int:
"""Main entry point."""
parser = create_parser()
args = parser.parse_args(argv)
if args.command is None:
parser.print_help()
return 0
result: int = args.func(args)
return result
if __name__ == "__main__":
main()