Spaces:
Runtime error
Runtime error
| import gradio as gr | |
| import json | |
| import logging | |
| from enum import Enum, auto | |
| from typing import Protocol, List, Dict, Any, Optional | |
| from dataclasses import dataclass, field | |
| from datetime import datetime | |
| import difflib | |
| import pytest | |
| from concurrent.futures import ThreadPoolExecutor | |
| import asyncio | |
| # Initialize logger | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| class CustomJSONEncoder(json.JSONEncoder): | |
| def default(self, obj): | |
| if isinstance(obj, datetime): | |
| return obj.isoformat() | |
| return super().default(obj) | |
| class Config: | |
| """Configuration class for the agent system""" | |
| rag_system_path: str | |
| max_workers: int = 10 | |
| log_level: str = "INFO" | |
| model_settings: Dict[str, Any] = field(default_factory=dict) | |
| api_keys: Dict[str, str] = field(default_factory=dict) | |
| design_system_config: Dict[str, Any] = field(default_factory=dict) | |
| def __post_init__(self): | |
| """Validate configuration after initialization""" | |
| if not self.rag_system_path: | |
| raise ValueError("RAG system path must be specified in config") | |
| if not self.design_system_config: | |
| self.design_system_config = { | |
| 'theme': 'light', | |
| 'responsive': True, | |
| 'accessibility_level': 'AAA' | |
| } | |
| class DesignSystem: | |
| def __init__(self): | |
| self.theme = { | |
| 'colors': { | |
| 'primary': '#007bff', | |
| 'secondary': '#6c757d', | |
| 'success': '#28a745', | |
| 'danger': '#dc3545', | |
| 'warning': '#ffc107', | |
| 'info': '#17a2b8', | |
| 'light': '#f8f9fa', | |
| 'dark': '#343a40' | |
| }, | |
| 'typography': { | |
| 'fontFamily': { | |
| 'primary': '"Helvetica Neue", Arial, sans-serif', | |
| 'secondary': 'Georgia, serif', | |
| 'monospace': 'Monaco, Consolas, monospace' | |
| }, | |
| 'fontSizes': { | |
| 'xs': '12px', | |
| 'sm': '14px', | |
| 'base': '16px', | |
| 'lg': '18px', | |
| 'xl': '20px', | |
| 'xxl': '24px', | |
| 'display': '32px' | |
| }, | |
| 'lineHeight': { | |
| 'tight': '1.25', | |
| 'normal': '1.5', | |
| 'relaxed': '1.75' | |
| } | |
| }, | |
| 'spacing': { | |
| 'unit': '8px', | |
| 'scales': { | |
| 'xs': '0.25rem', | |
| 'sm': '0.5rem', | |
| 'md': '1rem', | |
| 'lg': '1.5rem', | |
| 'xl': '2rem' | |
| } | |
| }, | |
| 'breakpoints': { | |
| 'mobile': '320px', | |
| 'tablet': '768px', | |
| 'desktop': '1024px', | |
| 'large': '1440px' | |
| } | |
| } | |
| def get_color(self, color_name: str) -> str: | |
| return self.theme['colors'].get(color_name) | |
| def get_font_family(self, type_name: str) -> str: | |
| return self.theme['typography']['fontFamily'].get(type_name) | |
| def get_spacing(self, scale: str) -> str: | |
| return self.theme['spacing']['scales'].get(scale) | |
| class UIComponentLibrary: | |
| def __init__(self, design_system: DesignSystem): | |
| self.design_system = design_system | |
| def get_component_template(self, component_type: str) -> Dict[str, Any]: | |
| components = { | |
| 'button': { | |
| 'template': ''' | |
| <button class="btn {{variant}}" {{attributes}}> | |
| {{text}} | |
| </button> | |
| ''', | |
| 'styles': self._get_button_styles() | |
| }, | |
| 'card': { | |
| 'template': ''' | |
| <div class="card {{variant}}"> | |
| <div class="card-header">{{header}}</div> | |
| <div class="card-body">{{content}}</div> | |
| <div class="card-footer">{{footer}}</div> | |
| </div> | |
| ''', | |
| 'styles': self._get_card_styles() | |
| }, | |
| 'input': { | |
| 'template': ''' | |
| <div class="form-group"> | |
| <label for="{{id}}">{{label}}</label> | |
| <input type="{{type}}" id="{{id}}" | |
| class="form-control {{variant}}" {{attributes}}> | |
| <small class="form-text">{{helper_text}}</small> | |
| </div> | |
| ''', | |
| 'styles': self._get_input_styles() | |
| } | |
| } | |
| return components.get(component_type) | |
| def _get_button_styles(self) -> Dict[str, str]: | |
| return { | |
| 'base': f''' | |
| font-family: {self.design_system.get_font_family('primary')}; | |
| padding: {self.design_system.get_spacing('sm')} {self.design_system.get_spacing('md')}; | |
| border-radius: 4px; | |
| border: none; | |
| cursor: pointer; | |
| transition: all 0.3s ease; | |
| ''', | |
| 'primary': f'background-color: {self.design_system.get_color("primary")};', | |
| 'secondary': f'background-color: {self.design_system.get_color("secondary")};' | |
| } | |
| def _get_card_styles(self) -> Dict[str, str]: | |
| return { | |
| 'base': f''' | |
| border-radius: 8px; | |
| padding: {self.design_system.get_spacing('md')}; | |
| box-shadow: 0 2px 4px rgba(0,0,0,0.1); | |
| ''' | |
| } | |
| def _get_input_styles(self) -> Dict[str, str]: | |
| return { | |
| 'base': f''' | |
| font-family: {self.design_system.get_font_family('primary')}; | |
| padding: {self.design_system.get_spacing('sm')}; | |
| border-radius: 4px; | |
| border: 1px solid {self.design_system.get_color('secondary')}; | |
| ''' | |
| } | |
| class WebDesignValidator: | |
| def __init__(self): | |
| self.accessibility_rules = { | |
| 'aria_labels': True, | |
| 'alt_texts': True, | |
| 'semantic_html': True, | |
| 'keyboard_navigation': True, | |
| 'color_contrast': True, | |
| 'focus_indicators': True | |
| } | |
| self.responsive_breakpoints = { | |
| 'mobile': '320px', | |
| 'tablet': '768px', | |
| 'desktop': '1024px', | |
| 'large': '1440px' | |
| } | |
| async def validate_design_principles(self, implementation: Dict[str, Any]) -> Dict[str, Any]: | |
| results = { | |
| 'accessibility': await self._check_accessibility(implementation), | |
| 'responsive_design': await self._check_responsive_design(implementation), | |
| 'color_contrast': await self._check_color_contrast(implementation), | |
| 'typography': await self._check_typography(implementation), | |
| 'performance': await self._check_performance(implementation) | |
| } | |
| return { | |
| 'validation_results': results, | |
| 'overall_status': self._calculate_overall_status(results), | |
| 'recommendations': self._generate_recommendations(results) | |
| } | |
| async def _check_accessibility(self, implementation: Dict[str, Any]) -> Dict[str, Any]: | |
| results = { | |
| 'passed': [], | |
| 'failed': [], | |
| 'warnings': [] | |
| } | |
| for component in implementation.get('components', []): | |
| for rule, enabled in self.accessibility_rules.items(): | |
| if enabled: | |
| result = await self._validate_accessibility_rule(component, rule) | |
| if result['status'] == 'passed': | |
| results['passed'].append(f"{component['name']}: {rule}") | |
| elif result['status'] == 'failed': | |
| results['failed'].append({ | |
| 'component': component['name'], | |
| 'rule': rule, | |
| 'message': result['message'] | |
| }) | |
| else: | |
| results['warnings'].append({ | |
| 'component': component['name'], | |
| 'rule': rule, | |
| 'message': result['message'] | |
| }) | |
| return results | |
| async def _validate_accessibility_rule(self, component: Dict[str, Any], rule: str) -> Dict[str, Any]: | |
| validators = { | |
| 'aria_labels': self._check_aria_labels, | |
| 'alt_texts': self._check_alt_texts, | |
| 'semantic_html': self._check_semantic_html, | |
| 'keyboard_navigation': self._check_keyboard_navigation, | |
| 'color_contrast': self._check_specific_color_contrast, | |
| 'focus_indicators': self._check_focus_indicators | |
| } | |
| validator = validators.get(rule) | |
| if validator: | |
| return await validator(component) | |
| return {'status': 'warning', 'message': f'No validator found for {rule}'} | |
| async def _check_responsive_design(self, implementation: Dict[str, Any]) -> Dict[str, Any]: | |
| results = { | |
| 'breakpoints_tested': [], | |
| 'layout_issues': [], | |
| 'recommendations': [] | |
| } | |
| for breakpoint, size in self.responsive_breakpoints.items(): | |
| test_result = await self._test_breakpoint(implementation, breakpoint, size) | |
| results['breakpoints_tested'].append({ | |
| 'breakpoint': breakpoint, | |
| 'size': size, | |
| 'result': test_result | |
| }) | |
| if test_result.get('issues'): | |
| results['layout_issues'].extend(test_result['issues']) | |
| results['recommendations'].extend(test_result['recommendations']) | |
| return results | |
| async def _test_breakpoint(self, implementation: Dict[str, Any], breakpoint: str, size: str) -> Dict[str, Any]: | |
| # Simulate testing at different viewport sizes | |
| return { | |
| 'breakpoint': breakpoint, | |
| 'size': size, | |
| 'layout_integrity': True, | |
| 'issues': [], | |
| 'recommendations': [] | |
| } | |
| async def _check_color_contrast(self, implementation: Dict[str, Any]) -> Dict[str, Any]: | |
| results = { | |
| 'passed': [], | |
| 'failed': [], | |
| 'warnings': [] | |
| } | |
| for component in implementation.get('components', []): | |
| contrast_ratio = await self._calculate_contrast_ratio( | |
| component.get('foreground_color'), | |
| component.get('background_color') | |
| ) | |
| if contrast_ratio >= 4.5: # WCAG AA standard | |
| results['passed'].append({ | |
| 'component': component['name'], | |
| 'ratio': contrast_ratio | |
| }) | |
| else: | |
| results['failed'].append({ | |
| 'component': component['name'], | |
| 'ratio': contrast_ratio, | |
| 'recommendation': 'Increase contrast to at least 4.5:1' | |
| }) | |
| return results | |
| async def _check_typography(self, implementation: Dict[str, Any]) -> Dict[str, Any]: | |
| return { | |
| 'font_hierarchy': await self._check_font_hierarchy(implementation), | |
| 'line_height': await self._check_line_height(implementation), | |
| 'font_sizes': await self._check_font_sizes(implementation), | |
| 'recommendations': [] | |
| } | |
| async def _check_performance(self, implementation: Dict[str, Any]) -> Dict[str, Any]: | |
| return { | |
| 'image_optimization': await self._check_image_optimization(implementation), | |
| 'css_optimization': await self._check_css_optimization(implementation), | |
| 'loading_time': await self._check_loading_time(implementation), | |
| 'recommendations': [] | |
| } | |
| def _calculate_overall_status(self, results: Dict[str, Any]) -> str: | |
| # Implementation of overall status calculation | |
| failed_count = sum(len(category.get('failed', [])) for category in results.values()) | |
| if failed_count > 0: | |
| return 'fail' | |
| return 'pass' | |
| def _generate_recommendations(self, results: Dict[str, Any]) -> List[str]: | |
| recommendations = [] | |
| for category, result in results.items(): | |
| if 'recommendations' in result: | |
| recommendations.extend(result['recommendations']) | |
| return recommendations | |
| if __name__ == "__app__": | |
| logger.info("===== Application Startup at %s =====", datetime.now().isoformat()) | |
| try: | |
| # Example data to test JSON serialization | |
| test_results = { | |
| "timestamp": datetime.now(), | |
| "status": "success" | |
| } | |
| print("Test Results:", json.dumps(test_results, indent=2, cls=CustomJSONEncoder)) | |
| except Exception as e: | |
| logger.error(f"Error serializing test results: {e}") | |
| logger.info("Application initialized successfully.") |