Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,22 +1,170 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
|
5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
input_ids = gpt2_tokenizer.encode(response_prompt, return_tensors='pt')
|
7 |
response_ids = gpt2_model.generate(
|
8 |
input_ids,
|
9 |
-
max_length=
|
10 |
-
temperature=0.
|
11 |
-
top_k=
|
12 |
-
repetition_penalty=1.
|
13 |
num_return_sequences=1
|
|
|
14 |
)
|
15 |
|
16 |
# Decode the response and clean it up by removing the prompt
|
17 |
response = gpt2_tokenizer.decode(response_ids[0], skip_special_tokens=True)
|
18 |
|
19 |
# Strip out the prompt portion to get a clean, empathetic message
|
20 |
-
cleaned_response = response.replace(f"
|
21 |
|
22 |
return cleaned_response
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
3 |
+
from gtts import gTTS
|
4 |
+
from pytube import Search
|
5 |
+
import random
|
6 |
+
import os
|
7 |
+
|
8 |
+
# Load pretrained models
|
9 |
+
tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium")
|
10 |
+
model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-medium")
|
11 |
+
# Load GPT-2 model and tokenizer for story generation
|
12 |
+
gpt2_tokenizer = AutoTokenizer.from_pretrained("gpt2-medium")
|
13 |
+
gpt2_model = AutoModelForCausalLM.from_pretrained("gpt2-medium")
|
14 |
+
|
15 |
+
emotion_classifier = pipeline("text-classification", model="bhadresh-savani/distilbert-base-uncased-emotion", return_all_scores=True)
|
16 |
+
|
17 |
+
# Function to generate a comforting story using GPT-2
|
18 |
+
def generate_story(theme):
|
19 |
+
# A detailed prompt for generating a comforting story about the selected theme
|
20 |
+
story_prompt = f"Write a comforting, detailed, and heartwarming story about {theme}. The story should include a character who faces a tough challenge, finds hope, and ultimately overcomes the situation with a positive resolution."
|
21 |
+
|
22 |
+
# Generate story using GPT-2
|
23 |
+
input_ids = gpt2_tokenizer.encode(story_prompt, return_tensors='pt')
|
24 |
|
25 |
+
story_ids = gpt2_model.generate(
|
26 |
+
input_ids,
|
27 |
+
max_length=500, # Generate longer stories
|
28 |
+
temperature=0.8, # Balanced creativity
|
29 |
+
top_p=0.9,
|
30 |
+
repetition_penalty=1.2,
|
31 |
+
num_return_sequences=1
|
32 |
+
)
|
33 |
+
|
34 |
+
# Decode the generated text
|
35 |
+
story = gpt2_tokenizer.decode(story_ids[0], skip_special_tokens=True)
|
36 |
+
return story
|
37 |
+
|
38 |
+
def generate_response(user_input):
|
39 |
+
response_prompt = (
|
40 |
+
f"A user is feeling very sad and overwhelmed: '{user_input}'. "
|
41 |
+
"You are a compassionate support bot. Respond with empathy, encouragement, and reassurance."
|
42 |
+
)
|
43 |
input_ids = gpt2_tokenizer.encode(response_prompt, return_tensors='pt')
|
44 |
response_ids = gpt2_model.generate(
|
45 |
input_ids,
|
46 |
+
max_length=150,
|
47 |
+
temperature=0.8,
|
48 |
+
top_k=40,
|
49 |
+
repetition_penalty=1.1,
|
50 |
num_return_sequences=1
|
51 |
+
|
52 |
)
|
53 |
|
54 |
# Decode the response and clean it up by removing the prompt
|
55 |
response = gpt2_tokenizer.decode(response_ids[0], skip_special_tokens=True)
|
56 |
|
57 |
# Strip out the prompt portion to get a clean, empathetic message
|
58 |
+
cleaned_response = response.replace(f"A user is feeling very sad and overwhelmed:{user_input}.You are a compassionate support bot. Respond with empathy, encouragement, and reassurance", "").strip()
|
59 |
|
60 |
return cleaned_response
|
61 |
+
|
62 |
+
|
63 |
+
|
64 |
+
# Analyze user input for emotional tone
|
65 |
+
def get_emotion(user_input):
|
66 |
+
emotions = emotion_classifier(user_input)
|
67 |
+
emotions_sorted = sorted(emotions[0], key=lambda x: x['score'], reverse=True)
|
68 |
+
return emotions_sorted[0]['label']
|
69 |
+
|
70 |
+
# Function to fetch YouTube videos
|
71 |
+
def fetch_youtube_videos(activity):
|
72 |
+
search = Search(f"{activity} for mental health relaxation")
|
73 |
+
search_results = search.results[:3]
|
74 |
+
videos = []
|
75 |
+
for video in search_results:
|
76 |
+
video_url = f"https://www.youtube.com/watch?v={video.video_id}"
|
77 |
+
videos.append((video.title, video_url))
|
78 |
+
return videos
|
79 |
+
|
80 |
+
# Streamlit page configuration
|
81 |
+
st.set_page_config(page_title="Grief and Loss Support Bot πΏ", page_icon="πΏ", layout="centered")
|
82 |
+
st.markdown("<style>.css-1d391kg { background-color: #F3F7F6; }</style>", unsafe_allow_html=True)
|
83 |
+
|
84 |
+
st.title("Grief and Loss Support Bot πΏ")
|
85 |
+
st.subheader("Your compassionate companion in tough times π")
|
86 |
+
|
87 |
+
# Sidebar for Meditation and Story Generation
|
88 |
+
with st.sidebar:
|
89 |
+
st.header("π§ Guided Meditation")
|
90 |
+
if st.button("Play Meditation"):
|
91 |
+
meditation_audio = "meditation.mp3"
|
92 |
+
if not os.path.exists(meditation_audio):
|
93 |
+
tts = gTTS("Take a deep breath. Relax and let go of any tension...", lang='en')
|
94 |
+
tts.save(meditation_audio)
|
95 |
+
st.audio(meditation_audio, format="audio/mp3")
|
96 |
+
|
97 |
+
# Generating a comforting story
|
98 |
+
st.sidebar.header("π Short Comforting Story")
|
99 |
+
story_theme = st.selectbox("Choose a theme for your story:", ["courage", "healing", "hope"])
|
100 |
+
if st.sidebar.button("Generate Story"):
|
101 |
+
with st.spinner("Generating your story..."):
|
102 |
+
story = generate_story(story_theme)
|
103 |
+
st.text_area("Here's your story:", story, height=300)
|
104 |
+
|
105 |
+
|
106 |
+
|
107 |
+
# User input section
|
108 |
+
user_input = st.text_input("Share what's on your mind. I am here to listen...", placeholder="Type here...", max_chars=500, key="user_input_1")
|
109 |
+
|
110 |
+
|
111 |
+
# Initialize session state
|
112 |
+
if 'previous_responses' not in st.session_state:
|
113 |
+
st.session_state.previous_responses = []
|
114 |
+
if 'badges' not in st.session_state:
|
115 |
+
st.session_state.badges = []
|
116 |
+
|
117 |
+
|
118 |
+
# Initialize session state
|
119 |
+
if 'badges' not in st.session_state:
|
120 |
+
st.session_state.badges = []
|
121 |
+
|
122 |
+
if user_input:
|
123 |
+
with st.spinner("Analyzing your input..."):
|
124 |
+
# Get the emotion of the user input
|
125 |
+
emotion = get_emotion(user_input)
|
126 |
+
|
127 |
+
# Generate an empathetic response
|
128 |
+
response = generate_response(user_input)
|
129 |
+
|
130 |
+
# Display the bot's response
|
131 |
+
st.text_area("Bot's Response:", response, height=250)
|
132 |
+
|
133 |
+
# Assign badges based on the detected emotion
|
134 |
+
if emotion in ["joy", "optimism"]:
|
135 |
+
badge = "π Positivity Badge"
|
136 |
+
if badge not in st.session_state.badges:
|
137 |
+
st.session_state.badges.append(badge)
|
138 |
+
st.success(f"Congratulations! You've earned a {badge}!")
|
139 |
+
|
140 |
+
# Suggest activities based on emotion
|
141 |
+
st.info("π¨ Try a New Activity")
|
142 |
+
activities = ["exercise", "yoga", "journaling", "painting", "meditation", "swimming"]
|
143 |
+
selected_activity = st.selectbox("Pick an activity:", activities)
|
144 |
+
|
145 |
+
if st.button("Find Videos"):
|
146 |
+
videos = fetch_youtube_videos(selected_activity)
|
147 |
+
if videos:
|
148 |
+
for title, url in videos:
|
149 |
+
st.write(f"[{title}]({url})")
|
150 |
+
else:
|
151 |
+
st.write(f"No results found for '{selected_activity}'.")
|
152 |
+
|
153 |
+
# Crisis resources
|
154 |
+
if user_input and any(word in user_input.lower() for word in ["suicide", "help", "depressed"]):
|
155 |
+
st.warning("Please reach out to a crisis hotline for immediate support.")
|
156 |
+
st.write("[Find emergency resources here](https://www.helpguide.org/find-help.htm)")
|
157 |
+
|
158 |
+
|
159 |
+
# Generate audio response
|
160 |
+
if user_input:
|
161 |
+
tts = gTTS(response, lang='en')
|
162 |
+
audio_file = "response.mp3"
|
163 |
+
tts.save(audio_file)
|
164 |
+
st.audio(audio_file, format="audio/mp3")
|
165 |
+
|
166 |
+
# Display badgesz
|
167 |
+
if st.session_state.badges:
|
168 |
+
st.sidebar.header("π
Achievements")
|
169 |
+
for badge in st.session_state.badges:
|
170 |
+
st.sidebar.write(badge)
|