Sephfox commited on
Commit
53f69b8
·
verified ·
1 Parent(s): f8ff0d4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -94
app.py CHANGED
@@ -5,7 +5,6 @@ import os
5
  import json
6
  import random
7
  import gradio as gr
8
- import gradio.components
9
  import torch
10
  import torch.nn as nn
11
  import torch.optim as optim
@@ -185,107 +184,64 @@ def evolve_emotions():
185
  (lambda: random.uniform(80, 120),),
186
  n=1)
187
  toolbox.register("population", tools.initRepeat, list, toolbox.individual)
188
-
189
- toolbox.register("evaluate", evaluate)
190
- toolbox.register("mate", tools.cxSimulatedBinaryBounded, low=0, up=120, eta=20.0)
191
- toolbox.register("mutate", tools.mutPolynomialBounded, low=0, up=120, eta=20.0, indpb=0.1)
192
  toolbox.register("select", tools.selNSGA2)
 
 
 
 
 
193
 
194
- population = toolbox.population(n=50)
195
-
196
- for gen in range(25):
197
- offspring = algorithms.varAnd(population, toolbox, cxpb=0.7, mutpb=0.3)
198
- fits = toolbox.map(toolbox.evaluate, offspring)
199
- for fit, ind in zip(fits, offspring):
200
- ind.fitness.values = fit
201
- population = toolbox.select(offspring + population, k=len(population))
202
-
203
  best_individual = tools.selBest(population, k=1)[0]
204
-
205
- for idx, emotion in enumerate(emotions.keys()):
206
- if idx < len(emotions) - 1:
207
- emotions[emotion]['percentage'] = best_individual[idx]
208
- emotions[emotion]['intensity'] = best_individual[idx + len(emotions) - 1]
209
- else:
210
- emotions[emotion]['percentage'] = best_individual[-1]
211
-
212
- # Lazy loading for the language model
213
- def get_language_model():
214
- model_name = 'bigscience/bloom-1b7'
215
- tokenizer = AutoTokenizer.from_pretrained(model_name)
216
- lm_model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", low_cpu_mem_usage=True)
217
- return tokenizer, lm_model
218
-
219
- def generate_text(prompt, max_length=100):
220
- tokenizer, lm_model = get_language_model()
221
- input_ids = tokenizer.encode(prompt, return_tensors='pt').to(lm_model.device)
222
- with torch.no_grad():
223
- output = lm_model.generate(
224
- input_ids,
225
- max_length=max_length,
226
- num_return_sequences=1,
227
- no_repeat_ngram_size=2,
228
- do_sample=True,
229
- top_k=50,
230
- top_p=0.95,
231
- temperature=0.7
232
- )
233
- generated_text = tokenizer.decode(output[0], skip_special_tokens=True)
234
- return generated_text
235
-
236
- model_name = "distilbert-base-uncased-finetuned-sst-2-english"
237
- tokenizer = AutoTokenizer.from_pretrained(model_name)
238
- model = AutoModelForSequenceClassification.from_pretrained(model_name)
239
- sentiment_pipeline = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
240
- def get_sentiment(text):
241
- result = sentiment_pipeline(text)[0]
242
- return f"Sentiment: {result['label']}, Score: {result['score']:.4f}"
243
-
244
- def get_emotional_response(context):
245
- context = normalize_context(context)
246
- context_encoded = encoder.transform([[context]])
247
-
248
- # Neural network prediction
249
- with torch.no_grad():
250
- nn_output = model(torch.FloatTensor(context_encoded.toarray()).to(device))
251
- nn_prediction = nn_output.argmax(1).item()
252
-
253
- # Random Forest prediction
254
- rf_prediction = rf_model.predict(context_encoded)[0]
255
-
256
- # Weighted ensemble
257
- ensemble_prediction = (0.6 * nn_prediction + 0.4 * rf_prediction)
258
- predicted_emotion = emotion_classes[int(ensemble_prediction)]
259
-
260
- # Isolation Forest anomaly detection
261
- anomaly_score = isolation_forest.decision_function(context_encoded.toarray())
262
- is_anomaly = isolation_forest.predict(context_encoded.toarray())[0] == -1
263
-
264
- if is_anomaly:
265
- return "Anomaly detected in the emotional response."
266
-
267
- return f"Predicted Emotion: {predicted_emotion}"
268
-
269
- # Gradio interface
270
- def process_input(input_text):
271
- emotional_response = get_emotional_response(input_text)
272
- sentiment_response = get_sentiment(input_text)
273
- generated_text = generate_text(input_text)
274
- return {
275
- "Emotional Response": emotional_response,
276
- "Sentiment Response": sentiment_response,
277
- "Generated Text": generated_text
278
- }
279
 
