Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,56 +1,78 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
import numpy as np
|
| 4 |
import pandas as pd
|
| 5 |
import torch
|
| 6 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 7 |
import gradio as gr
|
|
|
|
| 8 |
|
| 9 |
-
#
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
# Financial knowledge base - simple templates and responses
|
| 15 |
financial_templates = {
|
| 16 |
"budget": "Here's a simple budget template based on the 50/30/20 rule:\n- 50% for needs (rent, groceries, utilities)\n- 30% for wants (dining out, entertainment)\n- 20% for savings and debt repayment",
|
| 17 |
-
"
|
| 18 |
"debt": "Focus on high-interest debt first (like credit cards). Consider the debt avalanche (highest interest first) or debt snowball (smallest balance first) methods.",
|
| 19 |
"investing": "For beginners, consider index funds or ETFs for diversification. Time in the market beats timing the market.",
|
| 20 |
-
"retirement": "Take advantage of employer matches in retirement accounts - it's free money. Start early to benefit from compound interest."
|
|
|
|
|
|
|
| 21 |
}
|
| 22 |
|
| 23 |
# Define guided chat flow
|
| 24 |
def guided_response(user_message, chat_history):
|
| 25 |
# Check if we should use a template response
|
| 26 |
for key, template in financial_templates.items():
|
| 27 |
-
if key in user_message.lower():
|
| 28 |
-
return template
|
| 29 |
-
|
| 30 |
-
# For more general queries, use the AI model
|
| 31 |
-
prompt = f"""<human>I need financial advice: {user_message}</human>
|
| 32 |
-
<assistant>"""
|
| 33 |
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
max_length=
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
|
|
|
|
|
|
| 47 |
|
| 48 |
-
return response
|
| 49 |
|
| 50 |
# Create budget calculator function
|
| 51 |
def calculate_budget(monthly_income, housing, utilities, groceries, transportation):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
total_needs = housing + utilities + groceries + transportation
|
| 53 |
-
needs_percent = (total_needs / monthly_income) * 100
|
| 54 |
|
| 55 |
available_for_wants = monthly_income * 0.3
|
| 56 |
available_for_savings = monthly_income * 0.2
|
|
@@ -69,19 +91,28 @@ def calculate_budget(monthly_income, housing, utilities, groceries, transportati
|
|
| 69 |
# Setup Gradio interface with tabs
|
| 70 |
with gr.Blocks() as app:
|
| 71 |
gr.Markdown("# Financial Advisor Bot")
|
|
|
|
| 72 |
|
| 73 |
with gr.Tab("Chat Advisor"):
|
| 74 |
chatbot = gr.Chatbot(height=400)
|
| 75 |
-
msg = gr.Textbox(label="Ask
|
| 76 |
clear = gr.Button("Clear")
|
| 77 |
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
chat_history.append((message, bot_message))
|
| 81 |
-
return "", chat_history
|
| 82 |
-
|
| 83 |
-
msg.submit(respond, [msg, chatbot], [msg, chatbot])
|
| 84 |
clear.click(lambda: None, None, chatbot, queue=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
with gr.Tab("Budget Calculator"):
|
| 87 |
gr.Markdown("## 50/30/20 Budget Calculator")
|
|
@@ -97,7 +128,7 @@ with gr.Blocks() as app:
|
|
| 97 |
transport = gr.Number(label="Transportation", value=0)
|
| 98 |
|
| 99 |
calculate_btn = gr.Button("Calculate Budget")
|
| 100 |
-
output = gr.Textbox(label="Budget Analysis", lines=
|
| 101 |
|
| 102 |
calculate_btn.click(
|
| 103 |
calculate_budget,
|
|
@@ -105,5 +136,5 @@ with gr.Blocks() as app:
|
|
| 105 |
outputs=output
|
| 106 |
)
|
| 107 |
|
| 108 |
-
# Launch the app
|
| 109 |
-
app.launch(
|
|
|
|
| 1 |
+
# app.py - Main file for Hugging Face Spaces deployment
|
|
|
|
| 2 |
import numpy as np
|
| 3 |
import pandas as pd
|
| 4 |
import torch
|
|
|
|
| 5 |
import gradio as gr
|
| 6 |
+
from transformers import pipeline, AutoTokenizer
|
| 7 |
|
| 8 |
+
# Use a more lightweight approach with the pipeline API
|
| 9 |
+
# This is more memory-efficient for Spaces deployment
|
| 10 |
+
try:
|
| 11 |
+
# First try to load a lightweight text generation model
|
| 12 |
+
generator = pipeline('text-generation',
|
| 13 |
+
model="distilgpt2",
|
| 14 |
+
max_length=100)
|
| 15 |
+
tokenizer = AutoTokenizer.from_pretrained("distilgpt2")
|
| 16 |
+
print("Using distilGPT2 model")
|
| 17 |
+
except Exception as e:
|
| 18 |
+
# Fallback to an even smaller model if resources are limited
|
| 19 |
+
print(f"Error loading distilGPT2: {e}")
|
| 20 |
+
print("Falling back to smaller model")
|
| 21 |
+
generator = pipeline('text-generation',
|
| 22 |
+
model="sshleifer/tiny-gpt2",
|
| 23 |
+
max_length=100)
|
| 24 |
+
tokenizer = AutoTokenizer.from_pretrained("sshleifer/tiny-gpt2")
|
| 25 |
|
| 26 |
# Financial knowledge base - simple templates and responses
|
| 27 |
financial_templates = {
|
| 28 |
"budget": "Here's a simple budget template based on the 50/30/20 rule:\n- 50% for needs (rent, groceries, utilities)\n- 30% for wants (dining out, entertainment)\n- 20% for savings and debt repayment",
|
| 29 |
+
"emergency fund": "An emergency fund should ideally cover 3-6 months of expenses. Start with a goal of $1,000, then build from there.",
|
| 30 |
"debt": "Focus on high-interest debt first (like credit cards). Consider the debt avalanche (highest interest first) or debt snowball (smallest balance first) methods.",
|
| 31 |
"investing": "For beginners, consider index funds or ETFs for diversification. Time in the market beats timing the market.",
|
| 32 |
+
"retirement": "Take advantage of employer matches in retirement accounts - it's free money. Start early to benefit from compound interest.",
|
| 33 |
+
"save money": "To save money, try the 30-day rule (wait 30 days before making non-essential purchases), meal prep to reduce food costs, and use cashback apps for everyday purchases.",
|
| 34 |
+
"credit score": "To improve your credit score: pay bills on time, reduce credit card balances, don't close old accounts, and check your credit report regularly for errors."
|
| 35 |
}
|
| 36 |
|
| 37 |
# Define guided chat flow
|
| 38 |
def guided_response(user_message, chat_history):
|
| 39 |
# Check if we should use a template response
|
| 40 |
for key, template in financial_templates.items():
|
| 41 |
+
if key.lower() in user_message.lower():
|
| 42 |
+
return "", chat_history + [[user_message, template]]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
+
# For more general queries, use the AI model with a financial prefix
|
| 45 |
+
try:
|
| 46 |
+
prompt = f"The following is financial advice: {user_message}\nFinancial advisor:"
|
| 47 |
+
outputs = generator(prompt, max_length=150, temperature=0.7, num_return_sequences=1)
|
| 48 |
+
|
| 49 |
+
# Extract relevant part of the response
|
| 50 |
+
response = outputs[0]['generated_text'].replace(prompt, "").strip()
|
| 51 |
+
# Cleanup and limit response
|
| 52 |
+
response = response.split('.')[0] + '.' if '.' in response else response
|
| 53 |
+
|
| 54 |
+
# Add disclaimer for AI-generated content
|
| 55 |
+
response += "\n\n(Note: This is general advice. Please consult a professional financial advisor for specific situations.)"
|
| 56 |
+
|
| 57 |
+
except Exception as e:
|
| 58 |
+
response = f"I'm sorry, I couldn't generate advice at the moment. Please try asking about budgeting, emergency funds, debt, investing, or retirement."
|
| 59 |
|
| 60 |
+
return "", chat_history + [[user_message, response]]
|
| 61 |
|
| 62 |
# Create budget calculator function
|
| 63 |
def calculate_budget(monthly_income, housing, utilities, groceries, transportation):
|
| 64 |
+
if not monthly_income or monthly_income <= 0:
|
| 65 |
+
return "Please enter a valid monthly income greater than zero."
|
| 66 |
+
|
| 67 |
+
# Convert inputs to float and handle potential None values
|
| 68 |
+
housing = float(housing or 0)
|
| 69 |
+
utilities = float(utilities or 0)
|
| 70 |
+
groceries = float(groceries or 0)
|
| 71 |
+
transportation = float(transportation or 0)
|
| 72 |
+
monthly_income = float(monthly_income)
|
| 73 |
+
|
| 74 |
total_needs = housing + utilities + groceries + transportation
|
| 75 |
+
needs_percent = (total_needs / monthly_income) * 100 if monthly_income > 0 else 0
|
| 76 |
|
| 77 |
available_for_wants = monthly_income * 0.3
|
| 78 |
available_for_savings = monthly_income * 0.2
|
|
|
|
| 91 |
# Setup Gradio interface with tabs
|
| 92 |
with gr.Blocks() as app:
|
| 93 |
gr.Markdown("# Financial Advisor Bot")
|
| 94 |
+
gr.Markdown("Ask questions about personal finance or use the budget calculator.")
|
| 95 |
|
| 96 |
with gr.Tab("Chat Advisor"):
|
| 97 |
chatbot = gr.Chatbot(height=400)
|
| 98 |
+
msg = gr.Textbox(label="Ask about budgeting, emergency funds, debt, investing, retirement, etc.")
|
| 99 |
clear = gr.Button("Clear")
|
| 100 |
|
| 101 |
+
# Set up the chat interface
|
| 102 |
+
msg.submit(guided_response, [msg, chatbot], [msg, chatbot])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
clear.click(lambda: None, None, chatbot, queue=False)
|
| 104 |
+
|
| 105 |
+
# Add some example prompts to help users
|
| 106 |
+
gr.Examples(
|
| 107 |
+
examples=[
|
| 108 |
+
"How should I create a budget?",
|
| 109 |
+
"How much should I save for an emergency fund?",
|
| 110 |
+
"What's the best way to pay off debt?",
|
| 111 |
+
"How should I start investing?",
|
| 112 |
+
"How can I save for retirement?"
|
| 113 |
+
],
|
| 114 |
+
inputs=msg
|
| 115 |
+
)
|
| 116 |
|
| 117 |
with gr.Tab("Budget Calculator"):
|
| 118 |
gr.Markdown("## 50/30/20 Budget Calculator")
|
|
|
|
| 128 |
transport = gr.Number(label="Transportation", value=0)
|
| 129 |
|
| 130 |
calculate_btn = gr.Button("Calculate Budget")
|
| 131 |
+
output = gr.Textbox(label="Budget Analysis", lines=8)
|
| 132 |
|
| 133 |
calculate_btn.click(
|
| 134 |
calculate_budget,
|
|
|
|
| 136 |
outputs=output
|
| 137 |
)
|
| 138 |
|
| 139 |
+
# Launch the app
|
| 140 |
+
app.launch()
|