sejm_api_2011_2022: re-pin the dedup to the PPC TEI parliamentary (v2#54, 5A)

#110
by ppuzio - opened
artifacts/source_findings.md CHANGED
@@ -2379,3 +2379,29 @@ lines of real text (`2020 r.`) and 82 records quoting the transcript title in ru
2379
  a speaker filter is only as good as the turn boundaries under it: the first allowlist filtered
2380
  labels correctly but kept a guest's words inside an official's turn because the splitter knew only
2381
  role-anchored labels. Cut at everything that looks like a label, then classify.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2379
  a speaker filter is only as good as the turn boundaries under it: the first allowlist filtered
2380
  labels correctly but kept a guest's words inside an official's turn because the splitter knew only
2381
  role-anchored labels. Cut at everything that looks like a label, then classify.
2382
+
2383
+ ## sejm_api_2011_2022 — dedup re-pinned to the PPC TEI `parliamentary` (2026-10-08)
2384
+
2385
+ **Finding** (slayerlabs/polish-dynaword-v2#54, option 5A) — the cross-source dedup scored
2386
+ against the v0.2.5 `parliamentary`, which Hub PR 108 replaces with a rebuild from the PPC TEI
2387
+ dump under a speaker allowlist. The rebuild keeps Sejm plenary text up to term 8 but drops
2388
+ speakers the allowlist does not match, so a dedup against it keeps rows the old shard dropped.
2389
+
2390
+ **Fix** — `REFERENCES` pins the rebuilt `parliamentary.parquet` (`5f21252e…`). Reference groups
2391
+ are read from the record id (`PPC_ID`, `PPC_KINDS`: house and directory code; plenary,
2392
+ interpellation and reply codes are listed, every other code is a committee) instead of the old
2393
+ heuristic. The duplicate outcome key `sejm_api_only` (same count as `only_sejm_api`) is removed.
2394
+ 126,967 rows enter the search as before; 92,369 are contained (93,861), 34,598 published
2395
+ (33,106), 28,712,009 tokens. Against the old build 22 rows are newly dropped (2020-2022 Sejm
2396
+ speeches 0.50-0.71 contained in a 2019-2023 Senate document) and 1,514 rows (7,126,113
2397
+ characters) are kept again: 573 (4,908,128) whose speaker the allowlist drops (citizens'
2398
+ initiative representatives, the President's Chancellery, the Prosecutor General's office, agency
2399
+ heads; slayerlabs/polish-dynaword-v2#99), 470 (1,084,769) not in the dump (435 of them
2400
+ "(tekst niewygłoszony)"), 357 (911,196) mostly in kept text but under 0.5 (315 lose mainly
2401
+ floor interjections), 114 (222,020) to other rebuild drops. The 23 speeches of MP Piotr van der
2402
+ Coghen stay dropped: the rebuild's name check keeps a member's name with a particle (decision
2403
+ 1A of 2026-10-08). Parquet sha256 `f6ec51dfd87b47b93905adcdd8f8dfb3f8449d6319df4153526c900bf258062f`.
2404
+
2405
+ **Not established** — the hand checks in the card still date from Hub PR 76. The 573 rows whose
2406
+ speaker no allowlist rule matches stay here until the allowlist is applied to this source
2407
+ (slayerlabs/polish-dynaword-v2#99).
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:bb45cbd376de47a0244a661ac9eddf8a06a56ac37d048d5bcb00555c61dba72c
3
- size 16449002
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f0265fc4f2ee057a3c0d8d3b83ade5d1c2a9b02a6cac3c9729075d186c5e2eaa
3
+ size 17245797
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:848e9f7bb3731149c2533d9a0e86896fc8e4129871dd6390534fc47d8499b86f
3
- size 29347301
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0af52b4c94f4afee54471cb3da82a82071de9d08e12174a990519d2c0b7aee97
3
+ size 31246917
data/sejm_api_2011_2022/sejm_api_2011_2022.md CHANGED
@@ -11,7 +11,7 @@ from the already merged `sejm_api` 2023-onward artifact.
11
  - Domain: political/spoken
12
  - Language: Polish (`pl`)
13
  - License: `public-domain (official documents)`
14
- - Created: 2011-12-14 through 2022-12-14
15
  - Added: 2026-08-31
16
  - Contributor: Piotr Styła (`PiotrSty` on Hugging Face; `PiotrStyla` on GitHub)
17
 
@@ -46,54 +46,75 @@ Hub PR 18) and `has_events: null`, since the snapshot's events flag describes th
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
 
54
  The rights audit (slayerlabs/polish-dynaword-v2#57) found that this source
55
- re-publishes text already in `parliamentary` (released in 0.2.0). A speech is now
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.
84
- The slice split is the audit's heuristic classifier (`ppc_classify.py`, unvalidated):
85
- its "committee" label also catches plenary sittings (10 of 11 committee-labelled
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
 
@@ -105,11 +126,11 @@ the 6 that did not are all dated 2020 or later.
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
 
@@ -141,7 +162,7 @@ Which cleaning ran, in order:
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
 
11
  - Domain: political/spoken
12
  - Language: Polish (`pl`)
13
  - License: `public-domain (official documents)`
14
+ - Created: 2011-11-08 through 2022-12-14
15
  - Added: 2026-08-31
16
  - Contributor: Piotr Styła (`PiotrSty` on Hugging Face; `PiotrStyla` on GitHub)
17
 
 
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; 3,082 split rows are
50
+ published, 500 of them cut from a speech that is itself dropped as contained.
51
 
52
  ## Existing-source overlap
53
 
54
  The rights audit (slayerlabs/polish-dynaword-v2#57) found that this source
55
+ re-publishes text already in `parliamentary`. A speech is dropped when one document
56
+ of a pinned reference set holds at least half of its 5-word shingles (containment
57
+ >= 0.5 over NFKC-casefolded `\w+` tokens, the tokenisation of the repo's `near_dedup`,
58
+ in `src/shingle_containment.py`; the trailers are cut first, see "Trailer cut"). The
59
+ reference set is every Parquet whose registry `release` is not `None`:
60
+ `parliamentary` (the PPC TEI rebuild of slayerlabs/polish-dynaword-v2#54, Hub PR 108)
61
+ and `sejm_api` (after its own trailer cut), each pinned by SHA-256 in `REFERENCES`.
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, against all references and against
66
+ each reference group alone (a row can match several groups). A `parliamentary` group
67
+ is read from the record id: the house (`sjm` Sejm, `snt` Senate) and the dump's
68
+ directory code (plenary sitting, interpellation, reply to one; every other code is a
69
+ committee).
70
+
71
+ | Outcome key | Reference set | Dropped |
72
+ |---|---|---:|
73
+ | `all_references` | `parliamentary` + `sejm_api` (this build) | 92,369 |
74
+ | `parliamentary_all` | `parliamentary`, all groups | 92,347 |
75
+ | `only_parliamentary_sjm-plenary` | Sejm plenary sittings | 92,312 |
76
+ | `only_parliamentary_sjm-committee` | Sejm committee sittings | 125 |
77
+ | `only_parliamentary_sjm-interpellation` | Sejm interpellations | 281 |
78
+ | `only_parliamentary_sjm-reply` | Replies to Sejm interpellations | 19 |
79
+ | `only_parliamentary_snt-plenary` | Senate plenary sittings | 86 |
80
+ | `only_parliamentary_snt-committee` | Senate committee sittings | 27 |
81
+ | `only_sejm_api` | `sejm_api` | 45 |
82
+
83
+ The overlap is the Sejm plenary record of 2011-2019: 92,281 of the 92,369 drops are
84
+ dated 2011-2019. Kept per year, 2011-2019: 48, 120, 96, 102, 190, 235, 343, 304, 1,346;
85
+ 2020-2022 are nearly intact (88 dropped). Another 1,059 rows score 0.3-0.5 and are kept.
86
+
87
+ Against the v0.2.5 `parliamentary` this step dropped 93,861 rows. Against the rebuild,
88
+ 22 more rows are dropped (Sejm speeches of 2020-2022 that are 0.50-0.71 contained in a
89
+ 2019-2023 Senate document) and 1,514 rows (7,126,113 characters) are kept again:
90
+
91
+ - 573 rows (4,908,128 characters) are in the PPC dump, but the rebuild drops their
92
+ speaker because no allowlist rule matches: representatives of citizens' legislative
93
+ initiative committees, the President's Chancellery, the Prosecutor General's office
94
+ and agency heads. The allowlist does not apply to this source yet
95
+ (slayerlabs/polish-dynaword-v2#99), so they stay here.
96
+ - 470 rows (1,084,769 characters) are not in the dump: under 0.3 of their shingles
97
+ occur in its Sejm sittings of the same day. 435 of them are statements entered into
98
+ the record without being delivered (the author ends in "(tekst niewygłoszony)"),
99
+ which the dump's stenograms do not hold.
100
+ - 357 rows (911,196 characters) sit mostly in text the rebuild keeps but score under
101
+ 0.5. In 315 of them most of the rest is floor interjections (lines with ": "), which
102
+ the rebuild drops.
103
+ - 114 rows (222,020 characters) fall to other drops of the rebuild: speakers without a
104
+ role in the dump's header (41), interjection lines (50), free-text labels (14),
105
+ speaker lines inside a turn (8) and a committee chair who is not a member (1).
106
+
107
+ The 23 speeches of MP Piotr van der Coghen stay dropped: the rebuild keeps a name with a
108
+ particle when it is a member's (slayerlabs/polish-dynaword-v2#54, decision 1A).
109
 
110
  Known limits: containment is measured against single reference documents, not a union,
111
  and a threshold of 0.5 with no minimum size also drops short formulaic speeches. The
112
+ hand checks that follow were made against the v0.2.5 `parliamentary` before the trailer
113
+ cut (Hub PR 76), which had 170 drops dated 2020 or later, against 88 now. In a random 12
114
+ of those 170, 9 were stage directions or stock phrases, 2 were report templates
115
+ (0.5-0.58) and 1 was real reuse. In a hand check of 20 pairs between 0.3 and 0.7, 14 had
116
+ the speech's own wording in the reference (4 of 10 between 0.3 and 0.5, 10 of 10 between
117
+ 0.5 and 0.7); the 6 that did not are all dated 2020 or later.
118
 
119
  ## Statistics
120
 
 
126
  | Statements split into rows of their own | 15,648 |
127
  | Rows under 200 characters after the trailer cut | 7,563 |
128
  | Exact duplicate texts removed | 20 |
129
+ | Contained in `parliamentary` / `sejm_api` (containment >= 0.5) | 92,369 |
130
+ | Documents published | 34,598 |
131
+ | Characters | 77,313,079 |
132
+ | Tokens (`cl100k_base` proxy) | 28,712,009 |
133
+ | Documents with speaker attribution | 34,598 |
134
 
135
  The canonical schema is `id, text, source, added, created, token_count, license, author`.
136
 
 
162
  3. **Trailer cut and cross-source dedup** (`src/clean_sejm_api_2011_2022.py`, run on
163
  the output of step 2): cuts the "Przebieg posiedzenia" trailers and splits the
164
  appended statements into rows of their own (see "Trailer cut"), then drops the
165
+ 92,369 rows contained (5-shingle containment >= 0.5) in a `parliamentary` or
166
  `sejm_api` document; see "Existing-source overlap".
167
 
168
  Apart from the trailer cut, before/after at the text level is a deliberate no-op (the pinned
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:622228ca4c287f91792b7da3fb97c098610c1cf890f1bdc08922dc3aca3742db
3
- size 28185916
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f6ec51dfd87b47b93905adcdd8f8dfb3f8449d6319df4153526c900bf258062f
3
+ size 31048209
data/sejm_api_2011_2022/sejm_api_2011_2022.stats.json CHANGED
@@ -1,45 +1,45 @@
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": {
@@ -49,7 +49,7 @@
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,
@@ -60,49 +60,49 @@
60
  "sejm_api_2011_2022.stats.json": "398dbaff87ec8f1d8702fce347db65ae8a3e4cf69a90594a6c7998cc4441c356"
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
  }
 
1
  {
2
  "added": "2026-08-31",
3
+ "authors_with_value": 34598,
4
  "by_source_split": {
5
+ "train": 33914,
6
+ "validation": 684
7
  },
8
  "by_term": {
9
+ "7": 461,
10
+ "8": 1220,
11
+ "9": 32917
12
  },
13
  "by_year": {
14
+ "2011": 48,
15
+ "2012": 120,
16
+ "2013": 96,
17
+ "2014": 102,
18
+ "2015": 190,
19
+ "2016": 235,
20
+ "2017": 343,
21
+ "2018": 304,
22
+ "2019": 1346,
23
+ "2020": 7934,
24
+ "2021": 10238,
25
+ "2022": 13642
26
  },
27
+ "chars": 77313079,
28
  "created_max": "2022-12-14",
29
+ "created_min": "2011-11-08",
30
  "drop_after_end": 38812,
31
  "drop_before_start": 0,
32
  "drop_dup": 20,
33
+ "kept": 34598,
34
  "license": "public-domain (official documents)",
35
  "licenses": {
36
+ "public-domain (official documents)": 34598
37
  },
38
  "read": 157714,
39
  "source_revision": "124557799608ce4212cf22fa90ca7904618de1b6",
40
  "stats_recomputed_from_parquet": true,
41
  "target_base_revision": "a9d134ac79a9fe586fc9c11cb39eb32d69dcd21f",
42
+ "tokens": 28712009,
43
  "split_rows": 15648,
44
  "drop_short": 7563,
45
  "trailer_cut": {
 
49
  "drop_short": 7563,
50
  "drop_dup": 20
51
  },
52
+ "drop_cross_source_dup": 92369,
53
  "cross_source_dedup": {
54
  "drop_at": 0.5,
55
  "report_at": 0.3,
 
60
  "sejm_api_2011_2022.stats.json": "398dbaff87ec8f1d8702fce347db65ae8a3e4cf69a90594a6c7998cc4441c356"
61
  },
62
  "reference_sha256": {
63
+ "parliamentary": "5f21252ee65425a77cdd48bdb964171fb06cd6cf0c59c0b882be995d84dcec7c",
64
  "sejm_api": "ba2daa20d2d2753c09e8bdd477839f43c82170f44caeadc634cb2295362c9c3b"
65
  },
66
  "no_shingles": 0,
67
  "dropped_by_best_group": {
68
+ "parliamentary:sjm-committee": 3,
69
+ "parliamentary:sjm-interpellation": 15,
70
+ "parliamentary:sjm-plenary": 92304,
71
+ "parliamentary:snt-committee": 14,
72
+ "parliamentary:snt-plenary": 8,
73
+ "sejm_api": 25
74
  },
75
  "dropped_by_year": {
76
+ "2011": 949,
77
+ "2012": 12462,
78
+ "2013": 12859,
79
+ "2014": 11305,
80
+ "2015": 11330,
81
+ "2016": 13991,
82
+ "2017": 12470,
83
+ "2018": 10604,
84
+ "2019": 6311,
85
+ "2020": 15,
86
+ "2021": 38,
87
+ "2022": 35
88
  },
89
  "dropped_by_shingles": {
90
  "<10": 0,
91
+ "10-19": 3,
92
+ "20-49": 3769,
93
+ "50-199": 42466,
94
+ ">=200": 46131
95
  },
96
+ "kept_partial": 1059,
97
  "outcomes": {
98
+ "all_references": 92369,
99
+ "parliamentary_all": 92347,
100
+ "only_parliamentary_sjm-committee": 125,
101
+ "only_parliamentary_sjm-interpellation": 281,
102
+ "only_parliamentary_sjm-plenary": 92312,
103
+ "only_parliamentary_sjm-reply": 19,
104
+ "only_parliamentary_snt-committee": 27,
105
+ "only_parliamentary_snt-plenary": 86,
 
106
  "only_sejm_api": 45
107
  }
108
  }
src/clean_sejm_api_2011_2022.py CHANGED
@@ -1,9 +1,9 @@
1
  #!/usr/bin/env python3
2
  """Drop sejm_api_2011_2022 speeches already contained in a pinned reference set (slayerlabs/polish-dynaword-v2#57).
3
 
4
- The rights audit found that sejm_api_2011_2022 overlaps `parliamentary` (2011-2019) and the
5
- since-removed `parlamint_pl`. A speech is dropped when one document of the reference set holds at
6
- least DROP_AT of its shingles:
7
 
8
  containment(speech, ref) = |S(speech) & S(ref)| / |S(speech)|
9
 
@@ -16,17 +16,17 @@ document can be a whole sitting while a speech is a few paragraphs. It is measur
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
20
- committee slice), re-pin REFERENCES and rerun this script on the restored input; nothing here
21
  follows the registry silently.
22
 
23
  Exact search: the speeches are indexed, the references are streamed. A speech is found when a
24
  reference shares at least one of its rarest (1 - REPORT_AT) * n + 1 shingles (prefix filter,
25
  exact by pigeonhole), and every such candidate is then scored on its full shingle sets. No
26
  MinHash/LSH, so there is no sampling error. Speeches scoring from REPORT_AT up are written to
27
- sejm_api_2011_2022.decisions.jsonl with the best score against each reference group, so the
28
- effect of each #54 outcome can be read without rerunning. Speeches under five words have no
29
- shingles and are never dropped.
30
 
31
  The inputs are the pre-dedup release files, pinned by SHA-256. Restore them before a rerun:
32
  git checkout 3bab9f9 -- data/sejm_api_2011_2022/sejm_api_2011_2022.{parquet,attribution.jsonl,stats.json}
@@ -66,7 +66,7 @@ INPUT_SHA256 = {
66
  # `parlamint_pl` left the registry in Hub PR 54 and never had data, so it cannot be pinned.
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
  }
@@ -76,29 +76,22 @@ REPORT_AT = 0.3
76
  ROW_GROUP_SIZE = 1024 # the layout of the released file
77
  SIZE_BUCKETS = (("<10", 0, 10), ("10-19", 10, 20), ("20-49", 20, 50), ("50-199", 50, 200), (">=200", 200, 10**9))
78
 
79
- _R = lambda pattern: re.compile(pattern, re.I) # noqa: E731
80
- # The audit's heuristic split of `parliamentary` (artifacts/rights_audit_2026-10/official/ppc_classify.py,
81
- # unvalidated, v2#54). It only labels the report; the drop decision never uses it.
82
- PPC_COMMITTEE = _R(r'(Otwieram|Rozpoczynam|Witam)[^.\n]{0,160}(posiedzenie|posiedzeniu|Komisji)|posiedzenie (Komisji|Podkomisji)|^\(Początek posiedzenia|Posiedzeniu przewodniczy')
83
- PPC_PLENARY = _R(r'^\((Wznowienie|Początek|Ciąg dalszy|Przerwa)[^)]*\)\s*\n?\(?(Posiedzeniu przewodnicz|Na posiedzeniu przewodnicz)|Wysoka Izbo|Wysoki Sejmie|Wysoki Senacie')
84
- PPC_REPLY = _R(r'SPS-0\d\d|W odpowiedzi na (interpelacj|zapytani)|Odpowiadając na (interpelacj|zapytani)|odpowiedzi na (interpelacj|zapytani)|w związku z (interpelacj|zapytani)')
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):
91
- return "committee"
92
- if PPC_PLENARY.search(text[:4000]) and not PPC_REPLY.search(head):
93
- return "plenary"
94
- if PPC_REPLY.search(head):
95
- return "interp_reply"
96
- return "interp_question" if PPC_QUESTION.search(head) else "other"
97
-
98
-
99
- def group_of(source: str, text: str) -> str:
100
- """Reference group a document is reported under: `parliamentary:<slice>` or the source key."""
101
- return f"parliamentary:{ppc_slice(text)}" if source == "parliamentary" else source
102
 
103
 
104
  def min_shared(sizes: np.ndarray, at: float) -> np.ndarray:
@@ -162,7 +155,7 @@ def _scan_row_group(task: tuple[str, str, int]) -> dict[tuple[int, str], tuple[i
162
  hits = int(lens.sum())
163
  if not hits:
164
  continue
165
- group = group_of(source, text)
166
  for doc in np.unique(prefix_doc[np.repeat(lo - np.cumsum(lens) + lens, lens) + np.arange(hits)]):
167
  speech = flat[offsets[doc]:offsets[doc + 1]]
168
  at = np.minimum(np.searchsorted(ref, speech), len(ref) - 1)
@@ -217,15 +210,13 @@ def score_table(sizes: np.ndarray, best: dict[tuple[int, str], tuple[int, str]],
217
 
218
 
219
  def outcomes(scores: np.ndarray, groups: list[str]) -> dict[str, int]:
220
- """Speeches dropped (best score >= DROP_AT) for each reference set the maintainers may end up with."""
221
  def dropped(wanted):
222
  cols = [i for i, g in enumerate(groups) if wanted(g)]
223
  return int((scores[:, cols].max(axis=1) >= DROP_AT).sum()) if cols else 0
224
  return {
225
  "all_references": dropped(lambda g: True),
226
- "sejm_api_only": dropped(lambda g: g == "sejm_api"),
227
  "parliamentary_all": dropped(lambda g: g.startswith("parliamentary:")),
228
- "parliamentary_without_committee_plus_sejm_api": dropped(lambda g: g != "parliamentary:committee"),
229
  **{f"only_{g.replace(':', '_')}": dropped(lambda x, g=g: x == g) for g in groups},
230
  }
231
 
 
1
  #!/usr/bin/env python3
2
  """Drop sejm_api_2011_2022 speeches already contained in a pinned reference set (slayerlabs/polish-dynaword-v2#57).
3
 
4
+ The rights audit found that sejm_api_2011_2022 overlaps `parliamentary` (Sejm sittings to the end of
5
+ term 8, sejm_api_common.PARLIAMENTARY_SEJM_END) and the since-removed `parlamint_pl`. A speech is
6
+ dropped when one document of the reference set holds at least DROP_AT of its shingles:
7
 
8
  containment(speech, ref) = |S(speech) & S(ref)| / |S(speech)|
9
 
 
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. `parliamentary` is the PPC TEI rebuild of slayerlabs/polish-dynaword-v2#54 (option C). When a
20
+ reference changes, re-pin REFERENCES and rerun this script on the restored input; nothing here
21
  follows the registry silently.
22
 
23
  Exact search: the speeches are indexed, the references are streamed. A speech is found when a
24
  reference shares at least one of its rarest (1 - REPORT_AT) * n + 1 shingles (prefix filter,
25
  exact by pigeonhole), and every such candidate is then scored on its full shingle sets. No
26
  MinHash/LSH, so there is no sampling error. Speeches scoring from REPORT_AT up are written to
27
+ sejm_api_2011_2022.decisions.jsonl with the best score against each reference group
28
+ (`parliamentary:<house>-<kind>` from the record id, or the source key). Speeches under five words
29
+ have no shingles and are never dropped.
30
 
31
  The inputs are the pre-dedup release files, pinned by SHA-256. Restore them before a rerun:
32
  git checkout 3bab9f9 -- data/sejm_api_2011_2022/sejm_api_2011_2022.{parquet,attribution.jsonl,stats.json}
 
66
  # `parlamint_pl` left the registry in Hub PR 54 and never had data, so it cannot be pinned.
67
  REFERENCES = {
68
  "parliamentary": (ROOT / "data/parliamentary/parliamentary.parquet",
69
+ "5f21252ee65425a77cdd48bdb964171fb06cd6cf0c59c0b882be995d84dcec7c"),
70
  "sejm_api": (ROOT / "data/sejm_api/sejm_api.parquet", # after src/clean_sejm_api.py
71
  "ba2daa20d2d2753c09e8bdd477839f43c82170f44caeadc634cb2295362c9c3b"),
72
  }
 
76
  ROW_GROUP_SIZE = 1024 # the layout of the released file
77
  SIZE_BUCKETS = (("<10", 0, 10), ("10-19", 10, 20), ("20-49", 20, 50), ("50-199", 50, 200), (">=200", 200, 10**9))
78
 
79
+ # `parliamentary` ids are parliamentary_<term>-<house>-<code>-<sitting>-<part> (src/fetch_parliamentary.py),
80
+ # <code> being the dump's directory name padded with "x" to five letters. These codes are the plenary and
81
+ # interpellation directories; every other code is a committee. Codes can be non-ASCII ("kśpxx").
82
+ PPC_ID = re.compile(r"parliamentary_\d+-(sjm|snt|krn)-(\w+)-\d+-\d+")
83
+ PPC_KINDS = {"ppxxx": "plenary", "usxxx": "plenary", "uzxxx": "plenary", "wsxxx": "plenary", "znxxx": "plenary",
84
+ "ipxxx": "interpellation", "zpxxx": "interpellation", "ioxxx": "reply", "zoxxx": "reply"}
 
85
 
86
 
87
+ def group_of(source: str, ref_id: str) -> str:
88
+ """Reference group a document is reported under: `parliamentary:<house>-<kind>` or the source key."""
89
+ if source != "parliamentary":
90
+ return source
91
+ match = PPC_ID.fullmatch(ref_id)
92
+ if not match:
93
+ raise ValueError(f"{ref_id!r} is not a parliamentary record id")
94
+ return f"parliamentary:{match[1]}-{PPC_KINDS.get(match[2], 'committee')}"
 
 
 
 
 
 
95
 
96
 
97
  def min_shared(sizes: np.ndarray, at: float) -> np.ndarray:
 
155
  hits = int(lens.sum())
156
  if not hits:
157
  continue
158
+ group = group_of(source, ref_id)
159
  for doc in np.unique(prefix_doc[np.repeat(lo - np.cumsum(lens) + lens, lens) + np.arange(hits)]):
160
  speech = flat[offsets[doc]:offsets[doc + 1]]
161
  at = np.minimum(np.searchsorted(ref, speech), len(ref) - 1)
 
210
 
211
 
212
  def outcomes(scores: np.ndarray, groups: list[str]) -> dict[str, int]:
213
+ """Speeches dropped (best score >= DROP_AT) against each reference, and against each group alone."""
214
  def dropped(wanted):
215
  cols = [i for i, g in enumerate(groups) if wanted(g)]
216
  return int((scores[:, cols].max(axis=1) >= DROP_AT).sum()) if cols else 0
217
  return {
218
  "all_references": dropped(lambda g: True),
 
219
  "parliamentary_all": dropped(lambda g: g.startswith("parliamentary:")),
 
220
  **{f"only_{g.replace(':', '_')}": dropped(lambda x, g=g: x == g) for g in groups},
221
  }
222
 
src/sources.py CHANGED
@@ -332,13 +332,13 @@ SOURCES = {
332
  "src/clean_sejm_api_2011_2022.py cuts the \"Przebieg posiedzenia\" "
333
  "trailers (appended statements become rows of their own) and drops rows "
334
  "whose 5-shingle containment in one document of the pinned "
335
- "parliamentary / sejm_api Parquets is >= 0.5 (118,902 -> 33,106 docs; "
336
- "re-pin and rerun if polish-dynaword-v2#54 changes parliamentary). NERGAL "
337
  "not run - re-run "
338
  "through SlayerLab/NERGAL before release. Shared helpers factored into "
339
  "src/sejm_api_common.py.",
340
  "domain": "political/spoken",
341
- "created": "2011-12-14, 2022-12-14",
342
  "is_ocr": False,
343
  "custom_datasheet": True,
344
  },
 
332
  "src/clean_sejm_api_2011_2022.py cuts the \"Przebieg posiedzenia\" "
333
  "trailers (appended statements become rows of their own) and drops rows "
334
  "whose 5-shingle containment in one document of the pinned "
335
+ "parliamentary / sejm_api Parquets is >= 0.5 (118,902 -> 34,598 docs; "
336
+ "parliamentary is the polish-dynaword-v2#54 PPC TEI rebuild). NERGAL "
337
  "not run - re-run "
338
  "through SlayerLab/NERGAL before release. Shared helpers factored into "
339
  "src/sejm_api_common.py.",
340
  "domain": "political/spoken",
341
+ "created": "2011-11-08, 2022-12-14",
342
  "is_ocr": False,
343
  "custom_datasheet": True,
344
  },
src/test_sejm_api_2011_2022_contract.py CHANGED
@@ -225,6 +225,44 @@ def test_no_trailer_is_left_and_split_rows_are_marked():
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"):
@@ -244,31 +282,32 @@ def test_pin_check_fails_closed_and_writes_nothing(tmp_path, monkeypatch):
244
 
245
 
246
  WORDS = lambda tag, count: " ".join(f"{tag}{i}" for i in range(count)) # noqa: E731
 
247
 
248
 
249
  def _write_refs(tmp_path):
250
  parliamentary, sejm_api = tmp_path / "parliamentary.parquet", tmp_path / "sejm_api.parquet"
251
- pq.write_table(pa.table({"id": ["ref_p1", "ref_p2"], "text": [WORDS("w", 40), WORDS("z", 40)]}), parliamentary)
252
  pq.write_table(pa.table({"id": ["ref_s1"], "text": [WORDS("s", 40)]}), sejm_api)
253
  return {"parliamentary": parliamentary, "sejm_api": sejm_api}
254
 
255
 
256
  def test_synthetic_containment_boundaries_and_groups(tmp_path):
257
  texts = [
258
- WORDS("w", 20), # 0: all of it is in ref_p1 -> 1.0
259
  WORDS("w", 8) + " " + WORDS("a", 6), # 1: 4 of 10 shingles -> 0.4, reported, kept
260
  WORDS("w", 8) + " " + WORDS("b", 4), # 2: 4 of 8 shingles -> exactly 0.5, dropped
261
  WORDS("q", 30), # 3: unrelated
262
  "w0 w1 w2 w3", # 4: under five words, no shingles
263
- WORDS("w", 20) + " " + WORDS("s", 20), # 5: ref_p1 holds 16 of 36, ref_s1 holds 16 of 36
264
  WORDS("s", 30), # 6: only in the sejm_api reference
265
  ]
266
  sizes, best = clean.find_contained(texts, _write_refs(tmp_path), tmp_path, workers=1)
267
  assert sizes.tolist() == [16, 10, 8, 26, 0, 36, 26]
268
- assert best[(0, "parliamentary:other")] == (16, "ref_p1")
269
- assert best[(1, "parliamentary:other")] == (4, "ref_p1")
270
- assert best[(2, "parliamentary:other")] == (4, "ref_p1")
271
- assert best[(5, "parliamentary:other")] == (16, "ref_p1")
272
  assert best[(5, "sejm_api")] == (16, "ref_s1")
273
  assert best[(6, "sejm_api")] == (26, "ref_s1")
274
  assert not {doc for doc, _ in best} & {3, 4}
@@ -276,13 +315,16 @@ def test_synthetic_containment_boundaries_and_groups(tmp_path):
276
  scores = clean.score_table(sizes, best, groups)
277
  assert scores[2].max() == 0.5 and scores[1].max() == 0.4
278
  assert clean.outcomes(scores, groups)["all_references"] == 3 # docs 0, 2 and 6; doc 5 holds 16/36 = 0.44 per group
279
- assert clean.outcomes(scores, groups)["sejm_api_only"] == 1 # doc 6
 
 
280
 
281
 
282
  def test_search_agrees_with_brute_force_and_ties_go_to_the_smaller_id(tmp_path):
283
  from shingle_containment import shingles
284
  refs = {"parliamentary": tmp_path / "parliamentary.parquet"}
285
- ref_texts = {"ref_b": WORDS("w", 25), "ref_a": WORDS("w", 25), "ref_c": WORDS("w", 12) + " " + WORDS("k", 20)}
 
286
  pq.write_table(pa.table({"id": list(ref_texts), "text": list(ref_texts.values())}), refs["parliamentary"],
287
  row_group_size=1)
288
  texts = [WORDS("w", n) + " " + WORDS(f"n{n}_", m) for n, m in ((25, 0), (14, 6), (10, 10), (6, 12))]
@@ -292,20 +334,33 @@ def test_search_agrees_with_brute_force_and_ties_go_to_the_smaller_id(tmp_path):
292
  expected = {rid: len(mine & set(shingles(r).tolist())) for rid, r in ref_texts.items()}
293
  top = max(expected.values())
294
  if top >= clean.min_shared(sizes[doc:doc + 1], clean.REPORT_AT)[0]:
295
- assert best[(doc, "parliamentary:other")] == (top, min(r for r, n in expected.items() if n == top))
296
  else:
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"
303
- assert clean.ppc_slice("Otwieram posiedzenie Komisji Kultury") == "committee"
304
- assert clean.ppc_slice("W odpowiedzi na interpelację nr 5") == "interp_reply"
305
- assert clean.ppc_slice("Szanowny Panie Ministrze, zwracam się") == "interp_question"
306
- assert clean.ppc_slice(WORDS("w", 10)) == "other"
307
- assert clean.group_of("parliamentary", WORDS("w", 10)) == "parliamentary:other"
308
- assert clean.group_of("sejm_api", "Otwieram posiedzenie Komisji") == "sejm_api"
309
 
310
 
311
  def _synthetic_release(directory, ids_texts):
@@ -336,7 +391,7 @@ def test_synthetic_build_filters_every_output_consistently(tmp_path, monkeypatch
336
  assert [json.loads(line)["id"] for line in (tmp_path / f"{clean.SOURCE}.attribution.jsonl").open()] == ["keep", "part", "tiny"]
337
  decisions = [json.loads(line) for line in (tmp_path / clean.DECISIONS).open()]
338
  assert [(d["id"], d["action"], d["containment"], d["ref_id"]) for d in decisions] == [
339
- ("dup", "drop", 1.0, "ref_p1"), ("edge", "drop", 0.5, "ref_p1"), ("part", "keep_partial", 0.4, "ref_p1")]
340
  assert (stats["kept"], stats["drop_cross_source_dup"], stats["read"]) == (3, 2, 8)
341
  assert stats["chars"] == sum(len(t) for i, t in release if i in ("keep", "part", "tiny"))
342
  assert stats["cross_source_dedup"]["no_shingles"] == 1 and stats["cross_source_dedup"]["kept_partial"] == 1
@@ -347,7 +402,7 @@ def test_synthetic_build_filters_every_output_consistently(tmp_path, monkeypatch
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)]))
@@ -357,7 +412,7 @@ def test_trailers_are_cut_before_containment(tmp_path, monkeypatch):
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
 
225
  for row, line in split)
226
 
227
 
228
+ def test_card_cites_the_stats():
229
+ stats = json.loads((DATA / "sejm_api_2011_2022.stats.json").read_text(encoding="utf-8"))
230
+ dedup = stats["cross_source_dedup"]
231
+ card = " ".join((DATA / "sejm_api_2011_2022.md").read_text(encoding="utf-8").split())
232
+ table = {
233
+ "Source rows inspected": stats["read"],
234
+ "Rows after 2022-12-31 excluded": stats["drop_after_end"],
235
+ "Rows before 2011-01-01 excluded": stats["drop_before_start"],
236
+ "Statements split into rows of their own": stats["split_rows"],
237
+ "Rows under 200 characters after the trailer cut": stats["drop_short"],
238
+ "Exact duplicate texts removed": stats["drop_dup"],
239
+ "Contained in `parliamentary` / `sejm_api` (containment >= 0.5)": stats["drop_cross_source_dup"],
240
+ "Documents published": stats["kept"],
241
+ "Characters": stats["chars"],
242
+ "Tokens (`cl100k_base` proxy)": stats["tokens"],
243
+ "Documents with speaker attribution": stats["authors_with_value"],
244
+ }
245
+ for label, value in table.items():
246
+ assert f"| {label} | {value:,} |" in card
247
+ assert f"- Created: {stats['created_min']} through {stats['created_max']}" in card
248
+ entry = SOURCES["sejm_api_2011_2022"]
249
+ assert entry["created"] == f"{stats['created_min']}, {stats['created_max']}"
250
+ assert f"-> {stats['kept']:,} docs" in entry["provenance"]
251
+ for outcome, dropped in dedup["outcomes"].items():
252
+ assert re.search(rf"\| `{re.escape(outcome)}` \|[^|]*\| {dropped:,} \|", card), outcome
253
+ assert f"Another {dedup['kept_partial']:,} rows score 0.3-0.5 and are kept." in card
254
+ assert f"drops the {stats['drop_cross_source_dup']:,} rows contained" in card
255
+ kept_by_year = ", ".join(f"{stats['by_year'].get(str(year), 0):,}" for year in range(2011, 2020))
256
+ assert f"Kept per year, 2011-2019: {kept_by_year};" in card
257
+
258
+ decisions = [json.loads(line) for line in (DATA / clean.DECISIONS).open(encoding="utf-8")]
259
+ dropped = {d["id"] for d in decisions if d["action"] == "drop"}
260
+ with (DATA / "sejm_api_2011_2022.attribution.jsonl").open(encoding="utf-8") as stream:
261
+ parents = [line["split_from"] for line in map(json.loads, stream) if "split_from" in line]
262
+ assert (f"{len(parents):,} split rows are published, {sum(p in dropped for p in parents):,} of them "
263
+ "cut from a speech that is itself dropped as contained") in card
264
+
265
+
266
  def test_pin_check_fails_closed_and_writes_nothing(tmp_path, monkeypatch):
267
  (tmp_path / "x").write_bytes(b"x")
268
  with pytest.raises(SystemExit, match="pinned SHA-256"):
 
282
 
283
 
284
  WORDS = lambda tag, count: " ".join(f"{tag}{i}" for i in range(count)) # noqa: E731
285
+ P1, P2 = "parliamentary_201115-sjm-ppxxx-00001-01", "parliamentary_201115-sjm-zdrxx-00001-01" # plenary, committee
286
 
287
 
288
  def _write_refs(tmp_path):
289
  parliamentary, sejm_api = tmp_path / "parliamentary.parquet", tmp_path / "sejm_api.parquet"
290
+ pq.write_table(pa.table({"id": [P1, P2], "text": [WORDS("w", 40), WORDS("z", 40)]}), parliamentary)
291
  pq.write_table(pa.table({"id": ["ref_s1"], "text": [WORDS("s", 40)]}), sejm_api)
292
  return {"parliamentary": parliamentary, "sejm_api": sejm_api}
293
 
294
 
295
  def test_synthetic_containment_boundaries_and_groups(tmp_path):
296
  texts = [
297
+ WORDS("w", 20), # 0: all of it is in P1 -> 1.0
298
  WORDS("w", 8) + " " + WORDS("a", 6), # 1: 4 of 10 shingles -> 0.4, reported, kept
299
  WORDS("w", 8) + " " + WORDS("b", 4), # 2: 4 of 8 shingles -> exactly 0.5, dropped
300
  WORDS("q", 30), # 3: unrelated
301
  "w0 w1 w2 w3", # 4: under five words, no shingles
302
+ WORDS("w", 20) + " " + WORDS("s", 20), # 5: P1 holds 16 of 36, ref_s1 holds 16 of 36
303
  WORDS("s", 30), # 6: only in the sejm_api reference
304
  ]
305
  sizes, best = clean.find_contained(texts, _write_refs(tmp_path), tmp_path, workers=1)
306
  assert sizes.tolist() == [16, 10, 8, 26, 0, 36, 26]
307
+ assert best[(0, "parliamentary:sjm-plenary")] == (16, P1)
308
+ assert best[(1, "parliamentary:sjm-plenary")] == (4, P1)
309
+ assert best[(2, "parliamentary:sjm-plenary")] == (4, P1)
310
+ assert best[(5, "parliamentary:sjm-plenary")] == (16, P1)
311
  assert best[(5, "sejm_api")] == (16, "ref_s1")
312
  assert best[(6, "sejm_api")] == (26, "ref_s1")
313
  assert not {doc for doc, _ in best} & {3, 4}
 
315
  scores = clean.score_table(sizes, best, groups)
316
  assert scores[2].max() == 0.5 and scores[1].max() == 0.4
317
  assert clean.outcomes(scores, groups)["all_references"] == 3 # docs 0, 2 and 6; doc 5 holds 16/36 = 0.44 per group
318
+ assert clean.outcomes(scores, groups)["only_sejm_api"] == 1 # doc 6
319
+ assert clean.outcomes(scores, groups)["parliamentary_all"] == 2 # docs 0 and 2
320
+ assert clean.outcomes(scores, groups)["only_parliamentary_sjm-plenary"] == 2
321
 
322
 
323
  def test_search_agrees_with_brute_force_and_ties_go_to_the_smaller_id(tmp_path):
324
  from shingle_containment import shingles
325
  refs = {"parliamentary": tmp_path / "parliamentary.parquet"}
326
+ a, b, c = (f"parliamentary_201115-sjm-ppxxx-0000{n}-01" for n in (1, 2, 3))
327
+ ref_texts = {b: WORDS("w", 25), a: WORDS("w", 25), c: WORDS("w", 12) + " " + WORDS("k", 20)}
328
  pq.write_table(pa.table({"id": list(ref_texts), "text": list(ref_texts.values())}), refs["parliamentary"],
329
  row_group_size=1)
330
  texts = [WORDS("w", n) + " " + WORDS(f"n{n}_", m) for n, m in ((25, 0), (14, 6), (10, 10), (6, 12))]
 
334
  expected = {rid: len(mine & set(shingles(r).tolist())) for rid, r in ref_texts.items()}
335
  top = max(expected.values())
336
  if top >= clean.min_shared(sizes[doc:doc + 1], clean.REPORT_AT)[0]:
337
+ assert best[(doc, "parliamentary:sjm-plenary")] == (top, min(r for r, n in expected.items() if n == top))
338
  else:
339
+ assert (doc, "parliamentary:sjm-plenary") not in best
340
+
341
+
342
+ def test_groups_come_from_the_record_id():
343
+ assert clean.group_of("parliamentary", P1) == "parliamentary:sjm-plenary"
344
+ assert clean.group_of("parliamentary", P2) == "parliamentary:sjm-committee"
345
+ assert clean.group_of("parliamentary", "parliamentary_202327-snt-kśpxx-00001-01") == "parliamentary:snt-committee"
346
+ assert clean.group_of("parliamentary", "parliamentary_201115-sjm-ipxxx-00001-01") == "parliamentary:sjm-interpellation"
347
+ assert clean.group_of("parliamentary", "parliamentary_201115-sjm-zoxxx-00001-01") == "parliamentary:sjm-reply"
348
+ assert clean.group_of("parliamentary", "parliamentary_194447-krn-ppxxx-00001-01") == "parliamentary:krn-plenary"
349
+ assert clean.group_of("sejm_api", "anything") == "sejm_api"
350
+ for bad in ("ref_p1", "parliamentary_201115-xyz-ppxxx-00001-01", "parliamentary_201115-sjm-ppxxx-00001"):
351
+ with pytest.raises(ValueError, match="not a parliamentary record id"):
352
+ clean.group_of("parliamentary", bad)
353
 
354
 
355
+ def test_record_id_groups_agree_with_the_ppc_document_types():
356
+ kinds = {"Komisja": "committee", "Interpelacja": "interpellation", "Zapytanie": "interpellation",
357
+ "Odpowiedź na interpelację": "reply", "Odpowiedź na zapytanie": "reply"}
358
+ with (ROOT / "data/parliamentary/parliamentary.attribution.jsonl").open(encoding="utf-8") as stream:
359
+ lines = [json.loads(line) for line in stream]
360
+ assert lines
361
+ wrong = [line["id"] for line in lines
362
+ if clean.group_of("parliamentary", line["id"]).split("-")[-1] != kinds.get(line["type"], "plenary")]
363
+ assert wrong == []
364
 
365
 
366
  def _synthetic_release(directory, ids_texts):
 
391
  assert [json.loads(line)["id"] for line in (tmp_path / f"{clean.SOURCE}.attribution.jsonl").open()] == ["keep", "part", "tiny"]
392
  decisions = [json.loads(line) for line in (tmp_path / clean.DECISIONS).open()]
393
  assert [(d["id"], d["action"], d["containment"], d["ref_id"]) for d in decisions] == [
394
+ ("dup", "drop", 1.0, P1), ("edge", "drop", 0.5, P1), ("part", "keep_partial", 0.4, P1)]
395
  assert (stats["kept"], stats["drop_cross_source_dup"], stats["read"]) == (3, 2, 8)
396
  assert stats["chars"] == sum(len(t) for i, t in release if i in ("keep", "part", "tiny"))
397
  assert stats["cross_source_dedup"]["no_shingles"] == 1 and stats["cross_source_dedup"]["kept_partial"] == 1
 
402
  def test_trailers_are_cut_before_containment(tmp_path, monkeypatch):
403
  (tmp_path / "refs").mkdir()
404
  refs = _write_refs(tmp_path / "refs")
405
+ statement = WORDS("w", 40) + " " + WORDS("x", 20) # 219 characters; 36 of its 56 shingles are in P1
406
  # Uncut, the row would hold those 36 among ~130 shingles (under REPORT_AT) and be kept whole.
407
  text = WORDS("q", 60) + " " + header("Jan Nowak", "Poseł Jan Nowak", "01-01-2020") + " Poseł Jan Nowak: " + statement
408
  monkeypatch.setattr(clean, "INPUT_SHA256", _synthetic_release(tmp_path, [("speech", text)]))
 
412
  assert pq.read_table(tmp_path / f"{clean.SOURCE}.parquet").to_pylist()[0]["text"] == WORDS("q", 60)
413
  assert [json.loads(line)["id"] for line in (tmp_path / f"{clean.SOURCE}.attribution.jsonl").open()] == ["speech"]
414
  decisions = [json.loads(line) for line in (tmp_path / clean.DECISIONS).open()]
415
+ assert [(d["action"], d["containment"], d["ref_id"]) for d in decisions] == [("drop", round(36 / 56, 4), P1)]
416
  assert decisions[0]["id"].startswith(f"{clean.SOURCE}_")
417
  assert (stats["kept"], stats["split_rows"], stats["drop_short"], stats["drop_cross_source_dup"]) == (1, 1, 0, 1)
418
  assert stats["trailer_cut"]["rows_cut"] == 1