Processing 291 lines Found transaction: {'date': '01/02/2020', 'amount': '101.01', 'payee': ''} Found transaction: {'date': '01/02/2020', 'amount': '102.01', 'payee': ''} Found transaction: {'date': '01/02/2020', 'amount': '102.01', 'payee': ''} The above file's transaction date's are being read as transaction amounts
Dates are incorrectly being recognized as amounts. Please improve my script so that it correctly identifies transaction values.
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import re
from pathlib import Path
from collections import defaultdict
import PyPDF2
from datetime import datetime
import os
import logging
class StatementConverter:
def init(self, root):
self.root = root
self.root.title("Nordea PDF Statement to QIF Converter")
code
Assistant
# Configure window
self.root.geometry("600x500")
self.root.configure(padx=20, pady=20)
# Setup logging
logging.basicConfig(level=logging.DEBUG)
self.logger = logging.getLogger(__name__)
# Store selected files
self.selected_files = []
# Create GUI elements
self.create_gui()
# Store transactions by account
self.transactions_by_account = defaultdict(list)
def create_gui(self):
# Title
tk.Label(
self.root,
text="Nordea PDF Statement to QIF Converter",
font=('Arial', 14, 'bold')
).pack(pady=10)
# File list
frame = tk.Frame(self.root)
frame.pack(fill=tk.BOTH, expand=True, pady=10)
self.file_listbox = tk.Listbox(frame)
self.file_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar = tk.Scrollbar(frame)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.file_listbox.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=self.file_listbox.yview)
# Buttons
button_frame = tk.Frame(self.root)
button_frame.pack(fill=tk.X, pady=10)
tk.Button(
button_frame,
text="Add PDF Files",
command=self.add_files
).pack(side=tk.LEFT, padx=5)
tk.Button(
button_frame,
text="Clear Files",
command=self.clear_files
).pack(side=tk.LEFT, padx=5)
tk.Button(
button_frame,
text="Convert to QIF",
command=self.convert_files
).pack(side=tk.LEFT, padx=5)
# Debug info
self.debug_text = tk.Text(self.root, height=8, width=70)
self.debug_text.pack(pady=10)
# Status
self.status_label = tk.Label(self.root, text="", wraplength=550)
self.status_label.pack(pady=10)
# Progress bar
self.progress = ttk.Progressbar(
self.root,
orient="horizontal",
length=550,
mode="determinate"
)
self.progress.pack(pady=10)
def log_debug(self, message):
self.debug_text.insert(tk.END, f"{message}\n")
self.debug_text.see(tk.END)
self.logger.debug(message)
self.root.update()
def add_files(self):
files = filedialog.askopenfilenames(
title="Select PDF Statement Files",
filetypes=[("PDF files", "*.pdf"), ("All files", "*.*")]
)
for file in files:
if file not in self.selected_files:
self.selected_files.append(file)
self.file_listbox.insert(tk.END, Path(file).name)
def clear_files(self):
self.selected_files.clear()
self.file_listbox.delete(0, tk.END)
self.status_label.config(text="")
self.debug_text.delete(1.0, tk.END)
self.progress["value"] = 0
def parse_date(self, date_str):
try:
# Convert from DD.MM.YYYY to MM/DD/YYYY
day, month, year = date_str.split('.')
return f"{month.strip()}/{day.strip()}/{year.strip()}"
except:
return date_str
def clean_amount(self, amount_str):
# Remove spaces and convert commas to dots
amount = amount_str.replace(' ', '').replace(',', '.')
# Ensure it's a valid number
try:
return str(float(amount))
except:
return None
def extract_transactions(self, text):
self.log_debug("Starting transaction extraction...")
# Extract account number - try different formats
iban_patterns = [
r'IBAN\s*(FI\d{2}\s*\d{4}\s*\d{4}\s*\d{4}\s*\d{2})',
r'IBAN\s*FI(\d{2}\d{4}\d{4}\d{4}\d{2})',
]
account = None
for pattern in iban_patterns:
match = re.search(pattern, text.replace(' ', ''))
if match:
account = match.group(1).replace(' ', '')
break
if not account:
# Try to find old format account number
old_format = re.search(r'(\d{6}-\d{5})', text)
if old_format:
account = old_format.group(1)
if not account:
self.log_debug("No account number found in text")
return None, []
self.log_debug(f"Found account: {account}")
transactions = []
# Split into lines and process
lines = text.split('\n')
self.log_debug(f"Processing {len(lines)} lines")
# Extract year from statement if possible
year_match = re.search(r'TILIOTE\s+\d+/(\d{2})', text)
default_year = f"20{year_match.group(1)}" if year_match else None
# Get all lines with potential transactions
for i, line in enumerate(lines):
line = line.strip()
# Skip empty lines
if not line:
continue
# Try to find date at start of line
date_match = re.match(r'(\d{2})\.(\d{2})', line)
if not date_match:
continue
try:
# Extract date
day, month = date_match.groups()
date = f"{day}.{month}.{default_year}" if default_year else f"{day}.{month}.2020"
# Look for amount at the end of the line
amount_match = re.search(r'[-]?\d+[,. ]\d{2}\s*$', line)
if not amount_match:
continue
amount = self.clean_amount(amount_match.group(0))
if not amount:
continue
# Get description (everything between date and amount)
description = line[line.find(month) + 2:line.rfind(amount_match.group(0))].strip()
# Create transaction
transaction = {
'date': self.parse_date(date),
'amount': amount,
'payee': description
}
transactions.append(transaction)
self.log_debug(f"Found transaction: {transaction}")
except Exception as e:
self.log_debug(f"Error parsing line {i}: '{line}' - {str(e)}")
continue
self.log_debug(f"Found {len(transactions)} transactions")
return account, transactions
def convert_files(self):
if not self.selected_files:
messagebox.showwarning("Warning", "Please add PDF files first!")
return
self.transactions_by_account.clear()
self.progress["value"] = 0
self.progress["maximum"] = len(self.selected_files)
self.debug_text.delete(1.0, tk.END)
try:
# Process each PDF file
for pdf_file in self.selected_files:
self.status_label.config(text=f"Processing: {Path(pdf_file).name}")
self.log_debug(f"\nProcessing file: {pdf_file}")
with open(pdf_file, 'rb') as file:
pdf_reader = PyPDF2.PdfReader(file)
text = ""
for page in pdf_reader.pages:
text += page.extract_text() + "\n"
self.log_debug("PDF text extracted, length: " + str(len(text)))
self.log_debug("First 200 characters: " + text[:200])
# For debugging, log some sample lines
sample_lines = text.split('\n')[:10]
self.log_debug("Sample lines:")
for line in sample_lines:
self.log_debug(f"LINE: {line}")
account, transactions = self.extract_transactions(text)
if account and transactions:
self.transactions_by_account[account].extend(transactions)
self.log_debug(f"Added {len(transactions)} transactions for account {account}")
else:
self.log_debug("No transactions found in this file")
self.progress["value"] += 1
self.root.update()
# Create output directory
output_dir = Path(self.selected_files[0]).parent / "qif_output"
output_dir.mkdir(exist_ok=True)
# Generate QIF files for each account
for account, transactions in self.transactions_by_account.items():
output_file = output_dir / f"{account}.qif"
self.log_debug(f"Writing {len(transactions)} transactions to {output_file}")
with open(output_file, 'w', encoding='utf-8') as f:
f.write("!Type:Bank\n")
for trans in sorted(transactions, key=lambda x: x['date']):
f.write(f"D{trans['date']}\n")
f.write(f"T{trans['amount']}\n")
f.write(f"P{trans['payee']}\n")
f.write("LUnknown\n")
f.write("^\n")
self.log_debug(f"Finished writing to {output_file}")
self.status_label.config(
text=f"Conversion complete! QIF files saved in:\n{output_dir}",
fg="green"
)
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {str(e)}")
self.status_label.config(
text="Conversion failed. See error message.",
fg="red"
)
self.log_debug(f"Error: {str(e)}")
It looks like your script is incorrectly parsing the transaction dates as amounts due to the way it processes each line in the PDF statement. This issue often arises from the regular expressions or the parsing logic not accurately distinguishing between different parts of a transaction line (e.g., date, amount, payee).
To resolve this, we'll enhance the parsing logic to ensure that dates and amounts are correctly identified and assigned. Here's a step-by-step guide along with the improved script:
1. Understand the PDF Statement Structure
Before diving into the code, it's crucial to understand the exact structure of the transaction lines in your PDF statements. Typically, a transaction line might look like this:
code
01.02.2020 Some Payee Description 101,01 €
Where:
Date: 01.02.2020
Payee/Description: Some Payee Description
Amount: 101,01 €
Ensure that this structure is consistent across all your PDF statements. If there are variations, the parsing logic might need further adjustments.
2. Enhance Regular Expressions
We'll improve the regular expressions to accurately capture the full date (including the year) and correctly extract the amount, considering possible negative values and different decimal separators.
3. Improve the Parsing Logic
By refining how each line is processed, we'll ensure that each component (date, amount, payee) is correctly identified and assigned.
4. Implement the Improved Script
Here's the revised version of your script with the necessary enhancements:
python
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import re
from pathlib import Path
from collections import defaultdict
import PyPDF2
from datetime import datetime
import os
import logging
class StatementConverter:
def __init__(self, root):
self.root = root
self.root.title("Nordea PDF Statement to QIF Converter")
# Configure window
self.root.geometry("600x600")
self.root.configure(padx=20, pady=20)
# Setup logging
logging.basicConfig(level=logging.DEBUG)
self.logger = logging.getLogger(__name__)
# Store selected files
self.selected_files = []
# Create GUI elements
self.create_gui()
# Store transactions by account
self.transactions_by_account = defaultdict(list)
def create_gui(self):
# Title
tk.Label(
self.root,
text="Nordea PDF Statement to QIF Converter",
font=('Arial', 14, 'bold')
).pack(pady=10)
# File list
frame = tk.Frame(self.root)
frame.pack(fill=tk.BOTH, expand=True, pady=10)
self.file_listbox = tk.Listbox(frame, height=10)
self.file_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar = tk.Scrollbar(frame)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.file_listbox.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=self.file_listbox.yview)
# Buttons
button_frame = tk.Frame(self.root)
button_frame.pack(fill=tk.X, pady=10)
tk.Button(
button_frame,
text="Add PDF Files",
command=self.add_files
).pack(side=tk.LEFT, padx=5)
tk.Button(
button_frame,
text="Clear Files",
command=self.clear_files
).pack(side=tk.LEFT, padx=5)
tk.Button(
button_frame,
text="Convert to QIF",
command=self.convert_files
).pack(side=tk.LEFT, padx=5)
# Debug info
self.debug_text = tk.Text(self.root, height=15, width=70)
self.debug_text.pack(pady=10)
# Status
self.status_label = tk.Label(self.root, text="", wraplength=550)
self.status_label.pack(pady=10)
# Progress bar
self.progress = ttk.Progressbar(
self.root,
orient="horizontal",
length=550,
mode="determinate"
)
self.progress.pack(pady=10)
def log_debug(self, message):
self.debug_text.insert(tk.END, f"{message}\n")
self.debug_text.see(tk.END)
self.logger.debug(message)
self.root.update()
def add_files(self):
files = filedialog.askopenfilenames(
title="Select PDF Statement Files",
filetypes=[("PDF files", "*.pdf"), ("All files", "*.*")]
)
for file in files:
if file not in self.selected_files:
self.selected_files.append(file)
self.file_listbox.insert(tk.END, Path(file).name)
def clear_files(self):
self.selected_files.clear()
self.file_listbox.delete(0, tk.END)
self.status_label.config(text="")
self.debug_text.delete(1.0, tk.END)
self.progress["value"] = 0
def parse_date(self, date_str):
"""
Parse date from DD.MM.YYYY or DD.MM format to MM/DD/YYYY.
If year is missing, use the default year.
"""
try:
parts = date_str.split('.')
if len(parts) == 3:
day, month, year = parts
elif len(parts) == 2:
day, month = parts
year = self.default_year if self.default_year else "2020"
else:
return None
# Ensure year is four digits
if len(year) == 2:
year = f"20{year}"
date_obj = datetime.strptime(f"{day}.{month}.{year}", "%d.%m.%Y")
return date_obj.strftime("%m/%d/%Y")
except Exception as e:
self.log_debug(f"Date parsing error: {str(e)} for date_str: {date_str}")
return None
def clean_amount(self, amount_str):
"""
Clean the amount string by removing spaces, converting commas to dots,
and handling negative signs.
"""
amount = amount_str.replace(' ', '').replace(',', '.').replace('€', '')
# Handle negative amounts
if '−' in amount or '-' in amount:
amount = '-' + re.sub(r'[^0-9.]', '', amount)
else:
amount = re.sub(r'[^0-9.]', '', amount)
try:
return f"{float(amount):.2f}"
except:
return None
def extract_transactions(self, text):
self.log_debug("Starting transaction extraction...")
# Extract account number - try different formats
iban_patterns = [
r'IBAN\s*(FI\d{2}\s*\d{4}\s*\d{4}\s*\d{4}\s*\d{2})',
r'IBAN\s*FI(\d{2}\d{4}\d{4}\d{4}\d{2})',
]
account = None
for pattern in iban_patterns:
match = re.search(pattern, text, re.IGNORECASE)
if match:
account = match.group(1).replace(' ', '')
break
if not account:
# Try to find old format account number
old_format = re.search(r'(\d{6}-\d{5})', text)
if old_format:
account = old_format.group(1)
if not account:
self.log_debug("No account number found in text")
return None, []
self.log_debug(f"Found account: {account}")
transactions = []
# Split into lines and process
lines = text.split('\n')
self.log_debug(f"Processing {len(lines)} lines")
# Extract year from statement if possible
year_match = re.search(r'TILIOTE\s+\d+/\s*(\d{2})', text, re.IGNORECASE)
self.default_year = f"20{year_match.group(1)}" if year_match else None
if self.default_year:
self.log_debug(f"Default year extracted: {self.default_year}")
else:
self.log_debug("Default year not found, using 2020")
# Define a robust regex pattern for transaction lines
# Example pattern: 01.02.2020 Description of transaction 101,01 €
transaction_pattern = re.compile(
r'^\s*(\d{2}\.\d{2}(?:\.\d{4})?)\s+(.+?)\s+([−-]?\d+[.,]\d{2})\s*€?\s*$'
)
for i, line in enumerate(lines):
line = line.strip()
# Skip empty lines
if not line:
continue
match = transaction_pattern.match(line)
if not match:
continue
date_str, description, amount_str = match.groups()
date = self.parse_date(date_str)
if not date:
self.log_debug(f"Skipping line {i+1} due to invalid date: '{date_str}'")
continue
amount = self.clean_amount(amount_str)
if amount is None:
self.log_debug(f"Skipping line {i+1} due to invalid amount: '{amount_str}'")
continue
transaction = {
'date': date,
'amount': amount,
'payee': description.strip()
}
transactions.append(transaction)
self.log_debug(f"Found transaction: {transaction}")
self.log_debug(f"Found {len(transactions)} transactions")
return account, transactions
def convert_files(self):
if not self.selected_files:
messagebox.showwarning("Warning", "Please add PDF files first!")
return
self.transactions_by_account.clear()
self.progress["value"] = 0
self.progress["maximum"] = len(self.selected_files)
self.debug_text.delete(1.0, tk.END)
try:
# Process each PDF file
for pdf_file in self.selected_files:
self.status_label.config(text=f"Processing: {Path(pdf_file).name}")
self.log_debug(f"\nProcessing file: {pdf_file}")
with open(pdf_file, 'rb') as file:
pdf_reader = PyPDF2.PdfReader(file)
text = ""
for page_num, page in enumerate(pdf_reader.pages, start=1):
page_text = page.extract_text()
if page_text:
text += page_text + "\n"
else:
self.log_debug(f"Page {page_num} is empty or couldn't be read.")
self.log_debug("PDF text extracted, length: " + str(len(text)))
self.log_debug("First 200 characters: " + text[:200])
# For debugging, log some sample lines
sample_lines = text.split('\n')[:10]
self.log_debug("Sample lines:")
for idx, line in enumerate(sample_lines, start=1):
self.log_debug(f"LINE {idx}: {line}")
account, transactions = self.extract_transactions(text)
if account and transactions:
self.transactions_by_account[account].extend(transactions)
self.log_debug(f"Added {len(transactions)} transactions for account {account}")
else:
self.log_debug("No transactions found in this file")
self.progress["value"] += 1
self.root.update()
if not self.transactions_by_account:
self.status_label.config(
text="No transactions found in the selected files.",
fg="red"
)
return
# Create output directory
output_dir = Path(self.selected_files[0]).parent / "qif_output"
output_dir.mkdir(exist_ok=True)
# Generate QIF files for each account
for account, transactions in self.transactions_by_account.items():
output_file = output_dir / f"{account}.qif"
self.log_debug(f"Writing {len(transactions)} transactions to {output_file}")
with open(output_file, 'w', encoding='utf-8') as f:
f.write("!Type:Bank\n")
for trans in sorted(transactions, key=lambda x: datetime.strptime(x['date'], "%m/%d/%Y")):
f.write(f"D{trans['date']}\n")
f.write(f"T{trans['amount']}\n")
f.write(f"P{trans['payee']}\n")
f.write("LUnknown\n")
f.write("^\n")
self.log_debug(f"Finished writing to {output_file}")
self.status_label.config(
text=f"Conversion complete! QIF files saved in:\n{output_dir}",
fg="green"
)
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {str(e)}")
self.status_label.config(
text="Conversion failed. See error message.",
fg="red"
)
self.log_debug(f"Error: {str(e)}")
def main():
root = tk.Tk()
app = StatementConverter(root)
root.mainloop()
if __name__ == "__main__":
main()
5. Key Improvements Explained
a. Robust Regular Expressions
The transaction_pattern regular expression is designed to match lines that start with a date (dd.mm.yyyy or dd.mm), followed by a description, and ending with an amount. Here's the breakdown:
^\s*: Start of the line, allowing optional leading whitespace.
(\d{2}\.\d{2}(?:\.\d{4})?): Captures the date in dd.mm or dd.mm.yyyy format.
\s+: At least one whitespace character.
(.+?): Non-greedy capture of the description/payee.
\s+: At least one whitespace character.
([−-]?\d+[.,]\d{2}): Captures the amount, which may start with a minus sign and contains decimal separators.
\s*€?\s*$: Optional whitespace and Euro symbol at the end of the line.
b. Enhanced Date Parsing
The parse_date method now handles both dd.mm and dd.mm.yyyy formats. If the year is missing, it uses a default year extracted from the statement or defaults to 2020:
python
def parse_date(self, date_str):
try:
parts = date_str.split('.')
if len(parts) == 3:
day, month, year = parts
elif len(parts) == 2:
day, month = parts
year = self.default_year if self.default_year else "2020"
else:
return None
# Ensure year is four digits
if len(year) == 2:
year = f"20{year}"
date_obj = datetime.strptime(f"{day}.{month}.{year}", "%d.%m.%Y")
return date_obj.strftime("%m/%d/%Y")
except Exception as e:
self.log_debug(f"Date parsing error: {str(e)} for date_str: {date_str}")
return None
c. Accurate Amount Cleaning
The clean_amount method now correctly handles negative amounts and various decimal separators:
The script now provides more detailed debug information, making it easier to trace and identify where parsing might fail.
e. Handling Pages Without Extractable Text
Some PDF pages might not have extractable text. The script logs a message if a page is empty or couldn't be read:
python
for page_num, page in enumerate(pdf_reader.pages, start=1):
page_text = page.extract_text()
if page_text:
text += page_text + "\n"
else:
self.log_debug(f"Page {page_num} is empty or couldn't be read.")
6. Testing and Validation
After implementing the improved script:
Test with Multiple PDF Statements: Ensure that the script correctly parses various statements, especially those with different formats or edge cases.
Verify Output QIF Files: Open the generated QIF files in your financial software to confirm that dates, amounts, and payees are correctly imported.
Check for Negative Transactions: Ensure that withdrawals or negative amounts are correctly represented.
Review Logs: Utilize the debug logs to identify and troubleshoot any parsing issues.
7. Additional Recommendations
Internationalization: If your statements use different date or number formats based on locale, consider making the parser adaptable to these variations.
Error Handling: Enhance error handling to skip or report malformed lines without halting the entire conversion process.
User Feedback: Provide more user-friendly messages or progress indicators to enhance the user experience during the conversion process.
By implementing these enhancements, your script should accurately parse transaction dates and amounts, ensuring that the QIF files generated are correct and reliable.