Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -37,22 +37,22 @@ from utils import (
|
|
37 |
from datetime import datetime
|
38 |
import json
|
39 |
|
40 |
-
|
41 |
app_state = {"components": []} terminal_history = ""
|
42 |
|
43 |
-
|
44 |
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... }
|
45 |
|
46 |
-
|
47 |
nlp_model_name = "google/flan-t5-small"
|
48 |
|
49 |
-
Check if the model exists in the cache
|
50 |
try: cached_download(hf_hub_url(nlp_model_name, revision="main")) nlp_model = InferenceClient(nlp_model_name) except: nlp_model = None
|
51 |
|
52 |
-
|
53 |
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."
|
54 |
|
55 |
-
--- Component Class ---
|
56 |
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()
|
57 |
|
58 |
def to_dict(self):
|
@@ -74,13 +74,13 @@ def render(self):
|
|
74 |
return components_registry[self.type]["code_snippet"].format(
|
75 |
**self.properties
|
76 |
)
|
77 |
-
--- Function to update the app canvas (for preview) ---
|
78 |
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
|
79 |
|
80 |
-
--- Function to handle component addition ---
|
81 |
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"
|
82 |
|
83 |
-
--- Function to handle terminal input ---
|
84 |
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
|
85 |
|
86 |
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.")
|
@@ -114,10 +114,10 @@ component_id = int(set_parts[0]) # Use component ID
|
|
114 |
|
115 |
except Exception as e:
|
116 |
return None, f"Error: Invalid 'set' command format or error setting property: {str(e)}\n"
|
117 |
-
|
118 |
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
|
119 |
|
120 |
-
--- Code Generation ---
|
121 |
def generate_python_code(app_name): code = f""" import gradio as gr
|
122 |
|
123 |
Define your Gradio components here
|
@@ -126,13 +126,12 @@ with gr.Blocks() as {app_name}: """ for component in app_state["components"]: co
|
|
126 |
code += f"""
|
127 |
{app_name}.launch() """ return code
|
128 |
|
129 |
-
--- Save/Load App State ---
|
130 |
def save_app_state(filename="app_state.json"): with open(filename, "w") as f: json.dump(app_state, f)
|
131 |
|
|
|
132 |
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.")
|
133 |
|
134 |
-
--- Hugging Face Deployment --- def deploy_to_huggingface(app_name): # Generate Python code code = generate_python_code(app_name)
|
135 |
-
|
136 |
# Create requirements.txt
|
137 |
with open("requirements.txt", "w") as f:
|
138 |
f.write("gradio==3.32.0\n")
|
@@ -163,7 +162,7 @@ try:
|
|
163 |
["git", "add", "."], cwd=f"./{app_name}", check=True
|
164 |
)
|
165 |
subprocess.run(
|
166 |
-
['git', 'commit', '-m', '"Initial commit"'], cwd=f"./{app_name}", check=True
|
167 |
)
|
168 |
subprocess.run(
|
169 |
["git", "push", "https://huggingface.co/spaces/" + app_name, "main"], cwd=f"./{app_name}", check=True
|
|
|
37 |
from datetime import datetime
|
38 |
import json
|
39 |
|
40 |
+
#--- Global Variables for App State ---
|
41 |
app_state = {"components": []} terminal_history = ""
|
42 |
|
43 |
+
#--- Component Library ---
|
44 |
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... }
|
45 |
|
46 |
+
#--- NLP Model (Example using Hugging Face) ---
|
47 |
nlp_model_name = "google/flan-t5-small"
|
48 |
|
49 |
+
# Check if the model exists in the cache
|
50 |
try: cached_download(hf_hub_url(nlp_model_name, revision="main")) nlp_model = InferenceClient(nlp_model_name) except: nlp_model = None
|
51 |
|
52 |
+
#--- Function to get NLP model response ---
|
53 |
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."
|
54 |
|
55 |
+
# --- Component Class ---
|
56 |
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()
|
57 |
|
58 |
def to_dict(self):
|
|
|
74 |
return components_registry[self.type]["code_snippet"].format(
|
75 |
**self.properties
|
76 |
)
|
77 |
+
# --- Function to update the app canvas (for preview) ---
|
78 |
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
|
79 |
|
80 |
+
# --- Function to handle component addition ---
|
81 |
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"
|
82 |
|
83 |
+
# --- Function to handle terminal input ---
|
84 |
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
|
85 |
|
86 |
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.")
|
|
|
114 |
|
115 |
except Exception as e:
|
116 |
return None, f"Error: Invalid 'set' command format or error setting property: {str(e)}\n"
|
117 |
+
#--- Function to handle chat interaction ---
|
118 |
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
|
119 |
|
120 |
+
# --- Code Generation ---
|
121 |
def generate_python_code(app_name): code = f""" import gradio as gr
|
122 |
|
123 |
Define your Gradio components here
|
|
|
126 |
code += f"""
|
127 |
{app_name}.launch() """ return code
|
128 |
|
129 |
+
# --- Save/Load App State ---
|
130 |
def save_app_state(filename="app_state.json"): with open(filename, "w") as f: json.dump(app_state, f)
|
131 |
|
132 |
+
# --- Hugging Face Deployment --- def deploy_to_huggingface(app_name): # Generate Python code code = generate_python_code(app_name)
|
133 |
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.")
|
134 |
|
|
|
|
|
135 |
# Create requirements.txt
|
136 |
with open("requirements.txt", "w") as f:
|
137 |
f.write("gradio==3.32.0\n")
|
|
|
162 |
["git", "add", "."], cwd=f"./{app_name}", check=True
|
163 |
)
|
164 |
subprocess.run(
|
165 |
+
['git', 'commit', '-m', '"Initial commit"'], cwd=f"./{user_name}/{app_name}", check=True
|
166 |
)
|
167 |
subprocess.run(
|
168 |
["git", "push", "https://huggingface.co/spaces/" + app_name, "main"], cwd=f"./{app_name}", check=True
|