File size: 3,759 Bytes
cc858da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
import json
import math
from pathlib import Path

import numpy as np


ROOT = Path(".")
DATA_DIR = ROOT / "data"
META_DIR = ROOT / "metadata"

SPLITS = {
    "train": "train",
    "val": "validation",
    "validation": "validation",
    "test": "test",
}

EXPECTED_SHAPE = (64, 32, 32)
EXPECTED_DTYPE = np.float32


def read_json(path: Path) -> dict:
    with path.open("r", encoding="utf-8") as f:
        return json.load(f)


def parse_stiffness(value):
    if value is None:
        return None
    if isinstance(value, (int, float)) and math.isfinite(float(value)):
        return float(value)
    raise ValueError(f"invalid stiffness: {value!r}")


def get_label(targets: dict):
    # 兼容旧字段 rigidity,新字段 deformation_response 优先。
    if "deformation_response" in targets:
        label = targets["deformation_response"]
    elif "rigidity" in targets:
        label = targets["rigidity"]
    else:
        raise ValueError("missing targets.deformation_response or targets.rigidity")

    if label not in ("rigid", "deformable"):
        raise ValueError(f"invalid deformation label: {label!r}")

    return label


def inspect_npz(npz_path: Path):
    with np.load(npz_path, allow_pickle=False) as z:
        if "frames" not in z.files:
            raise ValueError(f"missing key 'frames', keys={z.files}")

        frames = z["frames"]
        shape = tuple(frames.shape)
        dtype = frames.dtype

        if shape != EXPECTED_SHAPE:
            raise ValueError(f"bad shape {shape}, expected {EXPECTED_SHAPE}")

        if dtype != EXPECTED_DTYPE:
            raise ValueError(f"bad dtype {dtype}, expected float32")

        return shape, str(dtype)


def main():
    META_DIR.mkdir(parents=True, exist_ok=True)

    summary = {}

    for folder_name, split_name in SPLITS.items():
        split_dir = DATA_DIR / folder_name
        if not split_dir.exists():
            continue

        rows = []
        errors = []

        for npz_path in sorted(split_dir.glob("*.npz")):
            json_path = npz_path.with_suffix(".json")

            if not json_path.exists():
                errors.append(f"{npz_path.name}: missing json")
                continue

            try:
                meta = read_json(json_path)
                targets = meta.get("targets", {})

                shape, dtype = inspect_npz(npz_path)

                row = {
                    "file_name": npz_path.name,
                    "npz_path": str(npz_path.as_posix()),
                    "json_path": str(json_path.as_posix()),
                    "sample_id": meta.get("sample_id"),
                    "specimen_id": meta.get("specimen_id"),
                    "deformation_response": get_label(targets),
                    "stiffness": parse_stiffness(targets.get("stiffness")),
                    "num_frames": shape[0],
                    "height": shape[1],
                    "width": shape[2],
                    "dtype": dtype,
                    "split": split_name,
                }
                rows.append(row)

            except Exception as exc:
                errors.append(f"{npz_path.name}: {exc}")

        out_path = META_DIR / f"{split_name}.jsonl"
        with out_path.open("w", encoding="utf-8") as f:
            for row in rows:
                f.write(json.dumps(row, ensure_ascii=False, allow_nan=False) + "\n")

        summary[split_name] = {
            "samples": len(rows),
            "errors": errors,
        }

    with (META_DIR / "summary.json").open("w", encoding="utf-8") as f:
        json.dump(summary, f, indent=2, ensure_ascii=False, allow_nan=False)

    print(json.dumps(summary, indent=2, ensure_ascii=False))


if __name__ == "__main__":
    main()