Dearsawan commited on
Commit
604aca4
·
verified ·
1 Parent(s): 3b021e6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -62
app.py CHANGED
@@ -2,81 +2,73 @@ import streamlit as st
2
  import pandas as pd
3
  import matplotlib.pyplot as plt
4
  import seaborn as sns
5
- import requests
6
  # Create an empty DataFrame for expenses
7
  columns = ['Date', 'Category', 'Description', 'Amount']
8
- expenses_df = pd.DataFrame(columns=columns)
9
-
10
- # Streamlit app layout
11
- st.title('Expense Tracker')
12
-
13
- # Add new expense entry
14
- st.subheader("Add New Expense")
15
 
16
- date = st.date_input("Date")
17
- category = st.selectbox("Category", ['Food', 'Transport', 'Entertainment', 'Other'])
18
- description = st.text_input("Description")
19
- amount = st.number_input("Amount", min_value=0.0, format="%.2f")
20
 
21
- if st.button("Add Expense"):
22
- new_expense = pd.DataFrame([[date, category, description, amount]], columns=expenses_df.columns)
23
- expenses_df = pd.concat([expenses_df, new_expense], ignore_index=True)
24
- st.success(f"Added expense: {description} - ${amount:.2f}")
25
 
26
- # Display all expenses
27
- st.subheader("Expenses List")
28
- st.write(expenses_df)
29
 
30
- # Ensure 'Amount' is numeric (convert if necessary)
31
- expenses_df['Amount'] = pd.to_numeric(expenses_df['Amount'], errors='coerce')
 
 
 
 
32
 
33
- # Show category summary
34
- st.subheader("Category Summary")
35
- category_summary = expenses_df.groupby('Category')['Amount'].sum().reset_index()
36
- st.write(category_summary)
37
 
38
- # Generate individual bar and pie charts per Description
39
- st.subheader("Bar Charts and Pie Charts per Description")
40
 
41
- # Get all unique descriptions
42
- unique_descriptions = expenses_df['Description'].unique()
 
 
 
43
 
44
- # Loop through each unique description to plot bar and pie charts
45
- for description in unique_descriptions:
46
- description_df = expenses_df[expenses_df['Description'] == description]
47
 
48
- # Plot bar chart for each description
49
- fig, ax = plt.subplots(figsize=(10, 6))
50
- sns.barplot(x='Category', y='Amount', data=description_df, ax=ax)
51
- ax.set_title(f'Total Expenses for: {description}')
52
- ax.set_xlabel('Category')
53
- ax.set_ylabel('Amount Spent ($)')
54
- ax.set_xticklabels(ax.get_xticklabels(), rotation=45)
55
- st.pyplot(fig)
56
 
57
- # Plot pie chart for each description
58
- fig, ax = plt.subplots(figsize=(8, 8))
59
- description_summary = description_df.groupby('Category')['Amount'].sum().reset_index()
60
- description_summary.set_index('Category')['Amount'].plot(kind='pie', autopct='%1.1f%%', legend=False, ax=ax)
61
- ax.set_title(f'Expense Distribution for: {description}')
62
- ax.set_ylabel('') # Hide ylabel
63
- st.pyplot(fig)
 
 
64
 
65
- # Save the expenses to a CSV file
66
- st.download_button(
67
- label="Download Expenses as CSV",
68
- data=expenses_df.to_csv(index=False),
69
- file_name="expenses.csv",
70
- mime="text/csv"
71
- )
72
 
73
- # Example of making an API call using the API Key (optional, depending on your use case)
74
- api_url = "https://example.com/api/data"
75
- headers = {"Authorization": f"Bearer {API_KEY}"}
 
 
 
76
 
77
- response = requests.get(api_url, headers=headers)
 
 
 
78
 
79
- if response.status_code == 200:
80
- st.write("API Data:", response.json()) # Display data from API response
81
- else:
82
- st.error("Failed to fetch data from API")
 
2
  import pandas as pd
3
  import matplotlib.pyplot as plt
4
  import seaborn as sns
5
+
6
  # Create an empty DataFrame for expenses
7
  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