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