Download scripts/prepare_data.py from wangyanbo/MindView-Bench: direct link, hf CLI and curl.
- Browser
- Download file 14.7 kB
-
https://huggingface.co/datasets/wangyanbo/MindView-Bench/resolve/main/scripts/prepare_data.py
- Command line
-
hf download hf://datasets/wangyanbo/MindView-Bench/scripts/prepare_data.py
-
curl -L -o prepare_data.py https://huggingface.co/datasets/wangyanbo/MindView-Bench/resolve/main/scripts/prepare_data.py
14.7 kB
| #!/usr/bin/env python3 | |
| """Verify a complete MindView dataset snapshot; optionally extract its listed assets. | |
| Standard library only. Does not access credentials, networks, or model runtimes. | |
| Use a trusted, pinned snapshot and a destination not modified by other processes. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import json | |
| import os | |
| from pathlib import Path, PurePosixPath | |
| import re | |
| import stat | |
| import sys | |
| import tarfile | |
| import tempfile | |
| CHUNK = 8 * 1024 * 1024 | |
| SOURCES = {"scannet", "scannetpp", "arkitscenes"} | |
| SHA = re.compile(r"[0-9a-f]{64}\Z") | |
| class VerificationError(Exception): | |
| """Invalid package or unsafe extraction request.""" | |
| def relative(value: object, label: str) -> str: | |
| if not isinstance(value, str) or not value or "\\" in value or any(ord(char) < 32 or ord(char) == 127 for char in value): | |
| raise VerificationError(f"Invalid {label}: {value!r}") | |
| parts = value.split("/") | |
| if value.startswith("/") or any(p in {"", ".", ".."} for p in parts): | |
| raise VerificationError(f"Unsafe {label}: {value!r}") | |
| if ":" in parts[0] or str(PurePosixPath(value)) != value: | |
| raise VerificationError(f"Noncanonical {label}: {value!r}") | |
| return value | |
| def digest_value(value: object, label: str) -> str: | |
| if not isinstance(value, str) or SHA.fullmatch(value) is None: | |
| raise VerificationError(f"Invalid SHA256 for {label}") | |
| return value | |
| def size_value(value: object, label: str) -> int: | |
| if type(value) is not int or value < 0: | |
| raise VerificationError(f"Invalid byte size for {label}") | |
| return value | |
| def check_ancestors(path: Path, *, missing_ok: bool = False) -> None: | |
| """Reject symlinks and non-directories in every existing parent component.""" | |
| absolute = path.absolute() | |
| current = Path(absolute.anchor) | |
| for part in absolute.parts[1:]: | |
| current = current / part | |
| try: | |
| status = current.lstat() | |
| except FileNotFoundError: | |
| if missing_ok: | |
| return | |
| raise VerificationError(f"Missing directory: {current}") from None | |
| if stat.S_ISLNK(status.st_mode) or not stat.S_ISDIR(status.st_mode): | |
| raise VerificationError(f"Expected a real directory, found unsafe component: {current}") | |
| def input_file(repo: Path, name: str) -> Path: | |
| path = repo / relative(name, "repository path") | |
| check_ancestors(path.parent) | |
| try: | |
| mode = path.lstat().st_mode | |
| except FileNotFoundError: | |
| raise VerificationError(f"Missing package file: {name}") from None | |
| if not stat.S_ISREG(mode): | |
| raise VerificationError(f"Package file is not a regular file: {name}") | |
| return path | |
| def open_regular(path: Path): | |
| flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | |
| fd = os.open(path, flags) | |
| if not stat.S_ISREG(os.fstat(fd).st_mode): | |
| os.close(fd) | |
| raise VerificationError(f"Not a regular file: {path}") | |
| return os.fdopen(fd, "rb") | |
| def hash_stream(stream) -> tuple[str, int]: | |
| digest = hashlib.sha256() | |
| total = 0 | |
| while True: | |
| block = stream.read(CHUNK) | |
| if not block: | |
| return digest.hexdigest(), total | |
| digest.update(block) | |
| total += len(block) | |
| def file_hash(path: Path) -> tuple[str, int]: | |
| with open_regular(path) as stream: | |
| return hash_stream(stream) | |
| def checksum_inventory(repo: Path) -> dict[str, str]: | |
| checks = {} | |
| inventory = input_file(repo, "SHA256SUMS") | |
| with inventory.open("r", encoding="utf-8") as stream: | |
| for number, line in enumerate(stream, 1): | |
| line = line.rstrip("\n") | |
| match = re.fullmatch(r"([0-9a-f]{64}) [ *](.+)", line) | |
| if match is None: | |
| raise VerificationError(f"Malformed SHA256SUMS line {number}") | |
| expected, name = match.groups() | |
| relative(name, "checksum path") | |
| if name == "SHA256SUMS" or name in checks: | |
| raise VerificationError(f"Duplicate/self-referential checksum path: {name}") | |
| checks[name] = expected | |
| if not checks: | |
| raise VerificationError("Empty SHA256SUMS inventory") | |
| for name, expected in checks.items(): | |
| actual, _ = file_hash(input_file(repo, name)) | |
| if actual != expected: | |
| raise VerificationError(f"Checksum mismatch: {name}") | |
| return checks | |
| def read_manifest(repo: Path, checks: dict[str, str]): | |
| index_name = "manifests/asset_archives.json" | |
| assets_name = "manifests/assets.jsonl" | |
| for name in (index_name, assets_name): | |
| if name not in checks: | |
| raise VerificationError(f"Missing checksum entry: {name}") | |
| with input_file(repo, index_name).open("r", encoding="utf-8") as stream: | |
| index = json.load(stream) | |
| if not isinstance(index, dict) or not isinstance(index.get("archives"), list): | |
| raise VerificationError("Archive index must contain an archives list") | |
| archives = {} | |
| members = {} | |
| destinations = set() | |
| for entry in index["archives"]: | |
| if not isinstance(entry, dict): | |
| raise VerificationError("Archive entry must be an object") | |
| name = relative(entry.get("path"), "archive path") | |
| if not name.startswith("assets/") or not name.endswith(".tar"): | |
| raise VerificationError(f"Expected an assets/*.tar archive: {name}") | |
| if name in archives: | |
| raise VerificationError(f"Duplicate archive: {name}") | |
| source = entry.get("dataset") | |
| if not isinstance(source, str) or source not in SOURCES: | |
| raise VerificationError(f"Unknown source dataset: {source!r}") | |
| size_value(entry.get("bytes"), name) | |
| digest_value(entry.get("sha256"), name) | |
| if checks.get(name) != entry["sha256"]: | |
| raise VerificationError(f"Archive hash absent/inconsistent in SHA256SUMS: {name}") | |
| if input_file(repo, name).stat().st_size != entry["bytes"]: | |
| raise VerificationError(f"Archive size mismatch: {name}") | |
| archives[name] = entry | |
| members[name] = {} | |
| with input_file(repo, assets_name).open("r", encoding="utf-8") as stream: | |
| for number, line in enumerate(stream, 1): | |
| try: | |
| row = json.loads(line) | |
| except json.JSONDecodeError as exc: | |
| raise VerificationError(f"Malformed assets.jsonl line {number}: {exc}") from None | |
| if not isinstance(row, dict): | |
| raise VerificationError(f"Asset row {number} is not an object") | |
| shard = relative(row.get("shard"), "asset shard") | |
| member = relative(row.get("member"), "TAR member") | |
| source_path = relative(row.get("relative_path"), "asset source path") | |
| if shard not in archives: | |
| raise VerificationError(f"Asset points to an unlisted archive: {shard}") | |
| if row.get("dataset") != archives[shard]["dataset"]: | |
| raise VerificationError(f"Dataset mismatch for {shard}:{member}") | |
| if member != source_path: | |
| raise VerificationError(f"Member/source path mismatch: {shard}:{member}") | |
| size_value(row.get("bytes"), member) | |
| digest_value(row.get("sha256"), member) | |
| destination = f"{row['dataset']}/{source_path}" | |
| if member in members[shard] or destination in destinations: | |
| raise VerificationError(f"Duplicate asset destination: {destination}") | |
| destinations.add(destination) | |
| members[shard][member] = row | |
| ordered_destinations = sorted(destinations) | |
| for first, second in zip(ordered_destinations, ordered_destinations[1:]): | |
| if second.startswith(first + "/"): | |
| raise VerificationError(f"Overlapping asset destinations: {first} and {second}") | |
| if not destinations or not archives: | |
| raise VerificationError("Empty asset/archive inventory") | |
| for name, entries in members.items(): | |
| if not entries: | |
| raise VerificationError(f"Archive has no listed assets: {name}") | |
| declared = archives[name].get("num_assets") | |
| if declared is not None and declared != len(entries): | |
| raise VerificationError(f"Archive member count mismatch: {name}") | |
| declared_bytes = archives[name].get("uncompressed_bytes") | |
| if declared_bytes is not None and declared_bytes != sum(r["bytes"] for r in entries.values()): | |
| raise VerificationError(f"Archive uncompressed byte count mismatch: {name}") | |
| return archives, members | |
| def checked_members(repo: Path, name: str, expected: dict): | |
| """Yield regular, listed members only; the caller must consume all members.""" | |
| seen = set() | |
| with open_regular(input_file(repo, name)) as stream: | |
| with tarfile.open(fileobj=stream, mode="r:") as archive: | |
| for member in archive: | |
| relative(member.name, "TAR member") | |
| if not member.isfile() or member.issparse(): | |
| raise VerificationError(f"Non-regular/sparse TAR member: {name}:{member.name}") | |
| if member.name in seen or member.name not in expected: | |
| raise VerificationError(f"Duplicate/unlisted TAR member: {name}:{member.name}") | |
| seen.add(member.name) | |
| row = expected[member.name] | |
| if member.size != row["bytes"]: | |
| raise VerificationError(f"Member size mismatch: {name}:{member.name}") | |
| payload = archive.extractfile(member) | |
| if payload is None: | |
| raise VerificationError(f"Cannot read TAR member: {name}:{member.name}") | |
| with payload: | |
| yield row, payload | |
| if seen != set(expected): | |
| missing = sorted(set(expected) - seen) | |
| raise VerificationError(f"Missing TAR members in {name}: {missing[:3]}") | |
| def verify_members(repo: Path, members: dict) -> None: | |
| for name, entries in members.items(): | |
| for row, payload in checked_members(repo, name, entries): | |
| digest, length = hash_stream(payload) | |
| if digest != row["sha256"] or length != row["bytes"]: | |
| raise VerificationError(f"Member checksum mismatch: {name}:{row['member']}") | |
| def output_file(output: Path, row: dict) -> Path: | |
| path = output / row["dataset"] / row["relative_path"] | |
| check_ancestors(path.parent, missing_ok=True) | |
| try: | |
| mode = path.lstat().st_mode | |
| except FileNotFoundError: | |
| return path | |
| if not stat.S_ISREG(mode): | |
| raise VerificationError(f"Existing output is not a regular file: {path}") | |
| actual, length = file_hash(path) | |
| if actual != row["sha256"] or length != row["bytes"]: | |
| raise VerificationError(f"Refusing to overwrite a conflicting output: {path}") | |
| return path | |
| def extract(repo: Path, output: Path, members: dict) -> tuple[int, int]: | |
| # Preflight every destination before any writes; identical files are reusable. | |
| for entries in members.values(): | |
| for row in entries.values(): | |
| output_file(output, row) | |
| extracted = reused = 0 | |
| for name, entries in members.items(): | |
| for row, payload in checked_members(repo, name, entries): | |
| path = output_file(output, row) | |
| if path.exists(): | |
| reused += 1 | |
| # Ensure the second archive traversal still consumes payload safely. | |
| digest, length = hash_stream(payload) | |
| if digest != row["sha256"] or length != row["bytes"]: | |
| raise VerificationError(f"Archive changed after verification: {name}:{row['member']}") | |
| continue | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| check_ancestors(path.parent) | |
| descriptor, temporary = tempfile.mkstemp(prefix=".mindview-", dir=path.parent) | |
| try: | |
| digest = hashlib.sha256() | |
| length = 0 | |
| with os.fdopen(descriptor, "wb") as target: | |
| while True: | |
| block = payload.read(CHUNK) | |
| if not block: | |
| break | |
| target.write(block) | |
| digest.update(block) | |
| length += len(block) | |
| target.flush() | |
| os.fsync(target.fileno()) | |
| if digest.hexdigest() != row["sha256"] or length != row["bytes"]: | |
| raise VerificationError(f"Archive changed after verification: {name}:{row['member']}") | |
| os.chmod(temporary, 0o644) | |
| # A hard-link install is atomic and refuses to replace an existing path. | |
| try: | |
| os.link(temporary, path, follow_symlinks=False) | |
| except FileExistsError: | |
| output_file(output, row) | |
| reused += 1 | |
| else: | |
| extracted += 1 | |
| finally: | |
| Path(temporary).unlink(missing_ok=True) | |
| return extracted, reused | |
| def main(argv=None) -> int: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--repo", type=Path, default=Path(__file__).resolve().parents[1], help="Complete downloaded dataset repository") | |
| group = parser.add_mutually_exclusive_group(required=True) | |
| group.add_argument("--verify-only", action="store_true", help="Verify all package files and TAR members; write no assets") | |
| group.add_argument("--output", type=Path, help="Extract under OUTPUT/<source-dataset>/") | |
| args = parser.parse_args(argv) | |
| repo = Path(os.path.abspath(args.repo)) | |
| check_ancestors(repo) | |
| checks = checksum_inventory(repo) | |
| archives, members = read_manifest(repo, checks) | |
| verify_members(repo, members) | |
| result = {"status": "pass", "checksum_files": len(checks), "archives": len(archives), "assets": sum(map(len, members.values())), "mode": "verify-only"} | |
| if args.output is not None: | |
| output = Path(os.path.abspath(args.output)) | |
| check_ancestors(output, missing_ok=True) | |
| if output == repo or repo in output.parents or output in repo.parents: | |
| raise VerificationError("Extraction directory and package directory must not contain one another") | |
| created, reused = extract(repo, output, members) | |
| result.update(mode="verified-extraction", extracted=created, reused=reused) | |
| print(json.dumps(result, indent=2)) | |
| return 0 | |
| if __name__ == "__main__": | |
| try: | |
| raise SystemExit(main()) | |
| except (VerificationError, OSError, ValueError, tarfile.TarError) as exc: | |
| print(f"ERROR: {exc}", file=sys.stderr) | |
| raise SystemExit(1) | |