Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
249 lines (206 loc) · 12.5 KB
/
Copy pathapp.py
File metadata and controls
249 lines (206 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
from flask import Flask, request, jsonify, Response
from flask_cors import CORS
from datetime import datetime
from dotenv import load_dotenv
from pathlib import Path
import csv, io, os, base64
# Explicitly point to the .env next to app.py — works regardless of cwd
load_dotenv(dotenv_path=Path(__file__).parent / '.env', override=True)
from google import genai as google_genai
from google.genai import types as genai_types
from google.genai.errors import ClientError
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "")
app = Flask(__name__)
CORS(app)
# Dummy Data for Hackathon Presentation
expenses = [
{"id": "1", "description": "D-Mart Groceries", "amount": 4500, "category": "Groceries", "date": "2026-03-12T10:30"},
{"id": "2", "description": "Swiggy Pizza", "amount": 450, "category": "Food", "date": "2026-03-14T19:45"},
{"id": "3", "description": "BESCOM Electricity", "amount": 1200, "category": "Bills", "date": "2026-03-15T09:15"},
{"id": "4", "description": "Metro Card Recharge", "amount": 500, "category": "Transport", "date": "2026-03-16T08:30"},
{"id": "5", "description": "Mutual Fund Auto-SIP", "amount": 5000, "category": "Savings", "date": "2026-03-19T10:00"},
{"id": "6", "description": "Myntra Summer Shirts", "amount": 1999, "category": "Shopping", "date": "2026-03-20T14:20"},
{"id": "7", "description": "Zomato Family Dinner", "amount": 1250, "category": "Food", "date": "2026-03-22T21:00"},
{"id": "8", "description": "Apollo Pharmacy Meds", "amount": 650, "category": "Health", "date": "2026-03-23T11:45"},
{"id": "9", "description": "Uber Office Ride", "amount": 450, "category": "Transport", "date": "2026-03-24T09:00"},
{"id": "10", "description": "Udemy Web Dev Course", "amount": 499, "category": "Education", "date": "2026-03-25T16:30"},
{"id": "11", "description": "Classmate Notebooks & Pens", "amount": 350, "category": "Stationeries", "date": "2026-03-25T18:00"},
{"id": "12", "description": "Netflix Subscription", "amount": 499, "category": "Entertainment", "date": "2026-03-26T08:00"}
]
# ── Add expense ────────────────────────────────────────────────────────────────
@app.route('/add_expense', methods=['POST'])
def add_expense():
data = request.json
data['date'] = datetime.now().strftime("%Y-%m-%d %H:%M")
expenses.append(data)
return jsonify({"message": "Expense added successfully!"})
# ── Get all expenses ───────────────────────────────────────────────────────────
@app.route('/get_expenses', methods=['GET'])
def get_expenses():
return jsonify(expenses)
# ── Delete expense ─────────────────────────────────────────────────────────────
@app.route('/delete_expense/<int:index>', methods=['DELETE'])
def delete_expense(index):
if 0 <= index < len(expenses):
expenses.pop(index)
return jsonify({"message": "Deleted!"})
return jsonify({"message": "Not found"}), 404
# ── AI Insight Engine ──────────────────────────────────────────────────────────
@app.route('/get_insights', methods=['GET'])
def get_insights():
if not expenses:
return jsonify({"insights": ["No expenses yet. Start adding your expenses!"], "total": 0, "category_totals": {}})
category_totals = {}
total = 0
now = datetime.now()
# For Week-over-Week comparison
from datetime import timedelta
this_week_totals = {}
last_week_totals = {}
for e in expenses:
cat = e.get('category', 'Other')
amt = float(e.get('amount', 0))
total += amt
category_totals[cat] = category_totals.get(cat, 0) + amt
# Calculate weekly totals if date is present
if 'date' in e and e['date']:
try:
date_obj = datetime.strptime(e['date'], "%Y-%m-%d %H:%M")
days_ago = (now - date_obj).days
if 0 <= days_ago < 7:
this_week_totals[cat] = this_week_totals.get(cat, 0) + amt
elif 7 <= days_ago < 14:
last_week_totals[cat] = last_week_totals.get(cat, 0) + amt
except ValueError:
pass
insights = []
top_category = max(category_totals, key=category_totals.get)
top_percent = round((category_totals[top_category] / total) * 100)
insights.append(f"🔴 You spent {top_percent}% of your total on {top_category} — ₹{category_totals[top_category]:.0f}")
if category_totals.get('Food', 0) > total * 0.4:
insights.append("⚠️ Food expenses are too high! Try cooking at home more often.")
if category_totals.get('Entertainment', 0) > total * 0.2:
insights.append("⚠️ You are overspending on Entertainment. Consider setting a limit.")
if category_totals.get('Transport', 0) > total * 0.3:
insights.append("⚠️ Transport costs are high. Consider carpooling or public transport.")
# Week over Week comparison & Unusual spending spikes
for cat, this_amt in this_week_totals.items():
last_amt = last_week_totals.get(cat, 0)
if last_amt > 0:
increase_pct = ((this_amt - last_amt) / last_amt) * 100
if increase_pct > 30:
insights.append(f"📈 Unusual Spending: You spent {increase_pct:.0f}% MORE on {cat} this week compared to last week (₹{this_amt:.0f} vs ₹{last_amt:.0f}).")
elif increase_pct < -20:
insights.append(f"📉 Great job! You spent {abs(increase_pct):.0f}% LESS on {cat} this week compared to last week.")
# ── Financial Philosophy Book Integration ──
books = []
# 1. The Richest Man in Babylon (Savings)
savings_amt = category_totals.get('Savings', 0)
if savings_amt > total * 0.05:
books.append("🏛️ *The Richest Man in Babylon:* You are practicing the golden rule—'A part of all you earn is yours to keep'. Excellent job saving!")
elif savings_amt == 0:
books.append("🏛️ *The Richest Man in Babylon:* 'Pay yourself first.' You have no savings recorded. Start saving a portion before spending!")
# 2. Rich Dad Poor Dad (Assets vs Liabilities)
if top_category in ["Shopping", "Entertainment", "Other"]:
books.append("📘 *Rich Dad Poor Dad:* 'The rich buy assets. The poor only have expenses.' Limit discretionary heavy spending and build assets.")
# 3. The Psychology of Money (Behavior vs Math)
if top_percent > 40:
books.append("🧠 *The Psychology of Money:* 'Wealth is what you don't see.' High spending in a single category is a behavioral leak. Try smoothing out your budget.")
# 4. Think and Grow Rich (Persistence)
if len(expenses) >= 10:
books.append("🏔️ *Think and Grow Rich:* 'Desire backed by faith knows no impossible.' Your persistence in tracking expenses is building the habits of actual wealth.")
insights.extend(books)
score = "Poor 🔴" if top_percent > 60 else ("Average 🟡" if top_percent > 40 else "Good 🟢")
insights.append(f"📊 Your Financial Health Score: {score}")
return jsonify({"insights": insights, "total": total, "category_totals": category_totals})
# ── Budget Predictor ───────────────────────────────────────────────────────────
@app.route('/predict_budget', methods=['GET'])
def predict_budget():
if not expenses:
return jsonify({"prediction": None, "message": "No expenses to predict from."})
now = datetime.now()
this_month = [e for e in expenses if e.get('date', '').startswith(now.strftime("%Y-%m"))]
if not this_month:
return jsonify({"prediction": None, "message": "No expenses this month yet."})
total_this_month = sum(float(e.get('amount', 0)) for e in this_month)
day_of_month = now.day
import calendar
days_in_month = calendar.monthrange(now.year, now.month)[1]
days_remaining = days_in_month - day_of_month
daily_avg = total_this_month / day_of_month
predicted_total = total_this_month + daily_avg * days_remaining
return jsonify({
"prediction": round(predicted_total, 2),
"spent_so_far": round(total_this_month, 2),
"daily_avg": round(daily_avg, 2),
"days_remaining": days_remaining,
"message": (
f"📅 You've spent ₹{total_this_month:.0f} in {day_of_month} days. "
f"At ₹{daily_avg:.0f}/day, you'll likely spend ₹{predicted_total:.0f} this month."
)
})
# ── Scan Receipt with Gemini Vision ───────────────────────────────────────────
@app.route('/scan_receipt', methods=['POST'])
def scan_receipt():
if not GEMINI_API_KEY or GEMINI_API_KEY == "your_gemini_api_key_here":
return jsonify({"error": "Gemini API key not configured in .env"}), 400
if 'image' not in request.files:
return jsonify({"error": "No image file provided"}), 400
image_file = request.files['image']
mime_type = image_file.content_type or 'image/jpeg'
img_bytes = image_file.read()
prompt = """
You are a smart expense analyzer. Look at this receipt/invoice carefully.
Identify the ACTUAL item purchased (e.g. "Furniture", "Coffee", "Nike Shoes", "Groceries") instead of just the shop name. If it's a long grocery list, simply write "Groceries - [Shop Name]".
Extract ONLY these 3 fields:
1. description: A short, accurate name for the actual expense/items
2. amount: The TOTAL amount in numbers only (e.g. 245.50)
3. category: Choose EXACTLY one from: Food, Transport, Bills, Entertainment, Shopping, Groceries, Stationeries, Health, Savings, Education, Other
Respond with ONLY a valid JSON object:
{"description": "...", "amount": 123.45, "category": "Food"}
"""
try:
client = google_genai.Client(api_key=GEMINI_API_KEY)
image_part = genai_types.Part.from_bytes(data=img_bytes, mime_type=mime_type)
response = client.models.generate_content(
model="models/gemini-2.0-flash-lite",
contents=[prompt, image_part]
)
raw = response.text.strip()
if raw.startswith("```"):
raw = raw.split("```")[1]
if raw.startswith("json"):
raw = raw[4:]
raw = raw.strip()
import json
result = json.loads(raw)
allowed_cats = [
"Food", "Transport", "Bills", "Entertainment", "Shopping",
"Groceries", "Stationeries", "Health", "Savings", "Education", "Other"
]
if result.get("category") not in allowed_cats:
result["category"] = "Other"
result["amount"] = float(result.get("amount", 0))
return jsonify(result)
except ClientError as e:
if e.code == 429:
return jsonify({"error": "QUOTA_EXCEEDED: You must create a new API key in a BRAND NEW Google Cloud Project to get a fresh free tier limit."}), 429
return jsonify({"error": f"Gemini scan failed: {str(e)}"}), 500
except Exception as e:
return jsonify({"error": f"Failed: {str(e)}"}), 500
# ── Export CSV ─────────────────────────────────────────────────────────────────
@app.route('/export_csv', methods=['GET'])
def export_csv():
output = io.StringIO()
writer = csv.writer(output)
writer.writerow(['Description', 'Amount (₹)', 'Category', 'Date'])
for e in expenses:
writer.writerow([e.get('description',''), e.get('amount',''), e.get('category',''), e.get('date','')])
return Response(output.getvalue(), mimetype='text/csv',
headers={"Content-Disposition": "attachment; filename=expenses.csv"})
# ── Health check ───────────────────────────────────────────────────────────────
@app.route('/')
def home():
return "Smart Expense Analyzer Backend is Running!"
if __name__ == '__main__':
app.run(debug=True)