-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProfiler_Suite_V15.py
More file actions
8846 lines (7123 loc) · 324 KB
/
Copy pathProfiler_Suite_V15.py
File metadata and controls
8846 lines (7123 loc) · 324 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import os
import io
import json
import uuid
import hashlib
import re
import shutil
import sqlite3
import time
import subprocess
import traceback
from datetime import datetime, timedelta, timezone
from pathlib import Path
from PySide6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QListWidget, QListWidgetItem,
QMenu, QHBoxLayout, QPushButton, QProgressBar, QLabel,
QDialog, QFormLayout, QLineEdit, QComboBox, QCheckBox, QDialogButtonBox,
QFileDialog, QTabWidget, QSplitter, QTextEdit, QSystemTrayIcon, QStyle, QMessageBox,
QTreeWidget, QTreeWidgetItem, QInputDialog, QGroupBox, QRadioButton, QButtonGroup,
QFileIconProvider, QSpinBox, QScrollArea
)
from PySide6.QtCore import (
Qt, QThread, Signal, QObject, QTimer,
QSize, QFileInfo, QMimeData
)
from PySide6.QtGui import QAction, QPalette, QColor, QFont, QPixmap, QIcon, QImage
from workspace_exchange import (
WorkspaceFormatError,
export_workspace as export_redacted_workspace,
import_workspace as import_redacted_workspace,
)
from app_paths import app_data_dir, config_path, resolve_read_path
from sibling_launcher import (
normalize_configured_tool_path,
resolve_prosync_launch_path,
launch_prosync as _sibling_launch_prosync,
LaunchResult as _LaunchResult,
)
from version import APP_VERSION
# Optionale Bibliotheken
try:
# pypdf ist der gepflegte Nachfolger von PyPDF2. PyPDF2 wurde eingestellt
# und bekommt keine Sicherheitspatches mehr (GHSA-4vvm-4w3v-6mr8 hat dort
# bis heute keine korrigierte Version). Die hier genutzte API
# (PdfReader/PdfWriter) ist in beiden identisch.
import pypdf
from pypdf import PdfReader, PdfWriter
HAS_PDF = True
except ImportError:
HAS_PDF = False
try:
import docx
HAS_DOCX = True
except ImportError:
HAS_DOCX = False
try:
import pytesseract
from PIL import Image
HAS_OCR = True
except ImportError:
HAS_OCR = False
try:
from pdf2image import convert_from_path
HAS_PDF2IMAGE = True
except ImportError:
HAS_PDF2IMAGE = False
try:
import fitz # PyMuPDF for redaction
HAS_FITZ = True
except ImportError:
HAS_FITZ = False
try:
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
HAS_WATCHDOG = True
except ImportError:
HAS_WATCHDOG = False
try:
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, PageBreak, Table, TableStyle
from reportlab.lib.units import cm
from reportlab.lib import colors
HAS_REPORTLAB = True
except ImportError:
HAS_REPORTLAB = False
try:
import pikepdf
HAS_PIKEPDF = True
except ImportError:
HAS_PIKEPDF = False
try:
from module_registry import ModuleRegistry
_MODULE_REGISTRY_AVAILABLE = True
except ImportError:
_MODULE_REGISTRY_AVAILABLE = False
# ============================================================================
# ENCODING SETUP
# ============================================================================
def setup_windows_encoding():
"""
Konfiguriert UTF-8 Encoding für Windows-Konsole.
Verhindert Encoding-Probleme bei deutschen Umlauten und Sonderzeichen.
"""
if sys.platform == 'win32':
if sys.stdout.encoding != 'utf-8':
sys.stdout.reconfigure(encoding='utf-8')
if sys.stderr.encoding != 'utf-8':
sys.stderr.reconfigure(encoding='utf-8')
# Encoding-Setup beim Import ausführen
setup_windows_encoding()
print(f"ProFiler Suite {APP_VERSION} startet...")
print("Encoding Check:", sys.stdout.encoding)
# ============================================================================
# 1. SHARED UTILS & CONFIG
# ============================================================================
_CONFIG_DIR = app_data_dir()
SEARCH_CONFIG_PATH = str(config_path("search_config.json"))
SYNC_CONFIG_PATH = str(config_path("profiler_config.json"))
SETTINGS_PATH = str(config_path("profiler_settings.json"))
# Konstanten für File Processing
DEFAULT_CHUNK_SIZE = 1024 * 1024 # 1 MB für Hash-Berechnung
PDF_TEXT_MIN_CHARS = 20 # Minimale Zeichenanzahl für Text-Erkennung
PDF_PAGES_TO_CHECK = 3 # Anzahl zu prüfender Seiten in PDFs
FILE_ATTR_CLOUD_PLACEHOLDER = 0x1000 # Windows File-Attribut für Cloud-Placeholder
FILE_ATTR_RECALL_ON_ACCESS = 0x400 # Windows File-Attribut für Recall-on-Access
# WINDOWS_ENV_VAR_PATTERN: nach sibling_launcher.py verschoben
def app_base_dir():
"""Liefert den Laufzeitpfad für lokale und eingefrorene Builds."""
if getattr(sys, "frozen", False):
return os.path.dirname(sys.executable)
return os.path.dirname(os.path.abspath(__file__))
# normalize_configured_tool_path und resolve_prosync_launch_path sind
# aus sibling_launcher importiert (kanonische Implementierung dort).
def sha256_file(path, chunk_size=DEFAULT_CHUNK_SIZE):
"""Berechnet den SHA256 Hash. Robust gegen leere Dateien."""
h = hashlib.sha256()
try:
with open(path, "rb") as f:
while True:
chunk = f.read(chunk_size)
if not chunk: break
h.update(chunk)
except (PermissionError, OSError):
return None
return h.hexdigest()
def is_cloud_placeholder(path):
"""
Prüft ob eine Datei ein Cloud-Placeholder ist (OneDrive/Dropbox).
Args:
path: Dateipfad
Returns:
bool: True wenn Placeholder, False sonst
"""
if os.name != 'nt':
return False
try:
attrs = os.stat(path).st_file_attributes
return (attrs & FILE_ATTR_CLOUD_PLACEHOLDER) or (attrs & FILE_ATTR_RECALL_ON_ACCESS)
except (OSError, AttributeError):
return False
def shorten_filename(name, max_len):
"""
Kürzt einen Dateinamen auf maximale Länge.
Args:
name: Dateiname
max_len: Maximale Länge
Returns:
str: Gekürzter Dateiname mit "..." in der Mitte
"""
if len(name) <= max_len:
return name
root, ext = os.path.splitext(name)
keep = max(1, max_len - len(ext) - 3)
return root[:keep] + "..." + ext
def get_file_category(filename):
"""
Kategorisiert Dateien nach Extension.
Args:
filename: Dateiname mit Extension
Returns:
str: Kategorie (Dokumente, Bilder, Audio, Video, Archive, Code, Tabellen, Andere)
"""
ext = os.path.splitext(filename)[1].lower()
if ext in ['.pdf', '.doc', '.docx', '.txt', '.md', '.rtf', '.odt']: return "Dokumente"
if ext in ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg', '.webp']: return "Bilder"
if ext in ['.mp3', '.wav', '.flac', '.aac', '.ogg', '.m4a']: return "Audio"
if ext in ['.mp4', '.mkv', '.avi', '.mov', '.wmv']: return "Video"
if ext in ['.zip', '.rar', '.7z', '.tar', '.gz']: return "Archive"
if ext in ['.py', '.js', '.html', '.css', '.json', '.xml', '.sql', '.cpp', '.c', '.h']: return "Code"
if ext in ['.xls', '.xlsx', '.csv']: return "Tabellen"
return "Andere"
def is_pdf_encrypted(filepath):
"""
Prüft ob eine PDF-Datei verschlüsselt ist.
Args:
filepath: Pfad zur PDF-Datei
Returns:
bool: True wenn verschlüsselt, False sonst
"""
if not HAS_PDF:
return False
try:
with open(filepath, 'rb') as f:
pdf = PdfReader(f)
return pdf.is_encrypted
except (OSError, Exception):
return False
def has_pdf_text(filepath):
"""
Prüft ob eine PDF-Datei extrahierbaren Text enthält.
Scannt bis zu 3 Seiten und prüft ob mindestens 20 Zeichen Text gefunden werden.
Verhindert falsche OCR-Erkennung bei reinen Bild-PDFs.
Args:
filepath: Pfad zur PDF-Datei
Returns:
bool: True wenn Text vorhanden, False wenn nur Bilder
"""
if not HAS_PDF:
return False
try:
with open(filepath, 'rb') as f:
pdf = PdfReader(f)
if len(pdf.pages) == 0:
return False
# Prüfe bis zu PDF_PAGES_TO_CHECK Seiten für bessere Erkennung
pages_to_check = min(PDF_PAGES_TO_CHECK, len(pdf.pages))
for i in range(pages_to_check):
text = pdf.pages[i].extract_text() or ""
# Reduzierte Schwelle: PDF_TEXT_MIN_CHARS statt 50 Zeichen
if len(text.strip()) > PDF_TEXT_MIN_CHARS:
return True
return False
except (OSError, Exception):
return False
def find_tool_path(tool_name):
"""Sucht nach einem Tool im Projekt-Verzeichnis.
Delegiert an ModuleRegistry wenn verfügbar (kennt alle Begleitmodule +
konfigurierte Pfade). Fallback: einfache same-dir/parent-dir-Prüfung für
unbekannte tool_name-Werte.
"""
if _MODULE_REGISTRY_AVAILABLE:
script_dir = Path(os.path.abspath(__file__)).parent
reg = ModuleRegistry(base_dir=script_dir)
info = reg.get_by_filename(tool_name)
if info is not None:
return str(info.resolved_path) if info.available else None
# Fallback für unbekannte Dateinamen
script_dir = os.path.dirname(os.path.abspath(__file__))
tool_path = os.path.join(script_dir, tool_name)
if os.path.exists(tool_path):
return tool_path
parent_dir = os.path.dirname(script_dir)
parent_path = os.path.join(parent_dir, tool_name)
if os.path.exists(parent_path):
return parent_path
return None
def configure_compact_picker_button(button, *, tooltip, accessible_name, accessible_description):
"""Ergänzt Icon-/Kurzbuttons um sprechende A11y- und Tooltip-Texte."""
button.setToolTip(tooltip)
button.setAccessibleName(accessible_name)
button.setAccessibleDescription(accessible_description)
# --- CONFIG MANAGERS ---
class SearchConfigManager:
def __init__(self):
self.dbs = []
self.load()
def load(self):
load_path = resolve_read_path(Path(SEARCH_CONFIG_PATH).name)
if load_path.exists():
try:
with open(load_path, "r", encoding="utf-8") as f:
self.dbs = json.load(f).get("databases", [])
except (OSError, json.JSONDecodeError, KeyError):
self.save()
else:
self.save()
def save(self):
os.makedirs(os.path.dirname(SEARCH_CONFIG_PATH) or ".", exist_ok=True)
with open(SEARCH_CONFIG_PATH, "w", encoding="utf-8") as f:
json.dump({"databases": self.dbs}, f, indent=2)
def add_db(self, path):
if path and path not in self.dbs: self.dbs.append(path); self.save()
def remove_db(self, path):
self.dbs = [d for d in self.dbs if d != path]; self.save()
class SyncConfigManager:
def __init__(self, path):
self.path = path
self.data = {"connections": []}
self.load()
def load(self):
load_path = resolve_read_path(Path(self.path).name)
if load_path.exists():
try:
with open(load_path, "r", encoding="utf-8") as f:
self.data = json.load(f)
except (OSError, json.JSONDecodeError):
self.save()
else:
self.save()
def save(self):
os.makedirs(os.path.dirname(self.path) or ".", exist_ok=True)
with open(self.path, "w", encoding="utf-8") as f: json.dump(self.data, f, indent=2)
def list_connections(self): return self.data.get("connections", [])
def add_or_update_connection(self, conn):
conns = self.data.get("connections", [])
found = False
for i, c in enumerate(conns):
if c.get("id") == conn.get("id"):
conns[i] = conn; found = True; break
if not found: conns.append(conn)
self.data["connections"] = conns; self.save()
def remove_connection(self, conn_id):
self.data["connections"] = [c for c in self.data.get("connections", []) if c.get("id") != conn_id]
self.save()
class SettingsManager:
"""Verwaltet App-Einstellungen; PDF-Passwörter bleiben sitzungsbezogen."""
SESSION_ONLY_KEYS = frozenset({
"pdf_master_password_open",
"pdf_master_password_save",
})
def __init__(self):
self.data = {
"delete_mode": "soft",
"trash_retention_days": 30,
"auto_cleanup_enabled": True,
"pdf_master_password_open": "", # Masterpasswort zum Öffnen
"pdf_master_password_save": "", # Masterpasswort zum Speichern
"ocr_language": "deu", # Tesseract Language
"ocr_enabled": True,
"prosync_path": ""
}
self.load()
def load(self):
load_path = resolve_read_path(Path(SETTINGS_PATH).name)
if load_path.exists():
try:
with open(load_path, "r", encoding="utf-8") as f:
loaded = json.load(f)
if not isinstance(loaded, dict):
raise ValueError("Einstellungsdatei muss ein JSON-Objekt sein")
had_legacy_secrets = any(key in loaded for key in self.SESSION_ONLY_KEYS)
for key in self.SESSION_ONLY_KEYS:
loaded.pop(key, None)
self.data.update(loaded)
if had_legacy_secrets:
self.save()
except (OSError, ValueError, json.JSONDecodeError):
self.save()
else:
self.save()
def save(self):
os.makedirs(os.path.dirname(SETTINGS_PATH) or ".", exist_ok=True)
persistent_data = {
key: value
for key, value in self.data.items()
if key not in self.SESSION_ONLY_KEYS
}
target = Path(SETTINGS_PATH)
temporary = target.with_suffix(target.suffix + ".tmp")
temporary.write_text(
json.dumps(persistent_data, indent=2, ensure_ascii=False) + "\n",
encoding="utf-8",
)
os.replace(temporary, target)
def get(self, key, default=None):
return self.data.get(key, default)
def set(self, key, value):
self.data[key] = value
self.save()
# ============================================================================
# AUTO-SYNC WATCHDOG (V14.3)
# ============================================================================
class AutoSyncHandler(FileSystemEventHandler if HAS_WATCHDOG else object):
"""
Überwacht einen Ordner auf neue/geänderte Dateien und synchronisiert automatisch.
Benötigt: pip install watchdog
"""
def __init__(self, target_folder, extensions=None, callback=None):
if HAS_WATCHDOG:
super().__init__()
self.target = target_folder
self.extensions = extensions or ['.pdf', '.docx', '.xlsx', '.txt', '.jpg', '.png']
self.callback = callback # UI-Callback für Status-Updates
self.sync_count = 0
self.last_sync = None
def on_created(self, event):
"""Wird aufgerufen wenn eine neue Datei erstellt wird."""
if event.is_directory:
return
if self._should_sync(event.src_path):
self._sync_file(event.src_path, "created")
def on_modified(self, event):
"""Wird aufgerufen wenn eine Datei geändert wird."""
if event.is_directory:
return
if self._should_sync(event.src_path):
self._sync_file(event.src_path, "modified")
def _should_sync(self, path):
"""Prüft ob die Datei synchronisiert werden soll (basierend auf Extension)."""
return any(path.lower().endswith(ext) for ext in self.extensions)
def _sync_file(self, src_path, event_type):
"""Kopiert die Datei in den Zielordner."""
try:
filename = os.path.basename(src_path)
dest_path = os.path.join(self.target, filename)
# Duplikat-Handling
if os.path.exists(dest_path):
base, ext = os.path.splitext(filename)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
dest_path = os.path.join(self.target, f"{base}_{timestamp}{ext}")
shutil.copy2(src_path, dest_path)
self.sync_count += 1
self.last_sync = datetime.now()
if self.callback:
self.callback(f"Sync: {filename} ({event_type})")
except Exception as e:
if self.callback:
self.callback(f"Sync-Fehler: {e}")
class AutoSyncManager(QObject):
"""
Verwaltet Watchdog-Observer für Auto-Sync.
Kann mehrere Watch-Ordner gleichzeitig überwachen.
"""
status_changed = Signal(str)
file_synced = Signal(str)
def __init__(self, parent=None):
super().__init__(parent)
self.observers = {} # source_path -> Observer
self.handlers = {} # source_path -> AutoSyncHandler
self.active = False
def start_watch(self, source_folder, target_folder, extensions=None):
"""Startet die Überwachung eines Ordners."""
if not HAS_WATCHDOG:
self.status_changed.emit("Watchdog nicht installiert (pip install watchdog)")
return False
if source_folder in self.observers:
self.status_changed.emit(f"Ordner wird bereits überwacht: {source_folder}")
return False
handler = AutoSyncHandler(
target_folder,
extensions,
callback=lambda msg: self.file_synced.emit(msg)
)
observer = Observer()
observer.schedule(handler, source_folder, recursive=False)
observer.start()
self.observers[source_folder] = observer
self.handlers[source_folder] = handler
self.active = True
self.status_changed.emit(f"Überwachung gestartet: {source_folder} → {target_folder}")
return True
def stop_watch(self, source_folder=None):
"""Stoppt die Überwachung (eines oder aller Ordner)."""
if source_folder:
if source_folder in self.observers:
self.observers[source_folder].stop()
self.observers[source_folder].join()
del self.observers[source_folder]
del self.handlers[source_folder]
self.status_changed.emit(f"Überwachung gestoppt: {source_folder}")
else:
# Alle stoppen
for path, obs in self.observers.items():
obs.stop()
obs.join()
self.observers.clear()
self.handlers.clear()
self.status_changed.emit("Alle Überwachungen gestoppt")
self.active = len(self.observers) > 0
def get_status(self):
"""Gibt den aktuellen Status zurück."""
if not self.observers:
return "Inaktiv"
return f"Aktiv: {len(self.observers)} Ordner überwacht"
def get_stats(self):
"""Gibt Statistiken zurück."""
total_synced = sum(h.sync_count for h in self.handlers.values())
return {
"watched_folders": len(self.observers),
"total_synced": total_synced,
"active": self.active
}
# ============================================================================
# CONNECTIONS DATABASE (from ProFiler V4 + multi-folder support)
# ============================================================================
DDL_SCHEMA = """
CREATE TABLE IF NOT EXISTS files(
id INTEGER PRIMARY KEY,
content_hash TEXT UNIQUE,
size INTEGER,
mime TEXT,
first_seen TEXT
);
CREATE TABLE IF NOT EXISTS versions(
id INTEGER PRIMARY KEY,
file_id INTEGER,
name TEXT,
path TEXT,
mtime TEXT,
ctime TEXT,
version_index INTEGER,
source_folder TEXT
);
CREATE TABLE IF NOT EXISTS tags(
id INTEGER PRIMARY KEY,
file_id INTEGER,
tag TEXT
);
CREATE TABLE IF NOT EXISTS events(
id INTEGER PRIMARY KEY,
file_id INTEGER,
event_type TEXT,
details TEXT,
ts TEXT
);
"""
# ============================================================================
# 2. PDF UTILITY FUNCTIONS
# ============================================================================
class PDFUtils:
"""PDF-spezifische Utility-Funktionen"""
@staticmethod
def encrypt_pdf(input_path, output_path, password):
"""Verschlüsselt ein PDF mit Passwort"""
if not HAS_PDF:
raise Exception("pypdf nicht installiert")
try:
reader = PdfReader(input_path)
writer = PdfWriter()
# Alle Seiten kopieren
for page in reader.pages:
writer.add_page(page)
# Verschlüsseln
writer.encrypt(password)
# Speichern
with open(output_path, 'wb') as f:
writer.write(f)
return True
except Exception as e:
raise Exception(f"Verschlüsselung fehlgeschlagen: {str(e)}")
@staticmethod
def decrypt_pdf(input_path, output_path, password):
"""Entschlüsselt ein PDF"""
if not HAS_PDF:
raise Exception("pypdf nicht installiert")
try:
reader = PdfReader(input_path)
if reader.is_encrypted:
# Passwort versuchen
if not reader.decrypt(password):
raise Exception("Falsches Passwort")
writer = PdfWriter()
# Alle Seiten kopieren
for page in reader.pages:
writer.add_page(page)
# OHNE Verschlüsselung speichern
with open(output_path, 'wb') as f:
writer.write(f)
return True
except Exception as e:
raise Exception(f"Entschlüsselung fehlgeschlagen: {str(e)}")
@staticmethod
def extract_pages(input_path, output_path, page_indices):
"""Erstellt PDF-Auszug mit ausgewählten Seiten"""
if not HAS_PDF:
raise Exception("pypdf nicht installiert")
try:
reader = PdfReader(input_path)
writer = PdfWriter()
# Nur ausgewählte Seiten
for idx in page_indices:
if 0 <= idx < len(reader.pages):
writer.add_page(reader.pages[idx])
with open(output_path, 'wb') as f:
writer.write(f)
return True
except Exception as e:
raise Exception(f"Auszug-Erstellung fehlgeschlagen: {str(e)}")
@staticmethod
def remove_text_from_pdf(input_path, output_path):
"""Entfernt Text aus PDF, behlt nur Bilder"""
if not HAS_PDF:
raise Exception("pypdf nicht installiert")
try:
# Dies ist komplex - vereinfachte Version:
# Konvertiere zu Bildern und zurück zu PDF
if not HAS_PDF2IMAGE:
raise Exception("pdf2image nicht installiert")
images = convert_from_path(input_path)
if images:
images[0].save(output_path, "PDF", save_all=True,
append_images=images[1:] if len(images) > 1 else [])
return True
return False
except Exception as e:
raise Exception(f"Text-Entfernung fehlgeschlagen: {str(e)}")
@staticmethod
def apply_ocr_to_pdf(input_path, output_path, lang='deu'):
"""Erzeugt aus Bildseiten ein durchsuchbares PDF mit OCR-Textebene."""
if not HAS_OCR or not HAS_PDF2IMAGE or not HAS_PDF:
raise Exception("pytesseract, pdf2image oder pypdf nicht installiert")
try:
# PDF zu Bildern
images = convert_from_path(input_path)
writer = PdfWriter()
for img in images:
page_pdf = pytesseract.image_to_pdf_or_hocr(
img,
extension="pdf",
lang=lang,
)
page_reader = PdfReader(io.BytesIO(page_pdf))
for page in page_reader.pages:
writer.add_page(page)
if not writer.pages:
raise ValueError("OCR lieferte keine PDF-Seiten")
target = Path(output_path)
target.parent.mkdir(parents=True, exist_ok=True)
temporary = target.with_suffix(target.suffix + ".tmp")
try:
with temporary.open("wb") as handle:
writer.write(handle)
os.replace(temporary, target)
finally:
temporary.unlink(missing_ok=True)
return True
except Exception as e:
raise Exception(f"OCR fehlgeschlagen: {str(e)}")
# ============================================================================
# ANONYMIZATION ENGINE
# ============================================================================
class AnonymizationWorker(QThread):
"""Worker-Thread für Anonymisierung und Schwärzung"""
progress = Signal(int, int) # current, total
log_message = Signal(str)
finished = Signal()
def __init__(self, file_paths, blacklist, whitelist, placeholder="[-----]", mode="anonymize"):
super().__init__()
self.file_paths = file_paths
self.blacklist = blacklist
self.whitelist = whitelist
self.placeholder = placeholder
self.mode = mode # "anonymize" or "redact"
self.is_running = True
def run(self):
"""Verarbeitet Dateien"""
total = len(self.file_paths)
for idx, file_path in enumerate(self.file_paths):
if not self.is_running:
break
self.progress.emit(idx + 1, total)
try:
ext = os.path.splitext(file_path)[1].lower()
folder = os.path.dirname(file_path)
basename = os.path.splitext(os.path.basename(file_path))[0]
if self.mode == "anonymize":
# Textdatei-Anonymisierung
if ext in ['.txt', '.log', '.py', '.md']:
output_path = os.path.join(folder, f"{basename}_anonymisiert{ext}")
self.anonymize_text_file(file_path, output_path)
self.log_message.emit(f"✅ Anonymisiert: {os.path.basename(output_path)}")
elif ext == '.docx':
output_path = os.path.join(folder, f"{basename}_anonymisiert{ext}")
self.anonymize_docx_file(file_path, output_path)
self.log_message.emit(f"✅ Anonymisiert: {os.path.basename(output_path)}")
elif ext == '.pdf':
output_path = os.path.join(folder, f"{basename}_geschwärzt.pdf")
self.redact_pdf(file_path, output_path)
self.log_message.emit(f"✅ Geschwärzt: {os.path.basename(output_path)}")
else:
self.log_message.emit(f"⚠️ Format nicht unterstützt: {os.path.basename(file_path)}")
elif self.mode == "redact":
# PDF-Schwärzung
if ext != '.pdf':
# Konvertiere zu PDF zuerst
temp_pdf = self.convert_to_pdf(file_path)
if temp_pdf:
output_path = os.path.join(folder, f"{basename}_geschwärzt.pdf")
self.redact_pdf(temp_pdf, output_path)
os.remove(temp_pdf)
self.log_message.emit(f"✅ Geschwärzt: {os.path.basename(output_path)}")
else:
self.log_message.emit(f"❌ Konvertierung fehlgeschlagen: {os.path.basename(file_path)}")
else:
output_path = os.path.join(folder, f"{basename}_geschwärzt.pdf")
self.redact_pdf(file_path, output_path)
self.log_message.emit(f"✅ Geschwärzt: {os.path.basename(output_path)}")
except Exception as e:
self.log_message.emit(f"❌ Fehler bei {os.path.basename(file_path)}: {str(e)}")
self.finished.emit()
def anonymize_text_file(self, input_path, output_path):
"""Anonymisiert Textdatei durch Platzhalter-Ersetzung"""
with open(input_path, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
for word in self.blacklist:
if self.is_whitelisted(word):
continue
# Case-insensitive replace
import re
pattern = re.compile(re.escape(word), re.IGNORECASE)
content = pattern.sub(self.placeholder, content)
with open(output_path, 'w', encoding='utf-8') as f:
f.write(content)
def anonymize_docx_file(self, input_path, output_path):
"""Anonymisiert Word-Dokument"""
if not HAS_DOCX:
raise Exception("python-docx nicht installiert")
doc = docx.Document(input_path)
# Absätze
for paragraph in doc.paragraphs:
for word in self.blacklist:
if self.is_whitelisted(word):
continue
if word.lower() in paragraph.text.lower():
# Vereinfachte Ersetzung
import re
pattern = re.compile(re.escape(word), re.IGNORECASE)
paragraph.text = pattern.sub(self.placeholder, paragraph.text)
# Tabellen
for table in doc.tables:
for row in table.rows:
for cell in row.cells:
for paragraph in cell.paragraphs:
for word in self.blacklist:
if self.is_whitelisted(word):
continue
if word.lower() in paragraph.text.lower():
import re
pattern = re.compile(re.escape(word), re.IGNORECASE)
paragraph.text = pattern.sub(self.placeholder, paragraph.text)
doc.save(output_path)
def redact_pdf(self, input_path, output_path):
"""Schwärzt PDF mit schwarzen Balken"""
if not HAS_FITZ:
raise Exception("PyMuPDF (fitz) nicht installiert")
doc = fitz.open(input_path)
for page in doc:
for word in self.blacklist:
if self.is_whitelisted(word):
continue
# Suche Wort im PDF
hits = page.search_for(word)
for rect in hits:
# Fge Schwrzungs-Annotation hinzu
page.add_redact_annot(rect, fill=(0, 0, 0))
# Wende Schwrzungen an
page.apply_redactions()
doc.save(output_path)
doc.close()
def convert_to_pdf(self, path):
"""Konvertiert Datei zu PDF"""
import tempfile
ext = os.path.splitext(path)[1].lower()
temp_pdf = os.path.join(tempfile.gettempdir(), f"temp_{int(time.time())}.pdf")
# Bild -> PDF
if ext in ['.png', '.jpg', '.jpeg', '.bmp', '.tiff']:
try:
from PIL import Image
img = Image.open(path)
img.convert("RGB").save(temp_pdf)
return temp_pdf
except (OSError, IOError):
return None
# TXT -> PDF
if ext in ['.txt', '.log', '.py', '.md']:
try:
doc = fitz.open()
page = doc.new_page()
with open(path, 'r', encoding='utf-8', errors='ignore') as f:
text = f.read()
page.insert_text((50, 50), text, fontsize=10)
doc.save(temp_pdf)
doc.close()
return temp_pdf
except (OSError, IOError):
return None
return None
def is_whitelisted(self, word):
"""Prüft ob Wort auf Whitelist steht"""
norm_word = word.strip().lower()
for white in self.whitelist:
if norm_word == white.strip().lower():
return True
return False
def stop(self):
"""Stoppt Worker"""
self.is_running = False
# ============================================================================
# 3. ENHANCED DATABASE WITH PDF METADATA
# ============================================================================
DDL_BASE = """
PRAGMA journal_mode=WAL;
CREATE TABLE IF NOT EXISTS files(
id INTEGER PRIMARY KEY,
content_hash TEXT UNIQUE,
size INTEGER,
mime TEXT,
first_seen TEXT
);
CREATE TABLE IF NOT EXISTS versions(
id INTEGER PRIMARY KEY,
file_id INTEGER,
name TEXT,
path TEXT,
mtime TEXT,
ctime TEXT,
version_index INTEGER,
source_side TEXT
);
CREATE TABLE IF NOT EXISTS collections(
id INTEGER PRIMARY KEY,
name TEXT UNIQUE
);
CREATE TABLE IF NOT EXISTS collection_items(
collection_id INTEGER,
version_id INTEGER,
PRIMARY KEY(collection_id, version_id)
);
CREATE TABLE IF NOT EXISTS tags(
id INTEGER PRIMARY KEY,
file_id INTEGER,
tag TEXT
);
CREATE INDEX IF NOT EXISTS idx_versions_path ON versions(path);
CREATE INDEX IF NOT EXISTS idx_versions_mtime ON versions(mtime);
"""
# ============================================================================
# AUTO-UPDATE SYSTEM mit Watchdog
# ============================================================================
if HAS_WATCHDOG:
class ConnectionWatcher(FileSystemEventHandler):
"""überwacht Verbindungsordner auf änderungen"""
def __init__(self, connection_config, callback):
super().__init__()
self.conn_config = connection_config