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,630 @@
1
+ """Lokale FastAPI Web-Oberfläche (100 % offline auf 127.0.0.1) mit 1-Klick-Prüfung & Maus-Schwärzung."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import socket
7
+ import threading
8
+ import time
9
+ import uuid
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from fastapi import FastAPI, File, Form, HTTPException, Query, UploadFile
14
+ from fastapi.responses import HTMLResponse, JSONResponse, Response
15
+ from fastapi.staticfiles import StaticFiles
16
+ from pydantic import BaseModel
17
+
18
+ from .csv_io import LoadedCSV, dump_csv_bytes, dump_xlsx_bytes, load_tabular_bytes
19
+ from .engine import (
20
+ RedactionEngine,
21
+ detect_pii_warning_columns,
22
+ recommend_default_columns,
23
+ run_residual_pii_check,
24
+ )
25
+ from .models import RedactionConfig, SpanMatch
26
+ from .pdf_export import dump_pdf_bytes
27
+ from .pdf_redactor import (
28
+ PdfDocumentData,
29
+ apply_pdf_redactions_to_bytes,
30
+ extract_pdf_document,
31
+ is_pdf_bytes,
32
+ is_pdf_support_available,
33
+ render_pdf_page_png,
34
+ )
35
+ from .report import build_audit_csv_bytes, build_html_report
36
+ from .session import PAGINATION_THRESHOLD, ScanSession, serialize_session
37
+
38
+ PROJECT_ROOT = Path(__file__).resolve().parent.parent
39
+ TEMPLATES_DIR = PROJECT_ROOT / "templates"
40
+ STATIC_DIR = PROJECT_ROOT / "static"
41
+ MAX_UPLOAD_BYTES = 100 * 1024 * 1024 # 100 MB Schutzlimit
42
+ SESSION_TTL_SECONDS = 3600 # Sitzungen nach 60 Min. automatisch aus RAM entfernen
43
+
44
+
45
+ class ToggleMatchRequest(BaseModel):
46
+ match_id: str
47
+ redacted: bool
48
+
49
+
50
+ class ManualRedactRequest(BaseModel):
51
+ row_index: int
52
+ column: str
53
+ start: int
54
+ end: int
55
+ text: str | None = None
56
+
57
+
58
+ class BulkWordActionRequest(BaseModel):
59
+ word: str = ""
60
+ words: list[str] | None = None
61
+ action: str # "release" | "redact"
62
+
63
+
64
+ class ReplacementUpdateRequest(BaseModel):
65
+ replacement: str = "██████"
66
+ use_typed_placeholders: bool = False
67
+
68
+
69
+ def _split_terms(val: Any) -> list[str]:
70
+ if isinstance(val, list):
71
+ return [str(x).strip() for x in val if str(x).strip()]
72
+ if isinstance(val, str):
73
+ return [x.strip() for x in val.replace("\n", ",").split(",") if x.strip()]
74
+ return []
75
+
76
+
77
+ def _load_uploaded_source(
78
+ raw: bytes,
79
+ filename: str = "",
80
+ delimiter: str | None = None,
81
+ ) -> tuple[LoadedCSV, PdfDocumentData | None]:
82
+ """Liest CSV, Excel (.xlsx) oder PDF (.pdf) ein."""
83
+ if is_pdf_bytes(raw, filename):
84
+ pdf_doc = extract_pdf_document(raw)
85
+ return pdf_doc.loaded, pdf_doc
86
+ return load_tabular_bytes(raw, filename=filename, delimiter=delimiter), None
87
+
88
+
89
+ def _build_config_from_opts(opts: dict[str, Any]) -> RedactionConfig:
90
+ extra_wl = _split_terms(opts.get("extra_whitelist", []))
91
+ for item in _split_terms(opts.get("applicant_extra_data", [])):
92
+ if item not in extra_wl:
93
+ extra_wl.append(item)
94
+
95
+ return RedactionConfig(
96
+ applicant_first_name=str(opts.get("applicant_first_name", "")).strip(),
97
+ applicant_last_name=str(opts.get("applicant_last_name", "")).strip(),
98
+ extra_whitelist=extra_wl,
99
+ extra_blacklist=_split_terms(opts.get("extra_blacklist", [])),
100
+ replacement=str(opts.get("replacement", "██████")) or "██████",
101
+ use_typed_placeholders=bool(opts.get("use_typed_placeholders", False)),
102
+ redact_names=bool(opts.get("redact_names", True)),
103
+ redact_addresses=bool(opts.get("redact_addresses", True)),
104
+ redact_house_numbers=bool(opts.get("redact_house_numbers", True)),
105
+ redact_postal_codes=bool(opts.get("redact_postal_codes", True)),
106
+ redact_locations=bool(opts.get("redact_locations", True)),
107
+ redact_bank=bool(opts.get("redact_bank", True)),
108
+ redact_job_titles=bool(opts.get("redact_job_titles", True)),
109
+ redact_amounts=bool(opts.get("redact_amounts", True)),
110
+ redact_phones=bool(opts.get("redact_phones", True)),
111
+ redact_emails=bool(opts.get("redact_emails", True)),
112
+ redact_websites=bool(opts.get("redact_websites", True)),
113
+ redact_ip_addresses=bool(opts.get("redact_ip_addresses", True)),
114
+ redact_birthdates=bool(opts.get("redact_birthdates", True)),
115
+ redact_license_plates=bool(opts.get("redact_license_plates", True)),
116
+ redact_tax_ids=bool(opts.get("redact_tax_ids", True)),
117
+ redact_companies=bool(opts.get("redact_companies", False)),
118
+ redact_uncertain_by_default=bool(opts.get("redact_uncertain_by_default", True)),
119
+ use_ner=bool(opts.get("use_ner", True)),
120
+ columns=opts.get("columns") or None,
121
+ )
122
+
123
+
124
+ def create_app(engine: RedactionEngine | None = None) -> FastAPI:
125
+ app = FastAPI(title="BLACKTHIS – DSGVO Redactor (Lokal & Offline)", docs_url=None, redoc_url=None)
126
+ if STATIC_DIR.is_dir():
127
+ app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
128
+
129
+ redaction_engine = engine if engine is not None else RedactionEngine()
130
+ sessions: dict[str, ScanSession] = {}
131
+ scan_jobs: dict[str, dict[str, Any]] = {}
132
+ jobs_lock = threading.Lock()
133
+
134
+ def _purge_expired_sessions() -> None:
135
+ now = time.time()
136
+ expired = [k for k, s in sessions.items() if now - s.created_at > SESSION_TTL_SECONDS]
137
+ for k in expired:
138
+ del sessions[k]
139
+
140
+ def _register_session(session: ScanSession) -> None:
141
+ _purge_expired_sessions()
142
+ if len(sessions) >= 5:
143
+ del sessions[next(iter(sessions))]
144
+ sessions[session.session_id] = session
145
+
146
+ async def _read_upload_guarded(file: UploadFile) -> bytes:
147
+ _purge_expired_sessions()
148
+ raw = await file.read()
149
+ if not raw:
150
+ raise HTTPException(status_code=400, detail="Die hochgeladene Datei ist leer.")
151
+ if len(raw) > MAX_UPLOAD_BYTES:
152
+ raise HTTPException(status_code=413, detail="Datei überschreitet das lokale Limit von 100 MB.")
153
+ return raw
154
+
155
+ def _get_session_or_404(session_id: str) -> ScanSession:
156
+ session = sessions.get(session_id)
157
+ if not session:
158
+ raise HTTPException(status_code=404, detail="Sitzung nicht gefunden. Bitte Datei erneut scannen.")
159
+ return session
160
+
161
+ @app.get("/", response_class=HTMLResponse)
162
+ async def index() -> HTMLResponse:
163
+ return HTMLResponse((TEMPLATES_DIR / "index.html").read_text(encoding="utf-8"))
164
+
165
+ @app.get("/api/status")
166
+ async def api_status() -> JSONResponse:
167
+ return JSONResponse({
168
+ "offline": True,
169
+ "ner_available": redaction_engine.ner.available,
170
+ "ner_model": redaction_engine.ner.model_name,
171
+ "pdf_available": is_pdf_support_available(),
172
+ })
173
+
174
+ @app.post("/api/inspect")
175
+ async def api_inspect(file: UploadFile = File(...)) -> JSONResponse:
176
+ raw = await _read_upload_guarded(file)
177
+ try:
178
+ loaded, pdf_doc = _load_uploaded_source(raw, filename=file.filename or "")
179
+ except (ValueError, RuntimeError) as exc:
180
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
181
+ if not loaded.headers:
182
+ raise HTTPException(status_code=400, detail="Keine Spaltenüberschriften in der Datei gefunden.")
183
+ is_pdf = pdf_doc is not None
184
+ return JSONResponse({
185
+ "filename": file.filename or ("upload.pdf" if is_pdf else "upload.csv"),
186
+ "file_type": "pdf" if is_pdf else "table",
187
+ "pdf_info": (
188
+ {
189
+ "page_count": pdf_doc.page_count,
190
+ "pages_with_text": pdf_doc.pages_with_text,
191
+ "image_only_pages": pdf_doc.image_only_pages,
192
+ }
193
+ if pdf_doc is not None
194
+ else None
195
+ ),
196
+ "headers": loaded.headers,
197
+ "recommended_columns": ["Text"] if is_pdf else recommend_default_columns(loaded.headers),
198
+ "pii_warning_columns": {} if is_pdf else detect_pii_warning_columns(loaded.headers, loaded.rows),
199
+ "row_count": len(loaded.rows),
200
+ "encoding": loaded.encoding,
201
+ "delimiter": loaded.delimiter,
202
+ "preview_rows": loaded.rows[:3],
203
+ })
204
+
205
+ @app.post("/api/scan")
206
+ async def api_scan(file: UploadFile = File(...), options_json: str = Form("{}")) -> JSONResponse:
207
+ raw = await _read_upload_guarded(file)
208
+ try:
209
+ opts: dict[str, Any] = json.loads(options_json) if options_json else {}
210
+ except json.JSONDecodeError as exc:
211
+ raise HTTPException(status_code=400, detail=f"Ungültige Optionen: {exc}") from exc
212
+
213
+ try:
214
+ loaded, pdf_doc = _load_uploaded_source(raw, filename=file.filename or "", delimiter=opts.get("delimiter") or None)
215
+ except (ValueError, RuntimeError) as exc:
216
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
217
+ if not loaded.headers:
218
+ raise HTTPException(status_code=400, detail="Keine Spalten in der Datei gefunden.")
219
+
220
+ if pdf_doc is not None:
221
+ opts["columns"] = ["Text"]
222
+ config = _build_config_from_opts(opts)
223
+ ner_by_text: dict[str, list[SpanMatch]] = {}
224
+ redacted_rows, cell_results, summary = redaction_engine.scan_rows(
225
+ headers=loaded.headers,
226
+ rows=loaded.rows,
227
+ config=config,
228
+ encoding=loaded.encoding,
229
+ delimiter=loaded.delimiter,
230
+ out_ner_by_text=ner_by_text,
231
+ )
232
+
233
+ cell_lookup = {(c.row_index, c.column): c for c in cell_results}
234
+ residual = run_residual_pii_check(redacted_rows, summary.scanned_columns, config, cell_lookup)
235
+
236
+ session = ScanSession(
237
+ session_id=uuid.uuid4().hex,
238
+ filename=file.filename or ("upload.pdf" if pdf_doc is not None else "upload.csv"),
239
+ loaded=loaded,
240
+ config=config,
241
+ redacted_rows=redacted_rows,
242
+ cell_results=cell_results,
243
+ summary=summary,
244
+ cell_lookup=cell_lookup,
245
+ ner_by_text=ner_by_text,
246
+ residual_check=residual,
247
+ pdf_source=pdf_doc,
248
+ )
249
+ _register_session(session)
250
+ return JSONResponse(serialize_session(session))
251
+
252
+ @app.post("/api/scan/start")
253
+ async def api_scan_start(file: UploadFile = File(...), options_json: str = Form("{}")) -> JSONResponse:
254
+ raw = await _read_upload_guarded(file)
255
+ try:
256
+ opts: dict[str, Any] = json.loads(options_json) if options_json else {}
257
+ except json.JSONDecodeError as exc:
258
+ raise HTTPException(status_code=400, detail=f"Ungültige Optionen: {exc}") from exc
259
+
260
+ filename = file.filename or "upload.csv"
261
+ job_id = uuid.uuid4().hex
262
+ started_at = time.perf_counter()
263
+
264
+ with jobs_lock:
265
+ if len(scan_jobs) >= 10:
266
+ del scan_jobs[next(iter(scan_jobs))]
267
+ scan_jobs[job_id] = {
268
+ "job_id": job_id,
269
+ "status": "running",
270
+ "phase": "loading",
271
+ "phase_label": "Lese Datei ein & erkenne Format/Encoding…",
272
+ "percent": 4,
273
+ "processed": 0,
274
+ "total": 0,
275
+ "redactions_so_far": 0,
276
+ "detail": f"{filename} ({max(1, len(raw) // 1024):,} KB)".replace(",", "."),
277
+ "started_at": started_at,
278
+ "error": None,
279
+ "result": None,
280
+ }
281
+
282
+ def _worker() -> None:
283
+ def _on_progress(update: dict[str, Any]) -> None:
284
+ with jobs_lock:
285
+ job = scan_jobs.get(job_id)
286
+ if job:
287
+ job.update(update)
288
+
289
+ try:
290
+ loaded, pdf_doc = _load_uploaded_source(raw, filename=filename, delimiter=opts.get("delimiter") or None)
291
+ if not loaded.headers:
292
+ raise ValueError("Keine Spalten in der Datei gefunden.")
293
+
294
+ if pdf_doc is not None:
295
+ opts["columns"] = ["Text"]
296
+ config = _build_config_from_opts(opts)
297
+ ner_by_text: dict[str, list[SpanMatch]] = {}
298
+ redacted_rows, cell_results, summary = redaction_engine.scan_rows(
299
+ headers=loaded.headers,
300
+ rows=loaded.rows,
301
+ config=config,
302
+ encoding=loaded.encoding,
303
+ delimiter=loaded.delimiter,
304
+ out_ner_by_text=ner_by_text,
305
+ progress_cb=_on_progress,
306
+ )
307
+
308
+ cell_lookup = {(c.row_index, c.column): c for c in cell_results}
309
+ _on_progress({"phase": "finalizing", "phase_label": "2. Kontroll-Durchlauf (Rest-PII-Prüfung) läuft…", "percent": 99})
310
+ residual = run_residual_pii_check(redacted_rows, summary.scanned_columns, config, cell_lookup)
311
+
312
+ session = ScanSession(
313
+ session_id=uuid.uuid4().hex,
314
+ filename=filename,
315
+ loaded=loaded,
316
+ config=config,
317
+ redacted_rows=redacted_rows,
318
+ cell_results=cell_results,
319
+ summary=summary,
320
+ cell_lookup=cell_lookup,
321
+ ner_by_text=ner_by_text,
322
+ residual_check=residual,
323
+ pdf_source=pdf_doc,
324
+ )
325
+ _register_session(session)
326
+ serialized = serialize_session(session)
327
+ unit_lbl = "Seiten" if pdf_doc is not None else "Zeilen"
328
+
329
+ with jobs_lock:
330
+ job = scan_jobs.get(job_id)
331
+ if job:
332
+ job.update({
333
+ "status": "done",
334
+ "phase": "done",
335
+ "phase_label": "Scan abgeschlossen – bereit zur Prüfung!",
336
+ "percent": 100,
337
+ "processed": len(loaded.rows),
338
+ "total": len(loaded.rows),
339
+ "redactions_so_far": summary.total_redactions,
340
+ "detail": f"{len(loaded.rows):,} {unit_lbl} · {summary.total_redactions:,} Schwärzungen".replace(",", "."),
341
+ "result": serialized,
342
+ })
343
+ except Exception as exc: # noqa: BLE001
344
+ with jobs_lock:
345
+ job = scan_jobs.get(job_id)
346
+ if job:
347
+ job.update({"status": "error", "phase": "error", "phase_label": "Fehler beim Scannen", "error": str(exc)})
348
+
349
+ threading.Thread(target=_worker, daemon=True).start()
350
+ return JSONResponse({"job_id": job_id, "status": "running"})
351
+
352
+ @app.get("/api/scan/progress/{job_id}")
353
+ async def api_scan_progress(job_id: str) -> JSONResponse:
354
+ with jobs_lock:
355
+ job = scan_jobs.get(job_id)
356
+ if not job:
357
+ raise HTTPException(status_code=404, detail="Scan-Auftrag nicht gefunden.")
358
+ snapshot = dict(job)
359
+ snapshot["elapsed_ms"] = int((time.perf_counter() - snapshot.pop("started_at", time.perf_counter())) * 1000)
360
+ return JSONResponse(snapshot)
361
+
362
+ @app.get("/api/session/{session_id}/cells")
363
+ async def api_list_cells(
364
+ session_id: str,
365
+ filter: str = Query("all"),
366
+ q: str = Query(""),
367
+ offset: int = Query(0, ge=0),
368
+ limit: int = Query(100, ge=1, le=500),
369
+ ) -> JSONResponse:
370
+ session = _get_session_or_404(session_id)
371
+ page_cells, total = session.get_filtered_cells(filter_mode=filter, query=q, offset=offset, limit=limit)
372
+ context_cols = [c for c in session.loaded.headers if c not in session.summary.scanned_columns]
373
+ row_contexts = {
374
+ str(c.row_index): {col: session.loaded.rows[c.row_index].get(col, "") for col in context_cols}
375
+ for c in page_cells
376
+ }
377
+ return JSONResponse({
378
+ "filter": filter,
379
+ "total": total,
380
+ "offset": offset,
381
+ "limit": limit,
382
+ "has_more": offset + len(page_cells) < total,
383
+ "cells": [c.to_dict() for c in page_cells],
384
+ "row_contexts": row_contexts,
385
+ })
386
+
387
+ @app.get("/api/session/{session_id}/table")
388
+ async def api_list_table_rows(
389
+ session_id: str,
390
+ q: str = Query(""),
391
+ offset: int = Query(0, ge=0),
392
+ limit: int = Query(100, ge=1, le=500),
393
+ ) -> JSONResponse:
394
+ """Liefert paginierte vollständige Zeilen inkl. aller Spalten (auch nicht geschwärzter Spalten)."""
395
+ session = _get_session_or_404(session_id)
396
+ rows_page, total = session.get_table_rows(query=q, offset=offset, limit=limit)
397
+ return JSONResponse({
398
+ "headers": session.loaded.headers,
399
+ "scanned_columns": session.summary.scanned_columns,
400
+ "total": total,
401
+ "offset": offset,
402
+ "limit": limit,
403
+ "has_more": offset + len(rows_page) < total,
404
+ "rows": rows_page,
405
+ })
406
+
407
+ @app.post("/api/session/{session_id}/toggle")
408
+ async def api_toggle_match(session_id: str, req: ToggleMatchRequest) -> JSONResponse:
409
+ session = _get_session_or_404(session_id)
410
+ updated_cell = session.toggle_match(req.match_id, req.redacted)
411
+ if updated_cell is None:
412
+ raise HTTPException(status_code=404, detail="Fundstelle nicht gefunden.")
413
+ return JSONResponse({
414
+ "summary": session.summary.to_dict(),
415
+ "cell": updated_cell.to_dict(),
416
+ "findings_count": len(session.cell_results),
417
+ "revision": session.revision,
418
+ })
419
+
420
+ @app.post("/api/session/{session_id}/manual-redact")
421
+ async def api_manual_redact(session_id: str, req: ManualRedactRequest) -> JSONResponse:
422
+ session = _get_session_or_404(session_id)
423
+ try:
424
+ cell, match = session.add_manual_span(req.row_index, req.column, req.start, req.end, expected_text=req.text)
425
+ except ValueError as exc:
426
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
427
+ return JSONResponse({
428
+ "summary": session.summary.to_dict(),
429
+ "cell": cell.to_dict(),
430
+ "match": match.to_dict(),
431
+ "findings_count": len(session.cell_results),
432
+ "revision": session.revision,
433
+ })
434
+
435
+ @app.post("/api/session/{session_id}/replacement")
436
+ async def api_update_replacement(session_id: str, req: ReplacementUpdateRequest) -> JSONResponse:
437
+ """Ändert den Schwärzungs-Text einer laufenden Sitzung sofort ohne Neuscan."""
438
+ session = _get_session_or_404(session_id)
439
+ session.update_replacement(req.replacement, req.use_typed_placeholders)
440
+ return JSONResponse({
441
+ "replacement": session.config.replacement,
442
+ "use_typed_placeholders": session.config.use_typed_placeholders,
443
+ "revision": session.revision,
444
+ })
445
+
446
+ @app.post("/api/session/{session_id}/bulk-word")
447
+ async def api_bulk_word(session_id: str, req: BulkWordActionRequest) -> JSONResponse:
448
+ session = _get_session_or_404(session_id)
449
+ if req.words:
450
+ raw_terms = [w.strip() for w in req.words if w and w.strip()]
451
+ else:
452
+ raw_terms = [
453
+ part.strip()
454
+ for part in req.word.replace("\n", ",").replace(";", ",").split(",")
455
+ if part.strip()
456
+ ]
457
+ # Doppelte Begriffe (case-insensitive) deduplizieren
458
+ terms: list[str] = []
459
+ seen_l: set[str] = set()
460
+ for t in raw_terms:
461
+ tl = t.lower()
462
+ if tl not in seen_l:
463
+ seen_l.add(tl)
464
+ terms.append(t)
465
+
466
+ if not terms:
467
+ raise HTTPException(status_code=400, detail="Bitte mindestens ein Wort angeben.")
468
+
469
+ if req.action == "release":
470
+ existing_wl = {w.lower() for w in session.config.extra_whitelist}
471
+ for t in terms:
472
+ if t.lower() not in existing_wl:
473
+ session.config.extra_whitelist.append(t)
474
+ existing_wl.add(t.lower())
475
+ session.config.extra_blacklist = [w for w in session.config.extra_blacklist if w.lower() not in seen_l]
476
+ for rec in session.manual_spans:
477
+ if rec.text.strip().lower() in seen_l:
478
+ rec.redacted = False
479
+ elif req.action == "redact":
480
+ existing_bl = {w.lower() for w in session.config.extra_blacklist}
481
+ for t in terms:
482
+ if t.lower() not in existing_bl:
483
+ session.config.extra_blacklist.append(t)
484
+ existing_bl.add(t.lower())
485
+ session.config.extra_whitelist = [w for w in session.config.extra_whitelist if w.lower() not in seen_l]
486
+ else:
487
+ raise HTTPException(status_code=400, detail="Unbekannte Aktion.")
488
+
489
+ for key in list(session.toggle_overrides.keys()):
490
+ r_idx, col, s, e = key
491
+ orig = session.loaded.rows[r_idx].get(col, "") or ""
492
+ if orig[s:e].strip().lower() in seen_l:
493
+ del session.toggle_overrides[key]
494
+
495
+ affected_count = session.apply_bulk_words_incremental(words=terms, action=req.action, engine=redaction_engine)
496
+ payload = serialize_session(session)
497
+ payload["affected_count"] = affected_count
498
+ payload["terms_count"] = len(terms)
499
+ return JSONResponse(payload)
500
+
501
+ @app.delete("/api/session/{session_id}")
502
+ async def api_delete_session(session_id: str) -> JSONResponse:
503
+ return JSONResponse({"deleted": sessions.pop(session_id, None) is not None})
504
+
505
+ @app.get("/api/session/{session_id}/pdf-page/{page_num}")
506
+ async def api_pdf_page_preview(
507
+ session_id: str,
508
+ page_num: int,
509
+ mode: str = Query("redacted"),
510
+ ) -> Response:
511
+ """Rendert eine einzelne PDF-Seite (Original oder live geschwärzt) als PNG für die Layout-Vorschau."""
512
+ session = _get_session_or_404(session_id)
513
+ if session.pdf_source is None:
514
+ raise HTTPException(status_code=400, detail="Diese Sitzung stammt nicht aus einem PDF-Upload.")
515
+ page_idx = page_num - 1
516
+ if page_idx < 0 or page_idx >= session.pdf_source.page_count:
517
+ raise HTTPException(status_code=404, detail=f"PDF-Seite {page_num} existiert nicht.")
518
+ clean_mode = "original" if mode == "original" else "redacted"
519
+ cell = session.cell_lookup.get((page_idx, "Text"))
520
+ try:
521
+ png_bytes = render_pdf_page_png(
522
+ pdf_doc=session.pdf_source,
523
+ page_index=page_idx,
524
+ cell=cell,
525
+ config=session.config,
526
+ mode=clean_mode,
527
+ dpi=130,
528
+ )
529
+ except (ValueError, RuntimeError) as exc:
530
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
531
+ return Response(png_bytes, media_type="image/png", headers={"Cache-Control": "no-store"})
532
+
533
+ @app.get("/api/session/{session_id}/export/{fmt}")
534
+ async def api_export(session_id: str, fmt: str) -> Response:
535
+ session = _get_session_or_404(session_id)
536
+ stem = Path(session.filename).stem
537
+
538
+ if fmt == "csv":
539
+ data = dump_csv_bytes(session.loaded.headers, session.redacted_rows, delimiter=session.loaded.delimiter, encoding="utf-8-sig")
540
+ return Response(data, media_type="text/csv; charset=utf-8", headers={"Content-Disposition": f'attachment; filename="{stem}_geschwaerzt.csv"'})
541
+ if fmt == "pdf":
542
+ if session.pdf_source is not None:
543
+ data = apply_pdf_redactions_to_bytes(session.pdf_source, session.cell_results, session.config)
544
+ else:
545
+ data = dump_pdf_bytes(session.loaded.headers, session.redacted_rows, filename=session.filename, summary=session.summary, config=session.config)
546
+ return Response(data, media_type="application/pdf", headers={"Content-Disposition": f'attachment; filename="{stem}_geschwaerzt.pdf"'})
547
+ if fmt == "xlsx":
548
+ data = dump_xlsx_bytes(session.loaded.headers, session.redacted_rows)
549
+ return Response(data, media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", headers={"Content-Disposition": f'attachment; filename="{stem}_geschwaerzt.xlsx"'})
550
+ if fmt == "report":
551
+ html_str = build_html_report(session.filename, session.summary, session.cell_results, session.config)
552
+ return Response(html_str.encode("utf-8"), media_type="text/html; charset=utf-8", headers={"Content-Disposition": f'attachment; filename="INTERN_NICHT_VERSENDEN_{stem}_pruefbericht.html"'})
553
+ if fmt == "audit":
554
+ data = build_audit_csv_bytes(session.cell_results, include_originals=True)
555
+ return Response(data, media_type="text/csv; charset=utf-8", headers={"Content-Disposition": f'attachment; filename="INTERN_NICHT_VERSENDEN_{stem}_audit_log.csv"'})
556
+ if fmt == "audit-anon":
557
+ data = build_audit_csv_bytes(session.cell_results, include_originals=False)
558
+ return Response(data, media_type="text/csv; charset=utf-8", headers={"Content-Disposition": f'attachment; filename="{stem}_audit_ohne_originale.csv"'})
559
+
560
+ raise HTTPException(status_code=400, detail=f"Unbekanntes Export-Format: {fmt}")
561
+
562
+ return app
563
+
564
+
565
+ def _is_port_free(host: str, port: int) -> bool:
566
+ for family, addr in ((socket.AF_INET, host), (socket.AF_INET6, "::1")):
567
+ try:
568
+ with socket.socket(family, socket.SOCK_STREAM) as probe:
569
+ probe.settimeout(0.15)
570
+ if probe.connect_ex((addr, port)) == 0:
571
+ return False
572
+ except OSError:
573
+ pass
574
+ try:
575
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
576
+ sock.bind((host, port))
577
+ return True
578
+ except OSError:
579
+ return False
580
+
581
+
582
+ def _find_free_port(host: str = "127.0.0.1", preferred_port: int = 8765, max_tries: int = 50) -> int:
583
+ for candidate in range(preferred_port, preferred_port + max_tries):
584
+ if _is_port_free(host, candidate):
585
+ return candidate
586
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
587
+ sock.bind((host, 0))
588
+ return int(sock.getsockname()[1])
589
+
590
+
591
+ def run_server(host: str = "127.0.0.1", port: int = 8765, open_browser: bool = True, allow_network: bool = False) -> None:
592
+ import sys
593
+ import webbrowser
594
+ import uvicorn
595
+
596
+ if host not in {"127.0.0.1", "localhost", "::1"} and not allow_network:
597
+ print(
598
+ f"\nSicherheits-Sperre: Bindung an '{host}' (Netzwerk) ist ohne Authentifizierung blockiert.\n"
599
+ "Nutze den sicheren Lokal-Standard (127.0.0.1) oder explizit --allow-network.\n",
600
+ file=sys.stderr,
601
+ )
602
+ raise SystemExit(2)
603
+
604
+ actual_port = _find_free_port(host, port)
605
+ if actual_port != port:
606
+ print(f"\nHinweis: Port {port} ist bereits durch eine andere App belegt – weiche automatisch auf freien Port {actual_port} aus.")
607
+
608
+ display_host = "127.0.0.1" if host == "0.0.0.0" else host
609
+ url = f"http://{display_host}:{actual_port}"
610
+ if open_browser:
611
+ def _open() -> None:
612
+ time.sleep(1.0)
613
+ webbrowser.open(url)
614
+ threading.Thread(target=_open, daemon=True).start()
615
+
616
+ print(f"\nBLACKTHIS läuft 100 % lokal unter: {url}")
617
+ print("Zum Beenden im Terminal Strg+C drücken.\n")
618
+ uvicorn.run(create_app(), host=host, port=actual_port, log_level="warning")
619
+
620
+
621
+ if __name__ == "__main__":
622
+ import argparse
623
+
624
+ parser = argparse.ArgumentParser(description="BLACKTHIS – lokale DSGVO-Schwärzungsoberfläche")
625
+ parser.add_argument("--host", default="127.0.0.1", help="Bind-Host (Standard: 127.0.0.1)")
626
+ parser.add_argument("--port", type=int, default=8765, help="Bevorzugter Port (Standard: 8765)")
627
+ parser.add_argument("--no-open", action="store_true", help="Browser nicht automatisch öffnen")
628
+ parser.add_argument("--allow-network", action="store_true", help="Erlaubt explizit Bindung außerhalb von localhost.")
629
+ cli_args = parser.parse_args()
630
+ run_server(host=cli_args.host, port=cli_args.port, open_browser=not cli_args.no_open, allow_network=cli_args.allow_network)