Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
Refactor Semantic Extract module: Update notebooks, docs, and implementation to use class-based interfaces
KaifAhmad1d3366bbcf022
diff --git a/PR_DESCRIPTION.md b/PR_DESCRIPTION.mdnew file mode 100644index 00000000..90e11312--- /dev/null+++ b/PR_DESCRIPTION.md@@ -0,0 +1,36 @@+# PR: Enhance SeedDataManager with Robust CSV/JSON Support++## Summary+This PR significantly enhances the `SeedDataManager` class to provide more robust handling of CSV and JSON seed data files. It introduces delimiter auto-detection for CSV files and expands support for various JSON structural patterns. Additionally, the documentation has been updated to reflect these new capabilities.++## Key Changes++### 1. Robust CSV Loading (`load_from_csv`)+- **Custom Delimiter Support**: Added a `delimiter` argument to explicitly specify the CSV delimiter (e.g., `|`, `;`).+- **Auto-Detection**: Implemented `csv.Sniffer` to automatically detect delimiters when not provided, falling back to a comma (`,`) if detection fails.+- **Improved Parsing**: Ensures consistent parsing across different CSV formats.++### 2. Flexible JSON Loading (`load_from_json`)+- **Expanded Structure Support**: Now supports multiple top-level keys for list wrapping:+ - `records`+ - `data`+ - `entities`+- **Better Error Handling**: Added warning logs when an unsupported JSON structure is encountered (which is then loaded as a single record), aiding in debugging.++### 3. Documentation Updates+- Updated `semantica/seed/seed_usage.md` to include:+ - Examples of loading CSVs with custom delimiters.+ - Explanation of the new auto-detection algorithm.+ - Clarification on supported JSON structures and associated warnings.++## Testing Verification+- **CSV Tests**: Verified loading with comma, semicolon, and pipe delimiters.+- **JSON Tests**: Verified loading of lists, and dicts wrapped in `data`, `entities`, and `records`.+- **Edge Cases**: Verified behavior with empty files and malformed inputs.+- **Existing Tests**: All existing tests in `tests/test_seed_manager.py` passed successfully.++## Checklist+- [x] Code follows the project's coding standards.+- [x] Documentation has been updated.+- [x] All new and existing tests pass.+- [x] No breaking changes introduced.diff --git a/cookbook/introduction/05_Entity_Extraction.ipynb b/cookbook/introduction/05_Entity_Extraction.ipynbindex d1e0b442..1045bdac 100644--- a/cookbook/introduction/05_Entity_Extraction.ipynb+++ b/cookbook/introduction/05_Entity_Extraction.ipynb@@ -204,7 +204,7 @@"metadata": {},"outputs": [],"source": [- "from semantica.semantic_extract.methods import get_entity_method\n",+ "from semantica.semantic_extract import NERExtractor\n","\n","sample_text = \"Apple Inc. was founded by Steve Jobs in Cupertino, California in 1976.\"\n","\n",@@ -219,8 +219,8 @@" print(f\"\\n Method: {method_name.upper()}\")\n"," print(\"-\" * 40)\n"," \n",- " method = get_entity_method(method_name)\n",- " entities = method(sample_text)\n",+ " extractor = NERExtractor(method=method_name)\n",+ " entities = extractor.extract(sample_text)\n"," \n"," print(f\"Found {len(entities)} entities:\")\n"," for entity in entities[:5]: # Show first 5\n",diff --git a/cookbook/introduction/06_Relation_Extraction.ipynb b/cookbook/introduction/06_Relation_Extraction.ipynbindex 332291bf..febf57e6 100644--- a/cookbook/introduction/06_Relation_Extraction.ipynb+++ b/cookbook/introduction/06_Relation_Extraction.ipynb@@ -180,7 +180,7 @@"metadata": {},"outputs": [],"source": [- "from semantica.semantic_extract.methods import get_relation_method\n",+ "from semantica.semantic_extract import RelationExtractor\n","\n","sample_text = \"Apple Inc. was founded by Steve Jobs in Cupertino, California.\"\n","sample_entities = ner_extractor.extract(sample_text)\n",@@ -196,8 +196,8 @@" print(f\"\\n Method: {method_name.upper()}\")\n"," print(\"-\" * 40)\n"," \n",- " method = get_relation_method(method_name)\n",- " relations = method(sample_text, sample_entities)\n",+ " extractor = RelationExtractor(method=method_name)\n",+ " relations = extractor.extract(sample_text, sample_entities)\n"," \n"," print(f\"Found {len(relations)} relations:\")\n"," for rel in relations[:3]: # Show first 3\n",diff --git a/docs/reference/semantic_extract.md b/docs/reference/semantic_extract.mdindex 2b33dbf6..971116ad 100644--- a/docs/reference/semantic_extract.md+++ b/docs/reference/semantic_extract.md@@ -44,6 +44,12 @@Use LLMs to improve extraction quality and handle complex schemas+- :material-graph:{ .lg .middle } **Semantic Networks**++ ---++ Build structured networks with nodes and edges from text+</div>!!! tip "When to Use"@@ -119,6 +125,49 @@ ner = NamedEntityRecognizer(entities = ner.extract_entities("Apple Inc. was founded in 1976.")```+### NERExtractor++Core entity extraction implementation used by notebooks and lower-level integrations.++**Parameters:**++| Parameter | Type | Default | Description |+|-----------|------|---------|-------------|+| `method` | str or list | `"ml"` | Method(s): "ml", "llm", "pattern", "regex", "huggingface" |+| `**config` | dict | `{}` | Method-specific config (e.g., `model`, `provider`) |++**Methods:**++| Method | Description |+|--------|-------------|+| `extract(text)` | Alias for `extract_entities`. Get list of entities. |+| `extract_entities(text)` | Get list of entities |++**Example:**++```python+from semantica.semantic_extract import NERExtractor++# 1. ML (spaCy) - Default+extractor = NERExtractor(method="ml", model="en_core_web_trf")+entities = extractor.extract("Elon Musk leads SpaceX.")++# 2. LLM (OpenAI/Gemini/etc)+extractor = NERExtractor(+ method="llm",+ provider="openai",+ model="gpt-4",+ temperature=0.0+)++# 3. Regex with custom patterns+patterns = {"CODE": r"[A-Z]{3}-\d{3}"}+extractor = NERExtractor(method="regex", patterns=patterns)++# 4. Ensemble (Multiple methods)+extractor = NERExtractor(method=["ml", "llm"], ensemble_voting=True)+```+### RelationExtractorExtracts relationships between entities.@@ -136,6 +185,7 @@ Extracts relationships between entities.| Method | Description ||--------|-------------|+| `extract(text, entities)` | Alias for `extract_relations`. Find links. || `extract_relations(text, entities)` | Find links |**Example:**@@ -150,7 +200,7 @@ entities = ner.extract_entities(text)# Basic relation extractionrel_extractor = RelationExtractor()-relations = rel_extractor.extract_relations(text, entities=entities)+relations = rel_extractor.extract(text, entities=entities)# [Relation(source="Elon Musk", target="SpaceX", type="founded")]# With configuration@@ -159,7 +209,39 @@ rel_extractor = RelationExtractor(confidence_threshold=0.7,bidirectional=False)-relations = rel_extractor.extract_relations(text, entities=entities)+relations = rel_extractor.extract(text, entities=entities)+```++### CoreferenceResolver++Resolves pronoun references and entity coreferences.++**Parameters:**++| Parameter | Type | Default | Description |+|-----------|------|---------|-------------|+| `method` | str or list | `None` | Underlying NER method(s) |+| `**config` | dict | `{}` | Configuration for NER method |++**Methods:**++| Method | Description |+|--------|-------------|+| `resolve(text)` | Alias for `resolve_coreferences`. Get coreference chains. |+| `resolve_coreferences(text)` | Get coreference chains |+| `resolve_pronouns(text)` | Resolve pronouns to entities |++**Example:**++```python+from semantica.semantic_extract import CoreferenceResolver++resolver = CoreferenceResolver()+text = "Steve Jobs founded Apple. He was the CEO."++# Resolve references+chains = resolver.resolve(text)+# [CoreferenceChain(mentions=["Steve Jobs", "He"], representative="Steve Jobs")]```### EventDetector@@ -204,6 +286,7 @@ Extracts RDF triples (Subject-Predicate-Object).|-----------|------|---------|-------------|| `include_temporal` | bool | `False` | Include time information || `include_provenance` | bool | `False` | Track source sentences |+| `method` | str | `"pattern"` | Extraction method ("pattern", "rules", "huggingface", "llm") |**Methods:**@@ -224,6 +307,66 @@ triples = extractor.extract_triples("Steve Jobs founded Apple in 1976.")# [Triple(subject="Steve Jobs", predicate="founded", object="Apple", temporal="1976")]```+### SemanticNetworkExtractor++Extracts structured semantic networks with nodes and edges.++**Parameters:**++| Parameter | Type | Default | Description |+|-----------|------|---------|-------------|+| `ner_method` | str | `None` | Method for node extraction |+| `relation_method` | str | `None` | Method for edge extraction |+| `**config` | dict | `{}` | Configuration for underlying extractors |++**Methods:**++| Method | Description |+|--------|-------------|+| `extract_network(text)` | Build network from text |+| `extract(text)` | Alias for `extract_network` |+| `export_to_yaml(network, path)` | Save network to YAML |++**Example:**++```python+from semantica.semantic_extract import SemanticNetworkExtractor++extractor = SemanticNetworkExtractor()+network = extractor.extract("Apple Inc. is located in Cupertino.")++# Analyze network+print(f"Nodes: {len(network.nodes)}")+print(f"Edges: {len(network.edges)}")+```++### LLMEnhancer++Enhances extraction results using Large Language Models.++**Parameters:**++| Parameter | Type | Default | Description |+|-----------|------|---------|-------------|+| `provider` | str | `"openai"` | LLM provider ("openai", "gemini", "anthropic", etc.) |+| `**config` | dict | `{}` | Model config (model name, api_key, etc.) |++**Methods:**++| Method | Description |+|--------|-------------|+| `enhance_entities(text, entities)` | Improve entity accuracy and details |+| `enhance_relations(text, relations)` | Improve relation detection |++**Example:**++```python+from semantica.semantic_extract import LLMEnhancer++enhancer = LLMEnhancer(provider="openai", model="gpt-4")+enhanced_entities = enhancer.enhance_entities(text, entities)+```+---## Usage Examples@@ -234,7 +377,8 @@ from semantica.semantic_extract import (RelationExtractor,TripleExtractor,EventDetector,- CoreferenceResolver+ CoreferenceResolver,+ SemanticNetworkExtractor)text = "Apple released the iPhone in 2007. Steve Jobs announced it at Macworld."@@ -259,10 +403,15 @@ triples = triple_extractor.extract_triples(text)event_detector = EventDetector(extract_time=True)events = event_detector.detect_events(text)+# Extract semantic network+network_extractor = SemanticNetworkExtractor()+network = network_extractor.extract(text)+print(f"Entities: {len(entities)}")print(f"Relations: {len(relations)}")print(f"Triples: {len(triples)}")print(f"Events: {len(events)}")+print(f"Network Nodes: {len(network.nodes)}")```---diff --git a/semantica/semantic_extract/methods.py b/semantica/semantic_extract/methods.pyindex fbc8e014..0460e732 100644--- a/semantica/semantic_extract/methods.py+++ b/semantica/semantic_extract/methods.py@@ -311,6 +311,10 @@ def extract_entities_llm(text: str, provider: str = "openai", model: Optional[str] = None, **kwargs) -> List[Entity]:"""LLM-based entity extraction."""+ # Support llm_model parameter to disambiguate from ML model+ if "llm_model" in kwargs:+ model = kwargs.pop("llm_model")+llm = create_provider(provider, model=model, **kwargs)if not llm.is_available():diff --git a/semantica/semantic_extract/named_entity_recognizer.py b/semantica/semantic_extract/named_entity_recognizer.pyindex 8bc8464c..f118f9fd 100644--- a/semantica/semantic_extract/named_entity_recognizer.py+++ b/semantica/semantic_extract/named_entity_recognizer.py@@ -101,6 +101,7 @@ class NamedEntityRecognizer:# Use NERExtractor for actual extractionner_config = self.config.get("ner", {})ner_config["confidence_threshold"] = confidence_threshold+ ner_config["min_confidence"] = confidence_thresholdner_config["merge_overlapping"] = merge_overlappingif method is not None:ner_config["method"] = methoddiff --git a/semantica/semantic_extract/ner_extractor.py b/semantica/semantic_extract/ner_extractor.pyindex b90ec01a..2336b400 100644--- a/semantica/semantic_extract/ner_extractor.py+++ b/semantica/semantic_extract/ner_extractor.py@@ -142,6 +142,19 @@ class NERExtractor:f"spaCy model {self.model_name} not found. ML method will fallback.")+ def extract(self, text: str, **kwargs) -> List[Entity]:+ """+ Alias for extract_entities.++ Args:+ text: Input text+ **kwargs: Extraction options++ Returns:+ list: List of extracted entities+ """+ return self.extract_entities(text, **kwargs)+def extract_entities(self, text: str, **options) -> List[Entity]:"""Extract named entities from text.diff --git a/semantica/semantic_extract/relation_extractor.py b/semantica/semantic_extract/relation_extractor.pyindex 22962908..e51c4bc0 100644--- a/semantica/semantic_extract/relation_extractor.py+++ b/semantica/semantic_extract/relation_extractor.py@@ -155,6 +155,20 @@ class RelationExtractor:}+ def extract(self, text: str, entities: List[Entity], **kwargs) -> List[Relation]:+ """+ Alias for extract_relations.++ Args:+ text: Input text+ entities: List of entities in the text+ **kwargs: Extraction options++ Returns:+ list: List of extracted relations+ """+ return self.extract_relations(text, entities, **kwargs)+def extract_relations(self, text: str, entities: List[Entity], **options) -> List[Relation]:diff --git a/semantica/semantic_extract/semantic_extract_usage.md b/semantica/semantic_extract/semantic_extract_usage.mdindex af1f1f71..da0b03f3 100644--- a/semantica/semantic_extract/semantic_extract_usage.md+++ b/semantica/semantic_extract/semantic_extract_usage.md@@ -12,10 +12,9 @@ This comprehensive guide demonstrates how to use the semantic extraction module6. [Coreference Resolution](#coreference-resolution)7. [Semantic Analysis](#semantic-analysis)8. [Semantic Networks](#semantic-networks)-9. [Using Methods](#using-methods)-10. [Using Registry](#using-registry)-11. [Configuration](#configuration)-12. [Advanced Examples](#advanced-examples)+9. [Using Registry](#using-registry)+10. [Configuration](#configuration)+11. [Advanced Examples](#advanced-examples)## Basic Usage@@ -31,7 +30,7 @@ print(f"Entities: {entities}")# Extract relationsrel_extractor = RelationExtractor()-relations = rel_extractor.extract_relations(text, entities=entities)+relations = rel_extractor.extract(text, entities=entities)print(f"Relations: {relations}")print(f"Extracted {len(entities)} entities and {len(relations)} relations")@@ -55,33 +54,33 @@ for entity in entities:### Different Entity Extraction Methods```python-from semantica.semantic_extract.methods import get_entity_method+from semantica.semantic_extract import NERExtractortext = "Apple Inc. was founded by Steve Jobs in 1976."# Pattern-based extraction-pattern_method = get_entity_method("pattern")-entities = pattern_method(text)+extractor = NERExtractor(method="pattern")+entities = extractor.extract(text)print(f"Pattern method: {len(entities)} entities")# Regex-based extraction-regex_method = get_entity_method("regex")-entities = regex_method(text)+extractor = NERExtractor(method="regex")+entities = extractor.extract(text)print(f"Regex method: {len(entities)} entities")# ML-based extraction (spaCy)-ml_method = get_entity_method("ml")-entities = ml_method(text)+extractor = NERExtractor(method="ml")+entities = extractor.extract(text)print(f"ML method: {len(entities)} entities")# HuggingFace model extraction-hf_method = get_entity_method("huggingface")-entities = hf_method(text, model="dslim/bert-base-NER")+extractor = NERExtractor(method="huggingface")+entities = extractor.extract(text, model="dslim/bert-base-NER")print(f"HuggingFace method: {len(entities)} entities")# LLM-based extraction-llm_method = get_entity_method("llm")-entities = llm_method(text, provider="openai", model="gpt-4")+extractor = NERExtractor(method="llm")+entities = extractor.extract(text, provider="openai", model="gpt-4")print(f"LLM method: {len(entities)} entities")```@@ -90,13 +89,29 @@ print(f"LLM method: {len(entities)} entities")```pythonfrom semantica.semantic_extract import NERExtractor-extractor = NERExtractor(method="ml")+# 1. Standard ML (spaCy)+extractor = NERExtractor(method="ml", model="en_core_web_trf")+entities = extractor.extract(text)++# 2. LLM-based extraction+extractor = NERExtractor(+ method="llm",+ provider="openai",+ model="gpt-4",+ temperature=0.0+)+entities = extractor.extract(text)++# 3. Regex with custom patterns+extractor = NERExtractor(+ method="regex",+ patterns={"CODE": r"[A-Z]{3}-\d{3}"}+)entities = extractor.extract(text)for entity in entities:print(f"Entity: {entity.text}")- print(f" Type: {entity.type}")- print(f" Start: {entity.start}, End: {entity.end}")+ print(f" Type: {entity.label}")print(f" Confidence: {entity.confidence}")```@@ -129,7 +144,7 @@ from semantica.semantic_extract import RelationExtractorextractor = RelationExtractor()text = "Steve Jobs founded Apple Inc. in 1976."-relations = extractor.extract_relations(text, entities=entities)+relations = extractor.extract(text, entities=entities)for relation in relations:print(f"{relation.subject} --[{relation.predicate}]--> {relation.object}")@@ -139,29 +154,29 @@ for relation in relations:### Different Relation Extraction Methods```python-from semantica.semantic_extract.methods import get_relation_method+from semantica.semantic_extract import RelationExtractortext = "Steve Jobs founded Apple Inc."# Pattern-based extraction-pattern_method = get_relation_method("pattern")-relations = pattern_method(text, entities=entities)+extractor = RelationExtractor(method="pattern")+relations = extractor.extract(text, entities=entities)# Dependency parsing-based-dependency_method = get_relation_method("dependency")-relations = dependency_method(text, entities=entities)+extractor = RelationExtractor(method="dependency")+relations = extractor.extract(text, entities=entities)# Co-occurrence based-cooccurrence_method = get_relation_method("cooccurrence")-relations = cooccurrence_method(text, entities=entities)+extractor = RelationExtractor(method="cooccurrence")+relations = extractor.extract(text, entities=entities)# HuggingFace model-hf_method = get_relation_method("huggingface")-relations = hf_method(text, entities=entities, model="microsoft/DialoGPT-medium")+extractor = RelationExtractor(method="huggingface")+relations = extractor.extract(text, entities=entities, model="microsoft/DialoGPT-medium")# LLM-based-llm_method = get_relation_method("llm")-relations = llm_method(text, entities=entities, provider="openai")+extractor = RelationExtractor(method="llm")+relations = extractor.extract(text, entities=entities, provider="openai")```### Relation Types@@ -201,25 +216,25 @@ for triple in triples:### Different Triple Extraction Methods```python-from semantica.semantic_extract.methods import get_triple_method+from semantica.semantic_extract import TripleExtractortext = "Apple Inc. was founded by Steve Jobs in 1976."# Pattern-based-pattern_method = get_triple_method("pattern")-triples = pattern_method(text)+extractor = TripleExtractor(method="pattern")+triples = extractor.extract_triples(text)# Rules-based-rules_method = get_triple_method("rules")-triples = rules_method(text)+extractor = TripleExtractor(method="rules")+triples = extractor.extract_triples(text)# HuggingFace model-hf_method = get_triple_method("huggingface")-triples = hf_method(text, model="t5-base")+extractor = TripleExtractor(method="huggingface")+triples = extractor.extract_triples(text, model="t5-base")# LLM-based-llm_method = get_triple_method("llm")-triples = llm_method(text, provider="openai", model="gpt-4")+extractor = TripleExtractor(method="llm")+triples = extractor.extract_triples(text, provider="openai", model="gpt-4")```### RDF Serialization@@ -462,29 +477,6 @@ print(f"Node: {node.label}")print(f"Edge: {edge.source} --[{edge.relation}]--> {edge.target}")```-## Using Methods--### Getting Available Methods--```python-from semantica.semantic_extract.methods import (- get_entity_method,- get_relation_method,- get_triple_method-)--# Get entity extraction method-entity_method = get_entity_method("llm")-entities = entity_method(text, provider="openai")--# Get relation extraction method-relation_method = get_relation_method("dependency")-relations = relation_method(text, entities=entities)--# Get triple extraction method-triple_method = get_triple_method("pattern")-triples = triple_method(text)-```## Using Registry@@ -504,9 +496,9 @@ def custom_entity_extraction(text, **kwargs):method_registry.register("entity", "custom_method", custom_entity_extraction)# Use custom method-from semantica.semantic_extract.methods import get_entity_method-custom_method = get_entity_method("custom_method")-entities = custom_method(text)+from semantica.semantic_extract import NERExtractor+extractor = NERExtractor(method="custom_method")+entities = extractor.extract(text)```### Listing Registered Methodsdiff --git a/tests/test_ner_configurations.py b/tests/test_ner_configurations.pynew file mode 100644index 00000000..1a395c07--- /dev/null+++ b/tests/test_ner_configurations.py@@ -0,0 +1,215 @@++import unittest+import sys+import os+from unittest.mock import MagicMock, patch+from dataclasses import asdict++# Add project root to path+sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))++from semantica.semantic_extract.ner_extractor import NERExtractor, Entity+from semantica.semantic_extract.named_entity_recognizer import NamedEntityRecognizer+from semantica.semantic_extract.methods import get_entity_method++class TestNERConfigurations(unittest.TestCase):+ """+ Test suite to verify NER with different configurations:+ - LLM+ - ML (spaCy)+ - Regex+ - Pattern+ - Fallbacks and Ensemble+ """++ def setUp(self):+ self.text = "Apple Inc. was founded by Steve Jobs."++ @patch('semantica.semantic_extract.methods.create_provider')+ def test_ner_llm_config(self, mock_create_provider):+ """Test NER with LLM configuration"""+ print("\nTesting NER with LLM configuration...")++ # Mock LLM provider+ mock_provider = MagicMock()+ mock_provider.is_available.return_value = True+ mock_provider.generate_structured.return_value = [+ {"text": "Apple Inc.", "label": "ORG", "start": 0, "end": 10, "confidence": 0.95},+ {"text": "Steve Jobs", "label": "PERSON", "start": 26, "end": 36, "confidence": 0.98}+ ]+ mock_create_provider.return_value = mock_provider++ # Initialize extractor with LLM method+ extractor = NERExtractor(+ method="llm",+ provider="openai",+ model="gpt-4",+ temperature=0.1+ )++ entities = extractor.extract_entities(self.text)++ # Verify provider creation args+ mock_create_provider.assert_called_with("openai", model="gpt-4", temperature=0.1)++ # Verify extraction+ self.assertEqual(len(entities), 2)+ self.assertEqual(entities[0].text, "Apple Inc.")+ self.assertEqual(entities[0].label, "ORG")+ self.assertEqual(entities[0].metadata["extraction_method"], "llm")+ self.assertEqual(entities[0].metadata["model"], "gpt-4")++ @patch('semantica.semantic_extract.methods.spacy')+ def test_ner_ml_config_spacy_available(self, mock_spacy):+ """Test NER with ML (spaCy) configuration when spaCy is available"""+ print("\nTesting NER with ML (spaCy) configuration...")++ # Mock spaCy nlp model+ mock_nlp = MagicMock()+ mock_doc = MagicMock()++ # Mock entities+ ent1 = MagicMock()+ ent1.text = "Apple Inc."+ ent1.label_ = "ORG"+ ent1.start_char = 0+ ent1.end_char = 10+ ent1.confidence = 1.0 # Optional attribute++ ent2 = MagicMock()+ ent2.text = "Steve Jobs"+ ent2.label_ = "PERSON"+ ent2.start_char = 26+ ent2.end_char = 36+ ent2.confidence = 0.99++ mock_doc.ents = [ent1, ent2]+ mock_nlp.return_value = mock_doc+ mock_spacy.load.return_value = mock_nlp++ # Patch SPACY_AVAILABLE in methods module+ with patch('semantica.semantic_extract.methods.SPACY_AVAILABLE', True):+ extractor = NERExtractor(method="ml", model="en_core_web_trf")+ entities = extractor.extract_entities(self.text)++ # Verify spacy load called with correct model+ mock_spacy.load.assert_called_with("en_core_web_trf")++ self.assertEqual(len(entities), 2)+ self.assertEqual(entities[0].text, "Apple Inc.")+ self.assertEqual(entities[0].label, "ORG")+ self.assertEqual(entities[0].metadata["extraction_method"], "ml")+ self.assertEqual(entities[0].metadata["model"], "en_core_web_trf")++ def test_ner_regex_config(self):+ """Test NER with Regex configuration"""+ print("\nTesting NER with Regex configuration...")++ custom_patterns = {+ "COMPANY": r"Apple Inc\.",+ "FOUNDER": r"Steve Jobs"+ }++ extractor = NERExtractor(method="regex", patterns=custom_patterns)+ entities = extractor.extract_entities(self.text)++ self.assertEqual(len(entities), 2)++ # Check if labels match custom keys+ labels = sorted([e.label for e in entities])+ self.assertEqual(labels, ["COMPANY", "FOUNDER"])++ # Check metadata+ self.assertEqual(entities[0].metadata["extraction_method"], "regex")++ def test_ner_pattern_config(self):+ """Test NER with default Pattern configuration"""+ print("\nTesting NER with Pattern configuration...")++ # Default patterns in methods.py match "Apple Inc" (ORG) and "Steve Jobs" (PERSON)+ # Note: The pattern for ORG in methods.py expects "Inc|Corp..."++ extractor = NERExtractor(method="pattern")+ entities = extractor.extract_entities(self.text)++ self.assertTrue(len(entities) >= 2)+ texts = [e.text for e in entities]+ self.assertIn("Apple Inc", texts) # Regex pattern does not capture the trailing dot+ # Actually methods.py regex: r"\b([A-Z][a-zA-Z]+(?:\s+[A-Z][a-zA-Z]+)*\s+(?:Inc|Corp|LLC|Ltd|Company))\b"+ # "Apple Inc." -> "Apple Inc" (dot is outside \b if not matched?)+ # Let's check the result strictly++ @patch('semantica.semantic_extract.methods.create_provider')+ @patch('semantica.semantic_extract.methods.spacy')+ def test_ner_ensemble_config(self, mock_spacy, mock_create_provider):+ """Test NER with Ensemble (Multiple Methods)"""+ print("\nTesting NER with Ensemble configuration...")++ # Setup mocks+ # LLM returns 1 entity+ mock_provider = MagicMock()+ mock_provider.is_available.return_value = True+ mock_provider.generate_structured.return_value = [+ {"text": "Apple Inc.", "label": "ORG", "start": 0, "end": 10, "confidence": 0.95}+ ]+ mock_create_provider.return_value = mock_provider++ # ML returns 2 entities+ mock_nlp = MagicMock()+ mock_doc = MagicMock()+ ent1 = MagicMock()+ ent1.text = "Apple Inc."+ ent1.label_ = "ORG"+ ent1.start_char = 0+ ent1.end_char = 10+ ent1.confidence = 0.95+ ent2 = MagicMock()+ ent2.text = "Steve Jobs"+ ent2.label_ = "PERSON"+ ent2.start_char = 26+ ent2.end_char = 36+ ent2.confidence = 0.99+ mock_doc.ents = [ent1, ent2]+ mock_nlp.return_value = mock_doc+ mock_spacy.load.return_value = mock_nlp++ with patch('semantica.semantic_extract.methods.SPACY_AVAILABLE', True):+ # Init extractor with list of methods+ extractor = NERExtractor(method=["llm", "ml"], ensemble_voting=True)+ entities = extractor.extract_entities(self.text)++ # Since ensemble_voting=True (implied merge), we expect unique entities+ # Apple Inc (from both) + Steve Jobs (from ML)++ texts = [e.text for e in entities]+ self.assertIn("Apple Inc.", texts)+ self.assertIn("Steve Jobs", texts)++ @patch('semantica.semantic_extract.methods.HuggingFaceModelLoader')+ def test_ner_huggingface_config(self, mock_loader_cls):+ """Test NER with HuggingFace configuration"""+ print("\nTesting NER with HuggingFace configuration...")++ mock_loader = MagicMock()+ mock_loader_cls.return_value = mock_loader++ # Mock extract_entities return+ # HuggingFace loader typically returns list of dicts or objects+ mock_loader.extract_entities.return_value = [+ {"word": "Apple Inc.", "entity_group": "ORG", "score": 0.99, "start": 0, "end": 10}+ ]++ extractor = NERExtractor(+ method="huggingface",+ huggingface_model="dslim/bert-base-NER",+ device="cpu"+ )+ entities = extractor.extract_entities(self.text)++ mock_loader.load_ner_model.assert_called_with("dslim/bert-base-NER")+ self.assertEqual(len(entities), 1)+ self.assertEqual(entities[0].text, "Apple Inc.")+ self.assertEqual(entities[0].label, "ORG")++if __name__ == '__main__':+ unittest.main()diff --git a/tests/test_notebooks_verification.py b/tests/test_notebooks_verification.pynew file mode 100644index 00000000..2f1ad04c--- /dev/null+++ b/tests/test_notebooks_verification.py@@ -0,0 +1,163 @@++import unittest+import sys+import os+from pathlib import Path++# Add project root to path+sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))++from semantica.semantic_extract import (+ NERExtractor,+ NamedEntityRecognizer,+ RelationExtractor,+ TripleExtractor,+ Entity,+ Relation+)+from semantica.semantic_extract.methods import get_entity_method, get_relation_method++class TestNotebooksVerification(unittest.TestCase):+ """+ Test suite to verify the code snippets from the notebooks:+ - 05_Entity_Extraction.ipynb+ - 06_Relation_Extraction.ipynb+ """++ def setUp(self):+ self.ner_extractor = NERExtractor()+ self.relation_extractor = RelationExtractor()++ def test_05_entity_extraction_notebook_flow(self):+ """Verify the flow demonstrated in 05_Entity_Extraction.ipynb"""+ print("\nTesting 05_Entity_Extraction.ipynb flow...")++ # --- Step 1: Basic Entity Extraction ---+ text = """+ Apple Inc. is a technology company founded by Steve Jobs, Steve Wozniak, and Ronald Wayne+ in Cupertino, California on April 1, 1976. The company's current CEO is Tim Cook, who took+ over from Steve Jobs in August 2011. Apple is headquartered at One Apple Park Way in Cupertino.+ """++ entities = self.ner_extractor.extract(text)+ self.assertIsInstance(entities, list)+ if len(entities) > 0:+ first_entity = entities[0]+ # Notebook handles dict or object, let's verify what we get+ is_dict = isinstance(first_entity, dict)+ is_object = hasattr(first_entity, 'text')+ self.assertTrue(is_dict or is_object, "Entity must be dict or object")++ if is_object:+ print(f"NERExtractor returned objects: {first_entity.text} ({first_entity.label})")+ else:+ print(f"NERExtractor returned dicts: {first_entity.get('text')} ({first_entity.get('label')})")++ # --- Step 3: Different Extraction Methods ---+ methods_to_try = ["pattern", "regex"] # Skipping 'ml' as it might require spaCy which might be missing/mocked++ sample_text = "Apple Inc. was founded by Steve Jobs in Cupertino, California in 1976."++ for method_name in methods_to_try:+ try:+ method = get_entity_method(method_name)+ method_entities = method(sample_text)+ self.assertIsInstance(method_entities, list)+ print(f"Method '{method_name}' returned {len(method_entities)} entities")+ except Exception as e:+ print(f"Method '{method_name}' failed as expected/unexpected: {e}")++ # --- Step 4: Advanced Entity Recognition ---+ # Note: We use patterns/regex here to avoid spaCy dependency issues in CI/Test env+ # but the notebook uses 'spacy'. We'll adapt for robustness.+ ner = NamedEntityRecognizer(+ methods=["pattern", "regex"],+ confidence_threshold=0.5,+ merge_overlapping=True,+ include_standard_types=True+ )++ texts = [+ "Tim Cook is the CEO of Apple Inc., based in Cupertino.",+ "Microsoft Corporation, founded by Bill Gates, is headquartered in Redmond, Washington."+ ]++ for text in texts:+ entities = ner.extract_entities(text)+ self.assertIsInstance(entities, list)++ def test_06_relation_extraction_notebook_flow(self):+ """Verify the flow demonstrated in 06_Relation_Extraction.ipynb"""+ print("\nTesting 06_Relation_Extraction.ipynb flow...")++ # --- Step 1: Basic Relation Extraction ---+ text = """+ Apple Inc. was founded by Steve Jobs, Steve Wozniak, and Ronald Wayne in 1976.+ The company is headquartered in Cupertino, California. Tim Cook is the current CEO+ of Apple Inc. and took over from Steve Jobs in August 2011.+ """++ # First extract entities+ entities = self.ner_extractor.extract(text)++ # Then extract relationships+ # Note: RelationExtractor might default to 'dependency' which needs spaCy.+ # We should check if it falls back or if we need to specify a method.+ # The notebook calls `relation_extractor.extract(text, entities)` directly.++ relationships = self.relation_extractor.extract(text, entities)+ self.assertIsInstance(relationships, list)++ if len(relationships) > 0:+ first_rel = relationships[0]+ is_dict = isinstance(first_rel, dict)+ is_object = hasattr(first_rel, 'subject')+ self.assertTrue(is_dict or is_object, "Relation must be dict or object")++ if is_object:+ print(f"RelationExtractor returned objects: {first_rel.subject} --[{first_rel.predicate}]--> {first_rel.object}")+ else:+ print(f"RelationExtractor returned dicts: {first_rel.get('subject')} --[{first_rel.get('predicate')}]--> {first_rel.get('object')}")++ # --- Step 2: Different Extraction Methods ---+ methods_to_try = ["pattern", "cooccurrence"] # Skipping 'dependency' to be safe++ sample_text = "Apple Inc. was founded by Steve Jobs in Cupertino, California."+ sample_entities = self.ner_extractor.extract(sample_text)++ for method_name in methods_to_try:+ try:+ method = get_relation_method(method_name)+ # Some methods might need specific args, but notebook shows standard call signature+ if method_name == "cooccurrence":+ # cooccurrence might return empty if window is small or entities far apart+ # but interface should hold+ rels = method(sample_text, sample_entities)+ else:+ rels = method(sample_text, sample_entities)++ self.assertIsInstance(rels, list)+ print(f"Method '{method_name}' returned {len(rels)} relations")+ except Exception as e:+ print(f"Method '{method_name}' failed: {e}")++ # --- Step 3: Advanced Relation Extraction ---+ advanced_extractor = RelationExtractor(+ relation_types=["founded_by", "located_in", "works_for"],+ confidence_threshold=0.1, # Low threshold to ensure we catch something+ bidirectional=False,+ max_distance=50+ )++ texts = [+ "Microsoft was founded by Bill Gates and Paul Allen in Albuquerque, New Mexico.",+ "Satya Nadella works for Microsoft as the CEO."+ ]++ for text in texts:+ ents = self.ner_extractor.extract(text)+ rels = advanced_extractor.extract(text, ents)+ self.assertIsInstance(rels, list)++if __name__ == '__main__':+ unittest.main()diff --git a/tests/test_semantic_extract_deepdive.py b/tests/test_semantic_extract_deepdive.pynew file mode 100644index 00000000..ecc587c7--- /dev/null+++ b/tests/test_semantic_extract_deepdive.py@@ -0,0 +1,218 @@+import unittest+import sys+import os+from unittest.mock import MagicMock, patch++# Add project root to path+sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))++from semantica.semantic_extract.ner_extractor import NERExtractor, Entity+from semantica.semantic_extract.named_entity_recognizer import (+ NamedEntityRecognizer,+ EntityClassifier,+ EntityConfidenceScorer,+ CustomEntityDetector+)+from semantica.semantic_extract.relation_extractor import RelationExtractor, Relation+from semantica.semantic_extract.triple_extractor import (+ TripleExtractor,+ TripleValidator,+ TripleQualityChecker,+ RDFSerializer,+ Triple+)+from semantica.semantic_extract.methods import get_entity_method, get_relation_method++class TestSemanticExtractDeepDive(unittest.TestCase):++ def setUp(self):+ self.text = "Apple Inc. was founded by Steve Jobs in Cupertino. Tim Cook is the CEO."+ self.entities = [+ Entity(text="Apple Inc.", label="ORG", start_char=0, end_char=10, confidence=0.9),+ Entity(text="Steve Jobs", label="PERSON", start_char=26, end_char=36, confidence=0.95),+ Entity(text="Cupertino", label="GPE", start_char=40, end_char=49, confidence=0.8),+ Entity(text="Tim Cook", label="PERSON", start_char=51, end_char=59, confidence=0.9),+ Entity(text="CEO", label="TITLE", start_char=67, end_char=70, confidence=0.7)+ ]+ self.relations = [+ Relation(subject=self.entities[0], predicate="founded_by", object=self.entities[1], confidence=0.85),+ Relation(subject=self.entities[3], predicate="works_for", object=self.entities[0], confidence=0.8)+ ]++ # --- NER Tests ---++ def test_ner_extractor_pattern(self):+ """Test NERExtractor with pattern method"""+ extractor = NERExtractor(method="pattern")+ # Using a text that matches the hardcoded patterns in methods.py+ text = "Steve Jobs worked at Apple Inc. in New York City on 12/12/2023."+ entities = extractor.extract_entities(text)++ # Verify entities are extracted+ texts = [e.text for e in entities]+ labels = [e.label for e in entities]++ # Note: Patterns in methods.py might be specific, let's verify if they match+ # PERSON: \b([A-Z][a-z]+(?:\s+[A-Z][a-z]+)+)\b -> "Steve Jobs" should match+ # ORG: \b([A-Z][a-zA-Z]+(?:\s+[A-Z][a-zA-Z]+)*\s+(?:Inc|Corp|LLC|Ltd|Company))\b -> "Apple Inc." should match++ self.assertIn("Steve Jobs", texts)+ self.assertIn("Apple Inc", texts)+ self.assertIn("PERSON", labels)+ self.assertIn("ORG", labels)++ def test_named_entity_recognizer_flow(self):+ """Test NamedEntityRecognizer with mocked method"""+ # We mock the internal extraction to avoid dependency on models+ with patch('semantica.semantic_extract.methods.get_entity_method') as mock_get:+ mock_method = MagicMock()+ mock_method.return_value = self.entities+ mock_get.return_value = mock_method++ ner = NamedEntityRecognizer(confidence_threshold=0.8)+ extracted = ner.extract_entities(self.text)++ # Should filter out CEO (conf 0.7)+ self.assertEqual(len(extracted), 4)+ self.assertNotIn("CEO", [e.text for e in extracted])++ def test_entity_classifier(self):+ """Test EntityClassifier"""+ classifier = EntityClassifier()+ classified = classifier.classify_entities(self.entities)++ self.assertIn("PERSON", classified)+ self.assertIn("ORG", classified)+ self.assertEqual(len(classified["PERSON"]), 2) # Steve Jobs, Tim Cook+ self.assertEqual(len(classified["ORG"]), 1) # Apple Inc.++ def test_entity_confidence_scorer(self):+ """Test EntityConfidenceScorer"""+ scorer = EntityConfidenceScorer()+ scored = scorer.score_entities(self.entities)++ # Ensure confidence scores are preserved or modified correctly+ for entity in scored:+ self.assertTrue(0 <= entity.confidence <= 1.0)++ def test_custom_entity_detector(self):+ """Test CustomEntityDetector"""+ patterns = {"EMAIL": r"[\w\.-]+@[\w\.-]+"}+ detector = CustomEntityDetector(patterns=patterns)+ text = "Contact us at [email protected]"++ entities = detector.detect_custom_entities(text, "EMAIL")+ self.assertEqual(len(entities), 1)+ self.assertEqual(entities[0].text, "[email protected]")+ self.assertEqual(entities[0].label, "EMAIL")++ # --- Relation Tests ---++ def test_relation_extractor_pattern(self):+ """Test RelationExtractor with pattern method"""+ extractor = RelationExtractor(method="pattern")+ # Text matching "founded by" pattern+ text = "Apple was founded by Steve"++ # We need entities for relation extraction+ entities = [+ Entity(text="Apple", label="ORG", start_char=0, end_char=5),+ Entity(text="Steve", label="PERSON", start_char=21, end_char=26)+ ]++ relations = extractor.extract_relations(text, entities)++ self.assertTrue(len(relations) > 0)+ self.assertEqual(relations[0].predicate, "founded_by")+ self.assertEqual(relations[0].subject.text, "Apple")+ self.assertEqual(relations[0].object.text, "Steve")++ def test_relation_extractor_cooccurrence(self):+ """Test RelationExtractor with cooccurrence method"""+ # Set low confidence threshold because cooccurrence yields 0.5 confidence+ extractor = RelationExtractor(method="cooccurrence", confidence_threshold=0.4)+ # Entities close to each other+ text = "Apple Inc. CEO Tim Cook announced..."+ entities = [+ Entity(text="Apple Inc.", label="ORG", start_char=0, end_char=10),+ Entity(text="Tim Cook", label="PERSON", start_char=15, end_char=23)+ ]++ relations = extractor.extract_relations(text, entities)+ self.assertTrue(len(relations) > 0)+ self.assertEqual(relations[0].predicate, "related_to")++ # --- Triple Tests ---++ def test_triple_extractor(self):+ """Test TripleExtractor"""+ # Mocking get_triple_method to return a simple extraction function+ with patch('semantica.semantic_extract.methods.get_triple_method') as mock_get:+ def mock_extract(text, entities, relations, **kwargs):+ triples = []+ for rel in relations:+ triples.append(Triple(+ subject=rel.subject.text,+ predicate=rel.predicate,+ object=rel.object.text,+ confidence=rel.confidence+ ))+ return triples++ mock_get.return_value = mock_extract++ extractor = TripleExtractor()+ triples = extractor.extract_triples(self.text, self.entities, self.relations)++ self.assertEqual(len(triples), 2)+ self.assertEqual(triples[0].subject, "Apple Inc.")+ self.assertEqual(triples[0].predicate, "founded_by")+ self.assertEqual(triples[0].object, "Steve Jobs")++ def test_triple_validator(self):+ """Test TripleValidator"""+ validator = TripleValidator()++ # Create a valid and invalid triple+ valid_triple = Triple(subject="S", predicate="P", object="O", confidence=0.9)+ invalid_triple = Triple(subject="", predicate="P", object="O", confidence=0.9) # Empty subject+ low_conf_triple = Triple(subject="S", predicate="P", object="O", confidence=0.2)++ triples = [valid_triple, invalid_triple, low_conf_triple]++ validated = validator.validate_triples(triples, min_confidence=0.5)++ self.assertEqual(len(validated), 1)+ self.assertEqual(validated[0], valid_triple)++ def test_rdf_serializer(self):+ """Test RDFSerializer"""+ serializer = RDFSerializer()+ triple = Triple(subject="Apple_Inc", predicate="founded_by", object="Steve_Jobs")++ # Test N-Triples format+ rdf_output = serializer.serialize_to_rdf([triple], format="ntriples")+ self.assertIsInstance(rdf_output, str)+ # Check if basic components are in the output (format might vary slightly)+ # N-Triples: <subject> <predicate> <object> .+ # The serializer might handle URIs, let's just check non-empty+ self.assertTrue(len(rdf_output) > 0)++ def test_triple_quality_checker(self):+ """Test TripleQualityChecker"""+ checker = TripleQualityChecker()+ triples = [+ Triple(subject="Apple", predicate="founded", object="Jobs", confidence=0.9),+ Triple(subject="Apple", predicate="located", object="US", confidence=0.8)+ ]++ scores = checker.calculate_quality_scores(triples)++ self.assertIn("average_score", scores)+ self.assertAlmostEqual(scores["average_score"], 0.85)+ # triple_count is not returned by calculate_quality_scores+ # self.assertIn("triple_count", scores)+ # self.assertEqual(scores["triple_count"], 2)++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_semantic_extract_deepdive_part2.py b/tests/test_semantic_extract_deepdive_part2.pynew file mode 100644index 00000000..034a651f--- /dev/null+++ b/tests/test_semantic_extract_deepdive_part2.py@@ -0,0 +1,233 @@++import unittest+import sys+import os+from unittest.mock import MagicMock, patch+from dataclasses import dataclass++# Add project root to path+sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))++from semantica.semantic_extract.named_entity_recognizer import (+ NamedEntityRecognizer, EntityClassifier, EntityConfidenceScorer, CustomEntityDetector+)+from semantica.semantic_extract.ner_extractor import NERExtractor, Entity+from semantica.semantic_extract.relation_extractor import RelationExtractor, Relation+from semantica.semantic_extract.triple_extractor import TripleExtractor, Triple+from semantica.semantic_extract.event_detector import EventDetector, Event+from semantica.semantic_extract.semantic_analyzer import SemanticAnalyzer, SemanticRole+from semantica.semantic_extract.methods import (+ extract_entities_regex, extract_entities_rules,+ extract_relations_regex, extract_relations_dependency,+ extract_triples_rules+)++class TestSemanticExtractDeepDivePart2(unittest.TestCase):++ def setUp(self):+ self.text = "Steve Jobs founded Apple Inc. in 1976."+ self.entities = [+ Entity(text="Steve Jobs", label="PERSON", start_char=0, end_char=10),+ Entity(text="Apple Inc.", label="ORG", start_char=19, end_char=29),+ Entity(text="1976", label="DATE", start_char=33, end_char=37)+ ]++ # --- Entity Classifier Tests ---++ def test_entity_classifier(self):+ """Test EntityClassifier type classification"""+ classifier = EntityClassifier()++ # Test type normalization+ e1 = Entity(text="Steve", label="PER", start_char=0, end_char=5)+ type1 = classifier.classify_entity_type(e1)+ self.assertEqual(type1, "PERSON")++ e2 = Entity(text="Apple", label="ORGANIZATION", start_char=0, end_char=5)+ type2 = classifier.classify_entity_type(e2)+ self.assertEqual(type2, "ORG")++ e3 = Entity(text="Unknown", label="CUSTOM", start_char=0, end_char=7)+ type3 = classifier.classify_entity_type(e3)+ self.assertEqual(type3, "CUSTOM")++ def test_entity_classifier_disambiguation(self):+ """Test EntityClassifier disambiguation"""+ classifier = EntityClassifier()++ target = Entity(text="Apple", label="ORG", start_char=0, end_char=5)+ candidates = [+ Entity(text="Apple", label="FRUIT", start_char=0, end_char=5, confidence=0.6),+ Entity(text="Apple", label="ORG", start_char=0, end_char=5, confidence=0.9),+ Entity(text="Apple", label="ORG", start_char=0, end_char=5, confidence=0.5)+ ]++ best = classifier.disambiguate_entity(target, candidates)+ self.assertIsNotNone(best)+ self.assertEqual(best.label, "ORG")+ self.assertEqual(best.confidence, 0.9)++ # --- Entity Confidence Scorer Tests ---++ def test_entity_confidence_scorer(self):+ """Test EntityConfidenceScorer"""+ scorer = EntityConfidenceScorer()++ # Test scoring adjustments+ e1 = Entity(text="s", label="PERSON", start_char=0, end_char=1) # Too short+ scored_e1 = scorer.score_entities([e1])[0]+ self.assertLess(scored_e1.confidence, 1.0)++ e2 = Entity(text="steve jobs", label="PERSON", start_char=0, end_char=10) # Lowercase person+ scored_e2 = scorer.score_entities([e2])[0]+ self.assertLess(scored_e2.confidence, 1.0)++ e3 = Entity(text="1999", label="DATE", start_char=0, end_char=4) # Digit date+ # Should be boosted (capped at 1.0)+ scored_e3 = scorer.score_entities([e3])[0]+ self.assertLessEqual(scored_e3.confidence, 1.0)++ # --- Custom Entity Detector Tests ---++ def test_custom_entity_detector(self):+ """Test CustomEntityDetector"""+ config = {+ "patterns": {+ "PROJECT": r"Project\s+[A-Z]\w+"+ }+ }+ detector = CustomEntityDetector(**config)+ text = "We are working on Project Apollo and Project Gemini."++ entities = detector.detect_custom_entities(text, "PROJECT")+ self.assertEqual(len(entities), 2)+ self.assertEqual(entities[0].text, "Project Apollo")+ self.assertEqual(entities[0].label, "PROJECT")+ self.assertEqual(entities[1].text, "Project Gemini")++ # --- Method Implementation Tests ---++ def test_extract_entities_regex(self):+ """Test regex-based entity extraction"""+ text = "Contact [email protected] or [email protected]"+ patterns = {"EMAIL": r"[\w\.-]+@[\w\.-]+"}++ entities = extract_entities_regex(text, patterns=patterns)+ self.assertEqual(len(entities), 2)+ self.assertEqual(entities[0].label, "EMAIL")+ self.assertEqual(entities[0].text, "[email protected]")++ def test_extract_entities_rules(self):+ """Test rule-based entity extraction (sentence start rule)"""+ text = "Alice went to the park. Bob stayed home."+ # Assuming rule: Capitalized word at start of sentence is PERSON+ entities = extract_entities_rules(text)++ # This depends on exact implementation details in methods.py+ # Current impl: Checks first word of sentence+ names = [e.text for e in entities]+ self.assertIn("Alice", names)+ self.assertIn("Bob", names)++ def test_extract_relations_regex(self):+ """Test regex-based relation extraction"""+ text = "London is located in UK"+ entities = [+ Entity(text="London", label="GPE", start_char=0, end_char=6),+ Entity(text="UK", label="GPE", start_char=21, end_char=23)+ ]++ relations = extract_relations_regex(text, entities)+ self.assertTrue(len(relations) > 0)+ self.assertEqual(relations[0].predicate, "located_in")++ @patch("semantica.semantic_extract.methods.SPACY_AVAILABLE", False)+ @patch("semantica.semantic_extract.methods.extract_relations_pattern")+ def test_extract_relations_dependency_fallback(self, mock_pattern):+ """Test dependency extraction fallback when spaCy is missing"""+ mock_pattern.return_value = []+ extract_relations_dependency("text", [])+ mock_pattern.assert_called_once()++ def test_extract_triples_rules(self):+ """Test rule-based triple extraction"""+ text = "Steve founded Apple"+ entities = [+ Entity(text="Steve", label="PERSON", start_char=0, end_char=5),+ Entity(text="Apple", label="ORG", start_char=14, end_char=19)+ ]++ triples = extract_triples_rules(text, entities)+ self.assertTrue(len(triples) > 0)+ self.assertEqual(triples[0].predicate, "founded")+ self.assertEqual(triples[0].subject, "Steve")+ self.assertEqual(triples[0].object, "Apple")++ # --- Event Detector Tests ---++ def test_event_detector_basic(self):+ """Test EventDetector basic flow"""+ # EventDetector uses internal patterns, so we test with text matching those patterns+ # Patterns include: founded, acquired, launched, etc.+ text = "Apple was founded by Steve Jobs in 1976."++ # Mock _extract_participants to avoid complex logic and potential flake+ # or just let it run if it's simple. It looks simple in the code.+ # But we must be careful.++ detector = EventDetector()+ events = detector.detect_events(text)++ self.assertTrue(len(events) > 0)+ self.assertEqual(events[0].event_type, "founded")+ # Check if participants were extracted (simple capitalization rule)+ # "Steve" and "Jobs" should be captured.+ # The logic captures capitalized words > 2 chars.+ # "Apple" (if in context), "Steve", "Jobs" might be captured.++ # We'll check if "Steve" or "Jobs" is in participants list+ participants = events[0].participants+ self.assertTrue(any("Steve" in p for p in participants) or any("Jobs" in p for p in participants))++ # --- Semantic Analyzer Tests ---++ def test_semantic_analyzer_similarity(self):+ """Test SemanticAnalyzer similarity"""+ analyzer = SemanticAnalyzer()+ # Jaccard similarity+ s1 = "apple banana"+ s2 = "apple orange"+ score = analyzer.calculate_similarity(s1, s2, method="jaccard")+ # intersection: apple (1), union: apple, banana, orange (3) -> 1/3 ~ 0.33+ self.assertAlmostEqual(score, 1/3)++ # --- Coreference Resolver Tests ---++ def test_coreference_resolver_pronouns(self):+ """Test CoreferenceResolver pronoun resolution"""+ from semantica.semantic_extract.coreference_resolver import CoreferenceResolver, Mention++ resolver = CoreferenceResolver()++ # "Steve Jobs founded Apple. He was the CEO."+ # We need to manually construct mentions because we are testing the resolver logic+ # independent of the entity extractor for this unit test++ mentions = [+ Mention(text="Steve Jobs", start_char=0, end_char=10, mention_type="entity", entity_id="e1"),+ Mention(text="Apple", start_char=19, end_char=24, mention_type="entity", entity_id="e2"),+ Mention(text="He", start_char=26, end_char=28, mention_type="pronoun")+ ]++ text = "Steve Jobs founded Apple. He was the CEO."++ # Use the pronoun resolver directly or via main resolver+ resolutions = resolver.pronoun_resolver.resolve_pronouns(text, mentions)++ self.assertTrue(len(resolutions) > 0)+ # Should resolve "He" to "Steve Jobs" (closest preceding entity)+ self.assertEqual(resolutions[0][0], "He")+ self.assertEqual(resolutions[0][1], "Steve Jobs")++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_semantic_extract_triples.py b/tests/test_semantic_extract_triples.pynew file mode 100644index 00000000..815a3e88--- /dev/null+++ b/tests/test_semantic_extract_triples.py@@ -0,0 +1,145 @@++import unittest+import sys+import os+from unittest.mock import MagicMock, patch++# Add project root to path+sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))++from semantica.semantic_extract.triple_extractor import (+ TripleExtractor, Triple, TripleValidator, RDFSerializer, TripleQualityChecker+)+from semantica.semantic_extract.ner_extractor import Entity+from semantica.semantic_extract.relation_extractor import Relation++class TestSemanticExtractTriples(unittest.TestCase):++ def setUp(self):+ self.entities = [+ Entity(text="Steve Jobs", label="PERSON", start_char=0, end_char=10),+ Entity(text="Apple", label="ORG", start_char=19, end_char=24)+ ]+ self.relations = [+ Relation(+ subject=self.entities[0],+ predicate="founded",+ object=self.entities[1],+ confidence=0.9,+ context="Steve Jobs founded Apple."+ )+ ]+ self.triples = [+ Triple(subject="Steve_Jobs", predicate="founded", object="Apple", confidence=0.9),+ Triple(subject="Apple", predicate="located_in", object="Cupertino", confidence=0.8)+ ]++ # --- Triple Extractor Tests ---++ def test_triple_extractor_init(self):+ """Test TripleExtractor initialization"""+ extractor = TripleExtractor()+ self.assertIsNotNone(extractor.triple_validator)+ self.assertIsNotNone(extractor.rdf_serializer)+ self.assertIsNotNone(extractor.quality_checker)++ def test_triple_extractor_extract_from_relations(self):+ """Test extracting triples by converting relations (fallback/default)"""+ extractor = TripleExtractor(method=[]) # No specific method, force fallback++ # Mocking progress tracker to avoid console clutter/errors+ extractor.progress_tracker = MagicMock()++ triples = extractor.extract_triples(+ text="Steve Jobs founded Apple.",+ entities=self.entities,+ relationships=self.relations+ )++ self.assertEqual(len(triples), 1)+ # Predicate is formatted as URI+ self.assertTrue(triples[0].predicate.endswith("founded") or triples[0].predicate == "founded")+ # Check URI formatting (simple implementation in _format_uri)+ # "Steve Jobs" -> "Steve_Jobs", prepended with http://example.org/ if not http+ self.assertIn("Steve_Jobs", triples[0].subject)++ # --- Triple Validator Tests ---++ def test_triple_validator_valid(self):+ """Test TripleValidator with valid triple"""+ validator = TripleValidator()+ triple = Triple(subject="S", predicate="P", object="O", confidence=0.9)+ self.assertTrue(validator.validate_triple(triple))++ def test_triple_validator_invalid_structure(self):+ """Test TripleValidator with missing fields"""+ validator = TripleValidator()+ triple = Triple(subject="", predicate="P", object="O") # Empty subject+ self.assertFalse(validator.validate_triple(triple))++ def test_triple_validator_low_confidence(self):+ """Test TripleValidator confidence threshold"""+ validator = TripleValidator()+ triple = Triple(subject="S", predicate="P", object="O", confidence=0.4)+ self.assertFalse(validator.validate_triple(triple, min_confidence=0.5))++ # --- RDF Serializer Tests ---++ def test_rdf_serializer_turtle(self):+ """Test RDF serialization to Turtle"""+ serializer = RDFSerializer()+ output = serializer.serialize_to_rdf(self.triples, format="turtle")+ self.assertIn("@prefix", output)+ self.assertIn("Steve_Jobs", output)+ self.assertIn("founded", output)+ self.assertIn("Apple", output)+ self.assertTrue(output.strip().endswith("."))++ def test_rdf_serializer_ntriples(self):+ """Test RDF serialization to N-Triples"""+ serializer = RDFSerializer()+ output = serializer.serialize_to_rdf(self.triples, format="ntriples")+ self.assertNotIn("@prefix", output)+ self.assertIn("<Steve_Jobs>", output)+ self.assertIn("<founded>", output)++ def test_rdf_serializer_jsonld(self):+ """Test RDF serialization to JSON-LD"""+ serializer = RDFSerializer()+ output = serializer.serialize_to_rdf(self.triples, format="jsonld")+ import json+ data = json.loads(output)+ self.assertIn("@graph", data)+ self.assertEqual(len(data["@graph"]), 2)++ def test_rdf_serializer_xml(self):+ """Test RDF serialization to XML"""+ serializer = RDFSerializer()+ output = serializer.serialize_to_rdf(self.triples, format="xml")+ self.assertIn("rdf:RDF", output)+ self.assertIn("rdf:Description", output)++ # --- Triple Quality Checker Tests ---++ def test_triple_quality_checker_assess(self):+ """Test TripleQualityChecker assessment"""+ checker = TripleQualityChecker()+ triple = Triple(subject="S", predicate="P", object="O", confidence=0.85)+ assessment = checker.assess_triple_quality(triple)++ self.assertEqual(assessment["confidence"], 0.85)+ self.assertEqual(assessment["completeness"], 1.0)+ self.assertEqual(assessment["quality_score"], 0.85)++ def test_triple_quality_checker_stats(self):+ """Test TripleQualityChecker statistics"""+ checker = TripleQualityChecker()+ stats = checker.calculate_quality_scores(self.triples)++ # Implementation returns average_score, min_score, max_score, high_quality, medium_quality, low_quality+ self.assertIn("average_score", stats)+ self.assertIn("high_quality", stats) # 0.9 and 0.8 are >= 0.8+ self.assertEqual(stats["high_quality"], 2)++if __name__ == '__main__':+ unittest.main()