-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatements.py
More file actions
1620 lines (1404 loc) · 62.2 KB
/
Copy pathstatements.py
File metadata and controls
1620 lines (1404 loc) · 62.2 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 -*-
r"""
statement_import_cli.py — PDF-Kontoauszüge → CSV (Import + Review)
------------------------------------------------------------------
Pipeline:
[Extraktion] -> [Normalisierung] -> [Validierung] -> [Export]
Ausgabe:
- paypal_import.csv, paypal_review.csv
- haspa_import.csv, haspa_review.csv
CSV-Format (Semikolon):
Datum;Empfänger/Zahlungspflichtiger;Betrag in Euro;Verwendungszweck
Review-CSV enthält zusätzlich: ;Kommentar
"""
from __future__ import annotations
import argparse
import csv
import importlib
import os
import re
import subprocess
import sys
from dataclasses import dataclass, replace
from pathlib import Path
from typing import Iterable, List, Optional, Sequence, Tuple
# ---- Optionale Abhängigkeiten (PayPal-Tabellen via Camelot)
_CAMELOT_MODULE = None
_PYPDF_MODULE = None
_TRIED_PIP_PACKAGES: set[str] = set()
# --------------------- Dependency Helpers ---------------------
def install_python_package(package: str) -> bool:
if package in _TRIED_PIP_PACKAGES:
return False
_TRIED_PIP_PACKAGES.add(package)
try:
print(f"[INFO] Installiere fehlendes Paket '{package}' …", file=sys.stderr)
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
return True
except Exception as exc: # pragma: no cover - nur im Fehlerfall relevant
print(f"[WARN] Installation von '{package}' fehlgeschlagen: {exc}", file=sys.stderr)
return False
def ensure_module(name: str, pip_name: Optional[str], auto_install: bool):
try:
return importlib.import_module(name)
except ImportError:
if not auto_install:
return None
pkg = pip_name or name
if install_python_package(pkg):
try:
return importlib.import_module(name)
except ImportError as exc:
print(f"[WARN] Modul '{name}' trotz Installation nicht verfügbar: {exc}", file=sys.stderr)
return None
def check_system_dependency(cmd: str) -> bool:
"""Prüft, ob ein System-Kommando verfügbar ist."""
try:
subprocess.run([cmd, "--version"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=False)
return True
except FileNotFoundError:
return False
def detect_os() -> str:
"""Erkennt das Betriebssystem."""
if sys.platform == "darwin":
return "macos"
elif sys.platform.startswith("linux"):
# Versuche Distribution zu erkennen
if os.path.isfile("/etc/os-release"):
with open("/etc/os-release") as f:
content = f.read().lower()
if any(x in content for x in ["ubuntu", "debian", "mint", "pop"]):
return "debian"
elif any(x in content for x in ["fedora", "rhel", "centos", "rocky", "alma"]):
return "redhat"
elif any(x in content for x in ["arch", "manjaro", "endeavour"]):
return "arch"
return "linux-unknown"
else:
return "unknown"
def get_install_command(os_type: str, package: str) -> Optional[str]:
"""Gibt den passenden Installationsbefehl für ein System-Paket zurück."""
commands = {
"debian": f"sudo apt update && sudo apt install -y {package}",
"redhat": f"sudo dnf install -y {package}",
"arch": f"sudo pacman -S --noconfirm {package}",
"macos": f"brew install {package}",
}
return commands.get(os_type)
def check_and_install_system_dependencies(auto_install: bool = True) -> bool:
"""
Prüft System-Abhängigkeiten (pdftotext) und bietet Installation an.
Gibt True zurück wenn alle Dependencies verfügbar sind.
"""
# pdftotext ist essentiell für PDF-Verarbeitung
if check_system_dependency("pdftotext"):
return True
print("[WARN] 'pdftotext' nicht gefunden (Teil von poppler-utils)", file=sys.stderr)
if not auto_install:
print("[INFO] Bitte installiere poppler-utils manuell oder nutze ./install_dependencies.sh", file=sys.stderr)
return False
os_type = detect_os()
# Für macOS: Homebrew-Check
if os_type == "macos":
if not check_system_dependency("brew"):
print("[ERROR] Homebrew nicht gefunden. Bitte installiere erst Homebrew:", file=sys.stderr)
print(" /bin/bash -c \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\"", file=sys.stderr)
print("[INFO] Oder nutze: ./install_dependencies.sh", file=sys.stderr)
return False
# Installations-Hinweis
package_map = {
"debian": "poppler-utils",
"redhat": "poppler-utils",
"arch": "poppler",
"macos": "poppler",
}
package = package_map.get(os_type, "poppler-utils")
install_cmd = get_install_command(os_type, package)
if install_cmd:
print(f"[INFO] Empfohlene Installation für {os_type}:", file=sys.stderr)
print(f" {install_cmd}", file=sys.stderr)
print("[INFO] Oder nutze das automatische Setup-Skript:", file=sys.stderr)
print(" ./install_dependencies.sh", file=sys.stderr)
else:
print("[INFO] Bitte installiere poppler-utils für dein System", file=sys.stderr)
print("[INFO] Oder nutze: ./install_dependencies.sh", file=sys.stderr)
# Biete direkte Installation an (nur für nicht-interaktive Skripte sinnvoll)
if os_type in ["debian", "redhat", "arch", "macos"]:
print("[INFO] Automatische Installation wird versucht...", file=sys.stderr)
try:
if os_type == "macos":
subprocess.check_call(["brew", "install", "poppler"])
else:
# Für Linux: Nutzer muss sudo rechte haben
print("[WARN] Root-Rechte erforderlich. Bitte Installation manuell durchführen.", file=sys.stderr)
return False
# Erneut prüfen
if check_system_dependency("pdftotext"):
print("[OK] poppler-utils erfolgreich installiert", file=sys.stderr)
return True
except Exception as e:
print(f"[ERROR] Automatische Installation fehlgeschlagen: {e}", file=sys.stderr)
return False
# --------------------- Datenmodell ---------------------
@dataclass
class Tx:
"""
Transaktion mit OCR-Metadaten für bessere Nachvollziehbarkeit.
"""
datum: str
empfaenger: str
betrag: float
verwendungszweck: str
kommentar: str = ""
# Optionale Metadaten (für erweiterte CSV-Ausgabe)
confidence_datum: int = 100 # 0-100: Wie sicher ist das Datum?
confidence_betrag: int = 100 # 0-100: Wie sicher ist der Betrag?
confidence_empfaenger: int = 100 # 0-100: Wie sicher ist der Empfänger?
ocr_raw_date: str = "" # Original OCR-Datum (falls korrigiert)
ocr_raw_amount: str = "" # Original OCR-Betrag (falls korrigiert)
def key(self) -> Tuple[str, str, float, str]:
return (self.datum, self.empfaenger, self.betrag, self.verwendungszweck)
# --------------------- Regex/Utils ---------------------
_WS = re.compile(r"\s+")
_DATE_FULL = re.compile(r"(?<!\d)(\d{2})\.(\d{2})\.(\d{4})(?!\d)")
_DATE_DDMM = re.compile(r"(?<!\d)(\d{2})\.(\d{2})(?![\d.])")
_MONEY = re.compile(r"[-−–—]?\s*(?:\d{1,3}(?:\.\d{3})*|\d+),\d{2}-?")
_DATE_START = re.compile(r"^[\\'\"`~_%\-\s]*\d{2}[.,]\d{2}(?:[.,]\d{4})?")
_NUM_GAP1 = re.compile(r"(\d)\s+([.,])")
_NUM_GAP2 = re.compile(r"([.,])\s+(\d)")
# VERBESSERUNG: Auch Beträge mit nur 1 Dezimalstelle oder OCR-Müll akzeptieren
_AMOUNT_TOKEN = re.compile(r"[+−–—-]?\s*(?:\d{1,3}(?:[.\s]\d{3})*|\d+),\s*\d{1,2}(?:\s*[!;:=A-Z]+)?")
_AMOUNT_SKIP = re.compile(r"(übertra\w*|ubertra\w*|kontostand|saldo|abrechnung|auszug|anfangsbestand)", re.I)
_EMPFAENGER_SKIP = re.compile(
r"(wert:|iban|bic|konto|kontostand|übertrag|gläubiger-id|rn:|datum|tan|rechnung|ust-)",
re.I,
)
# === GENERISCHE BUCHUNGSTYP-ERKENNUNG ===
# Statt fixer Listen: Fuzzy-Pattern mit OCR-Toleranz
def _make_fuzzy_pattern(base: str) -> re.Pattern[str]:
"""Erstellt OCR-tolerantes Regex-Pattern (o→0, l→1, etc.)"""
# Häufige OCR-Verwechslungen
ocr_map = {"o": "[o0q]", "l": "[l1i]", "i": "[i1l]", "s": "[s5]"}
pattern = ""
for char in base.lower():
pattern += ocr_map.get(char, char)
return re.compile(pattern, re.I)
_HASPA_TYPE_PATTERNS: List[Tuple[re.Pattern[str], str]] = [
(_make_fuzzy_pattern("zahlungseingang"), "Zahlungseingang"),
(_make_fuzzy_pattern("lastschrift"), "Lastschrift"),
(_make_fuzzy_pattern("kartenzahlung"), "Kartenzahlung"),
(re.compile(r"überw[.\s]*(?:[o0q]n[l1i]ine)?banking", re.I), "Überw. OnlineBanking"),
(_make_fuzzy_pattern("überweisung"), "Überweisung"),
(_make_fuzzy_pattern("einzahlung"), "Einzahlung"),
(_make_fuzzy_pattern("auszahlung"), "Auszahlung"),
(_make_fuzzy_pattern("entgeltabrechnung"), "Entgeltabrechnung"),
(_make_fuzzy_pattern("gutschrift"), "Gutschrift"),
(re.compile(r"[l1i][o0q]hn.?/?.?gehalt", re.I), "Lohn/Gehalt"),
(_make_fuzzy_pattern("dauerauftrag"), "Dauerauftrag"),
]
_PAYPAL_TYPE_TOKENS = {
"paypal", "express", "zahlung", "allgemeine", "gemeine", "handyzahlung",
"bankgutschrift", "abbuchung", "rückbuchung", "rueckbuchung", "einbehaltung",
"einbehalt", "gutschrift", "transaktion"
}
_PAYPAL_STOPWORDS = {
"datum", "typ", "name", "e-mail-adresse", "transaktionscode", "brutto",
"gebühr", "netto", "zahlung", "gmbh", "kg", "ag", "digital", "services",
"technology", "payment", "gbr", "kg.", "ltd", "co.", "co", "llc", "de",
"emailadresse", "händlerkonto-id", "transaktionsübersicht"
}
_PAYPAL_COMMON_TLDS = {
"de", "com", "net", "org", "info", "io", "co", "uk", "co.uk", "fr", "es",
"it", "ch", "at", "nl", "be", "pl", "us", "ca"
}
def normalize_paypal_line(line: str) -> str:
if not line:
return ""
line = line.replace("\u00ad", "")
line = line.replace("–", "-").replace("—", "-")
line = line.replace("|", " ")
line = line.replace("°", " ")
# Entfernt nicht druckbare Zeichen (OCR-Artefakte)
line = re.sub(r"[^\x20-\x7E]", " ", line)
return norm_ws(line)
def sanitize_token(token: str) -> str:
if not token:
return ""
cleaned = re.sub(r"[.,;:<>\"'()\\[\\]{}]", "", token)
cleaned = cleaned.replace("/", "").replace("\\", "").replace("'", "").replace("`", "")
return cleaned.strip()
def sanitize_email(raw: str) -> str:
raw = raw.strip()
if not raw:
return ""
raw = raw.strip("<>[]()\"' ")
if "@" not in raw:
return ""
local, _, domain = raw.partition("@")
local = re.sub(r"[^A-Za-z0-9._%+-]", "", local)
domain = re.sub(r"[^A-Za-z0-9.-]", "", domain)
domain = domain.lstrip(".")
email = f"{local}@{domain}" if local and domain else ""
return email.lower()
def extract_paypal_email(tokens: List[str]) -> Tuple[str, int]:
def _domain_complete(dom: str) -> bool:
stripped = dom.strip(".-")
return bool(stripped) and "." in stripped
for idx, tok in enumerate(tokens):
if "@" not in tok:
continue
email = sanitize_email(tok)
if not email:
continue
local, _, domain = email.partition("@")
domain = domain.rstrip("-")
# VERBESSERUNG: Wenn Domain nur ein Buchstabe ist (z.B. "@g"), versuche nächsten Token
# Beispiel: "nataliya.ttusova@g mx.de" → sollte "gmx.de" werden
if len(domain) == 1 and idx + 1 < len(tokens):
next_tok = sanitize_token(tokens[idx + 1]).lower()
# Wenn nächster Token wie Domain-Teil aussieht (mx, mail, etc.)
if next_tok in {"mx", "mail", "web", "yahoo", "hotmail"} or next_tok.endswith(".de") or next_tok.endswith(".com"):
if domain in {"g", "m", "w", "y", "h"}:
# Kombiniere: "g" + "mx" → "gmx"
domain = domain + next_tok
idx_offset = 2
# Prüfe ob danach noch ".de" oder ".com" kommt
if idx + idx_offset < len(tokens):
next2 = sanitize_token(tokens[idx + idx_offset]).lower()
if next2 in {"de", "com", "net", "org"}:
domain = domain + "." + next2
email = f"{local}@{domain}"
return (sanitize_email(email), idx)
j = idx + 1
limit = min(len(tokens), idx + 12)
while not _domain_complete(domain) and j < limit:
cand = sanitize_token(tokens[j])
if not cand:
j += 1
continue
if "@" in cand:
break
if _TXID17.search(cand.replace(" ", "")):
j += 1
continue
if re.match(r"^-?\d+[.,]\d+$", cand):
j += 1
continue
lower = cand.lower()
lower_clean = lower.strip("-")
if lower_clean in _PAYPAL_TYPE_TOKENS or lower_clean in {"auf", "konto", "bankkonto", "bankgutschrift"}:
j += 1
continue
if lower_clean in {"gmbh", "kg", "ag"}:
j += 1
continue
if "." in cand:
fragment = cand
elif lower_clean in _PAYPAL_COMMON_TLDS:
fragment = "." + lower_clean if not lower_clean.startswith(".") else lower_clean
else:
j += 1
continue
if domain.endswith("-"):
domain = domain[:-1] + fragment
elif domain and fragment and not fragment.startswith(".") and not domain.endswith("."):
domain = f"{domain}.{fragment}"
else:
domain += fragment
if "." in fragment:
break
j += 1
domain = domain.replace("..", ".").strip(".-")
email = f"{local}@{domain}" if domain else email
return (sanitize_email(email), idx)
return ("", -1)
def extract_paypal_name(tokens: List[str], email_idx: int) -> str:
if email_idx < 0:
return ""
name_parts: List[str] = []
i = email_idx - 1
while i > 0 and len(name_parts) < 4:
cand = sanitize_token(tokens[i])
if not cand:
i -= 1
continue
if "@" in cand:
break
if re.match(r"^-?\d+[.,]\d+$", cand):
break
if _TXID17.search(cand.replace(" ", "")):
break
low_clean = cand.lower().strip("-")
if low_clean in _PAYPAL_TYPE_TOKENS or low_clean in _PAYPAL_STOPWORDS:
break
if any(ch.isdigit() for ch in cand):
break
name_parts.append(cand)
i -= 1
name_parts.reverse()
name = norm_ws(" ".join(name_parts))
return name
_TXID17 = re.compile(r"\b[A-Z0-9]{17}\b")
def norm_ws(s: str) -> str:
return _WS.sub(" ", (s or "").strip())
def clean_str(s: str) -> str:
# Entfernt weiche Trennstriche & normalisiert WS
return norm_ws(s).replace("\u00ad", "")
def to_float_de(num: str) -> float:
s = num.strip()
neg = s.endswith("-") or s.startswith(("-", "−", "–", "—"))
s = s.replace("-", "").replace("−", "").replace("–", "").replace("—", "")
try:
val = float(s.replace(".", "").replace(",", "."))
except ValueError:
return 0.0
return -val if neg else val
def parse_last_amount(text: str) -> Optional[float]:
"""Findet den letzten gültigen Betrag im Text, auch mit OCR-Müll."""
candidate = None
# Erst Standard-Regex (mit 2 Dezimalstellen)
for m in _MONEY.finditer(text):
token = m.group(0)
value = to_float_de(token)
if abs(value) > 1_000_000:
continue
candidate = token
# VERBESSERUNG: Wenn nichts gefunden, suche nach Beträgen mit OCR-Müll
# z.B. "26, !G =" sollte als "26,XX" interpretiert werden
if candidate is None:
# Suche nach Muster: Zahl + Komma + optionale Ziffer(n) + OCR-Müll
pattern = re.compile(r'(\d{1,6})\s*,\s*(\d{0,2})\s*[!;:=A-Z]+')
matches = list(pattern.finditer(text))
if matches:
m = matches[-1] # letzter Match
integer = m.group(1)
frac = m.group(2) if m.group(2) else "00"
# Wenn nur 1 Ziffer, zweite mit 0 auffüllen
if len(frac) == 1:
frac = frac + "0"
elif len(frac) == 0:
frac = "00"
candidate = f"{integer},{frac}"
return to_float_de(candidate) if candidate else None
def normalize_amount_line(line: str) -> str:
"""Schiebt Dezimaltrennzeichen dichter an die Ziffern (entfernt OCR-Zwischenräume)."""
s = line
for _ in range(3):
new = _NUM_GAP1.sub(r"\1\2", s)
new = _NUM_GAP2.sub(r"\1\2", new)
if new == s:
break
s = new
return s
def line_starts_with_date(line: str) -> bool:
stripped = line.lstrip(" '\\\"`~_%\t-–—")
if not stripped:
return False
probe = stripped.replace(",", ".", 2)
m = re.match(r"(\d{2})\.(\d{2})(?:\.(\d{2,4}))?", probe)
if not m:
return False
day = int(m.group(1))
month = int(m.group(2))
if not (1 <= day <= 31 and 1 <= month <= 12):
return False
return True
def eur(x: float) -> str:
return f"{x:.2f}".replace(".", ",")
def fix_date_ddmmyyyy(dd: str, mm: str, yyyy: str, clamp_to: Optional[int] = None) -> str:
"""
Intelligente OCR-Datumskorrektur mit Kontext-Validierung.
Statt fixer Regeln: Plausibilitätsprüfung gegen Kalender.
"""
day = int(dd)
month = int(mm)
year = int(yyyy)
# === STRATEGIE 1: Tag-Korrektur (OCR verwechselt oft 1↔4, 1↔7, 3↔8) ===
# Mapping häufiger OCR-Fehler bei Tagen
ocr_day_corrections = {
# 40er → 10er (4→1)
40: 10, 41: 11, 42: 12, 43: 13, 44: 14, 45: 15, 46: 16, 47: 17, 48: 18, 49: 19,
# 50er → 20er (5→2)
50: 20, 51: 21, 52: 22, 53: 23, 54: 24, 55: 25, 56: 26, 57: 27, 58: 28, 59: 29,
# 60er → 20er (6→2)
60: 20, 61: 21, 62: 22, 63: 23, 64: 24, 65: 25, 66: 26, 67: 27, 68: 28, 69: 29,
# 70er → 10er (7→1)
70: 10, 71: 11, 72: 12, 73: 13, 74: 14, 75: 15, 76: 16, 77: 17, 78: 18, 79: 19,
# 80er → 20er (8→2)
80: 20, 81: 21, 82: 22, 83: 23, 84: 24, 85: 25, 86: 26, 87: 27, 88: 28, 89: 29,
# 90er → 20er (9→2)
90: 20, 91: 21, 92: 22, 93: 23, 94: 24, 95: 25, 96: 26, 97: 27, 98: 28, 99: 29,
}
if day in ocr_day_corrections:
day = ocr_day_corrections[day]
elif day > 31:
# Generische Fallback-Logik
day = day % 31
if day == 0:
day = 1
# === STRATEGIE 2: Monat-Validierung ===
month = max(1, min(12, month))
# === STRATEGIE 3: Kalender-Validierung (Schaltjahre, Monatslängen) ===
# Max Tage pro Monat
days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
# Schaltjahr-Check
is_leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
if is_leap and month == 2:
max_day = 29
else:
max_day = days_in_month[month - 1]
# Tag auf gültigen Bereich begrenzen
day = min(day, max_day)
day = max(1, day)
# === STRATEGIE 4: Jahr-Clamping (gegen Ausreißer) ===
if clamp_to is not None and (year < clamp_to - 1 or year > clamp_to + 1):
year = clamp_to
return f"{day:02d}.{month:02d}.{year:04d}"
def fix_date_any(s: str, default_year: Optional[int]) -> Optional[str]:
m = _DATE_FULL.search(s)
if m:
return fix_date_ddmmyyyy(m.group(1), m.group(2), m.group(3), clamp_to=default_year)
m2 = _DATE_DDMM.search(s)
if m2 and default_year:
return fix_date_ddmmyyyy(m2.group(1), m2.group(2), str(default_year))
return None
def extract_date_from_block(block: Sequence[str], default_year: Optional[int]) -> str:
for candidate in block[:3]:
date = fix_date_any(candidate.replace(",", "."), default_year)
if date:
return date
joined = "\n".join(block)
return fix_date_any(joined.replace(",", "."), default_year) or ""
def parse_amount_token(token: str) -> Optional[float]:
raw = token.strip()
if not raw:
return None
neg = False
if raw.endswith(("-", "−", "–", "—")):
neg = True
raw = raw[:-1]
if raw.startswith(("−", "–", "—", "-")):
neg = True
raw = raw[1:]
raw = raw.lstrip("+")
raw = raw.replace(" ", "")
raw = raw.replace("’", "").replace("`", "")
filtered = re.sub(r"[^0-9,\.]", "", raw)
if not filtered:
return None
if filtered.count(",") > 1 and filtered.count(".") == 0:
return None
if "," in filtered:
parts = filtered.split(",")
if len(parts) > 2:
return None
elif "." in filtered:
parts = filtered.split(".")
if len(parts) > 2:
return None
else:
return None
if len(parts) < 2:
return None
integer_raw = "".join(parts[:-1]) or "0"
frac_raw = parts[-1]
integer_digits = re.sub(r"\D", "", integer_raw)
frac_digits = re.sub(r"\D", "", frac_raw)
if not frac_digits:
return None
# Wenn nur 1 Dezimalstelle, mit 0 auffüllen
if len(frac_digits) == 1:
frac_digits = frac_digits + "0"
elif len(frac_digits) > 2:
frac_digits = frac_digits[:2]
if not integer_digits:
integer_digits = "0"
if len(integer_digits) > 7:
return None
value = float(integer_digits + "." + frac_digits)
return -value if neg else value
def extract_amount_candidates(block: Sequence[str]) -> List[float]:
"""
Extrahiert ALLE Betrags-Kandidaten aus einem Block mit SCORING.
Gibt sortierte Liste zurück (beste zuerst).
"""
candidates: List[Tuple[float, int, int]] = [] # (betrag, score, position)
skip_following = 0
for line_idx, line in enumerate(block):
if _AMOUNT_SKIP.search(line):
skip_following = 2
continue
if skip_following:
skip_following -= 1
continue
norm_line = normalize_amount_line(line)
for token in _AMOUNT_TOKEN.findall(norm_line):
amount = parse_amount_token(token)
if amount is None:
continue
# === SCORING-SYSTEM ===
score = 100 # Basis-Score
# 1. Position: Letzte Zeilen bevorzugen (+30 für letzte 3 Zeilen)
if line_idx >= len(block) - 3:
score += 30
# 2. Plausibilität: Typische Betragsgrößen bevorzugen
abs_amount = abs(amount)
if 0.01 <= abs_amount <= 10000:
score += 20
elif abs_amount > 1_000_000:
score -= 50 # Sehr unwahrscheinlich
# 3. Format-Qualität: Mit 2 Dezimalstellen bevorzugen
if re.search(r',\d{2}(?:[^0-9]|$)', token):
score += 15
# 4. Kontext: Betrag am Ende der Zeile bevorzugen
if line.strip().endswith(token.strip()) or line.strip().endswith(token.strip() + "-"):
score += 10
# 5. Minuspunkte für OCR-Müll in der Nähe
if re.search(r'[!@#$%^&*]', token):
score -= 10
candidates.append((amount, score, line_idx))
# Sortiere nach Score (höchster zuerst)
candidates.sort(key=lambda x: x[1], reverse=True)
# Gebe nur die Beträge zurück (ohne Score)
return [amount for amount, score, pos in candidates]
def select_haspa_amount(block: Sequence[str]) -> Optional[float]:
"""Wählt den besten Betrags-Kandidaten mit Scoring-System."""
candidates = extract_amount_candidates(block)
if candidates:
return candidates[0] # Bester Kandidat
# Fallback: Alte Logik
joined = "\n".join(block)
amount = parse_last_amount(joined)
return amount
def should_skip_empfaenger_line(line: str) -> bool:
"""
Filtert Header/Footer/Tabellen-Müll aus OCR-Erkennung.
Best Practice: Tesseract hat Schwierigkeiten mit Tabellen-Layout.
→ Aggressive Filterung von technischen Zeilen, Timestamps, Codes.
"""
if not line:
return True
if _EMPFAENGER_SKIP.search(line):
return True
# Reine Zahlen/Zeichen-Zeilen (Tabellen-Separatoren)
if re.fullmatch(r"[\d\s,.\-+/:%]+", line):
return True
# OCR-Müll mit vielen gleichen Zeichen (z.B. "XXXML99XXX", "||||", "----")
if re.search(r"(X{3,}|[|]{3,}|[-]{5,}|[_]{5,})", line):
return True
# Timestamp-Zeilen (z.B. "2020-01-11718:07 Debitk.8 2022-12")
if re.search(r"\d{4}-\d{2}-\d{2}[T\d]", line):
return True
# ISO-Timestamps mit Uhrzeit
if re.search(r"\d{2}:\d{2}:\d{2}", line):
return True
# Technische Codes (z.B. "Debitk.8", "SEPA-ELV", "2022-12")
if re.search(r"(Debitk\.|SEPA-|Kreditk\.|BIC:|IBAN:|\d{4}-\d{2}$)", line):
return True
# Tabellen-Header (häufig in PayPal-PDFs)
if re.search(r"(Datum\s+Beschreibung|Name\s+Betrag|Transaktionscode)", line, re.IGNORECASE):
return True
# Seitenzahlen und Footer
if re.search(r"(Seite\s+\d+|Page\s+\d+|\d+\s+von\s+\d+)", line, re.IGNORECASE):
return True
# Zu wenig Buchstaben = wahrscheinlich kein Empfänger-Name
alpha = re.sub(r"[^A-Za-zÄÖÜäöüß]", "", line)
return len(alpha) < 2
def should_merge_name_line(line: str) -> bool:
if not line or should_skip_empfaenger_line(line):
return False
if re.search(r"\d", line):
return False
return len(line) <= 6
def format_name(name: str) -> str:
name = norm_ws(name)
name = re.sub(r"\s+,", ",", name)
name = re.sub(r"[ ,;/]+$", "", name)
# Unvollständige Namen bereinigen (z.B. "LUKU Roh" → wahrscheinlich abgeschnitten)
# Wenn Name zu kurz/kryptisch, als "Unbekannt" markieren
alpha_only = re.sub(r"[^A-Za-zÄÖÜäöüß]", "", name)
if len(alpha_only) < 3:
return "Unbekannt"
return name.strip()
def resolve_empfaenger(block: Sequence[str], start_idx: int) -> str:
for idx in range(start_idx, min(len(block), start_idx + 8)):
candidate = block[idx]
if should_skip_empfaenger_line(candidate):
continue
name = candidate
merge_idx = idx + 1
while merge_idx < len(block) and should_merge_name_line(block[merge_idx]):
name = f"{name} {block[merge_idx]}"
merge_idx += 1
return format_name(name)
return "Unbekannt"
def parse_date_for_sort(d: str) -> Tuple[int,int,int]:
m = _DATE_FULL.fullmatch(d.strip())
if not m:
return (0,0,0)
return (int(m.group(3)), int(m.group(2)), int(m.group(1)))
def sort_txs(rows: List[Tx]) -> List[Tx]:
return sorted(rows, key=lambda t: (parse_date_for_sort(t.datum), t.empfaenger, t.verwendungszweck, t.betrag))
def dedupe(rows: List[Tx]) -> List[Tx]:
seen = set()
out: List[Tx] = []
for tx in rows:
k = tx.key()
if k in seen:
continue
seen.add(k)
out.append(tx)
return out
def autofix_email_domain(email: str) -> str:
"""
GENERISCHE Email-Domain-Korrektur mit Pattern-Matching statt Hardcoding.
Erkennt häufige Provider automatisch und korrigiert OCR-Fehler.
"""
if not email or "@" not in email:
return email
local, dom = email.split("@", 1)
dom = dom.lower().replace(" ", "").replace("..", ".")
# === STRATEGIE 1: Bekannte Provider mit Levenshtein-ähnlicher Logik ===
# Definiere Kern-Provider-Namen (ohne TLD)
known_providers = {
"gmail": ["gmail", "gmai", "gmall", "gmalle", "g.mail", "gma.il", "gmaile"],
"gmx": ["gmx", "g.mx", "gmxde"],
"yahoo": ["yahoo", "yaho0", "ya.hoo", "yaoo", "yaahoo"],
"hotmail": ["hotmail", "hotm.ail", "hotmai"],
"web": ["web"],
"googlemail": ["googlemail", "googl.email"],
}
# Provider-TLD-Mapping
provider_tlds = {
"gmail": "com",
"googlemail": "com",
"yahoo": "com",
"hotmail": "com",
"gmx": "de",
"web": "de",
}
# Extrahiere Domain-Basis (ohne TLD)
domain_parts = dom.split(".")
domain_base = domain_parts[0] if domain_parts else dom
# Versuche Provider zu matchen
matched_provider = None
for provider, variants in known_providers.items():
for variant in variants:
# Exakter Match oder sehr ähnlich
if domain_base == variant or domain_base.replace(".", "") == variant.replace(".", ""):
matched_provider = provider
break
# Fuzzy-Match: mindestens 70% der Buchstaben stimmen überein
if len(variant) >= 3 and len(domain_base) >= 3:
common = sum(1 for a, b in zip(domain_base, variant) if a == b)
if common / max(len(domain_base), len(variant)) >= 0.7:
matched_provider = provider
break
if matched_provider:
break
if matched_provider:
tld = provider_tlds.get(matched_provider, "com")
dom = f"{matched_provider}.{tld}"
else:
# === STRATEGIE 2: OCR-Fehler-Patterns ===
# Häufige Einzelfehler korrigieren
dom = dom.replace(".dee", ".de").replace(".co", ".com")
dom = dom.replace("media-saturn.com", "mediasaturn.com")
# Wenn Domain nur Einzelbuchstabe: Rate häufigsten Provider
if len(dom) == 1:
provider_guess = {"g": "gmail.com", "m": "gmx.de", "y": "yahoo.com",
"h": "hotmail.com", "w": "web.de"}.get(dom)
if provider_guess:
dom = provider_guess
# Wenn keine TLD vorhanden und bekannter Name: Ergänze .com/.de
if "." not in dom:
if dom in {"gmail", "yahoo", "hotmail", "googlemail"}:
dom = f"{dom}.com"
elif dom in {"gmx", "web"}:
dom = f"{dom}.de"
return f"{local}@{dom}"
def shutil_which(name: str) -> Optional[str]:
for p in os.environ.get("PATH", "").split(os.pathsep):
cand = Path(p) / name
if cand.exists() and os.access(cand, os.X_OK):
return str(cand)
return None
# --------------------- CSV Writer ----------------------
def write_csv(rows: Sequence[Tx], out_path: Path, encoding: str, review: bool, extended: bool = False):
"""
CSV-Export mit optionalen erweiterten Metadaten.
Args:
rows: Transaktionen
out_path: Ausgabepfad
encoding: Zeichensatz
review: Review-CSV (mit Kommentar-Spalte)?
extended: Erweiterte Metadaten ausgeben? (Confidence-Scores, OCR-Rohdaten)
"""
out_path.parent.mkdir(parents=True, exist_ok=True)
headers = ["Datum", "Empfänger/Zahlungspflichtiger", "Betrag in Euro", "Verwendungszweck"]
if review:
headers += ["Kommentar"]
if extended:
headers += ["Confidence Datum", "Confidence Betrag", "Confidence Empfänger",
"OCR Raw Datum", "OCR Raw Betrag"]
with open(out_path, "w", encoding=encoding, newline="") as f:
w = csv.writer(f, delimiter=";")
w.writerow(headers)
for tx in rows:
base = [tx.datum, tx.empfaenger, eur(tx.betrag), tx.verwendungszweck]
if review:
base.append(tx.kommentar)
if extended:
base.extend([
str(tx.confidence_datum),
str(tx.confidence_betrag),
str(tx.confidence_empfaenger),
tx.ocr_raw_date or "",
tx.ocr_raw_amount or ""
])
w.writerow(base)
# --------------------- Common Validation ----------------------
def calculate_ocr_quality_score(text: str) -> int:
"""
Bewertet die OCR-Qualität eines Textes (0-100).
Basierend auf Tesseract Best Practices: Weniger OCR-Artefakte = höhere Qualität.
Indikatoren für schlechte OCR-Qualität:
- Viele Sonderzeichen (!?@#$%^&*~)
- Viele einzelne Großbuchstaben (z.B. "D E U T S C H E B A N K")
- Wiederholte gleiche Zeichen (|||, ---, XXX)
- Ungewöhnlich viele Zahlen-Buchstaben-Mischungen (O→0, I→1 Fehler)
"""
if not text:
return 0
score = 100
length = len(text)
# Sonderzeichen-Anteil (OCR-Müll wie !?@#$%^&*)
special_chars = len(re.findall(r"[!?@#$%^&*~°|]", text))
if length > 0:
special_ratio = special_chars / length
score -= int(special_ratio * 100) # Max -100
# Einzelne Großbuchstaben mit Leerzeichen (typisch für schlechte OCR)
single_caps = len(re.findall(r"\b[A-Z]\b", text))
if single_caps > 3:
score -= min(20, single_caps * 2)
# Wiederholte Zeichen (|||, ---, XXX, etc.)
repeated_chars = len(re.findall(r"(.)\1{2,}", text))
score -= min(15, repeated_chars * 5)
# Zahlen-Buchstaben-Chaos (z.B. "0CT0BER" statt "OCTOBER")
num_letter_mix = len(re.findall(r"\d[A-Za-z]|[A-Za-z]\d", text))
if num_letter_mix > 2:
score -= min(10, num_letter_mix * 2)
return max(0, min(100, score))
def needs_review_common(tx: Tx) -> List[str]:
"""
Gemeinsame Validierung mit adaptiver Confidence-Score-Berechnung.
Aktualisiert automatisch die Confidence-Werte basierend auf:
- OCR-Korrekturen (fix_date, autofix_email, etc.)
- Datenqualität (Vollständigkeit, Format)
- OCR-Qualitätsindikatoren (Sonderzeichen, Müll)
"""
reasons: List[str] = []
# === Datum-Validierung mit Confidence ===
if not _DATE_FULL.fullmatch(tx.datum.strip()):
reasons.append("Datum unvollständig/fehlerhaft")
tx.confidence_datum = 0
elif tx.ocr_raw_date and tx.ocr_raw_date != tx.datum:
# Datum wurde korrigiert → moderate Confidence
tx.confidence_datum = 70
else:
# Datum sieht gut aus
tx.confidence_datum = 100
# === Betrag-Validierung mit Confidence ===
if abs(tx.betrag) < 0.005:
reasons.append("Betrag nicht erkannt/0,00")
tx.confidence_betrag = 0
elif tx.ocr_raw_amount:
# OCR-Müll gefiltert → gute Confidence
tx.confidence_betrag = 80
else:
# Betrag sauber erkannt
tx.confidence_betrag = 100
# === Empfänger-Validierung mit adaptiver Confidence ===
if not tx.empfaenger or tx.empfaenger.strip().lower() in {"", "unbekannt"}:
reasons.append("Empfänger unklar")
tx.confidence_empfaenger = 0
elif len(tx.empfaenger) < 5:
# Sehr kurzer Name → niedrige Confidence
tx.confidence_empfaenger = 50
else:
# Bewerte OCR-Qualität des Empfänger-Namens
ocr_quality = calculate_ocr_quality_score(tx.empfaenger)
tx.confidence_empfaenger = ocr_quality
# Wenn OCR-Qualität schlecht (<60), zur Review markieren
if ocr_quality < 60:
reasons.append(f"Empfänger enthält OCR-Artefakte (Qualität: {ocr_quality}%)")
# Verwendungszweck-Validierung
if not tx.verwendungszweck or len(tx.verwendungszweck.strip()) < 3:
reasons.append("Verwendungszweck unklar")
return reasons
# --------------------- PDF Reader Helpers ---------------------
def get_pypdf(auto_install: bool):
global _PYPDF_MODULE
if _PYPDF_MODULE is not None:
return _PYPDF_MODULE
_PYPDF_MODULE = ensure_module("PyPDF2", "PyPDF2", auto_install)
return _PYPDF_MODULE
def extract_with_pypdf(pdf: Path, auto_install: bool) -> Optional[str]:
mod = get_pypdf(auto_install)
if mod is None: