ppuzio Claude Opus 5.5 commited on
Commit
8f1921a
·
1 Parent(s): 80bd390

sejm_api_2011_2022: cut the "Przebieg posiedzenia" trailers before the cross-source dedup (v0.2.6, v2#57)

Browse files

Hub PR 76 stripped the headers only from the shingled text; the published rows kept them,
with any appended statement inside its parent. clean_sejm_api_2011_2022.py now runs
sejm_api_common.split_release_rows (as clean_sejm_api.py does) on the pinned pre-dedup
inputs before the containment search, re-pins the sejm_api reference to its post-cut
Parquet, and drops the local header stripper. 105,920 rows cut, 15,648 statements split
out, 7,563 rows under 200 chars and 20 new duplicates dropped; 93,861 contained.
32,460 -> 33,106 documents, 30,766,807 -> 26,112,679 tokens.

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

artifacts/source_findings.md CHANGED
@@ -2253,3 +2253,27 @@ existing `sejm_api` registry entry that meets the contract instead of failing.
2253
 
2254
  **Lesson** — check a scraped snapshot for navigation text glued to the record: a trailer
2255
  in 90% of rows hid in plain sight because each row still began with the right speech.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2253
 
2254
  **Lesson** — check a scraped snapshot for navigation text glued to the record: a trailer
2255
  in 90% of rows hid in plain sight because each row still began with the right speech.
2256
+
2257
+ ## sejm_api_2011_2022 — trailers cut before the cross-source dedup (2026-10-06)
2258
+
2259
+ **Finding** (slayerlabs/polish-dynaword-v2#57) — the same "Przebieg posiedzenia" trailers
2260
+ as in `sejm_api` (section above) are in 105,920 of the 118,902 pre-dedup speeches:
2261
+ 97,723,744 characters. Hub PR 76 only stripped them from the shingled text when it scored
2262
+ containment; the published rows kept them.
2263
+
2264
+ **Fix** — `src/clean_sejm_api_2011_2022.py` now runs `sejm_api_common.split_release_rows`
2265
+ on the pinned pre-dedup inputs before the containment search, so the published rows lose
2266
+ their trailers and each appended statement is scored and published on its own (15,648
2267
+ split rows; 5,374 cut speeches and 2,189 split rows under 200 characters and 20 new exact
2268
+ duplicates dropped; 126,967 rows enter the search). The `sejm_api` reference is re-pinned
2269
+ to its own post-cut Parquet (`ba2daa20…`). Header stripping in the shingler is gone: after
2270
+ the cut no header is left in the inputs or the references. 118,902 → 33,106 documents
2271
+ (Hub PR 76: 32,460), 135,072,403 → 26,112,679 tokens (30,766,807), 93,861 rows contained
2272
+ (86,442), 93,784 of them dated 2011-2019. Of the 32,460 rows Hub PR 76 kept, 1,882 fall
2273
+ under 200 characters once their trailer is cut (504 of them dated 2011-2019), 4 now reach
2274
+ 0.5 and 5 drop below it; 2,527 split rows are added, 180 of them from a speech that is
2275
+ itself dropped. Kept 2011-2019 rows go from 1,697 to 1,281. Parquet sha256
2276
+ `622228ca4c287f91792b7da3fb97c098610c1cf890f1bdc08922dc3aca3742db`.
2277
+
2278
+ **Not established** — the card's hand checks (12 of the post-2019 drops, 20 pairs at
2279
+ 0.3-0.7) were made on the Hub PR 76 build and were not repeated.
data/sejm_api_2011_2022/sejm_api_2011_2022.attribution.jsonl CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:5ce9a3c14e4860ac77f9b86c88bb001547d3b75f9793d2452279c680bf4094b4
3
- size 15892312
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bb45cbd376de47a0244a661ac9eddf8a06a56ac37d048d5bcb00555c61dba72c
3
+ size 16449002
data/sejm_api_2011_2022/sejm_api_2011_2022.decisions.jsonl CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:f50d31feb07692432aca476bf2b8caa15ff4b9b39035d4fcd8ddf6676cf6e045
3
- size 27242090
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:848e9f7bb3731149c2533d9a0e86896fc8e4129871dd6390534fc47d8499b86f
3
+ size 29347301
data/sejm_api_2011_2022/sejm_api_2011_2022.md CHANGED
@@ -26,9 +26,28 @@ from the already merged `sejm_api` 2023-onward artifact.
26
  API; SlayerLab did not re-fetch it from api.sejm.gov.pl.
27
  - Each `source_url` in `sejm_api_2011_2022.attribution.jsonl` is a day-level
28
  listing (`https://api.sejm.gov.pl/sejm/term{N}/videos/{date}`), not a per-speech URL.
29
- - Cross-source dedup: `python src/clean_sejm_api_2011_2022.py`, run on the pre-dedup
30
- release files (the inputs and the references are pinned by SHA-256). Every dropped
31
- or near-dropped speech is listed in `sejm_api_2011_2022.decisions.jsonl`.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
  ## Existing-source overlap
34
 
@@ -37,27 +56,28 @@ re-publishes text already in `parliamentary` (released in 0.2.0). A speech is no
37
  dropped when one document of a pinned reference set holds at least half of its
38
  5-word shingles (containment >= 0.5 over NFKC-casefolded `\w+` tokens, the
39
  tokenisation of the repo's `near_dedup`, in `src/shingle_containment.py`; the
40
- sitting/agenda header lines that the snapshot interleaves with the speeches are
41
- stripped first). The reference set is every Parquet whose registry `release` is
42
- not `None`: `parliamentary` and `sejm_api`.
43
  `parlamint_pl` is no longer registered and has no data, so it is not a reference.
44
- Speeches under five words have no shingles and are kept (271).
45
 
46
- Speeches dropped, of 118,902, by reference set (a speech can match several slices):
 
47
 
48
  | Reference set | Dropped |
49
  |---|---:|
50
- | `parliamentary` + `sejm_api` (this build) | 86,442 |
51
- | `parliamentary`, all slices | 86,417 |
52
- | `parliamentary`, plenary slice alone | 48,660 |
53
- | `parliamentary`, committee slice alone | 38,539 |
54
- | `parliamentary`, interpellation question / reply / other alone | 190 / 47 / 143 |
55
- | `sejm_api` alone (outcome A: `parliamentary` withdrawn) | 216 |
56
- | `sejm_api` + `parliamentary` without its committee slice (outcome B) | 48,833 |
57
-
58
- Almost all overlap is 2011-2019: 86,272 of the 86,442 drops. Kept per year, 2011-2019:
59
- 1, 10, 36, 36, 78, 187, 130, 78, 1,141; 2020-2022 are nearly intact (170 dropped).
60
- Another 899 speeches score 0.3-0.5 and are kept.
61
 
62
  If #54 changes `parliamentary`, the pinned reference set is out of date: re-pin
63
  `REFERENCES` in `src/clean_sejm_api_2011_2022.py` and rerun it on the restored inputs.
@@ -66,13 +86,14 @@ its "committee" label also catches plenary sittings (10 of 11 committee-labelled
66
  references in a 20-pair hand check), so outcome B is the number that classifier gives,
67
  not a count of committee transcripts.
68
 
69
- Known limits: containment is measured against single reference documents, not a union;
70
- agenda titles without a number ("Oświadczenia.") are not stripped from the header text;
71
- and a threshold of 0.5 with no minimum size also drops short formulaic speeches. In a
72
- random 12 of the 170 drops dated 2020 or later, 9 were stage directions or stock phrases,
73
- 2 were report templates (0.5-0.58) and 1 was real reuse. In a hand check of 20 pairs
74
- between 0.3 and 0.7, 14 had the speech's own wording in the reference (4 of 10 between
75
- 0.3 and 0.5, 10 of 10 between 0.5 and 0.7); the 6 that did not are all dated 2020 or later.
 
