Repository navigation
Expand file tree
/
Copy pathNullifyPDF.py
More file actions
3522 lines (3235 loc) · 144 KB
/
Copy pathNullifyPDF.py
File metadata and controls
3522 lines (3235 loc) · 144 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import re
import signal
import datetime
import pathlib
import string
import platform
import logging
import logging.handlers
import traceback
import atexit
import hashlib
import html
import importlib.util
import json
import math
from typing import Optional, List, Set, Dict, Any, Tuple, TypedDict, NotRequired
import pymupdf as fitz
from PySide6.QtWidgets import (
QApplication,
QMainWindow,
QWidget,
QVBoxLayout,
QHBoxLayout,
QLabel,
QPushButton,
QCheckBox,
QProgressBar,
QProgressDialog,
QTextEdit,
QGraphicsView,
QGraphicsScene,
QFileDialog,
QDialog,
QDialogButtonBox,
QLineEdit,
QGraphicsRectItem,
QMessageBox,
QInputDialog,
QTextBrowser,
)
from PySide6.QtGui import (
QKeySequence,
QShortcut,
QIcon,
QPixmap,
QImage,
QPainter,
QColor,
QPen,
QDragEnterEvent,
QDropEvent,
)
from PySide6.QtCore import (
Qt,
QThread,
QObject,
Signal,
Slot,
QRectF,
QPointF,
QMutex,
QMutexLocker,
QStandardPaths,
QTimer,
QUrl,
)
from PySide6.QtGui import QDesktopServices
from privacy_core import (
PSEUDONYM_STYLES,
PlaceholderEntry,
export_pseudonym_key,
generate_recovery_key,
import_pseudonym_key,
parse_recovery_key,
PlaceholderRegistry,
PrivacyMode,
password_strength,
build_restore_payload,
decrypt_restore_payload,
encrypt_restore_payload,
parse_restore_entries,
sort_entries_longest_placeholder_first,
)
from pii_detection import (
ALL_GROUP_IDS,
ENTITY_GROUPS,
NON_PRESIDIO_TYPES,
build_detections,
build_page_index,
Candidate,
classify_page,
covered_fraction,
expand_group_ids,
load_enabled_groups,
save_enabled_groups,
whole_word_rects,
)
import licences_info
import spacy_models
import update_check
from export_engine import (
build_audit_record,
cleanup_stale_temp,
collect_removed_values,
export_document,
name_leaks_value,
neutral_map_name,
neutral_output_name,
private_temp_dir,
purge_old_logs,
wipe_local_data,
write_audit_record,
write_private_file,
)
from pii_detection import GLYPH_CORE_INSET, core_hits as _core_hits, glyph_core, target_chars
from pdf_sanitize import (
SanitizePolicy,
page_image_coverage,
reveal_hidden_layers,
suggest_signature_areas,
)
from review_dialog import ReviewDialog
from model_dialog import ModelDialog
from help_guide import GuideDialog, apply_tooltips
from dictionary_dialog import DictionaryDialog
from word_lists import PDFListManager
from word_import import docx_to_pdf
import secure_store
from model_manager import CATALOG, MODEL_CANDIDATES, ModelStore
from onnx_ner import OnnxTokenDetector
# PyMuPDF defines these constants dynamically, which mypy cannot see; read
# them once here (with the suppression) instead of at every call site.
PDF_ANNOT_REDACT: int = fitz.PDF_ANNOT_REDACT # type: ignore[attr-defined]
PDF_REDACT_IMAGE_PIXELS: int = fitz.PDF_REDACT_IMAGE_PIXELS # type: ignore[attr-defined]
__version__ = "2.4.0"
__version_prerelease__ = ""
APP_VERSION = (
f"{__version__}-{__version_prerelease__}"
if __version_prerelease__
else __version__
)
def about_version_text() -> str:
"""Version line of the About dialog; says "Beta" only for prereleases."""
suffix = " Beta" if __version_prerelease__ else ""
return f"v{APP_VERSION}{suffix}"
class UpdateCheckWorker(QThread):
"""Fetch the GitHub release list and pick the update (if any)."""
result_sig = Signal(object) # release dict, or None when up to date
error_sig = Signal(str)
def run(self) -> None:
try:
releases = update_check.fetch_releases()
self.result_sig.emit(update_check.find_update(releases, APP_VERSION))
except Exception as e: # network errors, bad JSON, rate limit...
logging.getLogger("nullifypdf").warning(f"Update check failed: {e}")
self.error_sig.emit(f"{type(e).__name__}: {e}")
class SpacyModelInstallWorker(QThread):
"""Download the optional Italian spaCy pipeline off the UI thread."""
progress_sig = Signal(int, int)
done_sig = Signal()
error_sig = Signal(str)
def __init__(self, root: pathlib.Path) -> None:
super().__init__()
self._root = root
def run(self) -> None:
try:
spacy_models.install_italian(
self._root, progress=lambda d, t: self.progress_sig.emit(d, t)
)
self.done_sig.emit()
except Exception as e:
self.error_sig.emit(str(e))
class UpdateDownloadWorker(QThread):
"""Download a release asset into the user's Downloads folder."""
progress_sig = Signal(int, int)
done_sig = Signal(str)
error_sig = Signal(str)
def __init__(self, url: str, dest: pathlib.Path, size: int, digest: str = "") -> None:
super().__init__()
self._digest = digest
self._url = url
self._dest = dest
self._size = size
self._cancel = False
def cancel(self) -> None:
self._cancel = True
def run(self) -> None:
try:
update_check.download_file(
self._url,
self._dest,
expected_size=self._size,
digest=self._digest,
progress=lambda d, t: self.progress_sig.emit(d, t),
cancelled=lambda: self._cancel,
)
self.done_sig.emit(str(self._dest))
except InterruptedError:
self.error_sig.emit("")
except Exception as e:
logging.getLogger("nullifypdf").warning(f"Update download failed: {e}")
self.error_sig.emit(f"{type(e).__name__}: {e}")
def downloads_folder() -> pathlib.Path:
"""The user's Downloads folder as configured in the running OS.
Qt resolves it per platform (Windows known folder, XDG user-dirs on
Linux, ~/Downloads on macOS); fall back to ~/Downloads. The folder is
not created here: the caller does it when it actually downloads.
"""
path = QStandardPaths.writableLocation(QStandardPaths.StandardLocation.DownloadLocation)
return pathlib.Path(path) if path else pathlib.Path.home() / "Downloads"
class DetectionDict(TypedDict):
text: str
entity_type: str
rects: List[Tuple[float, float, float, float]]
source: NotRequired[str]
score: NotRequired[float]
state: NotRequired[str]
reasons: NotRequired[List[str]]
glued: NotRequired[bool]
def setup_logging() -> logging.Logger:
"""Configure file-based logging.
Respects NULLIFYPDF_DEBUG environment variable for verbose output.
Returns:
logging.Logger: Configured logger instance for nullifypdf.
"""
log_dir = pathlib.Path.home() / ".nullifypdf" / "logs"
log_dir.mkdir(parents=True, exist_ok=True)
purge_old_logs(log_dir, max_age_days=30)
logger = logging.getLogger("nullifypdf")
debug_mode = os.environ.get("NULLIFYPDF_DEBUG", "").lower() == "true"
logger.setLevel(logging.DEBUG if debug_mode else logging.INFO)
if logger.handlers:
return logger
try:
# Rotating, so diagnostics are not kept indefinitely (storage
# limitation); old rotated files are also purged above.
handler = logging.handlers.RotatingFileHandler(
log_dir / "nullifypdf.log",
maxBytes=512 * 1024,
backupCount=3,
encoding="utf-8",
)
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter(
'%(asctime)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
handler.setFormatter(formatter)
logger.addHandler(handler)
except Exception as e:
print(f"Warning: Could not setup file logging: {e}")
return logger
def resource_path(relative_path: str) -> str:
"""Get absolute path for resource file (compatible with PyInstaller).
Args:
relative_path: Relative path to resource file.
Returns:
str: Absolute path to resource.
"""
try:
base_path = getattr(sys, "_MEIPASS")
except Exception:
base_path = os.path.dirname(os.path.abspath(__file__))
return os.path.join(base_path, relative_path)
def sha256_file(path: str) -> str:
"""Return the SHA-256 digest for a local file."""
digest = hashlib.sha256()
with open(path, "rb") as fh:
for chunk in iter(lambda: fh.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
class RestoreMapMismatch(ValueError):
"""Raised when a restore map's recorded hash doesn't match the PDF."""
REDACTION_FONTNAME = "helv"
# Labels (longest first) drawn on image / signature areas after redaction.
KIND_LABELS: Dict[str, List[str]] = {
"IMAGE": ["[IMMAGINE RIMOSSA]", "[IMMAGINE]", "[IMG]", "#"],
"SIGNATURE": ["[FIRMA RIMOSSA]", "[FIRMA]", "[F]", "#"],
}
REDACTION_MAX_FONTSIZE = 8.0
# PyMuPDF's apply_redactions() never inserts replacement text below 4 pt, so
# a smaller floor would only produce text that is silently dropped.
REDACTION_MIN_FONTSIZE = 4.0
# Text written with TextWriter has no such floor.
LABEL_MIN_FONTSIZE = 1.0
LABEL_PREFERRED_MIN_FONTSIZE = 4.0
def fit_redaction_fontsize(
text: str,
rect: "fitz.Rect",
max_size: float = REDACTION_MAX_FONTSIZE,
min_size: float = REDACTION_MIN_FONTSIZE,
) -> float:
"""Return the largest font size that lays `text` out inside `rect` intact.
`apply_redactions()` lays its replacement text out as a text *box*: when
the text is wider than the box it wraps, and MuPDF will happily break in
the middle of a token, turning ``DATA_001`` into ``DATA_`` + ``001``. The
result is still perfectly legible on screen but is no longer findable by
`page.search_for("DATA_001")`, which silently breaks reconstruction. If
the text cannot be wrapped into the box at all, MuPDF drops it entirely.
Picking a size that fits up front avoids both outcomes. Wrapping
*between words* is fine and stays legible, so the size only has to make
the longest unbreakable token fit the box width; the box must then be
tall enough for the resulting number of wrapped lines.
Args:
text: The replacement string to be stamped into the box.
rect: The redaction box.
max_size: Preferred (largest) font size.
min_size: Floor; returned even if the text still does not fit.
Returns:
float: Font size to pass to `add_redact_annot(..., fontsize=...)`.
"""
tokens = text.split() or [text]
usable_width = max(1.0, rect.width - 2.0)
size = max_size
while size > min_size:
line_height = size * 1.35
widest_token = max(
fitz.get_text_length(token, fontname=REDACTION_FONTNAME, fontsize=size)
for token in tokens
)
total_width = fitz.get_text_length(
text, fontname=REDACTION_FONTNAME, fontsize=size
)
lines_needed = max(1, math.ceil(total_width / usable_width))
if widest_token <= usable_width and lines_needed * line_height <= rect.height:
return size
size -= 0.25
return min_size
def _placeholder_rects_by_chars(page: Any, placeholder: str) -> List["fitz.Rect"]:
"""Locate a placeholder that `search_for()` cannot find, character by character.
Fallback for version 1 restore maps (which carry no coordinates) whose
placeholder was wrapped by `apply_redactions()`. Depending on the
PyMuPDF version, a wrap can land its pieces on separate *lines* of the
same text block, or in entirely separate *blocks* (observed with
PyMuPDF 1.28.2: a narrow box wraps "DATA_001" into a "DATA_" block and a
separate "001" block). Concatenating only within each block therefore
still misses it, so this walks every character on the page, in reading
order, ignoring block/line boundaries entirely.
"""
rects: List["fitz.Rect"] = []
try:
raw = page.get_text("rawdict")
except Exception:
return rects
chars: List[Any] = []
for block in raw.get("blocks", []):
for line in block.get("lines", []):
for span in line.get("spans", []):
chars.extend(span.get("chars", []))
if not chars:
return rects
text = "".join(ch.get("c", "") for ch in chars)
start = text.find(placeholder)
while start != -1:
matched = chars[start:start + len(placeholder)]
box = fitz.Rect(matched[0]["bbox"])
for ch in matched[1:]:
box |= fitz.Rect(ch["bbox"])
rects.append(box)
start = text.find(placeholder, start + len(placeholder))
return rects
def capture_text_style(page: Any, rect: "fitz.Rect") -> Optional[Dict[str, Any]]:
"""Read the typography of the native text under `rect`.
Returns ``{font, size, color, flags, origin, text}`` for the line the
box was taken from, where ``text`` is the text of that line inside the
box and ``origin`` the baseline start of its first character. Only
characters on a single baseline whose deletion core the box intersects
are used, so with tight leading the text of the lines above and below
(whose boxes overlap this one) is never captured. Returns None when the
box holds no real text: no span at all, or only an invisible OCR layer
(GlyphLessFont / render mode 3). That is what distinguishes a native PDF
from a scanned one.
"""
try:
blocks = page.get_text("rawdict", clip=rect).get("blocks", [])
except Exception:
return None
# (baseline y rounded, span, char)
hits: List[Tuple[float, Dict[str, Any], Dict[str, Any]]] = []
for block in blocks:
if block.get("type") != 0:
continue
for line in block.get("lines", []):
for span in line.get("spans", []):
if "glyphless" in str(span.get("font", "")).lower():
continue
if span.get("alpha", 255) == 0:
continue
for ch in span.get("chars", []):
if not str(ch.get("c", "")).strip():
continue
if not _core_hits(tuple(ch["bbox"]), rect):
continue
hits.append((round(float(ch["origin"][1]), 1), span, ch))
if not hits:
return None
centre = (rect.y0 + rect.y1) / 2
counts: Dict[float, int] = {}
for base, _sp, _ch in hits:
counts[base] = counts.get(base, 0) + 1
# The target line is the baseline nearest the middle of the box among
# those inside it; with tight leading a neighbour's baseline can also
# fall inside the box, but never closer to its middle.
inside = [k for k in counts if rect.y0 <= k <= rect.y1] or list(counts)
base = min(inside, key=lambda k: (abs(k - centre), -counts[k]))
chosen = [(sp, ch) for b_, sp, ch in hits if b_ == base]
chosen.sort(key=lambda t: t[1]["origin"][0])
spans_used: Dict[int, int] = {}
for sp, _ch in chosen:
spans_used[id(sp)] = spans_used.get(id(sp), 0) + 1
dominant = next(sp for sp, _ in chosen if spans_used[id(sp)] == max(spans_used.values()))
# Spaces between the selected characters are not in `hits` (they were
# filtered out above); rebuild them from the horizontal gaps.
pieces: List[str] = []
prev_x1: Optional[float] = None
for _sp, ch in chosen:
x0, _y0, x1, _y1 = ch["bbox"]
if prev_x1 is not None and x0 - prev_x1 > 0.25 * float(dominant["size"]):
pieces.append(" ")
pieces.append(str(ch["c"]))
prev_x1 = x1
first = chosen[0][1]
return {
"font": str(dominant.get("font", "")),
"size": float(dominant["size"]),
"color": int(dominant.get("color", 0)),
"flags": int(dominant.get("flags", 0)),
"origin": [float(first["origin"][0]), float(first["origin"][1])],
"text": "".join(pieces).strip(),
}
def band_covers_target(page: Any, band: "fitz.Rect", full: "fitz.Rect") -> bool:
"""True when `band` reaches the deletion core of every target character.
A glyph that is smaller or higher than the rest of its word (a
superscript, a trailing digit) could keep its core outside a thin band
and survive the redaction.
"""
chars = target_chars(page, full)
# An empty clipped result is not proof of coverage. A band trimmed
# against neighbouring lines can otherwise leave part of the glyph.
return bool(chars) and all(_core_hits(tuple(ch["bbox"]), band) for ch in chars)
def text_under_rect(page: Any, rect: "fitz.Rect") -> str:
"""The text a box was drawn over, without neighbouring lines' fragments.
`get_text(clip=...)` follows a different rule from glyph deletion and, with
tight leading, returns pieces of the lines above and below. Native text is
read from a single baseline (see capture_text_style); the plain clip text
is only the fallback for scanned / image pages.
"""
style = capture_text_style(page, rect)
if style and style.get("text"):
return " ".join(str(style["text"]).split())
return " ".join(page.get_text("text", clip=rect).split())
_BASE14 = {
# (family, bold, italic) -> Base-14 font code
("sans", False, False): "helv", ("sans", True, False): "hebo",
("sans", False, True): "heit", ("sans", True, True): "hebi",
("serif", False, False): "tiro", ("serif", True, False): "tibo",
("serif", False, True): "tiit", ("serif", True, True): "tibi",
("mono", False, False): "cour", ("mono", True, False): "cobo",
("mono", False, True): "coit", ("mono", True, True): "cobi",
}
_SERIF_HINTS = (
"times", "serif", "georgia", "cambria", "garamond", "book", "palatino", "minion",
)
def _strip_subset_prefix(name: str) -> str:
return re.sub(r"^[A-Z]{6}\+", "", name or "").lower()
def _same_face(basefont: str, wanted: str) -> bool:
"""Loose font-name match: ignores subset prefix, case and punctuation."""
def norm(name: str) -> str:
n = re.sub(r"[^a-z0-9]", "", _strip_subset_prefix(name))
return re.sub(r"(regular|mt|ps)$", "", n)
a, b = norm(basefont), norm(wanted)
return bool(a) and bool(b) and (a == b or a.startswith(b) or b.startswith(a))
def closest_base14(style: Dict[str, Any]) -> str:
"""Pick the Base-14 font code closest to the original face."""
name = _strip_subset_prefix(str(style.get("font", "")))
flags = int(style.get("flags", 0))
if "mono" in name or "courier" in name or "consolas" in name or flags & 8:
family = "mono"
elif "sans" not in name and (flags & 4 or any(k in name for k in _SERIF_HINTS)):
family = "serif"
else:
family = "sans"
bold = bool(flags & 16) or any(k in name for k in ("bold", "black", "heavy"))
italic = bool(flags & 2) or any(k in name for k in ("italic", "oblique"))
return _BASE14[(family, bold, italic)]
def resolve_font(
doc: Any, page: Any, style: Dict[str, Any], text: str
) -> Tuple["fitz.Font", str]:
"""Return ``(font, description)`` for restoring `text` in `style`.
Prefers the original embedded font when the file still carries it and it
has a glyph for every character; otherwise the closest Base-14 face.
"""
wanted = _strip_subset_prefix(str(style.get("font", "")))
if wanted:
try:
for entry in page.get_fonts(full=True):
xref, basefont = entry[0], str(entry[3])
if xref <= 0 or not _same_face(basefont, wanted):
continue
_name, ext, _type, buffer = doc.extract_font(xref)
if not buffer or ext in ("", "n/a"):
continue
font = fitz.Font(fontbuffer=buffer)
if all(font.has_glyph(ord(ch)) for ch in text if not ch.isspace()):
return font, f"embedded:{basefont}"
except Exception:
pass
code = closest_base14(style)
return fitz.Font(code), f"base14:{code}"
def write_styled_text(
doc: Any, page: Any, rect: "fitz.Rect", text: str, style: Dict[str, Any]
) -> None:
"""Write `text` with the original size, colour, baseline and closest font."""
font, used = resolve_font(doc, page, style, text)
logging.getLogger("nullifypdf").debug(
"Reconstruction font: original=%s used=%s", style.get("font"), used
)
size = float(style["size"])
color = fitz.sRGB_to_pdf(int(style.get("color", 0)))
origin = fitz.Point(style["origin"][0], style["origin"][1])
width = font.text_length(text, fontsize=size)
usable = max(1.0, rect.width + 1.0)
writer = fitz.TextWriter(page.rect)
if width <= usable:
writer.append(origin, text, font=font, fontsize=size)
else:
# Wider in the fallback font (or a multi-line original): shrink a
# little, and wrap inside the box if it still does not fit.
scaled = max(LABEL_MIN_FONTSIZE, size * usable / width)
if font.text_length(text, fontsize=scaled) <= usable:
writer.append(origin, text, font=font, fontsize=scaled)
else:
writer.fill_textbox(rect, text, font=font, fontsize=scaled, align=0)
writer.write_text(page, color=color)
def compact_labels(placeholder: str) -> List[str]:
"""Shorter stand-ins for a placeholder, longest first (full one first)."""
head, _, tail = placeholder.rpartition("_")
if not head or not tail:
return [placeholder]
out = [placeholder, f"{head[:1]}{tail}", tail, f"#{tail[:2]}"]
seen: List[str] = []
for item in out:
if item not in seen:
seen.append(item)
return seen
def write_label(
page: Any,
rect: "fitz.Rect",
labels: List[str],
*,
style: Optional[Dict[str, Any]] = None,
allowance: float = 0.0,
max_size: float = REDACTION_MAX_FONTSIZE,
) -> str:
"""Draw the first of `labels` that is legible inside the box; return it.
Drawn with TextWriter after apply_redactions(), so there is no 4 pt
floor and no silent drop. A label may extend past the box to the right by
`allowance` points (free space on the same line). Preference: the longest
label that fits at 4 pt or more; otherwise the shortest at whatever size
fits (down to 1 pt).
"""
font = fitz.Font(REDACTION_FONTNAME)
# A band squeezed between tight lines is short: keep the label inside it.
max_size = min(max_size, max(LABEL_MIN_FONTSIZE, rect.height * 0.9))
usable = max(1.0, rect.width - 1.0 + allowance)
chosen = labels[-1]
size = LABEL_MIN_FONTSIZE
for lab in labels:
full = font.text_length(lab, fontsize=1.0)
fit = min(max_size, usable / full) if full > 0 else max_size
if fit >= LABEL_PREFERRED_MIN_FONTSIZE:
chosen, size = lab, fit
break
else:
full = font.text_length(chosen, fontsize=1.0)
size = max(LABEL_MIN_FONTSIZE, min(max_size, usable / full if full else max_size))
if style and style.get("origin"):
base_y = float(style["origin"][1])
else:
base_y = rect.y0 + (rect.height + size * 0.7) / 2
writer = fitz.TextWriter(page.rect)
writer.append(fitz.Point(rect.x0 + 0.5, base_y), chosen, font=font, fontsize=size)
writer.write_text(page, color=(0, 0, 0))
return chosen
def free_space_right(page: Any, rect: "fitz.Rect", limit: float = 40.0) -> float:
"""Free width to the right of `rect` on the same line (after redaction)."""
gap = limit
for w in page.get_text("words"):
overlap = min(rect.y1, w[3]) - max(rect.y0, w[1])
if overlap < 0.5 * min(rect.height, w[3] - w[1]):
continue
if w[0] >= rect.x1 - 0.5:
gap = min(gap, w[0] - rect.x1 - 1.0)
return max(0.0, gap)
def _restore_targets(
page: Any, entry: PlaceholderEntry
) -> List[Tuple["fitz.Rect", Optional[Dict[str, Any]]]]:
"""Return the ``(box, style)`` pairs on `page` that should get `entry.original` back.
Prefers the coordinates recorded in the restore map (version 2+), which
are the boxes the original value was taken from, so the value fits back
into them. Falls back to text search only for version 1 maps.
"""
stored = [
(fitz.Rect(occurrence.rect), occurrence.style)
for occurrence in entry.occurrences
if occurrence.page == page.number
]
if stored:
return stored
hits = list(page.search_for(entry.placeholder))
if not hits:
hits = _placeholder_rects_by_chars(page, entry.placeholder)
return [(hit, None) for hit in hits]
def reconstruct_pdf(in_path: str, out_path: str, payload: Dict[str, Any]) -> int:
"""Rebuild a pseudonymized PDF's original values from a decrypted restore map.
Replaces every placeholder occurrence (e.g. ``PERSON_001``) with the
original value, using the same add_redact_annot()-then-apply_redactions()
mechanism used to create the placeholders during export. Does not restore
the original layout: a placeholder's redaction box is sized for the
placeholder text, so a longer original value may be visually clipped or
crowd the box.
Uses the redaction boxes recorded in the restore map (version 2+) and
only falls back to searching for the placeholder text with version 1
maps, which carry no coordinates.
Args:
in_path: Path to the pseudonymized PDF to reconstruct from.
out_path: Path to write the reconstructed PDF to.
payload: Decrypted restore-map payload (see `privacy_core.build_restore_payload`).
Returns:
int: Number of placeholder occurrences whose original value was
**verified present** in the saved output. The count is taken
from the written file, not from the number of redactions
requested, so a value that `apply_redactions()` silently
dropped is never reported as restored.
Raises:
ValueError: If the payload is not a recognized restore map.
RestoreMapMismatch: If `output_sha256` in the payload does not match
the SHA-256 of `in_path`.
"""
expected_sha256 = payload.get("output_sha256")
if expected_sha256 and sha256_file(in_path) != expected_sha256:
raise RestoreMapMismatch(
"La mappa di ripristino non corrisponde a questo PDF "
"(hash SHA-256 diverso)."
)
entries = sort_entries_longest_placeholder_first(parse_restore_entries(payload))
# (page index, box, original value) for every restoration we attempted,
# so the saved output can be checked against it below.
attempted: List[Tuple[int, fitz.Rect, str]] = []
doc = fitz.open(in_path)
try:
for page in doc.pages():
claimed: List[fitz.Rect] = []
styled: List[Tuple[fitz.Rect, str, Dict[str, Any]]] = []
plain: List[Tuple[fitz.Rect, str]] = []
for entry in entries:
for rect, style in _restore_targets(page, entry):
# Entries are sorted longest-placeholder-first, so a
# shorter placeholder must not re-redact a box a longer
# one already claimed: searching for PERSON_001 also hits
# the first ten characters of a rendered PERSON_0010, and
# that hit sits *inside* the longer one's box.
# Containment, not intersection: two separate fields the
# user boxed side by side may legitimately touch, and
# skipping the second would drop a value.
if any(taken.contains(rect) for taken in claimed):
continue
claimed.append(fitz.Rect(rect))
if style:
# Native text: blank the box now, write the value in
# its original typography after apply_redactions()
# (which would otherwise erase it).
text = entry.original # never the captured clip text
page.add_redact_annot(rect, fill=(1, 1, 1))
styled.append((fitz.Rect(rect), text, style))
attempted.append((page.number, fitz.Rect(rect), text))
continue
page.add_redact_annot(rect, fill=(1, 1, 1))
plain.append((fitz.Rect(rect), entry.original))
attempted.append((page.number, fitz.Rect(rect), entry.original))
page.apply_redactions(images=PDF_REDACT_IMAGE_PIXELS, graphics=True)
for rect, text, style in styled:
write_styled_text(doc, page, rect, text, style)
for rect, text in plain:
write_label(page, rect, [text])
doc.save(out_path, garbage=4, deflate=True, clean=True)
finally:
doc.close()
return _verify_restored(out_path, attempted)
def expected_restore_count(payload: Dict[str, Any]) -> int:
"""Return how many placeholder occurrences a restore map should put back.
Counts occurrences, not entries: one entry can carry several boxes (the
same value redacted on more than one page), and `reconstruct_pdf`
returns restored *occurrences*. Comparing its result against the entry
count would hide a partial restore -- which is exactly the repeated-value
case reconstruction has already gone wrong on once.
"""
return sum(
max(1, len(entry.occurrences)) for entry in parse_restore_entries(payload)
)
def _verify_restored(
out_path: str, attempted: List[Tuple[int, "fitz.Rect", str]]
) -> int:
"""Count how many attempted restorations actually landed in the output.
`apply_redactions()` drops its replacement text silently when the text
cannot be laid out inside the box, so counting the redactions we asked
for would over-report: the feature would claim to have restored values
it had in fact destroyed. Read the answer back off the written file.
"""
logger = logging.getLogger("nullifypdf")
restored = 0
doc = fitz.open(out_path)
try:
for page_number, rect, original in attempted:
probe = fitz.Rect(rect) + (-2, -2, 2, 2)
# Whitespace-insensitive: a long value legitimately wraps onto
# several lines inside its box. What matters is that its
# characters are back on the page, not how they are broken up.
found = "".join(doc[page_number].get_text("text", clip=probe).split())
if "".join(original.split()) in found:
restored += 1
else:
logger.warning(
"Reconstruction: value not restored on page %s at %s "
"(it did not fit its redaction box).",
page_number + 1,
tuple(round(v, 1) for v in (rect.x0, rect.y0, rect.x1, rect.y1)),
)
finally:
doc.close()
return restored
def find_tessdata_dir() -> Optional[str]:
"""Find a local Tesseract tessdata directory for PyMuPDF OCR."""
candidates = []
env_value = os.environ.get("TESSDATA_PREFIX")
if env_value:
candidates.append(env_value)
try:
candidates.append(fitz.get_tessdata())
except Exception:
pass
candidates.append(resource_path(os.path.join("ocr", "tessdata")))
candidates.extend(
[
r"C:\Program Files\Tesseract-OCR\tessdata",
r"C:\Program Files (x86)\Tesseract-OCR\tessdata",
"/usr/share/tesseract-ocr/4.00/tessdata",
"/usr/share/tesseract-ocr/5/tessdata",
"/usr/share/tessdata",
]
)
for candidate in candidates:
if not candidate:
continue
path = pathlib.Path(candidate)
if path.is_dir() and any(path.glob("*.traineddata")):
return str(path)
return None
def ocr_language_for_choice(choice: str, tessdata_dir: Optional[str]) -> str:
"""Tesseract languages for the scan: Italian, plus English data if installed.
The program analyses Italian documents only; the English OCR data is kept
just so that English words and Latin-script terms inside them are read
well. `choice` is kept for API stability and must be "IT".
"""
if not tessdata_dir:
return "ita"
available = [
lang for lang in ("ita", "eng")
if (pathlib.Path(tessdata_dir) / f"{lang}.traineddata").exists()
]
return "+".join(available or ["ita"])
STYLESHEET = """
QMainWindow, QDialog { background-color: #0f172a; }
QWidget { color: #cbd5e1; font-family: 'Segoe UI', 'Roboto', sans-serif; font-size: 13px; }
QFrame#Sidebar, QFrame#Panel { background-color: #1e293b; border-radius: 6px; }
QPushButton { background-color: #334155; border: 1px solid #475569; border-radius: 4px; padding: 8px; color: #e2e8f0; font-weight: bold; }
QPushButton:hover { background-color: #475569; border-color: #0ea5e9; }
QPushButton#Primary { background-color: #0284c7; color: white; border: none; }
QPushButton#Primary:hover { background-color: #0369a1; }
QPushButton#Danger { background-color: #dc2626; color: white; border: none; }
QPushButton#Danger:hover { background-color: #b91c1c; }
QPushButton#Exit { background-color: transparent; border: none; color: #64748b; font-weight: normal; }
QPushButton#Exit:hover { color: #ef4444; background-color: #1e293b; }
QTextEdit { background-color: #0f172a; border: 1px solid #334155; border-radius: 4px; padding: 4px; color: #94a3b8; font-family: 'Consolas', monospace; }
QLineEdit { background-color: #0f172a; border: 1px solid #334155; border-radius: 4px; padding: 4px; color: #e2e8f0; }
QLineEdit:focus { border: 1px solid #0ea5e9; }
QProgressBar { background-color: #0f172a; border: 1px solid #334155; border-radius: 4px; text-align: center; color: transparent; height: 8px;}
QProgressBar::chunk { background-color: #0ea5e9; border-radius: 3px; }
QGraphicsView { border: none; background-color: #020617; }
QListWidget, QTableWidget, QTextBrowser { background-color: #0f172a; border: 1px solid #334155; border-radius: 4px; color: #cbd5e1; gridline-color: #334155; selection-background-color: #0284c7; selection-color: white; }
QListWidget::item { padding: 6px; }
QHeaderView::section { background-color: #1e293b; color: #e2e8f0; border: 1px solid #334155; padding: 4px; }
QComboBox, QDoubleSpinBox { background-color: #0f172a; border: 1px solid #334155; border-radius: 4px; padding: 4px; color: #e2e8f0; }
QComboBox QAbstractItemView { background-color: #0f172a; color: #e2e8f0; selection-background-color: #0284c7; }
QTabWidget::pane { border: 1px solid #334155; }
QTabBar::tab { background-color: #1e293b; color: #cbd5e1; padding: 6px 14px; border: 1px solid #334155; }
QTabBar::tab:selected { background-color: #0284c7; color: white; }
QToolTip { background-color: #1e293b; color: #e2e8f0; border: 1px solid #0ea5e9; padding: 4px; }
QRadioButton::indicator, QCheckBox::indicator { width: 16px; height: 16px; border: 1px solid #475569; border-radius: 8px; background-color: #0f172a; }
QCheckBox::indicator { border-radius: 4px; }
QRadioButton::indicator:checked, QCheckBox::indicator:checked { background-color: #0ea5e9; border: 1px solid #0ea5e9; }
"""
class AIWorker(QObject):
"""AI analysis worker thread for PDF sensitive data detection.
Uses Microsoft Presidio + spaCy for NER (Named Entity Recognition).
Runs in separate thread to prevent UI blocking.
Signals:
log_sig: Emits log message (str).
progress_sig: Emits (current_page, total_pages) progress.
page_done_sig: Emits (page_index, detections) when page scan completes.
finished_sig: Emitted when all pages processed.
"""
log_sig = Signal(str)
progress_sig = Signal(int, int)
page_done_sig = Signal(int, object)
finished_sig = Signal()
def __init__(self) -> None:
"""Initialize AI worker with empty analyzer."""
super().__init__()
self.analyzer: Optional[Any] = None
self.loaded_langs: List[str] = []
# Set by the window before a scan: package name or folder of the
# Italian pipeline (it is downloaded on demand, see spacy_models).
self.italian_model: str = spacy_models.ITALIAN_PACKAGE
self._loaded_italian = ""
self.model_detectors: List[Tuple[str, OnnxTokenDetector]] = []
self._stop_requested = False
def cleanup(self) -> None:
"""Release AI resources (Presidio, spaCy models).
Must be called before thread termination to avoid hanging processes.
"""
self._stop_requested = True
try:
if self.analyzer:
# Clear analyzer reference; let GC reclaim spaCy/Presidio resources.
# NOTE: Mutating nlp.vocab.vectors.shape is not supported in modern
# spaCy (read-only property), so we simply drop the reference.
self.analyzer = None
self.loaded_langs.clear()
self.model_detectors.clear()
except Exception as e:
logging.getLogger("nullifypdf").debug(f"Error during AI cleanup: {e}")
@Slot(object, object, str, list, set, bool, object, list, bool)
def run_scan(self, doc: Any, doc_mutex: Any, choice: str,
compiled_allowlist: List[Tuple[str, Any]],
allowlist_set: Set[str], use_ocr: bool,
tessdata_dir: Optional[str],
enabled_types: List[str],
health_mode: bool = False) -> None:
"""Run AI scan on PDF pages and emit detected sensitive entities.
Text extraction (`page.get_text()`) is performed inside this worker so
it does not block the UI thread on large documents. Access to the
shared PyMuPDF document is serialized through `doc_mutex` because the
UI thread also reads from it (render) and writes to it (apply
redactions) concurrently.
Args:
doc: PyMuPDF document (shared with UI thread, mutex-protected).
doc_mutex: QMutex serializing access to `doc`.
choice: Language of the document; only 'IT' is supported.
compiled_allowlist: Pre-compiled regex patterns to skip redaction.
allowlist_set: Set of allowlist entries (lowercase) for O(1)
exact-match fast-path lookup before regex any() scan.
enabled_types: Presidio entity types the user chose to detect.
health_mode: Health-document profile: no uncertain hit is dropped
silently, it becomes a suggestion for review instead.
"""
try:
if self._stop_requested:
self.finished_sig.emit()
return
if doc is None:
self.log_sig.emit("ERRORE: doc non valido")
self.finished_sig.emit()
return
if choice != "IT":
self.log_sig.emit(f"ERRORE: Scelta lingua non valida: {choice}")
self.finished_sig.emit()
return