Sephfox commited on
Commit
a403423
·
verified ·
1 Parent(s): 208a6c7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +261 -52
app.py CHANGED
@@ -1,63 +1,272 @@
 
 
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
 
 
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
 
 
 
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
 
26
- messages.append({"role": "user", "content": message})
 
27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  response = ""
 
 
 
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
- """
43
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
44
- """
45
- demo = gr.ChatInterface(
46
- respond,
47
- additional_inputs=[
48
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
49
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
50
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
51
- gr.Slider(
52
- minimum=0.1,
53
- maximum=1.0,
54
- value=0.95,
55
- step=0.05,
56
- label="Top-p (nucleus sampling)",
57
- ),
58
- ],
59
- )
60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
- if __name__ == "__main__":
63
- demo.launch()
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ import os
4
+ import json
5
+ import random
6
  import gradio as gr
7
+ from sklearn.ensemble import IsolationForest
8
+ from sklearn.model_selection import train_test_split
9
+ from sklearn.preprocessing import OneHotEncoder
10
+ from sklearn.neural_network import MLPClassifier
11
+ from deap import base, creator, tools, algorithms
12
+ from transformers import BloomForCausalLM, BloomTokenizerFast
13
+ import torch
14
 
15
+ # Initialize Example Emotions Dataset
16
+ data = {
17
+ 'context': [
18
+ 'I am happy', 'I am sad', 'I am angry', 'I am excited', 'I am calm',
19
+ 'I am feeling joyful', 'I am grieving', 'I am feeling peaceful', 'I am frustrated',
20
+ 'I am determined', 'I feel resentment', 'I am feeling glorious', 'I am motivated',
21
+ 'I am surprised', 'I am fearful', 'I am trusting', 'I feel disgust', 'I am optimistic',
22
+ 'I am pessimistic', 'I feel bored', 'I am envious'
23
+ ],
24
+ 'emotion': [
25
+ 'joy', 'sadness', 'anger', 'joy', 'calmness', 'joy', 'grief', 'calmness', 'anger',
26
+ 'determination', 'resentment', 'glory', 'motivation', 'surprise', 'fear', 'trust',
27
+ 'disgust', 'optimism', 'pessimism', 'boredom', 'envy'
28
+ ]
29
+ }
30
+ df = pd.DataFrame(data)
31
+
32
+ # Encoding the contexts using One-Hot Encoding
33
+ encoder = OneHotEncoder(handle_unknown='ignore')
34
+ contexts_encoded = encoder.fit_transform(df[['context']]).toarray()
35
+
36
+ # Encoding emotions
37
+ emotions_target = df['emotion'].astype('category').cat.codes
38
+ emotion_classes = df['emotion'].astype('category').cat.categories
39
+
40
+ # Train Neural Network
41
+ X_train, X_test, y_train, y_test = train_test_split(contexts_encoded, emotions_target, test_size=0.2, random_state=42)
42
+ model = MLPClassifier(hidden_layer_sizes=(10, 10), max_iter=1000, random_state=42)
43
+ model.fit(X_train, y_train)
44
+
45
+ # Isolation Forest Anomaly Detection Model
46
+ historical_data = np.array([model.predict(contexts_encoded)]).T
47
+ isolation_forest = IsolationForest(contamination=0.1, random_state=42)
48
+ isolation_forest.fit(historical_data)
49
+
50
+ # Emotional States with 20 emotions
51
+ emotions = {
52
+ 'joy': {'percentage': 10, 'motivation': 'positive'},
53
+ 'pleasure': {'percentage': 10, 'motivation': 'selfish'},
54
+ 'sadness': {'percentage': 10, 'motivation': 'negative'},
55
+ 'grief': {'percentage': 10, 'motivation': 'negative'},
56
+ 'anger': {'percentage': 10, 'motivation': 'traumatic or strong'},
57
+ 'calmness': {'percentage': 10, 'motivation': 'neutral'},
58
+ 'determination': {'percentage': 10, 'motivation': 'positive'},
59
+ 'resentment': {'percentage': 10, 'motivation': 'negative'},
60
+ 'glory': {'percentage': 10, 'motivation': 'positive'},
61
+ 'motivation': {'percentage': 10, 'motivation': 'positive'},
62
+ 'ideal_state': {'percentage': 100, 'motivation': 'balanced'},
63
+ 'fear': {'percentage': 10, 'motivation': 'defensive'},
64
+ 'surprise': {'percentage': 10, 'motivation': 'unexpected'},
65
+ 'anticipation': {'percentage': 10, 'motivation': 'predictive'},
66
+ 'trust': {'percentage': 10, 'motivation': 'reliable'},
67
+ 'disgust': {'percentage': 10, 'motivation': 'repulsive'},
68
+ 'optimism': {'percentage': 10, 'motivation': 'hopeful'},
69
+ 'pessimism': {'percentage': 10, 'motivation': 'doubtful'},
70
+ 'boredom': {'percentage': 10, 'motivation': 'indifferent'},
71
+ 'envy': {'percentage': 10, 'motivation': 'jealous'}
72
+ }
73
+
74
+ # Adjust all emotions to a total of 200%
75
+ total_percentage = 200
76
+ default_percentage = total_percentage / len(emotions)
77
+ for emotion in emotions:
78
+ emotions[emotion]['percentage'] = default_percentage
79
+
80
+ emotion_history_file = 'emotion_history.json'
81
+
82
+ # Load historical data from file if exists
83
+ def load_historical_data(file_path=emotion_history_file):
84
+ if os.path.exists(file_path):
85
+ with open(file_path, 'r') as file:
86
+ return json.load(file)
87
+ return []
88
+
89
+ # Save historical data to file
90
+ def save_historical_data(historical_data, file_path=emotion_history_file):
91
+ with open(file_path, 'w') as file:
92
+ json.dump(historical_data, file)
93
+
94
+ # Load previous emotional states
95
+ emotion_history = load_historical_data()
96
+
97
+ # Function to update emotions
98
+ def update_emotion(emotion, percentage):
99
+ emotions['ideal_state']['percentage'] -= percentage
100
+ emotions[emotion]['percentage'] += percentage
101
+
102
+ # Ensure total percentage remains 200%
103
+ total_current = sum(e['percentage'] for e in emotions.values())
104
+ adjustment = total_percentage - total_current
105
+ emotions['ideal_state']['percentage'] += adjustment
106
+
107
+ # Function to normalize context
108
+ def normalize_context(context):
109
+ return context.lower().strip()
110
+
111
+ # Function to evolve emotions using genetic algorithm
112
+ def evolve_emotions():
113
+ # Define the fitness function
114
+ def evaluate(individual):
115
+ ideal_state = individual[-1] # Last value is the ideal state percentage
116
+ other_emotions = individual[:-1] # All other emotions
117
+ return abs(ideal_state - 100), sum(other_emotions)
118
+
119
+ # Register the genetic algorithm components
120
+ creator.create("FitnessMin", base.Fitness, weights=(-1.0, -1.0))
121
+ creator.create("Individual", list, fitness=creator.FitnessMin)
122
 
