Datasets:
Download data/biblioteka_nauki/recover_attribution.py from SlayerLab/polish-dynaword: direct link, hf CLI and curl.
- Browser
- Download file 5.19 kB
-
https://huggingface.co/datasets/SlayerLab/polish-dynaword/resolve/main/data/biblioteka_nauki/recover_attribution.py
- Command line
-
hf download hf://datasets/SlayerLab/polish-dynaword/data/biblioteka_nauki/recover_attribution.py
-
curl -L -o recover_attribution.py https://huggingface.co/datasets/SlayerLab/polish-dynaword/resolve/main/data/biblioteka_nauki/recover_attribution.py
5.19 kB
| #!/usr/bin/env python3 | |
| """Targeted attribution pass for the CLEAN (CC-BY/CC-BY-SA/CC0) Biblioteka Nauki ids ONLY. | |
| The first recovery pass stored the license correctly but parsed the wrong attribution fields. | |
| CC-BY/CC-BY-SA legally REQUIRE attribution, so re-fetch just the ~43.6k clean ids and extract: | |
| authors = contributors[role=AUTHOR] firstName+lastName ; year = dates[PUBLISHED].date.year ; | |
| title = mainTitle.text ; publisher = publishingCompanyInfo.name | |
| licenses.jsonl -> attribution.jsonl {type,id,license,authors,year,title,publisher} | |
| Resumable, threaded, polite. ~43.6k calls. | |
| """ | |
| import json, os, random, sys, threading, time | |
| from concurrent.futures import ThreadPoolExecutor, as_completed | |
| import requests | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| LIC = os.path.join(HERE, "licenses.jsonl") | |
| OUT = os.path.join(HERE, "attribution.jsonl") | |
| PROG = os.path.join(HERE, "attribution_progress.txt") | |
| # The v0.2.4 run also kept "public-domain": the CC Public Domain Mark, a label rather than a grant | |
| # (polish-dynaword-v2#52). src/clean_biblioteka_nauki.py drops it from the shipped Parquet; its KEEP | |
| # set must equal this one. | |
| CLEAN = {"cc-by", "cc-by-sa", "cc0"} | |
| WORKERS = 8 | |
| UA = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 " | |
| "(KHTML, like Gecko) Chrome/124 Safari/537.36") | |
| HEADERS = {"User-Agent": UA, "Accept": "application/json", "Referer": "https://bibliotekanauki.pl/"} | |
| _local = threading.local() | |
| _wlock = threading.Lock() | |
| def session(): | |
| s = getattr(_local, "s", None) | |
| if s is None: | |
| s = requests.Session() | |
| s.headers.update(HEADERS) | |
| s.mount("https://", requests.adapters.HTTPAdapter(pool_connections=4, pool_maxsize=4)) | |
| _local.s = s | |
| return s | |
| def parse(d): | |
| authors = [] | |
| for c in (d.get("contributors") or []): | |
| if c.get("role") == "AUTHOR": | |
| nm = f"{c.get('firstName','') or ''} {c.get('lastName','') or ''}".strip() | |
| if nm: | |
| authors.append(nm) | |
| year = None | |
| dates = d.get("dates") or [] | |
| for dt in dates: | |
| if dt.get("type") == "PUBLISHED": | |
| year = (dt.get("date") or {}).get("year") | |
| break | |
| if not year and dates: | |
| year = (dates[0].get("date") or {}).get("year") | |
| title = (d.get("mainTitle") or {}).get("text") | |
| pub = (d.get("publishingCompanyInfo") or {}).get("name") | |
| return authors[:20], (str(year) if year else None), title, pub | |
| def fetch(item): | |
| typ, _id, lic = item | |
| url = f"https://bibliotekanauki.pl/api/{typ}/{_id}" | |
| for attempt in range(4): | |
| try: | |
| r = session().get(url, timeout=25) | |
| if r.status_code == 200: | |
| a, y, t, p = parse(r.json()) | |
| return {"type": typ, "id": _id, "license": lic, | |
| "authors": a, "year": y, "title": t, "publisher": p, "status": "ok"} | |
| if r.status_code in (403, 404, 410): | |
| return {"type": typ, "id": _id, "license": lic, "status": f"http{r.status_code}"} | |
| time.sleep((2 ** attempt) + random.random()) | |
| except Exception as e: | |
| if attempt == 3: | |
| return {"type": typ, "id": _id, "license": lic, "status": f"err:{type(e).__name__}"} | |
| time.sleep((2 ** attempt) + random.random()) | |
| return {"type": typ, "id": _id, "license": lic, "status": "err:retries"} | |
| def main(): | |
| best = {} | |
| for l in open(LIC, encoding="utf-8"): | |
| try: | |
| r = json.loads(l) | |
| except Exception: | |
| continue | |
| best[(r["type"], r["id"])] = r | |
| clean = [(t, i, r["iconId"]) for (t, i), r in best.items() | |
| if r.get("status") == "ok" and r.get("iconId") in CLEAN] | |
| done = set() | |
| if os.path.exists(OUT): | |
| for l in open(OUT, encoding="utf-8"): | |
| try: | |
| r = json.loads(l) | |
| done.add((r["type"], r["id"])) | |
| except Exception: | |
| pass | |
| todo = [c for c in clean if (c[0], c[1]) not in done] | |
| print(f"clean={len(clean)} done={len(done)} todo={len(todo)} workers={WORKERS}", flush=True) | |
| out = open(OUT, "a", encoding="utf-8") | |
| n = len(done) | |
| t0 = time.time() | |
| counts = {} | |
| with ThreadPoolExecutor(max_workers=WORKERS) as ex: | |
| futs = [ex.submit(fetch, c) for c in todo] | |
| for fut in as_completed(futs): | |
| res = fut.result() | |
| with _wlock: | |
| out.write(json.dumps(res, ensure_ascii=False) + "\n") | |
| n += 1 | |
| counts[res.get("status")] = counts.get(res.get("status"), 0) + 1 | |
| time.sleep(random.uniform(0.02, 0.10)) | |
| if n % 500 == 0: | |
| out.flush() | |
| rate = (n - len(done)) / max(time.time() - t0, 1) | |
| eta = (len(clean) - n) / max(rate, 0.1) / 60 | |
| msg = f"{n}/{len(clean)} {rate:.1f}/s ETA {eta:.0f}m " + \ | |
| " ".join(f"{k}={v}" for k, v in sorted(counts.items())) | |
| print(msg, flush=True) | |
| open(PROG, "w").write(msg + "\n") | |
| out.flush(); out.close() | |
| print(f"DONE attribution: {n}/{len(clean)} counts={counts}", flush=True) | |
| if __name__ == "__main__": | |
| main() | |