File size: 5,010 Bytes
db613b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Read-only audit of existing Hub asset shards using ranged metadata reads."""

from __future__ import annotations

import argparse
import json
from collections import Counter
from pathlib import Path

import pyarrow.parquet as pq
from huggingface_hub import HfApi, HfFileSystem

from kitti_c2l.release import require
from kitti_c2l.schema import ASSETS_SCHEMA
from kitti_c2l.sequence_mapping import load_sequence_mapping


def audit(repo_id: str, revision: str | None, root: Path) -> dict:
    api = HfApi()
    info = api.dataset_info(repo_id, revision=revision, files_metadata=True)
    inventory = []
    for item in info.siblings or []:
        lfs = item.lfs
        inventory.append(
            {
                "path": item.rfilename,
                "bytes": item.size,
                "sha256": (getattr(lfs, "sha256", None) or lfs.get("sha256")) if lfs else None,
            }
        )
    fs = HfFileSystem()
    mapping = load_sequence_mapping()
    expected = {
        (seq, frame)
        for seq, source in mapping.items()
        if source.available
        for frame in range(source.frame_count)
    }
    seen = set()
    counts = Counter()
    shards = []
    columns = [
        "frame_id",
        "sequence",
        "frame_index",
        "split",
        "camera_id",
        "image_width",
        "image_height",
        "raw_date",
        "raw_drive",
        "raw_frame_index",
    ]
    for item in inventory:
        if not Path(item["path"]).name.startswith("frames_"):
            continue
        path = f"datasets/{repo_id}@{info.sha}/{item['path']}"
        with fs.open(path, "rb", block_size=256 * 1024, cache_type="readahead") as stream:
            parquet = pq.ParquetFile(stream)
            require(
                parquet.schema_arrow.equals(ASSETS_SCHEMA, check_metadata=False),
                f"schema mismatch: {item['path']}",
            )
            rows = parquet.read(columns=columns, use_threads=False).to_pylist()
            row_groups = parquet.metadata.num_row_groups
        for row in rows:
            key = (row["sequence"], row["frame_index"])
            require(
                key in expected and key not in seen, f"missing/unexpected/duplicate frame: {key}"
            )
            seen.add(key)
            source = mapping[row["sequence"]]
            require(
                row["frame_id"] == f"{row['sequence']}_{row['frame_index']:06d}",
                "frame ID mismatch",
            )
            require(
                (row["raw_date"], row["raw_drive"], row["raw_frame_index"])
                == (source.date, source.drive, source.start + row["frame_index"]),
                "Raw mapping mismatch",
            )
            require(row["split"] == source.split and row["camera_id"] == 2, "split/camera mismatch")
            counts[source.split] += 1
        shards.append(dict(item, rows=len(rows), row_groups=row_groups))
        print(f"{item['path']}: {len(rows)} frame identities verified", flush=True)
    require(seen == expected, "incomplete source-frame coverage")
    local = json.loads((root / "release/v1/manifest.json").read_text())
    remote = {item["path"]: item for item in inventory}
    for item in local["files"]:
        require(
            remote[item["path"]]["sha256"] == item["sha256"]
            and remote[item["path"]]["bytes"] == item["bytes"],
            "metadata snapshot differs from local audit",
        )
    return {
        "repo_id": repo_id,
        "revision": info.sha,
        "private_at_audit": info.private,
        "shards": shards,
        "frames_by_split": dict(counts),
        "total_frames": len(seen),
        "asset_bytes": sum(item["bytes"] for item in shards),
        "audit_scope": "All shard schemas, row counts and frame identity/source mapping columns via authenticated ranged reads. Payload checksums are Hub LFS declarations; not a download of every sensor payload.",
        "schema_coverage_and_raw_mappings": "pass",
        "metadata_files": [remote[item["path"]] for item in local["files"]],
        "metadata_sha256_matches_audited_snapshot": True,
    }


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--repo-id", default="mcocheteux/KITTI-C2L-Dataset")
    parser.add_argument("--revision", help="Pinned Hub revision; defaults to current main")
    parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1])
    parser.add_argument("--output", required=True, type=Path)
    args = parser.parse_args()
    if args.output.exists():
        raise FileExistsError(f"Refusing to overwrite audit: {args.output}")
    report = audit(args.repo_id, args.revision, args.root)
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_text(json.dumps(report, indent=2) + "\n")
    print(
        f"Verified {report['total_frames']} frames in {len(report['shards'])} shards; report: {args.output}"
    )


if __name__ == "__main__":
    main()