Files
politics-tracking/backend/politrack/sources/parlament/speeches.py
T
simonandClaude Opus 5.5 95355305d4 speeches: end XXIV-XXVII speeches at the next RU_ anchor or the chair
Protocols of these periods mark speeches with RU_ anchors only, so no heading was found and
every speech ran to the end of its session protocol (~57k documents of up to 2.8 MB;
document table 11 GB, chunks 5.6 GB, nightly dump 0.4 -> 6+ GB). Segments longer than any
real speech (200k chars) are now dropped instead of stored. parser_version 2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 12:20:10 +01:00

122 lines
6.2 KiB
Python
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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"<p\b[^>]*>.*?</p>", re.IGNORECASE | re.DOTALL)
HEADING_ANCHOR = re.compile(r'<a\s+name="T_[^"]+"', re.IGNORECASE)
# XXIV-XXVII: every speech starts with a time-stamp paragraph carrying an "RU_" anchor
SPEECH_ANCHOR = re.compile(r'<a\s+name="RU_[^"]+"', re.IGNORECASE)
# The presiding officer's interventions end a speech ("<p class=MsoNormal><b>... Präsident <a>Name</a>:</b> ...")
CHAIR = re.compile(r"^<p[^>]*>\s*<b>(?:\s*<span[^>]*>.*?</span>)?\s*(?:Pr&auml;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("<body", 1)[-1]
return {anchors[0]: html_text(body)}
# Session protocols: every speech begins with a heading paragraph - the speaker's name in bold, with "T_"
# anchors before or after it ("<a name=T_...></a><b>Abgeordneter ...</b>" or "<b>Präsident<a ...>:</b>").
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 "<b" in p[:600].lower()) or SPEECH_ANCHOR.search(p)
or CHAIR.match(p)]
out = {}
for anchor in anchors:
m = re.search(r'(?:name|id)="' + re.escape(anchor) + '"', html)
if not m:
continue
start = max((s for s in headings if s <= m.start()), default=html.rfind("<p", 0, m.start()))
end = min((s for s in headings if s > 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]:
yield Request(url=file, kind="protocol", meta={"anchors": sorted(set(anchors))})
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]},
))