Bey007 commited on
Commit
d2a9917
Β·
verified Β·
1 Parent(s): 3dfc83c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -38
app.py CHANGED
@@ -1,16 +1,13 @@
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 model for empathetic dialogue
8
- conversational_bot = pipeline("text-generation", model="microsoft/DialoGPT-medium")
 
9
 
10
- # Initialize sentiment analysis
11
- sentiment_analysis = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
12
-
13
- # Set up Streamlit page
14
  st.set_page_config(page_title="Grief and Loss Support Bot", page_icon="🌿", layout="centered")
15
  st.markdown("""
16
  <style>
@@ -23,43 +20,64 @@ st.markdown("""
23
  </style>
24
  """, unsafe_allow_html=True)
25
 
26
- # Title
27
  st.title("Grief and Loss Support Bot 🌿")
28
  st.subheader("Your compassionate companion in tough times πŸ’š")
29
 
30
- # Get user input
31
  user_input = st.text_input("Share what's on your mind...", placeholder="Type here...", max_chars=500)
32
 
33
- # Check if user has entered text
34
- if user_input:
35
- # Run sentiment analysis to check for distress
36
- sentiment = sentiment_analysis(user_input)[0]
37
- # Generate empathetic response
38
- response = conversational_bot(user_input, max_length=250, temperature=0.95, top_k=60)[0]['generated_text']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
- # Display response
41
- st.text_area("Bot's Response:", response, height=200)
 
 
 
 
 
 
42
 
43
- # Text-to-speech output
44
  tts = gTTS(response, lang='en')
45
  audio_file = "response.mp3"
46
  tts.save(audio_file)
47
  st.audio(audio_file, format="audio/mp3")
48
-
49
- # Suggest a productive activity based on detected keywords
50
- if any(keyword in user_input.lower() for keyword in ["lonely", "lost", "sad", "overwhelmed"]):
51
- st.info("Here's a suggestion to help you cope:")
52
- activities = ["journaling", "yoga", "painting"]
53
- selected_activity = st.selectbox("Choose an activity you'd like to try:", activities)
54
-
55
- # Search YouTube for videos related to the selected activity
56
- search = Search(selected_activity)
57
- search_results = search.results[:3] # limit results to 3 videos
58
- for video in search_results:
59
- st.write(f"[{video.title}]({video.watch_url})")
60
-
61
- # Crisis resources
62
- crisis_keywords = ["help", "suicide", "depressed", "emergency", "hurt", "lost"]
63
- if any(keyword in user_input.lower() for keyword in crisis_keywords):
64
- st.warning("It seems like you might be in distress. Please reach out to a crisis hotline or a trusted individual.")
65
- st.write("[Find emergency resources here](https://www.helpguide.org/find-help.htm)")
 
1
  import streamlit as st
2
+ from transformers import GPT2LMHeadModel, GPT2Tokenizer
3
  from gtts import gTTS
4
+ import torch
 
5
 
6
+ # Load GPT-2 model and tokenizer from Hugging Face
7
+ tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
8
+ model = GPT2LMHeadModel.from_pretrained("gpt2")
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
  </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
35
+ def generate_response(user_input):
36
+ # Tokenize input and set parameters for text generation
37
+ inputs = tokenizer.encode(user_input, return_tensors="pt")
38
+ outputs = model.generate(
39
+ inputs,
40
+ max_length=200,
41
+ temperature=0.8,
42
+ top_k=50,
43
+ num_return_sequences=1,
44
+ pad_token_id=tokenizer.eos_token_id
45
+ )
46
+ response_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
47
+
48
+ # Add a suggestion for coping activity based on keywords in user input
49
+ if "angry" in user_input.lower() or "frustrated" in user_input.lower():
50
+ activity_suggestion = (
51
+ "Sometimes, deep breathing exercises can help calm your mind. "
52
+ "Try taking slow, deep breaths to regain a sense of calm and focus."
53
+ )
54
+ elif "sad" in user_input.lower() or "lonely" in user_input.lower():
55
+ activity_suggestion = (
56
+ "Writing about your feelings can be very therapeutic. "
57
+ "Try journaling as a way to process and release some of your emotions."
58
+ )
59
+ else:
60
+ activity_suggestion = (
61
+ "Finding a creative outlet like drawing or painting can help. "
62
+ "Art is a way to express feelings that might be difficult to put into words."
63
+ )
64
+
65
+ # Append the activity suggestion to the generated response
66
+ response = f"{response_text}\n\nHere's something you could try to help cope with how you're feeling:\n{activity_suggestion}"
67
+
68
+ return response
69
 
70
+ # Check if the user has typed something
71
+ if user_input:
72
+ # Generate the empathetic response
73
+ response = generate_response(user_input)
74
+
75
+ # Store and show the new response
76
+ st.session_state.previous_responses.append(response)
77
+ st.text_area("Bot's Response:", response, height=250)
78
 
79
+ # Text-to-speech output (optional)
80
  tts = gTTS(response, lang='en')
81
  audio_file = "response.mp3"
82
  tts.save(audio_file)
83
  st.audio(audio_file, format="audio/mp3")