# app.py (updated) import gradio as gr import pandas as pd import numpy as np import os import tempfile from finance_utils import preprocess_transactions, summarize_transactions, predict_expenses, category_summary DATA_DIR = "data" def load_bundled_datasets(): files = [f for f in os.listdir(DATA_DIR) if f.lower().endswith((".csv",".xlsx",".xls"))] datasets = {} for f in files: path = os.path.join(DATA_DIR, f) try: df = pd.read_csv(path) except Exception: try: df = pd.read_excel(path) except Exception: continue datasets[f] = df return datasets def analyze_uploaded(files, use_bundled=True): combined = [] if use_bundled: bundled = load_bundled_datasets() for name, df in bundled.items(): combined.append(df) if files: for f in files: # gr.File gives a file-like with .name pointing to a temp file path on the server try: df = pd.read_csv(f.name) except Exception: try: df = pd.read_excel(f.name) except Exception: continue combined.append(df) if not combined: return "No data found. Upload CSV(s) or include datasets in the data/ folder of the Space repository.", None df = pd.concat(combined, ignore_index=True, sort=False) df_clean = preprocess_transactions(df) summary = summarize_transactions(df_clean) preds = predict_expenses(df_clean) cat_summary = category_summary(df_clean) # save processed CSV to temporary file for download tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".csv") df_clean.to_csv(tmp.name, index=False) tmp.close() # return summary text and path to file (gr.File will serve that path) return summary, tmp.name title = "BudgetBuddy — Autonomous Personal Finance Agent" description = """ Upload your bank transaction CSVs (or include them in the Space `data/` folder). BudgetBuddy will: - Parse and standardize transactions (date, amount, description) - Auto-categorize spending (rules + ML fallback) - Produce monthly summaries and category breakdowns - Predict next month's expenses per category (simple model) - Export a cleaned CSV with categories for further analysis """ with gr.Blocks() as demo: gr.Markdown(f"# {title}") gr.Markdown(description) with gr.Row(): upload = gr.File(file_count="multiple", label="Upload bank CSV(s) (optional)") use_bundled = gr.Checkbox(value=True, label="Also load bundled datasets from data/ folder") analyze_btn = gr.Button("Analyze") output_text = gr.Textbox(lines=12, label="Summary") output_file = gr.File(label="Download processed CSV") # gr.File used for download analyze_btn.click(fn=analyze_uploaded, inputs=[upload, use_bundled], outputs=[output_text, output_file]) if __name__ == "__main__": demo.launch()