burocrazia / fetch.py
albertobarnabo's picture
Documenti d'Italia v1.0: 204 gold annotations, schema, scorer, inaugural leaderboard
6bdf6a4 verified
Raw History Blame Contribute Delete
1.57 kB
#!/usr/bin/env python3
"""Fetch the non-rehosted documents of Documenti d'Italia from their original
public sources, verifying sha256. Stdlib only. Re-run to resume; already-valid
files are skipped. Files that disappear from the web are reported — their
annotations remain usable and scoreable for the subset you hold."""
import hashlib, json, os, sys, time, urllib.request
HERE = os.path.dirname(os.path.abspath(__file__))
UA = "documenti-italia-fetch/1.0 (dataset reconstruction)"
ok = miss = skip = 0
for line in open(os.path.join(HERE, "manifest.jsonl")):
e = json.loads(line)
if e.get("file"):
continue
if not e.get("url") or e["url"].startswith("unknown"):
print("UNAVAILABLE (no known source):", e["doc_id"][:16]); miss += 1; continue
dst = os.path.join(HERE, "docs", "fetched", e["sha256"] + "." + e["format"])
if os.path.exists(dst) and hashlib.sha256(open(dst, "rb").read()).hexdigest() == e["sha256"]:
skip += 1; continue
os.makedirs(os.path.dirname(dst), exist_ok=True)
try:
req = urllib.request.Request(e["url"], headers={"User-Agent": UA})
data = urllib.request.urlopen(req, timeout=60).read()
if hashlib.sha256(data).hexdigest() != e["sha256"]:
print("CHANGED upstream:", e["url"][:80]); miss += 1; continue
open(dst, "wb").write(data); ok += 1; print("ok", e["sha256"][:12])
time.sleep(1)
except Exception as ex:
print("FAILED:", e["url"][:80], "-", str(ex)[:60]); miss += 1
print(f"fetched {ok}, skipped {skip}, unavailable {miss}")