AnasAlokla commited on
Commit
7e95e63
·
verified ·
1 Parent(s): 9c41078

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -34
app.py CHANGED
@@ -12,10 +12,27 @@ with open('languages_config.json', 'r', encoding='utf-8') as f:
12
  with open('emotion_templates.json', 'r') as f:
13
  data = json.load(f)
14
 
15
- # Configure Gemini (replace with your API key)
 
 
 
16
  genai.configure(api_key="AIzaSyCYRYNwCU1f9cgJYn8pd86Xcf6hiSMwJr0")
17
  model = genai.GenerativeModel('gemini-2.0-flash')
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  def generate_text(prompt, context=""):
20
  """
21
  Generates text using the Gemini model.
@@ -46,9 +63,6 @@ def create_prompt(emotion, topic=None):
46
  prompt = subfix_prompt + prompt + prefix_prompt
47
  return prompt
48
 
49
- # 1. Emotion Detection Model (Using Hugging Face's transformer)
50
- emotion_classifier = pipeline("text-classification", model="AnasAlokla/multilingual_go_emotions")
51
-
52
  # 2. Conversational Agent Logic
53
  def get_ai_response(user_input, emotion_predictions):
54
  """Generates AI response based on user input and detected emotions."""
@@ -60,52 +74,90 @@ def get_ai_response(user_input, emotion_predictions):
60
  max_score = prediction['score']
61
  dominant_emotion = prediction['label']
62
 
63
- prompt_text = create_prompt(dominant_emotion, user_input)
64
- responses = generate_text(prompt_text)
65
-
66
- # Handle cases where no specific emotion is clear
67
- if dominant_emotion is None:
68
- return "Error for response"
 
 
 
69
  else:
70
  return responses
71
 
72
  # 3. Streamlit Frontend
73
  def main():
74
- # Language Selection
75
- selected_language = st.sidebar.selectbox(
76
- "Select Interface Language",
77
- list(LANGUAGES.keys()),
78
- index=0 # Default to English
79
- )
80
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  # Display Image
82
- st.image('chatBot_image.jpg', channels='RGB')
83
 
84
  # Set page title and header based on selected language
85
  st.title(LANGUAGES[selected_language]['title'])
 
86
 
87
  # Input Text Box
88
  user_input = st.text_input(
89
  LANGUAGES[selected_language]['input_placeholder'],
90
- ""
 
91
  )
92
 
93
  if user_input:
94
- # Emotion Detection
95
- emotion_predictions = emotion_classifier(user_input)
96
-
97
- # Display Emotions
98
- st.subheader(LANGUAGES[selected_language]['emotions_header'])
99
- for prediction in emotion_predictions:
100
- st.write(f"- {prediction['label']}: {prediction['score']:.2f}")
101
-
102
- # Get AI Response
103
- ai_response = get_ai_response(user_input, emotion_predictions)
104
-
105
- # Display AI Response
106
- st.subheader(LANGUAGES[selected_language]['response_header'])
107
- st.write(ai_response)
 
 
 
 
 
108
 
109
  # Run the main function
110
  if __name__ == "__main__":
111
- main()
 
 
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
  """
38
  Generates text using the Gemini model.
 
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."""
 
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
+