ClarzW commited on
Commit
f2bbca4
·
verified ·
1 Parent(s): 2c6a6ec

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -38
app.py CHANGED
@@ -1,28 +1,36 @@
1
  import streamlit as st
2
  import pandas as pd
3
  import matplotlib.pyplot as plt
4
- import matplotlib.dates as mdates
5
  import seaborn as sns
6
  import os
7
 
 
 
8
  DATA_FILE = 'expenses.csv'
9
 
 
 
 
10
  def load_data():
11
  '''
12
  Reads the CSV file saved within HuggingFace storage. If not found, then creates a dataframe to be used for storing expense data
13
  '''
14
  try:
 
15
  return pd.read_csv(DATA_FILE)
16
  except FileNotFoundError:
 
17
  return pd.DataFrame(columns=['Date', 'Category', 'Amount', 'Description'])
18
 
 
19
  def save_data(df):
20
  '''
21
  Saves the expenses dataframe to HuggingFace storage
22
  '''
23
  df.to_csv(DATA_FILE, index=False)
 
24
 
25
- # Add categories as required (TO-DO: Add input to append to this list? Might be too complicated for 30 minutes)
26
  categories = ['Food', 'Transport', 'Bills', 'Entertainment', 'Other']
27
 
28
 
@@ -34,94 +42,148 @@ if 'file_processed' not in st.session_state:
34
  st.session_state['file_processed'] = False
35
 
36
 
 
 
 
37
  st.title("Expense Tracker")
38
 
 
39
  st.markdown("""
40
  ## Instructions
41
  - Welcome! This is an app used to track your expenses.
42
  - You can import data from a csv file for previous data, or you can add each expense separately through the form on this app.
43
  - There is a "Download Expenses as CSV" button. This is highly recommended, as the CSV will not be saved if the app sleeps or is restarted. You can import the data again afterwards.
44
- - There is a "Visualise Data" button. This allows you to see graphs that will show how you are spending your money.
45
  """)
46
 
47
  st.write("")
48
 
49
- col1, col2 = st.columns([2,1])
 
50
 
51
  with col1:
52
 
53
- # Upload file from computer and not HuggingFace
54
  uploaded_file = st.file_uploader("Import Expense Data", type="csv")
55
-
 
56
  if uploaded_file is not None and not st.session_state['file_processed']:
57
- # Check the file type based on the MIME type
58
- if uploaded_file.name.endswith('.csv'):
 
59
  new_data = pd.read_csv(uploaded_file)
60
-
61
- st.session_state['expenses'] = pd.concat([st.session_state['expenses'], new_data], ignore_index=True)
62
-
63
- save_data(st.session_state['expenses']) # Ensures the HuggingFace storage contains this version
64
- st.success("CSV file successfully uploaded!")
 
 
 
 
65
 
66
- st.session_state['file_processed'] = True
 
67
 
68
- else:
69
- st.error("File type is not supported. Please upload a CSV file.")
 
 
 
70
 
71
- with col2:
72
- csv = st.session_state['expenses'].to_csv(index=False).encode("utf-8")
 
 
 
 
 
73
 
 
 
74
  st.write("")
75
  st.write("")
76
  st.write("")
77
-
 
 
 
 
78
  st.download_button(
79
- label = "Export Expenses as CSV",
80
- data = csv,
81
- file_name = "expenses.csv",
82
- mime = "text/csv"
83
  )
84
 
85
 
86
  with st.form("expense_form"):
 
87
  amount = st.number_input("Amount", format="%0.2f", min_value=0.01)
 
 
88
  category = st.selectbox("Category", categories)
 
 
89
  description = st.text_input("Description")
 
 
90
  date = st.date_input("Date")
91
 
 
92
  submit = st.form_submit_button("Add Expense")
93
 
94
  if submit:
 
95
  new_expense = pd.DataFrame({
96
  'Date': [date],
97
  'Category': [category],
98
  'Amount': [amount],
99
  'Description': [description]
100
  })
 
 
101
  st.session_state['expenses'] = pd.concat([st.session_state['expenses'], new_expense], ignore_index=True)
102
- save_data(st.session_state['expenses']) # Save data after adding a new expense, maybe better to have button for saving data?
 
 
 
 
103
  st.success("Expense added successfully!")
 
104
 
105
-
106
-
107
-
108
  if not st.session_state['expenses'].empty:
109
  st.subheader("Current Expenses")
 
 
110
  display_df = st.session_state['expenses'].copy()
 
 
111
  display_df['Date'] = display_df['Date'].astype(str)
 
 
112
  st.dataframe(display_df)
 
113
  else:
 
114
  st.write("No expenses yet.")
115
 
 
 
116
  viz_button = st.button("Visualise Data")
117
 
118
  if viz_button:
119
-
120
  if not st.session_state['expenses'].empty:
121
-
 
122
  st.subheader("Expense Summary")
 
 
123
  category_summary = st.session_state['expenses'].groupby('Category')['Amount'].sum().reset_index()
124
-
 
125
  fig, ax = plt.subplots(figsize=(10,6))
