#!/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. Per-record licence basis and the reviewed drops (polish-dynaword-v2#111, maintainer decisions of 2026-10-20). The rows left by the steps above are scanned with src/licence_basis_biblioteka_nauki.py (the rules and the hand decisions). `biblioteka_nauki.review.csv` (`id,decision,reason`, pinned by SHA-256) holds one decision for every row a rule nominates and for nothing else; the build refuses to run when it differs from what the rules give. Rows it marks `drop` are removed: the 88 rows of the clear-cut reasons, the 97 rows with a restriction notice and no CC note of their own, and the rows whose `created` year is earlier than the first year of their label's licence version. A kept row is not changed (stats `content_sha256`, and the evidence file records a digest of every column of the kept rows). The attribution sidecar carries `licence_basis`, `licence_basis_url` and `licence_basis_date` from the same run. 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 After a change to a rule or a hand decision, `--propose-review` rewrites the review table from the rules; read the diff and pin the new SHA-256 in REVIEW_SHA256. """ from __future__ import annotations import argparse import hashlib import json import re import sys from collections import Counter from pathlib import Path from typing import Iterator, NamedTuple import pyarrow as pa import pyarrow.compute as pc import pyarrow.parquet as pq sys.path.insert(0, str(Path(__file__).resolve().parent)) import licence_basis as lb # noqa: E402 import licence_basis_biblioteka_nauki as lbn # noqa: E402 from biblioteka_nauki_overlap import ATTRIBUTION_SEP # noqa: E402 from normalize_schema import SCHEMA # noqa: E402 (the canonical columns every shipped shard carries) from sejm_api_common import check_pin, read_pinned_review, replace_all, sha256_file # noqa: E402 SOURCE = "biblioteka_nauki" DATA = Path(__file__).resolve().parents[1] / "data" / SOURCE PARQUET, STATS, ATTRIBUTION, EVIDENCE, REVIEW, LICENSE_API = ( DATA / f"{SOURCE}.{name}" for name in ("parquet", "stats.json", "attribution.jsonl", "licence-basis.json", "review.csv", "license-api.json")) INPUT_SHA256 = "cc93cdd5ca3e6576a1da0aa294df1308e879b8516ac30911289e430c69a07b26" # v0.2.5 LICENSE_API_SHA256 = "51e0bf7900e016f4b0102eecfd5032f3969a566899bf8ba094abad9f4f4578b5" # the labels (and so the review) depend on it CLEANED_CONTENT_SHA256 = "cc4ad9ce16aaef3c7bc5197743ad58182e3d5011f78cbf53896083e7a8541954" # content_digest of the rows left before the review REVIEW_SHA256 = "25e27c96280b6af547f2fdfb9d49a2d35861e96195a647047d6836af4a68a401" # biblioteka_nauki.review.csv ROW_GROUP_SIZE = 128 # the Dataset Viewer reads a whole row group; 128 rows keep each under 100 MB REVIEW_REASONS = {decision: set(group) for decision, group in lbn.REASONS.items()} 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) RESTORE = f"restore it with `git checkout v0.2.5 -- data/{SOURCE}/{SOURCE}.parquet`" # 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} _TRAILING_MARKER = re.compile(r"\s+\d+$") # a footnote marker glued to the last name in the source _HAS_LETTER = re.compile(r"[^\W\d_]", re.UNICODE) # a name has a letter; `. .` does not def split_author(citation: str) -> str: """The author name(s): the first citation field, without a trailing marker or an empty placeholder.""" author = _TRAILING_MARKER.sub("", citation.split(ATTRIBUTION_SEP, 1)[0].strip()) return author if _HAS_LETTER.search(author) else "" def split_attribution(table: pa.Table) -> pa.Table: """The table in the canonical columns: the citation (`attribution`) is replaced by its author names (`author`).""" citations = table.column("attribution").to_pylist() index = table.schema.get_field_index("attribution") table = table.set_column(index, "author", pa.array([split_author(c or "") for c in citations], pa.string())) return table.select(SCHEMA.names) 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 batches(source: Path | pa.Table, columns: list[str] | None = None) -> Iterator[pa.RecordBatch]: if isinstance(source, Path): yield from pq.ParquetFile(source).iter_batches(columns=columns, batch_size=2000) else: yield from source.select(columns or source.column_names).to_batches(max_chunksize=2000) def content_digest(source: Path | pa.Table, skip: frozenset[str] = frozenset()) -> str: """SHA-256 over every (id, SHA-256 of text) in row 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 batches(source, ["id", "text"]): 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 rows_digest(source: Path | pa.Table, skip: frozenset[str] = frozenset()) -> str: """SHA-256 over every column of every row in row order (the row as JSON, keys sorted), minus ids in `skip`.""" digest = hashlib.sha256() for batch in batches(source): for row in batch.to_pylist(): if row["id"] not in skip: digest.update(json.dumps(row, ensure_ascii=False, sort_keys=True).encode() + b"\n") return digest.hexdigest() def clean_table(table: pa.Table, api: dict, overrides: dict[str, str] = API_OVERRIDES, nc_nd: dict[str, str] = TEXT_NC_ND, reprint: dict[str, str] = TEXT_REPRINT) -> tuple[pa.Table, dict[str, int], dict[str, str]]: """The rows left after the licence steps (a rights label, the API's licence, the two hand lists), the stats counts of what each step took, and {id: reason} for the withheld rows. `api` is the license-api sidecar.""" granted = filter_table(table) labelled, api_withheld = relabel(granted, api, overrides) labelled, nc_nd_withheld = withhold_listed(labelled, nc_nd) kept, reprint_withheld = withhold_listed(labelled, reprint) withheld = {**api_withheld, **nc_nd_withheld, **reprint_withheld} assert len(withheld) == len(api_withheld) + len(nc_nd_withheld) + len(reprint_withheld) counts = {"drop_rights": table.num_rows - granted.num_rows, "drop_license_unverified": len(api_withheld), "drop_text_nc_nd": len(nc_nd_withheld), "drop_text_reprint": len(reprint_withheld)} return kept, counts, withheld class Screen(NamedTuple): """The rows left after the licence steps, with what the rules say about them.""" cleaned: pa.Table counts: dict[str, int] withheld: dict[str, str] recs: list[dict] flags: dict[str, list[str]] by_rule: dict[str, dict[str, tuple[str, str]]] final: dict[str, tuple[str, str, str]] def screen(input_path: Path) -> Screen: check_pin(input_path, INPUT_SHA256, RESTORE) check_pin(LICENSE_API, LICENSE_API_SHA256, "the labels, and so the review, depend on it; it is the committed file") api = json.loads(LICENSE_API.read_text(encoding="utf-8")) cleaned, counts, withheld = clean_table(pq.read_table(input_path), api) if (digest := content_digest(cleaned)) != CLEANED_CONTENT_SHA256: raise SystemExit(f"the rows left before the review differ from the ones it was made for ({digest}, expected {CLEANED_CONTENT_SHA256})") recs = lbn.scan(cleaned) ids = set(cleaned.column("id").to_pylist()) flags = {i: f for i, f in api["flagged"].items() if i in ids} by_rule = lbn.decisions(recs, set(flags)) return Screen(cleaned, counts, withheld, recs, flags, by_rule, lbn.final_reasons(by_rule)) def read_review(path: Path = REVIEW, expected: str = REVIEW_SHA256) -> dict[str, tuple[str, str]]: """id -> (decision, reason) from the pinned review table.""" return read_pinned_review(path, expected, f"it is not the reviewed {REVIEW.name}; `--propose-review` writes the one the rules give", REVIEW_REASONS) def check_review(review: dict[str, tuple[str, str]], final: dict[str, tuple[str, str, str]]) -> None: """The review holds one decision for every row a rule nominates and for nothing else.""" proposed = lbn.proposed_review(final) if review != proposed: differing = sorted(i for i in review.keys() | proposed.keys() if review.get(i) != proposed.get(i)) raise SystemExit(f"the pinned review and the rules disagree on {len(differing)} ids, first {differing[:5]}; " "`--propose-review` writes what the rules give: read the difference, pin the new SHA-256") def build(input_path: Path, out_dir: Path, review_path: Path = REVIEW, expected_review: str = REVIEW_SHA256) -> dict: scr = screen(input_path) review = read_review(review_path, expected_review) check_review(review, scr.final) dropped = {i: reason for i, (decision, reason) in review.items() if decision == lbn.DROP} pre_review = split_attribution(scr.cleaned) # the shard as it was before the review kept, _ = withhold_listed(pre_review, dropped) skip = frozenset(dropped) citations = [c for i, c in zip(scr.cleaned.column("id").to_pylist(), scr.cleaned.column("attribution").to_pylist()) if i not in skip] kept_recs = [r for r in scr.recs if r["id"] not in skip] lines = lbn.attribution_lines(kept_recs, citations) if problems := lb.check_lines(lines, kept.column("id").to_pylist()): raise SystemExit(f"the attribution sidecar does not fit the rows: {problems[:5]}") stats_path = out_dir / STATS.name stats = json.loads(stats_path.read_text(encoding="utf-8")) # keeps build_dynaword's read/drop_* counts stats.update( kept=kept.num_rows, **scr.counts, drop_review=len(dropped), drop_review_by_reason=dict(sorted(Counter(dropped.values()).items())), 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(scr.withheld.items())), input_sha256=INPUT_SHA256, content_sha256=content_digest(kept), ) pinned = { "review": {"file": review_path.name, "sha256": expected_review, "rows": len(review)}, "input": {"v0.2.5_parquet_sha256": INPUT_SHA256, "license_api_sha256": LICENSE_API_SHA256, "rows_before_review": scr.cleaned.num_rows, "rows_before_review_content_sha256": CLEANED_CONTENT_SHA256}, "kept": {"rows": kept.num_rows, "rows_sha256": rows_digest(pre_review, skip), "note": "SHA-256 of every column of the kept rows (id, text, source, added, created, token_count, license, author), as they were before the review; " "the test recomputes it from the shipped Parquet"}, } evidence = lbn.evidence(scr.recs, scr.by_rule, scr.final, scr.flags, pinned) replace_all({ out_dir / PARQUET.name: lambda path: pq.write_table(kept, path, row_group_size=ROW_GROUP_SIZE), stats_path: lambda path: path.write_text(json.dumps(stats, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"), out_dir / ATTRIBUTION.name: lambda path: path.write_bytes(lbn.sidecar_bytes(lines)), out_dir / EVIDENCE.name: lambda path: path.write_text(json.dumps(evidence, ensure_ascii=False, sort_keys=True, indent=2) + "\n", encoding="utf-8"), }) return stats def propose_review(input_path: Path, review_path: Path = REVIEW) -> str: """Write the review table the rules give; returns its SHA-256, to be pinned as REVIEW_SHA256.""" review_path.write_bytes(lbn.review_csv(screen(input_path).final).encode("utf-8")) return sha256_file(review_path) def main() -> None: parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) parser.add_argument("--input", type=Path, default=PARQUET) parser.add_argument("--out", type=Path, default=DATA) parser.add_argument("--propose-review", action="store_true", help=f"write {REVIEW.name} from the rules and print its SHA-256; nothing else changes") args = parser.parse_args() if args.propose_review: print(f"{REVIEW}\nREVIEW_SHA256 = {propose_review(args.input)!r}") return print(json.dumps(build(args.input, args.out), indent=2, ensure_ascii=False)) if __name__ == "__main__": main()