saherPervaiz commited on
Commit
395e2e4
·
verified ·
1 Parent(s): c62b820

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -61
app.py CHANGED
@@ -1,80 +1,98 @@
1
  import streamlit as st
2
- import pandas as pd
 
3
 
4
  # Set the GROC API Key directly in the code
5
  GROC_API_KEY = "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" # Replace with your actual GROC API key
6
 
7
- # Function to load and preprocess data
8
- @st.cache_data
9
- def load_data(file):
10
- df = pd.read_csv(file)
11
- return df
 
 
 
 
 
 
 
 
 
 
12
 
13
- # Function to provide detailed health advice based on user data
14
- def provide_observed_advice(data):
15
- advice = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
- # High depression and anxiety with low stress-relief activities
18
- if data['depression'] > 7 and data['anxiety'] > 7:
19
- advice.append("You seem to be experiencing high levels of both depression and anxiety. It's important to consider professional mental health support. You might also benefit from engaging in calming activities like deep breathing, mindfulness, or yoga.")
20
 
21
- # Moderate depression or anxiety
22
- elif data['depression'] > 5 or data['anxiety'] > 5:
23
- advice.append("You are showing moderate levels of depression or anxiety. It would be helpful to develop healthy coping strategies like maintaining a regular sleep schedule, engaging in physical activity, and reaching out to friends or family for support.")
24
 
25
- # High isolation and low stress-relief activities
26
- if data['isolation'] > 7 and data['stress_relief_activities'] < 5:
27
- advice.append("It seems you are feeling isolated, and your engagement in stress-relief activities is low. It's important to connect with friends or join community groups. Incorporate activities that help alleviate stress, such as walking, journaling, or meditation.")
 
 
28
 
29
- # High future insecurity
30
- if data['future_insecurity'] > 7:
31
- advice.append("You are feeling a significant amount of insecurity about the future. It can be helpful to break down your larger goals into smaller, manageable tasks. Seeking career counseling or mentorship could provide valuable guidance and reduce anxiety about the future.")
32
 
33
- # Overall low engagement in stress-relief activities
34
- if data['stress_relief_activities'] < 5:
35
- advice.append("Your engagement in stress-relief activities is quite low. It's essential to engage in activities that reduce stress and promote mental wellness, such as hobbies, physical exercise, and relaxation techniques like deep breathing or yoga.")
36
 
37
- return advice
 
 
38
 
39
- # Streamlit app layout
40
- def main():
41
- st.title("Student Health Advisory Assistant")
42
- st.subheader("Analyze your well-being and get personalized advice")
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
- # File upload
45
- uploaded_file = st.file_uploader("Upload your dataset (CSV)", type=["csv"])
46
- if uploaded_file:
47
- df = load_data(uploaded_file)
48
- st.write("Dataset preview:")
49
- st.dataframe(df.head())
50
 
51
- # User input for analysis
52
- st.header("Input Your Details")
53
- gender = st.selectbox("Gender", ["Male", "Female"])
54
- age = st.slider("Age", 18, 35, step=1)
55
- depression = st.slider("Depression Level (1-10)", 1, 10)
56
- anxiety = st.slider("Anxiety Level (1-10)", 1, 10)
57
- isolation = st.slider("Isolation Level (1-10)", 1, 10)
58
- future_insecurity = st.slider("Future Insecurity Level (1-10)", 1, 10)
59
- stress_relief_activities = st.slider("Stress Relief Activities Level (1-10)", 1, 10)
60
 
61
- # Data dictionary for advice
62
- user_data = {
63
- "gender": gender,
64
- "age": age,
65
- "depression": depression,
66
- "anxiety": anxiety,
67
- "isolation": isolation,
68
- "future_insecurity": future_insecurity,
69
- "stress_relief_activities": stress_relief_activities,
70
- }
71
-
72
- # Provide advice based on user inputs
73
- if st.button("Get Observed Advice"):
74
- st.subheader("Health Advice Based on Observations")
75
- advice = provide_observed_advice(user_data)
76
- for i, tip in enumerate(advice, 1):
77
- st.write(f"{i}. {tip}")
78
 