123
+ # Create individuals and population
124
+ toolbox = base.Toolbox()
125
+ toolbox.register("attribute", lambda: random.uniform(0, 20))
126
+ toolbox.register("individual", tools.initCycle, creator.Individual, toolbox.attribute, n=(len(emotions) - 1))
127
+ toolbox.register("ideal_state", lambda: random.uniform(80, 120))
128
+ toolbox.register("complete_individual", tools.initConcat, creator.Individual, toolbox.individual, toolbox.ideal_state)
129
+ toolbox.register("population", tools.initRepeat, list, toolbox.complete_individual)
130
 
131
+ # Register genetic operators
132
+ toolbox.register("evaluate", evaluate)
133
+ toolbox.register("mate", tools.cxBlend, alpha=0.5)
134
+ toolbox.register("mutate", tools.mutGaussian, mu=10, sigma=5, indpb=0.3)
135
+ toolbox.register("select", tools.selTournament, tournsize=3)
 
 
 
 
136
 
137
+ # Initialize the population
138
+ population = toolbox.population(n=10)
 
 
 
139
 
140
+ # Run genetic algorithm
141
+ population, log = algorithms.eaSimple(population, toolbox, cxpb=0.5, mutpb=0.2, ngen=20, verbose=False)
142
 
143
+ # Update the emotions with the best individual
144
+ best_individual = tools.selBest(population, k=1)[0]
145
+ for idx, emotion in enumerate(emotions.keys()):
146
+ emotions[emotion]['percentage'] = best_individual[idx]
147
+
148
+ # Function to get emotional response
149
+ def get_emotional_response(context):
150
+ # Normalize context
151
+ context = normalize_context(context)
152
+
153
+ # Encode the context and predict the emotion using the neural network
154
+ context_encoded = encoder.transform([[context]]).toarray()
155
+ prediction = model.predict(context_encoded)
156
+ predicted_emotion = emotion_classes[prediction[0]]
157
+
158
+ # Check for anomalies using Isolation Forest
159
+ anomaly_score = isolation_forest.decision_function([prediction])[0]
160
+ if anomaly_score < -0.5:
161
+ print("Anomalous context detected. Adjusting emotional response.")
162
+ update_emotion('calmness', 20)
163
+ else:
164
+ # Define emotional responses
165
+ if predicted_emotion == 'joy':
166
+ update_emotion('joy', 20)
167
+ update_emotion('pleasure', 20)
168
+ elif predicted_emotion == 'sadness':
169
+ update_emotion('sadness', 20)
170
+ update_emotion('grief', 20)
171
+ elif predicted_emotion == 'anger':
172
+ update_emotion('anger', 20)
173
+ elif predicted_emotion == 'determination':
174
+ update_emotion('determination', 20)
175
+ elif predicted_emotion == 'resentment':
176
+ update_emotion('resentment', 20)
177
+ elif predicted_emotion == 'glory':
178
+ update_emotion('glory', 20)
179
+ elif predicted_emotion == 'motivation':
180
+ update_emotion('motivation', 20)
181
+ elif predicted_emotion == 'surprise':
182
+ update_emotion('surprise', 20)
183
+ elif predicted_emotion == 'fear':
184
+ update_emotion('fear', 20)
185
+ elif predicted_emotion == 'trust':
186
+ update_emotion('trust', 20)
187
+ elif predicted_emotion == 'disgust':
188
+ update_emotion('disgust', 20)
189
+ elif predicted_emotion == 'optimism':
190
+ update_emotion('optimism', 20)
191
+ elif predicted_emotion == 'pessimism':
192
+ update_emotion('pessimism', 20)
193
+ elif predicted_emotion == 'boredom':
194
+ update_emotion('boredom', 20)
195
+ elif predicted_emotion == 'envy':
196
+ update_emotion('envy', 20)
197
+ else:
198
+ update_emotion('calmness', 20)
199
+
200
+ # Record the current emotional state in history
201
+ emotion_state = {emotion: data['percentage'] for emotion, data in emotions.items()}
202
+ emotion_history.append(emotion_state)
203
+
204
+ # Save the history to file
205
+ save_historical_data(emotion_history)
206
+
207
+ # Print the current emotional state
208
  response = ""
