-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNullifyPDF.py
More file actions
1205 lines (1077 loc) · 45.6 KB
/
Copy pathNullifyPDF.py
File metadata and controls
1205 lines (1077 loc) · 45.6 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 traceback
import atexit
from typing import Optional, List, Set, Dict, Any, Tuple
import fitz
from PySide6.QtWidgets import (
QApplication,
QMainWindow,
QWidget,
QVBoxLayout,
QHBoxLayout,
QLabel,
QPushButton,
QRadioButton,
QCheckBox,
QProgressBar,
QTextEdit,
QGraphicsView,
QGraphicsScene,
QFileDialog,
QDialog,
QLineEdit,
QButtonGroup,
QGraphicsRectItem,
QMessageBox,
)
from PySide6.QtGui import (
QIcon,
QPixmap,
QImage,
QPainter,
QColor,
QPen,
QDragEnterEvent,
QDropEvent,
)
from PySide6.QtCore import Qt, QThread, QObject, Signal, Slot, QRectF, QPointF, QMutex, QMutexLocker
__version__ = "2.0.5"
def setup_logging() -> logging.Logger:
"""Configure file-based logging with rotation.
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)
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:
handler = logging.FileHandler(
log_dir / "nullifypdf.log",
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 = sys._MEIPASS
except Exception:
base_path = os.path.dirname(os.path.abspath(__file__))
return os.path.join(base_path, relative_path)
class PDFListManager:
"""Manages blocklist/allowlist persistence to disk.
Handles loading and saving word lists with automatic path management
and UTF-8 encoding.
"""
def __init__(self, config_dir: pathlib.Path) -> None:
"""Initialize list manager with config directory.
Args:
config_dir: Path to configuration directory.
"""
self.config_dir = config_dir
self.config_dir.mkdir(parents=True, exist_ok=True)
self.block_file = config_dir / "blocklist.txt"
self.allow_file = config_dir / "allowlist.txt"
def load_blocklist(self) -> Set[str]:
"""Load blocklist from disk.
Returns:
Set[str]: Words to redact (lowercase).
"""
return self._load_list(self.block_file)
def load_allowlist(self) -> Set[str]:
"""Load allowlist from disk.
Returns:
Set[str]: Words to preserve from redaction (lowercase).
"""
return self._load_list(self.allow_file)
def save_blocklist(self, blocklist: Set[str]) -> None:
"""Persist blocklist to disk.
Args:
blocklist: Set of words to save.
"""
self._save_list(self.block_file, blocklist)
def save_allowlist(self, allowlist: Set[str]) -> None:
"""Persist allowlist to disk.
Args:
allowlist: Set of words to save.
"""
self._save_list(self.allow_file, allowlist)
def _load_list(self, path: pathlib.Path) -> Set[str]:
"""Load word list from file with validation.
Args:
path: Path to list file.
Returns:
Set[str]: Set of words (lowercase, stripped, min length 3).
"""
if not path.exists():
return set()
try:
# Use context manager to ensure file handle is closed deterministically
with open(path, "r", encoding="utf-8") as fh:
return {
line.strip().lower()
for line in fh
if len(line.strip()) > 2
}
except Exception as e:
logging.getLogger(__name__).error(f"Error loading {path}: {e}")
return set()
def _save_list(self, path: pathlib.Path, words: Set[str]) -> None:
"""Save word list to file.
Args:
path: Path to save list.
words: Set of words to save.
"""
try:
with open(path, "w", encoding="utf-8") as f:
f.write("\n".join(sorted(words)))
except Exception as e:
logging.getLogger(__name__).error(f"Error saving {path}: {e}")
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; }
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, found_words) 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, set)
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] = []
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()
except Exception as e:
logging.getLogger("nullifypdf").debug(f"Error during AI cleanup: {e}")
@Slot(object, object, str, list, set)
def run_scan(self, doc: Any, doc_mutex: Any, choice: str,
compiled_allowlist: List[Tuple[str, Any]],
allowlist_set: Set[str]) -> 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 choice: 'EN', 'IT', or 'BOTH'.
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.
"""
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 not in ("EN", "IT", "BOTH"):
self.log_sig.emit(f"ERRORE: Scelta lingua non valida: {choice}")
self.finished_sig.emit()
return
if not isinstance(compiled_allowlist, list):
self.log_sig.emit("ERRORE: compiled_allowlist non valido")
self.finished_sig.emit()
return
if not isinstance(allowlist_set, set):
allowlist_set = set()
target_langs = ["en", "it"] if choice == "BOTH" else [choice.lower()]
if not self.analyzer or sorted(self.loaded_langs) != sorted(target_langs):
self.log_sig.emit(f"Inizializzazione AI ({choice})...")
from presidio_analyzer import AnalyzerEngine
from presidio_analyzer.nlp_engine import NlpEngineProvider
models = (
[{"lang_code": "en", "model_name": "en_core_web_md"}]
if "en" in target_langs
else []
)
if "it" in target_langs:
models.append({"lang_code": "it", "model_name": "it_core_news_md"})
provider = NlpEngineProvider(
nlp_configuration={"nlp_engine_name": "spacy", "models": models}
)
self.analyzer = AnalyzerEngine(
nlp_engine=provider.create_engine(),
supported_languages=target_langs,
)
self.loaded_langs = target_langs
self.log_sig.emit("Scansione forense in corso...")
targets = [
"PERSON",
"LOCATION",
"EMAIL_ADDRESS",
"PHONE_NUMBER",
"IBAN_CODE",
"CREDIT_CARD",
"CRYPTO",
]
# Determine page count under mutex (cheap, but doc may be replaced
# mid-flight by load_path if not for the disabled UI during scan).
with QMutexLocker(doc_mutex):
total_pages = len(doc)
for i in range(total_pages):
if self._stop_requested:
break
# Extract text in worker thread (off the UI thread) under mutex
# because UI thread renders / mutates annotations on the same doc.
with QMutexLocker(doc_mutex):
try:
text = doc[i].get_text()
except Exception as e:
self.log_sig.emit(f"Avviso: get_text fallito pagina {i+1}: {e}")
text = ""
found = set()
for lang in self.loaded_langs:
res = self.analyzer.analyze(
text=text, entities=targets, language=lang
)
for r in res:
w = text[r.start : r.end].strip()
if len(w) > 2:
found.add(w)
final_words = set()
for m in found:
clean = " ".join(m.strip(string.punctuation).lower().split())
if not clean:
continue
# Fast path: exact set membership is O(1). The vast majority
# of user allowlist entries are full tokens matched verbatim
# against `clean`, so this short-circuits before the O(N)
# regex any() scan over the whole allowlist.
if clean in allowlist_set:
continue
# Cache the word-boundary regex for `clean` so we don't
# rebuild and recompile it once per allowlist entry.
clean_pattern = re.compile(r"\b" + re.escape(clean) + r"\b")
if not any(
f_reg.search(clean) or clean_pattern.search(a_str)
for a_str, f_reg in compiled_allowlist
):
final_words.add(m)
self.page_done_sig.emit(i, final_words)
self.progress_sig.emit(i + 1, total_pages)
if not self._stop_requested:
self.log_sig.emit("Anonimizzazione completata.")
except Exception as e:
# Log full traceback to file for diagnostics; show only summary in UI
logging.getLogger("nullifypdf").error(
f"AI scan error: {traceback.format_exc()}"
)
self.log_sig.emit(f"ERRORE AI: {type(e).__name__}: {str(e)}")
finally:
self.finished_sig.emit()
class PDFView(QGraphicsView):
"""Custom graphics view for interactive PDF page display.
Handles mouse events for rectangle drawing (redaction) and zoom control.
Signals:
rect_drawn: Emits QRectF when user finishes drawing selection rectangle.
point_clicked: Emits QPointF when user clicks on page.
zoom_req: Emits int (+1 for zoom in, -1 for zoom out).
"""
rect_drawn = Signal(QRectF)
point_clicked = Signal(QPointF)
zoom_req = Signal(int)
def __init__(self, scene: QGraphicsScene, parent: Optional[Any] = None) -> None:
"""Initialize PDF view with scene.
Args:
scene: Graphics scene to display.
parent: Parent widget.
"""
super().__init__(scene, parent)
self.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform)
self.start_pos: Optional[QPointF] = None
self.temp_rect: Optional[QGraphicsRectItem] = None
def mousePressEvent(self, event: Any) -> None:
"""Handle mouse press: start selection rectangle on left-click."""
if event.button() == Qt.LeftButton:
sp = self.mapToScene(event.position())
self.start_pos = sp
self.point_clicked.emit(sp)
self.temp_rect = QGraphicsRectItem(QRectF(sp, sp))
self.temp_rect.setPen(QPen(QColor("#ef4444"), 2))
self.scene().addItem(self.temp_rect)
super().mousePressEvent(event)
def mouseMoveEvent(self, event: Any) -> None:
"""Update in-progress selection rectangle while dragging."""
if self.start_pos and self.temp_rect:
ep = self.mapToScene(event.position())
self.temp_rect.setRect(QRectF(self.start_pos, ep).normalized())
super().mouseMoveEvent(event)
def mouseReleaseEvent(self, event: Any) -> None:
"""Finalize selection rectangle and emit rect_drawn if large enough."""
if event.button() == Qt.LeftButton and self.temp_rect:
rect = self.temp_rect.rect()
self.scene().removeItem(self.temp_rect)
self.temp_rect = None
self.start_pos = None
if rect.width() > 5 and rect.height() > 5:
self.rect_drawn.emit(rect)
super().mouseReleaseEvent(event)
def wheelEvent(self, event: Any) -> None:
if event.modifiers() == Qt.ControlModifier:
self.zoom_req.emit(1 if event.angleDelta().y() > 0 else -1)
event.accept()
else:
super().wheelEvent(event)
class NullifyPDF(QMainWindow):
"""Main application window for PDF redaction using AI.
Handles PDF loading, manual/AI-assisted redaction, blocklist/allowlist
management, and secure export with forensic scrubbing.
Attributes:
doc: Currently loaded PDF document (None if not loaded).
page_num: Current page index (0-based).
scale: Current zoom scale factor (0.5 - 4.0).
blocklist: Set of strings to redact automatically.
allowlist: Set of strings to preserve from redaction.
config_dir: Path to user config directory (~/.nullifypdf).
"""
start_scan_sig = Signal(object, object, str, list, set)
def __init__(self) -> None:
"""Initialize main application window and setup UI."""
super().__init__()
self.logger = setup_logging()
self.logger.info("Application started")
self.setWindowTitle("NullifyPDF - AI Forensic Edition")
self.resize(1350, 950)
self.setStyleSheet(STYLESHEET)
self.setAcceptDrops(True)
ip = resource_path(os.path.join("images", "NullifyPDF_icon.png"))
if os.path.exists(ip):
self.setWindowIcon(QIcon(ip))
self.doc = None
self.page_num = 0
self.scale = 1.5
# Mutex guards `self.doc` against concurrent access from the AI worker
# thread (text extraction) and the UI thread (render, apply redactions).
self.doc_mutex = QMutex()
self.config_dir = pathlib.Path.home() / ".nullifypdf"
self.list_manager = PDFListManager(self.config_dir)
self.blocklist = self.list_manager.load_blocklist()
self.allowlist = self.list_manager.load_allowlist()
self.ai_thread = QThread()
self.ai_worker = AIWorker()
self.ai_worker.moveToThread(self.ai_thread)
self.ai_worker.log_sig.connect(self.write_log)
self.ai_worker.progress_sig.connect(self.update_progress)
self.ai_worker.page_done_sig.connect(self.apply_ai_to_page)
self.ai_worker.finished_sig.connect(self.ai_finished)
self.start_scan_sig.connect(self.ai_worker.run_scan)
self.ai_thread.start()
self.build_ui()
# Setup signal handlers for graceful shutdown
self._setup_signal_handlers()
# Register cleanup on exit
atexit.register(self._cleanup_on_exit)
if len(sys.argv) > 1:
self.load_path(sys.argv[1])
def _setup_signal_handlers(self) -> None:
"""Setup SIGINT/SIGTERM handlers for graceful shutdown.
Allows Ctrl+C to properly cleanup resources before exit.
"""
from PySide6.QtCore import QTimer
def signal_handler(signum: int, frame: Any) -> None:
self.logger.info(f"Signal {signum} received, initiating graceful shutdown")
# Defer close() onto the Qt event loop. Python signal handlers run
# at arbitrary points in main-thread bytecode; calling Qt APIs
# directly from one can crash or leave Qt in an inconsistent state.
QTimer.singleShot(0, self.close)
# Windows doesn't support SIGTERM for user processes, but SIGINT works
signal.signal(signal.SIGINT, signal_handler)
if hasattr(signal, 'SIGTERM'):
signal.signal(signal.SIGTERM, signal_handler)
def _cleanup_resources(self) -> None:
"""Cleanup all resources before application termination.
Releases:
- PDF document (PyMuPDF)
- AI worker thread and models
- All connections
"""
self.logger.info("Starting resource cleanup")
try:
# Stop AI worker from processing
if hasattr(self, 'ai_worker'):
self.ai_worker.cleanup()
# Quit and wait for thread
if hasattr(self, 'ai_thread') and self.ai_thread.isRunning():
self.ai_thread.quit()
# Wait up to 5 seconds for thread to finish
if not self.ai_thread.wait(5000):
self.logger.warning("AI thread did not terminate within timeout, forcing termination")
self.ai_thread.terminate()
self.ai_thread.wait()
# Close PDF document
if self.doc:
try:
self.doc.close()
self.logger.debug("PDF document closed")
except Exception as e:
self.logger.debug(f"Error closing PDF: {e}")
self.doc = None
# Note: Signal disconnection is optional - Python's garbage collector
# will clean up signal/slot connections when objects are destroyed.
# Explicit disconnect() is not necessary and can cause RuntimeWarning
# if the worker thread has already been cleaned up.
self.logger.info("Resource cleanup completed")
except Exception as e:
self.logger.error(f"Error during cleanup: {e}")
def _cleanup_on_exit(self) -> None:
"""Final cleanup hook called on application exit via atexit.
This ensures cleanup happens even if closeEvent is not called.
"""
self._cleanup_resources()
def closeEvent(self, event: Any) -> None:
"""Handle window close event with proper resource cleanup.
Args:
event: Qt QCloseEvent passed by the framework.
"""
self._cleanup_resources()
super().closeEvent(event)
def build_ui(self) -> None:
"""Build main application UI layout."""
c_widget = QWidget()
self.setCentralWidget(c_widget)
main_lay = QHBoxLayout(c_widget)
main_lay.setContentsMargins(10, 10, 10, 10)
sidebar = QWidget()
sidebar.setObjectName("Sidebar")
sidebar.setFixedWidth(280)
s_lay = QVBoxLayout(sidebar)
lbl_title = QLabel("NullifyPDF")
lbl_title.setStyleSheet("font-size: 24px; font-weight: bold; color: #0ea5e9;")
s_lay.addWidget(lbl_title)
s_lay.addWidget(QLabel("AI Forensic Edition\n"))
btn_open = QPushButton("Apri PDF")
btn_open.setObjectName("Primary")
btn_open.clicked.connect(self.cmd_open)
s_lay.addWidget(btn_open)
s_lay.addSpacing(20)
s_lay.addWidget(QLabel("Modello Lingua AI:"))
lang_lay = QHBoxLayout()
self.rb_en = QRadioButton("EN")
self.rb_it = QRadioButton("IT")
self.rb_both = QRadioButton("BOTH")
self.rb_en.setChecked(True)
self.lang_grp = QButtonGroup(self)
for rb in (self.rb_en, self.rb_it, self.rb_both):
self.lang_grp.addButton(rb)
lang_lay.addWidget(rb)
s_lay.addLayout(lang_lay)
s_lay.addSpacing(10)
self.chk_img = QCheckBox("Oscura Immagini")
s_lay.addWidget(self.chk_img)
s_lay.addSpacing(20)
btn_dict = QPushButton("Dizionari")
btn_dict.clicked.connect(self.cmd_dict)
s_lay.addWidget(btn_dict)
self.btn_ai = QPushButton("Auto Redact (AI)")
self.btn_ai.setObjectName("Danger")
self.btn_ai.clicked.connect(self.cmd_auto_ai)
s_lay.addWidget(self.btn_ai)
btn_clear = QPushButton("Pulisci Pagina")
btn_clear.clicked.connect(self.cmd_clear)
s_lay.addWidget(btn_clear)
s_lay.addSpacing(20)
btn_export = QPushButton("Esporta PDF Sicuro")
btn_export.setStyleSheet("border-color: #0ea5e9; color: #0ea5e9;")
btn_export.clicked.connect(self.cmd_export)
s_lay.addWidget(btn_export)
s_lay.addStretch()
btn_about = QPushButton("Info")
btn_about.clicked.connect(self.cmd_about)
s_lay.addWidget(btn_about)
btn_exit = QPushButton("Esci")
btn_exit.setObjectName("Exit")
btn_exit.clicked.connect(self.close)
s_lay.addWidget(btn_exit)
main_lay.addWidget(sidebar)
right_panel = QWidget()
r_lay = QVBoxLayout(right_panel)
top_bar = QWidget()
top_bar.setObjectName("Panel")
tb_lay = QHBoxLayout(top_bar)
tb_lay.addWidget(QLabel("<b>Visualizzatore Documento</b>"))
tb_lay.addStretch()
btn_zout = QPushButton("-")
btn_zout.clicked.connect(lambda: self.adjust_zoom(-1))
self.lbl_zoom = QLabel("150%")
btn_zin = QPushButton("+")
btn_zin.clicked.connect(lambda: self.adjust_zoom(1))
tb_lay.addWidget(btn_zout)
tb_lay.addWidget(self.lbl_zoom)
tb_lay.addWidget(btn_zin)
tb_lay.addSpacing(20)
btn_prev = QPushButton("<")
btn_prev.clicked.connect(lambda: self.move_page(-1))
self.le_page = QLineEdit("0")
self.le_page.setFixedWidth(40)
self.le_page.setAlignment(Qt.AlignCenter)
self.le_page.returnPressed.connect(self.jump_page)
self.lbl_tot = QLabel("/ 0")
btn_next = QPushButton(">")
btn_next.clicked.connect(lambda: self.move_page(1))
tb_lay.addWidget(btn_prev)
tb_lay.addWidget(self.le_page)
tb_lay.addWidget(self.lbl_tot)
tb_lay.addWidget(btn_next)
r_lay.addWidget(top_bar)
self.scene = QGraphicsScene()
self.view = PDFView(self.scene)
self.view.rect_drawn.connect(self.user_draw_rect)
self.view.point_clicked.connect(self.user_click_pt)
self.view.zoom_req.connect(self.adjust_zoom)
r_lay.addWidget(self.view, stretch=1)
footer = QWidget()
footer.setObjectName("Panel")
f_lay = QVBoxLayout(footer)
self.prog = QProgressBar()
self.prog.setValue(0)
self.log = QTextEdit()
self.log.setReadOnly(True)
self.log.setFixedHeight(80)
f_lay.addWidget(self.prog)
f_lay.addWidget(self.log)
r_lay.addWidget(footer)
main_lay.addWidget(right_panel, stretch=1)
def dragEnterEvent(self, e: QDragEnterEvent) -> None:
"""Accept drag enter event for dropped files."""
if e.mimeData().hasUrls():
e.acceptProposedAction()
def dropEvent(self, e: QDropEvent) -> None:
"""Handle dropped PDF files."""
urls = e.mimeData().urls()
if urls and urls[0].isLocalFile():
self.load_path(urls[0].toLocalFile())
def write_log(self, m: str) -> None:
"""Write message to UI log with color coding.
Args:
m: Message to log.
"""
t = datetime.datetime.now().strftime("%H:%M:%S")
color = (
"#ef4444"
if "ERRORE" in m
else (
"#f59e0b"
if "Avviso" in m
else "#10b981" if "successo" in m or "completata" in m else "#94a3b8"
)
)
self.log.append(f"<span style='color: {color};'>[{t}] {m}</span>")
def update_progress(self, c: int, t: int) -> None:
"""Update progress bar.
Args:
c: Current progress.
t: Total progress.
"""
# Guard against division by zero (empty document edge case)
if t <= 0:
self.prog.setValue(0)
return
self.prog.setValue(int((c / t) * 100))
def cmd_open(self) -> None:
"""Open file dialog to load PDF."""
p, _ = QFileDialog.getOpenFileName(self, "Apri PDF", "", "PDF (*.pdf)")
if p:
self.load_path(p)
def load_path(self, path: str) -> None:
"""Load a PDF document from disk and reset viewer state.
Args:
path: Filesystem path to a .pdf file.
"""
if not path or not isinstance(path, str):
self.write_log("ERRORE: Path non valido")
return
if not os.path.exists(path):
self.write_log(f"ERRORE: File non trovato: {path}")
return
if not path.lower().endswith('.pdf'):
self.write_log("ERRORE: Solo file PDF sono supportati")
return
try:
tdoc = fitz.open(path)
if tdoc.needs_pass:
self.write_log("ERRORE: PDF cifrato - inserire password non supportato")
tdoc.close()
return
# Swap docs under mutex so the AI worker thread (if running) is not
# holding a reference to a closed document.
with QMutexLocker(self.doc_mutex):
if self.doc:
self.doc.close()
self.doc = tdoc
self.page_num = 0
self.scale = 1.5
self.adjust_zoom(0)
self.write_log(f"Caricato: {os.path.basename(path)}")
except FileNotFoundError:
self.write_log(f"ERRORE: File non trovato")
except Exception as e:
self.logger.error(f"Error loading PDF: {traceback.format_exc()}")
self.write_log(f"ERRORE: {type(e).__name__}: {str(e)}")
def render(self) -> None:
"""Render current PDF page to display."""
if not self.doc:
return
with QMutexLocker(self.doc_mutex):
if not self.doc or self.page_num >= len(self.doc):
return
page = self.doc[self.page_num]
pix = page.get_pixmap(matrix=fitz.Matrix(self.scale, self.scale), annots=True)
total = len(self.doc)
# QImage does NOT copy `pix.samples`; if `pix` is garbage-collected before
# the image is used the buffer is freed (UB / crash). Force a deep copy.
img = QImage(
pix.samples, pix.width, pix.height, pix.stride, QImage.Format_RGB888
).copy()
self.scene.clear()
self.scene.addPixmap(QPixmap.fromImage(img))
self.scene.setSceneRect(0, 0, pix.width, pix.height)
self.le_page.setText(str(self.page_num + 1))
self.lbl_tot.setText(f"/ {total}")
def adjust_zoom(self, d: int) -> None:
"""Adjust zoom level.
Args:
d: Zoom direction (+1 to zoom in, -1 to zoom out).
"""
self.scale = max(0.5, min(4.0, self.scale + (0.25 * d)))
self.lbl_zoom.setText(f"{int(self.scale * 100)}%")
self.render()
def move_page(self, d: int) -> None:
"""Move to adjacent page.
Args:
d: Page direction (+1 for next, -1 for previous).
"""
if self.doc and 0 <= self.page_num + d < len(self.doc):
self.page_num += d
self.render()
def jump_page(self) -> None:
"""Jump to the page number entered in the page selector."""
if not self.doc:
self.write_log("Avviso: Nessun PDF caricato")
return
try:
n = int(self.le_page.text()) - 1
if 0 <= n < len(self.doc):
self.page_num = n
self.render()
else:
self.write_log(f"Avviso: Pagina {n + 1} non esiste (intervallo: 1-{len(self.doc)})")
except ValueError:
self.write_log("ERRORE: Inserire un numero valido per il numero di pagina")
except Exception as e:
self.logger.error(f"Unexpected error in jump_page: {traceback.format_exc()}")
self.write_log(f"ERRORE: {type(e).__name__}: {str(e)}")
def user_draw_rect(self, qrect: QRectF) -> None:
"""Handle user-drawn redaction rectangle.
Args:
qrect: Rectangle drawn by user in scene coordinates.
"""
if not self.doc:
return
r = fitz.Rect(
qrect.left() / self.scale,
qrect.top() / self.scale,
qrect.right() / self.scale,
qrect.bottom() / self.scale,
)
with QMutexLocker(self.doc_mutex):
if not self.doc:
return
p = self.doc[self.page_num]
txt = p.get_text("text", clip=r).strip()
if not txt:
p.add_redact_annot(
r,
text="[ IMMAGINE RIMOSSA ]",
align=1,
fill=(0.9, 0.9, 0.9),
fontsize=8,
)
else:
p.add_redact_annot(r, fill=(0, 0, 0))
cl = " ".join(txt.split()).lower()
if len(cl) > 2:
self.allowlist.discard(cl)
self.blocklist.add(cl)
self.list_manager.save_blocklist(self.blocklist)
self.list_manager.save_allowlist(self.allowlist)
self.render()
def user_click_pt(self, qpt: QPointF) -> None:
"""Handle user click on redaction to delete it.
Args:
qpt: Point clicked by user in scene coordinates.
"""
if not self.doc:
return
pt = fitz.Point(qpt.x() / self.scale, qpt.y() / self.scale)
has_ans = False
with QMutexLocker(self.doc_mutex):
if not self.doc:
return
p = self.doc[self.page_num]
ans = [
a
for a in (p.annots() or [])
if a.type[0] == fitz.PDF_ANNOT_REDACT and a.rect.contains(pt)
]
if ans:
has_ans = True
txt = p.get_text("text", clip=ans[0].rect)
for a in ans:
p.delete_annot(a)
cl = " ".join(txt.split()).lower()
if len(cl) > 2:
self.blocklist.discard(cl)
self.allowlist.add(cl)
self.list_manager.save_blocklist(self.blocklist)
self.list_manager.save_allowlist(self.allowlist)
if has_ans:
self.render()
def cmd_clear(self) -> None:
"""Clear all redactions on current page."""
if not self.doc:
return
with QMutexLocker(self.doc_mutex):
if not self.doc:
return
p = self.doc[self.page_num]
# Materialize list first: deleting annotations invalidates the
# generator returned by p.annots(), and list-comprehension-for-
# side-effects is an anti-pattern (PEP 8 / pylint W0106).
to_delete = [
a for a in (p.annots() or []) if a.type[0] == fitz.PDF_ANNOT_REDACT
]
for a in to_delete:
p.delete_annot(a)
self.render()
self.write_log(f"Censure rimosse su pagina {self.page_num+1}")
def cmd_dict(self) -> None:
"""Open dialog to edit blocklist/allowlist."""
d = QDialog(self)
d.setWindowTitle("Dizionari")
d.resize(500, 450)
lay = QVBoxLayout(d)
lay.addWidget(QLabel("<b>🔴 BLOCKLIST</b>"))
bx = QTextEdit()
bx.setPlainText("\n".join(sorted(self.blocklist)))
lay.addWidget(bx)
lay.addWidget(QLabel("<b>🟢 ALLOWLIST</b>"))
ax = QTextEdit()
ax.setPlainText("\n".join(sorted(self.allowlist)))
lay.addWidget(ax)
btn = QPushButton("Salva")
btn.setObjectName("Primary")
def s() -> None:
self.blocklist = {
line.strip().lower()
for line in bx.toPlainText().split("\n")
if len(line.strip()) > 2
}
self.allowlist = {
line.strip().lower()
for line in ax.toPlainText().split("\n")
if len(line.strip()) > 2
}
self.list_manager.save_blocklist(self.blocklist)
self.list_manager.save_allowlist(self.allowlist)
d.accept()
btn.clicked.connect(s)
lay.addWidget(btn)
d.exec()
def cmd_about(self) -> None:
"""Show about dialog."""
d = QDialog(self)
d.setWindowTitle("Info")
d.setFixedSize(340, 440)
lay = QVBoxLayout(d)
lay.setAlignment(Qt.AlignCenter)
ip = resource_path(os.path.join("images", "NullifyPDF_icon.png"))
if os.path.exists(ip):
lbl_icon = QLabel()
lbl_icon.setPixmap(
QPixmap(ip).scaled(
100, 100, Qt.KeepAspectRatio, Qt.SmoothTransformation
)
)
lbl_icon.setAlignment(Qt.AlignCenter)
lay.addWidget(lbl_icon)
lay.addSpacing(10)
lbl_title = QLabel("NullifyPDF")
lbl_title.setStyleSheet("font-size: 24px; font-weight: bold;")
lbl_title.setAlignment(Qt.AlignCenter)
lay.addWidget(lbl_title)
lbl_ver = QLabel(f"v{__version__} AI Forensic")
lbl_ver.setStyleSheet("color: #0ea5e9; font-weight: bold;")
lbl_ver.setAlignment(Qt.AlignCenter)
lay.addWidget(lbl_ver)
desc = QLabel(
"\nAnonimizzazione PDF Offline.\n\nSviluppato da: Graziano Mariella\nLicenza MIT"
)
desc.setAlignment(Qt.AlignCenter)
lay.addWidget(desc)
lay.addSpacing(20)
btn = QPushButton("Chiudi")
btn.clicked.connect(d.accept)
lay.addWidget(btn)
d.exec()
def cmd_auto_ai(self) -> None:
"""Start AI scan for sensitive entities.
Text extraction is delegated to the AIWorker thread so the UI stays