File size: 48,370 Bytes
8032ef4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
"""Fetch, parse and build Sejm committee full-transcript speaker turns.

Assembled from the pinned pipeline of PiotrSty/sejm-committee-transcripts @9efc4e2
(scripts/probe_sittings.py, bulk_download.py, parse_zapis.py, extract_all.py,
build_dataset.py - their function bodies are preserved) plus the canonical
DynaWord schema build. Normalization, PII redaction and the speaker allowlist live
HERE so the shard is reproducible from this script alone.

Turns: a turn starts at every label line (`split_at_labels`: a line ending with ":" whose text is a
speaker label, whoever the speaker is, also a label wrapped over two lines), after the PDF page-break
blocks (page number + stenographer initials, the title "Pełny Zapis Przebiegu Posiedzenia:", the
committee line "Komisji ... (nr N)") were cut out and a word hyphenated across one was rejoined
(`strip_page_blocks`). The pinned upstream rule (a label had to start with one of a fixed list of role
words and be indented at most 6 spaces) left every other speaker's words inside the previous turn; the
indent check is gone because the stored text has no indentation to check.

Speaker allowlist: only turns whose speaker label fully matches `SPEAKER_RULES` (MPs,
members of the government, heads of constitutional organs, Sejm/Senate staff) or is one of
the typo labels in `EXACT_LABELS` are kept; guests, experts, union/NGO/company representatives, "Głos z sali" and
every unrecognised label are dropped. The shard on the Hub was filtered with
src/clean_sejm_committee_transcripts.py (the PDF cache is not kept): it applies the same page-block
stripper and label detector to the stored turn text, so it cuts the same lines a fresh parse would.
A turn it cuts into pieces keeps its id for the first piece and gets `<id>_<k>` for the next ones, so the
ids differ from a fresh `build()`, which numbers the cut turns consecutively (`turn_idx` and the
content hash differ too); the text and the authors are the same.

Source: Kancelaria Sejmu RP, https://api.sejm.gov.pl/
(`GET /sejm/term{n}/committees/{code}/sittings/{num}/pdf`, the
"pelny zapis przebiegu posiedzenia" transcripts), terms 9 and 10.

Requirements: Python 3.10+, `pdftotext` (poppler-utils) on PATH, `tiktoken`,
`pyarrow`. Working cache: ./sejm_cache (API cache, PDFs, parsed turns).

Usage:
  python3 src/fetch_sejm_committee_transcripts.py probe 9 10
  python3 src/fetch_sejm_committee_transcripts.py download 9 10
  python3 src/fetch_sejm_committee_transcripts.py extract 9 10
  python3 src/fetch_sejm_committee_transcripts.py build
  python3 src/fetch_sejm_committee_transcripts.py all 9 10
"""
import concurrent.futures as cf
import hashlib
import json
import pathlib
import re
import subprocess
import sys
import unicodedata
import urllib.error
import urllib.request

BASE = "https://api.sejm.gov.pl/sejm"
CACHE = pathlib.Path("sejm_cache")
SOURCE = "sejm_committee_transcripts"
ADDED = "2026-09-18"
LICENSE = "public-domain (official documents)"
FIELDS = ["id", "text", "source", "added", "created", "token_count", "license", "author"]
# The attribution sidecar line of a row: these keys of the parsed turn, plus the row id.
ATTRIBUTION_KEYS = ("term", "committee_code", "committee_name", "sitting_num", "date", "turn_idx", "speaker",
                    "content_sha1", "source_url")
MIN_TURN_CHARS = 15

# ---------------------------------------------------------------- parse_zapis
HEADER_PAT = re.compile(
    r"^\s*(X{0,2}I?X kadencja|KANCELARIA SEJMU|Biuro Komisji Sejmowych|"
    r"PEŁNY ZAPIS PRZEBIEGU POSIEDZENIA|Pełny zapis przebiegu posiedzenia|¢.*)\s*$"
)
PAGEFOOT_PAT = re.compile(r"^\s*[a-z]{1,3}\.?\s+\d{1,4}\s*$")
PAGENUM_PAT = re.compile(r"^\s*\d{1,4}\s*$")

def dehyphenate(text: str) -> str:
    # soft hyphenation join: "Kon-\nrada" -> "Konrada"
    return re.sub(r"([a-ząćęłńóśźż])-\s*\n\s*([a-ząćęłńóśźż])", r"\1\2", text)


def pdf_text(path: str) -> str:
    r = subprocess.run(
        ["pdftotext", "-layout", "-enc", "UTF-8", path, "-"],
        capture_output=True, text=True, encoding="utf-8", errors="replace", check=True)
    return r.stdout


def parse_pdf(path: str):
    """Return (transcript_type, header_text, turns) where turns = [(speaker, text)].

    Turns start at every label line (`split_at_labels`), whoever the speaker is; the allowlist is
    applied later. Page-break blocks are cut out first (`strip_page_blocks`)."""
    raw = pdf_text(path)
    if "PEŁNY ZAPIS" not in raw and "pełny zapis" not in raw.lower()[:2000]:
        return "other", None, []
    lines = [s for s in (ln.strip() for ln in raw.splitlines())
             if s and not (HEADER_PAT.match(s) or PAGEFOOT_PAT.match(s) or PAGENUM_PAT.match(s))]
    pieces = split_at_labels(strip_page_blocks(lines)[0])
    if len(pieces) == 1:
        return "nospeaker", None, []
    turns = []
    for label, body in pieces[1:]:
        text = turn_text(body)
        if len(text) >= MIN_TURN_CHARS:
            turns.append((label, text))
    return "pelny_zapis", " ".join(pieces[0][1]), turns


def doc_id(term, code, num, text):
    return hashlib.sha1(f"{term}/{code}/{num}/{text}".encode()).hexdigest()[:16]


def row_id(r):
    return f"{SOURCE}_{r['term']}_{r['committee_code']}_{r['sitting_num']}_{r['turn_idx']}"


def dedup_turns(rows):
    """Sitting-level joint-sitting dedup (term + content sha1) and adjacent exact-turn dedup.

    Joint sittings of two or more committees appear in each committee's sittings
    list; identical content (per-sitting sha1) is kept once.
    """
    sittings = {}
    for r in rows:
        sittings.setdefault((r["term"], r["committee_code"], r["sitting_num"]), []).append(r)
    keep, seen_keys, dropped = [], set(), 0
    for key in sorted(sittings):
        group = sittings[key]
        content_key = (group[0]["term"], group[0]["content_sha1"])
        if content_key in seen_keys:
            dropped += len(group)
            continue
        seen_keys.add(content_key)
        keep.extend(sorted(group, key=lambda r: r["turn_idx"]))
    final, exact_dup, prev = [], 0, None
    for r in keep:
        if prev and prev["term"] == r["term"] and prev["committee_code"] == r["committee_code"] \
           and prev["sitting_num"] == r["sitting_num"] and prev["speaker"] == r["speaker"] and prev["text"] == r["text"]:
            exact_dup += 1
            continue
        final.append(r)
        prev = r
    return final, dropped, exact_dup


