Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

refactor(core): enhance documentation and code quality for all core module files

KaifAhmad187765b852b63
diff --git a/semantica/core/__init__.py b/semantica/core/__init__.py
index cfbebfae..ba2e3c0c 100644
--- a/semantica/core/__init__.py
+++ b/semantica/core/__init__.py
@@ -1,14 +1,27 @@
"""
Core Orchestration Module
-This module provides the main orchestration capabilities for the Semantica framework.
+This module provides the main orchestration capabilities for the Semantica framework,
+including the primary Semantica class, configuration management, lifecycle management,
+and plugin system.
-Exports:
- - Semantica: Main framework class for orchestration
- - Config: Configuration data class
- - ConfigManager: Configuration management system
- - LifecycleManager: Lifecycle management
- - PluginRegistry: Plugin management system
+Main Components:
+ - Semantica: Main framework class for orchestration and knowledge base building
+ - Config: Configuration data class with validation
+ - ConfigManager: Configuration loading, validation, and management
+ - LifecycleManager: System lifecycle management with hooks and health monitoring
+ - PluginRegistry: Dynamic plugin discovery, loading, and management
+
+Example Usage:
+ >>> from semantica.core import Semantica, ConfigManager
+ >>> # Initialize framework
+ >>> framework = Semantica()
+ >>> # Load configuration
+ >>> config_manager = ConfigManager()
+ >>> config = config_manager.load_from_file("config.yaml")
+
+Author: Semantica Contributors
+License: MIT
"""
from .orchestrator import Semantica
diff --git a/semantica/core/config_manager.py b/semantica/core/config_manager.py
index f13e532c..a772d76f 100644
--- a/semantica/core/config_manager.py
+++ b/semantica/core/config_manager.py
@@ -1,18 +1,25 @@
"""
Configuration Management Module
-Handles all configuration loading, validation, and management for the framework.
+This module provides comprehensive configuration management for the Semantica framework,
+including loading from files, environment variables, validation, and dynamic updates.
Key Features:
- - YAML/JSON configuration parsing
- - Environment variable support
- - Configuration validation
- - Dynamic configuration updates
- - Configuration inheritance
+ - YAML/JSON configuration file parsing
+ - Environment variable support with SEMANTICA_ prefix
+ - Configuration validation with detailed error messages
+ - Dynamic configuration updates at runtime
+ - Configuration inheritance and merging
+ - Nested configuration access via dot notation
-Main Classes:
- - Config: Configuration data class
- - ConfigManager: Configuration management system
+Example Usage:
+ >>> from semantica.core import ConfigManager
+ >>> manager = ConfigManager()
+ >>> config = manager.load_from_file("config.yaml")
+ >>> batch_size = config.get("processing.batch_size", default=32)
+
+Author: Semantica Contributors
+License: MIT
"""
import os
@@ -89,70 +96,141 @@ class Config:
"""
Load configuration values from environment variables.
- Environment variables with prefix SEMANTICA_ will override
- configuration values. Format: SEMANTICA_SECTION_KEY=value
+ Environment variables with prefix SEMANTICA_ will override configuration
+ values. The format is: SEMANTICA_SECTION_KEY=value
+
+ Examples:
+ SEMANTICA_PROCESSING_BATCH_SIZE=64
+ SEMANTICA_LLM_PROVIDER_MODEL=gpt-4
+ SEMANTICA_QUALITY_MIN_CONFIDENCE=0.8
Args:
- config_dict: Configuration dictionary to update
+ config_dict: Configuration dictionary to update with env values
"""
prefix = "SEMANTICA_"
+ prefix_length = len(prefix)
+
+ for env_key, env_value in os.environ.items():
+ if not env_key.startswith(prefix):
+ continue
+
+ # Remove prefix and convert to lowercase for consistency
+ config_key = env_key[prefix_length:].lower()
+
+ # Parse the environment variable value
+ # Try JSON first (for complex types like lists/dicts)
+ try:
+ parsed_value = json.loads(env_value)
+ except (json.JSONDecodeError, ValueError):
+ # Not valid JSON, try type conversion
+ parsed_value = self._parse_env_value(env_value)
+
+ # Set nested value using dot notation
+ # e.g., "processing_batch_size" -> "processing.batch_size"
+ normalized_key = config_key.replace("_", ".")
+ set_nested_value(config_dict, normalized_key, parsed_value)
+
+ def _parse_env_value(self, value: str) -> Union[str, int, float, bool]:
+ """
+ Parse environment variable value to appropriate Python type.
+
+ Args:
+ value: Raw environment variable value string
+
+ Returns:
+ Parsed value with appropriate type (bool, int, float, or str)
+ """
+ # Boolean values
+ if value.lower() in ("true", "false"):
+ return value.lower() == "true"
+
+ # Integer values
+ if value.isdigit() or (value.startswith("-") and value[1:].isdigit()):
+ return int(value)
- for key, value in os.environ.items():
- if key.startswith(prefix):
- # Remove prefix and convert to lowercase
- config_key = key[len(prefix):].lower()
-
- # Try to parse as JSON, otherwise use as string
- try:
- parsed_value = json.loads(value)
- except (json.JSONDecodeError, ValueError):
- # Convert boolean strings
- if value.lower() in ("true", "false"):
- parsed_value = value.lower() == "true"
- # Convert numeric strings
- elif value.isdigit():
- parsed_value = int(value)
- elif value.replace(".", "", 1).isdigit():
- parsed_value = float(value)
- else:
- parsed_value = value
-
- # Set nested value
- set_nested_value(config_dict, config_key, parsed_value)
+ # Float values
+ try:
+ # Check if it's a valid float (allows one decimal point)
+ if value.replace(".", "", 1).replace("-", "", 1).isdigit():
+ return float(value)
+ except ValueError:
+ pass
+
+ # Default: return as string
+ return value
def validate(self) -> None:
"""
Validate configuration settings.
+ This method performs comprehensive validation of all configuration
+ settings, checking types, ranges, and required fields.
+
Raises:
- ConfigurationError: If configuration is invalid
+ ConfigurationError: If configuration is invalid with detailed error messages
"""
- errors = []
+ validation_errors = []
# Validate processing settings
- if "processing" in self.to_dict():
- processing = self.processing
- if "batch_size" in processing:
- batch_size = processing["batch_size"]
- if not isinstance(batch_size, int) or batch_size <= 0:
- errors.append("processing.batch_size must be a positive integer")
+ processing_config = self.processing
+ if processing_config:
+ # Validate batch_size
+ if "batch_size" in processing_config:
+ batch_size = processing_config["batch_size"]
+ if not isinstance(batch_size, int):
+ validation_errors.append(
+ f"processing.batch_size must be an integer, got {type(batch_size).__name__}"
+ )
+ elif batch_size <= 0:
+ validation_errors.append(
+ f"processing.batch_size must be positive, got {batch_size}"
+ )
- if "max_workers" in processing:
- max_workers = processing["max_workers"]
- if not isinstance(max_workers, int) or max_workers <= 0:
- errors.append("processing.max_workers must be a positive integer")
+ # Validate max_workers
+ if "max_workers" in processing_config:
+ max_workers = processing_config["max_workers"]
+ if not isinstance(max_workers, int):
+ validation_errors.append(
+ f"processing.max_workers must be an integer, got {type(max_workers).__name__}"
+ )
+ elif max_workers <= 0:
+ validation_errors.append(
+ f"processing.max_workers must be positive, got {max_workers}"
+ )
# Validate quality settings
- if "quality" in self.to_dict():
- quality = self.quality
- if "min_confidence" in quality:
- confidence = quality["min_confidence"]
- if not isinstance(confidence, (int, float)) or not (0.0 <= confidence <= 1.0):
- errors.append("quality.min_confidence must be between 0.0 and 1.0")
-
- if errors:
+ quality_config = self.quality
+ if quality_config:
+ # Validate min_confidence
+ if "min_confidence" in quality_config:
+ confidence = quality_config["min_confidence"]
+ if not isinstance(confidence, (int, float)):
+ validation_errors.append(
+ f"quality.min_confidence must be a number, got {type(confidence).__name__}"
+ )
+ elif not (0.0 <= confidence <= 1.0):
+ validation_errors.append(
+ f"quality.min_confidence must be between 0.0 and 1.0, got {confidence}"
+ )
+
+ # Validate logging settings
+ logging_config = self.logging
+ if logging_config:
+ valid_levels = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
+ if "level" in logging_config:
+ level = logging_config["level"]
+ if level not in valid_levels:
+ validation_errors.append(
+ f"logging.level must be one of {valid_levels}, got {level}"
+ )
+
+ # Raise error if any validation failures
+ if validation_errors:
+ error_message = "Configuration validation failed:\n" + "\n".join(
+ f" - {error}" for error in validation_errors
+ )
raise ConfigurationError(
- f"Configuration validation failed: {', '.join(errors)}",
+ error_message,
config_context=self.to_dict(),
)
@@ -229,12 +307,32 @@ class ConfigManager:
"""
Configuration management system.
- Handles loading, validation, and updating of configuration.
+ This class provides a centralized way to load, validate, merge, and manage
+ configuration for the Semantica framework. It supports multiple configuration
+ sources and formats.
+
+ Features:
+ - Load from YAML/JSON files
+ - Load from dictionaries
+ - Merge multiple configurations
+ - Validate configuration
+ - Reload configuration dynamically
+
+ Example Usage:
+ >>> manager = ConfigManager()
+ >>> config = manager.load_from_file("config.yaml")
+ >>> merged = manager.merge_configs(config1, config2, config3)
"""
def __init__(self):
- """Initialize configuration manager."""
+ """
+ Initialize configuration manager.
+
+ Creates a new ConfigManager instance with no loaded configuration.
+ Use load_from_file() or load_from_dict() to load configuration.
+ """
self._config: Optional[Config] = None
+ self._last_file_path: Optional[Path] = None
def load_from_file(
self,
@@ -281,14 +379,17 @@ class ConfigManager:
"Supported formats: .yaml, .yml, .json"
)
- # Create config object
+ # Create config object from loaded dictionary
config = Config(config_dict=config_dict)
- # Validate if requested
+ # Validate configuration if requested
if validate:
config.validate()
+ # Store config and file path for potential reload
self._config = config
+ self._last_file_path = file_path
+
return config
except Exception as e:
diff --git a/semantica/core/lifecycle.py b/semantica/core/lifecycle.py
index e768cab7..48db4682 100644
--- a/semantica/core/lifecycle.py
+++ b/semantica/core/lifecycle.py
@@ -1,17 +1,25 @@
"""
Lifecycle Management Module
-Manages system lifecycle including startup, shutdown, and health monitoring.
+This module provides comprehensive lifecycle management for the Semantica framework,
+including startup/shutdown sequences, health monitoring, and resource management.
Key Features:
- - Startup/shutdown hooks
- - Health monitoring
- - Graceful degradation
- - Resource cleanup
- - State management
+ - Startup and shutdown hook system with priority ordering
+ - Component health monitoring and status tracking
+ - Graceful degradation and error handling
+ - Resource cleanup and state management
+ - System state tracking (uninitialized, ready, running, stopped, etc.)
-Main Classes:
- - LifecycleManager: Lifecycle coordination
+Example Usage:
+ >>> from semantica.core import LifecycleManager
+ >>> manager = LifecycleManager()
+ >>> manager.register_startup_hook(my_hook, priority=10)
+ >>> manager.startup()
+ >>> health = manager.get_health_summary()
+
+Author: Semantica Contributors
+License: MIT
"""
import time
@@ -51,74 +59,122 @@ class LifecycleManager:
"""
System lifecycle manager.
- Coordinates startup, shutdown, and health monitoring of all
- framework components.
+ This class coordinates the startup, shutdown, and health monitoring of all
+ framework components. It provides a hook-based system for executing code
+ at specific lifecycle stages with priority ordering.
- Attributes:
- state: Current system state
- health_status: Dictionary of component health statuses
- startup_hooks: List of startup hooks
- shutdown_hooks: List of shutdown hooks
+ Features:
+ - Priority-based startup/shutdown hooks
+ - Component registration and health monitoring
+ - State management and tracking
+ - Graceful error handling during lifecycle transitions
+
+ Example Usage:
+ >>> manager = LifecycleManager()
+ >>> manager.register_component("database", db_connection)
+ >>> manager.register_startup_hook(init_db, priority=10)
+ >>> manager.startup()
+ >>> # System is now ready
+ >>> manager.shutdown(graceful=True)
"""
def __init__(self):
- """Initialize lifecycle manager."""
- self.state: SystemState = SystemState.UNINITIALIZED
- self.health_status: Dict[str, HealthStatus] = {}
- self.startup_hooks: List[Tuple[Callable, int]] = [] # (hook, priority)
- self.shutdown_hooks: List[Tuple[Callable, int]] = [] # (hook, priority)
+ """
+ Initialize lifecycle manager.
+
+ Creates a new lifecycle manager in UNINITIALIZED state with empty
+ registries for components, hooks, and health status.
+ """
self.logger = get_logger("lifecycle")
+
+ # System state tracking
+ self.state: SystemState = SystemState.UNINITIALIZED
+
+ # Component registry for health monitoring
self._component_registry: Dict[str, Any] = {}
+
+ # Health status tracking
+ self.health_status: Dict[str, HealthStatus] = {}
self._last_health_check: Optional[float] = None
+
+ # Hook registries: list of (hook_function, priority) tuples
+ # Lower priority = earlier execution
+ self.startup_hooks: List[Tuple[Callable[[], None], int]] = []
+ self.shutdown_hooks: List[Tuple[Callable[[], None], int]] = []
+
+ self.logger.debug("Lifecycle manager initialized")
def startup(self) -> None:
"""
Execute startup sequence.
- This method initializes all components in the correct order
- and verifies system readiness.
+ This method runs all registered startup hooks in priority order,
+ verifies component initialization, and performs initial health checks.
+ The system transitions from UNINITIALIZED -> INITIALIZING -> READY.
Raises:
- SemanticaError: If startup fails
+ SemanticaError: If startup fails (hook failure, component verification failure)
+
+ Example:
+ >>> manager = LifecycleManager()
+ >>> manager.register_startup_hook(init_config, priority=10)
+ >>> manager.register_startup_hook(init_database, priority=20)
+ >>> manager.startup() # Hooks execute in order: init_config, then init_database
"""
- if self.state == SystemState.READY or self.state == SystemState.RUNNING:
- self.logger.warning("System already started")
+ # Check if already started
+ if self.state in (SystemState.READY, SystemState.RUNNING):
+ self.logger.warning(
+ f"System already in {self.state.value} state, skipping startup"
+ )
return
try:
+ # Transition to initializing state
self.state = SystemState.INITIALIZING
self.logger.info("Starting system lifecycle")
- # Sort hooks by priority (lower = earlier)
+ # Sort hooks by priority (lower priority = earlier execution)
sorted_hooks = sorted(self.startup_hooks, key=lambda x: x[1])
- # Execute startup hooks
+ if sorted_hooks:
+ self.logger.debug(f"Executing {len(sorted_hooks)} startup hook(s)")
+
+ # Execute all startup hooks in priority order
for hook_fn, priority in sorted_hooks:
try:
- self.logger.debug(f"Executing startup hook (priority: {priority})")
+ self.logger.debug(
+ f"Executing startup hook with priority {priority}"
+ )
hook_fn()
except Exception as e:
- self.logger.error(f"Startup hook failed: {e}")
+ error_msg = f"Startup hook (priority {priority}) failed: {e}"
+ self.logger.error(error_msg)
self.state = SystemState.ERROR
- raise SemanticaError(f"Startup hook failed: {e}")
+ raise SemanticaError(error_msg) from e
- # Verify all components are initialized
+ # Verify all registered components are properly initialized
self._verify_components()
- # Run initial health checks
+ # Run initial health checks on all components
health_results = self.health_check()
- unhealthy = [
+ unhealthy_components = [
name for name, status in health_results.items()
if not status.healthy
]
- if unhealthy:
- self.logger.warning(f"Some components are unhealthy: {unhealthy}")
+ if unhealthy_components:
+ self.logger.warning(
+ f"Some components are unhealthy after startup: {unhealthy_components}"
+ )
+ else:
+ self.logger.debug("All components are healthy")
+ # Transition to ready state
self.state = SystemState.READY
self.logger.info("System startup completed successfully")
except Exception as e:
+ # Transition to error state on failure
self.state = SystemState.ERROR
self.logger.error(f"System startup failed: {e}")
raise
@@ -127,78 +183,125 @@ class LifecycleManager:
"""
Execute shutdown sequence.
+ This method runs all registered shutdown hooks in priority order and
+ cleans up resources. In graceful mode, hook failures are logged but
+ don't stop the shutdown process.
+
Args:
graceful: Whether to shutdown gracefully (default: True)
+ - True: Continue shutdown even if hooks fail (log warnings)
+ - False: Stop shutdown on first hook failure (raise error)
+
+ Raises:
+ SemanticaError: If shutdown fails and graceful=False
+
+ Example:
+ >>> manager.shutdown(graceful=True) # Continue even if cleanup fails
+ >>> manager.shutdown(graceful=False) # Stop on first error
"""
+ # Check if already stopped
if self.state == SystemState.STOPPED:
- self.logger.warning("System already stopped")
+ self.logger.warning("System already in STOPPED state")
return
try:
+ # Transition to stopping state
self.state = SystemState.STOPPING
- self.logger.info(f"Shutting down system (graceful: {graceful})")
+ self.logger.info(f"Shutting down system (graceful={graceful})")
- # Sort hooks by priority (lower = earlier)
+ # Sort hooks by priority (lower priority = earlier execution)
sorted_hooks = sorted(self.shutdown_hooks, key=lambda x: x[1])
- # Execute shutdown hooks
+ if sorted_hooks:
+ self.logger.debug(f"Executing {len(sorted_hooks)} shutdown hook(s)")
+
+ # Execute all shutdown hooks in priority order
for hook_fn, priority in sorted_hooks:
try:
- self.logger.debug(f"Executing shutdown hook (priority: {priority})")
+ self.logger.debug(
+ f"Executing shutdown hook with priority {priority}"
+ )
hook_fn()
except Exception as e:
+ error_msg = f"Shutdown hook (priority {priority}) failed: {e}"
+
if graceful:
- self.logger.warning(f"Shutdown hook failed: {e}")
+ # In graceful mode, log warning but continue
+ self.logger.warning(error_msg)
else:
- self.logger.error(f"Shutdown hook failed: {e}")
- raise SemanticaError(f"Shutdown hook failed: {e}")
+ # In non-graceful mode, stop on first error
+ self.logger.error(error_msg)
+ raise SemanticaError(error_msg) from e
- # Cleanup resources
+ # Cleanup all registered components
self._cleanup_resources()
+ # Transition to stopped state
self.state = SystemState.STOPPED
- self.logger.info("System shutdown completed")
+ self.logger.info("System shutdown completed successfully")
except Exception as e:
+ # Transition to error state on failure
self.state = SystemState.ERROR
self.logger.error(f"System shutdown failed: {e}")
+
+ # Re-raise if not graceful shutdown
if not graceful:
raise
def health_check(self) -> Dict[str, HealthStatus]:
"""
- Perform system health check.
+ Perform comprehensive system health check.
- Checks health of all registered components and returns
- status information.
+ This method checks the health of all registered components by calling
+ their health_check() method if available, or using default health logic.
+ Results are cached in health_status and returned.
Returns:
- Dictionary mapping component names to HealthStatus objects
+ Dictionary mapping component names to HealthStatus objects,
+ containing health status, messages, and details for each component
+
+ Example:
+ >>> health = manager.health_check()
+ >>> for name, status in health.items():
+ ... print(f"{name}: {'✓' if status.healthy else '✗'}")
"""
+ # Record health check timestamp
self._last_health_check = time.time()
- # Check registered components
health_results = {}
+ # Check health of each registered component
for component_name, component in self._component_registry.items():
try:
- # Try to get health from component
+ # Try to get health status from component
if hasattr(component, "health_check"):
+ # Component has its own health check method
component_health = component.health_check()
+
+ # Handle different return types
if isinstance(component_health, dict):
+ # Dictionary format: {"healthy": bool, "message": str, "details": dict}
healthy = component_health.get("healthy", True)
message = component_health.get("message", "")
details = component_health.get("details", {})
+ elif isinstance(component_health, bool):
+ # Simple boolean
+ healthy = component_health
+ message = ""
+ details = {}
else:
+ # Other types: convert to boolean
healthy = bool(component_health)
message = ""
details = {}
else:
- # Default: assume healthy if component exists
+ # No health_check method: assume healthy if component exists
healthy = component is not None
- message = ""
+ message = "Component exists" if healthy else "Component is None"
details = {}
+ # Create health status object
status = HealthStatus(
component=component_name,
healthy=healthy,
@@ -207,26 +310,35 @@ class LifecycleManager:
)
except Exception as e:
+ # Health check failed: mark as unhealthy
+ error_msg = f"Health check failed: {e}"
+ self.logger.warning(f"Component {component_name} health check error: {e}")
+
status = HealthStatus(
component=component_name,
healthy=False,
- message=f"Health check failed: {e}",
- details={"error": str(e)}
+ message=error_msg,
+ details={"error": str(e), "error_type": type(e).__name__}
)
+ # Store results
health_results[component_name] = status
self.health_status[component_name] = status
- # Log unhealthy components
- unhealthy = [
+ # Log summary of unhealthy components
+ unhealthy_components = [
name for name, status in health_results.items()
if not status.healthy
]
- if unhealthy:
+ if unhealthy_components:
self.logger.warning(
- f"Unhealthy components detected: {unhealthy}",
- extra={"health_status": health_results}
+ f"Health check found {len(unhealthy_components)} unhealthy component(s): "
+ f"{unhealthy_components}"
+ )
+ else:
+ self.logger.debug(
+ f"Health check passed for all {len(health_results)} component(s)"
)
return health_results
@@ -369,17 +481,38 @@ class LifecycleManager:
)
def _cleanup_resources(self) -> None:
- """Cleanup system resources."""
- # Cleanup components if they have cleanup methods
- for name, component in self._component_registry.items():
+ """
+ Cleanup all system resources.
+
+ This method attempts to cleanup all registered components by calling
+ their cleanup() or close() methods if available. Errors during cleanup
+ are logged but don't stop the cleanup process.
+ """
+ cleanup_count = 0
+
+ # Cleanup each registered component
+ for component_name, component in self._component_registry.items():
try:
+ # Try cleanup() method first, then close()
if hasattr(component, "cleanup"):
component.cleanup()
+ cleanup_count += 1
+ self.logger.debug(f"Cleaned up component: {component_name}")
elif hasattr(component, "close"):
component.close()
+ cleanup_count += 1
+ self.logger.debug(f"Closed component: {component_name}")
except Exception as e:
- self.logger.warning(f"Failed to cleanup component {name}: {e}")
+ # Log but continue cleanup for other components
+ self.logger.warning(
+ f"Failed to cleanup component {component_name}: {e}"
+ )
- # Clear registries
+ if cleanup_count > 0:
+ self.logger.debug(f"Cleaned up {cleanup_count} component(s)")
+
+ # Clear all registries
self._component_registry.clear()
- self.health_status.clear()
\ No newline at end of file
+ self.health_status.clear()
+
+ self.logger.debug("Resource cleanup completed")
\ No newline at end of file
diff --git a/semantica/core/orchestrator.py b/semantica/core/orchestrator.py
index 071cf5a5..3d4a704c 100644
--- a/semantica/core/orchestrator.py
+++ b/semantica/core/orchestrator.py
@@ -4,15 +4,24 @@ Main Orchestrator Module
The Semantica orchestrator coordinates all framework components and manages
the overall execution flow.
-Key Responsibilities:
- - Initialize and coordinate all modules
- - Manage pipeline execution
- - Handle resource allocation
- - Coordinate plugin loading
- - Manage system lifecycle
+This module provides the main entry point for the Semantica framework, handling:
+- Framework initialization and lifecycle management
+- Knowledge base construction from various data sources
+- Pipeline execution and resource management
+- Plugin system coordination
+- System health monitoring
-Main Classes:
- - Semantica: Main framework class
+Example Usage:
+ >>> from semantica import Semantica
+ >>> framework = Semantica()
+ >>> result = framework.build_knowledge_base(
+ ... sources=["doc1.pdf", "doc2.docx"],
+ ... embeddings=True,
+ ... graph=True
+ ... )
+
+Author: Semantica Contributors
+License: MIT
"""
from typing import Any, Dict, List, Optional, Union
@@ -76,6 +85,7 @@ class Semantica:
# Module placeholders (to be initialized)
self._modules: Dict[str, Any] = {}
+ self._initialized: bool = False
self.logger.info("Semantica framework initialized")
@@ -118,12 +128,18 @@ class Semantica:
extra={"health_summary": health_summary}
)
+ self._initialized = True
self.logger.info("Semantica framework initialization completed")
except Exception as e:
self.logger.error(f"Initialization failed: {e}")
raise
+ def _ensure_initialized(self) -> None:
+ """Ensure framework is initialized (lazy initialization)."""
+ if not self._initialized:
+ self.initialize()
+
@log_execution_time
def build_knowledge_base(self, sources: List[Union[str, Path]], **kwargs) -> Dict[str, Any]:
"""
@@ -150,6 +166,9 @@ class Semantica:
Raises:
ProcessingError: If processing fails
"""
+ # Auto-initialize if not already initialized
+ self._ensure_initialized()
+
try:
self.logger.info(f"Building knowledge base from {len(sources)} sources")
@@ -317,119 +336,376 @@ class Semantica:
self.logger.info("Semantica framework shutdown completed")
def _register_startup_hooks(self) -> None:
- """Register framework startup hooks."""
- # Register config validation hook
+ """
+ Register framework startup hooks.
+
+ This method registers all framework-level startup hooks that execute
+ during initialization. Hooks are registered with specific priorities
+ to ensure correct execution order.
+
+ Registered Hooks:
+ - Config validation (priority 10): Validates configuration before other operations
+ - Module initialization (priority 30): Initializes framework modules
+ """
+ # Register config validation hook (high priority - runs first)
def validate_config_hook():
+ """Validate configuration during startup."""
self.config.validate()
self.lifecycle_manager.register_startup_hook(validate_config_hook, priority=10)
- # Register module initialization hook
+ # Register module initialization hook (lower priority - runs after validation)
def initialize_modules_hook():
+ """Initialize framework modules during startup."""
self._initialize_modules()
self.lifecycle_manager.register_startup_hook(initialize_modules_hook, priority=30)
def _initialize_modules(self) -> None:
- """Initialize framework modules."""
- # Initialize core modules if needed
- # This is called during startup to ensure all modules are ready
+ """
+ Initialize framework modules.
+
+ This method attempts to import and verify availability of key framework
+ modules. It's called during startup to ensure modules are ready for use.
+ Import failures are logged but don't stop initialization (modules may be optional).
+
+ Modules Checked:
+ - GraphBuilder: Knowledge graph construction
+ - PipelineBuilder: Processing pipeline creation
+ - FileIngestor: File ingestion capabilities
+ - DocumentParser: Document parsing capabilities
+ """
try:
- # Import and initialize key modules to ensure they're available
+ # Import key modules to verify they're available
+ # These imports don't create instances, just verify module availability
from ..kg import GraphBuilder
from ..pipeline import PipelineBuilder
from ..ingest import FileIngestor
from ..parse import DocumentParser
- # Log initialization
- if hasattr(self, 'logger'):
- self.logger.debug("Framework modules initialized")
+ self.logger.debug("Framework modules verified and available")
except ImportError as e:
- # Log but don't fail - modules may be optional
- if hasattr(self, 'logger'):
- self.logger.warning(f"Some modules could not be imported: {e}")
+ # Log but don't fail - modules may be optional or not installed
+ self.logger.warning(
+ f"Some framework modules could not be imported: {e}. "
+ "They may be optional or not installed."
+ )
def _load_plugins(self) -> None:
- """Load configured plugins."""
+ """
+ Load configured plugins from configuration.
+
+ This method reads the plugin configuration from the framework config
+ and loads each plugin using the plugin registry. Plugin loading failures
+ are logged but don't stop the initialization process.
+
+ Configuration Format:
+ plugins:
+ plugin_name:
+ config_key: config_value
+ ...
+ """
plugins_config = self.config.get("plugins", {})
+ if not plugins_config:
+ self.logger.debug("No plugins configured")
+ return
+
+ self.logger.info(f"Loading {len(plugins_config)} configured plugin(s)")
+
for plugin_name, plugin_config in plugins_config.items():
try:
+ # Load plugin with its configuration
self.plugin_registry.load_plugin(plugin_name, **plugin_config)
- self.logger.info(f"Loaded plugin: {plugin_name}")
+ self.logger.info(f"Successfully loaded plugin: {plugin_name}")
except Exception as e:
- self.logger.error(f"Failed to load plugin {plugin_name}: {e}")
+ # Log error but continue loading other plugins
+ self.logger.error(
+ f"Failed to load plugin '{plugin_name}': {e}. "
+ "Continuing with other plugins."
+ )
def _validate_sources(self, sources: List[Union[str, Path]]) -> List[Union[str, Path]]:
- """Validate data sources."""
- validated = []
+ """
+ Validate and filter data sources.
+
+ This method checks if sources exist (for file paths) or are valid URLs.
+ Invalid sources are logged as warnings but don't stop processing.
+
+ Args:
+ sources: List of source paths or URLs to validate
+
+ Returns:
+ List of validated sources
+
+ Raises:
+ ProcessingError: If no valid sources are found
+ """
+ validated_sources = []
for source in sources:
+ # Convert string to Path for easier handling
source_path = Path(source) if isinstance(source, str) else source
- # Check if source exists (if it's a file path)
- if source_path.exists() or str(source).startswith(("http://", "https://")):
- validated.append(source)
+ # Check if source is valid:
+ # 1. File path exists on filesystem
+ # 2. URL starts with http:// or https://
+ is_valid_file = source_path.exists()
+ is_valid_url = isinstance(source, str) and source.startswith(("http://", "https://"))
+
+ if is_valid_file or is_valid_url:
+ validated_sources.append(source)
else:
- self.logger.warning(f"Source not found or invalid: {source}")
+ self.logger.warning(
+ f"Source not found or invalid: {source}. "
+ "Skipping this source."
+ )
- if not validated:
- raise ProcessingError("No valid sources provided")
+ # Ensure we have at least one valid source
+ if not validated_sources:
+ error_msg = (
+ f"No valid sources provided. "
+ f"Checked {len(sources)} source(s), all were invalid."
+ )
+ raise ProcessingError(error_msg)
- return validated
+ return validated_sources
def _create_pipeline(self, pipeline_config: Dict[str, Any]) -> Any:
- """Create processing pipeline from configuration."""
- # Pipeline creation will be implemented in pipeline module
- # For now, return config as placeholder
- return pipeline_config
+ """
+ Create processing pipeline from configuration.
+
+ This method creates a pipeline instance from the provided configuration.
+ The actual pipeline creation is delegated to the pipeline module.
+
+ Args:
+ pipeline_config: Pipeline configuration dictionary
+
+ Returns:
+ Pipeline object or configuration dict (if pipeline module not available)
+ """
+ try:
+ # Try to use PipelineBuilder if available
+ from ..pipeline import PipelineBuilder
+ pipeline_builder = PipelineBuilder()
+ return pipeline_builder.build_from_config(pipeline_config)
+ except ImportError:
+ # Fallback: return config as-is if pipeline module not available
+ self.logger.debug("Pipeline module not available, using config directly")
+ return pipeline_config
def _create_pipeline_from_dict(self, pipeline_dict: Dict[str, Any]) -> Any:
- """Create pipeline object from dictionary."""
- # This will be implemented when pipeline module is available
- return pipeline_dict
+ """
+ Create pipeline object from dictionary configuration.
+
+ Args:
+ pipeline_dict: Dictionary containing pipeline configuration
+
+ Returns:
+ Pipeline object or dict if pipeline module not available
+ """
+ return self._create_pipeline(pipeline_dict)
def _build_knowledge_graph(self, results: List[Dict[str, Any]]) -> Dict[str, Any]:
- """Build knowledge graph from processing results."""
- # Knowledge graph building will be implemented in kg module
- return {"status": "placeholder", "results": results}
+ """
+ Build knowledge graph from processing results.
+
+ This method extracts entities and relationships from processing results
+ and constructs a knowledge graph structure.
+
+ Args:
+ results: List of processing results containing entities and relationships
+
+ Returns:
+ Dictionary containing knowledge graph structure
+ """
+ try:
+ from ..kg import GraphBuilder
+
+ # Extract entities and relationships from results
+ graph_sources = []
+ for result in results:
+ if isinstance(result, dict):
+ source_data = {}
+ if "entities" in result:
+ source_data["entities"] = result["entities"]
+ if "relationships" in result:
+ source_data["relationships"] = result["relationships"]
+ if source_data:
+ graph_sources.append(source_data)
+
+ if not graph_sources:
+ self.logger.warning("No entities or relationships found in results")
+ return {"entities": [], "relationships": [], "metadata": {}}
+
+ # Build knowledge graph
+ graph_builder = GraphBuilder(merge_entities=True, resolve_conflicts=True)
+ knowledge_graph = graph_builder.build(graph_sources)
+
+ return knowledge_graph
+
+ except ImportError:
+ self.logger.warning("KG module not available, returning placeholder")
+ return {"status": "placeholder", "results": results}
def _generate_embeddings(self, results: List[Dict[str, Any]]) -> Dict[str, Any]:
- """Generate embeddings from processing results."""
- # Embedding generation will be implemented in embeddings module
- return {"status": "placeholder", "results": results}
+ """
+ Generate embeddings from processing results.
+
+ This method extracts text content from processing results and generates
+ embeddings using the embeddings module.
+
+ Args:
+ results: List of processing results containing text content
+
+ Returns:
+ Dictionary containing generated embeddings
+ """
+ try:
+ from ..embeddings import EmbeddingGenerator
+
+ # Extract text content from results
+ texts_to_embed = []
+ for result in results:
+ if isinstance(result, dict):
+ # Try to find text content in various possible keys
+ text = (
+ result.get("text") or
+ result.get("content") or
+ result.get("output", {}).get("text") if isinstance(result.get("output"), dict) else None
+ )
+ if text:
+ texts_to_embed.append(text)
+
+ if not texts_to_embed:
+ self.logger.warning("No text content found in results for embedding")
+ return {"embeddings": [], "metadata": {}}
+
+ # Generate embeddings
+ embedding_generator = EmbeddingGenerator()
+ embeddings_result = embedding_generator.process_batch(texts_to_embed)
+
+ return {
+ "embeddings": embeddings_result["embeddings"],
+ "metadata": {
+ "total_texts": len(texts_to_embed),
+ "successful": embeddings_result["success_count"],
+ "failed": embeddings_result["failure_count"]
+ }
+ }
+
+ except ImportError:
+ self.logger.warning("Embeddings module not available, returning placeholder")
+ return {"status": "placeholder", "results": results}
def _allocate_resources(self, pipeline: Any) -> Dict[str, Any]:
- """Allocate resources for pipeline execution."""
- # Resource allocation logic
- return {"allocated": True}
+ """
+ Allocate resources for pipeline execution.
+
+ This method prepares and allocates necessary resources (connections,
+ memory, etc.) for pipeline execution. Currently returns a placeholder
+ but can be extended for actual resource management.
+
+ Args:
+ pipeline: Pipeline object that will be executed
+
+ Returns:
+ Dictionary containing resource allocation information:
+ - allocated: Whether resources were successfully allocated
+ - resources: List of allocated resource references (optional)
+ """
+ # Placeholder for resource allocation logic
+ # Can be extended to allocate database connections, file handles, etc.
+ return {
+ "allocated": True,
+ "resources": []
+ }
def _release_resources(self, resources: Dict[str, Any]) -> None:
- """Release allocated resources."""
+ """
+ Release allocated resources safely.
+
+ This method ensures all resources (connections, files, etc.) are properly
+ closed and cleaned up, even if errors occur during cleanup.
+
+ Args:
+ resources: Dictionary containing resource references to release
+ """
if not resources:
return
- # Release any allocated resources
- if "connections" in resources:
- for conn in resources.get("connections", []):
- try:
- if hasattr(conn, "close"):
- conn.close()
- except Exception:
- pass
+ # Release database/network connections
+ connections = resources.get("connections", [])
+ for connection in connections:
+ try:
+ if hasattr(connection, "close"):
+ connection.close()
+ self.logger.debug("Closed connection resource")
+ except Exception as e:
+ self.logger.warning(f"Error closing connection: {e}")
- if "files" in resources:
- for file_obj in resources.get("files", []):
- try:
- if hasattr(file_obj, "close"):
- file_obj.close()
- except Exception:
- pass
+ # Release file handles
+ file_handles = resources.get("files", [])
+ for file_handle in file_handles:
+ try:
+ if hasattr(file_handle, "close"):
+ file_handle.close()
+ self.logger.debug("Closed file resource")
+ except Exception as e:
+ self.logger.warning(f"Error closing file: {e}")
- # Clear resource dictionary
+ # Clear resource dictionary to prevent reuse
resources.clear()
+ self.logger.debug("All resources released")
def _collect_metrics(self, pipeline: Any) -> Dict[str, Any]:
- """Collect performance metrics from pipeline execution."""
- # Metrics collection logic
- return {"execution_time": 0.0, "memory_usage": 0}
\ No newline at end of file
+ """
+ Collect performance metrics from pipeline execution.
+
+ This method gathers execution metrics such as execution time, memory usage,
+ and other performance indicators from the pipeline.
+
+ Args:
+ pipeline: Pipeline object that was executed
+
+ Returns:
+ Dictionary containing performance metrics
+ """
+ metrics = {
+ "execution_time": 0.0,
+ "memory_usage": 0,
+ "cpu_usage": 0.0
+ }
+
+ # Try to get metrics from pipeline if it has them
+ try:
+ if hasattr(pipeline, "get_metrics"):
+ pipeline_metrics = pipeline.get_metrics()
+ metrics.update(pipeline_metrics)
+ except Exception as e:
+ self.logger.debug(f"Pipeline metrics not available: {e}")
+
+ # Try to get system metrics using psutil (optional dependency)
+ try:
+ import psutil
+ import os
+
+ process = psutil.Process(os.getpid())
+ memory_info = process.memory_info()
+ metrics["memory_usage"] = memory_info.rss # Resident Set Size in bytes
+
+ # Get CPU usage (non-blocking)
+ try:
+ cpu_percent = process.cpu_percent(interval=0.1)
+ metrics["cpu_usage"] = cpu_percent
+ except Exception:
+ # CPU percent may not be available immediately
+ pass
+
+ except ImportError:
+ # psutil not available, use basic metrics
+ self.logger.debug("psutil not available, using basic metrics")
+ except Exception as e:
+ self.logger.debug(f"Error collecting system metrics: {e}")
+
+ return metrics
\ No newline at end of file
diff --git a/semantica/core/plugin_registry.py b/semantica/core/plugin_registry.py
index 990aa753..09a50ef6 100644
--- a/semantica/core/plugin_registry.py
+++ b/semantica/core/plugin_registry.py
@@ -1,17 +1,24 @@
"""
Plugin Registry Module
-Manages dynamic plugin loading, version compatibility, and dependency resolution.
+This module provides comprehensive plugin management for the Semantica framework,
+including dynamic plugin discovery, loading, dependency resolution, and lifecycle management.
Key Features:
- - Dynamic plugin discovery
- - Plugin version management
- - Dependency resolution
- - Plugin lifecycle management
- - Plugin isolation
+ - Dynamic plugin discovery from file system
+ - Plugin version management and compatibility checking
+ - Automatic dependency resolution and loading
+ - Plugin lifecycle management (load, unload, cleanup)
+ - Plugin isolation and error handling
-Main Classes:
- - PluginRegistry: Plugin management system
+Example Usage:
+ >>> from semantica.core import PluginRegistry
+ >>> registry = PluginRegistry(plugin_paths=["./plugins"])
+ >>> plugin = registry.load_plugin("my_plugin", config={"key": "value"})
+ >>> plugins = registry.list_plugins()
+
+Author: Semantica Contributors
+License: MIT
"""
import importlib
@@ -19,7 +26,7 @@ import importlib.util
import inspect
import time
from pathlib import Path
-from typing import Any, Dict, List, Optional, Type
+from typing import Any, Dict, List, Optional, Type, Union
from dataclasses import dataclass, field
from ..utils.exceptions import ConfigurationError, ValidationError
@@ -54,29 +61,57 @@ class PluginRegistry:
"""
Plugin registry and management system.
- Handles registration, loading, and management of plugins.
+ This class manages the complete lifecycle of plugins including discovery,
+ registration, loading, dependency resolution, and unloading. It supports
+ automatic plugin discovery from file paths and manual registration.
+
+ Features:
+ - Automatic plugin discovery from directories
+ - Dependency resolution and automatic loading
+ - Plugin version management
+ - Lifecycle management (load, unload, cleanup)
+ - Plugin metadata and capability tracking
- Attributes:
- plugins: Dictionary of registered plugins
- loaded_plugins: Dictionary of loaded plugin instances
- plugin_paths: List of paths to search for plugins
+ Example Usage:
+ >>> registry = PluginRegistry(plugin_paths=["./plugins", "./custom_plugins"])
+ >>> # Auto-discover plugins from paths
+ >>> plugin = registry.load_plugin("my_plugin", api_key="xxx")
+ >>> info = registry.get_plugin_info("my_plugin")
"""
- def __init__(self, plugin_paths: Optional[List[Path]] = None):
+ def __init__(self, plugin_paths: Optional[List[Union[str, Path]]] = None):
"""
Initialize plugin registry.
+ Creates a new plugin registry and automatically discovers plugins
+ from the provided paths.
+
Args:
- plugin_paths: List of paths to search for plugins
+ plugin_paths: List of directory paths to search for plugins.
+ Can be strings or Path objects. If None, no
+ automatic discovery is performed.
"""
self.logger = get_logger("plugin_registry")
- self.plugins: Dict[str, PluginInfo] = {}
- self.loaded_plugins: Dict[str, LoadedPlugin] = {}
- self.plugin_paths = plugin_paths or []
- self._discovered_plugins: Dict[str, Path] = {}
- # Discover available plugins
- self._discover_plugins()
+ # Normalize plugin paths to Path objects
+ self.plugin_paths: List[Path] = []
+ if plugin_paths:
+ for path in plugin_paths:
+ normalized_path = Path(path) if isinstance(path, str) else path
+ self.plugin_paths.append(normalized_path)
+
+ # Plugin registries
+ self.plugins: Dict[str, PluginInfo] = {} # Registered plugins
+ self.loaded_plugins: Dict[str, LoadedPlugin] = {} # Currently loaded plugins
+ self._discovered_plugins: Dict[str, Path] = {} # Discovery cache
+
+ # Discover available plugins from paths
+ if self.plugin_paths:
+ self.logger.info(f"Discovering plugins from {len(self.plugin_paths)} path(s)")
+ self._discover_plugins()
+ self.logger.info(f"Discovered {len(self.plugins)} plugin(s)")
+ else:
+ self.logger.debug("No plugin paths provided, skipping auto-discovery")
def register_plugin(
self,
@@ -145,53 +180,90 @@ class PluginRegistry:
"""
Load and initialize a plugin.
+ This method loads a plugin, resolves its dependencies automatically,
+ creates an instance, and initializes it. If the plugin is already
+ loaded, returns the existing instance.
+
Args:
- plugin_name: Name of plugin to load
- **config: Plugin configuration
+ plugin_name: Name of the plugin to load
+ **config: Plugin configuration passed to plugin constructor
Returns:
Loaded and initialized plugin instance
Raises:
- ConfigurationError: If plugin not found or load fails
+ ConfigurationError: If plugin not found, dependencies missing,
+ or initialization fails
+
+ Example:
+ >>> plugin = registry.load_plugin("database_plugin", host="localhost")
+ >>> # Dependencies are automatically loaded first
"""
try:
- # Check if already loaded
+ # Check if plugin is already loaded (return existing instance)
if plugin_name in self.loaded_plugins:
- self.logger.debug(f"Plugin {plugin_name} already loaded")
+ self.logger.debug(f"Plugin '{plugin_name}' already loaded, returning existing instance")
return self.loaded_plugins[plugin_name].instance
- # Check if plugin registered
+ # Check if plugin is registered
if plugin_name not in self.plugins:
- # Try to discover and register
+ # Try to discover and register the plugin
+ self.logger.debug(f"Plugin '{plugin_name}' not registered, attempting discovery")
self._discover_plugin(plugin_name)
+ # Check again after discovery
if plugin_name not in self.plugins:
- raise ConfigurationError(f"Plugin {plugin_name} not found")
+ available = list(self.plugins.keys())
+ error_msg = (
+ f"Plugin '{plugin_name}' not found. "
+ f"Available plugins: {available if available else 'none'}"
+ )
+ raise ConfigurationError(error_msg)
plugin_info = self.plugins[plugin_name]
-
- # Load dependencies first
- for dep_name in plugin_info.dependencies:
- if dep_name not in self.loaded_plugins:
- self.logger.debug(f"Loading dependency: {dep_name}")
- self.load_plugin(dep_name)
+ self.logger.debug(f"Loading plugin '{plugin_name}' v{plugin_info.version}")
+
+ # Load dependencies first (recursive)
+ if plugin_info.dependencies:
+ self.logger.debug(
+ f"Plugin '{plugin_name}' has {len(plugin_info.dependencies)} dependency(ies)"
+ )
+ for dep_name in plugin_info.dependencies:
+ if dep_name not in self.loaded_plugins:
+ self.logger.debug(f"Loading dependency: {dep_name}")
+ self.load_plugin(dep_name) # Recursive call
+ else:
+ self.logger.debug(f"Dependency '{dep_name}' already loaded")
# Create plugin instance
plugin_class = plugin_info.plugin_class
try:
+ # Try to create instance with provided config
plugin_instance = plugin_class(**config)
except TypeError as e:
- # If initialization fails, try without config
- self.logger.warning(f"Failed to initialize with config, trying without: {e}")
- plugin_instance = plugin_class()
+ # If initialization fails with config, try without
+ self.logger.warning(
+ f"Failed to initialize '{plugin_name}' with config: {e}. "
+ "Trying without config."
+ )
+ try:
+ plugin_instance = plugin_class()
+ except Exception as e2:
+ raise ConfigurationError(
+ f"Failed to initialize plugin '{plugin_name}': {e2}"
+ ) from e2
- # Initialize plugin
+ # Initialize plugin if it has an initialize method
if hasattr(plugin_instance, "initialize"):
- plugin_instance.initialize()
+ try:
+ plugin_instance.initialize()
+ except Exception as e:
+ raise ConfigurationError(
+ f"Plugin '{plugin_name}' initialization failed: {e}"
+ ) from e
- # Store loaded plugin
+ # Store loaded plugin information
loaded_plugin = LoadedPlugin(
info=plugin_info,
instance=plugin_instance,
@@ -201,13 +273,20 @@ class PluginRegistry:
self.loaded_plugins[plugin_name] = loaded_plugin
- self.logger.info(f"Loaded plugin: {plugin_name}")
+ self.logger.info(
+ f"Successfully loaded plugin '{plugin_name}' v{plugin_info.version}"
+ )
return plugin_instance
+ except ConfigurationError:
+ # Re-raise configuration errors as-is
+ raise
except Exception as e:
- self.logger.error(f"Failed to load plugin {plugin_name}: {e}")
- raise ConfigurationError(f"Failed to load plugin {plugin_name}: {e}")
+ # Wrap other exceptions
+ error_msg = f"Failed to load plugin '{plugin_name}': {e}"
+ self.logger.error(error_msg)
+ raise ConfigurationError(error_msg) from e
def unload_plugin(self, plugin_name: str) -> None:
"""
@@ -333,13 +412,38 @@ class PluginRegistry:
return None
def _discover_plugins(self) -> None:
- """Discover available plugins from plugin paths."""
+ """
+ Discover available plugins from configured plugin paths.
+
+ This method scans all configured plugin paths for Python files that
+ contain plugin classes. Each discovered plugin is automatically
+ registered with the registry.
+
+ Discovery Process:
+ 1. Iterate through all configured plugin paths
+ 2. For each directory, scan for .py files
+ 3. Attempt to load and register each plugin file
+ 4. Log discovery results
+ """
+ discovered_count = 0
+
for plugin_path in self.plugin_paths:
+ # Normalize path to Path object
if isinstance(plugin_path, str):
plugin_path = Path(plugin_path)
+ # Check if path exists and is a directory
if plugin_path.exists() and plugin_path.is_dir():
+ self.logger.debug(f"Scanning plugin directory: {plugin_path}")
+ before_count = len(self.plugins)
self._scan_directory(plugin_path)
+ after_count = len(self.plugins)
+ discovered_count += (after_count - before_count)
+ else:
+ self.logger.debug(f"Plugin path not found or not a directory: {plugin_path}")
+
+ if discovered_count > 0:
+ self.logger.info(f"Discovered {discovered_count} plugin(s) from paths")
def _discover_plugin(self, plugin_name: str) -> None:
"""
@@ -362,8 +466,32 @@ class PluginRegistry:
self.logger.warning(f"Failed to load plugin from {plugin_module_path}: {e}")
def _scan_directory(self, directory: Path) -> None:
- """Scan directory for plugin files."""
- for file_path in directory.glob("*.py"):
+ """
+ Scan directory for plugin files and load them.
+
+ This method finds all Python files in the directory (excluding __init__.py)
+ and attempts to load them as plugins. Files that fail to load are logged
+ but don't stop the scanning process.
+
+ Args:
+ directory: Directory path to scan for plugin files
+
+ Process:
+ - Finds all .py files in directory
+ - Skips __init__.py files
+ - Attempts to load each file as a plugin
+ - Logs failures but continues scanning
+ """
+ plugin_files = list(directory.glob("*.py"))
+
+ if not plugin_files:
+ self.logger.debug(f"No Python files found in {directory}")
+ return
+
+ self.logger.debug(f"Scanning {len(plugin_files)} file(s) in {directory}")
+
+ for file_path in plugin_files:
+ # Skip __init__.py files
if file_path.name == "__init__.py":
continue
@@ -371,65 +499,110 @@ class PluginRegistry:
try:
self._load_plugin_from_file(file_path, plugin_name)
except Exception as e:
- self.logger.debug(f"Failed to load plugin from {file_path}: {e}")
+ # Log but continue - file might not be a valid plugin
+ self.logger.debug(
+ f"Failed to load plugin from {file_path}: {e}. "
+ "File may not be a valid plugin."
+ )
def _load_plugin_from_file(self, file_path: Path, plugin_name: str) -> None:
- """Load plugin from file."""
+ """
+ Load and register a plugin from a Python file.
+
+ This method dynamically imports a Python module, finds the plugin class,
+ extracts metadata, and registers the plugin with the registry.
+
+ Plugin Class Detection:
+ The method tries multiple strategies to find the plugin class:
+ 1. Common naming patterns (PluginName, PluginNamePlugin, etc.)
+ 2. Any class containing "Plugin" in its name
+ 3. Falls back to first class found if no pattern matches
+
+ Metadata Extraction:
+ Extracts plugin metadata from module attributes:
+ - description: From __doc__ or module.description
+ - author: From module.author
+ - version: From module.version (default: "1.0.0")
+ - dependencies: From module.dependencies
+ - capabilities: From module.capabilities
+
+ Args:
+ file_path: Path to the Python file containing the plugin
+ plugin_name: Name to use for the plugin (typically file stem)
+
+ Raises:
+ Exception: If file cannot be loaded or plugin class not found
+ """
try:
- # Import module
+ # Create module spec from file path
spec = importlib.util.spec_from_file_location(plugin_name, file_path)
if spec is None or spec.loader is None:
+ self.logger.warning(f"Could not create module spec for {file_path}")
return
+ # Load and execute the module
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
- # Find plugin class (typically named after plugin or has Plugin suffix)
+ # Find plugin class using multiple strategies
plugin_class = None
- # Try common naming patterns
+ # Strategy 1: Try common naming patterns
class_names = [
- plugin_name.capitalize(),
- plugin_name.capitalize() + "Plugin",
- plugin_name.replace("_", "").capitalize(),
+ plugin_name.capitalize(), # "my_plugin" -> "My_plugin"
+ plugin_name.capitalize() + "Plugin", # "my_plugin" -> "My_pluginPlugin"
+ plugin_name.replace("_", "").capitalize(), # "my_plugin" -> "Myplugin"
]
for class_name in class_names:
if hasattr(module, class_name):
- plugin_class = getattr(module, class_name)
- if inspect.isclass(plugin_class):
+ candidate = getattr(module, class_name)
+ if inspect.isclass(candidate):
+ plugin_class = candidate
+ self.logger.debug(f"Found plugin class '{class_name}' using naming pattern")
break
- # If not found, look for any class with Plugin in name
+ # Strategy 2: Look for any class with "Plugin" in name
if plugin_class is None:
for name, obj in inspect.getmembers(module):
if inspect.isclass(obj) and "Plugin" in name:
plugin_class = obj
+ self.logger.debug(f"Found plugin class '{name}' by 'Plugin' keyword")
break
+ # If still not found, cannot register plugin
if plugin_class is None:
- self.logger.warning(f"No plugin class found in {file_path}")
+ self.logger.warning(
+ f"No plugin class found in {file_path}. "
+ "Expected class name patterns: PluginName, PluginNamePlugin, or *Plugin"
+ )
return
- # Get metadata from module if available
+ # Extract metadata from module attributes
metadata = {
- "description": getattr(module, "__doc__", "") or getattr(module, "description", ""),
+ "description": (
+ getattr(module, "__doc__", "") or
+ getattr(module, "description", "")
+ ),
"author": getattr(module, "author", ""),
"version": getattr(module, "version", "1.0.0"),
"dependencies": getattr(module, "dependencies", []),
"capabilities": getattr(module, "capabilities", []),
}
- # Register plugin
+ # Register the discovered plugin
self.register_plugin(
plugin_name=plugin_name,
plugin_class=plugin_class,
**metadata
)
+ self.logger.debug(f"Successfully loaded plugin '{plugin_name}' from {file_path}")
+
except Exception as e:
- self.logger.error(f"Failed to load plugin from {file_path}: {e}")
- raise
+ error_msg = f"Failed to load plugin from {file_path}: {e}"
+ self.logger.error(error_msg)
+ raise Exception(error_msg) from e
def _validate_dependencies(self, plugin_info: PluginInfo) -> None:
"""