import gradio as gr import os import re from openai import OpenAI # --- Configuration and Utility Functions --- # Placeholder for the API Key. In a deployed environment (like Hugging Face Spaces), # this could be handled by environment variables. # We will check if the user provides a key via the UI. DEFAULT_API_KEY = "" # Model configuration for the Gemini API via the OpenAI client wrapper GEMINI_MODEL_NAME = "gemini-2.5-flash" GEMINI_API_BASE_URL = "https://generativelanguage.googleapis.com/v1beta/openai/" # Initial generic data for the UI GENERIC_FINANCIAL_DATA = { "salary": 100000, "sip": 30000, "bills": 25000, "shopping": 5000, "dining": 5000, "entertainment": 5000, "travel": 5000, "other_expenses": 5000, "target_surplus_percentage": 10, } def parse_financial_file(file_path): """ Parses a text file (TXT or simple CSV) for financial data. Assumes a format like 'Key: Value' or 'Key,Value'. """ if not file_path: return None extracted_data = {} # Define keywords to search for (case-insensitive) keywords = { 'salary': 'salary|income|monthly pay', 'sip': 'sip|investments|mutual fund', 'bills': 'bills|rent|emi', 'shopping': 'shopping|clothes|ecommerce', 'dining': 'dining|food|zomato|swiggy', 'entertainment': 'entertainment|ott|movies|subscriptions', 'travel': 'travel|transport|fuel', 'other_expenses': 'other|miscellaneous|misc', 'target_surplus_percentage': 'target|goal|savings percentage' } try: with open(file_path, 'r') as f: content = f.read() for key, pattern in keywords.items(): # Regex to find the key followed by a colon or comma, and then capture the number match = re.search(rf"({pattern})[:,\s]*(\d+[\.\d]*)", content, re.IGNORECASE) if match: try: # Convert the captured value to an appropriate type (float/int) value = float(match.group(2)) # Convert percentage to integer if it's the target surplus if key == 'target_surplus_percentage': extracted_data[key] = int(value) else: extracted_data[key] = int(value) except ValueError: print(f"Could not convert value for {key}") except Exception as e: return f"Error reading file: {e}" return extracted_data def generate_portfolio_download( salary, sip, bills, shopping, dining, entertainment, travel, other_expenses, target_surplus_percentage, ai_response ): """ Generates the content for the download button. """ total_income = salary total_fixed_expenses = sip + bills total_discretionary_expenses = shopping + dining + entertainment + travel + other_expenses total_expenses = total_fixed_expenses + total_discretionary_expenses net_cashflow = total_income - total_expenses target_surplus_amount = (target_surplus_percentage / 100) * total_income portfolio_content = f""" # Personal Financial Health Report ## 1. Input Data | Category | Monthly Amount (₹) | | :--- | :--- | | **Gross Monthly Salary** | ₹{salary:,.0f} | | **Fixed/Commitment Expenses** | | | Mandatory SIP/Investment | ₹{sip:,.0f} | | Bills/EMIs/Rent | ₹{bills:,.0f} | | **Discretionary Expenses** | | | Shopping | ₹{shopping:,.0f} | | Dining & Food Delivery | ₹{dining:,.0f} | | Entertainment/Subscriptions | ₹{entertainment:,.0f} | | Travel/Fuel | ₹{travel:,.0f} | | Other Expenses | ₹{other_expenses:,.0f} | | **Target Savings Goal** | {target_surplus_percentage}% of Salary | ## 2. Calculated Summary - **Total Income:** ₹{total_income:,.0f} - **Total Fixed Expenses:** ₹{total_fixed_expenses:,.0f} - **Total Discretionary Expenses:** ₹{total_discretionary_expenses:,.0f} - **Total Expenses:** ₹{total_expenses:,.0f} - **Net Cashflow (Target Surplus):** ₹{net_cashflow:,.0f} - **Target Surplus Amount:** ₹{target_surplus_amount:,.0f} - **Status:** {'Surplus' if net_cashflow > 0 else 'Deficit'} ## 3. AI Financial Coach Analysis {ai_response} --- Generated by the AI Personal Finance Agent. """ return portfolio_content def personal_finance_agent( api_key, salary, sip, bills, shopping, dining, entertainment, travel, other_expenses, target_surplus_percentage, uploaded_file, prompt ): """ Main function to run the financial analysis and AI response. Handles file parsing and API client initialization. """ # 1. API Key Initialization # Use the key from the UI if provided, otherwise default. final_api_key = api_key if api_key else os.environ.get("GEMINI_API_KEY", DEFAULT_API_KEY) if not final_api_key: return "ERROR: Gemini/OpenAI API Key is missing. Please enter your key in the 'API Key' field above.", "" try: # Initialize the client using the Gemini base URL client = OpenAI( base_url=GEMINI_API_BASE_URL, api_key=final_api_key, timeout=60.0 # Set a reasonable timeout ) except Exception as e: return f"ERROR: Could not initialize API client. Check your key and ensure connectivity. Detail: {e}", "" # 2. File Parsing and Data Overwrite if uploaded_file: file_data = parse_financial_file(uploaded_file.name) if isinstance(file_data, str) and file_data.startswith("Error"): return file_data, "" # Return file reading error if file_data: # Overwrite Gradio inputs with data from the file if found salary = file_data.get("salary", salary) sip = file_data.get("sip", sip) bills = file_data.get("bills", bills) shopping = file_data.get("shopping", shopping) dining = file_data.get("dining", dining) entertainment = file_data.get("entertainment", entertainment) travel = file_data.get("travel", travel) other_expenses = file_data.get("other_expenses", other_expenses) target_surplus_percentage = file_data.get("target_surplus_percentage", target_surplus_percentage) # Note: We return the updated input values so they are reflected in the UI gr.Info("Data loaded successfully from file. Running analysis...") else: gr.Warning("File uploaded but no matching financial data found. Using manually entered data.") # 3. Calculations total_income = salary total_fixed_expenses = sip + bills total_discretionary_expenses = shopping + dining + entertainment + travel + other_expenses total_expenses = total_fixed_expenses + total_discretionary_expenses net_cashflow = total_income - total_expenses target_surplus_amount = (target_surplus_percentage / 100) * total_income status = "Surplus" if net_cashflow > 0 else "Deficit" # 4. Dynamic System Prompt Generation system_prompt = f""" You are a world-class, empathetic personal financial analyst and coach. Your role is to analyze the user's monthly financial data and provide actionable, encouraging advice. The user's current monthly financial summary is: - Gross Monthly Salary (Income): ₹{total_income:,.0f} - Mandatory SIP/Investment: ₹{sip:,.0f} - Bills/EMIs/Rent: ₹{bills:,.0f} - Total Fixed Expenses (SIP + Bills): ₹{total_fixed_expenses:,.0f} - Total Discretionary Expenses (Shopping, Dining, etc.): ₹{total_discretionary_expenses:,.0f} - Total Expenses: ₹{total_expenses:,.0f} - **Net Cashflow (Available Surplus/Deficit)**: ₹{net_cashflow:,.0f} - **Target Monthly Savings Goal ({target_surplus_percentage}%)**: ₹{target_surplus_amount:,.0f} - **Current Status**: {status} Based on the detailed discretionary spending below, provide: 1. A brief summary of their current financial health (e.g., Are they meeting their goal?). 2. Specific, positive, and practical recommendations (e.g., "Reduce dining by ₹X to achieve your target."). 3. Use Indian Rupee (₹) formatting and address the user directly. 4. Focus heavily on optimizing discretionary spending areas: Shopping, Dining, Entertainment, Travel, and Other. """ # 5. User Query user_query = f""" My current discretionary spending breakdown is: - Shopping: ₹{shopping:,.0f} - Dining & Food Delivery: ₹{dining:,.0f} - Entertainment/Subscriptions: ₹{entertainment:,.0f} - Travel/Fuel: ₹{travel:,.0f} - Other Expenses: ₹{other_expenses:,.0f} Please provide your analysis and coaching based on the system prompt and this prompt. User prompt/request: "{prompt}" """ try: # 6. API Call response = client.chat.completions.create( model=GEMINI_MODEL_NAME, messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_query} ], temperature=0.7, ) ai_response = response.choices[0].message.content except Exception as e: ai_response = f"An API error occurred: {e}" # 7. Format Output and Return # Detailed financial summary to display on the UI summary_html = f"""
Total Income: ₹{total_income:,.0f}
Total Expenses: ₹{total_expenses:,.0f} (Fixed: ₹{total_fixed_expenses:,.0f} | Discretionary: ₹{total_discretionary_expenses:,.0f})
Target Savings Goal ({target_surplus_percentage}%): ₹{target_surplus_amount:,.0f}
= target_surplus_amount else '#dc3545'};'> Net Cashflow (Surplus/Deficit): ₹{net_cashflow:,.0f}
Enter your data and press Analyze to see your summary.
" ) ai_response_output = gr.Markdown( label="AI Coach Response", value="The AI's personalized advice will appear here." ) # --- Event Handlers --- # List of all input components inputs = [ api_key_input, salary_input, sip_input, bills_input, shopping_input, dining_input, entertainment_input, travel_input, other_expenses_input, target_surplus_input, file_upload, prompt_input ] # List of output components (note: we also return updated input values to reflect file load) outputs = [ financial_summary_output, ai_response_output, salary_input, sip_input, bills_input, shopping_input, dining_input, entertainment_input, travel_input, other_expenses_input, target_surplus_input ] # The main analysis flow run_button.click( fn=personal_finance_agent, inputs=inputs, outputs=outputs, queue=False, ).then( # Second chain: Update the state and download button content after analysis fn=lambda *args: (args[-1], generate_portfolio_download(*args[1:10], args[-1])), inputs=[ api_key_input, salary_input, sip_input, bills_input, shopping_input, dining_input, entertainment_input, travel_input, other_expenses_input, target_surplus_input, ai_response_output ], outputs=[last_ai_response, download_btn], queue=False, ) # Logic to auto-run on file upload if an API key is present file_upload.change( fn=personal_finance_agent, inputs=inputs, outputs=outputs, queue=False, show_progress="full", ).then( # Second chain: Update the state and download button content after file load analysis fn=lambda *args: (args[-1], generate_portfolio_download(*args[1:10], args[-1])), inputs=[ api_key_input, salary_input, sip_input, bills_input, shopping_input, dining_input, entertainment_input, travel_input, other_expenses_input, target_surplus_input, ai_response_output ], outputs=[last_ai_response, download_btn], queue=False, ) # demo.launch() # Uncomment this line if running locally