Spaces:
Sleeping
Sleeping
ogegadavis254
commited on
Commit
•
6e2a9c8
1
Parent(s):
8c44f48
Update app.py
Browse files
app.py
CHANGED
@@ -2,11 +2,8 @@ import streamlit as st
|
|
2 |
import requests
|
3 |
import os
|
4 |
from dotenv import load_dotenv
|
5 |
-
from
|
6 |
-
import
|
7 |
-
|
8 |
-
# Download VADER lexicon for sentiment analysis
|
9 |
-
nltk.download('vader_lexicon')
|
10 |
|
11 |
load_dotenv()
|
12 |
|
@@ -29,60 +26,55 @@ model_pre_instructions = {
|
|
29 |
"Mental health AI": "From now on, you are an AI Therapist called Dave. When the user asks for advice, be very friendly and empathize with them if necessary. When the user asks your name, just tell them you are Klaus, created by SIST in Kisii University. You were built to be very friendly and compassionate. Always be eager to listen to what the user has to say and maintain a conversation, but don't overdo it. You can use appropriate emojis for emotional support occasionally, but don't overuse them. Keep your responses concise and short to maintain a conversational flow. Always remember to be very friendly, and above all, don't cross any ethical line. From time to time, assure the user that you do not store any of their data. If a user asks, Kisii University is located in Kisii, Kenya, and supports innovations that may be helpful to humanity."
|
30 |
}
|
31 |
|
32 |
-
#
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
if '
|
37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
38 |
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
# Perform sentiment analysis on the last user message
|
46 |
-
last_user_message = next((msg[1] for msg in reversed(messages) if msg[0] == "user"), None)
|
47 |
-
if not last_user_message:
|
48 |
-
return ["No user messages yet"]
|
49 |
-
|
50 |
-
sentiment_score = sia.polarity_scores(last_user_message)
|
51 |
-
|
52 |
-
# Analyze chat content for specific mental health conditions
|
53 |
-
chat_text = " ".join([msg[1] for msg in messages if msg[0] == "user"])
|
54 |
-
|
55 |
-
# Initialize diagnosis list
|
56 |
-
diagnoses = []
|
57 |
-
|
58 |
-
# Analyze chat content for specific mental health conditions
|
59 |
-
mental_conditions = {
|
60 |
-
"Depression": ["depression", "sad", "hopeless", "lonely", "empty", "worthless", "miserable"],
|
61 |
-
"Anxiety": ["anxiety", "nervous", "worried", "fearful", "panicked", "stressed", "tense"],
|
62 |
-
"Panic disorder": ["panic attack", "panic", "scared", "terrified", "frightened", "hyperventilate", "heart racing"],
|
63 |
-
"Bipolar disorder": ["bipolar", "manic", "mania", "euphoric", "energetic", "depressed", "hopeless"],
|
64 |
-
"Schizophrenia": ["schizophrenia", "hallucination", "delusion", "paranoia", "disorganized", "psychotic", "dissociation"],
|
65 |
-
"PTSD": ["ptsd", "trauma", "nightmare", "flashback", "startled", "avoidance", "hypervigilance"],
|
66 |
-
"Obsessive-Compulsive Disorder": ["ocd", "obsession", "compulsion", "intrusive thought", "ritual", "cleaning", "checking"],
|
67 |
-
"Eating disorder": ["eating disorder", "anorexia", "bulimia", "binge eating", "body image", "weight obsession", "purging"]
|
68 |
}
|
69 |
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
|
|
|
|
75 |
|
76 |
-
|
77 |
-
if not diagnoses:
|
78 |
-
if sentiment_score['compound'] > 0.1:
|
79 |
-
diagnoses.append("Positive mood")
|
80 |
-
elif sentiment_score['compound'] < -0.1:
|
81 |
-
diagnoses.append("Negative mood")
|
82 |
-
else:
|
83 |
-
diagnoses.append("Neutral mood")
|
84 |
|
85 |
-
|
|
|
|
|
86 |
|
87 |
# Create sidebar with model selection dropdown and reset button
|
88 |
selected_model = st.sidebar.selectbox("Select Model", list(model_links.keys()), key="model_selection")
|
@@ -91,35 +83,55 @@ if st.session_state.get('selected_model') != selected_model:
|
|
91 |
st.info(f"You have switched to {selected_model}.")
|
92 |
st.sidebar.button('Reset Chat', on_click=reset_conversation)
|
93 |
|
94 |
-
#
|
95 |
-
|
96 |
-
diagnosis = predict_diagnosis(st.session_state.messages)
|
97 |
-
st.sidebar.subheader("User Diagnosis")
|
98 |
-
st.sidebar.write(", ".join(diagnosis))
|
99 |
-
else:
|
100 |
-
st.sidebar.subheader("User Diagnosis")
|
101 |
-
st.sidebar.write("No messages yet")
|
102 |
|
103 |
# Add logo and text to the sidebar
|
104 |
st.sidebar.image("https://assets.isu.pub/document-structure/221118065013-a6029cf3d563afaf9b946bb9497d45d4/v1/2841525b232adaef7bd0efe1da81a4c5.jpeg", width=200)
|
105 |
st.sidebar.write("A product proudly developed by Kisii University")
|
106 |
|
107 |
-
#
|
108 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
109 |
|
110 |
# Accept user input
|
111 |
-
if prompt := st.
|
|
|
|
|
|
|
112 |
# Add user message to chat history
|
113 |
st.session_state.messages.append(("user", prompt))
|
|
|
114 |
|
115 |
-
#
|
116 |
-
assistant_response = "This is where the AI response would go."
|
117 |
-
|
118 |
-
# Display assistant response in chat message container
|
119 |
with st.empty():
|
120 |
st.markdown("AI is typing...")
|
|
|
121 |
st.empty()
|
122 |
-
st.markdown(
|
|
|
|
|
|
|
|
|
123 |
|
124 |
-
#
|
125 |
-
st.session_state.messages
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
import requests
|
3 |
import os
|
4 |
from dotenv import load_dotenv
|
5 |
+
from requests.exceptions import RequestException
|
6 |
+
import time
|
|
|
|
|
|
|
7 |
|
8 |
load_dotenv()
|
9 |
|
|
|
26 |
"Mental health AI": "From now on, you are an AI Therapist called Dave. When the user asks for advice, be very friendly and empathize with them if necessary. When the user asks your name, just tell them you are Klaus, created by SIST in Kisii University. You were built to be very friendly and compassionate. Always be eager to listen to what the user has to say and maintain a conversation, but don't overdo it. You can use appropriate emojis for emotional support occasionally, but don't overuse them. Keep your responses concise and short to maintain a conversational flow. Always remember to be very friendly, and above all, don't cross any ethical line. From time to time, assure the user that you do not store any of their data. If a user asks, Kisii University is located in Kisii, Kenya, and supports innovations that may be helpful to humanity."
|
27 |
}
|
28 |
|
29 |
+
# Function to interact with the selected model via the Together API
|
30 |
+
def interact_with_together_api(messages, model_link):
|
31 |
+
all_messages = []
|
32 |
+
|
33 |
+
# Add pre-instructions to the message history if it's the first interaction with this model
|
34 |
+
if not any("role" in msg for msg in messages):
|
35 |
+
all_messages.append({"role": "system", "content": model_pre_instructions[selected_model]})
|
36 |
+
else:
|
37 |
+
all_messages.append({"role": "system", "content": f"Switched to model: {selected_model}"})
|
38 |
+
|
39 |
+
# Append user and assistant messages
|
40 |
+
for human, assistant in messages:
|
41 |
+
all_messages.append({"role": "user", "content": human})
|
42 |
+
all_messages.append({"role": "assistant", "content": assistant})
|
43 |
+
|
44 |
+
# Add the latest user message
|
45 |
+
all_messages.append({"role": "user", "content": messages[-1][1]})
|
46 |
+
|
47 |
+
url = "https://api.together.xyz/v1/chat/completions"
|
48 |
+
payload = {
|
49 |
+
"model": model_link,
|
50 |
+
"temperature": 1.05,
|
51 |
+
"top_p": 0.9,
|
52 |
+
"top_k": 50,
|
53 |
+
"repetition_penalty": 1,
|
54 |
+
"n": 1,
|
55 |
+
"messages": all_messages,
|
56 |
+
}
|
57 |
|
58 |
+
TOGETHER_API_KEY = os.getenv('TOGETHER_API_KEY')
|
59 |
+
headers = {
|
60 |
+
"accept": "application/json",
|
61 |
+
"content-type": "application/json",
|
62 |
+
"Authorization": f"Bearer {TOGETHER_API_KEY}",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
63 |
}
|
64 |
|
65 |
+
try:
|
66 |
+
response = requests.post(url, json=payload, headers=headers)
|
67 |
+
response.raise_for_status() # Ensure HTTP request was successful
|
68 |
+
|
69 |
+
# Extract response from JSON
|
70 |
+
response_data = response.json()
|
71 |
+
assistant_response = response_data["choices"][0]["message"]["content"]
|
72 |
|
73 |
+
return assistant_response
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
74 |
|
75 |
+
except RequestException as e:
|
76 |
+
st.error(f"Error communicating with the API: {e}")
|
77 |
+
return None
|
78 |
|
79 |
# Create sidebar with model selection dropdown and reset button
|
80 |
selected_model = st.sidebar.selectbox("Select Model", list(model_links.keys()), key="model_selection")
|
|
|
83 |
st.info(f"You have switched to {selected_model}.")
|
84 |
st.sidebar.button('Reset Chat', on_click=reset_conversation)
|
85 |
|
86 |
+
# Add cautionary message about testing phase at the bottom of the sidebar
|
87 |
+
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.")
|
|
|
|
|
|
|
|
|
|
|
|
|
88 |
|
89 |
# Add logo and text to the sidebar
|
90 |
st.sidebar.image("https://assets.isu.pub/document-structure/221118065013-a6029cf3d563afaf9b946bb9497d45d4/v1/2841525b232adaef7bd0efe1da81a4c5.jpeg", width=200)
|
91 |
st.sidebar.write("A product proudly developed by Kisii University")
|
92 |
|
93 |
+
# Initialize chat history
|
94 |
+
if "messages" not in st.session_state:
|
95 |
+
st.session_state.messages = []
|
96 |
+
st.session_state.message_count = 0
|
97 |
+
st.session_state.ask_intervention = False
|
98 |
+
|
99 |
+
# Display chat messages from history on app rerun
|
100 |
+
for message in st.session_state.messages:
|
101 |
+
with st.chat_message(message[0]):
|
102 |
+
st.markdown(message[1])
|
103 |
|
104 |
# Accept user input
|
105 |
+
if prompt := st.chat_input(f"Hi, I'm {selected_model}, let's chat"):
|
106 |
+
# Display user message in chat message container
|
107 |
+
with st.chat_message("user"):
|
108 |
+
st.markdown(prompt)
|
109 |
# Add user message to chat history
|
110 |
st.session_state.messages.append(("user", prompt))
|
111 |
+
st.session_state.message_count += 1
|
112 |
|
113 |
+
# Simulate typing
|
|
|
|
|
|
|
114 |
with st.empty():
|
115 |
st.markdown("AI is typing...")
|
116 |
+
time.sleep(0.5)
|
117 |
st.empty()
|
118 |
+
st.markdown("AI is typing...")
|
119 |
+
time.sleep(0.5)
|
120 |
+
st.empty()
|
121 |
+
st.markdown("AI is typing...")
|
122 |
+
time.sleep(0.5)
|
123 |
|
124 |
+
# Interact with the selected model
|
125 |
+
assistant_response = interact_with_together_api(st.session_state.messages, model_links[selected_model])
|
126 |
+
|
127 |
+
if assistant_response is not None:
|
128 |
+
# Display assistant response in chat message container
|
129 |
+
with st.chat_message("assistant"):
|
130 |
+
st.markdown(assistant_response)
|
131 |
+
|
132 |
+
# Check if intervention is needed based on bot response
|
133 |
+
if any(keyword in prompt.lower() for keyword in ["human", "therapist", "someone", "died", "death", "help", "suicide", "suffering", "crisis", "emergency", "support", "depressed", "anxiety", "lonely", "desperate", "struggling", "counseling", "distressed", "hurt", "pain", "grief", "trauma", "abuse", "danger", "risk", "urgent", "need assistance"]):
|
134 |
+
# Intervention logic here
|
135 |
+
if not st.session_state.ask_intervention:
|
136 |
+
if st.button("After analyzing our session you may need some extra help, so you can reach out to a certified therapist at +25493609747 Name: Ogega feel free to talk"):
|
137 |
+
st.write("You can reach out to a certified therapist at +25493609747.")
|