Bey007 commited on
Commit
83c726d
β€’
1 Parent(s): f95f0f5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -19
app.py CHANGED
@@ -2,6 +2,7 @@ import streamlit as st
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
@@ -15,17 +16,41 @@ emotion_classifier = pipeline("text-classification", model="bhadresh-savani/dist
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,12 +60,13 @@ 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,6 +85,7 @@ with st.sidebar:
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,29 +93,35 @@ 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,15 +137,15 @@ if any(word in user_input.lower() for word in ["suicide", "help", "depressed"]):
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:
118
- st.sidebar.write(badge)
 
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
 
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
 
39
  # Function to generate an empathetic response
40
  def generate_response(user_input):
41
  response_prompt = f"You are a compassionate support bot. A user has shared: '{user_input}'. Respond with empathy and encouragement."
42
  input_ids = tokenizer.encode(response_prompt, return_tensors='pt')
43
+ chat_history_ids = model.generate(
44
+ input_ids,
45
+ max_length=300,
46
+ temperature=0.85,
47
+ top_k=50,
48
+ repetition_penalty=1.2,
49
+ num_return_sequences=1
50
+ )
51
+ response = tokenizer.decode(chat_history_ids[:, input_ids.shape[-1]:][0], skip_special_tokens=True)
52
+ return response
53
+
54
 
55
  # Analyze user input for emotional tone
56
  def get_emotion(user_input):
 
60
 
61
  # Function to fetch YouTube videos
62
  def fetch_youtube_videos(activity):
63
+ search = Search(f"{activity} for mental health relaxation")
64
+ search_results = search.results[:3]
65
+ videos = []
66
+ for video in search_results:
67
+ video_url = f"https://www.youtube.com/watch?v={video.video_id}"
68
+ videos.append((video.title, video_url))
69
+ return videos
70
 
71
  # Streamlit page configuration
72
  st.set_page_config(page_title="Grief and Loss Support Bot 🌿", page_icon="🌿", layout="centered")
 
85
  tts.save(meditation_audio)
86
  st.audio(meditation_audio, format="audio/mp3")
87
 
88
+ # Generating a comforting story
89
  st.sidebar.header("πŸ“– Short Comforting Story")
90
  story_theme = st.selectbox("Choose a theme for your story:", ["courage", "healing", "hope"])
91
  if st.sidebar.button("Generate Story"):
 
93
  story = generate_story(story_theme)
94
  st.text_area("Here's your story:", story, height=300)
95
 
96
+
97
+
98
  # User input section
99
  user_input = st.text_input("Share what's on your mind...", placeholder="Type here...", max_chars=500)
100
 
101
  # Initialize session state
102
+ if 'previous_responses' not in st.session_state:
103
+ st.session_state.previous_responses = []
104
  if 'badges' not in st.session_state:
105
  st.session_state.badges = []
106
 
107
  if user_input:
108
  with st.spinner("Thinking..."):
 
109
  response = generate_response(user_input)
 
110
 
111
+ # Display the bot's response
112
+ st.text_area("Bot's Response:", response, height=250)
113
+
114
+
115
+ # Assign motivational badges
116
  if emotion in ["joy", "optimism"]:
117
  badge = "🌟 Positivity Badge"
118
  if badge not in st.session_state.badges:
119
  st.session_state.badges.append(badge)
120
  st.success(f"Congratulations! You've earned a {badge}!")
121
+
122
  # Suggest activities
123
  st.info("🎨 Try a New Activity")
124
+ activities = ["exercise", "yoga", "journaling", "painting", "meditation", "Swimming"]
125
  selected_activity = st.selectbox("Pick an activity:", activities)
126
 
127
  if st.button("Find Videos"):
 
137
  st.warning("Please reach out to a crisis hotline for immediate support.")
138
  st.write("[Find emergency resources here](https://www.helpguide.org/find-help.htm)")
139
 
140
+ # Generate audio response
141
  if user_input:
142
  tts = gTTS(response, lang='en')
143
  audio_file = "response.mp3"
144
  tts.save(audio_file)
145
  st.audio(audio_file, format="audio/mp3")
146
 
147
+ # Display badgesz
148
  if st.session_state.badges:
149
  st.sidebar.header("πŸ… Achievements")
150
  for badge in st.session_state.badges:
151
+ st.sidebar.write(badge)