Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat: implement utils module with exceptions, helpers, logging, types, and validators

KaifAhmad1877d842de27c
diff --git a/git-commands.md b/git-commands.md
new file mode 100644
index 00000000..27d59516
--- /dev/null
+++ b/git-commands.md
@@ -0,0 +1,157 @@
+# Git Commands for Branch, PR, and Merge Workflow
+
+## Option 1: Using GitHub CLI (Recommended)
+
+### Step 1: Create and Switch to New Branch
+```bash
+git checkout -b feature/utils-implementation
+```
+or
+```bash
+git switch -c feature/utils-implementation
+```
+
+### Step 2: Stage Your Changes
+```bash
+git add libs/semantica/utils/
+```
+
+### Step 3: Commit Changes
+```bash
+git commit -m "feat: implement utils module with exceptions, helpers, logging, types, and validators
+
+- Implement exceptions.py with comprehensive error handling
+- Implement helpers.py with utility functions
+- Implement logging.py with structured logging
+- Implement types.py with type definitions and protocols
+- Implement validators.py with validation functions
+- Update __init__.py to export all utilities"
+```
+
+### Step 4: Push Branch to Remote
+```bash
+git push -u origin feature/utils-implementation
+```
+
+### Step 5: Create Pull Request (using GitHub CLI)
+```bash
+gh pr create --title "feat: implement utils module" --body "Implements complete utils module with all utilities, exceptions, logging, types, and validators" --base main
+```
+
+### Step 6: Merge Pull Request (using GitHub CLI)
+```bash
+gh pr merge feature/utils-implementation --merge --delete-branch
+```
+
+---
+
+## Option 2: Manual Git Commands (Without GitHub CLI)
+
+### Step 1: Create and Switch to New Branch
+```bash
+git checkout -b feature/utils-implementation
+```
+
+### Step 2: Stage Your Changes
+```bash
+git add libs/semantica/utils/
+```
+
+### Step 3: Commit Changes
+```bash
+git commit -m "feat: implement utils module with exceptions, helpers, logging, types, and validators
+
+- Implement exceptions.py with comprehensive error handling
+- Implement helpers.py with utility functions
+- Implement logging.py with structured logging
+- Implement types.py with type definitions and protocols
+- Implement validators.py with validation functions
+- Update __init__.py to export all utilities"
+```
+
+### Step 4: Push Branch to Remote
+```bash
+git push -u origin feature/utils-implementation
+```
+
+### Step 5: Create Pull Request
+After pushing, go to GitHub and create PR, OR use the URL:
+```
+https://github.com/YOUR_USERNAME/semantica-9/compare/main...feature/utils-implementation
+```
+
+### Step 6: Merge Locally (Alternative to PR merge)
+```bash
+# Switch to main branch
+git checkout main
+
+# Pull latest changes
+git pull origin main
+
+# Merge feature branch
+git merge feature/utils-implementation
+
+# Push merged changes
+git push origin main
+
+# Delete local branch
+git branch -d feature/utils-implementation
+
+# Delete remote branch
+git push origin --delete feature/utils-implementation
+```
+
+---
+
+## Quick Commands Summary (Copy-Paste)
+
+### For Feature Branch Workflow:
+```bash
+# 1. Create branch
+git checkout -b feature/utils-implementation
+
+# 2. Stage changes
+git add libs/semantica/utils/
+
+# 3. Commit
+git commit -m "feat: implement utils module"
+
+# 4. Push
+git push -u origin feature/utils-implementation
+
+# 5. Create PR (with GitHub CLI)
+gh pr create --title "feat: implement utils module" --body "Implements complete utils module" --base main
+
+# 6. Merge PR (with GitHub CLI)
+gh pr merge feature/utils-implementation --merge --delete-branch
+```
+
+### For Direct Merge to Main (If PR not needed):
+```bash
+# 1. Create branch
+git checkout -b feature/utils-implementation
+
+# 2. Stage and commit
+git add libs/semantica/utils/
+git commit -m "feat: implement utils module"
+
+# 3. Switch to main
+git checkout main
+
+# 4. Merge branch
+git merge feature/utils-implementation
+
+# 5. Push
+git push origin main
+
+# 6. Clean up
+git branch -d feature/utils-implementation
+```
+
+---
+
+## Notes:
+- Replace `feature/utils-implementation` with your preferred branch name
+- Replace commit message with your preferred message
+- If using GitHub CLI, make sure you're logged in: `gh auth login`
+- Always pull latest changes before creating branch: `git pull origin main`
diff --git a/libs/semantica/utils/__init__.py b/libs/semantica/utils/__init__.py
index 3adb5b9a..9e48e6b2 100644
--- a/libs/semantica/utils/__init__.py
+++ b/libs/semantica/utils/__init__.py
@@ -11,9 +11,200 @@ Exports:
- Constants and types
"""
-# from .logging import setup_logging, get_logger
-# from .exceptions import SemanticaError, ValidationError, ProcessingError
-# from .validators import validate_data, validate_config
-# from .helpers import format_data, clean_text, normalize_entities
-# from .constants import SUPPORTED_FORMATS, DEFAULT_CONFIG
-# from .types import DataType, ProcessingStatus, QualityLevel
+from .logging import (
+ setup_logging,
+ get_logger,
+ log_performance,
+ log_error,
+ log_data_quality,
+ log_execution_time,
+)
+from .exceptions import (
+ SemanticaError,
+ ValidationError,
+ ProcessingError,
+ ConfigurationError,
+ QualityError,
+ handle_exception,
+ format_exception,
+)
+from .validators import (
+ validate_data,
+ validate_config,
+ validate_schema,
+ validate_types,
+ validate_required_fields,
+ validate_string_constraints,
+ validate_numeric_constraints,
+ validate_list_constraints,
+ validate_entity,
+ validate_relationship,
+ validate_file_path,
+ validate_url,
+ validate_email,
+)
+from .helpers import (
+ format_data,
+ clean_text,
+ normalize_entities,
+ hash_data,
+ safe_filename,
+ ensure_directory,
+ read_json_file,
+ write_json_file,
+ get_file_size,
+ format_timestamp,
+ parse_timestamp,
+ merge_dicts,
+ chunk_list,
+ flatten_dict,
+ get_nested_value,
+ set_nested_value,
+ retry_on_error,
+)
+from .constants import (
+ SUPPORTED_DOCUMENT_FORMATS,
+ SUPPORTED_IMAGE_FORMATS,
+ SUPPORTED_AUDIO_FORMATS,
+ SUPPORTED_VIDEO_FORMATS,
+ SUPPORTED_RDF_FORMATS,
+ SUPPORTED_VECTOR_STORES,
+ SUPPORTED_GRAPH_DBS,
+ DEFAULT_CONFIG,
+ ERROR_CODES,
+ PERFORMANCE_THRESHOLDS,
+ QUALITY_LEVELS,
+ ENTITY_TYPES,
+ RELATIONSHIP_TYPES,
+ PROCESSING_STATUS,
+ DATA_TYPES,
+ API_ENDPOINTS,
+ FILE_SIZE_LIMITS,
+ RETRY_CONFIG,
+ CACHE_CONFIG,
+)
+from .types import (
+ # Type Aliases
+ JSONType,
+ EntityDict,
+ RelationshipDict,
+ ConfigDict,
+ DataDict,
+ # Enums
+ EntityType,
+ DataType,
+ ProcessingStatus,
+ QualityLevel,
+ RelationshipType,
+ # Data Classes
+ Entity,
+ Relationship,
+ ProcessingResult,
+ QualityMetrics,
+ # Generic Types
+ Result,
+ BatchResult,
+ # Type Guards
+ is_entity_dict,
+ is_relationship_dict,
+ is_processing_result,
+ # Conversion Functions
+ entity_to_dict,
+ dict_to_entity,
+ relationship_to_dict,
+ dict_to_relationship,
+)
+
+__all__ = [
+ # Logging
+ "setup_logging",
+ "get_logger",
+ "log_performance",
+ "log_error",
+ "log_data_quality",
+ "log_execution_time",
+ # Exceptions
+ "SemanticaError",
+ "ValidationError",
+ "ProcessingError",
+ "ConfigurationError",
+ "QualityError",
+ "handle_exception",
+ "format_exception",
+ # Validators
+ "validate_data",
+ "validate_config",
+ "validate_schema",
+ "validate_types",
+ "validate_required_fields",
+ "validate_string_constraints",
+ "validate_numeric_constraints",
+ "validate_list_constraints",
+ "validate_entity",
+ "validate_relationship",
+ "validate_file_path",
+ "validate_url",
+ "validate_email",
+ # Helpers
+ "format_data",
+ "clean_text",
+ "normalize_entities",
+ "hash_data",
+ "safe_filename",
+ "ensure_directory",
+ "read_json_file",
+ "write_json_file",
+ "get_file_size",
+ "format_timestamp",
+ "parse_timestamp",
+ "merge_dicts",
+ "chunk_list",
+ "flatten_dict",
+ "get_nested_value",
+ "set_nested_value",
+ "retry_on_error",
+ # Constants
+ "SUPPORTED_DOCUMENT_FORMATS",
+ "SUPPORTED_IMAGE_FORMATS",
+ "SUPPORTED_AUDIO_FORMATS",
+ "SUPPORTED_VIDEO_FORMATS",
+ "SUPPORTED_RDF_FORMATS",
+ "SUPPORTED_VECTOR_STORES",
+ "SUPPORTED_GRAPH_DBS",
+ "DEFAULT_CONFIG",
+ "ERROR_CODES",
+ "PERFORMANCE_THRESHOLDS",
+ "QUALITY_LEVELS",
+ "ENTITY_TYPES",
+ "RELATIONSHIP_TYPES",
+ "PROCESSING_STATUS",
+ "DATA_TYPES",
+ "API_ENDPOINTS",
+ "FILE_SIZE_LIMITS",
+ "RETRY_CONFIG",
+ "CACHE_CONFIG",
+ # Types
+ "JSONType",
+ "EntityDict",
+ "RelationshipDict",
+ "ConfigDict",
+ "DataDict",
+ "EntityType",
+ "DataType",
+ "ProcessingStatus",
+ "QualityLevel",
+ "RelationshipType",
+ "Entity",
+ "Relationship",
+ "ProcessingResult",
+ "QualityMetrics",
+ "Result",
+ "BatchResult",
+ "is_entity_dict",
+ "is_relationship_dict",
+ "is_processing_result",
+ "entity_to_dict",
+ "dict_to_entity",
+ "relationship_to_dict",
+ "dict_to_relationship",
+]
\ No newline at end of file
diff --git a/libs/semantica/utils/exceptions.py b/libs/semantica/utils/exceptions.py
index 9243fbb4..20186494 100644
--- a/libs/semantica/utils/exceptions.py
+++ b/libs/semantica/utils/exceptions.py
@@ -11,205 +11,351 @@ Key Features:
- Error reporting and logging
"""
+import traceback
+import sys
+from typing import Any, Dict, Optional, Type
+
class SemanticaError(Exception):
"""
Base exception class for all Semantica framework errors.
- • Provides base error handling
- • Includes error context and debugging information
- • Supports error chaining and propagation
- • Handles error reporting and logging
+ Provides base error handling with:
+ - Error context and debugging information
+ - Error chaining and propagation
+ - Error reporting and logging
"""
- def __init__(self, message, context=None, **details):
+ def __init__(
+ self,
+ message: str,
+ context: Optional[Dict[str, Any]] = None,
+ **details: Any
+ ):
"""
Initialize Semantica error.
- • Set error message
- • Include error context
- • Add error details
- • Setup error debugging information
-
Args:
message: Error message
- context: Error context
- **details: Additional error details
+ context: Error context dictionary
+ **details: Additional error details as keyword arguments
+ """
+ super().__init__(message)
+ self.message = message
+ self.context = context or {}
+ self.details = details
+ self.error_code = self.details.get("error_code", "SEM000")
+
+ # Capture stack trace
+ _, _, self.traceback = sys.exc_info()
+
+ def __str__(self) -> str:
+ """Return formatted error message with context."""
+ parts = [self.message]
+
+ if self.context:
+ context_str = ", ".join(f"{k}={v}" for k, v in self.context.items())
+ parts.append(f"Context: {context_str}")
+
+ if self.details:
+ details_str = ", ".join(
+ f"{k}={v}" for k, v in self.details.items() if k != "error_code"
+ )
+ if details_str:
+ parts.append(f"Details: {details_str}")
+
+ return " | ".join(parts)
+
+ def __repr__(self) -> str:
+ """Return detailed representation of the error."""
+ return (
+ f"{self.__class__.__name__}("
+ f"message={self.message!r}, "
+ f"context={self.context}, "
+ f"error_code={self.error_code}, "
+ f"details={self.details})"
+ )
+
+ def to_dict(self) -> Dict[str, Any]:
+ """
+ Convert error to dictionary format for serialization.
+
+ Returns:
+ Dictionary containing error information
"""
- # TODO: Set error message
- # TODO: Include error context
- # TODO: Add error details
- # TODO: Setup error debugging information
- pass
+ return {
+ "error_type": self.__class__.__name__,
+ "message": self.message,
+ "error_code": self.error_code,
+ "context": self.context,
+ "details": self.details,
+ }
class ValidationError(SemanticaError):
"""
Exception raised for data validation errors.
- • Handles data validation failures
- • Includes validation context and details
- • Supports validation error reporting
- • Manages validation error recovery
+ Handles data validation failures with:
+ - Validation context and details
+ - Validation error reporting
+ - Validation error recovery support
"""
- def __init__(self, message, validation_context=None, **details):
+ def __init__(
+ self,
+ message: str,
+ validation_context: Optional[Dict[str, Any]] = None,
+ **details: Any
+ ):
"""
Initialize validation error.
- • Set validation error message
- • Include validation context
- • Add validation details
- • Setup validation error debugging
-
Args:
message: Validation error message
- validation_context: Validation context
+ validation_context: Validation context dictionary
**details: Additional validation details
"""
- # TODO: Set validation error message
- # TODO: Include validation context
- # TODO: Add validation details
- # TODO: Setup validation error debugging
- pass
+ super().__init__(
+ message,
+ context=validation_context,
+ error_code="SEM001",
+ **details
+ )
+ self.validation_context = validation_context or {}
+ self.field = details.get("field")
+ self.value = details.get("value")
+ self.constraint = details.get("constraint")
class ProcessingError(SemanticaError):
"""
Exception raised for data processing errors.
- • Handles data processing failures
- • Includes processing context and details
- • Supports processing error reporting
- • Manages processing error recovery
+ Handles data processing failures with:
+ - Processing context and details
+ - Processing error reporting
+ - Processing error recovery support
"""
- def __init__(self, message, processing_context=None, **details):
+ def __init__(
+ self,
+ message: str,
+ processing_context: Optional[Dict[str, Any]] = None,
+ **details: Any
+ ):
"""
Initialize processing error.
- • Set processing error message
- • Include processing context
- • Add processing details
- • Setup processing error debugging
-
Args:
message: Processing error message
- processing_context: Processing context
+ processing_context: Processing context dictionary
**details: Additional processing details
"""
- # TODO: Set processing error message
- # TODO: Include processing context
- # TODO: Add processing details
- # TODO: Setup processing error debugging
- pass
+ super().__init__(
+ message,
+ context=processing_context,
+ error_code="SEM002",
+ **details
+ )
+ self.processing_context = processing_context or {}
+ self.stage = details.get("stage")
+ self.input_data = details.get("input_data")
+ self.output_data = details.get("output_data")
class ConfigurationError(SemanticaError):
"""
Exception raised for configuration errors.
- • Handles configuration validation failures
- • Includes configuration context and details
- • Supports configuration error reporting
- • Manages configuration error recovery
+ Handles configuration validation failures with:
+ - Configuration context and details
+ - Configuration error reporting
+ - Configuration error recovery support
"""
- def __init__(self, message, config_context=None, **details):
+ def __init__(
+ self,
+ message: str,
+ config_context: Optional[Dict[str, Any]] = None,
+ **details: Any
+ ):
"""
Initialize configuration error.
- • Set configuration error message
- • Include configuration context
- • Add configuration details
- • Setup configuration error debugging
-
Args:
message: Configuration error message
- config_context: Configuration context
+ config_context: Configuration context dictionary
**details: Additional configuration details
"""
- # TODO: Set configuration error message
- # TODO: Include configuration context
- # TODO: Add configuration details
- # TODO: Setup configuration error debugging
- pass
+ super().__init__(
+ message,
+ context=config_context,
+ error_code="SEM003",
+ **details
+ )
+ self.config_context = config_context or {}
+ self.config_key = details.get("config_key")
+ self.config_value = details.get("config_value")
+ self.expected_type = details.get("expected_type")
class QualityError(SemanticaError):
"""
Exception raised for data quality errors.
- • Handles data quality validation failures
- • Includes quality context and details
- • Supports quality error reporting
- • Manages quality error recovery
+ Handles data quality validation failures with:
+ - Quality context and details
+ - Quality error reporting
+ - Quality error recovery support
"""
- def __init__(self, message, quality_context=None, **details):
+ def __init__(
+ self,
+ message: str,
+ quality_context: Optional[Dict[str, Any]] = None,
+ **details: Any
+ ):
"""
Initialize quality error.
- • Set quality error message
- • Include quality context
- • Add quality details
- • Setup quality error debugging
-
Args:
message: Quality error message
- quality_context: Quality context
+ quality_context: Quality context dictionary
**details: Additional quality details
"""
- # TODO: Set quality error message
- # TODO: Include quality context
- # TODO: Add quality details
- # TODO: Setup quality error debugging
- pass
+ super().__init__(
+ message,
+ context=quality_context,
+ error_code="SEM004",
+ **details
+ )
+ self.quality_context = quality_context or {}
+ self.quality_score = details.get("quality_score")
+ self.threshold = details.get("threshold")
+ self.metrics = details.get("metrics", {})
-def handle_exception(exception, context=None, **options):
+def handle_exception(
+ exception: Exception,
+ context: Optional[Dict[str, Any]] = None,
+ **options: Any
+) -> Dict[str, Any]:
"""
Handle exception with context and options.
- • Process exception information
- • Include context and debugging information
- • Handle exception recovery
- • Log exception details
+ Processes exception information and returns structured error data.
Args:
exception: Exception to handle
- context: Exception context
+ context: Exception context dictionary
**options: Additional handling options
Returns:
- dict: Exception handling results
+ Dictionary containing exception handling results:
+ - handled: Whether exception was handled
+ - error_type: Type of error
+ - message: Error message
+ - context: Error context
+ - traceback: Formatted traceback string
+ - recovery: Recovery action if any
"""
- # TODO: Process exception information
- # TODO: Include context and debugging information
- # TODO: Handle exception recovery
- # TODO: Log exception details
- # TODO: Return exception handling results
- pass
+ context = context or {}
+ recovery_action = options.get("recovery_action", "log_and_continue")
+ log_error = options.get("log_error", True)
+
+ # Extract error information
+ error_info = {
+ "handled": True,
+ "error_type": type(exception).__name__,
+ "message": str(exception),
+ "context": context,
+ "traceback": None,
+ "recovery": recovery_action,
+ }
+
+ # Add traceback if requested
+ if options.get("include_traceback", True):
+ error_info["traceback"] = "".join(
+ traceback.format_exception(type(exception), exception, exception.__traceback__)
+ )
+
+ # Add exception-specific details
+ if isinstance(exception, SemanticaError):
+ error_info["error_code"] = exception.error_code
+ error_info["details"] = exception.details
+ if hasattr(exception, "context"):
+ error_info["context"].update(exception.context)
+
+ # Log error if requested
+ if log_error:
+ # Import here to avoid circular dependency
+ try:
+ from .logging import log_error as log_err
+ log_err(exception, context=context, **options)
+ except ImportError:
+ # Fallback to print if logging not available
+ print(f"Error: {error_info}")
+
+ return error_info
-def format_exception(exception, **options):
+def format_exception(exception: Exception, **options: Any) -> str:
"""
Format exception for display and logging.
- • Format exception message
- • Include exception context
- • Add debugging information
- • Return formatted exception
+ Formats exception message with context and debugging information.
Args:
exception: Exception to format
- **options: Additional formatting options
-
+ **options: Additional formatting options:
+ - include_traceback: Include full traceback (default: False)
+ - include_context: Include context information (default: True)
+ - max_length: Maximum length of formatted string (default: None)
+
Returns:
- str: Formatted exception string
+ Formatted exception string
"""
- # TODO: Format exception message
- # TODO: Include exception context
- # TODO: Add debugging information
- # TODO: Return formatted exception string
- pass
+ parts = []
+
+ # Add error type and message
+ error_type = type(exception).__name__
+ error_message = str(exception)
+ parts.append(f"{error_type}: {error_message}")
+
+ # Add exception-specific details
+ if isinstance(exception, SemanticaError):
+ if exception.error_code:
+ parts.append(f"Error Code: {exception.error_code}")
+
+ if options.get("include_context", True) and exception.context:
+ context_str = ", ".join(
+ f"{k}={v}" for k, v in exception.context.items()
+ )
+ parts.append(f"Context: {context_str}")
+
+ if exception.details:
+ details_str = ", ".join(
+ f"{k}={v}" for k, v in exception.details.items()
+ if k != "error_code"
+ )
+ if details_str:
+ parts.append(f"Details: {details_str}")
+
+ # Add traceback if requested
+ if options.get("include_traceback", False):
+ tb_str = "".join(
+ traceback.format_exception(
+ type(exception), exception, exception.__traceback__
+ )
+ )
+ parts.append(f"\nTraceback:\n{tb_str}")
+
+ formatted = "\n".join(parts)
+
+ # Truncate if max_length specified
+ max_length = options.get("max_length")
+ if max_length and len(formatted) > max_length:
+ formatted = formatted[:max_length] + "..."
+
+ return formatted
\ No newline at end of file
diff --git a/libs/semantica/utils/helpers.py b/libs/semantica/utils/helpers.py
index 45972c4f..e224fb63 100644
--- a/libs/semantica/utils/helpers.py
+++ b/libs/semantica/utils/helpers.py
@@ -3,12 +3,471 @@ Helper utilities for Semantica framework.
This module contains shared utility functions used across different
modules of the Semantica framework.
+
+Key Features:
+ - Common data manipulation utilities
+ - File handling helpers
+ - String processing utilities
+ - Date/time helpers
+ - Configuration helpers
+ - Error handling utilities
"""
-# TODO: Implement helper functions
-# - Common data manipulation utilities
-# - File handling helpers
-# - String processing utilities
-# - Date/time helpers
-# - Configuration helpers
-# - Error handling utilities
+import os
+import re
+import json
+import hashlib
+from datetime import datetime, timezone
+from typing import Any, Dict, List, Optional, Union, Tuple
+from pathlib import Path
+
+
+def format_data(data: Any, format_type: str = "json") -> str:
+ """
+ Format data into specified format.
+
+ Args:
+ data: Data to format
+ format_type: Format type ('json', 'yaml', 'xml', 'csv')
+
+ Returns:
+ Formatted data string
+
+ Raises:
+ ValueError: If format_type is not supported
+ """
+ if format_type == "json":
+ return json.dumps(data, indent=2, ensure_ascii=False)
+ elif format_type == "yaml":
+ try:
+ import yaml
+ return yaml.dump(data, default_flow_style=False)
+ except ImportError:
+ raise ValueError("PyYAML not installed. Install with: pip install pyyaml")
+ else:
+ raise ValueError(f"Unsupported format type: {format_type}")
+
+
+def clean_text(text: str, preserve_whitespace: bool = False) -> str:
+ """
+ Clean and normalize text.
+
+ Removes extra whitespace, normalizes line breaks, and handles
+ common text issues.
+
+ Args:
+ text: Text to clean
+ preserve_whitespace: If True, preserve significant whitespace
+
+ Returns:
+ Cleaned text string
+ """
+ if not text:
+ return ""
+
+ # Remove leading/trailing whitespace
+ text = text.strip()
+
+ if not preserve_whitespace:
+ # Normalize multiple spaces to single space
+ text = re.sub(r"\s+", " ", text)
+ # Normalize line breaks
+ text = re.sub(r"\n\s*\n", "\n", text)
+
+ # Remove zero-width characters
+ text = re.sub(r"[\u200b-\u200d\ufeff]", "", text)
+
+ return text
+
+
+def normalize_entities(entities: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
+ """
+ Normalize entity dictionaries to consistent format.
+
+ Ensures all entities have required fields and consistent structure.
+
+ Args:
+ entities: List of entity dictionaries
+
+ Returns:
+ List of normalized entity dictionaries
+ """
+ normalized = []
+
+ for entity in entities:
+ normalized_entity = {
+ "id": entity.get("id") or entity.get("entity_id"),
+ "text": entity.get("text") or entity.get("label") or entity.get("name"),
+ "type": entity.get("type") or entity.get("entity_type"),
+ "confidence": entity.get("confidence", 1.0),
+ "start": entity.get("start") or entity.get("start_offset"),
+ "end": entity.get("end") or entity.get("end_offset"),
+ }
+
+ # Add optional fields if present
+ if "metadata" in entity:
+ normalized_entity["metadata"] = entity["metadata"]
+ if "relations" in entity:
+ normalized_entity["relations"] = entity["relations"]
+
+ normalized.append(normalized_entity)
+
+ return normalized
+
+
+def hash_data(data: Union[str, bytes, Dict[str, Any]]) -> str:
+ """
+ Generate hash for data.
+
+ Args:
+ data: Data to hash (string, bytes, or dictionary)
+
+ Returns:
+ Hexadecimal hash string
+ """
+ if isinstance(data, dict):
+ # Sort keys for consistent hashing
+ data_str = json.dumps(data, sort_keys=True)
+ data = data_str.encode("utf-8")
+ elif isinstance(data, str):
+ data = data.encode("utf-8")
+
+ return hashlib.sha256(data).hexdigest()
+
+
+def safe_filename(filename: str, max_length: int = 255) -> str:
+ """
+ Generate safe filename from string.
+
+ Removes invalid characters and ensures filename is safe for filesystem.
+
+ Args:
+ filename: Original filename
+ max_length: Maximum length of filename
+
+ Returns:
+ Safe filename string
+ """
+ # Remove invalid characters
+ filename = re.sub(r'[<>:"/\\|?*]', "", filename)
+
+ # Replace spaces with underscores
+ filename = filename.replace(" ", "_")
+
+ # Remove leading/trailing dots and spaces
+ filename = filename.strip(". ")
+
+ # Truncate if too long
+ if len(filename) > max_length:
+ name, ext = os.path.splitext(filename)
+ max_name_length = max_length - len(ext)
+ filename = name[:max_name_length] + ext
+
+ return filename or "unnamed"
+
+
+def ensure_directory(path: Union[str, Path]) -> Path:
+ """
+ Ensure directory exists, create if it doesn't.
+
+ Args:
+ path: Directory path
+
+ Returns:
+ Path object for the directory
+ """
+ dir_path = Path(path)
+ dir_path.mkdir(parents=True, exist_ok=True)
+ return dir_path
+
+
+def read_json_file(filepath: Union[str, Path]) -> Dict[str, Any]:
+ """
+ Read JSON file safely.
+
+ Args:
+ filepath: Path to JSON file
+
+ Returns:
+ Parsed JSON data
+
+ Raises:
+ FileNotFoundError: If file doesn't exist
+ json.JSONDecodeError: If file contains invalid JSON
+ """
+ filepath = Path(filepath)
+ if not filepath.exists():
+ raise FileNotFoundError(f"File not found: {filepath}")
+
+ with open(filepath, "r", encoding="utf-8") as f:
+ return json.load(f)
+
+
+def write_json_file(
+ data: Dict[str, Any],
+ filepath: Union[str, Path],
+ indent: int = 2,
+ ensure_ascii: bool = False
+) -> None:
+ """
+ Write data to JSON file safely.
+
+ Args:
+ data: Data to write
+ filepath: Path to JSON file
+ indent: JSON indentation level
+ ensure_ascii: Whether to ensure ASCII encoding
+ """
+ filepath = Path(filepath)
+ ensure_directory(filepath.parent)
+
+ with open(filepath, "w", encoding="utf-8") as f:
+ json.dump(data, f, indent=indent, ensure_ascii=ensure_ascii)
+
+
+def get_file_size(filepath: Union[str, Path]) -> int:
+ """
+ Get file size in bytes.
+
+ Args:
+ filepath: Path to file
+
+ Returns:
+ File size in bytes
+ """
+ return Path(filepath).stat().st_size
+
+
+def format_timestamp(
+ timestamp: Optional[Union[datetime, float, int]] = None,
+ format_str: str = "%Y-%m-%d %H:%M:%S",
+ timezone_aware: bool = True
+) -> str:
+ """
+ Format timestamp to string.
+
+ Args:
+ timestamp: Timestamp (datetime, float, or int). If None, uses current time.
+ format_str: DateTime format string
+ timezone_aware: Whether to include timezone information
+
+ Returns:
+ Formatted timestamp string
+ """
+ if timestamp is None:
+ dt = datetime.now(timezone.utc if timezone_aware else None)
+ elif isinstance(timestamp, (int, float)):
+ dt = datetime.fromtimestamp(timestamp, timezone.utc if timezone_aware else None)
+ elif isinstance(timestamp, datetime):
+ dt = timestamp
+ else:
+ raise ValueError(f"Invalid timestamp type: {type(timestamp)}")
+
+ return dt.strftime(format_str)
+
+
+def parse_timestamp(
+ timestamp_str: str,
+ format_str: Optional[str] = None
+) -> datetime:
+ """
+ Parse timestamp string to datetime.
+
+ Args:
+ timestamp_str: Timestamp string
+ format_str: DateTime format string. If None, tries common formats.
+
+ Returns:
+ Parsed datetime object
+ """
+ if format_str:
+ return datetime.strptime(timestamp_str, format_str)
+
+ # Try common formats
+ formats = [
+ "%Y-%m-%d %H:%M:%S",
+ "%Y-%m-%dT%H:%M:%S",
+ "%Y-%m-%dT%H:%M:%S%z",
+ "%Y-%m-%d",
+ "%d/%m/%Y",
+ "%m/%d/%Y",
+ ]
+
+ for fmt in formats:
+ try:
+ return datetime.strptime(timestamp_str, fmt)
+ except ValueError:
+ continue
+
+ raise ValueError(f"Could not parse timestamp: {timestamp_str}")
+
+
+def merge_dicts(*dicts: Dict[str, Any], deep: bool = True) -> Dict[str, Any]:
+ """
+ Merge multiple dictionaries.
+
+ Args:
+ *dicts: Dictionaries to merge
+ deep: If True, perform deep merge for nested dictionaries
+
+ Returns:
+ Merged dictionary
+ """
+ if not dicts:
+ return {}
+
+ result = {}
+
+ for d in dicts:
+ if not isinstance(d, dict):
+ continue
+
+ for key, value in d.items():
+ if deep and key in result and isinstance(result[key], dict) and isinstance(value, dict):
+ result[key] = merge_dicts(result[key], value, deep=True)
+ else:
+ result[key] = value
+
+ return result
+
+
+def chunk_list(items: List[Any], chunk_size: int) -> List[List[Any]]:
+ """
+ Split list into chunks of specified size.
+
+ Args:
+ items: List to chunk
+ chunk_size: Size of each chunk
+
+ Returns:
+ List of chunks
+ """
+ return [items[i:i + chunk_size] for i in range(0, len(items), chunk_size)]
+
+
+def flatten_dict(
+ d: Dict[str, Any],
+ parent_key: str = "",
+ sep: str = "."
+) -> Dict[str, Any]:
+ """
+ Flatten nested dictionary.
+
+ Args:
+ d: Dictionary to flatten
+ parent_key: Parent key prefix
+ sep: Separator for nested keys
+
+ Returns:
+ Flattened dictionary
+ """
+ items = []
+
+ for k, v in d.items():
+ new_key = f"{parent_key}{sep}{k}" if parent_key else k
+
+ if isinstance(v, dict):
+ items.extend(flatten_dict(v, new_key, sep=sep).items())
+ else:
+ items.append((new_key, v))
+
+ return dict(items)
+
+
+def get_nested_value(
+ d: Dict[str, Any],
+ key_path: str,
+ default: Any = None,
+ sep: str = "."
+) -> Any:
+ """
+ Get nested dictionary value by dot-separated key path.
+
+ Args:
+ d: Dictionary
+ key_path: Dot-separated key path (e.g., "config.database.host")
+ default: Default value if key not found
+ sep: Separator for key path
+
+ Returns:
+ Value at key path or default
+ """
+ keys = key_path.split(sep)
+ value = d
+
+ for key in keys:
+ if isinstance(value, dict) and key in value:
+ value = value[key]
+ else:
+ return default
+
+ return value
+
+
+def set_nested_value(
+ d: Dict[str, Any],
+ key_path: str,
+ value: Any,
+ sep: str = "."
+) -> None:
+ """
+ Set nested dictionary value by dot-separated key path.
+
+ Args:
+ d: Dictionary to modify
+ key_path: Dot-separated key path (e.g., "config.database.host")
+ value: Value to set
+ sep: Separator for key path
+ """
+ keys = key_path.split(sep)
+
+ for key in keys[:-1]:
+ if key not in d:
+ d[key] = {}
+ d = d[key]
+
+ d[keys[-1]] = value
+
+
+def retry_on_error(
+ max_retries: int = 3,
+ delay: float = 1.0,
+ backoff_factor: float = 2.0,
+ exceptions: Tuple[Type[Exception], ...] = (Exception,)
+):
+ """
+ Decorator for retrying function on error.
+
+ Args:
+ max_retries: Maximum number of retries
+ delay: Initial delay between retries in seconds
+ backoff_factor: Backoff multiplier for delay
+ exceptions: Tuple of exception types to catch
+
+ Returns:
+ Decorator function
+ """
+ import time
+ import functools
+
+ def decorator(func):
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ current_delay = delay
+ last_exception = None
+
+ for attempt in range(max_retries + 1):
+ try:
+ return func(*args, **kwargs)
+ except exceptions as e:
+ last_exception = e
+ if attempt < max_retries:
+ time.sleep(current_delay)
+ current_delay *= backoff_factor
+ else:
+ raise
+
+ raise last_exception
+
+ return wrapper
+ return decorator
\ No newline at end of file
diff --git a/libs/semantica/utils/logging.py b/libs/semantica/utils/logging.py
index b68044ea..d6af8265 100644
--- a/libs/semantica/utils/logging.py
+++ b/libs/semantica/utils/logging.py
@@ -11,115 +11,355 @@ Key Features:
- Error logging and debugging support
"""
+import logging
+import sys
+from logging.handlers import RotatingFileHandler, TimedRotatingFileHandler
+from pathlib import Path
+from typing import Any, Dict, Optional, Union
+from datetime import datetime
-def setup_logging(config=None, **kwargs):
+from .constants import DEFAULT_CONFIG
+
+
+def setup_logging(config: Optional[Dict[str, Any]] = None, **kwargs) -> logging.Logger:
"""
Setup logging configuration for Semantica framework.
- • Configure logging levels and formats
- • Setup log output destinations
- • Configure log rotation and retention
- • Setup performance logging
- • Configure error logging and debugging
+ Configures logging levels, formats, and output destinations.
+ Supports file rotation and console output.
Args:
- config: Logging configuration dictionary
- **kwargs: Additional logging options
-
+ config: Logging configuration dictionary. If None, uses DEFAULT_CONFIG.
+ **kwargs: Additional logging options:
+ - level: Logging level (default: from config or INFO)
+ - format: Log format string
+ - file: Log file path
+ - console: Enable console output (default: True)
+ - rotation: Enable file rotation (default: True)
+ - max_bytes: Maximum file size for rotation
+ - backup_count: Number of backup files to keep
+
Returns:
- logging.Logger: Configured logger instance
+ Configured root logger instance
"""
- # TODO: Setup logging configuration
- # TODO: Configure logging levels and formats
- # TODO: Setup log output destinations
- # TODO: Configure log rotation and retention
- # TODO: Setup performance logging
- # TODO: Configure error logging and debugging
- # TODO: Return configured logger
- pass
+ # Merge config with defaults
+ if config is None:
+ config = DEFAULT_CONFIG.get("logging", {})
+
+ config = {**config, **kwargs}
+
+ # Get configuration values
+ level = config.get("level", "INFO")
+ format_str = config.get(
+ "format",
+ "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
+ )
+ log_file = config.get("file", "semantica.log")
+ console_enabled = config.get("console", True)
+ rotation_enabled = config.get("rotation", True)
+ max_bytes = config.get("max_bytes", 10485760) # 10MB
+ backup_count = config.get("backup_count", 5)
+
+ # Convert level string to logging level
+ if isinstance(level, str):
+ level = getattr(logging, level.upper(), logging.INFO)
+
+ # Configure root logger
+ root_logger = logging.getLogger("semantica")
+ root_logger.setLevel(level)
+
+ # Clear existing handlers
+ root_logger.handlers.clear()
+
+ # Create formatter
+ formatter = logging.Formatter(format_str)
+
+ # Console handler
+ if console_enabled:
+ console_handler = logging.StreamHandler(sys.stdout)
+ console_handler.setLevel(level)
+ console_handler.setFormatter(formatter)
+ root_logger.addHandler(console_handler)
+
+ # File handler with rotation
+ if log_file:
+ log_path = Path(log_file)
+ log_path.parent.mkdir(parents=True, exist_ok=True)
+
+ if rotation_enabled:
+ file_handler = RotatingFileHandler(
+ log_file,
+ maxBytes=max_bytes,
+ backupCount=backup_count,
+ encoding="utf-8"
+ )
+ else:
+ file_handler = logging.FileHandler(log_file, encoding="utf-8")
+
+ file_handler.setLevel(level)
+ file_handler.setFormatter(formatter)
+ root_logger.addHandler(file_handler)
+
+ # Prevent propagation to root logger
+ root_logger.propagate = False
+
+ return root_logger
-def get_logger(name, level=None, **options):
+def get_logger(
+ name: str,
+ level: Optional[Union[str, int]] = None,
+ **options: Any
+) -> logging.Logger:
"""
Get logger instance for specified name.
- • Create logger with specified name
- • Configure logger level if provided
- • Setup logger handlers
- • Return logger instance
+ Creates or retrieves a logger with the specified name.
+ If level is provided, sets the logger level.
Args:
- name: Logger name
- level: Logging level
- **options: Additional logger options
-
+ name: Logger name (typically __name__)
+ level: Logging level (string or logging constant)
+ **options: Additional logger options:
+ - propagate: Whether to propagate to parent logger (default: True)
+ - format: Custom format string
+
Returns:
- logging.Logger: Logger instance
+ Logger instance
"""
- # TODO: Create logger with specified name
- # TODO: Configure logger level if provided
- # TODO: Setup logger handlers
- # TODO: Return logger instance
- pass
+ logger = logging.getLogger(f"semantica.{name}")
+
+ # Set level if provided
+ if level is not None:
+ if isinstance(level, str):
+ level = getattr(logging, level.upper(), logging.INFO)
+ logger.setLevel(level)
+
+ # Configure propagation
+ if "propagate" in options:
+ logger.propagate = options["propagate"]
+
+ # Add custom handler if format specified
+ if "format" in options:
+ handler = logging.StreamHandler(sys.stdout)
+ handler.setFormatter(logging.Formatter(options["format"]))
+ logger.addHandler(handler)
+
+ return logger
-def log_performance(func_name, execution_time, **metrics):
+def log_performance(
+ func_name: str,
+ execution_time: float,
+ **metrics: Any
+) -> None:
"""
Log performance metrics for function execution.
- • Log function execution time
- • Log additional performance metrics
- • Track performance trends
- • Handle performance alerts
+ Logs function execution time and additional performance metrics.
+ Tracks performance trends and can trigger alerts.
Args:
func_name: Name of function being logged
- execution_time: Function execution time
- **metrics: Additional performance metrics
+ execution_time: Function execution time in seconds
+ **metrics: Additional performance metrics:
+ - memory_usage: Memory usage in bytes
+ - input_size: Size of input data
+ - output_size: Size of output data
+ - cache_hit: Whether cache was hit
+ - level: Logging level (default: INFO)
"""
- # TODO: Log function execution time
- # TODO: Log additional performance metrics
- # TODO: Track performance trends
- # TODO: Handle performance alerts
- pass
+ logger = get_logger("performance")
+ level = metrics.pop("level", logging.INFO)
+
+ # Build log message
+ message_parts = [f"Function: {func_name}", f"Execution Time: {execution_time:.4f}s"]
+
+ if "memory_usage" in metrics:
+ memory_mb = metrics["memory_usage"] / (1024 * 1024)
+ message_parts.append(f"Memory: {memory_mb:.2f}MB")
+
+ if "input_size" in metrics:
+ message_parts.append(f"Input Size: {metrics['input_size']}")
+
+ if "output_size" in metrics:
+ message_parts.append(f"Output Size: {metrics['output_size']}")
+
+ if "cache_hit" in metrics:
+ message_parts.append(f"Cache: {'HIT' if metrics['cache_hit'] else 'MISS'}")
+
+ message = " | ".join(message_parts)
+
+ # Log additional metrics as extra data
+ extra_metrics = {k: v for k, v in metrics.items() if k not in [
+ "memory_usage", "input_size", "output_size", "cache_hit", "level"
+ ]}
+
+ if extra_metrics:
+ logger.log(level, message, extra={"metrics": extra_metrics})
+ else:
+ logger.log(level, message)
-def log_error(error, context=None, **details):
+def log_error(
+ error: Exception,
+ context: Optional[Dict[str, Any]] = None,
+ **details: Any
+) -> None:
"""
Log error with context and details.
- • Log error information
- • Include context information
- • Add error details
- • Handle error escalation
+ Logs error information with context and details for debugging.
+ Can handle error escalation if configured.
Args:
- error: Error to log
- context: Error context
- **details: Additional error details
+ error: Error/Exception to log
+ context: Error context dictionary
+ **details: Additional error details:
+ - level: Logging level (default: ERROR)
+ - include_traceback: Include full traceback (default: True)
+ - escalate: Whether to escalate error (default: False)
"""
- # TODO: Log error information
- # TODO: Include context information
- # TODO: Add error details
- # TODO: Handle error escalation
- pass
+ logger = get_logger("error")
+ level = details.pop("level", logging.ERROR)
+ include_traceback = details.pop("include_traceback", True)
+ escalate = details.pop("escalate", False)
+
+ # Build error message
+ error_type = type(error).__name__
+ error_message = str(error)
+ message = f"{error_type}: {error_message}"
+
+ # Add context information
+ log_data = {
+ "error_type": error_type,
+ "error_message": error_message,
+ "context": context or {},
+ "details": details,
+ }
+
+ # Include traceback if requested
+ if include_traceback and hasattr(error, "__traceback__"):
+ import traceback
+ log_data["traceback"] = "".join(
+ traceback.format_exception(type(error), error, error.__traceback__)
+ )
+
+ # Add error code if available
+ if hasattr(error, "error_code"):
+ log_data["error_code"] = error.error_code
+
+ # Log error
+ logger.log(level, message, extra=log_data)
+
+ # Handle escalation
+ if escalate:
+ logger.critical(f"ESCALATED: {message}", extra=log_data)
-def log_data_quality(quality_metrics, **options):
+def log_data_quality(
+ quality_metrics: Dict[str, Any],
+ **options: Any
+) -> None:
"""
Log data quality metrics and statistics.
- • Log quality metrics
- • Track quality trends
- • Handle quality alerts
- • Generate quality reports
+ Logs quality metrics, tracks quality trends, and can generate alerts
+ when quality thresholds are not met.
Args:
- quality_metrics: Quality metrics to log
- **options: Additional logging options
+ quality_metrics: Quality metrics dictionary:
+ - score: Overall quality score
+ - completeness: Completeness score
+ - accuracy: Accuracy score
+ - consistency: Consistency score
+ - validity: Validity score
+ - timeliness: Timeliness score
+ **options: Additional logging options:
+ - level: Logging level (default: INFO)
+ - threshold: Quality threshold (default: 0.7)
+ - alert_on_threshold: Alert if below threshold (default: True)
+ - generate_report: Generate quality report (default: False)
+ """
+ logger = get_logger("quality")
+ level = options.get("level", logging.INFO)
+ threshold = options.get("threshold", 0.7)
+ alert_on_threshold = options.get("alert_on_threshold", True)
+ generate_report = options.get("generate_report", False)
+
+ # Extract quality scores
+ overall_score = quality_metrics.get("score", quality_metrics.get("overall_score"))
+
+ # Build log message
+ message_parts = [f"Quality Score: {overall_score:.3f}"]
+
+ # Add individual metrics
+ metric_names = ["completeness", "accuracy", "consistency", "validity", "timeliness"]
+ for metric in metric_names:
+ if metric in quality_metrics:
+ message_parts.append(f"{metric.capitalize()}: {quality_metrics[metric]:.3f}")
+
+ message = " | ".join(message_parts)
+
+ # Log quality metrics
+ logger.log(level, message, extra={"quality_metrics": quality_metrics})
+
+ # Alert if below threshold
+ if alert_on_threshold and overall_score is not None and overall_score < threshold:
+ logger.warning(
+ f"Quality score {overall_score:.3f} below threshold {threshold}",
+ extra={"quality_metrics": quality_metrics, "threshold": threshold}
+ )
+
+ # Generate report if requested
+ if generate_report:
+ report = {
+ "timestamp": datetime.now().isoformat(),
+ "quality_metrics": quality_metrics,
+ "threshold": threshold,
+ "status": "PASS" if (overall_score and overall_score >= threshold) else "FAIL"
+ }
+ logger.info("Quality Report", extra={"report": report})
+
+
+# Performance decorator for easy function timing
+def log_execution_time(func):
+ """
+ Decorator to log function execution time.
+
+ Usage:
+ @log_execution_time
+ def my_function():
+ ...
"""
- # TODO: Log quality metrics
- # TODO: Track quality trends
- # TODO: Handle quality alerts
- # TODO: Generate quality reports
- pass
+ import functools
+ import time
+
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ logger = get_logger("performance")
+ start_time = time.time()
+
+ try:
+ result = func(*args, **kwargs)
+ execution_time = time.time() - start_time
+
+ log_performance(
+ func.__name__,
+ execution_time,
+ **{"success": True}
+ )
+
+ return result
+ except Exception as e:
+ execution_time = time.time() - start_time
+
+ log_performance(
+ func.__name__,
+ execution_time,
+ **{"success": False, "error": str(e)}
+ )
+
+ raise
+
+ return wrapper
\ No newline at end of file
diff --git a/libs/semantica/utils/types.py b/libs/semantica/utils/types.py
index e1e03a4e..d2c9f479 100644
--- a/libs/semantica/utils/types.py
+++ b/libs/semantica/utils/types.py
@@ -3,11 +3,347 @@ Type definitions and protocols for Semantica framework.
This module contains type hints, protocols, and data structures
used throughout the Semantica framework.
+
+Key Features:
+ - Type aliases for common data types
+ - Protocol definitions for interfaces
+ - Data classes for structured data
+ - Generic types for reusable components
+ - Union types for flexible parameters
"""
-# TODO: Implement type definitions
-# - Type aliases for common data types
-# - Protocol definitions for interfaces
-# - Data classes for structured data
-# - Generic types for reusable components
-# - Union types for flexible parameters
+from typing import (
+ Any,
+ Dict,
+ List,
+ Optional,
+ Union,
+ Tuple,
+ Callable,
+ Protocol,
+ TypeVar,
+ Generic,
+ Iterator,
+ Sequence,
+)
+from dataclasses import dataclass, field
+from enum import Enum
+from datetime import datetime
+
+
+# Type Aliases
+JSONType = Union[Dict[str, Any], List[Any], str, int, float, bool, None]
+EntityDict = Dict[str, Any]
+RelationshipDict = Dict[str, Any]
+ConfigDict = Dict[str, Any]
+DataDict = Dict[str, Any]
+
+
+# Generic Type Variables
+T = TypeVar("T")
+K = TypeVar("K")
+V = TypeVar("V")
+
+
+# Entity Types
+class EntityType(str, Enum):
+ """Entity type enumeration."""
+
+ PERSON = "PERSON"
+ ORGANIZATION = "ORGANIZATION"
+ LOCATION = "LOCATION"
+ EVENT = "EVENT"
+ PRODUCT = "PRODUCT"
+ CONCEPT = "CONCEPT"
+ DATE = "DATE"
+ TIME = "TIME"
+ MONEY = "MONEY"
+ PERCENT = "PERCENT"
+ QUANTITY = "QUANTITY"
+ ORDINAL = "ORDINAL"
+ CARDINAL = "CARDINAL"
+ UNKNOWN = "UNKNOWN"
+
+
+# Data Types
+class DataType(str, Enum):
+ """Data type enumeration."""
+
+ TEXT = "text"
+ IMAGE = "image"
+ AUDIO = "audio"
+ VIDEO = "video"
+ DOCUMENT = "document"
+ STRUCTURED = "structured"
+ UNSTRUCTURED = "unstructured"
+
+
+# Processing Status
+class ProcessingStatus(str, Enum):
+ """Processing status enumeration."""
+
+ PENDING = "pending"
+ PROCESSING = "processing"
+ COMPLETED = "completed"
+ FAILED = "failed"
+ CANCELLED = "cancelled"
+ PAUSED = "paused"
+ RETRYING = "retrying"
+
+
+# Quality Levels
+class QualityLevel(str, Enum):
+ """Quality level enumeration."""
+
+ HIGH = "high"
+ MEDIUM = "medium"
+ LOW = "low"
+ POOR = "poor"
+
+
+# Relationship Types
+class RelationshipType(str, Enum):
+ """Relationship type enumeration."""
+
+ WORKS_FOR = "WORKS_FOR"
+ LOCATED_IN = "LOCATED_IN"
+ PART_OF = "PART_OF"
+ RELATED_TO = "RELATED_TO"
+ CAUSES = "CAUSES"
+ AFFECTS = "AFFECTS"
+ BEFORE = "BEFORE"
+ AFTER = "AFTER"
+ DURING = "DURING"
+ SAME_AS = "SAME_AS"
+ DIFFERENT_FROM = "DIFFERENT_FROM"
+ SIMILAR_TO = "SIMILAR_TO"
+ UNKNOWN = "UNKNOWN"
+
+
+# Data Classes
+@dataclass
+class Entity:
+ """Structured entity data."""
+
+ id: str
+ text: str
+ type: Union[str, EntityType]
+ confidence: float = 1.0
+ start: Optional[int] = None
+ end: Optional[int] = None
+ metadata: Dict[str, Any] = field(default_factory=dict)
+ relations: List[RelationshipDict] = field(default_factory=list)
+
+
+@dataclass
+class Relationship:
+ """Structured relationship data."""
+
+ id: str
+ source_id: str
+ target_id: str
+ type: Union[str, RelationshipType]
+ confidence: float = 1.0
+ metadata: Dict[str, Any] = field(default_factory=dict)
+ properties: Dict[str, Any] = field(default_factory=dict)
+
+
+@dataclass
+class ProcessingResult:
+ """Result of a processing operation."""
+
+ status: ProcessingStatus
+ data: Optional[Any] = None
+ entities: List[Entity] = field(default_factory=list)
+ relationships: List[Relationship] = field(default_factory=list)
+ metadata: Dict[str, Any] = field(default_factory=dict)
+ error: Optional[str] = None
+ execution_time: Optional[float] = None
+
+
+@dataclass
+class QualityMetrics:
+ """Data quality metrics."""
+
+ score: float
+ completeness: Optional[float] = None
+ accuracy: Optional[float] = None
+ consistency: Optional[float] = None
+ validity: Optional[float] = None
+ timeliness: Optional[float] = None
+ metadata: Dict[str, Any] = field(default_factory=dict)
+
+
+# Protocol Definitions
+class Processor(Protocol):
+ """Protocol for data processors."""
+
+ def process(self, data: Any, **options: Any) -> ProcessingResult:
+ """Process data and return result."""
+ ...
+
+
+class Validator(Protocol):
+ """Protocol for validators."""
+
+ def validate(self, data: Any, **options: Any) -> bool:
+ """Validate data and return True if valid."""
+ ...
+
+
+class Exporter(Protocol):
+ """Protocol for data exporters."""
+
+ def export(self, data: Any, destination: str, **options: Any) -> bool:
+ """Export data to destination and return True if successful."""
+ ...
+
+
+class Importer(Protocol):
+ """Protocol for data importers."""
+
+ def import_data(self, source: str, **options: Any) -> Any:
+ """Import data from source and return imported data."""
+ ...
+
+
+# Callable Type Aliases
+DataTransformer = Callable[[Any], Any]
+DataFilter = Callable[[Any], bool]
+DataValidator = Callable[[Any], Tuple[bool, Optional[str]]]
+
+
+# Generic Container Types
+class Result(Generic[T]):
+ """Generic result container."""
+
+ def __init__(self, value: Optional[T] = None, error: Optional[str] = None):
+ self.value = value
+ self.error = error
+ self.success = error is None
+
+ def __bool__(self) -> bool:
+ return self.success
+
+ def __repr__(self) -> str:
+ if self.success:
+ return f"Result(value={self.value})"
+ else:
+ return f"Result(error={self.error})"
+
+
+class BatchResult(Generic[T]):
+ """Generic batch result container."""
+
+ def __init__(self, results: List[Result[T]]):
+ self.results = results
+ self.successful = [r for r in results if r.success]
+ self.failed = [r for r in results if not r.success]
+
+ @property
+ def success_count(self) -> int:
+ return len(self.successful)
+
+ @property
+ def failure_count(self) -> int:
+ return len(self.failed)
+
+ @property
+ def total_count(self) -> int:
+ return len(self.results)
+
+ @property
+ def success_rate(self) -> float:
+ if self.total_count == 0:
+ return 0.0
+ return self.success_count / self.total_count
+
+
+# Type Guards
+def is_entity_dict(obj: Any) -> bool:
+ """Type guard to check if object is an entity dictionary."""
+ return (
+ isinstance(obj, dict) and
+ "id" in obj and
+ "text" in obj and
+ "type" in obj
+ )
+
+
+def is_relationship_dict(obj: Any) -> bool:
+ """Type guard to check if object is a relationship dictionary."""
+ return (
+ isinstance(obj, dict) and
+ "id" in obj and
+ "source_id" in obj and
+ "target_id" in obj and
+ "type" in obj
+ )
+
+
+def is_processing_result(obj: Any) -> bool:
+ """Type guard to check if object is a processing result."""
+ return (
+ isinstance(obj, dict) and
+ "status" in obj and
+ obj["status"] in [s.value for s in ProcessingStatus]
+ )
+
+
+# Conversion Functions
+def entity_to_dict(entity: Entity) -> EntityDict:
+ """Convert Entity dataclass to dictionary."""
+ return {
+ "id": entity.id,
+ "text": entity.text,
+ "type": entity.type.value if isinstance(entity.type, EntityType) else entity.type,
+ "confidence": entity.confidence,
+ "start": entity.start,
+ "end": entity.end,
+ "metadata": entity.metadata,
+ "relations": entity.relations,
+ }
+
+
+def dict_to_entity(data: EntityDict) -> Entity:
+ """Convert dictionary to Entity dataclass."""
+ return Entity(
+ id=data["id"],
+ text=data["text"],
+ type=data["type"],
+ confidence=data.get("confidence", 1.0),
+ start=data.get("start"),
+ end=data.get("end"),
+ metadata=data.get("metadata", {}),
+ relations=data.get("relations", []),
+ )
+
+
+def relationship_to_dict(relationship: Relationship) -> RelationshipDict:
+ """Convert Relationship dataclass to dictionary."""
+ return {
+ "id": relationship.id,
+ "source_id": relationship.source_id,
+ "target_id": relationship.target_id,
+ "type": (
+ relationship.type.value
+ if isinstance(relationship.type, RelationshipType)
+ else relationship.type
+ ),
+ "confidence": relationship.confidence,
+ "metadata": relationship.metadata,
+ "properties": relationship.properties,
+ }
+
+
+def dict_to_relationship(data: RelationshipDict) -> Relationship:
+ """Convert dictionary to Relationship dataclass."""
+ return Relationship(
+ id=data["id"],
+ source_id=data["source_id"],
+ target_id=data["target_id"],
+ type=data["type"],
+ confidence=data.get("confidence", 1.0),
+ metadata=data.get("metadata", {}),
+ properties=data.get("properties", {}),
+ )
\ No newline at end of file
diff --git a/libs/semantica/utils/validators.py b/libs/semantica/utils/validators.py
index 36c94843..5ac745c4 100644
--- a/libs/semantica/utils/validators.py
+++ b/libs/semantica/utils/validators.py
@@ -3,11 +3,514 @@ Validation utilities for Semantica framework.
This module provides common validation functions used across the framework
for data validation, type checking, and constraint enforcement.
+
+Key Features:
+ - Input data validation
+ - Type checking utilities
+ - Constraint validation
+ - Schema validation helpers
+ - Data quality checks
"""
-# TODO: Implement validation functions
-# - Input data validation
-# - Type checking utilities
-# - Constraint validation
-# - Schema validation helpers
-# - Data quality checks
+import re
+from typing import Any, Dict, List, Optional, Tuple, Union, Callable
+from pathlib import Path
+
+from .exceptions import ValidationError
+from .types import EntityDict, RelationshipDict, Entity, Relationship
+
+
+def validate_data(
+ data: Any,
+ schema: Optional[Dict[str, Any]] = None,
+ **constraints: Any
+) -> Tuple[bool, Optional[str]]:
+ """
+ Validate data against schema and constraints.
+
+ Args:
+ data: Data to validate
+ schema: Schema dictionary defining expected structure
+ **constraints: Additional validation constraints:
+ - required_fields: List of required field names
+ - field_types: Dictionary mapping field names to types
+ - min_length: Minimum length for strings/lists
+ - max_length: Maximum length for strings/lists
+ - min_value: Minimum value for numbers
+ - max_value: Maximum value for numbers
+ - pattern: Regex pattern for string validation
+
+ Returns:
+ Tuple of (is_valid, error_message)
+ """
+ # Schema validation
+ if schema:
+ is_valid, error = validate_schema(data, schema)
+ if not is_valid:
+ return False, error
+
+ # Type validation
+ if "field_types" in constraints:
+ is_valid, error = validate_types(data, constraints["field_types"])
+ if not is_valid:
+ return False, error
+
+ # Required fields validation
+ if isinstance(data, dict) and "required_fields" in constraints:
+ is_valid, error = validate_required_fields(data, constraints["required_fields"])
+ if not is_valid:
+ return False, error
+
+ # String constraints
+ if isinstance(data, str):
+ is_valid, error = validate_string_constraints(data, constraints)
+ if not is_valid:
+ return False, error
+
+ # Numeric constraints
+ if isinstance(data, (int, float)):
+ is_valid, error = validate_numeric_constraints(data, constraints)
+ if not is_valid:
+ return False, error
+
+ # List constraints
+ if isinstance(data, list):
+ is_valid, error = validate_list_constraints(data, constraints)
+ if not is_valid:
+ return False, error
+
+ return True, None
+
+
+def validate_config(
+ config: Dict[str, Any],
+ required_keys: Optional[List[str]] = None,
+ **options: Any
+) -> Tuple[bool, Optional[str]]:
+ """
+ Validate configuration dictionary.
+
+ Args:
+ config: Configuration dictionary
+ required_keys: List of required configuration keys
+ **options: Additional validation options:
+ - allowed_keys: List of allowed keys (raises error if others present)
+ - key_types: Dictionary mapping keys to expected types
+ - nested_validation: Validate nested dictionaries (default: True)
+
+ Returns:
+ Tuple of (is_valid, error_message)
+ """
+ if not isinstance(config, dict):
+ return False, "Configuration must be a dictionary"
+
+ # Check required keys
+ if required_keys:
+ missing_keys = [key for key in required_keys if key not in config]
+ if missing_keys:
+ return False, f"Missing required configuration keys: {', '.join(missing_keys)}"
+
+ # Check allowed keys
+ if "allowed_keys" in options:
+ allowed = set(options["allowed_keys"])
+ provided = set(config.keys())
+ invalid_keys = provided - allowed
+ if invalid_keys:
+ return False, f"Invalid configuration keys: {', '.join(invalid_keys)}"
+
+ # Check key types
+ if "key_types" in options:
+ for key, expected_type in options["key_types"].items():
+ if key in config:
+ if not isinstance(config[key], expected_type):
+ return False, (
+ f"Configuration key '{key}' must be of type "
+ f"{expected_type.__name__}, got {type(config[key]).__name__}"
+ )
+
+ # Nested validation
+ if options.get("nested_validation", True):
+ for key, value in config.items():
+ if isinstance(value, dict):
+ is_valid, error = validate_config(value, **options)
+ if not is_valid:
+ return False, f"Error in nested config '{key}': {error}"
+
+ return True, None
+
+
+def validate_schema(data: Any, schema: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
+ """
+ Validate data against JSON-like schema.
+
+ Args:
+ data: Data to validate
+ schema: Schema dictionary
+
+ Returns:
+ Tuple of (is_valid, error_message)
+ """
+ # Simple schema validation
+ if "type" in schema:
+ expected_type = schema["type"]
+ if expected_type == "string" and not isinstance(data, str):
+ return False, f"Expected string, got {type(data).__name__}"
+ elif expected_type == "integer" and not isinstance(data, int):
+ return False, f"Expected integer, got {type(data).__name__}"
+ elif expected_type == "number" and not isinstance(data, (int, float)):
+ return False, f"Expected number, got {type(data).__name__}"
+ elif expected_type == "boolean" and not isinstance(data, bool):
+ return False, f"Expected boolean, got {type(data).__name__}"
+ elif expected_type == "array" and not isinstance(data, list):
+ return False, f"Expected array, got {type(data).__name__}"
+ elif expected_type == "object" and not isinstance(data, dict):
+ return False, f"Expected object, got {type(data).__name__}"
+
+ # Properties validation for objects
+ if isinstance(data, dict) and "properties" in schema:
+ for prop_name, prop_schema in schema["properties"].items():
+ if prop_name in data:
+ is_valid, error = validate_schema(data[prop_name], prop_schema)
+ if not is_valid:
+ return False, f"Property '{prop_name}': {error}"
+
+ # Required properties
+ if isinstance(data, dict) and "required" in schema:
+ missing = [req for req in schema["required"] if req not in data]
+ if missing:
+ return False, f"Missing required properties: {', '.join(missing)}"
+
+ return True, None
+
+
+def validate_types(
+ data: Dict[str, Any],
+ field_types: Dict[str, type]
+) -> Tuple[bool, Optional[str]]:
+ """
+ Validate field types in dictionary.
+
+ Args:
+ data: Dictionary to validate
+ field_types: Dictionary mapping field names to expected types
+
+ Returns:
+ Tuple of (is_valid, error_message)
+ """
+ for field_name, expected_type in field_types.items():
+ if field_name in data:
+ value = data[field_name]
+ if not isinstance(value, expected_type):
+ return False, (
+ f"Field '{field_name}' must be of type "
+ f"{expected_type.__name__}, got {type(value).__name__}"
+ )
+
+ return True, None
+
+
+def validate_required_fields(
+ data: Dict[str, Any],
+ required_fields: List[str]
+) -> Tuple[bool, Optional[str]]:
+ """
+ Validate that all required fields are present.
+
+ Args:
+ data: Dictionary to validate
+ required_fields: List of required field names
+
+ Returns:
+ Tuple of (is_valid, error_message)
+ """
+ missing_fields = [field for field in required_fields if field not in data]
+
+ if missing_fields:
+ return False, f"Missing required fields: {', '.join(missing_fields)}"
+
+ return True, None
+
+
+def validate_string_constraints(
+ value: str,
+ constraints: Dict[str, Any]
+) -> Tuple[bool, Optional[str]]:
+ """
+ Validate string against constraints.
+
+ Args:
+ value: String to validate
+ constraints: Dictionary of constraints:
+ - min_length: Minimum length
+ - max_length: Maximum length
+ - pattern: Regex pattern
+ - allowed_values: List of allowed values
+
+ Returns:
+ Tuple of (is_valid, error_message)
+ """
+ if "min_length" in constraints:
+ if len(value) < constraints["min_length"]:
+ return False, (
+ f"String length {len(value)} is less than minimum "
+ f"{constraints['min_length']}"
+ )
+
+ if "max_length" in constraints:
+ if len(value) > constraints["max_length"]:
+ return False, (
+ f"String length {len(value)} exceeds maximum "
+ f"{constraints['max_length']}"
+ )
+
+ if "pattern" in constraints:
+ pattern = constraints["pattern"]
+ if not re.match(pattern, value):
+ return False, f"String does not match required pattern: {pattern}"
+
+ if "allowed_values" in constraints:
+ if value not in constraints["allowed_values"]:
+ return False, (
+ f"Value '{value}' is not in allowed values: "
+ f"{constraints['allowed_values']}"
+ )
+
+ return True, None
+
+
+def validate_numeric_constraints(
+ value: Union[int, float],
+ constraints: Dict[str, Any]
+) -> Tuple[bool, Optional[str]]:
+ """
+ Validate numeric value against constraints.
+
+ Args:
+ value: Numeric value to validate
+ constraints: Dictionary of constraints:
+ - min_value: Minimum value
+ - max_value: Maximum value
+ - allowed_values: List of allowed values
+
+ Returns:
+ Tuple of (is_valid, error_message)
+ """
+ if "min_value" in constraints:
+ if value < constraints["min_value"]:
+ return False, (
+ f"Value {value} is less than minimum {constraints['min_value']}"
+ )
+
+ if "max_value" in constraints:
+ if value > constraints["max_value"]:
+ return False, (
+ f"Value {value} exceeds maximum {constraints['max_value']}"
+ )
+
+ if "allowed_values" in constraints:
+ if value not in constraints["allowed_values"]:
+ return False, (
+ f"Value {value} is not in allowed values: "
+ f"{constraints['allowed_values']}"
+ )
+
+ return True, None
+
+
+def validate_list_constraints(
+ value: List[Any],
+ constraints: Dict[str, Any]
+) -> Tuple[bool, Optional[str]]:
+ """
+ Validate list against constraints.
+
+ Args:
+ value: List to validate
+ constraints: Dictionary of constraints:
+ - min_length: Minimum length
+ - max_length: Maximum length
+ - item_type: Expected type for list items
+ - unique: Whether items must be unique
+
+ Returns:
+ Tuple of (is_valid, error_message)
+ """
+ if "min_length" in constraints:
+ if len(value) < constraints["min_length"]:
+ return False, (
+ f"List length {len(value)} is less than minimum "
+ f"{constraints['min_length']}"
+ )
+
+ if "max_length" in constraints:
+ if len(value) > constraints["max_length"]:
+ return False, (
+ f"List length {len(value)} exceeds maximum "
+ f"{constraints['max_length']}"
+ )
+
+ if "item_type" in constraints:
+ expected_type = constraints["item_type"]
+ for i, item in enumerate(value):
+ if not isinstance(item, expected_type):
+ return False, (
+ f"List item at index {i} must be of type "
+ f"{expected_type.__name__}, got {type(item).__name__}"
+ )
+
+ if constraints.get("unique", False):
+ if len(value) != len(set(value)):
+ return False, "List items must be unique"
+
+ return True, None
+
+
+def validate_entity(entity: Union[Entity, EntityDict]) -> Tuple[bool, Optional[str]]:
+ """
+ Validate entity structure.
+
+ Args:
+ entity: Entity object or dictionary
+
+ Returns:
+ Tuple of (is_valid, error_message)
+ """
+ if isinstance(entity, Entity):
+ entity_dict = {
+ "id": entity.id,
+ "text": entity.text,
+ "type": entity.type,
+ }
+ else:
+ entity_dict = entity
+
+ required_fields = ["id", "text", "type"]
+ is_valid, error = validate_required_fields(entity_dict, required_fields)
+ if not is_valid:
+ return False, error
+
+ # Validate confidence if present
+ if "confidence" in entity_dict:
+ confidence = entity_dict["confidence"]
+ if not isinstance(confidence, (int, float)):
+ return False, "Confidence must be a number"
+ if not (0.0 <= confidence <= 1.0):
+ return False, "Confidence must be between 0.0 and 1.0"
+
+ return True, None
+
+
+def validate_relationship(
+ relationship: Union[Relationship, RelationshipDict]
+) -> Tuple[bool, Optional[str]]:
+ """
+ Validate relationship structure.
+
+ Args:
+ relationship: Relationship object or dictionary
+
+ Returns:
+ Tuple of (is_valid, error_message)
+ """
+ if isinstance(relationship, Relationship):
+ rel_dict = {
+ "id": relationship.id,
+ "source_id": relationship.source_id,
+ "target_id": relationship.target_id,
+ "type": relationship.type,
+ }
+ else:
+ rel_dict = relationship
+
+ required_fields = ["id", "source_id", "target_id", "type"]
+ is_valid, error = validate_required_fields(rel_dict, required_fields)
+ if not is_valid:
+ return False, error
+
+ # Validate confidence if present
+ if "confidence" in rel_dict:
+ confidence = rel_dict["confidence"]
+ if not isinstance(confidence, (int, float)):
+ return False, "Confidence must be a number"
+ if not (0.0 <= confidence <= 1.0):
+ return False, "Confidence must be between 0.0 and 1.0"
+
+ return True, None
+
+
+def validate_file_path(
+ file_path: Union[str, Path],
+ must_exist: bool = False,
+ allowed_extensions: Optional[List[str]] = None
+) -> Tuple[bool, Optional[str]]:
+ """
+ Validate file path.
+
+ Args:
+ file_path: Path to validate
+ must_exist: Whether file must exist
+ allowed_extensions: List of allowed file extensions (e.g., ['.txt', '.json'])
+
+ Returns:
+ Tuple of (is_valid, error_message)
+ """
+ path = Path(file_path)
+
+ if must_exist and not path.exists():
+ return False, f"File does not exist: {file_path}"
+
+ if allowed_extensions:
+ extension = path.suffix.lower()
+ if extension not in [ext.lower() for ext in allowed_extensions]:
+ return False, (
+ f"File extension '{extension}' not in allowed extensions: "
+ f"{allowed_extensions}"
+ )
+
+ return True, None
+
+
+def validate_url(url: str) -> Tuple[bool, Optional[str]]:
+ """
+ Validate URL format.
+
+ Args:
+ url: URL string to validate
+
+ Returns:
+ Tuple of (is_valid, error_message)
+ """
+ url_pattern = re.compile(
+ r"^https?://" # http:// or https://
+ r"(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?|" # domain...
+ r"localhost|" # localhost...
+ r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})" # ...or ip
+ r"(?::\d+)?" # optional port
+ r"(?:/?|[/?]\S+)$",
+ re.IGNORECASE
+ )
+
+ if not url_pattern.match(url):
+ return False, f"Invalid URL format: {url}"
+
+ return True, None
+
+
+def validate_email(email: str) -> Tuple[bool, Optional[str]]:
+ """
+ Validate email address format.
+
+ Args:
+ email: Email string to validate
+
+ Returns:
+ Tuple of (is_valid, error_message)
+ """
+ email_pattern = re.compile(
+ r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
+ )
+
+ if not email_pattern.match(email):
+ return False, f"Invalid email format: {email}"
+
+ return True, None
\ No newline at end of file