Spaces:
Running
Running
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() | |