"""Full texts of plenary speeches from the stenographic protocols (CC BY 4.0). parlament.persons stores each speech as a `statement` whose evidence links to the protocol, usually with an anchor: newer periods publish one small HTML file per speech (`A_-_13_06_18_01035235.html#48`), older ones one large file per session in which each speech starts at a named anchor in front of the speaker's name (`fnameorig_024808.html#T_067A1930_39_20034545`). This adapter fetches those files and stores the text of each speech as the full text of its evidence document (so it becomes searchable), with the interjections and reactions ("Beifall bei ...", "Ruf: ...", "Zwischenruf ...") listed separately in the document's meta. Speeches linked without an anchor can't be told apart from the rest of the session and are skipped. """ from __future__ import annotations import re from collections import defaultdict from collections.abc import Iterator from typing import Any from bs4 import BeautifulSoup from politrack.core import Adapter, Request, Response, RunContext, register from politrack.core.records import Document, Evidence from politrack.sources.parlament.common import SPEC from politrack.text import excerpt PARAGRAPH = re.compile(r"
]*>.*?
", re.IGNORECASE | re.DOTALL) HEADING_ANCHOR = re.compile(r'... Präsident Name: ...") CHAIR = re.compile(r"^]*>\s*(?:\s*]*>.*?)?\s*(?:Präsident|Präsident)", re.IGNORECASE | re.DOTALL) MAX_SPEECH_CHARS = 200_000 # no plenary speech is longer; a longer segment means its end wasn't found INTERJECTION = re.compile(r"\(([^()]{3,800}?)\)") INTERJECTION_WORDS = re.compile(r"\b(Beifall|Ruf|Rufe|Zwischenruf|Heiterkeit|Abg\.|Abgeordnete[rn]?|Präsident|" r"Unruhe|Widerspruch|Lachen|Bravo|Pfui|Zustimmung)\b") TIMESTAMP = re.compile(r"^\d{1,2}\.\d{2}$") EDITORIAL_NOTE = "Die angezeigte Rede ist noch nicht" # "... nach § 52 Abs. 2 GOG-NR autorisiert" def html_text(fragment: str) -> str: """Readable text of an HTML fragment: paragraphs as lines, time stamps and margin numbers dropped.""" soup = BeautifulSoup(fragment, "html.parser") for el in soup.select("p.randnummer, p._RB, p.RB, style, script, title"): el.decompose() lines = [] for p in soup.find_all("p") or [soup]: text = re.sub(r"\s+", " ", p.get_text(" ")).replace("", "").strip() if text and not TIMESTAMP.match(text) and not text.startswith(EDITORIAL_NOTE): lines.append(text) text = "\n".join(lines) return re.sub(r" ([,.;:!?)])", r"\1", re.sub(r"\( ", "(", text)) def interjections(text: str) -> list[str]: """Reactions recorded in parentheses: applause, calls, interjections.""" return [m.group(1).strip(" –-") for m in INTERJECTION.finditer(text) if INTERJECTION_WORDS.search(m.group(1))] def speech_segments(html: str, anchors: list[str]) -> dict[str, str]: """Text per anchor. A file that is one speech (newer periods) belongs to its anchor as a whole; in a session protocol a speech runs from its anchor to the next speaker's start (or the next wanted anchor).""" if len(html) < 60_000 and len(anchors) == 1: body = html.split("
Abgeordneter ..." or "Präsident:"). paragraphs = [(m.start(), m.end(), m.group(0)) for m in PARAGRAPH.finditer(html)] headings = [start for start, _, p in paragraphs if (HEADING_ANCHOR.search(p) and " m.start()), default=len(html)) text = html_text(html[start:end]) if len(text) <= MAX_SPEECH_CHARS: out[anchor] = text return out @register class SpeechTexts(Adapter): spec = SPEC name = "parlament.speeches" parser_version = 2 # 2: speeches of XXIV-XXVII end at the next "RU_" speech or the chair (were whole protocols) description = "Full texts and interjections of plenary speeches (stenographic protocols)" schedule = "20 4 * * *" queue = "bulk" def start(self, ctx: RunContext) -> Iterator[Request]: if ctx.conn is None: return limit = int(ctx.params.get("max_protocols", 3000)) rows = ctx.conn.execute( """SELECT st.url FROM statement st JOIN document d ON d.url = st.url WHERE st.context = 'parliament_speech' AND st.url LIKE '%%#%%' AND d.full_text IS NULL ORDER BY st.said_at DESC NULLS LAST""" ).fetchall() by_file: dict[str, list[str]] = defaultdict(list) for row in rows: file, anchor = row["url"].split("#", 1) by_file[file].append(anchor) ctx.stats["protocols_pending"] = len(by_file) for file, anchors in list(by_file.items())[:limit]: # always parse: the anchors wanted from a file grow over time, and the archive keeps the first set only yield Request(url=file, kind="protocol", meta={"anchors": sorted(set(anchors))}, conditional=False, skip_unchanged=False) def parse(self, ctx: RunContext, response: Response) -> Iterator[Any]: anchors = response.meta["anchors"] segments = speech_segments(response.text, anchors) ctx.stats["anchors_not_found"] += len(anchors) - len(segments) for anchor, text in segments.items(): if len(text) < 40: ctx.stats["speech_too_short"] += 1 continue yield Document(Evidence( url=f"{response.request.url}#{anchor}", doc_type="protocol", source="parlament", full_text=text, excerpt=excerpt(text, 400), meta={"interjections": interjections(text)[:200]}, ))