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,393 @@
1
+ """100 % lokaler Pure-Python PDF-1.4-Export mit echten schwarzen Schwärzungsbalken (0 Extra-Abhängigkeiten)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import zlib
7
+ from typing import Sequence
8
+
9
+ from .models import RedactionConfig, ScanSummary
10
+
11
+ # DIN A4 Querformat (Punkte: 1 pt = 1/72 inch)
12
+ PAGE_W = 841.89
13
+ PAGE_H = 595.28
14
+ MARGIN_X = 32.0
15
+ MARGIN_TOP = 32.0
16
+ MARGIN_BOTTOM = 34.0
17
+ USABLE_W = PAGE_W - 2 * MARGIN_X
18
+
19
+ # Zeichen, die nicht in WinAnsi/CP1252 liegen, sauber auf lesbare Entsprechungen abbilden
20
+ _UNICODE_FALLBACKS = str.maketrans({
21
+ "\u2013": "-", # –
22
+ "\u2014": "-", # —
23
+ "\u2018": "'", # ‘
24
+ "\u2019": "'", # ’
25
+ "\u201a": ",", # ‚
26
+ "\u201c": '"', # “
27
+ "\u201d": '"', # ”
28
+ "\u201e": '"', # „
29
+ "\u2026": "...", # …
30
+ "\u00a0": " ", # NBSP
31
+ "\u202f": " ", # Narrow NBSP
32
+ "\u200b": "", # Zero-width space
33
+ "\u2192": "->", # →
34
+ "\u2022": "*", # •
35
+ "\u2713": "OK", # ✓
36
+ "\u2714": "OK", # ✔
37
+ "\u2212": "-", # −
38
+ })
39
+
40
+ _REDACT_RUN_RE = re.compile(r"(█+|\[GESCHWÄRZT\]|\[SECRET\])")
41
+
42
+ # Vorkalkulierte ASCII-Breitentabelle (O(1)-Lookup statt Schleifen-Frozenset-Check pro Zeichen)
43
+ _NARROW_CHARS = frozenset("ilI1.,:;!'|()[]{}tfj ")
44
+ _WIDE_CHARS = frozenset("mwMWÄÖÜ@%#&")
45
+ _ASCII_WIDTH_FACTOR: tuple[float, ...] = tuple(
46
+ 0.30 if chr(c) in _NARROW_CHARS
47
+ else (0.78 if chr(c) in _WIDE_CHARS else (0.66 if 65 <= c <= 90 else 0.52))
48
+ for c in range(128)
49
+ )
50
+
51
+
52
+ def _char_width(ch: str, font_size: float) -> float:
53
+ code = ord(ch)
54
+ if code < 128:
55
+ return font_size * _ASCII_WIDTH_FACTOR[code]
56
+ if ch == "█":
57
+ return font_size * 0.58
58
+ if ch in _WIDE_CHARS:
59
+ return font_size * 0.78
60
+ return font_size * (0.66 if ch.isupper() else 0.52)
61
+
62
+
63
+ def _text_width(text: str, font_size: float) -> float:
64
+ factors = _ASCII_WIDTH_FACTOR
65
+ total = 0.0
66
+ for ch in text:
67
+ code = ord(ch)
68
+ if code < 128:
69
+ total += factors[code]
70
+ elif ch == "█":
71
+ total += 0.58
72
+ elif ch in _WIDE_CHARS:
73
+ total += 0.78
74
+ else:
75
+ total += 0.66 if ch.isupper() else 0.52
76
+ return total * font_size
77
+
78
+
79
+ def _bar_width_for_run(run: str, font_size: float) -> float:
80
+ return min(font_size * 4.6, max(font_size * 1.8, len(run) * font_size * 0.62))
81
+
82
+
83
+ def _line_width(line: str, font_size: float) -> float:
84
+ total = 0.0
85
+ for part in _REDACT_RUN_RE.split(line):
86
+ if not part:
87
+ continue
88
+ if part[0] == "█":
89
+ total += _bar_width_for_run(part, font_size)
90
+ else:
91
+ total += _text_width(part, font_size)
92
+ return total
93
+
94
+
95
+ def _pdf_str(text: str) -> bytes:
96
+ """Kodiert Text nach WinAnsi (CP1252) und escaped PDF-String-Sonderzeichen."""
97
+ cleaned = text.translate(_UNICODE_FALLBACKS)
98
+ raw = cleaned.encode("cp1252", errors="replace")
99
+ out = bytearray(b"(")
100
+ for b in raw:
101
+ if b in (0x28, 0x29, 0x5C): # (, ), \
102
+ out.append(0x5C)
103
+ out.append(b)
104
+ elif b < 0x20:
105
+ out.append(0x20)
106
+ else:
107
+ out.append(b)
108
+ out.append(0x29)
109
+ return bytes(out)
110
+
111
+
112
+ def _wrap_cell_text(text: str, max_width: float, font_size: float) -> list[str]:
113
+ """Bricht mehrzeiligen Zellentext sauber auf max_width um (inkl. langer Wörter & Schwärzungsbalken)."""
114
+ if not text:
115
+ return [""]
116
+
117
+ safe_max = max(20.0, max_width)
118
+ lines: list[str] = []
119
+
120
+ for raw_para in text.replace("\r\n", "\n").replace("\r", "\n").split("\n"):
121
+ if not raw_para:
122
+ lines.append("")
123
+ continue
124
+ words = raw_para.split(" ")
125
+ current = ""
126
+ for word in words:
127
+ candidate = word if not current else f"{current} {word}"
128
+ if _line_width(candidate, font_size) <= safe_max:
129
+ current = candidate
130
+ continue
131
+ if current:
132
+ lines.append(current)
133
+ current = ""
134
+ # Einzelnes Wort ist länger als die Spaltenbreite -> hart umbrechen
135
+ if _line_width(word, font_size) <= safe_max:
136
+ current = word
137
+ else:
138
+ buf = ""
139
+ for ch in word:
140
+ if buf and _line_width(buf + ch, font_size) > safe_max:
141
+ lines.append(buf)
142
+ buf = ch
143
+ else:
144
+ buf += ch
145
+ current = buf
146
+ if current or not words:
147
+ lines.append(current)
148
+
149
+ return lines or [""]
150
+
151
+
152
+ def _compute_column_widths(headers: Sequence[str], rows: Sequence[dict[str, str]]) -> list[float]:
153
+ """Berechnet harmonische Spaltenbreiten (Textspalten bekommen deutlich mehr Platz)."""
154
+ if not headers:
155
+ return []
156
+ text_names = {"notiz", "notizen", "nachricht", "nachrichten", "text", "kommentar", "bemerkung", "beschreibung", "inhalt"}
157
+ sample = rows[:120]
158
+ weights: list[float] = []
159
+
160
+ for h in headers:
161
+ hl = h.strip().lower()
162
+ if hl in text_names:
163
+ weights.append(5.8)
164
+ continue
165
+ avg_len = 0.0
166
+ if sample:
167
+ avg_len = sum(len(str(r.get(h, "") or "")) for r in sample) / len(sample)
168
+ if avg_len > 65:
169
+ weights.append(5.2)
170
+ elif avg_len > 25:
171
+ weights.append(2.2)
172
+ else:
173
+ weights.append(max(1.0, min(1.8, max(len(h), avg_len) / 10.0)))
174
+
175
+ total_w = sum(weights) or 1.0
176
+ widths = [(w / total_w) * USABLE_W for w in weights]
177
+ # Mindestbreite pro Spalte absichern
178
+ min_col = min(56.0, USABLE_W / len(headers))
179
+ widths = [max(min_col, w) for w in widths]
180
+ scale = USABLE_W / sum(widths)
181
+ return [w * scale for w in widths]
182
+
183
+
184
+ def _draw_line_with_redaction_bars(
185
+ ops: list[bytes],
186
+ line: str,
187
+ x_start: float,
188
+ baseline_y: float,
189
+ font_size: float,
190
+ bold: bool = False,
191
+ ) -> None:
192
+ """Zeichnet eine Textzeile und ersetzt █-Läufe durch echte gefüllte schwarze Vektorbalken."""
193
+ font_tag = b"/F2" if bold else b"/F1"
194
+ x = x_start
195
+ for part in _REDACT_RUN_RE.split(line):
196
+ if not part:
197
+ continue
198
+ if part[0] == "█":
199
+ bar_w = _bar_width_for_run(part, font_size)
200
+ bar_h = font_size + 1.4
201
+ bar_y = baseline_y - 1.8
202
+ ops.append(
203
+ f"0.04 0.06 0.11 rg {x:.2f} {bar_y:.2f} {bar_w:.2f} {bar_h:.2f} re f\n".encode("ascii")
204
+ )
205
+ x += bar_w + 0.8
206
+ elif part in ("[GESCHWÄRZT]", "[SECRET]"):
207
+ ops.append(
208
+ b"0.02 0.04 0.09 rg BT /F2"
209
+ + f" {font_size:.2f} Tf {x:.2f} {baseline_y:.2f} Td ".encode("ascii")
210
+ + _pdf_str(part)
211
+ + b" Tj ET\n"
212
+ )
213
+ x += _text_width(part, font_size) * 1.04
214
+ else:
215
+ ops.append(
216
+ b"0.08 0.11 0.18 rg BT "
217
+ + font_tag
218
+ + f" {font_size:.2f} Tf {x:.2f} {baseline_y:.2f} Td ".encode("ascii")
219
+ + _pdf_str(part)
220
+ + b" Tj ET\n"
221
+ )
222
+ x += _text_width(part, font_size)
223
+
224
+
225
+ def dump_pdf_bytes(
226
+ headers: list[str],
227
+ rows: list[dict[str, str]],
228
+ filename: str = "auskunft.csv",
229
+ summary: ScanSummary | None = None,
230
+ config: RedactionConfig | None = None,
231
+ ) -> bytes:
232
+ """Erstellt eine druckfertige, mehrseitige DIN-A4-Querformat-PDF mit echten schwarzen Schwärzungsbalken."""
233
+ col_widths = _compute_column_widths(headers, rows)
234
+ font_size = 8.4 if len(headers) <= 7 else 7.4
235
+ header_font_size = 8.6 if len(headers) <= 7 else 7.6
236
+ line_height = font_size + 3.0
237
+ cell_pad_x = 5.0
238
+ cell_pad_y = 4.5
239
+
240
+ pages_ops: list[list[bytes]] = []
241
+
242
+ def _start_page() -> tuple[list[bytes], float]:
243
+ ops: list[bytes] = []
244
+ y = PAGE_H - MARGIN_TOP
245
+
246
+ # Tabellen-Kopfzeile (wird auf jeder Seite wiederholt)
247
+ th_h = 20.0
248
+ th_y = y - th_h
249
+ ops.append(
250
+ f"0.12 0.16 0.23 rg {MARGIN_X:.2f} {th_y:.2f} {USABLE_W:.2f} {th_h:.2f} re f\n".encode("ascii")
251
+ )
252
+ cx = MARGIN_X
253
+ for h, cw in zip(headers, col_widths):
254
+ short_h = _wrap_cell_text(h, cw - 2 * cell_pad_x, header_font_size)[0]
255
+ ops.append(
256
+ b"1 1 1 rg BT /F2 "
257
+ + f"{header_font_size:.2f} Tf {cx + cell_pad_x:.2f} {th_y + 6.5:.2f} Td ".encode("ascii")
258
+ + _pdf_str(short_h)
259
+ + b" Tj ET\n"
260
+ )
261
+ cx += cw
262
+
263
+ pages_ops.append(ops)
264
+ return ops, th_y
265
+
266
+ cur_ops, cur_y = _start_page()
267
+ min_y = MARGIN_BOTTOM + 14.0
268
+
269
+ for row_idx, row in enumerate(rows):
270
+ wrapped_cols: list[list[str]] = []
271
+ max_lines = 1
272
+ for h, cw in zip(headers, col_widths):
273
+ val = str(row.get(h, "") or "")
274
+ w_lines = _wrap_cell_text(val, cw - 2 * cell_pad_x, font_size)
275
+ wrapped_cols.append(w_lines)
276
+ if len(w_lines) > max_lines:
277
+ max_lines = len(w_lines)
278
+
279
+ # Sehr lange Einzelzellen bei Bedarf sauber über Seiten verteilen
280
+ line_offset = 0
281
+ while line_offset < max_lines:
282
+ available_h = cur_y - min_y
283
+ max_fit = int((available_h - 2 * cell_pad_y) // line_height)
284
+ if max_fit < 1:
285
+ cur_ops, cur_y = _start_page()
286
+ available_h = cur_y - min_y
287
+ max_fit = max(1, int((available_h - 2 * cell_pad_y) // line_height))
288
+
289
+ chunk_lines = min(max_lines - line_offset, max_fit)
290
+ row_h = chunk_lines * line_height + 2 * cell_pad_y
291
+ row_bottom = cur_y - row_h
292
+
293
+ # Dezente Zebra-Schattierung
294
+ if row_idx % 2 == 1:
295
+ cur_ops.append(
296
+ f"0.97 0.98 0.99 rg {MARGIN_X:.2f} {row_bottom:.2f} {USABLE_W:.2f} {row_h:.2f} re f\n".encode("ascii")
297
+ )
298
+
299
+ # Rahmenlinie
300
+ cur_ops.append(
301
+ f"0.86 0.89 0.93 RG 0.4 w {MARGIN_X:.2f} {row_bottom:.2f} {USABLE_W:.2f} {row_h:.2f} re S\n".encode("ascii")
302
+ )
303
+
304
+ # Spalten-Trennlinien + Zellentext mit echten schwarzen Schwärzungsbalken
305
+ cx = MARGIN_X
306
+ for col_i, (col_lines, cw) in enumerate(zip(wrapped_cols, col_widths)):
307
+ if col_i > 0:
308
+ cur_ops.append(
309
+ f"0.88 0.90 0.94 RG 0.35 w {cx:.2f} {row_bottom:.2f} m {cx:.2f} {cur_y:.2f} l S\n".encode("ascii")
310
+ )
311
+ slice_lines = col_lines[line_offset:line_offset + chunk_lines]
312
+ for li, line_txt in enumerate(slice_lines):
313
+ if not line_txt:
314
+ continue
315
+ baseline_y = cur_y - cell_pad_y - font_size - (li * line_height)
316
+ _draw_line_with_redaction_bars(
317
+ cur_ops,
318
+ line_txt,
319
+ x_start=cx + cell_pad_x,
320
+ baseline_y=baseline_y,
321
+ font_size=font_size,
322
+ )
323
+ cx += cw
324
+
325
+ cur_y = row_bottom
326
+ line_offset += chunk_lines
327
+
328
+ # Seitenzahlen in Fußzeile auf jeder Seite ergänzen
329
+ total_pages = len(pages_ops)
330
+ for page_num, ops in enumerate(pages_ops, start=1):
331
+ footer_right = f"Seite {page_num} / {total_pages}"
332
+ right_w = _text_width(footer_right, 7.8)
333
+ ops.append(
334
+ b"0.45 0.51 0.60 rg BT /F1 7.8 Tf "
335
+ + f"{PAGE_W - MARGIN_X - right_w:.2f} {MARGIN_BOTTOM - 14:.2f} Td ".encode("ascii")
336
+ + _pdf_str(footer_right)
337
+ + b" Tj ET\n"
338
+ )
339
+
340
+ # PDF-1.4-Binärstruktur zusammensetzen
341
+ objects: list[bytes] = []
342
+ # 1: Catalog, 2: Pages, 3: Helvetica, 4: Helvetica-Bold, 5: Info
343
+ pdf_title = "Export"
344
+ page_obj_ids: list[int] = []
345
+ next_id = 6
346
+ page_pairs: list[tuple[int, int, bytes]] = []
347
+ for ops in pages_ops:
348
+ content_id = next_id
349
+ page_id = next_id + 1
350
+ next_id += 2
351
+ compressed = zlib.compress(b"".join(ops), level=6)
352
+ page_pairs.append((content_id, page_id, compressed))
353
+ page_obj_ids.append(page_id)
354
+
355
+ kids_str = " ".join(f"{pid} 0 R" for pid in page_obj_ids)
356
+ objects.append(b"<< /Type /Catalog /Pages 2 0 R >>")
357
+ objects.append(f"<< /Type /Pages /Kids [{kids_str}] /Count {len(page_obj_ids)} >>".encode("ascii"))
358
+ objects.append(b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>")
359
+ objects.append(b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>")
360
+ objects.append(b"<< /Title " + _pdf_str(pdf_title) + b" >>")
361
+
362
+ for content_id, page_id, compressed in page_pairs:
363
+ stream_obj = (
364
+ f"<< /Length {len(compressed)} /Filter /FlateDecode >>\nstream\n".encode("ascii")
365
+ + compressed
366
+ + b"\nendstream"
367
+ )
368
+ page_obj = (
369
+ f"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {PAGE_W:.2f} {PAGE_H:.2f}] "
370
+ f"/Resources << /Font << /F1 3 0 R /F2 4 0 R >> >> "
371
+ f"/Contents {content_id} 0 R >>"
372
+ ).encode("ascii")
373
+ objects.append(stream_obj)
374
+ objects.append(page_obj)
375
+
376
+ pdf = bytearray(b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n")
377
+ offsets: list[int] = [0]
378
+ for obj_num, body in enumerate(objects, start=1):
379
+ offsets.append(len(pdf))
380
+ pdf.extend(f"{obj_num} 0 obj\n".encode("ascii"))
381
+ pdf.extend(body)
382
+ pdf.extend(b"\nendobj\n")
383
+
384
+ xref_pos = len(pdf)
385
+ pdf.extend(f"xref\n0 {len(objects) + 1}\n".encode("ascii"))
386
+ pdf.extend(b"0000000000 65535 f \n")
387
+ for off in offsets[1:]:
388
+ pdf.extend(f"{off:010d} 00000 n \n".encode("ascii"))
389
+
390
+ pdf.extend(
391
+ f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R /Info 5 0 R >>\nstartxref\n{xref_pos}\n%%EOF\n".encode("ascii")
392
+ )
393
+ return bytes(pdf)