Bey007 commited on
Commit
b9cae4e
β€’
1 Parent(s): 4ddc0d8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -23
app.py CHANGED
@@ -11,6 +11,23 @@ tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium")
11
  model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-medium")
12
  emotion_classifier = pipeline("text-classification", model="bhadresh-savani/distilbert-base-uncased-emotion", return_all_scores=True)
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  # Streamlit page configuration
15
  st.set_page_config(page_title="Grief and Loss Support Bot 🌿", page_icon="🌿", layout="centered")
16
  st.markdown("<style>.css-1d391kg { background-color: #F3F7F6; }</style>", unsafe_allow_html=True)
@@ -32,11 +49,9 @@ with st.sidebar:
32
  st.header("πŸ“– Short Comforting Story")
33
  story_theme = st.selectbox("Choose a theme for your story:", ["courage", "healing", "hope"])
34
  if st.button("Generate Story"):
35
- story_prompt = f"Tell me a comforting story about {story_theme}."
36
- input_ids = tokenizer.encode(story_prompt, return_tensors='pt')
37
- story_ids = model.generate(input_ids, max_length=150, temperature=0.8, repetition_penalty=1.1)
38
- story = tokenizer.decode(story_ids[0], skip_special_tokens=True)
39
- st.text_area("Here's your story:", story, height=200)
40
 
41
  # User input section
42
  user_input = st.text_input("Share what's on your mind...", placeholder="Type here...", max_chars=500)
@@ -46,13 +61,20 @@ if 'previous_responses' not in st.session_state:
46
  if 'badges' not in st.session_state:
47
  st.session_state.badges = []
48
 
49
- # Generate empathetic response
50
  def generate_response(user_input):
51
  input_ids = tokenizer.encode(user_input + tokenizer.eos_token, return_tensors='pt')
52
- chat_history_ids = model.generate(input_ids, max_length=150, temperature=0.7, top_k=50, repetition_penalty=1.2)
 
 
 
 
 
 
 
53
  response = tokenizer.decode(chat_history_ids[:, input_ids.shape[-1]:][0], skip_special_tokens=True)
54
  return response
55
 
 
56
  # Analyze user input for emotional tone
57
  def get_emotion(user_input):
58
  emotions = emotion_classifier(user_input)
@@ -80,22 +102,31 @@ if user_input:
80
  activities = ["exercise", "yoga", "journaling", "painting", "meditation"]
81
  selected_activity = st.selectbox("Pick an activity:", activities)
82
 
83
- # Fetch YouTube video suggestions
84
- if st.button("Find Videos"):
85
- search = Search(selected_activity)
86
- search_results = search.results[:3]
87
- if not search_results:
88
- st.write(f"No results found for '{selected_activity}'.")
89
- else:
90
- for video in search_results:
91
- st.write(f"[{video.title}]({video.watch_url})")
92
-
93
- # Crisis resources
94
- if any(word in user_input.lower() for word in ["suicide", "help", "depressed"]):
95
- st.warning("Please reach out to a crisis hotline for immediate support.")
96
- st.write("[Find emergency resources here](https://www.helpguide.org/find-help.htm)")
97
-
98
- # Generate audio response
 
 
 
 
 
 
 
 
 
99
  tts = gTTS(response, lang='en')
100
  audio_file = "response.mp3"
101
  tts.save(audio_file)
 
11
  model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-medium")
12
  emotion_classifier = pipeline("text-classification", model="bhadresh-savani/distilbert-base-uncased-emotion", return_all_scores=True)
13
 
14
+ # Function to generate a comforting story using the pretrained model
15
+ def generate_story(theme):
16
+ # Construct a prompt for generating a story based on the user's selected theme
17
+ story_prompt = f"Tell a comforting and inspiring story about {theme}. Make it detailed and heartwarming."
18
+ input_ids = tokenizer.encode(story_prompt, return_tensors='pt')
19
+ story_ids = model.generate(
20
+ input_ids,
21
+ max_length=350, # Longer story length for richer 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
  # Streamlit page configuration
32
  st.set_page_config(page_title="Grief and Loss Support Bot 🌿", page_icon="🌿", layout="centered")
33
  st.markdown("<style>.css-1d391kg { background-color: #F3F7F6; }</style>", unsafe_allow_html=True)
 
49
  st.header("πŸ“– Short Comforting Story")
50
  story_theme = st.selectbox("Choose a theme for your story:", ["courage", "healing", "hope"])
51
  if st.button("Generate Story"):
52
+ with st.spinner("Generating your story..."):
53
+ story = generate_story(story_theme)
54
+ st.text_area("Here's your story:", story, height=300)
 
 
55
 
56
  # User input section
57
  user_input = st.text_input("Share what's on your mind...", placeholder="Type here...", max_chars=500)
 
61
  if 'badges' not in st.session_state:
62
  st.session_state.badges = []
63
 
 
64
  def generate_response(user_input):
65
  input_ids = tokenizer.encode(user_input + tokenizer.eos_token, return_tensors='pt')
66
+ chat_history_ids = model.generate(
67
+ input_ids,
68
+ max_length=350, # Increase length for more detailed responses
69
+ temperature=0.85, # Adjust temperature for creative responses
70
+ top_k=50,
71
+ repetition_penalty=1.2,
72
+ num_return_sequences=1
73
+ )
74
  response = tokenizer.decode(chat_history_ids[:, input_ids.shape[-1]:][0], skip_special_tokens=True)
75
  return response
76
 
77
+
78
  # Analyze user input for emotional tone
79
  def get_emotion(user_input):
80
  emotions = emotion_classifier(user_input)
 
102
  activities = ["exercise", "yoga", "journaling", "painting", "meditation"]
103
  selected_activity = st.selectbox("Pick an activity:", activities)
104
 
105
+ def fetch_youtube_videos(activity):
106
+ search = Search(f"{activity} for mental health relaxation")
107
+ search_results = search.results[:3]
108
+ videos = []
109
+ for video in search_results:
110
+ video_url = f"https://www.youtube.com/watch?v={video.video_id}"
111
+ videos.append((video.title, video_url))
112
+ return videos
113
+
114
+ if st.button("Find Videos"):
115
+ videos = fetch_youtube_videos(selected_activity)
116
+ if not videos:
117
+ st.write(f"No results found for '{selected_activity}'.")
118
+ else:
119
+ for title, url in videos:
120
+ st.write(f"[{title}]({url})")
121
+
122
+
123
+ # Crisis resources
124
+ if any(word in user_input.lower() for word in ["suicide", "help", "depressed"]):
125
+ st.warning("Please reach out to a crisis hotline for immediate support.")
126
+ st.write("[Find emergency resources here](https://www.helpguide.org/find-help.htm)")
127
+
128
+ # Generate audio response
129
+ if user_input:
130
  tts = gTTS(response, lang='en')
131
  audio_file = "response.mp3"
132
  tts.save(audio_file)