Unfaithful commited on
Commit
fee153b
·
verified ·
1 Parent(s): ec22742

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -109
app.py CHANGED
@@ -1,150 +1,147 @@
1
- import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
  import gradio as gr
5
  from transformers import pipeline
6
  from graphviz import Digraph
7
- import sqlite3
8
  import os
9
 
10
- # Initialize AI model
 
 
 
11
  ai_model = pipeline("text-classification", model="distilbert-base-uncased-finetuned-sst-2-english")
12
 
13
- # Database setup
14
- DB_PATH = "fractal_tree.db"
15
-
16
- def init_db():
17
- """Initialize the SQLite database."""
18
- conn = sqlite3.connect(DB_PATH)
19
- cursor = conn.cursor()
20
- cursor.execute("""
21
- CREATE TABLE IF NOT EXISTS nodes (
22
- id INTEGER PRIMARY KEY AUTOINCREMENT,
23
- data TEXT,
24
- module TEXT,
25
- parent_id INTEGER,
26
- FOREIGN KEY(parent_id) REFERENCES nodes(id)
27
- )
28
- """)
29
- conn.commit()
30
- conn.close()
31
-
32
- def save_node(data, module, parent_id=None):
33
- """Save a node to the database."""
34
- conn = sqlite3.connect(DB_PATH)
35
- cursor = conn.cursor()
36
- cursor.execute("INSERT INTO nodes (data, module, parent_id) VALUES (?, ?, ?)", (data, module, parent_id))
37
- conn.commit()
38
- node_id = cursor.lastrowid
39
- conn.close()
40
- return node_id
41
-
42
- def get_node(node_id):
43
- """Retrieve a node by ID."""
44
- conn = sqlite3.connect(DB_PATH)
45
- cursor = conn.cursor()
46
- cursor.execute("SELECT * FROM nodes WHERE id = ?", (node_id,))
47
- node = cursor.fetchone()
48
- conn.close()
49
- return node
50
-
51
- def get_children(parent_id):
52
- """Retrieve children of a node."""
53
- conn = sqlite3.connect(DB_PATH)
54
- cursor = conn.cursor()
55
- cursor.execute("SELECT * FROM nodes WHERE parent_id = ?", (parent_id,))
56
- children = cursor.fetchall()
57
- conn.close()
58
- return children
59
-
60
- def build_graph():
61
- """Build a graphical representation of the tree."""
62
- conn = sqlite3.connect(DB_PATH)
63
- cursor = conn.cursor()
64
- cursor.execute("SELECT * FROM nodes")
65
- nodes = cursor.fetchall()
66
- conn.close()
67
-
68
- graph = Digraph()
69
- for node in nodes:
70
- graph.node(str(node[0]), f"{node[1]} ({node[2]})")
71
- if node[3]: # If parent_id exists
72
- graph.edge(str(node[3]), str(node[0]))
73
- return graph
74
-
75
- # Initialize database
76
- init_db()
77
-
78
- # Fractal Tree Manager
79
  class FractalTree:
80
  def __init__(self):
 
81
  self.current_node = None
82
- self.ensure_root_exists()
83
-
84
- def ensure_root_exists(self):
85
- """Ensure the root node exists."""
86
- conn = sqlite3.connect(DB_PATH)
87
- cursor = conn.cursor()
88
- cursor.execute("SELECT * FROM nodes WHERE parent_id IS NULL")
89
- root = cursor.fetchone()
90
- if not root:
91
- self.current_node = save_node("Root", "Root Module")
 
 
 
92
  else:
93
- self.current_node = root[0]
94
- conn.close()
 
95
 
96
  def add_node(self, data):
97
- """Add a new node as a child of the current node."""
98
- suggestion = ai_model(data)[0]['label'] # AI suggests a module
99
- node_id = save_node(data, suggestion, self.current_node)
100
- return f"Added node: '{data}' with module: '{suggestion}'"
 
 
 
 
 
 
 
101
 
102
  def go_to_child(self, index):
103
  """Navigate to a child node by index."""
104
- children = get_children(self.current_node)
105
- if 0 <= index < len(children):
106
- self.current_node = children[index][0]
107
- return f"Moved to child node: {children[index][1]}"
108
  return "Invalid child index."
109
 
110
  def go_to_parent(self):
111
  """Navigate to the parent node."""
112
- node = get_node(self.current_node)
113
- if node and node[3]:
114
- self.current_node = node[3]
115
- return f"Moved to parent node: {get_node(self.current_node)[1]}"
 
 
116
  return "Already at the root node."
117
 
118
- def view_tree(self):
119
- """Generate a visual representation of the tree."""
120
- graph = build_graph()
121
- graph_path = "/tmp/fractal_tree"
122
- graph.render(graph_path, format="png", cleanup=True)
123
- return graph_path + ".png"
124
-
125
- # Initialize fractal tree
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  fractal_tree = FractalTree()
127
 
128
  # Gradio Functions
129
  def add_node(data):
130
- """Add a new node."""
131
  return fractal_tree.add_node(data)
132
 
133
  def go_to_child(index):
134
- """Navigate to a child node."""
135
  return fractal_tree.go_to_child(int(index))
136
 
137
  def go_to_parent():
138
- """Navigate to the parent node."""
139
  return fractal_tree.go_to_parent()
140
 
141
  def view_tree():
142
- """Display the tree structure."""
143
- return fractal_tree.view_tree()
 
 
 
