Distopia22 commited on
Commit
ac3e730
Β·
verified Β·
1 Parent(s): 6df25fd

Create app.py

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