Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat: Add multiple extraction methods and LLM provider support

KaifAhmad10a1821d58614
diff --git a/pyproject.toml b/pyproject.toml
index 35ea4dbc..d79b65fc 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -141,6 +141,28 @@ monitoring = [
"grafana-api>=1.0.0",
"elasticsearch>=8.5.0"
]
+llm-openai = [
+ "openai>=1.0.0"
+]
+llm-gemini = [
+ "google-generativeai>=0.3.0"
+]
+llm-groq = [
+ "groq>=0.4.0"
+]
+llm-anthropic = [
+ "anthropic>=0.18.0"
+]
+llm-ollama = [
+ "ollama>=0.1.0"
+]
+llm-all = [
+ "semantica[llm-openai,llm-gemini,llm-groq,llm-anthropic,llm-ollama]"
+]
+models-huggingface = [
+ "transformers>=4.20.0",
+ "torch>=1.12.0"
+]
[project.urls]
Homepage = "https://semantica.dev"
diff --git a/semantica/semantic_extract/__init__.py b/semantica/semantic_extract/__init__.py
index 7e3dda3a..1cca26ff 100644
--- a/semantica/semantic_extract/__init__.py
+++ b/semantica/semantic_extract/__init__.py
@@ -100,6 +100,29 @@ from .extraction_validator import (
ExtractionValidator,
ValidationResult
)
+from .providers import (
+ BaseProvider,
+ OpenAIProvider,
+ GeminiProvider,
+ GroqProvider,
+ AnthropicProvider,
+ OllamaProvider,
+ HuggingFaceLLMProvider,
+ HuggingFaceModelLoader,
+ create_provider
+)
+from .registry import (
+ ProviderRegistry,
+ MethodRegistry,
+ provider_registry,
+ method_registry
+)
+from .config import Config, config
+from .methods import (
+ get_entity_method,
+ get_relation_method,
+ get_triple_method
+)
__all__ = [
# Named Entity Recognition
@@ -157,6 +180,34 @@ __all__ = [
# Validation
"ExtractionValidator",
"ValidationResult",
+
+ # Providers
+ "BaseProvider",
+ "OpenAIProvider",
+ "GeminiProvider",
+ "GroqProvider",
+ "AnthropicProvider",
+ "OllamaProvider",
+ "HuggingFaceLLMProvider",
+ "HuggingFaceModelLoader",
+ "create_provider",
+
+ # Registry
+ "ProviderRegistry",
+ "MethodRegistry",
+ "provider_registry",
+ "method_registry",
+
+ # Config
+ "Config",
+ "config",
+
+ # Methods
+ "get_entity_method",
+ "get_relation_method",
+ "get_triple_method",
+
+ # Convenience
"build",
]
diff --git a/semantica/semantic_extract/config.py b/semantica/semantic_extract/config.py
new file mode 100644
index 00000000..a69fd49f
--- /dev/null
+++ b/semantica/semantic_extract/config.py
@@ -0,0 +1,116 @@
+"""
+Configuration Management Module
+
+This module provides centralized configuration management for semantic extraction,
+supporting multiple configuration sources including environment variables, config files,
+and programmatic configuration.
+
+Supported Configuration Sources:
+ - Environment variables: OPENAI_API_KEY, GEMINI_API_KEY, GROQ_API_KEY, etc.
+ - Config files: YAML, JSON, TOML formats
+ - Programmatic: Python API for setting provider configurations
+
+Algorithms Used:
+ - Environment Variable Parsing: OS-level environment variable access
+ - YAML Parsing: YAML parser for configuration file loading
+ - JSON Parsing: JSON parser for configuration file loading
+ - TOML Parsing: TOML parser for configuration file loading
+ - Fallback Chain: Priority-based configuration resolution
+ - Dictionary Merging: Deep merge algorithms for configuration updates
+
+Key Features:
+ - Environment variable support for API keys (OPENAI_API_KEY, GEMINI_API_KEY, etc.)
+ - Config file support (YAML, JSON, TOML formats)
+ - Programmatic configuration via Python API
+ - Provider-specific configuration management
+ - Automatic fallback chain (config file -> environment -> defaults)
+ - Global config instance for easy access
+
+Main Classes:
+ - Config: Main configuration manager class
+
+Example Usage:
+ >>> from semantica.semantic_extract.config import config
+ >>> api_key = config.get_api_key("openai")
+ >>> config.set_provider("openai", api_key="sk-...", model="gpt-4")
+ >>> provider_config = config.get_provider_config("gemini")
+
+Author: Semantica Contributors
+License: MIT
+"""
+
+import os
+from typing import Optional, Dict
+from pathlib import Path
+
+from ..utils.logging import get_logger
+
+
+class Config:
+ """Configuration manager - supports .env files, environment variables, and programmatic config."""
+
+ def __init__(self, config_file: Optional[str] = None):
+ """Initialize configuration manager."""
+ self.logger = get_logger("config")
+ self._configs: Dict[str, Dict] = {}
+ self._load_config_file(config_file)
+ self._load_env_vars()
+
+ def _load_config_file(self, config_file: Optional[str]):
+ """Load configuration from file."""
+ if config_file and Path(config_file).exists():
+ try:
+ # Support YAML, JSON, TOML
+ if config_file.endswith('.yaml') or config_file.endswith('.yml'):
+ import yaml
+ with open(config_file, 'r') as f:
+ self._configs.update(yaml.safe_load(f) or {})
+ elif config_file.endswith('.json'):
+ import json
+ with open(config_file, 'r') as f:
+ self._configs.update(json.load(f) or {})
+ elif config_file.endswith('.toml'):
+ import toml
+ with open(config_file, 'r') as f:
+ self._configs.update(toml.load(f) or {})
+ except Exception as e:
+ self.logger.warning(f"Failed to load config file {config_file}: {e}")
+
+ def _load_env_vars(self):
+ """Load configuration from environment variables."""
+ # Common environment variable patterns
+ providers = ["openai", "gemini", "groq", "anthropic", "ollama"]
+ for provider in providers:
+ env_key = f"{provider.upper()}_API_KEY"
+ api_key = os.getenv(env_key)
+ if api_key:
+ if provider not in self._configs:
+ self._configs[provider] = {}
+ self._configs[provider]["api_key"] = api_key
+
+ def set_provider(self, name: str, **config):
+ """Set provider config programmatically."""
+ self._configs[name] = config
+
+ def get_provider_config(self, name: str) -> Dict:
+ """Get provider configuration."""
+ if name in self._configs:
+ return self._configs[name]
+
+ # Fallback to environment variables
+ env_key = f"{name.upper()}_API_KEY"
+ api_key = os.getenv(env_key)
+ if api_key:
+ return {"api_key": api_key}
+
+ return {}
+
+ def get_api_key(self, provider: str) -> Optional[str]:
+ """Get API key with fallback chain: config -> env -> None."""
+ if provider in self._configs:
+ return self._configs[provider].get("api_key")
+ return os.getenv(f"{provider.upper()}_API_KEY")
+
+
+# Global config instance
+config = Config()
diff --git a/semantica/semantic_extract/coreference_resolver.py b/semantica/semantic_extract/coreference_resolver.py
index 83dc647d..477cfd28 100644
--- a/semantica/semantic_extract/coreference_resolver.py
+++ b/semantica/semantic_extract/coreference_resolver.py
@@ -3,7 +3,25 @@ Coreference Resolution Module
This module provides comprehensive coreference resolution capabilities for resolving
pronoun references and entity coreferences in text, enabling better understanding
-of entity mentions and references.
+of entity mentions and references. Supports multiple extraction methods for
+underlying entity extraction.
+
+Supported Methods (for underlying NER extractors):
+ - "pattern": Pattern-based extraction
+ - "regex": Regex-based extraction
+ - "rules": Rule-based extraction
+ - "ml": ML-based extraction (spaCy)
+ - "huggingface": HuggingFace model extraction
+ - "llm": LLM-based extraction
+ - Any method supported by NERExtractor
+
+Algorithms Used:
+ - Pronoun Resolution: Rule-based and distance-based antecedent resolution
+ - Entity Coreference: String matching and similarity-based coreference detection
+ - Coreference Chain Building: Graph-based chain construction algorithms
+ - Mention Extraction: Pattern-based and ML-based mention detection
+ - Ambiguity Resolution: Context-aware disambiguation algorithms
+ - Distance Metrics: Character distance and sentence distance calculations
Key Features:
- Pronoun resolution (he, she, it, they, etc.)
@@ -12,6 +30,8 @@ Key Features:
- Ambiguity resolution
- Cross-document coreference support
- Mention extraction and tracking
+ - Integration with multiple NER extraction methods
+ - Method parameter support for underlying extractors
Main Classes:
- CoreferenceResolver: Main coreference resolution coordinator
@@ -23,8 +43,14 @@ Main Classes:
Example Usage:
>>> from semantica.semantic_extract import CoreferenceResolver
+ >>> # Using default methods
>>> resolver = CoreferenceResolver()
>>> chains = resolver.resolve_coreferences("John went to the store. He bought milk.")
+ >>>
+ >>> # Using LLM-based extraction for entities
+ >>> resolver = CoreferenceResolver(method="llm", provider="openai")
+ >>> chains = resolver.resolve_coreferences("John went to the store. He bought milk.")
+ >>>
>>> pronouns = resolver.resolve_pronouns("Mary said she would come.")
Author: Semantica Contributors
@@ -33,7 +59,7 @@ License: MIT
from dataclasses import dataclass, field
import re
-from typing import Any, Dict, List, Optional, Tuple
+from typing import Any, Dict, List, Optional, Tuple, Union
from ..utils.exceptions import ProcessingError
from ..utils.logging import get_logger
@@ -65,13 +91,27 @@ class CoreferenceChain:
class CoreferenceResolver:
"""Coreference resolution handler."""
- def __init__(self, config=None, **kwargs):
- """Initialize coreference resolver."""
+ def __init__(self, method: Union[str, List[str]] = None, config=None, **kwargs):
+ """
+ Initialize coreference resolver.
+
+ Args:
+ method: Extraction method(s) for underlying NER extractors.
+ Can be passed to ner_method in config.
+ config: Legacy config dict (deprecated, use kwargs)
+ **kwargs: Configuration options:
+ - ner_method: Method for NER extraction (if entities need to be extracted)
+ - Other options passed to sub-components
+ """
self.logger = get_logger("coreference_resolver")
self.config = config or {}
self.config.update(kwargs)
self.progress_tracker = get_progress_tracker()
+ # Store method for passing to extractors if needed
+ if method is not None:
+ self.config["ner_method"] = method
+
self.pronoun_resolver = PronounResolver(**self.config.get("pronoun", {}))
self.entity_detector = EntityCoreferenceDetector(**self.config.get("entity", {}))
self.chain_builder = CoreferenceChainBuilder(**self.config.get("chain", {}))
diff --git a/semantica/semantic_extract/event_detector.py b/semantica/semantic_extract/event_detector.py
index de904020..e1736e04 100644
--- a/semantica/semantic_extract/event_detector.py
+++ b/semantica/semantic_extract/event_detector.py
@@ -3,7 +3,26 @@ Event Detection Module
This module provides comprehensive event detection and extraction capabilities,
enabling identification of events, their participants, temporal information,
-and relationships between events.
+and relationships between events. Supports multiple extraction methods for
+entity and relation extraction used in event detection.
+
+Supported Methods (for underlying NER/Relation extractors):
+ - "pattern": Pattern-based extraction
+ - "regex": Regex-based extraction
+ - "rules": Rule-based extraction
+ - "ml": ML-based extraction (spaCy)
+ - "huggingface": HuggingFace model extraction
+ - "llm": LLM-based extraction
+ - Any method supported by NERExtractor and RelationExtractor
+
+Algorithms Used:
+ - Pattern Matching: Regular expression matching for event triggers
+ - Temporal Extraction: Date/time pattern recognition and parsing
+ - Location Extraction: Named entity recognition for locations
+ - Participant Extraction: Capitalization-based and pattern-based participant detection
+ - Event Classification: Rule-based and ML-based event type classification
+ - Temporal Sorting: Chronological ordering algorithms
+ - Event Relationship Detection: Graph-based event relationship extraction
Key Features:
- Event detection and classification
@@ -12,6 +31,8 @@ Key Features:
- Event confidence scoring
- Custom event pattern detection
- Participant and location extraction
+ - Integration with multiple NER and relation extraction methods
+ - Method parameter support for underlying extractors
Main Classes:
- EventDetector: Main event detection coordinator
@@ -22,8 +43,14 @@ Main Classes:
Example Usage:
>>> from semantica.semantic_extract import EventDetector
+ >>> # Using default methods
>>> detector = EventDetector()
>>> events = detector.detect_events("Apple was founded in 1976 by Steve Jobs.")
+ >>>
+ >>> # Using LLM-based extraction for entities
+ >>> detector = EventDetector(ner_method="llm", provider="openai")
+ >>> events = detector.detect_events("Apple was founded in 1976 by Steve Jobs.")
+ >>>
>>> classified = detector.classify_events(events)
Author: Semantica Contributors
@@ -32,7 +59,7 @@ License: MIT
import re
from dataclasses import dataclass, field
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, List, Optional, Union
from ..utils.exceptions import ProcessingError
from ..utils.logging import get_logger
@@ -58,13 +85,29 @@ class Event:
class EventDetector:
"""Event detection and extraction handler."""
- def __init__(self, config=None, **kwargs):
- """Initialize event detector."""
+ def __init__(self, method: Union[str, List[str]] = None, config=None, **kwargs):
+ """
+ Initialize event detector.
+
+ Args:
+ method: Extraction method(s) for underlying NER/relation extractors.
+ Can be passed to ner_method and relation_method in config.
+ config: Legacy config dict (deprecated, use kwargs)
+ **kwargs: Configuration options:
+ - ner_method: Method for NER extraction (if entities need to be extracted)
+ - relation_method: Method for relation extraction (if relations need to be extracted)
+ - Other options passed to sub-components
+ """
self.logger = get_logger("event_detector")
self.config = config or {}
self.config.update(kwargs)
self.progress_tracker = get_progress_tracker()
+ # Store method for passing to extractors if needed
+ if method is not None:
+ self.config["ner_method"] = method
+ self.config["relation_method"] = method
+
self.event_classifier = EventClassifier(**self.config.get("classifier", {}))
self.temporal_processor = TemporalEventProcessor(**self.config.get("temporal", {}))
self.relationship_extractor = EventRelationshipExtractor(**self.config.get("relationship", {}))
diff --git a/semantica/semantic_extract/extraction_validator.py b/semantica/semantic_extract/extraction_validator.py
index 61edab85..96eba089 100644
--- a/semantica/semantic_extract/extraction_validator.py
+++ b/semantica/semantic_extract/extraction_validator.py
@@ -3,6 +3,20 @@ Extraction Validator Module
This module provides comprehensive quality validation for semantic extractions,
ensuring accuracy, consistency, and reliability of extracted entities and relations.
+Supports method parameter for future extensibility with method-specific validation.
+
+Supported Methods (for future extensibility):
+ - Method parameter reserved for method-specific validation strategies
+ - Currently supports general validation for all extraction methods
+ - Future: Method-specific validation rules (e.g., "llm", "ml", "pattern")
+
+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
+ - Quality Scoring: Weighted scoring algorithms for extraction quality
+ - Validation Metrics: Precision, recall, F1-score calculations
+ - Boundary Validation: Character position and text boundary checking
Key Features:
- Entity validation with confidence checking
@@ -11,6 +25,7 @@ Key Features:
- Duplicate detection
- Confidence-based filtering
- Validation result reporting
+ - Method parameter support for future method-specific validation
Main Classes:
- ExtractionValidator: Main validation coordinator
@@ -18,10 +33,14 @@ Main Classes:
Example Usage:
>>> from semantica.semantic_extract import ExtractionValidator
+ >>> # Using default validation
>>> validator = ExtractionValidator()
>>> result = validator.validate_entities(entities)
>>> if result.valid:
... print(f"Quality score: {result.score}")
+ >>>
+ >>> # Using method-specific validation (future extensibility)
+ >>> validator = ExtractionValidator(method="llm")
>>> filtered = validator.filter_by_confidence(entities, min_confidence=0.8)
Author: Semantica Contributors
@@ -52,11 +71,12 @@ class ValidationResult:
class ExtractionValidator:
"""Validator for semantic extractions."""
- def __init__(self, **config):
+ def __init__(self, method: Optional[str] = None, **config):
"""
Initialize extraction validator.
Args:
+ 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)
@@ -65,6 +85,7 @@ class ExtractionValidator:
self.config = config
self.progress_tracker = get_progress_tracker()
+ 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)
diff --git a/semantica/semantic_extract/llm_enhancer.py b/semantica/semantic_extract/llm_enhancer.py
index 3fea516c..ae1ebf43 100644
--- a/semantica/semantic_extract/llm_enhancer.py
+++ b/semantica/semantic_extract/llm_enhancer.py
@@ -1,16 +1,41 @@
"""
LLM Enhancement Module
-This module provides LLM-based extraction enhancement capabilities using OpenAI,
-Anthropic, and other language models to improve entity and relation extraction quality.
+This module provides LLM-based extraction enhancement capabilities using multiple
+language model providers to improve entity and relation extraction quality through
+post-processing and refinement.
+
+Supported Providers:
+ - "openai": OpenAI (GPT-3.5, GPT-4, etc.)
+ - "gemini": Google Gemini (gemini-pro, etc.)
+ - "groq": Groq (llama2, mixtral, etc.)
+ - "anthropic": Anthropic Claude (claude-3-sonnet, etc.)
+ - "ollama": Ollama (local open-source models)
+ - "huggingface_llm": HuggingFace Transformers (custom LLM models)
+
+Algorithms Used:
+ - Prompt Engineering: Structured prompt construction for enhancement tasks
+ - LLM Generation: Transformer-based language model text generation
+ - Response Parsing: JSON parsing and structured output extraction
+ - Entity Refinement: Confidence-based entity validation and correction
+ - Relation Enhancement: Context-aware relation validation and improvement
+ - Temperature Sampling: Stochastic sampling for diverse outputs
Key Features:
- Entity extraction enhancement using LLMs
- Relation extraction enhancement
- - Multi-provider support (OpenAI, Anthropic)
- - Configurable model selection
- - API key management
+ - Multi-provider support:
+ * OpenAI (GPT-3.5, GPT-4, etc.)
+ * Google Gemini (gemini-pro, etc.)
+ * Groq (llama2, mixtral, etc.)
+ * Anthropic Claude (claude-3-sonnet, etc.)
+ * Ollama (local open-source models)
+ * HuggingFace Transformers (custom LLM models)
+ - Unified provider interface via providers module
+ - Configurable model selection per provider
+ - Automatic API key management from environment variables
- Graceful fallback when LLM unavailable
+ - Structured prompt generation for enhancement tasks
Main Classes:
- LLMEnhancer: Main LLM enhancement coordinator
@@ -18,9 +43,18 @@ Main Classes:
Example Usage:
>>> from semantica.semantic_extract import LLMEnhancer
- >>> enhancer = LLMEnhancer(provider="openai", model="gpt-3.5-turbo")
+ >>> # Using OpenAI
+ >>> enhancer = LLMEnhancer(provider="openai", model="gpt-4")
>>> enhanced_entities = enhancer.enhance_entities(text, entities)
>>> enhanced_relations = enhancer.enhance_relations(text, relations)
+ >>>
+ >>> # Using Gemini
+ >>> enhancer = LLMEnhancer(provider="gemini", model="gemini-pro")
+ >>> enhanced_entities = enhancer.enhance_entities(text, entities)
+ >>>
+ >>> # Using Ollama (local)
+ >>> enhancer = LLMEnhancer(provider="ollama", model="llama2")
+ >>> enhanced_entities = enhancer.enhance_entities(text, entities)
Author: Semantica Contributors
License: MIT
@@ -34,6 +68,7 @@ from ..utils.logging import get_logger
from ..utils.progress_tracker import get_progress_tracker
from .ner_extractor import Entity
from .relation_extractor import Relation
+from .providers import create_provider
@dataclass
@@ -49,14 +84,14 @@ class LLMResponse:
class LLMEnhancer:
"""LLM-based extraction enhancer."""
- def __init__(self, **config):
+ def __init__(self, provider: str = "openai", **config):
"""
Initialize LLM enhancer.
Args:
+ provider: LLM provider ("openai", "gemini", "groq", "anthropic", "ollama", "huggingface_llm")
**config: Configuration options:
- - provider: LLM provider ("openai", "anthropic", default: "openai")
- - model: Model name (default: "gpt-3.5-turbo")
+ - model: Model name (default depends on provider)
- api_key: API key (from environment if not provided)
- temperature: Temperature for generation
"""
@@ -64,37 +99,16 @@ class LLMEnhancer:
self.config = config
self.progress_tracker = get_progress_tracker()
- self.provider = config.get("provider", "openai")
- self.model = config.get("model", "gpt-3.5-turbo")
+ self.provider_name = provider
+ self.model = config.get("model")
self.temperature = config.get("temperature", 0.3)
- # Initialize client
- self.client = None
- self._initialize_client()
-
- def _initialize_client(self):
- """Initialize LLM client based on provider."""
+ # Initialize provider using new system
try:
- if self.provider == "openai":
- import os
- from openai import OpenAI
- api_key = self.config.get("api_key") or os.getenv("OPENAI_API_KEY")
- if api_key:
- self.client = OpenAI(api_key=api_key)
- else:
- self.logger.warning("OpenAI API key not found. LLM features disabled.")
- elif self.provider == "anthropic":
- import os
- from anthropic import Anthropic
- api_key = self.config.get("api_key") or os.getenv("ANTHROPIC_API_KEY")
- if api_key:
- self.client = Anthropic(api_key=api_key)
- else:
- self.logger.warning("Anthropic API key not found. LLM features disabled.")
- else:
- self.logger.warning(f"Unsupported LLM provider: {self.provider}")
- except ImportError:
- self.logger.warning(f"Required library for {self.provider} not installed. LLM features disabled.")
+ self.provider = create_provider(provider, **config)
+ except Exception as e:
+ self.logger.warning(f"Failed to initialize {provider} provider: {e}")
+ self.provider = None
def enhance_entities(self, text: str, entities: List[Entity], **options) -> List[Entity]:
"""
@@ -115,16 +129,16 @@ class LLMEnhancer:
)
try:
- if not self.client:
- self.logger.warning("LLM client not available. Returning original entities.")
- self.progress_tracker.stop_tracking(tracking_id, status="completed", message="LLM client not available")
+ if not self.provider or not self.provider.is_available():
+ self.logger.warning("LLM provider not available. Returning original entities.")
+ self.progress_tracker.stop_tracking(tracking_id, status="completed", message="LLM provider not available")
return entities
self.progress_tracker.update_tracking(tracking_id, message="Building prompt...")
prompt = self._build_entity_prompt(text, entities)
self.progress_tracker.update_tracking(tracking_id, message="Calling LLM API...")
- response = self._call_llm(prompt, **options)
+ response = self.provider.generate(prompt, temperature=options.get("temperature", self.temperature))
self.progress_tracker.update_tracking(tracking_id, message="Parsing LLM response...")
enhanced_entities = self._parse_entity_response(response, entities)
@@ -149,39 +163,20 @@ class LLMEnhancer:
Returns:
list: Enhanced relations
"""
- if not self.client:
- self.logger.warning("LLM client not available. Returning original relations.")
+ if not self.provider or not self.provider.is_available():
+ self.logger.warning("LLM provider not available. Returning original relations.")
return relations
prompt = self._build_relation_prompt(text, relations)
try:
- response = self._call_llm(prompt, **options)
+ response = self.provider.generate(prompt, temperature=options.get("temperature", self.temperature))
enhanced_relations = self._parse_relation_response(response, relations)
return enhanced_relations
except Exception as e:
self.logger.error(f"Failed to enhance relations with LLM: {e}")
return relations
- def _call_llm(self, prompt: str, **options) -> str:
- """Call LLM API."""
- if self.provider == "openai" and self.client:
- response = self.client.chat.completions.create(
- model=options.get("model", self.model),
- messages=[{"role": "user", "content": prompt}],
- temperature=options.get("temperature", self.temperature)
- )
- return response.choices[0].message.content
- elif self.provider == "anthropic" and self.client:
- response = self.client.messages.create(
- model=options.get("model", self.model),
- max_tokens=4096,
- messages=[{"role": "user", "content": prompt}]
- )
- return response.content[0].text
-
- raise ProcessingError("LLM client not available")
-
def _build_entity_prompt(self, text: str, entities: List[Entity]) -> str:
"""Build prompt for entity enhancement."""
entities_str = "\n".join([f"- {e.text} ({e.label})" for e in entities])
diff --git a/semantica/semantic_extract/methods.py b/semantica/semantic_extract/methods.py
new file mode 100644
index 00000000..ec110bdf
--- /dev/null
+++ b/semantica/semantic_extract/methods.py
@@ -0,0 +1,737 @@
+"""
+Extraction Methods Module
+
+This module provides all extraction methods as simple, reusable functions for
+entities, relations, and triples. It supports multiple extraction approaches
+ranging from simple pattern matching to advanced LLM-based extraction.
+
+Supported Methods:
+
+Entity Extraction:
+ - "pattern": Pattern-based entity extraction using regex
+ - "regex": Advanced regex-based entity extraction with custom patterns
+ - "rules": Rule-based entity extraction using linguistic rules
+ - "ml": ML-based entity extraction using spaCy
+ - "huggingface": HuggingFace NER model extraction
+ - "llm": LLM-based entity extraction
+
+Relation Extraction:
+ - "pattern": Pattern-based relation extraction
+ - "regex": Advanced regex-based relation extraction
+ - "cooccurrence": Co-occurrence based relation detection
+ - "dependency": Dependency parsing-based relation extraction
+ - "huggingface": HuggingFace relation extraction models
+ - "llm": LLM-based relation extraction
+
+Triple Extraction:
+ - "pattern": Pattern-based triple extraction
+ - "rules": Rule-based triple extraction
+ - "huggingface": HuggingFace triplet extraction models
+ - "llm": LLM-based triple extraction
+
+Algorithms Used:
+
+Entity Extraction:
+ - Regular Expression Matching: Finite automata-based pattern matching
+ - Rule-based NLP: Linguistic rule application and pattern matching
+ - Neural NER: CNN/Transformer-based named entity recognition (spaCy)
+ - Transformer Token Classification: BERT/RoBERTa for token-level classification
+ - LLM Generation: Transformer-based language models for entity extraction
+
+Relation Extraction:
+ - Pattern Matching: Regex and string pattern matching algorithms
+ - Co-occurrence Analysis: Proximity-based entity relationship detection
+ - Dependency Parsing: Transition-based and graph-based parsing algorithms
+ - Sequence Classification: Transformer-based relation classification
+ - LLM Generation: Language model-based relation extraction
+
+Triple Extraction:
+ - Pattern Matching: Subject-predicate-object pattern extraction
+ - Rule-based Extraction: Linguistic rule application
+ - Seq2Seq Models: Encoder-decoder transformer models for triplet generation
+ - LLM Generation: Structured output generation from language models
+
+Key Features:
+ - Multiple extraction methods for entities:
+ * Pattern-based: Simple regex pattern matching
+ * Regex-based: Advanced regex with custom patterns
+ * Rules-based: Linguistic rule-based extraction
+ * ML-based: spaCy-based machine learning extraction
+ * HuggingFace: Custom HuggingFace NER models
+ * LLM-based: Large language model extraction
+ - Multiple extraction methods for relations:
+ * Pattern-based: Pattern matching for common relations
+ * Regex-based: Advanced regex relation extraction
+ * Co-occurrence: Proximity-based relation detection
+ * Dependency: Dependency parsing-based extraction
+ * HuggingFace: Custom HuggingFace relation models
+ * LLM-based: LLM-powered relation extraction
+ - Multiple extraction methods for triples:
+ * Pattern-based: Pattern matching for triple extraction
+ * Rules-based: Rule-based triple extraction
+ * HuggingFace: Custom HuggingFace triplet models
+ * LLM-based: LLM-powered triple extraction
+ - Method dispatchers with registry support
+ - Custom method registration capability
+ - Consistent interface across all methods
+
+Main Functions:
+ - extract_entities_pattern: Pattern-based entity extraction
+ - extract_entities_regex: Regex-based entity extraction
+ - extract_entities_rules: Rule-based entity extraction
+ - extract_entities_ml: ML-based (spaCy) entity extraction
+ - extract_entities_huggingface: HuggingFace model entity extraction
+ - extract_entities_llm: LLM-based entity extraction
+ - extract_relations_pattern: Pattern-based relation extraction
+ - extract_relations_regex: Regex-based relation extraction
+ - extract_relations_cooccurrence: Co-occurrence relation extraction
+ - extract_relations_dependency: Dependency parsing relation extraction
+ - extract_relations_huggingface: HuggingFace relation extraction
+ - extract_relations_llm: LLM-based relation extraction
+ - extract_triples_pattern: Pattern-based triple extraction
+ - extract_triples_rules: Rule-based triple extraction
+ - extract_triples_huggingface: HuggingFace triple extraction
+ - extract_triples_llm: LLM-based triple extraction
+ - get_entity_method: Get entity extraction method by name
+ - get_relation_method: Get relation extraction method by name
+ - get_triple_method: Get triple extraction method by name
+
+Example Usage:
+ >>> from semantica.semantic_extract.methods import get_entity_method
+ >>> extract_fn = get_entity_method("llm")
+ >>> entities = extract_fn("Apple Inc. was founded in 1976.", provider="openai")
+
+Author: Semantica Contributors
+License: MIT
+"""
+
+import re
+from typing import List, Dict, Any, Optional, Union
+
+from ..utils.logging import get_logger
+from ..utils.exceptions import ProcessingError
+from .providers import create_provider, HuggingFaceModelLoader
+from .registry import method_registry
+from .ner_extractor import Entity
+from .relation_extractor import Relation
+from .triple_extractor import Triple
+
+logger = get_logger("methods")
+
+# Try to import spaCy
+try:
+ import spacy
+ SPACY_AVAILABLE = True
+except ImportError:
+ SPACY_AVAILABLE = False
+
+
+# ============================================================================
+# Entity Extraction Methods
+# ============================================================================
+
+def extract_entities_pattern(text: str, **kwargs) -> List[Entity]:
+ """Pattern-based entity extraction using regex."""
+ 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',
+ "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'
+ }
+
+ for label, pattern in patterns.items():
+ for match in re.finditer(pattern, text):
+ entities.append(Entity(
+ text=match.group(1) if match.groups() else match.group(0),
+ label=label,
+ start_char=match.start(),
+ end_char=match.end(),
+ confidence=0.7,
+ metadata={"extraction_method": "pattern"}
+ ))
+
+ return entities
+
+
+def extract_entities_regex(text: str, patterns: Optional[Dict[str, str]] = None, **kwargs) -> List[Entity]:
+ """Advanced regex-based entity extraction with custom patterns."""
+ entities = []
+
+ if patterns is None:
+ 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|Corporation))\b',
+ "GPE": r'\b([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)\b',
+ "DATE": r'\b(\d{1,2}[/-]\d{1,2}[/-]\d{2,4}|\d{4})\b',
+ "MONEY": r'\b(\$[\d,]+(?:\.\d{2})?)\b',
+ "PERCENT": r'\b(\d+(?:\.\d+)?%)\b'
+ }
+
+ for label, pattern in patterns.items():
+ for match in re.finditer(pattern, text, re.IGNORECASE):
+ entities.append(Entity(
+ text=match.group(1) if match.groups() else match.group(0),
+ label=label,
+ start_char=match.start(),
+ end_char=match.end(),
+ confidence=0.75,
+ metadata={"extraction_method": "regex", "pattern": pattern}
+ ))
+
+ return entities
+
+
+def extract_entities_rules(text: str, **kwargs) -> List[Entity]:
+ """Rule-based entity extraction using linguistic rules."""
+ entities = []
+ words = text.split()
+
+ # Rule: Capitalized words at sentence start are likely entities
+ sentences = re.split(r'[.!?]+', text)
+ char_offset = 0
+
+ for sentence in sentences:
+ sentence = sentence.strip()
+ if not sentence:
+ char_offset += 1
+ continue
+
+ words_in_sent = sentence.split()
+ if words_in_sent:
+ first_word = words_in_sent[0]
+ if first_word and first_word[0].isupper() and len(first_word) > 2:
+ start = text.find(first_word, char_offset)
+ if start >= 0:
+ entities.append(Entity(
+ text=first_word,
+ label="PERSON", # Default assumption
+ start_char=start,
+ end_char=start + len(first_word),
+ confidence=0.6,
+ metadata={"extraction_method": "rules", "rule": "sentence_start"}
+ ))
+
+ char_offset += len(sentence) + 1
+
+ return entities
+
+
+def extract_entities_ml(text: str, model: str = "en_core_web_sm", **kwargs) -> List[Entity]:
+ """ML-based entity extraction using spaCy."""
+ if not SPACY_AVAILABLE:
+ logger.warning("spaCy not available, falling back to pattern extraction")
+ return extract_entities_pattern(text, **kwargs)
+
+ try:
+ nlp = spacy.load(model)
+ except OSError:
+ logger.warning(f"spaCy model {model} not found, using en_core_web_sm")
+ try:
+ nlp = spacy.load("en_core_web_sm")
+ except OSError:
+ logger.warning("spaCy model not available, falling back to pattern extraction")
+ return extract_entities_pattern(text, **kwargs)
+
+ doc = nlp(text)
+ entities = []
+
+ for ent in doc.ents:
+ confidence = 1.0
+ if hasattr(ent, 'confidence'):
+ confidence = ent.confidence
+ elif hasattr(ent, 'score'):
+ confidence = ent.score
+
+ entities.append(Entity(
+ text=ent.text,
+ label=ent.label_,
+ start_char=ent.start_char,
+ end_char=ent.end_char,
+ confidence=confidence,
+ metadata={
+ "extraction_method": "ml",
+ "model": model,
+ "lemma": ent.lemma_ if hasattr(ent, 'lemma_') else ent.text
+ }
+ ))
+
+ return entities
+
+
+def extract_entities_huggingface(text: str, model: str = "dslim/bert-base-NER", device: Optional[str] = None, **kwargs) -> List[Entity]:
+ """HuggingFace entity extraction."""
+ loader = HuggingFaceModelLoader(device=device)
+ model_obj = loader.load_ner_model(model)
+ results = loader.extract_entities(model_obj, text)
+
+ entities = []
+ for result in results:
+ if isinstance(result, dict):
+ entities.append(Entity(
+ text=result.get("word", result.get("entity", "")),
+ label=result.get("entity_group", result.get("label", "UNKNOWN")),
+ start_char=result.get("start", 0),
+ end_char=result.get("end", 0),
+ confidence=result.get("score", 1.0),
+ metadata={"model": model, "extraction_method": "huggingface"}
+ ))
+
+ return entities
+
+
+def extract_entities_llm(text: str, provider: str = "openai", model: Optional[str] = None, **kwargs) -> List[Entity]:
+ """LLM-based entity extraction."""
+ llm = create_provider(provider, model=model, **kwargs)
+
+ if not llm.is_available():
+ raise ProcessingError(f"{provider} provider not available")
+
+ prompt = f"""Extract named entities from the following text.
+Return JSON format: [{{"text": "...", "label": "PERSON|ORG|GPE|DATE|...", "start": 0, "end": 10}}]
+
+Text: {text}"""
+
+ try:
+ result = llm.generate_structured(prompt)
+ entities = []
+
+ if isinstance(result, list):
+ for item in result:
+ entities.append(Entity(
+ text=item.get("text", ""),
+ label=item.get("label", "UNKNOWN"),
+ start_char=item.get("start", 0),
+ end_char=item.get("end", 0),
+ confidence=item.get("confidence", 0.9),
+ metadata={"provider": provider, "model": model, "extraction_method": "llm"}
+ ))
+ elif isinstance(result, dict) and "entities" in result:
+ for item in result["entities"]:
+ entities.append(Entity(
+ text=item.get("text", ""),
+ label=item.get("label", "UNKNOWN"),
+ start_char=item.get("start", 0),
+ end_char=item.get("end", 0),
+ confidence=item.get("confidence", 0.9),
+ metadata={"provider": provider, "model": model, "extraction_method": "llm"}
+ ))
+
+ return entities
+ except Exception as e:
+ logger.error(f"LLM entity extraction failed: {e}")
+ return []
+
+
+# ============================================================================
+# Relation Extraction Methods
+# ============================================================================
+
+def extract_relations_pattern(text: str, entities: List[Entity], **kwargs) -> List[Relation]:
+ """Pattern-based relation extraction."""
+ relations = []
+
+ relation_patterns = {
+ "founded_by": [
+ r"(?P<subject>\w+)\s+(?:was\s+)?founded\s+by\s+(?P<object>\w+(?:\s+\w+)*)",
+ r"(?P<object>\w+(?:\s+\w+)*)\s+founded\s+(?P<subject>\w+)"
+ ],
+ "located_in": [
+ r"(?P<subject>\w+)\s+is\s+located\s+in\s+(?P<object>\w+)",
+ r"(?P<subject>\w+)\s+in\s+(?P<object>\w+)"
+ ],
+ "works_for": [
+ r"(?P<subject>\w+)\s+works?\s+for\s+(?P<object>\w+)",
+ r"(?P<subject>\w+)\s+is\s+an?\s+employee\s+of\s+(?P<object>\w+)"
+ ],
+ "born_in": [
+ r"(?P<subject>\w+)\s+was\s+born\s+in\s+(?P<object>\w+)",
+ r"(?P<subject>\w+)\s+born\s+in\s+(?P<object>\w+)"
+ ]
+ }
+
+ entity_map = {e.text.lower(): e for e in entities}
+
+ for relation_type, patterns in relation_patterns.items():
+ for pattern in patterns:
+ for match in re.finditer(pattern, text, re.IGNORECASE):
+ subject_text = match.group("subject")
+ object_text = match.group("object")
+
+ subject_entity = entity_map.get(subject_text.lower())
+ object_entity = entity_map.get(object_text.lower())
+
+ if subject_entity and object_entity:
+ start = max(0, match.start() - 50)
+ end = min(len(text), match.end() + 50)
+ context = text[start:end]
+
+ relations.append(Relation(
+ subject=subject_entity,
+ predicate=relation_type,
+ object=object_entity,
+ confidence=0.7,
+ context=context,
+ metadata={"extraction_method": "pattern", "pattern": pattern}
+ ))
+
+ return relations
+
+
+def extract_relations_regex(text: str, entities: List[Entity], patterns: Optional[Dict[str, List[str]]] = None, **kwargs) -> List[Relation]:
+ """Advanced regex-based relation extraction."""
+ if patterns is None:
+ patterns = {
+ "founded_by": [r"(?P<subject>\w+)\s+(?:was\s+)?founded\s+by\s+(?P<object>\w+(?:\s+\w+)*)"],
+ "located_in": [r"(?P<subject>\w+)\s+is\s+located\s+in\s+(?P<object>\w+)"],
+ }
+
+ relations = []
+ entity_map = {e.text.lower(): e for e in entities}
+
+ for relation_type, pattern_list in patterns.items():
+ for pattern in pattern_list:
+ for match in re.finditer(pattern, text, re.IGNORECASE):
+ subject_text = match.group("subject")
+ object_text = match.group("object")
+
+ subject_entity = entity_map.get(subject_text.lower())
+ object_entity = entity_map.get(object_text.lower())
+
+ if subject_entity and object_entity:
+ relations.append(Relation(
+ subject=subject_entity,
+ predicate=relation_type,
+ object=object_entity,
+ confidence=0.75,
+ context=text[max(0, match.start()-30):min(len(text), match.end()+30)],
+ metadata={"extraction_method": "regex"}
+ ))
+
+ return relations
+
+
+def extract_relations_cooccurrence(text: str, entities: List[Entity], **kwargs) -> List[Relation]:
+ """Co-occurrence based relation extraction."""
+ relations = []
+
+ for i, entity1 in enumerate(entities):
+ for entity2 in entities[i+1:]:
+ distance = abs(entity1.end_char - entity2.start_char)
+ if distance < 100: # Within 100 characters
+ start = min(entity1.start_char, entity2.start_char)
+ end = max(entity1.end_char, entity2.end_char)
+ context = text[max(0, start-30):min(len(text), end+30)]
+
+ relations.append(Relation(
+ subject=entity1,
+ predicate="related_to",
+ object=entity2,
+ confidence=0.5,
+ context=context,
+ metadata={"extraction_method": "co_occurrence", "distance": distance}
+ ))
+
+ return relations
+
+
+def extract_relations_dependency(text: str, entities: List[Entity], model: str = "en_core_web_sm", **kwargs) -> List[Relation]:
+ """Dependency parsing based relation extraction."""
+ if not SPACY_AVAILABLE:
+ logger.warning("spaCy not available, falling back to pattern extraction")
+ return extract_relations_pattern(text, entities, **kwargs)
+
+ try:
+ nlp = spacy.load(model)
+ except OSError:
+ logger.warning(f"spaCy model {model} not found")
+ return extract_relations_pattern(text, entities, **kwargs)
+
+ doc = nlp(text)
+ relations = []
+ entity_map = {e.text.lower(): e for e in entities}
+
+ for token in doc:
+ # Look for subject-verb-object patterns
+ if token.dep_ == "nsubj" or token.dep_ == "nsubjpass":
+ subject = token.text
+ verb = token.head
+ # Find object
+ for child in verb.children:
+ if child.dep_ in ["dobj", "pobj", "attr"]:
+ obj = child.text
+
+ subject_entity = entity_map.get(subject.lower())
+ object_entity = entity_map.get(obj.lower())
+
+ if subject_entity and object_entity:
+ relations.append(Relation(
+ subject=subject_entity,
+ predicate=verb.lemma_,
+ object=object_entity,
+ confidence=0.8,
+ context=text[max(0, token.idx-30):min(len(text), child.idx+len(obj)+30)],
+ metadata={"extraction_method": "dependency", "dependency_path": f"{token.dep_} -> {child.dep_}"}
+ ))
+
+ return relations
+
+
+def extract_relations_huggingface(text: str, entities: List[Entity], model: str, device: Optional[str] = None, **kwargs) -> List[Relation]:
+ """HuggingFace relation extraction."""
+ loader = HuggingFaceModelLoader(device=device)
+ model_obj = loader.load_relation_model(model)
+
+ # This is simplified - actual implementation would depend on model architecture
+ results = loader.extract_relations(model_obj, text, entities)
+
+ relations = []
+ # Parse results based on model output format
+ # This is a placeholder - actual parsing would depend on the model
+ return relations
+
+
+def extract_relations_llm(text: str, entities: List[Entity], provider: str = "openai", model: Optional[str] = None, **kwargs) -> List[Relation]:
+ """LLM-based relation extraction."""
+ llm = create_provider(provider, model=model, **kwargs)
+
+ if not llm.is_available():
+ raise ProcessingError(f"{provider} provider not available")
+
+ entities_str = ", ".join([f"{e.text} ({e.label})" for e in entities])
+ prompt = f"""Extract relations between entities from the following text.
+
+Text: {text}
+Entities: {entities_str}
+
+Return JSON format: [{{"subject": "...", "predicate": "...", "object": "...", "confidence": 0.9}}]"""
+
+ try:
+ result = llm.generate_structured(prompt)
+ relations = []
+
+ if isinstance(result, list):
+ for item in result:
+ # Find matching entities
+ subject_text = item.get("subject", "")
+ object_text = item.get("object", "")
+
+ subject_entity = next((e for e in entities if e.text.lower() == subject_text.lower()), None)
+ object_entity = next((e for e in entities if e.text.lower() == object_text.lower()), None)
+
+ if subject_entity and object_entity:
+ relations.append(Relation(
+ subject=subject_entity,
+ predicate=item.get("predicate", "related_to"),
+ object=object_entity,
+ confidence=item.get("confidence", 0.9),
+ context=text,
+ metadata={"provider": provider, "model": model, "extraction_method": "llm"}
+ ))
+
+ return relations
+ except Exception as e:
+ logger.error(f"LLM relation extraction failed: {e}")
+ return []
+
+
+# ============================================================================
+# Triple Extraction Methods
+# ============================================================================
+
+def extract_triples_pattern(text: str, entities: Optional[List[Entity]] = None, relations: Optional[List[Relation]] = None, **kwargs) -> List[Triple]:
+ """Pattern-based triple extraction."""
+ triples = []
+
+ if relations:
+ # Convert relations to triples
+ for relation in relations:
+ triples.append(Triple(
+ subject=relation.subject.text,
+ predicate=relation.predicate,
+ object=relation.object.text,
+ confidence=relation.confidence,
+ metadata={"extraction_method": "pattern", **relation.metadata}
+ ))
+ elif entities:
+ # Simple triple extraction from entities
+ # Look for subject-verb-object patterns
+ pattern = r"(?P<subject>\w+)\s+(?P<predicate>\w+)\s+(?P<object>\w+)"
+ for match in re.finditer(pattern, text):
+ subject_text = match.group("subject")
+ predicate_text = match.group("predicate")
+ object_text = match.group("object")
+
+ subject_entity = next((e for e in entities if e.text.lower() == subject_text.lower()), None)
+ object_entity = next((e for e in entities if e.text.lower() == object_text.lower()), None)
+
+ if subject_entity and object_entity:
+ triples.append(Triple(
+ subject=subject_entity.text,
+ predicate=predicate_text,
+ object=object_entity.text,
+ confidence=0.7,
+ metadata={"extraction_method": "pattern"}
+ ))
+
+ return triples
+
+
+def extract_triples_rules(text: str, entities: Optional[List[Entity]] = None, **kwargs) -> List[Triple]:
+ """Rule-based triple extraction."""
+ triples = []
+
+ if not entities:
+ return triples
+
+ # Rule: Look for verb patterns between entities
+ sentences = re.split(r'[.!?]+', text)
+ for sentence in sentences:
+ words = sentence.split()
+ for i, word in enumerate(words):
+ if word.lower() in ["is", "was", "has", "founded", "located"]:
+ # Look for entities before and after
+ if i > 0 and i < len(words) - 1:
+ before = " ".join(words[:i])
+ after = " ".join(words[i+1:])
+
+ subject_entity = next((e for e in entities if e.text.lower() in before.lower()), None)
+ object_entity = next((e for e in entities if e.text.lower() in after.lower()), None)
+
+ if subject_entity and object_entity:
+ triples.append(Triple(
+ subject=subject_entity.text,
+ predicate=word,
+ object=object_entity.text,
+ confidence=0.7,
+ metadata={"extraction_method": "rules"}
+ ))
+
+ return triples
+
+
+def extract_triples_huggingface(text: str, model: str, device: Optional[str] = None, **kwargs) -> List[Triple]:
+ """HuggingFace triple extraction."""
+ loader = HuggingFaceModelLoader(device=device)
+ model_obj = loader.load_triplet_model(model)
+ results = loader.extract_triplets(model_obj, text)
+
+ triples = []
+ for result in results:
+ # Parse result based on model output format
+ # This is a placeholder - actual parsing would depend on the model
+ if "triplet" in result:
+ # Parse triplet string (format depends on model)
+ pass
+
+ return triples
+
+
+def extract_triples_llm(text: str, entities: Optional[List[Entity]] = None, relations: Optional[List[Relation]] = None,
+ provider: str = "openai", model: Optional[str] = None, **kwargs) -> List[Triple]:
+ """LLM-based triple extraction."""
+ llm = create_provider(provider, model=model, **kwargs)
+
+ if not llm.is_available():
+ raise ProcessingError(f"{provider} provider not available")
+
+ prompt = f"""Extract RDF triples (subject-predicate-object) from the following text.
+
+Text: {text}
+
+Return JSON format: [{{"subject": "...", "predicate": "...", "object": "...", "confidence": 0.9}}]"""
+
+ try:
+ result = llm.generate_structured(prompt)
+ triples = []
+
+ if isinstance(result, list):
+ for item in result:
+ triples.append(Triple(
+ subject=item.get("subject", ""),
+ predicate=item.get("predicate", ""),
+ object=item.get("object", ""),
+ confidence=item.get("confidence", 0.9),
+ metadata={"provider": provider, "model": model, "extraction_method": "llm"}
+ ))
+
+ return triples
+ except Exception as e:
+ logger.error(f"LLM triple extraction failed: {e}")
+ return []
+
+
+# ============================================================================
+# Method Dispatchers
+# ============================================================================
+
+def get_entity_method(method_name: str):
+ """Get entity extraction method - checks registry for custom methods."""
+ # Check registry first
+ custom_method = method_registry.get("entity", method_name)
+ if custom_method:
+ return custom_method
+
+ # Built-in methods
+ builtin = {
+ "pattern": extract_entities_pattern,
+ "regex": extract_entities_regex,
+ "rules": extract_entities_rules,
+ "ml": extract_entities_ml,
+ "huggingface": extract_entities_huggingface,
+ "llm": extract_entities_llm,
+ }
+
+ method_func = builtin.get(method_name)
+ if not method_func:
+ raise ValueError(f"Unknown method: {method_name}. Register custom method or use built-in: {list(builtin.keys())}")
+
+ return method_func
+
+
+def get_relation_method(method_name: str):
+ """Get relation extraction method - checks registry for custom methods."""
+ # Check registry first
+ custom_method = method_registry.get("relation", method_name)
+ if custom_method:
+ return custom_method
+
+ # Built-in methods
+ builtin = {
+ "pattern": extract_relations_pattern,
+ "regex": extract_relations_regex,
+ "cooccurrence": extract_relations_cooccurrence,
+ "dependency": extract_relations_dependency,
+ "huggingface": extract_relations_huggingface,
+ "llm": extract_relations_llm,
+ }
+
+ method_func = builtin.get(method_name)
+ if not method_func:
+ raise ValueError(f"Unknown method: {method_name}. Register custom method or use built-in: {list(builtin.keys())}")
+
+ return method_func
+
+
+def get_triple_method(method_name: str):
+ """Get triple extraction method - checks registry for custom methods."""
+ # Check registry first
+ custom_method = method_registry.get("triple", method_name)
+ if custom_method:
+ return custom_method
+
+ # Built-in methods
+ builtin = {
+ "pattern": extract_triples_pattern,
+ "rules": extract_triples_rules,
+ "huggingface": extract_triples_huggingface,
+ "llm": extract_triples_llm,
+ }
+
+ method_func = builtin.get(method_name)
+ if not method_func:
+ raise ValueError(f"Unknown method: {method_name}. Register custom method or use built-in: {list(builtin.keys())}")
+
+ return method_func
+
diff --git a/semantica/semantic_extract/named_entity_recognizer.py b/semantica/semantic_extract/named_entity_recognizer.py
index c5eac53a..1c15930c 100644
--- a/semantica/semantic_extract/named_entity_recognizer.py
+++ b/semantica/semantic_extract/named_entity_recognizer.py
@@ -3,7 +3,22 @@ Named Entity Recognition Module
This module provides comprehensive named entity recognition capabilities for
extracting and classifying entities from text with confidence scoring and
-custom type support.
+custom type support. Uses NERExtractor internally with method parameter support.
+
+Supported Methods (passed to NERExtractor):
+ - "pattern": Pattern-based extraction using simple regex patterns
+ - "regex": Advanced regex-based extraction with custom patterns
+ - "rules": Rule-based extraction using linguistic rules
+ - "ml": ML-based extraction using spaCy (default)
+ - "huggingface": Custom HuggingFace NER models
+ - "llm": LLM-based extraction using various providers (OpenAI, Gemini, Groq, etc.)
+
+Algorithms Used:
+ - Entity Classification: Rule-based and ML-based entity type classification
+ - Confidence Scoring: Statistical and model-based confidence calculation
+ - Entity Disambiguation: Context-aware entity disambiguation algorithms
+ - Batch Processing: Parallel and sequential batch processing algorithms
+ - Custom Entity Detection: Pattern-based custom entity type detection
Key Features:
- Multi-type entity recognition (PERSON, ORG, GPE, DATE, etc.)
@@ -51,15 +66,25 @@ class NamedEntityRecognizer:
• Processes batch text collections
"""
- def __init__(self, config=None, **kwargs):
- """Initialize named entity recognizer."""
+ def __init__(self, method=None, config=None, **kwargs):
+ """
+ Initialize named entity recognizer.
+
+ Args:
+ method: Extraction method(s) - passed to NERExtractor
+ config: Legacy config dict (deprecated, use kwargs)
+ **kwargs: Configuration options passed to NERExtractor
+ """
self.logger = get_logger("named_entity_recognizer")
self.config = config or {}
self.config.update(kwargs)
self.progress_tracker = get_progress_tracker()
# Use NERExtractor for actual extraction
- self.ner_extractor = NERExtractor(**self.config.get("ner", {}))
+ ner_config = self.config.get("ner", {})
+ if method is not None:
+ ner_config["method"] = method
+ self.ner_extractor = NERExtractor(**ner_config, **self.config)
self.entity_classifier = EntityClassifier(**self.config.get("classifier", {}))
self.confidence_scorer = EntityConfidenceScorer(**self.config.get("scorer", {}))
diff --git a/semantica/semantic_extract/ner_extractor.py b/semantica/semantic_extract/ner_extractor.py
index c66fc564..95e932e8 100644
--- a/semantica/semantic_extract/ner_extractor.py
+++ b/semantica/semantic_extract/ner_extractor.py
@@ -1,37 +1,76 @@
"""
Named Entity Recognition Extractor Module
-This module provides core NER capabilities using spaCy and transformers for
-entity identification and classification, with fallback pattern-based extraction.
+This module provides comprehensive NER capabilities with multiple extraction methods,
+ranging from simple pattern matching to advanced LLM-based extraction, with support
+for fallback chains and ensemble voting.
+
+Supported Methods:
+ - "pattern": Pattern-based extraction using simple regex patterns
+ - "regex": Advanced regex-based extraction with custom patterns
+ - "rules": Rule-based extraction using linguistic rules
+ - "ml": ML-based extraction using spaCy (default)
+ - "huggingface": Custom HuggingFace NER models
+ - "llm": LLM-based extraction using various providers (OpenAI, Gemini, Groq, etc.)
+
+Algorithms Used:
+ - Regular Expression Matching: Pattern matching using finite automata
+ - Rule-based Extraction: Linguistic rule application and pattern matching
+ - Neural Named Entity Recognition: spaCy's CNN/Transformer-based NER models
+ - 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
Key Features:
- - spaCy-based entity extraction
- - Pattern-based fallback extraction
- - Multiple entity type support
- - Confidence scoring
- - Batch processing
- - Entity filtering by confidence
+ - Multiple extraction methods:
+ * Pattern-based: Simple regex pattern matching
+ * Regex-based: Advanced regex with custom patterns
+ * Rules-based: Linguistic rule-based extraction
+ * ML-based: spaCy-based machine learning extraction (default)
+ * HuggingFace: Custom HuggingFace NER models
+ * LLM-based: Large language model extraction
+ - Fallback chain support: Try methods in order until one succeeds
+ - Ensemble voting: Combine results from multiple methods
+ - Post-processing: Entity boundary validation and deduplication
+ - Multiple entity type support (PERSON, ORG, GPE, DATE, etc.)
+ - Confidence scoring and filtering
+ - Batch processing capabilities
+ - Entity classification and grouping
Main Classes:
- - NERExtractor: Core NER extractor
+ - NERExtractor: Core NER extractor with method selection
- Entity: Entity representation dataclass
Example Usage:
>>> from semantica.semantic_extract import NERExtractor
- >>> extractor = NERExtractor(model="en_core_web_sm")
+ >>> # Using ML method (default)
+ >>> extractor = NERExtractor(method="ml", model="en_core_web_sm")
+ >>> entities = extractor.extract_entities("Apple Inc. was founded in 1976.")
+ >>>
+ >>> # Using LLM method
+ >>> extractor = NERExtractor(method="llm", provider="openai", llm_model="gpt-4")
+ >>> entities = extractor.extract_entities("Apple Inc. was founded in 1976.")
+ >>>
+ >>> # Using HuggingFace model
+ >>> extractor = NERExtractor(method="huggingface", huggingface_model="dslim/bert-base-NER")
+ >>> entities = extractor.extract_entities("Apple Inc. was founded in 1976.")
+ >>>
+ >>> # Using fallback chain
+ >>> extractor = NERExtractor(method=["llm", "ml", "pattern"], ensemble_voting=True)
>>> 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
-from typing import Any, Dict, List, Optional, Tuple
+from typing import Any, Dict, List, Optional, Tuple, Union
from ..utils.exceptions import ProcessingError
from ..utils.logging import get_logger
from ..utils.progress_tracker import get_progress_tracker
+from .methods import get_entity_method
try:
import spacy
@@ -55,31 +94,49 @@ class Entity:
class NERExtractor:
"""Named Entity Recognition extractor."""
- def __init__(self, **config):
+ def __init__(self, method: Union[str, List[str]] = "ml", **config):
"""
Initialize NER extractor.
Args:
+ method: Extraction method(s). Can be:
+ - "pattern": Pattern-based extraction
+ - "regex": Regex-based extraction
+ - "rules": Rule-based extraction
+ - "ml": ML-based (spaCy) - default
+ - "huggingface": HuggingFace model
+ - "llm": LLM-based extraction
+ - List of methods for fallback chain
**config: Configuration options:
- - model: Model name (default: "en_core_web_sm")
- - language: Language code (default: "en")
+ - model: Model name (for ML/HuggingFace methods)
+ - huggingface_model: HuggingFace model name
+ - provider: LLM provider (for LLM method)
+ - llm_model: LLM model name
+ - device: Device for HuggingFace models ("cuda" or "cpu")
- min_confidence: Minimum confidence threshold
+ - ensemble_voting: Enable ensemble voting (default: False)
+ - post_process: Enable post-processing (default: False)
"""
self.logger = get_logger("ner_extractor")
self.config = config
+ # Method configuration
+ self.method = method if isinstance(method, list) else [method]
self.model_name = config.get("model", "en_core_web_sm")
+ self.huggingface_model = config.get("huggingface_model", config.get("model", "dslim/bert-base-NER"))
self.language = config.get("language", "en")
self.min_confidence = config.get("min_confidence", 0.5)
+ self.ensemble_voting = config.get("ensemble_voting", False)
+ self.post_process = config.get("post_process", False)
self.progress_tracker = get_progress_tracker()
- # Initialize spaCy model if available
+ # Initialize spaCy model if ML method is used
self.nlp = None
- if SPACY_AVAILABLE:
+ if "ml" in self.method and SPACY_AVAILABLE:
try:
self.nlp = spacy.load(self.model_name)
except OSError:
- self.logger.warning(f"spaCy model {self.model_name} not found. NER capabilities limited.")
+ self.logger.warning(f"spaCy model {self.model_name} not found. ML method will fallback.")
def extract_entities(self, text: str, **options) -> List[Entity]:
"""
@@ -90,6 +147,7 @@ class NERExtractor:
**options: Extraction options:
- entity_types: Filter by entity types (list)
- min_confidence: Minimum confidence threshold
+ - method: Override method (if not set in __init__)
Returns:
list: List of extracted entities
@@ -105,15 +163,64 @@ class NERExtractor:
self.progress_tracker.stop_tracking(tracking_id, status="completed", message="No text provided")
return []
+ # Use method from options if provided, otherwise use instance method
+ methods = options.get("method", self.method)
+ if isinstance(methods, str):
+ methods = [methods]
+
min_confidence = options.get("min_confidence", self.min_confidence)
entity_types = options.get("entity_types")
- if self.nlp:
- self.progress_tracker.update_tracking(tracking_id, message="Extracting entities using spaCy...")
- entities = self._extract_with_spacy(text, min_confidence, entity_types)
+ # Merge config with options
+ all_options = {**self.config, **options}
+
+ # Try each method in order (fallback chain)
+ all_entities = []
+ for method_name in methods:
+ try:
+ self.progress_tracker.update_tracking(tracking_id, message=f"Extracting entities using {method_name}...")
+ method_func = get_entity_method(method_name)
+
+ # Prepare method-specific options
+ method_options = all_options.copy()
+ if method_name == "huggingface":
+ method_options["model"] = all_options.get("huggingface_model", self.huggingface_model)
+ method_options["device"] = all_options.get("device")
+ elif method_name == "llm":
+ method_options["provider"] = all_options.get("provider", "openai")
+ method_options["model"] = all_options.get("llm_model", all_options.get("model"))
+
+ entities = method_func(text, **method_options)
+
+ # Filter by confidence and entity types
+ filtered = [e for e in entities if e.confidence >= min_confidence]
+ if entity_types:
+ filtered = [e for e in filtered if e.label in entity_types]
+
+ if filtered:
+ all_entities.append((method_name, filtered))
+
+ # If not using ensemble, return first successful result
+ if not self.ensemble_voting:
+ self.progress_tracker.stop_tracking(tracking_id, status="completed",
+ message=f"Extracted {len(filtered)} entities using {method_name}")
+ return filtered
+
+ except Exception as e:
+ self.logger.warning(f"Method {method_name} failed: {e}")
+ continue
+
+ # Ensemble voting if enabled
+ if self.ensemble_voting and len(all_entities) > 1:
+ entities = self._vote_entities([entities for _, entities in all_entities])
+ elif all_entities:
+ entities = all_entities[0][1] # Use first successful method
else:
- self.progress_tracker.update_tracking(tracking_id, message="Extracting entities using fallback method...")
- entities = self._extract_fallback(text)
+ entities = []
+
+ # Post-processing if enabled
+ if self.post_process and entities:
+ entities = self._post_process_entities(entities, text)
self.progress_tracker.stop_tracking(tracking_id, status="completed",
message=f"Extracted {len(entities)} entities")
@@ -123,6 +230,63 @@ class NERExtractor:
self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))
raise
+ def _vote_entities(self, results: List[List[Entity]], threshold: float = 0.5) -> List[Entity]:
+ """Vote on entities across methods."""
+ entity_counts = {}
+ total_methods = len(results)
+
+ for entities in results:
+ for entity in entities:
+ key = (entity.text.lower(), entity.label)
+ if key not in entity_counts:
+ entity_counts[key] = {
+ "entity": entity,
+ "score": 0.0,
+ "count": 0
+ }
+ entity_counts[key]["score"] += entity.confidence
+ entity_counts[key]["count"] += 1
+
+ # Return entities that meet threshold
+ voted = []
+ for key, data in entity_counts.items():
+ avg_score = data["score"] / data["count"]
+ if avg_score >= threshold:
+ entity = data["entity"]
+ entity.confidence = avg_score
+ voted.append(entity)
+
+ return voted
+
+ 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():
+ # Try to find correct boundaries
+ start = text.lower().find(entity.text.lower(), max(0, entity.start_char - 10))
+ if start >= 0:
+ entity.start_char = start
+ entity.end_char = start + len(entity.text)
+
+ processed.append(entity)
+
+ return processed
+
def _extract_with_spacy(self, text: str, min_confidence: float, entity_types: Optional[List[str]]) -> List[Entity]:
"""Extract entities using spaCy."""
entities = []
diff --git a/semantica/semantic_extract/providers.py b/semantica/semantic_extract/providers.py
new file mode 100644
index 00000000..7647f14c
--- /dev/null
+++ b/semantica/semantic_extract/providers.py
@@ -0,0 +1,585 @@
+"""
+LLM Providers and Model Loaders Module
+
+This module provides a unified interface for all LLM providers and HuggingFace model
+loaders, enabling seamless integration with multiple language model services and
+custom HuggingFace models for semantic extraction tasks.
+
+Supported Providers:
+ - "openai": OpenAI API (GPT-3.5, GPT-4, etc.)
+ - "gemini": Google Gemini API (gemini-pro, etc.)
+ - "groq": Groq API (llama2, mixtral, etc.)
+ - "anthropic": Anthropic Claude API (claude-3-sonnet, etc.)
+ - "ollama": Ollama local provider (local open-source models)
+ - "huggingface_llm": HuggingFace Transformers for LLM tasks
+
+Supported Model Types:
+ - NER Models: Token classification models for named entity recognition
+ - Relation Models: Sequence classification models for relation extraction
+ - Triplet Models: Seq2Seq models for triple extraction
+
+Algorithms Used:
+ - Transformer Architecture: Attention mechanism-based neural networks
+ - Token Classification: BERT, RoBERTa, DistilBERT for NER tasks
+ - Sequence Classification: Transformer encoders for relation classification
+ - Sequence-to-Sequence: Encoder-decoder transformers for triplet generation
+ - Autoregressive Generation: GPT-style models for text generation
+ - API Integration: RESTful API communication and JSON parsing
+ - Model Caching: LRU cache and memory management for model loading
+ - Device Management: CPU/GPU allocation and tensor operations
+
+Key Features:
+ - Unified provider interface for all LLM services
+ - Support for multiple LLM providers:
+ * OpenAI (GPT-3.5, GPT-4, etc.)
+ * Google Gemini (gemini-pro, etc.)
+ * Groq (llama2, mixtral, etc.)
+ * Anthropic Claude (claude-3-sonnet, etc.)
+ * Ollama (local open-source models)
+ * HuggingFace Transformers (custom LLM models)
+ - HuggingFace model loader for NER, relation extraction, and triple extraction
+ - Automatic API key management from environment variables
+ - Structured JSON output generation
+ - Model caching and device management (CPU/GPU)
+ - Graceful fallback when providers are unavailable
+ - Custom provider registration support
+
+Main Classes:
+ - BaseProvider: Abstract base class for all providers
+ - OpenAIProvider: OpenAI API provider implementation
+ - GeminiProvider: Google Gemini API provider implementation
+ - GroqProvider: Groq API provider implementation
+ - AnthropicProvider: Anthropic Claude API provider implementation
+ - OllamaProvider: Ollama local provider implementation
+ - HuggingFaceLLMProvider: HuggingFace transformers for LLM tasks
+ - HuggingFaceModelLoader: Loader for HuggingFace models (NER, RE, TE)
+
+Functions:
+ - create_provider: Factory function to create provider instances
+
+Example Usage:
+ >>> from semantica.semantic_extract.providers import create_provider
+ >>> provider = create_provider("openai", model="gpt-4")
+ >>> response = provider.generate("Extract entities from: Apple Inc. was founded in 1976.")
+ >>>
+ >>> loader = HuggingFaceModelLoader(device="cuda")
+ >>> ner_model = loader.load_ner_model("dslim/bert-base-NER")
+
+Author: Semantica Contributors
+License: MIT
+"""
+
+import os
+import json
+from typing import Any, Dict, List, Optional
+import torch
+
+from ..utils.exceptions import ProcessingError
+from ..utils.logging import get_logger
+from .config import config
+from .registry import provider_registry
+
+
+class BaseProvider:
+ """Base class for providers - makes it easy to add custom providers."""
+
+ def __init__(self, **kwargs):
+ """Initialize provider."""
+ self.config = kwargs
+ self.logger = get_logger(f"provider_{self.__class__.__name__}")
+
+ def is_available(self) -> bool:
+ """Check if provider is available."""
+ return True
+
+ def generate(self, prompt: str, **kwargs) -> str:
+ """Generate text - must be implemented."""
+ raise NotImplementedError
+
+ def generate_structured(self, prompt: str, **kwargs) -> dict:
+ """Generate structured output - must be implemented."""
+ raise NotImplementedError
+
+
+class OpenAIProvider(BaseProvider):
+ """OpenAI provider implementation."""
+
+ def __init__(self, api_key: Optional[str] = None, model: str = "gpt-3.5-turbo", **kwargs):
+ """Initialize OpenAI provider."""
+ super().__init__(**kwargs)
+ self.api_key = api_key or config.get_api_key("openai")
+ self.model = model
+ self.client = None
+ self._init_client()
+
+ def _init_client(self):
+ """Initialize OpenAI client."""
+ try:
+ from openai import OpenAI
+ if self.api_key:
+ self.client = OpenAI(api_key=self.api_key)
+ except ImportError:
+ self.client = None
+ self.logger.warning("openai library not installed. Install with: pip install semantica[llm-openai]")
+
+ def is_available(self) -> bool:
+ """Check if provider is available."""
+ return self.client is not None
+
+ def generate(self, prompt: str, **kwargs) -> str:
+ """Generate text from prompt."""
+ if not self.client:
+ raise ProcessingError("OpenAI client not initialized. Set OPENAI_API_KEY or pass api_key.")
+
+ response = self.client.chat.completions.create(
+ model=kwargs.get("model", self.model),
+ messages=[{"role": "user", "content": prompt}],
+ temperature=kwargs.get("temperature", 0.3)
+ )
+ return response.choices[0].message.content
+
+ def generate_structured(self, prompt: str, **kwargs) -> dict:
+ """Generate structured JSON output."""
+ if not self.client:
+ raise ProcessingError("OpenAI client not initialized.")
+
+ response = self.client.chat.completions.create(
+ model=kwargs.get("model", self.model),
+ messages=[{"role": "user", "content": prompt}],
+ response_format={"type": "json_object"},
+ temperature=kwargs.get("temperature", 0.3)
+ )
+ return json.loads(response.choices[0].message.content)
+
+
+class GeminiProvider(BaseProvider):
+ """Google Gemini provider implementation."""
+
+ def __init__(self, api_key: Optional[str] = None, model: str = "gemini-pro", **kwargs):
+ """Initialize Gemini provider."""
+ super().__init__(**kwargs)
+ self.api_key = api_key or config.get_api_key("gemini")
+ self.model = model
+ self.client = None
+ self._init_client()
+
+ def _init_client(self):
+ """Initialize Gemini client."""
+ try:
+ import google.generativeai as genai
+ if self.api_key:
+ genai.configure(api_key=self.api_key)
+ self.client = genai.GenerativeModel(self.model)
+ except ImportError:
+ self.client = None
+ self.logger.warning("google-generativeai library not installed. Install with: pip install semantica[llm-gemini]")
+
+ def is_available(self) -> bool:
+ """Check if provider is available."""
+ return self.client is not None
+
+ def generate(self, prompt: str, **kwargs) -> str:
+ """Generate text from prompt."""
+ if not self.client:
+ raise ProcessingError("Gemini client not initialized. Set GEMINI_API_KEY or pass api_key.")
+
+ response = self.client.generate_content(
+ prompt,
+ generation_config={
+ "temperature": kwargs.get("temperature", 0.3)
+ }
+ )
+ return response.text
+
+ def generate_structured(self, prompt: str, **kwargs) -> dict:
+ """Generate structured output."""
+ if not self.client:
+ raise ProcessingError("Gemini client not initialized.")
+
+ # Add JSON format instruction to prompt
+ json_prompt = f"{prompt}\n\nReturn the response as valid JSON only."
+ response = self.client.generate_content(json_prompt)
+ try:
+ return json.loads(response.text)
+ except json.JSONDecodeError:
+ # Try to extract JSON from response
+ text = response.text
+ start = text.find('{')
+ end = text.rfind('}') + 1
+ if start >= 0 and end > start:
+ return json.loads(text[start:end])
+ raise ProcessingError("Failed to parse JSON from Gemini response")
+
+
+class GroqProvider(BaseProvider):
+ """Groq provider implementation."""
+
+ def __init__(self, api_key: Optional[str] = None, model: str = "llama2-70b-4096", **kwargs):
+ """Initialize Groq provider."""
+ super().__init__(**kwargs)
+ self.api_key = api_key or config.get_api_key("groq")
+ self.model = model
+ self.client = None
+ self._init_client()
+
+ def _init_client(self):
+ """Initialize Groq client."""
+ try:
+ from groq import Groq
+ if self.api_key:
+ self.client = Groq(api_key=self.api_key)
+ except ImportError:
+ self.client = None
+ self.logger.warning("groq library not installed. Install with: pip install semantica[llm-groq]")
+
+ def is_available(self) -> bool:
+ """Check if provider is available."""
+ return self.client is not None
+
+ def generate(self, prompt: str, **kwargs) -> str:
+ """Generate text from prompt."""
+ if not self.client:
+ raise ProcessingError("Groq client not initialized. Set GROQ_API_KEY or pass api_key.")
+
+ response = self.client.chat.completions.create(
+ model=kwargs.get("model", self.model),
+ messages=[{"role": "user", "content": prompt}],
+ temperature=kwargs.get("temperature", 0.3)
+ )
+ return response.choices[0].message.content
+
+ def generate_structured(self, prompt: str, **kwargs) -> dict:
+ """Generate structured output."""
+ if not self.client:
+ raise ProcessingError("Groq client not initialized.")
+
+ 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)
+ )
+ try:
+ return json.loads(response.choices[0].message.content)
+ except json.JSONDecodeError:
+ text = response.choices[0].message.content
+ start = text.find('{')
+ end = text.rfind('}') + 1
+ if start >= 0 and end > start:
+ return json.loads(text[start:end])
+ raise ProcessingError("Failed to parse JSON from Groq response")
+
+
+class AnthropicProvider(BaseProvider):
+ """Anthropic Claude provider implementation."""
+
+ def __init__(self, api_key: Optional[str] = None, model: str = "claude-3-sonnet-20240229", **kwargs):
+ """Initialize Anthropic provider."""
+ super().__init__(**kwargs)
+ self.api_key = api_key or config.get_api_key("anthropic")
+ self.model = model
+ self.client = None
+ self._init_client()
+
+ def _init_client(self):
+ """Initialize Anthropic client."""
+ try:
+ from anthropic import Anthropic
+ if self.api_key:
+ self.client = Anthropic(api_key=self.api_key)
+ except ImportError:
+ self.client = None
+ self.logger.warning("anthropic library not installed. Install with: pip install semantica[llm-anthropic]")
+
+ def is_available(self) -> bool:
+ """Check if provider is available."""
+ return self.client is not None
+
+ def generate(self, prompt: str, **kwargs) -> str:
+ """Generate text from prompt."""
+ if not self.client:
+ raise ProcessingError("Anthropic client not initialized. Set ANTHROPIC_API_KEY or pass api_key.")
+
+ response = self.client.messages.create(
+ model=kwargs.get("model", self.model),
+ max_tokens=kwargs.get("max_tokens", 4096),
+ messages=[{"role": "user", "content": prompt}]
+ )
+ return response.content[0].text
+
+ def generate_structured(self, prompt: str, **kwargs) -> dict:
+ """Generate structured output."""
+ if not self.client:
+ raise ProcessingError("Anthropic client not initialized.")
+
+ json_prompt = f"{prompt}\n\nReturn the response as valid JSON only."
+ response = self.client.messages.create(
+ model=kwargs.get("model", self.model),
+ max_tokens=kwargs.get("max_tokens", 4096),
+ messages=[{"role": "user", "content": json_prompt}]
+ )
+ try:
+ return json.loads(response.content[0].text)
+ except json.JSONDecodeError:
+ text = response.content[0].text
+ start = text.find('{')
+ end = text.rfind('}') + 1
+ if start >= 0 and end > start:
+ return json.loads(text[start:end])
+ raise ProcessingError("Failed to parse JSON from Anthropic response")
+
+
+class OllamaProvider(BaseProvider):
+ """Ollama local provider implementation."""
+
+ def __init__(self, base_url: str = "http://localhost:11434", model: str = "llama2", **kwargs):
+ """Initialize Ollama provider."""
+ super().__init__(**kwargs)
+ self.base_url = base_url
+ self.model = model
+ self.client = None
+ self._init_client()
+
+ def _init_client(self):
+ """Initialize Ollama client."""
+ try:
+ import ollama
+ self.client = ollama
+ # Test connection
+ try:
+ self.client.list() # Test if Ollama is running
+ except Exception:
+ self.client = None
+ self.logger.warning("Ollama server not accessible. Make sure Ollama is running.")
+ except ImportError:
+ self.client = None
+ self.logger.warning("ollama library not installed. Install with: pip install semantica[llm-ollama]")
+
+ def is_available(self) -> bool:
+ """Check if provider is available."""
+ return self.client is not None
+
+ def generate(self, prompt: str, **kwargs) -> str:
+ """Generate text from prompt."""
+ if not self.client:
+ raise ProcessingError("Ollama client not initialized. Make sure Ollama is running.")
+
+ response = self.client.generate(
+ model=kwargs.get("model", self.model),
+ prompt=prompt,
+ options={
+ "temperature": kwargs.get("temperature", 0.3)
+ }
+ )
+ return response.get("response", "")
+
+ def generate_structured(self, prompt: str, **kwargs) -> dict:
+ """Generate structured output."""
+ if not self.client:
+ raise ProcessingError("Ollama client not initialized.")
+
+ json_prompt = f"{prompt}\n\nReturn the response as valid JSON only."
+ response = self.client.generate(
+ model=kwargs.get("model", self.model),
+ prompt=json_prompt,
+ options={
+ "temperature": kwargs.get("temperature", 0.3)
+ }
+ )
+ try:
+ return json.loads(response.get("response", "{}"))
+ except json.JSONDecodeError:
+ text = response.get("response", "")
+ start = text.find('{')
+ end = text.rfind('}') + 1
+ if start >= 0 and end > start:
+ return json.loads(text[start:end])
+ raise ProcessingError("Failed to parse JSON from Ollama response")
+
+
+class HuggingFaceLLMProvider(BaseProvider):
+ """HuggingFace transformers for LLM tasks."""
+
+ def __init__(self, model_name: str = "gpt2", device: Optional[str] = None, **kwargs):
+ """Initialize HuggingFace LLM provider."""
+ super().__init__(**kwargs)
+ self.model_name = model_name
+ self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
+ self.model = None
+ self.tokenizer = None
+ self._init_model()
+
+ def _init_model(self):
+ """Initialize HuggingFace model."""
+ try:
+ from transformers import AutoTokenizer, AutoModelForCausalLM
+
+ self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
+ self.model = AutoModelForCausalLM.from_pretrained(self.model_name)
+ self.model.to(self.device)
+ self.model.eval()
+ except ImportError:
+ self.logger.warning("transformers library not installed. Install with: pip install semantica[models-huggingface]")
+ except Exception as e:
+ self.logger.warning(f"Failed to load HuggingFace model {self.model_name}: {e}")
+ self.model = None
+
+ def is_available(self) -> bool:
+ """Check if provider is available."""
+ return self.model is not None and self.tokenizer is not None
+
+ def generate(self, prompt: str, **kwargs) -> str:
+ """Generate text from prompt."""
+ if not self.model or not self.tokenizer:
+ raise ProcessingError("HuggingFace model not initialized.")
+
+ inputs = self.tokenizer.encode(prompt, return_tensors="pt").to(self.device)
+ outputs = self.model.generate(
+ inputs,
+ max_length=kwargs.get("max_length", 100),
+ temperature=kwargs.get("temperature", 0.7),
+ do_sample=True
+ )
+ generated_text = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
+ # Remove the original prompt from the response
+ return generated_text[len(prompt):].strip()
+
+ def generate_structured(self, prompt: str, **kwargs) -> dict:
+ """Generate structured output."""
+ response = self.generate(prompt, **kwargs)
+ try:
+ return json.loads(response)
+ except json.JSONDecodeError:
+ start = response.find('{')
+ end = response.rfind('}') + 1
+ if start >= 0 and end > start:
+ return json.loads(response[start:end])
+ raise ProcessingError("Failed to parse JSON from HuggingFace response")
+
+
+class HuggingFaceModelLoader:
+ """HuggingFace model loader for NER, RE, Triplets."""
+
+ def __init__(self, device: Optional[str] = None):
+ """Initialize HuggingFace model loader."""
+ self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
+ self._cache: Dict[str, Any] = {}
+ self.logger = get_logger("huggingface_loader")
+
+ def load_ner_model(self, model_name: str, **kwargs):
+ """Load NER model."""
+ cache_key = f"{model_name}_ner"
+ if cache_key in self._cache:
+ return self._cache[cache_key]
+
+ try:
+ from transformers import pipeline
+
+ nlp = pipeline(
+ "ner",
+ model=model_name,
+ device=self.device if torch.cuda.is_available() else -1,
+ aggregation_strategy="simple"
+ )
+ self._cache[cache_key] = nlp
+ return nlp
+ except ImportError:
+ raise ImportError("transformers library not installed. Install with: pip install semantica[models-huggingface]")
+ except Exception as e:
+ self.logger.error(f"Failed to load NER model {model_name}: {e}")
+ raise
+
+ def load_relation_model(self, model_name: str, **kwargs):
+ """Load relation extraction model."""
+ cache_key = f"{model_name}_relation"
+ if cache_key in self._cache:
+ return self._cache[cache_key]
+
+ try:
+ from transformers import pipeline
+
+ nlp = pipeline(
+ "text-classification",
+ model=model_name,
+ device=self.device if torch.cuda.is_available() else -1
+ )
+ self._cache[cache_key] = nlp
+ return nlp
+ except ImportError:
+ raise ImportError("transformers library not installed. Install with: pip install semantica[models-huggingface]")
+ except Exception as e:
+ self.logger.error(f"Failed to load relation model {model_name}: {e}")
+ raise
+
+ def load_triplet_model(self, model_name: str, **kwargs):
+ """Load triplet extraction model."""
+ cache_key = f"{model_name}_triplet"
+ if cache_key in self._cache:
+ return self._cache[cache_key]
+
+ try:
+ from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM
+
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
+ model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
+ model.to(self.device)
+
+ nlp = {
+ "tokenizer": tokenizer,
+ "model": model,
+ "device": self.device
+ }
+ self._cache[cache_key] = nlp
+ return nlp
+ except ImportError:
+ raise ImportError("transformers library not installed. Install with: pip install semantica[models-huggingface]")
+ except Exception as e:
+ self.logger.error(f"Failed to load triplet model {model_name}: {e}")
+ raise
+
+ def extract_entities(self, model, text: str) -> List[Dict]:
+ """Extract entities using loaded model."""
+ return model(text)
+
+ def extract_relations(self, model, text: str, entities: List) -> List[Dict]:
+ """Extract relations using loaded model."""
+ # This would need to be customized based on the model architecture
+ return model(text)
+
+ def extract_triplets(self, model, text: str) -> List[Dict]:
+ """Extract triplets using loaded model."""
+ tokenizer = model["tokenizer"]
+ model_obj = model["model"]
+ device = model["device"]
+
+ inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=512).to(device)
+ outputs = model_obj.generate(**inputs, max_length=128)
+ decoded = tokenizer.decode(outputs[0], skip_special_tokens=True)
+
+ # Parse decoded output (format depends on model)
+ # This is a placeholder - actual parsing would depend on model output format
+ return [{"triplet": decoded}]
+
+
+def create_provider(name: str, **kwargs) -> BaseProvider:
+ """Create provider - checks registry for custom providers."""
+ # Check registry first
+ custom_provider = provider_registry.get(name)
+ if custom_provider:
+ return custom_provider(**kwargs)
+
+ # Built-in providers
+ builtin = {
+ "openai": OpenAIProvider,
+ "gemini": GeminiProvider,
+ "groq": GroqProvider,
+ "anthropic": AnthropicProvider,
+ "ollama": OllamaProvider,
+ "huggingface_llm": HuggingFaceLLMProvider,
+ }
+
+ provider_class = builtin.get(name.lower())
+ if not provider_class:
+ raise ValueError(f"Unknown provider: {name}. Register custom provider or use built-in: {list(builtin.keys())}")
+
+ return provider_class(**kwargs)
diff --git a/semantica/semantic_extract/registry.py b/semantica/semantic_extract/registry.py
new file mode 100644
index 00000000..4f1ff493
--- /dev/null
+++ b/semantica/semantic_extract/registry.py
@@ -0,0 +1,119 @@
+"""
+Plugin Registry Module
+
+This module provides a plugin registry system for registering custom LLM providers
+and extraction methods, enabling extensibility and community contributions to the
+semantic extraction toolkit.
+
+Supported Registration Types:
+ - Provider Registry: Register custom LLM providers
+ - Method Registry: Register custom extraction methods for:
+ * "entity": Entity extraction methods
+ * "relation": Relation extraction methods
+ * "triple": Triple extraction methods
+ * "event": Event extraction methods
+ * "coreference": Coreference resolution methods
+
+Algorithms Used:
+ - Registry Pattern: Dictionary-based registration and lookup
+ - Dynamic Registration: Runtime class and function registration
+ - Type Checking: Type validation for registered components
+ - Lookup Algorithms: Hash-based O(1) lookup for providers and methods
+ - Task-based Organization: Hierarchical organization by task type
+
+Key Features:
+ - Provider registry for custom LLM providers
+ - Method registry for custom extraction methods
+ - Task-based method organization (entity, relation, triple, event, coreference)
+ - Dynamic registration and unregistration
+ - Easy discovery of available providers and methods
+ - Support for community-contributed extensions
+
+Main Classes:
+ - ProviderRegistry: Registry for custom LLM providers
+ - MethodRegistry: Registry for custom extraction methods
+
+Global Instances:
+ - provider_registry: Global provider registry instance
+ - method_registry: Global method registry instance
+
+Example Usage:
+ >>> from semantica.semantic_extract.registry import provider_registry, method_registry
+ >>> provider_registry.register("custom_provider", CustomProviderClass)
+ >>> method_registry.register("entity", "custom_method", custom_extract_function)
+ >>> available = method_registry.list_all("entity")
+
+Author: Semantica Contributors
+License: MIT
+"""
+
+from typing import Dict, Type, Callable, Any, List, Optional
+
+
+class ProviderRegistry:
+ """Registry for custom LLM providers."""
+
+ _providers: Dict[str, Type] = {}
+
+ @classmethod
+ def register(cls, name: str, provider_class: Type):
+ """Register a custom provider."""
+ cls._providers[name] = provider_class
+
+ @classmethod
+ def get(cls, name: str) -> Optional[Type]:
+ """Get provider by name."""
+ return cls._providers.get(name)
+
+ @classmethod
+ def list_all(cls) -> List[str]:
+ """List all registered providers."""
+ return list(cls._providers.keys())
+
+ @classmethod
+ def unregister(cls, name: str):
+ """Unregister a provider."""
+ if name in cls._providers:
+ del cls._providers[name]
+
+
+class MethodRegistry:
+ """Registry for custom extraction methods."""
+
+ _methods: Dict[str, Dict[str, Callable]] = {
+ "entity": {},
+ "relation": {},
+ "triple": {},
+ "event": {},
+ "coreference": {},
+ }
+
+ @classmethod
+ def register(cls, task: str, name: str, method_func: Callable):
+ """Register a custom extraction method."""
+ if task not in cls._methods:
+ cls._methods[task] = {}
+ cls._methods[task][name] = method_func
+
+ @classmethod
+ def get(cls, task: str, name: str) -> Optional[Callable]:
+ """Get method by task and name."""
+ return cls._methods.get(task, {}).get(name)
+
+ @classmethod
+ def list_all(cls, task: Optional[str] = None) -> Dict[str, List[str]]:
+ """List all registered methods."""
+ if task:
+ return {task: list(cls._methods.get(task, {}).keys())}
+ return {t: list(m.keys()) for t, m in cls._methods.items()}
+
+ @classmethod
+ def unregister(cls, task: str, name: str):
+ """Unregister a method."""
+ if task in cls._methods and name in cls._methods[task]:
+ del cls._methods[task][name]
+
+
+# Global registries
+provider_registry = ProviderRegistry()
+method_registry = MethodRegistry()
diff --git a/semantica/semantic_extract/relation_extractor.py b/semantica/semantic_extract/relation_extractor.py
index ee66eb72..e657eaee 100644
--- a/semantica/semantic_extract/relation_extractor.py
+++ b/semantica/semantic_extract/relation_extractor.py
@@ -2,26 +2,61 @@
Relation Extraction Module
This module provides comprehensive relationship detection and extraction
-between entities in text documents using pattern matching and co-occurrence analysis.
+between entities in text documents using multiple extraction methods, from
+pattern matching to advanced LLM-based extraction.
+
+Supported Methods:
+ - "pattern": Pattern-based extraction using common relation patterns (default)
+ - "regex": Advanced regex-based relation extraction
+ - "cooccurrence": Co-occurrence based relation detection (proximity-based)
+ - "dependency": Dependency parsing-based extraction using spaCy
+ - "huggingface": Custom HuggingFace relation extraction models
+ - "llm": LLM-based relation extraction using various providers
+
+Algorithms Used:
+ - Pattern Matching: Regular expression and string pattern matching
+ - Co-occurrence Analysis: Proximity-based entity co-occurrence detection
+ - Dependency Parsing: Transition-based or graph-based dependency parsing
+ - 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
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
+ - Multiple extraction methods:
+ * Pattern-based: Pattern matching for common relations (default)
+ * Regex-based: Advanced regex relation extraction
+ * Co-occurrence: Proximity-based relation detection
+ * Dependency: Dependency parsing-based extraction
+ * HuggingFace: Custom HuggingFace relation models
+ * LLM-based: LLM-powered relation extraction
+ - Fallback chain support: Try methods in order until one succeeds
+ - Multiple relation types (founded_by, located_in, works_for, born_in, etc.)
+ - Relation classification and grouping
+ - Relation validation and consistency checking
+ - Context extraction for each relation
+ - Confidence scoring and filtering
Main Classes:
- - RelationExtractor: Main relation extractor
+ - RelationExtractor: Main relation extractor with method selection
- Relation: Relation representation dataclass
Example Usage:
>>> from semantica.semantic_extract import RelationExtractor
- >>> extractor = RelationExtractor()
+ >>> # Using pattern method (default)
+ >>> extractor = RelationExtractor(method="pattern")
+ >>> relations = extractor.extract_relations("Apple was founded by Steve Jobs.", entities)
+ >>>
+ >>> # Using dependency parsing
+ >>> extractor = RelationExtractor(method="dependency", model="en_core_web_sm")
+ >>> relations = extractor.extract_relations("Apple was founded by Steve Jobs.", entities)
+ >>>
+ >>> # Using LLM method
+ >>> extractor = RelationExtractor(method="llm", provider="openai", llm_model="gpt-4")
+ >>> relations = extractor.extract_relations("Apple was founded by Steve Jobs.", entities)
+ >>>
+ >>> # Using fallback chain
+ >>> extractor = RelationExtractor(method=["llm", "dependency", "pattern"])
>>> 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
@@ -29,12 +64,13 @@ License: MIT
import re
from dataclasses import dataclass, field
-from typing import Any, Dict, List, Optional, Tuple
+from typing import Any, Dict, List, Optional, Tuple, Union
from ..utils.exceptions import ProcessingError
from ..utils.logging import get_logger
from ..utils.progress_tracker import get_progress_tracker
from .ner_extractor import Entity
+from .methods import get_relation_method
@dataclass
@@ -52,21 +88,36 @@ class Relation:
class RelationExtractor:
"""Relation extractor for entity relationships."""
- def __init__(self, **config):
+ def __init__(self, method: Union[str, List[str]] = "pattern", **config):
"""
Initialize relation extractor.
Args:
+ method: Extraction method(s). Can be:
+ - "pattern": Pattern-based extraction (default)
+ - "regex": Regex-based extraction
+ - "cooccurrence": Co-occurrence based
+ - "dependency": Dependency parsing based
+ - "huggingface": HuggingFace model
+ - "llm": LLM-based extraction
+ - List of methods for fallback chain
**config: Configuration options:
+ - model: Model name (for dependency/HuggingFace methods)
+ - huggingface_model: HuggingFace model name
+ - provider: LLM provider (for LLM method)
+ - llm_model: LLM model name
+ - device: Device for HuggingFace models
- min_confidence: Minimum confidence threshold
- - use_llm: Use LLM for relation extraction (default: False)
+ - validate: Enable validation (default: False)
"""
self.logger = get_logger("relation_extractor")
self.config = config
self.progress_tracker = get_progress_tracker()
+ # Method configuration
+ self.method = method if isinstance(method, list) else [method]
self.min_confidence = config.get("min_confidence", 0.5)
- self.use_llm = config.get("use_llm", False)
+ self.validate = config.get("validate", False)
# Common relation patterns
self.relation_patterns = {
@@ -95,8 +146,11 @@ class RelationExtractor:
Args:
text: Input text
entities: List of extracted entities
- **options: Extraction options
-
+ **options: Extraction options:
+ - method: Override method (if not set in __init__)
+ - min_confidence: Minimum confidence threshold
+ - validate: Enable validation
+
Returns:
list: List of extracted relations
"""
@@ -111,15 +165,65 @@ class RelationExtractor:
self.progress_tracker.stop_tracking(tracking_id, status="completed", message="No text or entities provided")
return []
+ # Use method from options if provided, otherwise use instance method
+ methods = options.get("method", self.method)
+ if isinstance(methods, str):
+ methods = [methods]
+
min_confidence = options.get("min_confidence", self.min_confidence)
+ validate = options.get("validate", self.validate)
+
+ # Merge config with options
+ all_options = {**self.config, **options}
+
+ # Try each method in order (fallback chain)
+ all_relations = []
+ for method_name in methods:
+ try:
+ self.progress_tracker.update_tracking(tracking_id, message=f"Extracting relations using {method_name}...")
+ method_func = get_relation_method(method_name)
+
+ # Prepare method-specific options
+ method_options = all_options.copy()
+ if method_name == "huggingface":
+ method_options["model"] = all_options.get("huggingface_model", all_options.get("model"))
+ method_options["device"] = all_options.get("device")
+ elif method_name == "llm":
+ method_options["provider"] = all_options.get("provider", "openai")
+ method_options["model"] = all_options.get("llm_model", all_options.get("model"))
+ elif method_name == "dependency":
+ method_options["model"] = all_options.get("model", "en_core_web_sm")
+
+ relations = method_func(text, entities, **method_options)
+
+ # Filter by confidence
+ filtered = [r for r in relations if r.confidence >= min_confidence]
+
+ if filtered:
+ all_relations.append((method_name, filtered))
+
+ # If not using ensemble, return first successful result
+ if len(methods) == 1:
+ result = filtered
+ if validate:
+ result = self.validate_relations(result)
+ self.progress_tracker.stop_tracking(tracking_id, status="completed",
+ message=f"Extracted {len(result)} relations using {method_name}")
+ return result
+
+ except Exception as e:
+ self.logger.warning(f"Method {method_name} failed: {e}")
+ continue
- # Pattern-based extraction
- self.progress_tracker.update_tracking(tracking_id, message="Extracting relations using patterns...")
- relations = self._extract_with_patterns(text, entities)
+ # Use first successful method or combine
+ if all_relations:
+ relations = all_relations[0][1] # Use first successful method
+ else:
+ relations = []
- # Filter by confidence
- self.progress_tracker.update_tracking(tracking_id, message=f"Filtering {len(relations)} relations by confidence...")
- relations = [r for r in relations if r.confidence >= min_confidence]
+ # Validate if enabled
+ if validate:
+ relations = self.validate_relations(relations)
self.progress_tracker.stop_tracking(tracking_id, status="completed",
message=f"Extracted {len(relations)} relations")
diff --git a/semantica/semantic_extract/semantic_analyzer.py b/semantica/semantic_extract/semantic_analyzer.py
index e6071602..a89c08f8 100644
--- a/semantica/semantic_extract/semantic_analyzer.py
+++ b/semantica/semantic_extract/semantic_analyzer.py
@@ -3,6 +3,24 @@ Semantic Analysis Module
This module provides comprehensive semantic analysis capabilities including
similarity calculation, role labeling, clustering, and feature extraction.
+Supports multiple extraction methods for underlying entity and relation extraction.
+
+Supported Methods (for underlying NER/Relation extractors):
+ - "pattern": Pattern-based extraction
+ - "regex": Regex-based extraction
+ - "rules": Rule-based extraction
+ - "ml": ML-based extraction (spaCy)
+ - "huggingface": HuggingFace model extraction
+ - "llm": LLM-based extraction
+ - Any method supported by NERExtractor and RelationExtractor
+
+Algorithms Used:
+ - Jaccard Similarity: Set intersection over union for text similarity
+ - Cosine Similarity: Vector space model with TF-IDF or embeddings
+ - Semantic Role Labeling: Dependency parsing and rule-based role assignment
+ - Clustering: K-means, hierarchical clustering for semantic grouping
+ - Feature Extraction: TF-IDF, word embeddings, and semantic features
+ - Text Quality Metrics: Readability, coherence, and complexity measures
Key Features:
- Semantic similarity analysis (Jaccard, cosine)
@@ -10,6 +28,8 @@ Key Features:
- Semantic clustering and grouping
- Semantic feature extraction
- Text quality assessment
+ - Integration with multiple NER and relation extraction methods
+ - Method parameter support for underlying extractors
Main Classes:
- SemanticAnalyzer: Main semantic analysis coordinator
@@ -21,8 +41,12 @@ Main Classes:
Example Usage:
>>> from semantica.semantic_extract import SemanticAnalyzer
+ >>> # Using default methods
>>> analyzer = SemanticAnalyzer()
>>> similarity = analyzer.calculate_similarity("Apple Inc.", "Apple company")
+ >>>
+ >>> # Using LLM-based extraction
+ >>> analyzer = SemanticAnalyzer(method="llm", provider="openai")
>>> roles = analyzer.label_semantic_roles("John bought a car.")
>>> clusters = analyzer.cluster_semantically(texts)
@@ -31,7 +55,7 @@ License: MIT
"""
from dataclasses import dataclass, field
-from typing import Any, Dict, List, Optional, Tuple
+from typing import Any, Dict, List, Optional, Tuple, Union
from ..utils.exceptions import ProcessingError
from ..utils.logging import get_logger
@@ -62,13 +86,29 @@ class SemanticCluster:
class SemanticAnalyzer:
"""Comprehensive semantic analysis handler."""
- def __init__(self, config=None, **kwargs):
- """Initialize semantic analyzer."""
+ def __init__(self, method: Union[str, List[str]] = None, config=None, **kwargs):
+ """
+ Initialize semantic analyzer.
+
+ Args:
+ method: Extraction method(s) for underlying NER/relation extractors.
+ Can be passed to ner_method and relation_method in config.
+ config: Legacy config dict (deprecated, use kwargs)
+ **kwargs: Configuration options:
+ - ner_method: Method for NER extraction (if entities need to be extracted)
+ - relation_method: Method for relation extraction (if relations need to be extracted)
+ - Other options passed to sub-components
+ """
self.logger = get_logger("semantic_analyzer")
self.config = config or {}
self.config.update(kwargs)
self.progress_tracker = get_progress_tracker()
+ # Store method for passing to extractors if needed
+ if method is not None:
+ self.config["ner_method"] = method
+ self.config["relation_method"] = method
+
self.similarity_analyzer = SimilarityAnalyzer(**self.config.get("similarity", {}))
self.role_labeler = RoleLabeler(**self.config.get("role", {}))
self.semantic_clusterer = SemanticClusterer(**self.config.get("clustering", {}))
diff --git a/semantica/semantic_extract/semantic_network_extractor.py b/semantica/semantic_extract/semantic_network_extractor.py
index f568f320..b58e8f5b 100644
--- a/semantica/semantic_extract/semantic_network_extractor.py
+++ b/semantica/semantic_extract/semantic_network_extractor.py
@@ -4,6 +4,24 @@ Semantic Network Extractor Module
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).
+Supports multiple extraction methods for underlying entity and relation extraction.
+
+Supported Methods (for underlying NER/Relation extractors):
+ - "pattern": Pattern-based extraction
+ - "regex": Regex-based extraction
+ - "rules": Rule-based extraction
+ - "ml": ML-based extraction (spaCy)
+ - "huggingface": HuggingFace model extraction
+ - "llm": LLM-based extraction
+ - Any method supported by NERExtractor and RelationExtractor
+
+Algorithms Used:
+ - Graph Construction: Node and edge creation from entities and relations
+ - Network Analysis: Degree centrality, betweenness centrality calculations
+ - Connectivity Analysis: Path finding and component detection algorithms
+ - YAML Serialization: Tree structure serialization algorithms
+ - Graph Metrics: Node count, edge count, density calculations
+ - Entity-Relation Mapping: Hash-based and graph-based entity-relation mapping
Key Features:
- Semantic network construction from entities and relations
@@ -11,6 +29,8 @@ Key Features:
- Network analysis and metrics
- YAML export capabilities
- Connectivity analysis
+ - Integration with multiple NER and relation extraction methods
+ - Method parameter support for underlying extractors
Main Classes:
- SemanticNetworkExtractor: Main network extractor
@@ -20,8 +40,14 @@ Main Classes:
Example Usage:
>>> from semantica.semantic_extract import SemanticNetworkExtractor
+ >>> # Using default methods
>>> extractor = SemanticNetworkExtractor()
>>> network = extractor.extract_network(text, entities, relations)
+ >>>
+ >>> # Using LLM-based extraction
+ >>> extractor = SemanticNetworkExtractor(ner_method="llm", relation_method="llm", provider="openai")
+ >>> network = extractor.extract_network(text)
+ >>>
>>> analysis = extractor.analyze_network(network)
>>> yaml_str = extractor.export_to_yaml(network, "network.yaml")
@@ -30,7 +56,7 @@ License: MIT
"""
from dataclasses import dataclass, field
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, List, Optional, Union
import yaml
@@ -75,16 +101,26 @@ class SemanticNetwork:
class SemanticNetworkExtractor:
"""Semantic network extractor for structured networks."""
- def __init__(self, **config):
+ def __init__(self, method: Union[str, List[str]] = None, **config):
"""
Initialize semantic network extractor.
Args:
- **config: Configuration options
+ method: Extraction method(s) for underlying NER/relation extractors.
+ Can be passed to ner_method and relation_method in config.
+ **config: Configuration options:
+ - ner_method: Method for NER extraction (if entities need to be extracted)
+ - relation_method: Method for relation extraction (if relations need to be extracted)
+ - Other options passed to NER and relation extractors
"""
self.logger = get_logger("semantic_network_extractor")
self.config = config
self.progress_tracker = get_progress_tracker()
+
+ # Store method for passing to extractors if needed
+ if method is not None:
+ self.config["ner_method"] = method
+ self.config["relation_method"] = method
def extract_network(
self,
@@ -118,14 +154,22 @@ class SemanticNetworkExtractor:
# Extract entities if not provided
if entities is None:
self.progress_tracker.update_tracking(tracking_id, message="Extracting entities...")
- ner = NERExtractor(**self.config.get("ner", {}))
- entities = ner.extract_entities(text)
+ ner_config = self.config.get("ner", {})
+ # Pass method if specified
+ 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"]})
+ entities = ner.extract_entities(text, **options)
# Extract relations if not provided
if relations is None:
self.progress_tracker.update_tracking(tracking_id, message="Extracting relations...")
- rel_extractor = RelationExtractor(**self.config.get("relation", {}))
- relations = rel_extractor.extract_relations(text, entities)
+ rel_config = self.config.get("relation", {})
+ # Pass method if specified
+ if "relation_method" in self.config:
+ rel_config["method"] = self.config["relation_method"]
+ rel_extractor = RelationExtractor(**rel_config, **{k: v for k, v in self.config.items() if k not in ["ner", "relation"]})
+ relations = rel_extractor.extract_relations(text, entities, **options)
# Build network
self.progress_tracker.update_tracking(tracking_id, message="Building semantic network...")
diff --git a/semantica/semantic_extract/triple_extractor.py b/semantica/semantic_extract/triple_extractor.py
index 2c3ea47f..f0e4eaa6 100644
--- a/semantica/semantic_extract/triple_extractor.py
+++ b/semantica/semantic_extract/triple_extractor.py
@@ -2,19 +2,40 @@
RDF Triple Extraction Module
This module provides comprehensive RDF triple extraction capabilities, enabling
-conversion of entities and relations into RDF triples with validation and
-serialization support.
+conversion of entities and relations into RDF triples using multiple extraction
+methods, with validation and serialization support.
+
+Supported Methods:
+ - "pattern": Pattern-based triple extraction from relations (default)
+ - "rules": Rule-based triple extraction using linguistic rules
+ - "huggingface": Custom HuggingFace triplet extraction models
+ - "llm": LLM-based triple extraction using various providers
+
+Algorithms Used:
+ - Pattern Matching: Regex-based subject-predicate-object extraction
+ - Rule-based Extraction: Linguistic rule application for triple formation
+ - Sequence-to-Sequence Models: Transformer-based seq2seq for triplet generation
+ - Large Language Models: GPT, Claude, Gemini for structured triple extraction
+ - RDF Serialization: Graph serialization algorithms (Turtle, N-Triples, JSON-LD)
+ - URI Normalization: String normalization and URI formatting algorithms
Key Features:
+ - Multiple extraction methods:
+ * Pattern-based: Pattern matching for triple extraction (default)
+ * Rules-based: Rule-based triple extraction
+ * HuggingFace: Custom HuggingFace triplet models
+ * LLM-based: LLM-powered triple extraction
+ - Fallback chain support: Try methods in order until one succeeds
- RDF triple generation from entities and relations
- Subject-predicate-object extraction
- Triple validation and quality checking
- RDF serialization (Turtle, N-Triples, JSON-LD, RDF/XML)
- Batch triple processing
- URI formatting and normalization
+ - Quality assessment and scoring
Main Classes:
- - TripleExtractor: Main triple extraction coordinator
+ - TripleExtractor: Main triple extraction coordinator with method selection
- TripleValidator: Triple validation engine
- RDFSerializer: RDF serialization handler
- TripleQualityChecker: Triple quality assessment
@@ -22,8 +43,19 @@ Main Classes:
Example Usage:
>>> from semantica.semantic_extract import TripleExtractor
- >>> extractor = TripleExtractor()
+ >>> # Using pattern method (default)
+ >>> extractor = TripleExtractor(method="pattern")
+ >>> triples = extractor.extract_triples(text, entities, relations)
+ >>>
+ >>> # Using LLM method
+ >>> extractor = TripleExtractor(method="llm", provider="openai", llm_model="gpt-4")
>>> triples = extractor.extract_triples(text, entities, relations)
+ >>>
+ >>> # Using HuggingFace model
+ >>> extractor = TripleExtractor(method="huggingface", huggingface_model="custom/triplet-model")
+ >>> triples = extractor.extract_triples(text)
+ >>>
+ >>> # Serialize to RDF
>>> rdf_turtle = extractor.serialize_triples(triples, format="turtle")
>>> validated = extractor.validate_triples(triples)
@@ -32,7 +64,7 @@ License: MIT
"""
from dataclasses import dataclass, field
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, List, Optional, Union
from urllib.parse import quote
from ..utils.exceptions import ProcessingError, ValidationError
@@ -40,6 +72,7 @@ from ..utils.logging import get_logger
from ..utils.progress_tracker import get_progress_tracker
from .ner_extractor import Entity
from .relation_extractor import Relation
+from .methods import get_triple_method
@dataclass
@@ -56,13 +89,37 @@ class Triple:
class TripleExtractor:
"""RDF triple extraction handler."""
- def __init__(self, config=None, **kwargs):
- """Initialize triple extractor."""
+ def __init__(self, method: Union[str, List[str]] = "pattern", config=None, **kwargs):
+ """
+ Initialize triple extractor.
+
+ Args:
+ method: Extraction method(s). Can be:
+ - "pattern": Pattern-based extraction (default)
+ - "rules": Rule-based extraction
+ - "huggingface": HuggingFace model
+ - "llm": LLM-based extraction
+ - List of methods for fallback chain
+ config: Legacy config dict (deprecated, use kwargs)
+ **kwargs: Configuration options:
+ - model: Model name (for HuggingFace methods)
+ - huggingface_model: HuggingFace model name
+ - provider: LLM provider (for LLM method)
+ - llm_model: LLM model name
+ - device: Device for HuggingFace models
+ - min_confidence: Minimum confidence threshold
+ - validate: Enable validation (default: True)
+ """
self.logger = get_logger("triple_extractor")
self.config = config or {}
self.config.update(kwargs)
self.progress_tracker = get_progress_tracker()
+ # Method configuration
+ self.method = method if isinstance(method, list) else [method]
+ self.min_confidence = self.config.get("min_confidence", 0.5)
+ self.validate_triples = self.config.get("validate", True)
+
self.triple_validator = TripleValidator(**self.config.get("validator", {}))
self.rdf_serializer = RDFSerializer(**self.config.get("serializer", {}))
self.quality_checker = TripleQualityChecker(**self.config.get("quality", {}))
@@ -110,24 +167,74 @@ class TripleExtractor:
rel_extractor = RelationExtractor(**self.config.get("relation", {}))
relationships = rel_extractor.extract_relations(text, entities)
- # Convert relations to triples
- self.progress_tracker.update_tracking(tracking_id, message=f"Converting {len(relationships)} relations to triples...")
- triples = []
- for relation in relationships:
- triple = Triple(
- 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
- }
- )
- triples.append(triple)
+ # Use method-based extraction
+ methods = options.get("method", self.method)
+ if isinstance(methods, str):
+ methods = [methods]
+
+ # Merge config with options
+ all_options = {**self.config, **options}
+
+ # Try each method in order (fallback chain)
+ all_triples = []
+ for method_name in methods:
+ try:
+ self.progress_tracker.update_tracking(tracking_id, message=f"Extracting triples using {method_name}...")
+ method_func = get_triple_method(method_name)
+
+ # Prepare method-specific options
+ method_options = all_options.copy()
+ if method_name == "huggingface":
+ method_options["model"] = all_options.get("huggingface_model", all_options.get("model"))
+ method_options["device"] = all_options.get("device")
+ elif method_name == "llm":
+ method_options["provider"] = all_options.get("provider", "openai")
+ method_options["model"] = all_options.get("llm_model", all_options.get("model"))
+
+ triples = method_func(text, entities=entities, relations=relationships, **method_options)
+
+ # Filter by confidence
+ min_conf = options.get("min_confidence", self.min_confidence)
+ filtered = [t for t in triples if t.confidence >= min_conf]
+
+ if filtered:
+ all_triples.append((method_name, filtered))
+
+ # If not using ensemble, return first successful result
+ if len(methods) == 1:
+ result = filtered
+ if options.get("validate", self.validate_triples):
+ result = self.triple_validator.validate_triples(result)
+ self.progress_tracker.stop_tracking(tracking_id, status="completed",
+ message=f"Extracted {len(result)} triples using {method_name}")
+ return result
+
+ except Exception as e:
+ self.logger.warning(f"Method {method_name} failed: {e}")
+ continue
+
+ # Use first successful method or fallback to relation conversion
+ if all_triples:
+ triples = all_triples[0][1]
+ else:
+ # Fallback: Convert relations to triples
+ self.progress_tracker.update_tracking(tracking_id, message=f"Converting {len(relationships)} relations to triples...")
+ triples = []
+ for relation in relationships:
+ triple = Triple(
+ 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
+ }
+ )
+ triples.append(triple)
# Validate triples
- if options.get("validate", True):
+ if options.get("validate", self.validate_triples):
self.progress_tracker.update_tracking(tracking_id, message="Validating triples...")
triples = self.triple_validator.validate_triples(triples)