Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
@@ -1,9 +1,3 @@
|
|
1 |
-
import warnings
|
2 |
-
import numpy as np
|
3 |
-
import pandas as pd
|
4 |
-
import os
|
5 |
-
import json
|
6 |
-
import random
|
7 |
import gradio as gr
|
8 |
import torch
|
9 |
from sklearn.preprocessing import OneHotEncoder
|
@@ -17,51 +11,24 @@ from nltk.chunk import ne_chunk
|
|
17 |
from textblob import TextBlob
|
18 |
import matplotlib.pyplot as plt
|
19 |
import seaborn as sns
|
20 |
-
import ssl
|
21 |
-
import spacy
|
22 |
-
from spacy import displacy
|
23 |
-
from collections import Counter
|
24 |
-
import en_core_web_sm
|
25 |
-
from gensim import corpora
|
26 |
-
from gensim.models import LdaModel
|
27 |
-
from gensim.utils import simple_preprocess
|
28 |
-
from neuralcoref import NeuralCoref
|
29 |
-
|
30 |
-
# NLTK data download
|
31 |
-
try:
|
32 |
-
_create_unverified_https_context = ssl._create_unverified_context
|
33 |
-
except AttributeError:
|
34 |
-
pass
|
35 |
-
else:
|
36 |
-
ssl._create_default_https_context = _create_unverified_https_context
|
37 |
|
38 |
-
|
|
|
|
|
39 |
nltk.download('vader_lexicon', quiet=True)
|
40 |
nltk.download('punkt', quiet=True)
|
41 |
nltk.download('averaged_perceptron_tagger', quiet=True)
|
42 |
nltk.download('maxent_ne_chunker', quiet=True)
|
43 |
-
|
44 |
-
# Set NLTK data path
|
45 |
-
nltk.data.path.append('/home/user/nltk_data')
|
46 |
-
|
47 |
-
warnings.filterwarnings('ignore', category=FutureWarning, module='huggingface_hub.file_download')
|
48 |
-
|
49 |
-
# Load spaCy model
|
50 |
-
nlp = en_core_web_sm.load()
|
51 |
-
|
52 |
-
# Add NeuralCoref to spaCy pipeline
|
53 |
-
coref = NeuralCoref(nlp.vocab)
|
54 |
-
nlp.add_pipe(coref, name='neuralcoref')
|
55 |
|
56 |
# Initialize Example Dataset (For Emotion Prediction)
|
57 |
data = {
|
58 |
'context': [
|
59 |
-
'I am
|
60 |
-
'I am
|
61 |
-
'I am determined
|
62 |
-
'I am
|
63 |
-
'I
|
64 |
-
'I am envious and jealous'
|
65 |
],
|
66 |
'emotion': [
|
67 |
'joy', 'sadness', 'anger', 'joy', 'calmness', 'joy', 'grief', 'calmness', 'anger',
|
@@ -83,39 +50,33 @@ emotions_target = pd.Categorical(df['emotion']).codes
|
|
83 |
emotion_classes = pd.Categorical(df['emotion']).categories
|
84 |
|
85 |
# Load pre-trained BERT model for emotion prediction
|
86 |
-
emotion_prediction_model =
|
87 |
-
emotion_prediction_tokenizer =
|
88 |
-
|
89 |
-
# Load pre-trained
|
90 |
-
|
91 |
-
response_tokenizer =
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
emotion_prediction_model = AutoModelForSequenceClassification.from_pretrained("bhadresh-savani/distilbert-base-uncased-emotion")
|
97 |
-
emotion_prediction_tokenizer = AutoTokenizer.from_pretrained("bhadresh-savani/distilbert-base-uncased-emotion")
|
98 |
-
response_model_name = "gpt2-xl"
|
99 |
-
response_tokenizer = AutoTokenizer.from_pretrained(response_model_name)
|
100 |
-
response_model = AutoModelForCausalLM.from_pretrained(response_model_name)
|
101 |
-
response_tokenizer.pad_token = response_tokenizer.eos_token
|
102 |
|
103 |
# Enhanced Emotional States
|
104 |
emotions = {
|
105 |
-
'joy': {'percentage':
|
106 |
-
'sadness': {'percentage':
|
107 |
-
'anger': {'percentage':
|
108 |
-
'fear': {'percentage': 10, 'motivation': '
|
109 |
-
'love': {'percentage':
|
110 |
-
'surprise': {'percentage': 10, 'motivation': '
|
111 |
-
'neutral': {'percentage':
|
112 |
}
|
113 |
|
114 |
total_percentage = 100
|
115 |
emotion_history_file = 'emotion_history.json'
|
116 |
global conversation_history
|
117 |
conversation_history = []
|
118 |
-
max_history_length =
|
119 |
|
120 |
def load_historical_data(file_path=emotion_history_file):
|
121 |
if os.path.exists(file_path):
|
@@ -141,6 +102,7 @@ def update_emotion(emotion, percentage, intensity):
|
|
141 |
def normalize_context(context):
|
142 |
return context.lower().strip()
|
143 |
|
|
|
144 |
creator.create("FitnessMulti", base.Fitness, weights=(-1.0, -0.5, -0.2))
|
145 |
creator.create("Individual", list, fitness=creator.FitnessMulti)
|
146 |
|
@@ -159,7 +121,6 @@ def evolve_emotions():
|
|
159 |
toolbox.register("attr_float", random.uniform, 0, 100)
|
160 |
toolbox.register("attr_intensity", random.uniform, 0, 10)
|
161 |
toolbox.register("individual", tools.initCycle, creator.Individual,
|
162 |
-
toolbox.register("individual", tools.initCycle, creator.Individual,
|
163 |
(toolbox.attr_float,) * len(emotions) +
|
164 |
(toolbox.attr_intensity,) * len(emotions), n=1)
|
165 |
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
|
@@ -176,8 +137,73 @@ def evolve_emotions():
|
|
176 |
emotion_values = best_individual[:len(emotions)]
|
177 |
intensities = best_individual[len(emotions):]
|
178 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
179 |
def predict_emotion(context):
|
180 |
-
load_models()
|
181 |
inputs = emotion_prediction_tokenizer(context, return_tensors="pt", truncation=True, max_length=512)
|
182 |
with torch.no_grad():
|
183 |
outputs = emotion_prediction_model(**inputs)
|
@@ -192,50 +218,12 @@ def sentiment_analysis(text):
|
|
192 |
return sentiment_scores
|
193 |
|
194 |
def extract_entities(text):
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
noun_phrases = [chunk.text for chunk in doc.noun_chunks]
|
202 |
-
|
203 |
-
# Key Phrases (using textrank algorithm)
|
204 |
-
from textacy.extract import keyterms as kt
|
205 |
-
keyterms = kt.textrank(doc, normalize="lemma", topn=5)
|
206 |
-
|
207 |
-
# Dependency Parsing
|
208 |
-
dependencies = [(token.text, token.dep_, token.head.text) for token in doc]
|
209 |
-
|
210 |
-
# Part-of-Speech Tagging
|
211 |
-
pos_tags = [(token.text, token.pos_) for token in doc]
|
212 |
-
|
213 |
-
return {
|
214 |
-
"named_entities": named_entities,
|
215 |
-
"noun_phrases": noun_phrases,
|
216 |
-
"key_phrases": keyterms,
|
217 |
-
"dependencies": dependencies,
|
218 |
-
"pos_tags": pos_tags
|
219 |
-
}
|
220 |
-
|
221 |
-
def analyze_context(text):
|
222 |
-
doc = nlp(text)
|
223 |
-
|
224 |
-
# Coreference resolution
|
225 |
-
resolved_text = doc._.coref_resolved
|
226 |
-
|
227 |
-
# Topic modeling
|
228 |
-
processed_text = simple_preprocess(resolved_text)
|
229 |
-
dictionary = corpora.Dictionary([processed_text])
|
230 |
-
corpus = [dictionary.doc2bow(processed_text)]
|
231 |
-
|
232 |
-
lda_model = LdaModel(corpus=corpus, id2word=dictionary, num_topics=3, random_state=42)
|
233 |
-
topics = lda_model.print_topics()
|
234 |
-
|
235 |
-
return {
|
236 |
-
"resolved_text": resolved_text,
|
237 |
-
"topics": topics
|
238 |
-
}
|
239 |
|
240 |
def analyze_text_complexity(text):
|
241 |
blob = TextBlob(text)
|
@@ -247,112 +235,92 @@ def analyze_text_complexity(text):
|
|
247 |
'subjectivity': blob.sentiment.subjectivity
|
248 |
}
|
249 |
|
250 |
-
def
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
emotions_df = pd.DataFrame([(e, d['percentage'], d['intensity']) for e, d in emotions.items()],
|
262 |
-
columns=['emotion', 'percentage', 'intensity'])
|
263 |
-
sns.barplot(x='emotion', y='percentage', data=emotions_df)
|
264 |
-
plt.title(f'Current Emotional State: {ai_emotion.capitalize()} ({ai_emotion_percentage:.2f}%)')
|
265 |
-
plt.xlabel('Emotion')
|
266 |
-
plt.ylabel('Percentage')
|
267 |
-
plt.xticks(rotation=90)
|
268 |
-
plt.savefig(emotion_visualization_path)
|
269 |
-
plt.close()
|
270 |
-
except Exception as e:
|
271 |
-
print(f"Error generating emotion visualization: {e}")
|
272 |
-
emotion_visualization_path = None
|
273 |
-
return emotion_visualization_path
|
274 |
-
|
275 |
-
def generate_response(ai_emotion, input_text, entities, context_analysis):
|
276 |
-
load_models()
|
277 |
-
prompt = f"As an AI assistant, I am currently feeling {ai_emotion}. My response will reflect this emotional state. "
|
278 |
-
prompt += f"The input text contains the following entities: {entities['named_entities']}. "
|
279 |
-
prompt += f"The main topics are: {context_analysis['topics']}. "
|
280 |
-
prompt += f"Considering this context, here's my response to '{input_text}': "
|
281 |
-
|
282 |
-
inputs = response_tokenizer(prompt, return_tensors="pt", padding=True, truncation=True, max_length=8192)
|
283 |
-
|
284 |
-
temperature = 0.7
|
285 |
-
if ai_emotion == 'anger':
|
286 |
-
temperature = 0.9
|
287 |
-
elif ai_emotion == 'joy':
|
288 |
-
temperature = 0.5
|
289 |
|
290 |
-
|
291 |
-
response_ids = response_model.generate(
|
292 |
-
inputs.input_ids,
|
293 |
-
attention_mask=inputs.attention_mask,
|
294 |
-
max_length=400,
|
295 |
-
num_return_sequences=1,
|
296 |
-
no_repeat_ngram_size=2,
|
297 |
-
do_sample=True,
|
298 |
-
top_k=50,
|
299 |
-
top_p=0.95,
|
300 |
-
temperature=temperature,
|
301 |
-
pad_token_id=response_tokenizer.eos_token_id
|
302 |
-
)
|
303 |
-
response = response_tokenizer.decode(response_ids[0], skip_special_tokens=True)
|
304 |
-
|
305 |
-
return response.strip()
|
306 |
|
307 |
def interactive_interface(input_text):
|
308 |
-
|
309 |
-
|
310 |
-
|
311 |
-
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
|
327 |
-
|
328 |
-
|
329 |
-
|
330 |
-
|
331 |
-
|
332 |
-
|
333 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
334 |
|
335 |
-
# Gradio interface
|
336 |
def gradio_interface(input_text):
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
|
343 |
-
|
344 |
-
|
345 |
-
|
346 |
-
|
347 |
-
|
|
|
|
|
348 |
|
|
|
349 |
iface = gr.Interface(
|
350 |
fn=gradio_interface,
|
351 |
inputs="text",
|
352 |
outputs=["text", gr.Image(type="filepath")],
|
353 |
-
title="Enhanced AI
|
354 |
-
description="Enter
|
355 |
)
|
356 |
|
357 |
if __name__ == "__main__":
|
358 |
-
iface.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
import torch
|
3 |
from sklearn.preprocessing import OneHotEncoder
|
|
|
11 |
from textblob import TextBlob
|
12 |
import matplotlib.pyplot as plt
|
13 |
import seaborn as sns
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
|
15 |
+
warnings.filterwarnings('ignore', category=FutureWarning, module='huggingface_hub.file_download')
|
16 |
+
|
17 |
+
# Download necessary NLTK data
|
18 |
nltk.download('vader_lexicon', quiet=True)
|
19 |
nltk.download('punkt', quiet=True)
|
20 |
nltk.download('averaged_perceptron_tagger', quiet=True)
|
21 |
nltk.download('maxent_ne_chunker', quiet=True)
|
22 |
+
nltk.download('words', quiet=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
|
24 |
# Initialize Example Dataset (For Emotion Prediction)
|
25 |
data = {
|
26 |
'context': [
|
27 |
+
'I am happy', 'I am sad', 'I am angry', 'I am excited', 'I am calm',
|
28 |
+
'I am feeling joyful', 'I am grieving', 'I am feeling peaceful', 'I am frustrated',
|
29 |
+
'I am determined', 'I feel resentment', 'I am feeling glorious', 'I am motivated',
|
30 |
+
'I am surprised', 'I am fearful', 'I am trusting', 'I feel disgust', 'I am optimistic',
|
31 |
+
'I am pessimistic', 'I feel bored', 'I am envious'
|
|
|
32 |
],
|
33 |
'emotion': [
|
34 |
'joy', 'sadness', 'anger', 'joy', 'calmness', 'joy', 'grief', 'calmness', 'anger',
|
|
|
50 |
emotion_classes = pd.Categorical(df['emotion']).categories
|
51 |
|
52 |
# Load pre-trained BERT model for emotion prediction
|
53 |
+
emotion_prediction_model = AutoModelForSequenceClassification.from_pretrained("bhadresh-savani/distilbert-base-uncased-emotion")
|
54 |
+
emotion_prediction_tokenizer = AutoTokenizer.from_pretrained("bhadresh-savani/distilbert-base-uncased-emotion")
|
55 |
+
|
56 |
+
# Load pre-trained LLM model and tokenizer for response generation with increased context window
|
57 |
+
response_model_name = "microsoft/DialoGPT-medium"
|
58 |
+
response_tokenizer = AutoTokenizer.from_pretrained(response_model_name)
|
59 |
+
response_model = AutoModelForCausalLM.from_pretrained(response_model_name)
|
60 |
+
|
61 |
+
# Set the pad token
|
62 |
+
response_tokenizer.pad_token = response_tokenizer.eos_token
|
|
|
|
|
|
|
|
|
|
|
|
|
63 |
|
64 |
# Enhanced Emotional States
|
65 |
emotions = {
|
66 |
+
'joy': {'percentage': 10, 'motivation': 'positive', 'intensity': 0},
|
67 |
+
'sadness': {'percentage': 10, 'motivation': 'negative', 'intensity': 0},
|
68 |
+
'anger': {'percentage': 10, 'motivation': 'traumatic or strong', 'intensity': 0},
|
69 |
+
'fear': {'percentage': 10, 'motivation': 'defensive', 'intensity': 0},
|
70 |
+
'love': {'percentage': 10, 'motivation': 'affectionate', 'intensity': 0},
|
71 |
+
'surprise': {'percentage': 10, 'motivation': 'unexpected', 'intensity': 0},
|
72 |
+
'neutral': {'percentage': 40, 'motivation': 'balanced', 'intensity': 0},
|
73 |
}
|
74 |
|
75 |
total_percentage = 100
|
76 |
emotion_history_file = 'emotion_history.json'
|
77 |
global conversation_history
|
78 |
conversation_history = []
|
79 |
+
max_history_length = 30
|
80 |
|
81 |
def load_historical_data(file_path=emotion_history_file):
|
82 |
if os.path.exists(file_path):
|
|
|
102 |
def normalize_context(context):
|
103 |
return context.lower().strip()
|
104 |
|
105 |
+
# Create FitnessMulti and Individual outside of evolve_emotions
|
106 |
creator.create("FitnessMulti", base.Fitness, weights=(-1.0, -0.5, -0.2))
|
107 |
creator.create("Individual", list, fitness=creator.FitnessMulti)
|
108 |
|
|
|
121 |
toolbox.register("attr_float", random.uniform, 0, 100)
|
122 |
toolbox.register("attr_intensity", random.uniform, 0, 10)
|
123 |
toolbox.register("individual", tools.initCycle, creator.Individual,
|
|
|
124 |
(toolbox.attr_float,) * len(emotions) +
|
125 |
(toolbox.attr_intensity,) * len(emotions), n=1)
|
126 |
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
|
|
|
137 |
emotion_values = best_individual[:len(emotions)]
|
138 |
intensities = best_individual[len(emotions):]
|
139 |
|
140 |
+
for i, (emotion, data) in enumerate(emotions.items()):
|
141 |
+
data['percentage'] = emotion_values[i]
|
142 |
+
data['intensity'] = intensities[i]
|
143 |
+
|
144 |
+
# Normalize percentages
|
145 |
+
total = sum(e['percentage'] for e in emotions.values())
|
146 |
+
for e in emotions:
|
147 |
+
emotions[e]['percentage'] = (emotions[e]['percentage'] / total) * 100
|
148 |
+
def update_emotion_history(emotion, percentage, intensity, context):
|
149 |
+
entry = {
|
150 |
+
'emotion': emotion,
|
151 |
+
'percentage': percentage,
|
152 |
+
'intensity': intensity,
|
153 |
+
'context': context,
|
154 |
+
'timestamp': pd.Timestamp.now().isoformat()
|
155 |
+
}
|
156 |
+
emotion_history.append(entry)
|
157 |
+
save_historical_data(emotion_history)
|
158 |
+
|
159 |
+
# Adding 443 features
|
160 |
+
additional_features = {}
|
161 |
+
for i in range(443):
|
162 |
+
additional_features[f'feature_{i+1}'] = 0
|
163 |
+
|
164 |
+
def feature_transformations():
|
165 |
+
global additional_features
|
166 |
+
for feature in additional_features:
|
167 |
+
additional_features[feature] += random.uniform(-1, 1)
|
168 |
+
|
169 |
+
def generate_response(input_text, ai_emotion):
|
170 |
+
global conversation_history
|
171 |
+
# Prepare a prompt based on the current emotion and input
|
172 |
+
prompt = f"You are an AI assistant currently feeling {ai_emotion}. Your response should reflect this emotion. Human: {input_text}\nAI:"
|
173 |
+
|
174 |
+
# Add conversation history to the prompt
|
175 |
+
for entry in conversation_history[-5:]: # Use last 5 entries for context
|
176 |
+
prompt = f"Human: {entry['user']}\nAI: {entry['response']}\n" + prompt
|
177 |
+
|
178 |
+
inputs = response_tokenizer(prompt, return_tensors="pt", padding=True, truncation=True, max_length=1024)
|
179 |
+
|
180 |
+
# Adjust generation parameters based on emotion
|
181 |
+
temperature = 0.7
|
182 |
+
if ai_emotion == 'anger':
|
183 |
+
temperature = 0.9 # More randomness for angry responses
|
184 |
+
elif ai_emotion == 'joy':
|
185 |
+
temperature = 0.5 # More focused responses for joyful state
|
186 |
+
|
187 |
+
with torch.no_grad():
|
188 |
+
response_ids = response_model.generate(
|
189 |
+
inputs.input_ids,
|
190 |
+
attention_mask=inputs.attention_mask,
|
191 |
+
max_length=1024,
|
192 |
+
num_return_sequences=1,
|
193 |
+
no_repeat_ngram_size=2,
|
194 |
+
do_sample=True,
|
195 |
+
top_k=50,
|
196 |
+
top_p=0.95,
|
197 |
+
temperature=temperature,
|
198 |
+
pad_token_id=response_tokenizer.eos_token_id
|
199 |
+
)
|
200 |
+
response = response_tokenizer.decode(response_ids[0], skip_special_tokens=True)
|
201 |
+
|
202 |
+
# Extract only the AI's response
|
203 |
+
response = response.split("AI:")[-1].strip()
|
204 |
+
return response
|
205 |
+
|
206 |
def predict_emotion(context):
|
|
|
207 |
inputs = emotion_prediction_tokenizer(context, return_tensors="pt", truncation=True, max_length=512)
|
208 |
with torch.no_grad():
|
209 |
outputs = emotion_prediction_model(**inputs)
|
|
|
218 |
return sentiment_scores
|
219 |
|
220 |
def extract_entities(text):
|
221 |
+
chunked = ne_chunk(pos_tag(word_tokenize(text)))
|
222 |
+
entities = []
|
223 |
+
for chunk in chunked:
|
224 |
+
if hasattr(chunk, 'label'):
|
225 |
+
entities.append(((' '.join(c[0] for c in chunk)), chunk.label()))
|
226 |
+
return entities
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
227 |
|
228 |
def analyze_text_complexity(text):
|
229 |
blob = TextBlob(text)
|
|
|
235 |
'subjectivity': blob.sentiment.subjectivity
|
236 |
}
|
237 |
|
238 |
+
def visualize_emotions():
|
239 |
+
emotions_df = pd.DataFrame([(e, d['percentage'], d['intensity']) for e, d in emotions.items()],
|
240 |
+
columns=['Emotion', 'Percentage', 'Intensity'])
|
241 |
+
|
242 |
+
plt.figure(figsize=(12, 6))
|
243 |
+
sns.barplot(x='Emotion', y='Percentage', data=emotions_df)
|
244 |
+
plt.title('Current Emotional State')
|
245 |
+
plt.xticks(rotation=45, ha='right')
|
246 |
+
plt.tight_layout()
|
247 |
+
plt.savefig('emotional_state.png')
|
248 |
+
plt.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
249 |
|
250 |
+
return 'emotional_state.png'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
251 |
|
252 |
def interactive_interface(input_text):
|
253 |
+
global conversation_history
|
254 |
+
try:
|
255 |
+
evolve_emotions()
|
256 |
+
predicted_emotion = predict_emotion(input_text)
|
257 |
+
sentiment_scores = sentiment_analysis(input_text)
|
258 |
+
entities = extract_entities(input_text)
|
259 |
+
text_complexity = analyze_text_complexity(input_text)
|
260 |
+
|
261 |
+
# Update AI's emotional state based on input
|
262 |
+
update_emotion(predicted_emotion, random.uniform(5, 15), random.uniform(0, 10))
|
263 |
+
|
264 |
+
# Determine AI's current dominant emotion
|
265 |
+
ai_emotion = max(emotions, key=lambda e: emotions[e]['percentage'])
|
266 |
+
|
267 |
+
# Generate response based on AI's emotion
|
268 |
+
response = generate_response(input_text, ai_emotion)
|
269 |
+
|
270 |
+
# Update conversation history
|
271 |
+
conversation_history.append({
|
272 |
+
'user': input_text,
|
273 |
+
'response': response
|
274 |
+
})
|
275 |
+
|
276 |
+
# Trim conversation history if it exceeds the maximum length
|
277 |
+
if len(conversation_history) > max_history_length:
|
278 |
+
conversation_history = conversation_history[-max_history_length:]
|
279 |
+
|
280 |
+
update_emotion_history(ai_emotion, emotions[ai_emotion]['percentage'], emotions[ai_emotion]['intensity'], input_text)
|
281 |
+
feature_transformations()
|
282 |
+
|
283 |
+
emotion_visualization = visualize_emotions()
|
284 |
+
|
285 |
+
analysis_result = {
|
286 |
+
'predicted_user_emotion': predicted_emotion,
|
287 |
+
'ai_emotion': ai_emotion,
|
288 |
+
'sentiment_scores': sentiment_scores,
|
289 |
+
'entities': entities,
|
290 |
+
'text_complexity': text_complexity,
|
291 |
+
'current_emotional_state': emotions,
|
292 |
+
'response': response,
|
293 |
+
'emotion_visualization': emotion_visualization
|
294 |
+
}
|
295 |
+
|
296 |
+
return analysis_result
|
297 |
+
except Exception as e:
|
298 |
+
print(f"An error occurred: {str(e)}")
|
299 |
+
return "I apologize, but I encountered an error while processing your input. Please try again."
|
300 |
|
|
|
301 |
def gradio_interface(input_text):
|
302 |
+
response = interactive_interface(input_text)
|
303 |
+
if isinstance(response, str):
|
304 |
+
return response, None
|
305 |
+
else:
|
306 |
+
return (
|
307 |
+
f"User Emotion: {response['predicted_user_emotion']}\n"
|
308 |
+
f"AI Emotion: {response['ai_emotion']}\n"
|
309 |
+
f"AI Response: {response['response']}\n\n"
|
310 |
+
f"Sentiment: {response['sentiment_scores']}\n"
|
311 |
+
f"Entities: {response['entities']}\n"
|
312 |
+
f"Text Complexity: {response['text_complexity']}\n",
|
313 |
+
response['emotion_visualization']
|
314 |
+
)
|
315 |
|
316 |
+
# Create Gradio interface
|
317 |
iface = gr.Interface(
|
318 |
fn=gradio_interface,
|
319 |
inputs="text",
|
320 |
outputs=["text", gr.Image(type="filepath")],
|
321 |
+
title="Enhanced Emotional AI Interface",
|
322 |
+
description="Enter text to interact with the AI and analyze emotions."
|
323 |
)
|
324 |
|
325 |
if __name__ == "__main__":
|
326 |
+
iface.launch(share=True)
|