ajeetkumar01's picture
Update app.py
8ec0647 verified
raw
history blame
2.35 kB
import json
import streamlit as st
st.set_page_config(page_title="Self-Learning Chatbot")
st.title("Self-Learning Chatbot")
class ChatBot:
def __init__(self, knowledge_base_file='knowledge_base.json'):
self.knowledge_base_file = knowledge_base_file
self.knowledge_base = self.load_knowledge_base()
def load_knowledge_base(self):
"""Load knowledge base from the JSON file."""
try:
with open(self.knowledge_base_file, "r") as f:
return json.load(f)
except FileNotFoundError:
return {"questions": []} # Return an empty structure if file does not exist
def save_knowledge_base(self):
"""Save knowledge base to the JSON file."""
with open(self.knowledge_base_file, 'w') as f:
json.dump(self.knowledge_base, f, indent=4)
def learn_and_respond(self, user_input):
response = self.find_response(user_input)
if response is None:
response = st.text_input(f"I don't have a response for '{user_input}'. Please teach me:", key="response_input")
if response: # Only teach a response if something is entered
self.teach_response(user_input, response)
st.success("Learned successfully!")
# Save the updated knowledge base to the JSON file
self.save_knowledge_base()
return response
def find_response(self, user_input):
user_input = user_input.lower().strip()
for question in self.knowledge_base.get("questions", []):
if question['question'].lower() == user_input:
return question['response']
return None
def teach_response(self, user_input, response):
new_question = {'question': user_input.lower().strip(), 'response': response}
if 'questions' not in self.knowledge_base:
self.knowledge_base['questions'] = []
self.knowledge_base['questions'].append(new_question)
if __name__ == "__main__":
# Initialize the chatbot with the JSON file
chatbot = ChatBot('knowledge_base.json')
# User interaction with Streamlit UI
user_input = st.text_input("Enter your query below:", key="user_input")
if user_input:
response = chatbot.learn_and_respond(user_input)
if response:
st.write(f"Bot: {response}")