#!/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()