209
+ for emotion, data in emotions.items():
210
+ response += f"{emotion.capitalize()}: {data['percentage']:.2f}% ({data['motivation']} motivation)\n"
211
+
212
+ return response
213
 
214
+ # Function to handle idle state using genetic algorithm
215
+ def handle_idle_state():
216
+ evolve_emotions()
217
+ response = "Emotions evolved\n"
218
+ for emotion, data in emotions.items():
219
+ response += f"{emotion.capitalize()}: {data['percentage']:.2f}% ({data['motivation']} motivation)\n"
220
+ return response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
 
222
+ # S.O.U.L. (Self-Organizing Universal Learning) Function
223
+ class SOUL:
224
+ def __init__(self, model_name='bigscience/bloom-1b1'):
225
+ self.tokenizer = BloomTokenizerFast.from_pretrained(model_name)
226
+ self.model = BloomForCausalLM.from_pretrained(model_name)
227
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
228
+ self.model.to(self.device)
229
+
230
+ def generate_text(self, prompt, max_length=100):
231
+ inputs = self.tokenizer(prompt, return_tensors="pt").to(self.device)
232
+
233
+ # Generate
234
+ with torch.no_grad():
235
+ generate_ids = self.model.generate(
236
+ inputs.input_ids,
237
+ max_length=max_length,
238
+ num_return_sequences=1,
239
+ no_repeat_ngram_size=2,
240
+ do_sample=True,
241
+ top_k=50,
242
+ top_p=0.95,
243
+ temperature=0.7
244
+ )
245
+
246
+ return self.tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
247
+
248
+ def bridge_ai(self, prompt):
249
+ # Generate the response using BLOOM
250
+ bloom_response = self.generate_text(prompt)
251
+
252
+ # Get the emotional response
253
+ emotional_response = get_emotional_response(bloom_response)
254
+
255
+ return bloom_response, emotional_response
256
+
257
+ # Example usage of S.O.U.L. function
258
+ soul = SOUL()
259
+
260
+ def interact_with_soul(user_input):
261
+ bloom_response, emotional_response = soul.bridge_ai(user_input)
262
+ return bloom_response, emotional_response
263
+
264
+ iface = gr.Interface(
265
+ fn=interact_with_soul,
266
+ inputs="text",
267
+ outputs=["text", "text"],
268
+ title="S.O.U.L AI",
269
+ description="Enter a prompt to interact with the S.O.U.L AI, which will generate a response and provide an emotional analysis."
270
+ )
271
 
272
+ iface.launch()