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.
- package/LICENSE +21 -0
- package/README.md +66 -2
- package/bin/blackthis.js +255 -0
- package/dsgvo_redactor/__init__.py +3 -0
- package/dsgvo_redactor/cli.py +214 -0
- package/dsgvo_redactor/csv_io.py +221 -0
- package/dsgvo_redactor/detectors.py +114 -0
- package/dsgvo_redactor/detectors_addresses.py +278 -0
- package/dsgvo_redactor/detectors_common.py +72 -0
- package/dsgvo_redactor/detectors_entities.py +818 -0
- package/dsgvo_redactor/detectors_structured.py +471 -0
- package/dsgvo_redactor/engine.py +810 -0
- package/dsgvo_redactor/german_dict.py +100 -0
- package/dsgvo_redactor/lexicons.py +690 -0
- package/dsgvo_redactor/models.py +247 -0
- package/dsgvo_redactor/ner_engine.py +377 -0
- package/dsgvo_redactor/pdf_export.py +393 -0
- package/dsgvo_redactor/pdf_redactor.py +356 -0
- package/dsgvo_redactor/report.py +269 -0
- package/dsgvo_redactor/session.py +518 -0
- package/dsgvo_redactor/validators.py +188 -0
- package/dsgvo_redactor/web_app.py +630 -0
- package/dsgvo_redactor/whitelist.py +273 -0
- package/package.json +52 -4
- package/redact_csv.py +7 -0
- package/requirements.txt +8 -0
- package/static/app.js +1670 -0
- package/static/styles.css +1067 -0
- package/templates/index.html +344 -0
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"""Datenmodelle für DSGVO CSV Redactor."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from enum import Enum
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Category(str, Enum):
|
|
11
|
+
"""Kategorien sensibler personenbezogener Daten."""
|
|
12
|
+
|
|
13
|
+
NAME = "NAME"
|
|
14
|
+
ADDRESS = "ADRESSE"
|
|
15
|
+
HOUSE_NUMBER = "HAUSNUMMER"
|
|
16
|
+
POSTAL_CODE = "PLZ"
|
|
17
|
+
LOCATION = "ORTSCHAFT"
|
|
18
|
+
BANK = "KONTODATEN"
|
|
19
|
+
JOB_TITLE = "BERUF_POSITION"
|
|
20
|
+
AMOUNT = "GELDBETRAG"
|
|
21
|
+
PHONE = "TELEFON"
|
|
22
|
+
EMAIL = "EMAIL"
|
|
23
|
+
WEBSITE = "WEBSEITE"
|
|
24
|
+
IP_ADDRESS = "IP_ADRESSE"
|
|
25
|
+
BIRTHDATE = "GEBURTSDATUM"
|
|
26
|
+
LICENSE_PLATE = "KFZ_KENNZEICHEN"
|
|
27
|
+
TAX_ID = "STEUER_AUSWEIS_ID"
|
|
28
|
+
COMPANY = "FIRMENNAME"
|
|
29
|
+
MANUAL = "MANUELL"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
CATEGORY_LABELS_DE: dict[Category, str] = {
|
|
33
|
+
Category.NAME: "Klarname",
|
|
34
|
+
Category.ADDRESS: "Adresse / Straße",
|
|
35
|
+
Category.HOUSE_NUMBER: "Hausnummer",
|
|
36
|
+
Category.POSTAL_CODE: "Postleitzahl",
|
|
37
|
+
Category.LOCATION: "Ortschaft / Stadt",
|
|
38
|
+
Category.BANK: "Kontodaten",
|
|
39
|
+
Category.JOB_TITLE: "Job-Position / Beruf",
|
|
40
|
+
Category.AMOUNT: "Geldbetrag",
|
|
41
|
+
Category.PHONE: "Telefonnummer",
|
|
42
|
+
Category.EMAIL: "E-Mail-Adresse",
|
|
43
|
+
Category.WEBSITE: "Webseite / URL",
|
|
44
|
+
Category.IP_ADDRESS: "IP-Adresse",
|
|
45
|
+
Category.BIRTHDATE: "Geburtsdatum",
|
|
46
|
+
Category.LICENSE_PLATE: "Kfz-Kennzeichen",
|
|
47
|
+
Category.TAX_ID: "Steuer- / Ausweis-ID",
|
|
48
|
+
Category.COMPANY: "Firmenname",
|
|
49
|
+
Category.MANUAL: "Manuelle Regel überall",
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
# Priorität bei überlappenden Fundstellen (höher gewinnt)
|
|
53
|
+
CATEGORY_PRIORITY: dict[Category, int] = {
|
|
54
|
+
Category.BANK: 100,
|
|
55
|
+
Category.EMAIL: 98,
|
|
56
|
+
Category.TAX_ID: 95,
|
|
57
|
+
Category.IP_ADDRESS: 93,
|
|
58
|
+
Category.WEBSITE: 92,
|
|
59
|
+
Category.PHONE: 90,
|
|
60
|
+
Category.BIRTHDATE: 88,
|
|
61
|
+
Category.LICENSE_PLATE: 86,
|
|
62
|
+
Category.ADDRESS: 85,
|
|
63
|
+
Category.POSTAL_CODE: 82,
|
|
64
|
+
Category.HOUSE_NUMBER: 80,
|
|
65
|
+
Category.AMOUNT: 78,
|
|
66
|
+
Category.JOB_TITLE: 75,
|
|
67
|
+
Category.COMPANY: 74,
|
|
68
|
+
Category.NAME: 72,
|
|
69
|
+
Category.LOCATION: 70,
|
|
70
|
+
Category.MANUAL: 110,
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class Confidence(str, Enum):
|
|
75
|
+
"""Konfidenzstufe eines Treffers."""
|
|
76
|
+
|
|
77
|
+
HIGH = "HIGH" # Sicher erkannt
|
|
78
|
+
REVIEW = "REVIEW" # Unsicher / Grenzfall – im Zweifel geschwärzt, gelb markiert
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass
|
|
82
|
+
class SpanMatch:
|
|
83
|
+
"""Ein einzelner erkannter Textabschnitt innerhalb einer Zelle."""
|
|
84
|
+
|
|
85
|
+
start: int
|
|
86
|
+
end: int
|
|
87
|
+
text: str
|
|
88
|
+
category: Category
|
|
89
|
+
confidence: Confidence
|
|
90
|
+
rule: str
|
|
91
|
+
reasons: list[str] = field(default_factory=list)
|
|
92
|
+
redacted: bool = True
|
|
93
|
+
protected: bool = False
|
|
94
|
+
match_id: str = ""
|
|
95
|
+
|
|
96
|
+
def __post_init__(self) -> None:
|
|
97
|
+
if not self.reasons:
|
|
98
|
+
self.reasons = [self.rule]
|
|
99
|
+
|
|
100
|
+
def to_dict(self) -> dict[str, Any]:
|
|
101
|
+
return {
|
|
102
|
+
"id": self.match_id,
|
|
103
|
+
"start": self.start,
|
|
104
|
+
"end": self.end,
|
|
105
|
+
"text": self.text,
|
|
106
|
+
"category": self.category.value,
|
|
107
|
+
"category_label": CATEGORY_LABELS_DE.get(self.category, self.category.value),
|
|
108
|
+
"confidence": self.confidence.value,
|
|
109
|
+
"rule": self.rule,
|
|
110
|
+
"reasons": self.reasons,
|
|
111
|
+
"redacted": self.redacted,
|
|
112
|
+
"protected": self.protected,
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@dataclass
|
|
117
|
+
class RedactionConfig:
|
|
118
|
+
"""Konfiguration für einen Schwärzungsdurchlauf."""
|
|
119
|
+
|
|
120
|
+
applicant_first_name: str = ""
|
|
121
|
+
applicant_last_name: str = ""
|
|
122
|
+
extra_whitelist: list[str] = field(default_factory=list)
|
|
123
|
+
extra_blacklist: list[str] = field(default_factory=list)
|
|
124
|
+
replacement: str = "██████"
|
|
125
|
+
use_typed_placeholders: bool = False
|
|
126
|
+
|
|
127
|
+
# Kategorien (Standard gemäß Anforderungen)
|
|
128
|
+
redact_names: bool = True
|
|
129
|
+
redact_addresses: bool = True
|
|
130
|
+
redact_house_numbers: bool = True
|
|
131
|
+
redact_postal_codes: bool = True
|
|
132
|
+
redact_locations: bool = True
|
|
133
|
+
redact_bank: bool = True
|
|
134
|
+
redact_job_titles: bool = True
|
|
135
|
+
redact_amounts: bool = True
|
|
136
|
+
redact_phones: bool = True
|
|
137
|
+
redact_emails: bool = True
|
|
138
|
+
redact_websites: bool = True
|
|
139
|
+
redact_ip_addresses: bool = True
|
|
140
|
+
redact_birthdates: bool = True
|
|
141
|
+
redact_license_plates: bool = True
|
|
142
|
+
redact_tax_ids: bool = True
|
|
143
|
+
redact_companies: bool = False # Standardmäßig AUS, per Checkbox aktivierbar
|
|
144
|
+
|
|
145
|
+
# DSGVO-Sicherheit: Unsichere Treffer im Zweifel automatisch schwärzen
|
|
146
|
+
redact_uncertain_by_default: bool = True
|
|
147
|
+
use_ner: bool = True
|
|
148
|
+
columns: list[str] | None = None
|
|
149
|
+
|
|
150
|
+
def enabled_categories(self) -> set[Category]:
|
|
151
|
+
enabled: set[Category] = {Category.MANUAL}
|
|
152
|
+
mapping = {
|
|
153
|
+
Category.NAME: self.redact_names,
|
|
154
|
+
Category.ADDRESS: self.redact_addresses,
|
|
155
|
+
Category.HOUSE_NUMBER: self.redact_house_numbers,
|
|
156
|
+
Category.POSTAL_CODE: self.redact_postal_codes,
|
|
157
|
+
Category.LOCATION: self.redact_locations,
|
|
158
|
+
Category.BANK: self.redact_bank,
|
|
159
|
+
Category.JOB_TITLE: self.redact_job_titles,
|
|
160
|
+
Category.AMOUNT: self.redact_amounts,
|
|
161
|
+
Category.PHONE: self.redact_phones,
|
|
162
|
+
Category.EMAIL: self.redact_emails,
|
|
163
|
+
Category.WEBSITE: self.redact_websites,
|
|
164
|
+
Category.IP_ADDRESS: self.redact_ip_addresses,
|
|
165
|
+
Category.BIRTHDATE: self.redact_birthdates,
|
|
166
|
+
Category.LICENSE_PLATE: self.redact_license_plates,
|
|
167
|
+
Category.TAX_ID: self.redact_tax_ids,
|
|
168
|
+
Category.COMPANY: self.redact_companies,
|
|
169
|
+
}
|
|
170
|
+
for cat, is_on in mapping.items():
|
|
171
|
+
if is_on:
|
|
172
|
+
enabled.add(cat)
|
|
173
|
+
return enabled
|
|
174
|
+
|
|
175
|
+
def replacement_for(self, category: Category) -> str:
|
|
176
|
+
if self.use_typed_placeholders:
|
|
177
|
+
return f"[{category.value}]"
|
|
178
|
+
return self.replacement
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
@dataclass
|
|
182
|
+
class CellResult:
|
|
183
|
+
"""Ergebnis für eine einzelne gescannte CSV-Zelle."""
|
|
184
|
+
|
|
185
|
+
row_index: int
|
|
186
|
+
column: str
|
|
187
|
+
original: str
|
|
188
|
+
redacted: str
|
|
189
|
+
matches: list[SpanMatch] = field(default_factory=list)
|
|
190
|
+
|
|
191
|
+
@property
|
|
192
|
+
def high_count(self) -> int:
|
|
193
|
+
return sum(1 for m in self.matches if not m.protected and m.redacted and m.confidence == Confidence.HIGH)
|
|
194
|
+
|
|
195
|
+
@property
|
|
196
|
+
def review_count(self) -> int:
|
|
197
|
+
return sum(1 for m in self.matches if not m.protected and m.redacted and m.confidence == Confidence.REVIEW)
|
|
198
|
+
|
|
199
|
+
@property
|
|
200
|
+
def protected_count(self) -> int:
|
|
201
|
+
return sum(1 for m in self.matches if m.protected)
|
|
202
|
+
|
|
203
|
+
def to_dict(self) -> dict[str, Any]:
|
|
204
|
+
return {
|
|
205
|
+
"row_index": self.row_index,
|
|
206
|
+
"column": self.column,
|
|
207
|
+
"original": self.original,
|
|
208
|
+
"redacted": self.redacted,
|
|
209
|
+
"matches": [m.to_dict() for m in self.matches],
|
|
210
|
+
"high_count": self.high_count,
|
|
211
|
+
"review_count": self.review_count,
|
|
212
|
+
"protected_count": self.protected_count,
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
@dataclass
|
|
217
|
+
class ScanSummary:
|
|
218
|
+
"""Zusammenfassung eines kompletten CSV-Scans."""
|
|
219
|
+
|
|
220
|
+
total_rows: int
|
|
221
|
+
scanned_columns: list[str]
|
|
222
|
+
rows_with_findings: int
|
|
223
|
+
total_redactions: int
|
|
224
|
+
high_confidence_redactions: int
|
|
225
|
+
review_findings: int
|
|
226
|
+
protected_applicant_hits: int
|
|
227
|
+
by_category: dict[str, int]
|
|
228
|
+
ner_active: bool
|
|
229
|
+
ner_model_name: str
|
|
230
|
+
encoding: str = "utf-8"
|
|
231
|
+
delimiter: str = ";"
|
|
232
|
+
|
|
233
|
+
def to_dict(self) -> dict[str, Any]:
|
|
234
|
+
return {
|
|
235
|
+
"total_rows": self.total_rows,
|
|
236
|
+
"scanned_columns": self.scanned_columns,
|
|
237
|
+
"rows_with_findings": self.rows_with_findings,
|
|
238
|
+
"total_redactions": self.total_redactions,
|
|
239
|
+
"high_confidence_redactions": self.high_confidence_redactions,
|
|
240
|
+
"review_findings": self.review_findings,
|
|
241
|
+
"protected_applicant_hits": self.protected_applicant_hits,
|
|
242
|
+
"by_category": self.by_category,
|
|
243
|
+
"ner_active": self.ner_active,
|
|
244
|
+
"ner_model_name": self.ner_model_name,
|
|
245
|
+
"encoding": self.encoding,
|
|
246
|
+
"delimiter": self.delimiter,
|
|
247
|
+
}
|
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
"""Lokales Offline-NER-Modul (spaCy Deutsch) – speicherschonend, vorkompiliert & 100 % offline."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from functools import lru_cache
|
|
7
|
+
from typing import Any, Callable
|
|
8
|
+
|
|
9
|
+
from .detectors_common import has_digit, is_german_compound_non_entity, is_public_authority
|
|
10
|
+
from .german_dict import is_common_german_dictionary_word
|
|
11
|
+
from .lexicons import (
|
|
12
|
+
COMMON_FIRST_NAMES,
|
|
13
|
+
COMMON_SURNAMES,
|
|
14
|
+
COUNTRIES_AND_REGIONS_NON_TOWN,
|
|
15
|
+
MAJOR_GERMAN_CITIES,
|
|
16
|
+
NON_NAME_WORDS,
|
|
17
|
+
ORG_NOISE_WORDS,
|
|
18
|
+
)
|
|
19
|
+
from .models import Category, Confidence, RedactionConfig, SpanMatch
|
|
20
|
+
|
|
21
|
+
PREFERRED_MODELS = ("de_core_news_lg", "de_core_news_md", "de_core_news_sm")
|
|
22
|
+
|
|
23
|
+
_IMAGE_FILENAME_RE = re.compile(r"\.(?:jpe?g|png|gif|pdf|docx?|xlsx?|csv|txt)$", re.IGNORECASE)
|
|
24
|
+
_ORDER_CODE_RE = re.compile(
|
|
25
|
+
r"^(?:[A-Za-zÄÖÜäöüß]{1,15}[-_/#]?\d[\dA-Za-z\-_/]*|\d+[-_/][A-Za-z0-9\-_/]+)$"
|
|
26
|
+
)
|
|
27
|
+
# Technische Bezeichner wie camelCase („sendTemplateMail“, „getUserById“) oder snake_case („bcc_mail“, „customer_ref“)
|
|
28
|
+
_CAMEL_OR_SNAKE_CODE_RE = re.compile(r"^(?:[a-zäöüß]+[A-ZÄÖÜ][A-Za-z0-9]*|[A-Za-z0-9]+_[A-Za-z0-9_]+)$")
|
|
29
|
+
_NUMERIC_ONLY_RE = re.compile(r"^[\d\s.,:/\-+]+$")
|
|
30
|
+
_HONORIFIC_STRIP_RE = re.compile(r"^(?:Herrn?|Frau|Hr\.?|Fr\.?)[ \t]+", re.IGNORECASE)
|
|
31
|
+
_TAIL_WORD_RE = re.compile(r"[ \t]+(\S+)$")
|
|
32
|
+
_LEGAL_FORM_RE = re.compile(
|
|
33
|
+
r"\b(?:GmbH|UG|AG|OHG|KG|GbR|e\.?\s*K\.?|e\.?\s*V\.?|SE|Ltd\.?|Inc\.?|mbH|PartG|KGaA)\b"
|
|
34
|
+
)
|
|
35
|
+
_LEGAL_FORM_FOLLOW_RE = re.compile(
|
|
36
|
+
r"^[ \t]+(?:(?:&\s*Co\.?[ \t]*)?(?:GmbH|UG|AG|OHG|KG|GbR|e\.?\s*K\.?|e\.?\s*V\.?|SE|Ltd\.?|Inc\.?|mbH|PartG|KGaA))\b"
|
|
37
|
+
)
|
|
38
|
+
_PUBLIC_AUTH_BEFORE_LOC_RE = re.compile(
|
|
39
|
+
r"(?i)\b(?:Stadt|Gemeinde|Kreis|Landkreis|Bezirksamt|Ordnungsamt|Bürgeramt|"
|
|
40
|
+
r"Straßenverkehrsamt|Strassenverkehrsamt|Tiefbauamt|Bauamt|Finanzamt|Polizei|"
|
|
41
|
+
r"Polizeipräsidium|Landratsamt|Stadtverwaltung|Gemeindeverwaltung|Kreisverwaltung|"
|
|
42
|
+
r"Bezirksregierung|Senatsverwaltung|Magistrat|Rathaus|Landesamt|Bundesamt|"
|
|
43
|
+
r"Amt[ \t]+für[ \t]+\w+)(?:[ \t]+(?:der[ \t]+|des[ \t]+)?)?[ \t]+\Z"
|
|
44
|
+
)
|
|
45
|
+
_LOC_CONTEXT_BEFORE_RE = re.compile(
|
|
46
|
+
r"(?i)(?:\b(?:in|aus|nach|bei|von|um|Richtung|Raum|Bereich|Umgebung|Ort|Wohnort|Ortschaft|Gemeinde|Stadtteil)[ \t]*[:=]?[ \t]+|,[ \t]+)\Z"
|
|
47
|
+
)
|
|
48
|
+
_ALPHA_RE = re.compile(r"[A-Za-zÄÖÜäöüß]")
|
|
49
|
+
# Schneidet HTML-Tags & angeschnittene Tag-Reste aus NER-Spans heraus (z. B. „Max Mustermann</span></font>...<tr><td“)
|
|
50
|
+
_HTML_TAG_OR_FRAG_RE = re.compile(r"<[^>]*>|<[^>\n]*$|^[^<\n]*>")
|
|
51
|
+
|
|
52
|
+
_NON_ENTITY_STTS_PREFIXES = (
|
|
53
|
+
"ADJ", "VV", "VA", "VM", "ADV", "APPR", "ART", "KO", "P", "CARD", "PTK",
|
|
54
|
+
)
|
|
55
|
+
# Typische Adress-/Wohnungs-Abkürzungen, die spaCy manchmal als LOC rät („Hnr“, „Whg“, „OG“, „EG“)
|
|
56
|
+
_ADDRESS_ABBREV_NON_LOC = frozenset({
|
|
57
|
+
"hnr", "hausnr", "whg", "etg", "og", "eg", "dg", "ug", "str", "plz",
|
|
58
|
+
"tel", "fax", "mob", "zhd", "app", "apt", "nr", "abs", "empf",
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
_is_german_compound_non_entity = is_german_compound_non_entity
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _segment_has_only_non_entity_pos(doc: Any, start: int, end: int, *, reject_common_noun: bool = False) -> bool:
|
|
65
|
+
"""Prüft per spaCy POS-Tagger, ob eine Einzelwort-Entität nur Adjektiv/Verb/Funktionswort (oder NN-Sachwort) ist."""
|
|
66
|
+
span = doc.char_span(start, end, alignment_mode="contract")
|
|
67
|
+
if span is None or len(span) != 1:
|
|
68
|
+
return False
|
|
69
|
+
tag = getattr(span[0], "tag_", "") or ""
|
|
70
|
+
if not tag:
|
|
71
|
+
return False
|
|
72
|
+
if reject_common_noun and tag == "NN":
|
|
73
|
+
return True
|
|
74
|
+
return tag.startswith(_NON_ENTITY_STTS_PREFIXES)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _emit_clean_subsegments(
|
|
78
|
+
doc_text: str,
|
|
79
|
+
seg_start: int,
|
|
80
|
+
part_clean: str,
|
|
81
|
+
out: list[tuple[int, int, str]],
|
|
82
|
+
) -> None:
|
|
83
|
+
"""Teilt ein Zeilensegment zusätzlich an HTML-Tags (<...>) auf und trimmt Whitespace exakt."""
|
|
84
|
+
if "<" not in part_clean and ">" not in part_clean:
|
|
85
|
+
if not part_clean.strip():
|
|
86
|
+
return
|
|
87
|
+
lead = len(part_clean) - len(part_clean.lstrip())
|
|
88
|
+
trail = len(part_clean) - len(part_clean.rstrip())
|
|
89
|
+
s = seg_start + lead
|
|
90
|
+
e = seg_start + len(part_clean) - trail
|
|
91
|
+
if s < e:
|
|
92
|
+
out.append((s, e, doc_text[s:e]))
|
|
93
|
+
return
|
|
94
|
+
|
|
95
|
+
pos = 0
|
|
96
|
+
for m in _HTML_TAG_OR_FRAG_RE.finditer(part_clean):
|
|
97
|
+
if m.start() > pos:
|
|
98
|
+
chunk = part_clean[pos:m.start()]
|
|
99
|
+
if chunk.strip():
|
|
100
|
+
lead = len(chunk) - len(chunk.lstrip())
|
|
101
|
+
trail = len(chunk) - len(chunk.rstrip())
|
|
102
|
+
s = seg_start + pos + lead
|
|
103
|
+
e = seg_start + m.start() - trail
|
|
104
|
+
if s < e:
|
|
105
|
+
out.append((s, e, doc_text[s:e]))
|
|
106
|
+
pos = m.end()
|
|
107
|
+
if pos < len(part_clean):
|
|
108
|
+
chunk = part_clean[pos:]
|
|
109
|
+
if chunk.strip():
|
|
110
|
+
lead = len(chunk) - len(chunk.lstrip())
|
|
111
|
+
trail = len(chunk) - len(chunk.rstrip())
|
|
112
|
+
s = seg_start + pos + lead
|
|
113
|
+
e = seg_start + len(part_clean) - trail
|
|
114
|
+
if s < e:
|
|
115
|
+
out.append((s, e, doc_text[s:e]))
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _iter_line_segments(doc_text: str, ent_start: int, ent_end: int) -> list[tuple[int, int, str]]:
|
|
119
|
+
"""Teilt eine NER-Entität an Zeilenumbrüchen & HTML-Tags auf, damit Namen sauber abgegrenzt bleiben."""
|
|
120
|
+
raw_slice = doc_text[ent_start:ent_end]
|
|
121
|
+
segments: list[tuple[int, int, str]] = []
|
|
122
|
+
if "\n" not in raw_slice and "\r" not in raw_slice:
|
|
123
|
+
_emit_clean_subsegments(doc_text, ent_start, raw_slice, segments)
|
|
124
|
+
return segments
|
|
125
|
+
|
|
126
|
+
cursor = ent_start
|
|
127
|
+
for part in raw_slice.splitlines(keepends=True):
|
|
128
|
+
part_clean = part.rstrip("\r\n")
|
|
129
|
+
if part_clean.strip():
|
|
130
|
+
_emit_clean_subsegments(doc_text, cursor, part_clean, segments)
|
|
131
|
+
cursor += len(part)
|
|
132
|
+
return segments
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class LocalGermanNER:
|
|
136
|
+
"""Wrapper um das lokale deutsche spaCy-Sprachmodell mit automatischer Erkennung & sauberem Fallback."""
|
|
137
|
+
|
|
138
|
+
def __init__(self, model_name: str | None = None) -> None:
|
|
139
|
+
self.nlp: Any = None
|
|
140
|
+
self.model_name: str = "nicht installiert"
|
|
141
|
+
self.available: bool = False
|
|
142
|
+
self._load(model_name)
|
|
143
|
+
|
|
144
|
+
def _load(self, preferred: str | None = None) -> None:
|
|
145
|
+
try:
|
|
146
|
+
import spacy # type: ignore
|
|
147
|
+
except ImportError:
|
|
148
|
+
self.available = False
|
|
149
|
+
self.model_name = "spacy nicht installiert"
|
|
150
|
+
return
|
|
151
|
+
|
|
152
|
+
candidates = [preferred] if preferred else list(PREFERRED_MODELS)
|
|
153
|
+
for name in candidates:
|
|
154
|
+
if not name:
|
|
155
|
+
continue
|
|
156
|
+
try:
|
|
157
|
+
self.nlp = spacy.load(name, exclude=["parser", "lemmatizer", "attribute_ruler"])
|
|
158
|
+
self.model_name = name
|
|
159
|
+
self.available = True
|
|
160
|
+
return
|
|
161
|
+
except OSError:
|
|
162
|
+
continue
|
|
163
|
+
|
|
164
|
+
self.available = False
|
|
165
|
+
self.model_name = "kein deutsches spaCy-Modell gefunden"
|
|
166
|
+
|
|
167
|
+
@staticmethod
|
|
168
|
+
def _is_noise_entity(raw: str) -> bool:
|
|
169
|
+
cleaned = raw.strip(" \t\n\r.,:;!?()[]{}\"'")
|
|
170
|
+
if (
|
|
171
|
+
len(cleaned) < 2
|
|
172
|
+
or "<" in cleaned
|
|
173
|
+
or ">" in cleaned
|
|
174
|
+
or "=" in cleaned
|
|
175
|
+
or _NUMERIC_ONLY_RE.match(cleaned)
|
|
176
|
+
or _IMAGE_FILENAME_RE.search(cleaned)
|
|
177
|
+
or _ORDER_CODE_RE.match(cleaned)
|
|
178
|
+
or _CAMEL_OR_SNAKE_CODE_RE.match(cleaned)
|
|
179
|
+
):
|
|
180
|
+
return True
|
|
181
|
+
tokens = [t.strip(".,:;!?()[]{}\"'").lower() for t in cleaned.split() if t.strip()]
|
|
182
|
+
if not tokens:
|
|
183
|
+
return True
|
|
184
|
+
if cleaned.lower() in MAJOR_GERMAN_CITIES:
|
|
185
|
+
return False
|
|
186
|
+
return all(t in NON_NAME_WORDS and t not in MAJOR_GERMAN_CITIES for t in tokens)
|
|
187
|
+
|
|
188
|
+
def _extract_from_doc(self, doc: Any, enabled: set[Category]) -> list[SpanMatch]:
|
|
189
|
+
matches: list[SpanMatch] = []
|
|
190
|
+
doc_text = doc.text
|
|
191
|
+
|
|
192
|
+
for ent in doc.ents:
|
|
193
|
+
if not ent.text or not ent.text.strip():
|
|
194
|
+
continue
|
|
195
|
+
label = ent.label_
|
|
196
|
+
if label == "PER" and Category.NAME not in enabled:
|
|
197
|
+
continue
|
|
198
|
+
if label == "ORG" and Category.COMPANY not in enabled:
|
|
199
|
+
continue
|
|
200
|
+
if label == "LOC" and Category.LOCATION not in enabled:
|
|
201
|
+
continue
|
|
202
|
+
if label not in ("PER", "ORG", "LOC"):
|
|
203
|
+
continue
|
|
204
|
+
|
|
205
|
+
for start, end, text_val in _iter_line_segments(doc_text, ent.start_char, ent.end_char):
|
|
206
|
+
if not text_val or self._is_noise_entity(text_val):
|
|
207
|
+
continue
|
|
208
|
+
|
|
209
|
+
if label == "PER":
|
|
210
|
+
if has_digit(text_val):
|
|
211
|
+
continue
|
|
212
|
+
lead_trim = len(text_val) - len(text_val.lstrip("([{\"«' "))
|
|
213
|
+
start += lead_trim
|
|
214
|
+
text_val = text_val[lead_trim:]
|
|
215
|
+
had_trailing_colon = text_val.endswith(":") or doc_text[end:end + 1] == ":"
|
|
216
|
+
trimmed_val = text_val.rstrip(".,:;!?)]}\"»' ")
|
|
217
|
+
if not trimmed_val:
|
|
218
|
+
continue
|
|
219
|
+
end = start + len(trimmed_val)
|
|
220
|
+
text_val = trimmed_val
|
|
221
|
+
if self._is_noise_entity(text_val):
|
|
222
|
+
continue
|
|
223
|
+
if _LEGAL_FORM_RE.search(text_val) or _LEGAL_FORM_FOLLOW_RE.match(doc_text[end:]):
|
|
224
|
+
continue
|
|
225
|
+
if text_val.lower() in MAJOR_GERMAN_CITIES or is_public_authority(text_val):
|
|
226
|
+
continue
|
|
227
|
+
if text_val.isupper() and len(text_val) <= 5:
|
|
228
|
+
continue
|
|
229
|
+
|
|
230
|
+
stripped = _HONORIFIC_STRIP_RE.sub("", text_val)
|
|
231
|
+
if not stripped:
|
|
232
|
+
continue
|
|
233
|
+
start += len(text_val) - len(stripped)
|
|
234
|
+
text_val = stripped
|
|
235
|
+
|
|
236
|
+
while True:
|
|
237
|
+
m_tail = _TAIL_WORD_RE.search(text_val)
|
|
238
|
+
if not m_tail:
|
|
239
|
+
break
|
|
240
|
+
tail_l = m_tail.group(1).lower().rstrip(".,:;!?")
|
|
241
|
+
if tail_l in NON_NAME_WORDS and tail_l not in COMMON_SURNAMES:
|
|
242
|
+
text_val = text_val[:m_tail.start()].rstrip(" \t.,:;!?")
|
|
243
|
+
else:
|
|
244
|
+
break
|
|
245
|
+
if not text_val:
|
|
246
|
+
continue
|
|
247
|
+
end = start + len(text_val)
|
|
248
|
+
|
|
249
|
+
words = text_val.split()
|
|
250
|
+
if not words:
|
|
251
|
+
continue
|
|
252
|
+
low_full = text_val.lower().rstrip(".,:;!?")
|
|
253
|
+
if low_full in NON_NAME_WORDS and low_full not in COMMON_SURNAMES:
|
|
254
|
+
continue
|
|
255
|
+
if len(words) == 1 and low_full not in COMMON_FIRST_NAMES and low_full not in COMMON_SURNAMES:
|
|
256
|
+
# Einzelnes kleingeschriebenes Wort ohne Anrede („konk“, „zusatzrechnung“, „tourenplanung“) ist kein NER-PER
|
|
257
|
+
if text_val[0].islower():
|
|
258
|
+
continue
|
|
259
|
+
if (
|
|
260
|
+
had_trailing_colon
|
|
261
|
+
or is_common_german_dictionary_word(text_val)
|
|
262
|
+
or _segment_has_only_non_entity_pos(doc, start, end, reject_common_noun=True)
|
|
263
|
+
):
|
|
264
|
+
continue
|
|
265
|
+
|
|
266
|
+
conf = Confidence.HIGH if (
|
|
267
|
+
len(words) >= 2 or words[0].lower() in COMMON_FIRST_NAMES or words[0].lower() in COMMON_SURNAMES
|
|
268
|
+
) else Confidence.REVIEW
|
|
269
|
+
matches.append(SpanMatch(start, end, doc_text[start:end], Category.NAME, conf, f"Lokale Sprach-KI ({self.model_name}: PER)"))
|
|
270
|
+
|
|
271
|
+
elif label == "ORG":
|
|
272
|
+
lead_trim = len(text_val) - len(text_val.lstrip("([{\"«' "))
|
|
273
|
+
start += lead_trim
|
|
274
|
+
text_val = text_val[lead_trim:]
|
|
275
|
+
trimmed_val = text_val.rstrip(".,:;!?)]}\"»' ")
|
|
276
|
+
if not trimmed_val or len(trimmed_val) < 2:
|
|
277
|
+
continue
|
|
278
|
+
end = start + len(trimmed_val)
|
|
279
|
+
text_val = trimmed_val
|
|
280
|
+
low_org = text_val.lower()
|
|
281
|
+
if (
|
|
282
|
+
is_public_authority(text_val)
|
|
283
|
+
or low_org in MAJOR_GERMAN_CITIES
|
|
284
|
+
or low_org in NON_NAME_WORDS
|
|
285
|
+
or low_org in ORG_NOISE_WORDS
|
|
286
|
+
or low_org in COUNTRIES_AND_REGIONS_NON_TOWN
|
|
287
|
+
or (text_val.isupper() and len(text_val) <= 4)
|
|
288
|
+
or _IMAGE_FILENAME_RE.search(text_val)
|
|
289
|
+
):
|
|
290
|
+
continue
|
|
291
|
+
if " " not in text_val and (
|
|
292
|
+
is_common_german_dictionary_word(text_val)
|
|
293
|
+
or _segment_has_only_non_entity_pos(doc, start, end)
|
|
294
|
+
):
|
|
295
|
+
continue
|
|
296
|
+
conf = Confidence.HIGH if (_LEGAL_FORM_RE.search(text_val) or "&" in text_val) else Confidence.REVIEW
|
|
297
|
+
matches.append(SpanMatch(start, end, doc_text[start:end], Category.COMPANY, conf, f"Lokale Sprach-KI ({self.model_name}: ORG)"))
|
|
298
|
+
|
|
299
|
+
elif label == "LOC":
|
|
300
|
+
if has_digit(text_val) or not text_val[0].isupper():
|
|
301
|
+
continue
|
|
302
|
+
trimmed_val = text_val.rstrip(".,:;!?")
|
|
303
|
+
if not trimmed_val or len(trimmed_val) < 3:
|
|
304
|
+
continue
|
|
305
|
+
end = start + len(trimmed_val)
|
|
306
|
+
text_val = trimmed_val
|
|
307
|
+
low = text_val.lower()
|
|
308
|
+
if is_public_authority(text_val) or low in COUNTRIES_AND_REGIONS_NON_TOWN:
|
|
309
|
+
continue
|
|
310
|
+
line_before = doc_text[max(0, start - 40):start].rsplit("\n", 1)[-1].rsplit("\r", 1)[-1]
|
|
311
|
+
if _PUBLIC_AUTH_BEFORE_LOC_RE.search(line_before):
|
|
312
|
+
continue
|
|
313
|
+
if _LEGAL_FORM_RE.search(text_val) or _LEGAL_FORM_FOLLOW_RE.match(doc_text[end:]):
|
|
314
|
+
continue
|
|
315
|
+
if (
|
|
316
|
+
(text_val.isupper() and len(text_val) <= 4)
|
|
317
|
+
or low in _ADDRESS_ABBREV_NON_LOC
|
|
318
|
+
or (low in NON_NAME_WORDS and low not in MAJOR_GERMAN_CITIES)
|
|
319
|
+
):
|
|
320
|
+
continue
|
|
321
|
+
if " " not in text_val and low not in MAJOR_GERMAN_CITIES:
|
|
322
|
+
if (
|
|
323
|
+
is_common_german_dictionary_word(text_val)
|
|
324
|
+
or _segment_has_only_non_entity_pos(doc, start, end, reject_common_noun=True)
|
|
325
|
+
):
|
|
326
|
+
continue
|
|
327
|
+
conf = Confidence.HIGH if (
|
|
328
|
+
low in MAJOR_GERMAN_CITIES or "-" in text_val or " " in text_val or _LOC_CONTEXT_BEFORE_RE.search(line_before)
|
|
329
|
+
) else Confidence.REVIEW
|
|
330
|
+
matches.append(SpanMatch(start, end, doc_text[start:end], Category.LOCATION, conf, f"Lokale Sprach-KI ({self.model_name}: LOC)"))
|
|
331
|
+
|
|
332
|
+
return matches
|
|
333
|
+
|
|
334
|
+
def detect(self, text: str, config: RedactionConfig) -> list[SpanMatch]:
|
|
335
|
+
if not self.available or not config.use_ner or not text or len(text) < 3 or not _ALPHA_RE.search(text):
|
|
336
|
+
return []
|
|
337
|
+
doc = self.nlp(text)
|
|
338
|
+
return self._extract_from_doc(doc, config.enabled_categories())
|
|
339
|
+
|
|
340
|
+
def detect_batch(
|
|
341
|
+
self,
|
|
342
|
+
texts: list[str],
|
|
343
|
+
config: RedactionConfig,
|
|
344
|
+
batch_size: int = 64,
|
|
345
|
+
progress_cb: Callable[[int, int], None] | None = None,
|
|
346
|
+
) -> list[list[SpanMatch]]:
|
|
347
|
+
"""Speicherschonende Batch-Verarbeitung mit spaCy nlp.pipe (überspringt reine Zahlen/Codes)."""
|
|
348
|
+
if not self.available or not config.use_ner:
|
|
349
|
+
return [[] for _ in texts]
|
|
350
|
+
|
|
351
|
+
enabled = config.enabled_categories()
|
|
352
|
+
if not ({Category.NAME, Category.COMPANY, Category.LOCATION} & enabled):
|
|
353
|
+
return [[] for _ in texts]
|
|
354
|
+
|
|
355
|
+
total = len(texts)
|
|
356
|
+
results: list[list[SpanMatch]] = [[] for _ in range(total)]
|
|
357
|
+
|
|
358
|
+
# Nur Texte mit Buchstaben durch spaCy schicken (überspringt reine Zahlen, Codes, Daten)
|
|
359
|
+
active_indices: list[int] = []
|
|
360
|
+
active_texts: list[str] = []
|
|
361
|
+
for idx, t in enumerate(texts):
|
|
362
|
+
if len(t) >= 3 and _ALPHA_RE.search(t):
|
|
363
|
+
active_indices.append(idx)
|
|
364
|
+
active_texts.append(t)
|
|
365
|
+
|
|
366
|
+
if not active_texts:
|
|
367
|
+
if progress_cb:
|
|
368
|
+
progress_cb(total, total)
|
|
369
|
+
return results
|
|
370
|
+
|
|
371
|
+
step = max(24, batch_size // 2)
|
|
372
|
+
active_total = len(active_texts)
|
|
373
|
+
for pos, doc in enumerate(self.nlp.pipe(active_texts, batch_size=batch_size), start=1):
|
|
374
|
+
results[active_indices[pos - 1]] = self._extract_from_doc(doc, enabled)
|
|
375
|
+
if progress_cb and (pos % step == 0 or pos == active_total):
|
|
376
|
+
progress_cb(pos, active_total)
|
|
377
|
+
return results
|