-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
233 lines (167 loc) · 6.15 KB
/
Copy pathapp.py
File metadata and controls
233 lines (167 loc) · 6.15 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
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
from data_processor import process_csv
from agent import categorize_transactions, generate_financial_insight
from database import (
insert_expenses,
get_total_spent,
get_category_summary,
get_monthly_summary,
fetch_expenses_by_category
)
st.set_page_config(page_title="AI Expense Tracking Agent", layout="wide")
st.title("AI Expense Tracking Agent")
menu = st.sidebar.selectbox(
"Select Page",
["Upload Data", "Dashboard"]
)
# PAGE 1 — Upload Data
if menu == "Upload Data":
uploaded_file = st.file_uploader("Upload your expense CSV", type=["csv"])
if uploaded_file:
try:
try:
df = pd.read_csv(uploaded_file)
except:
df = pd.read_csv(uploaded_file, sep=";")
cleaned_df = process_csv(df)
with st.spinner("AI is categorizing transactions..."):
categorized_df = categorize_transactions(cleaned_df)
categorized_df = categorized_df.rename(columns={
"spent_on": "description",
"predicted_category": "category"
})
categorized_df["date"] = pd.to_datetime(
categorized_df["date"], errors="coerce"
).dt.date
categorized_df = categorized_df[
["date", "description", "amount", "category"]
]
st.dataframe(categorized_df.reset_index(drop=True))
inserted, skipped = insert_expenses(categorized_df)
st.success(f"{inserted} new records inserted.")
if skipped > 0:
st.info(f"{skipped} duplicate records skipped.")
except Exception as e:
st.error(f"Error: {e}")
# PAGE 2 — Dashboard
if menu == "Dashboard":
st.header("Financial Dashboard")
category_df_all = get_category_summary()
category_list = ["All"] + category_df_all["category"].tolist()
selected_category = st.selectbox("Filter by Category", category_list)
records_df = fetch_expenses_by_category(selected_category)
total_spent = get_total_spent(selected_category)
category_df = get_category_summary(selected_category)
monthly_df = get_monthly_summary(selected_category)
# TOTAL BUDGET
st.subheader("Monthly Budget Planning")
total_budget = st.number_input(
"Set Your Total Monthly Budget (PKR)",
min_value=0.0,
step=1000.0
)
col1, col2, col3 = st.columns(3)
col1.metric("Total Spending", f"PKR {total_spent:,.0f}")
col2.metric("Transactions", len(records_df))
if total_budget > 0:
remaining_total = total_budget - total_spent
col3.metric("Remaining Budget", f"PKR {remaining_total:,.0f}")
st.progress(min(total_spent / total_budget, 1.0))
st.divider()
# CHARTS
col4, col5 = st.columns(2)
with col4:
st.subheader("Monthly Spending Trend")
if not monthly_df.empty:
fig, ax = plt.subplots(figsize=(6, 4))
ax.plot(
monthly_df["month"],
monthly_df["total"],
marker="o",
linewidth=2
)
ax.set_title("Monthly Expense Trend")
ax.set_xlabel("Month")
ax.set_ylabel("Amount (PKR)")
ax.grid(True, linestyle="--", alpha=0.6)
plt.xticks(rotation=45)
plt.tight_layout()
st.pyplot(fig)
else:
st.info("No data available.")
with col5:
st.subheader("Spending by Category")
if not category_df.empty:
fig2, ax2 = plt.subplots(figsize=(6, 4))
ax2.bar(
category_df["category"],
category_df["total"]
)
ax2.set_title("Category Distribution")
ax2.set_xlabel("Category")
ax2.set_ylabel("Amount (PKR)")
ax2.grid(axis="y", linestyle="--", alpha=0.6)
plt.xticks(rotation=45)
plt.tight_layout()
st.pyplot(fig2)
else:
st.info("No data available.")
st.divider()
# AI Budget Distribution
if total_budget > 0 and not category_df_all.empty:
st.subheader("AI Suggested Budget Allocation")
total_historical_spent = category_df_all["total"].sum()
allocation_data = []
for _, row in category_df_all.iterrows():
category_name = row["category"]
category_spent = row["total"]
historical_ratio = (
category_spent / total_historical_spent
if total_historical_spent > 0 else 0
)
suggested_budget = historical_ratio * total_budget
remaining = suggested_budget - category_spent
usage_percent = (
(category_spent / suggested_budget) * 100
if suggested_budget > 0 else 0
)
allocation_data.append([
category_name,
round(suggested_budget, 0),
round(category_spent, 0),
round(remaining, 0),
round(usage_percent, 1)
])
allocation_df = pd.DataFrame(
allocation_data,
columns=[
"Category",
"AI Suggested Budget",
"Current Spending",
"Remaining",
"Usage %"
]
)
st.dataframe(
allocation_df,
use_container_width=True
)
st.divider()
# AI Insight
st.subheader("AI Financial Insight")
if "ai_insight" not in st.session_state:
st.session_state.ai_insight = None
if st.button("Generate AI Insight"):
if not records_df.empty:
with st.spinner("Analyzing your financial data..."):
st.session_state.ai_insight = generate_financial_insight(
total_spent,
category_df,
monthly_df
)
else:
st.session_state.ai_insight = "No data available for analysis."
if st.session_state.ai_insight:
st.success(st.session_state.ai_insight)