Bey007 commited on
Commit
4ddc0d8
β€’
1 Parent(s): 07d54b6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -69
app.py CHANGED
@@ -4,91 +4,105 @@ 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; }
21
- .css-ffhzg2 { font-size: 1.5em; font-weight: 500; color: #4C6D7D; }
22
- .stTextInput>div>div>input { background-color: #D8E3E2; }
23
- .stButton>button { background-color: #A9D0B6; color: white; border-radius: 5px; }
24
- .stButton>button:hover { background-color: #8FB79A; }
25
- .stTextInput>div>label { color: #4C6D7D; }
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.")
 
4
  from pytube import Search
5
  import random
6
  import os
7
+ import time
 
8
 
9
+ # Load pretrained models
10
  tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium")
11
  model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-medium")
12
+ emotion_classifier = pipeline("text-classification", model="bhadresh-savani/distilbert-base-uncased-emotion", return_all_scores=True)
13
 
14
+ # Streamlit page configuration
15
+ st.set_page_config(page_title="Grief and Loss Support Bot 🌿", page_icon="🌿", layout="centered")
16
+ st.markdown("<style>.css-1d391kg { background-color: #F3F7F6; }</style>", unsafe_allow_html=True)
17
 
18
+ # Title and welcome text
 
 
 
 
 
 
 
 
 
 
 
19
  st.title("Grief and Loss Support Bot 🌿")
20
  st.subheader("Your compassionate companion in tough times πŸ’š")
21
 
22
+ # Sidebar for additional features
23
+ with st.sidebar:
24
+ st.header("🧘 Guided Meditation")
25
+ if st.button("Play Meditation"):
26
+ meditation_audio = "meditation.mp3"
27
+ if not os.path.exists(meditation_audio):
28
+ tts = gTTS("Take a deep breath. Relax and let go of any tension...", lang='en')
29
+ tts.save(meditation_audio)
30
+ st.audio(meditation_audio, format="audio/mp3")
 
 
31
 
32
+ st.header("πŸ“– Short Comforting Story")
33
+ story_theme = st.selectbox("Choose a theme for your story:", ["courage", "healing", "hope"])
34
+ if st.button("Generate Story"):
35
+ story_prompt = f"Tell me a comforting story about {story_theme}."
36
+ input_ids = tokenizer.encode(story_prompt, return_tensors='pt')
37
+ story_ids = model.generate(input_ids, max_length=150, temperature=0.8, repetition_penalty=1.1)
38
+ story = tokenizer.decode(story_ids[0], skip_special_tokens=True)
39
+ st.text_area("Here's your story:", story, height=200)
40
 
41
+ # User input section
42
+ user_input = st.text_input("Share what's on your mind...", placeholder="Type here...", max_chars=500)
 
 
 
 
 
43
 
44
+ if 'previous_responses' not in st.session_state:
45
+ st.session_state.previous_responses = []
46
+ if 'badges' not in st.session_state:
47
+ st.session_state.badges = []
48
 
49
+ # Generate empathetic response
50
+ def generate_response(user_input):
51
+ input_ids = tokenizer.encode(user_input + tokenizer.eos_token, return_tensors='pt')
52
+ chat_history_ids = model.generate(input_ids, max_length=150, temperature=0.7, top_k=50, repetition_penalty=1.2)
53
+ response = tokenizer.decode(chat_history_ids[:, input_ids.shape[-1]:][0], skip_special_tokens=True)
54
+ return response
 
 
 
 
55
 
56
+ # Analyze user input for emotional tone
57
+ def get_emotion(user_input):
58
+ emotions = emotion_classifier(user_input)
59
+ emotions_sorted = sorted(emotions[0], key=lambda x: x['score'], reverse=True)
60
+ return emotions_sorted[0]['label']
61
+
62
+ # Provide a response if user input is provided
63
  if user_input:
64
+ emotion = get_emotion(user_input)
65
  response = generate_response(user_input)
66
+
67
+ # Display the bot's response
68
+ st.session_state.previous_responses.append(response)
69
  st.text_area("Bot's Response:", response, height=250)
70
 
71
+ # Assign motivational badges
72
+ if emotion in ["joy", "optimism"]:
73
+ badge = "🌟 Positivity Badge"
74
+ if badge not in st.session_state.badges:
75
+ st.session_state.badges.append(badge)
76
+ st.success(f"Congratulations! You've earned a {badge}!")
77
+
78
+ # Suggest coping activities
79
+ st.info("🎨 Try a New Activity")
80
+ activities = ["exercise", "yoga", "journaling", "painting", "meditation"]
81
+ selected_activity = st.selectbox("Pick an activity:", activities)
82
+
83
+ # Fetch YouTube video suggestions
84
+ if st.button("Find Videos"):
85
+ search = Search(selected_activity)
86
+ search_results = search.results[:3]
87
+ if not search_results:
88
+ st.write(f"No results found for '{selected_activity}'.")
89
+ else:
90
+ for video in search_results:
91
+ st.write(f"[{video.title}]({video.watch_url})")
92
+
93
+ # Crisis resources
94
+ if any(word in user_input.lower() for word in ["suicide", "help", "depressed"]):
95
+ st.warning("Please reach out to a crisis hotline for immediate support.")
96
+ st.write("[Find emergency resources here](https://www.helpguide.org/find-help.htm)")
97
+
98
+ # Generate audio response
99
  tts = gTTS(response, lang='en')
100
+ audio_file = "response.mp3"
101
+ tts.save(audio_file)
102
+ st.audio(audio_file, format="audio/mp3")
103
 
104
+ # Display badges and achievements
105
+ if st.session_state.badges:
106
+ st.sidebar.header("πŸ… Achievements")
107
+ for badge in st.session_state.badges:
108
+ st.sidebar.write(badge)