File size: 9,523 Bytes
6e0334f
709409d
 
6e0334f
709409d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e0334f
709409d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15b389d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3eef21b
 
 
 
 
15b389d
 
 
 
 
 
 
 
 
 
3eef21b
 
 
 
15b389d
 
 
 
 
 
 
 
 
 
 
 
709409d
 
 
15b389d
709409d
 
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
"""Colab worker: mirror the two largest free-egress sources into STAR-future/Trinity-SciData, in batches.

Run inside Colab (free egress), after `HF_TOKEN` is available as `TOK`:
    exec(open(hf_hub_download('STAR-future/Trinity-SciData', 'tools/colab_scidata_worker.py', repo_type='dataset', token=TOK)).read())

* PubChem Compound SDF (~350 *.sdf.gz): downloaded and uploaded in batches of ~BATCH_GB, so the Colab disk never fills.
* PDB mmCIF (~1,100 two-letter folders, ~240k files): packed into tar shards of ~BATCH_GB (HF does badly with
  hundreds of thousands of small files). Each shard lists its folders in shard index JSON.
Resumable: everything already on the Hub is skipped. Only redistributable data (CC0 / NCBI public data).
"""
import json
import os
import re
import shutil
import subprocess
import tarfile
import time
import urllib.request
from pathlib import Path

from huggingface_hub import HfApi, hf_hub_download

REPO = "STAR-future/Trinity-SciData"
WORK = Path("/content/scidata")
BATCH_GB = float(os.environ.get("SCIDATA_BATCH_GB", "25"))
PUBCHEM = "https://ftp.ncbi.nlm.nih.gov/pubchem/Compound/CURRENT-Full/SDF/"
PDB = "https://files.wwpdb.org/pub/pdb/data/structures/divided/mmCIF/"
api = HfApi(token=TOK)  # noqa: F821  (TOK is defined by the Colab cell)


def say(*a):
    print(time.strftime("%H:%M:%S"), *a, flush=True)


def listing(url, pat):
    html = urllib.request.urlopen(url, timeout=120).read().decode("utf-8", "replace")
    return sorted(set(re.findall(pat, html)))


def on_hub(prefix):
    try:
        return {f.rsplit("/", 1)[-1] for f in api.list_repo_files(REPO, repo_type="dataset") if f.startswith(prefix)}
    except Exception as e:  # noqa: BLE001
        say("list failed", e)
        return set()


def upload(folder, path_in_repo, msg):
    for k in range(5):
        try:
            api.upload_folder(repo_id=REPO, repo_type="dataset", folder_path=str(folder), path_in_repo=path_in_repo,
                              commit_message=msg)
            return
        except Exception as e:  # noqa: BLE001
            say("upload retry", k, e)
            time.sleep(60 * (k + 1))
    raise SystemExit("upload failed 5 times: " + msg)


def free_gb():
    return shutil.disk_usage("/content").free / 1e9


