Download faisi/src/data_engine/fetch_sources.py from ppJustin/micro: direct link, hf CLI and curl.
- Browser
- Download file 7.14 kB
-
https://huggingface.co/datasets/ppJustin/micro/resolve/main/faisi/src/data_engine/fetch_sources.py
- Command line
-
hf download hf://datasets/ppJustin/micro/faisi/src/data_engine/fetch_sources.py
-
curl -L -o fetch_sources.py https://huggingface.co/datasets/ppJustin/micro/resolve/main/faisi/src/data_engine/fetch_sources.py
7.14 kB
| """Fetch pinned public sources, verify publisher checksums and unpack datapacks.""" | |
| import argparse | |
| import hashlib | |
| import json | |
| import os | |
| from pathlib import Path, PurePosixPath | |
| import shutil | |
| import stat | |
| import tarfile | |
| import tempfile | |
| import zipfile | |
| from huggingface_hub import HfApi, snapshot_download | |
| HF_SOURCES = { | |
| "openrca_v1": ("cdreetz/OpenRCA", "7a29a7c3600cc07b7760a6c5097d36ac8573f039"), | |
| "openrca_v2": ("anon-ops/ops-lite", "9ac09981c08ab02a0b923eab7830d778934851a8"), | |
| "propagation_bench": ("PolarBear2026/RCABench", "d107acb13481c5c72e4001c81f3ce5ed378e3410"), | |
| } | |
| ZENODO_MD5 = { | |
| "rcabench-absolute_anomaly.tar.gz": "96d32ae290e06be7d4e251be02b36cb8", | |
| "rcabench-fse-26.zip": "51b80c5d7b79c67e531c2639ec43412f", | |
| "rcabench-platform-feat-fse26.zip": "b363d3a0fff3a1047c907648afbe8575", | |
| } | |
| V1_FILES = ("*.csv", "*.xlsx") | |
| def file_digest(path, algorithm, prefix=b""): | |
| digest = hashlib.new(algorithm) | |
| digest.update(prefix) | |
| with path.open("rb") as handle: | |
| while block := handle.read(8 * 1024 * 1024): | |
| digest.update(block) | |
| return digest.hexdigest() | |
| def safe_path(root, name): | |
| path = PurePosixPath(name) | |
| if path.is_absolute() or ".." in path.parts or "\\" in name: | |
| raise ValueError(f"Invalid archive path: {name}") | |
| return root.joinpath(*path.parts) | |
| def extract(archive, destination): | |
| if destination.is_dir(): | |
| return sum(p.is_file() for p in destination.rglob("*")) | |
| with tempfile.TemporaryDirectory(dir=destination.parent, prefix=".extract-") as tmp: | |
| staging = Path(tmp) / "data" | |
| staging.mkdir() | |
| count = 0 | |
| if archive.suffix == ".zip": | |
| with zipfile.ZipFile(archive) as zipped: | |
| for info in zipped.infolist(): | |
| path = safe_path(staging, info.filename) | |
| kind = stat.S_IFMT(info.external_attr >> 16) | |
| if info.is_dir(): | |
| path.mkdir(parents=True, exist_ok=True) | |
| elif kind in (0, stat.S_IFREG): | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| with zipped.open(info) as src, path.open("xb") as dst: | |
| shutil.copyfileobj(src, dst) | |
| count += 1 | |
| else: | |
| raise ValueError(f"Unsupported ZIP entry: {info.filename}") | |
| else: | |
| with tarfile.open(archive, mode="r|gz") as tar: | |
| for info in tar: | |
| path = safe_path(staging, info.name) | |
| if info.isdir(): | |
| path.mkdir(parents=True, exist_ok=True) | |
| elif info.isfile(): | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| with tar.extractfile(info) as src, path.open("xb") as dst: | |
| shutil.copyfileobj(src, dst, 1024 * 1024) | |
| count += 1 | |
| else: | |
| raise ValueError(f"Unsupported TAR entry: {info.name}") | |
| staging.rename(destination) | |
| return count | |
| def verify_hub(directory, dataset, metadata=None): | |
| repo, revision = HF_SOURCES[dataset] | |
| if metadata: | |
| data = json.loads(Path(metadata).read_text()) | |
| if data["id"] != repo or data["sha"] != revision: | |
| raise ValueError("Metadata does not match pinned source") | |
| entries = [(x["rfilename"], x.get("size"), x.get("lfs") or {}, x.get("blobId")) | |
| for x in data["siblings"]] | |
| else: | |
| info = HfApi().dataset_info(repo, revision=revision, files_metadata=True) | |
| entries = [(x.rfilename, x.size, {"sha256": x.lfs.sha256} if x.lfs else {}, x.blob_id) | |
| for x in info.siblings] | |
| count = size = 0 | |
| for name, expected_size, lfs, blob in entries: | |
| if dataset == "openrca_v1" and not name.endswith((".csv", ".xlsx")): | |
| continue | |
| path = safe_path(directory, name) | |
| if not path.is_file() or path.stat().st_size != expected_size: | |
| raise ValueError(f"Missing file or size mismatch: {name}") | |
| algorithm = "sha256" if lfs else "sha1" | |
| expected = lfs.get("sha256", blob) | |
| prefix = b"" if lfs else f"blob {expected_size}\0".encode() | |
| if file_digest(path, algorithm, prefix) != expected: | |
| raise ValueError(f"Integrity check failed: {name}") | |
| count += 1 | |
| size += expected_size | |
| return {"repo": repo, "revision": revision, "verified_files": count, "verified_bytes": size} | |
| def verify_propagation(directory): | |
| files = {} | |
| for name, checksum in ZENODO_MD5.items(): | |
| archive = directory / "archives" / name | |
| if file_digest(archive, "md5") != checksum: | |
| raise ValueError(f"Zenodo MD5 mismatch for {name}") | |
| destination = "datapacks" if name.endswith(".tar.gz") else archive.stem | |
| files[name] = { | |
| "md5": checksum, | |
| "bytes": archive.stat().st_size, | |
| "extracted_files": extract(archive, directory / destination), | |
| } | |
| repo, revision = HF_SOURCES["propagation_bench"] | |
| datapacks = directory / "datapacks" | |
| markers = ("injection.json", "env.json", "normal_traces.parquet", "abnormal_traces.parquet") | |
| cases = {entry.parent for name in markers for entry in datapacks.rglob(name)} | |
| invalid = sum((case / ".invalid").is_file() for case in cases) | |
| return {"doi": "10.5281/zenodo.17105974", "mirror": repo, "revision": revision, | |
| "archives": files, "archived_cases": len(cases), | |
| "publisher_marked_invalid_cases": invalid, "eligible_cases": len(cases) - invalid} | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("dataset", choices=HF_SOURCES) | |
| parser.add_argument("--storage-root", type=Path, required=True) | |
| parser.add_argument("--jobs", type=int, default=24) | |
| parser.add_argument("--verify-only", action="store_true") | |
| parser.add_argument("--metadata", type=Path, help="Cached Hub metadata with files_metadata enabled") | |
| args = parser.parse_args() | |
| directory = args.storage_root / "datasets_raw" / args.dataset | |
| directory.mkdir(parents=True, exist_ok=True) | |
| repo, revision = HF_SOURCES[args.dataset] | |
| if not args.verify_only: | |
| archive = args.dataset == "propagation_bench" | |
| patterns = list(ZENODO_MD5) if archive else V1_FILES if args.dataset == "openrca_v1" else None | |
| snapshot_download(repo, repo_type="dataset", revision=revision, max_workers=args.jobs, | |
| local_dir=directory / "archives" if archive else directory, | |
| allow_patterns=patterns) | |
| proof = verify_propagation(directory) if args.dataset == "propagation_bench" else ( | |
| verify_hub(directory, args.dataset, args.metadata) | |
| ) | |
| with tempfile.NamedTemporaryFile(dir=directory, mode="w", delete=False) as handle: | |
| json.dump(proof, handle, indent=2) | |
| handle.write("\n") | |
| os.replace(handle.name, directory / ".verified.json") | |
| print(json.dumps(proof), flush=True) | |
| if __name__ == "__main__": | |
| main() | |