Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

refactor: standardize utils module with comprehensive documentation

KaifAhmad18a8487aa9355
diff --git a/semantica/utils/__init__.py b/semantica/utils/__init__.py
index 9e48e6b2..4b8558e1 100644
--- a/semantica/utils/__init__.py
+++ b/semantica/utils/__init__.py
@@ -1,14 +1,40 @@
"""
Utilities Module
-This module provides shared utilities and helper functions for the Semantica framework.
+This module provides shared utilities and helper functions for the Semantica framework,
+including logging, exception handling, data validation, helper functions, constants,
+and type definitions used throughout the framework.
-Exports:
- - Logging utilities
- - Exception handling
- - Data validation
- - Helper functions
- - Constants and types
+Key Features:
+ - Comprehensive logging utilities with structured output
+ - Custom exception hierarchy with error context
+ - Data validation and type checking
+ - Common helper functions for data manipulation
+ - Framework constants and configuration defaults
+ - Type definitions and protocols
+
+Main Classes:
+ - Logging utilities: setup_logging, get_logger, log_performance, log_error
+ - Exception classes: SemanticaError, ValidationError, ProcessingError, ConfigurationError, QualityError
+ - Validators: validate_data, validate_config, validate_entity, validate_relationship
+ - Helpers: format_data, clean_text, normalize_entities, hash_data, merge_dicts
+ - Types: Entity, Relationship, ProcessingResult, QualityMetrics
+
+Example Usage:
+ >>> from semantica.utils import setup_logging, get_logger
+ >>> logger = setup_logging(level="INFO")
+ >>> module_logger = get_logger(__name__)
+ >>>
+ >>> from semantica.utils import ValidationError, validate_entity
+ >>> entity = {"id": "e1", "text": "John Doe", "type": "PERSON"}
+ >>> is_valid, error = validate_entity(entity)
+ >>>
+ >>> from semantica.utils import clean_text, merge_dicts
+ >>> cleaned = clean_text(" Hello World ")
+ >>> merged = merge_dicts({"a": 1}, {"b": 2})
+
+Author: Semantica Contributors
+License: MIT
"""
from .logging import (
diff --git a/semantica/utils/constants.py b/semantica/utils/constants.py
index dec706b6..f235e894 100644
--- a/semantica/utils/constants.py
+++ b/semantica/utils/constants.py
@@ -1,14 +1,48 @@
"""
-Constants and Configuration
+Constants and Configuration Module
-This module provides constants and configuration values for the Semantica framework.
+This module provides constants and configuration values for the Semantica framework,
+including supported file formats, default configurations, error codes, performance
+thresholds, and framework-wide constants.
Key Features:
- - Framework constants and defaults
- - Supported formats and types
- - Configuration templates
- - Error codes and messages
- - Performance thresholds
+ - Supported file format definitions (documents, images, audio, video, RDF)
+ - Vector store and graph database backends
+ - Default configuration templates
+ - Error code definitions
+ - Performance and quality thresholds
+ - Entity and relationship type definitions
+ - Processing status and data type enumerations
+
+Main Constants:
+ - SUPPORTED_DOCUMENT_FORMATS: List of supported document formats
+ - SUPPORTED_IMAGE_FORMATS: List of supported image formats
+ - SUPPORTED_AUDIO_FORMATS: List of supported audio formats
+ - SUPPORTED_VIDEO_FORMATS: List of supported video formats
+ - SUPPORTED_RDF_FORMATS: List of supported RDF serialization formats
+ - SUPPORTED_VECTOR_STORES: List of supported vector store backends
+ - SUPPORTED_GRAPH_DBS: List of supported graph database backends
+ - DEFAULT_CONFIG: Default framework configuration
+ - ERROR_CODES: Error code mappings
+ - PERFORMANCE_THRESHOLDS: Performance limit definitions
+ - QUALITY_LEVELS: Quality score thresholds
+ - ENTITY_TYPES: Available entity type definitions
+ - RELATIONSHIP_TYPES: Available relationship type definitions
+
+Example Usage:
+ >>> from semantica.utils import SUPPORTED_DOCUMENT_FORMATS, DEFAULT_CONFIG
+ >>> if file_extension in SUPPORTED_DOCUMENT_FORMATS:
+ ... process_document(file_path)
+ >>>
+ >>> config = DEFAULT_CONFIG.copy()
+ >>> config["processing"]["batch_size"] = 200
+ >>>
+ >>> from semantica.utils import ERROR_CODES, PERFORMANCE_THRESHOLDS
+ >>> error_code = ERROR_CODES["VALIDATION_ERROR"]
+ >>> max_time = PERFORMANCE_THRESHOLDS["max_processing_time"]
+
+Author: Semantica Contributors
+License: MIT
"""
# Supported Data Formats
diff --git a/semantica/utils/exceptions.py b/semantica/utils/exceptions.py
index 20186494..3c411985 100644
--- a/semantica/utils/exceptions.py
+++ b/semantica/utils/exceptions.py
@@ -1,14 +1,42 @@
"""
-Exception Handling
+Exception Handling Module
-This module provides comprehensive exception handling for the Semantica framework.
+This module provides comprehensive exception handling for the Semantica framework,
+including a custom exception hierarchy, error context management, and exception
+handling utilities for robust error reporting and debugging.
Key Features:
- - Custom exception classes
- - Exception hierarchy and inheritance
+ - Custom exception hierarchy with base SemanticaError class
+ - Specialized exception types (ValidationError, ProcessingError, ConfigurationError, QualityError)
- Error context and debugging information
- - Exception handling utilities
- - Error reporting and logging
+ - Exception serialization and formatting
+ - Exception handling utilities with recovery support
+ - Error code management
+
+Main Classes:
+ - SemanticaError: Base exception class for all framework errors
+ - ValidationError: Exception for data validation failures
+ - ProcessingError: Exception for data processing failures
+ - ConfigurationError: Exception for configuration validation failures
+ - QualityError: Exception for data quality validation failures
+
+Example Usage:
+ >>> from semantica.utils import ValidationError, ProcessingError
+ >>> try:
+ ... if not is_valid:
+ ... raise ValidationError("Invalid data format", field="name", value=value)
+ ... except ValidationError as e:
+ ... print(f"Error: {e}, Code: {e.error_code}")
+ >>>
+ >>> from semantica.utils import handle_exception, format_exception
+ >>> try:
+ ... process_data(data)
+ ... except Exception as e:
+ ... error_info = handle_exception(e, context={"stage": "processing"})
+ ... formatted = format_exception(e, include_traceback=True)
+
+Author: Semantica Contributors
+License: MIT
"""
import traceback
diff --git a/semantica/utils/helpers.py b/semantica/utils/helpers.py
index e224fb63..226206d0 100644
--- a/semantica/utils/helpers.py
+++ b/semantica/utils/helpers.py
@@ -1,16 +1,58 @@
"""
-Helper utilities for Semantica framework.
+Helper Utilities Module
-This module contains shared utility functions used across different
-modules of the Semantica framework.
+This module contains shared utility functions used across different modules of the
+Semantica framework, providing common data manipulation, file handling, string
+processing, date/time operations, and configuration management capabilities.
Key Features:
- - Common data manipulation utilities
- - File handling helpers
- - String processing utilities
- - Date/time helpers
- - Configuration helpers
- - Error handling utilities
+ - Data formatting and serialization (JSON, YAML)
+ - Text cleaning and normalization
+ - Entity normalization and hashing
+ - File and directory operations
+ - Timestamp formatting and parsing
+ - Dictionary manipulation (merge, flatten, nested access)
+ - List chunking and batch processing
+ - Retry decorators for error handling
+
+Main Functions:
+ - format_data: Format data into JSON, YAML, or other formats
+ - clean_text: Clean and normalize text strings
+ - normalize_entities: Normalize entity dictionaries to consistent format
+ - hash_data: Generate hash for data (string, bytes, or dictionary)
+ - safe_filename: Generate safe filename from string
+ - ensure_directory: Ensure directory exists, create if needed
+ - read_json_file: Read JSON file safely
+ - write_json_file: Write data to JSON file safely
+ - format_timestamp: Format timestamp to string
+ - parse_timestamp: Parse timestamp string to datetime
+ - merge_dicts: Merge multiple dictionaries (deep merge support)
+ - chunk_list: Split list into chunks of specified size
+ - flatten_dict: Flatten nested dictionary
+ - get_nested_value: Get nested dictionary value by dot-separated path
+ - set_nested_value: Set nested dictionary value by dot-separated path
+ - retry_on_error: Decorator for retrying function on error
+
+Example Usage:
+ >>> from semantica.utils import clean_text, normalize_entities
+ >>> cleaned = clean_text(" Hello World ")
+ >>> entities = normalize_entities([{"id": "e1", "text": "John", "type": "PERSON"}])
+ >>>
+ >>> from semantica.utils import hash_data, safe_filename
+ >>> data_hash = hash_data({"key": "value"})
+ >>> safe_name = safe_filename("my file.txt")
+ >>>
+ >>> from semantica.utils import merge_dicts, get_nested_value
+ >>> merged = merge_dicts({"a": 1}, {"b": 2}, deep=True)
+ >>> value = get_nested_value(config, "database.host", default="localhost")
+ >>>
+ >>> from semantica.utils import retry_on_error
+ >>> @retry_on_error(max_retries=3, delay=1.0)
+ ... def fetch_data():
+ ... return api_call()
+
+Author: Semantica Contributors
+License: MIT
"""
import os
diff --git a/semantica/utils/logging.py b/semantica/utils/logging.py
index d6af8265..55071255 100644
--- a/semantica/utils/logging.py
+++ b/semantica/utils/logging.py
@@ -1,14 +1,47 @@
"""
-Logging Utilities
+Logging Utilities Module
-This module provides comprehensive logging utilities for the Semantica framework.
+This module provides comprehensive logging utilities for the Semantica framework,
+including structured logging, log rotation, performance metrics, error logging,
+and data quality tracking with configurable output destinations and formats.
Key Features:
- - Structured logging with different levels
- - Log formatting and output configuration
- - Log rotation and retention management
- - Performance logging and metrics
- - Error logging and debugging support
+ - Structured logging with configurable levels and formats
+ - Console and file output with rotation support
+ - Performance logging with execution time and metrics
+ - Error logging with context and traceback support
+ - Data quality metrics logging and threshold alerts
+ - Execution time decorator for automatic function timing
+
+Main Functions:
+ - setup_logging: Setup logging configuration for framework
+ - get_logger: Get logger instance for specified name
+ - log_performance: Log performance metrics for function execution
+ - log_error: Log error with context and details
+ - log_data_quality: Log data quality metrics and statistics
+ - log_execution_time: Decorator to log function execution time
+
+Example Usage:
+ >>> from semantica.utils import setup_logging, get_logger
+ >>> logger = setup_logging(level="INFO", file="app.log")
+ >>> module_logger = get_logger(__name__)
+ >>> module_logger.info("Processing started")
+ >>>
+ >>> from semantica.utils import log_performance, log_error
+ >>> log_performance("process_data", 2.5, memory_usage=1024*1024*100)
+ >>> try:
+ ... process_data()
+ ... except Exception as e:
+ ... log_error(e, context={"stage": "processing"}, include_traceback=True)
+ >>>
+ >>> from semantica.utils import log_execution_time
+ >>> @log_execution_time
+ ... def my_function():
+ ... # Function implementation
+ ... pass
+
+Author: Semantica Contributors
+License: MIT
"""
import logging
diff --git a/semantica/utils/types.py b/semantica/utils/types.py
index d2c9f479..632880e2 100644
--- a/semantica/utils/types.py
+++ b/semantica/utils/types.py
@@ -1,15 +1,56 @@
"""
-Type definitions and protocols for Semantica framework.
+Type Definitions and Protocols Module
-This module contains type hints, protocols, and data structures
-used throughout the Semantica framework.
+This module contains type hints, protocols, and data structures used throughout
+the Semantica framework, providing type safety, interface definitions, and
+structured data representations for entities, relationships, and processing results.
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
+ - Type aliases for common data types (JSONType, EntityDict, RelationshipDict)
+ - Enumeration types (EntityType, DataType, ProcessingStatus, QualityLevel, RelationshipType)
+ - Data classes for structured data (Entity, Relationship, ProcessingResult, QualityMetrics)
+ - Protocol definitions for interfaces (Processor, Validator, Exporter, Importer)
+ - Generic types for reusable components (Result, BatchResult)
+ - Type guards for runtime type checking
+ - Conversion functions between dataclasses and dictionaries
+
+Main Classes:
+ - EntityType: Entity type enumeration (PERSON, ORGANIZATION, LOCATION, etc.)
+ - DataType: Data type enumeration (TEXT, IMAGE, AUDIO, VIDEO, etc.)
+ - ProcessingStatus: Processing status enumeration (PENDING, PROCESSING, COMPLETED, etc.)
+ - QualityLevel: Quality level enumeration (HIGH, MEDIUM, LOW, POOR)
+ - RelationshipType: Relationship type enumeration (WORKS_FOR, LOCATED_IN, etc.)
+ - Entity: Structured entity data class
+ - Relationship: Structured relationship data class
+ - ProcessingResult: Result of a processing operation
+ - QualityMetrics: Data quality metrics data class
+ - Result: Generic result container with success/error handling
+ - BatchResult: Generic batch result container with success rate tracking
+
+Example Usage:
+ >>> from semantica.utils import Entity, EntityType, Relationship, RelationshipType
+ >>> entity = Entity(
+ ... id="e1",
+ ... text="John Doe",
+ ... type=EntityType.PERSON,
+ ... confidence=0.95
+ ... )
+ >>> relationship = Relationship(
+ ... id="r1",
+ ... source_id="e1",
+ ... target_id="e2",
+ ... type=RelationshipType.WORKS_FOR
+ ... )
+ >>>
+ >>> from semantica.utils import Result, BatchResult
+ >>> result = Result(value=processed_data)
+ >>> if result.success:
+ ... use_data(result.value)
+ >>> batch = BatchResult([Result(v) for v in values])
+ >>> print(f"Success rate: {batch.success_rate:.2%}")
+
+Author: Semantica Contributors
+License: MIT
"""
from typing import (
diff --git a/semantica/utils/validators.py b/semantica/utils/validators.py
index 5ac745c4..35e5915d 100644
--- a/semantica/utils/validators.py
+++ b/semantica/utils/validators.py
@@ -1,15 +1,53 @@
"""
-Validation utilities for Semantica framework.
+Validation Utilities Module
-This module provides common validation functions used across the framework
-for data validation, type checking, and constraint enforcement.
+This module provides common validation functions used across the Semantica framework
+for data validation, type checking, constraint enforcement, and schema validation,
+ensuring data quality and consistency throughout the framework.
Key Features:
- - Input data validation
- - Type checking utilities
- - Constraint validation
- - Schema validation helpers
- - Data quality checks
+ - Comprehensive data validation against schemas and constraints
+ - Type checking for dictionary fields and values
+ - Constraint validation (min/max length, value ranges, patterns)
+ - Schema validation with required fields and property validation
+ - Entity and relationship structure validation
+ - File path and URL/email format validation
+ - Configuration dictionary validation
+
+Main Functions:
+ - validate_data: Validate data against schema and constraints
+ - validate_config: Validate configuration dictionary
+ - validate_schema: Validate data against JSON-like schema
+ - validate_types: Validate field types in dictionary
+ - validate_required_fields: Validate that all required fields are present
+ - validate_string_constraints: Validate string against constraints
+ - validate_numeric_constraints: Validate numeric value against constraints
+ - validate_list_constraints: Validate list against constraints
+ - validate_entity: Validate entity structure
+ - validate_relationship: Validate relationship structure
+ - validate_file_path: Validate file path with existence and extension checks
+ - validate_url: Validate URL format
+ - validate_email: Validate email address format
+
+Example Usage:
+ >>> from semantica.utils import validate_data, validate_entity
+ >>> is_valid, error = validate_data(
+ ... {"name": "John", "age": 30},
+ ... required_fields=["name", "age"],
+ ... field_types={"name": str, "age": int}
+ ... )
+ >>>
+ >>> entity = {"id": "e1", "text": "John Doe", "type": "PERSON"}
+ >>> is_valid, error = validate_entity(entity)
+ >>> if not is_valid:
+ ... raise ValidationError(error)
+ >>>
+ >>> from semantica.utils import validate_url, validate_file_path
+ >>> is_valid, error = validate_url("https://example.com")
+ >>> is_valid, error = validate_file_path("data.json", must_exist=True)
+
+Author: Semantica Contributors
+License: MIT
"""
import re