144
 
145
  # Gradio Interface
146
  with gr.Blocks() as app:
147
- gr.Markdown("# Emergent Fractal App")
148
 
149
  # Add Node Section
150
  with gr.Row():
 
 
 
 
1
  import gradio as gr
2
  from transformers import pipeline
3
  from graphviz import Digraph
4
+ import json
5
  import os
6
 
7
+ # File-based persistence
8
+ DB_FILE = "fractal_tree.json"
9
+
10
+ # AI Model Initialization
11
  ai_model = pipeline("text-classification", model="distilbert-base-uncased-finetuned-sst-2-english")
12
 
13
+
14
+ class Node:
15
+ def __init__(self, node_id, data, module, parent_id=None):
16
+ self.node_id = node_id
17
+ self.data = data
18
+ self.module = module
19
+ self.parent_id = parent_id
20
+ self.children = []
21
+
22
+ def to_dict(self):
23
+ """Convert Node to dictionary for JSON storage."""
24
+ return {
25
+ "node_id": self.node_id,
26
+ "data": self.data,
27
+ "module": self.module,
28
+ "parent_id": self.parent_id,
29
+ "children": [child.to_dict() for child in self.children],
30
+ }
31
+
32
+ @staticmethod
33
+ def from_dict(node_dict):
34
+ """Create Node from dictionary."""
35
+ node = Node(
36
+ node_dict["node_id"],
37
+ node_dict["data"],
38
+ node_dict["module"],
39
+ node_dict.get("parent_id"),
40
+ )
41
+ node.children = [Node.from_dict(child) for child in node_dict["children"]]
42
+ return node
43
+
44
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  class FractalTree:
46
  def __init__(self):
47
+ self.tree = None
48
  self.current_node = None
49
+ self.load_tree()
50
+
51
+ def save_tree(self):
52
+ """Save the tree to a JSON file."""
53
+ with open(DB_FILE, "w") as f:
54
+ json.dump(self.tree.to_dict(), f, indent=4)
55
+
56
+ def load_tree(self):
57
+ """Load the tree from a JSON file."""
58
+ if os.path.exists(DB_FILE):
59
+ with open(DB_FILE, "r") as f:
60
+ self.tree = Node.from_dict(json.load(f))
61
+ self.current_node = self.tree
62
  else:
63
+ self.tree = Node("0", "Root", "Root Module")
64
+ self.current_node = self.tree
65
+ self.save_tree()
66
 
67
  def add_node(self, data):
68
+ """Add a node as a child of the current node."""
69
+ suggestion = ai_model(data)[0]["label"]
70
+ new_node = Node(
71
+ node_id=str(len(self.tree.to_dict())), # Generate unique ID
72
+ data=data,
73
+ module=suggestion,
74
+ parent_id=self.current_node.node_id,
75
+ )
76
+ self.current_node.children.append(new_node)
77
+ self.save_tree()
78
+ return f"Added node with data: '{data}' and module: '{suggestion}'"
79
 
80
  def go_to_child(self, index):
81
  """Navigate to a child node by index."""
82
+ if 0 <= index < len(self.current_node.children):
83
+ self.current_node = self.current_node.children[index]
84
+ self.save_tree()
85
+ return f"Moved to child node: {self.current_node.data}"
86
  return "Invalid child index."
87
 
88
  def go_to_parent(self):
89
  """Navigate to the parent node."""
90
+ if self.current_node.parent_id:
91
+ parent_node = self.find_node(self.tree, self.current_node.parent_id)
92
+ if parent_node:
93
+ self.current_node = parent_node
94
+ self.save_tree()
95
+ return f"Moved to parent node: {self.current_node.data}"
96
  return "Already at the root node."
97
 
98
+ def find_node(self, node, node_id):
99
+ """Recursively find a node by ID."""
100
+ if node.node_id == node_id:
101
+ return node
102
+ for child in node.children:
103
+ result = self.find_node(child, node_id)
104
+ if result:
105
+ return result
106
+ return None
107
+
108
+ def build_graph(self):
109
+ """Build a graph visualization of the tree."""
110
+ def traverse(node, graph, node_id="0"):
111
+ graph.node(node_id, f"{node.data} ({node.module})")
112
+ for idx, child in enumerate(node.children):
113
+ child_id = f"{node_id}-{idx}"
114
+ graph.edge(node_id, child_id)
115
+ traverse(child, graph, child_id)
116
+
117
+ graph = Digraph()
118
+ traverse(self.tree, graph)
119
+ return graph
120
+
121
+
122
+ # Initialize Fractal Tree
123
  fractal_tree = FractalTree()
124
 
125
  # Gradio Functions
126
  def add_node(data):
 
127
  return fractal_tree.add_node(data)
128
 
129
  def go_to_child(index):
 
130
  return fractal_tree.go_to_child(int(index))
131
 
132
  def go_to_parent():
 
133
  return fractal_tree.go_to_parent()
134
 
135
  def view_tree():
136
+ graph = fractal_tree.build_graph()
137
+ graph_path = "/tmp/fractal_tree"
138
+ graph.render(graph_path, format="png", cleanup=True)
139
+ return graph_path + ".png"
140
+
141
 
142
  # Gradio Interface
143
  with gr.Blocks() as app:
144
+ gr.Markdown("# Emergent Fractal App with JSON Persistence")
145
 
146
  # Add Node Section
147
  with gr.Row():