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,810 @@
1
+ """Zentrale Schwärzungs-Engine: kombiniert Regeln, lokales Offline-NER, Memoization & Antragsteller-Schutz."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections import Counter
7
+ from typing import Any, Callable
8
+
9
+ from .detectors import run_rule_detectors
10
+ from .detectors_common import LEGAL_FORM_TAIL_RE
11
+ from .detectors_entities import matches_job_stem, normalize_job_token
12
+ from .lexicons import COMMON_FIRST_NAMES, COMMON_SURNAMES, MAJOR_GERMAN_CITIES, NON_NAME_WORDS, ORG_NOISE_WORDS
13
+ from .models import (
14
+ CATEGORY_LABELS_DE,
15
+ CATEGORY_PRIORITY,
16
+ Category,
17
+ CellResult,
18
+ Confidence,
19
+ RedactionConfig,
20
+ ScanSummary,
21
+ SpanMatch,
22
+ )
23
+ from .ner_engine import LocalGermanNER
24
+ from .whitelist import ApplicantWhitelist, ProtectedSpan
25
+
26
+ _JSON_KEY_TOKEN_RE = re.compile(r'(?<=[{,])\s*"([A-Za-z0-9_\-äöüÄÖÜß]{1,50})"\s*:')
27
+
28
+
29
+ def _find_json_key_spans(text: str) -> list[tuple[int, int]]:
30
+ """Liefert Zeichenbereiche von JSON-Feldnamen (z. B. "berater":null), damit Schlüssel nicht geschwärzt werden."""
31
+ if '":' not in text and '" :' not in text:
32
+ return []
33
+ return [(m.start(1), m.end(1)) for m in _JSON_KEY_TOKEN_RE.finditer(text)]
34
+
35
+
36
+ def _clone_match(m: SpanMatch, match_id: str = "") -> SpanMatch:
37
+ return SpanMatch(
38
+ start=m.start,
39
+ end=m.end,
40
+ text=m.text,
41
+ category=m.category,
42
+ confidence=m.confidence,
43
+ rule=m.rule,
44
+ reasons=list(m.reasons),
45
+ redacted=m.redacted,
46
+ protected=m.protected,
47
+ match_id=match_id,
48
+ )
49
+
50
+
51
+ def apply_redactions_to_text(
52
+ text: str,
53
+ matches: list[SpanMatch],
54
+ config: RedactionConfig,
55
+ ) -> str:
56
+ """Wendet alle als `redacted=True` markierten Spans sauber von hinten nach vorne an."""
57
+ if not text or not matches:
58
+ return text
59
+
60
+ active = [m for m in matches if m.redacted and not m.protected]
61
+ if not active:
62
+ return text
63
+
64
+ active.sort(key=lambda m: (m.start, -m.end))
65
+ parts: list[str] = []
66
+ cursor = 0
67
+ for m in active:
68
+ if m.start < cursor:
69
+ continue
70
+ parts.append(text[cursor:m.start])
71
+ parts.append(config.replacement_for(m.category))
72
+ cursor = m.end
73
+ parts.append(text[cursor:])
74
+ return "".join(parts)
75
+
76
+
77
+ class RedactionEngine:
78
+ """Orchestriert alle Erkennungsschichten, Konfliktauflösung, Memoization und Antragsteller-Whitelist."""
79
+
80
+ def __init__(self, ner: LocalGermanNER | None = None) -> None:
81
+ self.ner = ner if ner is not None else LocalGermanNER()
82
+
83
+ @staticmethod
84
+ def _spans_overlap(a_start: int, a_end: int, b_start: int, b_end: int) -> bool:
85
+ return a_start < b_end and b_start < a_end
86
+
87
+ def _resolve_overlaps(self, text: str, raw_matches: list[SpanMatch]) -> list[SpanMatch]:
88
+ """Löst überlappende Treffer deterministisch auf und bündelt übereinstimmende Gründe."""
89
+ if not raw_matches:
90
+ return []
91
+
92
+ text_len = len(text)
93
+ grouped: dict[tuple[int, int], list[SpanMatch]] = {}
94
+ for m in raw_matches:
95
+ if 0 <= m.start < m.end <= text_len:
96
+ grouped.setdefault((m.start, m.end), []).append(m)
97
+
98
+ deduped: list[SpanMatch] = []
99
+ for (start, end), group in grouped.items():
100
+ if len(group) == 1:
101
+ m0 = group[0]
102
+ deduped.append(SpanMatch(start, end, text[start:end], m0.category, m0.confidence, m0.rule, list(m0.reasons)))
103
+ continue
104
+
105
+ group.sort(
106
+ key=lambda x: (1 if x.confidence == Confidence.HIGH else 0, CATEGORY_PRIORITY.get(x.category, 0)),
107
+ reverse=True,
108
+ )
109
+ best = group[0]
110
+ all_reasons = list(dict.fromkeys(r for item in group for r in item.reasons))
111
+ conf = Confidence.HIGH if (any(x.confidence == Confidence.HIGH for x in group) or len(all_reasons) >= 2) else Confidence.REVIEW
112
+ deduped.append(SpanMatch(start, end, text[start:end], best.category, conf, best.rule, all_reasons))
113
+
114
+ deduped.sort(
115
+ key=lambda m: (CATEGORY_PRIORITY.get(m.category, 0), 1 if m.confidence == Confidence.HIGH else 0, m.end - m.start, -m.start),
116
+ reverse=True,
117
+ )
118
+
119
+ accepted: list[SpanMatch] = []
120
+ for cand in deduped:
121
+ overlapping = [a for a in accepted if self._spans_overlap(cand.start, cand.end, a.start, a.end)]
122
+ if not overlapping:
123
+ accepted.append(cand)
124
+ continue
125
+
126
+ for acc in overlapping:
127
+ if acc.start <= cand.start and cand.end <= acc.end:
128
+ for r in cand.reasons:
129
+ if r not in acc.reasons:
130
+ acc.reasons.append(r)
131
+ if cand.confidence == Confidence.HIGH:
132
+ acc.confidence = Confidence.HIGH
133
+ elif (
134
+ acc.category == Category.NAME
135
+ and cand.category == Category.NAME
136
+ and (cand.end - cand.start) > (acc.end - acc.start)
137
+ ):
138
+ acc.start = min(acc.start, cand.start)
139
+ acc.end = max(acc.end, cand.end)
140
+ acc.text = text[acc.start:acc.end]
141
+ for r in cand.reasons:
142
+ if r not in acc.reasons:
143
+ acc.reasons.append(r)
144
+ if cand.confidence == Confidence.HIGH:
145
+ acc.confidence = Confidence.HIGH
146
+
147
+ accepted.sort(key=lambda m: m.start)
148
+
149
+ merged: list[SpanMatch] = []
150
+ for m in accepted:
151
+ if (
152
+ merged
153
+ and merged[-1].category == Category.NAME
154
+ and m.category == Category.NAME
155
+ and text[merged[-1].end:m.start] == " "
156
+ ):
157
+ prev = merged[-1]
158
+ prev.end = m.end
159
+ prev.text = text[prev.start:prev.end]
160
+ for r in m.reasons:
161
+ if r not in prev.reasons:
162
+ prev.reasons.append(r)
163
+ if m.confidence == Confidence.HIGH:
164
+ prev.confidence = Confidence.HIGH
165
+ else:
166
+ merged.append(m)
167
+
168
+ return merged
169
+
170
+ @staticmethod
171
+ def _is_meaningful_remainder(piece: str) -> bool:
172
+ """Prüft, ob nach dem Herausschneiden eines geschützten Antragsteller-Spans noch ein echter Name übrig bleibt."""
173
+ clean = piece.strip(" \t\r\n.,:;!?()[]{}\"'<>/\\|-")
174
+ if len(clean) < 2 or "<" in clean or ">" in clean or "=" in clean:
175
+ return False
176
+ if not any(ch.isalpha() for ch in clean):
177
+ return False
178
+ tokens = [t.strip(".,:;!?()[]{}\"'").lower() for t in clean.split() if t.strip()]
179
+ if not tokens:
180
+ return False
181
+ return not all(
182
+ t in NON_NAME_WORDS or t in {"herr", "herrn", "frau", "hr", "fr", "dr", "prof"}
183
+ for t in tokens
184
+ )
185
+
186
+ def _apply_whitelist(
187
+ self,
188
+ matches: list[SpanMatch],
189
+ protected_spans: list[ProtectedSpan],
190
+ whitelist: ApplicantWhitelist,
191
+ ) -> list[SpanMatch]:
192
+ if not protected_spans:
193
+ return matches
194
+
195
+ result: list[SpanMatch] = []
196
+ covered_protected_idx: set[int] = set()
197
+ emitted_protected_idx: set[int] = set()
198
+
199
+ for m in matches:
200
+ matched_ps_idx: int | None = None
201
+ overlapping_eligible: list[tuple[int, ProtectedSpan]] = []
202
+ for idx, ps in enumerate(protected_spans):
203
+ if m.category == Category.NAME:
204
+ if (ps.start <= m.start and m.end <= ps.end) or (
205
+ self._spans_overlap(m.start, m.end, ps.start, ps.end) and whitelist.is_name_of_applicant(m.text)
206
+ ):
207
+ matched_ps_idx = idx
208
+ break
209
+ if self._spans_overlap(m.start, m.end, ps.start, ps.end):
210
+ overlapping_eligible.append((idx, ps))
211
+ elif ps.reason.startswith("Ausnahme-Liste"):
212
+ if ps.start <= m.start and m.end <= ps.end:
213
+ matched_ps_idx = idx
214
+ break
215
+ if self._spans_overlap(m.start, m.end, ps.start, ps.end):
216
+ overlapping_eligible.append((idx, ps))
217
+
218
+ if matched_ps_idx is not None:
219
+ ps = protected_spans[matched_ps_idx]
220
+ covered_protected_idx.add(matched_ps_idx)
221
+ m.protected = True
222
+ m.redacted = False
223
+ m.reasons.append(f"Geschützt: {ps.reason}")
224
+ result.append(m)
225
+ continue
226
+
227
+ if overlapping_eligible:
228
+ # Größerer Treffer (z. B. durch HTML-Tag oder Nachbarwort) enthält geschützten Antragsteller:
229
+ # Antragsteller sauber herausschneiden & schützen, nur echte Rest-Namen behalten.
230
+ overlapping_eligible.sort(key=lambda item: item[1].start)
231
+ cursor = m.start
232
+ for idx, ps in overlapping_eligible:
233
+ if ps.start > cursor:
234
+ raw_rem = m.text[cursor - m.start : ps.start - m.start]
235
+ if self._is_meaningful_remainder(raw_rem):
236
+ lead = len(raw_rem) - len(raw_rem.lstrip(" \t\r\n.,:;!?()[]{}\"'<>/\\|-"))
237
+ trail = len(raw_rem) - len(raw_rem.rstrip(" \t\r\n.,:;!?()[]{}\"'<>/\\|-"))
238
+ rs = cursor + lead
239
+ re_ = ps.start - trail
240
+ if rs < re_:
241
+ result.append(
242
+ SpanMatch(
243
+ start=rs,
244
+ end=re_,
245
+ text=m.text[rs - m.start : re_ - m.start],
246
+ category=m.category,
247
+ confidence=m.confidence,
248
+ rule=m.rule,
249
+ reasons=list(m.reasons),
250
+ redacted=m.redacted,
251
+ protected=False,
252
+ )
253
+ )
254
+ covered_protected_idx.add(idx)
255
+ if idx not in emitted_protected_idx:
256
+ emitted_protected_idx.add(idx)
257
+ result.append(
258
+ SpanMatch(
259
+ start=ps.start,
260
+ end=ps.end,
261
+ text=ps.text,
262
+ category=Category.NAME,
263
+ confidence=Confidence.HIGH,
264
+ rule=ps.reason,
265
+ reasons=[f"Geschützt: {ps.reason}"],
266
+ redacted=False,
267
+ protected=True,
268
+ )
269
+ )
270
+ cursor = max(cursor, ps.end)
271
+
272
+ if cursor < m.end:
273
+ raw_rem = m.text[cursor - m.start :]
274
+ if self._is_meaningful_remainder(raw_rem):
275
+ lead = len(raw_rem) - len(raw_rem.lstrip(" \t\r\n.,:;!?()[]{}\"'<>/\\|-"))
276
+ trail = len(raw_rem) - len(raw_rem.rstrip(" \t\r\n.,:;!?()[]{}\"'<>/\\|-"))
277
+ rs = cursor + lead
278
+ re_ = m.end - trail
279
+ if rs < re_:
280
+ result.append(
281
+ SpanMatch(
282
+ start=rs,
283
+ end=re_,
284
+ text=m.text[rs - m.start : re_ - m.start],
285
+ category=m.category,
286
+ confidence=m.confidence,
287
+ rule=m.rule,
288
+ reasons=list(m.reasons),
289
+ redacted=m.redacted,
290
+ protected=False,
291
+ )
292
+ )
293
+ continue
294
+
295
+ result.append(m)
296
+
297
+ for idx, ps in enumerate(protected_spans):
298
+ if idx in covered_protected_idx:
299
+ continue
300
+ if any(self._spans_overlap(ps.start, ps.end, r.start, r.end) for r in result):
301
+ continue
302
+ result.append(
303
+ SpanMatch(
304
+ start=ps.start,
305
+ end=ps.end,
306
+ text=ps.text,
307
+ category=Category.NAME,
308
+ confidence=Confidence.HIGH,
309
+ rule=ps.reason,
310
+ reasons=[f"Geschützt: {ps.reason}"],
311
+ redacted=False,
312
+ protected=True,
313
+ )
314
+ )
315
+
316
+ result.sort(key=lambda m: m.start)
317
+ return result
318
+
319
+ def _propagate_cell_names(
320
+ self,
321
+ text: str,
322
+ resolved: list[SpanMatch],
323
+ whitelist: ApplicantWhitelist,
324
+ json_key_spans: list[tuple[int, int]],
325
+ ) -> list[SpanMatch]:
326
+ """Überträgt in derselben Zelle bereits erkannte Namen konsistent auf weitere Vorkommen (auch ALL-CAPS)."""
327
+ candidate_tokens: dict[str, str] = {}
328
+ for m in resolved:
329
+ if m.category != Category.NAME:
330
+ continue
331
+ for raw_tok in m.text.split():
332
+ tok = raw_tok.strip(".,:;!?()[]{}\"'")
333
+ if not tok:
334
+ continue
335
+ low = tok.lower()
336
+ min_len = 3 if (low in COMMON_FIRST_NAMES or low in COMMON_SURNAMES) else 4
337
+ if len(tok) < min_len:
338
+ continue
339
+ if not tok.replace("-", "").isalpha():
340
+ continue
341
+ if (
342
+ low in NON_NAME_WORDS
343
+ or low in MAJOR_GERMAN_CITIES
344
+ or low in ORG_NOISE_WORDS
345
+ or LEGAL_FORM_TAIL_RE.fullmatch(tok)
346
+ or matches_job_stem(normalize_job_token(tok))
347
+ or whitelist.is_name_of_applicant(tok)
348
+ ):
349
+ continue
350
+ candidate_tokens.setdefault(low, tok)
351
+
352
+ if not candidate_tokens:
353
+ return resolved
354
+
355
+ extra: list[SpanMatch] = []
356
+ for low_tok, orig_tok in candidate_tokens.items():
357
+ pat = re.compile(rf"\b{re.escape(low_tok)}\b", re.IGNORECASE)
358
+ for hit in pat.finditer(text):
359
+ s, e = hit.start(), hit.end()
360
+ seg = text[s:e]
361
+ # Nur großgeschriebene / ALL-CAPS Vorkommen übernehmen (verhindert kleingeschriebene Verben/Wörter)
362
+ if not seg[0].isupper():
363
+ continue
364
+ if json_key_spans and any(ks <= s and e <= ke for ks, ke in json_key_spans):
365
+ continue
366
+ if any(self._spans_overlap(s, e, ex.start, ex.end) for ex in resolved):
367
+ continue
368
+ if any(self._spans_overlap(s, e, ex.start, ex.end) for ex in extra):
369
+ continue
370
+ extra.append(
371
+ SpanMatch(
372
+ start=s,
373
+ end=e,
374
+ text=seg,
375
+ category=Category.NAME,
376
+ confidence=Confidence.HIGH,
377
+ rule=f"Name (Wiederholung im selben Text: {orig_tok})",
378
+ )
379
+ )
380
+
381
+ if not extra:
382
+ return resolved
383
+
384
+ combined = sorted(resolved + extra, key=lambda m: m.start)
385
+ # Direkt benachbarte NAME-Treffer (z. B. „CELESTE“ + „MUSTERMANN“) zu einem sauberen Block verschmelzen
386
+ merged: list[SpanMatch] = []
387
+ for m in combined:
388
+ if (
389
+ merged
390
+ and merged[-1].category == Category.NAME
391
+ and m.category == Category.NAME
392
+ and text[merged[-1].end:m.start] == " "
393
+ ):
394
+ prev = merged[-1]
395
+ prev.end = m.end
396
+ prev.text = text[prev.start:prev.end]
397
+ for r in m.reasons:
398
+ if r not in prev.reasons:
399
+ prev.reasons.append(r)
400
+ if m.confidence == Confidence.HIGH:
401
+ prev.confidence = Confidence.HIGH
402
+ else:
403
+ merged.append(m)
404
+ return merged
405
+
406
+ def analyze_cell(
407
+ self,
408
+ text: str,
409
+ config: RedactionConfig,
410
+ row_index: int = 0,
411
+ column: str = "",
412
+ ner_matches: list[SpanMatch] | None = None,
413
+ whitelist: ApplicantWhitelist | None = None,
414
+ ) -> CellResult:
415
+ """Analysiert eine einzelne Zelle vollständig und liefert Original, Schwärzung & alle Fundstellen."""
416
+ if not text or not text.strip():
417
+ return CellResult(row_index=row_index, column=column, original=text, redacted=text, matches=[])
418
+
419
+ wl = whitelist or ApplicantWhitelist(
420
+ first_name=config.applicant_first_name,
421
+ last_name=config.applicant_last_name,
422
+ extra_terms=config.extra_whitelist,
423
+ )
424
+
425
+ raw_matches = run_rule_detectors(text, config)
426
+ if ner_matches is not None:
427
+ raw_matches.extend(ner_matches)
428
+ elif config.use_ner and self.ner.available:
429
+ raw_matches.extend(self.ner.detect(text, config))
430
+
431
+ json_key_spans = _find_json_key_spans(text)
432
+ if json_key_spans:
433
+ raw_matches = [
434
+ m
435
+ for m in raw_matches
436
+ if m.category == Category.MANUAL
437
+ or not any(ks <= m.start and m.end <= ke for ks, ke in json_key_spans)
438
+ ]
439
+
440
+ resolved = self._resolve_overlaps(text, raw_matches)
441
+
442
+ # Intra-Zellen-Namens-Propagation: Wenn ein Name einmal im Text erkannt wurde (z. B. „Celeste“
443
+ # nach „Liebe Grüße“), werden alle weiteren Vorkommen desselben Namens (auch GROSSBUCHSTABEN wie „CELESTE“)
444
+ # im selben Text zuverlässig mitgeschwärzt und mit angrenzenden Namen verschmolzen!
445
+ if config.redact_names and resolved:
446
+ resolved = self._propagate_cell_names(text, resolved, wl, json_key_spans)
447
+
448
+ for m in resolved:
449
+ m.redacted = True if m.confidence == Confidence.HIGH else config.redact_uncertain_by_default
450
+
451
+ protected_spans = wl.find_protected_spans(text)
452
+ final_matches = self._apply_whitelist(resolved, protected_spans, wl)
453
+
454
+ for idx, m in enumerate(final_matches):
455
+ m.match_id = f"r{row_index}_{column}_{idx}"
456
+
457
+ redacted_text = apply_redactions_to_text(text, final_matches, config)
458
+ return CellResult(row_index=row_index, column=column, original=text, redacted=redacted_text, matches=final_matches)
459
+
460
+ def scan_rows(
461
+ self,
462
+ headers: list[str],
463
+ rows: list[dict[str, str]],
464
+ config: RedactionConfig,
465
+ encoding: str = "utf-8",
466
+ delimiter: str = ";",
467
+ cached_ner_map: dict[tuple[int, str], list[SpanMatch]] | None = None,
468
+ out_ner_map: dict[tuple[int, str], list[SpanMatch]] | None = None,
469
+ out_ner_by_text: dict[str, list[SpanMatch]] | None = None,
470
+ progress_cb: Callable[[dict[str, Any]], None] | None = None,
471
+ ) -> tuple[list[dict[str, str]], list[CellResult], ScanSummary]:
472
+ """Scannt alle ausgewählten Spalten mit Text-Deduplizierung (NER + Regel-Memoization)."""
473
+ target_columns = self._select_columns(headers, config.columns)
474
+ whitelist = ApplicantWhitelist(
475
+ first_name=config.applicant_first_name,
476
+ last_name=config.applicant_last_name,
477
+ extra_terms=config.extra_whitelist,
478
+ )
479
+
480
+ # Einzigartige nicht-leere Texte sammeln -> spart sowohl spaCy-Zeit als auch Regel-CPU & RAM!
481
+ unique_texts: list[str] = []
482
+ text_to_uid: dict[str, int] = {}
483
+ non_empty_cells = 0
484
+ for row in rows:
485
+ for col in target_columns:
486
+ val = row.get(col, "") or ""
487
+ if val.strip():
488
+ non_empty_cells += 1
489
+ if val not in text_to_uid:
490
+ text_to_uid[val] = len(unique_texts)
491
+ unique_texts.append(val)
492
+
493
+ ner_active = bool(cached_ner_map is None and config.use_ner and self.ner.available and unique_texts)
494
+ if progress_cb:
495
+ progress_cb({
496
+ "phase": "ner" if ner_active else "rules",
497
+ "phase_label": (
498
+ f"Lokale Sprach-KI ({self.ner.model_name}) analysiert Texte…"
499
+ if ner_active
500
+ else "Regel-Detektoren & Antragsteller-Schutz laufen…"
501
+ ),
502
+ "percent": 10,
503
+ "processed": 0,
504
+ "total": len(rows),
505
+ "redactions_so_far": 0,
506
+ "detail": f"{len(rows):,} Zeilen · {len(unique_texts):,} einzigartige Texte".replace(",", "."),
507
+ })
508
+
509
+ ner_by_text: dict[str, list[SpanMatch]] = {}
510
+ if ner_active:
511
+ def _on_ner_progress(done_u: int, total_u: int) -> None:
512
+ if not progress_cb:
513
+ return
514
+ pct = 10 + int(54 * (done_u / max(1, total_u)))
515
+ progress_cb({
516
+ "phase": "ner",
517
+ "phase_label": f"Lokale Sprach-KI ({self.ner.model_name}) erkennt Namen, Orte & Firmen…",
518
+ "percent": min(64, pct),
519
+ "processed": done_u,
520
+ "total": total_u,
521
+ "redactions_so_far": 0,
522
+ "detail": f"{done_u:,} / {total_u:,} einzigartige Texte analysiert".replace(",", "."),
523
+ })
524
+
525
+ unique_ner = self.ner.detect_batch(
526
+ unique_texts,
527
+ config,
528
+ batch_size=64,
529
+ progress_cb=_on_ner_progress if progress_cb else None,
530
+ )
531
+ for txt, raw_m in zip(unique_texts, unique_ner):
532
+ if raw_m:
533
+ ner_by_text[txt] = raw_m
534
+ if out_ner_by_text is not None:
535
+ out_ner_by_text.update(ner_by_text)
536
+
537
+ # Regel- & Whitelist-Memoization pro einzigartigem Zellentext (massiver Speedup bei CRM-Wiederholungen!)
538
+ use_text_memo = cached_ner_map is None
539
+ analyzed_memo: dict[str, tuple[str, list[SpanMatch]]] = {}
540
+
541
+ redacted_rows: list[dict[str, str]] = []
542
+ cell_results: list[CellResult] = []
543
+ rows_with_findings: set[int] = set()
544
+ cat_counter: Counter[str] = Counter()
545
+ total_redactions = 0
546
+ high_redactions = 0
547
+ review_findings = 0
548
+ protected_hits = 0
549
+
550
+ total_rows_n = len(rows)
551
+ rules_start_pct = 65 if ner_active else 12
552
+ rules_span_pct = 96 - rules_start_pct
553
+ report_every = max(25, total_rows_n // 60) if total_rows_n else 1
554
+
555
+ for r_idx, row in enumerate(rows):
556
+ new_row = dict(row)
557
+ for col in target_columns:
558
+ val = row.get(col, "") or ""
559
+ if not val or not val.strip():
560
+ continue
561
+
562
+ if use_text_memo and val in analyzed_memo:
563
+ memo_redacted, memo_matches = analyzed_memo[val]
564
+ if memo_matches:
565
+ cloned_matches = [_clone_match(m, f"r{r_idx}_{col}_{i}") for i, m in enumerate(memo_matches)]
566
+ cell = CellResult(r_idx, col, val, memo_redacted, cloned_matches)
567
+ else:
568
+ cell = CellResult(r_idx, col, val, memo_redacted, [])
569
+ else:
570
+ if cached_ner_map is not None:
571
+ ner_list = [_clone_match(m) for m in cached_ner_map.get((r_idx, col), [])]
572
+ else:
573
+ raw_ner = ner_by_text.get(val)
574
+ ner_list = [_clone_match(m) for m in raw_ner] if raw_ner else []
575
+ if out_ner_map is not None and ner_list:
576
+ out_ner_map[(r_idx, col)] = [_clone_match(m) for m in ner_list]
577
+
578
+ cell = self.analyze_cell(
579
+ text=val,
580
+ config=config,
581
+ row_index=r_idx,
582
+ column=col,
583
+ ner_matches=ner_list,
584
+ whitelist=whitelist,
585
+ )
586
+ if use_text_memo:
587
+ analyzed_memo[val] = (cell.redacted, [_clone_match(m) for m in cell.matches])
588
+
589
+ new_row[col] = cell.redacted
590
+ if cell.matches:
591
+ cell_results.append(cell)
592
+ if any(not m.protected for m in cell.matches):
593
+ rows_with_findings.add(r_idx)
594
+ for m in cell.matches:
595
+ if m.protected:
596
+ protected_hits += 1
597
+ else:
598
+ if m.redacted:
599
+ total_redactions += 1
600
+ if m.confidence == Confidence.HIGH:
601
+ high_redactions += 1
602
+ elif m.confidence == Confidence.REVIEW:
603
+ review_findings += 1
604
+ cat_counter[CATEGORY_LABELS_DE.get(m.category, m.category.value)] += 1
605
+ redacted_rows.append(new_row)
606
+
607
+ if progress_cb and ((r_idx + 1) % report_every == 0 or r_idx + 1 == total_rows_n):
608
+ done_r = r_idx + 1
609
+ pct = rules_start_pct + int(rules_span_pct * (done_r / max(1, total_rows_n)))
610
+ progress_cb({
611
+ "phase": "rules",
612
+ "phase_label": "Prüfe Regeln, Kontodaten, Adressen, Ortschaften & Antragsteller-Schutz…",
613
+ "percent": min(96, pct),
614
+ "processed": done_r,
615
+ "total": total_rows_n,
616
+ "redactions_so_far": total_redactions,
617
+ "detail": f"{done_r:,} / {total_rows_n:,} Zeilen geprüft · {total_redactions:,} Schwärzungen".replace(",", "."),
618
+ })
619
+
620
+ if progress_cb:
621
+ progress_cb({
622
+ "phase": "finalizing",
623
+ "phase_label": "Bereite Live-Vorschau, Prüfbericht & Exporte vor…",
624
+ "percent": 98,
625
+ "processed": total_rows_n,
626
+ "total": total_rows_n,
627
+ "redactions_so_far": total_redactions,
628
+ "detail": f"{total_rows_n:,} Zeilen fertig · {total_redactions:,} aktive Schwärzungen".replace(",", "."),
629
+ })
630
+
631
+ summary = ScanSummary(
632
+ total_rows=len(rows),
633
+ scanned_columns=target_columns,
634
+ rows_with_findings=len(rows_with_findings),
635
+ total_redactions=total_redactions,
636
+ high_confidence_redactions=high_redactions,
637
+ review_findings=review_findings,
638
+ protected_applicant_hits=protected_hits,
639
+ by_category=dict(cat_counter.most_common()),
640
+ ner_active=bool(config.use_ner and self.ner.available),
641
+ ner_model_name=self.ner.model_name,
642
+ encoding=encoding,
643
+ delimiter=delimiter,
644
+ )
645
+ return redacted_rows, cell_results, summary
646
+
647
+ @staticmethod
648
+ def _select_columns(headers: list[str], requested: list[str] | None) -> list[str]:
649
+ if requested:
650
+ valid = [c for c in requested if c in headers]
651
+ if valid:
652
+ return valid
653
+ selected = [h for h in headers if _is_recommended_scan_column(h)]
654
+ if selected:
655
+ return selected
656
+ skip_names = {"datum", "date", "zeit", "timestamp", "id", "bestellung", "bestellnummer", "kunde", "kundennummer", "art", "typ", "status"}
657
+ non_id = [h for h in headers if h.strip().lower() not in skip_names]
658
+ return non_id if non_id else list(headers)
659
+
660
+
661
+ _FREE_TEXT_HEADERS = frozenset({
662
+ "notiz", "notizen", "nachricht", "nachrichten", "text", "kommentar", "kommentare",
663
+ "bemerkung", "bemerkungen", "beschreibung", "inhalt", "betreff", "subject", "body", "message", "notes",
664
+ })
665
+
666
+ _PII_HEADER_KEYWORDS: tuple[tuple[str, str], ...] = (
667
+ ("vorname", "Vorname"), ("nachname", "Nachname"), ("familienname", "Nachname"),
668
+ ("kundenname", "Kundenname"), ("ansprechpartner", "Ansprechpartner"),
669
+ ("sachbearbeiter", "Sachbearbeiter"), ("mitarbeiter", "Mitarbeiter"),
670
+ ("absender", "Absender"), ("empfänger", "Empfänger"), ("empfaenger", "Empfänger"),
671
+ ("kontoinhaber", "Kontoinhaber"), ("email", "E-Mail"), ("e-mail", "E-Mail"),
672
+ ("mail", "E-Mail"), ("telefon", "Telefonnummer"), ("rufnummer", "Telefonnummer"),
673
+ ("mobil", "Mobilnummer"), ("handy", "Handynummer"), ("fax", "Faxnummer"),
674
+ ("iban", "IBAN"), ("kontonummer", "Kontonummer"), ("bankverbindung", "Kontodaten"),
675
+ ("adresse", "Adresse"), ("anschrift", "Adresse"), ("straße", "Straße"), ("strasse", "Straße"),
676
+ ("wohnort", "Wohnort"), ("postleitzahl", "PLZ"), ("geburtsdatum", "Geburtsdatum"),
677
+ ("geburtstag", "Geburtsdatum"), ("kennzeichen", "Kfz-Kennzeichen"),
678
+ ("steuernummer", "Steuernummer"), ("steuer-id", "Steuer-ID"), ("ust-id", "USt-IdNr"),
679
+ ("firma", "Firmenname"), ("unternehmen", "Firmenname"),
680
+ )
681
+
682
+ _EXACT_PII_HEADERS: dict[str, str] = {
683
+ "name": "Name", "tel": "Telefonnummer", "tel.": "Telefonnummer", "plz": "PLZ",
684
+ "ort": "Ort", "stadt": "Stadt", "bank": "Bank", "kfz": "Kfz-Kennzeichen",
685
+ "ip": "IP-Adresse", "ip-adresse": "IP-Adresse",
686
+ }
687
+
688
+ _SAMPLE_EMAIL_RE = re.compile(r"\b[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,15}\b")
689
+ _SAMPLE_IBAN_RE = re.compile(r"\bDE\d{2}[ \t]?(?:\d{4}[ \t]?){4}\d{2}\b", re.IGNORECASE)
690
+ _SAMPLE_PHONE_RE = re.compile(r"(?:\+49|0049|01[567]\d|0[2-9]\d{1,4})[ \t/\-]+\d{3,}")
691
+
692
+
693
+ def _pii_header_reason(header: str) -> str | None:
694
+ hl = header.strip().lower()
695
+ if hl in _EXACT_PII_HEADERS:
696
+ return f"Spaltenname „{header}“ ({_EXACT_PII_HEADERS[hl]})"
697
+ for kw, label in _PII_HEADER_KEYWORDS:
698
+ if kw in hl:
699
+ return f"Spaltenname „{header}“ ({label})"
700
+ return None
701
+
702
+
703
+ def _is_recommended_scan_column(header: str) -> bool:
704
+ hl = header.strip().lower()
705
+ return hl in _FREE_TEXT_HEADERS or _pii_header_reason(header) is not None
706
+
707
+
708
+ def detect_pii_warning_columns(headers: list[str], rows: list[dict[str, str]], sample_limit: int = 40) -> dict[str, str]:
709
+ """Prüft Überschriften & Beispielwerte auf mögliche personenbezogene Daten (für UI-Warnung bei Abwahl)."""
710
+ warnings: dict[str, str] = {}
711
+ sample = rows[:sample_limit]
712
+ for h in headers:
713
+ reason = _pii_header_reason(h)
714
+ if reason:
715
+ warnings[h] = reason
716
+ continue
717
+ for row in sample:
718
+ val = (row.get(h, "") or "").strip()
719
+ if not val:
720
+ continue
721
+ if "@" in val and _SAMPLE_EMAIL_RE.search(val):
722
+ warnings[h] = f"Enthält E-Mail-Adressen in „{h}“"
723
+ break
724
+ if _SAMPLE_IBAN_RE.search(val):
725
+ warnings[h] = f"Enthält IBANs in „{h}“"
726
+ break
727
+ if _SAMPLE_PHONE_RE.search(val):
728
+ warnings[h] = f"Enthält Telefonnummern in „{h}“"
729
+ break
730
+ return warnings
731
+
732
+
733
+ def run_residual_pii_check(
734
+ redacted_rows: list[dict[str, str]],
735
+ target_columns: list[str],
736
+ config: RedactionConfig,
737
+ cell_lookup: dict[tuple[int, str], CellResult],
738
+ max_samples: int = 25,
739
+ ) -> dict[str, Any]:
740
+ """Zweiter Kontroll-Durchlauf über die fertige geschwärzte Ausgabe (mit Text-Memoization)."""
741
+ check_cfg = RedactionConfig(
742
+ applicant_first_name=config.applicant_first_name,
743
+ applicant_last_name=config.applicant_last_name,
744
+ extra_whitelist=list(config.extra_whitelist),
745
+ redact_names=False,
746
+ redact_addresses=config.redact_addresses,
747
+ redact_house_numbers=False,
748
+ redact_postal_codes=False,
749
+ redact_locations=False,
750
+ redact_bank=config.redact_bank,
751
+ redact_job_titles=False,
752
+ redact_amounts=False,
753
+ redact_phones=config.redact_phones,
754
+ redact_emails=config.redact_emails,
755
+ redact_websites=False,
756
+ redact_ip_addresses=config.redact_ip_addresses,
757
+ redact_birthdates=config.redact_birthdates,
758
+ redact_license_plates=config.redact_license_plates,
759
+ redact_tax_ids=config.redact_tax_ids,
760
+ redact_companies=False,
761
+ use_ner=False,
762
+ )
763
+ wl = ApplicantWhitelist(
764
+ first_name=config.applicant_first_name,
765
+ last_name=config.applicant_last_name,
766
+ extra_terms=config.extra_whitelist,
767
+ )
768
+
769
+ residual_count = 0
770
+ samples: list[dict[str, Any]] = []
771
+ hits_cache: dict[str, list[SpanMatch]] = {}
772
+
773
+ for r_idx, row in enumerate(redacted_rows):
774
+ for col in target_columns:
775
+ val = row.get(col, "") or ""
776
+ if not val.strip():
777
+ continue
778
+ hits = hits_cache.get(val)
779
+ if hits is None:
780
+ raw_hits = [h for h in run_rule_detectors(val, check_cfg) if h.confidence == Confidence.HIGH]
781
+ if raw_hits and wl.active:
782
+ prot_spans = wl.find_protected_spans(val)
783
+ if prot_spans:
784
+ raw_hits = [h for h in raw_hits if not any(ps.start <= h.start and h.end <= ps.end for ps in prot_spans)]
785
+ hits = raw_hits
786
+ hits_cache[val] = hits
787
+ if not hits:
788
+ continue
789
+
790
+ cell = cell_lookup.get((r_idx, col))
791
+ released_texts = {m.text.strip().lower() for m in (cell.matches if cell else []) if not m.redacted}
792
+ for h in hits:
793
+ if h.text.strip().lower() in released_texts:
794
+ continue
795
+ residual_count += 1
796
+ if len(samples) < max_samples:
797
+ samples.append({
798
+ "row": r_idx + 2,
799
+ "column": col,
800
+ "category": CATEGORY_LABELS_DE.get(h.category, h.category.value),
801
+ "text": h.text,
802
+ "rule": h.rule,
803
+ })
804
+
805
+ return {"count": residual_count, "samples": samples}
806
+
807
+
808
+ def recommend_default_columns(headers: list[str]) -> list[str]:
809
+ """Empfiehlt Standard-Spalten für die Auswahl in der Browser-Oberfläche."""
810
+ return RedactionEngine._select_columns(headers, None)