AnasAlokla commited on
Commit
b467d1d
·
verified ·
1 Parent(s): 7c83f7b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +93 -91
app.py CHANGED
@@ -3,6 +3,11 @@ from transformers import pipeline
3
  import google.generativeai as genai
4
  import json
5
  import random
 
 
 
 
 
6
 
7
  # Load language configurations from JSON
8
  with open('languages_config.json', 'r', encoding='utf-8') as f:
@@ -11,27 +16,26 @@ with open('languages_config.json', 'r', encoding='utf-8') as f:
11
  # Load the JSON data for emotion templates
12
  with open('emotion_templates.json', 'r') as f:
13
  data = json.load(f)
14
-
15
- # Configure Gemini (replace with your API key or use environment variable)
16
- # It's recommended to use st.secrets for API keys in Streamlit Cloud
17
- # For local testing, you can keep it as is or load from an environment variable
18
- # genai.configure(api_key=st.secrets["GEMINI_API_KEY"] if "GEMINI_API_KEY" in st.secrets else "YOUR_HARDCODED_API_KEY")
19
- genai.configure(api_key="AIzaSyCYRYNwCU1f9cgJYn8pd86Xcf6hiSMwJr0")
20
- model = genai.GenerativeModel('gemini-2.0-flash')
21
 
22
- # Use st.cache_resource to cache the loaded Hugging Face models
23
- # This prevents reloading the model every time the app reruns (e.g., on user input)
24
- @st.cache_resource
25
- def load_emotion_classifier(model_name: str):
26
- """Loads and caches the Hugging Face emotion classifier pipeline."""
27
- st.spinner(f"Loading emotion detection model: {model_name}...")
28
- try:
29
- classifier = pipeline("text-classification", model=model_name)
30
- st.success(f"Model {model_name} loaded!")
31
- return classifier
32
- except Exception as e:
33
- st.error(f"Error loading model {model_name}: {e}")
34
- return None
 
 
 
 
 
 
35
 
36
  def generate_text(prompt, context=""):
37
  """
@@ -62,102 +66,100 @@ def create_prompt(emotion, topic=None):
62
  prefix_prompt = "## topic\n" + topic
63
  prompt = subfix_prompt + prompt + prefix_prompt
64
  return prompt
65
-
66
- # 2. Conversational Agent Logic
 
 
 
 
 
 
 
 
 
 
 
 
67
  def get_ai_response(user_input, emotion_predictions):
68
  """Generates AI response based on user input and detected emotions."""
69
  dominant_emotion = None
70
  max_score = 0
71
  responses = None
 
72
  for prediction in emotion_predictions:
73
  if prediction['score'] > max_score:
74
  max_score = prediction['score']
75
  dominant_emotion = prediction['label']
76
 
77
- if dominant_emotion: # Ensure an emotion was detected
78
- prompt_text = create_prompt(dominant_emotion, user_input)
79
- responses = generate_text(prompt_text)
80
- else:
81
- responses = "I couldn't clearly detect a dominant emotion from your input."
82
-
83
- # Handle cases where no specific emotion is clear or generation failed
84
- if responses is None:
85
- return "I am sorry, I couldn't generate a response based on the detected emotion."
86
  else:
87
  return responses
88
 
89
- # 3. Streamlit Frontend
90
  def main():
91
- st.set_page_config(page_title="Emotion-Aware Chatbot", layout="centered")
92
-
93
- # --- Sidebar for Language and Model Selection ---
94
- with st.sidebar:
95
- st.header("Settings")
96
-
97
- # Language Selection
98
- selected_language = st.selectbox(
99
- "Select Interface Language",
100
- list(LANGUAGES.keys()),
101
- index=0 # Default to English
102
- )
103
-
104
- # Model Selection
105
- model_options = {
106
- "Multilingual GoEmotions (v1.0)": "AnasAlokla/multilingual_go_emotions",
107
- "Multilingual GoEmotions (v1.1)": "AnasAlokla/multilingual_go_emotions_V1.1"
108
- }
109
-
110
- selected_model_display_name = st.selectbox(
111
- "Select Emotion Detection Model",
112
- list(model_options.keys())
113
- )
114
-
115
- selected_model_path = model_options[selected_model_display_name]
116
-
117
- # Load the selected emotion classifier
118
- emotion_classifier = load_emotion_classifier(selected_model_path)
119
-
120
- if emotion_classifier is None:
121
- st.error("Emotion detection model could not be loaded. Please check your internet connection or try again.")
122
- return # Stop execution if model didn't load
123
-
124
- # --- Main Content Area ---
125
  # Display Image
126
- st.image('chatBot_image.jpg', caption="Emotion-Aware Chatbot", use_column_width=True)
127
 
128
  # Set page title and header based on selected language
129
  st.title(LANGUAGES[selected_language]['title'])
130
- st.write(LANGUAGES[selected_language]['description'])
131
 
132
  # Input Text Box
133
  user_input = st.text_input(
134
  LANGUAGES[selected_language]['input_placeholder'],
135
- "",
136
- key="user_input_text" # Added a key for better re-rendering behavior
137
  )
138
 
139
  if user_input:
140
- if emotion_classifier: # Proceed only if model is loaded
141
- # Emotion Detection
142
- with st.spinner(LANGUAGES[selected_language]['detecting_emotion']):
143
- emotion_predictions = emotion_classifier(user_input)
144
-
145
- # Display Emotions
146
- st.subheader(LANGUAGES[selected_language]['emotions_header'])
147
- for prediction in emotion_predictions:
148
- st.write(f"- {prediction['label']}: {prediction['score']:.2f}")
149
-
150
- # Get AI Response
151
- with st.spinner(LANGUAGES[selected_language]['generating_response']):
152
- ai_response = get_ai_response(user_input, emotion_predictions)
153
-
154
- # Display AI Response
155
- st.subheader(LANGUAGES[selected_language]['response_header'])
156
- st.info(ai_response) # Using st.info for a distinct display
157
- else:
158
- st.warning("Cannot process input because the emotion detection model failed to load.")
159
 
160
  # Run the main function
161
  if __name__ == "__main__":
162
- main()
163
-
 
3
  import google.generativeai as genai
4
  import json
5
  import random
6
+ import os
7
+ from dotenv import load_dotenv
8
+
9
+ # Load environment variables
10
+ load_dotenv()
11
 
12
  # Load language configurations from JSON
13
  with open('languages_config.json', 'r', encoding='utf-8') as f:
 
16
  # Load the JSON data for emotion templates
17
  with open('emotion_templates.json', 'r') as f:
18
  data = json.load(f)
 
 
 
 
 
 
 
19
 
20
+ # Configure Gemini API
21
+ gemini_api_key = os.getenv("GEMINI_API_KEY")
22
+ if not gemini_api_key:
23
+ st.error("GEMINI_API_KEY not found in environment variables. Please set it in your .env file.")
24
+ st.stop()
25
+
26
+ genai.configure(api_key=gemini_api_key)
27
+ model = genai.GenerativeModel('gemini-2.0-flash')
28
+
29
+ # Configure Hugging Face API (optional, for private models or rate limiting)
30
+ hf_token = os.getenv("HUGGINGFACE_TOKEN")
31
+ if hf_token:
32
+ os.environ["HUGGINGFACE_HUB_TOKEN"] = hf_token
33
+
34
+ # Available emotion detection models
35
+ EMOTION_MODELS = {
36
+ "AnasAlokla/multilingual_go_emotions": "Multilingual Go Emotions (Original)",
37
+ "AnasAlokla/multilingual_go_emotions_V1.1": "Multilingual Go Emotions (V1.1)"
38
+ }
39
 
40
  def generate_text(prompt, context=""):
41
  """
 