# ------------------------------------------------------------------ speaker allowlist
# Legal basis is the official-documents exclusion (Polish copyright act art. 4 pkt 2). It
# covers statements made in office by MPs, senators, members of the government, heads of
# constitutional organs and Sejm/Senate staff. Guests, experts, union/NGO/company
# representatives and the anonymous "Głos z sali" are not covered, so their turns are
# dropped. The allowlist is fail-closed: a turn is kept only if its raw `speaker` label
# matches one rule below IN FULL (name tail included) or is one of the typo labels in
# EXACT_LABELS; every other label is dropped, including any label this code has never seen.
# Rule ids are persisted in the stats and in data/<SOURCE>/<SOURCE>.speaker-roles.csv, so keep
# them stable.
_UP = "A-ZĄĆĘŁŃÓŚŹŻ"
_LO = "a-ząćęłńóśźżéüöäèç"
_TOK = rf"[{_UP}][{_LO}'’.]+(?:(?: ?[-–]){{1,2}} ?[{_UP}][{_LO}'’]+)*"  # Kowalski, Kowalska-Nowak, Kowalska – Nowak, O'Neill, "Kowalska- -Nowak"
_NAME = rf"{_TOK}(?: (?:(?:[Vv]el|de|von|van) )?{_TOK}){{1,2}}"  # 2-3 tokens, optional particle
_TAIL = r"(?: (?:prof\.|dr|hab\.|inż\.|mgr))*(?: " + _NAME + ")?"  # titles + optional name
# Party tag after a name: "(PiS)", glued "Kowalski(PiS)", "Kowalski, (KP)", and the typos "((PSL-TD)", "(PSL-TD".
_PARTY = r"[ ,.]{0,3}(?:\(\(?[^()\n]{1,60}\)|\([^()\s]{1,30})"
# "Poseł Jan Kowalski (PiS)", surname-only "Poseł Kowalski (PiS)"; without a party only when the label
# says the MP is outside the committee ("Poseł Jan Kowalski – spoza składu Komisji", party may follow).
# A party tag may be followed by a note on whom the MP speaks for. The label must name the MP: a bare
# "Poseł" or "Poseł (PiS)" never matches.
_SPOZA = r" ?[–−-] ?(?:poseł )?spoza sk[łl]ad(?:u|ów) (?:[Kk]omisji|podkomisji)"
_NOTE = r"(?:" + _SPOZA + r"|(?: ?[–−-] ?przedstawiciel Komisji| reprezentując[ayą]) [^()\n]{1,80})"
_MP = (rf"(?:[Pp]oseł|[Pp]osłanka)(?: wnioskodawc[aęy])? "
       rf"(?:{_NAME}(?:{_PARTY}(?:{_NOTE})?|{_SPOZA}(?:{_PARTY})?)|{_TOK}{_PARTY}(?:{_NOTE})?)")
# "Podkomisji", with the topic some subcommittees carry: "Podkomisji d.s. Ponownego Zbadania Wypadku Lotniczego".
_SUBCOMMITTEE = rf"[Pp]odkomisji(?: (?:d\.s\.|ds\.|do [Ss]praw)(?: [{_UP}{_LO}-]+){{1,10}})?"
_CHAIR_DEPUTY = r"(?:(?:[Pp]ierwsz[ya]|[Dd]rug[ia]) )?[Zz]astęp(?:ca|czyni) przewodnicząc(?:ego|ej)"
_SEJM_BUREAU = (r"(?:BAS|Bas|BEOS|Beos|Biur\w+ Analiz Sejmowych"
                r"|Biur\w+ Ekspertyz(?: (?i:i))? Ocen(?:y)? Skutków Regulacji)(?: (?:w )?Kancelarii Sejmu(?: RP)?)?")
# Other units of the Kancelaria Sejmu whose directors are Sejm staff; "KS" is the label's own short form of
# "Kancelarii Sejmu" ("Dyrektor BOM KS", "Dyrektor biura KS"), BKSP the Biuro Komunikacji Społecznej.
_SEJM_OFFICE = (rf"(?:{_SEJM_BUREAU}|Biur\w+ Legislacy\w+|Biur\w+ Komisji Sejmowych|Biur\w+ Obsługi Posłów|Bibliotek\w+ Sejmow\w+|BKSP"
                r"|[\w -]+ Kancelarii (?:Sejmu|Senatu)|(?:[Bb]iura(?: [\w-]+)?|B[A-ZŁ]{1,3}) KS)")
_BL = r"(?:BL|Biur\w+ Legislacy\w+)(?: (?:w )?Kancelarii Sejmu)?"  # Biuro Legislacyjne ("Legislacyjego" typo too)
_MINISTRY_WORDS = "|".join(r"ds\." if w == "ds." else w for w in (
    "rolnictwa rozwoju przedsiębiorczości wsi klimatu środowiska zdrowia sportu turystyki edukacji narodowej narodowego nauki "
    "szkolnictwa wyższego kultury dziedzictwa spraw wewnętrznych administracji sprawiedliwości "
    "zagranicznych cyfryzacji technologii polityki senioralnej gospodarki morskiej żeglugi "
    "śródlądowej przemysłu funduszy regionalnej rodziny pracy społecznej finansów infrastruktury "
    "obrony energii aktywów państwowych równości Unii Europejskiej europejskich UE ds. do i w z "
    "KPRM Kancelarii Prezesa Rady Ministrów RM członek szef koordynator służb specjalnych "
    "prokurator generalny przewodniczący Komitetu Stałego").split())
_MINISTRY_ABBREVIATION = r"\bM[A-ZŚŻŁ][A-Za-zŚŻŁśżł]{0,6}\b"
_STATE_SECRETARY_WORDS = _MINISTRY_WORDS + "|" + "|".join(
    "we Ministerstwie Ministerstwa Ministerstwo zastępca szefa pełnomocnik rządu główny generalny generalna "
    "konserwator geolog kraju przyrody inspektor informacji finansowej zabytków leśnictwa łowiectwa osób "
    "niepełnosprawnych wsi CPK KAS dla RP spraw".split())
