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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
|
| 4 |
+
import torch
|
| 5 |
+
import requests
|
| 6 |
+
import json
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
|
| 9 |
+
class FinanceAgent:
|
| 10 |
+
def __init__(self):
|
| 11 |
+
"""Initialize the Finance Agent with a language model"""
|
| 12 |
+
try:
|
| 13 |
+
# Use a lightweight model that works well for text generation
|
| 14 |
+
model_name = "microsoft/DialoGPT-medium"
|
| 15 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 16 |
+
self.model = AutoModelForCausalLM.from_pretrained(model_name)
|
| 17 |
+
|
| 18 |
+
# Add padding token if it doesn't exist
|
| 19 |
+
if self.tokenizer.pad_token is None:
|
| 20 |
+
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 21 |
+
|
| 22 |
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 23 |
+
self.model.to(self.device)
|
| 24 |
+
|
| 25 |
+
except Exception as e:
|
| 26 |
+
print(f"Error initializing model: {e}")
|
| 27 |
+
self.model = None
|
| 28 |
+
self.tokenizer = None
|
| 29 |
+
|
| 30 |
+
def get_finance_knowledge_base(self):
|
| 31 |
+
"""Finance knowledge base for common topics"""
|
| 32 |
+
return {
|
| 33 |
+
"stocks": {
|
| 34 |
+
"definition": "Stocks represent ownership shares in a company",
|
| 35 |
+
"key_points": [
|
| 36 |
+
"Stock prices fluctuate based on supply and demand",
|
| 37 |
+
"Dividends provide regular income to shareholders",
|
| 38 |
+
"Growth stocks focus on capital appreciation",
|
| 39 |
+
"Value stocks are typically undervalued by the market",
|
| 40 |
+
"Diversification reduces investment risk"
|
| 41 |
+
]
|
| 42 |
+
},
|
| 43 |
+
"bonds": {
|
| 44 |
+
"definition": "Bonds are debt securities issued by corporations or governments",
|
| 45 |
+
"key_points": [
|
| 46 |
+
"Bonds pay fixed interest over time",
|
| 47 |
+
"Government bonds are generally safer than corporate bonds",
|
| 48 |
+
"Bond prices move inversely to interest rates",
|
| 49 |
+
"Credit rating affects bond yields",
|
| 50 |
+
"Bonds provide portfolio stability"
|
| 51 |
+
]
|
| 52 |
+
},
|
| 53 |
+
"cryptocurrency": {
|
| 54 |
+
"definition": "Digital currencies secured by cryptography",
|
| 55 |
+
"key_points": [
|
| 56 |
+
"Bitcoin was the first cryptocurrency",
|
| 57 |
+
"Blockchain technology ensures security",
|
| 58 |
+
"High volatility characterizes crypto markets",
|
| 59 |
+
"Regulatory uncertainty affects prices",
|
| 60 |
+
"Limited supply drives scarcity value"
|
| 61 |
+
]
|
| 62 |
+
},
|
| 63 |
+
"investing": {
|
| 64 |
+
"definition": "Allocating money to generate returns over time",
|
| 65 |
+
"key_points": [
|
| 66 |
+
"Start early to benefit from compound interest",
|
| 67 |
+
"Diversify across asset classes",
|
| 68 |
+
"Consider risk tolerance and time horizon",
|
| 69 |
+
"Regular investing through dollar-cost averaging",
|
| 70 |
+
"Rebalance portfolio periodically"
|
| 71 |
+
]
|
| 72 |
+
},
|
| 73 |
+
"retirement": {
|
| 74 |
+
"definition": "Planning for financial security after working years",
|
| 75 |
+
"key_points": [
|
| 76 |
+
"401(k) plans offer tax advantages",
|
| 77 |
+
"IRA accounts provide additional savings options",
|
| 78 |
+
"Social Security provides base income",
|
| 79 |
+
"Healthcare costs increase in retirement",
|
| 80 |
+
"Estate planning protects beneficiaries"
|
| 81 |
+
]
|
| 82 |
+
},
|
| 83 |
+
"budgeting": {
|
| 84 |
+
"definition": "Planning and controlling personal expenses",
|
| 85 |
+
"key_points": [
|
| 86 |
+
"Track income and expenses regularly",
|
| 87 |
+
"Follow the 50/30/20 rule for allocation",
|
| 88 |
+
"Build an emergency fund",
|
| 89 |
+
"Automate savings and bill payments",
|
| 90 |
+
"Review and adjust budget monthly"
|
| 91 |
+
]
|
| 92 |
+
}
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
def generate_finance_response(self, user_input):
|
| 96 |
+
"""Generate a comprehensive finance response"""
|
| 97 |
+
user_input_lower = user_input.lower()
|
| 98 |
+
knowledge_base = self.get_finance_knowledge_base()
|
| 99 |
+
|
| 100 |
+
# Find relevant topics
|
| 101 |
+
relevant_topics = []
|
| 102 |
+
for topic, info in knowledge_base.items():
|
| 103 |
+
if topic in user_input_lower or any(keyword in user_input_lower for keyword in [topic]):
|
| 104 |
+
relevant_topics.append((topic, info))
|
| 105 |
+
|
| 106 |
+
# Generate response
|
| 107 |
+
if relevant_topics:
|
| 108 |
+
response = f"## Finance Topic: {user_input}\n\n"
|
| 109 |
+
|
| 110 |
+
for topic, info in relevant_topics:
|
| 111 |
+
response += f"### {topic.title()}\n"
|
| 112 |
+
response += f"**Definition:** {info['definition']}\n\n"
|
| 113 |
+
response += "**Key Points:**\n"
|
| 114 |
+
for point in info['key_points']:
|
| 115 |
+
response += f"• {point}\n"
|
| 116 |
+
response += "\n"
|
| 117 |
+
else:
|
| 118 |
+
# General finance advice
|
| 119 |
+
response = f"## Finance Topic: {user_input}\n\n"
|
| 120 |
+
response += self.generate_general_advice(user_input)
|
| 121 |
+
|
| 122 |
+
# Add disclaimer
|
| 123 |
+
response += "\n---\n"
|
| 124 |
+
response += "*Disclaimer: This information is for educational purposes only and should not be considered as financial advice. Please consult with a qualified financial advisor for personalized guidance.*"
|
| 125 |
+
|
| 126 |
+
return response
|
| 127 |
+
|
| 128 |
+
def generate_general_advice(self, topic):
|
| 129 |
+
"""Generate general financial advice for unknown topics"""
|
| 130 |
+
general_tips = [
|
| 131 |
+
"Consider your financial goals and risk tolerance",
|
| 132 |
+
"Diversification is key to managing investment risk",
|
| 133 |
+
"Start with fundamental analysis before making decisions",
|
| 134 |
+
"Keep informed about market trends and economic indicators",
|
| 135 |
+
"Consider consulting with financial professionals",
|
| 136 |
+
"Maintain an emergency fund for unexpected expenses",
|
| 137 |
+
"Regular review and adjustment of financial strategies is important"
|
| 138 |
+
]
|
| 139 |
+
|
| 140 |
+
response = f"Here's some general guidance regarding '{topic}':\n\n"
|
| 141 |
+
response += "**General Financial Principles:**\n"
|
| 142 |
+
for tip in general_tips[:5]: # Show first 5 tips
|
| 143 |
+
response += f"• {tip}\n"
|
| 144 |
+
|
| 145 |
+
response += f"\n**Specific to '{topic}':**\n"
|
| 146 |
+
response += f"• Research thoroughly before making any financial decisions related to {topic}\n"
|
| 147 |
+
response += f"• Understand the risks and potential returns associated with {topic}\n"
|
| 148 |
+
response += f"• Consider how {topic} fits into your overall financial portfolio\n"
|
| 149 |
+
|
| 150 |
+
return response
|
| 151 |
+
|
| 152 |
+
# Initialize the finance agent
|
| 153 |
+
finance_agent = FinanceAgent()
|
| 154 |
+
|
| 155 |
+
def process_finance_query(user_input, history):
|
| 156 |
+
"""Process user input and return finance advice"""
|
| 157 |
+
if not user_input.strip():
|
| 158 |
+
return "Please enter a finance topic or question.", history
|
| 159 |
+
|
| 160 |
+
try:
|
| 161 |
+
# Generate response
|
| 162 |
+
response = finance_agent.generate_finance_response(user_input)
|
| 163 |
+
|
| 164 |
+
# Update history
|
| 165 |
+
history.append([user_input, response])
|
| 166 |
+
|
| 167 |
+
return "", history
|
| 168 |
+
|
| 169 |
+
except Exception as e:
|
| 170 |
+
error_response = f"I apologize, but I encountered an error processing your request: {str(e)}\n\nPlease try rephrasing your question."
|
| 171 |
+
history.append([user_input, error_response])
|
| 172 |
+
return "", history
|
| 173 |
+
|
| 174 |
+
def clear_conversation():
|
| 175 |
+
"""Clear the conversation history"""
|
| 176 |
+
return [], ""
|
| 177 |
+
|
| 178 |
+
# Create Gradio interface
|
| 179 |
+
with gr.Blocks(
|
| 180 |
+
theme=gr.themes.Soft(),
|
| 181 |
+
title="Finance Agent",
|
| 182 |
+
css="""
|
| 183 |
+
.container {
|
| 184 |
+
max-width: 800px;
|
| 185 |
+
margin: 0 auto;
|
| 186 |
+
}
|
| 187 |
+
.header {
|
| 188 |
+
text-align: center;
|
| 189 |
+
padding: 20px;
|
| 190 |
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 191 |
+
color: white;
|
| 192 |
+
border-radius: 10px;
|
| 193 |
+
margin-bottom: 20px;
|
| 194 |
+
}
|
| 195 |
+
"""
|
| 196 |
+
) as demo:
|
| 197 |
+
|
| 198 |
+
gr.HTML("""
|
| 199 |
+
<div class="header">
|
| 200 |
+
<h1>🏦 Finance Agent</h1>
|
| 201 |
+
<p>Your AI-powered financial advisor for quick insights and guidance</p>
|
| 202 |
+
</div>
|
| 203 |
+
""")
|
| 204 |
+
|
| 205 |
+
with gr.Row():
|
| 206 |
+
with gr.Column(scale=1):
|
| 207 |
+
gr.HTML("""
|
| 208 |
+
<div style="background: #f8f9fa; padding: 15px; border-radius: 10px; margin-bottom: 15px;">
|
| 209 |
+
<h3>💡 How to Use:</h3>
|
| 210 |
+
<ul>
|
| 211 |
+
<li>Enter any finance topic (stocks, bonds, investing, etc.)</li>
|
| 212 |
+
<li>Ask questions about budgeting, retirement planning</li>
|
| 213 |
+
<li>Get quick insights on cryptocurrency, trading</li>
|
| 214 |
+
<li>Learn about financial planning strategies</li>
|
| 215 |
+
</ul>
|
| 216 |
+
</div>
|
| 217 |
+
""")
|
| 218 |
+
|
| 219 |
+
gr.HTML("""
|
| 220 |
+
<div style="background: #e8f5e8; padding: 15px; border-radius: 10px;">
|
| 221 |
+
<h3>📈 Popular Topics:</h3>
|
| 222 |
+
<p><strong>Investing:</strong> Stocks, Bonds, ETFs</p>
|
| 223 |
+
<p><strong>Planning:</strong> Retirement, Budgeting</p>
|
| 224 |
+
<p><strong>Trading:</strong> Cryptocurrency, Options</p>
|
| 225 |
+
<p><strong>Banking:</strong> Savings, Loans, Credit</p>
|
| 226 |
+
</div>
|
| 227 |
+
""")
|
| 228 |
+
|
| 229 |
+
with gr.Column(scale=2):
|
| 230 |
+
chatbot = gr.Chatbot(
|
| 231 |
+
height=500,
|
| 232 |
+
show_label=False,
|
| 233 |
+
container=True,
|
| 234 |
+
bubble_full_width=False
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
with gr.Row():
|
| 238 |
+
user_input = gr.Textbox(
|
| 239 |
+
placeholder="Enter your finance topic or question (e.g., 'stocks', 'retirement planning', 'cryptocurrency')",
|
| 240 |
+
show_label=False,
|
| 241 |
+
container=False,
|
| 242 |
+
scale=4
|
| 243 |
+
)
|
| 244 |
+
submit_btn = gr.Button("Ask Agent", variant="primary", scale=1)
|
| 245 |
+
|
| 246 |
+
with gr.Row():
|
| 247 |
+
clear_btn = gr.Button("Clear Chat", variant="secondary")
|
| 248 |
+
gr.HTML("<div style='flex: 1;'></div>") # Spacer
|
| 249 |
+
|
| 250 |
+
# Example questions
|
| 251 |
+
gr.Examples(
|
| 252 |
+
examples=[
|
| 253 |
+
["What are stocks and how do they work?"],
|
| 254 |
+
["How should I start investing as a beginner?"],
|
| 255 |
+
["Explain cryptocurrency basics"],
|
| 256 |
+
["What's the best budgeting strategy?"],
|
| 257 |
+
["How to plan for retirement?"],
|
| 258 |
+
["What are the differences between stocks and bonds?"]
|
| 259 |
+
],
|
| 260 |
+
inputs=user_input,
|
| 261 |
+
label="Example Questions"
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
# Event handlers
|
| 265 |
+
submit_btn.click(
|
| 266 |
+
process_finance_query,
|
| 267 |
+
inputs=[user_input, chatbot],
|
| 268 |
+
outputs=[user_input, chatbot]
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
user_input.submit(
|
| 272 |
+
process_finance_query,
|
| 273 |
+
inputs=[user_input, chatbot],
|
| 274 |
+
outputs=[user_input, chatbot]
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
clear_btn.click(
|
| 278 |
+
clear_conversation,
|
| 279 |
+
outputs=[chatbot, user_input]
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
gr.HTML("""
|
| 283 |
+
<div style="text-align: center; margin-top: 20px; padding: 15px; background: #f1f3f4; border-radius: 10px;">
|
| 284 |
+
<p><strong>⚠️ Important Disclaimer:</strong> This AI agent provides educational information only.
|
| 285 |
+
Always consult qualified financial advisors for personalized advice.</p>
|
| 286 |
+
<p>Built with ❤️ using Gradio and Hugging Face</p>
|
| 287 |
+
</div>
|
| 288 |
+
""")
|
| 289 |
+
|
| 290 |
+
# Launch configuration for Hugging Face Spaces
|
| 291 |
+
if __name__ == "__main__":
|
| 292 |
+
demo.launch(
|
| 293 |
+
server_name="0.0.0.0",
|
| 294 |
+
server_port=7860,
|
| 295 |
+
share=False
|
| 296 |
+
)
|