File size: 8,600 Bytes
14e7f18
 
ce90055
fee153b
14e7f18
ac28957
 
14e7f18
fee153b
 
 
 
ac28957
 
fee153b
dd42f9d
fee153b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14e7f18
 
fee153b
14e7f18
fee153b
 
 
 
 
 
 
 
 
 
 
 
 
14e7f18
fee153b
 
 
14e7f18
ac28957
 
 
fee153b
ac28957
fee153b
 
ac28957
fee153b
ac28957
fee153b
ac28957
 
 
dd42f9d
 
 
ac28957
 
 
 
dd42f9d
 
 
 
 
 
 
 
 
ac28957
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fee153b
 
ce90055
 
 
 
 
 
 
 
ac28957
ce90055
fee153b
ce90055
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fee153b
 
 
14e7f18
 
ac28957
6f86fdb
 
 
ac28957
6f86fdb
 
ac28957
6f86fdb
ac28957
 
 
6f86fdb
 
 
14e7f18
6f86fdb
 
 
 
14e7f18
 
ac28957
14e7f18
ce90055
 
fee153b
ac28957
 
 
 
 
dd42f9d
 
 
 
 
ac28957
 
 
 
 
 
14e7f18
 
 
dd42f9d
14e7f18
ac28957
14e7f18
ac28957
ce90055
14e7f18
ac28957
14e7f18
ac28957
 
 
14e7f18
dd42f9d
 
 
 
 
6f86fdb
 
 
 
 
 
 
 
 
ac28957
 
 
 
ae70076
14e7f18
 
ac28957
dd42f9d
6f86fdb
 
 
 
 
 
ac28957
ae70076
14e7f18
ae70076
14e7f18
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
import gradio as gr
from transformers import pipeline
import plotly.graph_objects as go
import json
import os
import threading
import time

# File-based persistence
DB_FILE = "fractal_tree.json"

# AI Model Initialization
classification_model = pipeline("text-classification", model="distilbert-base-uncased-finetuned-sst-2-english")
generation_model = pipeline("text-generation", model="gpt2", max_length=50, temperature=0.7)


class Node:
    def __init__(self, node_id, data, module, parent_id=None):
        self.node_id = node_id
        self.data = data
        self.module = module
        self.parent_id = parent_id
        self.children = []

    def to_dict(self):
        """Convert Node to dictionary for JSON storage."""
        return {
            "node_id": self.node_id,
            "data": self.data,
            "module": self.module,
            "parent_id": self.parent_id,
            "children": [child.to_dict() for child in self.children],
        }

    @staticmethod
    def from_dict(node_dict):
        """Create Node from dictionary."""
        node = Node(
            node_dict["node_id"],
            node_dict["data"],
            node_dict["module"],
            node_dict.get("parent_id"),
        )
        node.children = [Node.from_dict(child) for child in node_dict["children"]]
        return node


class FractalTree:
    def __init__(self):
        self.tree = None
        self.current_node = None
        self.load_tree()

    def save_tree(self):
        """Save the tree to a JSON file."""
        with open(DB_FILE, "w") as f:
            json.dump(self.tree.to_dict(), f, indent=4)

    def load_tree(self):
        """Load the tree from a JSON file."""
        if os.path.exists(DB_FILE):
            with open(DB_FILE, "r") as f:
                self.tree = Node.from_dict(json.load(f))
                self.current_node = self.tree
        else:
            self.tree = Node("0", "Root", "Root Module")
            self.current_node = self.tree
            self.save_tree()

    def add_node(self, parent_node, data):
        """Add a node as a child of the given parent node."""
        suggestion = classification_model(data)[0]["label"]
        new_node = Node(
            node_id=f"{len(self.tree.to_dict())}-{len(parent_node.children)}",  # Unique ID
            data=data,
            module=suggestion,
            parent_id=parent_node.node_id,
        )
        parent_node.children.append(new_node)
        self.save_tree()
        return new_node

    def ai_expand_node(self, parent_node):
        """Generate intelligent node data using GPT-2."""
        prompt = f"Generate creative and context-aware suggestions based on: {parent_node.data}"
        response = generation_model(prompt, num_return_sequences=2)
        suggestions = [res["generated_text"].strip() for res in response]
        for suggestion in suggestions:
            self.add_node(parent_node, suggestion)

    def emergent_behavior(self, parent_node):
        """Apply emergent behaviors using intelligent inferences."""
        prompt = f"What would be an interesting idea or extension of the topic: {parent_node.data}?"
        response = generation_model(prompt, num_return_sequences=1)
        emergent_data = response[0]["generated_text"].strip()

        # Add emergent node
        return self.add_node(parent_node, emergent_data)

    def auto_expand(self, iterations=1, children_per_node=2):
        """Automatically expand the tree iteratively."""
        for _ in range(iterations):
            nodes_to_expand = self.get_all_nodes(self.tree)
            for node in nodes_to_expand:
                for _ in range(children_per_node):
                    self.ai_expand_node(node)

    def get_all_nodes(self, root_node):
        """Retrieve all nodes in the tree."""
        all_nodes = []

        def traverse(node):
            all_nodes.append(node)
            for child in node.children:
                traverse(child)

        traverse(root_node)
        return all_nodes

    def build_graph(self):
        """Build an interactive Plotly visualization of the tree."""
        nodes = []
        edges = []

        def traverse(node, parent=None):
            nodes.append(node.data)
            if parent is not None:
                edges.append((parent, node.data))
            for child in node.children:
                traverse(child, node.data)

        traverse(self.tree)

        # Build Plotly figure
        fig = go.Figure()
        for source, target in edges:
            fig.add_trace(go.Scatter(
                x=[nodes.index(source), nodes.index(target)],
                y=[-nodes.index(source), -nodes.index(target) - 1],
                mode="lines+markers+text",
                text=[source, target],
                line=dict(color="blue", width=2),
                marker=dict(size=10)
            ))
        fig.update_layout(title="Fractal Tree Visualization", showlegend=False)
        return fig


