Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Refactor terminology: Triple -> Triplet across codebase, docs, and notebooks

KaifAhmad14fdc4839350d
diff --git a/README.md b/README.md
index 32e99109..d25373a9 100644
--- a/README.md
+++ b/README.md
@@ -102,7 +102,7 @@ flowchart TD
D --> E[Semantic Layer<br/>Core Intelligence]
E --> F[Entity Extraction<br/>NER + LLM Enhancement]
- E --> G[Relationship Mapping<br/>Triple Generation]
+ E --> G[Relationship Mapping<br/>Triplet Generation]
E --> H[Ontology Generation<br/>6-Stage Pipeline]
E --> I[Context Engineering<br/>Semantic Enrichment]
E --> J[Quality Assurance<br/>Conflict Detection]
@@ -155,7 +155,7 @@ flowchart TD
**Universal Data Ingestion** — Handles 50+ formats (PDF, DOCX, HTML, JSON, CSV, databases, APIs, streams) with unified pipeline, no custom parsers needed.
-**Automated Semantic Extraction** — NER, relationship extraction, and triple generation with LLM enhancement discovers entities and relationships automatically.
+**Automated Semantic Extraction** — NER, relationship extraction, and triplet generation with LLM enhancement discovers entities and relationships automatically.
**Knowledge Graph Construction** — Production-ready graphs with entity resolution, temporal support, and graph analytics. Queryable knowledge ready for AI applications.
@@ -174,7 +174,7 @@ flowchart TD
| **Feature Category** | **Capabilities** | **Key Benefits** |
|:---------------------|:-----------------|:------------------|
| **Data Ingestion** | 50+ formats (PDF, DOCX, HTML, JSON, CSV, databases, APIs, streams, archives) | Universal ingestion, no custom parsers needed |
-| **Semantic Extraction** | NER, relationship extraction, triple generation, LLM enhancement | Automated discovery of entities and relationships |
+| **Semantic Extraction** | NER, relationship extraction, triplet generation, LLM enhancement | Automated discovery of entities and relationships |
| **Knowledge Graphs** | Entity resolution, temporal support, graph analytics, query interface | Production-ready, queryable knowledge structures |
| **Ontology Generation** | 6-stage LLM pipeline, OWL generation, HermiT/Pellet validation | Automated ontology creation from documents |
| **GraphRAG** | Hybrid vector + graph retrieval, multi-hop reasoning | 91% accuracy, 30% improvement over vector-only |
@@ -284,7 +284,7 @@ print(f" Ingested {len(sources)} sources")
### Semantic Intelligence Engine
-> **Entity & Relation Extraction** • NER, Relationships, Events, Triples with LLM Enhancement
+> **Entity & Relation Extraction** • NER, Relationships, Events, Triplets with LLM Enhancement
```python
from semantica import Semantica
diff --git a/cookbook/advanced/01_Advanced_Extraction.ipynb b/cookbook/advanced/01_Advanced_Extraction.ipynb
index 38736d04..8818109f 100644
--- a/cookbook/advanced/01_Advanced_Extraction.ipynb
+++ b/cookbook/advanced/01_Advanced_Extraction.ipynb
@@ -10,7 +10,7 @@
"\n",
"## Overview\n",
"\n",
- "This notebook demonstrates advanced semantic extraction using EventDetector, CoreferenceResolver, TripleExtractor, SemanticAnalyzer, SemanticNetworkExtractor, LLMEnhancer, and ExtractionValidator.\n",
+ "This notebook demonstrates advanced semantic extraction using EventDetector, CoreferenceResolver, TripletExtractor, SemanticAnalyzer, SemanticNetworkExtractor, LLMEnhancer, and ExtractionValidator.\n",
"\n",
"\n",
"**Documentation**: [API Reference](https://semantica.readthedocs.io/reference/semantic_extract/)\n",
@@ -19,7 +19,7 @@
"\n",
"- Use EventDetector to detect events\n",
"- Use CoreferenceResolver to resolve coreferences\n",
- "- Use TripleExtractor to extract RDF triples\n",
+ "- Use TripletExtractor to extract RDF triplets\n",
"- Use SemanticAnalyzer for semantic analysis\n",
"- Use SemanticNetworkExtractor to extract semantic networks\n",
"- Use LLMEnhancer for LLM-based enhancement\n",
@@ -37,7 +37,7 @@
"\n",
"---\n",
"\n",
- "## Workflow: Event Detection \u2192 Coreference Resolution \u2192 Triple Extraction \u2192 Semantic Analysis \u2192 Network Extraction \u2192 LLM Enhancement \u2192 Validation\n"
+ "## Workflow: Event Detection \u2192 Coreference Resolution \u2192 Triplet Extraction \u2192 Semantic Analysis \u2192 Network Extraction \u2192 LLM Enhancement \u2192 Validation\n"
]
},
{
@@ -56,7 +56,7 @@
"outputs": [],
"source": [
"from semantica.semantic_extract import (\n",
- " EventDetector, CoreferenceResolver, TripleExtractor,\n",
+ " EventDetector, CoreferenceResolver, TripletExtractor,\n",
" SemanticAnalyzer, SemanticNetworkExtractor, LLMEnhancer, ExtractionValidator\n",
")\n",
"\n",
@@ -96,9 +96,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "## Step 3: Triple Extraction\n",
+ "## Step 3: Triplet Extraction\n",
"\n",
- "Extract RDF triples.\n"
+ "Extract RDF triplets.\n"
]
},
{
@@ -107,13 +107,13 @@
"metadata": {},
"outputs": [],
"source": [
- "triple_extractor = TripleExtractor()\n",
+ "triplet_extractor = TripletExtractor()\n",
"\n",
- "triples = triple_extractor.extract_triples(text)\n",
+ "triplets = triplet_extractor.extract_triplets(text)\n",
"\n",
- "print(f\"Extracted {len(triples)} triples\")\n",
- "for triple in triples[:3]:\n",
- " print(f\" ({triple.get('subject', '')}, {triple.get('predicate', '')}, {triple.get('object', '')})\")\n"
+ "print(f\"Extracted {len(triplets)} triplets\")\n",
+ "for triplet in triplets[:3]:\n",
+ " print(f\" ({triplet.get('subject', '')}, {triplet.get('predicate', '')}, {triplet.get('object', '')})\")\n"
]
},
{
@@ -217,7 +217,7 @@
"\n",
"- **EventDetector**: Event detection and classification\n",
"- **CoreferenceResolver**: Coreference resolution\n",
- "- **TripleExtractor**: RDF triple extraction\n",
+ "- **TripletExtractor**: RDF triplet extraction\n",
"- **SemanticAnalyzer**: Semantic analysis and role labeling\n",
"- **SemanticNetworkExtractor**: Semantic network extraction\n",
"- **LLMEnhancer**: LLM-based extraction enhancement\n",
diff --git a/cookbook/advanced/02_Advanced_Graph_Analytics.ipynb b/cookbook/advanced/02_Advanced_Graph_Analytics.ipynb
index 573cdabf..3be19ad3 100644
--- a/cookbook/advanced/02_Advanced_Graph_Analytics.ipynb
+++ b/cookbook/advanced/02_Advanced_Graph_Analytics.ipynb
@@ -262,7 +262,7 @@
"- **ConnectivityAnalyzer**: Connectivity analysis\n",
"- **GraphValidator**: Graph validation\n",
"- **Deduplicator**: Graph deduplication\n",
- "- **GraphStore**: Persist graphs to Neo4j or FalkorDB\n",
+ "- **GraphStore**: Persist graphs to Neo4j or FalkorDB\n"
]
}
],
diff --git a/cookbook/introduction/01_Welcome_to_Semantica.ipynb b/cookbook/introduction/01_Welcome_to_Semantica.ipynb
index 3538e9c9..b9e86174 100644
--- a/cookbook/introduction/01_Welcome_to_Semantica.ipynb
+++ b/cookbook/introduction/01_Welcome_to_Semantica.ipynb
@@ -354,7 +354,7 @@
"| **`embeddings`** | **Vector Embeddings**<br>Generates semantic vectors. | • Text & Graph embeddings<br>• Multi-provider support (OpenAI, etc.) |\n",
"| **`vector_store`** | **Vector Database**<br>Stores and searches vectors. | • Similarity search & Filtering<br>• Hybrid search (Vector + Keyword) |\n",
"| **`graph_store`** | **Property Graph Store**<br>Persists graph data. | • Neo4j, FalkorDB adapters<br>• Cypher query support |\n",
- "| **`triplet_store`** | **RDF Store**<br>Persists semantic triples. | • SPARQL endpoints<br>• BlazeGraph, Jena, Virtuoso adapters |\n",
+ "| **`triplet_store`** | **RDF Store**<br>Persists semantic triplets. | • SPARQL endpoints<br>• BlazeGraph, Jena, Virtuoso adapters |\n",
"\n",
"### 🔎 Reasoning & Analysis\n",
"Modules for deriving new knowledge and evaluating quality.\n",
diff --git a/cookbook/introduction/06_Relation_Extraction.ipynb b/cookbook/introduction/06_Relation_Extraction.ipynb
index 102b8883..1003a0b9 100644
--- a/cookbook/introduction/06_Relation_Extraction.ipynb
+++ b/cookbook/introduction/06_Relation_Extraction.ipynb
@@ -10,7 +10,7 @@
"\n",
"## Overview\n",
"\n",
- "This notebook provides a **comprehensive guide** to extracting relationships between entities and building RDF triples using Semantica's relation extraction modules. You'll learn to identify connections, extract structured triples, and prepare data for knowledge graphs.\n",
+ "This notebook provides a **comprehensive guide** to extracting relationships between entities and building RDF triplets using Semantica's relation extraction modules. You'll learn to identify connections, extract structured triplets, and prepare data for knowledge graphs.\n",
"\n",
"**Documentation**: [API Reference](https://semantica.readthedocs.io/reference/semantic_extract/)\n",
"\n",
@@ -21,21 +21,21 @@
"- Extract relationships using `RelationExtractor`\n",
"- Understand different extraction methods (pattern, dependency, co-occurrence, HuggingFace, LLM)\n",
"- Configure extraction parameters for optimal results\n",
- "- Extract RDF triples with `TripleExtractor`\n",
- "- Validate triples using `TripleValidator`\n",
- "- Serialize triples to RDF formats with `RDFSerializer`\n",
- "- Assess triple quality with `TripleQualityChecker`\n",
- "- Build complete entity \u2192 relation \u2192 triple pipelines\n",
+ "- Extract RDF triplets with `TripletExtractor`\n",
+ "- Validate triplets using `TripletValidator`\n",
+ "- Serialize triplets to RDF formats with `RDFSerializer`\n",
+ "- Assess triplet quality with `TripletQualityChecker`\n",
+ "- Build complete entity \u2192 relation \u2192 triplet pipelines\n",
"\n",
"### What You'll Learn\n",
"\n",
"| Component | Purpose | When to Use |\n",
"|-----------|---------|-------------|\n",
"| `RelationExtractor` | Extract entity relationships | Finding connections |\n",
- "| `TripleExtractor` | Extract RDF triples | Building knowledge graphs |\n",
- "| `TripleValidator` | Validate triple quality | Quality assurance |\n",
+ "| `TripletExtractor` | Extract RDF triplets | Building knowledge graphs |\n",
+ "| `TripletValidator` | Validate triplet quality | Quality assurance |\n",
"| `RDFSerializer` | Serialize to RDF formats | Data export |\n",
- "| `TripleQualityChecker` | Assess triple quality | Quality metrics |\n",
+ "| `TripletQualityChecker` | Assess triplet quality | Quality metrics |\n",
"\n",
"---\n",
"\n",
@@ -336,20 +336,20 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "## Step 5: Triple Extraction\n",
+ "## Step 5: Triplet Extraction\n",
"\n",
- "Extract RDF triples using `TripleExtractor`. Triples are the foundation of knowledge graphs.\n",
+ "Extract RDF triplets using `TripletExtractor`. Triplets are the foundation of knowledge graphs.\n",
"\n",
- "### What are RDF Triples?\n",
+ "### What are RDF Triplets?\n",
"\n",
- "RDF (Resource Description Framework) triples are statements with three parts:\n",
+ "RDF (Resource Description Framework) triplets are statements with three parts:\n",
"- **Subject**: What we're talking about\n",
"- **Predicate**: The property or relationship\n",
"- **Object**: The value or target\n",
"\n",
"Example: `(Apple Inc., founded_by, Steve Jobs)`\n",
"\n",
- "### Why Use Triples?\n",
+ "### Why Use Triplets?\n",
"\n",
"- **Standardized format** for knowledge representation\n",
"- **Compatible** with RDF databases and semantic web\n",
@@ -363,37 +363,37 @@
"metadata": {},
"outputs": [],
"source": [
- "from semantica.semantic_extract import TripleExtractor\n",
+ "from semantica.semantic_extract import TripletExtractor\n",
"\n",
- "# Initialize triple extractor\n",
- "triple_extractor = TripleExtractor(\n",
+ "# Initialize triplet extractor\n",
+ "triplet_extractor = TripletExtractor(\n",
" include_temporal=True, # Include temporal information\n",
" include_provenance=True # Track source sentences\n",
")\n",
"\n",
"# Sample text\n",
- "triple_text = \"\"\"\n",
+ "triplet_text = \"\"\"\n",
"Apple Inc. was founded by Steve Jobs in 1976. The company is based in Cupertino, California.\n",
"Tim Cook became CEO in 2011. Apple develops the iPhone and MacBook products.\n",
"\"\"\"\n",
"\n",
- "# Extract triples\n",
- "triples = triple_extractor.extract_triples(triple_text)\n",
+ "# Extract triplets\n",
+ "triplets = triplet_extractor.extract_triplets(triplet_text)\n",
"\n",
- "print(f\" Extracted {len(triples)} RDF Triples:\\n\")\n",
+ "print(f\" Extracted {len(triplets)} RDF Triplets:\\n\")\n",
"print(\"=\" * 80)\n",
"\n",
- "for i, triple in enumerate(triples, 1):\n",
- " subject = triple.get('subject', '') if isinstance(triple, dict) else triple.subject\n",
- " predicate = triple.get('predicate', '') if isinstance(triple, dict) else triple.predicate\n",
- " obj = triple.get('object', '') if isinstance(triple, dict) else triple.object\n",
- " confidence = triple.get('confidence', 1.0) if isinstance(triple, dict) else getattr(triple, 'confidence', 1.0)\n",
+ "for i, triplet in enumerate(triplets, 1):\n",
+ " subject = triplet.get('subject', '') if isinstance(triplet, dict) else triplet.subject\n",
+ " predicate = triplet.get('predicate', '') if isinstance(triplet, dict) else triplet.predicate\n",
+ " obj = triplet.get('object', '') if isinstance(triplet, dict) else triplet.object\n",
+ " confidence = triplet.get('confidence', 1.0) if isinstance(triplet, dict) else getattr(triplet, 'confidence', 1.0)\n",
" \n",
" print(f\"{i:2d}. ({subject}, {predicate}, {obj})\")\n",
" print(f\" Confidence: {confidence:.2f}\")\n",
" \n",
" # Show temporal info if available\n",
- " metadata = triple.get('metadata', {}) if isinstance(triple, dict) else getattr(triple, 'metadata', {})\n",
+ " metadata = triplet.get('metadata', {}) if isinstance(triplet, dict) else getattr(triplet, 'metadata', {})\n",
" if metadata.get('temporal'):\n",
" print(f\" Temporal: {metadata['temporal']}\")\n",
" print()\n",
@@ -405,11 +405,11 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "## Step 6: Triple Validation\n",
+ "## Step 6: Triplet Validation\n",
"\n",
- "Validate extracted triples using `TripleValidator` and assess quality with `TripleQualityChecker`.\n",
+ "Validate extracted triplets using `TripletValidator` and assess quality with `TripletQualityChecker`.\n",
"\n",
- "### Why Validate Triples?\n",
+ "### Why Validate Triplets?\n",
"\n",
"- **Ensure completeness**: All parts (subject, predicate, object) present\n",
"- **Check confidence**: Filter low-quality extractions\n",
@@ -423,25 +423,25 @@
"metadata": {},
"outputs": [],
"source": [
- "from semantica.semantic_extract import TripleValidator, TripleQualityChecker\n",
+ "from semantica.semantic_extract import TripletValidator, TripletQualityChecker\n",
"\n",
"# Initialize validator and quality checker\n",
- "validator = TripleValidator()\n",
- "quality_checker = TripleQualityChecker()\n",
+ "validator = TripletValidator()\n",
+ "quality_checker = TripletQualityChecker()\n",
"\n",
- "print(\" Triple Validation:\\n\")\n",
+ "print(\" Triplet Validation:\\n\")\n",
"print(\"=\" * 80)\n",
"\n",
- "# Validate triples\n",
- "valid_triples = validator.validate_triples(triples, min_confidence=0.5)\n",
+ "# Validate triplets\n",
+ "valid_triplets = validator.validate_triplets(triplets, min_confidence=0.5)\n",
"\n",
"print(f\"\\n Validation Results:\")\n",
- "print(f\" Total triples: {len(triples)}\")\n",
- "print(f\" Valid triples: {len(valid_triples)}\")\n",
- "print(f\" Filtered out: {len(triples) - len(valid_triples)}\")\n",
+ "print(f\" Total triplets: {len(triplets)}\")\n",
+ "print(f\" Valid triplets: {len(valid_triplets)}\")\n",
+ "print(f\" Filtered out: {len(triplets) - len(valid_triplets)}\")\n",
"\n",
"# Check quality\n",
- "quality_scores = quality_checker.calculate_quality_scores(valid_triples)\n",
+ "quality_scores = quality_checker.calculate_quality_scores(valid_triplets)\n",
"\n",
"print(f\"\\n Quality Metrics:\")\n",
"print(\"-\" * 40)\n",
@@ -452,7 +452,7 @@
" print(f\" {metric}: {value}\")\n",
"\n",
"# Check consistency\n",
- "consistency_report = validator.check_triple_consistency(valid_triples)\n",
+ "consistency_report = validator.check_triplet_consistency(valid_triplets)\n",
"\n",
"print(f\"\\n Consistency Check:\")\n",
"print(f\" Consistent: {consistency_report.get('consistent', True)}\")\n",
@@ -467,7 +467,7 @@
"source": [
"## Step 7: RDF Serialization\n",
"\n",
- "Serialize triples to various RDF formats using `RDFSerializer`.\n",
+ "Serialize triplets to various RDF formats using `RDFSerializer`.\n",
"\n",
"### Supported Formats:\n",
"\n",
@@ -501,7 +501,7 @@
" print(\"-\" * 40)\n",
" \n",
" try:\n",
- " serialized = serializer.serialize_to_rdf(valid_triples[:3], format=fmt) # Show first 3\n",
+ " serialized = serializer.serialize_to_rdf(valid_triplets[:3], format=fmt) # Show first 3\n",
" \n",
" # Show preview (first 300 chars)\n",
" preview = serialized[:300] + \"...\" if len(serialized) > 300 else serialized\n",
@@ -519,7 +519,7 @@
"source": [
"## Step 8: Complete Extraction Pipeline\n",
"\n",
- "Let's build a complete pipeline: **Entities \u2192 Relations \u2192 Triples**\n",
+ "Let's build a complete pipeline: **Entities \u2192 Relations \u2192 Triplets**\n",
"\n",
"This demonstrates the full workflow for knowledge graph construction."
]
@@ -538,7 +538,7 @@
" text: Input text\n",
" \n",
" Returns:\n",
- " dict: Extracted entities, relations, and triples\n",
+ " dict: Extracted entities, relations, and triplets\n",
" \"\"\"\n",
" # Step 1: Extract entities\n",
" entities = ner_extractor.extract(text)\n",
@@ -546,16 +546,16 @@
" # Step 2: Extract relations\n",
" relations = relation_extractor.extract(text, entities)\n",
" \n",
- " # Step 3: Extract triples\n",
- " triples = triple_extractor.extract_triples(text, entities=entities, relationships=relations)\n",
+ " # Step 3: Extract triplets\n",
+ " triplets = triplet_extractor.extract_triplets(text, entities=entities, relationships=relations)\n",
" \n",
- " # Step 4: Validate triples\n",
- " valid_triples = validator.validate_triples(triples)\n",
+ " # Step 4: Validate triplets\n",
+ " valid_triplets = validator.validate_triplets(triplets)\n",
" \n",
" return {\n",
" 'entities': entities,\n",
" 'relations': relations,\n",
- " 'triples': valid_triples\n",
+ " 'triplets': valid_triplets\n",
" }\n",
"\n",
"# Sample knowledge-rich text\n",
@@ -576,13 +576,13 @@
"print(\"-\" * 40)\n",
"print(f\"Entities extracted: {len(result['entities'])}\")\n",
"print(f\"Relations extracted: {len(result['relations'])}\")\n",
- "print(f\"Triples extracted: {len(result['triples'])}\")\n",
+ "print(f\"Triplets extracted: {len(result['triplets'])}\")\n",
"\n",
- "print(f\"\\n Sample Triples:\")\n",
- "for i, triple in enumerate(result['triples'][:5], 1):\n",
- " subject = triple.get('subject', '') if isinstance(triple, dict) else triple.subject\n",
- " predicate = triple.get('predicate', '') if isinstance(triple, dict) else triple.predicate\n",
- " obj = triple.get('object', '') if isinstance(triple, dict) else triple.object\n",
+ "print(f\"\\n Sample Triplets:\")\n",
+ "for i, triplet in enumerate(result['triplets'][:5], 1):\n",
+ " subject = triplet.get('subject', '') if isinstance(triplet, dict) else triplet.subject\n",
+ " predicate = triplet.get('predicate', '') if isinstance(triplet, dict) else triplet.predicate\n",
+ " obj = triplet.get('object', '') if isinstance(triplet, dict) else triplet.object\n",
" print(f\" {i}. ({subject}, {predicate}, {obj})\")\n",
"\n",
"print(\"\\n\" + \"=\" * 80)"
@@ -606,28 +606,28 @@
"- **Set confidence thresholds** (0.6-0.7 for production)\n",
"- **Specify relation_types** to focus extraction\n",
"- **Adjust max_distance** based on text structure\n",
- "- **Validate triples** before using in knowledge graphs\n",
+ "- **Validate triplets** before using in knowledge graphs\n",
"\n",
"### Common Pitfalls to Avoid\n",
"\n",
"- **Don't** skip entity extraction (relations need entities)\n",
"- **Don't** use very low confidence thresholds\n",
"- **Don't** ignore relation validation\n",
- "- **Don't** forget to serialize triples for storage\n",
+ "- **Don't** forget to serialize triplets for storage\n",
"\n",
"### When to Use Each Component\n",
"\n",
"| Use Case | Recommended Component |\n",
"|----------|----------------------|\n",
"| Find entity connections | `RelationExtractor` |\n",
- "| Build knowledge graphs | `TripleExtractor` |\n",
- "| Quality assurance | `TripleValidator` |\n",
+ "| Build knowledge graphs | `TripletExtractor` |\n",
+ "| Quality assurance | `TripletValidator` |\n",
"| Export to RDF | `RDFSerializer` |\n",
- "| Assess extraction quality | `TripleQualityChecker` |\n",
+ "| Assess extraction quality | `TripletQualityChecker` |\n",
"\n",
"### Performance Tips\n",
"\n",
- "1. **Extract entities once**, reuse for relations and triples\n",
+ "1. **Extract entities once**, reuse for relations and triplets\n",
"2. **Batch process** multiple documents together\n",
"3. **Cache extractors** instead of recreating\n",
"4. **Filter early** with confidence thresholds\n",
@@ -647,25 +647,25 @@
" **Extract relationships** using `RelationExtractor` \n",
" **Compare extraction methods** (pattern, dependency, co-occurrence, HuggingFace, LLM) \n",
" **Configure extraction parameters** for optimal results \n",
- " **Extract RDF triples** with `TripleExtractor` \n",
- " **Validate triples** using `TripleValidator` \n",
+ " **Extract RDF triplets** with `TripletExtractor` \n",
+ " **Validate triplets** using `TripletValidator` \n",
" **Serialize to RDF formats** with `RDFSerializer` \n",
- " **Assess quality** with `TripleQualityChecker` \n",
- " **Build complete pipelines** from entities to triples \n",
+ " **Assess quality** with `TripletQualityChecker` \n",
+ " **Build complete pipelines** from entities to triplets \n",
"\n",
"### Key Takeaways\n",
"\n",
"1. **Relations connect entities**: They form the backbone of knowledge graphs\n",
"2. **Multiple methods available**: Choose based on accuracy vs speed needs\n",
"3. **Configuration is powerful**: Tune parameters for your domain\n",
- "4. **Triples are standardized**: Use RDF for interoperability\n",
- "5. **Validation is essential**: Ensure quality before using triples\n",
- "6. **Pipelines are efficient**: Extract entities \u2192 relations \u2192 triples in sequence\n",
+ "4. **Triplets are standardized**: Use RDF for interoperability\n",
+ "5. **Validation is essential**: Ensure quality before using triplets\n",
+ "6. **Pipelines are efficient**: Extract entities \u2192 relations \u2192 triplets in sequence\n",
"\n",
"### Next Steps\n",
"\n",
" **Next Notebook**: [07_Building_Knowledge_Graphs.ipynb](./07_Building_Knowledge_Graphs.ipynb) \n",
- "Learn how to build complete knowledge graphs from your extracted triples!\n",
+ "Learn how to build complete knowledge graphs from your extracted triplets!\n",
"\n",
" **Further Reading**:\n",
"- [Semantic Extract API Reference](https://semantica.readthedocs.io/reference/semantic_extract/)\n",
diff --git a/cookbook/introduction/11_Chunking_and_Splitting.ipynb b/cookbook/introduction/11_Chunking_and_Splitting.ipynb
index d6ab4d8f..c1cd0deb 100644
--- a/cookbook/introduction/11_Chunking_and_Splitting.ipynb
+++ b/cookbook/introduction/11_Chunking_and_Splitting.ipynb
@@ -34,7 +34,7 @@
"| `TextSplitter` | Unified splitter | All chunking needs |\n",
"| `SemanticChunker` | Semantic boundaries | Topic-based chunks |\n",
"| `EntityAwareChunker` | Preserve entities | GraphRAG workflows |\n",
- "| `RelationAwareChunker` | Preserve triples | KG construction |\n",
+ "| `RelationAwareChunker` | Preserve triplets | KG construction |\n",
"| `StructuralChunker` | Document structure | Formatted documents |\n",
"| `HierarchicalChunker` | Multi-level chunks | Large documents |\n",
"\n",
@@ -183,7 +183,7 @@
"### Why Token-Based?\n",
"\n",
"- **LLM Context Windows**: GPT-4 has 8K/32K token limits\n",
- "- **Accurate Counting**: Character count \u2260 token count\n",
+ "- **Accurate Counting**: Character count ≠ token count\n",
"- **Cost Optimization**: Tokens determine API costs"
]
},
@@ -319,11 +319,11 @@
"source": [
"## Step 6: Relation-Aware Chunking\n",
"\n",
- "Relation-aware chunking preserves relationship triples within chunks.\n",
+ "Relation-aware chunking preserves relationship triplets within chunks.\n",
"\n",
"### Why Relation-Aware?\n",
"\n",
- "- **Preserve Triples**: Keep (subject, predicate, object) together\n",
+ "- **Preserve Triplets**: Keep (subject, predicate, object) together\n",
"- **KG Construction**: Better for building knowledge graphs\n",
"- **Context**: Relationships need complete context"
]
@@ -340,7 +340,7 @@
"relation_chunker = RelationAwareChunker(\n",
" chunk_size=200,\n",
" chunk_overlap=50,\n",
- " preserve_triples=True\n",
+ " preserve_triplets=True\n",
")\n",
"\n",
"chunks = relation_chunker.chunk(text)\n",
@@ -349,12 +349,12 @@
"print(\"=\" * 80)\n",
"\n",
"for i, chunk in enumerate(chunks, 1):\n",
- " triples = chunk.metadata.get('triples', [])\n",
+ " triplets = chunk.metadata.get('triplets', [])\n",
" relationships = chunk.metadata.get('relationships', [])\n",
" \n",
" print(f\"\\nChunk {i}:\")\n",
" print(f\" Length: {len(chunk.text)} chars\")\n",
- " print(f\" Triples: {len(triples)}\")\n",
+ " print(f\" Triplets: {len(triplets)}\")\n",
" print(f\" Relationships: {len(relationships)}\")\n",
"\n",
"print(\"\\n\" + \"=\" * 80)"
@@ -439,7 +439,7 @@
"\n",
"### Benefits\n",
"\n",
- "- **Multiple Granularities**: Document \u2192 Section \u2192 Paragraph\n",
+ "- **Multiple Granularities**: Document → Section → Paragraph\n",
"- **Better Navigation**: Parent-child relationships\n",
"- **Flexible Retrieval**: Query at different levels"
]
@@ -859,4 +859,4 @@
},
"nbformat": 4,
"nbformat_minor": 2
-}
\ No newline at end of file
+}
diff --git a/cookbook/introduction/14_Ontology.ipynb b/cookbook/introduction/14_Ontology.ipynb
index 0f88ade5..ecfc5e61 100644
--- a/cookbook/introduction/14_Ontology.ipynb
+++ b/cookbook/introduction/14_Ontology.ipynb
@@ -320,7 +320,7 @@
"\n",
"## Visualization\n",
"\n",
- "A picture is worth a thousand triples! The `OntologyVisualizer` lets you explore your ontology's structure interactively.\n",
+ "A picture is worth a thousand triplets! The `OntologyVisualizer` lets you explore your ontology's structure interactively.\n",
"\n",
"We can visualize:\n",
"* **Class Hierarchies**: Tree diagrams of class inheritance.\n",
diff --git a/cookbook/introduction/20_Triplet_Store.ipynb b/cookbook/introduction/20_Triplet_Store.ipynb
index 81bbb4b1..45feac8b 100644
--- a/cookbook/introduction/20_Triplet_Store.ipynb
+++ b/cookbook/introduction/20_Triplet_Store.ipynb
@@ -4,7 +4,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/introduction/20_Triple_Store.ipynb)\n",
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/introduction/20_Triplet_Store.ipynb)\n",
"\n",
"# Triplet Store - Comprehensive Guide\n",
"\n",
@@ -74,7 +74,7 @@
"\n",
"`TripletManager` is the main coordinator for triplet store operations:\n",
"- **Store Registration**: Register multiple backends\n",
- "- **CRUD Operations**: Add, get, update, delete triples\n",
+ "- **CRUD Operations**: Add, get, update, delete triplets\n",
"- **Multi-Store**: Manage multiple stores simultaneously"
]
},
@@ -85,9 +85,9 @@
"outputs": [],
"source": [
"from semantica.triplet_store import TripletManager\n",
- "from semantica.semantic_extract.triple_extractor import Triple\n",
+ "from semantica.semantic_extract.triplet_extractor import Triplet\n",
"\n",
- "# Create triple manager\n",
+ "# Create triplet manager\n",
"manager = TripletManager()\n",
"\n",
"# Register a Blazegraph store (in-memory for demo)\n",
@@ -101,18 +101,18 @@
"print(f\"Store type: {store.store_type}\")\n",
"print(f\"Endpoint: {store.endpoint}\")\n",
"\n",
- "# Create a triple\n",
- "triple = Triple(\n",
+ "# Create a triplet\n",
+ "triplet = Triplet(\n",
" subject=\"http://example.org/Alice\",\n",
" predicate=\"http://example.org/knows\",\n",
" object=\"http://example.org/Bob\",\n",
" confidence=0.95\n",
")\n",
"\n",
- "# Add triple to store\n",
- "result = manager.add_triple(triple, store_id=\"demo\")\n",
- "print(f\"\\nTriple added: {result['success']}\")\n",
- "print(f\"Triple: {triple.subject} -> {triple.predicate} -> {triple.object}\")"
+ "# Add triplet to store\n",
+ "result = manager.add_triplet(triplet, store_id=\"demo\")\n",
+ "print(f\"\\nTriplet added: {result['success']}\")\n",
+ "print(f\"Triplet: {triplet.subject} -> {triplet.predicate} -> {triplet.object}\")"
]
},
{
@@ -172,14 +172,14 @@
"source": [
"## Step 3: CRUD Operations\n",
"\n",
- "Perform Create, Read, Update, Delete operations on triples.\n",
+ "Perform Create, Read, Update, Delete operations on triplets.\n",
"\n",
"### Operations Overview\n",
"\n",
- "- **Create**: `add_triple()`, `add_triples()`\n",
- "- **Read**: `get_triple()`\n",
- "- **Update**: `update_triple()`\n",
- "- **Delete**: `delete_triple()`"
+ "- **Create**: `add_triplet()`, `add_triplets()`\n",
+ "- **Read**: `get_triplet()`\n",
+ "- **Update**: `update_triplet()`\n",
+ "- **Delete**: `delete_triplet()`"
]
},
{
@@ -188,43 +188,43 @@
"metadata": {},
"outputs": [],
"source": [
- "from semantica.triplet_store import add_triple, add_triples, get_triples, update_triple, delete_triple\n",
+ "from semantica.triplet_store import add_triplet, add_triplets, get_triplets, update_triplet, delete_triplet\n",
"\n",
- "# Create - Add single triple\n",
- "triple1 = Triple(\n",
+ "# Create - Add single triplet\n",
+ "triplet1 = Triplet(\n",
" subject=\"http://example.org/Alice\",\n",
" predicate=\"http://example.org/hasAge\",\n",
" object=\"30\"\n",
")\n",
- "result = add_triple(triple1, store_id=\"demo\")\n",
- "print(f\"Added single triple: {result['success']}\")\n",
- "\n",
- "# Create - Add multiple triples\n",
- "triples = [\n",
- " Triple(\"http://example.org/Alice\", \"http://example.org/hasCity\", \"New York\"),\n",
- " Triple(\"http://example.org/Bob\", \"http://example.org/hasAge\", \"25\"),\n",
- " Triple(\"http://example.org/Bob\", \"http://example.org/hasCity\", \"Boston\")\n",
+ "result = add_triplet(triplet1, store_id=\"demo\")\n",
+ "print(f\"Added single triplet: {result['success']}\")\n",
+ "\n",
+ "# Create - Add multiple triplets\n",
+ "triplets = [\n",
+ " Triplet(\"http://example.org/Alice\", \"http://example.org/hasCity\", \"New York\"),\n",
+ " Triplet(\"http://example.org/Bob\", \"http://example.org/hasAge\", \"25\"),\n",
+ " Triplet(\"http://example.org/Bob\", \"http://example.org/hasCity\", \"Boston\")\n",
"]\n",
- "result = add_triples(triples, store_id=\"demo\")\n",
- "print(f\"\\nAdded {result['total_triples']} triples in {result['batches']} batches\")\n",
+ "result = add_triplets(triplets, store_id=\"demo\")\n",
+ "print(f\"\\nAdded {result['total_triplets']} triplets in {result['batches']} batches\")\n",
"\n",
- "# Read - Get triples for a subject\n",
- "alice_triples = get_triples(\n",
+ "# Read - Get triplets for a subject\n",
+ "alice_triplets = get_triplets(\n",
" subject=\"http://example.org/Alice\",\n",
" store_id=\"demo\"\n",
")\n",
- "print(f\"\\nFound {len(alice_triples)} triples for Alice\")\n",
+ "print(f\"\\nFound {len(alice_triplets)} triplets for Alice\")\n",
"\n",
"# Update - Change Alice's age\n",
- "old_triple = Triple(\"http://example.org/Alice\", \"http://example.org/hasAge\", \"30\")\n",
- "new_triple = Triple(\"http://example.org/Alice\", \"http://example.org/hasAge\", \"31\")\n",
- "result = update_triple(old_triple, new_triple, store_id=\"demo\")\n",
- "print(f\"\\nUpdated triple: {result['success']}\")\n",
- "\n",
- "# Delete - Remove a triple\n",
- "triple_to_delete = Triple(\"http://example.org/Bob\", \"http://example.org/hasCity\", \"Boston\")\n",
- "result = delete_triple(triple_to_delete, store_id=\"demo\")\n",
- "print(f\"Deleted triple: {result['success']}\")"
+ "old_triplet = Triplet(\"http://example.org/Alice\", \"http://example.org/hasAge\", \"30\")\n",
+ "new_triplet = Triplet(\"http://example.org/Alice\", \"http://example.org/hasAge\", \"31\")\n",
+ "result = update_triplet(old_triplet, new_triplet, store_id=\"demo\")\n",
+ "print(f\"\\nUpdated triplet: {result['success']}\")\n",
+ "\n",
+ "# Delete - Remove a triplet\n",
+ "triplet_to_delete = Triplet(\"http://example.org/Bob\", \"http://example.org/hasCity\", \"Boston\")\n",
+ "result = delete_triplet(triplet_to_delete, store_id=\"demo\")\n",
+ "print(f\"Deleted triplet: {result['success']}\")"
]
},
{
@@ -364,9 +364,9 @@
" max_retries=3\n",
")\n",
"\n",
- "# Generate sample triples\n",
+ "# Generate sample triplets\n",
"large_dataset = [\n",
- " Triple(\n",
+ " Triplet(\n",
" f\"http://example.org/entity{i}\",\n",
" \"http://example.org/hasName\",\n",
" f\"Entity {i}\"\n",
@@ -377,22 +377,22 @@
"# Progress callback\n",
"def progress_callback(progress: LoadProgress):\n",
" print(f\"Progress: {progress.progress_percentage:.1f}% \"\n",
- " f\"({progress.loaded_triples}/{progress.total_triples}) \"\n",
+ " f\"({progress.loaded_triplets}/{progress.total_triplets}) \"\n",
" f\"Batch {progress.current_batch}/{progress.total_batches}\")\n",
"\n",
- "# Load triples with progress tracking\n",
+ "# Load triplets with progress tracking\n",
"adapter = BlazegraphAdapter(endpoint=\"http://localhost:9999/blazegraph/sparql\")\n",
- "progress = loader.load_triples(\n",
+ "progress = loader.load_triplets(\n",
" large_dataset,\n",
" adapter,\n",
" progress_callback=progress_callback\n",
")\n",
"\n",
"print(f\"\\nLoading Complete:\")\n",
- "print(f\" Loaded: {progress.loaded_triples}/{progress.total_triples}\")\n",
- "print(f\" Failed: {progress.failed_triples}\")\n",
+ "print(f\" Loaded: {progress.loaded_triplets}/{progress.total_triplets}\")\n",
+ "print(f\" Failed: {progress.failed_triplets}\")\n",
"print(f\" Elapsed time: {progress.elapsed_time:.2f}s\")\n",
- "print(f\" Throughput: {progress.metadata.get('throughput', 0):.0f} triples/sec\")"
+ "print(f\" Throughput: {progress.metadata.get('throughput', 0):.0f} triplets/sec\")"
]
},
{
@@ -423,11 +423,11 @@
" timeout=30\n",
")\n",
"\n",
- "# Add triples\n",
- "triples = [\n",
- " Triple(\"http://example.org/Alice\", \"http://example.org/hasSkill\", \"Python\")\n",
+ "# Add triplets\n",
+ "triplets = [\n",
+ " Triplet(\"http://example.org/Alice\", \"http://example.org/hasSkill\", \"Python\")\n",
"]\n",
- "result = blazegraph.add_triples(triples)\n",
+ "result = blazegraph.add_triplets(triplets)\n",
"print(f\"Blazegraph - Added: {result['success']}\")\n",
"\n",
"# Execute SPARQL query\n",
@@ -463,20 +463,20 @@
"# enable_inference=True\n",
"# )\n",
"\n",
- "# Add triples with inference\n",
- "triples = [\n",
- " Triple(\n",
+ "# Add triplets with inference\n",
+ "triplets = [\n",
+ " Triplet(\n",
" \"http://example.org/Dog\",\n",
" \"http://www.w3.org/2000/01/rdf-schema#subClassOf\",\n",
" \"http://example.org/Animal\"\n",
" ),\n",
- " Triple(\n",
+ " Triplet(\n",
" \"http://example.org/Fido\",\n",
" \"http://www.w3.org/1999/02/22-rdf-syntax-ns#type\",\n",
" \"http://example.org/Dog\"\n",
" )\n",
"]\n",
- "result = jena.add_triples(triples)\n",
+ "result = jena.add_triplets(triplets)\n",
"print(f\"Jena - Added: {result['success']}\")\n",
"\n",
"# Query with inference (Fido is inferred to be an Animal)\n",
@@ -514,18 +514,18 @@
" repository_id=\"test\"\n",
")\n",
"\n",
- "# Add triples with transaction\n",
+ "# Add triplets with transaction\n",
"rdf4j.begin_transaction()\n",
"try:\n",
- " triple = Triple(\n",
+ " triplet = Triplet(\n",
" \"http://example.org/Alice\",\n",
" \"http://example.org/hasEmail\",\n",
" )\n",
- " rdf4j.add_triple(\n",
- " subject=triple.subject,\n",
- " predicate=triple.predicate,\n",
- " object_literal=triple.object\n",
+ " rdf4j.add_triplet(\n",
+ " subject=triplet.subject,\n",
+ " predicate=triplet.predicate,\n",
+ " object_literal=triplet.object\n",
" )\n",
" rdf4j.commit_transaction()\n",
" print(\"RDF4J - Transaction committed\")\n",
@@ -563,20 +563,20 @@
"graph_uri = \"http://example.org/graph1\"\n",
"virtuoso.create_graph(graph_uri)\n",
"\n",
- "# Add triples to named graph\n",
- "triple = Triple(\n",
+ "# Add triplets to named graph\n",
+ "triplet = Triplet(\n",
" \"http://example.org/Alice\",\n",
" \"http://example.org/worksAt\",\n",
" \"http://example.org/Company1\"\n",
")\n",
- "virtuoso.add_triple(\n",
- " subject=triple.subject,\n",
- " predicate=triple.predicate,\n",
- " object=triple.object,\n",
+ "virtuoso.add_triplet(\n",
+ " subject=triplet.subject,\n",
+ " predicate=triplet.predicate,\n",
+ " object=triplet.object,\n",
" graph=graph_uri\n",
")\n",
"\n",
- "print(f\"Virtuoso - Added triple to graph: {graph_uri}\")\n",
+ "print(f\"Virtuoso - Added triplet to graph: {graph_uri}\")\n",
"\n",
"# Query specific graph\n",
"query = f\"\"\"\n",
@@ -595,9 +595,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "## Step 8: Triple Validation\n",
+ "## Step 8: Triplet Validation\n",
"\n",
- "Validate triples before adding them to the store.\n",
+ "Validate triplets before adding them to the store.\n",
"\n",
"### Validation Checks\n",
"\n",
@@ -613,22 +613,22 @@
"metadata": {},
"outputs": [],
"source": [
- "from semantica.triplet_store import validate_triples\n",
- "\n",
- "# Create triples (some invalid)\n",
- "triples_to_validate = [\n",
- " Triple(\"http://example.org/Alice\", \"http://example.org/knows\", \"http://example.org/Bob\"), # Valid\n",
- " Triple(\"\", \"http://example.org/knows\", \"http://example.org/Charlie\"), # Invalid (empty subject)\n",
- " Triple(\"http://example.org/Dave\", \"\", \"http://example.org/Eve\"), # Invalid (empty predicate)\n",
- " Triple(\"http://example.org/Frank\", \"http://example.org/knows\", \"http://example.org/Grace\", confidence=1.5), # Invalid (confidence > 1)\n",
+ "from semantica.triplet_store import validate_triplets\n",
+ "\n",
+ "# Create triplets (some invalid)\n",
+ "triplets_to_validate = [\n",
+ " Triplet(\"http://example.org/Alice\", \"http://example.org/knows\", \"http://example.org/Bob\"), # Valid\n",
+ " Triplet(\"\", \"http://example.org/knows\", \"http://example.org/Charlie\"), # Invalid (empty subject)\n",
+ " Triplet(\"http://example.org/Dave\", \"\", \"http://example.org/Eve\"), # Invalid (empty predicate)\n",
+ " Triplet(\"http://example.org/Frank\", \"http://example.org/knows\", \"http://example.org/Grace\", confidence=1.5), # Invalid (confidence > 1)\n",
"]\n",
"\n",
- "# Validate triples\n",
- "validation = validate_triples(triples_to_validate)\n",
+ "# Validate triplets\n",
+ "validation = validate_triplets(triplets_to_validate)\n",
"\n",
"print(\"Validation Results:\")\n",
"print(f\" Valid: {validation['valid']}\")\n",
- "print(f\" Valid triples: {validation['valid_triples']}/{validation['total_triples']}\")\n",
+ "print(f\" Valid triplets: {validation['valid_triplets']}/{validation['total_triplets']}\")\n",
"print(f\"\\nErrors: {len(validation['errors'])}\")\n",
"for error in validation['errors']:\n",
" print(f\" - {error}\")\n",
@@ -674,16 +674,16 @@
")\n",
"\n",
"# Add to primary store\n",
- "triple = Triple(\n",
+ "triplet = Triplet(\n",
" \"http://example.org/Document1\",\n",
" \"http://example.org/hasAuthor\",\n",
" \"http://example.org/Alice\"\n",
")\n",
- "manager.add_triple(triple, store_id=\"primary\")\n",
+ "manager.add_triplet(triplet, store_id=\"primary\")\n",
"print(\"Added to primary store\")\n",
"\n",
"# Replicate to backup store\n",
- "manager.add_triple(triple, store_id=\"backup\")\n",
+ "manager.add_triplet(triplet, store_id=\"backup\")\n",
"print(\"Replicated to backup store\")\n",
"\n",
"# List all stores\n",
@@ -706,7 +706,7 @@
"\n",
"### Performance Tips\n",
"\n",
- "- **Batch Operations**: Use `add_triples()` for multiple triples\n",
+ "- **Batch Operations**: Use `add_triplets()` for multiple triplets\n",
"- **Query Optimization**: Enable optimization and caching\n",
"- **Bulk Loading**: Use `BulkLoader` for large datasets\n",
"- **Validation**: Validate before loading to avoid errors\n",
@@ -730,11 +730,11 @@
"In this notebook, you've learned how to:\n",
"\n",
"- Register and manage triplet stores\n",
- "- Perform CRUD operations on RDF triples\n",
+ "- Perform CRUD operations on RDF triplets\n",
"- Execute and optimize SPARQL queries\n",
"- Use bulk loading for large datasets\n",
"- Work with multiple store backends\n",
- "- Validate triples before operations\n",
+ "- Validate triplets before operations\n",
"- Choose the right backend for your use case\n",
"\n",
"### Key Takeaways\n",
diff --git a/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb b/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb
index 623367bb..46f59cd5 100644
--- a/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb
+++ b/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb
@@ -317,7 +317,7 @@
"\n",
"**For Graph Store** (knowledge structure preservation):\n",
"- **Entity-Aware Chunking**: Preserves entity boundaries (prevents splitting entities)\n",
- "- **Relation-Aware Chunking**: Preserves relationship triples (keeps subject-predicate-object together)\n",
+ "- **Relation-Aware Chunking**: Preserves relationship triplets (keeps subject-predicate-object together)\n",
"- **Graph-Based Chunking**: Uses existing graph structure for optimal chunking\n",
"\n",
"We'll create chunks optimized for each store type.\n"
@@ -329,17 +329,17 @@
"metadata": {},
"outputs": [],
"source": [
- "from semantica.semantic_extract import NamedEntityRecognizer, RelationExtractor, TripleExtractor\n",
+ "from semantica.semantic_extract import NamedEntityRecognizer, RelationExtractor, TripletExtractor\n",
"\n",
- "print(\"Extracting entities, relationships, and triples...\")\n",
+ "print(\"Extracting entities, relationships, and triplets...\")\n",
"\n",
"ner = NamedEntityRecognizer()\n",
"rel_extractor = RelationExtractor()\n",
- "triple_extractor = TripleExtractor()\n",
+ "triplet_extractor = TripletExtractor()\n",
"\n",
"flat_entities = []\n",
"flat_relationships = []\n",
- "flat_triples = []\n",
+ "flat_triplets = []\n",
"\n",
"for doc in normalized_documents:\n",
" text = str(doc.content) if hasattr(doc, 'content') else str(doc)\n",
@@ -350,12 +350,12 @@
" relations = rel_extractor.extract_relations(text, entities=entities)\n",
" flat_relationships.extend(relations if isinstance(relations, list) else [relations])\n",
" \n",
- " triples = triple_extractor.extract_triples(text, entities=entities, relationships=relations)\n",
- " flat_triples.extend(triples if isinstance(triples, list) else [triples])\n",
+ " triplets = triplet_extractor.extract_triplets(text, entities=entities, relationships=relations)\n",
+ " flat_triplets.extend(triplets if isinstance(triplets, list) else [triplets])\n",
"\n",
"print(f\"Extracted {len(flat_entities)} entities\")\n",
"print(f\"Extracted {len(flat_relationships)} relationships\")\n",
- "print(f\"Extracted {len(flat_triples)} triples\")\n"
+ "print(f\"Extracted {len(flat_triplets)} triplets\")\n"
]
},
{
@@ -435,7 +435,7 @@
"source": [
"## Step 4: Semantic Extraction\n",
"\n",
- "Extract entities, relationships, and triples from the processed documents. This is the foundation for building the knowledge graph.\n",
+ "Extract entities, relationships, and triplets from the processed documents. This is the foundation for building the knowledge graph.\n",
"\n"
]
},
@@ -447,22 +447,22 @@
"source": [
"from semantica.semantic_extract import build as extract_build\n",
"\n",
- "print(\"Extracting entities, relationships, and triples...\")\n",
+ "print(\"Extracting entities, relationships, and triplets...\")\n",
"\n",
"extraction_result = extract_build(\n",
" text=[str(doc.content) if hasattr(doc, 'content') else str(doc) for doc in normalized_documents],\n",
" extract_entities=True,\n",
" extract_relations=True,\n",
- " extract_triples=True\n",
+ " extract_triplets=True\n",
")\n",
"\n",
"flat_entities = extraction_result.get('entities', [])\n",
"flat_relationships = extraction_result.get('relationships', [])\n",
- "flat_triples = extraction_result.get('triples', [])\n",
+ "flat_triplets = extraction_result.get('triplets', [])\n",
"\n",
"print(f\"Extracted {len(flat_entities)} entities\")\n",
"print(f\"Extracted {len(flat_relationships)} relationships\")\n",
- "print(f\"Extracted {len(flat_triples)} triples\")\n"
+ "print(f\"Extracted {len(flat_triplets)} triplets\")\n"
]
},
{
@@ -479,7 +479,7 @@
"print(f\"\\nExtraction Summary:\")\n",
"print(f\"Entities: {len(flat_entities)}\")\n",
"print(f\"Relationships: {len(flat_relationships)}\")\n",
- "print(f\"Triples: {len(flat_triples)}\")\n"
+ "print(f\"Triplets: {len(flat_triplets)}\")\n"
]
},
{
@@ -529,7 +529,7 @@
" sources=[{\n",
" 'entities': resolved_entities,\n",
" 'relationships': flat_relationships,\n",
- " 'triples': flat_triples\n",
+ " 'triplets': flat_triplets\n",
" }],\n",
" method=\"default\",\n",
" merge_entities=True,\n",
@@ -1589,7 +1589,7 @@
"\n",
"1. **Real-World Data Ingestion**: MCP servers, web scraping, RSS feeds\n",
"2. **Document Processing**: Parsing, splitting, normalization\n",
- "3. **Semantic Extraction**: Entities, relationships, triples\n",
+ "3. **Semantic Extraction**: Entities, relationships, triplets\n",
"4. **Knowledge Graph Construction**: With quality assurance\n",
"5. **Embedding Generation**: For documents and entities\n",
"6. **Vector Store**: Fast similarity search\n",
diff --git a/cookbook/use_cases/biomedical/01_Drug_Discovery_Pipeline.ipynb b/cookbook/use_cases/biomedical/01_Drug_Discovery_Pipeline.ipynb
index fee625dc..8ee5fffa 100644
--- a/cookbook/use_cases/biomedical/01_Drug_Discovery_Pipeline.ipynb
+++ b/cookbook/use_cases/biomedical/01_Drug_Discovery_Pipeline.ipynb
@@ -29,7 +29,7 @@
"\n",
"- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, EmailIngestor, RepoIngestor, MCPIngestor\n",
"- **Parsing**: JSONParser, StructuredDataParser, DocumentParser, MCPParser\n",
- "- **Extraction**: NERExtractor, RelationExtractor, TripleExtractor, SemanticAnalyzer\n",
+ "- **Extraction**: NERExtractor, RelationExtractor, TripletExtractor, SemanticAnalyzer\n",
"- **KG**: GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",
"- **Analytics**: ConnectivityAnalyzer, TemporalGraphQuery\n",
"- **Embeddings**: EmbeddingGenerator, TextEmbedder\n",
@@ -67,7 +67,7 @@
"source": [
"from semantica.ingest import WebIngestor, DBIngestor, FeedIngestor, FileIngestor, MCPIngestor, ingest_mcp\n",
"from semantica.parse import JSONParser, StructuredDataParser, DocumentParser, MCPParser\n",
- "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripleExtractor, SemanticAnalyzer\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripletExtractor, SemanticAnalyzer\n",
"from semantica.kg import GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",
"from semantica.kg import ConnectivityAnalyzer, TemporalGraphQuery\n",
"from semantica.embeddings import EmbeddingGenerator, TextEmbedder\n",
@@ -275,7 +275,7 @@
"source": [
"ner_extractor = NERExtractor()\n",
"relation_extractor = RelationExtractor()\n",
- "triple_extractor = TripleExtractor()\n",
+ "triplet_extractor = TripletExtractor()\n",
"semantic_analyzer = SemanticAnalyzer()\n",
"\n",
"all_drug_texts = []\n",
@@ -292,7 +292,7 @@
"# Extract entities\n",
"all_entities = []\n",
"all_relationships = []\n",
- "all_triples = []\n",
+ "all_triplets = []\n",
"\n",
"for text in all_drug_texts:\n",
" entities = ner_extractor.extract(text)\n",
@@ -301,8 +301,8 @@
" relationships = relation_extractor.extract(text, entities)\n",
" all_relationships.extend(relationships)\n",
" \n",
- " triples = triple_extractor.extract(text)\n",
- " all_triples.extend(triples)\n",
+ " triplets = triplet_extractor.extract(text)\n",
+ " all_triplets.extend(triplets)\n",
"\n",
"# Build structured entity list\n",
"compound_entities = []\n",
@@ -363,7 +363,7 @@
"print(f\"Extracted {len(target_entities)} unique targets\")\n",
"print(f\"Extracted {len(interaction_entities)} interactions\")\n",
"print(f\"Extracted {len(all_relationships)} relationships\")\n",
- "print(f\"Extracted {len(all_triples)} triples\")\n"
+ "print(f\"Extracted {len(all_triplets)} triplets\")\n"
]
},
{
diff --git a/cookbook/use_cases/biomedical/02_Genomic_Variant_Analysis.ipynb b/cookbook/use_cases/biomedical/02_Genomic_Variant_Analysis.ipynb
index 85aea7a1..207b8e68 100644
--- a/cookbook/use_cases/biomedical/02_Genomic_Variant_Analysis.ipynb
+++ b/cookbook/use_cases/biomedical/02_Genomic_Variant_Analysis.ipynb
@@ -19,7 +19,7 @@
"\n",
"- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, RepoIngestor, EmailIngestor, MCPIngestor\n",
"- **Parsing**: JSONParser, StructuredDataParser, DocumentParser\n",
- "- **Extraction**: NERExtractor, RelationExtractor, TripleExtractor, SemanticAnalyzer\n",
+ "- **Extraction**: NERExtractor, RelationExtractor, TripletExtractor, SemanticAnalyzer\n",
"- **KG**: GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",
"- **Analytics**: ConnectivityAnalyzer, TemporalGraphQuery, TemporalPatternDetector\n",
"- **Ontology**: OntologyGenerator, ClassInferrer, PropertyGenerator, OntologyValidator\n",
@@ -66,7 +66,7 @@
"source": [
"from semantica.ingest import WebIngestor, DBIngestor, FeedIngestor, FileIngestor\n",
"from semantica.parse import JSONParser, StructuredDataParser, DocumentParser\n",
- "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripleExtractor, SemanticAnalyzer\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripletExtractor, SemanticAnalyzer\n",
"from semantica.kg import GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",
"from semantica.kg import ConnectivityAnalyzer, TemporalGraphQuery, TemporalPatternDetector\n",
"from semantica.ontology import OntologyGenerator, ClassInferrer, PropertyGenerator, OntologyValidator\n",
@@ -241,7 +241,7 @@
"source": [
"ner_extractor = NERExtractor()\n",
"relation_extractor = RelationExtractor()\n",
- "triple_extractor = TripleExtractor()\n",
+ "triplet_extractor = TripletExtractor()\n",
"semantic_analyzer = SemanticAnalyzer()\n",
"\n",
"all_genomic_texts = []\n",
@@ -258,7 +258,7 @@
"# Extract entities\n",
"all_entities = []\n",
"all_relationships = []\n",
- "all_triples = []\n",
+ "all_triplets = []\n",
"\n",
"for text in all_genomic_texts:\n",
" entities = ner_extractor.extract(text)\n",
@@ -267,8 +267,8 @@
" relationships = relation_extractor.extract(text, entities)\n",
" all_relationships.extend(relationships)\n",
" \n",
- " triples = triple_extractor.extract(text)\n",
- " all_triples.extend(triples)\n",
+ " triplets = triplet_extractor.extract(text)\n",
+ " all_triplets.extend(triplets)\n",
"\n",
"# Build structured entity list\n",
"variant_entities = []\n",
@@ -343,7 +343,7 @@
"print(f\"Extracted {len(disease_entities)} unique diseases\")\n",
"print(f\"Extracted {len(pathway_entities)} unique pathways\")\n",
"print(f\"Extracted {len(all_relationships)} relationships\")\n",
- "print(f\"Extracted {len(all_triples)} triples\")\n"
+ "print(f\"Extracted {len(all_triplets)} triplets\")\n"
]
},
{
diff --git a/cookbook/use_cases/blockchain/02_Transaction_Network_Analysis.ipynb b/cookbook/use_cases/blockchain/02_Transaction_Network_Analysis.ipynb
index 3c5e5fb3..d5856930 100644
--- a/cookbook/use_cases/blockchain/02_Transaction_Network_Analysis.ipynb
+++ b/cookbook/use_cases/blockchain/02_Transaction_Network_Analysis.ipynb
@@ -19,7 +19,7 @@
"\n",
"- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, RepoIngestor, EmailIngestor, MCPIngestor\n",
"- **Parsing**: JSONParser, StructuredDataParser\n",
- "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripleExtractor\n",
+ "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",
"- **KG**: GraphBuilder, TemporalGraphQuery, TemporalPatternDetector, GraphAnalyzer\n",
"- **Graph Store**: GraphStore with Neo4j/FalkorDB for persistent blockchain graph\n",
"- **Analytics**: CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",
@@ -66,7 +66,7 @@
"source": [
"from semantica.ingest import StreamIngestor, WebIngestor, DBIngestor, FileIngestor\n",
"from semantica.parse import JSONParser, StructuredDataParser\n",
- "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, TripleExtractor\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",
"from semantica.kg import GraphBuilder, TemporalGraphQuery, TemporalPatternDetector, GraphAnalyzer\n",
"from semantica.kg import CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",
"from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",
@@ -213,7 +213,7 @@
"ner_extractor = NERExtractor()\n",
"relation_extractor = RelationExtractor()\n",
"event_detector = EventDetector()\n",
- "triple_extractor = TripleExtractor()\n",
+ "triplet_extractor = TripletExtractor()\n",
"\n",
"all_transaction_texts = []\n",
"all_transactions = []\n",
@@ -230,7 +230,7 @@
"all_entities = []\n",
"all_relationships = []\n",
"all_events = []\n",
- "all_triples = []\n",
+ "all_triplets = []\n",
"\n",
"for text in all_transaction_texts:\n",
" entities = ner_extractor.extract(text)\n",
@@ -242,8 +242,8 @@
" events = event_detector.detect_events(text)\n",
" all_events.extend(events)\n",
" \n",
- " triples = triple_extractor.extract(text)\n",
- " all_triples.extend(triples)\n",
+ " triplets = triplet_extractor.extract(text)\n",
+ " all_triplets.extend(triplets)\n",
"\n",
"# Build structured entity list\n",
"transaction_entities = []\n",
@@ -297,7 +297,7 @@
"print(f\"Extracted {len(wallet_entities)} unique wallets\")\n",
"print(f\"Extracted {len(all_relationships)} relationships\")\n",
"print(f\"Detected {len(all_events)} events\")\n",
- "print(f\"Extracted {len(all_triples)} triples\")\n"
+ "print(f\"Extracted {len(all_triplets)} triplets\")\n"
]
},
{
diff --git a/cookbook/use_cases/cybersecurity/01_Anomaly_Detection_Real_Time.ipynb b/cookbook/use_cases/cybersecurity/01_Anomaly_Detection_Real_Time.ipynb
index f2001e44..3cc40ae5 100644
--- a/cookbook/use_cases/cybersecurity/01_Anomaly_Detection_Real_Time.ipynb
+++ b/cookbook/use_cases/cybersecurity/01_Anomaly_Detection_Real_Time.ipynb
@@ -29,7 +29,7 @@
"\n",
"- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, EmailIngestor, RepoIngestor, MCPIngestor\n",
"- **Parsing**: JSONParser, StructuredDataParser, DocumentParser\n",
- "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripleExtractor\n",
+ "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",
"- **KG**: GraphBuilder, TemporalPatternDetector, TemporalGraphQuery, GraphAnalyzer\n",
"- **Analytics**: CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",
"- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",
@@ -65,7 +65,7 @@
"source": [
"from semantica.ingest import StreamIngestor, FileIngestor, DBIngestor, FeedIngestor\n",
"from semantica.parse import JSONParser, StructuredDataParser, DocumentParser\n",
- "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, TripleExtractor\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",
"from semantica.kg import GraphBuilder, TemporalPatternDetector, TemporalGraphQuery, GraphAnalyzer\n",
"from semantica.kg import CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",
"from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",
@@ -203,7 +203,7 @@
"ner_extractor = NERExtractor()\n",
"relation_extractor = RelationExtractor()\n",
"event_detector = EventDetector()\n",
- "triple_extractor = TripleExtractor()\n",
+ "triplet_extractor = TripletExtractor()\n",
"\n",
"# Real-time processing loop (simulated)\n",
"security_entities = []\n",
diff --git a/cookbook/use_cases/cybersecurity/02_Incident_Analysis.ipynb b/cookbook/use_cases/cybersecurity/02_Incident_Analysis.ipynb
index b5919511..e60a5876 100644
--- a/cookbook/use_cases/cybersecurity/02_Incident_Analysis.ipynb
+++ b/cookbook/use_cases/cybersecurity/02_Incident_Analysis.ipynb
@@ -19,7 +19,7 @@
"\n",
"- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, RepoIngestor, EmailIngestor, MCPIngestor\n",
"- **Parsing**: JSONParser, XMLParser, StructuredDataParser, DocumentParser\n",
- "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripleExtractor\n",
+ "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",
"- **KG**: GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer, CentralityCalculator\n",
"- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",
"- **Quality**: KGQualityAssessor, ConflictDetector, ProvenanceTracker\n",
@@ -64,7 +64,7 @@
"source": [
"from semantica.ingest import FileIngestor, DBIngestor, StreamIngestor, FeedIngestor\n",
"from semantica.parse import JSONParser, XMLParser, StructuredDataParser, DocumentParser\n",
- "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, TripleExtractor\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",
"from semantica.kg import GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer, CentralityCalculator\n",
"from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",
"from semantica.conflicts import ConflictDetector\n",
@@ -194,7 +194,7 @@
"ner_extractor = NERExtractor()\n",
"relation_extractor = RelationExtractor()\n",
"event_detector = EventDetector()\n",
- "triple_extractor = TripleExtractor()\n",
+ "triplet_extractor = TripletExtractor()\n",
"\n",
"all_entities = []\n",
"all_relationships = []\n",
diff --git a/cookbook/use_cases/cybersecurity/04_Threat_Intelligence_Hybrid_RAG.ipynb b/cookbook/use_cases/cybersecurity/04_Threat_Intelligence_Hybrid_RAG.ipynb
index 105e376b..3f70d93a 100644
--- a/cookbook/use_cases/cybersecurity/04_Threat_Intelligence_Hybrid_RAG.ipynb
+++ b/cookbook/use_cases/cybersecurity/04_Threat_Intelligence_Hybrid_RAG.ipynb
@@ -19,7 +19,7 @@
"\n",
"- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, DBIngestor, MCPIngestor\n",
"- **Parsing**: JSONParser, XMLParser, HTMLParser, DocumentParser, MCPParser\n",
- "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripleExtractor\n",
+ "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",
"- **KG**: GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer\n",
"- **Embeddings**: EmbeddingGenerator, TextEmbedder\n",
"- **Vector Store**: VectorStore, HybridSearch\n",
@@ -66,7 +66,7 @@
"source": [
"from semantica.ingest import FileIngestor, WebIngestor, FeedIngestor, DBIngestor, MCPIngestor, ingest_mcp\n",
"from semantica.parse import JSONParser, XMLParser, HTMLParser, DocumentParser, MCPParser\n",
- "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, TripleExtractor\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",
"from semantica.kg import GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer\n",
"from semantica.embeddings import EmbeddingGenerator, TextEmbedder\n",
"from semantica.vector_store import VectorStore, HybridSearch\n",
@@ -276,7 +276,7 @@
"ner_extractor = NERExtractor()\n",
"relation_extractor = RelationExtractor()\n",
"event_detector = EventDetector()\n",
- "triple_extractor = TripleExtractor()\n",
+ "triplet_extractor = TripletExtractor()\n",
"\n",
"threat_entities = []\n",
"threat_relationships = []\n",
diff --git a/cookbook/use_cases/cybersecurity/05_Threat_Intelligence_Integration.ipynb b/cookbook/use_cases/cybersecurity/05_Threat_Intelligence_Integration.ipynb
index 605f7fe1..ba80fe41 100644
--- a/cookbook/use_cases/cybersecurity/05_Threat_Intelligence_Integration.ipynb
+++ b/cookbook/use_cases/cybersecurity/05_Threat_Intelligence_Integration.ipynb
@@ -21,7 +21,7 @@
"\n",
"- **Ingestion**: MCPIngestor, ingest_mcp, WebIngestor, FeedIngestor\n",
"- **Parsing**: MCPParser, JSONParser, XMLParser, StructuredDataParser\n",
- "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripleExtractor\n",
+ "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",
"- **KG**: GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer\n",
"- **Embeddings**: EmbeddingGenerator, TextEmbedder\n",
"- **Vector Store**: VectorStore, HybridSearch\n",
@@ -67,7 +67,7 @@
"source": [
"from semantica.ingest import MCPIngestor, ingest_mcp\n",
"from semantica.parse import MCPParser, JSONParser, XMLParser, StructuredDataParser\n",
- "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, TripleExtractor\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",
"from semantica.kg import GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer\n",
"from semantica.embeddings import EmbeddingGenerator, TextEmbedder\n",
"from semantica.vector_store import VectorStore, HybridSearch\n",
@@ -288,7 +288,7 @@
"ner_extractor = NERExtractor()\n",
"relation_extractor = RelationExtractor()\n",
"event_detector = EventDetector()\n",
- "triple_extractor = TripleExtractor()\n",
+ "triplet_extractor = TripletExtractor()\n",
"\n",
"threat_entities = []\n",
"threat_relationships = []\n",
diff --git a/cookbook/use_cases/cybersecurity/06_Vulnerability_Tracking.ipynb b/cookbook/use_cases/cybersecurity/06_Vulnerability_Tracking.ipynb
index 64e78a31..ef08dc2e 100644
--- a/cookbook/use_cases/cybersecurity/06_Vulnerability_Tracking.ipynb
+++ b/cookbook/use_cases/cybersecurity/06_Vulnerability_Tracking.ipynb
@@ -19,7 +19,7 @@
"\n",
"- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, RepoIngestor, EmailIngestor, MCPIngestor\n",
"- **Parsing**: JSONParser, XMLParser, StructuredDataParser\n",
- "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripleExtractor\n",
+ "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",
"- **KG**: GraphBuilder, TemporalGraphQuery, TemporalPatternDetector, GraphAnalyzer\n",
"- **Analytics**: CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",
"- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",
@@ -65,7 +65,7 @@
"source": [
"from semantica.ingest import WebIngestor, FeedIngestor, DBIngestor, FileIngestor\n",
"from semantica.parse import JSONParser, XMLParser, StructuredDataParser\n",
- "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, TripleExtractor\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",
"from semantica.kg import GraphBuilder, TemporalGraphQuery, TemporalPatternDetector, GraphAnalyzer\n",
"from semantica.kg import CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",
"from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",
diff --git a/cookbook/use_cases/finance/02_Financial_Reports_Analysis.ipynb b/cookbook/use_cases/finance/02_Financial_Reports_Analysis.ipynb
index 11773db5..ac98d2ff 100644
--- a/cookbook/use_cases/finance/02_Financial_Reports_Analysis.ipynb
+++ b/cookbook/use_cases/finance/02_Financial_Reports_Analysis.ipynb
@@ -29,7 +29,7 @@
"\n",
"- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, EmailIngestor, RepoIngestor, MCPIngestor\n",
"- **Parsing**: DocumentParser, PDFParser, HTMLParser, StructuredDataParser\n",
- "- **Extraction**: NERExtractor, RelationExtractor, TripleExtractor, SemanticAnalyzer\n",
+ "- **Extraction**: NERExtractor, RelationExtractor, TripletExtractor, SemanticAnalyzer\n",
"- **KG**: GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",
"- **Analytics**: ConnectivityAnalyzer, TemporalGraphQuery, TemporalPatternDetector\n",
"- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",
@@ -65,7 +65,7 @@
"source": [
"from semantica.ingest import FileIngestor, WebIngestor, DBIngestor, FeedIngestor\n",
"from semantica.parse import DocumentParser, PDFParser, HTMLParser, StructuredDataParser\n",
- "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripleExtractor, SemanticAnalyzer\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripletExtractor, SemanticAnalyzer\n",
"from semantica.kg import GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",
"from semantica.kg import ConnectivityAnalyzer, TemporalGraphQuery, TemporalPatternDetector\n",
"from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",
@@ -164,7 +164,7 @@
"source": [
"ner_extractor = NERExtractor()\n",
"relation_extractor = RelationExtractor()\n",
- "triple_extractor = TripleExtractor()\n",
+ "triplet_extractor = TripletExtractor()\n",
"semantic_analyzer = SemanticAnalyzer()\n",
"\n",
"financial_entities = []\n",
diff --git a/cookbook/use_cases/finance/05_Regulatory_Compliance.ipynb b/cookbook/use_cases/finance/05_Regulatory_Compliance.ipynb
index abca5f66..90f92536 100644
--- a/cookbook/use_cases/finance/05_Regulatory_Compliance.ipynb
+++ b/cookbook/use_cases/finance/05_Regulatory_Compliance.ipynb
@@ -29,7 +29,7 @@
"\n",
"- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, EmailIngestor, RepoIngestor, MCPIngestor\n",
"- **Parsing**: DocumentParser, PDFParser, HTMLParser, StructuredDataParser\n",
- "- **Extraction**: NERExtractor, RelationExtractor, TripleExtractor, SemanticAnalyzer\n",
+ "- **Extraction**: NERExtractor, RelationExtractor, TripletExtractor, SemanticAnalyzer\n",
"- **KG**: GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer\n",
"- **Ontology**: OntologyGenerator, ClassInferrer, PropertyGenerator, OntologyValidator\n",
"- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",
@@ -65,7 +65,7 @@
"source": [
"from semantica.ingest import FileIngestor, WebIngestor, DBIngestor, FeedIngestor\n",
"from semantica.parse import DocumentParser, PDFParser, HTMLParser, StructuredDataParser\n",
- "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripleExtractor, SemanticAnalyzer\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripletExtractor, SemanticAnalyzer\n",
"from semantica.kg import GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer\n",
"from semantica.ontology import OntologyGenerator, ClassInferrer, PropertyGenerator, OntologyValidator\n",
"from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",
@@ -161,7 +161,7 @@
"source": [
"ner_extractor = NERExtractor()\n",
"relation_extractor = RelationExtractor()\n",
- "triple_extractor = TripleExtractor()\n",
+ "triplet_extractor = TripletExtractor()\n",
"semantic_analyzer = SemanticAnalyzer()\n",
"\n",
"compliance_entities = []\n",
diff --git a/cookbook/use_cases/healthcare/01_Clinical_Reports_Processing.ipynb b/cookbook/use_cases/healthcare/01_Clinical_Reports_Processing.ipynb
index def82281..0b3c0d25 100644
--- a/cookbook/use_cases/healthcare/01_Clinical_Reports_Processing.ipynb
+++ b/cookbook/use_cases/healthcare/01_Clinical_Reports_Processing.ipynb
@@ -10,7 +10,7 @@
"\n",
"## Overview\n",
"\n",
- "This notebook demonstrates a complete clinical reports processing pipeline: ingest clinical documents from multiple sources (EHR systems, HL7/FHIR APIs, medical databases), extract medical entities, build knowledge graph, store in triple store, and query patient data.\n",
+ "This notebook demonstrates a complete clinical reports processing pipeline: ingest clinical documents from multiple sources (EHR systems, HL7/FHIR APIs, medical databases), extract medical entities, build knowledge graph, store in triplet store, and query patient data.\n",
"\n",
"\n",
"**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",
@@ -29,7 +29,7 @@
"\n",
"- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, EmailIngestor, RepoIngestor, MCPIngestor\n",
"- **Parsing**: DocumentParser, PDFParser, StructuredDataParser, CSVParser, MCPParser\n",
- "- **Extraction**: NERExtractor, RelationExtractor, CoreferenceResolver, TripleExtractor\n",
+ "- **Extraction**: NERExtractor, RelationExtractor, CoreferenceResolver, TripletExtractor\n",
"- **KG**: GraphBuilder, GraphValidator, EntityResolver, GraphAnalyzer\n",
"- **Triplet Store**: TripletStore, TripletManager, QueryEngine\n",
"- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",
@@ -39,7 +39,7 @@
"\n",
"### Pipeline\n",
"\n",
- "**Clinical Documents (Files, APIs, DB, MCP) \u2192 Parse \u2192 Extract Medical Entities \u2192 Build Medical KG \u2192 Store in Triple Store \u2192 Query Patient Data \u2192 Generate Reports \u2192 Visualize**\n",
+ "**Clinical Documents (Files, APIs, DB, MCP) \u2192 Parse \u2192 Extract Medical Entities \u2192 Build Medical KG \u2192 Store in Triplet Store \u2192 Query Patient Data \u2192 Generate Reports \u2192 Visualize**\n",
"\n",
"---\n",
"\n",
@@ -65,9 +65,9 @@
"source": [
"from semantica.ingest import FileIngestor, DBIngestor, StreamIngestor, WebIngestor, MCPIngestor, ingest_mcp\n",
"from semantica.parse import DocumentParser, PDFParser, StructuredDataParser, CSVParser, MCPParser\n",
- "from semantica.semantic_extract import NERExtractor, RelationExtractor, CoreferenceResolver, TripleExtractor\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, CoreferenceResolver, TripletExtractor\n",
"from semantica.kg import GraphBuilder, GraphValidator, EntityResolver, GraphAnalyzer\n",
- "from semantica.triple_store import TripleStore, TripleManager, QueryEngine\n",
+ "from semantica.triplet_store import TripletStore, TripletManager, QueryEngine\n",
"from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",
"from semantica.export import JSONExporter, RDFExporter, OWLExporter, ReportGenerator\n",
"from semantica.visualization import KGVisualizer, OntologyVisualizer, TemporalVisualizer\n",
@@ -212,7 +212,7 @@
"ner_extractor = NERExtractor()\n",
"relation_extractor = RelationExtractor()\n",
"coreference_resolver = CoreferenceResolver()\n",
- "triple_extractor = TripleExtractor()\n",
+ "triplet_extractor = TripletExtractor()\n",
"\n",
"medical_entities = []\n",
"relationships = []\n",
@@ -334,9 +334,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "## Step 4: Store in Triple Store and Query Patient Data\n",
+ "## Step 4: Store in Triplet Store and Query Patient Data\n",
"\n",
- "Store knowledge graph in triple store and query patient information.\n"
+ "Store knowledge graph in triplet store and query patient information.\n"
]
},
{
@@ -345,14 +345,14 @@
"metadata": {},
"outputs": [],
"source": [
- "triple_store = TripleStore()\n",
- "triple_manager = TripleManager()\n",
+ "triplet_store = TripletStore()\n",
+ "triplet_manager = TripletManager()\n",
"query_engine = QueryEngine()\n",
"inference_engine = InferenceEngine()\n",
"rule_manager = RuleManager()\n",
"explanation_generator = ExplanationGenerator()\n",
"\n",
- "triple_store.store_knowledge_graph(medical_kg)\n",
+ "triplet_store.store_knowledge_graph(medical_kg)\n",
"\n",
"# Query patient data\n",
"patient_id = \"P001\"\n",
@@ -378,7 +378,7 @@
"\n",
"medical_insights = inference_engine.forward_chain()\n",
"\n",
- "print(f\"Stored medical knowledge graph in triple store\")\n",
+ "print(f\"Stored medical knowledge graph in triplet store\")\n",
"print(f\"Query returned {len(query_results) if query_results else 0} results\")\n",
"print(f\"Generated {len(medical_insights)} medical insights\")\n"
]
@@ -427,7 +427,7 @@
"temporal_viz = temporal_visualizer.visualize_timeline(medical_kg, output=\"interactive\")\n",
"\n",
"print(f\"Total modules used: 20+\")\n",
- "print(f\"Pipeline complete: Clinical Documents \u2192 Parse \u2192 Extract \u2192 Build KG \u2192 Triple Store \u2192 Query \u2192 Reports \u2192 Visualize\")\n"
+ "print(f\"Pipeline complete: Clinical Documents \u2192 Parse \u2192 Extract \u2192 Build KG \u2192 Triplet Store \u2192 Query \u2192 Reports \u2192 Visualize\")\n"
]
}
],
diff --git a/cookbook/use_cases/healthcare/02_Disease_Network_Analysis.ipynb b/cookbook/use_cases/healthcare/02_Disease_Network_Analysis.ipynb
index 4625e728..185b49e8 100644
--- a/cookbook/use_cases/healthcare/02_Disease_Network_Analysis.ipynb
+++ b/cookbook/use_cases/healthcare/02_Disease_Network_Analysis.ipynb
@@ -29,7 +29,7 @@
"\n",
"- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, EmailIngestor, RepoIngestor, MCPIngestor\n",
"- **Parsing**: DocumentParser, PDFParser, StructuredDataParser, JSONParser\n",
- "- **Extraction**: NERExtractor, RelationExtractor, TripleExtractor, SemanticAnalyzer\n",
+ "- **Extraction**: NERExtractor, RelationExtractor, TripletExtractor, SemanticAnalyzer\n",
"- **KG**: GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",
"- **Analytics**: ConnectivityAnalyzer, TemporalGraphQuery, TemporalPatternDetector\n",
"- **Ontology**: OntologyGenerator, ClassInferrer, PropertyGenerator, OntologyValidator\n",
@@ -66,7 +66,7 @@
"source": [
"from semantica.ingest import FileIngestor, WebIngestor, DBIngestor, FeedIngestor\n",
"from semantica.parse import DocumentParser, PDFParser, StructuredDataParser, JSONParser\n",
- "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripleExtractor, SemanticAnalyzer\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripletExtractor, SemanticAnalyzer\n",
"from semantica.kg import GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",
"from semantica.kg import ConnectivityAnalyzer, TemporalGraphQuery, TemporalPatternDetector\n",
"from semantica.ontology import OntologyGenerator, ClassInferrer, PropertyGenerator, OntologyValidator\n",
@@ -167,7 +167,7 @@
"source": [
"ner_extractor = NERExtractor()\n",
"relation_extractor = RelationExtractor()\n",
- "triple_extractor = TripleExtractor()\n",
+ "triplet_extractor = TripletExtractor()\n",
"semantic_analyzer = SemanticAnalyzer()\n",
"\n",
"disease_entities = []\n",
diff --git a/cookbook/use_cases/healthcare/03_Drug_Interactions_Analysis.ipynb b/cookbook/use_cases/healthcare/03_Drug_Interactions_Analysis.ipynb
index 6981aa2c..9ca928d3 100644
--- a/cookbook/use_cases/healthcare/03_Drug_Interactions_Analysis.ipynb
+++ b/cookbook/use_cases/healthcare/03_Drug_Interactions_Analysis.ipynb
@@ -19,7 +19,7 @@
"\n",
"- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, RepoIngestor, EmailIngestor, MCPIngestor\n",
"- **Parsing**: DocumentParser, PDFParser, StructuredDataParser, JSONParser\n",
- "- **Extraction**: NERExtractor, RelationExtractor, TripleExtractor, SemanticAnalyzer\n",
+ "- **Extraction**: NERExtractor, RelationExtractor, TripletExtractor, SemanticAnalyzer\n",
"- **KG**: GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",
"- **Analytics**: ConnectivityAnalyzer, TemporalGraphQuery\n",
"- **Ontology**: OntologyGenerator, ClassInferrer, PropertyGenerator, OntologyValidator\n",
@@ -66,7 +66,7 @@
"source": [
"from semantica.ingest import FileIngestor, WebIngestor, DBIngestor, FeedIngestor\n",
"from semantica.parse import DocumentParser, PDFParser, StructuredDataParser, JSONParser\n",
- "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripleExtractor, SemanticAnalyzer\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripletExtractor, SemanticAnalyzer\n",
"from semantica.kg import GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",
"from semantica.kg import ConnectivityAnalyzer, TemporalGraphQuery\n",
"from semantica.ontology import OntologyGenerator, ClassInferrer, PropertyGenerator, OntologyValidator\n",
@@ -172,7 +172,7 @@
"source": [
"ner_extractor = NERExtractor()\n",
"relation_extractor = RelationExtractor()\n",
- "triple_extractor = TripleExtractor()\n",
+ "triplet_extractor = TripletExtractor()\n",
"semantic_analyzer = SemanticAnalyzer()\n",
"\n",
"drug_entities = []\n",
diff --git a/cookbook/use_cases/healthcare/04_Healthcare_GraphRAG_Hybrid.ipynb b/cookbook/use_cases/healthcare/04_Healthcare_GraphRAG_Hybrid.ipynb
index 5c68cb32..2c124169 100644
--- a/cookbook/use_cases/healthcare/04_Healthcare_GraphRAG_Hybrid.ipynb
+++ b/cookbook/use_cases/healthcare/04_Healthcare_GraphRAG_Hybrid.ipynb
@@ -50,7 +50,7 @@
"- **Ingest**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, RepoIngestor, EmailIngestor, MCPIngestor (for EHR virtual connections and medical literature)\n",
"- **Parse**: DocumentParser, PDFParser (clinical documents), StructuredDataParser (for structured medical data)\n",
"- **Normalize**: TextNormalizer (for text normalization)\n",
- "- **Semantic Extract**: NERExtractor, RelationExtractor, TripleExtractor (medical entities and relationships)\n",
+ "- **Semantic Extract**: NERExtractor, RelationExtractor, TripletExtractor (medical entities and relationships)\n",
"- **Ontology**: OntologyGenerator, OWLGenerator (medical ontologies like SNOMED CT, ICD-10)\n",
"- **KG**: GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer (materialized knowledge graph)\n",
"- **Embeddings**: EmbeddingGenerator, TextEmbedder (for embeddings)\n",
@@ -99,7 +99,7 @@
"from semantica.ingest import FileIngestor, DBIngestor, WebIngestor\n",
"from semantica.parse import DocumentParser, PDFParser, StructuredDataParser\n",
"from semantica.normalize import TextNormalizer\n",
- "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripleExtractor\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripletExtractor\n",
"from semantica.ontology import OntologyGenerator, OWLGenerator\n",
"from semantica.kg import GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer\n",
"from semantica.embeddings import EmbeddingGenerator, TextEmbedder\n",
@@ -238,7 +238,7 @@
"source": [
"## Step 4: Extract Medical Entities and Relationships Using Semantica\n",
"\n",
- "Using Semantica's semantic extraction modules to extract medical entities, relationships, and triples from the parsed data.\n"
+ "Using Semantica's semantic extraction modules to extract medical entities, relationships, and triplets from the parsed data.\n"
]
},
{
@@ -250,7 +250,7 @@
"# Initialize Semantica extractors\n",
"ner_extractor = NERExtractor()\n",
"relation_extractor = RelationExtractor()\n",
- "triple_extractor = TripleExtractor()\n",
+ "triplet_extractor = TripletExtractor()\n",
"\n",
"# Extract entities from clinical document\n",
"clinical_text = clinical_data.get('normalized_content', clinical_data.get('content', ''))\n",
@@ -259,8 +259,8 @@
"# Extract relationships\n",
"extracted_relationships = relation_extractor.extract(clinical_text, entities=extracted_entities)\n",
"\n",
- "# Extract triples\n",
- "extracted_triples = triple_extractor.extract(clinical_text)\n",
+ "# Extract triplets\n",
+ "extracted_triplets = triplet_extractor.extract(clinical_text)\n",
"\n",
"# Build entity list for knowledge graph\n",
"medical_entities = []\n",
@@ -476,9 +476,9 @@
"# Register triplet store (using in-memory for demo)\n",
"store = triplet_manager.register_store(\"healthcare_ontology\", \"jena\", \"http://localhost:3030/healthcare\")\n",
"\n",
- "# Convert ontology to triples and add to store\n",
+ "# Convert ontology to triplets and add to store\n",
"# In production, this would load the OWL ontology\n",
- "sample_triples = [\n",
+ "sample_triplets = [\n",
" {\n",
" \"subject\": \"http://semantica.example.org/healthcare#Type2Diabetes\",\n",
" \"predicate\": \"http://www.w3.org/2000/01/rdf-schema#subClassOf\",\n",
@@ -493,11 +493,11 @@
" }\n",
"]\n",
"\n",
- "# Add triples using Semantica\n",
- "for triple in sample_triples:\n",
- " triplet_manager.add_triple(triple, store_id=\"healthcare_ontology\")\n",
+ "# Add triplets using Semantica\n",
+ "for triplet in sample_triplets:\n",
+ " triplet_manager.add_triplet(triplet, store_id=\"healthcare_ontology\")\n",
"\n",
- "print(f\" - Triples added: {len(sample_triples)}\")\n",
+ "print(f\" - Triplets added: {len(sample_triplets)}\")\n",
"print(f\" - SPARQL queries enabled for ontology\")\n"
]
},
diff --git a/cookbook/use_cases/healthcare/05_Medical_Database_Integration.ipynb b/cookbook/use_cases/healthcare/05_Medical_Database_Integration.ipynb
index fcb7bc02..b15a0c13 100644
--- a/cookbook/use_cases/healthcare/05_Medical_Database_Integration.ipynb
+++ b/cookbook/use_cases/healthcare/05_Medical_Database_Integration.ipynb
@@ -21,7 +21,7 @@
"\n",
"- **Ingestion**: MCPIngestor, ingest_mcp, DBIngestor, FileIngestor\n",
"- **Parsing**: MCPParser, JSONParser, StructuredDataParser, DocumentParser\n",
- "- **Extraction**: NERExtractor, RelationExtractor, TripleExtractor, SemanticAnalyzer\n",
+ "- **Extraction**: NERExtractor, RelationExtractor, TripletExtractor, SemanticAnalyzer\n",
"- **KG**: GraphBuilder, GraphValidator, EntityResolver, GraphAnalyzer\n",
"- **Triplet Store**: TripletStore, TripletManager, QueryEngine\n",
"- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",
@@ -76,7 +76,7 @@
"source": [
"from semantica.ingest import MCPIngestor, ingest_mcp\n",
"from semantica.parse import MCPParser, JSONParser, StructuredDataParser, DocumentParser\n",
- "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripleExtractor, SemanticAnalyzer\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripletExtractor, SemanticAnalyzer\n",
"from semantica.kg import GraphBuilder, GraphValidator, EntityResolver, GraphAnalyzer\n",
"from semantica.triplet_store import TripletStore, TripletManager, QueryEngine\n",
"from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",
@@ -290,7 +290,7 @@
"source": [
"ner_extractor = NERExtractor()\n",
"relation_extractor = RelationExtractor()\n",
- "triple_extractor = TripleExtractor()\n",
+ "triplet_extractor = TripletExtractor()\n",
"semantic_analyzer = SemanticAnalyzer()\n",
"\n",
"medical_entities = []\n",
@@ -444,9 +444,9 @@
"# Register default store (in-memory for demo)\n",
"store = triplet_manager.register_store(\"medical_kg\", \"jena\", \"http://localhost:3030/medical\")\n",
"\n",
- "# Convert KG to triples and add to store (simplified)\n",
- "# In a real scenario, we would convert entities/relations to triples first\n",
- "# triplet_manager.add_triples(triples, store_id=\"medical_kg\")\n",
+ "# Convert KG to triplets and add to store (simplified)\n",
+ "# In a real scenario, we would convert entities/relations to triplets first\n",
+ "# triplet_manager.add_triplets(triplets, store_id=\"medical_kg\")\n",
"\n",
"print(f\" Entities: {len(resolved_kg.get('entities', []))}\")\n",
"print(f\" Relationships: {len(resolved_kg.get('relationships', []))}\")\n",
diff --git a/cookbook/use_cases/healthcare/06_Patient_Records_Temporal.ipynb b/cookbook/use_cases/healthcare/06_Patient_Records_Temporal.ipynb
index dfb057b0..586fb407 100644
--- a/cookbook/use_cases/healthcare/06_Patient_Records_Temporal.ipynb
+++ b/cookbook/use_cases/healthcare/06_Patient_Records_Temporal.ipynb
@@ -282,7 +282,7 @@
"outputs": [],
"source": [
"triplet_store = TripletStore()\n",
- "triple_manager = TripletManager()\n",
+ "triplet_manager = TripletManager()\n",
"query_engine = QueryEngine()\n",
"temporal_query = TemporalGraphQuery()\n",
"\n",
diff --git a/cookbook/use_cases/intelligence/01_Criminal_Network_Analysis.ipynb b/cookbook/use_cases/intelligence/01_Criminal_Network_Analysis.ipynb
index 914df873..38a3a2ad 100644
--- a/cookbook/use_cases/intelligence/01_Criminal_Network_Analysis.ipynb
+++ b/cookbook/use_cases/intelligence/01_Criminal_Network_Analysis.ipynb
@@ -54,7 +54,7 @@
"- **MCP Integration**: MCP browser tools and resources for external data access\n",
"- **Parse**: StructuredDataParser, CSVParser, JSONParser, DocumentParser\n",
"- **Normalize**: TextNormalizer, DataNormalizer\n",
- "- **Semantic Extract**: NERExtractor, RelationExtractor, TripleExtractor, EventDetector\n",
+ "- **Semantic Extract**: NERExtractor, RelationExtractor, TripletExtractor, EventDetector\n",
"- **KG**: GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer, TemporalGraphQuery\n",
"- **Graph Store**: GraphStore with Neo4j/FalkorDB for persistent criminal network storage\n",
"- **Graph Analytics**: PageRank, Betweenness, Closeness, Eigenvector centrality, Louvain community detection\n",
@@ -102,7 +102,7 @@
"from semantica.ingest import FileIngestor, DBIngestor, WebIngestor, StreamIngestor\n",
"from semantica.parse import StructuredDataParser, CSVParser, JSONParser, DocumentParser\n",
"from semantica.normalize import TextNormalizer, DataNormalizer\n",
- "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripleExtractor, EventDetector\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripletExtractor, EventDetector\n",
"from semantica.kg import GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer, TemporalGraphQuery\n",
"from semantica.embeddings import EmbeddingGenerator, TextEmbedder\n",
"from semantica.vector_store import VectorStore, HybridSearch, MetadataFilter\n",
@@ -330,7 +330,7 @@
"# Initialize extractors\n",
"ner_extractor = NERExtractor()\n",
"relation_extractor = RelationExtractor()\n",
- "triple_extractor = TripleExtractor()\n",
+ "triplet_extractor = TripletExtractor()\n",
"event_detector = EventDetector()\n",
"\n",
"# Extract entities and relationships\n",
diff --git a/cookbook/use_cases/intelligence/02_Intelligence_Analysis.ipynb b/cookbook/use_cases/intelligence/02_Intelligence_Analysis.ipynb
index 5e09d638..cc4b10a8 100644
--- a/cookbook/use_cases/intelligence/02_Intelligence_Analysis.ipynb
+++ b/cookbook/use_cases/intelligence/02_Intelligence_Analysis.ipynb
@@ -58,7 +58,7 @@
"- **MCP Integration**: MCP browser tools and resources\n",
"- **Parse**: JSONParser, XMLParser, CSVParser, DocumentParser, StructuredDataParser\n",
"- **Normalize**: TextNormalizer, DataNormalizer\n",
- "- **Semantic Extract**: NERExtractor, RelationExtractor, TripleExtractor, EventDetector\n",
+ "- **Semantic Extract**: NERExtractor, RelationExtractor, TripletExtractor, EventDetector\n",
"- **Ontology**: OntologyGenerator, ClassInferrer, PropertyGenerator, OWLGenerator, OntologyValidator\n",
"- **KG**: GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer, CentralityCalculator, CommunityDetector\n",
"- **Graph Analytics**: All centrality measures, Louvain, connectivity, path finding\n",
@@ -115,7 +115,7 @@
"from semantica.ingest import FileIngestor, DBIngestor, WebIngestor, StreamIngestor, FeedIngestor\n",
"from semantica.parse import JSONParser, XMLParser, CSVParser, DocumentParser, StructuredDataParser\n",
"from semantica.normalize import TextNormalizer, DataNormalizer\n",
- "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripleExtractor, EventDetector\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripletExtractor, EventDetector\n",
"from semantica.ontology import OntologyGenerator, ClassInferrer, PropertyGenerator, OWLGenerator, OntologyValidator\n",
"from semantica.kg import GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer\n",
"from semantica.embeddings import EmbeddingGenerator, TextEmbedder\n",
diff --git a/cookbook/use_cases/intelligence/03_Law_Enforcement_Forensics.ipynb b/cookbook/use_cases/intelligence/03_Law_Enforcement_Forensics.ipynb
index f455a878..9ec7d30d 100644
--- a/cookbook/use_cases/intelligence/03_Law_Enforcement_Forensics.ipynb
+++ b/cookbook/use_cases/intelligence/03_Law_Enforcement_Forensics.ipynb
@@ -43,7 +43,7 @@
"- **Ingest**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, RepoIngestor, EmailIngestor, MCPIngestor (case files, evidence databases)\n",
"- **Parse**: DocumentParser, StructuredDataParser, JSONParser, CSVParser\n",
"- **Normalize**: TextNormalizer, DataNormalizer\n",
- "- **Semantic Extract**: NERExtractor, RelationExtractor, TripleExtractor, EventDetector\n",
+ "- **Semantic Extract**: NERExtractor, RelationExtractor, TripletExtractor, EventDetector\n",
"- **KG**: GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer\n",
"- **Graph Analytics**: Community detection, centrality measures, path finding\n",
"- **Embeddings**: EmbeddingGenerator, TextEmbedder\n",
@@ -98,7 +98,7 @@
"from semantica.ingest import FileIngestor, DBIngestor\n",
"from semantica.parse import DocumentParser, StructuredDataParser, JSONParser, CSVParser\n",
"from semantica.normalize import TextNormalizer, DataNormalizer\n",
- "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripleExtractor, EventDetector\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripletExtractor, EventDetector\n",
"from semantica.kg import GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer\n",
"from semantica.embeddings import EmbeddingGenerator, TextEmbedder\n",
"from semantica.vector_store import VectorStore, HybridSearch, MetadataFilter\n",
diff --git a/cookbook/use_cases/renewable_energy/03_Grid_Management.ipynb b/cookbook/use_cases/renewable_energy/03_Grid_Management.ipynb
index 990be409..dae9e01c 100644
--- a/cookbook/use_cases/renewable_energy/03_Grid_Management.ipynb
+++ b/cookbook/use_cases/renewable_energy/03_Grid_Management.ipynb
@@ -19,7 +19,7 @@
"\n",
"- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, RepoIngestor, EmailIngestor, MCPIngestor\n",
"- **Parsing**: JSONParser, StructuredDataParser, CSVParser\n",
- "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripleExtractor\n",
+ "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",
"- **KG**: GraphBuilder, TemporalGraphQuery, TemporalPatternDetector, GraphAnalyzer\n",
"- **Analytics**: CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",
"- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",
@@ -65,7 +65,7 @@
"source": [
"from semantica.ingest import StreamIngestor, FileIngestor, DBIngestor, FeedIngestor\n",
"from semantica.parse import JSONParser, StructuredDataParser, CSVParser\n",
- "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, TripleExtractor\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",
"from semantica.kg import GraphBuilder, TemporalGraphQuery, TemporalPatternDetector, GraphAnalyzer\n",
"from semantica.kg import CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",
"from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",
@@ -189,7 +189,7 @@
"ner_extractor = NERExtractor()\n",
"relation_extractor = RelationExtractor()\n",
"event_detector = EventDetector()\n",
- "triple_extractor = TripleExtractor()\n",
+ "triplet_extractor = TripletExtractor()\n",
"\n",
"grid_entities = []\n",
"grid_relationships = []\n",
diff --git a/cookbook/use_cases/supply_chain/01_Supply_Chain_Data_Integration.ipynb b/cookbook/use_cases/supply_chain/01_Supply_Chain_Data_Integration.ipynb
index 2dda89d8..840f96e7 100644
--- a/cookbook/use_cases/supply_chain/01_Supply_Chain_Data_Integration.ipynb
+++ b/cookbook/use_cases/supply_chain/01_Supply_Chain_Data_Integration.ipynb
@@ -31,7 +31,7 @@
"\n",
"- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, EmailIngestor, RepoIngestor, MCPIngestor\n",
"- **Parsing**: MCPParser, JSONParser, StructuredDataParser, CSVParser\n",
- "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripleExtractor\n",
+ "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",
"- **KG**: GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer\n",
"- **Analytics**: CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",
"- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",
@@ -66,7 +66,7 @@
"source": [
"from semantica.ingest import MCPIngestor, ingest_mcp, DBIngestor, FileIngestor\n",
"from semantica.parse import MCPParser, JSONParser, StructuredDataParser, CSVParser\n",
- "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, TripleExtractor\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",
"from semantica.kg import GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer\n",
"from semantica.kg import CentralityCalculator, CommunityDetector\n",
"from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",
@@ -293,7 +293,7 @@
"ner_extractor = NERExtractor()\n",
"relation_extractor = RelationExtractor()\n",
"event_detector = EventDetector()\n",
- "triple_extractor = TripleExtractor()\n",
+ "triplet_extractor = TripletExtractor()\n",
"\n",
"supply_chain_entities = []\n",
"supply_chain_relationships = []\n",
diff --git a/cookbook/use_cases/supply_chain/02_Supply_Chain_Risk_Management.ipynb b/cookbook/use_cases/supply_chain/02_Supply_Chain_Risk_Management.ipynb
index 251b6ccd..13bc3acd 100644
--- a/cookbook/use_cases/supply_chain/02_Supply_Chain_Risk_Management.ipynb
+++ b/cookbook/use_cases/supply_chain/02_Supply_Chain_Risk_Management.ipynb
@@ -41,7 +41,7 @@
"- **Ingest**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, RepoIngestor, EmailIngestor, MCPIngestor (supply chain data from multiple sources)\n",
"- **Parse**: StructuredDataParser, JSONParser, CSVParser (BOM data, supplier data, tariff data)\n",
"- **Normalize**: TextNormalizer, DataNormalizer (for data standardization)\n",
- "- **Semantic Extract**: RelationExtractor, TripleExtractor (supplier relationships, dependencies, risk factors)\n",
+ "- **Semantic Extract**: RelationExtractor, TripletExtractor (supplier relationships, dependencies, risk factors)\n",
"- **KG**: GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer (supply chain graph construction)\n",
"- **Graph Analytics**: Use Semantica's GraphAnalyzer for community detection, centrality measures (PageRank, Betweenness, Closeness)\n",
"- **Embeddings**: EmbeddingGenerator (for supplier similarity, risk clustering)\n",
@@ -90,7 +90,7 @@
"from semantica.ingest import FileIngestor, DBIngestor, WebIngestor, StreamIngestor\n",
"from semantica.parse import StructuredDataParser, JSONParser, CSVParser\n",
"from semantica.normalize import TextNormalizer, DataNormalizer\n",
- "from semantica.semantic_extract import RelationExtractor, TripleExtractor\n",
+ "from semantica.semantic_extract import RelationExtractor, TripletExtractor\n",
"from semantica.kg import GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer\n",
"from semantica.embeddings import EmbeddingGenerator\n",
"from semantica.vector_store import VectorStore, HybridSearch\n",
@@ -261,7 +261,7 @@
"source": [
"# Initialize Semantica extractors\n",
"relation_extractor = RelationExtractor()\n",
- "triple_extractor = TripleExtractor()\n",
+ "triplet_extractor = TripletExtractor()\n",
"\n",
"# Build supply chain entities and relationships\n",
"supply_chain_entities = []\n",
diff --git a/cookbook/use_cases/trading/03_Real_Time_Monitoring.ipynb b/cookbook/use_cases/trading/03_Real_Time_Monitoring.ipynb
index 37bef3d9..ebbd088b 100644
--- a/cookbook/use_cases/trading/03_Real_Time_Monitoring.ipynb
+++ b/cookbook/use_cases/trading/03_Real_Time_Monitoring.ipynb
@@ -29,7 +29,7 @@
"\n",
"- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, EmailIngestor, RepoIngestor, MCPIngestor\n",
"- **Parsing**: JSONParser, StructuredDataParser\n",
- "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripleExtractor\n",
+ "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",
"- **KG**: GraphBuilder, TemporalGraphQuery, TemporalPatternDetector, GraphAnalyzer\n",
"- **Analytics**: CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",
"- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",
@@ -65,7 +65,7 @@
"source": [
"from semantica.ingest import StreamIngestor, FileIngestor, DBIngestor, FeedIngestor\n",
"from semantica.parse import JSONParser, StructuredDataParser\n",
- "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, TripleExtractor\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",
"from semantica.kg import GraphBuilder, TemporalGraphQuery, TemporalPatternDetector, GraphAnalyzer\n",
"from semantica.kg import CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",
"from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",
@@ -172,7 +172,7 @@
"ner_extractor = NERExtractor()\n",
"relation_extractor = RelationExtractor()\n",
"event_detector = EventDetector()\n",
- "triple_extractor = TripleExtractor()\n",
+ "triplet_extractor = TripletExtractor()\n",
"\n",
"trading_entities = []\n",
"trading_relationships = []\n",
diff --git a/docs/CodeExamples.md b/docs/CodeExamples.md
index 1ffda8f2..5387d3e3 100644
--- a/docs/CodeExamples.md
+++ b/docs/CodeExamples.md
@@ -50,7 +50,7 @@ knowledge_base = core.build_knowledge_base(sources)
print(f"Processed {len(knowledge_base.documents)} documents")
print(f"Extracted {len(knowledge_base.entities)} entities")
-print(f"Generated {len(knowledge_base.triples)} semantic triples")
+print(f"Generated {len(knowledge_base.triplets)} semantic triplets")
print(f"Created {len(knowledge_base.embeddings)} vector embeddings")
# Query the knowledge base
@@ -85,7 +85,7 @@ excel_content = doc_processor.process_excel("data.xlsx")
# Extract semantic information
for content in [pdf_content, docx_content, pptx_content]:
semantics = core.extract_semantics(content)
- triples = core.generate_triples(semantics)
+ triplets = core.generate_triplets(semantics)
embeddings = core.create_embeddings(content.chunks)
```
@@ -128,7 +128,7 @@ for feed_url in feeds:
# Process new feed items
async for item in feed_processor.stream_items():
semantics = core.extract_semantics(item.content)
- knowledge_graph.add_triples(core.generate_triples(semantics))
+ knowledge_graph.add_triplets(core.generate_triplets(semantics))
```
### 📊 Structured Data Processing Module
@@ -154,7 +154,7 @@ xml_data = structured_processor.process_xml("data.xml")
# Extract semantic relationships
for data in [json_data, csv_data, yaml_data, xml_data]:
schema = structured_processor.generate_schema(data)
- triples = structured_processor.extract_triples(data, schema)
+ triplets = structured_processor.extract_triplets(data, schema)
ontology = structured_processor.create_ontology(schema)
```
@@ -189,7 +189,7 @@ archive_contents = archive_processor.process_archive("documents.zip")
# Extract semantic information from all contents
for content in archive_contents:
semantics = core.extract_semantics(content)
- triples = core.generate_triples(semantics)
+ triplets = core.generate_triplets(semantics)
```
### 🔬 Scientific & Academic Processing Module
@@ -212,47 +212,47 @@ latex_content = academic_processor.process_latex("paper.tex")
bibtex_content = academic_processor.process_bibtex("references.bib")
jats_content = academic_processor.process_jats("article.xml")
-# Extract academic semantic triples
+# Extract academic semantic triplets
for content in [latex_content, bibtex_content, jats_content]:
academic_semantics = academic_processor.extract_academic_entities(content)
citation_graph = academic_processor.build_citation_network(content)
- research_triples = academic_processor.generate_research_triples(content)
+ research_triplets = academic_processor.generate_research_triples(content)
```
---
## 🧩 Semantic Extraction & Transformation
-### 🎯 Automatic Triple Generation
+### 🎯 Automatic Triplet Generation
-Generate RDF triples from any content automatically:
+Generate semantic triplets from any content automatically:
```python
-from semantica.extraction import TripleExtractor
+from semantica.extraction import TripletExtractor
-# Initialize triple extractor
-triple_extractor = TripleExtractor(
+# Initialize triplet extractor
+triplet_extractor = TripletExtractor(
confidence_threshold=0.8,
include_implicit_relations=True,
temporal_modeling=True
)
-# Extract triples from any content
+# Extract triplets from any content
text = "Apple Inc. was founded by Steve Jobs in 1976 in Cupertino, California."
-triples = triple_extractor.extract_triples(text)
+triplets = triplet_extractor.extract_triplets(text)
-print(triples)
+print(triplets)
# [
-# Triple(subject="Apple Inc.", predicate="founded_by", object="Steve Jobs"),
-# Triple(subject="Apple Inc.", predicate="founded_in", object="1976"),
-# Triple(subject="Apple Inc.", predicate="located_in", object="Cupertino"),
-# Triple(subject="Cupertino", predicate="located_in", object="California")
+# Triplet(subject="Apple Inc.", predicate="founded_by", object="Steve Jobs"),
+# Triplet(subject="Apple Inc.", predicate="founded_in", object="1976"),
+# Triplet(subject="Apple Inc.", predicate="located_in", object="Cupertino"),
+# Triplet(subject="Cupertino", predicate="located_in", object="California")
# ]
# Export to various formats
-turtle_format = triple_extractor.to_turtle(triples)
-ntriples_format = triple_extractor.to_ntriples(triples)
-jsonld_format = triple_extractor.to_jsonld(triples)
+turtle_format = triplet_extractor.serialize_triplets(triplets, format="turtle")
+ntriples_format = triplet_extractor.serialize_triplets(triplets, format="ntriples")
+jsonld_format = triplet_extractor.serialize_triplets(triplets, format="jsonld")
```
### 🧠 Ontology Generation Module
@@ -280,7 +280,7 @@ rdf_ontology = ontology.to_rdf()
turtle_ontology = ontology.to_turtle()
# Save to triplet store
-ontology.save_to_triple_store("http://localhost:9999/blazegraph/sparql")
+ontology.save_to_triplet_store("http://localhost:9999/blazegraph/sparql")
```
### 📊 Graph Store - Persistent Property Graph Storage
@@ -398,11 +398,11 @@ async for feed_item in feed_processor.stream():
# Extract semantics from new content
semantics = core.extract_semantics(feed_item.content)
- # Generate triples
- triples = core.generate_triples(semantics)
+ # Generate triplets
+ triplets = core.generate_triplets(semantics)
# Update knowledge graph
- knowledge_graph.add_triples(triples)
+ knowledge_graph.add_triplets(triplets)
# Create embeddings for search
embeddings = core.create_embeddings([feed_item.content])
@@ -447,8 +447,8 @@ async for message in kafka_processor.consume():
# Extract semantics and build knowledge
semantics = core.extract_semantics(processed)
- triples = core.generate_triples(semantics)
- knowledge_graph.add_triples(triples)
+ triplets = core.generate_triplets(semantics)
+ knowledge_graph.add_triplets(triplets)
```
---
@@ -545,8 +545,8 @@ sources = [
financial_knowledge = finance_processor.build_financial_knowledge_graph(sources)
-# Generate financial semantic triples
-triples = financial_knowledge.extract_financial_triples()
+# Generate financial semantic triplets
+triplets = financial_knowledge.extract_financial_triplets()
# Export to financial analysis platforms
financial_knowledge.export_to_bloomberg_api()
@@ -603,7 +603,7 @@ pipeline = PipelineBuilder() \
.add_semantic_processing([
"entity_extraction",
"relation_extraction",
- "triple_generation",
+ "triplet_generation",
"ontology_mapping"
]) \
.add_enrichment([
@@ -614,7 +614,7 @@ pipeline = PipelineBuilder() \
.add_output_formats([
"knowledge_graph",
"vector_embeddings",
- "rdf_triples",
+ "rdf_triplets",
"json_ld"
]) \
.build()
@@ -668,14 +668,14 @@ from semantica.quality import QualityAssurance
qa = QualityAssurance(
validation_rules=[
"entity_consistency",
- "triple_validity",
+ "triplet_validity",
"schema_compliance",
"ontology_alignment"
],
confidence_thresholds={
"entity_extraction": 0.8,
"relation_extraction": 0.7,
- "triple_generation": 0.9
+ "triplet_generation": 0.9
}
)
diff --git a/docs/LIBS_README.md b/docs/LIBS_README.md
index 32e2a478..4e38f192 100644
--- a/docs/LIBS_README.md
+++ b/docs/LIBS_README.md
@@ -510,12 +510,12 @@ for relation in relations:
print()
```
-#### Triple Extraction
+#### Triplet Extraction
```python
-from semantica.semantic_extract import TripleExtractor
+from semantica.semantic_extract import TripletExtractor
-# Initialize triple extractor
-triple_extractor = TripleExtractor(
+# Initialize triplet extractor
+triplet_extractor = TripletExtractor(
config={
"validator": {"strict": True},
"serializer": {"format": "turtle"}
@@ -525,13 +525,13 @@ triple_extractor = TripleExtractor(
text = "Barack Obama was the President of the United States from 2009 to 2017."
# Extract RDF triples
-triples = triple_extractor.extract_triples(text)
+triplets = triplet_extractor.extract_triples(text)
-for triple in triples:
- print(f"Subject: {triple.subject}")
- print(f"Predicate: {triple.predicate}")
- print(f"Object: {triple.object}")
- print(f"Confidence: {triple.confidence}")
+for triplet in triples:
+ print(f"Subject: {triplet.subject}")
+ print(f"Predicate: {triplet.predicate}")
+ print(f"Object: {triplet.object}")
+ print(f"Confidence: {triplet.confidence}")
print()
```
diff --git a/docs/concepts.md b/docs/concepts.md
index 12dd4938..a60cc6c9 100644
--- a/docs/concepts.md
+++ b/docs/concepts.md
@@ -543,14 +543,14 @@ graph LR
print(f" {rel['source_text']} {arrow} {rel['target_text']}")
print(f" Relation: {rel['type']}")
```
-=== "Triple Extraction (RDF)"
- Extract subject-predicate-object triples for RDF/semantic web:
+=== "Triplet Extraction (RDF)"
+ Extract subject-predicate-object triplets for RDF/semantic web:
```python
from semantica.semantic_extract import (
- TripleExtractor,
+ TripletExtractor,
RDFSerializer,
- TripleValidator
+ TripletValidator
)
text = """
@@ -559,30 +559,30 @@ graph LR
Einstein worked at Princeton University until his death in 1955.
"""
- # Extract RDF-style triples
- extractor = TripleExtractor(
+ # Extract RDF-style triplets
+ extractor = TripletExtractor(
include_temporal=True, # Include time information
include_provenance=True # Track source sentences
)
- triples = extractor.extract_triples(text)
+ triplets = extractor.extract_triplets(text)
- print("Extracted Triples (Subject-Predicate-Object):")
- for triple in triples:
- print(f" Subject: {triple['subject']}")
- print(f" Predicate: {triple['predicate']}")
- print(f" Object: {triple['object']}")
- if triple.get('temporal'):
- print(f" When: {triple['temporal']}")
+ print("Extracted Triplets (Subject-Predicate-Object):")
+ for triplet in triplets:
+ print(f" Subject: {triplet['subject']}")
+ print(f" Predicate: {triplet['predicate']}")
+ print(f" Object: {triplet['object']}")
+ if triplet.get('temporal'):
+ print(f" When: {triplet['temporal']}")
print()
- validator = TripleValidator()
- validation = validator.validate(triples)
- print(f"Valid triples: {validation['valid_count']}/{len(triples)}")
+ validator = TripletValidator()
+ validation = validator.validate(triplets)
+ print(f"Valid triplets: {validation['valid_count']}/{len(triplets)}")
serializer = RDFSerializer(format="turtle")
turtle_output = serializer.serialize(
- triples,
+ triplets,
base_uri="https://example.org/knowledge/"
)
print("Turtle Output:")
diff --git a/docs/deep-dive.md b/docs/deep-dive.md
index b57b567c..53ada134 100644
--- a/docs/deep-dive.md
+++ b/docs/deep-dive.md
@@ -19,7 +19,7 @@ graph TB
D --> D1[Entity Extractor]
D --> D2[Relationship Extractor]
- D --> D3[Triple Extractor]
+ D --> D3[Triplet Extractor]
G --> G1[Graph Validator]
G --> G2[Graph Analyzer]
@@ -60,7 +60,7 @@ text → Tokenization → NER → Entity Linking → Entity Validation
**Components:**
- Named Entity Recognition (NER)
- Relationship Extraction
-- Triple Extraction
+- Triplet Extraction
- Coreference Resolution
### 4. Normalization Layer
diff --git a/docs/glossary.md b/docs/glossary.md
index db813079..ba1e6e36 100644
--- a/docs/glossary.md
+++ b/docs/glossary.md
@@ -147,7 +147,7 @@ A comprehensive reference of terms and concepts used in Semantica.
: A technique that enhances LLM responses by retrieving relevant information from a knowledge base before generating an answer.
**RDF (Resource Description Framework)**
-: A W3C standard for representing information about resources in the form of subject-predicate-object triples.
+: A W3C standard for representing information about resources in the form of subject-predicate-object triplets.
**Reasoning**
: The process of deriving new knowledge from existing facts using logical rules and inference.
@@ -178,11 +178,11 @@ A comprehensive reference of terms and concepts used in Semantica.
**Temporal Graph**
: A knowledge graph that tracks changes over time, allowing queries about the state of the graph at specific time points.
-**Triple**
+**Triplet**
: A basic unit of knowledge in RDF, consisting of a subject, predicate, and object (e.g., `<Apple_Inc> <founded_by> <Steve_Jobs>`).
**Triplet Store**
-: A database designed specifically for storing and querying RDF triples.
+: A database designed specifically for storing and querying RDF triplets.
---
diff --git a/docs/index.md b/docs/index.md
index 61efecfc..c3ffd2ce 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -335,7 +335,7 @@ Transform raw text into structured semantic knowledge with state-of-the-art NLP
- **Relationship Extraction**: Identify semantic, temporal, and causal relationships
- **Event Detection**: Detect and classify events (acquisitions, partnerships, announcements)
- **Coreference Resolution**: Resolve pronouns and entity mentions across documents
-- **Triple Extraction**: Generate RDF triples for knowledge graph construction
+- **Triplet Extraction**: Generate RDF triplets for knowledge graph construction
### 3. 🕸️ Knowledge Graph Construction
diff --git a/docs/modules.md b/docs/modules.md
index b121f66b..2639432a 100644
--- a/docs/modules.md
+++ b/docs/modules.md
@@ -142,7 +142,7 @@ for doc in parsed_docs:
- `SlidingWindowChunker` — Fixed-size sliding window chunking
- `TableChunker` — Table-specific chunking
- `EntityAwareChunker` — Entity boundary-preserving chunker
-- `RelationAwareChunker` — Triple-preserving chunker
+- `RelationAwareChunker` — Triplet-preserving chunker
- `GraphBasedChunker` — Graph structure-based chunker
- `OntologyAwareChunker` — Ontology concept-based chunker
- `HierarchicalChunker` — Multi-level hierarchical chunker
@@ -412,7 +412,7 @@ print(f"Inferred {len(new_facts)} new facts")
## Storage Layer
-These modules handle persistence and retrieval of vectors, graphs, and triples.
+These modules handle persistence and retrieval of vectors, graphs, and triplets.
---
@@ -605,8 +605,8 @@ from semantica.triplet_store import TripletManager, execute_query
manager = TripletManager()
store = manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
-# Add triple
-result = manager.add_triple({
+# Add triplet
+result = manager.add_triplet({
"subject": "http://example.org/Alice",
"predicate": "http://example.org/knows",
"object": "http://example.org/Bob"
diff --git a/docs/reference/reasoning.md b/docs/reference/reasoning.md
index 475d5002..9b3b1eca 100644
--- a/docs/reference/reasoning.md
+++ b/docs/reference/reasoning.md
@@ -70,7 +70,7 @@
### SPARQL Reasoning
- **Query Rewriting**: Modifying queries to include inferred patterns.
- **Property Paths**: Handling transitive relationships (`foaf:knows+`).
-- **Materialization**: Pre-computing inferred triples for fast read performance.
+- **Materialization**: Pre-computing inferred triplets for fast read performance.
### Abductive Reasoning
- **Hypothesis Generation**: Finding rules where the conclusion matches the observation.
@@ -128,7 +128,7 @@ SPARQL-based reasoner for RDF graphs.
| Method | Description |
|--------|-------------|
| `expand_query(query)` | Rewrite query with inference |
-| `infer_results(result)` | Add inferred triples to result |
+| `infer_results(result)` | Add inferred triplets to result |
### AbductiveReasoner
@@ -221,14 +221,14 @@ rules = [
# 2. Load Graph
kg = KnowledgeGraph()
-facts = kg.get_all_triples()
+facts = kg.get_all_triplets()
# 3. Run Inference
engine = InferenceEngine()
-inferred_triples = engine.infer(facts, rules)
+inferred_triplets = engine.infer(facts, rules)
# 4. Update Graph
-kg.add_triples(inferred_triples)
+kg.add_triplets(inferred_triplets)
```
---
diff --git a/docs/reference/semantic_extract.md b/docs/reference/semantic_extract.md
index 971116ad..0679dfad 100644
--- a/docs/reference/semantic_extract.md
+++ b/docs/reference/semantic_extract.md
@@ -1,6 +1,6 @@
# Semantic Extract
-> **Advanced information extraction system for Entities, Relations, Events, and Triples.**
+> **Advanced information extraction system for Entities, Relations, Events, and Triplets.**
---
@@ -32,11 +32,11 @@
Resolve pronouns ("he", "it") to their entity references
-- :material-share-variant:{ .lg .middle } **Triple Extraction**
+- :material-share-variant:{ .lg .middle } **Triplet Extraction**
---
- Extract Subject-Predicate-Object triples for Knowledge Graphs
+ Extract Subject-Predicate-Object triplets for Knowledge Graphs
- :material-robot:{ .lg .middle } **LLM Enhancement**
@@ -77,7 +77,7 @@
- **Clustering**: Grouping mentions that refer to the same real-world entity.
- **Pronoun Resolution**: Mapping pronouns to the most likely antecedent.
-### Triple Extraction
+### Triplet Extraction
- **OpenIE**: Open Information Extraction for arbitrary relation strings.
- **Schema-Based**: Mapping extracted relations to a predefined ontology.
- **Reification**: Handling complex relations (time, location) by creating event nodes.
@@ -276,9 +276,9 @@ detector = EventDetector(
events = detector.detect_events("SpaceX launched Starship on March 14, 2024.")
```
-### TripleExtractor
+### TripletExtractor
-Extracts RDF triples (Subject-Predicate-Object).
+Extracts RDF triplets (Subject-Predicate-Object).
**Parameters:**
@@ -292,19 +292,19 @@ Extracts RDF triples (Subject-Predicate-Object).
| Method | Description |
|--------|-------------|
-| `extract_triples(text)` | Get (S, P, O) tuples |
+| `extract_triplets(text)` | Get (S, P, O) tuples |
**Example:**
```python
-from semantica.semantic_extract import TripleExtractor
+from semantica.semantic_extract import TripletExtractor
-extractor = TripleExtractor(
+extractor = TripletExtractor(
include_temporal=True,
include_provenance=True
)
-triples = extractor.extract_triples("Steve Jobs founded Apple in 1976.")
-# [Triple(subject="Steve Jobs", predicate="founded", object="Apple", temporal="1976")]
+triplets = extractor.extract_triplets("Steve Jobs founded Apple in 1976.")
+# [Triplet(subject="Steve Jobs", predicate="founded", object="Apple", temporal="1976")]
```
### SemanticNetworkExtractor
@@ -375,7 +375,7 @@ enhanced_entities = enhancer.enhance_entities(text, entities)
from semantica.semantic_extract import (
NamedEntityRecognizer,
RelationExtractor,
- TripleExtractor,
+ TripletExtractor,
EventDetector,
CoreferenceResolver,
SemanticNetworkExtractor
@@ -395,9 +395,9 @@ resolved = coref.resolve(text)
rel_extractor = RelationExtractor(confidence_threshold=0.6)
relations = rel_extractor.extract_relations(text, entities=entities)
-# Extract triples for KG
-triple_extractor = TripleExtractor(include_temporal=True)
-triples = triple_extractor.extract_triples(text)
+# Extract triplets for KG
+triplet_extractor = TripletExtractor(include_temporal=True)
+triplets = triplet_extractor.extract_triplets(text)
# Detect events
event_detector = EventDetector(extract_time=True)
@@ -409,7 +409,7 @@ network = network_extractor.extract(text)
print(f"Entities: {len(entities)}")
print(f"Relations: {len(relations)}")
-print(f"Triples: {len(triples)}")
+print(f"Triplets: {len(triplets)}")
print(f"Events: {len(events)}")
print(f"Network Nodes: {len(network.nodes)}")
```
@@ -448,21 +448,21 @@ semantic_extract:
### KG Population Pipeline
```python
-from semantica.semantic_extract import NamedEntityRecognizer, RelationExtractor, TripleExtractor
+from semantica.semantic_extract import NamedEntityRecognizer, RelationExtractor, TripletExtractor
from semantica.kg import GraphBuilder
# 1. Extract
text = "Google was founded by Larry Page and Sergey Brin."
ner = NamedEntityRecognizer()
entities = ner.extract_entities(text)
-triple_extractor = TripleExtractor()
-triples = triple_extractor.extract_triples(text)
+triplet_extractor = TripletExtractor()
+triplets = triplet_extractor.extract_triplets(text)
# 2. Populate KG using GraphBuilder
builder = GraphBuilder()
sources = [{
"entities": entities,
- "relationships": [{"source": t.subject, "target": t.object, "type": t.predicate} for t in triples]
+ "relationships": [{"source": t.subject, "target": t.object, "type": t.predicate} for t in triplets]
}]
kg = builder.build(sources)
```
diff --git a/docs/reference/split.md b/docs/reference/split.md
index b5b9cdf6..c5e7ba7b 100644
--- a/docs/reference/split.md
+++ b/docs/reference/split.md
@@ -80,8 +80,8 @@
- NER-based entity extraction (spaCy, LLM)
- Entity span tracking
- Boundary preservation (no entity splitting)
-- **Triple Preservation**:
- - Graph-based triple integrity checking
+- **Triplet Preservation**:
+ - Graph-based triplet integrity checking
- Subject-predicate-object span tracking
- Relationship boundary preservation
- **Graph Centrality Analysis**:
@@ -278,15 +278,15 @@ for chunk in chunks:
### RelationAwareChunker
-Preserve relationship triples during chunking.
+Preserve relationship triplets during chunking.
**Methods:**
| Method | Description | Algorithm |
|--------|-------------|-----------|
-| `chunk(text, relationships)` | Chunk preserving triples | Triple span tracking |
+| `chunk(text, relationships)` | Chunk preserving triplets | Triplet span tracking |
| `extract_relationships(text)` | Extract relationships | Relation extraction |
-| `validate_triple_integrity(chunk, relationships)` | Validate triples | Integrity checking |
+| `validate_triplet_integrity(chunk, relationships)` | Validate triplets | Integrity checking |
**Example:**
@@ -301,7 +301,7 @@ relationships = rel_extractor.extract(text)
# Chunk preserving relationships
chunker = RelationAwareChunker(
chunk_size=1000,
- preserve_triples=True
+ preserve_triplets=True
)
chunks = chunker.chunk(text, relationships=relationships)
@@ -697,7 +697,7 @@ split:
min_entity_gap: 50
relation_aware:
- preserve_triples: true
+ preserve_triplets: true
relation_extraction_method: llm
graph_based:
@@ -728,7 +728,7 @@ split:
| **sentence** | Coherent chunks | Respects sentences | Variable size |
| **semantic_transformer** | Topic coherence | Semantic boundaries | Slower, needs embeddings |
| **entity_aware** | GraphRAG | Preserves entities | Requires NER |
-| **relation_aware** | KG extraction | Preserves triples | Requires relation extraction |
+| **relation_aware** | KG extraction | Preserves triplets | Requires relation extraction |
| **graph_based** | Graph analysis | Graph-aware | Requires graph construction |
| **hierarchical** | Large documents | Multi-level | More complex |
| **structural** | Formatted docs | Respects structure | Needs structure |
diff --git a/docs/reference/triplet_store.md b/docs/reference/triplet_store.md
index 81880afc..aa554a22 100644
--- a/docs/reference/triplet_store.md
+++ b/docs/reference/triplet_store.md
@@ -58,7 +58,7 @@
### Query Algorithms
- **SPARQL Query Optimization**: Join reordering with selectivity estimation
-- **Triple Pattern Matching**: Index-based lookup with B+ trees
+- **Triplet Pattern Matching**: Index-based lookup with B+ trees
- **Graph Pattern Matching**: Subgraph isomorphism with backtracking
- **Query Planning**: Cost-based optimization with statistics
- **Join Algorithms**: Hash join, merge join, nested loop join
@@ -75,12 +75,12 @@
### Reasoning Algorithms
- **RDFS Reasoning**: Subclass/subproperty inference, domain/range inference
- **OWL Reasoning**: Class hierarchy, property characteristics, cardinality constraints
-- **Forward Chaining**: Materialization of inferred triples
+- **Forward Chaining**: Materialization of inferred triplets
- **Backward Chaining**: On-demand inference during query execution
- **Rule-Based Inference**: Custom SWRL rules
### Bulk Loading
-- **Batch Processing**: Chunked triple insertion with configurable batch size
+- **Batch Processing**: Chunked triplet insertion with configurable batch size
- **Parallel Loading**: Multi-threaded data loading
- **Index Building**: Deferred index construction for faster loading
- **Transaction Management**: Atomic batch commits with rollback support
@@ -98,8 +98,8 @@ Main coordinator for triplet store operations across multiple backends.
| Method | Description | Algorithm |
|--------|-------------|-----------|
| `register_store(store_id, backend, endpoint)` | Register triplet store | Store registration |
-| `add_triple(triple, store_id)` | Add single triplet | Index insertion |
-| `add_triples(triples, store_id)` | Batch add triplets | Bulk index insertion |
+| `add_triplet(triplet, store_id)` | Add single triplet | Index insertion |
+| `add_triplets(triplets, store_id)` | Batch add triplets | Bulk index insertion |
| `query(sparql, store_id)` | Execute SPARQL query | Query optimization + execution |
| `delete(pattern, store_id)` | Delete matching triplets | Pattern matching + deletion |
| `bulk_load(file_path, format, store_id)` | Bulk load from file | Streaming parser + batch insert |
@@ -120,9 +120,9 @@ store = manager.register_store(
endpoint="http://localhost:9999/blazegraph/sparql"
)
-# Add single triple
-result = manager.add_triple(
- triple={
+# Add single triplet
+result = manager.add_triplet(
+ triplet ={
"subject": "http://example.org/Alice",
"predicate": "http://example.org/knows",
"object": "http://example.org/Bob"
@@ -130,8 +130,8 @@ result = manager.add_triple(
store_id="main"
)
-# Add multiple triples
-triples = [
+# Add multiple triplets
+triplets = [
{
"subject": "http://example.org/Alice",
"predicate": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
@@ -144,7 +144,7 @@ triples = [
}
]
-manager.add_triples(triples, store_id="main")
+manager.add_triplets(triplets, store_id="main")
# Query with SPARQL
results = manager.query("""
@@ -162,7 +162,7 @@ for row in results["results"]["bindings"]:
# Get statistics
stats = manager.get_stats("main")
-print(f"Total triples: {stats['triple_count']}")
+print(f"Total triplets: {stats['triplet_count']}")
```
---
@@ -261,8 +261,8 @@ High-performance bulk data loading with progress tracking.
**Supported Formats:**
- **RDF/XML**: W3C RDF/XML format
-- **Turtle**: Terse RDF Triple Language
-- **N-Triples**: Line-based triple format
+- **Turtle**: Terse RDF Triplet Language
+- **N-Triples**: Line-based triplet format
- **N-Quads**: N-Triples with named graphs
- **JSON-LD**: JSON-based RDF format
- **TriG**: Turtle with named graphs
@@ -289,8 +289,8 @@ progress = loader.load(
store=store
)
-print(f"Loaded {progress['triples_loaded']} triples in {progress['elapsed_time']:.2f}s")
-print(f"Throughput: {progress['triples_per_second']:.0f} triples/sec")
+print(f"Loaded {progress['triplets_loaded']} triplets in {progress['elapsed_time']:.2f}s")
+print(f"Throughput: {progress['triplets_per_second']:.0f} triplets/sec")
# Load from URL
progress = loader.load_from_url(
@@ -350,8 +350,8 @@ adapter.create_namespace("my_kb", properties={
"com.bigdata.rdf.store.AbstractTripleStore.geoSpatial": "true"
})
-# Add triples
-adapter.add_triple(
+# Add triplets
+adapter.add_triplet(
subject="http://example.org/Alice",
predicate="http://example.org/name",
object_literal="Alice",
@@ -394,14 +394,14 @@ adapter = JenaAdapter(
adapter.connect()
-# Add triples with inference
-adapter.add_triple(
+# Add triplets with inference
+adapter.add_triplet(
subject="http://example.org/Dog",
predicate="http://www.w3.org/2000/01/rdf-schema#subClassOf",
object="http://example.org/Animal"
)
-adapter.add_triple(
+adapter.add_triplet(
subject="http://example.org/Fido",
predicate="http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
object="http://example.org/Dog"
@@ -460,10 +460,10 @@ adapter = RDF4JAdapter(
adapter.connect()
-# Add triples with transaction
+# Add triplet with transaction
adapter.begin_transaction()
try:
- adapter.add_triple(
+ adapter.add_triplet(
subject="http://example.org/Alice",
predicate="http://example.org/name",
object_literal="Alice"
@@ -508,11 +508,10 @@ adapter = VirtuosoAdapter(
adapter.connect()
-# Add triples to named graph
+# Add triplets to named graph
graph_uri = "http://example.org/graph1"
-adapter.create_graph(graph_uri)
-adapter.add_triple(
+adapter.add_triplet(
subject="http://example.org/Alice",
predicate="http://example.org/name",
object_literal="Alice",
@@ -538,16 +537,17 @@ Quick access to triplet store operations:
```python
from semantica.triplet_store import (
- add_triple,
- add_triples,
+ add_triplet,
+ add_triplets,
+ get_triplets,
execute_query,
bulk_load,
export_graph,
import_graph
)
-# Add single triple
-add_triple(
+# Add single triplet
+add_triplet(
subject="http://example.org/Alice",
predicate="http://example.org/knows",
object="http://example.org/Bob"
@@ -632,9 +632,9 @@ Bulk loading progress dataclass.
| Attribute | Type | Description |
|-----------|------|-------------|
-| `loaded_triples` | int | Number of triples loaded |
-| `total_triples` | int | Total triples to load |
-| `failed_triples` | int | Number of failed triples |
+| `loaded_triplets` | int | Number of triplets loaded |
+| `total_triplets` | int | Total triplets to load |
+| `failed_triplets` | int | Number of failed triplets |
| `progress_percentage` | float | Loading progress (0-100) |
| `elapsed_time` | float | Time elapsed (seconds) |
| `current_batch` | int | Current batch number |
@@ -880,7 +880,7 @@ query = """
### Bulk Loading Optimization
```python
-from semantica.triple_store import BulkLoader
+from semantica.triplet_store import BulkLoader
loader = BulkLoader(
batch_size=50000, # Larger batches for better performance
@@ -915,38 +915,38 @@ adapter.create_fulltext_index([
```python
from semantica.kg import GraphBuilder
-from semantica.triple_store import TripleManager, BulkLoader
+from semantica.triplet_store import TripletManager, BulkLoader
# Build knowledge graph
builder = GraphBuilder()
kg = builder.build(entities, relationships)
-# Convert to RDF triples
-triples = []
+# Convert to RDF triplets
+triplets = []
for entity in kg.entities:
- triples.append({
+ triplets.append({
"subject": f"http://example.org/{entity.id}",
"predicate": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
"object": f"http://example.org/{entity.type}"
})
for prop, value in entity.properties.items():
- triples.append({
+ triplets.append({
"subject": f"http://example.org/{entity.id}",
"predicate": f"http://example.org/{prop}",
"object_literal": str(value)
})
-# Load into triple store
-manager = TripleManager()
+# Load into triplet store
+manager = TripletManager()
store = manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph/sparql")
-manager.add_triples(triples, store_id="main")
+manager.add_triplets(triplets, store_id="main")
```
### Semantic Search with SPARQL
```python
-from semantica.triple_store import QueryEngine
+from semantica.triplet_store import QueryEngine
engine = QueryEngine()
@@ -1017,7 +1017,7 @@ loader = BulkLoader(
```python
# Solution: Validate query first
-from semantica.triple_store import QueryEngine
+from semantica.triplet_store import QueryEngine
engine = QueryEngine()
is_valid = engine.validate_query(sparql_query)
@@ -1036,4 +1036,4 @@ if not is_valid:
- [Export Module](export.md) - Export to various formats
## Cookbook
-- [Triple Store](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/20_Triple_Store.ipynb)
+- [Triplet Store](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/20_Triplet_Store.ipynb)
diff --git a/semantica/export/__init__.py b/semantica/export/__init__.py
index 79a4f99f..c17c1edf 100644
--- a/semantica/export/__init__.py
+++ b/semantica/export/__init__.py
@@ -10,9 +10,9 @@ Algorithms Used:
RDF Export:
- RDF Serialization: Multiple format serialization (Turtle, RDF/XML, JSON-LD, N-Triples, N3)
- Namespace Management: Namespace registration, conflict resolution, declaration generation
- - RDF Validation: RDF syntax validation, triple validation, namespace validation
+ - RDF Validation: RDF syntax validation, triplet validation, namespace validation
- URI Generation: Hash-based and text-based URI assignment for RDF resources
- - Triple Extraction: Entity and relationship to RDF triple conversion
+ - Triplet Extraction: Entity and relationship to RDF triplet conversion
- Format Conversion: Cross-format RDF conversion algorithms
LPG (Labeled Property Graph) Export:
diff --git a/semantica/export/methods.py b/semantica/export/methods.py
index e06d1de9..821de83f 100644
--- a/semantica/export/methods.py
+++ b/semantica/export/methods.py
@@ -58,9 +58,9 @@ Algorithms Used:
RDF Export:
- RDF Serialization: Multiple format serialization (Turtle, RDF/XML, JSON-LD, N-Triples, N3)
- Namespace Management: Namespace registration, conflict resolution, declaration generation
- - RDF Validation: RDF syntax validation, triple validation, namespace validation
+ - RDF Validation: RDF syntax validation, triplet validation, namespace validation
- URI Generation: Hash-based and text-based URI assignment for RDF resources
- - Triple Extraction: Entity and relationship to RDF triple conversion
+ - Triplet Extraction: Entity and relationship to RDF triplet conversion
- Format Conversion: Cross-format RDF conversion algorithms
LPG (Labeled Property Graph) Export:
@@ -183,7 +183,7 @@ def export_rdf(
This is a user-friendly wrapper that exports data to RDF using the specified format.
Args:
- data: Data to export (knowledge graph, entities, relationships, or triples)
+ data: Data to export (knowledge graph, entities, relationships, or triplets)
file_path: Output RDF file path
format: RDF format (default: "turtle")
- "turtle": Turtle format
diff --git a/semantica/export/rdf_exporter.py b/semantica/export/rdf_exporter.py
index 13c5c737..2b677a69 100644
--- a/semantica/export/rdf_exporter.py
+++ b/semantica/export/rdf_exporter.py
@@ -246,7 +246,7 @@ class RDFSerializer:
Turtle is a compact, human-readable RDF serialization format. This method
converts RDF data (entities and relationships) to Turtle syntax with
- namespace declarations and RDF triples.
+ namespace declarations and RDF triplets.
Args:
rdf_data: RDF data dictionary containing:
@@ -276,7 +276,7 @@ class RDFSerializer:
lines.append(ns_declarations)
lines.append("")
- # Convert entities to RDF triples
+ # Convert entities to RDF triplets
entities = rdf_data.get("entities", [])
for entity in entities:
# Generate entity ID if not provided
@@ -289,20 +289,20 @@ class RDFSerializer:
text = entity.get("text") or entity.get("label", "")
confidence = entity.get("confidence", 1.0)
- # Turtle triple syntax: subject predicate object .
+ # Turtle triplet syntax: subject predicate object .
lines.append(f"<{entity_id}> a <{entity_type}> ;")
lines.append(f' semantica:text "{text}" ;')
lines.append(f" semantica:confidence {confidence} .")
lines.append("")
- # Convert relationships to RDF triples
+ # Convert relationships to RDF triplets
relationships = rdf_data.get("relationships", [])
for rel in relationships:
source_id = rel.get("source_id") or rel.get("source")
target_id = rel.get("target_id") or rel.get("target")
rel_type = rel.get("type", "semantica:related_to")
- # Simple triple: subject predicate object .
+ # Simple triplet: subject predicate object .
lines.append(f"<{source_id}> <{rel_type}> <{target_id}> .")
return "\n".join(lines)
diff --git a/semantica/export/yaml_exporter.py b/semantica/export/yaml_exporter.py
index d910251e..4699157c 100644
--- a/semantica/export/yaml_exporter.py
+++ b/semantica/export/yaml_exporter.py
@@ -8,7 +8,7 @@ Key Features:
- Semantic network export to YAML
- Ontology schema export for human editing
- Pipeline-ready YAML format
- - Entity, relationship, and triple export
+ - Entity, relationship, and triplet export
- Class and property definition export
Example Usage:
@@ -85,14 +85,14 @@ class SemanticNetworkYAMLExporter:
"""
Export semantic network to YAML string.
- This method converts a semantic network (entities, relationships, triples)
+ This method converts a semantic network (entities, relationships, triplets)
to YAML format with metadata and provenance information.
Args:
semantic_network: Semantic network dictionary containing:
- entities: List of entity dictionaries
- relationships: List of relationship dictionaries
- - triples: List of triple dictionaries (optional)
+ - triplets: List of triplet dictionaries (optional)
- metadata: Metadata dictionary (optional)
**options: Additional export options (unused)
@@ -103,7 +103,7 @@ class SemanticNetworkYAMLExporter:
>>> network = {
... "entities": [...],
... "relationships": [...],
- ... "triples": [...]
+ ... "triplets": [...]
... }
>>> yaml_str = exporter.export_semantic_network(network)
"""
@@ -127,7 +127,7 @@ class SemanticNetworkYAMLExporter:
},
"entities": semantic_network.get("entities", []),
"relationships": semantic_network.get("relationships", []),
- "triples": semantic_network.get("triples", []),
+ "triplets": semantic_network.get("triplets", []),
}
self.progress_tracker.update_tracking(
@@ -201,7 +201,7 @@ class SemanticNetworkYAMLExporter:
"""
Export relationships to YAML format.
- • Format relationship triples
+ • Format relationship triplets
• Include relationship types
• Add directional information
• Return YAML representation
@@ -216,19 +216,19 @@ class SemanticNetworkYAMLExporter:
return self.yaml.dump(yaml_data, default_flow_style=False, sort_keys=False)
- def export_triples(
- self, triples: List[Dict[str, Any]], include_confidence: bool = True, **options
+ def export_triplets(
+ self, triplets: List[Dict[str, Any]], include_confidence: bool = True, **options
) -> str:
"""
- Export RDF triples to YAML format.
+ Export RDF triplets to YAML format.
- • Format subject-predicate-object triples
+ • Format subject-predicate-object triplets
• Include namespace information
• Add confidence and provenance
• Return YAML representation
"""
yaml_data = {
- "triples": [
+ "triplets": [
{
"subject": t.get("subject") or t.get("s"),
"predicate": t.get("predicate") or t.get("p"),
@@ -242,13 +242,13 @@ class SemanticNetworkYAMLExporter:
{"provenance": t.get("provenance")} if "provenance" in t else {}
),
}
- for t in triples
+ for t in triplets
]
}
yaml_data["metadata"] = {
"exported_at": datetime.now().isoformat(),
- "triple_count": len(triples),
+ "triplet_count": len(triplets),
}
return self.yaml.dump(yaml_data, default_flow_style=False, sort_keys=False)
@@ -273,7 +273,7 @@ class SemanticNetworkYAMLExporter:
"semantic_network": {
"entities": extracted_data.get("entities", []),
"relationships": extracted_data.get("relationships", []),
- "triples": extracted_data.get("triples", []),
+ "triplets": extracted_data.get("triplets", []),
},
}
diff --git a/semantica/ontology/__init__.py b/semantica/ontology/__init__.py
index aa0b2d30..1e228517 100644
--- a/semantica/ontology/__init__.py
+++ b/semantica/ontology/__init__.py
@@ -11,7 +11,7 @@ Ontology Generation (6-Stage Pipeline):
- Stage 2 - YAML-to-Definition: Transform concepts into class definitions, YAML parsing, definition structure creation, class inference (ClassInferrer.infer_classes)
- Stage 3 - Definition-to-Types: Map definitions to OWL types, type inference, OWL class/property mapping (@type assignment: owl:Class, owl:ObjectProperty, owl:DatatypeProperty), property inference (PropertyGenerator.infer_properties)
- Stage 4 - Hierarchy Generation: Build taxonomic structures, parent-child relationship inference, hierarchy validation, circular dependency detection (DFS), transitive closure calculation
- - Stage 5 - TTL Generation: Generate OWL/Turtle syntax using rdflib, namespace prefix handling, RDF serialization (rdflib.serialize format="turtle"), triple generation (subject-predicate-object)
+ - Stage 5 - TTL Generation: Generate OWL/Turtle syntax using rdflib, namespace prefix handling, RDF serialization (rdflib.serialize format="turtle"), triplet generation (subject-predicate-object)
- Stage 6 - Symbolic Validation: HermiT/Pellet reasoning (owlready2.sync_reasoner), consistency checking, satisfiability checking, constraint validation
Class Inference:
@@ -30,7 +30,7 @@ Ontology Validation:
- Hallucination Detection: LLM-generated ontology validation, fact verification, relationship validation, error/warning collection
OWL/RDF Generation:
- - RDF Graph Construction: rdflib.Graph creation, namespace binding, triple generation (subject-predicate-object), namespace prefix declaration
+ - RDF Graph Construction: rdflib.Graph creation, namespace binding, triplet generation (subject-predicate-object), namespace prefix declaration
- Serialization: Turtle format (rdflib.serialize format="turtle"), RDF/XML format, JSON-LD format, N3 format, format selection and conversion
- Namespace Management: Prefix declaration, IRI resolution, namespace prefix mapping, standard namespace registration (RDF, RDFS, OWL, XSD, SKOS, DC)
diff --git a/semantica/ontology/methods.py b/semantica/ontology/methods.py
index f941b925..3c56f699 100644
--- a/semantica/ontology/methods.py
+++ b/semantica/ontology/methods.py
@@ -62,7 +62,7 @@ Ontology Validation:
- Hallucination Detection: LLM-generated ontology validation, fact verification, relationship validation
OWL/RDF Generation:
- - RDF Graph Construction: rdflib.Graph creation, namespace binding, triple generation (subject-predicate-object)
+ - RDF Graph Construction: rdflib.Graph creation, namespace binding, triplet generation (subject-predicate-object)
- Serialization: Turtle format (rdflib.serialize format="turtle"), RDF/XML format, JSON-LD format, N3 format
- Namespace Management: Prefix declaration, IRI resolution, namespace prefix mapping
diff --git a/semantica/ontology/ontology_generator.py b/semantica/ontology/ontology_generator.py
index 672a4971..bffd6a79 100644
--- a/semantica/ontology/ontology_generator.py
+++ b/semantica/ontology/ontology_generator.py
@@ -51,7 +51,7 @@ class OntologyGenerator:
2. YAML-to-Definition → Transform into class definitions
3. Definition-to-Types → Map to OWL types
4. Hierarchy Generation → Build taxonomic structures
- 5. TTL Generation → Generate OWL/Turtle syntax
+ 5. TTL Generation → Generate OWL/Turtle syntax using rdflib, triplet generation (subject-predicate-object)
6. Symbolic Validation → HermiT/Pellet reasoning
• Generates ontologies from data and text
@@ -304,7 +304,7 @@ class OntologyGenerator:
"metadata": getattr(rel_item, "metadata", {}),
}
elif isinstance(rel_item, (list, tuple)) and len(rel_item) >= 3:
- # Assume [source, type, target] (RDF triple style)
+ # Assume [source, type, target] (RDF triplet style)
# or [source, target, type]
# Heuristic: if 2nd element is short and looks like a relation, assume [source, type, target]
rel = {
diff --git a/semantica/reasoning/__init__.py b/semantica/reasoning/__init__.py
index a6fcb14b..cefef696 100644
--- a/semantica/reasoning/__init__.py
+++ b/semantica/reasoning/__init__.py
@@ -22,7 +22,7 @@ Rete Algorithm:
SPARQL Reasoning:
- Query Expansion: Inference rule integration (convert rules to SPARQL patterns), query rewriting (add inferred patterns to WHERE clause), transitive closure (compute transitive relationships), property chain inference (infer relationships through property chains)
- Query Optimization: Query plan generation (logical plan construction), join ordering (selectivity-based ordering), filter pushdown (apply filters early), projection pushdown (select only needed variables)
- - Inference Rule Integration: Rule-to-SPARQL translation (convert rule conditions/conclusions to SPARQL triple patterns), query augmentation (add inferred patterns), materialization (pre-compute inferred triples)
+ - Inference Rule Integration: Rule-to-SPARQL translation (convert rule conditions/conclusions to SPARQL triplet patterns), query augmentation (add inferred patterns), materialization (pre-compute inferred triplets)
- Caching: Query result caching (cache query results by query pattern), cache invalidation (invalidate on data updates), cache hit optimization (fast lookup for repeated queries)
Abductive Reasoning:
diff --git a/semantica/seed/__init__.py b/semantica/seed/__init__.py
index 0f6352e4..2057687f 100644
--- a/semantica/seed/__init__.py
+++ b/semantica/seed/__init__.py
@@ -22,12 +22,12 @@ Foundation Graph Creation:
Data Integration:
- Merge Strategies: Seed-first (seed data takes precedence, extracted fills gaps), extracted-first (extracted data takes precedence, seed fills gaps), merge (property merging, seed takes precedence for conflicts)
- Entity Merging: ID-based entity matching, property merging, conflict resolution (seed-first, extracted-first, merge), duplicate handling
- - Relationship Merging: Triple-based relationship matching (source_id, target_id, type), duplicate relationship detection, relationship property merging
+ - Relationship Merging: Triplet-based relationship matching (source_id, target_id, type), duplicate relationship detection, relationship property merging
- Conflict Resolution: Priority-based conflict resolution, property-level merging, metadata preservation
Quality Validation:
- Required Field Checking: Entity ID validation, relationship source/target ID validation, type field checking, missing field detection
- - Duplicate Detection: Entity ID duplicate detection (set-based), relationship duplicate detection (triple-based), duplicate counting and reporting
+ - Duplicate Detection: Entity ID duplicate detection (set-based), relationship duplicate detection (triplet-based), duplicate counting and reporting
- Consistency Validation: Entity-reference consistency (relationships reference existing entities), type consistency checking, metadata consistency
- Metrics Calculation: Entity count, relationship count, unique entity ID count, duplicate entity count, validation statistics
diff --git a/semantica/seed/seed_usage.md b/semantica/seed/seed_usage.md
index d69ba826..85e78602 100644
--- a/semantica/seed/seed_usage.md
+++ b/semantica/seed/seed_usage.md
@@ -752,10 +752,10 @@ integrated = manager.integrate_with_extracted(
**Space Complexity**: O(n + m) for merged entities
#### Relationship Merging
-**Algorithm**: Triple-based relationship matching
+**Algorithm**: Triplet-based relationship matching
-1. **Triple Indexing**: Create (source_id, target_id, type) to relationship mapping
-2. **Triple Matching**: Match relationships by triple
+1. **Triplet Indexing**: Create (source_id, target_id, type) to relationship mapping
+2. **Triplet Matching**: Match relationships by triple
3. **Property Merging**: Merge relationship properties
4. **Duplicate Handling**: Handle duplicate relationships
5. **Result Construction**: Build merged relationship list
@@ -789,11 +789,11 @@ validation = manager.validate_quality(foundation)
1. **Entity ID Collection**: Collect all entity IDs
2. **Set Creation**: Create set of unique IDs
3. **Duplicate Counting**: Count duplicates (total - unique)
-4. **Relationship Triple Collection**: Collect (source_id, target_id, type) triples
+4. **Relationship Triplet Collection**: Collect (source_id, target_id, type) triplets
5. **Duplicate Detection**: Detect duplicate relationships
**Time Complexity**: O(n + r) where n = entities, r = relationships
-**Space Complexity**: O(n + r) for ID/triple sets
+**Space Complexity**: O(n + r) for ID/triplet sets
```python
# Duplicate detection
diff --git a/semantica/semantic_extract/__init__.py b/semantica/semantic_extract/__init__.py
index 740ee424..ce346fee 100644
--- a/semantica/semantic_extract/__init__.py
+++ b/semantica/semantic_extract/__init__.py
@@ -2,7 +2,7 @@
Semantic Extraction Module
This module provides comprehensive semantic extraction capabilities for knowledge
-engineering, enabling extraction of entities, relations, events, triples, and
+engineering, enabling extraction of entities, relations, events, triplets, and
semantic networks from text.
Key Features:
@@ -10,7 +10,7 @@ Key Features:
- Relationship extraction between entities
- Event detection and temporal processing
- Coreference resolution for pronouns and entity references
- - RDF triple extraction and serialization
+ - RDF triplet extraction and serialization
- Semantic analysis and role labeling
- Semantic network construction
- LLM-based extraction enhancement
@@ -22,7 +22,7 @@ Main Classes:
- RelationExtractor: Relationship extraction (confidence_threshold, bidirectional)
- EventDetector: Event detection and classification (extract_participants, extract_time)
- CoreferenceResolver: Coreference resolution
- - TripleExtractor: RDF triple extraction (include_temporal, include_provenance)
+ - TripletExtractor: RDF triplet extraction (include_temporal, include_provenance)
- SemanticAnalyzer: Semantic analysis engine
- SemanticNetworkExtractor: Semantic network construction
- LLMEnhancer: LLM-based enhancement
@@ -37,9 +37,9 @@ Example Usage:
>>> rel_extractor = RelationExtractor(confidence_threshold=0.6)
>>> relations = rel_extractor.extract_relations(text, entities=entities)
- >>> from semantica.semantic_extract import TripleExtractor
- >>> triple_extractor = TripleExtractor(include_temporal=True)
- >>> triples = triple_extractor.extract_triples(text)
+ >>> from semantica.semantic_extract import TripletExtractor
+ >>> triplet_extractor = TripletExtractor(include_temporal=True)
+ >>> triplets = triplet_extractor.extract_triplets(text)
Author: Semantica Contributors
License: MIT
@@ -65,7 +65,7 @@ from .event_detector import (
)
from .extraction_validator import ExtractionValidator, ValidationResult
from .llm_enhancer import LLMEnhancer, LLMResponse
-from .methods import get_entity_method, get_relation_method, get_triple_method
+from .methods import get_entity_method, get_relation_method, get_triplet_method
from .named_entity_recognizer import (
CustomEntityDetector,
EntityClassifier,
@@ -105,12 +105,12 @@ from .semantic_network_extractor import (
SemanticNetworkExtractor,
SemanticNode,
)
-from .triple_extractor import (
+from .triplet_extractor import (
RDFSerializer,
- Triple,
- TripleExtractor,
- TripleQualityChecker,
- TripleValidator,
+ Triplet,
+ TripletExtractor,
+ TripletQualityChecker,
+ TripletValidator,
)
__all__ = [
@@ -137,12 +137,12 @@ __all__ = [
"PronounResolver",
"EntityCoreferenceDetector",
"CoreferenceChainBuilder",
- # Triple Extraction
- "TripleExtractor",
- "Triple",
- "TripleValidator",
+ # Triplet Extraction
+ "TripletExtractor",
+ "Triplet",
+ "TripletValidator",
"RDFSerializer",
- "TripleQualityChecker",
+ "TripletQualityChecker",
# Semantic Analysis
"SemanticAnalyzer",
"SemanticRole",
@@ -182,6 +182,5 @@ __all__ = [
# Methods
"get_entity_method",
"get_relation_method",
- "get_triple_method",
+ "get_triplet_method",
]
-
diff --git a/semantica/semantic_extract/methods.py b/semantica/semantic_extract/methods.py
index 5312cf9a..3749fd8b 100644
--- a/semantica/semantic_extract/methods.py
+++ b/semantica/semantic_extract/methods.py
@@ -2,7 +2,7 @@
Extraction Methods Module
This module provides all extraction methods as simple, reusable functions for
-entities, relations, and triples. It supports multiple extraction approaches
+entities, relations, and triplets. It supports multiple extraction approaches
ranging from simple pattern matching to advanced LLM-based extraction.
Supported Methods:
@@ -23,11 +23,11 @@ Relation Extraction:
- "huggingface": HuggingFace relation extraction models
- "llm": LLM-based relation extraction
-Triple Extraction:
- - "pattern": Pattern-based triple extraction
- - "rules": Rule-based triple extraction
+Triplet Extraction:
+ - "pattern": Pattern-based triplet extraction
+ - "rules": Rule-based triplet extraction
- "huggingface": HuggingFace triplet extraction models
- - "llm": LLM-based triple extraction
+ - "llm": LLM-based triplet extraction
Algorithms Used:
@@ -45,7 +45,7 @@ Relation Extraction:
- Sequence Classification: Transformer-based relation classification
- LLM Generation: Language model-based relation extraction
-Triple Extraction:
+Triplet Extraction:
- Pattern Matching: Subject-predicate-object pattern extraction
- Rule-based Extraction: Linguistic rule application
- Seq2Seq Models: Encoder-decoder transformer models for triplet generation
@@ -66,11 +66,11 @@ Key Features:
* 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
+ - Multiple extraction methods for triplets:
+ * Pattern-based: Pattern matching for triplet extraction
+ * Rules-based: Rule-based triplet extraction
* HuggingFace: Custom HuggingFace triplet models
- * LLM-based: LLM-powered triple extraction
+ * LLM-based: LLM-powered triplet extraction
- Method dispatchers with registry support
- Custom method registration capability
- Consistent interface across all methods
@@ -88,13 +88,13 @@ Main Functions:
- 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
+ - extract_triplets_pattern: Pattern-based triplet extraction
+ - extract_triplets_rules: Rule-based triplet extraction
+ - extract_triplets_huggingface: HuggingFace triplet extraction
+ - extract_triplets_llm: LLM-based triplet 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
+ - get_triplet_method: Get triplet extraction method by name
Example Usage:
>>> from semantica.semantic_extract.methods import get_entity_method
@@ -114,7 +114,7 @@ from .ner_extractor import Entity
from .providers import HuggingFaceModelLoader, create_provider
from .registry import method_registry
from .relation_extractor import Relation
-from .triple_extractor import Triple
+from .triplet_extractor import Triplet
logger = get_logger("methods")
@@ -748,24 +748,24 @@ Return JSON format: [{{"subject": "...", "predicate": "...", "object": "...", "c
# ============================================================================
-# Triple Extraction Methods
+# Triplet Extraction Methods
# ============================================================================
-def extract_triples_pattern(
+def extract_triplets_pattern(
text: str,
entities: Optional[List[Entity]] = None,
relations: Optional[List[Relation]] = None,
**kwargs,
-) -> List[Triple]:
- """Pattern-based triple extraction."""
- triples = []
+) -> List[Triplet]:
+ """Pattern-based triplet extraction."""
+ triplets = []
if relations:
- # Convert relations to triples
+ # Convert relations to triplets
for relation in relations:
- triples.append(
- Triple(
+ triplets.append(
+ Triplet(
subject=relation.subject.text,
predicate=relation.predicate,
object=relation.object.text,
@@ -774,7 +774,7 @@ def extract_triples_pattern(
)
)
elif entities:
- # Simple triple extraction from entities
+ # Simple triplet 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):
@@ -790,8 +790,8 @@ def extract_triples_pattern(
)
if subject_entity and object_entity:
- triples.append(
- Triple(
+ triplets.append(
+ Triplet(
subject=subject_entity.text,
predicate=predicate_text,
object=object_entity.text,
@@ -800,17 +800,17 @@ def extract_triples_pattern(
)
)
- return triples
+ return triplets
-def extract_triples_rules(
+def extract_triplets_rules(
text: str, entities: Optional[List[Entity]] = None, **kwargs
-) -> List[Triple]:
- """Rule-based triple extraction."""
- triples = []
+) -> List[Triplet]:
+ """Rule-based triplet extraction."""
+ triplets = []
if not entities:
- return triples
+ return triplets
# Rule: Look for verb patterns between entities
sentences = re.split(r"[.!?]+", text)
@@ -831,8 +831,8 @@ def extract_triples_rules(
)
if subject_entity and object_entity:
- triples.append(
- Triple(
+ triplets.append(
+ Triplet(
subject=subject_entity.text,
predicate=word,
object=object_entity.text,
@@ -841,18 +841,18 @@ def extract_triples_rules(
)
)
- return triples
+ return triplets
-def extract_triples_huggingface(
+def extract_triplets_huggingface(
text: str, model: str, device: Optional[str] = None, **kwargs
-) -> List[Triple]:
- """HuggingFace triple extraction."""
+) -> List[Triplet]:
+ """HuggingFace triplet extraction."""
loader = HuggingFaceModelLoader(device=device)
model_obj = loader.load_triplet_model(model)
results = loader.extract_triplets(model_obj, text)
- triples = []
+ triplets = []
for result in results:
# Parse result based on model output format
# This is a placeholder - actual parsing would depend on the model
@@ -860,24 +860,24 @@ def extract_triples_huggingface(
# Parse triplet string (format depends on model)
pass
- return triples
+ return triplets
-def extract_triples_llm(
+def extract_triplets_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."""
+) -> List[Triplet]:
+ """LLM-based triplet 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.
+ prompt = f"""Extract RDF triplets (subject-predicate-object) from the following text.
Text: {text}
@@ -885,12 +885,12 @@ Return JSON format: [{{"subject": "...", "predicate": "...", "object": "...", "c
try:
result = llm.generate_structured(prompt)
- triples = []
+ triplets = []
if isinstance(result, list):
for item in result:
- triples.append(
- Triple(
+ triplets.append(
+ Triplet(
subject=item.get("subject", ""),
predicate=item.get("predicate", ""),
object=item.get("object", ""),
@@ -903,9 +903,9 @@ Return JSON format: [{{"subject": "...", "predicate": "...", "object": "...", "c
)
)
- return triples
+ return triplets
except Exception as e:
- logger.error(f"LLM triple extraction failed: {e}")
+ logger.error(f"LLM triplet extraction failed: {e}")
return []
@@ -969,19 +969,19 @@ def get_relation_method(method_name: str):
return method_func
-def get_triple_method(method_name: str):
- """Get triple extraction method - checks registry for custom methods."""
+def get_triplet_method(method_name: str):
+ """Get triplet extraction method - checks registry for custom methods."""
# Check registry first
- custom_method = method_registry.get("triple", method_name)
+ custom_method = method_registry.get("triplet", 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,
+ "pattern": extract_triplets_pattern,
+ "rules": extract_triplets_rules,
+ "huggingface": extract_triplets_huggingface,
+ "llm": extract_triplets_llm,
}
method_func = builtin.get(method_name)
diff --git a/semantica/semantic_extract/providers.py b/semantica/semantic_extract/providers.py
index e6d5e207..2f1a1423 100644
--- a/semantica/semantic_extract/providers.py
+++ b/semantica/semantic_extract/providers.py
@@ -16,7 +16,7 @@ Supported Providers:
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
+ - Triplet Models: Seq2Seq models for triplet extraction
Algorithms Used:
- Transformer Architecture: Attention mechanism-based neural networks
@@ -37,7 +37,7 @@ Key Features:
* 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
+ - HuggingFace model loader for NER, relation extraction, and triplet extraction
- Automatic API key management from environment variables
- Structured JSON output generation
- Model caching and device management (CPU/GPU)
diff --git a/semantica/semantic_extract/registry.py b/semantica/semantic_extract/registry.py
index bd3fad51..f7fc9848 100644
--- a/semantica/semantic_extract/registry.py
+++ b/semantica/semantic_extract/registry.py
@@ -10,7 +10,7 @@ Supported Registration Types:
- Method Registry: Register custom extraction methods for:
* "entity": Entity extraction methods
* "relation": Relation extraction methods
- * "triple": Triple extraction methods
+ * "triplet": Triplet extraction methods
* "event": Event extraction methods
* "coreference": Coreference resolution methods
@@ -24,7 +24,7 @@ Algorithms Used:
Key Features:
- Provider registry for custom LLM providers
- Method registry for custom extraction methods
- - Task-based method organization (entity, relation, triple, event, coreference)
+ - Task-based method organization (entity, relation, triplet, event, coreference)
- Dynamic registration and unregistration
- Easy discovery of available providers and methods
- Support for community-contributed extensions
@@ -83,7 +83,7 @@ class MethodRegistry:
_methods: Dict[str, Dict[str, Callable]] = {
"entity": {},
"relation": {},
- "triple": {},
+ "triplet": {},
"event": {},
"coreference": {},
}
diff --git a/semantica/semantic_extract/semantic_extract_usage.md b/semantica/semantic_extract/semantic_extract_usage.md
index da0b03f3..8339a2a3 100644
--- a/semantica/semantic_extract/semantic_extract_usage.md
+++ b/semantica/semantic_extract/semantic_extract_usage.md
@@ -1,13 +1,13 @@
# Semantic Extract Module Usage Guide
-This comprehensive guide demonstrates how to use the semantic extraction module for extracting entities, relations, events, triples, and semantic networks from text. The module provides multiple extraction methods including pattern-based, ML-based, and LLM-based approaches, with support for custom method registration and configuration management.
+This comprehensive guide demonstrates how to use the semantic extraction module for extracting entities, relations, events, triplets, and semantic networks from text. The module provides multiple extraction methods including pattern-based, ML-based, and LLM-based approaches, with support for custom method registration and configuration management.
## Table of Contents
1. [Basic Usage](#basic-usage)
2. [Entity Extraction](#entity-extraction)
3. [Relation Extraction](#relation-extraction)
-4. [Triple Extraction](#triple-extraction)
+4. [Triplet Extraction](#triplet-extraction)
5. [Event Detection](#event-detection)
6. [Coreference Resolution](#coreference-resolution)
7. [Semantic Analysis](#semantic-analysis)
@@ -196,80 +196,80 @@ relation = Relation(
print(f"Relation: {relation.subject} --[{relation.predicate}]--> {relation.object}")
```
-## Triple Extraction
+## Triplet Extraction
-### Basic Triple Extraction
+### Basic Triplet Extraction
```python
-from semantica.semantic_extract import TripleExtractor
+from semantica.semantic_extract import TripletExtractor
-extractor = TripleExtractor()
+extractor = TripletExtractor()
text = "Apple Inc. was founded by Steve Jobs in 1976."
-triples = extractor.extract_triples(text)
+triplets = extractor.extract_triplets(text)
-for triple in triples:
- print(f"({triple.subject}, {triple.predicate}, {triple.object})")
- print(f" Confidence: {triple.confidence:.2f}")
+for triplet in triplets:
+ print(f"({triplet.subject}, {triplet.predicate}, {triplet.object})")
+ print(f" Confidence: {triplet.confidence:.2f}")
```
-### Different Triple Extraction Methods
+### Different Triplet Extraction Methods
```python
-from semantica.semantic_extract import TripleExtractor
+from semantica.semantic_extract import TripletExtractor
text = "Apple Inc. was founded by Steve Jobs in 1976."
# Pattern-based
-extractor = TripleExtractor(method="pattern")
-triples = extractor.extract_triples(text)
+extractor = TripletExtractor(method="pattern")
+triplets = extractor.extract_triplets(text)
# Rules-based
-extractor = TripleExtractor(method="rules")
-triples = extractor.extract_triples(text)
+extractor = TripletExtractor(method="rules")
+triplets = extractor.extract_triplets(text)
# HuggingFace model
-extractor = TripleExtractor(method="huggingface")
-triples = extractor.extract_triples(text, model="t5-base")
+extractor = TripletExtractor(method="huggingface")
+triplets = extractor.extract_triplets(text, model="t5-base")
# LLM-based
-extractor = TripleExtractor(method="llm")
-triples = extractor.extract_triples(text, provider="openai", model="gpt-4")
+extractor = TripletExtractor(method="llm")
+triplets = extractor.extract_triplets(text, provider="openai", model="gpt-4")
```
### RDF Serialization
```python
-from semantica.semantic_extract import TripleExtractor, RDFSerializer
+from semantica.semantic_extract import TripletExtractor, RDFSerializer
-extractor = TripleExtractor()
-triples = extractor.extract_triples(text)
+extractor = TripletExtractor()
+triplets = extractor.extract_triplets(text)
# Serialize to RDF
serializer = RDFSerializer()
-rdf_output = serializer.serialize(triples, format="turtle")
+rdf_output = serializer.serialize(triplets, format="turtle")
print(rdf_output)
# Serialize to JSON-LD
-jsonld_output = serializer.serialize(triples, format="json-ld")
+jsonld_output = serializer.serialize(triplets, format="json-ld")
print(jsonld_output)
```
-### Triple Validation
+### Triplet Validation
```python
-from semantica.semantic_extract import TripleValidator, TripleQualityChecker
+from semantica.semantic_extract import TripletValidator, TripletQualityChecker
-validator = TripleValidator()
-quality_checker = TripleQualityChecker()
+validator = TripletValidator()
+quality_checker = TripletQualityChecker()
-for triple in triples:
- # Validate triple
- is_valid = validator.validate(triple)
+for triplet in triplets:
+ # Validate triplet
+ is_valid = validator.validate(triplet)
print(f"Valid: {is_valid}")
# Check quality
- quality = quality_checker.check_quality(triple)
+ quality = quality_checker.check_quality(triplet)
print(f"Quality score: {quality:.2f}")
```
@@ -498,218 +498,3 @@ method_registry.register("entity", "custom_method", custom_entity_extraction)
# Use custom method
from semantica.semantic_extract import NERExtractor
extractor = NERExtractor(method="custom_method")
-entities = extractor.extract(text)
-```
-
-### Listing Registered Methods
-
-```python
-from semantica.semantic_extract.registry import method_registry
-
-# List all registered methods
-all_methods = method_registry.list_all()
-print("Registered methods:", all_methods)
-
-# List methods for specific task
-entity_methods = method_registry.list_all("entity")
-print("Entity methods:", entity_methods)
-```
-
-## Configuration
-
-### Using Configuration Manager
-
-```python
-from semantica.semantic_extract.config import config
-
-# Get API key
-api_key = config.get_api_key("openai")
-print(f"OpenAI API key: {api_key[:10]}...")
-
-# Set provider configuration
-config.set_provider("openai", api_key="sk-...", model="gpt-4")
-
-# Get provider configuration
-provider_config = config.get_provider_config("openai")
-print(f"Provider config: {provider_config}")
-```
-
-### Environment Variables
-
-```bash
-# Set API keys
-export OPENAI_API_KEY=sk-...
-export GEMINI_API_KEY=...
-export GROQ_API_KEY=...
-export ANTHROPIC_API_KEY=...
-```
-
-### Configuration File
-
-```yaml
-# config.yaml
-openai:
- api_key: sk-...
- model: gpt-4
-
-gemini:
- api_key: ...
- model: gemini-pro
-```
-
-```python
-from semantica.semantic_extract.config import Config
-
-# Load from config file
-config = Config(config_file="config.yaml")
-api_key = config.get_api_key("openai")
-```
-
-## Advanced Examples
-
-### Complete Extraction Pipeline
-
-```python
-from semantica.semantic_extract import (
- NamedEntityRecognizer,
- RelationExtractor,
- TripleExtractor,
- EventDetector,
- CoreferenceResolver
-)
-
-text = """
-Apple Inc. was founded by Steve Jobs, Steve Wozniak, and Ronald Wayne in 1976.
-The company launched the iPhone in 2007. It is headquartered in Cupertino, California.
-"""
-
-# Step 1: Extract entities
-ner = NamedEntityRecognizer()
-entities = ner.extract_entities(text)
-print(f"Entities: {len(entities)}")
-
-# Step 2: Resolve coreferences
-resolver = CoreferenceResolver()
-resolved_text = resolver.resolve(text)
-print(f"Resolved coreferences")
-
-# Step 3: Extract relations
-rel_extractor = RelationExtractor()
-relations = rel_extractor.extract_relations(resolved_text, entities=entities)
-print(f"Relations: {len(relations)}")
-
-# Step 4: Extract triples
-triple_extractor = TripleExtractor()
-triples = triple_extractor.extract_triples(resolved_text)
-print(f"Triples: {len(triples)}")
-
-# Step 5: Detect events
-event_detector = EventDetector()
-events = event_detector.detect_events(resolved_text)
-print(f"Events: {len(events)}")
-```
-
-### LLM-Enhanced Extraction
-
-```python
-from semantica.semantic_extract import LLMEnhancer
-
-enhancer = LLMEnhancer(provider="openai", model="gpt-4")
-
-# Enhance existing extraction
-entities = ner.extract_entities(text)
-enhanced_entities = enhancer.enhance_entities(entities, text)
-
-for original, enhanced in zip(entities, enhanced_entities):
- print(f"Original: {original.text}")
- print(f"Enhanced: {enhanced.text}")
- print(f" Additional info: {enhanced.metadata}")
-```
-
-### Extraction Validation
-
-```python
-from semantica.semantic_extract import ExtractionValidator
-
-validator = ExtractionValidator()
-
-# Validate extraction results
-result = {
- "entities": entities,
- "relations": relations,
- "triples": triples
-}
-
-validation = validator.validate(result)
-
-print(f"Validation passed: {validation.passed}")
-print(f"Quality score: {validation.quality_score:.2f}")
-print(f"Issues: {validation.issues}")
-```
-
-### Building Knowledge Graph from Extraction
-
-```python
-from semantica.semantic_extract import NamedEntityRecognizer, RelationExtractor, TripleExtractor
-from semantica.kg import GraphBuilder
-
-# Extract all information
-ner = NamedEntityRecognizer()
-entities = ner.extract_entities(text)
-
-rel_extractor = RelationExtractor()
-relations = rel_extractor.extract_relations(text, entities=entities)
-
-triple_extractor = TripleExtractor()
-triples = triple_extractor.extract_triples(text, entities=entities, relationships=relations)
-
-# Build knowledge graph
-graph_builder = GraphBuilder()
-knowledge_graph = graph_builder.build({
- "entities": entities,
- "relations": relations,
- "triples": triples
-})
-
-print(f"Knowledge graph nodes: {len(knowledge_graph.nodes)}")
-print(f"Knowledge graph edges: {len(knowledge_graph.edges)}")
-```
-
-### Batch Processing
-
-```python
-from semantica.semantic_extract import NamedEntityRecognizer, RelationExtractor
-
-texts = [
- "Apple Inc. was founded in 1976.",
- "Microsoft was founded in 1975.",
- "Google was founded in 1998."
-]
-
-# Process multiple texts
-ner = NamedEntityRecognizer()
-rel_extractor = RelationExtractor()
-
-all_entities = []
-all_relations = []
-
-for text in texts:
- entities = ner.extract_entities(text)
- relations = rel_extractor.extract_relations(text, entities=entities)
- all_entities.extend(entities)
- all_relations.extend(relations)
-
-print(f"Total entities: {len(all_entities)}")
-print(f"Total relations: {len(all_relations)}")
-```
-
-## Best Practices
-
-1. **Choose appropriate extraction methods**: Use pattern-based for simple cases, LLM-based for complex extraction
-2. **Resolve coreferences first**: Resolve coreferences before relation extraction for better accuracy
-3. **Validate extraction results**: Always validate extraction results for quality assurance
-4. **Use appropriate providers**: Choose LLM providers based on your needs (cost, speed, accuracy)
-5. **Batch processing**: Process multiple texts together for efficiency
-6. **Combine methods**: Use multiple extraction methods and combine results for better coverage
-7. **Customize extraction**: Register custom methods for domain-specific extraction needs
-
diff --git a/semantica/semantic_extract/triple_extractor.py b/semantica/semantic_extract/triplet_extractor.py
similarity index 61%
rename from semantica/semantic_extract/triple_extractor.py
rename to semantica/semantic_extract/triplet_extractor.py
index fbca10c0..e000ede6 100644
--- a/semantica/semantic_extract/triple_extractor.py
+++ b/semantica/semantic_extract/triplet_extractor.py
@@ -1,63 +1,63 @@
"""
-RDF Triple Extraction Module
+RDF Triplet Extraction Module
-This module provides comprehensive RDF triple extraction capabilities, enabling
-conversion of entities and relations into RDF triples using multiple extraction
+This module provides comprehensive RDF triplet extraction capabilities, enabling
+conversion of entities and relations into RDF triplets 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
+ - "pattern": Pattern-based triplet extraction from relations (default)
+ - "rules": Rule-based triplet extraction using linguistic rules
- "huggingface": Custom HuggingFace triplet extraction models
- - "llm": LLM-based triple extraction using various providers
+ - "llm": LLM-based triplet extraction using various providers
Algorithms Used:
- Pattern Matching: Regex-based subject-predicate-object extraction
- - Rule-based Extraction: Linguistic rule application for triple formation
+ - Rule-based Extraction: Linguistic rule application for triplet formation
- Sequence-to-Sequence Models: Transformer-based seq2seq for triplet generation
- - Large Language Models: GPT, Claude, Gemini for structured triple extraction
+ - Large Language Models: GPT, Claude, Gemini for structured triplet extraction
- RDF Serialization: Graph serialization algorithms (Turtle, N-Triples, JSON-LD)
- URI Normalization: String normalization and URI formatting algorithms
Key Features:
- Multiple extraction methods:
- * Pattern-based: Pattern matching for triple extraction (default)
- * Rules-based: Rule-based triple extraction
+ * Pattern-based: Pattern matching for triplet extraction (default)
+ * Rules-based: Rule-based triplet extraction
* HuggingFace: Custom HuggingFace triplet models
- * LLM-based: LLM-powered triple extraction
+ * LLM-based: LLM-powered triplet extraction
- Fallback chain support: Try methods in order until one succeeds
- - RDF triple generation from entities and relations
+ - RDF triplet generation from entities and relations
- Subject-predicate-object extraction
- - Triple validation and quality checking
+ - Triplet validation and quality checking
- RDF serialization (Turtle, N-Triples, JSON-LD, RDF/XML)
- - Batch triple processing
+ - Batch triplet processing
- URI formatting and normalization
- Quality assessment and scoring
Main Classes:
- - TripleExtractor: Main triple extraction coordinator with method selection
- - TripleValidator: Triple validation engine
+ - TripletExtractor: Main triplet extraction coordinator with method selection
+ - TripletValidator: Triplet validation engine
- RDFSerializer: RDF serialization handler
- - TripleQualityChecker: Triple quality assessment
- - Triple: RDF triple representation dataclass
+ - TripletQualityChecker: Triplet quality assessment
+ - Triplet: RDF triplet representation dataclass
Example Usage:
- >>> from semantica.semantic_extract import TripleExtractor
+ >>> from semantica.semantic_extract import TripletExtractor
>>> # Using pattern method (default)
- >>> extractor = TripleExtractor(method="pattern")
- >>> triples = extractor.extract_triples(text, entities, relations)
+ >>> extractor = TripletExtractor(method="pattern")
+ >>> triplets = extractor.extract_triplets(text, entities, relations)
>>>
>>> # Using LLM method
- >>> extractor = TripleExtractor(method="llm", provider="openai", llm_model="gpt-4")
- >>> triples = extractor.extract_triples(text, entities, relations)
+ >>> extractor = TripletExtractor(method="llm", provider="openai", llm_model="gpt-4")
+ >>> triplets = extractor.extract_triplets(text, entities, relations)
>>>
>>> # Using HuggingFace model
- >>> extractor = TripleExtractor(method="huggingface", huggingface_model="custom/triplet-model")
- >>> triples = extractor.extract_triples(text)
+ >>> extractor = TripletExtractor(method="huggingface", huggingface_model="custom/triplet-model")
+ >>> triplets = extractor.extract_triplets(text)
>>>
>>> # Serialize to RDF
- >>> rdf_turtle = extractor.serialize_triples(triples, format="turtle")
- >>> validated = extractor.validate_triples(triples)
+ >>> rdf_turtle = extractor.serialize_triplets(triplets, format="turtle")
+ >>> validated = extractor.validate_triplets(triplets)
Author: Semantica Contributors
License: MIT
@@ -75,8 +75,8 @@ from .relation_extractor import Relation
@dataclass
-class Triple:
- """RDF triple representation."""
+class Triplet:
+ """RDF triplet representation."""
subject: str
predicate: str
@@ -85,8 +85,8 @@ class Triple:
metadata: Dict[str, Any] = field(default_factory=dict)
-class TripleExtractor:
- """RDF triple extraction handler."""
+class TripletExtractor:
+ """RDF triplet extraction handler."""
def __init__(
self,
@@ -97,7 +97,7 @@ class TripleExtractor:
**kwargs
):
"""
- Initialize triple extractor.
+ Initialize triplet extractor.
Args:
method: Extraction method(s). Can be:
@@ -106,7 +106,7 @@ class TripleExtractor:
- "huggingface": HuggingFace model
- "llm": LLM-based extraction
- List of methods for fallback chain
- include_temporal: Whether to include temporal information in triples
+ include_temporal: Whether to include temporal information in triplets
include_provenance: Whether to track source sentences for provenance
config: Legacy config dict (deprecated, use kwargs)
**kwargs: Configuration options:
@@ -118,7 +118,7 @@ class TripleExtractor:
- min_confidence: Minimum confidence threshold
- validate: Enable validation (default: True)
"""
- self.logger = get_logger("triple_extractor")
+ self.logger = get_logger("triplet_extractor")
self.config = config or {}
self.config.update(kwargs)
self.progress_tracker = get_progress_tracker()
@@ -130,39 +130,39 @@ class TripleExtractor:
# 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.validate_triplets = self.config.get("validate", True)
- self.triple_validator = TripleValidator(**self.config.get("validator", {}))
+ self.triplet_validator = TripletValidator(**self.config.get("validator", {}))
self.rdf_serializer = RDFSerializer(**self.config.get("serializer", {}))
- self.quality_checker = TripleQualityChecker(**self.config.get("quality", {}))
+ self.quality_checker = TripletQualityChecker(**self.config.get("quality", {}))
self.supported_formats = ["turtle", "ntriples", "jsonld", "xml"]
- def extract_triples(
+ def extract_triplets(
self,
text: str,
entities: Optional[List[Entity]] = None,
- relationships: Optional[List[Relation]] = None,
+ relations: Optional[List[Relation]] = None,
**options,
- ) -> List[Triple]:
+ ) -> List[Triplet]:
"""
- Extract RDF triples from text.
+ Extract RDF triplets from text.
Args:
text: Input text
entities: Pre-extracted entities (optional)
- relationships: Pre-extracted relations (optional)
+ relations: Pre-extracted relations (optional)
**options: Extraction options
Returns:
- list: List of extracted triples
+ list: List of extracted triplets
"""
- from .methods import get_triple_method
+ from .methods import get_triplet_method
tracking_id = self.progress_tracker.start_tracking(
module="semantic_extract",
- submodule="TripleExtractor",
- message="Extracting RDF triples from text",
+ submodule="TripletExtractor",
+ message="Extracting RDF triplets from text",
)
try:
@@ -178,12 +178,12 @@ class TripleExtractor:
entities = ner.extract_entities(text)
# Extract relations if not provided
- if relationships is None:
+ if relations is None:
self.progress_tracker.update_tracking(
tracking_id, message="Extracting relations..."
)
rel_extractor = RelationExtractor(**self.config.get("relation", {}))
- relationships = rel_extractor.extract_relations(text, entities)
+ relations = rel_extractor.extract_relations(text, entities)
# Use method-based extraction
methods = options.get("method", self.method)
@@ -194,14 +194,14 @@ class TripleExtractor:
all_options = {**self.config, **options}
# Try each method in order (fallback chain)
- all_triples = []
+ all_triplets = []
for method_name in methods:
try:
self.progress_tracker.update_tracking(
tracking_id,
- message=f"Extracting triples using {method_name}...",
+ message=f"Extracting triplets using {method_name}...",
)
- method_func = get_triple_method(method_name)
+ method_func = get_triplet_method(method_name)
# Prepare method-specific options
method_options = all_options.copy()
@@ -218,29 +218,29 @@ class TripleExtractor:
"llm_model", all_options.get("model")
)
- triples = method_func(
+ triplets = method_func(
text,
entities=entities,
- relations=relationships,
+ relations=relations,
**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]
+ filtered = [t for t in triplets if t.confidence >= min_conf]
if filtered:
- all_triples.append((method_name, filtered))
+ all_triplets.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)
+ if options.get("validate", self.validate_triplets):
+ result = self.triplet_validator.validate_triplets(result)
self.progress_tracker.stop_tracking(
tracking_id,
status="completed",
- message=f"Extracted {len(result)} triples using {method_name}",
+ message=f"Extracted {len(result)} triplets using {method_name}",
)
return result
@@ -249,38 +249,38 @@ class TripleExtractor:
continue
# Use first successful method or fallback to relation conversion
- if all_triples:
- triples = all_triples[0][1]
+ if all_triplets:
+ triplets = all_triplets[0][1]
else:
- # Fallback: Convert relations to triples
+ # Fallback: Convert relations to triplets
self.progress_tracker.update_tracking(
tracking_id,
- message=f"Converting {len(relationships)} relations to triples...",
+ message=f"Converting {len(relations)} relations to triplets...",
)
- triples = []
- for relation in relationships:
- triple = Triple(
+ triplets = []
+ for relation in relations:
+ triplet = Triplet(
subject=self._format_uri(relation.subject.text),
predicate=self._format_uri(relation.predicate),
object=self._format_uri(relation.object.text),
confidence=relation.confidence,
metadata={"context": relation.context, **relation.metadata},
)
- triples.append(triple)
+ triplets.append(triplet)
- # Validate triples
- if options.get("validate", self.validate_triples):
+ # Validate triplets
+ if options.get("validate", self.validate_triplets):
self.progress_tracker.update_tracking(
- tracking_id, message="Validating triples..."
+ tracking_id, message="Validating triplets..."
)
- triples = self.triple_validator.validate_triples(triples)
+ triplets = self.triplet_validator.validate_triplets(triplets)
self.progress_tracker.stop_tracking(
tracking_id,
status="completed",
- message=f"Extracted {len(triples)} triples",
+ message=f"Extracted {len(triplets)} triplets",
)
- return triples
+ return triplets
except Exception as e:
self.progress_tracker.stop_tracking(
@@ -298,109 +298,109 @@ class TripleExtractor:
formatted = quote(value.replace(" ", "_"), safe="")
return f"http://example.org/{formatted}"
- def validate_triples(self, triples: List[Triple], **criteria) -> List[Triple]:
+ def validate_triplets(self, triplets: List[Triplet], **criteria) -> List[Triplet]:
"""
- Validate triple quality and consistency.
+ Validate triplet quality and consistency.
Args:
- triples: List of triples
+ triplets: List of triplets
**criteria: Validation criteria
Returns:
- list: Validated triples
+ list: Validated triplets
"""
- return self.triple_validator.validate_triples(triples, **criteria)
+ return self.triplet_validator.validate_triplets(triplets, **criteria)
- def serialize_triples(
- self, triples: List[Triple], format: str = "turtle", **options
+ def serialize_triplets(
+ self, triplets: List[Triplet], format: str = "turtle", **options
) -> str:
"""
- Serialize triples to RDF format.
+ Serialize triplets to RDF format.
Args:
- triples: List of triples
+ triplets: List of triplets
format: RDF format (turtle, ntriples, jsonld, xml)
**options: Serialization options
Returns:
str: Serialized RDF
"""
- return self.rdf_serializer.serialize_to_rdf(triples, format, **options)
+ return self.rdf_serializer.serialize_to_rdf(triplets, format, **options)
- def process_batch(self, texts: List[str], **options) -> List[List[Triple]]:
+ def process_batch(self, texts: List[str], **options) -> List[List[Triplet]]:
"""
- Process multiple texts for triple extraction.
+ Process multiple texts for triplet extraction.
Args:
texts: List of input texts
**options: Processing options
Returns:
- list: List of triple lists for each text
+ list: List of triplet lists for each text
"""
- return [self.extract_triples(text, **options) for text in texts]
+ return [self.extract_triplets(text, **options) for text in texts]
-class TripleValidator:
- """Triple validation engine."""
+class TripletValidator:
+ """Triplet validation engine."""
def __init__(self, **config):
- """Initialize triple validator."""
- self.logger = get_logger("triple_validator")
+ """Initialize triplet validator."""
+ self.logger = get_logger("triplet_validator")
self.config = config
- def validate_triple(self, triple: Triple, **criteria) -> bool:
+ def validate_triplet(self, triplet: Triplet, **criteria) -> bool:
"""
- Validate individual triple.
+ Validate individual triplet.
Args:
- triple: Triple to validate
+ triplet: Triplet to validate
**criteria: Validation criteria
Returns:
bool: True if valid
"""
# Check structure
- if not triple.subject or not triple.predicate or not triple.object:
+ if not triplet.subject or not triplet.predicate or not triplet.object:
return False
# Check confidence
min_confidence = criteria.get("min_confidence", 0.5)
- if triple.confidence < min_confidence:
+ if triplet.confidence < min_confidence:
return False
return True
- def validate_triples(self, triples: List[Triple], **criteria) -> List[Triple]:
+ def validate_triplets(self, triplets: List[Triplet], **criteria) -> List[Triplet]:
"""
- Validate list of triples.
+ Validate list of triplets.
Args:
- triples: List of triples
+ triplets: List of triplets
**criteria: Validation criteria
Returns:
- list: Valid triples
+ list: Valid triplets
"""
- return [t for t in triples if self.validate_triple(t, **criteria)]
+ return [t for t in triplets if self.validate_triplet(t, **criteria)]
- def check_triple_consistency(self, triples: List[Triple]) -> Dict[str, Any]:
+ def check_triplet_consistency(self, triplets: List[Triplet]) -> Dict[str, Any]:
"""
- Check consistency among triples.
+ Check consistency among triplets.
Args:
- triples: List of triples
+ triplets: List of triplets
Returns:
dict: Consistency report
"""
issues = []
- # Check for contradictory triples
+ # Check for contradictory triplets
# (simplified - would need domain knowledge for full implementation)
return {
- "total_triples": len(triples),
+ "total_triplets": len(triplets),
"issues": issues,
"consistent": len(issues) == 0,
}
@@ -415,13 +415,13 @@ class RDFSerializer:
self.config = config
def serialize_to_rdf(
- self, triples: List[Triple], format: str = "turtle", **options
+ self, triplets: List[Triplet], format: str = "turtle", **options
) -> str:
"""
- Serialize triples to RDF format.
+ Serialize triplets to RDF format.
Args:
- triples: List of triples
+ triplets: List of triplets
format: RDF format
**options: Serialization options
@@ -429,55 +429,55 @@ class RDFSerializer:
str: Serialized RDF
"""
if format == "turtle":
- return self._serialize_turtle(triples, **options)
+ return self._serialize_turtle(triplets, **options)
elif format == "ntriples":
- return self._serialize_ntriples(triples, **options)
+ return self._serialize_ntriples(triplets, **options)
elif format == "jsonld":
- return self._serialize_jsonld(triples, **options)
+ return self._serialize_jsonld(triplets, **options)
elif format == "xml":
- return self._serialize_xml(triples, **options)
+ return self._serialize_xml(triplets, **options)
else:
raise ValidationError(f"Unsupported RDF format: {format}")
- def _serialize_turtle(self, triples: List[Triple], **options) -> str:
+ def _serialize_turtle(self, triplets: List[Triplet], **options) -> str:
"""Serialize to Turtle format."""
lines = ["@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> ."]
- for triple in triples:
- line = f"{triple.subject} <{triple.predicate}> {triple.object} ."
+ for triplet in triplets:
+ line = f"{triplet.subject} <{triplet.predicate}> {triplet.object} ."
lines.append(line)
return "\n".join(lines)
- def _serialize_ntriples(self, triples: List[Triple], **options) -> str:
+ def _serialize_ntriples(self, triplets: List[Triplet], **options) -> str:
"""Serialize to N-Triples format."""
lines = []
- for triple in triples:
- line = f"<{triple.subject}> <{triple.predicate}> <{triple.object}> ."
+ for triplet in triplets:
+ line = f"<{triplet.subject}> <{triplet.predicate}> <{triplet.object}> ."
lines.append(line)
return "\n".join(lines)
- def _serialize_jsonld(self, triples: List[Triple], **options) -> str:
+ def _serialize_jsonld(self, triplets: List[Triplet], **options) -> str:
"""Serialize to JSON-LD format."""
import json
graph = []
- for triple in triples:
- graph.append({"@id": triple.subject, triple.predicate: triple.object})
+ for triplet in triplets:
+ graph.append({"@id": triplet.subject, triplet.predicate: triplet.object})
return json.dumps({"@graph": graph}, indent=2)
- def _serialize_xml(self, triples: List[Triple], **options) -> str:
+ def _serialize_xml(self, triplets: List[Triplet], **options) -> str:
"""Serialize to RDF/XML format."""
lines = [
'<?xml version="1.0"?>',
'<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">',
]
- for triple in triples:
- lines.append(f' <rdf:Description rdf:about="{triple.subject}">')
+ for triplet in triplets:
+ lines.append(f' <rdf:Description rdf:about="{triplet.subject}">')
lines.append(
- f" <{triple.predicate}>{triple.object}</{triple.predicate}>"
+ f" <{triplet.predicate}>{triplet.object}</{triplet.predicate}>"
)
lines.append(" </rdf:Description>")
@@ -485,50 +485,50 @@ class RDFSerializer:
return "\n".join(lines)
-class TripleQualityChecker:
- """Triple quality assessment engine."""
+class TripletQualityChecker:
+ """Triplet quality assessment engine."""
def __init__(self, **config):
- """Initialize triple quality checker."""
- self.logger = get_logger("triple_quality_checker")
+ """Initialize triplet quality checker."""
+ self.logger = get_logger("triplet_quality_checker")
self.config = config
- def assess_triple_quality(self, triple: Triple, **metrics) -> Dict[str, Any]:
+ def assess_triplet_quality(self, triplet: Triplet, **metrics) -> Dict[str, Any]:
"""
- Assess quality of individual triple.
+ Assess quality of individual triplet.
Args:
- triple: Triple to assess
+ triplet: Triplet to assess
**metrics: Quality metrics
Returns:
dict: Quality assessment
"""
return {
- "confidence": triple.confidence,
+ "confidence": triplet.confidence,
"completeness": 1.0
- if triple.subject and triple.predicate and triple.object
+ if triplet.subject and triplet.predicate and triplet.object
else 0.0,
- "quality_score": triple.confidence,
+ "quality_score": triplet.confidence,
}
def calculate_quality_scores(
- self, triples: List[Triple], **options
+ self, triplets: List[Triplet], **options
) -> Dict[str, Any]:
"""
- Calculate quality scores for triples.
+ Calculate quality scores for triplets.
Args:
- triples: List of triples
+ triplets: List of triplets
**options: Quality options
Returns:
dict: Quality scores
"""
- if not triples:
+ if not triplets:
return {}
- scores = [self.assess_triple_quality(t)["quality_score"] for t in triples]
+ scores = [self.assess_triplet_quality(t)["quality_score"] for t in triplets]
return {
"average_score": sum(scores) / len(scores),
diff --git a/semantica/split/__init__.py b/semantica/split/__init__.py
index 0502c065..c2de7e81 100644
--- a/semantica/split/__init__.py
+++ b/semantica/split/__init__.py
@@ -16,7 +16,7 @@ Algorithms Used:
- Semantic Boundary Detection: Sentence transformer embeddings and similarity
- LLM-based Splitting: Prompt engineering for optimal split point detection
- Entity Boundary Detection: NER-based entity extraction and boundary preservation
- - Triple Preservation: Graph-based triple integrity checking
+ - Triplet Preservation: Graph-based triplet integrity checking
- Graph Centrality Analysis: Degree, betweenness, closeness, eigenvector centrality
- Community Detection: Louvain algorithm, Leiden algorithm, modularity optimization
@@ -43,7 +43,7 @@ Main Classes:
- SlidingWindowChunker: Fixed-size sliding window chunking
- TableChunker: Table-specific chunking
- EntityAwareChunker: Entity boundary-preserving chunker
- - RelationAwareChunker: Triple-preserving chunker
+ - RelationAwareChunker: Triplet-preserving chunker
- GraphBasedChunker: Graph structure-based chunker
- OntologyAwareChunker: Ontology concept-based chunker
- HierarchicalChunker: Multi-level hierarchical chunker
diff --git a/semantica/split/kg_chunkers.py b/semantica/split/kg_chunkers.py
index f9ccf43d..94ff5f53 100644
--- a/semantica/split/kg_chunkers.py
+++ b/semantica/split/kg_chunkers.py
@@ -6,14 +6,14 @@ analytics workflows, designed to preserve graph structure and semantic relations
Supported Chunkers:
- EntityAwareChunker: Preserves entity boundaries
- - RelationAwareChunker: Preserves triple integrity
+ - RelationAwareChunker: Preserves triplet integrity
- GraphBasedChunker: Uses graph structure for chunking
- OntologyAwareChunker: Uses ontology concepts for chunking
- HierarchicalChunker: Multi-level hierarchical chunking
Algorithms Used:
- Entity Boundary Detection: NER-based entity extraction and boundary preservation
- - Triple Preservation: Graph-based triple integrity checking
+ - Triplet Preservation: Graph-based triplet integrity checking
- Graph Centrality Analysis: Degree, betweenness, closeness, eigenvector centrality
- Community Detection: Louvain algorithm, Leiden algorithm, modularity optimization
- Graph Connectivity: Connected components, shortest paths, bridge detection
@@ -21,7 +21,7 @@ Algorithms Used:
Key Features:
- Entity boundary preservation for GraphRAG
- - Triple integrity preservation for KG workflows
+ - Triplet integrity preservation for KG workflows
- Graph structure-aware chunking
- Ontology concept-aware chunking
- Hierarchical multi-level chunking
@@ -29,7 +29,7 @@ Key Features:
Main Classes:
- EntityAwareChunker: Entity boundary-preserving chunker
- - RelationAwareChunker: Triple-preserving chunker
+ - RelationAwareChunker: Triplet-preserving chunker
- GraphBasedChunker: Graph structure-based chunker
- OntologyAwareChunker: Ontology concept-based chunker
- HierarchicalChunker: Multi-level hierarchical chunker
@@ -136,9 +136,9 @@ class EntityAwareChunker:
class RelationAwareChunker:
"""
- Triple-preserving chunker for KG workflows.
+ Triplet-preserving chunker for KG workflows.
- Ensures that relation triples (subject-predicate-object) are preserved within
+ Ensures that relation triplets (subject-predicate-object) are preserved within
the same chunk, preventing the loss of relational context.
"""
@@ -147,7 +147,7 @@ class RelationAwareChunker:
chunk_size: int = 1000,
chunk_overlap: int = 200,
relation_method: str = "ml",
- preserve_triples: bool = True,
+ preserve_triplets: bool = True,
**kwargs,
):
"""
@@ -157,20 +157,20 @@ class RelationAwareChunker:
chunk_size: Target chunk size
chunk_overlap: Overlap between chunks
relation_method: Relation extraction method
- preserve_triples: Whether to preserve triple integrity
+ preserve_triplets: Whether to preserve triplet integrity
**kwargs: Additional options for relation extractor
"""
self.chunk_size = chunk_size
self.chunk_overlap = chunk_overlap
self.relation_method = relation_method
- self.preserve_triples = preserve_triples
+ self.preserve_triplets = preserve_triplets
self.options = kwargs
self.logger = get_logger("relation_aware_chunker")
self.progress_tracker = get_progress_tracker()
def chunk(self, text: str, **options) -> List[Chunk]:
"""
- Chunk text preserving triple integrity.
+ Chunk text preserving triplet integrity.
Args:
text: Input text
@@ -191,7 +191,7 @@ class RelationAwareChunker:
text,
chunk_size=self.chunk_size,
relation_method=self.relation_method,
- preserve_triples=self.preserve_triples,
+ preserve_triplets=self.preserve_triplets,
**merged_options,
)
diff --git a/semantica/split/methods.py b/semantica/split/methods.py
index fbf57b10..a464b022 100644
--- a/semantica/split/methods.py
+++ b/semantica/split/methods.py
@@ -21,7 +21,7 @@ Standard Text Splitting:
KG/Ontology/Graph Analytics Methods:
- "entity_aware": Entity boundary-preserving splitting
- - "relation_aware": Triple-preserving splitting
+ - "relation_aware": Triplet-preserving splitting
- "graph_based": Graph structure-based splitting
- "ontology_aware": Ontology concept/hierarchy-based splitting
- "embedding_semantic": Embedding similarity-based boundaries
@@ -42,7 +42,7 @@ Standard Splitting:
KG/Ontology/Graph Analytics:
- Entity Boundary Detection: NER-based entity extraction and boundary preservation
- - Triple Preservation: Graph-based triple integrity checking
+ - Triplet Preservation: Graph-based triplet integrity checking
- Graph Centrality Analysis: Degree, betweenness, closeness, eigenvector centrality
- Community Detection: Louvain algorithm, Leiden algorithm, modularity optimization
- Graph Connectivity: Connected components, shortest paths, bridge detection
@@ -70,7 +70,7 @@ Main Functions:
- split_semantic_transformer: Sentence transformer-based splitting
- split_llm: LLM-based optimal split point detection
- split_entity_aware: Entity boundary-preserving splitting
- - split_relation_aware: Triple-preserving splitting
+ - split_relation_aware: Triplet-preserving splitting
- split_graph_based: Graph structure-based splitting
- split_ontology_aware: Ontology concept-based splitting
- split_hierarchical: Multi-level hierarchical chunking
@@ -998,17 +998,17 @@ def split_relation_aware(
text: str,
chunk_size: int = 1000,
relation_method: str = "ml",
- preserve_triples: bool = True,
+ preserve_triplets: bool = True,
**kwargs,
) -> List[Chunk]:
"""
- Triple-preserving splitting.
+ Triplet-preserving splitting.
Args:
text: Input text
chunk_size: Target chunk size
relation_method: Relation extraction method
- preserve_triples: Whether to preserve triple integrity
+ preserve_triplets: Whether to preserve triplet integrity
**kwargs: Additional options
Returns:
@@ -1026,18 +1026,18 @@ def split_relation_aware(
ner_extractor = NERExtractor(method=ner_method, **kwargs)
entities = ner_extractor.extract(text)
- # Extract relations/triples
+ # Extract relations/triplets
relation_extractor = RelationExtractor(method=relation_method, **kwargs)
relations = relation_extractor.extract(text, entities)
- # Create triple boundaries (subject, relation, object must be in same chunk)
- triple_boundaries = []
+ # Create triplet boundaries (subject, relation, object must be in same chunk)
+ triplet_boundaries = []
for relation in relations:
start = min(relation.subject.start_char, relation.object.start_char)
end = max(relation.subject.end_char, relation.object.end_char)
- triple_boundaries.append((start, end))
+ triplet_boundaries.append((start, end))
- # Split text ensuring triples are not split
+ # Split text ensuring triplets are not split
chunks = []
current_chunk = ""
current_size = 0
@@ -1051,16 +1051,16 @@ def split_relation_aware(
sentence_start = char_pos
sentence_end = char_pos + sentence_size
- # Check if sentence is part of a triple
- is_in_triple = any(
+ # Check if sentence is part of a triplet
+ is_in_triplet = any(
start <= sentence_start <= end or start <= sentence_end <= end
- for start, end in triple_boundaries
+ for start, end in triplet_boundaries
)
# Check size limit
if current_size + sentence_size > chunk_size and current_chunk:
- # Don't split if it would break a triple
- if preserve_triples and is_in_triple:
+ # Don't split if it would break a triplet
+ if preserve_triplets and is_in_triplet:
# Add to current chunk even if it exceeds size
pass
else:
diff --git a/semantica/split/split_usage.md b/semantica/split/split_usage.md
index fb7c22b5..7586df79 100644
--- a/semantica/split/split_usage.md
+++ b/semantica/split/split_usage.md
@@ -226,11 +226,11 @@ chunks = split_relation_aware(
text,
chunk_size=1000,
chunk_overlap=200,
- preserve_triples=True
+ preserve_triplets=True
)
for chunk in chunks:
- print(f"Triples in chunk: {chunk.metadata.get('triples')}")
+ print(f"Triplets in chunk: {chunk.metadata.get('triplets')}")
```
### Graph-based Splitting
@@ -332,7 +332,7 @@ chunks = entity_chunker.chunk(text)
# Relation-aware chunking
relation_chunker = RelationAwareChunker(
chunk_size=1000,
- preserve_triples=True
+ preserve_triplets=True
)
chunks = relation_chunker.chunk(text)
@@ -612,20 +612,20 @@ for chunk in chunks:
```python
from semantica.split import RelationAwareChunker
-# Relation-aware chunking preserves triple integrity
+# Relation-aware chunking preserves triplet integrity
relation_chunker = RelationAwareChunker(
chunk_size=1000,
- preserve_triples=True
+ preserve_triplets=True
)
chunks = relation_chunker.chunk(text)
for chunk in chunks:
- triples = chunk.metadata.get("triples", [])
- print(f"Chunk triples: {len(triples)}")
+ triplets = chunk.metadata.get("triplets", [])
+ print(f"Chunk triplets: {len(triplets)}")
# Use for knowledge graph construction
- # Triples are preserved within chunks
+ # Triplets are preserved within chunks
```
### Semantic Chunking with Custom Model
diff --git a/semantica/triplet_store/__init__.py b/semantica/triplet_store/__init__.py
index 92aadb2a..a37befe2 100644
--- a/semantica/triplet_store/__init__.py
+++ b/semantica/triplet_store/__init__.py
@@ -20,7 +20,7 @@ CRUD Operations:
Bulk Loading:
- Batch Processing: Chunking algorithm (fixed-size batch creation), batch size optimization, memory management for large datasets
- - Progress Tracking: Load progress calculation (loaded/total percentage), elapsed time tracking, estimated remaining time calculation (linear projection), throughput calculation (triples/second)
+ - Progress Tracking: Load progress calculation (loaded/total percentage), elapsed time tracking, estimated remaining time calculation (linear projection), throughput calculation (triplets/second)
- Retry Mechanism: Exponential backoff retry (delay = retry_delay * (attempt + 1)), max retry limit, error recovery, stop-on-error option
- Stream Processing: Iterator-based stream processing, incremental batch collection, memory-efficient loading
- Validation: Pre-load validation (empty component checking, URI validation, confidence checking), error/warning collection
@@ -44,7 +44,7 @@ Store Adapters:
- Virtuoso Adapter: Virtuoso SPARQL endpoint communication, SQL/SPARQL hybrid queries, bulk loading, transaction support
Data Validation:
- - Triple Validation: Required field checking (subject, predicate, object), confidence range validation (0-1), URI format validation
+ - Triplet Validation: Required field checking (subject, predicate, object), confidence range validation (0-1), URI format validation
- Pre-load Validation: Empty component detection, URI format checking, confidence threshold checking, error/warning categorization
Performance Optimization:
@@ -79,10 +79,10 @@ Main Classes:
Convenience Functions:
- register_store: Register triplet store wrapper
- - add_triple: Add single triplet wrapper
- - add_triples: Add multiple triplets wrapper
- - get_triples: Get triplets matching pattern wrapper
- - delete_triple: Delete triplet wrapper
+ - add_triplet: Add single triplet wrapper
+ - add_triplets: Add multiple triplets wrapper
+ - get_triplets: Get triplets matching pattern wrapper
+ - delete_triplet: Delete triplet wrapper
- execute_query: Execute SPARQL query wrapper
- optimize_query: Optimize SPARQL query wrapper
- bulk_load: Bulk load triplets wrapper
@@ -90,15 +90,15 @@ Convenience Functions:
- list_available_methods: List registered triplet store methods
Example Usage:
- >>> from semantica.triplet_store import TripletManager, register_store, add_triple, execute_query
+ >>> from semantica.triplet_store import TripletManager, register_store, add_triplet, execute_query
>>> # Using convenience functions
>>> store = register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
- >>> result = add_triple(triple, store_id="main")
+ >>> result = add_triplet(triplet, store_id="main")
>>> query_result = execute_query(sparql_query, store_adapter)
>>> # Using classes directly
>>> manager = TripletManager()
>>> store = manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
- >>> result = manager.add_triple(triple, store_id="main")
+ >>> result = manager.add_triplet(triplet, store_id="main")
>>> from semantica.triplet_store import QueryEngine
>>> engine = QueryEngine()
>>> query_result = engine.execute_query(sparql_query, store_adapter)
@@ -112,19 +112,19 @@ from .bulk_loader import BulkLoader, LoadProgress
from .config import TripletStoreConfig, triplet_store_config
from .jena_adapter import JenaAdapter
from .methods import (
- add_triple,
- add_triples,
+ add_triplet,
+ add_triplets,
bulk_load,
- delete_triple,
+ delete_triplet,
execute_query,
get_triplet_store_method,
- get_triples,
+ get_triplets,
list_available_methods,
optimize_query,
plan_query,
register_store,
- update_triple,
- validate_triples,
+ update_triplet,
+ validate_triplets,
)
from .query_engine import QueryEngine, QueryPlan, QueryResult
from .rdf4j_adapter import RDF4JAdapter
@@ -133,7 +133,7 @@ from .triplet_manager import TripletManager, TripletStore
from .virtuoso_adapter import VirtuosoAdapter
__all__ = [
- # Triple management
+ # Triplet management
"TripletManager",
"TripletStore",
# Store adapters
@@ -150,16 +150,16 @@ __all__ = [
"LoadProgress",
# Convenience functions
"register_store",
- "add_triple",
- "add_triples",
- "get_triples",
- "delete_triple",
- "update_triple",
+ "add_triplet",
+ "add_triplets",
+ "get_triplets",
+ "delete_triplet",
+ "update_triplet",
"execute_query",
"optimize_query",
"plan_query",
"bulk_load",
- "validate_triples",
+ "validate_triplets",
"get_triplet_store_method",
"list_available_methods",
# Configuration and registry
diff --git a/semantica/triplet_store/blazegraph_adapter.py b/semantica/triplet_store/blazegraph_adapter.py
index f1463837..49b99357 100644
--- a/semantica/triplet_store/blazegraph_adapter.py
+++ b/semantica/triplet_store/blazegraph_adapter.py
@@ -20,7 +20,7 @@ Example Usage:
>>> from semantica.triplet_store import BlazegraphAdapter
>>> adapter = BlazegraphAdapter(endpoint="http://localhost:9999/blazegraph", namespace="kb")
>>> result = adapter.execute_sparql(sparql_query)
- >>> load_result = adapter.bulk_load(triples)
+ >>> load_result = adapter.bulk_load(triplets)
>>> namespace_result = adapter.create_namespace("new_namespace")
Author: Semantica Contributors
@@ -32,7 +32,7 @@ from urllib.parse import urljoin
import requests
-from ..semantic_extract.triple_extractor import Triple
+from ..semantic_extract.triplet_extractor import Triplet
from ..utils.exceptions import ProcessingError, ValidationError
from ..utils.logging import get_logger
from ..utils.progress_tracker import get_progress_tracker
@@ -174,12 +174,12 @@ class BlazegraphAdapter:
)
raise ProcessingError(f"SPARQL query failed: {e}")
- def bulk_load(self, triples: List[Triple], **options) -> Dict[str, Any]:
+ def bulk_load(self, triplets: List[Triplet], **options) -> Dict[str, Any]:
"""
- Load triples in bulk.
+ Load triplets in bulk.
Args:
- triples: List of triples
+ triplets: List of triplets
**options: Additional options:
- format: RDF format (turtle, ntriples, rdfxml)
- graph: Named graph URI
@@ -190,9 +190,9 @@ class BlazegraphAdapter:
if not self.connected:
raise ProcessingError("Not connected to Blazegraph")
- # Convert triples to RDF format
+ # Convert triplets to RDF format
format = options.get("format", "turtle")
- rdf_data = self._triples_to_rdf(triples, format)
+ rdf_data = self._triplets_to_rdf(triplets, format)
# Upload endpoint
upload_endpoint = urljoin(
@@ -205,7 +205,7 @@ class BlazegraphAdapter:
graph_clause = f"GRAPH <{graph}>" if graph else ""
# Build INSERT query
- insert_data = self._build_insert_data(triples)
+ insert_data = self._build_insert_data(triplets)
query = f"INSERT DATA {graph_clause} {{ {insert_data} }}"
response = requests.post(
@@ -222,49 +222,49 @@ class BlazegraphAdapter:
return {
"success": True,
- "triples_loaded": len(triples),
+ "triplets_loaded": len(triplets),
"namespace": self.namespace,
}
except Exception as e:
self.logger.error(f"Bulk load failed: {e}")
raise ProcessingError(f"Bulk load failed: {e}")
- def _triples_to_rdf(self, triples: List[Triple], format: str = "turtle") -> str:
- """Convert triples to RDF format."""
+ def _triplets_to_rdf(self, triplets: List[Triplet], format: str = "turtle") -> str:
+ """Convert triplets to RDF format."""
if format == "turtle":
lines = []
- for triple in triples:
+ for triplet in triplets:
lines.append(
- f"<{triple.subject}> <{triple.predicate}> <{triple.object}> ."
+ f"<{triplet.subject}> <{triplet.predicate}> <{triplet.object}> ."
)
return "\n".join(lines)
else:
# For other formats, use simple turtle conversion
- return self._triples_to_rdf(triples, "turtle")
+ return self._triplets_to_rdf(triplets, "turtle")
- def _build_insert_data(self, triples: List[Triple]) -> str:
+ def _build_insert_data(self, triplets: List[Triplet]) -> str:
"""Build SPARQL INSERT DATA clause."""
lines = []
- for triple in triples:
- lines.append(f"<{triple.subject}> <{triple.predicate}> <{triple.object}> .")
+ for triplet in triplets:
+ lines.append(f"<{triplet.subject}> <{triplet.predicate}> <{triplet.object}> .")
return " ".join(lines)
- def add_triple(self, triple: Triple, **options) -> Dict[str, Any]:
- """Add single triple."""
- return self.bulk_load([triple], **options)
+ def add_triplet(self, triplet: Triplet, **options) -> Dict[str, Any]:
+ """Add single triplet."""
+ return self.bulk_load([triplet], **options)
- def add_triples(self, triples: List[Triple], **options) -> Dict[str, Any]:
- """Add multiple triples."""
- return self.bulk_load(triples, **options)
+ def add_triplets(self, triplets: List[Triplet], **options) -> Dict[str, Any]:
+ """Add multiple triplets."""
+ return self.bulk_load(triplets, **options)
- def get_triples(
+ def get_triplets(
self,
subject: Optional[str] = None,
predicate: Optional[str] = None,
object: Optional[str] = None,
**options,
- ) -> List[Triple]:
- """Get triples matching criteria."""
+ ) -> List[Triplet]:
+ """Get triplets matching criteria."""
# Build SPARQL query
where_clauses = []
if subject:
@@ -279,11 +279,11 @@ class BlazegraphAdapter:
result = self.execute_sparql(query, **options)
- # Convert bindings to triples
- triples = []
+ # Convert bindings to triplets
+ triplets = []
for binding in result["bindings"]:
- triples.append(
- Triple(
+ triplets.append(
+ Triplet(
subject=binding.get("s", {}).get("value", ""),
predicate=binding.get("p", {}).get("value", ""),
object=binding.get("o", {}).get("value", ""),
@@ -291,16 +291,16 @@ class BlazegraphAdapter:
)
)
- return triples
+ return triplets
- def delete_triple(self, triple: Triple, **options) -> Dict[str, Any]:
- """Delete triple."""
+ def delete_triplet(self, triplet: Triplet, **options) -> Dict[str, Any]:
+ """Delete triplet."""
if not self.connected:
raise ProcessingError("Not connected to Blazegraph")
update_endpoint = self._get_update_endpoint()
- query = f"DELETE DATA {{ <{triple.subject}> <{triple.predicate}> <{triple.object}> }}"
+ query = f"DELETE DATA {{ <{triplet.subject}> <{triplet.predicate}> <{triplet.object}> }}"
try:
response = requests.post(
@@ -317,8 +317,8 @@ class BlazegraphAdapter:
return {"success": True}
except Exception as e:
- self.logger.error(f"Delete triple failed: {e}")
- raise ProcessingError(f"Delete triple failed: {e}")
+ self.logger.error(f"Delete triplet failed: {e}")
+ raise ProcessingError(f"Delete triplet failed: {e}")
def create_namespace(self, namespace: str, **options) -> Dict[str, Any]:
"""
diff --git a/semantica/triplet_store/bulk_loader.py b/semantica/triplet_store/bulk_loader.py
index 1d59396b..0eb2be67 100644
--- a/semantica/triplet_store/bulk_loader.py
+++ b/semantica/triplet_store/bulk_loader.py
@@ -20,9 +20,9 @@ Main Classes:
Example Usage:
>>> from semantica.triplet_store import BulkLoader
>>> loader = BulkLoader(batch_size=1000, max_retries=3)
- >>> progress = loader.load_triples(triples, store_adapter)
- >>> print(f"Loaded {progress.loaded_triples}/{progress.total_triples} triples")
- >>> validation = loader.validate_before_load(triples)
+ >>> progress = loader.load_triplets(triplets, store_adapter)
+ >>> print(f"Loaded {progress.loaded_triplets}/{progress.total_triplets} triplets")
+ >>> validation = loader.validate_before_load(triplets)
Author: Semantica Contributors
License: MIT
@@ -33,7 +33,7 @@ from dataclasses import dataclass, field
from datetime import datetime
from typing import Any, Dict, List, Optional
-from ..semantic_extract.triple_extractor import Triple
+from ..semantic_extract.triplet_extractor import Triplet
from ..utils.exceptions import ProcessingError, ValidationError
from ..utils.logging import get_logger
from ..utils.progress_tracker import get_progress_tracker
@@ -43,9 +43,9 @@ from ..utils.progress_tracker import get_progress_tracker
class LoadProgress:
"""Bulk loading progress information."""
- total_triples: int
- loaded_triples: int
- failed_triples: int = 0
+ total_triplets: int
+ loaded_triplets: int
+ failed_triplets: int = 0
current_batch: int = 0
total_batches: int = 0
progress_percentage: float = 0.0
@@ -86,15 +86,15 @@ class BulkLoader:
self.max_retries = self.config.get("max_retries", 3)
self.retry_delay = self.config.get("retry_delay", 1.0)
- def load_triples(
- self, triples: List[Triple], store_adapter: Any, **options
+ def load_triplets(
+ self, triplets: List[Triplet], store_adapter: Any, **options
) -> LoadProgress:
"""
- Load triples in bulk.
+ Load triplets in bulk.
Args:
- triples: List of triples to load
- store_adapter: Triple store adapter instance
+ triplets: List of triplets to load
+ store_adapter: Triplet store adapter instance
**options: Additional options:
- batch_size: Override default batch size
- progress_callback: Callback function for progress updates
@@ -106,7 +106,7 @@ class BulkLoader:
tracking_id = self.progress_tracker.start_tracking(
module="triplet_store",
submodule="BulkLoader",
- message=f"Loading {len(triples)} triples in bulk",
+ message=f"Loading {len(triplets)} triplets in bulk",
)
try:
@@ -115,14 +115,14 @@ class BulkLoader:
stop_on_error = options.get("stop_on_error", False)
progress_callback = options.get("progress_callback")
- total_triples = len(triples)
- total_batches = (total_triples + batch_size - 1) // batch_size
+ total_triplets = len(triplets)
+ total_batches = (total_triplets + batch_size - 1) // batch_size
loaded_count = 0
failed_count = 0
self.logger.info(
- f"Starting bulk load: {total_triples} triples in {total_batches} batches"
+ f"Starting bulk load: {total_triplets} triplets in {total_batches} batches"
)
# Process in batches
@@ -132,8 +132,8 @@ class BulkLoader:
message=f"Processing batch {batch_num + 1}/{total_batches}...",
)
batch_start = batch_num * batch_size
- batch_end = min(batch_start + batch_size, total_triples)
- batch = triples[batch_start:batch_end]
+ batch_end = min(batch_start + batch_size, total_triplets)
+ batch = triplets[batch_start:batch_end]
# Load batch with retries
batch_loaded = 0
@@ -141,8 +141,8 @@ class BulkLoader:
try:
if hasattr(store_adapter, "bulk_load"):
result = store_adapter.bulk_load(batch, **options)
- elif hasattr(store_adapter, "add_triples"):
- result = store_adapter.add_triples(batch, **options)
+ elif hasattr(store_adapter, "add_triplets"):
+ result = store_adapter.add_triplets(batch, **options)
else:
raise ProcessingError(
"Store adapter does not support bulk loading"
@@ -177,18 +177,18 @@ class BulkLoader:
# Update progress
elapsed = time.time() - start_time
progress = (
- (loaded_count / total_triples * 100) if total_triples > 0 else 0.0
+ (loaded_count / total_triplets * 100) if total_triplets > 0 else 0.0
)
estimated_remaining = None
if loaded_count > 0:
estimated_remaining = (elapsed / loaded_count) * (
- total_triples - loaded_count
+ total_triplets - loaded_count
)
progress_info = LoadProgress(
- total_triples=total_triples,
- loaded_triples=loaded_count,
- failed_triples=failed_count,
+ total_triplets=total_triplets,
+ loaded_triplets=loaded_count,
+ failed_triplets=failed_count,
current_batch=batch_num + 1,
total_batches=total_batches,
progress_percentage=progress,
@@ -205,15 +205,15 @@ class BulkLoader:
progress_callback(progress_info)
self.logger.debug(
- f"Progress: {progress:.1f}% ({loaded_count}/{total_triples} triples)"
+ f"Progress: {progress:.1f}% ({loaded_count}/{total_triplets} triplets)"
)
elapsed = time.time() - start_time
final_progress = LoadProgress(
- total_triples=total_triples,
- loaded_triples=loaded_count,
- failed_triples=failed_count,
+ total_triplets=total_triplets,
+ loaded_triplets=loaded_count,
+ failed_triplets=failed_count,
current_batch=total_batches,
total_batches=total_batches,
progress_percentage=100.0,
@@ -226,14 +226,14 @@ class BulkLoader:
)
self.logger.info(
- f"Bulk load completed: {loaded_count}/{total_triples} triples loaded "
- f"in {elapsed:.2f}s ({loaded_count / elapsed:.0f} triples/sec)"
+ f"Bulk load completed: {loaded_count}/{total_triplets} triplets loaded "
+ f"in {elapsed:.2f}s ({loaded_count / elapsed:.0f} triplets/sec)"
)
self.progress_tracker.stop_tracking(
tracking_id,
status="completed",
- message=f"Bulk load completed: {loaded_count}/{total_triples} triples loaded",
+ message=f"Bulk load completed: {loaded_count}/{total_triplets} triplets loaded",
)
return final_progress
@@ -247,11 +247,11 @@ class BulkLoader:
self, file_path: str, store_adapter: Any, **options
) -> LoadProgress:
"""
- Load triples from file.
+ Load triplets from file.
Args:
file_path: Path to RDF file
- store_adapter: Triple store adapter
+ store_adapter: Triplet store adapter
**options: Additional options:
- format: File format (turtle, ntriples, rdfxml)
- chunk_size: Chunk size for reading large files
@@ -262,62 +262,62 @@ class BulkLoader:
format = options.get("format", "turtle")
chunk_size = options.get("chunk_size", 10000)
- # This would parse the file and extract triples
+ # This would parse the file and extract triplets
# For now, return placeholder
self.logger.warning(
"File loading not fully implemented - would parse and load RDF file"
)
return LoadProgress(
- total_triples=0,
- loaded_triples=0,
+ total_triplets=0,
+ loaded_triplets=0,
metadata={"file_path": file_path, "format": format},
)
def load_from_stream(
- self, triples_stream: Any, store_adapter: Any, **options
+ self, triplets_stream: Any, store_adapter: Any, **options
) -> LoadProgress:
"""
- Load triples from stream.
+ Load triplets from stream.
Args:
- triples_stream: Stream of triples
- store_adapter: Triple store adapter
+ triplets_stream: Stream of triplets
+ store_adapter: Triplet store adapter
**options: Additional options
Returns:
Load progress information
"""
- # Collect triples from stream in batches
+ # Collect triplets from stream in batches
batch = []
total_loaded = 0
- for triple in triples_stream:
- batch.append(triple)
+ for triplet in triplets_stream:
+ batch.append(triplet)
if len(batch) >= self.batch_size:
# Load batch
- progress = self.load_triples(batch, store_adapter, **options)
- total_loaded += progress.loaded_triples
+ progress = self.load_triplets(batch, store_adapter, **options)
+ total_loaded += progress.loaded_triplets
batch = []
- # Load remaining triples
+ # Load remaining triplets
if batch:
- progress = self.load_triples(batch, store_adapter, **options)
- total_loaded += progress.loaded_triples
+ progress = self.load_triplets(batch, store_adapter, **options)
+ total_loaded += progress.loaded_triplets
return LoadProgress(
- total_triples=total_loaded,
- loaded_triples=total_loaded,
+ total_triplets=total_loaded,
+ loaded_triplets=total_loaded,
metadata={"source": "stream"},
)
- def validate_before_load(self, triples: List[Triple], **options) -> Dict[str, Any]:
+ def validate_before_load(self, triplets: List[Triplet], **options) -> Dict[str, Any]:
"""
- Validate triples before loading.
+ Validate triplets before loading.
Args:
- triples: List of triples to validate
+ triplets: List of triplets to validate
**options: Validation options
Returns:
@@ -326,37 +326,37 @@ class BulkLoader:
errors = []
warnings = []
- # Check for empty triples
- empty_triples = [
- t for t in triples if not t.subject or not t.predicate or not t.object
+ # Check for empty triplets
+ empty_triplets = [
+ t for t in triplets if not t.subject or not t.predicate or not t.object
]
- if empty_triples:
- errors.append(f"{len(empty_triples)} triples have empty components")
+ if empty_triplets:
+ errors.append(f"{len(empty_triplets)} triplets have empty components")
# Check for invalid URIs
invalid_uris = []
- for triple in triples:
- if not triple.subject.startswith("http") and not triple.subject.startswith(
+ for triplet in triplets:
+ if not triplet.subject.startswith("http") and not triplet.subject.startswith(
"<"
):
- invalid_uris.append(f"Subject: {triple.subject}")
- if not triple.predicate.startswith(
+ invalid_uris.append(f"Subject: {triplet.subject}")
+ if not triplet.predicate.startswith(
"http"
- ) and not triple.predicate.startswith("<"):
- invalid_uris.append(f"Predicate: {triple.predicate}")
+ ) and not triplet.predicate.startswith("<"):
+ invalid_uris.append(f"Predicate: {triplet.predicate}")
if invalid_uris:
- warnings.append(f"{len(invalid_uris)} triples may have invalid URIs")
+ warnings.append(f"{len(invalid_uris)} triplets may have invalid URIs")
# Check confidence scores
- low_confidence = [t for t in triples if t.confidence < 0.5]
+ low_confidence = [t for t in triplets if t.confidence < 0.5]
if low_confidence:
- warnings.append(f"{len(low_confidence)} triples have low confidence scores")
+ warnings.append(f"{len(low_confidence)} triplets have low confidence scores")
return {
"valid": len(errors) == 0,
"errors": errors,
"warnings": warnings,
- "total_triples": len(triples),
- "valid_triples": len(triples) - len(empty_triples),
+ "total_triplets": len(triplets),
+ "valid_triplets": len(triplets) - len(empty_triplets),
}
diff --git a/semantica/triplet_store/config.py b/semantica/triplet_store/config.py
index 8cc136e4..01db8151 100644
--- a/semantica/triplet_store/config.py
+++ b/semantica/triplet_store/config.py
@@ -33,7 +33,7 @@ Example Usage:
>>> from semantica.triplet_store.config import triplet_store_config
>>> default_store = triplet_store_config.get("default_store", default="main")
>>> triplet_store_config.set("default_store", "main")
- >>> method_config = triplet_store_config.get_method_config("add_triple")
+ >>> method_config = triplet_store_config.get_method_config("add_triplet")
"""
import os
diff --git a/semantica/triplet_store/jena_adapter.py b/semantica/triplet_store/jena_adapter.py
index 2a681b67..43795a41 100644
--- a/semantica/triplet_store/jena_adapter.py
+++ b/semantica/triplet_store/jena_adapter.py
@@ -18,7 +18,7 @@ Main Classes:
Example Usage:
>>> from semantica.triplet_store import JenaAdapter
>>> adapter = JenaAdapter(endpoint="http://localhost:3030/ds", dataset="default")
- >>> result = adapter.add_triples(triples)
+ >>> result = adapter.add_triplets(triplets)
>>> query_result = adapter.execute_sparql(sparql_query)
>>> rdf_turtle = adapter.serialize(format="turtle")
@@ -28,7 +28,7 @@ License: MIT
from typing import Any, Dict, List, Optional
-from ..semantic_extract.triple_extractor import Triple
+from ..semantic_extract.triplet_extractor import Triplet
from ..utils.exceptions import ProcessingError, ValidationError
from ..utils.logging import get_logger
from ..utils.progress_tracker import get_progress_tracker
@@ -114,15 +114,15 @@ class JenaAdapter:
return {
"model_id": self.dataset,
"endpoint": self.endpoint,
- "triple_count": len(self.graph) if self.graph else 0,
+ "triplet_count": len(self.graph) if self.graph else 0,
}
- def add_triples(self, triples: List[Triple], **options) -> Dict[str, Any]:
+ def add_triplets(self, triplets: List[Triplet], **options) -> Dict[str, Any]:
"""
- Add triples to model.
+ Add triplets to model.
Args:
- triples: List of triples
+ triplets: List of triplets
**options: Additional options
Returns:
@@ -131,7 +131,7 @@ class JenaAdapter:
tracking_id = self.progress_tracker.start_tracking(
module="triplet_store",
submodule="JenaAdapter",
- message=f"Adding {len(triples)} triples to Jena model",
+ message=f"Adding {len(triplets)} triplets to Jena model",
)
try:
@@ -143,48 +143,48 @@ class JenaAdapter:
added_count = 0
self.progress_tracker.update_tracking(
- tracking_id, message="Adding triples to graph..."
+ tracking_id, message="Adding triplets to graph..."
)
- for triple in triples:
+ for triplet in triplets:
try:
- subject = URIRef(triple.subject)
- predicate = URIRef(triple.predicate)
+ subject = URIRef(triplet.subject)
+ predicate = URIRef(triplet.predicate)
obj = (
- URIRef(triple.object)
- if triple.object.startswith("http")
- else Literal(triple.object)
+ URIRef(triplet.object)
+ if triplet.object.startswith("http")
+ else Literal(triplet.object)
)
self.graph.add((subject, predicate, obj))
added_count += 1
except Exception as e:
- self.logger.warning(f"Failed to add triple: {e}")
+ self.logger.warning(f"Failed to add triplet: {e}")
self.progress_tracker.stop_tracking(
tracking_id,
status="completed",
- message=f"Added {added_count}/{len(triples)} triples",
+ message=f"Added {added_count}/{len(triplets)} triplets",
)
- return {"success": True, "added": added_count, "total": len(triples)}
+ return {"success": True, "added": added_count, "total": len(triplets)}
except Exception as e:
- self.logger.error(f"Failed to add triples: {e}")
+ self.logger.error(f"Failed to add triplets: {e}")
self.progress_tracker.stop_tracking(
tracking_id, status="failed", message=str(e)
)
- raise ProcessingError(f"Failed to add triples: {e}")
+ raise ProcessingError(f"Failed to add triplets: {e}")
- def add_triple(self, triple: Triple, **options) -> Dict[str, Any]:
- """Add single triple."""
- return self.add_triples([triple], **options)
+ def add_triplet(self, triplet: Triplet, **options) -> Dict[str, Any]:
+ """Add single triplet."""
+ return self.add_triplets([triplet], **options)
- def get_triples(
+ def get_triplets(
self,
subject: Optional[str] = None,
predicate: Optional[str] = None,
object: Optional[str] = None,
**options,
- ) -> List[Triple]:
- """Get triples matching criteria."""
+ ) -> List[Triplet]:
+ """Get triplets matching criteria."""
if not self.graph:
return []
@@ -203,10 +203,10 @@ class JenaAdapter:
results = self.graph.query(query)
- triples = []
+ triplets = []
for row in results:
- triples.append(
- Triple(
+ triplets.append(
+ Triplet(
subject=str(row.s),
predicate=str(row.p),
object=str(row.o),
@@ -214,31 +214,31 @@ class JenaAdapter:
)
)
- return triples
+ return triplets
except Exception as e:
- self.logger.error(f"Failed to get triples: {e}")
+ self.logger.error(f"Failed to get triplets: {e}")
return []
- def delete_triple(self, triple: Triple, **options) -> Dict[str, Any]:
- """Delete triple."""
+ def delete_triplet(self, triplet: Triplet, **options) -> Dict[str, Any]:
+ """Delete triplet."""
if not self.graph:
raise ProcessingError("Graph not initialized")
try:
- subject = URIRef(triple.subject)
- predicate = URIRef(triple.predicate)
+ subject = URIRef(triplet.subject)
+ predicate = URIRef(triplet.predicate)
obj = (
- URIRef(triple.object)
- if triple.object.startswith("http")
- else Literal(triple.object)
+ URIRef(triplet.object)
+ if triplet.object.startswith("http")
+ else Literal(triplet.object)
)
self.graph.remove((subject, predicate, obj))
return {"success": True}
except Exception as e:
- self.logger.error(f"Failed to delete triple: {e}")
- raise ProcessingError(f"Failed to delete triple: {e}")
+ self.logger.error(f"Failed to delete triplet: {e}")
+ raise ProcessingError(f"Failed to delete triplet: {e}")
def run_inference(self, model: Optional[Any] = None, **options) -> Dict[str, Any]:
"""
@@ -261,7 +261,7 @@ class JenaAdapter:
return {
"success": True,
- "inferred_triples": 0,
+ "inferred_triplets": 0,
"message": "Inference placeholder",
}
diff --git a/semantica/triplet_store/methods.py b/semantica/triplet_store/methods.py
index ca351ac7..262f4847 100644
--- a/semantica/triplet_store/methods.py
+++ b/semantica/triplet_store/methods.py
@@ -2,7 +2,7 @@
Triplet Store Methods Module
This module provides all triplet store methods as simple, reusable functions for
-registering stores, adding triples, querying, and managing triplet stores. It supports
+registering stores, adding triplets, querying, and managing triplet stores. It supports
multiple approaches and integrates with the method registry for extensibility.
Supported Methods:
@@ -14,24 +14,24 @@ Store Registration:
- "rdf4j": RDF4J-specific registration
- "virtuoso": Virtuoso-specific registration
-Triple Addition:
- - "default": Default triple addition
- - "single": Single triple addition
- - "batch": Batch triple addition
- - "bulk": Bulk triple addition
+Triplet Addition:
+ - "default": Default triplet addition
+ - "single": Single triplet addition
+ - "batch": Batch triplet addition
+ - "bulk": Bulk triplet addition
-Triple Retrieval:
- - "default": Default triple retrieval
+Triplet Retrieval:
+ - "default": Default triplet retrieval
- "pattern": Pattern-based retrieval
- "sparql": SPARQL-based retrieval
-Triple Deletion:
- - "default": Default triple deletion
- - "single": Single triple deletion
- - "batch": Batch triple deletion
+Triplet Deletion:
+ - "default": Default triplet deletion
+ - "single": Single triplet deletion
+ - "batch": Batch triplet deletion
-Triple Update:
- - "default": Default triple update (delete-then-add)
+Triplet Update:
+ - "default": Default triplet update (delete-then-add)
- "atomic": Atomic update (when supported)
SPARQL Query:
@@ -51,7 +51,7 @@ Bulk Loading:
Validation:
- "default": Default validation
- - "triple": Triple structure validation
+ - "triplet": Triplet structure validation
- "pre_load": Pre-load validation
Algorithms Used:
@@ -61,8 +61,8 @@ Store Registration:
- Configuration Management: Store configuration storage, default store selection
- Adapter Instantiation: Backend-specific adapter creation, connection initialization
-Triple Operations:
- - Triple Validation: Required field checking, confidence validation, URI validation
+Triplet Operations:
+ - Triplet Validation: Required field checking, confidence validation, URI validation
- Batch Processing: Chunking algorithm, batch size optimization
- Pattern Matching: Subject/predicate/object filtering, SPARQL query construction
@@ -86,28 +86,28 @@ Key Features:
Main Functions:
- register_store: Store registration wrapper
- - add_triple: Triple addition wrapper
- - add_triples: Multiple triple addition wrapper
- - get_triples: Triple retrieval wrapper
- - delete_triple: Triple deletion wrapper
- - update_triple: Triple update wrapper
+ - add_triplet: Triplet addition wrapper
+ - add_triplets: Multiple triplet addition wrapper
+ - get_triplets: Triplet retrieval wrapper
+ - delete_triplet: Triplet deletion wrapper
+ - update_triplet: Triplet update wrapper
- execute_query: SPARQL query execution wrapper
- optimize_query: Query optimization wrapper
- bulk_load: Bulk loading wrapper
- - validate_triples: Triple validation wrapper
+ - validate_triplets: Triplet validation wrapper
- get_triplet_store_method: Get triplet store method by task and name
- list_available_methods: List registered methods
Example Usage:
- >>> from semantica.triplet_store.methods import register_store, add_triple, execute_query
+ >>> from semantica.triplet_store.methods import register_store, add_triplet, execute_query
>>> store = register_store("main", "blazegraph", "http://localhost:9999/blazegraph", method="default")
- >>> result = add_triple(triple, store_id="main", method="default")
+ >>> result = add_triplet(triplet, store_id="main", method="default")
>>> query_result = execute_query(sparql_query, store_adapter, method="default")
"""
from typing import Any, Dict, List, Optional, Union
-from ..semantic_extract.triple_extractor import Triple
+from ..semantic_extract.triplet_extractor import Triplet
from .bulk_loader import BulkLoader, LoadProgress
from .config import triplet_store_config
from .query_engine import QueryEngine, QueryPlan, QueryResult
@@ -173,14 +173,14 @@ def register_store(
return manager.register_store(store_id, store_type, endpoint, **options)
-def add_triple(
- triple: Triple, store_id: Optional[str] = None, method: str = "default", **options
+def add_triplet(
+ triplet: Triplet, store_id: Optional[str] = None, method: str = "default", **options
) -> Dict[str, Any]:
"""
- Add single triple to store.
+ Add single triplet to store.
Args:
- triple: Triple to add
+ triplet: Triplet to add
store_id: Store identifier (uses default if not provided)
method: Addition method name (default: "default")
**options: Additional options
@@ -191,24 +191,24 @@ def add_triple(
# Check registry for custom method
custom_method = method_registry.get("add", method)
if custom_method:
- return custom_method(triple, store_id=store_id, **options)
+ return custom_method(triplet, store_id=store_id, **options)
# Default implementation
manager = _get_manager()
- return manager.add_triple(triple, store_id=store_id, **options)
+ return manager.add_triplet(triplet, store_id=store_id, **options)
-def add_triples(
- triples: List[Triple],
+def add_triplets(
+ triplets: List[Triplet],
store_id: Optional[str] = None,
method: str = "default",
**options,
) -> Dict[str, Any]:
"""
- Add multiple triples to store.
+ Add multiple triplets to store.
Args:
- triples: List of triples to add
+ triplets: List of triplets to add
store_id: Store identifier
method: Addition method name (default: "default")
**options: Additional options
@@ -219,23 +219,23 @@ def add_triples(
# Check registry for custom method
custom_method = method_registry.get("add", method)
if custom_method:
- return custom_method(triples, store_id=store_id, **options)
+ return custom_method(triplets, store_id=store_id, **options)
# Default implementation
manager = _get_manager()
- return manager.add_triples(triples, store_id=store_id, **options)
+ return manager.add_triplets(triplets, store_id=store_id, **options)
-def get_triples(
+def get_triplets(
subject: Optional[str] = None,
predicate: Optional[str] = None,
object: Optional[str] = None,
store_id: Optional[str] = None,
method: str = "default",
**options,
-) -> List[Triple]:
+) -> List[Triplet]:
"""
- Get triples matching criteria.
+ Get triplets matching criteria.
Args:
subject: Optional subject URI
@@ -246,7 +246,7 @@ def get_triples(
**options: Additional options
Returns:
- List of matching triples
+ List of matching triplets
"""
# Check registry for custom method
custom_method = method_registry.get("get", method)
@@ -255,17 +255,17 @@ def get_triples(
# Default implementation
manager = _get_manager()
- return manager.get_triple(subject, predicate, object, store_id=store_id, **options)
+ return manager.get_triplets(subject, predicate, object, store_id=store_id, **options)
-def delete_triple(
- triple: Triple, store_id: Optional[str] = None, method: str = "default", **options
+def delete_triplet(
+ triplet: Triplet, store_id: Optional[str] = None, method: str = "default", **options
) -> Dict[str, Any]:
"""
- Delete triple from store.
+ Delete triplet from store.
Args:
- triple: Triple to delete
+ triplet: Triplet to delete
store_id: Store identifier
method: Deletion method name (default: "default")
**options: Additional options
@@ -276,26 +276,26 @@ def delete_triple(
# Check registry for custom method
custom_method = method_registry.get("delete", method)
if custom_method:
- return custom_method(triple, store_id=store_id, **options)
+ return custom_method(triplet, store_id=store_id, **options)
# Default implementation
manager = _get_manager()
- return manager.delete_triple(triple, store_id=store_id, **options)
+ return manager.delete_triplet(triplet, store_id=store_id, **options)
-def update_triple(
- old_triple: Triple,
- new_triple: Triple,
+def update_triplet(
+ old_triplet: Triplet,
+ new_triplet: Triplet,
store_id: Optional[str] = None,
method: str = "default",
**options,
) -> Dict[str, Any]:
"""
- Update triple in store.
+ Update triplet in store.
Args:
- old_triple: Original triple
- new_triple: Updated triple
+ old_triplet: Original triplet
+ new_triplet: Updated triplet
store_id: Store identifier
method: Update method name (default: "default")
**options: Additional options
@@ -306,11 +306,11 @@ def update_triple(
# Check registry for custom method
custom_method = method_registry.get("update", method)
if custom_method:
- return custom_method(old_triple, new_triple, store_id=store_id, **options)
+ return custom_method(old_triplet, new_triplet, store_id=store_id, **options)
# Default implementation
manager = _get_manager()
- return manager.update_triple(old_triple, new_triple, store_id=store_id, **options)
+ return manager.update_triplet(old_triplet, new_triplet, store_id=store_id, **options)
def execute_query(
@@ -376,13 +376,13 @@ def plan_query(query: str, **options) -> QueryPlan:
def bulk_load(
- triples: List[Triple], store_adapter: Any, method: str = "default", **options
+ triplets: List[Triplet], store_adapter: Any, method: str = "default", **options
) -> LoadProgress:
"""
- Load triples in bulk.
+ Load triplets in bulk.
Args:
- triples: List of triples to load
+ triplets: List of triplets to load
store_adapter: Triplet store adapter instance
method: Loading method name (default: "default")
**options: Additional options
@@ -393,21 +393,21 @@ def bulk_load(
# Check registry for custom method
custom_method = method_registry.get("bulk_load", method)
if custom_method:
- return custom_method(triples, store_adapter, **options)
+ return custom_method(triplets, store_adapter, **options)
# Default implementation
loader = _get_bulk_loader()
- return loader.load_triples(triples, store_adapter, **options)
+ return loader.load_triplets(triplets, store_adapter, **options)
-def validate_triples(
- triples: List[Triple], method: str = "default", **options
+def validate_triplets(
+ triplets: List[Triplet], method: str = "default", **options
) -> Dict[str, Any]:
"""
- Validate triples before loading.
+ Validate triplets before loading.
Args:
- triples: List of triples to validate
+ triplets: List of triplets to validate
method: Validation method name (default: "default")
**options: Validation options
@@ -417,11 +417,11 @@ def validate_triples(
# Check registry for custom method
custom_method = method_registry.get("validate", method)
if custom_method:
- return custom_method(triples, **options)
+ return custom_method(triplets, **options)
# Default implementation
loader = _get_bulk_loader()
- return loader.validate_before_load(triples, **options)
+ return loader.validate_before_load(triplets, **options)
def get_triplet_store_method(task: str, method_name: str) -> Optional[Any]:
diff --git a/semantica/triplet_store/query_engine.py b/semantica/triplet_store/query_engine.py
index 9bbaf312..49e5a589 100644
--- a/semantica/triplet_store/query_engine.py
+++ b/semantica/triplet_store/query_engine.py
@@ -102,7 +102,7 @@ class QueryEngine:
Args:
query: SPARQL query string
- store_adapter: Triple store adapter instance
+ store_adapter: Triplet store adapter instance
**options: Additional options
Returns:
diff --git a/semantica/triplet_store/rdf4j_adapter.py b/semantica/triplet_store/rdf4j_adapter.py
index 5c80a59e..89027a80 100644
--- a/semantica/triplet_store/rdf4j_adapter.py
+++ b/semantica/triplet_store/rdf4j_adapter.py
@@ -20,7 +20,7 @@ Example Usage:
>>> adapter = RDF4JAdapter(endpoint="http://localhost:8080/rdf4j-server", repository_id="repo1")
>>> result = adapter.execute_sparql(sparql_query)
>>> tx_id = adapter.begin_transaction()
- >>> result = adapter.add_triples(triples)
+ >>> result = adapter.add_triplets(triplets)
Author: Semantica Contributors
License: MIT
@@ -30,7 +30,7 @@ from typing import Any, Dict, List, Optional
import requests
-from ..semantic_extract.triple_extractor import Triple
+from ..semantic_extract.triplet_extractor import Triplet
from ..utils.exceptions import ProcessingError, ValidationError
from ..utils.logging import get_logger
from ..utils.progress_tracker import get_progress_tracker
@@ -238,12 +238,12 @@ class RDF4JAdapter:
)
raise ProcessingError(f"SPARQL query failed: {e}")
- def add_triples(self, triples: List[Triple], **options) -> Dict[str, Any]:
+ def add_triplets(self, triplets: List[Triplet], **options) -> Dict[str, Any]:
"""
- Add triples to repository.
+ Add triplets to repository.
Args:
- triples: List of triples
+ triplets: List of triplets
**options: Additional options
Returns:
@@ -252,7 +252,7 @@ class RDF4JAdapter:
tracking_id = self.progress_tracker.start_tracking(
module="triplet_store",
submodule="RDF4JAdapter",
- message=f"Adding {len(triples)} triples to RDF4J repository",
+ message=f"Adding {len(triplets)} triplets to RDF4J repository",
)
try:
@@ -264,14 +264,14 @@ class RDF4JAdapter:
update_endpoint = self._get_update_endpoint()
- # Convert triples to RDF format
+ # Convert triplets to RDF format
self.progress_tracker.update_tracking(
- tracking_id, message="Converting triples to RDF format..."
+ tracking_id, message="Converting triplets to RDF format..."
)
- rdf_data = self._triples_to_ntriples(triples)
+ rdf_data = self._triplets_to_ntriples(triplets)
self.progress_tracker.update_tracking(
- tracking_id, message="Sending triples to RDF4J repository..."
+ tracking_id, message="Sending triplets to RDF4J repository..."
)
response = requests.post(
update_endpoint,
@@ -288,29 +288,29 @@ class RDF4JAdapter:
self.progress_tracker.stop_tracking(
tracking_id,
status="completed",
- message=f"Added {len(triples)} triples to repository",
+ message=f"Added {len(triplets)} triplets to repository",
)
- return {"success": True, "triples_added": len(triples)}
+ return {"success": True, "triplets_added": len(triplets)}
except Exception as e:
- self.logger.error(f"Add triples failed: {e}")
+ self.logger.error(f"Add triplets failed: {e}")
self.progress_tracker.stop_tracking(
tracking_id, status="failed", message=str(e)
)
- raise ProcessingError(f"Add triples failed: {e}")
+ raise ProcessingError(f"Add triplets failed: {e}")
- def add_triple(self, triple: Triple, **options) -> Dict[str, Any]:
- """Add single triple."""
- return self.add_triples([triple], **options)
+ def add_triplet(self, triplet: Triplet, **options) -> Dict[str, Any]:
+ """Add single triplet."""
+ return self.add_triplets([triplet], **options)
- def get_triples(
+ def get_triplets(
self,
subject: Optional[str] = None,
predicate: Optional[str] = None,
object: Optional[str] = None,
**options,
- ) -> List[Triple]:
- """Get triples matching criteria."""
+ ) -> List[Triplet]:
+ """Get triplets matching criteria."""
# Build SPARQL query
where_clauses = []
if subject:
@@ -325,11 +325,11 @@ class RDF4JAdapter:
result = self.execute_sparql(query, **options)
- # Convert bindings to triples
- triples = []
+ # Convert bindings to triplets
+ triplets = []
for binding in result["bindings"]:
- triples.append(
- Triple(
+ triplets.append(
+ Triplet(
subject=binding.get("s", {}).get("value", ""),
predicate=binding.get("p", {}).get("value", ""),
object=binding.get("o", {}).get("value", ""),
@@ -337,17 +337,17 @@ class RDF4JAdapter:
)
)
- return triples
+ return triplets
- def delete_triple(self, triple: Triple, **options) -> Dict[str, Any]:
- """Delete triple."""
+ def delete_triplet(self, triplet: Triplet, **options) -> Dict[str, Any]:
+ """Delete triplet."""
if not self.connected:
raise ProcessingError("Not connected to RDF4J")
update_endpoint = self._get_update_endpoint()
# Use SPARQL DELETE
- query = f"DELETE DATA {{ <{triple.subject}> <{triple.predicate}> <{triple.object}> }}"
+ query = f"DELETE DATA {{ <{triplet.subject}> <{triplet.predicate}> <{triplet.object}> }}"
try:
response = requests.post(
@@ -364,12 +364,12 @@ class RDF4JAdapter:
return {"success": True}
except Exception as e:
- self.logger.error(f"Delete triple failed: {e}")
- raise ProcessingError(f"Delete triple failed: {e}")
+ self.logger.error(f"Delete triplet failed: {e}")
+ raise ProcessingError(f"Delete triplet failed: {e}")
- def _triples_to_ntriples(self, triples: List[Triple]) -> str:
- """Convert triples to N-Triples format."""
+ def _triplets_to_ntriples(self, triplets: List[Triplet]) -> str:
+ """Convert triplets to N-Triples format."""
lines = []
- for triple in triples:
- lines.append(f"<{triple.subject}> <{triple.predicate}> <{triple.object}> .")
+ for triplet in triplets:
+ lines.append(f"<{triplet.subject}> <{triplet.predicate}> <{triplet.object}> .")
return "\n".join(lines)
diff --git a/semantica/triplet_store/registry.py b/semantica/triplet_store/registry.py
index d4eebf03..8c8136c5 100644
--- a/semantica/triplet_store/registry.py
+++ b/semantica/triplet_store/registry.py
@@ -7,10 +7,10 @@ enabling extensibility and community contributions to the triplet store toolkit.
Supported Registration Types:
- Method Registry: Register custom triplet store methods for:
* "register": Store registration methods
- * "add": Triple addition methods
- * "get": Triple retrieval methods
- * "delete": Triple deletion methods
- * "update": Triple update methods
+ * "add": Triplet addition methods
+ * "get": Triplet retrieval methods
+ * "delete": Triplet deletion methods
+ * "update": Triplet update methods
* "query": SPARQL query execution methods
* "optimize": Query optimization methods
* "bulk_load": Bulk loading methods
diff --git a/semantica/triplet_store/triplet_manager.py b/semantica/triplet_store/triplet_manager.py
index aace44eb..be3b076b 100644
--- a/semantica/triplet_store/triplet_manager.py
+++ b/semantica/triplet_store/triplet_manager.py
@@ -21,9 +21,9 @@ Example Usage:
>>> from semantica.triplet_store import TripletManager
>>> manager = TripletManager()
>>> store = manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
- >>> result = manager.add_triple(triple, store_id="main")
- >>> triples = manager.get_triple(subject="http://example.org/entity1")
- >>> result = manager.add_triples(triple_list, store_id="main", batch_size=1000)
+ >>> result = manager.add_triplet(triplet, store_id="main")
+ >>> triplets = manager.get_triplets(subject="http://example.org/entity1")
+ >>> result = manager.add_triplets(triplet_list, store_id="main", batch_size=1000)
Author: Semantica Contributors
License: MIT
@@ -32,7 +32,7 @@ License: MIT
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
-from ..semantic_extract.triple_extractor import Triple
+from ..semantic_extract.triplet_extractor import Triplet
from ..utils.exceptions import ProcessingError, ValidationError
from ..utils.logging import get_logger
from ..utils.progress_tracker import get_progress_tracker
@@ -53,9 +53,9 @@ class TripletManager:
"""
Triplet store management system.
- • CRUD operations for RDF triples
+ • CRUD operations for RDF triplets
• Batch operations and bulk loading
- • Triple validation and consistency
+ • Triplet validation and consistency
• Transaction support
• Performance optimization
• Error handling and recovery
@@ -106,14 +106,14 @@ class TripletManager:
return store
- def add_triple(
- self, triple: Triple, store_id: Optional[str] = None, **options
+ def add_triplet(
+ self, triplet: Triplet, store_id: Optional[str] = None, **options
) -> Dict[str, Any]:
"""
- Add single triple to store.
+ Add single triplet to store.
Args:
- triple: Triple to add
+ triplet: Triplet to add
store_id: Store identifier (uses default if not provided)
**options: Additional options
@@ -122,37 +122,37 @@ class TripletManager:
"""
store = self._get_store(store_id)
- # Validate triple
- if not self._validate_triple(triple):
- raise ValidationError("Invalid triple")
+ # Validate triplet
+ if not self._validate_triplet(triplet):
+ raise ValidationError("Invalid triplet")
# Add to store (delegates to adapter)
try:
adapter = self._get_adapter(store)
- result = adapter.add_triple(triple, **options)
+ result = adapter.add_triplet(triplet, **options)
return {
"success": True,
"store_id": store.store_id,
- "triple": triple,
+ "triplet": triplet,
**result,
}
except Exception as e:
- self.logger.error(f"Failed to add triple: {e}")
- raise ProcessingError(f"Failed to add triple: {e}")
+ self.logger.error(f"Failed to add triplet: {e}")
+ raise ProcessingError(f"Failed to add triplet: {e}")
- def add_triples(
- self, triples: List[Triple], store_id: Optional[str] = None, **options
+ def add_triplets(
+ self, triplets: List[Triplet], store_id: Optional[str] = None, **options
) -> Dict[str, Any]:
"""
- Add multiple triples to store.
+ Add multiple triplets to store.
Args:
- triples: List of triples
+ triplets: List of triplets
store_id: Store identifier
**options: Additional options:
- batch_size: Batch size for bulk operations
- - validate: Validate triples before adding
+ - validate: Validate triplets before adding
Returns:
Operation status
@@ -160,69 +160,69 @@ class TripletManager:
tracking_id = self.progress_tracker.start_tracking(
module="triplet_store",
submodule="TripletManager",
- message=f"Adding {len(triples)} triples to store",
+ message=f"Adding {len(triplets)} triplets to store",
)
try:
store = self._get_store(store_id)
- # Validate triples
+ # Validate triplets
if options.get("validate", True):
self.progress_tracker.update_tracking(
- tracking_id, message="Validating triples..."
+ tracking_id, message="Validating triplets..."
)
- valid_triples = [t for t in triples if self._validate_triple(t)]
- invalid_count = len(triples) - len(valid_triples)
+ valid_triplets = [t for t in triplets if self._validate_triplet(t)]
+ invalid_count = len(triplets) - len(valid_triplets)
if invalid_count > 0:
- self.logger.warning(f"{invalid_count} invalid triples filtered out")
+ self.logger.warning(f"{invalid_count} invalid triplets filtered out")
else:
- valid_triples = triples
+ valid_triplets = triplets
# Add to store
adapter = self._get_adapter(store)
batch_size = options.get("batch_size", 1000)
- total_batches = (len(valid_triples) + batch_size - 1) // batch_size
+ total_batches = (len(valid_triplets) + batch_size - 1) // batch_size
results = []
- for i in range(0, len(valid_triples), batch_size):
+ for i in range(0, len(valid_triplets), batch_size):
batch_num = i // batch_size + 1
self.progress_tracker.update_tracking(
tracking_id,
message=f"Processing batch {batch_num}/{total_batches}...",
)
- batch = valid_triples[i : i + batch_size]
- result = adapter.add_triples(batch, **options)
+ batch = valid_triplets[i : i + batch_size]
+ result = adapter.add_triplets(batch, **options)
results.append(result)
self.progress_tracker.stop_tracking(
tracking_id,
status="completed",
- message=f"Added {len(valid_triples)} triples in {len(results)} batches",
+ message=f"Added {len(valid_triplets)} triplets in {len(results)} batches",
)
return {
"success": True,
"store_id": store.store_id,
- "total_triples": len(valid_triples),
+ "total_triplets": len(valid_triplets),
"batches": len(results),
"results": results,
}
except Exception as e:
- self.logger.error(f"Failed to add triples: {e}")
+ self.logger.error(f"Failed to add triplets: {e}")
self.progress_tracker.stop_tracking(
tracking_id, status="failed", message=str(e)
)
- raise ProcessingError(f"Failed to add triples: {e}")
+ raise ProcessingError(f"Failed to add triplets: {e}")
- def get_triple(
+ def get_triplets(
self,
subject: str,
predicate: Optional[str] = None,
object: Optional[str] = None,
store_id: Optional[str] = None,
**options,
- ) -> List[Triple]:
+ ) -> List[Triplet]:
"""
- Get triples matching criteria.
+ Get triplets matching criteria.
Args:
subject: Subject URI
@@ -232,25 +232,25 @@ class TripletManager:
**options: Additional options
Returns:
- List of matching triples
+ List of matching triplets
"""
store = self._get_store(store_id)
try:
adapter = self._get_adapter(store)
- return adapter.get_triples(subject, predicate, object, **options)
+ return adapter.get_triplets(subject, predicate, object, **options)
except Exception as e:
- self.logger.error(f"Failed to get triples: {e}")
- raise ProcessingError(f"Failed to get triples: {e}")
+ self.logger.error(f"Failed to get triplets: {e}")
+ raise ProcessingError(f"Failed to get triplets: {e}")
- def delete_triple(
- self, triple: Triple, store_id: Optional[str] = None, **options
+ def delete_triplet(
+ self, triplet: Triplet, store_id: Optional[str] = None, **options
) -> Dict[str, Any]:
"""
- Delete triple from store.
+ Delete triplet from store.
Args:
- triple: Triple to delete
+ triplet: Triplet to delete
store_id: Store identifier
**options: Additional options
@@ -261,26 +261,26 @@ class TripletManager:
try:
adapter = self._get_adapter(store)
- result = adapter.delete_triple(triple, **options)
+ result = adapter.delete_triplet(triplet, **options)
return {"success": True, "store_id": store.store_id, **result}
except Exception as e:
- self.logger.error(f"Failed to delete triple: {e}")
- raise ProcessingError(f"Failed to delete triple: {e}")
+ self.logger.error(f"Failed to delete triplet: {e}")
+ raise ProcessingError(f"Failed to delete triplet: {e}")
- def update_triple(
+ def update_triplet(
self,
- old_triple: Triple,
- new_triple: Triple,
+ old_triplet: Triplet,
+ new_triplet: Triplet,
store_id: Optional[str] = None,
**options,
) -> Dict[str, Any]:
"""
- Update triple in store.
+ Update triplet in store.
Args:
- old_triple: Original triple
- new_triple: Updated triple
+ old_triplet: Original triplet
+ new_triplet: Updated triplet
store_id: Store identifier
**options: Additional options
@@ -288,15 +288,15 @@ class TripletManager:
Operation status
"""
# Delete old and add new
- self.delete_triple(old_triple, store_id, **options)
- return self.add_triple(new_triple, store_id, **options)
+ self.delete_triplet(old_triplet, store_id, **options)
+ return self.add_triplet(new_triplet, store_id, **options)
- def _validate_triple(self, triple: Triple) -> bool:
- """Validate triple structure."""
- if not triple.subject or not triple.predicate or not triple.object:
+ def _validate_triplet(self, triplet: Triplet) -> bool:
+ """Validate triplet structure."""
+ if not triplet.subject or not triplet.predicate or not triplet.object:
return False
- if triple.confidence < 0 or triple.confidence > 1:
+ if triplet.confidence < 0 or triplet.confidence > 1:
return False
return True
diff --git a/semantica/triplet_store/triplet_store_usage.md b/semantica/triplet_store/triplet_store_usage.md
index 9b4696a7..89a557af 100644
--- a/semantica/triplet_store/triplet_store_usage.md
+++ b/semantica/triplet_store/triplet_store_usage.md
@@ -21,7 +21,7 @@ This comprehensive guide demonstrates how to use the triplet store module for RD
```python
from semantica.triplet_store import TripletManager
-from semantica.semantic_extract.triple_extractor import Triple
+from semantica.semantic_extract.triplet_extractor import Triplet
# Create triplet manager
manager = TripletManager()
@@ -29,38 +29,38 @@ manager = TripletManager()
# Register a store
store = manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
-# Add a triple
-triple = Triple(
+# Add a triplet
+triplet = Triplet(
subject="http://example.org/entity1",
predicate="http://example.org/hasName",
object="John Doe",
confidence=0.9
)
-result = manager.add_triple(triple, store_id="main")
+result = manager.add_triplet(triplet, store_id="main")
-print(f"Triple added: {result['success']}")
+print(f"Triplet added: {result['success']}")
```
### Using Convenience Functions
```python
-from semantica.triplet_store import register_store, add_triple, get_triples, execute_query
-from semantica.semantic_extract.triple_extractor import Triple
+from semantica.triplet_store import register_store, add_triplet, get_triplets, execute_query
+from semantica.semantic_extract.triplet_extractor import Triplet
# Register store
store = register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
-# Add triple
-triple = Triple(
+# Add triplet
+triplet = Triplet(
subject="http://example.org/entity1",
predicate="http://example.org/hasName",
object="John Doe"
)
-result = add_triple(triple, store_id="main")
+result = add_triplet(triplet, store_id="main")
-# Get triples
-triples = get_triples(subject="http://example.org/entity1", store_id="main")
-print(f"Found {len(triples)} triples")
+# Get triplets
+triplets = get_triplets(subject="http://example.org/entity1", store_id="main")
+print(f"Found {len(triplets)} triplets")
```
### Using QueryEngine
@@ -162,36 +162,36 @@ print(f"Store endpoint: {store.endpoint}")
## CRUD Operations
-### Adding Triples
+### Adding Triplets
```python
from semantica.triplet_store import TripletManager
-from semantica.semantic_extract.triple_extractor import Triple
+from semantica.semantic_extract.triplet_extractor import Triplet
manager = TripletManager()
manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
-# Add single triple
-triple = Triple(
+# Add single triplet
+triplet = Triplet(
subject="http://example.org/entity1",
predicate="http://example.org/hasName",
object="John Doe",
confidence=0.9
)
-result = manager.add_triple(triple, store_id="main")
+result = manager.add_triplet(triplet, store_id="main")
print(f"Added: {result['success']}")
-# Add multiple triples
-triples = [
- Triple("http://example.org/entity1", "http://example.org/hasAge", "30"),
- Triple("http://example.org/entity1", "http://example.org/hasCity", "New York"),
- Triple("http://example.org/entity2", "http://example.org/hasName", "Jane Smith")
+# Add multiple triplets
+triplets = [
+ Triplet("http://example.org/entity1", "http://example.org/hasAge", "30"),
+ Triplet("http://example.org/entity1", "http://example.org/hasCity", "New York"),
+ Triplet("http://example.org/entity2", "http://example.org/hasName", "Jane Smith")
]
-result = manager.add_triples(triples, store_id="main", batch_size=1000)
-print(f"Added {result['total_triples']} triples in {result['batches']} batches")
+result = manager.add_triplets(triplets, store_id="main", batch_size=1000)
+print(f"Added {result['total_triplets']} triplets in {result['batches']} batches")
```
-### Retrieving Triples
+### Retrieving Triplets
```python
from semantica.triplet_store import TripletManager
@@ -199,22 +199,22 @@ from semantica.triplet_store import TripletManager
manager = TripletManager()
manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
-# Get all triples for a subject
-triples = manager.get_triple(
+# Get all triplets for a subject
+triplets = manager.get_triplets(
subject="http://example.org/entity1",
store_id="main"
)
-print(f"Found {len(triples)} triples for entity1")
+print(f"Found {len(triplets)} triplets for entity1")
-# Get triples matching predicate
-triples = manager.get_triple(
+# Get triplets matching predicate
+triplets = manager.get_triplets(
predicate="http://example.org/hasName",
store_id="main"
)
-print(f"Found {len(triples)} triples with hasName predicate")
+print(f"Found {len(triplets)} triplets with hasName predicate")
-# Get specific triple
-triples = manager.get_triple(
+# Get specific triplet
+triplets = manager.get_triplets(
subject="http://example.org/entity1",
predicate="http://example.org/hasName",
object="John Doe",
@@ -222,46 +222,46 @@ triples = manager.get_triple(
)
```
-### Deleting Triples
+### Deleting Triplets
```python
from semantica.triplet_store import TripletManager
-from semantica.semantic_extract.triple_extractor import Triple
+from semantica.semantic_extract.triplet_extractor import Triplet
manager = TripletManager()
manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
-# Delete triple
-triple = Triple(
+# Delete triplet
+triplet = Triplet(
subject="http://example.org/entity1",
predicate="http://example.org/hasName",
object="John Doe"
)
-result = manager.delete_triple(triple, store_id="main")
+result = manager.delete_triplet(triplet, store_id="main")
print(f"Deleted: {result['success']}")
```
-### Updating Triples
+### Updating Triplets
```python
from semantica.triplet_store import TripletManager
-from semantica.semantic_extract.triple_extractor import Triple
+from semantica.semantic_extract.triplet_extractor import Triplet
manager = TripletManager()
manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
-# Update triple (delete old, add new)
-old_triple = Triple(
+# Update triplet (delete old, add new)
+old_triplet = Triplet(
subject="http://example.org/entity1",
predicate="http://example.org/hasAge",
object="30"
)
-new_triple = Triple(
+new_triplet = Triplet(
subject="http://example.org/entity1",
predicate="http://example.org/hasAge",
object="31"
)
-result = manager.update_triple(old_triple, new_triple, store_id="main")
+result = manager.update_triplet(old_triplet, new_triplet, store_id="main")
print(f"Updated: {result['success']}")
```
@@ -428,7 +428,7 @@ print(f"Cache size: {stats['cache_size']}")
```python
from semantica.triplet_store import BulkLoader, BlazegraphAdapter
-from semantica.semantic_extract.triple_extractor import Triple
+from semantica.semantic_extract.triplet_extractor import Triplet
# Create bulk loader
loader = BulkLoader(batch_size=1000, max_retries=3)
@@ -436,27 +436,27 @@ loader = BulkLoader(batch_size=1000, max_retries=3)
# Create adapter
adapter = BlazegraphAdapter(endpoint="http://localhost:9999/blazegraph")
-# Generate triples
-triples = [
- Triple(f"http://example.org/entity{i}", "http://example.org/hasName", f"Entity {i}")
+# Generate triplets
+triplets = [
+ Triplet(f"http://example.org/entity{i}", "http://example.org/hasName", f"Entity {i}")
for i in range(10000)
]
-# Load triples
-progress = loader.load_triples(triples, adapter)
+# Load triplets
+progress = loader.load_triplets(triplets, adapter)
-print(f"Loaded: {progress.loaded_triples}/{progress.total_triples}")
-print(f"Failed: {progress.failed_triples}")
+print(f"Loaded: {progress.loaded_triplets}/{progress.total_triplets}")
+print(f"Failed: {progress.failed_triplets}")
print(f"Progress: {progress.progress_percentage:.1f}%")
print(f"Elapsed time: {progress.elapsed_time:.2f}s")
-print(f"Throughput: {progress.metadata.get('throughput', 0):.0f} triples/sec")
+print(f"Throughput: {progress.metadata.get('throughput', 0):.0f} triplets/sec")
```
### Progress Tracking
```python
from semantica.triplet_store import BulkLoader, BlazegraphAdapter, LoadProgress
-from semantica.semantic_extract.triple_extractor import Triple
+from semantica.semantic_extract.triplet_extractor import Triplet
loader = BulkLoader(batch_size=1000)
adapter = BlazegraphAdapter(endpoint="http://localhost:9999/blazegraph")
@@ -465,56 +465,56 @@ adapter = BlazegraphAdapter(endpoint="http://localhost:9999/blazegraph")
def progress_callback(progress: LoadProgress):
print(f"Batch {progress.current_batch}/{progress.total_batches}: "
f"{progress.progress_percentage:.1f}% "
- f"({progress.loaded_triples}/{progress.total_triples})")
+ f"({progress.loaded_triplets}/{progress.total_triplets})")
# Load with progress callback
-triples = [Triple(f"http://example.org/entity{i}", "http://example.org/hasName", f"Entity {i}")
+triplets = [Triplet(f"http://example.org/entity{i}", "http://example.org/hasName", f"Entity {i}")
for i in range(5000)]
-progress = loader.load_triples(triples, adapter, progress_callback=progress_callback)
+progress = loader.load_triplets(triplets, adapter, progress_callback=progress_callback)
```
### Pre-load Validation
```python
from semantica.triplet_store import BulkLoader
-from semantica.semantic_extract.triple_extractor import Triple
+from semantica.semantic_extract.triplet_extractor import Triplet
loader = BulkLoader()
-# Create triples (some invalid)
-triples = [
- Triple("http://example.org/entity1", "http://example.org/hasName", "John"), # Valid
- Triple("", "http://example.org/hasName", "Jane"), # Invalid (empty subject)
- Triple("http://example.org/entity3", "", "Bob"), # Invalid (empty predicate)
- Triple("http://example.org/entity4", "http://example.org/hasAge", "30"), # Valid
+# Create triplets (some invalid)
+triplets = [
+ Triplet("http://example.org/entity1", "http://example.org/hasName", "John"), # Valid
+ Triplet("", "http://example.org/hasName", "Jane"), # Invalid (empty subject)
+ Triplet("http://example.org/entity3", "", "Bob"), # Invalid (empty predicate)
+ Triplet("http://example.org/entity4", "http://example.org/hasAge", "30"), # Valid
]
# Validate before loading
-validation = loader.validate_before_load(triples)
+validation = loader.validate_before_load(triplets)
print(f"Valid: {validation['valid']}")
print(f"Errors: {validation['errors']}")
print(f"Warnings: {validation['warnings']}")
-print(f"Valid triples: {validation['valid_triples']}/{validation['total_triples']}")
+print(f"Valid triplets: {validation['valid_triplets']}/{validation['total_triplets']}")
```
### Stream-based Loading
```python
from semantica.triplet_store import BulkLoader, BlazegraphAdapter
-from semantica.semantic_extract.triple_extractor import Triple
+from semantica.semantic_extract.triplet_extractor import Triplet
loader = BulkLoader(batch_size=1000)
adapter = BlazegraphAdapter(endpoint="http://localhost:9999/blazegraph")
-# Create stream of triples
-def triple_stream():
+# Create stream of triplets
+def triplet_stream():
for i in range(10000):
- yield Triple(f"http://example.org/entity{i}", "http://example.org/hasName", f"Entity {i}")
+ yield Triplet(f"http://example.org/entity{i}", "http://example.org/hasName", f"Entity {i}")
# Load from stream
-progress = loader.load_from_stream(triple_stream(), adapter)
-print(f"Loaded {progress.loaded_triples} triples from stream")
+progress = loader.load_from_stream(triplet_stream(), adapter)
+print(f"Loaded {progress.loaded_triplets} triplets from stream")
```
## Store Adapters
@@ -523,7 +523,7 @@ print(f"Loaded {progress.loaded_triples} triples from stream")
```python
from semantica.triplet_store import BlazegraphAdapter
-from semantica.semantic_extract.triple_extractor import Triple
+from semantica.semantic_extract.triplet_extractor import Triplet
# Create Blazegraph adapter
adapter = BlazegraphAdapter(
@@ -532,11 +532,11 @@ adapter = BlazegraphAdapter(
auth=("user", "password") # Optional
)
-# Add triples
-triples = [
- Triple("http://example.org/entity1", "http://example.org/hasName", "John")
+# Add triplets
+triplets = [
+ Triplet("http://example.org/entity1", "http://example.org/hasName", "John")
]
-result = adapter.add_triples(triples)
+result = adapter.add_triplets(triplets)
print(f"Added: {result['success']}")
# Execute SPARQL query
@@ -549,7 +549,7 @@ print(f"Found {len(result['bindings'])} results")
```python
from semantica.triplet_store import JenaAdapter
-from semantica.semantic_extract.triple_extractor import Triple
+from semantica.semantic_extract.triplet_extractor import Triplet
# Create Jena adapter (in-memory)
adapter = JenaAdapter()
@@ -561,11 +561,11 @@ adapter = JenaAdapter(
enable_inference=True
)
-# Add triples
-triples = [
- Triple("http://example.org/entity1", "http://example.org/hasName", "John")
+## Add triplets
+triplets = [
+ Triplet("http://example.org/entity1", "http://example.org/hasName", "John")
]
-result = adapter.add_triples(triples)
+result = adapter.add_triplets(triplets)
# Serialize to Turtle
turtle = adapter.serialize(format="turtle")
@@ -576,7 +576,7 @@ print(turtle)
```python
from semantica.triplet_store import RDF4JAdapter
-from semantica.semantic_extract.triple_extractor import Triple
+from semantica.semantic_extract.triplet_extractor import Triplet
# Create RDF4J adapter
adapter = RDF4JAdapter(
@@ -584,18 +584,18 @@ adapter = RDF4JAdapter(
repository="test"
)
-# Add triples
-triples = [
- Triple("http://example.org/entity1", "http://example.org/hasName", "John")
+## Add triplets
+triplets = [
+ Triplet("http://example.org/entity1", "http://example.org/hasName", "John")
]
-result = adapter.add_triples(triples)
+result = adapter.add_triplets(triplets)
```
### Virtuoso Adapter
```python
from semantica.triplet_store import VirtuosoAdapter
-from semantica.semantic_extract.triple_extractor import Triple
+from semantica.semantic_extract.triplet_extractor import Triplet
# Create Virtuoso adapter
adapter = VirtuosoAdapter(
@@ -604,11 +604,11 @@ adapter = VirtuosoAdapter(
password="dba"
)
-# Add triples
-triples = [
- Triple("http://example.org/entity1", "http://example.org/hasName", "John")
+## Add triplets
+triplets = [
+ Triplet("http://example.org/entity1", "http://example.org/hasName", "John")
]
-result = adapter.add_triples(triples)
+result = adapter.add_triplets(triplets)
```
## Algorithms and Methods
@@ -634,7 +634,7 @@ store = manager.register_store("main", "blazegraph", "http://localhost:9999/blaz
#### Adapter Pattern
**Algorithm**: Unified interface for multiple backends
-1. **Interface Definition**: Common interface for all adapters (add_triple, execute_sparql, etc.)
+1. **Interface Definition**: Common interface for all adapters (add_triplet, execute_sparql, etc.)
2. **Backend-Specific Implementation**: Each adapter implements interface for its backend
3. **Adapter Instantiation**: Create adapter instance on-demand
4. **Operation Delegation**: Delegate operations to appropriate adapter
@@ -644,37 +644,37 @@ store = manager.register_store("main", "blazegraph", "http://localhost:9999/blaz
### CRUD Operations Algorithms
-#### Triple Addition
-**Algorithm**: Single and batch triple insertion
+#### Triplet Addition
+**Algorithm**: Single and batch triplet insertion
-1. **Triple Validation**: Check required fields (subject, predicate, object), validate confidence (0-1)
+1. **Triplet Validation**: Check required fields (subject, predicate, object), validate confidence (0-1)
2. **Adapter Selection**: Get adapter for specified store
-3. **Operation Delegation**: Delegate to adapter's add_triple/add_triples method
+3. **Operation Delegation**: Delegate to adapter's add_triplet/add_triplets method
4. **Result Processing**: Process and return operation result
-**Time Complexity**: O(1) for single, O(n) for batch where n = triples
+**Time Complexity**: O(1) for single, O(n) for batch where n = triplets
**Space Complexity**: O(1) for single, O(n) for batch
```python
-# Triple addition
-result = manager.add_triple(triple, store_id="main")
-result = manager.add_triples(triples, store_id="main", batch_size=1000)
+# Triplet addition
+result = manager.add_triplet(triplet, store_id="main")
+result = manager.add_triplets(triplets, store_id="main", batch_size=1000)
```
-#### Triple Retrieval
-**Algorithm**: Pattern-based triple retrieval
+#### Triplet Retrieval
+**Algorithm**: Pattern-based triplet retrieval
1. **Pattern Construction**: Build SPARQL query from subject/predicate/object patterns
2. **Query Execution**: Execute SPARQL query via adapter
3. **Result Binding Extraction**: Extract bindings from query result
-4. **Triple Reconstruction**: Convert bindings to Triple objects
+4. **Triplet Reconstruction**: Convert bindings to Triplet objects
**Time Complexity**: O(n) where n = result count
**Space Complexity**: O(n) for results
```python
-# Triple retrieval
-triples = manager.get_triple(subject="http://example.org/entity1", store_id="main")
+# Triplet retrieval
+triplets = manager.get_triplets(subject="http://example.org/entity1", store_id="main")
```
### Bulk Loading Algorithms
@@ -682,26 +682,26 @@ triples = manager.get_triple(subject="http://example.org/entity1", store_id="mai
#### Batch Processing
**Algorithm**: Chunking algorithm for large datasets
-1. **Batch Creation**: Divide triples into fixed-size batches
+1. **Batch Creation**: Divide triplets into fixed-size batches
2. **Batch Processing**: Process each batch sequentially
3. **Progress Tracking**: Track loaded count, failed count, progress percentage
4. **Error Handling**: Retry failed batches with exponential backoff
-**Time Complexity**: O(n) where n = total triples
+**Time Complexity**: O(n) where n = total triplets
**Space Complexity**: O(b) where b = batch size
```python
# Batch processing
-progress = loader.load_triples(triples, adapter, batch_size=1000)
+progress = loader.load_triplets(triplets, adapter, batch_size=1000)
```
#### Progress Tracking
**Algorithm**: Load progress calculation
-1. **Progress Calculation**: loaded_triples / total_triples * 100
+1. **Progress Calculation**: loaded_triplets / total_triplets * 100
2. **Elapsed Time Tracking**: Track time since start
3. **Estimated Remaining**: (elapsed / loaded) * (total - loaded)
-4. **Throughput Calculation**: loaded_triples / elapsed_time
+4. **Throughput Calculation**: loaded_triplets / elapsed_time
**Time Complexity**: O(1) per update
**Space Complexity**: O(1)
@@ -786,11 +786,11 @@ cost = engine._estimate_query_cost(query)
#### TripletManager Methods
- `register_store(store_id, store_type, endpoint, **config)`: Register triplet store
-- `add_triple(triple, store_id, **options)`: Add single triple
+- `add_triplet(triple, store_id, **options)`: Add single triple
- `add_triples(triples, store_id, **options)`: Add multiple triples
-- `get_triple(subject, predicate, object, store_id, **options)`: Get triples matching pattern
-- `delete_triple(triple, store_id, **options)`: Delete triple
-- `update_triple(old_triple, new_triple, store_id, **options)`: Update triple
+- `get_triplets(subject, predicate, object, store_id, **options)`: Get triplets matching pattern
+- `delete_triplet(triple, store_id, **options)`: Delete triple
+- `update_triplet(old_triple, new_triple, store_id, **options)`: Update triple
- `get_store(store_id)`: Get store by ID
- `list_stores()`: List all store IDs
@@ -804,23 +804,23 @@ cost = engine._estimate_query_cost(query)
#### BulkLoader Methods
-- `load_triples(triples, store_adapter, **options)`: Load triples in bulk
-- `load_from_file(file_path, store_adapter, **options)`: Load triples from file
-- `load_from_stream(triples_stream, store_adapter, **options)`: Load triples from stream
-- `validate_before_load(triples, **options)`: Validate triples before loading
+- `load_triples(triples, store_adapter, **options)`: Load triplets in bulk
+- `load_from_file(file_path, store_adapter, **options)`: Load triplets from file
+- `load_from_stream(triples_stream, store_adapter, **options)`: Load triplets from stream
+- `validate_before_load(triples, **options)`: Validate triplets before loading
#### Convenience Functions
- `register_store(store_id, store_type, endpoint, method, **options)`: Register store wrapper
-- `add_triple(triple, store_id, method, **options)`: Add triple wrapper
-- `add_triples(triples, store_id, method, **options)`: Add triples wrapper
-- `get_triples(subject, predicate, object, store_id, method, **options)`: Get triples wrapper
-- `delete_triple(triple, store_id, method, **options)`: Delete triple wrapper
-- `update_triple(old_triple, new_triple, store_id, method, **options)`: Update triple wrapper
+- `add_triplet(triple, store_id, method, **options)`: Add triplet wrapper
+- `add_triples(triples, store_id, method, **options)`: Add triplets wrapper
+- `get_triples(subject, predicate, object, store_id, method, **options)`: Get triplets wrapper
+- `delete_triplet(triple, store_id, method, **options)`: Delete triplet wrapper
+- `update_triplet(old_triple, new_triple, store_id, method, **options)`: Update triplet wrapper
- `execute_query(query, store_adapter, method, **options)`: Execute query wrapper
- `optimize_query(query, method, **options)`: Optimize query wrapper
- `bulk_load(triples, store_adapter, method, **options)`: Bulk load wrapper
-- `validate_triples(triples, method, **options)`: Validate triples wrapper
+- `validate_triples(triples, method, **options)`: Validate triplets wrapper
## Dataclasses
@@ -967,14 +967,14 @@ from semantica.triplet_store import (
add_triples,
execute_query
)
-from semantica.semantic_extract.triple_extractor import Triple
+from semantica.semantic_extract.triplet_extractor import Triplet
# 1. Register store
store = register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
# 2. Generate and add triples
-triples = [
- Triple(f"http://example.org/entity{i}", "http://example.org/hasName", f"Entity {i}")
+triplets = [
+ Triplet(f"http://example.org/entity{i}", "http://example.org/hasName", f"Entity {i}")
for i in range(1000)
]
result = add_triples(triples, store_id="main", batch_size=100)
@@ -993,7 +993,7 @@ print(f"Query returned {len(query_result.bindings)} results")
```python
from semantica.triplet_store import TripletManager
-from semantica.semantic_extract.triple_extractor import Triple
+from semantica.semantic_extract.triplet_extractor import Triplet
manager = TripletManager()
@@ -1002,11 +1002,11 @@ manager.register_store("primary", "blazegraph", "http://localhost:9999/blazegrap
manager.register_store("backup", "jena", "http://localhost:3030/ds")
# Add to primary store
-triple = Triple("http://example.org/entity1", "http://example.org/hasName", "John")
-manager.add_triple(triple, store_id="primary")
+triplet = Triplet("http://example.org/entity1", "http://example.org/hasName", "John")
+manager.add_triplet(triple, store_id="primary")
# Replicate to backup store
-manager.add_triple(triple, store_id="backup")
+manager.add_triplet(triple, store_id="backup")
```
### Query Optimization Workflow
@@ -1041,14 +1041,14 @@ print(f"Optimized: {result.metadata.get('optimized', False)}")
```python
from semantica.triplet_store import BulkLoader, BlazegraphAdapter
-from semantica.semantic_extract.triple_extractor import Triple
+from semantica.semantic_extract.triplet_extractor import Triplet
loader = BulkLoader(batch_size=1000, max_retries=3)
adapter = BlazegraphAdapter(endpoint="http://localhost:9999/blazegraph")
# Generate triples
-triples = [
- Triple(f"http://example.org/entity{i}", "http://example.org/hasName", f"Entity {i}")
+triplets = [
+ Triplet(f"http://example.org/entity{i}", "http://example.org/hasName", f"Entity {i}")
for i in range(10000)
]
@@ -1070,19 +1070,19 @@ from semantica.triplet_store.registry import method_registry
from semantica.triplet_store import add_triple
# Register custom add method
-def custom_add_triple(triple, store_id=None, **options):
+def custom_add_triplet(triple, store_id=None, **options):
# Custom logic
- print(f"Custom add: {triple.subject}")
+ print(f"Custom add: {triplet.subject}")
# Call default implementation
from semantica.triplet_store.methods import _get_manager
manager = _get_manager()
- return manager.add_triple(triple, store_id=store_id, **options)
+ return manager.add_triplet(triple, store_id=store_id, **options)
method_registry.register("add", "custom", custom_add_triple)
# Use custom method
from semantica.triplet_store.methods import add_triple
-result = add_triple(triple, store_id="main", method="custom")
+result = add_triplet(triple, store_id="main", method="custom")
```
## Best Practices
@@ -1093,8 +1093,8 @@ result = add_triple(triple, store_id="main", method="custom")
- Set appropriate default store
- Configure store-specific options
-2. **Triple Operations**:
- - Validate triples before adding
+2. **Triplet Operations**:
+ - Validate triplets before adding
- Use batch operations for multiple triples
- Set appropriate batch sizes
- Handle errors gracefully
@@ -1106,7 +1106,7 @@ result = add_triple(triple, store_id="main", method="custom")
- Use appropriate LIMIT clauses
4. **Bulk Loading**:
- - Validate triples before loading
+ - Validate triplets before loading
- Use appropriate batch sizes
- Monitor progress for large loads
- Handle retries appropriately
@@ -1118,7 +1118,7 @@ result = add_triple(triple, store_id="main", method="custom")
- Monitor query statistics
6. **Error Handling**:
- - Validate triples before operations
+ - Validate triplets before operations
- Handle adapter errors gracefully
- Use retry mechanisms for bulk operations
- Log errors for debugging
diff --git a/semantica/triplet_store/virtuoso_adapter.py b/semantica/triplet_store/virtuoso_adapter.py
index 0498f5fa..145ff8ba 100644
--- a/semantica/triplet_store/virtuoso_adapter.py
+++ b/semantica/triplet_store/virtuoso_adapter.py
@@ -19,7 +19,7 @@ Example Usage:
>>> from semantica.triplet_store import VirtuosoAdapter
>>> adapter = VirtuosoAdapter(endpoint="http://localhost:8890/sparql", username="dba", password="dba")
>>> result = adapter.execute_sparql(sparql_query)
- >>> load_result = adapter.bulk_load(triples, graph="http://example.org/graph")
+ >>> load_result = adapter.bulk_load(triplets, graph="http://example.org/graph")
>>> cluster_status = adapter.connect_cluster(cluster_config)
Author: Semantica Contributors
@@ -31,9 +31,10 @@ from urllib.parse import urljoin
import requests
-from ..semantic_extract.triple_extractor import Triple
+from ..semantic_extract.triplet_extractor import Triplet
from ..utils.exceptions import ProcessingError, ValidationError
from ..utils.logging import get_logger
+from ..utils.progress_tracker import get_progress_tracker
class VirtuosoAdapter:
@@ -226,12 +227,12 @@ class VirtuosoAdapter:
return optimized
- def bulk_load(self, triples: List[Triple], **options) -> Dict[str, Any]:
+ def bulk_load(self, triplets: List[Triplet], **options) -> Dict[str, Any]:
"""
- Load triples in bulk.
+ Load triplets in bulk.
Args:
- triples: List of triples
+ triplets: List of triplets
**options: Additional options:
- graph: Named graph URI
- format: RDF format (turtle, ntriples)
@@ -242,7 +243,7 @@ class VirtuosoAdapter:
tracking_id = self.progress_tracker.start_tracking(
module="triplet_store",
submodule="VirtuosoAdapter",
- message=f"Bulk loading {len(triples)} triples to Virtuoso",
+ message=f"Bulk loading {len(triplets)} triplets to Virtuoso",
)
try:
@@ -255,17 +256,17 @@ class VirtuosoAdapter:
graph = options.get("graph", self.default_graph)
format = options.get("format", "turtle")
- # Convert triples to RDF
+ # Convert triplets to RDF
self.progress_tracker.update_tracking(
- tracking_id, message="Converting triples to RDF format..."
+ tracking_id, message="Converting triplets to RDF format..."
)
- rdf_data = self._triples_to_rdf(triples, format)
+ rdf_data = self._triplets_to_rdf(triplets, format)
# Use SPARQL INSERT for bulk loading
update_endpoint = self._get_sparql_update_endpoint()
graph_clause = f"GRAPH <{graph}>" if graph else ""
- insert_data = self._build_insert_data(triples)
+ insert_data = self._build_insert_data(triplets)
query = f"INSERT DATA {graph_clause} {{ {insert_data} }}"
self.progress_tracker.update_tracking(
@@ -284,9 +285,9 @@ class VirtuosoAdapter:
self.progress_tracker.stop_tracking(
tracking_id,
status="completed",
- message=f"Bulk loaded {len(triples)} triples",
+ message=f"Bulk loaded {len(triplets)} triplets",
)
- return {"success": True, "triples_loaded": len(triples), "graph": graph}
+ return {"success": True, "triplets_loaded": len(triplets), "graph": graph}
except Exception as e:
self.logger.error(f"Bulk load failed: {e}")
self.progress_tracker.stop_tracking(
@@ -294,46 +295,46 @@ class VirtuosoAdapter:
)
raise ProcessingError(f"Bulk load failed: {e}")
- def _triples_to_rdf(self, triples: List[Triple], format: str = "turtle") -> str:
- """Convert triples to RDF format."""
+ def _triplets_to_rdf(self, triplets: List[Triplet], format: str = "turtle") -> str:
+ """Convert triplets to RDF format."""
if format == "turtle":
lines = []
- for triple in triples:
+ for triplet in triplets:
lines.append(
- f"<{triple.subject}> <{triple.predicate}> <{triple.object}> ."
+ f"<{triplet.subject}> <{triplet.predicate}> <{triplet.object}> ."
)
return "\n".join(lines)
else: # ntriples
lines = []
- for triple in triples:
+ for triplet in triplets:
lines.append(
- f"<{triple.subject}> <{triple.predicate}> <{triple.object}> ."
+ f"<{triplet.subject}> <{triplet.predicate}> <{triplet.object}> ."
)
return "\n".join(lines)
- def _build_insert_data(self, triples: List[Triple]) -> str:
+ def _build_insert_data(self, triplets: List[Triplet]) -> str:
"""Build SPARQL INSERT DATA clause."""
lines = []
- for triple in triples:
- lines.append(f"<{triple.subject}> <{triple.predicate}> <{triple.object}> .")
+ for triplet in triplets:
+ lines.append(f"<{triplet.subject}> <{triplet.predicate}> <{triplet.object}> .")
return " ".join(lines)
- def add_triple(self, triple: Triple, **options) -> Dict[str, Any]:
- """Add single triple."""
- return self.bulk_load([triple], **options)
+ def add_triplet(self, triplet: Triplet, **options) -> Dict[str, Any]:
+ """Add single triplet."""
+ return self.bulk_load([triplet], **options)
- def add_triples(self, triples: List[Triple], **options) -> Dict[str, Any]:
- """Add multiple triples."""
- return self.bulk_load(triples, **options)
+ def add_triplets(self, triplets: List[Triplet], **options) -> Dict[str, Any]:
+ """Add multiple triplets."""
+ return self.bulk_load(triplets, **options)
- def get_triples(
+ def get_triplets(
self,
subject: Optional[str] = None,
predicate: Optional[str] = None,
object: Optional[str] = None,
**options,
- ) -> List[Triple]:
- """Get triples matching criteria."""
+ ) -> List[Triplet]:
+ """Get triplets matching criteria."""
# Build SPARQL query
where_clauses = []
if subject:
@@ -348,11 +349,11 @@ class VirtuosoAdapter:
result = self.execute_sparql(query, **options)
- # Convert bindings to triples
- triples = []
+ # Convert bindings to triplets
+ triplets = []
for binding in result["bindings"]:
- triples.append(
- Triple(
+ triplets.append(
+ Triplet(
subject=binding.get("s", {}).get("value", ""),
predicate=binding.get("p", {}).get("value", ""),
object=binding.get("o", {}).get("value", ""),
@@ -360,16 +361,16 @@ class VirtuosoAdapter:
)
)
- return triples
+ return triplets
- def delete_triple(self, triple: Triple, **options) -> Dict[str, Any]:
- """Delete triple."""
+ def delete_triplet(self, triplet: Triplet, **options) -> Dict[str, Any]:
+ """Delete triplet."""
if not self.connected:
raise ProcessingError("Not connected to Virtuoso")
update_endpoint = self._get_sparql_update_endpoint()
- query = f"DELETE DATA {{ <{triple.subject}> <{triple.predicate}> <{triple.object}> }}"
+ query = f"DELETE DATA {{ <{triplet.subject}> <{triplet.predicate}> <{triplet.object}> }}"
try:
response = requests.post(
@@ -384,5 +385,5 @@ class VirtuosoAdapter:
return {"success": True}
except Exception as e:
- self.logger.error(f"Delete triple failed: {e}")
- raise ProcessingError(f"Delete triple failed: {e}")
+ self.logger.error(f"Delete triplet failed: {e}")
+ raise ProcessingError(f"Delete triplet failed: {e}")
diff --git a/tests/cookbook/test_disease_network_analysis.py b/tests/cookbook/test_disease_network_analysis.py
index 4490d8f9..665689d3 100644
--- a/tests/cookbook/test_disease_network_analysis.py
+++ b/tests/cookbook/test_disease_network_analysis.py
@@ -10,7 +10,7 @@ from unittest.mock import MagicMock, patch
try:
from semantica.ingest import FileIngestor, WebIngestor, DBIngestor, FeedIngestor
from semantica.parse import DocumentParser, PDFParser, StructuredDataParser, JSONParser
- from semantica.semantic_extract import NERExtractor, RelationExtractor, TripleExtractor, SemanticAnalyzer
+ from semantica.semantic_extract import NERExtractor, RelationExtractor, TripletExtractor, SemanticAnalyzer
from semantica.kg import GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector
from semantica.kg import ConnectivityAnalyzer, TemporalGraphQuery, TemporalPatternDetector
from semantica.ontology import OntologyGenerator, ClassInferrer, PropertyGenerator, OntologyValidator
diff --git a/tests/semantic_extract/test_extractors.py b/tests/semantic_extract/test_extractors.py
index 2fbb90ef..6258394e 100644
--- a/tests/semantic_extract/test_extractors.py
+++ b/tests/semantic_extract/test_extractors.py
@@ -8,7 +8,7 @@ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../.
from semantica.semantic_extract.ner_extractor import NERExtractor
from semantica.semantic_extract.relation_extractor import RelationExtractor
-from semantica.semantic_extract.triple_extractor import TripleExtractor
+from semantica.semantic_extract.triplet_extractor import TripletExtractor
from semantica.semantic_extract.named_entity_recognizer import Entity
from semantica.semantic_extract.relation_extractor import Relation
@@ -30,13 +30,13 @@ class TestExtractors(unittest.TestCase):
except ImportError as e:
self.fail(f"RelationExtractor initialization failed with ImportError: {e}")
- def test_triple_extractor_initialization(self):
- """Test TripleExtractor initialization and circular import resolution"""
+ def test_triplet_extractor_initialization(self):
+ """Test TripletExtractor initialization and circular import resolution"""
try:
- extractor = TripleExtractor(method="pattern")
+ extractor = TripletExtractor(method="pattern")
self.assertIsNotNone(extractor)
except ImportError as e:
- self.fail(f"TripleExtractor initialization failed with ImportError: {e}")
+ self.fail(f"TripletExtractor initialization failed with ImportError: {e}")
@patch("semantica.semantic_extract.methods.get_entity_method")
def test_ner_extraction(self, mock_get_method):
@@ -65,20 +65,20 @@ class TestExtractors(unittest.TestCase):
self.assertIsInstance(relations, list)
mock_get_method.assert_called()
- @patch("semantica.semantic_extract.methods.get_triple_method")
- def test_triple_extraction(self, mock_get_method):
- """Test triple extraction call"""
+ @patch("semantica.semantic_extract.methods.get_triplet_method")
+ def test_triplet_extraction(self, mock_get_method):
+ """Test triplet extraction call"""
mock_method = MagicMock()
- mock_method.extract_triples.return_value = []
+ mock_method.extract_triplets.return_value = []
mock_get_method.return_value = mock_method
- extractor = TripleExtractor(method="pattern")
+ extractor = TripletExtractor(method="pattern")
entities = [Entity(text="A", label="PERSON", start_char=0, end_char=1)]
relations = [Relation(subject=entities[0], object=entities[0], predicate="knows")]
- triples = extractor.extract_triples("A knows A", entities, relations)
+ triplets = extractor.extract_triplets("A knows A", entities, relations)
- self.assertIsInstance(triples, list)
+ self.assertIsInstance(triplets, list)
mock_get_method.assert_called()
if __name__ == "__main__":
diff --git a/tests/test_notebooks_verification.py b/tests/test_notebooks_verification.py
index 0f0d8257..f03618bb 100644
--- a/tests/test_notebooks_verification.py
+++ b/tests/test_notebooks_verification.py
@@ -11,7 +11,7 @@ from semantica.semantic_extract import (
NERExtractor,
NamedEntityRecognizer,
RelationExtractor,
- TripleExtractor,
+ TripletExtractor,
Entity,
Relation
)
diff --git a/tests/test_semantic_extract_deepdive.py b/tests/test_semantic_extract_deepdive.py
index c31d0f1e..932443d4 100644
--- a/tests/test_semantic_extract_deepdive.py
+++ b/tests/test_semantic_extract_deepdive.py
@@ -15,12 +15,12 @@ from semantica.semantic_extract.named_entity_recognizer import (
CustomEntityDetector
)
from semantica.semantic_extract.relation_extractor import RelationExtractor, Relation
-from semantica.semantic_extract.triple_extractor import (
- TripleExtractor,
- TripleValidator,
- TripleQualityChecker,
+from semantica.semantic_extract.triplet_extractor import (
+ TripletExtractor,
+ TripletValidator,
+ TripletQualityChecker,
RDFSerializer,
- Triple
+ Triplet
)
from semantica.semantic_extract.methods import get_entity_method, get_relation_method
@@ -145,77 +145,77 @@ class TestSemanticExtractDeepDive(unittest.TestCase):
self.assertTrue(len(relations) > 0)
self.assertEqual(relations[0].predicate, "related_to")
- # --- Triple Tests ---
+ # --- Triplet 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 test_triplet_extractor(self):
+ """Test TripletExtractor"""
+ # Mocking get_triplet_method to return a simple extraction function
+ with patch('semantica.semantic_extract.methods.get_triplet_method') as mock_get:
def mock_extract(text, entities, relations, **kwargs):
- triples = []
+ triplets = []
for rel in relations:
- triples.append(Triple(
+ triplets.append(Triplet(
subject=rel.subject.text,
predicate=rel.predicate,
object=rel.object.text,
confidence=rel.confidence
))
- return triples
+ return triplets
mock_get.return_value = mock_extract
- extractor = TripleExtractor()
- triples = extractor.extract_triples(self.text, self.entities, self.relations)
+ extractor = TripletExtractor()
+ triplets = extractor.extract_triplets(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")
+ self.assertEqual(len(triplets), 2)
+ self.assertEqual(triplets[0].subject, "Apple Inc.")
+ self.assertEqual(triplets[0].predicate, "founded_by")
+ self.assertEqual(triplets[0].object, "Steve Jobs")
- def test_triple_validator(self):
- """Test TripleValidator"""
- validator = TripleValidator()
+ def test_triplet_validator(self):
+ """Test TripletValidator"""
+ validator = TripletValidator()
- # 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)
+ # Create a valid and invalid triplet
+ valid_triplet = Triplet(subject="S", predicate="P", object="O", confidence=0.9)
+ invalid_triplet = Triplet(subject="", predicate="P", object="O", confidence=0.9) # Empty subject
+ low_conf_triplet = Triplet(subject="S", predicate="P", object="O", confidence=0.2)
- triples = [valid_triple, invalid_triple, low_conf_triple]
+ triplets = [valid_triplet, invalid_triplet, low_conf_triplet]
- validated = validator.validate_triples(triples, min_confidence=0.5)
+ validated = validator.validate_triplets(triplets, min_confidence=0.5)
self.assertEqual(len(validated), 1)
- self.assertEqual(validated[0], valid_triple)
+ self.assertEqual(validated[0], valid_triplet)
def test_rdf_serializer(self):
"""Test RDFSerializer"""
serializer = RDFSerializer()
- triple = Triple(subject="Apple_Inc", predicate="founded_by", object="Steve_Jobs")
+ triplet = Triplet(subject="Apple_Inc", predicate="founded_by", object="Steve_Jobs")
# Test N-Triples format
- rdf_output = serializer.serialize_to_rdf([triple], format="ntriples")
+ rdf_output = serializer.serialize_to_rdf([triplet], 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)
+ def test_triplet_quality_checker(self):
+ """Test TripletQualityChecker"""
+ checker = TripletQualityChecker()
+ triplets = [
+ Triplet(subject="Apple", predicate="founded", object="Jobs", confidence=0.9),
+ Triplet(subject="Apple", predicate="located", object="US", confidence=0.8)
]
- scores = checker.calculate_quality_scores(triples)
+ scores = checker.calculate_quality_scores(triplets)
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)
+ # triplet_count is not returned by calculate_quality_scores
+ # self.assertIn("triplet_count", scores)
+ # self.assertEqual(scores["triplet_count"], 2)
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_semantic_extract_deepdive_part2.py b/tests/test_semantic_extract_deepdive_part2.py
index a37eabdc..5e96c305 100644
--- a/tests/test_semantic_extract_deepdive_part2.py
+++ b/tests/test_semantic_extract_deepdive_part2.py
@@ -13,13 +13,13 @@ from semantica.semantic_extract.named_entity_recognizer import (
)
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.triplet_extractor import TripletExtractor, Triplet
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
+ extract_triplets_rules
)
pytestmark = pytest.mark.integration
@@ -151,19 +151,19 @@ class TestSemanticExtractDeepDivePart2(unittest.TestCase):
extract_relations_dependency("text", [])
mock_pattern.assert_called_once()
- def test_extract_triples_rules(self):
- """Test rule-based triple extraction"""
+ def test_extract_triplets_rules(self):
+ """Test rule-based triplet 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")
+ triplets = extract_triplets_rules(text, entities)
+ self.assertTrue(len(triplets) > 0)
+ self.assertEqual(triplets[0].predicate, "founded")
+ self.assertEqual(triplets[0].subject, "Steve")
+ self.assertEqual(triplets[0].object, "Apple")
# --- Event Detector Tests ---
diff --git a/tests/test_semantic_extract_triples.py b/tests/test_semantic_extract_triplets.py
similarity index 50%
rename from tests/test_semantic_extract_triples.py
rename to tests/test_semantic_extract_triplets.py
index 815a3e88..3a5a656b 100644
--- a/tests/test_semantic_extract_triples.py
+++ b/tests/test_semantic_extract_triplets.py
@@ -7,13 +7,13 @@ 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.triplet_extractor import (
+ TripletExtractor, Triplet, TripletValidator, RDFSerializer, TripletQualityChecker
)
from semantica.semantic_extract.ner_extractor import Entity
from semantica.semantic_extract.relation_extractor import Relation
-class TestSemanticExtractTriples(unittest.TestCase):
+class TestSemanticExtractTriplets(unittest.TestCase):
def setUp(self):
self.entities = [
@@ -29,66 +29,66 @@ class TestSemanticExtractTriples(unittest.TestCase):
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)
+ self.triplets = [
+ Triplet(subject="Steve_Jobs", predicate="founded", object="Apple", confidence=0.9),
+ Triplet(subject="Apple", predicate="located_in", object="Cupertino", confidence=0.8)
]
- # --- Triple Extractor Tests ---
+ # --- Triplet Extractor Tests ---
- def test_triple_extractor_init(self):
- """Test TripleExtractor initialization"""
- extractor = TripleExtractor()
- self.assertIsNotNone(extractor.triple_validator)
+ def test_triplet_extractor_init(self):
+ """Test TripletExtractor initialization"""
+ extractor = TripletExtractor()
+ self.assertIsNotNone(extractor.triplet_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
+ def test_triplet_extractor_extract_from_relations(self):
+ """Test extracting triplets by converting relations (fallback/default)"""
+ extractor = TripletExtractor(method=[]) # No specific method, force fallback
# Mocking progress tracker to avoid console clutter/errors
extractor.progress_tracker = MagicMock()
- triples = extractor.extract_triples(
+ triplets = extractor.extract_triplets(
text="Steve Jobs founded Apple.",
entities=self.entities,
- relationships=self.relations
+ relations=self.relations
)
- self.assertEqual(len(triples), 1)
+ self.assertEqual(len(triplets), 1)
# Predicate is formatted as URI
- self.assertTrue(triples[0].predicate.endswith("founded") or triples[0].predicate == "founded")
+ self.assertTrue(triplets[0].predicate.endswith("founded") or triplets[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)
+ self.assertIn("Steve_Jobs", triplets[0].subject)
- # --- Triple Validator Tests ---
+ # --- Triplet 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_triplet_validator_valid(self):
+ """Test TripletValidator with valid triplet"""
+ validator = TripletValidator()
+ triplet = Triplet(subject="S", predicate="P", object="O", confidence=0.9)
+ self.assertTrue(validator.validate_triplet(triplet))
- 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_triplet_validator_invalid_structure(self):
+ """Test TripletValidator with missing fields"""
+ validator = TripletValidator()
+ triplet = Triplet(subject="", predicate="P", object="O") # Empty subject
+ self.assertFalse(validator.validate_triplet(triplet))
- 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))
+ def test_triplet_validator_low_confidence(self):
+ """Test TripletValidator confidence threshold"""
+ validator = TripletValidator()
+ triplet = Triplet(subject="S", predicate="P", object="O", confidence=0.4)
+ self.assertFalse(validator.validate_triplet(triplet, 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")
+ output = serializer.serialize_to_rdf(self.triplets, format="turtle")
self.assertIn("@prefix", output)
self.assertIn("Steve_Jobs", output)
self.assertIn("founded", output)
@@ -98,7 +98,7 @@ class TestSemanticExtractTriples(unittest.TestCase):
def test_rdf_serializer_ntriples(self):
"""Test RDF serialization to N-Triples"""
serializer = RDFSerializer()
- output = serializer.serialize_to_rdf(self.triples, format="ntriples")
+ output = serializer.serialize_to_rdf(self.triplets, format="ntriples")
self.assertNotIn("@prefix", output)
self.assertIn("<Steve_Jobs>", output)
self.assertIn("<founded>", output)
@@ -106,7 +106,7 @@ class TestSemanticExtractTriples(unittest.TestCase):
def test_rdf_serializer_jsonld(self):
"""Test RDF serialization to JSON-LD"""
serializer = RDFSerializer()
- output = serializer.serialize_to_rdf(self.triples, format="jsonld")
+ output = serializer.serialize_to_rdf(self.triplets, format="jsonld")
import json
data = json.loads(output)
self.assertIn("@graph", data)
@@ -115,26 +115,26 @@ class TestSemanticExtractTriples(unittest.TestCase):
def test_rdf_serializer_xml(self):
"""Test RDF serialization to XML"""
serializer = RDFSerializer()
- output = serializer.serialize_to_rdf(self.triples, format="xml")
+ output = serializer.serialize_to_rdf(self.triplets, format="xml")
self.assertIn("rdf:RDF", output)
self.assertIn("rdf:Description", output)
- # --- Triple Quality Checker Tests ---
+ # --- Triplet 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)
+ def test_triplet_quality_checker_assess(self):
+ """Test TripletQualityChecker assessment"""
+ checker = TripletQualityChecker()
+ triplet = Triplet(subject="S", predicate="P", object="O", confidence=0.85)
+ assessment = checker.assess_triplet_quality(triplet)
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)
+ def test_triplet_quality_checker_stats(self):
+ """Test TripletQualityChecker statistics"""
+ checker = TripletQualityChecker()
+ stats = checker.calculate_quality_scores(self.triplets)
# Implementation returns average_score, min_score, max_score, high_quality, medium_quality, low_quality
self.assertIn("average_score", stats)
diff --git a/tests/triplet_store/test_triplet_store.py b/tests/triplet_store/test_triplet_store.py
index 05dd6fa5..d4d90f4f 100644
--- a/tests/triplet_store/test_triplet_store.py
+++ b/tests/triplet_store/test_triplet_store.py
@@ -2,7 +2,7 @@ import unittest
from unittest.mock import MagicMock, patch
from semantica.triplet_store.triplet_manager import TripletManager, TripletStore
from semantica.triplet_store.query_engine import QueryEngine, QueryResult
-from semantica.semantic_extract.triple_extractor import Triple
+from semantica.semantic_extract.triplet_extractor import Triplet
class TestTripletStore(unittest.TestCase):
@@ -41,89 +41,89 @@ class TestTripletStore(unittest.TestCase):
self.assertIn("main", manager.stores)
@patch('semantica.triplet_store.triplet_manager.TripletManager._get_adapter')
- def test_add_triple(self, mock_get_adapter):
+ def test_add_triplet(self, mock_get_adapter):
manager = TripletManager()
manager.register_store("main", "blazegraph", "http://localhost:9999")
mock_adapter = MagicMock()
mock_get_adapter.return_value = mock_adapter
- mock_adapter.add_triple.return_value = {"status": "success"}
+ mock_adapter.add_triplet.return_value = {"status": "success"}
- triple = Triple(subject="s", predicate="p", object="o")
- result = manager.add_triple(triple, store_id="main")
+ triplet = Triplet(subject="s", predicate="p", object="o")
+ result = manager.add_triplet(triplet, store_id="main")
self.assertTrue(result["success"])
self.assertEqual(result["store_id"], "main")
- mock_adapter.add_triple.assert_called_once_with(triple)
+ mock_adapter.add_triplet.assert_called_once_with(triplet)
@patch('semantica.triplet_store.triplet_manager.TripletManager._get_adapter')
- def test_add_triples(self, mock_get_adapter):
+ def test_add_triplets(self, mock_get_adapter):
manager = TripletManager()
manager.register_store("main", "blazegraph", "http://localhost:9999")
mock_adapter = MagicMock()
mock_get_adapter.return_value = mock_adapter
- mock_adapter.add_triples.return_value = {"status": "success"}
+ mock_adapter.add_triplets.return_value = {"status": "success"}
- triples = [
- Triple(subject="s1", predicate="p1", object="o1"),
- Triple(subject="s2", predicate="p2", object="o2")
+ triplets = [
+ Triplet(subject="s1", predicate="p1", object="o1"),
+ Triplet(subject="s2", predicate="p2", object="o2")
]
- result = manager.add_triples(triples, store_id="main", batch_size=2)
+ result = manager.add_triplets(triplets, store_id="main", batch_size=2)
self.assertTrue(result["success"])
- self.assertEqual(result["total_triples"], 2)
- mock_adapter.add_triples.assert_called()
+ self.assertEqual(result["store_id"], "main")
+ mock_adapter.add_triplets.assert_called()
@patch('semantica.triplet_store.triplet_manager.TripletManager._get_adapter')
- def test_get_triple(self, mock_get_adapter):
+ def test_get_triplets(self, mock_get_adapter):
manager = TripletManager()
manager.register_store("main", "blazegraph", "http://localhost:9999")
mock_adapter = MagicMock()
mock_get_adapter.return_value = mock_adapter
- expected_triples = [Triple(subject="s", predicate="p", object="o")]
- mock_adapter.get_triples.return_value = expected_triples
+ expected_triplets = [Triplet(subject="s", predicate="p", object="o")]
+ mock_adapter.get_triplets.return_value = expected_triplets
- result = manager.get_triple(subject="s", store_id="main")
+ result = manager.get_triplets(subject="s", store_id="main")
- self.assertEqual(result, expected_triples)
- mock_adapter.get_triples.assert_called_once_with("s", None, None)
+ self.assertEqual(result, expected_triplets)
+ mock_adapter.get_triplets.assert_called_once_with("s", None, None)
@patch('semantica.triplet_store.triplet_manager.TripletManager._get_adapter')
- def test_delete_triple(self, mock_get_adapter):
+ def test_delete_triplet(self, mock_get_adapter):
manager = TripletManager()
manager.register_store("main", "blazegraph", "http://localhost:9999")
mock_adapter = MagicMock()
mock_get_adapter.return_value = mock_adapter
- mock_adapter.delete_triple.return_value = {"status": "deleted"}
+ mock_adapter.delete_triplet.return_value = {"status": "deleted"}
- triple = Triple(subject="s", predicate="p", object="o")
- result = manager.delete_triple(triple, store_id="main")
+ triplet = Triplet(subject="s", predicate="p", object="o")
+ result = manager.delete_triplet(triplet, store_id="main")
self.assertTrue(result["success"])
- mock_adapter.delete_triple.assert_called_once_with(triple)
+ mock_adapter.delete_triplet.assert_called_once_with(triplet)
@patch('semantica.triplet_store.triplet_manager.TripletManager._get_adapter')
- def test_update_triple(self, mock_get_adapter):
+ def test_update_triplet(self, mock_get_adapter):
manager = TripletManager()
manager.register_store("main", "blazegraph", "http://localhost:9999")
mock_adapter = MagicMock()
mock_get_adapter.return_value = mock_adapter
- mock_adapter.delete_triple.return_value = {"status": "deleted"}
- mock_adapter.add_triple.return_value = {"status": "added"}
+ mock_adapter.delete_triplet.return_value = {"status": "deleted"}
+ mock_adapter.add_triplet.return_value = {"status": "added"}
- old_triple = Triple(subject="s", predicate="p", object="o_old")
- new_triple = Triple(subject="s", predicate="p", object="o_new")
+ old_triplet = Triplet(subject="s", predicate="p", object="o_old")
+ new_triplet = Triplet(subject="s", predicate="p", object="o_new")
- result = manager.update_triple(old_triple, new_triple, store_id="main")
+ result = manager.update_triplet(old_triplet, new_triplet, store_id="main")
self.assertTrue(result["success"])
- mock_adapter.delete_triple.assert_called_once_with(old_triple)
- mock_adapter.add_triple.assert_called_once_with(new_triple)
+ mock_adapter.delete_triplet.assert_called_once_with(old_triplet)
+ mock_adapter.add_triplet.assert_called_once_with(new_triplet)
def test_query_engine_init(self):
engine = QueryEngine(enable_caching=True)