import gradio as gr import subprocess import random import json import os import tempfile from pathlib import Path from datetime import datetime import logging from typing import Dict, List, Any, Optional import yaml # Configure logging logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) # Template Categories and Configurations TEMPLATE_CATEGORIES = { "Chat Applications": { "Basic Chat": { "components": [ {"type": "Chatbot", "label": "Chat History"}, {"type": "Textbox", "label": "User Input", "placeholder": "Type your message..."}, {"type": "Button", "label": "Send", "variant": "primary"}, {"type": "Radio", "label": "Model", "choices": ["GPT-3.5", "GPT-4", "Claude", "Custom"]}, {"type": "Slider", "label": "Temperature", "minimum": 0, "maximum": 1, "step": 0.1}, {"type": "Checkbox", "label": "Stream Output"}, ], "layout": "vertical", "css": """ .chat-container { max-width: 800px; margin: auto; } .message { padding: 10px; margin: 5px; border-radius: 5px; } .user { background: #e3f2fd; } .bot { background: #f5f5f5; } """ }, "Advanced Chat": { "components": [ {"type": "Chatbot", "label": "Chat History"}, {"type": "Textbox", "label": "User Input", "placeholder": "Type your message..."}, {"type": "Button", "label": "Send", "variant": "primary"}, {"type": "Dropdown", "label": "Model", "choices": ["GPT-3.5", "GPT-4", "Claude", "Custom"]}, {"type": "Slider", "label": "Temperature", "minimum": 0, "maximum": 1, "step": 0.1}, {"type": "Slider", "label": "Max Length", "minimum": 100, "maximum": 2000, "step": 100}, {"type": "Checkbox", "label": "Stream Output"}, {"type": "File", "label": "Upload Context", "file_types": [".txt", ".pdf"]}, {"type": "Dropdown", "label": "Language", "choices": ["English", "Spanish", "French", "German"]}, {"type": "Radio", "label": "Mode", "choices": ["Chat", "Completion", "QA"]}, ], "layout": "vertical", "dependencies": ["openai", "transformers", "langchain"] } }, "Audio Generation": { "Music Generator": { "components": [ {"type": "Audio", "label": "Generated Audio", "source": "microphone"}, {"type": "Textbox", "label": "Prompt", "placeholder": "Describe the music..."}, {"type": "Dropdown", "label": "Style", "choices": ["Classical", "Jazz", "Rock", "Electronic"]}, {"type": "Slider", "label": "Duration (seconds)", "minimum": 5, "maximum": 60}, {"type": "Button", "label": "Generate", "variant": "primary"}, {"type": "File", "label": "Download", "file_types": [".mp3", ".wav"]}, ], "layout": "vertical", "dependencies": ["audiocraft", "torchaudio"] } }, "Image Processing": { "Image Generator": { "components": [ {"type": "Image", "label": "Generated Image"}, {"type": "Textbox", "label": "Prompt", "placeholder": "Describe the image..."}, {"type": "Dropdown", "label": "Model", "choices": ["Stable Diffusion", "DALL-E", "Midjourney"]}, {"type": "Slider", "label": "Steps", "minimum": 20, "maximum": 100}, {"type": "Button", "label": "Generate", "variant": "primary"}, ], "layout": "vertical", "dependencies": ["diffusers", "torch"] }, "Image Editor": { "components": [ {"type": "Image", "label": "Input Image", "source": "upload"}, {"type": "Image", "label": "Output Image"}, {"type": "Dropdown", "label": "Effect", "choices": ["Blur", "Sharpen", "Style Transfer"]}, {"type": "Slider", "label": "Intensity", "minimum": 0, "maximum": 1, "step": 0.1}, {"type": "Button", "label": "Apply", "variant": "primary"}, ], "layout": "horizontal", "dependencies": ["pillow", "opencv-python"] } }, "3D Processing": { "3D Model Viewer": { "components": [ {"type": "Model3D", "label": "3D Model"}, {"type": "File", "label": "Upload Model", "file_types": [".obj", ".glb", ".gltf"]}, {"type": "Checkbox", "label": "Show Wireframe"}, {"type": "ColorPicker", "label": "Background Color"}, {"type": "Slider", "label": "Camera Distance", "minimum": 1, "maximum": 10}, ], "layout": "vertical", "dependencies": ["pygltflib", "trimesh"] } }, "Data Analysis": { "Data Explorer": { "components": [ {"type": "File", "label": "Upload Dataset", "file_types": [".csv", ".xlsx"]}, {"type": "Dataframe", "label": "Data Preview"}, {"type": "Dropdown", "label": "Chart Type", "choices": ["Line", "Bar", "Scatter", "Histogram"]}, {"type": "Dropdown", "label": "X Axis"}, {"type": "Dropdown", "label": "Y Axis"}, {"type": "Plot", "label": "Visualization"}, ], "layout": "vertical", "dependencies": ["pandas", "plotly"] } } } # Enhanced Component Registry with Categories COMPONENT_CATEGORIES = { "Basic Input": { "Textbox": { "properties": { "label": "Text Input", "placeholder": "Enter text...", "lines": 1, "type": "text" }, "code_snippet": 'gr.Textbox(label="{label}", placeholder="{placeholder}", lines={lines})' }, "Number": { "properties": { "label": "Number Input", "value": 0, "minimum": None, "maximum": None }, "code_snippet": 'gr.Number(label="{label}", value={value}, minimum={minimum}, maximum={maximum})' }, "Slider": { "properties": { "label": "Slider", "minimum": 0, "maximum": 100, "step": 1, "value": 50 }, "code_snippet": 'gr.Slider(label="{label}", minimum={minimum}, maximum={maximum}, step={step}, value={value})' } }, "Media Input": { "Image": { "properties": { "label": "Image Input", "source": "upload", "tool": "select", "type": "filepath" }, "code_snippet": 'gr.Image(label="{label}", source="{source}", tool="{tool}", type="{type}")' }, "Audio": { "properties": { "label": "Audio Input", "source": "upload", "type": "filepath" }, "code_snippet": 'gr.Audio(label="{label}", source="{source}", type="{type}")' }, "Video": { "properties": { "label": "Video Input", "source": "upload", "format": "mp4" }, "code_snippet": 'gr.Video(label="{label}", source="{source}", format="{format}")' } }, "Control Elements": { "Button": { "properties": { "label": "Click Me", "variant": "primary", "size": "sm" }, "code_snippet": 'gr.Button(value="{label}", variant="{variant}", size="{size}")' }, "Checkbox": { "properties": { "label": "Check this", "value": False }, "code_snippet": 'gr.Checkbox(label="{label}", value={value})' }, "Radio": { "properties": { "label": "Select One", "choices": ["Option 1", "Option 2", "Option 3"], "value": "Option 1" }, "code_snippet": 'gr.Radio(label="{label}", choices={choices}, value="{value}")' } }, "Advanced Input": { "JSON": { "properties": { "label": "JSON Input", "value": "{}" }, "code_snippet": 'gr.JSON(label="{label}", value={value})' }, "File": { "properties": { "label": "File Upload", "file_types": [".txt", ".pdf", ".csv"], "multiple": False }, "code_snippet": 'gr.File(label="{label}", file_types={file_types}, multiple={multiple})' }, "Dataframe": { "properties": { "label": "Data Table", "headers": ["Column 1", "Column 2"], "interactive": True }, "code_snippet": 'gr.Dataframe(label="{label}", headers={headers}, interactive={interactive})' } }, "Output Display": { "Label": { "properties": { "label": "Output Label", "value": "Result will appear here..." }, "code_snippet": 'gr.Label(label="{label}", value="{value}")' }, "Plot": { "properties": { "label": "Plot Output", "type": "line" }, "code_snippet": 'gr.Plot(label="{label}")' }, "HTML": { "properties": { "label": "HTML Output", "value": "
HTML content here
" }, "code_snippet": 'gr.HTML(label="{label}", value="""{value}""")' } } } class ComponentManager: def __init__(self): self.categories = COMPONENT_CATEGORIES self.templates = TEMPLATE_CATEGORIES self.active_components = [] self.dependencies = set() def get_component_info(self, category: str, component_type: str) -> Dict: """Get component information from registry""" return self.categories[category][component_type] def add_component(self, category: str, component_type: str, properties: Dict = None) -> Dict: """Add a component with specified properties""" component_info = self.get_component_info(category, component_type) component_id = f"{component_type}_{len(self.active_components)}" new_component = { "id": component_id, "type": component_type, "category": category, "properties": properties or component_info["properties"].copy(), "code_snippet": component_info["code_snippet"] } self.active_components.append(new_component) return new_component def remove_component(self, component_id: str): """Remove a component by ID""" self.active_components = [c for c in self.active_components if c["id"] != component_id] def update_component(self, component_id: str, properties: Dict): """Update component properties""" for component in self.active_components: if component["id"] == component_id: component["properties"].update(properties) break class TemplateManager: def __init__(self): self.templates = TEMPLATE_CATEGORIES self.component_manager = ComponentManager() def load_template(self, category: str, template_name: str) -> Dict: """Load a template configuration""" template = self.templates[category][template_name] self.component_manager.active_components = [] self.component_manager.dependencies = set(template.get("dependencies", [])) # Add components from template for component_config in template["components"]: component_type = component_config.pop("type") # Find category for component type for cat, components in COMPONENT_CATEGORIES.items(): if component_type in components: self.component_manager.add_component(cat, component_type, component_config) break return { "layout": template.get("layout", "vertical"), "css": template.get("css", ""), "dependencies": list(self.component_manager.dependencies) } class CodeGenerator: def __init__(self, template_manager: TemplateManager): self.template_manager = template_manager def generate_imports(self) -> str: """Generate import statements""" imports = [ "import gradio as gr", "import os", "import logging", "from pathlib import Path", ] # Add template-specific imports if self.template_manager.component_manager.dependencies: imports.extend([f"import {dep}" for dep in self.template_manager.component_manager.dependencies]) return "\n".join(imports) + "\n\n" def generate_component_code(self, component: Dict) -> str: """Generate code for a single component""" try: return component["code_snippet"].format(**component["properties"]) except KeyError as e: logger.error(f"Missing property {e} for component {component['id']}") return f"# Error generating code for {component['id']}" def generate_layout_code(self, layout: str, components: List[Dict]) -> str: """Generate layout code""" indent = " " code = [] if layout == "horizontal": code.append("with gr.Row():") indent = " " elif layout == "vertical": code.append("with gr.Column():") indent = " " for component in components: code.append(f"{indent}{self.generate_component_code(component)}") return "\n".join(code) def generate_full_code(self, app_name: str, template_config: Dict) -> str: """Generate complete application code""" code_parts = [ self.generate_imports(), "# Configure logging", 'logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")', 'logger = logging.getLogger(__name__)\n', ] # Add CSS if present if template_config.get("css"): code_parts.extend([ "# Custom CSS", f'custom_css = """{template_config["css"]}"""', "" ]) # Start app definition code_parts.extend([ f"def create_{app_name}():", " with gr.Blocks(css=custom_css) as app:", f' gr.Markdown("# {app_name}")\n' ]) # Add layout code code_parts.append(self.generate_layout_code( template_config["layout"], self.template_manager.component_manager.active_components )) # Add launch code code_parts.extend([ "\n return app", "\nif __name__ == '__main__':", f" app = create_{app_name}()", " app.launch(debug=True)" ]) return "\n".join(code_parts) class AppBuilder: def __init__(self): self.template_manager = TemplateManager() self.code_generator = CodeGenerator(self.template_manager) self.current_app_name = "" self.current_template = None def create_interface(self): with gr.Blocks(theme=gr.themes.Default()) as interface: gr.Markdown("# 🚀 Advanced Gradio App Builder") with gr.Tabs(): # Template Selection Tab with gr.TabItem("📋 Templates"): with gr.Row(): template_category = gr.Dropdown( choices=list(TEMPLATE_CATEGORIES.keys()), label="Category" ) template_name = gr.Dropdown( label="Template" ) app_name = gr.Textbox(label="Application Name") load_template_btn = gr.Button("Load Template", variant="primary") template_info = gr.JSON(label="Template Information") # Component Editor Tab with gr.TabItem("🔧 Components"): with gr.Row(): with gr.Column(scale=1): component_category = gr.Dropdown( choices=list(COMPONENT_CATEGORIES.keys()), label="Component Category" ) component_type = gr.Dropdown( label="Component Type" ) add_component_btn = gr.Button("Add Component") with gr.Column(scale=2): component_list = gr.JSON(label="Active Components") component_properties = gr.JSON(label="Component Properties") # Code Preview Tab with gr.TabItem("💻 Code"): generate_code_btn = gr.Button("Generate Code") code_output = gr.Code(language="python") # Preview Tab with gr.TabItem("👁️ Preview"): preview_btn = gr.Button("Update Preview") preview_area = gr.HTML() # Event handlers def update_template_choices(category): return gr.Dropdown(choices=list(TEMPLATE_CATEGORIES[category].keys())) def update_component_choices(category): return gr.Dropdown(choices=list(COMPONENT_CATEGORIES[category].keys())) def load_template(category, template_name, app_name): if not app_name: return "Please enter an application name", None self.current_app_name = app_name template_config = self.template_manager.load_template(category, template_name) self.current_template = template_config return "Template loaded successfully", template_config def add_component(category, component_type): if not self.current_template: return "Please load a template first", None new_component = self.template_manager.component_manager.add_component( category, component_type ) return ( "Component added successfully", self.template_manager.component_manager.active_components ) def generate_code(): if not self.current_template or not self.current_app_name: return "Please load a template first" return self.code_generator.generate_full_code( self.current_app_name, self.current_template ) # Connect events template_category.change( update_template_choices, inputs=[template_category], outputs=[template_name] ) component_category.change( update_component_choices, inputs=[component_category], outputs=[component_type] ) load_template_btn.click( load_template, inputs=[template_category, template_name, app_name], outputs=[template_info, component_list] ) add_component_btn.click( add_component, inputs=[component_category, component_type], outputs=[component_list, component_properties] ) generate_code_btn.click( generate_code, outputs=[code_output] ) return interface if __name__ == "__main__": builder = AppBuilder() interface = builder.create_interface() interface.launch(server_port=7860, share=True, debug=True)