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")

        # 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)}")


def main():
    root = tk.Tk()
    app = StatementConverter(root)
    root.mainloop()


if __name__ == "__main__":
    main()