File size: 20,728 Bytes
c9cb3bc
e3abedf
c9cb3bc
 
 
 
 
 
 
f72d856
 
e3abedf
c9cb3bc
f72d856
c9cb3bc
e3abedf
f72d856
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beda045
f72d856
 
 
 
 
 
 
 
 
 
 
 
 
beda045
f72d856
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beda045
f72d856
 
 
 
 
 
 
 
 
 
 
 
beda045
f72d856
 
 
 
 
 
 
 
 
 
 
 
 
 
beda045
 
f72d856
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beda045
f72d856
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beda045
f72d856
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beda045
f72d856
 
 
beda045
f72d856
 
 
 
c9cb3bc
f72d856
 
 
 
 
 
c9cb3bc
 
f72d856
 
f6f4b8a
f72d856
 
 
 
 
 
 
 
 
 
f6f4b8a
f72d856
f9a1d72
f72d856
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9a1d72
c9cb3bc
f72d856
 
 
f9a1d72
f72d856
 
 
 
 
 
 
 
 
 
 
 
c9cb3bc
f72d856
 
 
 
 
 
 
 
 
 
 
 
 
 
c9cb3bc
f72d856
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9cb3bc
f72d856
 
 
beda045
f72d856
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9cb3bc
f72d856
 
 
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
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": "<div>HTML content here</div>"
            },
            "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)