h5json 2.0.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.
h5json/__init__.py ADDED
@@ -0,0 +1,41 @@
1
+ ##############################################################################
2
+ # Copyright by The HDF Group. #
3
+ # All rights reserved. #
4
+ # #
5
+ # This file is part of H5Serv (HDF5 REST Server) Service, Libraries and #
6
+ # Utilities. The full HDF5 REST Server copyright notice, including #
7
+ # terms governing use, modification, and redistribution, is contained in #
8
+ # the file COPYING, which can be found at the root of the source code #
9
+ # distribution tree. If you do not have access to this file, you may #
10
+ # request a copy from help@hdfgroup.org. #
11
+ ##############################################################################
12
+
13
+
14
+ """
15
+ This is the h5json package, a mapping between HDF5 objects and JSON
16
+ """
17
+
18
+ from __future__ import absolute_import
19
+
20
+ from importlib.metadata import PackageNotFoundError as _PackageNotFoundError
21
+ from importlib.metadata import version as _pkg_version
22
+
23
+ from .hdf5dtype import getTypeItem
24
+ from .hdf5dtype import getTypeResponse
25
+ from .hdf5dtype import getItemSize
26
+ from .hdf5dtype import createDataType
27
+ from .objid import createObjId
28
+ from .objid import getCollectionForId
29
+ from .objid import isObjId
30
+ from .objid import isS3ObjKey
31
+ from .objid import getS3Key
32
+ from .objid import getObjId
33
+ from .objid import isSchema2Id
34
+ from .objid import isRootObjId
35
+ from .hdf5db import Hdf5db
36
+
37
+ try:
38
+ __version__ = _pkg_version("h5json")
39
+ except _PackageNotFoundError:
40
+ # running from a source tree that has not been installed
41
+ __version__ = "0.0.0.dev0"
h5json/apiversion.py ADDED
@@ -0,0 +1,15 @@
1
+ ##############################################################################
2
+ # Copyright by The HDF Group. #
3
+ # All rights reserved. #
4
+ # #
5
+ # This file is part of H5Serv (HDF5 REST Server) Service, Libraries and #
6
+ # Utilities. The full HDF5 REST Server copyright notice, including #
7
+ # terms governing use, modification, and redistribution, is contained in #
8
+ # the file COPYING, which can be found at the root of the source code #
9
+ # distribution tree. If you do not have access to this file, you may #
10
+ # request a copy from help@hdfgroup.org. #
11
+ ##############################################################################
12
+
13
+ # IMPORTANT: HDF5/JSON apiVersion key value is set here. Update only when the
14
+ # HDF5/JSON spec changes.
15
+ _apiver = "1.1.1"
@@ -0,0 +1,11 @@
1
+ ##############################################################################
2
+ # Copyright by The HDF Group. #
3
+ # All rights reserved. #
4
+ # #
5
+ # This file is part of H5Serv (HDF5 REST Server) Service, Libraries and #
6
+ # Utilities. The full HDF5 REST Server copyright notice, including #
7
+ # terms governing use, modification, and redistribution, is contained in #
8
+ # the file COPYING, which can be found at the root of the source code #
9
+ # distribution tree. If you do not have access to this file, you may #
10
+ # request a copy from help@hdfgroup.org. #
11
+ ##############################################################################
@@ -0,0 +1,70 @@
1
+ ##############################################################################
2
+ # Copyright by The HDF Group. #
3
+ # All rights reserved. #
4
+ # #
5
+ # This file is part of H5Serv (HDF5 REST Server) Service, Libraries and #
6
+ # Utilities. The full HDF5 REST Server copyright notice, including #
7
+ # terms governing use, modification, and redistribution, is contained in #
8
+ # the file COPYING, which can be found at the root of the source code #
9
+ # distribution tree. If you do not have access to this file, you may #
10
+ # request a copy from help@hdfgroup.org. #
11
+ ##############################################################################
12
+ import sys
13
+ import os.path as op
14
+ import logging
15
+
16
+ from h5json import Hdf5db
17
+ from h5json.jsonstore.h5json_plugin import H5JsonPlugin
18
+ from h5json.h5pystore.h5py_plugin import H5pyPlugin
19
+
20
+
21
+ def main():
22
+ if len(sys.argv) < 2 or sys.argv[1] in ("-h", "--help"):
23
+ print(f"usage: {sys.argv[0]} [-h] [--nodata] [--data-limit n] <hdf5_file>")
24
+ sys.exit(0)
25
+
26
+ data_limit = None
27
+ filename = None
28
+ for i in range(1, len(sys.argv)):
29
+ if sys.argv[i] == "--nodata":
30
+ data_limit = 0
31
+ elif sys.argv[i] == "--data-limit":
32
+ i += 1
33
+ if i >= len(sys.argv):
34
+ sys.exit("Error: --data-limit requires a numeric argument")
35
+ try:
36
+ data_limit = int(sys.argv[i])
37
+ except ValueError:
38
+ sys.exit("Error: --data-limit requires a numeric argument")
39
+ else:
40
+ filename = sys.argv[i]
41
+
42
+ # create logger
43
+ logfname = "h5tojson.log"
44
+ loglevel = logging.DEBUG
45
+ logging.basicConfig(filename=logfname, format='%(levelname)s %(asctime)s %(message)s', level=loglevel)
46
+ log = logging.getLogger()
47
+
48
+ # check that the input file exists
49
+ if not op.isfile(filename):
50
+ sys.exit(f"Cannot find file: {filename}")
51
+
52
+ log.info(f"h5tojson {filename}")
53
+
54
+ # read_only=True: open the source file in h5py mode='r' - src_db never
55
+ # creates/modifies anything, and read_only guarantees that even if it
56
+ # somehow did, nothing could actually be written back to the source file
57
+ src_db = Hdf5db(plugin=H5pyPlugin(filename, read_only=True, app_logger=log), app_logger=log)
58
+ src_db.open() # read HDF5 data into src_db
59
+
60
+ dst_db = Hdf5db(plugin=H5JsonPlugin(None, data_limit=data_limit, app_logger=log), app_logger=log)
61
+ dst_db.open()
62
+
63
+ src_db.copy(dst_db) # write src_db's content into dst_db
64
+
65
+ dst_db.close() # triggers write to json file (stdout, since filepath is None)
66
+ src_db.close()
67
+
68
+
69
+ if __name__ == "__main__":
70
+ main()
@@ -0,0 +1,65 @@
1
+ ##############################################################################
2
+ # Copyright by The HDF Group. #
3
+ # All rights reserved. #
4
+ # #
5
+ # This file is part of H5Serv (HDF5 REST Server) Service, Libraries and #
6
+ # Utilities. The full HDF5 REST Server copyright notice, including #
7
+ # terms governing use, modification, and redistribution, is contained in #
8
+ # the file COPYING, which can be found at the root of the source code #
9
+ # distribution tree. If you do not have access to this file, you may #
10
+ # request a copy from help@hdfgroup.org. #
11
+ ##############################################################################
12
+ import sys
13
+ import os.path as op
14
+ import logging
15
+
16
+ from h5json import Hdf5db
17
+ from h5json.h5pystore.h5py_plugin import H5pyPlugin
18
+ from h5json.jsonstore.h5json_plugin import H5JsonPlugin
19
+
20
+
21
+ def main():
22
+ if len(sys.argv) < 3 or sys.argv[1] in ("-h", "--help"):
23
+ print(f"usage: {sys.argv[0]} [-h] [--nodata] <json_file> <h5_file>")
24
+ sys.exit(0)
25
+
26
+ no_data = False
27
+ json_filename = None
28
+ hdf5_filename = None
29
+ for i in range(1, len(sys.argv)):
30
+ if sys.argv[i] == "--nodata":
31
+ no_data = True
32
+ elif not json_filename:
33
+ json_filename = sys.argv[i]
34
+ else:
35
+ hdf5_filename = sys.argv[i]
36
+
37
+ # create logger
38
+ logfname = "jsontoh5.log"
39
+ loglevel = logging.DEBUG
40
+ logging.basicConfig(filename=logfname, format='%(levelname)s %(asctime)s %(message)s', level=loglevel)
41
+ log = logging.getLogger()
42
+
43
+ # check that the input file exists
44
+ if not op.isfile(json_filename):
45
+ sys.exit(f"Cannot find file: {json_filename}")
46
+
47
+ log.info(f"jsontoh5 {json_filename} to {hdf5_filename}")
48
+
49
+ # read_only=True: src_db never creates/modifies anything, and read_only
50
+ # guarantees flush() can never write back to json_filename even if it
51
+ # somehow did (append alone would still permit a write)
52
+ src_db = Hdf5db(plugin=H5JsonPlugin(json_filename, read_only=True, app_logger=log), app_logger=log)
53
+ src_db.open() # read json data into src_db
54
+
55
+ dst_db = Hdf5db(plugin=H5pyPlugin(hdf5_filename, no_data=no_data, app_logger=log), app_logger=log)
56
+ dst_db.open()
57
+
58
+ src_db.copy(dst_db) # write everything src_db read to the output file
59
+
60
+ dst_db.close()
61
+ src_db.close()
62
+
63
+
64
+ if __name__ == "__main__":
65
+ main()
@@ -0,0 +1,101 @@
1
+ ##############################################################################
2
+ # Copyright by The HDF Group. #
3
+ # All rights reserved. #
4
+ # #
5
+ # This file is part of h5json. The full copyright notice, including #
6
+ # terms governing use, modification, and redistribution, is contained in #
7
+ # the file COPYING, which can be found at the root of the source code #
8
+ # distribution tree. If you do not have access to this file, you may #
9
+ # request a copy from help@hdfgroup.org. #
10
+ ##############################################################################
11
+ import sys
12
+ import argparse
13
+ from pathlib import Path
14
+ import json
15
+ import jsonschema
16
+ from h5json import schema
17
+ try:
18
+ import importlib_resources as ilr
19
+ except ImportError:
20
+ import importlib.resources as ilr
21
+
22
+
23
+ def prepare_validator() -> jsonschema.Draft202012Validator:
24
+ """Return a configured jsonschema.Draft202012Validator instance."""
25
+ with ilr.open_text(schema, "hdf5.schema.json") as f:
26
+ h5schema = json.load(f)
27
+
28
+ schema_store = dict()
29
+ schema_components = [
30
+ "attribute.schema.json",
31
+ "filters.schema.json",
32
+ "group.schema.json",
33
+ "datatypes.schema.json",
34
+ "dataspaces.schema.json",
35
+ "dataset.schema.json",
36
+ ]
37
+ for sc in schema_components:
38
+ with ilr.open_text(schema, sc) as f:
39
+ temp = json.load(f)
40
+ schema_store[temp["$id"]] = temp
41
+ resolver = jsonschema.RefResolver(h5schema["$id"], h5schema, store=schema_store)
42
+ return jsonschema.Draft202012Validator(h5schema, resolver=resolver)
43
+
44
+
45
+ def main() -> None:
46
+ parser = argparse.ArgumentParser(
47
+ description="HDF5/JSON validator",
48
+ epilog="Copyright 2021 The HDF Group",
49
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
50
+ )
51
+ parser.add_argument(
52
+ "jsonloc",
53
+ nargs="+",
54
+ help="JSON location (files or folders)",
55
+ metavar="JSON_LOC",
56
+ type=Path,
57
+ )
58
+ parser.add_argument(
59
+ "--stop",
60
+ "-s",
61
+ action="store_true",
62
+ help="Stop after first HDF5/JSON file failed validation",
63
+ )
64
+ args = parser.parse_args()
65
+
66
+ # Find all JSON files for validation...
67
+ json_files = list()
68
+ for p in args.jsonloc:
69
+ if p.is_file():
70
+ json_files.append(p)
71
+ elif p.is_dir():
72
+ json_files.extend([f for f in p.glob("*.json")])
73
+ if not json_files:
74
+ sys.exit("No JSON files for validation found.")
75
+
76
+ validator = prepare_validator()
77
+
78
+ # Validate HDF5/JSON files...
79
+ valid_errors = False
80
+ for h5j in json_files:
81
+ print(f"Validating {str(h5j)} ... ", end="")
82
+ try:
83
+ with h5j.open() as f:
84
+ inst = json.load(f)
85
+ validator.validate(inst)
86
+ print("pass")
87
+ except jsonschema.exceptions.ValidationError:
88
+ print("FAIL")
89
+ valid_errors = True
90
+ inst_name = str(h5j)
91
+ print(f"HDF5/JSON validation failed for {inst_name}", file=sys.stderr)
92
+ for err in validator.iter_errors(inst):
93
+ print(f"{inst_name} ---> {err}", file=sys.stderr)
94
+ if args.stop:
95
+ sys.exit("HDF5/JSON validation failed.")
96
+ if valid_errors:
97
+ sys.exit("HDF5/JSON validation failed.")
98
+
99
+
100
+ if __name__ == "__main__":
101
+ main()