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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 blackthis
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,67 @@
1
- # Temporary Holding Version
1
+ # BLACKTHIS – 100 % lokaler DSGVO-Schwärzer für CSV, Excel & PDF
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Ein hochpräzises Offline-Tool zum automatischen und manuellen Schwärzen sensibler Daten Dritter in **CSV-**, **Excel- (`.xlsx`)** und **PDF-Dateien** für **DSGVO Art. 15 Auskunftsersuchen** — **100 % lokal auf deinem Rechner, ohne Cloud und ohne Chat-LLM**.
4
+
5
+ ---
6
+
7
+ ## Schnellstart per npm (macOS, Linux & Windows)
8
+
9
+ ### Direkt starten (ohne manuelles Setup)
10
+ ```bash
11
+ npx blackthis
12
+ ```
13
+ Oder einmalig global installieren, damit überall im Terminal **`blackthis`** reicht:
14
+ ```bash
15
+ npm install -g blackthis
16
+ blackthis
17
+ ```
18
+
19
+ - **Beim ersten Start** richtet `blackthis` automatisch eine dauerhafte lokale Python-Umgebung in `~/.blackthis/venv` ein und lädt einmalig das deutsche Sprachmodell (`de_core_news_lg`, ~550 MB).
20
+ - **Bei jedem weiteren Start** öffnet sich sofort die lokale Browser-Oberfläche auf `127.0.0.1` (mit automatischer Port-Suche, falls Port `8765` belegt ist) — **100 % offline**.
21
+
22
+ ### Weitere Befehle
23
+ ```bash
24
+ blackthis --port 8799 # Bevorzugten Port setzen
25
+ blackthis --no-open # Server starten, ohne Browser zu öffnen
26
+ blackthis --setup # Lokale Umgebung & Sprachmodell manuell einrichten/reparieren
27
+ blackthis --cli --input datei.csv --vorname Max --nachname Mustermann
28
+ blackthis --cli --input dokument.pdf --vorname Max --nachname Mustermann
29
+ ```
30
+
31
+ ---
32
+
33
+ ## Highlights & Funktionen
34
+
35
+ ### Unterstützte Formate
36
+ - **CSV (`.csv` / `.txt`):** Automatische Erkennung von Encoding (UTF-8, UTF-8-BOM, CP1252/Latin-1), Trennzeichen (`;`, `,`, Tab, `|`) und mehrzeiligen Zellen.
37
+ - **Excel (`.xlsx`):** Direktes Einlesen & Exportieren als formatierte Arbeitsmappe.
38
+ - **PDF (`.pdf`) – echte In-Place-Schwärzung:** Original-Layout, Tabellen und Briefköpfe bleiben 1:1 erhalten; geschwärzter Text, überlappende `mailto:`/`tel:`/URL-Links und PDF-Metadaten werden **unwiderruflich** aus dem PDF entfernt. Inkl. visueller **PDF-Vorschau (Original vs. Geschwärzt)** im Browser und automatischer Warnung bei reinen Bild-Scans ohne Text-Ebene.
39
+
40
+ ### Erkennung & Datenschutz-Logik
41
+ - **Klarnamen (Dritte):** Anreden, Kontextregeln, E-Mail-Signaturen, JSON-/HTML-Payloads, Intra-Zellen-Namenspropagation sowie lokale deutsche Sprach-KI (`spaCy de_core_news_lg`) kombiniert mit lokalem deutschem Häufigkeits-Wörterbuch (`wordfreq`) gegen Fehlalarme bei normalen Substantiven.
42
+ - **Antragsteller-Schutz:** Vor- und Nachname des Antragstellers (inkl. Anreden, Initialen und Umlaut-Varianten wie `Hübner` ↔ `Huebner`) bleiben sichtbar, ohne fremde Namensvettern zu leaken.
43
+ - **Strukturierte PII:** Adressen, Straßen, Hausnummern, PLZ (DE/AT/CH), Ortschaften (Behörden wie `Stadt Köln` bleiben sichtbar), IBAN (ISO-13616-Prüfziffer) / BIC / Bankdaten, Job-Positionen, Geldbeträge, Telefonnummern, E-Mails, URLs, IP-Adressen, Geburtsdaten, Kfz-Kennzeichen, Steuer-/USt-IDs sowie optional Firmennamen.
44
+
45
+ ### Interaktive Prüfung & Exporte
46
+ - **Gelbe Prüffälle-Navigator:** Nummerierte Badges (`#1`, `#2`, …), Sprung-Buttons (`← Zurück | Check | Vor →`) und automatisch einblendende Prüf-Leiste beim Scrollen.
47
+ - **1-Klick-Umschalten & Maus-Markierung:** Beliebigen Text im Original markieren → **🔒 Nur hier schwärzen** (lila), **🔒 Überall schwärzen** (blau) oder **✓ Überall freigeben** (grün).
48
+ - **Live-Schwärzungs-Text:** Jederzeit ohne neuen Scan umschaltbar zwischen `██████`, **`[GESCHWÄRZT]`**, **`[SECRET]`**, Kategorie-Platzhaltern (`[NAME]`, `[IBAN]`) oder eigenem Text.
49
+ - **Exporte:** Geschwärztes **PDF**, **CSV** oder **Excel (`.xlsx`)** sowie **Audit ohne Originale (CSV)**, **Interner Prüfbericht (HTML)** und **Internes Audit-Log (CSV)**.
50
+
51
+ ---
52
+
53
+ ## Direkt im Projektordner nutzen (macOS)
54
+
55
+ ```bash
56
+ chmod +x setup_mac.command start_ui.command
57
+ ./setup_mac.command
58
+ ./start_ui.command
59
+ ```
60
+
61
+ ## Auf npmjs.com veröffentlichen
62
+
63
+ ```bash
64
+ npm login
65
+ npm pack --dry-run # Prüfen, welche Dateien genau im Paket landen
66
+ npm publish # Veröffentlicht 'blackthis' (falls vergeben: in package.json z. B. '@deinname/blackthis' setzen)
67
+ ```
@@ -0,0 +1,255 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ const { spawn, spawnSync } = require("child_process");
5
+ const crypto = require("crypto");
6
+ const fs = require("fs");
7
+ const os = require("os");
8
+ const path = require("path");
9
+
10
+ const PKG_ROOT = path.resolve(__dirname, "..");
11
+ const PKG_JSON = JSON.parse(fs.readFileSync(path.join(PKG_ROOT, "package.json"), "utf8"));
12
+ const REQUIREMENTS_FILE = path.join(PKG_ROOT, "requirements.txt");
13
+ const HOME_STATE_DIR = path.join(os.homedir(), ".blackthis");
14
+ const HOME_VENV_DIR = path.join(HOME_STATE_DIR, "venv");
15
+ const DEPS_HASH_FILE = path.join(HOME_STATE_DIR, ".deps_hash");
16
+ const IS_WIN = process.platform === "win32";
17
+
18
+ function venvPythonPath(venvDir) {
19
+ return IS_WIN
20
+ ? path.join(venvDir, "Scripts", "python.exe")
21
+ : path.join(venvDir, "bin", "python");
22
+ }
23
+
24
+ function runSync(cmd, args, opts = {}) {
25
+ return spawnSync(cmd, args, {
26
+ stdio: opts.silent ? "pipe" : "inherit",
27
+ encoding: "utf8",
28
+ ...opts,
29
+ });
30
+ }
31
+
32
+ function hasCommand(cmd) {
33
+ const res = runSync(cmd, ["--version"], { silent: true });
34
+ return res.status === 0;
35
+ }
36
+
37
+ function getPythonVersion(pyBin) {
38
+ const res = runSync(
39
+ pyBin,
40
+ ["-c", "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')"],
41
+ { silent: true }
42
+ );
43
+ if (res.status !== 0 || !res.stdout) return null;
44
+ const [maj, min] = res.stdout.trim().split(".").map(Number);
45
+ if (Number.isNaN(maj) || Number.isNaN(min)) return null;
46
+ return { major: maj, minor: min };
47
+ }
48
+
49
+ function findSuitableSystemPython() {
50
+ const candidates = IS_WIN
51
+ ? ["python", "python3", "py"]
52
+ : ["python3.12", "python3.11", "python3.13", "python3.10", "python3", "python"];
53
+
54
+ for (const bin of candidates) {
55
+ const ver = getPythonVersion(bin);
56
+ if (ver && ver.major === 3 && ver.minor >= 10 && ver.minor <= 13) {
57
+ return bin;
58
+ }
59
+ }
60
+ return null;
61
+ }
62
+
63
+ function computeRequirementsHash() {
64
+ const content = fs.readFileSync(REQUIREMENTS_FILE, "utf8");
65
+ return crypto.createHash("sha256").update(content).digest("hex").slice(0, 16);
66
+ }
67
+
68
+ function pythonCanImport(pyBin, moduleName) {
69
+ const res = runSync(pyBin, ["-c", `import ${moduleName}`], { silent: true });
70
+ return res.status === 0;
71
+ }
72
+
73
+ function hasGermanSpacyModel(pyBin) {
74
+ const code = [
75
+ "import spacy",
76
+ "ok = any(spacy.util.is_package(m) for m in ('de_core_news_lg', 'de_core_news_md', 'de_core_news_sm'))",
77
+ "raise SystemExit(0 if ok else 1)",
78
+ ].join("; ");
79
+ const res = runSync(pyBin, ["-c", code], { silent: true });
80
+ return res.status === 0;
81
+ }
82
+
83
+ function ensureEnvironment({ forceSetup = false, skipModel = false } = {}) {
84
+ // 1. Falls direkt im lokalen Projektordner mit fertigem .venv gestartet wird -> direkt wiederverwenden!
85
+ const localVenvPy = venvPythonPath(path.join(PKG_ROOT, ".venv"));
86
+ if (!forceSetup && fs.existsSync(localVenvPy) && pythonCanImport(localVenvPy, "uvicorn")) {
87
+ if (!skipModel && pythonCanImport(localVenvPy, "spacy") && !hasGermanSpacyModel(localVenvPy)) {
88
+ console.log("\nLade lokales deutsches Sprachmodell (de_core_news_lg, ~550 MB, einmalig)...");
89
+ runSync(localVenvPy, ["-m", "spacy", "download", "de_core_news_lg"]);
90
+ }
91
+ return localVenvPy;
92
+ }
93
+
94
+ // 2. Persistente Umgebung in ~/.blackthis/venv nutzen (überlebt npx-Updates ohne Modell-Redownload!)
95
+ fs.mkdirSync(HOME_STATE_DIR, { recursive: true });
96
+ const pyBin = venvPythonPath(HOME_VENV_DIR);
97
+ const targetHash = computeRequirementsHash();
98
+ const currentHash = fs.existsSync(DEPS_HASH_FILE)
99
+ ? fs.readFileSync(DEPS_HASH_FILE, "utf8").trim()
100
+ : "";
101
+
102
+ const needVenv = forceSetup || !fs.existsSync(pyBin);
103
+ const needDeps = needVenv || currentHash !== targetHash || !pythonCanImport(pyBin, "uvicorn");
104
+
105
+ if (needVenv) {
106
+ console.log("==============================================");
107
+ console.log(` blackthis v${PKG_JSON.version} – Einmalige Einrichtung`);
108
+ console.log("==============================================\n");
109
+
110
+ const useUv = hasCommand("uv");
111
+ if (useUv) {
112
+ console.log("1/3 Erstelle lokale Python-3.12-Umgebung via uv (~/.blackthis/venv)...");
113
+ const res = runSync("uv", ["venv", "--seed", "--python", "3.12", HOME_VENV_DIR]);
114
+ if (res.status !== 0) {
115
+ console.error("Fehler beim Erstellen der Python-Umgebung mit uv.");
116
+ process.exit(1);
117
+ }
118
+ } else {
119
+ const sysPy = findSuitableSystemPython();
120
+ if (!sysPy) {
121
+ console.error("\nFehler: Kein passendes Python (3.10 – 3.13) gefunden.");
122
+ console.error("Schnell-Installation auf macOS (1 Befehl im Terminal):");
123
+ console.error(" brew install python@3.12");
124
+ console.error("Oder installiere uv (lädt Python automatisch): https://docs.astral.sh/uv/\n");
125
+ process.exit(1);
126
+ }
127
+ console.log(`1/3 Erstelle lokale Python-Umgebung (${sysPy} -> ~/.blackthis/venv)...`);
128
+ const res = runSync(sysPy, ["-m", "venv", HOME_VENV_DIR]);
129
+ if (res.status !== 0) {
130
+ console.error("Fehler beim Erstellen der virtuellen Python-Umgebung.");
131
+ process.exit(1);
132
+ }
133
+ }
134
+ }
135
+
136
+ if (needDeps) {
137
+ console.log("2/3 Installiere Python-Pakete (FastAPI, Uvicorn, spaCy, openpyxl, wordfreq, PyMuPDF)...");
138
+ let installRes;
139
+ if (hasCommand("uv")) {
140
+ installRes = runSync("uv", ["pip", "install", "--python", pyBin, "-r", REQUIREMENTS_FILE]);
141
+ } else {
142
+ runSync(pyBin, ["-m", "pip", "install", "--upgrade", "pip"]);
143
+ installRes = runSync(pyBin, ["-m", "pip", "install", "-r", REQUIREMENTS_FILE]);
144
+ }
145
+ if (installRes.status !== 0) {
146
+ console.error("Fehler bei der Paket-Installation.");
147
+ process.exit(1);
148
+ }
149
+ fs.writeFileSync(DEPS_HASH_FILE, targetHash, "utf8");
150
+ }
151
+
152
+ if (!skipModel && !hasGermanSpacyModel(pyBin)) {
153
+ console.log("3/3 Lade lokales deutsches Sprachmodell (de_core_news_lg, ~550 MB, einmalig)...");
154
+ console.log(" Danach läuft blackthis zu 100 % offline ohne Internet.\n");
155
+ const dlRes = runSync(pyBin, ["-m", "spacy", "download", "de_core_news_lg"]);
156
+ if (dlRes.status !== 0) {
157
+ console.warn(
158
+ "\nHinweis: Sprachmodell konnte nicht geladen werden – starte im Regel-Modus.\n" +
159
+ "Du kannst das Modell später mit 'blackthis --setup' nachladen.\n"
160
+ );
161
+ }
162
+ }
163
+
164
+ return pyBin;
165
+ }
166
+
167
+ function printHelp() {
168
+ console.log(`
169
+ blackthis v${PKG_JSON.version} – 100 % lokaler DSGVO Schwärzer für CSV, Excel & PDF (Offline)
170
+
171
+ Verwendung:
172
+ blackthis Startet lokale Browser-Oberfläche (sucht automatisch freien Port)
173
+ blackthis --port 8799 Bevorzugten Port setzen (Standard: 8765)
174
+ blackthis --no-open Startet Server ohne den Browser automatisch zu öffnen
175
+ blackthis --cli [OPTIONEN] Startet den schnellen Terminal-Modus (CSV, Excel & PDF)
176
+ blackthis --setup Richtet lokale Python-Umgebung & deutsches Sprachmodell ein/neu ein
177
+ blackthis --no-model Startet ohne Download des 550-MB-Sprachmodells (nur Regeln)
178
+ blackthis --version Zeigt die Version an
179
+ blackthis --help Zeigt diese Hilfe an
180
+
181
+ Beispiel Terminal-Modus:
182
+ blackthis --cli --input meine_datei.csv --vorname Max --nachname Mustermann
183
+ blackthis --cli --input dokument.pdf --vorname Max --nachname Mustermann
184
+ `);
185
+ }
186
+
187
+ function main() {
188
+ const args = process.argv.slice(2);
189
+ const cliIdx = args.indexOf("--cli");
190
+ const isCliMode = cliIdx !== -1;
191
+
192
+ if (!isCliMode && (args.includes("--help") || args.includes("-h"))) {
193
+ printHelp();
194
+ return;
195
+ }
196
+ if (!isCliMode && (args.includes("--version") || args.includes("-v"))) {
197
+ console.log(`blackthis v${PKG_JSON.version}`);
198
+ return;
199
+ }
200
+
201
+ const forceSetup = args.includes("--setup");
202
+ const skipModel = args.includes("--no-model");
203
+
204
+ const pyBin = ensureEnvironment({ forceSetup, skipModel });
205
+
206
+ if (forceSetup && args.length === 1) {
207
+ console.log("\nEinrichtung abgeschlossen! Starte das Tool jederzeit mit: blackthis\n");
208
+ return;
209
+ }
210
+
211
+ const env = {
212
+ ...process.env,
213
+ PYTHONPATH: process.env.PYTHONPATH
214
+ ? `${PKG_ROOT}${path.delimiter}${process.env.PYTHONPATH}`
215
+ : PKG_ROOT,
216
+ };
217
+
218
+ let pyArgs;
219
+ if (isCliMode) {
220
+ const forwarded = args.filter((_, i) => i !== cliIdx && args[i] !== "--setup" && args[i] !== "--no-model");
221
+ pyArgs = ["-m", "dsgvo_redactor.cli", ...forwarded];
222
+ } else {
223
+ const webArgs = [];
224
+ for (let i = 0; i < args.length; i++) {
225
+ const a = args[i];
226
+ if ((a === "--port" || a === "-p") && args[i + 1]) {
227
+ webArgs.push("--port", args[++i]);
228
+ } else if (a === "--host" && args[i + 1]) {
229
+ webArgs.push("--host", args[++i]);
230
+ } else if (a === "--no-open") {
231
+ webArgs.push("--no-open");
232
+ } else if (a === "--allow-network") {
233
+ webArgs.push("--allow-network");
234
+ }
235
+ }
236
+ pyArgs = ["-m", "dsgvo_redactor.web_app", ...webArgs];
237
+ }
238
+
239
+ const child = spawn(pyBin, pyArgs, {
240
+ stdio: "inherit",
241
+ env,
242
+ });
243
+
244
+ const forwardSignal = (sig) => {
245
+ if (!child.killed) child.kill(sig);
246
+ };
247
+ process.on("SIGINT", () => forwardSignal("SIGINT"));
248
+ process.on("SIGTERM", () => forwardSignal("SIGTERM"));
249
+
250
+ child.on("exit", (code) => {
251
+ process.exit(code ?? 0);
252
+ });
253
+ }
254
+
255
+ main();
@@ -0,0 +1,3 @@
1
+ """DSGVO CSV Redactor – hochpräzises Offline-Schwärzungstool für DSGVO-Auskünfte."""
2
+
3
+ __version__ = "1.0.0"
@@ -0,0 +1,214 @@
1
+ """Kommandozeilen-Interface (CLI) für den DSGVO CSV Redactor."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from .csv_io import dump_xlsx_bytes, load_csv_file, write_csv_file
10
+ from .engine import RedactionEngine
11
+ from .models import RedactionConfig
12
+ from .pdf_redactor import apply_pdf_redactions_to_bytes, extract_pdf_document, is_pdf_bytes
13
+ from .report import build_audit_csv_bytes, build_audit_json, build_html_report
14
+
15
+
16
+ def build_parser() -> argparse.ArgumentParser:
17
+ p = argparse.ArgumentParser(
18
+ prog="redact_csv.py",
19
+ description="DSGVO CSV Redactor – 100 % lokales Schwärzungstool für DSGVO-Auskünfte (ohne Cloud / ohne LLM).",
20
+ )
21
+ p.add_argument("-i", "--input", required=True, help="Pfad zur Eingabe-CSV-Datei.")
22
+ p.add_argument(
23
+ "-o",
24
+ "--output",
25
+ help="Pfad zur geschwärzten Ausgabe-CSV (Standard: <eingabe>_geschwaerzt.csv).",
26
+ )
27
+ p.add_argument("--vorname", default="", help="Vorname des Antragstellers (bleibt ungeschwärzt).")
28
+ p.add_argument("--nachname", default="", help="Nachname des Antragstellers (bleibt ungeschwärzt).")
29
+ p.add_argument(
30
+ "--whitelist",
31
+ nargs="*",
32
+ default=[],
33
+ help="Weitere Begriffe, die NICHT geschwärzt werden sollen (z. B. Kürzel, Geburtsname).",
34
+ )
35
+ p.add_argument(
36
+ "--blacklist",
37
+ nargs="*",
38
+ default=[],
39
+ help="Weitere Begriffe, die IMMER geschwärzt werden sollen.",
40
+ )
41
+ p.add_argument(
42
+ "--columns",
43
+ nargs="*",
44
+ default=None,
45
+ help="Spaltennamen, die gescannt werden sollen (Standard: automatisch z. B. 'Notiz').",
46
+ )
47
+ p.add_argument(
48
+ "--replacement",
49
+ default="██████",
50
+ help="Ersetzungstext für geschwärzte Stellen (Standard: ██████).",
51
+ )
52
+ p.add_argument(
53
+ "--typed-placeholders",
54
+ action="store_true",
55
+ help="Verwendet kategoriebezogene Platzhalter wie [NAME], [IBAN] statt einheitlichem Balken.",
56
+ )
57
+ p.add_argument(
58
+ "--redact-companies",
59
+ action="store_true",
60
+ help="Schwärzt zusätzlich Firmennamen / Organisationen (standardmäßig deaktiviert).",
61
+ )
62
+ p.add_argument(
63
+ "--no-locations",
64
+ action="store_true",
65
+ help="Deaktiviert die Schwärzung alleinstehender Ortschaften / Städte (Behörden wie 'Stadt Köln' bleiben immer sichtbar).",
66
+ )
67
+ p.add_argument(
68
+ "--keep-uncertain",
69
+ action="store_true",
70
+ help="Unsichere Fälle NICHT automatisch schwärzen (Standard: im Zweifel schwärzen).",
71
+ )
72
+ p.add_argument(
73
+ "--no-ner",
74
+ action="store_true",
75
+ help="Deaktiviert die lokale spaCy-Sprach-KI (nur feste Regeln & Listen).",
76
+ )
77
+ p.add_argument(
78
+ "--delimiter",
79
+ default=None,
80
+ help="Optional festes CSV-Trennzeichen (Standard: automatische Erkennung).",
81
+ )
82
+ p.add_argument(
83
+ "--report",
84
+ default=None,
85
+ help="Pfad für HTML-Prüfbericht (Standard: <output>_pruefbericht.html). 'none' zum Deaktivieren.",
86
+ )
87
+ p.add_argument(
88
+ "--audit-csv",
89
+ default=None,
90
+ help="Optionaler Pfad für detailliertes Audit-Protokoll als CSV.",
91
+ )
92
+ p.add_argument(
93
+ "--audit-json",
94
+ default=None,
95
+ help="Optionaler Pfad für detailliertes Audit-Protokoll als JSON.",
96
+ )
97
+ p.add_argument(
98
+ "--xlsx",
99
+ default=None,
100
+ help="Optionaler Pfad für zusätzlichen Excel-Export (.xlsx).",
101
+ )
102
+ return p
103
+
104
+
105
+ def main(argv: list[str] | None = None) -> int:
106
+ parser = build_parser()
107
+ args = parser.parse_args(argv)
108
+
109
+ input_path = Path(args.input)
110
+ if not input_path.is_file():
111
+ print(f"Fehler: Datei nicht gefunden: {input_path}", file=sys.stderr)
112
+ return 1
113
+
114
+ raw_input = input_path.read_bytes()
115
+ pdf_doc = None
116
+ if is_pdf_bytes(raw_input, input_path.name):
117
+ pdf_doc = extract_pdf_document(raw_input)
118
+ loaded = pdf_doc.loaded
119
+ output_path = (
120
+ Path(args.output)
121
+ if args.output
122
+ else input_path.with_name(f"{input_path.stem}_geschwaerzt.pdf")
123
+ )
124
+ else:
125
+ loaded = load_csv_file(input_path, delimiter=args.delimiter)
126
+ output_path = (
127
+ Path(args.output)
128
+ if args.output
129
+ else input_path.with_name(f"{input_path.stem}_geschwaerzt.csv")
130
+ )
131
+ if not loaded.headers:
132
+ print("Fehler: Eingabedatei scheint leer zu sein.", file=sys.stderr)
133
+ return 1
134
+
135
+ config = RedactionConfig(
136
+ applicant_first_name=args.vorname,
137
+ applicant_last_name=args.nachname,
138
+ extra_whitelist=args.whitelist,
139
+ extra_blacklist=args.blacklist,
140
+ replacement=args.replacement,
141
+ use_typed_placeholders=args.typed_placeholders,
142
+ redact_companies=args.redact_companies,
143
+ redact_locations=not args.no_locations,
144
+ redact_uncertain_by_default=not args.keep_uncertain,
145
+ use_ner=not args.no_ner,
146
+ columns=["Text"] if pdf_doc is not None else args.columns,
147
+ )
148
+
149
+ engine = RedactionEngine()
150
+ redacted_rows, cell_results, summary = engine.scan_rows(
151
+ headers=loaded.headers,
152
+ rows=loaded.rows,
153
+ config=config,
154
+ encoding=loaded.encoding,
155
+ delimiter=loaded.delimiter,
156
+ )
157
+
158
+ if pdf_doc is not None:
159
+ output_path.write_bytes(apply_pdf_redactions_to_bytes(pdf_doc, cell_results, config))
160
+ else:
161
+ write_csv_file(
162
+ output_path,
163
+ headers=loaded.headers,
164
+ rows=redacted_rows,
165
+ delimiter=loaded.delimiter,
166
+ encoding="utf-8-sig",
167
+ )
168
+
169
+ report_path: Path | None = None
170
+ if args.report != "none":
171
+ report_path = (
172
+ Path(args.report)
173
+ if args.report
174
+ else output_path.with_name(f"{output_path.stem}_pruefbericht.html")
175
+ )
176
+ html_content = build_html_report(input_path.name, summary, cell_results, config)
177
+ report_path.write_text(html_content, encoding="utf-8")
178
+
179
+ if args.audit_csv:
180
+ Path(args.audit_csv).write_bytes(build_audit_csv_bytes(cell_results))
181
+
182
+ if args.audit_json:
183
+ Path(args.audit_json).write_text(
184
+ build_audit_json(input_path.name, summary, cell_results), encoding="utf-8"
185
+ )
186
+
187
+ if args.xlsx:
188
+ Path(args.xlsx).write_bytes(dump_xlsx_bytes(loaded.headers, redacted_rows))
189
+
190
+ unit_lbl = "Seiten" if pdf_doc is not None else "Zeilen"
191
+ out_lbl = "Ausgabe-PDF:" if pdf_doc is not None else "Ausgabe-CSV:"
192
+ print("=== BLACKTHIS – DSGVO Redactor Ergebnis ===")
193
+ print(f"Eingabe: {input_path} ({summary.total_rows} {unit_lbl}, Encoding {loaded.encoding})")
194
+ print(f"Gescannte Spalten: {', '.join(summary.scanned_columns)}")
195
+ print(f"Lokale Sprach-KI: {summary.ner_model_name if summary.ner_active else 'DEAKTIVIERT (nur Regeln)'}")
196
+ print(f"Antragsteller: {(args.vorname + ' ' + args.nachname).strip() or '—'} ({summary.protected_applicant_hits} geschützte Stellen)")
197
+ print(f"Geschwärzte Stellen: {summary.total_redactions} (davon {summary.review_findings} unsichere Fälle zur Prüfung)")
198
+ if summary.by_category:
199
+ print("Nach Kategorie:")
200
+ for cat, cnt in summary.by_category.items():
201
+ print(f" - {cat}: {cnt}")
202
+ print(f"{out_lbl:<23}{output_path}")
203
+ if report_path:
204
+ print(f"HTML-Prüfbericht: {report_path}")
205
+ if args.xlsx:
206
+ print(f"Excel-Export: {args.xlsx}")
207
+ if args.audit_csv:
208
+ print(f"Audit-CSV: {args.audit_csv}")
209
+
210
+ return 0
211
+
212
+
213
+ if __name__ == "__main__":
214
+ raise SystemExit(main())