STAR-future commited on
Commit
709409d
·
verified ·
1 Parent(s): 7e7c4d7

add Colab worker for PubChem/PDB

Browse files
Files changed (1) hide show
  1. tools/colab_scidata_worker.py +135 -0
tools/colab_scidata_worker.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Colab worker: mirror the two largest free-egress sources into STAR-future/LittleBoy-SciData, in batches.
2
+
3
+ Run inside Colab (free egress), after `HF_TOKEN` is available as `TOK`:
4
+ exec(open(hf_hub_download('STAR-future/LittleBoy-SciData', 'tools/colab_scidata_worker.py', repo_type='dataset', token=TOK)).read())
5
+
6
+ * PubChem Compound SDF (~350 *.sdf.gz): downloaded and uploaded in batches of ~BATCH_GB, so the Colab disk never fills.
7
+ * PDB mmCIF (~1,100 two-letter folders, ~240k files): packed into tar shards of ~BATCH_GB (HF does badly with
8
+ hundreds of thousands of small files). Each shard lists its folders in shard index JSON.
9
+ Resumable: everything already on the Hub is skipped. Only redistributable data (CC0 / NCBI public data).
10
+ """
11
+ import json
12
+ import os
13
+ import re
14
+ import shutil
15
+ import subprocess
16
+ import tarfile
17
+ import time
18
+ import urllib.request
19
+ from pathlib import Path
20
+
21
+ from huggingface_hub import HfApi, hf_hub_download
22
+
23
+ REPO = "STAR-future/LittleBoy-SciData"
24
+ WORK = Path("/content/scidata")
25
+ BATCH_GB = float(os.environ.get("SCIDATA_BATCH_GB", "25"))
26
+ PUBCHEM = "https://ftp.ncbi.nlm.nih.gov/pubchem/Compound/CURRENT-Full/SDF/"
27
+ PDB = "https://files.wwpdb.org/pub/pdb/data/structures/divided/mmCIF/"
28
+ api = HfApi(token=TOK) # noqa: F821 (TOK is defined by the Colab cell)
29
+
30
+
31
+ def say(*a):
32
+ print(time.strftime("%H:%M:%S"), *a, flush=True)
33
+
34
+
35
+ def listing(url, pat):
36
+ html = urllib.request.urlopen(url, timeout=120).read().decode("utf-8", "replace")
37
+ return sorted(set(re.findall(pat, html)))
38
+
39
+
40
+ def on_hub(prefix):
41
+ try:
42
+ return {f.rsplit("/", 1)[-1] for f in api.list_repo_files(REPO, repo_type="dataset") if f.startswith(prefix)}
43
+ except Exception as e: # noqa: BLE001
44
+ say("list failed", e)
45
+ return set()
46
+
47
+
48
+ def upload(folder, path_in_repo, msg):
49
+ for k in range(5):
50
+ try:
51
+ api.upload_folder(repo_id=REPO, repo_type="dataset", folder_path=str(folder), path_in_repo=path_in_repo,
52
+ commit_message=msg)
53
+ return
54
+ except Exception as e: # noqa: BLE001
55
+ say("upload retry", k, e)
56
+ time.sleep(60 * (k + 1))
57
+ raise SystemExit("upload failed 5 times: " + msg)
58
+
59
+
60
+ def free_gb():
61
+ return shutil.disk_usage("/content").free / 1e9
62
+
63
+
64
+ def pubchem():
65
+ name = "chemistry/pubchem_compound_sdf"
66
+ files = listing(PUBCHEM, r'href="(Compound_[0-9_]+\.sdf\.gz(?:\.md5)?)"') + ["README-Compound-SDF"]
67
+ have = on_hub(name + "/")
68
+ todo = [f for f in files if f not in have]
69
+ say("pubchem", len(files), "files,", len(todo), "to do, free disk", round(free_gb()), "GB")
70
+ d = WORK / "pubchem"
71
+ while todo:
72
+ shutil.rmtree(d, ignore_errors=True)
73
+ d.mkdir(parents=True)
74
+ size = 0
75
+ while todo and size < BATCH_GB * 1e9:
76
+ f = todo.pop(0)
77
+ r = subprocess.run(["wget", "-q", "-O", str(d / f), PUBCHEM + f])
78
+ if r.returncode:
79
+ (d / f).unlink(missing_ok=True)
80
+ say("skip (wget)", f, r.returncode)
81
+ continue
82
+ size += (d / f).stat().st_size
83
+ (d / "SOURCE.json").write_text(json.dumps({"name": name, "licence": "PubChem / NCBI public data; see NCBI "
84
+ "data-usage policy", "url": PUBCHEM,
85
+ "fetched_at_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}))
86
+ upload(d, name, f"add {name} batch ({size / 1e9:.1f} GB)")
87
+ say("pubchem batch up", round(size / 1e9, 1), "GB,", len(todo), "left")
88
+ shutil.rmtree(d, ignore_errors=True)
89
+
90
+
91
+ def pdb():
92
+ name = "biology/pdb_mmcif"
93
+ dirs = listing(PDB, r'href="([0-9a-z]{2})/"')
94
+ have = on_hub(name + "/")
95
+ done = set()
96
+ idx = sorted(f for f in have if f.startswith("index_") and f.endswith(".json"))
97
+ for f in idx:
98
+ p = hf_hub_download(REPO, f"{name}/{f}", repo_type="dataset", token=TOK) # noqa: F821
99
+ done |= set(json.loads(Path(p).read_text())["dirs"])
100
+ todo = [x for x in dirs if x not in done]
101
+ say("pdb", len(dirs), "dirs,", len(todo), "to do")
102
+ k = len(idx)
103
+ while todo:
104
+ stage = WORK / "pdb_stage"
105
+ out = WORK / "pdb_out"
106
+ for p in (stage, out):
107
+ shutil.rmtree(p, ignore_errors=True)
108
+ p.mkdir(parents=True)
109
+ group, size = [], 0
110
+ while todo and size < BATCH_GB * 1e9:
111
+ x = todo.pop(0)
112
+ subprocess.run(["wget", "-q", "-r", "-np", "-nH", "--cut-dirs=6", "-e", "robots=off", "-R", "index.html*",
113
+ "-P", str(stage), PDB + x + "/"])
114
+ group.append(x)
115
+ size = sum(p.stat().st_size for p in stage.rglob("*") if p.is_file())
116
+ tag = f"{k:04d}"
117
+ with tarfile.open(out / f"pdb_mmcif_{tag}.tar", "w") as t:
118
+ t.add(stage, arcname="mmCIF")
119
+ (out / f"index_{tag}.json").write_text(json.dumps({"dirs": group, "bytes": size,
120
+ "files": sum(1 for p in stage.rglob("*") if p.is_file())}))
121
+ if k == 0:
122
+ (out / "SOURCE.json").write_text(json.dumps({"name": name, "licence": "CC0 1.0 (wwPDB)", "url": PDB,
123
+ "layout": "tar shards of the divided mmCIF tree; index_NNNN.json "
124
+ "lists the two-letter folders in each shard"}))
125
+ shutil.rmtree(stage)
126
+ upload(out, name, f"add {name} shard {tag}")
127
+ say("pdb shard", tag, round(size / 1e9, 1), "GB,", len(todo), "dirs left")
128
+ k += 1
129
+
130
+
131
+ WORK.mkdir(parents=True, exist_ok=True)
132
+ say("scidata worker start, free disk", round(free_gb()), "GB, batch", BATCH_GB, "GB")
133
+ pubchem()
134
+ pdb()
135
+ say("SCIDATA_DONE")