File size: 10,419 Bytes
8b262e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
#!/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()