Spaces:
Runtime error
Runtime error
File size: 10,566 Bytes
c9cb3bc e3abedf c9cb3bc beda045 e3abedf c9cb3bc e3abedf beda045 c9cb3bc f6f4b8a c9cb3bc f6f4b8a c9cb3bc f6f4b8a c9cb3bc f6f4b8a c9cb3bc f6f4b8a beda045 c9cb3bc f9a1d72 c9cb3bc beda045 c9cb3bc beda045 c9cb3bc f9a1d72 c9cb3bc f9a1d72 c9cb3bc beda045 c9cb3bc beda045 c9cb3bc beda045 c9cb3bc f9a1d72 beda045 c9cb3bc beda045 c9cb3bc beda045 c9cb3bc beda045 c9cb3bc f9a1d72 beda045 c9cb3bc beda045 c9cb3bc beda045 e3abedf c9cb3bc e3abedf c9cb3bc beda045 c9cb3bc beda045 c9cb3bc beda045 c9cb3bc beda045 c9cb3bc beda045 c9cb3bc beda045 |
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 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 |
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) |