sejm_api: cut the "Przebieg posiedzenia" trailers, split appended statements (amends #69, v2#57)

#83
by ppuzio - opened
artifacts/source_findings.md CHANGED
@@ -2214,3 +2214,42 @@ was assembled is not re-verified.
2214
 
2215
  **Lesson** — a label that drops the version is not a licence. 28,280 rows are CC BY and
2216
  13,705 CC BY-SA, and 13,273 of the 41,985 rows are not 4.0.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2214
 
2215
  **Lesson** — a label that drops the version is not a licence. 28,280 rows are CC BY and
2216
  13,705 CC BY-SA, and 13,273 of the 41,985 rows are not 4.0.
2217
+
2218
+ ## sejm_api — "Przebieg posiedzenia" trailers cut, appended statements split out (2026-10-06)
2219
+
2220
+ **Finding** (slayerlabs/polish-dynaword-v2#57) — the PiotrSty snapshot appends to 34,980
2221
+ of 38,812 speeches the header of a later statement of the same sitting day
2222
+ ("Przebieg posiedzenia {name}: {term}. kadencja, {n}. posiedzenie, {d}. dzień - {label}
2223
+ … ({dd-mm-yyyy})"), and after 2,466 of those headers that statement's text. The trailers
2224
+ are 23,485,670 characters (24% of the source), released in v0.2.5 (Hub PR 16).
2225
+
2226
+ **Fix** — `src/clean_sejm_api.py` (inputs pinned by SHA-256 to the pre-cut files at
2227
+ `262df1b`, unchanged since v0.2.5) cuts every trailer with `sejm_api_common.split_trailers` and emits each
2228
+ appended statement as a row of its own (`split_release_rows`): speaker = the name the
2229
+ header gives ("Przebieg posiedzenia {name}:"), date and term of the parent row,
2230
+ `split_from` = parent id, `has_events: null`. Rows under 200 characters after the cut
2231
+ (1,318 parents, 53 split rows) and 8 new exact duplicates are dropped. 38,812 → 39,899
2232
+ documents, 36,335,587 → 30,860,439 tokens. Same-speaker follow-ups (373) are kept as
2233
+ separate rows; agenda titles ("N. punkt porządku dziennego: …", "Oświadczenia.") before a
2234
+ follow-up are dropped.
2235
+
2236
+ **Author of a split row** — the first push of this PR credited split rows in the snapshot's own
2237
+ `speaker` convention, the header label minus its first word. That is right for "Poseł Jan
2238
+ Kowalski" but leaves an office fragment for officials ("Podsekretarz Stanu w Ministerstwie
2239
+ Zdrowia Janusz Cieszyński" -> "Stanu w Ministerstwie Zdrowia Janusz Cieszyński"). The header's
2240
+ name fixes 2,052 published split rows; 129 more lose a "(tekst niewygłoszony)" suffix and 12 a
2241
+ "Sprawozdawca" prefix that the snapshot keeps on its own rows. Text, counts and stats are
2242
+ unchanged; the ids of these 2,193 rows change, since the id hashes the speaker.
2243
+
2244
+ **Upstream quirk** — the snapshot labels the 11th sitting of term 10 (2024-05-08/09/15)
2245
+ "11. kadencja" in 696 headers. The split keeps the parent's term; a trailer dated on
2246
+ another day than its parent fails closed (none occur).
2247
+
2248
+ **Also fixed** — `fetch_sejm_api.py` read the registry end date as the latest date in
2249
+ the entry, which picked up `added` (2026-07-02) once entries carried it, and a rerun
2250
+ then failed temporal novelty. It now parses the `created` range only, checks against
2251
+ `parliamentary` alone (`parlamint_pl` left in Hub PR 54 and never shipped), and keeps an
2252
+ existing `sejm_api` registry entry that meets the contract instead of failing.
2253
+
2254
+ **Lesson** — check a scraped snapshot for navigation text glued to the record: a trailer
2255
+ in 90% of rows hid in plain sight because each row still began with the right speech.
data/sejm_api/sejm_api.attribution.jsonl CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:4ab6513f8173498d403f7ec1a9534b8e0086264d3eca6ff9ac4f9c5dbca4c069
3
- size 18722278
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:47d87542492629791df1112455ad4f5754fc74cd11ef620d7559ee4a243e80b1
3
+ size 19448386
data/sejm_api/sejm_api.md CHANGED
@@ -33,7 +33,8 @@ source. No unverified upstream Creative Commons license is asserted.
33
  - Immutable source release: `PiotrSty/sejm-speeches-corpus@v1.0.1`.
34
  - Pinned source commit: `124557799608ce4212cf22fa90ca7904618de1b6`.
35
  - Reviewed DynaWord base commit: `8cc48a3c564ac9edabfbbf012842ad11f70a3e5c`.
36
- - Rebuild: `python src/fetch_sejm_api.py --help`.
 
37
  - Speaker attribution and source URLs are in `sejm_api.attribution.jsonl`. Each
38
  `source_url` is a day-level listing (`https://api.sejm.gov.pl/sejm/term{N}/videos/{date}`),
39
  not a per-speech URL.
@@ -52,15 +53,35 @@ SHA-1 fingerprints; this is not a claim of global cross-domain near-deduplicatio
52
  |---|---:|
53
  | Source rows inspected | 157,714 |
54
  | Rows before 2023-01-01 | 118,902 |
55
- | Exact duplicate texts removed | 0 |
56
- | Documents published | 38,812 |
57
- | Characters | 96,596,566 |
58
- | Tokens (`cl100k_base` proxy) | 36,335,587 |
59
- | Documents with speaker attribution | 38,812 |
 
 
60
 
61
  Statistics are recomputed from the released Parquet file. The canonical schema
62
  is `id, text, source, added, created, token_count, license, author`.
63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  ## Privacy and limitations
65
 
66
  The upstream release heuristically redacts email addresses, PESEL identifiers
 
33
  - Immutable source release: `PiotrSty/sejm-speeches-corpus@v1.0.1`.
34
  - Pinned source commit: `124557799608ce4212cf22fa90ca7904618de1b6`.
35
  - Reviewed DynaWord base commit: `8cc48a3c564ac9edabfbbf012842ad11f70a3e5c`.
36
+ - Rebuild: `python src/fetch_sejm_api.py --help`, then `python3 src/clean_sejm_api.py`
37
+ (trailer cut, below).
38
  - Speaker attribution and source URLs are in `sejm_api.attribution.jsonl`. Each
39
  `source_url` is a day-level listing (`https://api.sejm.gov.pl/sejm/term{N}/videos/{date}`),
40
  not a per-speech URL.
 
53
  |---|---:|
54
  | Source rows inspected | 157,714 |
55
  | Rows before 2023-01-01 | 118,902 |
56
+ | Statements split into rows of their own | 2,466 |
57
+ | Rows under 200 characters | 1,371 |
58
+ | Exact duplicate texts removed | 8 |
59
+ | Documents published | 39,899 |
60
+ | Characters | 83,482,628 |
61
+ | Tokens (`cl100k_base` proxy) | 30,860,439 |
62
+ | Documents with speaker attribution | 39,899 |
63
 
64
  Statistics are recomputed from the released Parquet file. The canonical schema
65
  is `id, text, source, added, created, token_count, license, author`.
66
 
67
+ ## Trailer cut
68
+
69
+ The rights audit (slayerlabs/polish-dynaword-v2#57) found that the snapshot
70
+ appends to 34,980 of the 38,812 fetched speeches a "Przebieg posiedzenia" header
71
+ of a later statement of the same sitting day, and sometimes that statement's
72
+ text. `src/clean_sejm_api.py` cuts every trailer (23,485,670 characters). An
73
+ appended statement with text becomes a row of its own (2,466 rows), credited to
74
+ the speaker the header names ("Przebieg posiedzenia Janusz Kowalski: …"), without
75
+ the office in its label. Its date and term are those
76
+ of the row it was cut from: the snapshot labels the 11th sitting of term 10
77
+ (2024-05-08, 2024-05-09, 2024-05-15) "11. kadencja" in 696 headers. A split row's
78
+ id hashes its date, term, speaker and text like every other row; its sidecar
79
+ line carries `split_from` (the id of the row it was cut from in v0.2.5) and
80
+ `has_events: null`, since the snapshot's events
81
+ flag describes the whole parent row. Rows that fall under the fetch's
82
+ 200-character minimum after the cut (1,318 cut speeches and 53 split rows) and 8
83
+ texts that became exact duplicates are dropped.
84
+
85
  ## Privacy and limitations
86
 
87
  The upstream release heuristically redacts email addresses, PESEL identifiers
data/sejm_api/sejm_api.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:56f7b03483488dec8f0fa145c6d26746926175d83096e9d1931e535aa81cf161
3
- size 35267581
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ba2daa20d2d2753c09e8bdd477839f43c82170f44caeadc634cb2295362c9c3b
3
+ size 34336428
data/sejm_api/sejm_api.stats.json CHANGED
@@ -1,36 +1,49 @@
1
  {
2
  "added": "2026-08-22",
3
- "authors_with_value": 38812,
4
  "by_source_split": {
5
- "train": 38053,
6
- "validation": 759
7
  },
8
  "by_term": {
9
- "10": 30789,
10
- "9": 8023
11
  },
12
  "by_year": {
13
- "2023": 10220,
14
- "2024": 4788,
15
- "2025": 13712,
16
- "2026": 10092
17
  },
18
- "chars": 96596566,
19
  "created_max": "2026-07-03",
20
  "created_min": "2023-01-11",
21
  "drop_before_start": 118902,
22
- "drop_dup": 0,
23
  "drop_lang": 0,
24
  "drop_ocr": 0,
25
- "drop_short": 0,
26
- "kept": 38812,
27
  "license": "public-domain (official documents)",
28
  "licenses": {
29
- "public-domain (official documents)": 38812
30
  },
31
  "read": 157714,
32
  "source_revision": "124557799608ce4212cf22fa90ca7904618de1b6",
 
33
  "stats_recomputed_from_parquet": true,
34
  "target_base_revision": "8cc48a3c564ac9edabfbbf012842ad11f70a3e5c",
35
- "tokens": 36335587
 
 
 
 
 
 
 
 
 
 
 
 
36
  }
 
1
  {
2
  "added": "2026-08-22",
3
+ "authors_with_value": 39899,
4
  "by_source_split": {
5
+ "train": 39132,
6
+ "validation": 767
7
  },
8
  "by_term": {
9
+ "10": 31655,
10
+ "9": 8244
11
  },
12
  "by_year": {
13
+ "2023": 10341,
14
+ "2024": 4937,
15
+ "2025": 14110,
16
+ "2026": 10511
17
  },
18
+ "chars": 83482628,
19
  "created_max": "2026-07-03",
20
  "created_min": "2023-01-11",
21
  "drop_before_start": 118902,
22
+ "drop_dup": 8,
23
  "drop_lang": 0,
24
  "drop_ocr": 0,
25
+ "drop_short": 1371,
26
+ "kept": 39899,
27
  "license": "public-domain (official documents)",
28
  "licenses": {
29
+ "public-domain (official documents)": 39899
30
  },
31
  "read": 157714,
32
  "source_revision": "124557799608ce4212cf22fa90ca7904618de1b6",
33
+ "split_rows": 2466,
34
  "stats_recomputed_from_parquet": true,
35
  "target_base_revision": "8cc48a3c564ac9edabfbbf012842ad11f70a3e5c",
36
+ "tokens": 30860439,
37
+ "trailer_cut": {
38
+ "chars_cut": 23485670,
39
+ "drop_dup": 8,
40
+ "drop_short": 1371,
41
+ "input_sha256": {
42
+ "sejm_api.attribution.jsonl": "4ab6513f8173498d403f7ec1a9534b8e0086264d3eca6ff9ac4f9c5dbca4c069",
43
+ "sejm_api.parquet": "56f7b03483488dec8f0fa145c6d26746926175d83096e9d1931e535aa81cf161",
44
+ "sejm_api.stats.json": "edee610cdc0fcbc1c7015ed4f7d5dda74b549100cca5f410beaaf8ae3b0229c2"
45
+ },
46
+ "rows_cut": 34980,
47
+ "split_rows": 2466
48
+ }
49
  }
src/clean_sejm_api.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Cut the "Przebieg posiedzenia" trailers off the sejm_api speeches (slayerlabs/polish-dynaword-v2#57).
3
+
4
+ The PiotrSty snapshot appends to most speeches the header of a later statement of the same sitting
5
+ day, and sometimes that statement's text (see sejm_api_common.split_trailers). This script cuts every
6
+ trailer and keeps a trailer's speech as a row of its own under the header's speaker
7
+ (sejm_api_common.split_release_rows); rows that fall under the 200-character minimum after the cut,
8
+ and texts that become exact duplicates, are dropped.
9
+
10
+ The inputs are the pre-cut release files, pinned by SHA-256. Restore them before a rerun:
11
+ git checkout 262df1b -- data/sejm_api/sejm_api.{parquet,attribution.jsonl,stats.json}
12
+ python3 src/clean_sejm_api.py
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import json
18
+ from pathlib import Path
19
+
20
+ import pyarrow as pa
21
+ import pyarrow.parquet as pq
22
+ import tiktoken
23
+
24
+ from sejm_api_common import check_pin, release_stats, replace_all, split_release_rows
25
+
26
+ SOURCE = "sejm_api"
27
+ ROOT = Path(__file__).resolve().parents[1]
28
+ DATA = ROOT / "data" / SOURCE
29
+ # Pre-cut release files (main at 262df1b; the Parquet is the v0.2.5 file);
30
+ # artifacts/sejm_api_ontology_manifest.json records the fetch output, i.e. these.
31
+ INPUT_SHA256 = {
32
+ f"{SOURCE}.parquet": "56f7b03483488dec8f0fa145c6d26746926175d83096e9d1931e535aa81cf161",
33
+ f"{SOURCE}.attribution.jsonl": "4ab6513f8173498d403f7ec1a9534b8e0086264d3eca6ff9ac4f9c5dbca4c069",
34
+ f"{SOURCE}.stats.json": "edee610cdc0fcbc1c7015ed4f7d5dda74b549100cca5f410beaaf8ae3b0229c2",
35
+ }
36
+ ROW_GROUP_SIZE = 512 # the layout of the released file
37
+
38
+
39
+ def build(input_dir: Path, out_dir: Path) -> dict:
40
+ for name, sha in INPUT_SHA256.items():
41
+ check_pin(input_dir / name, sha, f"restore it with `git checkout 262df1b -- data/{SOURCE}/{name}`")
42
+ table = pq.read_table(input_dir / f"{SOURCE}.parquet")
43
+ with (input_dir / f"{SOURCE}.attribution.jsonl").open(encoding="utf-8") as stream:
44
+ sidecar = [json.loads(line) for line in stream]
45
+ stats = json.loads((input_dir / f"{SOURCE}.stats.json").read_text(encoding="utf-8"))
46
+ rows = table.to_pylist()
47
+ recomputed = release_stats(rows, sidecar)
48
+ if recomputed != {key: stats[key] for key in recomputed}:
49
+ raise SystemExit("the input stats.json does not describe the input Parquet")
50
+
51
+ rows, sidecar, counts = split_release_rows(rows, sidecar, tiktoken.get_encoding("cl100k_base"))
52
+ stats.update(release_stats(rows, sidecar))
53
+ stats["split_rows"] = counts["split_rows"]
54
+ stats["drop_short"] += counts["drop_short"]
55
+ stats["drop_dup"] += counts["drop_dup"]
56
+ stats["trailer_cut"] = {"input_sha256": INPUT_SHA256, **counts}
57
+ drops = ("drop_before_start", "drop_dup", "drop_short", "drop_lang", "drop_ocr")
58
+ if stats["read"] + stats["split_rows"] - sum(stats[k] for k in drops) != stats["kept"]:
59
+ raise SystemExit("stats drop counts do not add up to the kept rows")
60
+
61
+ replace_all({
62
+ out_dir / f"{SOURCE}.parquet": lambda p: pq.write_table(
63
+ pa.Table.from_pylist(rows, schema=table.schema), p, compression="zstd", row_group_size=ROW_GROUP_SIZE),
64
+ out_dir / f"{SOURCE}.attribution.jsonl": lambda p: p.write_text(
65
+ "".join(json.dumps(line, ensure_ascii=False, sort_keys=True) + "\n" for line in sidecar), encoding="utf-8"),
66
+ out_dir / f"{SOURCE}.stats.json": lambda p: p.write_text(
67
+ json.dumps(stats, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8"),
68
+ })
69
+ return stats
70
+
71
+
72
+ def main() -> None:
73
+ parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
74
+ parser.add_argument("--data", type=Path, default=DATA, help="directory holding the (restored) input files; outputs are written there")
75
+ args = parser.parse_args()
76
+ print(json.dumps(build(args.data, args.data), indent=2, ensure_ascii=False))
77
+
78
+
79
+ if __name__ == "__main__":
80
+ main()
src/fetch_sejm_api.py CHANGED
@@ -107,26 +107,37 @@ def normalize_source_row(
107
  return document, attribution
108
 
109
 
110
- def registry_source_end_date(registry: str, source_name: str) -> str:
111
  pattern = re.compile(
112
  rf'^\s{{4}}["\']{re.escape(source_name)}["\']\s*:\s*\{{'
113
  rf'(?P<body>.*?)^\s{{4}}\}},?',
114
  flags=re.MULTILINE | re.DOTALL,
115
  )
116
- match = pattern.search(registry)
 
 
 
 
117
  if not match:
118
  raise ContributionError(f"existing parliamentary source missing from registry: {source_name}")
119
- dates = re.findall(r"\d{4}-\d{2}-\d{2}", match.group("body"))
120
- if not dates:
 
 
121
  raise ContributionError(f"source {source_name} has no documented date range")
122
- return max(dates)
 
 
 
 
 
123
 
124
 
125
  def assert_temporal_novelty(registry: str, start_date: str) -> dict[str, str]:
126
  threshold = dt.date.fromisoformat(start_date)
127
  end_dates = {
128
  name: registry_source_end_date(registry, name)
129
- for name in ("parliamentary", "parlamint_pl")
130
  }
131
  overlapping = {
132
  name: value for name, value in end_dates.items()
@@ -138,11 +149,23 @@ def assert_temporal_novelty(registry: str, start_date: str) -> dict[str, str]:
138
 
139
 
140
  def insert_source_registry_entry(registry: str, *, end_date: str) -> str:
141
- if re.search(r'^\s{4}["\']sejm_api["\']\s*:', registry, flags=re.MULTILINE):
142
- raise ContributionError("sejm_api already exists in the DynaWord source registry")
143
- marker = ' "parlamint_pl": {'
144
- if registry.count(marker) != 1:
145
- raise ContributionError("cannot safely locate the existing parlamint_pl registry entry")
 
 
 
 
 
 
 
 
 
 
 
 
146
  entry = (
147
  ' "sejm_api": {\n'
148
  ' "file_key": "sejm_api",\n'
@@ -163,7 +186,8 @@ def insert_source_registry_entry(registry: str, *, end_date: str) -> str:
163
  ' "is_ocr": False,\n'
164
  ' },\n'
165
  )
166
- updated = registry.replace(marker, entry + marker, 1)
 
167
  ast.parse(updated)
168
  return updated
169
 
@@ -310,8 +334,8 @@ def ontology_manifest(
310
  ]
311
  claims = [
312
  {"id": f"slayer://claim/sejm-api-temporal-novelty@sha256:{version_digest[:20]}",
313
- "statement": "Every contributed speech postdates both registered parliamentary source ranges.",
314
- "falsification_condition": "Any contributed created date is <= either documented source end date.",
315
  "scope": [version], "supported_by": [evidence_ids["temporal-novelty"]], "asserted_by": actor},
316
  {"id": f"slayer://claim/sejm-api-full-speaker-attribution@sha256:{version_digest[:20]}",
317
  "statement": "Every contributed document has a non-empty speech-speaker attribution.",
 
107
  return document, attribution
108
 
109
 
110
+ def registry_entry(registry: str, source_name: str) -> re.Match[str] | None:
111
  pattern = re.compile(
112
  rf'^\s{{4}}["\']{re.escape(source_name)}["\']\s*:\s*\{{'
113
  rf'(?P<body>.*?)^\s{{4}}\}},?',
114
  flags=re.MULTILINE | re.DOTALL,
115
  )
116
+ return pattern.search(registry)
117
+
118
+
119
+ def registry_source_end_date(registry: str, source_name: str) -> str:
120
+ match = registry_entry(registry, source_name)
121
  if not match:
122
  raise ContributionError(f"existing parliamentary source missing from registry: {source_name}")
123
+ # The `created` range only: entries also carry an `added` date.
124
+ created = re.search(r'["\']created["\']\s*:\s*["\']\d{4}-\d{2}-\d{2}, (\d{4}-\d{2}-\d{2})["\']',
125
+ match.group("body"))
126
+ if not created:
127
  raise ContributionError(f"source {source_name} has no documented date range")
128
+ return created.group(1)
129
+
130
+
131
+ # `parlamint_pl` (2015-2022) left the registry in Hub PR 54 without ever shipping data, so only
132
+ # `parliamentary` is checked; sejm_api_2011_2022 ends on 2022-12-31 by its own END_DATE.
133
+ PRIOR_PARLIAMENTARY_SOURCES = ("parliamentary",)
134
 
135
 
136
  def assert_temporal_novelty(registry: str, start_date: str) -> dict[str, str]:
137
  threshold = dt.date.fromisoformat(start_date)
138
  end_dates = {
139
  name: registry_source_end_date(registry, name)
140
+ for name in PRIOR_PARLIAMENTARY_SOURCES
141
  }
142
  overlapping = {
143
  name: value for name, value in end_dates.items()
 
149
 
150
 
151
  def insert_source_registry_entry(registry: str, *, end_date: str) -> str:
152
+ """Add the sejm_api entry after `parliamentary`; on a rerun, check the existing entry and keep it."""
153
+ existing = registry_entry(registry, SOURCE_NAME)
154
+ if existing:
155
+ required = (
156
+ f'"file_key": "{SOURCE_NAME}"',
157
+ f'"license": "{SOURCE_LICENSE}"',
158
+ '"license_spdx": "LicenseRef-Polish-Official-Documents"',
159
+ f'"upstream": "{SEJM_API}"',
160
+ f'"created": "{START_DATE}, {end_date}"',
161
+ )
162
+ differing = [value for value in required if value not in existing.group("body")]
163
+ if differing:
164
+ raise ContributionError(f"existing sejm_api registry entry differs from the contract: {differing}")
165
+ return registry
166
+ anchor = registry_entry(registry, "parliamentary")
167
+ if not anchor:
168
+ raise ContributionError("cannot safely locate the existing parliamentary registry entry")
169
  entry = (
170
  ' "sejm_api": {\n'
171
  ' "file_key": "sejm_api",\n'
 
186
  ' "is_ocr": False,\n'
187
  ' },\n'
188
  )
189
+ insert_at = registry.index("\n", anchor.end()) + 1
190
+ updated = registry[:insert_at] + entry + registry[insert_at:]
191
  ast.parse(updated)
192
  return updated
193
 
 
334
  ]
335
  claims = [
336
  {"id": f"slayer://claim/sejm-api-temporal-novelty@sha256:{version_digest[:20]}",
337
+ "statement": "Every contributed speech postdates every checked registered parliamentary source range.",
338
+ "falsification_condition": "Any contributed created date is <= a documented source end date.",
339
  "scope": [version], "supported_by": [evidence_ids["temporal-novelty"]], "asserted_by": actor},
340
  {"id": f"slayer://claim/sejm-api-full-speaker-attribution@sha256:{version_digest[:20]}",
341
  "statement": "Every contributed document has a non-empty speech-speaker attribution.",
src/sejm_api_common.py CHANGED
@@ -10,8 +10,11 @@ from __future__ import annotations
10
 
11
  import hashlib
12
  import json
 
13
  import pathlib
14
- from typing import Any
 
 
15
 
16
  COPYRIGHT_ACT = "https://eli.gov.pl/api/acts/DU/2025/24/text/O/D20250024.pdf"
17
  OPEN_DATA_ACT = "https://eli.gov.pl/api/acts/DU/2023/1524/text.html"
@@ -23,6 +26,149 @@ EXPECTED_FIELDS = (
23
  )
24
 
25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  def sha256_file(path: pathlib.Path) -> str:
27
  digest = hashlib.sha256()
28
  with path.open("rb") as stream:
 
10
 
11
  import hashlib
12
  import json
13
+ import os
14
  import pathlib
15
+ import re
16
+ from collections import Counter
17
+ from typing import Any, Callable
18
 
19
  COPYRIGHT_ACT = "https://eli.gov.pl/api/acts/DU/2025/24/text/O/D20250024.pdf"
20
  OPEN_DATA_ACT = "https://eli.gov.pl/api/acts/DU/2023/1524/text.html"
 
26
  )
27
 
28
 
29
+ # The PiotrSty snapshot ends many speeches with the header of a later statement of the sitting,
30
+ # "Przebieg posiedzenia <name>: <T>. kadencja, <n>. posiedzenie, <d>. dzień - <label> <T>. kadencja,
31
+ # ... (dd-mm-yyyy)", then an optional agenda title ("<k>. punkt porządku dziennego: <title>." or
32
+ # "Oświadczenia."), then, when that statement has no row of its own (ministers, follow-up questions),
33
+ # its text, usually opened by "<label>: ". Term 7 omits the dots after the numbers. A row can carry
34
+ # several trailers; some rows end with a bare or truncated header instead.
35
+ _SITTING = r"\d+\.? kadencja,\s+\d+\.? posiedzenie, \d+\.? dzień"
36
+ TRAILER = re.compile(
37
+ r"Przebieg posiedzenia (?P<name>[^:\n]{1,120}?): (?P<term>\d+)\.? kadencja,\s+\d+\.? posiedzenie, \d+\.? dzień"
38
+ r" - (?P<label>[^\n]{1,300}?) (?P=term)\.? kadencja,\s+\d+\.? posiedzenie, \d+\.? dzień \((?P<date>\d{2}-\d{2}-\d{4})\)"
39
+ )
40
+ TRUNCATED_TRAILER = re.compile(
41
+ r"\s*Przebieg posiedzenia(?: [^:\n]{1,120}?: " + _SITTING + r"(?: - [^.():!?\n]{1,200})?)?\s*$"
42
+ )
43
+ # A title ends at its "(druk nr N)." citation, else at its first full stop; numbered items ("9. ...")
44
+ # that follow belong to it.
45
+ _SENTENCE = r"(?:.{0,800}?\(druki? nr [^)]{0,80}\)\.|.*?\.)(?=\s|\Z)"
46
+ AGENDA = re.compile(
47
+ r"\s*(?:\d[\d., i]{0,40} punkt porządku dziennego: " + _SENTENCE + r"(?:\s\d+\. " + _SENTENCE + r")*"
48
+ r"|Oświadczenia\.)?"
49
+ )
50
+
51
+
52
+ def split_trailers(text: str, author: str) -> tuple[str, list[dict[str, str]]]:
53
+ """Cut the trailers off a speech: (its own text, one dict per trailer).
54
+
55
+ A trailer's `text` is what follows its "<label>: " line. Without that line it is what follows
56
+ the agenda title when the trailer names the row's own speaker (a follow-up of theirs), else ""
57
+ (the header of a statement that has a row of its own). `date` is ISO. `name` is the header's
58
+ own speaker name; the label prefixes it with an office ("Podsekretarz Stanu w Ministerstwie
59
+ Zdrowia Janusz Cieszyński"), which the snapshot's `speaker` convention (the label without its
60
+ first word) would garble.
61
+ """
62
+ end = TRUNCATED_TRAILER.search(text)
63
+ stop = end.start() if end else len(text)
64
+ heads = list(TRAILER.finditer(text, 0, stop))
65
+ own = text[: heads[0].start() if heads else stop].rstrip()
66
+ trailers = []
67
+ for head, following in zip(heads, heads[1:] + [None]):
68
+ chunk = text[head.end(): following.start() if following else stop]
69
+ line = chunk.find(head["label"] + ": ")
70
+ if line >= 0:
71
+ body = chunk[line + len(head["label"]) + 2:]
72
+ elif re.search(rf"(?<!\w){re.escape(head['name'])}(?!\w)", author):
73
+ body = chunk[AGENDA.match(chunk).end():]
74
+ else:
75
+ body = ""
76
+ day, month, year = head["date"].split("-")
77
+ trailers.append({"name": head["name"], "term": head["term"],
78
+ "date": f"{year}-{month}-{day}", "text": body.strip()})
79
+ return own, trailers
80
+
81
+
82
+ MIN_CHARS = 200 # the fetchers' own minimum (normalize_source_row)
83
+
84
+
85
+ def split_release_rows(rows: list[dict[str, Any]], sidecar: list[dict[str, Any]], encoder: Any
86
+ ) -> tuple[list[dict[str, Any]], list[dict[str, Any]], Counter[str]]:
87
+ """Cut the trailers off released rows and give each trailer speech a row of its own.
88
+
89
+ `rows` (Parquet) and `sidecar` (attribution) are parallel. A cut row keeps its id, and its
90
+ token_count, char_count and word_count are recomputed. A trailer speech becomes a new row right
91
+ after its parent, with the snapshot's id scheme over (date, term, speaker, text), the parent's
92
+ source, license, added, term and source_url, and `split_from` = the parent id in the sidecar.
93
+ `has_events` (an upstream flag the text cannot give) is null on new rows. Cut and new rows under
94
+ MIN_CHARS, and exact text duplicates (SHA-1, first wins), are dropped, as the fetchers do; uncut
95
+ rows pass unchecked.
96
+ """
97
+ if [row["id"] for row in rows] != [line["id"] for line in sidecar]:
98
+ raise ValueError("the attribution sidecar does not match the Parquet ids")
99
+ out_rows: list[dict[str, Any]] = []
100
+ out_sidecar: list[dict[str, Any]] = []
101
+ seen: set[str] = set()
102
+ counts: Counter[str] = Counter(rows_cut=0, chars_cut=0, split_rows=0, drop_short=0, drop_dup=0)
103
+
104
+ def emit(row: dict[str, Any], line: dict[str, Any], changed: bool) -> None:
105
+ fingerprint = hashlib.sha1(row["text"].encode("utf-8")).hexdigest()
106
+ if changed and len(row["text"]) < MIN_CHARS:
107
+ counts["drop_short"] += 1
108
+ elif fingerprint in seen:
109
+ counts["drop_dup"] += 1
110
+ else:
111
+ seen.add(fingerprint)
112
+ out_rows.append(row)
113
+ out_sidecar.append(line)
114
+
115
+ def with_text(row: dict[str, Any], line: dict[str, Any], text: str) -> tuple[dict, dict]:
116
+ return ({**row, "text": text, "token_count": len(encoder.encode_ordinary(text))},
117
+ {**line, "char_count": len(text), "word_count": len(text.split())})
118
+
119
+ for row, line in zip(rows, sidecar):
120
+ own, trailers = split_trailers(row["text"], row["author"])
121
+ cut = own != row["text"]
122
+ if cut:
123
+ counts["rows_cut"] += 1
124
+ counts["chars_cut"] += len(row["text"]) - len(own)
125
+ emit(*(with_text(row, line, own) if cut else (row, line)), cut)
126
+ for trailer in trailers:
127
+ if not trailer["text"]:
128
+ continue
129
+ # The row's term, not the header's: the snapshot labels the 11th sitting of term 10
130
+ # (2024-05-08/09/15) "11. kadencja" in 696 headers.
131
+ if trailer["date"] != row["created"]:
132
+ raise ValueError(f"{row['id']}: a trailer from another sitting day: {trailer['date']}")
133
+ counts["split_rows"] += 1
134
+ new_id = stable_document_id({"date": trailer["date"], "term": line["term"],
135
+ "speaker": trailer["name"], "text": trailer["text"]}, row["source"])
136
+ new_row, new_line = with_text({**row, "id": new_id, "author": trailer["name"]},
137
+ {**line, "id": new_id, "speaker": trailer["name"],
138
+ "has_events": None, "split_from": row["id"]}, trailer["text"])
139
+ emit(new_row, new_line, True)
140
+ return out_rows, out_sidecar, counts
141
+
142
+
143
+ def release_stats(rows: list[dict[str, Any]], sidecar: list[dict[str, Any]]) -> dict[str, Any]:
144
+ """The stats.json fields that are recomputed from the released rows."""
145
+ created = [row["created"] for row in rows]
146
+ return {
147
+ "kept": len(rows),
148
+ "chars": sum(len(row["text"]) for row in rows),
149
+ "tokens": sum(row["token_count"] for row in rows),
150
+ "licenses": dict(sorted(Counter(row["license"] for row in rows).items())),
151
+ "authors_with_value": sum(bool(row["author"]) for row in rows),
152
+ "created_min": min(created), "created_max": max(created),
153
+ "by_year": dict(sorted(Counter(date[:4] for date in created).items())),
154
+ "by_term": dict(sorted(Counter(line["term"] for line in sidecar).items())),
155
+ "by_source_split": dict(sorted(Counter(line["source_split"] for line in sidecar).items())),
156
+ }
157
+
158
+
159
+ def check_pin(path: pathlib.Path, expected: str, restore: str) -> None:
160
+ if sha256_file(path) != expected:
161
+ raise SystemExit(f"{path} does not match the pinned SHA-256; {restore}")
162
+
163
+
164
+ def replace_all(writers: dict[pathlib.Path, Callable[[pathlib.Path], None]]) -> None:
165
+ """Write every output to <path>.tmp first, then move them all into place."""
166
+ for path, write in writers.items():
167
+ write(path.with_name(path.name + ".tmp"))
168
+ for path in writers:
169
+ os.replace(path.with_name(path.name + ".tmp"), path)
170
+
171
+
172
  def sha256_file(path: pathlib.Path) -> str:
173
  digest = hashlib.sha256()
174
  with path.open("rb") as stream:
src/test_sejm_api_contract.py CHANGED
@@ -29,18 +29,22 @@ except ImportError:
29
  )
30
 
31
  from sources import SOURCES # noqa: E402 (src/ is on sys.path above)
 
 
 
32
 
33
  ROOT = pathlib.Path(__file__).resolve().parents[1]
34
  DAY_LEVEL_URL = re.compile(r"https://api\.sejm\.gov\.pl/sejm/term\d+/videos/\d{4}-\d{2}-\d{2}")
35
 
36
  REGISTRY = '''SOURCES = {
37
  "parliamentary": {
 
38
  "created": "1991-01-01, 2019-12-31",
39
  "license": "public-domain (official documents)",
40
  },
41
- "parlamint_pl": {
42
- "created": "2015-01-01, 2022-12-31",
43
- "license": "CC-BY-4.0",
44
  },
45
  }
46
  '''
@@ -89,7 +93,7 @@ class DynawordContractTests(unittest.TestCase):
89
  added_date="2026-08-22", encoder=FakeEncoder()
90
  ))
91
 
92
- def test_first_day_after_parlamint_is_included(self) -> None:
93
  self.assertIsNotNone(normalize_source_row(
94
  sample_row(2, date="2023-01-01"), start_date=START_DATE,
95
  added_date="2026-08-22", encoder=FakeEncoder()
@@ -121,23 +125,32 @@ class DynawordContractTests(unittest.TestCase):
121
  start_date=START_DATE, added_date="2026-08-22", encoder=FakeEncoder()
122
  )
123
 
124
- def test_temporal_novelty_against_both_registered_sources(self) -> None:
125
- self.assertEqual(assert_temporal_novelty(REGISTRY, START_DATE), {
126
- "parliamentary": "2019-12-31",
127
- "parlamint_pl": "2022-12-31",
128
- })
129
 
130
- def test_overlap_with_registered_parlamint_fails_closed(self) -> None:
131
  with self.assertRaisesRegex(ContributionError, "overlaps"):
132
- assert_temporal_novelty(REGISTRY, "2022-01-01")
133
 
134
  def test_registry_entry_is_valid_and_preserves_existing_sources(self) -> None:
135
  updated = insert_source_registry_entry(REGISTRY, end_date="2026-07-03")
136
  ast.parse(updated)
137
- self.assertIn('"sejm_api": {', updated)
138
- self.assertIn('"parlamint_pl": {', updated)
139
  self.assertIn('"created": "2023-01-01, 2026-07-03"', updated)
140
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  def test_registry_template_matches_the_shipped_provenance(self) -> None:
142
  updated = insert_source_registry_entry(REGISTRY, end_date="2026-07-03")
143
  template = ast.literal_eval(updated.split("=", 1)[1])["sejm_api"]
@@ -217,5 +230,174 @@ class DynawordParquetIntegrationTests(unittest.TestCase):
217
  self.assertTrue((output / "src" / "test_sejm_api_contract.py").is_file())
218
 
219
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
  if __name__ == "__main__":
221
  unittest.main()
 
29
  )
30
 
31
  from sources import SOURCES # noqa: E402 (src/ is on sys.path above)
32
+ from sejm_api_common import ( # noqa: E402
33
+ TRAILER, TRUNCATED_TRAILER, release_stats, split_release_rows, split_trailers,
34
+ )
35
 
36
  ROOT = pathlib.Path(__file__).resolve().parents[1]
37
  DAY_LEVEL_URL = re.compile(r"https://api\.sejm\.gov\.pl/sejm/term\d+/videos/\d{4}-\d{2}-\d{2}")
38
 
39
  REGISTRY = '''SOURCES = {
40
  "parliamentary": {
41
+ "added": "2026-07-02",
42
  "created": "1991-01-01, 2019-12-31",
43
  "license": "public-domain (official documents)",
44
  },
45
+ "sejm_interpellations": {
46
+ "created": "2023-11-13, 2026-07-03",
47
+ "license": "public-domain (official documents)",
48
  },
49
  }
50
  '''
 
93
  added_date="2026-08-22", encoder=FakeEncoder()
94
  ))
95
 
96
+ def test_first_day_of_2023_is_included(self) -> None:
97
  self.assertIsNotNone(normalize_source_row(
98
  sample_row(2, date="2023-01-01"), start_date=START_DATE,
99
  added_date="2026-08-22", encoder=FakeEncoder()
 
125
  start_date=START_DATE, added_date="2026-08-22", encoder=FakeEncoder()
126
  )
127
 
128
+ def test_temporal_novelty_reads_the_created_range_not_the_added_date(self) -> None:
129
+ self.assertEqual(assert_temporal_novelty(REGISTRY, START_DATE), {"parliamentary": "2019-12-31"})
 
 
 
130
 
131
+ def test_overlap_with_registered_parliamentary_fails_closed(self) -> None:
132
  with self.assertRaisesRegex(ContributionError, "overlaps"):
133
+ assert_temporal_novelty(REGISTRY, "2019-06-01")
134
 
135
  def test_registry_entry_is_valid_and_preserves_existing_sources(self) -> None:
136
  updated = insert_source_registry_entry(REGISTRY, end_date="2026-07-03")
137
  ast.parse(updated)
138
+ self.assertLess(updated.index('"parliamentary": {'), updated.index('"sejm_api": {'))
139
+ self.assertLess(updated.index('"sejm_api": {'), updated.index('"sejm_interpellations": {'))
140
  self.assertIn('"created": "2023-01-01, 2026-07-03"', updated)
141
 
142
+ def test_rerun_keeps_an_existing_entry_that_meets_the_contract(self) -> None:
143
+ updated = insert_source_registry_entry(REGISTRY, end_date="2026-07-03")
144
+ self.assertEqual(insert_source_registry_entry(updated, end_date="2026-07-03"), updated)
145
+ with self.assertRaisesRegex(ContributionError, "differs from the contract"):
146
+ insert_source_registry_entry(updated, end_date="2026-08-01")
147
+
148
+ def test_rerun_against_the_shipped_registry(self) -> None:
149
+ registry = (ROOT / "src" / "sources.py").read_text(encoding="utf-8")
150
+ self.assertEqual(assert_temporal_novelty(registry, START_DATE), {"parliamentary": "2019-12-31"})
151
+ end_date = SOURCES["sejm_api"]["created"].split(", ")[1]
152
+ self.assertEqual(insert_source_registry_entry(registry, end_date=end_date), registry)
153
+
154
  def test_registry_template_matches_the_shipped_provenance(self) -> None:
155
  updated = insert_source_registry_entry(REGISTRY, end_date="2026-07-03")
156
  template = ast.literal_eval(updated.split("=", 1)[1])["sejm_api"]
 
230
  self.assertTrue((output / "src" / "test_sejm_api_contract.py").is_file())
231
 
232
 
233
+ def header(name: str, label: str, date: str, *, term: str = "9", sitting: str = "70", day: str = "1") -> str:
234
+ """A "Przebieg posiedzenia" trailer header as the snapshot writes it (terms 8-10; term 7 drops the dots)."""
235
+ if term == "7":
236
+ sitting_day = f"7 kadencja, {sitting} posiedzenie, {day} dzień"
237
+ else:
238
+ sitting_day = f"{term}. kadencja, {sitting}. posiedzenie, {day}. dzień"
239
+ return f"Przebieg posiedzenia {name}: {sitting_day} - {label} {sitting_day} ({date})"
240
+
241
+
242
+ class TrailerSplitTests(unittest.TestCase):
243
+ """v2#57: the trailers are cut, and a trailer's speech becomes a row of its own (real snippets)."""
244
+
245
+ def test_header_of_a_statement_with_its_own_row_is_cut(self) -> None:
246
+ own = "Komisja Ochrony Środowiska, Zasobów Naturalnych i Leśnictwa - godz. 17. Dziękuję."
247
+ text = own + " " + header("Krzysztof Paszyk", "Poseł Krzysztof Paszyk", "11-01-2023")
248
+ self.assertEqual(split_trailers(text, "Ryszard Terlecki"), (own, [{
249
+ "name": "Krzysztof Paszyk", "term": "9",
250
+ "date": "2023-01-11", "text": ""}]))
251
+
252
+ def test_appended_statement_after_its_label_line_is_kept(self) -> None:
253
+ label = "Sekretarz Stanu w Ministerstwie Rolnictwa i Rozwoju Wsi Janusz Kowalski"
254
+ speech = "Szanowna Pani Marszałek! Szanowna Wysoka Izbo! Szanowny Panie Pośle!"
255
+ text = ("Co zamierzacie zrobić w najbliższym czasie? Dziękuję. "
256
+ + header("Janusz Kowalski", label, "12-01-2023", day="2")
257
+ + " 11. punkt porządku dziennego: Pytania w sprawach bieżących. " + label + ": " + speech)
258
+ own, trailers = split_trailers(text, "Stefan Krajewski")
259
+ self.assertEqual(own, "Co zamierzacie zrobić w najbliższym czasie? Dziękuję.")
260
+ self.assertEqual(len(trailers), 1)
261
+ self.assertEqual(trailers[0]["text"], speech)
262
+ # The header's name, not the label minus its first word ("Stanu w Ministerstwie ...").
263
+ self.assertEqual(trailers[0]["name"], "Janusz Kowalski")
264
+
265
+ def test_term_7_follow_up_of_the_same_speaker_and_a_later_header(self) -> None:
266
+ follow_up = ("Mój wniosek formalny jest taki, żeby pani marszałek odpowiedziała Wysokiej Izbie. "
267
+ "Dziękuję. (Poruszenie na sali)")
268
+ text = ("Nie ma biało-czerwonej flagi. (Poruszenie, wesołość na sali) "
269
+ + header("Marek Matuszewski", "Poseł Marek Matuszewski", "01-12-2011", term="7", sitting="1", day="5")
270
+ + " " + follow_up + " "
271
+ + header("Stanisław Piotrowicz", "Poseł Stanisław Piotrowicz", "01-12-2011", term="7", sitting="1", day="5")
272
+ + " 15 punkt porządku dziennego: Wybór zastępcy przewodniczącego Trybunału Stanu (druk nr 31).")
273
+ own, trailers = split_trailers(text, "Marek Matuszewski")
274
+ self.assertEqual(own, "Nie ma biało-czerwonej flagi. (Poruszenie, wesołość na sali)")
275
+ self.assertEqual([(t["name"], t["term"], t["date"], t["text"]) for t in trailers], [
276
+ ("Marek Matuszewski", "7", "2011-12-01", follow_up),
277
+ ("Stanisław Piotrowicz", "7", "2011-12-01", ""),
278
+ ])
279
+
280
+ def test_agenda_title_before_a_same_speaker_follow_up_is_dropped(self) -> None:
281
+ for agenda in ("1 punkt porządku dziennego: Wybór marszałka Sejmu Rzeczypospolitej Polskiej.",
282
+ "Oświadczenia."):
283
+ text = ("Panie marszałku, nie bójmy się tej nazwy. (Oklaski) "
284
+ + header("Beata Mazurek", "Poseł Beata Mazurek", "08-11-2011", term="7", sitting="1")
285
+ + f" {agenda} Pani minister, to moje pierwsze pytanie.")
286
+ _, trailers = split_trailers(text, "Beata Mazurek")
287
+ self.assertEqual(trailers[0]["text"], "Pani minister, to moje pierwsze pytanie.")
288
+
289
+ def test_truncated_and_bare_headers_at_the_end_are_cut(self) -> None:
290
+ own = "Dziękuję bardzo. (Oklaski)"
291
+ for tail in (" Przebieg posiedzenia Barbara Dolniak: 8. kadencja, 31. posiedzenie, 1. dzień - Poseł Barbara Dolniak",
292
+ " Przebieg posiedzenia"):
293
+ self.assertEqual(split_trailers(own + tail, "Małgorzata Pępek"), (own, []))
294
+
295
+ def test_speech_about_a_sitting_is_not_cut(self) -> None:
296
+ text = "Przebieg posiedzenia komisji był burzliwy: 9. kadencja nie widziała takiej debaty."
297
+ self.assertEqual(split_trailers(text, "Jan Kowalski"), (text, []))
298
+
299
+
300
+ def release_row(index: int, text: str, *, author: str = "Ryszard Terlecki", created: str = "2023-01-11") -> tuple[dict, dict]:
301
+ row_id = f"sejm_api_{index}"
302
+ return ({"id": row_id, "text": text, "source": "sejm_api", "added": "2026-08-22", "created": created,
303
+ "token_count": len(text.split()), "license": SOURCE_LICENSE, "author": author},
304
+ {"id": row_id, "source_url": f"https://api.sejm.gov.pl/sejm/term10/videos/{created}", "speaker": author,
305
+ "created": created, "term": "10", "has_events": True, "word_count": len(text.split()),
306
+ "char_count": len(text), "provider": "Kancelaria Sejmu RP", "source_split": "train"})
307
+
308
+
309
+ class SplitReleaseRowsTests(unittest.TestCase):
310
+ OWN = "Wysoka Izbo!" + " Mówię o budżecie państwa." * 10
311
+ SPEECH = "Panie Marszałku! " + "Odpowiadam na pytanie pana posła. " * 10
312
+
313
+ def split(self, *rows: tuple[dict, dict]):
314
+ return split_release_rows([r for r, _ in rows], [s for _, s in rows], FakeEncoder())
315
+
316
+ def test_cut_parent_keeps_its_id_and_the_speech_gets_a_row(self) -> None:
317
+ # The header says "11. kadencja" as the snapshot does for the 11th sitting of term 10.
318
+ text = (self.OWN + " " + header("Jan Nowak", "Poseł Jan Nowak", "08-05-2024", term="11", sitting="11")
319
+ + " Poseł Jan Nowak: " + self.SPEECH)
320
+ rows, sidecar, counts = self.split(release_row(1, text, created="2024-05-08"))
321
+ parent, child = rows
322
+ self.assertEqual((parent["id"], parent["text"]), ("sejm_api_1", self.OWN))
323
+ self.assertEqual(parent["token_count"], len(self.OWN.split()))
324
+ self.assertEqual((sidecar[0]["char_count"], sidecar[0]["has_events"]), (len(self.OWN), True))
325
+ self.assertEqual((child["author"], child["created"], child["text"]), ("Jan Nowak", "2024-05-08", self.SPEECH.strip()))
326
+ self.assertEqual(child["id"], stable_document_id(
327
+ {"date": "2024-05-08", "term": "10", "speaker": "Jan Nowak", "text": self.SPEECH.strip()}))
328
+ self.assertEqual({k: sidecar[1][k] for k in ("id", "speaker", "term", "has_events", "split_from", "source_url")},
329
+ {"id": child["id"], "speaker": "Jan Nowak", "term": "10", "has_events": None,
330
+ "split_from": "sejm_api_1", "source_url": sidecar[0]["source_url"]})
331
+ self.assertEqual(dict(counts), {"rows_cut": 1, "chars_cut": len(text) - len(self.OWN),
332
+ "split_rows": 1, "drop_short": 0, "drop_dup": 0})
333
+
334
+ def test_short_rows_and_exact_duplicates_are_dropped(self) -> None:
335
+ trailer = " " + header("Jan Nowak", "Poseł Jan Nowak", "11-01-2023")
336
+ rows, _, counts = self.split(release_row(1, "Dziękuję." + trailer), release_row(2, self.OWN + trailer),
337
+ release_row(3, self.OWN, author="Inny Poseł"))
338
+ self.assertEqual([row["id"] for row in rows], ["sejm_api_2"])
339
+ self.assertEqual((counts["drop_short"], counts["drop_dup"], counts["rows_cut"]), (1, 1, 2))
340
+
341
+ def test_uncut_rows_pass_unchecked(self) -> None:
342
+ rows, _, counts = self.split(release_row(1, "Dziękuję."))
343
+ self.assertEqual(([row["id"] for row in rows], counts["drop_short"]), (["sejm_api_1"], 0))
344
+
345
+ def test_a_trailer_from_another_day_fails_closed(self) -> None:
346
+ text = self.OWN + " " + header("Jan Nowak", "Poseł Jan Nowak", "12-01-2023") + " Poseł Jan Nowak: " + self.SPEECH
347
+ with self.assertRaisesRegex(ValueError, "another sitting day"):
348
+ self.split(release_row(1, text))
349
+
350
+ def test_misaligned_sidecar_fails_closed(self) -> None:
351
+ row, line = release_row(1, self.OWN)
352
+ with self.assertRaisesRegex(ValueError, "sidecar"):
353
+ split_release_rows([row], [dict(line, id="sejm_api_2")], FakeEncoder())
354
+
355
+
356
+ class ReleasedTrailerCutTests(unittest.TestCase):
357
+ """The released files after src/clean_sejm_api.py."""
358
+
359
+ @classmethod
360
+ def setUpClass(cls) -> None:
361
+ try:
362
+ import pyarrow.parquet as pq
363
+ except ImportError:
364
+ raise unittest.SkipTest("pyarrow is installed on the release runner")
365
+ data = ROOT / "data" / "sejm_api"
366
+ cls.rows = pq.read_table(data / "sejm_api.parquet").to_pylist()
367
+ with (data / "sejm_api.attribution.jsonl").open(encoding="utf-8") as stream:
368
+ cls.sidecar = [json.loads(line) for line in stream]
369
+ cls.stats = json.loads((data / "sejm_api.stats.json").read_text(encoding="utf-8"))
370
+ cls.card = (data / "sejm_api.md").read_text(encoding="utf-8")
371
+
372
+ def test_no_trailer_is_left(self) -> None:
373
+ self.assertEqual([row["id"] for row in self.rows
374
+ if TRAILER.search(row["text"]) or TRUNCATED_TRAILER.search(row["text"])], [])
375
+
376
+ def test_rows_meet_the_fetch_contract(self) -> None:
377
+ self.assertEqual([row["id"] for row in self.rows], [line["id"] for line in self.sidecar])
378
+ self.assertEqual(min(len(row["text"]) for row in self.rows), 200)
379
+ self.assertEqual(len({row["text"] for row in self.rows}), len(self.rows))
380
+ self.assertTrue(all(row["author"] == line["speaker"] for row, line in zip(self.rows, self.sidecar)))
381
+ self.assertTrue(all(line["char_count"] == len(row["text"]) for row, line in zip(self.rows, self.sidecar)))
382
+
383
+ def test_split_rows_are_marked(self) -> None:
384
+ split = [line for line in self.sidecar if "split_from" in line]
385
+ # Fewer than split_rows: new rows under 200 characters are dropped like the cut parents.
386
+ self.assertTrue(0 < len(split) <= self.stats["split_rows"])
387
+ self.assertTrue(all(line["has_events"] is None for line in split))
388
+ self.assertTrue(all(line["split_from"].startswith("sejm_api_") for line in split))
389
+
390
+ def test_stats_and_card_describe_the_parquet(self) -> None:
391
+ recomputed = release_stats(self.rows, self.sidecar)
392
+ self.assertEqual({key: self.stats[key] for key in recomputed}, recomputed)
393
+ drops = ("drop_before_start", "drop_dup", "drop_short", "drop_lang", "drop_ocr")
394
+ self.assertEqual(self.stats["read"] + self.stats["split_rows"] - sum(self.stats[k] for k in drops),
395
+ self.stats["kept"])
396
+ for label, key in (("Documents published", "kept"), ("Characters", "chars"),
397
+ ("Tokens (`cl100k_base` proxy)", "tokens"), ("Rows under 200 characters", "drop_short"),
398
+ ("Statements split into rows of their own", "split_rows")):
399
+ self.assertIn(f"| {label} | {self.stats[key]:,} |", self.card)
400
+
401
+
402
  if __name__ == "__main__":
403
  unittest.main()