Files
politics-tracking/backend/politrack/text.py
T
simonandClaude Opus 5.5 1395dc2840 normalize_org_name keeps a partnership marker: a GmbH & Co KG no longer matches the GmbH
'Huber GmbH & Co KG' -> 'huber kg', 'Porsche Austria GmbH & Co OG' -> 'porsche austria og' (also &CoKG, KEG,
OHG), 'Huber GmbH' -> 'huber'. Alias matching treated the partnership and its general partner (different legal
entities) as one organisation. New legal_form_class(); firmenbuch.is_partnership uses it. Existing aliases are
recomputed and the merged organisations split by a one-off script.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 18:20:42 +01:00

112 lines
4.4 KiB
Python

import hashlib
import html
import re
import unicodedata
from bs4 import BeautifulSoup
from slugify import slugify
ACADEMIC_TITLES = re.compile(
r"\b(Mag\.?(\s?\(FH\))?|Dr\.?|DI|Dipl\.-Ing\.?|Ing\.?|MMag\.?|Prof\.?|Univ\.-Prof\.?|BA|MA|BSc|MSc|MBA|LL\.?M\.?|"
r"PhD|MAS|MPA|Bakk\.?|DDr\.?|KR|Abg\.?|Mmag\.?|MEd|BEd|Dipl\.-Päd\.?)(?=\s|,|$)",
re.IGNORECASE,
)
def normalize(text: str) -> str:
"""Lowercase, strip accents, ß -> ss and collapse whitespace (matches SQL lower(unaccent()))."""
text = unicodedata.normalize("NFKD", text)
text = "".join(c for c in text if not unicodedata.combining(c))
return re.sub(r"\s+", " ", text).strip().lower().replace("ß", "ss")
def strip_titles(name: str) -> str:
name = ACADEMIC_TITLES.sub("", name)
name = re.sub(r"\s*,\s*", ", ", name)
return re.sub(r"\s+", " ", name).strip(" ,")
def make_slug(*parts: str) -> str:
return slugify(" ".join(p for p in parts if p), lowercase=True, replacements=[["ß", "ss"]])
def html_to_text(fragment: str | None) -> str:
if not fragment:
return ""
return re.sub(r"\s+", " ", BeautifulSoup(html.unescape(fragment), "html.parser").get_text(" ")).strip()
def fingerprint(*parts: object) -> str:
raw = "|".join(str(p) for p in parts)
return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:40]
LEGAL_FORMS = re.compile(
r"\b(gesellschaft\s+m\.?\s?b\.?\s?h\.?|ges\.?\s?m\.?\s?b\.?\s?h\.?|gmbh|g\.m\.b\.h\.?|aktiengesellschaft|ag|"
r"kommanditgesellschaft|kg|og|e\.?\s?u\.?|eg|e\.?\s?gen\.?|reg\.?\s?gen\.?\s?m\.?\s?b\.?\s?h\.?|se|ltd\.?|inc\.?|"
r"llc|s\.?a\.?|b\.?v\.?|n\.?v\.?|& co\.?|co\.?|und co\.?|gesmbh|mbh|kgaa|plc)\b",
re.IGNORECASE,
)
# Partnerships (KG, OG, GmbH & Co KG) are separate legal entities from the corporation of the same name, which is
# often their general partner. KEG and OHG/OEG are the pre-2007 names of KG and OG (same entity, renamed by the UGB).
PARTNERSHIP_FORMS = re.compile(
r"\b(?:(?P<kg>kommanditgesellschaft|kommandit-erwerbsgesellschaft|keg|kg|cokg)"
r"|(?P<og>offene\s+(?:handels|erwerbs)?gesellschaft|ohg|oeg|og))\b"
)
CORPORATE_FORMS = re.compile(
r"\b(gmbh|gesmbh|mbh|g\.m\.b\.h|m\.?\s?b\.?\s?h|ag|aktiengesellschaft|se|e\.?\s?gen|egen|eg|ltd|inc|llc|plc)\b"
)
def legal_form_class(name: str) -> str | None:
"""'kg' or 'og' for a partnership (also 'GmbH & Co KG'), 'corp' for a corporation (GmbH, AG, SE, eGen ...),
None when the name carries no legal form."""
text = normalize(name)
m = PARTNERSHIP_FORMS.search(text)
if m:
return "kg" if m.group("kg") else "og"
return "corp" if CORPORATE_FORMS.search(text) else None
def normalize_org_name(name: str) -> str:
"""'HYPO TIROL BANK AG' == 'Hypo Tirol Bank Aktiengesellschaft' -> 'hypo tirol bank'.
Lowercase, strip accents, quotes, punctuation and legal-form suffixes, so the same company is
recognised across sources (side-job lists, procurement notices, donation lists, ad reports).
A partnership keeps a marker: 'Huber GmbH & Co KG' -> 'huber kg', 'Maier OG' -> 'maier og', so it never
matches 'Huber GmbH' -> 'huber'.
"""
text = normalize(name)
partnership = PARTNERSHIP_FORMS.search(text)
text = re.sub(r"[\"'„“”»«]", "", text)
text = LEGAL_FORMS.sub(" ", text)
text = PARTNERSHIP_FORMS.sub(" ", text)
text = re.sub(r"[^\w\s-]", " ", text)
text = re.sub(r"\s+", " ", text).strip(" -&")
if partnership and text:
text += " kg" if partnership.group("kg") else " og"
return text
def firmenbuch_number(value: str | None) -> str | None:
"""'FN 306527 a', 'FN306527a', '306527a', '068616g' -> '306527a', '68616g' (Austrian company register number,
normalised: no leading zeros, lower-case check letter)."""
m = re.fullmatch(r"\s*(?:FN\s*)?(\d{1,6})\s?([a-zA-Z])\s*", value or "", re.IGNORECASE)
return f"{int(m.group(1))}{m.group(2).lower()}" if m and int(m.group(1)) else None
def format_eur_de(amount: object) -> str:
"""1234567.8 -> '1.234.567,80' (German number format; formats only the number, never the sentence)."""
try:
value = float(amount) # type: ignore[arg-type]
except (TypeError, ValueError):
return str(amount)
return f"{value:,.2f}".replace(",", "X").replace(".", ",").replace("X", ".")
def excerpt(text: str, limit: int = 400) -> str:
text = re.sub(r"\s+", " ", text).strip()
return text if len(text) <= limit else text[: limit - 1].rsplit(" ", 1)[0] + "…"