File size: 1,814 Bytes
f79b85d
 
 
 
 
 
 
 
 
 
 
 
 
 
c021d5a
f79b85d
 
 
c021d5a
46117ba
 
f79b85d
63f3504
f79b85d
63f3504
f79b85d
059c015
f79b85d
46117ba
f79b85d
46117ba
059c015
f79b85d
46117ba
f79b85d
46117ba
 
 
f79b85d
46117ba
 
 
059c015
f79b85d
ddac941
41637c6
46117ba
 
059c015
46117ba
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
import json
from difflib import get_close_matches
import streamlit as st

def load_knowledge_base(file_path: str) -> dict:
    with open(file_path, 'r') as file:
        data: dict = json.load(file)
    return data

def save_knowledge_base(file_path: str, data: dict):
    with open(file_path, 'w') as file:
        json.dump(data, file, indent=2)

def find_best_match(usr_question: str, questions: list[str]) -> str | None:
    matches: list = get_close_matches(usr_question, questions, n=1, cutoff=0.6)
    return matches[0] if matches else None

def get_answer_for_question(question: str, knowledge_base: dict) -> str | None:
    for q in knowledge_base['questions']:
        if q['question'] == question:
            return q['answer']

st.title("Curious Chat Bot")

knowledge_base: dict = load_knowledge_base('knowledge_base.json')

widget_counter = st.session_state.get('widget_counter', 0)  

user_input = st.text_input("You:", key=f"user_input_{widget_counter}")

if st.button("Ask"):
    widget_counter += 1  

    best_match: str = find_best_match(user_input, [q['question'] for q in knowledge_base['questions']])

    if best_match:
        answer: str = get_answer_for_question(best_match, knowledge_base)
        st.text(f"Bot: {answer}")

    else:
        st.text("Bot: I don't know the answer, please can you teach me?")
        new_answer: str = st.text_input('Type the answer or "skip" to skip:', key=f"user_input_{widget_counter}")
        widget_counter += 1  

        if new_answer.lower() != 'skip':
            st.text("Bot: Thank you! I learnt something new.")
            knowledge_base['questions'].append({'question': user_input, 'answer': new_answer})
            save_knowledge_base('knowledge_base.json', knowledge_base)
            
st.session_state.widget_counter = widget_counter