Samarth4023 commited on
Commit
88e4b6f
·
2 Parent(s): b8866542c96cfb
Files changed (5) hide show
  1. .gitattributes +6 -0
  2. Images/Bot Image.jpeg +0 -0
  3. README.md +16 -0
  4. app.py +190 -0
  5. requirements.txt +8 -0
.gitattributes CHANGED
@@ -1,2 +1,8 @@
 
1
  Trained[[:space:]]Model/bert_chatbot_model.pth filter=lfs diff=lfs merge=lfs -text
2
  Trained[[:space:]]Model/chatbot_model/model.safetensors filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
1
+ <<<<<<< HEAD
2
  Trained[[:space:]]Model/bert_chatbot_model.pth filter=lfs diff=lfs merge=lfs -text
3
  Trained[[:space:]]Model/chatbot_model/model.safetensors filter=lfs diff=lfs merge=lfs -text
4
+ =======
5
+ Trained[[:space:]]Model/bert_chatbot_model.pth filter=lfs diff=lfs merge=lfs -text
6
+ Trained[[:space:]]Model/chatbot_model/model.safetensors filter=lfs diff=lfs merge=lfs -text
7
+ Images/Bot[[:space:]]Image.jpeg filter=lfs diff=lfs merge=lfs -text
8
+ >>>>>>> hf/main
Images/Bot Image.jpeg CHANGED

Git LFS Details

  • SHA256: 2f1760f6c71098287ba8dbe6d5c7a645b89154c2189355aba3b0da13515a4f27
  • Pointer size: 131 Bytes
  • Size of remote file: 370 kB
README.md CHANGED
@@ -1,3 +1,4 @@
 
1
  # **🤖 AI-Powered Chatbot using NLP**
2
 
3
  ## **📌 Introduction**
@@ -109,3 +110,18 @@ This project is **open-source** and free to use. Feel free to contribute!
109
  📌 **GitHub:** [Samarth4023](https://github.com/Samarth4023)
110
  📌 **LinkedIn:** [Samarth Pujari](https://www.linkedin.com/in/samarth-pujari-328a1326a)
111
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <<<<<<< HEAD
2
  # **🤖 AI-Powered Chatbot using NLP**
3
 
4
  ## **📌 Introduction**
 
110
  📌 **GitHub:** [Samarth4023](https://github.com/Samarth4023)
111
  📌 **LinkedIn:** [Samarth Pujari](https://www.linkedin.com/in/samarth-pujari-328a1326a)
112
 
113
+ =======
114
+ ---
115
+ license: apache-2.0
116
+ title: 🧠AI Chatbot🤖
117
+ sdk: streamlit
118
+ emoji: 💻
119
+ colorFrom: pink
120
+ colorTo: purple
121
+ thumbnail: >-
122
+ https://cdn-uploads.huggingface.co/production/uploads/6686260107019f3fe482ce08/AyL6xBZnErZdG1_ou4QgV.jpeg
123
+ short_description: The System on Real Time Intent Recognition and Conversations
124
+ ---
125
+ # Implementation of Chatbot using Natural Language Processing (NLP)
126
+ Welcome!
127
+ >>>>>>> hf/main
app.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import streamlit as st
2
  import torch
3
  from transformers import BertTokenizer, BertForSequenceClassification
@@ -185,4 +186,193 @@ st.markdown("""
185
  .stChatMessageUser {background-color: #900C3F;}
186
  .stChatMessageAssistant {background-color: #900C3F;}
187
  </style>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
188
  """, unsafe_allow_html=True)
 
1
+ <<<<<<< HEAD
2
  import streamlit as st
3
  import torch
4
  from transformers import BertTokenizer, BertForSequenceClassification
 
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)
requirements.txt CHANGED
@@ -1,5 +1,13 @@
 
1
  streamlit
2
  torch
3
  transformers
4
  streamlit_extras
5
  streamlit_modal
 
 
 
 
 
 
 
 
1
+ <<<<<<< HEAD
2
  streamlit
3
  torch
4
  transformers
5
  streamlit_extras
6
  streamlit_modal
7
+ =======
8
+ streamlit
9
+ torch
10
+ transformers
11
+ streamlit_extras
12
+ streamlit_modal
13
+ >>>>>>> hf/main