# What a state secretary may hold besides the post ("pełnomocnik rządu do spraw równego traktowania",
# "szef Krajowej Administracji Skarbowej"): an office noun, then letters-only words (no digits, so
# "w latach 2015–2018" never passes), then the name. The same offices may stand BEFORE the rank
# ("Pełnomocnik rządu ds. X, sekretarz stanu w MP NAME", "Zastępca szefa KPRM podsekretarz stanu NAME");
# there only the government offices, not "przewodniczący"/"sekretarz", open the label.
_OFFICE_WORD = r"[^\W\d_]+(?:-[^\W\d_]+)*[.,]?"
_OFFICE_NOUN = r"pełnomocni(?:k|czka)|szef(?:owa)?|zastępc[ay]|zastępczyni|wiceprzewodnicząc[ya]|główn[yae]"
_STATE_OFFICE = (rf"[ ,–-]+(?:(?:i|oraz) )?(?i:{_OFFICE_NOUN}|przewodnicząc[ya]|sekretarz)(?: {_OFFICE_WORD}){{0,14}}")
_STATE_PREFIX = rf"(?i:{_OFFICE_NOUN})(?: {_OFFICE_WORD}){{0,14}}[ ,–-]+"
_STATE_RANK = r"(?:[Pp]od)?[Ss]ekretarza? [Ss]tanu"
_STATE_BODY = rf"(?:[ ,–-]+(?:(?i:{_STATE_SECRETARY_WORDS})|{_MINISTRY_ABBREVIATION}))*"  # "w MRiPS", "w Ministerstwie Zdrowia"
# A state secretary's label names a government body, never the President's office ("Kancelaria Prezydenta",
# KPRP, BPM stay out: 1A) and never a former post ("były podsekretarz stanu", "b. sekretarz stanu").
_GOVERNMENT_BODY = (rf"(?:{_MINISTRY_ABBREVIATION}|(?i:ministerst)|KPRM|Kancelarii Prezesa Rady Ministrów"
                    r"|Komitetu (?:do [Ss]praw|ds\.) Pożytku Publicznego)")
_NOT_STATE_SECRETARY = r"(?:Prezydent|KPRP|KP RP|BPM|(?i:\bbył|ówczesn|dawn)|\bb\.)"
_CONSTITUTIONAL_HEAD = "|".join([
    r"Prezes (?:NIK|Najwyższej Izby Kontroli)",
    r"Prezes (?:NBP|Narodowego Banku Polskiego)",
    r"Prezes (?:TK|Trybunału Konstytucyjnego)",
    r"Prezes (?:NSA|Naczelnego Sądu Administracyjnego)",
    r"Pierwszy Prezes (?:SN|Sądu Najwyższego)",
    r"Rzecznik [Pp]raw [Oo]bywatelskich",
    r"Rzecznik [Pp]raw [Dd]ziecka",
    r"Przewodnicząc(?:y|a) (?:KRRiT|Krajowej Rady Radiofonii i Telewizji)",
    r"Przewodnicząc(?:y|a) (?:KRS|Krajowej Rady Sądownictwa)",
    r"Prokurator Generalny",
])

# Standing committees of the Sejm (terms 9 and 10, as in the `committee_name` column) after "Komisji", i.e. in
# the genitive: "Komisja Regulaminowa, ..." is "Komisji Regulaminowej, ...". Extraordinary and investigative
# committees are not listed: no secretary of one is labelled in the data.
_SEJM_COMMITTEES = "|".join(re.escape(name) for name in (
    "Administracji i Spraw Wewnętrznych", "Cyfryzacji, Innowacyjności i Nowoczesnych Technologii",
    "do Spraw Deregulacji", "do Spraw Dzieci i Młodzieży", "do Spraw Energii, Klimatu i Aktywów Państwowych",
    "do Spraw Kontroli Państwowej", "do Spraw Petycji", "do Spraw Unii Europejskiej",
    "Edukacji i Nauki", "Edukacji, Nauki i Młodzieży", "Etyki Poselskiej", "Finansów Publicznych",
    "Gospodarki i Rozwoju", "Gospodarki Morskiej i Żeglugi Śródlądowej", "Infrastruktury",
    "Kultury Fizycznej, Sportu i Turystyki", "Kultury i Środków Przekazu",
    "Kultury, Dziedzictwa Narodowego i Środków Przekazu", "Łączności z Polakami za Granicą",
    "Mniejszości Narodowych i Etnicznych", "Obrony Narodowej", "Ochrony Środowiska, Zasobów Naturalnych i Leśnictwa",
    "Odpowiedzialności Konstytucyjnej", "Polityki Senioralnej", "Polityki Społecznej i Rodziny",
    "Regulaminowej, Spraw Poselskich i Immunitetowych", "Rolnictwa i Rozwoju Wsi",
    "Samorządu Terytorialnego i Polityki Regionalnej", "Spraw Zagranicznych", "Sprawiedliwości i Praw Człowieka",
    "Ustawodawczej", "Zdrowia"))