79
  if __name__ == "__main__":
80
  main()
 
1
  import streamlit as st
2
+ import requests
3
+ import random
4
 
5
  # Set the GROC API Key directly in the code
6
  GROC_API_KEY = "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" # Replace with your actual GROC API key
7
 
8
+ # Function to fetch advice from GROC API
9
+ def get_health_advice_from_groc(query):
10
+ url = f"https://api.groc.com/search?q={query}"
11
+ headers = {"Authorization": f"Bearer {GROC_API_KEY}"}
12
+
13
+ try:
14
+ response = requests.get(url, headers=headers)
15
+ response.raise_for_status()
16
+ data = response.json() # Assuming the API returns JSON
17
+ articles = [{"title": item["title"], "url": item["url"]} for item in data.get("results", [])]
18
+ if articles:
19
+ return random.choice(articles) # Randomly choose one article
20
+ return "I couldn't find specific advice from GROC. Let's proceed with what I know."
21
+ except requests.exceptions.RequestException as e:
22
+ return f"Error fetching articles: {e}"
23
 
24
+ # Function to provide dynamic advice based on user input
25
+ def get_dynamic_advice(symptom, level):
26
+ # Simple static advice (you can also replace this with data from GROC API if needed)
27
+ advice_data = {
28
+ "depression": {
29
+ "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.",
30
+ "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.",
31
+ "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."
32
+ },
33
+ "anxiety": {
34
+ "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.",
35
+ "moderate": "You might be experiencing moderate anxiety. Try relaxation techniques such as yoga, meditation, and adequate sleep to manage your anxiety.",
36
+ "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."
37
+ },
38
+ "stress": {
39
+ "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.",
40
+ "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.",
41
+ "low": "You're managing stress well! Keep maintaining a balance and taking time to relax and enjoy life."
42
+ }
43
+ }
44
 
45
+ if symptom in advice_data:
46
+ return advice_data[symptom].get(level, "I couldn't find the advice level you selected.")
47
+ return "I don't have advice on that symptom."
48
 
49
+ # Chat interface function
50
+ def chat_interface():
51
+ st.title("Dynamic Health Advisor Chatbot")
52
 
53
+ 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.")
54
+
55
+ # Initialize a session state to store chat history
56
+ if 'messages' not in st.session_state:
57
+ st.session_state['messages'] = []
58
 
59
+ # Display the previous messages
60
+ for message in st.session_state['messages']:
61
+ st.write(f"{message['role']}: {message['content']}")
62
 
63
+ # Get user input (the user sends a message)
64
+ user_input = st.text_input("You: ", "")
 
65
 
66
+ if user_input:
67
+ # Add the user's message to the chat history
68
+ st.session_state['messages'].append({"role": "User", "content": user_input})
69
 
70
+ # Simple keyword-based matching for advice (can be expanded to NLP-based analysis)
71
+ if "depression" in user_input.lower():
72
+ level = st.radio("How would you rate your depression?", ("high", "moderate", "low"))
73
+ advice = get_dynamic_advice("depression", level)
74
+ response = advice
75
+ elif "anxiety" in user_input.lower():
76
+ level = st.radio("How would you rate your anxiety?", ("high", "moderate", "low"))
77
+ advice = get_dynamic_advice("anxiety", level)
78
+ response = advice
79
+ elif "stress" in user_input.lower():
80
+ level = st.radio("How would you rate your stress?", ("high", "moderate", "low"))
81
+ advice = get_dynamic_advice("stress", level)
82
+ response = advice
83
+ else:
84
+ # If the symptom is not recognized, use GROC API to fetch health articles
85
+ response = get_health_advice_from_groc(user_input)
86
 
87
+ # Add the bot's response to the chat history
88
+ st.session_state['messages'].append({"role": "Bot", "content": response})
 
 
 
 
89
 
90
+ # Reload the chat interface to display the updated conversation
91
+ st.experimental_rerun()
 
 
 
 
 
 
 
92
 
93
+ # Streamlit app layout
94
+ def main():
95
+ chat_interface()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
  if __name__ == "__main__":
98
  main()