Rahil80/intent-chatbot-space
0
1import streamlit as st
2import nltk
3import numpy as np
4from keras.models import load_model
5from nltk.stem import WordNetLemmatizer
6import pickle
7import json
8import random
9import os
10
11# Download required NLTK data
12nltk.download('punkt')
13nltk.download('wordnet')
14
15# === Define model directory paths ===
16MODEL_DIR = "models"
17MODEL_PATH = os.path.join(MODEL_DIR, "model.h5")
18
19if not os.path.exists(MODEL_PATH):
20 raise RuntimeError("Model not found. CI should push models/model.h5 into this Space repo.")
21
22TEXTS_PATH = os.path.join(MODEL_DIR, "texts.pkl")
23LABELS_PATH = os.path.join(MODEL_DIR, "labels.pkl")
24INTENTS_PATH = os.path.join(MODEL_DIR, "intents.json")
25
26# === Load model and supporting data ===
27model = load_model(MODEL_PATH)
28words = pickle.load(open(TEXTS_PATH, 'rb'))
29classes = pickle.load(open(LABELS_PATH, 'rb'))
30
31# Try to load intents from models folder (fallback to root if not found)
32if os.path.exists(INTENTS_PATH):
33 with open(INTENTS_PATH, 'r', encoding='utf-8') as file:
34 intents = json.load(file)
35else:
36 with open('intents.json', 'r', encoding='utf-8') as file:
37 intents = json.load(file)
38
39lemmatizer = WordNetLemmatizer()
40
41# === Preprocessing Function ===
42def preprocess_input(sentence):
43 sentence_words = nltk.word_tokenize(sentence)
44 sentence_words = [lemmatizer.lemmatize(word.lower()) for word in sentence_words]
45
46 bag = [0] * len(words)
47 for s in sentence_words:
48 for i, w in enumerate(words):
49 if w == s:
50 bag[i] = 1
51 return np.array(bag)
52
53# === Prediction Function ===
54def predict_intent(sentence):
55 bag = preprocess_input(sentence)
56 res = model.predict(np.array([bag]))[0]
57 ERROR_THRESHOLD = 0.25
58 results = [[i, r] for i, r in enumerate(res) if r > ERROR_THRESHOLD]
59 results.sort(key=lambda x: x[1], reverse=True)
60
61 return [{"intent": classes[r[0]], "probability": str(r[1])} for r in results]
62
63# === Response Retrieval ===
64def get_response(intents_list, intents_json):
65 tag = intents_list[0]['intent']
66 for intent in intents_json['intents']:
67 if intent['tag'] == tag:
68 return random.choice(intent['responses'])
69
70def chatbot_response(user_input):
71 intents_list = predict_intent(user_input)
72 if intents_list:
73 return get_response(intents_list, intents)
74 return "I didn't understand that. Could you please rephrase?"
75
76# === Streamlit UI ===
77st.set_page_config(page_title="Chatbot", layout="centered")
78
79# Sidebar Menu
80st.sidebar.title("Menu")
81menu_option = st.sidebar.radio(
82 "Choose an option:",
83 ("Chatbot", "Conversation History", "About the Chatbot")
84)
85
86# Initialize chat history
87if 'chat_history' not in st.session_state:
88 st.session_state['chat_history'] = []
89
90# === Chatbot Interface ===
91if menu_option == "Chatbot":
92 st.title("Talk Data to Me")
93 st.markdown("Type a message below to interact with the chatbot.")
94
95 user_input = st.text_input("Type your message", "", key="user_input")
96 if st.button("Send"):
97 if user_input:
98 response = chatbot_response(user_input)
99 st.session_state['chat_history'].append({"user": user_input, "bot": response})
100
101 # Display chat history
102 for chat in st.session_state['chat_history']:
103 st.markdown(f"**You:** {chat['user']}")
104 st.markdown(f"**Bot:** {chat['bot']}")
105
106# === Conversation History ===
107elif menu_option == "Conversation History":
108 st.title("Conversation History")
109 if st.session_state['chat_history']:
110 for chat in st.session_state['chat_history']:
111 st.markdown(f"**You:** {chat['user']}")
112 st.markdown(f"**Bot:** {chat['bot']}")
113 if st.button("Clear History"):
114 st.session_state['chat_history'] = []
115 st.success("Chat history cleared!")
116 else:
117 st.info("No conversation history available.")
118
119# === About Section ===
120elif menu_option == "About the Chatbot":
121 st.title("About the Chatbot")
122 st.markdown("""
123 ### Intent-Based Chatbot
124 This chatbot is an **intent-based chatbot** designed to understand and respond to user queries based on predefined intents.
125 It uses **NLP (Natural Language Processing)** to classify user input and **Keras** for intent prediction.
126
127 #### How It Works:
128 1. **Intent Recognition** – The model classifies input text into one of the predefined intents.
129 2. **Response Generation** – The chatbot retrieves a suitable response for the detected intent.
130 3. **Conversation History** – All messages are stored in a session history for the current session.
131
132 #### Technologies Used:
133 - **NLTK** for tokenization and lemmatization
134 - **Keras/TensorFlow** for model training and prediction
135 - **Streamlit** for an interactive web interface
136
137 #### Developer:
138 This chatbot was developed as part of a project to demonstrate the capabilities of intent-based conversational agents.
139 """)
140 