Spaces:
Runtime error
Runtime error
File size: 18,889 Bytes
a230374 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 | 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"""
<div style='padding: 15px; border-radius: 8px; background-color: #f7f9fb; border-left: 5px solid #007bff;'>
<h4 style='margin-top: 0; color: #007bff;'>Current Financial Snapshot</h4>
<p><strong>Total Income:</strong> ₹{total_income:,.0f}</p>
<p><strong>Total Expenses:</strong> ₹{total_expenses:,.0f} (Fixed: ₹{total_fixed_expenses:,.0f} | Discretionary: ₹{total_discretionary_expenses:,.0f})</p>
<p><strong>Target Savings Goal ({target_surplus_percentage}%):</strong> ₹{target_surplus_amount:,.0f}</p>
<p style='font-size: 1.2em; font-weight: bold; color: {'#28a745' if net_cashflow >= target_surplus_amount else '#dc3545'};'>
Net Cashflow (Surplus/Deficit): ₹{net_cashflow:,.0f}
</p>
</div>
"""
return summary_html, ai_response, salary, sip, bills, shopping, dining, entertainment, travel, other_expenses, target_surplus_percentage
# --- Gradio UI Definition ---
with gr.Blocks(title="AI Personal Finance Coach") as demo:
gr.Markdown("# 🤖 AI Personal Finance Coach: Powered by Gemini 2.5 Flash")
gr.Markdown(
"""
Enter your monthly financial data or upload a file to get personalized budgeting advice
from a Gemini-powered financial analyst. Advice is dynamically adjusted based on your inputs.
"""
)
# State variable to store the last AI response for the download button
last_ai_response = gr.State("")
with gr.Row():
# Configuration Column (API Key & File Upload)
with gr.Column(scale=1):
gr.Markdown("## ⚙️ Configuration")
api_key_input = gr.Textbox(
label="Gemini/OpenAI API Key (Required)",
type="password",
value="",
placeholder="Enter your API Key here...",
info="Your key is not stored and is only used for this session.",
interactive=True
)
file_upload = gr.File(
label="Upload Financial Data File (Optional)",
file_types=[".txt", ".csv"],
info="Upload a file with 'Key: Value' pairs (e.g., 'Salary: 100000', 'Bills: 30000').",
interactive=True
)
download_btn = gr.DownloadButton(
label="Download Portfolio Report (.txt)",
value=lambda: "No data generated yet.", # Initial dummy value
filename="financial_report.txt",
scale=0
)
# Financial Inputs Column
with gr.Column(scale=2):
gr.Markdown("## 💸 Your Monthly Finances (in ₹)")
# --- Income and Fixed Expenses ---
with gr.Row():
salary_input = gr.Slider(
label="1. Gross Monthly Salary (Income)",
minimum=10000,
maximum=500000,
value=GENERIC_FINANCIAL_DATA["salary"],
step=1000,
interactive=True
)
with gr.Row():
sip_input = gr.Slider(
label="2. Mandatory SIP/Investment",
minimum=0,
maximum=100000,
value=GENERIC_FINANCIAL_DATA["sip"],
step=500,
interactive=True
)
bills_input = gr.Slider(
label="3. Bills/EMIs/Rent",
minimum=0,
maximum=200000,
value=GENERIC_FINANCIAL_DATA["bills"],
step=500,
interactive=True
)
gr.Markdown("### Discretionary Expenses")
# --- Discretionary Expenses ---
with gr.Row():
shopping_input = gr.Slider(
label="4. Shopping",
minimum=0,
maximum=50000,
value=GENERIC_FINANCIAL_DATA["shopping"],
step=100,
interactive=True
)
dining_input = gr.Slider(
label="5. Dining & Food Delivery",
minimum=0,
maximum=50000,
value=GENERIC_FINANCIAL_DATA["dining"],
step=100,
interactive=True
)
with gr.Row():
entertainment_input = gr.Slider(
label="6. Entertainment/Subscriptions",
minimum=0,
maximum=20000,
value=GENERIC_FINANCIAL_DATA["entertainment"],
step=50,
interactive=True
)
travel_input = gr.Slider(
label="7. Travel/Fuel",
minimum=0,
maximum=50000,
value=GENERIC_FINANCIAL_DATA["travel"],
step=100,
interactive=True
)
other_expenses_input = gr.Slider(
label="8. Other Expenses",
minimum=0,
maximum=30000,
value=GENERIC_FINANCIAL_DATA["other_expenses"],
step=100,
interactive=True
)
# --- Savings Goal ---
target_surplus_input = gr.Slider(
label="9. Target Savings Percentage (%)",
minimum=0,
maximum=50,
value=GENERIC_FINANCIAL_DATA["target_surplus_percentage"],
step=1,
interactive=True
)
gr.Markdown("---")
# --- Prompt and Action ---
prompt_input = gr.Textbox(
label="Your Specific Question (Optional)",
placeholder="e.g., How can I reduce my spending on food delivery?",
value="Analyze my current spending and suggest two actionable ways to increase my net cashflow."
)
run_button = gr.Button("💰 Analyze My Finances & Get Coaching")
# --- Output Section ---
gr.Markdown("## 📈 AI Financial Analysis & Coaching")
financial_summary_output = gr.HTML(
label="Financial Summary",
value="<p style='color: grey;'>Enter your data and press Analyze to see your summary.</p>"
)
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
|