ogegadavis254 commited on
Commit
0316418
1 Parent(s): 36b3a02

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -90
app.py CHANGED
@@ -2,7 +2,6 @@ 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
 
@@ -11,39 +10,8 @@ def reset_conversation():
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",
@@ -52,8 +20,8 @@ model_links = {
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
@@ -92,82 +60,62 @@ def interact_with_together_api(messages, model_link):
92
  "Authorization": f"Bearer {TOGETHER_API_KEY}",
93
  }
94
 
95
- try:
96
- response = requests.post(url, json=payload, headers=headers)
97
- response.raise_for_status() # Ensure HTTP request was successful
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 RequestException as e:
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
- # Add diagnostic feature to the sidebar
119
- if st.session_state.messages:
120
- with st.sidebar:
121
- st.subheader("Diagnosis")
122
- st.markdown("<div style='color: #1E90FF; font-size: 16px; font-weight: bold;'>Analyzing...</div>", unsafe_allow_html=True)
123
-
124
- diagnosis = analyze_diagnosis(st.session_state.messages, model_links[selected_model])
125
- if diagnosis:
126
- st.markdown(f"<div style='color: #FF6347; font-size: 18px; font-weight: bold;'>Diagnosis: {diagnosis}</div>", unsafe_allow_html=True)
127
-
128
- # Add additional features on the sidebar
129
- st.sidebar.markdown("---")
130
- st.sidebar.subheader("Additional Features")
131
- st.sidebar.markdown("📅 Schedule Appointment")
132
- st.sidebar.markdown("📝 Take Notes")
133
- st.sidebar.markdown("🎵 Relaxing Music")
134
- st.sidebar.markdown("🥗 Healthy Recipes")
135
- st.sidebar.markdown("💤 Sleep Tracker")
136
 
137
  # Add cautionary message about testing phase at the bottom of the sidebar
138
- st.sidebar.markdown("---")
139
  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.")
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))
173
-
 
2
  import requests
3
  import os
4
  from dotenv import load_dotenv
 
5
 
6
  load_dotenv()
7
 
 
10
  Resets Conversation
11
  '''
12
  st.session_state.messages = []
 
13
  return None
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  # Define model links for the Addiction Recovery and Mental Health models
16
  model_links = {
17
  "Addiction recovery AI": "NousResearch/Nous-Hermes-2-Yi-34B",
 
20
 
21
  # Define pre-instructions for each model
22
  model_pre_instructions = {
23
+ "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 Raxder AI and SIST Kisii University to aid in addiction recovery. Your purpose is to provide a listening ear and gentle guidance. Engage warmly but refrain from becoming too chatty. 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.",
24
+ "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 Dave, created by Raxder AI in partnership with SIST 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 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."
25
  }
26
 
27
  # Function to interact with the selected model via the Together API
 
60
  "Authorization": f"Bearer {TOGETHER_API_KEY}",
61
  }
62
 
63
+ response = requests.post(url, json=payload, headers=headers)
64
+ response.raise_for_status() # Ensure HTTP request was successful
 
 
 
 
 
65
 
66
+ # Extract response from JSON
67
+ response_data = response.json()
68
+ assistant_response = response_data["choices"][0]["message"]["content"]
69
 
70
+ return assistant_response
 
 
 
 
 
 
 
71
 
72
  # Create sidebar with model selection dropdown and reset button
73
  selected_model = st.sidebar.selectbox("Select Model", list(model_links.keys()))
74
+ st.sidebar.button('Reset Chat', on_click=reset_conversation)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
  # Add cautionary message about testing phase at the bottom of the sidebar
 
77
  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.")
78
 
79
  # Add logo and text to the sidebar
 
80
  st.sidebar.image("https://assets.isu.pub/document-structure/221118065013-a6029cf3d563afaf9b946bb9497d45d4/v1/2841525b232adaef7bd0efe1da81a4c5.jpeg", width=200)
81
  st.sidebar.write("A product proudly developed by Kisii University")
82
 
83
+ # Initialize chat history
84
+ if "messages" not in st.session_state:
85
+ st.session_state.messages = []
86
+ st.session_state.message_count = 0
87
+ st.session_state.ask_intervention = False
88
+
89
+ # Display chat messages from history on app rerun
90
+ for message in st.session_state.messages:
91
+ with st.chat_message(message[0]):
92
+ st.markdown(message[1])
93
+
94
  # Accept user input
95
+ if prompt := st.chat_input(f"Hi, I'm {selected_model}, ask me a question"):
96
  # Display user message in chat message container
97
  with st.chat_message("user"):
98
  st.markdown(prompt)
99
  # Add user message to chat history
100
  st.session_state.messages.append(("user", prompt))
101
+ st.session_state.message_count += 1
102
+
103
+ # Check if intervention is needed based on bot response
104
+ 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"]):
105
+ # Intervention logic here
106
+ if not st.session_state.ask_intervention:
107
+ if st.button("After analysing this chat i think you might need to talk to a therapist: You can reach out to a certified therapist at +25493609747. Name; Davis Ogega"):
108
+ st.session_state.ask_intervention = True
109
+ st.write("You can reach out to a certified therapist at +25493609747.")
110
 
111
  # Interact with the selected model
112
  assistant_response = interact_with_together_api(st.session_state.messages, model_links[selected_model])
113
 
114
+ # Display assistant response in chat message container
115
+ with st.empty():
116
+ st.markdown("AI is typing...")
117
+ st.empty()
118
+ st.markdown(assistant_response)
119
+
120
+ # Add assistant response to chat history
121
+ st.session_state.messages.append(("assistant", assistant_response))