PiotrSty's picture
Upload scripts/parse_zapis.py with huggingface_hub
410ae37 verified
Raw History Blame Contribute Delete
4.79 kB
"""Parser for Sejm committee 'pelny zapis przebiegu posiedzenia' PDFs."""
import re, subprocess, hashlib, unicodedata
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*$")
SPEAKER_ANCHOR = re.compile(
r"^(?:Przewodnicząc\w*|Wiceprzewodnicząc\w*|Poseł|Posłanka|poseł|posłanka|"
r"Wicemarszałek|Marszałek|Sekretarz stanu|sekretarz stanu|podsekretarz stanu|"
r"Podsekretarz stanu|minister|Minister|Wiceminister|Legislator|legislator|"
r"Protokolant|protokolant|Głos z sali|Głos z gości|Prezes|prezes|Wiceprezes|"
r"wiceprezes|p\.o\. ?\S*|dyrektor|Dyrektor|wicedyrektor|Wicedyrektor|"
r"Przedstawiciel\w*|przedstawiciel\w*|Sprawozdawca|sprawozdawca|Komendant|"
r"komendant|Naczelnik|naczelnik|Rzecznik|rzecznik|Prokurator|Sędzia|Doradca|"
r"doradca|Ekspert|ekspert|Mecenas|gen\.|nadinsp\.|insp\.|st\. bryg\.|płk|ppłk|"
r"Pełnomocnik|pełnomocnik|Szef|szef|Wojskowy|Pracownik|pracownik|Profesor|"
r"prof\.|Komisarz|komisarz)\b"
)
def is_speaker_line(content: str) -> bool:
c = content.strip()
if not (3 <= len(c) <= 120):
return False
if re.search(r"https?://|www\.|druk nr|\barts?\b", c, re.I):
return False
# wrapped preamble fragments: lowercase start with commas ("... poseł X (KO), przewodniczącej ..., rozpatrzyła")
if c[0].islower() and ("," in c or " rozpatrz" in c or "uznała" in c or "przyjęła" in c):
return False
return bool(SPEAKER_ANCHOR.match(c))
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)]."""
raw = pdf_text(path)
if "PEŁNY ZAPIS" not in raw and "pełny zapis" not in raw.lower()[:2000]:
return "other", None, []
lines = raw.splitlines()
# locate start: first speaker line
start = None
for i, ln in enumerate(lines):
s = ln.rstrip()
if not s.strip():
continue
if len(s) - len(s.lstrip()) <= 6 and s.strip().endswith(":") and is_speaker_line(s.strip()[:-1]):
start = i
break
if start is None:
return "nospeaker", None, []
preamble = []
# collect preamble (between title and first speaker), cleaned
for ln in lines[:start]:
if HEADER_PAT.match(ln) or PAGEFOOT_PAT.match(ln) or PAGENUM_PAT.match(ln) or not ln.strip():
continue
preamble.append(ln.strip())
turns = []
speaker = None
body = []
def flush():
nonlocal speaker, body
if speaker and body:
txt = dehyphenate("\n".join(body))
txt = re.sub(r"[ \t]+", " ", txt).strip()
if len(txt) >= 15:
turns.append((speaker, txt))
elif speaker and not body:
pass
speaker, body = None, []
i = start
while i < len(lines):
ln = lines[i].rstrip()
indent = len(ln) - len(ln.lstrip())
s = ln.strip()
if not s:
i += 1
continue
if HEADER_PAT.match(ln) or PAGEFOOT_PAT.match(ln) or PAGENUM_PAT.match(ln):
i += 1
continue
if indent <= 6 and s.endswith(":") and s[:-1] and is_speaker_line(s[:-1]):
flush()
speaker = s[:-1].strip()
# wrapped name continuation: next line also short, no colon, col<=6, next-next ends with ':'? skip for now
i += 1
continue
if speaker is not None:
body.append(s)
else:
# unexpected col-0 text after transcript start; treat as preamble footer noise
preamble.append(s)
i += 1
flush()
return "pelny_zapis", " ".join(preamble), turns
def doc_id(term, code, num, text):
return hashlib.sha1(f"{term}/{code}/{num}/{text}".encode()).hexdigest()[:16]
if __name__ == "__main__":
import sys, json
for p in sys.argv[1:]:
ttype, pre, turns = parse_pdf(p)
print(f"### {p}: type={ttype} turns={len(turns)} preamble_chars={len(pre or '')}")
for sp, tx in turns[:4]:
print(f" [{sp}] {tx[:140]}...")
print(f" ... last: [{turns[-1][0] if turns else '-'}]")