Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

refactor: standardize semantic_extract module with comprehensive documentation

KaifAhmad1bedacf45733e
diff --git a/semantica/semantic_extract/__init__.py b/semantica/semantic_extract/__init__.py
index f63a2775..7e3dda3a 100644
--- a/semantica/semantic_extract/__init__.py
+++ b/semantica/semantic_extract/__init__.py
@@ -1,21 +1,47 @@
"""
Semantic Extraction Module
-This module provides comprehensive semantic extraction capabilities for knowledge engineering.
+This module provides comprehensive semantic extraction capabilities for knowledge
+engineering, enabling extraction of entities, relations, events, triples, and
+semantic networks from text.
-Exports:
- - NamedEntityRecognizer: Named entity recognition
+Key Features:
+ - Named entity recognition (NER) with multiple implementations
+ - Relationship extraction between entities
+ - Event detection and temporal processing
+ - Coreference resolution for pronouns and entity references
+ - RDF triple extraction and serialization
+ - Semantic analysis and role labeling
+ - Semantic network construction
+ - LLM-based extraction enhancement
+ - Extraction validation and quality assessment
+
+Main Classes:
+ - NamedEntityRecognizer: Main NER coordinator
+ - NERExtractor: Core NER implementation
- RelationExtractor: Relationship extraction
- - EventDetector: Event detection and extraction
+ - EventDetector: Event detection and classification
- CoreferenceResolver: Coreference resolution
- TripleExtractor: RDF triple extraction
- SemanticAnalyzer: Semantic analysis engine
- - NERExtractor: Alternative NER implementation
- - LLMEnhancer: LLM-based extraction enhancement
- - ExtractionValidator: Extraction validation
- - SemanticNetworkExtractor: Semantic network extraction
+ - SemanticNetworkExtractor: Semantic network construction
+ - LLMEnhancer: LLM-based enhancement
+ - ExtractionValidator: Quality validation
+
+Example Usage:
+ >>> from semantica.semantic_extract import build
+ >>> result = build("Apple Inc. was founded by Steve Jobs in 1976.")
+ >>> print(f"Extracted {len(result['entities'])} entities")
+ >>> from semantica.semantic_extract import NamedEntityRecognizer
+ >>> ner = NamedEntityRecognizer()
+ >>> entities = ner.extract_entities("Steve Jobs founded Apple.")
+
+Author: Semantica Contributors
+License: MIT
"""
+from typing import Any, Dict, List, Optional, Union
+
from .named_entity_recognizer import (
NamedEntityRecognizer,
EntityClassifier,
@@ -131,4 +157,139 @@ __all__ = [
# Validation
"ExtractionValidator",
"ValidationResult",
+ "build",
]
+
+
+def build(
+ text: Union[str, List[str]],
+ extract_entities: bool = True,
+ extract_relations: bool = True,
+ extract_events: bool = False,
+ extract_triples: bool = False,
+ resolve_coreferences: bool = False,
+ **options
+) -> Dict[str, Any]:
+ """
+ Extract semantic information from text (module-level convenience function).
+
+ This is a user-friendly wrapper that performs comprehensive semantic extraction
+ including entities, relations, events, and triples.
+
+ Args:
+ text: Input text or list of texts to process
+ extract_entities: Whether to extract named entities (default: True)
+ extract_relations: Whether to extract relationships (default: True)
+ extract_events: Whether to extract events (default: False)
+ extract_triples: Whether to extract RDF triples (default: False)
+ resolve_coreferences: Whether to resolve coreferences (default: False)
+ **options: Additional extraction options
+
+ Returns:
+ Dictionary containing:
+ - entities: List of extracted entities
+ - relations: List of extracted relationships
+ - events: List of extracted events (if enabled)
+ - triples: List of extracted triples (if enabled)
+ - coreferences: Coreference resolution results (if enabled)
+ - metadata: Extraction metadata
+ - statistics: Extraction statistics
+
+ Examples:
+ >>> import semantica
+ >>> result = semantica.semantic_extract.build(
+ ... text="Apple Inc. was founded by Steve Jobs in 1976.",
+ ... extract_entities=True,
+ ... extract_relations=True
+ ... )
+ >>> print(f"Extracted {len(result['entities'])} entities")
+ """
+ # Normalize text to list
+ is_single = isinstance(text, str)
+ if is_single:
+ texts = [text]
+ else:
+ texts = text
+
+ results = {
+ "entities": [],
+ "relations": [],
+ "events": [],
+ "triples": [],
+ "coreferences": [],
+ "metadata": {},
+ "statistics": {}
+ }
+
+ # Initialize extractors
+ if extract_entities:
+ ner = NamedEntityRecognizer(config=options.get("ner_config", {}), **options)
+
+ if extract_relations:
+ from .relation_extractor import RelationExtractor
+ rel_extractor = RelationExtractor(**options.get("relation_config", {}), **options)
+
+ if extract_events:
+ from .event_detector import EventDetector
+ event_detector = EventDetector(**options.get("event_config", {}), **options)
+
+ if extract_triples:
+ from .triple_extractor import TripleExtractor
+ triple_extractor = TripleExtractor(**options.get("triple_config", {}), **options)
+
+ if resolve_coreferences:
+ from .coreference_resolver import CoreferenceResolver
+ coref_resolver = CoreferenceResolver(**options.get("coref_config", {}), **options)
+
+ # Process texts
+ all_entities = []
+ all_relations = []
+ all_events = []
+ all_triples = []
+
+ for txt in texts:
+ if extract_entities:
+ entities = ner.extract_entities(txt, **options)
+ all_entities.extend(entities)
+
+ if extract_relations:
+ # Relations typically need entities, so extract if not already done
+ if not extract_entities:
+ entities = ner.extract_entities(txt, **options) if 'ner' in locals() else []
+ relations = rel_extractor.extract_relations(txt, entities=entities if extract_entities else [], **options)
+ all_relations.extend(relations)
+
+ if extract_events:
+ events = event_detector.detect_events(txt, **options)
+ all_events.extend(events)
+
+ if extract_triples:
+ triples = triple_extractor.extract_triples(txt, **options)
+ all_triples.extend(triples)
+
+ if resolve_coreferences:
+ corefs = coref_resolver.resolve(txt, **options)
+ results["coreferences"].append(corefs)
+
+ results["entities"] = all_entities
+ results["relations"] = all_relations
+ results["events"] = all_events
+ results["triples"] = all_triples
+
+ results["statistics"] = {
+ "texts_processed": len(texts),
+ "entities_extracted": len(all_entities),
+ "relations_extracted": len(all_relations),
+ "events_extracted": len(all_events),
+ "triples_extracted": len(all_triples)
+ }
+
+ results["metadata"] = {
+ "extract_entities": extract_entities,
+ "extract_relations": extract_relations,
+ "extract_events": extract_events,
+ "extract_triples": extract_triples,
+ "resolve_coreferences": resolve_coreferences
+ }
+
+ return results
diff --git a/semantica/semantic_extract/coreference_resolver.py b/semantica/semantic_extract/coreference_resolver.py
index b1f59b03..4c53f4b8 100644
--- a/semantica/semantic_extract/coreference_resolver.py
+++ b/semantica/semantic_extract/coreference_resolver.py
@@ -1,20 +1,34 @@
"""
Coreference Resolution Module
-Handles resolution of coreferences and pronoun references.
+This module provides comprehensive coreference resolution capabilities for resolving
+pronoun references and entity coreferences in text, enabling better understanding
+of entity mentions and references.
Key Features:
- - Pronoun resolution
+ - Pronoun resolution (he, she, it, they, etc.)
- Entity coreference detection
- Coreference chain construction
- Ambiguity resolution
- - Cross-document coreference
+ - Cross-document coreference support
+ - Mention extraction and tracking
Main Classes:
- - CoreferenceResolver: Main coreference resolution class
+ - CoreferenceResolver: Main coreference resolution coordinator
- PronounResolver: Pronoun resolution engine
- EntityCoreferenceDetector: Entity coreference detection
- CoreferenceChainBuilder: Coreference chain construction
+ - Mention: Mention representation dataclass
+ - CoreferenceChain: Coreference chain representation dataclass
+
+Example Usage:
+ >>> from semantica.semantic_extract import CoreferenceResolver
+ >>> resolver = CoreferenceResolver()
+ >>> chains = resolver.resolve_coreferences("John went to the store. He bought milk.")
+ >>> pronouns = resolver.resolve_pronouns("Mary said she would come.")
+
+Author: Semantica Contributors
+License: MIT
"""
from dataclasses import dataclass, field
diff --git a/semantica/semantic_extract/event_detector.py b/semantica/semantic_extract/event_detector.py
index 77e28bd8..df19be94 100644
--- a/semantica/semantic_extract/event_detector.py
+++ b/semantica/semantic_extract/event_detector.py
@@ -1,20 +1,33 @@
"""
Event Detection Module
-Handles detection and extraction of events from text.
+This module provides comprehensive event detection and extraction capabilities,
+enabling identification of events, their participants, temporal information,
+and relationships between events.
Key Features:
- Event detection and classification
- - Temporal event processing
+ - Temporal event processing and sorting
- Event relationship extraction
- Event confidence scoring
- Custom event pattern detection
+ - Participant and location extraction
Main Classes:
- - EventDetector: Main event detection class
+ - EventDetector: Main event detection coordinator
- EventClassifier: Event type classification
- TemporalEventProcessor: Temporal event handling
- EventRelationshipExtractor: Event relationship extraction
+ - Event: Event representation dataclass
+
+Example Usage:
+ >>> from semantica.semantic_extract import EventDetector
+ >>> detector = EventDetector()
+ >>> events = detector.detect_events("Apple was founded in 1976 by Steve Jobs.")
+ >>> classified = detector.classify_events(events)
+
+Author: Semantica Contributors
+License: MIT
"""
import re
diff --git a/semantica/semantic_extract/extraction_validator.py b/semantica/semantic_extract/extraction_validator.py
index 5019136e..5b627ebf 100644
--- a/semantica/semantic_extract/extraction_validator.py
+++ b/semantica/semantic_extract/extraction_validator.py
@@ -1,8 +1,31 @@
"""
-Extraction validator for Semantica framework.
+Extraction Validator Module
-This module provides quality validation for semantic extractions
-to ensure accuracy and consistency.
+This module provides comprehensive quality validation for semantic extractions,
+ensuring accuracy, consistency, and reliability of extracted entities and relations.
+
+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
+
+Main Classes:
+ - ExtractionValidator: Main validation coordinator
+ - ValidationResult: Validation result representation dataclass
+
+Example Usage:
+ >>> from semantica.semantic_extract import ExtractionValidator
+ >>> validator = ExtractionValidator()
+ >>> result = validator.validate_entities(entities)
+ >>> if result.valid:
+ ... print(f"Quality score: {result.score}")
+ >>> filtered = validator.filter_by_confidence(entities, min_confidence=0.8)
+
+Author: Semantica Contributors
+License: MIT
"""
from dataclasses import dataclass, field
diff --git a/semantica/semantic_extract/llm_enhancer.py b/semantica/semantic_extract/llm_enhancer.py
index def7ee5f..b2c610a1 100644
--- a/semantica/semantic_extract/llm_enhancer.py
+++ b/semantica/semantic_extract/llm_enhancer.py
@@ -1,8 +1,29 @@
"""
-LLM-based extraction enhancer for Semantica framework.
+LLM Enhancement Module
-This module provides LLM-based extraction capabilities
-using OpenAI, Anthropic, and other language models.
+This module provides LLM-based extraction enhancement capabilities using OpenAI,
+Anthropic, and other language models to improve entity and relation extraction quality.
+
+Key Features:
+ - Entity extraction enhancement using LLMs
+ - Relation extraction enhancement
+ - Multi-provider support (OpenAI, Anthropic)
+ - Configurable model selection
+ - API key management
+ - Graceful fallback when LLM unavailable
+
+Main Classes:
+ - LLMEnhancer: Main LLM enhancement coordinator
+ - LLMResponse: LLM response representation dataclass
+
+Example Usage:
+ >>> from semantica.semantic_extract import LLMEnhancer
+ >>> enhancer = LLMEnhancer(provider="openai", model="gpt-3.5-turbo")
+ >>> enhanced_entities = enhancer.enhance_entities(text, entities)
+ >>> enhanced_relations = enhancer.enhance_relations(text, relations)
+
+Author: Semantica Contributors
+License: MIT
"""
from dataclasses import dataclass
diff --git a/semantica/semantic_extract/named_entity_recognizer.py b/semantica/semantic_extract/named_entity_recognizer.py
index 6457ec23..43a996d6 100644
--- a/semantica/semantic_extract/named_entity_recognizer.py
+++ b/semantica/semantic_extract/named_entity_recognizer.py
@@ -1,20 +1,33 @@
"""
Named Entity Recognition Module
-Handles extraction and recognition of named entities from text.
+This module provides comprehensive named entity recognition capabilities for
+extracting and classifying entities from text with confidence scoring and
+custom type support.
Key Features:
- - Multi-type entity recognition
+ - Multi-type entity recognition (PERSON, ORG, GPE, DATE, etc.)
- Entity classification and categorization
- Entity confidence scoring
- Custom entity type support
- Batch entity processing
+ - Entity disambiguation
Main Classes:
- - NamedEntityRecognizer: Main NER class
+ - NamedEntityRecognizer: Main NER coordinator
- EntityClassifier: Entity classification engine
- EntityConfidenceScorer: Confidence scoring system
- CustomEntityDetector: Custom entity detection
+
+Example Usage:
+ >>> from semantica.semantic_extract import NamedEntityRecognizer
+ >>> ner = NamedEntityRecognizer()
+ >>> entities = ner.extract_entities("Steve Jobs founded Apple in 1976.")
+ >>> classified = ner.classify_entities(entities)
+ >>> scored = ner.score_confidence(entities)
+
+Author: Semantica Contributors
+License: MIT
"""
from dataclasses import dataclass, field
diff --git a/semantica/semantic_extract/ner_extractor.py b/semantica/semantic_extract/ner_extractor.py
index 0896ac6d..cfac8520 100644
--- a/semantica/semantic_extract/ner_extractor.py
+++ b/semantica/semantic_extract/ner_extractor.py
@@ -1,8 +1,29 @@
"""
-Named Entity Recognition extractor for Semantica framework.
+Named Entity Recognition Extractor Module
-This module provides NER capabilities using spaCy and transformers
-for entity identification and classification.
+This module provides core NER capabilities using spaCy and transformers for
+entity identification and classification, with fallback pattern-based extraction.
+
+Key Features:
+ - spaCy-based entity extraction
+ - Pattern-based fallback extraction
+ - Multiple entity type support
+ - Confidence scoring
+ - Batch processing
+ - Entity filtering by confidence
+
+Main Classes:
+ - NERExtractor: Core NER extractor
+ - Entity: Entity representation dataclass
+
+Example Usage:
+ >>> from semantica.semantic_extract import NERExtractor
+ >>> extractor = NERExtractor(model="en_core_web_sm")
+ >>> entities = extractor.extract_entities("Apple Inc. was founded in 1976.")
+ >>> filtered = extractor.filter_by_confidence(entities, min_confidence=0.8)
+
+Author: Semantica Contributors
+License: MIT
"""
from dataclasses import dataclass, field
diff --git a/semantica/semantic_extract/relation_extractor.py b/semantica/semantic_extract/relation_extractor.py
index 0ab08f58..21aebe18 100644
--- a/semantica/semantic_extract/relation_extractor.py
+++ b/semantica/semantic_extract/relation_extractor.py
@@ -1,8 +1,30 @@
"""
-Relation extraction for Semantica framework.
+Relation Extraction Module
-This module provides relationship detection and extraction
-between entities in text documents.
+This module provides comprehensive relationship detection and extraction
+between entities in text documents using pattern matching and co-occurrence analysis.
+
+Key Features:
+ - Pattern-based relation extraction
+ - Co-occurrence based relation detection
+ - Multiple relation types (founded_by, located_in, works_for, etc.)
+ - Relation classification
+ - Relation validation
+ - Context extraction
+
+Main Classes:
+ - RelationExtractor: Main relation extractor
+ - Relation: Relation representation dataclass
+
+Example Usage:
+ >>> from semantica.semantic_extract import RelationExtractor
+ >>> extractor = RelationExtractor()
+ >>> relations = extractor.extract_relations("Apple was founded by Steve Jobs.", entities)
+ >>> classified = extractor.classify_relations(relations)
+ >>> validated = extractor.validate_relations(relations)
+
+Author: Semantica Contributors
+License: MIT
"""
import re
diff --git a/semantica/semantic_extract/semantic_analyzer.py b/semantica/semantic_extract/semantic_analyzer.py
index 45bd0ccf..26be5c1d 100644
--- a/semantica/semantic_extract/semantic_analyzer.py
+++ b/semantica/semantic_extract/semantic_analyzer.py
@@ -1,20 +1,33 @@
"""
Semantic Analysis Module
-Handles comprehensive semantic analysis of text and data.
+This module provides comprehensive semantic analysis capabilities including
+similarity calculation, role labeling, clustering, and feature extraction.
Key Features:
- - Semantic similarity analysis
- - Semantic role labeling
+ - Semantic similarity analysis (Jaccard, cosine)
+ - Semantic role labeling (agent, patient, theme, location)
- Semantic clustering and grouping
- - Semantic relationship analysis
- - Semantic quality assessment
+ - Semantic feature extraction
+ - Text quality assessment
Main Classes:
- - SemanticAnalyzer: Main semantic analysis class
+ - SemanticAnalyzer: Main semantic analysis coordinator
- SimilarityAnalyzer: Semantic similarity analysis
- RoleLabeler: Semantic role labeling
- SemanticClusterer: Semantic clustering engine
+ - SemanticRole: Semantic role representation dataclass
+ - SemanticCluster: Semantic cluster representation dataclass
+
+Example Usage:
+ >>> from semantica.semantic_extract import SemanticAnalyzer
+ >>> analyzer = SemanticAnalyzer()
+ >>> similarity = analyzer.calculate_similarity("Apple Inc.", "Apple company")
+ >>> roles = analyzer.label_semantic_roles("John bought a car.")
+ >>> clusters = analyzer.cluster_semantically(texts)
+
+Author: Semantica Contributors
+License: MIT
"""
from dataclasses import dataclass, field
diff --git a/semantica/semantic_extract/semantic_network_extractor.py b/semantica/semantic_extract/semantic_network_extractor.py
index 592cfd48..f864ebf3 100644
--- a/semantica/semantic_extract/semantic_network_extractor.py
+++ b/semantica/semantic_extract/semantic_network_extractor.py
@@ -1,8 +1,32 @@
"""
-Semantic Network Extractor for Semantica framework.
+Semantic Network Extractor Module
-Extracts structured semantic networks from documents as part of the
+This module extracts structured semantic networks from documents, converting
+entities and relations into graph structures with nodes and edges. Part of the
6-stage ontology generation pipeline (Stage 2: semantic network extraction).
+
+Key Features:
+ - Semantic network construction from entities and relations
+ - Node and edge creation
+ - Network analysis and metrics
+ - YAML export capabilities
+ - Connectivity analysis
+
+Main Classes:
+ - SemanticNetworkExtractor: Main network extractor
+ - SemanticNetwork: Semantic network representation dataclass
+ - SemanticNode: Network node representation dataclass
+ - SemanticEdge: Network edge representation dataclass
+
+Example Usage:
+ >>> from semantica.semantic_extract import SemanticNetworkExtractor
+ >>> extractor = SemanticNetworkExtractor()
+ >>> network = extractor.extract_network(text, entities, relations)
+ >>> analysis = extractor.analyze_network(network)
+ >>> yaml_str = extractor.export_to_yaml(network, "network.yaml")
+
+Author: Semantica Contributors
+License: MIT
"""
from dataclasses import dataclass, field
diff --git a/semantica/semantic_extract/triple_extractor.py b/semantica/semantic_extract/triple_extractor.py
index c2b10206..c9fa82b0 100644
--- a/semantica/semantic_extract/triple_extractor.py
+++ b/semantica/semantic_extract/triple_extractor.py
@@ -1,20 +1,34 @@
"""
RDF Triple Extraction Module
-Handles extraction of RDF triples from text and structured data.
+This module provides comprehensive RDF triple extraction capabilities, enabling
+conversion of entities and relations into RDF triples with validation and
+serialization support.
Key Features:
- - RDF triple generation
+ - RDF triple generation from entities and relations
- Subject-predicate-object extraction
- Triple validation and quality checking
- - RDF serialization support
+ - RDF serialization (Turtle, N-Triples, JSON-LD, RDF/XML)
- Batch triple processing
+ - URI formatting and normalization
Main Classes:
- - TripleExtractor: Main triple extraction class
+ - TripleExtractor: Main triple extraction coordinator
- TripleValidator: Triple validation engine
- RDFSerializer: RDF serialization handler
- TripleQualityChecker: Triple quality assessment
+ - Triple: RDF triple representation dataclass
+
+Example Usage:
+ >>> from semantica.semantic_extract import TripleExtractor
+ >>> extractor = TripleExtractor()
+ >>> triples = extractor.extract_triples(text, entities, relations)
+ >>> rdf_turtle = extractor.serialize_triples(triples, format="turtle")
+ >>> validated = extractor.validate_triples(triples)
+
+Author: Semantica Contributors
+License: MIT
"""
from dataclasses import dataclass, field