Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

docs(normalize): standardize docs to class usage; update cookbook notebooks; fix Colab link; correct text_normalizer.normalize → normalize_text

KaifAhmad16b7f230b3752
diff --git a/cookbook/introduction/04_Data_Normalization.ipynb b/cookbook/introduction/04_Data_Normalization.ipynb
index 92c15aa8..19ac4552 100644
--- a/cookbook/introduction/04_Data_Normalization.ipynb
+++ b/cookbook/introduction/04_Data_Normalization.ipynb
@@ -196,11 +196,11 @@
"]\n",
"\n",
"for text in text_samples:\n",
- " detected_lang = language_detector.detect_language(text)\n",
+ " detected_lang = language_detector.detect(text)\n",
" print(f\"Text: {text[:30]}... -> Language: {detected_lang}\")\n",
"\n",
"sample_bytes = \"Hello World\".encode('utf-8')\n",
- "detected_encoding = encoding_handler.detect_encoding(sample_bytes)\n",
+ "detected_encoding = encoding_handler.detect(sample_bytes)\n",
"print(f\"\\nDetected encoding: {detected_encoding}\")\n"
]
},
diff --git a/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb b/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb
index 2eaf03dd..300f5356 100644
--- a/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb
+++ b/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb
@@ -487,7 +487,7 @@
"print(\"Normalizing vector store chunks...\")\n",
"normalized_vector_chunks = []\n",
"for chunk in vector_store_chunks:\n",
- " normalized = text_normalizer.normalize(chunk)\n",
+ " normalized = text_normalizer.normalize_text(chunk)\n",
" if isinstance(normalized, list):\n",
" normalized_vector_chunks.extend(normalized)\n",
" else:\n",
@@ -496,7 +496,7 @@
"print(\"Normalizing graph store chunks...\")\n",
"normalized_graph_chunks = []\n",
"for chunk in graph_store_chunks:\n",
- " normalized = text_normalizer.normalize(chunk)\n",
+ " normalized = text_normalizer.normalize_text(chunk)\n",
" if isinstance(normalized, list):\n",
" normalized_graph_chunks.extend(normalized)\n",
" else:\n",
diff --git a/cookbook/use_cases/healthcare/04_Healthcare_GraphRAG_Hybrid.ipynb b/cookbook/use_cases/healthcare/04_Healthcare_GraphRAG_Hybrid.ipynb
index d1a5418c..03695a46 100644
--- a/cookbook/use_cases/healthcare/04_Healthcare_GraphRAG_Hybrid.ipynb
+++ b/cookbook/use_cases/healthcare/04_Healthcare_GraphRAG_Hybrid.ipynb
@@ -210,9 +210,9 @@
"\n",
"# Normalize clinical text using Semantica\n",
"if isinstance(clinical_data, dict) and 'content' in clinical_data:\n",
- " normalized_text = text_normalizer.normalize(clinical_data['content'])\n",
+ " normalized_text = text_normalizer.normalize_text(clinical_data['content'])\n",
" clinical_data['normalized_content'] = normalized_text\n"
- ]
+ ]
},
{
"cell_type": "markdown",
diff --git a/cookbook/use_cases/supply_chain/02_Supply_Chain_Risk_Management.ipynb b/cookbook/use_cases/supply_chain/02_Supply_Chain_Risk_Management.ipynb
index a06f29f1..74212c92 100644
--- a/cookbook/use_cases/supply_chain/02_Supply_Chain_Risk_Management.ipynb
+++ b/cookbook/use_cases/supply_chain/02_Supply_Chain_Risk_Management.ipynb
@@ -232,8 +232,8 @@
"# Normalize supplier names using Semantica\n",
"if isinstance(supplier_data_parsed, dict):\n",
" for supplier in supplier_data_parsed.get('suppliers', []):\n",
- " supplier['normalized_name'] = text_normalizer.normalize(supplier.get('name', ''))\n"
- ]
+ " supplier['normalized_name'] = text_normalizer.normalize_text(supplier.get('name', ''))\n"
+ ]
},
{
"cell_type": "markdown",
diff --git a/docs/reference/normalize.md b/docs/reference/normalize.md
index bfef60e1..cd36e8dc 100644
--- a/docs/reference/normalize.md
+++ b/docs/reference/normalize.md
@@ -102,67 +102,29 @@ Main text normalization orchestrator with comprehensive cleaning capabilities.
**Methods:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `normalize(text)` | Normalize single text | Full normalization pipeline |
-| `normalize_documents(docs)` | Batch normalize documents | Parallel processing |
-| `clean(text)` | Clean text only | Noise removal |
-| `fix_encoding(text)` | Fix encoding issues | Character encoding detection |
-| `normalize_whitespace(text)` | Standardize whitespace | Regex-based cleanup |
-| `remove_diacritics(text)` | Remove accents | Unicode decomposition |
-
-**Configuration Options:**
-
-```python
-TextNormalizer(
- lowercase=False, # Convert to lowercase
- remove_punctuation=False, # Remove all punctuation
- remove_numbers=False, # Remove numeric values
- remove_whitespace=True, # Normalize whitespace
- fix_encoding=True, # Fix encoding issues
- remove_diacritics=False, # Remove accents/diacritics
- normalize_unicode=True, # Unicode normalization (NFC)
- remove_urls=False, # Remove URLs
- remove_emails=False, # Remove email addresses
- remove_phone_numbers=False, # Remove phone numbers
- expand_contractions=False, # Expand contractions (don't → do not)
- remove_html=True, # Remove HTML tags
- remove_extra_spaces=True, # Remove extra spaces
- strip=True # Strip leading/trailing whitespace
-)
-```
+| Method | Description |
+|--------|-------------|
+| `normalize_text(text, ...)` | Normalize single text using full pipeline |
+| `clean_text(text, ...)` | Clean text (HTML removal, sanitization) |
+| `standardize_format(text, format_type)` | Standardize formatting (standard/compact/preserve) |
+| `process_batch(texts, ...)` | Batch normalize multiple texts |
**Example:**
```python
from semantica.normalize import TextNormalizer
-# Basic normalization
-normalizer = TextNormalizer(
- lowercase=False,
- remove_punctuation=False,
- fix_encoding=True,
- normalize_whitespace=True
-)
+normalizer = TextNormalizer()
-text = " Apple Inc. was founded in 1976. "
-normalized = normalizer.normalize(text)
-print(normalized)
-# Output: "Apple Inc. was founded in 1976."
+# Normalize
+normalized = normalizer.normalize_text(" Apple Inc. was founded in 1976. ", case="preserve")
-# Aggressive cleaning
-aggressive_normalizer = TextNormalizer(
- lowercase=True,
- remove_punctuation=True,
- remove_numbers=True,
- remove_urls=True,
- expand_contractions=True
-)
+# Clean only
+cleaned = normalizer.clean_text("<p>Hello</p>", remove_html=True)
-text = "Check out https://example.com! It's amazing (founded in 2020)."
-cleaned = aggressive_normalizer.normalize(text)
-print(cleaned)
-# Output: "check out it is amazing founded in"
+# Batch
+texts = ["Hello World", "Another Example"]
+normalized_batch = normalizer.process_batch(texts, case="lower")
```
---
@@ -173,12 +135,12 @@ Standardize entity names and resolve variations to canonical forms.
**Methods:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `normalize(entities)` | Normalize entity list | Fuzzy + phonetic matching |
-| `normalize_single(entity)` | Normalize one entity | Canonical form lookup |
-| `add_canonical(entity, canonical)` | Add canonical mapping | Dictionary update |
-| `get_canonical(entity)` | Get canonical form | Fuzzy search |
+| Method | Description |
+|--------|-------------|
+| `normalize_entity(name, ...)` | Normalize entity name to canonical form |
+| `resolve_aliases(name, ...)` | Resolve aliases via alias map |
+| `disambiguate_entity(name, ...)` | Disambiguate using context and candidates |
+| `link_entities(names, ...)` | Link a list of names to canonical forms |
**Configuration Options:**
@@ -199,32 +161,13 @@ EntityNormalizer(
```python
from semantica.normalize import EntityNormalizer
-normalizer = EntityNormalizer(
- fuzzy_matching=True,
- similarity_threshold=0.85,
- expand_abbreviations=True
-)
+normalizer = EntityNormalizer(similarity_threshold=0.85)
-# Normalize entity variations
-entities = [
- "Apple Inc.",
- "Apple",
- "AAPL",
- "Apple Computer",
- "Apple, Inc."
-]
+# Normalize single
+canonical = normalizer.normalize_entity("Apple, Inc.")
-normalized = normalizer.normalize(entities)
-print(normalized)
-# All mapped to canonical form: "Apple Inc."
-
-# Add custom canonical mappings
-normalizer.add_canonical("AAPL", "Apple Inc.")
-normalizer.add_canonical("Microsoft Corp", "Microsoft Corporation")
-
-# Get canonical form
-canonical = normalizer.get_canonical("MSFT")
-print(canonical) # "Microsoft Corporation"
+# Link list
+linked = normalizer.link_entities(["Apple Inc.", "Apple", "AAPL"], entity_type="Organization")
```
---
@@ -235,12 +178,11 @@ Parse and standardize date/time formats to ISO 8601.
**Methods:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `normalize(date_string)` | Parse and normalize date | dateutil parser |
-| `normalize_batch(dates)` | Batch normalize dates | Parallel processing |
-| `parse_relative(relative_date)` | Parse relative dates | Date arithmetic |
-| `detect_format(date_string)` | Detect date format | Pattern matching |
+| Method | Description |
+|--------|-------------|
+| `normalize_date(date_str, ...)` | Parse and normalize date |
+| `normalize_time(time_str, ...)` | Normalize time-only strings |
+| `parse_temporal_expression(expr)` | Parse date ranges and temporal phrases |
**Configuration Options:**
@@ -260,38 +202,12 @@ DateNormalizer(
```python
from semantica.normalize import DateNormalizer
-normalizer = DateNormalizer(
- output_format="ISO8601",
- timezone="UTC",
- handle_relative=True
-)
-
-# Normalize various date formats
-dates = [
- "Jan 1, 2024",
- "01/01/2024",
- "2024-01-01",
- "1st January 2024",
- "yesterday",
- "March 2024"
-]
+normalizer = DateNormalizer()
-normalized = [normalizer.normalize(d) for d in dates]
-for original, norm in zip(dates, normalized):
- print(f"{original:20} → {norm}")
+dates = ["Jan 1, 2024", "01/01/2024", "yesterday"]
+normalized = [normalizer.normalize_date(d) for d in dates]
-# Output:
-# Jan 1, 2024 → 2024-01-01T00:00:00Z
-# 01/01/2024 → 2024-01-01T00:00:00Z
-# 2024-01-01 → 2024-01-01T00:00:00Z
-# 1st January 2024 → 2024-01-01T00:00:00Z
-# yesterday → 2024-11-29T00:00:00Z
-# March 2024 → 2024-03-01T00:00:00Z
-
-# Custom format
-custom_normalizer = DateNormalizer(output_format="%Y/%m/%d")
-result = custom_normalizer.normalize("Jan 1, 2024")
-print(result) # "2024/01/01"
+time = normalizer.normalize_time("10:30 AM")
```
---
@@ -302,41 +218,26 @@ Standardize numeric values, units, and measurements.
**Methods:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `normalize(number_string)` | Parse and normalize number | Regex parsing |
-| `convert_units(value, from_unit, to_unit)` | Convert units | Unit conversion |
-| `parse_currency(currency_string)` | Parse currency | Currency parsing |
-| `normalize_percentage(percent_string)` | Normalize percentage | Percentage parsing |
+| Method | Description |
+|--------|-------------|
+| `normalize_number(input, ...)` | Parse and normalize number |
+| `normalize_quantity(quantity, ...)` | Parse value with unit |
+| `convert_units(value, from_unit, to_unit)` | Convert units |
+| `process_currency(text, ...)` | Parse currency amount and code |
**Example:**
```python
from semantica.normalize import NumberNormalizer
-normalizer = NumberNormalizer(
- decimal_separator=".",
- thousands_separator=",",
- normalize_units=True
-)
-
-# Normalize various number formats
-numbers = [
- "1,000.50",
- "1.000,50",
- "1 000.50",
- "$1,234.56",
- "50%",
- "1.5e3"
-]
+normalizer = NumberNormalizer()
-normalized = [normalizer.normalize(n) for n in numbers]
-for original, norm in zip(numbers, normalized):
- print(f"{original:15} → {norm}")
+numbers = ["1,000.50", "50%", "1.5e3"]
+normalized = [normalizer.normalize_number(n) for n in numbers]
-# Unit conversion
-distance_km = normalizer.convert_units(5, "km", "m")
-print(f"5 km = {distance_km} m") # 5000 m
+quantity = normalizer.normalize_quantity("5 kg")
+converted = normalizer.convert_units(5, "km", "m")
+currency = normalizer.process_currency("$1,234.56")
```
---
@@ -347,11 +248,12 @@ Detect document language with confidence scoring.
**Methods:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `detect(text)` | Detect language | N-gram analysis |
-| `detect_batch(texts)` | Batch detect languages | Parallel processing |
-| `get_confidence(text, language)` | Get confidence score | Statistical model |
+| Method | Description |
+|--------|-------------|
+| `detect(text)` | Detect language |
+| `detect_with_confidence(text)` | Detect with confidence score |
+| `detect_multiple(text, top_n)` | List top-N candidate languages |
+| `detect_batch(texts)` | Batch language detection |
**Example:**
@@ -383,41 +285,6 @@ for text in texts:
---
-## Convenience Functions
-
-Quick access to normalization operations:
-
-```python
-from semantica.normalize import (
- normalize_text,
- normalize_entities,
- normalize_dates,
- normalize_numbers,
- detect_language,
- fix_encoding
-)
-
-# Normalize text
-clean_text = normalize_text(" Messy text ", remove_extra_spaces=True)
-
-# Normalize entities
-canonical_entities = normalize_entities(["Apple Inc.", "Apple", "AAPL"])
-
-# Normalize dates
-iso_dates = normalize_dates(["Jan 1, 2024", "01/01/2024"])
-
-# Normalize numbers
-standard_numbers = normalize_numbers(["1,000.50", "$1,234.56"])
-
-# Detect language
-language = detect_language("Hello, world!")
-
-# Fix encoding
-fixed_text = fix_encoding("Caf\u00e9") # Café
-```
-
----
-
## Configuration
### Environment Variables
@@ -495,21 +362,16 @@ for doc in documents:
doc.metadata["language"] = lang_result["language"]
doc.metadata["language_confidence"] = lang_result["confidence"]
-# Normalize text
-text_normalizer = TextNormalizer(
- fix_encoding=True,
- normalize_whitespace=True,
- remove_html=True
-)
+text_normalizer = TextNormalizer()
for doc in documents:
- doc.content = text_normalizer.normalize(doc.content)
+ doc.content = text_normalizer.normalize_text(doc.content)
# Normalize dates in metadata
date_normalizer = DateNormalizer(output_format="ISO8601")
for doc in documents:
if "date" in doc.metadata:
- doc.metadata["date"] = date_normalizer.normalize(doc.metadata["date"])
+ doc.metadata["date"] = date_normalizer.normalize_date(doc.metadata["date"])
# Normalize entities
entity_normalizer = EntityNormalizer(similarity_threshold=0.85)
@@ -535,7 +397,7 @@ def process_multilingual_document(text):
# Use language-specific normalizer
normalizer = normalizers.get(language, TextNormalizer())
- normalized = normalizer.normalize(text)
+ normalized = normalizer.normalize_text(text)
return {
"text": normalized,
@@ -584,7 +446,7 @@ aggressive = TextNormalizer(
```python
# Always keep original text
doc.original_content = doc.content
-doc.content = normalizer.normalize(doc.content)
+doc.content = normalizer.normalize_text(doc.content)
# Store normalization metadata
doc.metadata["normalized"] = True
@@ -596,7 +458,7 @@ doc.metadata["normalization_config"] = normalizer.config
```python
# Batch normalize for better performance
texts = [doc.content for doc in documents]
-normalized_texts = normalizer.normalize_documents(texts)
+normalized_texts = normalizer.process_batch(texts)
for doc, normalized in zip(documents, normalized_texts):
doc.content = normalized
@@ -615,8 +477,8 @@ for doc, normalized in zip(documents, normalized_texts):
normalizer = TextNormalizer(fix_encoding=True)
# Or manually fix encoding
-from semantica.normalize import fix_encoding
-fixed_text = fix_encoding(problematic_text)
+from semantica.normalize import handle_encoding
+fixed_text, confidence = handle_encoding(problematic_text, operation="convert", source_encoding="latin-1")
```
**Issue**: Over-normalization losing important information
@@ -635,15 +497,36 @@ normalizer = TextNormalizer(
```python
# Solution: Use batch processing
normalizer = TextNormalizer()
-normalized = normalizer.normalize_documents(
- documents,
- batch_size=100,
- n_jobs=4 # Parallel processing
-)
+normalized = normalizer.process_batch(documents)
```
---
+## Components
+
+Key supporting classes available in `semantica.normalize`:
+
+- `UnicodeNormalizer` — Unicode processing (NFC/NFD/NFKC/NFKD), special chars
+- `WhitespaceNormalizer` — Line breaks, indentation, whitespace cleanup
+- `SpecialCharacterProcessor` — Punctuation and diacritic handling
+- `TextCleaner` — HTML removal and sanitization utilities
+- `AliasResolver` — Entity alias mapping
+- `EntityDisambiguator` — Context-based entity disambiguation
+- `NameVariantHandler` — Title and name variant handling
+- `TimeZoneNormalizer` — Timezone conversion utilities
+- `RelativeDateProcessor` — Relative date expressions (e.g., "3 days ago")
+- `TemporalExpressionParser` — Date range and temporal phrase parsing
+- `UnitConverter` — Unit normalization and conversion
+- `CurrencyNormalizer` — Currency symbol/code parsing
+- `ScientificNotationHandler` — Scientific notation parsing
+- `DataCleaner` — General data cleaning utilities
+- `DuplicateDetector` — Duplicate record detection
+- `DataValidator` — Schema-based dataset validation
+- `MissingValueHandler` — Missing value strategies
+- `EncodingHandler` — Encoding detection and conversion
+- `MethodRegistry` — Register and retrieve custom normalization methods
+- `NormalizeConfig` — Module configuration manager
+
## Performance Tips
### Memory Optimization
@@ -655,7 +538,7 @@ def normalize_large_corpus(documents, chunk_size=1000):
for i in range(0, len(documents), chunk_size):
chunk = documents[i:i + chunk_size]
- normalized_chunk = normalizer.normalize_documents(chunk)
+ normalized_chunk = normalizer.process_batch(chunk)
yield from normalized_chunk
```
@@ -670,10 +553,8 @@ fast_normalizer = TextNormalizer(
)
# Use parallel processing
-normalizer.normalize_documents(
- documents,
- n_jobs=-1 # Use all CPU cores
-)
+# Batch processing
+normalized_docs = normalizer.process_batch(documents)
```
---
diff --git a/semantica/normalize/normalize_usage.md b/semantica/normalize/normalize_usage.md
index b4cb6478..c13f446c 100644
--- a/semantica/normalize/normalize_usage.md
+++ b/semantica/normalize/normalize_usage.md
@@ -1,43 +1,24 @@
-# Data Normalization Module Usage Guide
+# Normalize 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.
+Use the normalize module to clean, standardize, and prepare text and data for downstream processing. This guide only references classes and functions implemented in the module.
-## Table of Contents
+## 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)
+1. [Quick Start](#quick-start)
+2. [Text](#text)
+3. [Entities](#entities)
+4. [Dates & Time](#dates--time)
+5. [Numbers & Quantities](#numbers--quantities)
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)
+7. [Language](#language)
+8. [Encoding](#encoding)
+9. [Methods Registry](#methods-registry)
+10. [Configuration](#configuration)
+11. [Workflows](#workflows)
-## Basic Usage
+## Quick Start
-### 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
+### Main Classes
```python
from semantica.normalize import TextNormalizer, EntityNormalizer, DateNormalizer
@@ -57,107 +38,72 @@ normalized_entity = entity_norm.normalize_entity("John Doe", entity_type="Person
normalized_date = date_norm.normalize_date("2023-01-15", format="ISO8601")
```
-## Text Normalization
+## Text
-### Basic Text Normalization
+### Normalize Text
```python
-from semantica.normalize import normalize_text, TextNormalizer
-
-# Using convenience function
-normalized = normalize_text("Hello World", method="default")
-print(f"Normalized: {normalized}")
+from semantica.normalize import TextNormalizer
-# Using class directly
normalizer = TextNormalizer()
normalized = normalizer.normalize_text("Hello World", case="lower")
```
-### Unicode Normalization
+### Unicode
```python
-from semantica.normalize import normalize_text, UnicodeNormalizer
+from semantica.normalize import 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
+### Whitespace
```python
-from semantica.normalize import normalize_text, WhitespaceNormalizer
-
-# Normalize whitespace
-normalized = normalize_text(
- "Hello World\n\nTest",
- method="default",
- line_break_type="unix"
-)
+from semantica.normalize import WhitespaceNormalizer
-# Using WhitespaceNormalizer directly
whitespace_norm = WhitespaceNormalizer()
normalized = whitespace_norm.normalize_whitespace(
- "Hello World",
+ "Hello World\n\nTest",
line_break_type="unix"
)
```
-### Case Normalization
+### Case
```python
-from semantica.normalize import normalize_text
+from semantica.normalize import TextNormalizer
+
+normalizer = TextNormalizer()
# Lowercase
-lower = normalize_text("Hello World", method="default", case="lower")
+lower = normalizer.normalize_text("Hello World", case="lower")
# Uppercase
-upper = normalize_text("Hello World", method="default", case="upper")
+upper = normalizer.normalize_text("Hello World", case="upper")
# Title case
-title = normalize_text("hello world", method="default", case="title")
+title = normalizer.normalize_text("hello world", case="title")
# Preserve case
-preserved = normalize_text("Hello World", method="default", case="preserve")
+preserved = normalizer.normalize_text("Hello World", case="preserve")
```
-### Special Character Processing
+### Special Characters
```python
-from semantica.normalize import normalize_text, SpecialCharacterProcessor
-
-# Normalize with special character processing
-normalized = normalize_text(
- "Hello—World",
- method="default",
- normalize_diacritics=True
-)
+from semantica.normalize import SpecialCharacterProcessor
-# Using SpecialCharacterProcessor directly
char_processor = SpecialCharacterProcessor()
processed = char_processor.process_special_chars("Hello—World")
```
-### Text Cleaning
+### Cleaning
```python
-from semantica.normalize import clean_text, TextCleaner
+from semantica.normalize import 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>",
@@ -166,7 +112,7 @@ cleaned = cleaner.clean(
)
```
-### Batch Text Processing
+### Batch
```python
from semantica.normalize import TextNormalizer
@@ -185,66 +131,36 @@ for text in normalized_texts:
print(text)
```
-## Entity Normalization
+## Entities
-### Basic Entity Normalization
+### Normalize Entity
```python
-from semantica.normalize import normalize_entity, EntityNormalizer
-
-# Using convenience function
-normalized = normalize_entity(
- "John Doe",
- entity_type="Person",
- method="default"
-)
+from semantica.normalize import EntityNormalizer
-# Using class directly
normalizer = EntityNormalizer()
normalized = normalizer.normalize_entity("John Doe", entity_type="Person")
```
-### Alias Resolution
+### Aliases
```python
-from semantica.normalize import resolve_aliases, AliasResolver
+from semantica.normalize import 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
+### Disambiguation
```python
-from semantica.normalize import disambiguate_entity, EntityDisambiguator
-
-# Using convenience function
-result = disambiguate_entity(
- "Apple",
- method="default",
- entity_type="Organization",
- context="technology company"
-)
+from semantica.normalize import EntityDisambiguator
-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
+### Linking
```python
from semantica.normalize import EntityNormalizer
@@ -263,7 +179,7 @@ for original, canonical in linked.items():
print(f"{original} -> {canonical}")
```
-### Name Variant Handling
+### Name Variants
```python
from semantica.normalize import EntityNormalizer, NameVariantHandler
@@ -284,86 +200,58 @@ normalized = variant_handler.normalize_name_format(
)
```
-## Date/Time Normalization
+## Dates & Time
-### Basic Date Normalization
+### Normalize Date
```python
-from semantica.normalize import normalize_date, DateNormalizer
-
-# Using convenience function
-normalized = normalize_date("2023-01-15", method="default")
-print(f"Normalized: {normalized}")
+from semantica.normalize import DateNormalizer
-# Using class directly
normalizer = DateNormalizer()
normalized = normalizer.normalize_date("2023-01-15", format="ISO8601")
```
-### Different Date Formats
+### 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")
+from semantica.normalize import DateNormalizer
-# Custom format
-custom = normalize_date("2023-01-15", format="%Y-%m-%d", method="default")
+normalizer = DateNormalizer()
+iso_date = normalizer.normalize_date("2023-01-15", format="ISO8601")
+date_only = normalizer.normalize_date("2023-01-15", format="date")
+custom = normalizer.normalize_date("2023-01-15", format="%Y-%m-%d")
```
-### Timezone Normalization
+### Timezone
```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"
-)
+from semantica.normalize import TimeZoneNormalizer
-# 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
+### Relative Dates
```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")
+from semantica.normalize import RelativeDateProcessor
-# Using RelativeDateProcessor directly
relative_processor = RelativeDateProcessor()
dt = relative_processor.process_relative_expression("3 days ago")
```
-### Time Normalization
+### Time
```python
-from semantica.normalize import normalize_time, DateNormalizer
+from semantica.normalize import 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
+### Temporal Expressions
```python
from semantica.normalize import DateNormalizer, TemporalExpressionParser
@@ -379,58 +267,44 @@ parser = TemporalExpressionParser()
result = parser.parse_temporal_expression("last week")
```
-## Number/Quantity Normalization
+## Numbers & Quantities
-### Basic Number Normalization
+### Normalize Number
```python
-from semantica.normalize import normalize_number, NumberNormalizer
-
-# Using convenience function
-number = normalize_number("1,234.56", method="default")
-print(f"Normalized: {number}")
+from semantica.normalize import NumberNormalizer
-# Using class directly
normalizer = NumberNormalizer()
number = normalizer.normalize_number("1,234.56")
```
-### Percentage Handling
+### Percentages
```python
-from semantica.normalize import normalize_number
+from semantica.normalize import NumberNormalizer
-# Normalize percentage
-percentage = normalize_number("50%", method="default")
+normalizer = NumberNormalizer()
+percentage = normalizer.normalize_number("50%")
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
+from semantica.normalize import ScientificNotationHandler
-# Using ScientificNotationHandler directly
sci_handler = ScientificNotationHandler()
parsed = sci_handler.parse_scientific_notation("1.5e3")
```
-### Quantity Normalization
+### Quantities
```python
-from semantica.normalize import normalize_quantity, NumberNormalizer
+from semantica.normalize import 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")
+print(f"Value: {quantity['value']}, Unit: {quantity['unit']}")
```
### Unit Conversion
@@ -449,7 +323,7 @@ converter = UnitConverter()
converted = converter.convert_units(1, "kilometer", "mile")
```
-### Currency Processing
+### Currency
```python
from semantica.normalize import NumberNormalizer, CurrencyNormalizer
@@ -467,10 +341,10 @@ currency = currency_norm.normalize_currency("€50", default_currency="EUR")
## Data Cleaning
-### Basic Data Cleaning
+### Clean Data
```python
-from semantica.normalize import clean_data, DataCleaner
+from semantica.normalize import DataCleaner
dataset = [
{"id": 1, "name": "Alice", "age": 30},
@@ -478,16 +352,6 @@ dataset = [
{"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,
@@ -496,10 +360,10 @@ cleaned = cleaner.clean_data(
)
```
-### Duplicate Detection
+### Duplicates
```python
-from semantica.normalize import detect_duplicates, DuplicateDetector
+from semantica.normalize import DuplicateDetector
dataset = [
{"id": 1, "name": "Alice"},
@@ -507,23 +371,14 @@ dataset = [
{"id": 1, "name": "Alice"}, # Duplicate
]
-# Using convenience function
-duplicates = detect_duplicates(
- dataset,
- threshold=0.8,
- method="default"
-)
-
+detector = DuplicateDetector(similarity_threshold=0.8)
+duplicates = detector.detect_duplicates(dataset, key_fields=["id", "name"])
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
+### Validation
```python
from semantica.normalize import DataCleaner, DataValidator
@@ -556,7 +411,7 @@ validator = DataValidator()
validation = validator.validate_dataset(dataset, schema)
```
-### Missing Value Handling
+### Missing Values
```python
from semantica.normalize import DataCleaner, MissingValueHandler
@@ -592,37 +447,28 @@ handler = MissingValueHandler()
cleaned = handler.handle_missing_values(dataset, strategy="remove")
```
-## Language Detection
+## Language
-### Basic Language Detection
+### Detect
```python
-from semantica.normalize import detect_language, LanguageDetector
-
-# Using convenience function
-language = detect_language("Hello world", method="default")
-print(f"Detected language: {language}")
+from semantica.normalize import LanguageDetector
-# Using class directly
detector = LanguageDetector()
language = detector.detect("Bonjour le monde")
```
-### Detection with Confidence
+### Confidence
```python
-from semantica.normalize import detect_language
-
-# Detect with confidence score
-lang, confidence = detect_language(
- "Bonjour le monde",
- method="confidence"
-)
+from semantica.normalize import LanguageDetector
+detector = LanguageDetector()
+lang, confidence = detector.detect_with_confidence("Bonjour le monde")
print(f"Language: {lang}, Confidence: {confidence:.2f}")
```
-### Multiple Language Detection
+### Top-N
```python
from semantica.normalize import LanguageDetector
@@ -639,7 +485,7 @@ for lang, conf in languages:
print(f"{lang}: {conf:.2f}")
```
-### Language Validation
+### Validation
```python
from semantica.normalize import LanguageDetector
@@ -654,41 +500,23 @@ print(f"Is English: {is_english}")
print(f"Is French: {is_french}")
```
-## Encoding Handling
+## Encoding
-### Encoding Detection
+### Detect
```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}")
+from semantica.normalize import EncodingHandler
-# Using EncodingHandler directly
handler = EncodingHandler()
encoding, confidence = handler.detect(data)
+print(f"Encoding: {encoding}, Confidence: {confidence:.2f}")
```
-### UTF-8 Conversion
+### Convert to UTF-8
```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"
-)
+from semantica.normalize import EncodingHandler
-# Using EncodingHandler directly
handler = EncodingHandler()
utf8_text = handler.convert_to_utf8(data, source_encoding="latin-1")
```
@@ -696,21 +524,13 @@ 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"
-)
+from semantica.normalize import EncodingHandler
-# Using EncodingHandler directly
handler = EncodingHandler()
cleaned = handler.remove_bom(data)
```
-### File Encoding Conversion
+### File Encoding
```python
from semantica.normalize import EncodingHandler
@@ -725,9 +545,9 @@ encoding, confidence = handler.detect_file("input.txt")
print(f"File encoding: {encoding}")
```
-## Using Methods
+## Methods Registry
-### Getting Available Methods
+### List & Get
```python
from semantica.normalize.methods import get_normalize_method, list_available_methods
@@ -746,68 +566,12 @@ 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")
+### Examples
-# Encoding handling
-encoding, confidence = handle_encoding(data, operation="detect", method="default")
-```
-## Using Registry
+## Register Custom Methods
-### Registering Custom Methods
+### Register
```python
from semantica.normalize.registry import method_registry
@@ -827,7 +591,7 @@ custom_method = get_normalize_method("text", "custom_upper")
result = custom_method("hello world")
```
-### Listing Registered Methods
+### List
```python
from semantica.normalize.registry import method_registry
@@ -844,7 +608,7 @@ entity_methods = method_registry.list_all("entity")
print("Entity methods:", entity_methods)
```
-### Unregistering Methods
+### Unregister
```python
from semantica.normalize.registry import method_registry
@@ -861,7 +625,7 @@ method_registry.clear()
## Configuration
-### Using Configuration Manager
+### Config Manager
```python
from semantica.normalize.config import normalize_config
@@ -897,7 +661,7 @@ export NORMALIZE_DEFAULT_LANGUAGE=en
export NORMALIZE_DEFAULT_ENCODING=utf-8
```
-### Configuration File
+### Config File
```yaml
# config.yaml
@@ -928,39 +692,48 @@ config = NormalizeConfig(config_file="config.yaml")
unicode_form = config.get("unicode_form")
```
-## Advanced Examples
+## Workflows
-### Complete Normalization Pipeline
+### Complete Pipeline
```python
from semantica.normalize import (
- normalize_text,
- normalize_entity,
- normalize_date,
- normalize_number,
- clean_data
+ TextNormalizer,
+ EntityNormalizer,
+ DateNormalizer,
+ NumberNormalizer,
+ DataCleaner
)
+# Create normalizers
+text_norm = TextNormalizer()
+entity_norm = EntityNormalizer()
+date_norm = DateNormalizer()
+number_norm = NumberNormalizer()
+cleaner = DataCleaner()
+
# Step 1: Normalize text
-text = normalize_text("Hello World", method="default", case="lower")
+text = text_norm.normalize_text("Hello World", case="lower")
# Step 2: Normalize entities
entities = ["John Doe", "J. Doe", "Johnny Doe"]
normalized_entities = [
- normalize_entity(e, entity_type="Person", method="default")
+ entity_norm.normalize_entity(e, entity_type="Person")
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
+ date_norm.normalize_date(d)
+ 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
+ number_norm.normalize_number(n)
+ for n in numbers
]
# Step 5: Clean dataset
@@ -968,10 +741,10 @@ dataset = [
{"id": 1, "name": "Alice", "date": "2023-01-15"},
{"id": 2, "name": "Bob", "date": "yesterday"},
]
-cleaned = clean_data(dataset, method="default", remove_duplicates=True)
+cleaned = cleaner.clean_data(dataset, remove_duplicates=True)
```
-### Custom Normalization Workflow
+### Custom Workflow
```python
from semantica.normalize import (
@@ -1025,26 +798,29 @@ normalized_entities = [
]
```
-### Integration with Other Modules
+### Integration
```python
-from semantica.normalize import normalize_text, normalize_entity
+from semantica.normalize import TextNormalizer, EntityNormalizer
from semantica.kg import build
+text_norm = TextNormalizer()
+entity_norm = EntityNormalizer()
+
# Normalize text before KG building
-text = normalize_text("Apple Inc. was founded by Steve Jobs", method="default")
+text = text_norm.normalize_text("Apple Inc. was founded by Steve Jobs")
# 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")
+ entity_norm.normalize_entity("Apple Inc.", entity_type="Organization"),
+ entity_norm.normalize_entity("Steve Jobs", entity_type="Person")
]
# Build knowledge graph with normalized data
kg = build(sources=[{"entities": entities, "relationships": []}])
```
-### Custom Validation Rules
+### Custom Validation
```python
from semantica.normalize import DataCleaner, DataValidator
@@ -1072,58 +848,42 @@ if not validation.valid:
print(f"Error: {error}")
```
-### Language-Aware Normalization
+### Language-Aware
```python
-from semantica.normalize import (
- normalize_text,
- detect_language,
- LanguageDetector
-)
+from semantica.normalize import TextNormalizer, LanguageDetector
detector = LanguageDetector()
+normalizer = TextNormalizer()
-# 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")
+ normalized = normalizer.normalize_text(text, case="preserve")
else:
- normalized = normalize_text(text, method="default", case="lower")
+ normalized = normalizer.normalize_text(text, case="lower")
```
-### Encoding-Aware Text Processing
+### Encoding-Aware
```python
-from semantica.normalize import (
- handle_encoding,
- normalize_text,
- EncodingHandler
-)
+from semantica.normalize import TextNormalizer, EncodingHandler
handler = EncodingHandler()
+text_norm = TextNormalizer()
-# 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")
+normalized = text_norm.normalize_text(utf8_text)
```
-### Comprehensive Data Cleaning Pipeline
+### Cleaning Pipeline
```python
-from semantica.normalize import (
- clean_data,
- detect_duplicates,
- normalize_text,
- normalize_date,
- DataCleaner
-)
+from semantica.normalize import TextNormalizer, DateNormalizer, DataCleaner
# Raw dataset
raw_dataset = [
@@ -1133,15 +893,18 @@ raw_dataset = [
{"id": 3, "name": None, "date": "2023-01-20"}, # Missing name
]
+text_norm = TextNormalizer()
+date_norm = DateNormalizer()
+
# Step 1: Normalize text fields
for record in raw_dataset:
if record.get("name"):
- record["name"] = normalize_text(record["name"], method="default")
+ record["name"] = text_norm.normalize_text(record["name"])
# Step 2: Normalize dates
for record in raw_dataset:
if record.get("date"):
- record["date"] = normalize_date(record["date"], method="default")
+ record["date"] = date_norm.normalize_date(record["date"])
# Step 3: Clean data
cleaner = DataCleaner()