Spaces:
Runtime error
Runtime error
Download expense.py from flexingdatai/expense-tracker: direct link, hf CLI and curl.
- Browser
- Download file 6.47 kB
-
https://huggingface.co/spaces/flexingdatai/expense-tracker/resolve/main/expense.py
- Command line
-
hf download hf://spaces/flexingdatai/expense-tracker/expense.py
-
curl -L -o expense.py https://huggingface.co/spaces/flexingdatai/expense-tracker/resolve/main/expense.py
6.47 kB
| import streamlit as st | |
| import pandas as pd | |
| import requests | |
| import matplotlib.pyplot as plt | |
| from datetime import datetime | |
| import altair as alt | |
| # --- App Configuration --- | |
| st.set_page_config(page_title="πΈ Expense Tracker", layout="wide") | |
| st.title("πΈ Personal Expense Tracker") | |
| API_URL = st.secrets['API_URL'] | |
| SHEET_URL = st.secrets['SHEET_URL'] | |
| PWD = st.secrets['PWD'] | |
| USER_CREDENTIALS = {"admin": PWD} # Set your username and password here | |
| # --- Session State Setup --- | |
| if "authenticated" not in st.session_state: | |
| st.session_state.authenticated = False | |
| if "last_amount_selected" not in st.session_state: | |
| st.session_state.last_amount_selected = 0.0 | |
| if "expense_date" not in st.session_state: | |
| st.session_state.expense_date = datetime.today() | |
| # --- Login UI --- | |
| def login(): | |
| st.title("π Login to Expense Tracker") | |
| username = st.text_input("Username") | |
| password = st.text_input("Password", type="password") | |
| if st.button("Login"): | |
| if username in USER_CREDENTIALS and USER_CREDENTIALS[username] == password: | |
| st.session_state.authenticated = True | |
| st.rerun() | |
| else: | |
| st.error("β Invalid credentials") | |
| # --- Stop if Not Authenticated --- | |
| if not st.session_state.authenticated: | |
| login() | |
| st.stop() | |
| # --- Main UI --- | |
| st.caption("Track your spending smartly, securely, and stylishly.") | |
| # --- Expense Entry Form --- | |
| with st.form("expense_form"): | |
| st.subheader("β Add New Expense") | |
| col1, col2 = st.columns([2, 1]) | |
| with col1: | |
| category = st.selectbox("Category", ["Food", "Transport", "Utilities", "Shopping", "Entertainment", "Other"]) | |
| notes = st.text_input("Notes (optional)", placeholder="E.g. Cafe, Uber ride...") | |
| with col2: | |
| date = st.date_input("Date", value=st.session_state.expense_date) | |
| amount = st.number_input("Amount (βΉ)", min_value=0, step=50, value=int(st.session_state.last_amount_selected), format="%d") | |
| st.markdown("#### π‘ Quick Add") | |
| q1, q2, q3, q4 = st.columns(4) | |
| if q1.form_submit_button("βΉ100"): st.session_state.last_amount_selected = 100.0; st.rerun() | |
| if q2.form_submit_button("βΉ200"): st.session_state.last_amount_selected = 200.0; st.rerun() | |
| if q3.form_submit_button("βΉ500"): st.session_state.last_amount_selected = 500.0; st.rerun() | |
| if q4.form_submit_button("βΉ1000"): st.session_state.last_amount_selected = 1000.0; st.rerun() | |
| submitted = st.form_submit_button("π€ Submit Expense") | |
| if submitted: | |
| payload = { | |
| "date": str(date), | |
| "category": category, | |
| "amount": str(amount), | |
| "notes": notes | |
| } | |
| with st.spinner("Logging your expense..."): | |
| try: | |
| res = requests.post(API_URL, data=payload) | |
| if res.status_code == 200 and "Success" in res.text: | |
| st.success("β Expense logged successfully!") | |
| st.session_state.last_amount_selected = 0.0 | |
| st.session_state.expense_date = datetime.today() | |
| else: | |
| st.error("β Failed to log expense.") | |
| except Exception as e: | |
| st.error(f"β οΈ Error: {e}") | |
| # --- Analytics Section --- | |
| st.subheader("π Expense Analytics") | |
| try: | |
| df = pd.read_csv(SHEET_URL) | |
| df.columns = [c.strip() for c in df.columns] | |
| df["Date"] = pd.to_datetime(df["Date"], errors="coerce") | |
| df = df.dropna(subset=["Date", "Amount"]) | |
| df["Amount"] = pd.to_numeric(df["Amount"], errors="coerce") | |
| df["Month"] = df["Date"].dt.to_period("M").astype(str) | |
| # Layout: Metrics | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| st.metric("Total Spent", f"βΉ{df['Amount'].sum():,.2f}") | |
| with col2: | |
| st.metric("Entries", len(df)) | |
| # Monthly Expense Trend | |
| st.subheader("π Monthly Expense Trend") | |
| monthly_data = df.groupby("Month")["Amount"].sum().reset_index() | |
| line = alt.Chart(monthly_data).mark_line(point=alt.OverlayMarkDef(size=50, filled=True, color="#FF6B6B")).encode( | |
| x=alt.X("Month:O", title="Month", sort=None), # Preserve Month order | |
| y=alt.Y("Amount:Q", title="Total Amount (βΉ)", axis=alt.Axis(grid=True)), | |
| tooltip=[alt.Tooltip("Month:O"), alt.Tooltip("Amount:Q", format=".2f")] | |
| ) | |
| text = line.mark_text(align="center", baseline="middle", dy=-15, fontSize=12, fontWeight="bold").encode( | |
| text=alt.Text("Amount:Q", format=".2f") | |
| ) | |
| monthly_chart = (line + text).properties(width=700, height=300, title="Monthly Expense Trend").configure_line( | |
| color="#4ECDC4", strokeWidth=3 | |
| ).configure_axis(labelFontSize=12, titleFontSize=14) | |
| st.altair_chart(monthly_chart, use_container_width=True) | |
| # Daily Spending Pattern | |
| st.subheader("π Spend by Category") | |
| cat_sum = df.groupby("Category")["Amount"].sum() | |
| explode = [0.05] * len(cat_sum) | |
| colors = plt.cm.Paired(range(len(cat_sum))) | |
| fig, ax = plt.subplots(figsize=(25, 5)) | |
| labels = [f"{cat}\nβΉ{amt:,.0f}" for cat, amt in cat_sum.items()] | |
| ax.pie( | |
| cat_sum.values, | |
| labels=labels, | |
| autopct='%1.0f%%', | |
| startangle=90, | |
| counterclock=False, | |
| explode=explode, | |
| wedgeprops={'edgecolor': 'white', 'linewidth': 1}, | |
| colors=colors, | |
| textprops={'fontsize': 12} | |
| ) | |
| ax.axis("equal") | |
| fig.suptitle("Spend by Category", fontsize=16) | |
| st.pyplot(fig) | |
| # All Expense Entries | |
| st.subheader("π All Expense Entries") | |
| st.dataframe(df.sort_values("Date", ascending=False), use_container_width=True) | |
| # Optional: Add filter for interactivity | |
| st.sidebar.header("Filter Data") | |
| date_range = st.sidebar.date_input("Select Date Range", [df["Date"].min(), df["Date"].max()]) | |
| categories = st.sidebar.multiselect("Select Categories", options=df["Category"].unique(), default=df["Category"].unique()) | |
| filtered_df = df[(df["Date"].dt.date >= date_range[0]) & (df["Date"].dt.date <= date_range[1]) & (df["Category"].isin(categories))] | |
| if not filtered_df.empty: | |
| st.subheader("π Filtered Metrics") | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| st.metric("Filtered Total Spent", f"βΉ{filtered_df['Amount'].sum():,.2f}") | |
| with col2: | |
| st.metric("Filtered Entries", len(filtered_df)) | |
| except Exception as e: | |
| st.error("β οΈ Analytics not available.") | |
| st.text(f"Reason: {e}") | |