Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,72 +1,93 @@
|
|
| 1 |
-
import
|
| 2 |
import pandas as pd
|
| 3 |
-
import numpy as np
|
| 4 |
import matplotlib.pyplot as plt
|
| 5 |
from transformers import pipeline
|
| 6 |
import plotly.express as px
|
| 7 |
|
| 8 |
-
# Initialize
|
| 9 |
-
expense_classifier = pipeline(
|
|
|
|
| 10 |
|
| 11 |
-
#
|
| 12 |
-
|
| 13 |
-
candidate_labels = ["Groceries", "Entertainment", "Rent", "Utilities", "Dining", "Transportation", "Shopping", "Others"]
|
| 14 |
-
return [expense_classifier(description, candidate_labels)["labels"][0] for description in descriptions]
|
| 15 |
|
| 16 |
-
# Function to
|
| 17 |
-
def
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
# Check if required columns are present
|
| 22 |
-
if 'Date' not in df.columns or 'Description' not in df.columns or 'Amount' not in df.columns:
|
| 23 |
-
return "CSV file should contain 'Date', 'Description', and 'Amount' columns."
|
| 24 |
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
# 2. Monthly spending trends (Line plot)
|
| 34 |
-
df['Date'] = pd.to_datetime(df['Date'])
|
| 35 |
-
df['Month'] = df['Date'].dt.to_period('M')
|
| 36 |
-
monthly_spending = df.groupby('Month')['Amount'].sum()
|
| 37 |
-
fig2 = px.line(monthly_spending, x=monthly_spending.index, y=monthly_spending.values, title="Monthly Spending Trends")
|
| 38 |
-
|
| 39 |
-
# 3. Budget vs Actual Spending (Bar chart)
|
| 40 |
-
category_list = df['Category'].unique()
|
| 41 |
-
budget_dict = {category: 500 for category in category_list} # Default budget is 500 for each category
|
| 42 |
-
budget_spending = {category: [budget_dict[category], category_spending.get(category, 0)] for category in category_list}
|
| 43 |
-
budget_df = pd.DataFrame(budget_spending, index=["Budget", "Actual"]).T
|
| 44 |
-
fig3 = px.bar(budget_df, x=budget_df.index, y=["Budget", "Actual"], title="Budget vs Actual Spending")
|
| 45 |
-
|
| 46 |
-
# 4. Suggested savings (only calculate if over budget)
|
| 47 |
-
savings_tips = []
|
| 48 |
-
for category, actual in category_spending.items():
|
| 49 |
-
if actual > budget_dict.get(category, 500):
|
| 50 |
-
savings_tips.append(f"- **{category}**: Over budget by ${actual - budget_dict.get(category, 500)}. Consider reducing this expense.")
|
| 51 |
-
|
| 52 |
-
return df.head(), fig1, fig2, fig3, savings_tips
|
| 53 |
|
| 54 |
-
#
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
gr.Dataframe(label="Categorized Expense Data"),
|
| 58 |
-
gr.Plot(label="Category-wise Spending (Pie Chart)"),
|
| 59 |
-
gr.Plot(label="Monthly Spending Trends (Line Chart)"),
|
| 60 |
-
gr.Plot(label="Budget vs Actual Spending (Bar Chart)"),
|
| 61 |
-
gr.Textbox(label="Savings Tips")
|
| 62 |
-
]
|
| 63 |
|
| 64 |
-
#
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
import pandas as pd
|
|
|
|
| 3 |
import matplotlib.pyplot as plt
|
| 4 |
from transformers import pipeline
|
| 5 |
import plotly.express as px
|
| 6 |
|
| 7 |
+
# Initialize Hugging Face model pipelines for categorization and question-answering
|
| 8 |
+
expense_classifier = pipeline('zero-shot-classification', model='distilbert-base-uncased')
|
| 9 |
+
qa_model = pipeline('question-answering', model='distilbert-base-uncased-distilled-squad')
|
| 10 |
|
| 11 |
+
# List of possible expense categories
|
| 12 |
+
categories = ["Groceries", "Rent", "Utilities", "Entertainment", "Dining", "Transportation", "Salary"]
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
# Function to categorize transactions
|
| 15 |
+
def categorize_expense(description):
|
| 16 |
+
result = expense_classifier(description, candidate_labels=categories)
|
| 17 |
+
return result['labels'][0] # Choose the most probable category
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
+
# Streamlit UI
|
| 20 |
+
st.title("Smart Expense Tracker")
|
| 21 |
+
st.write("""
|
| 22 |
+
Upload a CSV file containing your transaction data, and this app will categorize your expenses, visualize trends,
|
| 23 |
+
and provide insights on your spending habits.
|
| 24 |
+
""")
|
| 25 |
|
| 26 |
+
# Upload CSV file
|
| 27 |
+
uploaded_file = st.file_uploader("Upload your CSV file", type=["csv"])
|
| 28 |
+
if uploaded_file is not None:
|
| 29 |
+
df = pd.read_csv(uploaded_file)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
+
# Display the first few rows of the data
|
| 32 |
+
st.subheader("Transaction Data")
|
| 33 |
+
st.dataframe(df.head())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
+
# Check if 'Description', 'Amount', and 'Date' columns exist in the file
|
| 36 |
+
if 'Description' in df.columns and 'Amount' in df.columns and 'Date' in df.columns:
|
| 37 |
+
# Categorize expenses
|
| 38 |
+
df['Category'] = df['Description'].apply(categorize_expense)
|
| 39 |
+
|
| 40 |
+
# Visualizations
|
| 41 |
+
st.subheader("Expense Distribution by Category (Pie Chart)")
|
| 42 |
+
category_expenses = df.groupby('Category')['Amount'].sum()
|
| 43 |
+
fig1 = px.pie(category_expenses, names=category_expenses.index, values=category_expenses.values, title="Category-wise Spending")
|
| 44 |
+
st.plotly_chart(fig1)
|
| 45 |
+
|
| 46 |
+
# Monthly spending trends (Line Chart)
|
| 47 |
+
df['Date'] = pd.to_datetime(df['Date'])
|
| 48 |
+
df['Month'] = df['Date'].dt.to_period('M')
|
| 49 |
+
monthly_expenses = df.groupby('Month')['Amount'].sum()
|
| 50 |
+
st.subheader("Monthly Spending Trends")
|
| 51 |
+
fig2 = px.line(monthly_expenses, x=monthly_expenses.index, y=monthly_expenses.values, title="Monthly Spending")
|
| 52 |
+
st.plotly_chart(fig2)
|
| 53 |
+
|
| 54 |
+
# Budget vs Actual Spending (Bar Chart)
|
| 55 |
+
budgets = {
|
| 56 |
+
"Groceries": 300,
|
| 57 |
+
"Rent": 1000,
|
| 58 |
+
"Utilities": 150,
|
| 59 |
+
"Entertainment": 100,
|
| 60 |
+
"Dining": 150,
|
| 61 |
+
"Transportation": 120,
|
| 62 |
+
}
|
| 63 |
+
budget_df = pd.DataFrame({
|
| 64 |
+
'Actual': monthly_expenses,
|
| 65 |
+
'Budget': [sum(budgets.values())] * len(monthly_expenses)
|
| 66 |
+
})
|
| 67 |
+
st.subheader("Monthly Spending vs Budget")
|
| 68 |
+
fig3 = px.bar(budget_df, x=budget_df.index, y=["Actual", "Budget"], title="Budget vs Actual Spending")
|
| 69 |
+
st.plotly_chart(fig3)
|
| 70 |
+
|
| 71 |
+
# Savings Tips (Alert if exceeding budget)
|
| 72 |
+
st.subheader("Savings Tips")
|
| 73 |
+
savings_tips = []
|
| 74 |
+
category_expenses = df.groupby("Category")['Amount'].sum()
|
| 75 |
+
for category, actual in category_expenses.items():
|
| 76 |
+
if actual > budgets.get(category, 0):
|
| 77 |
+
savings_tips.append(f"- **{category}**: Over budget by ${actual - budgets.get(category, 0)}. Consider reducing this expense.")
|
| 78 |
+
if savings_tips:
|
| 79 |
+
for tip in savings_tips:
|
| 80 |
+
st.write(tip)
|
| 81 |
+
else:
|
| 82 |
+
st.write("No categories exceeded their budget.")
|
| 83 |
+
|
| 84 |
+
# Question Answering Feature
|
| 85 |
+
st.subheader("Ask Questions About Your Expenses")
|
| 86 |
+
question = st.text_input("Ask a question about your expenses (e.g., 'How much did I spend on groceries?')")
|
| 87 |
+
if question:
|
| 88 |
+
knowledge_base = "\n".join(df.apply(lambda row: f"Description: {row['Description']}, Amount: {row['Amount']}, Category: {row['Category']}", axis=1))
|
| 89 |
+
answer = qa_model(question=question, context=knowledge_base)
|
| 90 |
+
st.write(f"Answer: {answer['answer']}")
|
| 91 |
+
|
| 92 |
+
else:
|
| 93 |
+
st.error("CSV file should contain 'Description', 'Amount', and 'Date' columns.")
|