PFA / app.py
chatbotdeveloper2025genai's picture
Upload folder using huggingface_hub
a230374 verified
Raw History Blame Contribute Delete
18.9 kB
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