Spaces:
Runtime error
Runtime error
acecalisto3
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -1,558 +1,402 @@
|
|
|
|
1 |
import subprocess
|
2 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
import black
|
4 |
from pylint import lint
|
5 |
from io import StringIO
|
6 |
-
import gradio as gr
|
7 |
-
import os
|
8 |
-
import json
|
9 |
-
import streamlit as st
|
10 |
-
from streamlit_ace import st_ace
|
11 |
-
from agent import (
|
12 |
-
PREFIX,
|
13 |
-
ACTION_PROMPT,
|
14 |
-
SEARCH_QUERY,
|
15 |
-
TASK_PROMPT,
|
16 |
-
READ_PROMPT,
|
17 |
-
ADD_PROMPT,
|
18 |
-
MODIFY_PROMPT,
|
19 |
-
UNDERSTAND_TEST_RESULTS,
|
20 |
-
COMPRESS_HISTORY,
|
21 |
-
LOG_PROMPT,
|
22 |
-
LOG_RESPONSE,
|
23 |
-
)
|
24 |
-
import importlib
|
25 |
-
import sys
|
26 |
-
|
27 |
-
def initialize_global_variables():
|
28 |
-
global HUGGING_FACE_REPO_URL, PROJECT_ROOT, AGENT_DIRECTORY, GRADIO_SERVER_PORT
|
29 |
-
HUGGING_FACE_REPO_URL = "https://huggingface.co/spaces/acecalisto3/CodeMixt"
|
30 |
-
PROJECT_ROOT = "projects"
|
31 |
-
AGENT_DIRECTORY = "agents"
|
32 |
-
GRADIO_SERVER_PORT = 7860 # Choose a consistently unused port
|
33 |
-
|
34 |
-
initialize_global_variables()
|
35 |
-
|
36 |
-
# Initialize session state attributes
|
37 |
-
for attr in ['chat_history', 'terminal_history', 'workspace_projects', 'available_agents', 'current_state']:
|
38 |
-
if attr not in st.session_state:
|
39 |
-
st.session_state[attr] = []
|
40 |
-
|
41 |
-
def save_agent_to_file(agent):
|
42 |
-
agents_path = os.path.join(PROJECT_ROOT, AGENT_DIRECTORY)
|
43 |
-
if not os.path.exists(agents_path):
|
44 |
-
os.makedirs(agents_path)
|
45 |
-
|
46 |
-
agent_file = os.path.join(agents_path, f"{agent.name}.txt")
|
47 |
-
config_file = os.path.join(agents_path, f"{agent.name}Config.txt")
|
48 |
-
|
49 |
-
with open(agent_file, "w") as file:
|
50 |
-
file.write(agent.create_agent_prompt())
|
51 |
-
|
52 |
-
with open(config_file, "w") as file:
|
53 |
-
file.write(f"Agent Name: {agent.name}\nDescription: {agent.description}")
|
54 |
-
|
55 |
-
st.session_state.available_agents.append(agent.name)
|
56 |
-
|
57 |
-
commit_and_push_changes(f"Add agent {agent.name}")
|
58 |
-
|
59 |
-
def load_agent_prompt(agent_name):
|
60 |
-
agent_file = os.path.join(AGENT_DIRECTORY, f"{agent_name}.txt")
|
61 |
-
if os.path.exists(agent_file):
|
62 |
-
with open(agent_file, "r") as file:
|
63 |
-
agent_prompt = file.read()
|
64 |
-
return agent_prompt
|
65 |
-
else:
|
66 |
-
return None
|
67 |
-
|
68 |
-
def create_agent_from_text(name, text):
|
69 |
-
skills = text.split('\n')
|
70 |
-
agent = AIAgent(name, "AI agent created from text input.", skills)
|
71 |
-
save_agent_to_file(agent)
|
72 |
-
return agent.create_agent_prompt()
|
73 |
-
|
74 |
-
# Global Variables
|
75 |
-
terminal_history = ""
|
76 |
-
|
77 |
-
# Component Library
|
78 |
-
components_registry = {
|
79 |
-
"Button": {
|
80 |
-
"properties": {"label": "Click Me", "onclick": ""},
|
81 |
-
"description": "A clickable button",
|
82 |
-
"code_snippet": 'gr.Button(value="{label}", variant="primary")',
|
83 |
-
},
|
84 |
-
"Text Input": {
|
85 |
-
"properties": {"value": "", "placeholder": "Enter text"},
|
86 |
-
"description": "A field for entering text",
|
87 |
-
"code_snippet": 'gr.Textbox(label="{placeholder}")',
|
88 |
-
},
|
89 |
-
"Image": {
|
90 |
-
"properties": {"src": "#", "alt": "Image"},
|
91 |
-
"description": "Displays an image",
|
92 |
-
"code_snippet": 'gr.Image(label="{alt}")',
|
93 |
-
},
|
94 |
-
"Dropdown": {
|
95 |
-
"properties": {"choices": ["Option 1", "Option 2"], "value": ""},
|
96 |
-
"description": "A dropdown menu for selecting options",
|
97 |
-
"code_snippet": 'gr.Dropdown(choices={choices}, label="Dropdown")',
|
98 |
-
},
|
99 |
-
# Add more components here...
|
100 |
-
}
|
101 |
-
|
102 |
-
# NLP Model (Example using Hugging Face)
|
103 |
-
nlp_model_names = [
|
104 |
-
"google/flan-t5-small",
|
105 |
-
"Qwen/CodeQwen1.5-7B-Chat-GGUF",
|
106 |
-
"bartowski/Codestral-22B-v0.1-GGUF",
|
107 |
-
"bartowski/AutoCoder-GGUF"
|
108 |
-
]
|
109 |
-
nlp_models = []
|
110 |
-
|
111 |
-
for nlp_model_name in nlp_model_names:
|
112 |
-
try:
|
113 |
-
cached_download(hf_hub_url(nlp_model_name, revision="main"))
|
114 |
-
nlp_models.append(InferenceClient(nlp_model_name))
|
115 |
-
except:
|
116 |
-
nlp_models.append(None)
|
117 |
-
|
118 |
-
# Function to get NLP model response
|
119 |
-
def get_nlp_response(input_text, model_index):
|
120 |
-
if nlp_models[model_index]:
|
121 |
-
response = nlp_models[model_index].text_generation(input_text)
|
122 |
-
return response.generated_text
|
123 |
-
else:
|
124 |
-
return "NLP model not available."
|
125 |
-
|
126 |
-
# Component Class
|
127 |
-
class Component:
|
128 |
-
def __init__(self, type, properties=None, id=None):
|
129 |
-
self.id = id or random.randint(1000, 9999)
|
130 |
-
self.type = type
|
131 |
-
self.properties = properties or components_registry[type]["properties"].copy()
|
132 |
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
def render(self):
|
141 |
-
# Properly format choices for Dropdown
|
142 |
-
if self.type == "Dropdown":
|
143 |
-
self.properties["choices"] = (
|
144 |
-
str(self.properties["choices"])
|
145 |
-
.replace("[", "")
|
146 |
-
.replace("]", "")
|
147 |
-
.replace("'", "")
|
148 |
-
)
|
149 |
-
return components_registry[self.type]["code_snippet"].format(**self.properties)
|
150 |
|
151 |
-
|
152 |
-
class AppCreationProcess:
|
153 |
def __init__(self):
|
154 |
-
self.
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
165 |
}
|
166 |
-
return f"Step {self.current_step}: {steps[self.current_step]}"
|
167 |
-
|
168 |
-
def add_component(self, component_type):
|
169 |
-
new_component = Component(component_type)
|
170 |
-
self.components.append(new_component.to_dict())
|
171 |
-
return self.update_app_canvas()
|
172 |
-
|
173 |
-
def set_component_property(self, component_id, property_name, property_value):
|
174 |
-
for component in self.components:
|
175 |
-
if component['id'] == component_id:
|
176 |
-
if property_name in component['properties']:
|
177 |
-
component['properties'][property_name.strip()] = property_value.strip()
|
178 |
-
return self.update_app_canvas(), f"Property '{property_name}' set to '{property_value}' for component {component_id}"
|
179 |
-
else:
|
180 |
-
return None, f"Error: Property '{property_name}' not found in component {component_id}"
|
181 |
-
return None, f"Error: Component with ID {component_id} not found."
|
182 |
-
|
183 |
-
def update_app_canvas(self):
|
184 |
-
components_html = "".join([
|
185 |
-
f"<div>Component ID: {component['id']}, Type: {component['type']}, Properties: {component['properties']}</div>"
|
186 |
-
for component in self.components
|
187 |
-
])
|
188 |
-
return components_html
|
189 |
-
|
190 |
-
def generate_python_code(self):
|
191 |
-
code = f"""import gradio as gr\n\nwith gr.Blocks() as {self.app_name}:\n"""
|
192 |
-
for component in self.components:
|
193 |
-
code += " " + Component(**component).render() + "\n"
|
194 |
-
code += f"\n{self.app_name}.launch()\n"
|
195 |
-
return code
|
196 |
|
197 |
-
def
|
198 |
-
|
199 |
-
code = self.generate_python_code()
|
200 |
-
# Create requirements.txt
|
201 |
-
with open("requirements.txt", "w") as f:
|
202 |
-
f.write("gradio==3.32.0\n")
|
203 |
-
# Create the app.py file
|
204 |
-
with open("app.py", "w") as f:
|
205 |
-
f.write(code)
|
206 |
-
# Execute the deployment command
|
207 |
try:
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
|
|
|
|
|
|
214 |
except Exception as e:
|
215 |
-
return f"
|
216 |
-
|
217 |
-
app_process = AppCreationProcess()
|
218 |
-
|
219 |
-
# Function to handle terminal input
|
220 |
-
def run_terminal_command(command, history):
|
221 |
-
global terminal_history
|
222 |
-
output = ""
|
223 |
-
try:
|
224 |
-
# Basic command parsing (expand with NLP)
|
225 |
-
if command.startswith("add "):
|
226 |
-
component_type = command.split("add ", 1)[1].strip()
|
227 |
-
output = app_process.add_component(component_type)
|
228 |
-
elif command.startswith("set "):
|
229 |
-
_, output = set_component_property(command)
|
230 |
-
elif command.startswith("search "):
|
231 |
-
search_query = command.split("search ", 1)[1].strip()
|
232 |
-
output = i_s(search_query)
|
233 |
-
elif command.startswith("deploy "):
|
234 |
-
output = app_process.deploy_to_huggingface()
|
235 |
-
else:
|
236 |
-
# Attempt to execute command as Python code
|
237 |
-
try:
|
238 |
-
result = subprocess.check_output(
|
239 |
-
command, shell=True, stderr=subprocess.STDOUT, text=True
|
240 |
-
)
|
241 |
-
output = result
|
242 |
-
except Exception as e:
|
243 |
-
output = f"Error executing Python code: {str(e)}"
|
244 |
-
except Exception as e:
|
245 |
-
output = f"Error: {str(e)}"
|
246 |
-
finally:
|
247 |
-
terminal_history += f"User: {command}\n{output}\n"
|
248 |
-
return terminal_history
|
249 |
-
|
250 |
-
def set_component_property(command):
|
251 |
-
try:
|
252 |
-
# Improved 'set' command parsing
|
253 |
-
set_parts = command.split(" ", 2)[1:]
|
254 |
-
if len(set_parts) != 2:
|
255 |
-
raise ValueError("Invalid 'set' command format.")
|
256 |
-
component_id = int(set_parts[0]) # Use component ID
|
257 |
-
property_name, property_value = set_parts[1].split("=", 1)
|
258 |
-
return app_process.set_component_property(component_id, property_name, property_value)
|
259 |
-
except Exception as e:
|
260 |
-
return None, f"Error: {str(e)}\n"
|
261 |
-
|
262 |
-
# Function to handle chat interaction
|
263 |
-
def run_chat(message, history):
|
264 |
-
global terminal_history
|
265 |
-
if message.startswith("!"):
|
266 |
-
command = message[1:]
|
267 |
-
terminal_history = run_terminal_command(command, history)
|
268 |
-
else:
|
269 |
-
model_index = 0 # Select the model to use for chat response
|
270 |
-
response = get_nlp_response(message, model_index)
|
271 |
-
if response:
|
272 |
-
return history, terminal_history + f"User: {message}\nAssistant: {response}"
|
273 |
-
else:
|
274 |
-
return history, terminal_history + f"User: {message}\nAssistant: I'm sorry, I couldn't generate a response. Please try again.\n"
|
275 |
-
|
276 |
-
# Gradio Interface
|
277 |
-
with gr.Blocks() as iface:
|
278 |
-
gr.Markdown("# Sequential App Builder")
|
279 |
-
|
280 |
-
with gr.Row():
|
281 |
-
current_step = gr.Markdown(app_process.get_current_step_info())
|
282 |
-
|
283 |
-
with gr.Row():
|
284 |
-
prev_button = gr.Button("Previous Step")
|
285 |
-
next_button = gr.Button("Next Step")
|
286 |
-
|
287 |
-
# Step 1: App Initialization
|
288 |
-
with gr.Group() as step1:
|
289 |
-
app_name_input = gr.Textbox(label="Enter App Name")
|
290 |
-
init_app_button = gr.Button("Initialize App")
|
291 |
|
292 |
-
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
|
298 |
-
|
299 |
-
|
300 |
-
|
301 |
-
|
302 |
-
|
303 |
-
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
|
310 |
-
|
311 |
-
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
chat_button = gr.Button("Send")
|
320 |
|
321 |
-
|
322 |
-
|
323 |
-
|
|
|
|
|
|
|
|
|
324 |
|
325 |
-
|
326 |
-
class AppCreationProcess:
|
327 |
def __init__(self):
|
328 |
-
|
329 |
-
self.
|
330 |
-
self.
|
331 |
-
|
332 |
-
|
333 |
-
|
334 |
-
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
|
|
|
|
|
|
|
|
|
|
|
339 |
}
|
340 |
-
|
341 |
-
|
342 |
-
def
|
343 |
-
|
344 |
-
self.
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
|
351 |
-
|
352 |
-
|
353 |
-
|
354 |
-
|
355 |
-
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
|
|
363 |
|
364 |
-
|
365 |
-
|
366 |
-
|
367 |
-
|
368 |
-
|
369 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
370 |
|
371 |
-
def
|
372 |
-
|
373 |
-
code = self.generate_python_code()
|
374 |
-
# Create requirements.txt
|
375 |
-
with open("requirements.txt", "w") as f:
|
376 |
-
f.write("gradio==3.32.0\n")
|
377 |
-
# Create the app.py file
|
378 |
-
with open("app.py", "w") as f:
|
379 |
-
f.write(code)
|
380 |
-
# Execute the deployment command
|
381 |
try:
|
382 |
-
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
388 |
except Exception as e:
|
389 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
390 |
|
391 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
392 |
|
393 |
-
|
394 |
-
def run_terminal_command(command, history):
|
395 |
-
global terminal_history
|
396 |
-
output = ""
|
397 |
-
try:
|
398 |
-
# Basic command parsing (expand with NLP)
|
399 |
-
if command.startswith("add "):
|
400 |
-
component_type = command.split("add ", 1)[1].strip()
|
401 |
-
output = app_process.add_component(component_type)
|
402 |
-
elif command.startswith("set "):
|
403 |
-
_, output = set_component_property(command)
|
404 |
-
elif command.startswith("search "):
|
405 |
-
search_query = command.split("search ", 1)[1].strip()
|
406 |
-
output = i_s(search_query)
|
407 |
-
elif command.startswith("deploy "):
|
408 |
-
output = app_process.deploy_to_huggingface()
|
409 |
-
else:
|
410 |
-
# Attempt to execute command as Python code
|
411 |
try:
|
412 |
-
|
413 |
-
|
|
|
|
|
414 |
)
|
415 |
-
output = result
|
416 |
except Exception as e:
|
417 |
-
|
418 |
-
except Exception as e:
|
419 |
-
output = f"Error: {str(e)}"
|
420 |
-
finally:
|
421 |
-
terminal_history += f"User: {command}\n{output}\n"
|
422 |
-
return terminal_history
|
423 |
|
424 |
-
def
|
425 |
-
|
426 |
-
|
427 |
-
|
428 |
-
|
429 |
-
|
430 |
-
|
431 |
-
|
432 |
-
|
433 |
-
|
434 |
-
|
435 |
-
|
436 |
-
|
437 |
-
|
438 |
-
|
439 |
-
|
440 |
-
|
441 |
-
|
442 |
-
|
443 |
-
|
444 |
-
|
445 |
-
|
446 |
-
|
447 |
-
|
448 |
-
|
449 |
-
|
450 |
-
|
451 |
-
with gr.Blocks() as iface:
|
452 |
-
gr.Markdown("# Sequential App Builder")
|
453 |
-
|
454 |
-
with gr.Row():
|
455 |
-
current_step = gr.Markdown(app_process.get_current_step_info())
|
456 |
-
|
457 |
-
with gr.Row():
|
458 |
-
prev_button = gr.Button("Previous Step")
|
459 |
-
next_button = gr.Button("Next Step")
|
460 |
-
|
461 |
-
# Step 1: App Initialization
|
462 |
-
with gr.Group() as step1:
|
463 |
-
app_name_input = gr.Textbox(label="Enter App Name")
|
464 |
-
init_app_button = gr.Button("Initialize App")
|
465 |
-
|
466 |
-
# Step 2: Component Addition
|
467 |
-
with gr.Group() as step2:
|
468 |
-
component_type = gr.Dropdown(choices=list(components_registry.keys()), label="Select Component Type")
|
469 |
-
add_component_button = gr.Button("Add Component")
|
470 |
-
components_display = gr.HTML()
|
471 |
-
|
472 |
-
# Step 3: Property Configuration
|
473 |
-
with gr.Group() as step3:
|
474 |
-
component_id = gr.Number(label="Component ID")
|
475 |
-
property_name = gr.Textbox(label="Property Name")
|
476 |
-
property_value = gr.Textbox(label="Property Value")
|
477 |
-
set_property_button = gr.Button("Set Property")
|
478 |
-
|
479 |
-
# Step 4: Code Generation
|
480 |
-
with gr.Group() as step4:
|
481 |
-
generated_code = gr.Code(language="python")
|
482 |
-
generate_code_button = gr.Button("Generate Code")
|
483 |
-
|
484 |
-
# Step 5: Deployment
|
485 |
-
with gr.Group() as step5:
|
486 |
-
deploy_button = gr.Button("Deploy to Hugging Face Spaces")
|
487 |
-
deployment_status = gr.Markdown()
|
488 |
-
|
489 |
-
# Chat and Terminal (optional, can be hidden or shown based on preference)
|
490 |
-
with gr.Accordion("Advanced", open=False):
|
491 |
-
chat_history = gr.Chatbot(label="Chat with Agent")
|
492 |
-
chat_input = gr.Textbox(label="Your Message")
|
493 |
-
chat_button = gr.Button("Send")
|
494 |
-
|
495 |
-
terminal_output = gr.Textbox(lines=8, label="Terminal", value=terminal_history)
|
496 |
-
terminal_input = gr.Textbox(label="Enter Command")
|
497 |
-
terminal_button = gr.Button("Run")
|
498 |
-
|
499 |
-
# App Creation Process Class
|
500 |
-
class AppCreationProcess:
|
501 |
-
def __init__(self):
|
502 |
-
self.current_step = 1
|
503 |
-
self.app_name = ""
|
504 |
-
self.components = []
|
505 |
-
|
506 |
-
def get_current_step_info(self):
|
507 |
-
steps = {
|
508 |
-
1: "App Initialization",
|
509 |
-
2: "Component Addition",
|
510 |
-
3: "Property Configuration",
|
511 |
-
4: "Code Generation",
|
512 |
-
5: "Deployment"
|
513 |
-
}
|
514 |
-
|
515 |
-
def next_step():
|
516 |
-
app_process.next_step()
|
517 |
-
current_step_info = app_process.get_current_step_info()
|
518 |
-
visibility_updates = update_visibility(app_process.current_step)
|
519 |
-
|
520 |
-
# Unpack the visibility updates
|
521 |
-
step1_update = visibility_updates[step1]
|
522 |
-
step2_update = visibility_updates[step2]
|
523 |
-
step3_update = visibility_updates[step3]
|
524 |
-
step4_update = visibility_updates[step4]
|
525 |
-
step5_update = visibility_updates[step5]
|
526 |
-
|
527 |
-
return [
|
528 |
-
current_step_info, # This should be a string for the Markdown component
|
529 |
-
step1_update,
|
530 |
-
step2_update,
|
531 |
-
step3_update,
|
532 |
-
step4_update,
|
533 |
-
step5_update
|
534 |
-
]
|
535 |
-
def prev_step():
|
536 |
-
app_process.previous_step()
|
537 |
-
return app_process.get_current_step_info(), update_visibility(app_process.current_step)
|
538 |
-
next_button.click(next_step, outputs=[current_step, step1, step2, step3, step4, step5])
|
539 |
-
prev_button.click(prev_step, outputs=[current_step, step1, step2, step3, step4, step5])
|
540 |
-
|
541 |
-
# Step 1: Initialize App
|
542 |
-
def init_app(name):
|
543 |
-
app_process.app_name = name
|
544 |
-
return f"App '{name}' initialized."
|
545 |
-
init_app_button.click(init_app, inputs=[app_name_input], outputs=[components_display])
|
546 |
-
# Step 2: Add Component
|
547 |
-
add_component_button.click(app_process.add_component, inputs=[component_type], outputs=[components_display])
|
548 |
-
# Step 3: Set Property
|
549 |
-
set_property_button.click(app_process.set_component_property, inputs=[component_id, property_name, property_value], outputs=[components_display])
|
550 |
-
# Step 4: Generate Code
|
551 |
-
generate_code_button.click(app_process.generate_python_code, outputs=[generated_code])
|
552 |
-
# Step 5: Deploy
|
553 |
-
deploy_button.click(app_process.deploy_to_huggingface, outputs=[deployment_status])
|
554 |
-
# Existing chat and terminal functionality
|
555 |
-
chat_button.click(run_chat, inputs=[chat_input, chat_history], outputs=[chat_history, terminal_output])
|
556 |
-
terminal_button.click(run_terminal_command, inputs=[terminal_input, terminal_output], outputs=[terminal_output])
|
557 |
-
|
558 |
-
iface.launch(server_port=GRADIO_SERVER_PORT)
|
|
|
1 |
+
import gradio as gr
|
2 |
import subprocess
|
3 |
+
import random
|
4 |
+
import json
|
5 |
+
import os
|
6 |
+
import tempfile
|
7 |
+
import time
|
8 |
+
from pathlib import Path
|
9 |
+
from datetime import datetime
|
10 |
+
import asyncio
|
11 |
+
import aiohttp
|
12 |
+
from typing import List, Dict, Any
|
13 |
+
import logging
|
14 |
import black
|
15 |
from pylint import lint
|
16 |
from io import StringIO
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
|
18 |
+
# Configure logging
|
19 |
+
logging.basicConfig(
|
20 |
+
level=logging.INFO,
|
21 |
+
format='%(asctime)s - %(levelname)s - %(message)s'
|
22 |
+
)
|
23 |
+
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
24 |
|
25 |
+
class EnhancedAppBuilder:
|
|
|
26 |
def __init__(self):
|
27 |
+
self.TEMPLATES = {
|
28 |
+
"Basic": "basic_app.json",
|
29 |
+
"Dashboard": "dashboard_template.json",
|
30 |
+
"Data Analysis": "data_analysis_template.json",
|
31 |
+
"ML Interface": "ml_interface_template.json"
|
32 |
+
}
|
33 |
+
|
34 |
+
self.THEMES = {
|
35 |
+
"Default": {},
|
36 |
+
"Dark": {"primary_hue": "slate", "secondary_hue": "slate"},
|
37 |
+
"Light": {"primary_hue": "blue", "secondary_hue": "blue"},
|
38 |
+
"Professional": {"primary_hue": "indigo", "secondary_hue": "indigo"}
|
39 |
+
}
|
40 |
+
|
41 |
+
self.ADVANCED_COMPONENTS = {
|
42 |
+
"Plot": {
|
43 |
+
"properties": {
|
44 |
+
"type": ["line", "bar", "scatter", "histogram"],
|
45 |
+
"data_source": "",
|
46 |
+
"x_axis": "",
|
47 |
+
"y_axis": ""
|
48 |
+
},
|
49 |
+
"code_snippet": 'gr.Plot(value=plot_{id}, label="{label}")'
|
50 |
+
},
|
51 |
+
"FileUploader": {
|
52 |
+
"properties": {
|
53 |
+
"file_types": [".csv", ".txt", ".pdf", ".png", ".jpg"],
|
54 |
+
"multiple": False
|
55 |
+
},
|
56 |
+
"code_snippet": 'gr.File(file_types={file_types}, label="{label}")'
|
57 |
+
},
|
58 |
+
"DataTable": {
|
59 |
+
"properties": {
|
60 |
+
"headers": [],
|
61 |
+
"row_count": 10,
|
62 |
+
"interactive": True
|
63 |
+
},
|
64 |
+
"code_snippet": 'gr.Dataframe(headers={headers}, interactive={interactive})'
|
65 |
+
},
|
66 |
+
"3D Plot": {
|
67 |
+
"properties": {
|
68 |
+
"type": ["surface", "scatter3d", "line3d"],
|
69 |
+
"data": None
|
70 |
+
},
|
71 |
+
"code_snippet": 'gr.Plot3D(value=plot3d_{id})'
|
72 |
+
}
|
73 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
74 |
|
75 |
+
async def validate_component(self, component: Dict) -> tuple:
|
76 |
+
"""Validate component configuration"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
77 |
try:
|
78 |
+
required_fields = ["type", "properties", "id"]
|
79 |
+
if not all(field in component for field in required_fields):
|
80 |
+
return False, "Missing required fields"
|
81 |
+
|
82 |
+
# Validate component type
|
83 |
+
if component["type"] not in {**components_registry, **self.ADVANCED_COMPONENTS}:
|
84 |
+
return False, f"Invalid component type: {component['type']}"
|
85 |
+
|
86 |
+
return True, "Component validation successful"
|
87 |
except Exception as e:
|
88 |
+
return False, f"Validation error: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
89 |
|
90 |
+
def format_code(self, code: str) -> str:
|
91 |
+
"""Format Python code using black"""
|
92 |
+
try:
|
93 |
+
return black.format_str(code, mode=black.FileMode())
|
94 |
+
except Exception as e:
|
95 |
+
logger.error(f"Code formatting error: {str(e)}")
|
96 |
+
return code
|
97 |
+
|
98 |
+
def lint_code(self, code: str) -> List[str]:
|
99 |
+
"""Run pylint on generated code"""
|
100 |
+
with tempfile.NamedTemporaryFile(mode='w', suffix='.py') as tmp:
|
101 |
+
tmp.write(code)
|
102 |
+
tmp.flush()
|
103 |
+
|
104 |
+
output = StringIO()
|
105 |
+
lint.Run([tmp.name], do_exit=False, reporter=lint.reporters.TextReporter(output))
|
106 |
+
return output.getvalue().split('\n')
|
107 |
+
|
108 |
+
async def optimize_layout(self, components: List[Dict]) -> List[Dict]:
|
109 |
+
"""Optimize component layout for better UX"""
|
110 |
+
# Group related components
|
111 |
+
groups = {}
|
112 |
+
for comp in components:
|
113 |
+
category = comp['type'].split('_')[0]
|
114 |
+
if category not in groups:
|
115 |
+
groups[category] = []
|
116 |
+
groups[category].append(comp)
|
|
|
117 |
|
118 |
+
# Arrange components in optimal order
|
119 |
+
optimized = []
|
120 |
+
for category in ['input', 'process', 'output']:
|
121 |
+
if category in groups:
|
122 |
+
optimized.extend(groups[category])
|
123 |
+
|
124 |
+
return optimized
|
125 |
|
126 |
+
class EnhancedAppCreationProcess(AppCreationProcess):
|
|
|
127 |
def __init__(self):
|
128 |
+
super().__init__()
|
129 |
+
self.builder = EnhancedAppBuilder()
|
130 |
+
self.history = []
|
131 |
+
self.current_theme = "Default"
|
132 |
+
self.custom_css = ""
|
133 |
+
self.event_handlers = {}
|
134 |
+
self.dependencies = []
|
135 |
+
|
136 |
+
def save_snapshot(self):
|
137 |
+
"""Save current state snapshot"""
|
138 |
+
snapshot = {
|
139 |
+
'timestamp': datetime.now().isoformat(),
|
140 |
+
'app_name': self.app_name,
|
141 |
+
'components': self.components.copy(),
|
142 |
+
'theme': self.current_theme,
|
143 |
+
'custom_css': self.custom_css
|
144 |
}
|
145 |
+
self.history.append(snapshot)
|
146 |
+
|
147 |
+
def restore_snapshot(self, index: int):
|
148 |
+
"""Restore from saved snapshot"""
|
149 |
+
if 0 <= index < len(self.history):
|
150 |
+
snapshot = self.history[index]
|
151 |
+
self.app_name = snapshot['app_name']
|
152 |
+
self.components = snapshot['components']
|
153 |
+
self.current_theme = snapshot['theme']
|
154 |
+
self.custom_css = snapshot['custom_css']
|
155 |
+
return "Snapshot restored successfully"
|
156 |
+
return "Invalid snapshot index"
|
157 |
+
|
158 |
+
async def generate_enhanced_code(self):
|
159 |
+
"""Generate enhanced application code"""
|
160 |
+
try:
|
161 |
+
# Start with imports
|
162 |
+
code = """import gradio as gr
|
163 |
+
import pandas as pd
|
164 |
+
import numpy as np
|
165 |
+
import plotly.express as px
|
166 |
+
from pathlib import Path
|
167 |
+
import logging
|
168 |
+
import json
|
169 |
|
170 |
+
# Configure logging
|
171 |
+
logging.basicConfig(level=logging.INFO)
|
172 |
+
logger = logging.getLogger(__name__)
|
173 |
+
"""
|
174 |
+
|
175 |
+
# Add theme configuration
|
176 |
+
theme_config = self.builder.THEMES.get(self.current_theme, {})
|
177 |
+
code += f"\ntheme = gr.themes.Default({', '.join(f'{k}={v!r}' for k, v in theme_config.items())})\n"
|
178 |
+
|
179 |
+
# Add custom CSS
|
180 |
+
if self.custom_css:
|
181 |
+
code += f"\ncustom_css = '''{self.custom_css}'''\n"
|
182 |
+
|
183 |
+
# Start app definition
|
184 |
+
code += f"\nwith gr.Blocks(theme=theme{',' if self.custom_css else ''} css=custom_css) as {self.app_name}:\n"
|
185 |
+
|
186 |
+
# Add components with layout optimization
|
187 |
+
optimized_components = await self.builder.optimize_layout(self.components)
|
188 |
+
|
189 |
+
# Generate component code
|
190 |
+
for component in optimized_components:
|
191 |
+
code += f" {Component(**component).render()}\n"
|
192 |
+
|
193 |
+
# Add event handlers
|
194 |
+
for handler in self.event_handlers:
|
195 |
+
code += f"\n {handler['trigger']}.change(fn={handler['function']}, "
|
196 |
+
code += f"inputs={handler['inputs']}, outputs={handler['outputs']})\n"
|
197 |
+
|
198 |
+
# Add launch configuration
|
199 |
+
code += f"\n{self.app_name}.launch(share=True, debug=True)\n"
|
200 |
+
|
201 |
+
# Format the code
|
202 |
+
formatted_code = self.builder.format_code(code)
|
203 |
+
|
204 |
+
# Run linting
|
205 |
+
lint_results = self.builder.lint_code(formatted_code)
|
206 |
+
|
207 |
+
return formatted_code, lint_results
|
208 |
+
|
209 |
+
except Exception as e:
|
210 |
+
logger.error(f"Code generation error: {str(e)}")
|
211 |
+
return str(e), []
|
212 |
|
213 |
+
async def deploy_enhanced(self):
|
214 |
+
"""Enhanced deployment process"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
215 |
try:
|
216 |
+
# Generate code
|
217 |
+
code, lint_results = await self.generate_enhanced_code()
|
218 |
+
|
219 |
+
# Create deployment directory
|
220 |
+
deploy_dir = Path(f"deployment_{self.app_name}")
|
221 |
+
deploy_dir.mkdir(exist_ok=True)
|
222 |
+
|
223 |
+
# Save main application file
|
224 |
+
with open(deploy_dir / "app.py", "w") as f:
|
225 |
+
f.write(code)
|
226 |
+
|
227 |
+
# Generate requirements.txt
|
228 |
+
requirements = [
|
229 |
+
"gradio>=3.50.2",
|
230 |
+
"pandas",
|
231 |
+
"numpy",
|
232 |
+
"plotly",
|
233 |
+
"pillow",
|
234 |
+
"scikit-learn"
|
235 |
+
]
|
236 |
+
with open(deploy_dir / "requirements.txt", "w") as f:
|
237 |
+
f.write("\n".join(requirements))
|
238 |
+
|
239 |
+
# Generate README.md
|
240 |
+
readme = f"""# {self.app_name}
|
241 |
+
|
242 |
+
Generated by Enhanced App Builder
|
243 |
+
|
244 |
+
## Features
|
245 |
+
- Interactive web interface
|
246 |
+
- Data visualization capabilities
|
247 |
+
- Responsive design with {self.current_theme} theme
|
248 |
+
- Advanced component integration
|
249 |
+
|
250 |
+
## Setup
|
251 |
+
1. Install requirements: `pip install -r requirements.txt`
|
252 |
+
2. Run the app: `python app.py`
|
253 |
+
"""
|
254 |
+
with open(deploy_dir / "README.md", "w") as f:
|
255 |
+
f.write(readme)
|
256 |
+
|
257 |
+
return {
|
258 |
+
"status": "success",
|
259 |
+
"message": f"Deployment files generated in {deploy_dir}",
|
260 |
+
"lint_results": lint_results
|
261 |
+
}
|
262 |
+
|
263 |
except Exception as e:
|
264 |
+
logger.error(f"Deployment error: {str(e)}")
|
265 |
+
return {
|
266 |
+
"status": "error",
|
267 |
+
"message": str(e)
|
268 |
+
}
|
269 |
+
|
270 |
+
# Create enhanced interface
|
271 |
+
def create_enhanced_interface():
|
272 |
+
app_process = EnhancedAppCreationProcess()
|
273 |
+
|
274 |
+
with gr.Blocks(theme=gr.themes.Default()) as iface:
|
275 |
+
gr.Markdown("# 🚀 Enhanced App Builder Pro")
|
276 |
+
|
277 |
+
with gr.Row():
|
278 |
+
with gr.Column(scale=2):
|
279 |
+
current_step = gr.Markdown(value=app_process.get_current_step_info())
|
280 |
+
with gr.Column(scale=1):
|
281 |
+
theme_dropdown = gr.Dropdown(
|
282 |
+
choices=list(app_process.builder.THEMES.keys()),
|
283 |
+
value="Default",
|
284 |
+
label="Theme"
|
285 |
+
)
|
286 |
+
|
287 |
+
with gr.Tabs():
|
288 |
+
# App Configuration Tab
|
289 |
+
with gr.TabItem("📱 App Configuration"):
|
290 |
+
with gr.Group():
|
291 |
+
app_name_input = gr.Textbox(label="App Name")
|
292 |
+
template_dropdown = gr.Dropdown(
|
293 |
+
choices=list(app_process.builder.TEMPLATES.keys()),
|
294 |
+
label="Template"
|
295 |
+
)
|
296 |
+
init_app_button = gr.Button("Initialize App", variant="primary")
|
297 |
+
init_status = gr.Markdown()
|
298 |
+
|
299 |
+
# Component Builder Tab
|
300 |
+
with gr.TabItem("🔧 Component Builder"):
|
301 |
+
with gr.Row():
|
302 |
+
with gr.Column():
|
303 |
+
component_type = gr.Dropdown(
|
304 |
+
choices=list({**components_registry, **app_process.builder.ADVANCED_COMPONENTS}.keys()),
|
305 |
+
label="Component Type"
|
306 |
+
)
|
307 |
+
add_component_button = gr.Button("Add Component")
|
308 |
+
with gr.Column():
|
309 |
+
components_display = gr.HTML()
|
310 |
+
|
311 |
+
# Style Editor Tab
|
312 |
+
with gr.TabItem("🎨 Style Editor"):
|
313 |
+
custom_css = gr.Code(
|
314 |
+
label="Custom CSS",
|
315 |
+
language="css"
|
316 |
+
)
|
317 |
+
apply_style_button = gr.Button("Apply Style")
|
318 |
+
style_status = gr.Markdown()
|
319 |
+
|
320 |
+
# Code Generator Tab
|
321 |
+
with gr.TabItem("💻 Code Generator"):
|
322 |
+
generate_code_button = gr.Button("Generate Code")
|
323 |
+
generated_code = gr.Code(language="python")
|
324 |
+
lint_results = gr.Markdown()
|
325 |
+
|
326 |
+
# Deployment Tab
|
327 |
+
with gr.TabItem("🚀 Deployment"):
|
328 |
+
with gr.Group():
|
329 |
+
deploy_button = gr.Button("Deploy Application")
|
330 |
+
deployment_status = gr.Markdown()
|
331 |
+
with gr.Accordion("Deployment Logs", open=False):
|
332 |
+
deployment_logs = gr.TextArea(label="Logs", interactive=False)
|
333 |
+
|
334 |
+
# Footer
|
335 |
+
gr.Markdown("---")
|
336 |
+
with gr.Row():
|
337 |
+
gr.Markdown("### 📊 Build Status")
|
338 |
+
components_count = gr.Number(label="Components", value=0)
|
339 |
+
validation_status = gr.Markdown()
|
340 |
+
|
341 |
+
# Event handlers
|
342 |
+
async def update_theme(theme_name):
|
343 |
+
app_process.current_theme = theme_name
|
344 |
+
return f"Theme updated to {theme_name}"
|
345 |
+
|
346 |
+
async def init_app(name, template):
|
347 |
+
try:
|
348 |
+
app_process.app_name = name
|
349 |
+
# Load template if selected
|
350 |
+
if template:
|
351 |
+
# Implementation for template loading
|
352 |
+
pass
|
353 |
+
app_process.save_snapshot()
|
354 |
+
return f"✅ App '{name}' initialized successfully with {template} template!"
|
355 |
+
except Exception as e:
|
356 |
+
return f"❌ Error: {str(e)}"
|
357 |
|
358 |
+
async def add_component(comp_type):
|
359 |
+
try:
|
360 |
+
result = app_process.add_component(comp_type)
|
361 |
+
count = len(app_process.components)
|
362 |
+
return result, count, "✅ Component added successfully"
|
363 |
+
except Exception as e:
|
364 |
+
return None, 0, f"❌ Error: {str(e)}"
|
365 |
|
366 |
+
async def generate_code():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
367 |
try:
|
368 |
+
code, lint_results = await app_process.generate_enhanced_code()
|
369 |
+
return (
|
370 |
+
code,
|
371 |
+
"### Lint Results:\n" + "\n".join(lint_results)
|
372 |
)
|
|
|
373 |
except Exception as e:
|
374 |
+
return str(e), "❌ Error in code generation"
|
|
|
|
|
|
|
|
|
|
|
375 |
|
376 |
+
async def deploy():
|
377 |
+
try:
|
378 |
+
result = await app_process.deploy_enhanced()
|
379 |
+
return (
|
380 |
+
f"### Deployment Status: {result['status']}\n\n{result['message']}",
|
381 |
+
"\n".join(result.get('lint_results', []))
|
382 |
+
)
|
383 |
+
except Exception as e:
|
384 |
+
return f"❌ Deployment Error: {str(e)}", ""
|
385 |
+
|
386 |
+
# Connect event handlers
|
387 |
+
theme_dropdown.change(update_theme, inputs=[theme_dropdown], outputs=[style_status])
|
388 |
+
init_app_button.click(init_app, inputs=[app_name_input, template_dropdown], outputs=[init_status])
|
389 |
+
add_component_button.click(add_component, inputs=[component_type], outputs=[components_display, components_count, validation_status])
|
390 |
+
generate_code_button.click(generate_code, outputs=[generated_code, lint_results])
|
391 |
+
deploy_button.click(deploy, outputs=[deployment_status, deployment_logs])
|
392 |
+
|
393 |
+
return iface
|
394 |
+
|
395 |
+
# Launch the enhanced interface
|
396 |
+
if __name__ == "__main__":
|
397 |
+
iface = create_enhanced_interface()
|
398 |
+
iface.launch(
|
399 |
+
server_port=7860,
|
400 |
+
share=True,
|
401 |
+
debug=True
|
402 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|