76
 
77
  ## Statistics
78
 
@@ -81,12 +102,14 @@ between 0.3 and 0.7, 14 had the speech's own wording in the reference (4 of 10 b
81
  | Source rows inspected | 157,714 |
82
  | Rows after 2022-12-31 excluded | 38,812 |
83
  | Rows before 2011-01-01 excluded | 0 |
84
- | Exact duplicate texts removed | 0 |
85
- | Contained in `parliamentary` / `sejm_api` (containment >= 0.5) | 86,442 |
86
- | Documents published | 32,460 |
87
- | Characters | 81,385,172 |
88
- | Tokens (`cl100k_base` proxy) | 30,766,807 |
89
- | Documents with speaker attribution | 32,460 |
 
 
90
 
91
  The canonical schema is `id, text, source, added, created, token_count, license, author`.
92
 
@@ -115,11 +138,13 @@ Which cleaning ran, in order:
115
  release's QA covers the corpus; the review ask is answered precisely: min
116
  length + author + exact dedup + date window are the only gates here). **No
117
  further text rewriting** happens in this build — the projection maps fields.
118
- 3. **Cross-source dedup** (`src/clean_sejm_api_2011_2022.py`, run on the output of
119
- step 2): drops the 86,442 speeches contained (5-shingle containment >= 0.5) in a
120
- `parliamentary` or `sejm_api` document; see "Existing-source overlap".
 
 
121
 
122
- Before/after at the text level is therefore a deliberate no-op (the pinned
123
  release preserves post-normalization text and a documented protocol; the raw
124
  stenogram pages are not pinned and drift on sejm.gov.pl), so the concrete
125
  before/after evidence is the redaction record above (the one e-mail replaced
 
26
  API; SlayerLab did not re-fetch it from api.sejm.gov.pl.
27
  - Each `source_url` in `sejm_api_2011_2022.attribution.jsonl` is a day-level
28
  listing (`https://api.sejm.gov.pl/sejm/term{N}/videos/{date}`), not a per-speech URL.
29
+ - Trailer cut and cross-source dedup: `python src/clean_sejm_api_2011_2022.py`, run on
30
+ the pre-dedup release files (the inputs and the references are pinned by SHA-256).
31
+ Every dropped or near-dropped row is listed in `sejm_api_2011_2022.decisions.jsonl`.
32
+
33
+ ## Trailer cut
34
+
35
+ The rights audit (slayerlabs/polish-dynaword-v2#57) found that the snapshot
36
+ appends to 105,920 of the 118,902 speeches a "Przebieg posiedzenia" header of a
37
+ later statement of the same sitting day, and sometimes that statement's text.
38
+ `src/clean_sejm_api_2011_2022.py` cuts every trailer (97,723,744 characters) with
39
+ the code `src/clean_sejm_api.py` uses for `sejm_api` (`sejm_api_common.split_release_rows`).
40
+ An appended statement with text becomes a row of its own (15,648 rows), credited to
41
+ the speaker the header names ("Przebieg posiedzenia Jan Kowalski: …"), without the
42
+ office in its label. Its date and term are those of the row it was cut from. A split row's id
43
+ hashes its date, term, speaker and text like every other row; its sidecar line
44
+ carries `split_from` (the id of the row it was cut from in the pre-dedup input of
45
+ Hub PR 18) and `has_events: null`, since the snapshot's events flag describes the
46
+ whole parent row. Rows that fall under the fetch's 200-character minimum after the
47
+ cut (5,374 cut speeches and 2,189 split rows) and 20 texts that became exact
48
+ duplicates are dropped. The cut runs before the containment search, so a speech is
49
+ scored on its own words and an appended statement on its own; 2,527 split rows are
50
+ published, 180 of them cut from a speech that is itself dropped as contained.
51
 
52
  ## Existing-source overlap
53
 
 
56
  dropped when one document of a pinned reference set holds at least half of its
57
  5-word shingles (containment >= 0.5 over NFKC-casefolded `\w+` tokens, the
58
  tokenisation of the repo's `near_dedup`, in `src/shingle_containment.py`; the
59
+ trailers are cut first, see "Trailer cut"). The reference set is every Parquet whose
60
+ registry `release` is not `None`: `parliamentary` and `sejm_api` (after its own
61
+ trailer cut).
62
  `parlamint_pl` is no longer registered and has no data, so it is not a reference.
63
+ Rows under five words have no shingles and are kept (none in this build).
64
 
65
+ Rows dropped, of 126,967 after the trailer cut, by reference set (a row can match
66
+ several slices):
67
 
68
  | Reference set | Dropped |
69
  |---|---:|
70
+ | `parliamentary` + `sejm_api` (this build) | 93,861 |
71
+ | `parliamentary`, all slices | 93,844 |
72
+ | `parliamentary`, plenary slice alone | 53,904 |
73
+ | `parliamentary`, committee slice alone | 40,429 |
74
+ | `parliamentary`, interpellation question / reply / other alone | 244 / 17 / 107 |
75
+ | `sejm_api` alone (outcome A: `parliamentary` withdrawn) | 45 |
76
+ | `sejm_api` + `parliamentary` without its committee slice (outcome B) | 54,081 |
77
+
78
+ Almost all overlap is 2011-2019: 93,784 of the 93,861 drops. Kept per year, 2011-2019:
79
+ 2, 5, 5, 5, 23, 50, 29, 32, 1,130; 2020-2022 are nearly intact (77 dropped).
80
+ Another 639 rows score 0.3-0.5 and are kept.
81
 
82
  If #54 changes `parliamentary`, the pinned reference set is out of date: re-pin
83
  `REFERENCES` in `src/clean_sejm_api_2011_2022.py` and rerun it on the restored inputs.
 
86
  references in a 20-pair hand check), so outcome B is the number that classifier gives,
87
  not a count of committee transcripts.
88
 
89
+ Known limits: containment is measured against single reference documents, not a union,
90
+ and a threshold of 0.5 with no minimum size also drops short formulaic speeches. The
91
+ hand checks that follow were made on the build before the trailer cut (Hub PR 76),
92
+ which had 170 drops dated 2020 or later, against 77 now. In a random 12 of those 170,
93
+ 9 were stage directions or stock phrases, 2 were report templates (0.5-0.58) and 1 was
94
+ real reuse. In a hand check of 20 pairs between 0.3 and 0.7, 14 had the speech's own
95
+ wording in the reference (4 of 10 between 0.3 and 0.5, 10 of 10 between 0.5 and 0.7);
96
+ the 6 that did not are all dated 2020 or later.
97
 
98
  ## Statistics
99
 
 
102
  | Source rows inspected | 157,714 |
103
  | Rows after 2022-12-31 excluded | 38,812 |
104
  | Rows before 2011-01-01 excluded | 0 |
105
+ | Statements split into rows of their own | 15,648 |
106
+ | Rows under 200 characters after the trailer cut | 7,563 |
107
+ | Exact duplicate texts removed | 20 |
108
+ | Contained in `parliamentary` / `sejm_api` (containment >= 0.5) | 93,861 |
109
+ | Documents published | 33,106 |
110
+ | Characters | 70,230,096 |
111
+ | Tokens (`cl100k_base` proxy) | 26,112,679 |
112
+ | Documents with speaker attribution | 33,106 |
113
 
114
  The canonical schema is `id, text, source, added, created, token_count, license, author`.
115
 
 
138
  release's QA covers the corpus; the review ask is answered precisely: min
139
  length + author + exact dedup + date window are the only gates here). **No
