CompanAIon / app.py
Bey007's picture
Update app.py
b9dc3fd verified
raw
history blame
5 kB
import streamlit as st
from transformers import AutoModelForCausalLM, AutoTokenizer
from gtts import gTTS
import torch
import tempfile
import random
from pytube import Search
# Load DialoGPT model and tokenizer from Hugging Face
tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium")
model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-medium")
# Set up Streamlit page configuration
st.set_page_config(page_title="Grief and Loss Support Bot", page_icon="🌿", layout="centered")
st.markdown("""
<style>
.css-1d391kg { background-color: #F3F7F6; }
.css-ffhzg2 { font-size: 1.5em; font-weight: 500; color: #4C6D7D; }
.stTextInput>div>div>input { background-color: #D8E3E2; }
.stButton>button { background-color: #A9D0B6; color: white; border-radius: 5px; }
.stButton>button:hover { background-color: #8FB79A; }
.stTextInput>div>label { color: #4C6D7D; }
</style>
""", unsafe_allow_html=True)
# Title and introduction to the bot
st.title("Grief and Loss Support Bot 🌿")
st.subheader("Your compassionate companion in tough times 💚")
# Initialize session state for chat history
if 'chat_history_ids' not in st.session_state:
st.session_state.chat_history_ids = None
if 'bot_messages' not in st.session_state:
st.session_state.bot_messages = []
# User input
user_input = st.text_input("Share what's on your mind...", placeholder="Type here...", max_chars=500)
# Function to generate a response using DialoGPT
def generate_response(user_input):
if not user_input:
return "I'm here whenever you're ready to talk."
# Encode the user input and append to chat history
new_user_input_ids = tokenizer.encode(user_input + tokenizer.eos_token, return_tensors='pt')
bot_input_ids = new_user_input_ids if st.session_state.chat_history_ids is None else torch.cat([st.session_state.chat_history_ids, new_user_input_ids], dim=-1)
# Generate the bot's response
chat_history_ids = model.generate(
bot_input_ids,
max_length=200,
pad_token_id=tokenizer.eos_token_id,
temperature=0.7,
top_k=50,
repetition_penalty=1.2
)
# Update the chat history
st.session_state.chat_history_ids = chat_history_ids
bot_response = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
bot_response += "\n\nYou're doing your best, and that’s all anyone can ask for. Please take care of yourself and know that it’s okay to take a step back when things feel overwhelming."
return bot_response
# Generate and display bot response if there's user input
if user_input:
response = generate_response(user_input)
st.session_state.bot_messages.append(response)
# Display bot's response
for message in st.session_state.bot_messages:
st.text_area("Bot's Response:", message, height=150)
# Text-to-speech output
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
tts = gTTS(response, lang='en')
tts.save(tmp_file.name)
st.audio(tmp_file.name, format="audio/mp3")
# Activity suggestion based on detected keywords
if any(keyword in user_input.lower() for keyword in ["lonely", "lost", "sad", "overwhelmed", "academic", "exam"]):
st.info("Here's a suggestion to help you cope:")
# Activities based on user mood and needs
activities = {
"journaling": "Express your feelings in writing. Journaling is a great way to process emotions.",
"yoga": "Yoga helps you relax and refocus. Try some deep breathing exercises or light stretching.",
"painting": "Creative expression through painting or drawing can be soothing and help you release pent-up emotions.",
"meditation": "Take a moment to calm your mind. Guided meditation can help reduce stress and anxiety.",
"exercise": "Physical activity can lift your mood. Even a short walk in nature can make a big difference."
}
# Randomly suggest an activity
activity = random.choice(list(activities.keys()))
st.write(f"How about {activity}? {activities[activity]}")
# Search YouTube for related videos using pytube
search = Search(activity)
search_results = search.results[:3] # Limit results to 3 videos
if search_results:
for video in search_results:
st.write(f"[{video.title}]({video.watch_url})")
else:
st.write("Sorry, I couldn't find any relevant videos at the moment.")
# Crisis resources for distress signals
crisis_keywords = ["help", "suicide", "depressed", "emergency", "hurt", "lost"]
if any(keyword in user_input.lower() for keyword in crisis_keywords):
st.warning("It seems like you might be in distress. Please reach out to a crisis hotline or a trusted individual.")
st.write("[Find emergency resources here](https://www.helpguide.org/find-help.htm)")