sdcreader 4.0.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.
- sdcreader-4.0.0/LICENSE +201 -0
- sdcreader-4.0.0/NOTICE +9 -0
- sdcreader-4.0.0/PKG-INFO +109 -0
- sdcreader-4.0.0/README.md +83 -0
- sdcreader-4.0.0/pyproject.toml +40 -0
- sdcreader-4.0.0/setup.cfg +4 -0
- sdcreader-4.0.0/src/sdcreader/__init__.py +18 -0
- sdcreader-4.0.0/src/sdcreader/model.py +233 -0
- sdcreader-4.0.0/src/sdcreader/package.py +106 -0
- sdcreader-4.0.0/src/sdcreader.egg-info/PKG-INFO +109 -0
- sdcreader-4.0.0/src/sdcreader.egg-info/SOURCES.txt +13 -0
- sdcreader-4.0.0/src/sdcreader.egg-info/dependency_links.txt +1 -0
- sdcreader-4.0.0/src/sdcreader.egg-info/requires.txt +8 -0
- sdcreader-4.0.0/src/sdcreader.egg-info/top_level.txt +1 -0
- sdcreader-4.0.0/tests/test_reader.py +118 -0
sdcreader-4.0.0/LICENSE
ADDED
|
@@ -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 [yyyy] [name of copyright owner]
|
|
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.
|
sdcreader-4.0.0/NOTICE
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
sdcreader
|
|
2
|
+
Copyright 2026 Axius SDC, Inc.
|
|
3
|
+
|
|
4
|
+
Licensed under the Apache License, Version 2.0.
|
|
5
|
+
|
|
6
|
+
The test fixture under samples/nhanes-participant/ is the published package of the NHANES Participant model of the
|
|
7
|
+
FAIR Data Demo (https://github.com/SemanticDataCharter/FAIR_Data_Demo), fetched from SDCStudio's public catalog, a
|
|
8
|
+
Semantic Data Charter model of National Health and Nutrition Examination Survey (CDC) variables; it is used as
|
|
9
|
+
evidence, unchanged.
|
sdcreader-4.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sdcreader
|
|
3
|
+
Version: 4.0.0
|
|
4
|
+
Summary: Read a published Semantic Data Charter model's package for projection into other standards (CDIF, DCAT-US, DCAT-AP, HealthDCAT-AP).
|
|
5
|
+
Author: Axius SDC, Inc.
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/SemanticDataCharter/sdcreader
|
|
8
|
+
Project-URL: Changelog, https://github.com/SemanticDataCharter/sdcreader/blob/main/CHANGELOG.md
|
|
9
|
+
Keywords: sdc,semantic data charter,governed data record,cdif,dcat,dcat-ap,healthdcat-ap,fair
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
License-File: NOTICE
|
|
19
|
+
Requires-Dist: lxml>=5.0
|
|
20
|
+
Provides-Extra: fetch
|
|
21
|
+
Requires-Dist: requests>=2.31; extra == "fetch"
|
|
22
|
+
Provides-Extra: dev
|
|
23
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
24
|
+
Requires-Dist: requests>=2.31; extra == "dev"
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
|
|
27
|
+
# sdcreader
|
|
28
|
+
|
|
29
|
+
Read a published Semantic Data Charter model's package for projection into other standards.
|
|
30
|
+
|
|
31
|
+
A projection describes a model's governed data records in another standard's terms: CDIF, DCAT-US 3.0, DCAT-AP
|
|
32
|
+
3.0.1, HealthDCAT-AP, and whatever comes next. What every projection describes is the same evidence, the model's
|
|
33
|
+
package, and reads it into the same shape. `sdcreader` is that evidence and that shape, once, with nothing about
|
|
34
|
+
any projection in it. The four projection writers (`sdc_cdif`, `sdc_dcat3_us`, `sdc_dcat3_ap`, `sdc_healthdcat_ap`)
|
|
35
|
+
carried it as identical copies until this package.
|
|
36
|
+
|
|
37
|
+
```
|
|
38
|
+
pip install sdcreader # or, until the PyPI release: pip install "sdcreader @ git+https://github.com/SemanticDataCharter/sdcreader@v4.0.0"
|
|
39
|
+
pip install "sdcreader[fetch]" # with HTTP, to fetch a package from the public catalog
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
from sdcreader import fetch_package, load_package, read_model
|
|
44
|
+
|
|
45
|
+
pkg = load_package("samples/nhanes-participant") # a package on disk
|
|
46
|
+
pkg = fetch_package("xy8upneajsb8vdcmnve01g6g", save_to="pkg/") # or from SDCStudio's public catalog, no account
|
|
47
|
+
model = read_model(pkg)
|
|
48
|
+
|
|
49
|
+
pkg.schema_url_pinned # https://sdcstudio.axius-sdc.com/dmlib/dm-xy8u...xsd?sha256=0df4... the exact bytes the records are validated against
|
|
50
|
+
model.title, model.leaves # 'NHANES Participant', 153 leaves in document order, each with its path of clusters
|
|
51
|
+
model.codes[ct_id] # the enumerated values of a component with the IRI, definition and code the schema annotates them with
|
|
52
|
+
model.dc("publisher") # what the modeler wrote, None where SDCStudio's default sits
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## What a package is
|
|
56
|
+
|
|
57
|
+
SDCStudio generates a package for every published model and serves it publicly for models in public projects:
|
|
58
|
+
|
|
59
|
+
| | |
|
|
60
|
+
|---|---|
|
|
61
|
+
| `GET /api/v1/catalog/dm/<ct>/` | the catalog record: title, description, project, the artifact list (`catalog.json`) |
|
|
62
|
+
| `GET /api/v1/catalog/dm/<ct>/<artifact>/` | a storage pointer, `{"download_url": ..., "filename": ..., "storage": "gcs"}`, for `jsonld`, `xsd` and the rest; the reader follows it |
|
|
63
|
+
| `dm-<ct>.jsonld` | the model and its components: type, label, description, cardinality, constraints (enumerations, units, ranges, patterns), semantic links (`dcterms:identifier` the library slot, `dcterms:source`, `dcterms:publisher`, `skos:exactMatch`, `rdfs:seeAlso`, `prov:wasRevisionOf`), `contains` |
|
|
64
|
+
| `GET /dmlib/dm-<ct>.xsd` | the schema bytes: the Dublin Core header for the model, and for each enumerated value its definition and the code it is defined by (`dm-<ct>.xsd`) |
|
|
65
|
+
| `GET /dmlib/dm-<ct>.versions.json` | every published version of the schema by SHA-256, with the current one (`versions.json`) |
|
|
66
|
+
|
|
67
|
+
A package directory holds those four files. The reader refuses a directory without the JSON-LD and the schema, a
|
|
68
|
+
JSON-LD whose identifier is not the directory's model, and a schema whose bytes are not the published current
|
|
69
|
+
version: a projection cites the schema by URL and SHA-256, so the bytes have to be the ones that URL serves.
|
|
70
|
+
|
|
71
|
+
Two gaps in the package are on SDCStudio's issue tracker: the JSON-LD metadata drops fields the schema header
|
|
72
|
+
carries (#748), and the header omits `dc:source` (#749). The reader takes the model's Dublin Core from the header,
|
|
73
|
+
which is complete.
|
|
74
|
+
|
|
75
|
+
## What the reader gives
|
|
76
|
+
|
|
77
|
+
- **`ModelPackage`**: the four files, the SHA-256, the schema URL and its pinned form (`?sha256=`), the public
|
|
78
|
+
catalog URL, and `check()`.
|
|
79
|
+
- **`Model`**: `title`, `description`, `root` (the governed record's cluster), `components` by identifier, `leaves`
|
|
80
|
+
in document order (each a `Leaf` with its `component`, its `path` of clusters and a `slug` of that path, unique in
|
|
81
|
+
the record), `codes` (the enumerated values per component as `Code`: value, IRI, definition, the code it is
|
|
82
|
+
defined by), `metadata` (the JSON-LD's) and `header` (the schema's Dublin Core).
|
|
83
|
+
- **`Model.dc(name)`**: what the modeler wrote, the header first and the JSON-LD second, with SDCStudio's field
|
|
84
|
+
defaults as unset: "Universal" for coverage, "None" for relation, "SDC Data Model (DM)" for type, blanks. A
|
|
85
|
+
projection never publishes a default as a fact. `contributors`, `subjects` (the semicolon list), `rights_url` and
|
|
86
|
+
`rights_statement` derive from it.
|
|
87
|
+
- **`Component`**: `sdc_type`, `label`, `description`, `data_type`, `constraints`, `links` by predicate (`link(p)` for
|
|
88
|
+
the first), `contains`, `iri`.
|
|
89
|
+
- Constants: the leaf, numeric and quantified types; the predicate IRIs `IDENTIFIER`, `SOURCE`, `PUBLISHER`, `EXACT`,
|
|
90
|
+
`CLOSE`, `SEE_ALSO`, `HAS_UNIT`; `DC_DEFAULTS`.
|
|
91
|
+
|
|
92
|
+
## Tests
|
|
93
|
+
|
|
94
|
+
```
|
|
95
|
+
pip install -e ".[dev]"
|
|
96
|
+
python -m pytest tests -q # includes one fetch against production
|
|
97
|
+
python -m pytest tests -q -m "not network" # offline, as CI runs it
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
The fixture is the NHANES Participant package of the FAIR Data Demo, the record every projection is proven on.
|
|
101
|
+
|
|
102
|
+
## Versioning
|
|
103
|
+
|
|
104
|
+
The leading 4 is the SDC4 reference model, as with every Semantic Data Charter package. An addition to what the
|
|
105
|
+
reader exposes is a minor version, a fix a patch; the major changes only when the reference model does.
|
|
106
|
+
|
|
107
|
+
## Licence
|
|
108
|
+
|
|
109
|
+
Apache-2.0 (see `LICENSE`, `NOTICE`).
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# sdcreader
|
|
2
|
+
|
|
3
|
+
Read a published Semantic Data Charter model's package for projection into other standards.
|
|
4
|
+
|
|
5
|
+
A projection describes a model's governed data records in another standard's terms: CDIF, DCAT-US 3.0, DCAT-AP
|
|
6
|
+
3.0.1, HealthDCAT-AP, and whatever comes next. What every projection describes is the same evidence, the model's
|
|
7
|
+
package, and reads it into the same shape. `sdcreader` is that evidence and that shape, once, with nothing about
|
|
8
|
+
any projection in it. The four projection writers (`sdc_cdif`, `sdc_dcat3_us`, `sdc_dcat3_ap`, `sdc_healthdcat_ap`)
|
|
9
|
+
carried it as identical copies until this package.
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
pip install sdcreader # or, until the PyPI release: pip install "sdcreader @ git+https://github.com/SemanticDataCharter/sdcreader@v4.0.0"
|
|
13
|
+
pip install "sdcreader[fetch]" # with HTTP, to fetch a package from the public catalog
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
```python
|
|
17
|
+
from sdcreader import fetch_package, load_package, read_model
|
|
18
|
+
|
|
19
|
+
pkg = load_package("samples/nhanes-participant") # a package on disk
|
|
20
|
+
pkg = fetch_package("xy8upneajsb8vdcmnve01g6g", save_to="pkg/") # or from SDCStudio's public catalog, no account
|
|
21
|
+
model = read_model(pkg)
|
|
22
|
+
|
|
23
|
+
pkg.schema_url_pinned # https://sdcstudio.axius-sdc.com/dmlib/dm-xy8u...xsd?sha256=0df4... the exact bytes the records are validated against
|
|
24
|
+
model.title, model.leaves # 'NHANES Participant', 153 leaves in document order, each with its path of clusters
|
|
25
|
+
model.codes[ct_id] # the enumerated values of a component with the IRI, definition and code the schema annotates them with
|
|
26
|
+
model.dc("publisher") # what the modeler wrote, None where SDCStudio's default sits
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## What a package is
|
|
30
|
+
|
|
31
|
+
SDCStudio generates a package for every published model and serves it publicly for models in public projects:
|
|
32
|
+
|
|
33
|
+
| | |
|
|
34
|
+
|---|---|
|
|
35
|
+
| `GET /api/v1/catalog/dm/<ct>/` | the catalog record: title, description, project, the artifact list (`catalog.json`) |
|
|
36
|
+
| `GET /api/v1/catalog/dm/<ct>/<artifact>/` | a storage pointer, `{"download_url": ..., "filename": ..., "storage": "gcs"}`, for `jsonld`, `xsd` and the rest; the reader follows it |
|
|
37
|
+
| `dm-<ct>.jsonld` | the model and its components: type, label, description, cardinality, constraints (enumerations, units, ranges, patterns), semantic links (`dcterms:identifier` the library slot, `dcterms:source`, `dcterms:publisher`, `skos:exactMatch`, `rdfs:seeAlso`, `prov:wasRevisionOf`), `contains` |
|
|
38
|
+
| `GET /dmlib/dm-<ct>.xsd` | the schema bytes: the Dublin Core header for the model, and for each enumerated value its definition and the code it is defined by (`dm-<ct>.xsd`) |
|
|
39
|
+
| `GET /dmlib/dm-<ct>.versions.json` | every published version of the schema by SHA-256, with the current one (`versions.json`) |
|
|
40
|
+
|
|
41
|
+
A package directory holds those four files. The reader refuses a directory without the JSON-LD and the schema, a
|
|
42
|
+
JSON-LD whose identifier is not the directory's model, and a schema whose bytes are not the published current
|
|
43
|
+
version: a projection cites the schema by URL and SHA-256, so the bytes have to be the ones that URL serves.
|
|
44
|
+
|
|
45
|
+
Two gaps in the package are on SDCStudio's issue tracker: the JSON-LD metadata drops fields the schema header
|
|
46
|
+
carries (#748), and the header omits `dc:source` (#749). The reader takes the model's Dublin Core from the header,
|
|
47
|
+
which is complete.
|
|
48
|
+
|
|
49
|
+
## What the reader gives
|
|
50
|
+
|
|
51
|
+
- **`ModelPackage`**: the four files, the SHA-256, the schema URL and its pinned form (`?sha256=`), the public
|
|
52
|
+
catalog URL, and `check()`.
|
|
53
|
+
- **`Model`**: `title`, `description`, `root` (the governed record's cluster), `components` by identifier, `leaves`
|
|
54
|
+
in document order (each a `Leaf` with its `component`, its `path` of clusters and a `slug` of that path, unique in
|
|
55
|
+
the record), `codes` (the enumerated values per component as `Code`: value, IRI, definition, the code it is
|
|
56
|
+
defined by), `metadata` (the JSON-LD's) and `header` (the schema's Dublin Core).
|
|
57
|
+
- **`Model.dc(name)`**: what the modeler wrote, the header first and the JSON-LD second, with SDCStudio's field
|
|
58
|
+
defaults as unset: "Universal" for coverage, "None" for relation, "SDC Data Model (DM)" for type, blanks. A
|
|
59
|
+
projection never publishes a default as a fact. `contributors`, `subjects` (the semicolon list), `rights_url` and
|
|
60
|
+
`rights_statement` derive from it.
|
|
61
|
+
- **`Component`**: `sdc_type`, `label`, `description`, `data_type`, `constraints`, `links` by predicate (`link(p)` for
|
|
62
|
+
the first), `contains`, `iri`.
|
|
63
|
+
- Constants: the leaf, numeric and quantified types; the predicate IRIs `IDENTIFIER`, `SOURCE`, `PUBLISHER`, `EXACT`,
|
|
64
|
+
`CLOSE`, `SEE_ALSO`, `HAS_UNIT`; `DC_DEFAULTS`.
|
|
65
|
+
|
|
66
|
+
## Tests
|
|
67
|
+
|
|
68
|
+
```
|
|
69
|
+
pip install -e ".[dev]"
|
|
70
|
+
python -m pytest tests -q # includes one fetch against production
|
|
71
|
+
python -m pytest tests -q -m "not network" # offline, as CI runs it
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
The fixture is the NHANES Participant package of the FAIR Data Demo, the record every projection is proven on.
|
|
75
|
+
|
|
76
|
+
## Versioning
|
|
77
|
+
|
|
78
|
+
The leading 4 is the SDC4 reference model, as with every Semantic Data Charter package. An addition to what the
|
|
79
|
+
reader exposes is a minor version, a fix a patch; the major changes only when the reference model does.
|
|
80
|
+
|
|
81
|
+
## Licence
|
|
82
|
+
|
|
83
|
+
Apache-2.0 (see `LICENSE`, `NOTICE`).
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "sdcreader"
|
|
7
|
+
version = "4.0.0"
|
|
8
|
+
description = "Read a published Semantic Data Charter model's package for projection into other standards (CDIF, DCAT-US, DCAT-AP, HealthDCAT-AP)."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = { text = "Apache-2.0" }
|
|
12
|
+
authors = [{ name = "Axius SDC, Inc." }]
|
|
13
|
+
keywords = ["sdc", "semantic data charter", "governed data record", "cdif", "dcat", "dcat-ap", "healthdcat-ap", "fair"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 4 - Beta",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"License :: OSI Approved :: Apache Software License",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Topic :: Scientific/Engineering :: Information Analysis",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
dependencies = [
|
|
23
|
+
# the schema is read for the enumeration definitions and codes and the model's Dublin Core header
|
|
24
|
+
"lxml>=5.0",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
[project.optional-dependencies]
|
|
28
|
+
# Fetching a package from SDCStudio's public catalog needs HTTP; a package already on disk does not.
|
|
29
|
+
fetch = ["requests>=2.31"]
|
|
30
|
+
dev = ["pytest>=8.0", "requests>=2.31"]
|
|
31
|
+
|
|
32
|
+
[project.urls]
|
|
33
|
+
Homepage = "https://github.com/SemanticDataCharter/sdcreader"
|
|
34
|
+
Changelog = "https://github.com/SemanticDataCharter/sdcreader/blob/main/CHANGELOG.md"
|
|
35
|
+
|
|
36
|
+
[tool.setuptools.packages.find]
|
|
37
|
+
where = ["src"]
|
|
38
|
+
|
|
39
|
+
[tool.pytest.ini_options]
|
|
40
|
+
markers = ["network: reaches SDCStudio's public catalog over the network; CI skips it"]
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""sdcreader: read a published Semantic Data Charter model's package for projection into other standards.
|
|
2
|
+
|
|
3
|
+
A projection (CDIF, DCAT-US, DCAT-AP, HealthDCAT-AP, ...) describes a model's governed data records in another
|
|
4
|
+
standard's terms. What it describes is the model's package: the JSON-LD with the components and their semantic
|
|
5
|
+
links, the immutable schema the records are validated against, the public catalog record, the published schema
|
|
6
|
+
versions. This package loads or fetches that evidence and reads it into one shape every projection shares: the
|
|
7
|
+
record tree, its leaves in document order, the enumerated values with the codes the schema annotates them with,
|
|
8
|
+
and the model's own Dublin Core with SDCStudio's field defaults read as unset. It knows nothing about any
|
|
9
|
+
projection.
|
|
10
|
+
"""
|
|
11
|
+
from .model import (CLOSE, DC_DEFAULTS, EXACT, HAS_UNIT, IDENTIFIER, LEAF_TYPES, NUMERIC_TYPES, PUBLISHER, QUANTIFIED_TYPES, SEE_ALSO,
|
|
12
|
+
SOURCE, Code, Component, Leaf, Model, enumeration_iri, read_header, read_model)
|
|
13
|
+
from .package import DEFAULT_HOST, ModelPackage, PackageError, fetch_package, load_package
|
|
14
|
+
|
|
15
|
+
__version__ = "4.0.0"
|
|
16
|
+
__all__ = ["ModelPackage", "PackageError", "DEFAULT_HOST", "load_package", "fetch_package", "read_model", "read_header", "enumeration_iri",
|
|
17
|
+
"Model", "Component", "Leaf", "Code", "LEAF_TYPES", "NUMERIC_TYPES", "QUANTIFIED_TYPES", "DC_DEFAULTS", "IDENTIFIER", "SOURCE",
|
|
18
|
+
"PUBLISHER", "EXACT", "CLOSE", "SEE_ALSO", "HAS_UNIT", "__version__"]
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
"""Read a model package into the shape the CDIF emitter needs: the record tree, its leaves in document order with
|
|
2
|
+
their path, the enumerations with the definitions and codes the schema carries, the units each quantity takes.
|
|
3
|
+
|
|
4
|
+
The JSON-LD package carries every component once, with `contains` references; a component composed in several
|
|
5
|
+
places (three blood pressure readings sharing one Blood Pressure cluster) is one component with several positions.
|
|
6
|
+
The schema carries what the JSON-LD does not: the definition and the code behind each enumerated value.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from urllib.parse import unquote
|
|
13
|
+
|
|
14
|
+
from lxml import etree
|
|
15
|
+
|
|
16
|
+
from .package import ModelPackage
|
|
17
|
+
|
|
18
|
+
XSD_NS = "http://www.w3.org/2001/XMLSchema"
|
|
19
|
+
DC_NS = "http://purl.org/dc/elements/1.1/"
|
|
20
|
+
RDFS_NS = "http://www.w3.org/2000/01/rdf-schema#"
|
|
21
|
+
RDF_NS = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
|
22
|
+
SDC4 = "https://semanticdatacharter.com/ns/sdc4/"
|
|
23
|
+
NS = {"xsd": XSD_NS, "rdfs": RDFS_NS, "rdf": RDF_NS}
|
|
24
|
+
|
|
25
|
+
LEAF_TYPES = {"XdString", "XdToken", "XdBoolean", "XdLink", "XdFile", "XdOrdinal", "XdCount", "XdQuantity", "XdFloat", "XdDouble",
|
|
26
|
+
"XdTemporal", "XdInterval", "XdStringList", "XdTokenList", "XdDecimalList", "XdIntegerList"}
|
|
27
|
+
NUMERIC_TYPES = {"XdCount", "XdQuantity", "XdFloat", "XdDouble", "XdOrdinal"}
|
|
28
|
+
QUANTIFIED_TYPES = {"XdCount", "XdQuantity", "XdFloat", "XdDouble"}
|
|
29
|
+
|
|
30
|
+
IDENTIFIER = "http://purl.org/dc/terms/identifier"
|
|
31
|
+
SOURCE = "http://purl.org/dc/terms/source"
|
|
32
|
+
PUBLISHER = "http://purl.org/dc/terms/publisher"
|
|
33
|
+
EXACT = "http://www.w3.org/2004/02/skos/core#exactMatch"
|
|
34
|
+
CLOSE = "http://www.w3.org/2004/02/skos/core#closeMatch"
|
|
35
|
+
SEE_ALSO = "http://www.w3.org/2000/01/rdf-schema#seeAlso"
|
|
36
|
+
HAS_UNIT = "https://semanticdatacharter.com/ontology/sdc4-meta/hasUnit"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class Code:
|
|
41
|
+
value: str
|
|
42
|
+
iri: str
|
|
43
|
+
definition: str = ""
|
|
44
|
+
defined_by: str = ""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass
|
|
48
|
+
class Component:
|
|
49
|
+
ct_id: str
|
|
50
|
+
sdc_type: str
|
|
51
|
+
label: str
|
|
52
|
+
description: str
|
|
53
|
+
data_type: str
|
|
54
|
+
constraints: dict
|
|
55
|
+
links: dict[str, list[str]]
|
|
56
|
+
contains: list[str] = field(default_factory=list)
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def iri(self) -> str:
|
|
60
|
+
return f"{SDC4}mc-{self.ct_id}"
|
|
61
|
+
|
|
62
|
+
def link(self, predicate: str) -> str | None:
|
|
63
|
+
v = self.links.get(predicate)
|
|
64
|
+
return v[0] if v else None
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass
|
|
68
|
+
class Leaf:
|
|
69
|
+
component: Component
|
|
70
|
+
path: list[Component] # the clusters above it, root first
|
|
71
|
+
position: int # document order, 0-based
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def slug(self) -> str:
|
|
75
|
+
return "/".join(_slug(c.label) for c in self.path[1:] + [self.component])
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
#: SDCStudio's field defaults, present in every schema header whether or not the modeler wrote anything; treated as
|
|
79
|
+
#: unset so a writer never publishes "Universal" as a geographic coverage or "None" as a relation.
|
|
80
|
+
DC_DEFAULTS = {"coverage": {"Universal"}, "relation": {"None"}, "type": {"SDC Data Model (DM)"}}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass
|
|
84
|
+
class Model:
|
|
85
|
+
package: ModelPackage
|
|
86
|
+
title: str
|
|
87
|
+
description: str
|
|
88
|
+
metadata: dict # the JSON-LD package's metadata (dc:title, dc:creator, dc:rights, dc:date, ...)
|
|
89
|
+
header: dict # the schema header's Dublin Core, complete: dc:subject, dc:coverage, dc:publisher, dc:contributor, ...
|
|
90
|
+
|
|
91
|
+
def dc(self, name: str) -> str | None:
|
|
92
|
+
"""A Dublin Core value the modeler wrote: the schema header first, the JSON-LD second, defaults and blanks as None."""
|
|
93
|
+
v = self.header.get(name)
|
|
94
|
+
if v is None:
|
|
95
|
+
v = self.metadata.get(f"dc:{name}")
|
|
96
|
+
if isinstance(v, list):
|
|
97
|
+
v = v[0] if v else None
|
|
98
|
+
v = (v or "").strip() if isinstance(v, str) else v
|
|
99
|
+
if not v or v in DC_DEFAULTS.get(name, set()):
|
|
100
|
+
return None
|
|
101
|
+
return v
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def contributors(self) -> list[str]:
|
|
105
|
+
v = self.header.get("contributor")
|
|
106
|
+
if v is None:
|
|
107
|
+
v = self.metadata.get("dc:contributor") or []
|
|
108
|
+
return [c.strip() for c in (v if isinstance(v, list) else [v]) if c and c.strip()]
|
|
109
|
+
|
|
110
|
+
@property
|
|
111
|
+
def subjects(self) -> list[str]:
|
|
112
|
+
"""dc:subject as SDCStudio asks for it: a semicolon-separated list of keywords."""
|
|
113
|
+
v = self.dc("subject") or ""
|
|
114
|
+
return [w.strip() for w in v.split(";") if w.strip()]
|
|
115
|
+
|
|
116
|
+
@property
|
|
117
|
+
def rights_url(self) -> str:
|
|
118
|
+
m = re.search(r"https?://\S+", self.dc("rights") or "")
|
|
119
|
+
return m.group(0).rstrip(".,;") if m else ""
|
|
120
|
+
|
|
121
|
+
@property
|
|
122
|
+
def rights_statement(self) -> str:
|
|
123
|
+
"""The rights text with its URL removed; empty when nothing but a label is left."""
|
|
124
|
+
text = re.sub(r"https?://\S+", "", self.dc("rights") or "").strip(" ,;:")
|
|
125
|
+
return text if len(text) > 12 else ""
|
|
126
|
+
root: Component
|
|
127
|
+
components: dict[str, Component]
|
|
128
|
+
leaves: list[Leaf]
|
|
129
|
+
codes: dict[str, list[Code]] # component ct_id -> enumerated values with their definitions and codes
|
|
130
|
+
|
|
131
|
+
@property
|
|
132
|
+
def ct_id(self) -> str:
|
|
133
|
+
return self.package.ct_id
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def read_model(pkg: ModelPackage) -> Model:
|
|
137
|
+
d = pkg.jsonld
|
|
138
|
+
comps: dict[str, Component] = {}
|
|
139
|
+
for n in d["components"]:
|
|
140
|
+
ct = n["@id"].split("mc-", 1)[1]
|
|
141
|
+
links: dict[str, list[str]] = {}
|
|
142
|
+
for l in n.get("semanticLinks") or []:
|
|
143
|
+
links.setdefault(l["predicate"], []).append(l["object"])
|
|
144
|
+
comps[ct] = Component(ct_id=ct, sdc_type=n["@type"][:-4] if n["@type"].endswith("Type") else n["@type"], label=n["label"],
|
|
145
|
+
description=n.get("description") or "", data_type=n.get("dataType") or "", constraints=n.get("constraints") or {},
|
|
146
|
+
links=links, contains=[m["@id"].split("mc-", 1)[1] for m in n.get("contains") or []])
|
|
147
|
+
root = _root(comps)
|
|
148
|
+
leaves: list[Leaf] = []
|
|
149
|
+
|
|
150
|
+
def walk(c: Component, path: list[Component]):
|
|
151
|
+
for m in c.contains:
|
|
152
|
+
child = comps[m]
|
|
153
|
+
if child.sdc_type == "Cluster":
|
|
154
|
+
walk(child, path + [child])
|
|
155
|
+
elif child.sdc_type in LEAF_TYPES:
|
|
156
|
+
leaves.append(Leaf(component=child, path=path + [c] if c is not path[-1] else path, position=len(leaves)))
|
|
157
|
+
|
|
158
|
+
walk(root, [root])
|
|
159
|
+
return Model(package=pkg, title=d.get("label") or d["metadata"].get("dc:title", ""), description=d.get("description") or "",
|
|
160
|
+
metadata=d.get("metadata") or {}, header=read_header(pkg.xsd_bytes), root=root, components=comps, leaves=leaves,
|
|
161
|
+
codes=_codes(pkg.xsd_bytes))
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def read_header(xsd_bytes: bytes) -> dict:
|
|
165
|
+
"""The Dublin Core the schema header carries for the model (the first rdf:Description with dc: children): every
|
|
166
|
+
field the modeler could fill, blanks included, contributors as a list."""
|
|
167
|
+
tree = etree.fromstring(xsd_bytes)
|
|
168
|
+
out: dict = {}
|
|
169
|
+
for desc in tree.iter(f"{{{RDF_NS}}}Description"):
|
|
170
|
+
dc = [el for el in desc if isinstance(el.tag, str) and el.tag.startswith(f"{{{DC_NS}}}")]
|
|
171
|
+
if not dc:
|
|
172
|
+
continue
|
|
173
|
+
for el in dc:
|
|
174
|
+
name = el.tag.split("}", 1)[1]
|
|
175
|
+
text = " ".join((el.text or "").split())
|
|
176
|
+
if name == "contributor":
|
|
177
|
+
out.setdefault("contributor", []).append(text)
|
|
178
|
+
else:
|
|
179
|
+
out[name] = text
|
|
180
|
+
break
|
|
181
|
+
return out
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _root(comps: dict[str, Component]) -> Component:
|
|
185
|
+
contained = {m for c in comps.values() for m in c.contains}
|
|
186
|
+
roots = [c for c in comps.values() if c.sdc_type == "Cluster" and c.ct_id not in contained and c.contains]
|
|
187
|
+
# the governed record is the cluster that contains the others; a party or audit detail cluster also sits uncontained
|
|
188
|
+
roots.sort(key=lambda c: -_size(c, comps))
|
|
189
|
+
if not roots:
|
|
190
|
+
raise ValueError("no root cluster in the package")
|
|
191
|
+
return roots[0]
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _size(c: Component, comps: dict[str, Component]) -> int:
|
|
195
|
+
return 1 + sum(_size(comps[m], comps) for m in c.contains)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _codes(xsd_bytes: bytes) -> dict[str, list[Code]]:
|
|
199
|
+
"""The enumerated values of every component, with the definition and the code the schema annotates them with."""
|
|
200
|
+
tree = etree.fromstring(xsd_bytes)
|
|
201
|
+
out: dict[str, list[Code]] = {}
|
|
202
|
+
for ct in tree.iterfind(f"{{{XSD_NS}}}complexType"):
|
|
203
|
+
name = ct.get("name") or ""
|
|
204
|
+
if not name.startswith("mc-"):
|
|
205
|
+
continue
|
|
206
|
+
codes: list[Code] = []
|
|
207
|
+
for enum in ct.iterfind(f".//{{{XSD_NS}}}enumeration"):
|
|
208
|
+
value = enum.get("value")
|
|
209
|
+
doc = enum.find(f"{{{XSD_NS}}}annotation/{{{XSD_NS}}}documentation")
|
|
210
|
+
cls = enum.find(f"{{{XSD_NS}}}annotation/{{{XSD_NS}}}appinfo/{{{RDFS_NS}}}Class")
|
|
211
|
+
iri = cls.get(f"{{{RDF_NS}}}about") if cls is not None else ""
|
|
212
|
+
defined_by = ""
|
|
213
|
+
if cls is not None:
|
|
214
|
+
db = cls.find(f"{{{RDFS_NS}}}isDefinedBy")
|
|
215
|
+
if db is not None:
|
|
216
|
+
defined_by = (db.get(f"{{{RDF_NS}}}resource") or (db.text or "")).strip()
|
|
217
|
+
codes.append(Code(value=value, iri=iri or "", definition=" ".join((doc.text or "").split()) if doc is not None else "", defined_by=defined_by))
|
|
218
|
+
if codes:
|
|
219
|
+
out[name[3:]] = codes
|
|
220
|
+
return out
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _slug(label: str) -> str:
|
|
224
|
+
s = re.sub(r"[^a-z0-9]+", "-", label.lower()).strip("-")
|
|
225
|
+
return s or "x"
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def enumeration_iri(component: Component, codes: list[Code]) -> str:
|
|
229
|
+
"""The IRI of a component's value set: the parent of the per-value class IRIs the schema declares."""
|
|
230
|
+
for c in codes:
|
|
231
|
+
if c.iri:
|
|
232
|
+
return c.iri.rsplit("/", 1)[0]
|
|
233
|
+
return f"{component.iri}/{component.sdc_type.lower()}-value"
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""A published model's package: the files the writer reads, from a directory or from SDCStudio's public catalog.
|
|
2
|
+
|
|
3
|
+
A package directory holds `dm-<ct>.jsonld` (the model and its components with their semantic links), `dm-<ct>.xsd`
|
|
4
|
+
(the schema, read for the enumeration definitions and hashed for the citation), and optionally `catalog.json` (the
|
|
5
|
+
public catalog record) and `versions.json` (the published schema versions). The writer refuses a model without a
|
|
6
|
+
package: the JSON-LD and the schema are the evidence it describes.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
DEFAULT_HOST = "https://sdcstudio.axius-sdc.com"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class PackageError(Exception):
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class ModelPackage:
|
|
24
|
+
ct_id: str
|
|
25
|
+
jsonld: dict
|
|
26
|
+
xsd_bytes: bytes
|
|
27
|
+
catalog: dict = field(default_factory=dict)
|
|
28
|
+
versions: dict = field(default_factory=dict)
|
|
29
|
+
host: str = DEFAULT_HOST
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def sha256(self) -> str:
|
|
33
|
+
return hashlib.sha256(self.xsd_bytes).hexdigest()
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def schema_url(self) -> str:
|
|
37
|
+
return f"{self.host}/dmlib/dm-{self.ct_id}.xsd"
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def schema_url_pinned(self) -> str:
|
|
41
|
+
return f"{self.schema_url}?sha256={self.sha256}"
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def catalog_url(self) -> str:
|
|
45
|
+
return f"{self.host}/api/v1/catalog/dm/{self.ct_id}/"
|
|
46
|
+
|
|
47
|
+
def check(self) -> None:
|
|
48
|
+
if self.jsonld.get("identifier") != self.ct_id:
|
|
49
|
+
raise PackageError(f"package JSON-LD identifier {self.jsonld.get('identifier')!r} is not {self.ct_id!r}")
|
|
50
|
+
if not self.jsonld.get("components"):
|
|
51
|
+
raise PackageError("package JSON-LD has no components")
|
|
52
|
+
if b"<xsd:schema" not in self.xsd_bytes[:4000] and b"<xs:schema" not in self.xsd_bytes[:4000]:
|
|
53
|
+
raise PackageError("package schema is not an XML Schema")
|
|
54
|
+
current = self.versions.get("current_sha256")
|
|
55
|
+
if current and current != self.sha256:
|
|
56
|
+
raise PackageError(f"schema on disk ({self.sha256[:12]}) is not the published current version ({current[:12]})")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def load_package(directory: str | Path, ct_id: str | None = None, host: str = DEFAULT_HOST) -> ModelPackage:
|
|
60
|
+
d = Path(directory)
|
|
61
|
+
if ct_id is None:
|
|
62
|
+
xsds = sorted(d.glob("dm-*.xsd"))
|
|
63
|
+
if len(xsds) != 1:
|
|
64
|
+
raise PackageError(f"{d}: expected one dm-<ct>.xsd, found {len(xsds)}")
|
|
65
|
+
ct_id = xsds[0].stem[3:]
|
|
66
|
+
jsonld_path, xsd_path = d / f"dm-{ct_id}.jsonld", d / f"dm-{ct_id}.xsd"
|
|
67
|
+
for p in (jsonld_path, xsd_path):
|
|
68
|
+
if not p.exists():
|
|
69
|
+
raise PackageError(f"{p} is missing: the writer needs the model's package, not just its identifier")
|
|
70
|
+
pkg = ModelPackage(ct_id=ct_id, jsonld=json.loads(jsonld_path.read_text(encoding="utf-8")), xsd_bytes=xsd_path.read_bytes(),
|
|
71
|
+
catalog=_optional_json(d / "catalog.json"), versions=_optional_json(d / "versions.json"), host=host)
|
|
72
|
+
pkg.check()
|
|
73
|
+
return pkg
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def fetch_package(ct_id: str, save_to: str | Path | None = None, host: str = DEFAULT_HOST, timeout: int = 60) -> ModelPackage:
|
|
77
|
+
"""Fetch a published model's package from the public catalog (no account needed) and optionally save it."""
|
|
78
|
+
import requests # optional dependency
|
|
79
|
+
|
|
80
|
+
def get(url, **kw):
|
|
81
|
+
r = requests.get(url, timeout=timeout, **kw)
|
|
82
|
+
if r.status_code != 200:
|
|
83
|
+
raise PackageError(f"{url}: HTTP {r.status_code}")
|
|
84
|
+
return r
|
|
85
|
+
|
|
86
|
+
catalog = get(f"{host}/api/v1/catalog/dm/{ct_id}/").json()
|
|
87
|
+
jsonld = get(f"{host}/api/v1/catalog/dm/{ct_id}/jsonld/").json()
|
|
88
|
+
if isinstance(jsonld, dict) and "download_url" in jsonld and "components" not in jsonld:
|
|
89
|
+
# a storage-backed artifact: the catalog answers with a pointer to the file, not the file
|
|
90
|
+
jsonld = get(jsonld["download_url"]).json()
|
|
91
|
+
xsd = get(f"{host}/dmlib/dm-{ct_id}.xsd").content
|
|
92
|
+
versions = get(f"{host}/dmlib/dm-{ct_id}.versions.json").json()
|
|
93
|
+
pkg = ModelPackage(ct_id=ct_id, jsonld=jsonld, xsd_bytes=xsd, catalog=catalog, versions=versions, host=host)
|
|
94
|
+
pkg.check()
|
|
95
|
+
if save_to is not None:
|
|
96
|
+
d = Path(save_to)
|
|
97
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
98
|
+
(d / f"dm-{ct_id}.jsonld").write_text(json.dumps(jsonld, indent=1, ensure_ascii=False), encoding="utf-8")
|
|
99
|
+
(d / f"dm-{ct_id}.xsd").write_bytes(xsd)
|
|
100
|
+
(d / "catalog.json").write_text(json.dumps(catalog, indent=1, ensure_ascii=False), encoding="utf-8")
|
|
101
|
+
(d / "versions.json").write_text(json.dumps(versions, indent=1), encoding="utf-8")
|
|
102
|
+
return pkg
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _optional_json(path: Path) -> dict:
|
|
106
|
+
return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sdcreader
|
|
3
|
+
Version: 4.0.0
|
|
4
|
+
Summary: Read a published Semantic Data Charter model's package for projection into other standards (CDIF, DCAT-US, DCAT-AP, HealthDCAT-AP).
|
|
5
|
+
Author: Axius SDC, Inc.
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/SemanticDataCharter/sdcreader
|
|
8
|
+
Project-URL: Changelog, https://github.com/SemanticDataCharter/sdcreader/blob/main/CHANGELOG.md
|
|
9
|
+
Keywords: sdc,semantic data charter,governed data record,cdif,dcat,dcat-ap,healthdcat-ap,fair
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
License-File: NOTICE
|
|
19
|
+
Requires-Dist: lxml>=5.0
|
|
20
|
+
Provides-Extra: fetch
|
|
21
|
+
Requires-Dist: requests>=2.31; extra == "fetch"
|
|
22
|
+
Provides-Extra: dev
|
|
23
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
24
|
+
Requires-Dist: requests>=2.31; extra == "dev"
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
|
|
27
|
+
# sdcreader
|
|
28
|
+
|
|
29
|
+
Read a published Semantic Data Charter model's package for projection into other standards.
|
|
30
|
+
|
|
31
|
+
A projection describes a model's governed data records in another standard's terms: CDIF, DCAT-US 3.0, DCAT-AP
|
|
32
|
+
3.0.1, HealthDCAT-AP, and whatever comes next. What every projection describes is the same evidence, the model's
|
|
33
|
+
package, and reads it into the same shape. `sdcreader` is that evidence and that shape, once, with nothing about
|
|
34
|
+
any projection in it. The four projection writers (`sdc_cdif`, `sdc_dcat3_us`, `sdc_dcat3_ap`, `sdc_healthdcat_ap`)
|
|
35
|
+
carried it as identical copies until this package.
|
|
36
|
+
|
|
37
|
+
```
|
|
38
|
+
pip install sdcreader # or, until the PyPI release: pip install "sdcreader @ git+https://github.com/SemanticDataCharter/sdcreader@v4.0.0"
|
|
39
|
+
pip install "sdcreader[fetch]" # with HTTP, to fetch a package from the public catalog
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
from sdcreader import fetch_package, load_package, read_model
|
|
44
|
+
|
|
45
|
+
pkg = load_package("samples/nhanes-participant") # a package on disk
|
|
46
|
+
pkg = fetch_package("xy8upneajsb8vdcmnve01g6g", save_to="pkg/") # or from SDCStudio's public catalog, no account
|
|
47
|
+
model = read_model(pkg)
|
|
48
|
+
|
|
49
|
+
pkg.schema_url_pinned # https://sdcstudio.axius-sdc.com/dmlib/dm-xy8u...xsd?sha256=0df4... the exact bytes the records are validated against
|
|
50
|
+
model.title, model.leaves # 'NHANES Participant', 153 leaves in document order, each with its path of clusters
|
|
51
|
+
model.codes[ct_id] # the enumerated values of a component with the IRI, definition and code the schema annotates them with
|
|
52
|
+
model.dc("publisher") # what the modeler wrote, None where SDCStudio's default sits
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## What a package is
|
|
56
|
+
|
|
57
|
+
SDCStudio generates a package for every published model and serves it publicly for models in public projects:
|
|
58
|
+
|
|
59
|
+
| | |
|
|
60
|
+
|---|---|
|
|
61
|
+
| `GET /api/v1/catalog/dm/<ct>/` | the catalog record: title, description, project, the artifact list (`catalog.json`) |
|
|
62
|
+
| `GET /api/v1/catalog/dm/<ct>/<artifact>/` | a storage pointer, `{"download_url": ..., "filename": ..., "storage": "gcs"}`, for `jsonld`, `xsd` and the rest; the reader follows it |
|
|
63
|
+
| `dm-<ct>.jsonld` | the model and its components: type, label, description, cardinality, constraints (enumerations, units, ranges, patterns), semantic links (`dcterms:identifier` the library slot, `dcterms:source`, `dcterms:publisher`, `skos:exactMatch`, `rdfs:seeAlso`, `prov:wasRevisionOf`), `contains` |
|
|
64
|
+
| `GET /dmlib/dm-<ct>.xsd` | the schema bytes: the Dublin Core header for the model, and for each enumerated value its definition and the code it is defined by (`dm-<ct>.xsd`) |
|
|
65
|
+
| `GET /dmlib/dm-<ct>.versions.json` | every published version of the schema by SHA-256, with the current one (`versions.json`) |
|
|
66
|
+
|
|
67
|
+
A package directory holds those four files. The reader refuses a directory without the JSON-LD and the schema, a
|
|
68
|
+
JSON-LD whose identifier is not the directory's model, and a schema whose bytes are not the published current
|
|
69
|
+
version: a projection cites the schema by URL and SHA-256, so the bytes have to be the ones that URL serves.
|
|
70
|
+
|
|
71
|
+
Two gaps in the package are on SDCStudio's issue tracker: the JSON-LD metadata drops fields the schema header
|
|
72
|
+
carries (#748), and the header omits `dc:source` (#749). The reader takes the model's Dublin Core from the header,
|
|
73
|
+
which is complete.
|
|
74
|
+
|
|
75
|
+
## What the reader gives
|
|
76
|
+
|
|
77
|
+
- **`ModelPackage`**: the four files, the SHA-256, the schema URL and its pinned form (`?sha256=`), the public
|
|
78
|
+
catalog URL, and `check()`.
|
|
79
|
+
- **`Model`**: `title`, `description`, `root` (the governed record's cluster), `components` by identifier, `leaves`
|
|
80
|
+
in document order (each a `Leaf` with its `component`, its `path` of clusters and a `slug` of that path, unique in
|
|
81
|
+
the record), `codes` (the enumerated values per component as `Code`: value, IRI, definition, the code it is
|
|
82
|
+
defined by), `metadata` (the JSON-LD's) and `header` (the schema's Dublin Core).
|
|
83
|
+
- **`Model.dc(name)`**: what the modeler wrote, the header first and the JSON-LD second, with SDCStudio's field
|
|
84
|
+
defaults as unset: "Universal" for coverage, "None" for relation, "SDC Data Model (DM)" for type, blanks. A
|
|
85
|
+
projection never publishes a default as a fact. `contributors`, `subjects` (the semicolon list), `rights_url` and
|
|
86
|
+
`rights_statement` derive from it.
|
|
87
|
+
- **`Component`**: `sdc_type`, `label`, `description`, `data_type`, `constraints`, `links` by predicate (`link(p)` for
|
|
88
|
+
the first), `contains`, `iri`.
|
|
89
|
+
- Constants: the leaf, numeric and quantified types; the predicate IRIs `IDENTIFIER`, `SOURCE`, `PUBLISHER`, `EXACT`,
|
|
90
|
+
`CLOSE`, `SEE_ALSO`, `HAS_UNIT`; `DC_DEFAULTS`.
|
|
91
|
+
|
|
92
|
+
## Tests
|
|
93
|
+
|
|
94
|
+
```
|
|
95
|
+
pip install -e ".[dev]"
|
|
96
|
+
python -m pytest tests -q # includes one fetch against production
|
|
97
|
+
python -m pytest tests -q -m "not network" # offline, as CI runs it
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
The fixture is the NHANES Participant package of the FAIR Data Demo, the record every projection is proven on.
|
|
101
|
+
|
|
102
|
+
## Versioning
|
|
103
|
+
|
|
104
|
+
The leading 4 is the SDC4 reference model, as with every Semantic Data Charter package. An addition to what the
|
|
105
|
+
reader exposes is a minor version, a fix a patch; the major changes only when the reference model does.
|
|
106
|
+
|
|
107
|
+
## Licence
|
|
108
|
+
|
|
109
|
+
Apache-2.0 (see `LICENSE`, `NOTICE`).
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
NOTICE
|
|
3
|
+
README.md
|
|
4
|
+
pyproject.toml
|
|
5
|
+
src/sdcreader/__init__.py
|
|
6
|
+
src/sdcreader/model.py
|
|
7
|
+
src/sdcreader/package.py
|
|
8
|
+
src/sdcreader.egg-info/PKG-INFO
|
|
9
|
+
src/sdcreader.egg-info/SOURCES.txt
|
|
10
|
+
src/sdcreader.egg-info/dependency_links.txt
|
|
11
|
+
src/sdcreader.egg-info/requires.txt
|
|
12
|
+
src/sdcreader.egg-info/top_level.txt
|
|
13
|
+
tests/test_reader.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
sdcreader
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""The reader on the NHANES Participant package: it loads and refuses as documented, proves the schema bytes are the
|
|
2
|
+
published current version, reads the record tree and its leaves in document order, the enumerated values with their
|
|
3
|
+
codes, the model's Dublin Core with SDCStudio's defaults as unset, and fetches a package from the public catalog
|
|
4
|
+
following the storage pointer (through a fake transport offline; against production behind the network marker)."""
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import pytest
|
|
10
|
+
|
|
11
|
+
import sdcreader
|
|
12
|
+
from sdcreader import Code, Leaf, Model, PackageError, enumeration_iri, fetch_package, load_package, read_header, read_model
|
|
13
|
+
|
|
14
|
+
ROOT = Path(__file__).resolve().parents[1]
|
|
15
|
+
PACKAGE = ROOT / "samples" / "nhanes-participant"
|
|
16
|
+
CT = "xy8upneajsb8vdcmnve01g6g"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@pytest.fixture(scope="module")
|
|
20
|
+
def pkg():
|
|
21
|
+
return load_package(PACKAGE)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@pytest.fixture(scope="module")
|
|
25
|
+
def model(pkg):
|
|
26
|
+
return read_model(pkg)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def test_the_version_carries_the_reference_model():
|
|
30
|
+
assert sdcreader.__version__.startswith("4.")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def test_a_package_loads_and_proves_its_schema_is_the_published_current_version(pkg):
|
|
34
|
+
assert pkg.ct_id == CT
|
|
35
|
+
sha = hashlib.sha256((PACKAGE / f"dm-{CT}.xsd").read_bytes()).hexdigest()
|
|
36
|
+
assert pkg.sha256 == sha == pkg.versions["current_sha256"]
|
|
37
|
+
assert pkg.schema_url == f"https://sdcstudio.axius-sdc.com/dmlib/dm-{CT}.xsd"
|
|
38
|
+
assert pkg.schema_url_pinned == f"{pkg.schema_url}?sha256={sha}"
|
|
39
|
+
assert pkg.catalog_url == f"https://sdcstudio.axius-sdc.com/api/v1/catalog/dm/{CT}/"
|
|
40
|
+
assert pkg.catalog["project_name"] == "FAIR Data Demo"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def test_the_reader_refuses_what_is_not_a_package(tmp_path):
|
|
44
|
+
(tmp_path / f"dm-{CT}.xsd").write_bytes(b"<xsd:schema/>")
|
|
45
|
+
with pytest.raises(PackageError, match="missing"):
|
|
46
|
+
load_package(tmp_path)
|
|
47
|
+
(tmp_path / f"dm-{CT}.jsonld").write_text(json.dumps({"identifier": "other", "components": [{}]}))
|
|
48
|
+
with pytest.raises(PackageError, match="identifier"):
|
|
49
|
+
load_package(tmp_path)
|
|
50
|
+
(tmp_path / f"dm-{CT}.jsonld").write_text(json.dumps({"identifier": CT, "components": [{}]}))
|
|
51
|
+
(tmp_path / "versions.json").write_text(json.dumps({"current_sha256": "0" * 64}))
|
|
52
|
+
with pytest.raises(PackageError, match="not the published current version"):
|
|
53
|
+
load_package(tmp_path)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def test_the_record_tree_its_leaves_and_their_codes(model: Model):
|
|
57
|
+
assert model.title == "NHANES Participant" and model.root.label == "NHANES Participant Governed Record"
|
|
58
|
+
assert len(model.leaves) == 153
|
|
59
|
+
first, last = model.leaves[0], model.leaves[-1]
|
|
60
|
+
assert isinstance(first, Leaf) and first.position == 0 and last.position == 152
|
|
61
|
+
assert first.slug.startswith("audit-event/") and all(l.component.sdc_type in sdcreader.LEAF_TYPES for l in model.leaves)
|
|
62
|
+
slugs = [l.slug for l in model.leaves]
|
|
63
|
+
assert len(set(slugs)) == len(slugs) # the path names each leaf once
|
|
64
|
+
assert len({l.component.ct_id for l in model.leaves}) < len(slugs) # a component composed three times (the blood pressure readings) is three leaves
|
|
65
|
+
enumerated = {k: v for k, v in model.codes.items() if k in model.components}
|
|
66
|
+
assert len(enumerated) >= 60
|
|
67
|
+
marital = next(l.component for l in model.leaves if l.component.label == "Marital Status (DMDMARTL)")
|
|
68
|
+
codes = model.codes[marital.ct_id]
|
|
69
|
+
assert [c.value for c in codes][:2] == ["Married", "Widowed"]
|
|
70
|
+
assert all(isinstance(c, Code) and c.iri.startswith(marital.iri) for c in codes)
|
|
71
|
+
assert codes[0].defined_by == "http://purl.obolibrary.org/obo/NCIT_C51773"
|
|
72
|
+
assert enumeration_iri(marital, codes) == f"{marital.iri}/xdtoken-value"
|
|
73
|
+
sbp = next(l.component for l in model.leaves if l.component.label == "Systolic Blood Pressure")
|
|
74
|
+
assert sbp.sdc_type == "XdQuantity" and sbp.data_type == "xsd:decimal" and sbp.link(sdcreader.IDENTIFIER).startswith("https://axius-sdc.com/library/")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def test_the_models_dublin_core_comes_from_the_schema_header_with_defaults_as_unset(model: Model, pkg):
|
|
78
|
+
header = read_header(pkg.xsd_bytes)
|
|
79
|
+
assert header["coverage"] == "Universal" and header["relation"] == "None" and header["publisher"] == ""
|
|
80
|
+
assert model.dc("coverage") is None and model.dc("relation") is None and model.dc("publisher") is None and model.dc("type") is None
|
|
81
|
+
assert model.dc("creator") == "Timothy Cook" and model.dc("date", ).startswith("2026-09-26")
|
|
82
|
+
assert model.subjects == [] and model.contributors == []
|
|
83
|
+
assert model.rights_url == "http://creativecommons.org/licenses/by/3.0/" and model.rights_statement == ""
|
|
84
|
+
authored = Model(**{**model.__dict__, "header": dict(header, subject="a; b;; c", contributor=["X"],
|
|
85
|
+
rights="Public domain in the United States https://creativecommons.org/publicdomain/zero/1.0/ except where noted")})
|
|
86
|
+
assert authored.subjects == ["a", "b", "c"] and authored.contributors == ["X"]
|
|
87
|
+
assert authored.rights_url == "https://creativecommons.org/publicdomain/zero/1.0/" and authored.rights_statement.startswith("Public domain")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def test_fetch_follows_the_catalogs_storage_pointer(monkeypatch, tmp_path):
|
|
91
|
+
"""The artifact endpoint answers with {download_url, filename, storage} for a storage-backed file, not the file."""
|
|
92
|
+
import requests
|
|
93
|
+
files = {
|
|
94
|
+
f"https://sdcstudio.axius-sdc.com/api/v1/catalog/dm/{CT}/": (PACKAGE / "catalog.json").read_bytes(),
|
|
95
|
+
f"https://sdcstudio.axius-sdc.com/api/v1/catalog/dm/{CT}/jsonld/": json.dumps({"download_url": "https://storage.example/dm.jsonld", "filename": "x", "storage": "gcs"}).encode(),
|
|
96
|
+
"https://storage.example/dm.jsonld": (PACKAGE / f"dm-{CT}.jsonld").read_bytes(),
|
|
97
|
+
f"https://sdcstudio.axius-sdc.com/dmlib/dm-{CT}.xsd": (PACKAGE / f"dm-{CT}.xsd").read_bytes(),
|
|
98
|
+
f"https://sdcstudio.axius-sdc.com/dmlib/dm-{CT}.versions.json": (PACKAGE / "versions.json").read_bytes(),
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
class R:
|
|
102
|
+
def __init__(self, content):
|
|
103
|
+
self.status_code, self.content = 200, content
|
|
104
|
+
|
|
105
|
+
def json(self):
|
|
106
|
+
return json.loads(self.content)
|
|
107
|
+
|
|
108
|
+
monkeypatch.setattr(requests, "get", lambda url, **kw: R(files[url]))
|
|
109
|
+
pkg = fetch_package(CT, save_to=tmp_path)
|
|
110
|
+
assert pkg.sha256 == load_package(PACKAGE).sha256 and pkg.jsonld["identifier"] == CT
|
|
111
|
+
assert sorted(p.name for p in tmp_path.iterdir()) == ["catalog.json", f"dm-{CT}.jsonld", f"dm-{CT}.xsd", "versions.json"]
|
|
112
|
+
assert load_package(tmp_path).sha256 == pkg.sha256
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
@pytest.mark.network
|
|
116
|
+
def test_fetch_from_production_matches_the_fixture():
|
|
117
|
+
pkg = fetch_package(CT)
|
|
118
|
+
assert pkg.sha256 == load_package(PACKAGE).sha256
|