140
  further text rewriting** happens in this build — the projection maps fields.
141
+ 3. **Trailer cut and cross-source dedup** (`src/clean_sejm_api_2011_2022.py`, run on
142
+ the output of step 2): cuts the "Przebieg posiedzenia" trailers and splits the
143
+ appended statements into rows of their own (see "Trailer cut"), then drops the
144
+ 93,861 rows contained (5-shingle containment >= 0.5) in a `parliamentary` or
145
+ `sejm_api` document; see "Existing-source overlap".
146
 
147
+ Apart from the trailer cut, before/after at the text level is a deliberate no-op (the pinned
148
  release preserves post-normalization text and a documented protocol; the raw
149
  stenogram pages are not pinned and drift on sejm.gov.pl), so the concrete
150
  before/after evidence is the redaction record above (the one e-mail replaced
data/sejm_api_2011_2022/sejm_api_2011_2022.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:8fad4b4eab069fb8a652f9dc6a2e7dbc8f49d1e1b6bfae0decd2b318d160a20a
3
- size 29096259
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:622228ca4c287f91792b7da3fb97c098610c1cf890f1bdc08922dc3aca3742db
3
+ size 28185916
data/sejm_api_2011_2022/sejm_api_2011_2022.stats.json CHANGED
@@ -1,46 +1,55 @@
1
  {
2
  "added": "2026-08-31",
3
- "authors_with_value": 32460,
4
  "by_source_split": {
5
- "train": 31822,
6
- "validation": 638
7
  },
8
  "by_term": {
9
- "7": 118,
10
- "8": 479,
11
- "9": 31863
12
  },
13
  "by_year": {
14
- "2011": 1,
15
- "2012": 10,
16
- "2013": 36,
17
- "2014": 36,
18
- "2015": 78,
19
- "2016": 187,
20
- "2017": 130,
21
- "2018": 78,
22
- "2019": 1141,
23
- "2020": 7632,
24
- "2021": 9997,
25
- "2022": 13134
26
  },
27
- "chars": 81385172,
28
  "created_max": "2022-12-14",
29
  "created_min": "2011-12-14",
30
  "drop_after_end": 38812,
31
  "drop_before_start": 0,
32
- "drop_dup": 0,
33
- "kept": 32460,
34
  "license": "public-domain (official documents)",
35
  "licenses": {
36
- "public-domain (official documents)": 32460
37
  },
38
  "read": 157714,
39
  "source_revision": "124557799608ce4212cf22fa90ca7904618de1b6",
40
  "stats_recomputed_from_parquet": true,
41
  "target_base_revision": "a9d134ac79a9fe586fc9c11cb39eb32d69dcd21f",
42
- "tokens": 30766807,
43
- "drop_cross_source_dup": 86442,
 
 
 
 
 
 
 
 
 
44
  "cross_source_dedup": {
45
  "drop_at": 0.5,
46
  "report_at": 0.3,
@@ -52,49 +61,49 @@
52
  },
53
  "reference_sha256": {
54
  "parliamentary": "64b94993e196b9df87b243189cfe104a84b38474b701c1f249fcc9cac60488c8",
55
- "sejm_api": "56f7b03483488dec8f0fa145c6d26746926175d83096e9d1931e535aa81cf161"
56
  },
57
- "no_shingles": 271,
58
  "dropped_by_best_group": {
59
- "parliamentary:committee": 38083,
60
  "parliamentary:interp_question": 2,
61
- "parliamentary:other": 52,
62
- "parliamentary:plenary": 48270,
63
- "sejm_api": 35
64
  },
65
  "dropped_by_year": {
66
- "2011": 870,
67
- "2012": 10722,
68
- "2013": 11780,
69
- "2014": 10444,
70
- "2015": 10592,
71
- "2016": 13576,
72
- "2017": 12184,
73
- "2018": 10128,
74
- "2019": 5976,
75
- "2020": 35,
76
- "2021": 75,
77
- "2022": 60
78
  },
79
  "dropped_by_shingles": {
80
- "<10": 1236,
81
- "10-19": 1177,
82
- "20-49": 3153,
83
- "50-199": 35360,
84
- ">=200": 45516
85
  },
86
- "kept_partial": 899,
87
  "outcomes": {
88
- "all_references": 86442,
89
- "sejm_api_only": 216,
90
- "parliamentary_all": 86417,
91
- "parliamentary_without_committee_plus_sejm_api": 48833,
92
- "only_parliamentary_committee": 38539,
93
- "only_parliamentary_interp_question": 190,
94
- "only_parliamentary_interp_reply": 47,
95
- "only_parliamentary_other": 143,
96
- "only_parliamentary_plenary": 48660,
97
- "only_sejm_api": 216
98
  }
99
  }
100
  }
 
