omids-validator 0.2.0__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.
- omids_validator/__init__.py +11 -0
- omids_validator/__main__.py +11 -0
- omids_validator/acquisition_profiles.py +478 -0
- omids_validator/cli.py +185 -0
- omids_validator/data/metadata_requirements.json +337 -0
- omids_validator/data/rules.json +364 -0
- omids_validator/file_types.py +46 -0
- omids_validator/inventory.py +133 -0
- omids_validator/models.py +60 -0
- omids_validator/participant_table.py +128 -0
- omids_validator/participants.py +235 -0
- omids_validator/patient_metadata.py +150 -0
- omids_validator/reporters/__init__.py +1 -0
- omids_validator/reporters/html_report.py +607 -0
- omids_validator/reporters/json_report.py +74 -0
- omids_validator/reporters/markdown_report.py +283 -0
- omids_validator/reporters/report_data.py +79 -0
- omids_validator/reporters/terminal.py +18 -0
- omids_validator/rule_catalog.py +279 -0
- omids_validator/rules/__init__.py +5 -0
- omids_validator/rules/layer0_structure.py +316 -0
- omids_validator/rules/layer1_naming.py +191 -0
- omids_validator/rules/layer2_sidecars.py +292 -0
- omids_validator/rules/layer3_metadata.py +144 -0
- omids_validator/rules/layer4_image_headers.py +152 -0
- omids_validator/rules/layer5_dataset.py +261 -0
- omids_validator/rules_document.py +192 -0
- omids_validator/validator.py +274 -0
- omids_validator-0.2.0.dist-info/METADATA +158 -0
- omids_validator-0.2.0.dist-info/RECORD +34 -0
- omids_validator-0.2.0.dist-info/WHEEL +5 -0
- omids_validator-0.2.0.dist-info/entry_points.txt +3 -0
- omids_validator-0.2.0.dist-info/licenses/LICENSE +677 -0
- omids_validator-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""Validate MIDS-formatted musculoskeletal imaging datasets."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
try:
|
|
7
|
+
__version__ = version("omids-validator")
|
|
8
|
+
except PackageNotFoundError:
|
|
9
|
+
# Source-only use has no installed distribution metadata. Release versions
|
|
10
|
+
# are defined only in pyproject.toml.
|
|
11
|
+
__version__ = "0+unknown"
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""Send ``python -m omids_validator`` to the command-line interface.
|
|
2
|
+
|
|
3
|
+
The installed ``omids_validator`` command points directly to ``cli.main``.
|
|
4
|
+
This small adapter gives module execution the same behavior.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from omids_validator.cli import main
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
if __name__ == "__main__":
|
|
11
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,478 @@
|
|
|
1
|
+
"""Load the scan-type definitions used by Layers 1 and 3.
|
|
2
|
+
|
|
3
|
+
The definitions connect recognized filename suffixes with their allowed folders
|
|
4
|
+
and required JSON metadata fields.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
from functools import lru_cache
|
|
9
|
+
from importlib.resources import files
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from omids_validator.file_types import nifti_stem
|
|
14
|
+
from omids_validator.inventory import VALID_DATATYPE_DIRECTORIES
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
METADATA_SCHEMA_VERSION = "0.1"
|
|
18
|
+
REQUIREMENT_STATUSES = frozenset({"mandatory", "optional", "proposed", "draft"})
|
|
19
|
+
PROFILE_FIELDS = frozenset(
|
|
20
|
+
{
|
|
21
|
+
"imaging_method",
|
|
22
|
+
"folders",
|
|
23
|
+
"suffixes",
|
|
24
|
+
"image_dimensions",
|
|
25
|
+
"dimension_labels",
|
|
26
|
+
"json_fields",
|
|
27
|
+
"inherits_json_fields_from",
|
|
28
|
+
"profile_notes",
|
|
29
|
+
"profile_status",
|
|
30
|
+
"suffix_status",
|
|
31
|
+
}
|
|
32
|
+
)
|
|
33
|
+
REQUIRED_PROFILE_FIELDS = frozenset(
|
|
34
|
+
{
|
|
35
|
+
"imaging_method",
|
|
36
|
+
"folders",
|
|
37
|
+
"suffixes",
|
|
38
|
+
"image_dimensions",
|
|
39
|
+
"dimension_labels",
|
|
40
|
+
"json_fields",
|
|
41
|
+
}
|
|
42
|
+
)
|
|
43
|
+
JSON_FIELD_FIELDS = frozenset(
|
|
44
|
+
{
|
|
45
|
+
"name",
|
|
46
|
+
"requirement_status",
|
|
47
|
+
"unit",
|
|
48
|
+
"expected_json_type",
|
|
49
|
+
"expected_value",
|
|
50
|
+
"allowed_values",
|
|
51
|
+
"transcription_note",
|
|
52
|
+
}
|
|
53
|
+
)
|
|
54
|
+
REQUIRED_JSON_FIELD_FIELDS = frozenset({"name", "requirement_status", "unit"})
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class MetadataRequirementsError(ValueError):
|
|
58
|
+
"""Raised when the packaged metadata requirements are inconsistent."""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _require_object(value: object, location: str) -> dict[str, Any]:
|
|
62
|
+
if not isinstance(value, dict):
|
|
63
|
+
raise MetadataRequirementsError(f"{location} must be a JSON object.")
|
|
64
|
+
return value
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _require_nonempty_string(value: object, location: str) -> str:
|
|
68
|
+
if not isinstance(value, str) or not value.strip():
|
|
69
|
+
raise MetadataRequirementsError(f"{location} must be a non-empty string.")
|
|
70
|
+
return value
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _require_string_list(
|
|
74
|
+
value: object,
|
|
75
|
+
location: str,
|
|
76
|
+
*,
|
|
77
|
+
allow_empty: bool,
|
|
78
|
+
) -> list[str]:
|
|
79
|
+
if not isinstance(value, list):
|
|
80
|
+
raise MetadataRequirementsError(f"{location} must be a JSON array.")
|
|
81
|
+
if not allow_empty and not value:
|
|
82
|
+
raise MetadataRequirementsError(f"{location} must not be empty.")
|
|
83
|
+
|
|
84
|
+
strings: list[str] = []
|
|
85
|
+
for index, item in enumerate(value):
|
|
86
|
+
strings.append(_require_nonempty_string(item, f"{location}[{index}]"))
|
|
87
|
+
return strings
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _require_known_fields(
|
|
91
|
+
value: dict[str, Any],
|
|
92
|
+
*,
|
|
93
|
+
required: frozenset[str],
|
|
94
|
+
allowed: frozenset[str],
|
|
95
|
+
location: str,
|
|
96
|
+
) -> None:
|
|
97
|
+
missing = sorted(required - value.keys())
|
|
98
|
+
unexpected = sorted(value.keys() - allowed)
|
|
99
|
+
if missing:
|
|
100
|
+
raise MetadataRequirementsError(
|
|
101
|
+
f"{location} is missing required field(s): {', '.join(missing)}."
|
|
102
|
+
)
|
|
103
|
+
if unexpected:
|
|
104
|
+
raise MetadataRequirementsError(
|
|
105
|
+
f"{location} has unexpected field(s): {', '.join(unexpected)}."
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _validate_json_field(
|
|
110
|
+
value: object,
|
|
111
|
+
*,
|
|
112
|
+
profile_name: str,
|
|
113
|
+
index: int,
|
|
114
|
+
) -> str:
|
|
115
|
+
location = f"profiles.{profile_name}.json_fields[{index}]"
|
|
116
|
+
field = _require_object(value, location)
|
|
117
|
+
_require_known_fields(
|
|
118
|
+
field,
|
|
119
|
+
required=REQUIRED_JSON_FIELD_FIELDS,
|
|
120
|
+
allowed=JSON_FIELD_FIELDS,
|
|
121
|
+
location=location,
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
field_name = _require_nonempty_string(field["name"], f"{location}.name")
|
|
125
|
+
requirement_status = _require_nonempty_string(
|
|
126
|
+
field["requirement_status"],
|
|
127
|
+
f"{location}.requirement_status",
|
|
128
|
+
)
|
|
129
|
+
if requirement_status not in REQUIREMENT_STATUSES:
|
|
130
|
+
allowed_statuses = ", ".join(sorted(REQUIREMENT_STATUSES))
|
|
131
|
+
raise MetadataRequirementsError(
|
|
132
|
+
f"{location}.requirement_status must be one of: {allowed_statuses}."
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
unit = field["unit"]
|
|
136
|
+
if unit is not None:
|
|
137
|
+
_require_nonempty_string(unit, f"{location}.unit")
|
|
138
|
+
|
|
139
|
+
for optional_string in (
|
|
140
|
+
"expected_json_type",
|
|
141
|
+
"expected_value",
|
|
142
|
+
"transcription_note",
|
|
143
|
+
):
|
|
144
|
+
if optional_string in field:
|
|
145
|
+
_require_nonempty_string(
|
|
146
|
+
field[optional_string],
|
|
147
|
+
f"{location}.{optional_string}",
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
if "allowed_values" in field:
|
|
151
|
+
_require_string_list(
|
|
152
|
+
field["allowed_values"],
|
|
153
|
+
f"{location}.allowed_values",
|
|
154
|
+
allow_empty=False,
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
return field_name
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _validate_profile(profile_name: str, value: object) -> dict[str, Any]:
|
|
161
|
+
location = f"profiles.{profile_name}"
|
|
162
|
+
profile = _require_object(value, location)
|
|
163
|
+
_require_known_fields(
|
|
164
|
+
profile,
|
|
165
|
+
required=REQUIRED_PROFILE_FIELDS,
|
|
166
|
+
allowed=PROFILE_FIELDS,
|
|
167
|
+
location=location,
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
_require_nonempty_string(profile["imaging_method"], f"{location}.imaging_method")
|
|
171
|
+
folders = _require_string_list(
|
|
172
|
+
profile["folders"],
|
|
173
|
+
f"{location}.folders",
|
|
174
|
+
allow_empty=False,
|
|
175
|
+
)
|
|
176
|
+
unsupported_folders = sorted(set(folders) - VALID_DATATYPE_DIRECTORIES)
|
|
177
|
+
if unsupported_folders:
|
|
178
|
+
raise MetadataRequirementsError(
|
|
179
|
+
f"{location}.folders contains unsupported value(s): "
|
|
180
|
+
+ ", ".join(unsupported_folders)
|
|
181
|
+
+ "."
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
_require_string_list(
|
|
185
|
+
profile["suffixes"],
|
|
186
|
+
f"{location}.suffixes",
|
|
187
|
+
allow_empty=True,
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
image_dimensions = profile["image_dimensions"]
|
|
191
|
+
if not isinstance(image_dimensions, list) or not image_dimensions:
|
|
192
|
+
raise MetadataRequirementsError(
|
|
193
|
+
f"{location}.image_dimensions must be a non-empty JSON array."
|
|
194
|
+
)
|
|
195
|
+
for index, dimension in enumerate(image_dimensions):
|
|
196
|
+
if (
|
|
197
|
+
not isinstance(dimension, int)
|
|
198
|
+
or isinstance(dimension, bool)
|
|
199
|
+
or dimension <= 0
|
|
200
|
+
):
|
|
201
|
+
raise MetadataRequirementsError(
|
|
202
|
+
f"{location}.image_dimensions[{index}] must be a positive integer."
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
_require_string_list(
|
|
206
|
+
profile["dimension_labels"],
|
|
207
|
+
f"{location}.dimension_labels",
|
|
208
|
+
allow_empty=False,
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
json_fields = profile["json_fields"]
|
|
212
|
+
if not isinstance(json_fields, list):
|
|
213
|
+
raise MetadataRequirementsError(
|
|
214
|
+
f"{location}.json_fields must be a JSON array."
|
|
215
|
+
)
|
|
216
|
+
field_names: set[str] = set()
|
|
217
|
+
for index, field in enumerate(json_fields):
|
|
218
|
+
field_name = _validate_json_field(
|
|
219
|
+
field,
|
|
220
|
+
profile_name=profile_name,
|
|
221
|
+
index=index,
|
|
222
|
+
)
|
|
223
|
+
if field_name in field_names:
|
|
224
|
+
raise MetadataRequirementsError(
|
|
225
|
+
f"{location}.json_fields repeats field {field_name!r}."
|
|
226
|
+
)
|
|
227
|
+
field_names.add(field_name)
|
|
228
|
+
|
|
229
|
+
for optional_string in (
|
|
230
|
+
"inherits_json_fields_from",
|
|
231
|
+
"profile_status",
|
|
232
|
+
"suffix_status",
|
|
233
|
+
):
|
|
234
|
+
if optional_string in profile:
|
|
235
|
+
_require_nonempty_string(
|
|
236
|
+
profile[optional_string],
|
|
237
|
+
f"{location}.{optional_string}",
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
if "profile_notes" in profile:
|
|
241
|
+
_require_string_list(
|
|
242
|
+
profile["profile_notes"],
|
|
243
|
+
f"{location}.profile_notes",
|
|
244
|
+
allow_empty=False,
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
return profile
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _validate_profile_relationships(profiles: dict[str, dict[str, Any]]) -> None:
|
|
251
|
+
suffix_owners: dict[str, str] = {}
|
|
252
|
+
for profile_name, profile in profiles.items():
|
|
253
|
+
for suffix in profile["suffixes"]:
|
|
254
|
+
normalized_suffix = suffix.casefold()
|
|
255
|
+
existing_owner = suffix_owners.get(normalized_suffix)
|
|
256
|
+
if existing_owner is not None:
|
|
257
|
+
raise MetadataRequirementsError(
|
|
258
|
+
f"Suffix {suffix!r} is assigned to both {existing_owner!r} "
|
|
259
|
+
f"and {profile_name!r}."
|
|
260
|
+
)
|
|
261
|
+
suffix_owners[normalized_suffix] = profile_name
|
|
262
|
+
|
|
263
|
+
visited: set[str] = set()
|
|
264
|
+
visiting: set[str] = set()
|
|
265
|
+
|
|
266
|
+
def visit(profile_name: str) -> None:
|
|
267
|
+
if profile_name in visited:
|
|
268
|
+
return
|
|
269
|
+
if profile_name in visiting:
|
|
270
|
+
raise MetadataRequirementsError(
|
|
271
|
+
f"Profile inheritance contains a cycle at {profile_name!r}."
|
|
272
|
+
)
|
|
273
|
+
|
|
274
|
+
visiting.add(profile_name)
|
|
275
|
+
parent_name = profiles[profile_name].get("inherits_json_fields_from")
|
|
276
|
+
if parent_name is not None:
|
|
277
|
+
if parent_name not in profiles:
|
|
278
|
+
raise MetadataRequirementsError(
|
|
279
|
+
f"Profile {profile_name!r} inherits from unknown profile "
|
|
280
|
+
f"{parent_name!r}."
|
|
281
|
+
)
|
|
282
|
+
visit(parent_name)
|
|
283
|
+
visiting.remove(profile_name)
|
|
284
|
+
visited.add(profile_name)
|
|
285
|
+
|
|
286
|
+
for profile_name in profiles:
|
|
287
|
+
visit(profile_name)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def validate_metadata_requirements(value: object) -> dict[str, Any]:
|
|
291
|
+
"""Validate decoded metadata requirements and return the original mapping."""
|
|
292
|
+
|
|
293
|
+
requirements = _require_object(value, "Metadata requirements")
|
|
294
|
+
top_level_fields = frozenset(
|
|
295
|
+
{"schema_version", "status", "source", "notes", "profiles", "shared_semantics"}
|
|
296
|
+
)
|
|
297
|
+
_require_known_fields(
|
|
298
|
+
requirements,
|
|
299
|
+
required=top_level_fields,
|
|
300
|
+
allowed=top_level_fields,
|
|
301
|
+
location="Metadata requirements",
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
schema_version = _require_nonempty_string(
|
|
305
|
+
requirements["schema_version"],
|
|
306
|
+
"Metadata requirements.schema_version",
|
|
307
|
+
)
|
|
308
|
+
if schema_version != METADATA_SCHEMA_VERSION:
|
|
309
|
+
raise MetadataRequirementsError(
|
|
310
|
+
"Unsupported metadata-requirements schema version "
|
|
311
|
+
f"{schema_version!r}; expected {METADATA_SCHEMA_VERSION!r}."
|
|
312
|
+
)
|
|
313
|
+
|
|
314
|
+
_require_nonempty_string(requirements["status"], "Metadata requirements.status")
|
|
315
|
+
_require_nonempty_string(requirements["source"], "Metadata requirements.source")
|
|
316
|
+
_require_string_list(
|
|
317
|
+
requirements["notes"],
|
|
318
|
+
"Metadata requirements.notes",
|
|
319
|
+
allow_empty=True,
|
|
320
|
+
)
|
|
321
|
+
_require_object(
|
|
322
|
+
requirements["shared_semantics"],
|
|
323
|
+
"Metadata requirements.shared_semantics",
|
|
324
|
+
)
|
|
325
|
+
|
|
326
|
+
raw_profiles = _require_object(
|
|
327
|
+
requirements["profiles"],
|
|
328
|
+
"Metadata requirements.profiles",
|
|
329
|
+
)
|
|
330
|
+
if not raw_profiles:
|
|
331
|
+
raise MetadataRequirementsError(
|
|
332
|
+
"Metadata requirements.profiles must not be empty."
|
|
333
|
+
)
|
|
334
|
+
|
|
335
|
+
profiles: dict[str, dict[str, Any]] = {}
|
|
336
|
+
for profile_name, profile in raw_profiles.items():
|
|
337
|
+
normalized_name = _require_nonempty_string(
|
|
338
|
+
profile_name,
|
|
339
|
+
"Metadata requirements profile name",
|
|
340
|
+
)
|
|
341
|
+
profiles[normalized_name] = _validate_profile(normalized_name, profile)
|
|
342
|
+
|
|
343
|
+
_validate_profile_relationships(profiles)
|
|
344
|
+
return requirements
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _object_without_duplicate_keys(
|
|
348
|
+
pairs: list[tuple[str, object]],
|
|
349
|
+
) -> dict[str, object]:
|
|
350
|
+
result: dict[str, object] = {}
|
|
351
|
+
for key, value in pairs:
|
|
352
|
+
if key in result:
|
|
353
|
+
raise MetadataRequirementsError(
|
|
354
|
+
f"Metadata requirements repeat JSON key {key!r}."
|
|
355
|
+
)
|
|
356
|
+
result[key] = value
|
|
357
|
+
return result
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def parse_metadata_requirements(text: str) -> dict[str, Any]:
|
|
361
|
+
"""Decode and validate metadata-requirements JSON text."""
|
|
362
|
+
|
|
363
|
+
try:
|
|
364
|
+
value = json.loads(text, object_pairs_hook=_object_without_duplicate_keys)
|
|
365
|
+
except json.JSONDecodeError as error:
|
|
366
|
+
raise MetadataRequirementsError(
|
|
367
|
+
f"Metadata requirements are not valid JSON: {error.msg}."
|
|
368
|
+
) from error
|
|
369
|
+
return validate_metadata_requirements(value)
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
@lru_cache(maxsize=1)
|
|
373
|
+
def load_metadata_requirements() -> dict[str, Any]:
|
|
374
|
+
"""Load and validate the packaged metadata-requirements catalogue once."""
|
|
375
|
+
|
|
376
|
+
requirements_path = files("omids_validator").joinpath(
|
|
377
|
+
"data",
|
|
378
|
+
"metadata_requirements.json",
|
|
379
|
+
)
|
|
380
|
+
try:
|
|
381
|
+
text = requirements_path.read_text(encoding="utf-8")
|
|
382
|
+
except OSError as error:
|
|
383
|
+
raise MetadataRequirementsError(
|
|
384
|
+
f"Metadata requirements could not be read: {error}."
|
|
385
|
+
) from error
|
|
386
|
+
return parse_metadata_requirements(text)
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def acquisition_profiles() -> dict[str, dict[str, Any]]:
|
|
390
|
+
"""Return the acquisition profiles from the requirements catalogue."""
|
|
391
|
+
|
|
392
|
+
return load_metadata_requirements()["profiles"]
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
@lru_cache(maxsize=1)
|
|
396
|
+
def _suffix_to_profile_name() -> dict[str, str]:
|
|
397
|
+
"""Return case-folded recognized suffixes mapped to profile names."""
|
|
398
|
+
|
|
399
|
+
suffix_map: dict[str, str] = {}
|
|
400
|
+
|
|
401
|
+
for profile_name, profile in acquisition_profiles().items():
|
|
402
|
+
for suffix in profile.get("suffixes", []):
|
|
403
|
+
normalized_suffix = suffix.casefold()
|
|
404
|
+
if normalized_suffix in suffix_map:
|
|
405
|
+
raise ValueError(
|
|
406
|
+
f"Acquisition suffix is assigned twice: {suffix}"
|
|
407
|
+
)
|
|
408
|
+
suffix_map[normalized_suffix] = profile_name
|
|
409
|
+
|
|
410
|
+
return suffix_map
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def image_suffix(image_path: Path) -> str | None:
|
|
414
|
+
"""Return a recognized compound suffix or the final filename component."""
|
|
415
|
+
|
|
416
|
+
image_stem = nifti_stem(image_path)
|
|
417
|
+
if image_stem is None:
|
|
418
|
+
return None
|
|
419
|
+
|
|
420
|
+
normalized_stem = image_stem.casefold()
|
|
421
|
+
recognized_suffixes = sorted(
|
|
422
|
+
_suffix_to_profile_name(),
|
|
423
|
+
key=len,
|
|
424
|
+
reverse=True,
|
|
425
|
+
)
|
|
426
|
+
|
|
427
|
+
for recognized_suffix in recognized_suffixes:
|
|
428
|
+
if normalized_stem.endswith(f"_{recognized_suffix}"):
|
|
429
|
+
return recognized_suffix
|
|
430
|
+
|
|
431
|
+
if "_" not in image_stem:
|
|
432
|
+
return None
|
|
433
|
+
|
|
434
|
+
return image_stem.rsplit("_", maxsplit=1)[-1]
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def acquisition_profile_for_suffix(
|
|
438
|
+
suffix: str,
|
|
439
|
+
) -> dict[str, Any] | None:
|
|
440
|
+
"""Return the recognized acquisition profile for a suffix, if any."""
|
|
441
|
+
|
|
442
|
+
profile_name = _suffix_to_profile_name().get(suffix.casefold())
|
|
443
|
+
if profile_name is None:
|
|
444
|
+
return None
|
|
445
|
+
|
|
446
|
+
return acquisition_profiles()[profile_name]
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
@lru_cache(maxsize=None)
|
|
450
|
+
def _resolved_metadata_fields(
|
|
451
|
+
profile_name: str,
|
|
452
|
+
) -> tuple[dict[str, Any], ...]:
|
|
453
|
+
"""Return inherited fields with child definitions overriding parents."""
|
|
454
|
+
|
|
455
|
+
profile = acquisition_profiles()[profile_name]
|
|
456
|
+
fields_by_name: dict[str, dict[str, Any]] = {}
|
|
457
|
+
parent_name = profile.get("inherits_json_fields_from")
|
|
458
|
+
|
|
459
|
+
if parent_name is not None:
|
|
460
|
+
for field in _resolved_metadata_fields(parent_name):
|
|
461
|
+
fields_by_name[field["name"]] = field
|
|
462
|
+
|
|
463
|
+
for field in profile.get("json_fields", []):
|
|
464
|
+
fields_by_name[field["name"]] = field
|
|
465
|
+
|
|
466
|
+
return tuple(fields_by_name.values())
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def metadata_fields_for_suffix(
|
|
470
|
+
suffix: str,
|
|
471
|
+
) -> tuple[dict[str, Any], ...] | None:
|
|
472
|
+
"""Return resolved metadata fields for a recognized image suffix."""
|
|
473
|
+
|
|
474
|
+
profile_name = _suffix_to_profile_name().get(suffix.casefold())
|
|
475
|
+
if profile_name is None:
|
|
476
|
+
return None
|
|
477
|
+
|
|
478
|
+
return _resolved_metadata_fields(profile_name)
|
omids_validator/cli.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""Run the OMIDS Validator command-line interface.
|
|
2
|
+
|
|
3
|
+
This module reads command-line options, asks the validator to check a dataset,
|
|
4
|
+
and writes the terminal, HTML, Markdown, and JSON reports. It also handles the
|
|
5
|
+
separate ``--rules`` command for generating the rule catalogue document.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import argparse
|
|
9
|
+
import sys
|
|
10
|
+
from datetime import datetime
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from omids_validator.reporters import html_report, json_report, markdown_report, terminal
|
|
14
|
+
from omids_validator.rules_document import write_rules_markdown
|
|
15
|
+
from omids_validator.validator import validate
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
VALIDATION_ERROR = 1
|
|
19
|
+
SETUP_ERROR = 2
|
|
20
|
+
RULES_DOCUMENT_NAME = "omids_validator_rules.md"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
24
|
+
parser = argparse.ArgumentParser(
|
|
25
|
+
description="Validate a MIDS dataset or generate the rule catalogue."
|
|
26
|
+
)
|
|
27
|
+
parser.add_argument(
|
|
28
|
+
"dataset",
|
|
29
|
+
nargs="?",
|
|
30
|
+
type=Path,
|
|
31
|
+
help="dataset directory; omit when using --rules",
|
|
32
|
+
)
|
|
33
|
+
parser.add_argument(
|
|
34
|
+
"-p",
|
|
35
|
+
"--participants",
|
|
36
|
+
action="store_true",
|
|
37
|
+
help=(
|
|
38
|
+
"create or populate participants.tsv with discovered subject IDs "
|
|
39
|
+
"and available patient age and sex metadata"
|
|
40
|
+
),
|
|
41
|
+
)
|
|
42
|
+
parser.add_argument(
|
|
43
|
+
"-i",
|
|
44
|
+
"--inspect-images",
|
|
45
|
+
action="store_true",
|
|
46
|
+
help="inspect NIfTI headers",
|
|
47
|
+
)
|
|
48
|
+
parser.add_argument(
|
|
49
|
+
"-o",
|
|
50
|
+
"--output-dir",
|
|
51
|
+
type=Path,
|
|
52
|
+
default=Path.cwd(),
|
|
53
|
+
help=(
|
|
54
|
+
"output directory; validation creates a timestamped child "
|
|
55
|
+
"directory"
|
|
56
|
+
),
|
|
57
|
+
)
|
|
58
|
+
parser.add_argument(
|
|
59
|
+
"--rules",
|
|
60
|
+
action="store_true",
|
|
61
|
+
help="write omids_validator_rules.md and exit without validating a dataset",
|
|
62
|
+
)
|
|
63
|
+
return parser
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _validate_arguments(
|
|
67
|
+
parser: argparse.ArgumentParser,
|
|
68
|
+
args: argparse.Namespace,
|
|
69
|
+
) -> None:
|
|
70
|
+
"""Require exactly one CLI mode and reject incompatible options."""
|
|
71
|
+
|
|
72
|
+
if args.rules:
|
|
73
|
+
incompatible: list[str] = []
|
|
74
|
+
if args.dataset is not None:
|
|
75
|
+
incompatible.append("DATASET")
|
|
76
|
+
if args.participants:
|
|
77
|
+
incompatible.append("--participants")
|
|
78
|
+
if args.inspect_images:
|
|
79
|
+
incompatible.append("--inspect-images")
|
|
80
|
+
if incompatible:
|
|
81
|
+
parser.error(
|
|
82
|
+
"--rules cannot be combined with " + ", ".join(incompatible)
|
|
83
|
+
)
|
|
84
|
+
return
|
|
85
|
+
|
|
86
|
+
if args.dataset is None:
|
|
87
|
+
parser.error("DATASET is required unless --rules is supplied")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _write_rules_document(output_directory: Path) -> Path:
|
|
91
|
+
"""Write the generated rules document and return its absolute path."""
|
|
92
|
+
|
|
93
|
+
resolved_output = output_directory.expanduser().resolve()
|
|
94
|
+
resolved_output.mkdir(parents=True, exist_ok=True)
|
|
95
|
+
rules_path = resolved_output / RULES_DOCUMENT_NAME
|
|
96
|
+
write_rules_markdown(rules_path)
|
|
97
|
+
return rules_path
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _create_report_directory(parent: Path) -> Path:
|
|
101
|
+
"""Create a timestamped, collision-free report directory."""
|
|
102
|
+
|
|
103
|
+
parent.mkdir(parents=True, exist_ok=True)
|
|
104
|
+
stamp = datetime.now().strftime("%Y-%m-%d_%H%M%S")
|
|
105
|
+
candidate = parent / f"omids_reports_{stamp}"
|
|
106
|
+
suffix = 1
|
|
107
|
+
while True:
|
|
108
|
+
try:
|
|
109
|
+
candidate.mkdir()
|
|
110
|
+
return candidate
|
|
111
|
+
except FileExistsError:
|
|
112
|
+
candidate = parent / f"omids_reports_{stamp}_{suffix:02d}"
|
|
113
|
+
suffix += 1
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _report_destination_is_inside_dataset(
|
|
117
|
+
dataset_path: Path,
|
|
118
|
+
output_directory: Path,
|
|
119
|
+
) -> bool:
|
|
120
|
+
"""Return whether reports would be written inside the dataset."""
|
|
121
|
+
|
|
122
|
+
resolved_dataset = dataset_path.expanduser().resolve()
|
|
123
|
+
resolved_output = output_directory.expanduser().resolve()
|
|
124
|
+
return resolved_output == resolved_dataset or resolved_output.is_relative_to(
|
|
125
|
+
resolved_dataset
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def main(argv: list[str] | None = None) -> int:
|
|
130
|
+
"""Run dataset validation or generate the rule catalogue document."""
|
|
131
|
+
|
|
132
|
+
parser = build_parser()
|
|
133
|
+
arguments = sys.argv[1:] if argv is None else argv
|
|
134
|
+
if not arguments:
|
|
135
|
+
parser.print_help()
|
|
136
|
+
return 0
|
|
137
|
+
|
|
138
|
+
args = parser.parse_args(arguments)
|
|
139
|
+
_validate_arguments(parser, args)
|
|
140
|
+
|
|
141
|
+
if args.rules:
|
|
142
|
+
try:
|
|
143
|
+
rules_path = _write_rules_document(args.output_dir)
|
|
144
|
+
except (OSError, ValueError) as error:
|
|
145
|
+
print(
|
|
146
|
+
f"omids_validator: unable to write rules document: {error}",
|
|
147
|
+
file=sys.stderr,
|
|
148
|
+
)
|
|
149
|
+
return SETUP_ERROR
|
|
150
|
+
|
|
151
|
+
print(f"OMIDS Validator rules created at {rules_path}")
|
|
152
|
+
return 0
|
|
153
|
+
|
|
154
|
+
if _report_destination_is_inside_dataset(args.dataset, args.output_dir):
|
|
155
|
+
print(
|
|
156
|
+
"omids_validator: report output must be outside the dataset; "
|
|
157
|
+
"choose another directory with --output-dir",
|
|
158
|
+
file=sys.stderr,
|
|
159
|
+
)
|
|
160
|
+
return SETUP_ERROR
|
|
161
|
+
|
|
162
|
+
try:
|
|
163
|
+
report = validate(
|
|
164
|
+
args.dataset,
|
|
165
|
+
inspect_images=args.inspect_images,
|
|
166
|
+
participants_requested=args.participants,
|
|
167
|
+
)
|
|
168
|
+
except (OSError, ValueError) as error:
|
|
169
|
+
print(
|
|
170
|
+
f"omids_validator: unable to validate dataset: {error}",
|
|
171
|
+
file=sys.stderr,
|
|
172
|
+
)
|
|
173
|
+
return SETUP_ERROR
|
|
174
|
+
|
|
175
|
+
try:
|
|
176
|
+
report_directory = _create_report_directory(args.output_dir)
|
|
177
|
+
json_report.write(report, report_directory / "report.json")
|
|
178
|
+
markdown_report.write(report, report_directory / "report.md")
|
|
179
|
+
html_report.write(report, report_directory / "report.html")
|
|
180
|
+
except (OSError, ValueError) as error:
|
|
181
|
+
print(f"omids_validator: unable to write report: {error}", file=sys.stderr)
|
|
182
|
+
return SETUP_ERROR
|
|
183
|
+
|
|
184
|
+
print(terminal.render(report, str(report_directory)))
|
|
185
|
+
return VALIDATION_ERROR if report.summary["error"] else 0
|