File size: 5,417 Bytes
1c49dd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#!/usr/bin/env python3
"""Inspect downloaded PHM-Vibench metadata and H5 samples locally."""

from __future__ import annotations

import argparse
import sys
from pathlib import Path

from phm_vibench_manifest import DATASET_TO_FILE, FILE_SIZES


REQUIRED_COLUMNS = ["Id", "Name", "File", "Label", "Sample_rate", "Sample_lenth", "Channel"]


def import_pandas():
    try:
        import pandas as pd
    except ImportError as exc:
        raise SystemExit("Missing dependency: pandas/openpyxl. Install with `pip install -r requirements.txt`.") from exc
    return pd


def import_h5py():
    try:
        import h5py
    except ImportError as exc:
        raise SystemExit("Missing dependency: h5py. Install with `pip install -r requirements.txt`.") from exc
    return h5py


def load_metadata(root: Path):
    path = root / "metadata.xlsx"
    if not path.is_file():
        raise SystemExit(f"Missing metadata.xlsx under {root}")
    pd = import_pandas()
    df = pd.read_excel(path)
    missing = [column for column in REQUIRED_COLUMNS if column not in df.columns]
    if missing:
        raise SystemExit("metadata.xlsx missing required columns: " + ", ".join(missing))
    return df


def print_dataset_summary(df) -> None:
    counts = df["Name"].value_counts().sort_index()
    print("datasets:", len(counts))
    for dataset, count in counts.items():
        file_name = DATASET_TO_FILE.get(dataset, "")
        print(f"{dataset:<18} samples={count:<6} file={file_name}")


def normalize_dataset_id(dataset: str) -> str:
    lookup = {name.lower(): name for name in DATASET_TO_FILE}
    normalized = lookup.get(dataset.lower())
    if normalized is None:
        raise SystemExit(f"Unknown dataset {dataset}. Use --list-datasets to inspect valid dataset ids.")
    return normalized


def choose_smoke_dataset(root: Path) -> str:
    present = []
    for dataset, h5_name in DATASET_TO_FILE.items():
        if (root / h5_name).is_file():
            present.append((FILE_SIZES[h5_name], dataset))
    if not present:
        raise SystemExit(f"No published H5 file found under {root}; download --preset demo or choose --metadata-only")
    present.sort()
    return present[0][1]


def select_sample(df, dataset: str, sample_index: int, sample_id: str | None):
    rows = df[df["Name"].eq(dataset)].reset_index(drop=True)
    if rows.empty:
        raise SystemExit(f"Dataset {dataset} not found in metadata.xlsx")
    if sample_id is not None:
        matches = rows[rows["Id"].astype(str).eq(sample_id)]
        if matches.empty:
            raise SystemExit(f"Sample id {sample_id} not found in dataset {dataset}")
        return matches.iloc[0], len(rows)
    if sample_index < 0 or sample_index >= len(rows):
        raise SystemExit(f"--sample-index must be in [0, {len(rows) - 1}] for {dataset}")
    return rows.iloc[sample_index], len(rows)


def inspect_sample(root: Path, dataset: str, sample_index: int, sample_id: str | None, *, metadata_only: bool) -> None:
    df = load_metadata(root)
    row, dataset_rows = select_sample(df, dataset, sample_index, sample_id)
    sample_key = str(int(row["Id"]))
    h5_name = DATASET_TO_FILE.get(dataset)
    if h5_name is None:
        raise SystemExit(f"Dataset {dataset} is not in the published H5 manifest")

    print(f"root={root}")
    print(f"dataset={dataset} samples={dataset_rows} h5={h5_name}")
    print(
        "sample "
        f"id={sample_key} label={row['Label']} sample_rate={row['Sample_rate']} "
        f"sample_lenth={row['Sample_lenth']} channel={row['Channel']}"
    )

    if metadata_only:
        return

    h5_path = root / h5_name
    if not h5_path.is_file():
        raise SystemExit(f"Missing {h5_name} under {root}")
    h5py = import_h5py()
    with h5py.File(h5_path, "r") as h5:
        if sample_key not in h5:
            raise SystemExit(f"Sample id {sample_key} not found in {h5_name}")
        dataset_obj = h5[sample_key]
        print(f"h5 key={sample_key} shape={dataset_obj.shape} dtype={dataset_obj.dtype}")


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--root", type=Path, default=Path("PHM-Vibench"), help="Downloaded dataset root")
    parser.add_argument("--dataset", default="RM_007_MFPT", help="Dataset id such as RM_007_MFPT; case-insensitive")
    parser.add_argument("--sample-index", type=int, default=0, help="Zero-based sample index within --dataset")
    parser.add_argument("--sample-id", help="Explicit sample Id from metadata.xlsx; overrides --sample-index")
    parser.add_argument("--metadata-only", action="store_true", help="Inspect metadata without opening the H5 file")
    parser.add_argument("--list-datasets", action="store_true", help="List dataset sample counts from metadata.xlsx")
    parser.add_argument("--smoke", action="store_true", help="Inspect the smallest published H5 file present under --root")
    return parser.parse_args()


def main() -> int:
    args = parse_args()
    if args.list_datasets:
        print_dataset_summary(load_metadata(args.root))
        return 0
    dataset = choose_smoke_dataset(args.root) if args.smoke else normalize_dataset_id(args.dataset)
    inspect_sample(
        args.root,
        dataset,
        args.sample_index,
        args.sample_id,
        metadata_only=args.metadata_only,
    )
    return 0


if __name__ == "__main__":
    sys.exit(main())