# Initialize Fractal Tree
fractal_tree = FractalTree()

# Background Automation for Iterative Expansion
stop_automation_event = threading.Event()

def start_automation(interval, iterations, children_per_node):
    """Automate tree expansion in the background."""
    stop_automation_event.clear()

    def automate():
        while not stop_automation_event.is_set():
            fractal_tree.auto_expand(iterations=iterations, children_per_node=children_per_node)
            time.sleep(interval)

    thread = threading.Thread(target=automate, daemon=True)
    thread.start()
    return "Automation started!"

def stop_automation():
    """Stop the background automation."""
    stop_automation_event.set()
    return "Automation stopped!"


# Gradio Functions
def view_tree():
    """Return Plotly interactive tree structure."""
    return fractal_tree.build_graph().to_html()

def add_custom_node(data):
    """Add a custom node to the current node."""
    fractal_tree.add_node(fractal_tree.current_node, data)
    return f"Added custom node with data: {data}"

def apply_emergent_behavior():
    """Apply emergent behavior to the current node."""
    result_node = fractal_tree.emergent_behavior(fractal_tree.current_node)
    return f"Added emergent behavior node: {result_node.data}"

def reset_tree():
    """Reset the entire fractal tree."""
    os.remove(DB_FILE) if os.path.exists(DB_FILE) else None
    fractal_tree.load_tree()
    return "Tree has been reset."


# Gradio Interface
with gr.Blocks() as app:
    gr.Markdown("# Intelligent AI Fractal Tree with Emergent Behaviors")

    # Tree Visualization Section
    with gr.Row():
        tree_view_button = gr.Button("View Tree")
        tree_view = gr.HTML(label="Tree Structure")

    # Add Custom Node Section
    with gr.Row():
        custom_node_input = gr.Textbox(label="Enter Custom Node Data")
        add_custom_node_button = gr.Button("Add Custom Node")
        add_custom_node_output = gr.Textbox(label="Output", interactive=False)

    # Emergent Behavior Section
    with gr.Row():
        emergent_behavior_button = gr.Button("Apply Emergent Behavior")
        emergent_behavior_output = gr.Textbox(label="Emergent Behavior Status", interactive=False)

    # Automation Controls Section
    with gr.Row():
        automation_interval = gr.Number(label="Interval (seconds)", value=10, precision=0)
        automation_iterations = gr.Number(label="Iterations per Cycle", value=1, precision=0)
        automation_children = gr.Number(label="Children per Node", value=2, precision=0)
        start_automation_button = gr.Button("Start Automation")
        stop_automation_button = gr.Button("Stop Automation")
        automation_status = gr.Textbox(label="Automation Status", interactive=False)

    # Reset Tree Section
    with gr.Row():
        reset_button = gr.Button("Reset Tree")
        reset_output = gr.Textbox(label="Reset Status", interactive=False)

    # Connect Functions
    tree_view_button.click(view_tree, outputs=[tree_view])
    add_custom_node_button.click(add_custom_node, inputs=[custom_node_input], outputs=[add_custom_node_output])
    emergent_behavior_button.click(apply_emergent_behavior, outputs=[emergent_behavior_output])
    start_automation_button.click(
        start_automation, 
        inputs=[automation_interval, automation_iterations, automation_children], 
        outputs=[automation_status]
    )
    stop_automation_button.click(stop_automation, outputs=[automation_status])
    reset_button.click(reset_tree, outputs=[reset_output])

# Launch App
if __name__ == "__main__":
    app.launch()