File size: 10,135 Bytes
fae4179
 
b8b7a36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e396de
b8b7a36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58ddfa5
 
b8b7a36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58ddfa5
b8b7a36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58ddfa5
b8b7a36
 
 
 
 
58ddfa5
b8b7a36
 
 
 
 
 
 
 
 
 
 
 
 
 
58ddfa5
b8b7a36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58ddfa5
b8b7a36
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
245
246
247
248
import os
import subprocess
import random
import json
from datetime import datetime

from huggingface_hub import (
    InferenceClient,
    cached_download,
    hf_hub_url
)
import gradio as gr

from safe_search import safe_search
from i_search import google
from i_search import i_search as i_s 

from agent import (
    ACTION_PROMPT,
    ADD_PROMPT,
    COMPRESS_HISTORY_PROMPT,
    
    LOG_PROMPT,
    LOG_RESPONSE,
    MODIFY_PROMPT,
    PRE_PREFIX,
    SEARCH_QUERY,
    READ_PROMPT,
    TASK_PROMPT,
    UNDERSTAND_TEST_RESULTS_PROMPT,
) 

from utils import (
    parse_action, 
    parse_file_content, 
    read_python_module_structure
) 
from datetime import datetime 
import json

#--- Global Variables for App State ---
app_state = {"components": []} 

