Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat: Implement normalize module - data cleaning and normalization

KaifAhmad1748511c086c4
diff --git a/libs/semantica/kg_qa/__init__.py b/libs/semantica/kg_qa/__init__.py
deleted file mode 100644
index 251c2c4b..00000000
--- a/libs/semantica/kg_qa/__init__.py
+++ /dev/null
@@ -1,13 +0,0 @@
-"""
-KG Quality Assurance Module
-
-This module provides knowledge graph quality assessment,
-consistency checking, and quality reporting.
-"""
-
-# TODO: Implement KG quality assurance
-# - Quality score calculation
-# - Consistency checking
-# - Quality report generation
-# - Quality metrics tracking
-# - Quality improvement recommendations
diff --git a/libs/semantica/kg_qa/quality_assessor.py b/libs/semantica/kg_qa/quality_assessor.py
deleted file mode 100644
index 2ce3d355..00000000
--- a/libs/semantica/kg_qa/quality_assessor.py
+++ /dev/null
@@ -1,13 +0,0 @@
-"""
-KG Quality Assessor for Semantica framework.
-
-Assesses knowledge graph quality and generates comprehensive
-quality reports with metrics and recommendations.
-"""
-
-# TODO: Implement quality assessor
-# - Calculate overall quality scores
-# - Assess completeness and consistency
-# - Generate quality reports
-# - Track quality metrics over time
-# - Provide quality improvement suggestions
diff --git a/libs/semantica/monitoring/__init__.py b/libs/semantica/monitoring/__init__.py
deleted file mode 100644
index 4cefc123..00000000
--- a/libs/semantica/monitoring/__init__.py
+++ /dev/null
@@ -1,6 +0,0 @@
-"""
-Monitoring module for Semantica framework.
-
-This module provides monitoring, analytics, and quality assurance
-capabilities for the Semantica framework.
-"""
diff --git a/libs/semantica/monitoring/alert_manager.py b/libs/semantica/monitoring/alert_manager.py
deleted file mode 100644
index 9ae0ff21..00000000
--- a/libs/semantica/monitoring/alert_manager.py
+++ /dev/null
@@ -1,14 +0,0 @@
-"""
-Alert manager for Semantica framework.
-
-This module provides alert configuration and management
-for framework monitoring and notifications.
-"""
-
-# TODO: Implement alert management
-# - Alert configuration and management
-# - Notification and alerting systems
-# - Alert routing and escalation
-# - Performance optimization
-# - Error handling and recovery
-# - Advanced alerting features
diff --git a/libs/semantica/monitoring/analytics_dashboard.py b/libs/semantica/monitoring/analytics_dashboard.py
deleted file mode 100644
index 1bd4520a..00000000
--- a/libs/semantica/monitoring/analytics_dashboard.py
+++ /dev/null
@@ -1,14 +0,0 @@
-"""
-Analytics dashboard for Semantica framework.
-
-This module provides real-time analytics and monitoring
-for framework performance and usage.
-"""
-
-# TODO: Implement analytics dashboard
-# - Real-time analytics and monitoring
-# - Performance metrics and visualization
-# - Usage statistics and reporting
-# - Interactive dashboard interface
-# - Performance optimization
-# - Error handling and recovery
diff --git a/libs/semantica/monitoring/health_checker.py b/libs/semantica/monitoring/health_checker.py
deleted file mode 100644
index e47c7263..00000000
--- a/libs/semantica/monitoring/health_checker.py
+++ /dev/null
@@ -1,14 +0,0 @@
-"""
-Health checker for Semantica framework.
-
-This module provides health monitoring and checking
-for framework components and services.
-"""
-
-# TODO: Implement health checking
-# - Health monitoring and checking
-# - Component health validation
-# - Service availability monitoring
-# - Performance optimization
-# - Error handling and recovery
-# - Advanced health monitoring
diff --git a/libs/semantica/monitoring/metrics_collector.py b/libs/semantica/monitoring/metrics_collector.py
deleted file mode 100644
index 62338022..00000000
--- a/libs/semantica/monitoring/metrics_collector.py
+++ /dev/null
@@ -1,14 +0,0 @@
-"""
-Metrics collector for Semantica framework.
-
-This module provides metrics collection and aggregation
-for framework monitoring and analysis.
-"""
-
-# TODO: Implement metrics collection
-# - Metrics collection and aggregation
-# - Data collection and processing
-# - Metrics storage and retrieval
-# - Performance optimization
-# - Error handling and recovery
-# - Advanced metrics techniques
diff --git a/libs/semantica/monitoring/performance_monitor.py b/libs/semantica/monitoring/performance_monitor.py
deleted file mode 100644
index 292b6cc2..00000000
--- a/libs/semantica/monitoring/performance_monitor.py
+++ /dev/null
@@ -1,14 +0,0 @@
-"""
-Performance monitor for Semantica framework.
-
-This module provides performance tracking and monitoring
-for framework operations and components.
-"""
-
-# TODO: Implement performance monitoring
-# - Performance tracking and monitoring
-# - Metrics collection and analysis
-# - Performance profiling and optimization
-# - Error handling and recovery
-# - Performance optimization
-# - Advanced monitoring techniques
diff --git a/libs/semantica/monitoring/quality_assurance.py b/libs/semantica/monitoring/quality_assurance.py
deleted file mode 100644
index 1b93957d..00000000
--- a/libs/semantica/monitoring/quality_assurance.py
+++ /dev/null
@@ -1,14 +0,0 @@
-"""
-Quality assurance for Semantica framework.
-
-This module provides quality validation and testing
-for framework components and operations.
-"""
-
-# TODO: Implement quality assurance
-# - Quality validation and testing
-# - Component testing and validation
-# - Performance benchmarking
-# - Error detection and reporting
-# - Performance optimization
-# - Advanced quality techniques
diff --git a/libs/semantica/normalize/__init__.py b/libs/semantica/normalize/__init__.py
index 9168293a..41765c38 100644
--- a/libs/semantica/normalize/__init__.py
+++ b/libs/semantica/normalize/__init__.py
@@ -9,10 +9,71 @@ Exports:
- DateNormalizer: Date and time normalization
- NumberNormalizer: Number and quantity normalization
- DataCleaner: General data cleaning utilities
+ - TextCleaner: Text cleaning utilities
+ - LanguageDetector: Language detection
+ - EncodingHandler: Encoding detection and conversion
"""
-# from .text_normalizer import TextNormalizer
-# from .entity_normalizer import EntityNormalizer
-# from .date_normalizer import DateNormalizer
-# from .number_normalizer import NumberNormalizer
-# from .data_cleaner import DataCleaner
+from .text_normalizer import (
+ TextNormalizer,
+ UnicodeNormalizer,
+ WhitespaceNormalizer,
+ SpecialCharacterProcessor,
+)
+from .entity_normalizer import (
+ EntityNormalizer,
+ AliasResolver,
+ EntityDisambiguator,
+ NameVariantHandler,
+)
+from .date_normalizer import (
+ DateNormalizer,
+ TimeZoneNormalizer,
+ RelativeDateProcessor,
+ TemporalExpressionParser,
+)
+from .number_normalizer import (
+ NumberNormalizer,
+ UnitConverter,
+ CurrencyNormalizer,
+ ScientificNotationHandler,
+)
+from .data_cleaner import (
+ DataCleaner,
+ DuplicateDetector,
+ DataValidator,
+ MissingValueHandler,
+ DuplicateGroup,
+ ValidationResult,
+)
+from .text_cleaner import TextCleaner
+from .language_detector import LanguageDetector
+from .encoding_handler import EncodingHandler
+
+__all__ = [
+ "TextNormalizer",
+ "UnicodeNormalizer",
+ "WhitespaceNormalizer",
+ "SpecialCharacterProcessor",
+ "EntityNormalizer",
+ "AliasResolver",
+ "EntityDisambiguator",
+ "NameVariantHandler",
+ "DateNormalizer",
+ "TimeZoneNormalizer",
+ "RelativeDateProcessor",
+ "TemporalExpressionParser",
+ "NumberNormalizer",
+ "UnitConverter",
+ "CurrencyNormalizer",
+ "ScientificNotationHandler",
+ "DataCleaner",
+ "DuplicateDetector",
+ "DataValidator",
+ "MissingValueHandler",
+ "DuplicateGroup",
+ "ValidationResult",
+ "TextCleaner",
+ "LanguageDetector",
+ "EncodingHandler",
+]
diff --git a/libs/semantica/normalize/data_cleaner.py b/libs/semantica/normalize/data_cleaner.py
index e0eb1743..5b9678b7 100644
--- a/libs/semantica/normalize/data_cleaner.py
+++ b/libs/semantica/normalize/data_cleaner.py
@@ -17,6 +17,29 @@ Main Classes:
- MissingValueHandler: Missing value processor
"""
+from typing import Any, Dict, List, Optional, Union
+from dataclasses import dataclass, field
+from collections import defaultdict
+
+from ..utils.exceptions import ValidationError, ProcessingError
+from ..utils.logging import get_logger
+
+
+@dataclass
+class DuplicateGroup:
+ """Duplicate record group."""
+ records: List[Dict[str, Any]]
+ similarity_score: float
+ canonical_record: Optional[Dict[str, Any]] = None
+
+
+@dataclass
+class ValidationResult:
+ """Data validation result."""
+ valid: bool
+ errors: List[Dict[str, Any]] = field(default_factory=list)
+ warnings: List[Dict[str, Any]] = field(default_factory=list)
+
class DataCleaner:
"""
@@ -28,79 +51,107 @@ class DataCleaner:
• Handles missing values
• Ensures data consistency
• Supports various data types
-
- Attributes:
- • duplicate_detector: Duplicate detection engine
- • data_validator: Data validation engine
- • missing_value_handler: Missing value processor
- • quality_assessor: Data quality assessor
- • consistency_checker: Data consistency checker
-
- Methods:
- • clean_data(): Clean dataset
- • detect_duplicates(): Detect duplicate records
- • validate_data(): Validate data integrity
- • handle_missing_values(): Process missing values
"""
def __init__(self, config=None, **kwargs):
"""
Initialize data cleaner.
- • Setup cleaning rules
- • Configure duplicate detection
- • Initialize validation tools
- • Setup missing value handling
- • Configure quality assessment
+ Args:
+ config: Configuration dictionary
+ **kwargs: Additional configuration options
"""
- pass
+ self.logger = get_logger("data_cleaner")
+ self.config = config or {}
+ self.config.update(kwargs)
+
+ self.duplicate_detector = DuplicateDetector(**self.config)
+ self.data_validator = DataValidator(**self.config)
+ self.missing_value_handler = MissingValueHandler(**self.config)
- def clean_data(self, dataset, **options):
+ def clean_data(self, dataset: List[Dict[str, Any]], **options) -> List[Dict[str, Any]]:
"""
Clean dataset with various cleaning operations.
- • Apply cleaning rules
- • Remove duplicates
- • Validate data integrity
- • Handle missing values
- • Check data consistency
- • Return cleaned dataset
+ Args:
+ dataset: List of data records
+ **options: Cleaning options:
+ - remove_duplicates: Remove duplicates (default: True)
+ - validate: Validate data (default: True)
+ - handle_missing: Handle missing values (default: True)
+
+ Returns:
+ Cleaned dataset
"""
- pass
+ cleaned = list(dataset)
+
+ # Handle missing values
+ if options.get("handle_missing", True):
+ strategy = options.get("missing_strategy", "remove")
+ cleaned = self.missing_value_handler.handle_missing_values(cleaned, strategy=strategy)
+
+ # Validate data
+ if options.get("validate", True):
+ schema = options.get("schema")
+ validation = self.data_validator.validate_dataset(cleaned, schema)
+ if not validation.valid:
+ self.logger.warning(f"Validation found {len(validation.errors)} errors")
+
+ # Remove duplicates
+ if options.get("remove_duplicates", True):
+ criteria = options.get("duplicate_criteria", {})
+ duplicates = self.detect_duplicates(cleaned, **criteria)
+
+ # Remove duplicates (keep first occurrence)
+ duplicate_indices = set()
+ for group in duplicates:
+ for record in group.records[1:]: # Skip first (canonical)
+ if record in cleaned:
+ idx = cleaned.index(record)
+ duplicate_indices.add(idx)
+
+ cleaned = [r for i, r in enumerate(cleaned) if i not in duplicate_indices]
+
+ return cleaned
- def detect_duplicates(self, dataset, **criteria):
+ def detect_duplicates(self, dataset: List[Dict[str, Any]], **criteria) -> List[DuplicateGroup]:
"""
Detect duplicate records in dataset.
- • Apply duplicate detection criteria
- • Identify duplicate records
- • Calculate similarity scores
- • Return duplicate information
+ Args:
+ dataset: List of data records
+ **criteria: Duplicate detection criteria
+
+ Returns:
+ List of duplicate groups
"""
- pass
+ return self.duplicate_detector.detect_duplicates(dataset, **criteria)
- def validate_data(self, dataset, schema=None):
+ def validate_data(self, dataset: List[Dict[str, Any]], schema=None) -> ValidationResult:
"""
Validate data against schema or rules.
- • Load validation schema
- • Check data types and formats
- • Validate constraints
- • Report validation errors
- • Return validation results
+ Args:
+ dataset: List of data records
+ schema: Validation schema
+
+ Returns:
+ Validation result
"""
- pass
+ return self.data_validator.validate_dataset(dataset, schema)
- def handle_missing_values(self, dataset, **strategy):
+ def handle_missing_values(self, dataset: List[Dict[str, Any]], **strategy) -> List[Dict[str, Any]]:
"""
Handle missing values in dataset.
- • Identify missing values
- • Apply handling strategy
- • Fill or remove missing data
- • Return processed dataset
+ Args:
+ dataset: List of data records
+ **strategy: Missing value handling strategy
+
+ Returns:
+ Processed dataset
"""
- pass
+ return self.missing_value_handler.handle_missing_values(dataset, **strategy)
class DuplicateDetector:
@@ -117,45 +168,172 @@ class DuplicateDetector:
"""
Initialize duplicate detector.
- • Setup similarity algorithms
- • Configure matching criteria
- • Initialize fuzzy matching
- • Setup resolution strategies
- """
- pass
+ Args:
+ **config: Configuration options:
+ - similarity_threshold: Minimum similarity for duplicates (default: 0.8)
+ - key_fields: Fields to use for comparison
+ """
+ self.logger = get_logger("duplicate_detector")
+ self.config = config
+ self.similarity_threshold = config.get("similarity_threshold", 0.8)
+ self.key_fields = config.get("key_fields", [])
- def detect_duplicates(self, dataset, **criteria):
+ def detect_duplicates(self, dataset: List[Dict[str, Any]], **criteria) -> List[DuplicateGroup]:
"""
Detect duplicates in dataset.
- • Apply matching criteria
- • Calculate similarity scores
- • Identify duplicate groups
- • Return duplicate information
+ Args:
+ dataset: List of records
+ **criteria: Detection criteria
+
+ Returns:
+ List of duplicate groups
"""
- pass
+ threshold = criteria.get("threshold", self.similarity_threshold)
+ key_fields = criteria.get("key_fields", self.key_fields)
+
+ duplicate_groups = []
+ processed = set()
+
+ for i, record1 in enumerate(dataset):
+ if i in processed:
+ continue
+
+ group = [record1]
+
+ for j, record2 in enumerate(dataset[i+1:], start=i+1):
+ if j in processed:
+ continue
+
+ similarity = self.calculate_similarity(record1, record2, key_fields=key_fields)
+
+ if similarity >= threshold:
+ group.append(record2)
+ processed.add(j)
+
+ if len(group) > 1:
+ # Calculate average similarity
+ avg_similarity = sum(
+ self.calculate_similarity(group[0], r, key_fields=key_fields)
+ for r in group[1:]
+ ) / (len(group) - 1)
+
+ duplicate_groups.append(
+ DuplicateGroup(
+ records=group,
+ similarity_score=avg_similarity,
+ canonical_record=group[0]
+ )
+ )
+ processed.add(i)
+
+ return duplicate_groups
- def calculate_similarity(self, record1, record2, **options):
+ def calculate_similarity(self, record1: Dict[str, Any], record2: Dict[str, Any], **options) -> float:
"""
Calculate similarity between records.
- • Apply similarity algorithms
- • Handle different data types
- • Calculate composite scores
- • Return similarity score
+ Args:
+ record1: First record
+ record2: Second record
+ **options: Similarity calculation options
+
+ Returns:
+ Similarity score (0.0 to 1.0)
"""
- pass
+ key_fields = options.get("key_fields", self.key_fields)
+
+ if not key_fields:
+ # Use all common fields
+ key_fields = list(set(record1.keys()) & set(record2.keys()))
+
+ if not key_fields:
+ return 0.0
+
+ similarities = []
+
+ for field in key_fields:
+ val1 = record1.get(field)
+ val2 = record2.get(field)
+
+ if val1 is None or val2 is None:
+ continue
+
+ # Exact match
+ if val1 == val2:
+ similarities.append(1.0)
+ else:
+ # String similarity
+ if isinstance(val1, str) and isinstance(val2, str):
+ sim = self._string_similarity(val1, val2)
+ similarities.append(sim)
+ else:
+ similarities.append(0.0)
+
+ return sum(similarities) / len(similarities) if similarities else 0.0
+
+ def _string_similarity(self, s1: str, s2: str) -> float:
+ """Calculate string similarity using simple ratio."""
+ if not s1 or not s2:
+ return 0.0
+
+ if s1 == s2:
+ return 1.0
+
+ # Simple character overlap
+ s1_lower = s1.lower()
+ s2_lower = s2.lower()
+
+ if s1_lower == s2_lower:
+ return 0.95
+
+ # Character-level similarity
+ set1 = set(s1_lower)
+ set2 = set(s2_lower)
+
+ intersection = len(set1 & set2)
+ union = len(set1 | set2)
+
+ return intersection / union if union > 0 else 0.0
- def resolve_duplicates(self, duplicate_groups, **strategy):
+ def resolve_duplicates(self, duplicate_groups: List[DuplicateGroup], **strategy) -> List[Dict[str, Any]]:
"""
Resolve duplicate groups.
- • Apply resolution strategy
- • Merge or remove duplicates
- • Preserve best quality records
- • Return resolved dataset
+ Args:
+ duplicate_groups: List of duplicate groups
+ **strategy: Resolution strategy
+
+ Returns:
+ List of resolved records
"""
- pass
+ resolved = []
+ strategy_type = strategy.get("strategy", "keep_first")
+
+ for group in duplicate_groups:
+ if strategy_type == "keep_first":
+ resolved.append(group.canonical_record or group.records[0])
+ elif strategy_type == "merge":
+ merged = self._merge_records(group.records)
+ resolved.append(merged)
+ else:
+ resolved.append(group.records[0])
+
+ return resolved
+
+ def _merge_records(self, records: List[Dict[str, Any]]) -> Dict[str, Any]:
+ """Merge multiple records into one."""
+ merged = {}
+
+ for record in records:
+ for key, value in record.items():
+ if key not in merged or merged[key] is None:
+ merged[key] = value
+ elif value is not None and merged[key] != value:
+ # Keep first non-null value
+ pass
+
+ return merged
class DataValidator:
@@ -172,46 +350,119 @@ class DataValidator:
"""
Initialize data validator.
- • Setup validation rules
- • Configure type checkers
- • Initialize constraint validators
- • Setup error handling
+ Args:
+ **config: Configuration options
"""
- pass
+ self.logger = get_logger("data_validator")
+ self.config = config
- def validate_dataset(self, dataset, schema):
+ def validate_dataset(self, dataset: List[Dict[str, Any]], schema: Optional[Dict[str, Any]] = None) -> ValidationResult:
"""
Validate entire dataset.
- • Load validation schema
- • Check each record
- • Validate constraints
- • Collect validation errors
- • Return validation results
+ Args:
+ dataset: List of records
+ schema: Validation schema
+
+ Returns:
+ Validation result
"""
- pass
+ errors = []
+ warnings = []
+
+ if not dataset:
+ return ValidationResult(valid=True)
+
+ for i, record in enumerate(dataset):
+ record_validation = self.validate_record(record, schema)
+
+ for error in record_validation.errors:
+ errors.append({"record_index": i, **error})
+
+ for warning in record_validation.warnings:
+ warnings.append({"record_index": i, **warning})
+
+ return ValidationResult(
+ valid=len(errors) == 0,
+ errors=errors,
+ warnings=warnings
+ )
- def validate_record(self, record, schema):
+ def validate_record(self, record: Dict[str, Any], schema: Optional[Dict[str, Any]] = None) -> ValidationResult:
"""
Validate individual record.
- • Check record structure
- • Validate field types
- • Check constraints
- • Return validation result
+ Args:
+ record: Record to validate
+ schema: Validation schema
+
+ Returns:
+ Validation result
"""
- pass
+ errors = []
+ warnings = []
+
+ if schema:
+ # Validate against schema
+ expected_fields = schema.get("fields", {})
+
+ for field, field_schema in expected_fields.items():
+ value = record.get(field)
+
+ # Check required fields
+ if field_schema.get("required", False) and value is None:
+ errors.append({"field": field, "message": f"Required field '{field}' is missing"})
+
+ # Check type
+ expected_type = field_schema.get("type")
+ if expected_type and value is not None:
+ type_check = self.check_data_types(value, expected_type)
+ if not type_check:
+ errors.append({
+ "field": field,
+ "message": f"Field '{field}' has incorrect type, expected {expected_type}"
+ })
+
+ return ValidationResult(
+ valid=len(errors) == 0,
+ errors=errors,
+ warnings=warnings
+ )
- def check_data_types(self, data, expected_types):
+ def check_data_types(self, data: Any, expected_types: Union[type, List[type]]) -> bool:
"""
Check data types against expected types.
- • Compare actual vs expected types
- • Handle type conversions
- • Report type mismatches
- • Return type validation result
+ Args:
+ data: Data to check
+ expected_types: Expected type(s)
+
+ Returns:
+ True if type matches
"""
- pass
+ if isinstance(expected_types, type):
+ expected_types = [expected_types]
+
+ actual_type = type(data)
+
+ # Map string type names to actual types
+ type_map = {
+ "str": str,
+ "int": int,
+ "float": float,
+ "bool": bool,
+ "list": list,
+ "dict": dict,
+ }
+
+ for expected_type in expected_types:
+ if isinstance(expected_type, str):
+ expected_type = type_map.get(expected_type, str)
+
+ if isinstance(data, expected_type):
+ return True
+
+ return False
class MissingValueHandler:
@@ -228,42 +479,140 @@ class MissingValueHandler:
"""
Initialize missing value handler.
- • Setup missing value detection
- • Configure handling strategies
- • Initialize imputation methods
- • Setup removal criteria
+ Args:
+ **config: Configuration options:
+ - missing_values: List of values considered missing (default: [None, "", "N/A", "null"])
"""
- pass
+ self.logger = get_logger("missing_value_handler")
+ self.config = config
+ self.missing_values = config.get("missing_values", [None, "", "N/A", "null", "NULL"])
- def identify_missing_values(self, dataset):
+ def identify_missing_values(self, dataset: List[Dict[str, Any]]) -> Dict[str, Any]:
"""
Identify missing values in dataset.
- • Scan dataset for missing values
- • Categorize missing value types
- • Calculate missing value statistics
- • Return missing value information
+ Args:
+ dataset: List of records
+
+ Returns:
+ Missing value information
"""
- pass
+ missing_info = defaultdict(int)
+ total_records = len(dataset)
+
+ if not dataset:
+ return {"total_records": 0, "missing_counts": {}}
+
+ all_fields = set()
+ for record in dataset:
+ all_fields.update(record.keys())
+
+ for field in all_fields:
+ missing_count = 0
+ for record in dataset:
+ value = record.get(field)
+ if value in self.missing_values or value is None:
+ missing_count += 1
+ missing_info[field] = missing_count
+
+ return {
+ "total_records": total_records,
+ "missing_counts": dict(missing_info),
+ "missing_percentages": {
+ field: (count / total_records * 100) if total_records > 0 else 0
+ for field, count in missing_info.items()
+ }
+ }
- def handle_missing_values(self, dataset, strategy="remove"):
+ def handle_missing_values(self, dataset: List[Dict[str, Any]], strategy: str = "remove") -> List[Dict[str, Any]]:
"""
Handle missing values using specified strategy.
- • Apply handling strategy
- • Fill or remove missing data
- • Preserve data quality
- • Return processed dataset
- """
- pass
+ Args:
+ dataset: List of records
+ strategy: Handling strategy ('remove', 'fill', 'impute')
+
+ Returns:
+ Processed dataset
+ """
+ if strategy == "remove":
+ return self._remove_missing(dataset)
+ elif strategy == "fill":
+ return self._fill_missing(dataset)
+ elif strategy == "impute":
+ return self.impute_values(dataset)
+ else:
+ return dataset
+
+ def _remove_missing(self, dataset: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
+ """Remove records with missing values."""
+ return [
+ record for record in dataset
+ if not any(
+ value in self.missing_values or value is None
+ for value in record.values()
+ )
+ ]
- def impute_values(self, dataset, method="mean"):
+ def _fill_missing(self, dataset: List[Dict[str, Any]], fill_value: Any = "") -> List[Dict[str, Any]]:
+ """Fill missing values with default value."""
+ filled = []
+ for record in dataset:
+ filled_record = {}
+ for key, value in record.items():
+ if value in self.missing_values or value is None:
+ filled_record[key] = fill_value
+ else:
+ filled_record[key] = value
+ filled.append(filled_record)
+ return filled
+
+ def impute_values(self, dataset: List[Dict[str, Any]], method: str = "mean") -> List[Dict[str, Any]]:
"""
Impute missing values using specified method.
- • Calculate imputation values
- • Fill missing data
- • Handle different data types
- • Return imputed dataset
+ Args:
+ dataset: List of records
+ method: Imputation method ('mean', 'median', 'mode', 'zero')
+
+ Returns:
+ Imputed dataset
"""
- pass
+ if not dataset:
+ return dataset
+
+ # Collect numeric values by field
+ numeric_fields = {}
+ for record in dataset:
+ for key, value in record.items():
+ if isinstance(value, (int, float)):
+ if key not in numeric_fields:
+ numeric_fields[key] = []
+ numeric_fields[key].append(value)
+
+ # Calculate imputation values
+ imputation_values = {}
+ for field, values in numeric_fields.items():
+ if method == "mean":
+ imputation_values[field] = sum(values) / len(values) if values else 0
+ elif method == "median":
+ sorted_values = sorted(values)
+ n = len(sorted_values)
+ imputation_values[field] = sorted_values[n // 2] if n > 0 else 0
+ elif method == "zero":
+ imputation_values[field] = 0
+ else:
+ imputation_values[field] = 0
+
+ # Impute missing values
+ imputed = []
+ for record in dataset:
+ imputed_record = {}
+ for key, value in record.items():
+ if value in self.missing_values or value is None:
+ imputed_record[key] = imputation_values.get(key, "")
+ else:
+ imputed_record[key] = value
+ imputed.append(imputed_record)
+
+ return imputed
diff --git a/libs/semantica/normalize/date_normalizer.py b/libs/semantica/normalize/date_normalizer.py
index 6e755419..af6aeb9d 100644
--- a/libs/semantica/normalize/date_normalizer.py
+++ b/libs/semantica/normalize/date_normalizer.py
@@ -17,6 +17,23 @@ Main Classes:
- TemporalExpressionParser: Temporal expression parser
"""
+import re
+from datetime import datetime, timedelta, timezone
+from typing import Any, Dict, List, Optional
+
+from ..utils.exceptions import ValidationError, ProcessingError
+from ..utils.logging import get_logger
+
+# Optional imports for date parsing
+try:
+ from dateutil import parser as date_parser
+ from dateutil.relativedelta import relativedelta
+ HAS_DATEUTIL = True
+except ImportError:
+ HAS_DATEUTIL = False
+ date_parser = None
+ relativedelta = None
+
class DateNormalizer:
"""
@@ -28,80 +45,124 @@ class DateNormalizer:
• Manages relative dates and temporal expressions
• Standardizes date representations
• Supports multiple calendar systems
-
- Attributes:
- • timezone_normalizer: Time zone processing engine
- • relative_date_processor: Relative date handler
- • temporal_parser: Temporal expression parser
- • format_converter: Date format converter
- • supported_calendars: List of supported calendars
-
- Methods:
- • normalize_date(): Normalize date to standard format
- • normalize_time(): Normalize time to standard format
- • process_relative_date(): Process relative dates
- • parse_temporal_expression(): Parse temporal expressions
"""
def __init__(self, config=None, **kwargs):
"""
Initialize date normalizer.
- • Setup date format patterns
- • Configure time zone handling
- • Initialize relative date processing
- • Setup temporal expression parsing
- • Configure calendar systems
+ Args:
+ config: Configuration dictionary
+ **kwargs: Additional configuration options
"""
- pass
+ self.logger = get_logger("date_normalizer")
+ self.config = config or {}
+ self.config.update(kwargs)
+
+ self.timezone_normalizer = TimeZoneNormalizer(**self.config)
+ self.relative_date_processor = RelativeDateProcessor(**self.config)
+ self.temporal_parser = TemporalExpressionParser(**self.config)
- def normalize_date(self, date_input, **options):
+ def normalize_date(self, date_input: Any, **options) -> str:
"""
Normalize date to standard format.
- • Parse date input in various formats
- • Convert to standard date format
- • Handle time zone conversion
- • Validate date validity
- • Return normalized date
+ Args:
+ date_input: Date input (string, datetime, or other)
+ **options: Normalization options:
+ - format: Output format (default: 'ISO8601')
+ - timezone: Target timezone (default: 'UTC')
+
+ Returns:
+ Normalized date string
"""
- pass
+ if not date_input:
+ return ""
+
+ # Parse date input
+ if isinstance(date_input, str):
+ try:
+ if HAS_DATEUTIL and date_parser:
+ dt = date_parser.parse(date_input)
+ else:
+ # Fallback to basic parsing
+ dt = datetime.fromisoformat(date_input.replace('Z', '+00:00'))
+ except Exception:
+ # Try relative date processing
+ dt = self.relative_date_processor.process_relative_expression(date_input)
+ elif isinstance(date_input, datetime):
+ dt = date_input
+ else:
+ raise ValidationError(f"Unsupported date input type: {type(date_input)}")
+
+ # Normalize timezone
+ target_tz = options.get("timezone", "UTC")
+ if target_tz != "UTC":
+ dt = self.timezone_normalizer.normalize_timezone(dt, target_tz)
+ else:
+ dt = self.timezone_normalizer.convert_to_utc(dt)
+
+ # Format output
+ output_format = options.get("format", "ISO8601")
+ if output_format == "ISO8601":
+ return dt.isoformat()
+ elif output_format == "date":
+ return dt.date().isoformat()
+ else:
+ return dt.strftime(output_format)
- def normalize_time(self, time_input, **options):
+ def normalize_time(self, time_input: Any, **options) -> str:
"""
Normalize time to standard format.
- • Parse time input in various formats
- • Convert to standard time format
- • Handle time zone conversion
- • Validate time validity
- • Return normalized time
- """
- pass
+ Args:
+ time_input: Time input
+ **options: Normalization options
+
+ Returns:
+ Normalized time string
+ """
+ if isinstance(time_input, str):
+ try:
+ if HAS_DATEUTIL and date_parser:
+ dt = date_parser.parse(time_input)
+ else:
+ # Fallback parsing
+ dt = datetime.fromisoformat(time_input)
+ except Exception:
+ return ""
+ elif isinstance(time_input, datetime):
+ dt = time_input
+ else:
+ return ""
+
+ return dt.time().isoformat()
- def process_relative_date(self, relative_expression, reference_date=None):
+ def process_relative_date(self, relative_expression: str, reference_date: Optional[datetime] = None) -> datetime:
"""
Process relative date expressions.
- • Parse relative date expressions
- • Calculate absolute dates
- • Handle various relative formats
- • Use reference date if provided
- • Return calculated date
+ Args:
+ relative_expression: Relative date expression
+ reference_date: Reference date (default: now)
+
+ Returns:
+ Calculated date
"""
- pass
+ return self.relative_date_processor.process_relative_expression(relative_expression, reference_date)
- def parse_temporal_expression(self, temporal_text, **context):
+ def parse_temporal_expression(self, temporal_text: str, **context) -> Dict[str, Any]:
"""
Parse temporal expressions and references.
- • Identify temporal expressions
- • Parse date and time components
- • Handle relative and absolute references
- • Consider contextual information
- • Return parsed temporal data
+ Args:
+ temporal_text: Temporal expression text
+ **context: Context information
+
+ Returns:
+ Parsed temporal data
"""
- pass
+ return self.temporal_parser.parse_temporal_expression(temporal_text, **context)
class TimeZoneNormalizer:
@@ -119,45 +180,64 @@ class TimeZoneNormalizer:
"""
Initialize time zone normalizer.
- • Setup time zone database
- • Configure DST handling
- • Initialize conversion tools
- • Setup abbreviation mapping
+ Args:
+ **config: Configuration options
"""
- pass
+ self.logger = get_logger("timezone_normalizer")
+ self.config = config
- def normalize_timezone(self, datetime_obj, target_timezone="UTC"):
+ def normalize_timezone(self, datetime_obj: datetime, target_timezone: str = "UTC") -> datetime:
"""
Normalize datetime to target timezone.
- • Convert datetime to target timezone
- • Handle DST transitions
- • Validate timezone conversion
- • Return normalized datetime
- """
- pass
+ Args:
+ datetime_obj: Datetime object
+ target_timezone: Target timezone
+
+ Returns:
+ Normalized datetime
+ """
+ try:
+ from zoneinfo import ZoneInfo
+ target_tz = ZoneInfo(target_timezone)
+ if datetime_obj.tzinfo is None:
+ datetime_obj = datetime_obj.replace(tzinfo=timezone.utc)
+ return datetime_obj.astimezone(target_tz)
+ except Exception:
+ # Fallback if zoneinfo not available
+ return datetime_obj
- def convert_to_utc(self, datetime_obj, source_timezone=None):
+ def convert_to_utc(self, datetime_obj: datetime, source_timezone: Optional[str] = None) -> datetime:
"""
Convert datetime to UTC.
- • Identify source timezone
- • Convert to UTC
- • Handle DST considerations
- • Return UTC datetime
- """
- pass
+ Args:
+ datetime_obj: Datetime object
+ source_timezone: Source timezone (auto-detect if None)
+
+ Returns:
+ UTC datetime
+ """
+ if datetime_obj.tzinfo is None:
+ if source_timezone:
+ datetime_obj = self.normalize_timezone(datetime_obj, source_timezone)
+ else:
+ datetime_obj = datetime_obj.replace(tzinfo=timezone.utc)
+
+ return datetime_obj.astimezone(timezone.utc)
- def handle_dst_transitions(self, datetime_obj, timezone):
+ def handle_dst_transitions(self, datetime_obj: datetime, timezone_str: str) -> datetime:
"""
Handle daylight saving time transitions.
- • Check for DST transitions
- • Apply appropriate offset
- • Handle ambiguous times
- • Return adjusted datetime
+ Args:
+ datetime_obj: Datetime object
+ timezone_str: Timezone string
+
+ Returns:
+ Adjusted datetime
"""
- pass
+ return self.normalize_timezone(datetime_obj, timezone_str)
class RelativeDateProcessor:
@@ -174,46 +254,108 @@ class RelativeDateProcessor:
"""
Initialize relative date processor.
- • Setup relative date patterns
- • Configure date arithmetic
- • Initialize expression parsers
- • Setup reference date handling
+ Args:
+ **config: Configuration options
"""
- pass
+ self.logger = get_logger("relative_date_processor")
+ self.config = config
+
+ self.relative_terms = {
+ "today": 0,
+ "yesterday": -1,
+ "tomorrow": 1,
+ "now": 0,
+ }
- def process_relative_expression(self, expression, reference_date=None):
+ def process_relative_expression(self, expression: str, reference_date: Optional[datetime] = None) -> datetime:
"""
Process relative date expression.
- • Parse relative date expression
- • Calculate absolute date
- • Handle various relative terms
- • Use reference date if provided
- • Return calculated date
+ Args:
+ expression: Relative date expression
+ reference_date: Reference date (default: now)
+
+ Returns:
+ Calculated date
"""
- pass
+ if reference_date is None:
+ reference_date = datetime.now()
+
+ expression_lower = expression.lower().strip()
+
+ # Check for relative terms
+ if expression_lower in self.relative_terms:
+ days = self.relative_terms[expression_lower]
+ return reference_date + timedelta(days=days)
+
+ # Parse patterns like "3 days ago", "2 weeks from now"
+ pattern = r'(\d+)\s*(day|week|month|year)s?\s*(ago|from now|later)?'
+ match = re.search(pattern, expression_lower)
+
+ if match:
+ amount = int(match.group(1))
+ unit = match.group(2)
+ direction = match.group(3) or "ago"
+
+ if unit == "day":
+ delta = timedelta(days=amount)
+ elif unit == "week":
+ delta = timedelta(weeks=amount)
+ elif unit == "month":
+ if HAS_DATEUTIL and relativedelta:
+ delta = relativedelta(months=amount)
+ else:
+ # Approximate month as 30 days
+ delta = timedelta(days=amount * 30)
+ elif unit == "year":
+ if HAS_DATEUTIL and relativedelta:
+ delta = relativedelta(years=amount)
+ else:
+ # Approximate year as 365 days
+ delta = timedelta(days=amount * 365)
+ else:
+ delta = timedelta(days=amount)
+
+ if direction in ["ago", "before"]:
+ return reference_date - delta
+ else:
+ return reference_date + delta
+
+ # Fallback: try to parse as absolute date
+ try:
+ if HAS_DATEUTIL and date_parser:
+ return date_parser.parse(expression)
+ else:
+ # Basic ISO format parsing
+ return datetime.fromisoformat(expression.replace('Z', '+00:00'))
+ except Exception:
+ return reference_date
- def calculate_date_offset(self, expression, reference_date):
+ def calculate_date_offset(self, expression: str, reference_date: datetime) -> datetime:
"""
Calculate date offset from expression.
- • Parse offset expression
- • Calculate date difference
- • Apply offset to reference date
- • Return calculated date
+ Args:
+ expression: Offset expression
+ reference_date: Reference date
+
+ Returns:
+ Calculated date
"""
- pass
+ return self.process_relative_expression(expression, reference_date)
- def handle_relative_terms(self, term, reference_date):
+ def handle_relative_terms(self, term: str, reference_date: datetime) -> datetime:
"""
Handle specific relative terms.
- • Process relative terms (yesterday, tomorrow, etc.)
- • Calculate corresponding dates
- • Handle business day calculations
- • Return calculated date
+ Args:
+ term: Relative term
+ reference_date: Reference date
+
+ Returns:
+ Calculated date
"""
- pass
+ return self.process_relative_expression(term, reference_date)
class TemporalExpressionParser:
@@ -230,54 +372,129 @@ class TemporalExpressionParser:
"""
Initialize temporal expression parser.
- • Setup temporal expression patterns
- • Configure natural language processing
- • Initialize component extractors
- • Setup range processors
+ Args:
+ **config: Configuration options
"""
- pass
+ self.logger = get_logger("temporal_expression_parser")
+ self.config = config
- def parse_temporal_expression(self, text, **context):
+ def parse_temporal_expression(self, text: str, **context) -> Dict[str, Any]:
"""
Parse temporal expression from text.
- • Identify temporal expressions
- • Extract date and time components
- • Parse relative and absolute references
- • Consider contextual information
- • Return parsed temporal data
- """
- pass
+ Args:
+ text: Temporal expression text
+ **context: Context information
+
+ Returns:
+ Parsed temporal data
+ """
+ result = {
+ "date": None,
+ "time": None,
+ "range": None,
+ "relative": False
+ }
+
+ # Try to extract date components
+ date_components = self.extract_date_components(text)
+ if date_components:
+ result.update(date_components)
+
+ # Try to extract time components
+ time_components = self.extract_time_components(text)
+ if time_components:
+ result.update(time_components)
+
+ # Try to parse as range
+ range_info = self.process_temporal_ranges(text)
+ if range_info:
+ result["range"] = range_info
+
+ return result
- def extract_date_components(self, text):
+ def extract_date_components(self, text: str) -> Dict[str, Any]:
"""
Extract date components from text.
- • Identify year, month, day references
- • Parse date formats
- • Handle various date representations
- • Return date components
- """
- pass
+ Args:
+ text: Input text
+
+ Returns:
+ Date components
+ """
+ try:
+ if HAS_DATEUTIL and date_parser:
+ dt = date_parser.parse(text, fuzzy=True)
+ else:
+ # Basic parsing
+ dt = datetime.fromisoformat(text.replace('Z', '+00:00'))
+ return {
+ "date": dt.date().isoformat(),
+ "year": dt.year,
+ "month": dt.month,
+ "day": dt.day
+ }
+ except Exception:
+ return {}
- def extract_time_components(self, text):
+ def extract_time_components(self, text: str) -> Dict[str, Any]:
"""
Extract time components from text.
- • Identify hour, minute, second references
- • Parse time formats
- • Handle various time representations
- • Return time components
- """
- pass
+ Args:
+ text: Input text
+
+ Returns:
+ Time components
+ """
+ try:
+ if HAS_DATEUTIL and date_parser:
+ dt = date_parser.parse(text, fuzzy=True)
+ else:
+ # Basic parsing
+ dt = datetime.fromisoformat(text.replace('Z', '+00:00'))
+ return {
+ "time": dt.time().isoformat(),
+ "hour": dt.hour,
+ "minute": dt.minute,
+ "second": dt.second
+ }
+ except Exception:
+ return {}
- def process_temporal_ranges(self, text):
+ def process_temporal_ranges(self, text: str) -> Optional[Dict[str, Any]]:
"""
Process temporal ranges and periods.
- • Identify range expressions
- • Parse start and end dates
- • Handle duration expressions
- • Return range information
- """
- pass
+ Args:
+ text: Input text
+
+ Returns:
+ Range information or None
+ """
+ # Look for range patterns like "from X to Y", "between X and Y"
+ range_patterns = [
+ r'from\s+(.+?)\s+to\s+(.+?)',
+ r'between\s+(.+?)\s+and\s+(.+?)',
+ ]
+
+ for pattern in range_patterns:
+ match = re.search(pattern, text, re.IGNORECASE)
+ if match:
+ try:
+ if HAS_DATEUTIL and date_parser:
+ start = date_parser.parse(match.group(1))
+ end = date_parser.parse(match.group(2))
+ else:
+ # Basic parsing
+ start = datetime.fromisoformat(match.group(1).replace('Z', '+00:00'))
+ end = datetime.fromisoformat(match.group(2).replace('Z', '+00:00'))
+ return {
+ "start": start.isoformat(),
+ "end": end.isoformat()
+ }
+ except Exception:
+ continue
+
+ return None
diff --git a/libs/semantica/normalize/entity_normalizer.py b/libs/semantica/normalize/entity_normalizer.py
index b804922b..e85c4b97 100644
--- a/libs/semantica/normalize/entity_normalizer.py
+++ b/libs/semantica/normalize/entity_normalizer.py
@@ -17,6 +17,12 @@ Main Classes:
- NameVariantHandler: Name variant processing
"""
+import re
+from typing import Any, Dict, List, Optional
+
+from ..utils.exceptions import ValidationError, ProcessingError
+from ..utils.logging import get_logger
+
class EntityNormalizer:
"""
@@ -28,80 +34,100 @@ class EntityNormalizer:
• Standardizes entity formats
• Links entities to canonical forms
• Supports multiple entity types
-
- Attributes:
- • alias_resolver: Entity alias resolution engine
- • disambiguator: Entity disambiguation engine
- • variant_handler: Name variant processor
- • entity_linker: Entity linking system
- • supported_entity_types: List of supported types
-
- Methods:
- • normalize_entity(): Normalize entity name
- • resolve_aliases(): Resolve entity aliases
- • disambiguate_entity(): Disambiguate entity
- • link_entities(): Link entities to canonical forms
"""
def __init__(self, config=None, **kwargs):
"""
Initialize entity normalizer.
- • Setup entity normalization rules
- • Configure alias resolution
- • Initialize disambiguation engine
- • Setup entity linking
- • Configure variant handling
+ Args:
+ config: Configuration dictionary
+ **kwargs: Additional configuration options
"""
- pass
+ self.logger = get_logger("entity_normalizer")
+ self.config = config or {}
+ self.config.update(kwargs)
+
+ self.alias_resolver = AliasResolver(**self.config)
+ self.disambiguator = EntityDisambiguator(**self.config)
+ self.variant_handler = NameVariantHandler(**self.config)
- def normalize_entity(self, entity_name, entity_type=None, **options):
+ def normalize_entity(self, entity_name: str, entity_type: Optional[str] = None, **options) -> str:
"""
Normalize entity name to standard form.
- • Clean and standardize entity name
- • Apply entity-type specific rules
- • Handle name variations and formats
- • Resolve common abbreviations
- • Return normalized entity
+ Args:
+ entity_name: Entity name to normalize
+ entity_type: Entity type (optional)
+ **options: Normalization options
+
+ Returns:
+ Normalized entity name
"""
- pass
+ if not entity_name:
+ return ""
+
+ normalized = entity_name.strip()
+
+ # Clean and standardize
+ normalized = re.sub(r'\s+', ' ', normalized)
+ normalized = normalized.title() if entity_type == "Person" else normalized
+
+ # Resolve aliases
+ if options.get("resolve_aliases", True):
+ resolved = self.alias_resolver.resolve_aliases(normalized, entity_type=entity_type)
+ if resolved:
+ normalized = resolved
+
+ # Handle name variants
+ normalized = self.variant_handler.normalize_name_format(normalized, format_type="standard")
+
+ return normalized
- def resolve_aliases(self, entity_name, **context):
+ def resolve_aliases(self, entity_name: str, **context) -> Optional[str]:
"""
Resolve entity aliases and variants.
- • Identify entity aliases
- • Map variants to canonical form
- • Handle different name formats
- • Consider contextual information
- • Return alias resolution results
+ Args:
+ entity_name: Entity name
+ **context: Context information
+
+ Returns:
+ Resolved canonical form or None
"""
- pass
+ return self.alias_resolver.resolve_aliases(entity_name, **context)
- def disambiguate_entity(self, entity_name, **context):
+ def disambiguate_entity(self, entity_name: str, **context) -> Dict[str, Any]:
"""
Disambiguate entity when multiple candidates exist.
- • Identify potential entity candidates
- • Analyze contextual information
- • Apply disambiguation rules
- • Select best candidate
- • Return disambiguation result
+ Args:
+ entity_name: Entity name
+ **context: Context information
+
+ Returns:
+ Disambiguation result
"""
- pass
+ return self.disambiguator.disambiguate(entity_name, **context)
- def link_entities(self, entities, **options):
+ def link_entities(self, entities: List[str], **options) -> Dict[str, str]:
"""
Link entities to canonical forms.
- • Identify canonical entity forms
- • Link variants to canonical forms
- • Build entity relationship graph
- • Handle entity conflicts
- • Return entity linking results
+ Args:
+ entities: List of entity names
+ **options: Linking options
+
+ Returns:
+ Dictionary mapping entities to canonical forms
"""
- pass
+ linked = {}
+
+ for entity in entities:
+ canonical = self.normalize_entity(entity, **options)
+ linked[entity] = canonical
+
+ return linked
class AliasResolver:
@@ -118,46 +144,63 @@ class AliasResolver:
"""
Initialize alias resolver.
- • Setup alias mapping database
- • Configure resolution rules
- • Initialize cultural processors
- • Setup linguistic handlers
+ Args:
+ **config: Configuration options
"""
- pass
+ self.logger = get_logger("alias_resolver")
+ self.config = config
+ self.alias_map = config.get("alias_map", {})
- def resolve_aliases(self, entity_name, **context):
+ def resolve_aliases(self, entity_name: str, **context) -> Optional[str]:
"""
Resolve entity aliases to canonical form.
- • Look up entity in alias database
- • Apply resolution rules
- • Consider contextual information
- • Handle multiple candidates
- • Return resolved entity
+ Args:
+ entity_name: Entity name
+ **context: Context information
+
+ Returns:
+ Resolved canonical form or None
"""
- pass
+ # Check alias map
+ entity_lower = entity_name.lower()
+
+ if entity_lower in self.alias_map:
+ return self.alias_map[entity_lower]
+
+ # Check for common aliases
+ for alias, canonical in self.alias_map.items():
+ if alias.lower() == entity_lower:
+ return canonical
+
+ return None
- def map_variants(self, entity_name, entity_type):
+ def map_variants(self, entity_name: str, entity_type: str) -> str:
"""
Map entity name variants.
- • Identify name variations
- • Map to canonical form
- • Handle different formats
- • Return variant mapping
+ Args:
+ entity_name: Entity name
+ entity_type: Entity type
+
+ Returns:
+ Mapped variant
"""
- pass
+ # Simple variant mapping
+ return entity_name
- def handle_cultural_variations(self, entity_name, culture=None):
+ def handle_cultural_variations(self, entity_name: str, culture: Optional[str] = None) -> str:
"""
Handle cultural and linguistic variations.
- • Apply cultural naming rules
- • Handle linguistic variations
- • Process cultural conventions
- • Return culturally appropriate form
+ Args:
+ entity_name: Entity name
+ culture: Culture identifier
+
+ Returns:
+ Culturally appropriate form
"""
- pass
+ return entity_name
class EntityDisambiguator:
@@ -174,46 +217,64 @@ class EntityDisambiguator:
"""
Initialize entity disambiguator.
- • Setup disambiguation models
- • Configure context analysis
- • Initialize classification tools
- • Setup confidence scoring
+ Args:
+ **config: Configuration options
"""
- pass
+ self.logger = get_logger("entity_disambiguator")
+ self.config = config
- def disambiguate(self, entity_name, **context):
+ def disambiguate(self, entity_name: str, **context) -> Dict[str, Any]:
"""
Disambiguate entity using context.
- • Analyze contextual information
- • Apply disambiguation models
- • Calculate confidence scores
- • Select best candidate
- • Return disambiguation result
+ Args:
+ entity_name: Entity name
+ **context: Context information
+
+ Returns:
+ Disambiguation result
"""
- pass
+ entity_type = context.get("entity_type")
+ text_context = context.get("context", "")
+
+ return {
+ "entity_name": entity_name,
+ "entity_type": entity_type,
+ "confidence": 0.8,
+ "candidates": [entity_name]
+ }
- def classify_entity_type(self, entity_name, **context):
+ def classify_entity_type(self, entity_name: str, **context) -> str:
"""
Classify entity type for disambiguation.
- • Analyze entity characteristics
- • Apply type classification models
- • Consider contextual clues
- • Return entity type classification
- """
- pass
+ Args:
+ entity_name: Entity name
+ **context: Context information
+
+ Returns:
+ Entity type
+ """
+ # Simple heuristic-based classification
+ if entity_name[0].isupper() and ' ' in entity_name:
+ return "Person"
+ elif entity_name[0].isupper():
+ return "Organization"
+ else:
+ return "Entity"
- def calculate_confidence(self, candidates, **context):
+ def calculate_confidence(self, candidates: List[str], **context) -> Dict[str, float]:
"""
Calculate confidence scores for candidates.
- • Analyze candidate characteristics
- • Apply confidence models
- • Consider contextual factors
- • Return confidence scores
+ Args:
+ candidates: List of candidate entities
+ **context: Context information
+
+ Returns:
+ Dictionary of confidence scores
"""
- pass
+ return {candidate: 0.8 for candidate in candidates}
class NameVariantHandler:
@@ -230,43 +291,79 @@ class NameVariantHandler:
"""
Initialize name variant handler.
- • Setup variant processing rules
- • Configure format handlers
- • Initialize title processors
- • Setup order normalization
+ Args:
+ **config: Configuration options
"""
- pass
+ self.logger = get_logger("name_variant_handler")
+ self.config = config
+ self.titles = {"Mr.", "Mrs.", "Ms.", "Dr.", "Prof.", "Sir", "Madam"}
- def process_variants(self, entity_name, **options):
+ def process_variants(self, entity_name: str, **options) -> List[str]:
"""
Process entity name variants.
- • Identify name variations
- • Normalize name format
- • Handle different orderings
- • Process titles and honorifics
- • Return processed variants
+ Args:
+ entity_name: Entity name
+ **options: Processing options
+
+ Returns:
+ List of variants
"""
- pass
+ variants = [entity_name]
+
+ # Generate common variants
+ normalized = self.normalize_name_format(entity_name, "standard")
+ if normalized != entity_name:
+ variants.append(normalized)
+
+ return variants
- def normalize_name_format(self, entity_name, format_type="standard"):
+ def normalize_name_format(self, entity_name: str, format_type: str = "standard") -> str:
"""
Normalize name format.
- • Apply format-specific rules
- • Standardize name structure
- • Handle different conventions
- • Return formatted name
+ Args:
+ entity_name: Entity name
+ format_type: Format type ('standard', 'title', 'lower')
+
+ Returns:
+ Formatted name
"""
- pass
+ # Remove titles
+ name = entity_name
+ for title in self.titles:
+ name = name.replace(title + " ", "").replace(title, "")
+
+ name = name.strip()
+
+ if format_type == "standard":
+ # Title case for names
+ parts = name.split()
+ name = " ".join(part.capitalize() for part in parts)
+ elif format_type == "title":
+ name = name.title()
+ elif format_type == "lower":
+ name = name.lower()
+
+ return name
- def handle_titles_and_honorifics(self, entity_name):
+ def handle_titles_and_honorifics(self, entity_name: str) -> Dict[str, Any]:
"""
Handle titles and honorifics in names.
- • Identify titles and honorifics
- • Normalize title usage
- • Handle cultural variations
- • Return processed name
+ Args:
+ entity_name: Entity name
+
+ Returns:
+ Dictionary with name and title
"""
- pass
+ title = None
+ name = entity_name
+
+ for t in self.titles:
+ if entity_name.startswith(t):
+ title = t
+ name = entity_name.replace(t, "").strip()
+ break
+
+ return {"name": name, "title": title}
diff --git a/libs/semantica/normalize/number_normalizer.py b/libs/semantica/normalize/number_normalizer.py
index 068191b8..66f6cf87 100644
--- a/libs/semantica/normalize/number_normalizer.py
+++ b/libs/semantica/normalize/number_normalizer.py
@@ -17,6 +17,12 @@ Main Classes:
- ScientificNotationHandler: Scientific notation processor
"""
+import re
+from typing import Any, Dict, List, Optional, Union
+
+from ..utils.exceptions import ValidationError, ProcessingError
+from ..utils.logging import get_logger
+
class NumberNormalizer:
"""
@@ -28,78 +34,125 @@ class NumberNormalizer:
• Manages currency and percentage values
• Standardizes numerical expressions
• Supports multiple number systems
-
- Attributes:
- • unit_converter: Unit conversion engine
- • currency_normalizer: Currency processor
- • scientific_handler: Scientific notation processor
- • format_converter: Number format converter
- • supported_units: List of supported units
-
- Methods:
- • normalize_number(): Normalize number to standard format
- • normalize_quantity(): Normalize quantity with units
- • convert_units(): Convert between units
- • process_currency(): Process currency values
"""
def __init__(self, config=None, **kwargs):
"""
Initialize number normalizer.
- • Setup number format patterns
- • Configure unit conversion
- • Initialize currency handling
- • Setup scientific notation processing
- • Configure number system support
+ Args:
+ config: Configuration dictionary
+ **kwargs: Additional configuration options
"""
- pass
+ self.logger = get_logger("number_normalizer")
+ self.config = config or {}
+ self.config.update(kwargs)
+
+ self.unit_converter = UnitConverter(**self.config)
+ self.currency_normalizer = CurrencyNormalizer(**self.config)
+ self.scientific_handler = ScientificNotationHandler(**self.config)
- def normalize_number(self, number_input, **options):
+ def normalize_number(self, number_input: Union[str, int, float], **options) -> Union[int, float]:
"""
Normalize number to standard format.
- • Parse number in various formats
- • Convert to standard numerical format
- • Handle different number systems
- • Validate number validity
- • Return normalized number
+ Args:
+ number_input: Number input (string, int, or float)
+ **options: Normalization options
+
+ Returns:
+ Normalized number
"""
- pass
+ if isinstance(number_input, (int, float)):
+ return number_input
+
+ if not isinstance(number_input, str):
+ raise ValidationError(f"Unsupported number input type: {type(number_input)}")
+
+ # Remove formatting characters
+ cleaned = number_input.replace(',', '').replace(' ', '').strip()
+
+ # Handle percentages
+ if '%' in cleaned:
+ cleaned = cleaned.replace('%', '')
+ value = float(cleaned) / 100
+ return value
+
+ # Handle scientific notation
+ if 'e' in cleaned.lower() or 'E' in cleaned:
+ parsed = self.scientific_handler.parse_scientific_notation(cleaned)
+ return parsed
+
+ # Parse as float or int
+ try:
+ if '.' in cleaned:
+ return float(cleaned)
+ else:
+ return int(cleaned)
+ except ValueError:
+ raise ValidationError(f"Unable to parse number: {number_input}")
- def normalize_quantity(self, quantity_input, **options):
+ def normalize_quantity(self, quantity_input: str, **options) -> Dict[str, Any]:
"""
Normalize quantity with units.
- • Parse quantity and unit
- • Normalize unit to standard form
- • Convert to base units if needed
- • Validate quantity validity
- • Return normalized quantity
+ Args:
+ quantity_input: Quantity string (e.g., "5 kg", "10 meters")
+ **options: Normalization options
+
+ Returns:
+ Normalized quantity dictionary
"""
- pass
+ # Parse quantity and unit
+ pattern = r'([\d.,\s]+)\s*([a-zA-Z]+)'
+ match = re.search(pattern, quantity_input)
+
+ if match:
+ value_str = match.group(1).replace(',', '').replace(' ', '')
+ unit = match.group(2).lower()
+
+ try:
+ value = float(value_str)
+
+ # Normalize unit
+ normalized_unit = self.unit_converter.normalize_unit(unit)
+
+ return {
+ "value": value,
+ "unit": normalized_unit,
+ "original": quantity_input
+ }
+ except ValueError:
+ raise ValidationError(f"Unable to parse quantity: {quantity_input}")
+ else:
+ raise ValidationError(f"Invalid quantity format: {quantity_input}")
- def convert_units(self, value, from_unit, to_unit):
+ def convert_units(self, value: float, from_unit: str, to_unit: str) -> float:
"""
Convert value between units.
- • Identify unit types
- • Apply conversion factors
- • Handle unit compatibility
- • Return converted value
+ Args:
+ value: Value to convert
+ from_unit: Source unit
+ to_unit: Target unit
+
+ Returns:
+ Converted value
"""
- pass
+ return self.unit_converter.convert_units(value, from_unit, to_unit)
- def process_currency(self, currency_input, **options):
+ def process_currency(self, currency_input: str, **options) -> Dict[str, Any]:
"""
Process currency values.
- • Parse currency amount and code
- • Normalize currency format
- • Handle currency conversion
- • Return normalized currency
+ Args:
+ currency_input: Currency string (e.g., "$100", "100 USD")
+ **options: Processing options
+
+ Returns:
+ Normalized currency dictionary
"""
- pass
+ return self.currency_normalizer.normalize_currency(currency_input, **options)
class UnitConverter:
@@ -117,43 +170,151 @@ class UnitConverter:
"""
Initialize unit converter.
- • Setup unit conversion database
- • Configure conversion factors
- • Initialize unit validators
- • Setup compound unit handlers
+ Args:
+ **config: Configuration options
"""
- pass
+ self.logger = get_logger("unit_converter")
+ self.config = config
+
+ # Unit conversion factors (to base unit)
+ self.conversion_factors = {
+ # Length
+ "meter": 1.0, "meters": 1.0, "m": 1.0,
+ "kilometer": 1000.0, "kilometers": 1000.0, "km": 1000.0,
+ "centimeter": 0.01, "centimeters": 0.01, "cm": 0.01,
+ "millimeter": 0.001, "millimeters": 0.001, "mm": 0.001,
+ "inch": 0.0254, "inches": 0.0254, "in": 0.0254,
+ "foot": 0.3048, "feet": 0.3048, "ft": 0.3048,
+ "yard": 0.9144, "yards": 0.9144, "yd": 0.9144,
+ "mile": 1609.34, "miles": 1609.34, "mi": 1609.34,
+
+ # Weight
+ "kilogram": 1.0, "kilograms": 1.0, "kg": 1.0,
+ "gram": 0.001, "grams": 0.001, "g": 0.001,
+ "pound": 0.453592, "pounds": 0.453592, "lb": 0.453592,
+ "ounce": 0.0283495, "ounces": 0.0283495, "oz": 0.0283495,
+
+ # Volume
+ "liter": 1.0, "liters": 1.0, "l": 1.0,
+ "milliliter": 0.001, "milliliters": 0.001, "ml": 0.001,
+ "gallon": 3.78541, "gallons": 3.78541, "gal": 3.78541,
+ }
+
+ # Unit categories
+ self.unit_categories = {
+ "length": ["meter", "kilometer", "centimeter", "millimeter", "inch", "foot", "yard", "mile"],
+ "weight": ["kilogram", "gram", "pound", "ounce"],
+ "volume": ["liter", "milliliter", "gallon"],
+ }
- def convert_units(self, value, from_unit, to_unit):
+ def convert_units(self, value: float, from_unit: str, to_unit: str) -> float:
"""
Convert value between units.
- • Look up conversion factor
- • Apply conversion calculation
- • Handle unit compatibility
- • Return converted value
+ Args:
+ value: Value to convert
+ from_unit: Source unit
+ to_unit: Target unit
+
+ Returns:
+ Converted value
"""
- pass
+ from_unit = from_unit.lower()
+ to_unit = to_unit.lower()
+
+ # Validate units
+ if not self.validate_units(from_unit, to_unit):
+ raise ValidationError(f"Cannot convert from {from_unit} to {to_unit}")
+
+ # Get conversion factors
+ from_factor = self.get_conversion_factor(from_unit, "base")
+ to_factor = self.get_conversion_factor(to_unit, "base")
+
+ # Convert to base unit, then to target unit
+ base_value = value * from_factor
+ converted_value = base_value / to_factor
+
+ return converted_value
- def validate_units(self, from_unit, to_unit):
+ def validate_units(self, from_unit: str, to_unit: str) -> bool:
"""
Validate unit conversion compatibility.
- • Check unit compatibility
- • Validate unit types
- • Return validation result
+ Args:
+ from_unit: Source unit
+ to_unit: Target unit
+
+ Returns:
+ True if units are compatible
"""
- pass
+ from_unit = from_unit.lower()
+ to_unit = to_unit.lower()
+
+ # Check if both units exist
+ if from_unit not in self.conversion_factors or to_unit not in self.conversion_factors:
+ return False
+
+ # Check if units are in same category
+ from_category = None
+ to_category = None
+
+ for category, units in self.unit_categories.items():
+ if from_unit in units:
+ from_category = category
+ if to_unit in units:
+ to_category = category
+
+ return from_category == to_category
- def get_conversion_factor(self, from_unit, to_unit):
+ def get_conversion_factor(self, from_unit: str, to_unit: str) -> float:
"""
Get conversion factor between units.
- • Look up conversion factor
- • Handle compound units
- • Return conversion factor
+ Args:
+ from_unit: Source unit
+ to_unit: Target unit
+
+ Returns:
+ Conversion factor
"""
- pass
+ from_unit = from_unit.lower()
+
+ if to_unit == "base":
+ return self.conversion_factors.get(from_unit, 1.0)
+
+ to_unit = to_unit.lower()
+ from_factor = self.conversion_factors.get(from_unit, 1.0)
+ to_factor = self.conversion_factors.get(to_unit, 1.0)
+
+ return from_factor / to_factor
+
+ def normalize_unit(self, unit: str) -> str:
+ """
+ Normalize unit name to standard form.
+
+ Args:
+ unit: Unit name
+
+ Returns:
+ Normalized unit name
+ """
+ unit_lower = unit.lower()
+
+ # Map to standard unit
+ unit_map = {
+ "m": "meter",
+ "km": "kilometer",
+ "cm": "centimeter",
+ "mm": "millimeter",
+ "kg": "kilogram",
+ "g": "gram",
+ "lb": "pound",
+ "oz": "ounce",
+ "l": "liter",
+ "ml": "milliliter",
+ }
+
+ return unit_map.get(unit_lower, unit_lower)
class CurrencyNormalizer:
@@ -171,44 +332,115 @@ class CurrencyNormalizer:
"""
Initialize currency normalizer.
- • Setup currency code mapping
- • Configure exchange rate handling
- • Initialize symbol processors
- • Setup conversion tools
+ Args:
+ **config: Configuration options
"""
- pass
+ self.logger = get_logger("currency_normalizer")
+ self.config = config
+
+ # Currency symbols and codes
+ self.currency_symbols = {
+ "$": "USD",
+ "€": "EUR",
+ "£": "GBP",
+ "¥": "JPY",
+ "₹": "INR",
+ "₽": "RUB",
+ "₩": "KRW",
+ "₪": "ILS",
+ "₦": "NGN",
+ "₨": "PKR",
+ }
+
+ self.currency_codes = ["USD", "EUR", "GBP", "JPY", "CNY", "INR", "AUD", "CAD", "CHF", "SEK", "NOK", "DKK"]
- def normalize_currency(self, currency_input, **options):
+ def normalize_currency(self, currency_input: str, **options) -> Dict[str, Any]:
"""
Normalize currency value and code.
- • Parse currency amount and code
- • Normalize currency format
- • Validate currency code
- • Return normalized currency
+ Args:
+ currency_input: Currency string
+ **options: Normalization options
+
+ Returns:
+ Normalized currency dictionary
"""
- pass
+ # Extract currency symbol or code
+ currency_code = None
+ amount = None
+
+ # Check for currency symbol
+ for symbol, code in self.currency_symbols.items():
+ if symbol in currency_input:
+ currency_code = code
+ # Remove symbol and extract amount
+ amount_str = currency_input.replace(symbol, "").strip()
+ amount_str = amount_str.replace(',', '').replace(' ', '')
+ try:
+ amount = float(amount_str)
+ except ValueError:
+ pass
+ break
+
+ # Check for currency code
+ if not currency_code:
+ for code in self.currency_codes:
+ if code in currency_input.upper():
+ currency_code = code
+ amount_str = currency_input.replace(code, "").replace(code.lower(), "").strip()
+ amount_str = amount_str.replace(',', '').replace(' ', '')
+ try:
+ amount = float(amount_str)
+ except ValueError:
+ pass
+ break
+
+ # Extract amount if not found
+ if amount is None:
+ amount_str = re.sub(r'[^\d.,]', '', currency_input)
+ amount_str = amount_str.replace(',', '').replace(' ', '')
+ try:
+ amount = float(amount_str)
+ except ValueError:
+ amount = None
+
+ # Default to USD if no currency found
+ if not currency_code:
+ currency_code = options.get("default_currency", "USD")
+
+ return {
+ "amount": amount,
+ "currency": currency_code,
+ "original": currency_input
+ }
- def convert_currency(self, amount, from_currency, to_currency):
+ def convert_currency(self, amount: float, from_currency: str, to_currency: str) -> float:
"""
Convert currency between different currencies.
- • Get exchange rate
- • Apply conversion calculation
- • Handle rate updates
- • Return converted amount
+ Args:
+ amount: Amount to convert
+ from_currency: Source currency
+ to_currency: Target currency
+
+ Returns:
+ Converted amount
"""
- pass
+ # Note: This is a placeholder. In production, you'd fetch exchange rates
+ self.logger.warning("Currency conversion requires exchange rate API")
+ return amount
- def validate_currency_code(self, currency_code):
+ def validate_currency_code(self, currency_code: str) -> bool:
"""
Validate currency code.
- • Check currency code format
- • Validate against known currencies
- • Return validation result
+ Args:
+ currency_code: Currency code to validate
+
+ Returns:
+ True if valid
"""
- pass
+ return currency_code.upper() in self.currency_codes
class ScientificNotationHandler:
@@ -225,40 +457,68 @@ class ScientificNotationHandler:
"""
Initialize scientific notation handler.
- • Setup notation patterns
- • Configure precision handling
- • Initialize format converters
- • Setup validation tools
+ Args:
+ **config: Configuration options
"""
- pass
+ self.logger = get_logger("scientific_notation_handler")
+ self.config = config
- def parse_scientific_notation(self, number_string):
+ def parse_scientific_notation(self, number_string: str) -> float:
"""
Parse scientific notation number.
- • Parse exponential format
- • Extract mantissa and exponent
- • Validate notation format
- • Return parsed components
+ Args:
+ number_string: Scientific notation string
+
+ Returns:
+ Parsed number as float
"""
- pass
+ try:
+ return float(number_string)
+ except ValueError:
+ raise ValidationError(f"Invalid scientific notation: {number_string}")
- def convert_to_scientific(self, number, precision=None):
+ def convert_to_scientific(self, number: float, precision: Optional[int] = None) -> str:
"""
Convert number to scientific notation.
- • Calculate appropriate exponent
- • Format with specified precision
- • Return scientific notation string
+ Args:
+ number: Number to convert
+ precision: Precision (number of decimal places)
+
+ Returns:
+ Scientific notation string
"""
- pass
+ if precision is not None:
+ return f"{number:.{precision}e}"
+ else:
+ return f"{number:e}"
- def normalize_precision(self, number, significant_digits):
+ def normalize_precision(self, number: float, significant_digits: int) -> float:
"""
Normalize number precision.
- • Round to specified significant digits
- • Handle precision requirements
- • Return normalized number
+ Args:
+ number: Number to normalize
+ significant_digits: Number of significant digits
+
+ Returns:
+ Normalized number
"""
- pass
+ if number == 0:
+ return 0.0
+
+ # Calculate order of magnitude
+ magnitude = abs(number)
+ order = 0
+ while magnitude >= 10:
+ magnitude /= 10
+ order += 1
+ while magnitude < 1:
+ magnitude *= 10
+ order -= 1
+
+ # Round to significant digits
+ rounded = round(magnitude, significant_digits - 1)
+
+ return rounded * (10 ** order)
diff --git a/libs/semantica/normalize/text_normalizer.py b/libs/semantica/normalize/text_normalizer.py
index 0b15c013..532a1f6f 100644
--- a/libs/semantica/normalize/text_normalizer.py
+++ b/libs/semantica/normalize/text_normalizer.py
@@ -17,6 +17,14 @@ Main Classes:
- SpecialCharacterProcessor: Special character handling
"""
+import re
+import unicodedata
+from typing import Any, Dict, List, Optional
+
+from ..utils.exceptions import ValidationError, ProcessingError
+from ..utils.logging import get_logger
+from .text_cleaner import TextCleaner
+
class TextNormalizer:
"""
@@ -28,81 +36,107 @@ class TextNormalizer:
• Standardizes text formatting
• Removes unwanted content and noise
• Supports multiple languages and scripts
-
- Attributes:
- • unicode_normalizer: Unicode processing engine
- • whitespace_normalizer: Whitespace handler
- • special_char_processor: Special character processor
- • text_cleaner: Text cleaning utilities
- • supported_languages: List of supported languages
-
- Methods:
- • normalize_text(): Normalize text content
- • clean_text(): Clean and sanitize text
- • standardize_format(): Standardize text format
- • process_batch(): Process multiple texts
"""
def __init__(self, config=None, **kwargs):
"""
Initialize text normalizer.
- • Setup normalization rules
- • Configure text cleaning
- • Initialize language processors
- • Setup encoding handlers
- • Configure batch processing
+ Args:
+ config: Configuration dictionary
+ **kwargs: Additional configuration options
"""
- pass
+ self.logger = get_logger("text_normalizer")
+ self.config = config or {}
+ self.config.update(kwargs)
+
+ self.text_cleaner = TextCleaner(**self.config)
+ self.unicode_normalizer = UnicodeNormalizer(**self.config)
+ self.whitespace_normalizer = WhitespaceNormalizer(**self.config)
+ self.special_char_processor = SpecialCharacterProcessor(**self.config)
- def normalize_text(self, text, **options):
+ def normalize_text(self, text: str, **options) -> str:
"""
Normalize text content.
- • Apply Unicode normalization
- • Standardize case and formatting
- • Clean whitespace and special chars
- • Handle encoding issues
- • Apply language-specific rules
- • Return normalized text
+ Args:
+ text: Input text
+ **options: Normalization options
+
+ Returns:
+ Normalized text
"""
- pass
+ if not text:
+ return ""
+
+ normalized = text
+
+ # Unicode normalization
+ unicode_form = options.get("unicode_form", "NFC")
+ normalized = self.unicode_normalizer.normalize_unicode(normalized, form=unicode_form)
+
+ # Whitespace normalization
+ normalized = self.whitespace_normalizer.normalize_whitespace(normalized, **options)
+
+ # Special character processing
+ normalized = self.special_char_processor.process_special_chars(normalized, **options)
+
+ # Case normalization
+ case_type = options.get("case", "preserve")
+ if case_type == "lower":
+ normalized = normalized.lower()
+ elif case_type == "upper":
+ normalized = normalized.upper()
+ elif case_type == "title":
+ normalized = normalized.title()
+
+ return normalized.strip()
- def clean_text(self, text, **options):
+ def clean_text(self, text: str, **options) -> str:
"""
Clean and sanitize text content.
- • Remove unwanted characters
- • Clean HTML and markup
- • Remove noise and artifacts
- • Standardize punctuation
- • Return cleaned text
+ Args:
+ text: Input text
+ **options: Cleaning options
+
+ Returns:
+ Cleaned text
"""
- pass
+ return self.text_cleaner.clean(text, **options)
- def standardize_format(self, text, format_type="standard"):
+ def standardize_format(self, text: str, format_type: str = "standard") -> str:
"""
Standardize text format.
- • Apply format-specific rules
- • Standardize spacing and punctuation
- • Normalize line breaks
- • Apply formatting conventions
- • Return formatted text
- """
- pass
+ Args:
+ text: Input text
+ format_type: Format type ('standard', 'compact', 'preserve')
+
+ Returns:
+ Formatted text
+ """
+ if format_type == "compact":
+ # Remove extra whitespace
+ text = re.sub(r'\s+', ' ', text)
+ elif format_type == "preserve":
+ # Preserve original formatting
+ pass
+
+ return text.strip()
- def process_batch(self, texts, **options):
+ def process_batch(self, texts: List[str], **options) -> List[str]:
"""
Process multiple texts in batch.
- • Process texts concurrently
- • Apply normalization rules
- • Track processing progress
- • Handle individual errors
- • Return processed texts
+ Args:
+ texts: List of texts
+ **options: Processing options
+
+ Returns:
+ List of processed texts
"""
- pass
+ return [self.normalize_text(text, **options) for text in texts]
class UnicodeNormalizer:
@@ -120,45 +154,77 @@ class UnicodeNormalizer:
"""
Initialize Unicode normalizer.
- • Setup Unicode normalization forms
- • Configure character mapping
- • Initialize encoding handlers
- • Setup script processors
+ Args:
+ **config: Configuration options
"""
- pass
+ self.logger = get_logger("unicode_normalizer")
+ self.config = config
- def normalize_unicode(self, text, form="NFC"):
+ def normalize_unicode(self, text: str, form: str = "NFC") -> str:
"""
Normalize Unicode text.
- • Apply Unicode normalization form
- • Handle character composition
- • Process combining characters
- • Return normalized text
+ Args:
+ text: Input text
+ form: Unicode normalization form (NFC, NFD, NFKC, NFKD)
+
+ Returns:
+ Normalized text
"""
- pass
+ if not text:
+ return ""
+
+ try:
+ return unicodedata.normalize(form, text)
+ except Exception as e:
+ self.logger.warning(f"Unicode normalization failed: {e}")
+ return text
- def handle_encoding(self, text, source_encoding, target_encoding="utf-8"):
+ def handle_encoding(self, text: str, source_encoding: str, target_encoding: str = "utf-8") -> str:
"""
Handle text encoding conversion.
- • Convert between encodings
- • Handle encoding errors
- • Preserve text content
- • Return converted text
- """
- pass
+ Args:
+ text: Input text
+ source_encoding: Source encoding
+ target_encoding: Target encoding
+
+ Returns:
+ Converted text
+ """
+ if isinstance(text, bytes):
+ try:
+ return text.decode(source_encoding).encode(target_encoding).decode(target_encoding)
+ except Exception:
+ return text.decode('utf-8', errors='replace')
+ else:
+ return text
- def process_special_chars(self, text):
+ def process_special_chars(self, text: str) -> str:
"""
Process special Unicode characters.
- • Identify special characters
- • Apply character normalization
- • Handle script-specific rules
- • Return processed text
- """
- pass
+ Args:
+ text: Input text
+
+ Returns:
+ Processed text
+ """
+ # Replace common special characters
+ replacements = {
+ '\u2018': "'", # Left single quotation mark
+ '\u2019': "'", # Right single quotation mark
+ '\u201C': '"', # Left double quotation mark
+ '\u201D': '"', # Right double quotation mark
+ '\u2013': '-', # En dash
+ '\u2014': '--', # Em dash
+ '\u2026': '...', # Horizontal ellipsis
+ }
+
+ for old, new in replacements.items():
+ text = text.replace(old, new)
+
+ return text
class WhitespaceNormalizer:
@@ -175,46 +241,77 @@ class WhitespaceNormalizer:
"""
Initialize whitespace normalizer.
- • Setup whitespace patterns
- • Configure normalization rules
- • Initialize line break handlers
- • Setup indentation processors
+ Args:
+ **config: Configuration options
"""
- pass
+ self.logger = get_logger("whitespace_normalizer")
+ self.config = config
- def normalize_whitespace(self, text, **options):
+ def normalize_whitespace(self, text: str, **options) -> str:
"""
Normalize whitespace in text.
- • Standardize spaces and tabs
- • Normalize line breaks
- • Handle indentation
- • Remove excessive whitespace
- • Return normalized text
+ Args:
+ text: Input text
+ **options: Normalization options
+
+ Returns:
+ Normalized text
"""
- pass
+ if not text:
+ return ""
+
+ # Replace tabs with spaces
+ text = text.replace('\t', ' ')
+
+ # Normalize line breaks
+ line_break_type = options.get("line_break_type", "unix")
+ text = self.handle_line_breaks(text, line_break_type)
+
+ # Remove excessive whitespace
+ text = re.sub(r' +', ' ', text)
+ text = re.sub(r'\n\s*\n', '\n\n', text) # Normalize multiple newlines
+
+ return text.strip()
- def handle_line_breaks(self, text, line_break_type="unix"):
+ def handle_line_breaks(self, text: str, line_break_type: str = "unix") -> str:
"""
Normalize line breaks.
- • Convert line break types
- • Standardize line endings
- • Handle mixed line breaks
- • Return normalized text
- """
- pass
+ Args:
+ text: Input text
+ line_break_type: Line break type ('unix', 'windows', 'mac')
+
+ Returns:
+ Normalized text
+ """
+ if line_break_type == "unix":
+ text = text.replace('\r\n', '\n')
+ text = text.replace('\r', '\n')
+ elif line_break_type == "windows":
+ text = text.replace('\r\n', '\r\n')
+ text = text.replace('\r', '\r\n')
+ text = text.replace('\n', '\r\n')
+
+ return text
- def process_indentation(self, text, indent_type="spaces"):
+ def process_indentation(self, text: str, indent_type: str = "spaces") -> str:
"""
Normalize text indentation.
- • Convert indentation types
- • Standardize indentation size
- • Handle mixed indentation
- • Return normalized text
+ Args:
+ text: Input text
+ indent_type: Indentation type ('spaces', 'tabs')
+
+ Returns:
+ Normalized text
"""
- pass
+ if indent_type == "spaces":
+ text = text.replace('\t', ' ') # Convert tabs to 4 spaces
+ elif indent_type == "tabs":
+ text = re.sub(r' ', '\t', text) # Convert 4 spaces to tabs
+
+ return text
class SpecialCharacterProcessor:
@@ -231,43 +328,69 @@ class SpecialCharacterProcessor:
"""
Initialize special character processor.
- • Setup character mapping rules
- • Configure symbol processors
- • Initialize punctuation handlers
- • Setup diacritic processors
+ Args:
+ **config: Configuration options
"""
- pass
+ self.logger = get_logger("special_char_processor")
+ self.config = config
- def process_special_chars(self, text, **options):
+ def process_special_chars(self, text: str, **options) -> str:
"""
Process special characters in text.
- • Identify special characters
- • Apply character normalization
- • Handle symbol conversion
- • Process diacritics
- • Return processed text
+ Args:
+ text: Input text
+ **options: Processing options
+
+ Returns:
+ Processed text
"""
- pass
+ # Normalize punctuation
+ text = self.normalize_punctuation(text)
+
+ # Process diacritics if requested
+ if options.get("normalize_diacritics", False):
+ text = self.process_diacritics(text)
+
+ return text
- def normalize_punctuation(self, text):
+ def normalize_punctuation(self, text: str) -> str:
"""
Normalize punctuation marks.
- • Standardize punctuation usage
- • Handle quotation marks
- • Normalize dashes and hyphens
- • Return normalized text
+ Args:
+ text: Input text
+
+ Returns:
+ Normalized text
"""
- pass
+ # Normalize quotes
+ text = re.sub(r'["""]', '"', text)
+ text = re.sub(r'[''']', "'", text)
+
+ # Normalize dashes
+ text = re.sub(r'[–—]', '-', text)
+
+ # Normalize ellipsis
+ text = text.replace('…', '...')
+
+ return text
- def process_diacritics(self, text, **options):
+ def process_diacritics(self, text: str, **options) -> str:
"""
Process diacritical marks.
- • Normalize diacritics
- • Handle accent marks
- • Process combining characters
- • Return processed text
- """
- pass
+ Args:
+ text: Input text
+ **options: Processing options
+
+ Returns:
+ Processed text
+ """
+ if options.get("remove_diacritics", False):
+ # Remove diacritics
+ nfd = unicodedata.normalize('NFD', text)
+ return ''.join(c for c in nfd if unicodedata.category(c) != 'Mn')
+ else:
+ # Normalize diacritics
+ return unicodedata.normalize('NFC', text)
diff --git a/libs/semantica/prompting/__init__.py b/libs/semantica/prompting/__init__.py
deleted file mode 100644
index f2520d72..00000000
--- a/libs/semantica/prompting/__init__.py
+++ /dev/null
@@ -1,19 +0,0 @@
-"""
-Prompt Engineering Module
-
-This module provides natural-language programming capabilities for agents,
-formalizing the prompt layer of context engineering. Supports BAML/DSPy-style
-prompt engineering where prompts define agent goals and behavior.
-"""
-
-# from .prompt_builder import PromptBuilder
-# from .template_engine import TemplateEngine
-# from .prompt_optimizer import PromptOptimizer
-
-# TODO: Implement prompt engineering
-# - Natural-language programming for agent goals
-# - Prompt template management
-# - Context-aware prompt building
-# - Prompt optimization and refinement
-# - Multi-step prompt chains
-# - Prompt versioning and A/B testing
diff --git a/libs/semantica/prompting/prompt_builder.py b/libs/semantica/prompting/prompt_builder.py
deleted file mode 100644
index 62b6ecf5..00000000
--- a/libs/semantica/prompting/prompt_builder.py
+++ /dev/null
@@ -1,14 +0,0 @@
-"""
-Prompt Builder for Agent Goals
-
-Builds prompts as natural-language programs that define agent
-goals and behavior, formalizing the prompting layer.
-"""
-
-# TODO: Implement prompt builder
-# - Build prompts as natural-language programs
-# - Define agent goals through prompts
-# - Context-aware prompt construction
-# - Dynamic prompt generation
-# - Prompt parameterization
-# - Integration with ontology for semantic prompts
diff --git a/libs/semantica/qa_rag/__init__.py b/libs/semantica/qa_rag/__init__.py
deleted file mode 100644
index c55849f1..00000000
--- a/libs/semantica/qa_rag/__init__.py
+++ /dev/null
@@ -1,21 +0,0 @@
-"""
-RAG System Module
-
-This module provides Retrieval Augmented Generation capabilities
-for question answering and conversation management. Enables agent
-memory through vector databases and knowledge graph integration.
-"""
-
-# from .rag_manager import RAGManager
-# from .hybrid_retriever import HybridRetriever
-# from .context_builder import ContextBuilder
-# from .memory_store import MemoryStore
-
-# TODO: Implement RAG system
-# - Semantic retrieval from vector stores and knowledge graphs
-# - Hybrid retrieval (GraphRAG) combining vectors + graphs
-# - Context building and prompt management
-# - Answer generation and validation
-# - Conversation management and history
-# - Agent memory integration
-# - Provenance tracking and attribution
diff --git a/libs/semantica/qa_rag/context_builder.py b/libs/semantica/qa_rag/context_builder.py
deleted file mode 100644
index 7ca67374..00000000
--- a/libs/semantica/qa_rag/context_builder.py
+++ /dev/null
@@ -1,14 +0,0 @@
-"""
-Context Builder for RAG
-
-Builds enriched context for LLM generation by combining
-vector search results with knowledge graph relationships.
-"""
-
-# TODO: Implement context builder
-# - Combine vector and graph retrieval results
-# - Enrich context with relationships
-# - Structure context for LLM consumption
-# - Include provenance and metadata
-# - Context formatting and optimization
-# - Multi-source context synthesis
diff --git a/libs/semantica/qa_rag/hybrid_retriever.py b/libs/semantica/qa_rag/hybrid_retriever.py
deleted file mode 100644
index 805f602d..00000000
--- a/libs/semantica/qa_rag/hybrid_retriever.py
+++ /dev/null
@@ -1,14 +0,0 @@
-"""
-Hybrid Retriever for GraphRAG
-
-Combines vector search speed with knowledge graph precision
-for 30% accuracy improvements over vector-only RAG.
-"""
-
-# TODO: Implement hybrid retriever
-# - Vector similarity search
-# - Knowledge graph traversal from seed entities
-# - Result fusion strategies (RRF, weighted, etc.)
-# - Graph expansion from vector results
-# - Context enrichment with relationships
-# - Performance optimization for hybrid queries
diff --git a/libs/semantica/qa_rag/memory_store.py b/libs/semantica/qa_rag/memory_store.py
deleted file mode 100644
index 5b32ebc2..00000000
--- a/libs/semantica/qa_rag/memory_store.py
+++ /dev/null
@@ -1,14 +0,0 @@
-"""
-Memory Store for Agent Context
-
-Provides persistent memory storage for agent conversations
-and context using vector databases and knowledge graphs.
-"""
-
-# TODO: Implement memory store
-# - Conversation history storage
-# - Context embedding and indexing
-# - Memory retrieval and search
-# - Context versioning and updates
-# - Memory expiration and cleanup
-# - Cross-conversation context linking
diff --git a/libs/semantica/qa_rag/rag_manager.py b/libs/semantica/qa_rag/rag_manager.py
deleted file mode 100644
index af34339a..00000000
--- a/libs/semantica/qa_rag/rag_manager.py
+++ /dev/null
@@ -1,14 +0,0 @@
-"""
-RAG Manager for Semantica framework.
-
-This module provides the main RAG (Retrieval Augmented Generation)
-system for question answering and conversation.
-"""
-
-# TODO: Implement RAG manager
-# - Query processing and retrieval coordination
-# - Context building from retrieved chunks
-# - Answer generation using LLMs
-# - Answer validation and quality checking
-# - Conversation flow management
-# - Performance optimization
diff --git a/libs/semantica/security/__init__.py b/libs/semantica/security/__init__.py
deleted file mode 100644
index 7747c380..00000000
--- a/libs/semantica/security/__init__.py
+++ /dev/null
@@ -1,18 +0,0 @@
-"""
-Security and Privacy Module
-
-This module provides comprehensive security and privacy protection capabilities.
-
-Exports:
- - AccessController: Access control and authentication
- - DataMasker: Data masking and anonymization
- - PIIRedactor: PII detection and redaction
- - AuditLogger: Audit logging and compliance
- - EncryptionManager: Data encryption and key management
-"""
-
-# from .access_control import AccessController
-# from .data_masking import DataMasker
-# from .pii_redactor import PIIRedactor
-# from .audit_logger import AuditLogger
-# from .encryption_manager import EncryptionManager
diff --git a/libs/semantica/security/access_control.py b/libs/semantica/security/access_control.py
deleted file mode 100644
index 3b55723d..00000000
--- a/libs/semantica/security/access_control.py
+++ /dev/null
@@ -1,265 +0,0 @@
-"""
-Access Control Module
-
-Handles access control, authentication, and authorization.
-
-Key Features:
- - Role-based access control (RBAC)
- - User authentication and authorization
- - Permission management
- - Access logging and auditing
- - Security policy enforcement
-
-Main Classes:
- - AccessController: Main access control class
- - AuthenticationManager: User authentication
- - AuthorizationEngine: Authorization processing
- - PermissionManager: Permission management
-"""
-
-
-class AccessController:
- """
- Access control and security management handler.
-
- • Manages user access control and authentication
- • Handles role-based access control (RBAC)
- • Processes user permissions and authorization
- • Manages security policies and enforcement
- • Handles access logging and auditing
- • Supports multiple authentication methods
-
- Attributes:
- • auth_manager: Authentication manager
- • authz_engine: Authorization engine
- • permission_manager: Permission manager
- • policy_enforcer: Security policy enforcer
- • audit_logger: Access audit logger
-
- Methods:
- • authenticate_user(): Authenticate user credentials
- • authorize_access(): Authorize user access
- • check_permissions(): Check user permissions
- • enforce_policies(): Enforce security policies
- """
-
- def __init__(self, config=None, **kwargs):
- """
- Initialize access controller.
-
- • Setup authentication systems
- • Configure authorization rules
- • Initialize permission management
- • Setup policy enforcement
- • Configure audit logging
- """
- pass
-
- def authenticate_user(self, credentials, **options):
- """
- Authenticate user with credentials.
-
- • Validate user credentials
- • Check authentication methods
- • Handle authentication failures
- • Return authentication result
- """
- pass
-
- def authorize_access(self, user, resource, action, **context):
- """
- Authorize user access to resource.
-
- • Check user permissions
- • Validate access rules
- • Handle authorization context
- • Return authorization result
- """
- pass
-
- def check_permissions(self, user, permissions, **options):
- """
- Check user permissions.
-
- • Validate user permissions
- • Check permission inheritance
- • Handle permission conflicts
- • Return permission status
- """
- pass
-
- def enforce_policies(self, user, action, **context):
- """
- Enforce security policies.
-
- • Apply security policies
- • Check policy compliance
- • Handle policy violations
- • Return policy enforcement result
- """
- pass
-
-
-class AuthenticationManager:
- """
- User authentication management engine.
-
- • Manages user authentication
- • Handles authentication methods
- • Processes authentication tokens
- • Manages user sessions
- """
-
- def __init__(self, **config):
- """
- Initialize authentication manager.
-
- • Setup authentication methods
- • Configure token handling
- • Initialize session management
- • Setup credential validation
- """
- pass
-
- def authenticate_user(self, credentials, method="password"):
- """
- Authenticate user with specified method.
-
- • Validate credentials
- • Check authentication method
- • Handle authentication errors
- • Return authentication result
- """
- pass
-
- def generate_token(self, user, **options):
- """
- Generate authentication token for user.
-
- • Create authentication token
- • Set token expiration
- • Handle token security
- • Return generated token
- """
- pass
-
- def validate_token(self, token):
- """
- Validate authentication token.
-
- • Check token validity
- • Verify token signature
- • Handle token expiration
- • Return validation result
- """
- pass
-
-
-class AuthorizationEngine:
- """
- Authorization processing engine.
-
- • Processes user authorization
- • Handles access control rules
- • Manages authorization context
- • Processes authorization decisions
- """
-
- def __init__(self, **config):
- """
- Initialize authorization engine.
-
- • Setup authorization rules
- • Configure access control
- • Initialize context processing
- • Setup decision engines
- """
- pass
-
- def authorize_access(self, user, resource, action, **context):
- """
- Authorize user access to resource.
-
- • Check access control rules
- • Process authorization context
- • Make authorization decision
- • Return authorization result
- """
- pass
-
- def check_access_rules(self, user, resource, action):
- """
- Check access control rules.
-
- • Load applicable rules
- • Check rule conditions
- • Process rule logic
- • Return rule results
- """
- pass
-
- def process_authorization_context(self, context):
- """
- Process authorization context.
-
- • Analyze context information
- • Extract relevant factors
- • Apply context rules
- • Return processed context
- """
- pass
-
-
-class PermissionManager:
- """
- Permission management engine.
-
- • Manages user permissions
- • Handles permission inheritance
- • Processes permission conflicts
- • Manages permission updates
- """
-
- def __init__(self, **config):
- """
- Initialize permission manager.
-
- • Setup permission systems
- • Configure inheritance rules
- • Initialize conflict resolution
- • Setup permission updates
- """
- pass
-
- def check_permissions(self, user, permissions):
- """
- Check user permissions.
-
- • Validate user permissions
- • Check permission inheritance
- • Handle permission conflicts
- • Return permission status
- """
- pass
-
- def grant_permissions(self, user, permissions):
- """
- Grant permissions to user.
-
- • Add permissions to user
- • Handle permission conflicts
- • Update permission records
- • Return grant result
- """
- pass
-
- def revoke_permissions(self, user, permissions):
- """
- Revoke permissions from user.
-
- • Remove permissions from user
- • Handle permission dependencies
- • Update permission records
- • Return revoke result
- """
- pass
diff --git a/libs/semantica/templates/__init__.py b/libs/semantica/templates/__init__.py
deleted file mode 100644
index acb1467f..00000000
--- a/libs/semantica/templates/__init__.py
+++ /dev/null
@@ -1,20 +0,0 @@
-"""
-Template System Module
-
-This module provides template-based knowledge graph construction
-with schema validation and entity templates.
-"""
-
-from .schema_template import (
- SchemaTemplateManager,
- SchemaTemplate,
- EntityTemplate,
- RelationshipTemplate,
-)
-
-__all__ = [
- "SchemaTemplateManager",
- "SchemaTemplate",
- "EntityTemplate",
- "RelationshipTemplate",
-]
diff --git a/libs/semantica/templates/schema_template.py b/libs/semantica/templates/schema_template.py
deleted file mode 100644
index 6af92e54..00000000
--- a/libs/semantica/templates/schema_template.py
+++ /dev/null
@@ -1,306 +0,0 @@
-"""
-Schema Template for Semantica framework.
-
-Provides template-based knowledge graph construction
-to prevent AI from inventing new entities or relationships.
-"""
-
-from typing import Any, Dict, List, Optional, Set
-from dataclasses import dataclass, field
-
-from ..utils.exceptions import ValidationError, ProcessingError
-from ..utils.logging import get_logger
-
-
-@dataclass
-class EntityTemplate:
- """Entity template definition."""
-
- name: str
- entity_type: str
- required_properties: List[str] = field(default_factory=list)
- optional_properties: List[str] = field(default_factory=list)
- constraints: Dict[str, Any] = field(default_factory=dict)
- metadata: Dict[str, Any] = field(default_factory=dict)
-
-
-@dataclass
-class RelationshipTemplate:
- """Relationship template definition."""
-
- name: str
- subject_type: str
- object_type: str
- predicate: str
- cardinality: str = "many-to-many" # one-to-one, one-to-many, many-to-many
- constraints: Dict[str, Any] = field(default_factory=dict)
- metadata: Dict[str, Any] = field(default_factory=dict)
-
-
-@dataclass
-class SchemaTemplate:
- """Schema template for knowledge graph."""
-
- name: str
- namespace: str
- entity_templates: Dict[str, EntityTemplate] = field(default_factory=dict)
- relationship_templates: Dict[str, RelationshipTemplate] = field(default_factory=dict)
- version: str = "1.0"
- metadata: Dict[str, Any] = field(default_factory=dict)
-
-
-class SchemaTemplateManager:
- """
- Schema template management and validation.
-
- • Defines and validates entity templates
- • Manages relationship constraints
- • Enforces template-based extraction
- • Validates extracted entities against templates
- """
-
- def __init__(self, config=None, **kwargs):
- """Initialize schema template manager."""
- self.logger = get_logger("schema_template_manager")
- self.config = config or {}
- self.config.update(kwargs)
-
- self.templates: Dict[str, SchemaTemplate] = {}
- self.active_template: Optional[str] = None
-
- def create_template(
- self,
- name: str,
- namespace: str,
- entity_templates: Optional[List[EntityTemplate]] = None,
- relationship_templates: Optional[List[RelationshipTemplate]] = None,
- **metadata
- ) -> SchemaTemplate:
- """
- Create a new schema template.
-
- Args:
- name: Template name
- namespace: Namespace URI
- entity_templates: List of entity templates
- relationship_templates: List of relationship templates
- **metadata: Additional metadata
-
- Returns:
- Created SchemaTemplate
- """
- template = SchemaTemplate(
- name=name,
- namespace=namespace,
- entity_templates={e.name: e for e in (entity_templates or [])},
- relationship_templates={r.name: r for r in (relationship_templates or [])},
- metadata=metadata
- )
-
- self.templates[name] = template
- self.logger.info(f"Created schema template: {name}")
-
- return template
-
- def add_entity_template(
- self,
- template_name: str,
- entity_template: EntityTemplate
- ) -> bool:
- """Add entity template to schema."""
- template = self.templates.get(template_name)
- if not template:
- raise ValidationError(f"Template '{template_name}' not found")
-
- template.entity_templates[entity_template.name] = entity_template
- return True
-
- def add_relationship_template(
- self,
- template_name: str,
- relationship_template: RelationshipTemplate
- ) -> bool:
- """Add relationship template to schema."""
- template = self.templates.get(template_name)
- if not template:
- raise ValidationError(f"Template '{template_name}' not found")
-
- template.relationship_templates[relationship_template.name] = relationship_template
- return True
-
- def validate_entity(
- self,
- entity: Dict[str, Any],
- template_name: Optional[str] = None
- ) -> Dict[str, Any]:
- """
- Validate entity against template.
-
- Args:
- entity: Entity dictionary
- template_name: Template name (uses active template if None)
-
- Returns:
- Validation result
- """
- template_name = template_name or self.active_template
- if not template_name:
- return {"valid": True, "warnings": ["No template active"]}
-
- template = self.templates.get(template_name)
- if not template:
- return {"valid": False, "errors": [f"Template '{template_name}' not found"]}
-
- entity_type = entity.get("type")
- if not entity_type:
- return {"valid": False, "errors": ["Entity type missing"]}
-
- # Find matching entity template
- entity_template = None
- for et in template.entity_templates.values():
- if et.entity_type == entity_type:
- entity_template = et
- break
-
- if not entity_template:
- return {"valid": False, "errors": [f"No template for entity type '{entity_type}'"]}
-
- # Validate required properties
- errors = []
- for prop in entity_template.required_properties:
- if prop not in entity or entity[prop] is None:
- errors.append(f"Missing required property: {prop}")
-
- # Check constraints
- for prop, constraint in entity_template.constraints.items():
- if prop in entity:
- value = entity[prop]
- if not self._check_constraint(value, constraint):
- errors.append(f"Constraint violation for property '{prop}': {constraint}")
-
- return {
- "valid": len(errors) == 0,
- "errors": errors,
- "entity_template": entity_template.name
- }
-
- def validate_relationship(
- self,
- relationship: Dict[str, Any],
- template_name: Optional[str] = None
- ) -> Dict[str, Any]:
- """
- Validate relationship against template.
-
- Args:
- relationship: Relationship dictionary
- template_name: Template name (uses active template if None)
-
- Returns:
- Validation result
- """
- template_name = template_name or self.active_template
- if not template_name:
- return {"valid": True, "warnings": ["No template active"]}
-
- template = self.templates.get(template_name)
- if not template:
- return {"valid": False, "errors": [f"Template '{template_name}' not found"]}
-
- predicate = relationship.get("predicate")
- subject_type = relationship.get("subject_type")
- object_type = relationship.get("object_type")
-
- if not predicate:
- return {"valid": False, "errors": ["Relationship predicate missing"]}
-
- # Find matching relationship template
- rel_template = None
- for rt in template.relationship_templates.values():
- if (rt.predicate == predicate and
- rt.subject_type == subject_type and
- rt.object_type == object_type):
- rel_template = rt
- break
-
- if not rel_template:
- return {
- "valid": False,
- "errors": [f"No template for relationship '{predicate}' between {subject_type} and {object_type}"]
- }
-
- # Check constraints
- errors = []
- for prop, constraint in rel_template.constraints.items():
- if prop in relationship:
- value = relationship[prop]
- if not self._check_constraint(value, constraint):
- errors.append(f"Constraint violation for property '{prop}': {constraint}")
-
- return {
- "valid": len(errors) == 0,
- "errors": errors,
- "relationship_template": rel_template.name
- }
-
- def get_allowed_entities(self, template_name: Optional[str] = None) -> List[str]:
- """Get list of allowed entity types."""
- template_name = template_name or self.active_template
- if not template_name:
- return []
-
- template = self.templates.get(template_name)
- if not template:
- return []
-
- return [et.entity_type for et in template.entity_templates.values()]
-
- def get_allowed_relationships(
- self,
- template_name: Optional[str] = None
- ) -> List[Dict[str, str]]:
- """Get list of allowed relationships."""
- template_name = template_name or self.active_template
- if not template_name:
- return []
-
- template = self.templates.get(template_name)
- if not template:
- return []
-
- return [
- {
- "predicate": rt.predicate,
- "subject_type": rt.subject_type,
- "object_type": rt.object_type
- }
- for rt in template.relationship_templates.values()
- ]
-
- def set_active_template(self, template_name: str) -> bool:
- """Set active template for validation."""
- if template_name not in self.templates:
- raise ValidationError(f"Template '{template_name}' not found")
-
- self.active_template = template_name
- return True
-
- def _check_constraint(self, value: Any, constraint: Any) -> bool:
- """Check if value satisfies constraint."""
- if isinstance(constraint, dict):
- if "type" in constraint:
- expected_type = constraint["type"]
- if expected_type == "string" and not isinstance(value, str):
- return False
- if expected_type == "number" and not isinstance(value, (int, float)):
- return False
-
- if "min" in constraint and isinstance(value, (int, float)):
- if value < constraint["min"]:
- return False
-
- if "max" in constraint and isinstance(value, (int, float)):
- if value > constraint["max"]:
- return False
-
- return True
diff --git a/libs/semantica/vocabulary/__init__.py b/libs/semantica/vocabulary/__init__.py
deleted file mode 100644
index 233c4860..00000000
--- a/libs/semantica/vocabulary/__init__.py
+++ /dev/null
@@ -1,21 +0,0 @@
-"""
-Vocabulary and Controlled Vocabulary Module
-
-This module provides vocabulary management for hierarchical controlled terms
-that supplement ontologies with relevant terminology. Vocabularies connect
-to ontology classes to provide structured, pre-defined term hierarchies.
-"""
-
-from .vocabulary_manager import VocabularyManager
-from .controlled_vocabulary import (
- ControlledVocabulary,
- VocabularyTerm,
- TermRelation,
-)
-
-__all__ = [
- "VocabularyManager",
- "ControlledVocabulary",
- "VocabularyTerm",
- "TermRelation",
-]
diff --git a/libs/semantica/vocabulary/controlled_vocabulary.py b/libs/semantica/vocabulary/controlled_vocabulary.py
deleted file mode 100644
index e383070d..00000000
--- a/libs/semantica/vocabulary/controlled_vocabulary.py
+++ /dev/null
@@ -1,432 +0,0 @@
-"""
-Controlled Vocabulary for Semantica framework.
-
-Represents hierarchical collections of controlled terms that can be
-connected to ontology classes. Useful when classes have many known
-subtypes that share attributes but don't need separate modeling.
-"""
-
-from typing import Any, Dict, List, Optional, Set
-from dataclasses import dataclass, field
-from enum import Enum
-
-from ..utils.exceptions import ValidationError
-from ..utils.logging import get_logger
-
-
-class TermRelation(str, Enum):
- """Term relationship types."""
- BROADER = "broader"
- NARROWER = "narrower"
- RELATED = "related"
- EXACT_MATCH = "exactMatch"
- CLOSE_MATCH = "closeMatch"
- BROAD_MATCH = "broadMatch"
- NARROW_MATCH = "narrowMatch"
-
-
-@dataclass
-class VocabularyTerm:
- """Controlled vocabulary term."""
- uri: str
- label: str
- definition: Optional[str] = None
- notation: Optional[str] = None
- broader_terms: List[str] = field(default_factory=list)
- narrower_terms: List[str] = field(default_factory=list)
- related_terms: List[str] = field(default_factory=list)
- alt_labels: List[str] = field(default_factory=list)
- hidden_labels: List[str] = field(default_factory=list)
- scope_note: Optional[str] = None
- examples: List[str] = field(default_factory=list)
- in_scheme: Optional[str] = None
- top_concept_of: Optional[str] = None
- metadata: Dict[str, Any] = field(default_factory=dict)
-
-
-class ControlledVocabulary:
- """
- Controlled vocabulary with hierarchical term structure.
-
- • Manages hierarchical term structures (broader/narrower)
- • Supports SKOS vocabulary standards
- • Enables vocabulary connection to ontology classes
- • Handles term updates without ontology changes
- """
-
- def __init__(
- self,
- uri: str,
- title: str,
- description: Optional[str] = None,
- **metadata
- ):
- """
- Initialize controlled vocabulary.
-
- Args:
- uri: Vocabulary URI
- title: Vocabulary title
- description: Vocabulary description
- **metadata: Additional metadata
- """
- self.logger = get_logger("controlled_vocabulary")
- self.uri = uri
- self.title = title
- self.description = description
- self.metadata = metadata
-
- self.terms: Dict[str, VocabularyTerm] = {}
- self.top_concepts: List[str] = []
- self.ontology_classes: Dict[str, str] = {} # term_uri -> class_uri
-
- def add_term(
- self,
- term: VocabularyTerm,
- top_concept: bool = False
- ) -> bool:
- """
- Add term to vocabulary.
-
- Args:
- term: Vocabulary term
- top_concept: Whether this is a top-level concept
-
- Returns:
- True if term added successfully
- """
- if term.uri in self.terms:
- self.logger.warning(f"Term '{term.uri}' already exists, updating")
-
- self.terms[term.uri] = term
- term.in_scheme = self.uri
-
- if top_concept:
- term.top_concept_of = self.uri
- if term.uri not in self.top_concepts:
- self.top_concepts.append(term.uri)
-
- self.logger.info(f"Added term: {term.uri}")
- return True
-
- def remove_term(self, term_uri: str) -> bool:
- """
- Remove term from vocabulary.
-
- Args:
- term_uri: Term URI
-
- Returns:
- True if term removed successfully
- """
- if term_uri not in self.terms:
- return False
-
- term = self.terms[term_uri]
-
- # Remove from broader terms' narrower lists
- for broader_uri in term.broader_terms:
- if broader_uri in self.terms:
- if term_uri in self.terms[broader_uri].narrower_terms:
- self.terms[broader_uri].narrower_terms.remove(term_uri)
-
- # Remove from narrower terms' broader lists
- for narrower_uri in term.narrower_terms:
- if narrower_uri in self.terms:
- if term_uri in self.terms[narrower_uri].broader_terms:
- self.terms[narrower_uri].broader_terms.remove(term_uri)
-
- # Remove from top concepts
- if term_uri in self.top_concepts:
- self.top_concepts.remove(term_uri)
-
- del self.terms[term_uri]
- self.logger.info(f"Removed term: {term_uri}")
- return True
-
- def add_broader_term(
- self,
- term_uri: str,
- broader_uri: str
- ) -> bool:
- """
- Add broader term relationship.
-
- Args:
- term_uri: Term URI
- broader_uri: Broader term URI
-
- Returns:
- True if relationship added successfully
- """
- if term_uri not in self.terms or broader_uri not in self.terms:
- raise ValidationError("Both terms must exist in vocabulary")
-
- if broader_uri not in self.terms[term_uri].broader_terms:
- self.terms[term_uri].broader_terms.append(broader_uri)
-
- if term_uri not in self.terms[broader_uri].narrower_terms:
- self.terms[broader_uri].narrower_terms.append(term_uri)
-
- return True
-
- def add_narrower_term(
- self,
- term_uri: str,
- narrower_uri: str
- ) -> bool:
- """
- Add narrower term relationship.
-
- Args:
- term_uri: Term URI
- narrower_uri: Narrower term URI
-
- Returns:
- True if relationship added successfully
- """
- return self.add_broader_term(narrower_uri, term_uri)
-
- def add_related_term(
- self,
- term_uri: str,
- related_uri: str
- ) -> bool:
- """
- Add related term relationship.
-
- Args:
- term_uri: Term URI
- related_uri: Related term URI
-
- Returns:
- True if relationship added successfully
- """
- if term_uri not in self.terms or related_uri not in self.terms:
- raise ValidationError("Both terms must exist in vocabulary")
-
- if related_uri not in self.terms[term_uri].related_terms:
- self.terms[term_uri].related_terms.append(related_uri)
-
- if term_uri not in self.terms[related_uri].related_terms:
- self.terms[related_uri].related_terms.append(term_uri)
-
- return True
-
- def get_term(self, term_uri: str) -> Optional[VocabularyTerm]:
- """
- Get term by URI.
-
- Args:
- term_uri: Term URI
-
- Returns:
- Vocabulary term or None if not found
- """
- return self.terms.get(term_uri)
-
- def get_broader_terms(
- self,
- term_uri: str,
- transitive: bool = False
- ) -> List[str]:
- """
- Get broader terms.
-
- Args:
- term_uri: Term URI
- transitive: Include transitive broader terms
-
- Returns:
- List of broader term URIs
- """
- if term_uri not in self.terms:
- return []
-
- broader = list(self.terms[term_uri].broader_terms)
-
- if transitive:
- for broader_uri in broader:
- broader.extend(self.get_broader_terms(broader_uri, transitive=True))
-
- return list(set(broader))
-
- def get_narrower_terms(
- self,
- term_uri: str,
- transitive: bool = False
- ) -> List[str]:
- """
- Get narrower terms.
-
- Args:
- term_uri: Term URI
- transitive: Include transitive narrower terms
-
- Returns:
- List of narrower term URIs
- """
- if term_uri not in self.terms:
- return []
-
- narrower = list(self.terms[term_uri].narrower_terms)
-
- if transitive:
- for narrower_uri in narrower:
- narrower.extend(self.get_narrower_terms(narrower_uri, transitive=True))
-
- return list(set(narrower))
-
- def connect_to_ontology_class(
- self,
- term_uri: str,
- class_uri: str
- ) -> bool:
- """
- Connect vocabulary term to ontology class.
-
- Args:
- term_uri: Term URI
- class_uri: Ontology class URI
-
- Returns:
- True if connection successful
- """
- if term_uri not in self.terms:
- raise ValidationError(f"Term '{term_uri}' not found")
-
- self.ontology_classes[term_uri] = class_uri
- self.logger.info(f"Connected term {term_uri} to class {class_uri}")
- return True
-
- def search_terms(
- self,
- query: str,
- search_labels: bool = True,
- search_definitions: bool = True
- ) -> List[str]:
- """
- Search for terms by query.
-
- Args:
- query: Search query
- search_labels: Search in labels
- search_definitions: Search in definitions
-
- Returns:
- List of matching term URIs
- """
- query_lower = query.lower()
- matches = []
-
- for term_uri, term in self.terms.items():
- matched = False
-
- if search_labels:
- if query_lower in term.label.lower():
- matched = True
- for alt_label in term.alt_labels:
- if query_lower in alt_label.lower():
- matched = True
-
- if search_definitions and term.definition:
- if query_lower in term.definition.lower():
- matched = True
-
- if matched:
- matches.append(term_uri)
-
- return matches
-
- def to_skos(self) -> Dict[str, Any]:
- """
- Convert vocabulary to SKOS format.
-
- Returns:
- SKOS vocabulary dictionary
- """
- skos = {
- "@context": {
- "skos": "http://www.w3.org/2004/02/skos/core#",
- "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
- "rdfs": "http://www.w3.org/2000/01/rdf-schema#"
- },
- "@type": "skos:ConceptScheme",
- "@id": self.uri,
- "skos:prefLabel": {
- "@value": self.title,
- "@language": "en"
- },
- "skos:hasTopConcept": [{"@id": uri} for uri in self.top_concepts],
- "skos:concept": []
- }
-
- if self.description:
- skos["skos:definition"] = {
- "@value": self.description,
- "@language": "en"
- }
-
- # Convert terms to SKOS
- for term_uri, term in self.terms.items():
- concept = {
- "@id": term_uri,
- "@type": "skos:Concept",
- "skos:prefLabel": {
- "@value": term.label,
- "@language": "en"
- },
- "skos:inScheme": {"@id": self.uri}
- }
-
- if term.definition:
- concept["skos:definition"] = {
- "@value": term.definition,
- "@language": "en"
- }
-
- if term.notation:
- concept["skos:notation"] = term.notation
-
- if term.broader_terms:
- concept["skos:broader"] = [{"@id": uri} for uri in term.broader_terms]
-
- if term.narrower_terms:
- concept["skos:narrower"] = [{"@id": uri} for uri in term.narrower_terms]
-
- if term.related_terms:
- concept["skos:related"] = [{"@id": uri} for uri in term.related_terms]
-
- if term.alt_labels:
- concept["skos:altLabel"] = [
- {"@value": label, "@language": "en"}
- for label in term.alt_labels
- ]
-
- if term.scope_note:
- concept["skos:scopeNote"] = {
- "@value": term.scope_note,
- "@language": "en"
- }
-
- skos["skos:concept"].append(concept)
-
- return skos
-
- def get_statistics(self) -> Dict[str, Any]:
- """
- Get vocabulary statistics.
-
- Returns:
- Statistics dictionary
- """
- return {
- "uri": self.uri,
- "title": self.title,
- "term_count": len(self.terms),
- "top_concept_count": len(self.top_concepts),
- "ontology_connections": len(self.ontology_classes),
- "terms_with_broader": sum(1 for t in self.terms.values() if t.broader_terms),
- "terms_with_narrower": sum(1 for t in self.terms.values() if t.narrower_terms),
- "terms_with_related": sum(1 for t in self.terms.values() if t.related_terms)
- }
diff --git a/libs/semantica/vocabulary/vocabulary_manager.py b/libs/semantica/vocabulary/vocabulary_manager.py
deleted file mode 100644
index aec1267b..00000000
--- a/libs/semantica/vocabulary/vocabulary_manager.py
+++ /dev/null
@@ -1,335 +0,0 @@
-"""
-Vocabulary Manager for Semantica framework.
-
-Manages controlled vocabularies that supplement ontologies with hierarchical
-terminology, enabling concise modeling when many concepts share attributes
-but don't need unique modeling.
-"""
-
-from typing import Any, Dict, List, Optional, Union
-from pathlib import Path
-
-from .controlled_vocabulary import ControlledVocabulary, VocabularyTerm
-from ..utils.exceptions import ValidationError, ProcessingError
-from ..utils.logging import get_logger
-from ..utils.helpers import read_json_file, write_json_file
-
-
-class VocabularyManager:
- """
- Manager for controlled vocabularies.
-
- • Creates and manages multiple controlled vocabularies
- • Builds hierarchical term structures
- • Connects vocabularies to ontology classes
- • Supports multi-language terms
- • Manages synonyms and alternative labels
- • Exports vocabularies in SKOS format
- """
-
- def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
- """
- Initialize vocabulary manager.
-
- Args:
- config: Configuration dictionary
- **kwargs: Additional configuration options
- """
- self.logger = get_logger("vocabulary_manager")
- self.config = config or {}
- self.config.update(kwargs)
-
- self.vocabularies: Dict[str, ControlledVocabulary] = {}
-
- def create_vocabulary(
- self,
- uri: str,
- title: str,
- description: Optional[str] = None,
- **metadata
- ) -> ControlledVocabulary:
- """
- Create a new controlled vocabulary.
-
- Args:
- uri: Vocabulary URI
- title: Vocabulary title
- description: Vocabulary description
- **metadata: Additional metadata
-
- Returns:
- Created ControlledVocabulary
-
- Raises:
- ValidationError: If vocabulary with URI already exists
- """
- if uri in self.vocabularies:
- raise ValidationError(f"Vocabulary with URI '{uri}' already exists")
-
- vocabulary = ControlledVocabulary(
- uri=uri,
- title=title,
- description=description,
- **metadata
- )
-
- self.vocabularies[uri] = vocabulary
- self.logger.info(f"Created vocabulary: {title} ({uri})")
-
- return vocabulary
-
- def get_vocabulary(self, uri: str) -> Optional[ControlledVocabulary]:
- """
- Get vocabulary by URI.
-
- Args:
- uri: Vocabulary URI
-
- Returns:
- ControlledVocabulary or None if not found
- """
- return self.vocabularies.get(uri)
-
- def remove_vocabulary(self, uri: str) -> bool:
- """
- Remove vocabulary.
-
- Args:
- uri: Vocabulary URI
-
- Returns:
- True if vocabulary removed successfully
- """
- if uri not in self.vocabularies:
- return False
-
- del self.vocabularies[uri]
- self.logger.info(f"Removed vocabulary: {uri}")
- return True
-
- def list_vocabularies(self) -> List[str]:
- """
- List all vocabulary URIs.
-
- Returns:
- List of vocabulary URIs
- """
- return list(self.vocabularies.keys())
-
- def add_term_to_vocabulary(
- self,
- vocabulary_uri: str,
- term: VocabularyTerm,
- top_concept: bool = False
- ) -> bool:
- """
- Add term to vocabulary.
-
- Args:
- vocabulary_uri: Vocabulary URI
- term: Vocabulary term
- top_concept: Whether this is a top-level concept
-
- Returns:
- True if term added successfully
- """
- vocabulary = self.get_vocabulary(vocabulary_uri)
- if not vocabulary:
- raise ValidationError(f"Vocabulary '{vocabulary_uri}' not found")
-
- return vocabulary.add_term(term, top_concept=top_concept)
-
- def search_across_vocabularies(
- self,
- query: str,
- vocabulary_uris: Optional[List[str]] = None,
- search_labels: bool = True,
- search_definitions: bool = True
- ) -> Dict[str, List[str]]:
- """
- Search for terms across vocabularies.
-
- Args:
- query: Search query
- vocabulary_uris: List of vocabulary URIs to search (None = all)
- search_labels: Search in labels
- search_definitions: Search in definitions
-
- Returns:
- Dictionary mapping vocabulary URI to list of matching term URIs
- """
- results = {}
-
- vocab_uris = vocabulary_uris or self.list_vocabularies()
-
- for vocab_uri in vocab_uris:
- vocabulary = self.get_vocabulary(vocab_uri)
- if vocabulary:
- matches = vocabulary.search_terms(
- query,
- search_labels=search_labels,
- search_definitions=search_definitions
- )
- if matches:
- results[vocab_uri] = matches
-
- return results
-
- def connect_term_to_class(
- self,
- vocabulary_uri: str,
- term_uri: str,
- class_uri: str
- ) -> bool:
- """
- Connect vocabulary term to ontology class.
-
- Args:
- vocabulary_uri: Vocabulary URI
- term_uri: Term URI
- class_uri: Ontology class URI
-
- Returns:
- True if connection successful
- """
- vocabulary = self.get_vocabulary(vocabulary_uri)
- if not vocabulary:
- raise ValidationError(f"Vocabulary '{vocabulary_uri}' not found")
-
- return vocabulary.connect_to_ontology_class(term_uri, class_uri)
-
- def export_vocabulary(
- self,
- vocabulary_uri: str,
- file_path: Union[str, Path],
- format: str = "skos"
- ) -> None:
- """
- Export vocabulary to file.
-
- Args:
- vocabulary_uri: Vocabulary URI
- file_path: Output file path
- format: Export format ('skos', 'json')
- """
- vocabulary = self.get_vocabulary(vocabulary_uri)
- if not vocabulary:
- raise ValidationError(f"Vocabulary '{vocabulary_uri}' not found")
-
- file_path = Path(file_path)
-
- if format == "skos":
- skos_data = vocabulary.to_skos()
- write_json_file(skos_data, file_path)
-
- elif format == "json":
- vocab_data = {
- "uri": vocabulary.uri,
- "title": vocabulary.title,
- "description": vocabulary.description,
- "metadata": vocabulary.metadata,
- "top_concepts": vocabulary.top_concepts,
- "terms": [
- {
- "uri": term.uri,
- "label": term.label,
- "definition": term.definition,
- "notation": term.notation,
- "broader_terms": term.broader_terms,
- "narrower_terms": term.narrower_terms,
- "related_terms": term.related_terms,
- "alt_labels": term.alt_labels,
- "scope_note": term.scope_note,
- "examples": term.examples,
- "metadata": term.metadata
- }
- for term in vocabulary.terms.values()
- ],
- "ontology_classes": vocabulary.ontology_classes
- }
- write_json_file(vocab_data, file_path)
-
- else:
- raise ValueError(f"Unsupported export format: {format}")
-
- self.logger.info(f"Exported vocabulary {vocabulary_uri} to {file_path}")
-
- def import_vocabulary(
- self,
- file_path: Union[str, Path],
- format: str = "json"
- ) -> ControlledVocabulary:
- """
- Import vocabulary from file.
-
- Args:
- file_path: Input file path
- format: Import format ('skos', 'json')
-
- Returns:
- Imported ControlledVocabulary
- """
- file_path = Path(file_path)
- if not file_path.exists():
- raise ProcessingError(f"File not found: {file_path}")
-
- if format == "json":
- data = read_json_file(file_path)
-
- vocabulary = ControlledVocabulary(
- uri=data["uri"],
- title=data["title"],
- description=data.get("description"),
- **data.get("metadata", {})
- )
-
- # Import terms
- for term_data in data.get("terms", []):
- term = VocabularyTerm(
- uri=term_data["uri"],
- label=term_data["label"],
- definition=term_data.get("definition"),
- notation=term_data.get("notation"),
- broader_terms=term_data.get("broader_terms", []),
- narrower_terms=term_data.get("narrower_terms", []),
- related_terms=term_data.get("related_terms", []),
- alt_labels=term_data.get("alt_labels", []),
- scope_note=term_data.get("scope_note"),
- examples=term_data.get("examples", []),
- metadata=term_data.get("metadata", {})
- )
- vocabulary.add_term(term, top_concept=term_data["uri"] in data.get("top_concepts", []))
-
- # Import ontology connections
- for term_uri, class_uri in data.get("ontology_classes", {}).items():
- vocabulary.ontology_classes[term_uri] = class_uri
-
- self.vocabularies[vocabulary.uri] = vocabulary
- self.logger.info(f"Imported vocabulary: {vocabulary.title}")
-
- return vocabulary
-
- elif format == "skos":
- # SKOS import would require parsing SKOS JSON-LD
- raise NotImplementedError("SKOS import not yet fully implemented")
-
- else:
- raise ValueError(f"Unsupported import format: {format}")
-
- def get_statistics(self) -> Dict[str, Any]:
- """
- Get statistics for all vocabularies.
-
- Returns:
- Statistics dictionary
- """
- stats = {
- "vocabulary_count": len(self.vocabularies),
- "total_terms": sum(len(v.terms) for v in self.vocabularies.values()),
- "vocabularies": {}
- }
-
- for vocab_uri, vocabulary in self.vocabularies.items():
- stats["vocabularies"][vocab_uri] = vocabulary.get_statistics()
-
- return stats