engralimalik commited on
Commit
118b9d7
·
verified ·
1 Parent(s): 0a44aa0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -35
app.py CHANGED
@@ -2,7 +2,27 @@ import pandas as pd
2
  import plotly.express as px
3
  import streamlit as st
4
  from transformers import pipeline
5
- import datetime
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
  # File upload
8
  uploaded_file = st.file_uploader("Upload your expense CSV file", type=["csv"])
@@ -12,11 +32,11 @@ if uploaded_file:
12
  # Display Dataframe
13
  st.write(df.head())
14
 
15
- # Initialize Hugging Face model for zero-shot classification
16
- classifier = pipeline('zero-shot-classification', model='distilbert-base-uncased')
17
  categories = ["Groceries", "Rent", "Utilities", "Entertainment", "Dining", "Transportation"]
18
 
19
- # Function to categorize
20
  def categorize_expense(description):
21
  result = classifier(description, candidate_labels=categories)
22
  return result['labels'][0] # Most probable category
@@ -24,6 +44,9 @@ if uploaded_file:
24
  # Apply categorization
25
  df['Category'] = df['Description'].apply(categorize_expense)
26
 
 
 
 
27
  # Sidebar for setting the monthly budget using sliders
28
  st.sidebar.header("Set Your Monthly Budget")
29
  groceries_budget = st.sidebar.slider("Groceries Budget", 0, 1000, 300)
@@ -43,49 +66,37 @@ if uploaded_file:
43
  "Transportation": transportation_budget
44
  }
45
 
46
- # Add a date slider for start and end date (default is the last month)
47
- today = datetime.date.today()
48
- last_month = today - pd.DateOffset(months=1)
49
- start_date = st.sidebar.date_input("Start Date", last_month)
50
- end_date = st.sidebar.date_input("End Date", today)
51
-
52
- # Filter data by date range
53
- df['Date'] = pd.to_datetime(df['Date'])
54
- df_filtered = df[(df['Date'] >= pd.to_datetime(start_date)) & (df['Date'] <= pd.to_datetime(end_date))]
55
-
56
  # Track if any category exceeds its budget
57
- df_filtered['Budget_Exceeded'] = df_filtered.apply(lambda row: row['Amount'] > budgets.get(row['Category'], 0), axis=1)
58
 
59
  # Show categories that exceeded their budget
60
- exceeded_budget = df_filtered[df_filtered['Budget_Exceeded'] == True]
61
  st.write("Categories that exceeded the budget:", exceeded_budget[['Date', 'Category', 'Amount']])
62
 
63
  # Visualizations
64
 
65
  # 1. Pie Chart for expense distribution by category
66
- category_expenses = df_filtered.groupby('Category')['Amount'].sum()
67
  fig1 = px.pie(category_expenses, values=category_expenses.values, names=category_expenses.index, title="Expense Distribution by Category")
68
  st.plotly_chart(fig1)
69
 
70
  # 2. Monthly Spending Trends (Line Chart)
71
- df_filtered['Month'] = df_filtered['Date'].dt.to_period('M').astype(str) # Convert Period to string for Plotly compatibility
72
- monthly_expenses = df_filtered.groupby('Month')['Amount'].sum()
 
73
 
74
- # Convert monthly_expenses into DataFrame for correct plotting
75
- monthly_expenses_df = monthly_expenses.reset_index()
76
- if not monthly_expenses_df.empty:
77
- fig2 = px.line(monthly_expenses_df, x='Month', y='Amount', title="Monthly Expenses", labels={"Month": "Month", "Amount": "Amount ($)"})
78
- st.plotly_chart(fig2)
79
- else:
80
- st.write("No data to display for the selected date range.")
81
 
82
  # 3. Monthly Spending vs Budget (Bar Chart)
83
- if not monthly_expenses_df.empty:
84
- monthly_expenses_df = pd.DataFrame({
85
- 'Actual': monthly_expenses,
86
- 'Budget': [sum(budgets.values())] * len(monthly_expenses) # Same budget for simplicity
87
- })
88
- fig3 = monthly_expenses_df.plot(kind='bar', figsize=(10, 6))
89
- st.pyplot(fig3)
90
- else:
91
- st.write("No data to display for the selected date range.")
 
 
 
