Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,10 +1,8 @@
|
|
1 |
import streamlit as st
|
2 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
3 |
from gtts import gTTS
|
4 |
-
import torch
|
5 |
-
import tempfile
|
6 |
-
import random
|
7 |
from pytube import Search
|
|
|
8 |
|
9 |
# Load DialoGPT model and tokenizer from Hugging Face
|
10 |
tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium")
|
@@ -27,85 +25,77 @@ st.markdown("""
|
|
27 |
st.title("Grief and Loss Support Bot 🌿")
|
28 |
st.subheader("Your compassionate companion in tough times 💚")
|
29 |
|
30 |
-
# Initialize session state for chat history
|
31 |
-
if 'chat_history_ids' not in st.session_state:
|
32 |
-
st.session_state.chat_history_ids = None
|
33 |
-
if 'bot_messages' not in st.session_state:
|
34 |
-
st.session_state.bot_messages = []
|
35 |
-
|
36 |
# User input
|
37 |
user_input = st.text_input("Share what's on your mind...", placeholder="Type here...", max_chars=500)
|
38 |
|
39 |
-
#
|
40 |
-
|
41 |
-
|
42 |
-
return "I'm here whenever you're ready to talk."
|
43 |
|
44 |
-
|
|
|
|
|
45 |
new_user_input_ids = tokenizer.encode(user_input + tokenizer.eos_token, return_tensors='pt')
|
46 |
-
bot_input_ids = new_user_input_ids
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
# Generate and display bot response if there's user input
|
67 |
-
if user_input:
|
68 |
-
response = generate_response(user_input)
|
69 |
-
st.session_state.bot_messages.append(response)
|
70 |
-
|
71 |
-
# Display bot's response
|
72 |
-
for message in st.session_state.bot_messages:
|
73 |
-
st.text_area("Bot's Response:", message, height=150)
|
74 |
-
|
75 |
-
# Text-to-speech output
|
76 |
-
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
|
77 |
-
tts = gTTS(response, lang='en')
|
78 |
-
tts.save(tmp_file.name)
|
79 |
-
st.audio(tmp_file.name, format="audio/mp3")
|
80 |
-
|
81 |
-
# Activity suggestion based on detected keywords
|
82 |
-
if any(keyword in user_input.lower() for keyword in ["lonely", "lost", "sad", "overwhelmed", "academic", "exam"]):
|
83 |
st.info("Here's a suggestion to help you cope:")
|
84 |
|
85 |
-
#
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
# Crisis resources for distress signals
|
108 |
crisis_keywords = ["help", "suicide", "depressed", "emergency", "hurt", "lost"]
|
109 |
if any(keyword in user_input.lower() for keyword in crisis_keywords):
|
110 |
st.warning("It seems like you might be in distress. Please reach out to a crisis hotline or a trusted individual.")
|
111 |
st.write("[Find emergency resources here](https://www.helpguide.org/find-help.htm)")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import streamlit as st
|
2 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
3 |
from gtts import gTTS
|
|
|
|
|
|
|
4 |
from pytube import Search
|
5 |
+
import random
|
6 |
|
7 |
# Load DialoGPT model and tokenizer from Hugging Face
|
8 |
tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium")
|
|
|
25 |
st.title("Grief and Loss Support Bot 🌿")
|
26 |
st.subheader("Your compassionate companion in tough times 💚")
|
27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
# User input
|
29 |
user_input = st.text_input("Share what's on your mind...", placeholder="Type here...", max_chars=500)
|
30 |
|
31 |
+
# Store previous responses to check for repetition
|
32 |
+
if 'previous_responses' not in st.session_state:
|
33 |
+
st.session_state.previous_responses = []
|
|
|
34 |
|
35 |
+
# Function to generate a more empathetic and focused response using DialoGPT
|
36 |
+
def generate_response(user_input):
|
37 |
+
# Encode the input text and generate a response
|
38 |
new_user_input_ids = tokenizer.encode(user_input + tokenizer.eos_token, return_tensors='pt')
|
39 |
+
bot_input_ids = new_user_input_ids
|
40 |
+
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)
|
41 |
+
|
42 |
+
# Decode the response to text
|
43 |
+
chat_history_ids = chat_history_ids[:, bot_input_ids.shape[-1]:] # remove the input from the response
|
44 |
+
bot_output = tokenizer.decode(chat_history_ids[0], skip_special_tokens=True)
|
45 |
+
|
46 |
+
# Build a more empathetic and thoughtful response
|
47 |
+
response = f"I’m really sorry you're feeling like this. It’s completely normal to feel overwhelmed when you're facing a heavy workload. It’s important to acknowledge how you feel and not keep it bottled up. Sometimes, stress and emotional exhaustion can build up, and it’s okay to let yourself feel those emotions."
|
48 |
+
|
49 |
+
# Add coping strategies based on the situation
|
50 |
+
if "workload" in user_input.lower():
|
51 |
+
response += "\n\nWhen the workload feels too heavy, it can be helpful to break tasks down into smaller, more manageable steps. Focus on one thing at a time, and remember that it’s okay to take breaks when needed. Asking for support from colleagues or friends is also a good way to lighten the load."
|
52 |
+
|
53 |
+
# Add general supportive message
|
54 |
+
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 too much. Your well-being is the most important thing."
|
55 |
+
|
56 |
+
# Suggest a productive activity based on detected keywords
|
57 |
+
if any(keyword in user_input.lower() for keyword in ["lonely", "lost", "sad", "overwhelmed"]):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
58 |
st.info("Here's a suggestion to help you cope:")
|
59 |
|
60 |
+
# List of activities
|
61 |
+
hobbies = ["journaling", "yoga", "painting", "exercise", "meditation"]
|
62 |
+
activity = st.selectbox("Choose an activity you'd like to try:", hobbies)
|
63 |
+
|
64 |
+
# Search YouTube for videos related to the selected activity
|
65 |
+
try:
|
66 |
+
search = Search(activity)
|
67 |
+
search_results = search.results[:3] # limit results to 3 videos
|
68 |
+
st.write(f"Searching for videos related to {activity}...") # Debugging line
|
69 |
+
|
70 |
+
if not search_results:
|
71 |
+
st.write(f"No results found for '{activity}'. Please try again.")
|
72 |
+
else:
|
73 |
+
st.write(f"Found {len(search_results)} video(s) related to '{activity}'!")
|
74 |
+
for video in search_results:
|
75 |
+
st.write(f"[{video.title}]({video.watch_url})")
|
76 |
+
except Exception as e:
|
77 |
+
st.write(f"An error occurred while searching for videos: {str(e)}")
|
78 |
+
st.write("Sorry, I couldn't fetch videos at the moment.")
|
79 |
+
|
80 |
+
# Crisis resources
|
|
|
|
|
81 |
crisis_keywords = ["help", "suicide", "depressed", "emergency", "hurt", "lost"]
|
82 |
if any(keyword in user_input.lower() for keyword in crisis_keywords):
|
83 |
st.warning("It seems like you might be in distress. Please reach out to a crisis hotline or a trusted individual.")
|
84 |
st.write("[Find emergency resources here](https://www.helpguide.org/find-help.htm)")
|
85 |
+
|
86 |
+
return response
|
87 |
+
|
88 |
+
# Check if the user has typed something
|
89 |
+
if user_input:
|
90 |
+
# Generate the empathetic response
|
91 |
+
response = generate_response(user_input)
|
92 |
+
|
93 |
+
# Store and show the new response
|
94 |
+
st.session_state.previous_responses.append(response)
|
95 |
+
st.text_area("Bot's Response:", response, height=250)
|
96 |
+
|
97 |
+
# Text-to-speech output (optional)
|
98 |
+
tts = gTTS(response, lang='en')
|
99 |
+
audio_file = "response.mp3"
|
100 |
+
tts.save(audio_file)
|
101 |
+
st.audio(audio_file, format="audio/mp3")
|