File size: 5,660 Bytes
f1912e6
 
 
 
 
7eb8478
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1912e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7eb8478
 
f1912e6
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# Initialize an empty DataFrame to hold expenses data
columns = ['Date', 'Category', 'Description', 'Amount']
if 'expenses_df' not in st.session_state:
    st.session_state['expenses_df'] = pd.DataFrame(columns=columns)

# Initialize a list for storing messages between user and bot
if 'messages' not in st.session_state:
    st.session_state['messages'] = []

# Function to add an expense
def add_expense(date, category, description, amount):
    new_expense = pd.DataFrame([[date, category, description, amount]], columns=st.session_state['expenses_df'].columns)
    st.session_state['expenses_df'] = pd.concat([st.session_state['expenses_df'], new_expense], ignore_index=True)

# Function to generate response for the chatbot
def chatbot_response(user_input):
    # If the user wants to add an expense, we can extract the details from the input
    if "add" in user_input.lower() and "expense" in user_input.lower():
        # Ask the user for details about the expense
        st.session_state['messages'].append({"role": "assistant", "content": "Please enter the date of the expense."})
        return "Please enter the date of the expense."

    elif "view" in user_input.lower():
        st.session_state['messages'].append({"role": "assistant", "content": str(st.session_state['expenses_df'])})
        return "Here are all your expenses:\n" + str(st.session_state['expenses_df'])
    
    elif "summary" in user_input.lower():
        category_summary = st.session_state['expenses_df'].groupby('Category')['Amount'].sum().reset_index()
        st.session_state['messages'].append({"role": "assistant", "content": str(category_summary)})
        return "Here is the expense suimport streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# Initialize an empty DataFrame to hold expenses data
columns = ['Date', 'Category', 'Description', 'Amount']
if 'expenses_df' not in st.session_state:
    st.session_state['expenses_df'] = pd.DataFrame(columns=columns)

# Initialize a list for storing messages between user and bot
if 'messages' not in st.session_state:
    st.session_state['messages'] = []

# Function to add an expense
def add_expense(date, category, description, amount):
    new_expense = pd.DataFrame([[date, category, description, amount]], columns=st.session_state['expenses_df'].columns)
    st.session_state['expenses_df'] = pd.concat([st.session_state['expenses_df'], new_expense], ignore_index=True)

# Function to generate response for the chatbot
def chatbot_response(user_input):
    # If the user wants to add an expense, we can extract the details from the input
    if "add" in user_input.lower() and "expense" in user_input.lower():
        # Ask the user for details about the expense
        st.session_state['messages'].append({"role": "assistant", "content": "Please enter the date of the expense."})
        return "Please enter the date of the expense."

    elif "view" in user_input.lower():
        st.session_state['messages'].append({"role": "assistant", "content": str(st.session_state['expenses_df'])})
        return "Here are all your expenses:\n" + str(st.session_state['expenses_df'])
    
    elif "summary" in user_input.lower():
        category_summary = st.session_state['expenses_df'].groupby('Category')['Amount'].sum().reset_index()
        st.session_state['messages'].append({"role": "assistant", "content": str(category_summary)})
        return "Here is the expense summary by category:\n" + str(category_summary)

    elif "visualize" in user_input.lower():
        fig, ax = plt.subplots(figsize=(10, 6))
        sns.barplot(x='Category', y='Amount', data=st.session_state['expenses_df'], ax=ax)
        ax.set_title('Total Expenses by Category')
        ax.set_xlabel('Category')
        ax.set_ylabel('Amount Spent ($)')
        ax.set_xticklabels(ax.get_xticklabels(), rotation=45)
        st.pyplot(fig)
        return "Here is the bar chart showing total expenses by category."
    
    else:
        return "I'm sorry, I didn't understand that. You can add expenses, view expenses, or ask for a summary."

# Streamlit UI
st.title("Daily Expense Tracker - Chatbot")

# Display messages (chat history)
for message in st.session_state['messages']:
    if message["role"] == "assistant":
        st.chat_message("assistant").markdown(message["content"])
    else:
        st.chat_message("user").markdown(message["content"])

# User input for chatbot
user_input = st.text_input("You:", key="user_input")

if user_input:
    st.session_state['messages'].append({"role": "user", "content": user_input})

    # Get response from chatbot
    response = chatbot_response(user_input)

    st.session_state['messages'].append({"role": "assistant", "content": response})

# Expense Addition Flow
# Ensure there is at least one message and check for the assistant's message asking for date input
if st.session_state['messages'] and "Please enter the date of the expense." in st.session_state['messages'][-1].get("content", ""):
    date = st.date_input("Enter Expense Date")
    category = st.selectbox("Category", ['Food', 'Transport', 'Entertainment', 'Other'])
    description = st.text_input("Description")
    amount = st.number_input("Amount", min_value=0.0, format="%.2f")

    if st.button("Submit Expense"):
        add_expense(date, category, description, amount)
        st.session_state['messages'].append({"role": "assistant", "content": f"Expense added: {description} - ${amount:.2f}"})
        st.success(f"Added expense: {description} - ${amount:.2f}")