Datasets:
sejm_api_2011_2022: relabel provenance, drop speeches contained in parliamentary / sejm_api (118,902 -> 32,460)
#76
by ppuzio - opened
- artifacts/source_findings.md +49 -0
- data/sejm_api_2011_2022/NOTICE.md +3 -2
- data/sejm_api_2011_2022/sejm_api_2011_2022.attribution.jsonl +2 -2
- data/sejm_api_2011_2022/sejm_api_2011_2022.decisions.jsonl +3 -0
- data/sejm_api_2011_2022/sejm_api_2011_2022.md +58 -14
- data/sejm_api_2011_2022/sejm_api_2011_2022.parquet +2 -2
- data/sejm_api_2011_2022/sejm_api_2011_2022.stats.json +80 -23
- src/clean_sejm_api_2011_2022.py +349 -0
- src/sources.py +16 -9
- src/test_sejm_api_2011_2022_contract.py +214 -7
artifacts/source_findings.md
CHANGED
|
@@ -1798,3 +1798,52 @@ tokens, the profile pair 8,653).
|
|
| 1798 |
|
| 1799 |
**Lesson:** an audit count ("3 quotes") is a lead, not a list. Reproduce it from the data before
|
| 1800 |
writing the filter, and say which drops are confirmed.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1798 |
|
| 1799 |
**Lesson:** an audit count ("3 quotes") is a lead, not a list. Reproduce it from the data before
|
| 1800 |
writing the filter, and say which drops are confirmed.
|
| 1801 |
+
|
| 1802 |
+
## sejm_api_2011_2022 — provenance relabelled, cross-source dedup (2026-10-06)
|
| 1803 |
+
|
| 1804 |
+
**Verdict** — held (`release: None`). 118,902 → 32,460 documents, 135,072,403 →
|
| 1805 |
+
30,766,807 tokens, 361,275,710 → 81,385,172 characters; parquet sha256
|
| 1806 |
+
`8fad4b4eab069fb8a652f9dc6a2e7dbc8f49d1e1b6bfae0decd2b318d160a20a`. Admission waits for
|
| 1807 |
+
the NERGAL pass (#60). Registry, card and NOTICE now say "Sejm API data via contributor
|
| 1808 |
+
snapshot" and that `source_url` is a day-level listing, not a per-speech URL.
|
| 1809 |
+
|
| 1810 |
+
**Reason** — the source overlaps `parliamentary` (0.2.0) and `sejm_api` (0.2.5).
|
| 1811 |
+
`src/clean_sejm_api_2011_2022.py` drops a speech when one document of a pinned reference
|
| 1812 |
+
Parquet holds at least half of its 5-word shingles (containment >= 0.5; exact, no
|
| 1813 |
+
MinHash). 86,442 speeches (73%) are dropped, 86,272 of them dated 2011-2019. By
|
| 1814 |
+
reference set, with the maintainer's two #54 outcomes:
|
| 1815 |
+
|
| 1816 |
+
| Reference set | Dropped |
|
| 1817 |
+
|---|---:|
|
| 1818 |
+
| `parliamentary` + `sejm_api` (this build) | 86,442 |
|
| 1819 |
+
| `parliamentary`, plenary / committee slice alone | 48,660 / 38,539 |
|
| 1820 |
+
| `sejm_api` alone (outcome A, `parliamentary` withdrawn) | 216 |
|
| 1821 |
+
| `sejm_api` + `parliamentary` without its committee slice (outcome B) | 48,833 |
|
| 1822 |
+
|
| 1823 |
+
Per-speech scores are in `sejm_api_2011_2022.decisions.jsonl`. If #54 changes
|
| 1824 |
+
`parliamentary`, re-pin `REFERENCES` and rerun the script on the restored inputs.
|
| 1825 |
+
Hand check of 20 pairs at 0.3-0.7: 14 carry the speech's own wording in the reference
|
| 1826 |
+
(4 of 10 under 0.5, 10 of 10 from 0.5); the 6 that do not are dated 2020 or later.
|
| 1827 |
+
|
| 1828 |
+
### Not established
|
| 1829 |
+
|
| 1830 |
+
- Outcome B is the audit's `ppc_classify` heuristic, which is unvalidated: 10 of the 11
|
| 1831 |
+
committee-labelled references in the hand-check sample are plenary sittings.
|
| 1832 |
+
- Containment is against single reference documents; the union of several is not scored.
|
| 1833 |
+
- No minimum size: 1,236 drops have under 10 shingles and 1,177 have 10-19. Of the 170
|
| 1834 |
+
drops dated 2020 or later, 12 sampled at random were 9 stock phrases or stage
|
| 1835 |
+
directions, 2 report templates and 1 real reuse, so about 100 may be false drops.
|
| 1836 |
+
65 of the 170 have 50 or more shingles; two were read (reuse of earlier text), the
|
| 1837 |
+
rest are unchecked. A minimum-shingles or date guard is the likely fix.
|
| 1838 |
+
- Agenda titles without a number ("Oświadczenia.") are not stripped from the snapshot
|
| 1839 |
+
headers before scoring; numbered titles end correctly in 98.7% of 14,090 checked.
|
| 1840 |
+
- Whether the snapshot matches the live API (20-row spot check) and whether the
|
| 1841 |
+
www.sejm.gov.pl terms reach API output; the API documents no licence.
|
| 1842 |
+
- `src/fetch_sejm_api_2011_2022.py` is unchanged because the ontology manifest pins its
|
| 1843 |
+
hash; rebuilding with it brings back the old wording and the 118,902 rows.
|
| 1844 |
+
|
| 1845 |
+
References: polish-dynaword-v2 #57, #54, #60; `rights_audit_2026-10/REVIEW.html`
|
| 1846 |
+
`#sejm_api_2011_2022`.
|
| 1847 |
+
|
| 1848 |
+
**Lesson** — "contained in a released source" needs a size floor and a date check: a
|
| 1849 |
+
containment score of one stock sentence says nothing about reuse.
|
data/sejm_api_2011_2022/NOTICE.md
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
# Source attribution
|
| 2 |
|
| 3 |
-
Official materials: Kancelaria Sejmu RP, API Sejmu - https://api.sejm.gov.pl/
|
|
|
|
| 4 |
|
| 5 |
-
Speech attribution
|
|
|
|
| 1 |
# Source attribution
|
| 2 |
|
| 3 |
+
Official materials: Kancelaria Sejmu RP, API Sejmu - https://api.sejm.gov.pl/,
|
| 4 |
+
obtained via the contributor snapshot `PiotrSty/sejm-speeches-corpus@v1.0.1`.
|
| 5 |
|
| 6 |
+
Speech attribution is preserved in `author`; the day-level source URL is in `sejm_api_2011_2022.attribution.jsonl`. Corpus preparation and contribution: Piotr Styła (PiotrSty / PiotrStyla).
|
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:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5ce9a3c14e4860ac77f9b86c88bb001547d3b75f9793d2452279c680bf4094b4
|
| 3 |
+
size 15892312
|
data/sejm_api_2011_2022/sejm_api_2011_2022.decisions.jsonl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f50d31feb07692432aca476bf2b8caa15ff4b9b39035d4fcd8ddf6676cf6e045
|
| 3 |
+
size 27242090
|
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-
|
| 15 |
- Added: 2026-08-31
|
| 16 |
- Contributor: Piotr Styła (`PiotrSty` on Hugging Face; `PiotrStyla` on GitHub)
|
| 17 |
|
|
@@ -21,18 +21,58 @@ from the already merged `sejm_api` 2023-onward artifact.
|
|
| 21 |
- Pinned source commit: `124557799608ce4212cf22fa90ca7904618de1b6`
|
| 22 |
- Pinned DynaWord base: `a9d134ac79a9fe586fc9c11cb39eb32d69dcd21f`
|
| 23 |
- Rebuild: `python src/fetch_sejm_api_2011_2022.py --help`
|
| 24 |
-
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
## Existing-source overlap
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
## Statistics
|
| 38 |
|
|
@@ -42,10 +82,11 @@ currently missing years. Exact duplicates within this contribution are removed.
|
|
| 42 |
| Rows after 2022-12-31 excluded | 38,812 |
|
| 43 |
| Rows before 2011-01-01 excluded | 0 |
|
| 44 |
| Exact duplicate texts removed | 0 |
|
| 45 |
-
|
|
| 46 |
-
|
|
| 47 |
-
|
|
| 48 |
-
|
|
|
|
|
| 49 |
|
| 50 |
The canonical schema is `id, text, source, added, created, token_count, license, author`.
|
| 51 |
|
|
@@ -74,6 +115,9 @@ Which cleaning ran, in order:
|
|
| 74 |
release's QA covers the corpus; the review ask is answered precisely: min
|
| 75 |
length + author + exact dedup + date window are the only gates here). **No
|
| 76 |
further text rewriting** happens in this build — the projection maps fields.
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
Before/after at the text level is therefore a deliberate no-op (the pinned
|
| 79 |
release preserves post-normalization text and a documented protocol; the raw
|
|
|
|
| 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 |
|
|
|
|
| 21 |
- Pinned source commit: `124557799608ce4212cf22fa90ca7904618de1b6`
|
| 22 |
- Pinned DynaWord base: `a9d134ac79a9fe586fc9c11cb39eb32d69dcd21f`
|
| 23 |
- Rebuild: `python src/fetch_sejm_api_2011_2022.py --help`
|
| 24 |
+
- Data route: Sejm API data via contributor snapshot. The text comes from the
|
| 25 |
+
Hugging Face dataset `PiotrSty/sejm-speeches-corpus@v1.0.1`, not from the live
|
| 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 |
|
| 35 |
+
The rights audit (slayerlabs/polish-dynaword-v2#57) found that this source
|
| 36 |
+
re-publishes text already in `parliamentary` (released in 0.2.0). A speech is now
|
| 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.
|
| 64 |
+
The slice split is the audit's heuristic classifier (`ppc_classify.py`, unvalidated):
|
| 65 |
+
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 |
|
|
|
|
| 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 |
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
|
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:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8fad4b4eab069fb8a652f9dc6a2e7dbc8f49d1e1b6bfae0decd2b318d160a20a
|
| 3 |
+
size 29096259
|
data/sejm_api_2011_2022/sejm_api_2011_2022.stats.json
CHANGED
|
@@ -1,43 +1,100 @@
|
|
| 1 |
{
|
| 2 |
"added": "2026-08-31",
|
| 3 |
-
"authors_with_value":
|
| 4 |
"by_source_split": {
|
| 5 |
-
"train":
|
| 6 |
-
"validation":
|
| 7 |
},
|
| 8 |
"by_term": {
|
| 9 |
-
"7":
|
| 10 |
-
"8":
|
| 11 |
-
"9":
|
| 12 |
},
|
| 13 |
"by_year": {
|
| 14 |
-
"2011":
|
| 15 |
-
"2012":
|
| 16 |
-
"2013":
|
| 17 |
-
"2014":
|
| 18 |
-
"2015":
|
| 19 |
-
"2016":
|
| 20 |
-
"2017":
|
| 21 |
-
"2018":
|
| 22 |
-
"2019":
|
| 23 |
-
"2020":
|
| 24 |
-
"2021":
|
| 25 |
-
"2022":
|
| 26 |
},
|
| 27 |
-
"chars":
|
| 28 |
"created_max": "2022-12-14",
|
| 29 |
-
"created_min": "2011-
|
| 30 |
"drop_after_end": 38812,
|
| 31 |
"drop_before_start": 0,
|
| 32 |
"drop_dup": 0,
|
| 33 |
-
"kept":
|
| 34 |
"license": "public-domain (official documents)",
|
| 35 |
"licenses": {
|
| 36 |
-
"public-domain (official documents)":
|
| 37 |
},
|
| 38 |
"read": 157714,
|
| 39 |
"source_revision": "124557799608ce4212cf22fa90ca7904618de1b6",
|
| 40 |
"stats_recomputed_from_parquet": true,
|
| 41 |
"target_base_revision": "a9d134ac79a9fe586fc9c11cb39eb32d69dcd21f",
|
| 42 |
-
"tokens":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
}
|
|
|
|
| 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,
|
| 47 |
+
"shingle_words": 5,
|
| 48 |
+
"input_sha256": {
|
| 49 |
+
"sejm_api_2011_2022.parquet": "606d49ab55180341bffe5270e9c88797a95ff9f8441bf2de095d36f9d7a756c1",
|
| 50 |
+
"sejm_api_2011_2022.attribution.jsonl": "a1c1a309075b2fbc2a42f5313e22e93584434f4260e61d6e92d6cc488b0d9be5",
|
| 51 |
+
"sejm_api_2011_2022.stats.json": "398dbaff87ec8f1d8702fce347db65ae8a3e4cf69a90594a6c7998cc4441c356"
|
| 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 |
}
|
src/clean_sejm_api_2011_2022.py
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 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
|
| 17 |
+
committee slice), re-pin REFERENCES and rerun this script on the restored input; nothing here
|
| 18 |
+
follows the registry silently.
|
| 19 |
+
|
| 20 |
+
Exact search: the speeches are indexed, the references are streamed. A speech is found when a
|
| 21 |
+
reference shares at least one of its rarest (1 - REPORT_AT) * n + 1 shingles (prefix filter,
|
| 22 |
+
exact by pigeonhole), and every such candidate is then scored on its full shingle sets. No
|
| 23 |
+
MinHash/LSH, so there is no sampling error. Speeches scoring from REPORT_AT up are written to
|
| 24 |
+
sejm_api_2011_2022.decisions.jsonl with the best score against each reference group, so the
|
| 25 |
+
effect of each #54 outcome can be read without rerunning. Speeches under five words have no
|
| 26 |
+
shingles and are never dropped.
|
| 27 |
+
|
| 28 |
+
The inputs are the pre-dedup release files, pinned by SHA-256. Restore them before a rerun:
|
| 29 |
+
git checkout 3bab9f9 -- data/sejm_api_2011_2022/sejm_api_2011_2022.{parquet,attribution.jsonl,stats.json}
|
| 30 |
+
python3 src/clean_sejm_api_2011_2022.py
|
| 31 |
+
"""
|
| 32 |
+
from __future__ import annotations
|
| 33 |
+
|
| 34 |
+
import argparse
|
| 35 |
+
import hashlib
|
| 36 |
+
import json
|
| 37 |
+
import multiprocessing
|
| 38 |
+
import os
|
| 39 |
+
import re
|
| 40 |
+
import tempfile
|
| 41 |
+
from collections import Counter
|
| 42 |
+
from concurrent.futures import ProcessPoolExecutor
|
| 43 |
+
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 |
+
|
| 53 |
+
SOURCE = "sejm_api_2011_2022"
|
| 54 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 55 |
+
DATA = ROOT / "data" / SOURCE
|
| 56 |
+
# Pre-dedup release files (main at 3bab9f9); the ontology manifest records the same three.
|
| 57 |
+
INPUT_SHA256 = {
|
| 58 |
+
f"{SOURCE}.parquet": "606d49ab55180341bffe5270e9c88797a95ff9f8441bf2de095d36f9d7a756c1",
|
| 59 |
+
f"{SOURCE}.attribution.jsonl": "a1c1a309075b2fbc2a42f5313e22e93584434f4260e61d6e92d6cc488b0d9be5",
|
| 60 |
+
f"{SOURCE}.stats.json": "398dbaff87ec8f1d8702fce347db65ae8a3e4cf69a90594a6c7998cc4441c356",
|
| 61 |
+
}
|
| 62 |
+
# Reference source -> (Parquet, SHA-256). Only sources with a registry release (checked in build()).
|
| 63 |
+
# `parlamint_pl` left the registry in Hub PR 54 and never had data, so it cannot be pinned.
|
| 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
|
| 72 |
+
REPORT_AT = 0.3
|
| 73 |
+
ROW_GROUP_SIZE = 1024 # the layout of the released file
|
| 74 |
+
SIZE_BUCKETS = (("<10", 0, 10), ("10-19", 10, 20), ("20-49", 20, 50), ("50-199", 50, 200), (">=200", 200, 10**9))
|
| 75 |
+
|
| 76 |
+
_R = lambda pattern: re.compile(pattern, re.I) # noqa: E731
|
| 77 |
+
# The audit's heuristic split of `parliamentary` (artifacts/rights_audit_2026-10/official/ppc_classify.py,
|
| 78 |
+
# unvalidated, v2#54). It only labels the report; the drop decision never uses it.
|
| 79 |
+
PPC_COMMITTEE = _R(r'(Otwieram|Rozpoczynam|Witam)[^.\n]{0,160}(posiedzenie|posiedzeniu|Komisji)|posiedzenie (Komisji|Podkomisji)|^\(Początek posiedzenia|Posiedzeniu przewodniczy')
|
| 80 |
+
PPC_PLENARY = _R(r'^\((Wznowienie|Początek|Ciąg dalszy|Przerwa)[^)]*\)\s*\n?\(?(Posiedzeniu przewodnicz|Na posiedzeniu przewodnicz)|Wysoka Izbo|Wysoki Sejmie|Wysoki Senacie')
|
| 81 |
+
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)')
|
| 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):
|
| 105 |
+
return "committee"
|
| 106 |
+
if PPC_PLENARY.search(text[:4000]) and not PPC_REPLY.search(head):
|
| 107 |
+
return "plenary"
|
| 108 |
+
if PPC_REPLY.search(head):
|
| 109 |
+
return "interp_reply"
|
| 110 |
+
return "interp_question" if PPC_QUESTION.search(head) else "other"
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def group_of(source: str, text: str) -> str:
|
| 114 |
+
"""Reference group a document is reported under: `parliamentary:<slice>` or the source key."""
|
| 115 |
+
return f"parliamentary:{ppc_slice(text)}" if source == "parliamentary" else source
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def min_shared(sizes: np.ndarray, at: float) -> np.ndarray:
|
| 119 |
+
"""Fewest shared shingles that reach containment `at` (the epsilon guards 0.3 * 10 = 3.0000000000000004)."""
|
| 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
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _load_index(work: str) -> None:
|
| 135 |
+
_INDEX.update({name: np.load(Path(work) / f"{name}.npy", mmap_mode="r")
|
| 136 |
+
for name in ("prefix_hash", "prefix_doc", "flat", "offsets", "need")})
|
| 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]:
|
| 144 |
+
"""Sorted (hash, doc) pairs of each speech's rarest n - need + 1 shingles.
|
| 145 |
+
|
| 146 |
+
A reference sharing >= `need` of a speech's n shingles misses at most need - 1 of them, so it
|
| 147 |
+
must hold one of the n - need + 1 chosen; rarity (the count among speeches) only keeps the
|
| 148 |
+
posting lists short.
|
| 149 |
+
"""
|
| 150 |
+
unique, counts = np.unique(flat, return_counts=True)
|
| 151 |
+
rarity = counts[np.searchsorted(unique, flat)]
|
| 152 |
+
hashes, docs = [], []
|
| 153 |
+
for doc in range(len(offsets) - 1):
|
| 154 |
+
lo, hi = offsets[doc], offsets[doc + 1]
|
| 155 |
+
if lo == hi:
|
| 156 |
+
continue
|
| 157 |
+
chosen = np.lexsort((flat[lo:hi], rarity[lo:hi]))[: hi - lo - need[doc] + 1]
|
| 158 |
+
hashes.append(flat[lo:hi][chosen])
|
| 159 |
+
docs.append(np.full(len(chosen), doc, np.int32))
|
| 160 |
+
hashes, docs = np.concatenate(hashes), np.concatenate(docs)
|
| 161 |
+
order = np.argsort(hashes, kind="stable")
|
| 162 |
+
return hashes[order], docs[order]
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def _keep_best(best: dict, key: tuple[int, str], shared: int, ref_id: str) -> None:
|
| 166 |
+
"""Most shared shingles wins; a tie goes to the smaller reference id, so the result is order-independent."""
|
| 167 |
+
if key not in best or shared > best[key][0] or (shared == best[key][0] and ref_id < best[key][1]):
|
| 168 |
+
best[key] = (shared, ref_id)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def _scan_row_group(task: tuple[str, str, int]) -> dict[tuple[int, str], tuple[int, str]]:
|
| 172 |
+
"""Best (shared shingles, reference id) per (speech, group) over one row group of a reference."""
|
| 173 |
+
path, source, row_group = task
|
| 174 |
+
table = pq.ParquetFile(path).read_row_group(row_group, columns=["id", "text"])
|
| 175 |
+
prefix_hash, prefix_doc = _INDEX["prefix_hash"], _INDEX["prefix_doc"]
|
| 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())
|
| 183 |
+
if not hits:
|
| 184 |
+
continue
|
| 185 |
+
group = group_of(source, text)
|
| 186 |
+
for doc in np.unique(prefix_doc[np.repeat(lo - np.cumsum(lens) + lens, lens) + np.arange(hits)]):
|
| 187 |
+
speech = flat[offsets[doc]:offsets[doc + 1]]
|
| 188 |
+
at = np.minimum(np.searchsorted(ref, speech), len(ref) - 1)
|
| 189 |
+
shared = int((ref[at] == speech).sum())
|
| 190 |
+
if shared >= need[doc]:
|
| 191 |
+
_keep_best(best, (int(doc), group), shared, ref_id)
|
| 192 |
+
return best
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def _map(fn, tasks: list, workers: int, work: str) -> list:
|
| 196 |
+
if workers == 1:
|
| 197 |
+
_load_index(work) if work else None
|
| 198 |
+
return [fn(task) for task in tasks]
|
| 199 |
+
context = multiprocessing.get_context("spawn")
|
| 200 |
+
with ProcessPoolExecutor(workers, mp_context=context, initializer=_load_index if work else None,
|
| 201 |
+
initargs=(work,) if work else ()) as pool:
|
| 202 |
+
return list(pool.map(fn, tasks))
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def find_contained(texts: list[str], references: dict[str, Path], work: Path, workers: int,
|
| 206 |
+
at: float = REPORT_AT) -> tuple[np.ndarray, dict[tuple[int, str], tuple[int, str]]]:
|
| 207 |
+
"""Shingle-set sizes of `texts`, and for every (text, reference group) pair scoring >= `at`
|
| 208 |
+
the best (shared shingles, reference id). `references` maps a source key to its Parquet."""
|
| 209 |
+
chunks = [texts[i:i + 2048] for i in range(0, len(texts), 2048)]
|
| 210 |
+
sets = [s for chunk in _map(_shingle_chunk, chunks, workers, "") for s in chunk]
|
| 211 |
+
sizes = np.array([len(s) for s in sets], np.int64)
|
| 212 |
+
offsets = np.concatenate([[0], np.cumsum(sizes)]).astype(np.int64)
|
| 213 |
+
flat = np.concatenate(sets) if sets else np.empty(0, np.uint64)
|
| 214 |
+
need = min_shared(sizes, at)
|
| 215 |
+
prefix_hash, prefix_doc = prefix_index(offsets, flat, need)
|
| 216 |
+
for name, array in (("prefix_hash", prefix_hash), ("prefix_doc", prefix_doc), ("flat", flat),
|
| 217 |
+
("offsets", offsets), ("need", need)):
|
| 218 |
+
np.save(work / f"{name}.npy", array)
|
| 219 |
+
del sets, flat, prefix_hash, prefix_doc
|
| 220 |
+
tasks = [(str(path), source, row_group) for source, path in references.items()
|
| 221 |
+
for row_group in range(pq.ParquetFile(path).num_row_groups)]
|
| 222 |
+
merged: dict[tuple[int, str], tuple[int, str]] = {}
|
| 223 |
+
for part in _map(_scan_row_group, tasks, workers, str(work)):
|
| 224 |
+
for key, (shared, ref_id) in part.items():
|
| 225 |
+
_keep_best(merged, key, shared, ref_id)
|
| 226 |
+
return sizes, merged
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
# --- build ---------------------------------------------------------------------------------------
|
| 230 |
+
|
| 231 |
+
def score_table(sizes: np.ndarray, best: dict[tuple[int, str], tuple[int, str]], groups: list[str]) -> np.ndarray:
|
| 232 |
+
"""(speeches x groups) containment matrix; 0 where a group scored below REPORT_AT."""
|
| 233 |
+
scores = np.zeros((len(sizes), len(groups)))
|
| 234 |
+
for (doc, group), (shared, _) in best.items():
|
| 235 |
+
scores[doc, groups.index(group)] = shared / sizes[doc]
|
| 236 |
+
return scores
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def outcomes(scores: np.ndarray, groups: list[str]) -> dict[str, int]:
|
| 240 |
+
"""Speeches dropped (best score >= DROP_AT) for each reference set the maintainers may end up with."""
|
| 241 |
+
def dropped(wanted):
|
| 242 |
+
cols = [i for i, g in enumerate(groups) if wanted(g)]
|
| 243 |
+
return int((scores[:, cols].max(axis=1) >= DROP_AT).sum()) if cols else 0
|
| 244 |
+
return {
|
| 245 |
+
"all_references": dropped(lambda g: True),
|
| 246 |
+
"sejm_api_only": dropped(lambda g: g == "sejm_api"),
|
| 247 |
+
"parliamentary_all": dropped(lambda g: g.startswith("parliamentary:")),
|
| 248 |
+
"parliamentary_without_committee_plus_sejm_api": dropped(lambda g: g != "parliamentary:committee"),
|
| 249 |
+
**{f"only_{g.replace(':', '_')}": dropped(lambda x, g=g: x == g) for g in groups},
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def build(input_dir: Path, references: dict[str, tuple[Path, str]], out_dir: Path, workers: int,
|
| 254 |
+
check_registry: bool = True) -> dict:
|
| 255 |
+
for name, sha in INPUT_SHA256.items():
|
| 256 |
+
check_pin(input_dir / name, sha, f"restore it with `git checkout 3bab9f9 -- data/{SOURCE}/{name}`")
|
| 257 |
+
for source, (path, sha) in references.items():
|
| 258 |
+
check_pin(path, sha, f"it is not the pinned {source} Parquet; re-pin REFERENCES (see the docstring)")
|
| 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 |
+
|
| 340 |
+
def main() -> None:
|
| 341 |
+
parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
| 342 |
+
parser.add_argument("--data", type=Path, default=DATA, help="directory holding the (restored) input files; outputs are written there")
|
| 343 |
+
parser.add_argument("--workers", type=int, default=os.cpu_count() or 1)
|
| 344 |
+
args = parser.parse_args()
|
| 345 |
+
print(json.dumps(build(args.data, REFERENCES, args.data, args.workers), indent=2, ensure_ascii=False))
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
if __name__ == "__main__":
|
| 349 |
+
main()
|
src/sources.py
CHANGED
|
@@ -241,17 +241,24 @@ SOURCES = {
|
|
| 241 |
"license_spdx": "LicenseRef-Polish-Official-Documents",
|
| 242 |
"traceable": "Official parliamentary materials excluded from copyright under "
|
| 243 |
"Polish Copyright Act art. 4(2); reusable under the Polish Open Data "
|
| 244 |
-
"Act arts. 2(12), 5, 6, 14(1), 15, 17.
|
| 245 |
-
"
|
| 246 |
"upstream": "https://api.sejm.gov.pl/",
|
| 247 |
-
"provenance": "
|
| 248 |
-
"
|
| 249 |
-
"
|
| 250 |
-
"
|
| 251 |
-
"
|
| 252 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
"domain": "political/spoken",
|
| 254 |
-
"created": "2011-
|
| 255 |
"is_ocr": False,
|
| 256 |
"custom_datasheet": True,
|
| 257 |
},
|
|
|
|
| 241 |
"license_spdx": "LicenseRef-Polish-Official-Documents",
|
| 242 |
"traceable": "Official parliamentary materials excluded from copyright under "
|
| 243 |
"Polish Copyright Act art. 4(2); reusable under the Polish Open Data "
|
| 244 |
+
"Act arts. 2(12), 5, 6, 14(1), 15, 17. Every row has a day-level api.sejm.gov.pl "
|
| 245 |
+
"/videos/ listing URL (not a per-speech URL) in the attribution sidecar.",
|
| 246 |
"upstream": "https://api.sejm.gov.pl/",
|
| 247 |
+
"provenance": "Sejm API data via contributor snapshot: text from the "
|
| 248 |
+
"PiotrSty/sejm-speeches-corpus@1245577 Hugging Face release, not fetched "
|
| 249 |
+
"from the live API by SlayerLab (upstream protocol: heuristic PII "
|
| 250 |
+
"redaction of e-mail/PESEL/phone, <50-word filter, exact dedup). Speaker "
|
| 251 |
+
"attribution preserved; source_url is a day-level api.sejm.gov.pl "
|
| 252 |
+
"/videos/ listing, not a per-speech URL. This build applies the date "
|
| 253 |
+
"window 2011-01-01..2022-12-31, >=200 chars + author, exact dedup, then "
|
| 254 |
+
"src/clean_sejm_api_2011_2022.py drops speeches whose 5-shingle "
|
| 255 |
+
"containment in one document of the pinned parliamentary / sejm_api "
|
| 256 |
+
"Parquets is >= 0.5 (118,902 -> 32,460 docs; re-pin and rerun if "
|
| 257 |
+
"polish-dynaword-v2#54 changes parliamentary). NERGAL not run - re-run "
|
| 258 |
+
"through SlayerLab/NERGAL before release. Shared helpers factored into "
|
| 259 |
+
"src/sejm_api_common.py.",
|
| 260 |
"domain": "political/spoken",
|
| 261 |
+
"created": "2011-12-14, 2022-12-14",
|
| 262 |
"is_ocr": False,
|
| 263 |
"custom_datasheet": True,
|
| 264 |
},
|
src/test_sejm_api_2011_2022_contract.py
CHANGED
|
@@ -4,13 +4,21 @@ import hashlib
|
|
| 4 |
import json
|
| 5 |
import pathlib
|
| 6 |
import re
|
|
|
|
| 7 |
|
|
|
|
| 8 |
import pyarrow.parquet as pq
|
|
|
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
| 12 |
DATA = ROOT / "data" / "sejm_api_2011_2022"
|
| 13 |
MANIFEST = ROOT / "artifacts" / "sejm_api_2011_2022_ontology_manifest.json"
|
|
|
|
| 14 |
|
| 15 |
|
| 16 |
def sha256_file(path):
|
|
@@ -129,10 +137,209 @@ def test_manifest_artifact_checksums():
|
|
| 129 |
item["payload"] for item in manifest["evidence"]
|
| 130 |
if item["observation_type"] == "artifact_checksums"
|
| 131 |
)
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
assert
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
import json
|
| 5 |
import pathlib
|
| 6 |
import re
|
| 7 |
+
import sys
|
| 8 |
|
| 9 |
+
import pyarrow as pa
|
| 10 |
import pyarrow.parquet as pq
|
| 11 |
+
import pytest
|
| 12 |
|
| 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"
|
| 20 |
MANIFEST = ROOT / "artifacts" / "sejm_api_2011_2022_ontology_manifest.json"
|
| 21 |
+
DAY_LEVEL_URL = re.compile(r"https://api\.sejm\.gov\.pl/sejm/term\d+/videos/\d{4}-\d{2}-\d{2}")
|
| 22 |
|
| 23 |
|
| 24 |
def sha256_file(path):
|
|
|
|
| 137 |
item["payload"] for item in manifest["evidence"]
|
| 138 |
if item["observation_type"] == "artifact_checksums"
|
| 139 |
)
|
| 140 |
+
# The manifest describes the pre-dedup build that src/fetch_sejm_api_2011_2022.py wrote; the
|
| 141 |
+
# shipped files are those three after src/clean_sejm_api_2011_2022.py, which pins them.
|
| 142 |
+
pinned = clean.INPUT_SHA256
|
| 143 |
+
assert checksums["parquet_sha256"] == pinned["sejm_api_2011_2022.parquet"]
|
| 144 |
+
assert checksums["attribution_sha256"] == pinned["sejm_api_2011_2022.attribution.jsonl"]
|
| 145 |
+
assert checksums["stats_sha256"] == pinned["sejm_api_2011_2022.stats.json"]
|
| 146 |
+
assert checksums["legal_evidence_sha256"] == sha256_file(DATA / "sejm_api_2011_2022.license-evidence.json")
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
# --- wording (v2#57) ---------------------------------------------------------------------------
|
| 150 |
+
|
| 151 |
+
def test_registry_and_card_state_the_contributor_snapshot():
|
| 152 |
+
card = (DATA / "sejm_api_2011_2022.md").read_text(encoding="utf-8")
|
| 153 |
+
entry = SOURCES["sejm_api_2011_2022"]
|
| 154 |
+
for text in (entry["provenance"], entry["traceable"], card):
|
| 155 |
+
assert "speech-level" not in text
|
| 156 |
+
assert "Direct official" not in text
|
| 157 |
+
for text in (entry["provenance"], card):
|
| 158 |
+
assert "contributor snapshot" in text
|
| 159 |
+
assert "day-level" in text
|
| 160 |
+
assert entry["release"] is None # admission waits for the NERGAL pass (v2#60)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def test_every_source_url_is_a_day_level_listing():
|
| 164 |
+
with (DATA / "sejm_api_2011_2022.attribution.jsonl").open(encoding="utf-8") as stream:
|
| 165 |
+
urls = [json.loads(line)["source_url"] for line in stream]
|
| 166 |
+
assert urls
|
| 167 |
+
assert [url for url in urls if not DAY_LEVEL_URL.fullmatch(url)] == []
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
# --- cross-source dedup (v2#57) ------------------------------------------------------------------
|
| 171 |
+
|
| 172 |
+
def test_reference_pins_match_the_files_and_the_registry():
|
| 173 |
+
assert set(clean.REFERENCES) == {"parliamentary", "sejm_api"}
|
| 174 |
+
for source, (path, sha) in clean.REFERENCES.items():
|
| 175 |
+
clean.check_pin(path, sha, "")
|
| 176 |
+
assert SOURCES[source]["release"] is not None, f"{source} is not released, so it is not a reference"
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def test_shipped_files_follow_from_the_pinned_inputs():
|
| 180 |
+
stats = json.loads((DATA / "sejm_api_2011_2022.stats.json").read_text(encoding="utf-8"))
|
| 181 |
+
dedup = stats["cross_source_dedup"]
|
| 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"]
|
| 189 |
+
assert dedup["outcomes"]["all_references"] == stats["drop_cross_source_dup"]
|
| 190 |
+
|
| 191 |
+
table = pq.read_table(DATA / "sejm_api_2011_2022.parquet", columns=["id"])
|
| 192 |
+
kept_ids = set(table.column("id").to_pylist())
|
| 193 |
+
assert len(kept_ids) == stats["kept"]
|
| 194 |
+
decisions = [json.loads(line) for line in (DATA / clean.DECISIONS).open(encoding="utf-8")]
|
| 195 |
+
dropped = {d["id"] for d in decisions if d["action"] == "drop"}
|
| 196 |
+
partial = {d["id"] for d in decisions if d["action"] == "keep_partial"}
|
| 197 |
+
assert len(dropped) == stats["drop_cross_source_dup"] and not dropped & kept_ids
|
| 198 |
+
assert partial <= kept_ids and len(partial) == dedup["kept_partial"]
|
| 199 |
+
assert all(d["containment"] >= clean.DROP_AT for d in decisions if d["action"] == "drop")
|
| 200 |
+
assert all(clean.REPORT_AT <= d["containment"] < clean.DROP_AT for d in decisions if d["action"] == "keep_partial")
|
| 201 |
+
with (DATA / "sejm_api_2011_2022.attribution.jsonl").open(encoding="utf-8") as stream:
|
| 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"):
|
| 208 |
+
clean.check_pin(tmp_path / "x", "0" * 64, "restore it")
|
| 209 |
+
for name in clean.INPUT_SHA256: # inputs that are not the pinned release files
|
| 210 |
+
(tmp_path / name).write_bytes(b"not the release")
|
| 211 |
+
before = sorted(p.name for p in tmp_path.iterdir())
|
| 212 |
+
with pytest.raises(SystemExit, match="pinned SHA-256"):
|
| 213 |
+
clean.build(tmp_path, clean.REFERENCES, tmp_path, workers=1)
|
| 214 |
+
assert sorted(p.name for p in tmp_path.iterdir()) == before
|
| 215 |
+
|
| 216 |
+
# a reference that is not the pinned file stops the build as well, before any search
|
| 217 |
+
(tmp_path / "p").write_bytes(b"a")
|
| 218 |
+
monkeypatch.setattr(clean, "INPUT_SHA256", {name: hashlib.sha256(b"not the release").hexdigest() for name in clean.INPUT_SHA256})
|
| 219 |
+
with pytest.raises(SystemExit, match="not the pinned parliamentary"):
|
| 220 |
+
clean.build(tmp_path, {"parliamentary": (tmp_path / "p", "0" * 64)}, tmp_path, workers=1)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
WORDS = lambda tag, count: " ".join(f"{tag}{i}" for i in range(count)) # noqa: E731
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def _write_refs(tmp_path):
|
| 227 |
+
parliamentary, sejm_api = tmp_path / "parliamentary.parquet", tmp_path / "sejm_api.parquet"
|
| 228 |
+
pq.write_table(pa.table({"id": ["ref_p1", "ref_p2"], "text": [WORDS("w", 40), WORDS("z", 40)]}), parliamentary)
|
| 229 |
+
pq.write_table(pa.table({"id": ["ref_s1"], "text": [WORDS("s", 40)]}), sejm_api)
|
| 230 |
+
return {"parliamentary": parliamentary, "sejm_api": sejm_api}
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def test_synthetic_containment_boundaries_and_groups(tmp_path):
|
| 234 |
+
texts = [
|
| 235 |
+
WORDS("w", 20), # 0: all of it is in ref_p1 -> 1.0
|
| 236 |
+
WORDS("w", 8) + " " + WORDS("a", 6), # 1: 4 of 10 shingles -> 0.4, reported, kept
|
| 237 |
+
WORDS("w", 8) + " " + WORDS("b", 4), # 2: 4 of 8 shingles -> exactly 0.5, dropped
|
| 238 |
+
WORDS("q", 30), # 3: unrelated
|
| 239 |
+
"w0 w1 w2 w3", # 4: under five words, no shingles
|
| 240 |
+
WORDS("w", 20) + " " + WORDS("s", 20), # 5: ref_p1 holds 16 of 36, ref_s1 holds 16 of 36
|
| 241 |
+
WORDS("s", 30), # 6: only in the sejm_api reference
|
| 242 |
+
]
|
| 243 |
+
sizes, best = clean.find_contained(texts, _write_refs(tmp_path), tmp_path, workers=1)
|
| 244 |
+
assert sizes.tolist() == [16, 10, 8, 26, 0, 36, 26]
|
| 245 |
+
assert best[(0, "parliamentary:other")] == (16, "ref_p1")
|
| 246 |
+
assert best[(1, "parliamentary:other")] == (4, "ref_p1")
|
| 247 |
+
assert best[(2, "parliamentary:other")] == (4, "ref_p1")
|
| 248 |
+
assert best[(5, "parliamentary:other")] == (16, "ref_p1")
|
| 249 |
+
assert best[(5, "sejm_api")] == (16, "ref_s1")
|
| 250 |
+
assert best[(6, "sejm_api")] == (26, "ref_s1")
|
| 251 |
+
assert not {doc for doc, _ in best} & {3, 4}
|
| 252 |
+
groups = sorted({group for _, group in best})
|
| 253 |
+
scores = clean.score_table(sizes, best, groups)
|
| 254 |
+
assert scores[2].max() == 0.5 and scores[1].max() == 0.4
|
| 255 |
+
assert clean.outcomes(scores, groups)["all_references"] == 3 # docs 0, 2 and 6; doc 5 holds 16/36 = 0.44 per group
|
| 256 |
+
assert clean.outcomes(scores, groups)["sejm_api_only"] == 1 # doc 6
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def test_search_agrees_with_brute_force_and_ties_go_to_the_smaller_id(tmp_path):
|
| 260 |
+
from shingle_containment import shingles
|
| 261 |
+
refs = {"parliamentary": tmp_path / "parliamentary.parquet"}
|
| 262 |
+
ref_texts = {"ref_b": WORDS("w", 25), "ref_a": WORDS("w", 25), "ref_c": WORDS("w", 12) + " " + WORDS("k", 20)}
|
| 263 |
+
pq.write_table(pa.table({"id": list(ref_texts), "text": list(ref_texts.values())}), refs["parliamentary"],
|
| 264 |
+
row_group_size=1)
|
| 265 |
+
texts = [WORDS("w", n) + " " + WORDS(f"n{n}_", m) for n, m in ((25, 0), (14, 6), (10, 10), (6, 12))]
|
| 266 |
+
sizes, best = clean.find_contained(texts, refs, tmp_path, workers=1)
|
| 267 |
+
for doc, text in enumerate(texts):
|
| 268 |
+
mine = set(shingles(text).tolist())
|
| 269 |
+
expected = {rid: len(mine & set(shingles(r).tolist())) for rid, r in ref_texts.items()}
|
| 270 |
+
top = max(expected.values())
|
| 271 |
+
if top >= clean.min_shared(sizes[doc:doc + 1], clean.REPORT_AT)[0]:
|
| 272 |
+
assert best[(doc, "parliamentary:other")] == (top, min(r for r, n in expected.items() if n == top))
|
| 273 |
+
else:
|
| 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"
|
| 295 |
+
assert clean.ppc_slice("Otwieram posiedzenie Komisji Kultury") == "committee"
|
| 296 |
+
assert clean.ppc_slice("W odpowiedzi na interpelację nr 5") == "interp_reply"
|
| 297 |
+
assert clean.ppc_slice("Szanowny Panie Ministrze, zwracam się") == "interp_question"
|
| 298 |
+
assert clean.ppc_slice(WORDS("w", 10)) == "other"
|
| 299 |
+
assert clean.group_of("parliamentary", WORDS("w", 10)) == "parliamentary:other"
|
| 300 |
+
assert clean.group_of("sejm_api", "Otwieram posiedzenie Komisji") == "sejm_api"
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def _synthetic_release(directory, ids_texts):
|
| 304 |
+
"""Pre-dedup release files for the given (id, text) pairs, and the SHA-256 pins that describe them."""
|
| 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 |
+
|
| 317 |
+
|
| 318 |
+
def test_synthetic_build_filters_every_output_consistently(tmp_path, monkeypatch):
|
| 319 |
+
(tmp_path / "refs").mkdir()
|
| 320 |
+
refs = _write_refs(tmp_path / "refs")
|
| 321 |
+
release = [("keep", WORDS("q", 30)), ("dup", WORDS("w", 20)), ("edge", WORDS("w", 8) + " " + WORDS("b", 4)),
|
| 322 |
+
("part", WORDS("w", 8) + " " + WORDS("a", 6)), ("tiny", "w0 w1")]
|
| 323 |
+
monkeypatch.setattr(clean, "INPUT_SHA256", _synthetic_release(tmp_path, release))
|
| 324 |
+
references = {s: (p, hashlib.sha256(p.read_bytes()).hexdigest()) for s, p in refs.items()}
|
| 325 |
+
stats = clean.build(tmp_path, references, tmp_path, workers=1, check_registry=False)
|
| 326 |
+
|
| 327 |
+
assert pq.read_table(tmp_path / f"{clean.SOURCE}.parquet").column("id").to_pylist() == ["keep", "part", "tiny"]
|
| 328 |
+
assert [json.loads(line)["id"] for line in (tmp_path / f"{clean.SOURCE}.attribution.jsonl").open()] == ["keep", "part", "tiny"]
|
| 329 |
+
decisions = [json.loads(line) for line in (tmp_path / clean.DECISIONS).open()]
|
| 330 |
+
assert [(d["id"], d["action"], d["containment"], d["ref_id"]) for d in decisions] == [
|
| 331 |
+
("dup", "drop", 1.0, "ref_p1"), ("edge", "drop", 0.5, "ref_p1"), ("part", "keep_partial", 0.4, "ref_p1")]
|
| 332 |
+
assert (stats["kept"], stats["drop_cross_source_dup"], stats["read"]) == (3, 2, 8)
|
| 333 |
+
assert stats["chars"] == sum(len(t) for i, t in release if i in ("keep", "part", "tiny"))
|
| 334 |
+
assert stats["cross_source_dedup"]["no_shingles"] == 1 and stats["cross_source_dedup"]["kept_partial"] == 1
|
| 335 |
+
assert stats["cross_source_dedup"]["outcomes"]["all_references"] == 2
|
| 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")
|
| 342 |
+
monkeypatch.setattr(clean, "INPUT_SHA256", _synthetic_release(tmp_path, [("a", WORDS("q", 30))]))
|
| 343 |
+
references = {"sejm_api_2011_2022": (refs["sejm_api"], hashlib.sha256(refs["sejm_api"].read_bytes()).hexdigest())}
|
| 344 |
+
with pytest.raises(SystemExit, match="no release"):
|
| 345 |
+
clean.build(tmp_path, references, tmp_path, workers=1)
|