# (rule id, pattern matched with fullmatch). First match wins.
SPEAKER_RULES = [
    ("mp", re.compile(_MP)),
    # "Przewodniczący poseł NAME (PARTY)" (the party may be missing), the older order
    # "Poseł przewodniczący NAME (PARTY)", and "Przewodnicząca NAME (PARTY)", where the party tag stands
    # in for the missing "poseł". A "Przewodniczący NAME" without a party tag never matches.
    # A subcommittee's chair or deputy chair ("Przewodniczący Podkomisji d.s. X poseł NAME (PARTY)",
    # "Pierwszy zastępca przewodniczącego Podkomisji poseł NAME") only with "poseł"/"posłanka" ahead of the name: a
    # subcommittee can be a ministry's, with members who are no MPs.
    # ponytail: any 2-3 capitalised words before the party tag count as the name; tighten if an
    # "Przewodniczący Rady Miasta (PO)"-type label ever shows up (the 2026-10 data has none).
    ("mp_committee_chair", re.compile(
        rf"(?:Wice)?[Pp]rzewodnicząc[ya](?: {_SUBCOMMITTEE})? (?:{_MP}|(?:poseł|posłanka) {_NAME})"
        rf"|{_CHAIR_DEPUTY} {_SUBCOMMITTEE} (?:{_MP}|(?:poseł|posłanka) {_NAME})"
        rf"|(?:[Pp]oseł|[Pp]osłanka) (?:wice)?przewodnicząc[yą] {_NAME}{_PARTY}"
        rf"|Przewodnicząc[ya] {_NAME}{_PARTY}")),
    ("senator", re.compile(rf"(?:Senator|Senatorka)(?: RP)? {_NAME}(?:{_PARTY})?")),
    ("sejm_senate_marshal", re.compile(
        rf"(?:Wicemarszałkini|(?:Wice)?[Mm]arszałek) (?:Sejmu|Senatu)(?: (?:RP|Rzeczypospolitej Polskiej))?(?:,? poseł)?{_TAIL}(?:{_PARTY})?")),
    # "Ministra" is the feminine title; "Szef KPRM" is a minister-member of the Council of Ministers;
    # "Członek Rady Ministrów" is a member by definition. "Minister pełnomocny" (an ambassador) never matches.
    ("government_member", re.compile(
        rf"(?:Wice)?[Pp]rezes (?:Rady Ministrów|RM)(?:, minister(?:[ ,]+[{_LO}]+)+)?{_TAIL}"
        rf"|Minist(?:er|ra)(?:[ ,–-]+(?i:{_MINISTRY_WORDS}))*{_TAIL}"
        rf"|Szef (?:KPRM|Kancelarii Prezesa Rady Ministrów){_TAIL}"
        rf"|Członek Rady Ministrów(?:[ ,]+(?:minister )?(?:ds\.|do spraw)(?: [{_LO}]+){{1,3}})?{_TAIL}")),
    # Secretaries/undersecretaries of state in a ministry or the PM's chancellery, the rank in any
    # position: first ("Sekretarz stanu w MZ NAME"), after the government offices they hold ("Pełnomocnik
    # rządu do spraw X, sekretarz stanu w MRiPS NAME", "Zastępca szefa KPRM podsekretarz stanu NAME") or
    # after the name ("Anna Radwan-Röhrenschef podsekretarz stanu w Ministerstwie Spraw Zagranicznych").
    # Between the rank and the name only ministry words, ministry abbreviations (MF, MSWiA) and the
    # government offices they hold ("główny konserwator zabytków") are allowed; a surname alone is
    # enough after the body ("w MSiT Gut-Mostowy"). The label must name a government body and no
    # presidential-office marker (KPRP etc.). Prose that merely contains the rank ("Witam panią X,
    # sekretarz stanu w ...") starts with neither an office noun nor a name, so it never matches.
    ("state_secretary", re.compile(
        rf"(?!.*{_NOT_STATE_SECRETARY})(?=.*{_GOVERNMENT_BODY})"
        rf"(?:(?:{_STATE_PREFIX})?{_STATE_RANK}{_STATE_BODY}(?:{_STATE_OFFICE} {_NAME}|{_TAIL}| {_TOK})"
        rf"|{_NAME} {_STATE_RANK}{_STATE_BODY})")),
    ("constitutional_organ_head", re.compile(rf"(?:{_CONSTITUTIONAL_HEAD}){_TAIL}")),
    # Plain "Legislator NAME" is the transcripts' own form for the Biuro Legislacyjne of the
    # Kancelaria Sejmu (the same names carry an explicit BL affiliation elsewhere). Legislators
    # of clubs, ministries and other bodies always carry their affiliation, so they never match.
    # Also "Legislator sejmowy", "Legislator z Kancelarii Sejmu" and the name-first order
    # "Legislator NAME z Biura Legislacyjnego".
    ("sejm_legislator", re.compile(
        rf"Legislator(?:ka)? (?:(?:[zZw] )?{_BL}{_TAIL}|(?:sejmowy|[zZ] Kancelarii Sejmu){_TAIL}|{_NAME}(?: [zZw] {_BL})?)")),
    # BAS/BEOS staff: experts and specialists (optionally "ds. <topic>"), heads of a BAS division
    # ("Naczelnik wydziału w BAS") and the committee-secretariat staff of BAS. An "Ekspert zewnętrzny"
    # (commissioned from outside) is not staff and never matches.
    ("sejm_bureau_expert", re.compile(
        rf"(?:Ekspert(?:ka)?|(?:Główny )?[Ss]pecjalist(?:a|ka))(?: (?:[zw] )?(?i:ds\.|do spraw)(?: [{_UP}{_LO}-]+){{1,6}})?(?: [zw])? "
        + _SEJM_BUREAU + _TAIL
        + rf"|Naczelnik [Ww]ydziału(?: (?:[{_UP}][{_LO}]+(?:-[{_UP}][{_LO}]+)?|[iwz])){{0,7}} {_SEJM_BUREAU}{_TAIL}"
        + rf"|Pracownic[ay] sekretariatu Komisji w {_SEJM_BUREAU}{_TAIL}")),
    # Heads of Kancelaria Sejmu/Senatu units: the Chancellery, BAS/BEOS, Biuro Legislacyjne, Biuro
    # Komisji Sejmowych, the Sejm Library, the Marshal's cabinet and the Marshal's Guard (whose "Ekspert"
    # is Sejm staff too, so it sits in this rule: rule ids stay stable).
    # The deputy chief ("Zastępca szefa Kancelarii Sejmu") and the chief in the feminine are included.
    ("sejm_senate_office_head", re.compile(
        r"(?:(?:Zastępca [Ss]zefa|Szef(?:owa)?) (?:Kancelarii (?:Sejmu|Senatu)(?: RP| Rzeczypospolitej Polskiej)?|KS)"
        rf"|(?:(?:Wice)?[Dd]yrektor|P\.o\. dyrektora) {_SEJM_OFFICE}"
        r"|Dyrektor generalny kierujący [Gg]abinetem [Mm]arszałka Sejmu(?: RP)?"
        rf"|(?:Komendant|Ekspert) Straży Marszałkowskiej){_TAIL}")),
    # Secretaries of Sejm committees are Sejm staff (Biuro Komisji Sejmowych): "Sekretarz Komisji FIRST
    # LAST", the same with the name of a Sejm committee ahead of the name ("Sekretarz Komisji Zdrowia
    # NAME"), "Sekretarz Komisji z Biura Spraw Międzynarodowych NAME" and "Starszy sekretarz". The name
    # is always two tokens: a secretary of a works council or of a joint commission carries more words
    # ("Komisji Wspólnej Rządu i Samorządu Terytorialnego"), and the adjective forms below ("Komisji
    # Zakładowej NSZZ ...") are excluded explicitly. A committee name the list does not know is dropped.
    ("sejm_committee_secretary", re.compile(
        rf"(?:Starszy sekretarz|Sekretarz) Komisji (?:(?!(?:Zakładowej|Międzyzakładowej|Wspólnej|Krajowej|Regionalnej|Rewizyjnej|Okręgowej) ){_TOK} {_TOK}"
        rf"|(?:{_SEJM_COMMITTEES}|z Biura (?:Spraw Międzynarodowych|Komisji Sejmowych)) {_TOK} {_TOK})")),
]

# Labels that are official speakers beyond doubt but that no rule above can take without also taking
# look-alikes. Each is a transcript typo or a bare name-plus-party form, matched in full and in NFC, mapped to
# the rule it belongs to:
#  - a misspelt MP name ("Szynkowski vel sęk", "TchórzePwski", glued "TomaszLatos"), the party tag is there;
#  - a stray "z" after "Legislator" (a rule for it would also take "Legislator z Ministerstwa Zdrowia");
#  - a club tag "(KO)" on a Biuro Legislacyjne legislator (her label "Legislator Katarzyna Abramowicz
#    z Biura Legislacyjnego" shows the affiliation; a rule for "Legislator NAME (PARTY)" would also take
#    club legislators).
# Keep this short: a new label belongs here only after it is checked against the same person's other labels.
EXACT_LABELS = {
    "Poseł Szymon Szynkowski vel sęk (PiS)": "mp",
    "Przewodniczący poseł Krzysztof TchórzePwski (PiS)": "mp_committee_chair",
    "Przewodniczący poseł TomaszLatos (PiS)": "mp_committee_chair",
    "Legislator z Jarosław Lichocki": "sejm_legislator",
    "Legislator z Konrad Nietrzebka": "sejm_legislator",
    "Legislator Katarzyna Abramowicz (KO)": "sejm_legislator",
    # MPs labelled by name and party tag only (no "Poseł"), and chair labels with a typo in "Przewodniczący"
    "Kamila Gasiuk-Pihowicz (KO)": "mp",
    "Ryszard Terlecki (PiS)": "mp",
    "Agnieszka Maria Kłopotek (PSL=TD)": "mp",
    "zrzewodniczący poseł Tomasz Ławniczak (PiS)": "mp_committee_chair",
    "Pewodniczący poseł Piotr Babinetz (PiS)": "mp_committee_chair",
    # Antoni Macierewicz (an MP) as chair of the MON subcommittee on the Smolensk crash, labelled without "poseł"
    # (the rule needs it: the subcommittee is a ministry's, its deputy chair Kazimierz Nowaczyk is no MP)
    "Przewodniczący podkomisji Antoni Macierewicz": "mp_committee_chair",
    "Przewodniczący Podkomisji ds. ponownego zbadania wypadku lotniczego Antoni Macierewicz": "mp_committee_chair",
    "PodPodsekretarz stanu w MKiDN Marek Krawczyk": "state_secretary",  # typo in "Podsekretarz"
}


