Update app.py
Browse files
app.py
CHANGED
@@ -1,64 +1,314 @@
|
|
1 |
import gradio as gr
|
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 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
top_p,
|
17 |
-
):
|
18 |
-
messages = [{"role": "system", "content": system_message}]
|
19 |
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
|
26 |
-
|
|
|
|
|
|
|
|
|
27 |
|
28 |
-
|
|
|
|
|
|
|
|
|
29 |
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
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 |
if __name__ == "__main__":
|
64 |
-
|
|
|
1 |
import gradio as gr
|
2 |
+
import torch
|
3 |
+
import os
|
4 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
5 |
+
from sentence_transformers import SentenceTransformer
|
6 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
7 |
+
import yfinance as yf
|
8 |
+
from datetime import datetime
|
9 |
+
from huggingface_hub import login
|
10 |
|
11 |
+
# Get Hugging Face token from environment variables
|
12 |
+
hf_token = os.environ.get("HF_TOKEN")
|
13 |
+
if hf_token:
|
14 |
+
# Login to Hugging Face
|
15 |
+
login(token=hf_token)
|
16 |
+
print("Successfully logged in to Hugging Face")
|
17 |
+
else:
|
18 |
+
print("WARNING: HF_TOKEN not found in environment variables. You may face access issues for gated models.")
|
19 |
+
|
20 |
+
# Load the Chatbot Model and Tokenizer
|
21 |
+
model_name = "Akshit-77/llama-3.2-3b-chatbot"
|
22 |
+
|
23 |
+
# Try to use local cache if already downloaded, otherwise load with auth token
|
24 |
+
try:
|
25 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name, token=hf_token)
|
26 |
+
except Exception as e:
|
27 |
+
print(f"Error loading tokenizer: {e}")
|
28 |
+
raise
|
29 |
+
|
30 |
+
# Configure quantization for memory efficiency
|
31 |
+
bnb_config = BitsAndBytesConfig(
|
32 |
+
load_in_4bit=True,
|
33 |
+
bnb_4bit_use_double_quant=True,
|
34 |
+
bnb_4bit_quant_type="fp4",
|
35 |
+
bnb_4bit_compute_dtype="float16"
|
36 |
+
)
|
37 |
+
|
38 |
+
# Load model with quantization and auth token
|
39 |
+
try:
|
40 |
+
model = AutoModelForCausalLM.from_pretrained(
|
41 |
+
model_name,
|
42 |
+
quantization_config=bnb_config,
|
43 |
+
device_map="auto",
|
44 |
+
token=hf_token
|
45 |
+
)
|
46 |
+
print("Model loaded successfully")
|
47 |
+
except Exception as e:
|
48 |
+
print(f"Error loading model: {e}")
|
49 |
+
raise
|
50 |
+
|
51 |
+
# CSS for Chatbot UI
|
52 |
+
css = """
|
53 |
+
#chatbot {
|
54 |
+
font-family: Arial, sans-serif;
|
55 |
+
background-color: #e5ddd5;
|
56 |
+
}
|
57 |
+
.message {
|
58 |
+
padding: 10px 15px;
|
59 |
+
border-radius: 7.5px;
|
60 |
+
margin: 5px 0;
|
61 |
+
max-width: 75%;
|
62 |
+
position: relative;
|
63 |
+
}
|
64 |
+
.user-message {
|
65 |
+
background: #dcf8c6;
|
66 |
+
margin-left: auto;
|
67 |
+
margin-right: 10px;
|
68 |
+
}
|
69 |
+
.bot-message {
|
70 |
+
background: white;
|
71 |
+
margin-left: 10px;
|
72 |
+
}
|
73 |
+
.timestamp {
|
74 |
+
font-size: 0.7em;
|
75 |
+
color: #667781;
|
76 |
+
float: right;
|
77 |
+
margin-left: 10px;
|
78 |
+
margin-top: 3px;
|
79 |
+
}
|
80 |
"""
|
|
|
|
|
|
|
81 |
|
82 |
+
class StockDataRetriever:
|
83 |
+
def __init__(self):
|
84 |
+
self.stock_mapping = {
|
85 |
+
# Existing mappings
|
86 |
+
'RELIANCE': 'RELIANCE.NS',
|
87 |
+
'TCS': 'TCS.NS',
|
88 |
+
'HDFCBANK': 'HDFCBANK.NS',
|
89 |
+
'INFY': 'INFY.NS',
|
90 |
+
'ICICIBANK': 'ICICIBANK.NS',
|
91 |
|
92 |
+
# Expanded Mappings
|
93 |
+
'RELIANCE-INDUSTRIES': 'RELIANCE.NS',
|
94 |
+
'HDFC': 'HDFC.NS',
|
95 |
+
'ONGC': 'ONGC.NS',
|
96 |
+
'INDIAN-OIL-CORPORATION': 'IOC.NS',
|
97 |
+
'ADANI-GROUP': 'ADANIENT.NS', # Using Adani Enterprises as a representative
|
|
|
|
|
|
|
98 |
|
99 |
+
'HERO-MOTOCORP': 'HEROMOTOCO.NS',
|
100 |
+
'ASIAN-PAINTS': 'ASIANPAINT.NS',
|
101 |
+
'EICHER-MOTORS': 'EICHERMOT.NS',
|
102 |
+
'ITC': 'ITC.NS',
|
103 |
+
'TATA-STEEL': 'TATASTEEL.NS',
|
104 |
|
105 |
+
'SHRIRAM-TRANSPORT-FINANCE': 'SHRIRAMFIN.NS',
|
106 |
+
'DR-REDDYS-LABORATORIES': 'DRREDDY.NS',
|
107 |
+
'INFOSYS': 'INFY.NS',
|
108 |
+
'SUN-PHARMA': 'SUNPHARMA.NS',
|
109 |
+
'TATA-CONSULTANCY-SERVICES': 'TCS.NS',
|
110 |
|
111 |
+
'MARUTI-SUZUKI': 'MARUTI.NS',
|
112 |
+
'HCL-TECHNOLOGIES': 'HCLTECH.NS',
|
113 |
+
'COAL-INDIA': 'COALINDIA.NS',
|
114 |
+
'LTI-MINDTREE': 'MINDTREE.NS',
|
115 |
+
'HDFC-LIFE': 'HDFCLIFE.NS',
|
116 |
|
117 |
+
'BAJAJ-AUTO': 'BAJAJ-AUTO.NS',
|
118 |
+
'BRITANNIA-INDUSTRIES': 'BRITANNIA.NS',
|
119 |
+
'HINDALCO-INDUSTRIES': 'HINDALCO.NS',
|
120 |
+
'LARSEN-AND-TOUBRO': 'LT.NS',
|
121 |
+
'TATA-CONSUMER-PRODUCTS': 'TATACONSUM.NS',
|
|
|
|
|
|
|
122 |
|
123 |
+
'WIPRO': 'WIPRO.NS',
|
124 |
+
'TITAN': 'TITAN.NS',
|
125 |
+
'BAJAJ-FINANCE': 'BAJFINANCE.NS',
|
126 |
+
'JSW-STEEL': 'JSWSTEEL.NS',
|
127 |
+
'ICICI-BANK': 'ICICIBANK.NS',
|
128 |
|
129 |
+
'INDUSIND-BANK': 'INDUSINDBK.NS',
|
130 |
+
'BHARTI-AIRTEL': 'BHARTIARTL.NS',
|
131 |
+
'DIVIS-LABORATORIES': 'DIVISLAB.NS',
|
132 |
+
'SBI-LIFE-INSURANCE': 'SBILIFE.NS',
|
133 |
+
'BAJAJ-FINSERV': 'BAJAJFINSV.NS',
|
134 |
|
135 |
+
'CIPLA': 'CIPLA.NS',
|
136 |
+
'GRASIM-INDUSTRIES': 'GRASIM.NS',
|
137 |
+
'HINDUSTAN-UNILEVER': 'HINDUNILVR.NS',
|
138 |
+
'MAHINDRA-AND-MAHINDRA': 'M&M.NS',
|
139 |
+
'TATA-MOTORS': 'TATAMOTORS.NS',
|
140 |
+
|
141 |
+
'APOLLO-HOSPITALS-ENTERPRISES': 'APOLLOHOSP.NS',
|
142 |
+
'SBI': 'SBIN.NS',
|
143 |
+
'KOTAK-MAHINDRA-BANK': 'KOTAKBANK.NS',
|
144 |
+
'POWER-GRID-CORPORATION-OF-INDIA': 'POWERGRID.NS',
|
145 |
+
'AXIS-BANK': 'AXISBANK.NS',
|
146 |
+
|
147 |
+
'NTPC': 'NTPC.NS',
|
148 |
+
'TECH-MAHINDRA': 'TECHM.NS',
|
149 |
+
'ADANI-PORTS': 'ADANIPORTS.NS',
|
150 |
+
'ULTRATECH-CEMENT': 'ULTRACEMCO.NS',
|
151 |
+
'NESTLE': 'NESTLE.NS',
|
152 |
+
'BHARAT-PETROLEUM': 'BPCL.NS'
|
153 |
+
}
|
154 |
+
|
155 |
+
def get_stock_data(self, symbol: str):
|
156 |
+
"""Fetch stock data from Yahoo Finance"""
|
157 |
+
try:
|
158 |
+
# Convert symbol to Yahoo Finance format
|
159 |
+
yf_symbol = self.stock_mapping.get(symbol.upper(), f"{symbol.upper()}.NS")
|
160 |
+
stock = yf.Ticker(yf_symbol)
|
161 |
+
info = stock.info
|
162 |
+
|
163 |
+
# Check if the response is valid
|
164 |
+
if not info or 'currentPrice' not in info:
|
165 |
+
return {"error": f"Stock symbol '{symbol}' not found or invalid. Please verify the symbol."}
|
166 |
+
|
167 |
+
return {
|
168 |
+
"current_price": info.get("currentPrice", "N/A"),
|
169 |
+
"previous_close": info.get("previousClose", "N/A"),
|
170 |
+
"day_high": info.get("dayHigh", "N/A"),
|
171 |
+
"day_low": info.get("dayLow", "N/A"),
|
172 |
+
"last_updated": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
173 |
+
}
|
174 |
+
except Exception as e:
|
175 |
+
return {"error": f"Could not fetch stock data: {str(e)}"}
|
176 |
+
|
177 |
+
|
178 |
+
class RAGPipeline:
|
179 |
+
def __init__(self, model_path):
|
180 |
+
self.tokenizer = tokenizer # Use already loaded tokenizer
|
181 |
+
self.model = model # Use already loaded model
|
182 |
+
self.stock_retriever = StockDataRetriever()
|
183 |
+
self.encoder = SentenceTransformer('all-MiniLM-L6-v2')
|
184 |
+
|
185 |
+
# Expanded and more flexible knowledge base
|
186 |
+
self.knowledge_base = [
|
187 |
+
"stock price of",
|
188 |
+
"current price",
|
189 |
+
"stock performance",
|
190 |
+
"today's stock price",
|
191 |
+
"stock data for",
|
192 |
+
"price of stock"
|
193 |
+
]
|
194 |
+
self.knowledge_embeddings = self.encoder.encode(self.knowledge_base)
|
195 |
+
|
196 |
+
# Predefined stock symbols for easier matching
|
197 |
+
self.stock_symbols = list(self.stock_retriever.stock_mapping.keys())
|
198 |
+
|
199 |
+
def _extract_stock_symbol(self, query):
|
200 |
+
# Try to find a stock symbol in the query
|
201 |
+
query_upper = query.upper()
|
202 |
+
for symbol in self.stock_symbols:
|
203 |
+
if symbol in query_upper:
|
204 |
+
return symbol
|
205 |
+
|
206 |
+
# Fallback: try to extract the last word if it looks like a symbol
|
207 |
+
words = query.split()
|
208 |
+
if words and len(words[-1]) > 1:
|
209 |
+
return words[-1].upper()
|
210 |
+
|
211 |
+
return None
|
212 |
+
|
213 |
+
def _is_price_query(self, query):
|
214 |
+
query_embedding = self.encoder.encode([query.lower()])
|
215 |
+
similarities = cosine_similarity(query_embedding, self.knowledge_embeddings)[0]
|
216 |
+
|
217 |
+
# Lower the threshold and check if any similarity is significant
|
218 |
+
return max(similarities) > 0.5
|
219 |
+
|
220 |
+
def _format_stock_data(self, stock_data):
|
221 |
+
"""Format stock data into a readable string"""
|
222 |
+
if 'error' in stock_data:
|
223 |
+
return stock_data['error']
|
224 |
+
|
225 |
+
return (
|
226 |
+
f"Stock Data:\n"
|
227 |
+
f"Current Price: ₹{stock_data['current_price']}\n"
|
228 |
+
f"Previous Close: ₹{stock_data['previous_close']}\n"
|
229 |
+
f"Day's High: ₹{stock_data['day_high']}\n"
|
230 |
+
f"Day's Low: ₹{stock_data['day_low']}\n"
|
231 |
+
f"Last Updated: {stock_data['last_updated']}"
|
232 |
+
)
|
233 |
+
|
234 |
+
def generate_response(self, query):
|
235 |
+
# Check if the query is related to stock prices
|
236 |
+
stock_context = ""
|
237 |
+
if self._is_price_query(query):
|
238 |
+
# Extract stock symbol
|
239 |
+
symbol = self._extract_stock_symbol(query)
|
240 |
+
|
241 |
+
if symbol:
|
242 |
+
# Retrieve stock data
|
243 |
+
stock_data = self.stock_retriever.get_stock_data(symbol)
|
244 |
+
stock_context = self._format_stock_data(stock_data)
|
245 |
+
else:
|
246 |
+
stock_context = "No specific stock symbol could be identified."
|
247 |
+
|
248 |
+
# Prepare input for the model with stock context
|
249 |
+
full_prompt = (
|
250 |
+
f"Context: {stock_context}\n\n"
|
251 |
+
f"Question: {query}\n"
|
252 |
+
"Answer:"
|
253 |
+
)
|
254 |
+
|
255 |
+
# Generate response using the fine-tuned model
|
256 |
+
inputs = self.tokenizer(full_prompt, return_tensors="pt").to(self.model.device)
|
257 |
+
with torch.no_grad():
|
258 |
+
outputs = self.model.generate(inputs["input_ids"], max_length=500)
|
259 |
+
|
260 |
+
return self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
261 |
+
|
262 |
+
|
263 |
+
# Initialize the pipeline once
|
264 |
+
try:
|
265 |
+
pipeline = RAGPipeline(model_name)
|
266 |
+
print("RAG Pipeline initialized successfully")
|
267 |
+
except Exception as e:
|
268 |
+
print(f"Error initializing RAG Pipeline: {e}")
|
269 |
+
raise
|
270 |
+
|
271 |
+
# Chatbot Interface function
|
272 |
+
def chat(message, history):
|
273 |
+
history = history or []
|
274 |
+
try:
|
275 |
+
response = pipeline.generate_response(message)
|
276 |
+
history.append((message, response))
|
277 |
+
except Exception as e:
|
278 |
+
history.append((message, f"Error generating response: {str(e)}"))
|
279 |
+
return history, ""
|
280 |
+
|
281 |
+
# Define the Gradio interface
|
282 |
+
def create_interface():
|
283 |
+
with gr.Blocks(css=css) as iface:
|
284 |
+
gr.HTML("<h1>Indian Stock Market Assistant</h1>")
|
285 |
+
gr.HTML("<p>Ask me about Indian stock prices or any general questions.</p>")
|
286 |
+
|
287 |
+
chatbot = gr.Chatbot(height=600, elem_id="chatbot")
|
288 |
+
txt = gr.Textbox(
|
289 |
+
placeholder="Type your question here (e.g., 'What is the current price of RELIANCE?')",
|
290 |
+
show_label=False
|
291 |
+
)
|
292 |
+
|
293 |
+
txt.submit(chat, [txt, chatbot], [chatbot, txt])
|
294 |
+
|
295 |
+
gr.HTML("""
|
296 |
+
<div style="text-align: center; margin-top: 20px; padding: 10px; background-color: #f0f0f0; border-radius: 5px;">
|
297 |
+
<p>This chatbot provides real-time Indian stock market data and can answer general questions.</p>
|
298 |
+
<p>Examples: "What's the current price of TCS?", "How is HDFC performing today?", "Tell me about RELIANCE stock"</p>
|
299 |
+
</div>
|
300 |
+
""")
|
301 |
+
|
302 |
+
return iface
|
303 |
|
304 |
+
# Create and launch the interface
|
305 |
+
try:
|
306 |
+
iface = create_interface()
|
307 |
+
print("Interface created successfully")
|
308 |
+
except Exception as e:
|
309 |
+
print(f"Error creating interface: {e}")
|
310 |
+
raise
|
311 |
|
312 |
+
# For Hugging Face Spaces deployment
|
313 |
if __name__ == "__main__":
|
314 |
+
iface.launch()
|