66
  prefix_prompt = "## topic\n" + topic
67
  prompt = subfix_prompt + prompt + prefix_prompt
68
  return prompt
69
+
70
+ @st.cache_resource
71
+ def load_emotion_classifier(model_name):
72
+ """Load and cache the emotion classifier model."""
73
+ try:
74
+ # Use the HF token if available for authentication
75
+ if hf_token:
76
+ return pipeline("text-classification", model=model_name, use_auth_token=hf_token)
77
+ else:
78
+ return pipeline("text-classification", model=model_name)
79
+ except Exception as e:
80
+ st.error(f"Error loading model {model_name}: {str(e)}")
81
+ return None
82
+
83
  def get_ai_response(user_input, emotion_predictions):
84
  """Generates AI response based on user input and detected emotions."""
85
  dominant_emotion = None
86
  max_score = 0
87
  responses = None
88
+
89
  for prediction in emotion_predictions:
90
  if prediction['score'] > max_score:
91
  max_score = prediction['score']
92
  dominant_emotion = prediction['label']
93
 
94
+ prompt_text = create_prompt(dominant_emotion, user_input)
95
+ responses = generate_text(prompt_text)
96
+
97
+ # Handle cases where no specific emotion is clear
98
+ if dominant_emotion is None:
99
+ return "Error for response"
 
 
 
100
  else:
101
  return responses
102
 
 
103
  def main():
104
+ # Sidebar configurations
105
+ st.sidebar.header("Configuration")
106
+
107
+ # Language Selection
108
+ selected_language = st.sidebar.selectbox(
109
+ "Select Interface Language",
110
+ list(LANGUAGES.keys()),
111
+ index=0 # Default to English
112
+ )
113
+
114
+ # Model Selection
115
+ selected_model_key = st.sidebar.selectbox(
116
+ "Select Emotion Detection Model",
117
+ list(EMOTION_MODELS.keys()),
118
+ format_func=lambda x: EMOTION_MODELS[x],
119
+ index=0 # Default to first model
120
+ )
121
+
122
+ # Load the selected emotion classifier
123
+ emotion_classifier = load_emotion_classifier(selected_model_key)
124
+
125
+ # Check if model loaded successfully
126
+ if emotion_classifier is None:
127
+ st.error("Failed to load the selected emotion detection model. Please try again or select a different model.")
128
+ return
129
+
130
+ # Display selected model info
131
+ st.sidebar.info(f"Current Model: {EMOTION_MODELS[selected_model_key]}")
132
+
 
 
 
 
 
133
  # Display Image
134
+ st.image('chatBot_image.jpg', channels='RGB')
135
 
136
  # Set page title and header based on selected language
137
  st.title(LANGUAGES[selected_language]['title'])
 
138
 
139
  # Input Text Box
140
  user_input = st.text_input(
141
  LANGUAGES[selected_language]['input_placeholder'],
142
+ ""
 
143
  )
144
 
145
  if user_input:
146
+ # Emotion Detection
147
+ with st.spinner("Analyzing emotions..."):
148
+ emotion_predictions = emotion_classifier(user_input)
149
+
150
+ # Display Emotions
151
+ st.subheader(LANGUAGES[selected_language]['emotions_header'])
152
+ for prediction in emotion_predictions:
153
+ st.write(f"- {prediction['label']}: {prediction['score']:.2f}")
154
+
155
+ # Get AI Response
156
+ with st.spinner("Generating response..."):
157
+ ai_response = get_ai_response(user_input, emotion_predictions)
158
+
159
+ # Display AI Response
160
+ st.subheader(LANGUAGES[selected_language]['response_header'])
161
+ st.write(ai_response)
 
 
 
162
 
163
  # Run the main function
164
  if __name__ == "__main__":
165
+ main()