-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
132 lines (103 loc) · 5.4 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
import os
import json
import datetime
import csv
import nltk
import ssl
import streamlit as st
import random
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
ssl._create_default_https_context = ssl._create_unverified_context
nltk.data.path.append(os.path.abspath("nltk_data"))
nltk.download('punkt')
# Load intents from the JSON file
file_path = os.path.abspath("./intents.json")
with open(file_path, "r") as file:
intents = json.load(file)
# Create the vectorizer and classifier
vectorizer = TfidfVectorizer(ngram_range=(1, 4))
clf = LogisticRegression(random_state=0, max_iter=10000)
# Preprocess the data
tags = []
patterns = []
for intent in intents:
for pattern in intent['patterns']:
tags.append(intent['tag'])
patterns.append(pattern)
# training the model
x = vectorizer.fit_transform(patterns)
y = tags
clf.fit(x, y)
def chatbot(input_text):
input_text = vectorizer.transform([input_text])
tag = clf.predict(input_text)[0]
for intent in intents:
if intent['tag'] == tag:
response = random.choice(intent['responses'])
return response
counter = 0
def main():
global counter
st.title("Intents of Chatbot using NLP")
# Create a sidebar menu with options
menu = ["Home", "Conversation History", "About"]
choice = st.sidebar.selectbox("Menu", menu)
# Home Menu
if choice == "Home":
st.write("Welcome to the chatbot. Please type a message and press Enter to start the conversation.")
# Check if the chat_log.csv file exists, and if not, create it with column names
if not os.path.exists('chat_log.csv'):
with open('chat_log.csv', 'w', newline='', encoding='utf-8') as csvfile:
csv_writer = csv.writer(csvfile)
csv_writer.writerow(['User Input', 'Chatbot Response', 'Timestamp'])
counter += 1
user_input = st.text_input("You:", key=f"user_input_{counter}")
if user_input:
# Convert the user input to a string
user_input_str = str(user_input)
response = chatbot(user_input)
st.text_area("Chatbot:", value=response, height=120, max_chars=None, key=f"chatbot_response_{counter}")
# Get the current timestamp
timestamp = datetime.datetime.now().strftime(f"%Y-%m-%d %H:%M:%S")
# Save the user input and chatbot response to the chat_log.csv file
with open('chat_log.csv', 'a', newline='', encoding='utf-8') as csvfile:
csv_writer = csv.writer(csvfile)
csv_writer.writerow([user_input_str, response, timestamp])
if response.lower() in ['goodbye', 'bye']:
st.write("Thank you for chatting with me. Have a great day!")
st.stop()
# Conversation History Menu
elif choice == "Conversation History":
# Display the conversation history in a collapsible expander
st.header("Conversation History")
# with st.beta_expander("Click to see Conversation History"):
with open('chat_log.csv', 'r', encoding='utf-8') as csvfile:
csv_reader = csv.reader(csvfile)
next(csv_reader) # Skip the header row
for row in csv_reader:
st.text(f"User: {row[0]}")
st.text(f"Chatbot: {row[1]}")
st.text(f"Timestamp: {row[2]}")
st.markdown("---")
elif choice == "About":
st.write("The goal of this project is to create a chatbot that can understand and respond to user input based on intents. The chatbot is built using Natural Language Processing (NLP) library and Logistic Regression, to extract the intents and entities from user input. The chatbot is built using Streamlit, a Python library for building interactive web applications.")
st.subheader("Project Overview:")
st.write("""
The project is divided into two parts:
1. NLP techniques and Logistic Regression algorithm is used to train the chatbot on labeled intents and entities.
2. For building the Chatbot interface, Streamlit web framework is used to build a web-based chatbot interface. The interface allows users to input text and receive responses from the chatbot.
""")
st.subheader("Dataset:")
st.write("""
The dataset used in this project is a collection of labelled intents and entities. The data is stored in a list.
- Intents: The intent of the user input (e.g. "greeting", "budget", "about")
- Entities: The entities extracted from user input (e.g. "Hi", "How do I create a budget?", "What is your purpose?")
- Text: The user input text.
""")
st.subheader("Streamlit Chatbot Interface:")
st.write("The chatbot interface is built using Streamlit. The interface includes a text input box for users to input their text and a chat window to display the chatbot's responses. The interface uses the trained model to generate responses to user input.")
st.subheader("Conclusion:")
st.write("In this project, a chatbot is built that can understand and respond to user input based on intents. The chatbot was trained using NLP and Logistic Regression, and the interface was built using Streamlit. This project can be extended by adding more data, using more sophisticated NLP techniques, deep learning algorithms.")
if __name__ == '__main__':
main()