polish-dynaword / src /fetch_europeana.py
kacperwikiel's picture
Release v0.3.1 Europeana preview shard (#4)
264ccc9
Raw
History Blame Contribute Delete
10.4 kB
#!/usr/bin/env python3
"""Direct Europeana rebuild with per-record rights metadata.
This intentionally does not consume the SpeakLeash Europeana aggregate. It uses
Europeana Search/Record APIs, preserves per-record rights/creator metadata, and
only emits records whose rights statement is open enough for DynaWord stable.
Usage:
EUROPEANA_API_KEY=... python3 src/fetch_europeana.py \
--query 'language:pl' --max-records 1000 --out data/upstream
For a connectivity smoke test, Europeana's public demo key can be used:
python3 src/fetch_europeana.py --api-key apidemo --query '*:*' --max-records 10 --out /tmp/dw
"""
from __future__ import annotations
import argparse
import json
import os
import re
import subprocess
import time
from collections import Counter
from pathlib import Path
from urllib.parse import quote
import requests
try:
from bs4 import BeautifulSoup
except Exception: # pragma: no cover - optional in some envs
BeautifulSoup = None
from rights import rights_ok, spdx
SEARCH_URL = "https://api.europeana.eu/record/v2/search.json"
RECORD_URL = "https://api.europeana.eu/record/v2/{record_id}.json"
UA = "polish-dynaword/0.3 (+direct-upstream-rights-rebuild)"
KEY = "europeana"
MIN_CHARS = 200
def compact_text(value) -> str:
if value is None:
return ""
if isinstance(value, list):
return "; ".join(str(v).strip() for v in value if str(v).strip())
if isinstance(value, dict):
parts = []
for v in value.values():
if isinstance(v, list):
parts.extend(str(x).strip() for x in v if str(x).strip())
elif v:
parts.append(str(v).strip())
return "; ".join(parts)
return str(value).strip()
def strip_html(text: str) -> str:
if not text:
return ""
if BeautifulSoup is not None:
text = BeautifulSoup(text, "html.parser").get_text("\n")
text = re.sub(r"\s+\n", "\n", text)
text = re.sub(r"\n{3,}", "\n\n", text)
text = re.sub(r"[ \t]{2,}", " ", text)
return text.strip()
def get_json(session: requests.Session, url: str, params: dict, tries: int = 5) -> dict:
for attempt in range(tries):
resp = session.get(url, params=params, timeout=60)
if resp.status_code in (429, 500, 502, 503, 504):
time.sleep(2 + attempt * 3)
continue
resp.raise_for_status()
return resp.json()
resp.raise_for_status()
return {}
def record_text(record: dict, item: dict) -> str:
obj = record.get("object", {}) if isinstance(record.get("object"), dict) else {}
proxies = obj.get("proxies") or []
candidates = []
for proxy in proxies:
for key in ("dcDescription", "dcTitle", "dctermsAlternative", "dctermsTableOfContents"):
candidates.append(compact_text(proxy.get(key)))
for key in ("title", "dcTitle", "description", "dcDescription"):
candidates.append(compact_text(item.get(key)))
text = "\n\n".join(part for part in candidates if part)
return strip_html(text)
def creator(record: dict, item: dict) -> str:
obj = record.get("object", {}) if isinstance(record.get("object"), dict) else {}
vals = []
for proxy in obj.get("proxies") or []:
for key in ("dcCreator", "dcContributor"):
val = compact_text(proxy.get(key))
if val:
vals.append(val)
for key in ("dcCreator", "edmAgentLabel"):
val = compact_text(item.get(key))
if val:
vals.append(val)
return "; ".join(dict.fromkeys(vals))
def created(record: dict, item: dict) -> str:
obj = record.get("object", {}) if isinstance(record.get("object"), dict) else {}
for proxy in obj.get("proxies") or []:
for key in ("year", "dctermsCreated", "dcDate", "dctermsIssued"):
val = compact_text(proxy.get(key))
if val:
return val
return compact_text(item.get("year") or item.get("timestamp_created_epoch"))
def rights_uri(record: dict, item: dict) -> str:
obj = record.get("object", {}) if isinstance(record.get("object"), dict) else {}
aggs = obj.get("aggregations") or []
for agg in aggs:
val = compact_text(agg.get("edmRights"))
if val:
return val
return compact_text(item.get("rights"))
def normalize_europeana_row(record: dict, item: dict) -> dict | None:
"""Normalize one API item only when its per-record rights are reusable."""
item_id = item.get("id")
if not item_id:
return None
rights = rights_uri(record, item)
if not rights_ok(rights):
return None
return {
"id": item_id.strip("/").replace("/", "_"),
"text": record_text(record, item),
"source_url": f"https://www.europeana.eu/item{item_id}",
"title": compact_text(item.get("title")),
"license": spdx(rights),
"rights_url": rights,
"author": creator(record, item),
"created": created(record, item),
"provider": compact_text(item.get("dataProvider") or item.get("provider")),
"raw_metadata": {"europeana_id": item_id, "rights": rights},
}
def compress_jsonl(path: Path) -> Path:
out = path.with_suffix(path.suffix + ".zst")
subprocess.run(["zstd", "-19", "-f", "--rm", str(path), "-o", str(out)], check=True)
return out
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--api-key", default=os.environ.get("EUROPEANA_API_KEY", ""))
ap.add_argument("--query", default="*:*")
ap.add_argument("--qf", action="append", default=["LANGUAGE:pl"])
ap.add_argument("--out", default="data/upstream")
ap.add_argument("--rows", type=int, default=100)
ap.add_argument("--max-records", type=int, default=1000)
ap.add_argument("--delay", type=float, default=0.05)
ap.add_argument("--include-short", action="store_true")
ap.add_argument("--record-api", action="store_true",
help="fetch every Record API document too; slower, use only for metadata comparison")
args = ap.parse_args()
if not args.api_key:
raise SystemExit("Set EUROPEANA_API_KEY or pass --api-key. Use --api-key apidemo only for smoke tests.")
out_root = Path(args.out).expanduser()
raw_dir = out_root / KEY / "raw"
raw_dir.mkdir(parents=True, exist_ok=True)
audit_dir = Path("artifacts")
audit_dir.mkdir(exist_ok=True)
jsonl = raw_dir / f"{KEY}.jsonl"
session = requests.Session()
session.headers.update({"User-Agent": UA})
stats = Counter()
rights_stats = Counter()
examples = {"included": [], "dropped": []}
cursor = "*"
written = 0
with jsonl.open("w", encoding="utf-8") as fo:
while written < args.max_records:
params = {
"wskey": args.api_key,
"query": args.query,
"qf": args.qf,
"rows": min(args.rows, args.max_records - written),
"cursor": cursor,
"profile": "rich",
}
page = get_json(session, SEARCH_URL, params)
items = page.get("items") or []
if not items:
break
cursor = page.get("nextCursor") or cursor
for item in items:
stats["seen"] += 1
item_id = item.get("id")
if not item_id:
stats["drop_no_id"] += 1
continue
# Search ``profile=rich`` already contains rights, creator and
# descriptions. Avoiding a second API request per item turns
# a 1,000-record run from thousands of HTTP calls into a dozen
# paged calls while retaining per-record provenance. The
# Record API remains available for comparison/debugging.
rec = get_json(
session,
RECORD_URL.format(record_id=quote(item_id.strip("/"), safe="/")),
{"wskey": args.api_key},
) if args.record_api else item
rights = rights_uri(rec, item)
rights_stats[rights or ""] += 1
row = normalize_europeana_row(rec, item)
if row is None:
stats["drop_rights"] += 1
if len(examples["dropped"]) < 20:
examples["dropped"].append({"id": item_id, "rights": rights, "reason": "rights_not_open"})
continue
text = row["text"]
if len(text) < MIN_CHARS and not args.include_short:
stats["drop_short"] += 1
continue
fo.write(json.dumps(row, ensure_ascii=False) + "\n")
stats["included"] += 1
written += 1
if len(examples["included"]) < 20:
examples["included"].append({k: row.get(k) for k in ("id", "title", "license", "rights_url", "author", "created")})
if written >= args.max_records:
break
time.sleep(args.delay)
if not page.get("nextCursor") or cursor == "*":
break
zst_path = compress_jsonl(jsonl)
audit = {
"source": KEY,
"query": args.query,
"qf": args.qf,
"max_records": args.max_records,
"stats": dict(stats),
"rights_distribution": dict(rights_stats.most_common()),
"examples": examples,
"output": str(zst_path),
"policy": "include only PDM/CC0/CC-BY/CC-BY-SA via per-record edm:rights",
}
audit_json = audit_dir / "europeana_direct_rebuild_audit.json"
audit_json.write_text(json.dumps(audit, ensure_ascii=False, indent=2), encoding="utf-8")
md = audit_dir / "europeana_direct_rebuild_audit.md"
md.write_text(
"# Europeana direct rebuild audit\n\n"
f"- Query: `{args.query}`\n"
f"- Output: `{zst_path}`\n"
f"- Seen: {stats['seen']}\n"
f"- Included: {stats['included']}\n"
f"- Dropped rights: {stats['drop_rights']}\n"
f"- Dropped short: {stats['drop_short']}\n\n"
"Rights distribution is stored in `europeana_direct_rebuild_audit.json`.\n",
encoding="utf-8",
)
print(json.dumps(audit["stats"], ensure_ascii=False, indent=2))
print(f"wrote {zst_path}")
if __name__ == "__main__":
main()