ppuzio commited on
Commit
563eea8
·
1 Parent(s): 3bab9f9

wolne_lektury: drop 63 docs that duplicate eltec_pol novels (6,141 -> 6,078 docs) (#67)

Browse files

- wolne_lektury: drop 63 docs that duplicate eltec_pol novels (v2#72) (dd905112dfe019283014a7cc537e25c1cd3cc0e2)
- Merge origin/main (global_voices #66) into v026-wolne_lektury-dedup (6eab276752cb81998c6dfff6674ba434bad70cb6)
- Merge origin/main (1000_novels rescreen, PR 65) into v026-wolne_lektury-dedup (e8f6722a3fdfb0fcea8e5f120cee689752ceac2c)
- wolne_lektury: move the containment code to src/shingle_containment.py (0783e5eb1e2eda3aab5edd4f76c7f85910e7ff3d)

artifacts/source_findings.md CHANGED
@@ -1480,3 +1480,43 @@ unresolved, so the release keeps 887 texts and drops 18 in copyright and 95 unre
1480
  `src/clean_1000_novels.py` pins the screen CSV by SHA-256
1481
  (`7fefc75f8fcbd07e5ec98842276765ffef9520b6acb4e24b4751c67cc3d2081c`, also in
1482
  `1000_novels.license-evidence.json`).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1480
  `src/clean_1000_novels.py` pins the screen CSV by SHA-256
1481
  (`7fefc75f8fcbd07e5ec98842276765ffef9520b6acb4e24b4751c67cc3d2081c`, also in
1482
  `1000_novels.license-evidence.json`).
1483
+
1484
+ ## wolne_lektury — eltec_pol duplicates dropped (2026-10-06)
1485
+
1486
+ **Verdict** — kept, 63 documents dropped: 6,141 → 6,078 documents, 103,009,797 →
1487
+ 90,654,820 tokens (input: the v0.2.5 Parquet, unchanged since v0.2.1). Each dropped
1488
+ document is a novel, or one tome of a novel, that `eltec_pol` also carries. 50 ELTeC
1489
+ novels are concerned, and `eltec_pol` stays whole (maintainer decision A,
1490
+ polish-dynaword-v2 #72). The filter is `src/clean_wolne_lektury.py` and the pair list is
1491
+ `data/wolne_lektury/wolne_lektury.eltec_pairs.tsv`.
1492
+ - Score: the share of a WL document's 5-word shingles found in the ELTeC novel that
1493
+ shares the most with it. Tokenisation follows `near_dedup`, and a trailing WL footer is
1494
+ cut first (no WL row has one). Containment is used, not Jaccard, because WL splits
1495
+ novels into tomes: Chłopi has 4, Faraon, Nad Niemnem and Stara baśń have 3.
1496
+ - Threshold 0.9, in an empty stretch: no document scores between 0.7588 and 0.9636. All
1497
+ 63 documents above it pair with an ELTeC novel by the same author and title (Żuławski's
1498
+ two WL documents are headed with the trilogy's title).
1499
+ - Hand-checked: all 3 documents between 0.3 and 0.9, the 3 between 0.9 and 0.99, and 10
1500
+ sampled at ≥ 0.99 (seed 72). In 12 of the 13 drops checked, the unmatched shingles
1501
+ form short scattered runs of at most 27 words (title head, spelling variants). The
1502
+ exception is Dzieje grzechu (0.9879): its WL copy ends with a "Dodatek" of draft
1503
+ chapters, about 1,800 words that ELTeC lacks. It is dropped with the novel.
1504
+ - Kept and listed as `keep_partial`: both WL tomes of Mniszek's Trędowata (0.7588 and
1505
+ 0.6473 against POL0051). The ELTeC text is shorter: about 121,000 words against WL's
1506
+ 162,000. 95% of the ELTeC shingles are in WL's tomes, and the WL text missing from
1507
+ ELTeC comes in runs of up to 5,418 words. The shared part stays duplicated across the
1508
+ two sources. Also kept: Kochanowski's Pieśń IX from Pieśni, księgi wtóre (0.4267),
1509
+ which Łoziński's Oko proroka quotes.
1510
+ - Below 0.3 (not listed, not dropped): 6 documents at 0.10–0.22, all poems of at most
1511
+ 2,321 tokens by Mickiewicz, Kochanowski and Miciński; their overlap with the paired
1512
+ novels was not inspected. Nothing scores between 0.2203 and 0.4267.
1513
+
1514
+ **Reason** — 51 of the 100 ELTeC novels duplicate WL texts. ELTeC's CC BY 4.0 licence
1515
+ is the clean one (`rights_audit_2026-10/reports/literary.md`: eltec_pol CLEAN). WL
1516
+ licence labels are not touched here; #57 relabels them per row.
1517
+
1518
+ References: polish-dynaword-v2 #72 (decision), #45 (method);
1519
+ `rights_audit_2026-10/literary/eltec_meta.tsv` (ELTeC file names and titles).
1520
+
1521
+ **Lesson** — Jaccard near-dedup misses a novel that one source splits into tomes.
1522
+ Measure containment from the split side.
data/wolne_lektury/wolne_lektury.eltec_pairs.tsv ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ wl_id eltec_id score action wl_title
2
+ wolne_lektury_2372617 eltec_pol_2455238 0.9995 drop Wacław Berent / Ozimina
3
+ wolne_lektury_2372618 eltec_pol_2455239 0.9997 drop Wacław Berent / Próchno
4
+ wolne_lektury_2373135 eltec_pol_2455240 0.9921 drop Deotyma / Branki w jasyrze
5
+ wolne_lektury_2373136 eltec_pol_2455241 0.9986 drop Deotyma / Panienka z okienka
6
+ wolne_lektury_2372152 eltec_pol_2455242 0.9998 drop Deotyma / Zwierciadlana zagadka
7
+ wolne_lektury_2374432 eltec_pol_2455246 0.9981 drop Tadeusz Dołęga-Mostowicz / Kariera Nikodema Dyzmy
8
+ wolne_lektury_2373182 eltec_pol_2455247 0.9999 drop Pamiętnik pani Hanki / Tadeusz Dołęga-Mostowicz
9
+ wolne_lektury_2372109 eltec_pol_2455248 0.9984 drop Tadeusz Dołęga-Mostowicz / Znachor
10
+ wolne_lektury_2374147 eltec_pol_2455249 0.9985 drop Antonina Domańska / Historia żółtej ciżemki
11
+ wolne_lektury_2374899 eltec_pol_2455250 0.9985 drop Antonina Domańska / Krysia bezimienna
12
+ wolne_lektury_2376177 eltec_pol_2455251 0.9981 drop Antonina Domańska / Paziowie
13
+ wolne_lektury_2373959 eltec_pol_2455258 0.9955 drop Stefan Grabiński / Namiętność
14
+ wolne_lektury_2376971 eltec_pol_2455259 0.9977 drop Stefan Grabiński / Salamandra
15
+ wolne_lektury_2373979 eltec_pol_2455260 0.9981 drop Stefan Grabiński / Wyspa Itongo
16
+ wolne_lektury_2374400 eltec_pol_2455262 0.9636 drop Zygmunt Kaczkowski / Murdelio
17
+ wolne_lektury_2374184 eltec_pol_2455267 0.9984 drop Józef Ignacy Kraszewski / Hrabina Cosel
18
+ wolne_lektury_2376438 eltec_pol_2455268 0.9980 drop Józef Ignacy Kraszewski / Pogrobek
19
+ wolne_lektury_2377370 eltec_pol_2455269 0.9984 drop Józef Ignacy Kraszewski / Stara baśń
20
+ wolne_lektury_2377371 eltec_pol_2455269 0.9983 drop Józef Ignacy Kraszewski / Stara baśń
21
+ wolne_lektury_2377372 eltec_pol_2455269 0.9983 drop Józef Ignacy Kraszewski / Stara baśń
22
+ wolne_lektury_2375201 eltec_pol_2455275 0.9974 drop Władysław Łoziński / Oko proroka
23
+ wolne_lektury_2376242 eltec_pol_2455275 0.4267 keep_partial Jan Kochanowski / Pieśni, Księgi wtóre
24
+ wolne_lektury_2375475 eltec_pol_2455281 0.7588 keep_partial Tom pierwszy / I
25
+ wolne_lektury_2375476 eltec_pol_2455281 0.6473 keep_partial Helena Mniszek / Trędowata
26
+ wolne_lektury_2375490 eltec_pol_2455283 0.9966 drop Zuzanna Morawska / Na zgliszczach Zakonu
27
+ wolne_lektury_2375491 eltec_pol_2455284 0.9966 drop Zuzanna Morawska / Wilcze gniazdo
28
+ wolne_lektury_2375933 eltec_pol_2455285 0.9999 drop Eliza Orzeszkowa / Marta
29
+ wolne_lektury_2375340 eltec_pol_2455286 0.9993 drop Eliza Orzeszkowa / Meir Ezofowicz
30
+ wolne_lektury_2375558 eltec_pol_2455287 0.9994 drop Eliza Orzeszkowa / Nad Niemnem
31
+ wolne_lektury_2375559 eltec_pol_2455287 0.9992 drop Eliza Orzeszkowa / Nad Niemnem
32
+ wolne_lektury_2375560 eltec_pol_2455287 0.9995 drop Eliza Orzeszkowa / Nad Niemnem
33
+ wolne_lektury_2373434 eltec_pol_2455291 0.9974 drop Bolesław Prus / Emancypantki
34
+ wolne_lektury_2373439 eltec_pol_2455292 0.9979 drop Bolesław Prus / Faraon
35
+ wolne_lektury_2373440 eltec_pol_2455292 0.9972 drop Bolesław Prus / Faraon
36
+ wolne_lektury_2373441 eltec_pol_2455292 0.9981 drop Bolesław Prus / Faraon
37
+ wolne_lektury_2375026 eltec_pol_2455293 0.9988 drop Bolesław Prus / Lalka
38
+ wolne_lektury_2375027 eltec_pol_2455293 0.9982 drop Bolesław Prus / Lalka
39
+ wolne_lektury_2372954 eltec_pol_2455294 0.9990 drop Władysław Stanisław Reymont / Chłopi
40
+ wolne_lektury_2372955 eltec_pol_2455294 0.9989 drop Władysław Stanisław Reymont / Chłopi
41
+ wolne_lektury_2372956 eltec_pol_2455294 0.9992 drop Władysław Stanisław Reymont / Chłopi
42
+ wolne_lektury_2376750 eltec_pol_2455294 0.9990 drop Władysław Stanisław Reymont / Chłopi
43
+ wolne_lektury_2374612 eltec_pol_2455295 0.9992 drop Władysław Stanisław Reymont / Komediantka
44
+ wolne_lektury_2372093 eltec_pol_2455296 0.9985 drop Władysław St. Reymont / Ziemia obiecana, tom II
45
+ wolne_lektury_2372094 eltec_pol_2455296 0.9990 drop Władysław St. Reymont / Ziemia obiecana, tom I
46
+ wolne_lektury_2376762 eltec_pol_2455297 0.9977 drop Maria Rodziewiczówna / Lato
47
+ wolne_lektury_2376763 eltec_pol_2455298 0.9985 drop Maria Rodziewiczówna / Między ustami a
48
+ wolne_lektury_2376764 eltec_pol_2455299 0.9984 drop Maria Rodziewiczówna / Straszny dziadunio
49
+ wolne_lektury_2375871 eltec_pol_2455300 0.9983 drop Henryk Sienkiewicz / Ogniem i mieczem
50
+ wolne_lektury_2375872 eltec_pol_2455300 0.9981 drop Henryk Sienkiewicz / Ogniem i mieczem
51
+ wolne_lektury_2376691 eltec_pol_2455301 0.9970 drop Henryk Sienkiewicz / Quo vadis
52
+ wolne_lektury_2376766 eltec_pol_2455302 0.9983 drop Henryk Sienkiewicz / Rodzina Połanieckich
53
+ wolne_lektury_2377398 eltec_pol_2455303 0.9998 drop Andrzej Strug / Dzieje jednego pocisku
54
+ wolne_lektury_2377720 eltec_pol_2455307 0.9899 drop Aleksander Świętochowski / Tragikomedya prawdy
55
+ wolne_lektury_2371802 eltec_pol_2455316 0.9991 drop Stanisław Ignacy Witkiewicz / Nienasycenie
56
+ wolne_lektury_2371803 eltec_pol_2455316 0.9988 drop Stanisław Ignacy Witkiewicz / Nienasycenie
57
+ wolne_lektury_2371806 eltec_pol_2455317 0.9993 drop Stanisław Ignacy Witkiewicz / Pożegnanie jesieni
58
+ wolne_lektury_2372038 eltec_pol_2455318 0.9999 drop Gabriela Zapolska / Kaśka Kariatyda
59
+ wolne_lektury_2372039 eltec_pol_2455319 0.9966 drop Gabiela Zapolska / Kobieta bez skazy
60
+ wolne_lektury_2377058 eltec_pol_2455320 0.9981 drop Gabriela Zapolska / Sezonowa miłość
61
+ wolne_lektury_2373356 eltec_pol_2455321 0.9879 drop Stefan Żeromski / Dzieje grzechu
62
+ wolne_lektury_2376559 eltec_pol_2455322 0.9995 drop Stefan Żeromski / Przedwiośnie
63
+ wolne_lektury_2377473 eltec_pol_2455323 0.9985 drop Stefan Żeromski / Syzyfowe prace
64
+ wolne_lektury_2372105 eltec_pol_2455326 0.9989 drop Narcyza Żmichowska / Poganka
65
+ wolne_lektury_2371605 eltec_pol_2455327 0.9988 drop Jerzy Żuławski / Trylogia księżycowa
66
+ wolne_lektury_2372130 eltec_pol_2455328 0.9986 drop Jerzy Żuławski / Powrót
67
+ wolne_lektury_2371607 eltec_pol_2455329 0.9981 drop Jerzy Żuławski / Trylogia księżycowa
data/wolne_lektury/wolne_lektury.md CHANGED
@@ -19,16 +19,19 @@ Pulled from SpeakLeash's public redistribution (`speakleash-ds-pub`, key `wolne_
19
  ## Statistics
20
  | documents | characters | tokens (tiktoken proxy) |
21
  |---:|---:|---:|
22
- | 6,141 | 261,892,000 | 103,009,797 |
23
 
24
 
25
  ## Per-document license metadata
26
  | license | documents |
27
  |---|---:|
28
- | `CC-BY-SA-4.0 / Wolna Sztuka 1.3` | 6,141 |
29
 
30
  Author metadata present for **0** documents. Empty values mean the upstream record did not expose a machine-readable author field.
31
 
 
 
 
32
  Statistics were recomputed directly from the released parquet file.
33
 
34
  ## Filters applied (build_dynaword.py)
@@ -37,7 +40,7 @@ Minimal, per Dynaword guidelines (heavy filtering left to downstream use):
37
  - drop non-Polish (diacritic ratio): **0**
38
  - exact cross-source dedup (sha1): **0**
39
  - OCR alpha-ratio < 0.70 (OCR sources only): **0**
40
- - read 6,141 → kept 6,141
41
 
42
  Token counts are a fast tiktoken (cl100k) proxy (~1% off Llama-3); the canonical
43
  Llama-3 count is computed at release.
 
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
 
37
  ## Filters applied (build_dynaword.py)
 
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.
data/wolne_lektury/wolne_lektury.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:5833c25db296f2479b3c09745ebedd550b2425dd6ebaf021f0095e684a0221a1
3
- size 128562077
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f308d49235551241d6c47c5e88138ba52e6235422ae272ddbc135c3b8696ae0e
3
+ size 113055766
data/wolne_lektury/wolne_lektury.stats.json CHANGED
@@ -1,16 +1,19 @@
1
  {
2
  "read": 6141,
3
- "kept": 6141,
4
  "drop_short": 0,
5
  "drop_lang": 0,
6
  "drop_dup": 0,
7
  "drop_ocr": 0,
8
- "chars": 261892000,
9
- "tokens": 103009797,
10
  "licenses": {
11
- "CC-BY-SA-4.0 / Wolna Sztuka 1.3": 6141
12
  },
13
  "authors_with_value": 0,
14
  "license": "CC-BY-SA-4.0 / Wolna Sztuka 1.3",
15
- "stats_recomputed_from_parquet": true
 
 
 
16
  }
 
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
  }
src/clean_wolne_lektury.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
6
+ licence. Wolne Lektury splits long novels into tomes, so the test is containment, not Jaccard:
7
+
8
+ score = |S(wl) & S(novel)| / |S(wl)|
9
+
10
+ S() is the set of 5-word shingles over NFKC-casefolded \\w+ tokens (the tokenisation of the
11
+ repo's near_dedup), and `novel` is the ELTeC novel sharing the most shingles with the WL doc;
12
+ the shingling and scoring code is in src/shingle_containment.py.
13
+ A trailing Wolne Lektury footer is cut from WL text before scoring (the #45 measurement's rule);
14
+ the released text is not changed. Docs scoring >= DROP_AT are dropped. Docs scoring
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
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import csv
26
+ import hashlib
27
+ import json
28
+ import os
29
+ from collections import Counter
30
+ from pathlib import Path
31
+
32
+ import pyarrow as pa
33
+ 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]
40
+ DATA = ROOT / "data" / SOURCE
41
+ ELTEC = ROOT / "data" / "eltec_pol" / "eltec_pol.parquet"
42
+ INPUT_SHA256 = "5833c25db296f2479b3c09745ebedd550b2425dd6ebaf021f0095e684a0221a1" # v0.2.1-v0.2.5
43
+ ELTEC_SHA256 = "ba40061741dff11165149f6c2cf3d5526e1b6c759e7ce1e03ccc164d58838325" # v0.2.1-v0.2.5
44
+ PAIRS = f"{SOURCE}.eltec_pairs.tsv"
45
+ # Thresholds sit in empty stretches of the v0.2.5 score distribution: no doc scores between
46
+ # 0.7588 and 0.9636 (above: 63 docs, the novels; below: two tomes of an abridged ELTeC
47
+ # Trędowata), and none between 0.2203 and 0.4267 (below: poems quoted in a novel).
48
+ DROP_AT = 0.9
49
+ REPORT_AT = 0.3
50
+
51
+
52
+ def wl_title(text: str) -> str:
53
+ """Author and title: the first two non-empty lines of a Wolne Lektury text."""
54
+ return " / ".join([line.strip() for line in text.splitlines() if line.strip()][:2])
55
+
56
+
57
+ def check_pin(path: Path, expected: str, restore: str) -> None:
58
+ with path.open("rb") as stream:
59
+ if hashlib.file_digest(stream, "sha256").hexdigest() != expected:
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")
67
+ table = pq.read_table(input_path)
68
+ eltec = pq.read_table(eltec_path, columns=["id", "text"])
69
+ texts = table.column("text").to_pylist()
70
+ eltec_ids = eltec.column("id").to_pylist()
71
+ scores = best_containment([strip_wl_footer(t) for t in texts], eltec.column("text").to_pylist())
72
+
73
+ keep, pairs = [], []
74
+ for wl_id, text, (novel, score) in zip(table.column("id").to_pylist(), texts, scores, strict=True):
75
+ keep.append(score < DROP_AT)
76
+ if score >= REPORT_AT:
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
+
98
+ staged = {
99
+ out_dir / f"{SOURCE}.parquet.tmp": lambda p: pq.write_table(kept, p, compression="zstd"),
100
+ out_dir / f"{PAIRS}.tmp": lambda p: _write_pairs(p, pairs),
101
+ out_dir / f"{SOURCE}.stats.json.tmp": lambda p: p.write_text(
102
+ json.dumps(stats, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"),
103
+ }
104
+ for path, write in staged.items():
105
+ write(path)
106
+ for path in staged:
107
+ os.replace(path, path.with_suffix(""))
108
+ return stats
109
+
110
+
111
+ def _write_pairs(path: Path, pairs: list[dict]) -> None:
112
+ with path.open("w", encoding="utf-8", newline="") as handle:
113
+ writer = csv.DictWriter(handle, ["wl_id", "eltec_id", "score", "action", "wl_title"],
114
+ delimiter="\t", lineterminator="\n")
115
+ writer.writeheader()
116
+ writer.writerows(sorted(pairs, key=lambda p: (p["eltec_id"], p["wl_id"])))
117
+
118
+
119
+ 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__":
129
+ main()
src/shingle_containment.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shingle containment between documents and a set of reference documents.
2
+
3
+ Shared by the cross-source dedup filters (src/clean_wolne_lektury.py, src/clean_1000_novels.py).
4
+ S() is the set of K-word shingles over NFKC-casefolded \\w+ tokens, the tokenisation of the repo's
5
+ near_dedup. Containment, not Jaccard: a document is scored by the share of its own shingles that
6
+ a reference holds, because Wolne Lektury splits long novels into tomes.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import re
12
+ import unicodedata
13
+ from functools import lru_cache
14
+ from typing import NamedTuple
15
+
16
+ import numpy as np
17
+
18
+ K = 5
19
+ WORD = re.compile(r"\w+")
20
+ # Odd 64-bit multipliers that mix the K word hashes of a shingle in order.
21
+ MULT = np.array([0x9E3779B97F4A7C15, 0xC2B2AE3D27D4EB4F, 0x165667B19E3779F9,
22
+ 0xD6E8FEB86659FD93, 0xFF51AFD7ED558CCD], dtype=np.uint64)
23
+
24
+
25
+ def strip_wl_footer(text: str) -> str:
26
+ """Text before a trailing "-----" footer that names wolnelektury, else the text unchanged."""
27
+ j = text.rfind("\n-----")
28
+ if j >= 0 and len(text) - j < 5000 and "wolnelektury" in text[j:].lower():
29
+ return text[:j]
30
+ return text
31
+
32
+
33
+ @lru_cache(maxsize=None)
34
+ def _word_hash(word: str) -> int:
35
+ # blake2b, not hash(): str hashing is salted per process, and the scores must be reproducible.
36
+ return int.from_bytes(hashlib.blake2b(word.encode("utf-8"), digest_size=8).digest(), "little")
37
+
38
+
39
+ def shingles(text: str) -> np.ndarray:
40
+ """Sorted unique uint64 hashes of the text's K-word shingles."""
41
+ words = WORD.findall(unicodedata.normalize("NFKC", text).casefold())
42
+ n = len(words) - K + 1
43
+ if n <= 0:
44
+ return np.empty(0, np.uint64)
45
+ h = np.fromiter((_word_hash(w) for w in words), dtype=np.uint64, count=len(words))
46
+ s = np.zeros(n, np.uint64)
47
+ for i in range(K):
48
+ s += h[i:i + n] * MULT[i]
49
+ s ^= s >> np.uint64(31)
50
+ return np.unique(s)
51
+
52
+
53
+ class Match(NamedTuple):
54
+ """How much of one document's shingle set the references hold."""
55
+ shingles: int # unique shingles in the document
56
+ covered: int # of those, how many occur in at least one reference
57
+ refs: np.ndarray # indices of the references sharing at least one shingle, ascending
58
+ shared: np.ndarray # shingles shared with each of those references
59
+
60
+ @property
61
+ def cover(self) -> float:
62
+ """Share of the document's shingles found in any reference (the union of the references)."""
63
+ return self.covered / self.shingles if self.shingles else 0.0
64
+
65
+ def best(self) -> tuple[int, float]:
66
+ """(index of the reference holding most shingles, share it holds); (-1, 0.0) if none."""
67
+ if not len(self.refs):
68
+ return -1, 0.0
69
+ i = int(self.shared.argmax()) # ties go to the lowest reference index
70
+ return int(self.refs[i]), self.shared[i] / self.shingles
71
+
72
+
73
+ def containment(docs: list[str], refs: list[str]) -> list[Match]:
74
+ """Match every doc against all refs at once."""
75
+ sets = [shingles(text) for text in refs] or [np.empty(0, np.uint64)]
76
+ hashes = np.concatenate(sets)
77
+ owner = np.concatenate([np.full(len(s), i, np.int32) for i, s in enumerate(sets)])
78
+ order = np.argsort(hashes, kind="stable")
79
+ hashes, owner = hashes[order], owner[order]
80
+ out = []
81
+ for text in docs:
82
+ a = shingles(text)
83
+ lo, hi = np.searchsorted(hashes, a, "left"), np.searchsorted(hashes, a, "right")
84
+ lens = hi - lo
85
+ # Every (doc shingle, ref) hit: each ref's set is unique, so a shingle counts once per ref.
86
+ idx = np.repeat(lo - np.cumsum(lens) + lens, lens) + np.arange(lens.sum())
87
+ ref_ids, shared = np.unique(owner[idx], return_counts=True)
88
+ out.append(Match(len(a), int((lens > 0).sum()), ref_ids, shared))
89
+ return out
90
+
91
+
92
+ def best_containment(docs: list[str], refs: list[str]) -> list[tuple[int, float]]:
93
+ """For each doc: (index of the ref holding most of its shingles, share held), (-1, 0.0) if none."""
94
+ return [m.best() for m in containment(docs, refs)]
src/sources.py CHANGED
@@ -311,6 +311,13 @@ SOURCES = {
311
  "upstream": "https://wolnelektury.pl/api/books/",
312
  "domain": "literature",
313
  "created": "1500-01-01, 2024-12-31",
 
 
 
 
 
 
 
314
  "is_ocr": False,
315
  },
316
  "wikinews": {
 
311
  "upstream": "https://wolnelektury.pl/api/books/",
312
  "domain": "literature",
313
  "created": "1500-01-01, 2024-12-31",
314
+ "legal_note": "For v0.2.6, 63 documents whose text is an eltec_pol novel are dropped "
315
+ "(share of a document's 5-word shingles found in one ELTeC novel >= 0.9; "
316
+ "src/clean_wolne_lektury.py, polish-dynaword-v2#72). eltec_pol keeps those "
317
+ "50 novels whole under CC BY 4.0. Three documents only partly in an ELTeC "
318
+ "novel are kept: both tomes of Mniszek's Trędowata (the ELTeC text is "
319
+ "shorter) and Kochanowski's Pieśń IX, quoted in Łoziński's Oko proroka. "
320
+ "Every pair is listed in wolne_lektury.eltec_pairs.tsv.",
321
  "is_ocr": False,
322
  },
323
  "wikinews": {
src/test_shingle_containment.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the shared cross-source containment code (src/shingle_containment.py)."""
2
+
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
7
+
8
+ from shingle_containment import best_containment, containment, shingles, strip_wl_footer
9
+
10
+ NOVEL = " ".join(f"w{i}" for i in range(400))
11
+ OTHER = " ".join(f"x{i}" for i in range(400))
12
+
13
+
14
+ def test_shingles_are_reproducible_across_processes():
15
+ # Fixed values: a salted hash() would change them on every interpreter start.
16
+ assert shingles("Ala ma kota, a kot ma Alę.").tolist() == [
17
+ 1095117514565903941, 11979537242062189157, 12971353317152582320]
18
+ assert shingles("ALA ma\nkota, a kot ma alę").tolist() == shingles("Ala ma kota, a kot ma Alę.").tolist()
19
+ assert shingles("a b c d e").tolist() != shingles("e d c b a").tolist()
20
+ assert len(shingles("a b c d")) == 0
21
+
22
+
23
+ def test_strip_wl_footer_cuts_only_a_trailing_wolne_lektury_footer():
24
+ footer = "\n-----\nTa lektura pochodzi ze strony wolnelektury.pl.\n"
25
+ assert strip_wl_footer("Tekst." + footer) == "Tekst."
26
+ assert strip_wl_footer("Tekst.\n-----\nKoniec.") == "Tekst.\n-----\nKoniec."
27
+ assert strip_wl_footer("Tekst." + footer + "x" * 5000) == "Tekst." + footer + "x" * 5000
28
+
29
+
30
+ def test_best_containment_finds_tomes_and_partial_copies():
31
+ words = NOVEL.split()
32
+ tome = " ".join(words[100:300]).upper()
33
+ half = " ".join(words[:100] + OTHER.split()[:100])
34
+ unrelated = " ".join(f"y{i}" for i in range(50))
35
+ novels = [" ".join(OTHER.split()[:50]), NOVEL]
36
+ scores = best_containment([tome, half, unrelated, "za krótki", NOVEL], novels)
37
+ assert scores[0] == (1, 1.0)
38
+ assert scores[1][0] == 1 and 0.45 < scores[1][1] < 0.55 # novel 1 holds more than novel 0
39
+ assert scores[2] == scores[3] == (-1, 0.0)
40
+ assert scores[4] == (1, 1.0)
41
+
42
+
43
+ def test_cover_is_the_union_of_the_references():
44
+ words = NOVEL.split()
45
+ tomes = [" ".join(words[:200]), " ".join(words[196:])] # two tomes, no shingle in both
46
+ whole, empty = containment([NOVEL, ""], tomes)
47
+ assert whole.shingles == whole.covered == 396 and whole.cover == 1.0
48
+ assert whole.refs.tolist() == [0, 1] and whole.shared.tolist() == [196, 200]
49
+ assert whole.best() == (1, 200 / 396) # no single tome holds half of it
50
+ assert (empty.shingles, empty.covered, empty.cover, empty.best()) == (0, 0, 0.0, (-1, 0.0))
51
+ [alone] = containment([NOVEL], [])
52
+ assert (alone.covered, alone.cover, alone.best()) == (0, 0.0, (-1, 0.0))
src/test_wolne_lektury_contract.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
10
+ import pyarrow.compute as pc
11
+ import pyarrow.parquet as pq
12
+ import pytest
13
+
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"}
21
+
22
+
23
+ def test_wl_title_is_the_first_two_nonempty_lines():
24
+ assert wl_title("Stefan Żeromski\n\nDzieje grzechu\n\nISBN 1\n\nText") == "Stefan Żeromski / Dzieje grzechu"
25
+
26
+
27
+ 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
+
35
+ def test_release_has_no_eltec_duplicates_and_matches_stats():
36
+ stats = json.loads((DATA / "wolne_lektury.stats.json").read_text(encoding="utf-8"))
37
+ table = pq.read_table(DATA / "wolne_lektury.parquet")
38
+ ids = set(table.column("id").to_pylist())
39
+ with (DATA / PAIRS).open(encoding="utf-8", newline="") as handle:
40
+ pairs = list(csv.DictReader(handle, delimiter="\t"))
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