Unfaithful commited on
Commit
14e7f18
·
verified ·
1 Parent(s): d118dfb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +168 -58
app.py CHANGED
@@ -1,64 +1,174 @@
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
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
 
 
 
 
 
62
 
 
63
  if __name__ == "__main__":
64
- demo.launch()
 
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():
151
+ data_input = gr.Textbox(label="Enter Node Data")
152
+ add_button = gr.Button("Add Node")
153
+
154
+ output_text = gr.Textbox(label="Output", interactive=False)
155
+
156
+ # Navigation Section
157
+ with gr.Row():
158
+ child_index = gr.Number(label="Child Index", value=0, precision=0)
159
+ child_button = gr.Button("Go to Child")
160
+ parent_button = gr.Button("Go to Parent")
161
+
162
+ # Tree Visualization
163
+ tree_view_button = gr.Button("View Tree")
164
+ tree_view = gr.Image(label="Tree Structure")
165
 
166
+ # Connect Functions
167
+ add_button.click(add_node, inputs=[data_input], outputs=[output_text])
168
+ child_button.click(go_to_child, inputs=[child_index], outputs=[output_text])
169
+ parent_button.click(go_to_parent, outputs=[output_text])
170
+ tree_view_button.click(view_tree, outputs=[tree_view])
171
 
172
+ # Launch App
173
  if __name__ == "__main__":
174
+ app.launch()