engralimalik commited on
Commit
2c359f1
·
verified ·
1 Parent(s): a477cd2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -82
app.py CHANGED
@@ -1,91 +1,70 @@
1
- import streamlit as st
2
  import pandas as pd
3
  import numpy as np
4
  import matplotlib.pyplot as plt
5
- import seaborn as sns
6
  from transformers import pipeline
7
- from io import StringIO
8
 
9
- # Streamlit page configuration
10
- st.set_page_config(page_title="Smart Expense Tracker", page_icon=":money_with_wings:")
11
 
12
- # Title
13
- st.title("Smart Expense Tracker :money_with_wings:")
 
 
14
 
15
- # File uploader to upload CSV
16
- st.sidebar.header("Upload your expense data")
17
- uploaded_file = st.sidebar.file_uploader("Choose a CSV file", type=["csv"])
18
 
19
- # Check if file is uploaded
20
- if uploaded_file is not None:
21
- # Read CSV
22
- df = pd.read_csv(uploaded_file)
23
-
24
- # Display first few rows of the uploaded data
25
- st.write("### Uploaded Data", df.head())
26
-
27
- # Ensure correct column names
28
  if 'Date' not in df.columns or 'Description' not in df.columns or 'Amount' not in df.columns:
29
- st.error("CSV file should contain 'Date', 'Description', and 'Amount' columns.")
30
- else:
31
- # Initialize Hugging Face pipeline for text classification (expense categorization)
32
- expense_classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
33
-
34
- # Function to categorize transactions
35
- def categorize_transaction_batch(descriptions):
36
- candidate_labels = ["Groceries", "Entertainment", "Rent", "Utilities", "Dining", "Transportation", "Shopping", "Others"]
37
- return [expense_classifier(description, candidate_labels)["labels"][0] for description in descriptions]
38
-
39
- # Batch process all descriptions at once for efficiency
40
- df['Category'] = categorize_transaction_batch(df['Description'].tolist())
41
-
42
- # Show categorized data
43
- st.write("### Categorized Expense Data", df.head())
44
-
45
- # Visualizations
46
-
47
- # Optimized Pie chart for Category-wise spending
48
- category_spending = df.groupby("Category")['Amount'].sum()
49
- st.write("### Category-wise Spending")
50
- fig, ax = plt.subplots(figsize=(8, 8))
51
- category_spending.plot(kind='pie', autopct='%1.1f%%', ax=ax)
52
- ax.set_ylabel('')
53
- st.pyplot(fig)
54
-
55
- # Optimized Monthly spending trends (Line plot)
56
- df['Date'] = pd.to_datetime(df['Date'])
57
- df['Month'] = df['Date'].dt.to_period('M')
58
- monthly_spending = df.groupby('Month')['Amount'].sum()
59
-
60
- st.write("### Monthly Spending Trends")
61
- fig, ax = plt.subplots(figsize=(10, 6))
62
- monthly_spending.plot(kind='line', ax=ax)
63
- ax.set_ylabel('Amount ($)')
64
- ax.set_xlabel('Month')
65
- ax.set_title('Monthly Spending Trends')
66
- st.pyplot(fig)
67
-
68
- # Optimized Budget Tracker
69
- st.sidebar.header("Budget Tracker")
70
- category_list = df['Category'].unique()
71
- budget_dict = {category: st.sidebar.number_input(f"Set budget for {category}", min_value=0, value=500) for category in category_list}
72
-
73
- # Optimized Budget vs Actual Spending (Bar chart)
74
- st.write("### Budget vs Actual Spending")
75
- budget_spending = {category: [budget_dict.get(category, 500), category_spending.get(category, 0)] for category in category_list}
76
- budget_df = pd.DataFrame(budget_spending, index=["Budget", "Actual"]).T
77
-
78
- fig, ax = plt.subplots(figsize=(10, 6))
79
- budget_df.plot(kind='bar', ax=ax)
80
- ax.set_ylabel('Amount ($)')
81
- ax.set_title('Budget vs Actual Spending')
82
- st.pyplot(fig)
83
-
84
- # Suggestions for saving
85
- st.write("### Suggested Savings Tips")
86
- for category, actual in category_spending.items():
87
- if actual > budget_dict.get(category, 500):
88
- st.write(f"- **{category}**: Over budget by ${actual - budget_dict.get(category, 500)}. Consider reducing this expense.")
89
-
90
- else:
91
- st.write("Upload a CSV file to start tracking your expenses!")
 
