Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
feat: standardize normalize module with methods, registry, and config
KaifAhmad1eaca241e9ac9
diff --git a/semantica/normalize/__init__.py b/semantica/normalize/__init__.pyindex 1a14abe5..438b4512 100644--- a/semantica/normalize/__init__.py+++ b/semantica/normalize/__init__.py@@ -5,6 +5,48 @@ This module provides comprehensive data normalization and cleaning capabilitiesfor the Semantica framework, enabling standardization and quality improvementof various data types.+Algorithms Used:++Text Normalization:+ - Unicode Normalization: NFC, NFD, NFKC, NFKD forms using unicodedata.normalize()+ - Whitespace Normalization: Multiple space to single space (re.sub(r' +', ' ', text)), line break normalization (\\r\\n, \\r, \\n to \\n), tab replacement (\\t to space)+ - Case Normalization: str.lower(), str.upper(), str.title() conversion, case preservation+ - Special Character Processing: Diacritic normalization, punctuation handling, smart quote replacement (\\u2018, \\u2019, \\u201C, \\u201D), dash normalization (\\u2013, \\u2014), ellipsis replacement (\\u2026)+ - Text Cleaning: HTML tag removal (BeautifulSoup/regex fallback), sanitization, special character removal, regex-based pattern matching++Entity Normalization:+ - Alias Resolution: Dictionary-based alias mapping (lowercase key lookup), fuzzy string matching, entity type-based resolution, variant mapping+ - Entity Disambiguation: Context-aware disambiguation, confidence scoring (0.0 to 1.0), candidate ranking, entity type classification (heuristic-based: Person, Organization, Entity)+ - Name Variant Handling: Title/honorific handling (Dr., Mr., etc.), format standardization, regex-based pattern matching, cultural variation handling+ - Entity Linking: Canonical form mapping, batch processing, similarity-based linking, name format normalization (title case for Person entities)++Date/Time Normalization:+ - Date Parsing: dateutil.parser.parse() with fallback to datetime.fromisoformat(), ISO format parsing, multiple format support+ - Timezone Normalization: UTC conversion using datetime.astimezone(), timezone-aware datetime handling, ZoneInfo integration (Python 3.9+), DST transition handling+ - Relative Date Processing: Natural language parsing ("yesterday", "3 days ago", "2 weeks from now"), timedelta calculation, relativedelta for complex expressions, reference date-based calculation+ - Temporal Expression Parsing: Complex temporal expressions, date range parsing ("from X to Y"), pattern matching, relative/absolute date detection++Number/Quantity Normalization:+ - Number Parsing: Comma/space removal (str.replace(',', '').replace(' ', '')), percentage handling (value / 100), scientific notation parsing (float()), decimal point detection+ - Unit Conversion: Unit normalization dictionary lookup, conversion factor calculation (base unit conversion), unit compatibility checking (category validation: length, weight, volume), conversion formula: base_value = value * from_factor, converted_value = base_value / to_factor+ - Currency Processing: Symbol/code normalization (regex-based: $, €, £), currency code extraction (USD, EUR, GBP), amount parsing, default currency assignment+ - Scientific Notation: Exponential notation parsing (float()), mantissa/exponent extraction, 'e'/'E' detection++Data Cleaning:+ - Duplicate Detection: Similarity-based detection (threshold matching), key field comparison, hash-based exact matching, pairwise comparison algorithm, duplicate group formation, average similarity calculation+ - Data Validation: Schema-based validation, type checking (isinstance()), required field validation, constraint checking, error/warning collection+ - Missing Value Handling: Removal (list filtering: [r for r in dataset if all(v is not None for v in r.values())]), filling (default value assignment), imputation (mean/median/mode calculation), strategy-based processing++Language Detection:+ - Multi-language Detection: langdetect.detect() integration, 50+ languages supported, probability-based detection, text length validation+ - Confidence Scoring: langdetect.detect_langs() for probability scores, confidence threshold filtering, top N language detection+ - Batch Processing: Multiple text language detection, result aggregation, language code to name mapping++Encoding Handling:+ - Encoding Detection: chardet.detect() integration, confidence scoring, byte analysis, string-to-bytes conversion for detection+ - UTF-8 Conversion: Fallback encoding chain (latin-1, cp1252, iso-8859-1), error handling strategies (ignore, replace, strict), decode/encode chain: decode(source) -> encode(utf-8) -> decode(utf-8)+ - BOM Removal: UTF-8 BOM detection (\\xef\\xbb\\xbf), UTF-16 BOM detection (\\xff\\xfe, \\xfe\\xff), byte removal, file-based BOM handling+Key Features:- Text normalization and cleaning (Unicode, whitespace, special characters)- Entity name normalization (aliases, variants, disambiguation)@@ -13,18 +55,60 @@ Key Features:- Data cleaning (duplicates, validation, missing values)- Language detection (multi-language support)- Encoding handling (detection, conversion, BOM removal)+ - Method registry for extensibility+ - Configuration management with environment variables and config filesMain Classes:- - TextNormalizer: Text cleaning and normalization- - EntityNormalizer: Entity name normalization- - DateNormalizer: Date and time normalization- - NumberNormalizer: Number and quantity normalization- - DataCleaner: General data cleaning utilities+ - TextNormalizer: Text cleaning and normalization coordinator+ - UnicodeNormalizer: Unicode processing engine+ - WhitespaceNormalizer: Whitespace handling engine+ - SpecialCharacterProcessor: Special character processing engine+ - EntityNormalizer: Entity name normalization coordinator+ - AliasResolver: Entity alias resolution engine+ - EntityDisambiguator: Entity disambiguation engine+ - NameVariantHandler: Name variant processing engine+ - DateNormalizer: Date and time normalization coordinator+ - TimeZoneNormalizer: Time zone processing engine+ - RelativeDateProcessor: Relative date handling engine+ - TemporalExpressionParser: Temporal expression parser+ - NumberNormalizer: Number and quantity normalization coordinator+ - UnitConverter: Unit conversion engine+ - CurrencyNormalizer: Currency processing engine+ - ScientificNotationHandler: Scientific notation processor+ - DataCleaner: General data cleaning utilities coordinator+ - DuplicateDetector: Duplicate detection engine+ - DataValidator: Data validation engine+ - MissingValueHandler: Missing value handling engine- TextCleaner: Text cleaning utilities- - LanguageDetector: Language detection- - EncodingHandler: Encoding detection and conversion+ - LanguageDetector: Language detection coordinator+ - EncodingHandler: Encoding detection and conversion coordinator+ - MethodRegistry: Registry for custom normalization methods+ - NormalizeConfig: Configuration manager for normalize module++Convenience Functions:+ - normalize_text: Text normalization wrapper+ - clean_text: Text cleaning wrapper+ - normalize_entity: Entity normalization wrapper+ - resolve_aliases: Alias resolution wrapper+ - disambiguate_entity: Entity disambiguation wrapper+ - normalize_date: Date normalization wrapper+ - normalize_time: Time normalization wrapper+ - normalize_number: Number normalization wrapper+ - normalize_quantity: Quantity normalization wrapper+ - clean_data: Data cleaning wrapper+ - detect_duplicates: Duplicate detection wrapper+ - detect_language: Language detection wrapper+ - handle_encoding: Encoding handling wrapper+ - get_normalize_method: Get normalization method by name+ - list_available_methods: List registered methodsExample Usage:+ >>> from semantica.normalize import normalize_text, normalize_entity, normalize_date, TextNormalizer+ >>> # Using convenience functions+ >>> text = normalize_text("Hello World", method="default")+ >>> entity = normalize_entity("John Doe", entity_type="Person", method="default")+ >>> date = normalize_date("2023-01-15", method="default")+ >>> # Using classes directly>>> from semantica.normalize import TextNormalizer, EntityNormalizer>>> text_norm = TextNormalizer()>>> normalized = text_norm.normalize_text("Hello World")@@ -35,6 +119,8 @@ Author: Semantica ContributorsLicense: MIT"""+from typing import Any, Dict, List, Optional, Union, Tuple+from .text_normalizer import (TextNormalizer,UnicodeNormalizer,@@ -70,31 +156,79 @@ from .data_cleaner import (from .text_cleaner import TextCleanerfrom .language_detector import LanguageDetectorfrom .encoding_handler import EncodingHandler+from .registry import MethodRegistry, method_registry+from .methods import (+ normalize_text,+ clean_text,+ normalize_entity,+ resolve_aliases,+ disambiguate_entity,+ normalize_date,+ normalize_time,+ normalize_number,+ normalize_quantity,+ clean_data,+ detect_duplicates,+ detect_language,+ handle_encoding,+ get_normalize_method,+ list_available_methods,+)+from .config import NormalizeConfig, normalize_config__all__ = [+ # Text normalization"TextNormalizer","UnicodeNormalizer","WhitespaceNormalizer","SpecialCharacterProcessor",+ # Entity normalization"EntityNormalizer","AliasResolver","EntityDisambiguator","NameVariantHandler",+ # Date/time normalization"DateNormalizer","TimeZoneNormalizer","RelativeDateProcessor","TemporalExpressionParser",+ # Number/quantity normalization"NumberNormalizer","UnitConverter","CurrencyNormalizer","ScientificNotationHandler",+ # Data cleaning"DataCleaner","DuplicateDetector","DataValidator","MissingValueHandler","DuplicateGroup","ValidationResult",+ # Text cleaning"TextCleaner",+ # Language detection"LanguageDetector",+ # Encoding handling"EncodingHandler",+ # Registry and Methods+ "MethodRegistry",+ "method_registry",+ "normalize_text",+ "clean_text",+ "normalize_entity",+ "resolve_aliases",+ "disambiguate_entity",+ "normalize_date",+ "normalize_time",+ "normalize_number",+ "normalize_quantity",+ "clean_data",+ "detect_duplicates",+ "detect_language",+ "handle_encoding",+ "get_normalize_method",+ "list_available_methods",+ # Configuration+ "NormalizeConfig",+ "normalize_config",]diff --git a/semantica/normalize/config.py b/semantica/normalize/config.pynew file mode 100644index 00000000..1dd44a36--- /dev/null+++ b/semantica/normalize/config.py@@ -0,0 +1,161 @@+"""+Configuration Management Module for Normalize++This module provides centralized configuration management for data normalization operations,+supporting multiple configuration sources including environment variables, config files,+and programmatic configuration.++Supported Configuration Sources:+ - Environment variables: NORMALIZE_UNICODE_FORM, NORMALIZE_CASE, NORMALIZE_DATE_FORMAT, etc.+ - Config files: YAML, JSON, TOML formats+ - Programmatic: Python API for setting normalization configurations++Algorithms Used:+ - Environment Variable Parsing: OS-level environment variable access+ - YAML Parsing: YAML parser for configuration file loading+ - JSON Parsing: JSON parser for configuration file loading+ - TOML Parsing: TOML parser for configuration file loading+ - Fallback Chain: Priority-based configuration resolution+ - Dictionary Merging: Deep merge algorithms for configuration updates++Key Features:+ - Environment variable support for normalization parameters+ - Config file support (YAML, JSON, TOML formats)+ - Programmatic configuration via Python API+ - Method-specific configuration management+ - Automatic fallback chain (config file -> environment -> defaults)+ - Global config instance for easy access++Main Classes:+ - NormalizeConfig: Main configuration manager class for normalize module++Example Usage:+ >>> from semantica.normalize.config import normalize_config+ >>> unicode_form = normalize_config.get("unicode_form", default="NFC")+ >>> normalize_config.set("unicode_form", "NFKC")+ >>> method_config = normalize_config.get_method_config("text")+"""++import os+from typing import Optional, Dict, Any+from pathlib import Path++from ..utils.logging import get_logger+++class NormalizeConfig:+ """Configuration manager for normalize module - supports .env files, environment variables, and programmatic config."""++ def __init__(self, config_file: Optional[str] = None):+ self.logger = get_logger("normalize_config")+ self._configs: Dict[str, Any] = {}+ self._method_configs: Dict[str, Dict] = {}+ self._load_config_file(config_file)+ self._load_env_vars()++ def _load_config_file(self, config_file: Optional[str]):+ if config_file and Path(config_file).exists():+ try:+ if config_file.endswith('.yaml') or config_file.endswith('.yml'):+ import yaml+ with open(config_file, 'r') as f:+ data = yaml.safe_load(f) or {}+ self._configs.update(data.get("normalize", {}))+ self._method_configs.update(data.get("normalize_methods", {}))+ elif config_file.endswith('.json'):+ import json+ with open(config_file, 'r') as f:+ data = json.load(f) or {}+ self._configs.update(data.get("normalize", {}))+ self._method_configs.update(data.get("normalize_methods", {}))+ elif config_file.endswith('.toml'):+ import toml+ with open(config_file, 'r') as f:+ data = toml.load(f) or {}+ if "normalize" in data:+ self._configs.update(data["normalize"])+ if "normalize_methods" in data:+ self._method_configs.update(data["normalize_methods"])+ self.logger.info(f"Loaded normalize config from {config_file}")+ except Exception as e:+ self.logger.warning(f"Failed to load config file {config_file}: {e}")++ def _load_env_vars(self):+ env_mappings = {+ "NORMALIZE_UNICODE_FORM": ("unicode_form", str),+ "NORMALIZE_CASE": ("case", str),+ "NORMALIZE_DATE_FORMAT": ("date_format", str),+ "NORMALIZE_TIMEZONE": ("timezone", str),+ "NORMALIZE_DEFAULT_LANGUAGE": ("default_language", str),+ "NORMALIZE_DEFAULT_ENCODING": ("default_encoding", str),+ }++ for env_key, (config_key, type_func) in env_mappings.items():+ value = os.getenv(env_key)+ if value:+ try:+ if type_func == bool:+ self._configs[config_key] = value.lower() in ("true", "1", "yes", "on")+ else:+ self._configs[config_key] = type_func(value)+ except (ValueError, TypeError):+ self.logger.warning(f"Failed to parse {env_key}={value}")++ env_prefix = "NORMALIZE_"+ for key, value in os.environ.items():+ if key.startswith(env_prefix) and key not in env_mappings:+ config_key = key[len(env_prefix):].lower()+ if value.lower() in ('true', 'false'):+ self._configs[config_key] = value.lower() == 'true'+ elif value.isdigit():+ self._configs[config_key] = int(value)+ else:+ try:+ self._configs[config_key] = float(value)+ except ValueError:+ self._configs[config_key] = value++ def set(self, key: str, value: Any):+ """Set configuration value programmatically."""+ self._configs[key] = value++ def get(self, key: str, default: Any = None) -> Any:+ """Get configuration value with fallback chain: config -> env -> default."""+ if key in self._configs:+ return self._configs[key]++ env_key = f"NORMALIZE_{key.upper()}"+ value = os.getenv(env_key)+ if value:+ try:+ if isinstance(default, int):+ return int(value)+ elif isinstance(default, float):+ return float(value)+ elif isinstance(default, bool):+ return value.lower() in ("true", "1", "yes", "on")+ return value+ except (ValueError, TypeError):+ pass++ return default++ def set_method_config(self, method: str, **config):+ """Set method-specific configuration."""+ self._method_configs[method] = config++ def get_method_config(self, method: str) -> Dict:+ """Get method-specific configuration."""+ return self._method_configs.get(method, {})++ def get_all(self) -> Dict[str, Any]:+ """Get all configuration."""+ return {+ "config": self._configs.copy(),+ "method_configs": self._method_configs.copy()+ }+++# Global config instance+normalize_config = NormalizeConfig()+diff --git a/semantica/normalize/methods.py b/semantica/normalize/methods.pynew file mode 100644index 00000000..5582d80e--- /dev/null+++ b/semantica/normalize/methods.py@@ -0,0 +1,799 @@+"""+Data Normalization Methods Module++This module provides all normalization methods as simple, reusable functions for+text normalization, entity normalization, date/time normalization, number/quantity+normalization, data cleaning, language detection, and encoding handling. It supports+multiple approaches and integrates with the method registry for extensibility.++Supported Methods:++Text Normalization:+ - "default": Default text normalization using TextNormalizer+ - "unicode": Unicode-focused normalization+ - "whitespace": Whitespace-focused normalization+ - "case": Case-focused normalization++Entity Normalization:+ - "default": Default entity normalization using EntityNormalizer+ - "alias": Alias resolution only+ - "disambiguate": Disambiguation only+ - "link": Entity linking only++Date/Time Normalization:+ - "default": Default date normalization using DateNormalizer+ - "iso": ISO8601 format normalization+ - "relative": Relative date processing+ - "timezone": Timezone-focused normalization++Number/Quantity Normalization:+ - "default": Default number normalization using NumberNormalizer+ - "quantity": Quantity normalization with units+ - "currency": Currency processing+ - "scientific": Scientific notation handling++Data Cleaning:+ - "default": Default data cleaning using DataCleaner+ - "duplicates": Duplicate detection only+ - "validation": Validation only+ - "missing": Missing value handling only++Language Detection:+ - "default": Default language detection using LanguageDetector+ - "confidence": Detection with confidence scores+ - "batch": Batch language detection++Encoding Handling:+ - "default": Default encoding handling using EncodingHandler+ - "detect": Encoding detection only+ - "convert": Encoding conversion only++Algorithms Used:++Text Normalization:+ - Unicode Normalization: NFC, NFD, NFKC, NFKD forms using unicodedata.normalize()+ - Whitespace Normalization: Multiple space to single space (re.sub), line break normalization (\\r\\n, \\r, \\n)+ - Case Normalization: str.lower(), str.upper(), str.title() conversion+ - Special Character Processing: Diacritic normalization, punctuation handling, regex-based processing+ - Text Cleaning: HTML tag removal (BeautifulSoup/regex fallback), sanitization, special character removal++Entity Normalization:+ - Alias Resolution: Dictionary-based alias mapping, fuzzy string matching, entity type-based resolution+ - Entity Disambiguation: Context-aware disambiguation, confidence scoring, candidate ranking+ - Name Variant Handling: Title/honorific handling (Dr., Mr., etc.), format standardization, regex-based pattern matching+ - Entity Linking: Canonical form mapping, batch processing, similarity-based linking++Date/Time Normalization:+ - Date Parsing: dateutil.parser.parse() with fallback to datetime.fromisoformat(), ISO format parsing+ - Timezone Normalization: UTC conversion using datetime.astimezone(), timezone-aware datetime handling+ - Relative Date Processing: Natural language parsing ("yesterday", "3 days ago"), timedelta calculation, relativedelta for complex expressions+ - Temporal Expression Parsing: Complex temporal expressions, date range parsing, pattern matching++Number/Quantity Normalization:+ - Number Parsing: Comma/space removal (str.replace), percentage handling (value / 100), scientific notation parsing (float())+ - Unit Conversion: Unit normalization dictionary lookup, conversion factor calculation, unit compatibility checking+ - Currency Processing: Symbol/code normalization (regex-based), currency code extraction, amount parsing+ - Scientific Notation: Exponential notation parsing (float()), mantissa/exponent extraction++Data Cleaning:+ - Duplicate Detection: Similarity-based detection (threshold matching), key field comparison, hash-based exact matching+ - Data Validation: Schema-based validation, type checking, required field validation, constraint checking+ - Missing Value Handling: Removal (list filtering), filling (default value assignment), imputation (mean/median/mode calculation)++Language Detection:+ - Multi-language Detection: langdetect.detect() integration, 50+ languages supported, probability-based detection+ - Confidence Scoring: langdetect.detect_langs() for probability scores, confidence threshold filtering+ - Batch Processing: Multiple text language detection, result aggregation++Encoding Handling:+ - Encoding Detection: chardet.detect() integration, confidence scoring, byte analysis+ - UTF-8 Conversion: Fallback encoding chain (latin-1, cp1252, iso-8859-1), error handling strategies (ignore, replace, strict)+ - BOM Removal: UTF-8 BOM detection (\\xef\\xbb\\xbf), UTF-16 BOM detection (\\xff\\xfe, \\xfe\\xff), byte removal++Key Features:+ - Multiple normalization operation methods+ - Normalization with method dispatch+ - Method dispatchers with registry support+ - Custom method registration capability+ - Consistent interface across all methods++Main Functions:+ - normalize_text: Text normalization wrapper+ - clean_text: Text cleaning wrapper+ - normalize_entity: Entity normalization wrapper+ - resolve_aliases: Alias resolution wrapper+ - disambiguate_entity: Entity disambiguation wrapper+ - normalize_date: Date normalization wrapper+ - normalize_time: Time normalization wrapper+ - normalize_number: Number normalization wrapper+ - normalize_quantity: Quantity normalization wrapper+ - clean_data: Data cleaning wrapper+ - detect_duplicates: Duplicate detection wrapper+ - detect_language: Language detection wrapper+ - handle_encoding: Encoding handling wrapper+ - get_normalize_method: Get normalization method by name+ - list_available_methods: List registered methods++Example Usage:+ >>> from semantica.normalize.methods import normalize_text, normalize_entity, normalize_date+ >>> text = normalize_text("Hello World", method="default")+ >>> entity = normalize_entity("John Doe", method="default")+ >>> date = normalize_date("2023-01-15", method="default")+"""++from typing import Any, Dict, List, Optional, Callable, Union, Tuple++from ..utils.logging import get_logger+from ..utils.exceptions import ProcessingError, ConfigurationError+from .text_normalizer import TextNormalizer+from .text_cleaner import TextCleaner+from .entity_normalizer import EntityNormalizer+from .date_normalizer import DateNormalizer+from .number_normalizer import NumberNormalizer+from .data_cleaner import DataCleaner+from .language_detector import LanguageDetector+from .encoding_handler import EncodingHandler+from .registry import method_registry+from .config import normalize_config++logger = get_logger("normalize_methods")+++def normalize_text(+ text: str,+ method: str = "default",+ **kwargs+) -> str:+ """+ Normalize text content (convenience function).++ This is a user-friendly wrapper that normalizes text using the specified method.++ Args:+ text: Input text to normalize+ method: Normalization method (default: "default")+ - "default": Use TextNormalizer with default settings+ - "unicode": Unicode-focused normalization+ - "whitespace": Whitespace-focused normalization+ - "case": Case-focused normalization+ **kwargs: Additional options passed to TextNormalizer+ - unicode_form: Unicode normalization form (NFC, NFD, NFKC, NFKD)+ - case: Case normalization (preserve, lower, upper, title)+ - normalize_diacritics: Whether to normalize diacritics+ - line_break_type: Line break type (unix, windows, mac)++ Returns:+ str: Normalized text++ Examples:+ >>> from semantica.normalize.methods import normalize_text+ >>> normalized = normalize_text("Hello World", method="default")+ >>> lower = normalize_text("Hello World", method="default", case="lower")+ """+ custom_method = method_registry.get("text", method)+ if custom_method:+ try:+ return custom_method(text, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ config = normalize_config.get_method_config("text")+ config.update(kwargs)++ normalizer = TextNormalizer(**config)+ return normalizer.normalize_text(text, **kwargs)++ except Exception as e:+ logger.error(f"Failed to normalize text: {e}")+ raise+++def clean_text(+ text: str,+ method: str = "default",+ **kwargs+) -> str:+ """+ Clean and sanitize text content (convenience function).++ This is a user-friendly wrapper that cleans text using the specified method.++ Args:+ text: Input text to clean+ method: Cleaning method (default: "default")+ **kwargs: Additional options passed to TextCleaner+ - remove_html: Whether to remove HTML tags+ - normalize_whitespace: Whether to normalize whitespace+ - normalize_unicode: Whether to normalize Unicode+ - remove_special_chars: Whether to remove special characters+ - unicode_form: Unicode normalization form++ Returns:+ str: Cleaned text++ Examples:+ >>> from semantica.normalize.methods import clean_text+ >>> cleaned = clean_text("<p>Hello World</p>", method="default", remove_html=True)+ """+ custom_method = method_registry.get("clean", method)+ if custom_method:+ try:+ return custom_method(text, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ config = normalize_config.get_method_config("clean")+ config.update(kwargs)++ cleaner = TextCleaner(**config)+ return cleaner.clean(text, **kwargs)++ except Exception as e:+ logger.error(f"Failed to clean text: {e}")+ raise+++def normalize_entity(+ entity_name: str,+ entity_type: Optional[str] = None,+ method: str = "default",+ **kwargs+) -> str:+ """+ Normalize entity name to standard form (convenience function).++ This is a user-friendly wrapper that normalizes entity names using the specified method.++ Args:+ entity_name: Entity name to normalize+ entity_type: Optional entity type (e.g., "Person", "Organization")+ method: Normalization method (default: "default")+ - "default": Use EntityNormalizer with default settings+ - "alias": Alias resolution only+ - "disambiguate": Disambiguation only+ - "link": Entity linking only+ **kwargs: Additional options passed to EntityNormalizer+ - resolve_aliases: Whether to resolve aliases++ Returns:+ str: Normalized entity name in standard form++ Examples:+ >>> from semantica.normalize.methods import normalize_entity+ >>> normalized = normalize_entity("John Doe", entity_type="Person", method="default")+ """+ custom_method = method_registry.get("entity", method)+ if custom_method:+ try:+ return custom_method(entity_name, entity_type, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ config = normalize_config.get_method_config("entity")+ config.update(kwargs)++ normalizer = EntityNormalizer(**config)+ return normalizer.normalize_entity(entity_name, entity_type=entity_type, **kwargs)++ except Exception as e:+ logger.error(f"Failed to normalize entity: {e}")+ raise+++def resolve_aliases(+ entity_name: str,+ entity_type: Optional[str] = None,+ method: str = "default",+ **kwargs+) -> Optional[str]:+ """+ Resolve entity aliases and variants (convenience function).++ This is a user-friendly wrapper that resolves aliases using the specified method.++ Args:+ entity_name: Entity name to resolve+ entity_type: Optional entity type+ method: Resolution method (default: "default")+ **kwargs: Additional options passed to EntityNormalizer++ Returns:+ Optional[str]: Resolved canonical form if found, None otherwise++ Examples:+ >>> from semantica.normalize.methods import resolve_aliases+ >>> canonical = resolve_aliases("J. Doe", entity_type="Person", method="default")+ """+ custom_method = method_registry.get("entity", method)+ if custom_method:+ try:+ return custom_method(entity_name, entity_type, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ config = normalize_config.get_method_config("entity")+ config.update(kwargs)++ normalizer = EntityNormalizer(**config)+ return normalizer.resolve_aliases(entity_name, entity_type=entity_type, **kwargs)++ except Exception as e:+ logger.error(f"Failed to resolve aliases: {e}")+ raise+++def disambiguate_entity(+ entity_name: str,+ method: str = "default",+ **context+) -> Dict[str, Any]:+ """+ Disambiguate entity when multiple candidates exist (convenience function).++ This is a user-friendly wrapper that disambiguates entities using the specified method.++ Args:+ entity_name: Entity name to disambiguate+ method: Disambiguation method (default: "default")+ **context: Context information (e.g., entity_type, context_text)++ Returns:+ dict: Disambiguation result containing:+ - entity_name: Original entity name+ - entity_type: Detected entity type+ - confidence: Confidence score (0.0 to 1.0)+ - candidates: List of candidate entity names++ Examples:+ >>> from semantica.normalize.methods import disambiguate_entity+ >>> result = disambiguate_entity("John Smith", entity_type="Person", method="default")+ """+ custom_method = method_registry.get("entity", method)+ if custom_method:+ try:+ return custom_method(entity_name, **context)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ config = normalize_config.get_method_config("entity")+ config.update(context)++ normalizer = EntityNormalizer(**config)+ return normalizer.disambiguate_entity(entity_name, **context)++ except Exception as e:+ logger.error(f"Failed to disambiguate entity: {e}")+ raise+++def normalize_date(+ date_input: Any,+ format: str = "ISO8601",+ timezone: str = "UTC",+ method: str = "default",+ **kwargs+) -> str:+ """+ Normalize date to standard format (convenience function).++ This is a user-friendly wrapper that normalizes dates using the specified method.++ Args:+ date_input: Date input (string or datetime object)+ format: Output format (default: "ISO8601")+ - "ISO8601": ISO 8601 format+ - "date": Date only+ - Custom format string (strftime format)+ timezone: Target timezone (default: "UTC")+ method: Normalization method (default: "default")+ - "default": Use DateNormalizer with default settings+ - "iso": ISO8601 format normalization+ - "relative": Relative date processing+ - "timezone": Timezone-focused normalization+ **kwargs: Additional options passed to DateNormalizer++ Returns:+ str: Normalized date string in specified format++ Examples:+ >>> from semantica.normalize.methods import normalize_date+ >>> normalized = normalize_date("2023-01-15", method="default")+ >>> relative = normalize_date("yesterday", method="relative")+ """+ custom_method = method_registry.get("date", method)+ if custom_method:+ try:+ return custom_method(date_input, format, timezone, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ config = normalize_config.get_method_config("date")+ config.update(kwargs)++ normalizer = DateNormalizer(**config)+ return normalizer.normalize_date(date_input, format=format, timezone=timezone, **kwargs)++ except Exception as e:+ logger.error(f"Failed to normalize date: {e}")+ raise+++def normalize_time(+ time_input: Any,+ method: str = "default",+ **kwargs+) -> str:+ """+ Normalize time to standard format (convenience function).++ This is a user-friendly wrapper that normalizes time using the specified method.++ Args:+ time_input: Time input (string or datetime object)+ method: Normalization method (default: "default")+ **kwargs: Additional options passed to DateNormalizer++ Returns:+ str: Normalized time string in ISO format (HH:MM:SS)++ Examples:+ >>> from semantica.normalize.methods import normalize_time+ >>> normalized = normalize_time("10:30:00", method="default")+ """+ custom_method = method_registry.get("date", method)+ if custom_method:+ try:+ return custom_method(time_input, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ config = normalize_config.get_method_config("date")+ config.update(kwargs)++ normalizer = DateNormalizer(**config)+ return normalizer.normalize_time(time_input, **kwargs)++ except Exception as e:+ logger.error(f"Failed to normalize time: {e}")+ raise+++def normalize_number(+ number_input: Union[str, int, float],+ method: str = "default",+ **kwargs+) -> Union[int, float]:+ """+ Normalize number to standard format (convenience function).++ This is a user-friendly wrapper that normalizes numbers using the specified method.++ Args:+ number_input: Number input (string, int, or float)+ method: Normalization method (default: "default")+ - "default": Use NumberNormalizer with default settings+ - "quantity": Quantity normalization with units+ - "currency": Currency processing+ - "scientific": Scientific notation handling+ **kwargs: Additional options passed to NumberNormalizer++ Returns:+ Union[int, float]: Normalized number (int if no decimal, float otherwise)++ Examples:+ >>> from semantica.normalize.methods import normalize_number+ >>> number = normalize_number("1,234.56", method="default")+ >>> percentage = normalize_number("50%", method="default")+ """+ custom_method = method_registry.get("number", method)+ if custom_method:+ try:+ return custom_method(number_input, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ config = normalize_config.get_method_config("number")+ config.update(kwargs)++ normalizer = NumberNormalizer(**config)+ return normalizer.normalize_number(number_input, **kwargs)++ except Exception as e:+ logger.error(f"Failed to normalize number: {e}")+ raise+++def normalize_quantity(+ quantity_input: str,+ method: str = "default",+ **kwargs+) -> Dict[str, Any]:+ """+ Normalize quantity with units (convenience function).++ This is a user-friendly wrapper that normalizes quantities using the specified method.++ Args:+ quantity_input: Quantity string (e.g., "5 kg", "10 meters")+ method: Normalization method (default: "default")+ **kwargs: Additional options passed to NumberNormalizer++ Returns:+ dict: Normalized quantity dictionary containing:+ - value: Numeric value (float)+ - unit: Normalized unit name (str)+ - original: Original quantity string (str)++ Examples:+ >>> from semantica.normalize.methods import normalize_quantity+ >>> quantity = normalize_quantity("5 kg", method="default")+ """+ custom_method = method_registry.get("number", method)+ if custom_method:+ try:+ return custom_method(quantity_input, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ config = normalize_config.get_method_config("number")+ config.update(kwargs)++ normalizer = NumberNormalizer(**config)+ return normalizer.normalize_quantity(quantity_input, **kwargs)++ except Exception as e:+ logger.error(f"Failed to normalize quantity: {e}")+ raise+++def clean_data(+ dataset: List[Dict[str, Any]],+ remove_duplicates: bool = True,+ validate: bool = True,+ handle_missing: bool = True,+ method: str = "default",+ **kwargs+) -> List[Dict[str, Any]]:+ """+ Clean dataset with various cleaning operations (convenience function).++ This is a user-friendly wrapper that cleans data using the specified method.++ Args:+ dataset: List of data record dictionaries+ remove_duplicates: Whether to remove duplicate records (default: True)+ validate: Whether to validate data against schema (default: True)+ handle_missing: Whether to handle missing values (default: True)+ method: Cleaning method (default: "default")+ - "default": Use DataCleaner with default settings+ - "duplicates": Duplicate detection only+ - "validation": Validation only+ - "missing": Missing value handling only+ **kwargs: Additional options passed to DataCleaner+ - missing_strategy: Strategy for missing values ("remove", "fill", "impute")+ - schema: Validation schema dictionary+ - duplicate_criteria: Criteria for duplicate detection++ Returns:+ list: Cleaned dataset (list of record dictionaries)++ Examples:+ >>> from semantica.normalize.methods import clean_data+ >>> cleaned = clean_data(dataset, method="default", remove_duplicates=True)+ """+ custom_method = method_registry.get("clean", method)+ if custom_method:+ try:+ return custom_method(dataset, remove_duplicates, validate, handle_missing, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ config = normalize_config.get_method_config("clean")+ config.update(kwargs)++ cleaner = DataCleaner(**config)+ return cleaner.clean_data(+ dataset,+ remove_duplicates=remove_duplicates,+ validate=validate,+ handle_missing=handle_missing,+ **kwargs+ )++ except Exception as e:+ logger.error(f"Failed to clean data: {e}")+ raise+++def detect_duplicates(+ dataset: List[Dict[str, Any]],+ threshold: Optional[float] = None,+ key_fields: Optional[List[str]] = None,+ method: str = "default",+ **kwargs+) -> List[Any]:+ """+ Detect duplicate records in dataset (convenience function).++ This is a user-friendly wrapper that detects duplicates using the specified method.++ Args:+ dataset: List of data record dictionaries+ threshold: Similarity threshold for duplicates (0.0 to 1.0, optional)+ key_fields: List of field names to use for comparison (optional)+ method: Detection method (default: "default")+ **kwargs: Additional options passed to DataCleaner++ Returns:+ list: List of DuplicateGroup objects++ Examples:+ >>> from semantica.normalize.methods import detect_duplicates+ >>> duplicates = detect_duplicates(dataset, method="default", threshold=0.8)+ """+ custom_method = method_registry.get("clean", method)+ if custom_method:+ try:+ return custom_method(dataset, threshold, key_fields, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ config = normalize_config.get_method_config("clean")+ config.update(kwargs)++ cleaner = DataCleaner(**config)+ return cleaner.detect_duplicates(+ dataset,+ threshold=threshold,+ key_fields=key_fields,+ **kwargs+ )++ except Exception as e:+ logger.error(f"Failed to detect duplicates: {e}")+ raise+++def detect_language(+ text: str,+ method: str = "default",+ **kwargs+) -> Union[str, Tuple[str, float]]:+ """+ Detect language of text (convenience function).++ This is a user-friendly wrapper that detects language using the specified method.++ Args:+ text: Input text to analyze+ method: Detection method (default: "default")+ - "default": Use LanguageDetector with default settings+ - "confidence": Detection with confidence scores+ - "batch": Batch language detection+ **kwargs: Additional options passed to LanguageDetector++ Returns:+ str or tuple: Language code, or (language_code, confidence_score) if method="confidence"++ Examples:+ >>> from semantica.normalize.methods import detect_language+ >>> language = detect_language("Hello world", method="default")+ >>> lang, conf = detect_language("Bonjour", method="confidence")+ """+ custom_method = method_registry.get("language", method)+ if custom_method:+ try:+ return custom_method(text, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ config = normalize_config.get_method_config("language")+ config.update(kwargs)++ detector = LanguageDetector(**config)++ if method == "confidence":+ return detector.detect_with_confidence(text, **kwargs)+ else:+ return detector.detect(text, **kwargs)++ except Exception as e:+ logger.error(f"Failed to detect language: {e}")+ raise+++def handle_encoding(+ data: Union[str, bytes],+ operation: str = "detect",+ method: str = "default",+ **kwargs+) -> Union[Tuple[str, float], str, bytes]:+ """+ Handle encoding detection and conversion (convenience function).++ This is a user-friendly wrapper that handles encoding using the specified method.++ Args:+ data: Input data (string or bytes)+ operation: Operation to perform (default: "detect")+ - "detect": Detect encoding+ - "convert": Convert to UTF-8+ - "remove_bom": Remove BOM+ method: Handling method (default: "default")+ - "default": Use EncodingHandler with default settings+ - "detect": Encoding detection only+ - "convert": Encoding conversion only+ **kwargs: Additional options passed to EncodingHandler+ - source_encoding: Source encoding for conversion+ - target_encoding: Target encoding (default: "utf-8")++ Returns:+ tuple, str, or bytes: Result depends on operation:+ - "detect": (encoding_name, confidence_score)+ - "convert": UTF-8 string or bytes+ - "remove_bom": Data with BOM removed++ Examples:+ >>> from semantica.normalize.methods import handle_encoding+ >>> encoding, confidence = handle_encoding(data, operation="detect", method="default")+ >>> utf8_text = handle_encoding(data, operation="convert", method="default")+ """+ custom_method = method_registry.get("encoding", method)+ if custom_method:+ try:+ return custom_method(data, operation, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ config = normalize_config.get_method_config("encoding")+ config.update(kwargs)++ handler = EncodingHandler(**config)++ if operation == "detect":+ return handler.detect(data, **kwargs)+ elif operation == "convert":+ source_encoding = kwargs.get("source_encoding")+ return handler.convert_to_utf8(data, source_encoding=source_encoding, **kwargs)+ elif operation == "remove_bom":+ return handler.remove_bom(data, **kwargs)+ else:+ raise ValueError(f"Unknown operation: {operation}")++ except Exception as e:+ logger.error(f"Failed to handle encoding: {e}")+ raise+++def get_normalize_method(task: str, name: str) -> Optional[Callable]:+ """Get normalization method by task and name."""+ return method_registry.get(task, name)+++def list_available_methods(task: Optional[str] = None) -> Dict[str, List[str]]:+ """List all registered normalization methods."""+ return method_registry.list_all(task)+++# Register default methods+method_registry.register("text", "default", normalize_text)+method_registry.register("clean", "default", clean_text)+method_registry.register("entity", "default", normalize_entity)+method_registry.register("date", "default", normalize_date)+method_registry.register("number", "default", normalize_number)+method_registry.register("language", "default", detect_language)+method_registry.register("encoding", "default", handle_encoding)+diff --git a/semantica/normalize/normalize_usage.md b/semantica/normalize/normalize_usage.mdnew file mode 100644index 00000000..b4cb6478--- /dev/null+++ b/semantica/normalize/normalize_usage.md@@ -0,0 +1,1172 @@+# Data Normalization Module Usage Guide++This comprehensive guide demonstrates how to use the data normalization module for text normalization, entity normalization, date/time normalization, number/quantity normalization, data cleaning, language detection, and encoding handling.++## Table of Contents++1. [Basic Usage](#basic-usage)+2. [Text Normalization](#text-normalization)+3. [Entity Normalization](#entity-normalization)+4. [Date/Time Normalization](#datetime-normalization)+5. [Number/Quantity Normalization](#numberquantity-normalization)+6. [Data Cleaning](#data-cleaning)+7. [Language Detection](#language-detection)+8. [Encoding Handling](#encoding-handling)+9. [Using Methods](#using-methods)+10. [Using Registry](#using-registry)+11. [Configuration](#configuration)+12. [Advanced Examples](#advanced-examples)++## Basic Usage++### Using the Convenience Functions++```python+from semantica.normalize import normalize_text, normalize_entity, normalize_date++# Normalize text+text = normalize_text("Hello World", method="default")+print(f"Normalized: {text}")++# Normalize entity+entity = normalize_entity("John Doe", entity_type="Person", method="default")+print(f"Normalized entity: {entity}")++# Normalize date+date = normalize_date("2023-01-15", method="default")+print(f"Normalized date: {date}")+```++### Using Main Classes++```python+from semantica.normalize import TextNormalizer, EntityNormalizer, DateNormalizer++# Create normalizers+text_norm = TextNormalizer()+entity_norm = EntityNormalizer()+date_norm = DateNormalizer()++# Normalize text+normalized_text = text_norm.normalize_text("Hello World", case="lower")++# Normalize entity+normalized_entity = entity_norm.normalize_entity("John Doe", entity_type="Person")++# Normalize date+normalized_date = date_norm.normalize_date("2023-01-15", format="ISO8601")+```++## Text Normalization++### Basic Text Normalization++```python+from semantica.normalize import normalize_text, TextNormalizer++# Using convenience function+normalized = normalize_text("Hello World", method="default")+print(f"Normalized: {normalized}")++# Using class directly+normalizer = TextNormalizer()+normalized = normalizer.normalize_text("Hello World", case="lower")+```++### Unicode Normalization++```python+from semantica.normalize import normalize_text, UnicodeNormalizer++# Normalize with different Unicode forms+nfc = normalize_text("café", method="default", unicode_form="NFC")+nfd = normalize_text("café", method="default", unicode_form="NFD")+nfkc = normalize_text("café", method="default", unicode_form="NFKC")+nfkd = normalize_text("café", method="default", unicode_form="NFKD")++# Using UnicodeNormalizer directly+unicode_norm = UnicodeNormalizer()+normalized = unicode_norm.normalize_unicode("café", form="NFC")+```++### Whitespace Normalization++```python+from semantica.normalize import normalize_text, WhitespaceNormalizer++# Normalize whitespace+normalized = normalize_text(+ "Hello World\n\nTest",+ method="default",+ line_break_type="unix"+)++# Using WhitespaceNormalizer directly+whitespace_norm = WhitespaceNormalizer()+normalized = whitespace_norm.normalize_whitespace(+ "Hello World",+ line_break_type="unix"+)+```++### Case Normalization++```python+from semantica.normalize import normalize_text++# Lowercase+lower = normalize_text("Hello World", method="default", case="lower")++# Uppercase+upper = normalize_text("Hello World", method="default", case="upper")++# Title case+title = normalize_text("hello world", method="default", case="title")++# Preserve case+preserved = normalize_text("Hello World", method="default", case="preserve")+```++### Special Character Processing++```python+from semantica.normalize import normalize_text, SpecialCharacterProcessor++# Normalize with special character processing+normalized = normalize_text(+ "Hello—World",+ method="default",+ normalize_diacritics=True+)++# Using SpecialCharacterProcessor directly+char_processor = SpecialCharacterProcessor()+processed = char_processor.process_special_chars("Hello—World")+```++### Text Cleaning++```python+from semantica.normalize import clean_text, TextCleaner++# Using convenience function+cleaned = clean_text(+ "<p>Hello World</p>",+ method="default",+ remove_html=True,+ normalize_whitespace=True+)++# Using TextCleaner directly+cleaner = TextCleaner()+cleaned = cleaner.clean(+ "<p>Hello World</p>",+ remove_html=True,+ normalize_unicode=True+)+```++### Batch Text Processing++```python+from semantica.normalize import TextNormalizer++normalizer = TextNormalizer()++texts = [+ "Hello World",+ "Test Text",+ "Another Example"+]++# Process batch+normalized_texts = normalizer.process_batch(texts, case="lower")+for text in normalized_texts:+ print(text)+```++## Entity Normalization++### Basic Entity Normalization++```python+from semantica.normalize import normalize_entity, EntityNormalizer++# Using convenience function+normalized = normalize_entity(+ "John Doe",+ entity_type="Person",+ method="default"+)++# Using class directly+normalizer = EntityNormalizer()+normalized = normalizer.normalize_entity("John Doe", entity_type="Person")+```++### Alias Resolution++```python+from semantica.normalize import resolve_aliases, AliasResolver++# Using convenience function+canonical = resolve_aliases(+ "J. Doe",+ entity_type="Person",+ method="default"+)++# Using AliasResolver directly+resolver = AliasResolver(alias_map={"j. doe": "John Doe"})+canonical = resolver.resolve_aliases("J. Doe", entity_type="Person")+```++### Entity Disambiguation++```python+from semantica.normalize import disambiguate_entity, EntityDisambiguator++# Using convenience function+result = disambiguate_entity(+ "Apple",+ method="default",+ entity_type="Organization",+ context="technology company"+)++print(f"Entity: {result['entity_name']}")+print(f"Type: {result['entity_type']}")+print(f"Confidence: {result['confidence']}")+print(f"Candidates: {result['candidates']}")++# Using EntityDisambiguator directly+disambiguator = EntityDisambiguator()+result = disambiguator.disambiguate("Apple", entity_type="Organization")+```++### Entity Linking++```python+from semantica.normalize import EntityNormalizer++normalizer = EntityNormalizer()++entities = [+ "John Doe",+ "J. Doe",+ "Johnny Doe"+]++# Link entities to canonical forms+linked = normalizer.link_entities(entities, entity_type="Person")+for original, canonical in linked.items():+ print(f"{original} -> {canonical}")+```++### Name Variant Handling++```python+from semantica.normalize import EntityNormalizer, NameVariantHandler++normalizer = EntityNormalizer()++# Normalize with variant handling+normalized = normalizer.normalize_entity(+ "Dr. John Doe",+ entity_type="Person"+)++# Using NameVariantHandler directly+variant_handler = NameVariantHandler()+normalized = variant_handler.normalize_name_format(+ "Dr. John Doe",+ format_type="standard"+)+```++## Date/Time Normalization++### Basic Date Normalization++```python+from semantica.normalize import normalize_date, DateNormalizer++# Using convenience function+normalized = normalize_date("2023-01-15", method="default")+print(f"Normalized: {normalized}")++# Using class directly+normalizer = DateNormalizer()+normalized = normalizer.normalize_date("2023-01-15", format="ISO8601")+```++### Different Date Formats++```python+from semantica.normalize import normalize_date++# ISO8601 format+iso_date = normalize_date("2023-01-15", format="ISO8601", method="default")++# Date only+date_only = normalize_date("2023-01-15", format="date", method="default")++# Custom format+custom = normalize_date("2023-01-15", format="%Y-%m-%d", method="default")+```++### Timezone Normalization++```python+from semantica.normalize import normalize_date, TimeZoneNormalizer++# Normalize with timezone+normalized = normalize_date(+ "2023-01-15T10:30:00",+ timezone="America/New_York",+ method="default"+)++# Using TimeZoneNormalizer directly+tz_norm = TimeZoneNormalizer()+from datetime import datetime+dt = datetime(2023, 1, 15, 10, 30, 0)+utc_dt = tz_norm.convert_to_utc(dt)+```++### Relative Date Processing++```python+from semantica.normalize import normalize_date, RelativeDateProcessor++# Process relative dates+yesterday = normalize_date("yesterday", method="relative")+three_days_ago = normalize_date("3 days ago", method="relative")+next_week = normalize_date("next week", method="relative")++# Using RelativeDateProcessor directly+relative_processor = RelativeDateProcessor()+dt = relative_processor.process_relative_expression("3 days ago")+```++### Time Normalization++```python+from semantica.normalize import normalize_time, DateNormalizer++# Normalize time+normalized = normalize_time("10:30:00", method="default")+print(f"Normalized time: {normalized}")++# Using DateNormalizer directly+normalizer = DateNormalizer()+normalized = normalizer.normalize_time("10:30 AM")+```++### Temporal Expression Parsing++```python+from semantica.normalize import DateNormalizer, TemporalExpressionParser++normalizer = DateNormalizer()++# Parse temporal expressions+result = normalizer.parse_temporal_expression("from January to March")+print(f"Date range: {result.get('range')}")++# Using TemporalExpressionParser directly+parser = TemporalExpressionParser()+result = parser.parse_temporal_expression("last week")+```++## Number/Quantity Normalization++### Basic Number Normalization++```python+from semantica.normalize import normalize_number, NumberNormalizer++# Using convenience function+number = normalize_number("1,234.56", method="default")+print(f"Normalized: {number}")++# Using class directly+normalizer = NumberNormalizer()+number = normalizer.normalize_number("1,234.56")+```++### Percentage Handling++```python+from semantica.normalize import normalize_number++# Normalize percentage+percentage = normalize_number("50%", method="default")+print(f"Percentage as decimal: {percentage}") # 0.5+```++### Scientific Notation++```python+from semantica.normalize import normalize_number, ScientificNotationHandler++# Normalize scientific notation+number = normalize_number("1.5e3", method="default")+print(f"Normalized: {number}") # 1500.0++# Using ScientificNotationHandler directly+sci_handler = ScientificNotationHandler()+parsed = sci_handler.parse_scientific_notation("1.5e3")+```++### Quantity Normalization++```python+from semantica.normalize import normalize_quantity, NumberNormalizer++# Using convenience function+quantity = normalize_quantity("5 kg", method="default")+print(f"Value: {quantity['value']}, Unit: {quantity['unit']}")++# Using class directly+normalizer = NumberNormalizer()+quantity = normalizer.normalize_quantity("10 meters")+```++### Unit Conversion++```python+from semantica.normalize import NumberNormalizer, UnitConverter++normalizer = NumberNormalizer()++# Convert units+converted = normalizer.convert_units(100, "kg", "pound")+print(f"100 kg = {converted} pounds")++# Using UnitConverter directly+converter = UnitConverter()+converted = converter.convert_units(1, "kilometer", "mile")+```++### Currency Processing++```python+from semantica.normalize import NumberNormalizer, CurrencyNormalizer++normalizer = NumberNormalizer()++# Process currency+currency = normalizer.process_currency("$100", default_currency="USD")+print(f"Amount: {currency['amount']}, Currency: {currency['currency']}")++# Using CurrencyNormalizer directly+currency_norm = CurrencyNormalizer()+currency = currency_norm.normalize_currency("€50", default_currency="EUR")+```++## Data Cleaning++### Basic Data Cleaning++```python+from semantica.normalize import clean_data, DataCleaner++dataset = [+ {"id": 1, "name": "Alice", "age": 30},+ {"id": 2, "name": "Bob", "age": None},+ {"id": 1, "name": "Alice", "age": 30}, # Duplicate+]++# Using convenience function+cleaned = clean_data(+ dataset,+ remove_duplicates=True,+ validate=True,+ handle_missing=True,+ method="default"+)++# Using class directly+cleaner = DataCleaner()+cleaned = cleaner.clean_data(+ dataset,+ remove_duplicates=True,+ handle_missing=True+)+```++### Duplicate Detection++```python+from semantica.normalize import detect_duplicates, DuplicateDetector++dataset = [+ {"id": 1, "name": "Alice"},+ {"id": 2, "name": "Bob"},+ {"id": 1, "name": "Alice"}, # Duplicate+]++# Using convenience function+duplicates = detect_duplicates(+ dataset,+ threshold=0.8,+ method="default"+)++for group in duplicates:+ print(f"Duplicate group: {len(group.records)} records")+ print(f"Similarity: {group.similarity_score}")++# Using DuplicateDetector directly+detector = DuplicateDetector(similarity_threshold=0.8)+duplicates = detector.detect_duplicates(dataset, key_fields=["id", "name"])+```++### Data Validation++```python+from semantica.normalize import DataCleaner, DataValidator++schema = {+ "fields": {+ "id": {"type": int, "required": True},+ "name": {"type": str, "required": True},+ "age": {"type": int, "required": False}+ }+}++dataset = [+ {"id": 1, "name": "Alice", "age": 30},+ {"id": 2, "name": "Bob"}, # Missing age (optional)+ {"id": None, "name": "Charlie"}, # Missing required id+]++# Validate data+cleaner = DataCleaner()+validation = cleaner.validate_data(dataset, schema)++if not validation.valid:+ print(f"Validation errors: {len(validation.errors)}")+ for error in validation.errors:+ print(f" {error}")++# Using DataValidator directly+validator = DataValidator()+validation = validator.validate_dataset(dataset, schema)+```++### Missing Value Handling++```python+from semantica.normalize import DataCleaner, MissingValueHandler++dataset = [+ {"id": 1, "name": "Alice", "age": 30},+ {"id": 2, "name": "Bob", "age": None},+ {"id": 3, "name": None, "age": 25},+]++# Handle missing values with different strategies+cleaner = DataCleaner()++# Remove records with missing values+cleaned_remove = cleaner.handle_missing_values(dataset, strategy="remove")++# Fill missing values+cleaned_fill = cleaner.handle_missing_values(+ dataset,+ strategy="fill",+ fill_value="Unknown"+)++# Impute missing values+cleaned_impute = cleaner.handle_missing_values(+ dataset,+ strategy="impute",+ method="mean"+)++# Using MissingValueHandler directly+handler = MissingValueHandler()+cleaned = handler.handle_missing_values(dataset, strategy="remove")+```++## Language Detection++### Basic Language Detection++```python+from semantica.normalize import detect_language, LanguageDetector++# Using convenience function+language = detect_language("Hello world", method="default")+print(f"Detected language: {language}")++# Using class directly+detector = LanguageDetector()+language = detector.detect("Bonjour le monde")+```++### Detection with Confidence++```python+from semantica.normalize import detect_language++# Detect with confidence score+lang, confidence = detect_language(+ "Bonjour le monde",+ method="confidence"+)++print(f"Language: {lang}, Confidence: {confidence:.2f}")+```++### Multiple Language Detection++```python+from semantica.normalize import LanguageDetector++detector = LanguageDetector()++# Detect top N languages+languages = detector.detect_multiple(+ "Hello world. Bonjour le monde.",+ top_n=3+)++for lang, conf in languages:+ print(f"{lang}: {conf:.2f}")+```++### Language Validation++```python+from semantica.normalize import LanguageDetector++detector = LanguageDetector()++# Check if text is in specific language+is_english = detector.is_language("Hello world", "en")+is_french = detector.is_language("Bonjour", "fr")++print(f"Is English: {is_english}")+print(f"Is French: {is_french}")+```++## Encoding Handling++### Encoding Detection++```python+from semantica.normalize import handle_encoding, EncodingHandler++# Using convenience function+encoding, confidence = handle_encoding(+ data,+ operation="detect",+ method="default"+)++print(f"Encoding: {encoding}, Confidence: {confidence:.2f}")++# Using EncodingHandler directly+handler = EncodingHandler()+encoding, confidence = handler.detect(data)+```++### UTF-8 Conversion++```python+from semantica.normalize import handle_encoding, EncodingHandler++# Convert to UTF-8+utf8_text = handle_encoding(+ data,+ operation="convert",+ method="default",+ source_encoding="latin-1"+)++# Using EncodingHandler directly+handler = EncodingHandler()+utf8_text = handler.convert_to_utf8(data, source_encoding="latin-1")+```++### BOM Removal++```python+from semantica.normalize import handle_encoding, EncodingHandler++# Remove BOM+cleaned = handle_encoding(+ data,+ operation="remove_bom",+ method="default"+)++# Using EncodingHandler directly+handler = EncodingHandler()+cleaned = handler.remove_bom(data)+```++### File Encoding Conversion++```python+from semantica.normalize import EncodingHandler++handler = EncodingHandler()++# Convert file to UTF-8+handler.convert_file_to_utf8("input.txt", "output.txt")++# Detect file encoding+encoding, confidence = handler.detect_file("input.txt")+print(f"File encoding: {encoding}")+```++## Using Methods++### Getting Available Methods++```python+from semantica.normalize.methods import get_normalize_method, list_available_methods++# List all available methods+all_methods = list_available_methods()+print("Available methods:", all_methods)++# List methods for specific task+text_methods = list_available_methods("text")+print("Text normalization methods:", text_methods)++# Get specific method+normalize_method = get_normalize_method("text", "default")+if normalize_method:+ result = normalize_method("Hello World")+```++### Method Examples++```python+from semantica.normalize.methods import (+ normalize_text,+ clean_text,+ normalize_entity,+ resolve_aliases,+ disambiguate_entity,+ normalize_date,+ normalize_time,+ normalize_number,+ normalize_quantity,+ clean_data,+ detect_duplicates,+ detect_language,+ handle_encoding+)++# Text normalization+text = normalize_text("Hello World", method="default")++# Text cleaning+cleaned = clean_text("<p>Hello</p>", method="default", remove_html=True)++# Entity normalization+entity = normalize_entity("John Doe", entity_type="Person", method="default")++# Alias resolution+canonical = resolve_aliases("J. Doe", entity_type="Person", method="default")++# Entity disambiguation+result = disambiguate_entity("Apple", method="default", entity_type="Organization")++# Date normalization+date = normalize_date("2023-01-15", method="default")++# Time normalization+time = normalize_time("10:30:00", method="default")++# Number normalization+number = normalize_number("1,234.56", method="default")++# Quantity normalization+quantity = normalize_quantity("5 kg", method="default")++# Data cleaning+cleaned = clean_data(dataset, method="default", remove_duplicates=True)++# Duplicate detection+duplicates = detect_duplicates(dataset, method="default", threshold=0.8)++# Language detection+language = detect_language("Hello world", method="default")++# Encoding handling+encoding, confidence = handle_encoding(data, operation="detect", method="default")+```++## Using Registry++### Registering Custom Methods++```python+from semantica.normalize.registry import method_registry++# Custom text normalization method+def custom_text_normalization(text, **kwargs):+ """Custom normalization logic."""+ # Your custom normalization code+ return text.upper().strip()++# Register custom method+method_registry.register("text", "custom_upper", custom_text_normalization)++# Use custom method+from semantica.normalize.methods import get_normalize_method+custom_method = get_normalize_method("text", "custom_upper")+result = custom_method("hello world")+```++### Listing Registered Methods++```python+from semantica.normalize.registry import method_registry++# List all registered methods+all_methods = method_registry.list_all()+print("Registered methods:", all_methods)++# List methods for specific task+text_methods = method_registry.list_all("text")+print("Text methods:", text_methods)++entity_methods = method_registry.list_all("entity")+print("Entity methods:", entity_methods)+```++### Unregistering Methods++```python+from semantica.normalize.registry import method_registry++# Unregister a method+method_registry.unregister("text", "custom_upper")++# Clear all methods for a task+method_registry.clear("text")++# Clear all methods+method_registry.clear()+```++## Configuration++### Using Configuration Manager++```python+from semantica.normalize.config import normalize_config++# Get configuration values+unicode_form = normalize_config.get("unicode_form", default="NFC")+case = normalize_config.get("case", default="preserve")+date_format = normalize_config.get("date_format", default="ISO8601")+timezone = normalize_config.get("timezone", default="UTC")++# Set configuration values+normalize_config.set("unicode_form", "NFKC")+normalize_config.set("case", "lower")++# Method-specific configuration+normalize_config.set_method_config("text", unicode_form="NFC", case="lower")+text_config = normalize_config.get_method_config("text")++# Get all configuration+all_config = normalize_config.get_all()+print("All config:", all_config)+```++### Environment Variables++```bash+# Set environment variables+export NORMALIZE_UNICODE_FORM=NFC+export NORMALIZE_CASE=lower+export NORMALIZE_DATE_FORMAT=ISO8601+export NORMALIZE_TIMEZONE=UTC+export NORMALIZE_DEFAULT_LANGUAGE=en+export NORMALIZE_DEFAULT_ENCODING=utf-8+```++### Configuration File++```yaml+# config.yaml+normalize:+ unicode_form: NFC+ case: lower+ date_format: ISO8601+ timezone: UTC+ default_language: en+ default_encoding: utf-8++normalize_methods:+ text:+ unicode_form: NFC+ case: lower+ entity:+ resolve_aliases: true+ date:+ format: ISO8601+ timezone: UTC+```++```python+from semantica.normalize.config import NormalizeConfig++# Load from config file+config = NormalizeConfig(config_file="config.yaml")+unicode_form = config.get("unicode_form")+```++## Advanced Examples++### Complete Normalization Pipeline++```python+from semantica.normalize import (+ normalize_text,+ normalize_entity,+ normalize_date,+ normalize_number,+ clean_data+)++# Step 1: Normalize text+text = normalize_text("Hello World", method="default", case="lower")++# Step 2: Normalize entities+entities = ["John Doe", "J. Doe", "Johnny Doe"]+normalized_entities = [+ normalize_entity(e, entity_type="Person", method="default")+ for e in entities+]++# Step 3: Normalize dates+dates = ["2023-01-15", "yesterday", "3 days ago"]+normalized_dates = [+ normalize_date(d, method="default") for d in dates+]++# Step 4: Normalize numbers+numbers = ["1,234.56", "50%", "1.5e3"]+normalized_numbers = [+ normalize_number(n, method="default") for n in numbers+]++# Step 5: Clean dataset+dataset = [+ {"id": 1, "name": "Alice", "date": "2023-01-15"},+ {"id": 2, "name": "Bob", "date": "yesterday"},+]+cleaned = clean_data(dataset, method="default", remove_duplicates=True)+```++### Custom Normalization Workflow++```python+from semantica.normalize import (+ TextNormalizer,+ EntityNormalizer,+ DateNormalizer,+ NumberNormalizer,+ DataCleaner+)++# Create normalizers with custom config+text_norm = TextNormalizer(unicode_form="NFKC", case="lower")+entity_norm = EntityNormalizer(alias_map={"j. doe": "John Doe"})+date_norm = DateNormalizer()+number_norm = NumberNormalizer()+cleaner = DataCleaner(similarity_threshold=0.85)++# Normalize text+text = text_norm.normalize_text("Hello World")++# Normalize entities+entity = entity_norm.normalize_entity("J. Doe", entity_type="Person")++# Normalize dates+date = date_norm.normalize_date("2023-01-15", format="ISO8601")++# Normalize numbers+number = number_norm.normalize_number("1,234.56")++# Clean data+cleaned = cleaner.clean_data(dataset, remove_duplicates=True)+```++### Batch Processing++```python+from semantica.normalize import TextNormalizer, EntityNormalizer++text_norm = TextNormalizer()+entity_norm = EntityNormalizer()++# Batch text normalization+texts = ["Hello World", "Test Text", "Another Example"]+normalized_texts = text_norm.process_batch(texts, case="lower")++# Batch entity normalization+entities = ["John Doe", "Jane Smith", "Bob Johnson"]+normalized_entities = [+ entity_norm.normalize_entity(e, entity_type="Person")+ for e in entities+]+```++### Integration with Other Modules++```python+from semantica.normalize import normalize_text, normalize_entity+from semantica.kg import build++# Normalize text before KG building+text = normalize_text("Apple Inc. was founded by Steve Jobs", method="default")++# Normalize entities before adding to KG+entities = [+ normalize_entity("Apple Inc.", entity_type="Organization", method="default"),+ normalize_entity("Steve Jobs", entity_type="Person", method="default")+]++# Build knowledge graph with normalized data+kg = build(sources=[{"entities": entities, "relationships": []}])+```++### Custom Validation Rules++```python+from semantica.normalize import DataCleaner, DataValidator++cleaner = DataCleaner()++# Custom validation schema+schema = {+ "fields": {+ "id": {"type": int, "required": True},+ "name": {"type": str, "required": True, "min_length": 2},+ "age": {"type": int, "required": False, "min": 0, "max": 150}+ }+}++dataset = [+ {"id": 1, "name": "Alice", "age": 30},+ {"id": 2, "name": "B", "age": 200}, # Invalid: name too short, age out of range+]++# Validate+validation = cleaner.validate_data(dataset, schema)+if not validation.valid:+ for error in validation.errors:+ print(f"Error: {error}")+```++### Language-Aware Normalization++```python+from semantica.normalize import (+ normalize_text,+ detect_language,+ LanguageDetector+)++detector = LanguageDetector()++# Detect language first+text = "Bonjour le monde"+language, confidence = detector.detect_with_confidence(text)++# Normalize based on language+if language == "fr":+ normalized = normalize_text(text, method="default", case="preserve")+else:+ normalized = normalize_text(text, method="default", case="lower")+```++### Encoding-Aware Text Processing++```python+from semantica.normalize import (+ handle_encoding,+ normalize_text,+ EncodingHandler+)++handler = EncodingHandler()++# Detect and convert encoding+data = b'\xff\xfeH\x00e\x00l\x00l\x00o\x00' # UTF-16 LE with BOM+encoding, confidence = handler.detect(data)+utf8_text = handler.convert_to_utf8(data, source_encoding=encoding)++# Normalize text after encoding conversion+normalized = normalize_text(utf8_text, method="default")+```++### Comprehensive Data Cleaning Pipeline++```python+from semantica.normalize import (+ clean_data,+ detect_duplicates,+ normalize_text,+ normalize_date,+ DataCleaner+)++# Raw dataset+raw_dataset = [+ {"id": 1, "name": " Alice ", "date": "2023-01-15"},+ {"id": 2, "name": "Bob", "date": "yesterday"},+ {"id": 1, "name": "Alice", "date": "2023-01-15"}, # Duplicate+ {"id": 3, "name": None, "date": "2023-01-20"}, # Missing name+]++# Step 1: Normalize text fields+for record in raw_dataset:+ if record.get("name"):+ record["name"] = normalize_text(record["name"], method="default")++# Step 2: Normalize dates+for record in raw_dataset:+ if record.get("date"):+ record["date"] = normalize_date(record["date"], method="default")++# Step 3: Clean data+cleaner = DataCleaner()+cleaned = cleaner.clean_data(+ raw_dataset,+ remove_duplicates=True,+ handle_missing=True,+ missing_strategy="remove"+)++print(f"Cleaned {len(raw_dataset)} -> {len(cleaned)} records")+```++## Best Practices++1. **Unicode Normalization**: Always use NFC form for most use cases, NFKC for compatibility+2. **Case Handling**: Preserve case when possible, normalize only when necessary+3. **Entity Normalization**: Provide entity_type when available for better normalization+4. **Date Parsing**: Use ISO8601 format for consistency, handle timezones explicitly+5. **Number Parsing**: Be aware of locale-specific formatting (commas vs periods)+6. **Data Cleaning**: Validate data before cleaning, use appropriate strategies+7. **Language Detection**: Ensure minimum text length (10+ characters) for reliable detection+8. **Encoding Handling**: Always detect encoding before conversion, use fallback chain+9. **Batch Processing**: Use batch methods for large datasets to improve performance+10. **Configuration**: Use configuration files for consistent settings across environments+11. **Error Handling**: Always handle ValidationError and ProcessingError exceptions+12. **Method Registry**: Register custom methods for domain-specific normalization needs+diff --git a/semantica/normalize/registry.py b/semantica/normalize/registry.pynew file mode 100644index 00000000..96a1de0d--- /dev/null+++ b/semantica/normalize/registry.py@@ -0,0 +1,132 @@+"""+Method Registry Module for Normalize++This module provides a method registry system for registering custom normalization methods,+enabling extensibility and community contributions to the normalization toolkit.++Supported Registration Types:+ - Method Registry: Register custom normalization methods for:+ * "text": Text normalization methods+ * "entity": Entity normalization methods+ * "date": Date/time normalization methods+ * "number": Number/quantity normalization methods+ * "clean": Data cleaning methods+ * "language": Language detection methods+ * "encoding": Encoding handling methods++Algorithms Used:+ - Registry Pattern: Dictionary-based registration and lookup+ - Dynamic Registration: Runtime function registration+ - Type Checking: Type validation for registered components+ - Lookup Algorithms: Hash-based O(1) lookup for methods+ - Task-based Organization: Hierarchical organization by task type++Key Features:+ - Method registry for custom normalization methods+ - Task-based method organization (text, entity, date, number, clean, language, encoding)+ - Dynamic registration and unregistration+ - Easy discovery of available methods+ - Support for community-contributed extensions++Main Classes:+ - MethodRegistry: Registry for custom normalization methods++Global Instances:+ - method_registry: Global method registry instance++Example Usage:+ >>> from semantica.normalize.registry import method_registry+ >>> method_registry.register("text", "custom_method", custom_text_normalization_function)+ >>> available = method_registry.list_all("text")+"""++from typing import Dict, Callable, Any, List, Optional+++class MethodRegistry:+ """Registry for custom normalization methods."""++ _methods: Dict[str, Dict[str, Callable]] = {+ "text": {},+ "entity": {},+ "date": {},+ "number": {},+ "clean": {},+ "language": {},+ "encoding": {},+ }++ @classmethod+ def register(cls, task: str, name: str, method_func: Callable):+ """+ Register a custom normalization method.++ Args:+ task: Task type ("text", "entity", "date", "number", "clean", "language", "encoding")+ name: Method name+ method_func: Method function+ """+ if task not in cls._methods:+ cls._methods[task] = {}+ cls._methods[task][name] = method_func++ @classmethod+ def get(cls, task: str, name: str) -> Optional[Callable]:+ """+ Get method by task and name.++ Args:+ task: Task type ("text", "entity", "date", "number", "clean", "language", "encoding")+ name: Method name++ Returns:+ Method function or None+ """+ return cls._methods.get(task, {}).get(name)++ @classmethod+ def list_all(cls, task: Optional[str] = None) -> Dict[str, List[str]]:+ """+ List all registered methods.++ Args:+ task: Optional task type to filter by++ Returns:+ Dictionary mapping task types to method names+ """+ if task:+ return {task: list(cls._methods.get(task, {}).keys())}+ return {t: list(m.keys()) for t, m in cls._methods.items()}++ @classmethod+ def unregister(cls, task: str, name: str):+ """+ Unregister a method.++ Args:+ task: Task type ("text", "entity", "date", "number", "clean", "language", "encoding")+ name: Method name+ """+ if task in cls._methods and name in cls._methods[task]:+ del cls._methods[task][name]++ @classmethod+ def clear(cls, task: Optional[str] = None):+ """+ Clear all registered methods for a task or all tasks.++ Args:+ task: Optional task type to clear (clears all if None)+ """+ if task:+ if task in cls._methods:+ cls._methods[task].clear()+ else:+ for task_dict in cls._methods.values():+ task_dict.clear()+++# Global registry+method_registry = MethodRegistry()+