| |
| |
|
|
| """ |
| Inspect any HDF5 file as a readable tree, including attributes. |
| |
| Examples: |
| python scripts/readh5.py data/example.h5 |
| python scripts/readh5.py data/example.h5 --max-depth 3 --max-items 20 |
| python scripts/readh5.py data/example.h5 --all --preview 5 |
| """ |
|
|
| import argparse |
| import math |
|
|
| import h5py |
| import numpy as np |
|
|
|
|
| DEFAULT_H5_FILE = "data/hdf5/continuous_waveform_usa_20190701.h5" |
|
|
|
|
| def safe_decode(value): |
| if isinstance(value, bytes): |
| return value.decode("utf-8", errors="replace") |
| return value |
|
|
|
|
| def format_scalar(value): |
| value = safe_decode(value) |
|
|
| if isinstance(value, np.generic): |
| value = value.item() |
| value = safe_decode(value) |
|
|
| return repr(value) if isinstance(value, str) else str(value) |
|
|
|
|
| def format_array(value, max_values=8): |
| array = np.asarray(value) |
|
|
| if array.ndim == 0: |
| return format_scalar(array[()]) |
|
|
| flat_values = [format_scalar(x) for x in array.flat[:max_values]] |
| suffix = ", ..." if array.size > max_values else "" |
| preview = ", ".join(flat_values) + suffix |
|
|
| return ( |
| f"array(shape={array.shape}, dtype={array.dtype}, " |
| f"values=[{preview}])" |
| ) |
|
|
|
|
| def format_attr_value(value, max_values=8): |
| if isinstance(value, np.ndarray): |
| return format_array(value, max_values=max_values) |
|
|
| if isinstance(value, (list, tuple)): |
| values = [format_attr_value(x, max_values=max_values) for x in value[:max_values]] |
| suffix = ", ..." if len(value) > max_values else "" |
| return f"{type(value).__name__}([{', '.join(values)}{suffix}])" |
|
|
| return format_scalar(value) |
|
|
|
|
| def format_nbytes(nbytes): |
| if nbytes is None: |
| return "unknown" |
|
|
| units = ("B", "KiB", "MiB", "GiB", "TiB") |
| value = float(nbytes) |
| unit_index = 0 |
|
|
| while value >= 1024 and unit_index < len(units) - 1: |
| value /= 1024 |
| unit_index += 1 |
|
|
| if unit_index == 0: |
| return f"{int(value)} {units[unit_index]}" |
| return f"{value:.2f} {units[unit_index]}" |
|
|
|
|
| def dataset_nbytes(dataset): |
| if dataset.shape is None: |
| return None |
|
|
| if any(dim is None for dim in dataset.shape): |
| return None |
|
|
| return math.prod(dataset.shape) * dataset.dtype.itemsize |
|
|
|
|
| def print_attrs(obj, indent, max_attr_values): |
| prefix = " " * indent |
|
|
| if not obj.attrs: |
| return |
|
|
| print(f"{prefix}@attrs") |
| for key, value in obj.attrs.items(): |
| formatted = format_attr_value(value, max_values=max_attr_values) |
| print(f"{prefix} - {key}: {formatted}") |
|
|
|
|
| def print_dataset(dataset, name, indent, max_attr_values, preview): |
| prefix = " " * indent |
| details = [ |
| f"shape={dataset.shape}", |
| f"dtype={dataset.dtype}", |
| f"size={format_nbytes(dataset_nbytes(dataset))}", |
| ] |
|
|
| if dataset.chunks is not None: |
| details.append(f"chunks={dataset.chunks}") |
|
|
| if dataset.compression is not None: |
| compression = dataset.compression |
| if dataset.compression_opts is not None: |
| compression = f"{compression}:{dataset.compression_opts}" |
| details.append(f"compression={compression}") |
|
|
| if dataset.maxshape is not None and dataset.maxshape != dataset.shape: |
| details.append(f"maxshape={dataset.maxshape}") |
|
|
| print(f"{prefix}{name} [Dataset] " + ", ".join(details)) |
| print_attrs(dataset, indent + 2, max_attr_values=max_attr_values) |
|
|
| if preview > 0: |
| print_dataset_preview(dataset, indent + 2, preview) |
|
|
|
|
| def print_dataset_preview(dataset, indent, preview): |
| prefix = " " * indent |
|
|
| try: |
| if dataset.shape == (): |
| values = dataset[()] |
| elif dataset.size == 0: |
| values = [] |
| elif dataset.ndim == 1: |
| values = dataset[:preview] |
| else: |
| slices = tuple(slice(0, min(preview, dim)) for dim in dataset.shape) |
| values = dataset[slices] |
|
|
| print(f"{prefix}preview: {format_array(values, max_values=preview)}") |
| except Exception as exc: |
| print(f"{prefix}preview: <unavailable: {exc}>") |
|
|
|
|
| def print_link(group, key, indent): |
| prefix = " " * indent |
| link = group.get(key, getlink=True) |
|
|
| if isinstance(link, h5py.SoftLink): |
| print(f"{prefix}{key} [SoftLink] -> {link.path}") |
| return True |
|
|
| if isinstance(link, h5py.ExternalLink): |
| print(f"{prefix}{key} [ExternalLink] -> {link.filename}:{link.path}") |
| return True |
|
|
| return False |
|
|
|
|
| def sorted_or_native(keys, sort_keys): |
| return sorted(keys) if sort_keys else list(keys) |
|
|
|
|
| def iter_limited(values, max_items): |
| if max_items is None: |
| yield from values |
| return |
|
|
| for value in values[:max_items]: |
| yield value |
|
|
|
|
| def inspect_group( |
| group, |
| name, |
| indent, |
| max_items, |
| max_depth, |
| max_attr_values, |
| preview, |
| sort_keys, |
| seen, |
| ): |
| prefix = " " * indent |
| node_type = "File" if isinstance(group, h5py.File) else "Group" |
| display_name = "/" if isinstance(group, h5py.File) else f"{name}/" |
| print(f"{prefix}{display_name} [{node_type}]") |
| print_attrs(group, indent + 2, max_attr_values=max_attr_values) |
|
|
| if max_depth is not None and indent // 2 >= max_depth: |
| print(f"{prefix} ... max depth reached") |
| return |
|
|
| keys = sorted_or_native(group.keys(), sort_keys=sort_keys) |
|
|
| for key in iter_limited(keys, max_items=max_items): |
| if print_link(group, key, indent + 2): |
| continue |
|
|
| try: |
| item = group[key] |
| except Exception as exc: |
| print(f"{' ' * (indent + 2)}{key} [Unreadable] {exc}") |
| continue |
|
|
| object_id = item.id.__hash__() |
| if object_id in seen: |
| print(f"{' ' * (indent + 2)}{key} [Already visited]") |
| continue |
|
|
| if isinstance(item, h5py.Group): |
| seen.add(object_id) |
| inspect_group( |
| item, |
| name=key, |
| indent=indent + 2, |
| max_items=max_items, |
| max_depth=max_depth, |
| max_attr_values=max_attr_values, |
| preview=preview, |
| sort_keys=sort_keys, |
| seen=seen, |
| ) |
| elif isinstance(item, h5py.Dataset): |
| print_dataset( |
| item, |
| name=key, |
| indent=indent + 2, |
| max_attr_values=max_attr_values, |
| preview=preview, |
| ) |
| else: |
| print(f"{' ' * (indent + 2)}{key} [{type(item).__name__}]") |
|
|
| if max_items is not None: |
| remaining = len(keys) - max_items |
| if remaining > 0: |
| print(f"{prefix} ... {remaining} more item(s), use --all to show all") |
|
|
|
|
| def inspect_hdf5( |
| h5_file, |
| max_items=50, |
| max_depth=None, |
| max_attr_values=8, |
| preview=0, |
| sort_keys=False, |
| ): |
| with h5py.File(h5_file, "r") as h5: |
| inspect_group( |
| h5, |
| name="/", |
| indent=0, |
| max_items=max_items, |
| max_depth=max_depth, |
| max_attr_values=max_attr_values, |
| preview=preview, |
| sort_keys=sort_keys, |
| seen={h5.id.__hash__()}, |
| ) |
|
|
|
|
| def positive_int(value): |
| value = int(value) |
| if value < 0: |
| raise argparse.ArgumentTypeError("value must be >= 0") |
| return value |
|
|
|
|
| def parse_args(): |
| parser = argparse.ArgumentParser( |
| description="Read any HDF5 file and print its tree structure with attributes." |
| ) |
| parser.add_argument( |
| "h5_file", |
| nargs="?", |
| default=DEFAULT_H5_FILE, |
| help=f"Input HDF5 file. Default: {DEFAULT_H5_FILE}", |
| ) |
| parser.add_argument( |
| "--h5_file", |
| dest="h5_file_option", |
| help="Input HDF5 file, kept for compatibility with older commands.", |
| ) |
| parser.add_argument( |
| "--max-items", |
| "--max_items", |
| type=positive_int, |
| default=50, |
| help="Maximum child items shown under each group. Default: 50.", |
| ) |
| parser.add_argument( |
| "--all", |
| action="store_true", |
| help="Show all child items under each group.", |
| ) |
| parser.add_argument( |
| "--max-depth", |
| "--max_depth", |
| type=positive_int, |
| default=None, |
| help="Maximum display depth. File root is depth 0. Default: unlimited.", |
| ) |
| parser.add_argument( |
| "--max-attr-values", |
| type=positive_int, |
| default=8, |
| help="Maximum values shown for each array-like attribute. Default: 8.", |
| ) |
| parser.add_argument( |
| "--preview", |
| type=positive_int, |
| default=0, |
| help="Preview up to N values from each dataset. Default: 0.", |
| ) |
| parser.add_argument( |
| "--sort", |
| action="store_true", |
| help="Sort group keys alphabetically instead of using file order.", |
| ) |
|
|
| args = parser.parse_args() |
|
|
| if args.h5_file_option: |
| args.h5_file = args.h5_file_option |
|
|
| if args.all: |
| args.max_items = None |
|
|
| return args |
|
|
|
|
| def main(): |
| args = parse_args() |
|
|
| inspect_hdf5( |
| h5_file=args.h5_file, |
| max_items=args.max_items, |
| max_depth=args.max_depth, |
| max_attr_values=args.max_attr_values, |
| preview=args.preview, |
| sort_keys=args.sort, |
| ) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|