import streamlit as st import os import tempfile from datetime import datetime import pandas as pd import sys # Configure page first st.set_page_config( page_title="Bank Statement Processor", page_icon="🏦", layout="wide", initial_sidebar_state="expanded" ) # Add current directory to path to import local modules sys.path.append('/app') sys.path.append('.') # Import local modules with error handling try: from models import BankStatement, Transaction, ProcessedImage from ocr_engine import OCREngine from bank_parsers import ParserFactory from storage_manager import StorageManager from utils import transactions_to_dataframe, calculate_totals, generate_statement_report MODULES_LOADED = True except ImportError as e: st.error(f"Some modules failed to load: {e}") MODULES_LOADED = False # Define fallback classes from dataclasses import dataclass from typing import List @dataclass class Transaction: date: str = "" description: str = "" amount: float = 0.0 transaction_type: str = "debit" full_date: str = "" @dataclass class BankStatement: bank_name: str = "Unknown Bank" account_number: str = "****Unknown" account_name: str = "Primary Checking" statement_year: str = "2024" transactions: List[Transaction] = None def __post_init__(self): if self.transactions is None: self.transactions = [] def to_dict(self): return self.__dict__ def standardize_dates(self): for transaction in self.transactions: if transaction.date and '/' in transaction.date and not transaction.full_date: transaction.full_date = f"{transaction.date}/{self.statement_year}" class OCREngine: def extract_text(self, image_path): return "OCR text would appear here." class ParserFactory: def parse_statement(self, text): return BankStatement() class StorageManager: def load_all_statements(self): return [] def get_accounts_summary(self): return [] def save_statement(self, statement): return "/tmp/saved.json" def transactions_to_dataframe(transactions): data = [] for t in transactions: data.append({ 'Date': t.full_date if t.full_date else t.date, 'Description': t.description, 'Amount': f"${t.amount:.2f}", 'Type': t.transaction_type }) return pd.DataFrame(data) def calculate_totals(transactions): credits = sum(t.amount for t in transactions if t.transaction_type == 'credit') debits = sum(t.amount for t in transactions if t.transaction_type == 'debit') return { 'total_credits': credits, 'total_debits': debits, 'net_amount': credits - debits } # Initialize session state if 'storage_manager' not in st.session_state: st.session_state.storage_manager = StorageManager() if 'ocr_engine' not in st.session_state: st.session_state.ocr_engine = OCREngine() if 'parser_factory' not in st.session_state: st.session_state.parser_factory = ParserFactory() if 'current_statement' not in st.session_state: st.session_state.current_statement = None if 'user_accounts' not in st.session_state: st.session_state.user_accounts = [] def main(): st.title("🏦 Bank Statement Processor") st.markdown("Upload bank statement images to extract and consolidate transaction data") # Display welcome message st.info(""" **Now with Account Management & Date Standardization!** Assign statements to specific accounts and standardize dates with year assignment. """) if not MODULES_LOADED: st.warning("⚠️ Running in limited mode. Some advanced features may be limited.") # Sidebar navigation st.sidebar.title("Navigation") app_mode = st.sidebar.selectbox( "Choose Mode", ["Upload & Process", "Validate Data", "View Statements", "Account Summary", "Manage Accounts"] ) if app_mode == "Upload & Process": upload_and_process() elif app_mode == "Validate Data": validate_data() elif app_mode == "View Statements": view_statements() elif app_mode == "Account Summary": account_summary() elif app_mode == "Manage Accounts": manage_accounts() def upload_and_process(): st.header("📤 Upload Bank Statements") # Account selection first st.subheader("1. Assign to Account") accounts = st.session_state.user_accounts if not accounts: st.warning("No accounts found. Please create accounts in 'Manage Accounts' first.") return account_options = {f"{acc['name']} ({acc['bank']} - {acc['number']})": acc for acc in accounts} selected_account_key = st.selectbox("Select Account", list(account_options.keys())) if selected_account_key: selected_account = account_options[selected_account_key] # Year assignment st.subheader("2. Set Statement Year") current_year = datetime.now().year statement_year = st.selectbox("Statement Year", [str(year) for year in range(current_year-2, current_year+1)], index=2) # Default to current year # File upload st.subheader("3. Upload Statement") uploaded_files = st.file_uploader( "Choose bank statement images", type=['png', 'jpg', 'jpeg'], accept_multiple_files=True, help="Supported formats: PNG, JPG, JPEG. For best results, use clear, high-resolution images." ) if uploaded_files: st.success(f"✅ {len(uploaded_files)} file(s) uploaded successfully!") for uploaded_file in uploaded_files: st.subheader(f"Processing: {uploaded_file.name}") col1, col2 = st.columns([1, 1]) with col1: st.image(uploaded_file, caption="Uploaded Image", use_container_width=True) with col2: with st.spinner("Extracting text with OCR..."): try: # Save to temp file with tempfile.NamedTemporaryFile(delete=False, suffix='.png') as tmp_file: tmp_file.write(uploaded_file.getbuffer()) temp_path = tmp_file.name # Extract text extracted_text = st.session_state.ocr_engine.extract_text(temp_path) # Parse statement statement = st.session_state.parser_factory.parse_statement(extracted_text) # Apply account assignment and year statement.bank_name = selected_account['bank'] statement.account_number = selected_account['number'] statement.account_name = selected_account['name'] statement.statement_year = statement_year # Standardize dates statement.standardize_dates() st.session_state.current_statement = statement # Cleanup os.unlink(temp_path) except Exception as e: st.error(f"❌ Error processing image: {str(e)}") continue # Display extraction results if extracted_text: with st.expander("📄 View Extracted Text", expanded=False): st.text_area("OCR Results", extracted_text, height=200, key=f"text_{uploaded_file.name}") # Show parsed data if statement and statement.transactions: st.success(f"🎉 Found {len(statement.transactions)} transactions!") # Display account info st.info(f"**Account:** {statement.account_name} | **Bank:** {statement.bank_name} | **Year:** {statement.statement_year}") # Display transactions df = transactions_to_dataframe(statement.transactions) st.dataframe(df, use_container_width=True) # Show summary totals = calculate_totals(statement.transactions) col1, col2, col3 = st.columns(3) with col1: st.metric("Total Credits", f"${totals['total_credits']:.2f}") with col2: st.metric("Total Debits", f"${totals['total_debits']:.2f}") with col3: st.metric("Net Amount", f"${totals['net_amount']:.2f}") # Save button if st.button("💾 Save Statement", key=f"save_{uploaded_file.name}", type="primary"): save_statement(statement, uploaded_file.name) else: st.warning("No transactions found. Try the Manual Entry option.") def manage_accounts(): st.header("👥 Manage Accounts") st.info("Create and manage your bank accounts for better organization.") # Add new account st.subheader("Add New Account") with st.form("add_account_form"): col1, col2, col3 = st.columns(3) with col1: account_name = st.text_input("Account Name", "Primary Checking") with col2: bank_name = st.selectbox("Bank", ["Chase", "Bank of America", "Wells Fargo", "Citibank", "Other"]) with col3: account_number = st.text_input("Account Number", "****7111") submitted = st.form_submit_button("Add Account") if submitted: new_account = { 'name': account_name, 'bank': bank_name, 'number': account_number, 'created_at': datetime.now().isoformat() } if 'user_accounts' not in st.session_state: st.session_state.user_accounts = [] st.session_state.user_accounts.append(new_account) st.success(f"✅ Added account: {account_name}") # Display existing accounts st.subheader("Your Accounts") accounts = st.session_state.user_accounts if not accounts: st.info("No accounts created yet. Add your first account above.") else: for i, account in enumerate(accounts): col1, col2, col3, col4 = st.columns([2, 2, 1, 1]) with col1: st.write(f"**{account['name']}**") with col2: st.write(f"{account['bank']} - {account['number']}") with col3: if st.button("Edit", key=f"edit_{i}"): st.info("Edit functionality coming soon") with col4: if st.button("Delete", key=f"delete_{i}"): st.session_state.user_accounts.pop(i) st.success("Account deleted") st.rerun() st.markdown("---") def validate_data(): st.header("✏️ Validate & Edit Data") statement = st.session_state.current_statement if not statement: st.warning("📝 Please upload and process a statement first using the 'Upload & Process' section.") return st.subheader(f"**{statement.account_name}** - {statement.bank_name} - {statement.account_number}") # Edit account info and year col1, col2, col3 = st.columns(3) with col1: new_account_name = st.text_input("Account Name", value=statement.account_name) with col2: new_bank = st.text_input("Bank Name", value=statement.bank_name) with col3: new_year = st.text_input("Statement Year", value=statement.statement_year) # Transaction editing if statement.transactions: st.subheader(f"Transactions ({len(statement.transactions)} found)") edited_transactions = [] for i, transaction in enumerate(statement.transactions): with st.expander(f"Transaction {i+1}: {transaction.date} - {transaction.description[:30]}...", expanded=False): col1, col2, col3, col4 = st.columns([1, 2, 1, 1]) with col1: new_date = st.text_input("Date (MM/DD)", value=transaction.date, key=f"date_{i}") # Auto-update full date when year changes if new_date and '/' in new_date: transaction.full_date = f"{new_date}/{new_year}" with col2: new_desc = st.text_area("Description", value=transaction.description, key=f"desc_{i}", height=60) with col3: new_amount = st.number_input("Amount", value=float(transaction.amount), key=f"amount_{i}", step=0.01) with col4: new_type = st.selectbox("Type", ["credit", "debit"], index=0 if transaction.transaction_type == "credit" else 1, key=f"type_{i}") # Create edited transaction edited_transaction = Transaction( date=new_date, description=new_desc, amount=float(new_amount), transaction_type=new_type, full_date=f"{new_date}/{new_year}" if new_date and '/' in new_date else transaction.full_date ) edited_transactions.append(edited_transaction) # Update and save col1, col2 = st.columns([3, 1]) with col2: if st.button("💾 Save All Changes", type="primary"): statement.account_name = new_account_name statement.bank_name = new_bank statement.statement_year = new_year statement.transactions = edited_transactions statement.standardize_dates() # Re-standardize dates st.session_state.current_statement = statement st.success("✅ All changes saved successfully!") # Show updated preview st.subheader("Updated Transactions") df = transactions_to_dataframe(statement.transactions) st.dataframe(df, use_container_width=True) else: st.info("No transactions available to validate.") def view_statements(): st.header("📊 View Consolidated Statements") statements = st.session_state.storage_manager.load_all_statements() if not statements: st.warning(""" 📂 No statements found. To get started: 1. Go to **Manage Accounts** to create accounts 2. Use **Upload & Process** to upload statements 3. Return here to view all your data """) return st.success(f"📈 Found {len(statements)} saved statements") # Filter by account accounts = list(set([f"{s.get('account_name', 'Unknown')} - {s.get('bank_name', 'Unknown')}" for s in statements])) selected_account = st.selectbox("Filter by Account", ["All Accounts"] + accounts) # Display statements for i, stmt_data in enumerate(statements): account_display = f"{stmt_data.get('account_name', 'Unknown')} - {stmt_data.get('bank_name', 'Unknown')}" if selected_account != "All Accounts" and account_display != selected_account: continue with st.expander(f"Statement {i+1}: {account_display} - {stmt_data.get('statement_year', 'Unknown')}", expanded=i==0): transactions = [Transaction(**t) for t in stmt_data.get('transactions', [])] if transactions: # Show summary totals = calculate_totals(transactions) col1, col2, col3, col4 = st.columns(4) with col1: st.metric("Transactions", len(transactions)) with col2: st.metric("Credits", f"${totals['total_credits']:.2f}") with col3: st.metric("Debits", f"${totals['total_debits']:.2f}") with col4: st.metric("Net", f"${totals['net_amount']:.2f}") # Show transactions table df = transactions_to_dataframe(transactions) st.dataframe(df, use_container_width=True) else: st.info("No transactions in this statement") def account_summary(): st.header("🏦 Account Summary") accounts = st.session_state.user_accounts if not accounts: st.warning(""" 🏦 No accounts found. Create accounts in the 'Manage Accounts' section first. """) return st.success(f"✅ Found {len(accounts)} accounts") # Display account cards for account in accounts: with st.container(): col1, col2, col3, col4 = st.columns(4) with col1: st.subheader(account['name']) st.caption(f"{account['bank']} - {account['number']}") with col2: # Count statements for this account statements = st.session_state.storage_manager.load_all_statements() account_statements = [s for s in statements if s.get('account_name') == account['name']] st.metric("Statements", len(account_statements)) with col3: # Count transactions total_transactions = sum(len(s.get('transactions', [])) for s in account_statements) st.metric("Transactions", total_transactions) with col4: st.write("**Created**") st.write(account.get('created_at', 'Unknown')[:10]) st.markdown("---") def save_statement(statement: BankStatement, original_filename: str): """Save statement to storage""" try: storage = st.session_state.storage_manager # Add processing metadata statement.processed_at = datetime.now().isoformat() # Save statement filepath = storage.save_statement(statement) if filepath: st.success(f"✅ Statement saved to {statement.account_name}!") else: st.error("❌ Failed to save statement") except Exception as e: st.error(f"Error saving statement: {e}") if __name__ == "__main__": main()