1
  {
2
  "added": "2026-08-31",
3
+ "authors_with_value": 33106,
4
  "by_source_split": {
5
+ "train": 32454,
6
+ "validation": 652
7
  },
8
  "by_term": {
9
+ "7": 21,
10
+ "8": 157,
11
+ "9": 32928
12
  },
13
  "by_year": {
14
+ "2011": 2,
15
+ "2012": 5,
16
+ "2013": 5,
17
+ "2014": 5,
18
+ "2015": 23,
19
+ "2016": 50,
20
+ "2017": 29,
21
+ "2018": 32,
22
+ "2019": 1130,
23
+ "2020": 7937,
24
+ "2021": 10239,
25
+ "2022": 13649
26
  },
27
+ "chars": 70230096,
28
  "created_max": "2022-12-14",
29
  "created_min": "2011-12-14",
30
  "drop_after_end": 38812,
31
  "drop_before_start": 0,
32
+ "drop_dup": 20,
33
+ "kept": 33106,
34
  "license": "public-domain (official documents)",
35
  "licenses": {
36
+ "public-domain (official documents)": 33106
37
  },
38
  "read": 157714,
39
  "source_revision": "124557799608ce4212cf22fa90ca7904618de1b6",
40
  "stats_recomputed_from_parquet": true,
41
  "target_base_revision": "a9d134ac79a9fe586fc9c11cb39eb32d69dcd21f",
42
+ "tokens": 26112679,
43
+ "split_rows": 15648,
44
+ "drop_short": 7563,
45
+ "trailer_cut": {
46
+ "rows_cut": 105920,
47
+ "chars_cut": 97723744,
48
+ "split_rows": 15648,
49
+ "drop_short": 7563,
50
+ "drop_dup": 20
51
+ },
52
+ "drop_cross_source_dup": 93861,
53
  "cross_source_dedup": {
54
  "drop_at": 0.5,
55
  "report_at": 0.3,
 
61
  },
62
  "reference_sha256": {
63
  "parliamentary": "64b94993e196b9df87b243189cfe104a84b38474b701c1f249fcc9cac60488c8",
64
+ "sejm_api": "ba2daa20d2d2753c09e8bdd477839f43c82170f44caeadc634cb2295362c9c3b"
65
  },
66
+ "no_shingles": 0,
67
  "dropped_by_best_group": {
68
+ "parliamentary:committee": 40095,
69
  "parliamentary:interp_question": 2,
70
+ "parliamentary:other": 61,
71
+ "parliamentary:plenary": 53683,
72
+ "sejm_api": 20
73
  },
74
  "dropped_by_year": {
75
+ "2011": 995,
76
+ "2012": 12577,
77
+ "2013": 12950,
78
+ "2014": 11402,
79
+ "2015": 11497,
80
+ "2016": 14176,
81
+ "2017": 12784,
82
+ "2018": 10876,
83
+ "2019": 6527,
84
+ "2020": 12,
85
+ "2021": 37,
86
+ "2022": 28
87
  },
88
  "dropped_by_shingles": {
89
+ "<10": 0,
90
+ "10-19": 5,
91
+ "20-49": 3910,
92
+ "50-199": 42880,
93
+ ">=200": 47066
94
  },
95
+ "kept_partial": 639,
96
  "outcomes": {
97
+ "all_references": 93861,
98
+ "sejm_api_only": 45,
99
+ "parliamentary_all": 93844,
100
+ "parliamentary_without_committee_plus_sejm_api": 54081,
101
+ "only_parliamentary_committee": 40429,
102
+ "only_parliamentary_interp_question": 244,
103
+ "only_parliamentary_interp_reply": 17,
104
+ "only_parliamentary_other": 107,
105
+ "only_parliamentary_plenary": 53904,
106
+ "only_sejm_api": 45
107
  }
108
  }
109
  }
src/clean_sejm_api_2011_2022.py CHANGED
@@ -8,9 +8,12 @@ least DROP_AT of its shingles:
8
  containment(speech, ref) = |S(speech) & S(ref)| / |S(speech)|
9
 
10
  S() is the set of 5-word shingles over NFKC-casefolded \\w+ tokens (the tokenisation of the repo's
11
- near_dedup, src/shingle_containment.py) of body(text), the speech without its sitting/agenda header.
12
- Containment is one-directional because a reference document can be a whole sitting while a speech
13
- is a few paragraphs. It is measured against single reference documents, not a union of them.
 
 
 
14
 
15
  The reference set is REFERENCES: every Parquet whose registry `release` is not None, each pinned by
16
  SHA-256. If slayerlabs/polish-dynaword-v2#54 changes `parliamentary` (withdraw it, or filter out its
@@ -32,7 +35,6 @@ The inputs are the pre-dedup release files, pinned by SHA-256. Restore them befo
32
  from __future__ import annotations
33
 
34
  import argparse
35
- import hashlib
36
  import json
37
  import multiprocessing
38
  import os
@@ -44,9 +46,10 @@ from pathlib import Path
44
 
45
  import numpy as np
46
  import pyarrow as pa
47
- import pyarrow.compute as pc
48
  import pyarrow.parquet as pq
 
49
 
 
50
  from shingle_containment import shingles
51
  from sources import SOURCES
52
 
