Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
-
<<<<<<< HEAD
|
| 2 |
import streamlit as st
|
| 3 |
import torch
|
| 4 |
from transformers import BertTokenizer, BertForSequenceClassification
|
|
@@ -186,193 +185,4 @@ st.markdown("""
|
|
| 186 |
.stChatMessageUser {background-color: #900C3F;}
|
| 187 |
.stChatMessageAssistant {background-color: #900C3F;}
|
| 188 |
</style>
|
| 189 |
-
=======
|
| 190 |
-
import streamlit as st
|
| 191 |
-
import torch
|
| 192 |
-
from transformers import BertTokenizer, BertForSequenceClassification
|
| 193 |
-
import json
|
| 194 |
-
import os
|
| 195 |
-
import time
|
| 196 |
-
import datetime
|
| 197 |
-
import random
|
| 198 |
-
from streamlit_extras.add_vertical_space import add_vertical_space
|
| 199 |
-
from streamlit_extras.let_it_rain import rain
|
| 200 |
-
from streamlit_modal import Modal
|
| 201 |
-
|
| 202 |
-
# Streamlit UI
|
| 203 |
-
st.set_page_config(page_title="ChatBot", layout="wide")
|
| 204 |
-
|
| 205 |
-
# Load BERT Model & Tokenizer
|
| 206 |
-
MODEL_PATH = "Trained Model/chatbot_model" # Path where your model & tokenizer are saved
|
| 207 |
-
|
| 208 |
-
# Set device
|
| 209 |
-
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 210 |
-
|
| 211 |
-
# Load model & tokenizer
|
| 212 |
-
tokenizer = BertTokenizer.from_pretrained(MODEL_PATH)
|
| 213 |
-
model = BertForSequenceClassification.from_pretrained(MODEL_PATH)
|
| 214 |
-
model.to(device)
|
| 215 |
-
model.eval()
|
| 216 |
-
|
| 217 |
-
# Load intents
|
| 218 |
-
with open("intents.json", "r") as file:
|
| 219 |
-
intents = json.load(file)
|
| 220 |
-
|
| 221 |
-
intent_mapping = {i: intent['tag'] for i, intent in enumerate(intents)}
|
| 222 |
-
|
| 223 |
-
# Chat history file
|
| 224 |
-
CHAT_HISTORY_FILE = "chat_history.json"
|
| 225 |
-
|
| 226 |
-
# Load Chat History (Ensuring Persistence)
|
| 227 |
-
def load_chat_history():
|
| 228 |
-
if os.path.exists(CHAT_HISTORY_FILE):
|
| 229 |
-
with open(CHAT_HISTORY_FILE, "r") as file:
|
| 230 |
-
return json.load(file)
|
| 231 |
-
return []
|
| 232 |
-
|
| 233 |
-
# Save Chat History
|
| 234 |
-
def save_chat_history():
|
| 235 |
-
with open(CHAT_HISTORY_FILE, "w") as file:
|
| 236 |
-
json.dump(st.session_state.chat_history, file)
|
| 237 |
-
|
| 238 |
-
# Initialize session state variables
|
| 239 |
-
if "chat_history" not in st.session_state:
|
| 240 |
-
st.session_state.chat_history = load_chat_history()
|
| 241 |
-
if "show_history" not in st.session_state:
|
| 242 |
-
st.session_state.show_history = False
|
| 243 |
-
if "show_about" not in st.session_state:
|
| 244 |
-
st.session_state.show_about = False
|
| 245 |
-
if "chat_input" not in st.session_state:
|
| 246 |
-
st.session_state.chat_input = ""
|
| 247 |
-
|
| 248 |
-
def predict_intent(text):
|
| 249 |
-
inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True).to(device)
|
| 250 |
-
with torch.no_grad():
|
| 251 |
-
outputs = model(**inputs)
|
| 252 |
-
|
| 253 |
-
predicted_index = torch.argmax(outputs.logits, dim=1).item()
|
| 254 |
-
return intent_mapping.get(predicted_index, "unknown")
|
| 255 |
-
|
| 256 |
-
def get_response(intent_label):
|
| 257 |
-
for intent in intents:
|
| 258 |
-
if intent_label == intent['tag']:
|
| 259 |
-
return random.choice(intent['responses'])
|
| 260 |
-
return "I'm not sure how to respond to that."
|
| 261 |
-
|
| 262 |
-
# Sidebar menu
|
| 263 |
-
with st.sidebar:
|
| 264 |
-
st.image("Images/Bot Image.jpeg", use_container_width=True)
|
| 265 |
-
st.title("💬 Chatbot Menu")
|
| 266 |
-
add_vertical_space(1)
|
| 267 |
-
|
| 268 |
-
if st.button("🆕 New Chat"):
|
| 269 |
-
st.session_state.chat_input = ""
|
| 270 |
-
save_chat_history()
|
| 271 |
-
|
| 272 |
-
if st.button("📜 Chat History"):
|
| 273 |
-
st.session_state.show_history = True
|
| 274 |
-
|
| 275 |
-
if st.button("ℹ️ About"):
|
| 276 |
-
st.session_state.show_about = True
|
| 277 |
-
st.caption("🚀 Built with ❤️ by AI Enthusiast")
|
| 278 |
-
|
| 279 |
-
# Modal Windows (Chat History & About)
|
| 280 |
-
history_modal = Modal("📜Chat History", key="history_modal")
|
| 281 |
-
about_modal = Modal("ℹ️About", key="about_modal")
|
| 282 |
-
|
| 283 |
-
# Display chat history without affecting the chat window
|
| 284 |
-
if st.session_state.show_history:
|
| 285 |
-
with history_modal.container():
|
| 286 |
-
if st.session_state.chat_history:
|
| 287 |
-
for chat in st.session_state.chat_history[-10:]: # Show last 10 messages
|
| 288 |
-
st.write(chat)
|
| 289 |
-
else:
|
| 290 |
-
st.info("No chat history available.")
|
| 291 |
-
|
| 292 |
-
# Clear History Button
|
| 293 |
-
if st.button("🗑 Clear History", key="clear_history"):
|
| 294 |
-
st.session_state.chat_history = [] # Clear session history
|
| 295 |
-
if os.path.exists(CHAT_HISTORY_FILE):
|
| 296 |
-
os.remove(CHAT_HISTORY_FILE) # Delete saved file
|
| 297 |
-
st.rerun() # Refresh UI to reflect changes
|
| 298 |
-
|
| 299 |
-
# Close Modal Button
|
| 300 |
-
if st.button("Close", key="close_history"):
|
| 301 |
-
st.session_state.show_history = False
|
| 302 |
-
st.rerun()
|
| 303 |
-
|
| 304 |
-
if st.session_state.show_about:
|
| 305 |
-
with about_modal.container():
|
| 306 |
-
st.info("""This chatbot is powered by a deep learning approach using Hugging Face Transformers and a BERT model for intent recognition.
|
| 307 |
-
It understands user queries by predicting intent and responding with predefined answers based on a trained dataset.
|
| 308 |
-
|
| 309 |
-
✅ Natural Language Processing (NLP)
|
| 310 |
-
|
| 311 |
-
🔹 Transformers (Hugging Face) 🤖 – BERT-based intent classification
|
| 312 |
-
|
| 313 |
-
✅ Deep Learning
|
| 314 |
-
|
| 315 |
-
🔹 PyTorch 🔥 – Model training & fine-tuning
|
| 316 |
-
""")
|
| 317 |
-
|
| 318 |
-
if st.button("Close", key="close_about"):
|
| 319 |
-
st.session_state.show_about = False # Close modal without resetting UI
|
| 320 |
-
st.rerun()
|
| 321 |
-
|
| 322 |
-
# Chat UI
|
| 323 |
-
st.title("🤖 AI Chatbot")
|
| 324 |
-
st.markdown("### Talk to me, I'm listening...")
|
| 325 |
-
|
| 326 |
-
rain(emoji="💬", font_size=10, falling_speed=5, animation_length="infinite")
|
| 327 |
-
rain(emoji="❄️", font_size=10, falling_speed=5, animation_length="infinite")
|
| 328 |
-
|
| 329 |
-
# Chat Input with Enter Button
|
| 330 |
-
with st.form("chat_form", clear_on_submit=True):
|
| 331 |
-
chat_input = st.text_input("You:", key="chat_input")
|
| 332 |
-
submit_button = st.form_submit_button("Enter")
|
| 333 |
-
|
| 334 |
-
if submit_button and chat_input:
|
| 335 |
-
intent_label = predict_intent(chat_input)
|
| 336 |
-
response = get_response(intent_label)
|
| 337 |
-
chat_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 338 |
-
|
| 339 |
-
# Append messages to chat history (User & Bot)
|
| 340 |
-
st.session_state.chat_history.append(f"[{chat_time}] You: {chat_input}")
|
| 341 |
-
st.session_state.chat_history.append(f"[{chat_time}] Bot: {response}")
|
| 342 |
-
|
| 343 |
-
# Save chat history persistently
|
| 344 |
-
save_chat_history()
|
| 345 |
-
|
| 346 |
-
# Display conversation immediately
|
| 347 |
-
with st.chat_message("user"):
|
| 348 |
-
st.markdown(f"**You:** {chat_input}")
|
| 349 |
-
time.sleep(0.5)
|
| 350 |
-
with st.chat_message("assistant"):
|
| 351 |
-
st.markdown(f"**Bot:** {response}")
|
| 352 |
-
|
| 353 |
-
# Style customization
|
| 354 |
-
st.markdown("""
|
| 355 |
-
<style>
|
| 356 |
-
|
| 357 |
-
/* Fix Modal Height & Enable Scroll */
|
| 358 |
-
div[data-modal-container="true"] {
|
| 359 |
-
position: fixed !important;
|
| 360 |
-
top: 5% !important; /* Adjust this value to position it higher */
|
| 361 |
-
color: #000000;
|
| 362 |
-
max-height: 1000px !important; /* Set max height */
|
| 363 |
-
}
|
| 364 |
-
|
| 365 |
-
/* Ensure the close button stays visible */
|
| 366 |
-
div[data-modal-container="true"] button {
|
| 367 |
-
position: sticky;
|
| 368 |
-
bottom: 10px;
|
| 369 |
-
background-color: #000000;
|
| 370 |
-
color: white;
|
| 371 |
-
}
|
| 372 |
-
|
| 373 |
-
.stChatMessage {padding: 10px; border-radius: 10px; background-color: #900C3F;}
|
| 374 |
-
.stChatMessageUser {background-color: #900C3F;}
|
| 375 |
-
.stChatMessageAssistant {background-color: #900C3F;}
|
| 376 |
-
</style>
|
| 377 |
-
>>>>>>> hf/main
|
| 378 |
""", unsafe_allow_html=True)
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
import torch
|
| 3 |
from transformers import BertTokenizer, BertForSequenceClassification
|
|
|
|
| 185 |
.stChatMessageUser {background-color: #900C3F;}
|
| 186 |
.stChatMessageAssistant {background-color: #900C3F;}
|
| 187 |
</style>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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