Kashaf10 commited on
Commit
cf94914
Β·
verified Β·
1 Parent(s): 38ca512

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -105
app.py CHANGED
@@ -2,116 +2,105 @@ import os
2
  import streamlit as st
3
  import pandas as pd
4
  import matplotlib.pyplot as plt
5
- import seaborn as sns
6
  from groq import Groq
7
- from datetime import datetime
8
 
9
- # -------------------- SETUP --------------------
10
- st.set_page_config(page_title="AI Expense Analyzer", layout="wide")
11
-
12
- # Initialize Groq client
13
- import os
14
  os.environ["GROQ_API_KEY"] = "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"
15
 
 
16
 
17
- # -------------------- APP HEADER --------------------
18
- st.title("πŸ’° AI Expense Analyzer (Groq + Streamlit)")
19
- st.markdown("Track, visualize, and get AI-powered insights on your spending habits.")
20
-
21
- # -------------------- SESSION STATE --------------------
22
- if submitted:
23
- new_expense = {"Date": date, "Category": category, "Amount": amount, "Description": description}
24
- st.session_state.expenses = pd.concat(
25
- [st.session_state.expenses, pd.DataFrame([new_expense])],
26
- ignore_index=True
27
- )
28
- # πŸ‘‡ Convert "Amount" to numeric after adding
29
- st.session_state.expenses["Amount"] = pd.to_numeric(st.session_state.expenses["Amount"], errors="coerce")
30
- st.success("Expense added successfully!")
31
-
32
-
33
- # -------------------- EXPENSE INPUT --------------------
34
- st.subheader("🧾 Add a New Expense")
35
-
36
- with st.form("expense_form", clear_on_submit=True):
37
- date = st.date_input("Date", datetime.now())
38
- category = st.selectbox("Category", ["Food", "Transport", "Shopping", "Bills", "Entertainment", "Other"])
39
- amount = st.number_input("Amount ($)", min_value=0.0, step=0.01)
40
- description = st.text_area("Description (optional)")
41
- submitted = st.form_submit_button("Add Expense")
42
-
43
- if submitted:
44
- new_expense = {"Date": date, "Category": category, "Amount": amount, "Description": description}
45
- st.session_state.expenses = pd.concat(
46
- [st.session_state.expenses, pd.DataFrame([new_expense])],
47
- ignore_index=True
48
- )
49
- st.success("Expense added successfully!")
50
-
51
- # -------------------- DISPLAY EXPENSE TABLE --------------------
52
- if len(st.session_state.expenses) > 0:
53
- st.subheader("πŸ“Š Expense History")
 
 
54
  st.dataframe(st.session_state.expenses, use_container_width=True)
55
 
56
- # -------------------- VISUALIZATIONS --------------------
57
- st.subheader("πŸ“ˆ Expense Visualizations")
58
- tab1, tab2, tab3 = st.tabs(["Bar Chart", "Pie Chart", "Trends"])
59
-
60
- with tab1:
61
- st.markdown("**Expenses by Category**")
62
- fig, ax = plt.subplots()
63
- sns.barplot(
64
- x="Category", y="Amount",
65
- data=st.session_state.expenses.groupby("Category", as_index=False).sum(),
66
- palette="viridis", ax=ax
67
- )
68
- plt.xticks(rotation=45)
69
- st.pyplot(fig)
70
-
71
- with tab2:
72
- st.markdown("**Spending Distribution**")
73
- fig, ax = plt.subplots()
74
- category_sums = st.session_state.expenses.groupby("Category")["Amount"].sum()
75
- ax.pie(category_sums, labels=category_sums.index, autopct="%1.1f%%", startangle=90)
76
- st.pyplot(fig)
77
-
78
- with tab3:
79
- st.markdown("**Spending Trends Over Time**")
80
- fig, ax = plt.subplots()
81
- daily = st.session_state.expenses.groupby("Date", as_index=False)["Amount"].sum()
82
- sns.lineplot(x="Date", y="Amount", data=daily, marker="o", ax=ax)
83
- plt.xticks(rotation=45)
84
- st.pyplot(fig)
85
-
86
- # -------------------- AI INSIGHTS --------------------
87
- st.subheader("πŸ€– AI Expense Analysis (Groq)")
88
-
89
- expense_summary = st.session_state.expenses.to_dict(orient="records")
90
- prompt = f"""
91
- You are an AI financial assistant. Analyze the following list of expenses and spending patterns:
92
- {expense_summary}
93
-
94
- Identify:
95
- 1. Spending patterns or trends
96
- 2. Categories where the user overspends
97
- 3. Suggestions for budgeting or saving
98
- 4. Any unusual or inconsistent spending behaviors
99
-
100
- Respond in a clear and structured way.
101
- """
102
-
103
- if st.button("Generate AI Insights"):
104
- with st.spinner("Analyzing your expenses using Groq LLM..."):
105
- response = client.chat.completions.create(
106
- model="llama-3.3-70b-versatile",
107
- messages=[{"role": "user", "content": prompt}],
108
- )
109
- ai_insight = response.choices[0].message.content
110
- st.markdown("### πŸ’‘ AI Insights")
111
- st.write(ai_insight)
112
-
113
  else:
