Spaces:
Runtime error
Runtime error
import gradio as gr | |
import subprocess | |
import random | |
import json | |
import os | |
import tempfile | |
import time | |
from pathlib import Path | |
from datetime import datetime | |
import logging | |
from typing import Dict, List, Any | |
# Configure logging | |
logging.basicConfig( | |
level=logging.INFO, | |
format='%(asctime)s - %(levelname)s - %(message)s' | |
) | |
logger = logging.getLogger(__name__) | |
# Base Component Registry | |
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")', | |
}, | |
} | |
# Define Component class first | |
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): | |
if self.type == "Dropdown": | |
self.properties["choices"] = ( | |
str(self.properties["choices"]) | |
.replace("[", "") | |
.replace("]", "") | |
.replace("'", "") | |
) | |
return components_registry[self.type]["code_snippet"].format(**self.properties) | |
# Define AppCreationProcess class before EnhancedAppCreationProcess | |
class AppCreationProcess: | |
def __init__(self): | |
self.current_step = 1 | |
self.app_name = "" | |
self.components = [] | |
self.theme = "Default" | |
self.custom_css = "" | |
def get_current_step_info(self): | |
steps = { | |
1: "App Initialization", | |
2: "Component Addition", | |
3: "Property Configuration", | |
4: "Code Generation", | |
5: "Deployment" | |
} | |
return f"Step {self.current_step}: {steps[self.current_step]}" | |
def add_component(self, component_type): | |
new_component = Component(component_type) | |
self.components.append(new_component.to_dict()) | |
return self.update_app_canvas() | |
def update_app_canvas(self): | |
components_html = "".join([ | |
f"<div>Component ID: {component['id']}, Type: {component['type']}, " | |
f"Properties: {component['properties']}</div>" | |
for component in self.components | |
]) | |
return components_html | |
def generate_python_code(self): | |
code = f"""import gradio as gr\n\nwith gr.Blocks() as {self.app_name}:\n""" | |
for component in self.components: | |
code += " " + Component(**component).render() + "\n" | |
code += f"\n{self.app_name}.launch()\n" | |
return code | |
# Now define EnhancedAppBuilder | |
class EnhancedAppBuilder: | |
def __init__(self): | |
self.TEMPLATES = { | |
"Basic": "basic_app.json", | |
"Dashboard": "dashboard_template.json", | |
"Data Analysis": "data_analysis_template.json", | |
"ML Interface": "ml_interface_template.json" | |
} | |
self.THEMES = { | |
"Default": {}, | |
"Dark": {"primary_hue": "slate", "secondary_hue": "slate"}, | |
"Light": {"primary_hue": "blue", "secondary_hue": "blue"}, | |
"Professional": {"primary_hue": "indigo", "secondary_hue": "indigo"} | |
} | |
self.ADVANCED_COMPONENTS = { | |
"Plot": { | |
"properties": { | |
"type": ["line", "bar", "scatter", "histogram"], | |
"data_source": "", | |
"x_axis": "", | |
"y_axis": "" | |
}, | |
"code_snippet": 'gr.Plot(value=plot_{id}, label="{label}")' | |
}, | |
"FileUploader": { | |
"properties": { | |
"file_types": [".csv", ".txt", ".pdf", ".png", ".jpg"], | |
"multiple": False | |
}, | |
"code_snippet": 'gr.File(file_types={file_types}, label="{label}")' | |
} | |
} | |
async def validate_component(self, component: Dict) -> tuple: | |
try: | |
required_fields = ["type", "properties", "id"] | |
if not all(field in component for field in required_fields): | |
return False, "Missing required fields" | |
if component["type"] not in {**components_registry, **self.ADVANCED_COMPONENTS}: | |
return False, f"Invalid component type: {component['type']}" | |
return True, "Component validation successful" | |
except Exception as e: | |
return False, f"Validation error: {str(e)}" | |
# Then define EnhancedAppCreationProcess | |
class EnhancedAppCreationProcess(AppCreationProcess): | |
def __init__(self): | |
super().__init__() | |
self.builder = EnhancedAppBuilder() | |
self.history = [] | |
self.event_handlers = {} | |
self.dependencies = [] | |
def save_snapshot(self): | |
snapshot = { | |
'timestamp': datetime.now().isoformat(), | |
'app_name': self.app_name, | |
'components': self.components.copy(), | |
'theme': self.theme, | |
'custom_css': self.custom_css | |
} | |
self.history.append(snapshot) | |
async def generate_enhanced_code(self): | |
try: | |
code = """import gradio as gr | |
import pandas as pd | |
import numpy as np | |
from pathlib import Path | |
import logging | |
logging.basicConfig(level=logging.INFO) | |
logger = logging.getLogger(__name__) | |
""" | |
theme_config = self.builder.THEMES.get(self.theme, {}) | |
code += f"\ntheme = gr.themes.Default({', '.join(f'{k}={v!r}' for k, v in theme_config.items())})\n" | |
if self.custom_css: | |
code += f"\ncustom_css = '''{self.custom_css}'''\n" | |
code += f"\nwith gr.Blocks(theme=theme{',' if self.custom_css else ''} css=custom_css) as {self.app_name}:\n" | |
for component in self.components: | |
code += f" {Component(**component).render()}\n" | |
code += f"\n{self.app_name}.launch(share=True, debug=True)\n" | |
return code, [] | |
except Exception as e: | |
logger.error(f"Code generation error: {str(e)}") | |
return str(e), [] | |
# Create the interface | |
def create_enhanced_interface(): | |
app_process = EnhancedAppCreationProcess() | |
with gr.Blocks(theme=gr.themes.Default()) as iface: | |
gr.Markdown("# 🚀 Enhanced App Builder Pro") | |
with gr.Row(): | |
with gr.Column(scale=2): | |
current_step = gr.Markdown(value=app_process.get_current_step_info()) | |
with gr.Column(scale=1): | |
theme_dropdown = gr.Dropdown( | |
choices=list(app_process.builder.THEMES.keys()), | |
value="Default", | |
label="Theme" | |
) | |
with gr.Tabs(): | |
# App Configuration Tab | |
with gr.TabItem("📱 App Configuration"): | |
app_name_input = gr.Textbox(label="App Name") | |
template_dropdown = gr.Dropdown( | |
choices=list(app_process.builder.TEMPLATES.keys()), | |
label="Template" | |
) | |
init_app_button = gr.Button("Initialize App", variant="primary") | |
init_status = gr.Markdown() | |
# Component Builder Tab | |
with gr.TabItem("🔧 Component Builder"): | |
with gr.Row(): | |
with gr.Column(): | |
component_type = gr.Dropdown( | |
choices=list({**components_registry, **app_process.builder.ADVANCED_COMPONENTS}.keys()), | |
label="Component Type" | |
) | |
add_component_button = gr.Button("Add Component") | |
with gr.Column(): | |
components_display = gr.HTML() | |
# Code Generator Tab | |
with gr.TabItem("💻 Code Generator"): | |
generate_code_button = gr.Button("Generate Code") | |
generated_code = gr.Code(language="python") | |
lint_results = gr.Markdown() | |
# Event handlers | |
def update_theme(theme_name): | |
app_process.theme = theme_name | |
return f"Theme updated to {theme_name}" | |
def init_app(name, template): | |
try: | |
app_process.app_name = name | |
app_process.save_snapshot() | |
return f"✅ App '{name}' initialized successfully with {template} template!" | |
except Exception as e: | |
return f"❌ Error: {str(e)}" | |
def add_component(comp_type): | |
try: | |
result = app_process.add_component(comp_type) | |
return result, "✅ Component added successfully" | |
except Exception as e: | |
return None, f"❌ Error: {str(e)}" | |
async def generate_code(): | |
try: | |
code, lint_results = await app_process.generate_enhanced_code() | |
return code, "Code generated successfully" | |
except Exception as e: | |
return str(e), f"❌ Error in code generation: {str(e)}" | |
# Connect event handlers | |
theme_dropdown.change(update_theme, inputs=[theme_dropdown], outputs=[init_status]) | |
init_app_button.click(init_app, inputs=[app_name_input, template_dropdown], outputs=[init_status]) | |
add_component_button.click(add_component, inputs=[component_type], outputs=[components_display, init_status]) | |
generate_code_button.click(generate_code, outputs=[generated_code, lint_results]) | |
return iface | |
# Launch the application | |
if __name__ == "__main__": | |
iface = create_enhanced_interface() | |
iface.launch(server_port=7860, share=True, debug=True) |