@@ -64,8 +67,8 @@ INPUT_SHA256 = {
64
  REFERENCES = {
65
  "parliamentary": (ROOT / "data/parliamentary/parliamentary.parquet",
66
  "64b94993e196b9df87b243189cfe104a84b38474b701c1f249fcc9cac60488c8"),
67
- "sejm_api": (ROOT / "data/sejm_api/sejm_api.parquet",
68
- "56f7b03483488dec8f0fa145c6d26746926175d83096e9d1931e535aa81cf161"),
69
  }
70
  DECISIONS = f"{SOURCE}.decisions.jsonl"
71
  DROP_AT = 0.5
@@ -82,23 +85,6 @@ PPC_REPLY = _R(r'SPS-0\d\d|W odpowiedzi na (interpelacj|zapytani)|Odpowiadając
82
  PPC_QUESTION = _R(r'^(Szanown|Szanowni|Wielce Szanown|Panie Marszałku|Pani Marszałek|Panie Ministrze|Pani Minister|Panie Premierze|Pani Premier)|zwracam się (do Pana|do Pani)|interpelacj')
83
 
84
 
85
- # The Sejm API snapshot interleaves its speeches with metadata headers, "Przebieg posiedzenia <speaker>:
86
- # <term> kadencja, <n> posiedzenie, <d> dzien - <role> <speaker> ... (dd-mm-yyyy) <k> punkt porzadku
87
- # dziennego: <title>". Every speech of that speaker on that agenda item carries the same one, and the
88
- # PPC text has none, so left in they would make short speeches look contained in each other.
89
- # A title ends at its "(druk nr N)." citation, else at its first full stop; numbered items ("9. ...")
90
- # that follow belong to it. On the 14,090 mid-text headers whose title is known from another speech
91
- # this ends the title exactly 98.7% of the time (short 0.9%, long 0.4%).
92
- _SENTENCE = r"(?:.{0,800}?\(druki? nr [^)]{0,80}\)\.|.*?\.)(?=\s|\Z)"
93
- HEADER = re.compile(r"Przebieg posiedzenia .{0,500}?\(\d{2}-\d{2}-\d{4}\)"
94
- r"(?: \d[\d., i]{0,40} punkt porządku dziennego: " + _SENTENCE + r"(?:\s\d+\. " + _SENTENCE + r")*)?")
95
-
96
-
97
- def body(text: str) -> str:
98
- """The speech without its sitting/agenda metadata headers."""
99
- return HEADER.sub(" ", text) if "Przebieg posiedzenia " in text else text
100
-
101
-
102
  def ppc_slice(text: str) -> str:
103
  head = text[:2500]
104
  if PPC_COMMITTEE.search(head) and not PPC_REPLY.search(head):
@@ -120,12 +106,6 @@ def min_shared(sizes: np.ndarray, at: float) -> np.ndarray:
120
  return np.ceil(at * sizes - 1e-9).astype(np.int64)
121
 
122
 
123
- def check_pin(path: Path, expected: str, restore: str) -> None:
124
- with path.open("rb") as stream:
125
- if hashlib.file_digest(stream, "sha256").hexdigest() != expected:
126
- raise SystemExit(f"{path} does not match the pinned SHA-256; {restore}")
127
-
128
-
129
  # --- exact containment search -------------------------------------------------------------------
130
 
131
  _INDEX: dict[str, np.ndarray] = {} # per-process, memory-mapped from the work directory
@@ -137,7 +117,7 @@ def _load_index(work: str) -> None:
137
 
138
 
139
  def _shingle_chunk(texts: list[str]) -> list[np.ndarray]:
140
- return [shingles(body(text)) for text in texts]
141
 
142
 
143
  def prefix_index(offsets: np.ndarray, flat: np.ndarray, need: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
@@ -176,7 +156,7 @@ def _scan_row_group(task: tuple[str, str, int]) -> dict[tuple[int, str], tuple[i
176
  flat, offsets, need = _INDEX["flat"], _INDEX["offsets"], _INDEX["need"]
177
  best: dict[tuple[int, str], tuple[int, str]] = {}
178
  for ref_id, text in zip(table.column("id").to_pylist(), table.column("text").to_pylist(), strict=True):
179
- ref = shingles(body(text))
180
  lo = np.searchsorted(prefix_hash, ref, "left")
181
  lens = np.searchsorted(prefix_hash, ref, "right") - lo
182
  hits = int(lens.sum())
@@ -259,81 +239,67 @@ def build(input_dir: Path, references: dict[str, tuple[Path, str]], out_dir: Pat
259
  if check_registry and SOURCES[source]["release"] is None:
260
  raise SystemExit(f"{source} has no release in src/sources.py; it cannot be a reference")
261
  table = pq.read_table(input_dir / f"{SOURCE}.parquet")
 
 
 
 
 
 
 
 
 
262
  with tempfile.TemporaryDirectory() as work:
263
- sizes, best = find_contained(table.column("text").to_pylist(), {s: p for s, (p, _) in references.items()},
264
  Path(work), workers)
265
  groups = sorted({group for _, group in best})
266
  scores = score_table(sizes, best, groups)
267
  top = scores.max(axis=1) if groups else np.zeros(len(sizes))
268
  drop = top >= DROP_AT
269
- kept = table.filter(pa.array(~drop))
270
 
271
- ids, created = table.column("id").to_pylist(), table.column("created").to_pylist()
272
  decisions = []
273
  for doc in np.flatnonzero(top >= REPORT_AT):
274
  group = groups[int(scores[doc].argmax())]
275
  decisions.append({
276
- "id": ids[doc], "created": created[doc], "action": "drop" if drop[doc] else "keep_partial",
277
  "containment": round(float(top[doc]), 4), "ref_group": group, "ref_id": best[(int(doc), group)][1],
278
  "shingles": int(sizes[doc]), "shared": best[(int(doc), group)][0],
279
  "by_group": {g: round(float(scores[doc, i]), 4) for i, g in enumerate(groups) if scores[doc, i]}})
280
  decisions.sort(key=lambda d: (-d["containment"], d["id"]))
281
-
282
- kept_ids = set(kept.column("id").to_pylist())
283
- sidecar_lines = []
284
- with (input_dir / f"{SOURCE}.attribution.jsonl").open(encoding="utf-8") as stream:
285
- for line in stream:
286
- if json.loads(line)["id"] in kept_ids:
287
- sidecar_lines.append(line)
288
- if len(sidecar_lines) != kept.num_rows:
289
- raise SystemExit("the attribution sidecar does not match the Parquet ids")
290
- sidecar = [json.loads(line) for line in sidecar_lines]
291
-
292
- stats = json.loads((input_dir / f"{SOURCE}.stats.json").read_text(encoding="utf-8"))
293
- if (pc.sum(pc.utf8_length(table.column("text"))).as_py(), pc.sum(table.column("token_count")).as_py(),
294
- table.num_rows) != (stats["chars"], stats["tokens"], stats["kept"]):
295
- raise SystemExit("the input stats.json does not describe the input Parquet")
296
- kept_created = kept.column("created").to_pylist()
297
- stats.update(
298
- kept=kept.num_rows,
299
- drop_cross_source_dup=int(drop.sum()),
300
- chars=pc.sum(pc.utf8_length(kept.column("text"))).as_py(),
301
- tokens=pc.sum(kept.column("token_count")).as_py(),
302
- licenses=dict(sorted(Counter(kept.column("license").to_pylist()).items())),
303
- authors_with_value=sum(map(bool, kept.column("author").to_pylist())),
304
- created_min=min(kept_created), created_max=max(kept_created),
305
- by_year=dict(sorted(Counter(c[:4] for c in kept_created).items())),
306
- by_term=dict(sorted(Counter(row["term"] for row in sidecar).items())),
307
- by_source_split=dict(sorted(Counter(row["source_split"] for row in sidecar).items())),
308
- cross_source_dedup={
309
- "drop_at": DROP_AT, "report_at": REPORT_AT, "shingle_words": 5,
310
- "input_sha256": INPUT_SHA256,
311
- "reference_sha256": {source: sha for source, (_, sha) in references.items()},
312
- "no_shingles": int((sizes == 0).sum()),
313
- "dropped_by_best_group": dict(sorted(Counter(d["ref_group"] for d in decisions if d["action"] == "drop").items())),
314
- "dropped_by_year": dict(sorted(Counter(d["created"][:4] for d in decisions if d["action"] == "drop").items())),
315
- "dropped_by_shingles": {label: sum(d["action"] == "drop" and lo <= d["shingles"] < hi for d in decisions)
316
- for label, lo, hi in SIZE_BUCKETS},
317
- "kept_partial": sum(d["action"] == "keep_partial" for d in decisions),
318
- "outcomes": outcomes(scores, groups) if groups else {},
319
- },
320
- )
321
- drops = ("drop_after_end", "drop_before_start", "drop_dup", "drop_cross_source_dup")
322
- if stats["read"] - sum(stats[k] for k in drops) != stats["kept"]:
323
  raise SystemExit("stats drop counts do not add up to the kept rows")
324
 
325
- staged = {
326
- out_dir / f"{SOURCE}.parquet.tmp": lambda p: pq.write_table(kept, p, compression="zstd", row_group_size=ROW_GROUP_SIZE),
327
- out_dir / f"{SOURCE}.attribution.jsonl.tmp": lambda p: p.write_text("".join(sidecar_lines), encoding="utf-8"),
328
- out_dir / f"{DECISIONS}.tmp": lambda p: p.write_text(
 
 
329
  "".join(json.dumps(d, ensure_ascii=False) + "\n" for d in decisions), encoding="utf-8"),
330
- out_dir / f"{SOURCE}.stats.json.tmp": lambda p: p.write_text(
331
  json.dumps(stats, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"),
332
- }
333
- for path, write in staged.items():
334
- write(path)
335
- for path in staged:
336
- os.replace(path, path.with_suffix(""))
337
  return stats
338
 
339
 
 
8
  containment(speech, ref) = |S(speech) & S(ref)| / |S(speech)|
9
 
10
  S() is the set of 5-word shingles over NFKC-casefolded \\w+ tokens (the tokenisation of the repo's
11
+ near_dedup, src/shingle_containment.py). The "Przebieg posiedzenia" trailers that the snapshot appends
12
+ to most speeches are cut first, and each appended statement becomes a row of its own
13
+ (sejm_api_common.split_release_rows, as in src/clean_sejm_api.py), so a speech is scored on its own
14
+ words and an appended statement on its own. Containment is one-directional because a reference
15
+ document can be a whole sitting while a speech is a few paragraphs. It is measured against single
16
+ reference documents, not a union of them.
17
 
18
  The reference set is REFERENCES: every Parquet whose registry `release` is not None, each pinned by
19
  SHA-256. If slayerlabs/polish-dynaword-v2#54 changes `parliamentary` (withdraw it, or filter out its
 
35
  from __future__ import annotations
36
 
37
  import argparse
 
38
  import json
39
  import multiprocessing
40
  import os
 
46
 
47
  import numpy as np
48
  import pyarrow as pa
 
49
  import pyarrow.parquet as pq
50
+ import tiktoken
51
 
52
+ from sejm_api_common import check_pin, release_stats, replace_all, split_release_rows
53
  from shingle_containment import shingles
54
  from sources import SOURCES
55
 
 
67
  REFERENCES = {
68
  "parliamentary": (ROOT / "data/parliamentary/parliamentary.parquet",
69
  "64b94993e196b9df87b243189cfe104a84b38474b701c1f249fcc9cac60488c8"),
70
+ "sejm_api": (ROOT / "data/sejm_api/sejm_api.parquet", # after src/clean_sejm_api.py
71
+ "ba2daa20d2d2753c09e8bdd477839f43c82170f44caeadc634cb2295362c9c3b"),
72
  }
73
  DECISIONS = f"{SOURCE}.decisions.jsonl"
74
  DROP_AT = 0.5
 
85
  PPC_QUESTION = _R(r'^(Szanown|Szanowni|Wielce Szanown|Panie Marszałku|Pani Marszałek|Panie Ministrze|Pani Minister|Panie Premierze|Pani Premier)|zwracam się (do Pana|do Pani)|interpelacj')
86
 
87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  def ppc_slice(text: str) -> str:
89
  head = text[:2500]
90
  if PPC_COMMITTEE.search(head) and not PPC_REPLY.search(head):
 
106
  return np.ceil(at * sizes - 1e-9).astype(np.int64)
107
 
108
 
 
 
 
 
 
 
109
  # --- exact containment search -------------------------------------------------------------------
110
 
111
  _INDEX: dict[str, np.ndarray] = {} # per-process, memory-mapped from the work directory
 
117
 
118
 
119
  def _shingle_chunk(texts: list[str]) -> list[np.ndarray]:
120
+ return [shingles(text) for text in texts]
121
 
122
 
123
  def prefix_index(offsets: np.ndarray, flat: np.ndarray, need: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
 
156
  flat, offsets, need = _INDEX["flat"], _INDEX["offsets"], _INDEX["need"]
157
  best: dict[tuple[int, str], tuple[int, str]] = {}
158
  for ref_id, text in zip(table.column("id").to_pylist(), table.column("text").to_pylist(), strict=True):
159
+ ref = shingles(text)
160
  lo = np.searchsorted(prefix_hash, ref, "left")
161
  lens = np.searchsorted(prefix_hash, ref, "right") - lo
162
  hits = int(lens.sum())
 
239
  if check_registry and SOURCES[source]["release"] is None:
240
  raise SystemExit(f"{source} has no release in src/sources.py; it cannot be a reference")
241
  table = pq.read_table(input_dir / f"{SOURCE}.parquet")
242
+ with (input_dir / f"{SOURCE}.attribution.jsonl").open(encoding="utf-8") as stream:
243
+ sidecar = [json.loads(line) for line in stream]
244
+ stats = json.loads((input_dir / f"{SOURCE}.stats.json").read_text(encoding="utf-8"))
245
+ rows = table.to_pylist()
246
+ recomputed = release_stats(rows, sidecar)
247
+ if recomputed != {key: stats.get(key) for key in recomputed}:
248
+ raise SystemExit("the input stats.json does not describe the input Parquet")
249
+
250
+ rows, sidecar, cut = split_release_rows(rows, sidecar, tiktoken.get_encoding("cl100k_base"))
251
  with tempfile.TemporaryDirectory() as work:
252
+ sizes, best = find_contained([row["text"] for row in rows], {s: p for s, (p, _) in references.items()},
253
  Path(work), workers)
254
  groups = sorted({group for _, group in best})
255
  scores = score_table(sizes, best, groups)
256
  top = scores.max(axis=1) if groups else np.zeros(len(sizes))
257
  drop = top >= DROP_AT
 
258
 
 
259
  decisions = []
260
  for doc in np.flatnonzero(top >= REPORT_AT):
261
  group = groups[int(scores[doc].argmax())]
262
  decisions.append({
263
+ "id": rows[doc]["id"], "created": rows[doc]["created"], "action": "drop" if drop[doc] else "keep_partial",
264
  "containment": round(float(top[doc]), 4), "ref_group": group, "ref_id": best[(int(doc), group)][1],
265
  "shingles": int(sizes[doc]), "shared": best[(int(doc), group)][0],
266
  "by_group": {g: round(float(scores[doc, i]), 4) for i, g in enumerate(groups) if scores[doc, i]}})
267
  decisions.sort(key=lambda d: (-d["containment"], d["id"]))
268
+ kept_rows = [row for row, dropped in zip(rows, drop) if not dropped]
269
+ kept_sidecar = [line for line, dropped in zip(sidecar, drop) if not dropped]
270
+
271
+ stats.update(release_stats(kept_rows, kept_sidecar))
272
+ stats["split_rows"] = cut["split_rows"]
273
+ stats["drop_short"] = cut["drop_short"]
274
+ stats["drop_dup"] += cut["drop_dup"]
275
+ stats["trailer_cut"] = dict(cut)
276
+ stats["drop_cross_source_dup"] = int(drop.sum())
277
+ stats["cross_source_dedup"] = {
278
+ "drop_at": DROP_AT, "report_at": REPORT_AT, "shingle_words": 5,
279
+ "input_sha256": INPUT_SHA256,
280
+ "reference_sha256": {source: sha for source, (_, sha) in references.items()},
281
+ "no_shingles": int((sizes == 0).sum()),
282
+ "dropped_by_best_group": dict(sorted(Counter(d["ref_group"] for d in decisions if d["action"] == "drop").items())),
283
+ "dropped_by_year": dict(sorted(Counter(d["created"][:4] for d in decisions if d["action"] == "drop").items())),
284
+ "dropped_by_shingles": {label: sum(d["action"] == "drop" and lo <= d["shingles"] < hi for d in decisions)
285
+ for label, lo, hi in SIZE_BUCKETS},
286
+ "kept_partial": sum(d["action"] == "keep_partial" for d in decisions),
287
+ "outcomes": outcomes(scores, groups) if groups else {},
288
+ }
289
+ drops = ("drop_after_end", "drop_before_start", "drop_dup", "drop_short", "drop_cross_source_dup")
290
+ if stats["read"] + stats["split_rows"] - sum(stats[k] for k in drops) != stats["kept"]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
291
  raise SystemExit("stats drop counts do not add up to the kept rows")
292
 
293
+ replace_all({
294
+ out_dir / f"{SOURCE}.parquet": lambda p: pq.write_table(
295
+ pa.Table.from_pylist(kept_rows, schema=table.schema), p, compression="zstd", row_group_size=ROW_GROUP_SIZE),
296
+ out_dir / f"{SOURCE}.attribution.jsonl": lambda p: p.write_text(
297
+ "".join(json.dumps(line, ensure_ascii=False, sort_keys=True) + "\n" for line in kept_sidecar), encoding="utf-8"),
298
+ out_dir / DECISIONS: lambda p: p.write_text(
299
  "".join(json.dumps(d, ensure_ascii=False) + "\n" for d in decisions), encoding="utf-8"),
300
+ out_dir / f"{SOURCE}.stats.json": lambda p: p.write_text(
301
  json.dumps(stats, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"),
302
+ })
 
 
 
 
303
  return stats
304
 
305
 
src/sources.py CHANGED
@@ -286,10 +286,12 @@ SOURCES = {
286
  "attribution preserved; source_url is a day-level api.sejm.gov.pl "
287
  "/videos/ listing, not a per-speech URL. This build applies the date "
288
  "window 2011-01-01..2022-12-31, >=200 chars + author, exact dedup, then "
289
- "src/clean_sejm_api_2011_2022.py drops speeches whose 5-shingle "
290
- "containment in one document of the pinned parliamentary / sejm_api "
291
- "Parquets is >= 0.5 (118,902 -> 32,460 docs; re-pin and rerun if "
292
- "polish-dynaword-v2#54 changes parliamentary). NERGAL not run - re-run "
 
 
293
  "through SlayerLab/NERGAL before release. Shared helpers factored into "
294
  "src/sejm_api_common.py.",
295
  "domain": "political/spoken",
 
286
  "attribution preserved; source_url is a day-level api.sejm.gov.pl "
287
  "/videos/ listing, not a per-speech URL. This build applies the date "
288
  "window 2011-01-01..2022-12-31, >=200 chars + author, exact dedup, then "
289
+ "src/clean_sejm_api_2011_2022.py cuts the \"Przebieg posiedzenia\" "
290
+ "trailers (appended statements become rows of their own) and drops rows "
291
+ "whose 5-shingle containment in one document of the pinned "
292
+ "parliamentary / sejm_api Parquets is >= 0.5 (118,902 -> 33,106 docs; "
293
+ "re-pin and rerun if polish-dynaword-v2#54 changes parliamentary). NERGAL "
294
+ "not run - re-run "
295
  "through SlayerLab/NERGAL before release. Shared helpers factored into "
296
  "src/sejm_api_common.py.",
297
  "domain": "political/spoken",
src/test_sejm_api_2011_2022_contract.py CHANGED
@@ -13,7 +13,9 @@ import pytest
13
  sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
14
 
15
  import clean_sejm_api_2011_2022 as clean
 
16
  from sources import SOURCES
 
17
 
18
  ROOT = pathlib.Path(__file__).resolve().parents[1]
19
  DATA = ROOT / "data" / "sejm_api_2011_2022"
@@ -182,7 +184,9 @@ def test_shipped_files_follow_from_the_pinned_inputs():
182
  assert dedup["input_sha256"] == clean.INPUT_SHA256
183
  assert dedup["reference_sha256"] == {source: sha for source, (_, sha) in clean.REFERENCES.items()}
184
  assert (dedup["drop_at"], dedup["report_at"], dedup["shingle_words"]) == (clean.DROP_AT, clean.REPORT_AT, 5)
185
- assert stats["read"] - sum(stats[k] for k in ("drop_after_end", "drop_before_start", "drop_dup", "drop_cross_source_dup")) == stats["kept"]
 
 
186
  assert sum(dedup["dropped_by_best_group"].values()) == stats["drop_cross_source_dup"]
187
  assert sum(dedup["dropped_by_year"].values()) == stats["drop_cross_source_dup"]
188
  assert sum(dedup["dropped_by_shingles"].values()) == stats["drop_cross_source_dup"]
@@ -202,6 +206,25 @@ def test_shipped_files_follow_from_the_pinned_inputs():
202
  assert {json.loads(line)["id"] for line in stream} == kept_ids
203
 
204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
  def test_pin_check_fails_closed_and_writes_nothing(tmp_path, monkeypatch):
206
  (tmp_path / "x").write_bytes(b"x")
207
  with pytest.raises(SystemExit, match="pinned SHA-256"):
@@ -274,21 +297,6 @@ def test_search_agrees_with_brute_force_and_ties_go_to_the_smaller_id(tmp_path):
274
  assert (doc, "parliamentary:other") not in best
275
 
276
 
277
- def test_header_stripping_keeps_headers_from_inflating_containment():
278
- header = ("Przebieg posiedzenia Poseł Jan Kowalski: 9 kadencja, 3 posiedzenie, 1 dzień - Poseł Jan Kowalski "
279
- "(12-01-2020) 5 punkt porządku dziennego: Sprawozdanie o projekcie ustawy (druk nr 12).")
280
- speech = "Panie Marszałku Wysoka Izbo to jest jedno krótkie wystąpienie"
281
- assert clean.body(f"{speech} {header}").split() == speech.split()
282
- assert clean.body(f"{header} {speech}").split() == speech.split()
283
- assert clean.body(speech) == speech
284
- # a numbered item list belongs to the title; the speech after it does not
285
- listed = ("Przebieg posiedzenia Poseł A: 9 kadencja (01-02-2021) 8. i 9. punkt porządku dziennego: "
286
- "Sprawozdanie pierwsze (druk nr 1). 9. Sprawozdanie drugie (druk nr 2). Dobrze. Panie marszałku, dziękuję.")
287
- assert clean.body(listed).split() == "Dobrze. Panie marszałku, dziękuję.".split()
288
- # two 12-word speeches that differ only in their (identical) header must not look alike
289
- assert clean.body(f"{WORDS('a', 12)} {header}") != clean.body(f"{WORDS('b', 12)} {header}")
290
-
291
-
292
  def test_slice_labels_follow_the_audit_heuristic():
293
  # Patterns copied verbatim from the audit's ppc_classify.py (unvalidated, v2#54); labels only, never a drop rule.
294
  assert clean.ppc_slice("(Wznowienie posiedzenia o godz. 9)\n(Na posiedzeniu przewodniczą marszałek Sejmu)") == "plenary"
@@ -305,12 +313,12 @@ def _synthetic_release(directory, ids_texts):
305
  rows = [{"id": i, "text": t, "source": clean.SOURCE, "added": "2026-08-31", "created": f"2020-01-{n + 1:02d}",
306
  "token_count": len(t.split()), "license": "public-domain (official documents)", "author": "Jan Kowalski"}
307
  for n, (i, t) in enumerate(ids_texts)]
 
308
  pq.write_table(pa.Table.from_pylist(rows), directory / f"{clean.SOURCE}.parquet", row_group_size=2)
309
  (directory / f"{clean.SOURCE}.attribution.jsonl").write_text(
310
- "".join(json.dumps({"id": r["id"], "term": 9, "source_split": "train", "source_url": "u"}) + "\n" for r in rows),
311
- encoding="utf-8")
312
- stats = {"read": len(rows) + 3, "drop_after_end": 3, "drop_before_start": 0, "drop_dup": 0, "kept": len(rows),
313
- "chars": sum(len(r["text"]) for r in rows), "tokens": sum(r["token_count"] for r in rows)}
314
  (directory / f"{clean.SOURCE}.stats.json").write_text(json.dumps(stats), encoding="utf-8")
315
  return {name: hashlib.sha256((directory / name).read_bytes()).hexdigest() for name in clean.INPUT_SHA256}
316
 
@@ -336,6 +344,25 @@ def test_synthetic_build_filters_every_output_consistently(tmp_path, monkeypatch
336
  assert not list(tmp_path.glob("*.tmp"))
337
 
338
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
  def test_build_refuses_an_unreleased_reference(tmp_path, monkeypatch):
340
  (tmp_path / "refs").mkdir()
341
  refs = _write_refs(tmp_path / "refs")
 
13
  sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
14
 
15
  import clean_sejm_api_2011_2022 as clean
16
+ from sejm_api_common import TRAILER, TRUNCATED_TRAILER, release_stats
17
  from sources import SOURCES
18
+ from test_sejm_api_contract import header
19
 
20
  ROOT = pathlib.Path(__file__).resolve().parents[1]
21
  DATA = ROOT / "data" / "sejm_api_2011_2022"
 
184
  assert dedup["input_sha256"] == clean.INPUT_SHA256
185
  assert dedup["reference_sha256"] == {source: sha for source, (_, sha) in clean.REFERENCES.items()}
186
  assert (dedup["drop_at"], dedup["report_at"], dedup["shingle_words"]) == (clean.DROP_AT, clean.REPORT_AT, 5)
187
+ drops = ("drop_after_end", "drop_before_start", "drop_dup", "drop_short", "drop_cross_source_dup")
188
+ assert stats["read"] + stats["split_rows"] - sum(stats[k] for k in drops) == stats["kept"]
189
+ assert stats["trailer_cut"]["split_rows"] == stats["split_rows"] and stats["trailer_cut"]["drop_short"] == stats["drop_short"]
190
  assert sum(dedup["dropped_by_best_group"].values()) == stats["drop_cross_source_dup"]
191
  assert sum(dedup["dropped_by_year"].values()) == stats["drop_cross_source_dup"]
192
  assert sum(dedup["dropped_by_shingles"].values()) == stats["drop_cross_source_dup"]
 
206
  assert {json.loads(line)["id"] for line in stream} == kept_ids
207
 
208
 
209
+ def test_no_trailer_is_left_and_split_rows_are_marked():
210
+ rows = pq.read_table(DATA / "sejm_api_2011_2022.parquet").to_pylist()
211
+ with (DATA / "sejm_api_2011_2022.attribution.jsonl").open(encoding="utf-8") as stream:
212
+ sidecar = [json.loads(line) for line in stream]
213
+ stats = json.loads((DATA / "sejm_api_2011_2022.stats.json").read_text(encoding="utf-8"))
214
+ assert [row["id"] for row in rows if TRAILER.search(row["text"]) or TRUNCATED_TRAILER.search(row["text"])] == []
215
+ assert [row["id"] for row in rows] == [line["id"] for line in sidecar]
216
+ assert len({row["text"] for row in rows}) == len(rows)
217
+ assert all(row["author"] == line["speaker"] and line["char_count"] == len(row["text"])
218
+ for row, line in zip(rows, sidecar))
219
+ recomputed = release_stats(rows, sidecar)
220
+ assert {key: stats[key] for key in recomputed} == recomputed
221
+ split = [(row, line) for row, line in zip(rows, sidecar) if "split_from" in line]
222
+ # Fewer than split_rows: split rows under 200 characters, or contained in a reference, are dropped.
223
+ assert 0 < len(split) <= stats["split_rows"]
224
+ assert all(len(row["text"]) >= 200 and line["has_events"] is None and line["split_from"].startswith(f"{clean.SOURCE}_")
225
+ for row, line in split)
226
+
227
+
228
  def test_pin_check_fails_closed_and_writes_nothing(tmp_path, monkeypatch):
229
  (tmp_path / "x").write_bytes(b"x")
230
  with pytest.raises(SystemExit, match="pinned SHA-256"):
 
297
  assert (doc, "parliamentary:other") not in best
298
 
299
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
300
  def test_slice_labels_follow_the_audit_heuristic():
301
  # Patterns copied verbatim from the audit's ppc_classify.py (unvalidated, v2#54); labels only, never a drop rule.
302
  assert clean.ppc_slice("(Wznowienie posiedzenia o godz. 9)\n(Na posiedzeniu przewodniczą marszałek Sejmu)") == "plenary"
 
313
  rows = [{"id": i, "text": t, "source": clean.SOURCE, "added": "2026-08-31", "created": f"2020-01-{n + 1:02d}",
314
  "token_count": len(t.split()), "license": "public-domain (official documents)", "author": "Jan Kowalski"}
315
  for n, (i, t) in enumerate(ids_texts)]
316
+ sidecar = [{"id": r["id"], "term": "9", "source_split": "train", "source_url": "u", "speaker": r["author"]} for r in rows]
317
  pq.write_table(pa.Table.from_pylist(rows), directory / f"{clean.SOURCE}.parquet", row_group_size=2)
318
  (directory / f"{clean.SOURCE}.attribution.jsonl").write_text(
319
+ "".join(json.dumps(line) + "\n" for line in sidecar), encoding="utf-8")
320
+ stats = {"read": len(rows) + 3, "drop_after_end": 3, "drop_before_start": 0, "drop_dup": 0,
321
+ **release_stats(rows, sidecar)}
 
322
  (directory / f"{clean.SOURCE}.stats.json").write_text(json.dumps(stats), encoding="utf-8")
323
  return {name: hashlib.sha256((directory / name).read_bytes()).hexdigest() for name in clean.INPUT_SHA256}
324
 
 
344
  assert not list(tmp_path.glob("*.tmp"))
345
 
346
 
347
+ def test_trailers_are_cut_before_containment(tmp_path, monkeypatch):
348
+ (tmp_path / "refs").mkdir()
349
+ refs = _write_refs(tmp_path / "refs")
350
+ statement = WORDS("w", 40) + " " + WORDS("x", 20) # 219 characters; 36 of its 56 shingles are in ref_p1
351
+ # Uncut, the row would hold those 36 among ~130 shingles (under REPORT_AT) and be kept whole.
352
+ text = WORDS("q", 60) + " " + header("Jan Nowak", "Poseł Jan Nowak", "01-01-2020") + " Poseł Jan Nowak: " + statement
353
+ monkeypatch.setattr(clean, "INPUT_SHA256", _synthetic_release(tmp_path, [("speech", text)]))
354
+ references = {s: (p, hashlib.sha256(p.read_bytes()).hexdigest()) for s, p in refs.items()}
355
+ stats = clean.build(tmp_path, references, tmp_path, workers=1, check_registry=False)
356
+
357
+ assert pq.read_table(tmp_path / f"{clean.SOURCE}.parquet").to_pylist()[0]["text"] == WORDS("q", 60)
358
+ assert [json.loads(line)["id"] for line in (tmp_path / f"{clean.SOURCE}.attribution.jsonl").open()] == ["speech"]
359
+ decisions = [json.loads(line) for line in (tmp_path / clean.DECISIONS).open()]
360
+ assert [(d["action"], d["containment"], d["ref_id"]) for d in decisions] == [("drop", round(36 / 56, 4), "ref_p1")]
361
+ assert decisions[0]["id"].startswith(f"{clean.SOURCE}_")
362
+ assert (stats["kept"], stats["split_rows"], stats["drop_short"], stats["drop_cross_source_dup"]) == (1, 1, 0, 1)
363
+ assert stats["trailer_cut"]["rows_cut"] == 1
364
+
365
+
366
  def test_build_refuses_an_unreleased_reference(tmp_path, monkeypatch):
367
  (tmp_path / "refs").mkdir()
368
  refs = _write_refs(tmp_path / "refs")