Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,64 +1,110 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
"""
|
5 |
-
For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
|
6 |
-
"""
|
7 |
-
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
8 |
-
|
9 |
-
|
10 |
-
def respond(
|
11 |
-
message,
|
12 |
-
history: list[tuple[str, str]],
|
13 |
-
system_message,
|
14 |
-
max_tokens,
|
15 |
-
temperature,
|
16 |
-
top_p,
|
17 |
-
):
|
18 |
-
messages = [{"role": "system", "content": system_message}]
|
19 |
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
messages.append({"role": "user", "content": message})
|
27 |
-
|
28 |
-
response = ""
|
29 |
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
temperature=temperature,
|
35 |
-
top_p=top_p,
|
36 |
-
):
|
37 |
-
token = message.choices[0].delta.content
|
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 |
-
|
|
|
1 |
+
# Install required dependencies
|
2 |
+
!pip install gradio transformers torch
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
|
4 |
+
import numpy as np
|
5 |
+
import pandas as pd
|
6 |
+
import torch
|
7 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
8 |
+
import gradio as gr
|
|
|
|
|
|
|
|
|
9 |
|
10 |
+
# Load a free model from Hugging Face
|
11 |
+
model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0" # Small model that works well for simple tasks
|
12 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
13 |
+
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16)
|
|
|
|
|
|
|
|
|
14 |
|
15 |
+
# Financial knowledge base - simple templates and responses
|
16 |
+
financial_templates = {
|
17 |
+
"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",
|
18 |
+
"emergency_fund": "An emergency fund should ideally cover 3-6 months of expenses. Start with a goal of $1,000, then build from there.",
|
19 |
+
"debt": "Focus on high-interest debt first (like credit cards). Consider the debt avalanche (highest interest first) or debt snowball (smallest balance first) methods.",
|
20 |
+
"investing": "For beginners, consider index funds or ETFs for diversification. Time in the market beats timing the market.",
|
21 |
+
"retirement": "Take advantage of employer matches in retirement accounts - it's free money. Start early to benefit from compound interest."
|
22 |
+
}
|
23 |
|
24 |
+
# Define guided chat flow
|
25 |
+
def guided_response(user_message, chat_history):
|
26 |
+
# Check if we should use a template response
|
27 |
+
for key, template in financial_templates.items():
|
28 |
+
if key in user_message.lower():
|
29 |
+
return template
|
30 |
+
|
31 |
+
# For more general queries, use the AI model
|
32 |
+
prompt = f"""<human>I need financial advice: {user_message}</human>
|
33 |
+
<assistant>"""
|
34 |
+
|
35 |
+
inputs = tokenizer(prompt, return_tensors="pt")
|
36 |
+
outputs = model.generate(
|
37 |
+
inputs["input_ids"],
|
38 |
+
max_length=512,
|
39 |
+
temperature=0.7,
|
40 |
+
do_sample=True,
|
41 |
+
pad_token_id=tokenizer.eos_token_id
|
42 |
+
)
|
43 |
+
|
44 |
+
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
45 |
+
# Extract just the assistant's response
|
46 |
+
if "<assistant>" in response:
|
47 |
+
response = response.split("<assistant>")[1].strip()
|
48 |
+
|
49 |
+
return response
|
50 |
|
51 |
+
# Create budget calculator function
|
52 |
+
def calculate_budget(monthly_income, housing, utilities, groceries, transportation):
|
53 |
+
total_needs = housing + utilities + groceries + transportation
|
54 |
+
needs_percent = (total_needs / monthly_income) * 100
|
55 |
+
|
56 |
+
available_for_wants = monthly_income * 0.3
|
57 |
+
available_for_savings = monthly_income * 0.2
|
58 |
+
|
59 |
+
return f"""Based on the 50/30/20 rule:
|
60 |
+
|
61 |
+
Current spending on needs: ${total_needs:.2f} ({needs_percent:.1f}% of income)
|
62 |
+
Recommended max for needs: ${monthly_income * 0.5:.2f} (50%)
|
63 |
+
|
64 |
+
Available for wants: ${available_for_wants:.2f} (30%)
|
65 |
+
Recommended for savings/debt: ${available_for_savings:.2f} (20%)
|
66 |
+
|
67 |
+
{'Your needs expenses are within recommended limits!' if needs_percent <= 50 else 'Your needs expenses exceed 50% of income. Consider areas to reduce spending.'}
|
68 |
+
"""
|
69 |
|
70 |
+
# Setup Gradio interface with tabs
|
71 |
+
with gr.Blocks() as app:
|
72 |
+
gr.Markdown("# Financial Advisor Bot")
|
73 |
+
|
74 |
+
with gr.Tab("Chat Advisor"):
|
75 |
+
chatbot = gr.Chatbot(height=400)
|
76 |
+
msg = gr.Textbox(label="Ask a question about personal finance")
|
77 |
+
clear = gr.Button("Clear")
|
78 |
+
|
79 |
+
def respond(message, chat_history):
|
80 |
+
bot_message = guided_response(message, chat_history)
|
81 |
+
chat_history.append((message, bot_message))
|
82 |
+
return "", chat_history
|
83 |
+
|
84 |
+
msg.submit(respond, [msg, chatbot], [msg, chatbot])
|
85 |
+
clear.click(lambda: None, None, chatbot, queue=False)
|
86 |
+
|
87 |
+
with gr.Tab("Budget Calculator"):
|
88 |
+
gr.Markdown("## 50/30/20 Budget Calculator")
|
89 |
+
with gr.Row():
|
90 |
+
income = gr.Number(label="Monthly Income (after tax)")
|
91 |
+
|
92 |
+
with gr.Row():
|
93 |
+
gr.Markdown("### Monthly Expenses (Needs)")
|
94 |
+
with gr.Row():
|
95 |
+
housing = gr.Number(label="Housing", value=0)
|
96 |
+
utilities = gr.Number(label="Utilities", value=0)
|
97 |
+
groceries = gr.Number(label="Groceries", value=0)
|
98 |
+
transport = gr.Number(label="Transportation", value=0)
|
99 |
+
|
100 |
+
calculate_btn = gr.Button("Calculate Budget")
|
101 |
+
output = gr.Textbox(label="Budget Analysis", lines=10)
|
102 |
+
|
103 |
+
calculate_btn.click(
|
104 |
+
calculate_budget,
|
105 |
+
inputs=[income, housing, utilities, groceries, transport],
|
106 |
+
outputs=output
|
107 |
+
)
|
108 |
|
109 |
+
# Launch the app in Colab
|
110 |
+
app.launch(share=True) # share=True creates a public link you can share with others
|