Spaces:
Sleeping
Sleeping
import streamlit as st | |
import torch | |
from transformers import AutoModelForCausalLM, AutoTokenizer | |
# Initialize the chatbot model and tokenizer | |
model_name = "microsoft/DialoGPT-medium" | |
tokenizer = AutoTokenizer.from_pretrained(model_name) | |
model = AutoModelForCausalLM.from_pretrained(model_name) | |
# Initialize chat history | |
if 'chat_history_ids' not in st.session_state: | |
st.session_state['chat_history_ids'] = None | |
if 'chat_history' not in st.session_state: | |
st.session_state['chat_history'] = [] | |
# Define the respond function | |
def respond(user_input): | |
new_user_input_ids = tokenizer.encode(user_input + tokenizer.eos_token, return_tensors='pt') | |
if st.session_state['chat_history_ids'] is None: | |
st.session_state['chat_history_ids'] = new_user_input_ids | |
else: | |
st.session_state['chat_history_ids'] = torch.cat([st.session_state['chat_history_ids'], new_user_input_ids], dim=-1) | |
# Emotional detection and response | |
if "happy" in user_input.lower(): | |
response = "That's wonderful to hear! What made you feel happy today?" | |
elif "sad" in user_input.lower(): | |
response = "I'm sorry to hear that. Would you like to share what's making you feel sad?" | |
elif "angry" in user_input.lower(): | |
response = "It's okay to feel angry. What’s bothering you?" | |
elif "excited" in user_input.lower(): | |
response = "That's great! What are you excited about?" | |
elif "depressed" in user_input.lower(): | |
response = "I'm really sorry to hear that. It's important to talk about it. Would you like to share more?" | |
elif "stressed" in user_input.lower(): | |
response = "Stress can be tough. What's been stressing you out?" | |
else: | |
# Generate a response from the model for general inquiries | |
chat_history_ids = model.generate( | |
st.session_state['chat_history_ids'], | |
max_length=1000, | |
pad_token_id=tokenizer.eos_token_id, | |
do_sample=True, | |
top_k=50, | |
top_p=0.95, | |
temperature=0.7 | |
) | |
response = tokenizer.decode(chat_history_ids[:, st.session_state['chat_history_ids'].shape[-1]:][0], skip_special_tokens=True) | |
# Update chat history | |
st.session_state['chat_history_ids'] = st.session_state['chat_history_ids'] | |
st.session_state['chat_history'].append({"user": user_input, "bot": response}) | |
return response | |
# Streamlit app layout | |
st.title("Emotional Support & General Knowledge Chatbot") | |
st.write("Hello! I'm here to support you emotionally and answer any questions. How are you feeling today?") | |
# Display chat history | |
if st.session_state['chat_history']: | |
for chat in st.session_state['chat_history']: | |
st.write(f"You: {chat['user']}") | |
st.write(f"Chatbot: {chat['bot']}") | |
# User input | |
user_input = st.text_input("You: ") | |
if st.button("Send"): | |
if user_input: | |
response = respond(user_input) | |
st.write(f"Chatbot: {response}") | |