Spaces:
Sleeping
Sleeping
Upload 3 files
Browse files- .gitattributes +1 -0
- requirements.txt +7 -2
- smartbot.py +131 -0
- train_data.csv +3 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
train_data.csv filter=lfs diff=lfs merge=lfs -text
|
requirements.txt
CHANGED
|
@@ -1,3 +1,8 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
pandas
|
| 3 |
-
|
|
|
|
| 1 |
+
streamlit
|
| 2 |
+
faiss-cpu
|
| 3 |
+
numpy
|
| 4 |
+
sentence-transformers
|
| 5 |
+
transformers
|
| 6 |
+
torch
|
| 7 |
pandas
|
| 8 |
+
huggingface_hub
|
smartbot.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import faiss
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import torch
|
| 6 |
+
import os
|
| 7 |
+
from sentence_transformers import SentenceTransformer
|
| 8 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 9 |
+
from huggingface_hub import login
|
| 10 |
+
|
| 11 |
+
# --- HuggingFace login ---
|
| 12 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 13 |
+
if HF_TOKEN:
|
| 14 |
+
login(token=HF_TOKEN)
|
| 15 |
+
|
| 16 |
+
# --- Load data ---
|
| 17 |
+
train = pd.read_csv('train_data.csv') # Assumes it's in the same directory
|
| 18 |
+
questions = train['question'].tolist()
|
| 19 |
+
answers = train['answer'].tolist()
|
| 20 |
+
|
| 21 |
+
qa_pairs = [f"Q: {q} A: {a}" for q, a in zip(questions, answers)]
|
| 22 |
+
|
| 23 |
+
# --- Embedding model ---
|
| 24 |
+
embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
|
| 25 |
+
answer_embeddings = embedding_model.encode(answers)
|
| 26 |
+
|
| 27 |
+
# --- FAISS index ---
|
| 28 |
+
index = faiss.IndexFlatL2(answer_embeddings.shape[1])
|
| 29 |
+
index.add(np.array(answer_embeddings))
|
| 30 |
+
|
| 31 |
+
# --- LLaMA model setup ---
|
| 32 |
+
model_name = "meta-llama/Llama-3-8B-Instruct" # Update to a valid space-available model if needed
|
| 33 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
|
| 34 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 35 |
+
model_name,
|
| 36 |
+
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
| 37 |
+
device_map="auto"
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
# --- Helper Functions ---
|
| 41 |
+
def sanitize_answer(question, answer):
|
| 42 |
+
return any(word.lower() in answer.lower() for word in question.lower().split())
|
| 43 |
+
|
| 44 |
+
recent_questions = {}
|
| 45 |
+
|
| 46 |
+
def is_finance_question(user_query):
|
| 47 |
+
check_prompt = (
|
| 48 |
+
f"You are a financial expert. Determine whether the following question is clearly about finance:\n\n"
|
| 49 |
+
f"Question: {user_query}\n\n"
|
| 50 |
+
f"Respond only with 'Yes' or 'No'."
|
| 51 |
+
)
|
| 52 |
+
input_ids = tokenizer(check_prompt, return_tensors="pt").to(model.device)
|
| 53 |
+
output_ids = model.generate(
|
| 54 |
+
**input_ids,
|
| 55 |
+
max_new_tokens=10,
|
| 56 |
+
temperature=0.0,
|
| 57 |
+
top_p=0.9,
|
| 58 |
+
pad_token_id=tokenizer.eos_token_id
|
| 59 |
+
)
|
| 60 |
+
response = tokenizer.decode(output_ids[0], skip_special_tokens=True).strip()
|
| 61 |
+
return response.lower().startswith("yes")
|
| 62 |
+
|
| 63 |
+
def ask_finance_bot(user_query, top_k=3):
|
| 64 |
+
normalized_query = user_query.lower().strip()
|
| 65 |
+
count = recent_questions.get(normalized_query, 0) + 1
|
| 66 |
+
recent_questions[normalized_query] = count
|
| 67 |
+
|
| 68 |
+
# Embed user query
|
| 69 |
+
query_embedding = embedding_model.encode([user_query])
|
| 70 |
+
D, I = index.search(np.array(query_embedding), top_k)
|
| 71 |
+
retrieved_answers = [answers[i] for i in I[0]]
|
| 72 |
+
context = "\n".join([f"- {text}" for text in retrieved_answers])
|
| 73 |
+
|
| 74 |
+
temperature = min(0.7 + 0.1 * (count - 1), 1.0)
|
| 75 |
+
|
| 76 |
+
instruction = (
|
| 77 |
+
"You are a highly knowledgeable AI assistant specializing strictly in finance.\n"
|
| 78 |
+
"Strictly answer only financially related topics.\n"
|
| 79 |
+
"Never answer questions that are not financially related.\n"
|
| 80 |
+
"Do not answer anything outside finance.\n"
|
| 81 |
+
"Always provide accurate, objective, and concise answers to financial questions.\n"
|
| 82 |
+
"Avoid unnecessary elaboration and focus directly on answering the user's query.\n"
|
| 83 |
+
"Use the background context only if it is accurate, clear, and relevant. If the context is unclear, incomplete, low-quality, or irrelevant, ignore it and generate your own correct, concise financial answer.\n"
|
| 84 |
+
"Do not copy or repeat the context verbatim — instead, synthesize your own response based on it.\n"
|
| 85 |
+
"Do not speculate or use personal phrases like 'I think' or 'In my opinion'.\n"
|
| 86 |
+
"If a valid financial question is asked, always answer — never refuse or say 'I can't help with that.'\n"
|
| 87 |
+
"If a question is unrelated to finance, respond: 'I'm specialized in finance and can't help with that. How can I assist you with a finance-related question today?'\n"
|
| 88 |
+
"If a greeting like 'Hi', 'Hello', or 'Hey' is used, respond with: 'Hello! How can I help you with your finance-related question today?'\n"
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
for _ in range(6):
|
| 92 |
+
prompt = f"""{instruction}
|
| 93 |
+
|
| 94 |
+
Background context:
|
| 95 |
+
{context}
|
| 96 |
+
|
| 97 |
+
User question: {user_query}
|
| 98 |
+
|
| 99 |
+
Answer:"""
|
| 100 |
+
|
| 101 |
+
input_ids = tokenizer(prompt, return_tensors="pt").to(model.device)
|
| 102 |
+
output_ids = model.generate(
|
| 103 |
+
**input_ids,
|
| 104 |
+
max_new_tokens=256,
|
| 105 |
+
temperature=temperature,
|
| 106 |
+
top_p=0.9,
|
| 107 |
+
pad_token_id=tokenizer.eos_token_id
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
response = tokenizer.decode(output_ids[0], skip_special_tokens=True)
|
| 111 |
+
answer_text = response.split("Answer:")[-1].strip()
|
| 112 |
+
|
| 113 |
+
if sanitize_answer(user_query, answer_text):
|
| 114 |
+
return answer_text
|
| 115 |
+
|
| 116 |
+
return "I'm not confident in the response. Please consult a certified financial expert."
|
| 117 |
+
|
| 118 |
+
# --- Streamlit App UI ---
|
| 119 |
+
st.set_page_config(page_title="DiMowkayBot - Finance Assistant", layout="centered")
|
| 120 |
+
st.title("💸 DiMowkayBot - Your Finance Q&A Assistant")
|
| 121 |
+
|
| 122 |
+
user_query = st.text_input("Enter your finance-related question:")
|
| 123 |
+
|
| 124 |
+
if user_query:
|
| 125 |
+
if not is_finance_question(user_query):
|
| 126 |
+
st.warning("I'm specialized in finance and can't help with that. How can I assist you with a finance-related question today?")
|
| 127 |
+
else:
|
| 128 |
+
with st.spinner("Thinking..."):
|
| 129 |
+
answer = ask_finance_bot(user_query)
|
| 130 |
+
st.success("Response:")
|
| 131 |
+
st.write(answer)
|
train_data.csv
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8b625b903a78f1367441c595d1285522b74cb005d43c0f44d08ee7be2e6119e0
|
| 3 |
+
size 13054424
|