Spaces:
Running
Running
Update app.py
Browse files
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 |
-
#
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
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 |
-
|
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 |
-
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',
|
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 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
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()
|
|