Bey007 commited on
Commit
9bdc1f1
β€’
1 Parent(s): b0faac5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -51
app.py CHANGED
@@ -4,7 +4,6 @@ from gtts import gTTS
4
  from pytube import Search
5
  import random
6
  import os
7
- import time
8
 
9
  # Load pretrained models
10
  tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium")
@@ -13,31 +12,57 @@ emotion_classifier = pipeline("text-classification", model="bhadresh-savani/dist
13
 
14
  # Function to generate a comforting story using the pretrained model
15
  def generate_story(theme):
16
- # A more detailed prompt for generating a story about courage
17
- story_prompt = f"Tell me a detailed, comforting, and heartwarming story about {theme}. The story should include a character facing a tough challenge, showing immense courage, and ultimately overcoming it with a positive resolution. Include specific moments of struggle and inspiration."
18
  input_ids = tokenizer.encode(story_prompt, return_tensors='pt')
19
  story_ids = model.generate(
20
  input_ids,
21
- max_length=500, # Increase length for more detailed content
22
- temperature=0.9, # Encourage creative storytelling
23
  repetition_penalty=1.1,
24
  num_return_sequences=1
25
  )
26
- # Decode the generated story text
27
  story = tokenizer.decode(story_ids[0], skip_special_tokens=True)
28
  return story
29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
 
 
 
 
 
 
 
 
 
31
 
32
  # Streamlit page configuration
33
  st.set_page_config(page_title="Grief and Loss Support Bot 🌿", page_icon="🌿", layout="centered")
34
  st.markdown("<style>.css-1d391kg { background-color: #F3F7F6; }</style>", unsafe_allow_html=True)
35
 
36
- # Title and welcome text
37
  st.title("Grief and Loss Support Bot 🌿")
38
  st.subheader("Your compassionate companion in tough times πŸ’š")
39
 
40
- # Sidebar for additional features
41
  with st.sidebar:
42
  st.header("🧘 Guided Meditation")
43
  if st.button("Play Meditation"):
@@ -46,7 +71,7 @@ with st.sidebar:
46
  tts = gTTS("Take a deep breath. Relax and let go of any tension...", lang='en')
47
  tts.save(meditation_audio)
48
  st.audio(meditation_audio, format="audio/mp3")
49
-
50
  st.header("πŸ“– Short Comforting Story")
51
  story_theme = st.selectbox("Choose a theme for your story:", ["courage", "healing", "hope"])
52
  if st.button("Generate Story"):
@@ -57,37 +82,17 @@ with st.sidebar:
57
  # User input section
58
  user_input = st.text_input("Share what's on your mind...", placeholder="Type here...", max_chars=500)
59
 
 
60
  if 'previous_responses' not in st.session_state:
61
  st.session_state.previous_responses = []
62
  if 'badges' not in st.session_state:
63
  st.session_state.badges = []
64
 
65
- def generate_response(user_input):
66
- input_ids = tokenizer.encode(user_input + tokenizer.eos_token, return_tensors='pt')
67
- chat_history_ids = model.generate(
68
- input_ids,
69
- max_length=350, # Increase length for more detailed responses
70
- temperature=0.85, # Adjust temperature for creative responses
71
- top_k=50,
72
- repetition_penalty=1.2,
73
- num_return_sequences=1
74
- )
75
- response = tokenizer.decode(chat_history_ids[:, input_ids.shape[-1]:][0], skip_special_tokens=True)
76
- return response
77
-
78
-
79
- # Analyze user input for emotional tone
80
- def get_emotion(user_input):
81
- emotions = emotion_classifier(user_input)
82
- emotions_sorted = sorted(emotions[0], key=lambda x: x['score'], reverse=True)
83
- return emotions_sorted[0]['label']
84
-
85
- # Provide a response if user input is provided
86
  if user_input:
87
  emotion = get_emotion(user_input)
88
- response = generate_response(user_input)
 
89
 
90
- # Display the bot's response
91
  st.session_state.previous_responses.append(response)
92
  st.text_area("Bot's Response:", response, height=250)
93
 
@@ -98,28 +103,18 @@ if user_input:
98
  st.session_state.badges.append(badge)
99
  st.success(f"Congratulations! You've earned a {badge}!")
100
 
101
- # Suggest coping activities
102
  st.info("🎨 Try a New Activity")
103
  activities = ["exercise", "yoga", "journaling", "painting", "meditation"]
104
  selected_activity = st.selectbox("Pick an activity:", activities)
105
-
106
- def fetch_youtube_videos(activity):
107
- search = Search(f"{activity} for mental health relaxation")
108
- search_results = search.results[:3]
109
- videos = []
110
- for video in search_results:
111
- video_url = f"https://www.youtube.com/watch?v={video.video_id}"
112
- videos.append((video.title, video_url))
113
- return videos
114
-
115
- if st.button("Find Videos"):
116
- videos = fetch_youtube_videos(selected_activity)
117
- if not videos:
118
- st.write(f"No results found for '{selected_activity}'.")
119
- else:
120
- for title, url in videos:
121
- st.write(f"[{title}]({url})")
122
 
 
 
 
 
 
 
 
123
 
124
  # Crisis resources
125
  if any(word in user_input.lower() for word in ["suicide", "help", "depressed"]):
@@ -133,7 +128,7 @@ if user_input:
133
  tts.save(audio_file)
134
  st.audio(audio_file, format="audio/mp3")
135
 
136
- # Display badges and achievements
137
  if st.session_state.badges:
138
  st.sidebar.header("πŸ… Achievements")
139
  for badge in st.session_state.badges:
 
4
  from pytube import Search
5
  import random
6
  import os
 
7
 
8
  # Load pretrained models
9
  tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium")
 
12
 
13
  # Function to generate a comforting story using the pretrained model
14
  def generate_story(theme):
15
+ story_prompt = f"Tell a detailed, comforting, and heartwarming story about {theme}. Include a character facing a tough challenge, showing courage, and overcoming it with a positive resolution."
 
16
  input_ids = tokenizer.encode(story_prompt, return_tensors='pt')
17
  story_ids = model.generate(
18
  input_ids,
19
+ max_length=500,
20
+ temperature=0.9,
21
  repetition_penalty=1.1,
22
  num_return_sequences=1
23
  )
 
24
  story = tokenizer.decode(story_ids[0], skip_special_tokens=True)
25
  return story
26
 
27
+ # Function to generate an empathetic response
28
+ def generate_response(user_input):
29
+ response_prompt = f"You are a compassionate support bot. A user has shared: '{user_input}'. Respond with empathy and encouragement."
30
+ input_ids = tokenizer.encode(response_prompt, return_tensors='pt')
31
+ chat_history_ids = model.generate(
32
+ input_ids,
33
+ max_length=300,
34
+ temperature=0.85,
35
+ top_k=50,
36
+ repetition_penalty=1.2,
37
+ num_return_sequences=1
38
+ )
39
+ response = tokenizer.decode(chat_history_ids[:, input_ids.shape[-1]:][0], skip_special_tokens=True)
40
+ return response
41
+
42
+ # Analyze user input for emotional tone
43
+ def get_emotion(user_input):
44
+ emotions = emotion_classifier(user_input)
45
+ emotions_sorted = sorted(emotions[0], key=lambda x: x['score'], reverse=True)
46
+ return emotions_sorted[0]['label']
47
 
48
+ # Function to fetch YouTube videos
49
+ def fetch_youtube_videos(activity):
50
+ search = Search(f"{activity} for mental health relaxation")
51
+ search_results = search.results[:3]
52
+ videos = []
53
+ for video in search_results:
54
+ video_url = f"https://www.youtube.com/watch?v={video.video_id}"
55
+ videos.append((video.title, video_url))
56
+ return videos
57
 
58
  # Streamlit page configuration
59
  st.set_page_config(page_title="Grief and Loss Support Bot 🌿", page_icon="🌿", layout="centered")
60
  st.markdown("<style>.css-1d391kg { background-color: #F3F7F6; }</style>", unsafe_allow_html=True)
61
 
 
62
  st.title("Grief and Loss Support Bot 🌿")
63
  st.subheader("Your compassionate companion in tough times πŸ’š")
64
 
65
+ # Sidebar for Meditation and Story Generation
66
  with st.sidebar:
67
  st.header("🧘 Guided Meditation")
68
  if st.button("Play Meditation"):
 
71
  tts = gTTS("Take a deep breath. Relax and let go of any tension...", lang='en')
72
  tts.save(meditation_audio)
73
  st.audio(meditation_audio, format="audio/mp3")
74
+
75
  st.header("πŸ“– Short Comforting Story")
76
  story_theme = st.selectbox("Choose a theme for your story:", ["courage", "healing", "hope"])
77
  if st.button("Generate Story"):
 
82
  # User input section
83
  user_input = st.text_input("Share what's on your mind...", placeholder="Type here...", max_chars=500)
84
 
85
+ # Initialize session state
86
  if 'previous_responses' not in st.session_state:
87
  st.session_state.previous_responses = []
88
  if 'badges' not in st.session_state:
89
  st.session_state.badges = []
90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  if user_input:
92
  emotion = get_emotion(user_input)
93
+ with st.spinner("Thinking..."):
94
+ response = generate_response(user_input)
95
 
 
96
  st.session_state.previous_responses.append(response)
97
  st.text_area("Bot's Response:", response, height=250)
98
 
 
103
  st.session_state.badges.append(badge)
104
  st.success(f"Congratulations! You've earned a {badge}!")
105
 
106
+ # Suggest activities
107
  st.info("🎨 Try a New Activity")
108
  activities = ["exercise", "yoga", "journaling", "painting", "meditation"]
109
  selected_activity = st.selectbox("Pick an activity:", activities)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
 
111
+ if st.button("Find Videos"):
112
+ videos = fetch_youtube_videos(selected_activity)
113
+ if videos:
114
+ for title, url in videos:
115
+ st.write(f"[{title}]({url})")
116
+ else:
117
+ st.write(f"No results found for '{selected_activity}'.")
118
 
119
  # Crisis resources
120
  if any(word in user_input.lower() for word in ["suicide", "help", "depressed"]):
 
128
  tts.save(audio_file)
129
  st.audio(audio_file, format="audio/mp3")
130
 
131
+ # Display badges
132
  if st.session_state.badges:
133
  st.sidebar.header("πŸ… Achievements")
134
  for badge in st.session_state.badges: