wolne_lektury: label each row with its own Wolne Lektury licence; drop 2 unlicensed rows (v2#57)

#99
by ppuzio - opened
data/wolne_lektury/wolne_lektury.licences.tsv ADDED
The diff for this file is too large to render. See raw diff
 
data/wolne_lektury/wolne_lektury.md CHANGED
@@ -6,12 +6,12 @@ Wolne Lektury (school readings)
6
  - **Source (upstream):** https://wolnelektury.pl/api/books/
7
  - **Domain:** literature
8
  - **Language:** Polish (pl)
9
- - **License:** `CC-BY-SA-4.0 / Wolna Sztuka 1.3`
10
  - **Created (range):** 1500-01-01, 2024-12-31
11
  - **Added:** 2026-06-15
12
 
13
  ## Licensing — traceable basis
14
- Wolne Lektury publishes under CC-BY-SA 4.0 or Free Art License; texts are public-domain classics + cleared works.
15
 
16
  ## Provenance
17
  Pulled from SpeakLeash's public redistribution (`speakleash-ds-pub`, key `wolne_lektury_corpus`) of the upstream source above. SpeakLeash credited as intermediate aggregator; upstream license/attribution preserved.
@@ -19,18 +19,22 @@ Pulled from SpeakLeash's public redistribution (`speakleash-ds-pub`, key `wolne_
19
  ## Statistics
20
  | documents | characters | tokens (tiktoken proxy) |
21
  |---:|---:|---:|
22
- | 6,078 | 230,764,171 | 90,654,820 |
23
 
24
 
25
  ## Per-document license metadata
26
  | license | documents |
27
  |---|---:|
28
- | `CC-BY-SA-4.0 / Wolna Sztuka 1.3` | 6,078 |
 
 
 
 
29
 
30
  Author metadata present for **0** documents. Empty values mean the upstream record did not expose a machine-readable author field.
31
 
32
  ## Legal scope note
33
- For v0.2.6, 63 documents whose text is an eltec_pol novel are dropped (share of a document's 5-word shingles found in one ELTeC novel >= 0.9; src/clean_wolne_lektury.py, polish-dynaword-v2#72). eltec_pol keeps those 50 novels whole under CC BY 4.0. Three documents only partly in an ELTeC novel are kept: both tomes of Mniszek's Trędowata (the ELTeC text is shorter) and Kochanowski's Pieśń IX, quoted in Łoziński's Oko proroka. Every pair is listed in wolne_lektury.eltec_pairs.tsv.
34
 
35
  Statistics were recomputed directly from the released parquet file.
36
 
@@ -40,7 +44,7 @@ Minimal, per Dynaword guidelines (heavy filtering left to downstream use):
40
  - drop non-Polish (diacritic ratio): **0**
41
  - exact cross-source dedup (sha1): **0**
42
  - OCR alpha-ratio < 0.70 (OCR sources only): **0**
43
- - read 6,141 → kept 6,078
44
 
45
  Token counts are a fast tiktoken (cl100k) proxy (~1% off Llama-3); the canonical
46
  Llama-3 count is computed at release.
 
6
  - **Source (upstream):** https://wolnelektury.pl/api/books/
7
  - **Domain:** literature
8
  - **Language:** Polish (pl)
9
+ - **License:** `per-record Wolne Lektury licence (public domain, LAL 1.3, CC BY-SA 3.0 PL/3.0/4.0)`
10
  - **Created (range):** 1500-01-01, 2024-12-31
11
  - **Added:** 2026-06-15
12
 
13
  ## Licensing — traceable basis
14
+ Each document's `license` is the one its own Wolne Lektury book states in dc:rights / dc:rights.license, never its parent collection's (src/wolne_lektury_licences.py, polish-dynaword-v2#57). Documents are matched to books by text: the same head and tail, or, where Wolne Lektury has edited a text since the scrape, a 5-word-shingle share of at least 0.6 at both ends; 17 were matched by hand. A label is set only when the rights text is unambiguous: a public-domain statement with no year after 1955, or one licence with its version. wolne_lektury.licences.tsv lists each document's book (its slug on wolnelektury.pl), the Wolne Lektury rights text and the label. The released text is Wolne Lektury's plain-text export without its footer, so it carries no attribution line, footnotes or motifs; the slug is the attribution link.
15
 
16
  ## Provenance
17
  Pulled from SpeakLeash's public redistribution (`speakleash-ds-pub`, key `wolne_lektury_corpus`) of the upstream source above. SpeakLeash credited as intermediate aggregator; upstream license/attribution preserved.
 
19
  ## Statistics
20
  | documents | characters | tokens (tiktoken proxy) |
21
  |---:|---:|---:|
22
+ | 6,076 | 230,761,977 | 90,653,913 |
23
 
24
 
25
  ## Per-document license metadata
26
  | license | documents |
27
  |---|---:|
28
+ | `public-domain` | 4,559 |
29
+ | `LAL-1.3` | 1,467 |
30
+ | `CC-BY-SA-3.0-PL` | 34 |
31
+ | `CC-BY-SA-4.0` | 11 |
32
+ | `CC-BY-SA-3.0` | 5 |
33
 
34
  Author metadata present for **0** documents. Empty values mean the upstream record did not expose a machine-readable author field.
35
 
36
  ## Legal scope note
37
+ For v0.2.6, 63 documents whose text is an eltec_pol novel are dropped (share of a document's 5-word shingles found in one ELTeC novel >= 0.9; src/clean_wolne_lektury.py, polish-dynaword-v2#72). eltec_pol keeps those 50 novels whole under CC BY 4.0. Three documents only partly in an ELTeC novel are kept: both tomes of Mniszek's Trędowata (the ELTeC text is shorter) and Kochanowski's Pieśń IX, quoted in Łoziński's Oko proroka. Every pair is listed in wolne_lektury.eltec_pairs.tsv. 2 documents are also dropped because Wolne Lektury gives them no usable licence: two Horace odes translated by Paweł Kozioł, one marked only "CC BY-SA" with no version, the other public domain for Marceli Motty's translation and "CC BY-SA" for Kozioł's (polish-dynaword-v2#57).
38
 
39
  Statistics were recomputed directly from the released parquet file.
40
 
 
44
  - drop non-Polish (diacritic ratio): **0**
45
  - exact cross-source dedup (sha1): **0**
46
  - OCR alpha-ratio < 0.70 (OCR sources only): **0**
47
+ - read 6,141 → kept 6,076
48
 
49
  Token counts are a fast tiktoken (cl100k) proxy (~1% off Llama-3); the canonical
50
  Llama-3 count is computed at release.
data/wolne_lektury/wolne_lektury.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:f308d49235551241d6c47c5e88138ba52e6235422ae272ddbc135c3b8696ae0e
3
- size 113055766
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ab0690efa4db1e0c8ea0980f35239d78f52c5fbc0d357c906056eeb4f81d829c
3
+ size 113055020
data/wolne_lektury/wolne_lektury.stats.json CHANGED
@@ -1,19 +1,24 @@
1
  {
2
  "read": 6141,
3
- "kept": 6078,
4
  "drop_short": 0,
5
  "drop_lang": 0,
6
  "drop_dup": 0,
7
  "drop_ocr": 0,
8
- "chars": 230764171,
9
- "tokens": 90654820,
10
  "licenses": {
11
- "CC-BY-SA-4.0 / Wolna Sztuka 1.3": 6078
 
 
 
 
12
  },
13
  "authors_with_value": 0,
14
- "license": "CC-BY-SA-4.0 / Wolna Sztuka 1.3",
15
  "stats_recomputed_from_parquet": true,
16
  "drop_eltec_dup": 63,
17
  "input_sha256": "5833c25db296f2479b3c09745ebedd550b2425dd6ebaf021f0095e684a0221a1",
18
- "eltec_sha256": "ba40061741dff11165149f6c2cf3d5526e1b6c759e7ce1e03ccc164d58838325"
 
19
  }
 
1
  {
2
  "read": 6141,
3
+ "kept": 6076,
4
  "drop_short": 0,
5
  "drop_lang": 0,
6
  "drop_dup": 0,
7
  "drop_ocr": 0,
8
+ "chars": 230761977,
9
+ "tokens": 90653913,
10
  "licenses": {
11
+ "CC-BY-SA-3.0": 5,
12
+ "CC-BY-SA-3.0-PL": 34,
13
+ "CC-BY-SA-4.0": 11,
14
+ "LAL-1.3": 1467,
15
+ "public-domain": 4559
16
  },
17
  "authors_with_value": 0,
18
+ "license": "per-record Wolne Lektury licence (public domain, LAL 1.3, CC BY-SA 3.0 PL/3.0/4.0)",
19
  "stats_recomputed_from_parquet": true,
20
  "drop_eltec_dup": 63,
21
  "input_sha256": "5833c25db296f2479b3c09745ebedd550b2425dd6ebaf021f0095e684a0221a1",
22
+ "eltec_sha256": "ba40061741dff11165149f6c2cf3d5526e1b6c759e7ce1e03ccc164d58838325",
23
+ "drop_rights": 2
24
  }
src/clean_wolne_lektury.py CHANGED
@@ -1,5 +1,6 @@
1
  #!/usr/bin/env python3
2
- """Drop wolne_lektury documents whose text is an eltec_pol novel (slayerlabs/polish-dynaword-v2#72).
 
3
 
4
  Half of the 100 ELTeC-pol novels are also in Wolne Lektury. The maintainer chose (2026-10-06) to
5
  drop the Wolne Lektury copies and keep eltec_pol whole, because ELTeC's CC BY 4.0 is the clean
@@ -15,6 +16,11 @@ the released text is not changed. Docs scoring >= DROP_AT are dropped. Docs scor
15
  >= REPORT_AT but below DROP_AT are only partly in an ELTeC novel; they are kept and listed.
16
  Both groups are written to wolne_lektury.eltec_pairs.tsv.
17
 
 
 
 
 
 
18
  Both input Parquets are pinned by SHA-256. Restore the WL Parquet before a rerun:
19
  git checkout v0.2.5 -- data/wolne_lektury/wolne_lektury.parquet
20
  python3 src/clean_wolne_lektury.py
@@ -34,6 +40,8 @@ import pyarrow.compute as pc
34
  import pyarrow.parquet as pq
35
 
36
  from shingle_containment import best_containment, strip_wl_footer
 
 
37
 
38
  SOURCE = "wolne_lektury"
39
  ROOT = Path(__file__).resolve().parents[1]
@@ -60,7 +68,30 @@ def check_pin(path: Path, expected: str, restore: str) -> None:
60
  raise SystemExit(f"{path} does not match the pinned SHA-256; {restore}")
61
 
62
 
63
- def build(input_path: Path, eltec_path: Path, out_dir: Path) -> dict:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  check_pin(input_path, INPUT_SHA256,
65
  f"restore it with `git checkout v0.2.5 -- data/{SOURCE}/{SOURCE}.parquet`")
66
  check_pin(eltec_path, ELTEC_SHA256, "it is not the v0.2.5 eltec_pol Parquet")
@@ -77,21 +108,25 @@ def build(input_path: Path, eltec_path: Path, out_dir: Path) -> dict:
77
  pairs.append({"wl_id": wl_id, "eltec_id": eltec_ids[novel], "score": f"{score:.4f}",
78
  "action": "drop" if score >= DROP_AT else "keep_partial",
79
  "wl_title": wl_title(text)})
80
- kept = table.filter(pa.array(keep))
 
 
81
 
82
  stats_path = out_dir / f"{SOURCE}.stats.json"
83
  stats = json.loads(stats_path.read_text(encoding="utf-8")) # keeps build_dynaword's read/drop_* counts
84
  stats.update(
85
  kept=kept.num_rows,
86
- drop_eltec_dup=table.num_rows - kept.num_rows,
 
87
  chars=pc.sum(pc.utf8_length(kept.column("text"))).as_py(),
88
  tokens=pc.sum(kept.column("token_count")).as_py(),
89
  licenses=dict(sorted(Counter(kept.column("license").to_pylist()).items())),
 
90
  authors_with_value=sum(map(bool, kept.column("author").to_pylist())),
91
  input_sha256=INPUT_SHA256,
92
  eltec_sha256=ELTEC_SHA256,
93
  )
94
- drops = ("drop_short", "drop_lang", "drop_dup", "drop_ocr", "drop_eltec_dup")
95
  if stats["read"] - sum(stats[k] for k in drops) != stats["kept"]:
96
  raise SystemExit("stats drop counts do not add up to the kept rows")
97
 
@@ -120,9 +155,10 @@ def main() -> None:
120
  parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
121
  parser.add_argument("--input", type=Path, default=DATA / f"{SOURCE}.parquet")
122
  parser.add_argument("--eltec", type=Path, default=ELTEC)
 
123
  parser.add_argument("--out", type=Path, default=DATA)
124
  args = parser.parse_args()
125
- print(json.dumps(build(args.input, args.eltec, args.out), indent=2, ensure_ascii=False))
126
 
127
 
128
  if __name__ == "__main__":
 
1
  #!/usr/bin/env python3
2
+ """Drop wolne_lektury documents whose text is an eltec_pol novel (slayerlabs/polish-dynaword-v2#72),
3
+ then label each kept row with its own Wolne Lektury licence (polish-dynaword-v2#57).
4
 
5
  Half of the 100 ELTeC-pol novels are also in Wolne Lektury. The maintainer chose (2026-10-06) to
6
  drop the Wolne Lektury copies and keep eltec_pol whole, because ELTeC's CC BY 4.0 is the clean
 
16
  >= REPORT_AT but below DROP_AT are only partly in an ELTeC novel; they are kept and listed.
17
  Both groups are written to wolne_lektury.eltec_pairs.tsv.
18
 
19
+ The `license` of each kept row comes from wolne_lektury.licences.tsv, which
20
+ src/wolne_lektury_licences.py writes from Wolne Lektury's metadata; the build stops unless that file
21
+ labels exactly the kept rows. The rows in that module's UNLICENSED, whose metadata gives no usable
22
+ licence, are dropped first (stats `drop_rights`).
23
+
24
  Both input Parquets are pinned by SHA-256. Restore the WL Parquet before a rerun:
25
  git checkout v0.2.5 -- data/wolne_lektury/wolne_lektury.parquet
26
  python3 src/clean_wolne_lektury.py
 
40
  import pyarrow.parquet as pq
41
 
42
  from shingle_containment import best_containment, strip_wl_footer
43
+ from sources import SOURCES
44
+ from wolne_lektury_licences import LABELS, LICENCES, UNLICENSED
45
 
46
  SOURCE = "wolne_lektury"
47
  ROOT = Path(__file__).resolve().parents[1]
 
68
  raise SystemExit(f"{path} does not match the pinned SHA-256; {restore}")
69
 
70
 
71
+ def relabel(table: pa.Table, licences_path: Path) -> pa.Table:
72
+ """`table` with each row's `license` from the licences TSV, which must list exactly its rows."""
73
+ with licences_path.open(encoding="utf-8", newline="") as handle:
74
+ records = list(csv.DictReader(handle, delimiter="\t"))
75
+ labels = {record["id"]: record["license"] for record in records}
76
+ ids = table.column("id").to_pylist()
77
+ if len(labels) != len(records) or labels.keys() != set(ids):
78
+ raise SystemExit(f"{licences_path.name} does not list exactly the kept rows; "
79
+ "rerun src/wolne_lektury_licences.py")
80
+ if not set(labels.values()) <= set(LABELS):
81
+ raise SystemExit(f"{licences_path.name} has labels outside {LABELS}")
82
+ return table.set_column(table.column_names.index("license"), "license",
83
+ pa.array([labels[i] for i in ids], pa.string()))
84
+
85
+
86
+ def drop_unlicensed(table: pa.Table) -> pa.Table:
87
+ """`table` without the UNLICENSED rows, every one of which must be in it."""
88
+ unlicensed = pc.is_in(table.column("id"), pa.array(sorted(UNLICENSED)))
89
+ if pc.sum(unlicensed).as_py() != len(UNLICENSED):
90
+ raise SystemExit("an UNLICENSED id is not among the deduplicated rows")
91
+ return table.filter(pc.invert(unlicensed))
92
+
93
+
94
+ def build(input_path: Path, eltec_path: Path, licences_path: Path, out_dir: Path) -> dict:
95
  check_pin(input_path, INPUT_SHA256,
96
  f"restore it with `git checkout v0.2.5 -- data/{SOURCE}/{SOURCE}.parquet`")
97
  check_pin(eltec_path, ELTEC_SHA256, "it is not the v0.2.5 eltec_pol Parquet")
 
108
  pairs.append({"wl_id": wl_id, "eltec_id": eltec_ids[novel], "score": f"{score:.4f}",
109
  "action": "drop" if score >= DROP_AT else "keep_partial",
110
  "wl_title": wl_title(text)})
111
+ deduped = table.filter(pa.array(keep))
112
+ licensed = drop_unlicensed(deduped)
113
+ kept = relabel(licensed, licences_path)
114
 
115
  stats_path = out_dir / f"{SOURCE}.stats.json"
116
  stats = json.loads(stats_path.read_text(encoding="utf-8")) # keeps build_dynaword's read/drop_* counts
117
  stats.update(
118
  kept=kept.num_rows,
119
+ drop_eltec_dup=table.num_rows - deduped.num_rows,
120
+ drop_rights=deduped.num_rows - licensed.num_rows,
121
  chars=pc.sum(pc.utf8_length(kept.column("text"))).as_py(),
122
  tokens=pc.sum(kept.column("token_count")).as_py(),
123
  licenses=dict(sorted(Counter(kept.column("license").to_pylist()).items())),
124
+ license=SOURCES[SOURCE]["license"],
125
  authors_with_value=sum(map(bool, kept.column("author").to_pylist())),
126
  input_sha256=INPUT_SHA256,
127
  eltec_sha256=ELTEC_SHA256,
128
  )
129
+ drops = ("drop_short", "drop_lang", "drop_dup", "drop_ocr", "drop_eltec_dup", "drop_rights")
130
  if stats["read"] - sum(stats[k] for k in drops) != stats["kept"]:
131
  raise SystemExit("stats drop counts do not add up to the kept rows")
132
 
 
155
  parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
156
  parser.add_argument("--input", type=Path, default=DATA / f"{SOURCE}.parquet")
157
  parser.add_argument("--eltec", type=Path, default=ELTEC)
158
+ parser.add_argument("--licences", type=Path, default=DATA / LICENCES)
159
  parser.add_argument("--out", type=Path, default=DATA)
160
  args = parser.parse_args()
161
+ print(json.dumps(build(args.input, args.eltec, args.licences, args.out), indent=2, ensure_ascii=False))
162
 
163
 
164
  if __name__ == "__main__":
src/sources.py CHANGED
@@ -386,10 +386,19 @@ SOURCES = {
386
  "release": "0.2.0",
387
  "speakleash_key": "wolne_lektury_corpus",
388
  "pretty": "Wolne Lektury (school readings)",
389
- "license": "CC-BY-SA-4.0 / Wolna Sztuka 1.3",
390
- "license_spdx": "CC-BY-SA-4.0",
391
- "traceable": "Wolne Lektury publishes under CC-BY-SA 4.0 or Free Art "
392
- "License; texts are public-domain classics + cleared works.",
 
 
 
 
 
 
 
 
 
393
  "upstream": "https://wolnelektury.pl/api/books/",
394
  "domain": "literature",
395
  "created": "1500-01-01, 2024-12-31",
@@ -399,7 +408,11 @@ SOURCES = {
399
  "50 novels whole under CC BY 4.0. Three documents only partly in an ELTeC "
400
  "novel are kept: both tomes of Mniszek's Trędowata (the ELTeC text is "
401
  "shorter) and Kochanowski's Pieśń IX, quoted in Łoziński's Oko proroka. "
402
- "Every pair is listed in wolne_lektury.eltec_pairs.tsv.",
 
 
 
 
403
  "is_ocr": False,
404
  },
405
  "wikinews": {
 
386
  "release": "0.2.0",
387
  "speakleash_key": "wolne_lektury_corpus",
388
  "pretty": "Wolne Lektury (school readings)",
389
+ "license": "per-record Wolne Lektury licence (public domain, LAL 1.3, CC BY-SA 3.0 PL/3.0/4.0)",
390
+ "license_spdx": "MIXED",
391
+ "traceable": "Each document's `license` is the one its own Wolne Lektury book states in "
392
+ "dc:rights / dc:rights.license, never its parent collection's "
393
+ "(src/wolne_lektury_licences.py, polish-dynaword-v2#57). Documents are matched "
394
+ "to books by text: the same head and tail, or, where Wolne Lektury has edited a "
395
+ "text since the scrape, a 5-word-shingle share of at least 0.6 at both ends; 17 "
396
+ "were matched by hand. A label is set only when the rights text is unambiguous: "
397
+ "a public-domain statement with no year after 1955, or one licence with its "
398
+ "version. wolne_lektury.licences.tsv lists each document's book (its slug on "
399
+ "wolnelektury.pl), the Wolne Lektury rights text and the label. The released "
400
+ "text is Wolne Lektury's plain-text export without its footer, so it carries no "
401
+ "attribution line, footnotes or motifs; the slug is the attribution link.",
402
  "upstream": "https://wolnelektury.pl/api/books/",
403
  "domain": "literature",
404
  "created": "1500-01-01, 2024-12-31",
 
408
  "50 novels whole under CC BY 4.0. Three documents only partly in an ELTeC "
409
  "novel are kept: both tomes of Mniszek's Trędowata (the ELTeC text is "
410
  "shorter) and Kochanowski's Pieśń IX, quoted in Łoziński's Oko proroka. "
411
+ "Every pair is listed in wolne_lektury.eltec_pairs.tsv. 2 documents are also "
412
+ "dropped because Wolne Lektury gives them no usable licence: two Horace odes "
413
+ "translated by Paweł Kozioł, one marked only \"CC BY-SA\" with no version, the "
414
+ "other public domain for Marceli Motty's translation and \"CC BY-SA\" for "
415
+ "Kozioł's (polish-dynaword-v2#57).",
416
  "is_ocr": False,
417
  },
418
  "wikinews": {
src/test_wolne_lektury_contract.py CHANGED
@@ -1,9 +1,11 @@
1
- """Contract checks for wolne_lektury after the eltec_pol dedup (src/clean_wolne_lektury.py, v2#72)."""
 
2
 
3
  import csv
4
  import hashlib
5
  import json
6
  import sys
 
7
  from pathlib import Path
8
 
9
  import pyarrow as pa
@@ -14,7 +16,9 @@ import pytest
14
  sys.path.insert(0, str(Path(__file__).resolve().parent))
15
 
16
  from clean_wolne_lektury import (DATA, DROP_AT, ELTEC, ELTEC_SHA256, PAIRS, REPORT_AT, build,
17
- wl_title)
 
 
18
 
19
  # Hand-checked: only part of each is in its ELTeC novel, so they stay (see the findings entry).
20
  PARTIAL_IDS = {"wolne_lektury_2375475", "wolne_lektury_2375476", "wolne_lektury_2376242"}
@@ -28,7 +32,7 @@ def test_build_fails_closed_on_unpinned_inputs(tmp_path):
28
  fake = tmp_path / "wolne_lektury.parquet"
29
  pq.write_table(pa.table({"id": ["a"], "text": ["b"]}), fake)
30
  with pytest.raises(SystemExit, match="pinned SHA-256"):
31
- build(fake, ELTEC, tmp_path)
32
  assert sorted(p.name for p in tmp_path.iterdir()) == ["wolne_lektury.parquet"]
33
 
34
 
@@ -41,24 +45,74 @@ def test_release_has_no_eltec_duplicates_and_matches_stats():
41
  dropped = {p["wl_id"] for p in pairs if p["action"] == "drop"}
42
  partial = {p["wl_id"] for p in pairs if p["action"] == "keep_partial"}
43
 
44
- assert table.num_rows == len(ids) == stats["kept"] == 6_078
45
  assert len(dropped) == stats["drop_eltec_dup"] == 63
 
46
  assert partial == PARTIAL_IDS
47
  assert not dropped & ids and partial <= ids
48
  assert all(float(p["score"]) >= DROP_AT for p in pairs if p["action"] == "drop")
49
  assert all(REPORT_AT <= float(p["score"]) < DROP_AT for p in pairs if p["action"] == "keep_partial")
50
  assert all(p["eltec_id"].startswith("eltec_pol_") for p in pairs)
51
- drops = ("drop_short", "drop_lang", "drop_dup", "drop_ocr", "drop_eltec_dup")
52
  assert stats["read"] - sum(stats[k] for k in drops) == stats["kept"]
53
  assert pc.sum(table.column("token_count")).as_py() == stats["tokens"]
54
  assert pc.sum(pc.utf8_length(table.column("text"))).as_py() == stats["chars"]
55
- assert stats["licenses"] == {"CC-BY-SA-4.0 / Wolna Sztuka 1.3": stats["kept"]} # #57 relabels later
56
  with ELTEC.open("rb") as stream: # eltec_pol is kept whole
57
  assert hashlib.file_digest(stream, "sha256").hexdigest() == ELTEC_SHA256
58
 
59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  def test_datasheet_counts_match_stats():
61
  stats = json.loads((DATA / "wolne_lektury.stats.json").read_text(encoding="utf-8"))
62
  card = (DATA / "wolne_lektury.md").read_text(encoding="utf-8")
63
  assert f"| {stats['kept']:,} | {stats['chars']:,} | {stats['tokens']:,} |" in card
64
  assert f"{stats['drop_eltec_dup']} " in card and "eltec_pol" in card
 
 
 
 
 
1
+ """Contract checks for wolne_lektury after the eltec_pol dedup (src/clean_wolne_lektury.py, v2#72)
2
+ and the per-row licence (src/wolne_lektury_licences.py, v2#57)."""
3
 
4
  import csv
5
  import hashlib
6
  import json
7
  import sys
8
+ from collections import Counter
9
  from pathlib import Path
10
 
11
  import pyarrow as pa
 
16
  sys.path.insert(0, str(Path(__file__).resolve().parent))
17
 
18
  from clean_wolne_lektury import (DATA, DROP_AT, ELTEC, ELTEC_SHA256, PAIRS, REPORT_AT, build,
19
+ drop_unlicensed, relabel, wl_title)
20
+ from sources import SOURCES
21
+ from wolne_lektury_licences import LABELS, LICENCES, MANUAL, PUBLIC_DOMAIN, UNLICENSED
22
 
23
  # Hand-checked: only part of each is in its ELTeC novel, so they stay (see the findings entry).
24
  PARTIAL_IDS = {"wolne_lektury_2375475", "wolne_lektury_2375476", "wolne_lektury_2376242"}
 
32
  fake = tmp_path / "wolne_lektury.parquet"
33
  pq.write_table(pa.table({"id": ["a"], "text": ["b"]}), fake)
34
  with pytest.raises(SystemExit, match="pinned SHA-256"):
35
+ build(fake, ELTEC, DATA / LICENCES, tmp_path)
36
  assert sorted(p.name for p in tmp_path.iterdir()) == ["wolne_lektury.parquet"]
37
 
38
 
 
45
  dropped = {p["wl_id"] for p in pairs if p["action"] == "drop"}
46
  partial = {p["wl_id"] for p in pairs if p["action"] == "keep_partial"}
47
 
48
+ assert table.num_rows == len(ids) == stats["kept"] == 6_076
49
  assert len(dropped) == stats["drop_eltec_dup"] == 63
50
+ assert len(UNLICENSED) == stats["drop_rights"] == 2 and not UNLICENSED & ids
51
  assert partial == PARTIAL_IDS
52
  assert not dropped & ids and partial <= ids
53
  assert all(float(p["score"]) >= DROP_AT for p in pairs if p["action"] == "drop")
54
  assert all(REPORT_AT <= float(p["score"]) < DROP_AT for p in pairs if p["action"] == "keep_partial")
55
  assert all(p["eltec_id"].startswith("eltec_pol_") for p in pairs)
56
+ drops = ("drop_short", "drop_lang", "drop_dup", "drop_ocr", "drop_eltec_dup", "drop_rights")
57
  assert stats["read"] - sum(stats[k] for k in drops) == stats["kept"]
58
  assert pc.sum(table.column("token_count")).as_py() == stats["tokens"]
59
  assert pc.sum(pc.utf8_length(table.column("text"))).as_py() == stats["chars"]
 
60
  with ELTEC.open("rb") as stream: # eltec_pol is kept whole
61
  assert hashlib.file_digest(stream, "sha256").hexdigest() == ELTEC_SHA256
62
 
63
 
64
+ def _licences():
65
+ with (DATA / LICENCES).open(encoding="utf-8", newline="") as handle:
66
+ return list(csv.DictReader(handle, delimiter="\t"))
67
+
68
+
69
+ def test_every_row_carries_its_own_wolne_lektury_licence():
70
+ stats = json.loads((DATA / "wolne_lektury.stats.json").read_text(encoding="utf-8"))
71
+ table = pq.read_table(DATA / "wolne_lektury.parquet", columns=["id", "license"])
72
+ records = _licences()
73
+ by_id = {r["id"]: r for r in records}
74
+ assert len(by_id) == len(records) == table.num_rows
75
+ assert dict(zip(table.column("id").to_pylist(), table.column("license").to_pylist())) == {
76
+ i: r["license"] for i, r in by_id.items()}
77
+ assert stats["licenses"] == dict(sorted(Counter(r["license"] for r in records).items()))
78
+ assert set(stats["licenses"]) <= set(LABELS)
79
+ assert all(r["slug"] and r["wl_rights"] for r in records)
80
+ assert {r["id"] for r in records if r["match"] == "manual"} == set(MANUAL)
81
+ assert {r["match"] for r in records} == {"exact", "fuzzy", "manual"}
82
+ assert stats["license"] == SOURCES["wolne_lektury"]["license"]
83
+ assert SOURCES["wolne_lektury"]["license_spdx"] == "MIXED"
84
+ # #57: a Proust tome is public domain in its own WL metadata; its parent is CC BY-SA 3.0 PL.
85
+ tome = by_id["wolne_lektury_2371693"]
86
+ assert tome["license"] == PUBLIC_DOMAIN and "Boy-Żeleński" in tome["wl_rights"]
87
+
88
+
89
+ def test_drop_unlicensed_fails_closed():
90
+ rows = pa.table({"id": ["a", *sorted(UNLICENSED)]})
91
+ assert drop_unlicensed(rows).column("id").to_pylist() == ["a"]
92
+ with pytest.raises(SystemExit, match="UNLICENSED"):
93
+ drop_unlicensed(rows.slice(0, 2)) # one UNLICENSED id is missing
94
+
95
+
96
+ def test_relabel_fails_closed(tmp_path):
97
+ table = pa.table({"id": ["a", "b"], "license": ["old", "old"]})
98
+ tsv = tmp_path / LICENCES
99
+ for body in ("id\tlicense\na\tpublic-domain\n", # b missing
100
+ "id\tlicense\na\tpublic-domain\nb\tpublic-domain\nc\tpublic-domain\n", # c extra
101
+ "id\tlicense\na\tpublic-domain\na\tLAL-1.3\nb\tLAL-1.3\n", # a twice
102
+ "id\tlicense\na\tpublic-domain\nb\tCC-BY-4.0\n"): # not a WL label
103
+ tsv.write_text(body, encoding="utf-8")
104
+ with pytest.raises(SystemExit):
105
+ relabel(table, tsv)
106
+ tsv.write_text("id\tlicense\nb\tLAL-1.3\na\tpublic-domain\n", encoding="utf-8")
107
+ assert relabel(table, tsv).column("license").to_pylist() == ["public-domain", "LAL-1.3"]
108
+
109
+
110
  def test_datasheet_counts_match_stats():
111
  stats = json.loads((DATA / "wolne_lektury.stats.json").read_text(encoding="utf-8"))
112
  card = (DATA / "wolne_lektury.md").read_text(encoding="utf-8")
113
  assert f"| {stats['kept']:,} | {stats['chars']:,} | {stats['tokens']:,} |" in card
114
  assert f"{stats['drop_eltec_dup']} " in card and "eltec_pol" in card
115
+ assert f"{stats['drop_rights']} documents" in card and "Kozioł" in card
116
+ assert f"; {len(MANUAL)} were matched by hand" in card
117
+ for label, count in stats["licenses"].items():
118
+ assert f"| `{label}` | {count:,} |" in card
src/test_wolne_lektury_licences.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit checks for the per-row Wolne Lektury licence match (src/wolne_lektury_licences.py, v2#57)."""
2
+
3
+ import json
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ import pytest
8
+
9
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
10
+
11
+ import wolne_lektury_licences
12
+ from wolne_lektury_licences import (CC_BY_SA_3, CC_BY_SA_3_PL, CC_BY_SA_4, FUZZY_CHARS, FUZZY_SLACK, LAL,
13
+ MANUAL, PUBLIC_DOMAIN, _fetch_book, _shares, classify, dc, label_rows,
14
+ match)
15
+
16
+ LAL_URL = "http://artlibre.org/licence/lal/pl/"
17
+ BY_SA_3 = "http://creativecommons.org/licenses/by-sa/3.0/"
18
+
19
+
20
+ @pytest.mark.parametrize("rights, urls, label", [
21
+ # dc:rights / dc:rights.license pairs as Wolne Lektury writes them
22
+ ("Domena publiczna - Jan Kochanowski zm. 1584", [], PUBLIC_DOMAIN),
23
+ ("Domena publiczna - Tadeusz Boy-Żeleński zm. 1941", ["Domena publiczna"], PUBLIC_DOMAIN),
24
+ ("Domena publiczna --- Zygmunt Krasiński zm. 1859", [], PUBLIC_DOMAIN),
25
+ ("Domena publiczna - XVIII w.", [], PUBLIC_DOMAIN),
26
+ ("domena publiczna", [], PUBLIC_DOMAIN),
27
+ ("Anatol France zm. 1924", [], PUBLIC_DOMAIN),
28
+ ("Domena publiczna - Wacław Sieroszewski zm.1945", [], PUBLIC_DOMAIN),
29
+ ("Domena publiczna - tłumacz nieznany, wydanie z roku 1927", [], PUBLIC_DOMAIN),
30
+ ("Licencja Wolnej Sztuki 1.3", [LAL_URL], LAL),
31
+ ("Licencja Wolnej Sztuki 1.3.", ["https://artlibre.org/licence/lal/pl"], LAL),
32
+ ("Creative Commons Uznanie Autorstwa - Na Tych Samych Warunkach 3.0.PL", [BY_SA_3], CC_BY_SA_3_PL),
33
+ ("Creative Commons Uznanie Autorstwa - Na Tych Samych Warunkach 3.0. PL", [BY_SA_3], CC_BY_SA_3_PL),
34
+ ("Creative Commons Uznanie Autorstwa - Na Tych Samych Warunkach 3.0 Unported", [BY_SA_3], CC_BY_SA_3),
35
+ ("Licencja Creative Commons Uznanie autorstwa - Na tych samych warunkach 4.0",
36
+ ["https://creativecommons.org/licenses/by-sa/4.0/deed.pl"], CC_BY_SA_4),
37
+ # fail closed: in copyright by WL's own death year, no version, two licences, nothing
38
+ ("Domena publiczna - Jan Kowalski zm. 1960", [], None),
39
+ ("Domena publiczna - Jan Kowalski zm.1960", [], None),
40
+ ("Domena publiczna - Jan Kowalski zm. w 1960", [], None),
41
+ ("Domena publiczna - Jan Kowalski (1960)", [], None),
42
+ ("Domena publiczna - Maria Pawlikowska-Jasnorzewska zm. 2015", [], None), # WL's typo for 1945
43
+ ("CC BY-SA", [], None),
44
+ ("Creative Commons Uznanie Autorstwa - Na Tych Samych Warunkach", [], None),
45
+ ("Domena publiczna - Marceli Motty zm. 1898; CC BY-SA - Paweł Kozioł", [], None),
46
+ ("Domena publiczna - Adam Asnyk zm. 1897", [LAL_URL], None),
47
+ ("Licencja Wolnej Sztuki 1.3", [BY_SA_3], None),
48
+ ("", [], None),
49
+ ])
50
+ def test_classify(rights, urls, label):
51
+ assert classify(rights, urls) == label
52
+
53
+
54
+ def test_dc_reads_every_value_with_any_attribute_order():
55
+ header = ('<dc:rights xml:lang="pl" xmlns:dc="x">Licencja Wolnej\n Sztuki 1.3</dc:rights>'
56
+ '<dc:rights.license xmlns:dc="x" xml:lang="pl">' + LAL_URL + '</dc:rights.license>')
57
+ assert dc(header, "rights") == ["Licencja Wolnej Sztuki 1.3"]
58
+ assert dc(header, "rights.license") == [LAL_URL]
59
+
60
+
61
+ FOOTER = "\n\n-----\nTa lektura, podobnie jak tysiące innych, jest dostępna w wolnelektury.pl.\n"
62
+ PART = "Adam Mickiewicz\n\nTo lubię\n\nSpojrzyj, Marylo, gdzie się kończą gaje"
63
+ COLLECTION = PART + "\n\nŚwiteź\n\nKto ty jesteś, młody panie"
64
+
65
+
66
+ def test_a_part_does_not_match_the_collection_that_starts_with_it():
67
+ books = {"to-lubie": PART + FOOTER, "ballady": COLLECTION + FOOTER}
68
+ rows = [{"id": "part", "text": PART}, {"id": "whole", "text": COLLECTION}]
69
+ assert match(rows, books, books, {}) == {"part": ("exact", ["to-lubie"]), "whole": ("exact", ["ballady"])}
70
+
71
+
72
+ def test_an_exact_match_to_a_collection_and_its_identical_part_keeps_the_part():
73
+ books = {"ballady": PART + FOOTER, "to-lubie": PART + FOOTER, "inne": PART + FOOTER}
74
+ assert match([{"id": "r", "text": PART}], books, books, {"ballady": {"to-lubie"}}) == {
75
+ "r": ("exact", ["inne", "to-lubie"])}
76
+
77
+
78
+ def test_match_ignores_whitespace_and_needs_both_ends():
79
+ body = "Autor\r\n\r\nTytuł\r\n\r\n" + " ".join(f"słowo{i}" for i in range(400))
80
+ heads = {"same": body + FOOTER, "edited": body.replace("słowo399", "słowo-399") + FOOTER}
81
+ row = {"id": "r", "text": " \n".join(body.split())}
82
+ assert match([row], {slug: text[:3000] for slug, text in heads.items()}, heads, {}) == {
83
+ "r": ("exact", ["same"])}
84
+
85
+
86
+ def _words(start, stop):
87
+ return " ".join(f"wyraz{i}" for i in range(start, stop))
88
+
89
+
90
+ def test_fuzzy_match_places_a_text_edited_at_both_ends():
91
+ book = "Autor\n\nTytuł\n\n" + _words(0, 800)
92
+ row = book.replace("wyraz3 ", "wyraz-3 ").replace("wyraz797", "wyraz797,") + " Koniec"
93
+ books = {"book": book + FOOTER, "other": "Autor\n\nInny\n\n" + _words(5000, 5800) + FOOTER}
94
+ assert match([{"id": "r", "text": row}], books, books, {}) == {"r": ("fuzzy", ["book"])}
95
+
96
+
97
+ def test_fuzzy_match_prefers_the_part_and_never_takes_a_collection_that_only_starts_with_it():
98
+ part = "Autor\n\nCzęść\n\n" + _words(0, 400)
99
+ row = part.replace("wyraz2 ", "wyraz-2 ") + " Koniec"
100
+ one_part = "Zbiór\n\n" + part # a collection of one part: both ends qualify
101
+ longer = part + " " + _words(1000, 1000 + FUZZY_CHARS + FUZZY_SLACK) # only its head qualifies
102
+ books = {"part": part + FOOTER, "one-part": one_part + FOOTER, "longer": longer + FOOTER}
103
+ parts = {"one-part": {"part"}, "longer": {"part", "rest"}}
104
+ assert match([{"id": "r", "text": row}], books, books, parts) == {"r": ("fuzzy", ["part"])}
105
+ del books["part"] # with the part gone, the one-part collection is the text's own book
106
+ assert match([{"id": "r", "text": row}], books, books, parts) == {"r": ("fuzzy", ["one-part"])}
107
+ del books["one-part"]
108
+ assert match([{"id": "r", "text": row}], books, books, parts) == {"r": ("fuzzy", [])}
109
+
110
+
111
+ def test_shares_of_a_text_under_k_words_is_empty():
112
+ assert _shares("trzy krótkie słowa", {}) == {}
113
+
114
+
115
+ def _cache(tmp_path, books):
116
+ for part in ("hdr", "head", "tail"):
117
+ (tmp_path / part).mkdir()
118
+ for slug, (text, rights) in books.items():
119
+ (tmp_path / "head" / f"{slug}.txt").write_text(text + FOOTER, encoding="utf-8")
120
+ (tmp_path / "tail" / f"{slug}.txt").write_text(text + FOOTER, encoding="utf-8")
121
+ (tmp_path / "hdr" / f"{slug}.rdf").write_text(f"<dc:rights>{rights}</dc:rights>", encoding="utf-8")
122
+ return tmp_path
123
+
124
+
125
+ def test_label_rows_takes_each_texts_own_licence(tmp_path):
126
+ cache = _cache(tmp_path, {"to-lubie": (PART, "Domena publiczna - Adam Mickiewicz zm. 1855"),
127
+ "ballady": (COLLECTION, "Licencja Wolnej Sztuki 1.3")})
128
+ out, problems = label_rows([{"id": "r1", "text": PART}, {"id": "r2", "text": COLLECTION}], cache)
129
+ assert problems == []
130
+ assert [(r["id"], r["slug"], r["license"]) for r in out] == [("r1", "to-lubie", PUBLIC_DOMAIN),
131
+ ("r2", "ballady", LAL)]
132
+
133
+
134
+ def test_label_rows_fails_closed(tmp_path):
135
+ cache = _cache(tmp_path, {"a": (PART, "Licencja Wolnej Sztuki 1.3"), "b": (PART, "Domena publiczna"),
136
+ "c": (COLLECTION, "CC BY-SA")})
137
+ rows = [{"id": "twins", "text": PART}, {"id": "unversioned", "text": COLLECTION},
138
+ {"id": "missing", "text": "Nieznany tekst"}]
139
+ out, problems = label_rows(rows, cache)
140
+ assert out == []
141
+ assert [line.split(":")[0] for line in problems] == ["twins", "unversioned", "missing"]
142
+
143
+
144
+ def test_identical_texts_with_one_licence_keep_both_slugs(tmp_path):
145
+ cache = _cache(tmp_path, {"a": (PART, "Domena publiczna"), "b": (PART, "Domena publiczna - XIX w.")})
146
+ out, problems = label_rows([{"id": "r", "text": PART}], cache)
147
+ assert problems == [] and out[0]["slug"] == "a b" and out[0]["license"] == PUBLIC_DOMAIN
148
+
149
+
150
+ def test_manual_rows_take_the_named_books_licence_and_stale_entries_fail(tmp_path, monkeypatch):
151
+ cache = _cache(tmp_path, {"to-lubie": (PART, "Domena publiczna - Adam Mickiewicz zm. 1855"),
152
+ "cykl": ("", "Licencja Wolnej Sztuki 1.3")})
153
+ (cache / "head" / "cykl.txt").unlink() # a collection: header, no txt
154
+ (cache / "tail" / "cykl.txt").unlink()
155
+ monkeypatch.setitem(MANUAL, "merged", "cykl")
156
+ monkeypatch.setitem(MANUAL, "stale", "cykl")
157
+ rows = [{"id": "merged", "text": "Tekst, którego nic nie zawiera"}, {"id": "stale", "text": PART}]
158
+ out, problems = label_rows(rows, cache)
159
+ assert [(r["id"], r["slug"], r["match"], r["license"]) for r in out] == [("merged", "cykl", "manual", LAL)]
160
+ assert problems == ["stale: in MANUAL but matches ['to-lubie']"]
161
+
162
+
163
+ def test_unlicensed_rows_are_left_out_until_they_label_cleanly(tmp_path, monkeypatch):
164
+ cache = _cache(tmp_path, {"to-lubie": (PART, "Domena publiczna - Adam Mickiewicz zm. 1855"),
165
+ "ballady": (COLLECTION, "CC BY-SA")})
166
+ monkeypatch.setattr(wolne_lektury_licences, "UNLICENSED", {"unversioned", "now-clean"})
167
+ rows = [{"id": "unversioned", "text": COLLECTION}, {"id": "now-clean", "text": PART}]
168
+ out, problems = label_rows(rows, cache)
169
+ assert out == []
170
+ assert problems == ["now-clean: in UNLICENSED but labels as {'public-domain'}"]
171
+
172
+
173
+ def test_fetch_takes_media_urls_from_the_api_entry(tmp_path, monkeypatch):
174
+ for part in ("hdr", "head", "tail"):
175
+ (tmp_path / part).mkdir()
176
+ api = wolne_lektury_licences.API
177
+ bodies = {f"{api}slug/": json.dumps({"xml": "https://x/media/other.xml", "txt": "https://x/media/other.txt"}),
178
+ "https://x/media/other.xml": "<rdf:RDF><dc:rights>Domena publiczna</dc:rights></rdf:RDF><utwor>",
179
+ "https://x/media/other.txt": "Autor\n\nTytuł"}
180
+ monkeypatch.setattr(wolne_lektury_licences, "_get", lambda url, byte_range=None: bodies[url].encode())
181
+ monkeypatch.setattr(wolne_lektury_licences.time, "sleep", lambda seconds: None)
182
+ _fetch_book(tmp_path, "slug")
183
+ assert (tmp_path / "hdr" / "slug.rdf").read_text() == "<rdf:RDF><dc:rights>Domena publiczna</dc:rights></rdf:RDF>"
184
+ assert (tmp_path / "head" / "slug.txt").read_text() == (tmp_path / "tail" / "slug.txt").read_text() == "Autor\n\nTytuł"
src/wolne_lektury_licences.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Per-row licence for wolne_lektury from each text's own Wolne Lektury metadata (polish-dynaword-v2#57).
3
+
4
+ Through v0.2.5 every row was labelled `CC-BY-SA-4.0 / Wolna Sztuka 1.3`. Wolne Lektury licenses each
5
+ text separately: most are public domain, the rest are under the Free Art Licence 1.3 (Licencja Wolnej
6
+ Sztuki) or CC BY-SA 3.0 / 4.0. The licence is in the `dc:rights` / `dc:rights.license` fields of the
7
+ book's XML header, which this script reads for every book in the catalogue (/api/books/).
8
+
9
+ A row is matched to its book by text, not by title: titles repeat (untitled poems "***", tomes of one
10
+ novel). The shard text is Wolne Lektury's txt export without its footer, so a row matches a book
11
+ exactly when the book's txt starts with the row's first HEAD_CHARS characters and, footer cut, ends
12
+ with its last TAIL_CHARS characters (whitespace collapsed). Wolne Lektury has edited some texts since
13
+ the scrape (spelling, brackets, a changed opening line); a row with no exact match matches a book
14
+ whose head and ending each hold FUZZY_MIN of the word shingles of the row's own opening and ending.
15
+ Both ends matter: a collection's txt starts like its first part, and a part must not take the
16
+ collection's licence (Boy-Żeleński's Proust tomes are public domain under a CC BY-SA 3.0 parent; see
17
+ the #57 thread), so a collection drops out when one of its parts also matches. The few rows neither
18
+ rule places are in MANUAL, each checked by hand.
19
+
20
+ Downloads (HTTP Range: the RDF header of each XML, the first and last bytes of each txt) go to --cache
21
+ and are reused. Output: data/wolne_lektury/wolne_lektury.licences.tsv, read by clean_wolne_lektury.py.
22
+ python3 src/wolne_lektury_licences.py --cache ~/speakleash/wolne_lektury_meta
23
+ """
24
+ from __future__ import annotations
25
+
26
+ import argparse
27
+ import concurrent.futures as cf
28
+ import csv
29
+ import json
30
+ import re
31
+ import time
32
+ import urllib.error
33
+ import urllib.request
34
+ from collections import Counter, defaultdict
35
+ from pathlib import Path
36
+
37
+ import pyarrow.parquet as pq
38
+
39
+ from shingle_containment import shingles, strip_wl_footer
40
+
41
+ SOURCE = "wolne_lektury"
42
+ ROOT = Path(__file__).resolve().parents[1]
43
+ DATA = ROOT / "data" / SOURCE
44
+ LICENCES = f"{SOURCE}.licences.tsv"
45
+ FIELDS = ["id", "slug", "match", "license", "wl_rights", "wl_license_url"]
46
+ API = "https://wolnelektury.pl/api/books/"
47
+ UA = "polish-dynaword-rights-audit/1.0 (+https://huggingface.co/datasets/SlayerLab/polish-dynaword)"
48
+ HEAD_BYTES, TAIL_BYTES = 3072, 16384 # the tail holds the text's end and the footer (< 3,000 chars)
49
+ HEAD_CHARS, TAIL_CHARS = 600, 300
50
+ INDEX_CHARS = 120
51
+ # Fuzzy match: the row's first and last FUZZY_CHARS characters against the book's head and its last
52
+ # FUZZY_CHARS + FUZZY_SLACK characters. On the v0.2.5 shard the 332 rows placed this way score 0.66 or
53
+ # more at both ends against their own book, and no other book scores above 0.04.
54
+ FUZZY_CHARS, FUZZY_SLACK, FUZZY_MIN = 1500, 500, 0.6
55
+ # Polish copyright runs 70 years from the end of the author's (or translator's) death year.
56
+ PD_DEATH_BY = 1955
57
+
58
+ PUBLIC_DOMAIN = "public-domain"
59
+ LAL = "LAL-1.3"
60
+ CC_BY_SA_3_PL = "CC-BY-SA-3.0-PL"
61
+ CC_BY_SA_3 = "CC-BY-SA-3.0"
62
+ CC_BY_SA_4 = "CC-BY-SA-4.0"
63
+ LABELS = (PUBLIC_DOMAIN, LAL, CC_BY_SA_3_PL, CC_BY_SA_3, CC_BY_SA_4)
64
+
65
+ # Rows whose book Wolne Lektury has merged or reworked past what `match` accepts (their own book scores
66
+ # 0.29-0.54, or they are parts of a merged book), each checked by hand against the current text. The
67
+ # licence still comes from the named book's own header.
68
+ MANUAL = {
69
+ # the prologue and the ten days of the Decameron, now one book (Edward Boyé's translation)
70
+ **{f"wolne_lektury_{n}": "boccaccio-dekameron" for n in range(2373120, 2373131)},
71
+ # the whole cycle, which has no txt export; each of its 11 poems is ~90% contained in the row
72
+ "wolne_lektury_2371820": "lesmian-w-malinowym-chrusniaku-cykl",
73
+ "wolne_lektury_2372184": "aleksander-dumas-trzej-muszkieterowie-tom-2", # spelling, both ends
74
+ "wolne_lektury_2372202": "antoniewicz-gdzie-bluszcz-po-zimnym-grobie-sie-wije", # spelling modernised
75
+ "wolne_lektury_2372206": "antoniewicz-lecz-jakze-prozne-sa-wszystkie-nadzieje", # spelling modernised
76
+ "wolne_lektury_2372684": "bielany", # Antoniewicz, spelling modernised
77
+ "wolne_lektury_2372321": "baczynski-1942-1943-1944-motto-i-dedykacja", # dedication now a footnote
78
+ }
79
+
80
+ # Rows whose Wolne Lektury metadata gives no usable licence. The maintainer chose (2026-10-07) to drop them
81
+ # rather than take a label from their collection; src/clean_wolne_lektury.py does. A row here that comes to
82
+ # label cleanly fails the run, so the drop is reviewed again.
83
+ UNLICENSED = {
84
+ # Horace, tr. Paweł Kozioł: "Domena publiczna - Marceli Motty zm. 1898; CC BY-SA - Paweł Kozioł"
85
+ "wolne_lektury_2373187", # do-manliusa-torkwata
86
+ # Horace, tr. Paweł Kozioł: "CC BY-SA" with no version or URL; its WL footer says public domain
87
+ "wolne_lektury_2373208", # do-taliarcha
88
+ }
89
+
90
+
91
+ def normalise(text: str) -> str:
92
+ return " ".join(text.lstrip("").split())
93
+
94
+
95
+ def dc(header: str, name: str) -> list[str]:
96
+ """Values of one Dublin Core element, whitespace collapsed."""
97
+ pattern = rf"<dc:{re.escape(name)}\b[^>]*>(.*?)</dc:{re.escape(name)}>"
98
+ return [" ".join(value.split()) for value in re.findall(pattern, header, re.S)]
99
+
100
+
101
+ def classify(rights: str, urls: list[str]) -> str | None:
102
+ """The row label for a book's dc:rights and dc:rights.license values; None when they do not fit
103
+ exactly one licence (then the row needs a hand check)."""
104
+ text = " ".join([rights, *urls]).casefold()
105
+ found = set()
106
+ if "artlibre.org/licence/lal" in text or "wolnej sztuki 1.3" in text:
107
+ found.add(LAL)
108
+ if "by-sa/4.0" in text or "na tych samych warunkach 4.0" in text:
109
+ found.add(CC_BY_SA_4)
110
+ if "by-sa/3.0" in text or "na tych samych warunkach 3.0" in text:
111
+ found.add(CC_BY_SA_3_PL if re.search(r"3\.0[ .]*pl\b|/3\.0/pl", text) else CC_BY_SA_3)
112
+ if ("cc by" in text or "creative commons" in text) and not found - {LAL}:
113
+ return None # a Creative Commons licence without a version
114
+ if text.startswith("domena publiczna") or re.search(r"\bzm\.", text):
115
+ # any later year (a death "zm.1960", "zm. w 1960", "(1960)", an edition) needs a hand check
116
+ if any(int(year) > PD_DEATH_BY for year in re.findall(r"\b\d{4}\b", text)):
117
+ return None
118
+ found.add(PUBLIC_DOMAIN)
119
+ return found.pop() if len(found) == 1 else None
120
+
121
+
122
+ def _get(url: str, byte_range: str | None = None) -> bytes | None:
123
+ """`url`'s body, or the part named by an HTTP byte range such as "0-99" or "-100"; None on 404."""
124
+ headers = {"User-Agent": UA} | ({"Range": f"bytes={byte_range}"} if byte_range else {})
125
+ request = urllib.request.Request(url, headers=headers)
126
+ for attempt in range(4):
127
+ try:
128
+ with urllib.request.urlopen(request, timeout=60) as response:
129
+ return response.read()
130
+ except urllib.error.HTTPError as error:
131
+ if error.code == 404:
132
+ return None
133
+ failure = error
134
+ except OSError as error:
135
+ failure = error
136
+ time.sleep(5 * (attempt + 1))
137
+ raise SystemExit(f"{url}: {failure!r}")
138
+
139
+
140
+ def _fetch_book(cache: Path, slug: str) -> None:
141
+ rdf = cache / "hdr" / f"{slug}.rdf"
142
+ txts = [(cache / part / f"{slug}.txt", byte_range)
143
+ for part, byte_range in (("head", f"0-{HEAD_BYTES - 1}"), ("tail", f"-{TAIL_BYTES}"))]
144
+ if rdf.exists() and all(path.exists() for path, _ in txts):
145
+ return
146
+ # The media files are usually named after the slug, but not always (Korczak's "Dziecko w rodzinie"
147
+ # is dziecko-w-rodzinie.xml), so take their URLs from the book's API entry.
148
+ book = json.loads(_get(f"{API}{slug}/") or b"{}")
149
+ if not rdf.exists() and book.get("xml"):
150
+ header = (_get(book["xml"], "0-131071") or b"").decode("utf-8", "ignore")
151
+ if "</rdf:RDF>" in header:
152
+ rdf.write_text(header[: header.index("</rdf:RDF>") + len("</rdf:RDF>")], encoding="utf-8")
153
+ for path, byte_range in txts:
154
+ if not path.exists() and book.get("txt"): # collections have no txt export
155
+ data = _get(book["txt"], byte_range)
156
+ if data is not None:
157
+ path.write_text(data.decode("utf-8", "ignore"), encoding="utf-8")
158
+ time.sleep(0.15)
159
+
160
+
161
+ def fetch(cache: Path, workers: int) -> None:
162
+ """Download the catalogue and each book's header and txt head and tail into `cache`."""
163
+ for part in ("hdr", "head", "tail"):
164
+ (cache / part).mkdir(parents=True, exist_ok=True)
165
+ catalogue = cache / "books.json"
166
+ if not catalogue.exists():
167
+ catalogue.write_bytes(_get(API))
168
+ slugs = [book["slug"] for book in json.loads(catalogue.read_text(encoding="utf-8"))]
169
+ with cf.ThreadPoolExecutor(workers) as pool:
170
+ list(pool.map(lambda slug: _fetch_book(cache, slug), slugs))
171
+
172
+
173
+ def _shingle_index(texts: dict[str, str]) -> dict[int, list[str]]:
174
+ index = defaultdict(list)
175
+ for slug, text in texts.items():
176
+ for shingle in shingles(text).tolist():
177
+ index[shingle].append(slug)
178
+ return index
179
+
180
+
181
+ def _shares(text: str, index: dict[int, list[str]]) -> dict[str, float]:
182
+ """Slug -> share of the text's word shingles found in that book's indexed text."""
183
+ own = shingles(text).tolist()
184
+ if not own: # under K words
185
+ return {}
186
+ counts = Counter(slug for shingle in own for slug in index.get(shingle, ()))
187
+ return {slug: count / len(own) for slug, count in counts.items()}
188
+
189
+
190
+ def _without_collections(hits: list[str], parts: dict[str, set[str]]) -> list[str]:
191
+ """`hits` less any collection one of whose parts is also a hit: the part's licence is the text's."""
192
+ return [slug for slug in hits if not parts.get(slug, set()) & set(hits)]
193
+
194
+
195
+ def match(rows: list[dict], heads: dict[str, str], tails: dict[str, str],
196
+ parts: dict[str, set[str]]) -> dict[str, tuple[str, list[str]]]:
197
+ """Row id -> ("exact" or "fuzzy", slugs). `heads` and `tails` are the cached txt heads and tails,
198
+ `parts` maps a collection's slug to its parts' slugs. Rows that match nothing get ("fuzzy", [])."""
199
+ heads = {slug: normalise(text) for slug, text in heads.items() if slug in tails}
200
+ tails = {slug: normalise(strip_wl_footer(text)) for slug, text in tails.items()}
201
+ index = defaultdict(list)
202
+ for slug, head in heads.items():
203
+ index[head[:INDEX_CHARS]].append(slug)
204
+ found, rest = {}, []
205
+ for row in rows:
206
+ text = normalise(row["text"])
207
+ head, tail = text[:HEAD_CHARS], text[-TAIL_CHARS:]
208
+ candidates = index.get(head[:INDEX_CHARS], ()) if len(head) >= INDEX_CHARS else heads
209
+ hits = sorted(slug for slug in candidates
210
+ if heads[slug].startswith(head) and tails[slug].endswith(tail))
211
+ if hits:
212
+ found[row["id"]] = ("exact", _without_collections(hits, parts))
213
+ else:
214
+ rest.append((row["id"], text))
215
+ if rest:
216
+ head_index = _shingle_index(heads)
217
+ tail_index = _shingle_index({slug: tail[-(FUZZY_CHARS + FUZZY_SLACK):] for slug, tail in tails.items()})
218
+ for row_id, text in rest:
219
+ head = _shares(text[:FUZZY_CHARS], head_index)
220
+ tail = _shares(text[-FUZZY_CHARS:], tail_index)
221
+ hits = [slug for slug, share in head.items() if share >= FUZZY_MIN and tail.get(slug, 0) >= FUZZY_MIN]
222
+ found[row_id] = ("fuzzy", _without_collections(sorted(hits), parts))
223
+ return found
224
+
225
+
226
+ def _read_dir(folder: Path, suffix: str = ".txt") -> dict[str, str]:
227
+ return {path.stem: path.read_text(encoding="utf-8") for path in sorted(folder.glob(f"*{suffix}"))}
228
+
229
+
230
+ def label_rows(rows: list[dict], cache: Path) -> tuple[list[dict], list[str]]:
231
+ """One output record per row, and a line per row that needs a hand check."""
232
+ headers = _read_dir(cache / "hdr", ".rdf")
233
+ parts = {slug: {url.rstrip("/").rsplit("/", 1)[-1] for url in dc(header, "relation.hasPart")}
234
+ for slug, header in headers.items()}
235
+ matches = match(rows, _read_dir(cache / "head"), _read_dir(cache / "tail"), parts)
236
+ out, problems = [], []
237
+ for row in rows:
238
+ how, hits = matches[row["id"]]
239
+ if row["id"] in MANUAL:
240
+ if hits: # the text matches again; the hand entry is stale
241
+ problems.append(f"{row['id']}: in MANUAL but matches {hits}")
242
+ continue
243
+ how, hits = "manual", [MANUAL[row["id"]]]
244
+ found = {}
245
+ for slug in hits:
246
+ header = headers.get(slug, "")
247
+ rights, urls = " | ".join(dc(header, "rights")), dc(header, "rights.license")
248
+ found[slug] = (classify(rights, urls), rights, " ".join(urls))
249
+ labels = {label for label, _, _ in found.values()}
250
+ unusable = not hits or None in labels or len(labels) > 1 # identical texts must agree on the licence
251
+ if row["id"] in UNLICENSED:
252
+ if not unusable:
253
+ problems.append(f"{row['id']}: in UNLICENSED but labels as {labels}")
254
+ continue
255
+ if unusable:
256
+ problems.append(f"{row['id']}: {found or 'no book'}")
257
+ continue
258
+ label, rights, urls = found[hits[0]]
259
+ out.append({"id": row["id"], "slug": " ".join(hits), "match": how, "license": label,
260
+ "wl_rights": rights, "wl_license_url": urls})
261
+ return out, problems
262
+
263
+
264
+ def build(input_path: Path, cache: Path, out_dir: Path) -> Counter:
265
+ rows = pq.read_table(input_path, columns=["id", "text"]).to_pylist()
266
+ out, problems = label_rows(rows, cache)
267
+ if problems:
268
+ raise SystemExit(f"{len(problems)} rows need a hand check:\n" + "\n".join(problems))
269
+ with (out_dir / LICENCES).open("w", encoding="utf-8", newline="") as handle:
270
+ writer = csv.DictWriter(handle, FIELDS, delimiter="\t", lineterminator="\n")
271
+ writer.writeheader()
272
+ writer.writerows(out)
273
+ return Counter(row["license"] for row in out)
274
+
275
+
276
+ def main() -> None:
277
+ parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
278
+ parser.add_argument("--input", type=Path, default=DATA / f"{SOURCE}.parquet")
279
+ parser.add_argument("--cache", type=Path, required=True)
280
+ parser.add_argument("--out", type=Path, default=DATA)
281
+ parser.add_argument("--workers", type=int, default=4)
282
+ parser.add_argument("--offline", action="store_true", help="use the cache as is; download nothing")
283
+ args = parser.parse_args()
284
+ cache = args.cache.expanduser()
285
+ if not args.offline:
286
+ fetch(cache, args.workers)
287
+ print(json.dumps(build(args.input, cache, args.out), indent=2))
288
+
289
+
290
+ if __name__ == "__main__":
291
+ main()