def classify_speaker(label):
    """Rule id of the first allowlist rule that fully matches `label`, else None (dropped).

    The label is matched in NFC: two shipped labels carry a decomposed "ó" (o + U+0301).
    """
    label = unicodedata.normalize("NFC", label)
    if label in EXACT_LABELS:
        return EXACT_LABELS[label]
    for rule_id, pattern in SPEAKER_RULES:
        if pattern.fullmatch(label):
            return rule_id
    return None


# ------------------------------------------------------------------ label lines and page blocks
# ONE label detector and ONE page-block stripper, used by parse_pdf() (a fresh PDF) and by
# clean_sejm_committee_transcripts.py (stored turn text), so both cut turns at the same lines.
#
# Label line: a line that ends with ":" and whose text before it is a speaker label, that is
# (optional role/title words) + a personal name (+ optional party/note in brackets, an organisation
# in quotes, a title suffix such as "prof. ucz."), or one of the unnamed forms "Głos z sali",
# "Świadek nr 3", "Tłumacz". A label is also whatever classify_speaker() accepts. Anything else ending
# with ":" is prose and stays in the text: "Proponuję brzmienie:", "Pełny Zapis Przebiegu
# Posiedzenia:", "Ja zacytuję pana ministra Jana Kowalskiego:".
# The detector is deliberately generous (a wrongly cut sentence only splits one turn and the
# piece is dropped, while a missed label leaves a guest's words inside an official's turn).
# Known misses (measured on a seeded sample, see the commit message): a label that follows prose on the
# same line ("... odwołuje Poseł Paweł Jabłoński (PiS):") and a label wrapped over three lines stay in
# the previous text. Known false positives: prose that ends in capitalised words before a colon.
LABEL_MIN, LABEL_MAX = 3, 300  # the longest labels in the data (a candidate for an ambassador) are about 260
MAX_LABEL_TOKENS = 40
_ABBREV = {
    "prof", "dr", "hab", "inż", "mgr", "ds", "im", "ul", "rez", "nadinsp", "insp", "bryg", "gen", "płk", "ppłk",
    "mjr", "kpt", "por", "st", "mł", "podinsp", "nadkom", "kom", "asp", "sierż", "doc", "lek", "med", "ks", "sp",
    "z", "o", "oo", "nr", "p", "r", "tzw", "pk", "kg", "adm", "cdr", "ppor", "ltn", "sztab", "dyw", "pil", "dypl",
    "wz", "zw", "red", "arch", "jr", "sr", "n", "m", "al", "pl", "os", "woj", "pow", "gm", "min", "wicemin",
    "pełn", "zast", "kier", "dyr", "ob", "prez", "mec", "adw",
}
_NAME_PARTICLES = {"vel", "de", "von", "van", "di", "da", "del", "della", "du", "le", "la", "ter", "ten", "der",
                   "den", "al", "el", "bin", "ibn", "ben", "dos", "das", "do", "y", "ap", "i"}  # "Jordi Salvador i Duch"
# a lone surname is a name only right after one of these ("Poseł Kowalski", "pan Kowalski")
_HONORIFICS = {
    "pan", "pani", "panie", "panu", "poseł", "posłanka", "posła", "minister", "ministrze", "ks", "ksiądz", "dr",
    "prof", "hab", "gen", "płk", "ppłk", "mjr", "kpt", "por", "insp", "nadinsp", "adm", "bryg", "sierż", "mł",
    "rez", "mgr", "inż", "senator", "marszałek", "prezes", "burmistrz", "wójt", "starosta", "ambasador", "radca",
    "mecenas", "sędzia", "profesor", "doktor",
}
_PROSE_WORDS = {"ja", "Ja", "my", "My", "że", "się", "nie", "jest", "są", "to"}  # never inside a label
_UNNAMED_LABEL = re.compile(
    r"[Gg][łl]os(?:y)? (?:z|za|poza|ze|spoza|zza|w) \S+(?: \S+){0,3}"
    r"|Świadek(?: nr)? \d+|Statysta [A-Z.]+|Tłumacz(?:ka)?|Protokolant(?:ka)?")
_BRACKETS = re.compile(r"\s*\([^()]{0,60}\)")
_QUOTED = re.compile(r"\s*„[^”]{0,100}”")  # an organisation named in a label: Inicjatorka akcji „Hejt nie jest OK” Ewa Abart
_TITLE_SUFFIX = re.compile(r"\s+prof\.(?:\s+[^\W\d_]{1,6}\.?)?$")  # "dr hab. Jan Kowalski prof. ucz."
_INITIALS = re.compile(r"(?:[^\W\d_]\.){2,3}")  # "M.B."
_TERMINAL = ".?!:;…"


def _name_part(part):
    """One hyphen-free part of a name: Kowalski, O'Neill, Coşkun, "P." (an initial), "M.B."."""
    part = part.strip("„”\"'")
    if _INITIALS.fullmatch(part):
        return True
    letters = [c for c in part if c.isalpha()]
    if not letters or not letters[0].isupper():
        return False
    if len(letters) == 1:
        return part.rstrip(".") == letters[0]
    return any(c.islower() for c in letters) and not any(c.isdigit() for c in part)


def _name_token(token):
    parts = [p for p in re.split(r"[-–]", token) if p] or [""]
    return _name_part(parts[0]) and all(_name_part(p) or p.islower() for p in parts[1:])  # "Sowiń-ski"


def _name_tail(tokens):
    """(name weight, index of its first token) of the personal name closing `tokens`; "M.B." weighs 2."""
    i, weight = len(tokens), 0
    while i > 0 and weight < 3:
        token = tokens[i - 1]
        if _name_token(token) and not (token.rstrip(".").lower() in _ABBREV and token.endswith(".") and len(token) > 2):
            i -= 1
            weight += 2 if _INITIALS.fullmatch(token) else 1
        elif token.lower() in _NAME_PARTICLES and weight and i > 1 and _name_token(tokens[i - 2]):
            i -= 1
        else:
            break
    return weight, i


