Spaces:
Running
Running
File size: 13,694 Bytes
c6f7445 5671ec3 b467d1d 0399867 b467d1d 5671ec3 0ba2c5f 98888dc 0ba2c5f 5671ec3 b467d1d 941f1c3 b467d1d 7e95e63 0399867 5671ec3 0399867 98888dc 0399867 98888dc 0399867 98888dc 0399867 98888dc 0399867 98888dc 0399867 98888dc 0399867 b467d1d 0399867 c6f7445 b467d1d c6f7445 98888dc b467d1d 0399867 c6f7445 941f1c3 0399867 98888dc b467d1d 941f1c3 b467d1d 941f1c3 b467d1d 941f1c3 b467d1d 941f1c3 0399867 873f5c7 0399867 b467d1d 941f1c3 b467d1d 0ba2c5f 0399867 0ba2c5f 98888dc f0f09ac 98888dc 0399867 98888dc 941f1c3 0399867 98888dc 0399867 873f5c7 0399867 b467d1d 941f1c3 b467d1d 941f1c3 0399867 941f1c3 0399867 941f1c3 0399867 941f1c3 b467d1d 0399867 b467d1d 98c55ae 0399867 873f5c7 0399867 98c55ae 0399867 98888dc b467d1d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 |
import streamlit as st
from transformers import pipeline
import google.generativeai as genai
import json
import random
import os
from dotenv import load_dotenv
import langdetect
from langdetect import detect, DetectorFactory
from langdetect.lang_detect_exception import LangDetectException
# Set seed for consistent language detection
DetectorFactory.seed = 0
# Load environment variables
load_dotenv()
# Load language configurations from JSON
with open('languages_config.json', 'r', encoding='utf-8') as f:
LANGUAGES = json.load(f)['LANGUAGES']
# Load the JSON data for emotion templates
with open('emotion_templates.json', 'r') as f:
data = json.load(f)
# Configure Gemini API
gemini_api_key = os.getenv("GEMINI_API_KEY")
if not gemini_api_key:
st.error("GEMINI_API_KEY not found in environment variables. Please set it in your .env file.")
st.stop()
genai.configure(api_key=gemini_api_key)
model = genai.GenerativeModel('gemini-2.0-flash')
# Configure Hugging Face API (optional, for private models or rate limiting)
hf_token = os.getenv("HUGGINGFACE_TOKEN")
if hf_token:
os.environ["HUGGINGFACE_HUB_TOKEN"] = hf_token
# Available emotion detection models
EMOTION_MODELS = {
"AnasAlokla/multilingual_go_emotions": "Multilingual Go Emotions (Original)",
"AnasAlokla/multilingual_go_emotions_V1.1": "Multilingual Go Emotions (V1.1)"
}
# Language mapping for detection
SUPPORTED_LANGUAGES = {
'en': 'English',
'ar': 'Arabic',
'fr': 'French',
'es': 'Spanish',
'nl': 'Dutch',
'tr': 'Turkish'
}
def detect_language(text):
"""Detect the language of the input text."""
try:
detected_lang = detect(text)
if detected_lang in SUPPORTED_LANGUAGES:
return detected_lang
else:
return 'en' # Default to English if language not supported
except LangDetectException:
return 'en' # Default to English if detection fails
def get_language_name(lang_code):
"""Get the full language name from language code."""
return SUPPORTED_LANGUAGES.get(lang_code, 'English')
def categorize_emotion(emotion):
"""Categorize emotion as positive, negative, or neutral."""
positive_emotions = ['admiration', 'amusement', 'approval', 'caring', 'curiosity',
'desire', 'excitement', 'gratitude', 'joy', 'love', 'optimism',
'pride', 'relief']
negative_emotions = ['anger', 'annoyance', 'confusion', 'disappointment', 'disapproval',
'disgust', 'embarrassment', 'fear', 'grief', 'nervousness',
'remorse', 'sadness']
if emotion in positive_emotions:
return 'positive'
elif emotion in negative_emotions:
return 'negative'
else:
return 'neutral'
def generate_text(prompt, context=""):
"""
Generates text using the Gemini model.
"""
try:
response = model.generate_content(prompt)
return response.text
except Exception as e:
print(f"Error generating text: {e}")
return "I am sorry, I encountered an error while generating the text."
def create_enhanced_prompt(emotion, topic, detected_language, emotion_score):
"""
Creates an enhanced emotional prompt based on detected language and emotion intensity.
"""
# Get base template from emotion_templates.json
templates = data["emotion_templates"][emotion]
base_prompt = random.choice(templates)
# Replace placeholders
if topic:
placeholders = ["[topic/person]", "[topic]", "[person]", "[object]", "[outcome]"]
for placeholder in placeholders:
base_prompt = base_prompt.replace(placeholder, topic)
# Get language name
language_name = get_language_name(detected_language)
# Get emotion category
emotion_category = categorize_emotion(emotion)
# Get emotional enhancers from JSON file
emotional_enhancers = data.get("emotional_enhancers", {})
language_enhancers = emotional_enhancers.get(detected_language, emotional_enhancers.get('en', {}))
emotion_enhancer = ""
if language_enhancers and emotion_category in language_enhancers:
emotion_enhancer = random.choice(language_enhancers[emotion_category])
# Calculate emotion intensity
intensity = "high" if emotion_score > 0.7 else "moderate" if emotion_score > 0.4 else "low"
# Create enhanced prompt
enhanced_prompt = f"""
You are an emotionally intelligent AI assistant. Respond with genuine {emotion} emotion at {intensity} intensity.
Language Instructions:
- Respond ONLY in {language_name}
- Use natural, native-speaker expressions
- Match the emotional tone of a {language_name} speaker
Emotional Guidelines:
- The detected emotion is: {emotion} (confidence: {emotion_score:.2f})
- Emotion category: {emotion_category}
- Use emotionally resonant words like: {emotion_enhancer}
- Express {emotion} authentically and appropriately
- Make your response feel genuinely {emotion_category}
Context: {base_prompt}
Topic to respond about: {topic}
Requirements:
- Keep response concise but emotionally expressive (2-4 sentences)
- Use appropriate emotional language for {emotion}
- Sound natural in {language_name}
- Show empathy and understanding
- Match the emotional intensity of the user's input
"""
return enhanced_prompt
@st.cache_resource
def load_emotion_classifier(model_name):
"""Load and cache the emotion classifier model."""
try:
# Use the HF token if available for authentication
if hf_token:
return pipeline("text-classification", model=model_name, use_auth_token=hf_token)
else:
return pipeline("text-classification", model=model_name)
except Exception as e:
st.error(f"Error loading model {model_name}: {str(e)}")
return None
def get_ai_response(user_input, emotion_predictions, detected_language):
"""Generates AI response based on user input, detected emotions, and language."""
dominant_emotion = None
max_score = 0
for prediction in emotion_predictions:
if prediction['score'] > max_score:
max_score = prediction['score']
dominant_emotion = prediction['label']
if dominant_emotion is None:
return "Error: No emotion detected for response generation."
# Create enhanced prompt with language and emotion context
prompt_text = create_enhanced_prompt(dominant_emotion, user_input, detected_language, max_score)
response = generate_text(prompt_text)
return response
def display_top_predictions(emotion_predictions, selected_language, num_predictions=10):
"""Display top emotion predictions in sidebar."""
# Sort predictions by score in descending order
sorted_predictions = sorted(emotion_predictions, key=lambda x: x['score'], reverse=True)
# Take top N predictions
top_predictions = sorted_predictions[:num_predictions]
# Display in sidebar
st.sidebar.markdown("---")
st.sidebar.subheader("π― Top Emotion Predictions")
for i, prediction in enumerate(top_predictions, 1):
emotion = prediction['label']
score = prediction['score']
percentage = score * 100
# Create a progress bar for visual representation
st.sidebar.markdown(f"**{i}. {emotion.title()}**")
st.sidebar.progress(score)
st.sidebar.markdown(f"Score: {percentage:.1f}%")
st.sidebar.markdown("---")
def display_language_info(detected_language, confidence_scores=None):
"""Display detected language information."""
language_name = get_language_name(detected_language)
st.sidebar.markdown("---")
st.sidebar.subheader("π Language Detection")
st.sidebar.success(f"**Detected:** {language_name} ({detected_language.upper()})")
if confidence_scores:
st.sidebar.markdown("**Detection Confidence:**")
for lang, score in confidence_scores.items():
if lang in SUPPORTED_LANGUAGES:
lang_name = SUPPORTED_LANGUAGES[lang]
st.sidebar.markdown(f"β’ {lang_name}: {score:.2f}")
def main():
# Sidebar configurations
st.sidebar.header("βοΈ Configuration")
# Language Selection
selected_language = st.sidebar.selectbox(
"π Select Interface Language",
list(LANGUAGES.keys()),
index=0 # Default to English
)
# Model Selection
selected_model_key = st.sidebar.selectbox(
"π€ Select Emotion Detection Model",
list(EMOTION_MODELS.keys()),
format_func=lambda x: EMOTION_MODELS[x],
index=0 # Default to first model
)
# Number of predictions to show in sidebar
num_predictions = st.sidebar.slider(
"π Number of predictions to show",
min_value=5,
max_value=15,
value=10,
step=1
)
# Language detection settings
#st.sidebar.markdown("---")
#st.sidebar.subheader("π Language Detection")
#auto_detect = st.sidebar.checkbox("Auto-detect input language", value=True)
auto_detect=True
#if not auto_detect:
# manual_language = st.sidebar.selectbox(
# "Select input language manually:",
# list(SUPPORTED_LANGUAGES.keys()),
# format_func=lambda x: SUPPORTED_LANGUAGES[x],
# index=0
# )
# Load the selected emotion classifier
emotion_classifier = load_emotion_classifier(selected_model_key)
# Check if model loaded successfully
if emotion_classifier is None:
st.error("Failed to load the selected emotion detection model. Please try again or select a different model.")
return
# Display selected model info
st.sidebar.success(f"β
Current Model: {EMOTION_MODELS[selected_model_key]}")
# Display Image
if os.path.exists('chatBot_image.jpg'):
st.image('chatBot_image.jpg', channels='RGB')
# Set page title and header based on selected language
st.title(LANGUAGES[selected_language]['title'])
st.markdown(f"### π¬ {LANGUAGES[selected_language]['analyze_subtitle']}")
# Add language support info
st.info("π **Supported Languages:** English, Arabic, French, Spanish, Dutch, Turkish")
# Input Text Box
user_input = st.text_area(
LANGUAGES[selected_language]['input_placeholder'],
"",
height=100,
help="Type your message here to analyze emotions and get an emotionally appropriate response"
)
if user_input:
# Language Detection
if auto_detect:
detected_language = detect_language(user_input)
#else:
# detected_language = manual_language
# Display language detection results
display_language_info(detected_language)
# Emotion Detection
with st.spinner("Analyzing emotions..."):
emotion_predictions = emotion_classifier(user_input)
# Display top predictions in sidebar
display_top_predictions(emotion_predictions, selected_language, num_predictions)
# Display Emotions in main area (top 5)
st.subheader(LANGUAGES[selected_language]['emotions_header'])
top_5_emotions = sorted(emotion_predictions, key=lambda x: x['score'], reverse=True)[:5]
# Create columns for better display
col1, col2 = st.columns(2)
for i, prediction in enumerate(top_5_emotions):
emotion = prediction['label']
score = prediction['score']
percentage = score * 100
# Add emotion category indicator
emotion_category = categorize_emotion(emotion)
category_emoji = "π" if emotion_category == "positive" else "π" if emotion_category == "negative" else "π"
if i % 2 == 0:
with col1:
st.metric(
label=f"{category_emoji} {emotion.title()}",
value=f"{percentage:.1f}%",
delta=None
)
else:
with col2:
st.metric(
label=f"{category_emoji} {emotion.title()}",
value=f"{percentage:.1f}%",
delta=None
)
# Get AI Response with enhanced emotional intelligence
with st.spinner("Generating emotionally intelligent response..."):
ai_response = get_ai_response(user_input, emotion_predictions, detected_language)
# Display AI Response
st.subheader(f"π€ {LANGUAGES[selected_language]['response_header']}")
# Show dominant emotion and response language
dominant_emotion = max(emotion_predictions, key=lambda x: x['score'])
language_name = get_language_name(detected_language)
#st.markdown(f"**Responding with:** {dominant_emotion['label'].title()} emotion in {language_name}")
#st.markdown("---")
# Display the response in a nice container
with st.container():
#st.markdown(f"**π€ AI Response:**")
st.write(ai_response)
# Add emotion intensity indicator
emotion_score = dominant_emotion['score']
intensity = "High" if emotion_score > 0.7 else "Moderate" if emotion_score > 0.4 else "Low"
st.caption(f"Emotion Intensity: {intensity} ({emotion_score:.2f})")
# Run the main function
if __name__ == "__main__":
main() |