Download app.py from chatbotdeveloper2025genai/personalFinance_agent: direct link, hf CLI and curl.
- Browser
- Download file 9.98 kB
-
https://huggingface.co/spaces/chatbotdeveloper2025genai/personalFinance_agent/resolve/main/app.py
- Command line
-
hf download hf://spaces/chatbotdeveloper2025genai/personalFinance_agent/app.py
-
curl -L -o app.py https://huggingface.co/spaces/chatbotdeveloper2025genai/personalFinance_agent/resolve/main/app.py
9.98 kB
| import os | |
| import io | |
| import base64 | |
| from PIL import Image as PImage | |
| from transformers import pipeline | |
| import gradio as gr | |
| from dotenv import load_dotenv | |
| import requests | |
| import json | |
| import warnings | |
| # --- 1. CONFIGURATION AND CLIENTS --- | |
| # Define API endpoints and models (Assuming API key will be handled externally or via environment) | |
| warnings.filterwarnings("ignore", category=FutureWarning) | |
| # In a Gradio/Hugging Face Space environment, environment variables are typically set in the Space Secrets. | |
| # For local testing, ensure your .env has GOOGLE_API_KEY. | |
| load_dotenv() | |
| google_api_key = os.getenv("GOOGLE_API_KEY") or "" # Assume empty string if not found for Canvas usage | |
| if not google_api_key: | |
| warnings.warn("GOOGLE_API_KEY not found in environment. Agent features may not work outside of Canvas/properly configured environment.") | |
| API_URL = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-05-20:generateContent?key={google_api_key}" | |
| # --- 2. CORE FINANCIAL DATA --- | |
| # Your specific details provided in the prompt | |
| SALARY = 25000.00 | |
| FIXED_EXPENSES = { | |
| "SIP": 3000.00, | |
| "Mutual_Fund": 1000.00, # Note: MF is usually investment, but treated as a fixed deduction here | |
| "Health_Insurance": 2000.00, | |
| "Rent/Other_Major_Bills": 12000.00, # Estimated major bills to reach a realistic spending level | |
| } | |
| # Variable Expenses (Based on your notes) | |
| # 3 days in office/week * 4 weeks = 12 trips/month | |
| OFFICE_TRIPS_PER_MONTH = 12.0 | |
| OFFICE_TRAVEL_COST_AVG = (200 + 400) / 2 # Avg. 300 per round trip | |
| OFFICE_FOOD_COST = 180.00 | |
| OFFICE_EXPENSE_MONTHLY = OFFICE_TRIPS_PER_MONTH * (OFFICE_TRAVEL_COST_AVG + OFFICE_FOOD_COST) | |
| # Weekend Social Expenses (Estimate 2 weekends a month for friends flat visits) | |
| WEEKENDS_AT_FRIENDS_PER_MONTH = 2.0 | |
| MIDNIGHT_PIZZA_COST = 150.00 | |
| COLD_DRINKS_DAILY_COST = 4 * 40 # 4 cold drinks * 40 Rs = 160 per day | |
| WEEKEND_EXPENSE_MONTHLY = WEEKENDS_AT_FRIENDS_PER_MONTH * (MIDNIGHT_PIZZA_COST + (2 * COLD_DRINKS_DAILY_COST)) # Assuming 2 days per weekend trip | |
| # --- 3. FINANCIAL CALCULATIONS --- | |
| def calculate_snapshot(): | |
| """Calculates fixed, estimated variable, and net cashflow.""" | |
| fixed_total = sum(FIXED_EXPENSES.values()) | |
| # Calculate variable totals | |
| variable_monthly = OFFICE_EXPENSE_MONTHLY + WEEKEND_EXPENSE_MONTHLY | |
| # Total outflow | |
| total_outflow = fixed_total + variable_monthly | |
| # Net monthly cashflow (before extra spending/movies/shopping) | |
| net_cashflow = SALARY - total_outflow | |
| snapshot = f""" | |
| --- Financial Summary --- | |
| Salary (Inflow): ₹{SALARY:,.2f} | |
| Fixed Commitments (Outflow): ₹{fixed_total:,.2f} | |
| - SIP: ₹{FIXED_EXPENSES['SIP']:,.2f} | |
| - Mutual Fund: ₹{FIXED_EXPENSES['Mutual_Fund']:,.2f} | |
| - Health Insurance: ₹{FIXED_EXPENSES['Health_Insurance']:,.2f} | |
| - Estimated Bills: ₹{FIXED_EXPENSES['Rent/Other_Major_Bills']:,.2f} | |
| Estimated Variable Expenses: ₹{variable_monthly:,.2f} | |
| - Office Travel/Food (12 days): ₹{OFFICE_EXPENSE_MONTHLY:,.2f} | |
| - Weekend Social (2 trips): ₹{WEEKEND_EXPENSE_MONTHLY:,.2f} | |
| -------------------------------------- | |
| Total Outflow (Fixed + Variable): ₹{total_outflow:,.2f} | |
| Net Cashflow (Target Surplus): ₹{net_cashflow:,.2f} | |
| -------------------------------------- | |
| Goal Note: Your net cashflow should be used for discretionary spending, but you mentioned you often overspend by selling stocks. This is the amount you need to manage carefully. | |
| """ | |
| return snapshot, net_cashflow | |
| # --- 4. GEMINI AGENT LOGIC (Reusing your class structure) --- | |
| class GeminiClient: | |
| def __init__(self, api_url, financial_data): | |
| self.api_url = api_url | |
| self.model_name = "gemini-2.5-flash-preview-05-20" | |
| self.financial_data = financial_data | |
| self.base_system_instruction = f""" | |
| You are a personalized Financial Health Coach. | |
| Your goal is to provide supportive, actionable, and specific advice based on the user's situation. | |
| The user's core financial data is: | |
| {financial_data} | |
| The user has a major issue with discretionary spending (movies, shopping, extra food delivery) which causes them to sell investments. | |
| Always tailor your advice to help the user manage their discretionary spending (their Net Cashflow amount) effectively. | |
| If the query requires outside knowledge (like "should I switch my SIP to a different fund?"), use the Google Search tool. | |
| """ | |
| def chat(self, user_prompt, enable_search=True): | |
| payload = { | |
| "contents": [{"parts": [{"text": user_prompt}]}], | |
| "systemInstruction": {"parts": [{"text": self.base_system_instruction}]}, | |
| "config": {} | |
| } | |
| if enable_search: | |
| payload["tools"] = [{"google_search": {}}] | |
| try: | |
| response = requests.post(self.api_url, headers={'Content-Type': 'application/json'}, data=json.dumps(payload)) | |
| response.raise_for_status() | |
| result = response.json() | |
| candidate = result.get('candidates', [{}])[0] | |
| # Extract Text | |
| text = candidate.get('content', {}).get('parts', [{}])[0].get('text', "Sorry, the AI could not generate a response.") | |
| # Extract Sources | |
| sources = candidate.get('groundingMetadata', {}).get('groundingAttributions', []) | |
| source_list = [] | |
| if sources: | |
| source_list = [f"[{i+1}] {s.get('web', {}).get('title', 'Source')} ({s.get('web', {}).get('uri', 'No URI')})" | |
| for i, s in enumerate(sources) if s.get('web')] | |
| if source_list: | |
| text += "\n\n---\n**Sources:**\n" + "\n".join(source_list) | |
| return text | |
| except Exception as e: | |
| return f"An error occurred while connecting to the Gemini API: {e}. Please check your API Key." | |
| # Initialize the client with the calculated snapshot | |
| initial_snapshot, net_cashflow_val = calculate_snapshot() | |
| gemini_client = GeminiClient(API_URL, initial_snapshot) | |
| # --- 5. GRADIO INTERFACE --- | |
| with gr.Blocks(title="Personal Finance AI Agent") as demo: | |
| gr.Markdown("# 💸 Personalized Finance Agent") | |
| gr.Markdown("---") | |
| # Display the static financial summary first | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.Markdown("## Your Financial Snapshot") | |
| snapshot_output = gr.Textbox( | |
| value=initial_snapshot, | |
| label="Monthly Cash Flow Breakdown", | |
| lines=15, | |
| interactive=False, | |
| elem_classes=["font-mono"] | |
| ) | |
| with gr.Column(scale=1): | |
| gr.Markdown("## Key Insight") | |
| gr.Markdown(f""" | |
| Your current Net Cashflow (Disposable Income before 'extra' spending) is: | |
| # **₹{net_cashflow_val:,.2f}** | |
| You have been overspending this amount, forcing you to sell investments. | |
| This AI Agent will help you manage this discretionary money better. | |
| """) | |
| # What-if Simulation Tool (Simple calculation for immediate value) | |
| gr.Markdown("## What-If Simulator") | |
| spending_reduction = gr.Slider( | |
| minimum=0, maximum=1000, step=100, value=200, | |
| label="Reduce Extra Spending (Zomato/Shopping/Movies) by (₹)", | |
| ) | |
| def simulate_savings(reduction): | |
| annual_savings = reduction * 12 | |
| new_net_cashflow = net_cashflow_val + reduction | |
| return f""" | |
| If you reduce discretionary spending by ₹{reduction:,.0f} per month: | |
| - **New Monthly Surplus:** ₹{new_net_cashflow:,.2f} | |
| - **Annual Savings Potential:** ₹{annual_savings:,.2f} | |
| Ask the AI to help you find ways to save this amount! | |
| """ | |
| simulation_output = gr.Textbox(label="Simulation Result", lines=6, interactive=False) | |
| spending_reduction.change(simulate_savings, inputs=[spending_reduction], outputs=simulation_output) | |
| # Initial simulation run | |
| simulation_output.value = simulate_savings(200) | |
| gr.Markdown("---") | |
| # AI Chat Interface | |
| gr.Markdown("## 🧠 Personalized Financial Coach Agent") | |
| def chat_fn(q, history): | |
| # Flatten history for better context passing if needed, but for simplicity, we focus on the current question | |
| # Add loading indicator | |
| history = history or [] | |
| # Determine if search is needed (e.g., asking about external topics like markets or other funds) | |
| needs_search = any(word in q.lower() for word in ["stock", "market", "fund", "tax", "switch", "best way", "latest news"]) | |
| answer = gemini_client.chat(q, enable_search=needs_search) | |
| history.append([q, answer]) | |
| return history, gr.Textbox(value="") # Clear user input box | |
| chatbot = gr.Chatbot(label="Finance Coach Conversation") | |
| user_input = gr.Textbox(label="Ask your Financial Coach (e.g., 'Give me 3 practical ways to save 2000 from my discretionary money,' or 'Should I shift my SIP?', or 'What is a good way to track my spending?')" , placeholder="Ask a question...") | |
| submit_btn = gr.Button("Get Advice") | |
| submit_btn.click(chat_fn, inputs=[user_input, chatbot], outputs=[chatbot, user_input]) | |
| user_input.submit(chat_fn, inputs=[user_input, chatbot], outputs=[chatbot, user_input]) | |
| demo.launch() | |