Health_advisor / app.py
saherPervaiz's picture
Update app.py
395e2e4 verified
raw
history blame
5.1 kB
import streamlit as st
import requests
import random
# Set the GROC API Key directly in the code
GROC_API_KEY = "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" # Replace with your actual GROC API key
# Function to fetch advice from GROC API
def get_health_advice_from_groc(query):
url = f"https://api.groc.com/search?q={query}"
headers = {"Authorization": f"Bearer {GROC_API_KEY}"}
try:
response = requests.get(url, headers=headers)
response.raise_for_status()
data = response.json() # Assuming the API returns JSON
articles = [{"title": item["title"], "url": item["url"]} for item in data.get("results", [])]
if articles:
return random.choice(articles) # Randomly choose one article
return "I couldn't find specific advice from GROC. Let's proceed with what I know."
except requests.exceptions.RequestException as e:
return f"Error fetching articles: {e}"
# Function to provide dynamic advice based on user input
def get_dynamic_advice(symptom, level):
# Simple static advice (you can also replace this with data from GROC API if needed)
advice_data = {
"depression": {
"high": "It seems like you're experiencing high levels of depression. It's important to seek professional help and engage in activities like mindfulness, exercise, and reaching out to loved ones.",
"moderate": "You might be feeling a bit down. Consider adopting a healthier lifestyle by maintaining a regular sleep schedule, exercising, and talking to someone you trust.",
"low": "It's great to see that you're feeling positive. Continue to maintain a healthy lifestyle and consider engaging in activities that bring you joy and fulfillment."
},
"anxiety": {
"high": "It seems you're feeling a lot of anxiety. Consider deep breathing exercises, reducing caffeine, and taking time to relax. Speaking to a therapist could also help.",
"moderate": "You might be experiencing moderate anxiety. Try relaxation techniques such as yoga, meditation, and adequate sleep to manage your anxiety.",
"low": "It's great to see that you're feeling calm. Keep up with relaxation practices and focus on managing stress in your day-to-day life."
},
"stress": {
"high": "You're dealing with a high level of stress. It's essential to find ways to relax, such as walking, breathing exercises, or pursuing hobbies.",
"moderate": "You're experiencing moderate stress. Make sure to balance your work and personal life and practice stress-relief techniques like deep breathing or journaling.",
"low": "You're managing stress well! Keep maintaining a balance and taking time to relax and enjoy life."
}
}
if symptom in advice_data:
return advice_data[symptom].get(level, "I couldn't find the advice level you selected.")
return "I don't have advice on that symptom."
# Chat interface function
def chat_interface():
st.title("Dynamic Health Advisor Chatbot")
st.write("Welcome to the Dynamic Health Advisor Chatbot. Ask me anything about your mental health, stress, anxiety, etc. I'll do my best to provide personalized advice.")
# Initialize a session state to store chat history
if 'messages' not in st.session_state:
st.session_state['messages'] = []
# Display the previous messages
for message in st.session_state['messages']:
st.write(f"{message['role']}: {message['content']}")
# Get user input (the user sends a message)
user_input = st.text_input("You: ", "")
if user_input:
# Add the user's message to the chat history
st.session_state['messages'].append({"role": "User", "content": user_input})
# Simple keyword-based matching for advice (can be expanded to NLP-based analysis)
if "depression" in user_input.lower():
level = st.radio("How would you rate your depression?", ("high", "moderate", "low"))
advice = get_dynamic_advice("depression", level)
response = advice
elif "anxiety" in user_input.lower():
level = st.radio("How would you rate your anxiety?", ("high", "moderate", "low"))
advice = get_dynamic_advice("anxiety", level)
response = advice
elif "stress" in user_input.lower():
level = st.radio("How would you rate your stress?", ("high", "moderate", "low"))
advice = get_dynamic_advice("stress", level)
response = advice
else:
# If the symptom is not recognized, use GROC API to fetch health articles
response = get_health_advice_from_groc(user_input)
# Add the bot's response to the chat history
st.session_state['messages'].append({"role": "Bot", "content": response})
# Reload the chat interface to display the updated conversation
st.experimental_rerun()
# Streamlit app layout
def main():
chat_interface()
if __name__ == "__main__":
main()