Datasets:
feat(data): add biblioteka_nauki source (42,071 docs, per-document license + attribution)
#11
by bartoszkobylinski1 - opened
data/biblioteka_nauki/biblioteka_nauki.md
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# biblioteka_nauki
|
| 2 |
+
|
| 3 |
+
Biblioteka Nauki — Polish open-access scholarly corpus (scientific articles, books, chapters)
|
| 4 |
+
|
| 5 |
+
## Dataset description
|
| 6 |
+
- **Source (upstream):** https://bibliotekanauki.pl (operated by ICM, University of Warsaw — Centrum Otwartej Nauki)
|
| 7 |
+
- **Domain:** academic (scientific articles, books, chapters)
|
| 8 |
+
- **Language:** Polish (pl)
|
| 9 |
+
- **License:** per-document — CC BY 4.0 28,335 · CC BY-SA 4.0 13,733 · Public Domain 3
|
| 10 |
+
- **Created (range):** per-document publication year, from each item's bibliotekanauki.pl metadata
|
| 11 |
+
- **Added:** 2026-06-27
|
| 12 |
+
|
| 13 |
+
## Licensing — traceable basis
|
| 14 |
+
The SpeakLeash blob carries no per-document license field, and ~53% of the upstream collection is
|
| 15 |
+
all-rights-reserved, so a per-item gate was mandatory. Each item's license was recovered from the
|
| 16 |
+
bibliotekanauki.pl API (`bibliotekanauki.pl/api/{type}/<id>` → `license.iconId`). Only openly-licensed
|
| 17 |
+
items are kept; all-rights-reserved and unknown items are gated out. Recovery yielded 43,576 clean ids.
|
| 18 |
+
|
| 19 |
+
| license | documents |
|
| 20 |
+
|---|---:|
|
| 21 |
+
| CC BY 4.0 | 28,335 |
|
| 22 |
+
| CC BY-SA 4.0 | 13,733 |
|
| 23 |
+
| Public Domain | 3 |
|
| 24 |
+
|
| 25 |
+
The per-document license is carried in the parquet `license` column.
|
| 26 |
+
|
| 27 |
+
## Attribution
|
| 28 |
+
Per-document attribution (author · year · title · publisher) was re-fetched 1:1 from
|
| 29 |
+
bibliotekanauki.pl (43,576 / 43,576 ok) and is carried in the parquet `attribution` column,
|
| 30 |
+
satisfying the CC BY / CC BY-SA attribution requirement that applies to every document here.
|
| 31 |
+
|
| 32 |
+
## Provenance
|
| 33 |
+
Pulled from SpeakLeash's public redistribution (`speakleash-ds-pub`, key `biblioteka_nauki_pl_corpus`)
|
| 34 |
+
of the upstream source above. SpeakLeash credited as intermediate aggregator; upstream license and
|
| 35 |
+
attribution recovered per document and preserved.
|
| 36 |
+
|
| 37 |
+
## Statistics
|
| 38 |
+
| documents | characters | tokens (tiktoken proxy) |
|
| 39 |
+
|---:|---:|---:|
|
| 40 |
+
| 42,071 | 1,748,333,935 | 673,488,831 |
|
| 41 |
+
|
| 42 |
+
## Filters applied (build_dynaword.py)
|
| 43 |
+
Minimal, per Dynaword guidelines (heavy filtering left to downstream use):
|
| 44 |
+
- drop documents < 200 chars: **0**
|
| 45 |
+
- drop non-Polish (diacritic ratio): **925**
|
| 46 |
+
- exact cross-source dedup (sha1): **180**
|
| 47 |
+
- OCR alpha-ratio < 0.70 (OCR source): **400**
|
| 48 |
+
- read 43,576 → kept 42,071
|
| 49 |
+
|
| 50 |
+
Token counts are a fast tiktoken (cl100k) proxy (~1% off Llama-3); the canonical
|
| 51 |
+
Llama-3 count is computed at release.
|
| 52 |
+
|
| 53 |
+
## Limitations
|
| 54 |
+
- **Mixed license.** Roughly one third of the documents are CC BY-SA 4.0 (share-alike); the exact
|
| 55 |
+
per-document license is in the `license` column. Downstream redistribution must respect share-alike
|
| 56 |
+
for those documents.
|
| 57 |
+
- **OCR / extraction noise.** Text is extracted from publisher PDFs; some layout and hyphenation
|
| 58 |
+
artefacts remain after the alpha-ratio filter.
|
| 59 |
+
- **Per-document dates.** `created` is the publication year from upstream metadata; finer-grained
|
| 60 |
+
dates are not available.
|
data/biblioteka_nauki/biblioteka_nauki.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cc93cdd5ca3e6576a1da0aa294df1308e879b8516ac30911289e430c69a07b26
|
| 3 |
+
size 1076638904
|
data/biblioteka_nauki/biblioteka_nauki.stats.json
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"read": 43576,
|
| 3 |
+
"kept": 42071,
|
| 4 |
+
"drop_short": 0,
|
| 5 |
+
"drop_lang": 925,
|
| 6 |
+
"drop_dup": 180,
|
| 7 |
+
"drop_ocr": 400,
|
| 8 |
+
"chars": 1748333935,
|
| 9 |
+
"tokens": 673488831,
|
| 10 |
+
"secs": 484.1,
|
| 11 |
+
"license": "CC-BY-4.0 / CC-BY-SA-4.0"
|
| 12 |
+
}
|
data/biblioteka_nauki/recover_attribution.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Targeted attribution pass for the CLEAN (CC-BY/CC-BY-SA/PD) Biblioteka Nauki ids ONLY.
|
| 3 |
+
The first recovery pass stored the license correctly but parsed the wrong attribution fields.
|
| 4 |
+
CC-BY/CC-BY-SA legally REQUIRE attribution, so re-fetch just the ~43.6k clean ids and extract:
|
| 5 |
+
authors = contributors[role=AUTHOR] firstName+lastName ; year = dates[PUBLISHED].date.year ;
|
| 6 |
+
title = mainTitle.text ; publisher = publishingCompanyInfo.name
|
| 7 |
+
|
| 8 |
+
licenses.jsonl -> attribution.jsonl {type,id,license,authors,year,title,publisher}
|
| 9 |
+
Resumable, threaded, polite. ~43.6k calls.
|
| 10 |
+
"""
|
| 11 |
+
import json, os, random, sys, threading, time
|
| 12 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 13 |
+
import requests
|
| 14 |
+
|
| 15 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 16 |
+
LIC = os.path.join(HERE, "licenses.jsonl")
|
| 17 |
+
OUT = os.path.join(HERE, "attribution.jsonl")
|
| 18 |
+
PROG = os.path.join(HERE, "attribution_progress.txt")
|
| 19 |
+
CLEAN = {"cc-by", "cc-by-sa", "cc0", "public-domain"}
|
| 20 |
+
WORKERS = 8
|
| 21 |
+
UA = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
|
| 22 |
+
"(KHTML, like Gecko) Chrome/124 Safari/537.36")
|
| 23 |
+
HEADERS = {"User-Agent": UA, "Accept": "application/json", "Referer": "https://bibliotekanauki.pl/"}
|
| 24 |
+
_local = threading.local()
|
| 25 |
+
_wlock = threading.Lock()
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def session():
|
| 29 |
+
s = getattr(_local, "s", None)
|
| 30 |
+
if s is None:
|
| 31 |
+
s = requests.Session()
|
| 32 |
+
s.headers.update(HEADERS)
|
| 33 |
+
s.mount("https://", requests.adapters.HTTPAdapter(pool_connections=4, pool_maxsize=4))
|
| 34 |
+
_local.s = s
|
| 35 |
+
return s
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def parse(d):
|
| 39 |
+
authors = []
|
| 40 |
+
for c in (d.get("contributors") or []):
|
| 41 |
+
if c.get("role") == "AUTHOR":
|
| 42 |
+
nm = f"{c.get('firstName','') or ''} {c.get('lastName','') or ''}".strip()
|
| 43 |
+
if nm:
|
| 44 |
+
authors.append(nm)
|
| 45 |
+
year = None
|
| 46 |
+
dates = d.get("dates") or []
|
| 47 |
+
for dt in dates:
|
| 48 |
+
if dt.get("type") == "PUBLISHED":
|
| 49 |
+
year = (dt.get("date") or {}).get("year")
|
| 50 |
+
break
|
| 51 |
+
if not year and dates:
|
| 52 |
+
year = (dates[0].get("date") or {}).get("year")
|
| 53 |
+
title = (d.get("mainTitle") or {}).get("text")
|
| 54 |
+
pub = (d.get("publishingCompanyInfo") or {}).get("name")
|
| 55 |
+
return authors[:20], (str(year) if year else None), title, pub
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def fetch(item):
|
| 59 |
+
typ, _id, lic = item
|
| 60 |
+
url = f"https://bibliotekanauki.pl/api/{typ}/{_id}"
|
| 61 |
+
for attempt in range(4):
|
| 62 |
+
try:
|
| 63 |
+
r = session().get(url, timeout=25)
|
| 64 |
+
if r.status_code == 200:
|
| 65 |
+
a, y, t, p = parse(r.json())
|
| 66 |
+
return {"type": typ, "id": _id, "license": lic,
|
| 67 |
+
"authors": a, "year": y, "title": t, "publisher": p, "status": "ok"}
|
| 68 |
+
if r.status_code in (403, 404, 410):
|
| 69 |
+
return {"type": typ, "id": _id, "license": lic, "status": f"http{r.status_code}"}
|
| 70 |
+
time.sleep((2 ** attempt) + random.random())
|
| 71 |
+
except Exception as e:
|
| 72 |
+
if attempt == 3:
|
| 73 |
+
return {"type": typ, "id": _id, "license": lic, "status": f"err:{type(e).__name__}"}
|
| 74 |
+
time.sleep((2 ** attempt) + random.random())
|
| 75 |
+
return {"type": typ, "id": _id, "license": lic, "status": "err:retries"}
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def main():
|
| 79 |
+
best = {}
|
| 80 |
+
for l in open(LIC, encoding="utf-8"):
|
| 81 |
+
try:
|
| 82 |
+
r = json.loads(l)
|
| 83 |
+
except Exception:
|
| 84 |
+
continue
|
| 85 |
+
best[(r["type"], r["id"])] = r
|
| 86 |
+
clean = [(t, i, r["iconId"]) for (t, i), r in best.items()
|
| 87 |
+
if r.get("status") == "ok" and r.get("iconId") in CLEAN]
|
| 88 |
+
done = set()
|
| 89 |
+
if os.path.exists(OUT):
|
| 90 |
+
for l in open(OUT, encoding="utf-8"):
|
| 91 |
+
try:
|
| 92 |
+
r = json.loads(l)
|
| 93 |
+
done.add((r["type"], r["id"]))
|
| 94 |
+
except Exception:
|
| 95 |
+
pass
|
| 96 |
+
todo = [c for c in clean if (c[0], c[1]) not in done]
|
| 97 |
+
print(f"clean={len(clean)} done={len(done)} todo={len(todo)} workers={WORKERS}", flush=True)
|
| 98 |
+
|
| 99 |
+
out = open(OUT, "a", encoding="utf-8")
|
| 100 |
+
n = len(done)
|
| 101 |
+
t0 = time.time()
|
| 102 |
+
counts = {}
|
| 103 |
+
with ThreadPoolExecutor(max_workers=WORKERS) as ex:
|
| 104 |
+
futs = [ex.submit(fetch, c) for c in todo]
|
| 105 |
+
for fut in as_completed(futs):
|
| 106 |
+
res = fut.result()
|
| 107 |
+
with _wlock:
|
| 108 |
+
out.write(json.dumps(res, ensure_ascii=False) + "\n")
|
| 109 |
+
n += 1
|
| 110 |
+
counts[res.get("status")] = counts.get(res.get("status"), 0) + 1
|
| 111 |
+
time.sleep(random.uniform(0.02, 0.10))
|
| 112 |
+
if n % 500 == 0:
|
| 113 |
+
out.flush()
|
| 114 |
+
rate = (n - len(done)) / max(time.time() - t0, 1)
|
| 115 |
+
eta = (len(clean) - n) / max(rate, 0.1) / 60
|
| 116 |
+
msg = f"{n}/{len(clean)} {rate:.1f}/s ETA {eta:.0f}m " + \
|
| 117 |
+
" ".join(f"{k}={v}" for k, v in sorted(counts.items()))
|
| 118 |
+
print(msg, flush=True)
|
| 119 |
+
open(PROG, "w").write(msg + "\n")
|
| 120 |
+
out.flush(); out.close()
|
| 121 |
+
print(f"DONE attribution: {n}/{len(clean)} counts={counts}", flush=True)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
if __name__ == "__main__":
|
| 125 |
+
main()
|
data/biblioteka_nauki/recover_licenses.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Pass 2: recover the per-item license for every Biblioteka Nauki doc via the public API.
|
| 3 |
+
index.jsonl -> GET bibliotekanauki.pl/api/{type}/{id} -> licenses.jsonl
|
| 4 |
+
|
| 5 |
+
Resumable (skips ids already in licenses.jsonl), polite (modest concurrency + jitter + backoff),
|
| 6 |
+
keep-alive sessions, and a circuit-breaker if the host starts blocking us.
|
| 7 |
+
|
| 8 |
+
Output line: {type,id, iconId, cc(bool), restricted(bool), authors, year, source, status}
|
| 9 |
+
status: "ok" | "http404" | "http403" | "err:<Type>"
|
| 10 |
+
"""
|
| 11 |
+
import json, os, random, sys, threading, time
|
| 12 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 13 |
+
import requests
|
| 14 |
+
|
| 15 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 16 |
+
INDEX = os.path.join(HERE, "index.jsonl")
|
| 17 |
+
OUT = os.path.join(HERE, "licenses.jsonl")
|
| 18 |
+
PROG = os.path.join(HERE, "recover_progress.txt")
|
| 19 |
+
|
| 20 |
+
WORKERS = 8
|
| 21 |
+
TIMEOUT = 25
|
| 22 |
+
MAX_RETRY = 4
|
| 23 |
+
UA = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
|
| 24 |
+
"(KHTML, like Gecko) Chrome/124 Safari/537.36")
|
| 25 |
+
HEADERS = {"User-Agent": UA, "Accept": "application/json", "Referer": "https://bibliotekanauki.pl/"}
|
| 26 |
+
|
| 27 |
+
_local = threading.local()
|
| 28 |
+
_write_lock = threading.Lock()
|
| 29 |
+
_recent = [] # rolling window of recent statuses for the circuit breaker
|
| 30 |
+
_recent_lock = threading.Lock()
|
| 31 |
+
_stop = threading.Event()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def session():
|
| 35 |
+
s = getattr(_local, "s", None)
|
| 36 |
+
if s is None:
|
| 37 |
+
s = requests.Session()
|
| 38 |
+
s.headers.update(HEADERS)
|
| 39 |
+
a = requests.adapters.HTTPAdapter(pool_connections=4, pool_maxsize=4)
|
| 40 |
+
s.mount("https://", a)
|
| 41 |
+
_local.s = s
|
| 42 |
+
return s
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def load_done():
|
| 46 |
+
done = set()
|
| 47 |
+
if os.path.exists(OUT):
|
| 48 |
+
with open(OUT, encoding="utf-8") as f:
|
| 49 |
+
for line in f:
|
| 50 |
+
try:
|
| 51 |
+
r = json.loads(line)
|
| 52 |
+
done.add((r["type"], r["id"]))
|
| 53 |
+
except Exception:
|
| 54 |
+
pass
|
| 55 |
+
return done
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def fetch(item):
|
| 59 |
+
if _stop.is_set():
|
| 60 |
+
return None
|
| 61 |
+
typ, _id = item["type"], item["id"]
|
| 62 |
+
url = f"https://bibliotekanauki.pl/api/{typ}/{_id}"
|
| 63 |
+
for attempt in range(MAX_RETRY):
|
| 64 |
+
try:
|
| 65 |
+
r = session().get(url, timeout=TIMEOUT)
|
| 66 |
+
if r.status_code == 200:
|
| 67 |
+
d = r.json()
|
| 68 |
+
lic = d.get("license") or {}
|
| 69 |
+
authors = []
|
| 70 |
+
for c in (d.get("contributors") or []):
|
| 71 |
+
nm = (c.get("name") or "").strip()
|
| 72 |
+
if nm:
|
| 73 |
+
authors.append(nm)
|
| 74 |
+
year = None
|
| 75 |
+
for dt in (d.get("dates") or []):
|
| 76 |
+
y = str(dt.get("year") or dt.get("value") or "")[:4]
|
| 77 |
+
if y.isdigit():
|
| 78 |
+
year = y
|
| 79 |
+
break
|
| 80 |
+
insts = d.get("publicationInstitutions") or d.get("journal") or None
|
| 81 |
+
if isinstance(insts, list):
|
| 82 |
+
insts = "; ".join(x.get("name", "") if isinstance(x, dict) else str(x) for x in insts) or None
|
| 83 |
+
return {
|
| 84 |
+
"type": typ, "id": _id,
|
| 85 |
+
"iconId": lic.get("iconId"),
|
| 86 |
+
"cc": bool(lic.get("creativeCommons")),
|
| 87 |
+
"restricted": bool(d.get("restricted")),
|
| 88 |
+
"authors": authors[:12],
|
| 89 |
+
"year": year,
|
| 90 |
+
"source": insts,
|
| 91 |
+
"status": "ok",
|
| 92 |
+
}
|
| 93 |
+
if r.status_code in (403,):
|
| 94 |
+
return {"type": typ, "id": _id, "status": "http403"}
|
| 95 |
+
if r.status_code in (404, 410):
|
| 96 |
+
return {"type": typ, "id": _id, "status": "http404"}
|
| 97 |
+
# 429 / 5xx -> backoff & retry
|
| 98 |
+
time.sleep((2 ** attempt) + random.random())
|
| 99 |
+
except Exception as e:
|
| 100 |
+
if attempt == MAX_RETRY - 1:
|
| 101 |
+
return {"type": typ, "id": _id, "status": f"err:{type(e).__name__}"}
|
| 102 |
+
time.sleep((2 ** attempt) + random.random())
|
| 103 |
+
return {"type": typ, "id": _id, "status": "err:retries"}
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def note(status):
|
| 107 |
+
with _recent_lock:
|
| 108 |
+
_recent.append(status)
|
| 109 |
+
if len(_recent) > 200:
|
| 110 |
+
_recent.pop(0)
|
| 111 |
+
# circuit breaker: >60% 403 over a full window => host is blocking us
|
| 112 |
+
if len(_recent) == 200 and sum(1 for s in _recent if s == "http403") > 120:
|
| 113 |
+
_stop.set()
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def main():
|
| 117 |
+
if not os.path.exists(INDEX):
|
| 118 |
+
sys.exit(f"missing {INDEX} — run build_index.py first")
|
| 119 |
+
items = []
|
| 120 |
+
with open(INDEX, encoding="utf-8") as f:
|
| 121 |
+
for line in f:
|
| 122 |
+
try:
|
| 123 |
+
r = json.loads(line)
|
| 124 |
+
items.append({"type": r["type"], "id": r["id"]})
|
| 125 |
+
except Exception:
|
| 126 |
+
pass
|
| 127 |
+
done = load_done()
|
| 128 |
+
todo = [it for it in items if (it["type"], it["id"]) not in done]
|
| 129 |
+
total = len(items)
|
| 130 |
+
print(f"index={total} done={len(done)} todo={len(todo)} workers={WORKERS}", flush=True)
|
| 131 |
+
|
| 132 |
+
n = len(done)
|
| 133 |
+
t0 = time.time()
|
| 134 |
+
out = open(OUT, "a", encoding="utf-8")
|
| 135 |
+
counts = {}
|
| 136 |
+
try:
|
| 137 |
+
with ThreadPoolExecutor(max_workers=WORKERS) as ex:
|
| 138 |
+
futs = [ex.submit(fetch, it) for it in todo]
|
| 139 |
+
for fut in as_completed(futs):
|
| 140 |
+
res = fut.result()
|
| 141 |
+
if res is None:
|
| 142 |
+
continue
|
| 143 |
+
with _write_lock:
|
| 144 |
+
out.write(json.dumps(res, ensure_ascii=False) + "\n")
|
| 145 |
+
n += 1
|
| 146 |
+
st = res.get("status", "?")
|
| 147 |
+
counts[st] = counts.get(st, 0) + 1
|
| 148 |
+
note(st)
|
| 149 |
+
# politeness jitter (per completed task; with 8 workers ~ a few hundred req/min)
|
| 150 |
+
time.sleep(random.uniform(0.02, 0.12))
|
| 151 |
+
if n % 500 == 0:
|
| 152 |
+
out.flush()
|
| 153 |
+
rate = (n - len(done)) / max(time.time() - t0, 1)
|
| 154 |
+
eta = (total - n) / max(rate, 0.1) / 60
|
| 155 |
+
msg = (f"{n}/{total} {rate:.1f}/s ETA {eta:.0f}m "
|
| 156 |
+
+ " ".join(f"{k}={v}" for k, v in sorted(counts.items())))
|
| 157 |
+
print(msg, flush=True)
|
| 158 |
+
with open(PROG, "w") as p:
|
| 159 |
+
p.write(msg + "\n")
|
| 160 |
+
if _stop.is_set():
|
| 161 |
+
print("!! circuit breaker tripped (sustained 403) — stopping. Re-run later to resume.", flush=True)
|
| 162 |
+
break
|
| 163 |
+
finally:
|
| 164 |
+
out.flush()
|
| 165 |
+
out.close()
|
| 166 |
+
print(f"FINISHED pass: wrote {n}/{total}. counts={counts}", flush=True)
|
| 167 |
+
print("Next: build_parquet.py to assemble the CC-BY/SA subset.", flush=True)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
if __name__ == "__main__":
|
| 171 |
+
main()
|