Code - Budgeting App

PHOTO EMBED

Tue Oct 22 2024 23:32:06 GMT+0000 (Coordinated Universal Time)

Saved by @abhinavchopra22

from flask import Flask, request, jsonify, send_file
import os
import uuid
import PyPDF2
import json
import matplotlib.pyplot as plt
import tempfile

app = Flask(__name__)

# In-memory storage for simplicity
transactions_db = {}

# Helper function to parse PDF and extract transactions
def extract_transactions_from_pdf(pdf_path):
    transactions = []
    try:
        with open(pdf_path, 'rb') as file:
            reader = PyPDF2.PdfReader(file)
            for page in reader.pages:
                text = page.extract_text()
                # Assuming the transactions are in a simple format for demonstration purposes
                for line in text.split('\n'):
                    if 'Transaction' in line:
                        # Extracting transaction details (this is a simplified example)
                        details = line.split(',')
                        transactions.append({
                            "date": details[0],
                            "description": details[1],
                            "amount": float(details[2])
                        })
    except Exception as e:
        print(f"Error extracting transactions: {e}")
    return transactions

# 1. Upload PDF Statement
@app.route('/upload_statement', methods=['POST'])
def upload_statement():
    if 'file' not in request.files:
        return jsonify({"error": "No file part"}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({"error": "No selected file"}), 400

    if file:
        # Save the file temporarily
        temp_file_path = os.path.join(tempfile.gettempdir(), str(uuid.uuid4()) + ".pdf")
        file.save(temp_file_path)
        
        # Extract transactions from the PDF
        transactions = extract_transactions_from_pdf(temp_file_path)
        os.remove(temp_file_path)
        
        # Store transactions in a mock database
        user_id = request.form.get('user_id', 'default_user')
        if user_id not in transactions_db:
            transactions_db[user_id] = []
        transactions_db[user_id].extend(transactions)
        
        return jsonify({"message": "Transactions uploaded successfully.", "transactions": transactions}), 200

# 2. Get Transactions
@app.route('/get_transactions', methods=['GET'])
def get_transactions():
    user_id = request.args.get('user_id', 'default_user')
    transactions = transactions_db.get(user_id, [])
    return jsonify({"transactions": transactions}), 200

# 3. Generate Graph Data (category-wise spending in this example)
def generate_category_wise_data(transactions):
    category_data = {}
    for txn in transactions:
        category = txn.get("description", "Others")
        amount = txn.get("amount", 0)
        if category in category_data:
            category_data[category] += amount
        else:
            category_data[category] = amount
    return category_data

# 4. Get Graphs
@app.route('/get_graph', methods=['GET'])
def get_graph():
    user_id = request.args.get('user_id', 'default_user')
    transactions = transactions_db.get(user_id, [])
    if not transactions:
        return jsonify({"error": "No transactions found for the user."}), 404

    # Generate category-wise spending data
    category_data = generate_category_wise_data(transactions)

    # Plotting the data
    labels = list(category_data.keys())
    sizes = list(category_data.values())

    fig, ax = plt.subplots()
    ax.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)
    ax.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

    # Save the graph to a temporary file
    graph_path = os.path.join(tempfile.gettempdir(), str(uuid.uuid4()) + ".png")
    plt.savefig(graph_path)
    plt.close(fig)

    return send_file(graph_path, mimetype='image/png')

if __name__ == '__main__':
    app.run(debug=True, port=5000)
content_copyCOPY