import streamlit as st import wikipediaapi import random # Initialize Wikipedia API wiki_wiki = wikipediaapi.Wikipedia( user_agent='HistoricalFiguresApp/1.0 (your_email@example.com)', language='en' ) def get_wikipedia_summary(name): """Retrieve and clean the Wikipedia summary for a historical figure, avoiding disambiguation pages.""" page = wiki_wiki.page(name) if not page.exists(): return "Sorry, I couldn't find information on that historical figure." # Remove disambiguation-related content if 'may refer to' in page.summary.lower(): return "This name refers to multiple topics. Can you provide more details?" return page.summary def generate_dynamic_response(person_name, user_input, context): """Dynamically generate a response based on the historical figure's persona and context.""" user_input = user_input.lower() intro = f"Hello! I am {person_name}. Do you have any questions for me?" sentences = [s.strip() for s in context.split('.') if len(s) > 10] relevant_sentences = [s for s in sentences if any(word in s.lower() for word in user_input.split())] if relevant_sentences: response = random.choice(relevant_sentences) elif "fishing" in user_input: response = "Ah, fishing! A pastime I did not indulge in, but I was always fascinated by the natural world and its forces." elif "hobbies" in user_input or "free time" in user_input: response = "In my free time, I was consumed by my experiments, always seeking the next great discovery." else: response = random.choice([ "That is an intriguing question. What makes you ask?", "A curious thought. Tell me more of your own views.", "History is shaped by questions such as these. What do you believe?" ]) return f"{intro} {response}" st.title("Chat with a Historical Figure!") # User inputs a historical figure if "chat_history" not in st.session_state: st.session_state.chat_history = [] st.session_state.summary = "" st.session_state.person_name = "" person_name = st.text_input("Enter the name of a historical figure:") if person_name and not st.session_state.person_name: st.session_state.person_name = person_name st.session_state.summary = get_wikipedia_summary(person_name) if "multiple topics" in st.session_state.summary: st.write(st.session_state.summary) else: st.session_state.chat_history.append((person_name, "I am here. Let us talk.")) if st.session_state.person_name and "multiple topics" not in st.session_state.summary: user_input = st.text_input("Ask a question:") if user_input: response = generate_dynamic_response(st.session_state.person_name, user_input, st.session_state.summary) st.session_state.chat_history.append(("You", user_input)) st.session_state.chat_history.append((st.session_state.person_name, response)) for speaker, message in st.session_state.chat_history: st.write(f"**{speaker}:** {message}")