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,356 @@
1
+ """Lokale In-Place PDF-Einlesung & unwiderrufliche DSGVO-Schwärzung via PyMuPDF (100 % offline)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Any
7
+
8
+ from .csv_io import LoadedCSV
9
+ from .models import CellResult, RedactionConfig
10
+
11
+ _BLOCK_CHARS = frozenset("█▓▒░■▪● ")
12
+
13
+
14
+ def is_pdf_bytes(raw: bytes, filename: str = "") -> bool:
15
+ """Erkennt zuverlässig anhand Dateiendung oder PDF-Header (%PDF-), ob es sich um ein PDF handelt."""
16
+ if filename.lower().endswith(".pdf"):
17
+ return True
18
+ return raw.lstrip()[:5] == b"%PDF-"
19
+
20
+
21
+ def is_pdf_support_available() -> bool:
22
+ """Prüft ohne Seiteneffekte, ob PyMuPDF (fitz) lokal installiert ist."""
23
+ try:
24
+ import fitz # noqa: F401
25
+ return True
26
+ except ImportError:
27
+ return False
28
+
29
+
30
+ def _import_fitz() -> Any:
31
+ try:
32
+ import fitz
33
+ return fitz
34
+ except ImportError as exc:
35
+ raise RuntimeError(
36
+ "Für den PDF-Upload wird das lokale Paket 'pymupdf' benötigt. "
37
+ "Bitte einmalig im Terminal installieren: .venv/bin/python -m pip install pymupdf"
38
+ ) from exc
39
+
40
+
41
+ @dataclass
42
+ class PdfPageLayout:
43
+ """Extrahierter Text einer PDF-Seite inkl. exakter Zeichen-Koordinaten (1:1-Mapping)."""
44
+
45
+ page_index: int
46
+ width: float
47
+ height: float
48
+ text: str
49
+ char_bboxes: list[tuple[float, float, float, float] | None]
50
+ has_text: bool
51
+ has_images: bool
52
+
53
+
54
+ @dataclass
55
+ class PdfDocumentData:
56
+ """Eingelesenes PDF-Dokument inkl. Original-Bytes für verlustfreien Layout-Export."""
57
+
58
+ raw_bytes: bytes
59
+ page_count: int
60
+ pages: list[PdfPageLayout]
61
+ image_only_pages: list[int] # 1-basierte Seitenzahlen ohne durchsuchbaren Text (reine Scans)
62
+ pages_with_text: int
63
+ loaded: LoadedCSV
64
+
65
+
66
+ def extract_pdf_document(raw_bytes: bytes) -> PdfDocumentData:
67
+ """Liest ein PDF zeichengenau inkl. Bounding-Boxes ein und erzeugt eine seitenweise Tabellen-Sicht."""
68
+ fitz = _import_fitz()
69
+ try:
70
+ doc = fitz.open(stream=raw_bytes, filetype="pdf")
71
+ except Exception as exc: # noqa: BLE001
72
+ raise ValueError(f"PDF konnte nicht geöffnet werden: {exc}") from exc
73
+
74
+ try:
75
+ if doc.is_encrypted and not doc.authenticate(""):
76
+ raise ValueError(
77
+ "Das PDF ist passwortgeschützt und kann ohne Entsperrung nicht verarbeitet werden."
78
+ )
79
+ if len(doc) == 0:
80
+ raise ValueError("Das hochgeladene PDF enthält keine Seiten.")
81
+
82
+ pages: list[PdfPageLayout] = []
83
+ image_only_pages: list[int] = []
84
+ rows: list[dict[str, str]] = []
85
+
86
+ for page_idx, page in enumerate(doc):
87
+ raw_dict = page.get_text("rawdict", sort=True)
88
+ chars: list[str] = []
89
+ bboxes: list[tuple[float, float, float, float] | None] = []
90
+
91
+ for block in raw_dict.get("blocks", []):
92
+ if block.get("type") != 0:
93
+ continue
94
+ if chars and chars[-1] != "\n":
95
+ chars.append("\n")
96
+ bboxes.append(None)
97
+
98
+ for line_idx, line in enumerate(block.get("lines", [])):
99
+ if line_idx > 0 and chars and chars[-1] != "\n":
100
+ chars.append("\n")
101
+ bboxes.append(None)
102
+
103
+ prev_x1: float | None = None
104
+ for span in line.get("spans", []):
105
+ span_chars = span.get("chars") or []
106
+ if not span_chars:
107
+ continue
108
+ font_size = float(span.get("size") or 10.0)
109
+ first_bbox = span_chars[0].get("bbox")
110
+ first_ch = (span_chars[0].get("c") or "").replace("\u00a0", " ")
111
+ if (
112
+ prev_x1 is not None
113
+ and first_bbox is not None
114
+ and len(first_bbox) == 4
115
+ and (float(first_bbox[0]) - prev_x1) > max(1.5, font_size * 0.22)
116
+ and chars
117
+ and chars[-1] not in (" ", "\n", "\t")
118
+ and not first_ch.startswith((" ", "\t", "\n"))
119
+ ):
120
+ chars.append(" ")
121
+ bboxes.append(None)
122
+
123
+ for c in span_chars:
124
+ ch_raw = c.get("c", "")
125
+ if not ch_raw:
126
+ continue
127
+ ch_norm = ch_raw.replace("\r", "").replace("\u00a0", " ")
128
+ if not ch_norm:
129
+ continue
130
+ raw_bb = c.get("bbox")
131
+ bb: tuple[float, float, float, float] | None = (
132
+ (float(raw_bb[0]), float(raw_bb[1]), float(raw_bb[2]), float(raw_bb[3]))
133
+ if raw_bb and len(raw_bb) == 4
134
+ else None
135
+ )
136
+ for single in ch_norm:
137
+ chars.append(single)
138
+ bboxes.append(bb)
139
+ if bb is not None:
140
+ prev_x1 = bb[2]
141
+
142
+ page_text = "".join(chars)
143
+ has_text = bool(page_text.strip())
144
+ has_images = bool(page.get_images(full=False))
145
+ if not has_text:
146
+ image_only_pages.append(page_idx + 1)
147
+
148
+ rect = page.rect
149
+ pages.append(
150
+ PdfPageLayout(
151
+ page_index=page_idx,
152
+ width=float(rect.width),
153
+ height=float(rect.height),
154
+ text=page_text,
155
+ char_bboxes=bboxes,
156
+ has_text=has_text,
157
+ has_images=has_images,
158
+ )
159
+ )
160
+ rows.append({"Seite": f"Seite {page_idx + 1}", "Text": page_text})
161
+
162
+ pages_with_text = sum(1 for p in pages if p.has_text)
163
+ loaded = LoadedCSV(
164
+ headers=["Seite", "Text"],
165
+ rows=rows,
166
+ encoding="pdf",
167
+ delimiter=";",
168
+ )
169
+ return PdfDocumentData(
170
+ raw_bytes=raw_bytes,
171
+ page_count=len(pages),
172
+ pages=pages,
173
+ image_only_pages=image_only_pages,
174
+ pages_with_text=pages_with_text,
175
+ loaded=loaded,
176
+ )
177
+ finally:
178
+ doc.close()
179
+
180
+
181
+ def _merge_span_bboxes(
182
+ char_bboxes: list[tuple[float, float, float, float] | None],
183
+ start: int,
184
+ end: int,
185
+ ) -> list[tuple[float, float, float, float]]:
186
+ """Fasst zusammenhängende Zeichen-Bounding-Boxes je visueller Zeile zu präzisen Schwärzungs-Rechtecken zusammen."""
187
+ valid: list[tuple[float, float, float, float]] = []
188
+ slice_end = min(end, len(char_bboxes))
189
+ for bb in char_bboxes[max(0, start) : slice_end]:
190
+ if bb is not None and bb[2] > bb[0] and bb[3] > bb[1]:
191
+ valid.append(bb)
192
+ if not valid:
193
+ return []
194
+
195
+ merged: list[list[float]] = []
196
+ for x0, y0, x1, y1 in valid:
197
+ if not merged:
198
+ merged.append([x0, y0, x1, y1])
199
+ continue
200
+ cur = merged[-1]
201
+ cur_h = max(1.0, cur[3] - cur[1])
202
+ cur_cy = (cur[1] + cur[3]) * 0.5
203
+ new_cy = (y0 + y1) * 0.5
204
+ same_line = abs(new_cy - cur_cy) <= max(4.0, cur_h * 0.55) and x0 >= cur[0] - 4.0
205
+ if same_line:
206
+ cur[0] = min(cur[0], x0)
207
+ cur[1] = min(cur[1], y0)
208
+ cur[2] = max(cur[2], x1)
209
+ cur[3] = max(cur[3], y1)
210
+ else:
211
+ merged.append([x0, y0, x1, y1])
212
+
213
+ # Vertikal minimal einrücken, damit eng gesetzte Nachbarzeilen nicht versehentlich gelöscht werden
214
+ rects: list[tuple[float, float, float, float]] = []
215
+ for x0, y0, x1, y1 in merged:
216
+ h = y1 - y0
217
+ inset_y = min(1.0, h * 0.08) if h > 4.0 else 0.0
218
+ ry0 = y0 + inset_y
219
+ ry1 = y1 - inset_y
220
+ if ry1 <= ry0 + 0.5:
221
+ ry0, ry1 = y0, y1
222
+ rects.append((max(0.0, x0 - 0.6), ry0, x1 + 0.6, ry1))
223
+ return rects
224
+
225
+
226
+ def _resolve_pdf_redaction_label(category_value: str, config: RedactionConfig) -> str:
227
+ """Ermittelt die optionale weiße Aufschrift auf dem schwarzen PDF-Schwärzungsbalken."""
228
+ if config.use_typed_placeholders:
229
+ return f"[{category_value}]"
230
+ repl = (config.replacement or "").strip()
231
+ if not repl or all(ch in _BLOCK_CHARS for ch in repl):
232
+ return ""
233
+ return repl
234
+
235
+
236
+ def _redact_fitz_page(
237
+ page: Any,
238
+ layout: PdfPageLayout,
239
+ cell: CellResult,
240
+ config: RedactionConfig,
241
+ fitz: Any,
242
+ ) -> int:
243
+ """Trägt alle aktiven Schwärzungen einer Seite ein, löscht überlappende Links und wendet sie unwiderruflich an."""
244
+ redaction_rects: list[Any] = []
245
+ applied_matches = 0
246
+
247
+ for m in cell.matches:
248
+ if not m.redacted or m.protected:
249
+ continue
250
+ boxes = _merge_span_bboxes(layout.char_bboxes, m.start, m.end)
251
+ if not boxes:
252
+ continue
253
+ applied_matches += 1
254
+ label = _resolve_pdf_redaction_label(m.category.value, config)
255
+ for idx, (x0, y0, x1, y1) in enumerate(boxes):
256
+ rect = fitz.Rect(x0, y0, x1, y1)
257
+ redaction_rects.append(rect)
258
+ rect_text = label if idx == 0 else ""
259
+ fontsize = max(5.5, min(10.0, rect.height * 0.72))
260
+ page.add_redact_annot(
261
+ rect,
262
+ text=rect_text,
263
+ fontname="helv",
264
+ fontsize=fontsize,
265
+ align=fitz.TEXT_ALIGN_CENTER,
266
+ fill=(0, 0, 0),
267
+ text_color=(1, 1, 1),
268
+ cross_out=False,
269
+ )
270
+
271
+ if not redaction_rects:
272
+ return 0
273
+
274
+ # Klickbare Link-Annotationen (z. B. mailto:, tel:, URLs) im geschwärzten Bereich mit entfernen!
275
+ for link in page.get_links():
276
+ link_from = link.get("from")
277
+ if not link_from:
278
+ continue
279
+ link_rect = fitz.Rect(link_from)
280
+ if any(link_rect.intersects(r) for r in redaction_rects):
281
+ try:
282
+ page.delete_link(link)
283
+ except Exception: # noqa: BLE001
284
+ pass
285
+
286
+ # Text physisch aus dem PDF-Content-Stream entfernen; Hintergrundbilder/Briefköpfe bleiben erhalten
287
+ try:
288
+ page.apply_redactions(
289
+ images=fitz.PDF_REDACT_IMAGE_NONE,
290
+ graphics=fitz.PDF_REDACT_LINE_ART_NONE,
291
+ )
292
+ except TypeError:
293
+ page.apply_redactions(images=fitz.PDF_REDACT_IMAGE_NONE)
294
+
295
+ return applied_matches
296
+
297
+
298
+ def apply_pdf_redactions_to_bytes(
299
+ pdf_doc: PdfDocumentData,
300
+ cell_results: list[CellResult],
301
+ config: RedactionConfig,
302
+ ) -> bytes:
303
+ """Wendet alle aktiven Schwärzungen unwiderruflich direkt im Original-PDF an und bereinigt Metadaten."""
304
+ fitz = _import_fitz()
305
+ doc = fitz.open(stream=pdf_doc.raw_bytes, filetype="pdf")
306
+ try:
307
+ cells_by_page = {
308
+ c.row_index: c
309
+ for c in cell_results
310
+ if c.column == "Text" and 0 <= c.row_index < len(pdf_doc.pages)
311
+ }
312
+ for page_idx, cell in cells_by_page.items():
313
+ _redact_fitz_page(doc[page_idx], pdf_doc.pages[page_idx], cell, config, fitz)
314
+
315
+ # Dokument-Metadaten DSGVO-konform bereinigen (kein Autor/Ersteller/Titel/Original-Dateiname)
316
+ doc.set_metadata(
317
+ {
318
+ "title": "",
319
+ "author": "",
320
+ "subject": "",
321
+ "keywords": "",
322
+ "creator": "",
323
+ "producer": "",
324
+ }
325
+ )
326
+ try:
327
+ doc.del_xml_metadata()
328
+ except Exception: # noqa: BLE001
329
+ pass
330
+
331
+ return bytes(doc.tobytes(garbage=4, deflate=True, clean=True))
332
+ finally:
333
+ doc.close()
334
+
335
+
336
+ def render_pdf_page_png(
337
+ pdf_doc: PdfDocumentData,
338
+ page_index: int,
339
+ cell: CellResult | None,
340
+ config: RedactionConfig,
341
+ mode: str = "redacted",
342
+ dpi: int = 130,
343
+ ) -> bytes:
344
+ """Rendert eine einzelne PDF-Seite (Original oder live geschwärzt) als PNG für die Browser-Vorschau."""
345
+ if page_index < 0 or page_index >= len(pdf_doc.pages):
346
+ raise ValueError(f"Ungültige PDF-Seite: {page_index + 1}")
347
+ fitz = _import_fitz()
348
+ doc = fitz.open(stream=pdf_doc.raw_bytes, filetype="pdf")
349
+ try:
350
+ page = doc[page_index]
351
+ if mode == "redacted" and cell is not None:
352
+ _redact_fitz_page(page, pdf_doc.pages[page_index], cell, config, fitz)
353
+ pix = page.get_pixmap(dpi=dpi, alpha=False)
354
+ return bytes(pix.tobytes("png"))
355
+ finally:
356
+ doc.close()
@@ -0,0 +1,269 @@
1
+ """Offline-Prüfbericht (HTML) & Audit-Log (CSV/JSON) für DSGVO-Dokumentation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import html
7
+ import io
8
+ import json
9
+ from datetime import datetime
10
+
11
+ from .models import CATEGORY_LABELS_DE, Category, CellResult, Confidence, RedactionConfig, ScanSummary, SpanMatch
12
+
13
+
14
+ def _highlight_html(text: str, matches: list[SpanMatch]) -> str:
15
+ """Rendert Originaltext mit farbig markierten Fundstellen (Rot=Sicher, Gelb=Prüfen, Lila=Manuell, Grün=Geschützt)."""
16
+ if not matches:
17
+ return html.escape(text).replace("\n", "<br>")
18
+
19
+ ordered = sorted(matches, key=lambda m: m.start)
20
+ parts: list[str] = []
21
+ cursor = 0
22
+ for m in ordered:
23
+ if m.start < cursor:
24
+ continue
25
+ parts.append(html.escape(text[cursor:m.start]))
26
+ seg = html.escape(text[m.start:m.end])
27
+ cat_label = CATEGORY_LABELS_DE.get(m.category, m.category.value)
28
+ reasons = html.escape(" | ".join(m.reasons))
29
+ if m.protected:
30
+ css = "badge-protected"
31
+ status = "Antragsteller geschützt"
32
+ elif not m.redacted:
33
+ css = "badge-released"
34
+ status = "Manuell freigegeben"
35
+ elif m.category == Category.MANUAL:
36
+ if "maus" in (m.rule or "").lower():
37
+ css = "badge-manual"
38
+ status = "Manuell geschwärzt (nur hier)"
39
+ cat_label = "Manuell (hier)"
40
+ else:
41
+ css = "badge-manual-global"
42
+ status = "Manuelle Regel überall"
43
+ cat_label = "Manuelle Regel überall"
44
+ elif m.confidence == Confidence.REVIEW:
45
+ css = "badge-review"
46
+ status = "Unsicher (im Zweifel geschwärzt)"
47
+ else:
48
+ css = "badge-high"
49
+ status = "Sicher geschwärzt"
50
+ tooltip = f"{status} · {cat_label} · {reasons}"
51
+ parts.append(f'<mark class="{css}" title="{tooltip}">{seg}<span class="tag">{html.escape(cat_label)}</span></mark>')
52
+ cursor = m.end
53
+ parts.append(html.escape(text[cursor:]))
54
+ return "".join(parts).replace("\n", "<br>")
55
+
56
+
57
+ def build_html_report(
58
+ filename: str,
59
+ summary: ScanSummary,
60
+ cell_results: list[CellResult],
61
+ config: RedactionConfig,
62
+ ) -> str:
63
+ """Erstellt einen eigenständigen, 100 % offline nutzbaren HTML-Prüfbericht."""
64
+ timestamp = datetime.now().strftime("%d.%m.%Y %H:%M:%S")
65
+ applicant_str = (
66
+ f"{config.applicant_first_name} {config.applicant_last_name}".strip()
67
+ or "Keine Ausnahme angegeben"
68
+ )
69
+
70
+ cat_pills = "".join(
71
+ f'<span class="pill">{html.escape(k)}: <strong>{v}</strong></span>'
72
+ for k, v in summary.by_category.items()
73
+ ) or '<span class="muted">Keine Schwärzungen</span>'
74
+
75
+ review_rows_html: list[str] = []
76
+ all_rows_html: list[str] = []
77
+
78
+ is_pdf = filename.lower().endswith(".pdf")
79
+ row_word = "Seite" if is_pdf else "Zeile"
80
+ total_lbl = "PDF-Seiten gesamt" if is_pdf else "CSV-Zeilen gesamt"
81
+ findings_lbl = "Seiten mit Fundstellen" if is_pdf else "Zeilen mit Fundstellen"
82
+
83
+ for cell in cell_results:
84
+ has_review = any(not m.protected and m.redacted and m.confidence == Confidence.REVIEW for m in cell.matches)
85
+ orig_hl = _highlight_html(cell.original, cell.matches)
86
+ red_escaped = (
87
+ html.escape(cell.redacted)
88
+ .replace("[GESCHWÄRZT]", "<strong>[GESCHWÄRZT]</strong>")
89
+ .replace("[SECRET]", "<strong>[SECRET]</strong>")
90
+ .replace("\n", "<br>")
91
+ )
92
+ display_num = cell.row_index + 1 if is_pdf else cell.row_index + 2
93
+
94
+ row_tr = (
95
+ f'<tr class="{"row-review" if has_review else ""}">'
96
+ f'<td class="col-meta"><strong>{row_word} {display_num}</strong><br>'
97
+ f'<span class="muted">{html.escape(cell.column)}</span></td>'
98
+ f'<td class="col-text">{orig_hl}</td>'
99
+ f'<td class="col-text redacted-col">{red_escaped}</td>'
100
+ f"</tr>"
101
+ )
102
+ all_rows_html.append(row_tr)
103
+ if has_review:
104
+ review_rows_html.append(row_tr)
105
+
106
+ review_section = ""
107
+ if review_rows_html:
108
+ review_section = f"""
109
+ <section class="card card-warn">
110
+ <h2>⚠️ Unsichere Fälle zur kurzen Gegenprüfung ({len(review_rows_html)} Zellen)</h2>
111
+ <p class="sub">Diese Stellen wurden nach dem Prinzip <em>„Im Zweifel schwärzen“</em> automatisch geschwärzt. Bitte kurz prüfen, ob etwas Harmloses dabei ist.</p>
112
+ <table>
113
+ <thead><tr><th>Zeile / Spalte</th><th>Original (Fundstellen markiert)</th><th>Geschwärztes Ergebnis</th></tr></thead>
114
+ <tbody>{''.join(review_rows_html)}</tbody>
115
+ </table>
116
+ </section>
117
+ """
118
+
119
+ return f"""<!DOCTYPE html>
120
+ <html lang="de">
121
+ <head>
122
+ <meta charset="utf-8">
123
+ <meta name="viewport" content="width=device-width, initial-scale=1">
124
+ <title>DSGVO-Prüfbericht – {html.escape(filename)}</title>
125
+ <style>
126
+ :root {{
127
+ --bg: #f8fafc; --card: #ffffff; --text: #0f172a; --muted: #64748b;
128
+ --border: #e2e8f0; --red-bg: #fee2e2; --red-bd: #dc2626;
129
+ --amber-bg: #fef3c7; --amber-bd: #d97706;
130
+ --green-bg: #ccfbf1; --green-bd: #0d9488;
131
+ --blue-bg: #dbeafe; --blue-bd: #2563eb;
132
+ --slate-bg: #f1f5f9; --slate-bd: #64748b;
133
+ --purple-bg: #f3e8ff; --purple-bd: #9333ea;
134
+ }}
135
+ * {{ box-sizing: border-box; }}
136
+ body {{ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: var(--bg); color: var(--text); margin: 0; padding: 28px; line-height: 1.5; }}
137
+ .wrap {{ max-width: 1440px; margin: 0 auto; }}
138
+ h1 {{ margin: 0 0 6px; font-size: 24px; }}
139
+ h2 {{ margin: 0 0 10px; font-size: 18px; }}
140
+ .sub {{ color: var(--muted); margin: 0 0 16px; font-size: 14px; }}
141
+ .muted {{ color: var(--muted); font-size: 13px; }}
142
+ .grid {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(190px, 1fr)); gap: 12px; margin: 18px 0; }}
143
+ .stat {{ background: var(--card); border: 1px solid var(--border); border-radius: 10px; padding: 14px 16px; }}
144
+ .stat .num {{ font-size: 28px; font-weight: 700; }}
145
+ .stat .lbl {{ color: var(--muted); font-size: 13px; }}
146
+ .card {{ background: var(--card); border: 1px solid var(--border); border-radius: 12px; padding: 20px; margin-bottom: 20px; }}
147
+ .card-warn {{ border-left: 5px solid var(--amber-bd); }}
148
+ .internal-banner {{
149
+ background: #7f1d1d; color: #fff; border-radius: 10px; padding: 12px 16px;
150
+ font-size: 13.5px; font-weight: 600; margin-bottom: 18px;
151
+ border: 1px solid #dc2626;
152
+ }}
153
+ .pills {{ display: flex; flex-wrap: wrap; gap: 8px; margin-top: 8px; }}
154
+ .pill {{ background: #f1f5f9; border: 1px solid var(--border); border-radius: 999px; padding: 4px 12px; font-size: 13px; }}
155
+ .legend {{ display: flex; flex-wrap: wrap; gap: 14px; font-size: 13px; margin: 12px 0; }}
156
+ table {{ width: 100%; border-collapse: collapse; font-size: 13.5px; }}
157
+ th, td {{ border: 1px solid var(--border); padding: 10px 12px; vertical-align: top; text-align: left; }}
158
+ th {{ background: #f1f5f9; font-weight: 600; }}
159
+ .col-meta {{ width: 120px; white-space: nowrap; }}
160
+ .col-text {{ width: 44%; word-break: break-word; }}
161
+ .redacted-col {{ background: #fcfcfd; }}
162
+ .row-review {{ background: #fffbeb; }}
163
+ mark {{ padding: 1px 5px; border-radius: 4px; font-weight: 500; }}
164
+ .badge-high {{ background: var(--red-bg); border-bottom: 2px solid var(--red-bd); color: #7f1d1d; }}
165
+ .badge-review {{ background: var(--amber-bg); border-bottom: 2px solid var(--amber-bd); color: #78350f; }}
166
+ .badge-protected {{ background: var(--green-bg); border-bottom: 2px solid var(--green-bd); color: #115e59; font-weight: 600; }}
167
+ .badge-released {{ background: var(--slate-bg); border-bottom: 2px dashed var(--slate-bd); color: #475569; text-decoration: line-through; }}
168
+ .badge-manual {{ background: var(--purple-bg); border-bottom: 2px solid var(--purple-bd); color: #581c87; }}
169
+ .badge-manual-global {{ background: var(--blue-bg); border-bottom: 2px solid var(--blue-bd); color: #1e3a8a; font-weight: 600; }}
170
+ .tag {{ font-size: 10px; font-weight: 700; text-transform: uppercase; margin-left: 4px; opacity: 0.78; }}
171
+ @media print {{ body {{ padding: 0; background: #fff; }} .card {{ break-inside: avoid; }} }}
172
+ </style>
173
+ </head>
174
+ <body>
175
+ <div class="wrap">
176
+ <div class="internal-banner">
177
+ ⚠️ VERTRAULICH – NUR FÜR INTERNE PRÜFUNG: Dieser Prüfbericht enthält ungeschwärzte Originaldaten. NIEMALS an den Antragsteller versenden – versende ausschließlich die geschwärzte PDF- oder CSV-Datei!
178
+ </div>
179
+ <h1>DSGVO-Prüfbericht (Art. 15 Auskunft)</h1>
180
+ <p class="sub">
181
+ Datei: <strong>{html.escape(filename)}</strong> · Erstellt am: {timestamp} ·
182
+ Antragsteller (geschützt): <strong>{html.escape(applicant_str)}</strong> ·
183
+ Sprach-KI: <strong>{html.escape(summary.ner_model_name if summary.ner_active else 'deaktiviert (nur Regeln)')}</strong> ·
184
+ Spalten: <strong>{html.escape(', '.join(summary.scanned_columns))}</strong>
185
+ </p>
186
+
187
+ <div class="grid">
188
+ <div class="stat"><div class="num">{summary.total_rows}</div><div class="lbl">{total_lbl}</div></div>
189
+ <div class="stat"><div class="num">{summary.rows_with_findings}</div><div class="lbl">{findings_lbl}</div></div>
190
+ <div class="stat"><div class="num" style="color:#dc2626">{summary.total_redactions}</div><div class="lbl">Geschwärzte Stellen</div></div>
191
+ <div class="stat"><div class="num" style="color:#d97706">{summary.review_findings}</div><div class="lbl">Unsichere Fälle (geprüft/markiert)</div></div>
192
+ <div class="stat"><div class="num" style="color:#16a34a">{summary.protected_applicant_hits}</div><div class="lbl">Antragsteller geschützt</div></div>
193
+ </div>
194
+
195
+ <section class="card">
196
+ <h2>Fundstellen nach Kategorie</h2>
197
+ <div class="pills">{cat_pills}</div>
198
+ <div class="legend">
199
+ <span><mark class="badge-high">Rot</mark> Sicher geschwärzt</span>
200
+ <span><mark class="badge-review">Gelb</mark> Unsicher (im Zweifel geschwärzt)</span>
201
+ <span><mark class="badge-manual-global">Blau</mark> Manuelle Regel überall</span>
202
+ <span><mark class="badge-manual">Lila</mark> Nur hier geschwärzt</span>
203
+ <span><mark class="badge-protected">👤 Türkis</mark> Antragsteller (bewusst nicht geschwärzt)</span>
204
+ <span><mark class="badge-released">Grau</mark> Manuell freigegeben</span>
205
+ </div>
206
+ </section>
207
+
208
+ {review_section}
209
+
210
+ <section class="card">
211
+ <h2>Alle Zellen mit Treffern ({len(all_rows_html)})</h2>
212
+ <table>
213
+ <thead><tr><th>Zeile / Spalte</th><th>Original (Fundstellen markiert)</th><th>Geschwärztes Ergebnis</th></tr></thead>
214
+ <tbody>{''.join(all_rows_html) if all_rows_html else '<tr><td colspan="3" class="muted">Keine personenbezogenen Daten gefunden.</td></tr>'}</tbody>
215
+ </table>
216
+ </section>
217
+ </div>
218
+ </body>
219
+ </html>
220
+ """
221
+
222
+
223
+ def build_audit_csv_bytes(cell_results: list[CellResult], include_originals: bool = True) -> bytes:
224
+ """Erstellt ein vollständiges Audit-Protokoll aller Fundstellen als CSV (optional ohne Original-Klartext)."""
225
+ buf = io.StringIO(newline="")
226
+ writer = csv.writer(buf, delimiter=";", lineterminator="\r\n")
227
+ header = [
228
+ "CSV_Zeile",
229
+ "Spalte",
230
+ "Status",
231
+ "Kategorie",
232
+ "Konfidenz",
233
+ ]
234
+ if include_originals:
235
+ header.append("Original_Text")
236
+ header.append("Regel_Begruendung")
237
+ writer.writerow(header)
238
+
239
+ for cell in cell_results:
240
+ for m in cell.matches:
241
+ if m.protected:
242
+ status = "GESCHUETZT_ANTRAGSTELLER"
243
+ elif m.redacted:
244
+ status = "GESCHWAERZT"
245
+ else:
246
+ status = "MANUELL_FREIGEGEBEN"
247
+ row = [
248
+ cell.row_index + 2, # 1-basiert inkl. Header
249
+ cell.column,
250
+ status,
251
+ CATEGORY_LABELS_DE.get(m.category, m.category.value),
252
+ m.confidence.value,
253
+ ]
254
+ if include_originals:
255
+ row.append(m.text)
256
+ row.append(" | ".join(m.reasons))
257
+ writer.writerow(row)
258
+ return buf.getvalue().encode("utf-8-sig")
259
+
260
+
261
+ def build_audit_json(filename: str, summary: ScanSummary, cell_results: list[CellResult]) -> str:
262
+ """Erstellt ein maschinenlesbares JSON-Audit-Protokoll."""
263
+ payload = {
264
+ "filename": filename,
265
+ "generated_at": datetime.now().isoformat(timespec="seconds"),
266
+ "summary": summary.to_dict(),
267
+ "cells": [c.to_dict() for c in cell_results],
268
+ }
269
+ return json.dumps(payload, ensure_ascii=False, indent=2)