2
  import plotly.express as px
3
  import streamlit as st
4
  from transformers import pipeline
5
+ import matplotlib.pyplot as plt
6
+
7
+ # Function to add custom background image from a URL
8
+ def add_bg_from_url(image_url):
9
+ st.markdown(
10
+ f"""
11
+ <style>
12
+ .stApp {{
13
+ background-image: url("{image_url}");
14
+ background-size: cover;
15
+ background-position: center center;
16
+ background-repeat: no-repeat;
17
+ }}
18
+ </style>
19
+ """,
20
+ unsafe_allow_html=True
21
+ )
22
+
23
+ # Add the background image using the provided URL
24
+ background_image_url = 'https://huggingface.co/spaces/engralimalik/Smart-Expense-Tracker/resolve/main/colorful-abstract-textured-background-design.jpg'
25
+ add_bg_from_url(background_image_url)
26
 
27
  # File upload
28
  uploaded_file = st.file_uploader("Upload your expense CSV file", type=["csv"])
 
32
  # Display Dataframe
33
  st.write(df.head())
34
 
35
+ # Initialize Hugging Face model for zero-shot classification (using a better model like roberta-large-mnli)
36
+ classifier = pipeline('zero-shot-classification', model='roberta-large-mnli')
37
  categories = ["Groceries", "Rent", "Utilities", "Entertainment", "Dining", "Transportation"]
38
 
39
+ # Function to categorize expenses based on the description
40
  def categorize_expense(description):
41
  result = classifier(description, candidate_labels=categories)
42
  return result['labels'][0] # Most probable category
 
44
  # Apply categorization
45
  df['Category'] = df['Description'].apply(categorize_expense)
46
 
47
+ # Display categorized data
48
+ st.write("Categorized Data", df)
49
+
50
  # Sidebar for setting the monthly budget using sliders
51
  st.sidebar.header("Set Your Monthly Budget")
52
  groceries_budget = st.sidebar.slider("Groceries Budget", 0, 1000, 300)
 
66
  "Transportation": transportation_budget
67
  }
68
 
 
 
 
 
 
 
 
 
 
 
69
  # Track if any category exceeds its budget
70
+ df['Budget_Exceeded'] = df.apply(lambda row: row['Amount'] > budgets.get(row['Category'], 0), axis=1)
71
 
72
  # Show categories that exceeded their budget
73
+ exceeded_budget = df[df['Budget_Exceeded'] == True]
74
  st.write("Categories that exceeded the budget:", exceeded_budget[['Date', 'Category', 'Amount']])
75
 
76
  # Visualizations
77
 
78
  # 1. Pie Chart for expense distribution by category
79
+ category_expenses = df.groupby('Category')['Amount'].sum()
80
  fig1 = px.pie(category_expenses, values=category_expenses.values, names=category_expenses.index, title="Expense Distribution by Category")
81
  st.plotly_chart(fig1)
82
 
83
  # 2. Monthly Spending Trends (Line Chart)
84
+ df['Date'] = pd.to_datetime(df['Date'])
85
+ df['Month'] = df['Date'].dt.to_period('M').astype(str) # Convert Period to string for Plotly compatibility
86
+ monthly_expenses = df.groupby('Month')['Amount'].sum()
87
 
88
+ fig2 = px.line(monthly_expenses, x=monthly_expenses.index, y=monthly_expenses.values, title="Monthly Expenses", labels={"x": "Month", "y": "Amount ($)"})
89
+ st.plotly_chart(fig2)
 
 
 
 
 
90
 
91
  # 3. Monthly Spending vs Budget (Bar Chart)
92
+ monthly_expenses_df = pd.DataFrame({
93
+ 'Actual': monthly_expenses,
94
+ 'Budget': [sum(budgets.values())] * len(monthly_expenses) # Same budget for simplicity
95
+ })
96
+
97
+ # Create a matplotlib figure for the bar chart
98
+ fig3, ax = plt.subplots(figsize=(10, 6))
99
+ monthly_expenses_df.plot(kind='bar', ax=ax)
100
+ ax.set_title('Monthly Spending vs Budget')
101
+ ax.set_ylabel('Amount ($)')
102
+ st.pyplot(fig3)