Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import streamlit as st
|
3 |
+
|
4 |
+
st.set_page_config(page_title="Self-Learning Chatbot")
|
5 |
+
st.title("Self-Learning Chatbot")
|
6 |
+
|
7 |
+
class ChatBot:
|
8 |
+
def __init__(self, knowledge_base_file='knowledge_base.json'):
|
9 |
+
self.knowledge_base_file = knowledge_base_file
|
10 |
+
self.knowledge_base = self.load_knowledge_base()
|
11 |
+
|
12 |
+
def load_knowledge_base(self):
|
13 |
+
"""Load knowledge base from the JSON file."""
|
14 |
+
try:
|
15 |
+
with open(self.knowledge_base_file, "r") as f:
|
16 |
+
return json.load(f)
|
17 |
+
except FileNotFoundError:
|
18 |
+
return {"questions": []} # Return an empty structure if file does not exist
|
19 |
+
|
20 |
+
def save_knowledge_base(self):
|
21 |
+
"""Save knowledge base to the JSON file."""
|
22 |
+
with open(self.knowledge_base_file, 'w') as f:
|
23 |
+
json.dump(self.knowledge_base, f, indent=4)
|
24 |
+
|
25 |
+
def learn_and_response(self, user_input):
|
26 |
+
response = self.find_response(user_input)
|
27 |
+
if response is None:
|
28 |
+
st.write(f"I don't have a response for '{user_input}'. Please teach me:")
|
29 |
+
response = st.text_input(f"Teach me a response for '{user_input}':", key="teach_input")
|
30 |
+
if st.button("Submit Response"):
|
31 |
+
if response:
|
32 |
+
self.teach_response(user_input, response)
|
33 |
+
self.save_knowledge_base() # Save after teaching
|
34 |
+
st.success("Response saved!")
|
35 |
+
else:
|
36 |
+
st.warning("Please provide a response before submitting.")
|
37 |
+
return response
|
38 |
+
|
39 |
+
def find_response(self, user_input):
|
40 |
+
for question in self.knowledge_base.get("questions", []):
|
41 |
+
if question['question'].lower() == user_input.lower():
|
42 |
+
return question['response']
|
43 |
+
return None
|
44 |
+
|
45 |
+
def teach_response(self, user_input, response):
|
46 |
+
new_question = {'question': user_input.lower(), 'response': response}
|
47 |
+
if 'questions' not in self.knowledge_base:
|
48 |
+
self.knowledge_base['questions'] = []
|
49 |
+
self.knowledge_base['questions'].append(new_question)
|
50 |
+
|
51 |
+
if __name__ == "__main__":
|
52 |
+
# Initialize the chatbot with the JSON file
|
53 |
+
chatbot = ChatBot('knowledge_base.json')
|
54 |
+
|
55 |
+
# User interaction with Streamlit UI
|
56 |
+
user_input = st.text_input("Enter your query below:", key="user_input")
|
57 |
+
if st.button("Submit Query"):
|
58 |
+
if user_input:
|
59 |
+
response = chatbot.learn_and_response(user_input)
|
60 |
+
if response:
|
61 |
+
st.write(f"Bot: {response}")
|
62 |
+
else:
|
63 |
+
st.warning("Please enter a query before submitting.")
|