help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
python-pattern-generator
RSK World
python-pattern-generator
Python Number Pattern Generator - 22 Pattern Types + Fractals + Mathematical Algorithms + GUI & Web Interface + REST API + Educational Design
python-pattern-generator
  • __pycache__
  • static
  • templates
  • .gitignore1.6 KB
  • README.md9.7 KB
  • animation.py14.3 KB
  • api.py19.9 KB
  • config.py14 KB
  • demo.py9.3 KB
  • index.html10.1 KB
  • main.py30.9 KB
  • pattern_comparison.py15.4 KB
  • patterns.py23 KB
  • push_to_github.bat3.9 KB
  • requirements.txt1 KB
  • svg_export.py13.4 KB
  • test_gui.py2.2 KB
  • test_patterns.py13.7 KB
  • web_app.py13.6 KB
config.py
config.py
Raw Download
Find: Go to:
"""
Configuration Module for Python Number Pattern Generator
Author: Molla Samser (Founder, RSK World)
Designer & Tester: Rima Khatun
Website: https://rskworld.in
Year: 2026
Description: Centralized configuration management
"""

import json
import os
from typing import Dict, Any, Optional


class Config:
    """Configuration manager for the pattern generator"""

    # Default configuration
    DEFAULT_CONFIG = {
        # Application settings
        "app": {
            "name": "Python Number Pattern Generator",
            "version": "2.0",
            "author": "Molla Samser (RSK World)",
            "designer": "Rima Khatun",
            "website": "https://rskworld.in",
            "year": 2026,
            "description": "Comprehensive number pattern generator with GUI and web interface"
        },

        # GUI settings
        "gui": {
            "window": {
                "width": 800,
                "height": 600,
                "min_width": 600,
                "min_height": 400,
                "title": "Python Number Pattern Generator - RSK World"
            },
            "theme": {
                "default": "default",
                "available_themes": ["default", "dark", "light"],
                "auto_save_theme": True
            },
            "fonts": {
                "family": "Arial",
                "size": {
                    "title": 16,
                    "normal": 10,
                    "small": 8
                }
            },
            "colors": {
                "primary": "#3498db",
                "success": "#27ae60",
                "warning": "#f39c12",
                "danger": "#e74c3c",
                "info": "#17a2b8"
            }
        },

        # Web interface settings
        "web": {
            "host": "0.0.0.0",
            "port": 5000,
            "debug": True,
            "secret_key": "rsk-world-pattern-generator-2026",
            "max_content_length": 16 * 1024 * 1024,  # 16MB
            "session_timeout": 3600,  # 1 hour
            "rate_limit": {
                "enabled": False,
                "requests_per_minute": 60
            }
        },

        # Pattern settings
        "patterns": {
            "max_size": {
                "basic": 50,
                "advanced": 20,
                "fractal": 10
            },
            "max_start_number": 1000,
            "min_size": 1,
            "default_size": 5,
            "default_start_number": 1,
            "computation_timeout": 30,  # seconds
            "cache_enabled": True,
            "cache_max_size": 100
        },

        # Export settings
        "export": {
            "formats": {
                "text": {
                    "enabled": True,
                    "extension": ".txt",
                    "encoding": "utf-8"
                },
                "json": {
                    "enabled": True,
                    "extension": ".json",
                    "indent": 2
                },
                "png": {
                    "enabled": True,
                    "extension": ".png",
                    "font_size": 20,
                    "background_color": "#000000",
                    "text_color": "#00FF00",
                    "padding": 20
                },
                "svg": {
                    "enabled": False,  # Not implemented yet
                    "extension": ".svg"
                },
                "pdf": {
                    "enabled": False,  # Not implemented yet
                    "extension": ".pdf"
                }
            },
            "default_format": "text",
            "include_metadata": True,
            "timestamp_format": "%Y-%m-%d %H:%M:%S",
            "auto_open_after_export": False
        },

        # Analysis settings
        "analysis": {
            "enabled": True,
            "calculate_statistics": True,
            "performance_monitoring": True,
            "memory_tracking": False,
            "detailed_analysis": {
                "number_distribution": True,
                "pattern_complexity": True,
                "mathematical_properties": True
            }
        },

        # Logging settings
        "logging": {
            "enabled": True,
            "level": "INFO",  # DEBUG, INFO, WARNING, ERROR
            "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
            "file": {
                "enabled": True,
                "path": "logs/pattern_generator.log",
                "max_size": 10 * 1024 * 1024,  # 10MB
                "backup_count": 5
            },
            "console": {
                "enabled": True,
                "colored": True
            }
        },

        # Performance settings
        "performance": {
            "max_workers": 4,
            "thread_pool_size": 8,
            "cache_ttl": 3600,  # 1 hour
            "optimization": {
                "string_concatenation": True,
                "memory_pool": True,
                "lazy_evaluation": False
            }
        },

        # Security settings
        "security": {
            "input_validation": {
                "strict_mode": True,
                "sanitize_input": True,
                "max_input_size": 10000
            },
            "rate_limiting": {
                "enabled": False,
                "window_seconds": 60,
                "max_requests": 100
            },
            "cors": {
                "enabled": True,
                "origins": ["*"],
                "methods": ["GET", "POST"],
                "headers": ["Content-Type", "Authorization"]
            }
        },

        # Feature flags
        "features": {
            "gui": True,
            "web_interface": True,
            "api": True,
            "export": True,
            "analysis": True,
            "animation": False,  # Not implemented yet
            "comparison": False,  # Not implemented yet
            "plugins": False,     # Not implemented yet
            "themes": True,
            "search": True,
            "statistics": True
        },

        # External integrations
        "integrations": {
            "matplotlib": {
                "enabled": False,
                "backend": "Agg"
            },
            "pillow": {
                "enabled": True,
                "max_image_size": 4096
            },
            "flask": {
                "enabled": True,
                "cors_enabled": True
            }
        },

        # User preferences
        "user": {
            "last_used_pattern": "pyramid",
            "last_size": 5,
            "last_start_number": 1,
            "favorite_patterns": [],
            "recent_patterns": [],
            "auto_save_settings": True,
            "language": "en",
            "timezone": "UTC"
        }
    }

    def __init__(self, config_file: str = "config.json"):
        """Initialize configuration manager

        Args:
            config_file: Path to the configuration file
        """
        self.config_file = config_file
        self._config = self.DEFAULT_CONFIG.copy()
        self.load_config()

    def load_config(self) -> None:
        """Load configuration from file"""
        try:
            if os.path.exists(self.config_file):
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    user_config = json.load(f)
                    self._merge_config(self._config, user_config)
                print(f"✅ Configuration loaded from {self.config_file}")
            else:
                print(f"⚠️  Configuration file not found, using defaults")
                self.save_config()  # Create default config file
        except Exception as e:
            print(f"❌ Error loading configuration: {e}")
            print("Using default configuration")

    def save_config(self) -> None:
        """Save current configuration to file"""
        try:
            # Ensure directory exists
            os.makedirs(os.path.dirname(self.config_file), exist_ok=True)

            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self._config, f, indent=2, ensure_ascii=False)

            print(f"💾 Configuration saved to {self.config_file}")
        except Exception as e:
            print(f"❌ Error saving configuration: {e}")

    def _merge_config(self, base: Dict[str, Any], update: Dict[str, Any]) -> None:
        """Recursively merge configuration dictionaries"""
        for key, value in update.items():
            if key in base and isinstance(base[key], dict) and isinstance(value, dict):
                self._merge_config(base[key], value)
            else:
                base[key] = value

    def get(self, key: str, default: Any = None) -> Any:
        """Get configuration value by key

        Args:
            key: Dot-separated key (e.g., 'gui.window.width')
            default: Default value if key not found

        Returns:
            Configuration value or default
        """
        keys = key.split('.')
        value = self._config

        try:
            for k in keys:
                value = value[k]
            return value
        except (KeyError, TypeError):
            return default

    def set(self, key: str, value: Any) -> None:
        """Set configuration value by key

        Args:
            key: Dot-separated key (e.g., 'gui.window.width')
            value: Value to set
        """
        keys = key.split('.')
        config = self._config

        # Navigate to the parent dictionary
        for k in keys[:-1]:
            if k not in config:
                config[k] = {}
            config = config[k]

        # Set the value
        config[keys[-1]] = value

        # Auto-save if enabled
        if self.get('user.auto_save_settings', True):
            self.save_config()

    def reset_to_defaults(self) -> None:
        """Reset configuration to default values"""
        self._config = self.DEFAULT_CONFIG.copy()
        self.save_config()

    def validate_config(self) -> Dict[str, Any]:
        """Validate current configuration

        Returns:
            Dictionary with validation results
        """
        issues = []

        # Check required settings
        required_keys = [
            'app.name',
            'patterns.max_size.basic',
            'patterns.min_size'
        ]

        for key in required_keys:
            if self.get(key) is None:
                issues.append(f"Missing required key: {key}")

        # Check value ranges
        if not (1 <= self.get('patterns.min_size', 0) <= self.get('patterns.max_size.basic', 100)):
            issues.append("Invalid size range")

        if self.get('patterns.max_start_number', 0) < 0:
            issues.append("Invalid max start number")

        return {
            'valid': len(issues) == 0,
            'issues': issues
        }

    def get_all(self) -> Dict[str, Any]:
        """Get entire configuration dictionary"""
        return self._config.copy()

    def print_config(self, section: Optional[str] = None) -> None:
        """Print configuration (optionally for specific section)"""
        if section:
            config_section = self.get(section, {})
            print(f"\n=== {section.upper()} Configuration ===")
            print(json.dumps(config_section, indent=2))
        else:
            print("\n=== Full Configuration ===")
            print(json.dumps(self._config, indent=2))

    # Convenience methods for common settings
    @property
    def app_name(self) -> str:
        return self.get('app.name', 'Pattern Generator')

    @property
    def app_version(self) -> str:
        return self.get('app.version', '1.0')

    @property
    def max_pattern_size(self) -> int:
        return self.get('patterns.max_size.basic', 50)

    @property
    def min_pattern_size(self) -> int:
        return self.get('patterns.min_size', 1)

    @property
    def max_start_number(self) -> int:
        return self.get('patterns.max_start_number', 1000)

    @property
    def default_theme(self) -> str:
        return self.get('gui.theme.default', 'default')

    @property
    def web_host(self) -> str:
        return self.get('web.host', 'localhost')

    @property
    def web_port(self) -> int:
        return self.get('web.port', 5000)


