engralimalik commited on
Commit
a6ee9ca
·
verified ·
1 Parent(s): 73fd7e1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -61
app.py CHANGED
@@ -1,72 +1,93 @@
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 (use zero-shot classification)
9
- expense_classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
 
10
 
11
- # Batch categorization function for efficiency
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
- # Read CSV data
19
- df = pd.read_csv(file.name)
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
- # Categorize the expenses (using batch processing to minimize model calls)
26
- df['Category'] = categorize_transaction_batch(df['Description'].tolist())
 
 
 
 
27
 
28
- # Create visualizations:
29
- # 1. Pie chart for Category-wise spending
30
- category_spending = df.groupby("Category")['Amount'].sum()
31
- fig1 = px.pie(category_spending, names=category_spending.index, values=category_spending.values, title="Category-wise Spending")
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
- # Gradio interface definition
55
- inputs = gr.File(label="Upload Expense CSV")
56
- outputs = [
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
- # Launch Gradio interface
65
- gr.Interface(
66
- fn=process_expenses,
67
- inputs=inputs,
68
- outputs=outputs,
69
- live=True,
70
- title="Smart Expense Tracker",
71
- description="Upload your CSV of transactions, categorize them, and view insights like spending trends and budget analysis."
72
- ).launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.")