ppuzio Claude Opus 5.5 commited on
Commit
0783e5e
·
1 Parent(s): e8f6722

wolne_lektury: move the containment code to src/shingle_containment.py

Browse files

The 1000_novels dedup (v2#45) uses the same 5-word-shingle containment, so the code
moves to a module both filters import, with its unit tests in
src/test_shingle_containment.py. It adds Match.cover, the share of a document's
shingles held by any reference (the union over Wolne Lektury tomes).

No output change: rebuilding from the v0.2.5 Parquet and stats gives byte-identical
wolne_lektury.parquet, stats.json and eltec_pairs.tsv.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

src/clean_wolne_lektury.py CHANGED
@@ -8,7 +8,8 @@ licence. Wolne Lektury splits long novels into tomes, so the test is containment
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
  A trailing Wolne Lektury footer is cut from WL text before scoring (the #45 measurement's rule);
13
  the released text is not changed. Docs scoring >= DROP_AT are dropped. Docs scoring
14
  >= REPORT_AT but below DROP_AT are only partly in an ELTeC novel; they are kept and listed.
@@ -25,17 +26,15 @@ import csv
25
  import hashlib
26
  import json
27
  import os
28
- import re
29
- import unicodedata
30
  from collections import Counter
31
- from functools import lru_cache
32
  from pathlib import Path
33
 
34
- import numpy as np
35
  import pyarrow as pa
36
  import pyarrow.compute as pc
37
  import pyarrow.parquet as pq
38
 
 
 
39
  SOURCE = "wolne_lektury"
40
  ROOT = Path(__file__).resolve().parents[1]
41
  DATA = ROOT / "data" / SOURCE
@@ -43,66 +42,11 @@ ELTEC = ROOT / "data" / "eltec_pol" / "eltec_pol.parquet"
43
  INPUT_SHA256 = "5833c25db296f2479b3c09745ebedd550b2425dd6ebaf021f0095e684a0221a1" # v0.2.1-v0.2.5
44
  ELTEC_SHA256 = "ba40061741dff11165149f6c2cf3d5526e1b6c759e7ce1e03ccc164d58838325" # v0.2.1-v0.2.5
45
  PAIRS = f"{SOURCE}.eltec_pairs.tsv"
46
- K = 5
47
  # Thresholds sit in empty stretches of the v0.2.5 score distribution: no doc scores between
48
  # 0.7588 and 0.9636 (above: 63 docs, the novels; below: two tomes of an abridged ELTeC
49
  # Trędowata), and none between 0.2203 and 0.4267 (below: poems quoted in a novel).
50
  DROP_AT = 0.9
51
  REPORT_AT = 0.3
52
- WORD = re.compile(r"\w+")
53
- # Odd 64-bit multipliers that mix the K word hashes of a shingle in order.
54
- MULT = np.array([0x9E3779B97F4A7C15, 0xC2B2AE3D27D4EB4F, 0x165667B19E3779F9,
55
- 0xD6E8FEB86659FD93, 0xFF51AFD7ED558CCD], dtype=np.uint64)
56
-
57
-
58
- def strip_wl_footer(text: str) -> str:
59
- """Text before a trailing "-----" footer that names wolnelektury, else the text unchanged."""
60
- j = text.rfind("\n-----")
61
- if j >= 0 and len(text) - j < 5000 and "wolnelektury" in text[j:].lower():
62
- return text[:j]
63
- return text
64
-
65
-
66
- @lru_cache(maxsize=None)
67
- def _word_hash(word: str) -> int:
68
- # blake2b, not hash(): str hashing is salted per process, and the scores must be reproducible.
69
- return int.from_bytes(hashlib.blake2b(word.encode("utf-8"), digest_size=8).digest(), "little")
70
-
71
-
72
- def shingles(text: str) -> np.ndarray:
73
- """Sorted unique uint64 hashes of the text's K-word shingles."""
74
- words = WORD.findall(unicodedata.normalize("NFKC", text).casefold())
75
- n = len(words) - K + 1
76
- if n <= 0:
77
- return np.empty(0, np.uint64)
78
- h = np.fromiter((_word_hash(w) for w in words), dtype=np.uint64, count=len(words))
79
- s = np.zeros(n, np.uint64)
80
- for i in range(K):
81
- s += h[i:i + n] * MULT[i]
82
- s ^= s >> np.uint64(31)
83
- return np.unique(s)
84
-
85
-
86
- def best_containment(docs: list[str], novels: list[str]) -> list[tuple[int, float]]:
87
- """For each doc: (index of the novel holding most of its shingles, share held), (-1, 0.0) if none."""
88
- sets = [shingles(text) for text in novels]
89
- hashes = np.concatenate(sets)
90
- owner = np.concatenate([np.full(len(s), i, np.int32) for i, s in enumerate(sets)])
91
- order = np.argsort(hashes, kind="stable")
92
- hashes, owner = hashes[order], owner[order]
93
- out = []
94
- for text in docs:
95
- a = shingles(text)
96
- if not len(a):
97
- out.append((-1, 0.0))
98
- continue
99
- lo, hi = np.searchsorted(hashes, a, "left"), np.searchsorted(hashes, a, "right")
100
- lens = hi - lo
101
- idx = np.repeat(lo - np.cumsum(lens) + lens, lens) + np.arange(lens.sum())
102
- shared = np.bincount(owner[idx], minlength=len(novels))
103
- best = int(shared.argmax())
104
- out.append((best, shared[best] / len(a)) if shared[best] else (-1, 0.0))
105
- return out
106
 
107
 
108
  def wl_title(text: str) -> str:
 
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.
 
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
 
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:
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/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 CHANGED
@@ -13,45 +13,13 @@ 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,
17
- best_containment, build, shingles, strip_wl_footer, wl_title)
18
 
19
- NOVEL = " ".join(f"w{i}" for i in range(400))
20
- OTHER = " ".join(f"x{i}" for i in range(400))
21
  # Hand-checked: only part of each is in its ELTeC novel, so they stay (see the findings entry).
22
  PARTIAL_IDS = {"wolne_lektury_2375475", "wolne_lektury_2375476", "wolne_lektury_2376242"}
23
 
24
 
25
- def test_shingles_are_reproducible_across_processes():
26
- # Fixed values: a salted hash() would change them on every interpreter start.
27
- assert shingles("Ala ma kota, a kot ma Alę.").tolist() == [
28
- 1095117514565903941, 11979537242062189157, 12971353317152582320]
29
- assert shingles("ALA ma\nkota, a kot ma alę").tolist() == shingles("Ala ma kota, a kot ma Alę.").tolist()
30
- assert shingles("a b c d e").tolist() != shingles("e d c b a").tolist()
31
- assert len(shingles("a b c d")) == 0
32
-
33
-
34
- def test_containment_finds_tomes_and_partial_copies():
35
- words = NOVEL.split()
36
- tome = " ".join(words[100:300]).upper()
37
- half = " ".join(words[:100] + OTHER.split()[:100])
38
- unrelated = " ".join(f"y{i}" for i in range(50))
39
- novels = [" ".join(OTHER.split()[:50]), NOVEL]
40
- scores = best_containment([tome, half, unrelated, "za krótki", NOVEL], novels)
41
- assert scores[0] == (1, 1.0)
42
- assert scores[1][0] == 1 and 0.45 < scores[1][1] < 0.55 # novel 1 holds more than novel 0
43
- assert scores[2] == scores[3] == (-1, 0.0)
44
- assert scores[4] == (1, 1.0)
45
- assert REPORT_AT < scores[1][1] < DROP_AT # a half copy is listed and kept
46
-
47
-
48
- def test_strip_wl_footer_cuts_only_a_trailing_wolne_lektury_footer():
49
- footer = "\n-----\nTa lektura pochodzi ze strony wolnelektury.pl.\n"
50
- assert strip_wl_footer("Tekst." + footer) == "Tekst."
51
- assert strip_wl_footer("Tekst.\n-----\nKoniec.") == "Tekst.\n-----\nKoniec."
52
- assert strip_wl_footer("Tekst." + footer + "x" * 5000) == "Tekst." + footer + "x" * 5000
53
-
54
-
55
  def test_wl_title_is_the_first_two_nonempty_lines():
56
  assert wl_title("Stefan Żeromski\n\nDzieje grzechu\n\nISBN 1\n\nText") == "Stefan Żeromski / Dzieje grzechu"
57
 
 
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