terminal_history = ""
#--- Component Library ---
components_registry = { "Button": { "properties": {"label": "Click Me", "onclick": ""}, "description": "A clickable button", "code_snippet": 'gr.Button(value="{label}", variant="primary")', }, "Text Input": { "properties": {"value": "", "placeholder": "Enter text"}, "description": "A field for entering text", "code_snippet": 'gr.Textbox(label="{placeholder}")', }, "Image": { "properties": {"src": "#", "alt": "Image"}, "description": "Displays an image", "code_snippet": 'gr.Image(label="{alt}")', }, "Dropdown": { "properties": {"choices": ["Option 1", "Option 2"], "value": ""}, "description": "A dropdown menu for selecting options", "code_snippet": 'gr.Dropdown(choices={choices}, label="Dropdown")', }, # Add more components here... }

#--- NLP Model (Example using Hugging Face) ---
nlp_model_name = "google/flan-t5-small"

# Check if the model exists in the cache
try: cached_download(hf_hub_url(nlp_model_name, revision="main")) nlp_model = InferenceClient(nlp_model_name) except: nlp_model = None

#--- Function to get NLP model response ---
def get_nlp_response(input_text): if nlp_model: response = nlp_model.text_generation(input_text) return response.generated_text else: return "NLP model not available."

# --- Component Class ---
class Component: def init(self, type, properties=None, id=None): self.id = id or random.randint(1000, 9999) self.type = type self.properties = properties or components_registry[type]["properties"].copy()

def to_dict(self):
    return {
        "id": self.id,
        "type": self.type,
        "properties": self.properties,
    }

def render(self):
    # Properly format choices for Dropdown
    if self.type == "Dropdown":
        self.properties["choices"] = (
            str(self.properties["choices"])
            .replace("[", "")
            .replace("]", "")
            .replace("'", "")
        )
    return components_registry[self.type]["code_snippet"].format(
        **self.properties
    )
# --- Function to update the app canvas (for preview) ---
def update_app_canvas(): components_html = "".join( [ f"<div>Component ID: {component['id']}, Type: {component['type']}, Properties: {component['properties']}</div>" for component in app_state["components"] ] ) return components_html

# --- Function to handle component addition ---
def add_component(component_type): if component_type in components_registry: new_component = Component(component_type) app_state["components"].append(new_component.to_dict()) return ( update_app_canvas(), f"System: Added component: {component_type}\n", ) else: return None, f"Error: Invalid component type: {component_type}\n"

# --- Function to handle terminal input ---
def run_terminal_command(command, history): global terminal_history output = "" try: # Basic command parsing (expand with NLP) if command.startswith("add "): component_type = command.split("add ", 1)[1].strip() _, output = add_component(component_type) elif command.startswith("set "): _, output = set_component_property(command) elif command.startswith("search "): search_query = command.split("search ", 1)[1].strip() output = i_s(search_query) elif command.startswith("deploy "): app_name = command.split("deploy ", 1)[1].strip() output = deploy_to_huggingface(app_name) else: # Attempt to execute command as Python code try: result = subprocess.check_output( command, shell=True, stderr=subprocess.STDOUT, text=True ) output = result except Exception as e: output = f"Error executing Python code: {str(e)}" except Exception as e: output = f"Error: {str(e)}" finally: terminal_history += f"User: {command}\n" terminal_history += f"{output}\n" return terminal_history

def set_component_property(command): try: # Improved 'set' command parsing set_parts = command.split(" ", 2)[1:] if len(set_parts) != 2: raise ValueError("Invalid 'set' command format.")

component_id = int(set_parts[0])  # Use component ID
    property_name, property_value = set_parts[1].split("=", 1)

    # Find component by ID
    component_found = False
    for component in app_state["components"]:
        if component["id"] == component_id:
            if property_name in component["properties"]:
                component["properties"][
                    property_name.strip()
                ] = property_value.strip()
                component_found = True
                return (
                    update_app_canvas(),
                    f"System: Property '{property_name}' set to '{property_value}' for component {component_id}\n",
                )
            else:
                return (
                    None,
                    f"Error: Property '{property_name}' not found in component {component_id}\n",
                )
    if not component_found:
        return (
            None,
            f"Error: Component with ID {component_id} not found.\n",
        )

except Exception as e:
    return None, f"Error: Invalid 'set' command format or error setting property: {str(e)}\n"
#--- Function to handle chat interaction ---
def run_chat(message, history): global terminal_history if message.startswith("!"): command = message[1:] terminal_history = run_terminal_command(command, history) return history, terminal_history else: # ... (Your regular chat response generation) return history, terminal_history

# --- Code Generation ---
def generate_python_code(app_name): code = f""" import gradio as gr
Define your Gradio components here
with gr.Blocks() as {app_name}: """ for component in app_state["components"]: code += " " + Component(**component).render() + "\n"

code += f"""
{app_name}.launch() """ return code

# --- Save/Load App State ---
def save_app_state(filename="app_state.json"): with open(filename, "w") as f: json.dump(app_state, f)

# --- Hugging Face Deployment --- def deploy_to_huggingface(app_name): # Generate Python code code = generate_python_code(app_name)
def load_app_state(filename="app_state.json"): global app_state try: with open(filename, "r") as f: app_state = json.load(f) except FileNotFoundError: print("App state file not found. Starting with a blank slate.")

# Create requirements.txt
with open("requirements.txt", "w") as f:
    f.write("gradio==3.32.0\n")

# Create the app.py file
with open("app.py", "w") as f:
    f.write(code)

# Execute the deployment command
try:
    subprocess.run(
        [
            "huggingface-cli",
            "repo",
            "create",
            "--type",
            "space",
            "--space_sdk",
            "gradio",
            app_name,
        ],
        check=True,
    )
    subprocess.run(
        ["git", "init"], cwd=f"./{app_name}", check=True
    )
    subprocess.run(
        ["git", "add", "."], cwd=f"./{app_name}", check=True
    )
    subprocess.run(
        ['git', 'commit', '-m', '"Initial commit"'], cwd=f"./{user_name}/{app_name}", check=True
    )
    subprocess.run(
        ["git", "push", "https://huggingface.co/spaces/" + app_name, "main"], cwd=f"./{app_name}", check=True
    )
    return (
        f"Successfully deployed to Hugging Face Spaces: https://huggingface.co/spaces/{app_name}"
    )
except Exception as e:
    return f"Error deploying to Hugging Face Spaces: {e}"
--- Gradio Interface ---
with gr.Blocks() as iface: with gr.Row(): # --- Chat Interface --- chat_history = gr.Chatbot(label="Chat with Agent") chat_input = gr.Textbox(label="Your Message") chat_button = gr.Button("Send")

chat_button.click(
        run_chat,
        inputs=[chat_input, chat_history],
        outputs=[chat_history, terminal_output],
    )

with gr.Row():
    # --- App Builder Section ---
    app_canvas = gr.HTML(
        "<div>App Canvas Preview:</div>", label="App Canvas"
    )
    with gr.Column():
        component_list = gr.Dropdown(
            choices=list(components_registry.keys()), label="Components"
        )
        add_button = gr.Button("Add Component")

        add_button.click(
            add_component,
            inputs=component_list,
            outputs=[app_canvas, terminal_output],
        )

with gr.Row():
    # --- Terminal ---
    terminal_output = gr.Textbox(
        lines=8, label="Terminal", value=terminal_history
    )
    terminal_input = gr.Textbox(label="Enter Command")
    terminal_button = gr.Button("Run")

    terminal_button.click(
        run_terminal_command,
        inputs=[terminal_input, terminal_output],
        outputs=terminal_output,
    )

with gr.Row():
    # --- Code Generation ---
    code_output = gr.Code(
        generate_python_code("app_name"),
        language="python",
        label="Generated Code",
    )
    app_name_input = gr.Textbox(label="App Name")
    generate_code_button = gr.Button("Generate Code")
    generate_code_button.click(
        generate_python_code,
        inputs=[app_name_input],
        outputs=code_output,
    )

with gr.Row():
    # --- Save/Load Buttons ---
    save_button = gr.Button("Save App State")
    load_button = gr.Button("Load App State")

    save_button.click(save_app_state)
    load_button.click(load_app_state)

with gr.Row():
    # --- Deploy Button ---
    deploy_button = gr.Button("Deploy to Hugging Face")
    deploy_output = gr.Textbox(label="Deployment Output")
    deploy_button.click(
        deploy_to_huggingface,
        inputs=[app_name_input],
        outputs=[deploy_output],
    )
iface.launch()