File size: 5,910 Bytes
6da4e64 | 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 | """Fetch a bounded CC-BY-4.0 object-capture sample for local development.
Image sequence from a controlled plant turntable, NOT a handheld room video or
an independent leaderboard result. Does not download camera/depth annotations.
"""
import argparse
from concurrent.futures import ThreadPoolExecutor
import hashlib
import json
import time
from pathlib import Path
from urllib.parse import quote
from urllib.request import getproxies
import requests
REPO = "SimeonOA/Botany-Bot"
REVISION = "e0f1b57b89f8deb4dfee22c99c227798f9c7c541"
BASE = f"https://huggingface.co/datasets/{REPO}/resolve/{REVISION}/"
def verify_content(entry, content):
if len(content) != entry["size"] or len(content) > 10_000_000:
raise ValueError(f"Size mismatch: {entry['path']}")
lfs = entry.get("lfs")
actual = hashlib.sha256(content).hexdigest() if lfs else hashlib.sha1(f"blob {len(content)}\0".encode()+content).hexdigest()
expected = lfs["oid"] if lfs else entry["oid"]
if actual != expected:
raise ValueError(f"Publisher object hash mismatch: {entry['path']}")
def download_once(entry, destination):
path = entry["path"]
url = BASE+quote(path)
if destination.exists():
content = destination.read_bytes()
verify_content(entry, content)
return {"source_path": path, "url": url, "file": destination.name,
"bytes": len(content), "sha256": hashlib.sha256(content).hexdigest(), "reused_verified": True}
response = requests.get(url, timeout=(15, 45), proxies=getproxies(), stream=True)
response.raise_for_status()
blocks, count = [], 0
for block in response.iter_content(256*1024):
count += len(block)
if count > min(entry["size"], 10_000_000):
response.close()
raise ValueError(f"Download exceeds declared size: {path}")
blocks.append(block)
content = b"".join(blocks)
verify_content(entry, content)
with destination.open("xb") as stream:
stream.write(content)
return {"source_path": path, "url": url, "file": destination.name,
"bytes": len(content), "sha256": hashlib.sha256(content).hexdigest()}
def download(entry, destination):
for attempt in range(3):
try:
return download_once(entry, destination)
except requests.RequestException:
if attempt == 2:
raise
time.sleep(attempt+1)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("output", type=Path)
parser.add_argument("--resume", action="store_true")
args = parser.parse_args()
response = requests.get(f"https://huggingface.co/api/datasets/{REPO}/tree/{REVISION}/alocasia/images_2", timeout=30, proxies=getproxies())
response.raise_for_status()
if response.links.get("next"):
raise RuntimeError("Unexpected pagination; refusing incomplete sample selection")
files = sorted([e for e in response.json() if e["type"] == "file" and e["path"].lower().endswith((".jpg", ".png", ".jpeg"))], key=lambda e: e["path"])
if len(files) < 48:
raise ValueError("Insufficient images for the predeclared 48-frame sample")
selected = [files[round(i*(len(files)-1)/47)] for i in range(48)]
if sum(e["size"] for e in selected) > 128_000_000:
raise ValueError("Sample exceeds 128 MB budget")
if args.resume:
previous = json.loads((args.output/"manifest.json").read_text(encoding="utf-8"))
if previous.get("repository") != REPO or previous.get("revision") != REVISION:
raise ValueError("Refusing resume of unrelated output")
(args.output/f"manifest-before-resume-{time.time_ns()}.json").write_text(json.dumps(previous, indent=2), encoding="utf-8")
else:
args.output.mkdir(parents=True, exist_ok=False)
images = args.output/"images"
images.mkdir(exist_ok=args.resume)
readme_path = args.output/"SOURCE_README.md"
if readme_path.exists():
readme_text = readme_path.read_text(encoding="utf-8")
else:
readme = requests.get(BASE+"README.md", timeout=30, proxies=getproxies())
readme.raise_for_status()
readme_text = readme.text
readme_bytes = readme_text.encode("utf-8")
readme_oid = hashlib.sha1(f"blob {len(readme_bytes)}\0".encode()+readme_bytes).hexdigest()
if readme_oid != "872d4fa794b1b599d3357fb4dd982330bd3b14b3":
raise ValueError("Dataset card does not match inspected publisher Git object")
if "license: cc-by-4.0" not in readme_text.lower():
raise ValueError("Pinned dataset card does not declare the expected license")
if not readme_path.exists():
readme_path.write_text(readme_text, encoding="utf-8")
report = {"status": "downloading", "repository": REPO, "revision": REVISION,
"license": "CC-BY-4.0", "attribution": "Adebola et al., Botany-Bot, IROS 2025; dataset card retained",
"selection": "48 evenly indexed alocasia/images_2 frames, selected before evaluation",
"scope": "Controlled turntable image sequence, not handheld video generalization",
"camera_or_depth_annotations_used": False, "files": []}
try:
def fetch(pair):
index, entry = pair
return download(entry, images/f"frame-{index:04d}{Path(entry['path']).suffix.lower()}")
with ThreadPoolExecutor(max_workers=2) as executor:
for record in executor.map(fetch, enumerate(selected)):
report["files"].append(record)
print(f"Verified {len(report['files'])}/48", flush=True)
report["status"] = "completed"
except Exception as error:
report.update(status="failed", error=f"{type(error).__name__}: {error}")
raise
finally:
(args.output/"manifest.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
if __name__ == "__main__":
main()
|