126
  sns.barplot(y='Category', x='Amount', data=category_summary, ax=ax) # Horizontal bar plot
127
  ax.set_title("Total Expenses by Category", pad=20) # Title for the bar plot
@@ -130,24 +192,29 @@ if viz_button:
130
  # Adding labels to each bar
131
  for index, value in enumerate(category_summary['Amount']):
132
  ax.text(value + 0.05, index, f'{value:.2f}', va='center')
133
-
 
134
  st.pyplot(fig)
135
 
136
 
137
- # Expenses Over Time Line Chart with Title, Labels, and Point Labels
138
  st.subheader("Expenses Over Time")
139
 
 
140
  monthly_df = st.session_state['expenses'].copy()
141
 
 
142
  monthly_df['Date'] = pd.to_datetime(monthly_df['Date'])
143
-
 
144
  monthly_df = monthly_df.sort_values(by = 'Date')
145
 
 
146
  dates = monthly_df['Date']
147
  expenses = monthly_df['Amount']
148
 
149
 
150
- # Create a figure
151
  fig, ax = plt.subplots()
152
 
153
  # Plot the data
@@ -158,13 +225,12 @@ if viz_button:
158
  ax.set_ylabel('Amount')
159
  ax.set_xlabel('Date')
160
 
 
161
  plt.xticks(rotation=45)
162
 
 
163
  st.pyplot(fig)
164
 
165
  else:
 
166
  st.write("No data to visualise.")
167
-
168
-
169
-
170
-
 
1
  import streamlit as st
2
  import pandas as pd
3
  import matplotlib.pyplot as plt
 
4
  import seaborn as sns
5
  import os
6
 
7
+
8
+ # Define the path for reading CSV file
9
  DATA_FILE = 'expenses.csv'
10
 
11
+
12
+ # Functions
13
+
14
  def load_data():
15
  '''
16
  Reads the CSV file saved within HuggingFace storage. If not found, then creates a dataframe to be used for storing expense data
17
  '''
18
  try:
19
+ # Attempt to load CSV file
20
  return pd.read_csv(DATA_FILE)
21
  except FileNotFoundError:
22
+ # Return empty DataFrame with specified columns if file is not found
23
  return pd.DataFrame(columns=['Date', 'Category', 'Amount', 'Description'])
24
 
25
+
26
  def save_data(df):
27
  '''
28
  Saves the expenses dataframe to HuggingFace storage
29
  '''
30
  df.to_csv(DATA_FILE, index=False)
31
+
32
 
33
+ # List of categories for the expense tracker
34
  categories = ['Food', 'Transport', 'Bills', 'Entertainment', 'Other']
35
 
36
 
 
42
  st.session_state['file_processed'] = False
43
 
44
 
45
+
46
+
47
+ # Front End Design
48
  st.title("Expense Tracker")
49
 
50
+ # Instructions and overview for the user
51
  st.markdown("""
52
  ## Instructions
53
  - Welcome! This is an app used to track your expenses.
54
  - You can import data from a csv file for previous data, or you can add each expense separately through the form on this app.
55
  - There is a "Download Expenses as CSV" button. This is highly recommended, as the CSV will not be saved if the app sleeps or is restarted. You can import the data again afterwards.
56
+ - There is a "Visualise Data" button. This allows you to see graphs showing how you are spending your money.
57
  """)
58
 
59
  st.write("")
60
 
61
+ # Creates two columns, so importing and exporting files are displayed side by side
62
+ col1, col2 = st.columns([2,1]) # col1 takes up twice the width of col2
63
 
64
  with col1:
65
 
66
+ # Upload file from user's computer
67
  uploaded_file = st.file_uploader("Import Expense Data", type="csv")
68
+
69
+ # Checks if a file is uploaded and if it hasn't already been processed
70
  if uploaded_file is not None and not st.session_state['file_processed']:
71
+
72
+ try:
73
+ # Read the uploaded CSV file into a DataFrame
74
  new_data = pd.read_csv(uploaded_file)
75
+
76
+ # Expected column names to validate the structure of CSV
77
+ expected columns = ['Date', 'Category', 'Amount', 'Description']
78
+
79
+ # Check if the uploaded CSV has the required columns
80
+ if list(new_data.columns) == expected_columns:
81
+
82
+ # Append new data into existing 'expenses' DataFrame in session_state
83
+ st.session_state['expenses'] = pd.concat([st.session_state['expenses'], new_data], ignore_index=True)
84
 
85
+ # Save the updated 'expenses' DataFrame to HuggingFace storage
86
+ save_data(st.session_state['expenses'])
87
 
88
+ # Display a success message to the user after successful upload
89
+ st.success("CSV file successfully uploaded!")
90
+
91
+ # Mark the file as processed, so that when page refreshes this block of code does not run again
92
+ st.session_state['file_processed'] = True
93
 
94
+ else:
95
+ #Show an error if the CSV columns do not match the expected format
96
+ st.error(f"Invalid CSV format. Expected columns: {expected_columns}")
97
+
98
+ except Exception as e:
99
+ # Handle any errors in reading the CSV file
100
+ st.error(f"Error uploading file: {e}")
101
 
