saherPervaiz commited on
Commit
80acb63
Β·
verified Β·
1 Parent(s): 67d7fa5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -36
app.py CHANGED
@@ -2,14 +2,14 @@ import streamlit as st
2
  import pandas as pd
3
  import requests
4
  import os
 
 
5
 
6
- from groq import Groq
 
7
 
8
- # Set the API key directly or from environment variable
9
- api_key = "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" # Replace with your actual demo API key
10
-
11
- # Initialize the Groq client with the API key
12
- client = Groq(api_key=api_key)
13
 
14
  # Function to load and preprocess data
15
  @st.cache_data
@@ -17,50 +17,50 @@ def load_data(file):
17
  df = pd.read_csv(file)
18
  return df
19
 
20
- # Function to provide detailed health advice based on user data
21
- def provide_observed_advice(data):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  advice = []
23
 
24
- # High depression and anxiety with low stress-relief activities
25
- if data['depression'] > 7 and data['anxiety'] > 7:
26
- 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.")
27
-
28
- # Moderate depression or anxiety
29
- elif data['depression'] > 5 or data['anxiety'] > 5:
30
- 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.")
31
-
32
- # High isolation and low stress-relief activities
33
- if data['isolation'] > 7 and data['stress_relief_activities'] < 5:
34
- 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.")
35
-
36
- # High future insecurity
37
- if data['future_insecurity'] > 7:
38
- 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.")
39
-
40
- # Overall low engagement in stress-relief activities
41
- if data['stress_relief_activities'] < 5:
42
- 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.")
43
 
44
  return advice
45
 
46
- # Function to fetch health articles from the GROC API based on the query
47
  def get_health_articles(query):
48
  url = f"https://api.groc.com/search?q={query}"
49
- headers = {"Authorization": f"Bearer {api_key}"} # Use the demo API key in the header
50
 
51
  try:
52
  response = requests.get(url, headers=headers)
53
- response.raise_for_status() # This will raise an HTTPError for bad responses
54
- data = response.json() # Assuming the API returns JSON
55
  if 'results' in data:
56
  articles = [{"title": item["title"], "url": item["url"]} for item in data['results']]
57
  else:
58
  articles = []
59
  return articles
60
- except requests.exceptions.HTTPError as http_err:
61
- st.error(f"HTTP error occurred: {http_err}. Please check your API key and the endpoint.")
62
- st.error(f"Response content: {response.text}")
63
- return []
64
  except requests.exceptions.RequestException as err:
65
  st.error(f"Error fetching articles: {err}. Please check your internet connection.")
66
  return []
@@ -125,7 +125,7 @@ def main():
125
  # Provide advice based on user inputs
126
  if st.button("πŸ” Get Observed Advice", key="advice_btn"):
127
  st.subheader("πŸ”” **Health Advice Based on Observations** πŸ””")
128
- advice = provide_observed_advice(user_data)
129
  if advice:
130
  for i, tip in enumerate(advice, 1):
131
  st.write(f"πŸ“Œ {i}. {tip}")
 
2
  import pandas as pd
3
  import requests
4
  import os
5
+ from google.cloud import language_v1
6
+ from google.oauth2 import service_account
7
 
8
+ # Set the API key for Google AI API (if not set in the environment variable)
9
+ api_key = "AIzaSyAlvoXLqzqcZgVjhQeCNUsQgk6_SGHQNr8" # Ensure your credentials are set up
10
 
11
+ # Initialize Google AI Client
12
+ client = language_v1.LanguageServiceClient(credentials=service_account.Credentials.from_service_account_file("path_to_your_service_account_json"))
 
 
 
13
 
14
  # Function to load and preprocess data
15
  @st.cache_data
 
17
  df = pd.read_csv(file)
18
  return df
19
 
20
+ # Function to fetch and analyze text using Google AI's Natural Language API
21
+ def analyze_text_with_google_ai(text):
22
+ document = language_v1.Document(content=text, type_=language_v1.Document.Type.PLAIN_TEXT)
23
+ response = client.analyze_sentiment(document=document)
24
+ sentiment_score = response.document_sentiment.score
25
+ sentiment_magnitude = response.document_sentiment.magnitude
26
+
27
+ # Example: Based on sentiment, provide advice
28
+ if sentiment_score < -0.5:
29
+ return "You may want to focus on activities that improve your mood, such as physical exercise, talking with a counselor, or engaging in mindfulness practices."
30
+ elif sentiment_score > 0.5:
31
+ return "It seems you're in a positive emotional state. Keep nurturing these positive habits, such as engaging in social activities and continuing to practice stress-relief strategies."
32
+ else:
33
+ return "You are in a neutral emotional state. Consider exploring activities that help enhance your mood, such as engaging in hobbies or relaxation exercises."
34
+
35
+ # Function to provide health advice based on user data and Google AI analysis
36
+ def provide_google_ai_advice(data):
37
  advice = []
38
 
39
+ # Example of analysis based on Google AI's sentiment analysis
40
+ if data['depression'] > 7 or data['anxiety'] > 7:
41
+ advice.append("It seems you're experiencing high levels of depression or anxiety. It might be helpful to talk to a professional or consider engaging in activities that can reduce stress, like mindfulness or physical exercise.")
42
+
43
+ # Call Google AI for sentiment-based advice
44
+ user_data_summary = f"User's depression: {data['depression']}, anxiety: {data['anxiety']}, isolation: {data['isolation']}, future insecurity: {data['future_insecurity']}, stress-relief activities: {data['stress_relief_activities']}"
45
+ google_ai_advice = analyze_text_with_google_ai(user_data_summary)
46
+ advice.append(google_ai_advice)
 
 
 
 
 
 
 
 
 
 
 
47
 
48
  return advice
49
 
50
+ # Function to fetch related health articles from GROC API (optional, for RAG-style application)
51
  def get_health_articles(query):
52
  url = f"https://api.groc.com/search?q={query}"
53
+ headers = {"Authorization": f"Bearer {api_key}"} # Replace with actual Google API key if required
54
 
55
  try:
56
  response = requests.get(url, headers=headers)
57
+ response.raise_for_status()
58
+ data = response.json()
59
  if 'results' in data:
60
  articles = [{"title": item["title"], "url": item["url"]} for item in data['results']]
61
  else:
62
  articles = []
63
  return articles
 
 
 
 
64
  except requests.exceptions.RequestException as err:
65
  st.error(f"Error fetching articles: {err}. Please check your internet connection.")
66
  return []
 
125
  # Provide advice based on user inputs
126
  if st.button("πŸ” Get Observed Advice", key="advice_btn"):
127
  st.subheader("πŸ”” **Health Advice Based on Observations** πŸ””")
128
+ advice = provide_google_ai_advice(user_data)
129
  if advice:
130
  for i, tip in enumerate(advice, 1):
131
  st.write(f"πŸ“Œ {i}. {tip}")