Talha812 commited on
Commit
59d4f30
Β·
verified Β·
1 Parent(s): 6c36410

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -0
app.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
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 = os.getenv("GROQ_API_KEY")
15
+
16
+ # --------------------------
17
+ # Initialize Groq client
18
+ # --------------------------
19
+ if not GROQ_API_KEY:
20
+ st.warning("⚠️ Please set your GROQ_API_KEY in Colab before running.")
21
+ client = Groq(api_key=GROQ_API_KEY)
22
+
23
+ # --------------------------
24
+ # Streamlit App Config
25
+ # --------------------------
26
+ st.set_page_config(page_title="AI Expense Analyzer", page_icon="πŸ’°", layout="wide")
27
+ st.title("πŸ’° AI Expense Analyzer")
28
+ st.markdown("Track your expenses, visualize spending patterns, and get smart AI suggestions!")
29
+
30
+ # --------------------------
31
+ # Initialize Session State
32
+ # --------------------------
33
+ if "expenses" not in st.session_state:
34
+ st.session_state.expenses = pd.DataFrame(columns=["Date", "Category", "Amount", "Description"])
35
+
36
+ # --------------------------
37
+ # Expense Input Form
38
+ # --------------------------
39
+ with st.expander("βž• Add New Expense", expanded=True):
40
+ with st.form("expense_form"):
41
+ date = st.date_input("Date")
42
+ category = st.selectbox("Category", ["Food", "Transport", "Shopping", "Entertainment", "Bills", "Other"])
43
+ amount = st.number_input("Amount (in PKR)", min_value=0.0, step=100.0)
44
+ description = st.text_area("Description (optional)")
45
+ submitted = st.form_submit_button("Add Expense")
46
+
47
+ if submitted:
48
+ new_data = pd.DataFrame([[date, category, amount, description]],
49
+ columns=["Date", "Category", "Amount", "Description"])
50
+ st.session_state.expenses = pd.concat([st.session_state.expenses, new_data], ignore_index=True)
51
+ st.success("βœ… Expense added successfully!")
52
+
53
+ # --------------------------
54
+ # Display Expenses
55
+ # --------------------------
56
+ if not st.session_state.expenses.empty:
57
+ st.subheader("πŸ“Š Expense Records")
58
+ st.dataframe(st.session_state.expenses, use_container_width=True)
59
+
60
+ # Pie Chart
61
+ st.subheader("🧩 Expense Distribution by Category")
62
+ category_data = st.session_state.expenses.groupby("Category")["Amount"].sum()
63
+ fig1, ax1 = plt.subplots()
64
+ ax1.pie(category_data, labels=category_data.index, autopct="%1.1f%%", startangle=90)
65
+ ax1.axis("equal")
66
+ st.pyplot(fig1)
67
+
68
+ # Trend Chart
69
+ st.subheader("πŸ“ˆ Spending Trend Over Time")
70
+ trend_data = st.session_state.expenses.groupby("Date")["Amount"].sum().reset_index()
71
+ fig2, ax2 = plt.subplots()
72
+ ax2.plot(trend_data["Date"], trend_data["Amount"], marker="o")
73
+ ax2.set_xlabel("Date")
74
+ ax2.set_ylabel("Total Spending (PKR)")
75
+ ax2.set_title("Spending Trend")
76
+ st.pyplot(fig2)
77
+
78
+ # AI Analysis
79
+ st.subheader("πŸ€– AI Expense Insights")
80
+
81
+ user_expense_summary = st.session_state.expenses.to_string(index=False)
82
+
83
+ if st.button("Analyze My Expenses πŸ’¬"):
84
+ with st.spinner("Analyzing your expense patterns with Groq Llama 3.3..."):
85
+ try:
86
+ prompt = f"""
87
+ You are a financial advisor. Analyze the following expense data and identify:
88
+ 1. Spending patterns
89
+ 2. Categories with overspending
90
+ 3. Suggested saving strategies
91
+ 4. A short summary of financial health.
92
+
93
+ Expense Data:
94
+ {user_expense_summary}
95
+ """
96
+
97
+ chat_completion = client.chat.completions.create(
98
+ messages=[{"role": "user", "content": prompt}],
99
+ model="llama-3.3-70b-versatile",
100
+ )
101
+
102
+ ai_analysis = chat_completion.choices[0].message.content
103
+ st.success("βœ… Analysis Complete!")
104
+ st.markdown(ai_analysis)
105
+
106
+ except Exception as e:
107
+ st.error(f"❌ Error: {str(e)}")
108
+ else:
109
+ st.info("πŸ’‘ Add some expenses above to get started!")