-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUniversalInvoiceMail.py
More file actions
3930 lines (3280 loc) · 153 KB
/
UniversalInvoiceMail.py
File metadata and controls
3930 lines (3280 loc) · 153 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 -*-
"""
UniversalInvoiceMail V2.3.0
===========================
Vereinfachte, fokussierte App zum Extrahieren von Rechnungen aus E-Mails.
Features:
- IMAP für alle Mail-Anbieter (Gmail, Outlook, GMX, etc.)
- Gmail API als Alternative (schneller, weniger Rate-Limits)
- Vorkonfigurierte Profile für beliebte Shops
- PDF-Anhänge + Mail-Body-zu-PDF Konvertierung
- DATEV-Export für ausgewählte Rechnungen
- Hash-basierte Duplikat-Erkennung
- Sichere Passwort-Speicherung via Keyring
Autor: Claude AI für Lukas
Datum: 2026-01-09
"""
import sys
import json
import os
import re
import base64
import io
import hashlib
import imaplib
import email
import email.header
import logging
import shutil
import subprocess
import tempfile
import time
from html import escape
from pathlib import Path
from dataclasses import dataclass, asdict, field, fields
from datetime import datetime, date, timedelta
from typing import List, Optional, Dict, Tuple
import uuid
# GUI
from PySide6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QLabel, QPushButton, QTableWidget, QTableWidgetItem, QHeaderView,
QMessageBox, QDialog, QFormLayout, QComboBox, QGroupBox, QCheckBox,
QTabWidget, QDialogButtonBox, QLineEdit, QFileDialog, QPlainTextEdit,
QListWidget, QListWidgetItem, QSpinBox, QProgressBar, QFrame,
QSplitter, QStyle
)
from PySide6.QtCore import Qt, QThread, Signal, QUrl, QSize
from PySide6.QtGui import QColor, QPalette, QDesktopServices, QFont, QIcon
# PDF Konvertierung
try:
from xhtml2pdf import pisa
XHTML2PDF_AVAILABLE = True
except ImportError:
XHTML2PDF_AVAILABLE = False
# Zusätzliche Anhang-Konvertierung (optional)
try:
from PIL import Image
PILLOW_AVAILABLE = True
except ImportError:
Image = None
PILLOW_AVAILABLE = False
try:
from openpyxl import load_workbook
OPENPYXL_AVAILABLE = True
except ImportError:
load_workbook = None
OPENPYXL_AVAILABLE = False
try:
from docx import Document as DocxDocument
PYTHON_DOCX_AVAILABLE = True
except ImportError:
DocxDocument = None
PYTHON_DOCX_AVAILABLE = False
try:
import pythoncom
import win32com.client
WIN32COM_AVAILABLE = True
except ImportError:
pythoncom = None
win32com = None
WIN32COM_AVAILABLE = False
# OCR und PDF-Verarbeitung (optional fuer "Vollstaendig"-Modus)
# Nutzt pypdfium2 statt pdf2image - KEIN Poppler noetig!
try:
import pytesseract
import pypdfium2 as pdfium # PDF zu Bild ohne Poppler
from pypdf import PdfReader, PdfWriter
OCR_AVAILABLE = PILLOW_AVAILABLE
# Portable Tesseract im Anwendungsordner suchen
_app_dir = Path(__file__).parent
_portable_tesseract = _app_dir / "tesseract_portable" / "tesseract.exe"
_portable_tessdata = _app_dir / "tesseract_portable" / "tessdata"
if _portable_tesseract.exists():
pytesseract.pytesseract.tesseract_cmd = str(_portable_tesseract)
# TESSDATA_PREFIX setzen falls tessdata im portable Ordner
if _portable_tessdata.exists():
os.environ['TESSDATA_PREFIX'] = str(_portable_tessdata.parent)
except ImportError:
pytesseract = None
pdfium = None
PdfReader = None
PdfWriter = None
OCR_AVAILABLE = False
# Browser-PDF Rendering via Selenium + CDP (optional fuer "Browser"-Modus)
try:
from selenium import webdriver
from selenium.webdriver.edge.options import Options as EdgeOptions
from selenium.webdriver.edge.service import Service as EdgeService
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.chrome.service import Service as ChromeService
SELENIUM_AVAILABLE = True
except ImportError:
SELENIUM_AVAILABLE = False
# WebDriver Manager fuer automatischen Driver-Download
try:
from webdriver_manager.microsoft import EdgeChromiumDriverManager
from webdriver_manager.chrome import ChromeDriverManager
WEBDRIVER_MANAGER_AVAILABLE = True
except ImportError:
WEBDRIVER_MANAGER_AVAILABLE = False
# Gmail API (optional)
try:
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google.auth.exceptions import RefreshError
GMAIL_API_AVAILABLE = True
except ImportError:
GMAIL_API_AVAILABLE = False
# Keyring für sichere Passwörter
try:
import keyring
KEYRING_AVAILABLE = True
except ImportError:
KEYRING_AVAILABLE = False
# DATEV-Export (optional, gleicher Ordner wie UniversalInvoiceMail.py)
try:
from datev_exporter import DATEVConfig, DATEVExporter, export_invoices_datev
DATEV_AVAILABLE = True
except ImportError:
DATEV_AVAILABLE = False
# Logger konfigurieren
logger = logging.getLogger(__name__)
# ==================== KONFIGURATION ====================
APP_NAME = "UniversalInvoiceMail"
VERSION = "2.3.0"
BASE_DIR = Path.home() / ".universal_invoice_mail"
BASE_DIR.mkdir(parents=True, exist_ok=True)
CONFIG_FILE = BASE_DIR / "config.json"
INVOICES_DB = BASE_DIR / "invoices.json"
TOKEN_FILE = BASE_DIR / "token.json"
CREDENTIALS_FILE = BASE_DIR / "credentials.json"
GMAIL_SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
PDF_ATTACHMENT_EXTENSIONS = {'.pdf'}
IMAGE_ATTACHMENT_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.bmp', '.tif', '.tiff', '.webp'}
OFFICE_ATTACHMENT_EXTENSIONS = {'.docx', '.xlsx'}
LEGACY_ATTACHMENT_EXTENSIONS = {'.doc', '.xls'}
SUPPORTED_ATTACHMENT_EXTENSIONS = (
PDF_ATTACHMENT_EXTENSIONS
| IMAGE_ATTACHMENT_EXTENSIONS
| OFFICE_ATTACHMENT_EXTENSIONS
| LEGACY_ATTACHMENT_EXTENSIONS
)
LIBREOFFICE_CANDIDATE_PATHS = (
Path("C:/Program Files/LibreOffice/program/soffice.exe"),
Path("C:/Program Files/LibreOffice/program/soffice.com"),
Path("C:/Program Files (x86)/LibreOffice/program/soffice.exe"),
Path("C:/Program Files (x86)/LibreOffice/program/soffice.com"),
)
WORD_PDF_FORMAT = 17
EXCEL_PDF_FORMAT = 0
# Vorkonfigurierte Shop-Profile
DEFAULT_SHOP_PROFILES = [
{"name": "Amazon", "sender": "amazon", "subject": "Bestellung,Rechnung,Invoice,order"},
{"name": "Otto", "sender": "otto.de", "subject": "Rechnung,Bestellung"},
{"name": "Temu", "sender": "temu", "subject": "order,Bestellung,shipped"},
{"name": "eBay", "sender": "ebay", "subject": "Rechnung,Invoice,Zahlung"},
{"name": "MediaMarkt", "sender": "mediamarkt", "subject": "Rechnung,Bestellung"},
{"name": "Saturn", "sender": "saturn", "subject": "Rechnung,Bestellung"},
{"name": "Zalando", "sender": "zalando", "subject": "Rechnung,Bestellung"},
{"name": "Lidl", "sender": "lidl", "subject": "Rechnung,Bestellung"},
{"name": "IKEA", "sender": "ikea", "subject": "Bestellung,order"},
{"name": "Apple", "sender": "apple.com", "subject": "Rechnung,Receipt,Invoice"},
{"name": "Google Play", "sender": "google", "subject": "Bestellung,Receipt,Quittung"},
{"name": "PayPal", "sender": "paypal", "subject": "Zahlung,Payment,Quittung"},
{"name": "Telekom", "sender": "telekom", "subject": "Rechnung"},
{"name": "Vodafone", "sender": "vodafone", "subject": "Rechnung"},
{"name": "O2", "sender": "o2online", "subject": "Rechnung"},
]
IMAP_PRESETS = {
"Gmail": {"host": "imap.gmail.com", "port": 993},
"Outlook/Hotmail": {"host": "outlook.office365.com", "port": 993},
"GMX": {"host": "imap.gmx.net", "port": 993},
"Web.de": {"host": "imap.web.de", "port": 993},
"T-Online": {"host": "secureimap.t-online.de", "port": 993},
"Yahoo": {"host": "imap.mail.yahoo.com", "port": 993},
"iCloud": {"host": "imap.mail.me.com", "port": 993},
"Posteo": {"host": "posteo.de", "port": 993},
"Mailbox.org": {"host": "imap.mailbox.org", "port": 993},
"Andere...": {"host": "", "port": 993},
}
# ==================== DATENMODELLE ====================
@dataclass
class MailAccount:
"""Email account configuration (IMAP or Gmail API)."""
id: str
name: str
provider: str # Gmail API, IMAP
host: str = ""
port: int = 993
username: str = ""
use_gmail_api: bool = False
def to_dict(self) -> dict:
return asdict(self)
@classmethod
def from_dict(cls, d: dict) -> 'MailAccount':
return cls(**d)
@dataclass
class InvoiceProfile:
"""Search profile for invoice extraction with sender/subject/body filters."""
id: str
name: str
account_id: str
sender_filter: str = "" # z.B. "amazon" oder "amazon.de,amazon.com"
subject_filter: str = "" # z.B. "Rechnung,Invoice,Bestellung"
blacklist: str = "" # Darf NICHT enthalten (Betreff/Body), kommasepariert
body_must_contain: str = "" # Body MUSS enthalten (kommasepariert, ODER)
body_must_not_contain: str = "" # Body darf NICHT enthalten (kommasepariert)
enabled: bool = True
target_subfolder: str = "" # Optional: Unterordner
def to_dict(self) -> dict:
return asdict(self)
@classmethod
def from_dict(cls, d: dict) -> 'InvoiceProfile':
return cls(**d)
@dataclass
class Invoice:
"""Downloaded invoice file with metadata."""
id: str
profile_name: str
filename: str
date: str
path: str
sender: str = ""
subject: str = ""
hash: str = ""
is_attachment: bool = False # True = PDF-Anhang, False = Body-Link
amount: Optional[float] = None # Rechnungsbetrag (manuell editierbar)
def to_dict(self) -> dict:
return asdict(self)
@classmethod
def from_dict(cls, d: dict) -> 'Invoice':
known = {f.name for f in fields(cls)}
return cls(**{k: v for k, v in d.items() if k in known})
@dataclass
class AppSettings:
"""Global application settings for download behavior and PDF conversion."""
download_path: str = str(Path.home() / "Documents" / "Rechnungen")
download_attachments: bool = True
convert_body_to_pdf: bool = True
merge_body_with_attachments: bool = False # Body-Text an PDF-Anhang anfuegen
enable_hash_check: bool = True
max_emails_per_run: int = 100
date_filter_months: int = 12 # Legacy: Nur Mails der letzten X Monate
date_from: str = "" # Von-Datum (YYYY-MM-DD) - leer = kein Filter
date_to: str = "" # Bis-Datum (YYYY-MM-DD) - leer = heute
include_trash: bool = False # Papierkorb durchsuchen
pdf_mode: str = "fast" # "fast" = nur Text, "full" = mit Bildern
ocr_enabled: bool = False # OCR fuer bildbasierte PDFs (benoetigt Tesseract)
def to_dict(self) -> dict:
return asdict(self)
@classmethod
def from_dict(cls, d: dict) -> 'AppSettings':
# Kompatibilitaet mit alten Configs ohne neue Felder
valid_fields = {f.name for f in cls.__dataclass_fields__.values()}
filtered = {k: v for k, v in d.items() if k in valid_fields}
return cls(**filtered)
# ==================== HILFSFUNKTIONEN ====================
def sanitize_filename(name: str) -> str:
"""Removes invalid characters from filenames and limits length to 120 chars."""
if not name:
return "unnamed"
s = re.sub(r'[<>:"/\\|?*\x00-\x1f]', '_', name)
s = re.sub(r'\s+', '_', s)
s = re.sub(r'_+', '_', s)
return s.strip('_')[:120]
def format_imap_date(dt: datetime) -> str:
"""Formats a date for IMAP (RFC 3501) — always uses English month names.
Note: strftime("%d-%b-%Y") is locale-dependent and produces "01-Mai-2025"
on German systems instead of "01-May-2025". IMAP servers require English.
"""
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
return f"{dt.day:02d}-{months[dt.month - 1]}-{dt.year}"
def safe_b64decode(data: str) -> bytes:
"""Base64 decoding with padding fix and whitespace cleanup.
Emails often contain newlines in the Base64 string that corrupt the padding
calculation. These must be removed before length computation.
"""
if not data:
return b""
# Whitespaces entfernen vor Padding-Berechnung (Fix fuer E-Mail Base64)
data = data.strip().replace(" ", "").replace("\n", "").replace("\r", "").replace("\t", "")
missing_padding = len(data) % 4
if missing_padding:
data += '=' * (4 - missing_padding)
return base64.urlsafe_b64decode(data)
def calculate_hash(data: bytes) -> str:
"""Calculates the SHA-256 hash of raw bytes."""
return hashlib.sha256(data).hexdigest()
def calculate_file_hash(path: Path) -> Optional[str]:
"""Calculates the SHA-256 hash of a file.
Args:
path: Path to the file.
Returns:
SHA-256 hex string, or None on read error.
"""
try:
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(8192), b""):
h.update(chunk)
return h.hexdigest()
except OSError:
# FileNotFoundError, PermissionError, IOError
return None
def decode_mail_header(header_val) -> str:
"""Decodes MIME-encoded email headers, handling multiple encodings.
Args:
header_val: Raw header value (str, bytes, or None).
Returns:
Decoded string, or str(header_val) on parsing error.
"""
if not header_val:
return ""
try:
decoded_list = email.header.decode_header(header_val)
result = ""
for text, encoding in decoded_list:
if isinstance(text, bytes):
result += text.decode(encoding or 'utf-8', errors='ignore')
else:
result += str(text)
return result.strip()
except (email.errors.HeaderParseError, LookupError, UnicodeDecodeError):
# Header-Parsing Fehler, unbekanntes Encoding, oder Unicode-Fehler
return str(header_val)
def break_long_urls(html_content: str) -> str:
"""Inserts zero-width spaces into long URLs for better line wrapping.
xhtml2pdf does not fully support word-break, so this workaround inserts
U+200B (zero-width space) after each /?&= and every 40 characters.
IMPORTANT: URLs in src/href attributes are NOT modified, because xhtml2pdf
cannot handle U+200B inside URLs and would fail to load images.
"""
def break_url(url: str) -> str:
# Nur URLs > 60 Zeichen bearbeiten
if len(url) < 60:
return url
# Zero-Width-Space nach Trennzeichen einfuegen
result = ""
char_count = 0
for char in url:
result += char
char_count += 1
# Nach bestimmten Zeichen umbrechen
if char in '/?&=':
result += '\u200b'
char_count = 0
# Alle 40 Zeichen umbrechen
elif char_count >= 40:
result += '\u200b'
char_count = 0
return result
# Nur URLs im sichtbaren Text umbrechen, NICHT in Attributen (src, href)
# Regex: URL die NICHT von =" oder =' vorangestellt wird
def replace_visible_urls(match):
prefix = match.group(1) or ""
url = match.group(2)
# Wenn Prefix ein Attribut-Zeichen ist, nicht modifizieren
if prefix in ('="', "='", '= "', "= '"):
return match.group(0)
return prefix + break_url(url)
# Suche URLs mit optionalem Prefix (um Attribute zu erkennen)
html_content = re.sub(
r'((?:=\s*["\'])?)(https?://[^\s<>"\']+)',
replace_visible_urls,
html_content
)
return html_content
def sanitize_html_for_pdf(html_content: str) -> str:
"""Removes all external resources from HTML for safe PDF conversion.
Removes:
- <img> tags (external images cause PermissionError in xhtml2pdf)
- <link> tags (external stylesheets)
- <style> tags completely (xhtml2pdf cannot handle modern CSS)
- <script> tags
- Zero-width spaces and control characters
"""
# Alle Control Characters entfernen (0x00-0x08, 0x0B, 0x0C, 0x0E-0x1F)
html_content = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f]', '', html_content)
# Zero-Width-Spaces entfernen (verursacht UnicodeEncodeError)
html_content = html_content.replace('\u200b', '')
html_content = html_content.replace('\u200c', '')
html_content = html_content.replace('\u200d', '')
html_content = html_content.replace('\ufeff', '')
# <style> Tags KOMPLETT entfernen (xhtml2pdf kann modernes CSS nicht parsen)
html_content = re.sub(r'<style[^>]*>.*?</style>', '', html_content, flags=re.IGNORECASE | re.DOTALL)
# <img> Tags entfernen (Hauptursache fuer PermissionError)
html_content = re.sub(r'<img[^>]*/?>', '', html_content, flags=re.IGNORECASE)
# <link> Tags entfernen (externe CSS)
html_content = re.sub(r'<link[^>]*/?>', '', html_content, flags=re.IGNORECASE)
# <script> Tags entfernen
html_content = re.sub(r'<script[^>]*>.*?</script>', '', html_content, flags=re.IGNORECASE | re.DOTALL)
# <meta> Tags mit problematischen Inhalten entfernen
html_content = re.sub(r'<meta[^>]*/?>', '', html_content, flags=re.IGNORECASE)
# Inline style-Attribute entfernen (koennen auch problematisch sein)
html_content = re.sub(r'\s+style\s*=\s*["\'][^"\']*["\']', '', html_content, flags=re.IGNORECASE)
# HTML-Kommentare entfernen (koennen Conditional Comments enthalten)
html_content = re.sub(r'<!--.*?-->', '', html_content, flags=re.DOTALL)
# Google Fonts und andere externe Font-Links entfernen
html_content = re.sub(r'https?://fonts\.googleapis\.com[^\s"\'<>]*', '', html_content)
html_content = re.sub(r'https?://fonts\.gstatic\.com[^\s"\'<>]*', '', html_content)
return html_content
def sanitize_html_for_pdf_full(html_content: str) -> str:
"""Prepares HTML for PDF conversion, but retains images (full mode).
Removes only dangerous elements:
- Control characters
- Scripts
- External stylesheets and fonts
Keeps:
- <img> tags (images are preserved)
- Inline styles (for layout)
"""
# Control Characters entfernen
html_content = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f]', '', html_content)
# Zero-Width-Spaces entfernen
html_content = html_content.replace('\u200b', '')
html_content = html_content.replace('\u200c', '')
html_content = html_content.replace('\u200d', '')
html_content = html_content.replace('\ufeff', '')
# <script> Tags entfernen (Sicherheit)
html_content = re.sub(r'<script[^>]*>.*?</script>', '', html_content, flags=re.IGNORECASE | re.DOTALL)
# <link> Tags entfernen (externe CSS - koennen Fehler verursachen)
html_content = re.sub(r'<link[^>]*/?>', '', html_content, flags=re.IGNORECASE)
# @font-face und @import aus Style-Bloecken entfernen
html_content = re.sub(r'@font-face\s*\{[^}]*\}', '', html_content, flags=re.IGNORECASE)
html_content = re.sub(r'@import[^;]*;', '', html_content, flags=re.IGNORECASE)
# Externe Bild-URLs neutralisieren (nur data: und cid: erlauben)
# Konvertiere externe URLs zu Platzhalter um PermissionError zu vermeiden
def replace_external_img(match):
tag = match.group(0)
# Behalte data: URLs (Base64 embedded) und cid: URLs (Content-ID)
if 'src="data:' in tag or "src='data:" in tag:
return tag
if 'src="cid:' in tag or "src='cid:" in tag:
return tag
# Externe URLs: src entfernen, aber Tag behalten (zeigt alt-Text)
return re.sub(r'\s+src\s*=\s*["\'][^"\']*["\']', '', tag)
html_content = re.sub(r'<img[^>]*>', replace_external_img, html_content, flags=re.IGNORECASE)
# HTML-Kommentare entfernen
html_content = re.sub(r'<!--.*?-->', '', html_content, flags=re.DOTALL)
# Google Fonts URLs entfernen
html_content = re.sub(r'https?://fonts\.googleapis\.com[^\s"\'<>]*', '', html_content)
html_content = re.sub(r'https?://fonts\.gstatic\.com[^\s"\'<>]*', '', html_content)
return html_content
class OCRProcessor:
"""Processes image-based PDFs using Tesseract OCR.
Uses pypdfium2 instead of pdf2image — no Poppler required.
"""
def __init__(self, log_func=None):
self.log = log_func or print
def _pdf_to_images(self, pdf_path: Path) -> List["Image.Image"]:
"""Converts PDF pages to PIL images using pypdfium2 (no Poppler needed)."""
images = []
try:
pdf = pdfium.PdfDocument(str(pdf_path))
for i in range(len(pdf)):
page = pdf[i]
# Scale 3 entspricht etwa 216 DPI (72 * 3), gut fuer OCR
bitmap = page.render(scale=3)
images.append(bitmap.to_pil())
pdf.close()
except Exception as e:
logger.debug(f"Fehler bei PDF->Bild Konvertierung: {e}")
return images
def has_text(self, pdf_path: Path) -> bool:
"""Returns True if the PDF already has a text layer (>50 characters)."""
if not OCR_AVAILABLE:
return True # Kein OCR verfuegbar, annehmen es hat Text
try:
reader = PdfReader(pdf_path)
text = ""
for page in reader.pages:
t = page.extract_text()
if t:
text += t
return len(text.strip()) > 50
except (OSError, ValueError, AttributeError):
# PDF-Read Fehler, korrupte Dateien, fehlende Attribute
return False
def add_text_layer(self, pdf_path: Path) -> Tuple[bool, str]:
"""Adds an OCR text layer to a PDF, replacing the original file.
WARNING: This method replaces the original file completely!
For browser-rendered PDFs, prefer enhance_with_ocr() instead.
Args:
pdf_path: Path to the PDF file to process.
Returns:
Tuple of (success: bool, message: str).
"""
if not OCR_AVAILABLE:
return False, "OCR nicht verfuegbar (pytesseract/pypdfium2 fehlt)"
try:
temp_path = pdf_path.with_suffix(".ocr_temp.pdf")
# PDF zu Bildern konvertieren (OHNE Poppler!)
images = self._pdf_to_images(pdf_path)
if not images:
return False, "Konnte keine Bilder aus PDF extrahieren"
writer = PdfWriter()
for img in images:
# Tesseract: Bild zu PDF mit Textlayer
pdf_bytes = pytesseract.image_to_pdf_or_hocr(
img, extension='pdf', lang='deu+eng'
)
reader = PdfReader(io.BytesIO(pdf_bytes))
writer.add_page(reader.pages[0])
# Schreibe neues PDF
with open(temp_path, "wb") as f:
writer.write(f)
# Ersetze Original
import shutil
shutil.move(str(temp_path), str(pdf_path))
return True, "OCR erfolgreich"
except Exception as e:
return False, str(e)
def enhance_with_ocr(self, pdf_path: Path) -> Tuple[bool, str]:
"""Runs OCR over all pages and appends the recognized text as a new page.
Advantages over add_text_layer():
- Original layout is preserved (important for browser-rendered PDFs!)
- OCR text is searchable
- Image-heavy emails (Temu, Amazon) become readable
- No Poppler required (uses pypdfium2)
Args:
pdf_path: Path to the PDF file to enhance.
Returns:
Tuple of (success: bool, message: str).
"""
if not OCR_AVAILABLE:
return False, "OCR nicht verfuegbar (pytesseract/pypdfium2 fehlt)"
try:
# PDF zu Bildern konvertieren (OHNE Poppler!)
images = self._pdf_to_images(pdf_path)
if not images:
return False, "Keine Seiten im PDF gefunden"
# OCR ueber alle Bilder ausfuehren
all_ocr_text = []
for i, img in enumerate(images):
try:
text = pytesseract.image_to_string(img, lang='deu+eng')
if text and text.strip():
all_ocr_text.append(f"--- Seite {i+1} ---\n{text.strip()}")
except Exception as e:
logger.debug(f"OCR Seite {i+1} fehlgeschlagen: {e}")
if not all_ocr_text:
return False, "Kein Text in Bildern erkannt"
# OCR-Text als neue PDF-Seite erstellen
ocr_content = "\n\n".join(all_ocr_text)
# HTML fuer OCR-Textseite
ocr_html = f"""<!DOCTYPE html>
<html><head><meta charset="utf-8">
<style>
@page {{ size: A4; margin: 2cm; }}
body {{ font-family: Arial, sans-serif; font-size: 10pt; line-height: 1.4; }}
h2 {{ color: #333; border-bottom: 1px solid #ccc; padding-bottom: 5px; }}
pre {{ white-space: pre-wrap; word-wrap: break-word; background: #f5f5f5;
padding: 10px; border-radius: 5px; font-size: 9pt; }}
</style>
</head>
<body>
<h2>OCR-Erkannter Text aus Bildern</h2>
<pre>{ocr_content}</pre>
</body></html>"""
# OCR-Seite als PDF erstellen
ocr_pdf_path = pdf_path.with_suffix(".ocr_page.pdf")
if XHTML2PDF_AVAILABLE:
with open(ocr_pdf_path, "wb") as f:
pisa.CreatePDF(ocr_html, dest=f, encoding='utf-8')
else:
return False, "xhtml2pdf nicht verfuegbar fuer OCR-Seite"
if not ocr_pdf_path.exists() or ocr_pdf_path.stat().st_size == 0:
return False, "OCR-Seite konnte nicht erstellt werden"
# Original-PDF und OCR-Seite zusammenfuegen
writer = PdfWriter()
# Original-Seiten hinzufuegen
original_reader = PdfReader(pdf_path)
for page in original_reader.pages:
writer.add_page(page)
# OCR-Seite(n) hinzufuegen
ocr_reader = PdfReader(ocr_pdf_path)
for page in ocr_reader.pages:
writer.add_page(page)
# Neues PDF schreiben
temp_path = pdf_path.with_suffix(".enhanced.pdf")
with open(temp_path, "wb") as f:
writer.write(f)
# Aufraeumen und ersetzen
ocr_pdf_path.unlink(missing_ok=True)
import shutil
shutil.move(str(temp_path), str(pdf_path))
return True, f"OCR hinzugefuegt ({len(all_ocr_text)} Seiten gescannt)"
except Exception as e:
# Aufraeumen bei Fehler
for suffix in [".ocr_page.pdf", ".enhanced.pdf"]:
tmp = pdf_path.with_suffix(suffix)
if tmp.exists():
tmp.unlink(missing_ok=True)
return False, str(e)
class BrowserPDFRenderer:
"""Renders HTML to PDF via browser (Edge/Chrome) using Chrome DevTools Protocol.
Advantages over xhtml2pdf:
- Native HTML/CSS rendering (including modern CSS, Flexbox, Grid)
- Images are loaded and rendered correctly
- No PermissionError with external resources
- Fonts are rendered correctly
"""
def __init__(self, log_func=None):
self.log = log_func or print
self.driver = None
self._initialized = False
def _ensure_driver(self) -> bool:
"""Starts the browser if not already running. Returns True on success."""
if self._initialized and self.driver:
try:
_ = self.driver.current_url
return True
except Exception:
self._initialized = False
self.driver = None
if not SELENIUM_AVAILABLE:
self.log("Browser-Modus nicht verfuegbar (Selenium fehlt)")
return False
# Versuche Edge zuerst, dann Chrome
for browser_type in ["edge", "chrome"]:
try:
if browser_type == "edge":
options = EdgeOptions()
options.add_argument("--headless=new")
options.add_argument("--disable-gpu")
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--window-size=1200,1600")
if WEBDRIVER_MANAGER_AVAILABLE:
try:
logging.getLogger('WDM').setLevel(logging.WARNING)
service = EdgeService(EdgeChromiumDriverManager().install())
self.driver = webdriver.Edge(service=service, options=options)
except (OSError, ValueError, ConnectionError):
# Driver-Download fehlgeschlagen, Fallback zu System-Driver
self.driver = webdriver.Edge(options=options)
else:
self.driver = webdriver.Edge(options=options)
else:
options = ChromeOptions()
options.add_argument("--headless=new")
options.add_argument("--disable-gpu")
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--window-size=1200,1600")
if WEBDRIVER_MANAGER_AVAILABLE:
try:
logging.getLogger('WDM').setLevel(logging.WARNING)
service = ChromeService(ChromeDriverManager().install())
self.driver = webdriver.Chrome(service=service, options=options)
except (OSError, ValueError, ConnectionError):
# Driver-Download fehlgeschlagen, Fallback zu System-Driver
self.driver = webdriver.Chrome(options=options)
else:
self.driver = webdriver.Chrome(options=options)
self._initialized = True
self.log(f"Browser gestartet ({browser_type.title()})")
return True
except Exception as e:
logger.debug(f"{browser_type} start failed: {e}")
continue
self.log("Kein Browser (Edge/Chrome) verfuegbar")
return False
def render_html_to_pdf(self, html_content: str, output_path: Path,
mail_meta: dict = None) -> bool:
"""Renders HTML to PDF via browser Chrome DevTools Protocol (CDP).
Args:
html_content: HTML content of the email.
output_path: Target PDF file path.
mail_meta: Optional dict with {sender, subject, date} for header.
Returns:
True on success, False on error.
"""
if not self._ensure_driver():
return False
try:
# HTML mit Header aufbereiten
if mail_meta:
header_html = f"""
<div style="background: #f5f5f5; border-bottom: 2px solid #333;
padding: 15px; margin-bottom: 20px; font-family: Arial, sans-serif;">
<table style="width: 100%; border-collapse: collapse;">
<tr>
<td style="padding: 5px;"><strong>Datum:</strong></td>
<td style="padding: 5px;">{mail_meta.get('date', '')}</td>
</tr>
<tr>
<td style="padding: 5px;"><strong>Von:</strong></td>
<td style="padding: 5px;">{mail_meta.get('sender', '')[:60]}</td>
</tr>
<tr>
<td style="padding: 5px;"><strong>Betreff:</strong></td>
<td style="padding: 5px;">{mail_meta.get('subject', '')[:80]}</td>
</tr>
</table>
</div>
"""
# Header einfuegen nach <body> falls vorhanden
if '<body' in html_content.lower():
html_content = re.sub(
r'(<body[^>]*>)',
r'\1' + header_html,
html_content,
flags=re.IGNORECASE
)
else:
html_content = f"<html><body>{header_html}{html_content}</body></html>"
# HTML als Data-URL laden (keine temp-Datei noetig)
html_b64 = base64.b64encode(html_content.encode('utf-8')).decode('ascii')
data_url = f"data:text/html;base64,{html_b64}"
self.driver.get(data_url)
time.sleep(0.5) # Kurz warten fuer Rendering
# PDF via Chrome DevTools Protocol erstellen
pdf_options = {
"printBackground": True,
"preferCSSPageSize": True,
"scale": 0.9,
"marginTop": 0.4,
"marginBottom": 0.4,
"marginLeft": 0.4,
"marginRight": 0.4,
"paperWidth": 8.27, # A4
"paperHeight": 11.69
}
result = self.driver.execute_cdp_cmd("Page.printToPDF", pdf_options)
pdf_data = base64.b64decode(result['data'])
# Pruefen ob PDF gueltig ist (min. 1KB)
if len(pdf_data) < 1024:
self.log("Browser-PDF zu klein, Fallback zu xhtml2pdf")
return False
# PDF speichern
output_path.parent.mkdir(parents=True, exist_ok=True)
with open(output_path, 'wb') as f:
f.write(pdf_data)
return True
except Exception as e:
logger.error(f"Browser PDF render failed: {e}")
return False
def close(self):
"""Closes the browser driver and resets internal state."""
if self.driver:
try:
self.driver.quit()
except Exception:
pass
self.driver = None
self._initialized = False
# Globale Instanz fuer Browser-Renderer (wird lazy initialisiert)
_browser_renderer: Optional[BrowserPDFRenderer] = None
def get_browser_renderer(log_func=None) -> BrowserPDFRenderer:
"""Returns the global BrowserPDFRenderer singleton, creating it if needed."""
global _browser_renderer
if _browser_renderer is None:
_browser_renderer = BrowserPDFRenderer(log_func)
return _browser_renderer
def html_to_pdf(html_content: str, output_path: Path,
mail_meta: dict = None, mode: str = "fast") -> bool:
"""Converts HTML content to a PDF file.
Args:
html_content: HTML string to convert.
output_path: Destination PDF file path.
mail_meta: Optional dict with {sender, subject, date} for a header block.
mode: Rendering mode — "fast" (text only), "full" (with images),
or "browser" (via headless Edge/Chrome).
Returns:
True on success, False on error.
"""
# Browser-Modus: Nutzt Edge/Chrome fuer natives HTML-Rendering
if mode == "browser":
if SELENIUM_AVAILABLE:
renderer = get_browser_renderer()
if renderer.render_html_to_pdf(html_content, output_path, mail_meta):
return True
# Fallback zu xhtml2pdf wenn Browser fehlschlaegt
logger.warning("Browser-Rendering fehlgeschlagen, Fallback zu xhtml2pdf")
mode = "full" # Fallback mit Bildern
else:
logger.warning("Selenium nicht installiert, Fallback zu xhtml2pdf")
mode = "full"
if not XHTML2PDF_AVAILABLE:
return False
try:
def link_callback(uri, rel):
"""Blockiert externe Ressourcen (nur im fast-Modus relevant)"""
if mode == "full":
# Im Full-Modus: data: und cid: URLs erlauben
if uri and (uri.startswith('data:') or uri.startswith('cid:')):
return uri
return None
# HTML bereinigen je nach Modus
if mode == "full":
html_content = sanitize_html_for_pdf_full(html_content)
else:
html_content = sanitize_html_for_pdf(html_content)
# Mail-Header Block wenn Metadaten vorhanden
header_html = ""
if mail_meta:
header_html = f"""
<table width="100%" cellpadding="0" cellspacing="0" style="background-color: #4a5568; margin-bottom: 20px;">
<tr><td style="padding: 15px; color: white; font-family: Arial, sans-serif;">
<div style="font-size: 9pt; color: #cbd5e0; margin-bottom: 5px;">
{mail_meta.get('date', '')}
</div>
<div style="font-size: 13pt; font-weight: bold; color: white; margin-bottom: 8px;">
{mail_meta.get('subject', 'Kein Betreff')}
</div>
<div style="font-size: 10pt; color: #e2e8f0;">
Von: {mail_meta.get('sender', 'Unbekannt')}
</div>
</td></tr>
</table>
"""