1
+ import gradio as gr
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 the Hugging Face model for expense categorization
9
+ expense_classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
10
 
11
+ # Function to categorize expenses
12
+ def categorize_transaction_batch(descriptions):
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 process the uploaded CSV and generate visualizations
17
+ def process_expenses(file):
18
+ df = pd.read_csv(file.name)
19
 
20
+ # Check required columns
 
 
 
 
 
 
 
 
21
  if 'Date' not in df.columns or 'Description' not in df.columns or 'Amount' not in df.columns:
22
+ return "CSV file should contain 'Date', 'Description', and 'Amount' columns."
23
+
24
+ # Categorize the expenses
25
+ df['Category'] = categorize_transaction_batch(df['Description'].tolist())
26
+
27
+ # Pie chart for Category-wise spending
28
+ category_spending = df.groupby("Category")['Amount'].sum()
29
+ fig1 = px.pie(category_spending, names=category_spending.index, values=category_spending.values, title="Category-wise Spending")
30
+
31
+ # Monthly spending trends (Line plot)
32
+ df['Date'] = pd.to_datetime(df['Date'])
33
+ df['Month'] = df['Date'].dt.to_period('M')
34
+ monthly_spending = df.groupby('Month')['Amount'].sum()
35
+ fig2 = px.line(monthly_spending, x=monthly_spending.index, y=monthly_spending.values, title="Monthly Spending Trends")
36
+
37
+ # Budget vs Actual Spending (Bar chart)
38
+ category_list = df['Category'].unique()
39
+ budget_dict = {category: 500 for category in category_list} # Set default budget of 500 for each category
40
+ budget_spending = {category: [budget_dict[category], category_spending.get(category, 0)] for category in category_list}
41
+ budget_df = pd.DataFrame(budget_spending, index=["Budget", "Actual"]).T
42
+ fig3 = px.bar(budget_df, x=budget_df.index, y=["Budget", "Actual"], title="Budget vs Actual Spending")
43
+
44
+ # Suggested savings
45
+ savings_tips = []
46
+ for category, actual in category_spending.items():
47
+ if actual > budget_dict.get(category, 500):
48
+ savings_tips.append(f"- **{category}**: Over budget by ${actual - budget_dict.get(category, 500)}. Consider reducing this expense.")
49
+
50
+ return df.head(), fig1, fig2, fig3, savings_tips
51
+
52
+ # Gradio interface definition
53
+ inputs = gr.inputs.File(label="Upload Expense CSV", type="file")
54
+ outputs = [
55
+ gr.outputs.Dataframe(label="Categorized Expense Data"),
56
+ gr.outputs.Plotly(label="Category-wise Spending (Pie Chart)"),
57
+ gr.outputs.Plotly(label="Monthly Spending Trends (Line Chart)"),
58
+ gr.outputs.Plotly(label="Budget vs Actual Spending (Bar Chart)"),
59
+ gr.outputs.Textbox(label="Savings Tips")
60
+ ]
61
+
62
+ # Launch Gradio interface
63
+ gr.Interface(
64
+ fn=process_expenses,
65
+ inputs=inputs,
66
+ outputs=outputs,
67
+ live=True,
68
+ title="Smart Expense Tracker",
69
+ description="Upload your CSV of transactions, categorize them, and view insights like spending trends and budget analysis."
70
+ ).launch()