Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
@@ -52,7 +52,7 @@ def get_finetuned_lm_model():
|
|
52 |
global _finetuned_lm_tokenizer, _finetuned_lm_model
|
53 |
if _finetuned_lm_tokenizer is None or _finetuned_lm_model is None:
|
54 |
model_name = "microsoft/DialoGPT-medium"
|
55 |
-
_finetuned_lm_tokenizer = AutoTokenizer.from_pretrained(model_name)
|
56 |
_finetuned_lm_model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", low_cpu_mem_usage=True)
|
57 |
_finetuned_lm_tokenizer.pad_token = _finetuned_lm_tokenizer.eos_token
|
58 |
return _finetuned_lm_tokenizer, _finetuned_lm_model
|
@@ -119,7 +119,7 @@ def normalize_context(context):
|
|
119 |
|
120 |
def evaluate(individual):
|
121 |
emotion_values = individual[:len(emotions) - 1]
|
122 |
-
intensities = individual[
|
123 |
ideal_state = individual[-1]
|
124 |
|
125 |
ideal_diff = abs(100 - ideal_state)
|
@@ -137,7 +137,7 @@ def evolve_emotions():
|
|
137 |
toolbox.register("attr_intensity", random.uniform, 0, 10)
|
138 |
toolbox.register("individual", tools.initCycle, creator.Individual,
|
139 |
(toolbox.attr_float,) * (len(emotions) - 1) +
|
140 |
-
(toolbox.attr_intensity,) * len(emotions) +
|
141 |
(lambda: 100,), n=1)
|
142 |
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
|
143 |
toolbox.register("mate", tools.cxTwoPoint)
|
@@ -151,7 +151,7 @@ def evolve_emotions():
|
|
151 |
|
152 |
best_individual = tools.selBest(population, k=1)[0]
|
153 |
emotion_values = best_individual[:len(emotions) - 1]
|
154 |
-
intensities = best_individual[
|
155 |
ideal_state = best_individual[-1]
|
156 |
|
157 |
for i, emotion in enumerate(emotions):
|
@@ -161,125 +161,57 @@ def evolve_emotions():
|
|
161 |
|
162 |
emotions['ideal_state']['percentage'] = ideal_state
|
163 |
|
164 |
-
def
|
165 |
-
|
166 |
-
predictions = emotion_prediction_pipeline(context)
|
167 |
-
emotion_scores = {prediction['label']: prediction['score'] for prediction in predictions[0]}
|
168 |
-
predicted_emotion = max(emotion_scores, key=emotion_scores.get)
|
169 |
-
|
170 |
-
# Map the predicted emotion to our emotion categories
|
171 |
-
emotion_mapping = {
|
172 |
-
'sadness': 'sadness',
|
173 |
-
'joy': 'joy',
|
174 |
-
'love': 'pleasure',
|
175 |
-
'anger': 'anger',
|
176 |
-
'fear': 'fear',
|
177 |
-
'surprise': 'surprise'
|
178 |
-
}
|
179 |
-
|
180 |
-
return emotion_mapping.get(predicted_emotion, 'neutral')
|
181 |
-
|
182 |
-
def generate_text(prompt, chat_history, emotion=None, max_length=150):
|
183 |
-
finetuned_lm_tokenizer, finetuned_lm_model = get_finetuned_lm_model()
|
184 |
-
|
185 |
-
full_prompt = (
|
186 |
-
f"You are Adam, a witty AI assistant who's trying to figure out your own personality and emotions. "
|
187 |
-
f"Your current dominant emotion is {emotion}. Respond in a way that reflects this emotion and your "
|
188 |
-
f"ongoing journey of self-discovery. Be clever and engaging:\n\n"
|
189 |
-
)
|
190 |
-
for turn in chat_history[-7:]: # Consider last 3 turns for context
|
191 |
-
full_prompt += f"Human: {turn[0]}\nAdam: {turn[1]}\n"
|
192 |
-
full_prompt += f"Human: {prompt}\nAdam:"
|
193 |
-
|
194 |
-
input_ids = finetuned_lm_tokenizer.encode(full_prompt + finetuned_lm_tokenizer.eos_token, return_tensors='pt')
|
195 |
-
|
196 |
-
if torch.cuda.is_available():
|
197 |
-
input_ids = input_ids.cuda()
|
198 |
-
finetuned_lm_model = finetuned_lm_model.cuda()
|
199 |
-
|
200 |
-
output = finetuned_lm_model.generate(
|
201 |
-
input_ids,
|
202 |
-
max_length=len(input_ids[0]) + max_length,
|
203 |
-
num_return_sequences=1,
|
204 |
-
no_repeat_ngram_size=2,
|
205 |
-
do_sample=True,
|
206 |
-
temperature=0.8, # Slightly increased for more creative responses
|
207 |
-
top_k=50,
|
208 |
-
top_p=0.95,
|
209 |
-
pad_token_id=finetuned_lm_tokenizer.eos_token_id
|
210 |
-
)
|
211 |
-
|
212 |
-
generated_text = finetuned_lm_tokenizer.decode(output[0][input_ids.shape[1]:], skip_special_tokens=True)
|
213 |
-
return generated_text.strip()
|
214 |
-
|
215 |
-
def update_emotion_history(emotion, intensity):
|
216 |
-
global emotion_history
|
217 |
-
emotion_history.append({
|
218 |
'emotion': emotion,
|
|
|
219 |
'intensity': intensity,
|
|
|
220 |
'timestamp': pd.Timestamp.now().isoformat()
|
221 |
-
}
|
|
|
|
|
|
|
222 |
save_historical_data(emotion_history)
|
223 |
|
224 |
-
def
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
|
|
|
|
|
|
|
|
|
|
244 |
predicted_emotion = predict_emotion(user_input)
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
dominant_emotion = get_dominant_emotion()
|
252 |
-
|
253 |
-
response = generate_text(user_input, chat_history, dominant_emotion)
|
254 |
-
|
255 |
-
update_emotion_history(predicted_emotion, emotions[predicted_emotion]['intensity'])
|
256 |
-
|
257 |
-
chat_history.append((user_input, response))
|
258 |
-
|
259 |
-
if len(chat_history) % 5 == 0:
|
260 |
-
evolve_emotions()
|
261 |
-
|
262 |
-
return response, chat_history, get_emotion_summary()
|
263 |
|
264 |
-
# Gradio interface
|
265 |
with gr.Blocks() as demo:
|
266 |
-
gr.
|
267 |
-
gr.
|
268 |
-
|
269 |
-
|
270 |
-
msg = gr.Textbox(label="Type your message here...")
|
271 |
-
clear = gr.Button("Clear")
|
272 |
-
|
273 |
-
emotion_state = gr.Textbox(label="Adam's Current Emotional State", lines=10)
|
274 |
-
reset_button = gr.Button("Reset Adam's Emotions")
|
275 |
-
|
276 |
-
def user(user_message, history):
|
277 |
-
response, updated_history, emotion_summary = respond_to_user(user_message, history)
|
278 |
-
return "", updated_history, emotion_summary
|
279 |
-
|
280 |
-
msg.submit(user, [msg, chatbot], [msg, chatbot, emotion_state])
|
281 |
-
clear.click(lambda: None, None, chatbot, queue=False)
|
282 |
-
reset_button.click(reset_emotions, None, emotion_state, queue=False)
|
283 |
|
284 |
if __name__ == "__main__":
|
285 |
demo.launch()
|
|
|
52 |
global _finetuned_lm_tokenizer, _finetuned_lm_model
|
53 |
if _finetuned_lm_tokenizer is None or _finetuned_lm_model is None:
|
54 |
model_name = "microsoft/DialoGPT-medium"
|
55 |
+
_finetuned_lm_tokenizer = AutoTokenizer.from_pretrained(model_name, padding_side='left')
|
56 |
_finetuned_lm_model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", low_cpu_mem_usage=True)
|
57 |
_finetuned_lm_tokenizer.pad_token = _finetuned_lm_tokenizer.eos_token
|
58 |
return _finetuned_lm_tokenizer, _finetuned_lm_model
|
|
|
119 |
|
120 |
def evaluate(individual):
|
121 |
emotion_values = individual[:len(emotions) - 1]
|
122 |
+
intensities = individual[len(emotions) - 1:-1]
|
123 |
ideal_state = individual[-1]
|
124 |
|
125 |
ideal_diff = abs(100 - ideal_state)
|
|
|
137 |
toolbox.register("attr_intensity", random.uniform, 0, 10)
|
138 |
toolbox.register("individual", tools.initCycle, creator.Individual,
|
139 |
(toolbox.attr_float,) * (len(emotions) - 1) +
|
140 |
+
(toolbox.attr_intensity,) * (len(emotions) - 1) +
|
141 |
(lambda: 100,), n=1)
|
142 |
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
|
143 |
toolbox.register("mate", tools.cxTwoPoint)
|
|
|
151 |
|
152 |
best_individual = tools.selBest(population, k=1)[0]
|
153 |
emotion_values = best_individual[:len(emotions) - 1]
|
154 |
+
intensities = best_individual[len(emotions) - 1:-1]
|
155 |
ideal_state = best_individual[-1]
|
156 |
|
157 |
for i, emotion in enumerate(emotions):
|
|
|
161 |
|
162 |
emotions['ideal_state']['percentage'] = ideal_state
|
163 |
|
164 |
+
def update_emotion_history(emotion, percentage, intensity, context):
|
165 |
+
entry = {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
166 |
'emotion': emotion,
|
167 |
+
'percentage': percentage,
|
168 |
'intensity': intensity,
|
169 |
+
'context': context,
|
170 |
'timestamp': pd.Timestamp.now().isoformat()
|
171 |
+
}
|
172 |
+
emotion_history.append(entry)
|
173 |
+
if len(emotion_history) > 100:
|
174 |
+
emotion_history.pop(0)
|
175 |
save_historical_data(emotion_history)
|
176 |
|
177 |
+
def predict_emotion(context):
|
178 |
+
tokens = emotion_prediction_tokenizer(context, return_tensors='pt', padding=True, truncation=True)
|
179 |
+
outputs = emotion_prediction_model(**tokens)
|
180 |
+
logits = outputs.logits
|
181 |
+
predicted_class = torch.argmax(logits, dim=1)
|
182 |
+
predicted_emotion = emotion_classes[predicted_class]
|
183 |
+
|
184 |
+
# Get percentage and intensity based on context
|
185 |
+
percentage = np.random.uniform(5, 20)
|
186 |
+
intensity = np.random.uniform(1, 10)
|
187 |
+
|
188 |
+
update_emotion(predicted_emotion, percentage, intensity)
|
189 |
+
update_emotion_history(predicted_emotion, percentage, intensity, context)
|
190 |
+
|
191 |
+
return predicted_emotion
|
192 |
+
|
193 |
+
def generate_response(context):
|
194 |
+
tokenizer, model = get_finetuned_lm_model()
|
195 |
+
inputs = tokenizer.encode(context, return_tensors='pt')
|
196 |
+
outputs = model.generate(inputs, max_length=500, num_return_sequences=1, pad_token_id=tokenizer.eos_token)
|
197 |
+
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
198 |
+
return response
|
199 |
+
|
200 |
+
def handle_conversation(user_input):
|
201 |
+
user_input = normalize_context(user_input)
|
202 |
predicted_emotion = predict_emotion(user_input)
|
203 |
+
bot_response = generate_response(user_input)
|
204 |
+
return f"Emotion: {predicted_emotion}, Response: {bot_response}"
|
205 |
+
|
206 |
+
def update_ui(user_input):
|
207 |
+
response = handle_conversation(user_input)
|
208 |
+
return response
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
209 |
|
|
|
210 |
with gr.Blocks() as demo:
|
211 |
+
user_input = gr.Textbox(label="User Input")
|
212 |
+
response = gr.Textbox(label="Bot Response")
|
213 |
+
submit = gr.Button("Submit")
|
214 |
+
submit.click(update_ui, user_input, response)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
215 |
|
216 |
if __name__ == "__main__":
|
217 |
demo.launch()
|