def pubchem():
    name = "chemistry/pubchem_compound_sdf"
    files = listing(PUBCHEM, r'href="(Compound_[0-9_]+\.sdf\.gz(?:\.md5)?)"') + ["README-Compound-SDF"]
    have = on_hub(name + "/")
    todo = [f for f in files if f not in have]
    say("pubchem", len(files), "files,", len(todo), "to do, free disk", round(free_gb()), "GB")
    d = WORK / "pubchem"
    while todo:
        shutil.rmtree(d, ignore_errors=True)
        d.mkdir(parents=True)
        size = 0
        while todo and size < BATCH_GB * 1e9:
            f = todo.pop(0)
            r = subprocess.run(["wget", "-q", "-O", str(d / f), PUBCHEM + f])
            if r.returncode:
                (d / f).unlink(missing_ok=True)
                say("skip (wget)", f, r.returncode)
                continue
            size += (d / f).stat().st_size
        (d / "SOURCE.json").write_text(json.dumps({"name": name, "licence": "PubChem / NCBI public data; see NCBI "
                                                   "data-usage policy", "url": PUBCHEM,
                                                   "fetched_at_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}))
        upload(d, name, f"add {name} batch ({size / 1e9:.1f} GB)")
        say("pubchem batch up", round(size / 1e9, 1), "GB,", len(todo), "left")
    shutil.rmtree(d, ignore_errors=True)


def pdb():
    name = "biology/pdb_mmcif"
    dirs = listing(PDB, r'href="([0-9a-z]{2})/"')
    have = on_hub(name + "/")
    done = set()
    idx = sorted(f for f in have if f.startswith("index_") and f.endswith(".json"))
    for f in idx:
        p = hf_hub_download(REPO, f"{name}/{f}", repo_type="dataset", token=TOK)  # noqa: F821
        done |= set(json.loads(Path(p).read_text())["dirs"])
    todo = [x for x in dirs if x not in done]
    say("pdb", len(dirs), "dirs,", len(todo), "to do")
    k = len(idx)
    while todo:
        stage = WORK / "pdb_stage"
        out = WORK / "pdb_out"
        for p in (stage, out):
            shutil.rmtree(p, ignore_errors=True)
            p.mkdir(parents=True)
        group, size = [], 0
        while todo and size < BATCH_GB * 1e9:
            x = todo.pop(0)
            subprocess.run(["wget", "-q", "-r", "-np", "-nH", "--cut-dirs=6", "-e", "robots=off", "-R", "index.html*",
                            "-P", str(stage), PDB + x + "/"])
            group.append(x)
            size = sum(p.stat().st_size for p in stage.rglob("*") if p.is_file())
        tag = f"{k:04d}"
        with tarfile.open(out / f"pdb_mmcif_{tag}.tar", "w") as t:
            t.add(stage, arcname="mmCIF")
        (out / f"index_{tag}.json").write_text(json.dumps({"dirs": group, "bytes": size,
                                                           "files": sum(1 for p in stage.rglob("*") if p.is_file())}))
        if k == 0:
            (out / "SOURCE.json").write_text(json.dumps({"name": name, "licence": "CC0 1.0 (wwPDB)", "url": PDB,
                                                         "layout": "tar shards of the divided mmCIF tree; index_NNNN.json "
                                                                   "lists the two-letter folders in each shard"}))
        shutil.rmtree(stage)
        upload(out, name, f"add {name} shard {tag}")
        say("pdb shard", tag, round(size / 1e9, 1), "GB,", len(todo), "dirs left")
        k += 1


TESS = "https://archive.stsci.edu/missions/tess/download_scripts/sector/"


def fetch_all(pairs, d, workers=24):
    """Download (filename, url) pairs into d in parallel; failures are retried 3 times, then skipped and counted."""
    from concurrent.futures import ThreadPoolExecutor

    def one(pair):
        fn, url = pair
        for k in range(3):
            try:
                with urllib.request.urlopen(url, timeout=120) as r, open(d / (fn + ".part"), "wb") as fo:
                    shutil.copyfileobj(r, fo, 1 << 20)
                (d / (fn + ".part")).rename(d / fn)
                return True
            except Exception:  # noqa: BLE001
                time.sleep(5 * (k + 1))
        return False

    with ThreadPoolExecutor(workers) as ex:
        ok = sum(ex.map(one, pairs))
    say("fetched", ok, "of", len(pairs))
    return ok


def tess(first=1, last=200):
    """TESS SPOC 2-min light curves (NASA/MAST, public domain), one sector at a time, packed in ~5 GB tar shards."""
    name = "space/tess_spoc_lightcurves"
    scripts = listing(TESS, r'(tesscurl_sector_(\d+)_lc\.sh)')
    sectors = sorted({int(n) for _, n in scripts if first <= int(n) <= last})
    have = on_hub(name + "/")          # file names only: MANIFEST_sNNNN.jsonl marks a finished sector
    say("tess", len(sectors), "sectors,", sum(f"MANIFEST_s{s:04d}.jsonl" in have for s in sectors), "already on the Hub")
    for s in sectors:
        if f"MANIFEST_s{s:04d}.jsonl" in have:
            continue
        d, out = WORK / "tess_dl", WORK / "tess_out"
        for p in (d, out):
            shutil.rmtree(p, ignore_errors=True)
            p.mkdir(parents=True)
        sh = urllib.request.urlopen(f"{TESS}tesscurl_sector_{s}_lc.sh", timeout=120).read().decode()
        pairs = []
        for ln in sh.splitlines():
            t = ln.split()
            if t and t[0] == "curl" and "-o" in t:
                fn = t[t.index("-o") + 1]
                if re.fullmatch(r"[\w.-]+\.fits", fn):
                    pairs.append((fn, t[-1]))
        ok = fetch_all(pairs, d)
        if ok < 0.98 * len(pairs):     # incomplete sector: never publish a manifest that marks it done
            say("tess sector", s, "INCOMPLETE", ok, "of", len(pairs), "- skipped, will retry on the next run")
            shutil.rmtree(d, ignore_errors=True)
            continue
        files = sorted(p for p in d.iterdir() if p.suffix == ".fits")
        k, cur, tf, rows = 0, 0, None, []
        for p in files:
            if tf is None or cur >= 5e9:
                if tf:
                    tf.close()
                tf, cur = tarfile.open(out / f"s{s:04d}_part_{k:03d}.tar", "w"), 0
                k += 1
            nm = p.name
            tf.add(p, arcname=f"sector_{s:04d}/{nm}")
            sz = p.stat().st_size
            cur += sz
            rows.append({"file": nm, "bytes": sz, "shard": f"s{s:04d}_part_{k - 1:03d}.tar"})
            p.unlink()                 # keep the disk peak at one copy of the sector
        if tf:
            tf.close()
        shutil.rmtree(d)
        (out / f"MANIFEST_s{s:04d}.jsonl").write_text("".join(json.dumps(r) + "\n" for r in rows))
        if s == sectors[0] and "SOURCE.json" not in have:
            (out / "SOURCE.json").write_text(json.dumps({"name": name, "licence": "NASA/MAST public data (US Government "
                                                         "work); acknowledge the TESS mission and MAST", "url": TESS}))
        upload(out, name, f"add {name} sector {s} ({len(rows)} light curves, {sum(r['bytes'] for r in rows) / 1e9:.1f} GB)")
        say("tess sector", s, len(rows), "files", round(sum(r["bytes"] for r in rows) / 1e9, 1), "GB")
    shutil.rmtree(WORK / "tess_out", ignore_errors=True)


WORK.mkdir(parents=True, exist_ok=True)
say("scidata worker start, free disk", round(free_gb()), "GB, batch", BATCH_GB, "GB")
pubchem()
tess()
pdb()
say("SCIDATA_DONE")