Bey007 commited on
Commit
80d269f
Β·
verified Β·
1 Parent(s): 4d28eb3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -52
app.py CHANGED
@@ -1,64 +1,99 @@
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 models
8
- conversational_bot = pipeline("text-generation", model="microsoft/DialoGPT-medium")
9
- sentiment_analysis = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
10
 
11
- # Set up Streamlit page
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; }
16
- .css-ffhzg2 { font-size: 1.5em; font-weight: 500; color: #4C6D7D; }
17
- .stTextInput>div>div>input { background-color: #D8E3E2; }
18
- .stButton>button { background-color: #A9D0B6; color: white; border-radius: 5px; }
19
- .stButton>button:hover { background-color: #8FB79A; }
20
- .stTextInput>div>label { color: #4C6D7D; }
21
- </style>
22
- """, unsafe_allow_html=True)
23
 
24
- # Title
25
- st.title("Grief and Loss Support Bot 🌿")
26
- st.subheader("Your compassionate companion in tough times πŸ’š")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
- # Get user input
29
- user_input = st.text_input("Share what's on your mind...", placeholder="Type here...", max_chars=500)
 
 
 
 
30
 
31
- # Check if user has entered text
32
  if user_input:
33
- # Run sentiment analysis for crisis detection
34
- sentiment = sentiment_analysis(user_input)[0]
35
-
36
- # Use conversational bot for responses
37
- response = conversational_bot(user_input, max_length=150)[0]['generated_text']
38
-
39
- # Display response
40
- st.text_area("Bot's Response:", response, height=150)
41
 
42
- # Text-to-speech output
43
- tts = gTTS(response, lang='en')
44
- audio_file = "response.mp3"
45
- tts.save(audio_file)
46
- st.audio(audio_file, format="audio/mp3") # Removed use_container_width=True
47
 
48
- # Suggest a productive activity based on detected keywords
49
- if any(keyword in user_input.lower() for keyword in ["lonely", "lost", "sad"]):
50
- st.info("Here's a suggestion to help you cope:")
51
- hobbies = ["journaling", "yoga", "painting"]
52
- activity = st.selectbox("Choose an activity you'd like to try:", hobbies)
53
-
54
- # Search YouTube for videos related to the selected activity
55
- search = Search(activity)
56
- search_results = search.results[:2] # limit results to 2 videos
57
- for video in search_results:
58
- st.write(f"[{video.title}]({video.watch_url})")
59
 
60
- # Crisis resources
61
- crisis_keywords = ["help", "suicide", "depressed", "emergency", "hurt", "lost"]
62
- if any(keyword in user_input.lower() for keyword in crisis_keywords):
63
- st.warning("It seems like you might be in distress. Please reach out to a crisis hotline or a trusted individual.")
64
- st.write("[Find emergency resources here](https://www.helpguide.org/find-help.htm)")
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  from transformers import pipeline
3
  from gtts import gTTS
4
+ from io import BytesIO
5
+ import random
6
+ import requests
7
+ from youtubesearchpython import VideosSearch
8
 
9
+ # Initialize the empathy bot pipeline
10
+ empathy_bot = pipeline("text2text-generation", model="mrm8488/t5-base-finetuned-empathy")
 
11
 
12
+ # Function to process the user's input and generate a dynamic response
13
+ def generate_dynamic_response(user_input):
14
+ # Generate an empathetic response using the model
15
+ response = empathy_bot(user_input)
16
+ empathetic_response = response[0]['generated_text']
 
 
 
 
 
 
 
17
 
18
+ # Possible activities to suggest
19
+ activities = {
20
+ "relaxation": [
21
+ "Deep Breathing Exercises",
22
+ "Guided Meditation",
23
+ "Mindfulness Breathing"
24
+ ],
25
+ "creative": [
26
+ "Journaling your thoughts",
27
+ "Drawing or doodling",
28
+ "Writing a poem"
29
+ ],
30
+ "exercise": [
31
+ "Try some yoga",
32
+ "Go for a walk outside",
33
+ "Stretching exercises to release tension"
34
+ ],
35
+ "self-care": [
36
+ "Take a warm bath",
37
+ "Listen to calming music",
38
+ "Treat yourself with some relaxation time"
39
+ ]
40
+ }
41
+
42
+ # Logic to determine context of user input (e.g., stress, sadness, etc.)
43
+ if "sad" in user_input or "overwhelmed" in user_input:
44
+ suggested_activity = random.choice(activities["relaxation"])
45
+ elif "bored" in user_input or "unmotivated" in user_input:
46
+ suggested_activity = random.choice(activities["creative"])
47
+ elif "stressed" in user_input or "tired" in user_input:
48
+ suggested_activity = random.choice(activities["exercise"])
49
+ else:
50
+ suggested_activity = random.choice(activities["self-care"])
51
+
52
+ # Search YouTube for relevant videos based on the activity suggestion
53
+ video_keywords = suggested_activity
54
+ video_results = search_youtube_videos(video_keywords)
55
+
56
+ return empathetic_response, suggested_activity, video_results
57
+
58
+ # Function to search for YouTube videos
59
+ def search_youtube_videos(query):
60
+ videos_search = VideosSearch(query, limit=3)
61
+ results = videos_search.result()
62
+
63
+ # Collect video details
64
+ video_links = []
65
+ for video in results['videos']:
66
+ title = video['title']
67
+ link = video['link']
68
+ video_links.append((title, link))
69
 
70
+ return video_links
71
+
72
+ # Streamlit UI
73
+ st.title("Grief and Loss Support Bot 🌿")
74
+ st.markdown("Your compassionate companion in tough times πŸ’š")
75
+ user_input = st.text_input("Share what's on your mind...")
76
 
 
77
  if user_input:
78
+ empathetic_response, suggested_activity, video_results = generate_dynamic_response(user_input)
 
 
 
 
 
 
 
79
 
80
+ # Display the empathetic response
81
+ st.write(f"**Bot's Response:**")
82
+ st.write(empathetic_response)
 
 
83
 
84
+ # Suggest an activity
85
+ st.write(f"Here's a suggestion to help you cope:")
86
+ st.write(f"**Activity to try:** {suggested_activity}")
 
 
 
 
 
 
 
 
87
 
88
+ # Display YouTube video suggestions
89
+ if video_results:
90
+ st.write("Here are some YouTube videos that may help:")
91
+ for title, link in video_results:
92
+ st.write(f"[{title}]({link})")
93
+
94
+ # Generate and play an audio response using gTTS
95
+ tts = gTTS(empathetic_response, lang='en')
96
+ audio_file = BytesIO()
97
+ tts.save(audio_file)
98
+ audio_file.seek(0)
99
+ st.audio(audio_file, format="audio/mp3", use_container_width=True)