Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat(semantic_extract): Update module with explicit parameters and docs

KaifAhmad1f1699c4f8063
diff --git a/docs/LIBS_README.md b/docs/LIBS_README.md
index caa557d0..6f25bf22 100644
--- a/docs/LIBS_README.md
+++ b/docs/LIBS_README.md
@@ -79,45 +79,39 @@ pip install -e ".[dev]"
## 🎯 Quick Start
-> **New User-Friendly API**: Semantica now supports lazy initialization and module-level `build()` functions. No need to call `initialize()` explicitly - the framework auto-initializes on first use. You can use `semantica.build()` or access submodules via dot notation like `semantica.kg.build()`, `semantica.ingest.build()`, etc.
+> **User-Friendly API**: Semantica supports lazy initialization. No need to call `initialize()` explicitly - the framework auto-initializes on first use. Access submodules via dot notation like `semantica.kg`, `semantica.embeddings`, etc.
#### API Usage Patterns
-**Pattern 1: Module-level build (Simplest)**
+**Pattern 1: Using Semantica class (Recommended)**
```python
-from semantica import build
+from semantica import Semantica
-# Build knowledge base - auto-initializes
-result = build(["doc1.pdf", "doc2.docx"], embeddings=True, graph=True)
+# Initialize and build knowledge base
+semantica = Semantica()
+result = semantica.build_knowledge_base(["doc1.pdf", "doc2.docx"], embeddings=True, graph=True)
```
-**Pattern 2: Dot notation access (Recommended for submodules)**
-```python
-import semantica
-
-# Access submodules via dot notation
-kg_result = semantica.kg.build(["doc1.pdf"], merge_entities=True)
-embeddings = semantica.embeddings.build(["text1", "text2"], data_type="text")
-ingested = semantica.ingest.build("documents/", source_type="directory")
-```
-
-**Pattern 3: Direct class usage (Advanced control)**
+**Pattern 2: Direct class usage (Fine-grained control)**
```python
from semantica.kg import GraphBuilder
-from semantica.embeddings import TextEmbedder
+from semantica.embeddings import EmbeddingGenerator
+from semantica.ingest import FileIngestor
-# Use classes directly for fine-grained control
+# Use classes directly
builder = GraphBuilder(merge_entities=True)
-embedder = TextEmbedder(model_name="all-MiniLM-L6-v2")
+generator = EmbeddingGenerator()
+ingestor = FileIngestor()
```
### 1. Basic Document Processing
```python
-from semantica import build
+from semantica import Semantica
# Build knowledge base from documents (auto-initializes)
+semantica = Semantica()
documents = ["document1.pdf", "document2.docx", "document3.txt"]
-result = build(
+result = semantica.build_knowledge_base(
documents,
embeddings=True,
graph=True,
@@ -165,26 +159,21 @@ web_content = web_ingestor.ingest_url(url)
sitemap_url = "https://example.com/sitemap.xml"
pages = web_ingestor.crawl_sitemap(sitemap_url)
-# Build knowledge base from web content using module-level build
+# Build knowledge base from web content
sources = [web_content.url for web_content in pages]
-result = semantica.build(sources)
-
-# Or use ingest module's build function
-result = semantica.ingest.build(sources)
+semantica_instance = Semantica()
+result = semantica_instance.build_knowledge_base(sources)
```
### 3. Knowledge Graph Analytics
```python
-import semantica
+from semantica import Semantica
from semantica.kg import GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector
-# Build knowledge graph using module-level build
+# Build knowledge graph using Semantica class
sources = ["document1.pdf", "document2.pdf"]
-result = semantica.build(sources, graph=True)
-kg_data = result["knowledge_graph"]
-
-# Or use kg module's build function directly
-result = semantica.kg.build(sources, merge_entities=True, resolve_conflicts=True)
+semantica = Semantica()
+result = semantica.build_knowledge_base(sources, graph=True)
kg_data = result["knowledge_graph"]
# Build graph object from extracted entities and relationships
@@ -282,14 +271,16 @@ print(f"Graph connectivity: {connectivity['is_connected']}")
**Option 1: Using module-level build function (Recommended)**
```python
-import semantica
+from semantica.ingest import FileIngestor
+
+# Initialize file ingestor
+ingestor = FileIngestor()
-# Simple approach - ingest files directly
-files = semantica.ingest.build(
+# Ingest directory recursively
+files = ingestor.ingest_directory(
"documents/",
- source_type="directory",
recursive=True,
- extensions=[".pdf", ".docx", ".txt"]
+ file_types=[".pdf", ".docx", ".txt"]
)
for file_obj in files:
@@ -298,7 +289,7 @@ for file_obj in files:
print(f"Size: {file_obj.size} bytes")
```
-**Option 2: Using FileIngestor directly (Advanced)**
+**Option 2: Using FileIngestor for single files**
```python
from semantica.ingest import FileIngestor
from pathlib import Path
@@ -441,13 +432,13 @@ results = db_ingestor.execute_query(
**Option 1: Using module-level build function (Recommended)**
```python
-import semantica
+from semantica.semantic_extract import NamedEntityRecognizer
text = "Apple Inc. is a technology company founded by Steve Jobs in Cupertino, California."
-# Extract entities using module-level function
-result = semantica.semantic_extract.build(text, extract_entities=True)
-entities = result.get("entities", [])
+# Extract entities using NamedEntityRecognizer
+ner = NamedEntityRecognizer()
+entities = ner.extract_entities(text)
for entity in entities:
print(f"Entity: {entity.get('text')}")
@@ -456,7 +447,7 @@ for entity in entities:
print()
```
-**Option 2: Using NERExtractor directly (Advanced)**
+**Option 2: Using NERExtractor for more control**
```python
from semantica.semantic_extract import NERExtractor, NamedEntityRecognizer
@@ -578,20 +569,21 @@ for event in events:
import semantica
import numpy as np
-# Simple approach - generate embeddings directly
+# Generate embeddings using EmbeddingGenerator
+from semantica.embeddings import EmbeddingGenerator
+
texts = [
"First document text.",
"Second document text.",
"Third document text."
]
-# Generate embeddings using module-level function
-result = semantica.embeddings.build(texts, data_type="text")
-embeddings = result["embeddings"]
-print(f"Batch embeddings shape: {embeddings.shape}")
+generator = EmbeddingGenerator()
+embeddings = [generator.generate_embeddings(t, data_type="text") for t in texts]
+print(f"Generated {len(embeddings)} embeddings")
```
-**Option 2: Using TextEmbedder directly (Advanced)**
+**Option 2: Using TextEmbedder for more control**
```python
import numpy as np
from semantica.embeddings import TextEmbedder, EmbeddingGenerator
@@ -673,26 +665,30 @@ print(f"Text-Image similarity: {similarity}")
#### Building Knowledge Graph
-**Option 1: Using module-level build function (Recommended)**
+**Option 1: Using GraphBuilder (Recommended)**
```python
-import semantica
+from semantica.kg import GraphBuilder
-# Simple approach - build knowledge graph directly from documents
-documents = ["doc1.pdf", "doc2.pdf", "doc3.txt"]
-result = semantica.kg.build(
- documents,
+# Build knowledge graph from entity/relationship data
+builder = GraphBuilder(
merge_entities=True,
entity_resolution_strategy="fuzzy",
resolve_conflicts=True,
enable_temporal=True
)
-graph = result["knowledge_graph"]
+# Prepare sources with entities and relationships
+sources = [{
+ "entities": [...], # Your extracted entities
+ "relationships": [...] # Your extracted relationships
+}]
+
+graph = builder.build(sources)
print(f"Total entities: {len(graph.get('entities', []))}")
print(f"Total relationships: {len(graph.get('relationships', []))}")
```
-**Option 2: Using GraphBuilder directly (Advanced)**
+**Option 2: Using GraphBuilder with full control**
```python
from semantica.kg import GraphBuilder, EntityResolver
from semantica.semantic_extract import NERExtractor, RelationExtractor
@@ -1277,12 +1273,13 @@ temporal_viz.visualize_metrics_evolution(metrics_history, timestamps,
#### Quick Visualization Example
```python
-import semantica
+from semantica import Semantica
from semantica.visualization import KGVisualizer, EmbeddingVisualizer
import numpy as np
-# Build knowledge graph (auto-initializes)
-result = semantica.build(["document.pdf"], graph=True, embeddings=True)
+# Build knowledge graph
+semantica = Semantica()
+result = semantica.build_knowledge_base(["document.pdf"], graph=True, embeddings=True)
# Visualize knowledge graph
kg_viz = KGVisualizer(layout="force", color_scheme="vibrant")
@@ -1327,14 +1324,14 @@ config = Config({
}
})
-# Use configuration with build function
-result = semantica.build(["document.pdf"], config=config)
+# Use configuration with Semantica
+semantica_instance = Semantica(config=config)
+result = semantica_instance.build_knowledge_base(["document.pdf"])
```
### Advanced Configuration
```python
-import semantica
-from semantica import Config
+from semantica import Semantica, Config
# Advanced configuration
config = Config({
@@ -1359,8 +1356,9 @@ config = Config({
}
})
-# Use advanced configuration with build function
-result = semantica.build(["document.pdf"], config=config)
+# Use advanced configuration with Semantica
+semantica = Semantica(config=config)
+result = semantica.build_knowledge_base(["document.pdf"])
```
## 🚀 Performance
diff --git a/docs/concepts.md b/docs/concepts.md
index 3ab703cc..192cd8b1 100644
--- a/docs/concepts.md
+++ b/docs/concepts.md
@@ -2,238 +2,3000 @@
Understand the fundamental concepts behind Semantica. This guide covers the theoretical foundations, key components, and best practices for building semantic applications.
-## 🧠 Core Concepts
+!!! info "About This Guide"
+ This guide provides a comprehensive overview of the core concepts in Semantica. Each concept includes definitions, visual diagrams, practical examples, and guidance on when to use them.
+
+---
+
+
+
+## Core Concepts
### 1. Knowledge Graphs
-**Definition**: A knowledge graph is a structured representation of entities (nodes) and their relationships (edges) with properties and attributes.
+!!! abstract "Definition"
+ A **knowledge graph** is a structured representation of entities (nodes) and their relationships (edges) with properties and attributes. It transforms unstructured data into a queryable, interconnected knowledge base.
+
+<div class="grid cards" markdown>
+
+- **Nodes (Entities)**
+ ---
+ Represent real-world objects, concepts, or events.
+ *Examples*: People, Organizations, Locations, Concepts
+
+- **Edges (Relationships)**
+ ---
+ Represent connections between entities.
+ *Examples*: `works_for`, `located_in`, `founded_by`, `causes`
+
+- **Properties**
+ ---
+ Attributes of entities and relationships.
+ *Examples*: Name, Date, Confidence Score, Source
+
+- **Metadata**
+ ---
+ Additional information about the data.
+ *Examples*: Source documents, timestamps, extraction methods
+
+</div>
+
+**Visual Example**:
+
+```mermaid
+graph LR
+ A[Apple Inc.<br/>Organization<br/>Founded: 1976] -->|founded_by| B[Steve Jobs<br/>Person<br/>1955-2011]
+ A -->|located_in| C[Cupertino<br/>Location<br/>City]
+ C -->|in_state| D[California<br/>Location<br/>State]
+ A -->|has_ceo| E[Tim Cook<br/>Person<br/>CEO since 2011]
+
+ style A fill:#e3f2fd,stroke:#1565c0,stroke-width:2px
+ style B fill:#fff3e0,stroke:#ef6c00,stroke-width:2px
+ style C fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px
+ style D fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px
+ style E fill:#fff3e0,stroke:#ef6c00,stroke-width:2px
+```
+
+**Practical Examples**:
+
+=== "Basic Usage"
+ Build a knowledge graph from a document with just a few lines:
+
+ ```python
+ from semantica import Semantica
+
+ # Initialize Semantica with default settings
+ semantica = Semantica()
+
+ # Build knowledge graph from a PDF document
+ result = semantica.build_knowledge_base(
+ sources=["company_report.pdf"],
+ embeddings=True, # Generate vector embeddings
+ graph=True # Build knowledge graph
+ )
+
+ kg = result["knowledge_graph"]
+
+ print(f"Extracted {len(kg['entities'])} entities")
+ print(f"Found {len(kg['relationships'])} relationships")
+
+ for entity in kg['entities'][:5]:
+ print(f" {entity['text']} ({entity['type']})")
+ ```
+
+=== "Direct KG Module Usage"
+ Use the `kg` module directly for more control:
+
+ ```python
+ from semantica.kg import GraphBuilder
+
+ # Option 1: Using the convenience function (semantica.kg.build)
+ kg = build(
+ sources=[
+ {
+ "entities": [
+ {"id": "e1", "text": "Apple Inc.", "type": "Organization"},
+ {"id": "e2", "text": "Tim Cook", "type": "Person"},
+ {"id": "e3", "text": "Cupertino", "type": "Location"}
+ ],
+ "relationships": [
+ {"source": "e2", "target": "e1", "type": "CEO_OF"},
+ {"source": "e1", "target": "e3", "type": "LOCATED_IN"}
+ ]
+ }
+ ],
+ merge_entities=True,
+ resolve_conflicts=True
+ )
+
+ print(f"Graph built: {kg['metadata']['num_entities']} entities, "
+ f"{kg['metadata']['num_relationships']} relationships")
+
+ # Option 2: Using GraphBuilder for advanced configuration
+ builder = GraphBuilder(
+ merge_entities=True,
+ entity_resolution_strategy="fuzzy", # "exact", "fuzzy", or "semantic"
+ resolve_conflicts=True,
+ enable_temporal=True, # Enable time-aware edges
+ temporal_granularity="day"
+ )
+ kg = builder.build(sources)
+ ```
+
+=== "Multi-Source Integration"
+ Merge knowledge from multiple data sources:
+
+ ```python
+ from semantica import Semantica
+
+ semantica = Semantica()
+
+ # Build graphs from different sources
+ kg_news = semantica.build_knowledge_base(
+ sources=["news_articles/"],
+ normalize=True
+ )["knowledge_graph"]
+
+ kg_reports = semantica.build_knowledge_base(
+ sources=["financial_reports/"],
+ normalize=True
+ )["knowledge_graph"]
+
+ # Merge into a unified knowledge graph
+ from semantica.kg import GraphBuilder
+ builder = GraphBuilder(
+ merge_entities=True,
+ entity_resolution_strategy="semantic" # Use embeddings for matching
+ )
+
+ unified_kg = builder.merge([kg_news, kg_reports])
+
+ print(f"Merged graph: {len(unified_kg['entities'])} unique entities")
+ print(f"Deduplicated from {len(kg_news['entities']) + len(kg_reports['entities'])} total")
+ ```
+
+=== "Graph Analytics"
+ Analyze the structure and properties of your knowledge graph:
+
+ ```python
+ from semantica.kg import (
+ GraphAnalyzer,
+ CentralityCalculator,
+ CommunityDetector,
+ ConnectivityAnalyzer,
+ analyze_graph,
+ calculate_centrality,
+ detect_communities,
+ analyze_connectivity
+ )
+
+ # Method 1: Using convenience functions
+ analysis = analyze_graph(kg, method="default")
+ centrality_scores = calculate_centrality(kg, method="degree")
+ communities = detect_communities(kg, method="louvain")
+ connectivity = analyze_connectivity(kg, method="default")
+
+ # Method 2: Using classes for more control
+ analyzer = GraphAnalyzer()
+ centrality_calc = CentralityCalculator()
+ community_detector = CommunityDetector()
+ connectivity_analyzer = ConnectivityAnalyzer()
+
+ # Run comprehensive analysis
+ analysis = analyzer.analyze(kg)
+ print(f"Graph density: {analysis['density']:.3f}")
+ print(f"Average degree: {analysis['avg_degree']:.2f}")
+
+ # Calculate centrality measures
+ degree_centrality = centrality_calc.calculate(kg, method="degree")
+ betweenness = centrality_calc.calculate(kg, method="betweenness")
+ print(f"Top entities by degree: {list(degree_centrality.items())[:3]}")
+
+ # Detect communities
+ communities = community_detector.detect(kg, method="louvain")
+ print(f"Found {len(communities)} communities")
+
+ # Analyze connectivity
+ conn = connectivity_analyzer.analyze(kg)
+ print(f"Connected components: {conn['num_components']}")
+ print(f"Largest component: {conn['largest_component_size']} nodes")
+ ```
+
+**Related Modules**:
+
+- [`kg` Module](reference/kg.md) - Knowledge graph construction and management
+- [`graph_store` Module](reference/graph_store.md) - Persistent graph storage
+- [`visualization` Module](reference/visualization.md) - Graph visualization
+
+---
+
+### 2. Entity Extraction (NER)
+
+!!! abstract "Definition"
+ **Named Entity Recognition (NER)** is the process of identifying and classifying named entities in text into predefined categories such as persons, organizations, locations, dates, and more.
+
+**Entity Types**:
+
+| Entity Type | Description | Example |
+| :--------------- | :----------------------------- | :------------------------------- |
+| **Person** | Names of people | Steve Jobs, Elon Musk, Marie Curie |
+| **Organization** | Companies, institutions | Apple Inc., NASA, MIT |
+| **Location** | Places, geographic entities | Cupertino, Mars, Pacific Ocean |
+| **Date/Time** | Temporal expressions | 1976, next Monday, Q1 2024 |
+| **Money** | Monetary values | $100 million, €50,000 |
+| **Event** | Events and occurrences | WWDC 2024, World War II |
+| **Product** | Products and services | iPhone 15, Tesla Model S |
+| **Technology** | Technologies and methods | Machine Learning, Python |
+
+!!! tip "Custom Entities"
+ Semantica allows you to define custom entity types via the [`Ontology`](reference/ontology.md) module. You aren't limited to the standard set!
+
+**Extraction Methods**:
+
+=== "Quick Start"
+ Extract entities from text using the convenience function:
+
+ ```python
+ from semantica.semantic_extract import NamedEntityRecognizer
+
+ text = """
+ Apple Inc. was founded by Steve Jobs, Steve Wozniak, and Ronald Wayne
+ in Cupertino, California on April 1, 1976. The company is now worth
+ over $3 trillion and employs more than 160,000 people worldwide.
+ """
+
+ # Initialize the NER extractor
+ ner = NamedEntityRecognizer()
+
+ # Extract entities
+ entities = ner.extract_entities(text)
+
+ print(f"Extracted {len(entities)} entities:")
+ for entity in entities:
+ print(f" {entity['text']:20} | Type: {entity['type']:15} | "
+ f"Confidence: {entity.get('confidence', 0.0):.2f}")
+ ```
+
+=== "Named Entity Recognizer"
+ Use the `NamedEntityRecognizer` class for advanced control:
+
+ ```python
+ from semantica.semantic_extract import NamedEntityRecognizer
+
+ # Initialize with custom configuration
+ ner = NamedEntityRecognizer(
+ methods=["spacy", "rule-based"], # Use multiple methods
+ confidence_threshold=0.7,
+ merge_overlapping=True
+ )
+
+ text = "Elon Musk announced that Tesla will invest $10B in Texas."
+
+ # Extract entities with detailed output
+ entities = ner.extract_entities(text)
+
+ for entity in entities:
+ print(f"""
+ Entity: {entity['text']}
+ Type: {entity['type']}
+ Start: {entity['start_char']}, End: {entity['end_char']}
+ Confidence: {entity['confidence']:.2f}
+ Method: {entity.get('extraction_method', 'N/A')}
+ """)
+ ```
+
+=== "Custom Entity Types"
+ Define and extract custom entity types for your domain:
+
+ ```python
+ from semantica.semantic_extract import (
+ NamedEntityRecognizer,
+ CustomEntityDetector
+ )
+
+ # Define custom entity patterns for a medical domain
+ custom_detector = CustomEntityDetector(
+ patterns={
+ "Drug": [
+ r"\b(aspirin|ibuprofen|acetaminophen)\b",
+ r"\b\w+(?:mycin|cillin|phen)\b" # Common drug suffixes
+ ],
+ "Dosage": [
+ r"\d+\s*(?:mg|ml|g|mcg)\b",
+ r"\b(?:once|twice|three times)\s+(?:daily|weekly)\b"
+ ],
+ "Condition": [
+ r"\b(?:diabetes|hypertension|arthritis)\b",
+ r"\b\w+itis\b" # Inflammation conditions
+ ]
+ }
+ )
+
+ ner = NamedEntityRecognizer(
+ custom_detectors=[custom_detector],
+ include_standard_types=True # Also extract Person, Org, etc.
+ )
+
+ medical_text = """
+ Patient prescribed ibuprofen 400mg twice daily for arthritis.
+ Previous treatment with amoxicillin was discontinued.
+ """
+
+ entities = ner.extract_entities(medical_text)
+
+ # Group by type
+ from collections import defaultdict
+ by_type = defaultdict(list)
+ for e in entities:
+ by_type[e['type']].append(e['text'])
+
+ for entity_type, items in by_type.items():
+ print(f"{entity_type}: {', '.join(items)}")
+
+ # Output:
+ # Drug: ibuprofen, amoxicillin
+ # Dosage: 400mg, twice daily
+ # Condition: arthritis
+ ```
+
+=== "LLM-Enhanced Extraction"
+ Use LLMs for context-aware, high-accuracy extraction:
+
+ ```python
+ from semantica.semantic_extract import (
+ NamedEntityRecognizer,
+ LLMEnhancer,
+ create_provider
+ )
+
+ # Create LLM provider (supports OpenAI, Anthropic, Groq, Ollama)
+ provider = create_provider(
+ provider_type="openai",
+ model="gpt-4o",
+ api_key="your-api-key" # Or use OPENAI_API_KEY env var
+ )
+
+ # Initialize LLM-enhanced NER
+ enhancer = LLMEnhancer(provider=provider)
+ ner = NamedEntityRecognizer(
+ llm_enhancer=enhancer,
+ use_llm_verification=True # Verify with LLM
+ )
+
+ # Extract with LLM enhancement for ambiguous cases
+ text = """
+ Apple reported record revenue. Tim said the new Apple Watch
+ and the partnership with Goldman Sachs exceeded expectations.
+ """
+
+ entities = ner.extract_entities(
+ text,
+ context="Financial earnings report" # Provide context for better accuracy
+ )
+
+ # LLM helps distinguish:
+ # - "Apple" (company) vs "apple" (fruit)
+ # - "Tim" (person - Tim Cook) from context
+ # - "Goldman Sachs" (organization)
+ # - "Apple Watch" (product vs organization)
+ ```
+
+=== "Batch Processing"
+ Process multiple documents efficiently:
+
+ ```python
+ from semantica.semantic_extract import NamedEntityRecognizer
+
+ ner = NamedEntityRecognizer(batch_size=32)
+
+ documents = [
+ "Microsoft acquired Activision for $69 billion.",
+ "Google announced Gemini AI at their Mountain View headquarters.",
+ "Amazon's Andy Jassy unveiled new AWS services in Seattle.",
+ # ... hundreds more documents
+ ]
+
+ # Process in batches for efficiency
+ all_entities = []
+ for i, doc in enumerate(documents):
+ entities = ner.extract_entities(doc)
+ all_entities.extend([
+ {**e, "doc_id": i} for e in entities
+ ])
+
+ if (i + 1) % 100 == 0:
+ print(f"Processed {i + 1}/{len(documents)} documents")
+
+ from collections import Counter
+ entity_types = Counter(e['type'] for e in all_entities)
+ print(f"Entity Distribution:")
+ for etype, count in entity_types.most_common():
+ print(f" {etype}: {count}")
+ ```
+
+**Related Modules**:
+- [`semantic_extract` Module](reference/semantic_extract.md) - Entity and relationship extraction
+- [`ontology` Module](reference/ontology.md) - Custom entity type definitions
+
+---
+
+### 3. Relationship Extraction
+
+!!! abstract "Definition"
+ **Relationship Extraction** is the process of identifying and extracting semantic relationships between entities in text. It connects entities to form meaningful knowledge structures.
+
+**Relationship Types**:
+
+=== "Semantic Relationships"
+ Relationships that define meaning and connection between entities.
+
+ - `works_for` - Employment relationships
+ - `located_in` - Geographic relationships
+ - `founded_by` - Creation relationships
+ - `owns` - Ownership relationships
+ - `part_of` - Hierarchical relationships
+
+ ```python
+ # Example: "Tim Cook works for Apple Inc."
+ # Extracted: (Tim Cook) --[works_for]--> (Apple Inc.)
+ ```
+
+=== "Temporal Relationships"
+ Relationships defined by time and sequence.
+
+ - `happened_before` - Temporal precedence
+ - `happened_after` - Temporal succession
+ - `during` - Temporal containment
+ - `overlaps_with` - Temporal overlap
+
+ ```python
+ # Example: "WWDC 2023 happened before WWDC 2024"
+ # Extracted: (WWDC 2023) --[happened_before]--> (WWDC 2024)
+ ```
+
+=== "Causal Relationships"
+ Cause and effect relationships.
+
+ - `causes` - Direct causation
+ - `results_in` - Outcome relationships
+ - `prevents` - Prevention relationships
+ - `influences` - Indirect influence
+
+ ```python
+ # Example: "High inflation causes economic instability"
+ # Extracted: (High inflation) --[causes]--> (Economic instability)
+ ```
+
+**Visual Example**:
+
+```mermaid
+graph LR
+ A[Apple Inc.] -->|founded_by| B[Steve Jobs]
+ A -->|located_in| C[Cupertino]
+ A -->|has_ceo| D[Tim Cook]
+ C -->|in_state| E[California]
+ B -->|co-founded| F[Apple Inc.]
+
+ style A fill:#e3f2fd
+ style B fill:#fff3e0
+ style C fill:#f3e5f5
+ style D fill:#fff3e0
+ style E fill:#f3e5f5
+ style F fill:#e3f2fd
+```
+
+**Practical Examples**:
+
+=== "Basic Relation Extraction"
+ Extract relationships between entities:
+
+ ```python
+ from semantica.semantic_extract import RelationExtractor, NamedEntityRecognizer
+
+ text = """
+ Tim Cook became CEO of Apple Inc. in 2011, succeeding Steve Jobs.
+ Apple is headquartered in Cupertino, California. The company
+ acquired Beats Electronics in 2014 for $3 billion.
+ """
+
+ # First extract entities
+ ner = NamedEntityRecognizer()
+ entities = ner.extract_entities(text)
+
+ # Then extract relationships
+ rel_extractor = RelationExtractor()
+ relations = rel_extractor.extract_relations(text, entities=entities)
+
+ print("Extracted Relationships:")
+ for rel in relations:
+ print(f" ({rel['source']}) --[{rel['type']}]--> ({rel['target']})")
+ print(f" Confidence: {rel.get('confidence', 0.0):.2f}")
+ ```
+
+=== "RelationExtractor Class"
+ Use the `RelationExtractor` for advanced control:
+
+ ```python
+ from semantica.semantic_extract import (
+ RelationExtractor,
+ NamedEntityRecognizer
+ )
+
+ # First extract entities
+ ner = NamedEntityRecognizer()
+ text = """
+ Dr. Sarah Chen published her research on quantum computing at MIT.
+ Her work was funded by DARPA and received the ACM Award in 2023.
+ """
+ entities = ner.extract_entities(text)
+
+ # Then extract relationships
+ rel_extractor = RelationExtractor(
+ relation_types=["works_at", "funded_by", "received", "published"],
+ bidirectional=False,
+ confidence_threshold=0.6
+ )
+
+ relations = rel_extractor.extract_relations(text, entities=entities)
+
+ print("Knowledge Graph Edges:")
+ for rel in relations:
+ arrow = "<->" if rel.get('bidirectional') else "->"
+ 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:
+
+ ```python
+ from semantica.semantic_extract import (
+ TripleExtractor,
+ RDFSerializer,
+ TripleValidator
+ )
+
+ text = """
+ Albert Einstein was born in Ulm, Germany in 1879. He developed
+ the theory of relativity and won the Nobel Prize in Physics in 1921.
+ Einstein worked at Princeton University until his death in 1955.
+ """
+
+ # Extract RDF-style triples
+ extractor = TripleExtractor(
+ include_temporal=True, # Include time information
+ include_provenance=True # Track source sentences
+ )
+
+ triples = extractor.extract_triples(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()
+
+ validator = TripleValidator()
+ validation = validator.validate(triples)
+ print(f"Valid triples: {validation['valid_count']}/{len(triples)}")
+
+ serializer = RDFSerializer(format="turtle")
+ turtle_output = serializer.serialize(
+ triples,
+ base_uri="https://example.org/knowledge/"
+ )
+ print("Turtle Output:")
+ print(turtle_output)
+ ```
+
+=== "Event Detection"
+ Extract events with temporal information:
+
+ ```python
+ from semantica.semantic_extract import (
+ EventDetector,
+ TemporalEventProcessor
+ )
+
+ news_text = """
+ On March 15, 2024, SpaceX successfully launched Starship from
+ Boca Chica, Texas. The rocket reached orbit before splashing down
+ in the Indian Ocean. CEO Elon Musk announced plans for a Mars
+ mission by 2026.
+ """
+
+ # Detect events
+ detector = EventDetector(
+ event_types=["launch", "announcement", "achievement"],
+ extract_participants=True,
+ extract_location=True,
+ extract_time=True
+ )
+
+ events = detector.detect_events(news_text)
+
+ print("Detected Events:")
+ for event in events:
+ print(f" Event: {event['description']}")
+ print(f" Type: {event['type']}")
+ print(f" When: {event.get('datetime', 'Unknown')}")
+ print(f" Where: {event.get('location', 'Unknown')}")
+ print(f" Who: {', '.join(event.get('participants', []))}")
+ print()
+
+ # Process temporal relationships between events
+ temporal = TemporalEventProcessor()
+ timeline = temporal.build_timeline(events)
+
+ print("Event Timeline:")
+ for i, evt in enumerate(timeline, 1):
+ print(f" {i}. {evt['datetime']}: {evt['description']}")
+ ```
+
+=== "Coreference Resolution"
+ Resolve pronouns and entity references:
+
+ ```python
+ from semantica.semantic_extract import CoreferenceResolver
+
+ text = """
+ Apple Inc. announced their new iPhone. The company said it would
+ be available in September. Tim Cook presented the device at their
+ headquarters. He emphasized its improved camera capabilities.
+ """
+
+ resolver = CoreferenceResolver()
+ result = resolver.resolve(text)
+
+ print("Coreference Chains:")
+ for chain in result['chains']:
+ print(f" Entity: {chain['canonical']}")
+ print(f" Mentions: {', '.join(chain['mentions'])}")
+ print()
+
+ resolved_text = resolver.get_resolved_text(text)
+ print("Resolved Text:")
+ print(resolved_text)
+ ```
+
+**Related Modules**:
+- [`semantic_extract` Module](reference/semantic_extract.md) - Relationship extraction
+- [`kg` Module](reference/kg.md) - Building graphs from relationships
+
+---
+
+### 4. Embeddings
+
+!!! abstract "Definition"
+ **Embeddings** are dense vector representations of text, images, or other data that capture semantic meaning in a continuous vector space. They enable machines to understand similarity and meaning.
+
+!!! note "The Bridge Between Language and Understanding"
+ Embeddings are the bridge between human language and machine understanding. They convert text into numerical vectors that preserve semantic relationships.
+
+**How Embeddings Work**:
+
+Embeddings convert text into numerical vectors that capture semantic meaning. Similar texts have similar vectors, enabling semantic search and similarity calculations.
+
+**Example**:
+
+```python
+Text: "machine learning"
+Embedding: [0.123, -0.456, 0.789, ..., 0.234] # (vector of 1536 dimensions)
+
+# Similar texts will have similar vectors
+"artificial intelligence" → [0.145, -0.432, 0.801, ..., 0.221] # Close in vector space
+"cooking recipes" → [-0.234, 0.567, -0.123, ..., -0.456] # Far in vector space
+```
+
+**Embedding Providers**:
+
+| Provider | Model | Dimensions | Speed | Cost | Best For |
+| :--- | :--- | :--- | :--- | :--- | :--- |
+| **OpenAI** | text-embedding-3-large | 3072 | Fast | Paid | Production, high accuracy |
+| **OpenAI** | text-embedding-3-small | 1536 | Fast | Paid | Balanced performance |
+| **Cohere** | embed-english-v3.0 | 1024 | Fast | Paid | Multilingual support |
+| **HuggingFace** | sentence-transformers | 384-768 | Medium | Free | Development, open source |
+| **Local** | Various | Variable | Slow | Free | Privacy, offline use |
+
+**Practical Examples**:
+
+=== "Quick Start"
+ Generate embeddings in one call:
+
+ ```python
+ from semantica.embeddings import EmbeddingGenerator, embed_text
+
+ # Using EmbeddingGenerator class
+ texts = [
+ "Machine learning is transforming industries",
+ "Artificial intelligence powers modern applications",
+ "Deep learning enables image recognition",
+ "Cooking recipes are delicious" # Different topic
+ ]
+
+ generator = EmbeddingGenerator()
+
+ # Generate embeddings for multiple texts
+ embeddings = []
+ for text in texts:
+ emb = generator.generate_embeddings(text, data_type="text")
+ embeddings.append(emb)
+
+ print(f"Generated {len(embeddings)} embeddings")
+ print(f"Dimensions: {embeddings[0].shape}")
+
+ # Or use the convenience function for single text
+ embedding = embed_text("Hello, world!", method="sentence_transformers")
+ print(f"Single embedding shape: {embedding.shape}")
+ ```
+
+=== "Similarity Search"
+ Calculate semantic similarity between texts:
+
+ ```python
+ from semantica.embeddings import (
+ EmbeddingGenerator,
+ calculate_similarity
+ )
+ import numpy as np
+
+ generator = EmbeddingGenerator()
+
+ # Generate embeddings
+ query = "How does photosynthesis work?"
+ documents = [
+ "Plants convert sunlight into energy through photosynthesis",
+ "The process of photosynthesis occurs in chloroplasts",
+ "Dogs are popular household pets",
+ "Solar panels convert sunlight to electricity",
+ "Chlorophyll absorbs light for photosynthesis"
+ ]
+
+ query_emb = generator.generate_embeddings(query, data_type="text")
+ doc_embs = [generator.generate_embeddings(d, data_type="text") for d in documents]
+
+ print("Semantic Similarity Search:")
+ print(f"Query: \"{query}\"")
+
+ similarities = []
+ for i, doc_emb in enumerate(doc_embs):
+ sim = calculate_similarity(query_emb, doc_emb, method="cosine")
+ similarities.append((sim, documents[i]))
+
+ for sim, doc in sorted(similarities, reverse=True):
+ relevance = "HIGH" if sim > 0.6 else "MED" if sim > 0.3 else "LOW"
+ print(f" [{relevance}] {sim:.3f}: {doc[:50]}...")
+ ```
+
+=== "Multiple Embedding Types"
+ Work with text, image, and audio embeddings:
+
+ ```python
+ from semantica.embeddings import (
+ TextEmbedder,
+ ImageEmbedder,
+ AudioEmbedder,
+ MultimodalEmbedder
+ )
+
+ text_embedder = TextEmbedder(model="all-MiniLM-L6-v2")
+ text_emb = text_embedder.embed("A beautiful sunset over the ocean")
+ print(f"Text embedding: {text_emb.shape}")
+
+ image_embedder = ImageEmbedder(model="clip")
+ image_emb = image_embedder.embed("sunset_photo.jpg")
+ print(f"Image embedding: {image_emb.shape}")
+
+ audio_embedder = AudioEmbedder()
+ audio_emb = audio_embedder.embed("ocean_waves.mp3")
+ print(f"Audio embedding: {audio_emb.shape}")
+
+ multimodal = MultimodalEmbedder()
+ combined = multimodal.embed(
+ text="sunset over ocean",
+ image="sunset_photo.jpg",
+ strategy="concatenate"
+ )
+ print(f"Combined embedding: {combined.shape}")
+
+ from semantica.embeddings import calculate_similarity
+ text_query = text_embedder.embed("beach at sunset")
+ images = ["beach.jpg", "mountain.jpg", "city.jpg"]
+
+ for img in images:
+ img_emb = image_embedder.embed(img)
+ sim = calculate_similarity(text_query, img_emb, method="cosine")
+ print(f" {img}: {sim:.3f}")
+ ```
+
+=== "Embedding Optimization"
+ Optimize embeddings for storage and performance:
+
+ ```python
+ from semantica.embeddings import EmbeddingOptimizer
+ import numpy as np
+
+ optimizer = EmbeddingOptimizer()
+
+ # Generate some embeddings
+ embeddings = np.random.randn(1000, 768).astype(np.float32)
+ print(f"Original size: {embeddings.nbytes / 1024:.1f} KB")
+
+ # Dimension reduction with PCA
+ reduced = optimizer.reduce_dimensions(
+ embeddings,
+ method="pca",
+ target_dims=256
+ )
+ print(f"After PCA (256d): {reduced.nbytes / 1024:.1f} KB")
+
+ # Quantization for storage efficiency
+ quantized = optimizer.quantize(
+ embeddings,
+ bits=8 # 8-bit quantization
+ )
+ print(f"After 8-bit quantization: {quantized.nbytes / 1024:.1f} KB")
+
+ # Normalize for cosine similarity
+ normalized = optimizer.normalize(embeddings, method="l2")
+ print(f"Normalized: unit vectors ready for dot product")
+ ```
+
+=== "Pooling Strategies"
+ Aggregate embeddings using different strategies:
+
+ ```python
+ from semantica.embeddings import (
+ MeanPooling,
+ MaxPooling,
+ AttentionPooling,
+ HierarchicalPooling
+ )
+ import numpy as np
+
+ # Simulate token-level embeddings (e.g., from a transformer)
+ # Shape: (sequence_length, embedding_dim)
+ token_embeddings = np.random.randn(128, 768)
+
+ # Mean pooling - average all tokens
+ mean_pool = MeanPooling()
+ mean_result = mean_pool.pool(token_embeddings)
+ print(f"Mean pooling: {mean_result.shape}") # (768,)
+
+ # Max pooling - take max across tokens
+ max_pool = MaxPooling()
+ max_result = max_pool.pool(token_embeddings)
+ print(f"Max pooling: {max_result.shape}") # (768,)
+
+ # Attention-based pooling - learned weights
+ attn_pool = AttentionPooling(hidden_dim=768)
+ attn_result = attn_pool.pool(token_embeddings)
+ print(f"Attention pooling: {attn_result.shape}") # (768,)
+
+ # Hierarchical pooling for long documents
+ hier_pool = HierarchicalPooling(chunk_size=32)
+ document_embeddings = np.random.randn(10, 128, 768) # 10 paragraphs
+ hier_result = hier_pool.pool(document_embeddings)
+ print(f"Hierarchical pooling: {hier_result.shape}") # (768,)
+ ```
+
+=== "Context Management"
+ Handle long texts with context windows:
+
+ ```python
+ from semantica.embeddings import ContextManager, EmbeddingGenerator
+
+ # Long document that exceeds model context
+ long_document = "..." * 10000 # Very long text
+
+ # Manage context windows
+ context_manager = ContextManager(
+ max_window_size=512, # Tokens per window
+ overlap=50, # Overlap between windows
+ preserve_sentences=True
+ )
+
+ windows = context_manager.split(long_document)
+ print(f"Split into {len(windows)} windows")
+
+ # Generate embeddings for each window
+ generator = EmbeddingGenerator()
+ window_embeddings = []
+
+ for i, window in enumerate(windows):
+ emb = generator.generate_embeddings(window.text, data_type="text")
+ window_embeddings.append({
+ 'embedding': emb,
+ 'start_char': window.start_char,
+ 'end_char': window.end_char
+ })
+
+ # Merge windows for document-level embedding
+ from semantica.embeddings import pool_embeddings
+ import numpy as np
+
+ all_embs = np.array([w['embedding'] for w in window_embeddings])
+ doc_embedding = pool_embeddings(all_embs, method="mean")
+ print(f"Document embedding shape: {doc_embedding.shape}")
+ ```
+
+**Related Modules**:
+- [`embeddings` Module](reference/embeddings.md) - Embedding generation
+- [`vector_store` Module](reference/vector_store.md) - Vector storage and search
+
+---
+
+### 5. Temporal Graphs
+
+!!! abstract "Definition"
+ **Temporal Graphs** are knowledge graphs that track changes over time, allowing queries about the state of the graph at specific time points. They enable time-aware reasoning and analysis.
+
+**Key Features**:
+
+- **Time-stamped Entities**: Entities have creation and modification timestamps
+- **Time-stamped Relationships**: Relationships have validity periods
+- **Historical Queries**: Query the graph state at any point in time
+- **Change Tracking**: Track how entities and relationships evolve
+
+**Visual Timeline**:
+
+```mermaid
+timeline
+ title Temporal Graph Evolution
+ 2020 : Entity A created
+ : Relationship A->B established
+ 2021 : Entity B updated
+ : Relationship B->C created
+ 2022 : Entity A deleted
+ : New Relationship D->C
+ 2023 : Entity C properties updated
+ : Relationship A->B expired
+```
+
+**Practical Examples**:
+
+=== "Building Temporal Graphs"
+ Create a knowledge graph with time-aware edges:
+
+ ```python
+ from semantica.kg import GraphBuilder
+ from datetime import datetime, timedelta
+
+ # Build a temporal knowledge graph
+ builder = GraphBuilder(
+ enable_temporal=True,
+ temporal_granularity="day", # day, hour, minute, second
+ track_history=True,
+ version_snapshots=True
+ )
+
+ # Add time-stamped data
+ sources = [{
+ "entities": [
+ {
+ "id": "e1",
+ "text": "Satya Nadella",
+ "type": "Person",
+ "valid_from": "2014-02-04" # Became CEO
+ },
+ {
+ "id": "e2",
+ "text": "Microsoft",
+ "type": "Organization"
+ },
+ {
+ "id": "e3",
+ "text": "Steve Ballmer",
+ "type": "Person",
+ "valid_from": "2000-01-13",
+ "valid_until": "2014-02-04" # Was CEO until
+ }
+ ],
+ "relationships": [
+ {
+ "source": "e1",
+ "target": "e2",
+ "type": "CEO_OF",
+ "valid_from": "2014-02-04",
+ "valid_until": None # Still active
+ },
+ {
+ "source": "e3",
+ "target": "e2",
+ "type": "CEO_OF",
+ "valid_from": "2000-01-13",
+ "valid_until": "2014-02-04"
+ }
+ ]
+ }]
+
+ kg = builder.build(sources)
+ print(f"Built temporal graph with {kg['metadata']['num_entities']} entities")
+ ```
+
+=== "Temporal Queries"
+ Query the graph at specific points in time:
+
+ ```python
+ from semantica.kg import TemporalGraphQuery
+ from datetime import datetime
+
+ # Initialize temporal query engine
+ temporal_query = TemporalGraphQuery(kg)
+
+ # Query 1: Who was CEO in 2010?
+ state_2010 = temporal_query.query_at_time(
+ datetime(2010, 6, 1),
+ query_type="relationships",
+ relationship_type="CEO_OF"
+ )
+ print(f"CEO in 2010: {state_2010['results']}")
+
+ state_2020 = temporal_query.query_at_time(
+ datetime(2020, 6, 1),
+ query_type="relationships",
+ relationship_type="CEO_OF"
+ )
+ print(f"CEO in 2020: {state_2020['results']}")
+
+ ceo_history = temporal_query.query_time_range(
+ start_time=datetime(2000, 1, 1),
+ end_time=datetime(2024, 1, 1),
+ relationship_type="CEO_OF"
+ )
+
+ print("CEO History:")
+ for rel in ceo_history['results']:
+ print(f" {rel['source']} -> {rel['valid_from']} to {rel.get('valid_until', 'present')}")
+ ```
+
+=== "Pattern Detection"
+ Detect temporal patterns in your graph:
+
+ ```python
+ from semantica.kg import TemporalPatternDetector
+
+ # Initialize pattern detector
+ detector = TemporalPatternDetector(kg)
+
+ # Detect sequences: A happened, then B, then C
+ sequences = detector.detect_sequences(
+ event_types=["HIRED", "PROMOTED", "RESIGNED"],
+ max_gap_days=365 # Events must be within 1 year
+ )
+
+ print("Detected Sequences:")
+ for seq in sequences:
+ print(f" {' -> '.join(seq['events'])}")
+ print(f" Entity: {seq['entity']}")
+ print(f" Duration: {seq['duration_days']} days")
+
+ cycles = detector.detect_cycles(
+ min_occurrences=2,
+ relationship_types=["QUARTERLY_REPORT"]
+ )
+
+ print("Detected Cycles:")
+ for cycle in cycles:
+ print(f" Pattern: {cycle['pattern']}")
+ print(f" Period: {cycle['period_days']} days")
+ print(f" Occurrences: {cycle['count']}")
+
+ trends = detector.detect_trends(
+ metric="employee_count",
+ entity_type="Organization",
+ window_days=90
+ )
+
+ for trend in trends:
+ direction = "UP" if trend['direction'] == 'increasing' else "DOWN"
+ print(f"[{direction}] {trend['entity']}: {trend['change_percent']:.1f}% over {trend['period']}")
+ ```
+
+=== "Version Management"
+ Track and manage graph versions over time:
+
+ ```python
+ from semantica.kg import TemporalVersionManager
+ from datetime import datetime
+
+ # Initialize version manager
+ version_mgr = TemporalVersionManager(kg)
+
+ # Create a snapshot of current state
+ snapshot_id = version_mgr.create_snapshot(
+ description="Q4 2024 knowledge graph",
+ timestamp=datetime.now()
+ )
+ print(f"Created snapshot: {snapshot_id}")
+
+ diff = version_mgr.compare_versions(
+ version_a=snapshot_id,
+ version_b="current"
+ )
+
+ print("Changes since snapshot:")
+ print(f" Added entities: {len(diff['added_entities'])}")
+ print(f" Removed entities: {len(diff['removed_entities'])}")
+ print(f" Modified entities: {len(diff['modified_entities'])}")
+ print(f" Added relationships: {len(diff['added_relationships'])}")
+ print(f" Removed relationships: {len(diff['removed_relationships'])}")
+
+ evolution = version_mgr.analyze_evolution(
+ start_date=datetime(2024, 1, 1),
+ end_date=datetime(2024, 12, 31)
+ )
+
+ print("Graph Evolution (2024):")
+ print(f" Total snapshots: {evolution['snapshot_count']}")
+ print(f" Net entity growth: {evolution['entity_growth']}")
+ print(f" Net relationship growth: {evolution['relationship_growth']}")
+ ```
+
+=== "Graph Evolution Analysis"
+ Analyze how your knowledge graph changes over time:
+
+ ```python
+ from semantica.kg import GraphAnalyzer
+
+ analyzer = GraphAnalyzer()
+
+ # Analyze temporal evolution
+ evolution = analyzer.analyze_temporal_evolution(
+ kg,
+ time_periods=[
+ ("2022-01-01", "2022-06-30"),
+ ("2022-07-01", "2022-12-31"),
+ ("2023-01-01", "2023-06-30"),
+ ("2023-07-01", "2023-12-31")
+ ]
+ )
+
+ print("Graph Evolution Analysis:")
+ for period in evolution['periods']:
+ print(f"Period: {period['start']} to {period['end']}")
+ print(f" Entities: {period['entity_count']} (+{period['entity_growth']})")
+ print(f" Relationships: {period['relationship_count']} (+{period['rel_growth']})")
+ print(f" Density: {period['density']:.4f}")
+ print(f" New entity types: {period['new_types']}")
+ print()
+
+ stability = analyzer.calculate_stability(kg, window_days=30)
+ print(f"Graph Stability Score: {stability['score']:.2f}")
+ print(f" Most stable entities: {stability['most_stable'][:3]}")
+ print(f" Most volatile entities: {stability['most_volatile'][:3]}")
+ ```
+
+**Related Modules**:
+- [`kg` Module](reference/kg.md) - Temporal graph support
+- [`visualization` Module](reference/visualization.md) - Temporal visualization
+
+---
+
+### 6. GraphRAG
+
+!!! abstract "Definition"
+ **GraphRAG (Graph-Augmented Retrieval Augmented Generation)** is an advanced RAG approach that combines vector search with knowledge graph traversal to provide more accurate and contextually relevant information to LLMs.
+
+**How GraphRAG Works**:
+
+```mermaid
+flowchart TD
+ subgraph Query["Query Processing"]
+ Q[User Query] --> VS[Vector Search]
+ Q --> KE[Keyword Extraction]
+ end
+
+ subgraph Retrieval["Hybrid Retrieval"]
+ VS --> Docs[Relevant Documents]
+ KE --> Nodes[Start Nodes]
+ Nodes --> Trav[Graph Traversal]
+ Trav --> Context[Graph Context]
+ end
+
+ subgraph Synthesis["Answer Generation"]
+ Docs --> Prompt[Enhanced Prompt]
+ Context --> Prompt
+ Prompt --> LLM[LLM Generation]
+ LLM --> A[Accurate Answer]
+ end
+
+ style Q fill:#e1f5fe
+ style LLM fill:#e8f5e9
+ style A fill:#fff9c4
+```
+
+**Advantages over Traditional RAG**:
+
+| Feature | Traditional RAG | GraphRAG |
+| :--- | :--- | :--- |
+| **Query Understanding** | Keyword matching | Semantic + structural |
+| **Context Retrieval** | Document chunks | Documents + relationships |
+| **Answer Accuracy** | Good | Better (grounded in graph) |
+| **Hallucination Risk** | Medium | Lower |
+| **Complex Queries** | Limited | Excellent |
+| **Relationship Awareness** | No | Yes |
+
+**Practical Examples**:
+
+=== "Basic GraphRAG"
+ Build a knowledge base and query with GraphRAG:
+
+ ```python
+ from semantica import Semantica
+ from semantica.vector_store import VectorStore, store_vectors, search_vectors
+ from semantica.semantic_extract import NamedEntityRecognizer
+ from semantica.embeddings import embed_text
+
+ # Initialize Semantica
+ semantica = Semantica()
+
+ # Build knowledge base from documents
+ result = semantica.build_knowledge_base(
+ sources=["company_docs/", "research_papers/"],
+ embeddings=True,
+ graph=True
+ )
+
+ kg = result["knowledge_graph"]
+ embeddings_data = result["embeddings"]
+
+ # Initialize vector store
+ vector_store = VectorStore(backend="faiss", dimension=768)
+
+ # Store embeddings
+ vector_ids = vector_store.store_vectors(
+ vectors=embeddings_data["vectors"],
+ metadata=embeddings_data["metadata"]
+ )
+
+ # Initialize NER for query processing
+ ner = NamedEntityRecognizer()
+
+ # Process a query
+ query = "Who is the CEO of Apple?"
+
+ # Get query embedding and search
+ query_embedding = embed_text(query, method="sentence_transformers")
+ vector_results = vector_store.search(query_embedding, k=5)
+
+ # Extract entities from query
+ query_entities = ner.extract_entities(query)
+
+ # Get graph context for query entities
+ graph_context = []
+ for entity in query_entities:
+ for rel in kg["relationships"]:
+ if entity["text"].lower() in rel.get("source_text", "").lower():
+ graph_context.append(rel)
+
+ print(f"Vector results: {len(vector_results)}")
+ print(f"Graph context: {len(graph_context)} relevant relationships")
+ ```
+
+=== "Context Retrieval"
+ Use the context module for agent memory and retrieval:
+
+ ```python
+ from semantica.context import (
+ ContextRetriever,
+ AgentMemory,
+ ContextGraphBuilder,
+ build_context
+ )
+ from semantica.vector_store import VectorStore
+
+ # Initialize vector store
+ vector_store = VectorStore(backend="faiss", dimension=768)
+
+ # Build context graph
+ context_result = build_context(
+ entities=kg["entities"],
+ relationships=kg["relationships"],
+ vector_store=vector_store,
+ knowledge_graph=kg,
+ store_initial_memories=True
+ )
+
+ print(f"Built context with {context_result['statistics']['graph'].get('node_count', 0)} nodes")
+
+ # Initialize agent memory
+ memory = AgentMemory(
+ vector_store=vector_store,
+ knowledge_graph=kg
+ )
+
+ # Store facts in memory
+ memory_id = memory.store(
+ "Tim Cook is the CEO of Apple Inc.",
+ metadata={"type": "fact", "source": "document"}
+ )
+ print(f"Stored memory: {memory_id}")
+
+ # Initialize context retriever
+ retriever = ContextRetriever(
+ vector_store=vector_store,
+ knowledge_graph=kg
+ )
+
+ # Retrieve relevant context
+ results = retriever.retrieve(
+ query="Who leads Apple?",
+ max_results=10
+ )
+
+ print("Retrieved context:")
+ for r in results:
+ print(f" {r.content} (score: {r.score:.2f})")
+ ```
+
+=== "Hybrid Search"
+ Combine vector and metadata search:
+
+ ```python
+ from semantica.vector_store import (
+ VectorStore,
+ HybridSearch,
+ MetadataFilter,
+ MetadataStore
+ )
+ from semantica.embeddings import embed_text
+
+ # Initialize stores
+ vector_store = VectorStore(backend="faiss", dimension=768)
+ metadata_store = MetadataStore()
+ hybrid_search = HybridSearch()
+
+ # Generate query embedding
+ query_embedding = embed_text("Apple CEO responsibilities", method="sentence_transformers")
+
+ # Create metadata filter
+ metadata_filter = MetadataFilter()
+ metadata_filter.eq("entity_type", "Person")
+ metadata_filter.eq("relationship", "CEO_OF")
+
+ # Get stored data
+ all_vectors = vector_store.get_all_vectors()
+ all_metadata = metadata_store.get_all()
+ all_ids = vector_store.get_all_ids()
+
+ # Perform hybrid search
+ results = hybrid_search.search(
+ query_vector=query_embedding,
+ vectors=all_vectors,
+ metadata=all_metadata,
+ vector_ids=all_ids,
+ filter=metadata_filter,
+ top_k=10
+ )
+
+ print("Hybrid search results:")
+ for result in results:
+ print(f" ID: {result['id']}, Score: {result['score']:.3f}")
+ ```
+
+=== "Reasoning with Inference"
+ Use the reasoning module for graph inference:
+
+ ```python
+ from semantica.reasoning import (
+ InferenceEngine,
+ RuleManager,
+ Rule,
+ ExplanationGenerator
+ )
+
+ # Initialize engine and rule manager
+ engine = InferenceEngine()
+ rule_manager = RuleManager()
+
+ # Add inference rules
+ rule_manager.add_rule(Rule(
+ name="ceo_works_for",
+ conditions=["?person CEO_OF ?company"],
+ conclusions=["?person WORKS_FOR ?company"],
+ priority=1
+ ))
+
+ rule_manager.add_rule(Rule(
+ name="transitivity",
+ conditions=["?a PART_OF ?b", "?b PART_OF ?c"],
+ conclusions=["?a PART_OF ?c"],
+ priority=2
+ ))
+
+ # Define facts
+ facts = [
+ {"subject": "Tim Cook", "predicate": "CEO_OF", "object": "Apple"},
+ {"subject": "iPhone", "predicate": "PART_OF", "object": "Apple"},
+ {"subject": "A15 Chip", "predicate": "PART_OF", "object": "iPhone"}
+ ]
+
+ # Run inference
+ inferred = engine.infer(
+ facts=facts,
+ rules=rule_manager.get_rules(),
+ strategy="forward"
+ )
+
+ print(f"Original facts: {len(facts)}")
+ print(f"After inference: {len(inferred.facts)}")
+
+ # Generate explanations
+ explainer = ExplanationGenerator()
+ for new_fact in inferred.new_facts:
+ explanation = explainer.generate_explanation(
+ conclusion=new_fact,
+ reasoning_path=inferred.reasoning_path
+ )
+ print(f" {new_fact}: {explanation.summary}")
+ ```
+
+=== "LLM-Enhanced Retrieval"
+ Integrate with LLM providers for answer generation:
+
+ ```python
+ from semantica import Semantica
+ from semantica.semantic_extract import create_provider, OpenAIProvider
+ from semantica.context import ContextRetriever
+ from semantica.vector_store import VectorStore
+
+ # Initialize components
+ vector_store = VectorStore(backend="faiss", dimension=768)
+
+ # Create LLM provider
+ provider = create_provider(
+ provider_type="openai",
+ model="gpt-4o"
+ )
+
+ # Initialize context retriever
+ retriever = ContextRetriever(
+ vector_store=vector_store,
+ knowledge_graph=kg
+ )
+
+ # Define question
+ question = "What products does Apple manufacture?"
+
+ # Retrieve relevant context
+ context = retriever.retrieve(query=question, max_results=5)
+
+ # Format context for prompt
+ context_text = "\n".join([
+ f"- {c.content}" for c in context
+ ])
+
+ # Build prompt
+ prompt = f"""Based on this context, answer the question.
+
+Context:
+{context_text}
+
+Question: {question}
+
+Answer:"""
+
+ # Generate response
+ response = provider.generate(prompt)
+ print(f"Answer: {response}")
+ ```
+
+**Related Modules**:
+- [`kg` Module](reference/kg.md) - Knowledge graph construction
+- [`vector_store` Module](reference/vector_store.md) - Vector search
+- [`reasoning` Module](reference/reasoning.md) - Graph reasoning
+
+---
+
+### 7. Ontology
+
+!!! abstract "Definition"
+ An **Ontology** is a formal specification of concepts, relationships, and constraints in a domain, typically expressed in OWL (Web Ontology Language). It defines the schema and structure of your knowledge domain.
+
+**Key Components**:
+
+- **Classes**: Categories of entities (e.g., `Person`, `Company`, `Location`)
+- **Properties**: Relationships and attributes (e.g., `worksFor`, `hasName`)
+- **Individuals**: Specific instances (e.g., `John Doe`, `Apple Inc.`)
+- **Axioms**: Rules and constraints (e.g., "A Person can only workFor one Company")
+
+**Ontology Structure**:
+
+```mermaid
+classDiagram
+ class Person {
+ +String name
+ +Date birthDate
+ +worksFor Company
+ }
+ class Company {
+ +String name
+ +Date founded
+ +locatedIn Location
+ }
+ class Location {
+ +String city
+ +String country
+ }
+
+ Person --> Company : worksFor
+ Company --> Location : locatedIn
+```
+
+**Practical Examples**:
+
+=== "Automatic Ontology Generation"
+ Generate an ontology from your knowledge graph:
+
+ ```python
+ from semantica.ontology import OntologyGenerator, generate_ontology
+
+ # Your knowledge graph data
+ kg_data = {
+ "entities": [
+ {"id": "e1", "text": "Apple Inc.", "type": "Company"},
+ {"id": "e2", "text": "Tim Cook", "type": "Person"},
+ {"id": "e3", "text": "iPhone", "type": "Product"},
+ {"id": "e4", "text": "Cupertino", "type": "Location"}
+ ],
+ "relationships": [
+ {"source": "e2", "target": "e1", "type": "CEO_OF"},
+ {"source": "e1", "target": "e3", "type": "MANUFACTURES"},
+ {"source": "e1", "target": "e4", "type": "HEADQUARTERED_IN"}
+ ]
+ }
+
+ # Method 1: Using convenience function
+ ontology = generate_ontology(kg_data, method="default")
+ print(f"Quick generation: {len(ontology.get('classes', []))} classes")
+
+ # Method 2: Using OntologyGenerator class for more control
+ generator = OntologyGenerator(
+ base_uri="https://example.org/ontology/",
+ version="1.0.0"
+ )
+
+ ontology = generator.generate_ontology(kg_data)
+
+ print(f"Generated Ontology:")
+ print(f" Classes: {len(ontology['classes'])}")
+ print(f" Properties: {len(ontology['properties'])}")
+ print(f" Axioms: {len(ontology.get('axioms', []))}")
+
+ # Display class details
+ print("Classes:")
+ for cls in ontology['classes']:
+ print(f" {cls['name']}")
+ print(f" URI: {cls['uri']}")
+ if cls.get('parent'):
+ print(f" Parent: {cls['parent']}")
+ ```
+
+=== "Class and Property Inference"
+ Automatically infer classes and properties from data:
+
+ ```python
+ from semantica.ontology import (
+ ClassInferrer,
+ PropertyGenerator,
+ infer_classes,
+ infer_properties
+ )
+
+ # Sample entities
+ entities = [
+ {"text": "Apple", "type": "Company"},
+ {"text": "Microsoft", "type": "Company"},
+ {"text": "Google", "type": "Company"},
+ {"text": "Tim Cook", "type": "Person"},
+ {"text": "Satya Nadella", "type": "Person"},
+ {"text": "iPhone", "type": "Product"},
+ {"text": "Windows", "type": "Product"},
+ ]
+
+ # Method 1: Using convenience function
+ classes = infer_classes(entities, method="default")
+
+ # Method 2: Using ClassInferrer for more control
+ class_inferrer = ClassInferrer(
+ min_occurrence=2, # Minimum entities to create a class
+ merge_similar=True,
+ similarity_threshold=0.8
+ )
+
+ classes = class_inferrer.infer_classes(entities)
+
+ print("Inferred Classes:")
+ for cls in classes:
+ print(f" {cls['name']}: {cls['instance_count']} instances")
+
+ # Infer properties from relationships
+ relationships = [
+ {"source_type": "Person", "target_type": "Company", "type": "CEO_OF"},
+ {"source_type": "Company", "target_type": "Product", "type": "MANUFACTURES"},
+ {"source_type": "Person", "target_type": "Company", "type": "WORKS_FOR"},
+ ]
+
+ # Using PropertyGenerator
+ prop_generator = PropertyGenerator()
+ properties = prop_generator.infer_properties(entities, relationships, classes)
+
+ print("Inferred Properties:")
+ for prop in properties:
+ print(f" {prop['name']}")
+ print(f" Domain: {prop['domain']} -> Range: {prop['range']}")
+ print(f" Type: {prop['property_type']}")
+ ```
+
+=== "OWL/RDF Generation"
+ Generate OWL ontologies in various formats:
+
+ ```python
+ from semantica.ontology import OWLGenerator, generate_owl
+
+ # Initialize OWL generator
+ owl_gen = OWLGenerator(
+ base_uri="https://example.org/onto/",
+ output_format="turtle" # turtle, rdf-xml, json-ld, n3
+ )
+
+ # Define ontology classes
+ owl_gen.add_class("Person", parent="Thing")
+ owl_gen.add_class("Company", parent="Thing")
+ owl_gen.add_class("CEO", parent="Person")
+
+ # Add object properties
+ owl_gen.add_object_property(
+ name="worksFor",
+ domain="Person",
+ range="Company"
+ )
+
+ owl_gen.add_object_property(
+ name="isCEOOf",
+ domain="CEO",
+ range="Company",
+ functional=True # A CEO can only be CEO of one company
+ )
+
+ # Add data properties
+ owl_gen.add_data_property(
+ name="hasName",
+ domain="Person",
+ range="xsd:string"
+ )
+
+ owl_gen.add_data_property(
+ name="foundedYear",
+ domain="Company",
+ range="xsd:integer"
+ )
+
+ # Add axioms/constraints
+ owl_gen.add_axiom(
+ class_name="CEO",
+ axiom="SubClassOf: worksFor exactly 1 Company"
+ )
+
+ # Generate Turtle output
+ turtle_output = owl_gen.serialize()
+ print(turtle_output)
+
+ # Example output:
+ # @prefix : <https://example.org/onto/> .
+ # @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ # :Person a owl:Class .
+ # :Company a owl:Class .
+ # :CEO a owl:Class ; rdfs:subClassOf :Person .
+
+ # Save to file
+ owl_gen.save("company_ontology.ttl")
+ print("Ontology saved to company_ontology.ttl")
+ ```
+
+=== "Ontology Validation"
+ Validate ontologies with symbolic reasoners:
+
+ ```python
+ from semantica.ontology import OntologyValidator, validate_ontology
+
+ # Load or create ontology
+ ontology_file = "company_ontology.ttl"
+
+ # Method 1: Using the convenience function
+ result = validate_ontology(ontology_file, method="default")
+ print(f"Quick validation: {'Valid' if result['valid'] else 'Invalid'}")
+
+ # Method 2: Using OntologyValidator for more control
+ validator = OntologyValidator(
+ reasoner="hermit", # hermit, pellet, or auto
+ check_consistency=True,
+ check_satisfiability=True
+ )
+
+ # Validate the ontology
+ validation_result = validator.validate(ontology_file)
+
+ print(f"Validation Results:")
+ print(f" Consistent: {'Yes' if validation_result.consistent else 'No'}")
+ print(f" Satisfiable: {'Yes' if validation_result.satisfiable else 'No'}")
+
+ if validation_result.errors:
+ print(f"Errors ({len(validation_result.errors)}):")
+ for error in validation_result.errors:
+ print(f" - {error}")
+
+ if validation_result.warnings:
+ print(f"Warnings ({len(validation_result.warnings)}):")
+ for warning in validation_result.warnings:
+ print(f" - {warning}")
+
+ # Check specific constraints
+ constraints = [
+ "Every CEO must work for exactly one Company",
+ "A Person cannot be their own manager"
+ ]
+
+ for constraint in constraints:
+ is_valid = validator.check_constraint(constraint)
+ status = "PASS" if is_valid else "FAIL"
+ print(f" [{status}] {constraint}")
+ ```
+
+=== "Competency Questions"
+ Define and evaluate competency questions:
+
+ ```python
+ from semantica.ontology import (
+ CompetencyQuestionsManager,
+ CompetencyQuestion,
+ OntologyEvaluator
+ )
+
+ # Initialize competency questions manager
+ cq_manager = CompetencyQuestionsManager()
+
+ # Add questions your ontology should be able to answer
+ cq_manager.add_question(CompetencyQuestion(
+ question="Who is the CEO of a given company?",
+ category="organizational",
+ priority=1, # 1=high, 2=medium, 3=low
+ expected_elements=["Person", "Company", "isCEOOf"]
+ ))
+
+ cq_manager.add_question(CompetencyQuestion(
+ question="What products does a company manufacture?",
+ category="products",
+ priority=1,
+ expected_elements=["Company", "Product", "manufactures"]
+ ))
+
+ cq_manager.add_question(CompetencyQuestion(
+ question="Where is a company headquartered?",
+ category="location",
+ priority=2,
+ expected_elements=["Company", "Location", "headquarteredIn"]
+ ))
+
+ # Get all questions
+ questions = cq_manager.get_questions()
+ print(f"Defined {len(questions)} competency questions")
+
+ # Evaluate ontology against competency questions
+ evaluator = OntologyEvaluator()
+ evaluation = evaluator.evaluate(
+ ontology="company_ontology.ttl",
+ competency_questions=questions
+ )
+
+ print(f"Ontology Evaluation:")
+ print(f" Coverage Score: {evaluation.coverage_score:.1%}")
+ print(f" Completeness Score: {evaluation.completeness_score:.1%}")
+
+ print("Question Coverage:")
+ for result in evaluation.question_results:
+ status = "YES" if result['answerable'] else "NO"
+ print(f" [{status}] {result['question']}")
+ if not result['answerable'] and result.get('missing_elements'):
+ print(f" Missing: {', '.join(result['missing_elements'])}")
+ ```
-- **Nodes**: Represent entities (people, places, concepts, events)
-- **Edges**: Represent relationships (works_for, located_in, causes)
-- **Properties**: Attributes of entities and relationships
-- **Metadata**: Additional information (sources, timestamps, confidence)
+=== "Domain Ontologies"
+ Use pre-built domain ontologies:
+
+ ```python
+ from semantica.ontology import DomainOntologies, OWLGenerator
+
+ # Access pre-built domain ontologies
+ domains = DomainOntologies()
+
+ # List available domains
+ print("Available Domain Ontologies:")
+ for domain in domains.list_domains():
+ print(f" - {domain['name']}: {domain['description']}")
+
+ # Load healthcare ontology
+ healthcare_onto = domains.load("healthcare")
+
+ print(f"Healthcare Ontology:")
+ print(f" Classes: {len(healthcare_onto.get('classes', []))}")
+ print(f" Properties: {len(healthcare_onto.get('properties', []))}")
+
+ # Extend the ontology
+ owl_gen = OWLGenerator(base_uri="https://example.org/healthcare/")
+ owl_gen.add_class("MedicalDevice", parent="Equipment")
+
+ # Load and merge multiple ontologies
+ finance_onto = domains.load("finance")
+ merged = domains.merge([healthcare_onto, finance_onto])
+
+ print(f"Merged ontology: {len(merged.get('classes', []))} classes")
+
+ # Find alignments between ontologies
+ alignments = domains.find_alignments(
+ healthcare_onto,
+ finance_onto,
+ similarity_threshold=0.7
+ )
+
+ print(f"Found {len(alignments)} concept alignments:")
+ for align in alignments[:5]:
+ print(f" {align['source']} ~ {align['target']} ({align['similarity']:.2f})")
+ ```
-??? info "Deep Dive: Graph Theory Basics"
- At its core, a knowledge graph is a directed multigraph $G = (V, E)$ where:
- - $V$ is a set of vertices (entities)
- - $E$ is a set of edges (relationships)
- - Edges are directed: $(u, v) \in E$ implies a relationship from $u$ to $v$.
- - Multigraph property allows multiple edges between the same pair of vertices (e.g., "Friend" and "Colleague").
+**Related Modules**:
+- [`ontology` Module](reference/ontology.md) - Ontology generation and management
+- [`kg` Module](reference/kg.md) - Knowledge graph construction
-**Benefits**:
-- Structured representation of unstructured data
-- Enables complex queries and reasoning
-- Supports temporal tracking
-- Facilitates knowledge discovery
+---
-```mermaid
-graph LR
- A[Apple Inc.<br/>Organization] -->|founded_by| B[Steve Jobs<br/>Person]
- A -->|located_in| C[Cupertino<br/>Location]
- C -->|in_state| D[California<br/>Location]
-
- style A fill:#e3f2fd,stroke:#1565c0
- style B fill:#fff3e0,stroke:#ef6c00
- style C fill:#f3e5f5,stroke:#7b1fa2
- style D fill:#f3e5f5,stroke:#7b1fa2
-```
+### 8. Quality Assurance
-### 2. Entity Extraction (NER)
+!!! abstract "Definition"
+ **Quality Assurance** encompasses processes and metrics to ensure knowledge graph quality, including completeness, consistency, accuracy, and coverage validation.
-**Definition**: The process of identifying and classifying named entities in text into predefined categories.
+**Quality Dimensions**:
-| Entity Type | Description | Example |
+| Dimension | Description | Metrics |
| :--- | :--- | :--- |
-| **Person** | Names of people | Steve Jobs, Elon Musk |
-| **Organization** | Companies, institutions | Apple Inc., NASA |
-| **Location** | Places, geographic entities | Cupertino, Mars |
-| **Date/Time** | Temporal expressions | 1976, next Monday |
-| **Money** | Monetary values | $100 million |
-| **Event** | Events and occurrences | WWDC 2024 |
+| **Completeness** | Percentage of entities with required properties | Property coverage, missing fields |
+| **Consistency** | Absence of contradictions | Conflict count, validation errors |
+| **Accuracy** | Correctness of extracted information | Precision, recall, F1-score |
+| **Coverage** | Breadth of domain coverage | Entity diversity, relationship types |
+| **Freshness** | How up-to-date the data is | Last update timestamp, staleness |
-!!! tip "Custom Entities"
- Semantica allows you to define custom entity types via the `Ontology` module. You aren't limited to the standard set!
+**Practical Examples**:
-**Methods**:
-- **Rule-based**: Pattern matching (Regex)
-- **Machine Learning**: Trained models (spaCy, transformers)
-- **LLM-based**: Using large language models (GPT-4, Claude)
+=== "Quality Assessment"
+ Assess the quality of your knowledge graph:
+
+ ```python
+ from semantica import (
+ KGQualityAssessor,
+ QualityMetrics,
+ CompletenessMetrics,
+ ConsistencyMetrics
+ )
+
+ # Initialize quality assessor
+ assessor = KGQualityAssessor()
+
+ # Run comprehensive quality assessment
+ quality_report = assessor.assess(kg)
+
+ print("Knowledge Graph Quality Report")
+ print(f"Overall Score: {quality_report['overall_score']:.1%}")
+
+ # Completeness analysis
+ completeness = quality_report['completeness']
+ print(f"Completeness: {completeness['score']:.1%}")
+ print(f" Entities with all required fields: {completeness['complete_entities']}/{completeness['total_entities']}")
+ print(f" Missing fields: {completeness['missing_fields']}")
+
+ # Consistency analysis
+ consistency = quality_report['consistency']
+ print(f"Consistency: {consistency['score']:.1%}")
+ print(f" Conflicts detected: {consistency['conflict_count']}")
+ print(f" Type mismatches: {consistency['type_mismatches']}")
+
+ # Coverage analysis
+ coverage = quality_report['coverage']
+ print(f"Coverage: {coverage['score']:.1%}")
+ print(f" Entity types: {coverage['entity_type_count']}")
+ print(f" Relationship types: {coverage['relationship_type_count']}")
+ print(f" Orphaned entities: {coverage['orphaned_count']}")
+ ```
-### 3. Relationship Extraction
+=== "Validation and Constraints"
+ Validate your graph against rules and constraints:
+
+ ```python
+ from semantica import ValidationEngine, ConstraintValidator
+ from semantica.kg import GraphValidator
+
+ # Initialize validation engine
+ validator = ValidationEngine()
+ graph_validator = GraphValidator()
+
+ # Define custom validation rules
+ rules = [
+ {
+ "name": "entity_has_type",
+ "description": "Every entity must have a type",
+ "check": lambda e: "type" in e and e["type"]
+ },
+ {
+ "name": "relationship_has_valid_endpoints",
+ "description": "Relationships must reference existing entities",
+ "check": lambda r, entities: r["source"] in entities and r["target"] in entities
+ },
+ {
+ "name": "person_has_name",
+ "description": "Person entities must have a name property",
+ "check": lambda e: e.get("type") != "Person" or "name" in e.get("properties", {})
+ }
+ ]
+
+ # Run validation with custom rules
+ results = validator.validate(kg, rules=rules)
+
+ print("Validation Results:")
+ for rule_name, result in results['rule_results'].items():
+ status = "PASS" if result['passed'] else "FAIL"
+ print(f"[{status}] {rule_name}")
+ if not result['passed']:
+ print(f" Failed: {len(result['violations'])} violations")
+ for v in result['violations'][:3]:
+ print(f" - {v['entity_id']}: {v['message']}")
+
+ # Validate graph structure
+ graph_result = graph_validator.validate(kg)
+ print(f"Graph Valid: {graph_result['valid']}")
+ if graph_result['errors']:
+ for error in graph_result['errors'][:3]:
+ print(f" Error: {error}")
+
+ # Check cardinality constraints
+ constraint_validator = ConstraintValidator()
+ constraint_results = constraint_validator.validate(kg, [
+ {"property": "CEO_OF", "max_cardinality": 1},
+ {"property": "WORKS_FOR", "min_cardinality": 0, "max_cardinality": 3}
+ ])
+ ```
+
+=== "Automated Fixes"
+ Automatically fix common quality issues:
+
+ ```python
+ from semantica import AutomatedFixer, IssueTracker, KGQualityAssessor
+
+ # Track and find issues
+ tracker = IssueTracker()
+ issues = tracker.find_issues(kg)
+
+ print(f"Found {len(issues)} issues:")
+ for issue in issues[:5]:
+ print(f" [{issue['severity']}] {issue['type']}: {issue['message']}")
+
+ # Initialize fixer
+ fixer = AutomatedFixer()
+
+ # Apply automated fixes
+ fixed_kg, fix_report = fixer.fix(
+ kg,
+ fix_types=[
+ "missing_entity_type",
+ "orphaned_relationships",
+ "duplicate_relationships",
+ "empty_properties"
+ ],
+ dry_run=False
+ )
+
+ print(f"Applied {fix_report['fixes_applied']} fixes:")
+ for fix_type, count in fix_report['by_type'].items():
+ print(f" {fix_type}: {count}")
+
+ # Measure quality improvement
+ assessor = KGQualityAssessor()
+ quality_after = assessor.assess(fixed_kg)
+ print(f"Quality after fixes: {quality_after['overall_score']:.1%}")
+ ```
+
+=== "Quality Reporting"
+ Generate detailed quality reports:
+
+ ```python
+ from semantica import QualityReporter, ImprovementSuggestions
+
+ # Initialize reporter
+ reporter = QualityReporter()
+
+ # Generate HTML report
+ reporter.generate_report(
+ kg,
+ output_path="quality_report.html",
+ format="html",
+ include_visualizations=True
+ )
+
+ # Generate JSON report for programmatic use
+ json_report = reporter.generate_report(kg, format="json")
+
+ print(f"Report generated with {len(json_report.get('sections', []))} sections")
+
+ # Get improvement suggestions
+ suggestions = ImprovementSuggestions()
+ recommendations = suggestions.analyze(kg)
+
+ print("Improvement Suggestions:")
+ for rec in recommendations:
+ print(f" Priority {rec['priority']}: {rec['suggestion']}")
+ print(f" Impact: {rec['expected_improvement']}")
+ print(f" Effort: {rec['effort_level']}")
+ ```
-**Definition**: Identifying and extracting relationships between entities in text.
+**Related Modules**:
+- [`kg_qa` Module](reference/evals.md) - Quality assurance and evaluation
+- [`conflicts` Module](../semantica/conflicts/conflicts_usage.md) - Conflict detection
-=== "Semantic"
- Relationships that define meaning and connection.
- - `works_for`
- - `located_in`
- - `founded_by`
+---
-=== "Temporal"
- Relationships defined by time.
- - `happened_before`
- - `happened_after`
- - `during`
+### 9. Deduplication & Entity Resolution
-=== "Causal"
- Cause and effect relationships.
- - `causes`
- - `results_in`
- - `prevents`
+!!! abstract "Definition"
+ **Deduplication** and **Entity Resolution** are processes that identify and merge duplicate entities in a knowledge graph, ensuring that the same real-world entity is represented by a single node.
-### 4. Embeddings
+**Why It Matters**:
-**Definition**: Dense vector representations of text, images, or other data that capture semantic meaning in a continuous vector space.
+- Multiple sources may refer to the same entity differently
+- "Apple Inc." vs "Apple" vs "Apple Computer" → Same entity
+- Prevents graph fragmentation and improves query accuracy
-> [!NOTE]
-> Embeddings are the bridge between human language and machine understanding.
+**Resolution Process**:
-**Example**:
-```python
-Text: "machine learning"
-Embedding: [0.123, -0.456, 0.789, ..., 0.234]
-# (vector of 1536 dimensions)
-```
+Deduplication works by calculating similarity between entities. If similarity exceeds a threshold, entities are merged; otherwise, they remain separate.
-### 5. Temporal Graphs
+**Practical Examples**:
+
+=== "Entity Resolution"
+ Identify and resolve duplicate entities:
+
+ ```python
+ from semantica.kg import EntityResolver, Deduplicator, resolve_entities
+
+ # Sample entities with potential duplicates
+ entities = [
+ {"id": "e1", "text": "Apple Inc.", "type": "Organization"},
+ {"id": "e2", "text": "Apple", "type": "Organization"},
+ {"id": "e3", "text": "Apple Computer, Inc.", "type": "Organization"},
+ {"id": "e4", "text": "Microsoft", "type": "Organization"},
+ {"id": "e5", "text": "MSFT", "type": "Organization"},
+ {"id": "e6", "text": "Microsoft Corporation", "type": "Organization"},
+ ]
+
+ # Method 1: Using convenience function
+ resolved = resolve_entities(entities, method="fuzzy")
+
+ # Method 2: Using EntityResolver class for more control
+ resolver = EntityResolver(
+ strategy="fuzzy", # "exact", "fuzzy", or "semantic"
+ similarity_threshold=0.85,
+ use_embeddings=True
+ )
+
+ # Find duplicate groups
+ duplicate_groups = resolver.find_duplicates(entities)
+
+ print("Duplicate Groups Found:")
+ for i, group in enumerate(duplicate_groups, 1):
+ print(f"Group {i}:")
+ for entity in group['entities']:
+ print(f" - {entity['text']} (id: {entity['id']})")
+ print(f" Confidence: {group['confidence']:.2f}")
+ ```
+
+=== "Semantic Matching"
+ Use embeddings for semantic similarity matching:
+
+ ```python
+ from semantica.kg import EntityResolver
+ from semantica.embeddings import EmbeddingGenerator
+
+ # Initialize with semantic matching
+ generator = EmbeddingGenerator()
+
+ resolver = EntityResolver(
+ strategy="semantic",
+ embedding_generator=generator,
+ similarity_threshold=0.8
+ )
+
+ # Entities with semantic variations
+ entities = [
+ {"id": "e1", "text": "Chief Executive Officer", "type": "Title"},
+ {"id": "e2", "text": "CEO", "type": "Title"},
+ {"id": "e3", "text": "Managing Director", "type": "Title"},
+ {"id": "e4", "text": "Head of the Company", "type": "Title"},
+ {"id": "e5", "text": "Software Developer", "type": "Title"},
+ {"id": "e6", "text": "Programmer", "type": "Title"},
+ ]
+
+ # Find semantically similar entities
+ semantic_matches = resolver.find_semantic_matches(entities)
+
+ print("Semantic Matches:")
+ for match in semantic_matches:
+ print(f" {match['entity1']['text']} ~ {match['entity2']['text']}")
+ print(f" Similarity: {match['similarity']:.3f}")
+
+ clusters = resolver.cluster_entities(
+ entities,
+ method="semantic",
+ min_cluster_size=2
+ )
+
+ print(f"Found {len(clusters)} semantic clusters")
+ ```
+
+=== "Graph Deduplication"
+ Deduplicate an entire knowledge graph:
+
+ ```python
+ from semantica.kg import Deduplicator, deduplicate_graph
+
+ # Method 1: Using convenience function
+ dedup_result = deduplicate_graph(kg, method="default")
+
+ # Method 2: Using Deduplicator class for more control
+ deduplicator = Deduplicator(
+ entity_similarity_threshold=0.85,
+ relationship_merge_strategy="union", # "union", "intersection", "first"
+ preserve_provenance=True
+ )
+
+ # Deduplicate the knowledge graph
+ dedup_result = deduplicator.deduplicate(kg)
+
+ print("Deduplication Results:")
+ print(f" Original entities: {dedup_result['original_entity_count']}")
+ print(f" After dedup: {dedup_result['final_entity_count']}")
+ print(f" Duplicates merged: {dedup_result['merged_count']}")
+ print(f" Reduction: {dedup_result['reduction_percent']:.1f}%")
+
+ # Get deduplicated graph
+ clean_kg = dedup_result['graph']
+
+ print("Merge Details:")
+ for merge in dedup_result['merges'][:5]:
+ print(f" Merged {len(merge['source_ids'])} entities -> {merge['canonical_id']}")
+ print(f" Canonical: {merge['canonical_text']}")
+ print(f" Aliases: {', '.join(merge['aliases'])}")
+ ```
+
+=== "Custom Matching Rules"
+ Define custom matching rules for your domain:
+
+ ```python
+ from semantica.kg import EntityResolver
+
+ # Define custom matching rules
+ custom_rules = {
+ "Organization": {
+ "normalize": [
+ ("Inc.", ""),
+ ("Corp.", ""),
+ ("Corporation", ""),
+ ("LLC", ""),
+ ("Ltd.", ""),
+ ],
+ "abbreviations": {
+ "IBM": "International Business Machines",
+ "GE": "General Electric",
+ "HP": "Hewlett-Packard",
+ },
+ "threshold": 0.8
+ },
+ "Person": {
+ "match_fields": ["name", "email"],
+ "normalize_case": True,
+ "threshold": 0.9
+ },
+ "Location": {
+ "normalize": [
+ ("St.", "Street"),
+ ("Ave.", "Avenue"),
+ ("Blvd.", "Boulevard"),
+ ],
+ "threshold": 0.85
+ }
+ }
+
+ resolver = EntityResolver(
+ strategy="rule_based",
+ custom_rules=custom_rules
+ )
+
+ # Apply custom rules
+ entities = [
+ {"id": "e1", "text": "Apple Inc.", "type": "Organization"},
+ {"id": "e2", "text": "Apple Corporation", "type": "Organization"},
+ {"id": "e3", "text": "International Business Machines", "type": "Organization"},
+ {"id": "e4", "text": "IBM", "type": "Organization"},
+ ]
+
+ matches = resolver.find_duplicates(entities)
+
+ print("Rule-Based Matches:")
+ for match in matches:
+ print(f" {match['entities'][0]['text']} = {match['entities'][1]['text']}")
+ print(f" Rule: {match['matched_rule']}")
+ ```
+
+=== "Merge Strategies"
+ Control how entities are merged:
+
+ ```python
+ from semantica.kg import EntityResolver
+
+ resolver = EntityResolver(strategy="fuzzy", similarity_threshold=0.85)
+
+ # Define merge strategy
+ merged_entity = resolver.merge_entities(
+ entities=[
+ {"id": "e1", "text": "Apple", "properties": {"founded": 1976}},
+ {"id": "e2", "text": "Apple Inc.", "properties": {"ceo": "Tim Cook"}},
+ {"id": "e3", "text": "Apple Computer", "properties": {"founded": 1976, "industry": "Tech"}}
+ ],
+ strategy={
+ "id": "keep_first", # Use first entity's ID
+ "text": "most_complete", # Use longest/most complete text
+ "properties": "merge_all", # Combine all properties
+ "conflicts": "keep_latest" # For conflicting values, keep latest
+ }
+ )
+
+ print("Merged Entity:")
+ print(f" ID: {merged_entity['id']}")
+ print(f" Text: {merged_entity['text']}")
+ print(f" Properties: {merged_entity['properties']}")
+ print(f" Source IDs: {merged_entity['source_ids']}")
+ ```
+
+**Related Modules**:
+- [`deduplication` Module](../semantica/deduplication/deduplication_usage.md) - Deduplication and merging
+- [`embeddings` Module](reference/embeddings.md) - Similarity calculation
+
+---
+
+### 10. Data Normalization
-**Definition**: Knowledge graphs that track changes over time, allowing queries about the state of the graph at specific time points.
+!!! abstract "Definition"
+ **Data Normalization** is the process of cleaning and standardizing data into a consistent format, ensuring uniformity across your knowledge graph.
+
+**Normalization Pipeline**:
```mermaid
-timeline
- title Temporal Graph Evolution
- 2020 : Entity A created
- : Relationship A->B
- 2021 : Entity B updated
- : Relationship B->C
- 2022 : Entity A deleted
- : New Relationship D->C
+flowchart LR
+ Raw[Raw Text] --> Clean[Text Cleaning]
+ Clean --> Entity[Entity<br/>Normalization]
+ Entity --> Date[Date<br/>Normalization]
+ Date --> Number[Number<br/>Normalization]
+ Number --> Normalized[Normalized<br/>Data]
+
+ style Raw fill:#ffcdd2
+ style Normalized fill:#c8e6c9
```
-### 6. GraphRAG
+**Practical Examples**:
+
+=== "Text Normalization"
+ Clean and normalize text data:
+
+ ```python
+ from semantica.normalize import TextNormalizer
+
+ normalizer = TextNormalizer(
+ lowercase=True,
+ remove_punctuation=False,
+ remove_extra_whitespace=True,
+ unicode_normalize=True,
+ expand_contractions=True
+ )
+
+ # Normalize text
+ raw_texts = [
+ " Apple Inc. was founded in 1976!! ",
+ "The iPhone's really great, isn't it?",
+ "Microsoft™ announced Windows® 11",
+ "café, naïve, résumé — special chars"
+ ]
+
+ for raw in raw_texts:
+ normalized = normalizer.normalize(raw)
+ print(f"Before: {raw!r}")
+ print(f"After: {normalized!r}\n")
+
+ # Batch normalization
+ normalized_batch = normalizer.normalize_batch(raw_texts)
+ ```
-**Definition**: An advanced RAG (Retrieval Augmented Generation) approach that combines vector search with knowledge graph traversal to provide more accurate and contextually relevant information to LLMs.
+=== "Entity Normalization"
+ Standardize entity names and types:
+
+ ```python
+ from semantica.normalize import EntityNormalizer
+
+ normalizer = EntityNormalizer(
+ case_style="title", # "title", "upper", "lower", "preserve"
+ remove_suffixes=["Inc.", "Corp.", "LLC", "Ltd."],
+ remove_prefixes=["The"],
+ normalize_whitespace=True
+ )
+
+ # Normalize entity names
+ entities = [
+ {"text": " THE apple INC. ", "type": "Organization"},
+ {"text": "MICROSOFT CORPORATION", "type": "Organization"},
+ {"text": "tim cook", "type": "Person"},
+ {"text": " new york city ", "type": "Location"}
+ ]
+
+ normalized = normalizer.normalize_entities(entities)
+
+ print("Normalized Entities:")
+ for orig, norm in zip(entities, normalized):
+ print(f" {orig['text']!r} -> {norm['text']!r}")
+ ```
-**Advantages over Traditional RAG**:
-- Better handling of complex queries
-- Relationship-aware retrieval
-- Reduced hallucinations
-- More accurate answers
+=== "Date Normalization"
+ Parse and normalize date formats:
+
+ ```python
+ from semantica.normalize import DateNormalizer
+
+ normalizer = DateNormalizer(
+ output_format="ISO8601", # "ISO8601", "US", "EU", "unix"
+ infer_missing=True,
+ handle_relative=True
+ )
+
+ # Various date formats
+ dates = [
+ "January 15, 2024",
+ "15/01/2024",
+ "01-15-2024",
+ "2024-01-15",
+ "last Tuesday",
+ "3 days ago",
+ "Q1 2024",
+ "mid-2023",
+ ]
+
+ print("Date Normalization:")
+ for date_str in dates:
+ result = normalizer.normalize(date_str)
+ print(f" {date_str:20} -> {result['normalized']}")
+ if result.get('is_range'):
+ print(f" Range: {result['start']} to {result['end']}")
+ ```
-```mermaid
-flowchart TD
- subgraph Query [Query Processing]
- Q[User Query] --> VS[Vector Search]
- Q --> KE[Keyword Extraction]
- end
+=== "Number Normalization"
+ Standardize numeric formats:
+
+ ```python
+ from semantica.normalize import NumberNormalizer
+
+ normalizer = NumberNormalizer(
+ output_format="numeric", # "numeric", "text", "scientific"
+ handle_currencies=True,
+ handle_percentages=True
+ )
+
+ # Various number formats
+ numbers = [
+ "1,234,567",
+ "one million",
+ "$3.5 billion",
+ "45%",
+ "1.5M",
+ "three hundred twenty-one",
+ "€50,000",
+ "12.5 percent"
+ ]
+
+ print("Number Normalization:")
+ for num_str in numbers:
+ result = normalizer.normalize(num_str)
+ print(f" {num_str:25} -> {result['value']:>15,.2f}")
+ if result.get('currency'):
+ print(f" Currency: {result['currency']}")
+ if result.get('is_percentage'):
+ print(f" Percentage: {result['decimal']:.4f}")
+ ```
- subgraph Retrieval [Hybrid Retrieval]
- VS --> Docs[Relevant Docs]
- KE --> Nodes[Start Nodes]
- Nodes --> Trav[Graph Traversal]
- Trav --> Context[Graph Context]
- end
+=== "Full Pipeline"
+ Run complete normalization pipeline:
+
+ ```python
+ from semantica.normalize import (
+ TextNormalizer,
+ EntityNormalizer,
+ DateNormalizer,
+ NumberNormalizer
+ )
+
+ # Initialize normalizers
+ text_norm = TextNormalizer(remove_extra_whitespace=True)
+ entity_norm = EntityNormalizer(case_style="title", remove_suffixes=["Inc.", "Corp."])
+ date_norm = DateNormalizer(output_format="ISO8601")
+ number_norm = NumberNormalizer(handle_currencies=True)
+
+ # Raw knowledge graph data
+ raw_kg = {
+ "entities": [
+ {"id": "e1", "text": " APPLE INC. ", "type": "Organization",
+ "properties": {"founded": "April 1, 1976", "revenue": "$394.3 billion"}},
+ {"id": "e2", "text": "tim cook", "type": "Person"},
+ ],
+ "relationships": [
+ {"source": "e2", "target": "e1", "type": "CEO_OF",
+ "properties": {"since": "August 24, 2011"}}
+ ]
+ }
+
+ # Normalize entities
+ normalized_entities = []
+ for entity in raw_kg['entities']:
+ norm_entity = entity.copy()
+
+ # Normalize text
+ norm_entity['text'] = text_norm.normalize(entity['text'])
+ norm_entity['text'] = entity_norm.normalize_entity_name(
+ norm_entity['text'],
+ entity_type=entity['type']
+ )
+
+ # Normalize properties
+ if 'properties' in entity:
+ props = entity['properties'].copy()
+ if 'founded' in props:
+ props['founded'] = date_norm.normalize(props['founded'])['normalized']
+ if 'revenue' in props:
+ props['revenue'] = number_norm.normalize(props['revenue'])
+ norm_entity['properties'] = props
+
+ normalized_entities.append(norm_entity)
+
+ # Normalize relationship properties
+ normalized_rels = []
+ for rel in raw_kg['relationships']:
+ norm_rel = rel.copy()
+ if 'properties' in rel and 'since' in rel['properties']:
+ norm_rel['properties']['since'] = date_norm.normalize(
+ rel['properties']['since']
+ )['normalized']
+ normalized_rels.append(norm_rel)
+
+ normalized_kg = {
+ "entities": normalized_entities,
+ "relationships": normalized_rels
+ }
+
+ print("Normalized Knowledge Graph:")
+ for entity in normalized_kg['entities']:
+ print(f" Entity: {entity['text']}")
+ for key, value in entity.get('properties', {}).items():
+ print(f" {key}: {value}")
+ ```
- subgraph Synthesis [Answer Generation]
- Docs --> Prompt
- Context --> Prompt
- Prompt --> LLM[LLM Generation]
- LLM --> A[Answer]
- end
+**Related Modules**:
+- [`normalize` Module](reference/normalize.md) - Data normalization
+- [`parse` Module](reference/parse.md) - Document parsing
+
+---
+
+### 11. Conflict Detection
+
+!!! abstract "Definition"
+ **Conflict Detection** identifies contradictory information in a knowledge graph, such as conflicting facts about the same entity from different sources.
+
+**Conflict Types**:
+
+| Type | Description | Example |
+| :--- | :--- | :--- |
+| **Value Conflict** | Different values for same property | "Founded: 1976" vs "Founded: 1977" |
+| **Relationship Conflict** | Conflicting relationships | "CEO: Tim Cook" vs "CEO: Steve Jobs" |
+| **Type Conflict** | Different entity types | "Apple: Company" vs "Apple: Product" |
+| **Temporal Conflict** | Conflicting time information | "Active: 2020-2023" vs "Active: 2021-2024" |
+
+**Practical Examples**:
+
+=== "Detecting Conflicts"
+ Find conflicts in your knowledge graph:
- style Q fill:#e1f5fe
- style LLM fill:#e8f5e9
- style A fill:#fff9c4
-```
+ ```python
+ from semantica.kg import ConflictDetector
+ from semantica.conflicts import ConflictAnalyzer, detect_conflicts
+
+ # Sample knowledge graph with conflicts
+ kg = {
+ "entities": [
+ {
+ "id": "e1",
+ "text": "Apple Inc.",
+ "type": "Organization",
+ "properties": {"founded": "1976", "employees": "160000"},
+ "source": "wikipedia"
+ },
+ {
+ "id": "e2",
+ "text": "Apple Inc.",
+ "type": "Organization",
+ "properties": {"founded": "1977", "employees": "164000"},
+ "source": "bloomberg"
+ },
+ ],
+ "relationships": [
+ {"source": "p1", "target": "e1", "type": "CEO_OF",
+ "properties": {"since": "2011"}, "data_source": "sec_filing"},
+ {"source": "p2", "target": "e1", "type": "CEO_OF",
+ "properties": {"since": "2011"}, "data_source": "news"}
+ ]
+ }
+
+ # Method 1: Using convenience function
+ conflicts = detect_conflicts(
+ kg["entities"],
+ method="value",
+ property_name="founded"
+ )
+
+ # Method 2: Using ConflictDetector class
+ detector = ConflictDetector()
+ all_conflicts = detector.detect_value_conflicts(kg["entities"], "founded")
+
+ print(f"Found {len(all_conflicts)} conflicts:")
+ for conflict in all_conflicts:
+ print(f" Type: {conflict.conflict_type.value}")
+ print(f" Entity: {conflict.entity_id}")
+ print(f" Property: {conflict.property_name}")
+ print(f" Values: {[v['value'] for v in conflict.values]}")
+ print(f" Sources: {conflict.sources}")
+
+ # Analyze conflicts
+ analyzer = ConflictAnalyzer()
+ analysis = analyzer.analyze(all_conflicts)
+
+ print(f"Conflict Analysis:")
+ print(f" Total conflicts: {analysis['total_conflicts']}")
+ print(f" By type: {analysis['by_type']}")
+ print(f" By severity: {analysis['by_severity']}")
+ ```
-### 7. Ontology
+=== "Resolution Strategies"
+ Resolve conflicts using different strategies:
+
+ ```python
+ from semantica.conflicts import (
+ ConflictResolver,
+ ResolutionStrategy,
+ Conflict,
+ ConflictType
+ )
+
+ # Create sample conflicts
+ conflicts = [
+ Conflict(
+ conflict_id="c1",
+ entity_id="e1",
+ conflict_type=ConflictType.VALUE,
+ property_name="founded",
+ values=[
+ {"value": "1976", "source": "wikipedia", "confidence": 0.95},
+ {"value": "1976", "source": "sec_filing", "confidence": 0.99},
+ {"value": "1977", "source": "news_article", "confidence": 0.70}
+ ],
+ sources=["wikipedia", "sec_filing", "news_article"]
+ )
+ ]
+
+ # Strategy 1: Voting (most common value wins)
+ resolver_voting = ConflictResolver(strategy=ResolutionStrategy.VOTING)
+ resolved_voting = resolver_voting.resolve(conflicts)
+
+ print("Voting Resolution:")
+ for r in resolved_voting:
+ print(f" {r.property_name}: {r.resolved_value}")
+
+ # Strategy 2: Highest confidence
+ resolver_conf = ConflictResolver(strategy=ResolutionStrategy.HIGHEST_CONFIDENCE)
+ resolved_conf = resolver_conf.resolve(conflicts)
+
+ print("Highest Confidence Resolution:")
+ for r in resolved_conf:
+ print(f" {r.property_name}: {r.resolved_value} (confidence: {r.confidence:.2f})")
+
+ # Strategy 3: Source priority
+ resolver_priority = ConflictResolver(
+ strategy=ResolutionStrategy.SOURCE_PRIORITY,
+ source_priority=["sec_filing", "wikipedia", "news_article"]
+ )
+ resolved_priority = resolver_priority.resolve(conflicts)
+
+ print("Source Priority Resolution:")
+ for r in resolved_priority:
+ print(f" {r.property_name}: {r.resolved_value} (source: {r.selected_source})")
+ ```
+
+=== "Custom Resolution Rules"
+ Define custom resolution rules per property:
+
+ ```python
+ from semantica.conflicts import (
+ ConflictResolver,
+ ResolutionStrategy,
+ resolve_conflicts
+ )
+
+ # Define property-specific resolution rules
+ resolution_config = {
+ "founded": {
+ "strategy": ResolutionStrategy.SOURCE_PRIORITY,
+ "source_priority": ["official_records", "sec_filing", "wikipedia"]
+ },
+ "revenue": {
+ "strategy": ResolutionStrategy.MOST_RECENT,
+ },
+ "employees": {
+ "strategy": ResolutionStrategy.VOTING,
+ },
+ "ceo": {
+ "strategy": ResolutionStrategy.HIGHEST_CONFIDENCE,
+ }
+ }
+
+ # Create resolver with custom config
+ resolver = ConflictResolver(
+ strategy=ResolutionStrategy.HIGHEST_CONFIDENCE,
+ min_confidence=0.7
+ )
+
+ # Resolve conflicts for each property
+ resolved_values = {}
+ for property_name, config in resolution_config.items():
+ property_resolver = ConflictResolver(
+ strategy=config["strategy"],
+ source_priority=config.get("source_priority")
+ )
+
+ # Get conflicts for this property
+ property_conflicts = [c for c in conflicts if c.property_name == property_name]
+
+ if property_conflicts:
+ results = property_resolver.resolve(property_conflicts)
+ for result in results:
+ resolved_values[property_name] = {
+ "value": result.resolved_value,
+ "strategy": config["strategy"].value,
+ "confidence": result.confidence
+ }
+
+ print("Resolved Values:")
+ for prop, info in resolved_values.items():
+ print(f" {prop}: {info['value']} (via {info['strategy']})")
+ ```
+
+=== "Source Tracking"
+ Track the origin of resolved values:
+
+ ```python
+ from semantica.conflicts import SourceTracker, SourceReference
+
+ # Initialize source tracker
+ tracker = SourceTracker()
+
+ # Add entities from different sources
+ tracker.add_source(SourceReference(
+ entity_id="e1",
+ property_name="founded",
+ value="1976",
+ source="wikipedia",
+ timestamp="2024-01-15",
+ confidence=0.95
+ ))
+
+ tracker.add_source(SourceReference(
+ entity_id="e1",
+ property_name="founded",
+ value="1976",
+ source="sec_filing",
+ timestamp="2024-03-01",
+ confidence=0.99
+ ))
+
+ tracker.add_source(SourceReference(
+ entity_id="e1",
+ property_name="founded",
+ value="1977",
+ source="news_article",
+ timestamp="2024-02-20",
+ confidence=0.70
+ ))
+
+ # Get all sources for an entity
+ sources = tracker.get_sources("e1")
+
+ print("Entity Sources:")
+ for source in sources:
+ print(f" Source: {source.source}")
+ print(f" Property: {source.property_name}")
+ print(f" Value: {source.value}")
+ print(f" Confidence: {source.confidence}")
+
+ # Get property-specific sources
+ property_sources = tracker.get_property_sources("e1", "founded")
+
+ print("Property Sources for 'founded':")
+ for ps in property_sources:
+ print(f" {ps.value} from {ps.source} ({ps.timestamp})")
+ ```
+
+=== "Conflict Investigation"
+ Deep dive into specific conflicts:
+
+ ```python
+ from semantica.conflicts import (
+ InvestigationGuideGenerator,
+ ConflictDetector,
+ Conflict,
+ ConflictType
+ )
+
+ # Initialize investigation guide generator
+ guide_generator = InvestigationGuideGenerator()
+
+ # Create a conflict object
+ conflict = Conflict(
+ conflict_id="c1",
+ entity_id="e1",
+ conflict_type=ConflictType.VALUE,
+ property_name="founded",
+ values=[
+ {"value": "1976", "source": "wikipedia", "confidence": 0.95},
+ {"value": "1977", "source": "news", "confidence": 0.70}
+ ],
+ sources=["wikipedia", "news"],
+ severity=0.6
+ )
+
+ # Generate investigation guide
+ guide = guide_generator.generate_guide(conflict)
+
+ print("Conflict Investigation Guide:")
+ print(f" Conflict ID: {guide.conflict_id}")
+ print(f" Title: {guide.title}")
+ print(f" Summary: {guide.summary}")
+
+ print("Investigation Steps:")
+ for i, step in enumerate(guide.steps, 1):
+ print(f" {i}. {step.description}")
+ print(f" Priority: {step.priority}")
+ if step.expected_outcome:
+ print(f" Expected: {step.expected_outcome}")
+
+ print("Checklist:")
+ for item in guide.checklist:
+ print(f" [ ] {item}")
+
+ # Get context for the conflict
+ context = guide_generator.get_conflict_context(conflict)
+ print(f"Context:")
+ print(f" Entity: {context.get('entity_text', 'Unknown')}")
+ print(f" Property: {context.get('property', 'Unknown')}")
+ print(f" Value count: {len(conflict.values)}")
+ ```
+
+**Related Modules**:
+- [`conflicts` Module](../semantica/conflicts/conflicts_usage.md) - Conflict detection and resolution
+- [`kg_qa` Module](reference/evals.md) - Quality assurance
-**Definition**: A formal specification of concepts, relationships, and constraints in a domain, typically expressed in OWL (Web Ontology Language).
+---
-- **Classes**: Categories of entities (e.g., `Person`, `Company`)
-- **Properties**: Relationships and attributes (e.g., `worksFor`)
-- **Individuals**: Specific instances (e.g., `John Doe`)
-- **Axioms**: Rules and constraints
+## Comparison Tables
-### 8. Quality Assurance
+### Embedding Providers Comparison
-**Definition**: Processes and metrics to ensure knowledge graph quality.
+| Provider | Model | Dimensions | Speed | Cost | Accuracy | Best For |
+| :--- | :--- | :--- | :--- | :--- | :--- | :--- |
+| **OpenAI** | text-embedding-3-large | 3072 | Fast | Paid | High | Production, high accuracy |
+| **OpenAI** | text-embedding-3-small | 1536 | Fast | Paid | High | Balanced performance |
+| **Cohere** | embed-english-v3.0 | 1024 | Fast | Paid | High | Multilingual support |
+| **HuggingFace** | all-MiniLM-L6-v2 | 384 | Medium | Free | Medium | Development, open source |
+| **Local** | sentence-transformers | 384-768 | Slow | Free | Medium | Privacy, offline use |
-- **Completeness**: Percentage of entities with required properties
-- **Consistency**: Absence of contradictions
-- **Accuracy**: Correctness of extracted information
-- **Coverage**: Breadth of domain coverage
+### Graph Backend Comparison
+
+| Backend | Type | Speed | Scalability | Query Language | Best For |
+| :--- | :--- | :--- | :--- | :--- | :--- |
+| **NetworkX**| In-memory | Fast | Small-medium | Python API | Development, small graphs |
+| **Neo4j** | Database | Medium | Large | Cypher | Production, complex queries |
+| **KuzuDB** | Embedded | Fast | Medium | Cypher | Embedded applications |
+| **FalkorDB**| Redis-based| Very Fast | Large | Cypher | Real-time, high throughput |
---
-## 🌟 Best Practices
+## Best Practices
Following these practices will help you build high-quality knowledge graphs and avoid common pitfalls.
### 1. Start Small
+
!!! tip "Iterative Approach"
Don't try to model the entire world at once. Start with a small, well-defined domain and expand incrementally.
+**Example**:
+```python
+# Start with a single document
+kg1 = semantica.build_knowledge_base(["doc1.pdf"])
+
+# Validate and refine
+quality = assessor.assess(kg1)
+
+# Then expand
+kg2 = semantica.build_knowledge_base(["doc2.pdf", "doc3.pdf"])
+merged = semantica.kg.merge([kg1, kg2])
+```
+
### 2. Configure Properly
-- Use environment variables for sensitive data.
-- Set up proper logging.
-- Configure appropriate model sizes.
+
+- Use environment variables for sensitive data
+- Set up proper logging
+- Configure appropriate model sizes
+- Use configuration files for complex setups
+
+```python
+# Good: Use environment variables
+import os
+api_key = os.getenv("OPENAI_API_KEY")
+
+# Good: Use config files
+from semantica import Config
+config = Config.from_file("config.yaml")
+semantica = Semantica(config=config)
+```
### 3. Validate Data
+
!!! warning "Garbage In, Garbage Out"
Always validate extracted entities. A knowledge graph with incorrect facts is worse than no graph at all.
+**Validation Checklist**:
+- Check entity extraction accuracy
+- Validate relationships make sense
+- Verify confidence scores
+- Review source attribution
+- Test with sample queries
+
### 4. Handle Errors
-- Implement error handling.
-- Use retry mechanisms.
-- Log errors for debugging.
+
+- Implement error handling
+- Use retry mechanisms
+- Log errors for debugging
+- Gracefully handle API failures
+
+```python
+from semantica import Semantica
+import logging
+
+logging.basicConfig(level=logging.INFO)
+semantica = Semantica()
+
+try:
+ result = semantica.build_knowledge_base(["doc.pdf"])
+except Exception as e:
+ logging.error(f"Error building KG: {e}")
+ # Handle error appropriately
+```
### 5. Optimize Performance
-- Use batch processing for large datasets.
-- Enable parallel processing where possible.
-- Cache embeddings and results.
+
+- Use batch processing for large datasets
+- Enable parallel processing where possible
+- Cache embeddings and results
+- Use appropriate backend for your scale
+
+```python
+# Batch processing
+sources = ["doc1.pdf", "doc2.pdf", ..., "doc100.pdf"]
+batch_size = 10
+
+for i in range(0, len(sources), batch_size):
+ batch = sources[i:i+batch_size]
+ result = semantica.build_knowledge_base(batch)
+ # Process and save results
+```
### 6. Document Workflows
-- Document data sources.
-- Track processing steps.
-- Maintain metadata.
+
+- Document data sources
+- Track processing steps
+- Maintain metadata
+- Version your knowledge graphs
---
-## 🔧 Troubleshooting
+## Troubleshooting
Common issues and solutions:
!!! failure "Import Errors"
**Solution**:
- - Ensure Semantica is properly installed.
- - Check Python version (3.8+).
- - Verify virtual environment is activated.
+ - Ensure Semantica is properly installed: `pip install semantica`
+ - Check Python version (3.8+): `python --version`
+ - Verify virtual environment is activated
- Install missing dependencies: `pip install -r requirements.txt`
!!! failure "API Key Errors"
**Solution**:
- - Set environment variables: `export SEMANTICA_API_KEY=your_key`
- - Check config file for correct key format.
- - Verify API key is valid and has sufficient credits.
+ - Set environment variables: `export OPENAI_API_KEY=your_key`
+ - Check config file for correct key format
+ - Verify API key is valid and has sufficient credits
+ - Test API connection: `curl https://api.openai.com/v1/models`
!!! failure "Memory Issues"
**Solution**:
- - Process documents in batches.
- - Use smaller embedding models.
- - Enable garbage collection.
- - Consider using streaming for large datasets.
+ - Process documents in batches
+ - Use smaller embedding models
+ - Enable garbage collection
+ - Consider using streaming for large datasets
+ - Use graph store backends (Neo4j, KuzuDB) instead of in-memory
!!! failure "Low Quality Extractions"
**Solution**:
- - Preprocess and normalize text.
- - Use domain-specific models.
- - Adjust extraction parameters.
- - Validate and clean extracted entities.
+ - Preprocess and normalize text
+ - Use domain-specific models
+ - Adjust extraction parameters
+ - Validate and clean extracted entities
+ - Use LLM-based extraction for better accuracy
+ - Fine-tune models on your domain
!!! failure "Slow Processing"
**Solution**:
- - Enable parallel processing.
- - Use GPU acceleration if available.
- - Cache intermediate results.
- - Optimize batch sizes.
+ - Enable parallel processing
+ - Use GPU acceleration if available
+ - Cache embeddings and results
+ - Optimize batch sizes
+ - Use faster embedding models
+ - Consider using local models for development
+
+!!! failure "Graph Too Large"
+ **Solution**:
+ - Use graph store backends (Neo4j, KuzuDB) instead of NetworkX
+ - Implement graph partitioning
+ - Use incremental building
+ - Filter entities by confidence threshold
+ - Remove low-value relationships
+
+---
+
+## Next Steps
+
+Now that you understand the core concepts:
+
+1. **[Getting Started](getting-started.md)** - Set up Semantica and build your first knowledge graph
+2. **[Modules Guide](modules.md)** - Learn about the available modules
+3. **[Use Cases](use-cases.md)** - Explore real-world applications
+4. **[Examples](examples.md)** - See practical code examples
+5. **[API Reference](reference/core.md)** - Detailed API documentation
+
+---
+
+!!! info "Contribute"
+ Found an issue or want to improve this guide? [Contribute on GitHub](https://github.com/Hawksight-AI/semantica)
+
+**Last Updated**: 2024
diff --git a/docs/reference/embeddings.md b/docs/reference/embeddings.md
index 12bce2ab..e1665ec3 100644
--- a/docs/reference/embeddings.md
+++ b/docs/reference/embeddings.md
@@ -1,81 +1,74 @@
-# Embeddings Module
+# Embeddings
-> **Transform text and images into dense vector representations for semantic search and similarity matching.**
+> **Multi-modal embedding generation for Text, Images, and Audio.**
---
## 🎯 Overview
-=== "Text Embeddings"
+<div class="grid cards" markdown>
- <div class="grid cards" markdown>
+- :material-text-box:{ .lg .middle } **Text Embeddings**
- - :material-text:{ .lg .middle } **Transformer Encoders**
-
- BERT, RoBERTa, DeBERTa with advanced pooling strategies
+ ---
- - :material-lightning-bolt:{ .lg .middle } **Sentence Transformers**
-
- Fast, efficient embeddings optimized for semantic similarity
+ Sentence-transformers, OpenAI, and BGE model support
- - :material-api:{ .lg .middle } **API Providers**
-
- OpenAI, Cohere, Google, HuggingFace integration
+- :material-image:{ .lg .middle } **Image Embeddings**
- </div>
+ ---
-=== "Image Embeddings"
+ CLIP-based vision embeddings for cross-modal search
- <div class="grid cards" markdown>
+- :material-waveform:{ .lg .middle } **Audio Embeddings**
- - :material-image:{ .lg .middle } **CLIP**
-
- Contrastive Language-Image Pre-training for multimodal embeddings
+ ---
- - :material-eye:{ .lg .middle } **Vision Transformers**
-
- ViT models for high-quality image representations
+ MFCC, Chroma, and Spectral feature extraction via Librosa
- - :material-layers:{ .lg .middle } **CNN Models**
-
- ResNet, EfficientNet for feature extraction
+- :material-layers-search:{ .lg .middle } **Multimodal**
- </div>
+ ---
-=== "Multimodal"
+ Unified embedding space for searching across modalities
- <div class="grid cards" markdown>
+- :material-compress:{ .lg .middle } **Optimization**
- - :material-merge:{ .lg .middle } **Fusion Strategies**
-
- Concatenation, weighted sum, cross-attention fusion
+ ---
- - :material-compare:{ .lg .middle } **Similarity**
-
- Text-image similarity in joint embedding space
+ PCA reduction, Quantization, and Pooling strategies
- </div>
+- :material-text-short:{ .lg .middle } **Context Management**
+
+ ---
+
+ Sliding window chunking with sentence boundary preservation
+
+</div>
+
+!!! tip "When to Use"
+ - **Semantic Search**: Converting text to vectors for similarity search
+ - **Clustering**: Grouping similar documents or images
+ - **Classification**: Using embeddings as features for ML models
+ - **RAG**: Embedding chunks for retrieval
---
## ⚙️ Algorithms Used
-### Text Embedding Algorithms
-- **Transformer Encoders**: BERT, RoBERTa, DeBERTa with mean pooling
-- **Sentence Transformers**: Siamese networks trained on sentence pairs
-- **OpenAI Embeddings**: Proprietary transformer models (ada-002, text-embedding-3)
-- **Contrastive Learning**: InfoNCE loss for similarity learning
+### Generation
+- **Transformer Encoding**: BERT/RoBERTa based models for text.
+- **CLIP Encoding**: Vision Transformer (ViT) for images.
+- **Feature Extraction**: Signal processing (MFCC, Spectral Contrast) for audio.
-### Pooling Strategies
-- **Mean Pooling**: Average of all token embeddings
-- **Max Pooling**: Maximum value across token dimension
-- **CLS Token**: Use [CLS] token embedding (BERT-style)
-- **Weighted Mean**: Attention-weighted averaging
+### Optimization
+- **PCA**: Dimensionality reduction to reduce storage costs while preserving variance.
+- **Quantization**: Converting float32 -> int8 for 4x memory savings.
+- **Pooling**: Mean, Max, or CLS token pooling to aggregate token vectors into sentence vectors.
-### Normalization
-- **L2 Normalization**: `v_norm = v / ||v||₂` for cosine similarity
-- **Min-Max Scaling**: Scale to [0, 1] range
-- **Standard Scaling**: Zero mean, unit variance
+### Context
+- **Sliding Window**: `[A, B, C], [B, C, D], ...` to capture context across boundaries.
+- **Sentence Splitting**: Regex-based splitting to avoid breaking sentences mid-chunk.
---
@@ -83,273 +76,136 @@
### EmbeddingGenerator
+Unified interface for all modalities.
**Methods:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `generate(texts)` | Generate embeddings | Provider-specific encoding with pooling |
-| `generate_batch(texts, batch_size)` | Batch generation | Chunked processing with parallel execution |
-| `encode(text)` | Encode single text | Tokenization + forward pass + pooling |
-| `normalize(embeddings)` | Normalize vectors | L2 normalization |
-| `set_provider(provider, model)` | Set embedding provider | Provider initialization |
-
-**Supported Providers:**
-
-| Provider | Models | Dimensions | Speed | Cost |
-|----------|--------|------------|-------|------|
-| **OpenAI** | text-embedding-3-small, text-embedding-3-large, ada-002 | 1536, 3072 | Fast | $$ |
-| **Cohere** | embed-english-v3.0, embed-multilingual-v3.0 | 1024 | Fast | $$ |
-| **HuggingFace** | Custom models | Variable | Medium | Free |
-| **Sentence Transformers** | all-MiniLM-L6-v2, all-mpnet-base-v2 | 384, 768 | Fast | Free |
-| **Google** | textembedding-gecko | 768 | Fast | $$ |
+| Method | Description |
+|--------|-------------|
+| `generate(data, type)` | Generate embedding |
+| `process_batch(items)` | Batch generation |
**Example:**
```python
from semantica.embeddings import EmbeddingGenerator
-# OpenAI embeddings
-generator = EmbeddingGenerator(
- provider="openai",
- model="text-embedding-3-large",
- dimensions=3072
-)
-
-texts = ["Machine learning is fascinating", "AI transforms industries"]
-embeddings = generator.generate(texts)
-
-print(f"Shape: {embeddings.shape}") # (2, 3072)
-print(f"Normalized: {np.linalg.norm(embeddings[0]):.3f}") # 1.000
-
-# Batch processing
-large_texts = [...] # 10,000 texts
-embeddings = generator.generate_batch(
- texts=large_texts,
- batch_size=100,
- show_progress=True
-)
+gen = EmbeddingGenerator()
+vec = gen.generate("Hello world", data_type="text")
```
----
-
### TextEmbedder
+Specialized text embedding.
**Methods:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `embed(text)` | Embed single text | Tokenization + encoding + pooling |
-| `embed_batch(texts)` | Batch embedding | Parallel processing |
-| `embed_query(query)` | Embed query (optimized) | Query-specific encoding |
-| `embed_documents(documents)` | Embed documents | Document-specific encoding |
-| `tokenize(text)` | Tokenize text | Subword tokenization (BPE/WordPiece) |
-
-**Tokenization Algorithms:**
-- **BPE (Byte Pair Encoding)**: Iterative merging of frequent pairs
-- **WordPiece**: Similar to BPE, used in BERT
-- **SentencePiece**: Unigram language model tokenization
-
-**Example:**
-
-```python
-from semantica.embeddings import TextEmbedder
-
-embedder = TextEmbedder(
- model="sentence-transformers/all-mpnet-base-v2",
- pooling="mean", # mean, max, cls
- normalize=True
-)
-
-# Different embedding strategies
-query_embedding = embedder.embed_query("What is machine learning?")
-doc_embeddings = embedder.embed_documents([
- "Machine learning is a subset of AI...",
- "Deep learning uses neural networks..."
-])
-
-# Calculate similarity
-from sklearn.metrics.pairwise import cosine_similarity
-similarity = cosine_similarity([query_embedding], doc_embeddings)
-print(f"Similarities: {similarity}")
-```
-
----
+| Method | Description |
+|--------|-------------|
+| `embed(text)` | Generate vector |
+| `embed_batch(texts)` | Batch processing |
### ImageEmbedder
+Specialized image embedding.
**Methods:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `embed(image)` | Embed single image | CNN/ViT encoding |
-| `embed_batch(images)` | Batch image embedding | Parallel CNN/ViT processing |
-| `preprocess(image)` | Preprocess image | Resize, normalize, augment |
-| `extract_features(image)` | Extract visual features | Feature map extraction |
-
-**Image Embedding Models:**
-- **CLIP**: Contrastive Language-Image Pre-training
-- **ViT (Vision Transformer)**: Transformer for images
-- **ResNet**: Residual networks
-- **EfficientNet**: Efficient convolutional networks
-
-**Example:**
-
-```python
-from semantica.embeddings import ImageEmbedder
-from PIL import Image
-
-embedder = ImageEmbedder(
- model="openai/clip-vit-base-patch32",
- image_size=224
-)
-
-image = Image.open("photo.jpg")
-embedding = embedder.embed(image)
-
-print(f"Image embedding shape: {embedding.shape}")
-```
-
----
+| Method | Description |
+|--------|-------------|
+| `embed(image_path)` | Generate vector |
-### MultimodalEmbedder
+### EmbeddingOptimizer
+Optimizes vectors.
**Methods:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `embed(text, image)` | Embed text + image | Multimodal fusion |
-| `embed_text_image(text, image)` | Joint embedding | CLIP-style contrastive learning |
-| `fuse_embeddings(text_emb, image_emb)` | Fuse embeddings | Concatenation or weighted sum |
-| `calculate_similarity(text, image)` | Text-image similarity | Cosine similarity in joint space |
+| Method | Description |
+|--------|-------------|
+| `reduce_dimension(vecs)` | Apply PCA |
+| `quantize(vecs)` | Apply quantization |
-**Fusion Strategies:**
-- **Concatenation**: `[text_emb; image_emb]`
-- **Weighted Sum**: `α*text_emb + (1-α)*image_emb`
-- **Cross-Attention**: Attention-based fusion
+---
-**Example:**
+## Convenience Functions
```python
-from semantica.embeddings import MultimodalEmbedder
+from semantica.embeddings import EmbeddingGenerator, embed_text, calculate_similarity
-embedder = MultimodalEmbedder(
- model="openai/clip-vit-base-patch32",
- fusion_strategy="weighted_sum",
- text_weight=0.6
-)
+# Generate embeddings
+generator = EmbeddingGenerator()
+emb1 = generator.generate_embeddings("text1", data_type="text")
+emb2 = generator.generate_embeddings("text2", data_type="text")
-text = "A cat sitting on a couch"
-image = Image.open("cat.jpg")
-
-embedding = embedder.embed(text, image)
-similarity = embedder.calculate_similarity(text, image)
-print(f"Text-Image similarity: {similarity:.3f}")
+# Similarity
+score = calculate_similarity(emb1, emb2)
```
---
-### EmbeddingOptimizer
-
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `optimize(embeddings)` | Optimize embeddings | Dimensionality reduction + quantization |
-| `reduce_dimensions(embeddings, target_dim)` | Reduce dimensions | PCA or random projection |
-| `quantize(embeddings, bits)` | Quantize embeddings | Scalar or product quantization |
-| `compress(embeddings)` | Compress embeddings | Lossy compression |
-
-**Optimization Techniques:**
-- **PCA**: Linear dimensionality reduction
-- **Random Projection**: Fast approximate reduction
-- **Product Quantization**: Divide into subvectors, quantize separately
-- **Scalar Quantization**: Reduce precision (float32 → int8)
+## Configuration
-**Example:**
+### Environment Variables
-```python
-from semantica.embeddings import EmbeddingOptimizer
-
-optimizer = EmbeddingOptimizer()
-
-# Reduce dimensions
-reduced = optimizer.reduce_dimensions(
- embeddings=embeddings,
- target_dim=256, # from 1536 to 256
- method="pca"
-)
-
-# Quantize to int8
-quantized = optimizer.quantize(
- embeddings=embeddings,
- bits=8 # float32 → int8 (4x compression)
-)
+```bash
+export EMBEDDING_MODEL=all-MiniLM-L6-v2
+export EMBEDDING_DEVICE=cuda
+export OPENAI_API_KEY=sk-...
```
----
-
-## Configuration
+### YAML Configuration
```yaml
-# config.yaml - Embeddings Configuration
-
embeddings:
- provider: openai # openai, cohere, huggingface, sentence-transformers
-
- openai:
- model: text-embedding-3-large
- dimensions: 3072
- api_key: ${OPENAI_API_KEY}
+ text:
+ model: all-MiniLM-L6-v2
+ batch_size: 32
- sentence_transformers:
- model: all-mpnet-base-v2
- pooling: mean # mean, max, cls
- normalize: true
- device: cuda # cuda, cpu
-
- batch_processing:
- batch_size: 100
- parallel_workers: 4
- show_progress: true
+ image:
+ model: clip-ViT-B-32
optimization:
- reduce_dimensions: false
- target_dimensions: 256
quantize: false
- quantization_bits: 8
```
---
-## Performance Characteristics
+## Integration Examples
-### Embedding Speed
+### Multimodal Search
-| Model | Dimensions | Tokens/sec | Batch Size | Device |
-|-------|------------|------------|------------|--------|
-| OpenAI ada-002 | 1536 | 10,000 | 100 | API |
-| OpenAI text-embedding-3-large | 3072 | 8,000 | 100 | API |
-| all-MiniLM-L6-v2 | 384 | 5,000 | 32 | GPU |
-| all-mpnet-base-v2 | 768 | 2,000 | 32 | GPU |
-| BERT-base | 768 | 1,000 | 16 | GPU |
+```python
+from semantica.embeddings import MultimodalEmbedder
+from semantica.vector_store import VectorStore
+
+# 1. Embed Image and Text into same space
+embedder = MultimodalEmbedder()
+img_vec = embedder.embed_image("cat.jpg")
+text_vec = embedder.embed_text("A cute kitten")
+
+# 2. Store
+store = VectorStore()
+store.store_vectors([img_vec], metadata=[{"type": "image", "path": "cat.jpg"}])
+
+# 3. Search with Text
+results = store.search(text_vec, k=1)
+print(f"Found: {results[0].metadata['path']}")
+```
+
+---
-### Memory Requirements
+## Best Practices
-| Model | Dimensions | Memory (GPU) | Memory (CPU) |
-|-------|------------|--------------|--------------|
-| MiniLM | 384 | 1 GB | 2 GB |
-| MPNet | 768 | 2 GB | 4 GB |
-| BERT-large | 1024 | 4 GB | 8 GB |
+1. **Batch Processing**: Always use batch methods (`embed_batch`, `process_batch`) for >1 item. It's much faster on GPU.
+2. **Use Caching**: Embeddings are expensive to compute. Cache them if possible.
+3. **Match Dimensions**: Ensure your vector store is configured with the correct dimension for your chosen model.
+4. **Normalize**: L2 normalization is usually required for Cosine Similarity to work correctly.
---
## See Also
-- [Vector Store Module](vector_store.md) - Store and search embeddings
-- [Semantic Extract Module](semantic_extract.md) - Extract entities
-- [Core Module](core.md) - Framework orchestration
+- [Vector Store Module](vector_store.md) - Storing the generated vectors
+- [Ingest Module](ingest.md) - Loading data to embed
+- [Pipeline Module](pipeline.md) - Orchestrating the embedding process
diff --git a/docs/reference/kg.md b/docs/reference/kg.md
index 58dc694d..7f6e662d 100644
--- a/docs/reference/kg.md
+++ b/docs/reference/kg.md
@@ -1,6 +1,6 @@
-# Knowledge Graph Module
+# Knowledge Graph
-> **Build, analyze, and manage knowledge graphs with advanced temporal support and graph analytics.**
+> **High-level KG construction, management, and analysis system.**
---
@@ -8,83 +8,67 @@
<div class="grid cards" markdown>
-- :material-graph-outline:{ .lg .middle } **Graph Building**
+- :material-graph-outline:{ .lg .middle } **KG Construction**
---
- Construct knowledge graphs from entities and relationships with automatic entity resolution
+ Build graphs from entities and relationships with automatic merging
-- :material-merge:{ .lg .middle } **Entity Resolution**
+- :material-clock-time-four-outline:{ .lg .middle } **Temporal Graphs**
---
- Merge duplicate entities using fuzzy and semantic matching algorithms
+ Time-aware edges (`valid_from`, `valid_until`) and temporal queries
-- :material-alert-circle:{ .lg .middle } **Conflict Detection**
+- :material-account-multiple-check:{ .lg .middle } **Entity Resolution**
---
- Handle contradictory information with multiple resolution strategies
+ Deduplicate entities using fuzzy matching and semantic similarity
-- :material-clock-outline:{ .lg .middle } **Temporal Graphs**
+- :material-alert-decagram:{ .lg .middle } **Conflict Detection**
---
- Track changes over time with versioning and temporal queries
+ Detect and resolve contradicting facts from multiple sources
-- :material-chart-line:{ .lg .middle } **Graph Analytics**
+- :material-chart-network:{ .lg .middle } **Graph Analytics**
---
- PageRank, centrality, community detection, and path finding
+ Centrality, Community Detection, and Connectivity analysis
-- :material-database-search:{ .lg .middle } **Graph Querying**
+- :material-history:{ .lg .middle } **Provenance**
---
- Cypher-like query language with pattern matching
+ Track the source and lineage of every node and edge
</div>
+!!! tip "When to Use"
+ - **KG Building**: The primary module for assembling a KG from extracted data
+ - **Data Cleaning**: Merging duplicates and resolving conflicts
+ - **Analysis**: Understanding the structure and importance of nodes
+ - **Time-Series**: Modeling how the graph evolves over time
+
---
## ⚙️ Algorithms Used
-### Graph Construction Algorithms
-- **Incremental Building**: Batch processing for large graphs with memory optimization
-- **Entity Merging**: Property aggregation, metadata merging, provenance tracking
-- **Relationship Deduplication**: Similarity-based relationship merging
-
-### Entity Resolution Algorithms
-- **Fuzzy Matching**: Levenshtein distance, Jaro-Winkler similarity for string matching
-- **Semantic Matching**: Embedding-based similarity (cosine similarity on entity embeddings)
-- **Threshold-based Grouping**: Configurable similarity thresholds for entity clustering
-- **Conflict Resolution Strategies**: Voting, credibility-weighted, most-recent, highest-confidence
-
-### Graph Analysis Algorithms
-- **Degree Centrality**: Normalized degree calculation: `degree / (n-1)`
-- **Betweenness Centrality**: Shortest path counting (BFS-based), normalized by `(n-1)*(n-2)/2`
-- **Closeness Centrality**: Average shortest path length calculation
-- **PageRank**: Iterative power method with damping factor (default: 0.85)
-- **Eigenvector Centrality**: Power iteration method for influence calculation
-
-### Community Detection Algorithms
-- **Louvain Method**: Modularity optimization with greedy agglomeration
-- **Leiden Algorithm**: Improved Louvain with guaranteed well-connected communities
-- **Label Propagation**: Fast community detection via label spreading
-- **Greedy Modularity**: Hierarchical community structure detection
-
-### Temporal Graph Algorithms
-- **Time-Point Queries**: Temporal filtering using valid_from/valid_until comparison
-- **Time-Range Queries**: Interval overlap detection, union/intersection aggregation
-- **Temporal Patterns**: Sequential pattern mining, temporal motif detection
-- **Version Management**: Snapshot creation, diff calculation, rollback support
-
-### Graph Validation Algorithms
-- **Schema Validation**: Type checking against ontology definitions
-- **Consistency Checking**: Logical constraint validation, relationship type validation
-- **Completeness Validation**: Required property checking, orphaned entity detection
-- **Density Calculation**: `E / (n*(n-1)/2)` for undirected graphs
+### Entity Resolution
+- **Fuzzy Matching**: Levenshtein/Jaro-Winkler distance for string similarity.
+- **Semantic Matching**: Cosine similarity of embeddings.
+- **Transitive Merging**: If A=B and B=C, then A=B=C.
+
+### Graph Analytics
+- **Centrality**: Degree, Betweenness, Closeness, Eigenvector.
+- **Communities**: Louvain, Leiden, K-Clique.
+- **Connectivity**: Connected Components, Bridge Detection.
+
+### Temporal Analysis
+- **Time-Slicing**: Viewing the graph at a specific point in time.
+- **Interval Algebra**: Allen's interval algebra for temporal reasoning (overlaps, during, before).
---
@@ -92,355 +76,123 @@
### GraphBuilder
+Constructs the KG from raw data.
**Methods:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `build(entities, relationships)` | Build knowledge graph | Incremental graph construction with entity resolution |
-| `add_node(entity)` | Add entity node | Node creation with property validation |
-| `add_edge(relationship)` | Add relationship edge | Edge creation with type validation |
-| `merge_graphs(graphs)` | Merge multiple graphs | Graph union with entity resolution |
-| `resolve_entities(threshold)` | Resolve duplicate entities | Fuzzy + semantic matching |
-| `detect_conflicts()` | Detect conflicting information | Multi-source conflict detection |
-| `to_neo4j(uri, username, password)` | Export to Neo4j | Cypher query generation |
-| `to_rdf(filename, format)` | Export to RDF | RDF serialization (Turtle, N-Triples) |
+| Method | Description |
+|--------|-------------|
+| `build(sources)` | Build graph from inputs |
+| `merge_entities()` | Run deduplication |
**Example:**
```python
from semantica.kg import GraphBuilder
-builder = GraphBuilder(
- merge_entities=True,
- entity_resolution_strategy="fuzzy", # "fuzzy", "semantic", "hybrid"
- similarity_threshold=0.85,
- resolve_conflicts=True,
- enable_temporal=True,
- temporal_granularity="day"
-)
-
-kg = builder.build(entities, relationships)
-
-# Export
-kg.to_neo4j("bolt://localhost:7687", "neo4j", "password")
-kg.to_rdf("output.ttl", format="turtle")
-
-print(f"Nodes: {kg.node_count}, Edges: {kg.edge_count}")
-```
-
----
-
-### EntityResolver
-
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `resolve(graph)` | Resolve all entities | Clustering + merging pipeline |
-| `find_duplicates(entities)` | Find duplicate entities | Similarity-based grouping |
-| `merge_entities(entity_group)` | Merge entity group | Property aggregation with conflict resolution |
-| `calculate_similarity(e1, e2)` | Calculate entity similarity | Weighted combination: string (0.4) + semantic (0.6) |
-| `cluster_entities(entities)` | Cluster similar entities | Agglomerative clustering |
-
-**Similarity Calculation:**
+builder = GraphBuilder(merge_entities=True)
+kg = builder.build([source1, source2])
```
-similarity = 0.4 * string_similarity(e1.name, e2.name) +
- 0.6 * cosine_similarity(embedding(e1), embedding(e2))
-```
-
-**Example:**
-
-```python
-from semantica.kg import EntityResolver
-
-resolver = EntityResolver(
- similarity_threshold=0.85,
- merge_strategy="highest_confidence", # "voting", "most_recent", "highest_confidence"
- use_embeddings=True
-)
-
-resolved_kg = resolver.resolve(kg)
-print(f"Merged {resolver.stats['duplicates_found']} duplicate entities")
-```
-
----
### GraphAnalyzer
+Runs analytical algorithms.
**Methods:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `compute_metrics()` | Compute graph metrics | Density, diameter, clustering coefficient |
-| `analyze_structure()` | Analyze graph structure | Component analysis, connectivity |
-| `find_patterns(pattern_type)` | Find graph patterns | Subgraph matching, motif detection |
-| `detect_anomalies()` | Detect graph anomalies | Statistical outlier detection |
-| `calculate_density()` | Calculate graph density | `E / (n*(n-1)/2)` |
-
-**Graph Metrics:**
-- **Density**: Ratio of actual edges to possible edges
-- **Diameter**: Longest shortest path in the graph
-- **Average Degree**: Mean number of connections per node
-- **Clustering Coefficient**: Measure of local clustering
-- **Connected Components**: Number of disconnected subgraphs
-
-**Example:**
+| Method | Description |
+|--------|-------------|
+| `centrality(method)` | Calculate importance |
+| `communities(method)` | Find clusters |
-```python
-from semantica.kg import GraphAnalyzer
-
-analyzer = GraphAnalyzer(kg)
-
-metrics = analyzer.compute_metrics()
-print(f"Density: {metrics['density']:.3f}")
-print(f"Diameter: {metrics['diameter']}")
-print(f"Avg degree: {metrics['avg_degree']:.2f}")
-print(f"Clustering: {metrics['clustering']:.3f}")
-```
-
----
-
-### CentralityCalculator
+### TemporalGraphQuery
+Queries time-aware graphs.
**Methods:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `pagerank(damping=0.85)` | Calculate PageRank | Power iteration method |
-| `betweenness_centrality()` | Calculate betweenness | Brandes' algorithm (BFS-based) |
-| `closeness_centrality()` | Calculate closeness | Average shortest path length |
-| `eigenvector_centrality()` | Calculate eigenvector centrality | Power iteration on adjacency matrix |
-| `degree_centrality()` | Calculate degree centrality | Normalized degree: `degree / (n-1)` |
-
-**PageRank Formula:**
-```
-PR(v) = (1-d)/N + d * Σ(PR(u)/L(u))
-where d = damping factor (0.85), N = total nodes, L(u) = outlinks from u
-```
-
-**Example:**
-
-```python
-from semantica.kg import CentralityCalculator
-
-centrality = CentralityCalculator(kg)
-
-# Calculate different centrality measures
-pagerank = centrality.pagerank(damping=0.85)
-betweenness = centrality.betweenness_centrality()
-closeness = centrality.closeness_centrality()
-
-# Find most influential entities
-top_entities = sorted(pagerank.items(), key=lambda x: x[1], reverse=True)[:10]
-
-for entity, score in top_entities:
- print(f"{entity}: {score:.3f}")
-```
+| Method | Description |
+|--------|-------------|
+| `at_time(timestamp)` | Graph state at T |
+| `during(start, end)` | Graph state in interval |
---
-### CommunityDetector
-
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `detect(algorithm)` | Detect communities | Specified algorithm (louvain/leiden/label_propagation) |
-| `louvain()` | Louvain method | Modularity optimization with greedy agglomeration |
-| `leiden()` | Leiden algorithm | Improved Louvain with quality guarantees |
-| `label_propagation()` | Label propagation | Fast community detection via label spreading |
-| `calculate_modularity(communities)` | Calculate modularity | Q = Σ(eii - ai²) |
-
-**Modularity Formula:**
-```
-Q = 1/(2m) * Σ[Aij - (ki*kj)/(2m)] * δ(ci, cj)
-where m = total edges, ki = degree of node i, ci = community of node i
-```
-
-**Example:**
+## Convenience Functions
```python
-from semantica.kg import CommunityDetector
-
-detector = CommunityDetector(kg)
+from semantica.kg import GraphBuilder, analyze_graph
-# Detect communities using Louvain
-communities = detector.detect(algorithm="louvain")
+# Build using GraphBuilder
+builder = GraphBuilder(resolve_conflicts=True)
+kg = builder.build(sources)
-print(f"Found {len(communities)} communities")
-for i, community in enumerate(communities[:5], 1):
- print(f"Community {i}: {len(community)} entities")
- print(f" Sample: {list(community)[:3]}")
+# Analyze
+stats = analyze_graph(kg)
+print(f"Communities: {stats['communities']}")
```
---
-### TemporalGraphQuery
-
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `query_at_time(query, timestamp)` | Query graph at specific time | Temporal filtering with valid_from/valid_until |
-| `query_time_range(query, start, end)` | Query over time range | Interval overlap detection |
-| `find_temporal_paths(source, target, time_range)` | Find time-aware paths | Temporal Dijkstra's algorithm |
-| `analyze_evolution(start, end, interval)` | Analyze graph evolution | Time-series analysis of graph metrics |
-| `detect_temporal_patterns(pattern_type)` | Detect temporal patterns | Sequential pattern mining |
-
-**Temporal Filtering:**
-```
-valid_at(edge, t) = (edge.valid_from <= t) AND (t <= edge.valid_until OR edge.valid_until IS NULL)
-```
+## Configuration
-**Example:**
+### Environment Variables
-```python
-from semantica.kg import TemporalGraphQuery
-from datetime import datetime
-
-temporal_query = TemporalGraphQuery(
- enable_temporal_reasoning=True,
- temporal_granularity="day"
-)
-
-# Query at specific time
-results = temporal_query.query_at_time(
- graph=kg,
- query="Who founded Apple Inc.?",
- at_time="2014-06-15"
-)
-
-# Query time range
-evolution = temporal_query.analyze_evolution(
- graph=kg,
- start_time="2000-01-01",
- end_time="2024-12-31",
- metrics=["node_count", "edge_count", "density"]
-)
+```bash
+export KG_MERGE_STRATEGY=fuzzy
+export KG_TEMPORAL_GRANULARITY=day
+export KG_CONFLICT_RESOLUTION=confidence
```
----
-
-### ConflictDetector
+### YAML Configuration
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `detect_conflicts(graph)` | Detect all conflicts | Multi-source comparison |
-| `resolve_conflict(conflict, strategy)` | Resolve single conflict | Strategy-based resolution |
-| `validate_consistency(graph)` | Validate logical consistency | Constraint checking |
-| `find_contradictions(entity)` | Find contradictory properties | Property value comparison |
-
-**Conflict Resolution Strategies:**
-- **Voting**: Majority value wins
-- **Credibility Weighted**: Weight by source credibility scores
-- **Most Recent**: Use most recent information
-- **Highest Confidence**: Use value with highest confidence score
-- **First Seen**: Use first encountered value
-
-**Example:**
-
-```python
-from semantica.kg import ConflictDetector
-
-detector = ConflictDetector(
- default_strategy="voting",
- track_provenance=True
-)
-
-conflicts = detector.detect_conflicts(kg)
-
-for conflict in conflicts:
- print(f"Conflict in {conflict.entity}: {conflict.property}")
- print(f" Values: {conflict.values}")
+```yaml
+kg:
+ resolution:
+ threshold: 0.9
+ strategy: semantic
- resolved = detector.resolve_conflict(conflict, strategy="voting")
- print(f" Resolved to: {resolved.value}")
+ temporal:
+ enabled: true
+ default_validity: infinite
```
---
-### ProvenanceTracker
-
+## Integration Examples
-**Methods:**
+### Temporal Analysis Pipeline
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `track(entity, source, timestamp)` | Track entity provenance | Metadata attachment |
-| `get_provenance(entity)` | Get entity provenance | Provenance retrieval |
-| `trace_lineage(entity)` | Trace entity lineage | Backward tracing through transformations |
-| `validate_provenance(entity)` | Validate provenance chain | Chain integrity checking |
+```python
+from semantica.kg import GraphBuilder, TemporalGraphQuery
----
+# 1. Build Temporal Graph
+builder = GraphBuilder(enable_temporal=True)
+kg = builder.build(temporal_data)
-## Configuration
+# 2. Query Evolution
+query = TemporalGraphQuery(kg)
+snapshot_2020 = query.at_time("2020-01-01")
+snapshot_2023 = query.at_time("2023-01-01")
-```yaml
-# config.yaml - Knowledge Graph Configuration
-
-kg:
- graph_builder:
- merge_entities: true
- entity_resolution_strategy: fuzzy # fuzzy, semantic, hybrid
- similarity_threshold: 0.85
- resolve_conflicts: true
- enable_temporal: true
- temporal_granularity: day # second, minute, hour, day, week, month, year
-
- entity_resolution:
- use_embeddings: true
- fuzzy_threshold: 0.80
- semantic_threshold: 0.85
- merge_strategy: highest_confidence
-
- conflict_resolution:
- default_strategy: voting # voting, credibility_weighted, most_recent, highest_confidence
- track_provenance: true
-
- graph_analytics:
- calculate_centrality: true
- detect_communities: true
- community_algorithm: louvain # louvain, leiden, label_propagation
-
- temporal:
- enable_versioning: true
- snapshot_interval: 30 # days
- track_history: true
+# 3. Compare
+diff = snapshot_2023.minus(snapshot_2020)
+print(f"New nodes since 2020: {len(diff.nodes)}")
```
---
-## Performance Characteristics
-
-### Graph Construction
-- **Incremental Building**: Efficient for large graphs
-- **Batch Processing**: Optimized for bulk operations
-- **Memory Management**: Streaming for very large graphs
+## Best Practices
-### Entity Resolution
-- **Fuzzy Matching**: O(n²) complexity, optimized with blocking
-- **Semantic Matching**: O(n) with vector index
-- **Hybrid**: Best of both approaches
-
-### Graph Analytics
-- **PageRank**: O(k*E) where k = iterations, E = edges
-- **Betweenness**: O(V*E) for unweighted graphs
-- **Community Detection**: O(E*log²V) for Louvain
+1. **Clean Data First**: Use `EntityResolver` aggressively to prevent "entity explosion" (too many duplicate nodes).
+2. **Use Provenance**: Always track sources (`track_history=True`) to debug where bad data came from.
+3. **Temporal Granularity**: Choose the right granularity (Day vs Second) to balance performance and precision.
+4. **Validate**: Run `GraphValidator` after building to ensure structural integrity.
---
## See Also
-- [Semantic Extract Module](semantic_extract.md) - Extract entities and relationships
-- [Vector Store Module](vector_store.md) - Store graph embeddings
-- [Triple Store Module](triple_store.md) - RDF storage
-- [Ontology Module](ontology.md) - Define graph schemas
+- [Graph Store Module](graph_store.md) - Persistence layer
+- [Semantic Extract Module](semantic_extract.md) - Data source
+- [Visualization Module](visualization.md) - Visualizing the KG
diff --git a/docs/reference/semantic_extract.md b/docs/reference/semantic_extract.md
index 334e454b..ed1a51fe 100644
--- a/docs/reference/semantic_extract.md
+++ b/docs/reference/semantic_extract.md
@@ -1,6 +1,6 @@
-# Semantic Extract Module
+# Semantic Extract
-> **Extract structured knowledge from unstructured text using state-of-the-art NLP and LLM models.**
+> **Advanced information extraction system for Entities, Relations, Events, and Triples.**
---
@@ -8,69 +8,73 @@
<div class="grid cards" markdown>
-- :material-account-search:{ .lg .middle } **Named Entity Recognition**
+- :material-account-search:{ .lg .middle } **NER**
---
- Extract people, organizations, locations, dates, and custom entities with high accuracy
+ Extract Named Entities (Person, Org, Loc) with confidence scores
-- :material-graph:{ .lg .middle } **Relationship Extraction**
+- :material-relation-one-to-one:{ .lg .middle } **Relation Extraction**
---
- Identify semantic, temporal, and causal relationships between entities
+ Identify relationships between entities (e.g., `founded_by`, `located_in`)
- :material-calendar-clock:{ .lg .middle } **Event Detection**
---
- Detect and classify events like acquisitions, partnerships, announcements
+ Detect events with temporal information and participants
-- :material-cube-outline:{ .lg .middle } **Triple Extraction**
+- :material-format-quote-close:{ .lg .middle } **Coreference**
---
- Generate RDF triples for knowledge graphs in multiple formats
+ Resolve pronouns ("he", "it") to their entity references
-- :material-link-variant:{ .lg .middle } **Coreference Resolution**
+- :material-share-variant:{ .lg .middle } **Triple Extraction**
---
- Resolve pronouns and entity mentions across documents
+ Extract Subject-Predicate-Object triples for Knowledge Graphs
-- :material-brain:{ .lg .middle } **Semantic Analysis**
+- :material-robot:{ .lg .middle } **LLM Enhancement**
---
- Deep semantic understanding with role labeling and clustering
+ Use LLMs to improve extraction quality and handle complex schemas
</div>
+!!! tip "When to Use"
+ - **KG Construction**: Converting unstructured text into structured graph data
+ - **Text Analysis**: Identifying key actors and events in documents
+ - **Search Indexing**: Extracting metadata for faceted search
+ - **Data Enrichment**: Adding semantic tags to content
+
---
## ⚙️ Algorithms Used
-### Entity Extraction Algorithms
-- **Transformer-based NER**: BERT, RoBERTa, DeBERTa models for high-accuracy entity recognition
-- **spaCy Statistical Models**: Fast, production-ready NER with en_core_web_sm/lg models
-- **Rule-based Matching**: Pattern-based entity detection using regex and linguistic rules
-- **LLM-based Extraction**: GPT-4, Claude for complex entity extraction with few-shot learning
+### Named Entity Recognition (NER)
+- **Transformer Models**: BERT/RoBERTa for token classification.
+- **Regex Patterns**: Pattern matching for specific formats (Emails, IDs).
+- **LLM Prompting**: Zero-shot extraction for custom entity types.
-### Relationship Extraction Algorithms
-- **Dependency Parsing**: Syntactic dependency trees for relationship identification
-- **Pattern Matching**: Rule-based relationship templates
-- **Neural Relation Classification**: BERT-based relation classifiers
-- **Hybrid Approach**: Combines rule-based + ML + LLM for optimal accuracy
+### Relation Extraction
+- **Dependency Parsing**: Analyzing grammatical structure to find subject-verb-object paths.
+- **Joint Extraction**: Extracting entities and relations simultaneously.
+- **Semantic Role Labeling**: Identifying "Who did What to Whom".
-### Coreference Resolution Algorithms
-- **Neural Coreference**: Span-based neural models for pronoun resolution
-- **Rule-based Resolution**: Heuristic rules for simple coreference cases
-- **Cluster-based Merging**: Entity mention clustering across documents
+### Coreference Resolution
+- **Mention Detection**: Finding all potential references (nouns, pronouns).
+- **Clustering**: Grouping mentions that refer to the same real-world entity.
+- **Pronoun Resolution**: Mapping pronouns to the most likely antecedent.
-### Triple Extraction Algorithms
-- **Subject-Predicate-Object Extraction**: Dependency parsing for triple generation
-- **RDF Serialization**: Turtle, N-Triples, JSON-LD format generation
-- **Triple Validation**: Schema-based validation and quality checking
+### Triple 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.
---
@@ -78,103 +82,104 @@
### NamedEntityRecognizer
+Coordinator for entity extraction.
+
+**Parameters:**
+
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `methods` | list | `["spacy"]` | Extraction methods to use |
+| `confidence_threshold` | float | `0.5` | Minimum confidence score |
+| `merge_overlapping` | bool | `True` | Merge overlapping entities |
+| `include_standard_types` | bool | `True` | Include Person, Org, Location |
**Methods:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `extract(text)` | Extract entities from text | Transformer-based NER with confidence scoring |
-| `extract_batch(texts)` | Batch entity extraction | Parallel processing with batching |
-| `add_custom_entity_type(name, patterns)` | Add custom entity type | Pattern matching with regex |
-| `classify_entity(entity)` | Classify entity type | Multi-class classification |
-| `score_confidence(entity)` | Calculate confidence score | Softmax probability scoring |
+| Method | Description |
+|--------|-------------|
+| `extract_entities(text)` | Get list of entities |
+| `add_custom_pattern(pattern)` | Add regex rule |
**Example:**
```python
from semantica.semantic_extract import NamedEntityRecognizer
-# Initialize with transformer model
+# Basic usage
+ner = NamedEntityRecognizer()
+entities = ner.extract_entities("Elon Musk leads SpaceX.")
+# [Entity(text="Elon Musk", label="PERSON"), Entity(text="SpaceX", label="ORG")]
+
+# With configuration
ner = NamedEntityRecognizer(
- model="transformer", # or "spacy", "stanza", "custom"
- lang="en",
- entities=["PERSON", "ORG", "LOC", "DATE", "MONEY"],
+ methods=["spacy", "rule-based"],
confidence_threshold=0.7,
- use_llm_enhancement=True
+ merge_overlapping=True
)
-
-text = "Apple Inc. was founded by Steve Jobs in 1976."
-entities = ner.extract(text)
-
-for entity in entities:
- print(f"{entity.text} ({entity.type}, confidence={entity.confidence:.2f})")
-# Output:
-# Apple Inc. (ORG, confidence=0.98)
-# Steve Jobs (PERSON, confidence=0.97)
-# 1976 (DATE, confidence=1.00)
+entities = ner.extract_entities("Apple Inc. was founded in 1976.")
```
----
-
### RelationExtractor
+Extracts relationships between entities.
-**Methods:**
+**Parameters:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `extract(text, entities)` | Extract relationships | Hybrid: dependency parsing + ML + LLM |
-| `extract_with_context(text, entities, context)` | Context-aware extraction | Contextual embeddings with attention |
-| `add_custom_relation(name, pattern)` | Add custom relation type | Pattern-based rule addition |
-| `classify_relation(subject, object, context)` | Classify relation type | Neural relation classification |
-| `score_confidence(relation)` | Calculate relation confidence | Ensemble scoring from multiple models |
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `relation_types` | list | `None` | Specific relation types to extract |
+| `bidirectional` | bool | `False` | Extract bidirectional relations |
+| `confidence_threshold` | float | `0.6` | Minimum confidence score |
+| `max_distance` | int | `50` | Max token distance between entities |
-**Algorithms:**
+**Methods:**
-- **Rule-based**: Pattern matching using dependency trees
-- **ML-based**: BERT fine-tuned on relation extraction datasets
-- **Hybrid**: Combines rules + ML for high precision and recall
-- **LLM-based**: Few-shot prompting with GPT-4/Claude for complex relations
+| Method | Description |
+|--------|-------------|
+| `extract_relations(text, entities)` | Find links |
**Example:**
```python
-from semantica.semantic_extract import RelationExtractor
+from semantica.semantic_extract import RelationExtractor, NamedEntityRecognizer
-extractor = RelationExtractor(
- strategy="hybrid", # "rule-based", "ml-based", "hybrid", "llm-based"
- confidence_threshold=0.7,
- max_relationships_per_entity=10
-)
+# First extract entities
+ner = NamedEntityRecognizer()
+text = "Elon Musk founded SpaceX in 2002."
+entities = ner.extract_entities(text)
-relationships = extractor.extract(text, entities)
+# Basic relation extraction
+rel_extractor = RelationExtractor()
+relations = rel_extractor.extract_relations(text, entities=entities)
+# [Relation(source="Elon Musk", target="SpaceX", type="founded")]
-for rel in relationships:
- print(f"{rel.subject} --[{rel.predicate}]--> {rel.object}")
-# Output:
-# Apple Inc. --[founded_by]--> Steve Jobs
+# With configuration
+rel_extractor = RelationExtractor(
+ relation_types=["founded", "leads", "works_at"],
+ confidence_threshold=0.7,
+ bidirectional=False
+)
+relations = rel_extractor.extract_relations(text, entities=entities)
```
----
-
### EventDetector
+Identifies events with temporal information and participants.
-**Methods:**
+**Parameters:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `detect(text, entities)` | Detect events in text | Event trigger detection + argument extraction |
-| `detect_batch(texts, entities_list)` | Batch event detection | Parallel processing |
-| `classify_event(event)` | Classify event type | Multi-label classification |
-| `extract_participants(event, entities)` | Extract event participants | Role labeling with semantic roles |
-| `extract_temporal_info(event)` | Extract event timing | Temporal expression extraction |
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `event_types` | list | `None` | Specific event types to detect |
+| `extract_participants` | bool | `True` | Extract event participants |
+| `extract_location` | bool | `True` | Extract event locations |
+| `extract_time` | bool | `True` | Extract temporal information |
+
+**Methods:**
-**Event Types Supported:**
-- ACQUISITION, FOUNDING, PARTNERSHIP, ANNOUNCEMENT
-- MERGER, IPO, BANKRUPTCY, LAWSUIT
-- PRODUCT_LAUNCH, CONFERENCE, ELECTION
-- Custom event types via configuration
+| Method | Description |
+|--------|-------------|
+| `detect_events(text)` | Find events |
**Example:**
@@ -182,37 +187,29 @@ for rel in relationships:
from semantica.semantic_extract import EventDetector
detector = EventDetector(
- event_types=["ACQUISITION", "FOUNDING", "PARTNERSHIP"],
- min_confidence=0.75
+ event_types=["launch", "acquisition", "announcement"],
+ extract_participants=True,
+ extract_time=True
)
-
-events = detector.detect(text, entities)
-
-for event in events:
- print(f"{event.type}: {event.description}")
- print(f"Participants: {[p.name for p in event.participants]}")
+events = detector.detect_events("SpaceX launched Starship on March 14, 2024.")
```
----
-
### TripleExtractor
+Extracts RDF triples (Subject-Predicate-Object).
-**Methods:**
+**Parameters:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `extract(text, entities, relationships)` | Extract RDF triples | Subject-predicate-object extraction from parse trees |
-| `extract_from_relations(relationships)` | Convert relations to triples | Direct mapping with URI generation |
-| `validate_triples(triples)` | Validate triple quality | Schema validation + consistency checking |
-| `serialize(triples, format)` | Serialize to RDF format | Turtle, N-Triples, JSON-LD serialization |
-| `generate_uri(entity)` | Generate URI for entity | Namespace + normalized entity name |
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `include_temporal` | bool | `False` | Include time information |
+| `include_provenance` | bool | `False` | Track source sentences |
-**Supported Formats:**
-- **RDF/XML**: W3C standard RDF format
-- **Turtle**: Human-readable RDF format
-- **N-Triples**: Line-based RDF format
-- **JSON-LD**: JSON-based linked data format
+**Methods:**
+
+| Method | Description |
+|--------|-------------|
+| `extract_triples(text)` | Get (S, P, O) tuples |
**Example:**
@@ -220,210 +217,120 @@ for event in events:
from semantica.semantic_extract import TripleExtractor
extractor = TripleExtractor(
- format="rdf", # "rdf", "turtle", "n-triples", "json-ld"
- validate_triples=True,
- namespace="http://example.org/"
+ include_temporal=True,
+ include_provenance=True
)
-
-triples = extractor.extract(text, entities, relationships)
-
-for triple in triples:
- print(f"{triple.subject} {triple.predicate} {triple.object}")
-# Output:
-# <Apple_Inc> <founded_by> <Steve_Jobs>
-# <Apple_Inc> <founded_in> "1976"^^xsd:gYear
+triples = extractor.extract_triples("Steve Jobs founded Apple in 1976.")
+# [Triple(subject="Steve Jobs", predicate="founded", object="Apple", temporal="1976")]
```
---
-### CoreferenceResolver
-
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `resolve(text, entities)` | Resolve coreferences | Neural coreference resolution with span ranking |
-| `resolve_batch(texts, entities_list)` | Batch resolution | Parallel coreference resolution |
-| `cluster_mentions(mentions)` | Cluster entity mentions | Agglomerative clustering with similarity threshold |
-| `merge_entities(entity_clusters)` | Merge coreferent entities | Property aggregation with conflict resolution |
-| `resolve_pronouns(text, entities)` | Resolve pronoun references | Rule-based + neural pronoun resolution |
-
-**Algorithms:**
-- **Neural Method**: Span-based neural coreference (e2e-coref, SpanBERT)
-- **Rule-based Method**: Heuristic rules for simple cases (gender, number agreement)
-- **Hybrid Method**: Combines neural + rules for optimal performance
-
-**Example:**
+## Convenience Functions
```python
-from semantica.semantic_extract import CoreferenceResolver
-
-resolver = CoreferenceResolver(
- method="neural", # "rule-based", "neural", "hybrid"
- resolve_pronouns=True
+from semantica.semantic_extract import (
+ NamedEntityRecognizer,
+ RelationExtractor,
+ TripleExtractor,
+ EventDetector,
+ CoreferenceResolver
)
-resolved_entities = resolver.resolve(text, entities)
-```
-
----
-
-### SemanticAnalyzer
-
-
-**Methods:**
+text = "Apple released the iPhone in 2007. Steve Jobs announced it at Macworld."
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `analyze_semantics(text, entities, relationships)` | Analyze semantic structure | Semantic role labeling + clustering |
-| `extract_semantic_roles(text)` | Extract semantic roles | PropBank/FrameNet-based role labeling |
-| `cluster_semantically(entities)` | Cluster by semantic similarity | K-means clustering on embeddings |
-| `calculate_similarity(entity1, entity2)` | Calculate semantic similarity | Cosine similarity on embeddings |
-| `analyze_coherence(text)` | Analyze text coherence | Coherence scoring with discourse analysis |
+# Extract entities with confidence filtering
+ner = NamedEntityRecognizer(confidence_threshold=0.7)
+entities = ner.extract_entities(text)
-**Example:**
+# Resolve coreferences (recommended before relation extraction)
+coref = CoreferenceResolver()
+resolved = coref.resolve(text)
-```python
-from semantica.semantic_extract import SemanticAnalyzer
+# Extract relations
+rel_extractor = RelationExtractor(confidence_threshold=0.6)
+relations = rel_extractor.extract_relations(text, entities=entities)
-analyzer = SemanticAnalyzer()
+# Extract triples for KG
+triple_extractor = TripleExtractor(include_temporal=True)
+triples = triple_extractor.extract_triples(text)
-analysis = analyzer.analyze_semantics(
- text=text,
- entities=entities,
- relationships=relationships
-)
+# Detect events
+event_detector = EventDetector(extract_time=True)
+events = event_detector.detect_events(text)
-print(f"Coherence score: {analysis.coherence_score:.2f}")
-print(f"Semantic roles: {analysis.semantic_roles}")
+print(f"Entities: {len(entities)}")
+print(f"Relations: {len(relations)}")
+print(f"Triples: {len(triples)}")
+print(f"Events: {len(events)}")
```
---
-### LLMEnhancer
-
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `enhance_entities(text, entities)` | Enhance entities with LLM | Few-shot prompting for entity enrichment |
-| `enhance_relationships(text, relationships)` | Enhance relationships | LLM-based relationship validation and enrichment |
-| `generate_descriptions(entity)` | Generate entity descriptions | LLM text generation |
-| `validate_extractions(extractions)` | Validate with LLM | LLM-based quality checking |
-| `classify_with_llm(text, labels)` | LLM-based classification | Zero/few-shot classification |
-
-**Supported LLM Providers:**
-- OpenAI (GPT-4, GPT-3.5-turbo)
-- Anthropic (Claude 3 Opus, Sonnet, Haiku)
-- Google (Gemini Pro, Ultra)
-- Groq (Mixtral, Llama)
-- Ollama (Local models)
-
-**Example:**
-
-```python
-from semantica.semantic_extract import LLMEnhancer
+## Configuration
-enhancer = LLMEnhancer(
- provider="openai",
- model="gpt-4",
- temperature=0.1
-)
+### Environment Variables
-enhanced_entities = enhancer.enhance_entities(text, entities)
-enhanced_relationships = enhancer.enhance_relationships(text, relationships)
+```bash
+export NER_MODEL=dslim/bert-base-NER
+export RELATION_MODEL=semantica/rel-extract-v1
+export EXTRACT_CONFIDENCE_THRESHOLD=0.7
```
----
-
-### ExtractionValidator
-
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `validate(text, entities, relationships, triples)` | Validate all extractions | Multi-level validation pipeline |
-| `validate_entities(entities)` | Validate entity quality | Schema validation + consistency checks |
-| `validate_relationships(relationships)` | Validate relationships | Type checking + logical validation |
-| `validate_triples(triples)` | Validate RDF triples | RDF schema validation |
-| `check_consistency(extractions)` | Check extraction consistency | Cross-validation between extraction types |
-
-**Validation Checks:**
-- **Schema Validation**: Type checking against ontology
-- **Consistency Checking**: Cross-validation between entities and relationships
-- **Quality Scoring**: Confidence-based quality metrics
-- **Completeness**: Required property validation
-
----
-
-## Configuration
+### YAML Configuration
```yaml
-# config.yaml - Semantic Extract Configuration
-
semantic_extract:
ner:
- model: transformer # spacy, stanza, transformer, llm
- lang: en
- entities: [PERSON, ORG, LOC, DATE, MONEY, PRODUCT]
- confidence_threshold: 0.7
- use_llm_enhancement: false
-
- relation_extraction:
- strategy: hybrid # rule-based, ml-based, hybrid, llm-based
- confidence_threshold: 0.7
- max_relationships_per_entity: 10
-
- event_detection:
- event_types: [ACQUISITION, FOUNDING, PARTNERSHIP, ANNOUNCEMENT]
- min_confidence: 0.75
- extract_participants: true
- extract_temporal: true
+ model: dslim/bert-base-NER
+ min_confidence: 0.7
- triple_extraction:
- format: turtle # rdf, turtle, n-triples, json-ld
- validate_triples: true
- namespace: "http://example.org/"
+ relations:
+ max_distance: 50 # tokens
coreference:
- method: neural # rule-based, neural, hybrid
- resolve_pronouns: true
- cluster_threshold: 0.85
-
- llm:
- provider: openai
- model: gpt-4
- temperature: 0.1
- max_tokens: 4000
+ enabled: true
```
---
-## Performance Characteristics
+## Integration Examples
+
+### KG Population Pipeline
-### Entity Extraction
-- **Transformer models**: High accuracy, moderate speed
-- **spaCy models**: Fast, good accuracy for common entities
-- **LLM-based**: Highest accuracy, slower, best for complex domains
+```python
+from semantica.semantic_extract import NamedEntityRecognizer, RelationExtractor, TripleExtractor
+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)
+
+# 2. Populate KG using GraphBuilder
+builder = GraphBuilder()
+sources = [{
+ "entities": entities,
+ "relationships": [{"source": t.subject, "target": t.object, "type": t.predicate} for t in triples]
+}]
+kg = builder.build(sources)
+```
+
+---
-### Relationship Extraction
-- **Rule-based**: Fast, high precision, lower recall
-- **ML-based**: Balanced precision/recall
-- **Hybrid**: Best overall performance
-- **LLM-based**: Highest quality, slower
+## Best Practices
-### Scalability
-- Batch processing supported for all extractors
-- Parallel processing for multi-document extraction
-- GPU acceleration available for transformer models
+1. **Resolve Coreferences**: Always run coreference resolution *before* relation extraction to link "He" to "John Doe".
+2. **Filter Low Confidence**: Set a confidence threshold (e.g., 0.7) to reduce noise.
+3. **Use Custom Patterns**: For domain-specific IDs (e.g., "Invoice #123"), regex is faster and more accurate than ML.
+4. **Batch Processing**: Use batch methods when processing large corpora.
---
## See Also
-- [Knowledge Graph Module](kg.md) - Build graphs from extracted data
-- [Ontology Module](ontology.md) - Define extraction schemas
-- [Core Module](core.md) - Framework orchestration
+- [Parse Module](parse.md) - Prepares text for extraction
+- [Ontology Module](ontology.md) - Defines the schema for extraction
+- [Knowledge Graph Module](kg.md) - Stores the extracted data
diff --git a/semantica/__init__.py b/semantica/__init__.py
index 8ad8960c..c7cf9449 100644
--- a/semantica/__init__.py
+++ b/semantica/__init__.py
@@ -8,88 +8,88 @@ Main exports:
- Semantica: Main framework class
- PipelineBuilder: Pipeline construction DSL
- Config: Configuration management
- - build: Module-level build function for easy access
"""
-__version__ = "0.0.1"
+__version__ = "0.0.5"
__author__ = "Semantica Contributors"
__license__ = "MIT"
-from typing import Any, Dict, List, Optional, Union
+# Import submodules for dot notation access
+import importlib
from pathlib import Path
+from typing import Any, Dict, List, Optional, Union
# Core imports
-from .core import Semantica, Config, ConfigManager, LifecycleManager, PluginRegistry
-
-# Pipeline imports
-from .pipeline import (
- PipelineBuilder,
- ExecutionEngine,
- FailureHandler,
- ParallelismManager,
- ResourceScheduler,
- PipelineValidator,
-)
+from .core import Config, ConfigManager, LifecycleManager, PluginRegistry, Semantica
# KG Quality Assurance
from .kg_qa import (
- KGQualityAssessor,
- ConsistencyChecker,
- CompletenessValidator,
- QualityMetrics,
+ AutomatedFixer,
+ AutoMerger,
+ AutoResolver,
CompletenessMetrics,
+ CompletenessValidator,
+ ConsistencyChecker,
ConsistencyMetrics,
- ValidationEngine,
- RuleValidator,
ConstraintValidator,
- QualityReporter,
- IssueTracker,
ImprovementSuggestions,
- AutomatedFixer,
- AutoMerger,
- AutoResolver,
+ IssueTracker,
+ KGQualityAssessor,
+ QualityMetrics,
+ QualityReporter,
+ RuleValidator,
+ ValidationEngine,
+)
+
+# Pipeline imports
+from .pipeline import (
+ ExecutionEngine,
+ FailureHandler,
+ ParallelismManager,
+ PipelineBuilder,
+ PipelineValidator,
+ ResourceScheduler,
)
# Visualization
from .visualization import (
+ AnalyticsVisualizer,
+ EmbeddingVisualizer,
KGVisualizer,
OntologyVisualizer,
- EmbeddingVisualizer,
- SemanticNetworkVisualizer,
QualityVisualizer,
- AnalyticsVisualizer,
+ SemanticNetworkVisualizer,
TemporalVisualizer,
)
-# Import submodules for dot notation access
-import importlib
# Module proxy class for submodule access
class _ModuleProxy:
"""Proxy class to enable dot notation access to submodules."""
-
+
def __init__(self, module_name: str):
self._module_name = module_name
self._module = None
-
+
def _get_module(self):
"""Lazy load the module."""
if self._module is None:
self._module = importlib.import_module(f"semantica.{self._module_name}")
return self._module
-
+
def __getattr__(self, name: str):
"""Delegate attribute access to the actual module."""
return getattr(self._get_module(), name)
-
+
def __dir__(self):
"""Return directory of the actual module."""
return dir(self._get_module())
+
# Create module proxies for submodule access
class _SemanticaModules:
"""Container for submodule proxies."""
-
+
def __init__(self):
self._kg = None
self._ingest = None
@@ -103,92 +103,101 @@ class _SemanticaModules:
self._export = None
self._vector_store = None
self._triple_store = None
+ self._graph_store = None
self._ontology = None
-
+ self._evals = None
+
@property
def kg(self):
"""Access knowledge graph module."""
if self._kg is None:
self._kg = _ModuleProxy("kg")
return self._kg
-
+
@property
def ingest(self):
"""Access ingestion module."""
if self._ingest is None:
self._ingest = _ModuleProxy("ingest")
return self._ingest
-
+
@property
def embeddings(self):
"""Access embeddings module."""
if self._embeddings is None:
self._embeddings = _ModuleProxy("embeddings")
return self._embeddings
-
+
@property
def semantic_extract(self):
"""Access semantic extraction module."""
if self._semantic_extract is None:
self._semantic_extract = _ModuleProxy("semantic_extract")
return self._semantic_extract
-
+
@property
def visualization(self):
"""Access visualization module."""
if self._visualization is None:
self._visualization = _ModuleProxy("visualization")
return self._visualization
-
+
@property
def kg_qa(self):
"""Access KG quality assurance module."""
if self._kg_qa is None:
self._kg_qa = _ModuleProxy("kg_qa")
return self._kg_qa
-
+
@property
def pipeline(self):
"""Access pipeline module."""
if self._pipeline is None:
self._pipeline = _ModuleProxy("pipeline")
return self._pipeline
-
+
@property
def parse(self):
"""Access parsing module."""
if self._parse is None:
self._parse = _ModuleProxy("parse")
return self._parse
-
+
@property
def normalize(self):
"""Access normalization module."""
if self._normalize is None:
self._normalize = _ModuleProxy("normalize")
return self._normalize
-
+
@property
def export(self):
"""Access export module."""
if self._export is None:
self._export = _ModuleProxy("export")
return self._export
-
+
@property
def vector_store(self):
"""Access vector store module."""
if self._vector_store is None:
self._vector_store = _ModuleProxy("vector_store")
return self._vector_store
-
+
@property
def triple_store(self):
"""Access triple store module."""
if self._triple_store is None:
self._triple_store = _ModuleProxy("triple_store")
return self._triple_store
-
+
+ @property
+ def graph_store(self):
+ """Access graph store module."""
+ if self._graph_store is None:
+ self._graph_store = _ModuleProxy("graph_store")
+ return self._graph_store
+
@property
def ontology(self):
"""Access ontology module."""
@@ -196,62 +205,17 @@ class _SemanticaModules:
self._ontology = _ModuleProxy("ontology")
return self._ontology
+ @property
+ def evals(self):
+ """Access evaluation module."""
+ if self._evals is None:
+ self._evals = _ModuleProxy("evals")
+ return self._evals
+
+
# Create singleton instance for module access
_modules = _SemanticaModules()
-# Singleton Semantica instance for module-level build()
-_semantica_instance: Optional[Semantica] = None
-
-def _get_semantica_instance(config: Optional[Union[Config, Dict[str, Any]]] = None, **kwargs) -> Semantica:
- """Get or create singleton Semantica instance."""
- global _semantica_instance
- if _semantica_instance is None:
- _semantica_instance = Semantica(config=config, **kwargs)
- return _semantica_instance
-
-def build(
- sources: Union[List[Union[str, Path]], str, Path],
- config: Optional[Union[Config, Dict[str, Any]]] = None,
- **kwargs
-) -> Dict[str, Any]:
- """
- Build knowledge base from data sources (module-level convenience function).
-
- This is a user-friendly wrapper around Semantica.build_knowledge_base()
- that handles initialization automatically.
-
- Args:
- sources: Data source(s) - can be a single path/URL or list of paths/URLs
- config: Optional configuration object or dict
- **kwargs: Additional processing options:
- - embeddings: Whether to generate embeddings (default: True)
- - graph: Whether to build knowledge graph (default: True)
- - normalize: Whether to normalize data (default: True)
- - pipeline: Custom pipeline configuration
- - fail_fast: Whether to fail on first error (default: False)
-
- Returns:
- Dictionary containing:
- - knowledge_graph: Knowledge graph data
- - embeddings: Embedding vectors
- - metadata: Processing metadata
- - statistics: Processing statistics
- - results: Processing results
-
- Examples:
- >>> from semantica import build
- >>> result = build(["doc1.pdf", "doc2.docx"], embeddings=True, graph=True)
- >>> print(result["statistics"])
- """
- # Normalize sources to list
- if isinstance(sources, (str, Path)):
- sources = [sources]
-
- # Get or create Semantica instance
- semantica = _get_semantica_instance(config=config, **kwargs)
-
- # Build knowledge base (auto-initializes if needed)
- return semantica.build_knowledge_base(sources, **kwargs)
__all__ = [
# Core
@@ -260,8 +224,6 @@ __all__ = [
"ConfigManager",
"LifecycleManager",
"PluginRegistry",
- # Module-level function
- "build",
# Pipeline
"PipelineBuilder",
"ExecutionEngine",
@@ -295,13 +257,26 @@ __all__ = [
"TemporalVisualizer",
]
+
# Make submodules accessible via dot notation
-# This allows: import semantica; semantica.kg.build()
def __getattr__(name: str):
"""Enable dot notation access to submodules."""
- if name in ["kg", "ingest", "embeddings", "semantic_extract", "visualization",
- "kg_qa", "pipeline", "parse", "normalize", "export",
- "vector_store", "triple_store", "ontology"]:
+ if name in [
+ "kg",
+ "ingest",
+ "embeddings",
+ "semantic_extract",
+ "visualization",
+ "kg_qa",
+ "pipeline",
+ "parse",
+ "normalize",
+ "export",
+ "vector_store",
+ "triple_store",
+ "graph_store",
+ "ontology",
+ "evals",
+ ]:
return getattr(_modules, name)
raise AttributeError(f"module 'semantica' has no attribute '{name}'")
-
diff --git a/semantica/core/__init__.py b/semantica/core/__init__.py
index cb3799d7..25cdf9b2 100644
--- a/semantica/core/__init__.py
+++ b/semantica/core/__init__.py
@@ -31,16 +31,12 @@ Main Components:
- Orchestration Methods: Reusable functions for common orchestration tasks
Example Usage:
- >>> from semantica.core import Semantica, build
+ >>> from semantica.core import Semantica
>>> # Using main class
>>> framework = Semantica()
>>> framework.initialize()
>>> result = framework.build_knowledge_base(sources=["doc1.pdf"])
>>>
- >>> # Using convenience function
- >>> from semantica.core import build
- >>> result = build(sources=["doc1.pdf", "doc2.docx"], embeddings=True, graph=True)
- >>>
>>> # Using methods directly
>>> from semantica.core.methods import build_knowledge_base
>>> result = build_knowledge_base(sources=["doc.pdf"], method="default")
@@ -49,45 +45,40 @@ Author: Semantica Contributors
License: MIT
"""
-from typing import Any, Dict, List, Optional, Union
from pathlib import Path
+from typing import Any, Dict, List, Optional, Union
-from .orchestrator import Semantica
from .config_manager import Config, ConfigManager
-from .lifecycle import LifecycleManager, SystemState, HealthStatus
-from .plugin_registry import PluginRegistry, PluginInfo, LoadedPlugin
-from .registry import MethodRegistry, method_registry
+from .lifecycle import HealthStatus, LifecycleManager, SystemState
from .methods import (
build_knowledge_base,
- run_pipeline,
- initialize_framework,
- get_status,
get_orchestration_method,
- list_available_methods
+ get_status,
+ initialize_framework,
+ list_available_methods,
+ run_pipeline,
)
+from .orchestrator import Semantica
+from .plugin_registry import LoadedPlugin, PluginInfo, PluginRegistry
+from .registry import MethodRegistry, method_registry
__all__ = [
# Main orchestrator
"Semantica",
-
# Configuration
"Config",
"ConfigManager",
-
# Lifecycle
"LifecycleManager",
"SystemState",
"HealthStatus",
-
# Plugins
"PluginRegistry",
"PluginInfo",
"LoadedPlugin",
-
# Registry
"MethodRegistry",
"method_registry",
-
# Methods
"build_knowledge_base",
"run_pipeline",
@@ -95,73 +86,4 @@ __all__ = [
"get_status",
"get_orchestration_method",
"list_available_methods",
-
- # Convenience
- "build",
]
-
-
-def build(
- sources: Union[str, List[Union[str, Path]]],
- extract_entities: bool = True,
- extract_relations: bool = True,
- embeddings: bool = True,
- graph: bool = True,
- **options
-) -> Dict[str, Any]:
- """
- Build knowledge base from sources (module-level convenience function).
-
- This is a user-friendly wrapper that performs comprehensive knowledge base
- construction including entity extraction, relation extraction, embeddings,
- and knowledge graph building.
-
- Args:
- sources: Input source or list of sources (files, URLs, streams)
- extract_entities: Whether to extract named entities (default: True)
- extract_relations: Whether to extract relationships (default: True)
- embeddings: Whether to generate embeddings (default: True)
- graph: Whether to build knowledge graph (default: True)
- **options: Additional processing options
-
- Returns:
- Dictionary containing:
- - knowledge_graph: Knowledge graph data
- - embeddings: Embedding vectors
- - results: Processing results
- - statistics: Processing statistics
- - metadata: Processing metadata
-
- Examples:
- >>> import semantica
- >>> result = semantica.core.build(
- ... sources=["doc1.pdf", "doc2.docx"],
- ... extract_entities=True,
- ... extract_relations=True,
- ... embeddings=True,
- ... graph=True
- ... )
- >>> print(f"Processed {result['statistics']['sources_processed']} sources")
- """
- # Normalize sources to list
- if isinstance(sources, str):
- sources = [sources]
-
- # Build pipeline configuration from options
- pipeline_config = options.get("pipeline", {})
- if extract_entities or extract_relations:
- pipeline_config.setdefault("extract", {})
- if extract_entities:
- pipeline_config["extract"]["entities"] = True
- if extract_relations:
- pipeline_config["extract"]["relations"] = True
-
- # Build knowledge base
- return build_knowledge_base(
- sources=sources,
- method=options.get("method", "default"),
- embeddings=embeddings,
- graph=graph,
- pipeline=pipeline_config,
- **{k: v for k, v in options.items() if k not in ["pipeline", "method"]}
- )
\ No newline at end of file
diff --git a/semantica/embeddings/__init__.py b/semantica/embeddings/__init__.py
index 8ae788eb..d72544e7 100644
--- a/semantica/embeddings/__init__.py
+++ b/semantica/embeddings/__init__.py
@@ -105,47 +105,48 @@ Author: Semantica Contributors
License: MIT
"""
-from typing import Any, Dict, List, Optional, Union
from pathlib import Path
+from typing import Any, Dict, List, Optional, Union
+
import numpy as np
-from .embedding_generator import EmbeddingGenerator
-from .text_embedder import TextEmbedder
-from .image_embedder import ImageEmbedder
from .audio_embedder import AudioEmbedder
-from .multimodal_embedder import MultimodalEmbedder
-from .embedding_optimizer import EmbeddingOptimizer
+from .config import EmbeddingsConfig, embeddings_config
from .context_manager import ContextManager, ContextWindow
-from .provider_adapters import (
- ProviderAdapter,
- OpenAIAdapter,
- BGEAdapter,
- LlamaAdapter,
- ProviderAdapterFactory,
+from .embedding_generator import EmbeddingGenerator
+from .embedding_optimizer import EmbeddingOptimizer
+from .image_embedder import ImageEmbedder
+from .methods import (
+ calculate_similarity,
+ embed_audio,
+ embed_image,
+ embed_multimodal,
+ embed_text,
+ generate_embeddings,
+ get_embedding_method,
+ list_available_methods,
+ optimize_embeddings,
+ pool_embeddings,
)
+from .multimodal_embedder import MultimodalEmbedder
from .pooling_strategies import (
- PoolingStrategy,
- MeanPooling,
- MaxPooling,
- CLSPooling,
AttentionPooling,
+ CLSPooling,
HierarchicalPooling,
+ MaxPooling,
+ MeanPooling,
+ PoolingStrategy,
PoolingStrategyFactory,
)
-from .registry import MethodRegistry, method_registry
-from .methods import (
- generate_embeddings,
- embed_text,
- embed_image,
- embed_audio,
- embed_multimodal,
- optimize_embeddings,
- calculate_similarity,
- pool_embeddings,
- get_embedding_method,
- list_available_methods,
+from .provider_adapters import (
+ BGEAdapter,
+ LlamaAdapter,
+ OpenAIAdapter,
+ ProviderAdapter,
+ ProviderAdapterFactory,
)
-from .config import EmbeddingsConfig, embeddings_config
+from .registry import MethodRegistry, method_registry
+from .text_embedder import TextEmbedder
__all__ = [
# Core Classes
@@ -187,92 +188,4 @@ __all__ = [
# Configuration
"EmbeddingsConfig",
"embeddings_config",
- # Convenience Functions
- "build",
]
-
-
-def build(
- data: Union[str, Path, List[Union[str, Path]]],
- data_type: Optional[str] = None,
- model: Optional[str] = None,
- batch_size: int = 32,
- **options
-) -> Dict[str, Any]:
- """
- Generate embeddings from data (module-level convenience function).
-
- This is a user-friendly wrapper around EmbeddingGenerator.generate_embeddings()
- that creates an EmbeddingGenerator instance and generates embeddings.
-
- Args:
- data: Input data - can be text string, file path, or list of texts/paths
- data_type: Data type - "text", "image", "audio" (auto-detected if None)
- model: Embedding model to use (default: None, uses default model)
- batch_size: Batch size for processing multiple items (default: 32)
- **options: Additional generation options
-
- Returns:
- Dictionary containing:
- - embeddings: Generated embeddings (numpy array or list of arrays)
- - metadata: Embedding metadata
- - statistics: Generation statistics
-
- Examples:
- >>> import semantica
- >>> result = semantica.embeddings.build(
- ... data=["text1", "text2", "text3"],
- ... data_type="text",
- ... model="sentence-transformers"
- ... )
- >>> print(f"Generated {len(result['embeddings'])} embeddings")
- """
- # Create EmbeddingGenerator instance
- config = {}
- if model:
- config["model"] = model
- config.update(options)
-
- generator = EmbeddingGenerator(config=config, **options)
-
- # Normalize data to list if single item
- is_single = not isinstance(data, list)
- if is_single:
- data = [data]
-
- # Generate embeddings
- if len(data) == 1:
- # Single item
- embeddings = generator.generate_embeddings(data[0], data_type=data_type, **options)
- if is_single:
- # Return single embedding array
- return {
- "embeddings": embeddings,
- "metadata": {
- "data_type": data_type or generator._detect_data_type(data[0]),
- "model": model or "default",
- "shape": embeddings.shape if isinstance(embeddings, np.ndarray) else None
- },
- "statistics": {
- "total_items": 1,
- "successful": 1,
- "failed": 0
- }
- }
- else:
- # Batch processing
- results = generator.process_batch(data, **options)
- return {
- "embeddings": results["embeddings"],
- "metadata": {
- "data_type": data_type or "auto-detected",
- "model": model or "default",
- "batch_size": batch_size
- },
- "statistics": {
- "total_items": results["total"],
- "successful": results["success_count"],
- "failed": results["failure_count"]
- },
- "failed_items": results.get("failed", [])
- }
diff --git a/semantica/ingest/__init__.py b/semantica/ingest/__init__.py
index 85d3c8d5..9f135c72 100644
--- a/semantica/ingest/__init__.py
+++ b/semantica/ingest/__init__.py
@@ -110,42 +110,61 @@ Example Usage:
>>> content = ingest_web("https://example.com", method="url")
"""
-from typing import Any, Dict, List, Optional, Union
from pathlib import Path
+from typing import Any, Dict, List, Optional, Union
-from .file_ingestor import FileIngestor, FileObject, FileTypeDetector, CloudStorageIngestor
-from .web_ingestor import WebIngestor, WebContent, RateLimiter, RobotsChecker, ContentExtractor, SitemapCrawler
-from .feed_ingestor import FeedIngestor, FeedItem, FeedData, FeedParser, FeedMonitor
-from .stream_ingestor import (
- StreamIngestor,
- StreamMessage,
- StreamProcessor,
- KafkaProcessor,
- RabbitMQProcessor,
- KinesisProcessor,
- PulsarProcessor,
- StreamMonitor,
+from .config import IngestConfig, ingest_config
+from .db_ingestor import DatabaseConnector, DataExporter, DBIngestor, TableData
+from .email_ingestor import AttachmentProcessor, EmailData, EmailIngestor
+from .email_ingestor import EmailParser as EmailIngestorParser
+from .feed_ingestor import FeedData, FeedIngestor, FeedItem, FeedMonitor, FeedParser
+from .file_ingestor import (
+ CloudStorageIngestor,
+ FileIngestor,
+ FileObject,
+ FileTypeDetector,
)
-from .repo_ingestor import RepoIngestor, CodeFile, CommitInfo, CodeExtractor, GitAnalyzer
-from .email_ingestor import EmailIngestor, EmailData, AttachmentProcessor, EmailParser as EmailIngestorParser
-from .db_ingestor import DBIngestor, TableData, DatabaseConnector, DataExporter
-from .mcp_ingestor import MCPIngestor, MCPData
from .mcp_client import MCPClient, MCPResource, MCPTool
-from .registry import MethodRegistry, method_registry
+from .mcp_ingestor import MCPData, MCPIngestor
from .methods import (
+ get_ingest_method,
ingest,
- ingest_file,
- ingest_web,
- ingest_feed,
- ingest_stream,
- ingest_repository,
- ingest_email,
ingest_database,
+ ingest_email,
+ ingest_feed,
+ ingest_file,
ingest_mcp,
- get_ingest_method,
+ ingest_repository,
+ ingest_stream,
+ ingest_web,
list_available_methods,
)
-from .config import IngestConfig, ingest_config
+from .registry import MethodRegistry, method_registry
+from .repo_ingestor import (
+ CodeExtractor,
+ CodeFile,
+ CommitInfo,
+ GitAnalyzer,
+ RepoIngestor,
+)
+from .stream_ingestor import (
+ KafkaProcessor,
+ KinesisProcessor,
+ PulsarProcessor,
+ RabbitMQProcessor,
+ StreamIngestor,
+ StreamMessage,
+ StreamMonitor,
+ StreamProcessor,
+)
+from .web_ingestor import (
+ ContentExtractor,
+ RateLimiter,
+ RobotsChecker,
+ SitemapCrawler,
+ WebContent,
+ WebIngestor,
+)
__all__ = [
# File ingestion
@@ -214,113 +233,4 @@ __all__ = [
# Configuration
"IngestConfig",
"ingest_config",
- # Legacy
- "build",
]
-
-
-def build(
- sources: Union[List[Union[str, Path]], str, Path],
- source_type: str = "file",
- recursive: bool = True,
- read_content: bool = True,
- **options
-) -> Dict[str, Any]:
- """
- Ingest data from sources (module-level convenience function).
-
- This is a user-friendly wrapper that automatically selects the appropriate
- ingestor based on source type and ingests the data.
-
- Args:
- sources: Data source(s) - can be file paths, URLs, directories, etc.
- source_type: Type of source - "file", "web", "feed", "stream", "repo", "email", "db" (default: "file")
- recursive: For directories, whether to ingest recursively (default: True)
- read_content: Whether to read file content (default: True)
- **options: Additional ingestion options
-
- Returns:
- Dictionary containing:
- - files: List of ingested file objects (for file ingestion)
- - content: Ingested content (for web/feed ingestion)
- - metadata: Ingestion metadata
- - statistics: Ingestion statistics
-
- Examples:
- >>> import semantica
- >>> result = semantica.ingest.build(
- ... sources=["doc1.pdf", "doc2.docx"],
- ... source_type="file",
- ... read_content=True
- ... )
- >>> print(f"Ingested {len(result['files'])} files")
- """
- # Normalize sources to list
- if isinstance(sources, (str, Path)):
- sources = [sources]
-
- results = {
- "files": [],
- "content": [],
- "metadata": {},
- "statistics": {}
- }
-
- if source_type == "file":
- # Use FileIngestor
- ingestor = FileIngestor(config=options.get("config", {}), **options)
-
- file_objects = []
- for source in sources:
- source_path = Path(source)
- if source_path.is_dir():
- # Ingest directory
- files = ingestor.ingest_directory(source_path, recursive=recursive, **options)
- file_objects.extend(files)
- elif source_path.is_file():
- # Ingest single file
- file_obj = ingestor.ingest_file(source_path, read_content=read_content, **options)
- file_objects.append(file_obj)
- else:
- # Try as file path string
- try:
- file_obj = ingestor.ingest_file(source, read_content=read_content, **options)
- file_objects.append(file_obj)
- except Exception as e:
- results["statistics"].setdefault("errors", []).append({
- "source": str(source),
- "error": str(e)
- })
-
- results["files"] = file_objects
- results["statistics"] = {
- "total_sources": len(sources),
- "ingested_files": len(file_objects),
- "errors": len(results["statistics"].get("errors", []))
- }
-
- elif source_type == "web":
- # Use WebIngestor
- from .web_ingestor import WebIngestor
- ingestor = WebIngestor(config=options.get("config", {}), **options)
-
- web_contents = []
- for source in sources:
- if isinstance(source, str) and (source.startswith("http://") or source.startswith("https://")):
- content = ingestor.ingest_url(source, **options)
- web_contents.append(content)
-
- results["content"] = web_contents
- results["statistics"] = {
- "total_urls": len(sources),
- "ingested_pages": len(web_contents)
- }
-
- else:
- # For other types, return placeholder
- results["statistics"] = {
- "message": f"Source type '{source_type}' ingestion not yet implemented in build() function",
- "suggestion": f"Use {source_type.capitalize()}Ingestor class directly"
- }
-
- return results
diff --git a/semantica/kg/__init__.py b/semantica/kg/__init__.py
index c0a8c324..f04622e5 100644
--- a/semantica/kg/__init__.py
+++ b/semantica/kg/__init__.py
@@ -140,34 +140,38 @@ License: MIT
from typing import Any, Dict, List, Optional, Union
-from .graph_builder import GraphBuilder
-from .entity_resolver import EntityResolver
-from .graph_analyzer import GraphAnalyzer
-from .temporal_query import TemporalGraphQuery, TemporalPatternDetector, TemporalVersionManager
-from .conflict_detector import ConflictDetector
-from .provenance_tracker import ProvenanceTracker
from .centrality_calculator import CentralityCalculator
from .community_detector import CommunityDetector
+from .config import KGConfig, kg_config
+from .conflict_detector import ConflictDetector
from .connectivity_analyzer import ConnectivityAnalyzer
from .deduplicator import Deduplicator
+from .entity_resolver import EntityResolver
+from .graph_analyzer import GraphAnalyzer
+from .graph_builder import GraphBuilder
from .graph_validator import GraphValidator
-from .seed_manager import SeedManager
-from .registry import MethodRegistry, method_registry
from .methods import (
- build_kg,
+ analyze_connectivity,
analyze_graph,
- resolve_entities,
- validate_graph,
- detect_conflicts,
+ build_kg,
calculate_centrality,
- detect_communities,
- analyze_connectivity,
deduplicate_graph,
- query_temporal,
+ detect_communities,
+ detect_conflicts,
get_kg_method,
list_available_methods,
+ query_temporal,
+ resolve_entities,
+ validate_graph,
+)
+from .provenance_tracker import ProvenanceTracker
+from .registry import MethodRegistry, method_registry
+from .seed_manager import SeedManager
+from .temporal_query import (
+ TemporalGraphQuery,
+ TemporalPatternDetector,
+ TemporalVersionManager,
)
-from .config import KGConfig, kg_config
__all__ = [
# Core Classes
@@ -203,73 +207,4 @@ __all__ = [
# Configuration
"KGConfig",
"kg_config",
- # Convenience Functions
- "build",
]
-
-
-def build(
- sources: Union[List[Any], Any],
- merge_entities: bool = True,
- entity_resolution_strategy: str = "fuzzy",
- resolve_conflicts: bool = True,
- enable_temporal: bool = False,
- temporal_granularity: str = "day",
- track_history: bool = False,
- version_snapshots: bool = False,
- entity_resolver: Optional[EntityResolver] = None,
- **options
-) -> Dict[str, Any]:
- """
- Build knowledge graph from sources (module-level convenience function).
-
- This is a user-friendly wrapper around GraphBuilder.build() that creates
- a GraphBuilder instance and builds the knowledge graph.
-
- Args:
- sources: List of sources (documents, entities, relationships, or dicts with entities/relationships)
- merge_entities: Whether to merge duplicate entities (default: True)
- entity_resolution_strategy: Strategy for entity resolution - "fuzzy", "exact", "semantic" (default: "fuzzy")
- resolve_conflicts: Whether to resolve conflicts (default: True)
- enable_temporal: Enable temporal knowledge graph features (default: False)
- temporal_granularity: Time granularity - "second", "minute", "hour", "day", etc. (default: "day")
- track_history: Track historical changes (default: False)
- version_snapshots: Create version snapshots (default: False)
- entity_resolver: Optional EntityResolver instance (default: None, creates one if needed)
- **options: Additional build options
-
- Returns:
- Dictionary containing:
- - entities: List of entities
- - relationships: List of relationships
- - metadata: Graph metadata including counts and timestamps
-
- Examples:
- >>> import semantica
- >>> result = semantica.kg.build(
- ... sources=[{"entities": [...], "relationships": [...]}],
- ... merge_entities=True,
- ... resolve_conflicts=True
- ... )
- >>> print(f"Built graph with {result['metadata']['num_entities']} entities")
- """
- # Normalize sources to list
- if not isinstance(sources, list):
- sources = [sources]
-
- # Create GraphBuilder instance
- graph_builder = GraphBuilder(
- merge_entities=merge_entities,
- entity_resolution_strategy=entity_resolution_strategy,
- resolve_conflicts=resolve_conflicts,
- enable_temporal=enable_temporal,
- temporal_granularity=temporal_granularity,
- track_history=track_history,
- version_snapshots=version_snapshots,
- **options
- )
-
- # Build knowledge graph
- graph = graph_builder.build(sources, entity_resolver=entity_resolver, **options)
-
- return graph
diff --git a/semantica/semantic_extract/__init__.py b/semantica/semantic_extract/__init__.py
index 1cca26ff..bff092f8 100644
--- a/semantica/semantic_extract/__init__.py
+++ b/semantica/semantic_extract/__init__.py
@@ -17,24 +17,29 @@ Key Features:
- Extraction validation and quality assessment
Main Classes:
- - NamedEntityRecognizer: Main NER coordinator
+ - NamedEntityRecognizer: Main NER coordinator (confidence_threshold, merge_overlapping)
- NERExtractor: Core NER implementation
- - RelationExtractor: Relationship extraction
- - EventDetector: Event detection and classification
+ - RelationExtractor: Relationship extraction (confidence_threshold, bidirectional)
+ - EventDetector: Event detection and classification (extract_participants, extract_time)
- CoreferenceResolver: Coreference resolution
- - TripleExtractor: RDF triple extraction
+ - TripleExtractor: RDF triple extraction (include_temporal, include_provenance)
- SemanticAnalyzer: Semantic analysis engine
- SemanticNetworkExtractor: Semantic network construction
- LLMEnhancer: LLM-based enhancement
- ExtractionValidator: Quality validation
Example Usage:
- >>> from semantica.semantic_extract import build
- >>> result = build("Apple Inc. was founded by Steve Jobs in 1976.")
- >>> print(f"Extracted {len(result['entities'])} entities")
>>> from semantica.semantic_extract import NamedEntityRecognizer
- >>> ner = NamedEntityRecognizer()
+ >>> ner = NamedEntityRecognizer(confidence_threshold=0.7)
>>> entities = ner.extract_entities("Steve Jobs founded Apple.")
+
+ >>> from semantica.semantic_extract import RelationExtractor
+ >>> 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)
Author: Semantica Contributors
License: MIT
@@ -42,86 +47,70 @@ License: MIT
from typing import Any, Dict, List, Optional, Union
-from .named_entity_recognizer import (
- NamedEntityRecognizer,
- EntityClassifier,
- EntityConfidenceScorer,
- CustomEntityDetector
-)
-from .ner_extractor import (
- NERExtractor,
- Entity
-)
-from .relation_extractor import (
- RelationExtractor,
- Relation
-)
-from .event_detector import (
- EventDetector,
- Event,
- EventClassifier,
- TemporalEventProcessor,
- EventRelationshipExtractor
-)
+from .config import Config, config
from .coreference_resolver import (
+ CoreferenceChain,
+ CoreferenceChainBuilder,
CoreferenceResolver,
+ EntityCoreferenceDetector,
Mention,
- CoreferenceChain,
PronounResolver,
- EntityCoreferenceDetector,
- CoreferenceChainBuilder
-)
-from .triple_extractor import (
- TripleExtractor,
- Triple,
- TripleValidator,
- RDFSerializer,
- TripleQualityChecker
)
-from .semantic_analyzer import (
- SemanticAnalyzer,
- SemanticRole,
- SemanticCluster,
- SimilarityAnalyzer,
- RoleLabeler,
- SemanticClusterer
-)
-from .semantic_network_extractor import (
- SemanticNetworkExtractor,
- SemanticNode,
- SemanticEdge,
- SemanticNetwork
-)
-from .llm_enhancer import (
- LLMEnhancer,
- LLMResponse
+from .event_detector import (
+ Event,
+ EventClassifier,
+ EventDetector,
+ EventRelationshipExtractor,
+ TemporalEventProcessor,
)
-from .extraction_validator import (
- ExtractionValidator,
- ValidationResult
+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 .named_entity_recognizer import (
+ CustomEntityDetector,
+ EntityClassifier,
+ EntityConfidenceScorer,
+ NamedEntityRecognizer,
)
+from .ner_extractor import Entity, NERExtractor
from .providers import (
+ AnthropicProvider,
BaseProvider,
- OpenAIProvider,
GeminiProvider,
GroqProvider,
- AnthropicProvider,
- OllamaProvider,
HuggingFaceLLMProvider,
HuggingFaceModelLoader,
- create_provider
+ OllamaProvider,
+ OpenAIProvider,
+ create_provider,
)
from .registry import (
- ProviderRegistry,
MethodRegistry,
+ ProviderRegistry,
+ method_registry,
provider_registry,
- method_registry
)
-from .config import Config, config
-from .methods import (
- get_entity_method,
- get_relation_method,
- get_triple_method
+from .relation_extractor import Relation, RelationExtractor
+from .semantic_analyzer import (
+ RoleLabeler,
+ SemanticAnalyzer,
+ SemanticCluster,
+ SemanticClusterer,
+ SemanticRole,
+ SimilarityAnalyzer,
+)
+from .semantic_network_extractor import (
+ SemanticEdge,
+ SemanticNetwork,
+ SemanticNetworkExtractor,
+ SemanticNode,
+)
+from .triple_extractor import (
+ RDFSerializer,
+ Triple,
+ TripleExtractor,
+ TripleQualityChecker,
+ TripleValidator,
)
__all__ = [
@@ -132,18 +121,15 @@ __all__ = [
"CustomEntityDetector",
"NERExtractor",
"Entity",
-
# Relation Extraction
"RelationExtractor",
"Relation",
-
# Event Detection
"EventDetector",
"Event",
"EventClassifier",
"TemporalEventProcessor",
"EventRelationshipExtractor",
-
# Coreference Resolution
"CoreferenceResolver",
"Mention",
@@ -151,14 +137,12 @@ __all__ = [
"PronounResolver",
"EntityCoreferenceDetector",
"CoreferenceChainBuilder",
-
# Triple Extraction
"TripleExtractor",
"Triple",
"TripleValidator",
"RDFSerializer",
"TripleQualityChecker",
-
# Semantic Analysis
"SemanticAnalyzer",
"SemanticRole",
@@ -166,21 +150,17 @@ __all__ = [
"SimilarityAnalyzer",
"RoleLabeler",
"SemanticClusterer",
-
# Semantic Network
"SemanticNetworkExtractor",
"SemanticNode",
"SemanticEdge",
"SemanticNetwork",
-
# LLM Enhancement
"LLMEnhancer",
"LLMResponse",
-
# Validation
"ExtractionValidator",
"ValidationResult",
-
# Providers
"BaseProvider",
"OpenAIProvider",
@@ -191,156 +171,16 @@ __all__ = [
"HuggingFaceLLMProvider",
"HuggingFaceModelLoader",
"create_provider",
-
# Registry
"ProviderRegistry",
"MethodRegistry",
"provider_registry",
"method_registry",
-
# Config
"Config",
"config",
-
# Methods
"get_entity_method",
"get_relation_method",
"get_triple_method",
-
- # Convenience
- "build",
]
-
-
-def build(
- text: Union[str, List[str]],
- extract_entities: bool = True,
- extract_relations: bool = True,
- extract_events: bool = False,
- extract_triples: bool = False,
- resolve_coreferences: bool = False,
- **options
-) -> Dict[str, Any]:
- """
- Extract semantic information from text (module-level convenience function).
-
- This is a user-friendly wrapper that performs comprehensive semantic extraction
- including entities, relations, events, and triples.
-
- Args:
- text: Input text or list of texts to process
- extract_entities: Whether to extract named entities (default: True)
- extract_relations: Whether to extract relationships (default: True)
- extract_events: Whether to extract events (default: False)
- extract_triples: Whether to extract RDF triples (default: False)
- resolve_coreferences: Whether to resolve coreferences (default: False)
- **options: Additional extraction options
-
- Returns:
- Dictionary containing:
- - entities: List of extracted entities
- - relations: List of extracted relationships
- - events: List of extracted events (if enabled)
- - triples: List of extracted triples (if enabled)
- - coreferences: Coreference resolution results (if enabled)
- - metadata: Extraction metadata
- - statistics: Extraction statistics
-
- Examples:
- >>> import semantica
- >>> result = semantica.semantic_extract.build(
- ... text="Apple Inc. was founded by Steve Jobs in 1976.",
- ... extract_entities=True,
- ... extract_relations=True
- ... )
- >>> print(f"Extracted {len(result['entities'])} entities")
- """
- # Normalize text to list
- is_single = isinstance(text, str)
- if is_single:
- texts = [text]
- else:
- texts = text
-
- results = {
- "entities": [],
- "relations": [],
- "events": [],
- "triples": [],
- "coreferences": [],
- "metadata": {},
- "statistics": {}
- }
-
- # Initialize extractors
- if extract_entities:
- ner = NamedEntityRecognizer(config=options.get("ner_config", {}), **options)
-
- if extract_relations:
- from .relation_extractor import RelationExtractor
- rel_extractor = RelationExtractor(**options.get("relation_config", {}), **options)
-
- if extract_events:
- from .event_detector import EventDetector
- event_detector = EventDetector(**options.get("event_config", {}), **options)
-
- if extract_triples:
- from .triple_extractor import TripleExtractor
- triple_extractor = TripleExtractor(**options.get("triple_config", {}), **options)
-
- if resolve_coreferences:
- from .coreference_resolver import CoreferenceResolver
- coref_resolver = CoreferenceResolver(**options.get("coref_config", {}), **options)
-
- # Process texts
- all_entities = []
- all_relations = []
- all_events = []
- all_triples = []
-
- for txt in texts:
- if extract_entities:
- entities = ner.extract_entities(txt, **options)
- all_entities.extend(entities)
-
- if extract_relations:
- # Relations typically need entities, so extract if not already done
- if not extract_entities:
- entities = ner.extract_entities(txt, **options) if 'ner' in locals() else []
- relations = rel_extractor.extract_relations(txt, entities=entities if extract_entities else [], **options)
- all_relations.extend(relations)
-
- if extract_events:
- events = event_detector.detect_events(txt, **options)
- all_events.extend(events)
-
- if extract_triples:
- triples = triple_extractor.extract_triples(txt, **options)
- all_triples.extend(triples)
-
- if resolve_coreferences:
- corefs = coref_resolver.resolve(txt, **options)
- results["coreferences"].append(corefs)
-
- results["entities"] = all_entities
- results["relations"] = all_relations
- results["events"] = all_events
- results["triples"] = all_triples
-
- results["statistics"] = {
- "texts_processed": len(texts),
- "entities_extracted": len(all_entities),
- "relations_extracted": len(all_relations),
- "events_extracted": len(all_events),
- "triples_extracted": len(all_triples)
- }
-
- results["metadata"] = {
- "extract_entities": extract_entities,
- "extract_relations": extract_relations,
- "extract_events": extract_events,
- "extract_triples": extract_triples,
- "resolve_coreferences": resolve_coreferences
- }
-
- return results
diff --git a/semantica/semantic_extract/coreference_resolver.py b/semantica/semantic_extract/coreference_resolver.py
index 477cfd28..b49e660b 100644
--- a/semantica/semantic_extract/coreference_resolver.py
+++ b/semantica/semantic_extract/coreference_resolver.py
@@ -57,8 +57,8 @@ Author: Semantica Contributors
License: MIT
"""
-from dataclasses import dataclass, field
import re
+from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Tuple, Union
from ..utils.exceptions import ProcessingError
@@ -70,7 +70,7 @@ from .ner_extractor import Entity
@dataclass
class Mention:
"""Mention representation."""
-
+
text: str
start_char: int
end_char: int
@@ -82,7 +82,7 @@ class Mention:
@dataclass
class CoreferenceChain:
"""Coreference chain representation."""
-
+
mentions: List[Mention]
representative: Mention
entity_type: Optional[str] = None
@@ -90,11 +90,11 @@ class CoreferenceChain:
class CoreferenceResolver:
"""Coreference resolution handler."""
-
+
def __init__(self, method: Union[str, List[str]] = None, config=None, **kwargs):
"""
Initialize coreference resolver.
-
+
Args:
method: Extraction method(s) for underlying NER extractors.
Can be passed to ner_method in config.
@@ -107,61 +107,93 @@ class CoreferenceResolver:
self.config = config or {}
self.config.update(kwargs)
self.progress_tracker = get_progress_tracker()
-
+
# Store method for passing to extractors if needed
if method is not None:
self.config["ner_method"] = method
-
+
self.pronoun_resolver = PronounResolver(**self.config.get("pronoun", {}))
- self.entity_detector = EntityCoreferenceDetector(**self.config.get("entity", {}))
+ self.entity_detector = EntityCoreferenceDetector(
+ **self.config.get("entity", {})
+ )
self.chain_builder = CoreferenceChainBuilder(**self.config.get("chain", {}))
-
+
def resolve_coreferences(self, text: str, **options) -> List[CoreferenceChain]:
"""
Resolve coreferences in text.
-
+
Args:
text: Input text
**options: Resolution options
-
+
Returns:
list: List of coreference chains
"""
tracking_id = self.progress_tracker.start_tracking(
module="semantic_extract",
submodule="CoreferenceResolver",
- message="Resolving coreferences in text"
+ message="Resolving coreferences in text",
)
-
+
try:
# Extract mentions
- self.progress_tracker.update_tracking(tracking_id, message="Extracting mentions...")
+ self.progress_tracker.update_tracking(
+ tracking_id, message="Extracting mentions..."
+ )
mentions = self._extract_mentions(text)
-
+
# Resolve pronouns
- self.progress_tracker.update_tracking(tracking_id, message="Resolving pronouns...")
- pronoun_resolutions = self.pronoun_resolver.resolve_pronouns(text, mentions, **options)
-
+ self.progress_tracker.update_tracking(
+ tracking_id, message="Resolving pronouns..."
+ )
+ pronoun_resolutions = self.pronoun_resolver.resolve_pronouns(
+ text, mentions, **options
+ )
+
# Detect entity coreferences
- self.progress_tracker.update_tracking(tracking_id, message="Detecting entity coreferences...")
- entity_corefs = self.entity_detector.detect_entity_coreferences(text, mentions, **options)
-
+ self.progress_tracker.update_tracking(
+ tracking_id, message="Detecting entity coreferences..."
+ )
+ entity_corefs = self.entity_detector.detect_entity_coreferences(
+ text, mentions, **options
+ )
+
# Build chains
- self.progress_tracker.update_tracking(tracking_id, message="Building coreference chains...")
+ self.progress_tracker.update_tracking(
+ tracking_id, message="Building coreference chains..."
+ )
chains = self.chain_builder.build_coreference_chains(mentions, **options)
-
- self.progress_tracker.stop_tracking(tracking_id, status="completed",
- message=f"Resolved {len(chains)} coreference chains")
+
+ self.progress_tracker.stop_tracking(
+ tracking_id,
+ status="completed",
+ message=f"Resolved {len(chains)} coreference chains",
+ )
return chains
-
+
except Exception as e:
- self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))
+ self.progress_tracker.stop_tracking(
+ tracking_id, status="failed", message=str(e)
+ )
raise
-
+
+ def resolve(self, text: str, **options) -> List[CoreferenceChain]:
+ """
+ Resolve coreferences in text (alias for resolve_coreferences).
+
+ Args:
+ text: Input text
+ **options: Resolution options
+
+ Returns:
+ list: List of coreference chains
+ """
+ return self.resolve_coreferences(text, **options)
+
def _extract_mentions(self, text: str) -> List[Mention]:
"""Extract all mentions from text."""
mentions = []
-
+
# Extract pronouns
pronoun_patterns = {
"he": r"\bhe\b",
@@ -170,57 +202,63 @@ class CoreferenceResolver:
"they": r"\bthey\b",
"his": r"\bhis\b",
"her": r"\bher\b",
- "their": r"\btheir\b"
+ "their": r"\btheir\b",
}
-
+
for pronoun, pattern in pronoun_patterns.items():
for match in re.finditer(pattern, text, re.IGNORECASE):
- mentions.append(Mention(
- text=match.group(0),
- start_char=match.start(),
- end_char=match.end(),
- mention_type="pronoun",
- metadata={"pronoun": pronoun}
- ))
-
+ mentions.append(
+ Mention(
+ text=match.group(0),
+ start_char=match.start(),
+ end_char=match.end(),
+ mention_type="pronoun",
+ metadata={"pronoun": pronoun},
+ )
+ )
+
return mentions
-
- def build_coreference_chains(self, mentions: List[Mention], **options) -> List[CoreferenceChain]:
+
+ def build_coreference_chains(
+ self, mentions: List[Mention], **options
+ ) -> List[CoreferenceChain]:
"""
Build coreference chains from mentions.
-
+
Args:
mentions: List of mentions
**options: Chain building options
-
+
Returns:
list: List of coreference chains
"""
return self.chain_builder.build_coreference_chains(mentions, **options)
-
+
def resolve_pronouns(self, text: str, **options) -> List[Tuple[str, str]]:
"""
Resolve pronoun references in text.
-
+
Args:
text: Input text
**options: Resolution options
-
+
Returns:
list: List of (pronoun, antecedent) tuples
"""
mentions = self._extract_mentions(text)
return self.pronoun_resolver.resolve_pronouns(text, mentions, **options)
-
- def detect_entity_coreferences(self, text: str, entities: List[Entity], **options) -> List[CoreferenceChain]:
+
+ def detect_entity_coreferences(
+ self, text: str, entities: List[Entity], **options
+ ) -> List[CoreferenceChain]:
"""
Detect entity coreferences in text.
-
+
Args:
text: Input text
entities: List of entities
**options: Detection options
-
+
Returns:
list: List of coreference chains
"""
@@ -231,88 +269,90 @@ class CoreferenceResolver:
start_char=e.start_char,
end_char=e.end_char,
mention_type="entity",
- metadata={"entity_label": e.label}
+ metadata={"entity_label": e.label},
)
for e in entities
]
-
- return self.entity_detector.detect_entity_coreferences(text, mentions, **options)
+
+ return self.entity_detector.detect_entity_coreferences(
+ text, mentions, **options
+ )
class PronounResolver:
"""Pronoun resolution engine."""
-
+
def __init__(self, **config):
"""Initialize pronoun resolver."""
self.logger = get_logger("pronoun_resolver")
self.config = config
-
+
def resolve_pronouns(
- self,
- text: str,
- mentions: List[Mention],
- **options
+ self, text: str, mentions: List[Mention], **options
) -> List[Tuple[str, str]]:
"""
Resolve pronoun references in text.
-
+
Args:
text: Input text
mentions: List of mentions
**options: Resolution options
-
+
Returns:
list: List of (pronoun, antecedent) tuples
"""
resolutions = []
-
+
# Get pronouns and entities
pronouns = [m for m in mentions if m.mention_type == "pronoun"]
- entities = [m for m in mentions if m.mention_type == "entity" or m.mention_type == "nominal"]
-
+ entities = [
+ m
+ for m in mentions
+ if m.mention_type == "entity" or m.mention_type == "nominal"
+ ]
+
# Simple resolution: find closest preceding entity
for pronoun in pronouns:
# Find preceding entities
preceding = [e for e in entities if e.end_char < pronoun.start_char]
-
+
if preceding:
# Take closest
antecedent = max(preceding, key=lambda e: e.end_char)
resolutions.append((pronoun.text, antecedent.text))
-
+
return resolutions
class EntityCoreferenceDetector:
"""Entity coreference detection."""
-
+
def __init__(self, **config):
"""Initialize entity coreference detector."""
self.logger = get_logger("entity_coreference_detector")
self.config = config
-
+
def detect_entity_coreferences(
- self,
- text: str,
- mentions: List[Mention],
- **options
+ self, text: str, mentions: List[Mention], **options
) -> List[CoreferenceChain]:
"""
Detect entity coreferences in text.
-
+
Args:
text: Input text
mentions: List of mentions
**options: Detection options
-
+
Returns:
list: List of coreference chains
"""
chains = []
-
+
# Group mentions by text similarity
- entity_mentions = [m for m in mentions if m.mention_type in ["entity", "nominal"]]
-
+ entity_mentions = [
+ m for m in mentions if m.mention_type in ["entity", "nominal"]
+ ]
+
# Simple grouping by exact text match
text_groups = {}
for mention in entity_mentions:
@@ -320,87 +360,93 @@ class EntityCoreferenceDetector:
if key not in text_groups:
text_groups[key] = []
text_groups[key].append(mention)
-
+
# Create chains from groups
for key, group_mentions in text_groups.items():
if len(group_mentions) > 1:
# Use first mention as representative
representative = group_mentions[0]
chain = CoreferenceChain(
- mentions=group_mentions,
- representative=representative
+ mentions=group_mentions, representative=representative
)
chains.append(chain)
-
+
return chains
class CoreferenceChainBuilder:
"""Coreference chain construction."""
-
+
def __init__(self, **config):
"""Initialize coreference chain builder."""
self.logger = get_logger("coreference_chain_builder")
self.config = config
-
- def build_coreference_chains(self, mentions: List[Mention], **options) -> List[CoreferenceChain]:
+
+ def build_coreference_chains(
+ self, mentions: List[Mention], **options
+ ) -> List[CoreferenceChain]:
"""
Build coreference chains from mentions.
-
+
Args:
mentions: List of mentions
**options: Chain building options
-
+
Returns:
list: List of coreference chains
"""
chains = []
-
+
# Simple implementation: group by text similarity
processed = set()
-
+
for mention in mentions:
if mention.text.lower() in processed:
continue
-
+
# Find similar mentions
similar = [
- m for m in mentions
- if m.text.lower() == mention.text.lower() or
- self._similar_mentions(mention.text, m.text)
+ m
+ for m in mentions
+ if m.text.lower() == mention.text.lower()
+ or self._similar_mentions(mention.text, m.text)
]
-
+
if len(similar) > 1:
processed.add(mention.text.lower())
-
+
# Representative is first (leftmost) mention
representative = min(similar, key=lambda m: m.start_char)
-
+
chain = CoreferenceChain(
mentions=similar,
representative=representative,
- entity_type=similar[0].metadata.get("entity_label")
+ entity_type=similar[0].metadata.get("entity_label"),
)
chains.append(chain)
-
+
return chains
-
+
def _similar_mentions(self, text1: str, text2: str) -> bool:
"""Check if two mentions are similar."""
t1_lower = text1.lower()
t2_lower = text2.lower()
-
+
# Exact match
if t1_lower == t2_lower:
return True
-
+
# One contains the other
if t1_lower in t2_lower or t2_lower in t1_lower:
return True
-
+
# Word overlap
words1 = set(t1_lower.split())
words2 = set(t2_lower.split())
- overlap = len(words1 & words2) / max(len(words1), len(words2)) if words1 or words2 else 0
-
+ overlap = (
+ len(words1 & words2) / max(len(words1), len(words2))
+ if words1 or words2
+ else 0
+ )
+
return overlap > 0.7
diff --git a/semantica/semantic_extract/event_detector.py b/semantica/semantic_extract/event_detector.py
index e1736e04..3a547464 100644
--- a/semantica/semantic_extract/event_detector.py
+++ b/semantica/semantic_extract/event_detector.py
@@ -70,7 +70,7 @@ from .ner_extractor import Entity
@dataclass
class Event:
"""Event representation."""
-
+
text: str
event_type: str
start_char: int
@@ -84,12 +84,25 @@ class Event:
class EventDetector:
"""Event detection and extraction handler."""
-
- def __init__(self, method: Union[str, List[str]] = None, config=None, **kwargs):
+
+ def __init__(
+ self,
+ event_types: Optional[List[str]] = None,
+ extract_participants: bool = True,
+ extract_location: bool = True,
+ extract_time: bool = True,
+ method: Union[str, List[str]] = None,
+ config=None,
+ **kwargs
+ ):
"""
Initialize event detector.
-
+
Args:
+ event_types: Specific event types to detect (e.g., ["launch", "acquisition"])
+ extract_participants: Whether to extract event participants
+ extract_location: Whether to extract event locations
+ extract_time: Whether to extract temporal information
method: Extraction method(s) for underlying NER/relation extractors.
Can be passed to ner_method and relation_method in config.
config: Legacy config dict (deprecated, use kwargs)
@@ -102,160 +115,199 @@ class EventDetector:
self.config = config or {}
self.config.update(kwargs)
self.progress_tracker = get_progress_tracker()
-
+
+ # Store parameters
+ self.event_types_filter = event_types
+ self.extract_participants = extract_participants
+ self.extract_location = extract_location
+ self.extract_time = extract_time
+
# Store method for passing to extractors if needed
if method is not None:
self.config["ner_method"] = method
self.config["relation_method"] = method
-
+
self.event_classifier = EventClassifier(**self.config.get("classifier", {}))
- self.temporal_processor = TemporalEventProcessor(**self.config.get("temporal", {}))
- self.relationship_extractor = EventRelationshipExtractor(**self.config.get("relationship", {}))
-
+ self.temporal_processor = TemporalEventProcessor(
+ **self.config.get("temporal", {})
+ )
+ self.relationship_extractor = EventRelationshipExtractor(
+ **self.config.get("relationship", {})
+ )
+
# Event patterns
self.event_patterns = {
"founded": r"founded|created|established",
"acquired": r"acquired|bought|purchased",
"launched": r"launched|released|introduced",
"announced": r"announced|declared|stated",
- "meeting": r"met|meeting|conference|summit"
+ "meeting": r"met|meeting|conference|summit",
}
-
+
def detect_events(self, text: str, **options) -> List[Event]:
"""
Detect events in text content.
-
+
Args:
text: Input text
**options: Detection options
-
+
Returns:
list: List of detected events
"""
tracking_id = self.progress_tracker.start_tracking(
module="semantic_extract",
submodule="EventDetector",
- message="Detecting events in text"
+ message="Detecting events in text",
)
-
+
try:
events = []
-
+
+ # Determine which event types to detect
+ event_patterns_to_use = self.event_patterns
+ if self.event_types_filter:
+ event_patterns_to_use = {
+ k: v for k, v in self.event_patterns.items()
+ if k in self.event_types_filter
+ }
+
# Detect events using patterns
- self.progress_tracker.update_tracking(tracking_id, message="Scanning text for event patterns...")
- for event_type, pattern in self.event_patterns.items():
+ self.progress_tracker.update_tracking(
+ tracking_id, message="Scanning text for event patterns..."
+ )
+ for event_type, pattern in event_patterns_to_use.items():
for match in re.finditer(pattern, text, re.IGNORECASE):
# Extract surrounding context
start = max(0, match.start() - 50)
end = min(len(text), match.end() + 50)
context = text[start:end]
-
- # Extract participants (simplified)
- participants = self._extract_participants(context)
-
+
+ # Extract participants if enabled
+ participants = []
+ if self.extract_participants:
+ participants = self._extract_participants(context)
+
+ # Extract location if enabled
+ location = None
+ if self.extract_location:
+ location = self._extract_location(context)
+
+ # Extract time if enabled
+ time_info = None
+ if self.extract_time:
+ time_info = self._extract_time(context)
+
event = Event(
text=match.group(0),
event_type=event_type,
start_char=match.start(),
end_char=match.end(),
participants=participants,
+ location=location,
+ time=time_info,
confidence=0.7,
- metadata={"context": context}
+ metadata={"context": context},
)
events.append(event)
-
- self.progress_tracker.stop_tracking(tracking_id, status="completed",
- message=f"Detected {len(events)} events")
+
+ self.progress_tracker.stop_tracking(
+ tracking_id,
+ status="completed",
+ message=f"Detected {len(events)} events",
+ )
return events
-
+
except Exception as e:
- self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))
+ self.progress_tracker.stop_tracking(
+ tracking_id, status="failed", message=str(e)
+ )
raise
-
+
def _extract_participants(self, context: str) -> List[str]:
"""Extract event participants from context."""
# Simple extraction - look for capitalized words
participants = []
words = context.split()
-
+
# Look for patterns like "X and Y", "X, Y, and Z"
capitalized = [w for w in words if w[0].isupper() and len(w) > 2]
participants.extend(capitalized[:3]) # Limit to first few
-
+
return participants
-
+
def classify_events(self, events: List[Event], **context) -> Dict[str, List[Event]]:
"""
Classify events by type and category.
-
+
Args:
events: List of events
**context: Context information
-
+
Returns:
dict: Events grouped by type
"""
return self.event_classifier.classify_events(events, **context)
-
+
def extract_event_properties(self, events: List[Event], **options) -> List[Event]:
"""
Extract properties and attributes from events.
-
+
Args:
events: List of events
**options: Extraction options
-
+
Returns:
list: Events with extracted properties
"""
for event in events:
# Extract location
event.location = self._extract_location(event.metadata.get("context", ""))
-
+
# Extract time
event.time = self._extract_time(event.metadata.get("context", ""))
-
+
return events
-
+
def _extract_location(self, context: str) -> Optional[str]:
"""Extract location from context."""
# Simple pattern matching for locations
location_patterns = [
r"in\s+([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)",
- r"at\s+([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)"
+ r"at\s+([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)",
]
-
+
for pattern in location_patterns:
match = re.search(pattern, context)
if match:
return match.group(1)
-
+
return None
-
+
def _extract_time(self, context: str) -> Optional[str]:
"""Extract time from context."""
# Simple pattern matching for dates/times
time_patterns = [
r"on\s+([A-Z][a-z]+\s+\d{1,2},?\s+\d{4})",
r"in\s+(\d{4})",
- r"(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})"
+ r"(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})",
]
-
+
for pattern in time_patterns:
match = re.search(pattern, context)
if match:
return match.group(1)
-
+
return None
-
+
def process_temporal_events(self, events: List[Event], **options) -> List[Event]:
"""
Process temporal information in events.
-
+
Args:
events: List of events
**options: Processing options
-
+
Returns:
list: Events with temporal information
"""
@@ -264,20 +316,20 @@ class EventDetector:
class EventClassifier:
"""Event type classification."""
-
+
def __init__(self, **config):
"""Initialize event classifier."""
self.logger = get_logger("event_classifier")
self.config = config
-
+
def classify_events(self, events: List[Event], **context) -> Dict[str, List[Event]]:
"""
Classify events by type.
-
+
Args:
events: List of events
**context: Context information
-
+
Returns:
dict: Events grouped by type
"""
@@ -286,26 +338,26 @@ class EventClassifier:
if event.event_type not in classified:
classified[event.event_type] = []
classified[event.event_type].append(event)
-
+
return classified
class TemporalEventProcessor:
"""Temporal event handling."""
-
+
def __init__(self, **config):
"""Initialize temporal event processor."""
self.logger = get_logger("temporal_event_processor")
self.config = config
-
+
def process_temporal(self, events: List[Event], **options) -> List[Event]:
"""
Process temporal information in events.
-
+
Args:
events: List of events
**options: Processing options
-
+
Returns:
list: Events with processed temporal info
"""
@@ -315,74 +367,77 @@ class TemporalEventProcessor:
# Try to extract from context
context = event.metadata.get("context", "")
event.time = self._extract_temporal(context)
-
+
# Sort events by time if available
if options.get("sort_by_time", False):
events.sort(key=lambda e: self._parse_time(e.time) if e.time else 0)
-
+
return events
-
+
def _extract_temporal(self, context: str) -> Optional[str]:
"""Extract temporal expression from context."""
# Simple temporal extraction
- patterns = [
- r"(\d{4})",
- r"([A-Z][a-z]+\s+\d{1,2},?\s+\d{4})"
- ]
-
+ patterns = [r"(\d{4})", r"([A-Z][a-z]+\s+\d{1,2},?\s+\d{4})"]
+
for pattern in patterns:
match = re.search(pattern, context)
if match:
return match.group(1)
-
+
return None
-
+
def _parse_time(self, time_str: Optional[str]) -> int:
"""Parse time string to integer for sorting."""
if not time_str:
return 0
-
+
# Extract year if available
year_match = re.search(r"(\d{4})", time_str)
if year_match:
return int(year_match.group(1))
-
+
return 0
class EventRelationshipExtractor:
"""Event relationship extraction."""
-
+
def __init__(self, **config):
"""Initialize event relationship extractor."""
self.logger = get_logger("event_relationship_extractor")
self.config = config
-
- def extract_relationships(self, events: List[Event], **options) -> List[Dict[str, Any]]:
+
+ def extract_relationships(
+ self, events: List[Event], **options
+ ) -> List[Dict[str, Any]]:
"""
Extract relationships between events.
-
+
Args:
events: List of events
**options: Extraction options
-
+
Returns:
list: List of event relationships
"""
relationships = []
-
+
# Find related events (same participants, same location, sequential time)
for i, event1 in enumerate(events):
- for event2 in events[i+1:]:
+ for event2 in events[i + 1 :]:
# Check for shared participants
- shared_participants = set(event1.participants) & set(event2.participants)
+ shared_participants = set(event1.participants) & set(
+ event2.participants
+ )
if shared_participants:
- relationships.append({
- "event1": event1.event_type,
- "event2": event2.event_type,
- "relationship": "related",
- "reason": "shared_participants",
- "participants": list(shared_participants)
- })
-
+ relationships.append(
+ {
+ "event1": event1.event_type,
+ "event2": event2.event_type,
+ "relationship": "related",
+ "reason": "shared_participants",
+ "participants": list(shared_participants),
+ }
+ )
+
return relationships
diff --git a/semantica/semantic_extract/named_entity_recognizer.py b/semantica/semantic_extract/named_entity_recognizer.py
index 1c15930c..084c22ad 100644
--- a/semantica/semantic_extract/named_entity_recognizer.py
+++ b/semantica/semantic_extract/named_entity_recognizer.py
@@ -57,7 +57,7 @@ from .ner_extractor import Entity, NERExtractor
class NamedEntityRecognizer:
"""
Named entity recognition handler.
-
+
• Extracts named entities from text
• Classifies entities by type and category
• Provides confidence scores for entities
@@ -65,89 +65,119 @@ class NamedEntityRecognizer:
• Handles multiple languages and domains
• Processes batch text collections
"""
-
- def __init__(self, method=None, config=None, **kwargs):
+
+ def __init__(
+ self,
+ methods: Optional[List[str]] = None,
+ confidence_threshold: float = 0.5,
+ merge_overlapping: bool = True,
+ include_standard_types: bool = True,
+ method=None,
+ config=None,
+ **kwargs
+ ):
"""
Initialize named entity recognizer.
-
+
Args:
- method: Extraction method(s) - passed to NERExtractor
+ methods: Extraction methods to use (e.g., ["spacy", "rule-based"])
+ confidence_threshold: Minimum confidence score (0.0-1.0)
+ merge_overlapping: Whether to merge overlapping entities
+ include_standard_types: Include standard types (Person, Org, Location)
+ method: Extraction method(s) - passed to NERExtractor (legacy)
config: Legacy config dict (deprecated, use kwargs)
- **kwargs: Configuration options passed to NERExtractor
+ **kwargs: Additional configuration options passed to NERExtractor
"""
self.logger = get_logger("named_entity_recognizer")
self.config = config or {}
self.config.update(kwargs)
self.progress_tracker = get_progress_tracker()
-
+
+ # Store parameters
+ self.methods = methods or ["spacy"]
+ self.confidence_threshold = confidence_threshold
+ self.merge_overlapping = merge_overlapping
+ self.include_standard_types = include_standard_types
+
# Use NERExtractor for actual extraction
ner_config = self.config.get("ner", {})
+ ner_config["confidence_threshold"] = confidence_threshold
+ ner_config["merge_overlapping"] = merge_overlapping
if method is not None:
ner_config["method"] = method
+ elif methods:
+ ner_config["method"] = methods[0] if len(methods) == 1 else methods
self.ner_extractor = NERExtractor(**ner_config, **self.config)
self.entity_classifier = EntityClassifier(**self.config.get("classifier", {}))
self.confidence_scorer = EntityConfidenceScorer(**self.config.get("scorer", {}))
-
+
def extract_entities(self, text: str, **options) -> List[Entity]:
"""
Extract named entities from text.
-
+
Args:
text: Input text
**options: Extraction options
-
+
Returns:
list: List of extracted entities
"""
tracking_id = self.progress_tracker.start_tracking(
module="semantic_extract",
submodule="NamedEntityRecognizer",
- message="Extracting named entities"
+ message="Extracting named entities",
)
-
+
try:
entities = self.ner_extractor.extract_entities(text, **options)
- self.progress_tracker.stop_tracking(tracking_id, status="completed",
- message=f"Extracted {len(entities)} entities")
+ self.progress_tracker.stop_tracking(
+ tracking_id,
+ status="completed",
+ message=f"Extracted {len(entities)} entities",
+ )
return entities
except Exception as e:
- self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))
+ self.progress_tracker.stop_tracking(
+ tracking_id, status="failed", message=str(e)
+ )
raise
-
- def classify_entities(self, entities: List[Entity], **context) -> Dict[str, List[Entity]]:
+
+ def classify_entities(
+ self, entities: List[Entity], **context
+ ) -> Dict[str, List[Entity]]:
"""
Classify entities by type and category.
-
+
Args:
entities: List of entities
**context: Context information
-
+
Returns:
dict: Entities grouped by type
"""
return self.entity_classifier.classify_entities(entities, **context)
-
+
def score_confidence(self, entities: List[Entity], **options) -> List[Entity]:
"""
Calculate confidence scores for entities.
-
+
Args:
entities: List of entities
**options: Scoring options
-
+
Returns:
list: Entities with confidence scores
"""
return self.confidence_scorer.score_entities(entities, **options)
-
+
def process_batch(self, texts: List[str], **options) -> List[List[Entity]]:
"""
Process multiple texts for entity extraction.
-
+
Args:
texts: List of input texts
**options: Processing options
-
+
Returns:
list: List of entity lists for each text
"""
@@ -156,12 +186,12 @@ class NamedEntityRecognizer:
class EntityClassifier:
"""Entity classification engine."""
-
+
def __init__(self, **config):
"""Initialize entity classifier."""
self.logger = get_logger("entity_classifier")
self.config = config
-
+
# Entity type mappings
self.type_hierarchy = {
"PERSON": ["PERSON", "PER"],
@@ -169,63 +199,67 @@ class EntityClassifier:
"GPE": ["GPE", "LOCATION", "LOC"],
"DATE": ["DATE", "TIME"],
"MONEY": ["MONEY", "CURRENCY"],
- "PERCENT": ["PERCENT", "PERCENTAGE"]
+ "PERCENT": ["PERCENT", "PERCENTAGE"],
}
-
+
def classify_entity_type(self, entity: Entity, **context) -> str:
"""
Classify entity by type.
-
+
Args:
entity: Entity to classify
**context: Context information
-
+
Returns:
str: Entity type
"""
# Normalize entity type
label = entity.label.upper()
-
+
# Check type hierarchy
for canonical_type, variants in self.type_hierarchy.items():
if label in variants:
return canonical_type
-
+
return label
-
- def disambiguate_entity(self, entity: Entity, candidates: List[Entity], **context) -> Optional[Entity]:
+
+ def disambiguate_entity(
+ self, entity: Entity, candidates: List[Entity], **context
+ ) -> Optional[Entity]:
"""
Disambiguate entity among candidates.
-
+
Args:
entity: Entity to disambiguate
candidates: Candidate entities
**context: Context information
-
+
Returns:
Entity: Best matching entity or None
"""
if not candidates:
return None
-
+
# Simple disambiguation by type match
entity_type = entity.label
matching = [c for c in candidates if c.label == entity_type]
-
+
if matching:
# Return first match with highest confidence
return max(matching, key=lambda e: e.confidence)
-
+
return candidates[0] if candidates else None
-
- def classify_entities(self, entities: List[Entity], **context) -> Dict[str, List[Entity]]:
+
+ def classify_entities(
+ self, entities: List[Entity], **context
+ ) -> Dict[str, List[Entity]]:
"""
Classify entities by type.
-
+
Args:
entities: List of entities
**context: Context information
-
+
Returns:
dict: Entities grouped by type
"""
@@ -235,104 +269,107 @@ class EntityClassifier:
if entity_type not in classified:
classified[entity_type] = []
classified[entity_type].append(entity)
-
+
return classified
class EntityConfidenceScorer:
"""Confidence scoring system."""
-
+
def __init__(self, **config):
"""Initialize confidence scorer."""
self.logger = get_logger("entity_confidence_scorer")
self.config = config
-
+
def score_entities(self, entities: List[Entity], **options) -> List[Entity]:
"""
Calculate confidence scores for entities.
-
+
Args:
entities: List of entities
**options: Scoring options
-
+
Returns:
list: Entities with updated confidence scores
"""
for entity in entities:
if entity.confidence == 1.0: # Only recalculate if needed
entity.confidence = self._calculate_confidence(entity, **options)
-
+
return entities
-
+
def _calculate_confidence(self, entity: Entity, **options) -> float:
"""
Calculate confidence score for entity.
-
+
Args:
entity: Entity to score
**options: Scoring options
-
+
Returns:
float: Confidence score (0-1)
"""
score = 1.0
-
+
# Length-based scoring
text_length = len(entity.text)
if text_length < 2:
score *= 0.7
elif text_length > 50:
score *= 0.9
-
+
# Capitalization check (for PERSON, ORG)
if entity.label in ["PERSON", "ORG", "GPE"]:
if not entity.text[0].isupper():
score *= 0.8
-
+
# Type-specific scoring
if entity.label == "DATE":
# Check if looks like date
if any(char.isdigit() for char in entity.text):
score *= 1.1 # Boost for date-like patterns
-
+
return min(1.0, max(0.0, score))
class CustomEntityDetector:
"""Custom entity detection."""
-
+
def __init__(self, **config):
"""Initialize custom entity detector."""
self.logger = get_logger("custom_entity_detector")
self.config = config
-
+
self.custom_patterns = config.get("patterns", {})
-
+
def detect_custom_entities(self, text: str, entity_type: str) -> List[Entity]:
"""
Detect custom entities using patterns.
-
+
Args:
text: Input text
entity_type: Custom entity type
-
+
Returns:
list: List of detected entities
"""
entities = []
-
+
if entity_type in self.custom_patterns:
import re
+
pattern = self.custom_patterns[entity_type]
-
+
for match in re.finditer(pattern, text):
- entities.append(Entity(
- text=match.group(0),
- label=entity_type,
- start_char=match.start(),
- end_char=match.end(),
- confidence=0.8,
- metadata={"extraction_method": "custom_pattern"}
- ))
-
+ entities.append(
+ Entity(
+ text=match.group(0),
+ label=entity_type,
+ start_char=match.start(),
+ end_char=match.end(),
+ confidence=0.8,
+ metadata={"extraction_method": "custom_pattern"},
+ )
+ )
+
return entities
diff --git a/semantica/semantic_extract/relation_extractor.py b/semantica/semantic_extract/relation_extractor.py
index e657eaee..f4484164 100644
--- a/semantica/semantic_extract/relation_extractor.py
+++ b/semantica/semantic_extract/relation_extractor.py
@@ -69,14 +69,14 @@ from typing import Any, Dict, List, Optional, Tuple, Union
from ..utils.exceptions import ProcessingError
from ..utils.logging import get_logger
from ..utils.progress_tracker import get_progress_tracker
-from .ner_extractor import Entity
from .methods import get_relation_method
+from .ner_extractor import Entity
@dataclass
class Relation:
"""Relation representation."""
-
+
subject: Entity
predicate: str
object: Entity
@@ -87,11 +87,19 @@ class Relation:
class RelationExtractor:
"""Relation extractor for entity relationships."""
-
- def __init__(self, method: Union[str, List[str]] = "pattern", **config):
+
+ def __init__(
+ self,
+ method: Union[str, List[str]] = "pattern",
+ relation_types: Optional[List[str]] = None,
+ bidirectional: bool = False,
+ confidence_threshold: float = 0.6,
+ max_distance: int = 50,
+ **config
+ ):
"""
Initialize relation extractor.
-
+
Args:
method: Extraction method(s). Can be:
- "pattern": Pattern-based extraction (default)
@@ -101,48 +109,59 @@ class RelationExtractor:
- "huggingface": HuggingFace model
- "llm": LLM-based extraction
- List of methods for fallback chain
- **config: Configuration options:
+ relation_types: Specific relation types to extract (e.g., ["founded", "works_at"])
+ bidirectional: Whether to extract bidirectional relations
+ confidence_threshold: Minimum confidence score (0.0-1.0)
+ max_distance: Maximum token distance between entities
+ **config: Additional configuration options:
- model: Model name (for dependency/HuggingFace methods)
- huggingface_model: HuggingFace model name
- provider: LLM provider (for LLM method)
- llm_model: LLM model name
- device: Device for HuggingFace models
- - min_confidence: Minimum confidence threshold
- validate: Enable validation (default: False)
"""
self.logger = get_logger("relation_extractor")
self.config = config
self.progress_tracker = get_progress_tracker()
-
+
+ # Store parameters
+ self.relation_types = relation_types
+ self.bidirectional = bidirectional
+ self.confidence_threshold = confidence_threshold
+ self.max_distance = max_distance
+
# Method configuration
self.method = method if isinstance(method, list) else [method]
- self.min_confidence = config.get("min_confidence", 0.5)
+ self.min_confidence = config.get("min_confidence", confidence_threshold)
self.validate = config.get("validate", False)
-
+
# Common relation patterns
self.relation_patterns = {
"founded_by": [
r"(?P<subject>\w+)\s+(?:was\s+)?founded\s+by\s+(?P<object>\w+(?:\s+\w+)*)",
- r"(?P<object>\w+(?:\s+\w+)*)\s+founded\s+(?P<subject>\w+)"
+ r"(?P<object>\w+(?:\s+\w+)*)\s+founded\s+(?P<subject>\w+)",
],
"located_in": [
r"(?P<subject>\w+)\s+is\s+located\s+in\s+(?P<object>\w+)",
- r"(?P<subject>\w+)\s+in\s+(?P<object>\w+)"
+ r"(?P<subject>\w+)\s+in\s+(?P<object>\w+)",
],
"works_for": [
r"(?P<subject>\w+)\s+works?\s+for\s+(?P<object>\w+)",
- r"(?P<subject>\w+)\s+is\s+an?\s+employee\s+of\s+(?P<object>\w+)"
+ r"(?P<subject>\w+)\s+is\s+an?\s+employee\s+of\s+(?P<object>\w+)",
],
"born_in": [
r"(?P<subject>\w+)\s+was\s+born\s+in\s+(?P<object>\w+)",
- r"(?P<subject>\w+)\s+born\s+in\s+(?P<object>\w+)"
- ]
+ r"(?P<subject>\w+)\s+born\s+in\s+(?P<object>\w+)",
+ ],
}
-
- def extract_relations(self, text: str, entities: List[Entity], **options) -> List[Relation]:
+
+ def extract_relations(
+ self, text: str, entities: List[Entity], **options
+ ) -> List[Relation]:
"""
Extract relations between entities.
-
+
Args:
text: Input text
entities: List of extracted entities
@@ -150,156 +169,187 @@ class RelationExtractor:
- method: Override method (if not set in __init__)
- min_confidence: Minimum confidence threshold
- validate: Enable validation
-
+
Returns:
list: List of extracted relations
"""
tracking_id = self.progress_tracker.start_tracking(
module="semantic_extract",
submodule="RelationExtractor",
- message=f"Extracting relations from {len(entities)} entities"
+ message=f"Extracting relations from {len(entities)} entities",
)
-
+
try:
if not text or not entities:
- self.progress_tracker.stop_tracking(tracking_id, status="completed", message="No text or entities provided")
+ self.progress_tracker.stop_tracking(
+ tracking_id,
+ status="completed",
+ message="No text or entities provided",
+ )
return []
-
+
# Use method from options if provided, otherwise use instance method
methods = options.get("method", self.method)
if isinstance(methods, str):
methods = [methods]
-
+
min_confidence = options.get("min_confidence", self.min_confidence)
validate = options.get("validate", self.validate)
-
+
# Merge config with options
all_options = {**self.config, **options}
-
+
# Try each method in order (fallback chain)
all_relations = []
for method_name in methods:
try:
- self.progress_tracker.update_tracking(tracking_id, message=f"Extracting relations using {method_name}...")
+ self.progress_tracker.update_tracking(
+ tracking_id,
+ message=f"Extracting relations using {method_name}...",
+ )
method_func = get_relation_method(method_name)
-
+
# Prepare method-specific options
method_options = all_options.copy()
if method_name == "huggingface":
- method_options["model"] = all_options.get("huggingface_model", all_options.get("model"))
+ method_options["model"] = all_options.get(
+ "huggingface_model", all_options.get("model")
+ )
method_options["device"] = all_options.get("device")
elif method_name == "llm":
- method_options["provider"] = all_options.get("provider", "openai")
- method_options["model"] = all_options.get("llm_model", all_options.get("model"))
+ method_options["provider"] = all_options.get(
+ "provider", "openai"
+ )
+ method_options["model"] = all_options.get(
+ "llm_model", all_options.get("model")
+ )
elif method_name == "dependency":
- method_options["model"] = all_options.get("model", "en_core_web_sm")
-
+ method_options["model"] = all_options.get(
+ "model", "en_core_web_sm"
+ )
+
relations = method_func(text, entities, **method_options)
-
+
# Filter by confidence
filtered = [r for r in relations if r.confidence >= min_confidence]
-
+
if filtered:
all_relations.append((method_name, filtered))
-
+
# If not using ensemble, return first successful result
if len(methods) == 1:
result = filtered
if validate:
result = self.validate_relations(result)
- self.progress_tracker.stop_tracking(tracking_id, status="completed",
- message=f"Extracted {len(result)} relations using {method_name}")
+ self.progress_tracker.stop_tracking(
+ tracking_id,
+ status="completed",
+ message=f"Extracted {len(result)} relations using {method_name}",
+ )
return result
-
+
except Exception as e:
self.logger.warning(f"Method {method_name} failed: {e}")
continue
-
+
# Use first successful method or combine
if all_relations:
relations = all_relations[0][1] # Use first successful method
else:
relations = []
-
+
# Validate if enabled
if validate:
relations = self.validate_relations(relations)
-
- self.progress_tracker.stop_tracking(tracking_id, status="completed",
- message=f"Extracted {len(relations)} relations")
+
+ self.progress_tracker.stop_tracking(
+ tracking_id,
+ status="completed",
+ message=f"Extracted {len(relations)} relations",
+ )
return relations
-
+
except Exception as e:
- self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))
+ self.progress_tracker.stop_tracking(
+ tracking_id, status="failed", message=str(e)
+ )
raise
-
- def _extract_with_patterns(self, text: str, entities: List[Entity]) -> List[Relation]:
+
+ def _extract_with_patterns(
+ self, text: str, entities: List[Entity]
+ ) -> List[Relation]:
"""Extract relations using pattern matching."""
relations = []
-
+
# Create entity lookup by text
entity_map = {e.text.lower(): e for e in entities}
-
+
# Check each relation pattern
for relation_type, patterns in self.relation_patterns.items():
for pattern in patterns:
for match in re.finditer(pattern, text, re.IGNORECASE):
subject_text = match.group("subject")
object_text = match.group("object")
-
+
subject_entity = entity_map.get(subject_text.lower())
object_entity = entity_map.get(object_text.lower())
-
+
if subject_entity and object_entity:
# Get context around the match
start = max(0, match.start() - 50)
end = min(len(text), match.end() + 50)
context = text[start:end]
-
- relations.append(Relation(
- subject=subject_entity,
- predicate=relation_type,
- object=object_entity,
- confidence=0.7, # Pattern-based confidence
- context=context,
- metadata={
- "extraction_method": "pattern",
- "pattern": pattern
- }
- ))
-
+
+ relations.append(
+ Relation(
+ subject=subject_entity,
+ predicate=relation_type,
+ object=object_entity,
+ confidence=0.7, # Pattern-based confidence
+ context=context,
+ metadata={
+ "extraction_method": "pattern",
+ "pattern": pattern,
+ },
+ )
+ )
+
# Co-occurrence based relations (entities close to each other)
for i, entity1 in enumerate(entities):
- for entity2 in entities[i+1:]:
+ for entity2 in entities[i + 1 :]:
# Check if entities are close in text
distance = abs(entity1.end_char - entity2.start_char)
if distance < 100: # Within 100 characters
# Simple relation based on proximity
start = min(entity1.start_char, entity2.start_char)
end = max(entity1.end_char, entity2.end_char)
- context = text[max(0, start-30):min(len(text), end+30)]
-
- relations.append(Relation(
- subject=entity1,
- predicate="related_to",
- object=entity2,
- confidence=0.5, # Lower confidence for co-occurrence
- context=context,
- metadata={
- "extraction_method": "co_occurrence",
- "distance": distance
- }
- ))
-
+ context = text[max(0, start - 30) : min(len(text), end + 30)]
+
+ relations.append(
+ Relation(
+ subject=entity1,
+ predicate="related_to",
+ object=entity2,
+ confidence=0.5, # Lower confidence for co-occurrence
+ context=context,
+ metadata={
+ "extraction_method": "co_occurrence",
+ "distance": distance,
+ },
+ )
+ )
+
return relations
-
- def classify_relations(self, relations: List[Relation]) -> Dict[str, List[Relation]]:
+
+ def classify_relations(
+ self, relations: List[Relation]
+ ) -> Dict[str, List[Relation]]:
"""
Classify relations by type.
-
+
Args:
relations: List of relations
-
+
Returns:
dict: Relations grouped by predicate type
"""
@@ -308,33 +358,33 @@ class RelationExtractor:
if relation.predicate not in classified:
classified[relation.predicate] = []
classified[relation.predicate].append(relation)
-
+
return classified
-
+
def validate_relations(self, relations: List[Relation]) -> List[Relation]:
"""
Validate relations for consistency.
-
+
Args:
relations: List of relations
-
+
Returns:
list: Validated relations
"""
valid_relations = []
-
+
for relation in relations:
# Basic validation
if not relation.subject or not relation.object:
continue
-
+
if not relation.predicate:
continue
-
+
# Check if subject and object are different
if relation.subject.text == relation.object.text:
continue
-
+
valid_relations.append(relation)
-
+
return valid_relations
diff --git a/semantica/semantic_extract/triple_extractor.py b/semantica/semantic_extract/triple_extractor.py
index f0e4eaa6..9a05019d 100644
--- a/semantica/semantic_extract/triple_extractor.py
+++ b/semantica/semantic_extract/triple_extractor.py
@@ -70,15 +70,15 @@ from urllib.parse import quote
from ..utils.exceptions import ProcessingError, ValidationError
from ..utils.logging import get_logger
from ..utils.progress_tracker import get_progress_tracker
+from .methods import get_triple_method
from .ner_extractor import Entity
from .relation_extractor import Relation
-from .methods import get_triple_method
@dataclass
class Triple:
"""RDF triple representation."""
-
+
subject: str
predicate: str
object: str
@@ -88,11 +88,18 @@ class Triple:
class TripleExtractor:
"""RDF triple extraction handler."""
-
- def __init__(self, method: Union[str, List[str]] = "pattern", config=None, **kwargs):
+
+ def __init__(
+ self,
+ method: Union[str, List[str]] = "pattern",
+ include_temporal: bool = False,
+ include_provenance: bool = False,
+ config=None,
+ **kwargs
+ ):
"""
Initialize triple extractor.
-
+
Args:
method: Extraction method(s). Can be:
- "pattern": Pattern-based extraction (default)
@@ -100,6 +107,8 @@ 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_provenance: Whether to track source sentences for provenance
config: Legacy config dict (deprecated, use kwargs)
**kwargs: Configuration options:
- model: Model name (for HuggingFace methods)
@@ -114,111 +123,139 @@ class TripleExtractor:
self.config = config or {}
self.config.update(kwargs)
self.progress_tracker = get_progress_tracker()
-
+
+ # Store parameters
+ self.include_temporal = include_temporal
+ self.include_provenance = include_provenance
+
# Method configuration
self.method = method if isinstance(method, list) else [method]
self.min_confidence = self.config.get("min_confidence", 0.5)
self.validate_triples = self.config.get("validate", True)
-
+
self.triple_validator = TripleValidator(**self.config.get("validator", {}))
self.rdf_serializer = RDFSerializer(**self.config.get("serializer", {}))
self.quality_checker = TripleQualityChecker(**self.config.get("quality", {}))
-
+
self.supported_formats = ["turtle", "ntriples", "jsonld", "xml"]
-
+
def extract_triples(
self,
text: str,
entities: Optional[List[Entity]] = None,
relationships: Optional[List[Relation]] = None,
- **options
+ **options,
) -> List[Triple]:
"""
Extract RDF triples from text.
-
+
Args:
text: Input text
entities: Pre-extracted entities (optional)
relationships: Pre-extracted relations (optional)
**options: Extraction options
-
+
Returns:
list: List of extracted triples
"""
tracking_id = self.progress_tracker.start_tracking(
module="semantic_extract",
submodule="TripleExtractor",
- message="Extracting RDF triples from text"
+ message="Extracting RDF triples from text",
)
-
+
try:
from .ner_extractor import NERExtractor
from .relation_extractor import RelationExtractor
-
+
# Extract entities if not provided
if entities is None:
- self.progress_tracker.update_tracking(tracking_id, message="Extracting entities...")
+ self.progress_tracker.update_tracking(
+ tracking_id, message="Extracting entities..."
+ )
ner = NERExtractor(**self.config.get("ner", {}))
entities = ner.extract_entities(text)
-
+
# Extract relations if not provided
if relationships is None:
- self.progress_tracker.update_tracking(tracking_id, message="Extracting relations...")
+ self.progress_tracker.update_tracking(
+ tracking_id, message="Extracting relations..."
+ )
rel_extractor = RelationExtractor(**self.config.get("relation", {}))
relationships = rel_extractor.extract_relations(text, entities)
-
+
# Use method-based extraction
methods = options.get("method", self.method)
if isinstance(methods, str):
methods = [methods]
-
+
# Merge config with options
all_options = {**self.config, **options}
-
+
# Try each method in order (fallback chain)
all_triples = []
for method_name in methods:
try:
- self.progress_tracker.update_tracking(tracking_id, message=f"Extracting triples using {method_name}...")
+ self.progress_tracker.update_tracking(
+ tracking_id,
+ message=f"Extracting triples using {method_name}...",
+ )
method_func = get_triple_method(method_name)
-
+
# Prepare method-specific options
method_options = all_options.copy()
if method_name == "huggingface":
- method_options["model"] = all_options.get("huggingface_model", all_options.get("model"))
+ method_options["model"] = all_options.get(
+ "huggingface_model", all_options.get("model")
+ )
method_options["device"] = all_options.get("device")
elif method_name == "llm":
- method_options["provider"] = all_options.get("provider", "openai")
- method_options["model"] = all_options.get("llm_model", all_options.get("model"))
-
- triples = method_func(text, entities=entities, relations=relationships, **method_options)
-
+ method_options["provider"] = all_options.get(
+ "provider", "openai"
+ )
+ method_options["model"] = all_options.get(
+ "llm_model", all_options.get("model")
+ )
+
+ triples = method_func(
+ text,
+ entities=entities,
+ relations=relationships,
+ **method_options,
+ )
+
# Filter by confidence
min_conf = options.get("min_confidence", self.min_confidence)
filtered = [t for t in triples if t.confidence >= min_conf]
-
+
if filtered:
all_triples.append((method_name, filtered))
-
+
# If not using ensemble, return first successful result
if len(methods) == 1:
result = filtered
if options.get("validate", self.validate_triples):
result = self.triple_validator.validate_triples(result)
- self.progress_tracker.stop_tracking(tracking_id, status="completed",
- message=f"Extracted {len(result)} triples using {method_name}")
+ self.progress_tracker.stop_tracking(
+ tracking_id,
+ status="completed",
+ message=f"Extracted {len(result)} triples using {method_name}",
+ )
return result
-
+
except Exception as e:
self.logger.warning(f"Method {method_name} failed: {e}")
continue
-
+
# Use first successful method or fallback to relation conversion
if all_triples:
triples = all_triples[0][1]
else:
# Fallback: Convert relations to triples
- self.progress_tracker.update_tracking(tracking_id, message=f"Converting {len(relationships)} relations to triples...")
+ self.progress_tracker.update_tracking(
+ tracking_id,
+ message=f"Converting {len(relationships)} relations to triples...",
+ )
triples = []
for relation in relationships:
triple = Triple(
@@ -226,71 +263,77 @@ class TripleExtractor:
predicate=self._format_uri(relation.predicate),
object=self._format_uri(relation.object.text),
confidence=relation.confidence,
- metadata={
- "context": relation.context,
- **relation.metadata
- }
+ metadata={"context": relation.context, **relation.metadata},
)
triples.append(triple)
-
+
# Validate triples
if options.get("validate", self.validate_triples):
- self.progress_tracker.update_tracking(tracking_id, message="Validating triples...")
+ self.progress_tracker.update_tracking(
+ tracking_id, message="Validating triples..."
+ )
triples = self.triple_validator.validate_triples(triples)
-
- self.progress_tracker.stop_tracking(tracking_id, status="completed",
- message=f"Extracted {len(triples)} triples")
+
+ self.progress_tracker.stop_tracking(
+ tracking_id,
+ status="completed",
+ message=f"Extracted {len(triples)} triples",
+ )
return triples
-
+
except Exception as e:
- self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))
+ self.progress_tracker.stop_tracking(
+ tracking_id, status="failed", message=str(e)
+ )
raise
-
+
def _format_uri(self, value: str) -> str:
"""Format value as URI."""
# Simple URI formatting
if value.startswith("http://") or value.startswith("https://"):
return value
-
+
# Format as local URI
formatted = quote(value.replace(" ", "_"), safe="")
return f"http://example.org/{formatted}"
-
+
def validate_triples(self, triples: List[Triple], **criteria) -> List[Triple]:
"""
Validate triple quality and consistency.
-
+
Args:
triples: List of triples
**criteria: Validation criteria
-
+
Returns:
list: Validated triples
"""
return self.triple_validator.validate_triples(triples, **criteria)
-
- def serialize_triples(self, triples: List[Triple], format: str = "turtle", **options) -> str:
+
+ def serialize_triples(
+ self, triples: List[Triple], format: str = "turtle", **options
+ ) -> str:
"""
Serialize triples to RDF format.
-
+
Args:
triples: List of triples
format: RDF format (turtle, ntriples, jsonld, xml)
**options: Serialization options
-
+
Returns:
str: Serialized RDF
"""
return self.rdf_serializer.serialize_to_rdf(triples, format, **options)
-
+
def process_batch(self, texts: List[str], **options) -> List[List[Triple]]:
"""
Process multiple texts for triple extraction.
-
+
Args:
texts: List of input texts
**options: Processing options
-
+
Returns:
list: List of triple lists for each text
"""
@@ -299,86 +342,88 @@ class TripleExtractor:
class TripleValidator:
"""Triple validation engine."""
-
+
def __init__(self, **config):
"""Initialize triple validator."""
self.logger = get_logger("triple_validator")
self.config = config
-
+
def validate_triple(self, triple: Triple, **criteria) -> bool:
"""
Validate individual triple.
-
+
Args:
triple: Triple to validate
**criteria: Validation criteria
-
+
Returns:
bool: True if valid
"""
# Check structure
if not triple.subject or not triple.predicate or not triple.object:
return False
-
+
# Check confidence
min_confidence = criteria.get("min_confidence", 0.5)
if triple.confidence < min_confidence:
return False
-
+
return True
-
+
def validate_triples(self, triples: List[Triple], **criteria) -> List[Triple]:
"""
Validate list of triples.
-
+
Args:
triples: List of triples
**criteria: Validation criteria
-
+
Returns:
list: Valid triples
"""
return [t for t in triples if self.validate_triple(t, **criteria)]
-
+
def check_triple_consistency(self, triples: List[Triple]) -> Dict[str, Any]:
"""
Check consistency among triples.
-
+
Args:
triples: List of triples
-
+
Returns:
dict: Consistency report
"""
issues = []
-
+
# Check for contradictory triples
# (simplified - would need domain knowledge for full implementation)
-
+
return {
"total_triples": len(triples),
"issues": issues,
- "consistent": len(issues) == 0
+ "consistent": len(issues) == 0,
}
class RDFSerializer:
"""RDF serialization handler."""
-
+
def __init__(self, **config):
"""Initialize RDF serializer."""
self.logger = get_logger("rdf_serializer")
self.config = config
-
- def serialize_to_rdf(self, triples: List[Triple], format: str = "turtle", **options) -> str:
+
+ def serialize_to_rdf(
+ self, triples: List[Triple], format: str = "turtle", **options
+ ) -> str:
"""
Serialize triples to RDF format.
-
+
Args:
triples: List of triples
format: RDF format
**options: Serialization options
-
+
Returns:
str: Serialized RDF
"""
@@ -392,17 +437,17 @@ class RDFSerializer:
return self._serialize_xml(triples, **options)
else:
raise ValidationError(f"Unsupported RDF format: {format}")
-
+
def _serialize_turtle(self, triples: List[Triple], **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} ."
lines.append(line)
-
+
return "\n".join(lines)
-
+
def _serialize_ntriples(self, triples: List[Triple], **options) -> str:
"""Serialize to N-Triples format."""
lines = []
@@ -410,79 +455,85 @@ class RDFSerializer:
line = f"<{triple.subject}> <{triple.predicate}> <{triple.object}> ."
lines.append(line)
return "\n".join(lines)
-
+
def _serialize_jsonld(self, triples: List[Triple], **options) -> str:
"""Serialize to JSON-LD format."""
import json
-
+
graph = []
for triple in triples:
- graph.append({
- "@id": triple.subject,
- triple.predicate: triple.object
- })
-
+ graph.append({"@id": triple.subject, triple.predicate: triple.object})
+
return json.dumps({"@graph": graph}, indent=2)
-
+
def _serialize_xml(self, triples: List[Triple], **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#">']
-
+ 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}">')
- lines.append(f' <{triple.predicate}>{triple.object}</{triple.predicate}>')
- lines.append(' </rdf:Description>')
-
- lines.append('</rdf:RDF>')
+ lines.append(
+ f" <{triple.predicate}>{triple.object}</{triple.predicate}>"
+ )
+ lines.append(" </rdf:Description>")
+
+ lines.append("</rdf:RDF>")
return "\n".join(lines)
class TripleQualityChecker:
"""Triple quality assessment engine."""
-
+
def __init__(self, **config):
"""Initialize triple quality checker."""
self.logger = get_logger("triple_quality_checker")
self.config = config
-
+
def assess_triple_quality(self, triple: Triple, **metrics) -> Dict[str, Any]:
"""
Assess quality of individual triple.
-
+
Args:
triple: Triple to assess
**metrics: Quality metrics
-
+
Returns:
dict: Quality assessment
"""
return {
"confidence": triple.confidence,
- "completeness": 1.0 if triple.subject and triple.predicate and triple.object else 0.0,
- "quality_score": triple.confidence
+ "completeness": 1.0
+ if triple.subject and triple.predicate and triple.object
+ else 0.0,
+ "quality_score": triple.confidence,
}
-
- def calculate_quality_scores(self, triples: List[Triple], **options) -> Dict[str, Any]:
+
+ def calculate_quality_scores(
+ self, triples: List[Triple], **options
+ ) -> Dict[str, Any]:
"""
Calculate quality scores for triples.
-
+
Args:
triples: List of triples
**options: Quality options
-
+
Returns:
dict: Quality scores
"""
if not triples:
return {}
-
+
scores = [self.assess_triple_quality(t)["quality_score"] for t in triples]
-
+
return {
"average_score": sum(scores) / len(scores),
"min_score": min(scores),
"max_score": max(scores),
"high_quality": len([s for s in scores if s >= 0.8]),
"medium_quality": len([s for s in scores if 0.5 <= s < 0.8]),
- "low_quality": len([s for s in scores if s < 0.5])
+ "low_quality": len([s for s in scores if s < 0.5]),
}