Spaces:
Sleeping
Sleeping
import streamlit as st | |
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline | |
from gtts import gTTS | |
from pytube import Search | |
import random | |
import os | |
import time | |
# Load pretrained models | |
tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium") | |
model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-medium") | |
emotion_classifier = pipeline("text-classification", model="bhadresh-savani/distilbert-base-uncased-emotion", return_all_scores=True) | |
# 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; }</style>", unsafe_allow_html=True) | |
# Title and welcome text | |
st.title("Grief and Loss Support Bot πΏ") | |
st.subheader("Your compassionate companion in tough times π") | |
# Sidebar for additional features | |
with st.sidebar: | |
st.header("π§ Guided Meditation") | |
if st.button("Play Meditation"): | |
meditation_audio = "meditation.mp3" | |
if not os.path.exists(meditation_audio): | |
tts = gTTS("Take a deep breath. Relax and let go of any tension...", lang='en') | |
tts.save(meditation_audio) | |
st.audio(meditation_audio, format="audio/mp3") | |
st.header("π Short Comforting Story") | |
story_theme = st.selectbox("Choose a theme for your story:", ["courage", "healing", "hope"]) | |
if st.button("Generate Story"): | |
story_prompt = f"Tell me a comforting story about {story_theme}." | |
input_ids = tokenizer.encode(story_prompt, return_tensors='pt') | |
story_ids = model.generate(input_ids, max_length=150, temperature=0.8, repetition_penalty=1.1) | |
story = tokenizer.decode(story_ids[0], skip_special_tokens=True) | |
st.text_area("Here's your story:", story, height=200) | |
# User input section | |
user_input = st.text_input("Share what's on your mind...", placeholder="Type here...", max_chars=500) | |
if 'previous_responses' not in st.session_state: | |
st.session_state.previous_responses = [] | |
if 'badges' not in st.session_state: | |
st.session_state.badges = [] | |
# Generate empathetic response | |
def generate_response(user_input): | |
input_ids = tokenizer.encode(user_input + tokenizer.eos_token, return_tensors='pt') | |
chat_history_ids = model.generate(input_ids, max_length=150, temperature=0.7, top_k=50, repetition_penalty=1.2) | |
response = tokenizer.decode(chat_history_ids[:, input_ids.shape[-1]:][0], skip_special_tokens=True) | |
return response | |
# Analyze user input for emotional tone | |
def get_emotion(user_input): | |
emotions = emotion_classifier(user_input) | |
emotions_sorted = sorted(emotions[0], key=lambda x: x['score'], reverse=True) | |
return emotions_sorted[0]['label'] | |
# Provide a response if user input is provided | |
if user_input: | |
emotion = get_emotion(user_input) | |
response = generate_response(user_input) | |
# Display the bot's response | |
st.session_state.previous_responses.append(response) | |
st.text_area("Bot's Response:", response, height=250) | |
# Assign motivational badges | |
if emotion in ["joy", "optimism"]: | |
badge = "π Positivity Badge" | |
if badge not in st.session_state.badges: | |
st.session_state.badges.append(badge) | |
st.success(f"Congratulations! You've earned a {badge}!") | |
# Suggest coping activities | |
st.info("π¨ Try a New Activity") | |
activities = ["exercise", "yoga", "journaling", "painting", "meditation"] | |
selected_activity = st.selectbox("Pick an activity:", activities) | |
# Fetch YouTube video suggestions | |
if st.button("Find Videos"): | |
search = Search(selected_activity) | |
search_results = search.results[:3] | |
if not search_results: | |
st.write(f"No results found for '{selected_activity}'.") | |
else: | |
for video in search_results: | |
st.write(f"[{video.title}]({video.watch_url})") | |
# Crisis resources | |
if any(word in user_input.lower() for word in ["suicide", "help", "depressed"]): | |
st.warning("Please reach out to a crisis hotline for immediate support.") | |
st.write("[Find emergency resources here](https://www.helpguide.org/find-help.htm)") | |
# Generate audio response | |
tts = gTTS(response, lang='en') | |
audio_file = "response.mp3" | |
tts.save(audio_file) | |
st.audio(audio_file, format="audio/mp3") | |
# Display badges and achievements | |
if st.session_state.badges: | |
st.sidebar.header("π Achievements") | |
for badge in st.session_state.badges: | |
st.sidebar.write(badge) | |