BrickForma-DataSet / scripts /download_from_hf.py
VergilLLLL's picture
scripts: downloader supports --group models|piano|eval
fd268ca verified
Raw History Blame Contribute Delete
4.05 kB
#!/usr/bin/env python3
"""Download the BrickForma dataset archives from Hugging Face and verify every SHA-256.
Examples
--------
pip install huggingface_hub
python scripts/download_from_hf.py --group models --output brickforma80k
python scripts/download_from_hf.py --group models --shard A --output brickforma80k --extract-metadata
python scripts/download_from_hf.py --group piano --output brickforma80k
python scripts/download_from_hf.py --group eval --output brickforma80k
python scripts/download_from_hf.py --group all --output brickforma80k
The repository is private, so log in first (`huggingface-cli login`) or pass --token, or
set the HF_TOKEN environment variable.
"""
import argparse
import hashlib
import json
import os
import sys
import zipfile
from pathlib import Path
from huggingface_hub import hf_hub_download
REPO_ID = "VergilLLLL/BrickForma-DataSet"
MANIFEST_IN_REPO = "checksums/SHA256_MANIFEST.json"
GROUPS = {"models": ("data/AI_A/", "data/AI_B/"),
"piano": ("data/piano_B_supported_1905/",),
"eval": ("evaluation/",)}
def sha256(path):
digest = hashlib.sha256()
with open(path, "rb") as handle:
for chunk in iter(lambda: handle.read(1 << 20), b""):
digest.update(chunk)
return digest.hexdigest()
def selected(entry, group, shard):
path = entry["path"]
if group == "all":
return True
if not path.startswith(GROUPS[group]):
return False
if group == "models" and shard != "all":
return path.startswith(f"data/AI_{shard}/")
return True
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--output", type=Path, default=Path("brickforma80k"))
parser.add_argument("--group", choices=("models", "piano", "eval", "all"), default="models")
parser.add_argument("--shard", choices=("all", "A", "B"), default="all")
parser.add_argument("--extract-metadata", action="store_true", help="unzip the metadata archives")
parser.add_argument("--token", default=os.environ.get("HF_TOKEN"))
parser.add_argument("--revision", default=None)
args = parser.parse_args()
args.output.mkdir(parents=True, exist_ok=True)
manifest_path = Path(hf_hub_download(REPO_ID, MANIFEST_IN_REPO, repo_type="dataset", token=args.token,
revision=args.revision, local_dir=str(args.output)))
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
wanted = [entry for entry in manifest["files"] if selected(entry, args.group, args.shard)]
total = sum(entry["bytes"] for entry in wanted)
print(f"{len(wanted)} archives, {total / 1e9:.2f} GB, group={args.group}, from {REPO_ID}")
for index, entry in enumerate(wanted, 1):
target = Path(hf_hub_download(REPO_ID, entry["path"], repo_type="dataset", token=args.token,
revision=args.revision, local_dir=str(args.output)))
size = target.stat().st_size
if size != entry["bytes"]:
sys.exit(f"size mismatch for {entry['path']}: {size} != {entry['bytes']}")
if sha256(target) != entry["sha256"]:
sys.exit(f"sha256 mismatch for {entry['path']}")
print(f"[{index}/{len(wanted)}] verified {entry['path']} ({size / 1e6:.0f} MB)")
if args.extract_metadata:
for archive in ("data/AI_A/metadata.zip", "data/AI_B/B_metadata.zip",
"data/piano_B_supported_1905/piano_B_supported_training_metadata.zip"):
path = args.output / archive
if not path.exists():
continue
destination = args.output / "metadata" / Path(archive).stem
destination.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(path) as bundle:
bundle.extractall(destination)
print(f"extracted {archive} -> {destination}")
print("all archives verified")
if __name__ == "__main__":
main()