Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -2,63 +2,30 @@ 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
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
emotion_classifier = pipeline("text-classification", model="bhadresh-savani/distilbert-base-uncased-emotion", return_all_scores=True)
|
16 |
|
|
|
17 |
def generate_story(theme):
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
input_ids = llama_tokenizer.encode(story_prompt, return_tensors='pt')
|
23 |
-
|
24 |
-
story_ids = llama_model.generate(
|
25 |
-
input_ids,
|
26 |
-
max_length=600, # Generate longer stories
|
27 |
-
temperature=0.7, # Balanced creativity
|
28 |
-
top_p=0.9,
|
29 |
-
repetition_penalty=1.1,
|
30 |
-
num_return_sequences=1
|
31 |
-
)
|
32 |
-
|
33 |
-
# Decode the generated text
|
34 |
-
story = llama_tokenizer.decode(story_ids[0], skip_special_tokens=True)
|
35 |
-
return story
|
36 |
-
|
37 |
-
|
38 |
|
39 |
# Function to generate an empathetic response
|
40 |
-
# Function to generate an empathetic response using Llama 2
|
41 |
def generate_response(user_input):
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
input_ids = llama_tokenizer.encode(response_prompt, return_tensors='pt')
|
47 |
-
|
48 |
-
# Generate the response using Llama 2
|
49 |
-
response_ids = llama_model.generate(
|
50 |
-
input_ids,
|
51 |
-
max_length=300, # Generate a longer response
|
52 |
-
temperature=0.7, # Adjust temperature for coherent and empathetic responses
|
53 |
-
top_p=0.9, # Use top-p sampling for balanced creativity
|
54 |
-
repetition_penalty=1.1, # Avoid repetitive responses
|
55 |
-
num_return_sequences=1
|
56 |
-
)
|
57 |
-
|
58 |
-
# Decode the generated text
|
59 |
-
response = llama_tokenizer.decode(response_ids[:, input_ids.shape[-1]:][0], skip_special_tokens=True)
|
60 |
-
return response
|
61 |
-
|
62 |
|
63 |
# Analyze user input for emotional tone
|
64 |
def get_emotion(user_input):
|
@@ -68,13 +35,12 @@ def get_emotion(user_input):
|
|
68 |
|
69 |
# Function to fetch YouTube videos
|
70 |
def fetch_youtube_videos(activity):
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
return videos
|
78 |
|
79 |
# Streamlit page configuration
|
80 |
st.set_page_config(page_title="Grief and Loss Support Bot πΏ", page_icon="πΏ", layout="centered")
|
@@ -93,7 +59,6 @@ with st.sidebar:
|
|
93 |
tts.save(meditation_audio)
|
94 |
st.audio(meditation_audio, format="audio/mp3")
|
95 |
|
96 |
-
# Generating a comforting story
|
97 |
st.sidebar.header("π Short Comforting Story")
|
98 |
story_theme = st.selectbox("Choose a theme for your story:", ["courage", "healing", "hope"])
|
99 |
if st.sidebar.button("Generate Story"):
|
@@ -101,35 +66,29 @@ if st.sidebar.button("Generate Story"):
|
|
101 |
story = generate_story(story_theme)
|
102 |
st.text_area("Here's your story:", story, height=300)
|
103 |
|
104 |
-
|
105 |
-
|
106 |
# User input section
|
107 |
user_input = st.text_input("Share what's on your mind...", placeholder="Type here...", max_chars=500)
|
108 |
|
109 |
# Initialize session state
|
110 |
-
if 'previous_responses' not in st.session_state:
|
111 |
-
st.session_state.previous_responses = []
|
112 |
if 'badges' not in st.session_state:
|
113 |
st.session_state.badges = []
|
114 |
|
115 |
if user_input:
|
116 |
with st.spinner("Thinking..."):
|
|
|
117 |
response = generate_response(user_input)
|
|
|
118 |
|
119 |
-
#
|
120 |
-
st.text_area("Bot's Response:", response, height=250)
|
121 |
-
|
122 |
-
|
123 |
-
# Assign motivational badges
|
124 |
if emotion in ["joy", "optimism"]:
|
125 |
badge = "π Positivity Badge"
|
126 |
if badge not in st.session_state.badges:
|
127 |
st.session_state.badges.append(badge)
|
128 |
st.success(f"Congratulations! You've earned a {badge}!")
|
129 |
-
|
130 |
# Suggest activities
|
131 |
st.info("π¨ Try a New Activity")
|
132 |
-
activities = ["exercise", "yoga", "journaling", "painting", "meditation"]
|
133 |
selected_activity = st.selectbox("Pick an activity:", activities)
|
134 |
|
135 |
if st.button("Find Videos"):
|
@@ -145,14 +104,14 @@ if any(word in user_input.lower() for word in ["suicide", "help", "depressed"]):
|
|
145 |
st.warning("Please reach out to a crisis hotline for immediate support.")
|
146 |
st.write("[Find emergency resources here](https://www.helpguide.org/find-help.htm)")
|
147 |
|
148 |
-
# Generate audio response
|
149 |
if user_input:
|
150 |
tts = gTTS(response, lang='en')
|
151 |
audio_file = "response.mp3"
|
152 |
tts.save(audio_file)
|
153 |
st.audio(audio_file, format="audio/mp3")
|
154 |
|
155 |
-
# Display badges
|
156 |
if st.session_state.badges:
|
157 |
st.sidebar.header("π
Achievements")
|
158 |
for badge in st.session_state.badges:
|
|
|
2 |
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
3 |
from gtts import gTTS
|
4 |
from pytube import Search
|
|
|
5 |
import os
|
6 |
|
7 |
# Load pretrained models
|
8 |
tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium")
|
9 |
model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-medium")
|
10 |
+
# Load GPT-2 model and tokenizer for story generation
|
11 |
+
gpt2_tokenizer = AutoTokenizer.from_pretrained("gpt2-medium")
|
12 |
+
gpt2_model = AutoModelForCausalLM.from_pretrained("gpt2-medium")
|
13 |
+
|
14 |
emotion_classifier = pipeline("text-classification", model="bhadresh-savani/distilbert-base-uncased-emotion", return_all_scores=True)
|
15 |
|
16 |
+
# Function to generate a comforting story using GPT-2
|
17 |
def generate_story(theme):
|
18 |
+
story_prompt = f"Write a comforting, detailed, and heartwarming story about {theme}. Include a character facing challenges and finding hope."
|
19 |
+
input_ids = gpt2_tokenizer.encode(story_prompt, return_tensors='pt')
|
20 |
+
story_ids = gpt2_model.generate(input_ids, max_length=500, temperature=0.8, top_p=0.9, repetition_penalty=1.2)
|
21 |
+
return gpt2_tokenizer.decode(story_ids[0], skip_special_tokens=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
22 |
|
23 |
# Function to generate an empathetic response
|
|
|
24 |
def generate_response(user_input):
|
25 |
+
response_prompt = f"You are a compassionate support bot. A user has shared: '{user_input}'. Respond with empathy and encouragement."
|
26 |
+
input_ids = tokenizer.encode(response_prompt, return_tensors='pt')
|
27 |
+
chat_history_ids = model.generate(input_ids, max_length=300, temperature=0.85, top_k=50, repetition_penalty=1.2)
|
28 |
+
return tokenizer.decode(chat_history_ids[:, input_ids.shape[-1]:][0], skip_special_tokens=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
|
30 |
# Analyze user input for emotional tone
|
31 |
def get_emotion(user_input):
|
|
|
35 |
|
36 |
# Function to fetch YouTube videos
|
37 |
def fetch_youtube_videos(activity):
|
38 |
+
try:
|
39 |
+
search = Search(f"{activity} for mental health relaxation")
|
40 |
+
videos = [(video.title, f"https://www.youtube.com/watch?v={video.video_id}") for video in search.results[:3]]
|
41 |
+
return videos
|
42 |
+
except Exception:
|
43 |
+
return []
|
|
|
44 |
|
45 |
# Streamlit page configuration
|
46 |
st.set_page_config(page_title="Grief and Loss Support Bot πΏ", page_icon="πΏ", layout="centered")
|
|
|
59 |
tts.save(meditation_audio)
|
60 |
st.audio(meditation_audio, format="audio/mp3")
|
61 |
|
|
|
62 |
st.sidebar.header("π Short Comforting Story")
|
63 |
story_theme = st.selectbox("Choose a theme for your story:", ["courage", "healing", "hope"])
|
64 |
if st.sidebar.button("Generate Story"):
|
|
|
66 |
story = generate_story(story_theme)
|
67 |
st.text_area("Here's your story:", story, height=300)
|
68 |
|
|
|
|
|
69 |
# User input section
|
70 |
user_input = st.text_input("Share what's on your mind...", placeholder="Type here...", max_chars=500)
|
71 |
|
72 |
# Initialize session state
|
|
|
|
|
73 |
if 'badges' not in st.session_state:
|
74 |
st.session_state.badges = []
|
75 |
|
76 |
if user_input:
|
77 |
with st.spinner("Thinking..."):
|
78 |
+
emotion = get_emotion(user_input)
|
79 |
response = generate_response(user_input)
|
80 |
+
st.text_area("Bot's Response:", response, height=250)
|
81 |
|
82 |
+
# Assign badges based on emotional analysis
|
|
|
|
|
|
|
|
|
83 |
if emotion in ["joy", "optimism"]:
|
84 |
badge = "π Positivity Badge"
|
85 |
if badge not in st.session_state.badges:
|
86 |
st.session_state.badges.append(badge)
|
87 |
st.success(f"Congratulations! You've earned a {badge}!")
|
88 |
+
|
89 |
# Suggest activities
|
90 |
st.info("π¨ Try a New Activity")
|
91 |
+
activities = ["exercise", "yoga", "journaling", "painting", "meditation", "swimming"]
|
92 |
selected_activity = st.selectbox("Pick an activity:", activities)
|
93 |
|
94 |
if st.button("Find Videos"):
|
|
|
104 |
st.warning("Please reach out to a crisis hotline for immediate support.")
|
105 |
st.write("[Find emergency resources here](https://www.helpguide.org/find-help.htm)")
|
106 |
|
107 |
+
# Generate and play audio response
|
108 |
if user_input:
|
109 |
tts = gTTS(response, lang='en')
|
110 |
audio_file = "response.mp3"
|
111 |
tts.save(audio_file)
|
112 |
st.audio(audio_file, format="audio/mp3")
|
113 |
|
114 |
+
# Display earned badges
|
115 |
if st.session_state.badges:
|
116 |
st.sidebar.header("π
Achievements")
|
117 |
for badge in st.session_state.badges:
|