Bey007 commited on
Commit
3dfc83c
·
verified ·
1 Parent(s): 629bb99

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -62
app.py CHANGED
@@ -1,13 +1,16 @@
1
  import streamlit as st
2
- from transformers import GPT2LMHeadModel, GPT2Tokenizer
3
  from gtts import gTTS
4
- import random
 
5
 
6
- # Load GPT-2 model and tokenizer from Hugging Face
7
- tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
8
- model = GPT2LMHeadModel.from_pretrained("gpt2")
9
 
10
- # Set up Streamlit page configuration
 
 
 
11
  st.set_page_config(page_title="Grief and Loss Support Bot", page_icon="🌿", layout="centered")
12
  st.markdown("""
13
  <style>
@@ -20,70 +23,43 @@ st.markdown("""
20
  </style>
21
  """, unsafe_allow_html=True)
22
 
23
- # Title and introduction to the bot
24
  st.title("Grief and Loss Support Bot 🌿")
25
  st.subheader("Your compassionate companion in tough times 💚")
26
 
27
- # User input
28
  user_input = st.text_input("Share what's on your mind...", placeholder="Type here...", max_chars=500)
29
 
30
- # Store previous responses to check for repetition
31
- if 'previous_responses' not in st.session_state:
32
- st.session_state.previous_responses = []
33
-
34
- # Function to generate a more empathetic and focused response
35
- def generate_response(user_input):
36
- # Empathy responses categorized by emotion
37
- emotion_responses = {
38
- "sadness": [
39
- "I'm truly sorry you're going through this difficult time. Grief and sadness can weigh heavy, but you're not alone in your feelings. It's okay to take things one step at a time, and together we can explore ways to help you cope and find peace.",
40
- "I can only imagine how overwhelming things must feel right now. When we’re grieving or under stress, it can be hard to see the light at the end of the tunnel, but you don’t have to carry the burden alone. I’m here for you.",
41
- "I'm really sorry you're feeling this way. It’s completely understandable to feel sad, and it's okay to let those emotions flow. Grief can be exhausting, and it’s normal to need time to process everything."
42
- ],
43
- "anger": [
44
- "It sounds like you're feeling really frustrated, and that’s totally valid. Sometimes, our anger is a way of protecting us from pain or stress. If you’d like, I’m here to help you work through these feelings and find ways to release some of that tension.",
45
- "I understand that things may feel frustrating and intense right now. Anger can be a difficult emotion to manage, but it’s completely natural. Sometimes, taking a step back and focusing on deep breathing or a calming activity can help.",
46
- "It’s okay to feel angry – sometimes it’s our body’s way of telling us that something needs to change or that we need to release pent-up stress. You’re not alone in this, and there are healthy ways we can work through it together."
47
- ]
48
- }
49
-
50
- # Tailored coping suggestions based on the user's input
51
- activity_suggestions = {
52
- "journaling": "Journaling can be a helpful way to process your thoughts and emotions. Writing down everything you’re feeling can allow you to see things more clearly and release some of the weight you’re carrying.",
53
- "deep breathing": "Deep breathing can help calm your mind and ease tension. Try taking a few slow, deep breaths, focusing on each inhale and exhale. It can help you feel grounded and in control of your emotions.",
54
- "exercise": "Physical activity is a wonderful way to release built-up tension and boost your mood. Taking a walk in nature or doing some light stretching can help ground you in the present moment and relieve stress.",
55
- "talking to someone": "Sometimes, sharing how you’re feeling with someone you trust can relieve some of the burden. Talking through your emotions with a friend or loved one can provide comfort and help you feel supported.",
56
- "art": "Art can be a therapeutic outlet for your emotions. Creating something with your hands, like drawing or painting, allows you to express what might be too difficult to put into words."
57
- }
58
-
59
- # Determine emotion based on keywords in user input
60
- if "angry" in user_input.lower() or "frustrated" in user_input.lower():
61
- emotion = "anger"
62
- activity = "deep breathing"
63
- response = random.choice(emotion_responses[emotion])
64
- activity_suggestion = activity_suggestions[activity]
65
- else:
66
- emotion = "sadness"
67
- activity = random.choice(list(activity_suggestions.keys()))
68
- response = random.choice(emotion_responses[emotion])
69
- activity_suggestion = activity_suggestions[activity]
70
-
71
- # Add the tailored coping activity suggestion to the response
72
- response += f"\n\nHere's something you could try to help cope with how you're feeling:\n{activity_suggestion}"
73
-
74
- return response
75
-
76
- # Check if the user has typed something
77
  if user_input:
78
- # Generate the empathetic response
79
- response = generate_response(user_input)
80
-
81
- # Store and show the new response
82
- st.session_state.previous_responses.append(response)
83
- st.text_area("Bot's Response:", response, height=250)
 
84
 
85
- # Text-to-speech output (optional)
86
  tts = gTTS(response, lang='en')
87
  audio_file = "response.mp3"
88
  tts.save(audio_file)
89
  st.audio(audio_file, format="audio/mp3")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ from transformers import pipeline
3
  from gtts import gTTS
4
+ from pytube import Search
5
+ import os
6
 
7
+ # Initialize conversational model for empathetic dialogue
8
+ conversational_bot = pipeline("text-generation", model="microsoft/DialoGPT-medium")
 
9
 
10
+ # Initialize sentiment analysis
11
+ sentiment_analysis = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
12
+
13
+ # Set up Streamlit page
14
  st.set_page_config(page_title="Grief and Loss Support Bot", page_icon="🌿", layout="centered")
15
  st.markdown("""
16
  <style>
 
23
  </style>
24
  """, unsafe_allow_html=True)
25
 
26
+ # Title
27
  st.title("Grief and Loss Support Bot 🌿")
28
  st.subheader("Your compassionate companion in tough times 💚")
29
 
30
+ # Get user input
31
  user_input = st.text_input("Share what's on your mind...", placeholder="Type here...", max_chars=500)
32
 
33
+ # Check if user has entered text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  if user_input:
35
+ # Run sentiment analysis to check for distress
36
+ sentiment = sentiment_analysis(user_input)[0]
37
+ # Generate empathetic response
38
+ response = conversational_bot(user_input, max_length=250, temperature=0.95, top_k=60)[0]['generated_text']
39
+
40
+ # Display response
41
+ st.text_area("Bot's Response:", response, height=200)
42
 
43
+ # Text-to-speech output
44
  tts = gTTS(response, lang='en')
45
  audio_file = "response.mp3"
46
  tts.save(audio_file)
47
  st.audio(audio_file, format="audio/mp3")
48
+
49
+ # Suggest a productive activity based on detected keywords
50
+ if any(keyword in user_input.lower() for keyword in ["lonely", "lost", "sad", "overwhelmed"]):
51
+ st.info("Here's a suggestion to help you cope:")
52
+ activities = ["journaling", "yoga", "painting"]
53
+ selected_activity = st.selectbox("Choose an activity you'd like to try:", activities)
54
+
55
+ # Search YouTube for videos related to the selected activity
56
+ search = Search(selected_activity)
57
+ search_results = search.results[:3] # limit results to 3 videos
58
+ for video in search_results:
59
+ st.write(f"[{video.title}]({video.watch_url})")
60
+
61
+ # Crisis resources
62
+ crisis_keywords = ["help", "suicide", "depressed", "emergency", "hurt", "lost"]
63
+ if any(keyword in user_input.lower() for keyword in crisis_keywords):
64
+ st.warning("It seems like you might be in distress. Please reach out to a crisis hotline or a trusted individual.")
65
+ st.write("[Find emergency resources here](https://www.helpguide.org/find-help.htm)")