280
  iface = gr.Interface(
281
  fn=process_input,
282
  inputs="text",
283
  outputs=[
284
- gr.Textbox(label="Emotional Response", interactive=False),
285
- gr.Textbox(label="Sentiment Response", interactive=False),
286
- gr.Textbox(label="Generated Text", interactive=False)
287
  ],
288
- allow_flagging="never"
289
  )
290
 
291
- iface.launch()
 
5
  import json
6
  import random
7
  import gradio as gr
 
8
  import torch
9
  import torch.nn as nn
10
  import torch.optim as optim
 
184
  (lambda: random.uniform(80, 120),),
185
  n=1)
186
  toolbox.register("population", tools.initRepeat, list, toolbox.individual)
187
+ toolbox.register("mate", tools.cxTwoPoint)
188
+ toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=1, indpb=0.2)
 
 
189
  toolbox.register("select", tools.selNSGA2)
190
+ toolbox.register("evaluate", evaluate)
191
+
192
+ population = toolbox.population(n=100)
193
+ algorithms.eaMuPlusLambda(population, toolbox, mu=50, lambda_=100, cxpb=0.7, mutpb=0.2, ngen=100,
194
+ stats=None, halloffame=None, verbose=False)
195
 
 
 
 
 
 
 
 
 
 
196
  best_individual = tools.selBest(population, k=1)[0]
197
+ emotion_values = best_individual[:len(emotions)-1]
198
+ intensities = best_individual[-21:-1]
199
+ ideal_state = best_individual[-1]
200
+
201
+ for i, emotion in enumerate(emotions):
202
+ emotions[emotion]['percentage'] = emotion_values[i]
203
+ emotions[emotion]['intensity'] = intensities[i]
204
+
205
+ emotions['ideal_state']['percentage'] = ideal_state
206
+
207
+ def process_input(text):
208
+ try:
209
+ normalized_text = normalize_context(text)
210
+ encoded_text = encoder.transform([[normalized_text]])
211
+
212
+ rf_prediction = rf_model.predict(encoded_text)[0]
213
+ isolation_score = isolation_forest.decision_function(encoded_text)[0]
214
+ nn_prediction = model(torch.FloatTensor(encoded_text.toarray()).to(device)).argmax(dim=1).item()
215
+
216
+ predicted_emotion = emotion_classes[rf_prediction]
217
+ sentiment_score = isolation_score
218
+ generated_text = emotion_classes[nn_prediction]
219
+
220
+ historical_data = load_historical_data()
221
+ historical_data.append({
222
+ 'context': text,
223
+ 'predicted_emotion': predicted_emotion,
224
+ 'sentiment_score': sentiment_score,
225
+ 'generated_text': generated_text
226
+ })
227
+ save_historical_data(historical_data)
228
+
229
+ return predicted_emotion, sentiment_score, generated_text
230
+
231
+ except Exception as e:
232
+ error_message = f"An error occurred: {str(e)}"
233
+ print(error_message) # Logging the error
234
+ return error_message, error_message, error_message
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
235
 
236
  iface = gr.Interface(
237
  fn=process_input,
238
  inputs="text",
239
  outputs=[
240
+ gr.outputs.Textbox(label="Emotional Response"),
241
+ gr.outputs.Textbox(label="Sentiment Response"),
242
+ gr.outputs.Textbox(label="Generated Text")
243
  ],
244
+ live=True
245
  )
246
 
247
+ iface.launch(share=True)