stepup-data 4.3.0a0__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.
@@ -0,0 +1,12 @@
1
+ # SPDX-FileCopyrightText: 2024 Toon Verstraelen <Toon.Verstraelen@UGent.be>
2
+ # SPDX-License-Identifier: LGPL-3.0-or-later
3
+ """StepUp extension for data exchange and archiving."""
4
+
5
+ from stepup.core.platform.stdio import write_utf8_unless_terminal
6
+
7
+ __all__ = ()
8
+
9
+ # Importing any module of this package makes the standard output and error
10
+ # write UTF-8 with `\n` line endings, unless they are a terminal,
11
+ # because StepUp decodes the output of every step as UTF-8.
12
+ write_utf8_unless_terminal()
stepup/data/api.py ADDED
@@ -0,0 +1,244 @@
1
+ # SPDX-FileCopyrightText: 2024 Toon Verstraelen <Toon.Verstraelen@UGent.be>
2
+ # SPDX-License-Identifier: LGPL-3.0-or-later
3
+ """Application programming interface for StepUp Data."""
4
+
5
+ from collections.abc import Collection
6
+
7
+ from stepup.core.api import run, shq
8
+ from stepup.core.nglob import has_any_wildcards
9
+ from stepup.core.path import StrPath, coerce_paths, coerce_str, make_path_out
10
+ from stepup.core.stepinfo import StepInfo
11
+
12
+ from .make_inventory import NO_HASH
13
+
14
+ __all__ = ("make_inventory", "sync_zenodo", "zip_inventory")
15
+
16
+
17
+ def make_inventory(
18
+ dest: StrPath,
19
+ *,
20
+ paths: StrPath | Collection[StrPath] = (),
21
+ include: str | Collection[str] = (),
22
+ include_info_inp: StrPath | Collection[StrPath] = (),
23
+ include_info_out: StrPath | Collection[StrPath] = (),
24
+ exclude: str | Collection[str] = (),
25
+ hash_algorithm: str | None = "md5",
26
+ mode: bool = False,
27
+ optional: bool = False,
28
+ resources: dict[str, int] | str | None = None,
29
+ duration: float | None = None,
30
+ ) -> StepInfo:
31
+ """Create an inventory file, in JSON Lines format with suffix `.jsonl`.
32
+
33
+ The format and the selection of the files are explained in the documentation of StepUp Data,
34
+ under "Inventory Files".
35
+ All paths and patterns are relative to the working directory of the step.
36
+
37
+ Parameters
38
+ ----------
39
+ dest
40
+ The inventory file to write, with suffix `.jsonl`.
41
+ paths
42
+ Files to include in the inventory, in the given order.
43
+ They are never interpreted as patterns.
44
+ include
45
+ Patterns of files to include, which must match static files.
46
+ An entry without wildcards is a literal path,
47
+ which may also be the output of another step.
48
+ The included files come after `paths`, sorted.
49
+ A pattern that matches no files is an error.
50
+ include_info_inp, include_info_out
51
+ Step info files, whose `inp` or `out` paths, respectively, are included,
52
+ e.g. written by `script(step_info=...)` or `dump_step_info()` in StepUp Core.
53
+ The step info files are inputs of the step, and may be built by other steps.
54
+ The included files come after `paths`, sorted together with those of `include`.
55
+ exclude
56
+ Patterns or literal paths of files to leave out,
57
+ matched against the names of the files selected by the other arguments.
58
+ hash_algorithm
59
+ The name of the `hashlib` algorithm for the digests of the files.
60
+ The default, `md5`, is the one that Zenodo reports.
61
+ Use `sha256` when deliberate tampering with the files must be detected.
62
+ With `None`, no digests are recorded and the contents of the files are not read,
63
+ which saves time for large datasets,
64
+ but then changes that keep the size of a file are not detected,
65
+ and the inventory cannot be used by `sync_zenodo()`.
66
+ mode
67
+ When True, the permission bits of the files are recorded and checked.
68
+ Files have no permission bits on Windows,
69
+ where the recorded modes depend on the read-only attribute and the file names.
70
+ optional
71
+ If `True`, the step is only executed when needed by other steps.
72
+ resources
73
+ Named resources required to run this step, e.g. `{"gpu": 1}`.
74
+ See `stepup.core.api.step()` for details.
75
+ duration
76
+ An initial estimate of the step's wall time in seconds.
77
+ See `stepup.core.api.step()` for details.
78
+
79
+ Returns
80
+ -------
81
+ step_info
82
+ Holds relevant information of the step, useful for defining follow-up steps.
83
+ """
84
+ if not coerce_str(dest).endswith(".jsonl"):
85
+ raise ValueError(f"The inventory file must have a `.jsonl` extension. Got {dest}")
86
+ paths_inp = coerce_paths(paths)
87
+ include = [include] if isinstance(include, str) else list(include)
88
+ include_info_inp = coerce_paths(include_info_inp)
89
+ include_info_out = coerce_paths(include_info_out)
90
+ exclude = [exclude] if isinstance(exclude, str) else list(exclude)
91
+ if not (paths_inp or include or include_info_inp or include_info_out):
92
+ raise ValueError("At least one path, include entry or step info file must be given.")
93
+ parts = ["sd-make-inventory"]
94
+ if len(paths_inp) > 0:
95
+ parts.append(shq(paths_inp))
96
+ parts.extend(f"--include {shq(entry)}" for entry in include)
97
+ parts.extend(f"--include-info-inp {shq(path)}" for path in include_info_inp)
98
+ parts.extend(f"--include-info-out {shq(path)}" for path in include_info_out)
99
+ parts.extend(f"--exclude {shq(entry)}" for entry in exclude)
100
+ parts.append(f"-o {shq(dest)}")
101
+ if hash_algorithm is None:
102
+ parts.append(f"--hash {NO_HASH}")
103
+ elif hash_algorithm != "md5":
104
+ parts.append(f"--hash {shq(hash_algorithm)}")
105
+ if mode:
106
+ parts.append("--mode")
107
+ # Literal includes and step info files are declared,
108
+ # so that the step waits for them when another step builds them.
109
+ paths_inp.extend(entry for entry in include if not has_any_wildcards(entry))
110
+ paths_inp.extend(include_info_inp + include_info_out)
111
+ return run(
112
+ " ".join(parts),
113
+ inp=paths_inp,
114
+ out=[dest],
115
+ optional=optional,
116
+ resources=resources,
117
+ duration=duration,
118
+ )
119
+
120
+
121
+ def zip_inventory(
122
+ path_inventory: StrPath,
123
+ dest: StrPath | None = None,
124
+ *,
125
+ optional: bool = False,
126
+ resources: dict[str, int] | str | None = None,
127
+ duration: float | None = None,
128
+ ) -> StepInfo:
129
+ """Create a ZIP file with all files listed in an inventory, after checking them.
130
+
131
+ Parameters
132
+ ----------
133
+ path_inventory
134
+ An inventory file with suffix `.jsonl`,
135
+ created with `make_inventory()` or with the command-line script `sd-make-inventory`.
136
+ The files are stored in the ZIP file under the paths of their records,
137
+ which must therefore be inside the directory of the inventory.
138
+ They are also amended as inputs of the step,
139
+ so the ZIP file is rebuilt when they change, even when the inventory does not.
140
+ The inventory itself is not added to the ZIP file.
141
+ Keep the inventory next to the ZIP file
142
+ to check the unpacked files with `sd-check-inventory`.
143
+ dest
144
+ Output destination: `None`, a directory with a trailing slash, or a file.
145
+ When `None`, the ZIP file is written next to the inventory, with suffix `.zip`.
146
+ In a directory, the ZIP file has the name of the inventory, with suffix `.zip`.
147
+ A file must have suffix `.zip`.
148
+ optional
149
+ If `True`, the step is only executed when needed by other steps.
150
+ resources
151
+ Named resources required to run this step, e.g. `{"gpu": 1}`.
152
+ See `stepup.core.api.step()` for details.
153
+ duration
154
+ An initial estimate of the step's wall time in seconds.
155
+ See `stepup.core.api.step()` for details.
156
+
157
+ Returns
158
+ -------
159
+ step_info
160
+ Holds relevant information of the step, useful for defining follow-up steps.
161
+ """
162
+ if not coerce_str(path_inventory).endswith(".jsonl"):
163
+ raise ValueError(f"The inventory file must have a `.jsonl` extension. Got {path_inventory}")
164
+ path_zip = make_path_out(path_inventory, dest, ".zip")
165
+ return run(
166
+ f"sd-zip-inventory {shq(path_inventory)} {shq(path_zip)}",
167
+ inp=path_inventory,
168
+ out=path_zip,
169
+ optional=optional,
170
+ resources=resources,
171
+ duration=duration,
172
+ )
173
+
174
+
175
+ def sync_zenodo(
176
+ path_config: StrPath,
177
+ path_description: StrPath,
178
+ path_inventory: StrPath,
179
+ *,
180
+ check_md5: bool = False,
181
+ verbose: bool = False,
182
+ resources: dict[str, int] | str | None = None,
183
+ duration: float | None = None,
184
+ ) -> StepInfo:
185
+ """Synchronize data with a draft dataset on Zenodo.
186
+
187
+ The step runs at every start of StepUp, after every change of its inputs,
188
+ and in watch mode after the `R` key or `stepup rebuild --recheck`,
189
+ as a step with `recheck=True` in StepUp Core.
190
+ It contacts Zenodo only when the `STEPUP_DATA_ZENODO_TOKEN` environment variable is set
191
+ and StepUp does not run offline.
192
+
193
+ Parameters
194
+ ----------
195
+ path_config
196
+ The configuration file for the Zenodo upload, in YAML, JSON or TOML format.
197
+ path_description
198
+ A Markdown (`.md`) or HTML (`.html`) file with the description of the dataset.
199
+ Markdown is converted to HTML before it is sent to Zenodo.
200
+ path_inventory
201
+ The inventory of the files to upload, usually written by `make_inventory()`
202
+ with the default hash algorithm, MD5.
203
+ The paths in the inventory are relative to its parent directory.
204
+ Zenodo does not support directory layouts or symbolic links,
205
+ so all files must be regular files with different names.
206
+ At most 100 files can be uploaded to a single record.
207
+ The first file is selected for preview on Zenodo.
208
+ check_md5
209
+ When True, the MD5 checksums of the local files are computed again
210
+ and compared to those in the inventory before anything is uploaded.
211
+ This suits an inventory that is not built in the same workflow.
212
+ An inventory built by `make_inventory()` is always up to date,
213
+ so the check is then redundant.
214
+ verbose
215
+ Set to True to print Zenodo API requests and responses to the standard output.
216
+ resources
217
+ Named resources required to run this step, e.g. `{"zenodo": 1}`.
218
+ See `stepup.core.api.step()` for details.
219
+ duration
220
+ An initial estimate of the step's wall time in seconds.
221
+ See `stepup.core.api.step()` for details.
222
+
223
+ Returns
224
+ -------
225
+ step_info
226
+ Holds relevant information of the step, useful for defining follow-up steps.
227
+ """
228
+ parts = [
229
+ "sd-sync-zenodo",
230
+ shq(path_config),
231
+ shq(path_description),
232
+ shq(path_inventory),
233
+ ]
234
+ if not check_md5:
235
+ parts.append("--no-check-md5")
236
+ if verbose:
237
+ parts.append("--verbose")
238
+ return run(
239
+ " ".join(parts),
240
+ inp=[path_config, path_description, path_inventory],
241
+ recheck=True,
242
+ resources=resources,
243
+ duration=duration,
244
+ )
@@ -0,0 +1,54 @@
1
+ # SPDX-FileCopyrightText: 2024 Toon Verstraelen <Toon.Verstraelen@UGent.be>
2
+ # SPDX-License-Identifier: LGPL-3.0-or-later
3
+ """Checking of inventory files."""
4
+
5
+ import argparse
6
+ import sys
7
+ from collections.abc import Sequence
8
+
9
+ from stepup.core.path import Path, StrPath
10
+
11
+ from .inventory import check_record, compute_record, open_inventory
12
+
13
+ __all__ = ("check_inventory", "main")
14
+
15
+
16
+ def main(argv: Sequence[str] | None = None):
17
+ """Main program."""
18
+ parser = argparse.ArgumentParser(
19
+ prog="sd-check-inventory", description="Check the files listed in an inventory."
20
+ )
21
+ parser.add_argument(
22
+ "inventory", help="An inventory file with suffix .jsonl, written by sd-make-inventory."
23
+ )
24
+ args = parser.parse_args(argv)
25
+ if not args.inventory.endswith(".jsonl"):
26
+ parser.error("The inventory file must end with .jsonl")
27
+ check_inventory(args.inventory)
28
+
29
+
30
+ def check_inventory(path_inventory: StrPath):
31
+ """Check that the files on disk match the records of an inventory.
32
+
33
+ Parameters
34
+ ----------
35
+ path_inventory
36
+ The inventory file.
37
+ The paths of its records are relative to its parent directory.
38
+
39
+ Raises
40
+ ------
41
+ ValueError
42
+ When the inventory cannot be read or when a file differs from its record.
43
+ """
44
+ path_inventory = Path(path_inventory)
45
+ root = path_inventory.parent
46
+ with open_inventory(path_inventory) as reader:
47
+ header = reader.header
48
+ for ref in reader:
49
+ new = compute_record(root / ref.path, root, header.hash_algorithm, header.mode)
50
+ check_record(new, ref)
51
+
52
+
53
+ if __name__ == "__main__":
54
+ sys.exit(main())
@@ -0,0 +1,19 @@
1
+ # SPDX-FileCopyrightText: 2026 Toon Verstraelen <Toon.Verstraelen@UGent.be>
2
+ # SPDX-License-Identifier: LGPL-3.0-or-later
3
+ """The `STEPUP_DATA_*` environment variables of StepUp Data.
4
+
5
+ They are registered with StepUp Core through the `stepup.env_vars` entry point,
6
+ so that `stepup config` lists them and masks the secret ones.
7
+ """
8
+
9
+ from stepup.core.env_vars import EnvVarInfo, EnvVarRegistry
10
+
11
+ __all__ = ("env_vars",)
12
+
13
+
14
+ def env_vars() -> EnvVarRegistry:
15
+ """Return the environment variables of StepUp Data."""
16
+ return EnvVarRegistry(
17
+ "StepUp Data",
18
+ {"STEPUP_DATA_ZENODO_TOKEN": EnvVarInfo(secret=True)},
19
+ )