File size: 3,055 Bytes
30bbc3e
 
 
 
 
 
 
 
 
 
18ce6e7
30bbc3e
 
 
 
 
 
 
18ce6e7
30bbc3e
 
 
 
 
 
18ce6e7
30bbc3e
 
 
 
 
904fd05
30bbc3e
 
 
 
429c6d8
 
30bbc3e
 
18ce6e7
 
30bbc3e
 
 
429c6d8
30bbc3e
 
 
 
 
 
429c6d8
30bbc3e
 
18ce6e7
429c6d8
30bbc3e
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()
        st.write(f"Loaded knowledge base: {self.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:
            st.write("Knowledge base file not found, starting with an empty knowledge base.")
            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)
        st.write(f"Knowledge base saved: {self.knowledge_base}")

    def learn_and_response(self, user_input):
        response = self.find_response(user_input)
        if response is None:
            st.write(f"I don't have a response for '{user_input}'. Please teach me:")
            # Display a text input to teach the bot
            response = st.text_input(f"Teach me a response for '{user_input}':", key="teach_input")
            if st.button("Submit Response"):
                if response:
                    self.teach_response(user_input, response)
                    st.success(f"Response saved for '{user_input}': {response}")
                    return response
                else:
                    st.warning("Please provide a response before submitting.")
        else:
            st.write(f"Found response for '{user_input}': {response}")
        return response

    def find_response(self, user_input):
        """Find a response in the knowledge base."""
        for question in self.knowledge_base.get("questions", []):
            if question['question'].lower() == user_input.lower():
                return question['response']
        return None

    def teach_response(self, user_input, response):
        """Teach the bot a new response."""
        new_question = {'question': user_input.lower(), 'response': response}
        self.knowledge_base['questions'].append(new_question)
        st.write(f"New question added: {new_question}")
        self.save_knowledge_base()  # Save the updated knowledge base

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 st.button("Submit Query"):
        if user_input:
            response = chatbot.learn_and_response(user_input)
            if response:
                st.write(f"Bot: {response}")
        else:
            st.warning("Please enter a query before submitting.")