Spaces:
Sleeping
Sleeping
import streamlit as st | |
import wikipediaapi | |
import requests | |
API_URL = "https://api-inference.huggingface.co/models/HuggingFaceH4/zephyr-7b-beta" | |
headers = {"Authorization": f"Bearer {st.secrets['HUGGINGFACE_TOKEN']}"} | |
def get_wikipedia_summary(name): | |
wiki = wikipediaapi.Wikipedia('en') | |
page = wiki.page(name) | |
return page.summary if page.exists() else None | |
def query_model(payload): | |
response = requests.post(API_URL, headers=headers, json=payload) | |
return response.json() | |
def chat_with_ai(person_name, user_input): | |
context = get_wikipedia_summary(person_name) | |
if not context: | |
return f"Could not find information about {person_name}" | |
prompt = f"You are {person_name}. Context: {context}\n\nUser: {user_input}\n{person_name}:" | |
try: | |
response = query_model({"inputs": prompt}) | |
return response[0]["generated_text"].split("User:")[0].strip() | |
except Exception as e: | |
return f"Error: {str(e)}" | |
st.title("Historical Figures Chat") | |
person_name = st.text_input("Enter historical figure name:") | |
if "messages" not in st.session_state: | |
st.session_state.messages = [] | |
for msg in st.session_state.messages: | |
st.chat_message(msg["role"]).write(msg["content"]) | |
if user_input := st.chat_input("Message..."): | |
if not person_name: | |
st.error("Please enter a historical figure's name") | |
st.stop() | |
st.session_state.messages.append({"role": "user", "content": user_input}) | |
st.chat_message("user").write(user_input) | |
with st.spinner("Thinking..."): | |
response = chat_with_ai(person_name, user_input) | |
st.session_state.messages.append({"role": "assistant", "content": response}) | |
st.chat_message("assistant").write(response) |