Bey007 commited on
Commit
d67bb32
1 Parent(s): b9dc3fd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -74
app.py CHANGED
@@ -1,10 +1,8 @@
1
  import streamlit as st
2
  from transformers import AutoModelForCausalLM, AutoTokenizer
3
  from gtts import gTTS
4
- import torch
5
- import tempfile
6
- import random
7
  from pytube import Search
 
8
 
9
  # Load DialoGPT model and tokenizer from Hugging Face
10
  tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium")
@@ -27,85 +25,77 @@ st.markdown("""
27
  st.title("Grief and Loss Support Bot 🌿")
28
  st.subheader("Your compassionate companion in tough times 💚")
29
 
30
- # Initialize session state for chat history
31
- if 'chat_history_ids' not in st.session_state:
32
- st.session_state.chat_history_ids = None
33
- if 'bot_messages' not in st.session_state:
34
- st.session_state.bot_messages = []
35
-
36
  # User input
37
  user_input = st.text_input("Share what's on your mind...", placeholder="Type here...", max_chars=500)
38
 
39
- # Function to generate a response using DialoGPT
40
- def generate_response(user_input):
41
- if not user_input:
42
- return "I'm here whenever you're ready to talk."
43
 
44
- # Encode the user input and append to chat history
 
 
45
  new_user_input_ids = tokenizer.encode(user_input + tokenizer.eos_token, return_tensors='pt')
46
- bot_input_ids = new_user_input_ids if st.session_state.chat_history_ids is None else torch.cat([st.session_state.chat_history_ids, new_user_input_ids], dim=-1)
47
-
48
- # Generate the bot's response
49
- chat_history_ids = model.generate(
50
- bot_input_ids,
51
- max_length=200,
52
- pad_token_id=tokenizer.eos_token_id,
53
- temperature=0.7,
54
- top_k=50,
55
- repetition_penalty=1.2
56
- )
57
-
58
- # Update the chat history
59
- st.session_state.chat_history_ids = chat_history_ids
60
- bot_response = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
61
-
62
- bot_response += "\n\nYou're doing your best, and that’s all anyone can ask for. Please take care of yourself and know that it’s okay to take a step back when things feel overwhelming."
63
-
64
- return bot_response
65
-
66
- # Generate and display bot response if there's user input
67
- if user_input:
68
- response = generate_response(user_input)
69
- st.session_state.bot_messages.append(response)
70
-
71
- # Display bot's response
72
- for message in st.session_state.bot_messages:
73
- st.text_area("Bot's Response:", message, height=150)
74
-
75
- # Text-to-speech output
76
- with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
77
- tts = gTTS(response, lang='en')
78
- tts.save(tmp_file.name)
79
- st.audio(tmp_file.name, format="audio/mp3")
80
-
81
- # Activity suggestion based on detected keywords
82
- if any(keyword in user_input.lower() for keyword in ["lonely", "lost", "sad", "overwhelmed", "academic", "exam"]):
83
  st.info("Here's a suggestion to help you cope:")
84
 
85
- # Activities based on user mood and needs
86
- activities = {
87
- "journaling": "Express your feelings in writing. Journaling is a great way to process emotions.",
88
- "yoga": "Yoga helps you relax and refocus. Try some deep breathing exercises or light stretching.",
89
- "painting": "Creative expression through painting or drawing can be soothing and help you release pent-up emotions.",
90
- "meditation": "Take a moment to calm your mind. Guided meditation can help reduce stress and anxiety.",
91
- "exercise": "Physical activity can lift your mood. Even a short walk in nature can make a big difference."
92
- }
93
-
94
- # Randomly suggest an activity
95
- activity = random.choice(list(activities.keys()))
96
- st.write(f"How about {activity}? {activities[activity]}")
97
-
98
- # Search YouTube for related videos using pytube
99
- search = Search(activity)
100
- search_results = search.results[:3] # Limit results to 3 videos
101
- if search_results:
102
- for video in search_results:
103
- st.write(f"[{video.title}]({video.watch_url})")
104
- else:
105
- st.write("Sorry, I couldn't find any relevant videos at the moment.")
106
-
107
- # Crisis resources for distress signals
108
  crisis_keywords = ["help", "suicide", "depressed", "emergency", "hurt", "lost"]
109
  if any(keyword in user_input.lower() for keyword in crisis_keywords):
110
  st.warning("It seems like you might be in distress. Please reach out to a crisis hotline or a trusted individual.")
111
  st.write("[Find emergency resources here](https://www.helpguide.org/find-help.htm)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  from transformers import AutoModelForCausalLM, AutoTokenizer
3
  from gtts import gTTS
 
 
 
4
  from pytube import Search
5
+ import random
6
 
7
  # Load DialoGPT model and tokenizer from Hugging Face
8
  tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium")
 
25
  st.title("Grief and Loss Support Bot 🌿")
26
  st.subheader("Your compassionate companion in tough times 💚")
27
 
 
 
 
 
 
 
28
  # User input
29
  user_input = st.text_input("Share what's on your mind...", placeholder="Type here...", max_chars=500)
30
 
31
+ # Store previous responses to check for repetition
32
+ if 'previous_responses' not in st.session_state:
33
+ st.session_state.previous_responses = []
 
34
 
35
+ # Function to generate a more empathetic and focused response using DialoGPT
36
+ def generate_response(user_input):
37
+ # Encode the input text and generate a response
38
  new_user_input_ids = tokenizer.encode(user_input + tokenizer.eos_token, return_tensors='pt')
39
+ bot_input_ids = new_user_input_ids
40
+ chat_history_ids = model.generate(bot_input_ids, max_length=200, pad_token_id=tokenizer.eos_token_id, temperature=0.7, top_k=50, repetition_penalty=1.2)
41
+
42
+ # Decode the response to text
43
+ chat_history_ids = chat_history_ids[:, bot_input_ids.shape[-1]:] # remove the input from the response
44
+ bot_output = tokenizer.decode(chat_history_ids[0], skip_special_tokens=True)
45
+
46
+ # Build a more empathetic and thoughtful response
47
+ response = f"I’m really sorry you're feeling like this. It’s completely normal to feel overwhelmed when you're facing a heavy workload. It’s important to acknowledge how you feel and not keep it bottled up. Sometimes, stress and emotional exhaustion can build up, and it’s okay to let yourself feel those emotions."
48
+
49
+ # Add coping strategies based on the situation
50
+ if "workload" in user_input.lower():
51
+ response += "\n\nWhen the workload feels too heavy, it can be helpful to break tasks down into smaller, more manageable steps. Focus on one thing at a time, and remember that it’s okay to take breaks when needed. Asking for support from colleagues or friends is also a good way to lighten the load."
52
+
53
+ # Add general supportive message
54
+ response += "\n\nYou're doing your best, and that’s all anyone can ask for. Please take care of yourself and know that it’s okay to take a step back when things feel too much. Your well-being is the most important thing."
55
+
56
+ # Suggest a productive activity based on detected keywords
57
+ if any(keyword in user_input.lower() for keyword in ["lonely", "lost", "sad", "overwhelmed"]):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  st.info("Here's a suggestion to help you cope:")
59
 
60
+ # List of activities
61
+ hobbies = ["journaling", "yoga", "painting", "exercise", "meditation"]
62
+ activity = st.selectbox("Choose an activity you'd like to try:", hobbies)
63
+
64
+ # Search YouTube for videos related to the selected activity
65
+ try:
66
+ search = Search(activity)
67
+ search_results = search.results[:3] # limit results to 3 videos
68
+ st.write(f"Searching for videos related to {activity}...") # Debugging line
69
+
70
+ if not search_results:
71
+ st.write(f"No results found for '{activity}'. Please try again.")
72
+ else:
73
+ st.write(f"Found {len(search_results)} video(s) related to '{activity}'!")
74
+ for video in search_results:
75
+ st.write(f"[{video.title}]({video.watch_url})")
76
+ except Exception as e:
77
+ st.write(f"An error occurred while searching for videos: {str(e)}")
78
+ st.write("Sorry, I couldn't fetch videos at the moment.")
79
+
80
+ # Crisis resources
 
 
81
  crisis_keywords = ["help", "suicide", "depressed", "emergency", "hurt", "lost"]
82
  if any(keyword in user_input.lower() for keyword in crisis_keywords):
83
  st.warning("It seems like you might be in distress. Please reach out to a crisis hotline or a trusted individual.")
84
  st.write("[Find emergency resources here](https://www.helpguide.org/find-help.htm)")
85
+
86
+ return response
87
+
88
+ # Check if the user has typed something
89
+ if user_input:
90
+ # Generate the empathetic response
91
+ response = generate_response(user_input)
92
+
93
+ # Store and show the new response
94
+ st.session_state.previous_responses.append(response)
95
+ st.text_area("Bot's Response:", response, height=250)
96
+
97
+ # Text-to-speech output (optional)
98
+ tts = gTTS(response, lang='en')
99
+ audio_file = "response.mp3"
100
+ tts.save(audio_file)
101
+ st.audio(audio_file, format="audio/mp3")