Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat: Add provenance metadata and robust fallback chains to semantic extraction

KaifAhmad1f338b662742c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7c7c9611..e484e2ed 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,36 +7,64 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
-### Fixed
-- Fixed model switching bug in `TextEmbedder` where internal state was not cleared, preventing dynamic updates between `fastembed` and `sentence_transformers` (#160).
-- Implemented model-intrinsic embedding dimension detection in `TextEmbedder` to ensure consistency between models and vector databases.
-- Updated `set_model` to properly refresh configuration and dimensions during model switches.
-
-### Added
-- Added `semantica/semantic_extract/schemas.py` with canonical Pydantic models for consistent structured output.
-- Enhanced extractors with robust fallback chains (LLM -> Pattern) to ensure data availability.
-- Added comprehensive unit test suite `tests/embeddings/test_model_switching.py` for verifying dynamic model transitions and dimension updates.
-- Fixed `TypeError: unhashable type: 'Entity'` in `GraphAnalyzer` when processing graphs with raw `Entity` objects or dictionaries in relationships (#159).
-- Robustified ID extraction across `CentralityCalculator`, `CommunityDetector`, and `ConnectivityAnalyzer` to handle various entity formats.
-- Improved `Entity` class hashability and equality logic in `utils/types.py`.
-- Added end-to-end integration test suite for Knowledge Graph pipeline validation (GraphBuilder -> EntityResolver -> GraphAnalyzer).
-- Fixed orchestrator lazy property initialization and configuration normalization logic in `Orchestrator`.
-- Resolved `AssertionError` in orchestrator tests by aligning test mocks with production component usage.
-- Fixed dependency compatibility issues by pinning `protobuf==4.25.3` and `grpcio==1.67.1`.
-- Added missing dependencies `GitPython` and `chardet` to `pyproject.toml`.
-- Verified and aligned `FileObject.text` property usage in GraphRAG notebooks for consistent content decoding.
-
### Added
+- **Robust Extraction Fallbacks**:
+ - Implemented comprehensive fallback chains ("ML/LLM" -> "Pattern" -> "Last Resort") across `NERExtractor`, `RelationExtractor`, and `TripletExtractor` to prevent empty result lists.
+ - Added "Last Resort" pattern matching in `NERExtractor` to identify capitalized words as generic entities when all other methods fail.
+ - Added "Last Resort" adjacency-based relation extraction in `RelationExtractor` to create weak connections between adjacent entities if no relations are found.
+ - Added fallback logic in `TripletExtractor` to convert relations to triplets or use rule-based extraction if standard methods fail.
+- **Provenance & Tracking**:
+ - Added count tracking to batch processing logs in `NERExtractor`, `RelationExtractor`, and `TripletExtractor`.
+ - Added `batch_index` and `document_id` to the metadata of all extracted entities, relations, triplets, semantic roles, and clusters for better traceability.
- **Semantic Extract Improvements**:
- Introduced `auto-chunking` for long text processing in LLM extraction methods (`extract_entities_llm`, `extract_relations_llm`, `extract_triplets_llm`).
- Added `silent_fail` parameter to LLM extraction methods for configurable error handling.
- Implemented robust JSON parsing and automatic retry logic (3 attempts with exponential backoff) in `BaseProvider` for all LLM providers.
- Enhanced `GroqProvider` with better diagnostics and connectivity testing.
- Added comprehensive entity, relation, and triplet deduplication for chunked extraction.
+ - Added `semantica/semantic_extract/schemas.py` with canonical Pydantic models for consistent structured output.
+- **Testing**:
+ - Added comprehensive robustness test suite `tests/semantic_extract/test_robustness_fallback.py` for validating extraction fallbacks and metadata propagation.
+ - Added comprehensive unit test suite `tests/embeddings/test_model_switching.py` for verifying dynamic model transitions and dimension updates.
+ - Added end-to-end integration test suite for Knowledge Graph pipeline validation (GraphBuilder -> EntityResolver -> GraphAnalyzer).
+- **Other**:
+ - Added missing dependencies `GitPython` and `chardet` to `pyproject.toml`.
+ - Robustified ID extraction across `CentralityCalculator`, `CommunityDetector`, and `ConnectivityAnalyzer` to handle various entity formats.
+ - Improved `Entity` class hashability and equality logic in `utils/types.py`.
+
+### Changed
+- **Deduplication & Conflict Logic**:
+ - Removed internal deduplication logic from `NERExtractor`, `RelationExtractor`, and `TripletExtractor`.
+ - Removed consistency/conflict checking from `ExtractionValidator` to defer to dedicated `semantica/conflicts` module.
+ - Removed `_deduplicate_*` methods from `semantica/semantic_extract/methods.py`.
+- **Batch Processing & Consistency**:
+ - Standardized batch processing across all extractors (`NERExtractor`, `RelationExtractor`, `TripletExtractor`, `SemanticNetworkExtractor`, `EventDetector`, `SemanticAnalyzer`, `CoreferenceResolver`) using a unified `extract`/`analyze`/`resolve` method pattern with progress tracking.
+ - Added provenance metadata (`batch_index`, `document_id`) to `SemanticNetwork` nodes/edges, `Event` objects, `SemanticRole` results, `CoreferenceChain` mentions, and `SemanticCluster` (tracking source `document_ids`).
+ - Updated `SemanticClusterer.cluster` and `SemanticAnalyzer.cluster_semantically` to accept list of dictionaries (with `content` and `id` keys) for better document tracking during clustering.
+ - Removed legacy `check_triplet_consistency` from `TripletExtractor`.
+ - Removed `validate_consistency` and `_check_consistency` from `ExtractionValidator`.
+- **Weighted Scoring**:
+ - Clarified weighted confidence scoring (50% Method Confidence + 50% Type Similarity) in comments.
+ - Explicitly labeled "Type Similarity" as "user-provided" in code comments to remove ambiguity.
+- **Refactoring**:
+ - Fixed orchestrator lazy property initialization and configuration normalization logic in `Orchestrator`.
+ - Verified and aligned `FileObject.text` property usage in GraphRAG notebooks for consistent content decoding.
### Fixed
-- Fixed a bug in `TripletExtractor` where the `validate_triplets` method was shadowed by an internal attribute.
-- Fixed incorrect `TextSplitter` import path in the `semantic_extract.methods` module.
+- **Critical Fixes**:
+ - Resolved `NameError` in `extraction_validator.py` by adding missing `Union` import.
+ - Resolved issues where extractors would return empty lists for valid input text when primary extraction methods failed.
+ - Fixed metadata initialization issue in batch processing where `batch_index` and `document_id` were occasionally missing from extracted items.
+ - Ensured `LLMExtraction` methods (`enhance_entities`, `enhance_relations`) return original input instead of failing or returning empty results when LLM providers are unavailable.
+- **Component Fixes**:
+ - Fixed model switching bug in `TextEmbedder` where internal state was not cleared, preventing dynamic updates between `fastembed` and `sentence_transformers` (#160).
+ - Implemented model-intrinsic embedding dimension detection in `TextEmbedder` to ensure consistency between models and vector databases.
+ - Updated `set_model` to properly refresh configuration and dimensions during model switches.
+ - Fixed `TypeError: unhashable type: 'Entity'` in `GraphAnalyzer` when processing graphs with raw `Entity` objects or dictionaries in relationships (#159).
+ - Resolved `AssertionError` in orchestrator tests by aligning test mocks with production component usage.
+ - Fixed dependency compatibility issues by pinning `protobuf==4.25.3` and `grpcio==1.67.1`.
+ - Fixed a bug in `TripletExtractor` where the `validate_triplets` method was shadowed by an internal attribute.
+ - Fixed incorrect `TextSplitter` import path in the `semantic_extract.methods` module.
## [0.1.1] - 2026-01-05
diff --git a/docs/reference/semantic_extract.md b/docs/reference/semantic_extract.md
index 6ae412eb..505629c3 100644
--- a/docs/reference/semantic_extract.md
+++ b/docs/reference/semantic_extract.md
@@ -424,6 +424,44 @@ enhanced_entities = extractor.enhance_entities(text, entities)
---
+## Batch Processing & Provenance
+
+All extractors support batch processing for high-throughput extraction. You can pass a list of strings or a list of dictionaries (with `content` and `id` keys).
+
+**Features:**
+- **Progress Tracking**: Automatically shows a progress bar for large batches.
+- **Provenance Metadata**: Each extracted item includes `batch_index` and `document_id` in its `metadata`.
+
+```python
+from semantica.semantic_extract import NERExtractor
+
+documents = [
+ {"id": "doc_1", "content": "Apple Inc. was founded by Steve Jobs."},
+ {"id": "doc_2", "content": "Microsoft Corporation was founded by Bill Gates."}
+]
+
+extractor = NERExtractor()
+batch_results = extractor.extract(documents)
+
+for i, doc_entities in enumerate(batch_results):
+ print(f"Document {i} entities:")
+ for entity in doc_entities:
+ print(f" - {entity.text} ({entity.label})")
+ print(f" Provenance: Batch Index {entity.metadata['batch_index']}, Doc ID {entity.metadata.get('document_id')}")
+```
+
+## Robust Extraction Fallbacks
+
+The framework implements robust fallback chains to prevent empty results when primary methods fail (e.g., due to model unavailability or obscure text).
+
+- **NER**: `ML/LLM` -> `Pattern` -> `Last Resort` (Capitalized Words)
+- **Relation**: `Primary` -> `Pattern` -> `Last Resort` (Adjacency)
+- **Triplet**: `Primary` -> `Relation-to-Triplet` -> `Pattern`
+
+This ensures that you almost always get *some* structured data, even if it requires falling back to simpler heuristics.
+
+---
+
## Usage Examples
```python
diff --git a/semantica/semantic_extract/__init__.py b/semantica/semantic_extract/__init__.py
index 787ad5a9..f0f14204 100644
--- a/semantica/semantic_extract/__init__.py
+++ b/semantica/semantic_extract/__init__.py
@@ -15,6 +15,8 @@ Key Features:
- Semantic network construction
- LLM-based extraction enhancement
- Extraction validation and quality assessment
+ - Batch processing with provenance tracking (batch_index, document_id)
+ - Robust fallback mechanisms (ML -> Pattern -> Last Resort)
Main Classes:
- NamedEntityRecognizer: Main NER coordinator (confidence_threshold, merge_overlapping)
diff --git a/semantica/semantic_extract/coreference_resolver.py b/semantica/semantic_extract/coreference_resolver.py
index 2ca1ba34..080b0436 100644
--- a/semantica/semantic_extract/coreference_resolver.py
+++ b/semantica/semantic_extract/coreference_resolver.py
@@ -86,6 +86,7 @@ class CoreferenceChain:
mentions: List[Mention]
representative: Mention
entity_type: Optional[str] = None
+ metadata: Dict[str, Any] = field(default_factory=dict)
class CoreferenceResolver:
@@ -121,12 +122,18 @@ class CoreferenceResolver:
)
self.chain_builder = CoreferenceChainBuilder(**self.config.get("chain", {}))
- def resolve_coreferences(self, text: str, **options) -> List[CoreferenceChain]:
+ def resolve_coreferences(
+ self,
+ text: str,
+ entities: Optional[List[Entity]] = None,
+ **options
+ ) -> List[CoreferenceChain]:
"""
Resolve coreferences in text.
Args:
text: Input text
+ entities: List of entities (optional)
**options: Resolution options
Returns:
@@ -139,6 +146,8 @@ class CoreferenceResolver:
)
try:
+ from .ner_extractor import NERExtractor
+
total_steps = 4 # Extract mentions, resolve pronouns, detect coreferences, build chains
current_step = 0
@@ -151,8 +160,38 @@ class CoreferenceResolver:
total=total_steps,
message=f"Extracting mentions... ({current_step}/{total_steps}, remaining: {remaining_steps} steps)"
)
+
+ # Extract pronouns
mentions = self._extract_mentions(text)
+ # Add entities as mentions
+ if entities is None:
+ # Extract entities if not provided
+ ner_config = self.config.get("ner", {})
+ if "ner_method" in self.config:
+ ner_config["method"] = self.config["ner_method"]
+ ner = NERExtractor(
+ **ner_config,
+ **{
+ k: v
+ for k, v in self.config.items()
+ if k not in ["ner", "relation", "chain", "entity", "pronoun"]
+ },
+ )
+ entities = ner.extract_entities(text, **options)
+
+ if entities:
+ for entity in entities:
+ mentions.append(
+ Mention(
+ text=entity.text,
+ start_char=entity.start_char,
+ end_char=entity.end_char,
+ mention_type="entity",
+ metadata={"entity_label": entity.label, "confidence": entity.confidence},
+ )
+ )
+
# Step 2: Resolve pronouns
current_step += 1
remaining_steps = total_steps - current_step
@@ -203,18 +242,120 @@ class CoreferenceResolver:
)
raise
- def resolve(self, text: str, **options) -> List[CoreferenceChain]:
+ def resolve(
+ self,
+ text: Union[str, List[str], List[Dict[str, Any]]],
+ entities: Optional[Union[List[Entity], List[List[Entity]]]] = None,
+ pipeline_id: Optional[str] = None,
+ **kwargs
+ ) -> Union[List[CoreferenceChain], List[List[CoreferenceChain]]]:
"""
- Resolve coreferences in text (alias for resolve_coreferences).
+ Resolve coreferences in text or list of documents.
+ Handles batch processing with progress tracking.
Args:
- text: Input text
- **options: Resolution options
+ text: Input text or list of documents
+ entities: List of entities or list of list of entities (optional)
+ pipeline_id: Optional pipeline ID for progress tracking
+ **kwargs: Resolution options
Returns:
- list: List of coreference chains
+ Union[List[CoreferenceChain], List[List[CoreferenceChain]]]: Resolved coreference chains
"""
- return self.resolve_coreferences(text, **options)
+ if isinstance(text, list):
+ # Handle batch resolution with progress tracking
+ tracking_id = self.progress_tracker.start_tracking(
+ module="semantic_extract",
+ submodule="CoreferenceResolver",
+ message=f"Batch resolving coreferences from {len(text)} documents",
+ pipeline_id=pipeline_id,
+ )
+
+ try:
+ results = []
+ total_items = len(text)
+ total_chains_count = 0
+
+ # Determine update interval
+ if total_items <= 10:
+ update_interval = 1
+ else:
+ update_interval = max(1, min(10, total_items // 100))
+
+ # Initial progress update
+ self.progress_tracker.update_progress(
+ tracking_id,
+ processed=0,
+ total=total_items,
+ message=f"Starting batch resolution... 0/{total_items} (remaining: {total_items})"
+ )
+
+ for idx, item in enumerate(text):
+ # Prepare arguments for single item
+ doc_text = item["content"] if isinstance(item, dict) and "content" in item else str(item)
+
+ doc_entities = None
+ if entities and idx < len(entities):
+ doc_entities = entities[idx]
+
+ # Resolve
+ chains = self.resolve_coreferences(doc_text, entities=doc_entities, **kwargs)
+
+ # Add provenance metadata
+ for chain in chains:
+ # Update chain metadata
+ if chain.metadata is None:
+ chain.metadata = {}
+ chain.metadata["batch_index"] = idx
+ if isinstance(item, dict) and "id" in item:
+ chain.metadata["document_id"] = item["id"]
+
+ # Update mentions metadata
+ for mention in chain.mentions:
+ if mention.metadata is None:
+ mention.metadata = {}
+ mention.metadata["batch_index"] = idx
+ if isinstance(item, dict) and "id" in item:
+ mention.metadata["document_id"] = item["id"]
+
+ # Update representative metadata
+ if chain.representative:
+ if chain.representative.metadata is None:
+ chain.representative.metadata = {}
+ chain.representative.metadata["batch_index"] = idx
+ if isinstance(item, dict) and "id" in item:
+ chain.representative.metadata["document_id"] = item["id"]
+
+ results.append(chains)
+ total_chains_count += len(chains)
+
+ # Update progress
+ if (idx + 1) % update_interval == 0 or (idx + 1) == total_items:
+ remaining = total_items - (idx + 1)
+ self.progress_tracker.update_progress(
+ tracking_id,
+ processed=idx + 1,
+ total=total_items,
+ message=f"Processing... {idx + 1}/{total_items} (remaining: {remaining}) - Resolved {total_chains_count} chains"
+ )
+
+ self.progress_tracker.stop_tracking(
+ tracking_id,
+ status="completed",
+ message=f"Batch resolution completed. Processed {len(results)} documents, resolved {total_chains_count} chains.",
+ )
+ return results
+
+ except Exception as e:
+ self.progress_tracker.stop_tracking(
+ tracking_id, status="failed", message=str(e)
+ )
+ raise
+
+ else:
+ # Single item
+ return self.resolve_coreferences(text, entities=entities, **kwargs)
+
def _extract_mentions(self, text: str) -> List[Mention]:
"""Extract all mentions from text."""
mentions = []
@@ -346,15 +487,49 @@ class PronounResolver:
if m.mention_type == "entity" or m.mention_type == "nominal"
]
- # Simple resolution: find closest preceding entity
+ # Simple resolution: find closest preceding entity with compatible type
+ pronoun_types = {
+ "he": ["PERSON"],
+ "him": ["PERSON"],
+ "his": ["PERSON"],
+ "she": ["PERSON"],
+ "her": ["PERSON"],
+ "it": ["ORG", "GPE", "LOC", "PRODUCT", "EVENT", "FAC", "WORK_OF_ART", "LAW", "LANGUAGE", "DATE", "TIME", "PERCENT", "MONEY", "QUANTITY", "ORDINAL", "CARDINAL"],
+ "its": ["ORG", "GPE", "LOC", "PRODUCT", "EVENT", "FAC", "WORK_OF_ART", "LAW", "LANGUAGE", "DATE", "TIME", "PERCENT", "MONEY", "QUANTITY", "ORDINAL", "CARDINAL"],
+ "they": ["ORG", "GPE", "PERSON", "NORP"], # Can be groups of people or organizations
+ "them": ["ORG", "GPE", "PERSON", "NORP"],
+ "their": ["ORG", "GPE", "PERSON", "NORP"],
+ }
+
for pronoun in pronouns:
# Find preceding entities
preceding = [e for e in entities if e.end_char < pronoun.start_char]
if preceding:
- # Take closest
- antecedent = max(preceding, key=lambda e: e.end_char)
+ pronoun_lower = pronoun.text.lower()
+ compatible_types = pronoun_types.get(pronoun_lower)
+
+ antecedent = None
+
+ if compatible_types:
+ # Filter by type
+ compatible = [
+ e for e in preceding
+ if e.metadata and e.metadata.get("entity_label") in compatible_types
+ ]
+ if compatible:
+ # Take closest compatible
+ antecedent = max(compatible, key=lambda e: e.end_char)
+
+ # Fallback to closest if no compatible found or pronoun type unknown
+ if antecedent is None:
+ antecedent = max(preceding, key=lambda e: e.end_char)
+
resolutions.append((pronoun.text, antecedent.text))
+
+ # Update pronoun metadata and link to antecedent
+ pronoun.entity_id = antecedent.text
+ pronoun.metadata["antecedent_text"] = antecedent.text
return resolutions
@@ -431,32 +606,59 @@ class CoreferenceChainBuilder:
list: List of coreference chains
"""
chains = []
+ processed_indices = set()
- # Simple implementation: group by text similarity
- processed = set()
-
- for mention in mentions:
- if mention.text.lower() in processed:
+ for i, mention in enumerate(mentions):
+ if i in processed_indices:
continue
- # Find similar mentions
- similar = [
- m
- for m in mentions
- if m.text.lower() == mention.text.lower()
- or self._similar_mentions(mention.text, m.text)
- ]
-
- if len(similar) > 1:
- processed.add(mention.text.lower())
-
- # Representative is first (leftmost) mention
- representative = min(similar, key=lambda m: m.start_char)
+ # Start a new group
+ group = [mention]
+ processed_indices.add(i)
+
+ # Find related mentions
+ for j, other in enumerate(mentions):
+ if j in processed_indices:
+ continue
+
+ is_related = False
+
+ # 1. Text similarity
+ if (
+ other.text.lower() == mention.text.lower()
+ or self._similar_mentions(mention.text, other.text)
+ ):
+ is_related = True
+
+ # 2. Pronoun resolution (entity_id matches text or entity_id matches entity_id)
+ elif mention.entity_id and (
+ mention.entity_id == other.text
+ or mention.entity_id == other.entity_id
+ ):
+ is_related = True
+ elif other.entity_id and (
+ other.entity_id == mention.text
+ or other.entity_id == mention.entity_id
+ ):
+ is_related = True
+
+ if is_related:
+ group.append(other)
+ processed_indices.add(j)
+
+ if len(group) > 1:
+ # Representative is first (leftmost) mention, or prefer entity over pronoun
+ # Prefer entity mention as representative
+ entities = [m for m in group if m.mention_type != "pronoun"]
+ if entities:
+ representative = min(entities, key=lambda m: m.start_char)
+ else:
+ representative = min(group, key=lambda m: m.start_char)
chain = CoreferenceChain(
- mentions=similar,
+ mentions=group,
representative=representative,
- entity_type=similar[0].metadata.get("entity_label"),
+ entity_type=representative.metadata.get("entity_label"),
)
chains.append(chain)
diff --git a/semantica/semantic_extract/event_detector.py b/semantica/semantic_extract/event_detector.py
index 5d1d4270..470e6ebf 100644
--- a/semantica/semantic_extract/event_detector.py
+++ b/semantica/semantic_extract/event_detector.py
@@ -147,6 +147,97 @@ class EventDetector:
"meeting": r"met|meeting|conference|summit",
}
+ def extract(
+ self,
+ text: Union[str, List[str], List[Dict[str, Any]]],
+ pipeline_id: Optional[str] = None,
+ **kwargs
+ ) -> Union[List[Event], List[List[Event]]]:
+ """
+ Detect events in text or list of documents.
+ Handles batch processing with progress tracking.
+
+ Args:
+ text: Input text or list of documents
+ pipeline_id: Optional pipeline ID for progress tracking
+ **kwargs: Detection options
+
+ Returns:
+ Union[List[Event], List[List[Event]]]: Detected events
+ """
+ if isinstance(text, list):
+ # Handle batch detection with progress tracking
+ tracking_id = self.progress_tracker.start_tracking(
+ module="semantic_extract",
+ submodule="EventDetector",
+ message=f"Batch detecting events from {len(text)} documents",
+ pipeline_id=pipeline_id,
+ )
+
+ try:
+ results = []
+ total_items = len(text)
+ total_events_count = 0
+
+ # Determine update interval
+ if total_items <= 10:
+ update_interval = 1
+ else:
+ update_interval = max(1, min(10, total_items // 100))
+
+ # Initial progress update
+ self.progress_tracker.update_progress(
+ tracking_id,
+ processed=0,
+ total=total_items,
+ message=f"Starting batch detection... 0/{total_items} (remaining: {total_items})"
+ )
+
+ for idx, item in enumerate(text):
+ # Prepare arguments for single item
+ doc_text = item["content"] if isinstance(item, dict) and "content" in item else str(item)
+
+ # Detect
+ events = self.detect_events(doc_text, **kwargs)
+
+ # Add provenance metadata
+ for event in events:
+ if event.metadata is None:
+ event.metadata = {}
+ event.metadata["batch_index"] = idx
+ if isinstance(item, dict) and "id" in item:
+ event.metadata["document_id"] = item["id"]
+
+ results.append(events)
+ total_events_count += len(events)
+
+ # Update progress
+ if (idx + 1) % update_interval == 0 or (idx + 1) == total_items:
+ remaining = total_items - (idx + 1)
+ self.progress_tracker.update_progress(
+ tracking_id,
+ processed=idx + 1,
+ total=total_items,
+ message=f"Processing... {idx + 1}/{total_items} (remaining: {remaining}) - Detected {total_events_count} events"
+ )
+
+ self.progress_tracker.stop_tracking(
+ tracking_id,
+ status="completed",
+ message=f"Batch detection completed. Processed {len(results)} documents, detected {total_events_count} events.",
+ )
+ return results
+
+ except Exception as e:
+ self.progress_tracker.stop_tracking(
+ tracking_id, status="failed", message=str(e)
+ )
+ raise
+
+ else:
+ # Single item
+ return self.detect_events(text, **kwargs)
+
def detect_events(self, text: str, **options) -> List[Event]:
"""
Detect events in text content.
diff --git a/semantica/semantic_extract/extraction_validator.py b/semantica/semantic_extract/extraction_validator.py
index da2cef83..be315cd4 100644
--- a/semantica/semantic_extract/extraction_validator.py
+++ b/semantica/semantic_extract/extraction_validator.py
@@ -12,8 +12,8 @@ Supported Methods (for future extensibility):
Algorithms Used:
- Confidence Thresholding: Statistical threshold-based filtering
- - Duplicate Detection: Set-based and similarity-based deduplication
- - Consistency Checking: Rule-based and graph-based consistency validation
+ - Duplicate Detection: (Removed - handled by external module)
+ - Consistency Checking: (Removed - handled by external module)
- Quality Scoring: Weighted scoring algorithms for extraction quality
- Validation Metrics: Precision, recall, F1-score calculations
- Boundary Validation: Character position and text boundary checking
@@ -22,7 +22,6 @@ Key Features:
- Entity validation with confidence checking
- Relation validation and consistency checking
- Quality scoring and metrics calculation
- - Duplicate detection
- Confidence-based filtering
- Validation result reporting
- Method parameter support for future method-specific validation
@@ -47,8 +46,10 @@ Author: Semantica Contributors
License: MIT
"""
+from typing import List, Dict, Any, Optional, Set, Tuple, Union
from dataclasses import dataclass, field
-from typing import Any, Dict, List, Optional
+from datetime import datetime
+import re
from ..utils.exceptions import ProcessingError
from ..utils.logging import get_logger
@@ -66,6 +67,7 @@ class ValidationResult:
errors: List[str] = field(default_factory=list)
warnings: List[str] = field(default_factory=list)
metrics: Dict[str, Any] = field(default_factory=dict)
+ metadata: Dict[str, Any] = field(default_factory=dict)
class ExtractionValidator:
@@ -79,7 +81,6 @@ class ExtractionValidator:
method: Validation method (for future extensibility, currently unused)
**config: Configuration options:
- min_confidence: Minimum confidence threshold (default: 0.5)
- - validate_consistency: Check consistency (default: True)
"""
self.logger = get_logger("extraction_validator")
self.config = config
@@ -90,19 +91,30 @@ class ExtractionValidator:
self.method = method # Reserved for future method-based validation
self.min_confidence = config.get("min_confidence", 0.5)
- self.validate_consistency = config.get("validate_consistency", True)
- def validate_entities(self, entities: List[Entity], **options) -> ValidationResult:
+ def validate_entities(self, entities: Union[List[Entity], List[List[Entity]]], **options) -> Union[ValidationResult, List[ValidationResult]]:
"""
Validate extracted entities.
+ Handles both single list and batch list of entities.
Args:
- entities: List of entities
+ entities: List of entities or list of list of entities
**options: Validation options
Returns:
- ValidationResult: Validation result
+ ValidationResult or List[ValidationResult]: Validation result(s)
"""
+ # Handle batch validation
+ if entities and isinstance(entities, list) and len(entities) > 0 and isinstance(entities[0], list):
+ results = []
+ for idx, batch_entities in enumerate(entities):
+ res = self.validate_entities(batch_entities, **options)
+ # Ensure metadata has batch index
+ if "batch_index" not in res.metadata:
+ res.metadata["batch_index"] = idx
+ results.append(res)
+ return results
+
tracking_id = self.progress_tracker.start_tracking(
module="semantic_extract",
submodule="ExtractionValidator",
@@ -126,14 +138,6 @@ class ExtractionValidator:
f"{len(low_confidence)} entities below confidence threshold"
)
- # Check for duplicates
- self.progress_tracker.update_tracking(
- tracking_id, message="Checking for duplicates..."
- )
- entity_texts = [e.text.lower() for e in entities]
- duplicates = len(entity_texts) - len(set(entity_texts))
- if duplicates > 0:
- warnings.append(f"{duplicates} duplicate entities found")
# Check for empty entities
empty_entities = [e for e in entities if not e.text.strip()]
@@ -148,8 +152,7 @@ class ExtractionValidator:
[e for e in entities if min_confidence <= e.confidence < 0.8]
),
"low_confidence": len(low_confidence),
- "unique_entities": len(set(entity_texts)),
- "duplicates": duplicates,
+ "unique_entities": len(set(e.text for e in entities)),
"entity_types": len(set(e.label for e in entities)),
"average_confidence": sum(e.confidence for e in entities)
/ len(entities)
@@ -162,12 +165,23 @@ class ExtractionValidator:
valid = len(errors) == 0
+ # Collect metadata from entities
+ metadata = {}
+ if entities:
+ first = entities[0]
+ if hasattr(first, "metadata") and first.metadata:
+ if "batch_index" in first.metadata:
+ metadata["batch_index"] = first.metadata["batch_index"]
+ if "document_id" in first.metadata:
+ metadata["document_id"] = first.metadata["document_id"]
+
result = ValidationResult(
valid=valid,
score=score,
errors=errors,
warnings=warnings,
metrics=metrics,
+ metadata=metadata,
)
self.progress_tracker.stop_tracking(
@@ -184,18 +198,30 @@ class ExtractionValidator:
raise
def validate_relations(
- self, relations: List[Relation], **options
- ) -> ValidationResult:
+ self, relations: Union[List[Relation], List[List[Relation]]], **options
+ ) -> Union[ValidationResult, List[ValidationResult]]:
"""
Validate extracted relations.
+ Handles both single list and batch list of relations.
Args:
- relations: List of relations
+ relations: List of relations or list of list of relations
**options: Validation options
Returns:
- ValidationResult: Validation result
+ ValidationResult or List[ValidationResult]: Validation result(s)
"""
+ # Handle batch validation
+ if relations and isinstance(relations, list) and len(relations) > 0 and isinstance(relations[0], list):
+ results = []
+ for idx, batch_relations in enumerate(relations):
+ res = self.validate_relations(batch_relations, **options)
+ # Ensure metadata has batch index
+ if "batch_index" not in res.metadata:
+ res.metadata["batch_index"] = idx
+ results.append(res)
+ return results
+
errors = []
warnings = []
metrics = {}
@@ -218,12 +244,6 @@ class ExtractionValidator:
if invalid_relations:
errors.append(f"{len(invalid_relations)} invalid relations found")
- # Check consistency
- if self.validate_consistency:
- consistency_issues = self._check_consistency(relations)
- if consistency_issues:
- warnings.append(f"{len(consistency_issues)} consistency issues found")
-
# Calculate metrics
metrics = {
"total_relations": len(relations),
@@ -244,31 +264,25 @@ class ExtractionValidator:
valid = len(errors) == 0
+ # Collect metadata from relations
+ metadata = {}
+ if relations:
+ first = relations[0]
+ if hasattr(first, "metadata") and first.metadata:
+ if "batch_index" in first.metadata:
+ metadata["batch_index"] = first.metadata["batch_index"]
+ if "document_id" in first.metadata:
+ metadata["document_id"] = first.metadata["document_id"]
+
return ValidationResult(
- valid=valid, score=score, errors=errors, warnings=warnings, metrics=metrics
+ valid=valid,
+ score=score,
+ errors=errors,
+ warnings=warnings,
+ metrics=metrics,
+ metadata=metadata
)
- def _check_consistency(self, relations: List[Relation]) -> List[str]:
- """Check consistency of relations."""
- issues = []
-
- # Check for contradictory relations
- relation_pairs = {}
- for relation in relations:
- key = (relation.subject.text, relation.object.text)
- if key not in relation_pairs:
- relation_pairs[key] = []
- relation_pairs[key].append(relation.predicate)
-
- # Find contradictions (e.g., "founded_by" and "founded" for same pair)
- for key, predicates in relation_pairs.items():
- if len(set(predicates)) > 1:
- # Check for obvious contradictions
- if "founded_by" in predicates and "founded" in predicates:
- issues.append(f"Contradictory relations for {key}")
-
- return issues
-
def _calculate_entity_score(
self, entities: List[Entity], metrics: Dict[str, Any]
) -> float:
diff --git a/semantica/semantic_extract/llm_extraction.py b/semantica/semantic_extract/llm_extraction.py
index 1a6f4cb7..2c0dd3c4 100644
--- a/semantica/semantic_extract/llm_extraction.py
+++ b/semantica/semantic_extract/llm_extraction.py
@@ -289,7 +289,14 @@ Return the enhanced relation list in JSON format."""
) -> List[Entity]:
"""Parse LLM response for entities."""
# Simplified parsing - in practice would parse JSON
- # For now, return original entities
+ # For now, return original entities with updated metadata
+ for entity in original_entities:
+ if entity.metadata is None:
+ entity.metadata = {}
+ entity.metadata.update({
+ "enhanced_by": self.provider_name,
+ "model": self.model
+ })
return original_entities
def _parse_relation_response(
@@ -297,7 +304,14 @@ Return the enhanced relation list in JSON format."""
) -> List[Relation]:
"""Parse LLM response for relations."""
# Simplified parsing - in practice would parse JSON
- # For now, return original relations
+ # For now, return original relations with updated metadata
+ for relation in original_relations:
+ if relation.metadata is None:
+ relation.metadata = {}
+ relation.metadata.update({
+ "enhanced_by": self.provider_name,
+ "model": self.model
+ })
return original_relations
diff --git a/semantica/semantic_extract/methods.py b/semantica/semantic_extract/methods.py
index f33e8124..5edc6e40 100644
--- a/semantica/semantic_extract/methods.py
+++ b/semantica/semantic_extract/methods.py
@@ -106,6 +106,7 @@ License: MIT
"""
import re
+import difflib
from typing import Any, Dict, List, Optional, Union
from ..utils.exceptions import ProcessingError
@@ -130,6 +131,275 @@ from ..utils.helpers import safe_import
spacy, SPACY_AVAILABLE = safe_import("spacy")
+# ============================================================================
+# Scoring Helper Functions
+# ============================================================================
+
+# Global cache for spacy model and text embedder to avoid reloading
+_nlp_cache = None
+_embedder_cache = None
+
+def get_text_embedder():
+ """
+ Get or load the TextEmbedder model for high-accuracy semantic similarity.
+ """
+ global _embedder_cache
+ if _embedder_cache:
+ return _embedder_cache
+
+ try:
+ from ..embeddings.text_embedder import TextEmbedder
+ # Use a lightweight but effective model for speed/accuracy balance
+ # BAAI/bge-small-en-v1.5 is excellent for semantic similarity
+ # Enable caching within the embedder if supported, or use our own
+ _embedder_cache = TextEmbedder(model_name="BAAI/bge-small-en-v1.5", normalize=True)
+ logger.info("Loaded TextEmbedder for high-accuracy similarity")
+ return _embedder_cache
+ except Exception as e:
+ logger.warning(f"Failed to load TextEmbedder: {e}")
+ return None
+
+def get_nlp_model():
+ """
+ Get or load a spaCy model for similarity calculations.
+ Prioritizes larger models for better vectors.
+ """
+ global _nlp_cache
+ if _nlp_cache:
+ return _nlp_cache
+
+ if not SPACY_AVAILABLE:
+ return None
+
+ try:
+ # Prefer larger models for vectors
+ # Note: 'en_core_web_lg' has true vectors. 'sm' only has context tensors.
+ for model_name in ["en_core_web_lg", "en_core_web_md", "en_core_web_sm"]:
+ if spacy.util.is_package(model_name):
+ try:
+ # Disable parser/ner for speed if we only need vectors
+ _nlp_cache = spacy.load(model_name, disable=["parser", "ner", "lemmatizer"])
+ logger.info(f"Loaded spaCy model for similarity: {model_name}")
+ return _nlp_cache
+ except Exception:
+ continue
+
+ # Try loading generic if specific ones fail
+ try:
+ _nlp_cache = spacy.load("en_core_web_sm", disable=["parser", "ner", "lemmatizer"])
+ return _nlp_cache
+ except:
+ pass
+
+ except Exception as e:
+ logger.warning(f"Failed to load spaCy model for similarity: {e}")
+ pass
+ return None
+
+def calculate_similarity(text: str, candidates: List[str]) -> float:
+ """
+ Calculate the maximum similarity between text and a list of candidates.
+ Uses a hybrid approach: Exact -> Substring -> Vectors -> Fuzzy.
+ """
+ if not candidates:
+ return 0.0
+
+ if not text:
+ return 0.0
+
+ text_lower = text.lower().strip()
+ if not text_lower:
+ return 0.0
+
+ best_score = 0.0
+
+ # 1. Exact Match (Fastest)
+ candidates_lower = [c.lower().strip() for c in candidates if c]
+ if text_lower in candidates_lower:
+ return 1.0
+
+ # 1b. Common Synonyms (Fast Heuristic)
+ # Map common NER labels and Relations to user-friendly types
+ synonyms = {
+ # Entity Types
+ "person": ["people", "human", "name", "individual", "artist", "actor", "author", "politician"],
+ "org": ["company", "organization", "business", "institution", "agency", "brand", "corporation"],
+ "organization": ["company", "business", "institution", "agency", "brand", "corporation"],
+ "gpe": ["location", "place", "city", "country", "state", "nation", "region"],
+ "loc": ["location", "place", "region", "area"],
+ "date": ["time", "year", "day", "month", "period", "duration"],
+ "money": ["cost", "price", "value", "currency", "amount"],
+ "product": ["item", "object", "commodity", "goods", "device", "tool", "vehicle", "software", "app"],
+ "event": ["incident", "occasion", "activity", "happening", "ceremony"],
+ "drug": ["medication", "medicine", "pharmaceutical", "chemical", "treatment", "therapy"],
+ "chemical": ["drug", "substance", "compound", "element"],
+ "disease": ["condition", "illness", "sickness", "disorder", "syndrome", "ailment"],
+
+ # Relation Types
+ "founded_by": ["founder", "creator", "established_by", "started_by", "originator"],
+ "acquired": ["bought", "purchased", "acquisition", "takeover", "ownership", "merged_with"],
+ "subsidiary_of": ["owned_by", "parent_company", "part_of", "division_of", "unit_of"],
+ "works_for": ["employee_of", "employed_by", "staff_of", "team_member", "employs", "hired_by"],
+ "located_in": ["based_in", "headquartered_in", "situated_in", "found_in", "operates_in"],
+ "ceo_of": ["leader_of", "head_of", "director_of", "president_of", "chief_executive", "managed_by"],
+ "invested_in": ["funded", "financed", "backed", "shareholder_of", "venture_capital"],
+ "partner_with": ["collaborate_with", "joint_venture", "alliance", "deal_with", "partnership"],
+ "competitor_of": ["rival", "competes_with", "opponent", "nemesis"],
+ "manufacturer_of": ["producer_of", "maker_of", "creator_of", "builder_of"],
+ "treats": ["cures", "heals", "remedy_for", "used_for", "prescribed_for"],
+ "causes": ["leads_to", "results_in", "triggers", "produces", "creates"],
+ "diagnosed_with": ["suffers_from", "has_condition", "patient_of", "victim_of"],
+ }
+
+ if text_lower in synonyms:
+ for syn in synonyms[text_lower]:
+ if syn in candidates_lower:
+ return 0.95
+ # Also check reverse: if candidate is in synonyms of text
+
+ # Check if any candidate is a synonym of the text
+ for cand in candidates_lower:
+ if cand in synonyms:
+ if text_lower in synonyms[cand]:
+ return 0.95
+
+ # 2. Substring Match (Fast)
+ # Give a boost if one is contained in the other, but penalize by length difference
+ for cand in candidates_lower:
+ if text_lower == cand:
+ return 1.0
+ if text_lower in cand or cand in text_lower:
+ # Calculate length ratio
+ ratio = min(len(text_lower), len(cand)) / max(len(text_lower), len(cand))
+ # Base score 0.85 for containment, adjusted by ratio
+ # e.g. "Apple" in "Apple Inc" -> 0.85 * (5/9) ~= 0.47 (too low?)
+ # Let's be more generous for containment
+ score = 0.9 * ratio + 0.1 # Boost slightly
+ if score > best_score:
+ best_score = score
+
+ # 3. Text Embeddings (High Accuracy Semantic)
+ # This is the most accurate method for diverse/unknown domains
+ embedder = get_text_embedder()
+ embedding_score = 0.0
+
+ if embedder:
+ try:
+ # Embed text and candidates
+ # Batch embedding is faster and scalable without caching
+ all_texts = [text] + candidates
+ embeddings = list(embedder.embed_batch(all_texts))
+
+ if embeddings and len(embeddings) > 1:
+ text_emb = embeddings[0]
+ cand_embs = embeddings[1:]
+
+ # Calculate cosine similarity manually or via numpy
+ import numpy as np
+ text_norm = np.linalg.norm(text_emb)
+
+ if text_norm > 0:
+ for cand_emb in cand_embs:
+ cand_norm = np.linalg.norm(cand_emb)
+ if cand_norm > 0:
+ sim = np.dot(text_emb, cand_emb) / (text_norm * cand_norm)
+ if sim > embedding_score:
+ embedding_score = sim
+ except Exception as e:
+ logger.debug(f"Embedding calculation failed: {e}")
+ pass
+
+ if embedding_score > best_score:
+ best_score = embedding_score
+
+ # 4. Vector Similarity (Legacy/Fallback)
+ # Only use if we haven't found a good match yet and embeddings failed/unavailable
+ if best_score < 0.9:
+ nlp = get_nlp_model()
+ vector_score = 0.0
+ if nlp and nlp.vocab.vectors.shape[0] > 0:
+ try:
+ # Only use vectors if the word is in vocab or we have a good model
+ doc = nlp(text)
+ if doc.vector_norm:
+ for candidate in candidates:
+ cand_doc = nlp(candidate)
+ if cand_doc.vector_norm:
+ score = doc.similarity(cand_doc)
+ if score > vector_score:
+ vector_score = score
+ except Exception:
+ pass
+
+ if vector_score > best_score:
+ best_score = vector_score
+
+ # 4. Fuzzy Match (Fallback/Refinement)
+ # If vector score is low (e.g. OOV words), fuzzy match might be better
+ # But difflib is slow for many candidates.
+ # Only run if we don't have a very high score yet
+ if best_score < 0.9:
+ for cand in candidates_lower:
+ # Quick check for common characters
+ if not cand: continue
+
+ # SequenceMatcher
+ score = difflib.SequenceMatcher(None, text_lower, cand).ratio()
+ if score > best_score:
+ best_score = score
+
+ return float(best_score)
+
+def calculate_weighted_confidence(
+ item_type: str,
+ original_confidence: float,
+ valid_types: Optional[List[str]] = None,
+ item_text: Optional[str] = None,
+ weight_method: float = 0.5,
+ weight_similarity: float = 0.5
+) -> float:
+ """
+ Calculate weighted confidence score using both Label and Content similarity.
+ Final Score = (weight_method * original_confidence) + (weight_similarity * max(label_sim, content_sim))
+
+ Args:
+ item_type: The extracted type/label/predicate (e.g., "PERSON", "founded_by")
+ original_confidence: The confidence score from the extraction method (0.0-1.0)
+ valid_types: List of valid/preferred types provided by user
+ item_text: The actual text content extracted (e.g., "Steve Jobs", "acquired")
+ weight_method: Weight for the original method confidence (default 0.5)
+ weight_similarity: Weight for the similarity score (default 0.5)
+
+ Returns:
+ float: Weighted confidence score (0.0-1.0)
+ """
+ if not valid_types:
+ return original_confidence
+
+ # Similarity 1: Label vs Valid Types (e.g., "PERSON" vs "Artist")
+ label_similarity = calculate_similarity(item_type, valid_types)
+
+ # Similarity 2: Content vs Valid Types (e.g., "Picasso" vs "Artist")
+ content_similarity = 0.0
+ if item_text:
+ content_similarity = calculate_similarity(item_text, valid_types)
+
+ # Take the best similarity match
+ best_similarity = max(label_similarity, content_similarity)
+
+ # Normalize weights
+ total_weight = weight_method + weight_similarity
+ if total_weight <= 0:
+ return original_confidence
+
+ w_m = weight_method / total_weight
+ w_s = weight_similarity / total_weight
+
+ final_score = (w_m * original_confidence) + (w_s * best_similarity)
+
+ return max(0.0, min(1.0, final_score))
+
+
# ============================================================================
# Entity Extraction Methods
# ============================================================================
@@ -140,8 +410,8 @@ def extract_entities_pattern(text: str, **kwargs) -> List[Entity]:
entities = []
patterns = {
- "PERSON": r"\b([A-Z][a-z]+(?:\s+[A-Z][a-z]+)+)\b",
- "ORG": r"\b([A-Z][a-zA-Z]+(?:\s+[A-Z][a-zA-Z]+)*\s+(?:Inc|Corp|LLC|Ltd|Company))\b",
+ "ORG": r"\b([A-Z][a-zA-Z]+(?:\s+[A-Z][a-zA-Z]+)*\s+(?:Inc|Corp|LLC|Ltd|Company)(?:\.|\b))",
+ "PERSON": r"\b([A-Z][a-z]+(?:\s+(?!Inc|Corp|LLC|Ltd|Company)[A-Z][a-z]+)+)\b",
"GPE": r"\b([A-Z][a-z]+\s*(?:City|State|Country|Nation))\b",
"DATE": r"\b(\d{1,2}[/-]\d{1,2}[/-]\d{2,4}|\d{4})\b",
}
@@ -405,11 +675,30 @@ Use the most appropriate type for each entity, including variations or synonyms
raise ImportError("Pydantic schemas not available. Install pydantic/instructor to use LLM extraction.")
try:
- prompt = f"""Extract named entities from the following text.
+ prompt = f"""Extract named entities from the provided text.
Return the result as a JSON object with an "entities" key containing the list of entities.
-{entity_types_instruction}
-
-Text: {text}"""
+Each entity should have 'text', 'label', and 'confidence' fields.
+
+IMPORTANT:
+- Return a FLAT LIST of entities.
+- DO NOT group entities by type.
+- The output structure must exactly match: {{ "entities": [ {{ "text": "...", "label": "...", "confidence": ... }}, ... ] }}
+
+Example output (JSON format only):
+{{
+ "entities": [
+ {{"text": "Entity Name", "label": "CATEGORY", "confidence": 0.95}},
+ {{"text": "Another Entity", "label": "OTHER_CATEGORY", "confidence": 0.90}}
+ ]
+}}
+
+Instructions:
+1. Extract entities ONLY from the text provided below.
+2. Do not include any entities from the example above.
+3. {entity_types_instruction}
+
+Text to extract from:
+{text}"""
# Use typed generation with Pydantic schema
result_obj = llm.generate_typed(prompt, schema=EntitiesResponse)
@@ -525,22 +814,10 @@ def _extract_entities_chunked(
all_entities.extend(chunk_entities)
- return _deduplicate_entities(all_entities)
+ return all_entities
+
-def _deduplicate_entities(entities: List[Entity]) -> List[Entity]:
- """Remove duplicate entities, keeping those with higher confidence or more metadata."""
- if not entities:
- return []
-
- # Sort by text, start_char, and confidence
- unique_entities = {}
- for ent in entities:
- key = (ent.text.lower(), ent.start_char, ent.end_char, ent.label)
- if key not in unique_entities or ent.confidence > unique_entities[key].confidence:
- unique_entities[key] = ent
-
- return sorted(list(unique_entities.values()), key=lambda e: e.start_char)
# ============================================================================
@@ -578,17 +855,17 @@ def extract_relations_pattern(
relation_patterns = {
"founded_by": [
- fr"(?P<subject>{subject_pat})\s+(?:was\s+)?founded\s+by\s+(?P<object>{ent_pat})",
- fr"(?P<object>{ent_pat})\s+founded\s+(?P<subject>{ent_pat})",
- fr"(?P<subject>{subject_pat})\s+(?:was\s+)?established\s+by\s+(?P<object>{ent_pat})",
- fr"(?P<object>{ent_pat})\s+established\s+(?P<subject>{ent_pat})",
- fr"(?P<subject>{subject_pat})\s+(?:was\s+)?created\s+by\s+(?P<object>{ent_pat})",
- fr"(?P<object>{ent_pat})\s+created\s+(?P<subject>{ent_pat})",
- fr"(?P<subject>{subject_pat})\s+(?:was\s+)?started\s+by\s+(?P<object>{ent_pat})",
- fr"(?P<object>{ent_pat})\s+started\s+(?P<subject>{ent_pat})",
- fr"(?P<subject>{subject_pat})\s+(?:was\s+)?co-founded\s+by\s+(?P<object>{ent_pat})",
- fr"(?P<object>{ent_pat})\s+co-founded\s+(?P<subject>{ent_pat})",
- fr"(?P<object>{ent_pat})\s+is\s+(?:the\s+)?founder\s+of\s+(?P<subject>{ent_pat})",
+ fr"(?P<subject>{subject_pat})(?:[.,])?\s+(?:was\s+)?founded\s+by\s+(?P<object>{ent_pat})",
+ fr"(?P<object>{ent_pat})(?:[.,])?\s+founded\s+(?P<subject>{ent_pat})",
+ fr"(?P<subject>{subject_pat})(?:[.,])?\s+(?:was\s+)?established\s+by\s+(?P<object>{ent_pat})",
+ fr"(?P<object>{ent_pat})(?:[.,])?\s+established\s+(?P<subject>{ent_pat})",
+ fr"(?P<subject>{subject_pat})(?:[.,])?\s+(?:was\s+)?created\s+by\s+(?P<object>{ent_pat})",
+ fr"(?P<object>{ent_pat})(?:[.,])?\s+created\s+(?P<subject>{ent_pat})",
+ fr"(?P<subject>{subject_pat})(?:[.,])?\s+(?:was\s+)?started\s+by\s+(?P<object>{ent_pat})",
+ fr"(?P<object>{ent_pat})(?:[.,])?\s+started\s+(?P<subject>{ent_pat})",
+ fr"(?P<subject>{subject_pat})(?:[.,])?\s+(?:was\s+)?co-founded\s+by\s+(?P<object>{ent_pat})",
+ fr"(?P<object>{ent_pat})(?:[.,])?\s+co-founded\s+(?P<subject>{ent_pat})",
+ fr"(?P<object>{ent_pat})(?:[.,])?\s+is\s+(?:the\s+)?founder\s+of\s+(?P<subject>{ent_pat})",
],
"located_in": [
fr"(?P<subject>{subject_pat})\s+is\s+located\s+in\s+(?P<object>{ent_pat})",
@@ -625,26 +902,16 @@ def extract_relations_pattern(
}
entity_map = {e.text.lower(): e for e in entities}
- # DEBUG: Print entities in map
- print(f"DEBUG: Entity map keys: {list(entity_map.keys())}")
for relation_type, patterns in relation_patterns.items():
for pattern in patterns:
- # DEBUG: Print pattern being tried
- # print(f"DEBUG: Trying pattern: {pattern}")
for match in re.finditer(pattern, text, re.IGNORECASE):
subject_text = match.group("subject").strip()
object_text = match.group("object").strip()
- # DEBUG: Print match details
- print(f"DEBUG: Match found! Subject='{subject_text}', Object='{object_text}'")
-
subject_entity = entity_map.get(subject_text.lower())
object_entity = entity_map.get(object_text.lower())
- # DEBUG: Print lookup results
- print(f"DEBUG: Subject Entity found: {subject_entity is not None}, Object Entity found: {object_entity is not None}")
-
if subject_entity and object_entity:
start = max(0, match.start() - 50)
end = min(len(text), match.end() + 50)
@@ -744,6 +1011,127 @@ def extract_relations_cooccurrence(
return relations
+def extract_relations_similarity(
+ text: str, entities: List[Entity], relation_types: Optional[List[str]] = None, **kwargs
+) -> List[Relation]:
+ """
+ Similarity-based relation extraction.
+ Uses semantic similarity to match the context between entities to provided relation types.
+ """
+ if not entities:
+ return []
+
+ # If no relation types provided, we can't do similarity matching against types
+ if not relation_types:
+ # Fallback to co-occurrence if no types to match against
+ logger.warning("No relation types provided for similarity matching. Falling back to co-occurrence.")
+ return extract_relations_cooccurrence(text, entities, **kwargs)
+
+ relations = []
+
+ # Try to load spaCy model with vectors
+ nlp = None
+ if SPACY_AVAILABLE:
+ try:
+ # Prefer larger models for vectors
+ for model_name in ["en_core_web_lg", "en_core_web_md", "en_core_web_sm"]:
+ if spacy.util.is_package(model_name):
+ nlp = spacy.load(model_name)
+ break
+ if not nlp:
+ # Try loading what we have
+ try:
+ nlp = spacy.load("en_core_web_sm")
+ except:
+ pass
+ except Exception:
+ pass
+
+ # Pre-compute relation type vectors if possible
+ relation_vectors = {}
+ has_vectors = False
+ if nlp:
+ # Check if model has vectors
+ if nlp.vocab.vectors.shape[0] > 0:
+ has_vectors = True
+ for rt in relation_types:
+ relation_vectors[rt] = nlp(rt)
+
+ for entity1 in entities:
+ for entity2 in entities:
+ if entity1 == entity2:
+ continue
+
+ # Check distance
+ distance = abs(entity1.end_char - entity2.start_char)
+ # Only consider entities reasonably close (e.g., within same sentence or clause)
+ if distance > 100:
+ continue
+
+ # Ensure correct order for extracting text between
+ if entity1.end_char < entity2.start_char:
+ start_pos = entity1.end_char
+ end_pos = entity2.start_char
+ else:
+ start_pos = entity2.end_char
+ end_pos = entity1.start_char
+
+ between_text = text[start_pos:end_pos].strip()
+
+ if not between_text:
+ continue
+
+ # Calculate similarity
+ best_type = None
+ best_score = 0.0
+
+ if has_vectors and relation_vectors:
+ # Vector similarity
+ doc = nlp(between_text)
+ if doc.vector_norm:
+ for rt, vec in relation_vectors.items():
+ if vec.vector_norm:
+ sim = doc.similarity(vec)
+ if sim > best_score:
+ best_score = sim
+ best_type = rt
+ else:
+ # String similarity / Keyword matching
+ from difflib import SequenceMatcher
+ for rt in relation_types:
+ # Check for direct keyword presence (strong signal)
+ if rt.lower() in between_text.lower():
+ score = 1.0
+ else:
+ # Fuzzy match
+ score = SequenceMatcher(None, rt.lower(), between_text.lower()).ratio()
+
+ if score > best_score:
+ best_score = score
+ best_type = rt
+
+ # Threshold
+ threshold = kwargs.get("similarity_threshold", 0.4 if has_vectors else 0.6)
+
+ if best_type and best_score >= threshold:
+ relations.append(
+ Relation(
+ subject=entity1,
+ predicate=best_type,
+ object=entity2,
+ confidence=float(best_score),
+ context=text[max(0, min(entity1.start_char, entity2.start_char) - 20) : min(len(text), max(entity1.end_char, entity2.end_char) + 20)],
+ metadata={
+ "extraction_method": "similarity",
+ "similarity_score": float(best_score),
+ "between_text": between_text
+ },
+ )
+ )
+
+ return relations
+
+
def extract_relations_dependency(
text: str, entities: List[Entity], model: str = "en_core_web_sm", **kwargs
) -> List[Relation]:
@@ -996,12 +1384,27 @@ Common relation types include: related_to, part_of, located_in, created_by, uses
if not SCHEMAS_AVAILABLE:
raise ImportError("Pydantic schemas not available. Install pydantic/instructor to use LLM extraction.")
- prompt = f"""Extract relations between entities from the following text.
+ prompt = f"""Extract relations between entities from the provided text.
Return the result as a JSON object with a "relations" key containing the list of relations.
Each relation must have 'subject', 'predicate', and 'object' fields.
-Text: {text}
-Entities: {entities_str}{relation_types_instruction}"""
+Example output (JSON format only):
+{{
+ "relations": [
+ {{"subject": "Entity A", "predicate": "related_to", "object": "Entity B", "confidence": 0.95}},
+ {{"subject": "Subject Entity", "predicate": "action_verb", "object": "Object Entity", "confidence": 0.90}}
+ ]
+}}
+
+Instructions:
+1. Extract relations ONLY from the text provided below.
+2. Do not include any relations from the example above.
+3. Use the provided entities list as a reference for subjects and objects.
+4. {relation_types_instruction}
+
+Text to extract from:
+{text}
+Entities found in text: {entities_str}"""
try:
# Use typed generation with Pydantic schema
@@ -1154,25 +1557,10 @@ def _extract_relations_chunked(
)
all_relations.extend(chunk_rels)
- return _deduplicate_relations(all_relations)
+ return all_relations
+
-def _deduplicate_relations(relations: List[Relation]) -> List[Relation]:
- """Remove duplicate relations."""
- if not relations:
- return []
-
- unique_rels = {}
- for rel in relations:
- key = (
- rel.subject.text.lower(),
- rel.predicate.lower(),
- rel.object.text.lower()
- )
- if key not in unique_rels or rel.confidence > unique_rels[key].confidence:
- unique_rels[key] = rel
-
- return list(unique_rels.values())
# ============================================================================
@@ -1370,13 +1758,42 @@ def extract_triplets_llm(
**kwargs
)
+ # Use custom triplet types if provided
+ triplet_types = kwargs.get("triplet_types")
+ if triplet_types:
+ triplet_types_str = ", ".join(triplet_types)
+ triplet_types_instruction = f"""
+Preferred triplet predicates: {triplet_types_str}.
+You may also use related or similar predicates if they better capture the relationship (e.g., variations, synonyms, or domain-specific predicates).
+If a predicate doesn't fit any of the preferred types, use the most appropriate type from the preferred list or a closely related type that accurately describes the relationship."""
+ else:
+ triplet_types_instruction = """
+Extract meaningful triplets (subject-predicate-object). Use appropriate predicates that accurately describe the relationship.
+Common predicates include: is_a, part_of, has_property, related_to, caused_by, etc."""
+
if not SCHEMAS_AVAILABLE:
raise ImportError("Pydantic schemas not available. Install pydantic/instructor to use LLM extraction.")
- prompt = f"""Extract RDF triplets (subject-predicate-object) from the following text.
+ prompt = f"""Extract RDF triplets (subject-predicate-object) from the provided text.
Return the result as a JSON object with a "triplets" key containing the list of triplets.
+Each triplet must have 'subject', 'predicate', and 'object' fields.
+
+Example output (JSON format only):
+{{
+ "triplets": [
+ {{"subject": "Subject", "predicate": "predicate_relation", "object": "Object", "confidence": 0.99}},
+ {{"subject": "Concept A", "predicate": "is_a", "object": "Concept B", "confidence": 0.95}}
+ ]
+}}
+
+Instructions:
+1. Extract triplets ONLY from the text provided below.
+2. Do not include any triplets from the example above.
+3. Ensure subjects and objects are substrings from the text.
+4. {triplet_types_instruction}
-Text: {text}"""
+Text to extract from:
+{text}"""
try:
# Use typed generation with Pydantic schema
@@ -1486,21 +1903,9 @@ def _extract_triplets_chunked(
)
all_triplets.extend(chunk_triplets)
- return _deduplicate_triplets(all_triplets)
+ return all_triplets
-def _deduplicate_triplets(triplets: List[Triplet]) -> List[Triplet]:
- """Remove duplicate triplets."""
- if not triplets:
- return []
-
- unique_triplets = {}
- for t in triplets:
- key = (t.subject.lower(), t.predicate.lower(), t.object.lower())
- if key not in unique_triplets or t.confidence > unique_triplets[key].confidence:
- unique_triplets[key] = t
-
- return list(unique_triplets.values())
# ============================================================================
@@ -1547,6 +1952,7 @@ def get_relation_method(method_name: str):
"pattern": extract_relations_pattern,
"regex": extract_relations_regex,
"cooccurrence": extract_relations_cooccurrence,
+ "similarity": extract_relations_similarity,
"dependency": extract_relations_dependency,
"ml": extract_relations_dependency, # Alias for dependency
"spacy": extract_relations_dependency, # Alias for dependency
diff --git a/semantica/semantic_extract/ner_extractor.py b/semantica/semantic_extract/ner_extractor.py
index 19bf852c..b9901fd6 100644
--- a/semantica/semantic_extract/ner_extractor.py
+++ b/semantica/semantic_extract/ner_extractor.py
@@ -20,7 +20,12 @@ Algorithms Used:
- Transformer Models: BERT, RoBERTa, DistilBERT for token classification
- Large Language Models: GPT, Claude, Gemini for zero-shot/few-shot extraction
- Ensemble Voting: Majority voting and confidence-weighted aggregation
- - Deduplication: Set-based and similarity-based entity deduplication
+ - Weighted Confidence Scoring:
+ * Formula: Score = (0.5 * Method_Confidence) + (0.5 * Type_Similarity_Score)
+ * Method_Confidence: Confidence score from the extraction algorithm
+ * Type_Similarity_Score: Semantic match with user-provided entity types (Exact=1.0, Synonym=0.95, Embedding=Cosine_Sim)
+ - Hybrid Similarity Matching: Exact -> Synonym -> Substring -> Semantic Embedding (Batch Optimized)
+ - Last Resort Fallback: Capitalized word heuristic when all other methods fail
Key Features:
- Multiple extraction methods:
@@ -31,8 +36,9 @@ Key Features:
* HuggingFace: Custom HuggingFace NER models
* LLM-based: Large language model extraction
- Fallback chain support: Try methods in order until one succeeds
+ - Robust Fallbacks: Prevents empty results via ML -> Pattern -> Last Resort chain
- Ensemble voting: Combine results from multiple methods
- - Post-processing: Entity boundary validation and deduplication
+ - Post-processing: Entity boundary validation
- Multiple entity type support (PERSON, ORG, GPE, DATE, etc.)
- Confidence scoring and filtering
- Batch processing capabilities
@@ -90,7 +96,12 @@ class Entity:
class NERExtractor:
"""Named Entity Recognition extractor."""
- def __init__(self, method: Union[str, List[str]] = "ml", **config):
+ def __init__(
+ self,
+ method: Union[str, List[str]] = "ml",
+ entity_types: Optional[List[str]] = None,
+ **config
+ ):
"""
Initialize NER extractor.
@@ -103,6 +114,8 @@ class NERExtractor:
- "huggingface": HuggingFace model
- "llm": LLM-based extraction
- List of methods for fallback chain
+ entity_types: List of entity types to extract (e.g., ["PERSON", "ORG"]).
+ If provided, extraction methods will try to limit/focus on these types.
**config: Configuration options:
- model: Model name (for ML/HuggingFace methods)
- huggingface_model: HuggingFace model name
@@ -115,6 +128,7 @@ class NERExtractor:
"""
self.logger = get_logger("ner_extractor")
self.config = config
+ self.entity_types = entity_types
# Method configuration
self.method = method if isinstance(method, list) else [method]
@@ -166,6 +180,7 @@ class NERExtractor:
try:
results = []
total_items = len(text)
+ total_entities_count = 0
# Update more frequently: every 1% or at least every 10 items, but always update for small datasets
if total_items <= 10:
update_interval = 1 # Update every item for small datasets
@@ -183,16 +198,28 @@ class NERExtractor:
for idx, item in enumerate(text, 1):
try:
+ current_entities = []
if isinstance(item, dict) and "content" in item:
- results.append(self.extract_entities(item["content"], **kwargs))
+ current_entities = self.extract_entities(item["content"], **kwargs)
elif isinstance(item, str):
- results.append(self.extract_entities(item, **kwargs))
+ current_entities = self.extract_entities(item, **kwargs)
else:
# Try converting to string
try:
- results.append(self.extract_entities(str(item), **kwargs))
+ current_entities = self.extract_entities(str(item), **kwargs)
except Exception:
- results.append([])
+ current_entities = []
+
+ # Add provenance metadata
+ for ent in current_entities:
+ if ent.metadata is None:
+ ent.metadata = {}
+ ent.metadata["batch_index"] = idx - 1
+ if isinstance(item, dict) and "id" in item:
+ ent.metadata["document_id"] = item["id"]
+
+ results.append(current_entities)
+ total_entities_count += len(current_entities)
except Exception:
results.append([])
@@ -209,13 +236,13 @@ class NERExtractor:
tracking_id,
processed=idx,
total=total_items,
- message=f"Processing documents... {idx}/{total_items} (remaining: {remaining})"
+ message=f"Processing documents... {idx}/{total_items} (remaining: {remaining}) - Extracted {total_entities_count} entities so far"
)
self.progress_tracker.stop_tracking(
tracking_id,
status="completed",
- message=f"Extracted entities from {len(results)} documents",
+ message=f"Batch extraction completed. Processed {len(results)} documents, extracted {total_entities_count} entities.",
)
return results
except Exception as e:
@@ -260,10 +287,12 @@ class NERExtractor:
methods = [methods]
min_confidence = options.get("min_confidence", self.min_confidence)
- entity_types = options.get("entity_types")
+ entity_types = options.get("entity_types", self.entity_types)
# Merge config with options
all_options = {**self.config, **options}
+ if entity_types:
+ all_options["entity_types"] = entity_types
# Try each method in order (fallback chain)
all_entities = []
@@ -300,29 +329,36 @@ class NERExtractor:
api_key = os.getenv(env_key)
if api_key:
method_options["api_key"] = api_key
- # Pass entity_types to LLM method so it can use them in the prompt
- if entity_types:
- method_options["entity_types"] = entity_types
entities = method_func(text, **method_options)
- # Filter by confidence and entity types
- filtered = [e for e in entities if e.confidence >= min_confidence]
+ # Apply weighted scoring if entity_types are provided
if entity_types:
- # Case-insensitive and flexible matching for entity types
- entity_types_lower = {et.lower() for et in entity_types}
- filtered = [
- e for e in filtered
- if e.label.lower() in entity_types_lower
- or any(et.lower() in e.label.lower() or e.label.lower() in et.lower()
- for et in entity_types)
- ]
-
+ try:
+ from .methods import calculate_weighted_confidence
+ for e in entities:
+ e.confidence = calculate_weighted_confidence(
+ item_type=e.label,
+ original_confidence=e.confidence,
+ valid_types=entity_types,
+ item_text=e.text
+ )
+ except ImportError:
+ pass
+
+ # Filter by confidence
+ filtered = [e for e in entities if e.confidence >= min_confidence]
+
if filtered:
all_entities.append((method_name, filtered))
# If not using ensemble, return first successful result
if not self.ensemble_voting:
+ # Ensure default metadata
+ for e in filtered:
+ if e.metadata is None: e.metadata = {}
+ if "batch_index" not in e.metadata: e.metadata["batch_index"] = 0
+
self.progress_tracker.stop_tracking(
tracking_id,
status="completed",
@@ -342,7 +378,8 @@ class NERExtractor:
elif all_entities:
entities = all_entities[0][1] # Use first successful method
else:
- entities = []
+ # Fallback to pattern-based extraction if all models fail
+ entities = self._extract_fallback(text)
# Post-processing if enabled
if self.post_process and entities:
@@ -390,19 +427,12 @@ class NERExtractor:
def _post_process_entities(self, entities: List[Entity], text: str) -> List[Entity]:
"""Post-process entities for refinement."""
processed = []
- seen = set()
for entity in entities:
# Check boundaries
if entity.start_char < 0 or entity.end_char > len(text):
continue
- # Check for duplicates
- key = (entity.text.lower(), entity.label, entity.start_char)
- if key in seen:
- continue
- seen.add(key)
-
# Validate entity text matches
actual_text = text[entity.start_char : entity.end_char]
if actual_text.lower() != entity.text.lower():
@@ -457,6 +487,7 @@ class NERExtractor:
def _extract_fallback(self, text: str) -> List[Entity]:
"""Fallback entity extraction using simple patterns."""
entities = []
+ import re
# Simple patterns for common entity types
patterns = {
@@ -466,20 +497,49 @@ class NERExtractor:
"DATE": r"\b(\d{1,2}[/-]\d{1,2}[/-]\d{2,4}|\d{4})\b",
}
- import re
+ # Track covered ranges to avoid overlaps
+ covered_ranges = set()
for label, pattern in patterns.items():
for match in re.finditer(pattern, text):
- entities.append(
- Entity(
- text=match.group(1),
- label=label,
- start_char=match.start(),
- end_char=match.end(),
- confidence=0.7, # Lower confidence for pattern-based
- metadata={"extraction_method": "pattern"},
+ start, end = match.start(), match.end()
+ # Check overlap
+ is_overlap = any(r_start < end and r_end > start for r_start, r_end in covered_ranges)
+ if not is_overlap:
+ # Use group 1 if available, else group 0
+ text_val = match.group(1) if match.lastindex and match.lastindex >= 1 else match.group(0)
+
+ entities.append(
+ Entity(
+ text=text_val,
+ label=label,
+ start_char=start,
+ end_char=end,
+ confidence=0.7, # Lower confidence for pattern-based
+ metadata={"extraction_method": "pattern"},
+ )
)
- )
+ covered_ranges.add((start, end))
+
+ # Last Resort: If no entities found, try single capitalized words as generic entities
+ if not entities:
+ # Match any capitalized word of length > 2
+ cap_pattern = r"\b[A-Z][a-z]{2,}\b"
+ for match in re.finditer(cap_pattern, text):
+ start, end = match.start(), match.end()
+ is_overlap = any(r_start < end and r_end > start for r_start, r_end in covered_ranges)
+ if not is_overlap:
+ entities.append(
+ Entity(
+ text=match.group(0),
+ label="UNKNOWN",
+ start_char=start,
+ end_char=end,
+ confidence=0.5,
+ metadata={"extraction_method": "last_resort_pattern"},
+ )
+ )
+ covered_ranges.add((start, end))
return entities
@@ -494,7 +554,7 @@ class NERExtractor:
Returns:
list: List of entity lists for each text
"""
- return [self.extract_entities(text, **options) for text in texts]
+ return self.extract(texts, **options)
def classify_entities(self, entities: List[Entity]) -> Dict[str, List[Entity]]:
"""
diff --git a/semantica/semantic_extract/providers.py b/semantica/semantic_extract/providers.py
index d4fe7011..8b688cd2 100644
--- a/semantica/semantic_extract/providers.py
+++ b/semantica/semantic_extract/providers.py
@@ -252,8 +252,22 @@ class BaseProvider:
mode=instructor.Mode.GEMINI_JSON
)
elif provider_name == "GroqProvider" and self.client:
- # Groq is OpenAI-compatible but works best with JSON mode
- client = instructor.from_openai(self.client, mode=instructor.Mode.JSON)
+ # Try using from_groq if available (newer instructor versions)
+ if hasattr(instructor, "from_groq"):
+ client = instructor.from_groq(self.client, mode=instructor.Mode.JSON)
+ else:
+ # Fallback: Create OpenAI client pointing to Groq
+ # This avoids the "Client should be an instance of openai.OpenAI" warning
+ try:
+ from openai import OpenAI
+ groq_client = OpenAI(
+ base_url="https://api.groq.com/openai/v1",
+ api_key=self.client.api_key,
+ )
+ client = instructor.from_openai(groq_client, mode=instructor.Mode.JSON)
+ except Exception:
+ # Last resort: try passing the groq client directly
+ client = instructor.from_openai(self.client, mode=instructor.Mode.JSON)
elif provider_name == "OllamaProvider":
# Create OpenAI-compatible client for Ollama
try:
@@ -296,13 +310,19 @@ class BaseProvider:
# Map generate arguments to client arguments
# Instructor standardizes on chat.completions.create for OpenAI/Groq/Anthropic/Gemini
- response = client.chat.completions.create(
- model=kwargs.get("model", self.model),
- messages=[{"role": "user", "content": prompt}],
- response_model=schema,
- max_retries=max_retries,
- temperature=kwargs.get("temperature", 0.1), # Low temp for structured
- )
+ create_kwargs = {
+ "model": kwargs.get("model", self.model),
+ "messages": [{"role": "user", "content": prompt}],
+ "response_model": schema,
+ "max_retries": max_retries,
+ "temperature": kwargs.get("temperature", 0.1), # Low temp for structured
+ }
+
+ # Add provider-specific params
+ if provider_name == "GroqProvider":
+ create_kwargs["response_format"] = {"type": "json_object"}
+
+ response = client.chat.completions.create(**create_kwargs)
return response
except Exception as e:
self.logger.warning(f"Instructor generation failed ({e}), falling back to manual repair loop.")
@@ -325,6 +345,55 @@ class BaseProvider:
if isinstance(json_result, list) and hasattr(schema, "entities") and "entities" in schema.model_fields:
# Auto-wrap for entities
json_result = {"entities": json_result}
+
+ # Handle categorized dictionary input (e.g. {"PERSON": ["Name"], "ORG": ["Corp"]})
+ elif isinstance(json_result, dict) and hasattr(schema, "entities") and "entities" in schema.model_fields:
+ # Check if it's NOT already in the correct format (i.e., missing "entities" key)
+ if "entities" not in json_result:
+ # Check if values are lists, suggesting categorized output
+ is_categorized = any(isinstance(v, list) for v in json_result.values())
+ if is_categorized:
+ flat_entities = []
+ for label, items in json_result.items():
+ if isinstance(items, list):
+ for item in items:
+ if isinstance(item, str):
+ flat_entities.append({"text": item, "label": label})
+ elif isinstance(item, dict):
+ # If it's already a dict but nested under label
+ item["label"] = label
+ flat_entities.append(item)
+ json_result = {"entities": flat_entities}
+
+ # Handle categorized dictionary input for relations (e.g. {"founded_by": [{"subject":..., "object":...}]})
+ elif isinstance(json_result, dict) and hasattr(schema, "relations") and "relations" in schema.model_fields:
+ if "relations" not in json_result:
+ is_categorized = any(isinstance(v, list) for v in json_result.values())
+ if is_categorized:
+ flat_relations = []
+ for label, items in json_result.items():
+ if isinstance(items, list):
+ for item in items:
+ if isinstance(item, dict):
+ # If predicate is missing, use the key as predicate
+ if "predicate" not in item:
+ item["predicate"] = label
+ flat_relations.append(item)
+ json_result = {"relations": flat_relations}
+
+ # Handle categorized dictionary input for triplets
+ elif isinstance(json_result, dict) and hasattr(schema, "triplets") and "triplets" in schema.model_fields:
+ if "triplets" not in json_result:
+ is_categorized = any(isinstance(v, list) for v in json_result.values())
+ if is_categorized:
+ flat_triplets = []
+ for label, items in json_result.items():
+ if isinstance(items, list):
+ for item in items:
+ if isinstance(item, dict):
+ flat_triplets.append(item)
+ json_result = {"triplets": flat_triplets}
+
elif isinstance(json_result, list) and hasattr(schema, "relations") and "relations" in schema.model_fields:
json_result = {"relations": json_result}
elif isinstance(json_result, list) and hasattr(schema, "triplets") and "triplets" in schema.model_fields:
@@ -564,11 +633,16 @@ class GroqProvider(BaseProvider):
if not self.client:
raise ProcessingError("Groq client not initialized.")
- json_prompt = f"{prompt}\n\nReturn the response as valid JSON only."
+ # Groq requires 'json' in the prompt for json_object mode
+ json_prompt = prompt
+ if "json" not in prompt.lower():
+ json_prompt = f"{prompt}\n\nReturn the response as valid JSON only."
+
response = self.client.chat.completions.create(
model=kwargs.get("model", self.model),
messages=[{"role": "user", "content": json_prompt}],
temperature=kwargs.get("temperature", 0.3),
+ response_format={"type": "json_object"},
)
try:
return self._parse_json(response.choices[0].message.content)
diff --git a/semantica/semantic_extract/relation_extractor.py b/semantica/semantic_extract/relation_extractor.py
index be3be2d5..aa4752e2 100644
--- a/semantica/semantic_extract/relation_extractor.py
+++ b/semantica/semantic_extract/relation_extractor.py
@@ -20,6 +20,12 @@ Algorithms Used:
- Sequence Classification: Transformer-based relation classification models
- Large Language Models: GPT, Claude, Gemini for relation extraction
- Context Window Analysis: Sliding window and context extraction algorithms
+ - Weighted Confidence Scoring:
+ * Formula: Score = (0.5 * Method_Confidence) + (0.5 * Type_Similarity_Score)
+ * Method_Confidence: Confidence score from the extraction algorithm
+ * Type_Similarity_Score: Semantic match with user-provided relation types (Exact=1.0, Synonym=0.95, Embedding=Cosine_Sim)
+ - Hybrid Similarity Matching: Exact -> Synonym -> Substring -> Semantic Embedding (Batch Optimized)
+ - Last Resort Fallback: Adjacency-based heuristic when all other methods fail
Key Features:
- Multiple extraction methods:
@@ -30,6 +36,7 @@ Key Features:
* HuggingFace: Custom HuggingFace relation models
* LLM-based: LLM-powered relation extraction
- Fallback chain support: Try methods in order until one succeeds
+ - Robust Fallbacks: Prevents empty results via Primary -> Pattern -> Last Resort chain
- Multiple relation types (founded_by, located_in, works_for, born_in, etc.)
- Relation classification and grouping
- Relation validation and consistency checking
@@ -197,6 +204,7 @@ class RelationExtractor:
results = []
# Ensure lists are same length
min_len = min(len(text), len(entities))
+ total_relations_count = 0
# Update more frequently: every 1% or at least every 10 items, but always update for small datasets
if min_len <= 10:
update_interval = 1 # Update every item for small datasets
@@ -228,7 +236,18 @@ class RelationExtractor:
if not isinstance(ent_item, list):
ent_item = [] # Should not happen if entities is List[List[Entity]]
- results.append(self.extract_relations(doc_text, ent_item, **kwargs))
+ current_relations = self.extract_relations(doc_text, ent_item, **kwargs)
+
+ # Add provenance metadata
+ for rel in current_relations:
+ if rel.metadata is None:
+ rel.metadata = {}
+ rel.metadata["batch_index"] = i
+ if isinstance(doc_item, dict) and "id" in doc_item:
+ rel.metadata["document_id"] = doc_item["id"]
+
+ results.append(current_relations)
+ total_relations_count += len(current_relations)
remaining = min_len - (i + 1)
# Update progress: always update for small datasets, or at intervals for large ones
@@ -243,13 +262,13 @@ class RelationExtractor:
tracking_id,
processed=i + 1,
total=min_len,
- message=f"Processing documents... {i + 1}/{min_len} (remaining: {remaining})"
+ message=f"Processing documents... {i + 1}/{min_len} (remaining: {remaining}) - Extracted {total_relations_count} relations so far"
)
self.progress_tracker.stop_tracking(
tracking_id,
status="completed",
- message=f"Extracted relations from {len(results)} documents",
+ message=f"Batch extraction completed. Processed {len(results)} documents, extracted {total_relations_count} relations.",
)
return results
except Exception as e:
@@ -322,6 +341,11 @@ class RelationExtractor:
# Prepare method-specific options
method_options = all_options.copy()
+
+ # Pass relation_types to all methods so they can use them (e.g. for similarity matching)
+ if relation_types:
+ method_options["relation_types"] = relation_types
+
if method_name == "huggingface":
method_options["model"] = all_options.get(
"huggingface_model", all_options.get("model")
@@ -345,9 +369,6 @@ class RelationExtractor:
api_key = os.getenv(env_key)
if api_key:
method_options["api_key"] = api_key
- # Pass relation_types to LLM method so it can use them in the prompt
- if relation_types:
- method_options["relation_types"] = relation_types
elif method_name == "dependency":
method_options["model"] = all_options.get(
"model", "en_core_web_sm"
@@ -366,6 +387,20 @@ class RelationExtractor:
import sys
print(f" [RelationExtractor] Extracted {len(relations)} relations", flush=True, file=sys.stdout)
+ # Apply weighted scoring if relation_types are provided
+ if relation_types:
+ try:
+ from .methods import calculate_weighted_confidence
+ for r in relations:
+ r.confidence = calculate_weighted_confidence(
+ item_type=r.predicate,
+ original_confidence=r.confidence,
+ valid_types=relation_types,
+ item_text=r.predicate # For relations, the predicate IS the text usually
+ )
+ except ImportError:
+ pass
+
# Filter by confidence
filtered = [r for r in relations if r.confidence >= min_confidence]
@@ -392,7 +427,12 @@ class RelationExtractor:
if all_relations:
relations = all_relations[0][1] # Use first successful method
else:
- relations = []
+ # Fallback to pattern-based extraction if all models fail
+ relations = self._extract_with_patterns(text, entities)
+
+ # Last resort: if patterns also fail but we have entities, force some relations
+ if not relations and entities and len(entities) >= 2:
+ relations = self._extract_last_resort_relations(text, entities)
# Validate if enabled
if validate:
@@ -411,6 +451,40 @@ class RelationExtractor:
)
raise
+ def _extract_last_resort_relations(self, text: str, entities: List[Entity]) -> List[Relation]:
+ """Last resort relation extraction based on simple adjacency."""
+ print(f"DEBUG: Last Resort Relations - {len(entities)} entities")
+ relations = []
+ # Connect adjacent entities
+ for i in range(len(entities) - 1):
+ e1 = entities[i]
+ e2 = entities[i+1]
+
+ # Create a weak relation
+ start_idx = min(e1.end_char, e2.start_char)
+ end_idx = max(e1.end_char, e2.start_char)
+ # Ensure context isn't too large or invalid
+ if start_idx < 0: start_idx = 0
+ if end_idx > len(text): end_idx = len(text)
+
+ # Expand context a bit
+ ctx_start = max(0, start_idx - 20)
+ ctx_end = min(len(text), end_idx + 20)
+
+ context = text[ctx_start:ctx_end]
+
+ rel = Relation(
+ subject=e1,
+ predicate="related_to",
+ object=e2,
+ confidence=0.3,
+ context=context,
+ metadata={"extraction_method": "last_resort_adjacency"}
+ )
+ relations.append(rel)
+ print(f"DEBUG: Created relation {rel.subject.text} -> {rel.object.text}")
+ return relations
+
def _extract_with_patterns(
self, text: str, entities: List[Entity]
) -> List[Relation]:
diff --git a/semantica/semantic_extract/schemas.py b/semantica/semantic_extract/schemas.py
index 58d2c69d..be105e23 100644
--- a/semantica/semantic_extract/schemas.py
+++ b/semantica/semantic_extract/schemas.py
@@ -10,6 +10,7 @@ class EntityOut(BaseModel):
start: int = Field(0, description="Start character index", alias="start_char")
end: int = Field(0, description="End character index", alias="end_char")
confidence: float = Field(0.9, description="Confidence score between 0 and 1")
+ metadata: dict = Field(default_factory=dict, description="Additional metadata including provenance")
@field_validator("text", mode="before")
@classmethod
@@ -53,6 +54,7 @@ class RelationOut(BaseModel):
object: str = Field(..., description="Target entity text")
predicate: str = Field(..., description="Relation type or predicate")
confidence: float = Field(0.9, description="Confidence score between 0 and 1")
+ metadata: dict = Field(default_factory=dict, description="Additional metadata including provenance")
@model_validator(mode="before")
@classmethod
@@ -98,6 +100,7 @@ class TripletOut(BaseModel):
predicate: str = Field(..., description="Predicate or relation")
object: str = Field(..., description="Object of the triplet")
confidence: float = Field(0.9, description="Confidence score between 0 and 1")
+ metadata: dict = Field(default_factory=dict, description="Additional metadata including provenance")
@field_validator("confidence", mode="before")
@classmethod
diff --git a/semantica/semantic_extract/semantic_analyzer.py b/semantica/semantic_extract/semantic_analyzer.py
index 1a2b4e28..56ef982c 100644
--- a/semantica/semantic_extract/semantic_analyzer.py
+++ b/semantica/semantic_extract/semantic_analyzer.py
@@ -71,6 +71,7 @@ class SemanticRole:
start_char: int
end_char: int
confidence: float = 1.0
+ metadata: Dict[str, Any] = field(default_factory=dict)
@dataclass
@@ -81,6 +82,7 @@ class SemanticCluster:
cluster_id: int
centroid: Optional[str] = None
similarity_score: float = 0.0
+ metadata: Dict[str, Any] = field(default_factory=dict)
class SemanticAnalyzer:
@@ -118,6 +120,103 @@ class SemanticAnalyzer:
self.role_labeler = RoleLabeler(**self.config.get("role", {}))
self.semantic_clusterer = SemanticClusterer(**self.config.get("clustering", {}))
+ def analyze(
+ self,
+ text: Union[str, List[str], List[Dict[str, Any]]],
+ pipeline_id: Optional[str] = None,
+ **kwargs
+ ) -> Union[Dict[str, Any], List[Dict[str, Any]]]:
+ """
+ Perform semantic analysis on text or list of documents.
+ Handles batch processing with progress tracking.
+
+ Args:
+ text: Input text or list of documents
+ pipeline_id: Optional pipeline ID for progress tracking
+ **kwargs: Analysis options
+
+ Returns:
+ Union[Dict[str, Any], List[Dict[str, Any]]]: Analysis results
+ """
+ if isinstance(text, list):
+ # Handle batch analysis with progress tracking
+ tracking_id = self.progress_tracker.start_tracking(
+ module="semantic_extract",
+ submodule="SemanticAnalyzer",
+ message=f"Batch analyzing {len(text)} documents",
+ pipeline_id=pipeline_id,
+ )
+
+ try:
+ results = []
+ total_items = len(text)
+
+ # Determine update interval
+ if total_items <= 10:
+ update_interval = 1
+ else:
+ update_interval = max(1, min(10, total_items // 100))
+
+ # Initial progress update
+ self.progress_tracker.update_progress(
+ tracking_id,
+ processed=0,
+ total=total_items,
+ message=f"Starting batch analysis... 0/{total_items} (remaining: {total_items})"
+ )
+
+ for idx, item in enumerate(text):
+ # Prepare arguments for single item
+ doc_text = item["content"] if isinstance(item, dict) and "content" in item else str(item)
+
+ # Analyze
+ analysis = self.analyze_semantics(doc_text, **kwargs)
+
+ # Add provenance metadata
+ analysis["batch_index"] = idx
+ if isinstance(item, dict) and "id" in item:
+ analysis["document_id"] = item["id"]
+
+ # Also inject into semantic roles if present
+ if "semantic_roles" in analysis:
+ for role in analysis["semantic_roles"]:
+ # role is a dict here because analyze_semantics converts it
+ if "metadata" not in role:
+ role["metadata"] = {}
+
+ role["metadata"]["batch_index"] = idx
+ if isinstance(item, dict) and "id" in item:
+ role["metadata"]["document_id"] = item["id"]
+
+ results.append(analysis)
+
+ # Update progress
+ if (idx + 1) % update_interval == 0 or (idx + 1) == total_items:
+ remaining = total_items - (idx + 1)
+ self.progress_tracker.update_progress(
+ tracking_id,
+ processed=idx + 1,
+ total=total_items,
+ message=f"Processing... {idx + 1}/{total_items} (remaining: {remaining})"
+ )
+
+ self.progress_tracker.stop_tracking(
+ tracking_id,
+ status="completed",
+ message=f"Batch analysis completed. Processed {len(results)} documents.",
+ )
+ return results
+
+ except Exception as e:
+ self.progress_tracker.stop_tracking(
+ tracking_id, status="failed", message=str(e)
+ )
+ raise
+
+ else:
+ # Single item
+ return self.analyze_semantics(text, **kwargs)
+
def analyze_semantics(self, text: str, **options) -> Dict[str, Any]:
"""
Perform comprehensive semantic analysis.
@@ -200,13 +299,13 @@ class SemanticAnalyzer:
return self.label_semantic_roles(text, **options)
def cluster_semantically(
- self, texts: List[str], **options
+ self, texts: Union[List[str], List[Dict[str, Any]]], **options
) -> List[SemanticCluster]:
"""
Perform semantic clustering of texts.
Args:
- texts: List of texts to cluster
+ texts: List of texts or documents to cluster
**options: Clustering options
Returns:
@@ -372,12 +471,14 @@ class SemanticClusterer:
if not self.progress_tracker.enabled:
self.progress_tracker.enabled = True
- def cluster(self, texts: List[str], **options) -> List[SemanticCluster]:
+ def cluster(
+ self, texts: Union[List[str], List[Dict[str, Any]]], **options
+ ) -> List[SemanticCluster]:
"""
Perform semantic clustering of texts.
Args:
- texts: List of texts to cluster
+ texts: List of texts or documents (dict with 'content' and 'id') to cluster
**options: Clustering options:
- num_clusters: Number of clusters (default: auto)
- similarity_threshold: Minimum similarity for clustering
@@ -388,11 +489,27 @@ class SemanticClusterer:
if not texts:
return []
+ # Extract content and IDs if input is list of dicts
+ processed_texts = []
+ doc_ids = []
+
+ for item in texts:
+ if isinstance(item, dict):
+ content = item.get("content", str(item))
+ processed_texts.append(content)
+ if "id" in item:
+ doc_ids.append(item["id"])
+ else:
+ doc_ids.append(None)
+ else:
+ processed_texts.append(str(item))
+ doc_ids.append(None)
+
# Track clustering
tracking_id = self.progress_tracker.start_tracking(
module="semantic_extract",
submodule="SemanticClusterer",
- message=f"Clustering {len(texts)} texts",
+ message=f"Clustering {len(processed_texts)} texts",
)
try:
@@ -402,7 +519,7 @@ class SemanticClusterer:
clusters = []
assigned = set()
- total_texts = len(texts)
+ total_texts = len(processed_texts)
if total_texts <= 10:
update_interval = 1 # Update every item for small datasets
else:
@@ -418,22 +535,28 @@ class SemanticClusterer:
)
cluster_id = 0
- for i, text1 in enumerate(texts):
+ for i, text1 in enumerate(processed_texts):
if i in assigned:
continue
cluster_texts = [text1]
+ cluster_doc_ids = []
+ if doc_ids[i] is not None:
+ cluster_doc_ids.append(doc_ids[i])
+
assigned.add(i)
# Find similar texts
- remaining_texts = len(texts) - (i + 1)
- for j, text2 in enumerate(texts[i + 1 :], start=i + 1):
+ remaining_texts = len(processed_texts) - (i + 1)
+ for j, text2 in enumerate(processed_texts[i + 1 :], start=i + 1):
if j in assigned:
continue
similarity = similarity_analyzer.calculate_similarity(text1, text2)
if similarity >= similarity_threshold:
cluster_texts.append(text2)
+ if doc_ids[j] is not None:
+ cluster_doc_ids.append(doc_ids[j])
assigned.add(j)
# Create cluster
@@ -443,6 +566,11 @@ class SemanticClusterer:
centroid=cluster_texts[0], # Use first as centroid
similarity_score=similarity_threshold,
)
+
+ # Add provenance metadata
+ if cluster_doc_ids:
+ cluster.metadata["document_ids"] = cluster_doc_ids
+
clusters.append(cluster)
cluster_id += 1
diff --git a/semantica/semantic_extract/semantic_extract_usage.md b/semantica/semantic_extract/semantic_extract_usage.md
index a2b5fb05..6df1b465 100644
--- a/semantica/semantic_extract/semantic_extract_usage.md
+++ b/semantica/semantic_extract/semantic_extract_usage.md
@@ -36,6 +36,41 @@ print(f"Relations: {relations}")
print(f"Extracted {len(entities)} entities and {len(relations)} relations")
```
+## Batch Processing & Provenance
+
+All extractors support batch processing for high-throughput extraction. You can pass a list of strings or a list of dictionaries (with `content` and `id` keys).
+
+**Features:**
+- **Progress Tracking**: Automatically shows a progress bar for large batches.
+- **Provenance Metadata**: Each extracted item includes `batch_index` and `document_id` in its `metadata`.
+
+```python
+from semantica.semantic_extract import NERExtractor
+
+documents = [
+ {"id": "doc_1", "content": "Apple Inc. was founded by Steve Jobs."},
+ {"id": "doc_2", "content": "Microsoft Corporation was founded by Bill Gates."}
+]
+
+extractor = NERExtractor()
+batch_results = extractor.extract(documents)
+
+for i, doc_entities in enumerate(batch_results):
+ print(f"Document {i} entities:")
+ for entity in doc_entities:
+ print(f" - {entity.text} ({entity.label})")
+ print(f" Provenance: Batch Index {entity.metadata['batch_index']}, Doc ID {entity.metadata.get('document_id')}")
+```
+
+## Robust Extraction Fallbacks
+
+The framework implements robust fallback chains to prevent empty results when primary methods fail (e.g., due to model unavailability or obscure text).
+
+- **NER**: `ML/LLM` -> `Pattern` -> `Last Resort` (Capitalized Words)
+- **Relation**: `Primary` -> `Pattern` -> `Last Resort` (Adjacency)
+- **Triplet**: `Primary` -> `Relation-to-Triplet` -> `Pattern`
+
+This ensures that you almost always get *some* structured data, even if it requires falling back to simpler heuristics.
## Entity Extraction
diff --git a/semantica/semantic_extract/semantic_network_extractor.py b/semantica/semantic_extract/semantic_network_extractor.py
index 335157da..f1c78cf8 100644
--- a/semantica/semantic_extract/semantic_network_extractor.py
+++ b/semantica/semantic_extract/semantic_network_extractor.py
@@ -149,6 +149,120 @@ class SemanticNetworkExtractor:
self.config["ner_method"] = method
self.config["relation_method"] = method
+ def extract(
+ self,
+ text: Union[str, List[str], List[Dict[str, Any]]],
+ entities: Optional[Union[List[Entity], List[List[Entity]]]] = None,
+ relations: Optional[Union[List[Relation], List[List[Relation]]]] = None,
+ pipeline_id: Optional[str] = None,
+ **kwargs
+ ) -> Union[SemanticNetwork, List[SemanticNetwork]]:
+ """
+ Extract semantic network from text or list of documents.
+ Handles batch processing with progress tracking.
+
+ Args:
+ text: Input text or list of documents
+ entities: Optional pre-extracted entities (single list or list of lists)
+ relations: Optional pre-extracted relations (single list or list of lists)
+ pipeline_id: Optional pipeline ID for progress tracking
+ **kwargs: Extraction options
+
+ Returns:
+ Union[SemanticNetwork, List[SemanticNetwork]]: Extracted semantic network(s)
+ """
+ if isinstance(text, list):
+ # Handle batch extraction with progress tracking
+ tracking_id = self.progress_tracker.start_tracking(
+ module="semantic_extract",
+ submodule="SemanticNetworkExtractor",
+ message=f"Batch extracting semantic networks from {len(text)} documents",
+ pipeline_id=pipeline_id,
+ )
+
+ try:
+ results = []
+ total_items = len(text)
+
+ # Determine update interval
+ if total_items <= 10:
+ update_interval = 1
+ else:
+ update_interval = max(1, min(10, total_items // 100))
+
+ # Initial progress update
+ self.progress_tracker.update_progress(
+ tracking_id,
+ processed=0,
+ total=total_items,
+ message=f"Starting batch extraction... 0/{total_items} (remaining: {total_items})"
+ )
+
+ for idx, item in enumerate(text):
+ # Prepare arguments for single item
+ doc_text = item["content"] if isinstance(item, dict) and "content" in item else str(item)
+
+ doc_entities = None
+ if entities and isinstance(entities, list) and idx < len(entities):
+ doc_entities = entities[idx]
+
+ doc_relations = None
+ if relations and isinstance(relations, list) and idx < len(relations):
+ doc_relations = relations[idx]
+
+ # Extract
+ network = self.extract_network(
+ doc_text,
+ entities=doc_entities,
+ relations=doc_relations,
+ **kwargs
+ )
+
+ # Add provenance metadata to nodes and edges
+ batch_meta = {"batch_index": idx}
+ if isinstance(item, dict) and "id" in item:
+ batch_meta["document_id"] = item["id"]
+
+ # Update network metadata
+ network.metadata.update(batch_meta)
+
+ # Update nodes metadata
+ for node in network.nodes:
+ node.metadata.update(batch_meta)
+
+ # Update edges metadata
+ for edge in network.edges:
+ edge.metadata.update(batch_meta)
+
+ results.append(network)
+
+ # Update progress
+ if (idx + 1) % update_interval == 0 or (idx + 1) == total_items:
+ remaining = total_items - (idx + 1)
+ self.progress_tracker.update_progress(
+ tracking_id,
+ processed=idx + 1,
+ total=total_items,
+ message=f"Processing... {idx + 1}/{total_items} (remaining: {remaining})"
+ )
+
+ self.progress_tracker.stop_tracking(
+ tracking_id,
+ status="completed",
+ message=f"Batch extraction completed. Processed {len(results)} documents.",
+ )
+ return results
+
+ except Exception as e:
+ self.progress_tracker.stop_tracking(
+ tracking_id, status="failed", message=str(e)
+ )
+ raise
+
+ else:
+ # Single item
+ return self.extract_network(text, entities=entities, relations=relations, **kwargs)
+
def extract_network(
self,
text: str,
diff --git a/semantica/semantic_extract/triplet_extractor.py b/semantica/semantic_extract/triplet_extractor.py
index a7667f04..d57e73d5 100644
--- a/semantica/semantic_extract/triplet_extractor.py
+++ b/semantica/semantic_extract/triplet_extractor.py
@@ -18,6 +18,12 @@ Algorithms Used:
- Large Language Models: GPT, Claude, Gemini for structured triplet extraction
- RDF Serialization: Graph serialization algorithms (Turtle, N-Triples, JSON-LD)
- URI Normalization: String normalization and URI formatting algorithms
+ - Weighted Confidence Scoring:
+ * Formula: Score = (0.5 * Method_Confidence) + (0.5 * Type_Similarity_Score)
+ * Method_Confidence: Confidence score from the extraction algorithm
+ * Type_Similarity_Score: Semantic match with user-provided triplet types (Exact=1.0, Synonym=0.95, Embedding=Cosine_Sim)
+ - Hybrid Similarity Matching: Exact -> Synonym -> Substring -> Semantic Embedding (Batch Optimized)
+ - Last Resort Fallback: Relation-to-Triplet conversion when all other methods fail
Key Features:
- Multiple extraction methods:
@@ -26,6 +32,7 @@ Key Features:
* HuggingFace: Custom HuggingFace triplet models
* LLM-based: LLM-powered triplet extraction
- Fallback chain support: Try methods in order until one succeeds
+ - Robust Fallbacks: Prevents empty results via Primary -> Relation-to-Triplet -> Pattern chain
- RDF triplet generation from entities and relations
- Subject-predicate-object extraction
- Triplet validation and quality checking
@@ -99,6 +106,7 @@ class TripletExtractor:
def __init__(
self,
method: Union[str, List[str]] = "pattern",
+ triplet_types: Optional[List[str]] = None,
include_temporal: bool = False,
include_provenance: bool = False,
config=None,
@@ -114,6 +122,7 @@ class TripletExtractor:
- "huggingface": HuggingFace model
- "llm": LLM-based extraction
- List of methods for fallback chain
+ triplet_types: Specific triplet types/predicates to extract (e.g., ["foundedBy", "locatedIn"])
include_temporal: Whether to include temporal information in triplets
include_provenance: Whether to track source sentences for provenance
config: Legacy config dict (deprecated, use kwargs)
@@ -135,6 +144,7 @@ class TripletExtractor:
self.progress_tracker.enabled = True
# Store parameters
+ self.triplet_types = triplet_types
self.include_temporal = include_temporal
self.include_provenance = include_provenance
@@ -149,6 +159,114 @@ class TripletExtractor:
self.supported_formats = ["turtle", "ntriples", "jsonld", "xml"]
+ def extract(
+ self,
+ text: Union[str, List[str], List[Dict[str, Any]]],
+ entities: Optional[Union[List[Entity], List[List[Entity]]]] = None,
+ relations: Optional[Union[List[Relation], List[List[Relation]]]] = None,
+ pipeline_id: Optional[str] = None,
+ **kwargs
+ ) -> Union[List[Triplet], List[List[Triplet]]]:
+ """
+ Extract triplets from text or list of documents.
+ Handles batch processing with progress tracking.
+
+ Args:
+ text: Input text or list of documents
+ entities: Optional pre-extracted entities (single list or list of lists)
+ relations: Optional pre-extracted relations (single list or list of lists)
+ pipeline_id: Optional pipeline ID for progress tracking
+ **kwargs: Extraction options
+
+ Returns:
+ Union[List[Triplet], List[List[Triplet]]]: Extracted triplets
+ """
+ if isinstance(text, list):
+ # Handle batch extraction with progress tracking
+ tracking_id = self.progress_tracker.start_tracking(
+ module="semantic_extract",
+ submodule="TripletExtractor",
+ message=f"Batch extracting triplets from {len(text)} documents",
+ pipeline_id=pipeline_id,
+ )
+
+ try:
+ results = []
+ total_items = len(text)
+ total_triplets_count = 0
+
+ # Determine update interval
+ if total_items <= 10:
+ update_interval = 1
+ else:
+ update_interval = max(1, min(10, total_items // 100))
+
+ # Initial progress update
+ self.progress_tracker.update_progress(
+ tracking_id,
+ processed=0,
+ total=total_items,
+ message=f"Starting batch extraction... 0/{total_items} (remaining: {total_items})"
+ )
+
+ for idx, item in enumerate(text):
+ # Prepare arguments for single item
+ doc_text = item["content"] if isinstance(item, dict) and "content" in item else str(item)
+
+ doc_entities = None
+ if entities and isinstance(entities, list) and idx < len(entities):
+ doc_entities = entities[idx]
+
+ doc_relations = None
+ if relations and isinstance(relations, list) and idx < len(relations):
+ doc_relations = relations[idx]
+
+ # Extract
+ current_triplets = self.extract_triplets(
+ doc_text,
+ entities=doc_entities,
+ relations=doc_relations,
+ **kwargs
+ )
+
+ # Add provenance metadata
+ for triplet in current_triplets:
+ if triplet.metadata is None:
+ triplet.metadata = {}
+ triplet.metadata["batch_index"] = idx
+ if isinstance(item, dict) and "id" in item:
+ triplet.metadata["document_id"] = item["id"]
+
+ results.append(current_triplets)
+ total_triplets_count += len(current_triplets)
+
+ # Update progress
+ if (idx + 1) % update_interval == 0 or (idx + 1) == total_items:
+ remaining = total_items - (idx + 1)
+ self.progress_tracker.update_progress(
+ tracking_id,
+ processed=idx + 1,
+ total=total_items,
+ message=f"Processing... {idx + 1}/{total_items} (remaining: {remaining}) - Extracted {total_triplets_count} triplets"
+ )
+
+ self.progress_tracker.stop_tracking(
+ tracking_id,
+ status="completed",
+ message=f"Batch extraction completed. Processed {len(results)} documents, extracted {total_triplets_count} triplets.",
+ )
+ return results
+
+ except Exception as e:
+ self.progress_tracker.stop_tracking(
+ tracking_id, status="failed", message=str(e)
+ )
+ raise
+
+ else:
+ # Single item
+ return self.extract_triplets(text, entities=entities, relations=relations, **kwargs)
+
def extract_triplets(
self,
text: str,
@@ -201,6 +319,8 @@ class TripletExtractor:
if isinstance(methods, str):
methods = [methods]
+ triplet_types = options.get("triplet_types", self.triplet_types)
+
# Merge config with options
all_options = {**self.config, **options}
@@ -234,6 +354,11 @@ class TripletExtractor:
# Prepare method-specific options
method_options = all_options.copy()
+
+ # Pass triplet_types to all methods
+ if triplet_types:
+ method_options["triplet_types"] = triplet_types
+
if method_name == "huggingface":
method_options["model"] = all_options.get(
"huggingface_model", all_options.get("model")
@@ -265,6 +390,20 @@ class TripletExtractor:
**method_options,
)
+ # Apply weighted scoring if triplet_types are provided
+ if triplet_types:
+ try:
+ from .methods import calculate_weighted_confidence
+ for t in triplets:
+ t.confidence = calculate_weighted_confidence(
+ item_type=t.predicate,
+ original_confidence=t.confidence,
+ valid_types=triplet_types,
+ item_text=t.predicate # For triplets, predicate is the key text
+ )
+ except ImportError:
+ pass
+
# Filter by confidence
min_conf = options.get("min_confidence", self.min_confidence)
filtered = [t for t in triplets if t.confidence >= min_conf]
@@ -293,20 +432,29 @@ class TripletExtractor:
triplets = all_triplets[0][1]
else:
# Fallback: Convert relations to triplets
- self.progress_tracker.update_tracking(
- tracking_id,
- message=f"Converting {len(relations)} relations to triplets...",
- )
- triplets = []
- for relation in relations:
- triplet = Triplet(
- subject=self._format_uri(relation.subject.text),
- predicate=self._format_uri(relation.predicate),
- object=self._format_uri(relation.object.text),
- confidence=relation.confidence,
- metadata={"context": relation.context, **relation.metadata},
+ if relations:
+ self.progress_tracker.update_tracking(
+ tracking_id,
+ message=f"Converting {len(relations)} relations to triplets...",
+ )
+ triplets = []
+ for relation in relations:
+ triplet = Triplet(
+ subject=self._format_uri(relation.subject.text),
+ predicate=self._format_uri(relation.predicate),
+ object=self._format_uri(relation.object.text),
+ confidence=relation.confidence,
+ metadata={"context": relation.context, **relation.metadata},
+ )
+ triplets.append(triplet)
+ else:
+ # Last resort: Try rule-based extraction if no relations exist
+ self.progress_tracker.update_tracking(
+ tracking_id,
+ message="No relations found. Trying rule-based triplet extraction...",
)
- triplets.append(triplet)
+ method_func = get_triplet_method("rules")
+ triplets = method_func(text, entities=entities, relations=[], **all_options)
# Validate triplets
if options.get("validate", self._should_validate):
@@ -382,7 +530,65 @@ class TripletExtractor:
Returns:
list: List of triplet lists for each text
"""
- return [self.extract_triplets(text, **options) for text in texts]
+ tracking_id = self.progress_tracker.start_tracking(
+ module="semantic_extract",
+ submodule="TripletExtractor",
+ message=f"Batch extracting triplets from {len(texts)} documents",
+ )
+
+ results = []
+ total_triplets_count = 0
+ total_items = len(texts)
+
+ try:
+ # Determine update interval
+ if total_items <= 10:
+ update_interval = 1
+ else:
+ update_interval = max(1, min(10, total_items // 100))
+
+ for idx, text in enumerate(texts, 1):
+ # Extract triplets
+ triplets = self.extract_triplets(text, **options)
+
+ # Add provenance metadata
+ for triplet in triplets:
+ if triplet.metadata is None:
+ triplet.metadata = {}
+ triplet.metadata["batch_index"] = idx - 1
+
+ results.append(triplets)
+ total_triplets_count += len(triplets)
+
+ # Update progress
+ should_update = (
+ idx % update_interval == 0 or
+ idx == total_items or
+ idx == 1 or
+ total_items <= 10
+ )
+
+ if should_update:
+ remaining = total_items - idx
+ self.progress_tracker.update_progress(
+ tracking_id,
+ processed=idx,
+ total=total_items,
+ message=f"Processing documents... {idx}/{total_items} (remaining: {remaining}) - Extracted {total_triplets_count} triplets so far"
+ )
+
+ self.progress_tracker.stop_tracking(
+ tracking_id,
+ status="completed",
+ message=f"Batch extraction completed. Processed {len(results)} documents, extracted {total_triplets_count} triplets.",
+ )
+ return results
+
+ except Exception as e:
+ self.progress_tracker.stop_tracking(
+ tracking_id, status="failed", message=str(e)
+ )
+ raise
class TripletValidator:
@@ -428,27 +634,6 @@ class TripletValidator:
"""
return [t for t in triplets if self.validate_triplet(t, **criteria)]
- def check_triplet_consistency(self, triplets: List[Triplet]) -> Dict[str, Any]:
- """
- Check consistency among triplets.
-
- Args:
- triplets: List of triplets
-
- Returns:
- dict: Consistency report
- """
- issues = []
-
- # Check for contradictory triplets
- # (simplified - would need domain knowledge for full implementation)
-
- return {
- "total_triplets": len(triplets),
- "issues": issues,
- "consistent": len(issues) == 0,
- }
-
class RDFSerializer:
"""RDF serialization handler."""
diff --git a/tests/semantic_extract/test_robustness_fallback.py b/tests/semantic_extract/test_robustness_fallback.py
new file mode 100644
index 00000000..07679e68
--- /dev/null
+++ b/tests/semantic_extract/test_robustness_fallback.py
@@ -0,0 +1,151 @@
+
+import pytest
+import sys
+
+from semantica.semantic_extract.ner_extractor import NERExtractor, Entity
+from semantica.semantic_extract.relation_extractor import RelationExtractor, Relation
+from semantica.semantic_extract.triplet_extractor import TripletExtractor
+
+class TestRobustnessFallback:
+
+ def test_ner_last_resort_fallback(self):
+ """Test that NER extractor finds entities even in obscure text via last resort."""
+ extractor = NERExtractor()
+
+ # Text with single capitalized word that shouldn't match PERSON pattern (requires 2+ words)
+ text = "Zylophone"
+
+ entities = extractor.extract_entities(text)
+
+ assert len(entities) > 0, "Should have extracted at least one entity via last resort"
+ # Check if they are the capitalized words
+ texts = [e.text for e in entities]
+ assert "Zylophone" in texts
+
+ # Verify metadata
+ for e in entities:
+ assert e.metadata is not None
+ assert "extraction_method" in e.metadata
+ # Should be last_resort_pattern
+ assert e.metadata["extraction_method"] == "last_resort_pattern"
+
+ def test_relation_last_resort_fallback(self):
+ """Test that Relation extractor creates adjacency relations when no patterns match."""
+ extractor = RelationExtractor()
+
+ # Create entities far apart to avoid "co_occurrence" fallback which triggers < 100 chars
+ padding = " " * 105
+ text = f"Alpha{padding}Beta{padding}Gamma"
+
+ # Alpha at start
+ e1_start = 0
+ e1_end = 5
+
+ # Beta after padding
+ e2_start = e1_end + 105
+ e2_end = e2_start + 4
+
+ # Gamma after padding
+ e3_start = e2_end + 105
+ e3_end = e3_start + 5
+
+ e1 = Entity(text="Alpha", label="UNKNOWN", start_char=e1_start, end_char=e1_end)
+ e2 = Entity(text="Beta", label="UNKNOWN", start_char=e2_start, end_char=e2_end)
+ e3 = Entity(text="Gamma", label="UNKNOWN", start_char=e3_start, end_char=e3_end)
+
+ entities = [e1, e2, e3]
+
+ # This text has no "is a", "works for", etc. patterns.
+ # And entities are too far for co-occurrence (< 100).
+ # It should trigger the last resort adjacency fallback.
+ relations = extractor.extract_relations(text, entities)
+
+ assert len(relations) > 0, "Should have extracted relations via last resort"
+
+ # Expect relations between adjacent entities: Alpha->Beta, Beta->Gamma
+ pairs = [(r.subject.text, r.object.text) for r in relations]
+ assert ("Alpha", "Beta") in pairs
+ assert ("Beta", "Gamma") in pairs
+
+ # Verify metadata
+ for r in relations:
+ assert r.metadata is not None
+ assert "extraction_method" in r.metadata
+ assert r.metadata.get("extraction_method") == "last_resort_adjacency"
+
+ def test_triplet_fallback_conversion(self):
+ """Test that Triplet extractor falls back to converting relations if extraction fails."""
+ # Setup mocks or use real classes
+ ner = NERExtractor() # We'll just pass entities directly
+ rel_extractor = RelationExtractor()
+ triplet_extractor = TripletExtractor()
+
+ text = "Alpha is connected to Beta."
+ e1 = Entity(text="Alpha", label="Thing", start_char=0, end_char=5)
+ e2 = Entity(text="Beta", label="Thing", start_char=22, end_char=26)
+ entities = [e1, e2]
+
+ # Create a relation manually to ensure we have one to convert
+ relation = Relation(
+ subject=e1,
+ predicate="connected_to",
+ object=e2,
+ confidence=0.9,
+ context=text
+ )
+
+ # We want to test the fallback in extract_triplets.
+ # Since we can't easily force the primary triplet method to return empty without mocking,
+ # we can pass the relations explicitly and rely on the fact that standard triplet extraction
+ # might not support "connected_to" if it relies on strict patterns, or we can use a method that fails.
+
+ # However, the triplet extractor calls relation extractor internally if not provided.
+ # Let's test the flow where we provide relations.
+
+ triplets = triplet_extractor.extract_triplets(text, entities=entities, relations=[relation])
+
+ assert len(triplets) > 0
+ assert triplets[0].subject == "Alpha"
+ assert triplets[0].object == "Beta"
+ assert triplets[0].predicate == "connected_to"
+
+ def test_batch_metadata_propagation(self):
+ """Verify batch_index and document_id are propagated in batch mode with fallbacks."""
+ ner = NERExtractor()
+
+ docs = [
+ {"content": "First doc", "id": "doc_1"},
+ {"content": "Second doc", "id": "doc_2"}
+ ]
+
+ # These docs are simple, might trigger fallback or simple patterns
+ results = ner.extract(docs)
+
+ assert len(results) == 2
+
+ # Check first doc results
+ for e in results[0]:
+ assert e.metadata["batch_index"] == 0
+ assert e.metadata["document_id"] == "doc_1"
+
+ # Check second doc results
+ for e in results[1]:
+ assert e.metadata["batch_index"] == 1
+ assert e.metadata["document_id"] == "doc_2"
+
+if __name__ == "__main__":
+ # Manually run if executed as script
+ t = TestRobustnessFallback()
+ try:
+ t.test_ner_last_resort_fallback()
+ print("NER Fallback Test Passed")
+ t.test_relation_last_resort_fallback()
+ print("Relation Fallback Test Passed")
+ t.test_triplet_fallback_conversion()
+ print("Triplet Fallback Test Passed")
+ t.test_batch_metadata_propagation()
+ print("Batch Metadata Test Passed")
+ except Exception as e:
+ print(f"Test Failed: {e}")
+ import traceback
+ traceback.print_exc()
diff --git a/tests/test_semantic_extract_batch_provenance.py b/tests/test_semantic_extract_batch_provenance.py
new file mode 100644
index 00000000..44518939
--- /dev/null
+++ b/tests/test_semantic_extract_batch_provenance.py
@@ -0,0 +1,122 @@
+
+print("Starting tests module...")
+import unittest
+from unittest.mock import MagicMock, patch
+try:
+ from semantica.semantic_extract.semantic_network_extractor import SemanticNetworkExtractor, SemanticNetwork, SemanticNode, SemanticEdge
+ from semantica.semantic_extract.event_detector import EventDetector, Event
+ from semantica.semantic_extract.semantic_analyzer import SemanticAnalyzer
+ from semantica.semantic_extract.coreference_resolver import CoreferenceResolver, CoreferenceChain, Mention
+ from semantica.semantic_extract.ner_extractor import Entity
+ print("Imports successful")
+except Exception as e:
+ print(f"Import failed: {e}")
+
+class TestSemanticExtractBatch(unittest.TestCase):
+
+ def setUp(self):
+ # Mock progress tracker to avoid console spam
+ self.tracker_patcher = patch('semantica.utils.progress_tracker.get_progress_tracker')
+ self.mock_tracker_cls = self.tracker_patcher.start()
+ self.mock_tracker = self.mock_tracker_cls.return_value
+ self.mock_tracker.enabled = True
+ self.mock_tracker.start_tracking.return_value = "tracking_id"
+
+ def tearDown(self):
+ self.tracker_patcher.stop()
+
+ def test_semantic_network_batch(self):
+ print("Running test_semantic_network_batch")
+ from copy import deepcopy
+ extractor = SemanticNetworkExtractor()
+
+ # Mock extract_network
+ mock_network = SemanticNetwork(
+ nodes=[SemanticNode(id="1", label="test", type="test", metadata={})],
+ edges=[SemanticEdge(source="1", target="1", label="self", metadata={})],
+ metadata={}
+ )
+ # Use side_effect to return a fresh copy each time
+ extractor.extract_network = MagicMock(side_effect=lambda *args, **kwargs: deepcopy(mock_network))
+
+ # Test input
+ docs = [{"content": "doc1", "id": "doc_1"}, {"content": "doc2", "id": "doc_2"}]
+
+ # Run batch
+ results = extractor.extract(docs)
+
+ self.assertEqual(len(results), 2)
+ # Check provenance
+ self.assertEqual(results[0].metadata["batch_index"], 0)
+ self.assertEqual(results[0].metadata["document_id"], "doc_1")
+ self.assertEqual(results[0].nodes[0].metadata["batch_index"], 0)
+ self.assertEqual(results[0].nodes[0].metadata["document_id"], "doc_1")
+
+ self.assertEqual(results[1].metadata["batch_index"], 1)
+ self.assertEqual(results[1].metadata["document_id"], "doc_2")
+
+ def test_event_detector_batch(self):
+ print("Running test_event_detector_batch")
+ detector = EventDetector()
+
+ # Mock detect_events
+ mock_event = Event(
+ text="event", event_type="test", start_char=0, end_char=5
+ )
+ detector.detect_events = MagicMock(return_value=[mock_event])
+
+ docs = [{"content": "doc1", "id": "doc_1"}]
+
+ results = detector.extract(docs)
+
+ self.assertEqual(len(results), 1)
+ self.assertEqual(len(results[0]), 1)
+ self.assertEqual(results[0][0].metadata["batch_index"], 0)
+ self.assertEqual(results[0][0].metadata["document_id"], "doc_1")
+
+ def test_semantic_analyzer_batch(self):
+ print("Running test_semantic_analyzer_batch")
+ analyzer = SemanticAnalyzer()
+
+ # Mock analyze_semantics
+ mock_result = {
+ "text": "test",
+ "semantic_roles": [{"word": "test", "role": "agent"}]
+ }
+ analyzer.analyze_semantics = MagicMock(return_value=mock_result)
+
+ docs = [{"content": "doc1", "id": "doc_1"}]
+
+ results = analyzer.analyze(docs)
+
+ self.assertEqual(len(results), 1)
+ self.assertEqual(results[0]["batch_index"], 0)
+ self.assertEqual(results[0]["document_id"], "doc_1")
+ self.assertEqual(results[0]["semantic_roles"][0]["batch_index"], 0)
+ self.assertEqual(results[0]["semantic_roles"][0]["document_id"], "doc_1")
+
+ def test_coreference_resolver_batch(self):
+ print("Running test_coreference_resolver_batch")
+ resolver = CoreferenceResolver()
+
+ # Mock resolve_coreferences
+ mock_mention = Mention(text="he", start_char=0, end_char=2, mention_type="pronoun")
+ mock_chain = CoreferenceChain(
+ mentions=[mock_mention],
+ representative=mock_mention
+ )
+ resolver.resolve_coreferences = MagicMock(return_value=[mock_chain])
+
+ docs = [{"content": "doc1", "id": "doc_1"}]
+
+ results = resolver.resolve(docs)
+
+ self.assertEqual(len(results), 1)
+ self.assertEqual(results[0][0].mentions[0].metadata["batch_index"], 0)
+ self.assertEqual(results[0][0].mentions[0].metadata["document_id"], "doc_1")
+ self.assertEqual(results[0][0].representative.metadata["batch_index"], 0)
+ self.assertEqual(results[0][0].representative.metadata["document_id"], "doc_1")
+
+if __name__ == '__main__':
+ print("Running main...")
+ unittest.main()