Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,101 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
-
from
|
| 3 |
-
from
|
| 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 |
-
Agent("ProgressTracker", "Progress Monitor", ["Progress Tracking", "Reporting", "Issue Resolution"], "google/flan-t5-base"),
|
| 62 |
-
])
|
| 63 |
-
|
| 64 |
-
# Agent Cluster for a Documentation Generator
|
| 65 |
-
documentation_agents = AgentCluster([
|
| 66 |
-
Agent("DocWriter", "Documentation Writer", ["Technical Writing", "API Documentation", "User Guides"], "google/flan-t5-base"),
|
| 67 |
-
Agent("CodeDocumenter", "Code Commenter", ["Code Documentation", "Code Explanation", "Code Readability"], "google/flan-t5-base"),
|
| 68 |
-
Agent("ContentOrganizer", "Content Manager", ["Content Structure", "Information Architecture", "Content Organization"], "google/flan-t5-base"),
|
| 69 |
-
])
|
| 70 |
-
|
| 71 |
-
# --- Web App Logic ---
|
| 72 |
-
|
| 73 |
-
def process_input(input_text: str, selected_cluster: str):
|
| 74 |
-
"""Processes user input and assigns tasks to the appropriate agent cluster."""
|
| 75 |
-
if selected_cluster == "Code Review":
|
| 76 |
-
cluster = code_review_agents
|
| 77 |
-
elif selected_cluster == "Project Management":
|
| 78 |
-
cluster = project_management_agents
|
| 79 |
-
elif selected_cluster == "Documentation Generation":
|
| 80 |
-
cluster = documentation_agents
|
| 81 |
else:
|
| 82 |
-
return "
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import subprocess
|
| 3 |
+
import random
|
| 4 |
+
import json
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
from huggingface_hub import InferenceClient, cached_download, hf_hub_url
|
| 7 |
import gradio as gr
|
| 8 |
+
from safe_search import safe_search
|
| 9 |
+
from i_search import google, i_search as i_s
|
| 10 |
+
from agent import (
|
| 11 |
+
ACTION_PROMPT, ADD_PROMPT, COMPRESS_HISTORY_PROMPT, LOG_PROMPT,
|
| 12 |
+
LOG_RESPONSE, MODIFY_PROMPT, PRE_PREFIX, SEARCH_QUERY, READ_PROMPT,
|
| 13 |
+
TASK_PROMPT, UNDERSTAND_TEST_RESULTS_PROMPT
|
| 14 |
+
)
|
| 15 |
+
from utils import parse_action, parse_file_content, read_python_module_structure
|
| 16 |
+
|
| 17 |
+
# Global Variables for App State
|
| 18 |
+
app_state = {"components": []}
|
| 19 |
+
terminal_history = ""
|
| 20 |
+
|
| 21 |
+
# Component Library
|
| 22 |
+
components_registry = {
|
| 23 |
+
"Button": {
|
| 24 |
+
"properties": {"label": "Click Me", "onclick": ""},
|
| 25 |
+
"description": "A clickable button",
|
| 26 |
+
"code_snippet": 'gr.Button(value="{label}", variant="primary")',
|
| 27 |
+
},
|
| 28 |
+
"Text Input": {
|
| 29 |
+
"properties": {"value": "", "placeholder": "Enter text"},
|
| 30 |
+
"description": "A field for entering text",
|
| 31 |
+
"code_snippet": 'gr.Textbox(label="{placeholder}")',
|
| 32 |
+
},
|
| 33 |
+
"Image": {
|
| 34 |
+
"properties": {"src": "#", "alt": "Image"},
|
| 35 |
+
"description": "Displays an image",
|
| 36 |
+
"code_snippet": 'gr.Image(label="{alt}")',
|
| 37 |
+
},
|
| 38 |
+
"Dropdown": {
|
| 39 |
+
"properties": {"choices": ["Option 1", "Option 2"], "value": ""},
|
| 40 |
+
"description": "A dropdown menu for selecting options",
|
| 41 |
+
"code_snippet": 'gr.Dropdown(choices={choices}, label="Dropdown")',
|
| 42 |
+
},
|
| 43 |
+
# Add more components here...
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
# NLP Model (Example using Hugging Face)
|
| 47 |
+
nlp_model_names = [
|
| 48 |
+
"google/flan-t5-small",
|
| 49 |
+
"Qwen/CodeQwen1.5-7B-Chat-GGUF",
|
| 50 |
+
"bartowski/Codestral-22B-v0.1-GGUF",
|
| 51 |
+
"bartowski/AutoCoder-GGUF"
|
| 52 |
+
]
|
| 53 |
+
nlp_models = []
|
| 54 |
+
|
| 55 |
+
for nlp_model_name in nlp_model_names:
|
| 56 |
+
try:
|
| 57 |
+
cached_download(hf_hub_url(nlp_model_name, revision="main"))
|
| 58 |
+
nlp_models.append(InferenceClient(nlp_model_name))
|
| 59 |
+
except:
|
| 60 |
+
nlp_models.append(None)
|
| 61 |
+
|
| 62 |
+
# Function to get NLP model response
|
| 63 |
+
def get_nlp_response(input_text, model_index):
|
| 64 |
+
if nlp_models[model_index]:
|
| 65 |
+
response = nlp_models[model_index].text_generation(input_text)
|
| 66 |
+
return response.generated_text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
else:
|
| 68 |
+
return "NLP model not available."
|
| 69 |
+
|
| 70 |
+
# Component Class
|
| 71 |
+
class Component:
|
| 72 |
+
def __init__(self, type, properties=None, id=None):
|
| 73 |
+
self.id = id or random.randint(1000, 9999)
|
| 74 |
+
self.type = type
|
| 75 |
+
self.properties = properties or components_registry[type]["properties"].copy()
|
| 76 |
+
|
| 77 |
+
def to_dict(self):
|
| 78 |
+
return {
|
| 79 |
+
"id": self.id,
|
| 80 |
+
"type": self.type,
|
| 81 |
+
"properties": self.properties,
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
def render(self):
|
| 85 |
+
# Properly format choices for Dropdown
|
| 86 |
+
if self.type == "Dropdown":
|
| 87 |
+
self.properties["choices"] = (
|
| 88 |
+
str(self.properties["choices"])
|
| 89 |
+
.replace("[", "")
|
| 90 |
+
.replace("]", "")
|
| 91 |
+
.replace("'", "")
|
| 92 |
+
)
|
| 93 |
+
return components_registry[self.type]["code_snippet"].format(**self.properties)
|
| 94 |
+
|
| 95 |
+
# Function to update the app canvas (for preview)
|
| 96 |
+
def update_app_canvas():
|
| 97 |
+
components_html = "".join([
|
| 98 |
+
f"<div>Component ID: {component['id']}, Type: {component['type']}, Properties: {component['properties']}</div>"
|
| 99 |
+
for component in app_state["components"]
|
| 100 |
+
])
|
| 101 |
+
return components_html
|
| 102 |
+
|
| 103 |
+
# Function to handle component addition
|
| 104 |
+
def add_component(component_type):
|
| 105 |
+
if component_type in components_registry:
|
| 106 |
+
new_component = Component(component_type)
|
| 107 |
+
app_state["components"].append(new_component.to_dict())
|
| 108 |
+
return update_app_canvas(), f"System: Added component: {component_type}\n"
|
| 109 |
+
else:
|
| 110 |
+
return None, f"Error: Invalid component type: {component_type}\n"
|
| 111 |
+
|
| 112 |
+
# Function to handle terminal input
|
| 113 |
+
def run_terminal_command(command, history):
|
| 114 |
+
global terminal_history
|
| 115 |
+
output = ""
|
| 116 |
+
try:
|
| 117 |
+
# Basic command parsing (expand with NLP)
|
| 118 |
+
if command.startswith("add "):
|
| 119 |
+
component_type = command.split("add ", 1)[1].strip()
|
| 120 |
+
_, output = add_component(component_type)
|
| 121 |
+
elif command.startswith("set "):
|
| 122 |
+
_, output = set_component_property(command)
|
| 123 |
+
elif command.startswith("search "):
|
| 124 |
+
search_query = command.split("search ", 1)[1].strip()
|
| 125 |
+
output = i_s(search_query)
|
| 126 |
+
elif command.startswith("deploy "):
|
| 127 |
+
app_name = command.split("deploy ", 1)[1].strip()
|
| 128 |
+
output = deploy_to_huggingface(app_name)
|
| 129 |
+
else:
|
| 130 |
+
# Attempt to execute command as Python code
|
| 131 |
+
try:
|
| 132 |
+
result = subprocess.check_output(
|
| 133 |
+
command, shell=True, stderr=subprocess.STDOUT, text=True
|
| 134 |
+
)
|
| 135 |
+
output = result
|
| 136 |
+
except Exception as e:
|
| 137 |
+
output = f"Error executing Python code: {str(e)}"
|
| 138 |
+
except Exception as e:
|
| 139 |
+
output = f"Error: {str(e)}"
|
| 140 |
+
finally:
|
| 141 |
+
terminal_history += f"User: {command}\n{output}\n"
|
| 142 |
+
return terminal_history
|
| 143 |
+
|
| 144 |
+
def set_component_property(command):
|
| 145 |
+
try:
|
| 146 |
+
# Improved 'set' command parsing
|
| 147 |
+
set_parts = command.split(" ", 2)[1:]
|
| 148 |
+
if len(set_parts) != 2:
|
| 149 |
+
raise ValueError("Invalid 'set' command format.")
|
| 150 |
+
component_id = int(set_parts[0]) # Use component ID
|
| 151 |
+
property_name, property_value = set_parts[1].split("=", 1)
|
| 152 |
+
# Find component by ID
|
| 153 |
+
component_found = False
|
| 154 |
+
for component in app_state["components"]:
|
| 155 |
+
if component["id"] == component_id:
|
| 156 |
+
if property_name in component["properties"]:
|
| 157 |
+
component["properties"][property_name.strip()] = property_value.strip()
|
| 158 |
+
component_found = True
|
| 159 |
+
return update_app_canvas(), f"System: Property '{property_name}' set to '{property_value}' for component {component_id}\n"
|
| 160 |
+
else:
|
| 161 |
+
return None, f"Error: Property '{property_name}' not found in component {component_id}\n"
|
| 162 |
+
if not component_found:
|
| 163 |
+
return None, f"Error: Component with ID {component_id} not found.\n"
|
| 164 |
+
except Exception as e:
|
| 165 |
+
return None, f"Error: {str(e)}\n"
|
| 166 |
+
|
| 167 |
+
# Function to handle chat interaction
|
| 168 |
+
def run_chat(message, history):
|
| 169 |
+
global terminal_history
|
| 170 |
+
if message.startswith("!"):
|
| 171 |
+
command = message[1:]
|
| 172 |
+
terminal_history = run_terminal_command(command, history)
|
| 173 |
+
else:
|
| 174 |
+
model_index = 0 # Select the model to use for chat response
|
| 175 |
+
response = get_nlp_response(message, model_index)
|
| 176 |
+
if response:
|
| 177 |
+
return history, terminal_history + f"User: {message}\nAssistant: {response}"
|
| 178 |
+
else:
|
| 179 |
+
return history, terminal_history + f"User: {message}\nAssistant: I'm sorry, I couldn't generate a response. Please try again.\n"
|
| 180 |
+
|
| 181 |
+
# Code Generation
|
| 182 |
+
def generate_python_code(app_name):
|
| 183 |
+
code = f"""import gradio as gr\n\nwith gr.Blocks() as {app_name}:\n"""
|
| 184 |
+
for component in app_state["components"]:
|
| 185 |
+
code += " " + Component(**component).render() + "\n"
|
| 186 |
+
code += f"\n{app_name}.launch()\n"
|
| 187 |
+
return code
|
| 188 |
+
|
| 189 |
+
# Hugging Face Deployment
|
| 190 |
+
def deploy_to_huggingface(app_name):
|
| 191 |
+
# Generate Python code
|
| 192 |
+
code = generate_python_code(app_name)
|
| 193 |
+
# Create requirements.txt
|
| 194 |
+
with open("requirements.txt", "w") as f:
|
| 195 |
+
f.write("gradio==3.32.0\n")
|
| 196 |
+
# Create the app.py file
|
| 197 |
+
with open("app.py", "w") as f:
|
| 198 |
+
f.write(code)
|
| 199 |
+
# Execute the deployment command
|
| 200 |
+
try:
|
| 201 |
+
subprocess.run(["huggingface-cli", "repo", "create", "--type", "space", "--space_sdk", "gradio", app_name], check=True)
|
| 202 |
+
subprocess.run(["git", "init"], cwd=f"./{app_name}", check=True)
|
| 203 |
+
subprocess.run(["git", "add", "."], cwd=f"./{app_name}", check=True)
|
| 204 |
+
subprocess.run(["git", "commit", "-m", "Initial commit"], cwd=f"./{app_name}", check=True)
|
| 205 |
+
subprocess.run(["git", "push", "https://huggingface.co/spaces/" + app_name, "main"], cwd=f"./{app_name}", check=True)
|
| 206 |
+
return f"Successfully deployed to Hugging Face Spaces: https://huggingface.co/spaces/{app_name}"
|
| 207 |
+
except Exception as e:
|
| 208 |
+
return f"Error deploying to Hugging Face Spaces: {e}"
|
| 209 |
+
|
| 210 |
+
# Gradio Interface
|
| 211 |
+
with gr.Blocks() as iface:
|
| 212 |
+
# Chat Interface
|
| 213 |
+
chat_history = gr.Chatbot(label="Chat with Agent")
|
| 214 |
+
chat_input = gr.Textbox(label="Your Message")
|
| 215 |
+
chat_button = gr.Button("Send")
|
| 216 |
+
chat_button.click(run_chat, inputs=[chat_input, chat_history], outputs=[chat_history, terminal_output])
|
| 217 |
+
|
| 218 |
+
# Terminal
|
| 219 |
+
terminal_output = gr.Textbox(lines=8, label="Terminal", value=terminal_history)
|
| 220 |
+
terminal_input = gr.Textbox(label="Enter Command")
|
| 221 |
+
terminal_button = gr.Button("Run")
|
| 222 |
+
terminal_button.click(run_terminal_command, inputs=[terminal_input, terminal_output], outputs=terminal_output)
|
| 223 |
+
|
| 224 |
+
iface.launch()
|