polish-dynaword / src /clean_biblioteka_nauki.py
ppuzio's picture
biblioteka_nauki: per-record licence versions from the API (42,068 -> 42,055 docs, v2#57) (#81)
620bbbd
Raw History Blame
15 kB
#!/usr/bin/env python3
"""Drop Biblioteka Nauki rows whose licence is not an established grant, and label the rest per record.
Kept: `cc-by`, `cc-by-sa` and `cc0` (none in v0.2.5), the per-item Creative Commons licence read from
bibliotekanauki.pl/api/{type}/{id} (`license.iconId`) by data/biblioteka_nauki/recover_licenses.py.
Dropped: `public-domain`. The platform shows it for items tagged with the CC Public Domain Mark 1.0
(API licence id 22, https://creativecommons.org/publicdomain/mark/1.0/). The Mark is a label, not
a waiver or a licence, and the 3 tagged items are original works first published 2019-2022, so
the Polish life+70 term cannot have run out (polish-dynaword-v2#52,
artifacts/rights_audit_2026-10/reports/academic.md). Any other licence value fails the run.
Relabel (polish-dynaword-v2#57): `iconId` drops the licence version, so v0.2.5 and the first v0.2.6
build said cc-by / cc-by-sa while the API gives 2.0, 3.0, 3.0 PL and 4.0. The `license` column now
carries the API's own licence, e.g. `CC-BY-3.0-PL`, read from the sidecar
data/biblioteka_nauki/biblioteka_nauki.license-api.json (written by recover_license_versions.py from one
API call per row). Only CC BY / CC BY-SA 2.0-4.0, generic or Poland port, whose URL, name and icon agree
with each other and with the stored label are labelled. A row the API did not resolve, or whose licence is
anything else, is withheld (dropped and listed in stats `withheld`), never kept under a guessed label.
No other column changes.
Maintainer decisions of 2026-10-06 (polish-dynaword-v2#57, Hub PR 81), applied by id, one reason per id:
API_OVERRIDES `articles_2011995` is labelled with the API's current CC BY-SA 4.0 although the earlier
recovery stored cc-by; the row is kept.
TEXT_NC_ND 56 rows whose own text prints a NonCommercial and/or NoDerivatives licence while the API
says CC BY or CC BY-SA. Withheld.
TEXT_REPRINT 15 rows whose text says it is a translation or reprint published by a publisher's
permission (Oxford University Press and 12 other publishers or journals). Withheld.
The build fails if a listed id is not reached, i.e. not among the rows that would otherwise be kept.
The v0.2.4 assembly script (build_parquet.py) was never committed, so this filters the shipped
v0.2.5 Parquet, pinned by SHA-256, and updates the stats file in place. Rerun:
git checkout v0.2.5 -- data/biblioteka_nauki/biblioteka_nauki.parquet
python3 src/clean_biblioteka_nauki.py
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
from collections import Counter
from pathlib import Path
import pyarrow as pa
import pyarrow.compute as pc
import pyarrow.parquet as pq
SOURCE = "biblioteka_nauki"
DATA = Path(__file__).resolve().parents[1] / "data" / SOURCE
INPUT_SHA256 = "cc93cdd5ca3e6576a1da0aa294df1308e879b8516ac30911289e430c69a07b26" # v0.2.5
KEEP = {"cc-by", "cc-by-sa", "cc0"} # = CLEAN in data/biblioteka_nauki/recover_attribution.py
DROP = {"public-domain"} # CC Public Domain Mark: a label, not a grant (see docstring)
SIDECAR = DATA / f"{SOURCE}.license-api.json"
# creativecommons.org/licenses/by/3.0/pl/legalcode, .../by-sa/4.0/legalcode.en, .../by/2.0/legalcode
LICENSE_URL = re.compile(r"^https://creativecommons\.org/licenses/(by|by-sa)/(\d\.\d)/(?:([a-z]{2})/)?legalcode(?:\.[a-z]{2})?$")
VERSIONS = {"2.0", "2.5", "3.0", "4.0"}
JURISDICTIONS = {None, "pl"} # None = generic / Unported
API_OVERRIDES = {f"{SOURCE}_articles_2011995": "CC-BY-SA-4.0"} # {id: label the API's own licence must give}
def _group(kind: str, numbers: str, reason: str) -> dict[str, str]:
return {f"{SOURCE}_{kind}_{number}": reason for number in numbers.split()}
# Printed licence read in the text (front or back matter) against a CC BY / CC BY-SA API label.
TEXT_NC_ND = {
**_group("articles", "1966144 2082824 1963195 1964252 1963167 1963170 1963181 1963183 1963187 1964253 1964257 "
"2082818 2082821 2082837 1963190 1991243 2082827 2082829 1964255 2082857 1963193",
"Krytyka Prawa 2019: the text prints CC BY-NC-ND 3.0"),
**_group("articles", "1032417 1032173 1032302 1032215 1032351 1032276 1032116 1032495 1032509 1032225 1032501 1032461",
"Journal of Health Sciences 2014 (Radom): the text prints the Creative Commons Attribution Noncommercial licence"),
**_group("articles", "2040728 2040731 2089607 2089605 2089606 2089616", "the text prints CC BY-NC-ND 4.0"),
**_group("articles", "2057203 2057193", "the text prints a CC-BY-NC-ND 4.0 licence URL"),
**_group("articles", "486876", "the issue colophon prints CC BY-NC-ND 4.0"),
**_group("articles", "520085", "the text prints CC BY-NC-ND 2.0 and says it is translated by permission of the author"),
**_group("articles", "1191739", "the text prints CC BY-NC-SA 4.0"),
**_group("articles", "487021", "the text prints CC BY-NC-ND 4.0"),
**_group("books", "1076493 1377755 1191609", "the colophon prints CC BY-NC-ND 3.0 PL"),
**_group("books", "1788278", "the colophon prints CC BY-NC 3.0 PL; the text and the attribution field name different works"),
**_group("books", "1396571", "the colophon prints CC BY-NC 3.0 PL"),
**_group("books", "1409913", "the colophon prints CC BY-ND 3.0 PL"),
**_group("books", "2010681", "the colophon prints a NonCommercial licence, contradicting its own CC BY-SA 4.0 abbreviation"),
**_group("books", "2159317 2028459", "the text prints CC BY-NC-SA 4.0"),
**_group("books", "2143725", "the text prints CC BY-NC 3.0 PL (its foreword says CC BY)"),
**_group("books", "1396563", "the front page prints CC BY-NC-SA 4.0 (its colophon says CC BY-SA 4.0)"),
}
# The text says it was translated or reprinted by permission of a publisher or journal; nothing shows that permission
# covers redistribution under CC BY / BY-SA.
TEXT_REPRINT = {
**_group("articles", "634914 634916", "translated and reprinted by permission of Oxford University Press (for the Oral History Association); "
"limited-rights notice with a licence number"),
**_group("articles", "1622298", "Polish translation published by permission of the author and Oxford University Press; "
"further reproduction needs the publisher's consent"),
**_group("articles", "1622259", "reprinted by permission of the University of Arkansas Press, via The Permissions Company"),
**_group("articles", "1621507", "translated by permission of the author and the publisher (Darton, Longman and Todd)"),
**_group("articles", "623064", "reprinted by permission of Sage"),
**_group("articles", "623121", "translated and reproduced with permission of International Affairs"),
**_group("articles", "643727 643809", "\"Reprinted by Permission of SAGE Publications\""),
**_group("articles", "643825", "reprinted by permission of Indiana University Press"),
**_group("articles", "694180", "reprinted by permission of Westview Press"),
**_group("articles", "630597", "reprinted with the editors' permission"),
**_group("articles", "634918", "reprinted from the Oral History Review by permission of the Oral History Association"),
**_group("articles", "1917546 1992050", "translated and published by permission of the author and of the journal's publisher (Nova et Vetera)"),
}
def filter_table(table: pa.Table) -> pa.Table:
"""Rows whose `license` is in KEEP. Fails on any value in neither KEEP nor DROP."""
if unknown := set(table.column("license").unique().to_pylist()) - KEEP - DROP:
raise SystemExit(f"unexpected license values: {sorted(unknown, key=str)}")
return table.filter(pc.is_in(table.column("license"), pa.array(sorted(KEEP))))
def license_label(api_license: dict, stored: str) -> str:
"""SPDX-style label (CC-BY-3.0-PL) for one API licence object. Raises ValueError, with the reason, unless it
is an allowlisted CC BY / BY-SA whose URL, English name and icon agree with each other and with `stored`."""
if not api_license.get("creativeCommons"):
raise ValueError(f"API licence {api_license.get('id')} is not marked creativeCommons")
match = LICENSE_URL.match(api_license.get("urlEn") or "")
if not match:
raise ValueError(f"licence URL not allowlisted: {api_license.get('urlEn')!r}")
kind, version, port = match.groups()
if version not in VERSIONS or port not in JURISDICTIONS:
raise ValueError(f"licence version/port not allowlisted: {api_license['urlEn']!r}")
name = api_license.get("nameEn") or ""
if f" {version}" not in name or (port and f" {port.upper()}" not in name):
raise ValueError(f"licence name {name!r} disagrees with URL {api_license['urlEn']!r}")
if not (api_license.get("iconId") == stored == f"cc-{kind}"):
raise ValueError(f"API icon {api_license.get('iconId')!r}, URL kind {kind!r} and stored {stored!r} disagree")
return f"CC-{kind.upper()}-{version}" + (f"-{port.upper()}" if port else "")
def relabel(table: pa.Table, sidecar: dict, overrides: dict[str, str] | None = None) -> tuple[pa.Table, dict[str, str]]:
"""Versioned `license` for every row from the API sidecar. Returns the table without withheld rows and
{id: reason} for them. Fails closed: unresolved, missing or non-allowlisted rows are withheld. Only `license` changes.
A row in `overrides` is labelled from its API licence alone (the earlier stored label may differ), which must
give the listed label; the run fails if such a row is not reached (absent, unresolved or not in the sidecar)."""
overrides = overrides or {}
ids, stored = table.column("id").to_pylist(), table.column("license").to_pylist()
reached: set[str] = set()
resolved: dict[tuple[int, str], str | None] = {} # (API licence id, stored label) -> label, None = withheld
reasons: dict[tuple[int, str], str] = {}
new, withheld = [], {}
for row_id, old in zip(ids, stored):
label = None
if row_id in sidecar["unresolved"]:
withheld[row_id] = f"API: {sidecar['unresolved'][row_id]}"
elif row_id not in sidecar["rows"]:
withheld[row_id] = "not in the API sidecar"
elif row_id in overrides:
reached.add(row_id)
api_license = sidecar["licenses"][str(sidecar["rows"][row_id])]
label = license_label(api_license, api_license["iconId"])
if label != overrides[row_id]:
raise SystemExit(f"{row_id}: the API gives {label}, the override expects {overrides[row_id]}")
else:
key = (sidecar["rows"][row_id], old)
if key not in resolved:
try:
resolved[key] = license_label(sidecar["licenses"][str(key[0])], old)
except ValueError as exc:
resolved[key], reasons[key] = None, str(exc)
label = resolved[key]
if label is None:
withheld[row_id] = reasons[key]
new.append(label)
if unreached := sorted(set(overrides) - reached):
raise SystemExit(f"override ids not reached: {unreached}")
index = table.schema.get_field_index("license")
relabelled = table.set_column(index, table.schema.field(index), pa.array(new, pa.string()))
return relabelled.filter(pa.array([label is not None for label in new])), withheld
def withhold_listed(table: pa.Table, listed: dict[str, str]) -> tuple[pa.Table, dict[str, str]]:
"""The table without the rows in `listed` ({id: reason}). Fails if a listed id is not in `table`."""
if unreached := sorted(set(listed) - set(table.column("id").to_pylist())):
raise SystemExit(f"listed ids not reached: {unreached}")
return table.filter(pc.invert(pc.is_in(table.column("id"), pa.array(sorted(listed), pa.string())))), dict(listed)
def content_digest(path: Path, skip: frozenset[str] = frozenset()) -> str:
"""SHA-256 over every (id, SHA-256 of text) in file order, minus ids in `skip`. Equal digests mean the same
rows in the same order with the same text, whatever the other columns say."""
digest = hashlib.sha256()
for batch in pq.ParquetFile(path).iter_batches(columns=["id", "text"], batch_size=2000):
for row_id, text in zip(batch.column("id").to_pylist(), batch.column("text").to_pylist()):
if row_id not in skip:
digest.update(f"{row_id}\t{hashlib.sha256(text.encode()).hexdigest()}\n".encode())
return digest.hexdigest()
def build(input_path: Path, out_dir: Path) -> dict:
with input_path.open("rb") as stream:
if hashlib.file_digest(stream, "sha256").hexdigest() != INPUT_SHA256:
raise SystemExit(f"{input_path} is not the v0.2.5 Parquet; restore it with "
f"`git checkout v0.2.5 -- data/{SOURCE}/{SOURCE}.parquet`")
table = pq.read_table(input_path)
granted = filter_table(table)
dropped = sorted(set(table.column("id").to_pylist()) - set(granted.column("id").to_pylist()))
labelled, api_withheld = relabel(granted, json.loads(SIDECAR.read_text(encoding="utf-8")), API_OVERRIDES)
labelled, nc_nd = withhold_listed(labelled, TEXT_NC_ND)
kept, reprint = withhold_listed(labelled, TEXT_REPRINT)
withheld = {**api_withheld, **nc_nd, **reprint}
assert len(withheld) == len(api_withheld) + len(nc_nd) + len(reprint)
stats_path = out_dir / f"{SOURCE}.stats.json"
stats = json.loads(stats_path.read_text(encoding="utf-8")) # keeps build_dynaword's read/drop_* counts
stats.update(
kept=kept.num_rows,
drop_rights=table.num_rows - granted.num_rows,
drop_license_unverified=len(api_withheld),
drop_text_nc_nd=len(nc_nd),
drop_text_reprint=len(reprint),
chars=pc.sum(pc.utf8_length(kept.column("text"))).as_py(),
tokens=pc.sum(kept.column("token_count")).as_py(),
license=" / ".join(sorted(set(kept.column("license").to_pylist()))),
licenses=dict(sorted(Counter(kept.column("license").to_pylist()).items())),
withheld=dict(sorted(withheld.items())),
input_sha256=INPUT_SHA256,
)
parquet_tmp = out_dir / f"{SOURCE}.parquet.tmp"
stats_tmp = out_dir / f"{SOURCE}.stats.json.tmp"
pq.write_table(kept, parquet_tmp)
os.replace(parquet_tmp, out_dir / f"{SOURCE}.parquet")
stats["content_sha256"] = content_digest(out_dir / f"{SOURCE}.parquet")
stats_tmp.write_text(json.dumps(stats, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
os.replace(stats_tmp, stats_path)
return {**stats, "dropped_ids": dropped}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
parser.add_argument("--input", type=Path, default=DATA / f"{SOURCE}.parquet")
parser.add_argument("--out", type=Path, default=DATA)
args = parser.parse_args()
print(json.dumps(build(args.input, args.out), indent=2, ensure_ascii=False))
if __name__ == "__main__":
main()