Sephfox commited on
Commit
0f6ffbd
·
verified ·
1 Parent(s): b7412b9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -46
app.py CHANGED
@@ -155,68 +155,94 @@ def evolve_emotions():
155
  def predict_emotion(context):
156
  emotion_prediction_pipeline = pipeline('text-classification', model=emotion_prediction_model, tokenizer=emotion_prediction_tokenizer, top_k=None)
157
  predictions = emotion_prediction_pipeline(context)
158
- emotion_scores = {emotion['label']: emotion['score'] for emotion in predictions}
159
- emotion_pred = emotion_classes[np.argmax([emotion_scores.get(label, 0) for label in emotion_classes])]
160
  return emotion_pred
161
 
162
- def generate_text(prompt, model, tokenizer, max_length=50):
163
- input_ids = tokenizer.encode(prompt, return_tensors='pt')
164
- output = model.generate(input_ids, max_length=max_length, num_return_sequences=1)
165
- return tokenizer.decode(output[0], skip_special_tokens=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
 
167
  def optimize_ai_model(emotion_history):
168
- X = [normalize_context(e['context']) for e in emotion_history]
169
- y = [e['emotion'] for e in emotion_history]
170
-
171
- X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
172
 
173
- rf = RandomForestClassifier(n_estimators=100, random_state=42)
174
- rf.fit(X_train, y_train)
175
- score = rf.score(X_test, y_test)
176
- return rf, score
177
 
178
- def ai_response(input_text, emotion_model):
179
- emotion_pred = predict_emotion(input_text)
180
- context_emotion = {'context': input_text, 'emotion': emotion_pred}
181
- emotion_history.append(context_emotion)
182
- save_historical_data(emotion_history)
183
 
184
- percentage_change = random.randint(1, 10)
185
- intensity_change = random.randint(1, 10)
186
- update_emotion(emotion_pred, percentage_change, intensity_change)
187
 
188
- evolve_emotions()
189
 
190
- finetuned_tokenizer, finetuned_model = get_finetuned_lm_model()
191
- response_text = generate_text(input_text, finetuned_model, finetuned_tokenizer)
192
 
193
- return response_text
 
194
 
195
- def run_genetic_algorithm_parallel():
196
- num_cores = mp.cpu_count()
197
- results = Parallel(n_jobs=num_cores)(delayed(evolve_emotions)() for _ in range(3))
198
 
199
- def clear_emotion_history():
200
- global emotion_history
201
- emotion_history = []
 
202
  save_historical_data(emotion_history)
203
 
204
- # Gradio Interface
205
- def respond(input_text):
206
  emotion_model, score = optimize_ai_model(emotion_history)
207
- response = ai_response(input_text, emotion_model)
208
- return response, score
209
 
210
- with gr.Blocks() as app:
211
- gr.Markdown("# Advanced AI Model")
212
- input_text = gr.Textbox(label="Input Text")
213
- response_text = gr.Textbox(label="Response Text", interactive=False)
214
- model_score = gr.Number(label="Model Accuracy", interactive=False)
 
215
 
216
- respond_button = gr.Button("Respond")
217
- respond_button.click(fn=respond, inputs=[input_text], outputs=[response_text, model_score])
 
 
 
 
 
 
 
 
 
 
 
 
218
 
219
- clear_button = gr.Button("Clear Emotion History")
220
- clear_button.click(fn=clear_emotion_history, inputs=[], outputs=[])
221
 
222
- app.launch()
 
155
  def predict_emotion(context):
156
  emotion_prediction_pipeline = pipeline('text-classification', model=emotion_prediction_model, tokenizer=emotion_prediction_tokenizer, top_k=None)
157
  predictions = emotion_prediction_pipeline(context)
158
+ emotion_scores = {prediction['label']: prediction['score'] for prediction in predictions}
159
+ emotion_pred = max(emotion_scores, key=emotion_scores.get)
160
  return emotion_pred
161
 
162
+ def generate_text(prompt, max_length=100, emotion=None):
163
+ finetuned_lm_tokenizer, finetuned_lm_model = get_finetuned_lm_model()
164
+ input_ids = finetuned_lm_tokenizer.encode(prompt, return_tensors='pt')
165
+ attention_mask = torch.ones(input_ids.shape, dtype=torch.long)
166
+
167
+ if torch.cuda.is_available():
168
+ input_ids = input_ids.cuda()
169
+ attention_mask = attention_mask.cuda()
170
+ finetuned_lm_model = finetuned_lm_model.cuda()
171
+
172
+ if emotion:
173
+ emotion_token = emotion_prediction_tokenizer.encode(emotion, add_special_tokens=False)
174
+ input_ids = torch.cat((input_ids, torch.tensor(emotion_token).unsqueeze(0)), dim=1)
175
+
176
+ outputs = finetuned_lm_model.generate(
177
+ input_ids=input_ids,
178
+ attention_mask=attention_mask,
179
+ max_length=max_length,
180
+ pad_token_id=finetuned_lm_tokenizer.eos_token_id,
181
+ num_return_sequences=1,
182
+ temperature=0.7,
183
+ top_p=0.9,
184
+ do_sample=True
185
+ )
186
+
187
+ return finetuned_lm_tokenizer.decode(outputs[0], skip_special_tokens=True)
188
 
189
  def optimize_ai_model(emotion_history):
190
+ if not emotion_history:
191
+ return None, None
 
 
192
 
193
+ contexts = [entry['context'] for entry in emotion_history]
194
+ emotions = [entry['emotion'] for entry in emotion_history]
 
 
195
 
196
+ encoder = OneHotEncoder(handle_unknown='ignore', sparse=False)
197
+ X = encoder.fit_transform(np.array(contexts).reshape(-1, 1))
198
+ y = np.array(pd.Categorical(emotions).codes)
 
 
199
 
200
+ if len(X) == 0 or len(y) == 0:
201
+ return None, None
 
202
 
203
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
204
 
205
+ classifier = RandomForestClassifier(n_estimators=100, random_state=42)
206
+ classifier.fit(X_train, y_train)
207
 
208
+ score = classifier.score(X_test, y_test)
209
+ return classifier, score
210
 
211
+ def respond(context, previous_responses, previous_emotions):
212
+ normalized_context = normalize_context(context)
213
+ emotion_pred = predict_emotion(normalized_context)
214
 
215
+ emotion_history.append({
216
+ 'context': normalized_context,
217
+ 'emotion': emotion_pred
218
+ })
219
  save_historical_data(emotion_history)
220
 
 
 
221
  emotion_model, score = optimize_ai_model(emotion_history)
 
 
222
 
223
+ evolve_emotions()
224
+
225
+ response_prompt = f"{normalized_context}\n\n{previous_responses}\n\n{emotion_pred}"
226
+ generated_response = generate_text(response_prompt, emotion=emotion_pred)
227
+
228
+ return generated_response, emotion_pred
229
 
230
+ # GUI with Gradio
231
+ with gr.Blocks() as demo:
232
+ context_input = gr.Textbox(label="Context")
233
+ response_output = gr.Textbox(label="Generated Response")
234
+ emotion_output = gr.Textbox(label="Detected Emotion")
235
+
236
+ conversation_history = gr.State([])
237
+ emotion_history_state = gr.State([])
238
+
239
+ def respond_wrapper(context, conversation_history, emotion_history_state):
240
+ response, emotion = respond(context, conversation_history, emotion_history_state)
241
+ conversation_history.append(response)
242
+ emotion_history_state.append(emotion)
243
+ return response, emotion, conversation_history, emotion_history_state
244
 
245
+ submit_button = gr.Button("Submit")
246
+ submit_button.click(respond_wrapper, [context_input, conversation_history, emotion_history_state], [response_output, emotion_output, conversation_history, emotion_history_state])
247
 
248
+ demo.launch(share=True)