File size: 3,022 Bytes
222e253 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import h5py
import numpy as np
def format_attr_value(value):
if isinstance(value, bytes):
return value.decode("utf-8", errors="ignore")
if isinstance(value, np.ndarray):
if value.size <= 6:
return value.tolist()
return f"array(shape={value.shape}, dtype={value.dtype})"
return value
def print_attrs(obj, indent):
if len(obj.attrs) == 0:
print(" " * indent + "attrs: {}")
return
print(" " * indent + "attrs:")
for key, value in obj.attrs.items():
value = format_attr_value(value)
print(" " * (indent + 2) + f"- {key}: {value}")
def inspect_group(group, name="/", indent=0, max_items=3, max_depth=None):
prefix = " " * indent
if isinstance(group, h5py.File):
print(f"{prefix}/ [File]")
else:
print(f"{prefix}{name}/ [Group]")
print_attrs(group, indent + 2)
if max_depth is not None and indent // 2 >= max_depth:
print(" " * (indent + 2) + "... max depth reached")
return
keys = list(group.keys())
shown_keys = keys[:max_items]
for key in shown_keys:
item = group[key]
if isinstance(item, h5py.Group):
inspect_group(
item,
name=key,
indent=indent + 2,
max_items=max_items,
max_depth=max_depth,
)
elif isinstance(item, h5py.Dataset):
print_dataset(
item,
name=key,
indent=indent + 2,
)
remaining = len(keys) - len(shown_keys)
if remaining > 0:
print(" " * (indent + 2) + f"... {remaining} more items not shown")
def print_dataset(dataset, name, indent):
prefix = " " * indent
print(
f"{prefix}{name} [Dataset] "
f"shape={dataset.shape}, dtype={dataset.dtype}"
)
print_attrs(dataset, indent + 2)
def inspect_hdf5(h5_file, max_items=3, max_depth=None):
with h5py.File(h5_file, "r") as h5:
inspect_group(
h5,
name="/",
indent=0,
max_items=max_items,
max_depth=max_depth,
)
def main():
parser = argparse.ArgumentParser(
description="Inspect HDF5 hierarchy and attributes."
)
parser.add_argument(
"--h5_file",
default="data/hdf5/continuous_waveform_usa_20190701.h5",
help="Input HDF5 file.",
)
parser.add_argument(
"--max_items",
type=int,
default=1,
help="Maximum number of child items shown under each group.",
)
parser.add_argument(
"--max_depth",
type=int,
default=None,
help="Maximum display depth. Default is unlimited.",
)
args = parser.parse_args()
inspect_hdf5(
h5_file=args.h5_file,
max_items=args.max_items,
max_depth=args.max_depth,
)
if __name__ == "__main__":
main() |