main / app.py
ogegadavis254's picture
Update app.py
6dac4be verified
raw
history blame
5.74 kB
import streamlit as st
import requests
import os
from dotenv import load_dotenv
from nltk.sentiment import SentimentIntensityAnalyzer
import nltk
# Download VADER lexicon for sentiment analysis
nltk.download('vader_lexicon')
load_dotenv()
def reset_conversation():
'''
Resets Conversation
'''
st.session_state.messages = []
return None
# Define model links for the Addiction Recovery and Mental Health models
model_links = {
"Addiction recovery AI": "NousResearch/Nous-Hermes-2-Yi-34B",
"Mental health AI": "NousResearch/Nous-Hermes-2-Yi-34B"
}
# Define pre-instructions for each model
model_pre_instructions = {
"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.",
"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."
}
# Initialize sentiment analyzer
sia = SentimentIntensityAnalyzer()
# Initialize session state
if 'messages' not in st.session_state:
st.session_state.messages = []
# Function to predict diagnosis based on sentiment analysis and chat content
def predict_diagnosis(messages):
# Perform sentiment analysis
sentiment_score = sia.polarity_scores(messages[-1][1]) # Analyze only the last user message
# Analyze chat content for specific mental health conditions
chat_text = " ".join([msg[1] for msg in messages if msg[0] == "user"])
# Initialize diagnosis list
diagnoses = []
# Analyze chat content for specific mental health conditions
mental_conditions = {
"Depression": ["depression", "sad", "hopeless", "lonely", "empty", "worthless", "miserable"],
"Anxiety": ["anxiety", "nervous", "worried", "fearful", "panicked", "stressed", "tense"],
"Panic disorder": ["panic attack", "panic", "scared", "terrified", "frightened", "hyperventilate", "heart racing"],
"Bipolar disorder": ["bipolar", "manic", "mania", "euphoric", "energetic", "depressed", "hopeless"],
"Schizophrenia": ["schizophrenia", "hallucination", "delusion", "paranoia", "disorganized", "psychotic", "dissociation"],
"PTSD": ["ptsd", "trauma", "nightmare", "flashback", "startled", "avoidance", "hypervigilance"],
"Obsessive-Compulsive Disorder": ["ocd", "obsession", "compulsion", "intrusive thought", "ritual", "cleaning", "checking"],
"Eating disorder": ["eating disorder", "anorexia", "bulimia", "binge eating", "body image", "weight obsession", "purging"]
}
for condition, keywords in mental_conditions.items():
for keyword in keywords:
if keyword in chat_text.lower():
diagnoses.append(condition)
break
# If no specific condition is detected, determine mood based on sentiment score
if not diagnoses:
if sentiment_score['compound'] > 0.1:
diagnoses.append("Positive mood")
elif sentiment_score['compound'] < -0.1:
diagnoses.append("Negative mood")
else:
diagnoses.append("Neutral mood")
return diagnoses
# Create sidebar with model selection dropdown and reset button
selected_model = st.sidebar.selectbox("Select Model", list(model_links.keys()), key="model_selection")
if st.session_state.get('selected_model') != selected_model:
st.session_state.selected_model = selected_model
st.info(f"You have switched to {selected_model}.")
st.sidebar.button('Reset Chat', on_click=reset_conversation)
# Display diagnosis based on chat messages if messages exist
if 'messages' in st.session_state:
diagnosis = predict_diagnosis(st.session_state.messages)
st.sidebar.subheader("User Diagnosis")
st.sidebar.write(", ".join(diagnosis))
else:
st.sidebar.subheader("User Diagnosis")
st.sidebar.write("No messages yet")
# Add logo and text to the sidebar
st.sidebar.image("https://assets.isu.pub/document-structure/221118065013-a6029cf3d563afaf9b946bb9497d45d4/v1/2841525b232adaef7bd0efe1da81a4c5.jpeg", width=200)
st.sidebar.write("A product proudly developed by Kisii University")
# Add cautionary message about testing phase at the bottom of the sidebar
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.")