ogegadavis254 commited on
Commit
bc9d32e
1 Parent(s): 59a8e2c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -93
app.py CHANGED
@@ -3,7 +3,6 @@ import requests
3
  import os
4
  from dotenv import load_dotenv
5
  from requests.exceptions import RequestException
6
- import time
7
  from nltk.sentiment import SentimentIntensityAnalyzer
8
  import nltk
9
 
@@ -34,66 +33,45 @@ model_pre_instructions = {
34
  # Initialize sentiment analyzer
35
  sia = SentimentIntensityAnalyzer()
36
 
37
- # Function to interact with the selected model via the Together API and perform sentiment analysis and diagnosis prediction
38
- def interact_with_together_api(messages, model_link):
39
- all_messages = []
40
-
41
- # Add pre-instructions to the message history if it's the first interaction with this model
42
- if not any("role" in msg for msg in messages):
43
- all_messages.append({"role": "system", "content": model_pre_instructions[selected_model]})
44
- else:
45
- all_messages.append({"role": "system", "content": f"Switched to model: {selected_model}"})
46
-
47
- # Append user and assistant messages
48
- for human, assistant in messages:
49
- all_messages.append({"role": "user", "content": human})
50
- all_messages.append({"role": "assistant", "content": assistant})
51
-
52
- # Add the latest user message
53
- all_messages.append({"role": "user", "content": messages[-1][1]})
54
-
55
- url = "https://api.together.xyz/v1/chat/completions"
56
- payload = {
57
- "model": model_link,
58
- "temperature": 1.05,
59
- "top_p": 0.9,
60
- "top_k": 50,
61
- "repetition_penalty": 1,
62
- "n": 1,
63
- "messages": all_messages,
64
- }
65
-
66
- TOGETHER_API_KEY = os.getenv('TOGETHER_API_KEY')
67
- headers = {
68
- "accept": "application/json",
69
- "content-type": "application/json",
70
- "Authorization": f"Bearer {TOGETHER_API_KEY}",
71
  }
72
 
73
- try:
74
- response = requests.post(url, json=payload, headers=headers)
75
- response.raise_for_status() # Ensure HTTP request was successful
76
-
77
- # Extract response from JSON
78
- response_data = response.json()
79
- assistant_response = response_data["choices"][0]["message"]["content"]
80
-
81
- # Perform sentiment analysis
82
- sentiment_score = sia.polarity_scores(messages[-1][1]) # Analyze only the last user message
83
-
84
- # Predict diagnosis based on sentiment score and chat content
85
- if sentiment_score['compound'] > 0.5:
86
- diagnosis = "Positive mood"
87
- elif sentiment_score['compound'] < -0.5:
88
- diagnosis = "Negative mood"
89
  else:
90
- diagnosis = "Neutral mood"
91
 
92
- return assistant_response, sentiment_score, diagnosis
93
-
94
- except RequestException as e:
95
- st.error(f"Error communicating with the API: {e}")
96
- return None, None, None
97
 
98
  # Create sidebar with model selection dropdown and reset button
99
  selected_model = st.sidebar.selectbox("Select Model", list(model_links.keys()), key="model_selection")
@@ -102,44 +80,14 @@ if st.session_state.get('selected_model') != selected_model:
102
  st.info(f"You have switched to {selected_model}.")
103
  st.sidebar.button('Reset Chat', on_click=reset_conversation)
104
 
105
- # Add cautionary message about testing phase at the bottom of the sidebar
106
- st.sidebar.markdown("**Note**: This model is still in the beta phase. Responses may be inaccurate or undesired. Use it cautiously, especially for critical issues.")
 
 
107
 
108
  # Add logo and text to the sidebar
109
  st.sidebar.image("https://assets.isu.pub/document-structure/221118065013-a6029cf3d563afaf9b946bb9497d45d4/v1/2841525b232adaef7bd0efe1da81a4c5.jpeg", width=200)
110
  st.sidebar.write("A product proudly developed by Kisii University")
111
 
112
- # Initialize chat history
113
- if "messages" not in st.session_state:
114
- st.session_state.messages = []
115
- st.session_state.message_count = 0
116
- st.session_state.ask_intervention = False
117
-
118
- # Display chat messages from history on app rerun
119
- for message in st.session_state.messages:
120
- with st.chat_message(message[0]):
121
- st.markdown(message[1])
122
-
123
- # Accept user input
124
- if prompt := st.chat_input(f"Hi, I'm {selected_model}, let's chat"):
125
- # Display user message in chat message container
126
- with st.chat_message("user"):
127
- st.markdown(prompt)
128
- # Add user message to chat history
129
- st.session_state.messages.append(("user", prompt))
130
- st.session_state.message_count += 1
131
-
132
- # Interact with the selected model and perform sentiment analysis and diagnosis prediction
133
- assistant_response, sentiment_score, diagnosis = interact_with_together_api(st.session_state.messages, model_links[selected_model])
134
-
135
- if assistant_response is not None:
136
- # Display assistant response in chat message container
137
- with st.chat_message("assistant"):
138
- st.markdown(assistant_response)
139
-
140
- # Update sidebar with sentiment analysis and diagnosis
141
- st.sidebar.subheader("Sentiment Analysis")
142
- st.sidebar.write(sentiment_score)
143
-
144
- st.sidebar.subheader("User Diagnosis")
145
- st.sidebar.write(diagnosis)
 
3
  import os
4
  from dotenv import load_dotenv
5
  from requests.exceptions import RequestException
 
6
  from nltk.sentiment import SentimentIntensityAnalyzer
7
  import nltk
8
 
 
33
  # Initialize sentiment analyzer
34
  sia = SentimentIntensityAnalyzer()
35
 
36
+ # Function to predict diagnosis based on sentiment analysis and chat content
37
+ def predict_diagnosis(messages):
38
+ # Perform sentiment analysis
39
+ sentiment_score = sia.polarity_scores(messages[-1][1]) # Analyze only the last user message
40
+
41
+ # Analyze chat content for specific mental health conditions
42
+ chat_text = " ".join([msg[1] for msg in messages if msg[0] == "user"])
43
+
44
+ # Initialize diagnosis list
45
+ diagnoses = []
46
+
47
+ # Analyze chat content for specific mental health conditions
48
+ mental_conditions = {
49
+ "Depression": ["depression", "sad", "hopeless", "lonely", "empty", "worthless", "miserable"],
50
+ "Anxiety": ["anxiety", "nervous", "worried", "fearful", "panicked", "stressed", "tense"],
51
+ "Panic disorder": ["panic attack", "panic", "scared", "terrified", "frightened", "hyperventilate", "heart racing"],
52
+ "Bipolar disorder": ["bipolar", "manic", "mania", "euphoric", "energetic", "depressed", "hopeless"],
53
+ "Schizophrenia": ["schizophrenia", "hallucination", "delusion", "paranoia", "disorganized", "psychotic", "dissociation"],
54
+ "PTSD": ["ptsd", "trauma", "nightmare", "flashback", "startled", "avoidance", "hypervigilance"],
55
+ "Obsessive-Compulsive Disorder": ["ocd", "obsession", "compulsion", "intrusive thought", "ritual", "cleaning", "checking"],
56
+ "Eating disorder": ["eating disorder", "anorexia", "bulimia", "binge eating", "body image", "weight obsession", "purging"]
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  }
58
 
59
+ for condition, keywords in mental_conditions.items():
60
+ for keyword in keywords:
61
+ if keyword in chat_text.lower():
62
+ diagnoses.append(condition)
63
+ break
64
+
65
+ # If no specific condition is detected, determine mood based on sentiment score
66
+ if not diagnoses:
67
+ if sentiment_score['compound'] > 0.1:
68
+ diagnoses.append("Positive mood")
69
+ elif sentiment_score['compound'] < -0.1:
70
+ diagnoses.append("Negative mood")
 
 
 
 
71
  else:
72
+ diagnoses.append("Neutral mood")
73
 
74
+ return diagnoses
 
 
 
 
75
 
76
  # Create sidebar with model selection dropdown and reset button
77
  selected_model = st.sidebar.selectbox("Select Model", list(model_links.keys()), key="model_selection")
 
80
  st.info(f"You have switched to {selected_model}.")
81
  st.sidebar.button('Reset Chat', on_click=reset_conversation)
82
 
83
+ # Display diagnosis based on chat messages
84
+ diagnosis = predict_diagnosis(st.session_state.messages)
85
+ st.sidebar.subheader("User Diagnosis")
86
+ st.sidebar.write(", ".join(diagnosis))
87
 
88
  # Add logo and text to the sidebar
89
  st.sidebar.image("https://assets.isu.pub/document-structure/221118065013-a6029cf3d563afaf9b946bb9497d45d4/v1/2841525b232adaef7bd0efe1da81a4c5.jpeg", width=200)
90
  st.sidebar.write("A product proudly developed by Kisii University")
91
 
92
+ # Add cautionary message about testing phase at the bottom of the sidebar
93
+ st.sidebar.markdown("**Note**: This model is still in the beta phase. Responses may be inaccurate or undesired. Use it cautiously, especially for critical issues.")