def _structural_label(body):
    """Role/title words + a personal name (+ bracketed party or note); `body` is the line without its colon."""
    if _UNNAMED_LABEL.fullmatch(body):
        return True
    if re.search(r"[?;]|https?://", body):
        return False
    core = _QUOTED.sub(" ", body)
    while "(" in core and _BRACKETS.search(core):
        core = _BRACKETS.sub("", core, count=1)
    core = _TITLE_SUFFIX.sub("", core.strip(" ,"))
    if "(" in core or ")" in core or re.search(r"\bdruk\b", core):
        return False
    tokens = core.split()
    if not tokens or len(tokens) > MAX_LABEL_TOKENS or any(t in _PROSE_WORDS for t in tokens):
        return False
    head = core.split(",")[0].split()  # "Pan Imię Nazwisko, rola ..."
    if head[0] in ("Pan", "Pani") and len(head) >= 3 and "," in core and all(_name_token(t) for t in head[1:]):
        return True
    weight, start = _name_tail(tokens)
    if weight >= 2:
        return True
    return weight == 1 and start > 0 and tokens[start - 1].rstrip(".").lower() in _HONORIFICS


def is_label(body):
    """True if `body` (a line without its closing colon) is a speaker label."""
    body = unicodedata.normalize("NFC", body.strip())
    if _TITLE.search(body):  # the page-block title is capitalised words like a name: never a label
        return False
    return LABEL_MIN <= len(body) <= LABEL_MAX and (classify_speaker(body) is not None or _structural_label(body))


def split_at_labels(lines):
    """[(label or None, [lines])]; the first piece (label None) is whatever precedes the first label.

    A label wrapped over two lines is one label: the line before the colon line has no closing
    punctuation and the two joined are a label too (unless the colon line alone is an allowlisted label).
    """
    pieces = [(None, [])]
    for line in lines:
        line = line.strip()
        if not line:
            continue
        label = None
        if line.endswith(":"):
            body = line[:-1].rstrip()
            previous = pieces[-1][1][-1] if pieces[-1][1] else None
            joined = None
            if previous is not None and previous[-1] not in _TERMINAL:
                # a double-barrelled name broken at its hyphen is written "Karpiel-" / "-Semberecka"
                joined = previous[:-1] + body if previous[-1] == "-" and body[:1] == "-" else f"{previous} {body}"
            if joined and classify_speaker(body) is None and is_label(joined):
                pieces[-1][1].pop()
                label = joined
            elif is_label(body):
                label = body
        if label is None:
            pieces[-1][1].append(line)
        else:
            pieces.append((unicodedata.normalize("NFC", label), []))
    return pieces


# Page-break block: footer (page number + stenographer initials), the title, and the committee line(s):
#   56 m.h.  /  Pełny Zapis Przebiegu Posiedzenia:  /  Komisji Finansów Publicznych (nr 12)
# Title variants: any case, "Pełny apis ...", doubled. Committee lines start with "Komisj" and end with "(nr N)".
_TITLE = re.compile(r"pe[łl]ny\s+(?:za|a)?pis\s+przebiegu\s+posiedzenia", re.I)
_INITIALS_TOKEN = r"(?:[^\W\d_][.,\\]+){1,4}[^\W\d_]?"  # "m.h." "k.k.m." "I.W.T" (not "tys." or "Dziękuję.")
_FOOTER = re.compile(rf"(?:\d{{1,4}}\s+)?(?:{_INITIALS_TOKEN}\s*){{1,6}}(?:\s+\d{{1,4}})?")
# In the pinned data pdftotext's footer was glued onto a hyphenated word ("pro-" + "b.m. 5" became "prob.m. 5").
_FUSED_FOOTER = re.compile(r"(.*?[a-ząćęłńóśźż])((?:[a-z]\.){2,3}(?:\s*,\s*(?:[a-z]\.){2,3})*)\s+\d{1,4}")
_COMMITTEE_END = re.compile(r"\((?:[Nn]r|NR)\.? ?\d+\)?\s*[,.]?\s*$")
_COMMITTEE_WINDOW = 4  # lines


def _after_title(line):
    """Text after the (possibly doubled) title, or None if `line` is not a title line.

    The colon may be missing only when the title is the whole line."""
    rest, found = line, False
    while match := _TITLE.match(rest):
        found = True
        rest = rest[match.end():].strip()
        colon = rest.startswith(":")
        rest = rest.lstrip(":").strip()
        if rest and not colon:
            return None
    return rest if found else None


def _committee_end(lines, first, first_text=None):
    """Index after the committee lines that start at `first`, or None if no "(nr N)" ends them."""
    for k in range(first, min(len(lines), first + _COMMITTEE_WINDOW)):
        if _COMMITTEE_END.search(first_text if k == first and first_text is not None else lines[k]):
            k += 1
            while k < len(lines) and lines[k].startswith("Komisj") and _COMMITTEE_END.search(lines[k]):
                k += 1
            return k
    return None


def _headless_block(lines, i, out):
    """A block without its title line: committee lines at `i` right after a footer."""
    return lines[i].startswith("Komisj") and bool(out) and _is_footer(out[-1]) and _committee_end(lines, i) is not None


def _is_footer(line):
    letters = len(re.findall(r"[^\W\d_]", line))  # two initials at least: "2020 r." is a year, "6 r.g" a footer
    return len(line) <= 30 and bool(re.search(r"\d", line)) and letters >= 2 and bool(_FOOTER.fullmatch(line))


def _is_lone_footer(line):
    """A footer on its own, with no title after it: it has to be clearly one ("12 m.c.", "r.k. 7")."""
    return _is_footer(line) and len(re.findall(r"[.,\\]", line)) >= 2


def strip_page_blocks(lines):
    """(lines without page-break blocks, counts). A word hyphenated across a block is rejoined.

    The counts are {"blocks", "rejoined" (hyphenated words), "fused" (glued footers), "lone_footers"}."""
    lines = [s for s in (line.strip() for line in lines) if s]
    out, counts, i, n = [], {"blocks": 0, "rejoined": 0, "fused": 0}, 0, len(lines)
    while i < n:
        rest = _after_title(lines[i])
        if rest is not None:  # title line (the committee text may follow on it)
            first = i if rest else i + 1
            has_committee = bool(rest) or (i + 1 < n and lines[i + 1].startswith("Komisj"))
            end = _committee_end(lines, first, rest or None) if has_committee else i + 1
            if end is None:  # no "(nr N)": drop the title and, if it stands alone, one committee line
                end = i + 1 if rest else i + 2
        elif _headless_block(lines, i, out):  # the title line is missing (dropped before this module existed)
            end = _committee_end(lines, i)
        else:
            out.append(lines[i])
            i += 1
            continue
        counts["blocks"] += 1
        glue = False
        if out and _is_footer(out[-1]):
            out.pop()
        elif out and len(out[-1]) > 12 and (fused := _FUSED_FOOTER.fullmatch(out[-1])):
            out[-1], glue = fused.group(1), True
            counts["fused"] += 1
        if out and not glue and re.search(r"[a-ząćęłńóśźż]-$", out[-1]) and end < n and lines[end][:1].islower():
            out[-1], glue = out[-1][:-1], True
            counts["rejoined"] += 1
        if glue and end < n:
            out[-1] += lines[end]
            end += 1
        i = end
    kept = [line for line in out if not _is_lone_footer(line)]  # a footer whose title was filtered out earlier
    counts["lone_footers"] = len(out) - len(kept)
    return kept, counts


