File size: 9,201 Bytes
a403423
 
 
 
 
4b172ec
a403423
 
 
 
 
6ea58c0
a403423
ef464fc
4b172ec
a403423
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b172ec
a403423
 
 
 
 
 
 
4b172ec
a403423
 
 
 
 
4b172ec
a403423
 
4b172ec
a403423
 
4b172ec
a403423
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ea58c0
a403423
4b172ec
6ea58c0
 
 
a403423
6ea58c0
a403423
6ea58c0
 
 
 
a403423
6ea58c0
 
 
 
a403423
6ea58c0
 
 
 
ef464fc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
import numpy as np
import pandas as pd
import os
import json
import random
import gradio as gr
from sklearn.ensemble import IsolationForest
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
from sklearn.neural_network import MLPClassifier
from deap import base, creator, tools, algorithms
from transformers import GPTJForCausalLM, GPT2TokenizerFast
import torch
import torch.multiprocessing as mp

# Initialize Example Emotions Dataset
data = {
    'context': [
        'I am happy', 'I am sad', 'I am angry', 'I am excited', 'I am calm',
        'I am feeling joyful', 'I am grieving', 'I am feeling peaceful', 'I am frustrated',
        'I am determined', 'I feel resentment', 'I am feeling glorious', 'I am motivated',
        'I am surprised', 'I am fearful', 'I am trusting', 'I feel disgust', 'I am optimistic',
        'I am pessimistic', 'I feel bored', 'I am envious'
    ],
    'emotion': [
        'joy', 'sadness', 'anger', 'joy', 'calmness', 'joy', 'grief', 'calmness', 'anger',
        'determination', 'resentment', 'glory', 'motivation', 'surprise', 'fear', 'trust',
        'disgust', 'optimism', 'pessimism', 'boredom', 'envy'
    ]
}
df = pd.DataFrame(data)

# Encoding the contexts using One-Hot Encoding
encoder = OneHotEncoder(handle_unknown='ignore')
contexts_encoded = encoder.fit_transform(df[['context']]).toarray()

# Encoding emotions
emotions_target = df['emotion'].astype('category').cat.codes
emotion_classes = df['emotion'].astype('category').cat.categories

# Train Neural Network
X_train, X_test, y_train, y_test = train_test_split(contexts_encoded, emotions_target, test_size=0.2, random_state=42)
model = MLPClassifier(hidden_layer_sizes=(10, 10), max_iter=1000, random_state=42)
model.fit(X_train, y_train)

# Isolation Forest Anomaly Detection Model
historical_data = np.array([model.predict(contexts_encoded)]).T
isolation_forest = IsolationForest(contamination=0.1, random_state=42)
isolation_forest.fit(historical_data)

# Emotional States with 20 emotions
emotions = {
    'joy': {'percentage': 10, 'motivation': 'positive'},
    'pleasure': {'percentage': 10, 'motivation': 'selfish'},
    'sadness': {'percentage': 10, 'motivation': 'negative'},
    'grief': {'percentage': 10, 'motivation': 'negative'},
    'anger': {'percentage': 10, 'motivation': 'traumatic or strong'},
    'calmness': {'percentage': 10, 'motivation': 'neutral'},
    'determination': {'percentage': 10, 'motivation': 'positive'},
    'resentment': {'percentage': 10, 'motivation': 'negative'},
    'glory': {'percentage': 10, 'motivation': 'positive'},
    'motivation': {'percentage': 10, 'motivation': 'positive'},
    'ideal_state': {'percentage': 100, 'motivation': 'balanced'},
    'fear': {'percentage': 10, 'motivation': 'defensive'},
    'surprise': {'percentage': 10, 'motivation': 'unexpected'},
    'anticipation': {'percentage': 10, 'motivation': 'predictive'},
    'trust': {'percentage': 10, 'motivation': 'reliable'},
    'disgust': {'percentage': 10, 'motivation': 'repulsive'},
    'optimism': {'percentage': 10, 'motivation': 'hopeful'},
    'pessimism': {'percentage': 10, 'motivation': 'doubtful'},
    'boredom': {'percentage': 10, 'motivation': 'indifferent'},
    'envy': {'percentage': 10, 'motivation': 'jealous'}
}

# Adjust all emotions to a total of 200%
total_percentage = 200
default_percentage = total_percentage / len(emotions)
for emotion in emotions:
    emotions[emotion]['percentage'] = default_percentage

emotion_history_file = 'emotion_history.json'

# Load historical data from file if exists
def load_historical_data(file_path=emotion_history_file):
    if os.path.exists(file_path):
        with open(file_path, 'r') as file:
            return json.load(file)
    return []

# Save historical data to file
def save_historical_data(historical_data, file_path=emotion_history_file):
    with open(file_path, 'w') as file:
        json.dump(historical_data, file)

# Load previous emotional states
emotion_history = load_historical_data()

