Bey007 commited on
Commit
f95f0f5
β€’
1 Parent(s): 6eeeee0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -67
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 Llama 2 model
12
- llama_model_name = "meta-llama/Llama-2-7b-hf"
13
- llama_tokenizer = AutoTokenizer.from_pretrained(llama_model_name)
14
- llama_model = AutoModelForCausalLM.from_pretrained(llama_model_name)
15
  emotion_classifier = pipeline("text-classification", model="bhadresh-savani/distilbert-base-uncased-emotion", return_all_scores=True)
16
 
 
17
  def generate_story(theme):
18
- # A detailed prompt for generating a comforting story about the selected theme
19
- 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."
20
-
21
- # Generate story using Llama 2
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
- # Create a prompt for the Llama 2 model to generate an empathetic response
43
- response_prompt = f"You are a compassionate support bot. A user has shared: '{user_input}'. Rather than sympathy, respond with empathy, understanding, and encouragement in a supportive manner."
44
-
45
- # Tokenize the prompt
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
- search = Search(f"{activity} for mental health relaxation")
72
- search_results = search.results[:3]
73
- videos = []
74
- for video in search_results:
75
- video_url = f"https://www.youtube.com/watch?v={video.video_id}"
76
- videos.append((video.title, video_url))
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
- # Display the bot's response
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: