Bey007 commited on
Commit
9216a0a
1 Parent(s): 9f55fc1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -103
app.py CHANGED
@@ -1,108 +1,69 @@
1
  import streamlit as st
2
- from llama_cpp import Llama
3
  from gtts import gTTS
4
- from io import BytesIO
5
  import random
6
- import requests
7
- import yt_dlp
8
-
9
- # Initialize the empathy bot using llama_cpp
10
- llm = Llama.from_pretrained(
11
- repo_id="featherless-ai-quants/HyunCello-KULLM3-empathy-v1.0-GGUF",
12
- filename="HyunCello-KULLM3-empathy-v1.0-IQ4_XS.gguf",
13
- )
14
-
15
- # Function to process the user's input and generate a dynamic response
16
- def generate_dynamic_response(user_input):
17
- # Generate an empathetic response using the Llama model
18
- response = llm.create_chat_completion(
19
- messages=[{"role": "user", "content": user_input}]
20
- )
21
- empathetic_response = response['choices'][0]['message']['content']
22
-
23
- # Possible activities to suggest
24
- activities = {
25
- "relaxation": [
26
- "Deep Breathing Exercises",
27
- "Guided Meditation",
28
- "Mindfulness Breathing"
29
- ],
30
- "creative": [
31
- "Journaling your thoughts",
32
- "Drawing or doodling",
33
- "Writing a poem"
34
- ],
35
- "exercise": [
36
- "Try some yoga",
37
- "Go for a walk outside",
38
- "Stretching exercises to release tension"
39
- ],
40
- "self-care": [
41
- "Take a warm bath",
42
- "Listen to calming music",
43
- "Treat yourself with some relaxation time"
44
- ]
45
- }
46
-
47
- # Logic to determine context of user input (e.g., stress, sadness, etc.)
48
- if "sad" in user_input or "overwhelmed" in user_input:
49
- suggested_activity = random.choice(activities["relaxation"])
50
- elif "bored" in user_input or "unmotivated" in user_input:
51
- suggested_activity = random.choice(activities["creative"])
52
- elif "stressed" in user_input or "tired" in user_input:
53
- suggested_activity = random.choice(activities["exercise"])
54
- else:
55
- suggested_activity = random.choice(activities["self-care"])
56
-
57
- # Search YouTube for relevant videos based on the activity suggestion
58
- video_keywords = suggested_activity
59
- video_results = search_youtube_videos(video_keywords)
60
-
61
- return empathetic_response, suggested_activity, video_results
62
-
63
-
64
- def search_youtube_videos(query):
65
- ydl_opts = {
66
- 'quiet': True,
67
- 'extract_flat': True,
68
- 'noplaylist': True,
69
- 'max_results': 3,
70
- }
71
-
72
- with yt_dlp.YoutubeDL(ydl_opts) as ydl:
73
- result = ydl.extract_info(f"ytsearch:{query}", download=False)
74
- videos = result.get("entries", [])
75
- video_links = [(video['title'], video['url']) for video in videos]
76
-
77
- return video_links
78
-
79
-
80
-
81
- # Streamlit UI
82
- st.title("Grief and Loss Support Bot 🌿")
83
- st.markdown("Your compassionate companion in tough times 💚")
84
- user_input = st.text_input("Share what's on your mind...")
85
-
86
  if user_input:
87
- empathetic_response, suggested_activity, video_results = generate_dynamic_response(user_input)
88
-
89
- # Display the empathetic response
90
- st.write(f"**Bot's Response:**")
91
- st.write(empathetic_response)
92
-
93
- # Suggest an activity
94
- st.write(f"Here's a suggestion to help you cope:")
95
- st.write(f"**Activity to try:** {suggested_activity}")
96
-
97
- # Display YouTube video suggestions
98
- if video_results:
99
- st.write("Here are some YouTube videos that may help:")
100
- for title, link in video_results:
101
- st.write(f"[{title}]({link})")
102
-
103
- # Generate and play an audio response using gTTS
104
- tts = gTTS(empathetic_response, lang='en')
105
- audio_file = BytesIO()
106
  tts.save(audio_file)
107
- audio_file.seek(0)
108
- st.audio(audio_file, format="audio/mp3", use_container_width=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ from transformers import pipeline
3
  from gtts import gTTS
4
+ from pytube import Search
5
  import random
6
+ import os
7
+
8
+ # Initialize pretrained Hugging Face models
9
+ empathetic_response = pipeline("text2text-generation", model="mrm8488/t5-base-finetuned-empathy")
10
+ sentiment_analysis = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
11
+
12
+ # Configure Streamlit page
13
+ st.set_page_config(page_title="Grief & Loss Support Bot", page_icon="🌱", layout="centered")
14
+ st.markdown("""
15
+ <style>
16
+ .main { background-color: #F4F9F9; }
17
+ h1, h2, h3, h4 { color: #4C6D7D; }
18
+ .stTextInput>div>div>input { background-color: #E8F1F2; border-radius: 5px; }
19
+ .stButton>button { background-color: #A4D4AE; color: white; }
20
+ .stButton>button:hover { background-color: #92C8A6; }
21
+ </style>
22
+ """, unsafe_allow_html=True)
23
+
24
+ # Title and description
25
+ st.title("Grief & Loss Support Bot 🌱")
26
+ st.subheader("Your compassionate companion in tough times 💚")
27
+
28
+ # User input
29
+ user_input = st.text_input("How are you feeling today?", placeholder="Share your thoughts here...", max_chars=500)
30
+
31
+ # Detect user sentiment and respond
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  if user_input:
33
+ sentiment = sentiment_analysis(user_input)[0]
34
+ empathy_response = empathetic_response(user_input, max_length=100)[0]['generated_text']
35
+
36
+ # Display empathetic response
37
+ st.text_area("Bot's Response:", empathy_response, height=150)
38
+
39
+ # Convert text to speech for added comfort
40
+ tts = gTTS(empathy_response, lang='en')
41
+ audio_file = "response.mp3"
 
 
 
 
 
 
 
 
 
 
42
  tts.save(audio_file)
43
+ st.audio(audio_file, format="audio/mp3")
44
+
45
+ # Activity Suggestion based on emotions detected
46
+ mood = sentiment['label'].lower()
47
+ activity_suggestions = {
48
+ "positive": ["try journaling your feelings", "practice yoga", "learn a new recipe"],
49
+ "neutral": ["take a short walk", "listen to calming music", "try some mindful breathing"],
50
+ "negative": ["explore creative activities like painting", "watch a motivational video", "write down small goals to feel organized"]
51
+ }
52
+ activities = activity_suggestions.get(mood, ["try relaxation exercises", "reach out to someone you trust"])
53
+
54
+ # Show dynamic activity suggestion
55
+ st.info("Here’s something you could try to lift your spirits:")
56
+ selected_activity = random.choice(activities)
57
+ st.write(f"**Activity Suggestion:** {selected_activity}")
58
+
59
+ # YouTube search for video resources
60
+ search = Search(selected_activity)
61
+ st.write("Recommended Videos:")
62
+ for video in search.results[:2]: # Display top 2 videos
63
+ st.write(f"[{video.title}]({video.watch_url})")
64
+
65
+ # Crisis response if critical keywords are detected
66
+ crisis_keywords = ["help", "suicide", "depressed", "emergency", "hurt", "lost"]
67
+ if any(keyword in user_input.lower() for keyword in crisis_keywords):
68
+ st.error("It sounds like you're going through a very tough time. Please don't hesitate to reach out for help.")
69
+ st.write("[Click here for emergency resources](https://www.helpguide.org/find-help.htm)")