import matplotlib.pyplot as plt import pandas as pd import os def generate_report(df, spending_analysis, recommendations): # Create a directory for images if it doesn't exist images_dir = "images" if not os.path.exists(images_dir): os.makedirs(images_dir) report = f""" ## Invoice Reader & Budget Categorizer Report ### Categorized Transactions {df.groupby('category').apply(lambda x: x.to_markdown(index=False)).to_string()} ### Spending Insights {spending_analysis} ### Budget Recommendations {recommendations} ### Visualizations #### Category-wise Spending ![Category-wise Spending]({os.path.join(images_dir, 'category_spending.png')}) #### Monthly Spending Trend ![Monthly Spending Trend]({os.path.join(images_dir, 'monthly_spending.png')}) """ if not df.empty: # Category-wise spending pie chart category_spending = df.groupby("category")["amount"].sum() plt.figure(figsize=(6, 6)) plt.pie(category_spending, labels=category_spending.index, autopct="%1.1f%%") plt.title("Category-wise Spending") plt.savefig(os.path.join(images_dir, "category_spending.png")) plt.close() # Monthly spending trend with validation monthly_spending = df.groupby("month")["amount"].sum() if len(monthly_spending) > 1: # Ensure multiple months plt.figure(figsize=(8, 4)) monthly_spending.plot(kind="line", marker="o") plt.title("Monthly Spending Trend") plt.xlabel("Month") plt.ylabel("Amount") plt.savefig(os.path.join(images_dir, "monthly_spending.png")) plt.close() else: report += "\n#### Monthly Spending Trend\n(No trend available: insufficient data across multiple months)" return report