-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinvoice.py
More file actions
1712 lines (1450 loc) · 75.7 KB
/
invoice.py
File metadata and controls
1712 lines (1450 loc) · 75.7 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
import os
import sys
import subprocess
import glob
import re
import shutil
import logging
import argparse
from typing import Dict, List, Optional, Tuple, Any, Set
import json
import platform
from datetime import datetime
import yaml
import tkinter as tk
from tkinter import messagebox
import socket
import time
# Now import the installed packages
try:
import pytesseract
import pdf2image
import PyPDF2
import requests
import numpy as np
from PIL import Image, ImageChops
from skimage.metrics import structural_similarity as ssim
except ImportError as e:
print(f"Error importing required libraries: {e}")
print("Please make sure all required libraries are installed.")
sys.exit(1)
# Path setup for EXE bundle
APP_DIR = os.path.dirname(os.path.abspath(__file__))
# Check if we're running as an executable or as a Python script
if hasattr(sys, 'frozen'):
# Running as executable
base_dir = APP_DIR
else:
# Running as script
base_dir = os.getcwd()
# Find poppler and tesseract
LOCAL_TESS = os.path.join(APP_DIR, "tesseract", "tesseract.exe")
LOCAL_TESSDATA = os.path.join(APP_DIR, "tesseract", "tessdata")
# Default Poppler location
POPPLER_BIN = os.path.join(APP_DIR, "resources", "poppler", "bin")
# Check if resources are in the current working directory instead
if not os.path.exists(POPPLER_BIN):
alt_poppler_bin = os.path.join(base_dir, "resources", "poppler", "bin")
if os.path.exists(alt_poppler_bin):
POPPLER_BIN = alt_poppler_bin
if os.path.exists(LOCAL_TESS):
pytesseract.pytesseract.tesseract_cmd = LOCAL_TESS
os.environ.setdefault("TESSDATA_PREFIX", LOCAL_TESSDATA)
# ======================================================================
# CONFIGURATION
# ======================================================================
# Default configuration if config.yaml is not found
DEFAULT_CONFIG = {
"global": {
"openai_key": "youropenaiapikey",
"model": "gpt-4.1-mini",
"threshold": 0.5,
"aggressive_split": False,
"processing_mode": "BUNDLE",
"blank_page_threshold": 0.90,
"directories": {
"complete": "Rechnungen",
"incomplete": "Rechnungen-Unsicher",
"backup": "Backup",
"temp": "temp_invoices"
},
"error_handling": {
"show_popup": True,
"keep_files_on_error": True
}
},
"company_names": [
"Vattenfall Europe Sales GmbH",
"VHV Versicherung",
"VHV Allgemeine Versicherung AG",
"Telekom Deutschland GmbH",
"Deutsche Telekom AG",
"SECURITAS Alert Services GmbH",
"DB Fernverkehr AG",
"Deutsche Lufthansa AG",
"reuter europe GmbH"
],
"similarity_weights": {
"header_similarity": 0.2,
"footer_similarity": 0.1,
"margin_similarity": 0.1,
"logo_similarity": 0.3,
"text_similarity": 0.3,
"page_number_match": 0.2,
"company_name_match": 0.4
},
"folders": []
}
# Global configuration variable
CONFIG = {}
def load_config():
"""Load configuration from config.yaml or create default if not exists"""
global CONFIG
config_path = os.path.join(os.getcwd(), "config.yaml")
# Check if config file exists
if os.path.exists(config_path):
try:
with open(config_path, 'r', encoding='utf-8') as f:
CONFIG = yaml.safe_load(f)
logger.info(f"Configuration loaded from {config_path}")
except Exception as e:
logger.error(f"Error loading configuration from {config_path}: {e}")
logger.info("Using default configuration")
CONFIG = DEFAULT_CONFIG
else:
# Create default config file
logger.info(f"Configuration file not found. Creating default at {config_path}")
CONFIG = DEFAULT_CONFIG
try:
with open(config_path, 'w', encoding='utf-8') as f:
yaml.dump(CONFIG, f, default_flow_style=False, sort_keys=False)
except Exception as e:
logger.error(f"Error creating default configuration file: {e}")
# Load similarity weights and other settings from config
SIM_WEIGHTS = {}
BLANK_PAGE_THRESHOLD = 0.95
AGGRESSIVE_SPLIT = False
def show_error_popup(title, message):
"""Display an error popup if enabled in configuration"""
if CONFIG.get("global", {}).get("error_handling", {}).get("show_popup", True):
try:
# Create a root window but hide it
root = tk.Tk()
root.withdraw()
# Show the error message
messagebox.showerror(title, message)
# Destroy the root window
root.destroy()
except Exception as e:
logger.error(f"Failed to show error popup: {e}")
def check_internet_connection():
"""Check if there is an internet connection available"""
try:
# Try to connect to OpenAI's API
socket.create_connection(("api.openai.com", 443), timeout=5)
return True
except OSError:
return False
# Get company names from configuration
def get_company_names():
"""Get the list of company names from configuration"""
return CONFIG.get("company_names", [])
# Get similarity threshold from configuration
def get_similarity_threshold():
"""Get the similarity threshold from configuration"""
return CONFIG.get("global", {}).get("threshold", 0.5)
# Get processing mode from configuration
def get_processing_mode():
"""Get the processing mode from configuration"""
return CONFIG.get("global", {}).get("processing_mode", "BUNDLE")
# Get blank page threshold from configuration
def get_blank_page_threshold():
"""Get the blank page detection threshold from configuration"""
return CONFIG.get("global", {}).get("blank_page_threshold", 0.95)
# Get similarity weights from configuration
def get_similarity_weights():
"""Get the similarity weights from configuration"""
return CONFIG.get("similarity_weights", {
"header_similarity": 0.2,
"footer_similarity": 0.1,
"margin_similarity": 0.1,
"logo_similarity": 0.3,
"text_similarity": 0.3,
"page_number_match": 0.2,
"company_name_match": 0.4
})
# Get directory paths from configuration
def get_directory_path(directory_type):
"""Get the path for a specific directory type from configuration"""
directories = CONFIG.get("global", {}).get("directories", {})
default_dirs = {
"complete": "Rechnungen",
"incomplete": "Rechnungen-Unsicher",
"backup": "Backup",
"temp": "temp_invoices"
}
return directories.get(directory_type, default_dirs.get(directory_type, ""))
# Function to check and install required packages
def install_required_packages():
required_packages = ['pytesseract', 'pdf2image', 'PyPDF2', 'requests', 'pillow', 'scikit-image', 'numpy', 'openai']
installed_packages = []
try:
# Get list of installed packages
reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze'])
installed_packages = [r.decode().split('==')[0].lower() for r in reqs.split()]
except Exception as e:
print(f"Warning: Could not check installed packages: {e}")
# Install missing packages
for package in required_packages:
if package.lower() not in installed_packages:
try:
logger.info(f"Installing missing package: {package}")
subprocess.check_call([sys.executable, '-m', 'pip', 'install', package])
except Exception as e:
logger.error(f"Failed to install {package}: {e}")
logger.info("Required packages check completed.")
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(),
logging.FileHandler('invoice_extractor.log')
]
)
logger = logging.getLogger(__name__)
# Load configuration first
load_config()
# Initialize global variables from config
SIM_WEIGHTS = CONFIG.get("similarity_weights", DEFAULT_CONFIG["similarity_weights"])
BLANK_PAGE_THRESHOLD = CONFIG["global"].get("blank_page_threshold", 0.90)
AGGRESSIVE_SPLIT = CONFIG["global"].get("aggressive_split", False)
os.environ.setdefault("AGGRESSIVE_INVOICE_SPLIT", str(AGGRESSIVE_SPLIT).lower())
# Install required packages
install_required_packages()
# On macOS, use system binaries if available for Poppler
if platform.system() == "Darwin": # macOS
# Check if poppler is installed via homebrew
if os.path.exists("/opt/homebrew/bin/pdftoppm"):
POPPLER_BIN = "/opt/homebrew/bin"
logger.info(f"Using macOS Homebrew Poppler binaries from: {POPPLER_BIN}")
elif os.path.exists("/usr/local/bin/pdftoppm"):
POPPLER_BIN = "/usr/local/bin"
logger.info(f"Using macOS Poppler binaries from: {POPPLER_BIN}")
# Set tesseract path based on operating system
def setup_tesseract():
"""Configure Tesseract OCR based on the operating system"""
system = platform.system()
# Log paths for debugging
logger.info(f"POPPLER_BIN path: {POPPLER_BIN}")
logger.info(f"POPPLER_BIN exists: {os.path.exists(POPPLER_BIN)}")
if os.path.exists(POPPLER_BIN):
try:
poppler_contents = os.listdir(POPPLER_BIN)
logger.info(f"Contents of POPPLER_BIN: {poppler_contents}")
# Check for pdftoppm executable
if platform.system() == "Darwin":
if "pdftoppm" in poppler_contents:
logger.info(f"Found pdftoppm in POPPLER_BIN")
else:
logger.warning(f"pdftoppm not found in POPPLER_BIN. PDF processing may fail.")
else:
if "pdftoppm.exe" in poppler_contents:
logger.info(f"Found pdftoppm.exe in POPPLER_BIN")
else:
logger.warning(f"pdftoppm.exe not found in POPPLER_BIN. PDF processing may fail.")
except Exception as e:
logger.warning(f"Could not list Poppler directory contents: {e}")
if system == "Windows":
# Common installation paths on Windows
windows_paths = [
r'C:\Program Files\Tesseract-OCR\tesseract.exe',
r'C:\Program Files (x86)\Tesseract-OCR\tesseract.exe',
r'C:\Tesseract-OCR\tesseract.exe',
# Add the Tesseract path if installed via Windows package managers
os.path.join(os.environ.get('LOCALAPPDATA', ''), r'Programs\Tesseract-OCR\tesseract.exe'),
os.path.join(os.environ.get('PROGRAMFILES', ''), r'Tesseract-OCR\tesseract.exe'),
os.path.join(os.environ.get('PROGRAMFILES(X86)', ''), r'Tesseract-OCR\tesseract.exe')
]
for path in windows_paths:
if os.path.exists(path):
logger.info(f"Found Tesseract at: {path}")
pytesseract.pytesseract.tesseract_cmd = path
return True
# Check if tesseract is in PATH
try:
pytesseract.get_tesseract_version()
logger.info("Tesseract found in system PATH")
return True
except pytesseract.TesseractNotFoundError:
logger.error("Tesseract OCR not found on Windows system")
logger.error("Please install Tesseract from: https://github.com/UB-Mannheim/tesseract/wiki")
logger.error("Install to the default location: C:\\Program Files\\Tesseract-OCR\\")
logger.error("Or add the Tesseract installation directory to your system PATH")
logger.error("After installation, restart this script")
# Create a more user-friendly error message for Windows users
print("\n" + "="*60)
print("ERROR: Tesseract OCR not found on your Windows system")
print("="*60)
print("\nTo fix this:")
print("1. Download and install Tesseract from: https://github.com/UB-Mannheim/tesseract/wiki")
print("2. Make sure to CHECK the 'Add to PATH' option during installation")
print("3. Install to the default location: C:\\Program Files\\Tesseract-OCR\\")
print("4. Restart your computer after installation")
print("5. Run this script again\n")
return False
elif system == "Darwin": # macOS
# Try to set the path to tesseract on macOS with Homebrew
mac_paths = [
'/opt/homebrew/bin/tesseract',
'/usr/local/bin/tesseract'
]
for path in mac_paths:
if os.path.exists(path):
logger.info(f"Found Tesseract at: {path}")
pytesseract.pytesseract.tesseract_cmd = path
return True
# Check if tesseract is in PATH
try:
pytesseract.get_tesseract_version()
logger.info("Tesseract found in system PATH")
return True
except pytesseract.TesseractNotFoundError:
logger.error("Tesseract OCR not found on macOS")
logger.error("Install it with: brew install tesseract")
return False
else: # Linux and other systems
try:
pytesseract.get_tesseract_version()
logger.info("Tesseract found in system PATH")
return True
except pytesseract.TesseractNotFoundError:
logger.error("Tesseract OCR not found on your system")
logger.error("On Linux, install with: sudo apt-get install tesseract-ocr")
return False
# Try to setup Tesseract
if not setup_tesseract():
print("Failed to configure Tesseract OCR. Exiting.")
sys.exit(1)
def extract_text_from_image_array(image: Image.Image) -> str:
"""Extract text from a PIL Image object using OCR."""
try:
text = pytesseract.image_to_string(image, lang='deu')
return text
except Exception as e:
logger.error(f"Error extracting text from image: {e}")
return ""
def extract_text_from_image(image_path: str) -> str:
"""Extract text from an image file using OCR."""
try:
image = Image.open(image_path)
text = pytesseract.image_to_string(image, lang='deu')
return text
except Exception as e:
logger.error(f"Error extracting text from image {image_path}: {e}")
return ""
def extract_text_from_pdf(pdf_path: str) -> str:
"""Extract text from a PDF file using OCR."""
try:
# First try to extract text directly (if the PDF has text layers)
with open(pdf_path, 'rb') as file:
reader = PyPDF2.PdfReader(file)
text = ""
for page_num in range(len(reader.pages)):
text += reader.pages[page_num].extract_text() or ""
# If we got meaningful text, return it
if text.strip() and len(text) > 100: # Arbitrary threshold to determine if text extraction worked
return text
# If direct extraction didn't yield good results, use OCR
logger.info(f"Using OCR for PDF: {pdf_path}")
all_text = ""
# Add debugging information about Poppler path
if not os.path.exists(POPPLER_BIN):
logger.warning(f"Poppler directory not found at: {POPPLER_BIN}")
else:
logger.info(f"Using Poppler from: {POPPLER_BIN}")
# Remove poppler scripts output
# try:
# contents = os.listdir(POPPLER_BIN)
# logger.info(f"Contents of Poppler directory: {contents}")
# except Exception as e:
# logger.warning(f"Could not list Poppler directory contents: {e}")
# Convert PDF to images
images = pdf2image.convert_from_path(pdf_path, poppler_path=POPPLER_BIN)
# Process each page
for i, image in enumerate(images):
# Extract text directly from the image object without saving temporarily
page_text = extract_text_from_image_array(image)
all_text += f"\n\n--- Page {i+1} ---\n\n" + page_text
return all_text
except Exception as e:
logger.error(f"Error extracting text from PDF {pdf_path}: {e}")
return ""
def query_llm(text: str) -> Dict[str, Any]:
"""
Query OpenAI to extract invoice information.
"""
# Check internet connectivity before making API call
if not check_internet_connection():
error_msg = "No internet connection available. Cannot process invoice."
logger.error(error_msg)
show_error_popup("Connection Error", error_msg)
return {"error": error_msg, "no_internet": True}
# Get company names from configuration
company_names = get_company_names()
company_names_str = ", ".join(company_names)
# Prepare the prompt for OpenAI
prompt = f"""
Extract the following information from this invoice text:
- Invoice date (Rechnungsdatum)
- Invoice number (Rechnungsnummer)
- Company name (Firmenname)
- Invoice amount (Rechnungsbetrag)
Return only the extracted information in JSON format:
{{
"invoice_date": "extracted date",
"invoice_number": "extracted number",
"company_name": "extracted company name",
"invoice_amount": "extracted amount"
}}
Important Information:
The company name will never be Bodenkontor Liegenschaften GmbH or similar. Use the other company you have found in the invoice.
Here are the most likely company names that should appear on the invoice:
{company_names_str}
If you find one of these names in the invoice, please use it. If not, extract the most likely company name from the invoice.
Here is the invoice text:
{text}
"""
# Call the OpenAI API
return query_openai(prompt)
def query_openai(prompt: str) -> Dict[str, Any]:
"""Use OpenAI API to extract invoice information from invoice text."""
try:
# Get OpenAI API key from config, environment, or hardcoded key
openai_api_key = CONFIG.get("global", {}).get("openai_key", "")
if not openai_api_key:
openai_api_key = os.environ.get('OPENAI_API_KEY', OPENAI_API_KEY)
if not openai_api_key:
error_msg = "No OpenAI API key found in config, environment, or script"
logger.error(error_msg)
show_error_popup("API Key Error", error_msg)
return {"error": error_msg}
# Basic validation of API key format
if not (openai_api_key.startswith('sk-') and len(openai_api_key) > 20):
error_msg = "Invalid OpenAI API key format. API keys should start with 'sk-' and be at least 20 characters."
logger.error(error_msg)
show_error_popup("API Key Error", error_msg)
return {"error": error_msg}
# Import the openai module
try:
import openai
# Set the API key
openai.api_key = openai_api_key
client = openai.OpenAI(api_key=openai_api_key)
except ImportError:
return {"error": "Failed to import openai module. Please make sure it's installed with 'pip install openai'."}
# Get model from config
model = CONFIG.get("global", {}).get("model", "gpt-4.1-mini")
logger.info(f"Sending invoice text to OpenAI API ({model})...")
try:
response = client.chat.completions.create(
model=model, # Use the model from config
messages=[
{"role": "system", "content": "You are a helpful assistant that extracts information from invoices."},
{"role": "user", "content": prompt}
],
temperature=0.1 # Low temperature for more deterministic results
)
# Extract content from OpenAI response
if hasattr(response, 'choices') and len(response.choices) > 0:
llm_response = response.choices[0].message.content
# Add detailed logging of the raw response
logger.info(f"Raw OpenAI response: {llm_response}")
# Try to parse JSON from the response
try:
# Find the start and end of JSON in the response
start_idx = llm_response.find('{')
end_idx = llm_response.rfind('}') + 1
if start_idx >= 0 and end_idx > start_idx:
json_str = llm_response[start_idx:end_idx]
logger.info(f"Extracted JSON string: {json_str}")
try:
result = json.loads(json_str)
return result
except json.JSONDecodeError as e:
logger.error(f"JSON parsing error: {e}")
return {"error": f"Failed to parse JSON from OpenAI response: {e}", "raw_response": llm_response}
else:
logger.error(f"No JSON found in response: {llm_response}")
return {"error": "Could not find JSON in OpenAI response", "raw_response": llm_response}
except Exception as e:
logger.error(f"Error processing OpenAI response: {e}")
return {"error": f"Error processing OpenAI response: {e}", "raw_response": llm_response}
else:
logger.error(f"Unexpected response format: {response}")
return {"error": "Unexpected response format from OpenAI", "raw_response": str(response)}
except openai.BadRequestError as e:
return {"error": f"OpenAI API Bad Request Error: {str(e)}"}
except openai.AuthenticationError as e:
return {"error": f"OpenAI API Authentication Error: {str(e)}"}
except openai.RateLimitError as e:
return {"error": f"OpenAI API Rate Limit Error: {str(e)}"}
except openai.APIError as e:
return {"error": f"OpenAI API Error: {str(e)}"}
except Exception as e:
logger.error(f"Unexpected error setting up OpenAI request: {str(e)}")
return {"error": f"Unexpected error setting up OpenAI request: {str(e)}"}
def is_blank_page(image, threshold=None, debug=False):
"""
Determine if an image is blank/white using multiple detection methods.
Args:
image: PIL Image object
threshold: Brightness threshold (0-1), higher values mean stricter blank detection
If None, uses the value from config
debug: If True, saves the image with debug information
Returns:
bool: True if the page is blank, False otherwise
"""
# Use global threshold from config if none specified
if threshold is None:
threshold = BLANK_PAGE_THRESHOLD
# Convert to grayscale
gray_img = image.convert('L')
# Calculate the average brightness (0-255)
hist = gray_img.histogram()
total_pixels = sum(hist)
if total_pixels == 0:
logger.debug("Empty image (no pixels)")
return True
# Calculate weighted brightness average
brightness_sum = sum(i * pixel_count for i, pixel_count in enumerate(hist))
average_brightness = brightness_sum / total_pixels
# Normalize to 0-1 range
normalized_brightness = average_brightness / 255.0
# Check if the image has very low contrast (another indicator of blank page)
dark_pixels = sum(hist[:50]) # Count very dark pixels
dark_pixel_percentage = dark_pixels / total_pixels
bright_pixels = sum(hist[200:]) # Count very bright pixels
bright_pixel_percentage = bright_pixels / total_pixels
low_contrast = bright_pixel_percentage > 0.95 # Page is >95% bright pixels
# Calculate the standard deviation of the image to detect variation
# (blank pages have low standard deviation)
pixel_values = np.array(gray_img)
std_dev = np.std(pixel_values) / 255.0
low_variation = std_dev < 0.05
# Initial assessment based on brightness and contrast
initial_blank = normalized_brightness > threshold and low_contrast and low_variation
logger.debug(f"Page analysis: brightness={normalized_brightness:.2f}, "
f"contrast_bright={bright_pixel_percentage:.2f}, "
f"contrast_dark={dark_pixel_percentage:.2f}, "
f"std_dev={std_dev:.4f}")
# If the initial test suggests it might be blank, perform deeper analysis
if initial_blank:
# Divide the image into a 3x3 grid and check each cell for content
width, height = image.size
cell_width = width // 3
cell_height = height // 3
# Check each cell for content
has_content_in_cells = False
for x in range(3):
for y in range(3):
cell = gray_img.crop((x*cell_width, y*cell_height,
(x+1)*cell_width, (y+1)*cell_height))
cell_pixels = np.array(cell)
cell_std_dev = np.std(cell_pixels) / 255.0
# If any cell has significant variation, the page has content
if cell_std_dev > 0.08:
has_content_in_cells = True
logger.debug(f"Found content in grid cell ({x},{y}): std_dev={cell_std_dev:.4f}")
break
if has_content_in_cells:
break
# Final decision
is_blank = initial_blank and not has_content_in_cells
# For borderline cases, run quick OCR on a small sample
if is_blank and (normalized_brightness < threshold + 0.05 or std_dev > 0.03):
try:
# Run OCR on a scaled-down version for speed
small_img = image.resize((image.width // 2, image.height // 2))
text = pytesseract.image_to_string(small_img, config='--psm 6')
# If we found meaningful text, it's not blank
if len(text.strip()) > 10: # Arbitrary threshold for "meaningful" text
logger.debug(f"OCR found text on seemingly blank page: {text[:50]}...")
is_blank = False
except Exception as e:
logger.warning(f"OCR check failed: {e}")
if debug and is_blank:
# Save the "blank" image for manual inspection
debug_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "debug")
os.makedirs(debug_dir, exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
debug_path = os.path.join(debug_dir, f"blank_page_{timestamp}.png")
image.save(debug_path)
logger.debug(f"Saved blank page for inspection at: {debug_path}")
else:
is_blank = False
if is_blank:
logger.info(f"Page classified as blank: brightness={normalized_brightness:.2f}, "
f"contrast={bright_pixel_percentage:.2f}, std_dev={std_dev:.4f}")
return is_blank
def compare_logo_area(img1, img2):
"""
Compare the top-right corner (logo area) of two images and return a similarity score (0-1).
Higher score means more similar logo areas.
"""
# Resize images to same dimensions if they're different
if img1.size != img2.size:
img2 = img2.resize(img1.size)
# Extract the logo area (top-right portion of the image - larger area)
h, w = img1.height, img1.width
# Using a larger area: 60% width, 25% height (instead of 25% width, 15% height)
crop1 = img1.crop((w*0.6, 0, w, h*0.25))
crop2 = img2.crop((w*0.6, 0, w, h*0.25))
return compare_images(crop1, crop2)
def compare_images(img1, img2):
"""
Compare two images and return a similarity score (0-1).
Higher score means more similar images.
"""
# Resize images to same dimensions if they're different
if img1.size != img2.size:
img2 = img2.resize(img1.size)
# Convert to grayscale for comparison
img1_gray = img1.convert('L')
img2_gray = img2.convert('L')
# Convert to numpy arrays
img1_array = np.array(img1_gray)
img2_array = np.array(img2_gray)
# Calculate structural similarity index
try:
score, _ = ssim(img1_array, img2_array, full=True)
return score
except Exception as e:
logger.error(f"Error comparing images: {e}")
# Fall back to a simpler difference method
diff = ImageChops.difference(img1_gray, img2_gray)
diff_stats = ImageChops.difference(img1_gray, img2_gray).getbbox()
if diff_stats is None: # Images are identical
return 1.0
else:
# Calculate a simple difference score (lower is more similar)
hist = diff.histogram()
sq = (value * ((idx % 256) ** 2) for idx, value in enumerate(hist))
sum_sq = sum(sq)
rms = (sum_sq / float(img1.size[0] * img1.size[1])) ** 0.5
# Convert to similarity score (1 - normalized difference)
return 1 - min(rms / 128, 1.0)
def compare_text_content(text1: str, text2: str) -> float:
"""
Compare two text contents and return a similarity score (0-1).
Higher score means more similar texts.
"""
# Preprocess text to remove whitespace and convert to lowercase
text1 = ' '.join(text1.lower().split())
text2 = ' '.join(text2.lower().split())
# If either text is empty, return 0
if not text1 or not text2:
return 0.0
# Split into words
words1 = set(text1.split())
words2 = set(text2.split())
# Calculate Jaccard similarity (intersection over union)
intersection = len(words1.intersection(words2))
union = len(words1.union(words2))
if union == 0:
return 0.0
return intersection / union
def detect_page_numbers(text: str) -> Optional[Tuple[int, int]]:
"""
Detect page numbering patterns like "Seite 1/2" or "Page 1 of 2".
Returns a tuple of (current_page, total_pages) if found, None otherwise.
"""
# German patterns
patterns = [
r'Seite\s+(\d+)\s*/\s*(\d+)', # Seite 1/2
r'Seite\s+(\d+)\s+von\s+(\d+)', # Seite 1 von 2
r'Blatt\s+(\d+)\s*/\s*(\d+)', # Blatt 1/2
# English patterns
r'Page\s+(\d+)\s*/\s*(\d+)', # Page 1/2
r'Page\s+(\d+)\s+of\s+(\d+)', # Page 1 of 2
# Generic patterns
r'(\d+)\s*/\s*(\d+)\s+Seite', # 1/2 Seite
r'(\d+)\s*/\s*(\d+)\s+Page', # 1/2 Page
r'(\d+)\s*-\s*(\d+)' # 1-2 (assuming first is current, second is total)
]
for pattern in patterns:
matches = re.search(pattern, text, re.IGNORECASE)
if matches:
try:
current_page = int(matches.group(1))
total_pages = int(matches.group(2))
return (current_page, total_pages)
except (ValueError, IndexError):
continue
return None
def extract_possible_company_names(text: str) -> Set[str]:
"""
Attempt to extract possible company names from text.
Returns a set of potential company names found.
"""
company_names = set()
# Look for common company type indicators (German and international)
company_types = [
# German company types
'GmbH', 'AG', 'KG', 'OHG', 'e.V.', 'e. V.', 'GbR', 'UG', 'SE',
'Co. KG', 'Co.KG', 'mbH', 'haftungsbeschränkt', 'eG',
# International company types
'Ltd', 'Inc', 'LLC', 'B.V.', 'Corp', 'Corporation', 'S.A.', 'S.p.A.',
'N.V.', 'GesmbH', 'Ges.m.b.H', 'S.A.S.', 'S.r.l.'
]
# Known company names from config
known_companies = CONFIG.get("company_names", [])
# Check for known companies first (most reliable)
for company in known_companies:
if company.lower() in text.lower():
company_names.add(company)
logger.debug(f"Found known company name: {company}")
# Regular expression to find company names (with company type suffix)
for company_type in company_types:
pattern = fr'([A-Z][a-zA-Z0-9\s\.\-&]+)\s+{re.escape(company_type)}'
matches = re.finditer(pattern, text)
for match in matches:
company_name = match.group(0).strip()
if 5 < len(company_name) < 50: # Reasonable length for a company name
company_names.add(company_name)
logger.debug(f"Found company name with pattern '{company_type}': {company_name}")
# Check for "typical" letterhead patterns (at the beginning of document)
lines = text.split('\n')
# Analyze first few lines (usually contain letterhead)
for i, line in enumerate(lines[:10]):
line = line.strip()
if not line:
continue
# Letterhead detection: First line is often a company name if it has uppercase letters
if i <= 3 and line and line[0].isupper() and 5 < len(line) < 50:
# Check if contains any company type
for company_type in company_types:
if company_type in line:
company_names.add(line)
logger.debug(f"Found company name in letterhead: {line}")
break
# Check for "standard" letterhead (company name on first line)
if i == 0 and not any(c_type in line for c_type in company_types):
# Assume a standalone first line could be a company name
words = len(line.split())
if 2 <= words <= 6 and not line.endswith(':') and not line.startswith('Re:'):
company_names.add(line)
logger.debug(f"Potential company name from first line: {line}")
# Check for bill-to/ship-to sections
bill_to_patterns = [
r'(?:bill\s*to|rechnungsadresse)[:\s]+([A-Z][\w\s\.,&-]+)',
r'(?:customer|kunde)[:\s]+([A-Z][\w\s\.,&-]+)'
]
for pattern in bill_to_patterns:
matches = re.finditer(pattern, text, re.IGNORECASE)
for match in matches:
if match.group(1):
name_part = match.group(1).strip()
# Limit to the first line or up to a comma/period if multi-line
first_line = name_part.split('\n')[0].split(',')[0].split('.')[0].strip()
if 5 < len(first_line) < 50:
company_names.add(first_line)
logger.debug(f"Found company name in bill-to section: {first_line}")
# If we didn't find any company name, try a more aggressive approach with common words
if not company_names:
# Words commonly found in company names
company_indicators = [
'Service', 'Systems', 'Solutions', 'Technologies', 'Consulting',
'Versicherung', 'Versicherungen', 'Gruppe', 'Group', 'Bank',
'Telekom', 'Media', 'Logistik', 'Energie', 'Wasser', 'Stadtwerke'
]
for indicator in company_indicators:
pattern = fr'([A-Z][a-zA-Z0-9\s\.\-&]+\s+{indicator})'
matches = re.finditer(pattern, text)
for match in matches:
company_name = match.group(0).strip()
if 5 < len(company_name) < 50:
company_names.add(company_name)
logger.debug(f"Found company name with indicator '{indicator}': {company_name}")
# Log extracted company names for debugging
if company_names:
logger.debug(f"Extracted company names: {', '.join(company_names)}")
else:
logger.debug("No company names extracted from text")
return company_names
def split_pdf_into_invoices(pdf_path: str) -> List[Dict[str, Any]]:
"""
Split a multi-page PDF into individual invoice documents.
Returns a list of dictionaries containing text and image data for each invoice.
"""
logger.info(f"Analyzing multi-page PDF: {pdf_path}")
try:
# Add debugging information about Poppler path
if not os.path.exists(POPPLER_BIN):
logger.warning(f"Poppler directory not found at: {POPPLER_BIN}")
else:
logger.info(f"Using Poppler from: {POPPLER_BIN}")
# Debug info about system
logger.info(f"Platform: {platform.system()}")
# Check if necessary Poppler binaries exist
if platform.system() == "Darwin": # macOS
pdftoppm_path = os.path.join(POPPLER_BIN, "pdftoppm")
if os.path.exists(pdftoppm_path):
logger.info(f"Found pdftoppm at: {pdftoppm_path}")
else:
logger.warning(f"pdftoppm not found at: {pdftoppm_path}")
else: # Windows
pdftoppm_path = os.path.join(POPPLER_BIN, "pdftoppm.exe")
if os.path.exists(pdftoppm_path):
logger.info(f"Found pdftoppm.exe at: {pdftoppm_path}")
else:
logger.warning(f"pdftoppm.exe not found at: {pdftoppm_path}")
# Convert PDF to images
images = pdf2image.convert_from_path(pdf_path, poppler_path=POPPLER_BIN)
if not images:
logger.error(f"Failed to convert PDF to images: {pdf_path}")
return [{"error": "Failed to convert PDF to images", "text": ""}]
# Use aggressive splitting from config or environment variable
aggressive_split = AGGRESSIVE_SPLIT or os.environ.get('AGGRESSIVE_INVOICE_SPLIT', 'false').lower() == 'true'
# Get threshold from config or environment variable
invoice_similarity_threshold = float(os.environ.get('INVOICE_SIMILARITY_THRESHOLD', '0.5'))
logger.info(f"Using aggressive splitting: {aggressive_split}, similarity threshold: {invoice_similarity_threshold}")
# If aggressive splitting is enabled, treat each page as a separate invoice
if aggressive_split:
invoices = []
for i, image in enumerate(images):
# Skip blank pages
if is_blank_page(image, debug=True):
logger.info(f"Page {i+1}: Blank page - skipping")
continue
page_text = extract_text_from_image_array(image)
logger.info(f"Page {i+1}: Treating as separate invoice (aggressive splitting)")
invoices.append({
"images": [image],
"text": page_text
})
logger.info(f"Split PDF into {len(invoices)} invoices using aggressive splitting")
return invoices
# Otherwise, use the more sophisticated approach
# Initialize variables
invoices = []
# Check if all pages are blank
all_blank = True
for img in images:
if not is_blank_page(img, debug=True):
all_blank = False
break
if all_blank:
logger.warning("All pages appear to be blank. Processing as a single invoice.")
invoices.append({
"images": images,
"text": "All pages appear to be blank."
})
return invoices
# Start with the first non-blank page
first_page_idx = 0
for idx, img in enumerate(images):
if not is_blank_page(img, debug=True):
first_page_idx = idx
break
current_invoice_images = [images[first_page_idx]]
current_invoice_text = extract_text_from_image_array(images[first_page_idx])
possible_company_names = extract_possible_company_names(current_invoice_text)
logger.info(f"Starting with page {first_page_idx + 1} (skipped {first_page_idx} blank pages)")
# Process each page after the first non-blank page
for i in range(first_page_idx + 1, len(images)):
page_image = images[i]
# Check if this is a blank page - if so, skip it
if is_blank_page(page_image, debug=True):