# Function to update emotions
def update_emotion(emotion, percentage):
    emotions['ideal_state']['percentage'] -= percentage
    emotions[emotion]['percentage'] += percentage

    # Ensure total percentage remains 200%
    total_current = sum(e['percentage'] for e in emotions.values())
    adjustment = total_percentage - total_current
    emotions['ideal_state']['percentage'] += adjustment

# Function to normalize context
def normalize_context(context):
    return context.lower().strip()

# Function to evolve emotions using genetic algorithm
def evolve_emotions():
    # Define the fitness function
    def evaluate(individual):
        ideal_state = individual[-1]  # Last value is the ideal state percentage
        other_emotions = individual[:-1]  # All other emotions
        return abs(ideal_state - 100), sum(other_emotions)

    # Register the genetic algorithm components
    creator.create("FitnessMin", base.Fitness, weights=(-1.0, -1.0))
    creator.create("Individual", list, fitness=creator.FitnessMin)

    # Create individuals and population
    toolbox = base.Toolbox()
    toolbox.register("attribute", lambda: random.uniform(0, 20))
    toolbox.register("individual", tools.initCycle, creator.Individual, toolbox.attribute, n=(len(emotions) - 1))
    toolbox.register("ideal_state", lambda: random.uniform(80, 120))
    toolbox.register("complete_individual", tools.initConcat, creator.Individual, toolbox.individual, toolbox.ideal_state)
    toolbox.register("population", tools.initRepeat, list, toolbox.complete_individual)

    # Register genetic operators
    toolbox.register("evaluate", evaluate)
    toolbox.register("mate", tools.cxBlend, alpha=0.5)
    toolbox.register("mutate", tools.mutGaussian, mu=10, sigma=5, indpb=0.3)
    toolbox.register("select", tools.selTournament, tournsize=3)

    # Initialize the population
    population = toolbox.population(n=10)

    # Run genetic algorithm
    population, log = algorithms.eaSimple(population, toolbox, cxpb=0.5, mutpb=0.2, ngen=20, verbose=False)

    # Update the emotions with the best individual
    best_individual = tools.selBest(population, k=1)[0]
    for idx, emotion in enumerate(emotions.keys()):
        emotions[emotion]['percentage'] = best_individual[idx]

# Function to get emotional response
def get_emotional_response(context):
    # Normalize context
    context = normalize_context(context)

    # Encode the context and predict the emotion using the neural network
    context_encoded = encoder.transform([[context]]).toarray()
    prediction = model.predict(context_encoded)
    predicted_emotion = emotion_classes[prediction[0]]

    # Check for anomalies using Isolation Forest
    anomaly_score = isolation_forest.decision_function([prediction])[0]
    if anomaly_score < -0.5:
        print("Anomalous context detected. Adjusting emotional response.")
        update_emotion('calmness', 20)
    else:
        # Define emotional responses
        if predicted_emotion == 'joy':
            update_emotion('joy', 20)
            update_emotion('pleasure', 20)
        elif predicted_emotion == 'sadness':
            update_emotion('sadness', 20)
            update_emotion('grief', 20)
        elif predicted_emotion == 'anger':
            update_emotion('anger', 20)
        elif predicted_emotion == 'determination':
            update_emotion('determination', 20)
        elif predicted_emotion == 'resentment':
            update_emotion('resentment', 20)
        elif predicted_emotion == 'glory':
            update_emotion('glory', 20)
        elif predicted_emotion == 'motivation':
            update_emotion('motivation', 20)
        elif predicted_emotion == 'surprise':
            update_emotion('surprise', 20)
        elif predicted_emotion == 'fear':
            update_emotion('fear', 20)
        elif predicted_emotion == 'trust':
            update_emotion('trust', 20)
        elif predicted_emotion == 'disgust':
            update_emotion('disgust', 20)
        elif predicted_emotion == 'optimism':
            update_emotion('optimism', 20)
        elif predicted_emotion == 'pessimism':
            update_emotion('pessimism', 20)
        elif predicted_emotion == 'boredom':
            update_emotion('boredom', 20)
        elif predicted_emotion == 'envy':
            update_emotion('envy', 20)
    
    # Evolve emotions
    evolve_emotions()

    # Save the updated emotion history
    emotion_history.append(emotions.copy())
    save_historical_data(emotion_history)

    return f"Emotion: {predicted_emotion}, Emotion Details: {emotions[predicted_emotion]}"

# Initialize the pre-trained language model
model_name = 'EleutherAI/gpt-j-6B'
tokenizer = GPT2TokenizerFast.from_pretrained(model_name)
lm_model = GPTJForCausalLM.from_pretrained(model_name)

# Multiprocessing context setting (ensure it's set only once)
if __name__ == '__main__':
    if mp.get_start_method(allow_none=True) != 'spawn':
        mp.set_start_method('spawn')

    # Example usage
    context_input = "I am feeling very joyful today"
    emotional_response = get_emotional_response(context_input)
    print(emotional_response)