114
- st.info("Add some expenses above to begin analysis.")
115
-
116
- st.markdown("---")
117
- st.markdown("Developed with ❀️ using [Groq](https://groq.com) and [Streamlit](https://streamlit.io)")
 
2
  import streamlit as st
3
  import pandas as pd
4
  import matplotlib.pyplot as plt
 
5
  from groq import Groq
 
6
 
7
+ # --------------------------
8
+ # Set your Groq API key manually (for Colab)
9
+ # --------------------------
10
+ # You can either:
11
+ # 1️⃣ Use environment variable:
12
  os.environ["GROQ_API_KEY"] = "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"
13
 
14
+ GROQ_API_KEY = ""
15
 
16
+ # --------------------------
17
+ # Initialize Groq client
18
+ # --------------------------
19
+
20
+ # --------------------------
21
+ # Streamlit App Config
22
+ # --------------------------
23
+ st.set_page_config(page_title="AI Expense Analyzer", page_icon="πŸ’°", layout="wide")
24
+ st.title("πŸ’° AI Expense Analyzer")
25
+ st.markdown("Track your expenses, visualize spending patterns, and get smart AI suggestions!")
26
+
27
+ # --------------------------
28
+ # Initialize Session State
29
+ # --------------------------
30
+ if "expenses" not in st.session_state:
31
+ st.session_state.expenses = pd.DataFrame(columns=["Date", "Category", "Amount", "Description"])
32
+
33
+ # --------------------------
34
+ # Expense Input Form
35
+ # --------------------------
36
+ with st.expander("βž• Add New Expense", expanded=True):
37
+ with st.form("expense_form"):
38
+ date = st.date_input("Date")
39
+ category = st.selectbox("Category", ["Food", "Transport", "Shopping", "Entertainment", "Bills", "Other"])
40
+ amount = st.number_input("Amount (in PKR)", min_value=0.0, step=100.0)
41
+ description = st.text_area("Description (optional)")
42
+ submitted = st.form_submit_button("Add Expense")
43
+
44
+ if submitted:
45
+ new_data = pd.DataFrame([[date, category, amount, description]],
46
+ columns=["Date", "Category", "Amount", "Description"])
47
+ st.session_state.expenses = pd.concat([st.session_state.expenses, new_data], ignore_index=True)
48
+ st.success("βœ… Expense added successfully!")
49
+
50
+ # --------------------------
51
+ # Display Expenses
52
+ # --------------------------
53
+ if not st.session_state.expenses.empty:
54
+ st.subheader("πŸ“Š Expense Records")
55
  st.dataframe(st.session_state.expenses, use_container_width=True)
56
 
57
+ # Pie Chart
58
+ st.subheader("🧩 Expense Distribution by Category")
59
+ category_data = st.session_state.expenses.groupby("Category")["Amount"].sum()
60
+ fig1, ax1 = plt.subplots()
61
+ ax1.pie(category_data, labels=category_data.index, autopct="%1.1f%%", startangle=90)
62
+ ax1.axis("equal")
63
+ st.pyplot(fig1)
64
+
65
+ # Trend Chart
66
+ st.subheader("πŸ“ˆ Spending Trend Over Time")
67
+ trend_data = st.session_state.expenses.groupby("Date")["Amount"].sum().reset_index()
68
+ fig2, ax2 = plt.subplots()
69
+ ax2.plot(trend_data["Date"], trend_data["Amount"], marker="o")
70
+ ax2.set_xlabel("Date")
71
+ ax2.set_ylabel("Total Spending (PKR)")
72
+ ax2.set_title("Spending Trend")
73
+ st.pyplot(fig2)
74
+
75
+ # AI Analysis
76
+ st.subheader("πŸ€– AI Expense Insights")
77
+
78
+ user_expense_summary = st.session_state.expenses.to_string(index=False)
79
+
80
+ if st.button("Analyze My Expenses πŸ’¬"):
81
+ with st.spinner("Analyzing your expense patterns with Groq Llama 3.3..."):
82
+ try:
83
+ prompt = f"""
84
+ You are a financial advisor. Analyze the following expense data and identify:
85
+ 1. Spending patterns
86
+ 2. Categories with overspending
87
+ 3. Suggested saving strategies
88
+ 4. A short summary of financial health.
89
+
90
+ Expense Data:
91
+ {user_expense_summary}
92
+ """
93
+
94
+ chat_completion = client.chat.completions.create(
95
+ messages=[{"role": "user", "content": prompt}],
96
+ model="llama-3.3-70b-versatile",
97
+ )
98
+
99
+ ai_analysis = chat_completion.choices[0].message.content
100
+ st.success("βœ… Analysis Complete!")
101
+ st.markdown(ai_analysis)
102
+
103
+ except Exception as e:
104
+ st.error(f"❌ Error: {str(e)}")
 
 
 
 
 
 
 
 
 
105
  else:
106
+ st.info("πŸ’‘ Add some expenses above to get started!")