"""Mirror large open scientific datasets into STAR-future/Trinity-SciData, one source at a time: download to local disk, upload with upload_large_folder (resumable), delete, next. Runs on a cloud VM (HF_TOKEN_FILE = a 600 file). Only sources whose licence allows redistribution; each folder gets a SOURCE.json with URL, licence and fetch time. python mirror_scidata.py --work /data [--only name] """ import argparse import json import os import shutil import subprocess import sys import tarfile import time import urllib.parse import urllib.request import xml.etree.ElementTree as ET from pathlib import Path from huggingface_hub import HfApi REPO = "STAR-future/Trinity-SciData" SOURCES = [ {"name": "space/naif_generic_kernels", "licence": "NASA/JPL NAIF public data (US Government work)", "url": "https://naif.jpl.nasa.gov/pub/naif/generic_kernels/", "cmd": ["wget", "-q", "-r", "-np", "-nH", "--cut-dirs=3", "-e", "robots=off", "-R", "index.html*", "https://naif.jpl.nasa.gov/pub/naif/generic_kernels/"]}, {"name": "space/omni", "licence": "NASA SPDF public data (US Government work); cite OMNIWeb", "url": "https://spdf.gsfc.nasa.gov/pub/data/omni/", "cmd": ["wget", "-q", "-r", "-np", "-nH", "--cut-dirs=4", "-e", "robots=off", "-R", "index.html*", "https://spdf.gsfc.nasa.gov/pub/data/omni/low_res_omni/", "https://spdf.gsfc.nasa.gov/pub/data/omni/high_res_omni/"]}, {"name": "chemistry/chembl", "licence": "CC BY-SA 3.0 (EMBL-EBI ChEMBL)", "url": "https://ftp.ebi.ac.uk/pub/databases/chembl/ChEMBLdb/latest/", "cmd": ["wget", "-q", "-r", "-np", "-nH", "--cut-dirs=5", "-e", "robots=off", "-R", "index.html*", "-A", "*sqlite.tar.gz,*.sdf.gz,*.fa.gz,*.txt,LICENSE*,REQUIRED*,README*,*.md5", "https://ftp.ebi.ac.uk/pub/databases/chembl/ChEMBLdb/latest/"]}, {"name": "energy/nrel_pvdaq_parquet", "licence": "CC BY 4.0 (NREL Open Energy Data Initiative, PVDAQ); cite PVDAQ", "url": "s3://oedi-data-lake/pvdaq/parquet/", "cmd": [sys.executable, os.path.abspath(__file__), "--s3", "oedi-data-lake", "pvdaq/parquet/"]}, {"name": "chips/skywater_sky130_pdk", "licence": "Apache-2.0 (Google / SkyWater SKY130 open PDK)", "url": "https://github.com/google/skywater-pdk", "cmd": ["bash", "-c", "find . -mindepth 1 -delete; git clone -q --depth 1 https://github.com/google/skywater-pdk . && " "git submodule update -q --init --depth 1 libraries/sky130_fd_sc_hd/latest libraries/sky130_fd_sc_hs/latest " "libraries/sky130_fd_pr/latest libraries/sky130_fd_io/latest && " "find . -name .git -prune -exec rm -rf {} +"]}, {"name": "chips/openroad_flow_scripts", "licence": "BSD-3-Clause (OpenROAD-flow-scripts); platform and design " "folders keep their own LICENSE files", "url": "https://github.com/The-OpenROAD-Project/OpenROAD-flow-scripts", "cmd": ["bash", "-c", "find . -mindepth 1 -delete; git clone -q --depth 1 https://github.com/The-OpenROAD-Project/OpenROAD-flow-scripts . && " "find . -name .git -prune -exec rm -rf {} +"]}, {"name": "chips/ihp_sg13g2_open_pdk", "licence": "Apache-2.0 (IHP Open PDK, SG13G2 130 nm SiGe BiCMOS)", "url": "https://github.com/IHP-GmbH/IHP-Open-PDK", "cmd": ["bash", "-c", "find . -mindepth 1 -delete; git clone -q --depth 1 https://github.com/IHP-GmbH/IHP-Open-PDK . && " "find . -name .git -prune -exec rm -rf {} +"]}, {"name": "chips/gf180mcu_pdk", "licence": "Apache-2.0 (Google / GlobalFoundries GF180MCU open PDK)", "url": "https://github.com/google/gf180mcu-pdk", "cmd": ["bash", "-c", "find . -mindepth 1 -delete; git clone -q --depth 1 https://github.com/google/gf180mcu-pdk . && " "find . -name .git -prune -exec rm -rf {} +"]}, {"name": "chips/yosys", "licence": "ISC (YosysHQ Yosys open synthesis suite)", "url": "https://github.com/YosysHQ/yosys", "cmd": ["bash", "-c", "find . -mindepth 1 -delete; git clone -q --depth 1 https://github.com/YosysHQ/yosys . && " "find . -name .git -prune -exec rm -rf {} +"]}, {"name": "chips/openroad", "licence": "BSD-3-Clause (The OpenROAD Project); bundled test data keeps its own LICENSE files", "url": "https://github.com/The-OpenROAD-Project/OpenROAD", "cmd": ["bash", "-c", "find . -mindepth 1 -delete; git clone -q --depth 1 https://github.com/The-OpenROAD-Project/OpenROAD . && " "find . -name .git -prune -exec rm -rf {} +"]}, ] FREE_EGRESS_SOURCES = [ # the largest sources: run them where egress is free (Colab/Kaggle), --set free # rsync works from Colab: 263,157 files, 93.56 GB, fetched 2026-11-20 10:31 UTC, on the Hub at 10:50. If port 33444 is # ever blocked, the RCSB snapshot on AWS Open Data is an anonymous-HTTPS alternative (older, yearly): # [sys.executable, __file__, "--s3", "pdbsnapshots", "20260101/pub/pdb/data/structures/divided/mmCIF/"] {"name": "biology/pdb_mmcif", "licence": "CC0 1.0 (wwPDB)", "url": "rsync.rcsb.org::ftp_data/structures/divided/mmCIF/", "cmd": ["rsync", "-rlpt", "-q", "--port=33444", "rsync.rcsb.org::ftp_data/structures/divided/mmCIF/", "."]}, {"name": "chemistry/pubchem_compound_sdf", "licence": "PubChem / NCBI public data; see NCBI data-usage policy", "url": "https://ftp.ncbi.nlm.nih.gov/pubchem/Compound/CURRENT-Full/SDF/", "cmd": ["wget", "-q", "-r", "-np", "-nH", "--cut-dirs=4", "-e", "robots=off", "-A", "*.sdf.gz,*.md5,README*", "https://ftp.ncbi.nlm.nih.gov/pubchem/Compound/CURRENT-Full/SDF/"]}, ] PACK_ABOVE_FILES = 5000 # the Hub handles hundreds of thousands of small files badly: pack them in tar shards SHARD_BYTES = 5 * 10 ** 9 def tree(d: Path) -> list: """Regular files and symbolic links under d, without following links (a git checkout of a PDK has symlinks, some to files that packing removes first, some dangling: following them crashed the mirror on 2026-11-19).""" out = [] for root, dirs, files in os.walk(d, followlinks=False): for name in files + [x for x in dirs if os.path.islink(os.path.join(root, x))]: p = Path(root) / name if p.is_symlink() or p.is_file(): out.append(p) return sorted(out) def nbytes(p: Path) -> int: return 0 if p.is_symlink() else p.lstat().st_size def pack(d: Path) -> None: """Replace the tree under d by tar shards of ~SHARD_BYTES plus MANIFEST.jsonl (path, bytes, shard[, symlink]).""" files = [p for p in tree(d) if p.name != "SOURCE.json"] out = d / "_packed" out.mkdir() k, cur, tf = 0, 0, None with open(out / "MANIFEST.jsonl", "w") as man: for p in files: if tf is None or cur >= SHARD_BYTES: if tf: tf.close() tf, cur = tarfile.open(out / f"part_{k:05d}.tar", "w"), 0 k += 1 rel = p.relative_to(d).as_posix() size = nbytes(p) tf.add(p, arcname=rel, recursive=False) # a symlink is stored as a symlink (lstat) cur += size row = {"path": rel, "bytes": size, "shard": f"part_{k - 1:05d}.tar"} if p.is_symlink(): row["symlink"] = os.readlink(p) else: # Exact POSIX tar payload offset (verified bit-exact across PAX headers & 512B boundaries, CC-27) row["offset_data"] = tf.offset - ((size + 511) // 512) * 512 man.write(json.dumps(row) + "\n") p.unlink() if tf: tf.close() for q in sorted((q for q in d.iterdir() if q.is_dir() and q.name != "_packed"), reverse=True): shutil.rmtree(q) for q in out.iterdir(): q.rename(d / q.name) out.rmdir() def s3_fetch(bucket: str, prefix: str, workers: int = 32) -> int: """Download every object under s3://bucket/prefix into the current directory over anonymous HTTPS (no awscli). Returns the number of failed objects (0 = complete).""" from concurrent.futures import ThreadPoolExecutor keys, tok = [], None while True: q = {"list-type": "2", "prefix": prefix} | ({"continuation-token": tok} if tok else {}) x = urllib.request.urlopen(f"https://{bucket}.s3.amazonaws.com/?" + urllib.parse.urlencode(q), timeout=120).read() root = ET.fromstring(x) ns = {"s": root.tag.split("}")[0].strip("{")} keys += [c.find("s:Key", ns).text for c in root.findall("s:Contents", ns)] t = root.find("s:NextContinuationToken", ns) if t is None: break tok = t.text def one(key): rel = Path(key[len(prefix):]) if not key.endswith("/") and not rel.exists(): rel.parent.mkdir(parents=True, exist_ok=True) for k in range(3): try: with urllib.request.urlopen(f"https://{bucket}.s3.amazonaws.com/{urllib.parse.quote(key)}", timeout=300) as r, open(str(rel) + ".part", "wb") as fo: shutil.copyfileobj(r, fo, 1 << 20) os.replace(str(rel) + ".part", rel) return 0 except Exception: # noqa: BLE001 time.sleep(5 * (k + 1)) return 1 return 0 with ThreadPoolExecutor(workers) as ex: bad = sum(ex.map(one, keys)) print("s3", bucket, prefix, len(keys), "objects,", bad, "failed", flush=True) return bad def main(): if len(sys.argv) == 4 and sys.argv[1] == "--s3": raise SystemExit(1 if s3_fetch(sys.argv[2], sys.argv[3]) else 0) ap = argparse.ArgumentParser() ap.add_argument("--work", required=True) ap.add_argument("--only", default="") ap.add_argument("--set", default="cloud", choices=["cloud", "free", "all"]) a = ap.parse_args() api = HfApi(token=Path(os.environ["HF_TOKEN_FILE"]).read_text().strip()) api.create_repo(REPO, repo_type="dataset", private=False, exist_ok=True) api.update_repo_settings(REPO, repo_type="dataset", gated="manual") log = Path(a.work) / "mirror_progress.jsonl" done = {json.loads(ln)["name"] for ln in log.read_text().splitlines()} if log.exists() else set() on_hub = {f.rsplit("/", 1)[0] for f in api.list_repo_files(REPO, repo_type="dataset") if f.endswith("/SOURCE.json")} for s in (SOURCES if a.set == "cloud" else FREE_EGRESS_SOURCES if a.set == "free" else SOURCES + FREE_EGRESS_SOURCES): if s["name"] in done or s["name"] in on_hub or (a.only and a.only != s["name"]): continue d = Path(a.work) / "stage" / s["name"] if (d / "_packed").exists(): # a pack interrupted half-way (2026-11-20: FileExistsError loop): start over print("stale _packed in", s["name"], ": refetching", flush=True) shutil.rmtree(d) d.mkdir(parents=True, exist_ok=True) t0 = time.time() prev = d / "SOURCE.json" if prev.exists() and json.loads(prev.read_text()).get("fetch_exit") == 0: r = subprocess.CompletedProcess(s["cmd"], 0) # already fetched (resume after an upload failure) prev.unlink() else: r = subprocess.run(s["cmd"], cwd=d) listing = tree(d) n = len(listing) size = sum(nbytes(p) for p in listing) if n == 0: # nothing fetched: never upload a stub, never mark the source as done print("FAILED", s["name"], "exit", r.returncode, "no files", flush=True) continue (d / "SOURCE.json").write_text(json.dumps({k: s[k] for k in ("name", "licence", "url")} | {"fetched_at_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "fetch_exit": r.returncode, "files": n, "bytes": size}, indent=1)) print("fetched", s["name"], n, size, "exit", r.returncode, flush=True) if n > PACK_ABOVE_FILES: pack(d) print("packed", s["name"], flush=True) if hasattr(api, "upload_large_folder"): api.upload_large_folder(repo_id=REPO, repo_type="dataset", folder_path=str(Path(a.work) / "stage"), allow_patterns=[s["name"] + "/**"], num_workers=4) else: # old huggingface_hub on the VM image api.upload_folder(repo_id=REPO, repo_type="dataset", folder_path=str(d), path_in_repo=s["name"], commit_message=f"add {s['name']}") shutil.rmtree(d) with open(log, "a") as fo: fo.write(json.dumps({"name": s["name"], "files": n, "bytes": size, "fetch_exit": r.returncode, "seconds": round(time.time() - t0)}) + "\n") print("uploaded", s["name"], flush=True) if __name__ == "__main__": main()