Spaces:
Sleeping
Sleeping
Download app.py from Kashaf10/kexpenseanalyzer: direct link, hf CLI and curl.
- Browser
- Download file 4.84 kB
-
https://huggingface.co/spaces/Kashaf10/kexpenseanalyzer/resolve/main/app.py
- Command line
-
hf download hf://spaces/Kashaf10/kexpenseanalyzer/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Kashaf10/kexpenseanalyzer/resolve/main/app.py
4.84 kB
| import os | |
| import streamlit as st | |
| import pandas as pd | |
| import seaborn as sns | |
| import matplotlib.pyplot as plt | |
| from groq import Groq | |
| # -------------------------- | |
| # π Set up Groq API Key | |
| # -------------------------- | |
| # Option 1: Use environment variable directly | |
| # os.environ["GROQ_API_KEY"] = "your_api_key_here" | |
| # Option 2: Use Streamlit secrets (recommended for deployment) | |
| # Use Hugging Face Secrets | |
| GROQ_API_KEY = os.getenv("Analyzerkey") | |
| # Initialize Groq client | |
| if not GROQ_API_KEY: | |
| st.warning("β οΈ Please set your GROQ_API_KEY before running the app.") | |
| else: | |
| client = Groq(api_key=GROQ_API_KEY) | |
| # -------------------------- | |
| # π¨ Streamlit Page Config | |
| # -------------------------- | |
| st.set_page_config(page_title="AI Expense Analyzer", page_icon="π°", layout="wide") | |
| st.title("π° AI Expense Analyzer") | |
| st.markdown("Track your expenses, visualize spending patterns, and get smart AI-driven insights!") | |
| # -------------------------- | |
| # π§Ύ Initialize Session State | |
| # -------------------------- | |
| if "expenses" not in st.session_state: | |
| st.session_state.expenses = pd.DataFrame(columns=["Date", "Category", "Amount", "Description"]) | |
| # -------------------------- | |
| # β Expense Input Form | |
| # -------------------------- | |
| with st.expander("β Add New Expense", expanded=True): | |
| with st.form("expense_form"): | |
| date = st.date_input("Date") | |
| category = st.selectbox("Category", ["Food", "Transport", "Shopping", "Entertainment", "Bills", "Other"]) | |
| amount = st.number_input("Amount (in PKR)", min_value=0.0, step=100.0) | |
| description = st.text_area("Description (optional)") | |
| submitted = st.form_submit_button("Add Expense") | |
| if submitted: | |
| new_data = pd.DataFrame([[date, category, amount, description]], | |
| columns=["Date", "Category", "Amount", "Description"]) | |
| st.session_state.expenses = pd.concat([st.session_state.expenses, new_data], ignore_index=True) | |
| st.success("β Expense added successfully!") | |
| # -------------------------- | |
| # π Display Expenses | |
| # -------------------------- | |
| if not st.session_state.expenses.empty: | |
| st.subheader("π Expense Records") | |
| st.dataframe(st.session_state.expenses, use_container_width=True) | |
| # Ensure 'Amount' is numeric | |
| st.session_state.expenses["Amount"] = pd.to_numeric(st.session_state.expenses["Amount"], errors="coerce") | |
| # -------------------------- | |
| # π§© Expense Distribution (Pie Chart) | |
| # -------------------------- | |
| st.subheader("π§© Expense Distribution by Category") | |
| category_data = st.session_state.expenses.groupby("Category")["Amount"].sum() | |
| fig1, ax1 = plt.subplots() | |
| ax1.pie(category_data, labels=category_data.index, autopct="%1.1f%%", startangle=90) | |
| ax1.axis("equal") | |
| st.pyplot(fig1) | |
| # -------------------------- | |
| # π Spending Trend (Line Chart) | |
| # -------------------------- | |
| st.subheader("π Spending Trend Over Time") | |
| trend_data = st.session_state.expenses.groupby("Date")["Amount"].sum().reset_index() | |
| fig2, ax2 = plt.subplots() | |
| sns.lineplot(x="Date", y="Amount", data=trend_data, marker="o", ax=ax2) | |
| ax2.set_xlabel("Date") | |
| ax2.set_ylabel("Total Spending (PKR)") | |
| ax2.set_title("Spending Trend") | |
| plt.xticks(rotation=45) | |
| st.pyplot(fig2) | |
| # -------------------------- | |
| # π€ AI Expense Analysis (Groq) | |
| # -------------------------- | |
| st.subheader("π€ AI Expense Insights") | |
| user_expense_summary = st.session_state.expenses.to_string(index=False) | |
| if st.button("Analyze My Expenses π¬"): | |
| if not GROQ_API_KEY: | |
| st.error("β Groq API key not set. Please configure it first.") | |
| else: | |
| with st.spinner("Analyzing your expense patterns with Groq Llama 3.3..."): | |
| try: | |
| prompt = f""" | |
| You are a financial advisor. Analyze the following expense data and identify: | |
| 1. Spending patterns | |
| 2. Categories with overspending | |
| 3. Suggested saving strategies | |
| 4. A short summary of financial health. | |
| Expense Data: | |
| {user_expense_summary} | |
| """ | |
| chat_completion = client.chat.completions.create( | |
| messages=[{"role": "user", "content": prompt}], | |
| model="llama-3.3-70b-versatile", | |
| ) | |
| ai_analysis = chat_completion.choices[0].message.content | |
| st.success("β Analysis Complete!") | |
| st.markdown(ai_analysis) | |
| except Exception as e: | |
| st.error(f"β Error: {str(e)}") | |
| else: | |
| st.info("π‘ Add some expenses above to get started!") | |