Bey007 commited on
Commit
f47e491
·
verified ·
1 Parent(s): f5ffc7f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -71
app.py CHANGED
@@ -1,77 +1,52 @@
1
  import streamlit as st
2
- from transformers import pipeline
3
- from gtts import gTTS
4
- import os
5
  from youtubesearchpython import VideosSearch
6
 
7
- # Page configuration
8
- st.set_page_config(page_title="Grief Support Bot", layout="wide")
9
- st.markdown("<style>.stApp {background-color: #f0f5f9;}</style>", unsafe_allow_html=True)
10
-
11
- # Load the pre-trained chatbot model
12
- chatbot = pipeline("conversational", model="microsoft/DialoGPT-medium")
13
-
14
- # Function for voice output
15
- def speak_text(text):
16
- tts = gTTS(text, lang='en')
17
- tts.save("response.mp3")
18
- os.system("mpg321 response.mp3") # This plays the audio
19
- st.audio("response.mp3")
20
-
21
- # Function to search for YouTube videos
22
- def get_video_links(query, max_results=3):
23
- search = VideosSearch(query, max_results=max_results)
24
- results = search.result()['result']
25
- return [(video['title'], video['link']) for video in results]
26
-
27
- # Function to detect crisis keywords
28
- crisis_keywords = ["suicide", "hopeless", "alone", "depressed"]
29
-
30
- def detect_crisis(input_text):
31
- return any(word in input_text.lower() for word in crisis_keywords)
32
-
33
- # Function to suggest hobbies
34
- def suggest_hobbies():
35
- return ["Painting", "Gardening", "Writing", "Yoga", "Learning an instrument"]
36
-
37
- # App header
38
  st.title("Grief and Loss Support Bot")
39
-
40
- # Maintain conversation history using session state
41
- if 'history' not in st.session_state:
42
- st.session_state['history'] = []
43
-
44
- # User input
45
- user_input = st.text_input("You:")
46
-
47
- # If there is input, process the conversation
48
- if user_input:
49
- # Crisis detection
50
- if detect_crisis(user_input):
51
- st.warning("We care about you. If you're in crisis, please reach out to a trusted person or call emergency services.")
52
- st.markdown("Hotline resources: [Link to emergency contacts]")
 
 
 
 
53
  else:
54
- # Generate chatbot response
55
- response = chatbot(user_input)
56
- generated_text = response[0]['generated_text']
57
-
58
- # Append to history and display response
59
- st.session_state['history'].append(("You", user_input))
60
- st.session_state['history'].append(("Bot", generated_text))
61
-
62
- # Display conversation history
63
- for speaker, text in st.session_state['history']:
64
- st.write(f"**{speaker}:** {text}")
65
-
66
- # Voice output
67
- speak_text(generated_text)
68
-
69
- # Display hobby suggestions
70
- st.markdown("### Hobby Suggestions")
71
- st.markdown(", ".join(suggest_hobbies()))
72
 
73
- # Provide interactive YouTube video links
74
- st.markdown("### Videos to Help You Cope with Grief")
75
- video_links = get_video_links("coping with grief and loss", max_results=3)
76
- for title, link in video_links:
77
- st.markdown(f"- [{title}]({link})")
 
1
  import streamlit as st
2
+ from transformers import AutoModelForCausalLM, AutoTokenizer
3
+ import pyttsx3
 
4
  from youtubesearchpython import VideosSearch
5
 
6
+ # Load model and tokenizer
7
+ model_name = "microsoft/DialoGPT-medium"
8
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
9
+ model = AutoModelForCausalLM.from_pretrained(model_name)
10
+
11
+ # Initialize text-to-speech engine
12
+ engine = pyttsx3.init()
13
+ engine.setProperty('rate', 150)
14
+ engine.setProperty('voice', 'english+f3') # Choose a calm, soothing voice
15
+
16
+ # Function to generate a response
17
+ def chat_with_bot(input_text):
18
+ input_ids = tokenizer.encode(input_text + tokenizer.eos_token, return_tensors="pt")
19
+ response_ids = model.generate(input_ids, max_length=1000, pad_token_id=tokenizer.eos_token_id)
20
+ response = tokenizer.decode(response_ids[:, input_ids.shape[-1]:][0], skip_special_tokens=True)
21
+ return response
22
+
23
+ # Function to search for YouTube videos related to grief and loss
24
+ def get_video_links(query):
25
+ videos_search = VideosSearch(query, limit=3)
26
+ return videos_search.result()["result"]
27
+
28
+ # Streamlit app interface
 
 
 
 
 
 
 
 
29
  st.title("Grief and Loss Support Bot")
30
+ st.write("Welcome! This bot provides support and resources to help you cope with grief and loss.")
31
+
32
+ user_input = st.text_input("You: ", placeholder="Type your message here...")
33
+ if st.button("Send"):
34
+ if user_input:
35
+ # Generate and display response
36
+ bot_response = chat_with_bot(user_input)
37
+ st.write("Bot:", bot_response)
38
+
39
+ # Speak the response using text-to-speech
40
+ engine.say(bot_response)
41
+ engine.runAndWait()
42
+
43
+ # Display interactive content links
44
+ st.write("Here are some helpful resources:")
45
+ video_results = get_video_links("grief and loss support")
46
+ for video in video_results:
47
+ st.write(f"[{video['title']}]({video['link']})")
48
  else:
49
+ st.write("Please enter a message.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
+ # Footer
52
+ st.write("Remember, you are not alone. If you're in crisis, please reach out to a trusted source or helpline.")