Dearsawan commited on
Commit
85e0fcf
·
verified ·
1 Parent(s): c995ce6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -56
app.py CHANGED
@@ -8,67 +8,56 @@ columns = ['Date', 'Category', 'Description', 'Amount']
8
  if 'expenses_df' not in st.session_state:
9
  st.session_state['expenses_df'] = pd.DataFrame(columns=columns)
10
 
11
- # Initialize a list for storing messages between user and bot
12
- if 'messages' not in st.session_state:
13
- st.session_state['messages'] = []
14
 
15
  # Function to add an expense
16
  def add_expense(date, category, description, amount):
17
  new_expense = pd.DataFrame([[date, category, description, amount]], columns=st.session_state['expenses_df'].columns)
18
  st.session_state['expenses_df'] = pd.concat([st.session_state['expenses_df'], new_expense], ignore_index=True)
19
 
20
- # Streamlit UI
21
- st.title("Daily Expense Tracker")
22
-
23
- # Display messages (chat history)
24
- for message in st.session_state['messages']:
25
- if message["role"] == "assistant":
26
- st.chat_message("assistant").markdown(message["content"])
27
- else:
28
- st.chat_message("user").markdown(message["content"])
29
-
30
- # User input for chatbot
31
- user_input = st.text_input("You:", key="user_input")
32
-
33
- if user_input:
34
- st.session_state['messages'].append({"role": "user", "content": user_input})
35
-
36
- # Get response from chatbot
37
- response = "I'm sorry, I didn't understand that."
38
- if "add" in user_input.lower() and "expense" in user_input.lower():
39
- st.session_state['messages'].append({"role": "assistant", "content": "Please enter the date of the expense."})
40
- response = "Please enter the date of the expense."
41
-
42
- elif "view" in user_input.lower():
43
- st.session_state['messages'].append({"role": "assistant", "content": str(st.session_state['expenses_df'])})
44
- response = "Here are all your expenses:\n" + str(st.session_state['expenses_df'])
45
-
46
- elif "summary" in user_input.lower():
47
- category_summary = st.session_state['expenses_df'].groupby('Category')['Amount'].sum().reset_index()
48
- st.session_state['messages'].append({"role": "assistant", "content": str(category_summary)})
49
- response = "Here is the expense summary by category:\n" + str(category_summary)
50
-
51
- elif "visualize" in user_input.lower():
52
- fig, ax = plt.subplots(figsize=(10, 6))
53
- sns.barplot(x='Category', y='Amount', data=st.session_state['expenses_df'], ax=ax)
54
- ax.set_title('Total Expenses by Category')
55
- ax.set_xlabel('Category')
56
- ax.set_ylabel('Amount Spent ($)')
57
- ax.set_xticklabels(ax.get_xticklabels(), rotation=45)
58
- st.pyplot(fig)
59
- response = "Here is the bar chart showing total expenses by category."
60
-
61
- st.session_state['messages'].append({"role": "assistant", "content": response})
62
-
63
- # Expense Addition Flow
64
- if st.session_state['messages'] and "Please enter the date of the expense." in st.session_state['messages'][-1].get("content", ""):
65
- date = st.date_input("Enter Expense Date")
66
- category = st.selectbox("Category", ['Food', 'Transport', 'Entertainment', 'Other'])
67
- description = st.text_input("Description")
68
- amount = st.number_input("Amount", min_value=0.0, format="%.2f")
69
 
70
- if st.button("Submit Expense"):
71
- add_expense(date, category, description, amount)
72
- st.session_state['messages'].append({"role": "assistant", "content": f"Expense added: {description} - ${amount:.2f}"})
73
- st.success(f"Added expense: {description} - ${amount:.2f}")
74
 
 
8
  if 'expenses_df' not in st.session_state:
9
  st.session_state['expenses_df'] = pd.DataFrame(columns=columns)
10
 
11
+ # Initialize the UI
12
+ st.title("Daily Expense Tracker")
 
13
 
14
  # Function to add an expense
15
  def add_expense(date, category, description, amount):
16
  new_expense = pd.DataFrame([[date, category, description, amount]], columns=st.session_state['expenses_df'].columns)
17
  st.session_state['expenses_df'] = pd.concat([st.session_state['expenses_df'], new_expense], ignore_index=True)
18
 
19
+ # Add some sample expenses (for testing purposes)
20
+ if st.button("Add Sample Expenses"):
21
+ add_expense('2024-12-01', 'Food', 'Lunch at restaurant', 15.50)
22
+ add_expense('2024-12-02', 'Transport', 'Uber ride', 20.00)
23
+ add_expense('2024-12-03', 'Entertainment', 'Movie ticket', 12.00)
24
+ add_expense('2024-12-04', 'Food', 'Grocery shopping', 35.75)
25
+ st.success("Sample expenses added.")
26
+
27
+ # Display expenses list
28
+ st.subheader("Expenses List")
29
+ st.write(st.session_state['expenses_df'])
30
+
31
+ # Generate summary by category
32
+ category_summary = st.session_state['expenses_df'].groupby('Category')['Amount'].sum().reset_index()
33
+
34
+ st.subheader("Category Summary")
35
+ st.write(category_summary)
36
+
37
+ # Visualize the expenses by category (Bar Chart)
38
+ st.subheader("Expense Visualization (Bar Chart)")
39
+ fig, ax = plt.subplots(figsize=(10, 6))
40
+ sns.barplot(x='Category', y='Amount', data=category_summary, ax=ax)
41
+ ax.set_title('Total Expenses by Category')
42
+ ax.set_xlabel('Category')
43
+ ax.set_ylabel('Amount Spent ($)')
44
+ ax.set_xticklabels(ax.get_xticklabels(), rotation=45)
45
+ st.pyplot(fig)
46
+
47
+ # Pie chart for category-wise expenses
48
+ st.subheader("Expense Distribution (Pie Chart)")
49
+ fig2, ax2 = plt.subplots(figsize=(8, 8))
50
+ category_summary.set_index('Category')['Amount'].plot(kind='pie', autopct='%1.1f%%', legend=False, ax=ax2)
51
+ ax2.set_title('Expense Distribution by Category')
52
+ ax2.set_ylabel('') # Hide ylabel
53
+ st.pyplot(fig2)
54
+
55
+ # Option to save the expenses to a CSV file
56
+ st.download_button(
57
+ label="Download Expenses as CSV",
58
+ data=st.session_state['expenses_df'].to_csv(index=False),
59
+ file_name="expenses.csv",
60
+ mime="text/csv"
61
+ )
 
 
 
 
 
 
62
 
 
 
 
 
63