Skip to main content

gradio designer

Project description


tags: [gradio-custom-component, SimpleTextbox, designer, drag and drop, custom designs] title: gradio_gradiodesigner short_description: gradio designer colorFrom: blue colorTo: yellow sdk: gradio pinned: false app_file: space.py

gradio_gradiodesigner

Static Badge

gradio designer

Installation

pip install gradio_gradiodesigner

Usage

import gradio as gr
from gradio_gradiodesigner import GradioDesigner
import json

def analyze_design(design_config):
    """Analyze the design configuration"""
    if not design_config or not isinstance(design_config, dict):
        return "No design configuration provided"
    
    components = design_config.get('components', [])
    
    # Count components by type
    component_types = {}
    for comp in components:
        comp_type = comp.get('type', 'Unknown')
        component_types[comp_type] = component_types.get(comp_type, 0) + 1
    
    # Calculate coverage area
    if components:
        positions = [(comp['position']['x'], comp['position']['y']) for comp in components]
        min_x, min_y = min(pos[0] for pos in positions), min(pos[1] for pos in positions)
        max_x, max_y = max(pos[0] for pos in positions), max(pos[1] for pos in positions)
        coverage = f"{max_x - min_x} x {max_y - min_y} pixels"
    else:
        coverage = "No components"
    
    analysis = f"""📊 **Design Analysis**

**Component Summary:**
• Total components: {len(components)}
• Component types: {dict(component_types)}
• Canvas coverage: {coverage}

**Component Details:**
"""
    
    for i, comp in enumerate(components, 1):
        analysis += f"\n{i}. **{comp['type']}** (`{comp['id']}`)"
        analysis += f"\n   - Position: ({comp['position']['x']}, {comp['position']['y']})"
        analysis += f"\n   - Size: {comp['size']['width']}×{comp['size']['height']}"
        if comp.get('props', {}).get('label'):
            analysis += f"\n   - Label: \"{comp['props']['label']}\""
    
    return analysis

def generate_gradio_code(design_config):
    """Generate complete Gradio code from design"""
    if not design_config or not isinstance(design_config, dict):
        return "# No design to generate code from"
    
    components = design_config.get('components', [])
    
    code = '''import gradio as gr

def process_input(*args):
    """Process the inputs from your app"""
    return "Hello from your generated app!"

with gr.Blocks(title="Generated Gradio App") as demo:
    gr.Markdown("# 🚀 Generated Gradio App")
    gr.Markdown("This app was generated from your visual design!")
    
'''
    
    # Sort components by position (top to bottom, left to right)
    sorted_components = sorted(components, key=lambda c: (c['position']['y'], c['position']['x']))
    
    component_vars = []
    
    for comp in sorted_components:
        comp_type = comp.get('type', 'Textbox')
        comp_id = comp.get('id', 'component')
        props = comp.get('props', {})
        
        # Build component declaration
        prop_parts = []
        for key, value in props.items():
            if key in ['label', 'placeholder', 'value'] and isinstance(value, str):
                prop_parts.append(f'{key}="{value}"')
            elif key in ['minimum', 'maximum', 'step', 'lines', 'max_length', 'precision'] and isinstance(value, (int, float)):
                prop_parts.append(f'{key}={value}')
            elif key == 'choices' and isinstance(value, list):
                prop_parts.append(f'{key}={value}')
            elif isinstance(value, bool):
                prop_parts.append(f'{key}={value}')
        
        prop_string = ", ".join(prop_parts) if prop_parts else ""
        
        code += f"    {comp_id} = gr.{comp_type}({prop_string})\n"
        component_vars.append(comp_id)
    
    # Add a simple interaction if there are components
    if component_vars:
        inputs = [var for var in component_vars if not var.startswith('button')]
        outputs = [var for var in component_vars if var.startswith('button')]
        
        if not outputs:
            outputs = inputs[:1]  # Use first input as output if no buttons
        
        if inputs and outputs:
            code += f"\n    # Add interactions\n"
            code += f"    # Example: connect inputs to outputs\n"
            code += f"    # {outputs[0]}.click(process_input, inputs=[{', '.join(inputs)}], outputs=[{outputs[0]}])\n"
    
    code += '''
if __name__ == "__main__":
    demo.launch()
'''
    
    return code