def turn_text(lines):
    """Text of a turn: lines joined, soft hyphenation undone, spaces collapsed."""
    return re.sub(r"[ \t]+", " ", dehyphenate("\n".join(lines))).strip()


def count_tokens(texts):
    """cl100k_base token counts of `texts` (also used by clean_sejm_committee_transcripts.py)."""
    import tiktoken
    return [len(ids) for ids in tiktoken.get_encoding("cl100k_base").encode_ordinary_batch(texts)]


# ------------------------------------------------------------------ extract_all
EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
PESEL = re.compile(r"(?<!\d)(\d{11})(?!\d)")
NIP = re.compile(r"(?<!\d)(\d{10})(?!\d)")
REGON = re.compile(r"(?<!\d)(\d{9}|\d{14})(?!\d)")
PHONE = re.compile(r"(?i)\b(tel\.?|telefon|fax)\b[:. ]*\+?\d[\d ()-]{6,}")
IBAN = re.compile(r"\b[A-Z]{2}\d{2}[ ]?(?:[ ]?\d{4}){4,7}\b")


def pesel_ok(d: str) -> bool:
    w = [1, 3, 7, 9, 1, 3, 7, 9, 1, 3]
    s = sum(int(a) * b for a, b in zip(d[:10], w)) % 10
    return (10 - s) % 10 == int(d[10])


def nip_ok(d: str) -> bool:
    w = [6, 5, 7, 2, 3, 4, 5, 6, 7]
    s = sum(int(a) * b for a, b in zip(d[:9], w)) % 11
    return s % 10 == int(d[9])


def regon_ok(d: str) -> bool:
    if len(d) == 9:
        w = [8, 9, 2, 3, 4, 5, 6, 7]
        s = sum(int(a) * b for a, b in zip(d[:8], w)) % 11
        return s % 10 == int(d[8])
    # GUS weights for the 14-digit REGON; the 14th digit is the check digit.
    w = [2, 4, 8, 5, 0, 9, 7, 3, 6, 1, 2, 4, 8]
    s = sum(int(a) * b for a, b in zip(d[:13], w)) % 11
    return s % 10 == int(d[13])


def redact(text: str) -> tuple[str, int]:
    n = 0

    def sub(replacement):
        def repl(m):
            nonlocal n
            out = replacement if isinstance(replacement, str) else replacement(m)
            n += out != m.group(0)  # a checksum-failing PESEL/NIP/REGON comes back unchanged
            return out
        return repl

    text = EMAIL.sub(sub(lambda m: "[ADRES_EMAIL]" if "@" in m.group(0) else "[DANE_NUMERY]"), text)
    text = PESEL.sub(sub(lambda m: "[DANE_NUMERY]" if pesel_ok(m.group(1)) else m.group(0)), text)
    text = NIP.sub(sub(lambda m: "[DANE_NUMERY]" if nip_ok(m.group(1)) else m.group(0)), text)
    text = REGON.sub(sub(lambda m: "[DANE_NUMERY]" if regon_ok(m.group(1)) else m.group(0)), text)
    text = PHONE.sub(sub("[DANE_KONTAKTOWE]"), text)
    text = IBAN.sub(sub("[DANE_NUMERY]"), text)
    return text, n


def fetch_json(url, retries=3, timeout=30):
    req = urllib.request.Request(url, headers={"User-Agent": "committee-corpus/0.1"})
    last = None
    for _ in range(retries):
        try:
            with urllib.request.urlopen(req, timeout=timeout) as r:
                return json.loads(r.read())
        except Exception as e:  # noqa: BLE001 - retry any transport failure
            last = e
    raise last


def probe(terms):
    """Enumerate committees and sittings per term into sejm_cache/api."""
    api = CACHE / "api"
    api.mkdir(parents=True, exist_ok=True)
    for term in terms:
        committees = fetch_json(f"{BASE}/term{term}/committees")
        (api / f"committees_term{term}.json").write_text(
            json.dumps(committees, ensure_ascii=False), encoding="utf-8")
        total = 0
        for c in committees:
            code = c["code"]
            dest = api / f"sittings_{term}_{code}.json"
            if dest.exists():
                sittings = json.loads(dest.read_text(encoding="utf-8"))
            else:
                sittings = fetch_json(f"{BASE}/term{term}/committees/{code}/sittings")
                dest.write_text(json.dumps(sittings, ensure_ascii=False), encoding="utf-8")
            total += sum(1 for s in sittings if s.get("num"))
        print(f"term {term}: {len(committees)} committees, {total} sittings", flush=True)


def download(terms):
    """Download zapis PDFs with cache and per-term manifest."""
    pdfdir = CACHE / "pdf"
    pdfdir.mkdir(parents=True, exist_ok=True)
    api = CACHE / "api"
    for term in terms:
        tasks = []
        for f in sorted(api.glob(f"sittings_{term}_*.json")):
            code = f.stem.split("_", 2)[2]
            for s in json.loads(f.read_text(encoding="utf-8")):
                if s.get("num"):
                    tasks.append((code, s["num"]))

        def fetch(t):
            code, num = t
            dest = pdfdir / f"t{term}_{code}_{num}.pdf"
            if dest.exists() and dest.stat().st_size > 100:
                return {"code": code, "num": num, "status": "cached", "bytes": dest.stat().st_size}
            url = f"{BASE}/term{term}/committees/{code}/sittings/{num}/pdf"
            for a in range(2):
                try:
                    req = urllib.request.Request(url, headers={"User-Agent": "committee-corpus/0.1"})
                    with urllib.request.urlopen(req, timeout=60) as r:
                        data = r.read()
                    if data[:5] == b"%PDF-":
                        dest.write_bytes(data)
                        return {"code": code, "num": num, "status": "ok", "bytes": len(data)}
                    return {"code": code, "num": num, "status": "notpdf", "bytes": len(data)}
                except urllib.error.HTTPError as e:
                    return {"code": code, "num": num, "status": f"http{e.code}", "bytes": 0}
                except Exception as e:  # noqa: BLE001
                    if a == 1:
                        return {"code": code, "num": num, "status": "error", "bytes": 0, "err": repr(e)[:80]}

        manifest = api / f"dl_manifest_{term}.jsonl"
        done = set()
        if manifest.exists():
            for line in open(manifest, encoding="utf-8"):
                try:
                    r = json.loads(line)
                    if r["status"] not in ("error",):
                        done.add((r["code"], r["num"]))
                except Exception:  # noqa: BLE001
                    pass
        todo = [t for t in tasks if t not in done]
        print(f"term {term}: downloading {len(todo)} ({len(done)} already done)", flush=True)
        with open(manifest, "a", encoding="utf-8") as fh, cf.ThreadPoolExecutor(48) as ex:
            for i, fut in enumerate(cf.as_completed([ex.submit(fetch, t) for t in todo])):
                fh.write(json.dumps(fut.result()) + "\n")
                if (i + 1) % 250 == 0:
                    print(f"{i + 1}/{len(todo)}", flush=True)


