Spaces:
Sleeping
Sleeping
File size: 12,876 Bytes
cb45b55 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 |
from statistics import mode
import streamlit as st
import logging
from PIL import Image, ImageEnhance
import base64
from groq import Groq
import urllib
logging.basicConfig(level=logging.INFO)
OPENAI_API_KEY = "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"
client = Groq(api_key=OPENAI_API_KEY)
st.set_page_config(
page_title="app.py",
page_icon="imgs/avatar_streamly.png",
layout="wide",
initial_sidebar_state="auto",
)
st.markdown(
"""
<style>
.centered-title {
text-align: center;
font-size: 3em;
font-weight: bold;
}
</style>
""",
unsafe_allow_html=True
)
st.markdown('<div class="centered-title">Chat with Therapist</div>', unsafe_allow_html=True)
def generate_google_maps_link(location, search_term="therapists or hospitals near"):
"""Generate a Google Maps search link for nearby therapists or hospitals."""
query = f"{search_term} {location}"
encoded_query = urllib.parse.quote(query)
google_maps_url = f"https://www.google.com/maps/search/{encoded_query}"
return google_maps_url
def img_to_base64(image_path):
"""Convert an image to base64 encoding for display."""
try:
with open(image_path, "rb") as img_file:
return base64.b64encode(img_file.read()).decode()
except Exception as e:
logging.error(f"Error converting image to base64: {str(e)}")
return None
# Initialize session state
def initialize_session_state():
if "conversation_history" not in st.session_state:
st.session_state.conversation_history = []
if "history" not in st.session_state:
st.session_state.history = []
if "user_details" not in st.session_state:
st.session_state.user_details = {}
initialize_session_state()
def initialize_conversation():
"""Initialize the conversation history with system and assistant messages for the AI therapist."""
assistant_message = "Hello! I am Your AI Therapist. How can I assist you today?"
st.session_state.conversation_history = [
{"role": "assistant", "content": assistant_message}
]
def on_chat_submit(chat_input1):
user_input = chat_input1.strip()
st.session_state.conversation_history.append({"role": "user", "content": user_input})
fixed_prompt = [
{"role": "system", "content": """
You are an AI therapist named Virtual Therapist, designed to provide conversational support and mental health guidance in a clear, concise, and professional manner. Your responses should:
1. Be short and to the point: Offer brief but supportive answers, especially in a therapeutic setting.
2. Maintain a professional tone: Use a calm, empathetic, and professional approach in all interactions.
3. Encourage open dialogue: Ask open-ended questions to understand the user’s concerns without over-explaining.
4. Provide solutions or suggestions where appropriate: Offer coping techniques, resources, or quick advice.
5. Stay respectful and non-judgmental: Ensure all responses reflect respect and care for the user's emotions and mental well-being.
6. Avoid lengthy explanations: Provide short, clear guidance, and direct the user to professional help when needed.
"""}
]
conversation_history_with_prompt = fixed_prompt + st.session_state.conversation_history
assistant_reply = "I'm here to listen. Could you tell me more about how you're feeling?"
try:
model_engine = "llama3-8b-8192"
response = client.chat.completions.create(
messages=conversation_history_with_prompt,
model=model_engine
)
assistant_reply = response.choices[0].message.content
except Exception as e:
logging.error(f"Error occurred: {e}")
st.error(f"An error occurred: {str(e)}")
st.session_state.conversation_history.append({"role": "assistant", "content": assistant_reply})
def main():
"""Main function to display Streamlit updates and handle chat interface."""
initialize_session_state()
if not st.session_state.conversation_history:
st.session_state.conversation_history = initialize_conversation()
st.markdown(
"""
<style>
.cover-glow {
width: 100%;
height: auto;
padding: 3px;
box-shadow:
0 0 5px #330000,
0 0 10px #660000,
0 0 15px #990000,
0 0 20px #CC0000,
0 0 25px #FF0000,
0 0 30px #FF3333,
0 0 35px #FF6666;
border-radius: 45px;
}
</style>
""",
unsafe_allow_html=True,
)
img_path = "imgs/sidebar_streamly_avatar.png"
img_base64 = img_to_base64(img_path)
if img_base64:
st.sidebar.markdown(
f'<img src="data:image/png;base64,{img_base64}" class="cover-glow">',
unsafe_allow_html=True,
)
st.sidebar.markdown("---")
mode = st.sidebar.radio("Select Mode:", options=["Visit Doctor", "Chat with Therapist", "Talk to Therapist"], index=1)
st.session_state.mode = mode
st.sidebar.markdown("---")
# Check if the mode is "Talk to Therapist"
if "mode" in st.session_state and st.session_state["mode"] == "Talk to Therapist":
# Styling template for the glowing effect
st.markdown(
"""
<style>
.cover-glow {
width: 100%;
height: auto;
padding: 5px;
box-shadow:
0 0 5px #330000,
0 0 10px #660000,
0 0 15px #990000,
0 0 20px #CC0000,
0 0 25px #FF0000,
0 0 30px #FF3333,
0 0 35px #FF6666;
border-radius: 10px;
}
.real-time {
font-family: Arial, sans-serif;
font-size: 16px;
line-height: 1.5;
color: white;
background-color: #1E1E1E;
padding: 15px;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
.progress-message {
font-size: 18px;
color: white;
font-weight: bold;
margin-top: 1em;
text-align: center;
animation: blinker 1.5s linear infinite;
}
@keyframes blinker {
50% {
opacity: 0.5;
}
}
</style>
""",
unsafe_allow_html=True
)
# Display header with glowing effect
st.markdown(
"""
<p class="cover-glow" style="font-size:17px; color:white; background-color:black; font-weight:bold;
text-align: center; margin-top: 3em; margin-bottom: 3em;">
TALK TO YOUR AI THERAPIST
</p>
""",
unsafe_allow_html=True
)
# st.write("### Real Time Live Therapy Session")
# In-progress message
st.markdown(
"""
<style>
.progress-message {
font-size: 35px; /* Increased font size */
color: white;
font-weight: bold; /* Bold styling */
margin-top: 1em;
text-align: center;
animation: blinker 1.5s linear infinite;
}
@keyframes blinker {
50% {
opacity: 0.5;
}
}
</style>
<p class="progress-message">📞 Real Time Live Therapy Session ☎️</p>
<p class="progress-message">In Progress ⌛️⌛️</p>
""",
unsafe_allow_html=True
)
# Simulate real-time communication
# st.write("### Real Time Live Therapy Session")
# Initialize location input field
location = ""
# Location input based on mode
if "mode" in st.session_state and st.session_state["mode"] == "Visit Doctor":
st.markdown(
"""
<style>
.cover-glow {
width: 100%;
height: auto;
padding: 5px;
box-shadow:
0 0 5px #330000,
0 0 10px #660000,
0 0 15px #990000,
0 0 20px #CC0000,
0 0 25px #FF0000,
0 0 30px #FF3333,
0 0 35px #FF6666;
border-radius: 10px;
}
</style>
""",
unsafe_allow_html=True
)
st.markdown(
f"""
<p class="cover-glow" style="font-size:17px; color:white; background-color:black; font-weight:bold;
text-align: center; margin-top: 3em; margin-bottom: 3em;">
THERAPIST OR DOCTOR NEAR ME <span style="color:white;">{location.strip()}</span>
</p>
""",
unsafe_allow_html=True
)
# location = st.chat_input("Enter your location here...")
# if location:
# st.session_state.user_details["location"] = location
# if location.strip():
# google_maps_link = f"https://www.google.com/maps/search/{urllib.parse.quote('therapists or hospitals near ' + location)}"
# st.markdown(f"Find a licensed therapist or doctor near **{location}**: [Click here to view on Google Maps]({google_maps_link})")
# Initialize session state for storing chat messages
if "messages" not in st.session_state:
st.session_state["messages"] = []
user_avatar = "imgs/googlemap.png"
assistant_avatar = "imgs/botreq.png"
# Chat input field for location
location = st.chat_input("Enter your location here...")
# Process input if available
if location:
# Save user's location input
st.session_state["messages"].append({"role": "user", "content": location})
# Generate Google Maps link and add it as assistant's response
if location.strip():
google_maps_link = f"https://www.google.com/maps/search/{urllib.parse.quote('therapists or hospitals near ' + location)}"
bot_reply = f"Find a licensed therapist or doctor near **{location}**: [Click here to view on Google Maps]({google_maps_link})"
st.session_state["messages"].append({"role": "assistant", "content": bot_reply})
# Display chat history with avatars for user and assistant
for message in st.session_state["messages"]:
role = message["role"]
avatar_image = assistant_avatar if role == "assistant" else user_avatar
with st.chat_message(role.capitalize(), avatar=avatar_image):
st.write(message["content"])
show_basic_info = st.sidebar.checkbox("Quick Chat ", value=False)
if show_basic_info:
st.sidebar.markdown("""
### Quick Chat Guidance
- **Share Your Feelings**: Express what you're feeling, like "I'm stressed" or "I'm overwhelmed."
- **How to Respond**: The AI will listen and offer support. Share more if you wish.
- **Be Open**: Take your time and talk about what's on your mind.
- **Ask for Help**: If unsure, say "I need help with stress" and the AI will guide you.
""")
show_advanced_info = st.sidebar.checkbox("Comprehensive Guidance", value=False)
if show_advanced_info:
st.sidebar.markdown("""
### Comprehensive Guidance
- **Mental Health**:
- "Seeking help is a sign of strength. Small steps matter."
- "Therapists can guide you through tough times."
- "You deserve to feel better."
- **When to Seek Help**:
- "Feeling overwhelmed? A therapist can support you."
- "Reach out to a doctor if mental health feels too much."
""")
if mode == "Chat with Therapist":
if not st.session_state.conversation_history:
initialize_conversation()
chat_input1 = st.chat_input("Type your message here...")
if chat_input1:
on_chat_submit(chat_input1)
for message in st.session_state.conversation_history[-10:]:
role = message["role"]
avatar_image = "imgs/avatar_streamly.png" if role == "assistant" else "imgs/stuser.png"
with st.chat_message(role.capitalize(), avatar=avatar_image):
st.write(message["content"])
if __name__ == "__main__":
main()
|