102
+ with col2:
103
+ # Adding empty spaces for formatting
104
  st.write("")
105
  st.write("")
106
  st.write("")
107
+
108
+ # Convert the DataFrame stored in session_state to a CSV format, without the index column.
109
+ csv = st.session_state['expenses'].to_csv(index=False).encode("utf-8")
110
+
111
+ # Download button for user to download expenses as a CSV file
112
  st.download_button(
113
+ label = "Export Expenses as CSV", # Text on the button
114
+ data = csv, # The data to download (csv from above)
115
+ file_name = "expenses.csv", # Name of downloaded file
116
+ mime = "text/csv" # Specify the file type (MIME type) as CSV
117
  )
118
 
119
 
120
  with st.form("expense_form"):
121
+ # Input for entering expense amount, with min value of 1 pence
122
  amount = st.number_input("Amount", format="%0.2f", min_value=0.01)
123
+
124
+ # Dropdown for selecting an expense category from a predefined list 'categories'
125
  category = st.selectbox("Category", categories)
126
+
127
+ # Text input for a brief descriptino of the expense
128
  description = st.text_input("Description")
129
+
130
+ # Input for selecting the date of expense
131
  date = st.date_input("Date")
132
 
133
+ # Button to submit the form
134
  submit = st.form_submit_button("Add Expense")
135
 
136
  if submit:
137
+ # Create a new DataFrame for the submitted expense details
138
  new_expense = pd.DataFrame({
139
  'Date': [date],
140
  'Category': [category],
141
  'Amount': [amount],
142
  'Description': [description]
143
  })
144
+
145
+ # Append new expense into existing 'expenses' DataFrame in session_state
146
  st.session_state['expenses'] = pd.concat([st.session_state['expenses'], new_expense], ignore_index=True)
147
+
148
+ # Save the updated 'expenses' DataFrame to HuggingFace storage after adding new expense
149
+ save_data(st.session_state['expenses']) for saving data?
150
+
151
+ # Display a success message after expense is added
152
  st.success("Expense added successfully!")
153
+
154
 
155
+ # Check if there are any expenses in session state
 
 
156
  if not st.session_state['expenses'].empty:
157
  st.subheader("Current Expenses")
158
+
159
+ # Create a copy of the expenses DataFrame to avoid modifying the original
160
  display_df = st.session_state['expenses'].copy()
161
+
162
+ # Convert 'Date' column to string format for better display
163
  display_df['Date'] = display_df['Date'].astype(str)
164
+
165
+ # Show the DataFrame in a table format
166
  st.dataframe(display_df)
167
+
168
  else:
169
+ # Message displayed when there are no expenses
170
  st.write("No expenses yet.")
171
 
172
+
173
+ # Button to trigger data visualisation
174
  viz_button = st.button("Visualise Data")
175
 
176
  if viz_button:
177
+ # Check again if there are any expenses before visualising
178
  if not st.session_state['expenses'].empty:
179
+
180
+ # Display a summary of expenses by category
181
  st.subheader("Expense Summary")
182
+
183
+ # Group by 'Category' and sum the 'Amount'
184
  category_summary = st.session_state['expenses'].groupby('Category')['Amount'].sum().reset_index()
185
+
186
+ # Create a bar plot for total expenses by Category
187
  fig, ax = plt.subplots(figsize=(10,6))
188
  sns.barplot(y='Category', x='Amount', data=category_summary, ax=ax) # Horizontal bar plot
189
  ax.set_title("Total Expenses by Category", pad=20) # Title for the bar plot
 
192
  # Adding labels to each bar
193
  for index, value in enumerate(category_summary['Amount']):
194
  ax.text(value + 0.05, index, f'{value:.2f}', va='center')
195
+
196
+ # Show the plot
197
  st.pyplot(fig)
198
 
199
 
200
+ # Display expenses over time
201
  st.subheader("Expenses Over Time")
202
 
203
+ # Copy DataFrame to not modify the original
204
  monthly_df = st.session_state['expenses'].copy()
205
 
206
+ # Convert 'Date' column to datetime format for plotting
207
  monthly_df['Date'] = pd.to_datetime(monthly_df['Date'])
208
+
209
+ # Sort the DataFrame by 'Date'
210
  monthly_df = monthly_df.sort_values(by = 'Date')
211
 
212
+ # Extract dates and expenses for plotting
213
  dates = monthly_df['Date']
214
  expenses = monthly_df['Amount']
215
 
216
 
217
+ # Create a line plot
218
  fig, ax = plt.subplots()
219
 
220
  # Plot the data
 
225
  ax.set_ylabel('Amount')
226
  ax.set_xlabel('Date')
227
 
228
+ # Rotate x-axis labels for better readability
229
  plt.xticks(rotation=45)
230
 
231
+ # Show the plot
232
  st.pyplot(fig)
233
 
234
  else:
235
+ # Message displayed when there is no data to visualise
236
  st.write("No data to visualise.")