def extract(terms):
    """Parse downloaded PDFs into redacted speaker turns (sejm_cache/parsed)."""
    outdir = CACHE / "parsed"
    outdir.mkdir(parents=True, exist_ok=True)
    api = CACHE / "api"
    for term in terms:
        names = {}
        for c in json.loads((api / f"committees_term{term}.json").read_text(encoding="utf-8")):
            names[c["code"]] = c.get("name") or c.get("prettyName") or c["code"]
        dates = {}
        for f in sorted(api.glob(f"sittings_{term}_*.json")):
            code = f.stem.split("_", 2)[2]
            for s in json.loads(f.read_text(encoding="utf-8")):
                if s.get("num"):
                    dates[(code, s["num"])] = s.get("date")

        jobs = []
        for line in open(api / f"dl_manifest_{term}.jsonl", encoding="utf-8"):
            r = json.loads(line)
            if r["status"] in ("ok", "cached"):
                p = CACHE / "pdf" / f"t{term}_{r['code']}_{r['num']}.pdf"
                if p.exists():
                    jobs.append((r["code"], r["num"], p))
        stats = {"pdfs": len(jobs), "type": {}, "turns": 0, "chars": 0, "pii": 0, "parse_fail": []}

        def do_parse(job):
            code, num, p = job
            try:
                return job, parse_pdf(str(p))
            except Exception as e:  # noqa: BLE001
                return job, ("__fail__", None, repr(e)[:100])

        with open(outdir / f"turns_{term}.jsonl", "w", encoding="utf-8") as fh, cf.ThreadPoolExecutor(10) as ex:
            for i, ((code, num, p), (ttype, preamble, turns)) in enumerate(ex.map(do_parse, jobs)):
                if ttype == "__fail__":
                    stats["parse_fail"].append({"code": code, "num": num, "err": turns})
                    continue
                stats["type"][ttype] = stats["type"].get(ttype, 0) + 1
                if ttype != "pelny_zapis" or not turns:
                    continue
                content = hashlib.sha1("␟".join(t for _, t in turns).encode()).hexdigest()[:16]
                for ti, (sp, tx) in enumerate(turns):
                    tx, n = redact(re.sub(r"[ \t]+", " ", tx).strip())
                    if len(tx) < MIN_TURN_CHARS:
                        continue
                    row = {
                        "term": str(term),
                        "committee_code": code,
                        "committee_name": names.get(code, code),
                        "sitting_num": num,
                        "date": dates.get((code, num)),
                        "turn_idx": ti,
                        "speaker": sp.strip(),
                        "text": tx,
                        "content_sha1": content,
                        "source_url": f"{BASE}/term{term}/committees/{code}/sittings/{num}/pdf",
                    }
                    fh.write(json.dumps(row, ensure_ascii=False) + "\n")
                    stats["turns"] += 1
                    stats["chars"] += len(tx)
                    stats["pii"] += n
                if (i + 1) % 500 == 0:
                    print(f"parsed {i + 1}/{len(jobs)}", flush=True)
        print(json.dumps(stats, ensure_ascii=False)[:600], flush=True)


# ------------------------------------------------------------------ build_dataset
def shard_stats(rows, attrs):
    """Content-derived stats of a shard (also used by clean_sejm_committee_transcripts.py).

    `rows` are the parquet rows, `attrs` the parallel attribution sidecar lines.
    """
    dates = [a["date"] for a in attrs if a["date"]]
    return {
        "kept": len(rows),
        "sittings": len({(a["term"], a["committee_code"], a["sitting_num"]) for a in attrs}),
        "committees": len({(a["term"], a["committee_code"]) for a in attrs}),
        "unique_speaker_labels": len({a["speaker"] for a in attrs}),
        "tokens": sum(r["token_count"] for r in rows),
        "characters": sum(len(r["text"]) for r in rows),
        "date_min": min(dates), "date_max": max(dates),
    }


def build(terms=(9, 10), outdir="."):
    """Dedup parsed turns and write the canonical DynaWord artifacts."""
    import pyarrow as pa
    import pyarrow.parquet as pq

    rows = []
    for term in terms:
        f = CACHE / "parsed" / f"turns_{term}.jsonl"
        if f.exists():
            rows += [json.loads(l) for l in open(f, encoding="utf-8")]

    n_raw = len(rows)
    rows, dedup_dropped, exact_dup = dedup_turns(rows)
    # Speaker allowlist (see classify_speaker). A dropped turn leaves no marker: every row is
    # one turn, so nothing else is cut and the surviving ids keep their `turn_idx` gaps.
    n_deduped = len(rows)
    rows = [r for r in rows if classify_speaker(r["speaker"])]
    not_official = n_deduped - len(rows)

    out_rows, attrs = [], []
    for r, tokens in zip(rows, count_tokens([r["text"] for r in rows])):
        rid = row_id(r)
        out_rows.append({
            "id": rid, "text": r["text"], "source": SOURCE, "added": ADDED,
            "created": r["date"] or "", "token_count": tokens,
            "license": LICENSE, "author": r["speaker"],
        })
        attrs.append({k: r[k] for k in ATTRIBUTION_KEYS} | {"id": rid})

    root = pathlib.Path(outdir) / "data" / SOURCE
    root.mkdir(parents=True, exist_ok=True)
    schema = pa.schema([(f, pa.int64() if f == "token_count" else pa.string()) for f in FIELDS])
    pq.write_table(pa.Table.from_pylist(out_rows, schema=schema),
                   root / f"{SOURCE}.parquet", compression="zstd")
    with open(root / f"{SOURCE}.attribution.jsonl", "w", encoding="utf-8") as fh:
        for a in attrs:
            fh.write(json.dumps(a, ensure_ascii=False, sort_keys=True) + "\n")

    stats = {
        "discovered_sittings": 9175, "sittings_with_pdf": 8658,
        "sittings_no_pdf_upstream": 455, "sittings_fetch_failed": 62,
        "rows_raw_extracted": n_raw,
        "rejected": dedup_dropped + exact_dup + not_official,
        "rejected_joint_sitting_dup": dedup_dropped, "rejected_exact_dup": exact_dup,
        "rejected_not_official_speaker": not_official,
        **shard_stats(out_rows, attrs), "added": ADDED,
    }
    (root / f"{SOURCE}.stats.json").write_text(
        json.dumps(stats, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8")
    print(json.dumps(stats, ensure_ascii=False, indent=1))


def main(argv):
    cmd, terms = argv[1], [int(t) for t in argv[2:]]
    if cmd == "probe":
        probe(terms)
    elif cmd == "download":
        download(terms)
    elif cmd == "extract":
        extract(terms)
    elif cmd == "build":
        build()
    elif cmd == "all":
        probe(terms)
        download(terms)
        extract(terms)
        build()
    else:
        raise SystemExit(__doc__)


if __name__ == "__main__":
    main(sys.argv)