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()