# Global configuration instance
config = Config()

# Convenience functions
def get_config(key: str, default: Any = None) -> Any:
    """Get configuration value"""
    return config.get(key, default)

def set_config(key: str, value: Any) -> None:
    """Set configuration value"""
    config.set(key, value)

def save_config() -> None:
    """Save configuration to file"""
    config.save_config()

def load_config() -> None:
    """Load configuration from file"""
    config.load_config()

if __name__ == '__main__':
    print("Python Number Pattern Generator - Configuration Manager")
    print("=" * 60)
    print("Developed by Molla Samser (RSK World)")
    print("Designed by Rima Khatun")
    print("Website: https://rskworld.in")
    print("Year: 2026")
    print("=" * 60)

    # Example usage
    print(f"App Name: {config.app_name}")
    print(f"Version: {config.app_version}")
    print(f"Max Pattern Size: {config.max_pattern_size}")
    print(f"Default Theme: {config.default_theme}")

    # Modify some settings
    config.set('user.last_used_pattern', 'sierpinski')
    config.set('user.last_size', 8)

    # Validate configuration
    validation = config.validate_config()
    if validation['valid']:
        print("✅ Configuration is valid")
    else:
        print("❌ Configuration issues:")
        for issue in validation['issues']:
            print(f"  - {issue}")

    # Save configuration
    config.save_config()
    print("\nConfiguration saved to config.json")
457 lines•14 KB
python

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer