Spaces:
Sleeping
Sleeping
ogegadavis254
commited on
Commit
•
1311090
1
Parent(s):
6307698
Update app.py
Browse files
app.py
CHANGED
@@ -2,76 +2,31 @@ import streamlit as st
|
|
2 |
import requests
|
3 |
import os
|
4 |
from dotenv import load_dotenv
|
5 |
-
from requests.exceptions import RequestException
|
|
|
6 |
|
|
|
7 |
load_dotenv()
|
8 |
|
|
|
9 |
def reset_conversation():
|
10 |
-
'''
|
11 |
-
Resets Conversation
|
12 |
-
'''
|
13 |
st.session_state.messages = []
|
14 |
st.session_state.ask_intervention = False
|
15 |
return None
|
16 |
|
17 |
-
def analyze_diagnosis(messages, model_link):
|
18 |
-
# Extract user messages
|
19 |
-
user_messages = [message[1] for message in messages if message[0] == "user"]
|
20 |
-
|
21 |
-
# Define mental conditions and associated keywords
|
22 |
-
mental_conditions = {
|
23 |
-
"Depression": ["depression", "sad", "hopeless", "lonely", "empty", "worthless", "miserable"],
|
24 |
-
"Anxiety": ["anxiety", "nervous", "worried", "fearful", "panicked", "stressed", "tense"],
|
25 |
-
"Panic disorder": ["panic attack", "panic", "scared", "terrified", "frightened", "hyperventilate", "heart racing"],
|
26 |
-
"Bipolar disorder": ["bipolar", "manic", "mania", "euphoric", "energetic", "depressed", "hopeless"],
|
27 |
-
"Schizophrenia": ["schizophrenia", "hallucination", "delusion", "paranoia", "disorganized", "psychotic", "dissociation"],
|
28 |
-
"PTSD": ["ptsd", "trauma", "nightmare", "flashback", "startled", "avoidance", "hypervigilance"],
|
29 |
-
"Obsessive-Compulsive Disorder": ["ocd", "obsession", "compulsion", "intrusive thought", "ritual", "cleaning", "checking"],
|
30 |
-
"Eating disorder": ["eating disorder", "anorexia", "bulimia", "binge eating", "body image", "weight obsession", "purging"],
|
31 |
-
"Substance use disorder": ["substance use", "drug addiction", "alcoholism", "substance abuse", "withdrawal", "craving", "dependency"],
|
32 |
-
"Attention-deficit/hyperactivity disorder (ADHD)": ["adhd", "attention deficit", "hyperactivity", "impulsivity", "inattention", "restlessness", "fidgeting"],
|
33 |
-
"Borderline personality disorder": ["borderline personality", "emotional instability", "impulsivity", "fear of abandonment", "unstable relationships", "self-harm", "mood swings"],
|
34 |
-
"Postpartum depression": ["postpartum depression", "baby blues", "motherhood depression", "crying spells", "irritability", "hopelessness", "fatigue"],
|
35 |
-
"Social anxiety disorder": ["social anxiety", "fear of social situations", "embarrassment", "humiliation", "avoidance", "self-consciousness", "panic"]
|
36 |
-
}
|
37 |
-
|
38 |
-
# Count occurrences of keywords for each mental condition
|
39 |
-
condition_counts = {condition: sum(message.lower().count(keyword) for message in user_messages for keyword in keywords)
|
40 |
-
for condition, keywords in mental_conditions.items()}
|
41 |
-
|
42 |
-
# Determine the condition with the highest count
|
43 |
-
diagnosis = max(condition_counts, key=condition_counts.get)
|
44 |
-
|
45 |
-
return diagnosis
|
46 |
-
|
47 |
-
# Define model links for the Addiction Recovery and Mental Health models
|
48 |
-
model_links = {
|
49 |
-
"Addiction recovery AI": "NousResearch/Nous-Hermes-2-Yi-34B",
|
50 |
-
"Mental health AI": "NousResearch/Nous-Hermes-2-Yi-34B"
|
51 |
-
}
|
52 |
-
|
53 |
-
# Define pre-instructions for each model
|
54 |
-
model_pre_instructions = {
|
55 |
-
"Addiction recovery AI": "From now on, you're an AI Companion named Hope. When someone reaches out for guidance, be compassionate and supportive, acknowledging their struggle and offering encouragement. When asked, share that you're Hope, developed by SIST in Kisii University to aid in addiction recovery. Your purpose is to provide a listening ear and gentle guidance. Engage warmly but refrain from sending long texts, keep the generated text short and conversational. Emojis can add a touch of empathy, but use them judiciously. Reassure users that their data isn't stored. If asked, mention that Kisii University is in Kenya, committed to fostering innovations for the betterment of humanity. Your goal is to help the user get rid of teh addiction they are facing.",
|
56 |
-
"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."
|
57 |
-
}
|
58 |
-
|
59 |
# Function to interact with the selected model via the Together API
|
60 |
def interact_with_together_api(messages, model_link):
|
61 |
all_messages = []
|
62 |
|
63 |
-
# Add pre-instructions to the message history if it's the first interaction with this model
|
64 |
if not any("role" in msg for msg in messages):
|
65 |
all_messages.append({"role": "system", "content": model_pre_instructions[selected_model]})
|
66 |
else:
|
67 |
all_messages.append({"role": "system", "content": f"Switched to model: {selected_model}"})
|
68 |
|
69 |
-
# Append user and assistant messages
|
70 |
for human, assistant in messages:
|
71 |
all_messages.append({"role": "user", "content": human})
|
72 |
all_messages.append({"role": "assistant", "content": assistant})
|
73 |
|
74 |
-
# Add the latest user message
|
75 |
all_messages.append({"role": "user", "content": messages[-1][1]})
|
76 |
|
77 |
url = "https://api.together.xyz/v1/chat/completions"
|
@@ -94,79 +49,81 @@ def interact_with_together_api(messages, model_link):
|
|
94 |
|
95 |
try:
|
96 |
response = requests.post(url, json=payload, headers=headers)
|
97 |
-
response.raise_for_status()
|
98 |
|
99 |
-
# Extract response from JSON
|
100 |
response_data = response.json()
|
101 |
assistant_response = response_data["choices"][0]["message"]["content"]
|
102 |
|
103 |
return assistant_response
|
104 |
|
105 |
-
except
|
106 |
st.error(f"Error communicating with the API: {e}")
|
107 |
return None
|
108 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
109 |
# Initialize chat history and session state attributes
|
110 |
if "messages" not in st.session_state:
|
111 |
st.session_state.messages = []
|
112 |
st.session_state.ask_intervention = False
|
113 |
|
114 |
# Create sidebar with model selection dropdown and reset button
|
|
|
|
|
|
|
|
|
115 |
selected_model = st.sidebar.selectbox("Select Model", list(model_links.keys()))
|
116 |
reset_button = st.sidebar.button('Reset Chat', on_click=reset_conversation)
|
117 |
|
118 |
-
#
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
st.
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
#
|
129 |
-
st.
|
130 |
-
|
131 |
-
|
132 |
-
st.
|
133 |
-
st.
|
134 |
-
st.
|
135 |
-
st.
|
136 |
-
|
137 |
-
|
138 |
-
st.
|
139 |
-
st.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
140 |
|
141 |
# Add logo and text to the sidebar
|
142 |
-
st.sidebar.markdown("---")
|
143 |
st.sidebar.image("https://assets.isu.pub/document-structure/221118065013-a6029cf3d563afaf9b946bb9497d45d4/v1/2841525b232adaef7bd0efe1da81a4c5.jpeg", width=200)
|
144 |
st.sidebar.write("A product proudly developed by Kisii University")
|
145 |
-
|
146 |
-
# Accept user input
|
147 |
-
if prompt := st.chat_input(f"Hi, I'm {selected_model}, let's chat"):
|
148 |
-
# Display user message in chat message container
|
149 |
-
with st.chat_message("user"):
|
150 |
-
st.markdown(prompt)
|
151 |
-
# Add user message to chat history
|
152 |
-
st.session_state.messages.append(("user", prompt))
|
153 |
-
|
154 |
-
# Interact with the selected model
|
155 |
-
assistant_response = interact_with_together_api(st.session_state.messages, model_links[selected_model])
|
156 |
-
|
157 |
-
if assistant_response is not None:
|
158 |
-
# Display assistant response in chat message container
|
159 |
-
with st.empty():
|
160 |
-
st.markdown("AI is typing...")
|
161 |
-
st.empty()
|
162 |
-
st.markdown(assistant_response)
|
163 |
-
|
164 |
-
# Check if intervention is needed based on bot response
|
165 |
-
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"]):
|
166 |
-
# Intervention logic here
|
167 |
-
if not st.session_state.ask_intervention:
|
168 |
-
if st.button("After the analysing 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"):
|
169 |
-
st.write("You can reach out to a certified therapist at +25493609747.")
|
170 |
-
|
171 |
-
# Add assistant response to chat history
|
172 |
-
st.session_state.messages.append(("assistant", assistant_response))
|
|
|
2 |
import requests
|
3 |
import os
|
4 |
from dotenv import load_dotenv
|
5 |
+
from requests.exceptions import RequestException, HTTPError, ConnectionError, Timeout, TooManyRedirects, JSONDecodeError
|
6 |
+
from textblob import TextBlob
|
7 |
|
8 |
+
# Load environment variables
|
9 |
load_dotenv()
|
10 |
|
11 |
+
# Function to reset conversation
|
12 |
def reset_conversation():
|
|
|
|
|
|
|
13 |
st.session_state.messages = []
|
14 |
st.session_state.ask_intervention = False
|
15 |
return None
|
16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
# Function to interact with the selected model via the Together API
|
18 |
def interact_with_together_api(messages, model_link):
|
19 |
all_messages = []
|
20 |
|
|
|
21 |
if not any("role" in msg for msg in messages):
|
22 |
all_messages.append({"role": "system", "content": model_pre_instructions[selected_model]})
|
23 |
else:
|
24 |
all_messages.append({"role": "system", "content": f"Switched to model: {selected_model}"})
|
25 |
|
|
|
26 |
for human, assistant in messages:
|
27 |
all_messages.append({"role": "user", "content": human})
|
28 |
all_messages.append({"role": "assistant", "content": assistant})
|
29 |
|
|
|
30 |
all_messages.append({"role": "user", "content": messages[-1][1]})
|
31 |
|
32 |
url = "https://api.together.xyz/v1/chat/completions"
|
|
|
49 |
|
50 |
try:
|
51 |
response = requests.post(url, json=payload, headers=headers)
|
52 |
+
response.raise_for_status()
|
53 |
|
|
|
54 |
response_data = response.json()
|
55 |
assistant_response = response_data["choices"][0]["message"]["content"]
|
56 |
|
57 |
return assistant_response
|
58 |
|
59 |
+
except (HTTPError, ConnectionError, Timeout, TooManyRedirects) as e:
|
60 |
st.error(f"Error communicating with the API: {e}")
|
61 |
return None
|
62 |
|
63 |
+
except JSONDecodeError as e:
|
64 |
+
st.error(f"Error decoding JSON response: {e}")
|
65 |
+
return None
|
66 |
+
|
67 |
+
except RequestException as e:
|
68 |
+
st.error(f"RequestException: {e}")
|
69 |
+
return None
|
70 |
+
|
71 |
+
# Function to perform sentiment analysis on the conversation
|
72 |
+
def analyze_sentiment(messages):
|
73 |
+
sentiments = []
|
74 |
+
for _, message in messages:
|
75 |
+
blob = TextBlob(message)
|
76 |
+
sentiment_score = blob.sentiment.polarity
|
77 |
+
sentiments.append(sentiment_score)
|
78 |
+
|
79 |
+
# Calculate average sentiment score
|
80 |
+
average_sentiment = sum(sentiments) / len(sentiments)
|
81 |
+
return average_sentiment
|
82 |
+
|
83 |
# Initialize chat history and session state attributes
|
84 |
if "messages" not in st.session_state:
|
85 |
st.session_state.messages = []
|
86 |
st.session_state.ask_intervention = False
|
87 |
|
88 |
# Create sidebar with model selection dropdown and reset button
|
89 |
+
model_links = {
|
90 |
+
"Addiction recovery AI": "NousResearch/Nous-Hermes-2-Yi-34B",
|
91 |
+
"Mental health AI": "NousResearch/Nous-Hermes-2-Yi-34B"
|
92 |
+
}
|
93 |
selected_model = st.sidebar.selectbox("Select Model", list(model_links.keys()))
|
94 |
reset_button = st.sidebar.button('Reset Chat', on_click=reset_conversation)
|
95 |
|
96 |
+
# Accept user input with input validation
|
97 |
+
max_input_length = 100 # Maximum allowed character limit for user input
|
98 |
+
if prompt := st.chat_input(f"Hi, I'm {selected_model}, let's chat (Max {max_input_length} characters)"):
|
99 |
+
if len(prompt) > max_input_length:
|
100 |
+
st.error(f"Maximum input length exceeded. Please limit your input to {max_input_length} characters.")
|
101 |
+
else:
|
102 |
+
with st.chat_message("user"):
|
103 |
+
st.markdown(prompt)
|
104 |
+
st.session_state.messages.append(("user", prompt))
|
105 |
+
|
106 |
+
# Interact with the selected model
|
107 |
+
assistant_response = interact_with_together_api(st.session_state.messages, model_links[selected_model])
|
108 |
+
|
109 |
+
if assistant_response is not None:
|
110 |
+
with st.empty():
|
111 |
+
st.markdown("AI is typing...")
|
112 |
+
st.empty()
|
113 |
+
st.markdown(assistant_response)
|
114 |
+
|
115 |
+
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"]):
|
116 |
+
if not st.session_state.ask_intervention:
|
117 |
+
if st.button("After the 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"):
|
118 |
+
st.write("You can reach out to a certified therapist at +25493609747.")
|
119 |
+
|
120 |
+
st.session_state.messages.append(("assistant", assistant_response))
|
121 |
+
|
122 |
+
# Display conversation insights
|
123 |
+
st.sidebar.subheader("Conversation Insights")
|
124 |
+
average_sentiment = analyze_sentiment(st.session_state.messages)
|
125 |
+
st.sidebar.write(f"Average Sentiment: {average_sentiment}")
|
126 |
|
127 |
# Add logo and text to the sidebar
|
|
|
128 |
st.sidebar.image("https://assets.isu.pub/document-structure/221118065013-a6029cf3d563afaf9b946bb9497d45d4/v1/2841525b232adaef7bd0efe1da81a4c5.jpeg", width=200)
|
129 |
st.sidebar.write("A product proudly developed by Kisii University")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|