blackthis 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,221 @@
1
+ """Robuste CSV- und Excel-Ein-/Ausgabe mit automatischer Encoding- und Trennzeichen-Erkennung."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import io
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+
11
+ @dataclass
12
+ class LoadedCSV:
13
+ """Eingelesene CSV-Daten inkl. erkannter Format-Metadaten."""
14
+
15
+ headers: list[str]
16
+ rows: list[dict[str, str]]
17
+ encoding: str
18
+ delimiter: str
19
+
20
+
21
+ CANDIDATE_ENCODINGS = ("utf-8-sig", "utf-8", "cp1252", "latin-1", "iso-8859-1")
22
+ CANDIDATE_DELIMITERS = (";", ",", "\t", "|")
23
+
24
+
25
+ def decode_csv_bytes(raw: bytes) -> tuple[str, str]:
26
+ """Erkennt das Text-Encoding zuverlässig (inkl. deutscher Umlaute & Excel UTF-8-BOM / CP1252)."""
27
+ for enc in CANDIDATE_ENCODINGS:
28
+ try:
29
+ text = raw.decode(enc)
30
+ return text, enc
31
+ except UnicodeDecodeError:
32
+ continue
33
+ return raw.decode("utf-8", errors="replace"), "utf-8"
34
+
35
+
36
+ def detect_delimiter(sample_text: str) -> str:
37
+ """Erkennt das CSV-Trennzeichen zuverlässig – auch bei mehrzeiligen Zellen in Anführungszeichen."""
38
+ # Erste Zeilen für Sniffer nehmen
39
+ sample = sample_text[:16384]
40
+ try:
41
+ dialect = csv.Sniffer().sniff(sample, delimiters="".join(CANDIDATE_DELIMITERS))
42
+ if dialect.delimiter in CANDIDATE_DELIMITERS:
43
+ return dialect.delimiter
44
+ except csv.Error:
45
+ pass
46
+
47
+ # Fallback: Header-Zeile analysieren
48
+ first_line = sample_text.splitlines()[0] if sample_text.splitlines() else ""
49
+ best_delim = ";"
50
+ best_count = -1
51
+ for delim in CANDIDATE_DELIMITERS:
52
+ cnt = first_line.count(delim)
53
+ if cnt > best_count:
54
+ best_count = cnt
55
+ best_delim = delim
56
+ return best_delim
57
+
58
+
59
+ def load_csv_bytes(raw: bytes, delimiter: str | None = None) -> LoadedCSV:
60
+ """Liest eine CSV aus Bytes inkl. mehrzeiliger Zellen verlustfrei ein."""
61
+ text, encoding = decode_csv_bytes(raw)
62
+ delim = delimiter or detect_delimiter(text)
63
+
64
+ stream = io.StringIO(text, newline="")
65
+ reader = csv.reader(stream, delimiter=delim)
66
+ all_rows = list(reader)
67
+ if not all_rows:
68
+ return LoadedCSV(headers=[], rows=[], encoding=encoding, delimiter=delim)
69
+
70
+ raw_headers = all_rows[0]
71
+ # Doppelte oder leere Header absichern
72
+ headers: list[str] = []
73
+ seen: dict[str, int] = {}
74
+ for idx, h in enumerate(raw_headers):
75
+ name = h.strip() or f"Spalte_{idx + 1}"
76
+ if name in seen:
77
+ seen[name] += 1
78
+ name = f"{name}_{seen[name]}"
79
+ else:
80
+ seen[name] = 1
81
+ headers.append(name)
82
+
83
+ dict_rows: list[dict[str, str]] = []
84
+ for raw_row in all_rows[1:]:
85
+ # Komplett leere Zeilen am Dateiende ignorieren
86
+ if not raw_row or all(not cell.strip() for cell in raw_row):
87
+ continue
88
+ row_dict: dict[str, str] = {}
89
+ for idx, h in enumerate(headers):
90
+ val = raw_row[idx] if idx < len(raw_row) else ""
91
+ # Zeilenumbrüche auf \n vereinheitlichen, damit Python- und Browser-Offsets 1:1 übereinstimmen
92
+ row_dict[h] = val.replace("\r\n", "\n").replace("\r", "\n")
93
+ dict_rows.append(row_dict)
94
+
95
+ return LoadedCSV(headers=headers, rows=dict_rows, encoding=encoding, delimiter=delim)
96
+
97
+
98
+ def load_csv_file(path: str | Path, delimiter: str | None = None) -> LoadedCSV:
99
+ """Liest eine lokale CSV- oder Excel-Datei (.xlsx) ein."""
100
+ p = Path(path)
101
+ raw = p.read_bytes()
102
+ return load_tabular_bytes(raw, filename=p.name, delimiter=delimiter)
103
+
104
+
105
+ def load_xlsx_bytes(raw: bytes) -> LoadedCSV:
106
+ """Liest das erste Tabellenblatt einer Excel-Datei (.xlsx) verlustfrei als LoadedCSV ein."""
107
+ from openpyxl import load_workbook
108
+
109
+ wb = load_workbook(io.BytesIO(raw), read_only=True, data_only=True)
110
+ ws = wb.active
111
+ raw_rows = list(ws.iter_rows(values_only=True))
112
+ wb.close()
113
+ if not raw_rows:
114
+ return LoadedCSV(headers=[], rows=[], encoding="xlsx", delimiter=";")
115
+
116
+ raw_headers = ["" if v is None else str(v) for v in raw_rows[0]]
117
+ headers: list[str] = []
118
+ seen: dict[str, int] = {}
119
+ for idx, h in enumerate(raw_headers):
120
+ name = h.strip() or f"Spalte_{idx + 1}"
121
+ if name in seen:
122
+ seen[name] += 1
123
+ name = f"{name}_{seen[name]}"
124
+ else:
125
+ seen[name] = 1
126
+ headers.append(name)
127
+
128
+ dict_rows: list[dict[str, str]] = []
129
+ for raw_row in raw_rows[1:]:
130
+ if not raw_row or all(v is None or not str(v).strip() for v in raw_row):
131
+ continue
132
+ row_dict: dict[str, str] = {}
133
+ for idx, h in enumerate(headers):
134
+ cell_v = raw_row[idx] if idx < len(raw_row) else None
135
+ val = "" if cell_v is None else str(cell_v)
136
+ row_dict[h] = val.replace("\r\n", "\n").replace("\r", "\n")
137
+ dict_rows.append(row_dict)
138
+
139
+ return LoadedCSV(headers=headers, rows=dict_rows, encoding="xlsx", delimiter=";")
140
+
141
+
142
+ def load_tabular_bytes(raw: bytes, filename: str = "", delimiter: str | None = None) -> LoadedCSV:
143
+ """Erkennt automatisch Excel (.xlsx) oder CSV und liest die Tabelle ein."""
144
+ is_xlsx = filename.lower().endswith(".xlsx") or raw[:4] == b"PK\x03\x04"
145
+ if is_xlsx:
146
+ return load_xlsx_bytes(raw)
147
+ return load_csv_bytes(raw, delimiter=delimiter)
148
+
149
+
150
+ def dump_csv_bytes(
151
+ headers: list[str],
152
+ rows: list[dict[str, str]],
153
+ delimiter: str = ";",
154
+ encoding: str = "utf-8-sig",
155
+ ) -> bytes:
156
+ """Schreibt CSV-Daten als Bytes (Standard: UTF-8 mit BOM für fehlerfreie Umlaute in Excel auf Mac)."""
157
+ buf = io.StringIO(newline="")
158
+ writer = csv.DictWriter(
159
+ buf,
160
+ fieldnames=headers,
161
+ delimiter=delimiter,
162
+ quoting=csv.QUOTE_MINIMAL,
163
+ lineterminator="\r\n",
164
+ )
165
+ writer.writeheader()
166
+ for row in rows:
167
+ writer.writerow({h: row.get(h, "") for h in headers})
168
+ return buf.getvalue().encode(encoding, errors="replace")
169
+
170
+
171
+ def write_csv_file(
172
+ path: str | Path,
173
+ headers: list[str],
174
+ rows: list[dict[str, str]],
175
+ delimiter: str = ";",
176
+ encoding: str = "utf-8-sig",
177
+ ) -> None:
178
+ """Speichert geschwärzte CSV-Daten auf Festplatte."""
179
+ data = dump_csv_bytes(headers, rows, delimiter=delimiter, encoding=encoding)
180
+ Path(path).write_bytes(data)
181
+
182
+
183
+ def dump_xlsx_bytes(headers: list[str], rows: list[dict[str, str]]) -> bytes:
184
+ """Exportiert die geschwärzte Tabelle als sauber formatierte Excel-Datei (.xlsx)."""
185
+ from openpyxl import Workbook
186
+ from openpyxl.styles import Alignment, Font, PatternFill
187
+
188
+ wb = Workbook()
189
+ ws = wb.active
190
+ ws.title = "Geschwärzte Auskunft"
191
+
192
+ header_fill = PatternFill(start_color="1E293B", end_color="1E293B", fill_type="solid")
193
+ header_font = Font(bold=True, color="FFFFFF")
194
+
195
+ ws.append(headers)
196
+ for col_idx in range(1, len(headers) + 1):
197
+ cell = ws.cell(row=1, column=col_idx)
198
+ cell.fill = header_fill
199
+ cell.font = header_font
200
+ cell.alignment = Alignment(vertical="center")
201
+
202
+ wrap_align = Alignment(wrap_text=True, vertical="top")
203
+ for row in rows:
204
+ ws.append([row.get(h, "") for h in headers])
205
+ cur_row = ws.max_row
206
+ for col_idx in range(1, len(headers) + 1):
207
+ ws.cell(row=cur_row, column=col_idx).alignment = wrap_align
208
+
209
+ # Sinnvolle Spaltenbreiten setzen
210
+ for col_idx, h in enumerate(headers, start=1):
211
+ col_letter = ws.cell(row=1, column=col_idx).column_letter
212
+ if h.strip().lower() in {"notiz", "notizen", "nachricht", "text", "kommentar", "beschreibung"}:
213
+ ws.column_dimensions[col_letter].width = 85
214
+ else:
215
+ max_len = max([len(h)] + [min(35, len(str(r.get(h, "")))) for r in rows[:200]])
216
+ ws.column_dimensions[col_letter].width = max(14, max_len + 4)
217
+
218
+ ws.freeze_panes = "A2"
219
+ out = io.BytesIO()
220
+ wb.save(out)
221
+ return out.getvalue()
@@ -0,0 +1,114 @@
1
+ """Zentrale Fassade & schneller Orchestrator für alle modularen Regel-Detektoren."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .detectors_addresses import detect_addresses_plz_housenumbers, detect_locations
6
+ from .detectors_common import has_digit, iter_lines_with_offsets
7
+ from .detectors_entities import detect_companies, detect_job_titles, detect_names
8
+ from .detectors_structured import (
9
+ detect_amounts,
10
+ detect_bank,
11
+ detect_birthdates,
12
+ detect_custom_blacklist,
13
+ detect_emails,
14
+ detect_ip_addresses,
15
+ detect_json_kv_fields,
16
+ detect_license_plates,
17
+ detect_phones,
18
+ detect_tax_ids,
19
+ detect_websites,
20
+ )
21
+ from .models import Category, RedactionConfig, SpanMatch
22
+
23
+ __all__ = [
24
+ "run_rule_detectors",
25
+ "detect_addresses_plz_housenumbers",
26
+ "detect_amounts",
27
+ "detect_bank",
28
+ "detect_birthdates",
29
+ "detect_companies",
30
+ "detect_custom_blacklist",
31
+ "detect_emails",
32
+ "detect_ip_addresses",
33
+ "detect_job_titles",
34
+ "detect_json_kv_fields",
35
+ "detect_license_plates",
36
+ "detect_locations",
37
+ "detect_names",
38
+ "detect_phones",
39
+ "detect_tax_ids",
40
+ "detect_websites",
41
+ ]
42
+
43
+
44
+ def run_rule_detectors(text: str, config: RedactionConfig) -> list[SpanMatch]:
45
+ """Führt alle aktivierten deterministischen & kontextbasierten Detektoren mit Fast-Path-Vorchecks aus."""
46
+ if not text or not text.strip():
47
+ return []
48
+
49
+ enabled = config.enabled_categories()
50
+ all_matches: list[SpanMatch] = []
51
+
52
+ # Einmalig pro Zelle berechnen und an alle Sub-Detektoren durchreichen
53
+ text_has_digit = has_digit(text)
54
+ lines_cache = iter_lines_with_offsets(text) if "\n" in text and (Category.NAME in enabled or Category.COMPANY in enabled) else None
55
+
56
+ if config.extra_blacklist:
57
+ all_matches.extend(detect_custom_blacklist(text, config.extra_blacklist))
58
+
59
+ all_matches.extend(detect_json_kv_fields(text, enabled))
60
+
61
+ email_matches: list[SpanMatch] = []
62
+ if Category.EMAIL in enabled:
63
+ email_matches = detect_emails(text)
64
+ all_matches.extend(email_matches)
65
+
66
+ if Category.WEBSITE in enabled:
67
+ email_spans = [(m.start, m.end) for m in email_matches]
68
+ all_matches.extend(detect_websites(text, email_spans))
69
+
70
+ if Category.IP_ADDRESS in enabled and text_has_digit:
71
+ all_matches.extend(detect_ip_addresses(text, text_has_digit=True))
72
+
73
+ if Category.BANK in enabled:
74
+ all_matches.extend(detect_bank(text, text_has_digit=text_has_digit))
75
+
76
+ if Category.TAX_ID in enabled and text_has_digit:
77
+ all_matches.extend(detect_tax_ids(text, text_has_digit=True))
78
+
79
+ if Category.PHONE in enabled and text_has_digit:
80
+ all_matches.extend(detect_phones(text, text_has_digit=True))
81
+
82
+ if Category.BIRTHDATE in enabled and text_has_digit:
83
+ all_matches.extend(detect_birthdates(text, text_has_digit=True))
84
+
85
+ if Category.LICENSE_PLATE in enabled and text_has_digit:
86
+ all_matches.extend(detect_license_plates(text, text_has_digit=True))
87
+
88
+ if Category.AMOUNT in enabled and text_has_digit:
89
+ all_matches.extend(detect_amounts(text, text_has_digit=True))
90
+
91
+ if any(c in enabled for c in (Category.ADDRESS, Category.HOUSE_NUMBER, Category.POSTAL_CODE)):
92
+ all_matches.extend(
93
+ detect_addresses_plz_housenumbers(
94
+ text,
95
+ want_address=Category.ADDRESS in enabled,
96
+ want_house_number=Category.HOUSE_NUMBER in enabled,
97
+ want_plz=Category.POSTAL_CODE in enabled,
98
+ text_has_digit=text_has_digit,
99
+ )
100
+ )
101
+
102
+ if Category.LOCATION in enabled:
103
+ all_matches.extend(detect_locations(text))
104
+
105
+ if Category.JOB_TITLE in enabled:
106
+ all_matches.extend(detect_job_titles(text))
107
+
108
+ if Category.NAME in enabled:
109
+ all_matches.extend(detect_names(text, lines_cache=lines_cache))
110
+
111
+ if Category.COMPANY in enabled:
112
+ all_matches.extend(detect_companies(text, lines_cache=lines_cache))
113
+
114
+ return all_matches
@@ -0,0 +1,278 @@
1
+ """Detektoren für Adressen, Straßen, Hausnummern, Postleitzahlen (DE/AT/CH) & Ortschaften."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ from .detectors_common import has_digit
8
+ from .lexicons import (
9
+ AMBIGUOUS_CITY_WORDS,
10
+ COUNTRIES_AND_REGIONS_NON_TOWN,
11
+ MAJOR_GERMAN_CITIES,
12
+ NON_NAME_WORDS,
13
+ STREET_PREFIX_PHRASES,
14
+ STREET_SUFFIXES_COMPOUND,
15
+ )
16
+ from .models import Category, Confidence, SpanMatch
17
+ from .validators import validate_german_plz
18
+
19
+ # --- Straßen, Hausnummern & PLZ ---
20
+
21
+ _STREET_SUFFIX_ALT = "|".join(sorted((re.escape(s) for s in STREET_SUFFIXES_COMPOUND), key=len, reverse=True))
22
+ _STREET_SUFFIX_CAP_ALT = "|".join(sorted((re.escape(s[0].upper() + s[1:]) for s in STREET_SUFFIXES_COMPOUND), key=len, reverse=True))
23
+ _HOUSE_NUM_PART = (
24
+ r"\d{1,4}[ \t]*[a-zA-Z]?(?:[ \t]*[-/][ \t]*\d{1,4}[ \t]*[a-zA-Z]?)?"
25
+ r"(?![ \t]*(?:,\d|\.\d{2}|:\d{2}|t\b|to\b|Tonnen?\b|kg\b|€|EUR\b|Euro\b|Uhr\b|%|Meter\b|cm\b|km\b|Tage?\b|Std\b|Stunden?\b))"
26
+ )
27
+
28
+ STREET_COMPOUND_RE = re.compile(
29
+ rf"\b(?:(?:Alt|Neu|Ober|Unter|Groß|Klein|Sankt|St\.)[a-zäöüß]*[ \t]+)?"
30
+ rf"(?:"
31
+ rf"(?:[A-ZÄÖÜ][a-zäöüßéèê]+(?:-[A-ZÄÖÜa-zäöüß]+)*[ \t]+){{0,2}}[A-ZÄÖÜ][a-zäöüßéèê\-]+(?:{_STREET_SUFFIX_ALT})"
32
+ rf"|"
33
+ rf"(?:[A-ZÄÖÜ][a-zäöüßéèê]+(?:-[A-ZÄÖÜa-zäöüß]+)*[ \t]+){{1,2}}(?:{_STREET_SUFFIX_CAP_ALT})"
34
+ rf")"
35
+ rf"(?:(?:[ \t]+|(?<=\.)|(?<=straße)|(?<=strasse))(?:Nr\.?[ \t]*)?{_HOUSE_NUM_PART})",
36
+ re.UNICODE,
37
+ )
38
+
39
+ _STREET_PREFIX_ALT = "|".join(sorted((re.escape(p) for p in STREET_PREFIX_PHRASES), key=len, reverse=True))
40
+ STREET_PREFIX_RE = re.compile(
41
+ rf"\b(?:{_STREET_PREFIX_ALT})[ \t]+[A-ZÄÖÜ][a-zäöüß\-]+(?:[ \t]+[A-ZÄÖÜ][a-zäöüß\-]+){{0,2}}[ \t]+(?:Nr\.?[ \t]*)?{_HOUSE_NUM_PART}",
42
+ re.UNICODE,
43
+ )
44
+
45
+ _LEADING_PREP_STRIP_RE = re.compile(
46
+ r"^(?:Für|In|An|Auf|Bei|Nach|Von|Zu|Zum|Zur|Über|Unter|Durch|Mit|Aus|Ab|Bis|Der|Die|Das|Den|Dem|Eine?m?|Eine?r?)\s+"
47
+ )
48
+ _ADDRESS_LABEL_RE = re.compile(
49
+ r"(?i)\b(?:Adresse|Anschrift|Straße|Strasse|Wohnadresse|Wohnanschrift|Lieferadresse|"
50
+ r"Rechnungsadresse|Einsatzort|Aufstellort|Standort)[ \t]*[:=][ \t]*([^\n;]{4,90})"
51
+ )
52
+ _HOUSENUMBER_EXPLICIT_RE = re.compile(
53
+ rf"(?i)\b(?:Hausnummer|Hausnr\.?|Haus-Nr\.?|Hnr\.?)[ \t]*[:=]?[ \t]*({_HOUSE_NUM_PART})"
54
+ )
55
+ _HOUSENUMBER_NR_CONTEXT_RE = re.compile(
56
+ rf"(?i)(?:Straße|Strasse|Str\.|Haus|Gebäude|Wohnung|Grundstück|Einfahrt|Ecke)[ \t]+Nr\.?[ \t]*({_HOUSE_NUM_PART})"
57
+ )
58
+
59
+ _PLZ_EXPLICIT_RE = re.compile(r"(?i)\b(?:PLZ|Postleitzahl)[ \t]*[:=]?[ \t]*(\d{4,5})\b")
60
+ _PLZ_COUNTRY_CITY_RE = re.compile(
61
+ r"\b(?:D|DE)-(\d{5})(?:[ \t]+([A-ZÄÖÜ][a-zäöüß\-]+(?:[ \t]+(?:am|an|im|in|ob|vor|bei)[ \t]+(?:der[ \t]+|dem[ \t]+|den[ \t]+)?[A-ZÄÖÜ][a-zäöüß\-]+)?))?"
62
+ )
63
+ _PLZ_AT_CH_COUNTRY_CITY_RE = re.compile(
64
+ r"\b(?:A|AT|CH)-([1-9]\d{3})(?:[ \t]+([A-ZÄÖÜ][a-zäöüß\-]+(?:[ \t]+(?:am|an|im|in|ob|vor|bei)[ \t]+(?:der[ \t]+|dem[ \t]+|den[ \t]+)?[A-ZÄÖÜ][a-zäöüß\-]+)?))?"
65
+ )
66
+ _PLZ_CITY_RE = re.compile(
67
+ r"(?<!\d)(\d{5})[ \t]+([A-ZÄÖÜ][a-zäöüß\-]+(?:[ \t]+(?:am|an|im|in|ob|vor|bei)[ \t]+(?:der[ \t]+|dem[ \t]+|den[ \t]+)?[A-ZÄÖÜ][a-zäöüß\-]+)?)"
68
+ )
69
+ _PLZ_STANDALONE_RE = re.compile(r"(?<![\d\-/A-Za-z])(\d{5})(?![\d\-/A-Za-z])")
70
+ _PLZ_UNIT_AFTER_RE = re.compile(r"^\s*(?:€|EUR\b|Euro\b|km\b|kg\b|t\b|Meter\b)", re.IGNORECASE)
71
+ _STREET_ALPHA_RE = re.compile(r"[A-Za-zÄÖÜäöüß]+")
72
+
73
+ _NOT_A_CITY_AFTER_PLZ = frozenset({
74
+ "euro", "eur", "chf", "usd", "stück", "meter", "km", "kg", "tonnen", "tage", "stunden",
75
+ "minuten", "uhr", "bestellung", "auftrag", "kunde", "kunden", "rechnung", "beleg",
76
+ "prozent", "mal", "punkte", "zeichen", "zeilen", "wörter", "seiten", "bilder", "fotos",
77
+ "schilder", "kartons", "kisten", "fahrzeuge", "lkw", "pkw",
78
+ })
79
+ _NON_PLZ_BEFORE_RE = re.compile(
80
+ r"(?i)(?:Bestell(?:ung|nummer|nr\.?)|Auftrag(?:snummer|snr\.?)?|Kunde(?:nnummer|nnr\.?)?|"
81
+ r"Kd\.?-?Nr\.?|Rechnung(?:snummer|snr\.?)?|Vorgang(?:snummer)?|Ticket|Ref\.?|ID|Nr\.?|No\.?|"
82
+ r"Tel\.?|Fax|Mobil|Konto|BLZ|IBAN|Betrag|Summe|Kosten|Preis|HV\d*)\s*[:=#\-]?\s*$"
83
+ )
84
+ _FALSE_STREET_WORDS = frozenset({
85
+ "montag", "dienstag", "mittwoch", "donnerstag", "freitag", "samstag", "sonntag",
86
+ "januar", "februar", "märz", "april", "mai", "juni", "juli", "august", "september",
87
+ "oktober", "november", "dezember", "tag", "datum", "termin", "uhr", "fall", "ende",
88
+ "anfang", "auftrag", "bestellung", "antrag", "genehmigung", "lkw", "pkw", "fahrzeug",
89
+ })
90
+ _STREET_SKIP_PREFIXES = frozenset({
91
+ "am", "an", "der", "den", "dem", "auf", "im", "in", "vor", "unter", "über",
92
+ "zum", "zur", "bei", "beim", "hinter", "zwischen", "nr",
93
+ })
94
+ _STREET_BAD_TAILS = frozenset({
95
+ "tag", "monat", "jahr", "stunde", "minute", "termin", "auftrag", "mal", "teil", "punkt", "seite", "bild", "foto",
96
+ })
97
+
98
+
99
+ def is_plausible_street(street_text: str) -> bool:
100
+ tokens = _STREET_ALPHA_RE.findall(street_text)
101
+ if not tokens:
102
+ return False
103
+ non_prefix = [t.lower() for t in tokens if t.lower() not in _STREET_SKIP_PREFIXES]
104
+ if not non_prefix or all(w in _FALSE_STREET_WORDS for w in non_prefix):
105
+ return False
106
+ if non_prefix[-1] in _STREET_BAD_TAILS:
107
+ return False
108
+ if len(non_prefix) == 1 and non_prefix[0] in _FALSE_STREET_WORDS:
109
+ return False
110
+ return True
111
+
112
+
113
+ def detect_addresses_plz_housenumbers(
114
+ text: str,
115
+ want_address: bool,
116
+ want_house_number: bool,
117
+ want_plz: bool,
118
+ *,
119
+ text_has_digit: bool | None = None,
120
+ ) -> list[SpanMatch]:
121
+ has_num = has_digit(text) if text_has_digit is None else text_has_digit
122
+ if not has_num and ":" not in text and "=" not in text:
123
+ return []
124
+
125
+ matches: list[SpanMatch] = []
126
+
127
+ if want_address:
128
+ if has_num:
129
+ for m in STREET_COMPOUND_RE.finditer(text):
130
+ raw = m.group(0).strip()
131
+ cleaned = _LEADING_PREP_STRIP_RE.sub("", raw)
132
+ offset = len(raw) - len(cleaned)
133
+ if is_plausible_street(cleaned):
134
+ matches.append(SpanMatch(m.start() + offset, m.start() + offset + len(cleaned), cleaned, Category.ADDRESS, Confidence.HIGH, "Straße + Hausnummer"))
135
+
136
+ for m in STREET_PREFIX_RE.finditer(text):
137
+ raw = m.group(0).strip()
138
+ if is_plausible_street(raw):
139
+ matches.append(SpanMatch(m.start(), m.start() + len(raw), raw, Category.ADDRESS, Confidence.HIGH, "Straße + Hausnummer (Präfix)"))
140
+
141
+ if ":" in text or "=" in text:
142
+ for m in _ADDRESS_LABEL_RE.finditer(text):
143
+ val = m.group(1).strip()
144
+ if val and val.lower() not in NON_NAME_WORDS:
145
+ matches.append(SpanMatch(m.start(1), m.start(1) + len(val), val, Category.ADDRESS, Confidence.HIGH, "Adresse (Kontext-Feld)"))
146
+
147
+ if want_house_number and has_num:
148
+ for regex, rule in (
149
+ (_HOUSENUMBER_EXPLICIT_RE, "Hausnummer (explizit)"),
150
+ (_HOUSENUMBER_NR_CONTEXT_RE, "Hausnummer (Adresskontext)"),
151
+ ):
152
+ for m in regex.finditer(text):
153
+ val = m.group(1).strip()
154
+ matches.append(SpanMatch(m.start(1), m.start(1) + len(val), val, Category.HOUSE_NUMBER, Confidence.HIGH, rule))
155
+
156
+ if want_plz and has_num:
157
+ matched_plz_ranges: list[tuple[int, int]] = []
158
+
159
+ for m in _PLZ_EXPLICIT_RE.finditer(text):
160
+ plz_val = m.group(1)
161
+ is_valid = (len(plz_val) == 5 and validate_german_plz(plz_val)) or (
162
+ len(plz_val) == 4 and 1000 <= int(plz_val) <= 9999
163
+ )
164
+ if is_valid:
165
+ matches.append(SpanMatch(m.start(1), m.end(1), plz_val, Category.POSTAL_CODE, Confidence.HIGH, "PLZ (explizit)"))
166
+ matched_plz_ranges.append((m.start(1), m.end(1)))
167
+
168
+ for m in _PLZ_COUNTRY_CITY_RE.finditer(text):
169
+ if validate_german_plz(m.group(1)):
170
+ cat = Category.ADDRESS if (m.group(2) and want_address) else Category.POSTAL_CODE
171
+ matches.append(SpanMatch(m.start(), m.end(), m.group(0), cat, Confidence.HIGH, "PLZ + Ort (Länderpräfix DE)"))
172
+ matched_plz_ranges.append((m.start(), m.end()))
173
+
174
+ for m in _PLZ_AT_CH_COUNTRY_CITY_RE.finditer(text):
175
+ cat = Category.ADDRESS if (m.group(2) and want_address) else Category.POSTAL_CODE
176
+ matches.append(SpanMatch(m.start(), m.end(), m.group(0), cat, Confidence.HIGH, "PLZ + Ort (AT/CH)"))
177
+ matched_plz_ranges.append((m.start(), m.end()))
178
+
179
+ for m in _PLZ_CITY_RE.finditer(text):
180
+ plz, city = m.group(1), m.group(2)
181
+ if not validate_german_plz(plz):
182
+ continue
183
+ if any(s <= m.start(1) and m.end(1) <= e for s, e in matched_plz_ranges):
184
+ continue
185
+ before = text[max(0, m.start(1) - 30):m.start(1)]
186
+ if _NON_PLZ_BEFORE_RE.search(before):
187
+ continue
188
+ city_first = city.split()[0].lower()
189
+ if city_first in _NOT_A_CITY_AFTER_PLZ:
190
+ continue
191
+ if city.lower() in MAJOR_GERMAN_CITIES or city_first not in NON_NAME_WORDS:
192
+ span_end = m.end(2) if want_address else m.end(1)
193
+ cat = Category.ADDRESS if want_address else Category.POSTAL_CODE
194
+ matches.append(SpanMatch(m.start(1), span_end, text[m.start(1):span_end], cat, Confidence.HIGH, "PLZ + Ort"))
195
+ matched_plz_ranges.append((m.start(1), span_end))
196
+
197
+ for m in _PLZ_STANDALONE_RE.finditer(text):
198
+ plz = m.group(1)
199
+ if not validate_german_plz(plz):
200
+ continue
201
+ if any(s <= m.start(1) and m.end(1) <= e for s, e in matched_plz_ranges):
202
+ continue
203
+ if _NON_PLZ_BEFORE_RE.search(text[max(0, m.start(1) - 35):m.start(1)]):
204
+ continue
205
+ if _PLZ_UNIT_AFTER_RE.match(text[m.end(1):min(len(text), m.end(1) + 20)]):
206
+ continue
207
+ matches.append(SpanMatch(m.start(1), m.end(1), plz, Category.POSTAL_CODE, Confidence.REVIEW, "Mögliche PLZ (5-stellig, bitte prüfen)"))
208
+
209
+ return matches
210
+
211
+
212
+ # --- Ortschaften / Städte (Behörden wie „Stadt Köln“ bleiben sichtbar!) ---
213
+
214
+ _PUBLIC_AUTH_BEFORE_LOC_RE = re.compile(
215
+ r"(?i)\b(?:Stadt|Gemeinde|Kreis|Landkreis|Bezirksamt|Ordnungsamt|Bürgeramt|"
216
+ r"Straßenverkehrsamt|Strassenverkehrsamt|Tiefbauamt|Bauamt|Finanzamt|Polizei|"
217
+ r"Polizeipräsidium|Landratsamt|Stadtverwaltung|Gemeindeverwaltung|Kreisverwaltung|"
218
+ r"Bezirksregierung|Senatsverwaltung|Magistrat|Rathaus|Landesamt|Bundesamt|"
219
+ r"Amt[ \t]+für[ \t]+\w+)(?:[ \t]+(?:der[ \t]+|des[ \t]+)?)?[ \t]+\Z"
220
+ )
221
+ _HONORIFIC_BEFORE_LOC_RE = re.compile(r"(?i)\b(?:Herrn?|Frau|Hr\.?|Fr\.?|Prof\.?|Dr\.?)[ \t]+\Z")
222
+ _LOC_PREP_BEFORE_RE = re.compile(
223
+ r"(?i)(?:\b(?:in|aus|nach|bei|von|um|Richtung|Raum|Bereich|Umgebung|Ort|Wohnort|Ortschaft|Gemeinde|Stadtteil)[ \t]*[:=]?[ \t]+|,[ \t]+)\Z"
224
+ )
225
+ _LEGAL_FORM_AFTER_LOC_RE = re.compile(
226
+ r"^[ \t]+(?:(?:&\s*Co\.?[ \t]*)?(?:GmbH|UG|AG|OHG|KG|GbR|e\.?\s*K\.?|e\.?\s*V\.?|SE|Ltd\.?|Inc\.?|mbH|PartG|KGaA))\b"
227
+ )
228
+ _TOWN_TOKEN = r"[A-ZÄÖÜ][a-zäöüßéèê]+(?:-[A-ZÄÖÜ][a-zäöüßéèê]+)*"
229
+ _TOWN_PHRASE = (
230
+ rf"(?:(?:Bad|Sankt|St\.|Bergisch|Mönchengladbach|Neu|Alt|Ober|Unter|Groß|Klein)[ \t]+)?{_TOWN_TOKEN}"
231
+ rf"(?:[ \t]+(?:am|an|im|in|ob|vor|bei)[ \t]+(?:der[ \t]+|dem[ \t]+|den[ \t]+)?{_TOWN_TOKEN})?"
232
+ )
233
+ _LOCATION_LABEL_RE = re.compile(
234
+ rf"(?i)\b(?:Wohnort|Ortschaft|Ort|Stadtteil|Ortsteil|Abholort|Zielort|Lieferort)[ \t]*[:=][ \t]*({_TOWN_PHRASE})"
235
+ )
236
+ _UNAMBIGUOUS_CITY_PAT = re.compile(
237
+ r"\b(" + "|".join(re.escape(c) for c in sorted(MAJOR_GERMAN_CITIES, key=len, reverse=True)) + r")\b",
238
+ re.IGNORECASE,
239
+ )
240
+
241
+
242
+ def _is_protected_authority_context(text: str, start: int) -> bool:
243
+ line_before = text[max(0, start - 40):start].rsplit("\n", 1)[-1].rsplit("\r", 1)[-1]
244
+ return bool(_PUBLIC_AUTH_BEFORE_LOC_RE.search(line_before))
245
+
246
+
247
+ def detect_locations(text: str) -> list[SpanMatch]:
248
+ """Erkennt Ortschaften / Städte / Wohnorte, lässt aber Behörden wie 'Stadt Köln' sichtbar."""
249
+ matches: list[SpanMatch] = []
250
+
251
+ if ":" in text or "=" in text:
252
+ for m in _LOCATION_LABEL_RE.finditer(text):
253
+ val = m.group(1).strip(" .,:;")
254
+ low = val.lower()
255
+ if not val or low in COUNTRIES_AND_REGIONS_NON_TOWN:
256
+ continue
257
+ if low in NON_NAME_WORDS and low not in MAJOR_GERMAN_CITIES:
258
+ continue
259
+ if _is_protected_authority_context(text, m.start(1)):
260
+ continue
261
+ matches.append(SpanMatch(m.start(1), m.start(1) + len(val), val, Category.LOCATION, Confidence.HIGH, "Ortschaft / Wohnort (Kontext-Feld)"))
262
+
263
+ for m in _UNAMBIGUOUS_CITY_PAT.finditer(text):
264
+ raw = m.group(1)
265
+ if not raw[0].isupper():
266
+ continue
267
+ start, end = m.start(1), m.end(1)
268
+ low = raw.lower()
269
+ if low in COUNTRIES_AND_REGIONS_NON_TOWN or _is_protected_authority_context(text, start):
270
+ continue
271
+ line_before = text[max(0, start - 30):start].rsplit("\n", 1)[-1].rsplit("\r", 1)[-1]
272
+ if _HONORIFIC_BEFORE_LOC_RE.search(line_before) or _LEGAL_FORM_AFTER_LOC_RE.match(text[end:]):
273
+ continue
274
+ if low in AMBIGUOUS_CITY_WORDS and not _LOC_PREP_BEFORE_RE.search(line_before):
275
+ continue
276
+ matches.append(SpanMatch(start, end, raw, Category.LOCATION, Confidence.HIGH, "Ortschaft / Stadt (Lexikon)"))
277
+
278
+ return matches
@@ -0,0 +1,72 @@
1
+ """Gemeinsame, vorkompilierte Bausteine & Fast-Path-Helfer für alle Detektor-Module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from functools import lru_cache
7
+
8
+ from .lexicons import (
9
+ COMMON_FIRST_NAMES,
10
+ COMMON_SURNAMES,
11
+ GERMAN_COMPOUND_NOUN_SUFFIXES,
12
+ MAJOR_GERMAN_CITIES,
13
+ PUBLIC_AUTHORITY_PREFIXES,
14
+ )
15
+
16
+ NAME_LOWER_CHARS = r"a-zäöüßéèêáàâóòôíìîúùûñçğşıćńśźżłęąćšžřěůý"
17
+ NAME_UPPER_CHARS = r"A-ZÄÖÜÉÈÊÁÀÂÓÒÔÍÌÎÚÙÛÑÇĞŞİĆŃŚŹŻŁČŠŽ"
18
+ NAME_TOKEN = (
19
+ rf"(?:(?:Mc|Mac|O'|Al-|El-)[{NAME_UPPER_CHARS}][{NAME_LOWER_CHARS}]+|"
20
+ rf"[{NAME_UPPER_CHARS}][{NAME_LOWER_CHARS}]+)"
21
+ rf"(?:-[{NAME_UPPER_CHARS}][{NAME_LOWER_CHARS}]+)?"
22
+ )
23
+ NAME_TOKEN_CI = rf"[{NAME_UPPER_CHARS}{NAME_LOWER_CHARS}]{{2,}}(?:-[{NAME_UPPER_CHARS}{NAME_LOWER_CHARS}]{{2,}})?"
24
+ NAME_PARTICLE = r"(?:von(?:[ \t]+der|[ \t]+dem|[ \t]+den)?|van(?:[ \t]+der|[ \t]+den)?|de(?:[ \t]+la)?|zu|zum|zur|del|di|da|al|el|ben)"
25
+ NAME_SEQ = rf"(?:[{NAME_UPPER_CHARS}]\.[ \t]+)?{NAME_TOKEN}(?:[ \t]+(?:{NAME_PARTICLE}[ \t]+)?{NAME_TOKEN}){{0,2}}"
26
+
27
+ IMAGE_OR_SOCIAL_LINE_RE = re.compile(
28
+ r"^\s*(?:[\w\-]+\.(?:jpe?g|png|gif|bmp|svg|webp|ico|pdf|docx?|xlsx?|csv|txt|zip|eml|msg)|"
29
+ r"cid:[^\s]+|linkedin|xing|facebook|instagram|twitter|youtube|tiktok|whatsapp)\s*$",
30
+ re.IGNORECASE,
31
+ )
32
+
33
+ LEGAL_FORM_TAIL_RE = re.compile(
34
+ r"\b(?:GmbH|UG|AG|OHG|KG|GbR|e\.?\s*K\.?|e\.?\s*V\.?|SE|Ltd\.?|Inc\.?|mbH|PartG|KGaA)\b"
35
+ )
36
+
37
+ _DIGIT_RE = re.compile(r"\d")
38
+
39
+
40
+ def has_digit(text: str) -> bool:
41
+ """Extrem schneller C-Check, ob mindestens eine Ziffer im Text vorkommt."""
42
+ return _DIGIT_RE.search(text) is not None
43
+
44
+
45
+ def is_public_authority(raw: str) -> bool:
46
+ low = raw.strip().lower()
47
+ return any(low == p or low.startswith(p + " ") for p in PUBLIC_AUTHORITY_PREFIXES)
48
+
49
+
50
+ @lru_cache(maxsize=4096)
51
+ def is_german_compound_non_entity(word: str) -> bool:
52
+ """Erkennt deutsche Geschäfts-/Sach-Komposita (z. B. 'Krankenfahrzeuge', 'Testkennzeichen', 'Anlieferung')."""
53
+ wl = word.lower().strip(".,:;!?()[]{}\"'")
54
+ if len(wl) < 5:
55
+ return False
56
+ if wl in COMMON_FIRST_NAMES or wl in COMMON_SURNAMES or wl in MAJOR_GERMAN_CITIES:
57
+ return False
58
+ for suf in GERMAN_COMPOUND_NOUN_SUFFIXES:
59
+ if wl == suf or (wl.endswith(suf) and len(wl) >= len(suf) + 3):
60
+ return True
61
+ return False
62
+
63
+
64
+ def iter_lines_with_offsets(text: str) -> list[tuple[int, int, str]]:
65
+ """Zerlegt Text einmalig in (start, end, line_without_nl) für Adress- & Signaturblöcke."""
66
+ out: list[tuple[int, int, str]] = []
67
+ pos = 0
68
+ for raw_line in text.splitlines(keepends=True):
69
+ clean = raw_line.rstrip("\r\n")
70
+ out.append((pos, pos + len(clean), clean))
71
+ pos += len(raw_line)
72
+ return out