Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,96 +1,87 @@
|
|
|
|
|
|
|
|
| 1 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 2 |
import torch
|
| 3 |
import gradio as gr
|
| 4 |
|
| 5 |
-
#
|
| 6 |
-
|
|
|
|
| 7 |
|
| 8 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
response_cache = {
|
| 10 |
-
"hi": "Hello! I'm your financial advisor. How can I help
|
| 11 |
-
"hello": "Hello! I'm your financial advisor. How can I help
|
| 12 |
-
"hey": "Hi there! Ready to discuss
|
| 13 |
"hi, pretend you are a financial advisor. now tell me how can i start investing in stock market?": (
|
| 14 |
-
"
|
| 15 |
-
"1. **Learn**: Use Investopedia or
|
| 16 |
"2. **Goals**: Set objectives (e.g., retirement) and assess risk tolerance.\n"
|
| 17 |
-
"3. **Brokerage**: Choose Fidelity
|
| 18 |
-
"4. **Investments**: Start with ETFs (e.g., VOO
|
| 19 |
-
"5. **Strategy**: Use dollar-cost averaging
|
| 20 |
"6. **Risks**: Diversify and monitor.\n"
|
| 21 |
"Consult a certified financial planner."
|
| 22 |
),
|
| 23 |
"do you have a list of companies you recommend?": (
|
| 24 |
-
"I cannot recommend specific companies without current
|
| 25 |
-
"
|
| 26 |
-
"Consult a
|
| 27 |
-
),
|
| 28 |
-
"can you provide me a list of companies you recommend?": (
|
| 29 |
-
"I cannot provide specific company recommendations without up-to-date market analysis. For safer investments, consider ETFs like VOO (S&P 500) or QQQ (tech-focused). "
|
| 30 |
-
"If interested in stocks, explore stable companies in technology (e.g., Apple, Microsoft) or healthcare (e.g., Johnson & Johnson) using Yahoo Finance. "
|
| 31 |
-
"Always consult a financial planner for tailored advice."
|
| 32 |
-
),
|
| 33 |
-
"you have a list of companies you recommend?": (
|
| 34 |
-
"I cannot recommend specific companies without current market data. Instead, consider ETFs like VOO (S&P 500) or QQQ (tech-focused) for broad exposure. "
|
| 35 |
-
"For stocks, research sectors like technology (e.g., Apple, Microsoft) or consumer goods (e.g., Procter & Gamble) using Yahoo Finance or Morningstar. "
|
| 36 |
-
"Consult a certified financial planner."
|
| 37 |
),
|
| 38 |
"how do i start investing in stocks?": (
|
| 39 |
-
"
|
| 40 |
-
"
|
| 41 |
-
"and begin with diversified options like ETFs (e.g., VOO) or mutual funds. Consult a financial planner for personalized advice."
|
| 42 |
-
),
|
| 43 |
-
"what are the best stocks to buy right now?": (
|
| 44 |
-
"I can’t recommend specific stocks without current market data. For a safer approach, consider ETFs like VOO (S&P 500) or QQQ (tech-focused). "
|
| 45 |
-
"If you prefer stocks, research companies in strong sectors like technology or healthcare using tools like Yahoo Finance. "
|
| 46 |
-
"Consult a financial planner for up-to-date advice."
|
| 47 |
),
|
| 48 |
"what's the difference between stocks and bonds?": (
|
| 49 |
-
"Stocks
|
| 50 |
-
"
|
| 51 |
),
|
| 52 |
"how much should i invest?": (
|
| 53 |
-
"
|
| 54 |
-
"
|
| 55 |
),
|
| 56 |
"what is dollar-cost averaging?": (
|
| 57 |
-
"Dollar-cost averaging
|
| 58 |
-
"
|
| 59 |
)
|
| 60 |
}
|
| 61 |
|
| 62 |
-
# Load model
|
| 63 |
model_name = "facebook/opt-350m"
|
| 64 |
try:
|
|
|
|
| 65 |
tokenizer = AutoTokenizer.from_pretrained(model_name, clean_up_tokenization_spaces=False)
|
|
|
|
| 66 |
model = AutoModelForCausalLM.from_pretrained(
|
| 67 |
model_name,
|
| 68 |
-
device_map="auto",
|
| 69 |
torch_dtype=torch.float16
|
| 70 |
).to(device)
|
| 71 |
except Exception as e:
|
| 72 |
-
|
| 73 |
-
|
| 74 |
|
| 75 |
# Pre-tokenize minimal prompt prefix
|
| 76 |
-
prompt_prefix =
|
| 77 |
-
"You are a financial advisor. Provide accurate, concise advice in one response. "
|
| 78 |
-
"If you cannot give specific recommendations, explain why and suggest alternatives.\n\n"
|
| 79 |
-
"Q: "
|
| 80 |
-
)
|
| 81 |
prefix_tokens = tokenizer(prompt_prefix, return_tensors="pt", truncation=True, max_length=512).to(device)
|
| 82 |
|
| 83 |
# Define chat function
|
| 84 |
-
def chat_with_model(message, history=None):
|
| 85 |
try:
|
| 86 |
-
|
|
|
|
| 87 |
cache_key = message.lower().strip()
|
| 88 |
if cache_key in response_cache:
|
|
|
|
| 89 |
return response_cache[cache_key]
|
| 90 |
|
| 91 |
-
# Skip model for
|
| 92 |
if len(message.strip()) <= 5:
|
| 93 |
-
|
|
|
|
| 94 |
|
| 95 |
# Construct prompt
|
| 96 |
full_prompt = prompt_prefix + message + "\nA:"
|
|
@@ -100,29 +91,39 @@ def chat_with_model(message, history=None): # Ignore history
|
|
| 100 |
with torch.no_grad():
|
| 101 |
outputs = model.generate(
|
| 102 |
**inputs,
|
| 103 |
-
max_new_tokens=15,
|
| 104 |
-
do_sample=False,
|
| 105 |
pad_token_id=tokenizer.eos_token_id
|
| 106 |
)
|
| 107 |
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
|
|
|
| 108 |
return response[len(full_prompt):].strip() if response.startswith(full_prompt) else response
|
| 109 |
except Exception as e:
|
| 110 |
-
|
|
|
|
| 111 |
|
| 112 |
# Create Gradio interface
|
|
|
|
| 113 |
interface = gr.ChatInterface(
|
| 114 |
fn=chat_with_model,
|
| 115 |
title="Financial Advisor Chatbot (OPT-350m)",
|
| 116 |
-
description="Ask
|
| 117 |
examples=[
|
| 118 |
"Hi",
|
| 119 |
"Hi, pretend you are a financial advisor. Now tell me how can I start investing in stock market?",
|
| 120 |
-
"
|
| 121 |
"What's the difference between stocks and bonds?",
|
| 122 |
-
"How much should I invest?"
|
| 123 |
-
"What is dollar-cost averaging?"
|
| 124 |
]
|
| 125 |
)
|
| 126 |
|
| 127 |
-
# Launch interface
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import os
|
| 3 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 4 |
import torch
|
| 5 |
import gradio as gr
|
| 6 |
|
| 7 |
+
# Set up logging
|
| 8 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
| 9 |
+
logger = logging.getLogger(__name__)
|
| 10 |
|
| 11 |
+
# Define device (force CPU for Spaces compatibility)
|
| 12 |
+
device = torch.device("cpu")
|
| 13 |
+
logger.info(f"Using device: {device}")
|
| 14 |
+
|
| 15 |
+
# Response cache with short prompts
|
| 16 |
response_cache = {
|
| 17 |
+
"hi": "Hello! I'm your financial advisor. How can I help with investing?",
|
| 18 |
+
"hello": "Hello! I'm your financial advisor. How can I help with investing?",
|
| 19 |
+
"hey": "Hi there! Ready to discuss investment goals?",
|
| 20 |
"hi, pretend you are a financial advisor. now tell me how can i start investing in stock market?": (
|
| 21 |
+
"Here’s a guide to start investing in the stock market:\n"
|
| 22 |
+
"1. **Learn**: Use Investopedia or 'The Intelligent Investor' by Benjamin Graham.\n"
|
| 23 |
"2. **Goals**: Set objectives (e.g., retirement) and assess risk tolerance.\n"
|
| 24 |
+
"3. **Brokerage**: Choose Fidelity, Vanguard, or Robinhood.\n"
|
| 25 |
+
"4. **Investments**: Start with ETFs (e.g., VOO) or mutual funds.\n"
|
| 26 |
+
"5. **Strategy**: Use dollar-cost averaging ($100-$500 monthly).\n"
|
| 27 |
"6. **Risks**: Diversify and monitor.\n"
|
| 28 |
"Consult a certified financial planner."
|
| 29 |
),
|
| 30 |
"do you have a list of companies you recommend?": (
|
| 31 |
+
"I cannot recommend specific companies without current data. Consider ETFs like VOO (S&P 500) or QQQ (tech). "
|
| 32 |
+
"Research sectors like technology (e.g., Apple) or healthcare (e.g., Johnson & Johnson) on Yahoo Finance. "
|
| 33 |
+
"Consult a financial planner."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
),
|
| 35 |
"how do i start investing in stocks?": (
|
| 36 |
+
"Educate yourself with Investopedia or 'The Intelligent Investor.' Set goals and assess risk tolerance. "
|
| 37 |
+
"Open a brokerage account with Fidelity or Vanguard and start with ETFs (e.g., VOO). Consult a financial planner."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
),
|
| 39 |
"what's the difference between stocks and bonds?": (
|
| 40 |
+
"Stocks offer ownership in a company with growth potential but higher risk. Bonds are loans to companies/governments, "
|
| 41 |
+
"offering steady interest with lower risk. Diversify with both for balance."
|
| 42 |
),
|
| 43 |
"how much should i invest?": (
|
| 44 |
+
"Invest what you can afford after expenses and an emergency fund (3-6 months’ savings). Start with $100-$500 monthly "
|
| 45 |
+
"in ETFs like VOO using dollar-cost averaging. Consult a financial planner."
|
| 46 |
),
|
| 47 |
"what is dollar-cost averaging?": (
|
| 48 |
+
"Dollar-cost averaging is investing a fixed amount regularly (e.g., $100 monthly) in assets like ETFs, "
|
| 49 |
+
"reducing risk by spreading purchases over time."
|
| 50 |
)
|
| 51 |
}
|
| 52 |
|
| 53 |
+
# Load model and tokenizer
|
| 54 |
model_name = "facebook/opt-350m"
|
| 55 |
try:
|
| 56 |
+
logger.info(f"Loading tokenizer for {model_name}")
|
| 57 |
tokenizer = AutoTokenizer.from_pretrained(model_name, clean_up_tokenization_spaces=False)
|
| 58 |
+
logger.info(f"Loading model {model_name}")
|
| 59 |
model = AutoModelForCausalLM.from_pretrained(
|
| 60 |
model_name,
|
|
|
|
| 61 |
torch_dtype=torch.float16
|
| 62 |
).to(device)
|
| 63 |
except Exception as e:
|
| 64 |
+
logger.error(f"Error loading model/tokenizer: {e}")
|
| 65 |
+
raise
|
| 66 |
|
| 67 |
# Pre-tokenize minimal prompt prefix
|
| 68 |
+
prompt_prefix = "You are a financial advisor. Provide concise advice. If no specific recommendations, suggest alternatives.\nQ: "
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
prefix_tokens = tokenizer(prompt_prefix, return_tensors="pt", truncation=True, max_length=512).to(device)
|
| 70 |
|
| 71 |
# Define chat function
|
| 72 |
+
def chat_with_model(message, history=None):
|
| 73 |
try:
|
| 74 |
+
logger.info(f"Processing message: {message}")
|
| 75 |
+
# Normalize input for cache
|
| 76 |
cache_key = message.lower().strip()
|
| 77 |
if cache_key in response_cache:
|
| 78 |
+
logger.info("Cache hit")
|
| 79 |
return response_cache[cache_key]
|
| 80 |
|
| 81 |
+
# Skip model for short prompts
|
| 82 |
if len(message.strip()) <= 5:
|
| 83 |
+
logger.info("Short prompt, returning default response")
|
| 84 |
+
return "Hello! I'm your financial advisor. Ask about investing!"
|
| 85 |
|
| 86 |
# Construct prompt
|
| 87 |
full_prompt = prompt_prefix + message + "\nA:"
|
|
|
|
| 91 |
with torch.no_grad():
|
| 92 |
outputs = model.generate(
|
| 93 |
**inputs,
|
| 94 |
+
max_new_tokens=15,
|
| 95 |
+
do_sample=False,
|
| 96 |
pad_token_id=tokenizer.eos_token_id
|
| 97 |
)
|
| 98 |
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 99 |
+
logger.info("Generated response")
|
| 100 |
return response[len(full_prompt):].strip() if response.startswith(full_prompt) else response
|
| 101 |
except Exception as e:
|
| 102 |
+
logger.error(f"Error generating response: {e}")
|
| 103 |
+
return f"Error: {str(e)}"
|
| 104 |
|
| 105 |
# Create Gradio interface
|
| 106 |
+
logger.info("Initializing Gradio interface")
|
| 107 |
interface = gr.ChatInterface(
|
| 108 |
fn=chat_with_model,
|
| 109 |
title="Financial Advisor Chatbot (OPT-350m)",
|
| 110 |
+
description="Ask about investing! Powered by Meta AI's OPT-350m. Fast, direct answers.",
|
| 111 |
examples=[
|
| 112 |
"Hi",
|
| 113 |
"Hi, pretend you are a financial advisor. Now tell me how can I start investing in stock market?",
|
| 114 |
+
"Do you have a list of companies you recommend?",
|
| 115 |
"What's the difference between stocks and bonds?",
|
| 116 |
+
"How much should I invest?"
|
|
|
|
| 117 |
]
|
| 118 |
)
|
| 119 |
|
| 120 |
+
# Launch interface (conditional for Spaces)
|
| 121 |
+
if __name__ == "__main__" and not os.getenv("HF_SPACE"):
|
| 122 |
+
logger.info("Launching Gradio interface locally")
|
| 123 |
+
try:
|
| 124 |
+
interface.launch(share=False, debug=True)
|
| 125 |
+
except Exception as e:
|
| 126 |
+
logger.error(f"Error launching interface: {e}")
|
| 127 |
+
raise
|
| 128 |
+
else:
|
| 129 |
+
logger.info("Running in Hugging Face Spaces, interface defined but not launched")
|