with gr.Blocks(title="Gradio Visual Designer Pro", theme=gr.themes.Soft()) as demo:
    gr.Markdown("""
    # 🎨 Gradio Visual Designer Pro
    
    **Build your Gradio apps visually!** Drag and drop components, customize properties, and generate production-ready code.
    
    **Features:** 25+ Gradio components • Real-time editing • Code generation • Export options
    """)
    
    with gr.Row():
        designer = GradioDesigner(
            label="Visual App Designer",
            value={"components": [], "layout": "blocks"}
        )
    
    with gr.Row():
        with gr.Column(scale=1):
            analysis_output = gr.Markdown(
                value="Design analysis will appear here...",
                label="Design Analysis"
            )
        
        with gr.Column(scale=1):
            code_output = gr.Code(
                label="Generated Gradio Code",
                language="python",
                value="# Design your app above to see generated code",
                lines=20
            )
    
    with gr.Row():
        analyze_btn = gr.Button("📊 Analyze Design", variant="secondary")
        generate_btn = gr.Button("🚀 Generate Code", variant="primary")
        clear_btn = gr.Button("🗑️ Clear All", variant="stop")
    
    # Event handlers
    designer.change(
        fn=analyze_design,
        inputs=[designer], 
        outputs=[analysis_output]
    )
    
    analyze_btn.click(
        fn=analyze_design,
        inputs=[designer],
        outputs=[analysis_output]
    )
    
    generate_btn.click(
        fn=generate_gradio_code,
        inputs=[designer],
        outputs=[code_output]
    )
    
    clear_btn.click(
        fn=lambda: {"components": [], "layout": "blocks"},
        outputs=[designer]
    )

if __name__ == "__main__":
    demo.launch()

GradioDesigner

Initialization

name type default description
value
dict | None
None None
label
str | None
None None

Events

name description
change Triggered when the value of the GradioDesigner changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See .input() for a listener that is only triggered by user input.
input This listener is triggered when the user changes the value of the GradioDesigner.

User function

The impact on the users predict function varies depending on whether the component is used as an input or output for an event (or both).

  • When used as an Input, the component only impacts the input signature of the user function.
  • When used as an output, the component only impacts the return signature of the user function.

The code snippet below is accurate in cases where the component is used as both an input and an output.

def predict(
    value: dict | None
) -> dict | None:
    return value

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

gradio_gradiodesigner-0.0.1.tar.gz (90.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

gradio_gradiodesigner-0.0.1-py3-none-any.whl (23.3 kB view details)

Uploaded Python 3

File details

Details for the file gradio_gradiodesigner-0.0.1.tar.gz.

File metadata

  • Download URL: gradio_gradiodesigner-0.0.1.tar.gz
  • Upload date:
  • Size: 90.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.3

File hashes

Hashes for gradio_gradiodesigner-0.0.1.tar.gz
Algorithm Hash digest
SHA256 d3fc53c3092edf8d7ae626f17c87ddaf1a14ce3a48277b5e0d295f5a13fb2436
MD5 caf522bf57d053cdc2e60f9a871a5afb
BLAKE2b-256 2c6ef64c7fb5fb5e289114c8bd00335458ae783201955bebbbae3ccfc2f36d54

See more details on using hashes here.

File details

Details for the file gradio_gradiodesigner-0.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for gradio_gradiodesigner-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 5f5bb1595241cb84970214ba0a5b4b75580ab832188e83a543494ddeb450f18a
MD5 69b13ab9a9587ad0ad528272364ebbb0
BLAKE2b-256 f610176ccacf519837196ee70d2e2b88917968ea2b8e05d28d96a17c4f35f38a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page