Bey007 commited on
Commit
1f6d39f
1 Parent(s): 43fc113

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -41
app.py CHANGED
@@ -1,13 +1,18 @@
1
  import streamlit as st
2
- from transformers import AutoModelForCausalLM, AutoTokenizer
3
  from gtts import gTTS
4
- import torch
 
 
5
 
6
- # Load DialoGPT model and tokenizer from Hugging Face
7
- tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium")
8
- model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-medium")
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,51 +25,83 @@ 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 using DialoGPT
35
- def generate_response(user_input):
36
- # Encode the input text and generate a response
37
- new_user_input_ids = tokenizer.encode(user_input + tokenizer.eos_token, return_tensors='pt')
38
- bot_input_ids = new_user_input_ids
39
- 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)
40
-
41
- # Decode the response to text
42
- chat_history_ids = chat_history_ids[:, bot_input_ids.shape[-1]:] # remove the input from the response
43
- bot_output = tokenizer.decode(chat_history_ids[0], skip_special_tokens=True)
44
-
45
- # Build a more empathetic and thoughtful response
46
- 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."
47
-
48
- # Add coping strategies based on the situation
49
- if "workload" in user_input.lower():
50
- 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."
51
-
52
- # Add general supportive message
53
- 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."
54
-
55
- return response
56
-
57
- # Check if the user has typed something
58
  if user_input:
59
- # Generate the empathetic response
60
- response = generate_response(user_input)
61
-
62
- # Store and show the new response
63
- st.session_state.previous_responses.append(response)
64
- st.text_area("Bot's Response:", response, height=250)
65
-
66
- # Text-to-speech output (optional)
67
- tts = gTTS(response, lang='en')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  audio_file = "response.mp3"
69
  tts.save(audio_file)
70
  st.audio(audio_file, format="audio/mp3")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ from transformers import pipeline, GPT2LMHeadModel, GPT2Tokenizer
3
  from gtts import gTTS
4
+ from pytube import Search
5
+ import os
6
+ import random
7
 
8
+ # Initialize GPT-2 model and tokenizer from Hugging Face
9
+ tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
10
+ model = GPT2LMHeadModel.from_pretrained("gpt2")
11
 
12
+ # Create a text generation pipeline using GPT-2
13
+ generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
14
+
15
+ # Set up Streamlit page
16
  st.set_page_config(page_title="Grief and Loss Support Bot", page_icon="🌿", layout="centered")
17
  st.markdown("""
18
  <style>
 
25
  </style>
26
  """, unsafe_allow_html=True)
27
 
28
+ # Title
29
  st.title("Grief and Loss Support Bot 🌿")
30
  st.subheader("Your compassionate companion in tough times 💚")
31
 
32
+ # Get user input
33
  user_input = st.text_input("Share what's on your mind...", placeholder="Type here...", max_chars=500)
34
 
35
  # Store previous responses to check for repetition
36
  if 'previous_responses' not in st.session_state:
37
  st.session_state.previous_responses = []
38
 
39
+ # Check if user has entered text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  if user_input:
41
+ # Run the text generation model to generate a response based on user input
42
+ generated_responses = generator(user_input, max_length=250, num_return_sequences=3, temperature=0.7)
43
+
44
+ # Filter out any responses that are too similar to previous responses or user input
45
+ new_responses = [response['generated_text'] for response in generated_responses]
46
+ new_responses = [resp for resp in new_responses if resp.lower() not in [prev.lower() for prev in st.session_state.previous_responses] and resp.lower() != user_input.lower()]
47
+
48
+ # If there are valid new responses, pick one, otherwise fallback
49
+ if new_responses:
50
+ selected_response = random.choice(new_responses)
51
+ else:
52
+ # If no new response, fallback to a more generic empathetic message
53
+ fallback_responses = [
54
+ "I understand how you're feeling. You're not alone in this. I'm here to listen and help.",
55
+ "I'm really sorry you're going through this. Let's take one step at a time. I'm here for you.",
56
+ "It sounds really tough right now. It's okay to feel overwhelmed. You're doing your best, and that's enough."
57
+ ]
58
+ selected_response = random.choice(fallback_responses)
59
+
60
+ # Add extra empathetic phrases to the response
61
+ extra_empathy = [
62
+ "It’s completely normal to feel this way when things get tough. You're doing great by reaching out.",
63
+ "I know it can feel like a lot right now, but one step at a time. You're not alone in this.",
64
+ "Even in the toughest times, remember that there’s always support around you."
65
+ ]
66
+ selected_response += " " + random.choice(extra_empathy)
67
+
68
+ # Store the new response for future checks
69
+ st.session_state.previous_responses.append(selected_response)
70
+
71
+ # Display response
72
+ st.text_area("Bot's Response:", selected_response, height=250)
73
+
74
+ # Text-to-speech output
75
+ tts = gTTS(selected_response, lang='en')
76
  audio_file = "response.mp3"
77
  tts.save(audio_file)
78
  st.audio(audio_file, format="audio/mp3")
79
+
80
+ # Suggest a productive activity based on detected keywords
81
+ if any(keyword in user_input.lower() for keyword in ["lonely", "lost", "sad", "overwhelmed", "academic", "exam"]):
82
+ st.info("Here's a suggestion to help you cope:")
83
+
84
+ # Providing a variety of activities based on user mood and needs
85
+ activities = {
86
+ "journaling": "Express your feelings in writing. Journaling is a great way to process emotions.",
87
+ "yoga": "Yoga helps you relax and refocus. Try some deep breathing exercises or light stretching.",
88
+ "painting": "Creative expression through painting or drawing can be soothing and help you release pent-up emotions.",
89
+ "meditation": "Take a moment to calm your mind. Guided meditation can help reduce stress and anxiety.",
90
+ "exercise": "Physical activity can lift your mood. Even a short walk in nature can make a big difference."
91
+ }
92
+
93
+ # Randomly select an activity category to suggest
94
+ activity = random.choice(list(activities.keys()))
95
+ st.write(f"How about {activity}? {activities[activity]}")
96
+
97
+ # Search YouTube for videos related to the selected activity
98
+ search = Search(activity)
99
+ search_results = search.results[:3] # limit results to 3 videos
100
+ for video in search_results:
101
+ st.write(f"[{video.title}]({video.watch_url})")
102
+
103
+ # Crisis resources
104
+ crisis_keywords = ["help", "suicide", "depressed", "emergency", "hurt", "lost"]
105
+ if any(keyword in user_input.lower() for keyword in crisis_keywords):
106
+ st.warning("It seems like you might be in distress. Please reach out to a crisis hotline or a trusted individual.")
107
+ st.write("[Find emergency resources here](https://www.helpguide.org/find-help.htm)")