Spaces:
Runtime error
Runtime error
LearnwithShashank commited on
Commit ·
10238e5
1
Parent(s): 10ba0b5
Files changed (6)
- app.pyDeleted-124
- app2.pyDeleted-167
- expense_old.pyDeleted-82
- expenses.csvDeleted-1
- index.htmlDeleted-19
- t.ipynbDeleted-128
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124import streamlit as stimport requestsfrom datetime import datetime
# ---------- App Config ----------st.set_page_config(page_title="💸 Expense Tracker", layout="centered", initial_sidebar_state="expanded")
# ---------- Custom CSS for Theme ----------st.markdown(""" <style> html, body, [class*="css"] { font-family: 'Segoe UI', sans-serif; background-color: #f4faff; } .stForm { background-color: #ffffff; padding: 2rem; border-radius: 1rem; box-shadow: 0 6px 18px rgba(0,0,0,0.05); border: 1px solid #e0ebf5; } .stTextInput>div>div>input, .stNumberInput>div>div>input { background-color: #ffffff !important; padding: 0.5rem; border-radius: 0.5rem; } .stButton>button { border-radius: 10px; padding: 0.4rem 1rem; font-weight: 500; color: #fff !important; background: linear-gradient(to right, #00bcd4, #2196f3); border: none; } .stButton>button:hover { background: linear-gradient(to right, #00acc1, #1976d2); } .quick-add-container { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 10px; } </style>""", unsafe_allow_html=True)
# ---------- Secure API ----------# API_URL = st.secrets['API_URL']API_URL='https://script.google.com/macros/s/AKfycbxIX_85ybaLTnVL712IVC7kEjEL0SQMVI0OVpk41yaqIl1e8V2Q29jCyS8D2lwkY8qJDg/exec'
# ---------- Session State ----------if "last_amount_selected" not in st.session_state: st.session_state.last_amount_selected = 0.0if "expense_date" not in st.session_state: st.session_state.expense_date = datetime.today()
amount_value = st.session_state.last_amount_selecteddate_value = st.session_state.expense_date
# ---------- Sidebar ----------with st.sidebar: st.markdown("## 🧭 Menu") st.markdown("➡️ **Log Expense**") st.markdown("---") st.success("Track your expenses with ease. Your data is securely stored in Google Sheets.")
# ---------- Header ----------st.markdown("## 📝 Add a New Expense")st.caption("Simple. Smart. Secure.")
# ---------- Form ----------with st.form("expense_form", border=False): 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. Lunch at cafe, Amazon order...")
with col2: date = st.date_input("📅 Date", value=date_value) amount = st.number_input("💰 Amount (₹)", min_value=0.0, step=10.0, format="%f", value=amount_value)
# ---------- Quick Add Buttons ---------- st.markdown("**Quick Add Amount**") st.markdown('<div class="quick-add-container">', unsafe_allow_html=True) c1, c2, c3, c4 = st.columns(4) if c1.form_submit_button("₹100"): st.session_state.last_amount_selected = 100.0 st.rerun() if c2.form_submit_button("₹200"): st.session_state.last_amount_selected = 200.0 st.rerun() if c3.form_submit_button("₹500"): st.session_state.last_amount_selected = 500.0 st.rerun() if c4.form_submit_button("₹1000"): st.session_state.last_amount_selected = 1000.0 st.rerun() st.markdown('</div>', unsafe_allow_html=True)
# ---------- Submit ---------- 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("❌ Submission failed. Server says: " + res.text) except Exception as e: st.error(f"⚠️ Network error: {e}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167import streamlit as stimport pandas as pdimport requestsimport matplotlib.pyplot as pltfrom datetime import datetimeimport altair as alt
# --- App Configuration ---st.set_page_config(page_title="💸 Expense Tracker", layout="wide")
# --- URLs & Credentials ---API_URL = 'https://script.google.com/macros/s/AKfycbxIX_85ybaLTnVL712IVC7kEjEL0SQMVI0OVpk41yaqIl1e8V2Q29jCyS8D2lwkY8qJDg/exec'SHEET_URL = "https://docs.google.com/spreadsheets/d/e/2PACX-1vSGGF50WFD3AR31xZ1eS6zpK9U9v8bhw4ITaD7VxPRAlsFcXEW2MJW_EvvjSQAl6YcM7TgsoV5XGNHw/pub?gid=0&single=true&output=csv"
API_URL = st.secrets['API_URL']SHEET_URL = st.secrets['SHEET_URL']
USER_CREDENTIALS = {"admin": "track123"} # Set your username and password here
# --- Session State Setup ---if "authenticated" not in st.session_state: st.session_state.authenticated = Falseif "last_amount_selected" not in st.session_state: st.session_state.last_amount_selected = 0.0if "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.title("💸 Personal Expense Tracker")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}")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182import streamlit as stimport requestsfrom datetime import datetime
# API_URL = st.secrets['API_URL']API_URL='https://script.google.com/macros/s/AKfycbxIX_85ybaLTnVL712IVC7kEjEL0SQMVI0OVpk41yaqIl1e8V2Q29jCyS8D2lwkY8qJDg/exec'
import streamlit as stimport requestsfrom datetime import datetime
# App configst.set_page_config(page_title="Expense Tracker", layout="wide")st.title("💸 Personal Expense Tracker")
# Your secure API URL# API_URL = st.secrets['API_URL']
# Sidebarwith st.sidebar: st.markdown("### 🚀 Menu") st.markdown("➕ Add Expense") st.markdown("---") st.info("Track your daily expenses with ease.\nAll data is securely stored in Google Sheets.")
# Headerst.markdown("### ✍️ Log Your Expense")
# Initialize session state on first loadif "last_amount_selected" not in st.session_state: st.session_state.last_amount_selected = 0.0
# Use a local variable to hold the current amountamount_value = st.session_state.last_amount_selected
# Quick Add Buttonsst.markdown("💡 Quick Add Amount:")q1, q2, q3, q4 = st.columns(4)if q1.button("₹100"): amount_value = 100.0if q2.button("₹200"): amount_value = 200.0if q3.button("₹500"): amount_value = 500.0if q4.button("₹1000"): amount_value = 1000.0
# Store the latest selected quick amount into session statest.session_state.last_amount_selected = amount_value
# Expense Formwith st.form("expense_form"): col1, col2 = st.columns(2)
with col1: date = st.date_input("Date", value=datetime.today()) category = st.selectbox("Category", ["Food", "Transport", "Utilities", "Shopping", "Entertainment", "Other"]) with col2: amount = st.number_input("Amount Spent (₹)", min_value=0.0, step=10.0, format="%f", value=amount_value)
notes = st.text_input("📝 Notes (optional)") 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 added to Google Sheet successfully!") st.session_state.last_amount_selected = 0.0 # Reset after submission else: st.error("❌ Failed to send data. Server says: " + res.text) except Exception as e: st.error(f"⚠️ An error occurred: {e}")1Date,Category,Amount,Notes12345678910111213141516171819<!doctype html><html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title>My static Space</title> <link rel="stylesheet" href="style.css" /> </head> <body> <div class="card"> <h1>Welcome to your static Space!</h1> <p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p> <p> Also don't forget to check the <a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>. </p> </div> </body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "36e64c91", "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>Date</th>\n", " <th>Category</th>\n", " <th>Amount</th>\n", " <th>Notes</th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>0</th>\n", " <td>2025-06-09</td>\n", " <td>Transport</td>\n", " <td>0.0</td>\n", " <td>NaN</td>\n", " </tr>\n", " <tr>\n", " <th>1</th>\n", " <td>2025-06-10</td>\n", " <td>Other</td>\n", " <td>0.0</td>\n", " <td>NaN</td>\n", " </tr>\n", " <tr>\n", " <th>2</th>\n", " <td>2025-06-12</td>\n", " <td>Food</td>\n", " <td>0.0</td>\n", " <td>NaN</td>\n", " </tr>\n", " <tr>\n", " <th>3</th>\n", " <td>2025-06-12</td>\n", " <td>Food</td>\n", " <td>6.7</td>\n", " <td>NaN</td>\n", " </tr>\n", " <tr>\n", " <th>4</th>\n", " <td>2025-06-12</td>\n", " <td>Food</td>\n", " <td>6.7</td>\n", " <td>NaN</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " Date Category Amount Notes\n", "0 2025-06-09 Transport 0.0 NaN\n", "1 2025-06-10 Other 0.0 NaN\n", "2 2025-06-12 Food 0.0 NaN\n", "3 2025-06-12 Food 6.7 NaN\n", "4 2025-06-12 Food 6.7 NaN" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import pandas as pd\n", "\n", "df=pd.read_csv('https://docs.google.com/spreadsheets/d/e/2PACX-1vSGGF50WFD3AR31xZ1eS6zpK9U9v8bhw4ITaD7VxPRAlsFcXEW2MJW_EvvjSQAl6YcM7TgsoV5XGNHw/pub?gid=0&single=true&output=csv')\n", "\n", "df.head()" ] }, { "cell_type": "code", "execution_count": null, "id": "d6ac5023", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.13.1" } }, "nbformat": 4, "nbformat_minor": 5}app.pyDeleted-124
app2.pyDeleted-167
expense_old.pyDeleted-82
expenses.csvDeleted-1
index.htmlDeleted-19
t.ipynbDeleted-128