Full texts and interjections of plenary speeches
parlament.speeches fetches the stenographic protocols that speeches link to (one file per speech since 2019, one per session before) and stores each speech's text on its evidence document, with the interjections listed in the document's meta. Speeches linked without an anchor are skipped. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0f7e003879
commit
fe418cce1f
7 files changed
+419
No files matched your search
@@ -0,0 +1,111 @@
|
||||
"""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)
|
||||
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()]
|
||||
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))
|
||||
out[anchor] = html_text(html[start:end])
|
||||
return out
|
||||
|
||||
|
||||
@register
|
||||
class SpeechTexts(Adapter):
|
||||
spec = SPEC
|
||||
name = "parlament.speeches"
|
||||
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]},
|
||||
))
|
||||
Reference in new issue
Block a user