Spaces:
Build error
Build error
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_names = [ "google/flan-t5-small", "Qwen/CodeQwen1.5-7B-Chat-GGUF", "bartowski/Codestral-22B-v0.1-GGUF", "bartowski/AutoCoder-GGUF" ] nlp_models = [] for nlp_model_name in nlp_model_names: try: cached_download(hf_hub_url(nlp_model_name, revision="main")) nlp_models.append(InferenceClient(nlp_model_name)) except: nlp_models.append(None) #--- Function to get NLP model response --- def get_nlp_response(input_text, model_index): if nlp_models[model_index]: response = nlp_models[model_index].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) else: # ... (Your regular chat response generation) model_index = 0 # Select the model to use for chat response response = get_nlp_response(message, model_index) if response: return history, terminal_history + f"User: {message}\nAssistant: {response}" else: return history, terminal_history + f"User: {message}\nAssistant: I'm sorry, I couldn't generate a response. Please try again.\n" --- 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 --- Hugging Face Deployment --- def deploy_to_huggingface(app_name): Generate Python code code = generate_python_code(app_name) 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'./{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: --- 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], ) --- 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, ) iface.launch()
Browse files
app.py
CHANGED
|
@@ -46,203 +46,230 @@ terminal_history = ""
|
|
| 46 |
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... }
|
| 47 |
|
| 48 |
#--- NLP Model (Example using Hugging Face) ---
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
#--- Function to get NLP model response ---
|
| 55 |
-
def get_nlp_response(input_text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
# --- Component Class ---
|
| 58 |
-
class Component:
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
"
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
)
|
| 76 |
-
return components_registry[self.type]["code_snippet"].format(
|
| 77 |
-
**self.properties
|
| 78 |
-
)
|
| 79 |
# --- Function to update the app canvas (for preview) ---
|
| 80 |
-
def update_app_canvas():
|
|
|
|
|
|
|
| 81 |
|
| 82 |
# --- Function to handle component addition ---
|
| 83 |
-
def add_component(component_type):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
# --- Function to handle terminal input ---
|
| 86 |
-
def run_terminal_command(command, history):
|
| 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 |
-
except Exception as e:
|
| 118 |
-
return None, f"Error: Invalid 'set' command format or error setting property: {str(e)}\n"
|
| 119 |
#--- Function to handle chat interaction ---
|
| 120 |
-
def run_chat(message, history):
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
Define your Gradio components here
|
| 125 |
with gr.Blocks() as {app_name}: """ for component in app_state["components"]: code += " " + Component(**component).render() + "\n"
|
| 126 |
|
| 127 |
code += f"""
|
| 128 |
{app_name}.launch() """ return code
|
| 129 |
|
| 130 |
-
|
| 131 |
-
def
|
| 132 |
|
| 133 |
-
|
| 134 |
-
|
| 135 |
|
| 136 |
-
|
| 137 |
with open("requirements.txt", "w") as f:
|
| 138 |
-
|
| 139 |
|
| 140 |
-
|
| 141 |
with open("app.py", "w") as f:
|
| 142 |
-
|
| 143 |
|
| 144 |
-
|
| 145 |
try:
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
subprocess.run(
|
| 166 |
-
['git', 'commit', '-m', '"Initial commit"'], cwd=f"./{user_name}/{app_name}", check=True
|
| 167 |
-
)
|
| 168 |
-
subprocess.run(
|
| 169 |
-
["git", "push", "https://huggingface.co/spaces/" + app_name, "main"], cwd=f"./{app_name}", check=True
|
| 170 |
-
)
|
| 171 |
-
return (
|
| 172 |
-
f"Successfully deployed to Hugging Face Spaces: https://huggingface.co/spaces/{app_name}"
|
| 173 |
-
)
|
| 174 |
except Exception as e:
|
| 175 |
-
|
|
|
|
| 176 |
--- Gradio Interface ---
|
| 177 |
-
with gr.Blocks() as iface:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
|
| 179 |
chat_button.click(
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
with gr.Row():
|
| 186 |
-
# --- App Builder Section ---
|
| 187 |
-
app_canvas = gr.HTML(
|
| 188 |
-
"<div>App Canvas Preview:</div>", label="App Canvas"
|
| 189 |
-
)
|
| 190 |
-
with gr.Column():
|
| 191 |
-
component_list = gr.Dropdown(
|
| 192 |
-
choices=list(components_registry.keys()), label="Components"
|
| 193 |
-
)
|
| 194 |
-
add_button = gr.Button("Add Component")
|
| 195 |
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
|
| 202 |
-
with gr.Row():
|
| 203 |
-
# --- Terminal ---
|
| 204 |
-
terminal_output = gr.Textbox(
|
| 205 |
-
lines=8, label="Terminal", value=terminal_history
|
| 206 |
-
)
|
| 207 |
-
terminal_input = gr.Textbox(label="Enter Command")
|
| 208 |
-
terminal_button = gr.Button("Run")
|
| 209 |
-
|
| 210 |
-
terminal_button.click(
|
| 211 |
-
run_terminal_command,
|
| 212 |
-
inputs=[terminal_input, terminal_output],
|
| 213 |
-
outputs=terminal_output,
|
| 214 |
-
)
|
| 215 |
-
|
| 216 |
-
with gr.Row():
|
| 217 |
-
# --- Code Generation ---
|
| 218 |
-
code_output = gr.Code(
|
| 219 |
-
generate_python_code("app_name"),
|
| 220 |
-
language="python",
|
| 221 |
-
label="Generated Code",
|
| 222 |
-
)
|
| 223 |
-
app_name_input = gr.Textbox(label="App Name")
|
| 224 |
-
generate_code_button = gr.Button("Generate Code")
|
| 225 |
-
generate_code_button.click(
|
| 226 |
-
generate_python_code,
|
| 227 |
-
inputs=[app_name_input],
|
| 228 |
-
outputs=code_output,
|
| 229 |
-
)
|
| 230 |
-
|
| 231 |
-
with gr.Row():
|
| 232 |
-
# --- Save/Load Buttons ---
|
| 233 |
-
save_button = gr.Button("Save App State")
|
| 234 |
-
load_button = gr.Button("Load App State")
|
| 235 |
-
|
| 236 |
-
save_button.click(save_app_state)
|
| 237 |
-
load_button.click(load_app_state)
|
| 238 |
-
|
| 239 |
-
with gr.Row():
|
| 240 |
-
# --- Deploy Button ---
|
| 241 |
-
deploy_button = gr.Button("Deploy to Hugging Face")
|
| 242 |
-
deploy_output = gr.Textbox(label="Deployment Output")
|
| 243 |
-
deploy_button.click(
|
| 244 |
-
deploy_to_huggingface,
|
| 245 |
-
inputs=[app_name_input],
|
| 246 |
-
outputs=[deploy_output],
|
| 247 |
-
)
|
| 248 |
iface.launch()
|
|
|
|
| 46 |
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... }
|
| 47 |
|
| 48 |
#--- NLP Model (Example using Hugging Face) ---
|
| 49 |
+
nlp_model_names = [
|
| 50 |
+
"google/flan-t5-small",
|
| 51 |
+
"Qwen/CodeQwen1.5-7B-Chat-GGUF",
|
| 52 |
+
"bartowski/Codestral-22B-v0.1-GGUF",
|
| 53 |
+
"bartowski/AutoCoder-GGUF"
|
| 54 |
+
]
|
| 55 |
+
|
| 56 |
+
nlp_models = []
|
| 57 |
+
|
| 58 |
+
for nlp_model_name in nlp_model_names:
|
| 59 |
+
try:
|
| 60 |
+
cached_download(hf_hub_url(nlp_model_name, revision="main"))
|
| 61 |
+
nlp_models.append(InferenceClient(nlp_model_name))
|
| 62 |
+
except:
|
| 63 |
+
nlp_models.append(None)
|
| 64 |
|
| 65 |
#--- Function to get NLP model response ---
|
| 66 |
+
def get_nlp_response(input_text, model_index):
|
| 67 |
+
if nlp_models[model_index]:
|
| 68 |
+
response = nlp_models[model_index].text_generation(input_text)
|
| 69 |
+
return response.generated_text
|
| 70 |
+
else:
|
| 71 |
+
return "NLP model not available."
|
| 72 |
|
| 73 |
# --- Component Class ---
|
| 74 |
+
class Component:
|
| 75 |
+
def __init__(self, type, properties=None, id=None):
|
| 76 |
+
self.id = id or random.randint(1000, 9999)
|
| 77 |
+
self.type = type
|
| 78 |
+
self.properties = properties or components_registry[type]["properties"].copy()
|
| 79 |
+
|
| 80 |
+
def to_dict(self):
|
| 81 |
+
return {
|
| 82 |
+
"id": self.id,
|
| 83 |
+
"type": self.type,
|
| 84 |
+
"properties": self.properties,
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
def render(self):
|
| 88 |
+
# Properly format choices for Dropdown
|
| 89 |
+
if self.type == "Dropdown":
|
| 90 |
+
self.properties["choices"] = (
|
| 91 |
+
str(self.properties["choices"])
|
| 92 |
+
.replace("[", "")
|
| 93 |
+
.replace("]", "")
|
| 94 |
+
.replace("'", "")
|
| 95 |
+
)
|
| 96 |
+
return components_registry[self.type]["code_snippet"].format(
|
| 97 |
+
**self.properties
|
| 98 |
)
|
|
|
|
|
|
|
|
|
|
| 99 |
# --- Function to update the app canvas (for preview) ---
|
| 100 |
+
def update_app_canvas():
|
| 101 |
+
components_html = "".join( [ f"<div>Component ID: {component['id']}, Type: {component['type']}, Properties: {component['properties']}</div>" for component in app_state["components"] ] )
|
| 102 |
+
return components_html
|
| 103 |
|
| 104 |
# --- Function to handle component addition ---
|
| 105 |
+
def add_component(component_type):
|
| 106 |
+
if component_type in components_registry:
|
| 107 |
+
new_component = Component(component_type)
|
| 108 |
+
app_state["components"].append(new_component.to_dict())
|
| 109 |
+
return (
|
| 110 |
+
update_app_canvas(),
|
| 111 |
+
f"System: Added component: {component_type}\n",
|
| 112 |
+
)
|
| 113 |
+
else:
|
| 114 |
+
return None, f"Error: Invalid component type: {component_type}\n"
|
| 115 |
|
| 116 |
# --- Function to handle terminal input ---
|
| 117 |
+
def run_terminal_command(command, history):
|
| 118 |
+
global terminal_history
|
| 119 |
+
output = ""
|
| 120 |
+
try:
|
| 121 |
+
# Basic command parsing (expand with NLP)
|
| 122 |
+
if command.startswith("add "):
|
| 123 |
+
component_type = command.split("add ", 1)[1].strip()
|
| 124 |
+
_, output = add_component(component_type)
|
| 125 |
+
elif command.startswith("set "):
|
| 126 |
+
_, output = set_component_property(command)
|
| 127 |
+
elif command.startswith("search "):
|
| 128 |
+
search_query = command.split("search ", 1)[1].strip()
|
| 129 |
+
output = i_s(search_query)
|
| 130 |
+
elif command.startswith("deploy "):
|
| 131 |
+
app_name = command.split("deploy ", 1)[1].strip()
|
| 132 |
+
output = deploy_to_huggingface(app_name)
|
| 133 |
+
else:
|
| 134 |
+
# Attempt to execute command as Python code
|
| 135 |
+
try:
|
| 136 |
+
result = subprocess.check_output(
|
| 137 |
+
command, shell=True, stderr=subprocess.STDOUT, text=True
|
| 138 |
)
|
| 139 |
+
output = result
|
| 140 |
+
except Exception as e:
|
| 141 |
+
output = f"Error executing Python code: {str(e)}"
|
| 142 |
+
except Exception as e:
|
| 143 |
+
output = f"Error: {str(e)}"
|
| 144 |
+
finally:
|
| 145 |
+
terminal_history += f"User: {command}\n"
|
| 146 |
+
terminal_history += f"{output}\n"
|
| 147 |
+
return terminal_history
|
| 148 |
+
|
| 149 |
+
def set_component_property(command):
|
| 150 |
+
try:
|
| 151 |
+
# Improved 'set' command parsing
|
| 152 |
+
set_parts = command.split(" ", 2)[1:]
|
| 153 |
+
if len(set_parts) != 2:
|
| 154 |
+
raise ValueError("Invalid 'set' command format.")
|
| 155 |
+
|
| 156 |
+
component_id = int(set_parts[0]) # Use component ID
|
| 157 |
+
property_name, property_value = set_parts[1].split("=", 1)
|
| 158 |
+
|
| 159 |
+
# Find component by ID
|
| 160 |
+
component_found = False
|
| 161 |
+
for component in app_state["components"]:
|
| 162 |
+
if component["id"] == component_id:
|
| 163 |
+
if property_name in component["properties"]:
|
| 164 |
+
component["properties"][
|
| 165 |
+
property_name.strip()
|
| 166 |
+
] = property_value.strip()
|
| 167 |
+
component_found = True
|
| 168 |
+
return (
|
| 169 |
+
update_app_canvas(),
|
| 170 |
+
f"System: Property '{property_name}' set to '{property_value}' for component {component_id}\n",
|
| 171 |
+
)
|
| 172 |
+
else:
|
| 173 |
+
return (
|
| 174 |
+
None,
|
| 175 |
+
f"Error: Property '{property_name}' not found in component {component_id}\n",
|
| 176 |
+
)
|
| 177 |
+
if not component_found:
|
| 178 |
+
return (
|
| 179 |
+
None,
|
| 180 |
+
f"Error: Component with ID {component_id} not found.\n",
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
except Exception as e:
|
| 184 |
+
return None, f"Error: Invalid 'set' command format or error setting property: {str(e)}\n"
|
| 185 |
|
|
|
|
|
|
|
| 186 |
#--- Function to handle chat interaction ---
|
| 187 |
+
def run_chat(message, history):
|
| 188 |
+
global terminal_history
|
| 189 |
+
if message.startswith("!"):
|
| 190 |
+
command = message[1:]
|
| 191 |
+
terminal_history = run_terminal_command(command, history)
|
| 192 |
+
else:
|
| 193 |
+
# ... (Your regular chat response generation)
|
| 194 |
+
model_index = 0 # Select the model to use for chat response
|
| 195 |
+
response = get_nlp_response(message, model_index)
|
| 196 |
+
if response:
|
| 197 |
+
return history, terminal_history + f"User: {message}\nAssistant: {response}"
|
| 198 |
+
else:
|
| 199 |
+
return history, terminal_history + f"User: {message}\nAssistant: I'm sorry, I couldn't generate a response. Please try again.\n"
|
| 200 |
+
|
| 201 |
+
--- Code Generation ---
|
| 202 |
+
def generate_python_code(app_name):
|
| 203 |
+
code = f"""import gradio as gr
|
| 204 |
Define your Gradio components here
|
| 205 |
with gr.Blocks() as {app_name}: """ for component in app_state["components"]: code += " " + Component(**component).render() + "\n"
|
| 206 |
|
| 207 |
code += f"""
|
| 208 |
{app_name}.launch() """ return code
|
| 209 |
|
| 210 |
+
--- Hugging Face Deployment ---
|
| 211 |
+
def deploy_to_huggingface(app_name):
|
| 212 |
|
| 213 |
+
Generate Python code
|
| 214 |
+
code = generate_python_code(app_name)
|
| 215 |
|
| 216 |
+
Create requirements.txt
|
| 217 |
with open("requirements.txt", "w") as f:
|
| 218 |
+
f.write("gradio==3.32.0\n")
|
| 219 |
|
| 220 |
+
Create the app.py file
|
| 221 |
with open("app.py", "w") as f:
|
| 222 |
+
f.write(code)
|
| 223 |
|
| 224 |
+
Execute the deployment command
|
| 225 |
try:
|
| 226 |
+
subprocess.run(
|
| 227 |
+
["huggingface-cli", "repo", "create", "--type", "space", "--space_sdk", "gradio", app_name],
|
| 228 |
+
check=True
|
| 229 |
+
)
|
| 230 |
+
subprocess.run(
|
| 231 |
+
["git", "init"], cwd=f"./{app_name}', check=True
|
| 232 |
+
)
|
| 233 |
+
subprocess.run(
|
| 234 |
+
["git", "add", "."], cwd=f'./{app_name}', check=True
|
| 235 |
+
)
|
| 236 |
+
subprocess.run(
|
| 237 |
+
['git', 'commit', '-m', '"Initial commit"'], cwd=f'./{app_name}', check=True
|
| 238 |
+
)
|
| 239 |
+
subprocess.run(
|
| 240 |
+
["git", "push", "https://huggingface.co/spaces/" + app_name, "main"], cwd=f'./{app_name}', check=True
|
| 241 |
+
)
|
| 242 |
+
return (
|
| 243 |
+
f"Successfully deployed to Hugging Face Spaces: https://huggingface.co/spaces/{app\_name}"
|
| 244 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
except Exception as e:
|
| 246 |
+
return f"Error deploying to Hugging Face Spaces: {e}"
|
| 247 |
+
|
| 248 |
--- Gradio Interface ---
|
| 249 |
+
with gr.Blocks() as iface:
|
| 250 |
+
|
| 251 |
+
--- Chat Interface ---
|
| 252 |
+
chat_history = gr.Chatbot(label="Chat with Agent")
|
| 253 |
+
chat_input = gr.Textbox(label="Your Message")
|
| 254 |
+
chat_button = gr.Button("Send")
|
| 255 |
|
| 256 |
chat_button.click(
|
| 257 |
+
run_chat,
|
| 258 |
+
inputs=[chat_input, chat_history],
|
| 259 |
+
outputs=[chat_history, terminal_output],
|
| 260 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 261 |
|
| 262 |
+
--- Terminal ---
|
| 263 |
+
terminal_output = gr.Textbox(
|
| 264 |
+
lines=8, label="Terminal", value=terminal_history
|
| 265 |
+
)
|
| 266 |
+
terminal_input = gr.Textbox(label="Enter Command")
|
| 267 |
+
terminal_button = gr.Button("Run")
|
| 268 |
+
|
| 269 |
+
terminal_button.click(
|
| 270 |
+
run_terminal_command,
|
| 271 |
+
inputs=[terminal_input, terminal_output],
|
| 272 |
+
outputs=terminal_output,
|
| 273 |
+
)
|
| 274 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 275 |
iface.launch()
|