Aluode commited on
Commit
fda9246
·
verified ·
1 Parent(s): 23f2f3b

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +285 -0
  2. readme (3).md +56 -0
  3. requirements.txt +7 -0
app.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pickle
3
+ import gradio as gr
4
+ import matplotlib.pyplot as plt
5
+ from mpl_toolkits.mplot3d import Axes3D
6
+ from io import BytesIO
7
+ from PIL import Image
8
+ import random
9
+ import requests
10
+ from bs4 import BeautifulSoup
11
+ import time
12
+ import networkx as nx
13
+
14
+ # Constants
15
+ MAX_DEPTH = 15
16
+ MAX_CHILDREN = 5
17
+ SPACE_SIZE = 10
18
+ GROWTH_PROBABILITY = 0.2 # Increased from 0.1
19
+
20
+ class FractalNode:
21
+ def __init__(self, node_id, position):
22
+ self.id = node_id
23
+ self.position = position
24
+ self.connections = {}
25
+ self.activation = 0.0
26
+
27
+ def activate(self, input_signal):
28
+ self.activation = np.tanh(input_signal)
29
+
30
+ def connect(self, other_node, weight):
31
+ self.connections[other_node.id] = weight
32
+
33
+ class FractalNetwork:
34
+ def __init__(self, initial_nodes=5, space_size=SPACE_SIZE):
35
+ self.nodes = {}
36
+ self.space_size = space_size
37
+ self.graph = nx.Graph()
38
+ self.cycle_count = 0
39
+ self.memory = ""
40
+ self.create_initial_nodes(initial_nodes)
41
+
42
+ def create_initial_nodes(self, num_nodes):
43
+ for i in range(num_nodes):
44
+ position = np.random.rand(3) * self.space_size
45
+ self.add_node(FractalNode(i, position))
46
+
47
+ def add_node(self, node):
48
+ self.nodes[node.id] = node
49
+ self.graph.add_node(node.id, pos=node.position)
50
+
51
+ def connect_nodes(self, node1, node2, weight):
52
+ node1.connect(node2, weight)
53
+ node2.connect(node1, weight)
54
+ self.graph.add_edge(node1.id, node2.id, weight=weight)
55
+
56
+ def grow(self):
57
+ new_node_id = len(self.nodes)
58
+ position = np.random.rand(3) * self.space_size
59
+ new_node = FractalNode(new_node_id, position)
60
+ self.add_node(new_node)
61
+
62
+ for node in self.nodes.values():
63
+ if node.id != new_node_id:
64
+ distance = np.linalg.norm(np.array(new_node.position) - np.array(node.position))
65
+ if distance < self.space_size * 0.2:
66
+ weight = np.random.rand()
67
+ self.connect_nodes(new_node, node, weight)
68
+
69
+ def hebbian_learning(self):
70
+ for node in self.nodes.values():
71
+ for other_node_id, weight in list(node.connections.items()):
72
+ other_node = self.nodes[other_node_id]
73
+ delta_weight = 0.01 * node.activation * other_node.activation
74
+ new_weight = np.clip(weight + delta_weight, 0, 1) # Clip weight to [0, 1]
75
+ node.connections[other_node_id] = new_weight
76
+ other_node.connections[node.id] = new_weight
77
+ self.graph[node.id][other_node_id]['weight'] = new_weight
78
+
79
+ def process_input(self, input_text):
80
+ input_signal = sum(ord(c) for c in input_text) / len(input_text) / 128
81
+ for node in self.nodes.values():
82
+ node.activate(input_signal)
83
+ self.hebbian_learning()
84
+ if random.random() < GROWTH_PROBABILITY:
85
+ self.grow()
86
+
87
+ def think(self):
88
+ self.cycle_count += 1
89
+ for node in self.nodes.values():
90
+ node.activate(np.random.rand())
91
+ self.hebbian_learning()
92
+ if random.random() < GROWTH_PROBABILITY:
93
+ self.grow()
94
+ return f"Cycle {self.cycle_count}: {chr(int(np.mean([node.activation for node in self.nodes.values()]) * 26) + 97)}"
95
+
96
+ def chat(self, input_text):
97
+ self.memory += input_text + " "
98
+ if len(self.memory) > 1000:
99
+ self.memory = self.memory[-1000:]
100
+ self.process_input(input_text)
101
+ response = ''.join(random.choice(self.memory) for _ in range(20))
102
+ self.cycle_count += 1
103
+ return f"Cycle {self.cycle_count}: {response}"
104
+
105
+ def save_state(self, filename):
106
+ with open(filename, 'wb') as f:
107
+ pickle.dump(self, f)
108
+
109
+ @staticmethod
110
+ def load_state(filename):
111
+ with open(filename, 'rb') as f:
112
+ return pickle.load(f)
113
+
114
+ def visualize(self, zoom=1.0):
115
+ fig = plt.figure(figsize=(10, 8))
116
+ ax = fig.add_subplot(111, projection='3d')
117
+
118
+ pos = nx.get_node_attributes(self.graph, 'pos')
119
+
120
+ for edge in self.graph.edges():
121
+ start = pos[edge[0]]
122
+ end = pos[edge[1]]
123
+ weight = self.graph[edge[0]][edge[1]]['weight']
124
+ ax.plot([start[0], end[0]], [start[1], end[1]], [start[2], end[2]],
125
+ color='b', alpha=min(weight, 1.0), linewidth=weight*3)
126
+
127
+ for node_id, node_pos in pos.items():
128
+ ax.scatter(node_pos[0], node_pos[1], node_pos[2],
129
+ color='r', s=100*self.nodes[node_id].activation+50)
130
+
131
+ center = self.space_size / 2
132
+ ax.set_xlim(center - self.space_size/(2*zoom), center + self.space_size/(2*zoom))
133
+ ax.set_ylim(center - self.space_size/(2*zoom), center + self.space_size/(2*zoom))
134
+ ax.set_zlim(center - self.space_size/(2*zoom), center + self.space_size/(2*zoom))
135
+ plt.title(f"Fractal Network - {len(self.nodes)} nodes")
136
+
137
+ buf = BytesIO()
138
+ plt.savefig(buf, format='png')
139
+ buf.seek(0)
140
+ plt.close(fig)
141
+ image = Image.open(buf)
142
+ return image
143
+
144
+ def fetch_wikipedia_content(topic):
145
+ url = f"https://en.wikipedia.org/wiki/{topic}"
146
+ response = requests.get(url)
147
+ if response.status_code == 200:
148
+ soup = BeautifulSoup(response.content, 'html.parser')
149
+ paragraphs = soup.find_all('p')
150
+ content = ' '.join([p.text for p in paragraphs])
151
+ return content
152
+ else:
153
+ return None
154
+
155
+ def gradio_interface():
156
+ network = FractalNetwork()
157
+ zoom_level = 1.0
158
+
159
+ def cycle_ai(num_cycles):
160
+ nonlocal zoom_level
161
+ thoughts = []
162
+ for _ in range(num_cycles):
163
+ thought = network.think()
164
+ thoughts.append(thought)
165
+
166
+ image = network.visualize(zoom_level)
167
+
168
+ return "\n".join(thoughts), image
169
+
170
+ def save_state(filename):
171
+ if filename.strip() == "":
172
+ return "Please enter a valid filename."
173
+ try:
174
+ network.save_state(filename)
175
+ return f"Network state saved as {filename}"
176
+ except Exception as e:
177
+ return f"Error saving network state: {str(e)}"
178
+
179
+ def load_state(file):
180
+ if file is None:
181
+ return "Please upload a file."
182
+ try:
183
+ loaded_network = FractalNetwork.load_state(file.name)
184
+ nonlocal network
185
+ network = loaded_network
186
+ return f"Loaded network state from {file.name}"
187
+ except Exception as e:
188
+ return f"Error loading network state: {str(e)}"
189
+
190
+ def recreate_network(initial_nodes):
191
+ nonlocal network, zoom_level
192
+ network = FractalNetwork(initial_nodes=initial_nodes)
193
+ image = network.visualize(zoom_level)
194
+ return f"Network recreated with {initial_nodes} initial nodes", image
195
+
196
+ def train_on_wikipedia(topic):
197
+ nonlocal zoom_level
198
+ content = fetch_wikipedia_content(topic)
199
+ if content:
200
+ chunks = [content[i:i+500] for i in range(0, len(content), 500)]
201
+ thoughts = []
202
+ for chunk in chunks:
203
+ network.process_input(chunk)
204
+ thoughts.append(f"Processed chunk: {network.think()}")
205
+
206
+ image = network.visualize(zoom_level)
207
+ return "\n".join(thoughts), image
208
+ else:
209
+ return f"Could not retrieve content for topic: {topic}", None
210
+
211
+ def chat_with_ai(input_text):
212
+ nonlocal zoom_level
213
+ response = network.chat(input_text)
214
+ image = network.visualize(zoom_level)
215
+ return response, image
216
+
217
+ def self_conversation(num_cycles):
218
+ nonlocal zoom_level
219
+ thoughts = []
220
+ for _ in range(num_cycles):
221
+ thought = network.think()
222
+ thoughts.append(thought)
223
+
224
+ image = network.visualize(zoom_level)
225
+
226
+ time.sleep(0.1) # Add a small delay to make the process visible
227
+
228
+ yield "\n".join(thoughts), image
229
+
230
+ def update_zoom(zoom_factor):
231
+ nonlocal zoom_level
232
+ zoom_level *= zoom_factor
233
+ image = network.visualize(zoom_level)
234
+ return image
235
+
236
+ with gr.Blocks() as demo:
237
+ gr.Markdown("# Advanced Fractal AI with Visualization and Interaction")
238
+
239
+ with gr.Row():
240
+ num_cycles = gr.Number(label="Number of Cycles", value=1, precision=0)
241
+ cycle_button = gr.Button("Run Cycles")
242
+
243
+ output_text = gr.Textbox(label="AI Thoughts", lines=5)
244
+ fractal_viz = gr.Image(label="Fractal Visualization")
245
+
246
+ with gr.Row():
247
+ zoom_in = gr.Button("Zoom In")
248
+ zoom_out = gr.Button("Zoom Out")
249
+
250
+ with gr.Row():
251
+ save_name = gr.Textbox(label="Save filename:")
252
+ save_btn = gr.Button("Save Network State")
253
+
254
+ load_file = gr.File(label="Load Network State")
255
+
256
+ initial_nodes_slider = gr.Slider(minimum=1, maximum=20, step=1, value=5, label="Initial Nodes")
257
+ recreate_btn = gr.Button("Recreate Network")
258
+
259
+ wiki_topic = gr.Textbox(label="Wikipedia Topic:")
260
+ wiki_btn = gr.Button("Train on Wikipedia")
261
+
262
+ chat_input = gr.Textbox(label="Chat with Fractal AI")
263
+ chat_output = gr.Textbox(label="Fractal AI Response", lines=3)
264
+ chat_button = gr.Button("Send")
265
+
266
+ self_convo_cycles = gr.Number(label="Self-Conversation Cycles", value=10, precision=0)
267
+ self_convo_button = gr.Button("Start Self-Conversation")
268
+
269
+ # Connect components
270
+ cycle_button.click(cycle_ai, inputs=[num_cycles], outputs=[output_text, fractal_viz])
271
+ save_btn.click(save_state, inputs=[save_name], outputs=[output_text])
272
+ load_file.change(load_state, inputs=[load_file], outputs=[output_text])
273
+ recreate_btn.click(recreate_network, inputs=[initial_nodes_slider], outputs=[output_text, fractal_viz])
274
+ wiki_btn.click(train_on_wikipedia, inputs=[wiki_topic], outputs=[output_text, fractal_viz])
275
+ chat_button.click(chat_with_ai, inputs=[chat_input], outputs=[chat_output, fractal_viz])
276
+ self_convo_button.click(self_conversation, inputs=[self_convo_cycles], outputs=[output_text, fractal_viz])
277
+ zoom_in.click(update_zoom, inputs=[gr.State(1.2)], outputs=[fractal_viz])
278
+ zoom_out.click(update_zoom, inputs=[gr.State(0.8)], outputs=[fractal_viz])
279
+
280
+ return demo
281
+
282
+ # Launch the Gradio interface
283
+ if __name__ == "__main__":
284
+ demo = gradio_interface()
285
+ demo.launch()
readme (3).md ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Fractal AI with Visualization and Interaction
2
+
3
+ ## Description
4
+ This project implements an advanced Fractal AI system with dynamic growth, visualization, and interactive features. It combines concepts from fractal geometry, neural networks, and Hebbian learning to create a unique and evolving AI structure.
5
+
6
+ ## Features
7
+ - Dynamic fractal network growth
8
+ - 3D visualization of the fractal AI structure
9
+ - Hebbian learning for connection weight updates
10
+ - Interactive chat functionality
11
+ - Wikipedia integration for training
12
+ - Self-conversation mode
13
+ - State saving and loading
14
+ - Zoom functionality for detailed exploration
15
+
16
+ ## Installation
17
+
18
+ 1. Clone this repository:
19
+ ```
20
+ git clone https://github.com/yourusername/fractal-ai.git
21
+ cd fractal-ai
22
+ ```
23
+
24
+ 2. Install the required dependencies:
25
+ ```
26
+ pip install -r requirements.txt
27
+ ```
28
+
29
+ ## Usage
30
+
31
+ Run the main script:
32
+ ```
33
+ python fractal_ai.py
34
+ ```
35
+
36
+ This will launch a Gradio interface in your default web browser, where you can interact with the Fractal AI system.
37
+
38
+ ## Interface Options
39
+
40
+ - **Run Cycles**: Execute a specified number of thinking cycles
41
+ - **Train on Wikipedia**: Input a topic to train the AI on Wikipedia content
42
+ - **Chat**: Engage in a conversation with the AI
43
+ - **Self-Conversation**: Let the AI converse with itself
44
+ - **Zoom**: Explore the fractal structure in detail
45
+ - **Save/Load State**: Preserve or restore the AI's state
46
+
47
+ ## Contributors
48
+ - Antti Luode - Original concept and ideation
49
+ - ChatGPT - Assisted in code generation and problem-solving
50
+ - Claude (Anthropic) - Implemented core functionality and resolved issues
51
+
52
+ ## Acknowledgements
53
+ Special thanks to Antti Luode for the innovative and ambitious idea behind this project. The collaboration between human creativity and AI assistance has made this unique project possible.
54
+
55
+ ## License
56
+ This project is open-source and available under the MIT License.
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ numpy==1.21.5
2
+ matplotlib==3.5.2
3
+ gradio==3.23.0
4
+ networkx==2.8.4
5
+ requests==2.28.1
6
+ beautifulsoup4==4.11.1
7
+ pillow==9.3.0