import gradio as gr import json import os from datetime import datetime import requests from huggingface_hub import HfApi, login from pathlib import Path # Configuration management class class ConfigManager: def __init__(self, config_file="config.json"): self.config_file = config_file self.default_config = { "app_name": "Gradio Configurator", "theme": "soft", "primary_color": "blue", "font_size": "medium", "show_header": True, "show_footer": True, "max_items": 10, "api_enabled": False, "last_updated": str(datetime.now()), "ai_model": "TheBloke/SauerkrautLM-Mixtral-8x7B-Instruct-GGUF", "ai_enabled": True, "temperature": 0.7, "max_tokens": 512 } self.load_config() def load_config(self): """Load configuration from file or use defaults""" try: if os.path.exists(self.config_file): with open(self.config_file, 'r') as f: self.config = json.load(f) else: self.config = self.default_config.copy() self.save_config() except Exception as e: print(f"Error loading config: {e}") self.config = self.default_config.copy() def save_config(self): """Save current configuration to file""" try: with open(self.config_file, 'w') as f: json.dump(self.config, f, indent=2) return True except Exception as e: print(f"Error saving config: {e}") return False def update_config(self, **kwargs): """Update configuration with new values""" for key, value in kwargs.items(): if key in self.config: self.config[key] = value self.config["last_updated"] = str(datetime.now()) return self.save_config() def get_config(self): """Get current configuration""" return self.config def reset_config(self): """Reset to default configuration""" self.config = self.default_config.copy() return self.save_config() # Initialize config manager config_manager = ConfigManager() def update_configuration( app_name, theme, primary_color, font_size, show_header, show_footer, max_items, api_enabled, ai_enabled, temperature, max_tokens ): """Update and save configuration""" success = config_manager.update_config( app_name=app_name, theme=theme, primary_color=primary_color, font_size=font_size, show_header=show_header, show_footer=show_footer, max_items=max_items, api_enabled=api_enabled, ai_enabled=ai_enabled, temperature=temperature, max_tokens=max_tokens ) if success: current_config = config_manager.get_config() return ( f"Configuration updated successfully!\nLast updated: {current_config['last_updated']}", json.dumps(current_config, indent=2) ) else: return "Failed to update configuration", "" def reset_configuration(): """Reset to default configuration""" success = config_manager.reset_config() if success: current_config = config_manager.get_config() return ( f"Configuration reset to defaults!\nLast updated: {current_config['last_updated']}", json.dumps(current_config, indent=2) ) else: return "Failed to reset configuration", "" def load_current_config(): """Load and display current configuration""" current_config = config_manager.get_config() return json.dumps(current_config, indent=2) def get_model_info(): """Get information about the SauerkrautLM model""" model_id = "TheBloke/SauerkrautLM-Mixtral-8x7B-Instruct-GGUF" try: api = HfApi() model_info = api.model_info(model_id) info_text = f""" ## 🤖 SauerkrautLM-Mixtral-8x7B-Instruct-GGUF **Model ID:** {model_id} **Author:** {model_info.author} **Last Modified:** {model_info.lastModified} **Downloads:** {model_info.downloads} ### Model Description: {SauerkrautLM-Mixtral-8x7B-Instruct is a high-quality Mistral-7B model fine-tuned on a large amount of data, with a focus on German and English language, as well as code. It comes with an instruct fine-tune on top of the base model, and supports a context length of 32,768 tokens.} ### Key Features: - ✅ German & English language support - ✅ Code generation capabilities - ✅ 32,768 token context length - ✅ High-quality instruction following - ✅ GGUF format for efficient inference """ return info_text except Exception as e: return f"Could not fetch model info: {str(e)}" def ai_assistant(prompt, chat_history): """AI assistant powered by SauerkrautLM""" config = config_manager.get_config() if not config.get("ai_enabled", True): return "AI is disabled in configuration." try: # In a real implementation, this would call the actual model API # For demo purposes, we'll simulate a response system_message = """You are a helpful AI assistant specialized in configuration management. You help users understand and configure their Gradio applications. Be concise and provide clear, actionable advice.""" # Simulated AI response (replace with actual API call) response = f""" Here's my analysis and recommendation for your configuration: **Your Request:** {prompt} **Recommendation:** Based on the SauerkrautLM-Mixtral-8x7B-Instruct model's capabilities, I suggest: 1. For theme selection: The '{config.get('theme', 'soft')}' theme is a good choice for most applications 2. Consider adjusting your primary color to match your brand identity 3. The current font size ('{config.get('font_size', 'medium')}') should work well for most users **Configuration Tips:** - Enable API access if you need programmatic control - Adjust max_items based on your expected user load - The AI model supports both German and English, so you can configure in either language Would you like me to suggest specific configuration values? """ return response except Exception as e: return f"AI Assistant Error: {str(e)}" # Create custom theme based on configuration def create_theme(): """Create theme based on current configuration""" config = config_manager.get_config() theme_map = { "soft": gr.themes.Soft, "glass": gr.themes.Glass, "monochrome": gr.themes.Monochrome, "base": gr.themes.Base } base_theme = theme_map.get(config["theme"].lower(), gr.themes.Soft) return base_theme( primary_hue=config["primary_color"], text_size="lg" if config["font_size"] == "large" else "md", spacing_size="lg" if config["font_size"] == "large" else "md" ) # Custom CSS for better styling custom_css = """ .gradio-container { max-width: 1200px !important; } .config-section { border: 1px solid #e5e7eb; border-radius: 8px; padding: 16px; margin-bottom: 16px; } .config-title { font-size: 1.2rem; font-weight: 600; margin-bottom: 12px; color: var(--primary-600); } .status-success { color: #10b981; font-weight: 500; } .status-error { color: #ef4444; font-weight: 500; } .json-output { font-family: 'Courier New', monospace; background-color: #f3f4f6; padding: 12px; border-radius: 4px; max-height: 400px; overflow-y: auto; } .ai-section { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; border-radius: 12px; margin: 20px 0; } .model-card { background: white; color: #374151; padding: 16px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); } """ # Create the Gradio interface with gr.Blocks() as demo: # Header with "Built with anycoder" link gr.Markdown(""" # 🚀 AI-Powered Configuration Manager **Built with [anycoder](https://huggingface.co/spaces/akhaliq/anycoder)** """) gr.Markdown("Configure your application settings with AI assistance from SauerkrautLM-Mixtral-8x7B-Instruct-GGUF") with gr.Tabs(): # AI Assistant Tab with gr.Tab("🤖 AI Assistant"): gr.Markdown("## AI Configuration Assistant") gr.Markdown("Get intelligent recommendations for your configuration using SauerkrautLM") with gr.Row(): with gr.Column(scale=2): ai_prompt = gr.Textbox( label="Ask the AI Assistant", placeholder="Ask about configuration best practices, theme selection, or any other questions...", lines=3 ) ai_submit = gr.Button("Get AI Recommendation", variant="primary") ai_response = gr.Markdown("AI response will appear here...") with gr.Column(scale=1): with gr.Accordion("AI Settings", open=True): ai_enabled = gr.Checkbox( label="Enable AI Assistant", value=config_manager.get_config()["ai_enabled"], info="Toggle AI-powered recommendations" ) temperature = gr.Slider( minimum=0.1, maximum=1.0, value=config_manager.get_config()["temperature"], step=0.1, label="AI Temperature", info="Higher values make output more random" ) max_tokens = gr.Slider( minimum=64, maximum=1024, value=config_manager.get_config()["max_tokens"], step=64, label="Max Tokens", info="Maximum response length" ) # Model Information with gr.Column(elem_classes="model-card"): model_info = gr.Markdown(get_model_info()) # Configuration Tab with gr.Tab("⚙️ Configuration"): with gr.Column(elem_classes="config-section"): gr.Markdown("## Application Settings", elem_classes="config-title") with gr.Row(): with gr.Column(): app_name = gr.Textbox( label="Application Name", value=config_manager.get_config()["app_name"], placeholder="Enter application name" ) theme_select = gr.Dropdown( choices=["Soft", "Glass", "Monochrome", "Base"], label="Theme", value=config_manager.get_config()["theme"], info="Select the visual theme" ) primary_color = gr.Dropdown( choices=["blue", "red", "green", "purple", "orange", "pink"], label="Primary Color", value=config_manager.get_config()["primary_color"], info="Main accent color" ) with gr.Column(): font_size = gr.Radio( choices=["small", "medium", "large"], label="Font Size", value=config_manager.get_config()["font_size"], info="Base font size" ) show_header = gr.Checkbox( label="Show Header", value=config_manager.get_config()["show_header"], info="Display header section" ) show_footer = gr.Checkbox( label="Show Footer", value=config_manager.get_config()["show_footer"], info="Display footer section" ) max_items = gr.Slider( minimum=1, maximum=50, value=config_manager.get_config()["max_items"], step=1, label="Max Items", info="Maximum number of items to display" ) api_enabled = gr.Checkbox( label="Enable API", value=config_manager.get_config()["api_enabled"], info="Enable API endpoints" ) with gr.Row(): update_btn = gr.Button("Update Configuration", variant="primary") reset_btn = gr.Button("Reset to Defaults", variant="secondary") status_output = gr.Markdown("Ready to configure", elem_classes="status-success") with gr.Column(elem_classes="config-section"): gr.Markdown("## Current Configuration", elem_classes="config-title") config_json = gr.JSON( value=config_manager.get_config(), label="Configuration JSON", elem_classes="json-output" ) refresh_btn = gr.Button("Refresh Configuration", variant="stop") # Preview Tab with gr.Tab("👁️ Preview"): gr.Markdown("## Configuration Preview") gr.Markdown("This shows how your configuration affects the application appearance.") with gr.Row(): with gr.Column(): gr.Markdown("### Sample Components") sample_text = gr.Textbox(label="Text Input", placeholder="Sample text input") sample_slider = gr.Slider(0, 100, value=50, label="Sample Slider") sample_button = gr.Button("Sample Button", variant="primary") gr.Markdown("### Configuration Info") preview_info = gr.Markdown(f""" **Current Theme:** {config_manager.get_config()['theme']} **Primary Color:** {config_manager.get_config()['primary_color']} **Font Size:** {config_manager.get_config()['font_size']} **Last Updated:** {config_manager.get_config()['last_updated']} """) with gr.Column(): gr.Markdown("### Theme Preview") theme_preview = gr.Markdown(""" This section shows how different components look with your selected theme. The colors, spacing, and typography are all controlled by your configuration. """) with gr.Accordion("Theme Details", open=False): gr.Markdown(f""" - **Theme Type:** {config_manager.get_config()['theme']} - **Primary Hue:** {config_manager.get_config()['primary_color']} - **Text Size:** {config_manager.get_config()['font_size']} - **Spacing:** Medium - **Radius:** Medium """) # Advanced Tab with gr.Tab("🔧 Advanced"): gr.Markdown("## Advanced Configuration") with gr.Column(elem_classes="config-section"): gr.Markdown("### Export/Import Configuration", elem_classes="config-title") with gr.Row(): export_btn = gr.Button("Export Configuration", variant="primary") import_btn = gr.Button("Import Configuration", variant="secondary") export_output = gr.File(label="Download Configuration File") import_input = gr.File(label="Upload Configuration File", file_types=[".json"]) import_status = gr.Markdown("Ready to import", elem_classes="status-success") # Event listeners update_btn.click( fn=update_configuration, inputs=[ app_name, theme_select, primary_color, font_size, show_header, show_footer, max_items, api_enabled, ai_enabled, temperature, max_tokens ], outputs=[status_output, config_json], api_visibility="public" ) reset_btn.click( fn=reset_configuration, inputs=None, outputs=[status_output, config_json], api_visibility="public" ) refresh_btn.click( fn=load_current_config, inputs=None, outputs=config_json, api_visibility="public" ) ai_submit.click( fn=ai_assistant, inputs=[ai_prompt], outputs=ai_response, api_visibility="public" ) def export_config(): config = config_manager.get_config() config_file = "config_export.json" with open(config_file, 'w') as f: json.dump(config, f, indent=2) return config_file export_btn.click( fn=export_config, inputs=None, outputs=export_output, api_visibility="public" ) def import_config_file(file): try: if file is not None: with open(file.name, 'r') as f: new_config = json.load(f) # Validate and update config for key, value in new_config.items(): if key in config_manager.default_config: config_manager.config[key] = value config_manager.save_config() return f"Configuration imported successfully from {file.name}" except Exception as e: return f"Error importing configuration: {str(e)}" import_btn.click( fn=import_config_file, inputs=import_input, outputs=import_status, api_visibility="public" ) # Launch the application with custom theme demo.launch( theme=create_theme(), css=custom_css, footer_links=[ {"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"}, {"label": "SauerkrautLM Model", "url": "https://huggingface.co/TheBloke/SauerkrautLM-Mixtral-8x7B-Instruct-GGUF"}, {"label": "Gradio Docs", "url": "https://www.gradio.app/docs"}, {"label": "GitHub", "url": "https://github.com/gradio-app/gradio"} ], show_error=True, title="AI Configuration Manager" )