Bey007 commited on
Commit
5721af8
1 Parent(s): d67bb32

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -67
app.py CHANGED
@@ -1,15 +1,20 @@
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")
9
  model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-medium")
 
10
 
11
  # Set up Streamlit page configuration
12
  st.set_page_config(page_title="Grief and Loss Support Bot", page_icon="🌿", layout="centered")
 
13
  st.markdown("""
14
  <style>
15
  .css-1d391kg { background-color: #F3F7F6; }
@@ -21,81 +26,69 @@ st.markdown("""
21
  </style>
22
  """, unsafe_allow_html=True)
23
 
24
- # Title and introduction to the bot
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")
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  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
+ import datetime
8
+ import torch
9
 
10
+ # Load models
11
  tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium")
12
  model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-medium")
13
+ emotion_analyzer = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta-base")
14
 
15
  # Set up Streamlit page configuration
16
  st.set_page_config(page_title="Grief and Loss Support Bot", page_icon="🌿", layout="centered")
17
+
18
  st.markdown("""
19
  <style>
20
  .css-1d391kg { background-color: #F3F7F6; }
 
26
  </style>
27
  """, unsafe_allow_html=True)
28
 
29
+ # Title and introduction
30
  st.title("Grief and Loss Support Bot 🌿")
31
  st.subheader("Your compassionate companion in tough times 💚")
32
 
33
+ # Function to generate a response
 
 
 
 
 
 
 
34
  def generate_response(user_input):
35
+ input_ids = tokenizer.encode(user_input + tokenizer.eos_token, return_tensors='pt')
36
+ chat_history_ids = model.generate(input_ids, max_length=200, pad_token_id=tokenizer.eos_token_id, temperature=0.7, top_k=50, repetition_penalty=1.2)
37
+ bot_output = tokenizer.decode(chat_history_ids[:, input_ids.shape[-1]:][0], skip_special_tokens=True)
38
+ return bot_output
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
+ # Function to generate a comforting story based on a theme
41
+ def generate_story(theme):
42
+ prompt = f"Tell me a short, comforting story about {theme}."
43
+ input_ids = tokenizer.encode(prompt + tokenizer.eos_token, return_tensors='pt')
44
+
45
+ # Generate story
46
+ story_ids = model.generate(input_ids, max_length=150, temperature=0.7, top_p=0.9, repetition_penalty=1.2, do_sample=True, num_return_sequences=1)
47
+ story = tokenizer.decode(story_ids[0], skip_special_tokens=True)
48
+ return story
49
 
50
+ # Mindfulness Meditation
51
+ st.write("### 🧘 Guided Meditation")
52
+ if st.button("Play a 5-minute Guided Meditation"):
53
+ meditation_text = "Focus on your breath. Inhale deeply, hold for a moment, and exhale slowly. Let go of any tension."
54
+ tts_meditation = gTTS(meditation_text, lang='en')
55
+ tts_meditation.save("meditation.mp3")
56
+ st.audio("meditation.mp3", format="audio/mp3")
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
+ # Interactive Storytelling
59
+ st.write("### 📖 Short Comforting Story")
 
 
 
60
 
61
+ # User selects a theme for the story
62
+ story_theme = st.selectbox("Choose a theme for your story:", ["hope", "courage", "healing", "friendship", "resilience"])
63
+ if st.button("Generate Story"):
64
+ story = generate_story(story_theme)
65
+ st.text_area("Here’s your comforting story:", story, height=250)
66
+
67
+ # Convert story to speech
68
+ tts_story = gTTS(story, lang='en')
69
+ tts_story.save("story.mp3")
70
+ st.audio("story.mp3", format="audio/mp3")
71
 
72
+ # User input for conversational support
73
+ user_input = st.text_input("Share what's on your mind...", placeholder="Type here...", max_chars=500)
74
  if user_input:
 
75
  response = generate_response(user_input)
 
 
 
76
  st.text_area("Bot's Response:", response, height=250)
77
+
78
+ # Text-to-speech for response
79
  tts = gTTS(response, lang='en')
80
+ tts.save("response.mp3")
81
+ st.audio("response.mp3", format="audio/mp3")
82
+
83
+ # Enhanced Activity Suggestions
84
+ st.write("### 🎨 Try a New Activity")
85
+ activities = ["journaling", "yoga", "painting", "exercise", "meditation"]
86
+ activity_choice = st.selectbox("Pick an activity:", activities)
87
+ if st.button("Find Videos"):
88
+ try:
89
+ search = Search(activity_choice)
90
+ results = search.results[:3]
91
+ for video in results:
92
+ st.write(f"[{video.title}]({video.watch_url})")
93
+ except Exception as e:
94
+ st.write("Error fetching videos.")